Exercise: rays from the camera, and where they hit

Goal

By the end of this exercise you should be able to:

  • build the ray through a pixel for a given camera and image size,
  • intersect a ray with a sphere, a plane and a triangle by hand, and pick the nearest hit,
  • read barycentric coordinates to decide inside or outside, and get the normal at the hit,
  • count the cost of ray casting (pixels × objects),
  • (math) derive the three intersections, including the numerically stable quadratic, and solve the triangle system by Cramer’s rule.

Do the pen-and-paper part first, then the demo.

Background

Idea What it means
Camera ray from the eye \mathbf o through the pixel centre (i + \tfrac12, j + \tfrac12); x_n = 2(i + \tfrac12)/W - 1, y_n = 1 - 2(j + \tfrac12)/H; \mathbf d \propto (x_n \tan\tfrac\varphi2 \tfrac WH,\ y_n \tan\tfrac\varphi2,\ -1) for a camera at the origin looking down -z
Ray \mathbf r(t) = \mathbf o + t\mathbf d, t > 0; with \lVert\mathbf d\rVert = 1, t is a distance
Nearest hit the smallest positive t over all objects
Sphere t = -b' \pm\sqrt{b'^2 - k}, b' = \mathbf d\cdot(\mathbf o - \mathbf c), k = \lVert\mathbf o - \mathbf c\rVert^2 - r^2 (unit \mathbf d); normal (\mathbf p - \mathbf c)/r
Plane t = (\mathbf p_0 - \mathbf o)\cdot\mathbf n / (\mathbf d\cdot\mathbf n); \mathbf d\cdot\mathbf n = 0: parallel
Triangle inside iff the barycentric coordinates (b_a, b_b, b_c) of the hit on its plane are all \ge 0
Lambert brightness \propto \max(0, \mathbf n\cdot\mathbf l), \mathbf l the unit vector towards the light

By hand

B1. Camera rays. A camera at the origin looks down -z, vertical field of view 90°, image 4 × 2 pixels (rows counted from the top). (a) Compute x_n, y_n and the direction \mathbf d (before and after normalising) for pixel (1, 0). (b) The same for pixel (3, 1). In which part of the view does it look? (c) Why does no pixel look exactly straight ahead along (0, 0, -1)?

B2. A sphere. The ray \mathbf o = \mathbf 0, \mathbf d = (0, 0, -1) and the sphere with centre \mathbf c = (0.5, 0, -5), radius r = 1. (a) Compute b', k and the discriminant b'^2 - k. Does the ray hit? (b) Find both roots and the hit point. (c) Find the normal at the hit and the Lambert term for a light straight behind the camera, \mathbf l = (0, 0, 1). (d) Move the sphere’s centre to (1.5, 0, -5). What happens?

B3. A plane. The floor y = -1 (normal (0, 1, 0)), eye at the origin. (a) Does the ray \mathbf d = (0, 0, -1) hit it? Why? (b) Where does \mathbf d = (0, -0.6, -0.8) hit it? (c) And \mathbf d = (0, 0.6, -0.8)?

B4. A triangle. The ray meets a triangle’s plane at three different points with barycentric coordinates (i) (0.2, 0.3, 0.5), (ii) (0.6, -0.1, 0.5), (iii) (0.4, 0.6, 0). Which are hits? For a miss, which edge is the point beyond? The vertex normals are \mathbf n_a = (0, 0, 1), \mathbf n_b = (0, 1, 0), \mathbf n_c = (1, 0, 0): which (unnormalised) normal does smooth shading use at point (i)?

B5. Nearest hit. Along one ray, the sphere gives roots -1.2 and 3.5, a plane gives t = 7.0, and a triangle gives t = 2.1 with barycentric coordinates (0.5, 0.6, -0.1). What does the pixel show, and why?

B6. Cost. (a) How many ray–object tests does a ray caster need for a 640 × 480 image of 5000 triangles? (b) For 1920 × 1080 pixels and a mesh of 10^6 triangles? (c) If one test takes 10 ns, how long does (b) take?

