Last updated: 2026-11-26

17. The torus and other polynomial surfaces

For new readers

Surfaces of higher degree: the torus, a quartic, and any surface given as a polynomial in x, y and z (a heart, Barth's sextic). The ray's equation is a polynomial in t, and this page opens the two ways of finding its roots that the renderer has: isolating them with derivatives, and interval bisection. Either is enough to draw a torus; the tests ask that at least one works, and separately that the two agree.

A Torus

The book's last chapter lists directions to take a ray tracer next (area lights, spotlights, focal blur, motion blur, anti-aliasing, texture maps, normal perturbation) and leaves them open. Here the next step is a new shape, the torus, which none of the others resemble: a quadric needs a quadratic and a cube needs slabs, but a torus needs a quartic.

Step 1 — a circle, displaced and rotated

Take the tube's cross-section: a circle of radius r in the xy plane about the origin. Displace it by R along x with a translator, then rotate it about the y axis with a rotor. Sweeping the angle of the rotor carries the circle once around, and the surface it sweeps is the torus with core circle of radius R and tube radius r. Nothing implicit is involved: a point of the circle is P(φ) = (r cos φ, r sin φ, 0), and the point it becomes is

Q(θ, φ) = Rθ · T_R · P(φ) · T̃_R · R̃θ        T_R = 1 − ½ R e1 e∞,   Rθ = rotor about e2

and the circle's own outward direction (cos φ, sin φ, 0), carried by the same rotor, is the surface normal there. That gives an independent way to make points and normals of the torus, used as an oracle below.

To meet a ray with it the surface is needed as an equation. Rotating a point p about the axis until it lies in the xy half-plane puts it at (ρ, y) with ρ = |e2 ∧ p|, the length of the rejection from the axis (the same quantity as the cylinder's in Boxes, cylinders and cones), and it is on the torus when that point is on the cross-section circle: (ρ − R)² + y² = r². Clearing the square root givescf. Boxes, cylinders and cones

(|p|² + R² − r²)² = 4 R² |e2 ∧ p|²

Step 2 — the ray's quartic

Put in the ray point o + t d. Both squared lengths are quadratics in t: |p|² = A t² + 2B t + C with A = d·d, B = o·d, C = o·o, and |e2 ∧ p|² = α t² + 2β t + γ with the same three inner products taken on the rejections (perp2 and perp_dot from Boxes, cylinders and cones). With K = R² − r² the hits are the real roots of

A² t⁴ + 4AB t³ + (2A(C + K) + 4B² − 4R²α) t² + (4B(C + K) − 8R²β) t + ((C + K)² − 4R²γ) = 0

Up to four of them: a ray through the tube's cross-section and then through the hole and the far side meets the torus four times. The search is confined to the stretch where the ray is inside the torus's bounding box, which also rejects most rays at once.

The normal is the gradient of the implicit form, ((|p|² − R² − r²) x, (|p|² + K) y, (|p|² − R² − r²) z), which is the direction from the nearest point of the core circle to p (a test checks this against the explicit construction).

make a function called torus takes big, small returns s
  return list_set(new_shape("torus"), 6, [big, small])
end

make a function called torus_major takes s returns v
  return s[6][0]
end

make a function called torus_minor takes s returns v
  return s[6][1]
end

make a function called torus_bounds takes s returns b
  let e = s[6][0] + s[6][1]
  return [[0 - e, 0 - s[6][1], 0 - e], [e, s[6][1], e]]
end

# the quartic's coefficients, constant term first
make a function called torus_quartic takes s, r returns c
  let big = s[6][0]
  let small = s[6][1]
  let k = big * big - small * small
  let o = tuple_evec(r[0])
  let d = tuple_evec(r[1])
  let a = ga_vec_dot(d, d)
  let b = ga_vec_dot(o, d)
  let cc = ga_vec_dot(o, o)
  let alpha = perp2(d)
  let beta = perp_dot(o, d)
  let gamma = perp2(o)
  let r2 = 4 * big * big
  return [(cc + k) * (cc + k) - r2 * gamma, 4 * b * (cc + k) - 2 * r2 * beta, 2 * a * (cc + k) + 4 * b * b - r2 * alpha, 4 * a * b, a * a]
end

# the stretch [t_near, t_far] of the ray inside a box, or false
make a function called box_range takes b, r returns range
  let o = r[0]
  let dvec = tuple_evec(r[1])
  let tmin = 0 - infinity()
  let tmax = infinity()
  let axis = 0
  while axis < 3 do
    let range = box_axis_range(o, dvec, axis, b[0][axis], b[1][axis])
    if range.length == 0 then
      return false
    end
    if range[0] > tmin then
      let tmin = range[0]
    end
    if range[1] < tmax then
      let tmax = range[1]
    end
    let axis = axis + 1
  end
  if tmin > tmax then
    return false
  end
  return [tmin, tmax]
end

make a function called torus_local_intersect takes s, r returns xs
  let window = box_range(torus_bounds(s), r)
  if window == false then
    return []
  end
  let c = torus_quartic(s, r)
  let ts = []
  let tr = s[9]
  if tr != false and tr.torus_method == "interval" then
    let ts = poly_roots_interval_traced(c, window[0] * 1.0, window[1] * 1.0, tr)
  else
    let ts = poly_roots(c, window[0] * 1.0, window[1] * 1.0)
  end
  let xs = []
  let k = 0
  while k < ts.length do
    let xs = list_push(xs, intersection(ts[k], s))
    let k = k + 1
  end
  return xs
end

make a function called torus_local_normal takes s, p returns n
  let big = s[6][0]
  let small = s[6][1]
  let x = get_x(p)
  let y = get_y(p)
  let z = get_z(p)
  let q = x * x + y * y + z * z
  let radial = q - big * big - small * small
  return normalize(vector(radial * x, (q + big * big - small * small) * y, radial * z))
end

Step 3 — two ways to find the roots

Derivative recursion. Between two consecutive roots of a polynomial's derivative the polynomial is monotone, so it has at most one root there, and it has one exactly when its sign changes. The roots of the derivative are found the same way, one degree down, until a straight line is reached. Each bracketed root is polished by Newton's method, falling back to bisection whenever a step leaves the bracket. A tangent (double) root shows no sign change and is not reported: a ray that only grazes the surface is a miss.

Interval bisection. Evaluate the polynomial over an interval [a, b] with interval arithmetic (Horner's scheme on intervals). If the result excludes 0 there is no root in [a, b], and the interval is dropped; if the derivative's interval also excludes 0 the polynomial is monotone on [a, b] and a sign change means exactly one root; otherwise the interval is halved. No sample points are used, so no root can slip between them. These are plain floating-point intervals, without outward rounding.

make a function called poly_roots takes c0, lo, hi returns roots
  let c = poly_trim(c0)
  if c.length <= 1 then
    return []
  end
  if c.length == 2 then
    let x = 0 - c[0] / c[1]
    if x >= lo and x <= hi then
      return [x]
    end
    return []
  end
  let d = poly_deriv(c)
  let cuts = [lo]
  let crit = poly_roots(d, lo, hi)
  let k = 0
  while k < crit.length do
    let cuts = list_push(cuts, crit[k])
    let k = k + 1
  end
  let cuts = list_push(cuts, hi)
  let roots = []
  let k = 0
  while k + 1 < cuts.length do
    let a = cuts[k]
    let b = cuts[k + 1]
    let fa = poly_eval(c, a)
    let fb = poly_eval(c, b)
    if fa == 0 and k == 0 then
      let roots = list_push(roots, a)
    end
    if (fa < 0 and fb > 0) or (fa > 0 and fb < 0) then
      let roots = list_push(roots, poly_refine(c, d, a, b))
    elif fb == 0 and b > a and fa != 0 then
      let roots = list_push(roots, b)
    end
    let k = k + 1
  end
  return roots
end
# the range of p over [a, b] by Horner's scheme on intervals: [lo, hi]
make a function called iv_eval takes c, a, b returns iv
  let lo = c[c.length - 1] * 1.0
  let hi = lo
  let k = c.length - 2
  while k >= 0 do
    let p1 = lo * a
    let p2 = lo * b
    let p3 = hi * a
    let p4 = hi * b
    let nlo = p1
    let nhi = p1
    if p2 < nlo then
      let nlo = p2
    end
    if p3 < nlo then
      let nlo = p3
    end
    if p4 < nlo then
      let nlo = p4
    end
    if p2 > nhi then
      let nhi = p2
    end
    if p3 > nhi then
      let nhi = p3
    end
    if p4 > nhi then
      let nhi = p4
    end
    let lo = nlo + c[k]
    let hi = nhi + c[k]
    let k = k - 1
  end
  return [lo, hi]
end

make a function called iv_contains takes iv, v returns yes
  return iv[0] <= v and v <= iv[1]
end

make a function called poly_roots_interval takes c0, lo, hi returns roots
  return poly_roots_interval_traced(c0, lo, hi, false)
end

make a function called poly_stack_put takes stack, at, item returns stack2
  if at < stack.length then
    return list_set(stack, at, item)
  end
  return list_push(stack, item)
end

make a function called poly_sort takes xs returns out
  let out = []
  let k = 0
  while k < xs.length do
    let v = xs[k]
    let placed = []
    let inserted = false
    let j = 0
    while j < out.length do
      if not inserted and v < out[j] then
        let placed = list_push(placed, v)
        let inserted = true
      end
      let placed = list_push(placed, out[j])
      let j = j + 1
    end
    if not inserted then
      let placed = list_push(placed, v)
    end
    let out = placed
    let k = k + 1
  end
  return out
end

Step 4 — tests and oracles

  • Polynomials with known roots: six polynomials built from exact rational roots (20 roots in all) are recovered to 1e-9 by both methods; a polynomial with no real root, and a root outside the window, behave.
  • Hits with known places: for torus(1, 1/4) a ray along the x axis meets it at x = −5/4, −3/4, 3/4, 5/4 (t = 15/4, 17/4, 23/4, 25/4), a ray down the axis meets nothing, a ray down through the tube at x = R hits at y = ±r, and a ray a thousandth above the top of the tube misses while one a thousandth below hits four times.
  • Membership: for 123 rays, the points before the first hit, between hits 1 and 2, 3 and 4, and after the last are tested for being inside the solid torus ((√(x² + z²) − R)² + y² < r²) on plain coordinates; they must alternate outside, inside, outside, and every ray has an even number of hits.
  • Both root finders give the same hits on those rays, to 1e-8, and every hit satisfies the implicit equation to 1e-10.
  • The swept circle of Step 1: 63 points made by translator and rotor satisfy the equation; the carried circle direction equals the torus's normal there; and a ray starting a tenth outside along that direction and heading in hits at t = 1/10.
  • Normals are unit, point out of the solid (a small step along leaves it, a step against enters it), and equal the vector from the nearest core-circle point.
  • A transformed torus gives the same t as the plain one for the correspondingly moved ray, and a torus inside a CSG difference works like any other shape.

Step 5 — Putting it together

Two linked tori: a gold ring standing in the plane of the picture and a blue ring lying flat, each passing through the other's hole. Both are slightly reflective, and the inside of the gold ring reflects the checkered floor at a glancing angle, which shows as a fine texture.

# chapter 17: two linked tori -- a gold ring facing the camera and a blue one lying
# flat, each passing through the other's hole -- on a checkered floor
make a function called build_torus_scene returns w
  let floor_m = 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((3/10), (3/10), (3/10))), scaling((1/2), (1/2), (1/2))))
  let floor_p = set_material(plane(), floor_m)
  let gold = with_reflective(material_with(color((9/10), (7/10), (1/10)), (1/10), (6/10), (7/10), 200), (1/4))
  let blue = with_reflective(material_with(color((1/5), (3/10), (9/10)), (1/10), (6/10), (7/10), 200), (1/5))
  let ring_a = set_material(set_transform(torus(1, (3/10)), mat_mul(translation(-(3/5), (27/20), 0), rotation_x(pi() / 2))), gold)
  let ring_b = set_material(set_transform(torus(1, (3/10)), translation((2/5), (27/20), 0)), blue)
  return [[floor_p, ring_a, ring_b], demo_light(), true]
