summaryrefslogtreecommitdiff
path: root/README.md
blob: 123b2bc06595aaab9c400c114f5d2842b2764cb8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
# sketchbook

A small Zig 0.17 platform for sketching games and toys, in the spirit of
Processing and pygame: write plain data and two functions, save, and the
running program picks up the new code with its state intact.

```zig
const sk = @import("sketch");

pub const State = struct { x: f32 = 480, y: f32 = 300, hue: f32 = 0 };

pub fn update(s: *State, in: *const sk.Input) void {
    if (in.pressed(sk.Key.space)) s.hue += 30;
    s.x += (in.mouse_x - s.x) * 0.1;
    s.y += (in.mouse_y - s.y) * 0.1;
}

pub fn draw(s: *const State, f: *sk.Frame) void {
    f.clear(0x202020);
    f.fill(.{ .x = s.x - 10, .y = s.y - 10, .w = 20, .h = 20 }, 0xff8040);
    f.print(8, 8, 2, 0xffffff, "hue {d}", .{s.hue});
}
```

## An app

An app is an ordinary module. Every declaration is optional:

| Declaration | Meaning |
| --- | --- |
| `name`, `width`, `height` | Window title and initial canvas |
| `State` | Saved to a file, snapshotted, replayed: what `update` changes. No pointers and no host handles (compile errors). |
| `Session` | This process: survives reloads, never saved. Caches, image and buffer handles, playback cursors. |
| `Store` | On disk, at the same address in every run: survives reloads and restarts. Big data that is not replayed (a recording, a document). May point into itself; no host handles. |
| `init(state, host)` | Setup for brand-new state, after the declared defaults |
| `update(state, input)` | **Deterministic**: the host replays recorded input through it |
| `draw(state, session, store, frame)` | Pictures and sound, as commands; may change Session and Store |
| `command(state, session, store, console, line) !bool` | Console lines the host does not know |
| `commands` | Console completions |

Functions take the parameters they name, matched by type and in any order:
`draw(s: *const State, f: *sk.Frame)` and `draw(s: *const State, store:
*Store, ss: *Session, f: *sk.Frame)` both work. `update` can only ask for
`State` and `Input`; asking for more is a compile error, since a replay could
not reproduce it.

Memory comes by lifetime, one allocator each:

| Allocator | Lifetime | Released |
| --- | --- | --- |
| `f.scratch` | this frame | all at once, after the frame is drawn |
| `f.session` | this process | one allocation at a time; the rest when Session's layout changes, along with the images and buffers the session made |
| `f.store` | on disk, `<state>.store` | one allocation at a time; `--fresh` empties it |

A Store layout change migrates field by field like State: unchanged fields,
pointers included, keep their values, since the store never moves.
`command` gets the session and store allocators on its `Console`.

`update` sees only State, so when a key should do something to Session or
Store, State carries a request: `seek: sk.Request(f32)`, sent with
`s.seek.send(0.5)`. Session keeps an `sk.Handled`, and `draw` runs
`if (ss.seek.take(s.seek)) |to| ...` once per request. A fresh Session
counts earlier requests as handled, so nothing re-fires after a restart.

`input.width`/`height` are the canvas, which a sketch sets with
`f.canvas(w, h)` and the host scales to fit its window.
`input.window_width`/`window_height` are the room it has (the window, in CSS
pixels on the web): a sketch that sets its canvas to them, and lays out by
the canvas, is responsive, at its own scale on a phone as on a desktop.

`update` sees `input.events`: pointer, wheel, key, text, `cancel` (focus loss,
console) and one `tick` per frame carrying `dt`. Pointer and wheel events
carry the modifier keys held as they happened (`e.modifiers()`, `Key.Mod`
bits): read those, not `input.held`, for ctrl+wheel and the like, since a
trackpad's or a touch screen's pinch arrives as ctrl+wheel with no key
events at all. `update` is called once per frame, with that frame's events
ending in its tick, live and replayed alike; in `update`, `input.now` and
`input.dt` come from that tick (`dt` read back from the tick's f32
seconds, so a replay sees the same bits). `input.mouse_x`/`buttons`/`held`
follow the events fed so far. So time-driven and pointer-driven sketches
replay exactly. Fields no event carries (`width`, `window_width`,
`console`, `frame`) are not replayed: a sketch that reads them in `update`
can replay differently. `input.started` is true on the first update after
the program starts, never after a reload: state is saved, so this is where
to stop what should not resume on its own. In `draw`, `input.jumped` says
State got where it is other than by `update` from what the last `draw`
saw: the first frame, a seek, step, snapshot load, `set`, `reset`, play or
record start, a sketch command, a reload. Anything `draw` piles up in
Session (a trail in an offscreen image) is stale then; repaint it from
State.