B1. (a) x_n = 2 \cdot 1.5/4 - 1 = -0.25, y_n = 1 - 2 \cdot 0.5/2 = 0.5; \tan 45° = 1, W/H = 2: \mathbf d \propto (-0.5, 0.5, -1), unit (-0.408, 0.408, -0.816). (b) x_n = 0.75, y_n = -0.5: \mathbf d \propto (1.5, -0.5, -1), unit (0.802, -0.267, -0.535): to the right and down. (c) With an even number of pixels across, the centre of the view falls on the border between two pixels; each pixel looks through its own centre, half a pixel off the axis.

B2. (a) \mathbf o - \mathbf c = (-0.5, 0, 5); b' = (0, 0, -1)\cdot(-0.5, 0, 5) = -5; k = 0.25 + 25 - 1 = 24.25; b'^2 - k = 25 - 24.25 = 0.75 > 0: two hits. (b) t = 5 \mp \sqrt{0.75} = 4.134 and 5.866; the nearest is t = 4.134, hit point (0, 0, -4.134). (c) \mathbf n = (\mathbf p - \mathbf c)/r = (-0.5, 0, 0.866); Lambert \mathbf n\cdot\mathbf l = 0.866. (d) Now \mathbf o - \mathbf c = (-1.5, 0, 5), b' = -5, k = 2.25 + 25 - 1 = 26.25, b'^2 - k = -1.25 < 0: the ray passes the sphere at distance 1.5 from its centre, more than the radius: a miss.

B3. (a) \mathbf d\cdot\mathbf n = 0: the ray is parallel to the floor and never reaches it. (b) t = (-1)/(-0.6) = 1.667; the point (0, -1, -1.333). (c) \mathbf d\cdot\mathbf n = 0.6, t = -1/0.6 = -1.667 < 0: the floor is “hit” behind the eye; no hit.

B4. (i) All \ge 0: a hit. (ii) b_b = -0.1 < 0: a miss, beyond the edge opposite \mathbf b, the edge \mathbf a\mathbf c. (iii) On the edge \mathbf a\mathbf b (b_c = 0): counts as a hit (a shared edge belongs to one of its two triangles; a ray caster may test with \ge 0 and accept either). Normal at (i): 0.2\,\mathbf n_a + 0.3\,\mathbf n_b + 0.5\,\mathbf n_c = (0.5, 0.3, 0.2), which still has to be normalised (length 0.616).

B5. The sphere: its roots are -1.2 (behind the eye) and 3.5, so the eye is inside the sphere and the ray hits its inside at t = 3.5. The triangle’s point is outside it (b_c < 0), so it does not count, even though 2.1 < 3.5. The plane at 7.0 is farther. The pixel shows the inside of the sphere.

B6. (a) 640 \cdot 480 \cdot 5000 = 1.54 \cdot 10^9. (b) 1920 \cdot 1080 \cdot 10^6 = 2.07 \cdot 10^{12}. (c) 2.07 \cdot 10^{12} \cdot 10^{-8} s = 2.1 \cdot 10^4 s, almost 6 hours for one image.

Math questions