end
# Chapter 17: two linked tori. Each ray meets a torus by solving a quartic.
include "../lib/spec.patlang"
include "../lib/png.patlang"
include "../lib/camera.patlang"
include "../lib/demo_scene.patlang"

let w = build_torus_scene()
let cam = set_camera_transform(camera(400, 200, pi() / 3), view_transform(point(0, 3, -6), point(0, (6/5), 0), vector(0, 1, 0)))
render_example(cam, w, "../out/ch17_torus.png")
> tools/prender.sh examples/ch17_torus.patlang
assembled 400x200 from 40 bands
rendered with 9 parallel processes (40 bands) in 331 s wall clock
Two linked tori, one gold and one blue

Checking it independently

The recursive tracer learned the torus without any polynomial. It takes the implicit function F(p) = (|p|² + R² − r²)² − 4R²(x² + z²), samples it 600 times along the ray inside the bounding sphere, and refines every sign change by bisection; its normal is p minus the nearest point of the core circle. Every second pixel in each direction, reflections included:

> powershell.exe -NoProfile -File tools/verify_recursive.ps1 out/ch17_torus.png -Scene torus -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

Negative control: the same tracer against the Built objects: solid geometry and a Dalek image, which it should reject.

> powershell.exe -NoProfile -File tools/verify_recursive.ps1 out/ch16_csg.png -Scene torus -Stride 4
decoded by .NET: 400x200; pixels differing from the independent recursive tracer by more than 1 level: 4586 (max difference 232); stride 4 in each direction, 5000 pixels checked