`draw` gets a `Frame`: `clear`, `fill`, `shape`, `shapeColors`, `image`,
`imageAt`, `target`, `blend`, `text`, `print`, `clip`, `canvas`, `cursor`, `voice`, `audio`, `microphone`, `pixels`, `gpu`,
`compute`, `upload`, `download`, `openFile`, `run`, `quit`, plus the three allocators and
`f.host` (`loadImage`, `decodeImage`, `newImage`, `newBuffer`, `loadSound`,
`decodeSound`, `samples`, `readFile`, `env`, `log`, `textSize`). Commands may be built
from locals: the methods copy what they keep (text, GPU descriptions,
uniforms) into scratch. Bulk data (vertices, samples, pixels, uploads) is
not copied and must outlive the frame: scratch, session or store memory.

`f.text(x, y, scale, bytes, color)` draws one line from its top left
corner; scale 1 is a 13 px monospace face (8 px a character on a 16 px
line), and any scale works, 1.5 or 7.25. `f.host.textSize(scale, bytes)`
is the width and line height it covers, for laying out tables and code.
Natively the text is shaped by Pango and drawn at the canvas's own pixels,
with advances rounded to whole pixels at that size: sharp at any size, but
a width is not a multiple of the scale (ten digits are 80 px at scale 1,
230 at scale 3), so measure at the scale drawn. The font is Go Mono, built
in; `SKETCHBOOK_FONT="JetBrains Mono"` in the environment puts an
installed family before it. On the web it is the page's `monospace`, 8 px a
character.

`f.openFile("open", .{ .pattern = "wav;flac" })` shows the system's file
dialog; the answer comes back as the console line `open <path>`, so it
reaches the sketch's `command` like anything typed there. `f.run(line)`
does the same with any line, after the frame: `draw` cannot write State,
so this is how it tells State something only it learns (how many takes a
Store holds, say).

`f.download(buffer, .{ .size = n, .key = k })` reads a GPU buffer back
without stalling: the bytes arrive in a later frame's `in.downloads`, a
frame or two behind. For measurements a shader made (a pitch, a level),
not for pixels.

Geometry and colors are duck-typed. Anything with `x`/`y` is a point, anything
that also has `w`/`h` (or `width`/`height`) is a rect, in any number type, and
`@Vector`s or arrays work too. Colors are `r`/`g`/`b`[/`a`] or `0xRRGGBB`. The
`Color`'s constants also go by name (`f.clear(.white)`); its functions
need the type (`sk.Color.gray(220)`), since an `anytype` parameter gives a
decl literal nothing to resolve against. The helpers return the caller's
own type:

- `sk.shape`: `isPoint`/`isRect`/`isColor`, `contains`, `inset`, `offset`
- `sk.Camera`: `toScreen`, `toWorld`, `pan`, `zoomAt`
- `sk.tween`: `lerp` over any plain data, `lerpFields(a, b, t, .{ .x, .zoom })`, `toward(a, .{ .x = 100 }, t)`, and `ease`

The drawing layer below is the exception: new, and typed (`sk.math.Vec`,
`sk.Color`), so decl literals and completion work.

## Drawing shapes

Circles, lines and polygons are one host command, `Command.shape`: a
region in one colour, given as points, subpath ends and triangle
indices into the points. The web fills the subpaths (nonzero, one fill
per outline and the holes after it); native draws the triangles with
`SDL_RenderGeometry`. Both describe the same region, so translucent
shapes blend alike, and shapes keep their order among `fill`, `image`,
`text` and the clip. Both antialias: the canvas does, and native draws
4x4 samples a pixel (with a GPU renderer: runs of consecutive shapes go
into a supersampled layer, composited when another command comes) and
averages them; 2x2 on a canvas or target over 1920x1080, none over
3840x2160. Edges come out within a few levels of the web's, and a
1 px line on a pixel row stays full black on both.

`sk.draw` makes them, at two levels, neither with state of its own:

```zig
const ball: sk.draw.Pen = .{ .fill = .gray(127), .stroke = .black, .width = 2 };

pub fn draw(s: *const State, f: *sk.Frame) void {
    f.clear(0xffffff);
    sk.draw.circle(f, s.position, 24, ball);            // radius, not diameter
    const pen = ball.transformed(.place(s.position, s.angle)); // push, translate, rotate
    sk.draw.line(f, .{ 0, 0 }, .{ 24, 0 }, pen);        // round ends
    sk.draw.polygon(f, &.{ .{ 30, 0 }, .{ 26, -4 }, .{ 26, 4 } }, pen);
}
```

