# Phase 3, lib-features: as shipped The phase-2 library fixes (rewrite-a/b friction), then stroke joins and caps, bulk rects and points, data that grows, and a game, each driven by a new example in `sketches/noc` written from scratch (the Processing port in `~/05-genizah/noc-2-processing-port` read for behaviour only). Paths are relative to `lib/sketchbook/` unless they start with `sketches/`. ## API added ```zig // ---- sk.Clock (src/sketch/clock.zig) ---- pub const Clock = struct { hz: f32 = 60, owed: i64 = 0, // was f64 seconds; now ns, down to -slack count: u64 = 0, pub fn steps(c: *Clock, in: *const Input) u32; pub fn tick(c: *Clock, dt: u64) u32; // was dt: f32 seconds; now ns (`e.tickDt()`) pub fn stepNs(c: *const Clock) i64; }; // ---- sk.math (src/math/) ---- pub fn noise(seed: u32, x: f32, y: f32, z: f32) f32; // same signature, new distribution pub fn uniform(r: std.Random, lo: f32, hi: f32) f32; // random(lo, hi) pub fn randomUnit(r: std.Random) Vec; // PVector.random2D() // ---- sk.draw (src/sketch/draw.zig) ---- pub const Join = enum { miter, round, bevel }; pub const Cap = enum { butt, round, square }; pub const Stroke = struct { width: f32 = 1, join: Join = .miter, cap: Cap = .butt, closed: bool = false, miter_limit: f32 = miter_limit }; // Tessellation (L1): pub fn strokePath(t, gpa, points: []const Vec, style: Stroke, xf: Affine) Error!void; pub fn fillRect(t, gpa, r: math.Rect, xf: Affine) Error!void; pub fn strokeRect(t, gpa, r: math.Rect, width: f32, xf: Affine) Error!void; // strokePolygon / strokePolyline keep their signatures (now strokePath underneath). // Pen (L2): new fields `join: Join = .miter`, `cap: Cap = .round` (Processing's defaults) pub fn Pen.outline(p: Pen, closed: bool) Stroke; pub fn polyline(f: *Frame, points: []const Vec, pen: Pen) void; // beginShape()/endShape() pub fn rect(f: *Frame, r: math.Rect, pen: Pen) void; pub fn point(f: *Frame, at: Vec, pen: Pen) void; // a dot `width` across // line() now honours pen.cap (round, the default, is the old stadium). // ---- sk.Derived (src/sketch/derived.zig; exported from root.zig by render-features) ---- pub fn Derived(comptime T: type) type; // { value: T, key: ?u64 = null, // stale(d, key: u64, in: *const Input) bool, forget(d) } // ---- abi.Input (render-features' file, asked for and agreed on the board) ---- pub const MouseButton = enum(u16) { left = 1, middle = 2, right = 3, _ }; pub fn mouseHeld(in, button: MouseButton) bool; pub fn mousePressed(in, button: MouseButton) ?Event; // first press this frame, with x/y pub fn mouseReleased(in, button: MouseButton) ?Event; // ---- host (src/host/fields.zig, script.zig, Console.zig) ---- pub fn fields.formatPath(layout, memory, path, w) !void; // scalars, or `{ ... }` of everything under a path // script: `print FIELD` (stderr, no frame); `console get` takes no frame; // `get`, `print` and a failed `expect` show vectors/arrays/structs as values. ``` ## Decisions - **Clock slack.** Counting integer nanoseconds alone does not fix it: a step at 60 Hz is 16 666 667 ns, a frame 16 666 666. Two allowances, both an eighth of a step (2 ms at 60 Hz): a tick within it of a whole number of steps counts as exactly that many (vsync snapping), and a step is due once `owed` is within it (so `owed` may sit a little below 0). With the snap, a 60 Hz display steps exactly once a frame; with the early step, measured vsync jitter (frames up to 1.5 ms late) still gives 1 a frame at 60 Hz and 0,1,0,1 at 30 Hz. A slack as small as the old helper's 1 µs would not cover jitter, and plain rounding (step at half a step) puts the threshold exactly where a 30 Hz clock on a 60 Hz display lands. It stays per tick, so N×1 == 1×N; all integer, so replays are bit-equal. `owed` changed type, so a saved clock resets `owed` (a fraction of a step) on migration; nothing else. - **Noise.** The same table-free hash-lattice gradient noise, two changes: the octave sum is scaled 0.7 instead of 0.5/0.9375 (measured on 200 000 points: sd 0.109 in 3D, 0.110 in 2D, 0.116 in 1D, against Processing's 0.108/0.123/0.142; flow_field's grid 0.109 vs 0.111; range ≈ 0.07..0.94, no clipping), and each octave is offset by fractions of the golden ratio so integer inputs are no longer exactly 0.5. Gradient (Perlin) noise rather than Processing's value noise: no visible grid, and the mean is 0.5 (Processing's is 0.47). New goldens, checked natively and on wasm32. flow_field now uses it (`noise(seed, x·0.1, y·0.1, 0)`, the seed from `random(10000)` as the book does); its picture has the book's swirls and streams (looked at). `src/processing_noise.zig` stays: render-features keeps noise_walker on it (design.md decision 3). - **Scripts/console.** `formatPath` walks every leaf under a path and sorts by offset, so `{ .count = 12, .hz = 60 }` is memory order, not declaration order (Zig reorders struct fields); good enough to read, and stable for a build. Capped at 64 values plus "... N more". Failed exact expects already printed the found value (core-host); now vectors print too. Only `get` became frameless among console lines: `diff` is read-only as well, but the game's console.script counts frames after it. - **Random in a range: tiny helpers, not a README line.** `uniform(rng, lo, hi)` and `randomUnit(rng)` are free functions over `std.Random`: no wrapper type, the generator stays std's in State. They replace the two most frequent spellings in the ports (`std.math.lerp(lo, hi, r.float(f32))` 5× in angular_forces' init; two lerps per random vector). - **Joins and caps.** Built into the existing stroker, keeping its contract (disjoint, positively wound triangles; an outline the web fills to the same region): a round join is a fan over the circular segment beyond the bevel triangle, a round cap a fan over the half disc beyond the butt end, a square cap a butt cap moved out by half a width. Arc points sit in the outline in travel order, so the web's path is the same shape. `Stroke.closed` sits in the style struct (SVG's `Z`) rather than a positional bool. Pen defaults are Processing's (miter, round), so `line` is unchanged. A zero-length open path is a dot with round or square caps, nothing with butt (SVG). - **State vs Store for growing data** (README "Data that grows"): - Koch and the L-system keep only the **generation** (one byte) in State. Their data is a pure function of it: 65 536 segments (1 MiB) at Koch generation 8, an 88 940-character sentence at L-system generation 5, and their tessellations. Putting them in State would copy them into every snapshot and seek; a `List` big enough would be 8 × 1 MiB in the state file for nothing. Store is wrong too: it is not rewound by a seek, so it would need the same key anyway, and it outlives the process for no reason. So they live in Session as `sk.Derived`, rebuilt when the generation differs (a click, a seek, a step) and on the first frame after a reload (new code may derive differently: the Koch reload edit flips the peaks, and the picture follows). The timeline scripts check it: a screenshot after a step back shows the previous generation, after stepping forward again the same picture as played. - The quadtree's **points** are what `update` changes (a drag adds them), so they are a `List(Vec, 4096)` in State (32 KiB). Its **tree** is derived, and cheap: rebuilt in `f.scratch` every frame (2000 inserts), no cache. - Store is for the user's work that is not a function of State. The library piece is `sk.Derived` (~25 lines): the key check plus the reload rule, which is the part easy to forget. - **Turtle push/pop** is recursion: `[` calls `walk` with a copy of the transform, `]` returns. No stack type needed; `Affine` is the state. - **Flappy Bird structure.** The book's version only prints "OOPS!" and flies on. Added, as a game needs: a round ends on a hit (nothing steps while `over`), a click or space starts the next (`newRound` resets bird, pipes, score; keeps `best` and the generator), the score counts a pipe once the bird is past it. Optional fields are not reflected in State, so "which pipe was hit" is `over: bool` + `hit: u8`. Text uses `f.print` over a translucent `rect` panel so pipes do not hide it. - Two book quirks: 5.13 centres y on `width / 2` (the cloud sits on the bottom edge), changed to `height / 2`; its root boundary is twice the canvas (half-sizes = width, height), kept, since it decides where the first split lines fall. ## Examples (sketches/noc, `// phase 3: lib-features` rows) Lines non-blank, non-comment (as loc-before.txt), against the Processing port's .pde files counted the same way. | example | Zig | Processing | drives | notes | | --- | ---: | ---: | --- | --- | | path_following (5.8) | 84 | 184 | `polyline`, round joins, translucent thick stroke, no-fill | road = black α55 over white = Processing's gray 200; `expect-pixel` checks 200 at both joins (blended once). Debug geometry computed by one `aim` used by `update` and `draw`. | | quadtree (5.13) | 101 | 156 | `strokeRect`/`fillRect` in bulk | ~700 outlines + 2000 points in one `shape`; query dots in a second. Debug build: ~6.5 ms a frame headless (3000 frames in 19.5 s). Drag adds points (the book's video version). | | koch (8.5) | 54 | 58 | growth ×4 a click, `sk.Derived` | one round-joined `strokePath` through all points; generation 5 is the book's picture. | | lsystem (8.9) | 77 | 64 | growth ×8 a click, turtle push/pop | step halves per generation so the tree keeps the book's size (6 px at 4). | | flappy_bird (11.1) | 113 | 94 | text, score, round over, restart | +score, best, end of round, restart, text panels over the book. | Each has `test/.script` (screenshots looked at and compared with the Processing sketch's picture), `test/.timeline.script` (the template, with its own input; koch and lsystem add step-back/step-forward screenshot checks), and a reload edit + `test/.reload.script` (State kept, screenshots differ): road colour, query square colour, Koch peaks pointing down (a derivation change, so it checks that `Derived` rebuilds on reload), L-system angle 25° → 35°, green pipes. ## Tests - clock.zig: N×1 == 1×N over 600 random ticks plus a stall; 6000 script frames at 60 Hz give exactly one step each; vsync with up to 1.5 ms of lateness gives 1 a frame at 60 Hz and alternating 0/1 at 30 Hz; a dropped frame is 2; 144 Hz on 60 averages 2.4. - noise.zig: smoothness and range; spread on flow_field's grid over 50 seeds (sd 0.095..0.13, mean 0.5 ± 0.02); no exact 0.5 at 100 lattice points; new goldens (native and wasm32-wasi). - math: `uniform` range, `randomUnit` length. - draw.zig: every join × cap × width (2, 12, 30) × transform (identity, mirror, place) on the zig-zag, a closed square, and the path-following shape at width 40, all through the contract checker (disjoint, positive, area equals the subpaths'); stadium area = round-capped segment, square cap area, zero-length dots; rect fill/stroke areas, many rects in one. - derived.zig: stale on key change, after reload, after `forget`. - fields.zig: `formatPath` for a vector, a lane, a struct, a struct element, an array of structs, a long array (cut off), an unknown path. - test/replay.script: `print`, `console get` of a vector and a struct element (checked with `expect-log`), and `expect updates 46` before and after: reading takes no frame. - Existing ports: re-ran all scripts after the Clock and noise changes. Every `clock.count` rose by 1 (60 frames now 59 steps after the dt-0 first tick, not 58) and the positions with it; flow_field's values changed with the noise. Only values (and three comments that explained the old 58/59 offset) were changed, in 10 ports' scripts. The walkers' scripts (noise_walker.reload, random_walk) shifted the same way, one step; render-features, who rewrote the walkers this phase, updated them, and the new counts are the correct ones. - All pass at the end: `zig build test` in lib/sketchbook, `zig build e2e` in sketches/noc (all examples, the other agents' included), and the game's `zig build test e2e`. ## Left - `diff` in scripts still costs a frame (the game's console.script relies on it); `print` covers reading. - `formatPath` prints memory order; declaration order would need the layout to keep it per struct. - Koch generation 8's segments (0.1 px) are shorter than the 2 px stroke, so most joins are the stroker's documented overlapping case: invisible in opaque black, would double-blend if translucent on native. - A Pen-level `strokePath` with dashes, and arcs/ellipses (no example needs them yet). - `Derived` keys are u64: a sketch deriving from many fields hashes them itself (`std.hash.Wyhash` over the values, not over padded bytes).