The cost of each method

The same 400 rays through the unit sphere and through the torus, timed in one process (examples/ch17_methods_bench.patlang):

> cd examples && v2_interp.exe ch17_methods_bench.patlang | grep microseconds
sphere, closed form (the quadratic formula): 246 ms for 400 rays (615 microseconds each), 396 hits
sphere, derivative recursion on the quadratic: 2065 ms for 400 rays (5162 microseconds each), 396 hits
sphere, interval bisection on the quadratic: 1538 ms for 400 rays (3845 microseconds each), 396 hits
torus, derivative recursion on the quartic: 2112 ms for 400 rays (5280 microseconds each), 226 hits
torus, interval bisection on the quartic: 1438 ms for 400 rays (3595 microseconds each), 226 hits

The closed form for the sphere is far ahead. Handing even a quadratic to the generic derivative-recursion finder costs about four times as much, and interval bisection about ten times. For the quartic, derivative recursion is cheap and interval bisection is about sixty times slower: Horner's scheme on intervals over-estimates the range of the polynomial (each use of t is treated as independent), so intervals must be cut very small before they can be dismissed, and every bisection pays four interval multiplications per coefficient. The interval method does what it promises, never sampling and never skipping a root (it found the same roots as the other on every test ray), but where a direct formula or a bracketed search exists, those are the ones to use.

