Last updated: 2026-11-26
22. Surfaces typed as text
For new readers
The function surfaces and the scene language's numbers are
typed as text: this page opens the expression language (+ โ * / ^, functions, variables),
its parser, its exact arithmetic, and the polynomial form (and its gradient, for normals) that the
root finders need.
Surfaces Typed as Text
The torus and other polynomial surfaces made a surface from a polynomial, but the polynomial had to be built by calls:
tm_pow, tm_sub, tm_scale, a page of them for the heart. This page reads it the way
it is written on paper:
(x-4)^2 + (y+2)^2 + (z-1)^2 - 9 = 0
or built up from pieces, one statement to a line, each piece usable in the ones after it:
f = x-4
g = y+2
h = z-1
r = 3
shape = f^2 + g^2 + h^2 - r^2
Both give the same exact polynomial, and the shape is the implicit surface of The torus and other polynomial surfaces with everything that goes with it: roots found exactly, normals from the gradient, a transformation, a material, CSG.
The language
| numbers | 3, 0.25, 1e-3, exact (0.25 is the rational 1/4); and pi, a float |
| variables | x, y, z |
| operators | + โ * / and ^ with a whole-number exponent from 0 to 32; brackets |
| precedence | ^ binds tighter than a minus in front (-x^2 is -(x^2)) and groups right to left (2^3^2 is 2^9); * and / before + and โ; the rest left to right |
| division | only by a constant: x/2 and (x+1)/3 are polynomials, x/y is not |
| products | *, or side by side when the second begins with a letter or a bracket: 2x, 3(x+1), (x+1)(xโ1), x(y+z). Names are whole words, so xy is one name; write x*y or x y |
| statements | name = expression gives it a name; any other = is an equation, left = right meaning left โ right (x^2 + y^2 = z, and x = 3, a plane); a bare expression means itself. Separated by a new line or ; |
| the surface | is shape if some statement assigns it, else the last statement |
| comments | # to the end of a line |
Every value is an exact polynomial in x, y and z: sums, products and whole powers of
polynomials are polynomials, and so is division by a constant. The limit of 32 on an exponent
is a guard against a typed x^1000000, not a technical one; a surface of degree 32 is already
beyond what the root finders can do in a render.
How it is read
The text is a list of bytes (Triangles and meshes from files's lesson about String indexing), parsed by recursive
descent with one function per level of precedence: an expression is terms joined by + and โ,
a term is factors joined by *, / or by juxtaposition, a factor has an optional minus, and
a power has an optional ^. Each function returns a polynomial built with the tm_* algebra of
The torus and other polynomial surfaces, so (x+y)^2 is expanded and collected as it is parsed.
Errors do not stop anything. A parse gives [true, polynomial] or [false, "message at position n"], a script [true, polynomial, names] or [false, "statement k: message"], and
surface_try(text, bounds, defs) [true, shape] or [false, message]; surface_from_text gives
the shape, or false.
A surface that is larger than the box that shows it must be cut off by it, as Barth's sextic is.
surface_from_text uses a cube of 20 round the origin; surface_from_text_in(text, bounds) takes
the box, and surface_from_text_with(text, bounds, defs) also takes names for the script:
[["cx", 4], ["rad", 3]].
# the bytes of a (short) string
make a function called ex_bytes takes text returns bytes
let bytes = []
let k = 0
while k < text.length do
let bytes = list_push(bytes, char_code(text, k))
let k = k + 1
end
return bytes
end
# the parser's state, a vec: [bytes, position (0-based), the error message or false]
make a function called ex_new takes text, mode returns st
let st = vec_new()
vec_push(st, ex_bytes(text))
vec_push(st, 0)
vec_push(st, false)
vec_push(st, mode)
vec_push(st, false)
return st
end
# note the first error and its place (1-based); always returns false
make a function called ex_fail takes st, msg returns no
if vec_get(st, 2) == false then
vec_set(st, 2, msg + " at position " + (vec_get(st, 1) + 1))
end
return false
end
make a function called ex_failed takes st returns yes
return vec_get(st, 2) != false
end
# the next byte after any blanks (which it skips), or -1 at the end
make a function called ex_peek takes st returns c
let bytes = vec_get(st, 0)
let i = vec_get(st, 1)
while i < bytes.length and (bytes[i] == 32 or bytes[i] == 9 or bytes[i] == 13) do
let i = i + 1
end
vec_set(st, 1, i)
if i >= bytes.length then
return -1
end
return bytes[i]
end
make a function called ex_is_letter takes c returns yes
return (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95
end
make a function called ex_is_digit takes c returns yes
return c >= 48 and c <= 57
end
# an exact number at the position: digits, an optional fraction, an optional exponent
make a function called ex_number takes st returns p
let bytes = vec_get(st, 0)
let i = vec_get(st, 1)
let whole = 0
let scale = 1
while i < bytes.length and ex_is_digit(bytes[i]) do
let whole = whole * 10 + (bytes[i] - 48)
let i = i + 1
end
if i + 1 < bytes.length and bytes[i] == 46 and ex_is_digit(bytes[i + 1]) then
let i = i + 1
while i < bytes.length and ex_is_digit(bytes[i]) do
let whole = whole * 10 + (bytes[i] - 48)
let scale = scale * 10
let i = i + 1
end
end
let value = whole / scale
# an exponent: e, an optional sign, and at least one digit (else the e is a name)
if i < bytes.length and (bytes[i] == 101 or bytes[i] == 69) then
let j = i + 1
let neg = false
if j < bytes.length and (bytes[j] == 45 or bytes[j] == 43) then
let neg = bytes[j] == 45
let j = j + 1
end
if j < bytes.length and ex_is_digit(bytes[j]) then
let e = 0
while j < bytes.length and ex_is_digit(bytes[j]) do
let e = e * 10 + (bytes[j] - 48)
let j = j + 1
end
let k = 0
while k < e do
if neg then
let value = value / 10
else
let value = value * 10
end
let k = k + 1
end
let i = j
end
end
vec_set(st, 1, i)
return ex_const(st, value)
end
# the name at the position, as a String
make a function called ex_name takes st returns name
let bytes = vec_get(st, 0)
let i = vec_get(st, 1)
let sb = sb_new()
while i < bytes.length and (ex_is_letter(bytes[i]) or ex_is_digit(bytes[i])) do
sb_push(sb, chr(bytes[i]))
let i = i + 1
end
vec_set(st, 1, i)
return sb_str(sb)
end
# the polynomial a name stands for: a named piece (the last one given), x, y, z, pi; or false
make a function called ex_lookup takes st, name, env returns p
let k = env.length - 1
while k >= 0 do
if env[k][0] == name then
return env[k][1]
end
let k = k - 1
end
if name == "x" then
return ex_var(st, 0)
end
if name == "y" then
return ex_var(st, 1)
end
if name == "z" then
return ex_var(st, 2)
end
if name == "pi" then
return ex_const(st, 4 * atan(1))
end
return false
end
# the number a polynomial is, if it is one; false if it has an x, y or z in it
make a function called ex_constant takes p returns v
if p.length == 0 then
return 0
end
# a tree: a number node
if p[0] == "num" then
return p[1]
end
if p[0] == "var" or p[0] == "add" or p[0] == "sub" or p[0] == "mul" or p[0] == "div" or p[0] == "neg" or p[0] == "powi" or p[0] == "fn" or p[0] == "min" or p[0] == "max" then
return false
end
# a polynomial: one term with no x, y or z
if p.length == 1 and p[0][1] == 0 and p[0][2] == 0 and p[0][3] == 0 then
return p[0][0]
end
return false
end
# a primary: a number, a name, or an expression in brackets
make a function called ex_primary takes st, env returns p
let c = ex_peek(st)
if c == -1 then
return ex_fail(st, "the expression ends where more was expected")
end
if c == 40 then
vec_set(st, 1, vec_get(st, 1) + 1)
let p = ex_expr(st, env)
if ex_failed(st) then
return false
end
if ex_peek(st) != 41 then
return ex_fail(st, "expected ')'")
end
vec_set(st, 1, vec_get(st, 1) + 1)
return p
end
if ex_is_digit(c) or (c == 46 and vec_get(st, 1) + 1 < vec_get(st, 0).length and ex_is_digit(vec_get(st, 0)[vec_get(st, 1) + 1])) then
return ex_number(st)
end
if ex_is_letter(c) then
let at = vec_get(st, 1)
let name = ex_name(st)
if ex_arity(name) > 0 and ex_peek(st) == 40 then
return ex_call(st, env, name)
end
let p = ex_lookup(st, name, env)
if p == false then
vec_set(st, 1, at)
return ex_fail(st, "unknown name '" + name + "'")
end
return p
end
return ex_fail(st, "unexpected '" + chr(c) + "'")
end
# a primary with an optional whole-number power: ^ groups to the right
make a function called ex_power takes st, env returns p
let base = ex_primary(st, env)
if ex_failed(st) then
return false
end
if ex_peek(st) == 94 then
vec_set(st, 1, vec_get(st, 1) + 1)
let at = vec_get(st, 1)
let ex = ex_unary(st, env)
if ex_failed(st) then
return false
end
let e = ex_constant(ex)
if e == false or e < 0 or floor(e) != e then
vec_set(st, 1, at)
return ex_fail(st, "an exponent must be a whole number, 0 or more")
end
if e > 32 then
vec_set(st, 1, at)
return ex_fail(st, "exponent " + e + " is over the limit of 32")
end
return ex_pow(st, base, e)
end
return base
end
make a function called ex_unary takes st, env returns p
let c = ex_peek(st)
if c == 45 then
vec_set(st, 1, vec_get(st, 1) + 1)
let p = ex_unary(st, env)
if ex_failed(st) then
return false
end
return ex_neg(st, p)
end
if c == 43 then
vec_set(st, 1, vec_get(st, 1) + 1)
return ex_unary(st, env)
end
return ex_power(st, env)
end
# factors joined by *, / (by a constant) or written side by side
make a function called ex_term takes st, env returns p
let left = ex_unary(st, env)
if ex_failed(st) then
return false
end
let going = true
while going do
let c = ex_peek(st)
if c == 42 then
vec_set(st, 1, vec_get(st, 1) + 1)
let right = ex_unary(st, env)
if ex_failed(st) then
return false
end
let left = ex_mul(st, left, right)
elif c == 47 then
vec_set(st, 1, vec_get(st, 1) + 1)
let at = vec_get(st, 1)
let right = ex_unary(st, env)
if ex_failed(st) then
return false
end
let d = ex_constant(right)
if vec_get(st, 3) == "fn" and d == false then
# a function may be divided by a function; where the divisor holds 0 the value is unbounded
let left = fa_div(left, right)
else
if d == false then
vec_set(st, 1, at)
# not a polynomial, but a function (Chapter 27) can have it
vec_set(st, 4, true)
return ex_fail(st, "division by something that is not a constant")
end
if d == 0 then
vec_set(st, 1, at)
return ex_fail(st, "division by zero")
end
if vec_get(st, 3) == "poly" then
let left = tm_scale(left, 1 / d)
else
let left = fa_div(left, right)
end
end
elif c == 40 or ex_is_letter(c) then
let right = ex_unary(st, env)
if ex_failed(st) then
return false
end
let left = ex_mul(st, left, right)
else
let going = false
end
end
return left
end
make a function called ex_expr takes st, env returns p
let left = ex_term(st, env)
if ex_failed(st) then
return false
end
let going = true
while going do
let c = ex_peek(st)
if c == 43 or c == 45 then
vec_set(st, 1, vec_get(st, 1) + 1)
let right = ex_term(st, env)
if ex_failed(st) then
return false
end
if c == 43 then
let left = ex_add(st, left, right)
else
let left = ex_sub(st, left, right)
end
else
let going = false
end
end
return left
end
make a function called expr_parse takes text, env returns result
return expr_parse_mode(text, env, "poly")
end
# the statements of a script: the text of each non-empty one, comments and blank lines gone
make a function called expr_statements takes text returns list
let bytes = ex_bytes(text)
let out = []
let sb = sb_new()
let have = false
let i = 0
let comment = false
while i <= bytes.length do
let c = 10
if i < bytes.length then
let c = bytes[i]
end
if c == 10 or c == 59 then
if have then
let out = list_push(out, sb_str(sb))
end
let sb = sb_new()
let have = false
let comment = false
elif c == 35 then
let comment = true
elif not comment then
sb_push(sb, chr(c))
if c != 32 and c != 9 and c != 13 then
let have = true
end
end
let i = i + 1
end
return out
end
# the part of the text before the first = (the whole text if there is none), the part after it,
# and the number of = signs
make a function called ex_split_equals takes text returns parts
let bytes = ex_bytes(text)
let left = sb_new()
let right = sb_new()
let count = 0
let i = 0
while i < bytes.length do
if bytes[i] == 61 then
let count = count + 1
elif count == 0 then
sb_push(left, chr(bytes[i]))
else
sb_push(right, chr(bytes[i]))
end
let i = i + 1
end
return [sb_str(left), sb_str(right), count]
end
# is the text, apart from blanks, one name that is free to be given a meaning
make a function called ex_assignable takes text returns name
let bytes = ex_bytes(text)
let a = 0
while a < bytes.length and (bytes[a] == 32 or bytes[a] == 9 or bytes[a] == 13) do
let a = a + 1
end
let b = bytes.length
while b > a and (bytes[b - 1] == 32 or bytes[b - 1] == 9 or bytes[b - 1] == 13) do
let b = b - 1
end
if b <= a or not ex_is_letter(bytes[a]) then
return false
end
let sb = sb_new()
let k = a
while k < b do
if not (ex_is_letter(bytes[k]) or ex_is_digit(bytes[k])) then
return false
end
sb_push(sb, chr(bytes[k]))
let k = k + 1
end
let name = sb_str(sb)
if name == "x" or name == "y" or name == "z" or name == "pi" then
return false
end
return name
end
# a script: [true, value, names, algebra] or [false, message]. It is read as a polynomial if it is
# one (the algebra is "poly" and the value is exact); if it uses a function (sin, sqrt, ...) it is
# read again as a tree (the algebra is "fn")
make a function called expr_script takes text, defs returns result
let r = expr_script_mode(text, defs, "poly")
if r[0] or not r[2] then
return r
end
let f = expr_script_mode(text, defs, "fn")
return f
end
make a function called expr_default_bounds returns b
return [[-10, -10, -10], [10, 10, 10]]
end
# the shape surface_try gives, or false if the text is wrong
make a function called surface_from_text_with takes text, bounds, defs returns s
let r = surface_try(text, bounds, defs)
if not r[0] then
return false
end
return r[1]
end
make a function called surface_from_text_in takes text, bounds returns s
return surface_from_text_with(text, bounds, [])
end
# in the default window, a cube of 20 round the origin
make a function called surface_from_text takes text returns s
return surface_from_text_with(text, expr_default_bounds(), [])
end
Scenarios and oracles
- Arithmetic. Exact numbers, precedence and associativity (
2-3-4,8/2/2,2^3^2,-2^2), stacked signs, rationals (1/3 + 1/6), white space. - Variables.
2x,3(x+1),(x+1)(xโ1)andx y zagainst the same written with*;(x+y)^2collected;x โ xthe zero polynomial. - Against the formula written out. Five surfaces (the sphere, a torus, the heart, a deliberately
tangled expression, the rounded block) at 300 random points each, against the same formula as
PatLang arithmetic: no code in common with the parser. At the integer point
(1, 2, 3)the sphere is exactly 20. - The book's surfaces as text. The heart and Barth's sextic (with
phi = 1597/987) typed as text are, term for term, the polynomials The torus and other polynomial surfaces built by hand; so isx^4 + y^4 + z^4 = 1. - Scripts. The sphere as one equation, as five lines, with
;, with CRLF line ends, with comments, and with a name used before and one redefined from itself all give the same polynomial;x = 3is a plane and not an assignment tox; names given by the caller. - Errors. An unknown name is named and placed; a missing bracket; a dangling operator; an
empty expression;
x/y;1/0;x^y,x^โ1,x^2.5,x^(1/2);2 3; a stray character; an exponent over the limit; the number of the statement; a surface with nox,yorz. - The shape. The text sphere hits where the sphere primitive, moved to
(4, โ2, 1)and scaled by 3, does, on 40 rays; the normal on the axis is(0, 0, โ1); the default window cuts off a sphere that is out atx = 20and a window of its own finds it; a text surface takes a transformation like any shape. - Negative controls: radius 4 is a different polynomial and a different hit.
Putting it together
The sphere of the question, as its pieces; a torus from R and r (written 4 R^2 (x^2 + z^2));
the heart; and the rounded block x^4 + y^4 + z^4 = 1, each typed as text:
# chapter 26: surfaces typed as text (expr.patlang). The sphere (x-4)^2 + (y+2)^2 + (z-1)^2 = 9 from
# its pieces, a torus from R and r, the heart, and the rounded block x^4 + y^4 + z^4 = 1, on a
# checkered floor below them.
make a function called build_expression_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, 1, 1)))
let floor_p = set_material(set_transform(plane(), translation(0, -(28/5), 0)), floor_m)
let sphere_text = "f = x-4" + chr(10) + "g = y+2" + chr(10) + "h = z-1" + chr(10) + "r = 3" + chr(10) + "shape = f^2 + g^2 + h^2 - r^2"
let ball = surface_from_text_in(sphere_text, [[1, -5, -2], [7, 1, 4]])
let ball = set_material(ball, with_reflective(material_with(color((9/10), (1/5), (1/5)), (1/10), (7/10), (6/10), 150), (1/10)))
let torus_text = "R = 3/2 ; r = 1/2" + chr(10) + "shape = (x^2 + y^2 + z^2 + R^2 - r^2)^2 - 4 R^2 (x^2 + z^2)"
let ring = surface_from_text_in(torus_text, [[-(21/10), -(3/5), -(21/10)], [(21/10), (3/5), (21/10)]])
let ring = set_material(set_transform(ring, translation(-(7/2), -(21/5), -1)), with_reflective(material_with(color((1/5), (3/10), (9/10)), (1/10), (7/10), (6/10), 150), (1/10)))
let heart_text = "(x^2 + 9/4*z^2 + y^2 - 1)^3 - x^2*y^3 - 9/80*z^2*y^3 = 0"
let heart = surface_from_text_in(heart_text, [[-(13/10), -(11/10), -(8/10)], [(13/10), (13/10), (8/10)]])
let heart = set_material(set_transform(heart, mat_mul(translation(-(1/2), -(9/2), -4), mat_mul(rotation_y((1/5)), scaling((9/10), (9/10), (9/10))))), material_with(color((9/10), (1/10), (3/10)), (1/10), (7/10), (6/10), 150))
let block = surface_from_text_in("x^4 + y^4 + z^4 = 1", [[-(11/10), -(11/10), -(11/10)], [(11/10), (11/10), (11/10)]])
let block = set_material(set_transform(block, mat_mul(translation(4, -(9/2), -4), mat_mul(rotation_y((4/10)), scaling((4/5), (4/5), (4/5))))), with_reflective(material_with(color((9/10), (7/10), (1/10)), (1/10), (6/10), (7/10), 200), (1/5)))
return [[floor_p, ball, ring, heart, block], point_light(point(-8, 6, -10), color(1, 1, 1)), true]
end
> tools/prender.sh examples/ch26_expressions.patlang
assembled 400x200 from 40 bands
rendered with 9 parallel processes (40 bands) in 545 s wall clock
Checking it independently
The exporter writes the text of each surface as an X line, and the independent tracer reads
the surface from that, not from the polynomial the library made. It has an interpreter of its own:
a tokenizer and precedence climbing with binding powers (+ โ 10, * / and juxtaposition 20, a
minus in front 25, ^ 30 to the right), which writes PowerShell code for f(x, y, z) in doubles,
compiled once. Nothing is shared with the library's parser or its polynomial algebra. It also
found a mistake in itself: PowerShell's hashtables ignore case, so its first version took the R
and r of the torus to be one name, and the torus vanished from its picture.case-sensitive names are vital here
> v2_interp.exe tools/export_scene.patlang --scene expressions --out out/expr_scene.txt
wrote out/expr_scene.txt (5 shapes)
> powershell.exe -NoProfile -File tools/verify_recursive.ps1 out/ch26_expressions.png -SceneFile out/expr_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 sphere's r = 3 changed to 2.8 in the text the checker reads, and the
heart's 9/4*z^2 changed to 3/4*z^2:
sed 's/;r = 3;shape/;r = 2.8;shape/' out/expr_scene.txt > out/expr_scene_wrong.txt
sed 's/(x^2 + 9\/4\*z^2/(x^2 + 3\/4*z^2/' out/expr_scene.txt > out/expr_scene_wrong2.txt
> powershell.exe -NoProfile -File tools/verify_recursive.ps1 out/ch26_expressions.png -SceneFile out/expr_scene_wrong.txt -Stride 4
decoded by .NET: 400x200; pixels differing from the independent recursive tracer by more than 1 level: 855 (max difference 170); stride 4 in each direction, 5000 pixels checked
> powershell.exe -NoProfile -File tools/verify_recursive.ps1 out/ch26_expressions.png -SceneFile out/expr_scene_wrong2.txt -Stride 4
decoded by .NET: 400x200; pixels differing from the independent recursive tracer by more than 1 level: 220 (max difference 224); stride 4 in each direction, 5000 pixels checked
What is not here
Only polynomials. sin(x) + y, sqrt(x^2 + y^2) โ 1 and abs(z) are not polynomials in t along a ray, so
the exact root finders of The torus and other polynomial surfaces do not apply to them; they need a different solver, bisection on
interval bounds of the expression itself, which is a page of its own.
How it is checked
> v2_interp.exe tests/run.patlang --node numbers/expressions --depth 2
[ ok ] Expressions
[ ok ] Arithmetic
[ ok ] Integers, decimals and exponents are exact: 3, 0.25 = 1/4, 1e2 = 100, 2.5e-1 = 1/4
[ ok ] X is x, y is y, z is z
[ ok ] Against the formulas
[ ok ] Five surfaces at 300 random points equal their formulas written out (1500 evaluations)
[ ok ] The heart as text is the heart of Chapter 20, term for term
[ ok ] Scripts
[ ok ] An equation lhs = rhs is lhs - rhs
[ ok ] Errors
[ ok ] An unknown name is named, with its place
[ ok ] The surface
[ ok ] Surface_from_text gives an implicit shape
checks: 7 passed, 0 failed, 0 blocked, 0 skipped, 0 not run
ALL PASSED
Graduate Attributes
Modelled on this page
- Researcher: A separate interpreter is used to verify the system and uncover a case sensitivity bug in the original implementation.
- Critical Thinker: The limitations of the polynomial approach are clearly defined by excluding non-polynomial functions and explaining the need for different solvers.
- Digitally Fluent: Technical constraints such as exponent limits are explained as practical safeguards against rendering failures rather than arbitrary rules.
University of Reading Graduate Attributes framework.