Skip to main content

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 AA, BB, CC and ray with origin OO and direction d\vec{d}, the algorithm computes edge vectors and cross products:

v1=BAv2=CAh=d×v2\begin{align} \vec{v_1} &= B - A \\ \vec{v_2} &= C - A \\ \vec{h} &= \vec{d} \times \vec{v_2} \\ \end{align}

The determinant a=v1ha = \vec{v_1} \cdot \vec{h} determines ray-plane parallelism. When a|a| approaches zero, the ray lies parallel to the triangle plane.

Barycentric Coordinate Calculation

The algorithm computes barycentric coordinates (u,v)(u, v) within the triangle:

s=OAu=shaq=s×v1v=dqa\begin{align} \vec{s} &= O - A \\ u &= \frac{\vec{s} \cdot \vec{h}}{a} \\ \vec{q} &= \vec{s} \times \vec{v_1} \\ v &= \frac{\vec{d} \cdot \vec{q}}{a} \end{align}

Valid intersections satisfy u0u \geq 0, v0v \geq 0, and u+v1u + v \leq 1.

Distance Parameter

The parametric distance tt along the ray is calculated as:

t=v2qat = \frac{\vec{v_2} \cdot \vec{q}}{a}

When t<0t < 0, the intersection occurs behind the ray origin. The function returns tt for valid intersections or a large value (9999999.99999999.9) for misses.

Live Editor
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)
})