Implicit Surfaces and Interval Bisection

Every shape so far has its own closed form: the sphere a quadratic, the cube a slab test, the torus a quartic written out by hand. A surface given only as an equation f(x, y, z) = 0 has none. Here the equation is all there is: a ray is substituted into it, f becomes a polynomial in the ray's parameter t, and the real roots of that polynomial are the hits. The torus and other polynomial surfaces compared two ways of finding such roots; the second, interval bisection, lost on every shape that already had a closed form. This is the kind of shape it was for.

By convention f < 0 inside the solid, so the gradient points outward and CSG works with implicit shapes like any other.

Step 1 — polynomials in three variables

A polynomial is a list of terms [c, i, j, k], meaning c x^i y^j z^k. A few functions add, multiply and raise them to a power, collect like terms, differentiate and evaluate, so that a surface can be written the way it is in a textbook, as a product of factors, and expanded once. Coefficients are exact rationals.

make a function called tm_const takes c returns p
  return [[c, 0, 0, 0]]
end

make a function called tm_var takes axis returns p
  if axis == 0 then
    return [[1, 1, 0, 0]]
  end
  if axis == 1 then
    return [[1, 0, 1, 0]]
  end
  return [[1, 0, 0, 1]]
end

make a function called tm_scale takes p, c returns q
  let q = []
  let n = 0
  while n < p.length do
    let q = list_push(q, [p[n][0] * c, p[n][1], p[n][2], p[n][3]])
    let n = n + 1
  end
  return q
end

# like terms collected, zeros dropped, in a fixed order
make a function called tm_combine takes p returns q
  let top = 0
  let n = 0
  while n < p.length do
    if p[n][1] > top then
      let top = p[n][1]
    end
    if p[n][2] > top then
      let top = p[n][2]
    end
    if p[n][3] > top then
      let top = p[n][3]
    end
    let n = n + 1
  end
  let side = top + 1
  let grid = vec_new()
  let n = 0
  while n < side * side * side do
    vec_push(grid, 0)
    let n = n + 1
  end
  let n = 0
  while n < p.length do
    let at = (p[n][1] * side + p[n][2]) * side + p[n][3]
    vec_set(grid, at, vec_get(grid, at) + p[n][0])
    let n = n + 1
  end
  let q = []
  let i = 0
  while i < side do
    let j = 0
    while j < side do
      let k = 0
      while k < side do
        let c = vec_get(grid, (i * side + j) * side + k)
        if c != 0 then
          let q = list_push(q, [c, i, j, k])
        end
        let k = k + 1
      end
      let j = j + 1
    end
    let i = i + 1
  end
  return q
end

make a function called tm_add takes a, b returns q
  let all = []
  let n = 0
  while n < a.length do
    let all = list_push(all, a[n])
    let n = n + 1
  end
  let n = 0
  while n < b.length do
    let all = list_push(all, b[n])
    let n = n + 1
  end
  return tm_combine(all)
end

make a function called tm_sub takes a, b returns q
  return tm_add(a, tm_scale(b, -1))
end

make a function called tm_mul takes a, b returns q
  let all = []
  let n = 0
  while n < a.length do
    let m = 0
    while m < b.length do
      let all = list_push(all, [a[n][0] * b[m][0], a[n][1] + b[m][1], a[n][2] + b[m][2], a[n][3] + b[m][3]])
      let m = m + 1
    end
    let n = n + 1
  end
  return tm_combine(all)
end

make a function called tm_pow takes a, e returns q
  let q = tm_const(1)
  let n = 0
  while n < e do
    let q = tm_mul(q, a)
    let n = n + 1
  end
  return q
end

make a function called tm_degree takes p returns d
  let d = 0
  let n = 0
  while n < p.length do
    let t = p[n][1] + p[n][2] + p[n][3]
    if t > d then
      let d = t
    end
    let n = n + 1
  end
  return d
end

# the partial derivative with respect to x (axis 0), y (1) or z (2)
make a function called tm_deriv takes p, axis returns q
  let q = []
  let n = 0
  while n < p.length do
    let e = p[n][1 + axis]
    if e > 0 then
      let t = [p[n][0] * e, p[n][1], p[n][2], p[n][3]]
      let t = list_set(t, 1 + axis, e - 1)
      let q = list_push(q, t)
    end
    let n = n + 1
  end
  return q
end

make a function called tm_eval takes p, x, y, z returns v
  let v = 0.0
  let n = 0
  while n < p.length do
    let t = p[n]
    let v = v + t[0] * pow(x, t[1]) * pow(y, t[2]) * pow(z, t[3])
    let n = n + 1
  end
  return v
end

Step 2 — a ray in the surface

With p(t) = o + t d, each coordinate is a linear function of t: x = ox + dx t, and so on. The powers x^i are then polynomials in t of degree i, and each term of f becomes the product of three of them. Adding up the terms gives f(p(t)), a polynomial in t of the surface's degree, with exact coefficients when the ray's are exact.

