triangleIntersect: Ray-Triangle Intersection Algorithm
Möller-Trumbore Method for Efficient Ray Testing
The triangle intersection function implements the Möller-Trumbore algorithm for computing ray-triangle intersections in 3D space. This method efficiently determines both intersection existence and parametric distance along the ray.
Given triangle vertices , , and ray with origin and direction , the algorithm computes edge vectors and cross products:
The determinant determines ray-plane parallelism. When approaches zero, the ray lies parallel to the triangle plane.
Barycentric Coordinate Calculation
The algorithm computes barycentric coordinates within the triangle:
Valid intersections satisfy , , and .
Distance Parameter
The parametric distance along the ray is calculated as:
When , the intersection occurs behind the ray origin. The function returns for valid intersections or a large value () for misses.
const fragment = () => Scope(() => { const tri = Triangle({ a: vec3(-0.5, -0.4, 0), b: vec3(0.5, -0.4, 0), c: vec3(0, 0.6, 0) }) const rayOrigin = vec3(uv.mul(2).sub(1), -1) const rayDir = vec3(0, 0, 1) const dist = triangleIntersect(tri, rayOrigin, rayDir) const hit = dist.step(1000) const depth = hit.mul(0.8).add(0.2) return vec4(vec3(depth), 1) })