Does the lighthouse beam light up the ship? Does the camera see the ship or is an asteroid in the way? Which object has the player clicked on? Has the ship collided with something? All these questions, which a game asks itself thousands of times per second, are intersection tests: casting a ray and seeing what it touches, or checking whether two volumes overlap. In this last lesson of the module we bring together everything we have learned—parametric lines, planes, dot and cross products, distances—to solve the most important intersections: a ray against a plane, a sphere, a triangle and a box, and the overlaps between simple volumes. We will also see why engines wrap complicated objects in simple shapes and test against the wrapper first.
The code assumes that the functions from the previous lessons of the module are already defined: squared_norm, distance, direction_to, dot_product, cross_product, plane_from_points and point_plane_distance.
The ray and its uses
A ray is a half-line: an origin \(\mathbf{o}\) and a direction \(\hat{\mathbf{d}}\), with the parameter limited to non-negative values.
\[ \mathbf{p}(t) = \mathbf{o} + t,\hat{\mathbf{d}} \qquad t \ge 0 \]
In this lesson the direction will always be a unit vector. That way, \(t\) is directly the distance from the origin, and comparing two hits comes down to comparing their \(t\): the closest is the one with the smallest \(t\).
| Use | Origin | Direction | Question |
|---|---|---|---|
| Mouse picking | Camera | Through the clicked pixel | Which object is under the cursor? |
| Instant-hit shots | Cannon | Where it is aiming | What does it hit, and where? |
| Line of sight | Observer | Toward the target | Is there anything in between? |
| Sensors and altimeters | Ship | Downward or forward | How far away is the obstacle? |
| Shadows and light | Point on the surface | Toward the light | Does the light arrive or is there an obstacle? |
All the tests follow the same scheme: we substitute the generic point of the ray into the object's equation, solve for \(t\) and interpret the result. Our functions will return the \(t\) of the first hit, or None if there is none.
Ray against plane
This is the base case, and we already solved it in "Equations of Planes and Lines". Substituting the ray into \(\hat{\mathbf{n}} \cdot \mathbf{p} + d = 0\):
\[ t = -\frac{\hat{\mathbf{n}} \cdot \mathbf{o} + d}{\hat{\mathbf{n}} \cdot \hat{\mathbf{d}}} \]
With the readings from the previous lesson, the formula explains itself: the numerator is the (signed) distance from the origin to the plane, and the denominator, how much closer the ray gets to the plane for each unit traveled. The only new thing is the ray filter: if the denominator is 0, the ray is parallel and there is no hit; if \(t < 0\), the plane is behind.
import numpy as np
def ray_plane(origin, direction, plane, tolerance=1e-9):
"""Distance t to the plane along the ray, or None if it does not reach it."""
n, d = plane
denominator = dot_product(n, direction)
if abs(denominator) < tolerance:
return None
t = -(dot_product(n, origin) + d) / denominator
return t if t >= 0.0 else None
lamp = np.array([0.0, 12.0, 0.0])
b1, b2, b3 = np.array([13.0, 0.0, 2.0]), np.array([9.0, 4.0, 0.0]), np.array([9.0, 0.0, 4.0])
strip = plane_from_points(b1, b2, b3)
strip_beam = np.array([1.0, -8.0, 4.0]) / 9.0
print(round(ray_plane(lamp, strip_beam, strip), 6), ray_plane(lamp, np.array([0.8, 0.0, 0.6]), strip))Ray against sphere
The equation
A sphere with center \(\mathbf{c}\) and radius \(r\) is the set of points at distance \(r\) from the center: \(\lVert \mathbf{p} - \mathbf{c} \rVert^2 = r^2\). We substitute \(\mathbf{p} = \mathbf{o} + t,\hat{\mathbf{d}}\) and call \(\mathbf{m} = \mathbf{c} - \mathbf{o}\) the vector from the ray's origin to the center:
\[ \lVert t,\hat{\mathbf{d}} - \mathbf{m} \rVert^2 = r^2 \quad\Longrightarrow\quad t^2 - 2,(\mathbf{m} \cdot \hat{\mathbf{d}}),t + (\mathbf{m} \cdot \mathbf{m} - r^2) = 0 \]
(we have used \(\hat{\mathbf{d}} \cdot \hat{\mathbf{d}} = 1\)). It is a quadratic equation in \(t\). With \(b = \mathbf{m} \cdot \hat{\mathbf{d}}\) and \(c = \mathbf{m} \cdot \mathbf{m} - r^2\), its solutions are:
\[ t = b \pm \sqrt{b^2 - c} \]
Geometric interpretation
Each term has a meaning we already know:
- \(b\) is the projection of \(\mathbf{m}\) onto the ray: the value of \(t\) at the point of the ray closest to the center.
- \(\mathbf{m} \cdot \mathbf{m} - b^2\) is, by Pythagoras, the squared distance from the center to the line of the ray.
- The discriminant \(\Delta = b^2 - c = r^2 - (\mathbf{m} \cdot \mathbf{m} - b^2)\) compares that distance with the radius, and \(\sqrt{\Delta}\) is half the chord the ray travels inside the sphere.
| Discriminant | Solutions | Situation |
|---|---|---|
| \(\Delta < 0\) | None | The line passes by: miss |
| \(\Delta = 0\) | One, \(t = b\) | Tangent: it grazes the sphere at one point |
| \(\Delta > 0\) | Two, \(t_1 < t_2\) | It goes through: it enters at \(t_1\) and exits at \(t_2\) |
The ray filter is still missing; we apply it by looking at the signs of the solutions:
- \(t_1 \ge 0\): the sphere is in front. The hit is \(t_1\).
- \(t_1 < 0 \le t_2\): the origin is inside the sphere. The ray only touches it on the way out, at \(t_2\).
- \(t_2 < 0\): the whole sphere is behind. There is no hit.
Examples
Two intersections. A rogue asteroid, with center \((2, 8, 5)\) and radius 5, gets in the way of the beam that the lamp \((0, 12, 0)\) aims at the strip with direction \(\left(\tfrac{1}{9}, -\tfrac{8}{9}, \tfrac{4}{9}\right)\).
- \(\mathbf{m} = (2, -4, 5)\); \(b = \dfrac{2 + 32 + 20}{9} = 6\); \(c = (4 + 16 + 25) - 25 = 20\).
- \(\Delta = 36 - 20 = 16\); \(t = 6 \pm 4\): it enters at \(t_1 = 2\) and exits at \(t_2 = 10\).
The beam touches the asteroid 2 m from the lamp, at \((0, 12, 0) + 2\left(\tfrac{1}{9}, -\tfrac{8}{9}, \tfrac{4}{9}\right) \approx (0.22, 10.22, 0.89)\). Since the plane of the strip was at \(t = 9\), the asteroid leaves it in shadow.
Tangent. The ship \((8, 3, 6)\) fires a laser downward, \((0, -1, 0)\), at the lighthouse asteroid (center \((0, -10, 0)\), radius 10): \(\mathbf{m} = (-8, -13, -6)\), \(b = 13\), \(c = 269 - 100 = 169\), \(\Delta = 169 - 169 = 0\). It grazes it at a single point, \((8, -10, 6)\): the ship is flying right above the asteroid's "equator".
def ray_sphere(origin, direction, center, radius):
"""Distance t to the first point of the sphere touched by the ray, or None."""
m = np.asarray(center, dtype=float) - np.asarray(origin, dtype=float)
b = dot_product(m, direction)
c = dot_product(m, m) - radius * radius
discriminant = b * b - c
if discriminant < 0.0:
return None
root = np.sqrt(discriminant)
if b + root < 0.0: # the sphere is behind
return None
t_enter = b - root
return float(t_enter) if t_enter >= 0.0 else float(b + root)
ship = np.array([8.0, 3.0, 6.0])
rogue, rogue_radius = np.array([2.0, 8.0, 5.0]), 5.0
lighthouse_asteroid, lighthouse_radius = np.array([0.0, -10.0, 0.0]), 10.0
print(ray_sphere(lamp, strip_beam, rogue, rogue_radius))
print(ray_sphere(ship, np.array([0.0, -1.0, 0.0]), lighthouse_asteroid, lighthouse_radius))
print(ray_sphere(lamp, np.array([0.8, 0.0, 0.6]), ship, 4.0))
print(ray_sphere([2.0, 8.0, 2.0], np.array([0.0, 0.0, 1.0]), rogue, rogue_radius))The third test is a miss (the horizontal beam passes 9 m above the ship) and the fourth starts from a point inside the rogue asteroid: it returns the exit distance.
Ray against triangle
3D models are made of triangles, so this is the test that gives the "exact" answer. It is solved in two steps.
Step 1: the plane. Step 2: inside or outside?
First we intersect the ray with the plane that contains the triangle \(ABC\), with normal \(\mathbf{n} = (B - A) \times (C - A)\). If the ray reaches it, we get a point \(P\). But the plane is infinite and the triangle is not: we still have to decide whether \(P\) falls inside.
To do so we walk around the boundary \(A \to B \to C \to A\). If \(P\) is inside, it lies on the same side (to the left, seen from where the normal points) of all three edges. And "which side of an edge" is something a cross product tells us: \((B - A) \times (P - A)\) points like \(\mathbf{n}\) if \(P\) is to the left of \(AB\), and the opposite way if it is to the right. The three conditions are:
\[ \big[(B - A) \times (P - A)\big] \cdot \mathbf{n} \ge 0 \qquad \big[(C - B) \times (P - B)\big] \cdot \mathbf{n} \ge 0 \qquad \big[(A - C) \times (P - C)\big] \cdot \mathbf{n} \ge 0 \]
Barycentric coordinates
Those three numbers mean something more. Each one is twice the area of the sub-triangle that \(P\) forms with one edge (multiplied by \(\lVert \mathbf{n} \rVert\)). Divided by \(\mathbf{n} \cdot \mathbf{n}\)—twice the total area, squared—they give three weights \(\gamma\), \(\alpha\) and \(\beta\), respectively: the barycentric coordinates of \(P\). Each weight corresponds to the vertex opposite the edge, and they satisfy:
\[ P = \alpha A + \beta B + \gamma C \qquad \alpha + \beta + \gamma = 1 \]
They express \(P\) as a blend of the three vertices, and they give a clean criterion: \(P\) is inside the triangle if and only if all three weights are between 0 and 1. A negative weight indicates that \(P\) has crossed the edge opposite that vertex. In Module 5 the same coordinates will be used to spread colors and textures across the interior of a triangle; here we only use them to decide.
Example. The lamp now points toward the ship with direction \(\hat{\mathbf{d}} = \left(\tfrac{2}{3}, -\tfrac{2}{3}, \tfrac{1}{3}\right)\). Let's try an upper face of the hull: right wing \(A = (10.4, 3, 2.8)\), tail \(B = (6.4, 3, 4.8)\) and top \(C = (8, 4, 6)\).
- Normal: \((B - A) \times (C - A) = (-4, 0, 2) \times (-2.4, 1, 3.2) = (-2, 8, -4)\).
- Plane: \(\mathbf{n} \cdot A = -8\), \(\mathbf{n} \cdot \mathbf{o} = 96\), \(\mathbf{n} \cdot \hat{\mathbf{d}} = \tfrac{-4 - 16 - 4}{3} = -8\). Then \(t = \dfrac{-8 - 96}{-8} = 13\) and \(P = \left(\tfrac{26}{3}, \tfrac{10}{3}, \tfrac{13}{3}\right) \approx (8.667, 3.333, 4.333)\).
- Weights: \(\alpha = 0.433\) (wing), \(\beta = 0.233\) (tail), \(\gamma = 0.333\) (top). All three positive and adding up to 1: hit.
By contrast, the beam aimed at the strip reached its plane at \((1, 4, 4)\), but with respect to the triangle of beacons \(B_1 B_2 B_3\) its weights are \((-2, 1, 2)\): one of them is negative. It lights the plane of the strip, but outside the area marked by the beacons.
The Möller–Trumbore algorithm
In practice an algorithm is used that does both things at once without computing the plane. It directly sets \(\mathbf{o} + t,\hat{\mathbf{d}} = A + u,(B - A) + v,(C - A)\)—ray equal to a point of the triangle in parametric form—a system of three equations with unknowns \(t\), \(u\), \(v\), and solves it by Cramer's rule, writing the determinants as scalar triple products. Here \(u\) and \(v\) are the weights of \(B\) and \(C\), and the hit is valid if \(u \ge 0\), \(v \ge 0\) and \(u + v \le 1\).
def ray_triangle(origin, direction, a, b, c, tolerance=1e-9):
"""Moller-Trumbore: distance t to the triangle, or None if the ray does not touch it."""
a = np.asarray(a, dtype=float)
edge1 = np.asarray(b, dtype=float) - a
edge2 = np.asarray(c, dtype=float) - a
h = cross_product(direction, edge2)
determinant = dot_product(edge1, h)
if abs(determinant) < tolerance: # ray parallel to the triangle
return None
s = np.asarray(origin, dtype=float) - a
u = dot_product(s, h) / determinant
if u < 0.0 or u > 1.0:
return None
q = cross_product(s, edge1)
v = dot_product(direction, q) / determinant
if v < 0.0 or u + v > 1.0:
return None
t = dot_product(edge2, q) / determinant
return float(t) if t >= 0.0 else None
def barycentric(p, a, b, c):
"""Weights (alpha, beta, gamma) of a point p in the plane of the triangle a, b, c."""
a, b, c = (np.asarray(x, dtype=float) for x in (a, b, c))
n = cross_product(b - a, c - a)
nn = dot_product(n, n)
alpha = dot_product(cross_product(c - b, p - b), n) / nn
beta = dot_product(cross_product(a - c, p - c), n) / nn
gamma = dot_product(cross_product(b - a, p - a), n) / nn
return alpha, beta, gamma
right_wing, left_wing = np.array([10.4, 3.0, 2.8]), np.array([5.6, 3.0, 9.2])
top, bottom = np.array([8.0, 4.0, 6.0]), np.array([8.0, 2.0, 6.0])
nose, tail = np.array([9.6, 3.0, 7.2]), np.array([6.4, 3.0, 4.8])
ship_beam = np.array([2.0, -2.0, 1.0]) / 3.0
t = ray_triangle(lamp, ship_beam, right_wing, tail, top)
print(round(t, 6), np.round(barycentric(lamp + t * ship_beam, right_wing, tail, top), 4))
print(ray_triangle(lamp, strip_beam, b1, b2, b3),
np.round(barycentric(np.array([1.0, 4.0, 4.0]), b1, b2, b3), 4))Bounding volumes: sphere and axis-aligned box
Testing a ray against the thousands of triangles of every object in the scene would be ruinous. The solution is to wrap each object in a bounding volume: a very simple shape that contains it completely. If the ray does not touch the wrapper, it cannot touch the object, and all its triangles are ruled out with a single cheap test.
Axis-aligned bounding box (AABB). It is a box whose faces are parallel to the coordinate planes. It is defined by two corners: the one with the minimum coordinates and the one with the maximum coordinates. It is computed by taking, axis by axis, the minimum and the maximum over all the vertices.
Bounding sphere. A center and a radius. A simple approach (not the tightest possible) is to take the center of the AABB as the center and the distance to the farthest vertex as the radius.
For the six vertices of the ship's hull:
| x | y | z | |
|---|---|---|---|
| Minimum | 5.6 | 2 | 2.8 |
| Maximum | 10.4 | 4 | 9.2 |
The center is \((8, 3, 6)\) and the farthest vertex (a wing tip) is 4 m away: the bounding sphere has radius 4.
The sphere has the advantage that it does not change when the object rotates (the AABB has to be recomputed), but it fits elongated objects poorly; the AABB fits objects placed diagonally poorly.
def aabb_from_points(points):
"""Axis-aligned box, as a pair (minimum, maximum)."""
points = np.asarray(points, dtype=float)
return points.min(axis=0), points.max(axis=0)
def sphere_from_points(points):
"""Simple bounding sphere, as a pair (center, radius)."""
minimum, maximum = aabb_from_points(points)
center = (minimum + maximum) / 2.0
return center, max(distance(center, p) for p in points)
hull = [right_wing, left_wing, top, bottom, nose, tail]
box_min, box_max = aabb_from_points(hull)
ship_center, ship_radius = sphere_from_points(hull)
print(box_min, box_max, ship_center, round(ship_radius, 6))Ray against box: the slab method
An AABB is the intersection of three slabs: the region between the planes \(x = x_{\min}\) and \(x = x_{\max}\), and the same for Y and Z. A point is in the box if it is in all three slabs at once.
Intersecting the ray with the two planes of a slab is trivial, because only one coordinate is involved: \(o_x + t,d_x = x_{\min}\) gives \(t = (x_{\min} - o_x)/d_x\). Each slab thus provides an interval of \(t\) during which the ray is inside it. The ray is inside the box when it is inside all three slabs: in the intersection of the three intervals.
- For each axis, compute the two values of \(t\) and sort them (entry, exit).
- \(t_{\text{enter}}\) = the largest of the three entry values (and of 0, since it is a ray).
- \(t_{\text{exit}}\) = the smallest of the three exit values.
- There is a hit if \(t_{\text{enter}} \le t_{\text{exit}}\).
If \(d_x = 0\), the ray is parallel to that slab: either the origin is between the two planes (and the slab restricts nothing) or there is no hit.
Example. The beam \(\left(\tfrac{2}{3}, -\tfrac{2}{3}, \tfrac{1}{3}\right)\) from the lamp \((0, 12, 0)\), against the ship's box:
| Axis | \(t\) at the minimum plane | \(t\) at the maximum plane | Interval |
|---|---|---|---|
| X | \(5.6 / \tfrac{2}{3} = 8.4\) | \(10.4 / \tfrac{2}{3} = 15.6\) | \([8.4,\ 15.6]\) |
| Y | \((2 - 12) / (-\tfrac{2}{3}) = 15\) | \((4 - 12) / (-\tfrac{2}{3}) = 12\) | \([12,\ 15]\) |
| Z | \(2.8 / \tfrac{1}{3} = 8.4\) | \(9.2 / \tfrac{1}{3} = 27.6\) | \([8.4,\ 27.6]\) |
\(t_{\text{enter}} = \max(8.4, 12, 8.4) = 12\) and \(t_{\text{exit}} = \min(15.6, 15, 27.6) = 15\). Since \(12 \le 15\), the ray goes through the box; it enters through the top face, at \((8, 4, 4)\). In Y the ray is descending, which is why it reaches the maximum plane first: hence the need to sort.
def ray_aabb(origin, direction, minimum, maximum):
"""Distance t to the box (0 if the origin is inside), or None."""
t_enter, t_exit = 0.0, np.inf
for axis in range(3):
if abs(direction[axis]) < 1e-12:
if origin[axis] < minimum[axis] or origin[axis] > maximum[axis]:
return None
continue
t1 = (minimum[axis] - origin[axis]) / direction[axis]
t2 = (maximum[axis] - origin[axis]) / direction[axis]
if t1 > t2:
t1, t2 = t2, t1
t_enter = max(t_enter, t1)
t_exit = min(t_exit, t2)
if t_enter > t_exit:
return None
return float(t_enter)
print(round(ray_aabb(lamp, ship_beam, box_min, box_max), 6), ray_aabb(lamp, strip_beam, box_min, box_max))Overlap tests between volumes
For collisions between objects there is no ray: the question is whether two volumes overlap. With simple volumes, each test is one line.
| Test | Criterion | Idea |
|---|---|---|
| Sphere–sphere | \(\lVert \mathbf{c}_2 - \mathbf{c}_1 \rVert^2 \le (r_1 + r_2)^2\) | The centers are closer than the sum of the radii (no roots) |
| AABB–AABB | On all three axes: \(\min_1 \le \max_2\) and \(\min_2 \le \max_1\) | Their intervals overlap in X, in Y and in Z |
| Sphere–AABB | \(\lVert \mathbf{c} - \mathbf{q} \rVert^2 \le r^2\), with \(\mathbf{q}\) the point of the box closest to \(\mathbf{c}\) | \(\mathbf{q}\) is obtained by clamping each coordinate of \(\mathbf{c}\) to the box's interval |
| Sphere–plane | \(\lvert \hat{\mathbf{n}} \cdot \mathbf{c} + d \rvert \le r\) | The distance from the center to the plane does not exceed the radius |
In AABB–AABB, a single axis on which the intervals do not overlap is enough to guarantee that the boxes are separated. The clamping in sphere–AABB is the same idea we used with the segment in the previous lesson, applied to three coordinates.
Example. Does the ship collide with the rogue asteroid?
- Sphere–sphere. \(\mathbf{c}_2 - \mathbf{c}_1 = (-6, 5, -1)\), with squared norm 62. Sum of the radii: \(4 + 5 = 9\), squared 81. Since \(62 \le 81\), the spheres overlap.
- Sphere–AABB. Clamping the center \((2, 8, 5)\) to the ship's box: \(x\) goes up to 5.6, \(y\) goes down to 4 and \(z = 5\) is already inside: \(\mathbf{q} = (5.6, 4, 5)\). Squared distance: \(3.6^2 + 4^2 + 0^2 = 28.96 > 25\). They do not overlap.
The ship's sphere said "maybe"; its box, a tighter fit, says "no". Spheres never give a false "no", but they do give false "maybes".
def spheres_overlap(center1, radius1, center2, radius2):
radius_sum = radius1 + radius2
separation = np.asarray(center2, dtype=float) - np.asarray(center1, dtype=float)
return squared_norm(separation) <= radius_sum * radius_sum
def aabb_overlap(minimum1, maximum1, minimum2, maximum2):
return bool(np.all(np.asarray(minimum1) <= np.asarray(maximum2))
and np.all(np.asarray(minimum2) <= np.asarray(maximum1)))
def sphere_aabb_overlap(center, radius, minimum, maximum):
closest = np.clip(center, minimum, maximum)
return squared_norm(np.asarray(center, dtype=float) - closest) <= radius * radius
def sphere_plane_overlap(center, radius, plane):
return abs(point_plane_distance(plane, center)) <= radius
print(spheres_overlap(ship_center, ship_radius, rogue, rogue_radius),
sphere_aabb_overlap(rogue, rogue_radius, box_min, box_max))
drone = np.array([10.0, 3.0, 6.0])
print(aabb_overlap(box_min, box_max, drone - 0.5, drone + 0.5),
sphere_plane_overlap(rogue, rogue_radius, strip))The escort drone's box (a cube 1 m on a side) overlaps the ship's, even though the drone flies outside the hull: another "maybe" that would have to be confirmed with a finer test.
Broad phase and narrow phase
The examples above show the strategy that every engine follows:
- Broad phase: very cheap tests with bounding volumes, whose only goal is to reject quickly. A "no" is final; a "yes" only means "maybe".
- Narrow phase: exact tests (triangle by triangle) only for the few candidates that survive.
When there are many objects, the volumes are also organized into hierarchies (boxes that contain boxes), so that a single test rules out entire groups.
A middle ground between the AABB and the triangles is the oriented bounding box (OBB): a box that rotates with the object. For the ship it would be the box with half-sides \((4, 1, 2)\) along its local axes \(n_1\), \(n_2\), \(n_3\), a much tighter fit than its AABB. It requires no new formulas: it is enough to take the ray into the object's local system with the inverse of its model matrix, as we learned in Module 2, and there the OBB is an AABB. For an arbitrary point cloud, the axes of a good OBB are the ones principal_axes returned in "Eigenvalues and Eigenvectors".
Application: the lighthouse beam and the line of sight
Let's put the pieces together. The ship's hull is an octahedron: eight faces, each with one vertex from each pair (right or left wing, top or bottom, nose or tail).
def hull_hit(origin, direction):
"""Broad phase (sphere, box) and narrow phase (the eight faces). Returns t or None."""
if ray_sphere(origin, direction, ship_center, ship_radius) is None:
return None
if ray_aabb(origin, direction, box_min, box_max) is None:
return None
hits = [ray_triangle(origin, direction, wing, vertical, end)
for wing in (right_wing, left_wing)
for vertical in (top, bottom)
for end in (nose, tail)]
hits = [t for t in hits if t is not None]
return min(hits) if hits else None
# 1) The lighthouse beam points at the ship
print(round(ray_sphere(lamp, ship_beam, ship_center, ship_radius), 4),
round(ray_aabb(lamp, ship_beam, box_min, box_max), 4),
round(hull_hit(lamp, ship_beam), 4))
# 2) A slightly deflected beam: toward the point (6, 4, 8)
deflected_beam = direction_to(lamp, [6.0, 4.0, 8.0])
print(round(ray_sphere(lamp, deflected_beam, ship_center, ship_radius), 4),
round(ray_aabb(lamp, deflected_beam, box_min, box_max), 4),
hull_hit(lamp, deflected_beam))
# 3) Line of sight: from the camera to the ship
camera = np.array([0.0, 5.0, 20.0])
line_of_sight = direction_to(camera, ship)
t_ship = hull_hit(camera, line_of_sight)
obstacles = [ray_sphere(camera, line_of_sight, rogue, rogue_radius),
ray_sphere(camera, line_of_sight, lighthouse_asteroid, lighthouse_radius)]
print(round(t_ship, 4), obstacles)- The beam lights up the ship. The bounding sphere is reached at 9.76 m, the box at 12 m and the actual hull at 13 m. Each wrapper is a tighter fit than the one before, and all of them give their warning before the real hit: they are conservative.
- The deflected beam does not light it up, even though it goes through the sphere and the box. It is a broad-phase false positive that the narrow phase corrects: the beam passes through an empty corner of the box.
- The camera sees the ship. The line of sight reaches the hull at 13.93 m and neither of the two asteroids gets in the way. If any obstacle had returned a \(t\) smaller than 13.93, the ship would be hidden.
Costs and uses
| Test | Main operations | Cost | Typical use |
|---|---|---|---|
| Ray–plane | 2 dot products, 1 division | Minimal | Floors, walls, dragging objects across a plane |
| Ray–sphere | 2 dot products, 1 root | Very low | Quick rejection, projectiles, round objects |
| Ray–AABB | 6 divisions and comparisons | Very low | Broad phase, box hierarchies |
| Ray–triangle | 2 cross products, 4 dot products | Low, but per triangle | Exact hit on a mesh |
| Sphere–sphere | 1 squared norm | Minimal | Approximate collisions, trigger radii |
| AABB–AABB | 6 comparisons | Minimal | Collision broad phase |
| Sphere–AABB | 1 clamp, 1 squared norm | Very low | Character against a level made of boxes |
| Sphere–plane | 1 dot product | Minimal | Object against floor or wall; culling against the camera |
Common Mistakes and Tips
- Using an unnormalized direction. The formulas in this lesson assume \(\lVert \hat{\mathbf{d}} \rVert = 1\). Otherwise, \(t\) is no longer a distance and the sphere equation needs its coefficient \(a = \mathbf{d} \cdot \mathbf{d}\).
- Accepting negative values of \(t\). It is the line, not the ray, that touches something behind the origin.
- Forgetting the "origin inside" case. With the sphere, the first solution is negative and the hit is the second.
- Keeping the first hit found instead of the closest. You have to go through all the candidates and keep the smallest \(t\).
- Self-intersection. A ray that starts on a surface (a bounce, a shadow) can "collide" with that very surface at \(t \approx 0\) because of rounding. This is avoided by requiring \(t\) to be greater than a small tolerance or by nudging the origin a little.
- Treating the "yes" of a bounding volume as a hit. It is only a "maybe". The "no", on the other hand, is final.
- Not updating the volumes. If the object moves, its sphere travels with it; if it rotates, its AABB has to be recomputed.
- Tip. Order the tests from cheapest to most expensive and bail out as soon as one fails: in a real scene, the vast majority of tests end in "no".
Exercises
Exercise 1. The camera \((0, 5, 20)\) casts a ray in its viewing direction, \((0, 0, -1)\). a) Does it touch the rogue asteroid (center \((2, 8, 5)\), radius 5)? If so, at what distance and at which point? b) Does it touch the lighthouse asteroid (center \((0, -10, 0)\), radius 10)?
Exercise 2. The strip is bounded by the beacons \((13, 0, 2)\), \((9, 4, 0)\), \((9, 0, 4)\) and \((5, 4, 2)\). a) Compute its AABB. b) With the slab method, find where the ship's descent ray enters that box: origin \((8, 3, 6)\), direction \((1, -1, -1)/\sqrt{3}\). c) Does the strip's AABB overlap the ship's? Does that mean the ship is touching the strip?
Exercise 3. The stray asteroid drifts to \((4, 4, 13)\); its radius is 2. Using the functions from the lesson, decide whether it now hides the ship from the camera.
Solutions
Solution 1.
a) \(\mathbf{m} = (2, 3, -15)\); \(b = \mathbf{m} \cdot (0, 0, -1) = 15\); \(c = (4 + 9 + 225) - 25 = 213\); \(\Delta = 225 - 213 = 12 > 0\). \(t = 15 \pm \sqrt{12}\): \(t_1 \approx 11.536\), \(t_2 \approx 18.464\). It touches it 11.54 m away, at \((0, 5, 20 - 11.536) = (0, 5, 8.464)\).
b) \(\mathbf{m} = (0, -15, -20)\); \(b = 20\); \(c = 625 - 100 = 525\); \(\Delta = 400 - 525 < 0\). It does not touch it: the ray passes \(\sqrt{625 - 400} = 15\) m from the center, more than the radius.
Solution 2.
a) Minimum \((5, 0, 0)\), maximum \((13, 4, 4)\).
b) Each component of the direction equals \(\pm 1/\sqrt{3} \approx \pm 0.5774\).
- X: \((5 - 8)/0.5774 = -5.196\) and \((13 - 8)/0.5774 = 8.660\). Interval \([-5.196,\ 8.660]\).
- Y: \((0 - 3)/(-0.5774) = 5.196\) and \((4 - 3)/(-0.5774) = -1.732\). Interval \([-1.732,\ 5.196]\).
- Z: \((0 - 6)/(-0.5774) = 10.392\) and \((4 - 6)/(-0.5774) = 3.464\). Interval \([3.464,\ 10.392]\).
\(t_{\text{enter}} = \max(0, -5.196, -1.732, 3.464) = 3.464\); \(t_{\text{exit}} = \min(8.660, 5.196, 10.392) = 5.196\). It enters the box at \(3.464 = 2\sqrt{3}\) m, at \((8, 3, 6) + 2,(1, -1, -1) = (10, 1, 4)\). The actual contact with the plane of the strip was \((11, 0, 3)\), at \(3\sqrt{3} \approx 5.196\) m: exactly where the ray exits the box.
c) Ship: \([5.6, 10.4] \times [2, 4] \times [2.8, 9.2]\). Strip: \([5, 13] \times [0, 4] \times [0, 4]\). The intervals overlap on all three axes, so the boxes overlap. But that does not imply contact: the ship is 3 m above the strip. Since the strip is sloping, its AABB contains a lot of empty space; it is a false positive that the narrow phase would rule out.
Solution 3.
print(round(ray_sphere(camera, np.array([0.0, 0.0, -1.0]), rogue, rogue_radius), 3))
strip_min, strip_max = aabb_from_points([b1, b2, b3, [5.0, 4.0, 2.0]])
descent = np.array([1.0, -1.0, -1.0]) / np.sqrt(3.0)
print(strip_min, strip_max, round(ray_aabb(ship, descent, strip_min, strip_max), 3),
aabb_overlap(box_min, box_max, strip_min, strip_max))
t_stray = ray_sphere(camera, line_of_sight, [4.0, 4.0, 13.0], 2.0)
print(round(t_stray, 3), t_stray < t_ship)The first two lines confirm Exercises 1 and 2. In the third, the line of sight touches the stray asteroid at 6.12 m, before the ship's hull (13.93 m): the ship is hidden. The asteroid is almost at the midpoint between the camera and the ship, \((4, 4, 13)\), which we computed in "Coordinates and Planes".
Conclusion
This lesson brings Module 3 to a close. We began by looking closely at the coordinate system and we end by casting rays around the scene: along the way we have learned to measure vectors and normalize them, to multiply them with the dot product and the cross product, to describe lines and planes, to compute distances, projections and reflections, and to decide whether a ray hits a plane, a sphere, a triangle or a box, relying on bounding volumes to quickly rule out what cannot be. We now know how to move the scene and how to measure it. One piece of unfinished business remains, which we have been dodging since Module 2: orientations. We have rotated the ship about a coordinate axis and we have manufactured an orientation matrix from a direction, but we do not yet know how to describe an arbitrary rotation with a few numbers, combine it with others without surprises or move smoothly from one orientation to another. That is what Module 4, "Rotations and Orientation in 3D", is about; it begins with the lesson "Euler Angles and Gimbal Lock": the most intuitive way of describing an orientation, and the famous problem it hides.