B7. (math) The sphere and cancellation. (a) Substitute \mathbf o + t\mathbf d into \lVert\mathbf x - \mathbf c\rVert^2 = r^2 and derive t^2 + 2b't + k = 0 for a unit \mathbf d. What changes if \mathbf d is not a unit vector? (b) In float32, with b' = -10^4 and k = 1: compute the small root with the textbook formula -b' - \sqrt{b'^2 - k}, given that floats near 10^8 are 8 apart. (c) Compute it the stable way, t = k/q with q = -(b' + \operatorname{sign}(b')\sqrt{b'^2 - k}), and compare with the exact value 1/(10^4 + \sqrt{10^8 - 1}).

B8. (math) Cramer’s rule. Triangle \mathbf a = (0, 0, -2), \mathbf b = (1, 0, -2), \mathbf c = (0, 1, -2), ray \mathbf o = \mathbf 0, \mathbf d = (0.2, 0.2, -1). (a) Write the system [-\mathbf d\ \ \mathbf e_1\ \ \mathbf e_2](t, u, v)^\top = \mathbf o - \mathbf a. (b) Solve it by Cramer’s rule: compute \det[-\mathbf d\ \mathbf e_1\ \mathbf e_2] and the three determinants with one column replaced. (c) Give the barycentric coordinates and check the hit point both ways.

B9. (math) Perspective-correct for free. A rasteriser interpolates an attribute f with screen-space weights \beta_i as \sum_i \beta_i f_i/w_i \big/ \sum_i \beta_i/w_i, where w_i is the depth of vertex i. Show that the weights \frac{\beta_i/w_i}{\sum_j \beta_j/w_j} are the barycentric coordinates of the 3D point seen through the pixel, which is what ray casting computes directly. (Hint: a 3D point \mathbf p = \sum_i b_i \mathbf v_i projects to the screen point \sum_i b_i w_i \mathbf s_i / \sum_i b_i w_i, where \mathbf s_i are the projected vertices.)

B10. (math) Ray–cylinder. An infinite cylinder of radius r around the z axis is x^2 + y^2 = r^2. (a) Derive the quadratic for the ray \mathbf o + t\mathbf d. Why does d_z not appear? (b) Solve it for \mathbf o = (-3, 0.5, 0), \mathbf d = (1, 0, 0), r = 1. (c) What is the normal at a hit point \mathbf p?

B7. (a) \lVert\mathbf o - \mathbf c + t\mathbf d\rVert^2 = \lVert\mathbf o - \mathbf c\rVert^2 + 2t\,\mathbf d\cdot(\mathbf o - \mathbf c) + t^2\lVert\mathbf d\rVert^2 = r^2; with \lVert\mathbf d\rVert = 1: t^2 + 2b't + k = 0. For a general \mathbf d: a t^2 + 2b't + k = 0 with a = \mathbf d\cdot\mathbf d, and t = (-b' \pm\sqrt{b'^2 - ak})/a; t is then measured in units of \lVert\mathbf d\rVert. (b) b'^2 - k = 10^8 - 1 rounds to 10^8 (the nearest float), its square root is exactly 10^4, and 10^4 - 10^4 = 0: the small root comes out as 0, a 100 % error. (c) q = -(-10^4 - 10^4) = 2\cdot10^4, t = 1/(2\cdot10^4) = 5\cdot10^{-5}; exact 5.0000000125\cdot10^{-5}: correct to 9 digits. Cancellation is avoided because the large root adds two numbers of equal sign.

B8. (a) \mathbf e_1 = (1, 0, 0), \mathbf e_2 = (0, 1, 0), -\mathbf d = (-0.2, -0.2, 1), \mathbf o - \mathbf a = (0, 0, 2): \begin{bmatrix} -0.2 & 1 & 0\\ -0.2 & 0 & 1\\ 1 & 0 & 0\end{bmatrix}\begin{bmatrix}t\\u\\v\end{bmatrix} = \begin{bmatrix}0\\0\\2\end{bmatrix}. (b) D = \det = 1 (expand along the third row: 1\cdot\det\begin{bmatrix}1&0\\0&1\end{bmatrix} = 1). Replacing column 1 by the right-hand side: D_t = 2; column 2: D_u = 0.4; column 3: D_v = 0.4. So t = 2, u = 0.4, v = 0.4. (c) (b_a, b_b, b_c) = (0.2, 0.4, 0.4), all \ge 0: a hit. Check: \mathbf o + 2\mathbf d = (0.4, 0.4, -2) and 0.2\,\mathbf a + 0.4\,\mathbf b + 0.4\,\mathbf c = (0.4, 0.4, -2).

B9. The point \mathbf p = \sum_i b_i\mathbf v_i (3D barycentrics b_i) has homogeneous projection \sum_i b_i (w_i\mathbf s_i, w_i), so its screen position is \mathbf s = \sum_i b_i w_i\mathbf s_i / \sum_j b_j w_j: the screen weights are \beta_i = b_i w_i/\sum_j b_j w_j. Invert: \beta_i/w_i \propto b_i, and normalising to sum 1 gives b_i = \frac{\beta_i/w_i}{\sum_j \beta_j/w_j}. These are exactly the rasteriser’s correction weights; a ray caster obtains b_i directly as (1 - u - v, u, v).