The surface carries a bounding box, which doubles as the window for the roots: a surface larger than its box is cut off by it (Barth's sextic, below, runs off to infinity, so it has to be). The polynomial is built from where the ray enters the box, not from the ray's own origin; the reason is in Step 5.

The normal is the gradient of f, evaluated at the hit point.

make a function called implicit takes terms, bounds returns s
  let f = tm_combine(terms)
  let grad = [tm_deriv(f, 0), tm_deriv(f, 1), tm_deriv(f, 2)]
  return list_set(new_shape("implicit"), 6, [f, bounds, grad, tm_degree(f)])
end

# the powers 1, v, v^2, ... of the linear polynomial a + b t, as polynomials in t
make a function called ray_powers takes a, b, top returns pw
  let pw = [[1]]
  let n = 1
  while n <= top do
    let prev = pw[n - 1]
    let next = []
    let k = 0
    while k <= prev.length do
      let v = 0
      if k < prev.length then
        let v = v + a * prev[k]
      end
      if k > 0 then
        let v = v + b * prev[k - 1]
      end
      let next = list_push(next, v)
      let k = k + 1
    end
    let pw = list_push(pw, next)
    let n = n + 1
  end
  return pw
end

make a function called poly_mul takes a, b returns c
  let n = a.length + b.length - 1
  let acc = vec_new()
  let k = 0
  while k < n do
    vec_push(acc, 0)
    let k = k + 1
  end
  let i = 0
  while i < a.length do
    let ai = a[i]
    if ai != 0 then
      let j = 0
      while j < b.length do
        vec_set(acc, i + j, vec_get(acc, i + j) + ai * b[j])
        let j = j + 1
      end
    end
    let i = i + 1
  end
  return vec_to_list(acc)
end

# f(o + t d) as a polynomial in t, constant term first
make a function called implicit_ray_poly takes s, r returns c
  let f = s[6][0]
  let top = s[6][3]
  let px = ray_powers(get_x(r[0]), get_x(r[1]), top)
  let py = ray_powers(get_y(r[0]), get_y(r[1]), top)
  let pz = ray_powers(get_z(r[0]), get_z(r[1]), top)
  let acc = vec_new()
  let k = 0
  while k <= top do
    vec_push(acc, 0)
    let k = k + 1
  end
  let n = 0
  while n < f.length do
    let t = f[n]
    let prod = poly_mul(poly_mul(px[t[1]], py[t[2]]), pz[t[3]])
    let k = 0
    while k < prod.length do
      vec_set(acc, k, vec_get(acc, k) + t[0] * prod[k])
      let k = k + 1
    end
    let n = n + 1
  end
  return vec_to_list(acc)
end

make a function called implicit_local_intersect takes s, r returns xs
  let window = box_range(s[6][1], r)
  if window == false then
    return []
  end
  # the polynomial is built from where the ray enters the box, not from the ray's own
  # origin: the coordinates then stay the size of the box, and powers of them (up to the
  # surface's degree) do not bury the small value of f in rounding
  let start = window[0] * 1.0
  let c = implicit_ray_poly(s, ray(position(r, start), r[1]))
  let ts = []
  let tr = s[9]
  if tr != false and tr.implicit_method == "roots" then
    let ts = poly_roots(c, 0.0, window[1] * 1.0 - start)
  else
    let ts = poly_roots_interval_traced(c, 0.0, window[1] * 1.0 - start, tr)
  end
  let xs = []
  let k = 0
  while k < ts.length do
    let xs = list_push(xs, intersection(ts[k] + start, s))
    let k = k + 1
  end
  return xs
end

# the gradient of f: it points from inside (f < 0) to outside
make a function called implicit_local_normal takes s, p returns n
  let g = s[6][2]
  let x = get_x(p) * 1.0
  let y = get_y(p) * 1.0
  let z = get_z(p) * 1.0
  return normalize(vector(tm_eval(g[0], x, y, z), tm_eval(g[1], x, y, z), tm_eval(g[2], x, y, z)))
end

Three classic surfaces come with it:

  • Barth's sextic, 4(φ²x² − y²)(φ²y² − z²)(φ²z² − x²) − (1 + 2φ)(x² + y² + z² − 1)², of degree 6 (here φ is the rational 1597/987, within 10⁻⁶ of the golden ratio);
  • the heart, (x² + 9/4 y² + z² − 1)³ − x² z³ − 9/80 y² z³ with up turned to y, of degree 9: 22 terms once expanded;
  • the rounded block x⁴ + y⁴ + z⁴ = 1.
# Barth's sextic (65 nodes with phi = (1 + sqrt 5) / 2; here phi is the rational 1597/987,
# which is within 10^-6 of it): 4 (phi^2 x^2 - y^2)(phi^2 y^2 - z^2)(phi^2 z^2 - x^2)
# - (1 + 2 phi)(x^2 + y^2 + z^2 - 1)^2, negated so that the middle (the origin) is inside.
# The affine surface runs off to infinity, so it is always shown inside a ball.
make a function called barth_sextic returns p
  let phi = (1597/987)
  let p2 = phi * phi
  let x2 = tm_pow(tm_var(0), 2)
  let y2 = tm_pow(tm_var(1), 2)
  let z2 = tm_pow(tm_var(2), 2)
  let a = tm_sub(tm_scale(x2, p2), y2)
  let b = tm_sub(tm_scale(y2, p2), z2)
  let c = tm_sub(tm_scale(z2, p2), x2)
  let r2 = tm_sub(tm_add(tm_add(x2, y2), z2), tm_const(1))
  let prod = tm_scale(tm_mul(tm_mul(a, b), c), 4)
  let ball = tm_scale(tm_mul(r2, r2), 1 + 2 * phi)
  return tm_sub(prod, ball)
end

# the "heart": (x^2 + 9/4 y^2 + z^2 - 1)^3 - x^2 z^3 - 9/80 y^2 z^3, with the usual
# axes (the heart's up is z) turned so that its up is y: (x, y, z) -> (x, -z, y).
make a function called heart_surface returns p
  let x2 = tm_pow(tm_var(0), 2)
  let up = tm_var(1)
  let depth = tm_scale(tm_var(2), -1)
  let y2 = tm_pow(depth, 2)
  let z3 = tm_pow(up, 3)
  let z2 = tm_pow(up, 2)
  let inner = tm_sub(tm_add(tm_add(x2, tm_scale(y2, (9/4))), z2), tm_const(1))
  let cube = tm_pow(inner, 3)
  let a = tm_mul(x2, z3)
  let b = tm_scale(tm_mul(y2, z3), (9/80))
  return tm_sub(tm_sub(cube, a), b)
end

# the rounded block x^4 + y^4 + z^4 = 1
make a function called quartic_surface returns p
  return [[1, 4, 0, 0], [1, 0, 4, 0], [1, 0, 0, 4], [-1, 0, 0, 0]]
end

Step 3 — two root finders, one of them made affordable

The torus and other polynomial surfaces's two methods are used unchanged: the roots of the derivatives, and interval bisection. Bisection takes the polynomial over an interval [a, b], bounds it by evaluating Horner's scheme in interval arithmetic, and drops the interval if the bound excludes zero. If the bound of the derivative also excludes zero, the polynomial is monotone there and a sign change means exactly one root; otherwise the interval is halved. Nothing is sampled, so a thin sheet cannot slip between sample points.monotone means strictly rising or falling

# the range of p over [a, b] by Horner's scheme on intervals: [lo, hi]
make a function called iv_eval takes c, a, b returns iv
  let lo = c[c.length - 1] * 1.0
  let hi = lo
  let k = c.length - 2
  while k >= 0 do
    let p1 = lo * a
    let p2 = lo * b
    let p3 = hi * a
    let p4 = hi * b
    let nlo = p1
    let nhi = p1
    if p2 < nlo then
      let nlo = p2
    end
    if p3 < nlo then
      let nlo = p3
    end
    if p4 < nlo then
      let nlo = p4
    end
    if p2 > nhi then
      let nhi = p2
    end
    if p3 > nhi then
      let nhi = p3
    end
    if p4 > nhi then
      let nhi = p4
    end
    let lo = nlo + c[k]
    let hi = nhi + c[k]
    let k = k - 1
  end
  return [lo, hi]
end

make a function called iv_contains takes iv, v returns yes
  return iv[0] <= v and v <= iv[1]
end

make a function called poly_roots_interval takes c0, lo, hi returns roots
  return poly_roots_interval_traced(c0, lo, hi, false)
end

Used as it was in The torus and other polynomial surfaces it was about 80 times slower than the derivative method on the shapes of this page (85 ms a ray for Barth's sextic, in the table below). Two refinements bring it level, and each is a small fix to a real defect:

  1. A far origin. A polynomial in t for a ray that starts four units from the shape has its roots near t = 4, and in the expanded form (t − 4)⁴ = t⁴ − 16 t³ + … every term is large while the sum is small. Interval arithmetic cannot know the terms cancel, so the bound is wide, and the bisection keeps halving intervals that contain no root. Seen from the middle of the window instead (poly_shift, a Taylor shift by repeated synthetic division), the terms are small and the bound is tight.
  2. The mean-value form. Over [a, b] with midpoint m, p(t) lies within p(m) ± max|p'| · (b − a)/2. Its excess shrinks with the square of the width, the Horner bound's with the width, and it matters near a tangent ray, where the Horner bound needs ever narrower intervals to exclude zero: the work there grows like one over the square root of the tolerance.
# the coefficients of p(u + s), i.e. p seen from a new origin at t = s (repeated
# synthetic division)
make a function called poly_shift takes c, s returns q
  let n = c.length - 1
  let w = vec_new()
  let k = 0
  while k <= n do
    vec_push(w, c[k])
    let k = k + 1
  end
  let i = 0
  while i < n do
    let j = n - 1
    while j >= i do
      vec_set(w, j, vec_get(w, j) + s * vec_get(w, j + 1))
      let j = j - 1
    end
    let i = i + 1
  end
  return vec_to_list(w)
end

What each is worth, on 400 rays through Barth's sextic (the polynomial taken from the ray's own origin, so the first refinement has something to do), and on one ray that nearly grazes the heart:

> v2_interp.exe examples/ch20_interval_bench.patlang
Barth's sextic, 400 rays
  Horner bound, ray origin     : 1895512 interval evaluations, 1423882 microseconds per ray, 704 hits
  + mean-value form            : 102096 interval evaluations, 114932 microseconds per ray, 704 hits
  + centred on the window      : 10588 interval evaluations, 47332 microseconds per ray, 704 hits
  both                         : 8268 interval evaluations, 46645 microseconds per ray, 704 hits
one near-tangent ray: interval evaluations at tolerance 1e-3, 1e-5, 1e-7, 1e-9
  Horner bound only   243  2763  31187  249407
  with mean-value     195  995  4901  8127

Used together they cost about 1 ms a ray, the same as the derivative method, and the interval method keeps its character: it examines every part of the window.

Neither method reports a multiple root, where the polynomial only touches zero or flattens as a cube. A ray that passes exactly through such a point is dropped by bisection; the derivative method reports it with an error of about a millionth, which is as good as a triple root can be located in floating point.

Step 4 — scenarios and oracles

  • Surfaces with known answers. The unit sphere as x² + y² + z² − 1: the ray's polynomial from (0, 0, −5) is t² − 10 t + 24, and 40 rays give the Rays, spheres and planes sphere's t values. The torus as its expanded quartic gives the torus's hits on 30 rays and the same normals at 12 points. For x⁴ + y⁴ + z⁴ = 1, along an axis the hits are at ±1, and along (1, 1, 1) at 3^(−1/4) per coordinate.
  • Thin sheets: z² = 1/10000, two faces 0.02 apart, are both found by both methods.
  • The methods agree on 120 rays through Barth's sextic.
  • The window clips: a sphere of radius 2 in a box of half-width 1 has no hits.
  • In a scene: translated, stretched, turned on its edge in a group, and as an operand of a CSG difference (the rounded block minus a ball: four hits where the ray enters the block, leaves it into the ball, comes out the far side and leaves the block).
  • Precision: the heart seen from 8 units away, where f is nearly flat: every hit point satisfies f = 0 to within 10⁻¹¹.
  • The hard ray: in the heart's plane of symmetry f is a perfect cube, so the polynomial has two triple roots. It settles in a few thousand interval evaluations, and bisection reports no hit that is not there.
  • Negative control: a sphere with r² = 1.01 gives different hits.

Step 5 — Putting it together

A checkered floor and a back wall, the heart (red, a little reflective), Barth's sextic cut to a ball by a CSG intersection (blue), and the rounded block with a ball taken out of its front by a CSG difference (gold):

# chapter 20: three implicit surfaces on a checkered floor in front of a wall: a heart
# (a degree 9 polynomial), Barth's sextic cut to a ball, and the rounded block
# x^4 + y^4 + z^4 = 1 dished by a ball (a CSG difference with an implicit operand)
make a function called build_implicit_scene returns w
  let floor_m = 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((3/10), (3/10), (3/10))), scaling((1/2), (1/2), (1/2))))
  let floor_p = set_material(plane(), floor_m)
  let back = set_material(set_transform(plane(), mat_mul(translation(0, 0, 4), rotation_x(pi() / 2))), material_with(color((8/10), (8/10), (9/10)), (1/10), (9/10), 0, 200))
  let heart_m = with_reflective(material_with(color((9/10), (1/10), (1/10)), (1/10), (7/10), (6/10), 150), (1/10))
  let heart = set_material(implicit(heart_surface(), [[(-13/10), (-11/10), (-8/10)], [(13/10), (13/10), (8/10)]]), heart_m)
  let heart = set_transform(heart, mat_mul(translation(-(5/2), (9/10), 0), mat_mul(rotation_y((1/5)), scaling((9/10), (9/10), (9/10)))))
  let barth_m = with_reflective(material_with(color((1/5), (3/10), (9/10)), (1/10), (7/10), (6/10), 150), (1/10))
  let barth = csg("intersection", implicit(barth_sextic(), [[(-8/5), (-8/5), (-8/5)], [(8/5), (8/5), (8/5)]]), sphere())
  let barth = with_material_deep(set_transform(barth, mat_mul(translation(0, (23/20), 0), scaling((9/10), (9/10), (9/10)))), barth_m)
  let gold = with_reflective(material_with(color((9/10), (7/10), (1/10)), (1/10), (6/10), (7/10), 200), (1/5))
  let block = implicit(quartic_surface(), [[(-11/10), (-11/10), (-11/10)], [(11/10), (11/10), (11/10)]])
  let dish = csg("difference", block, set_transform(sphere(), mat_mul(translation(0, 0, -(6/5)), scaling((9/10), (9/10), (9/10)))))
  let dish = with_material_deep(set_transform(dish, mat_mul(translation((5/2), (4/5), 0), mat_mul(rotation_y((4/10)), scaling((4/5), (4/5), (4/5))))), gold)
  return [[floor_p, back, heart, barth, dish], demo_light(), true]