A `Pen` is plain data (`fill: ?Color`, `stroke: ?Color`, `width`, `join`,
`cap`, `xf: Affine`), so it can be a `const`, a State field, or a copy
changed for one call. A null fill is `noFill()`, a null stroke
`noStroke()`. `circle`, `line`, `polyline` (Processing's `beginShape()` /
`endShape()`, open), `polygon` (`endShape(CLOSE)`), `rect` and `point` (a
dot `width` across, Processing's `point`) tessellate into `f.scratch` and
emit a shape for the fill and one for the stroke; out of memory, they log
and drop it, as `emit` does. Joins are `.miter` (bevelled past 4
half-widths), `.round` or `.bevel`, caps `.butt`, `.round` or `.square`;
the defaults are Processing's (miter, round).

```zig
// A translucent road with round joins: each pixel blended once, joins included.
const road: sk.draw.Pen = .{ .stroke = sk.Color.black.alpha(55), .width = 40, .join = .round };
sk.draw.polyline(f, &s.path, road);
```

Underneath, an `sk.draw.Tessellation` is the shape as a value the caller
owns: `fillCircle`, `strokeCircle`, `fillPolygon` (simple polygons,
concave too), `strokePolygon`, `strokePolyline` (mitered, bevelled past 4
half-widths), `strokeLine` (round ends), `fillRect`, `strokeRect`, and
`strokePath(t, gpa, points, .{ .width, .join, .cap, .closed, .miter_limit
}, xf)`, which the other strokes are, append to it with an allocator and
an `Affine`. A round join is the circular segment beyond the bevel, a
round cap the half disc beyond the end, so they stay disjoint like the
rest; a square cap is a butt cap half a width further out. Emit it with `f.shape(&t, color)` or as
`.{ .shape = ... }` yourself, put many shapes in one (1000 boids in two
commands; a quadtree's 700 outlines and 2000 points in one), or hand
`t.triangles(gpa)` to a GPU pass. Shapes of many
colours share one command through `f.shapeColors(&t, colors)`, a colour
per subpath (`t.ends`): fading particles batch too. A stroked circle is
two subpaths, its outline and its hole, which take the same colour. `appendPoint`,
`endSubpath` and `appendTriangle` build shapes of your own.

What the functions guarantee: triangles that do not overlap, wound
clockwise on screen (mirroring transforms included), covering exactly
what the subpaths do. One case cannot keep it: a stroke that overlaps
itself (a self-crossing polyline, or segments shorter than the stroke is
wide at an acute turn) blends twice natively where it overlaps and once
on the web. Circles get as many segments as keep them within a quarter
pixel of round, after the transform. `tools/shapes_web.mjs` (`zig build
test-web`) draws the same frame in headless Chrome and compares it with
the native screenshot, pixel for pixel away from edges.

## Offscreen images, blending, placed images

Processing's canvas that is never cleared is an image you draw into.
`host.newImage(w, h)` makes one, transparent; `f.target(img)` sends the 2D
commands after it there (any of them: `sk.draw`, `fill`, `image`, `text`),
`f.target(.none)` back to the canvas, and the image keeps what was drawn,
frame to frame, until `f.image` shows it:

```zig
pub const Session = struct { trail: sk.Image = .none, drawn: u64 = 0 };

pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void {
    if (ss.trail == .none or f.in.jumped) {
        if (ss.trail == .none) ss.trail = f.host.newImage(width, height);
        ss.drawn = 0;
        f.target(ss.trail);
        f.clear(.white);
    } else f.target(ss.trail);
    while (ss.drawn < s.steps) : (ss.drawn += 1) sk.draw.circle(f, at(ss.drawn), 24, pen);
    f.target(.none);
    f.image(ss.trail, .{ .x = 0, .y = 0, .w = width, .h = height }, .{});
}
```

The image is a cache in Session, never truth: after a seek or a load
(`in.jumped`) it is repainted from State, so what a seek shows is what
playing showed. Natively a target is supersampled whole and holds
premultiplied colour, so it looks the same whether its steps were painted
one a frame or all at once, and translucent edges are not darkened when
it is drawn. A frame starts on the canvas.

`f.blend(.add)` adds what follows (colour times alpha, and alpha: canvas
`lighter`; natively a custom SDL blend, since SDL's `ADD` keeps a
transparent target's alpha), `f.blend(.alpha)` goes back. It applies to
`fill`, shapes and images; `clear` and `text` ignore it. Each frame starts
with `.alpha`. There is no `multiply`: SDL's differs from the canvas's for
translucent colours, and images have no fixed-function equivalent.

`f.imageAt(img, xf, .{})` is `imageMode(CENTER)` under a transform: the
image centred on `xf`'s origin, along its axes (`.translate(x, y)`,
`.place(at, radians)`), at its own size or `.size`. Underneath,
`Command.image.corners` places an image anywhere an affine can. A tint
multiplies colour per channel and alpha as a whole, alike on both hosts
(the web multiplies the pixels itself, cached per tint, as canvas
compositing cannot where an image is translucent). Natively images sample
nearest; the web antialiases a turned image's edges.

## Math, time and lists

`sk.math` is the geometry the `vector` module uses too (`vector.geom`):
`Vec = @Vector(2, f32)`, so `+`, `-`, `*` and `+=` work on points as on a
shader's `vec2`; free functions; `Affine` transforms; cubic Béziers; and
noise. Processing's PVector, by name:

| PVector | `sk.math` |
| --- | --- |
| `add`, `sub`, `mult` by a vector | `a + b`, `a - b`, `a * b` |
| `mult(k)`, `div(k)` | `scale(a, k)`, `scale(a, 1 / k)` |
| `mag()` | `length(a)` |
| `normalize()` | `normalize(a)` (zero stays zero) |
| `setMag(m)` | `withLength(a, m)` |
| `limit(m)` | `clampLength(a, m)` |
| `heading()` | `angle(a)` (radians; not in shader code, `atan2` uses tables) |
| `PVector.fromAngle(r)` | `unit(r)` |
| `dist(b)` | `distance(a, b)` |
| `dot(b)`, `cross(b)` | `dot(a, b)`, `cross(a, b)` (the z of the 3D cross) |
| `lerp(b, t)` | `mix(a, b, t)` |
| `translate(p); rotate(r)` | `Affine.place(p, r)`, or `.translate(x, y).mul(.rotate(r))` |
| `random(lo, hi)` | `uniform(rng, lo, hi)` |
| `PVector.random2D()` | `randomUnit(rng)` |

`sk.math.noise(seed, x, y, z)` is smooth noise in 0..1 like Processing's
`noise()` (four octaves, each half the last): gradient noise on a hashed
lattice, no table, so the seed can live in State. Unused axes are 0. Its
spread is Processing's (a deviation of about 0.11, nearly all of it in
0.1..0.9, so `noise → angle` turns all the way round), and integer
inputs are not special: each octave is offset off the lattice. It gives
the same bits natively and on wasm32 (a golden-value test runs on both).
For random numbers keep a concrete `std.Random.Xoshiro256` in State (not
`DefaultPrng`, an alias that may change) and pass `s.rng.random()`;
`uniform(rng, lo, hi)` is `std.math.lerp(lo, hi, rng.float(f32))` by
another name, and `std.Random` has the rest (`floatNorm`,
`uintLessThan`).

`sk.Clock` steps a simulation at a fixed rate from the recorded ticks:
`clock: sk.Clock = .{ .hz = 60 }` in State, `for (0..s.clock.steps(in)) |_|
step(s);` in `update`. It owes at most 8 steps per tick and drops the rest
after a stall; `count` is the steps taken; `set clock.hz 30` is slow
motion. A frame of N ticks steps exactly as N frames of one. It counts
integer nanoseconds and allows an eighth of a step either way, so at the
display's rate it steps once a frame, jitter and all: a 60 Hz frame is
16 666 666 ns, a 60 Hz step 16 666 667, and 60 frames are 60 steps.

`sk.List(T, capacity)` is a list for State: `buffer` and `len` (public, so
`boids.buffer[3].pos[0]` works in the console), `slice`, `constSlice`,
`appendBounded` (`error.OutOfMemory` when full), `orderedRemove`,
`swapRemove`. Every method clamps `len` to the capacity, which matters
after a reload that shrinks it. The default buffer is the element's own
defaults, never `std.mem.zeroes` (an enum may have no 0).

**Data that grows.** State is snapshotted, replayed and migrated, so it
holds what `update` changes, at a size fixed in its type. Store is not
snapshotted or replayed, so what is in it does not follow a seek. Three
cases, by who needs the data:

- `update` needs it: a `List` in State, sized for the worst case (the
  quadtree's 4096 points, 32 KiB; flocking's 2048 boids).
- Only `draw` needs it, and it follows from a few State fields: keep
  those fields in State and the data in Session, rebuilt when they
  change. A Koch curve's 65536 segments are a function of its
  generation, one byte; an L-system's 89 000-character sentence of its
  generation too. `sk.Derived(T)` is that: `if (ss.curve.stale(s.generation,
  f.in)) rebuild(...)`; it is stale when the key changes (a click, a
  seek, a step) and on the first frame after a reload, since new code
  may derive it differently. A cheap derivation needs no cache at all:
  the quadtree builds its tree in `f.scratch` every frame.
- It is the user's work, not a function of State (a recording, a
  document): Store.

