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
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
|
# 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});
}
```
## Examples
The standalone example packages live in [`examples/`](examples/):
- [`noc`](examples/noc/): 21 Nature of Code sketches. Select one with `-Dsketch=flocking`.
- [`shaders`](examples/shaders/): five shader examples in both Zig and GLSL.
- [`vecanim`](examples/vecanim/): vector animation scenes. Select one with `-Dscene=scenes/live.zig`.
- [`micscope`](examples/micscope/): records the microphone or opens sound files, plays them either way, and shows waveform, spectrogram and spectrum; a tuner.
- [`spheres`](examples/spheres/): the three-body problem on the GPU, each body a voice synthesised by a compute shader.
- [`live`](examples/live/): a tiny language for sound and picture, typed over its own picture: every line that parses is compiled to a tape one GPU interpreter runs per pixel and per sample.
- [`talk.zig`](examples/talk.zig): a talk with a slider in it, a sketch that runs its own `anim.Deck` (`zig build test-talk` plays it).
- [`manual.zig`](examples/manual.zig): Figure 2-1 of the Intel SDM comes alive, then ADD's opcode table is written row by row and its `80 /0 ib` turns into SUB's `80 /5 ib`: PDF pages as vector shapes and parts of them (`zig build manual -Dmanual=PDF`; see Animation, PDF pages and parts).
Run `zig build run` inside a package, with `zig build lib --watch` in a second
terminal for hot reload. `zig build test` runs its headless checks;
`zig build web` builds the selected example for the browser.
## An app
An app is an ordinary module. Every declaration is optional:
| Declaration | Meaning |
| --- | --- |
| `name`, `width`, `height` | Window title and initial canvas |
| `audio_pull` | Samples the sound device takes at once (see sound) |
| `State` | The one thing a sketch keeps: what `update` changes, saved in one file with its history, replayed. No pointers, no host handles, and at most 32 MiB, half of a save (compile errors). |
| `Session` | This process: survives reloads, never saved. Caches, image and buffer handles, playback cursors. |
| `init(state, host)` | Seed brand-new state, after the declared defaults |
| `setup(session, init) !void` | Initialize resources once per fresh Session, including startup with restored State |
| `update(state, input)` | **Deterministic**: the host replays recorded input through it |
| `draw(state, session, frame)` | Pictures and sound, as commands; may change Session |
| `command(state, session, 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(f: *sk.Frame, ss: *Session,
s: *const State)` both work. `update` can only ask for
`State` and `Input`; asking for more is a compile error, since a replay could
not reproduce it.
`setup` receives `*sk.Init` with `host` and the `session` allocator; it may
also request Session or Host directly. It gets no State, Input,
or Frame. Load assets and create/upload GPU buffers there, then use those
resources in `draw`. `try init.host.writeBuffer(buffer, offset, bytes)` submits
a copy immediately; the source bytes may be released when it returns. WebGPU
uploads require four-byte-aligned offsets and sizes.
Resource setup runs after Session defaults, once on startup even when State was
restored from disk, and again if a reload changes Session's layout. Compatible
reloads and ordinary state resets preserve the Session and do not rerun setup.
The browser invokes it during its initial setup too. A hook may return `void` or
`!void`; uncaught errors are logged and disable app callbacks, while the native
host console and 9P controls remain available. Restart after fixing a failed setup.
Use a Session error field and handle the error inside setup when the app needs
to display an initialization failure. `zig build test-setup` checks this lifecycle.
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 |
`command` gets the session allocator on its `Console`.
`update` sees only State, so when a key should do something to Session,
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). Interactive Wayland frames use the
display-paced clock for update and draw automatically; unsupported backends use
wall time, and the browser uses its animation-frame timestamp.
`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, a mark's `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`, `gain`, `audio`, `audioBuffer`, `microphone`, `pixels`, `gpu`,
`compute`, `upload`, `download`, `openFile`, `run`, `quit`, plus the three allocators and
`f.host` (`loadImage`, `decodeImage`, `newImage`, `newBuffer`, `loadSound`,
`decodeSound`, `newSound`, `samples`, `readFile`, `appendFile`, `writeFile`, `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 or session 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.textIn(face, x, y, scale, bytes, color)` is the same line in another
face of the Go family, all six bundled in the binary (`sk.Face`): `.mono`,
`.mono_bold`, `.mono_italic` for data and code, `.sans`, `.sans_medium`,
`.sans_bold` for what is said about it; and `.code`, `.code_bold`,
`.code_italic`, `.code_medium` are JetBrains Mono NL (no ligatures),
bundled too, for programs. `f.host.textSizeIn(face, scale, bytes)`
measures a line. The seven monospaced faces advance alike (0.6 em: whole pixels at 20, 25, 30, 35, 45
and 60 px and at their doubles), so columns of text need no measuring;
JetBrains Mono's line box is taller (ascent 1.02 em, where Go's is 0.945).
The web host draws every face as its one.
Text is shaped for the size it is drawn at, so under a camera that zooms
its letters would shift against each other from frame to frame.
`f.textScaled(face, x, y, scale, raster, bytes, color)` lays the line out
and rasterizes it at `raster` and draws that at `scale`, unsnapped: give it
the scale the move ends on (the larger of its ends) while the camera
moves, and `textIn` again once it rests. One texture serves the whole
move. The web host ignores `raster`.
`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 (which of its
files are already written, say).
`f.host.appendFile(name, bytes)` appends to a file of the sketch's own,
`<stem>.<name>` beside its save `<stem>.xitdb` (in `.sketchbook/` under
`zig build run`), creating it, and returns its path for `readFile` ("" when nothing
was written, and always on the web). Only `draw` and `command` can call it,
and a write is not replayed, like sound. `readFile` maps a file once, so
what is appended afterwards is not in what it returned.
`f.host.writeFile(name, bytes)` does the same to a new, empty file of that
name. micscope starts each take's `take-<id>.f32` so, and appends to it as
it records.
`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; sound a shader made goes to the speakers with
`f.audioBuffer` (see sound, below), which does not wait a frame.
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`, `point` (a
dot `width` across, Processing's `point`) and `dashed` (a polyline in
dashes, `.{ on, off }` along the path, each dash whole round a corner;
`Tessellation.strokeDashes` underneath) 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 kept in keyframes, replayed and migrated, so
it holds what `update` changes, at a size fixed in its type, 32 MiB at most.
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): a `List` in State, or, bigger than a save, files of the
sketch's own (`appendFile`), named from State, as micscope's takes are.
The timeline then needs nothing more: a seek changes the key like an
update does (`examples/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. Given `.camera`, the
rects are world rects: the views are made at their size there and drawn
through the camera, so panning or zooming recomputes nothing. A sketch
that analyses buffers of its own runs the same shaders:
`scope.kernels.{waveform, spectrogram, spectrum}` over any read-only
buffer of samples, `scope.pipelines.{wave, spectrogram, spectrum}` to
draw them, with the parameter and view blocks in `scope.layouts`
(`Scope.gpu.tape` is a Scope's own history on the GPU, for a kernel of
the sketch's). `scope.midi(hz, a4)`, `scope.hz(note, a4)` and
`scope.note_names` name pitches. 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 (`zig build diff`, below).
**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, and the size: a uniform block is 4096 bytes at most, all
SDL_GPU's Vulkan backend binds of one (a larger one was cut off without a
word), so more goes in a storage buffer. 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,
.fade, .rate, .group })` 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. `.rate` is its speed and so its pitch (2 is an
octave up and half as long; resampled by linear interpolation, cheap and
a little dull far from 1); changing it does not restart the voice.
`.group` (0-7) puts it under a gain the sketch declares each frame,
`f.gain(group, value)`, 1 when not declared: music ducks under speech by
the sketch lowering one number, and the host glides to a new gain over
10 ms so a step does not click. The host mixes the voices once a frame,
topping its queue up to 2048 samples (about 43 ms) ahead of the device,
so what `draw` declares is heard up to that much later.
`f.audio(key, samples, .{})` streams PCM, and `input.stream(key)` reports
what the host has queued and played, and its `underruns` (pushes that found
it empty though the frame before had pushed to it: each a gap). The sketch
chooses how far ahead it keeps a stream; `input.lead` is how far the host
would: the slowest of the last 64 frames' worth of samples (a stream is fed
once a frame), plus the device's pull (what it takes from a stream at once,
1024 samples by SDL's default), plus half a pull for each recent underrun.
A sketch that makes its sound as it goes pushes `in.lead -|
in.stream(key).queued` a frame, and a change it makes is heard after what
is queued ahead of it, about a pull: 19 to 27 ms after `draw` on this
machine at 60 Hz.
A sketch that must answer faster asks for a smaller pull:
`pub const audio_pull = 256;` beside its `name` has the host ask SDL for
256-sample pulls (5.3 ms) when it opens the device, and a change then
leaves in about 6.5 ms. The price is paid by the whole machine: the audio
server then runs every program's sound at that size, four times as many
wake-ups, and under load it misses one now and then, a dropout (a click)
in everything playing, not only the sketch. Without it SDL picks (1024 at
48 kHz). `SDL_AUDIO_DEVICE_SAMPLE_FRAMES` in the environment wins over
both, the web ignores it, it is read once, when the host starts, and the
sound overlay (`overlay sound`) shows what the device took (`pull 256`).
`f.audioBuffer(key, buffer, .{ .count
= n })` streams `n` samples a compute shader wrote (f32 from `.offset`
bytes): the host reads them back within the frame, waiting for the GPU's
work so far (about 0.2 ms), and queues them. A GPU synth is then:
```zig
const n: u32 = @min(f.in.lead -| f.in.stream(1).queued, max_block);
if (n > 0) {
f.compute(.{ .kernel = synth, .readwrite = &.{ss.block}, .uniforms = ..., .groups = .{ (n + 63) / 64, 1, 1 } });
f.audioBuffer(1, ss.block, .{ .count = n });
}
```
(`examples/spheres` is one.) `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`. `--export` writes frames only, no sound.
The host sums the voices and limits the sum, sample by sample: below
0.75 (-2.5 dBFS) it plays at true volume, to the bit; above, it bends
smoothly (same value and slope at 0.75) toward 1 and never past it, so a
full-scale peak plays at 0.875 and any number of loud voices stays
bounded. Streams are not limited: SDL adds each, as pushed, to the voice
mix and clips the total at ±1.
A sketch can make its own sounds: `host.newSound(samples)` copies mono
samples at `input.sample_rate` into the host and returns an `Audio` that
voices play like a loaded one, so a synthesised one-shot is replay-safe
too. Like every sound it lives as long as the host: make each once and
keep the handle in Session. `sk.sfxr` is sfxr, the classic generator of
game blips, coins, lasers and explosions (`sfxr.Params`, its usual knobs,
rendered at any rate; at 44.1 kHz to the bit as the original):
```zig
if (ss.blip == .none) {
var buf: [4096]f32 = undefined;
const n = sk.sfxr.render(.{ .freq = 0.5, .sustain = 0.05, .decay = 0.1 }, f.in.sample_rate, &buf);
ss.blip = f.host.newSound(buf[0..n]);
}
if (s.coins != 0) f.voice(.{ .key = 1, .audio = ss.blip, .serial = s.coins });
```
(`test/voices.zig` is this sketch.)
Sounds decode with single-file C libraries in `vendor/` (dr_wav, dr_flac,
stb_vorbis): WAV, FLAC and Ogg Vorbis, chosen by content.
## Animation
The `anim` module (`sb.modules.anim`) is manim-style animation written as
code: Typst for text and math, shapes, cameras, morphs, talks that wait
for clicks, and objects the scene draws itself. A scene is one file, and
`sb.addScene` builds the player around it:
```zig
const std = @import("std");
const anim = @import("anim");
pub const typst_preamble = "#set text(fill: white)";
pub const scene = anim.Scene(construct);
fn construct(s: *anim.Builder) void {
const eq = s.typst("$ a^2 + b^2 = c^2 $", .{ .y = 220, .scale = 1.4 });
const eq2 = s.typst("$ c = sqrt(a^2 + b^2) $", .{ .y = 220, .scale = 1.4 });
const square = s.rect(.{ .w = 180, .h = 180, .x = -320, .stroke = anim.blue });
s.play(.{eq.write()}, .{});
s.play(.{ square.create(), square.rotate(std.math.pi / 4.0) }, .{ .seconds = 1.5 });
s.play(.{eq.transformInto(eq2)}, .{});
s.wait(1);
// Updaters run every frame, on top of the timeline. Their extra
// arguments are bound here, like a closure's captures.
const swing = s.value(0);
s.always(square, wobble, .{swing});
s.play(.{ swing.to(0.3), anim.camera(.{ .zoom = 1.4 }) }, .{ .ease = anim.ease.outBack });
}
fn wobble(now: anim.Now, swing: anim.Value) anim.Pose {
var p = now.pose;
p.rotation += now.value(swing) * @sin(now.t * 4);
return p;
}
```
Objects are added (`typst`, `svg`, `rect`, `circle`, `line`, `arrow`,
`polygon`, `custom`, and `part` of another) and show in the order they
were added; each call returns a handle. Animations are methods of the handle: `write`, `create`,
`fadeIn`, `fadeOut`, `transformInto`, `move(.{ .x, .y, .scale, .rotation,
.opacity })`, `scaleTo`, `rotate`, `indicate`; plus `anim.camera(...)` and
`value.to(x)`. `play` runs a tuple (or array) of them together; its
options are `.seconds`, `.ease` (any `fn (f32) f32`) and `.lag`, manim's
lag ratio (0 by default, all at once): each animation starts `lag` of its
own length after the one before, in the order given, and the play still
lasts `.seconds`, the last ending with it, so each of n lasts
`seconds / (1 + lag * (n - 1))`; a lag of 1 plays them one after
another. An object two animations of one play change is timed by the
first. `wait` moves time on; in a live scene, `pause()` makes what
follows wait for a click (see Talks). Positions are scene units: 1280x720 of them show at
camera zoom 1, the origin in the middle, y down. The page behind them is
the scene file's `pub const background = 0xRRGGBB` (manim's grey without
one).
A scene is one of two kinds, which share every call:
- **Compiled** (`anim.Scene(construct)`): `construct` runs at comptime,
and what it recorded is played once, still at comptime, into keyframes
per object: a `from` and a `to` pose (plain structs), a time span and an
easing. Drawing an instant is a lookup and a `tween.lerp`, then the
object's updaters. The whole timeline is data before the first frame, a
morph can look ahead to where its target ends, a broken scene is a
compile error, and Typst strings are written inline.
- **Live** (`anim.Live(frame, typst)`): `frame(s: *anim.Frame)` runs every
frame, at runtime. Each `play` takes effect at once against `s.t`, so the
code after it reads and changes what shows, with no callbacks:
`s.pose(obj).y = ...`, `s.get(value)`, `s.camera()`, the mouse
(`s.pointer`), the time (`s.t`, which runs on while a pause waits) or
any runtime data. Its Typst sources are the declarations of the
namespace it is given (or a tuple of namespaces), since the build cannot
run it to find them.
Both answer the player the same way (`shot`: objects, poses, values,
camera, plays and gates at an instant), so the only state is the time and
the pauses clicked through, and scrubbing, seeking and hot reload are
free. A test checks that a live
scene and a compiled one with the same timeline show the same poses at
every instant.
**Typst.** `s.typst(source, pose)` takes Typst markup; the scene's
`typst_preamble` goes in front of each (by default a transparent page
that fits its content). The build runs a generator that imports the scene
file, reads `scene.typst_sources`, compiles each with `typst compile`
(cached by content in `.zig-cache/typst`) and embeds the SVGs. Nothing
scans files, and a scene without Typst needs no `typst`.
**PDF pages and parts.** Typst imports a page of a PDF as vector paths,
so a page is a Typst object like any other:
`s.typst("#image(\"/home/me/sdm.pdf\", page: 31)", .{})`. Typst runs with
`/` as its root, so an absolute path names the file where it lies; the
file is not part of the cache key, so one changed in place needs its entry
in `.zig-cache/typst` gone. Text is outlines: every glyph is a filled
shape (nothing to search or select), drawn crisp at any camera zoom, and
`write` reveals the shapes in the order the PDF draws them (in the Intel
SDM: header and footer, the text from the top, then the figures; a
table's text row by row, left to right, and its rules after all of it). A page
costs what its shapes do: Figure 2-1's page of the SDM is 2.1 MB of SVG
and 1954 shapes, parsed once, 6-12 ms, the first frame it shows; then, at
1280x720 in a release build, 0.9-1.7 ms a frame to record for the GPU
(0.4 ms on the GPU itself) or 2-5 ms on the CPU renderer. A table of
contents, dot leaders and all, is five times that: show a part of it.
`zig build bench` times the page beside the simple objects, with a budget
of its own. An SVG a Typst object includes (`image("x.svg")`) is kept the
same way.
`s.part(page, .{ .x, .y, .w, .h })` takes the shapes whose bounds' centre
lies in a rectangle out of an object, as an object of its own, so a field
of a figure or a row of a table can glow, be written, fly off or morph
while the page around it stays. The rectangle is in the object's units,
its centre and size: the literal `s.rect` takes to cover the same place
when the object stands at the origin at scale 1. Pick it with the guides
(G: lay the page at the origin, at scale 1, and read the pointer), or
from `pdftotext -bbox -f N -l N file.pdf -`, whose points from the
top-left of a W x H pt page are `(x - W/2) * 4/3` across and
`(y - H/2) * 4/3` down. The part stands where its shapes stood, around
the rectangle's centre (so `indicate`, `scaleTo` and `rotate` turn it in
place), and shows as the object does after the plays laid so far: taken
from a page that has faded in, it is there. The object draws the rest
from then on, at every instant. A shape goes to the first part that
takes it, so a rule that crosses several fields (a box's outline) stays
with whichever holds its centre: keep areas inside the rules. A table's
column rules run its whole height, so their centres all lie in one row:
take them first, with a band a point high through that centre. Parts of
parts, and of any vector object, work the same way, and share the
object's geometry (a page is parsed once however many parts it gives).
`transformInto` morphs into the whole of its target, so a morph's result
can be split by parts taken after it: `c0.transformInto(bits)`, then
`s.part(bits, ...)` for each run of bits.
`examples/manual.zig` is a talk in two slides on the SDM (Vol. 2). On
Figure 2-1 (page 31), the fields of the instruction format glow in turn,
`83 C0 01` is written below, each byte flies into its field and `C0`
splits into `11 000 000` over Mod, Reg and R/M. Then ADD's opcode table
(page 132) is written row by row; its row `80 /0 ib ADD r/m8, imm8`,
cut in pieces, becomes SUB's from page 1400, laid so that the rows
coincide: first the digit after the slash alone, then the rest, a morph
per piece, so the glyphs that stay hold still; the two rows end one over
the other. `zig build manual` plays it in a
window; the PDF is `-Dmanual=PATH` (`~/01-resources/intel-devref-ii.pdf`
by default), never part of the repository: without it the example builds
a scene that says so, and its script (`test/manual.script`, in `zig build
test` when the file is there) is skipped.
**Custom objects** are drawn by the scene's own code with 2D commands
(`sk.draw`, `f.fill`, `f.text`): what is runtime data, a register table, a
memory grid, a code panel. `s.custom(&data, pose)` adds one, where `data`
has `pub fn draw(self: *const T, f: *sk.Frame, at: anim.Placed) void`. It
is an object like the others: the same camera, pose, `play`, `fadeIn`,
`move` and place in the order.
```zig
const Bar = struct {
level: f32,
pub fn draw(b: *const Bar, f: *sk.Frame, at: anim.Placed) void {
// In the object's own units, around its origin.
sk.draw.rect(f, .{ .x = -100, .y = -20, .w = 200, .h = 40 }, at.pen(.{ .stroke = .white, .width = 2 }));
sk.draw.rect(f, .{ .x = -100, .y = -20, .w = 200 * b.level, .h = 40 }, at.pen(.{ .fill = .hex(0xf0ac5f) }));
at.text(f, -100, 26, 1.5, "rax", .white);
}
};
fn frame(s: *anim.Frame) void {
const bar = s.new(Bar{ .level = 0 }); // lives for this frame
const obj = s.custom(bar, .{ .x = -200 });
const level = s.value(0);
s.play(.{ obj.fadeIn(), level.to(1) }, .{});
s.play(.{obj.move(.{ .x = 200, .scale = 1.5 })}, .{});
bar.level = s.get(level); // after the plays: as it stands now
}
```
`at` (`anim.Placed`) is where the object stands: `xf`, its units to
canvas pixels (camera, then pose); `scale`, pixels per unit; `pose`
(`opacity`; `drawn`, 0 to 1 while a `write` or `create` plays, to reveal
by; `highlight`); `stage`, scene units to pixels; `t`; and `value(v)`,
every `Value` now, which is how a compiled scene's custom object (its
data a constant) moves. `at.pen(pen)` is a `sk.draw.Pen` in the object's
units at its opacity, `at.text` and `at.textSize` are `f.text` and
`host.textSize` likewise. Text scales and moves with the object but does
not turn. A custom object has no outline to `transformInto`.
Vector objects are drawn on the GPU into an image, then the image onto
the canvas; a custom object draws onto the canvas directly. So the
picture is built in runs: the vector objects up to a custom one, that
object's 2D commands, the vector objects after it, and so on, each run
its own image (8x multisampled, at the canvas's size: about 140 MiB of
GPU memory at 1920x1080 and 560 at 3840x2160, so add custom objects next
to each other in the order where it does not matter). Within its `draw`,
a custom object's commands keep their own order.
**The player** (`src/anim/player.zig`) fits the scene's frame into the
canvas, and its canvas is the room it has: the window, or an export's
`--size`. Its State is an `anim.Deck` (`deck.t`, `deck.playing`, ...)
and the viewer's settings. Keys: click, space or page down for the next
step of a talk (space plays and pauses a scene with no pause), page up or
backspace back a step, `]`/`[` the next/previous slide, P play/pause,
left/right previous/next play, `,`/`.` step a frame, home/end, up/down
speed, B GPU or CPU renderer, L loop (a talk holds its end instead), G
guides (boxes, origins and the scene's axes, in scene units); drag and
wheel to look around, R to reset the view. Exported, it plays through once without controls, each pause
held for the scene file's `pub const hold` seconds (1 without one), and
quits at the end:
```sh
zig build export -- frames --size 3840x2160
zig build export -- - --size 1920x1080 --fps 60 |
ffmpeg -f rawvideo -pix_fmt rgba -s 1920x1080 -r 60 -i - -pix_fmt yuv420p scene.mp4
```
A package of scenes is a few lines of `build.zig`:
```zig
const sb = sketchbook.init(b, .{ .target = target, .optimize = optimize });
const scene = sb.addScene(.{ .root_source_file = b.path("scenes/intro.zig") });
_ = scene.app.addSteps(.{ .scripts = &.{b.path("test/intro.script")} });
```
`scene.app` is an app like any other (`run` with hot reload: save the
scene and the animation carries on from the same instant; `lib`, `web`,
`export`, `e2e`), named after the scene file; `.imports` are modules for
the scene file besides `anim` and `sketch`. `test/scene_live.zig` and
`test/scene_compiled.zig` are small scenes of each kind, with a custom
object.
### Talks
A talk is a live scene that waits: run from the top every frame, it is a
function of its time and of the gates opened so far. Time never stops at
a gate. What was laid before it (plays still running, a `loop`, code
reading `s.t`) carries on, and what comes after waits in the future until
the gate opens. So a talk seeks, steps back and hot-reloads like any live
scene.
- `s.pause()` waits for the presenter's next step (a click, space, page
down). A click while a step plays finishes it, like Keynote: the
picture jumps to where the next pause is laid; the next click opens it.
Back cuts to the picture held before the last click.
- `s.gate(open)` waits for anything: it opens on the first frame at or
after it is reached on which `open` is not null, and returns that value
from then on (null before), a choice to branch on:
`const pick = s.gate(app.answer) orelse return;`. Code after a closed
gate would show nothing, so `orelse return` is the usual end. A gate
opens only in `update`, from what `update` sees (events and State), so
a recording replays to the same talk. One click opens one gate.
- `s.beside(f, args)` runs `f(s, args...)`, plays and all, from the
cursor, and leaves the cursor where it was: what follows runs alongside
(`s.beside(anim.Frame.clear, .{.{}})` fades a slide out while the next
one writes). `s.loop(f, args)` plays `f` again and again from the
cursor until the gate laid right after it opens; the cycle running then
completes. `f` only plays, and ends where it began. `s.clear(options)`
fades out everything that shows.
- `s.slide()` begins a slide. Next/previous slide goes to a slide's
resting picture: held at its first gate (the end of the slide if it has
none), every gate before it opened at once (a choice with 0) or undone.
The playhead is `anim.Deck`, plain data (`t`, `playing`, `speed`, `hold`,
and `log`, each gate opened: how long after it was reached, and its
value), so hot reload, snapshots, replay, scripts and the console see it
like any field; `deck.waiting`, `deck.slide`, `deck.gates` and
`deck.duration` say where the talk stands. The stock player keeps one, and
any sketch can keep its own beside its data: its `update` decides which
events ask for what (`anim.Ask`: `next`, `back`, `next_slide`,
`back_slide`, `to`, `end`), so the deck never owns the keyboard. The talk
takes the sketch's data after the frame: in `update` as `*App`, so the
talk may change it, and when drawn as `*const App`, so drawing cannot.
`anim.mutable(app)` is the app to write to, null when drawn; `s.events`
are this update's events in scene units (none when drawn); a widget laid
out before the pause it waits at takes a click by setting `s.next =
false`. `anim.Painter` draws a shot as the player does:
```zig
pub const typst = struct { pub const law = "$ x'' + 2 zeta x' + x = 0 $"; };
pub const scene = struct { pub const typst_sources = anim.sources(.{typst}); }; // for sb.addTypst
pub const State = struct { deck: anim.Deck = .{}, app: App = .{} };
pub const Session = struct { painter: anim.Painter = .{} };
const App = struct { presses: u32 = 0 };
const button: sk.Rect = .{ .x = -30, .y = 150, .w = 60, .h = 60 }; // scene units
pub fn update(s: *State, in: *const sk.Input) void {
s.deck.update(in, .{ .next = in.mouseReleased(.left) != null, .back = in.pressed(sk.Key.left) }, talk, .{&s.app});
}
pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void {
const shot = s.deck.shot(f.scratch, f.in, .{ 0, 0 }, talk, .{&s.app}) catch return;
ss.painter.paint(f, shot, @import("typst"), .{}) catch {};
}
fn talk(s: *anim.Frame, app: anytype) void {
const law = s.typst(typst.law, .{});
s.play(.{law.write()}, .{});
s.loop(pulse, .{law}); // runs on while the deck waits
s.pause();
const knob = s.circle(.{ .r = 30, .y = 180, .fill = anim.blue });
s.play(.{knob.fadeIn()}, .{});
if (anim.mutable(app)) |a| for (s.events) |e| if (e.kind == .mouse_up and button.contains(e.x, e.y)) {
a.presses += 1; // the knob's click, not the presenter's next
s.next = false;
};
const many = s.gate(if (s.next) @intFromBool(app.presses > 2) else null) orelse return; // a choice
s.play(.{if (many == 1) knob.scaleTo(2) else knob.fadeOut()}, .{});
}
fn pulse(s: *anim.Frame, o: anim.Obj) void {
s.play(.{o.indicate()}, .{ .seconds = 1.5 });
}
```
`sb.addTypst(module)` compiles the Typst of a module that declares
`scene.typst_sources` (a module of the sketch's file without the `typst`
import, see `build.zig`'s talk). Gates are known by the order they are
reached: insert a pause above where a talk stands and it lands a step
earlier. An edit that moves the last opened gate (a step above retimed)
moves `t` with it on reload, so the presenter stays on the same step, as
far into it. Exported (`in.exporting`), every gate opens `deck.hold`
seconds after it is reached, in the first frame's run, so the video shows
each wait for that long, loops running, and the frames are the same every
run; a sketch quits at `deck.t >= shot.duration`. `examples/talk.zig` is
a talk with a slider, a loop, a choice, two slides and `beside`.
## The host
- **Hot reload.** It watches the library file and loads each new build through
a symlink with a fresh name (a build must replace the file, as `zig build`
does, not rewrite it in place). `zig build lib --watch -fincremental
--debounce 0` makes a reload take tens of milliseconds instead of a second:
Zig recompiles only what the edit changed, and starts as soon as a file is
saved instead of 50 ms later. Its limits, with Zig 0.17.1: the incremental
linker is new, and a library of it that does not link libc loads only
through a host workaround that Zig 0.18 makes unnecessary; if a reload ever runs code other than what you
wrote, stop the watch and rebuild without `-fincremental`. The library is
larger (27 MB instead of 10 for a small sketch), the watching compilers
stay in memory (about 300 MB for a small sketch, 1.3 GB for a game with C
and shaders), and a save that touches several files may build more than
once. The cache grows with each start of the watch (65 MB for a game),
not with edits.
- **The save.** A sketch keeps one thing, State, in one file, its save:
`<name>.xitdb`, an xitdb database. Live State is process memory; the save
holds the present, its newest keyframe and the frames logged after it,
which a run restores and replays through `update` (played by another
build, the keyframe alone, and the run says how many frames it left),
so a run starts where the last stopped; and the history before it
(Sessions, below). `--fresh` starts from defaults and leaves the save as
it is. A keyframe is State in 4 KiB pages and writes only the pages that
changed since the keyframe before it, an all-zero page nothing: about 5
KB a keyframe for drat-meout's 20 KiB State, 10 KB for a 4 MiB State
edited once a minute. Each stretch carries the reflected layout, so a
keyframe from an older layout migrates field by field, with enums
matched by tag name, and so does live State at a reload. 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. A state
file from before (`<name>.state` beside the save, any of its formats) is
imported into a new save once: its State the present, its snapshot slots
marks `1` to `7`; the file is left as it was and not read again, and one
that is not a state file is said and left.
- **Where files go.** `zig build run` and `export` keep a sketch's files in
`.sketchbook/`: `<name>.xitdb` and the `<name>.<file>` it appends to. The
host makes the directory with a `.gitignore` of `*`, so neither git nor
jj takes in a save that grows (the jj snapshot a build makes would commit
one while it is under a megabyte), and moves in, once, the `<name>.state`
an older build kept in the project's root; when both exist, nothing moves
and the host says which is used. Without `--state`, a run keeps them in
`$XDG_DATA_HOME/<name>/` (`~/.local/share/<name>/` without it), which is
where a shipped game's go; a script or an export uses `sketch.xitdb` in
the working directory. `--state x.xitdb` and `--state x.state` both name
the save `x.xitdb`.
- **Sessions.** Every run is a session in the save: an append-only log of the events live `update` was fed, in whole frames, and
keyframes, the State at the start, every minute while it changes, at
every jump (`load`, `set`, `reset`, a seek, a sketch command), before and
after a reload, at every mark and at exit. Each stretch of a session
between reloads keeps its build's identity, its layout and the source it
was built from: the repository's revision (`jj:<commit> <change>`, else
`git:<sha>`, `+dirty` with uncommitted changes, read once per `zig
build`), Zig's version, the backend and the mode. Nothing in it is ever
overwritten, only dropped, oldest first, at the cap (below); marks and
clips are names pointing into it.
`App.Options.record` decides how much of it the save keeps, at build
time: null, the default, means Debug builds keep all of it, up to the
cap below. A build that does not record keeps the present and the marks
(and clips) only: at every keyframe it drops the frames and keyframes
before it, and at exit it compacts the file, so while it runs the disk
holds at most the last minute of input, and after, none. A playtest
build of a release opts in with one line, `.record = b.option(bool,
"record", "collect sessions in a release build")`. A script from
`--fresh` state records in memory (time travel works, nothing touches
the disk; it stops at 256 MiB, ten hours or more of play, keeping what
it has), a script without `--fresh` to the file, an export nothing, and
an export has no marks or clips, as the console says. The console's
status line ends with `rec file`, `rec memory` or `rec off`, and
`sessions` says where.
A commit is a second of play (of event time, so a script commits on the
same frames every run), and is made at once for a reload, a mark, a
clip's start or end, an export and exit; only a mark and exit are synced
to disk. A crash (a panic, `kill -9`) loses the frames not yet committed,
under a second (15 of 255 in the kill test): the next run starts from the
last committed frame's State, the session lists as `(crashed)`, and a
clip it left open ends where the session does. A power loss loses what the kernel had
not written back (30 s past the last sync, by default); the torn end is
mended at the next start, the file opened at its last whole commit, and
a file still unreadable is renamed to `<path>.broken.<seconds>`, never
deleted, and a new one begun.
A minute of drat-meout's play was 268 KB with the pointer moving every
frame (16 MB an hour), 164 KB idle (86 KB of ticks, the rest keyframes,
then whole States; a keyframe is about 5 KB now).
**The cap.** A save is at most 64 MiB, and State half of that, so
history has room. A commit that leaves the file past it drops history
oldest first, keyframes' pages and the frames logged with them, and
compacts the file to three quarters of the cap: a hitch of about 170 ms
for a 48 MiB file in a Debug build, once every 16 MiB of history. The
present is never dropped, nor the keyframe of the newest mark of each
name, nor the newest clip of each name and its frames. What was dropped
says so when it is asked for (`load #K`, `play session N`). A mark of a
new name needs room for a whole State: when marks fill the save it is
refused, saying how to make room, by saving over a mark's name (the
older one then goes with history) or starting another save (`--state`).
Every commit leaves the nodes it copied behind, about a kilobyte, which
the compaction removes too.
Playtests: `export-session [S] FILE` writes session S (this run's when
none is given) with its marks and clips to a database of its own, for a
player to send; `import FILE` adds the sessions in such a file to this
sketch's (`sessions` lists them as `import <file>`), its marks and clips
named `NAME@<file>`; `play session N` replays one, and its stretch names
the commit to build to replay it without divergence. What such a file holds
of the player: every input event (pointer positions, keys, the text typed
into the sketch), the console lines that changed State (an `f.openFile`
answer is a local path), and the date the session started; nothing about
the machine or the user.
- **Time travel.** Marks, clips, replay, seek and step work on any sketch,
because they only need state bytes and events. `save NAME` marks the
State now: a keyframe with a name, the newest of a name winning. `load
NAME` (or `load #K`, the K-th in `marks`) brings it back through the
layout it was taken in, migrated to today's, and `diff NAME` compares it
with live leaf by leaf over the fields both layouts have. `record NAME`
starts a clip from the mark `snapshot NAME` chose (saved first if it is
new, restored if it exists, so several clips branch from the same bytes)
and `stop` ends it; `play NAME` restores its keyframe and replays its
frames; `pause`, `seek start|end|MS` and `step N` (frames) move within
it, stopping only between frames. `play session S [at SECONDS]` replays a
past session from its start, or from the keyframe before that time,
paused there. At each later keyframe `update` produced, the replay is
compared with what was recorded: a difference is said once, `diverged
before frame F: N values, first <field>`, and the replay goes on from the
recorded State, which also carries it over the jumps the log does not
hold. A clip or session made by another build says so, since the replay
may then differ. Going back and playing on is `play` or `seek`, then
`stop`: live goes on from there in the same session, nothing
overwritten. Names are words of up to 32 bytes, and numbers are names, so
`save 3` and `play 0` work as they always have. Restoring State (play,
seek, step, `load`) clears the pointer, button and key state, and a clip
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. Event times are the session's:
`in.now` does not restart at 0 in a clip.
- **Console and overlays.** `help` lists the console's verbs and `help
VERB` says what one does. `get`/`set <field path>` (`get` of a vector,
array or struct shows its values, in memory order; `set` of an array of
numbers takes all its values), marks, clips,
sessions (`marks`, `clips` and `sessions` list the last few) and the
memory, scope and frame timing 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 NAME` compares live state with
mark NAME 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 NAME` (live state equals mark NAME, leaf by leaf,
printing the first differences), `expect-key WHY field value` (the
newest keyframe of this session taken for WHY, `before_reload`, `mark`,
`exit`..., holds the value, read in its own layout),
`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`, `kill` (death by SIGKILL,
for tests of what a crash keeps). 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 saves nothing: its sessions are in memory, and the
files it appends to are `<stem>.<pid>.<name>`, removed 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
saves nothing, and the files it appends to are its own, removed at exit,
so it can run beside a player. `--export` plays no script. In a release build on an RTX 3050,
an `anim` scene takes 6 ms a frame as raw RGBA and 21 as PNG at
1920x1080, 19 and 73 at 3840x2160; with ffmpeg encoding x264 from the
pipe, 11 and 41. The PNG encoder is the slow part: pipe, when the frames
are only on their way to a video.
- **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`,
`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 |
| --- | --- |
| `sb.addScene(.{ .root_source_file, .name, .imports })` | an `anim` scene file's player: `.app`, and `.module` and `.typst` (its Typst as SVG) |
| `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, its files in `.sketchbook/` |
| `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.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.
`sb.app(.{ ..., .record = true })` keeps history in every mode (see
The host); null, the default, in Debug builds only.
**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. `examples/shaders` and
`examples/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. `examples/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), `typst` for scenes with Typst in them, and for `serve`,
`miniserve` and `openssl`. This repository's own tests also run `node`
(noise on wasm32, under WASI), `typst`, `resvg` and `python3` with numpy
and Pillow (the renderers against resvg), `ffmpeg` if there is one, and,
for `zig build test-web`, Chrome.
`sb.modules` (`abi`, `sketch`, `host`, `vector`, `scope`, `anim`, and
`cloud9`, the 9P library, whose `Fsys` lets an app's tests dial its own
executable as `fs` does), `sb.host_exe` is 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.
- 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.
- A keyframe hashes all of State to find the pages that changed: about 70
ms for 32 MiB in a Debug build, 3 ms in ReleaseFast, once a minute while
State changes and at every jump.
- On the web: nothing persists and no
sessions are recorded, and multisampling is 4× at most. Every voice is
silent there, whatever its sound (loaded, decoded or made with
`newSound`), and so are groups' gains; `decodeSound` gives `.none`, and
`loadSound` knows only sounds the page decoded (opened or dropped
files). What does sound: streams (`f.audio`, `f.audioBuffer`) and the
microphone, mixed on the main thread (a ScriptProcessor), so a busy page
can crackle. A GPU buffer streamed there arrives a frame or two later
(WebGPU reads back only asynchronously), counted as queued meanwhile, and
`in.lead` is a fixed 100 ms.
The reusable GPU executor and the pardes integration are described in
[docs/pardes-rendering.md](docs/pardes-rendering.md), including the remaining
renderer migration work and the optional addon boundary.
## 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 hash of
every shared type's layout and of the zig version, backend and optimize
mode, guards against the real hazards: a host refuses a library built
against different definitions, or by another compiler or mode (`zig build
run` beside `zig build lib --watch -Doptimize=fast`: Zig's own calling
convention differs between them), and says what differs. The layout half
costs half a second of comptime, so a small program (`src/abi_hash.zig`)
computes it once per change of the abi sources, at build time, and host and
sketches import the number; it is computed for the build machine in Debug,
so a layout change seen only by another target or mode is not caught.
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 clip 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).
And the rest: `test/text.zig` (a box of `textSize` under each line),
`test/export.zig` (two builds export the same frames, frame k at k/fps;
the raw stream's length; a video from ffmpeg with as many frames), and the
`anim` player on its two test scenes: the live one checks, pixel by
pixel, that a custom object sits over the vector object added before it
and under the one added after, moves, fades and zooms with the timeline
and camera, on both renderers; the compiled one is also exported at half
size.
`zig build diff` (part of `test`) renders a corpus (`test/svg`: every
path command, fill rules, joins, caps, dashes, transforms, opacity,
gradients, symbols, and Typst documents) with resvg as the reference, and
with both vector backends through the real host, headless
(`test/svgview.zig`, `tools/svgdiff.py`). Every case is under 0.7 mean
channel error, with no more than 0.01% of pixels off by more than 48;
side-by-side images land in `.zig-cache/svgdiff`. Two details make the
reference fair: resvg samples coverage on four sub-scanlines, so it
renders at 4x and is box-filtered down (padded to whole blocks, not
squeezed); and sizes in `pt` make it round to whole pixels before
scaling, so the harness gives it unit-free sizes.
`zig build bench` (part of `test`, after the rest) times each Typst
object of the compiled test scene at 1280x720, the drawing filling the
canvas, in release mode, and fails if a simple one (30 shapes) takes 1 ms
to parse and draw: an equation of 8 shapes parses in 0.02 ms, draws on the
CPU in 0.25 ms, and is recorded as a GPU pass in 0.02 ms (the GPU's own
time is not measured).
### Optional native profiling
Build the host with `zig build -Doptimize=ReleaseFast -Dtracy=/absolute/path/to/tracy`.
The checkout supplies `public/TracyClient.cpp`; no profiler is downloaded or
linked by default. Linked native apps pass their `-Dtracy` option to `sketchbook.init` as
`.tracy = path` and can import `sb.modules.tracy` for their own zones:
`const zone = tracy.zone(@src(), "work"); defer zone.end();`.
The host marks frames, input polling, drawing, command painting and presentation.
These are CPU wall times (presentation includes waits), not GPU timestamps.
Use a matching `tracy-capture` or the Tracy UI. Disabled builds compile the
calls out; tests disable their zones too. The wrapper follows Pardes's small
Zig Tracy binding. Forward the same option through dependencies that also
initialize Sketchbook so the build shares one host/client module.
ASCII text caches coverage independently of animated ink. The pinned SDL Vulkan
patch keeps memory relocation disabled and lets small transfer buffers share
allocations, avoiding hundreds of dedicated allocation frees during presentation.
## glTF / GLB assets
The optional `gltf` module wraps the vendored C99 `cgltf` loader. It loads scene
hierarchies, mesh accessors, materials, cameras, animation tracks and arbitrary
`extras` metadata without depending on the window or renderer. Import it into a
native executable or sketch with `.imports = &.{.{ .name = "gltf", .module = sb.modules.gltf }}`.
It currently requires libc; it is not wired into the freestanding browser host.
```zig
const gltf = @import("gltf");
const document = try gltf.Document.parse(bytes);
defer document.deinit();
try document.loadBuffers(null); // embedded GLB / data-URI buffers, no file reads
const node = document.findNode("CAM_StreetTour") orelse return error.MissingCamera;
const json = gltf.extrasJson(&node.extras) orelse return error.MissingMetadata;
// Parse json with std.json using the application's own metadata schema.
```
Keep `bytes` alive until `deinit`: GLB buffers may borrow it. Parsing validates
structure and uses cgltf's C allocator, released by `deinit`. `loadBuffers`
validates again with loaded data. Only passing a non-null, zero-terminated glTF
source path enables relative external buffer-file reads; use that for trusted
assets. Images and compressed geometry still need their own decoders.
`document.data` and `gltf.c` expose cgltf directly; `gltf.readFloats(accessor,
index, out)` adds bounds/component checks and supports strided, normalized and
sparse accessors. The raw animation channels remain available to the caller;
this module does not create GPU resources or implement an animation player.
Run `zig build test-gltf` for focused loader tests; they are also part of
`zig build test`.
### Generated scene bindings
`sb.addGltf` runs a native host executable in a separate build step, then supplies
its generated `.zig` file as a module. The glTF file is a tracked build input;
changing it regenerates the bindings before compiling their consumers.
```zig
// build.zig: add this import to the consuming module's .imports.
.{ .name = "street_scene", .module = sb.addGltf(b.path("street.glb")) }
```
```zig
const scene = @import("street_scene");
const camera = scene.nodes.CAM_StreetTour;
comptime {
if (!@import("std").mem.eql(u8, camera.extras.drat_role, "camera"))
@compileError("expected a camera role");
}
// camera.index locates the node; @TypeOf(camera.extras) exposes metadata fields.
```
The generated `nodes`, `animations`, `cameras`, `meshes`, and `materials`
namespaces expose named entries with indices and typed `extras`; nodes also
include optional camera and mesh indices. Labels with spaces use Zig's quoted
identifier syntax, e.g. `scene.nodes.@"Camera - At the corner"`. Unnamed entries
are omitted; duplicate labels within one namespace fail generation. JSON objects
become struct values, arrays become tuples, and strings/numbers retain explicit
Zig types. Comptime can reflect on these types or assert expected values; it never
parses the asset. Missing referenced labels/fields and incompatible types fail
compilation; application assertions define which metadata values must match.
The module contains no libc dependency. `source_path` is the build input filename;
`source_sha256` lets runtime consumers
reject a replaced asset before using generated indices. Code generation reads
metadata, not external buffers; geometry and animation sample checks still use
the runtime loader. The game repo's `scripts/check_scene.zig` demonstrates both.
### Local 9P controls
A running sketch is a small file tree, served over 9P by cloud9: its
State as files, a `ctl` that takes the console's words and a script's
input, its screen as a PNG. The tree describes itself: `README` has a
line for every file, every verb under `ctl` and every State file under
`state/`, made from the same tables the console, scripts and `--help`
read; `commands` lists the verbs alone, the sketch's own last.
A run a person watches posts its tree as `sketchbook/<name>` (the
socket `$XDG_RUNTIME_DIR/9p/sketchbook/<name>`, owner-only, removed at
a clean exit); `--9p NAME` posts it under another name, also headless,
and `--9p /path.sock` listens at a path instead. Every executable built
with sketchbook, and the generic host after its LIBRARY, takes `fs VERB
PATH`: cloud9's verbs (`ls read write ask follow stat help complete`)
on that tree, the server's refusals printed in its words, exit status 1.
With the sketch closed, `fs` serves the same tree itself, with no
window, from the save's newest State (the default save, or `--state`'s),
else from State's declared defaults: `README`, `commands` and `state/`
answer, and the rest say the sketch is not running. A `read` answered
that way says so on stderr (`drat-meout is not running: this is its
save's newest State, frame 61 of ...`), so a script that reads before the
sketch is up does not take the save for it.
```
ctl write a verb a line: ctl's own (screenshot, profile-reset),
a script's input verbs (click, key, type...: routed live,
no frame of their own), the console's (set, load, pause,
step...); any other line goes to the sketch
status, log name, canvas, mode, GPU, screenshot state; the console's
last five lines
screen.png the next frame: an open waits for it to be drawn
README the tree, a line a file; commands: the verbs
state/ the State: a directory per struct and per array, a file
per value (state/tracker/songs/3/bpm); a read is the
value as `get` shows it, a write is `set` (a jump)
sketch/ reserved for the sketch's own files, empty
```
An array of numbers is one file of its values, blank-separated
(`state/talk/text`, a vector's lanes), written the same way; an array
of arrays is a directory of such rows; an array of structs a directory
of indices, so drat-meout's 8x16x16x4 tracker notes are
`state/tracker/songs/<n>/patterns/<n>/<n>/<n>/pitch`. Optionals and
unions read as `<N bytes>` and refuse writes. A value is read as it was
at the open.
Driving a sketch from an agent, here drat-meout:
```sh
drat-meout --headless --9p drat-meout & # or just run it: it posts itself
drat-meout fs help ctl # the verbs, with their arguments
drat-meout fs write ctl 'scene street' # a console line, or the sketch's
drat-meout fs read state/scene # .street
until [ "$(drat-meout fs read state/street/time | cut -d. -f1)" -ge 3 ]; do :; done
drat-meout fs write ctl 'click 480 300' # input, live
drat-meout fs read screen.png > street.png # one read: answered when the frame lands
drat-meout fs write state/street/camera fast # fs: state/street/camera: InvalidValue
drat-meout fs help state/street/camera # state/street/camera .placeholder .scene
drat-meout fs write ctl quit
drat-meout fs read state/scene # closed: from the save
```
Scripts stay what tests use (a fixed clock, fresh state, `expect`); the
tree is live, between real frames, and an agent asserts by reading.
Anything that speaks 9P works too: `9p -a
unix!$XDG_RUNTIME_DIR/9p/sketchbook/drat-meout read state/scene`.
Four clients can connect; requests run between frames on the host
thread. `zig build test-fs` drives a sketch this way.
The native host's `timing` command toggles a scrolling graph with average, p90
and p99 in milliseconds. `timing on|off` sets visibility;
`timing frame|work` selects the graph and shows it; `overlay timing` also toggles.
`timing stats` prints current average/p90/p99/maximum; `timing reset` clears history
without changing visibility or metric. Collection continues while hidden.
Readouts refresh about four times a second from fixed text buffers. All glyphs
reuse one immutable atlas texture, so changing values neither rasterizes text
nor switches textures per digit. Fixed vertex/index arrays batch the entire
panel, graph and text into one geometry draw, without per-frame overlay allocation.
Percentiles use nearest rank over the last 240 individual frames. A separate
fixed graph ring holds 240 peaks, each over eight frames: eight times slower
scrolling, with single-frame spikes preserved across 1920 frames. Its scale
label updates when the peak range changes. Frame measures wall-clock cadence
between completed host frames, including pacing, event/9P polling and present.
Work measures update/draw through the deferred 2D command flush, before present.
Both include visible overlays and screenshot capture and use real time even
during replay/export. These are not GPU hardware timestamps, and frame can
include vsync waits. No GPU synchronization is added. Test with
`zig build test-timing`.
The read-only 9P file `timing-trace` exports paired raw samples as CSV:
`index,frame_ns,work_ns,outside_work_ns`. Indices start at zero within the captured
history, oldest first. `outside_work_ns` is saturating `frame_ns - work_ns`, including
pacing, polling, presentation and cleanup; it is not a hardware GPU duration. Each
open pins the bounded timing history, so subsequent frames or `timing reset`
cannot change a partially read trace. It works without `--profile-gpu`:
`drat-meout fs read timing-trace > timing.csv`.
For compositor/video measurements, launch with `--timing-marker`. This opt-in
marker is drawn last, independently of the timing overlay: 80 black/white cells,
each 4×8 canvas pixels, at the bottom-left (320×8 total). Cells encode, LSB-first,
16-bit magic `0xD3A7`, the low 32 bits of `Input.frame`, then the low 32 bits of
`Input.now` in whole milliseconds. It identifies submitted frames and draw
sample times in captured video; repeated decoded IDs reveal repeated presented
frames. Decode at canvas scale, accounting for any window/compositor scaling.
The marker is omitted when the canvas is smaller than 320×8 and is disabled by
default. `zig build test-timing` checks its encoding, placement and counter wrap.
On Wayland, `presentation-trace` provides immutable CSV snapshots of
`wp_presentation` feedback: frame ID, sample time, request time, presented/discarded
result, presentation timestamp, refresh period, sequence and flags. Status and
clock metadata make unsupported backends explicit. `commit_ns` is the feedback
request time before present, not an intercepted surface commit. Only subtract
timestamps in the same clock domain; sample time uses SDL's elapsed clock.
Feedback attaches to the next surface commit, which the binary marker lets a
compositor capture independently verify.
Interactive Wayland windows use this feedback to pace submissions and sample
one shared frame clock before update and draw. Ordinary `Input.now`, tick events
and `Input.dt` therefore follow display refresh automatically; sketches need no
separate rendering clock or animation correction. A tick never precedes the
previous frame or its queued input, so newly arrived input can move it slightly
past the scheduled instant. Recording stores these exact ticks; replay, scripts
and export retain their existing clocks. The browser already uses the
`requestAnimationFrame` timestamp for its shared update/draw clock.
Without usable feedback, rendering falls back to SDL's normal presentation and
wall-clock ticks. Hidden/minimized windows keep servicing controls but skip
animation and drawing until visible again.
The implementation is `src/host/Presentation.zig`, including the Wayland callbacks
and trace writer. `zig build test-presentation` checks its clock and feedback
behavior. Linux builds require `wayland-scanner` plus the `wayland-client`
development package and pkg-config metadata. The build generates the protocol
header/tables from the vendored XML and translates the header into Zig bindings;
only the generated protocol tables are compiled as C.
`ctl` takes up to 4096 bytes a write; an error returns as the 9P error,
the error's name (`UnknownField`, `InvalidValue`). Each open of
`screen.png` (and of the traces, `README` and a State file) pins its own
copy, so a later frame cannot change a partially read one; screenshots
include visible overlays. `zig build test-control` checks the control
boundary and snapshot lifetime; the same tests belong to the full host
suite.
With `--profile-gpu`, `profile` reports tab-separated `label`, `count`, `mean_ms`,
and `worst_ms`, plus a `# frames N` line. `profile-reset` written to `ctl` resets
counters and the frame denominator without discarding label allocations. Warm up
first, reset, then wait for the desired number of frames before reading. These
measure CPU wall time from GPU command recording through submission and fence
wait, including synchronization overhead; they are not hardware GPU timestamps.
Both operations return `ProfilingDisabled` when profiling is off.
### Imperative glTF drawing
Add an import with `.module = sb.addGltfRenderer()` (e.g. named `gltf_render`).
Its `Model` copies a GLB's meshes and animation tracks into the caller's session
arena. The cgltf document is released after loading; geometry uploads once to
host-owned GPU buffers. Opaque primitives in each mesh are batched into one draw
with per-vertex material colors. Only transforms and draw commands change each frame.
```zig
const render = @import("gltf_render");
const street_scene = @import("street_scene");
pub const Session = struct { model: render.Model = undefined, image: sk.Image = .none };
pub fn setup(ss: *Session, init: *sk.Init) !void {
// Filename + hash come from the generated bindings. Parses and uploads once.
ss.model = try render.Model.load(init, street_scene);
ss.image = init.host.newImage(960, 600);
}
pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void {
renderFrame(s, ss, f) catch |err| f.host.print("scene: {t}", .{err});
}
fn renderFrame(s: *const State, ss: *Session, f: *sk.Frame) !void {
try ss.model.scene.sample(street_scene.animations.CAM_StreetTour.index, s.time);
const camera = try render.sceneCamera(&ss.model.scene, street_scene.nodes.CAM_StreetTour.index);
var view = render.View.init(f, ss.image, 960, 600, camera);
try view.scene(&ss.model);
// Or: try view.mesh(&ss.model, street_scene.meshes.MyMesh.index, transform);
// Or: try view.triangles(&geometry, transform, color); // upload in setup first
view.end();
f.image(ss.image, .{ .x = 0, .y = 0, .w = 960, .h = 600 }, .{});
}
```
`model.scene.nodes[index].world` is a column-major transform; `meshes[index]`
exposes indexed vertices, normals and material colors. Animation sampling is
allocation-free, supports STEP, LINEAR (slerp for rotations), and CUBICSPLINE TRS,
and clamps to the clip range; the application decides how to loop. The separate
CPU API is `gltf.Scene.init(allocator, document)`, `sample`, `reset`, and `deinit`.
It copies loaded data, so the document can be destroyed after initialization.
`render.sceneCamera(scene, node_index)` derives perspective or orthographic
projection and view from the sampled camera node. Alternatively pass a plain
`render.Camera` with your own eye/target to `View.init`. `Model.init` remains
available for CPU loading, and `Geometry.upload(host)` uploads custom triangles
explicitly during setup. No resource loading happens inside `View.scene/mesh`.
This initial renderer uses opaque material base colors, directional light and a
depth buffer. It has no texture sampling, alpha blending, shadows, skinning or
morph animation. Unsupported mesh/animation features fail loading explicitly;
material textures are ignored. The renderer currently supports native hosts;
`render.supported` is false in the browser replacement module. GPU handles are
released by the host on session reset; call `model.release(host)` to release them
earlier. Vertex storage layout and shader uniform layout are checked at comptime;
GLSL uniform declarations are generated from the Zig types.
A separate fullscreen pass can sample a completed render with
`f.postProcess(source, target, .{ .vertex = vertex_shader, .fragment = fragment_shader,
.sample_depth = true, .fragment_uniforms = uniforms })`. Allocate distinct source
and target images in setup, then draw the target image after this command.
Native fragment bindings are color at 0 and depth at 1 (set 2). Web GLSL uses
separate texture/sampler pairs at 0/1 and 2/3 (set 2). Fragment uniforms use set 3,
binding 0. Depth sampling requires the source's latest pass to have `.depth = true`
and `.samples = 1`; missing depth, multisampled depth and feedback loops are
rejected. Omit `sample_depth` for a color-only pass. Native profiling reports this
work separately as `postprocess`.
`profile` also includes `p95_ms` and `p99_ms`: nearest-rank percentiles of the
latest 2048 measured commands per label. Mean and worst cover every command since
reset. `profile-trace` exposes those retained samples as CSV (`label,sample,ns`),
ordered oldest to newest within each label; sample numbers start at 1 after
reset. Each open pins the trace even if profiling continues or counters reset.
The render path writes a fixed ring; sorting and CSV generation happen only on
inspection. A trace snapshot is limited to 256 KiB and fails if it exceeds that
limit. Capture it with `drat-meout fs read profile-trace > trace.csv`.
|