Lesson 2.5 · II The language
Data from files
What this is about: a model should be able to use data someone else described: game pieces in a JSON file, sizes in a table. There are two steps for that: the first reads a file as text, the second turns the text into values. And there is one rule: nothing is guessed. What usually happens silently when files are read – the character encoding, line endings, the decimal comma, missing values – is written out in the model.

1. Two steps
let data = json(read("hex_tiles.json", encoding: "utf-8"), null: false)
read reads the file and gives its text, exactly as it is
– line endings included. json turns that into values.
Keeping them apart has two reasons. Each step can be checked on its own:
an error in the encoding is a different thing from an error in the JSON,
and the message says which step failed. And the steps combine: the same
text can be read with json, csv or
lines, and json also takes a text written in
the model.
2. Nothing is guessed
The character encoding has to be given; there is no default. Allowed
are "utf-8", "utf-8-bom",
"latin-1", "windows-1252",
"utf-16le" and "utf-16be". A byte that does
not fit the encoding is an error with line and column, never a silent
replacement character:
error: read: byte 78 (line 4, column 14) is not UTF-8 – is the file in another encoding,
"latin-1" perhaps?
The byte order mark (BOM, three invisible bytes at the start of a
file) is not passed over silently either: if there is one, you say
"utf-8-bom", and the other way round. (In UTF-16 the BOM
tells the order of the bytes; it is read and must agree with the one
given.)
A text file from Windows is rarely Latin-1 but mostly Windows-1252:
there the bytes 0x80 to 0x9F are characters like €, „“ and –, in Latin-1
invisible control characters. So such a byte with "latin-1"
is an error that points to "windows-1252".
Line endings are the second classic trap. A file
from Windows ends its lines with \r\n. Whoever splits it
with split(text, "\n") has an invisible \r on
every value. That is why only lines cuts a text into lines,
and it too needs the line ending: "lf",
"crlf", "cr", or explicitly
"any". Another kind in the text is an error:
error: lines: line 1 ends with \r\n, not with "lf" – the file mixes line endings, or has
others: say ending: "crlf" (or "any")
Whether the last line has a line ending does not matter – that is taste, not a trap.
null is the third. The language has no
value for "nothing", and json does not bring one in: such a
value seeps through the whole model until a computation fails somewhere
else entirely. Instead, null is an error naming the place
in the JSON (in .tiles[0].river), unless you say what it
stands for: json(text, null: false).
3. The path is written out
read("hex_tiles.json", encoding: "utf-8") // fine
read(name ++ ".json", encoding: "utf-8") // error: the path has to be written out
The path has to be a fixed text in the call, like the name after
import. Then what a model depends on is known
before it runs. The cache (Lesson 4.2) takes the file's
content into the fingerprint of every statement that mentions
read: if the file changes, it is computed again; otherwise
everything comes from the cache. The browser knows which files to have
ready.
Only files inside the project are read: relative to the model, no
.., no absolute paths. Subfolders are fine
("data/tiles.json"). A model with its data is a folder that
gives the same everywhere, on the command line as in the browser.
4. JSON becomes values
JSON fits the existing values almost completely: objects become
records, arrays lists, then numbers,
true/false and texts. So JSON feels as if it
belonged to the language, as in Clojure. Fields are read, taken apart
with patterns, filtered with comprehensions:
let rivers = [t.id | t <- data.tiles, t.river != false]
fn land("forest", k) = … // equations with text patterns
fn land("village", k) = …
Only one thing does not fit on its own: JSON keys are often no valid
names – "tile-size". Such fields are written as a text, in
a record, when reading it, and in a pattern:
let size = data["tile-size"]
let r = {"road-type": 2, width: 3}
match r { {"road-type": t} => t, _ => 0 }
A record is shown with such names in quotes, so whatever is shown can
be written as model text again. For data whose fields are not known
beforehand there are keys(r), has(r, "name")
and get(r, "name", otherwise); kind(v) says
what a value is ("number", "text",
"list", "record" …) – for JSON with a number
in one place and a list in the same place elsewhere.
Deeply nested data is a matter of recursion, as any tree is. In the
example mobile, mobile.json describes a mobile
of any depth: a node is a rod with a node at either end
(left, right), or a flat piece
(shape). One function goes down the tree and works out what
each branch weighs; a second hangs every rod where it balances, by the
lever rule; a third puts the pieces together. Optional fields come with
get(n, "thread", 20), the kind of node from
has(n, "rod"). Change a weight or add a branch, and the
whole mobile balances itself anew. What the file cannot promise, the
model checks: a thread too short for the piece below it to clear the rod
above is an error that names the piece.