end
> v2_interp.exe examples/ch20_implicit_bench.patlang
sphere (4 terms, degree 2): build 1535 us, interval 5022 us total, roots 3675 us total, 704 hits
x4+y4+z4=1 (4 terms, degree 4): build 4637 us, interval 7070 us total, roots 5885 us total, 782 hits
Barth sextic (17 terms, degree 6): build 34927 us, interval 24197 us total, roots 23580 us total, 704 hits
A heart, Barth's sextic and a dished block

The fine speckle on the heart's underside is the checkered floor in its mirror: the surface bends so quickly there that neighbouring pixels reflect different squares.

A bug the picture found

The first render had dark specks scattered over the heart. A shadow ray from one of them met the heart itself 0.0016 along. The hit point was 3 · 10⁻⁴ inside the surface: the gradient there is only 4 · 10⁻⁵, so a point that is off the surface by 10⁻⁸ in f is hundreds of times the shadow-ray offset away in space. The error was not the root finder but the polynomial: built from the camera, coordinates near 8 raised to the sixth power swamp the small value of f in rounding. Building it from where the ray enters the bounding box keeps the numbers the size of the box, and the heart's hit points now lie on the surface to within 10⁻¹¹ in f (10⁻¹⁵ at the point that showed the fault; the Precision scenario above). That change is also why a ray costs less than it did.