The timeline then needs nothing more: a seek changes the key like an
update does (`sketches/noc`: `koch`, `lsystem`, `quadtree`).

**Sound scopes**, in the `scope` module (import `sb.modules.scope`): a
`scope.Scope` kept in Session takes samples with `push` and, once a frame,
`draw`s the views given rects for: the last seconds as a scrolling waveform
and spectrogram, the smoothed spectrum of the newest samples, and an
oscilloscope. All analysed and drawn on the GPU, new columns only; its
shaders swap to WGSL for the web like any others. Lifted from micscope's
live view; spheres uses it.

**Vector graphics**, in the `vector` module (import `sb.modules.vector`):
SVG parsing (the static subset Typst emits, and more) into cubic Bézier
data; flattening, stroking, dashing, trimming, clipping and morphing as
geometry; and `vector.Renderer(.gpu)` or `vector.Renderer(.cpu)`. The CPU
backend computes exact coverage and runs anywhere, wasm included. The GPU
backend describes one pass (8× MSAA, gradients in a shader): convex fills
drawn directly, the rest stencil-then-cover, all batched into layers of
non-overlapping fills, a few draws per layer whatever the shape count. Both are tested against resvg (see `sketches/vecanim` in the game repository).

**GPU work is data.** A sketch describes pipelines (shader code, vertex
layout, blend, stencil) and passes (`f.gpu(.{ .image, .pipelines, .draws,
... })`); the native host runs them with SDL_GPU, the web host with WebGPU.
Both cache shaders and pipelines by content hash, so an edited shader is
just a new pipeline after a reload. No sketch touches a graphics API. The
shaders are GLSL; the build turns them into SPIR-V for native and WGSL for
the web, and each build imports the form its host reads (see Build API). `abi.gpu.pipeline(Vertex, ...)` derives the
vertex layout from a struct, and `abi.gpu.uniform` checks std140 at
compile time. A pipeline without attributes makes its own vertices from
`gl_VertexIndex` (a full-screen triangle, for shader-toy style views).

