Last updated: 2026-11-26
18. Surfaces of any function
For new readers
Surfaces of any function, not just polynomials: ripples, a gyroid, a rounded block. The function is compiled to a tape and evaluated on intervals, so the search can rule out whole stretches of a ray at once. On top of that come warps (twist, taper, bend), smooth joins and shells, which let built objects be deformed. The meadow's ground in the film is one of these surfaces; the expressions are typed as text, on their own page.
Surfaces of Any Function, by Interval Bisection
The torus and other polynomial surfaces solved f(x, y, z) = 0 for a polynomial f: along a ray it becomes a polynomial in
t, and its roots can be bracketed exactly. A function with a sin, a sqrt, an abs or a quotient
in it is not a polynomial in t, so its roots have to be hunted. The torus and other polynomial surfaces compared two ways to find
roots and The torus and other polynomial surfaces gave interval bisection its job: there it only had to match a method that already
worked. Here it is the only one that does.
The idea
Evaluate f not at a point but over a box, with interval arithmetic: the answer is an interval that
is certain to hold every value f takes in the box. Along a ray, a stretch [a, b] of t covers a
small box of x, y, z; if the interval for f over it excludes 0, the stretch has no root and is
dropped, with no sampling and no way for a thin sheet to slip between samples. If it does not, then
look at the slope: the derivative of f along the ray, bounded the same way. If that interval excludes
0 too, f is monotone on the stretch, so it has a root exactly when its two ends differ in sign, and a
bracketed Newton finds it in a handful of steps. Otherwise the stretch is cut in half.
The expression tree and the tape
A function is a tree of numbers, x, y, z, + − * /, whole powers, sin cos exp log sqrt abs atan, and min, max. The builders fold constants and drop 0s and 1s as they go. The tree is then
flattened to a tape: a list of instructions, instruction i leaving its result in register i, and
equal subtrees compiled once, so (x + y)(x + y) is four instructions, not seven. A function built by
substituting one expression into another, as Surfaces of any function does, shares most of its subtrees, and the tape
pays for each once.
One evaluator for values, intervals and slopes
fa_run takes each of x, y and z as [value low, value high, derivative low, derivative high]
and gives the result in the same form. The derivative is the one along the ray: the seeds of x,
y, z are the components of the ray's direction. With degenerate intervals it is the ordinary
evaluation with a derivative beside it (forward-mode differentiation); with a box it is a bound on the
value and the slope. The gradient for a normal is three runs with the seeds (1,0,0), (0,1,0),
(0,0,1). There is no separate code for derivatives of the tree, and nothing to get out of step with
the evaluator.
Some care in the arithmetic: 0 × ∞ is 0, not not-a-number; division by an interval that holds 0
is all the reals; sqrt drops the part of its argument below 0; sin and cos of an interval take
their extremes, ±1, whenever the interval holds a top or a bottom, and are [−1, 1] over a whole turn;
x^2 over [−3, 2] is [0, 9] where x × x would be [−6, 9]; abs over an interval that holds 0
has the slope [−1, 1]; min and max take the slope of whichever operand wins over the whole box,
and the hull of both where neither does.
make a function called fa_num takes v returns a
return ["num", v]
end
make a function called fa_var takes axis returns a
return ["var", axis]
end
make a function called fa_is_num takes a, v returns yes
return a[0] == "num" and a[1] == v
end
make a function called fa_neg takes a returns b
if a[0] == "num" then
return ["num", 0 - a[1]]
end
if a[0] == "neg" then
return a[1]
end
return ["neg", a]
end
make a function called fa_add takes a, b returns c
if a[0] == "num" and b[0] == "num" then
return ["num", a[1] + b[1]]
end
if fa_is_num(a, 0) then
return b
end
if fa_is_num(b, 0) then
return a
end
return ["add", a, b]
end
make a function called fa_sub takes a, b returns c
if a[0] == "num" and b[0] == "num" then
return ["num", a[1] - b[1]]
end
if fa_is_num(b, 0) then
return a
end
if fa_is_num(a, 0) then
return fa_neg(b)
end
return ["sub", a, b]
end
make a function called fa_mul takes a, b returns c
if a[0] == "num" and b[0] == "num" then
return ["num", a[1] * b[1]]
end
if fa_is_num(a, 0) or fa_is_num(b, 0) then
return ["num", 0]
end
if fa_is_num(a, 1) then
return b
end
if fa_is_num(b, 1) then
return a
end
if fa_is_num(a, -1) then
return fa_neg(b)
end
if fa_is_num(b, -1) then
return fa_neg(a)
end
return ["mul", a, b]
end
make a function called fa_div takes a, b returns c
if a[0] == "num" and b[0] == "num" and b[1] != 0 then
return ["num", a[1] / b[1]]
end
if fa_is_num(b, 1) then
return a
end
return ["div", a, b]
end
# a to the whole power n
make a function called fa_pow takes a, n returns b
if n == 0 then
return ["num", 1]
end
if n == 1 then
return a
end
if a[0] == "num" then
let v = 1
let k = 0
while k < n do
let v = v * a[1]
let k = k + 1
end
return ["num", v]
end
return ["powi", a, n]
end
make a function called fa_fn takes name, a returns b
if a[0] == "num" then
let v = a[1]
if name == "sin" then
return ["num", sin(v)]
end
if name == "cos" then
return ["num", cos(v)]
end
if name == "exp" then
return ["num", exp(v)]
end
if name == "abs" then
return ["num", abs(v)]
end
if name == "atan" then
return ["num", atan(v)]
end
if name == "sqrt" and v >= 0 then
return ["num", sqrt(v)]
end
if name == "log" and v > 0 then
return ["num", log(v)]
end
end
return ["fn", name, a]
end
make a function called fa_min takes a, b returns c
if a[0] == "num" and b[0] == "num" then
return ["num", num_min(a[1], b[1])]
end
return ["min", a, b]
end
make a function called fa_max takes a, b returns c
if a[0] == "num" and b[0] == "num" then
return ["num", num_max(a[1], b[1])]
end
return ["max", a, b]
end
# the tree of a polynomial given as terms [c, i, j, k] (Chapter 20)
make a function called fa_from_poly takes terms returns a
let sum = ["num", 0]
let n = 0
while n < terms.length do
let t = terms[n]
let m = fa_mul(fa_mul(fa_pow(fa_var(0), t[1]), fa_pow(fa_var(1), t[2])), fa_pow(fa_var(2), t[3]))
let sum = fa_add(sum, fa_mul(["num", t[0]], m))
let n = n + 1
end
return sum
end
# the reference evaluator: plain recursion on floats
make a function called fa_eval takes a, x, y, z returns v
let op = a[0]
if op == "num" then
return a[1]
end
if op == "var" then
if a[1] == 0 then
return x
end
if a[1] == 1 then
return y
end
return z
end
if op == "add" then
return fa_eval(a[1], x, y, z) + fa_eval(a[2], x, y, z)
end
if op == "sub" then
return fa_eval(a[1], x, y, z) - fa_eval(a[2], x, y, z)
end
if op == "mul" then
return fa_eval(a[1], x, y, z) * fa_eval(a[2], x, y, z)
end
if op == "div" then
return fa_eval(a[1], x, y, z) / fa_eval(a[2], x, y, z)
end
if op == "neg" then
return 0 - fa_eval(a[1], x, y, z)
end
if op == "powi" then
let b = fa_eval(a[1], x, y, z)
let v = 1.0
let k = 0
while k < a[2] do
let v = v * b
let k = k + 1
end
return v
end
if op == "min" then
return num_min(fa_eval(a[1], x, y, z), fa_eval(a[2], x, y, z))
end
if op == "max" then
return num_max(fa_eval(a[1], x, y, z), fa_eval(a[2], x, y, z))
end
let b = fa_eval(a[2], x, y, z)
let name = a[1]
if name == "sin" then
return sin(b)
end
if name == "cos" then
return cos(b)
end
if name == "exp" then
return exp(b)
end
if name == "log" then
return log(b)
end
if name == "sqrt" then
return sqrt(b)
end
if name == "abs" then
return abs(b)
end
return atan(b)
end
# opcodes: 0 number, 1 variable, 4 add, 5 sub, 6 mul, 7 div, 8 neg, 9 power, 10 sin, 11 cos,
# 12 exp, 13 log, 14 sqrt, 15 abs, 16 min, 17 max, 18 atan
make a function called fa_fn_code takes name returns code
if name == "sin" then
return 10
end
if name == "cos" then
return 11
end
if name == "exp" then
return 12
end
if name == "log" then
return 13
end
if name == "sqrt" then
return 14
end
if name == "abs" then
return 15
end
return 18
end
make a function called fa_emit takes a, ins, seen returns reg
let op = a[0]
let code = 0
let ra = 0
let rb = 0
let k = 0
let key = ""
if op == "num" then
let code = 0
let k = a[1]
let key = "n|" + k
elif op == "var" then
let code = 1
let ra = a[1]
let key = "v|" + ra
elif op == "neg" then
let code = 8
let ra = fa_emit(a[1], ins, seen)
let key = "g|" + ra
elif op == "powi" then
let code = 9
let ra = fa_emit(a[1], ins, seen)
let k = a[2]
let key = "p|" + ra + "|" + k
elif op == "fn" then
let code = fa_fn_code(a[1])
let ra = fa_emit(a[2], ins, seen)
let key = "f|" + code + "|" + ra
else
let rl = fa_emit(a[1], ins, seen)
let rr = fa_emit(a[2], ins, seen)
let ra = rl
let rb = rr
if op == "add" then
let code = 4
elif op == "sub" then
let code = 5
elif op == "mul" then
let code = 6
elif op == "div" then
let code = 7
elif op == "min" then
let code = 16
else
let code = 17
end
let key = "b|" + code + "|" + ra + "|" + rb
end
let known = get(seen, key)
if known != unit then
return known
end
vec_push(ins, [code, ra, rb, k])
let reg = vec_len(ins) - 1
send(seen, "set", key, reg)
return reg
end
make a function called fa_zero_vec takes n returns v
let v = vec_new()
let k = 0
while k < n do
vec_push(v, 0.0)
let k = k + 1
end
return v
end
# [instructions, number of registers, the output register]. A tape is a list, and so is shared
# by every thread that renders the surface; the registers a run computes in are made by the
# one asking (fa_registers).
make a function called fa_compile takes ast returns tape
let ins = vec_new()
let out = fa_emit(ast, ins, new("TapeKeys"))
let n = vec_len(ins)
return [vec_to_list(ins), n, out]
end
make a function called fa_tape_length takes tape returns n
return tape[1]
end
# the product of two intervals; 0 times infinity is 0
make a function called ia_mul takes al, ah, bl, bh returns iv
let p1 = al * bl
let p2 = al * bh
let p3 = ah * bl
let p4 = ah * bh
let s = p1 + p2 + p3 + p4
if s != s then
let p1 = 0
if al != 0 and bl != 0 then
let p1 = al * bl
end
let p2 = 0
if al != 0 and bh != 0 then
let p2 = al * bh
end
let p3 = 0
if ah != 0 and bl != 0 then
let p3 = ah * bl
end
let p4 = 0
if ah != 0 and bh != 0 then
let p4 = ah * bh
end
end
let lo = p1
let hi = p1
if p2 < lo then
let lo = p2
end
if p3 < lo then
let lo = p3
end
if p4 < lo then
let lo = p4
end
if p2 > hi then
let hi = p2
end
if p3 > hi then
let hi = p3
end
if p4 > hi then
let hi = p4
end
return [lo, hi]
end
make a function called ia_sin takes l, h returns iv
let two_pi = 8 * atan(1)
let half = 2 * atan(1)
if h - l >= two_pi then
return [-1, 1]
end
let sl = sin(l)
let sh = sin(h)
let lo = num_min(sl, sh)
let hi = num_max(sl, sh)
# the top, 1 at pi/2 + 2 pi k, and the bottom, -1 at -pi/2 + 2 pi k, if either is inside
let kt = 0 - floor(0 - (l - half) / two_pi)
if half + two_pi * kt <= h then
let hi = 1
end
let kb = 0 - floor(0 - (l + half) / two_pi)
if 0 - half + two_pi * kb <= h then
let lo = -1
end
return [lo, hi]
end
make a function called ia_cos takes l, h returns iv
let half = 2 * atan(1)
return ia_sin(l + half, h + half)
end
make a function called fa_ipow takes v, n returns p
let p = 1.0
let k = 0
while k < n do
let p = p * v
let k = k + 1
end
return p
end
# the whole power n >= 1 of an interval
make a function called ia_pow takes l, h, n returns iv
if n % 2 == 1 then
return [fa_ipow(l, n), fa_ipow(h, n)]
end
if l >= 0 then
return [fa_ipow(l, n), fa_ipow(h, n)]
end
if h <= 0 then
return [fa_ipow(h, n), fa_ipow(l, n)]
end
return [0.0, num_max(fa_ipow(l, n), fa_ipow(h, n))]
end
# the 1/b of an interval that does not hold 0
make a function called ia_inv takes l, h returns iv
return [1 / h, 1 / l]
end
make a function called fa_run takes tape, xi, yi, zi, want_d returns res
return fa_run_in(tape, fa_registers(tape), xi, yi, zi, want_d)
end
# the value and the three partial derivatives at a point, by three runs with the seeds
# (1, 0, 0), (0, 1, 0) and (0, 0, 1)
make a function called fa_gradient takes tape, x, y, z returns g
let regs = fa_registers(tape)
let gx = fa_run_in(tape, regs, [x, x, 1.0, 1.0], [y, y, 0.0, 0.0], [z, z, 0.0, 0.0], true)
let gy = fa_run_in(tape, regs, [x, x, 0.0, 0.0], [y, y, 1.0, 1.0], [z, z, 0.0, 0.0], true)
let gz = fa_run_in(tape, regs, [x, x, 0.0, 0.0], [y, y, 0.0, 0.0], [z, z, 1.0, 1.0], true)
return [gx[2], gy[2], gz[2]]
end
# f and df/dt at the parameter t of the ray (o, d): [f, f']
make a function called fa_point takes tape, regs, ox, oy, oz, dx, dy, dz, t returns fd
let x = ox + dx * t
let y = oy + dy * t
let z = oz + dz * t
let r = fa_run_in(tape, regs, [x, x, dx, dx], [y, y, dy, dy], [z, z, dz, dz], true)
return [r[0], r[2]]
end
# the root of a monotone stretch [a, b] whose ends have values fa and fb of opposite sign (or
# zero): a Newton step wherever it stays inside the bracket, bisection where not
make a function called fa_refine takes tape, regs, ox, oy, oz, dx, dy, dz, a, b, fa, fb returns t
if fa == 0 then
return a
end
if fb == 0 then
return b
end
let lo = a
let hi = b
let flo = fa
let t = (a + b) / 2
let k = 0
while k < 100 do
let fd = fa_point(tape, regs, ox, oy, oz, dx, dy, dz, t)
let f = fd[0]
if f == 0 then
return t
end
if (f < 0) == (flo < 0) then
let lo = t
let flo = f
else
let hi = t
end
let next = (lo + hi) / 2
if fd[1] != 0 then
let step = t - f / fd[1]
if step > lo and step < hi then
let next = step
end
end
if abs(next - t) <= 0.0000000000001 * (1 + abs(t)) then
return next
end
let t = next
let k = k + 1
end
return t
end
# the values of t in [t0, t1] where f(o + t d) = 0, in order
make a function called fa_roots takes tape, ox, oy, oz, dx, dy, dz, t0, t1 returns ts
return fa_roots_counted(tape, ox, oy, oz, dx, dy, dz, t0, t1)[0]
end
make a function called list_pop takes xs returns ys
let ys = []
let k = 0
while k < xs.length - 1 do
let ys = list_push(ys, xs[k])
let k = k + 1
end
return ys
end
# a list of numbers, ascending (merge sort)
make a function called fa_sort takes xs returns ys
if xs.length <= 1 then
return xs
end
let mid = floor(xs.length / 2)
let left = []
let right = []
let i = 0
while i < xs.length do
if i < mid then
let left = list_push(left, xs[i])
else
let right = list_push(right, xs[i])
end
let i = i + 1
end
let a = fa_sort(left)
let b = fa_sort(right)
let out = []
let i = 0
let j = 0
while i < a.length or j < b.length do
if j >= b.length or (i < a.length and a[i] <= b[j]) then
let out = list_push(out, a[i])
let i = i + 1
else
let out = list_push(out, b[j])
let j = j + 1
end
end
return out
end
# params: [tree, bounds, tape, the text it was typed as (or false)]; f < 0 is inside
make a function called function_surface takes ast, bounds returns s
return list_set(new_shape("function"), 6, [ast, bounds, fa_compile(ast), false])
end
make a function called function_local_intersect takes s, r returns xs
let window = box_range(s[6][1], r)
if window == false then
return []
end
# work from where the ray enters the box, so that t stays small
let start = window[0] * 1.0
let o = position(r, start)
let found = fa_roots_counted(s[6][2], get_x(o) * 1.0, get_y(o) * 1.0, get_z(o) * 1.0, get_x(r[1]) * 1.0, get_y(r[1]) * 1.0, get_z(r[1]) * 1.0, 0.0, window[1] * 1.0 - start)
let ts = found[0]
let tr = s[9]
if tr != false then
if tr.counting then
tr.ifunc_steps = found[1]
end
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, pointing from inside (f < 0) to outside
make a function called function_local_normal takes s, p returns n
let g = fa_gradient(s[6][2], get_x(p) * 1.0, get_y(p) * 1.0, get_z(p) * 1.0)
let len = sqrt(g[0] * g[0] + g[1] * g[1] + g[2] * g[2])
if len == 0 then
return vector(0, 1, 0)
end
return vector(g[0] / len, g[1] / len, g[2] / len)
end
What it does not find, and what it will not be fooled by
- A touch, a double root where
fcomes down to 0 and goes back up, is not found: there is no sign change. That is how The torus and other polynomial surfaces's bisection behaves too. - A pole,
1/x − 1atx = 0, changes sign but is not a root. A stretch that cannot be cut further and whose bound is infinite holds a singularity; a monotone stretch's root is checked by the value found, which at a pole is enormous. - A function that is
0over a whole region has no isolated roots and nothing to cut. A single ray is cut off afterifunc_limit(100 000) stretches, so it cannot hang a render. - Floating point has no directed rounding here, so a bound can be wrong by the last bit; the tests (below) look for what that would break, and have not found it.
Scenarios and oracles
- The tape against the reference. A plain recursive evaluator, the reference, against the tape at points: 18 expressions, one for each operation and some mixtures, 40 points each.
- Soundness of the intervals. For 450 random boxes (boxes of ray, with random directions), the value at 20 random points of the stretch is inside the interval, and so is a central-difference derivative along the ray inside the derivative interval: 9 000 samples, 18 expressions.
- Ranges at the edges.
sinover[0, 7], roundπ/2, throughπ, through−π/2;cosround 0 and throughπ;0times[−∞, ∞];1 / [−1, 1];1 / [2, 4];sqrtover[−1, 4];x²againstx × x;abs. - The tape. A shared subtree is compiled once; the gradient of
x²y + sin zby three runs is(2xy, x², cos z). - The solver against primitives. The sphere written
sqrt(x² + y² + z²) − 1, the cube asmax(|x|, |y|, |z|) − 1and a capped cylinder withsqrt,absandmaxgive, to 10⁻⁶, the hits of the sphere, cube and cylinder primitives on 40 rays each. - The solver against a search that shares nothing with it. On two surfaces with no closed form
(the wave
y = 0.3 sin 3x, and a sphere with ripplesr = 1 + 0.15 sin 7x sin 5y sin 6z) 50 rays each are searched by marching in steps of 0.002 and bisecting each sign change: the same hits, to 10⁻⁵. - Special cases. A sheet 0.002 thick (both faces); the pole of
1/x − 1; a miss of the box; a miss of the surface. - A shape. Normal from the gradient equal to the sphere primitive's; a transformation; a CSG intersection with a cube equal to sphere ∩ cube on 12 rays.
- Negative control: radius 1.1 enters 0.1 earlier than radius 1.
Functions typed as text
Surfaces typed as text's language gains the functions sin cos tan exp log sqrt abs atan (one argument) and
min max (two), division by anything, and a script that uses any of them is read as a tree instead of
a polynomial; a script that uses none is still the exact polynomial of Surfaces typed as text, and the exact
solver. The two readings are the same parser with a different algebra underneath.cf. Surfaces typed as text
- A text with functions is compared at 100 random points with the formula as PatLang arithmetic, for eight
texts that between them use every function and operator; precedence is kept (
2 sin(x) + 1,-sin(x)^2);min(x),sin(x, y)and an unclosedmin(x, yare errors; an unknown function is an unknown name;sin(2)has nox,yorz. sqrt(x^2 + y^2 + z^2) = 1typed as text hits where the sphere primitive does on 30 rays; andy - 0.3 sin(3x)typed as text agrees with the dense march.
The polynomial surfaces of Surfaces typed as text and everything before still pass:
What it costs
A ray through each of three surfaces, 100 rays each, and how many stretches of t the solver
looked at (including the ones it dropped at once):
> v2_interp.exe examples/ch27_interval_bench.patlang
sphere, sqrt(x^2 + y^2 + z^2) - 1: 9.2 ms a ray, 5 interval stretches a ray, 200 hits
rippled sphere: 38.9 ms a ray, 12 interval stretches a ray, 200 hits
wavy slab, y - 0.3 sin 3x: 1.3 ms a ray, 1 interval stretches a ray, 3 hits
That is a sphere about as dear as The torus and other polynomial surfaces's polynomial path (1 ms), the ripples several times that, and a picture of a few such surfaces a minute or two on 20 cores.
Putting it together
A sphere with ripples (r − 1 − 0.12 sin(7x) sin(5y) sin(6z)), a gyroid cut to a ball
(sin kx cos ky + sin ky cos kz + sin kz cos kx, k = 3, with max(g, r − 2.2)) and a torus with
ridges, each typed as text:
# chapter 27: surfaces of functions that are not polynomials, typed as text and found by interval
# bisection: a sphere with ripples, a gyroid cut to a ball (sin x cos y + sin y cos z + sin z cos x),
# and a torus with ridges, on a checkered floor
make a function called build_function_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 ripple_text = "r = sqrt(x^2 + y^2 + z^2)" + chr(10) + "shape = r - 1 - 0.12 sin(7x) sin(5y) sin(6z)"
let ripple = surface_from_text_in(ripple_text, [[-(3/2), -(3/2), -(3/2)], [(3/2), (3/2), (3/2)]])
let ripple = set_material(set_transform(ripple, translation(-(5/2), (23/20), 0)), with_reflective(material_with(color((9/10), (1/5), (1/5)), (1/10), (7/10), (6/10), 150), (1/10)))
let gyroid_text = "k = 3" + chr(10) + "g = sin(k x) cos(k y) + sin(k y) cos(k z) + sin(k z) cos(k x)" + chr(10) + "shape = max(g, sqrt(x^2 + y^2 + z^2) - 2.2)"
let gyroid = surface_from_text_in(gyroid_text, [[-(23/10), -(23/10), -(23/10)], [(23/10), (23/10), (23/10)]])
let gyroid = set_material(set_transform(gyroid, mat_mul(translation(0, (3/2), 1), scaling((3/5), (3/5), (3/5)))), material_with(color((9/10), (7/10), (1/10)), (1/10), (7/10), (5/10), 100))
let ridged_text = "(sqrt(x^2 + z^2) - 1.5)^2 + y^2 = (0.4 + 0.06 sin(12x) sin(12z))^2"
let ridged = surface_from_text_in(ridged_text, [[-(21/10), -(11/20), -(21/10)], [(21/10), (11/20), (21/10)]])
let ridged = set_material(set_transform(ridged, translation((5/2), (11/20), -1)), with_reflective(material_with(color((1/5), (3/10), (9/10)), (1/10), (7/10), (6/10), 150), (1/10)))
return [[floor_p, ripple, gyroid, ridged], point_light(point(-8, 10, -10), color(1, 1, 1)), true]
end
> tools/prender.sh examples/ch27_functions.patlang
assembled 400x200 from 40 bands
rendered with 9 parallel processes (40 bands) in 1504 s wall clock
Checking it independently
The exporter writes the text of each surface and the independent tracer reads the surface from that:
its interpreter of Surfaces typed as text now has the function calls too, and writes PowerShell code with
[Math]::Sin, [Math]::Sqrt and the rest, compiled once. It finds hits by sampling along the ray and
bisecting, which shares nothing with the interval solver.
> v2_interp.exe tools/export_scene.patlang --scene functions --out out/functions_scene.txt
wrote out/functions_scene.txt (4 shapes)
> powershell.exe -NoProfile -File tools/verify_recursive.ps1 out/ch27_functions.png -SceneFile out/functions_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 controls: the ripples' amplitude changed from 0.12 to 0.10, and the gyroid's k from 3 to
2.9, in the text the checker reads:
sed 's/- 1 - 0.12 sin(7x)/- 1 - 0.10 sin(7x)/' out/functions_scene.txt > out/functions_scene_wrong.txt
sed 's/k = 3;g/k = 2.9;g/' out/functions_scene.txt > out/functions_scene_wrong2.txt
> powershell.exe -NoProfile -File tools/verify_recursive.ps1 out/ch27_functions.png -SceneFile out/functions_scene_wrong.txt -Stride 4
decoded by .NET: 400x200; pixels differing from the independent recursive tracer by more than 1 level: 197 (max difference 127); stride 4 in each direction, 5000 pixels checked
> powershell.exe -NoProfile -File tools/verify_recursive.ps1 out/ch27_functions.png -SceneFile out/functions_scene_wrong2.txt -Stride 4
decoded by .NET: 400x200; pixels differing from the independent recursive tracer by more than 1 level: 115 (max difference 157); stride 4 in each direction, 5000 pixels checked
Built Objects as Implicit Functions
Surfaces of any function can render any function f(x, y, z), negative inside and positive outside. So any
object that is such a function can be treated there, and a surprising amount of what has been built
so far is: a sphere is √(x²+y²+z²) − 1, a cube max(|x|, |y|, |z|) − 1, CSG is min and max
of the two sides. Once an object is a function, changing it is changing what it is evaluated at: to
twist it, evaluate it at a rotated point.
The function of a built object
| object | function (negative inside) |
|---|---|
| sphere | sqrt(x² + y² + z²) − 1 |
| plane | y |
| cube | `max( |
| cylinder | max(sqrt(x² + z²) − 1, y − max, min − y), with the limits that are not infinite |
| cone | `max(sqrt(x² + z²) − |
| torus | sqrt((sqrt(x² + z²) − R)² + y²) − r |
| polynomial or function surface | its function, max'd with the box that cuts it off |
| union | min(a, b) |
| intersection | max(a, b) |
| difference | max(a, −b) |
| group | the min of its children |
transformed by M |
the function at M⁻¹ p |
Three limits. A cylinder or cone is a solid here, end caps and all, whether or not it was
closed: an open tube is a surface with no inside. A polynomial surface is cut by its box, which makes
the box's faces part of the solid (a ray solver only reports roots inside the box; a solid cut off by it
has a lid). And a triangle, a mesh, or a group holding one, has no function: a mesh has no inside to
speak of, and shape_function answers false.
# the tree with x, y and z replaced by the trees fx, fy and fz
make a function called fa_subst takes a, fx, fy, fz returns b
let op = a[0]
if op == "num" then
return a
end
if op == "var" then
if a[1] == 0 then
return fx
end
if a[1] == 1 then
return fy
end
return fz
end
if op == "neg" then
return fa_neg(fa_subst(a[1], fx, fy, fz))
end
if op == "powi" then
return fa_pow(fa_subst(a[1], fx, fy, fz), a[2])
end
if op == "fn" then
return fa_fn(a[1], fa_subst(a[2], fx, fy, fz))
end
let l = fa_subst(a[1], fx, fy, fz)
let r = fa_subst(a[2], fx, fy, fz)
if op == "add" then
return fa_add(l, r)
end
if op == "sub" then
return fa_sub(l, r)
end
if op == "mul" then
return fa_mul(l, r)
end
if op == "div" then
return fa_div(l, r)
end
if op == "min" then
return fa_min(l, r)
end
return fa_max(l, r)
end
# the tree of a point sent through the matrix m (4 x 4, as rows): component r of m (x, y, z, 1)
make a function called fa_row takes m, r returns a
let t = fa_mul(fa_num(m[r][0] * 1.0), fa_var(0))
let t = fa_add(t, fa_mul(fa_num(m[r][1] * 1.0), fa_var(1)))
let t = fa_add(t, fa_mul(fa_num(m[r][2] * 1.0), fa_var(2)))
return fa_add(t, fa_num(m[r][3] * 1.0))
end
# the function evaluated at m (x, y, z)
make a function called fa_affine takes a, m returns b
return fa_subst(a, fa_row(m, 0), fa_row(m, 1), fa_row(m, 2))
end
# the sum of squares and the like, for the primitives
make a function called fa_sq takes a returns b
return fa_pow(a, 2)
end
make a function called fa_radial takes u, v returns b
return fa_fn("sqrt", fa_add(fa_sq(u), fa_sq(v)))
end
# max(lo_i - v_i, v_i - hi_i) over the three axes: positive outside the box
make a function called fa_box_outside takes bounds returns a
let f = false
let k = 0
while k < 3 do
let v = fa_var(k)
let side = fa_max(fa_sub(fa_num(bounds[0][k] * 1.0), v), fa_sub(v, fa_num(bounds[1][k] * 1.0)))
if f == false then
let f = side
else
let f = fa_max(f, side)
end
let k = k + 1
end
return f
end
# limits on y that are not infinite
make a function called fa_limit_y takes f, lo, hi returns g
let g = f
if abs(hi) < infinity() then
let g = fa_max(g, fa_sub(fa_var(1), fa_num(hi * 1.0)))
end
if abs(lo) < infinity() then
let g = fa_max(g, fa_sub(fa_num(lo * 1.0), fa_var(1)))
end
return g
end
# the function of the shape in its own (object) space, or false
make a function called shape_local_function takes s returns f
let kind = s[5]
let x = fa_var(0)
let y = fa_var(1)
let z = fa_var(2)
if kind == "sphere" then
return fa_sub(fa_fn("sqrt", fa_add(fa_add(fa_sq(x), fa_sq(y)), fa_sq(z))), fa_num(1))
end
if kind == "plane" then
return y
end
if kind == "cube" then
return fa_sub(fa_max(fa_max(fa_fn("abs", x), fa_fn("abs", y)), fa_fn("abs", z)), fa_num(1))
end
if kind == "cylinder" then
return fa_limit_y(fa_sub(fa_radial(x, z), fa_num(1)), s[6][0], s[6][1])
end
if kind == "cone" then
return fa_limit_y(fa_sub(fa_radial(x, z), fa_fn("abs", y)), s[6][0], s[6][1])
end
if kind == "torus" then
return fa_sub(fa_fn("sqrt", fa_add(fa_sq(fa_sub(fa_radial(x, z), fa_num(s[6][0] * 1.0))), fa_sq(y))), fa_num(s[6][1] * 1.0))
end
if kind == "implicit" then
return fa_max(fa_from_poly(s[6][0]), fa_box_outside(s[6][1]))
end
if kind == "function" then
return fa_max(s[6][0], fa_box_outside(s[6][1]))
end
if kind == "group" then
let kids = s[6][0]
let f = fa_num(1)
let k = 0
while k < kids.length do
let kf = shape_function(kids[k])
if kf == false then
return false
end
if k == 0 then
let f = kf
else
let f = fa_min(f, kf)
end
let k = k + 1
end
return f
end
if kind == "csg" then
let l = shape_function(s[6][1])
let r = shape_function(s[6][2])
if l == false or r == false then
return false
end
if s[6][0] == "union" then
return fa_min(l, r)
end
if s[6][0] == "intersection" then
return fa_max(l, r)
end
return fa_max(l, fa_neg(r))
end
return false
end
# the function of the shape in its parent's space (the world, for a shape of the scene), or false
make a function called shape_function takes s returns f
let local = shape_local_function(s)
if local == false then
return false
end
if s[8] then
return local
end
return fa_affine(local, s[2])
end
# a function surface of the object's function, in the box `bounds`, with the object's material
make a function called implicit_view takes s, bounds returns v
let f = shape_function(s)
if f == false then
return false
end
return set_material(function_surface(f, bounds), shape_material(s))
end
# the inverse of the deformation as three trees of x, y, z: [x', y', z']
make a function called warp_maps takes kind, params returns maps
let x = fa_var(0)
let y = fa_var(1)
let z = fa_var(2)
if kind == "twist" then
let th = fa_mul(fa_num(params[0]), y)
let c = fa_fn("cos", th)
let s = fa_fn("sin", th)
return [fa_sub(fa_mul(x, c), fa_mul(z, s)), y, fa_add(fa_mul(x, s), fa_mul(z, c))]
end
if kind == "taper" then
let sc = fa_add(fa_num(1), fa_mul(fa_num(params[0]), y))
return [fa_div(x, sc), y, fa_div(z, sc)]
end
if kind == "bend" then
let big = 1 / params[0]
let u = fa_sub(fa_num(big), y)
return [fa_mul(fa_num(big), fa_fn("atan", fa_div(x, u))), fa_sub(fa_num(big), fa_fn("sqrt", fa_add(fa_sq(x), fa_sq(u)))), z]
end
if kind == "wave" then
return [x, fa_sub(y, fa_mul(fa_num(params[0]), fa_fn("sin", fa_mul(fa_num(params[1]), x)))), z]
end
# shear
return [fa_sub(x, fa_mul(fa_num(params[0]), y)), y, z]
end
# the deformation itself, on numbers [x, y, z]
make a function called warp_forward takes kind, params, q returns p
let x = q[0]
let y = q[1]
let z = q[2]
if kind == "twist" then
let th = params[0] * y
return [x * cos(th) + z * sin(th), y, 0 - x * sin(th) + z * cos(th)]
end
if kind == "taper" then
let sc = 1 + params[0] * y
return [x * sc, y, z * sc]
end
if kind == "bend" then
let big = 1 / params[0]
let th = x / big
return [(big - y) * sin(th), big - (big - y) * cos(th), z]
end
if kind == "wave" then
return [x, y + params[0] * sin(params[1] * x), z]
end
return [x + params[0] * y, y, z]
end
# the function f deformed
make a function called warped_function takes f, kind, params returns g
let m = warp_maps(kind, params)
return fa_subst(f, m[0], m[1], m[2])
end
# a deformed copy of the object, seen inside `bounds`
make a function called warped_shape takes s, kind, params, bounds returns w
let f = shape_function(s)
if f == false then
return false
end
return set_material(function_surface(warped_function(f, kind, params), bounds), shape_material(s))
end
# the box holding the deformed object, from the deformation of a grid of 9 x 9 x 9 points of the
# object's own box, grown by a twentieth of its size on every side: the deformations are smooth and
# the grid holds the corners, which is where their extremes are, but a grid can miss one between its
# points. (The tests check that every point of the surface lies inside.)
make a function called warp_bounds takes box, kind, params returns b
let lo = [infinity(), infinity(), infinity()]
let hi = [0 - infinity(), 0 - infinity(), 0 - infinity()]
let i = 0
while i <= 8 do
let j = 0
while j <= 8 do
let k = 0
while k <= 8 do
let q = [box[0][0] + (box[1][0] - box[0][0]) * i / 8, box[0][1] + (box[1][1] - box[0][1]) * j / 8, box[0][2] + (box[1][2] - box[0][2]) * k / 8]
let p = warp_forward(kind, params, q)
let a = 0
while a < 3 do
if p[a] < lo[a] then
let lo = list_set(lo, a, p[a])
end
if p[a] > hi[a] then
let hi = list_set(hi, a, p[a])
end
let a = a + 1
end
let k = k + 1
end
let j = j + 1
end
let i = i + 1
end
let out_lo = []
let out_hi = []
let a = 0
while a < 3 do
let pad = (hi[a] - lo[a]) / 20
let out_lo = list_push(out_lo, lo[a] - pad)
let out_hi = list_push(out_hi, hi[a] + pad)
let a = a + 1
end
return [out_lo, out_hi]
end
# the same, with the box found from the object's own: false if the object has no finite box
make a function called warped_shape_auto takes s, kind, params returns w
let box = parent_space_bounds(s)
if box == false then
return false
end
let k = 0
while k < 3 do
if abs(box[0][k]) >= infinity() or abs(box[1][k]) >= infinity() then
return false
end
let k = k + 1
end
return warped_shape(s, kind, params, warp_bounds(box, kind, params))
end
# the union of a and b, rounded where they come within k of each other: min(a, b) less
# max(k - |a - b|, 0)^2 / (4 k), at most k / 4 below the union
make a function called smooth_union takes a, b, k returns f
let h = fa_max(fa_sub(fa_num(k), fa_fn("abs", fa_sub(a, b))), fa_num(0))
return fa_sub(fa_min(a, b), fa_div(fa_sq(h), fa_num(4 * k)))
end
# the wall of thickness t about a's surface (t either side of it)
make a function called shell takes a, t returns f
return fa_sub(fa_fn("abs", a), fa_num(t))
end
# a's surface moved out by d
make a function called offset takes a, d returns f
return fa_sub(a, fa_num(d))
end
# a at s = 0, b at s = 1, and between them the mix
make a function called morph takes a, b, s returns f
return fa_add(fa_mul(fa_num(1 - s), a), fa_mul(fa_num(s), b))
end
Deformations
If an object is carried by q → W(q), its new function is f(W⁻¹(p)). So a deformation is its inverse,
three expressions of x, y, z, substituted into the tree. Five are built in:the inverse map undoes the deformation
| deformation | what it does | inverse used |
|---|---|---|
twist(k) |
turns layer y by k y radians about the y axis |
rotate by −k y |
taper(k) |
scales layer y about the y axis by 1 + k y |
divide x and z by 1 + k y |
bend(c) |
bends the x axis into a circle of radius 1/c |
x = R atan(x'/(R−y')), y = R − sqrt(x'² + (R−y')²) |
wave(a, w) |
lifts each point by a sin(w x) |
lower it by the same |
shear(k) |
moves each point sideways by k y |
move it back |
warp_forward is the same deformation as plain numbers. The renderer never uses it: it finds the
box that holds the deformed object (a 9 × 9 × 9 grid of the original box sent forward and grown by a
twentieth), and it is the oracle of the tests, which is written separately from the inverses.
A deformed function is no longer a distance, so thicknesses (shell, offset) are in the units of
the undeformed object, and only roughly right after a deformation. The sign is all the renderer needs.
A deformed object is one function surface, so it has one material: the colours of the parts (the
red, green and blue walls of Built objects: solid geometry and a Dalek's holes) do not survive.
Combinations
smooth_union(a, b, k) is the union, rounded where the two come within k of each other: min(a, b)
less max(k − |a − b|, 0)² / 4k, which is k/4 below the union at most. shell(a, t) is the wall of
thickness t about a's surface, |a| − t. offset(a, d) is a − d, the surface moved out by d.
morph(a, b, s) is a at s = 0 and b at s = 1, and the mix between.
Scenarios and oracles
- The function against the object. For 14 objects (the sphere, cube, a capped and an infinite cylinder, a closed cone, a torus, a stretched sphere, a cube turned about two axes, a lens, a cube minus a ball, a cube drilled by a cylinder, two spheres united, a group, and a moved difference), the sign of the function at 150 random points is compared with an odd or even number of surface crossings of a ray from the point, by the objects' own intersection code. Points within 0.02 of the surface are left out.
- The function view has the object's hits. On 30 rays each, a cube minus a ball, a cube drilled by a cylinder, a group, a stretched sphere.
- Inverse and forward. For each deformation, forward then inverse returns the point, on 100 points;
and by hand: twist 1 at
(1, 0.5, 0); taper aty = 2; shear; wave. - The surface follows. Points of the original surface (found by rays on the CSG object) sent forward satisfy the deformed function, to 10⁻⁶: this ties the forward map written as numbers to the inverse written as trees.
- Identities. A twist of zero of a capped cylinder gives the cylinder; a twist of 1.7 radians per unit about the cylinder's own axis changes nothing (a cylinder is a surface of revolution about it); a taper of a capped cylinder is exactly the cone frustum of Boxes, cylinders and cones's cone primitive, moved and scaled to meet it. Negative control: a twisted cube differs from the cube.
- Boxes. The box found for each deformation holds every deformed surface point sampled.
- Combinations. A smooth union is the union where the two differ by
kor more and at mostk/4below; exactlyk/4at the neck between two equal spheres; a shell's value at the middle of its wall; morph at 0, 1 and ½; a ray through a shelled sphere hits both faces of the wall on both sides.
Putting it together
The carved cube of Built objects: solid geometry and a Dalek as built, twisted, and tapered; a bar bent into an arch; and three
spheres smoothly joined, shelled, and cut open at the front with max(f, 0.2 − z):
# chapter 28: built objects as functions, deformed. The cube of Chapter 16 (rounded by a sphere,
# drilled by three cylinders) as built, twisted, and tapered; a bar bent into an arch; and three
# spheres smoothly joined into a blob, shelled, and cut open to show the wall. The deformed ones are single function
# surfaces, so each has one material.
make a function called build_warp_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/5))
let blue = with_reflective(material_with(color((1/5), (3/10), (9/10)), (1/10), (6/10), (7/10), 200), (1/10))
let red = material_with(color((9/10), (1/5), (1/5)), (1/10), (7/10), (6/10), 150)
let original = set_transform(carved_cube(), translation(-(24/5), 1, 0))
let twisted = set_transform(warped_shape_auto(set_material(carved_cube(), gold), "twist", [(9/10)]), translation(-(8/5), 1, 0))
let twisted = set_material(twisted, gold)
let tapered = set_material(set_transform(warped_shape_auto(carved_cube(), "taper", [(7/20)]), translation((8/5), 1, 0)), blue)
let bar = set_transform(cube(), scaling((11/5), (2/5), (2/5)))
let arch = set_material(set_transform(warped_shape_auto(bar, "bend", [(9/20)]), translation((24/5), (1/2), 0)), red)
let a = shape_function(set_transform(sphere(), translation(-(3/10), 0, 0)))
let b = shape_function(set_transform(sphere(), translation((3/10), 0, 0)))
let c = shape_function(set_transform(sphere(), translation(0, (1/2), 0)))
let hollow = shell(smooth_union(smooth_union(a, b, (4/5)), c, (4/5)), (1/10))
let cut = fa_max(hollow, fa_sub(fa_num((1/5)), fa_var(2)))
let blob = set_material(set_transform(function_surface(cut, [[-(3/2), -(3/2), -(3/2)], [(3/2), (3/2), (3/2)]]), mat_mul(translation(0, (3/2), 3), rotation_y((1/5)))), with_reflective(material_with(color((1/5), (4/5), (1/2)), (1/10), (7/10), (6/10), 150), (1/10)))
return [[floor_p, original, twisted, tapered, arch, blob], demo_light(), true]
end
> tools/prender.sh examples/ch28_warps.patlang
assembled 400x200 from 40 bands
rendered with 9 parallel processes (40 bands) in 1856 s wall clock
Checking it independently
What the independent tracer can check is the rendering of the function: the exporter sends each
function surface as its tape, one statement for each instruction (t12 = sin(t11);), and the
checker reads that with its own interpreter and finds hits by sampling and bisection, which shares
nothing with the interval solver or the evaluator. What the semantics of the deformations are is checked by the
oracles above (forward against inverse; the cylinder under twist; the taper against the cone), and the
original, undeformed carved cube on the left is rendered by the checker from its primitives.
> v2_interp.exe tools/export_scene.patlang --scene warps --out out/warps_scene.txt
wrote out/warps_scene.txt (14 shapes)
> powershell.exe -NoProfile -File tools/verify_recursive.ps1 out/ch28_warps.png -SceneFile out/warps_scene.txt -Stride 4
decoded by .NET: 400x200; pixels differing from the independent recursive tracer by more than 1 level: 1 (max difference 13); stride 4 in each direction, 5000 pixels checked
One pixel of 5 000 differs, by 13 levels out of 255, at (224, 76), on the edge of the tapered shape with the blob seen behind it. At that pixel the interval solver's hits on the two shapes the ray meets agree with a dense march of step 0.0005 (to 2 · 10⁻´), so the difference is in how the checker found the hit it needed, not in the hits themselves; it is left as it is. (With 1 500 samples a ray, the checker's first setting, three pixels differed: it stepped over a sliver 0.001 across, and finds it with 6 000.)
Negative controls: the twist's rate changed from 0.9 to 0.8 in the tape the checker reads, and the blob's smoothing from 4/5 to 3/5:
sed '/^X 10 /s/= 9\/10;/= 4\/5;/' out/warps_scene.txt > out/warps_scene_wrong.txt
sed '/^X 13 /s/= 4\/5;/= 3\/5;/' out/warps_scene.txt > out/warps_scene_wrong2.txt
> powershell.exe -NoProfile -File tools/verify_recursive.ps1 out/ch28_warps.png -SceneFile out/warps_scene_wrong.txt -Stride 4
decoded by .NET: 400x200; pixels differing from the independent recursive tracer by more than 1 level: 85 (max difference 91); stride 4 in each direction, 5000 pixels checked
> powershell.exe -NoProfile -File tools/verify_recursive.ps1 out/ch28_warps.png -SceneFile out/warps_scene_wrong2.txt -Stride 4
decoded by .NET: 400x200; pixels differing from the independent recursive tracer by more than 1 level: 88 (max difference 127); stride 4 in each direction, 5000 pixels checked
How it is checked
> v2_interp.exe tests/run.patlang --node numbers/intervals --depth 2
[ ok ] Intervals and function surfaces
[ ok ] The expression tree
[ ok ] Sums, products and powers of numbers fold: 2 + 3 = 5, 2 * 3 = 6, 2^3 = 8
[ ok ] The tape
[ ok ] The tape at a point equals the reference evaluator
[ ok ] A shared sum is computed once: (x + y)(x + y) is 4 instructions
[ ok ] Intervals
[ ok ] The interval value contains the value at every sampled point
[ ok ] Sin over [0, 7] (more than a turn) is [-1, 1]
[ ok ] The surface
[ ok ] A sphere written with sqrt gives the sphere primitive's hits on 40 rays
[ ok ] A wavy surface y = 0.3 sin 3x: the solver finds what a dense march finds, 50 rays
[ ok ] A thin sheet 0.002 thick: both faces found, at t = 0.499 and 0.501
[ ok ] The normal of the function sphere is the primitive's (gradient of the function)
[ ok ] Functions typed as text
[ ok ] A script that uses no function is still a polynomial
[ ok ] Surface_from_text makes a function shape of a text with sqrt
checks: 11 passed, 0 failed, 0 blocked, 0 skipped, 0 not run
ALL PASSED
> v2_interp.exe tests/run.patlang --node numbers/warps --depth 2
[ ok ] Warps, blends and offsets
[ ok ] The function of a built object
[ ok ] The function of a
[ ok ] The function view of
[ ok ] Deformations
[ ok ] Twist 1.0 turns (1, 0.5, 0) by 0.5 radians about y: (cos 0.5, 0.5, -sin 0.5)
[ ok ] The surface hit points of the original, sent forward, are on the warped surface
[ ok ] Twist 0 of a capped cylinder is the capped cylinder (30 rays)
[ ok ] Bounds
[ ok ] Combinations
[ ok ] A smooth union is the union where the two differ by the smoothing width or more, and at ...
checks: 7 passed, 0 failed, 0 blocked, 0 skipped, 0 not run
ALL PASSED