What does not happen: [1, 2, 3] does not become a point
by itself. A list stays a list; it becomes a point with
point(xs). Otherwise whether ++ joins lists or
fails would depend on the content.
5. CSV becomes a list of records
A CSV file is a table of rows. In the language it becomes a list of records, one record per row: everything there is for lists works, without a new type.
let rows = csv(read("heights.csv", encoding: "windows-1252"),
separator: ";", decimal: ",", header: true, ending: "crlf",
columns: {id: "text", height: "number", label: "text"})
let tall = [r.id | r <- rows, r.height > 3]
Each setting is required, because each one prevents a trap. A German
CSV file has ; and a decimal comma; "2,5" with
decimal: "." is an error, not the number 2. The columns
come in the file's order, each with its kind ("number",
"text", "bool"); with a header, its names must
be exactly these. A row with too many or too few fields is an error with
its line number. Fields in quotes may hold the separator and line
breaks, and a quote in them is doubled (""), as the CSV
standard has it.
6. In the browser
The browser, too, reads only what the model names with
read("…"). Since the path is written in the text, it is
known before the model runs: from an open folder the page fetches
exactly these files, and everything else stays unread. The files reach
the modeller as bytes, not as text. Otherwise the
browser would have guessed the encoding already, and
encoding: would be decoration. Lesson 4.1 shows how to see
and edit the files in the browser.
7. Tables with axes
A list of records is enough as long as rows are gone through. Often,
though, the rows are the points of a grid: a height for every ring,
every layer and every angle. Then you want to look up, not to search.
table declares columns axes:
let t = table(rows, axes: ["ring", "layer", "angle"], value: "h")
t.cell({ring: 2, layer: 1, angle: 45}) // a number
t.slice({ring: 2}) // a table: layer × angle
axis(t, "angle") // [0, 45, 90]
A CSV file is always two-dimensional, rows by columns; more
dimensions only come from reading it this way, and there may be as many
as you like. Looking up goes by the axes' values, not
by positions: angle: 45 is right even if the file is sorted
otherwise. Numbers on an axis come in ascending order, texts in the
order they first came.
Here too, nothing is guessed. Two rows for the same place are an
error. A place no row has is one too, unless missing: says
what stands there – as null: does for JSON. A value an axis
does not have is an error that names the ones it has:
error: cell: axis "ring" has no 3 – its values: 1, 2
cell needs every axis, slice leaves at
least one. What comes back is always clear: a value or a table, never
one sometimes and the other at other times. entries(t)
gives the cells as records again, for comprehensions. Not there:
interpolating values between the grid's points.
8. Fonts: bytes, not text
A font file is no text; an encoding makes no sense for it. So
read_bytes gives the bytes as they are, and
lettering turns them into the letters' outlines as exact
curves: quadratic Bézier pieces for TrueType, cubic ones for OpenType
with CFF, each contour joined with chain into one closed
NURBS curve.
let font = read_bytes("fonts/DejaVuSans-Bold.ttf")
let glyphs = lettering("knotflow", font: font, size: 12) // [{outline, holes}]
export letters("knotflow", font, 12, 1.5) // one solid (prelude)

Which contour is a hole – the inside of an o, of an A, the two of an
8 – is decided the way a font is filled: by the nonzero
rule. Every contour winds round the points inside it, one way
or the other (TrueType and CFF run opposite ways, so the direction alone
says nothing); where the windings add up to zero, nothing is filled.
Each contour is looked at in a dozen places along it, just inside and
just outside: filled inside and not outside makes an outline, the other
way round a hole. Several places vote, because contours may overlap: the
cedilla of a Ç lies over the bottom of the C. Both are outlines then,
and letters joins them. Each glyph is decided on its
own.
lettering is the building block. letters
lives in the prelude, written in the language: extrude the outline, take
the holes away with difference, join everything with
union so that letters that touch become one solid. Whoever
wants to engrave instead writes their own function from it. The tag in
the example name_tag measures the text with
bounds and fits the plate.
Here too nothing is guessed. A character the font has no glyph for is
an error ("the font has no glyph for '日'"), not an empty box, and so is
a picture font without outlines (emoji). \n starts a new
line at the font's line height. What is missing is said: kerning only
from the old kern table, no ligatures, no scripts that join
letters or run right to left. For names and labels in Latin script that
is enough.
9. Drawings: SVG
A shape is often easier drawn than described. svg takes
the text of an SVG drawing and gives its filled areas in the same form
as lettering: {outline, holes} per area, with
id and fill as the file has them – to sort by
colour, say for a print with two filaments.
let shape = svg(read("heart.svg", encoding: "utf-8"), unit: "document")[0]
export raised(svg(…), 2) // every shape stood up (prelude)

