cross
Computes the cross product of two 3D vectors.
Test cross in a live shader
Open the playground, start from a visual preset, and wire cross into the fragment stage to see how it behaves with real values.
Open PlaygroundLive Demo
The cross function computes the cross product of two 3D vectors, returning a vector perpendicular to both inputs.
Signature
cross :: (float3 a, float3 b) -> float3 {...}
Parameters
| Parameter | Type | Description |
|---|---|---|
a | float3 | First vector |
b | float3 | Second vector |
Return Value
Returns a vector perpendicular to both a and b, with magnitude equal to |a| * |b| * sin(θ).
Example
pipeline TangentSpace {
fragment {
// Calculate tangent space basis
float3 normal = normalize(input.normal);
float3 tangent = normalize(input.tangent);
// Compute bitangent using cross product
float3 bitangent = cross(normal, tangent);
// TBN matrix for normal mapping
float3x3 TBN = float3x3(tangent, bitangent, normal);
output.color = float4(normal * 0.5 + 0.5, 1.0);
}
}Common Use Cases
Normal Calculation
// Calculate face normal from triangle edges
float3 edge1 = v1 - v0;
float3 edge2 = v2 - v0;
float3 faceNormal = normalize(cross(edge1, edge2));Tangent Space
// Compute bitangent for TBN matrix
float3 bitangent = normalize(cross(normal, tangent)) * tangentSign;Rotation Axis
// Find axis to rotate from one direction to another
float3 from = normalize(fromDir);
float3 to = normalize(toDir);
float3 rotationAxis = normalize(cross(from, to));Camera Right Vector
// Calculate camera basis vectors
float3 forward = normalize(target - cameraPos);
float3 right = normalize(cross(forward, worldUp));
float3 up = cross(right, forward);Surface Area
// Parallelogram area from two edge vectors
float3 crossProd = cross(edge1, edge2);
float area = length(crossProd);Right-Hand Rule
The cross product follows the right-hand rule: if your fingers curl from a to b, your thumb points in the direction of cross(a, b).
Order Matters
Cross product is anti-commutative: cross(a, b) = -cross(b, a). Swapping arguments reverses the result direction.
3D Only
The cross product is only defined for 3D vectors. For 2D, use the "perp dot product": a.x * b.y - a.y * b.x.
Compiled Output
When compiled to GLSL:
cross(a, b)
When compiled to HLSL:
cross(a, b)