Compute is data too. `host.newBuffer(size)` makes a GPU storage buffer,
`f.upload(buffer, offset, bytes)` fills it, `f.compute(.{ .kernel, .readonly,
.readwrite, .uniforms, .groups })` runs a compute shader over buffers, and a
draw reads buffers through `.vertex_storage` / `.fragment_storage`. Results
stay on the GPU: a compute shader's output is a later draw's input, with no
readback. Each dispatch is its own compute pass, so it sees everything the
commands before it wrote.

Sound is declarative. `f.voice(.{ .key, .audio, .serial, .loop, .volume })`
declares a voice that should be sounding. A new key or serial starts it, and
an undeclared key stops it. A finished one-shot stays finished while it is
still declared, so replays and seeks never re-fire sounds. `f.audio(key,
samples, .{})` streams PCM, and `input.stream(key)` reports what the host has
queued and played. `f.microphone()` keeps the default recording device open
while declared, and the next frame's `input.microphone` holds what it heard
(to `draw` only: it is a device, not an event, so it does not replay).
`host.samples(audio)` gives a loaded sound's samples, mono at
`input.sample_rate`.

Sounds decode with single-file C libraries in `vendor/` (dr_wav, dr_flac,
stb_vorbis): WAV, FLAC and Ogg Vorbis, chosen by content.

## The host

- **Hot reload.** It watches the library file and loads each new build through
  a private copy.
- **State file.** `<name>.state` holds the live state plus 7 snapshot slots,
  shared via `MAP_SHARED`. Its header carries the reflected layout, so a
  layout change migrates every slot field by field, with enums matched by tag
  name, and `sketchbook-probe` can print any sketch's state. Arrays and
  vectors migrate element by element: the elements both layouts have, each
  field by field, so an element type can gain a field and a capacity can
  grow (new elements take their defaults) or shrink (the rest is dropped; a
  count field such as `sk.List`'s `len` is kept, and `List` clamps it where
  it is read). An array whose type is unchanged is copied whole. Files from
  before element leaves (`SKETCH01`) are read and rewritten; a file that
  is not a state file is refused, never truncated.
- **Store file.** `<name>.state.store` is a heap mapped at a fixed address
  (`0x2000_0000_0000`, 64 GiB reserved), grown in place, locked to one
  process. Power-of-two size classes with free lists in the file. Snapshots
  and replays do not cover it (only `draw` and `command` change it).
- **Time travel.** Recordings, replay, seek and step work on any sketch,
  because they only need state bytes and events. A recording is whole
  frames; playback, `seek` and `step N` (frames) stop only between them.
  Restoring a snapshot (play, seek, step, `load`) clears the pointer,
  button and key state, and a recording begins with events that bring back
  what was held when it started (a pointer move, a button or key down), so
  a replay starts from the same input whatever the live pointer did since.
  A recording carries a hash of the build that made it; `play` warns when
  the running build differs (edited `update`, a new compiler), since the
  replay may then diverge.