The curves stay exact: lines, quadratic and cubic Bézier pieces as
drawn, elliptical arcs as rational pieces, nothing approximated. The
drawing is turned the right way up: in SVG, y points down; here it
points up, and the bottom left corner of the drawing's area
(viewBox) is the origin. Seen from above, the shape looks
as it does in the drawing program.
The unit has to be said, because an SVG drawing
counts in units of its own. unit: "document" takes the
file's width and area (width="60mm" with
viewBox="0 0 100 90": a unit is 0.6 mm); a width without a
unit is an error, since it would have to be guessed. "px"
(1/96 inch), "mm", or a number (millimetres per unit) you
say yourself.
Which contour is a hole is decided here by the drawing's fill
rule (nonzero or evenodd), as the
drawing program shows it: a contour filled inside and not outside is an
outline, the other way round a hole. As with fonts, this is checked in a
dozen places per contour; a path that runs through itself is cut into
loops at the crossing. Contours that cross each other are an error under
evenodd (their overlap would be a hole), and under
nonzero only "filled or not" counts: two holes that overlap
take the overlap away too, where a drawing would fill it again. What
else a drawing can hold is an error with a hint, not silently left out:
text ("turn it into paths, or use lettering"), clones
(<use>), masks, elements with a stroke but no fill.
Of CSS only simple class rules are followed
(.cls-1 { fill: none }), as some drawing programs write
them.
The example cookie_cutter turns the shape into a cookie
cutter: a thin wall along the outside (offset), a brim on
top to press on, each a band made with difference, joined
with union.
10. Pictures: a field per pixel
A picture is a grid of numbers, and the language has a type for that
already: the field (lesson 3.13). image turns a PNG file
into a field, relief a field into a closed solid whose top
follows the values:
let picture = image(read_bytes("knot.png"), channel: "luminance", cell: 0.3)
export relief(1 - picture, height: 2.2, base: 0.8) // a lithophane

A lithophane is held against the light: where the plate is thick,
little light comes through, and the picture shows. Hence
1 - picture – dark places are to be thick. That is ordinary
arithmetic on fields, cell by cell; blur smooths the
picture first if needed.
Here too everything is said. Which channel
("gray", "red", "green",
"blue", "alpha" or "luminance")
has to be said; a colour picture with "gray" is an error,
not a silently chosen average. The values run from 0 (black) to 1
(white) as stored: the file's gamma is not undone
silently – whoever wants that computes it (picture ^ 2.2).
The size of a pixel in millimetres (cell)
is required. A transparent pixel is an error with its coordinates,
unless transparent: says what value it has. The top row of
the picture is at the top, the bottom left at the origin, as with SVG. A
picture has at most 4 million pixels (2000 × 2000). A photo from a phone
is scaled down first; a print shows no more than about 10 pixels per
millimetre anyway.
Values between the pixels: sample
A field does not have to end up as a plate.
sample(field, (x, y)) gives its value at any point, mixed
linearly between the centres of the cells. That turns a picture into a
function you can ask anywhere. The Moon in Lesson 1.3 is built like
this: a NASA map with two heights per degree (720 × 360 pixels, 16 bits)
becomes a field, and every point of the sphere asks for its height:
let heights = image(read_bytes("moon_heights.png"), channel: "gray", cell: 0.5)
fn km(v) = (v * 65535 - 20000) / 2000 // 16 bits: half metres above a base level
fn surface_height(lon, lat) = km(sample(heights, (lon + 180, lat + 90)))
cell: 0.5 makes the pixels half degrees, so that
(lon + 180, lat + 90) is directly the place on the map. The
picture's values run from 0 to 1; km turns them into
kilometres, as the map's description says. The rest of the model, rings
over the lines of latitude and a loft through them, is in
examples/moon.kf.
Try it
cargo run --release -p kf -- render examples/hex_tiles.kf -o out/hex_tiles.png
In examples/hex_tiles.json, change an edge from
"meadow" to "forest", and trees stand on the
tile. Remove "river" from a tile altogether, and
t.river becomes an error – then
get(t, "river", false) helps.