B10. (a) (o_x + t d_x)^2 + (o_y + t d_y)^2 = r^2: a t^2 + 2b't + k = 0 with a = d_x^2 + d_y^2, b' = o_x d_x + o_y d_y, k = o_x^2 + o_y^2 - r^2. The cylinder is the same at every height z, so the z components never enter (and a = 0, a ray along the axis, is the “parallel” case). (b) a = 1, b' = -3, k = 9 + 0.25 - 1 = 8.25, b'^2 - ak = 0.75: t = 3 \mp 0.866 = 2.134 and 3.866. (c) \mathbf n = (p_x, p_y, 0)/r: radial, no z component.

Explore

A small scene: two spheres (A, red; B, blue), an upright triangle and a ground plane with a checkerboard, lit by one light. The camera C looks down -z. Left: the image on a coarse grid of 16 × 12, 32 × 24 or 64 × 48 pixels, filled in as you trace (next pixel, next row, all; click any pixel to inspect it). Middle: a top view (the x–z plane): the camera, the image plane with its pixel columns, the inspected ray and every candidate hit (filled dot: a real hit in front of the eye; hollow: outside the triangle; red and dashed: behind the eye). The readout lists the discriminant and roots per sphere, t for the plane, t, u, v for the triangle, the nearest hit, its normal and \mathbf n\cdot\mathbf l. Drag C in the top view to move the camera.

E1. Preset one sphere. Press next pixel a few times, then next row. How many rays and tests does the full 16 × 12 image need? Inspect the centre pixel (8, 6): read the discriminant and the two roots. Why is the discriminant so small here?

E2. Preset a ray that misses. What is the discriminant for pixel (2, 2)? Click pixels towards the sphere: where does the discriminant change sign?

E3. Preset sphere behind the camera. Read the roots for the sphere A in pixel (16, 12). What does the pixel show instead, and at what distance? Drag the camera C back towards the bottom of the top view until sphere A appears in the image.

E4. Preset eye inside the sphere. Read the two roots of sphere A. Which one is the hit, and what does the whole image show?

E5. Preset the triangle: barycentrics (view: barycentric as red, green, blue). Read t, u, v for pixel (34, 25) and give (b_a, b_b, b_c). Click pixels near the triangle’s edges: which coordinate goes negative when you leave across each edge? What colour are the corners?

E6. Switch the views depth, normal and object at 64 × 48. What does each show, and where are the normals of the ground and of the spheres’ tops?

E7. Preset orthographic vs perspective. What happens to the ground, and why? Toggle orthographic off and on and compare the size of sphere B (farther away) with sphere A.

E8. Preset count the tests. How many rays and tests for 64 × 48? Predict the number for 32 × 24, then check.

E1. 16 × 12 = 192 rays and 192 tests (one object). Pixel (8, 6): discriminant 0.051, roots t = 5.81 and 6.26. The scene has one sphere of radius 0.8, and this pixel’s ray passes close to the top edge of the sphere (which sits below the centre of the view): the two hits are close together, so the ray almost grazes.

E2. −13.3: far from the sphere. The sign changes at the sphere’s silhouette: inside the silhouette the discriminant is positive (two hits), outside negative.

E3. Both roots negative: −2.30 and −0.70, so the sphere is behind the camera and not seen. The pixel shows the ground, at t = 33.3 (the ray points very slightly down). Dragging C to z > -0.7 puts the sphere in front again.

E4. Roots −0.80 and 0.80: the eye is at the centre of sphere A (radius 0.8). The hit is t = 0.80, the inside wall; every pixel sees the inside of the sphere, so the whole image is red, shaded by Lambert with the normals pointing away from the eye (flipped towards it).

E5. t = 7.76, u = 0.35, v = 0.33: (b_a, b_b, b_c) = (0.32, 0.35, 0.33), near the centroid. Leaving across the edge opposite a vertex makes that vertex’s weight negative. The corners are pure red (\mathbf a, bottom left), green (\mathbf b, bottom right) and blue (\mathbf c, top).

E6. Depth: brighter = nearer (t small); the ground fades towards the horizon. Normal: (n_x, n_y, n_z) mapped from [-1, 1] to [0, 255] as RGB; the ground is (0, 1, 0), a uniform light green (128, 255, 128), and so are the tops of the spheres; their left sides have less red (negative n_x), their right sides more. Object: one flat colour per object, the “which object does this pixel see?” answer of ray casting.