- **Console and overlays.** `get`/`set <field path>` (`get` of a vector,
  array or struct shows its values, in memory order), snapshots, recordings and
  the memory and scope overlays come from the host; unknown lines go to the
  sketch. Paths index arrays and vector lanes: `get pos[0]`,
  `set boids.buffer[3].pos[1] 20`. `diff N` compares live state with
  snapshot N leaf by leaf, so padding (a Debug `@Vector`'s spare lane)
  never counts.
- **Scripts** (`--headless --fresh --script file`) drive the same routing and
  frames as a player: `click`, `key`, `hold`/`release` (a key down until
  released, for modifiers), `wheel`, `type`, `console`, `print field`
  (to stderr, no frame: a vector, array or struct prints every value in
  it, `{ 300, 200 }`), `expect field value`
  (`expect pos[0] 250 ~0.5` within a tolerance; a failure prints what it
  found),
  `await field value [~tol]` (frames until it holds, a minute at most),
  `expect-snapshot N` (live state equals snapshot N, leaf by leaf, printing
  the first differences), `expect-log`/`expect-no-log text` (the console's
  recent lines), `expect-audio`, `screenshot`,
  `expect-same-screenshot a b [max [x y w h]]`,
  `expect-different-screenshot a b [x y w h]`, `expect-pixel file x y r g b
  a [tol]`, `load`, `reload`, `await-reload`. A failed
  `expect`, or a console line that errors (a sketch command returning an
  error included), fails the script. Headless always means offscreen, even
  with `SDL_VIDEO_DRIVER` set, and GPU work still runs, into a texture. A
  scripted `--fresh` run works on files of its own (`<state>.<pid>`),
  renamed to the given `--state` at exit, so two builds running the same
  script at once do not share them.
- **Export.** `--export DIR` plays the sketch headless, from fresh state,
  and saves every frame as `DIR/000000.png`, `000001.png`, ...;
  `--export -` writes them to stdout instead, as raw RGBA:

  ```sh
  demo --export frames --size 1920x1080 --frames 600
  demo --export - --size 3840x2160 --fps 60 --frames 600 |
      ffmpeg -f rawvideo -pix_fmt rgba -s 3840x2160 -r 60 -i - -pix_fmt yuv420p out.mp4
  ```

  The frames run on a clock of their own: frame k is k/fps seconds in
  (`--fps N`, 60 unless given) and its tick is exactly 1/N s (frame 0's
  is 0, as any run's first), however long a frame takes to draw. A sketch
  that takes its time from the ticks exports the same frames every time.
  It ends after `--frames N`, or when the sketch calls `f.quit()`;
  `in.exporting` tells a sketch that nobody is watching, so a player
  hides its controls, plays through and quits. `--size WxH` is the room
  for the canvas (`in.window_width`/`height`, and the first canvas): a
  sketch that sets its canvas to the room exports at any size. An export
  keeps state files of its own and removes them, so it can run beside a
  player. `--export` plays no script.
- **GPU.** The host's 2D renderer runs on an SDL GPU device, which also
  runs sketches' GPU passes. Without a GPU it falls back to any renderer.
  `--profile-gpu` times every upload, dispatch and pass alone on an idle
  GPU (SDL_GPU has no timestamp queries) and prints count, mean, worst and
  per-frame time by `label` at exit.
- **Memory.** SDL allocations go through a leak-checking allocator; a leak
  fails the exit. SDL's Vulkan backend leaked when `vkAllocateMemory`
  failed and it fell back to another memory type (it happens with many
  headless hosts at once); the build compiles that file with the fix.
  It also never defragments memory there: SDL moves textures to new ones
  inside whichever command buffer is submitted next, and a sketch's GPU
  pass is submitted while the frame's 2D commands are still being
  recorded, so the canvas lost what was drawn before the pass and showed
  the previous frame under the rest (after a large texture was freed).

## The web host

`web/host.js` runs the same sketch, compiled to wasm32-freestanding, in a
page. Draw commands go to a 2D canvas; GPU passes, dispatches, uploads and
downloads to WebGPU, whose renders are shown through the canvas; streams and
the microphone to Web Audio (at 48 kHz where the browser agrees, sound
starting at the first click or key, as browsers require); `f.openFile` to a
file picker, whose sound the browser decodes and hands over by name before
the console line arrives. `f.run` and the sketch's `command` work as on
native.

Touch: one finger is the mouse's left button. Two fingers pan, as the wheel
(60 px a notch), and pinch, as ctrl+wheel (a notch per 20 % of spread), both
around the point between them: what a trackpad sends, so a sketch that
handles a trackpad handles a touch screen. Keys have no touch equivalent;
draw buttons for what matters.

Without WebGPU, the page says why the first time the sketch asks for it:
not a secure context (WebGPU and the microphone need https, or localhost),
WebGPU turned off (Firefox on Linux: `dom.webgpu.enabled`), or no usable
adapter.

`.web = .{ .pwa = .{ .icons = ..., .theme = ... } }` makes the page an
installable app that opens offline: a manifest, icons, and `web/sw.js`, a
service worker that keeps a copy of everything the page fetches, network
first, so each new build shows as soon as there is a network. Service
workers need a secure context, like WebGPU.

For tests, `window.sketch` reads state (`field(path)`), runs console lines
(`command(line)`) and hands over decoded sound (`sound(name, samples)`).

## Build API

```zig
const sketchbook = @import("sketchbook");

pub fn build(b: *std.Build) void {
    const sb = sketchbook.init(b, .{ .target = target, .optimize = optimize });
    const app = sb.app(.{ .name = "demo", .root_source_file = b.path("src/main.zig") });
    _ = app.addSteps(.{ .scripts = &.{b.path("test/play.script")} });
}
```

`addSteps` installs the executable and adds `run`, `lib`, `probe`,
`export` (`zig build export -- frames --size 1920x1080`: what follows `--`
is `--export`'s directory, or `-`, then its options), `e2e` and
`test`, and with `.web = .{}` also `web` (the page into `zig-out/web`) and
`serve` (it, over https on port 8042, to the local network too; `zig build
web --watch` alongside rebuilds it for the next reload). Every piece is also available on its own
and returns plain `std.Build` objects:

| Call | Returns |
| --- | --- |
| `app.addLibrary()` | the hot-reloadable shared library |
| `app.addExecutable()` | host and sketch linked into one binary |
| `app.addScriptExecutable()` | the same, built in `script_optimize` mode, as `e2e` plays scripts with |
| `app.addWeb(.{ .assets = ... })` | the wasm module and a ready-to-serve directory, built from the app's modules with every shader module swapped for its WGSL twin; tests can read its state by path (indices too: `list[2].x`) with `sk_field` (numbers) and `sk_tag` (enum tag names) |
| `app.addServe(install)` | `miniserve` serving an installed web directory over https, on every interface, with a self-signed certificate made once by `openssl`: https makes the page a secure context on any device, which WebGPU and the microphone need. Its defaults are environment variables, so miniserve options after `--` replace them |
| `app.addRun(lib, .{})` | the generic host running the installed library |
| `app.addScript(exe_or_lib, file, .{})` | a headless, fresh-state scripted run, of the executable or of the library through the host (so the script can `reload` it) |
| `app.addExport(exe, .{ .fps, .frames, .size })` | a headless export of the executable's frames, as PNGs in `.frames`, a directory of the cache |
| `app.addProbe(state)` | the probe on a state file |
| `app.addTest(.{})` | tests with the app importable as `app` |
| `app.addReloadCheck(.{ .script, .edits })` | a check that the app hot-reloads with State kept (below) |

`sketchbook.init(b, .{ ..., .script_optimize = .ReleaseSafe })` builds
the executables `e2e` plays scripts with in another mode than the rest,
for sketches whose per-pixel loops crawl in Debug; null (the default) is
`optimize`. Only Zig code changes mode (the host's and the app's), so it
costs one more compile, not SDL's. A `b.option` makes it a `-D` flag.

**Hot reload, checked.** `addReloadCheck` builds the app's library as
written, and again from a copy of its sources with textual edits applied,
then plays a script on the first through the generic host with `{v2}`
defined as the second:

```zig
const check = app.addReloadCheck(.{ .script = b.path("test/reload.script"), .edits = &.{
    .{ .file = "src/main.zig", .old = "0xff8040", .new = "0x40c0ff" },
    .{ .file = "shaders/glsl/expo.frag", .old = "vec3(0.0, 1.0, 0.0)", .new = "vec3(1.0, 0.0, 0.0)" },
} });
steps.e2e.dependOn(&check.run.step);
```

Each `old` must occur exactly once in its `file` (a path as given to
`b.path`), or the build fails. The copy is of each directory holding a
source the app builds from (a module's root directory holds what it
imports), and every module and shader set made from it (`addShaders`,
`addZigShaders`) is made again from the copy, so edits to Zig code, GLSL
and Zig shaders all reach the second library. The script plays, checks
State, runs `load {v2}`, checks the same State, and compares screenshots
(`expect-different-screenshot a.png b.png [x y w h]`). Pausing a replay
first (`record`, `play`, `pause`) keeps the State still, so the two
screenshots differ only by the edit. `sketches/shaders` and
`sketches/noc` (bouncing_ball) have one each.

Shaders:

```zig
const shaders = sb.addShaders(.{
    .layouts = .{ .module = my_layouts, .types = &.{ "Vertex", "Paint" } },
    .sources = &.{ b.path("shaders/fill.vert"), b.path("shaders/fill.frag") },
});
const app = sb.app(.{ ..., .imports = &.{.{ .name = "shaders", .module = shaders.module }} });
// in the sketch: .{ .code = shaders.fill_vert }
```

The layouts are Zig structs (tagged with `pub const glsl = .vertex` or
`.{ .uniform = .{ .set, .instance } }`) written out as `<Name>.glsl` for the
sources to `#include`, so the Zig struct is the one definition. Each source
is compiled by `glslc` into `shaders.module`, as SPIR-V under its file name
(`fill.vert` is `fill_vert`). For the web it is compiled again with
`SKETCHBOOK_WEB` defined and translated by `naga` into `shaders.web`, the
same names in WGSL; `addWeb` puts that twin in place of the SPIR-V module
wherever the app's imports reach it, however deep (the `vector` module's
shaders included). Only the web build runs `naga`, and a missing tool
fails only the steps that need it, listing where it looked. WGSL has no
write-only storage buffers and no `coherent`: write them plain, or under
`#ifndef SKETCHBOOK_WEB`. Sources may `#include` files beside them;
`glslc`'s depfiles tell the build, so editing an included file recompiles
what includes it. `addGlslLayouts` and `addGlslc` are the pieces, for
anything else.

Shaders can be Zig too: `sb.addZigShaders(.{ .sources, .imports })`, one
shader per file with `export fn main() callconv(.{ .spirv_fragment = .{} })`,
returns the same `Shaders`, so a sketch cannot tell the language. Zig's own
SPIR-V backend compiles each for `spirv32-vulkan` (`spirv64` asks for
physical pointers, which naga refuses), self-hosted (through LLVM the
object comes out empty, silently); `tools/spirv_strip.zig` then drops the
`Aligned` operands Zig puts on every load and store, which Vulkan accepts
and naga's reader does not; and naga translates the result for the web as
for GLSL. Shader code cannot use table-driven `std.math` (`atan2`: call
GLSL.std.450 through inline assembly), and a uniform struct shared with
the CPU needs a vec2 that is `@Vector(2, f32)` only on SPIR-V and `[2]f32`
elsewhere. `sketches/shaders` has five Book of Shaders examples in both
languages.

Tools: `glslc` (shaderc, or the Vulkan SDK's) for shaders, for web builds
with shaders `naga` (`cargo install naga-cli`; found on PATH or in cargo's
directory), and for `serve`, `miniserve` and `openssl`. This repository's
own tests also run `node` (noise on wasm32, under WASI) and, for `zig build
test-web`, Chrome.

`sb.modules`, `sb.host_exe` and `sb.probe_exe` are exposed for anything else.
Add `.sketchbook = .{ .path = "..." }` to your `build.zig.zon`.

## Known limits

- The console line holds 96 characters, so long paths cannot be typed;
  `f.openFile` answers with a line of any length.
- Every upload, compute dispatch and GPU pass is its own command buffer and
  submit. Fine at a handful per frame; batch them per frame if that grows.
- The store is not crash-safe: a crash in the middle of an allocation can
  leave it inconsistent, and `--fresh` starts it over.
- Handles inside Store containers (`std.ArrayList(sk.Image)`) are not caught
  at compile time: the check does not follow pointers.
- Native antialiasing resolves coverage per sample within a run of
  shapes, the canvas per shape, so where two shapes' edges meet the web
  can show a faint seam native does not. `fill` rects and images are
  antialiased natively only inside a target. Without a GPU renderer,
  native draws aliased. A stroke that overlaps itself blends twice
  natively where it overlaps, once on the web.
- On the web: nothing persists (Store lasts as long as the page),
  synthesised voices are silent, `loadSound` knows only sounds the page
  decoded, multisampling is 4× at most, and mixing runs on the main thread
  (a ScriptProcessor), so a busy page can crackle.

## Designs

- [Regions in source](docs/regions-in-source.md): editing layout from the
  running sketch by rewriting the number literals in the source (not
  implemented yet).

## The boundary

Host and sketch are built by the same `zig build`, so ordinary Zig types cross
it (slices, tagged unions, `std.mem.Allocator`). `abi.hash`, a comptime hash
of every shared type's layout, guards against the one real hazard: a host
refuses a library built against different definitions. Everything that outlives
a call lives in host memory, since host code is never unloaded. Only the
recorded `Event` and the reflected `Layout` are `extern`, because they are
written to disk.

`zig build test` in this directory runs the unit tests, a headless reload
through `dlopen`, where a counter sketch changes its layout mid-run and keeps
its values, and a replay test (`test/replay.script`): a recording played,
sought, stepped and replayed after a live pointer move, each ending on the
state it was stopped at.

The drawing layer's tests are there too: the shape cases drawn natively
and checked pixel by pixel (`test/shapes.zig`), noise's golden values on
wasm32 under Node, and the examples in `examples/` (`pen.zig`: Pens and a
Clock; `flock.zig`: tessellations batched by hand, between Frame
methods). `test/render.zig` covers targets (and that `set` and `load`
repaint them while plain frames do not), blending, placed and tinted
images and colours per subpath, checked pixel by pixel. `zig build
test-web` draws the shape and render cases in headless Chrome, compares
them with the native screenshots (`tools/chrome.mjs`), and times 5000
circles a frame (software Canvas2D here: about 12 ms as 5000 shapes, 8 ms
batched).