Last updated: 2026-11-26
4. Mirrors and glass
For new readers
A point on a mirror or in glass is not finished by the light that falls on it: its colour also holds what a reflected ray sees, and what a refracted ray sees through it. This page adds those two rays, the bookkeeping of which medium a ray is in (for Snell's law), and Schlick's approximation of how much a transparent surface reflects. It is used by every glass and polished thing in the scenes of part III.
Reflection and Refraction
Mirrors and glass: the renderer starts spawning secondary rays, so color_at,
shade_hit and two new colour functions recurse, with a depth limit to stop
two facing mirrors bouncing forever. Both effects are geometry that the
algebra already speaks: reflection is a versor, and the refracted direction is
a scaled rejection.
Step 1 — materials and the precomputed state
A material gains reflective (0 matt … 1 mirror), transparency (0 opaque …
1 clear) and refractive_index (1 vacuum, 1.5 glass); glass_sphere() is the
book's helper. prepare_computations now takes the full sorted list of
intersections as a third argument, and returns, besides the earlier fields:
reflectv— the ray direction reflected about the normal, which is the sandwich−n v n⁻¹already used for the light's reflection in Light at a point, and shadows;under_point— the hit nudgedEPSILONagainst the normal, where refracted rays start (the mirror image ofover_point);n1,n2— the refractive index of the medium the ray leaves and the one it enters, from the book's "containers" walk: scan the intersections in order, and an object already in the list means the ray is leaving it.
# precomputed state of an intersection:
# [t, object, point, eyev, normalv, inside, over_point, reflectv, under_point, n1, n2]
# over_point / under_point are the hit point nudged EPSILON along / against the
# normal (translator sandwiches): shadow and reflection rays start just above
# the surface, refracted rays just below it. n1 / n2 are the refractive indices
# of the medium the ray leaves and the one it enters, found by walking the
# sorted intersections `xs` and tracking which objects the ray is inside.
make a function called prepare_computations takes i, r, xs returns comps
let t = i[0]
let object = i[1]
let p = position(r, t)
let eyev = tuple_neg(r[1])
let normalv = normal_at_hit(object, p, i)
let inside = false
if dot(normalv, eyev) < 0 then
let inside = true
let normalv = tuple_neg(normalv)
end
if m_bump(shape_material(object)) != false then
let normalv = perturb_normal(object, p, normalv)
end
let n1 = 1
let n2 = 1
let containers = []
# n1, n2 and the under point only matter to refraction: an opaque object never asks
let transparent = m_transparency(shape_material(object)) > 0
let k = 0
if not transparent then
let k = xs.length
end
while k < xs.length do
let x = xs[k]
let is_hit = x[0] == i[0] and x[1][0] == i[1][0]
if is_hit then
if containers.length > 0 then
let n1 = m_refractive_index(shape_material(containers[containers.length - 1]))
end
end
let at = -1
let c = 0
while c < containers.length do
if container_key(containers[c]) == container_key(x[1]) then
let at = c
end
let c = c + 1
end
if at >= 0 then
let kept = []
let c = 0
while c < containers.length do
if c != at then
let kept = list_push(kept, containers[c])
end
let c = c + 1
end
let containers = kept
else
let containers = list_push(containers, x[1])
end
if is_hit then
if containers.length > 0 then
let n2 = m_refractive_index(shape_material(containers[containers.length - 1]))
end
let k = xs.length
end
let k = k + 1
end
let offset = tuple_mul(normalv, epsilon())
let under = false
if transparent then
let under = tuple_sub(p, offset)
end
return [t, object, p, eyev, normalv, inside, tuple_add(p, offset), reflect(r[1], normalv), under, n1, n2]
end
Step 2 — reflection, with a depth limit
reflected_color spawns a ray from over_point along reflectv and scales its
colour by the material's reflective. shade_hit adds it to the surface colour,
and color_at can then reach shade_hit again, so the recursion is cut off by
a remaining count that starts at max_depth() = 5 and drops by one each
bounce. Two mirrors facing each other terminate.
Step 3 — refraction is a rejection
Snell's law, sin θᵢ / sin θₜ = n₂ / n₁, says exactly one thing about the
direction: its component tangent to the surface scales by n₁/n₂, and the
normal component is fixed by keeping the vector a unit vector. The tangent
component of d against a unit normal n is the rejection, which in geometric
algebra is a left contraction of a bivector:ratio is n1/n2, the index ratio
d_∥ = n ⌋ (n ∧ d) = d − (d·n) n
t = (n₁/n₂) · d_∥ − cos θₜ · n with d = −eyev
Expanding with cos θᵢ = eyev · n gives the book's
n (ratio·cos_i − cos_t) − eyev·ratio exactly — the book's line is this formula
with the geometry multiplied out. When sin²θₜ = (n₁/n₂)² (1 − cos²θᵢ) exceeds
1 there is no refracted ray (total internal reflection) and the function
returns false.
Schlick's approximation of the Fresnel reflectance blends the two when a material is both reflective and transparent.
make a function called set_world_shadows takes w, on returns w2
return list_set(world_full(w), 2, on)
end
# how many bounces a ray may spawn: reflection and refraction recurse
make a function called max_depth returns d
return 5
end
# Direction of the refracted ray, or false under total internal reflection.
# Snell's law scales the component of the direction TANGENT to the surface by
# n1/n2; that component is the rejection of d from the unit normal n, which in
# geometric algebra is the left contraction n _| (n ^ d). So
# t = (n1/n2) n _| (n ^ d) - cos(theta_t) n, d = -eyev
# -- the book's n (ratio cos_i - cos_t) - eyev ratio written as geometry.
make a function called refract_direction takes comps returns t
let ratio = comps[9] / comps[10]
let cos_i = dot(comps[3], comps[4])
let sin2_t = ratio * ratio * (1 - cos_i * cos_i)
if sin2_t > 1 then
return false
end
let cos_t = sqrt(1 - sin2_t)
let nv = tuple_evec(comps[4])
let dv = tuple_evec(tuple_neg(comps[3]))
let tangential = ga_lcontract(nv, ga_outer(nv, dv))
let tv = ga_sub(ga_scale(tangential, ratio), ga_scale(nv, cos_t))
return cga_direction(tv[1], tv[2], tv[4])
end
# Schlick's approximation of the Fresnel reflectance, in [0, 1].
make a function called schlick takes comps returns r
let cosv = dot(comps[3], comps[4])
if comps[9] > comps[10] then
let n = comps[9] / comps[10]
let sin2_t = n * n * (1 - cosv * cosv)
if sin2_t > 1 then
return 1
end
let cosv = sqrt(1 - sin2_t)
end
let r0 = ((comps[9] - comps[10]) / (comps[9] + comps[10]))
let r0 = r0 * r0
let k = 1 - cosv
return r0 + (1 - r0) * k * k * k * k * k
end
make a function called reflected_color takes w, comps, remaining returns c
let reflective = m_reflective(shape_material(comps[1]))
if reflective == 0 or remaining < 1 then
return color(0, 0, 0)
end
let reflect_ray = ray(comps[6], comps[7])
return color_scale(color_at_depth(w, reflect_ray, remaining - 1), reflective)
end
make a function called refracted_color takes w, comps, remaining returns c
let transparency = m_transparency(shape_material(comps[1]))
if transparency == 0 or remaining < 1 then
return color(0, 0, 0)
end
let direction = refract_direction(comps)
if direction == false then
return color(0, 0, 0)
end
return color_scale(color_at_depth(w, ray(comps[8], direction), remaining - 1), transparency)
end
make a function called shade_hit takes w, comps, remaining returns c
let surface = surface_lighting(w, comps)
let reflected = reflected_color(w, comps, remaining)
let refracted = refracted_color(w, comps, remaining)
let m = shape_material(comps[1])
if m_reflective(m) > 0 and m_transparency(m) > 0 then
let reflectance = schlick(comps)
return color_add(color_add(surface, color_scale(reflected, reflectance)), color_scale(refracted, 1 - reflectance))
end
return color_add(color_add(surface, reflected), refracted)
end
make a function called color_at_depth takes w, r, remaining returns c
let curve = world_mirage(w)
if curve != false then
return mirage_color_at(w, r, remaining, curve)
end
let xs = intersect_world(w, r)
let h = hit(xs)
let atm = world_atmosphere(w)
if h.length == 0 then
if atm != false then
return atmosphere_blend(atm, color(0, 0, 0), r, infinity())
end
return color(0, 0, 0)
end
let seen = shade_hit(w, prepare_computations(h, r, xs), remaining)
if atm != false then
return atmosphere_blend(atm, seen, r, h[0])
end
return seen
end
# the colour a ray sees, with the default recursion depth
make a function called color_at takes w, r returns c
return color_at_depth(w, r, max_depth())
end
# Shadows are on by default. The switch exists to show a scene with and without
# them (the book's Chapter 8 does exactly that comparison).
make a function called world_shadows takes w returns on
return w[2]
end
Step 4 — checks
The glass node at the end of this page checks the parts one at a time: the reflected
direction of a hit; a matt surface reflects nothing; two mirrors facing each other stop at
the depth limit; with no bounces left there is no reflected or refracted light; which
medium a ray leaves and enters at each of the six hits through three overlapping glass
balls of different index, against the bookkeeping of tools/oracle.py; past the critical
angle there is no refracted ray; and Schlick's reflectance at five configurations
against the oracle. The colours of whole rays through the glass ball of the test scene
are checked on the camera and world page.
Step 5 — oracles that do not reuse the formulas
- Refraction geometry, for five rays through a glass sphere: the GA rejection
form equals the book's expression; the refracted direction has unit length;
Snell's law holds with the sines measured as cross-product magnitudes,
|d × n| / |t × n| = n₂ / n₁; andd,n,tare coplanar, i.e. the trivectord ∧ n ∧ tvanishes. - A classical result: a ray at impact parameter
bthrough a glass sphere (radius 1,n = 1.5) leaves deviated by2(θᵢ − θₜ)withsin θᵢ = b,sin θₜ = b/1.5. Entry and exit are traced with the library's ownprepare_computations(so the containers walk handles the exit), and the angle between the incoming and outgoing directions is compared with the formula at four impact parameters. - Schlick against exact Fresnel: the unpolarised Fresnel reflectance is
computed from the Fresnel equations and compared with
schlickat nine angles up to 58°; reflectance is always within[0, 1], and at normal incidence both equal((n₁−n₂)/(n₁+n₂))² = 0.04. - The mirror-image principle: a ray hitting a perfect mirror and then a self-lit ball sees the same colour as the same ray does in a world with no mirror and the ball mirrored through the mirror's plane. Six rays, five of them see the ball, one is a deliberate miss.
Step 6 — Putting it together: a glass sphere in a room
A reflective checkered floor (reflective 0.3), a checkered backdrop plane, a
large glass sphere (transparency 0.9, reflective 0.9, refractive_index 1.5,
tight specular highlight), a red sphere and a blue one.
# chapter 11: a reflective checkered floor, a checkered backdrop seen through and
# in a glass sphere, a red sphere and a blue sphere.
make a function called build_glass_scene returns w
let floor_m = with_reflective(with_pattern(material_with(color(1, 1, 1), (1/10), (9/10), 0, 200), set_pattern_transform(checkers_pattern(color((9/10), (9/10), (9/10)), color((1/4), (1/4), (1/4))), scaling((3/2), (3/2), (3/2)))), (3/10))
let floor_p = set_material(plane(), floor_m)
let back_m = with_pattern(material_with(color(1, 1, 1), (1/10), (9/10), 0, 200), set_pattern_transform(checkers_pattern(color((17/20), (17/20), (9/10)), color((1/5), (1/4), (2/5))), scaling(1, 1, 1)))
let backdrop = set_material(set_transform(plane(), mat_mul(translation(0, 0, 7), rotation_x(pi() / 2))), back_m)
let glass_m = with_refractive_index(with_transparency(with_reflective(material_with(color((1/20), (1/20), (2/25)), (1/20), (1/10), 1, 300), (9/10)), (9/10)), (3/2))
let glass = set_material(set_transform(sphere(), translation(-(1/2), 1, (1/2))), glass_m)
let red_s = set_material(set_transform(sphere(), mat_mul(translation((17/10), (1/2), -(2/5)), scaling((1/2), (1/2), (1/2)))), with_reflective(material_with(color((9/10), (3/20), (1/10)), (1/10), (7/10), (2/5), 200), (3/20)))
let blue_s = set_material(set_transform(sphere(), mat_mul(translation(-2, (3/5), (9/5)), scaling((3/5), (3/5), (3/5)))), material_with(color((3/20), (1/4), (9/10)), (1/10), (7/10), (2/5), 200))
return [[floor_p, backdrop, glass, red_s, blue_s], demo_light(), true]
end
# Chapter 11, "Putting It Together": a reflective floor, a glass sphere that
# bends the checkered backdrop and mirrors the room, and two matt spheres.
include "../lib/spec.patlang"
include "../lib/png.patlang"
include "../lib/camera.patlang"
include "../lib/demo_scene.patlang"
let w = build_glass_scene()
let cam = set_camera_transform(camera(400, 200, pi() / 3), view_transform(point(0, (3/2), -5), point(0, 1, 0), vector(0, 1, 0)))
render_example(cam, w, "../out/ch11_glass.png")
> tools/prender.sh examples/ch11_glass.patlang
assembled 400x200 from 40 bands
rendered with 18 parallel processes (40 bands) in 622 s wall clock
The glass sphere shows the checkered backdrop inverted and bent through it, a reflection of the room on its surface, and the floor's reflection of the spheres.
Checking it independently
A recursive tracer written for this check, in PowerShell with plain doubles: own
matrix inverse, the book's formulas for ray/sphere, ray/plane, normals, Phong
with patterns, shadows, reflection, the n1/n2 containers walk, Snell
refraction with total internal reflection, and Schlick, to depth 5. It uses no
algebra and no code from this project. Every second pixel in each direction of the 400×200 image (20 000 pixels, a lattice over the whole picture):
> powershell.exe -NoProfile -File tools/verify_recursive.ps1 out/ch11_glass.png -Stride 2
decoded by .NET: 400x200; pixels differing from the independent recursive tracer by more than 1 level: 0 (max difference 0); stride 2 in each direction, 20000 pixels checked
The check can fail: the same tracer with the glass made opaque (-OpaqueGlass)
disagrees wherever light passes through the sphere:
> powershell.exe -NoProfile -File tools/verify_recursive.ps1 out/ch11_glass.png -OpaqueGlass -Stride 16
decoded by .NET: 400x200; pixels differing from the independent recursive tracer by more than 1 level: 66 (max difference 145); stride 16 in each direction, 325 pixels checked
Cost
About 9 ms per pixel at depth 5 (46 s at 100×50, measured alone), against about 2 ms for the shadowed sphere scene of Light at a point, and shadows: the glass sphere alone spawns reflected and refracted rays that each hit the sphere again from the inside, and the floor adds a reflected ray per pixel. The recursion depth is the main cost knob.
How it is checked
> v2_interp.exe tests/run.patlang --node picture/glass --depth 2
[ ok ] Mirrors and glass
[ ok ] The reflected direction of a hit is the eye's ray turned about the normal
[ ok ] A matt surface reflects nothing
[ ok ] Two mirrors facing each other: the bounces stop at the depth limit
[ ok ] With no bounces left, no reflected or refracted light
[ ok ] Which medium a ray leaves and enters, through three overlapping glass balls, against the oracle
[ ok ] A refracted ray obeys Snell's law and stays in the plane of incidence
[ ok ] Past the critical angle, going out of glass, there is no refracted ray
[ ok ] Schlick's reflectance, against the oracle (five cases)
[ ok ] Further checks, independent of the code they check
[ ok ] GA refraction (rejection form) = the book's formula
[ ok ] Total deviation through a glass sphere = 2 (theta_i - theta_t) (worst error
[ ok ] Schlick stays within 0.02 of the exact Fresnel reflectance, theta_i up to 58 degrees ...
[ ok ] Mirror = same ray into the mirrored scene
checks: 12 passed, 0 failed, 0 blocked, 0 skipped, 0 not run
ALL PASSED