Checking it independently

The recursive tracer reads the scene from the exporter of Built objects: solid geometry and a Dalek. For an implicit surface it receives the terms, evaluates f directly from them at sample points along the ray inside the box (no expansion in t, no interval arithmetic) with a sign change refined by bisection, and takes the normal from a central difference of f. The checkered pattern is exported with the shape.

> v2_interp.exe tools/export_scene.patlang --scene implicit --out out/implicit_scene.txt
wrote out/implicit_scene.txt (9 shapes)
> powershell.exe -NoProfile -File tools/verify_recursive.ps1 out/ch20_implicit.png -SceneFile out/implicit_scene.txt -Stride 4
decoded by .NET: 400x200; pixels differing from the independent recursive tracer by more than 1 level: 0 (max difference 0); stride 4 in each direction, 5000 pixels checked

Negative control: the same picture against the Dalek's scene:

> powershell.exe -NoProfile -File tools/verify_recursive.ps1 out/ch20_implicit.png -SceneFile out/dalek_front.txt -Stride 8
decoded by .NET: 400x200; pixels differing from the independent recursive tracer by more than 1 level: 1250 (max difference 182); stride 8 in each direction, 1250 pixels checked

How it is checked

> v2_interp.exe tests/run.patlang --node shapes/torus --depth 2
[ ok ] Tori
[ ok ]   Along a diameter, four hits; normals on the outside and the top
[ ok ]   Finding the roots of the quartic  (any one of)
[ ok ]     By isolating roots with derivatives
[ ok ]     By interval bisection
[ ok ]   The two root finders agree to 1e-9
[ ok ]   Turned, stretched and moved
[ ok ]     Every hit lies on the surface
[ ok ]     No crossing of the surface is missed
[ ok ]     Normals follow the gradient of the surface's function
[ ok ]   The torus, further
[ ok ]     Roots of polynomials
[ ok ]     The torus
checks: 17 passed, 0 failed, 0 blocked, 0 skipped, 0 not run
ALL PASSED
> v2_interp.exe tests/run.patlang --node shapes/implicit --depth 2
[ ok ] Polynomial surfaces
[ ok ]   Implicit surfaces
[ ok ]     A polynomial seen from a new origin: (t - 4)^4 shifted by 4 is u^4
[ ok ]     The ray's polynomial for the unit sphere from (0,0,-5) is t^2 - 10 t + 24, exactly
[ ok ]     40 rays: the implicit unit sphere gives the Chapter 5 sphere's t values
[ ok ]     The torus as an expanded quartic
[ ok ]     Normal of the implicit sphere at (0.6, 0.8, 0): the radius direction
[ ok ]     Interval bisection finds both faces of a sheet 0.02 thick (t = 2.99, 3.01)
[ ok ]     Barth's sextic: interval bisection and the derivative finder agree on 120 rays
[ ok ]     A sphere of radius 2 in a box of half-width 1: its surface is outside the box, no hits
[ ok ]     Translated by 2: the same two hits for a ray through the new centre
[ ok ]     Heart from 8 units away
[ ok ]     A near-tangent ray settles in
[ ok ]     Negative control: r^2 = 1.01 instead of 1 moves the hits (the comparison would notice)
checks: 12 passed, 0 failed, 0 blocked, 0 skipped, 0 not run
ALL PASSED