E7. The ground disappears: all rays are parallel to -z, so they run parallel to the ground plane (as in B3 a). Sphere B keeps its size in orthographic projection, while with perspective it looks smaller because it is farther away.

E8. 64 × 48 = 3072 rays, 4 objects: 12 288 tests. 32 × 24 = 768 rays, 3072 tests: a quarter, since the cost is proportional to the number of pixels.

Code

Write the algorithms of this unit yourself, in Rust. Setup, and how to run and check your code: coding exercises: getting started. Your code goes in raytracing/src/raycast/exercise.rs.

C1. camera_ray(i, j, width, height, fov): the ray from the eye at the origin through the centre of pixel (i, j), with a direction of length 1:

xn = 2 (i + 0.5) / width − 1
yn = 1 − 2 (j + 0.5) / height
d  = (xn · tan(fov/2) · width/height,  yn · tan(fov/2),  −1)
return ray from (0, 0, 0) along d / |d|

The check is your answer to B1.

C2. smaller_positive_root(b, k) and hit_sphere(ray, centre, radius): the nearest hit with a sphere, by the quadratic t^2 + 2b't + k = 0, computed in the stable way:

b' = d · (o − c);   k = |o − c|² − r²
if b'² − k < 0: no hit
q  = −b' − √(b'² − k)   if b' ≥ 0,   else  −b' + √(b'² − k)
the two roots are q and k / q
return the smaller root if it is > 0, else the larger one if it is > 0, else no hit

The checks are B2, B5 (the eye inside the sphere) and B7 (b' = -10^4, k = 1, where the textbook formula gives 0).

C3. hit_plane(ray, point, normal): t = (\mathbf p_0 - \mathbf o)\cdot\mathbf n / (\mathbf d\cdot\mathbf n); no hit if \mathbf d\cdot\mathbf n = 0 or t \le 0. The check is B3.

C4. hit_triangle(ray, a, b, c): solve the 3\times3 system by Cramer’s rule:

e1 = b − a;   e2 = c − a;   r = o − a
D  = det[−d, e1, e2]                         # det[x, y, z] = x · (y × z)
if D ≈ 0: no hit (parallel)
t = det[r, e1, e2] / D;   u = det[−d, r, e2] / D;   v = det[−d, e1, r] / D
hit if u ≥ 0, v ≥ 0, u + v ≤ 1 and t > 0

The check is B8.

C5. nearest_hit(ray, scene): ray casting for one ray.

best = none
for every object:
    t = the object's hit (C2, C3 or C4)
    if there is a hit and t < best.t:
        best = (t, the normal at o + t d, the object)
if best.normal · d > 0: flip the normal (seen from the back)

The check is B5: the triangle’s hit outside its edges must not count, and the inside of the sphere has its normal turned towards the eye.

Then cargo run -p raytracing -- raycast and open the pictures in out/raycast/.

C6. Compare colour.png, depth.png, normal.png and object.png. Which colour has the ground in normal.png, and why is it the same everywhere? Where else does that colour appear?

C7. The program prints how long its 307 200 tests took and what that means for 1920 × 1080 pixels and a mesh of 10^6 triangles. Compare with B6 (c). What would you have to change to make it fast?

The model solution is raytracing/src/raycast/solution.rs in the download.

C6. The colour image is Lambert shading; the other three come for free from the same hits: the depth (bright = near, the ground fades towards the horizon), the normal as a colour, and one flat colour per object (which object each pixel sees). The ground is one uniform light green in normal.png: its normal is (0, 1, 0) everywhere, shown as (0.5, 1, 0.5). The tops of the two spheres, whose normals also point straight up, have the same green.

C7. 76 800 rays and 307 200 tests took about 10 ms on our computer, some 30–40 ns per test (the shading included). At that speed the full-HD image of a million triangles takes between half a day and a day, of the same order as B6’s 6 hours at 10 ns per test. Faster tests do not help much: the number of tests (pixels × objects) is the problem. Unit 3 tests boxes around groups of objects and gets to about 2\log_2 N tests per ray.

Where this leads

Ray casting answers “what does this pixel see?”. The next unit, Shadows, mirrors and glass, keeps asking from the hit point: is the light visible from here (a shadow ray)? what does the mirror direction see? where does the light go inside the glass? Unit 3 makes all of this fast.