summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--README.md702
-rw-r--r--build.zig390
-rw-r--r--build.zig.zon7
-rw-r--r--examples/manual.zig312
-rw-r--r--examples/micscope/README.md158
-rw-r--r--examples/micscope/build.zig54
-rw-r--r--examples/micscope/build.zig.zon10
-rw-r--r--examples/micscope/shaders/tuner.comp134
-rw-r--r--examples/micscope/shaders/tuner_difference.comp49
-rw-r--r--examples/micscope/src/layouts.zig37
-rw-r--r--examples/micscope/src/main.zig1299
-rw-r--r--examples/micscope/src/tuner.zig132
-rw-r--r--examples/micscope/test/README.md22
-rw-r--r--examples/micscope/test/profile.script167
-rw-r--r--examples/micscope/test/record.script23
-rw-r--r--examples/micscope/test/reference.flacbin0 -> 3841704 bytes
-rw-r--r--examples/micscope/test/render.script18
-rw-r--r--examples/micscope/test/sweep.wavbin0 -> 192044 bytes
-rw-r--r--examples/micscope/test/tones.wavbin0 -> 480044 bytes
-rw-r--r--examples/micscope/test/transport.script98
-rw-r--r--examples/micscope/test/tuner.script31
-rw-r--r--examples/micscope/web/icon-192.pngbin0 -> 4204 bytes
-rw-r--r--examples/micscope/web/icon-512.pngbin0 -> 9911 bytes
-rw-r--r--examples/micscope/web/icon.svg26
-rw-r--r--examples/spheres/README.md155
-rw-r--r--examples/spheres/build.zig55
-rw-r--r--examples/spheres/build.zig.zon10
-rw-r--r--examples/spheres/shaders/advance.comp32
-rw-r--r--examples/spheres/shaders/fade.frag11
-rw-r--r--examples/spheres/shaders/fullscreen.vert6
-rw-r--r--examples/spheres/shaders/link.frag12
-rw-r--r--examples/spheres/shaders/link.vert47
-rw-r--r--examples/spheres/shaders/lookahead.comp52
-rw-r--r--examples/spheres/shaders/physics.glsl36
-rw-r--r--examples/spheres/shaders/rechord.comp27
-rw-r--r--examples/spheres/shaders/sim.comp86
-rw-r--r--examples/spheres/shaders/sprite.frag11
-rw-r--r--examples/spheres/shaders/sprite.vert23
-rw-r--r--examples/spheres/shaders/synth.comp112
-rw-r--r--examples/spheres/shaders/trail.frag7
-rw-r--r--examples/spheres/shaders/trail.vert48
-rw-r--r--examples/spheres/shaders/voices.glsl101
-rw-r--r--examples/spheres/src/chords.zig311
-rw-r--r--examples/spheres/src/layouts.zig163
-rw-r--r--examples/spheres/src/main.zig1121
-rw-r--r--examples/spheres/test/play.script60
-rw-r--r--examples/spheres/web/icon-192.pngbin0 -> 12407 bytes
-rw-r--r--examples/spheres/web/icon-512.pngbin0 -> 49109 bytes
-rw-r--r--examples/spheres/web/icon.svg28
-rw-r--r--examples/talk.zig160
-rw-r--r--examples/vecanim/README.md15
-rw-r--r--examples/vecanim/scenes/live.zig9
-rw-r--r--examples/vecanim/test/intro.script14
-rw-r--r--examples/vecanim/test/live.script5
-rw-r--r--src/abi.zig105
-rw-r--r--src/abi_hash.zig9
-rw-r--r--src/anim/Painter.zig262
-rw-r--r--src/anim/player.zig386
-rw-r--r--src/anim/root.zig1136
-rw-r--r--src/anim/typst.zig10
-rw-r--r--src/gpu/Executor.zig26
-rw-r--r--src/host/Console.zig526
-rw-r--r--src/host/Host.zig468
-rw-r--r--src/host/Sessions.zig1599
-rw-r--r--src/host/audio.zig266
-rw-r--r--src/host/control.zig339
-rw-r--r--src/host/fields.zig37
-rw-r--r--src/host/library.zig118
-rw-r--r--src/host/memory.zig586
-rw-r--r--src/host/overlay.zig4
-rw-r--r--src/host/probe.zig86
-rw-r--r--src/host/root.zig292
-rw-r--r--src/host/script.zig451
-rw-r--r--src/host/state_files.zig303
-rw-r--r--src/host/timeline.zig329
-rw-r--r--src/layout.zig66
-rw-r--r--src/scope/root.zig91
-rw-r--r--src/sketch/request.zig2
-rw-r--r--src/sketch/root.zig72
-rw-r--r--src/sketch/sfxr.zig267
-rw-r--r--src/sketch/web.zig35
-rw-r--r--src/vector/morph.zig60
-rw-r--r--src/vector/svg.zig96
-rw-r--r--test/kill.script5
-rw-r--r--test/killed.script6
-rw-r--r--test/manual.script131
-rw-r--r--test/past.script8
-rw-r--r--test/past_diverged.script6
-rw-r--r--test/past_replay.script12
-rw-r--r--test/reload.script2
-rw-r--r--test/same_sessions.zig66
-rw-r--r--test/scene_compiled.script2
-rw-r--r--test/scene_live.script21
-rw-r--r--test/scene_morph.script46
-rw-r--r--test/scene_morph.zig25
-rw-r--r--test/session_export.script3
-rw-r--r--test/session_import.script13
-rw-r--r--test/svg/image.svg9
-rw-r--r--test/svg/typst-image.typ6
-rw-r--r--test/talk.script104
-rw-r--r--test/voices.script29
-rw-r--r--test/voices.zig26
-rw-r--r--tools/bench.zig101
-rw-r--r--web/host.js22
104 files changed, 12995 insertions, 2061 deletions
diff --git a/README.md b/README.md
index 225f87c..733cc3d 100644
--- a/README.md
+++ b/README.md
@@ -29,6 +29,10 @@ 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.
+- [`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;
@@ -41,24 +45,24 @@ An app is an ordinary module. Every declaration is optional:
| Declaration | Meaning |
| --- | --- |
| `name`, `width`, `height` | Window title and initial canvas |
-| `State` | Saved to a file, snapshotted, replayed: what `update` changes. No pointers and no host handles (compile errors). |
+| `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. |
-| `Store` | On disk, at the same address in every run: survives reloads and restarts. Big data that is not replayed (a recording, a document). May point into itself; no host handles. |
| `init(state, host)` | 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, store, frame)` | Pictures and sound, as commands; may change Session and Store |
-| `command(state, session, store, console, line) !bool` | Console lines the host does not know |
+| `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(s: *const State, store:
-*Store, ss: *Session, f: *sk.Frame)` both work. `update` can only ask for
+`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`, `session`, and `store` allocators;
-it may also request Session, Store, or Host directly. It gets no State, Input,
+`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
@@ -79,14 +83,11 @@ Memory comes by lifetime, one allocator each:
| --- | --- | --- |
| `f.scratch` | this frame | all at once, after the frame is drawn |
| `f.session` | this process | one allocation at a time; the rest when Session's layout changes, along with the images and buffers the session made |
-| `f.store` | on disk, `<state>.store` | one allocation at a time; `--fresh` empties it |
-A Store layout change migrates field by field like State: unchanged fields,
-pointers included, keep their values, since the store never moves.
-`command` gets the session and store allocators on its `Console`.
+`command` gets the session allocator on its `Console`.
-`update` sees only State, so when a key should do something to Session or
-Store, State carries a request: `seek: sk.Request(f32)`, sent with
+`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.
@@ -116,19 +117,19 @@ can replay differently. `input.started` is true on the first update after
the program starts, never after a reload: state is saved, so this is where
to stop what should not resume on its own. In `draw`, `input.jumped` says
State got where it is other than by `update` from what the last `draw`
-saw: the first frame, a seek, step, snapshot load, `set`, `reset`, play or
+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`, `audio`, `microphone`, `pixels`, `gpu`,
+`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`, `samples`, `readFile`, `env`, `log`, `textSize`). Commands may be built
+`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, session or store memory.
+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
@@ -165,13 +166,24 @@ move. The web host ignores `raster`.
dialog; the answer comes back as the console line `open <path>`, so it
reaches the sketch's `command` like anything typed there. `f.run(line)`
does the same with any line, after the frame: `draw` cannot write State,
-so this is how it tells State something only it learns (how many takes a
-Store holds, say).
+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.
+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
@@ -363,10 +375,9 @@ display's rate it steps once a frame, jitter and all: a 60 Hz frame is
after a reload that shrinks it. The default buffer is the element's own
defaults, never `std.mem.zeroes` (an enum may have no 0).
-**Data that grows.** State is snapshotted, replayed and migrated, so it
-holds what `update` changes, at a size fixed in its type. Store is not
-snapshotted or replayed, so what is in it does not follow a seek. Three
-cases, by who needs the data:
+**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).
@@ -380,7 +391,8 @@ cases, by who needs the data:
may derive it differently. A cheap derivation needs no cache at all:
the quadtree builds its tree in `f.scratch` every frame.
- It is the user's work, not a function of State (a recording, a
- document): Store.
+ 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`).
@@ -390,8 +402,17 @@ update does (`examples/noc`: `koch`, `lsystem`, `quadtree`).
`draw`s the views given rects for: the last seconds as a scrolling waveform
and spectrogram, the smoothed spectrum of the newest samples, and an
oscilloscope. All analysed and drawn on the GPU, new columns only; its
-shaders swap to WGSL for the web like any others. Lifted from micscope's
-live view; spheres uses it.
+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
@@ -422,16 +443,87 @@ stay on the GPU: a compute shader's output is a later draw's input, with no
readback. Each dispatch is its own compute pass, so it sees everything the
commands before it wrote.
-Sound is declarative. `f.voice(.{ .key, .audio, .serial, .loop, .volume })`
-declares a voice that should be sounding. A new key or serial starts it, and
-an undeclared key stops it. A finished one-shot stays finished while it is
-still declared, so replays and seeks never re-fire sounds. `f.audio(key,
-samples, .{})` streams PCM, and `input.stream(key)` reports what the host has
-queued and played. `f.microphone()` keeps the default recording device open
+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`.
+`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.
@@ -439,8 +531,8 @@ 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, slide-style
-pauses, and objects the scene draws itself. A scene is one file, and
+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
@@ -474,14 +566,19 @@ fn wobble(now: anim.Now, swing: anim.Value) anim.Pose {
```
Objects are added (`typst`, `svg`, `rect`, `circle`, `line`, `arrow`,
-`polygon`, `custom`) and show in the order they were added; each call
-returns a handle. Animations are methods of the handle: `write`, `create`,
+`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). `wait` moves time on, `pause()` holds the player there until a
-click, like a slide. Positions are scene units: 1280x720 of them show at
+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).
@@ -499,13 +596,15 @@ A scene is one of two kinds, which share every call:
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 wall clock (`s.clock`, which runs on through pauses)
- or any runtime data. Its Typst sources are the declarations of the
- namespace it is given, since the build cannot run it to find them.
+ (`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 pauses at an instant), so the only state is `t`, and
-scrubbing, seeking and hot reload are free. A test checks that a live
+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.
@@ -516,6 +615,63 @@ 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`
@@ -566,11 +722,16 @@ 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`. Keys: space pause, click to continue after a `pause`, left/right
-previous/next play, `,`/`.` step a frame, home/end, up/down speed, B GPU or
-CPU renderer, L loop, 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 pauses or controls, and quits at the end:
+`--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
@@ -593,41 +754,251 @@ 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 private copy.
-- **State file.** `<name>.state` holds the live state plus 7 snapshot slots,
- shared via `MAP_SHARED`. Its header carries the reflected layout, so a
- layout change migrates every slot field by field, with enums matched by tag
- name, and `sketchbook-probe` can print any sketch's state. Arrays and
+ 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. Files from
- before element leaves (`SKETCH01`) are read and rewritten; a file that
- is not a state file is refused, never truncated.
-- **Store file.** `<name>.state.store` is a heap mapped at a fixed address
- (`0x2000_0000_0000`, 64 GiB reserved), grown in place, locked to one
- process. Power-of-two size classes with free lists in the file. Snapshots
- and replays do not cover it (only `draw` and `command` change it).
-- **Time travel.** Recordings, replay, seek and step work on any sketch,
- because they only need state bytes and events. A recording is whole
- frames; playback, `seek` and `step N` (frames) stop only between them.
- Restoring a snapshot (play, seek, step, `load`) clears the pointer,
- button and key state, and a recording begins with events that bring back
- what was held when it started (a pointer move, a button or key down), so
- a replay starts from the same input whatever the live pointer did since.
- A recording carries a hash of the build that made it; `play` warns when
- the running build differs (edited `update`, a new compiler), since the
- replay may then diverge.
-- **Console and overlays.** `get`/`set <field path>` (`get` of a vector,
- array or struct shows its values, in memory order), snapshots, recordings and
- the memory, 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 N` compares live state with
- snapshot N leaf by leaf, so padding (a Debug `@Vector`'s spare lane)
+ 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
@@ -637,18 +1008,22 @@ object.
(`expect pos[0] 250 ~0.5` within a tolerance; a failure prints what it
found),
`await field value [~tol]` (frames until it holds, a minute at most),
- `expect-snapshot N` (live state equals snapshot N, leaf by leaf, printing
- the first differences), `expect-log`/`expect-no-log text` (the console's
+ `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`. A failed
+ 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 works on files of its own (`<state>.<pid>`),
- renamed to the given `--state` at exit, so two builds running the same
- script at once do not share them.
+ 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:
@@ -668,8 +1043,8 @@ object.
hides its controls, plays through and quits. `--size WxH` is the room
for the canvas (`in.window_width`/`height`, and the first canvas): a
sketch that sets its canvas to the room exports at any size. An export
- keeps state files of its own and removes them, so it can run beside a
- player. `--export` plays no script. In a release build on an RTX 3050,
+ 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
@@ -732,7 +1107,7 @@ pub fn build(b: *std.Build) void {
}
```
-`addSteps` installs the executable and adds `run`, `lib`, `probe`,
+`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
@@ -748,10 +1123,9 @@ and returns plain `std.Build` objects:
| `app.addScriptExecutable()` | the same, built in `script_optimize` mode, as `e2e` plays scripts with |
| `app.addWeb(.{ .assets = ... })` | the wasm module and a ready-to-serve directory, built from the app's modules with every shader module swapped for its WGSL twin; tests can read its state by path (indices too: `list[2].x`) with `sk_field` (numbers) and `sk_tag` (enum tag names) |
| `app.addServe(install)` | `miniserve` serving an installed web directory over https, on every interface, with a self-signed certificate made once by `openssl`: https makes the page a secure context on any device, which WebGPU and the microphone need. Its defaults are environment variables, so miniserve options after `--` replace them |
-| `app.addRun(lib, .{})` | the generic host running the installed library |
+| `app.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.addProbe(state)` | the probe on a state file |
| `app.addTest(.{})` | tests with the app importable as `app` |
| `app.addReloadCheck(.{ .script, .edits })` | a check that the app hot-reloads with State kept (below) |
@@ -761,6 +1135,9 @@ 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}`
@@ -835,8 +1212,9 @@ directory), `typst` for scenes with Typst in them, and for `serve`,
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`),
-`sb.host_exe` and `sb.probe_exe` are exposed for anything else.
+`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
@@ -845,20 +1223,25 @@ Add `.sketchbook = .{ .path = "..." }` to your `build.zig.zon`.
`f.openFile` answers with a line of any length.
- Every upload, compute dispatch and GPU pass is its own command buffer and
submit. Fine at a handful per frame; batch them per frame if that grows.
-- The store is not crash-safe: a crash in the middle of an allocation can
- leave it inconsistent, and `--fresh` starts it over.
-- Handles inside Store containers (`std.ArrayList(sk.Image)`) are not caught
- at compile time: the check does not follow pointers.
- Native antialiasing resolves coverage per sample within a run of
shapes, the canvas per shape, so where two shapes' edges meet the web
can show a faint seam native does not. `fill` rects and images are
antialiased natively only inside a target. Without a GPU renderer,
native draws aliased. A stroke that overlaps itself blends twice
natively where it overlaps, once on the web.
-- On the web: nothing persists (Store lasts as long as the page),
- synthesised voices are silent, `loadSound` knows only sounds the page
- decoded, multisampling is 4× at most, and mixing runs on the main thread
- (a ScriptProcessor), so a busy page can crackle.
+- 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
@@ -873,16 +1256,23 @@ renderer migration work and the optional addon boundary.
## The boundary
Host and sketch are built by the same `zig build`, so ordinary Zig types cross
-it (slices, tagged unions, `std.mem.Allocator`). `abi.hash`, a comptime hash
-of every shared type's layout, guards against the one real hazard: a host
-refuses a library built against different definitions. Everything that outlives
-a call lives in host memory, since host code is never unloaded. Only the
-recorded `Event` and the reflected `Layout` are `extern`, because they are
-written to disk.
+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 recording played,
+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.
@@ -1014,22 +1404,74 @@ the runtime loader. The game repo's `scripts/check_scene.zig` demonstrates both.
### Local 9P controls
-Native hosts accept `--9p /absolute/path/game.sock`. The opt-in Unix socket uses
-cloud9, is owner-only (`0600`), refuses existing paths, and is removed on clean
-exit. Four clients can connect; requests run between frames on the host thread.
-The build uses the sibling `../cloud9` checkout.
+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
-./zig-out/bin/drat-meout --9p /tmp/drat.sock
-printf 'scene street\nget scene\n' | 9p -a unix!/tmp/drat.sock write ctl
-9p -a unix!/tmp/drat.sock read log
-printf 'screenshot\n' | 9p -a unix!/tmp/drat.sock write ctl
-9p -a unix!/tmp/drat.sock read status
-# Once screenshot_pending is false and screenshot_generation has advanced:
-9p -a unix!/tmp/drat.sock read screen.png > /tmp/street.png
-printf 'quit\n' | 9p -a unix!/tmp/drat.sock write ctl
+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.
@@ -1056,7 +1498,7 @@ history, oldest first. `outside_work_ns` is saturating `frame_ns - work_ns`, inc
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`:
-`9p -a unix!/tmp/drat.sock read timing-trace > timing.csv`.
+`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,
@@ -1096,15 +1538,13 @@ header/tables from the vendored XML and translates the header into Zig bindings;
only the generated protocol tables are compiled as C.
-`ctl` accepts complete console command lines (up to 4096 bytes per write),
-including game commands and host `set`, `get`, `pause`, `step`, `seek`, and `quit`.
-Errors return as 9P errors. `log` exposes the console's latest five lines;
-`status` reports canvas size, playback mode, GPU availability and capture state.
-`screenshot` captures the next rendered canvas as PNG; `screen.png` opens fail
-while capture is pending or failed. Each successful open pins its own snapshot,
-so a later capture cannot change a partially read image. Screenshots include
-visible overlays. `zig build test-control` checks the control boundary and
-snapshot lifetime; the same tests belong to the full host suite.
+`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
@@ -1188,4 +1628,4 @@ 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 `9p -a unix!/tmp/drat.sock read profile-trace > trace.csv`.
+limit. Capture it with `drat-meout fs read profile-trace > trace.csv`.
diff --git a/build.zig b/build.zig
index e441471..dc58962 100644
--- a/build.zig
+++ b/build.zig
@@ -6,7 +6,7 @@
//!
//! 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(.{}); // run, lib, probe, e2e, test, install;
+//! _ = app.addSteps(.{}); // run, lib, e2e, test, install;
//! // web and serve with `.web = .{}`
//!
//! or pick the pieces: `app.addLibrary()`, `app.addExecutable()`,
@@ -44,7 +44,14 @@ pub fn build(b: *Build) void {
b.installArtifact(gltf_generator);
// Target-free: they compile for whatever imports them, native or wasm.
- const abi = b.addModule("abi", .{ .root_source_file = b.path("src/abi.zig") });
+ // abi.hash's layout half, computed by a program once per change of the
+ // abi sources rather than at comptime in every sketch's compile.
+ const abi_hash = b.addRunArtifact(b.addExecutable(.{ .name = "abi-hash", .root_module = b.createModule(.{
+ .root_source_file = b.path("src/abi_hash.zig"),
+ .target = b.graph.host,
+ .imports = &.{.{ .name = "abi", .module = b.createModule(.{ .root_source_file = b.path("src/abi.zig") }) }},
+ }) })).captureStdOut(.{ .basename = "abi_hash.zig" });
+ const abi = b.addModule("abi", .{ .root_source_file = b.path("src/abi.zig"), .imports = &.{.{ .name = "abi_hash", .module = b.createModule(.{ .root_source_file = abi_hash }) }} });
const gpu = b.addModule("gpu", .{ .root_source_file = b.path("src/gpu/Executor.zig"), .imports = &.{.{ .name = "abi", .module = abi }} });
_ = b.addModule("gpu_scene", .{ .root_source_file = b.path("src/gpu/scene.zig"), .imports = &.{.{ .name = "abi", .module = abi }} });
// The cell renderer's shaders (src/gpu/Cells.zig): embedders compile the
@@ -59,6 +66,8 @@ pub fn build(b: *Build) void {
b.step("shaders", "refresh the committed src/gpu/shaders/prebuilt/*.spv (glslc)").dependOn(&update_shaders.step);
// Embedders provide their existing SDL translation and device.
if (b.option(bool, "gpu-only", "export GPU modules without building the sketch host") orelse false) return;
+ // The host's session database (src/host/Sessions.zig).
+ const xitdb = (b.lazyDependency("xitdb", .{}) orelse return).module("xitdb");
// Geometry and noise, shared by the sketch library and `vector`.
const math = b.addModule("math", .{ .root_source_file = b.path("src/math/root.zig") });
const sketch_imports: []const Build.Module.Import = &.{ .{ .name = "abi", .module = abi }, .{ .name = "math", .module = math } };
@@ -82,16 +91,21 @@ pub fn build(b: *Build) void {
// No optimize mode of its own: the host's Zig code builds in the mode
// of the executable it is part of (`script_optimize` makes use of it).
const cloud9 = b.dependency("cloud9", .{ .target = target, .optimize = optimize }).module("cloud9");
+ b.modules.put(b.graph.arena, "cloud9", cloud9) catch @panic("OOM");
const host = b.addModule("host", .{
.root_source_file = b.path("src/host/root.zig"),
.target = target,
- .imports = &.{ .{ .name = "abi", .module = abi }, .{ .name = "c", .module = c }, .{ .name = "gpu", .module = gpu }, .{ .name = "tracy", .module = tracy }, .{ .name = "cloud9", .module = cloud9 } },
+ .imports = &.{ .{ .name = "abi", .module = abi }, .{ .name = "c", .module = c }, .{ .name = "gpu", .module = gpu }, .{ .name = "tracy", .module = tracy }, .{ .name = "cloud9", .module = cloud9 }, .{ .name = "xitdb", .module = xitdb } },
});
- b.step("test-control", "Test 9P control validation and screenshot snapshots").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host, .filters = &.{ "control writes", "9P reads" } })).step);
+ b.step("test-control", "Test 9P control validation and screenshot snapshots").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host, .filters = &.{ "control writes", "9P reads", "the State as files", "a row of scalars" } })).step);
b.step("test-timing", "Test display clock, recorded ticks, timing history and console controls").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host, .filters = &.{ "timing", "presentation", "frames are whole", "a tick's dt" } })).step);
+ b.step("test-sessions", "Test the sessions database: frames, keyframes, marks, clips").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host, .filters = &.{"session"} })).step);
b.step("test-presentation", "Test presentation feedback, pacing and trace snapshots").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host, .filters = &.{"presentation"} })).step);
+ const test_audio = b.step("test-audio", "Test sound: the voice mixer (reconciling, limiting, pitch, groups), sfxr, and a made sound played as a voice");
+ test_audio.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host, .filters = &.{ "voice", "mixer" } })).step);
+ test_audio.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("src/sketch/root.zig"), .target = target, .optimize = optimize, .imports = sketch_imports }), .filters = &.{"sfxr"} })).step);
const setup_tests = b.step("test-setup", "Test resource setup lifecycle and arguments");
for ([_]*Build.Module{ host, b.createModule(.{ .root_source_file = b.path("src/sketch/root.zig"), .target = target, .optimize = optimize, .imports = sketch_imports }) }) |module| setup_tests.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = module, .filters = &.{"setup"} })).step);
@@ -107,18 +121,7 @@ pub fn build(b: *Build) void {
});
b.installArtifact(host_exe);
- const probe = b.addExecutable(.{
- .name = "sketchbook-probe",
- .root_module = b.createModule(.{
- .root_source_file = b.path("src/host/probe.zig"),
- .target = target,
- .optimize = optimize,
- .imports = &.{.{ .name = "abi", .module = abi }},
- }),
- });
- b.installArtifact(probe);
-
- var sb: Sketchbook = .{ .b = b, .target = target, .optimize = optimize, .modules = .{ .abi = abi, .sketch = sketch, .host = host, .tracy = tracy, .vector = undefined, .scope = undefined, .anim = undefined, .gltf = gltf }, .host_exe = host_exe, .probe_exe = probe, .gltf_generator = gltf_generator, .web = b.path("web"), .glsl = b.path("src/glsl.zig"), .tools = b.path("tools"), .anim_dir = b.path("src/anim"), .gltf_render_dir = b.path("src/gltf_render"), .script_optimize = optimize, .shared = .create(b) };
+ var sb: Sketchbook = .{ .b = b, .target = target, .optimize = optimize, .modules = .{ .abi = abi, .sketch = sketch, .host = host, .tracy = tracy, .vector = undefined, .scope = undefined, .anim = undefined, .gltf = gltf, .cloud9 = cloud9 }, .host_exe = host_exe, .gltf_generator = gltf_generator, .web = b.path("web"), .glsl = b.path("src/glsl.zig"), .tools = b.path("tools"), .anim_dir = b.path("src/anim"), .gltf_render_dir = b.path("src/gltf_render"), .script_optimize = optimize, .shared = .create(b) };
// Vector graphics: built with the same shader step apps use. Both forms
// of its shaders are exported, so apps' web builds can swap them too.
@@ -174,13 +177,26 @@ pub fn build(b: *Build) void {
for ([_]*Build.Module{
b.createModule(.{ .root_source_file = b.path("src/vector/root.zig"), .target = target, .optimize = optimize, .imports = vector_imports }),
b.createModule(.{ .root_source_file = b.path("src/scope/root.zig"), .target = target, .optimize = optimize, .imports = scope_imports }),
- b.createModule(.{ .root_source_file = b.path("src/anim/root.zig"), .target = target, .optimize = optimize, .imports = anim_imports }),
b.createModule(.{ .root_source_file = b.path("src/glsl.zig"), .target = target, .optimize = optimize }),
b.createModule(.{ .root_source_file = b.path("src/abi.zig"), .target = target, .optimize = optimize }),
b.createModule(.{ .root_source_file = b.path("src/sketch/root.zig"), .target = target, .optimize = optimize, .imports = sketch_imports }),
b.createModule(.{ .root_source_file = b.path("src/math/root.zig"), .target = target, .optimize = optimize }),
- b.createModule(.{ .root_source_file = b.path("src/host/root.zig"), .target = target, .optimize = optimize, .imports = &.{ .{ .name = "abi", .module = abi }, .{ .name = "c", .module = c }, .{ .name = "gpu", .module = gpu }, .{ .name = "tracy", .module = tracy }, .{ .name = "cloud9", .module = cloud9 } } }),
+ b.createModule(.{ .root_source_file = b.path("src/host/root.zig"), .target = target, .optimize = optimize, .imports = &.{ .{ .name = "abi", .module = abi }, .{ .name = "c", .module = c }, .{ .name = "gpu", .module = gpu }, .{ .name = "tracy", .module = tracy }, .{ .name = "cloud9", .module = cloud9 }, .{ .name = "xitdb", .module = xitdb } } }),
}) |module| test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = module })).step);
+ // A State bigger than a save holds is a compile error that says what to do.
+ const too_big = b.addObject(.{ .name = "too_big", .root_module = b.createModule(.{
+ .root_source_file = b.addWriteFiles().add("too_big.zig", "comptime { _ = @import(\"abi\").layout.of(struct { bytes: [(32 << 20) + 1]u8 }, .state); }"),
+ .target = target,
+ .optimize = optimize,
+ .imports = &.{.{ .name = "abi", .module = abi }},
+ }) });
+ too_big.expect_errors = .{ .contains = "may be 32 MiB, half of a save, so history has room: lower a capacity (an array, an sk.List), or keep what need not be saved in Session." };
+ test_step.dependOn(&too_big.step);
+ // The anim module alone: its unit tests, and below the player's scenes.
+ const test_anim = b.step("test-anim", "Test the anim module: its unit tests and the player on its test scenes");
+ const anim_tests = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("src/anim/root.zig"), .target = target, .optimize = optimize, .imports = anim_imports }) }));
+ test_anim.dependOn(&anim_tests.step);
+ test_step.dependOn(&anim_tests.step);
// The noise tests again on wasm32 as the web builds it, under Node's
// WASI: the golden bits must come out the same in the browser as
@@ -205,6 +221,9 @@ pub fn build(b: *Build) void {
// field name, through the real dlopen path and the headless host.
const v1 = sb.app(.{ .name = "counter", .root_source_file = b.path("test/counter_v1.zig") }).addLibrary();
const v2 = sb.app(.{ .name = "counter", .root_source_file = b.path("test/counter_v2.zig") }).addLibrary();
+ // v2 through the linker `-fincremental` uses, whose 0.17.1 libraries
+ // glibc loads only after the host's fixup (`withoutVersym`).
+ v2.use_new_linker = true;
// Command.shape on the native host: the parity cases, screenshotted
// and checked pixel by pixel (tools/shapes_web.mjs compares the same
// sketch in headless Chrome: `zig build test-web`).
@@ -240,17 +259,85 @@ pub fn build(b: *Build) void {
// `Host.textSize` against the text drawn (test/text.zig).
const text = sb.app(.{ .name = "text", .root_source_file = b.path("test/text.zig") });
test_step.dependOn(&text.addScript(text.addExecutable(), b.path("test/text.script"), .{}).step);
+ // A sound the sketch made, as a voice: once per serial, not again on a
+ // replay (test/voices.zig).
+ const voices = sb.app(.{ .name = "voices", .root_source_file = b.path("test/voices.zig") });
+ const voices_script = voices.addScript(voices.addExecutable(), b.path("test/voices.script"), .{});
+ test_step.dependOn(&voices_script.step);
+ test_audio.dependOn(&voices_script.step);
+ // And for the web, whose host keeps made sounds but plays no voices.
+ test_audio.dependOn(&voices.addWeb(.{}).wasm.step);
// The anim module's player on its test scenes: a live one with a
// custom object between vector objects, and a compiled one, which is
// also exported, at half size.
const live = sb.addScene(.{ .root_source_file = b.path("test/scene_live.zig") });
- test_step.dependOn(&live.app.addScript(live.app.addExecutable(), b.path("test/scene_live.script"), .{}).step);
+ const live_script = live.app.addScript(live.app.addExecutable(), b.path("test/scene_live.script"), .{});
+ test_step.dependOn(&live_script.step);
+ test_anim.dependOn(&live_script.step);
const compiled = sb.addScene(.{ .root_source_file = b.path("test/scene_compiled.zig") });
const compiled_exe = compiled.app.addExecutable();
const compiled_script = compiled.app.addScript(compiled_exe, b.path("test/scene_compiled.script"), .{});
compiled_script.addArg("--define");
compiled_script.addPrefixedDirectoryArg("frames=", compiled.app.addExport(compiled_exe, .{ .fps = 30, .size = .{ 640, 360 }, .frames = 200 }).frames);
test_step.dependOn(&compiled_script.step);
+ test_anim.dependOn(&compiled_script.step);
+ // Holes through morphs, on the GPU and the CPU renderer (vector/morph.zig).
+ const morph = sb.addScene(.{ .root_source_file = b.path("test/scene_morph.zig") });
+ const morph_script = morph.app.addScript(morph.app.addExecutable(), b.path("test/scene_morph.script"), .{});
+ test_step.dependOn(&morph_script.step);
+ test_anim.dependOn(&morph_script.step);
+
+ // The talk example: a Deck in a sketch's own State, stepped, sent back,
+ // jumped by slides, clicked on its slider, reloaded mid-wait with its
+ // first step retimed, and exported twice, with the same frames.
+ const talk_imports: []const Build.Module.Import = &.{ .{ .name = "anim", .module = sb.modules.anim }, .{ .name = "sketch", .module = sketch } };
+ const talk = sb.app(.{ .name = "talk", .root_source_file = b.path("examples/talk.zig"), .imports = &.{
+ .{ .name = "anim", .module = sb.modules.anim },
+ .{ .name = "typst", .module = sb.addTypst(b.createModule(.{ .root_source_file = b.path("examples/talk.zig"), .imports = talk_imports })) },
+ } });
+ const talk_check = talk.addReloadCheck(.{ .script = b.path("test/talk.script"), .edits = &.{.{
+ .file = "examples/talk.zig",
+ .old = "s.play(.{ title.write(), law.write() }, .{});",
+ .new = "s.play(.{ title.write(), law.write() }, .{ .seconds = 3 });",
+ }} });
+ const talk_exe = talk.addExecutable();
+ for ([_][]const u8{ "a", "b" }, [_]u64{ 400, 401 }) |define, frames| {
+ talk_check.run.addArg("--define");
+ talk_check.run.addPrefixedDirectoryArg(b.fmt("{s}=", .{define}), talk.addExport(talk_exe, .{ .fps = 30, .frames = frames, .size = .{ 640, 360 } }).frames);
+ }
+ // `zig build talk` shows it in a window; `zig build talk-lib --watch`
+ // beside it reloads every edit in place.
+ const talk_lib = talk.addLibrary();
+ b.step("talk", "Run the talk example in a window (reload edits with `zig build talk-lib --watch`)").dependOn(&talk.addRun(talk_lib, .{ .state = ".zig-cache/talk.state" }).step);
+ b.step("talk-lib", "Build and install the talk example's hot-reloadable library").dependOn(&b.addInstallArtifact(talk_lib, .{}).step);
+ const test_talk = b.step("test-talk", "Play the talk example: steps, back, slides, its slider, a reload mid-wait and its export");
+ test_talk.dependOn(&talk_check.run.step);
+ test_step.dependOn(&talk_check.run.step);
+
+ // The manual example: Figure 2-1 of the Intel SDM, Vol. 2, page 31, as
+ // a talk in the stock player. The PDF is named, never committed: built
+ // without it, the scene says so, and only its script needs it.
+ const pdf = b.option([]const u8, "manual", "The Intel SDM Vol. 2 PDF for the manual example (default ~/01-resources/intel-devref-ii.pdf)") orelse
+ b.pathJoin(&.{ b.graph.environ_map.get("HOME") orelse "/", "01-resources", "intel-devref-ii.pdf" });
+ const have_pdf = if (std.Io.Dir.cwd().access(b.graph.io, pdf, .{})) true else |_| false;
+ const manual_options = b.addOptions();
+ manual_options.addOption(?[]const u8, "pdf", if (have_pdf) pdf else null);
+ const manual = sb.addScene(.{ .root_source_file = b.path("examples/manual.zig"), .imports = &.{.{ .name = "manual", .module = manual_options.createModule() }} });
+ const manual_lib = manual.app.addLibrary();
+ b.step("manual", "Play the manual example in a window (-Dmanual=PDF, Vol. 2 of the Intel SDM)").dependOn(&manual.app.addRun(manual_lib, .{ .state = ".zig-cache/manual.state" }).step);
+ test_step.dependOn(&manual_lib.step);
+ if (have_pdf) {
+ const manual_exe = manual.app.addExecutable();
+ const manual_script = manual.app.addScript(manual_exe, b.path("test/manual.script"), .{});
+ // Two exports (a frame cap apiece, so the build runs both), which
+ // quit at the end, as the stock player does.
+ for ([_][]const u8{ "a", "b" }, [_]u64{ 1000, 1001 }) |define, cap| {
+ manual_script.addArg("--define");
+ manual_script.addPrefixedDirectoryArg(b.fmt("{s}=", .{define}), manual.app.addExport(manual_exe, .{ .fps = 10, .frames = cap, .size = .{ 640, 360 } }).frames);
+ }
+ b.step("test-manual", "Play the manual example through its steps, and export it twice").dependOn(&manual_script.step);
+ test_step.dependOn(&manual_script.step);
+ }
// Both vector renderers against resvg, through the host (tools/svgdiff.py).
const svgview = sb.app(.{ .name = "svgview", .root_source_file = b.path("test/svgview.zig"), .imports = &.{.{ .name = "vector", .module = sb.modules.vector }} });
@@ -276,11 +363,13 @@ pub fn build(b: *Build) void {
.{ .name = "anim", .module = sb.modules.anim },
.{ .name = "scene", .module = compiled.module },
.{ .name = "typst", .module = compiled.typst },
+ .{ .name = "manual", .module = manual.module },
+ .{ .name = "manual_typst", .module = manual.typst },
},
}),
}));
bench.has_side_effects = true;
- b.step("bench", "Time parsing and drawing a scene's Typst (release mode, must be under 1ms)").dependOn(&bench.step);
+ b.step("bench", "Time parsing and drawing scenes' Typst (release mode: a simple object under 1ms, a PDF page in its own budget)").dependOn(&bench.step);
// After the tests above, not beside them: it measures time.
for (test_step.dependencies.items) |step| bench.step.dependOn(step);
test_step.dependOn(&bench.step);
@@ -331,6 +420,184 @@ pub fn build(b: *Build) void {
reload.expectExitCode(0);
test_step.dependOn(&reload.step);
+ // A session survives a kill -9 up to its last commit: 255 frames
+ // played, four commits of 60 made, the fifth lost with the process; the
+ // next run starts from frame 240's State, replayed. Its sketch records
+ // in every mode, so the test does in release builds too; and a sketch
+ // that does not record keeps its present all the same.
+ const recorded = sb.app(.{ .name = "replay", .root_source_file = b.path("test/replay.zig"), .record = true }).addLibrary();
+ const unrecorded = sb.app(.{ .name = "replay", .root_source_file = b.path("test/replay.zig"), .record = false }).addLibrary();
+ const killed = b.addSystemCommand(&.{ "sh", "-c",
+ \\set -e
+ \\db="${3%.state}.xitdb"
+ \\for lib in "$4" "$5"; do
+ \\rm -f "$db"
+ \\if "$0" --headless --script "$1" --state "$3" "$lib"; then echo "killed run exited"; exit 1; else test $? = 137; fi
+ \\"$0" --headless --script "$2" --state "$3" "$lib"
+ \\test "$(stat -c %s "$db")" -lt 1048576
+ \\rm -f "$db"
+ \\done
+ });
+ killed.setName("a session survives kill -9");
+ killed.addArtifactArg(host_exe);
+ killed.addFileArg(b.path("test/kill.script"));
+ killed.addFileArg(b.path("test/killed.script"));
+ _ = killed.addOutputFileArg("kill.state");
+ killed.addArtifactArg(recorded);
+ killed.addArtifactArg(unrecorded);
+ killed.has_side_effects = true;
+ killed.expectExitCode(0);
+ test_step.dependOn(&killed.step);
+ b.step("test-kill", "A session survives kill -9 up to its last commit").dependOn(&killed.step);
+
+ // A past session plays again: from its start to a mark, the same
+ // State leaf by leaf; two seconds in, from the keyframe before; and,
+ // built from edited code, it diverges before the mark, says so once,
+ // and goes on from the mark's State.
+ const edited = sb.app(.{ .name = "replay", .root_source_file = b.path("test/replay.zig"), .record = true }).addReloadCheck(.{
+ .script = b.path("test/past_diverged.script"),
+ .edits = &.{.{ .file = "test/replay.zig", .old = "@splat(0.01)", .new = "@splat(0.02)" }},
+ });
+ const past = b.addSystemCommand(&.{ "sh", "-c",
+ \\set -e
+ \\db="${4%.state}.xitdb"
+ \\rm -f "$4" "$db"
+ \\"$0" --headless --script "$1" --state "$4" "$5"
+ \\"$0" --headless --script "$2" --state "$4" "$5"
+ \\"$0" --headless --script "$3" --state "$4" "$6"
+ \\test "$(stat -c %s "$db")" -lt 1048576
+ \\rm -f "$4" "$db"
+ });
+ past.setName("past sessions replay");
+ past.addArtifactArg(host_exe);
+ past.addFileArg(b.path("test/past.script"));
+ past.addFileArg(b.path("test/past_replay.script"));
+ past.addFileArg(b.path("test/past_diverged.script"));
+ _ = past.addOutputFileArg("past.state");
+ past.addArtifactArg(recorded);
+ past.addArtifactArg(edited.edited);
+ past.has_side_effects = true;
+ past.expectExitCode(0);
+ test_step.dependOn(&past.step);
+ b.step("test-past", "Replay past sessions, to a time and across a code change").dependOn(&past.step);
+
+ // A session exported from one database and imported into another plays
+ // there to the same State: at the mark it carries, and two seconds in.
+ const moved = b.addSystemCommand(&.{ "sh", "-c",
+ \\set -e
+ \\mkdir -p "$4"; d=$(realpath "$4"); rm -f "$d"/*
+ \\"$0" --headless --script "$1" --state "$d/a.state" "$5"
+ \\"$0" --headless --script "$2" --state "$d/a.state" --define file="$d/one.xitdb" "$5"
+ \\"$0" --headless --script "$3" --state "$d/z.state" --define file="$d/one.xitdb" "$5"
+ \\test "$(stat -c %s "$d/one.xitdb")" -lt 1048576
+ \\rm -f "$d"/*
+ });
+ moved.setName("export and import a session");
+ moved.addArtifactArg(host_exe);
+ moved.addFileArg(b.path("test/past.script"));
+ moved.addFileArg(b.path("test/session_export.script"));
+ moved.addFileArg(b.path("test/session_import.script"));
+ _ = moved.addOutputDirectoryArg("import");
+ moved.addArtifactArg(recorded);
+ moved.has_side_effects = true;
+ moved.expectExitCode(0);
+ test_step.dependOn(&moved.step);
+ b.step("test-import", "Export a session from one database, import it into another, replay it").dependOn(&moved.step);
+
+ // A script run twice records the same database but for the wall clock's
+ // times: the log and the keyframes follow from the script alone. From
+ // fresh state it records in memory: no file at all.
+ const same_sessions = b.addExecutable(.{ .name = "same_sessions", .root_module = b.createModule(.{
+ .root_source_file = b.path("test/same_sessions.zig"),
+ .target = target,
+ .optimize = optimize,
+ .imports = &.{.{ .name = "Sessions", .module = b.createModule(.{ .root_source_file = b.path("src/host/Sessions.zig"), .imports = &.{ .{ .name = "abi", .module = abi }, .{ .name = "xitdb", .module = xitdb } } }) }},
+ }) });
+ const twice = b.addSystemCommand(&.{ "sh", "-c",
+ \\set -e
+ \\mkdir -p "$3"; d=$(realpath "$3"); rm -f "$d"/*
+ \\"$0" --headless --script "$1" --state "$d/a.state" "$4"
+ \\"$0" --headless --script "$1" --state "$d/b.state" "$4"
+ \\"$2" "$d/a.xitdb" "$d/b.xitdb"
+ \\"$0" --headless --fresh --script "$1" --state "$d/c.state" "$4"
+ \\test ! -e "$d/c.state"; test ! -e "$d/c.xitdb"
+ \\rm -f "$d"/*
+ });
+ twice.setName("a script recorded twice");
+ twice.addArtifactArg(host_exe);
+ twice.addFileArg(b.path("test/past.script"));
+ twice.addArtifactArg(same_sessions);
+ _ = twice.addOutputDirectoryArg("twice");
+ twice.addArtifactArg(recorded);
+ twice.has_side_effects = true;
+ twice.expectExitCode(0);
+ test_step.dependOn(&twice.step);
+ b.step("test-same", "A script run twice records the same database but for times").dependOn(&twice.step);
+
+ // Where files go. Without --state: the XDG data directory, one file. In
+ // .sketchbook/ (`zig build run`'s): a .gitignore and the save, whose
+ // present the next run starts from; an older build's state file beside
+ // it is moved in, once, never over a file there, and never deleted.
+ const paths = b.addSystemCommand(&.{ "sh", "-c",
+ \\set -e
+ \\exe=$(realpath "$0"); lib=$(realpath "$1"); mkdir -p "$2"; d=$(realpath "$2")
+ \\rm -rf "$d"/* "$d"/.sketchbook; cd "$d"
+ \\XDG_DATA_HOME="$d/data" "$exe" --headless --console quit "$lib"
+ \\test "$(ls -A data/replay)" = replay.xitdb
+ \\"$exe" --headless --state .sketchbook/replay.xitdb --console "set updates 7" --console quit "$lib"
+ \\test "$(ls -A .sketchbook | tr '\n' ' ')" = ".gitignore replay.xitdb "; grep -qx '*' .sketchbook/.gitignore
+ \\printf 'expect updates 7\n' >check.script
+ \\"$exe" --headless --state .sketchbook/replay.xitdb --script check.script "$lib"
+ \\printf 'not a state file' >old.state
+ \\"$exe" --headless --state .sketchbook/old.xitdb --console quit "$lib" 2>err
+ \\grep -q moved err; test ! -e old.state; test "$(cat .sketchbook/old.state)" = 'not a state file'
+ \\printf 'not a state file' >old.state
+ \\"$exe" --headless --state .sketchbook/old.xitdb --console quit "$lib" 2>err
+ \\grep -q 'both exist' err; test -e old.state
+ \\rm -rf "$d"/* "$d"/.sketchbook
+ });
+ paths.setName("where the save goes");
+ paths.addArtifactArg(host_exe);
+ paths.addArtifactArg(recorded);
+ _ = paths.addOutputDirectoryArg("paths");
+ paths.has_side_effects = true;
+ paths.expectExitCode(0);
+ test_step.dependOn(&paths.step);
+ b.step("test-paths", "Check where the save goes").dependOn(&paths.step);
+
+ // The tree by name and the fs verbs, live and with the sketch closed.
+ const tree = b.addSystemCommand(&.{ "sh", "-c",
+ \\set -e
+ \\exe=$(realpath "$0"); lib=$(realpath "$1"); mkdir -p "$2"; d=$(realpath "$2")
+ \\rm -rf "$d"/*; cd "$d"; rt=$(mktemp -d /tmp/sketchbook-fs.XXXXXX)
+ \\unset PARDES_PID PARDES_9P PARDES_PANE PARDES_MOUNT NINE_MOUNT NINE_MNTGEN
+ \\export XDG_RUNTIME_DIR="$rt" XDG_DATA_HOME="$d/data"
+ \\fs() { "$exe" --9p fstest "$lib" fs "$@"; }
+ \\"$exe" --headless --fresh --state live.xitdb --9p fstest "$lib" & pid=$!
+ \\trap 'kill $pid 2>/dev/null || true; rm -rf "$rt"' EXIT
+ \\i=0; while ! test -S "$rt"/9p/sketchbook/fstest; do i=$((i+1)); test $i -lt 500; sleep 0.01; done
+ \\fs ls | grep -qx 'state/'
+ \\fs write state/dots/buffer/2/kind big; test "$(fs read state/dots/buffer/2/kind)" = .big
+ \\! fs write state/dots/buffer/2/kind huge 2>err; grep -q InvalidValue err
+ \\fs write ctl 'click 30 40'
+ \\test "$(fs read screen.png | head -c 4 | tail -c 3)" = PNG
+ \\fs help state/dots | grep -q '^state/dots/len '
+ \\fs help ctl | grep -q '^ click X Y '
+ \\fs write ctl quit; wait $pid
+ \\test ! -e "$rt"/9p/sketchbook/fstest
+ \\test "$(fs read state/dots/buffer/2/kind 2>err)" = .small; grep -q 'replay is not running' err
+ \\! fs read status 2>err; grep -q 'replay is not running' err
+ \\rm -rf "$d"/*
+ });
+ tree.setName("the tree by name, live and closed");
+ tree.addArtifactArg(host_exe);
+ tree.addArtifactArg(recorded);
+ _ = tree.addOutputDirectoryArg("tree");
+ tree.has_side_effects = true;
+ tree.expectExitCode(0);
+ test_step.dependOn(&tree.step);
+ b.step("test-fs", "Drive a sketch's tree by name with the fs verbs, running and closed").dependOn(&tree.step);
+
// Recorded input replays to the same state: played, seeked, stepped,
// and after a live pointer move (core host behaviour, not an API).
const replay = b.addRunArtifact(host_exe);
@@ -523,9 +790,8 @@ pub fn init(b: *Build, options: Options) Sketchbook {
.b = b,
.target = options.target,
.optimize = options.optimize,
- .modules = .{ .abi = dep.module("abi"), .sketch = dep.module("sketch"), .host = dep.module("host"), .tracy = dep.module("tracy"), .vector = dep.module("vector"), .scope = dep.module("scope"), .anim = dep.module("anim"), .gltf = dep.module("gltf") },
+ .modules = .{ .abi = dep.module("abi"), .sketch = dep.module("sketch"), .host = dep.module("host"), .tracy = dep.module("tracy"), .vector = dep.module("vector"), .scope = dep.module("scope"), .anim = dep.module("anim"), .gltf = dep.module("gltf"), .cloud9 = dep.module("cloud9") },
.host_exe = dep.artifact("sketchbook"),
- .probe_exe = dep.artifact("sketchbook-probe"),
.gltf_generator = dep.artifact("gltf-bindings"),
.web = dep.path("web"),
.glsl = dep.path("src/glsl.zig"),
@@ -552,6 +818,9 @@ const Shared = struct {
openssl: ?Build.LazyPath = null,
/// A self-signed certificate and its key, for `addServe`.
certificate: ?Certificate = null,
+ /// `source`, the revision the build's sketches are made from (see
+ /// `buildInfo`).
+ build_info: ?*Build.Module = null,
const Certificate = struct { cert: Build.LazyPath, key: Build.LazyPath };
const Recipe = union(enum) { glsl: Sketchbook.ShaderOptions, zig: Sketchbook.ZigShaderOptions };
@@ -571,11 +840,11 @@ pub const Sketchbook = struct {
/// waveform, spectrogram, spectrum and oscilloscope views of a sound.
/// `anim`: manim-style scenes as code (see `addScene`).
/// `gltf`: native glTF/GLB documents, accessors and extras through cgltf.
- modules: struct { abi: *Build.Module, sketch: *Build.Module, host: *Build.Module, tracy: *Build.Module, vector: *Build.Module, scope: *Build.Module, anim: *Build.Module, gltf: *Build.Module },
+ /// `cloud9` is the 9P library the host serves its tree with: its `Fsys`
+ /// dials a sketch's executable from the app's own tests.
+ modules: struct { abi: *Build.Module, sketch: *Build.Module, host: *Build.Module, tracy: *Build.Module, vector: *Build.Module, scope: *Build.Module, anim: *Build.Module, gltf: *Build.Module, cloud9: *Build.Module },
/// The generic host: loads and hot-reloads a sketch library.
host_exe: *Build.Step.Compile,
- /// Prints any sketch's state file.
- probe_exe: *Build.Step.Compile,
/// `host.js` and the `index.html` template.
web: Build.LazyPath,
/// The GLSL declaration generator (see `addGlslLayouts`).
@@ -980,6 +1249,30 @@ pub const Sketchbook = struct {
return b.createModule(.{ .root_source_file = dir.path(b, "typst.zig") });
}
+ /// The module `build_info`: `source`, the revision of the repository
+ /// the build runs in, read once per build.
+ // ponytail: one `jj log -r @` (else git, else nothing) per build, on the
+ // critical path of every sketch compile: 10-20 ms, a `snapshot working
+ // copy` op in the user's op log per build, and `sh` only. Upgrade, once
+ // incremental builds make 10 ms matter: the development host asks the
+ // repository at load time instead, off the compile path. Never fails a
+ // build: any error is "no source".
+ fn buildInfo(sb: Sketchbook) *Build.Module {
+ if (sb.shared.build_info) |module| return module;
+ const b = sb.b;
+ const run = b.addSystemCommand(&.{ "sh", "-c",
+ \\r=$(jj log --no-graph -r @ -T 'commit_id ++ " " ++ change_id' 2>/dev/null) && r="jj:$r" ||
+ \\ { r=$(git rev-parse HEAD 2>/dev/null) && { git diff --quiet HEAD 2>/dev/null || r="$r+dirty"; } && r="git:$r"; } ||
+ \\ r=""
+ \\printf 'pub const source = "%s";\n' "$r"
+ });
+ run.setCwd(b.path("."));
+ run.setName("source revision");
+ run.has_side_effects = true;
+ sb.shared.build_info = b.createModule(.{ .root_source_file = run.captureStdOut(.{ .basename = "build_info.zig" }) });
+ return sb.shared.build_info.?;
+ }
+
pub fn app(sb: Sketchbook, options: App.Options) App {
const imports = sb.b.allocator.alloc(Build.Module.Import, options.imports.len + 1) catch @panic("OOM");
imports[0] = .{ .name = "sketch", .module = sb.modules.sketch };
@@ -989,6 +1282,7 @@ pub const Sketchbook = struct {
.name = options.name,
.root_source_file = options.root_source_file,
.imports = imports,
+ .record = options.record,
// No target: every artifact compiles it for its own.
.module = sb.b.createModule(.{ .root_source_file = options.root_source_file, .imports = imports }),
};
@@ -1002,6 +1296,7 @@ pub const App = struct {
imports: []const Build.Module.Import,
/// The app's root, importing `sketch` and the app's own imports.
module: *Build.Module,
+ record: ?bool,
pub const Options = struct {
name: []const u8,
@@ -1009,16 +1304,24 @@ pub const App = struct {
/// Imports for the app's root module, besides `sketch`: for example
/// `sb.modules.vector`, or shaders from `addSpirvModule`.
imports: []const Build.Module.Import = &.{},
+ /// Keep every run's history in the save, the newest 64 MiB of it
+ /// (src/host/Sessions.zig); without, the save keeps the present and
+ /// the marks only. Null: in Debug builds only. A
+ /// playtest build of a release opts in with one line,
+ /// `.record = b.option(bool, "record", "collect sessions in a release build")`.
+ record: ?bool = null,
};
- /// A root module around the app: `source` sees `app`, `sketch` and `host`.
+ /// A root module around the app: `source` sees `app`, `sketch` and `host`,
+ /// and `{made}` in it becomes the app's `sketch.Build`.
fn wrap(app: App, source: []const u8, target: Build.ResolvedTarget, optimize: std.builtin.OptimizeMode) *Build.Module {
const b = app.sb.b;
+ const made = b.fmt(".{{ .source = @import(\"build_info\").source, .record = {} }}", .{app.record orelse (optimize == .debug)});
const root = b.createModule(.{
- .root_source_file = b.addWriteFiles().add("root.zig", source),
+ .root_source_file = b.addWriteFiles().add("root.zig", std.mem.replaceOwned(u8, b.allocator, source, "{made}", made) catch @panic("OOM")),
.target = target,
.optimize = optimize,
- .imports = &.{ .{ .name = "app", .module = app.module }, .{ .name = "sketch", .module = app.sb.modules.sketch } },
+ .imports = &.{ .{ .name = "app", .module = app.module }, .{ .name = "sketch", .module = app.sb.modules.sketch }, .{ .name = "build_info", .module = app.sb.buildInfo() } },
});
if (std.mem.indexOf(u8, source, "\"host\"") != null) root.addImport("host", app.sb.modules.host);
return root;
@@ -1029,7 +1332,7 @@ pub const App = struct {
return app.sb.b.addLibrary(.{
.name = app.name,
.linkage = .dynamic,
- .root_module = app.wrap("comptime { @import(\"sketch\").exportSketch(@import(\"app\")); }", app.sb.target, app.sb.optimize),
+ .root_module = app.wrap("comptime { @import(\"sketch\").exportSketch(@import(\"app\"), {made}); }", app.sb.target, app.sb.optimize),
});
}
@@ -1051,7 +1354,7 @@ pub const App = struct {
.root_module = app.wrap(
\\const std = @import("std");
\\pub fn main(init: std.process.Init) !void {
- \\ return @import("host").main(init, @import("sketch").sketch(@import("app")));
+ \\ return @import("host").main(init, @import("sketch").sketch(@import("app"), {made}));
\\}
, app.sb.target, optimize),
});
@@ -1202,7 +1505,8 @@ pub const App = struct {
}
pub const RunOptions = struct {
- /// State file, relative to the working directory.
+ /// The save, relative to the working directory;
+ /// `.sketchbook/<name>.xitdb` by default, ignored by git and jj.
state: ?[]const u8 = null,
/// Where relative asset paths resolve; the project root by default.
cwd: ?Build.LazyPath = null,
@@ -1215,7 +1519,7 @@ pub const App = struct {
const install = b.addInstallArtifact(library, .{});
const run = b.addRunArtifact(app.sb.host_exe);
run.step.dependOn(&install.step);
- run.addArgs(&.{ "--state", options.state orelse b.fmt("{s}.state", .{app.name}) });
+ run.addArgs(&.{ "--state", options.state orelse b.fmt(".sketchbook/{s}.xitdb", .{app.name}) });
run.addFileArg(b.graph.path(.install_lib, library.out_filename));
run.setCwd(options.cwd orelse b.path("."));
run.stdio = .inherit;
@@ -1229,7 +1533,7 @@ pub const App = struct {
cwd: ?Build.LazyPath = null,
};
- /// Plays a script headless, with a throwaway state file, against
+ /// Plays a script headless, from fresh state and saving nothing, against
/// `artifact`: the executable (`addExecutable`), or the hot-reloadable
/// library (`addLibrary`) through the generic host, which scripts can
/// `reload`. Fails when an expectation or a console line does.
@@ -1241,7 +1545,7 @@ pub const App = struct {
run.addFileArg(script);
run.addArg("--state");
// Named per script: runs of one app may share an output directory.
- _ = run.addOutputFileArg(b.fmt("{s}-{s}.state", .{ app.name, std.fs.path.stem(script.getDisplayName()) }));
+ _ = run.addOutputFileArg(b.fmt("{s}-{s}.xitdb", .{ app.name, std.fs.path.stem(script.getDisplayName()) }));
for (options.defines) |pair| run.addArgs(&.{ "--define", b.fmt("{s}={s}", .{ pair[0], pair[1] }) });
if (library) run.addArtifactArg(artifact);
run.setCwd(options.cwd orelse b.path("."));
@@ -1271,7 +1575,7 @@ pub const App = struct {
const b = app.sb.b;
const run = b.addRunArtifact(exe);
run.addArg("--state");
- _ = run.addOutputFileArg(b.fmt("{s}-export.state", .{app.name}));
+ _ = run.addOutputFileArg(b.fmt("{s}-export.xitdb", .{app.name}));
run.addArg("--export");
const frames = run.addOutputDirectoryArg("frames");
run.addArgs(&.{ "--fps", b.fmt("{d}", .{options.fps}) });
@@ -1282,17 +1586,6 @@ pub const App = struct {
return .{ .run = run, .frames = frames };
}
- /// Prints the app's live state; `zig build probe -- --watch` follows it.
- pub fn addProbe(app: App, state: ?[]const u8) *Build.Step.Run {
- const b = app.sb.b;
- const run = b.addRunArtifact(app.sb.probe_exe);
- run.addArg(state orelse b.fmt("{s}.state", .{app.name}));
- run.setCwd(b.path("."));
- run.stdio = .inherit;
- run.addPassthruArgs();
- return run;
- }
-
/// Tests in `root_source_file` (the app's root by default), with the
/// app's imports and the app itself importable as `app`.
pub fn addTest(app: App, options: struct { root_source_file: ?Build.LazyPath = null }) *Build.Step.Compile {
@@ -1537,7 +1830,7 @@ pub const App = struct {
/// The conventional wiring. Installs the executable, and adds:
/// `run` (host + hot reload), `lib` (rebuild the library; use `--watch`),
- /// `web` and `serve` (with `web` options), `probe`, `export` (frames
+ /// `web` and `serve` (with `web` options), `export` (frames
/// for ffmpeg), `e2e` (scripts) and `test`.
pub fn addSteps(app: App, options: StepsOptions) Steps {
const b = app.sb.b;
@@ -1548,7 +1841,6 @@ pub const App = struct {
const run = app.addRun(library, .{});
b.step("run", "Run with hot reload (rebuild with `zig build lib --watch`)").dependOn(&run.step);
b.step("lib", "Build and install the hot-reloadable library").dependOn(&b.addInstallArtifact(library, .{}).step);
- b.step("probe", "Print the live state (-- --watch to follow)").dependOn(&app.addProbe(null).step);
const web = if (options.web) |web_options| blk: {
const web = app.addWeb(web_options);
@@ -1560,7 +1852,7 @@ pub const App = struct {
// `--export` takes the first argument after `--`.
const exporting = b.addRunArtifact(exe);
- exporting.addArgs(&.{ "--state", b.fmt("{s}.state", .{app.name}), "--export" });
+ exporting.addArgs(&.{ "--state", b.fmt(".sketchbook/{s}.xitdb", .{app.name}), "--export" });
exporting.addPassthruArgs();
exporting.setCwd(b.path("."));
exporting.stdio = .inherit;
diff --git a/build.zig.zon b/build.zig.zon
index f48b70a..828a17e 100644
--- a/build.zig.zon
+++ b/build.zig.zon
@@ -11,6 +11,13 @@
.url = "git+https://codeberg.org/ziglang/translate-c?ref=zig-0.17.x#cfac21f3199b2b02ce3fd7db652aa456421fe4ab",
.hash = "translate_c-2.0.2-Q_BUWvBNBwDnyehSiuAJmdFcMYHYGA-Jc3KiYdrV2Dqx",
},
+ // Sessions (src/host/Sessions.zig). Lazy: a `gpu-only` embedder
+ // builds no host and fetches none of it.
+ .xitdb = .{
+ .url = "https://github.com/xit-vcs/xitdb/archive/6b93af1af3a260399fa0a0b1b268ded2cbf5eec5.tar.gz",
+ .hash = "xitdb-0.0.0-EEFkxhwmBwDz1N8H9oHhVhd1Al5YZp8iDhaMLm2_79pS",
+ .lazy = true,
+ },
},
.minimum_zig_version = "0.17.0",
.paths = .{ "build.zig", "build.zig.zon", "src", "tools", "vendor", "web" },
diff --git a/examples/manual.zig b/examples/manual.zig
new file mode 100644
index 0000000..7a53533
--- /dev/null
+++ b/examples/manual.zig
@@ -0,0 +1,312 @@
+//! Two pages of the Intel SDM (Vol. 2) as a talk, in two slides. The
+//! pages are Typst's import of the PDF, every glyph and rule a vector
+//! shape; what moves are `part`s of them, cut out by rectangles in the
+//! page's units (read off the player's guides and `pdftotext -bbox`,
+//! points to units: (pt - 306) * 4/3 across, (pt - 396) * 4/3 down).
+//!
+//! 1. Figure 2-1, the instruction format (page 31), comes alive: `83 C0
+//! 01`, `add eax, 1`, is written below, its bytes fly into their
+//! fields, and C0 splits into its ModR/M bits.
+//! 2. ADD's opcode table (page 132) is written row by row; its row `80 /0
+//! ib` becomes SUB's `80 /5 ib` (page 1400): the digit first, alone,
+//! then the rest of the row, and the two rows end one over the other.
+//!
+//! The PDF is the build's `-Dmanual` (`~/01-resources/intel-devref-ii.pdf`
+//! by default) and is never committed; without it the scene says so.
+//!
+//! click, space, page down next step page up back
+//! ] / [ next / previous slide
+const std = @import("std");
+const anim = @import("anim");
+const pdf: ?[]const u8 = @import("manual").pdf;
+
+pub const name = "manual";
+pub const hold = 1.5;
+pub const typst_preamble =
+ \\#set page(width: auto, height: auto, margin: 0pt, fill: none)
+ \\#set text(font: "DejaVu Sans Mono", size: 14pt, fill: rgb("#c0392b"))
+;
+pub const typst = struct {
+ pub const page = "#image(\"" ++ (pdf orelse "") ++ "\", page: 31)";
+ pub const title = "#text(font: \"New Computer Modern\", size: 40pt, fill: rgb(\"#ece6e2\"))[Figure 2-1, alive]";
+ pub const from = "#text(font: \"New Computer Modern\", size: 16pt, fill: rgb(\"#8c8c8c\"))[Intel® 64 and IA-32 SDM, Vol. 2, page 31]";
+ pub const add = "#text(fill: rgb(\"#555555\"))[add eax, 1]";
+ pub const b83 = "83";
+ pub const c0 = "C0";
+ pub const b01 = "01";
+ pub const bits = "11000000";
+ pub const direct = "#text(size: 8pt, fill: rgb(\"#555555\"))[direct]";
+ pub const is_add = "#text(size: 8pt, fill: rgb(\"#555555\"))[/0 ADD]";
+ pub const eax = "#text(size: 8pt, fill: rgb(\"#555555\"))[EAX]";
+ pub const add_page = "#image(\"" ++ (pdf orelse "") ++ "\", page: 132)";
+ pub const sub_page = "#image(\"" ++ (pdf orelse "") ++ "\", page: 1400)";
+ pub const table_title = "#text(font: \"New Computer Modern\", size: 40pt, fill: rgb(\"#ece6e2\"))[ADD, then SUB]";
+ pub const table_from = "#text(font: \"New Computer Modern\", size: 16pt, fill: rgb(\"#8c8c8c\"))[Intel® 64 and IA-32 SDM, Vol. 2, pages 132 and 1400]";
+ pub const group = "#text(font: \"New Computer Modern\", size: 11pt, fill: rgb(\"#555555\"))[One opcode byte, 80: the reg field of the ModR/M byte picks the operation]";
+};
+const missing = struct {
+ pub const note = "#text(font: \"New Computer Modern\", size: 24pt, fill: rgb(\"#ece6e2\"))[No manual: build with `-Dmanual=/path/to/intel-sdm-vol2.pdf`]";
+};
+pub const scene = anim.Live(if (pdf == null) placeholder else talk, if (pdf == null) missing else typst);
+
+fn placeholder(s: *anim.Frame) void {
+ s.play(.{s.typst(missing.note, .{}).write()}, .{});
+}
+
+/// Rectangles in the page's units, as `s.part` and `s.rect` take them.
+const Area = struct { x: f32, y: f32, w: f32, h: f32 };
+
+/// The labels of the figure's top row of fields: Prefixes, Opcode,
+/// ModR/M, SIB, Displacement, Immediate (inside the rules, which stay).
+const fields = [_]Area{
+ .{ .x = -199.5, .y = -110.7, .w = 69.3, .h = 33.3 },
+ .{ .x = -127.5, .y = -110.7, .w = 69.3, .h = 33.3 },
+ .{ .x = -55.5, .y = -110.7, .w = 69.3, .h = 33.3 },
+ .{ .x = 16.5, .y = -110.7, .w = 69.3, .h = 33.3 },
+ .{ .x = 100.5, .y = -110.7, .w = 93.3, .h = 33.3 },
+ .{ .x = 184.9, .y = -110.7, .w = 70.1, .h = 33.3 },
+};
+const opcode = 1;
+const modrm = 2;
+const immediate = 5;
+/// The ModR/M byte's own boxes: Mod, Reg/Opcode, R/M.
+const bit_boxes = [_]Area{
+ .{ .x = -144.0, .y = 5.3, .w = 33.3, .h = 25.3 },
+ .{ .x = -102.0, .y = 5.3, .w = 45.3, .h = 25.3 },
+ .{ .x = -53.7, .y = 5.3, .w = 46.0, .h = 25.3 },
+};
+/// The ModR/M byte's three boxes together, across.
+const byte_x = -95.7;
+/// The figure: both rows of boxes, the arrows and the notes; and its
+/// footnotes, under it.
+const figure: Area = .{ .x = -7.3, .y = -54.7, .w = 468, .h = 160 };
+const footnotes: Area = .{ .x = -8, .y = 70.7, .w = 453, .h = 56 };
+/// `11000000` in its own units: 8 characters of 0.6 em at 14 pt.
+const char = 0.6 * 14 * 4.0 / 3.0;
+
+fn talk(s: *anim.Frame) void {
+ s.slide();
+ instructionFormat(s);
+ s.pause();
+ s.clear(.{ .seconds = 0.8 });
+ s.slide();
+ opcodeTable(s);
+}
+
+/// Slide 1: Figure 2-1 comes alive.
+fn instructionFormat(s: *anim.Frame) void {
+ // The page, whole, on paper; the camera far enough out to see it all.
+ const paper = s.rect(.{ .w = 816, .h = 1056, .fill = 0xffffff });
+ const page = s.typst(typst.page, .{});
+ const title = s.typst(typst.title, .{ .x = -700, .y = -380 });
+ const from = s.typst(typst.from, .{ .x = -700, .y = -325 });
+ // A tint over each field's label box (the same rectangle as its part),
+ // laid before the parts so that they draw over it.
+ var tints: [fields.len]anim.Obj = undefined;
+ for (&tints, fields) |*t, f| t.* = s.rect(.{ .x = f.x, .y = f.y, .w = f.w, .h = f.h, .fill = 0x58c4dd60 });
+ s.play(.{anim.camera(.{ .zoom = 0.65 })}, .{ .seconds = 0 });
+ s.play(.{ title.write(), from.fadeIn(), paper.fadeIn(), page.fadeIn() }, .{ .seconds = 2 });
+ s.pause();
+
+ // Onto the figure. Its labels, the ModR/M byte's boxes, the figure
+ // around them and its footnotes become parts of the page; the rest of
+ // the page greys, and the footnotes go, to make room.
+ var labels: [fields.len]anim.Obj = undefined;
+ for (&labels, fields) |*l, f| l.* = s.part(page, f);
+ var boxes: [bit_boxes.len]anim.Obj = undefined;
+ for (&boxes, bit_boxes) |*b, area| b.* = s.part(page, area);
+ _ = s.part(page, figure);
+ const notes = s.part(page, footnotes);
+ s.play(.{ anim.camera(.{ .zoom = 2.3, .x = -7, .y = -35 }), page.move(.{ .opacity = 0.25 }), notes.fadeOut(), title.fadeOut(), from.fadeOut() }, .{ .seconds = 1.5 });
+ s.pause();
+
+ // Each field in turn.
+ for (labels, tints, 0..) |label, tint, i| {
+ if (i > 0) s.play(.{ tints[i - 1].fadeOut(), label.indicate(), tint.fadeIn() }, .{}) else s.play(.{ label.indicate(), tint.fadeIn() }, .{});
+ s.pause();
+ }
+ s.play(.{tints[fields.len - 1].fadeOut()}, .{ .seconds = 0.5 });
+
+ // An instruction: add eax, 1.
+ const b83 = s.typst(typst.b83, .{ .x = -40, .y = 70 });
+ const c0 = s.typst(typst.c0, .{ .y = 70 });
+ const b01 = s.typst(typst.b01, .{ .x = 40, .y = 70 });
+ const add = s.typst(typst.add, .{ .x = 150, .y = 70 });
+ s.play(.{ b83.write(), c0.write(), b01.write(), add.write() }, .{ .seconds = 1.5, .lag = 0.3 });
+ s.pause();
+
+ // Each byte flies into its field; the fields it has none for fade.
+ var flights: [fields.len + 3]anim.Animation = undefined;
+ for (labels, 0..) |label, i| flights[i] = switch (i) {
+ opcode, modrm, immediate => label.fadeOut(),
+ else => label.move(.{ .opacity = 0.3 }),
+ };
+ flights[6] = b83.move(.{ .x = fields[opcode].x, .y = fields[opcode].y, .scale = 1.3 });
+ flights[7] = c0.move(.{ .x = fields[modrm].x, .y = fields[modrm].y, .scale = 1.3 });
+ flights[8] = b01.move(.{ .x = fields[immediate].x, .y = fields[immediate].y, .scale = 1.3 });
+ s.play(flights, .{ .seconds = 1.5, .lag = 0.2 });
+ s.pause();
+
+ // C0 is a ModR/M byte: down the arrow into its boxes, as bits.
+ const bits = s.typst(typst.bits, .{ .x = byte_x, .y = bit_boxes[0].y });
+ s.play(.{ boxes[0].fadeOut(), boxes[1].fadeOut(), boxes[2].fadeOut(), c0.transformInto(bits) }, .{ .seconds = 1.5 });
+ s.pause();
+
+ // 11 000 000: mod, reg, r/m, each into its box, and what it says.
+ const mod = s.part(bits, .{ .x = -3 * char, .w = 2 * char, .h = 40 });
+ const reg = s.part(bits, .{ .x = -0.5 * char, .w = 3 * char, .h = 40 });
+ const rm = s.part(bits, .{ .x = 2.5 * char, .w = 3 * char, .h = 40 });
+ const says = [_]anim.Obj{
+ s.typst(typst.direct, .{ .x = bit_boxes[0].x, .y = 28 }),
+ s.typst(typst.is_add, .{ .x = bit_boxes[1].x, .y = 28 }),
+ s.typst(typst.eax, .{ .x = bit_boxes[2].x, .y = 28 }),
+ };
+ s.play(.{
+ mod.move(.{ .x = bit_boxes[0].x }),
+ reg.move(.{ .x = bit_boxes[1].x }),
+ rm.move(.{ .x = bit_boxes[2].x }),
+ says[0].write(),
+ says[1].write(),
+ says[2].write(),
+ }, .{ .seconds = 1.5 });
+ s.pause();
+
+ // Back to the page, filled in.
+ s.play(.{ anim.camera(.{ .zoom = 0.65, .x = 0, .y = 0 }), page.move(.{ .opacity = 1 }), notes.fadeIn(), add.fadeOut(), title.fadeIn(), from.fadeIn() }, .{ .seconds = 1.5 });
+}
+
+/// PDF points, a box from the top left of a 612 x 792 pt page, as an area
+/// in the page's units.
+fn onPage(x0: f32, y0: f32, x1: f32, y1: f32) Area {
+ return .{ .x = ((x0 + x1) / 2 - 306) * 4.0 / 3.0, .y = ((y0 + y1) / 2 - 396) * 4.0 / 3.0, .w = (x1 - x0) * 4.0 / 3.0, .h = (y1 - y0) * 4.0 / 3.0 };
+}
+
+/// ADD's opcode table on page 132, in points: the y of each of its
+/// horizontal rules, from the top of the header row to the foot of the
+/// last. The page draws the table's text row by row, left to right, and
+/// its rules after all of its text; a row is taken with the rule above
+/// it, so it is written with it.
+const add_rules = [_]f32{ 82, 107, 122, 137, 152, 167, 182, 197, 212, 227, 253, 268, 283, 298, 313, 328, 343, 358, 373, 388, 403, 418, 433, 448 };
+/// The column rules run the table's whole height, so their centres all
+/// lie in one row (`83 /0 ib`, at 265 pt) and would go with it: a band
+/// one point high through 265 takes them first, and nothing else.
+const column_rules = onPage(40, 264.5, 565, 265.5);
+/// The row `80 /0 ib ADD r/m8, imm8`, between the rules at 167 and 182.
+/// SUB's `80 /5 ib SUB r/m8, imm8` is a row lower on page 1400 (182 to
+/// 197), so that page stands 15 pt (20 units) higher: the rows coincide.
+const row = 5;
+const sub_y = -20;
+/// Each of the two rows in the same eight pieces, in points across (from
+/// `pdftotext -bbox`): the digit after the slash (`0`, `5`; its glyph's
+/// centre is at 67.5 in both), then the spans between these cuts: the
+/// rest of the opcode (`80 /`, `ib`), the instruction, the three short
+/// columns, and the description, word by word (`Add`, `imm8`, `to`,
+/// `r/m8.`; `Subtract`, `imm8`, `from`, `r/m8.`).
+const add_cuts = [_]f32{ 46.5, 144, 256, 376, 395, 418, 428.5, 557 };
+const sub_cuts = [_]f32{ 46.5, 144, 256, 376, 412.5, 436, 457, 557 };
+const digit = 0;
+/// The pieces that morph with the row, and those that are the same glyphs
+/// in the same places in both rows, and hold.
+const follow = [_]usize{ 2, 4, 5, 6, 7 };
+const same = [_]usize{ 1, 3 };
+/// What differs, marked at the end, in points across: the digit, the
+/// mnemonic, and two words of the description (ADD's, then SUB's).
+const add_differs = [_][2]f32{ .{ 65.5, 70.5 }, .{ 146, 166 }, .{ 377, 395 }, .{ 418, 428.5 } };
+const sub_differs = [_][2]f32{ .{ 65.5, 70.5 }, .{ 146, 166 }, .{ 377, 412.5 }, .{ 436, 457 } };
+/// How far below ADD's row SUB's goes at the end, in units (a row is 20).
+const gap = 30;
+
+/// Piece `i` of a row between `y0` and `y1` (points) cut at `cuts`.
+fn piece(cuts: []const f32, i: usize, y0: f32, y1: f32) Area {
+ return if (i == digit) onPage(65.5, y0, 70.5, y1) else onPage(cuts[i - 1], y0, cuts[i], y1);
+}
+
+/// Slide 2: ADD's opcode table, written row by row, and its row `80 /0 ib`
+/// turned into SUB's `80 /5 ib`.
+fn opcodeTable(s: *anim.Frame) void {
+ const paper = s.rect(.{ .w = 816, .h = 1056, .fill = 0xffffff });
+ const add = s.typst(typst.add_page, .{});
+ const sub = s.typst(typst.sub_page, .{ .y = sub_y });
+ const title = s.typst(typst.table_title, .{ .x = -700, .y = -380 });
+ const from = s.typst(typst.table_from, .{ .x = -700, .y = -325 });
+ // Tints, laid before the parts so that they draw over them: the
+ // row's opcode cell, and what differs, over ADD's row and over SUB's
+ // where it ends.
+ const cell = onPage(46, 167, 144.6, 182);
+ const tint = s.rect(.{ .x = cell.x, .y = cell.y, .w = cell.w, .h = cell.h, .fill = 0x58c4dd60 });
+ var marks: [add_differs.len + sub_differs.len]anim.Obj = undefined;
+ for (&marks, add_differs ++ sub_differs, 0..) |*m, d, i| {
+ const a = onPage(d[0], 167, d[1], 182);
+ const down: f32 = if (i < add_differs.len) 0 else gap;
+ m.* = s.rect(.{ .x = a.x, .y = a.y + down, .w = a.w, .h = a.h, .fill = 0xf7d96f80 });
+ }
+
+ // The table comes out of the page before it shows, to be written in:
+ // the column rules, then each row (the last with the rule under it
+ // too). And SUB's row out of its page, piece by piece.
+ const columns = s.part(add, column_rules);
+ var rows: [add_rules.len - 1]anim.Obj = undefined;
+ for (&rows, 0..) |*r, i| {
+ const foot = if (i == rows.len - 1) add_rules[i + 1] + 0.5 else add_rules[i + 1] - 0.5;
+ r.* = s.part(add, onPage(40, add_rules[i] - 0.5, 565, foot));
+ }
+ var subs: [add_cuts.len]anim.Obj = undefined;
+ for (&subs, 0..) |*p, i| p.* = s.part(sub, piece(&sub_cuts, i, 182.5, 196.5));
+
+ s.play(.{anim.camera(.{ .zoom = 0.65, .x = 0, .y = 0 })}, .{ .seconds = 0 });
+ s.play(.{ title.write(), from.fadeIn(), paper.fadeIn(), add.fadeIn() }, .{ .seconds = 2 });
+ s.pause();
+
+ // The table, row by row.
+ s.play(.{columns.create()}, .{ .seconds = 0.6 });
+ for (rows) |r| s.play(.{r.write()}, .{ .seconds = 0.25 });
+ s.pause();
+
+ // Onto the row 80 /0 ib, cut in its pieces; the rest greys.
+ const at = onPage(40, add_rules[row] - 0.5, 565, add_rules[row + 1] - 0.5);
+ var adds: [add_cuts.len]anim.Obj = undefined;
+ for (&adds, 0..) |*p, i| {
+ const a = piece(&add_cuts, i, 167.5, 181.5);
+ p.* = s.part(rows[row], .{ .x = a.x - at.x, .y = a.y - at.y, .w = a.w, .h = a.h });
+ }
+ var grey: [rows.len + 5]anim.Animation = undefined;
+ for (rows, 0..) |r, i| grey[i] = r.move(.{ .opacity = 0.25 });
+ grey[rows.len..].* = .{ columns.move(.{ .opacity = 0.25 }), add.move(.{ .opacity = 0.25 }), title.fadeOut(), from.fadeOut(), anim.camera(.{ .zoom = 1.7, .x = at.x, .y = at.y }) };
+ s.play(grey, .{ .seconds = 1.5 });
+ s.pause();
+
+ // Its opcode cell, and the opcode in it: the digit and the rest.
+ s.play(.{ tint.fadeIn(), adds[digit].indicate(), adds[1].indicate() }, .{});
+ s.pause();
+
+ // Close in (a little right of the cell, to stay on the paper): the
+ // digit after the slash, and only it, becomes SUB's.
+ s.play(.{anim.camera(.{ .zoom = 4, .x = cell.x + 40, .y = at.y })}, .{});
+ s.play(.{adds[digit].transformInto(subs[digit])}, .{ .seconds = 1.5 });
+ s.pause();
+
+ // The rest of the row follows, and the page around it is SUB's.
+ var swap: [rows.len + follow.len + 3]anim.Animation = undefined;
+ for (rows, 0..) |r, i| swap[i] = r.fadeOut();
+ for (follow, 0..) |i, j| swap[rows.len + j] = adds[i].transformInto(subs[i]);
+ swap[rows.len + follow.len ..].* = .{ columns.fadeOut(), add.fadeOut(), anim.camera(.{ .zoom = 1.7, .x = at.x, .y = at.y }) };
+ s.play(swap, .{ .seconds = 2 });
+ s.play(.{ sub.fadeIn(), sub.move(.{ .opacity = 0.25 }) }, .{});
+ s.pause();
+
+ // ADD's row again, and SUB's under it: the pieces that morphed come
+ // back, SUB's that held (the same glyphs as ADD's) come out from
+ // under them, what differs is marked, and why.
+ const group = s.typst(typst.group, .{ .x = at.x, .y = at.y + gap + 40 });
+ const back = [_]usize{digit} ++ follow;
+ var both: [back.len + same.len + subs.len + 3]anim.Animation = undefined;
+ for (back, 0..) |i, j| both[j] = adds[i].fadeIn();
+ for (same, 0..) |i, j| both[back.len + j] = subs[i].fadeIn();
+ for (subs, 0..) |p, i| both[back.len + same.len + i] = p.move(.{ .y = piece(&sub_cuts, i, 182.5, 196.5).y + sub_y + gap });
+ both[both.len - 3 ..].* = .{ sub.fadeOut(), tint.fadeOut(), anim.camera(.{ .zoom = 1.8, .x = at.x, .y = at.y + gap + 10 }) };
+ s.play(both, .{ .seconds = 1.5 });
+ var why: [marks.len + 1]anim.Animation = undefined;
+ for (marks, 0..) |m, i| why[i] = m.fadeIn();
+ why[marks.len] = group.write();
+ s.play(why, .{ .seconds = 1.5 });
+}
diff --git a/examples/micscope/README.md b/examples/micscope/README.md
new file mode 100644
index 0000000..875ebdf
--- /dev/null
+++ b/examples/micscope/README.md
@@ -0,0 +1,158 @@
+# micscope
+
+Records the microphone or opens sound files, plays them forwards or
+backwards, and shows each as a waveform, its spectrogram on the same time
+axis, and the spectrum at the playhead. A [sketchbook](../..) sketch, Linux only for now.
+
+The window shows a vertical strip of these panels, laid out in a world
+and seen through a camera, as in a game. Takes stack downwards in the
+order they were made, so each keeps its place; at the bottom is now: what
+the microphone hears, its last 6 s scrolling by, with the spectrum of the
+newest samples. Recording turns that panel red and fills it with the new
+take; stopping leaves the take there and puts the live view under it. The
+camera follows the bottom until you pan away, and follows again once you
+pan back down. Zoomed out, it overviews the whole strip. Every take keeps
+its own time zoom and playhead.
+
+A tuner reads the live sound (or the recording, or the selected take at
+its playhead) and shows it on that panel's spectrum: a line at the pitch,
+ticks at its harmonics, the two semitones either side shaded, and that
+shaded span magnified across the top: the nearest notes of the 12-tone
+chromatic scale, the pitch as a needle among them (green within 5 cents,
+yellow within 15), and the note, cents and Hz. It is not a guitar tuner
+in particular: it finds 30 Hz to 4.2 kHz, a five-string bass's low B to a
+piccolo's top, against any A4 (`[` and `]`, 440 Hz by default).
+
+Panels are rendered at world resolution and the camera only scales them,
+so moving or zooming it recomputes nothing.
+
+The waveform, spectrogram and spectrum shaders are sketchbook's `scope`
+module's (`src/scope/shaders/`): the live view is a `scope.Scope`, and the
+take panels run `scope.kernels` and `scope.pipelines` over the tape. The
+tuner's are micscope's own.
+
+| Shader | Does |
+| --- | --- |
+| `spectrum.comp` | Blackman-Harris window around the playhead, zero-padded 2×, radix-2 Stockham FFT (8192 points, one workgroup), dBFS per bin, then one value per log-spaced pixel column: a Catmull-Rom spline through the bins where columns are narrower than a bin, the loudest bin where they span several. Smoothed in time (fast attack, slow release) with falling peaks. |
+| `waveform.comp` | Per pixel column: min, max and RMS of its samples, plus the interpolated signal at the column's edges, so zoomed past one sample per pixel the columns still join into a line. Recomputed only when the view or tape changes. |
+| `spectrogram.comp` | One workgroup per waveform column, so it lines up with the waveform in time. A 2048-sample Blackman-Harris window zero-padded to 4096, transformed as 2048 complex points in shared memory (the real-input trick) and split into 2049 bins. Below 500 Hz a second analysis runs on the signal low-passed and decimated 4×: the same 2048 points span 170 ms and resolve ~6 Hz instead of 23, three windows a quarter apart averaged (Welch) so noise does not speckle; blended with the first between 250 and 500 Hz. Zoomed out, each column averages up to four windows spread across its samples, so it neither skips nor flickers. Rows are log frequency, interpolated like the spectrum. |
+| `tuner_difference.comp`, `tuner.comp` | Pitch by YIN rather than by the strongest FFT peak, which is often a harmonic (low strings, voices and brass put more into the 2nd or 3rd) or missing altogether (a missing fundamental). The difference function d(τ) = Σ(x[j] − x[j−τ])² over 2048 samples for lags up to 1700, spread over 107 workgroups; then in one workgroup, normalised by its running mean (a parallel scan), the first dip under 0.12 (the shortest period that explains the signal, so no octave drops) followed to its bottom, and a parabola through the raw dip for the period between samples. Read back to the CPU (`f.download`), which follows the median of the last five clear estimates, restarts on a jump of more than a semitone, and only changes the note shown 60 cents away from it. |
+| `waveform.frag`, `spectrogram.frag`, `spectrum.frag` | Full-screen triangles that draw those buffers: the waveform and spectrum anti-aliased with grids, the spectrogram through an inferno heat gradient. |
+
+The takes share one tape buffer on the GPU (each analysis reads from an
+offset), uploaded once. A take's waveform and spectrogram are recomputed
+only when its view changes, and its panel redrawn only when something on
+it moved; only the selected take's spectrum runs every frame.
+
+The live view (the scope module's) uploads the microphone's last 1.4 s each frame and analyses
+only the columns that became complete, into ring buffers the fragment
+shaders read from the oldest column. A column waits until everything its
+spectrogram windows reach has been heard (6160 samples past its centre),
+so it is analysed once and final: the live spectrogram runs about 130 ms
+behind, the live spectrum does not.
+
+## Keys
+
+| Key | |
+| --- | --- |
+| R | record a new take / stop |
+| Space | play / pause the selected take, resuming in the last direction |
+| Right / Left | play forwards / backwards |
+| Home / End | seek to the start / end |
+| Up / Down | select the older / newer take |
+| Delete | delete the selected take |
+| O | open a file (WAV, FLAC, Ogg Vorbis) as a take, through the system dialog |
+| click, drag | select a take; on its timeline, seek |
+| wheel, middle or right drag, Page Up / Down | pan the camera |
+| Ctrl + wheel, or a pinch | zoom what is under the pointer: a take's time on its timeline (Z unzooms), the camera elsewhere |
+| 0 | the whole strip, or back to full size |
+| - / = | waveform gain |
+| [ / ] | the tuner's A4, 1 Hz down / up |
+| \` | the sketchbook console: `open <path>` opens a file too |
+
+The buttons (REC, PLAY, REV, OPEN, DEL, ALL, A4−, A4+) do what the keys
+do, for touch screens: there, one finger clicks and drags, two fingers
+pan, and a pinch zooms like ctrl+wheel.
+
+The canvas is the window, and the layout follows it. Wide, each panel has
+the spectrum beside the waveform and spectrogram, and the buttons sit in
+the header; narrower than 760 px (a phone held upright), the spectrum goes
+under them at full width, and the buttons along the bottom, where thumbs
+are.
+
+## Rendering reference
+
+`test/reference.flac` puts a mastered song, a city street and a sweep on one
+screen (sources and licences in `test/README.md`); `zig build test` plays it
+through `test/render.script` and leaves screenshots in `.zig-cache/micscope/`.
+
+What it settled for the spectrogram's low end, checked against a plain
+numpy STFT of the same columns:
+
+- One long window resolves the street's two engine hums but shows noise as
+ speckle full of holes: a single window's spectrum of noise scatters as
+ much as its level.
+- Multitaper averaging (sine tapers, DPSS with NW 2 to 4) calms the noise but
+ widens the hums into one slab and leaks into silence, which a 96 dB scale
+ shows. Wrong trade for lines.
+- Averaging three windows a quarter apart in time keeps the hums sharp and
+ the kicks distinct, and settles the noise. That is what it does.
+
+`test/tones.wav` has five notes where the strongest peak is not the note
+(a bass E1 and a guitar E2 louder in their 2nd harmonic, a D4 without its
+fundamental), an A4 12 cents sharp and a piccolo C7; `test/tuner.script`
+screenshots the tuner on each. All read within 0.1 cent.
+
+## GPU time
+
+`zig build profile` zooms the reference one step per frame, recomputing the
+waveform and spectrogram every frame, and prints GPU time per command
+(`--profile-gpu`: each command timed alone on an idle GPU). On an RTX 3050:
+
+| Case | GPU per frame |
+| --- | --- |
+| playing, views cached | ~0.45 ms |
+| zooming the 32 s reference | ~1.1 ms on average, spectrogram 1.5 ms on the frames it recomputes |
+| zooming a 10 minute tape | ~1.6 ms on average, spectrogram 2.1 ms (worst 4.6 ms) |
+| zooming the reference, in the strip with the live view and both tuners | ~1.15 ms on average; the live view adds a spectrum (~0.15 ms) and a few columns, each tuner ~0.1 ms |
+
+## Building
+
+Zig 0.17 and `glslc` (shaderc) on PATH; for the web build also `naga`
+(`cargo install naga-cli`), which translates the shaders to WGSL, and to
+serve it `miniserve` and `openssl`.
+
+ zig build run # with hot reload: `zig build lib --watch` alongside
+ zig build test # unit tests and the headless scripts in test/
+ zig build profile # GPU time per command while zooming
+ zig-out/bin/micscope # the standalone build
+ zig build serve # the web build at https://<this machine>:8042/
+ # (`zig build web --watch` alongside rebuilds it)
+
+## On the web
+
+The same sketch, compiled to wasm32-freestanding, on WebGPU: every shader
+runs as on native, translated to WGSL, and the tuner's readback is a
+WebGPU buffer mapped a frame or two later. Sound and the microphone go
+through Web Audio (the page asks for the microphone, and sound starts at
+the first click or key, as browsers require); OPEN decodes a file with the
+browser's own decoders. Takes last as long as the page.
+
+It is an installable app (a PWA): browsers offer to add it to the home
+screen, and once opened it works offline, from a copy its service worker
+keeps of the page, the code and the wasm. The icon is `web/icon.svg`,
+rendered to the PNGs beside it with `resvg -w N -h N icon.svg icon-N.png`. It needs a browser
+with WebGPU (Chrome, Edge, Safari 26; Firefox on Linux with
+`dom.webgpu.enabled` set in about:config), and a secure context, which
+`zig build serve`'s https gives it on any device on the network once the
+browser has accepted its self-signed certificate (miniserve prints the
+addresses as QR codes, for phones).
+
+Each take is a file of its samples (mono 32-bit floats at the host's
+rate), `micscope.take-<id>.f32` beside the save (in `.sketchbook/`
+under `zig build run`), written as it records (`Host.appendFile`). State
+lists the takes, so they are still there after a restart. A take starts
+its file empty (`Host.writeFile`). A deleted take's file stays: a seek
+back, or any mark from before the delete, finds it again. Takes stop at ten minutes; the
+strip holds 64. A `micscope.state.store` from before is not read: its takes
+stay in it.
diff --git a/examples/micscope/build.zig b/examples/micscope/build.zig
new file mode 100644
index 0000000..2de639d
--- /dev/null
+++ b/examples/micscope/build.zig
@@ -0,0 +1,54 @@
+const std = @import("std");
+const sketchbook = @import("sketchbook");
+
+pub fn build(b: *std.Build) void {
+ const target = b.standardTargetOptions(.{});
+ const optimize = b.standardOptimizeOption(.{});
+ const sb = sketchbook.init(b, .{ .target = target, .optimize = optimize });
+
+ // The tuner's shaders, as SPIR-V for the native host and WGSL for the
+ // web; their uniform blocks come from the Zig structs in src/layouts.zig.
+ // The waveform, spectrogram and spectrum are the scope module's.
+ const layouts = b.createModule(.{ .root_source_file = b.path("src/layouts.zig") });
+ const shaders = sb.addShaders(.{
+ .layouts = .{ .module = layouts, .types = &.{"TunerParams"} },
+ .sources = &.{
+ b.path("shaders/tuner_difference.comp"),
+ b.path("shaders/tuner.comp"),
+ },
+ });
+
+ const app = sb.app(.{
+ .name = "micscope",
+ .root_source_file = b.path("src/main.zig"),
+ .imports = &.{
+ .{ .name = "layouts", .module = layouts },
+ .{ .name = "shaders", .module = shaders.module },
+ .{ .name = "scope", .module = sb.modules.scope },
+ },
+ });
+ const steps = app.addSteps(.{
+ // Installable, and it opens offline (icons from web/icon.svg).
+ .web = .{ .pwa = .{
+ .description = "Records the microphone, shows its waveform, spectrogram and spectrum, and tunes any instrument.",
+ .background = "#0b0c0f",
+ .theme = "#0b0c0f",
+ .icons = &.{
+ .{ .source = b.path("web/icon-192.png"), .size = 192 },
+ .{ .source = b.path("web/icon-512.png"), .size = 512 },
+ },
+ } },
+ .scripts = &.{ b.path("test/transport.script"), b.path("test/record.script"), b.path("test/render.script"), b.path("test/tuner.script") },
+ });
+
+ // GPU time per command while zooming, which recomputes every frame.
+ const profile = b.addRunArtifact(steps.exe);
+ profile.addArgs(&.{ "--headless", "--fresh", "--profile-gpu", "--script" });
+ profile.addFileArg(b.path("test/profile.script"));
+ profile.addArg("--state");
+ _ = profile.addOutputFileArg("profile.state");
+ profile.setCwd(b.path("."));
+ profile.has_side_effects = true;
+ profile.stdio = .inherit;
+ b.step("profile", "Print GPU time per command while zooming the reference").dependOn(&profile.step);
+}
diff --git a/examples/micscope/build.zig.zon b/examples/micscope/build.zig.zon
new file mode 100644
index 0000000..9c595cf
--- /dev/null
+++ b/examples/micscope/build.zig.zon
@@ -0,0 +1,10 @@
+.{
+ .name = .micscope,
+ .version = "0.0.1",
+ .dependencies = .{
+ .sketchbook = .{ .path = "../.." },
+ },
+ .minimum_zig_version = "0.17.0",
+ .paths = .{""},
+ .fingerprint = 0x780fbc0f374f0ce0,
+}
diff --git a/examples/micscope/shaders/tuner.comp b/examples/micscope/shaders/tuner.comp
new file mode 100644
index 0000000..1907f7f
--- /dev/null
+++ b/examples/micscope/shaders/tuner.comp
@@ -0,0 +1,134 @@
+#version 450
+#extension GL_GOOGLE_include_directive : require
+// The pitch of the newest (or the playhead's) sound, by YIN (de Cheveigné
+// and Kawahara, 2002), in one workgroup. Picking the strongest FFT peak
+// finds the loudest harmonic, which is often not the note: low strings,
+// voices and brass put more energy in the 2nd or 3rd harmonic, and a
+// missing fundamental has no peak at all. YIN looks for the period instead:
+//
+// 1. the difference function d(tau) = sum over the window of
+// (x[j] - x[j + tau])^2, which dips to 0 at every multiple of the
+// period, whatever the harmonics' balance;
+// 2. normalised by its running mean, d'(tau) = d(tau) * tau / sum d(1..tau),
+// which starts at 1 and removes the dip-at-zero bias, so the dips are
+// comparable;
+// 3. the first dip below an absolute threshold, then the bottom of it: the
+// shortest period that explains the signal, which keeps it from
+// dropping an octave onto a multiple of the period;
+// 4. a parabola through that dip of d and its neighbours, for a period
+// between samples: the semitone is 6 %, the cent 0.06 %, and whole samples
+// alone would be 30 cents apart at 1 kHz.
+layout(local_size_x = 256) in;
+
+#include "TunerParams.glsl"
+
+layout(set = 0, binding = 0) readonly buffer Tape { float tape[]; };
+// d(tau), from tuner_difference.comp, which does the bulk of the work.
+layout(set = 0, binding = 1) readonly buffer Difference { float difference[]; };
+// freq, clarity, level, period: layouts.Pitch.
+layout(set = 1, binding = 0) buffer Result { vec4 result; };
+
+// Match layouts.zig.
+const uint W = 2048;
+const uint LAGS = 1700;
+const uint THREADS = 256;
+
+// Each thread owns CHUNK consecutive lags.
+const uint CHUNK = (LAGS + THREADS - 1u) / THREADS;
+shared float d[THREADS * CHUNK];
+// d before normalising: the parabola goes through these, since the
+// normalisation's factor tau tilts a dip by more than a cent at high pitch.
+shared float raw[THREADS * CHUNK];
+shared float squares[THREADS];
+shared float sums[THREADS];
+shared uint first_dip;
+shared float deepest[THREADS];
+shared uint deepest_at[THREADS];
+
+void main() {
+ uint t = gl_LocalInvocationID.x;
+ uint tau_max = min(LAGS - 2u, uint(ceil(u.rate / u.min_freq)));
+ uint tau_min = max(2u, uint(floor(u.rate / u.max_freq)));
+
+ // 1. The difference function (tuner_difference.comp), and the window's
+ // energy.
+ int first = int(u.end) - int(W);
+ float sq = 0.0;
+ for (uint j = t; j < W; j += THREADS) {
+ int at = first + int(j);
+ float v = at >= 0 && at < int(u.samples) ? tape[u.offset + uint(at)] : 0.0;
+ sq += v * v;
+ }
+ squares[t] = sq;
+ float own = 0.0;
+ for (uint i = 0u; i < CHUNK; i++) {
+ uint tau = t * CHUNK + i;
+ float v = tau >= 1u && tau <= tau_max + 1u ? difference[tau] : 0.0;
+ raw[tau] = v;
+ own += v;
+ }
+ sums[t] = own;
+ if (t == 0u) first_dip = 0xffffffffu;
+ barrier();
+
+ // 2. Normalised by the running sum: a scan of the threads' chunk sums
+ // (Hillis-Steele), then each chunk in order.
+ for (uint stride = 1u; stride < THREADS; stride <<= 1u) {
+ float add = t >= stride ? sums[t - stride] : 0.0;
+ barrier();
+ sums[t] += add;
+ barrier();
+ }
+ float running = t > 0u ? sums[t - 1u] : 0.0;
+ float low = 2.0;
+ uint low_at = 0u;
+ for (uint i = 0u; i < CHUNK; i++) {
+ uint tau = t * CHUNK + i;
+ running += raw[tau];
+ float v = tau == 0u ? 1.0 : (running > 0.0 ? raw[tau] * float(tau) / running : 1.0);
+ d[tau] = v;
+ if (tau >= tau_min && tau <= tau_max) {
+ // 3. The first dip under the threshold, and the deepest.
+ if (v < u.threshold) atomicMin(first_dip, tau);
+ if (v < low) {
+ low = v;
+ low_at = tau;
+ }
+ }
+ }
+ deepest[t] = low;
+ deepest_at[t] = low_at;
+ barrier();
+ for (uint stride = THREADS / 2u; stride > 0u; stride >>= 1u) {
+ if (t < stride && deepest[t + stride] < deepest[t]) {
+ deepest[t] = deepest[t + stride];
+ deepest_at[t] = deepest_at[t + stride];
+ }
+ barrier();
+ }
+ if (t != 0u) return;
+
+ float energy = 0.0;
+ for (uint i = 0u; i < THREADS; i++) energy += squares[i];
+ float level = energy > 0.0 ? 10.0 * log(energy / float(W)) / log(10.0) : -160.0;
+
+ // The first dip followed to its bottom; failing one, the deepest, which
+ // the CPU may still reject as unclear.
+ uint best = first_dip;
+ if (best == 0xffffffffu) {
+ best = max(deepest_at[0], tau_min);
+ } else {
+ while (best + 1u <= tau_max && d[best + 1u] < d[best]) best++;
+ }
+
+ // 4. The parabola through the dip.
+ float a = raw[best - 1u];
+ float b = raw[best];
+ float c = raw[best + 1u];
+ float bend = a - 2.0 * b + c;
+ float shift = bend > 0.0 ? clamp(0.5 * (a - c) / bend, -0.5, 0.5) : 0.0;
+ float period = float(best) + shift;
+ float depth = d[best];
+ bool silent = energy <= 0.0;
+ result = vec4(silent ? 0.0 : u.rate / period, silent ? 0.0 : clamp(1.0 - depth, 0.0, 1.0), level, period);
+}
diff --git a/examples/micscope/shaders/tuner_difference.comp b/examples/micscope/shaders/tuner_difference.comp
new file mode 100644
index 0000000..c7d1b6e
--- /dev/null
+++ b/examples/micscope/shaders/tuner_difference.comp
@@ -0,0 +1,49 @@
+#version 450
+#extension GL_GOOGLE_include_directive : require
+// YIN's difference function for tuner.comp, spread over many workgroups:
+// d(tau) = sum over the newest W samples of (x[j] - x[j - tau])^2. Each
+// workgroup takes LAGS_PER_GROUP lags, with THREADS / LAGS_PER_GROUP
+// threads summing every so-many term of each, then adding up.
+layout(local_size_x = 256) in;
+
+#include "TunerParams.glsl"
+
+layout(set = 0, binding = 0) readonly buffer Tape { float tape[]; };
+layout(set = 1, binding = 0) buffer Difference { float d[]; };
+
+// Match layouts.zig and tuner.comp.
+const uint W = 2048;
+const uint LAGS = 1700;
+const uint THREADS = 256;
+const uint LAGS_PER_GROUP = 16;
+const uint PER_LAG = THREADS / LAGS_PER_GROUP;
+
+shared float x[W + LAGS];
+shared float partial[THREADS];
+
+void main() {
+ uint t = gl_LocalInvocationID.x;
+ int first = int(u.end) - int(W + LAGS);
+ for (uint i = t; i < W + LAGS; i += THREADS) {
+ int at = first + int(i);
+ x[i] = at >= 0 && at < int(u.samples) ? tape[u.offset + uint(at)] : 0.0;
+ }
+ barrier();
+
+ uint tau = gl_WorkGroupID.x * LAGS_PER_GROUP + t / PER_LAG;
+ uint lane = t % PER_LAG;
+ float sum = 0.0;
+ if (tau < LAGS) {
+ for (uint j = lane; j < W; j += PER_LAG) {
+ float diff = x[LAGS + j] - x[LAGS + j - tau];
+ sum += diff * diff;
+ }
+ }
+ partial[t] = sum;
+ barrier();
+ for (uint stride = PER_LAG / 2u; stride > 0u; stride >>= 1u) {
+ if (lane < stride) partial[t] += partial[t + stride];
+ barrier();
+ }
+ if (lane == 0u && tau < LAGS) d[tau] = partial[t];
+}
diff --git a/examples/micscope/src/layouts.zig b/examples/micscope/src/layouts.zig
new file mode 100644
index 0000000..be95799
--- /dev/null
+++ b/examples/micscope/src/layouts.zig
@@ -0,0 +1,37 @@
+//! What the tuner's shaders read, as Zig structs: the only definition. The
+//! shaders include GLSL generated from these (see sketchbook's `glsl.zig`).
+//! No imports, so the shader build can compile this alone. The views' own
+//! blocks are the scope module's (`scope.layouts`).
+
+/// tuner.comp: the YIN window is the `tuner_window + tuner_lags` samples
+/// ending at `end`, read like the other analyses (`offset`, `samples`).
+pub const tuner_window = 2048;
+pub const tuner_lags = 1700;
+
+pub const TunerParams = extern struct {
+ offset: u32,
+ end: u32,
+ samples: u32,
+ rate: f32,
+ /// The pitch range searched.
+ min_freq: f32,
+ max_freq: f32,
+ /// YIN's absolute threshold on the normalised difference.
+ threshold: f32,
+ pad: u32 = 0,
+
+ pub const glsl = .{ .uniform = .{ .set = 2, .instance = "u" } };
+};
+
+/// What tuner.comp writes (std430, read back by the CPU).
+pub const Pitch = extern struct {
+ /// Hz; 0 when nothing periodic was found.
+ freq: f32,
+ /// 1 minus YIN's normalised difference at the period: 1 is perfectly
+ /// periodic.
+ clarity: f32,
+ /// RMS of the window, dBFS.
+ level: f32,
+ /// The period in samples, interpolated.
+ period: f32,
+};
diff --git a/examples/micscope/src/main.zig b/examples/micscope/src/main.zig
new file mode 100644
index 0000000..99aac76
--- /dev/null
+++ b/examples/micscope/src/main.zig
@@ -0,0 +1,1299 @@
+//! micscope: records the microphone or opens sound files, plays them
+//! forwards or backwards, and shows each as a waveform, its spectrogram on
+//! the same time axis, and the spectrum at its playhead. The window is a
+//! vertical strip: on top, what the microphone hears right now (or the take
+//! being recorded); under it every take, newest first. The signal
+//! processing (windowed FFTs, log-frequency interpolation, smoothing,
+//! waveform reduction) and all the drawing run on the GPU; the CPU only
+//! moves samples: microphone to tape, tape to the GPU once, tape to the
+//! speakers.
+//!
+//! Memory by lifetime: State is the transport, the selection and the views,
+//! the takes (their ids and names), changed by `update` from keys and the
+//! mouse, and replayable. A take's samples are a file of its own, written
+//! by `draw` as it records and by `open` (see `Host.appendFile`): they are
+//! still there after a restart. Session is this process's copy of the
+//! takes' samples, the playback cursor, the microphone's recent past and
+//! GPU objects. Transport changes and seeks are `sk.Request`s, which `draw`
+//! carries out once each.
+const std = @import("std");
+const sk = @import("sketch");
+const gpu = sk.abi.gpu;
+const scope = @import("scope");
+const layouts = scope.layouts;
+/// The tuner's blocks; its shaders are `shaders`.
+const tuner_layouts = @import("layouts");
+const shaders = @import("shaders");
+const tuner = @import("tuner.zig");
+
+pub const name = "micscope";
+pub const width = 1280;
+pub const height = 900;
+pub const commands = .{ "open", "next-id" };
+
+/// The longest take: ten minutes at the host's rate.
+const max_seconds = 600;
+const max_takes = 64;
+/// The playback stream's key.
+const stream = 1;
+/// How far ahead playback keeps the stream filled.
+const lead_seconds = 0.06;
+/// The live view's span.
+const live_seconds = 6;
+
+pub const Transport = enum { stopped, recording, forward, backward };
+
+/// The part of a take its timeline shows, as fractions of it.
+pub const View = struct {
+ lo: f32 = 0,
+ hi: f32 = 1,
+};
+
+pub const State = struct {
+ transport: sk.Request(Transport) = .{},
+ /// The direction space resumes in.
+ backward: bool = false,
+ /// To a fraction of the selected take.
+ seek: sk.Request(f32) = .{},
+ scrubbing: bool = false,
+ dialog: sk.Request(void) = .{},
+ /// Oldest first.
+ takes: sk.List(Take, max_takes) = .{},
+ /// The next take's id. `draw` moves it past take files already there
+ /// with the `next-id` command: other runs' (`--fresh` keeps the files),
+ /// or the future a seek went back from.
+ next_id: u32 = 1,
+ /// The take the transport and the keys work on, by index (oldest 0).
+ selected: u32 = 0,
+ views: [max_takes]View = @splat(.{}),
+ /// Maps the world (the panels, stacked) to the screen.
+ camera: sk.Camera = .{},
+ /// The camera keeps the bottom, where now is, in view.
+ follow: bool = true,
+ panning: bool = false,
+ /// The pointer's height when panning last moved.
+ grab: f32 = 0,
+ gain: f32 = 1,
+ /// The tuner's reference pitch: A4, in Hz.
+ a4: f32 = 440,
+};
+
+pub const Take = struct {
+ /// Names its file, `take-<id>.f32`: its mono samples at
+ /// `Input.sample_rate`. Stays the same when earlier takes are deleted:
+ /// Session and the GPU caches go by it.
+ id: u32 = 0,
+ /// A file's name, or empty for the microphone.
+ source: [64]u8 = @splat(0),
+ source_len: u32 = 0,
+};
+
+/// A take's samples in `Session.tape`.
+const Clip = struct {
+ id: u32 = 0,
+ start: usize = 0,
+ len: usize = 0,
+ /// Where the listener is, in samples into the take.
+ heard: f64 = 0,
+};
+
+pub const Session = struct {
+ transport: sk.Handled = .{},
+ seek: sk.Handled = .{},
+ dialog: sk.Handled = .{},
+ /// State's takes' samples, read from their files once a process, one
+ /// after another in the order read. A recording grows the last one.
+ tape: std.ArrayList(f32) = .empty,
+ clips: sk.List(Clip, max_takes) = .{},
+ /// The take playback follows, by id, and the next of its samples to
+ /// queue.
+ playing: u32 = 0,
+ cursor: usize = 0,
+ /// The microphone's recent past and the live view.
+ live: scope.Scope = .{},
+ /// Pitch, by tuner.comp: of the microphone (live, or recording), and
+ /// of the selected take at its playhead.
+ tuners: [2]tuner.Tracker = @splat(.{}),
+ /// The take `tuners[1]` follows, by id.
+ tuned: u32 = 0,
+ gpu: Gpu = .{},
+};
+
+/// Which tracker a readback belongs to: its index, as the download key.
+const Tuned = enum(u32) { input, take };
+
+/// GPU objects, made on first use.
+const Gpu = struct {
+ ready: bool = false,
+ /// `Session.tape`, and how many of its samples are in it.
+ tape: sk.Buffer = .none,
+ capacity: usize = 0,
+ uploaded: usize = 0,
+ /// spectrum.comp's FFT, shared by every panel.
+ scratch: sk.Buffer = .none,
+ /// tuner.comp's results, a `tuner_layouts.Pitch` each, by `Tuned`, and
+ /// the difference functions it searches.
+ pitches: [2]sk.Buffer = @splat(.none),
+ differences: [2]sk.Buffer = @splat(.none),
+ /// For the takes on screen, by take id; the least recently used is
+ /// reused.
+ panels: [16]Panel = @splat(.{}),
+};
+
+/// One panel's buffers and images, and the inputs they were last made from:
+/// unchanged, they are not made again.
+const Panel = struct {
+ id: u32 = 0,
+ used: u64 = 0,
+ wave_columns: sk.Buffer = .none,
+ spectrum_columns: sk.Buffer = .none,
+ levels: sk.Buffer = .none,
+ wave: sk.Image = .none,
+ wave_size: [2]u32 = .{ 0, 0 },
+ spectrogram: sk.Image = .none,
+ spectrogram_size: [2]u32 = .{ 0, 0 },
+ spectrum: sk.Image = .none,
+ spectrum_size: [2]u32 = .{ 0, 0 },
+ wave_key: u64 = 0,
+ spectrogram_key: u64 = 0,
+ spectrum_key: u64 = 0,
+ wave_drawn: u64 = 0,
+ spectrogram_drawn: u64 = 0,
+
+ fn forget(p: *Panel) void {
+ p.wave_key = 0;
+ p.spectrogram_key = 0;
+ p.spectrum_key = 0;
+ p.wave_drawn = 0;
+ p.spectrogram_drawn = 0;
+ }
+};
+
+// ---------------------------------------------------------------------------
+// The world: panels stacked down in the order they were made, take 0 on top
+// and the live microphone at the bottom, where now is. A take keeps its
+// place as others are added. The camera maps the world to the screen: it
+// follows the bottom unless moved, and zooms out to overview the strip.
+// Panels are rendered at world resolution and scaled by the camera, so
+// moving it never recomputes anything.
+
+const spectrogram_height = 132;
+const min_zoom = 0.3;
+/// The canvas follows the window, but no smaller than this.
+const min_width = 320;
+const min_height = 300;
+
+/// Sizes, from the canvas. Wide, a panel is a waveform over its spectrogram
+/// with the spectrum beside them, and the buttons sit in the header. Narrow
+/// (a phone), the spectrum goes under them, full width, and the buttons
+/// along the bottom, where thumbs are, big enough to hit.
+const Layout = struct {
+ w: f32,
+ h: f32,
+ narrow: bool,
+ /// World units are canvas pixels at zoom 1.
+ world_width: f32,
+ panel_height: f32,
+ /// Where the world shows, between the header and the footer or buttons.
+ view: sk.Rect,
+
+ const header = 36;
+ const footer = 22;
+ const toolbar = 56;
+ const spectrum_width = 320;
+
+ fn of(w: f32, h: f32) Layout {
+ const narrow = w < 760;
+ const margin: f32 = if (narrow) 8 else 16;
+ const bottom: f32 = if (narrow) toolbar else footer;
+ return .{
+ .w = w,
+ .h = h,
+ .narrow = narrow,
+ .world_width = w - 2 * margin,
+ .panel_height = if (narrow) 412 else 236,
+ .view = .{ .x = 0, .y = header, .w = w, .h = h - header - bottom },
+ };
+ }
+
+ /// The panel in world slot `k`.
+ fn box(l: Layout, k: u32) Box {
+ const y = @as(f32, @floatFromInt(k)) * l.panel_height;
+ const timeline_w = if (l.narrow) l.world_width else l.world_width - spectrum_width - 16;
+ const wave: sk.Rect = .{ .x = 0, .y = y + 18, .w = timeline_w, .h = 64 };
+ const spectrogram: sk.Rect = .{ .x = 0, .y = wave.y + wave.h + 2, .w = timeline_w, .h = spectrogram_height };
+ const timeline: sk.Rect = .{ .x = 0, .y = wave.y, .w = timeline_w, .h = spectrogram.y + spectrogram.h - wave.y };
+ // Under the timeline and its time labels, or beside it; room for
+ // the frequency labels under it either way.
+ const levels: sk.Rect = if (l.narrow)
+ .{ .x = 0, .y = spectrogram.y + spectrogram.h + 22, .w = l.world_width, .h = 150 }
+ else
+ .{ .x = l.world_width - spectrum_width, .y = wave.y, .w = spectrum_width, .h = timeline.h - 14 };
+ return .{
+ .whole = .{ .x = 0, .y = y, .w = l.world_width, .h = l.panel_height },
+ .wave = wave,
+ .spectrogram = spectrogram,
+ .timeline = timeline,
+ .spectrum = levels,
+ };
+ }
+
+ /// Button `i` of `buttons`: right to left in the header, or left to
+ /// right across the bottom.
+ fn button(l: Layout, i: usize) sk.Rect {
+ const n: f32 = @floatFromInt(buttons.len);
+ const at: f32 = @floatFromInt(i);
+ if (l.narrow) {
+ const w = (l.w - 8 - (n - 1) * 4) / n;
+ return .{ .x = 4 + (n - 1 - at) * (w + 4), .y = l.h - toolbar + 6, .w = w, .h = toolbar - 10 };
+ }
+ return .{ .x = l.w - 16 - (at + 1) * (button_width + 6) + 6, .y = 5, .w = button_width, .h = 26 };
+ }
+
+ fn buttonAt(l: Layout, x: f32, y: f32) ?Action {
+ for (buttons, 0..) |a, i| if (l.button(i).contains(x, y)) return a;
+ return null;
+ }
+};
+
+const Box = struct {
+ whole: sk.Rect,
+ wave: sk.Rect,
+ spectrogram: sk.Rect,
+ /// Waveform and spectrogram: one time axis, where clicks seek and
+ /// ctrl+wheel (or a pinch) zooms.
+ timeline: sk.Rect,
+ spectrum: sk.Rect,
+
+ fn toScreen(b: Box, cam: sk.Camera) Box {
+ return .{
+ .whole = cam.toScreen(b.whole),
+ .wave = cam.toScreen(b.wave),
+ .spectrogram = cam.toScreen(b.spectrogram),
+ .timeline = cam.toScreen(b.timeline),
+ .spectrum = cam.toScreen(b.spectrum),
+ };
+ }
+};
+
+const World = struct {
+ /// Slots `0..takes` are takes; slot `takes` is the live view, unless a
+ /// recording (the last take) stands in for it.
+ takes: u32,
+ live: bool,
+
+ fn of(s: *const State) World {
+ return .{ .takes = s.takes.count(), .live = s.transport.value != .recording };
+ }
+ fn slots(w: World) u32 {
+ return w.takes + @intFromBool(w.live);
+ }
+ fn height(w: World, l: Layout) f32 {
+ return @as(f32, @floatFromInt(w.slots())) * l.panel_height;
+ }
+ /// The take at world point `p`.
+ fn takeAt(w: World, l: Layout, p: sk.shape.Point) ?u32 {
+ if (p.y < 0 or p.x < 0 or p.x > l.world_width) return null;
+ const k: u32 = @intFromFloat(@floor(p.y / l.panel_height));
+ return if (k < w.takes) k else null;
+ }
+};
+
+/// The camera's vertical range: from the world's top at the viewport's top
+/// to its bottom at the viewport's bottom.
+fn cameraRange(world: World, scale: f32, l: Layout) [2]f32 {
+ const highest = l.view.y + 4;
+ const lowest = l.view.y + l.view.h - 4 - world.height(l) * scale;
+ return .{ @min(lowest, highest), highest };
+}
+
+/// The camera as drawn: centred across, inside the world, and on the
+/// bottom while following.
+fn cameraOf(s: *const State, l: Layout) sk.Camera {
+ var cam = s.camera;
+ cam.zoom = std.math.clamp(cam.zoom, min_zoom, 1);
+ cam.x = @round((l.w - l.world_width * cam.zoom) / 2);
+ const range = cameraRange(World.of(s), cam.zoom, l);
+ cam.y = @round(if (s.follow) range[0] else std.math.clamp(cam.y, range[0], range[1]));
+ return cam;
+}
+
+/// Moves the camera, which follows again once it reaches the bottom.
+fn moveCamera(s: *State, cam: sk.Camera, in: *const sk.Input) void {
+ const l = Layout.of(in.width, in.height);
+ s.camera = cam;
+ s.follow = false;
+ s.camera = cameraOf(s, l);
+ const range = cameraRange(World.of(s), s.camera.zoom, l);
+ s.follow = s.camera.y <= range[0] + 0.5;
+}
+
+// ---------------------------------------------------------------------------
+// Update: transport, selection, views and camera, from input alone.
+
+pub fn update(s: *State, in: *const sk.Input) void {
+ if (in.started) {
+ // Nothing resumes on its own after a restart; the takes are kept.
+ s.transport.value = .stopped;
+ s.scrubbing = false;
+ s.panning = false;
+ }
+ const recording = s.transport.value == .recording;
+ for (keys) |k| if (in.pressed(k[0])) act(s, k[1], in);
+ if (in.pressed(sk.Key.equals)) s.gain = @min(s.gain * 1.25, 64);
+ if (in.pressed(sk.Key.minus)) s.gain = @max(s.gain / 1.25, 0.25);
+ if (in.pressed(sk.Key.z) and s.selected < max_takes) s.views[s.selected] = .{};
+ if (!recording and s.takes.count() > 0) {
+ // Up the strip is older.
+ if (in.pressed(sk.Key.up)) select(s, s.selected -| 1, in);
+ if (in.pressed(sk.Key.down)) select(s, @min(s.selected + 1, s.takes.count() - 1), in);
+ }
+ const l = Layout.of(in.width, in.height);
+ const page = l.view.h - l.panel_height / 2;
+ if (in.pressed(sk.Key.page_down)) panBy(s, -page, in);
+ if (in.pressed(sk.Key.page_up)) panBy(s, page, in);
+
+ const view = l.view;
+ for (in.events) |e| {
+ const cam = cameraOf(s, l);
+ const world = World.of(s);
+ const p = cam.toWorld(sk.shape.Point{ .x = e.x, .y = e.y });
+ switch (e.kind) {
+ .mouse_down => if (e.code == 1 and l.buttonAt(e.x, e.y) != null) {
+ act(s, l.buttonAt(e.x, e.y).?, in);
+ } else if (e.code == 2 or e.code == 3) {
+ // Middle or right drag pans.
+ s.panning = true;
+ s.grab = e.y;
+ } else if (e.code == 1 and !recording and view.contains(e.x, e.y)) {
+ const index = world.takeAt(l, p) orelse continue;
+ select(s, index, in);
+ const b = l.box(index);
+ if (b.timeline.contains(p.x, p.y)) {
+ s.scrubbing = true;
+ seekTo(s, fractionAt(s.views[index], b.timeline, p.x));
+ }
+ },
+ .mouse_move => if (s.panning) {
+ panBy(s, e.y - s.grab, in);
+ s.grab = e.y;
+ } else if (s.scrubbing and s.selected < world.takes) {
+ seekTo(s, fractionAt(s.views[s.selected], l.box(s.selected).timeline, p.x));
+ },
+ .mouse_up, .cancel => {
+ s.scrubbing = false;
+ s.panning = false;
+ },
+ // Ctrl+wheel, or a pinch (which browsers and the web host send
+ // as ctrl+wheel), zooms what is under it: a take's time on its
+ // timeline, the view anywhere else.
+ .wheel => if (view.contains(e.x, e.y)) {
+ const ctrl = e.modifiers() & sk.Key.Mod.ctrl != 0;
+ const over = world.takeAt(l, p);
+ if (ctrl and over != null and l.box(over.?).timeline.contains(p.x, p.y)) {
+ const index = over.?;
+ zoom(&s.views[index], fractionAt(s.views[index], l.box(index).timeline, p.x), std.math.pow(f32, 0.8, e.wheel()));
+ } else if (ctrl) {
+ var moved = cam;
+ moved.zoomAt(sk.shape.Point{ .x = e.x, .y = e.y }, e.wheel(), .{ .min = min_zoom, .max = 1 });
+ moveCamera(s, moved, in);
+ } else panBy(s, e.wheel() * 60, in);
+ },
+ else => {},
+ }
+ }
+}
+
+/// What keys and the buttons on top do.
+const Action = enum { record, play, forward, backward, start, end, open, delete, overview, a4_down, a4_up };
+
+const keys = [_]struct { sk.Key, Action }{
+ .{ .r, .record }, .{ .space, .play }, .{ .right, .forward }, .{ .left, .backward },
+ .{ .home, .start }, .{ .end, .end }, .{ .o, .open }, .{ .delete, .delete },
+ .{ .backspace, .delete }, .{ .@"0", .overview }, .{ .left_bracket, .a4_down }, .{ .right_bracket, .a4_up },
+};
+
+/// Everything a touch screen cannot reach by key, as buttons (see
+/// `Layout.button`). Labels change with what they would do.
+const buttons = [_]Action{ .a4_up, .a4_down, .overview, .delete, .open, .backward, .play, .record };
+const button_width = 52;
+
+fn act(s: *State, a: Action, in: *const sk.Input) void {
+ const now = s.transport.value;
+ switch (a) {
+ .record => if (now == .recording) change(s, .stopped) else record(s),
+ .play => change(s, switch (now) {
+ .forward, .backward => .stopped,
+ .stopped, .recording => if (s.backward) .backward else .forward,
+ }),
+ .forward => change(s, .forward),
+ .backward => change(s, .backward),
+ .start => seekTo(s, 0),
+ .end => seekTo(s, 1),
+ .open => s.dialog.send({}),
+ .delete => if (now != .recording and s.takes.count() > 0) remove(s, in),
+ .overview => {
+ // The whole strip, or back to full size.
+ const l = Layout.of(in.width, in.height);
+ var cam = cameraOf(s, l);
+ cam.zoom = if (cam.zoom < 1) 1 else l.view.h / @max(World.of(s).height(l), 1);
+ moveCamera(s, cam, in);
+ s.follow = true;
+ },
+ .a4_down => s.a4 = @max(s.a4 - 1, 400),
+ .a4_up => s.a4 = @min(s.a4 + 1, 480),
+ }
+}
+
+/// Starts a new take, unless the strip is full. It takes the live view's
+/// place, which the camera follows.
+fn record(s: *State) void {
+ s.takes.appendBounded(.{ .id = s.next_id }) catch return;
+ s.next_id += 1;
+ s.selected = s.takes.count() - 1;
+ s.views[s.selected] = .{};
+ s.follow = true;
+ change(s, .recording);
+}
+
+fn change(s: *State, to: Transport) void {
+ if (to == .forward or to == .backward) s.backward = to == .backward;
+ s.transport.send(to);
+}
+
+fn seekTo(s: *State, fraction: f32) void {
+ if (s.transport.value == .recording) return;
+ s.seek.send(std.math.clamp(fraction, 0, 1));
+}
+
+/// Selects a take and brings it into view.
+fn select(s: *State, index: u32, in: *const sk.Input) void {
+ s.selected = index;
+ const l = Layout.of(in.width, in.height);
+ var cam = cameraOf(s, l);
+ const b = cam.toScreen(l.box(index).whole);
+ const view = l.view;
+ if (b.y < view.y) cam.y += view.y - b.y + 4;
+ if (b.y + b.h > view.y + view.h) cam.y -= b.y + b.h - (view.y + view.h) + 4;
+ moveCamera(s, cam, in);
+}
+
+/// Moves the world down by `pixels` on screen.
+fn panBy(s: *State, pixels: f32, in: *const sk.Input) void {
+ var cam = cameraOf(s, Layout.of(in.width, in.height));
+ cam.y += pixels;
+ moveCamera(s, cam, in);
+}
+
+/// Deletes the selected take and selects the one above it. Its file stays:
+/// any keyframe or mark from before the delete brings the take back, and
+/// neither the sketch nor the host can tell when none is left.
+fn remove(s: *State, in: *const sk.Input) void {
+ const n = s.takes.count();
+ const index = @min(s.selected, n - 1);
+ _ = s.takes.orderedRemove(index);
+ std.mem.copyForwards(View, s.views[index .. n - 1], s.views[index + 1 .. n]);
+ s.selected = index -| 1;
+ moveCamera(s, cameraOf(s, Layout.of(in.width, in.height)), in);
+}
+
+fn fractionAt(v: View, timeline: sk.Rect, x: f32) f32 {
+ return v.lo + (x - timeline.x) / timeline.w * (v.hi - v.lo);
+}
+
+/// Scales the view by `factor` around `at`, keeping it inside the take.
+fn zoom(v: *View, at: f32, factor: f32) void {
+ const span = std.math.clamp((v.hi - v.lo) * factor, 1e-6, 1);
+ var lo = at - (at - v.lo) / (v.hi - v.lo) * span;
+ lo = std.math.clamp(lo, 0, 1 - span);
+ v.lo = lo;
+ v.hi = lo + span;
+}
+
+/// `open PATH` adds a file as a take, writing its samples to the take's
+/// file; `open` alone shows the dialog. `next-id N` moves the counter
+/// (`draw` sends it).
+pub fn command(s: *State, ss: *Session, c: *sk.Console, line: []const u8) !bool {
+ var words = std.mem.tokenizeAny(u8, line, " \t");
+ const verb = words.next() orelse return false;
+ if (std.mem.eql(u8, verb, "next-id")) {
+ s.next_id = try std.fmt.parseInt(u32, words.next() orelse return error.ExpectedId, 10);
+ return true;
+ }
+ if (!std.mem.eql(u8, verb, "open")) return false;
+ const path = std.mem.trim(u8, words.rest(), " \t");
+ if (path.len == 0) {
+ s.dialog.send({});
+ return true;
+ }
+ if (s.takes.count() >= max_takes) return error.TooManyTakes;
+ const samples = c.host.samples(c.host.loadSound(path));
+ if (samples.len == 0) return error.CannotOpen;
+ // Recording grows the last take: stop before this one goes after it.
+ if (s.transport.value == .recording) change(s, .stopped);
+ const kept = samples[0..@min(samples.len, max_seconds * c.in.sample_rate)];
+ var take: Take = .{ .id = s.next_id };
+ const base = std.fs.path.basename(path);
+ take.source_len = @intCast(@min(base.len, take.source.len));
+ @memcpy(take.source[0..take.source_len], base[0..take.source_len]);
+ // Into Session now, so the web, which keeps no files, has it too.
+ try ss.tape.appendSlice(c.session, kept);
+ try ss.clips.appendBounded(.{ .id = take.id, .start = ss.tape.items.len - kept.len, .len = kept.len });
+ var file: [32]u8 = undefined;
+ _ = c.host.writeFile(try std.fmt.bufPrint(&file, "take-{d}.f32", .{take.id}), std.mem.sliceAsBytes(kept));
+ try s.takes.appendBounded(take);
+ s.next_id += 1;
+ s.selected = s.takes.count() - 1;
+ s.views[s.selected] = .{};
+ s.follow = true;
+ change(s, .stopped);
+ c.print("opened {s}: {d:.1} s", .{ path, @as(f64, @floatFromInt(kept.len)) / @as(f64, @floatFromInt(c.in.sample_rate)) });
+ return true;
+}
+
+// ---------------------------------------------------------------------------
+// Draw: the takes, the microphone, the speakers and the GPU.
+
+pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void {
+ const in = f.in;
+ const rate: f64 = @floatFromInt(in.sample_rate);
+ const dt: f64 = @min(@as(f64, @floatFromInt(in.dt)) / std.time.ns_per_s, 0.1);
+ // As big as the window: the layout follows (see `Layout`).
+ f.canvas(@intFromFloat(@max(in.window_width, min_width)), @intFromFloat(@max(in.window_height, min_height)));
+ f.clear(0x0b0c0f);
+
+ if (ss.dialog.take(s.dialog) != null) f.openFile("open", .{ .pattern = "wav;flac;ogg" });
+ // Files are written live, never while a recording of the session plays
+ // back: like sound, a write is not replayed.
+ const writing = in.mode == .live or in.mode == .recording;
+ if (in.jumped and writing) {
+ // State came from elsewhere: the next id's file may hold samples.
+ var id = s.next_id;
+ while (f.host.readFile(f.host.appendFile(f.format("take-{d}.f32", .{id}), &.{})).len > 0) id += 1;
+ if (id != s.next_id) f.run(f.format("next-id {d}", .{id}));
+ }
+ // Requests from State. Any of them, or another take selected, flushes
+ // what is queued, so the cursor restarts from what was heard.
+ const transport = ss.transport.take(s.transport);
+ const seek = ss.seek.take(s.seek);
+ const takes = s.takes.constSlice();
+ // A take that begins here (not one a jump brought) starts its file
+ // empty, whatever a file of its id held.
+ if (transport == .recording and writing and !in.jumped and takes.len > 0) _ = f.host.writeFile(f.format("take-{d}.f32", .{takes[takes.len - 1].id}), &.{});
+ readTakes(s, ss, f);
+ const selected: ?*Clip = if (takes.len > 0) clipOf(ss, takes[@min(s.selected, takes.len - 1)].id) else null;
+ var queued: usize = in.stream(stream).queued;
+ if (selected) |t| {
+ if (transport != null or seek != null or t.id != ss.playing) {
+ f.audio(stream, &.{}, .{ .clear = true });
+ queued = 0;
+ ss.playing = t.id;
+ ss.cursor = @intFromFloat(std.math.clamp(@round(t.heard), 0, @as(f64, @floatFromInt(t.len))));
+ }
+ if (transport) |to| {
+ switch (to) {
+ .forward => if (ss.cursor >= t.len) {
+ ss.cursor = 0;
+ },
+ .backward => if (ss.cursor == 0) {
+ ss.cursor = t.len;
+ },
+ .stopped, .recording => {},
+ }
+ t.heard = @floatFromInt(ss.cursor);
+ }
+ if (seek) |fraction| if (s.transport.value != .recording) {
+ ss.cursor = @intFromFloat(@round(fraction * @as(f32, @floatFromInt(t.len))));
+ t.heard = @floatFromInt(ss.cursor);
+ };
+ }
+
+ // The microphone is always open: the live view shows it, and a
+ // recording keeps it.
+ f.microphone();
+ ss.live.push(in.microphone);
+ switch (s.transport.value) {
+ // Into the last take, at the tape's end.
+ .recording => if (takes.len > 0 and writing) if (clipOf(ss, takes[takes.len - 1].id)) |t| if (t.start + t.len == ss.tape.items.len) {
+ const room = max_seconds * in.sample_rate -| t.len;
+ const heard = in.microphone[0..@min(in.microphone.len, room)];
+ ss.tape.appendSlice(f.session, heard) catch f.host.log("out of memory: recording stopped");
+ _ = f.host.appendFile(f.format("take-{d}.f32", .{t.id}), std.mem.sliceAsBytes(heard));
+ t.len = ss.tape.items.len - t.start;
+ t.heard = @floatFromInt(t.len);
+ },
+ .forward, .backward => if (selected) |t| play(ss, t, ss.tape.items[t.start..][0..t.len], f, s.transport.value == .forward, queued, rate, dt),
+ .stopped => {},
+ }
+
+ // The tuner's readbacks, a frame or two old.
+ if (selected) |t| if (t.id != ss.tuned) {
+ ss.tuned = t.id;
+ ss.tuners[@intFromEnum(Tuned.take)] = .{};
+ };
+ for (in.downloads) |d| {
+ if (d.key >= ss.tuners.len or d.bytes.len < @sizeOf(tuner_layouts.Pitch)) continue;
+ ss.tuners[d.key].feed(std.mem.bytesToValue(tuner_layouts.Pitch, d.bytes[0..@sizeOf(tuner_layouts.Pitch)]), s.a4, @floatCast(dt));
+ }
+
+ if (!f.host.gpu()) {
+ f.text(16, Layout.header, 2, "micscope needs a GPU: the host has none.", 0xff8080);
+ return;
+ }
+ render(s, ss, f, rate, dt);
+}
+
+/// Session's tape follows State's takes: a take State no longer has leaves
+/// it, and one it lacks is read from its file (a new one's is empty).
+fn readTakes(s: *const State, ss: *Session, f: *sk.Frame) void {
+ var i: u32 = 0;
+ while (i < ss.clips.count()) {
+ const t = ss.clips.buffer[i];
+ if (for (s.takes.constSlice()) |take| {
+ if (take.id == t.id) break true;
+ } else false) {
+ i += 1;
+ continue;
+ }
+ _ = ss.clips.orderedRemove(i);
+ const tape = ss.tape.items;
+ std.mem.copyForwards(f32, tape[t.start .. tape.len - t.len], tape[t.start + t.len ..]);
+ ss.tape.shrinkRetainingCapacity(tape.len - t.len);
+ for (ss.clips.slice()[i..]) |*later| later.start -= t.len;
+ ss.gpu.uploaded = @min(ss.gpu.uploaded, t.start);
+ for (&ss.gpu.panels) |*p| if (p.id == t.id) {
+ p.id = 0;
+ p.forget();
+ };
+ }
+ for (s.takes.constSlice()) |take| if (clipOf(ss, take.id) == null) {
+ const bytes = f.host.readFile(f.host.appendFile(f.format("take-{d}.f32", .{take.id}), &.{}));
+ const samples = std.mem.bytesAsSlice(f32, @as([]align(4) const u8, @alignCast(bytes[0 .. bytes.len / 4 * 4])));
+ ss.tape.appendSlice(f.session, samples) catch return f.host.log("out of memory: takes not read");
+ ss.clips.appendBounded(.{ .id = take.id, .start = ss.tape.items.len - samples.len, .len = samples.len }) catch return;
+ };
+}
+
+fn clipOf(ss: *Session, id: u32) ?*Clip {
+ for (ss.clips.slice()) |*t| if (t.id == id) return t;
+ return null;
+}
+
+/// Keeps the stream `lead_seconds` ahead, reading the take either way, and
+/// follows the listener.
+fn play(ss: *Session, t: *Clip, tape: []const f32, f: *sk.Frame, forward: bool, queued: usize, rate: f64, dt: f64) void {
+ const lead: usize = @intFromFloat(rate * lead_seconds);
+ const want = lead -| queued;
+ // What is heard now: the cursor, less what is queued in front of it.
+ const measured: f64 = @floatFromInt(if (forward) ss.cursor -| queued else @min(ss.cursor + queued, tape.len));
+ if (forward) {
+ const n = @min(want, tape.len -| ss.cursor);
+ f.audio(stream, tape[@min(ss.cursor, tape.len)..][0..n], .{});
+ ss.cursor += n;
+ } else {
+ const n = @min(want, ss.cursor);
+ const reversed = f.scratch.alloc(f32, n) catch return;
+ for (reversed, 0..) |*sample, i| sample.* = tape[ss.cursor - 1 - i];
+ f.audio(stream, reversed, .{});
+ ss.cursor -= n;
+ }
+ // The queue drains in device-sized blocks: advance by the clock and
+ // pull gently towards the measurement, snapping when far off.
+ const direction: f64 = if (forward) 1 else -1;
+ t.heard += direction * dt * rate;
+ const off = measured - t.heard;
+ t.heard = if (@abs(off) > rate * 0.25) measured else t.heard + off * 0.15;
+ t.heard = std.math.clamp(t.heard, 0, @as(f64, @floatFromInt(tape.len)));
+}
+
+// ---------------------------------------------------------------------------
+// GPU: buffers, compute, passes.
+
+const tuner_difference_kernel: gpu.Kernel = .{
+ .code = shaders.tuner_difference_comp,
+ .readonly_buffers = 1,
+ .readwrite_buffers = 1,
+ .uniform_buffers = 1,
+ .threads = .{ 256, 1, 1 },
+};
+const tuner_kernel: gpu.Kernel = .{
+ .code = shaders.tuner_comp,
+ .readonly_buffers = 2,
+ .readwrite_buffers = 1,
+ .uniform_buffers = 1,
+ .threads = .{ 256, 1, 1 },
+};
+
+fn setup(g: *Gpu, f: *sk.Frame) void {
+ if (g.ready) return;
+ g.ready = true;
+ g.scratch = f.host.newBuffer(layouts.fft_size * 2 * @sizeOf([2]f32));
+ for (&g.pitches) |*b| b.* = f.host.newBuffer(@sizeOf(tuner_layouts.Pitch));
+ for (&g.differences) |*b| b.* = f.host.newBuffer(tuner_layouts.tuner_lags * @sizeOf(f32));
+}
+
+fn makeBuffers(p: *Panel, f: *sk.Frame) void {
+ if (p.wave_columns != .none) return;
+ p.wave_columns = f.host.newBuffer(layouts.max_columns * @sizeOf([4]f32));
+ p.spectrum_columns = f.host.newBuffer(layouts.max_columns * @sizeOf([2]f32));
+ p.levels = f.host.newBuffer(layouts.max_columns * spectrogram_height * @sizeOf(f32));
+}
+
+/// The panel for take `id`: the one it had, or the least recently used.
+fn panelFor(g: *Gpu, f: *sk.Frame, id: u32) *Panel {
+ const p = for (&g.panels) |*p| {
+ if (p.id == id) break p;
+ } else reuse: {
+ var oldest = &g.panels[0];
+ for (&g.panels) |*p| if (p.used < oldest.used) {
+ oldest = p;
+ };
+ oldest.id = id;
+ oldest.forget();
+ break :reuse oldest;
+ };
+ p.used = f.in.frame;
+ makeBuffers(p, f);
+ return p;
+}
+
+/// An image of `size`, (re)made when the size changes.
+fn target(f: *sk.Frame, image: *sk.Image, size: *[2]u32, r: sk.Rect) [2]u32 {
+ const want: [2]u32 = .{ @intFromFloat(@min(r.w, layouts.max_columns)), @intFromFloat(@min(r.h, spectrogram_height)) };
+ if (image.* == .none or size[0] != want[0] or size[1] != want[1]) {
+ if (image.* != .none) f.host.freeImage(image.*);
+ image.* = f.host.newImage(want[0], want[1]);
+ size.* = want;
+ }
+ return want;
+}
+
+/// Puts the tape on the GPU: new samples only, unless the buffer had to grow.
+fn sync(g: *Gpu, f: *sk.Frame, tape: []const f32) void {
+ if (tape.len > g.capacity or g.tape == .none) {
+ if (g.tape != .none) f.host.freeBuffer(g.tape);
+ g.capacity = @max(tape.len, g.capacity * 2, 60 * f.in.sample_rate);
+ g.tape = f.host.newBuffer(@intCast(g.capacity * @sizeOf(f32)));
+ g.uploaded = 0;
+ }
+ g.uploaded = @min(g.uploaded, tape.len);
+ if (g.uploaded < tape.len) {
+ f.upload(g.tape, @intCast(g.uploaded * @sizeOf(f32)), std.mem.sliceAsBytes(tape[g.uploaded..]));
+ g.uploaded = tape.len;
+ }
+}
+
+fn render(s: *const State, ss: *Session, f: *sk.Frame, rate: f64, dt: f64) void {
+ const g = &ss.gpu;
+ setup(g, f);
+ sync(g, f, ss.tape.items);
+ // New code may mean new shaders: make everything again (the live view
+ // sees to its own).
+ if (f.in.reloaded) for (&g.panels) |*p| p.forget();
+ const takes = s.takes.constSlice();
+ const selected = if (takes.len > 0) @min(s.selected, takes.len - 1) else 0;
+ const recording = s.transport.value == .recording;
+ const world: World = .of(s);
+ const l = Layout.of(f.in.width, f.in.height);
+ const cam = cameraOf(s, l);
+ const view = l.view;
+ // Images are made at world size; the camera only scales them.
+ const size = l.box(0);
+
+ f.clip(view);
+ // The live view, in the world's last slot. It keeps up even while it is
+ // hidden: drawn clipped away while a recording stands in for it.
+ const live = l.box(world.takes);
+ if (!world.live) f.clip(.{ .x = 0, .y = 0, .w = 0, .h = 0 });
+ ss.live.draw(f, .{ .seconds = live_seconds, .wave = live.wave, .spectrogram = live.spectrogram, .spectrum = live.spectrum, .gain = s.gain, .camera = cam });
+ f.clip(view);
+ // The tuner: on the microphone's newest sound, and on the selected take
+ // around its playhead.
+ const reach = tuner_layouts.tuner_window + tuner_layouts.tuner_lags;
+ const last = if (recording and takes.len > 0) clipOf(ss, takes[takes.len - 1].id) else null;
+ if (last) |t| {
+ tune(g, f, .input, g.tape, t.start, t.len, t.len, rate);
+ } else tune(g, f, .input, ss.live.gpu.tape, 0, scope.history, scope.history, rate);
+ if (!recording and takes.len > 0) if (clipOf(ss, takes[selected].id)) |t| {
+ const end: usize = @intFromFloat(@max(t.heard, 0));
+ tune(g, f, .take, g.tape, t.start, t.len, end + reach / 2, rate);
+ };
+ for (0..world.takes) |slot| {
+ const k: u32 = @intCast(slot);
+ const b = l.box(k).toScreen(cam);
+ if (b.whole.y + b.whole.h <= view.y or b.whole.y >= view.y + view.h) continue;
+ const tint: layouts.Tint = if (recording and k + 1 == world.takes) .recording else .take;
+ drawTake(s, g, f, size, b, clipOf(ss, takes[k].id) orelse continue, s.views[k], k == selected, tint, rate, dt);
+ }
+ f.clip(null);
+ labels(s, ss, f, world, cam, rate);
+}
+
+/// Finds the pitch of the `tuner_window` samples before `end` (of the
+/// `samples` from `offset`), and reads it back.
+fn tune(g: *Gpu, f: *sk.Frame, which: Tuned, tape: sk.Buffer, offset: usize, samples: usize, end: usize, rate: f64) void {
+ const result = g.pitches[@intFromEnum(which)];
+ const difference = g.differences[@intFromEnum(which)];
+ const params = gpu.uniform(f.scratch, tuner_layouts.TunerParams{
+ .offset = @intCast(offset),
+ .end = @intCast(end),
+ .samples = @intCast(samples),
+ .rate = @floatCast(rate),
+ .min_freq = tuner_low,
+ .max_freq = tuner_high,
+ .threshold = 0.12,
+ });
+ f.compute(.{
+ .label = "tuner_difference.comp",
+ .kernel = tuner_difference_kernel,
+ .readonly = &.{tape},
+ .readwrite = &.{difference},
+ .uniforms = params,
+ // Match tuner_difference.comp's LAGS_PER_GROUP.
+ .groups = .{ (tuner_layouts.tuner_lags + 15) / 16, 1, 1 },
+ });
+ f.compute(.{
+ .label = "tuner.comp",
+ .kernel = tuner_kernel,
+ .readonly = &.{ tape, difference },
+ .readwrite = &.{result},
+ .uniforms = params,
+ });
+ f.download(result, .{ .size = @sizeOf(tuner_layouts.Pitch), .key = @intFromEnum(which) });
+}
+
+/// The pitches the tuner looks for: a five-string bass's low B to a
+/// piccolo's top.
+const tuner_low = 30.0;
+const tuner_high = 4200.0;
+
+/// The spectrum's analysis of `tape`, then its pass.
+fn spectrum(g: *Gpu, f: *sk.Frame, tape: sk.Buffer, p: *Panel, size: [2]u32, params: layouts.SpectrumParams, rate: f64) void {
+ f.compute(.{
+ .label = "spectrum.comp",
+ .kernel = scope.kernels.spectrum,
+ .readonly = &.{tape},
+ .readwrite = &.{ g.scratch, p.spectrum_columns },
+ .uniforms = gpu.uniform(f.scratch, params),
+ });
+ f.gpu(.{
+ .label = "spectrum.frag",
+ .image = p.spectrum,
+ .width = size[0],
+ .height = size[1],
+ .clear = null,
+ .pipelines = &scope.pipelines.spectrum,
+ .draws = &.{.{
+ .pipeline = 0,
+ .vertex_count = 3,
+ .fragment_uniforms = gpu.uniform(f.scratch, layouts.SpectrumView{
+ .size = .{ @floatFromInt(size[0]), @floatFromInt(size[1]) },
+ .floor_db = scope.floor_db,
+ .ceil_db = 0,
+ .min_freq = scope.min_freq,
+ .max_freq = scope.maxFreq(rate),
+ }),
+ .fragment_storage = &.{p.spectrum_columns},
+ }},
+ });
+}
+
+fn drawTake(s: *const State, g: *Gpu, f: *sk.Frame, size: Box, b: Box, t: *const Clip, view: View, selected: bool, tint: layouts.Tint, rate: f64, dt: f64) void {
+ const p = panelFor(g, f, t.id);
+
+ // Waveform columns, when what they show changed.
+ const wave = target(f, &p.wave, &p.wave_size, size.wave);
+ const span = visible(view, t.len, wave[0]);
+ const first: u32 = @intFromFloat(@floor(span[0]));
+ const spp: f32 = @floatCast((span[1] - span[0]) / @as(f64, @floatFromInt(wave[0])));
+ const params: layouts.WaveParams = .{
+ .offset = @intCast(t.start),
+ .first = first,
+ .samples = @intCast(t.len),
+ .columns = wave[0],
+ .spp = spp,
+ .slot = 0,
+ .ring = layouts.max_columns,
+ };
+ const key = std.hash.Wyhash.hash(0, std.mem.asBytes(&params));
+ if (key != p.wave_key) {
+ p.wave_key = key;
+ f.compute(.{
+ .label = "waveform.comp",
+ .kernel = scope.kernels.waveform,
+ .readonly = &.{g.tape},
+ .readwrite = &.{p.wave_columns},
+ .uniforms = gpu.uniform(f.scratch, params),
+ .groups = .{ wave[0], 1, 1 },
+ });
+ }
+
+ // The spectrogram over the same columns.
+ const spectrogram = target(f, &p.spectrogram, &p.spectrogram_size, size.spectrogram);
+ const analysis: layouts.SpectrogramParams = .{
+ .offset = @intCast(t.start),
+ .first = first,
+ .samples = @intCast(t.len),
+ .columns = spectrogram[0],
+ .rows = spectrogram[1],
+ .spp = spp,
+ .rate = @floatCast(rate),
+ .min_freq = scope.min_freq,
+ .max_freq = scope.maxFreq(rate),
+ .slot = 0,
+ .ring = layouts.max_columns,
+ };
+ const analysis_key = std.hash.Wyhash.hash(0, std.mem.asBytes(&analysis));
+ if (analysis_key != p.spectrogram_key) {
+ p.spectrogram_key = analysis_key;
+ f.compute(.{
+ .label = "spectrogram.comp",
+ .kernel = scope.kernels.spectrogram,
+ .readonly = &.{g.tape},
+ .readwrite = &.{p.levels},
+ .uniforms = gpu.uniform(f.scratch, analysis),
+ .groups = .{ spectrogram[0], 1, 1 },
+ });
+ }
+
+ // The spectrum around the playhead, or of the latest while recording:
+ // every frame for the selected take, which plays and glides; the others
+ // only when it would change, and without smoothing.
+ const half: f64 = layouts.window / 2;
+ const len: f64 = @floatFromInt(t.len);
+ const end: f64 = if (tint == .recording) len else @min(t.heard + half, len + half);
+ const shown = target(f, &p.spectrum, &p.spectrum_size, size.spectrum);
+ var sparams: layouts.SpectrumParams = .{
+ .offset = @intCast(t.start),
+ .end = @intFromFloat(@max(end, 0)),
+ .samples = @intCast(t.len),
+ .columns = shown[0],
+ .reset = 0,
+ .rate = @floatCast(rate),
+ .min_freq = scope.min_freq,
+ .max_freq = scope.maxFreq(rate),
+ .dt = 0,
+ };
+ const spectrum_key = std.hash.Wyhash.hash(1, std.mem.asBytes(&sparams));
+ if (selected or spectrum_key != p.spectrum_key) {
+ sparams.reset = @intFromBool(!selected or p.spectrum_key == 0);
+ sparams.dt = @floatCast(dt);
+ p.spectrum_key = spectrum_key;
+ spectrum(g, f, g.tape, p, shown, sparams, rate);
+ }
+
+ const at: f32 = @floatCast((t.heard - span[0]) / (span[1] - span[0]) * @as(f64, @floatFromInt(wave[0])));
+ const playhead: f32 = if (!selected or t.len == 0 or at < 0 or at > @as(f32, @floatFromInt(wave[0]))) -1 else at;
+ const wave_view: layouts.WaveView = .{
+ .size = .{ @floatFromInt(wave[0]), @floatFromInt(wave[1]) },
+ .playhead = playhead,
+ .gain = s.gain,
+ .tint = @intFromEnum(tint),
+ .scroll = 0,
+ .filled = wave[0],
+ };
+ const wave_drawn = std.hash.Wyhash.hash(p.wave_key, std.mem.asBytes(&wave_view));
+ if (wave_drawn != p.wave_drawn) {
+ p.wave_drawn = wave_drawn;
+ f.gpu(.{
+ .label = "waveform.frag",
+ .image = p.wave,
+ .width = wave[0],
+ .height = wave[1],
+ .clear = null,
+ .pipelines = &scope.pipelines.wave,
+ .draws = &.{.{ .pipeline = 0, .vertex_count = 3, .fragment_uniforms = gpu.uniform(f.scratch, wave_view), .fragment_storage = &.{p.wave_columns} }},
+ });
+ }
+ const spectrogram_view: layouts.SpectrogramView = .{
+ .size = .{ @floatFromInt(spectrogram[0]), @floatFromInt(spectrogram[1]) },
+ .floor_db = scope.floor_db,
+ .ceil_db = -6,
+ .playhead = playhead,
+ .scroll = 0,
+ .filled = spectrogram[0],
+ };
+ const spectrogram_drawn = std.hash.Wyhash.hash(p.spectrogram_key, std.mem.asBytes(&spectrogram_view));
+ if (spectrogram_drawn != p.spectrogram_drawn) {
+ p.spectrogram_drawn = spectrogram_drawn;
+ f.gpu(.{
+ .label = "spectrogram.frag",
+ .image = p.spectrogram,
+ .width = spectrogram[0],
+ .height = spectrogram[1],
+ .clear = null,
+ .pipelines = &scope.pipelines.spectrogram,
+ .draws = &.{.{ .pipeline = 0, .vertex_count = 3, .fragment_uniforms = gpu.uniform(f.scratch, spectrogram_view), .fragment_storage = &.{p.levels} }},
+ });
+ }
+ f.image(p.wave, b.wave, .{});
+ f.image(p.spectrogram, b.spectrogram, .{});
+ f.image(p.spectrum, b.spectrum, .{});
+}
+
+/// The samples a take's timeline spans, at least 1/32 of a sample per
+/// column.
+fn visible(v: View, len: usize, columns: u32) [2]f64 {
+ const total: f64 = @floatFromInt(len);
+ var lo = v.lo * total;
+ var hi = v.hi * total;
+ const least = @as(f64, @floatFromInt(columns)) / 32;
+ if (hi - lo < least) {
+ const mid = (lo + hi) / 2;
+ lo = @max(mid - least / 2, 0);
+ hi = lo + least;
+ }
+ return .{ lo, hi };
+}
+
+// ---------------------------------------------------------------------------
+// Text.
+
+const dim = 0x7a8090;
+const bright = 0xe6e9ef;
+const red = 0xff5a5a;
+const green = 0x6fdc8c;
+const yellow = 0xffd84d;
+
+fn labels(s: *const State, ss: *Session, f: *sk.Frame, world: World, cam: sk.Camera, rate: f64) void {
+ const takes = s.takes.constSlice();
+ const recording = s.transport.value == .recording;
+ const selected = if (takes.len > 0) @min(s.selected, takes.len - 1) else 0;
+
+ // What the transport is doing, to which take.
+ const status: struct { []const u8, u24 } = switch (s.transport.value) {
+ .recording => .{ "REC", red },
+ .forward => .{ "PLAY >", 0x7fd7ff },
+ .backward => .{ "PLAY <", 0x7fd7ff },
+ .stopped => .{ "PAUSED", dim },
+ };
+ const l = Layout.of(f.in.width, f.in.height);
+ f.text(16, 10, 2, status[0], status[1]);
+ if (if (takes.len > 0) clipOf(ss, takes[selected].id) else null) |t| {
+ const times = .{ Time{ .seconds = t.heard / rate }, Time{ .seconds = @as(f64, @floatFromInt(t.len)) / rate } };
+ // As much as fits beside the buttons (or, narrow, the corner).
+ const room = if (l.narrow) l.w - 16 * 7 else l.button(buttons.len - 1).x - 16;
+ if (room >= 480) {
+ f.print(140, 10, 2, bright, "{f} / {f}", times);
+ if (room >= 740) f.print(500, 14, 1, dim, "take {d} of {d}: {s}", .{ selected + 1, takes.len, source(&takes[selected]) });
+ } else f.print(16 + 16 * 7, 14, 1, bright, "{f} / {f}", times);
+ }
+ for (buttons, 0..) |a, i| button(s, f, a, l.button(i));
+ const corner = f.format("{s}{s}", .{
+ if (s.gain != 1) f.format("gain x{d:.2} ", .{s.gain}) else "",
+ if (cam.zoom < 1) f.format("view x{d:.2}", .{cam.zoom}) else "",
+ });
+ f.text(f.in.width - 16 - @as(f32, @floatFromInt(corner.len * 8)), if (l.narrow) 14 else f.in.height - 16, 1, corner, dim);
+
+ const view = l.view;
+ f.clip(view);
+ for (0..world.slots()) |slot| {
+ const k: u32 = @intCast(slot);
+ const b = l.box(k).toScreen(cam);
+ if (b.whole.y + b.whole.h <= view.y or b.whole.y >= view.y + view.h) continue;
+ // Centred in the band above the waveform, whatever the zoom.
+ const title_y = @round(b.whole.y + (b.wave.y - b.whole.y - 8) / 2);
+ if (k == world.takes) {
+ f.print(b.whole.x, title_y, 1, green, "LIVE the microphone, the last {d} s", .{live_seconds});
+ if (ss.live.heard == 0) f.text(b.wave.x + 8, b.wave.y + 8, 1, "nothing from the microphone yet", dim);
+ if (cam.zoom >= 0.8) axes(f, b, rate, null);
+ tunerOverlay(f, b.spectrum, ss.tuners[@intFromEnum(Tuned.input)].reading, s.a4, rate, cam.zoom >= 0.8);
+ continue;
+ }
+ const t = clipOf(ss, takes[k].id) orelse continue;
+ const seconds = Time{ .seconds = @as(f64, @floatFromInt(t.len)) / rate };
+ if (recording and k + 1 == world.takes) {
+ f.print(b.whole.x, title_y, 1, red, "RECORDING take {d} {f}", .{ k + 1, seconds });
+ } else {
+ const chosen = k == selected;
+ if (chosen) f.fill(.{ .x = b.whole.x - if (l.narrow) @as(f32, 6) else 12, .y = b.wave.y, .w = 3, .h = b.timeline.h }, yellow);
+ f.print(b.whole.x, title_y, 1, @as(u24, if (chosen) bright else dim), "#{d} {s} {f}", .{ k + 1, source(&takes[k]), seconds });
+ }
+ if (cam.zoom >= 0.8) {
+ const span = visible(s.views[k], t.len, @intFromFloat(@min(l.box(0).wave.w, layouts.max_columns)));
+ axes(f, b, rate, .{ span[0] / rate, span[1] / rate });
+ }
+ const which: ?Tuned = if (recording) (if (k + 1 == world.takes) .input else null) else if (k == selected) .take else null;
+ if (which) |w| tunerOverlay(f, b.spectrum, ss.tuners[@intFromEnum(w)].reading, s.a4, rate, cam.zoom >= 0.8);
+ }
+ f.clip(null);
+ if (world.takes == 0) f.text(16, view.y + view.h - 12, 1, "No takes yet: REC records one, OPEN opens a file.", dim);
+ // Keys, where there is a keyboard to press them.
+ if (!l.narrow) f.text(16, f.in.height - 16, 1, "R SPACE LEFT RIGHT HOME END O DEL 0 [ ] UP/DOWN take wheel or 2 fingers pan CTRL+wheel or pinch zoom", dim);
+}
+
+/// The tuner on a spectrum: the pitch and its harmonics where they fall on
+/// it, the span of two semitones either side shaded, and that span
+/// magnified across the top: the nearest notes of the chromatic scale,
+/// the pitch as a needle between them, and the note in cents and Hz.
+fn tunerOverlay(f: *sk.Frame, r: sk.Rect, reading: ?tuner.Reading, a4: f32, rate: f64, detailed: bool) void {
+ const at = reading orelse return;
+ const max_freq = scope.maxFreq(rate);
+ const fade: u8 = @intFromFloat(255 * std.math.clamp(1 - at.quiet / tuner.hold_seconds, 0.2, 1));
+ const cents = at.cents();
+ const color = sk.Color.hex(if (@abs(cents) <= 5) green else if (@abs(cents) <= 15) yellow else 0xff8a4d).alpha(fade);
+ const x = struct {
+ fn of(rect: sk.Rect, hz: f32, ceiling: f32) f32 {
+ return rect.x + @log(hz / scope.min_freq) / @log(ceiling / scope.min_freq) * rect.w;
+ }
+ }.of;
+
+ const freq = scope.hz(at.pitch, a4);
+ const lo = scope.hz(@as(f32, @floatFromInt(at.note)) - 2.5, a4);
+ const hi = scope.hz(@as(f32, @floatFromInt(at.note)) + 2.5, a4);
+ f.fill(.{ .x = x(r, lo, max_freq), .y = r.y, .w = @max(x(r, hi, max_freq) - x(r, lo, max_freq), 1), .h = r.h }, sk.Color.white.alpha(fade / 10));
+ f.fill(.{ .x = @round(x(r, freq, max_freq)), .y = r.y, .w = 1, .h = r.h }, color);
+ // The harmonics the pitch accounts for.
+ for (2..9) |h| {
+ const hz = freq * @as(f32, @floatFromInt(h));
+ if (hz > max_freq) break;
+ f.fill(.{ .x = @round(x(r, hz, max_freq)), .y = r.y + r.h - 10, .w = 1, .h = 10 }, color.alpha(fade / 2));
+ }
+ if (!detailed) return;
+
+ // The magnified scale: semitones `note - 2.5` to `note + 2.5`.
+ const strip: sk.Rect = .{ .x = r.x + 6, .y = r.y + 4, .w = r.w - 12, .h = 30 };
+ const semitone = strip.w / 5;
+ const centre = strip.x + strip.w / 2;
+ f.fill(strip, sk.Color.hex(0x0b0c0f).alpha(220));
+ var c: f32 = -250;
+ while (c <= 250) : (c += 10) {
+ const whole = @mod(c, 100) == 0;
+ const h: f32 = if (whole) 10 else if (@mod(c, 50) == 0) 6 else 3;
+ f.fill(.{ .x = @round(centre + c / 100 * semitone), .y = strip.y + strip.h - h, .w = 1, .h = h }, sk.Color.hex(if (c == 0) bright else dim).alpha(if (whole) 220 else 120));
+ }
+ for (0..5) |i| {
+ const note = at.note - 2 + @as(i32, @intCast(i));
+ const label = f.format("{s}{d}", .{ tuner.name(note), tuner.octave(note) });
+ const lx = centre + (@as(f32, @floatFromInt(i)) - 2) * semitone - @as(f32, @floatFromInt(label.len * 4));
+ f.text(lx, strip.y + 4, 1, label, if (note == at.note) color else sk.Color.hex(dim).alpha(fade));
+ }
+ const needle = std.math.clamp(centre + cents / 100 * semitone, strip.x, strip.x + strip.w - 2);
+ f.fill(.{ .x = @round(needle) - 1, .y = strip.y + 14, .w = 3, .h = strip.h - 14 }, color);
+
+ // The reading.
+ const big = f.format("{s}{d}", .{ tuner.name(at.note), tuner.octave(at.note) });
+ const panel: sk.Rect = .{ .x = r.x + r.w - 6 - 124, .y = strip.y + strip.h + 4, .w = 124, .h = 50 };
+ f.fill(panel, sk.Color.hex(0x0b0c0f).alpha(200));
+ f.text(panel.x + 6, panel.y + 4, 3, big, color);
+ const whole = @round(cents);
+ f.print(panel.x + 6, panel.y + 30, 1, sk.Color.hex(bright).alpha(fade), "{s}{d:.0} cents", .{ if (whole > 0) "+" else "", if (whole == 0) 0 else whole });
+ f.print(panel.x + 6, panel.y + 40, 1, sk.Color.hex(dim).alpha(fade), "{d:.2} Hz", .{freq});
+ f.print(panel.x + 70, panel.y + 4, 1, sk.Color.hex(dim).alpha(fade), "A4 {d:.0}", .{a4});
+}
+
+fn button(s: *const State, f: *sk.Frame, a: Action, r: sk.Rect) void {
+ const now = s.transport.value;
+ const label: []const u8, const lit: ?u24 = switch (a) {
+ .record => if (now == .recording) .{ "STOP", red } else .{ "REC", null },
+ .play => if (now == .forward or now == .backward) .{ "PAUSE", 0x7fd7ff } else .{ "PLAY", null },
+ .backward => .{ "REV", if (now == .backward) 0x7fd7ff else null },
+ .open => .{ "OPEN", null },
+ .delete => .{ "DEL", null },
+ .overview => .{ "ALL", null },
+ .a4_down => .{ "A4-", null },
+ .a4_up => .{ "A4+", null },
+ .forward, .start, .end => .{ "", null },
+ };
+ f.fill(r, sk.Color.hex(if (lit) |c| c else 0x1c2029).alpha(if (lit != null) 70 else 255));
+ f.fill(.{ .x = r.x, .y = r.y + r.h - 1, .w = r.w, .h = 1 }, sk.Color.hex(lit orelse 0x2e3440));
+ f.text(r.x + (r.w - @as(f32, @floatFromInt(label.len * 8))) / 2, r.y + 9, 1, label, sk.Color.hex(lit orelse bright));
+}
+
+fn source(t: *const Take) []const u8 {
+ return if (t.source_len > 0) t.source[0..t.source_len] else "microphone";
+}
+
+/// A panel's scales: its time span (seconds; null for the live view, which
+/// ends now) under the spectrogram, frequencies up the spectrogram, and
+/// frequency and level on the spectrum.
+fn axes(f: *sk.Frame, b: Box, rate: f64, span: ?[2]f64) void {
+ const below = b.spectrogram.y + b.spectrogram.h + 4;
+ const left = if (span) |sp| f.format("{f}", .{Time{ .seconds = sp[0] }}) else f.format("-{d} s", .{live_seconds});
+ const right = if (span) |sp| f.format("{f}", .{Time{ .seconds = sp[1] }}) else "now";
+ f.text(b.wave.x, below, 1, left, dim);
+ f.text(b.wave.x + b.wave.w - @as(f32, @floatFromInt(right.len * 8)), below, 1, right, dim);
+
+ const max_freq = scope.maxFreq(rate);
+ for ([_]f64{ 100, 1000, 10000 }) |hz| {
+ const y = b.spectrogram.y + b.spectrogram.h * (1 - @as(f32, @floatCast(@log(hz / scope.min_freq) / @log(max_freq / scope.min_freq))));
+ f.fill(.{ .x = b.spectrogram.x, .y = y, .w = 6, .h = 1 }, sk.Color.white.alpha(140));
+ f.text(b.spectrogram.x + 9, y - 4, 1, hzLabel(f, hz), sk.Color.white.alpha(170));
+ }
+
+ for ([_]f64{ 50, 200, 1000, 5000, 20000 }) |hz| {
+ if (hz > max_freq) continue;
+ const x = b.spectrum.x + @as(f32, @floatCast(@log(hz / scope.min_freq) / @log(max_freq / scope.min_freq))) * b.spectrum.w;
+ f.text(@min(x + 3, b.spectrum.x + b.spectrum.w - 24), b.spectrum.y + b.spectrum.h + 4, 1, hzLabel(f, hz), dim);
+ }
+ var db: f32 = -24;
+ while (db > scope.floor_db) : (db -= 24) {
+ const y = b.spectrum.y + b.spectrum.h * (db / scope.floor_db);
+ f.print(b.spectrum.x + 4, y + 3, 1, dim, "{d}", .{db});
+ }
+}
+
+fn hzLabel(f: *sk.Frame, hz: f64) []const u8 {
+ return if (hz >= 1000) f.format("{d}k", .{hz / 1000}) else f.format("{d}", .{hz});
+}
+
+const Time = struct {
+ seconds: f64,
+
+ pub fn format(t: Time, w: *std.Io.Writer) std.Io.Writer.Error!void {
+ const ms: u64 = @intFromFloat(@max(t.seconds, 0) * 1000);
+ try w.print("{d}:{d:0>2}.{d:0>3}", .{ ms / 60_000, ms / 1000 % 60, ms % 1000 });
+ }
+};
+
+test "zoom keeps the view inside the take and around the pointer" {
+ var v: View = .{};
+ zoom(&v, 0.5, 0.5);
+ try std.testing.expectApproxEqAbs(@as(f32, 0.25), v.lo, 1e-6);
+ try std.testing.expectApproxEqAbs(@as(f32, 0.75), v.hi, 1e-6);
+ zoom(&v, 0.0, 4);
+ try std.testing.expectEqual(@as(f32, 0), v.lo);
+ try std.testing.expectEqual(@as(f32, 1), v.hi);
+}
+
+test "the world stacks takes in order with the live view last" {
+ const world: World = .{ .takes = 3, .live = true };
+ try std.testing.expectEqual(@as(u32, 4), world.slots());
+ const l = Layout.of(width, height);
+ try std.testing.expectEqual(@as(?u32, 0), world.takeAt(l, .{ .x = 10, .y = 1 }));
+ try std.testing.expectEqual(@as(?u32, 2), world.takeAt(l, .{ .x = 10, .y = 2 * l.panel_height + 1 }));
+ try std.testing.expectEqual(@as(?u32, null), world.takeAt(l, .{ .x = 10, .y = 3 * l.panel_height + 1 }));
+}
+
+test "the camera follows the bottom and stays inside the world, wide or narrow" {
+ for ([_]Layout{ .of(width, height), .of(390, 844) }) |l| {
+ var s: State = .{};
+ s.takes.len = 5;
+ const cam = cameraOf(&s, l);
+ // Following: the live view's bottom sits at the viewport's bottom.
+ try std.testing.expectApproxEqAbs(l.view.y + l.view.h - 4, cam.toScreen(l.box(5).whole).y + l.panel_height, 1);
+ s.follow = false;
+ s.camera.y = 1e6;
+ try std.testing.expectApproxEqAbs(l.view.y + 4, cameraOf(&s, l).toScreen(l.box(0).whole).y, 1);
+ }
+}
+
+test "a narrow layout stacks the spectrum under the timeline, inside the panel" {
+ const l: Layout = .of(390, 844);
+ try std.testing.expect(l.narrow);
+ const b = l.box(0);
+ try std.testing.expect(b.spectrum.y > b.timeline.y + b.timeline.h);
+ try std.testing.expect(b.spectrum.y + b.spectrum.h + 16 <= b.whole.y + b.whole.h);
+ try std.testing.expectEqual(l.world_width, b.timeline.w);
+ // Buttons fill the bottom, inside the canvas, without overlapping.
+ for (0..buttons.len) |i| {
+ const r = l.button(i);
+ try std.testing.expect(r.x >= 0 and r.x + r.w <= l.w and r.y + r.h <= l.h);
+ try std.testing.expect(r.w >= 40);
+ }
+}
+
+test {
+ _ = tuner;
+}
+
diff --git a/examples/micscope/src/tuner.zig b/examples/micscope/src/tuner.zig
new file mode 100644
index 0000000..159798b
--- /dev/null
+++ b/examples/micscope/src/tuner.zig
@@ -0,0 +1,132 @@
+//! From pitch estimates (tuner.comp's YIN, one per frame) to a steady note on
+//! the 12-tone equal-tempered chromatic scale, for any instrument: notes are
+//! MIDI numbers (69 is A4, at `a4` Hz), so the range is whatever the
+//! detector finds, from a bass's low B to a piccolo's top.
+//!
+//! Raw estimates jitter and, at a note's attack or release, misfire. So:
+//! unclear or quiet estimates are ignored; the median of the last few
+//! clear ones is followed, smoothed; a jump of over a semitone restarts the
+//! median, so a new note shows at once; and the note shown only changes
+//! once the pitch is 60 cents from it, so a note held a quarter tone sharp
+//! does not flicker between two names.
+const std = @import("std");
+const scope = @import("scope");
+const layouts = @import("layouts");
+
+/// Estimates clearer than this are a note (YIN's threshold is 0.12, so
+/// clarity 0.88 at least when its first dip was found).
+pub const min_clarity = 0.85;
+/// Quieter than this is silence, dBFS.
+pub const min_level = -60.0;
+/// How long the last note stays (shown as fading) after the sound stops.
+pub const hold_seconds = 1.0;
+
+pub fn name(note: i32) []const u8 {
+ return scope.note_names[@intCast(@mod(note, 12))];
+}
+
+pub fn octave(note: i32) i32 {
+ return @divFloor(note, 12) - 1;
+}
+
+pub const Reading = struct {
+ /// The note it is nearest, as a MIDI number.
+ note: i32,
+ /// The pitch, as a fractional MIDI number.
+ pitch: f32,
+ /// Seconds since a clear estimate: 0 while the note sounds.
+ quiet: f32,
+
+ pub fn cents(r: Reading) f32 {
+ return (r.pitch - @as(f32, @floatFromInt(r.note))) * 100;
+ }
+};
+
+pub const Tracker = struct {
+ recent: [5]f32 = @splat(0),
+ count: u32 = 0,
+ reading: ?Reading = null,
+
+ pub fn feed(t: *Tracker, p: layouts.Pitch, a4: f32, dt: f32) void {
+ const clear = p.freq > 0 and p.clarity >= min_clarity and p.level >= min_level;
+ if (!clear) {
+ t.count = 0;
+ if (t.reading) |*r| {
+ r.quiet += dt;
+ if (r.quiet > hold_seconds) t.reading = null;
+ }
+ return;
+ }
+ const m = scope.midi(p.freq, a4);
+ if (t.count > 0 and @abs(m - t.median()) > 1) t.count = 0;
+ if (t.count == t.recent.len) {
+ std.mem.copyForwards(f32, t.recent[0 .. t.recent.len - 1], t.recent[1..]);
+ t.count -= 1;
+ }
+ t.recent[t.count] = m;
+ t.count += 1;
+ const target = t.median();
+
+ const fresh = t.count == 1 or t.reading == null or t.reading.?.quiet > 0;
+ var r: Reading = if (fresh) .{ .note = @intFromFloat(@round(target)), .pitch = target, .quiet = 0 } else t.reading.?;
+ r.pitch += (target - r.pitch) * 0.4;
+ r.quiet = 0;
+ if (@abs(r.pitch - @as(f32, @floatFromInt(r.note))) > 0.6) r.note = @intFromFloat(@round(r.pitch));
+ t.reading = r;
+ }
+
+ fn median(t: *const Tracker) f32 {
+ var sorted = t.recent;
+ std.mem.sort(f32, sorted[0..t.count], {}, std.sort.asc(f32));
+ return sorted[t.count / 2];
+ }
+};
+
+fn pitchOf(freq: f32) layouts.Pitch {
+ return .{ .freq = freq, .clarity = 0.97, .level = -20, .period = 48_000 / freq };
+}
+
+test "notes and octaves on the chromatic scale" {
+ try std.testing.expectEqualStrings("E", name(40));
+ try std.testing.expectEqual(@as(i32, 2), octave(40));
+ try std.testing.expectEqualStrings("B", name(23));
+ try std.testing.expectEqual(@as(i32, 0), octave(23));
+}
+
+test "a held note settles, in cents from it" {
+ var t: Tracker = .{};
+ // A4, 12 cents sharp.
+ const sharp = scope.hz(69.12, 440);
+ for (0..20) |_| t.feed(pitchOf(sharp), 440, 1.0 / 60.0);
+ const r = t.reading.?;
+ try std.testing.expectEqual(@as(i32, 69), r.note);
+ try std.testing.expectApproxEqAbs(@as(f32, 12), r.cents(), 0.5);
+}
+
+test "one wild estimate does not move the note" {
+ var t: Tracker = .{};
+ for (0..10) |_| t.feed(pitchOf(110), 440, 1.0 / 60.0);
+ t.feed(pitchOf(220), 440, 1.0 / 60.0);
+ t.feed(pitchOf(110), 440, 1.0 / 60.0);
+ try std.testing.expectEqual(@as(i32, 45), t.reading.?.note);
+}
+
+test "a new note shows at once, a quarter tone does not flicker" {
+ var t: Tracker = .{};
+ for (0..10) |_| t.feed(pitchOf(110), 440, 1.0 / 60.0);
+ for (0..3) |_| t.feed(pitchOf(146.83), 440, 1.0 / 60.0);
+ try std.testing.expectEqual(@as(i32, 50), t.reading.?.note);
+ // 55 cents sharp of D3 stays D3.
+ for (0..30) |_| t.feed(pitchOf(scope.hz(50.55, 440)), 440, 1.0 / 60.0);
+ try std.testing.expectEqual(@as(i32, 50), t.reading.?.note);
+}
+
+test "silence holds the note a while, then lets go" {
+ var t: Tracker = .{};
+ for (0..10) |_| t.feed(pitchOf(330), 440, 1.0 / 60.0);
+ const quiet: layouts.Pitch = .{ .freq = 0, .clarity = 0, .level = -120, .period = 0 };
+ for (0..30) |_| t.feed(quiet, 440, 1.0 / 60.0);
+ try std.testing.expect(t.reading != null);
+ for (0..60) |_| t.feed(quiet, 440, 1.0 / 60.0);
+ try std.testing.expect(t.reading == null);
+}
diff --git a/examples/micscope/test/README.md b/examples/micscope/test/README.md
new file mode 100644
index 0000000..6f4b833
--- /dev/null
+++ b/examples/micscope/test/README.md
@@ -0,0 +1,22 @@
+# Test material
+
+- `sweep.wav`: a 2 s log sweep (40 Hz to 16 kHz) over a quiet 440 Hz tone,
+ 48 kHz mono, generated for these tests.
+- `tones.wav`: five 1 s notes for the tuner, generated for these tests
+ (harmonics with a little noise, 48 kHz mono): E1 with its 2nd harmonic
+ loudest, E2 with a weak fundamental, A4 12 cents sharp, D4 with no
+ fundamental at all, and C7.
+- `reference.flac`: the rendering reference, all on one screen. 15 s of a
+ loudly mastered electronic track (sub-bass kicks, hats, a full mix), then
+ 15 s of a Berlin street (traffic, a close vehicle pass, broadband noise),
+ then `sweep.wav`; 48 kHz stereo, joined with short crossfades.
+
+ - Square Punch, "Thundercat" (Plasma Pumper EP, 2011), from 3:36:
+ [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Square_Punch_-_Thundercat.flac),
+ CC BY-SA 3.0.
+ - LG, "traffic karl-liebknechtstrasse 111223", from 1:18:
+ [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:141977_lg_traffic-karl-liebknechtstrasse-111223.wav),
+ from [Freesound](http://freesound.org/people/LG/sounds/141977/),
+ CC BY-SA 3.0.
+
+ The excerpt is licensed CC BY-SA 3.0 like its sources.
diff --git a/examples/micscope/test/profile.script b/examples/micscope/test/profile.script
new file mode 100644
index 0000000..aa56b3e
--- /dev/null
+++ b/examples/micscope/test/profile.script
@@ -0,0 +1,167 @@
+# Zooms in and out one ctrl+wheel step per frame on the reference take, so
+# waveform and spectrogram are recomputed every frame: run by
+# `zig build profile` with --profile-gpu, which prints GPU time per command.
+console open test/reference.flac
+frames 3
+key right
+hold left_ctrl
+wheel 470 150 0.15
+frames 1
+wheel 470 150 0.15
+frames 1
+wheel 470 150 0.15
+frames 1
+wheel 470 150 0.15
+frames 1
+wheel 470 150 0.15
+frames 1
+wheel 470 150 0.15
+frames 1
+wheel 470 150 0.15
+frames 1
+wheel 470 150 0.15
+frames 1
+wheel 470 150 0.15
+frames 1
+wheel 470 150 0.15
+frames 1
+wheel 470 150 0.15
+frames 1
+wheel 470 150 0.15
+frames 1
+wheel 470 150 0.15
+frames 1
+wheel 470 150 0.15
+frames 1
+wheel 470 150 0.15
+frames 1
+wheel 470 150 0.15
+frames 1
+wheel 470 150 0.15
+frames 1
+wheel 470 150 0.15
+frames 1
+wheel 470 150 0.15
+frames 1
+wheel 470 150 0.15
+frames 1
+wheel 470 150 0.15
+frames 1
+wheel 470 150 0.15
+frames 1
+wheel 470 150 0.15
+frames 1
+wheel 470 150 0.15
+frames 1
+wheel 470 150 0.15
+frames 1
+wheel 470 150 0.15
+frames 1
+wheel 470 150 0.15
+frames 1
+wheel 470 150 0.15
+frames 1
+wheel 470 150 0.15
+frames 1
+wheel 470 150 0.15
+frames 1
+wheel 470 150 0.15
+frames 1
+wheel 470 150 0.15
+frames 1
+wheel 470 150 0.15
+frames 1
+wheel 470 150 0.15
+frames 1
+wheel 470 150 0.15
+frames 1
+wheel 470 150 0.15
+frames 1
+wheel 470 150 0.15
+frames 1
+wheel 470 150 0.15
+frames 1
+wheel 470 150 0.15
+frames 1
+wheel 470 150 0.15
+frames 1
+wheel 470 150 -0.15
+frames 1
+wheel 470 150 -0.15
+frames 1
+wheel 470 150 -0.15
+frames 1
+wheel 470 150 -0.15
+frames 1
+wheel 470 150 -0.15
+frames 1
+wheel 470 150 -0.15
+frames 1
+wheel 470 150 -0.15
+frames 1
+wheel 470 150 -0.15
+frames 1
+wheel 470 150 -0.15
+frames 1
+wheel 470 150 -0.15
+frames 1
+wheel 470 150 -0.15
+frames 1
+wheel 470 150 -0.15
+frames 1
+wheel 470 150 -0.15
+frames 1
+wheel 470 150 -0.15
+frames 1
+wheel 470 150 -0.15
+frames 1
+wheel 470 150 -0.15
+frames 1
+wheel 470 150 -0.15
+frames 1
+wheel 470 150 -0.15
+frames 1
+wheel 470 150 -0.15
+frames 1
+wheel 470 150 -0.15
+frames 1
+wheel 470 150 -0.15
+frames 1
+wheel 470 150 -0.15
+frames 1
+wheel 470 150 -0.15
+frames 1
+wheel 470 150 -0.15
+frames 1
+wheel 470 150 -0.15
+frames 1
+wheel 470 150 -0.15
+frames 1
+wheel 470 150 -0.15
+frames 1
+wheel 470 150 -0.15
+frames 1
+wheel 470 150 -0.15
+frames 1
+wheel 470 150 -0.15
+frames 1
+wheel 470 150 -0.15
+frames 1
+wheel 470 150 -0.15
+frames 1
+wheel 470 150 -0.15
+frames 1
+wheel 470 150 -0.15
+frames 1
+wheel 470 150 -0.15
+frames 1
+wheel 470 150 -0.15
+frames 1
+wheel 470 150 -0.15
+frames 1
+wheel 470 150 -0.15
+frames 1
+wheel 470 150 -0.15
+frames 1
+wheel 470 150 -0.15
+frames 1
diff --git a/examples/micscope/test/record.script b/examples/micscope/test/record.script
new file mode 100644
index 0000000..843d802
--- /dev/null
+++ b/examples/micscope/test/record.script
@@ -0,0 +1,23 @@
+# Records (from whatever microphone the host gives a headless run) into a
+# new take, stops, and plays it back.
+expect takes.len 0
+key r
+expect transport.value recording
+expect takes.len 1
+frames 60
+screenshot .zig-cache/micscope/recording.png
+key r
+expect transport.value stopped
+key space
+expect transport.value forward
+frames 10
+# Each recording is another take; opening a file while recording ends it.
+key r
+expect takes.len 2
+expect selected 1
+console open test/sweep.wav
+expect transport.value stopped
+expect takes.len 3
+frames 2
+expect takes.len 3
+screenshot .zig-cache/micscope/strip.png
diff --git a/examples/micscope/test/reference.flac b/examples/micscope/test/reference.flac
new file mode 100644
index 0000000..7ad1c63
--- /dev/null
+++ b/examples/micscope/test/reference.flac
Binary files differ
diff --git a/examples/micscope/test/render.script b/examples/micscope/test/render.script
new file mode 100644
index 0000000..71b50c7
--- /dev/null
+++ b/examples/micscope/test/render.script
@@ -0,0 +1,18 @@
+# The rendering reference (see README.md): song, street and sweep in one
+# take. Screenshots land in .zig-cache/micscope/ for review.
+console open test/reference.flac
+expect transport.value stopped
+frames 3
+screenshot .zig-cache/micscope/reference.png
+# Playing: the playhead across waveform and spectrogram, the spectrum.
+key right
+frames 90
+expect-audio 1
+screenshot .zig-cache/micscope/reference-playing.png
+# Zoomed into the street: the low end's hum lines and the noise floor.
+key space
+hold left_ctrl
+wheel 660 150 4
+release left_ctrl
+frames 3
+screenshot .zig-cache/micscope/reference-street.png
diff --git a/examples/micscope/test/sweep.wav b/examples/micscope/test/sweep.wav
new file mode 100644
index 0000000..1f131e3
--- /dev/null
+++ b/examples/micscope/test/sweep.wav
Binary files differ
diff --git a/examples/micscope/test/tones.wav b/examples/micscope/test/tones.wav
new file mode 100644
index 0000000..b2cf3ea
--- /dev/null
+++ b/examples/micscope/test/tones.wav
Binary files differ
diff --git a/examples/micscope/test/transport.script b/examples/micscope/test/transport.script
new file mode 100644
index 0000000..2015682
--- /dev/null
+++ b/examples/micscope/test/transport.script
@@ -0,0 +1,98 @@
+# Opens a file as a take and plays it both ways: a 2 s log sweep (40 Hz to
+# 16 kHz) over a quiet 440 Hz tone.
+console open test/sweep.wav
+frames 2
+expect takes.len 1
+expect selected 0
+expect transport.value stopped
+key right
+expect transport.value forward
+frames 30
+expect-audio 1
+screenshot .zig-cache/micscope/forward.png
+key left
+expect transport.value backward
+expect backward true
+frames 20
+key space
+expect transport.value stopped
+# Space resumes the way it last went.
+key space
+expect transport.value backward
+key space
+# Seeking: keys, and a click on the take's timeline.
+key end
+expect seek.value 1
+click 400 150
+expect seek.serial 2
+# Ctrl+wheel (or a pinch) on a take's timeline zooms its time around the
+# pointer; Z zooms back out.
+hold left_ctrl
+wheel 400 150 3
+release left_ctrl
+key z
+key right
+frames 30
+screenshot .zig-cache/micscope/played.png
+# A second take goes under the first and is selected; up is older.
+console open test/sweep.wav
+expect takes.len 2
+expect selected 1
+key up
+expect selected 0
+key down
+expect selected 1
+# A click on the first take selects it.
+click 400 150
+expect selected 0
+frames 2
+screenshot .zig-cache/micscope/two-takes.png
+# Deleting it leaves the second. Its file stays: going back to before the
+# deletion reads it again.
+console save two
+key delete
+expect takes.len 1
+expect selected 0
+console load two
+frames 2
+expect takes.len 2
+key delete
+expect takes.len 1
+# A counter that names a take file already written (--fresh keeps the
+# files; a seek back finds the future's) is moved past it by draw.
+console set next_id 1
+frames 2
+expect next_id 3
+# More takes than fit: the camera follows the bottom until the wheel pans
+# it, then 0 shows the whole strip.
+console open test/sweep.wav
+console open test/sweep.wav
+console open test/sweep.wav
+expect follow true
+wheel 400 400 2
+expect follow false
+frames 2
+screenshot .zig-cache/micscope/panned.png
+key 0
+expect follow true
+frames 2
+screenshot .zig-cache/micscope/overview.png
+# Ctrl+wheel off the timelines zooms the view.
+hold left_ctrl
+wheel 1150 400 1
+release left_ctrl
+frames 2
+screenshot .zig-cache/micscope/zoomed-view.png
+# The buttons on top do what the keys do, for touch screens.
+click 832 18
+expect transport.value recording
+click 832 18
+expect transport.value stopped
+click 890 18
+expect transport.value forward
+click 890 18
+expect transport.value stopped
+click 1238 18
+expect a4 441
+frames 2
+screenshot .zig-cache/micscope/buttons.png
diff --git a/examples/micscope/test/tuner.script b/examples/micscope/test/tuner.script
new file mode 100644
index 0000000..4e0e480
--- /dev/null
+++ b/examples/micscope/test/tuner.script
@@ -0,0 +1,31 @@
+# The tuner on a take, at its playhead: five notes where the strongest FFT
+# peak is not (or not only) the note. Expected, by screenshot:
+# E1 0 cents (41.2 Hz) bass, 2nd harmonic loudest
+# E2 0 cents (82.4 Hz) guitar, weak fundamental
+# A4 +12 cents (443.1 Hz) sharp
+# D4 0 cents (293.7 Hz) fundamental missing
+# C7 0 cents (2093 Hz) piccolo
+console open test/tones.wav
+click 107 150
+frames 20
+screenshot .zig-cache/micscope/tuner-e1.png
+click 290 150
+frames 20
+screenshot .zig-cache/micscope/tuner-e2.png
+click 472 150
+frames 20
+screenshot .zig-cache/micscope/tuner-a4.png
+click 654 150
+frames 20
+screenshot .zig-cache/micscope/tuner-d4.png
+click 837 150
+frames 20
+screenshot .zig-cache/micscope/tuner-c7.png
+# Another reference pitch: A4 = 443 makes the sharp A4 in tune.
+click 472 150
+key right_bracket
+key right_bracket
+key right_bracket
+expect a4 443
+frames 20
+screenshot .zig-cache/micscope/tuner-a443.png
diff --git a/examples/micscope/web/icon-192.png b/examples/micscope/web/icon-192.png
new file mode 100644
index 0000000..0b26078
--- /dev/null
+++ b/examples/micscope/web/icon-192.png
Binary files differ
diff --git a/examples/micscope/web/icon-512.png b/examples/micscope/web/icon-512.png
new file mode 100644
index 0000000..0b5538c
--- /dev/null
+++ b/examples/micscope/web/icon-512.png
Binary files differ
diff --git a/examples/micscope/web/icon.svg b/examples/micscope/web/icon.svg
new file mode 100644
index 0000000..1220011
--- /dev/null
+++ b/examples/micscope/web/icon.svg
@@ -0,0 +1,26 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
+ <!-- micscope's icon: a waveform over its spectrogram's harmonics, in the
+ app's colours. Full-bleed, so it also works masked. Rendered to the
+ PNGs beside it with: resvg -w N -h N icon.svg icon-N.png -->
+ <defs>
+ <linearGradient id="heat" gradientUnits="userSpaceOnUse" x1="96" y1="0" x2="416" y2="0">
+ <stop offset="0" stop-color="#2b0a4a"/>
+ <stop offset="0.25" stop-color="#b8325a"/>
+ <stop offset="0.6" stop-color="#f98c0a"/>
+ <stop offset="1" stop-color="#fcf3a6"/>
+ </linearGradient>
+ </defs>
+ <rect width="512" height="512" fill="#0b0c0f"/>
+ <!-- harmonics: a fundamental and its overtones, fading -->
+ <g stroke="url(#heat)" stroke-linecap="round">
+ <line x1="96" y1="392" x2="416" y2="392" stroke-width="22"/>
+ <line x1="96" y1="340" x2="416" y2="340" stroke-width="16" opacity="0.85"/>
+ <line x1="96" y1="300" x2="416" y2="300" stroke-width="11" opacity="0.65"/>
+ <line x1="96" y1="270" x2="416" y2="270" stroke-width="7" opacity="0.45"/>
+ </g>
+ <!-- the waveform -->
+ <path d="M96 176 C120 96 152 96 176 176 S232 256 256 176 S312 96 336 176 S392 256 416 176"
+ fill="none" stroke="#6fdc8c" stroke-width="18" stroke-linecap="round"/>
+ <!-- the tuner's needle -->
+ <rect x="246" y="76" width="20" height="356" rx="10" fill="#ffd84d" opacity="0.9"/>
+</svg>
diff --git a/examples/spheres/README.md b/examples/spheres/README.md
new file mode 100644
index 0000000..30023de
--- /dev/null
+++ b/examples/spheres/README.md
@@ -0,0 +1,155 @@
+# spheres
+
+The three-body problem, heard. Three bodies pull on each other; each is
+also a voice, synthesised from its motion. A [sketchbook](../..)
+sketch: native on Linux, and in browsers with WebGPU.
+
+Everything moves on the GPU:
+
+| Shader | Does |
+| --- | --- |
+| `sim.comp` | 16384 copies of the system at once, one per thread: system 0 as given, the others moved by up to 2×10⁻⁴. The copies drawn as a cloud show chaos as it happens: the Pythagorean problem's tears apart, the figure eight's stays a line. System 0 also leaves its trail and sings: from its own motion, or from a look-ahead snapshot while a chord is held. |
+| `physics.glsl`, `voices.glsl` | Included by the simulation and the look-ahead, so the live system and its futures move and sing alike. Leapfrog (kick, drift, kick), symplectic and time-reversible, with close passes split into steps of 2 % of the local dynamical time; and the mapping from motion to voices below. |
+| `lookahead.comp` | 32 futures of system 0, one per thread, from the preset's start: alternative 0 as system 0 began, the rest nudged by growing amounts so chaotic ones fan out. 8 snapshots a frame each (0.4 s of simulated time, against the live system's 0.7 s a second), every snapshot kept on the GPU with the chord sung there. |
+| `rechord.comp` | The look-ahead's chords again when SCALE changes. |
+| `synth.comp` | Each audio block, one thread per sample, from the voices: phases in closed form for frequencies gliding across the block, so blocks join seamlessly and every sample is computed alone. |
+| `advance.comp` | Where the block's phases ended, for the next. |
+| `sprite.*`, `trail.*`, `fade.frag` | The sky: the cloud as layered dust on a long exposure, system 0's bodies as glows, and their trails as ribbons tapering with age. |
+| `link.*` | The coupling: a ribbon from modulator to carrier, as bright as the coupling, with pulses flowing along it. |
+
+The sound goes from the GPU's block straight to the speakers
+(`f.audioBuffer`): the host reads it back in the same frame and keeps the
+lead it measures queued (`in.lead`), so a change is heard in about two
+device pulls rather than 100 ms. A second readback (`f.download`), a frame
+later, hands it to sketchbook's `scope` module (the views micscope uses)
+for the oscilloscope, spectrum and spectrogram.
+
+## From motion to sound
+
+Each body is a voice:
+
+- **pitch** follows its speed (220 Hz at speed 0.6, two octaves down to two
+ and a half up), snapped to a scale (diatonic by default; pentatonic, chromatic or none);
+- **modulator ratio** follows how lopsided its distances to the other two
+ are: near 1 or 2 (harmonic) when balanced, in between (bell-like) when
+ not;
+- **modulation depth** follows how near its nearest neighbour is: a close
+ pass bursts into sidebands.
+
+And the **closest pair is one FM voice**: the faster of the two falls
+silent and becomes the modulator, a sine at its own frequency modulating
+the slower one's carrier (two operators, both moved by the bodies), with an
+index that grows as they close in, up to 4. So two voices sound: the pair,
+and the third body on its own. When the closest pair changes, the old
+modulator fades back in as a voice while the new one fades out. In additive
+mode every harmonic gets the same push, so the timbre bends without
+turning harsh. The sky draws the pair: pulses running from the modulator to
+its carrier; the voices' lines say who is `modulating` and who is
+`FM by A 2.10`, and the spectrum marks the pair's sidebands, |J_k(index)|
+at multiples of the modulator's frequency.
+
+The synthesis, with carrier phase c, modulator phase m and depth d:
+
+| Mode | Signal |
+| --- | --- |
+| SINE | sin c |
+| ADD (the default) | harmonics k with weights r^(k−1), r = d/(d+2): brighter with depth |
+| AM | sin c · (1 + a sin m)/(1 + a), a = min(d/4, 1): sidebands at c ± m |
+| RING | sin c · sin m: only c ± m |
+| FM | the carrier's frequency swung by d times itself, by cos m: the index (deviation over modulator frequency) is d/ratio, so it changes as the ratio does |
+| PM | sin(c + d sin m): the index is d, whatever the modulator |
+
+FM and PM sound alike for a steady modulator and part when it moves. The
+spectrum marks where the theory puts each voice's partials (Bessel
+functions |J_k(index)| at carrier + k·modulator for FM and PM): the
+focused voice's in full, the others' as ticks.
+
+## As an instrument
+
+CHORDS (or C) turns spheres into a chord instrument. The look-ahead runs
+ahead of the sky, 120 s of simulated time filled in about five seconds, and
+the chords it finds light up on a grid laid out as a sanfona's (Stradella)
+bass side: columns round the circle of fifths (G♭ D♭ A♭ E♭ B♭ F C G D A E
+B; a phone shows B♭ to B), so neighbours are related chords, and rows by
+quality (major, minor, seventh, sus, power), each half a button over from
+the one above, so a progression is the same hand shape in any key. A
+button is dim until some future sings its chord. The computer keyboard's
+rows are staggered the same way: the number row plays majors, QWERTY
+minors, ASDF sevenths, ZXCV sus chords, column by column; Escape goes back
+to running free.
+
+A chord is the pitch classes of the three bodies' notes, the silent
+modulator's included (it sets the carrier's sidebands), and it only counts
+in a playable voicing: every note from E2 to A5, an octave and a fifth at
+most from lowest to highest, and the FM pair's index at most 3. Otherwise
+the same pitch classes are another sound, shrill, sprawling or a cloud of
+sidebands. How many there are
+depends on the scale (SCALE): pentatonic gives few, diatonic (the default)
+the white-key chords, chromatic every one, and unsnapped pitches round to
+the nearest semitone.
+
+A button finds the best time its chord plays in any of the 32 futures,
+weighing how near it is against how it sounds: half a second's travel more
+for another future than the system's own, 0.6 s for a root not in the bass,
+and up to 3 s for a wide, high or hard-modulated voicing. Then:
+
+- the sound jumps there at once: queued sound is dropped, and system 0
+ sings from that snapshot on the GPU, holding the chord;
+- the sky travels: the whole simulation runs forwards or backwards to that
+ time, about a second's ride, its trails drawn smoothly all the way (points
+ by simulated time, many a frame) or, going back, rewound, and system 0 steps into the snapshot,
+ into that future if it was another's, the jump leaving a break in the
+ trails rather than a line;
+- the sky holds still on that moment, the configuration that sings the
+ chord, until the next.
+
+The strip over the grid shows the system's own future's chords along time,
+coloured by row, now as a white line and the travel's target in yellow.
+Costs: the look-ahead takes about 0.7 ms of GPU a frame (2.4 ms at worst,
+through close passes) while it fills, and nothing after; the whole frame is
+about 1.4 ms on an RTX 3050.
+
+## Presets
+
+1. **Figure eight** (Chenciner and Montgomery): three equal masses on one
+ figure of eight. Stable.
+2. **Butterfly I** (Šuvakov and Dmitrašinović): periodic, unstable.
+3. **Pythagorean** (Burrau): masses 3, 4, 5 at rest on a 3-4-5 triangle;
+ close passes, chaos, and in the end an escape.
+4. **Lagrange triangle**: equal masses turning rigidly; unstable, so the
+ cloud shows it coming apart.
+5. **Random**: three masses and velocities from a seed (R draws again).
+
+## Keys
+
+| Key | |
+| --- | --- |
+| C | the instrument (the chord grid); Escape back to running free |
+| keyboard rows | as an instrument: number row majors, QWERTY minors, ASDF sevenths, ZXCV sus chords, by fifths |
+| Space | pause / run |
+| Left / Right | run time backwards / forwards (leapfrog retraces its steps, until chaos amplifies rounding) |
+| Up / Down | faster / slower |
+| P, E, X | the next preset, the figure eight, a random system |
+| S | the next synthesis mode |
+| Q | the scale: diatonic, chromatic, unsnapped, pentatonic |
+| M | mute |
+| Tab | the voice the spectrum and oscilloscope follow |
+| R | the preset again, copies spread anew |
+
+The buttons do the same on touch screens. The header shows the simulated
+time and the total energy: the figure eight's holds to the last digit
+shown; through the Pythagorean problem's close passes it drifts a few
+percent, where the adaptive steps cost leapfrog its exact symplecticity.
+
+On the web it is an installable app (a PWA) that opens offline. Its icon
+is `web/icon.svg`, rendered to the PNGs beside it with
+`resvg -w N -h N icon.svg icon-N.png`.
+
+## Building
+
+Zig 0.17 and `glslc`; for the web build `naga` (`cargo install naga-cli`),
+and to serve it `miniserve` and `openssl`.
+
+ zig build run # native, with hot reload (`zig build lib --watch` alongside)
+ zig build test # unit tests and a headless run of every preset and mode
+ zig build serve # the web build over https on port 8042
diff --git a/examples/spheres/build.zig b/examples/spheres/build.zig
new file mode 100644
index 0000000..8cc8f60
--- /dev/null
+++ b/examples/spheres/build.zig
@@ -0,0 +1,55 @@
+const std = @import("std");
+const sketchbook = @import("sketchbook");
+
+pub fn build(b: *std.Build) void {
+ const target = b.standardTargetOptions(.{});
+ const optimize = b.standardOptimizeOption(.{});
+ const sb = sketchbook.init(b, .{ .target = target, .optimize = optimize });
+
+ // The simulation, the synthesiser and the sky, as SPIR-V for the native
+ // host and WGSL for the web; their uniforms are src/layouts.zig's structs.
+ const layouts = b.createModule(.{ .root_source_file = b.path("src/layouts.zig") });
+ const shaders = sb.addShaders(.{
+ .layouts = .{ .module = layouts, .types = &.{ "SimParams", "LookParams", "SynthParams", "SkyView", "Fade" } },
+ .sources = &.{
+ b.path("shaders/sim.comp"),
+ b.path("shaders/lookahead.comp"),
+ b.path("shaders/rechord.comp"),
+ b.path("shaders/synth.comp"),
+ b.path("shaders/advance.comp"),
+ b.path("shaders/fullscreen.vert"),
+ b.path("shaders/fade.frag"),
+ b.path("shaders/sprite.vert"),
+ b.path("shaders/sprite.frag"),
+ b.path("shaders/trail.vert"),
+ b.path("shaders/trail.frag"),
+ b.path("shaders/link.vert"),
+ b.path("shaders/link.frag"),
+ },
+ });
+
+ const app = sb.app(.{
+ .name = "spheres",
+ .root_source_file = b.path("src/main.zig"),
+ .imports = &.{
+ .{ .name = "layouts", .module = layouts },
+ .{ .name = "shaders", .module = shaders.module },
+ .{ .name = "scope", .module = sb.modules.scope },
+ },
+ });
+ _ = app.addSteps(.{
+ // Installable, and it opens offline (icons from web/icon.svg).
+ // ReleaseSmall: a third the size of ReleaseSafe's wasm, and Zig
+ // 0.17's LLVM spins for many minutes optimising this sketch for speed.
+ .web = .{ .optimize = .ReleaseSmall, .pwa = .{
+ .description = "The three-body problem on the GPU, heard: each body a voice in FM, PM, AM, ring or additive synthesis.",
+ .background = "#05070d",
+ .theme = "#05070d",
+ .icons = &.{
+ .{ .source = b.path("web/icon-192.png"), .size = 192 },
+ .{ .source = b.path("web/icon-512.png"), .size = 512 },
+ },
+ } },
+ .scripts = &.{b.path("test/play.script")},
+ });
+}
diff --git a/examples/spheres/build.zig.zon b/examples/spheres/build.zig.zon
new file mode 100644
index 0000000..b982c30
--- /dev/null
+++ b/examples/spheres/build.zig.zon
@@ -0,0 +1,10 @@
+.{
+ .name = .spheres,
+ .version = "0.0.1",
+ .dependencies = .{
+ .sketchbook = .{ .path = "../.." },
+ },
+ .minimum_zig_version = "0.17.0",
+ .paths = .{""},
+ .fingerprint = 0x688720ee43c1135a,
+}
diff --git a/examples/spheres/shaders/advance.comp b/examples/spheres/shaders/advance.comp
new file mode 100644
index 0000000..e1e8789
--- /dev/null
+++ b/examples/spheres/shaders/advance.comp
@@ -0,0 +1,32 @@
+#version 450
+#extension GL_GOOGLE_include_directive : require
+// After synth.comp: where the block's phases ended, wrapped, for the next
+// block to start from; and the voices and coupling it ended on, to glide
+// from. (The coupling pushes phases without moving them on, so the phases
+// need nothing from it.)
+layout(local_size_x = 1) in;
+
+#include "SynthParams.glsl"
+
+layout(set = 1, binding = 0) buffer Voices { vec4 voices[]; };
+layout(set = 1, binding = 1) buffer Phases { vec4 phases[]; };
+
+const float TAU = 6.28318530718;
+
+void main() {
+ float count = float(u.count);
+ for (int i = 0; i < 3; i++) {
+ vec4 from = voices[i];
+ vec4 to = voices[3 + i];
+ vec4 phase = phases[i];
+ float wc0 = TAU * from.x / u.rate;
+ float wc1 = TAU * to.x / u.rate;
+ // As synth.comp's glide at n = count.
+ float c = phase.x + 0.5 * (wc0 + wc1) * count;
+ float m = phase.y + 0.5 * (wc0 * from.y + wc1 * to.y) * count;
+ float fm = phase.z + (c - phase.x) + to.z / max(to.y, 1e-3) * (sin(m) - sin(phase.y));
+ phases[i] = vec4(mod(c, TAU), mod(m, TAU), mod(fm, TAU), 0.0);
+ voices[i] = to;
+ voices[6 + i] = voices[9 + i];
+ }
+}
diff --git a/examples/spheres/shaders/fade.frag b/examples/spheres/shaders/fade.frag
new file mode 100644
index 0000000..71b02f2
--- /dev/null
+++ b/examples/spheres/shaders/fade.frag
@@ -0,0 +1,11 @@
+#version 450
+#extension GL_GOOGLE_include_directive : require
+// Blended over the sky (premultiplied), it moves every pixel `amount` of
+// the way to the background: what was drawn before fades, a long exposure.
+layout(location = 0) out vec4 out_color;
+
+#include "Fade.glsl"
+
+void main() {
+ out_color = vec4(u.background * u.amount, u.amount);
+}
diff --git a/examples/spheres/shaders/fullscreen.vert b/examples/spheres/shaders/fullscreen.vert
new file mode 100644
index 0000000..f45ee09
--- /dev/null
+++ b/examples/spheres/shaders/fullscreen.vert
@@ -0,0 +1,6 @@
+#version 450
+// One triangle covering the target.
+void main() {
+ vec2 p = vec2(float((gl_VertexIndex << 1) & 2), float(gl_VertexIndex & 2));
+ gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0);
+}
diff --git a/examples/spheres/shaders/link.frag b/examples/spheres/shaders/link.frag
new file mode 100644
index 0000000..53da3cf
--- /dev/null
+++ b/examples/spheres/shaders/link.frag
@@ -0,0 +1,12 @@
+#version 450
+// Pulses running from the modulator to the carrier, soft at the edges.
+layout(location = 0) in vec4 color;
+layout(location = 1) in vec2 along;
+layout(location = 2) flat in float time;
+layout(location = 0) out vec4 out_color;
+
+void main() {
+ float pulse = 0.5 + 0.5 * sin(along.x * 0.25 - time * 9.0);
+ float edge = 1.0 - along.y * along.y;
+ out_color = color * edge * (0.3 + 0.7 * pulse * pulse);
+}
diff --git a/examples/spheres/shaders/link.vert b/examples/spheres/shaders/link.vert
new file mode 100644
index 0000000..d4582e4
--- /dev/null
+++ b/examples/spheres/shaders/link.vert
@@ -0,0 +1,47 @@
+#version 450
+#extension GL_GOOGLE_include_directive : require
+// The FM pair, drawn: from the modulating body to its carrier, a ribbon
+// as wide and bright as the index is high, shading from the
+// modulator's colour to the carrier's. Six vertices for each of the six
+// ordered pairs; uncoupled pairs collapse to nothing.
+layout(location = 0) out vec4 color;
+layout(location = 1) out vec2 along;
+layout(location = 2) flat out float time;
+
+#include "SkyView.glsl"
+
+layout(set = 0, binding = 0) readonly buffer Bodies { vec4 bodies[]; };
+// layouts.voices_*: coupling rows now at 9..11.
+layout(set = 0, binding = 1) readonly buffer Voices { vec4 voices[]; };
+
+// Match main.zig's palette.
+const vec3 palette[3] = vec3[](vec3(0.40, 0.85, 1.0), vec3(1.0, 0.45, 0.82), vec3(1.0, 0.80, 0.35));
+// Pairs (carrier, modulator).
+const ivec2 pairs[6] = ivec2[](ivec2(0, 1), ivec2(0, 2), ivec2(1, 0), ivec2(1, 2), ivec2(2, 0), ivec2(2, 1));
+
+void main() {
+ ivec2 pair = pairs[uint(gl_VertexIndex) / 6u];
+ uint corner = uint(gl_VertexIndex) % 6u;
+ float amount = voices[9 + pair.x][pair.y];
+ time = u.time;
+ if (amount < 0.02) {
+ gl_Position = vec4(0.0, 0.0, 2.0, 1.0);
+ color = vec4(0.0);
+ along = vec2(0.0);
+ return;
+ }
+ // Corners 0, 3, 5 at the modulator, 1, 2, 4 at the carrier; 0, 1, 3 on
+ // one side.
+ bool far_end = corner == 1u || corner == 2u || corner == 4u;
+ bool side = corner == 2u || corner == 4u || corner == 5u;
+ vec2 from = (bodies[pair.y].xy - u.center) / u.per_pixel;
+ vec2 to = (bodies[pair.x].xy - u.center) / u.per_pixel;
+ vec2 d = to - from;
+ float len = max(length(d), 1e-3);
+ vec2 normal = vec2(-d.y, d.x) / len;
+ float width = u.radius * (0.4 + min(amount, 1.6));
+ vec2 at = (far_end ? to : from) + normal * (side ? width : -width);
+ gl_Position = vec4(at * 2.0 / u.size, 0.0, 1.0);
+ along = vec2(far_end ? len : 0.0, side ? 1.0 : -1.0);
+ color = vec4(mix(palette[pair.y], palette[pair.x], far_end ? 1.0 : 0.0), 1.0) * u.alpha * clamp(amount, 0.0, 1.0);
+}
diff --git a/examples/spheres/shaders/lookahead.comp b/examples/spheres/shaders/lookahead.comp
new file mode 100644
index 0000000..75902d7
--- /dev/null
+++ b/examples/spheres/shaders/lookahead.comp
@@ -0,0 +1,52 @@
+#version 450
+#extension GL_GOOGLE_include_directive : require
+// Futures of system 0, one per thread, for spheres as an instrument: from
+// the preset's start, alternative 0 exactly as system 0 began and the
+// others nudged by growing amounts, so where the system is chaotic their
+// futures fan out. Each is integrated ahead `count` samples a frame (with
+// physics.glsl, as the live system is), leaving a snapshot every
+// `sample_dt` and the chord its bodies would sing there (voices.glsl). A
+// chord chosen then finds the nearest time it plays, in any of them.
+layout(local_size_x = 32) in;
+
+#include "LookParams.glsl"
+#include "physics.glsl"
+#include "voices.glsl"
+
+// Where each alternative has got to: 3 vec4s each (position xy, velocity zw).
+layout(set = 1, binding = 0) buffer State { vec4 state[]; };
+// Snapshots, sample-major: sample t of alternative a at 3 (t * K + a).
+layout(set = 1, binding = 1) buffer Snapshots { vec4 snapshots[]; };
+// Chords, sample-major: t * K + a.
+layout(set = 1, binding = 2) buffer Chords { uint chords[]; };
+
+// Match main.zig's leapfrog step.
+const float BASE_STEP = 0.004;
+
+void main() {
+ uint alt = gl_GlobalInvocationID.x;
+ if (alt >= u.alternatives) return;
+ vec3 m = u.masses.xyz;
+ vec2 p[3];
+ vec2 v[3];
+ for (int i = 0; i < 3; i++) {
+ vec4 b = state[3u * alt + uint(i)];
+ p[i] = b.xy;
+ v[i] = b.zw;
+ }
+ vec2 a[3];
+ accelerations(p, m, u.softening, a);
+ Mapping map = Mapping(u.base, u.speed_ref, u.depth_scale, u.couple_scale, u.quantize);
+ uint steps = uint(ceil(u.sample_dt / BASE_STEP));
+ float dt = u.sample_dt / float(steps);
+ for (uint t = u.first; t < min(u.first + u.count, u.horizon); t++) {
+ uint at = t * u.alternatives + alt;
+ for (int i = 0; i < 3; i++) snapshots[3u * at + uint(i)] = vec4(p[i], v[i]);
+ vec4 sung[3];
+ vec4 coupled[3];
+ sing(p, v, map, sung, coupled);
+ chords[at] = chordOf(sung) | voicing(sung, coupled);
+ for (uint k = 0u; k < steps; k++) leapfrog(p, v, a, dt, m, u.softening, 256.0);
+ }
+ for (int i = 0; i < 3; i++) state[3u * alt + uint(i)] = vec4(p[i], v[i]);
+}
diff --git a/examples/spheres/shaders/physics.glsl b/examples/spheres/shaders/physics.glsl
new file mode 100644
index 0000000..5d74bee
--- /dev/null
+++ b/examples/spheres/shaders/physics.glsl
@@ -0,0 +1,36 @@
+// The three-body physics, shared by sim.comp and lookahead.comp so the live
+// system and its futures move alike: gravity with softening, and leapfrog
+// (kick, drift, kick), symplectic and time-reversible, split finer through
+// close passes, about 2 % of the local dynamical time a part: too coarse
+// and a close pass gains energy and flings a body out.
+
+void accelerations(vec2 p[3], vec3 m, float softening, out vec2 a[3]) {
+ float eps2 = softening * softening;
+ a[0] = vec2(0.0);
+ a[1] = vec2(0.0);
+ a[2] = vec2(0.0);
+ for (int i = 0; i < 3; i++) {
+ for (int j = i + 1; j < 3; j++) {
+ vec2 d = p[j] - p[i];
+ float inv = inversesqrt(dot(d, d) + eps2);
+ vec2 f = d * (inv * inv * inv);
+ a[i] += m[j] * f;
+ a[j] -= m[i] * f;
+ }
+ }
+}
+
+// One step of `dt`, in up to `most` parts; `a` holds the accelerations at
+// `p`, before and after.
+void leapfrog(inout vec2 p[3], inout vec2 v[3], inout vec2 a[3], float dt, vec3 m, float softening, float most) {
+ float near = min(min(distance(p[0], p[1]), distance(p[0], p[2])), distance(p[1], p[2])) + softening;
+ float local = sqrt(near * near * near / (m.x + m.y + m.z));
+ uint k = uint(clamp(ceil(abs(dt) / (0.02 * local)), 1.0, most));
+ float h = dt / float(k);
+ for (uint j = 0u; j < k; j++) {
+ for (int i = 0; i < 3; i++) v[i] += 0.5 * h * a[i];
+ for (int i = 0; i < 3; i++) p[i] += h * v[i];
+ accelerations(p, m, softening, a);
+ for (int i = 0; i < 3; i++) v[i] += 0.5 * h * a[i];
+ }
+}
diff --git a/examples/spheres/shaders/rechord.comp b/examples/spheres/shaders/rechord.comp
new file mode 100644
index 0000000..6119120
--- /dev/null
+++ b/examples/spheres/shaders/rechord.comp
@@ -0,0 +1,27 @@
+#version 450
+#extension GL_GOOGLE_include_directive : require
+// The look-ahead's chords again, for another scale setting: one thread per
+// snapshot, the first `count` of them.
+layout(local_size_x = 64) in;
+
+#include "LookParams.glsl"
+#include "voices.glsl"
+
+layout(set = 0, binding = 0) readonly buffer Snapshots { vec4 snapshots[]; };
+layout(set = 1, binding = 0) buffer Chords { uint chords[]; };
+
+void main() {
+ uint at = gl_GlobalInvocationID.x;
+ if (at >= u.count) return;
+ vec2 p[3];
+ vec2 v[3];
+ for (int i = 0; i < 3; i++) {
+ vec4 b = snapshots[3u * at + uint(i)];
+ p[i] = b.xy;
+ v[i] = b.zw;
+ }
+ vec4 sung[3];
+ vec4 coupled[3];
+ sing(p, v, Mapping(u.base, u.speed_ref, u.depth_scale, u.couple_scale, u.quantize), sung, coupled);
+ chords[at] = chordOf(sung) | voicing(sung, coupled);
+}
diff --git a/examples/spheres/shaders/sim.comp b/examples/spheres/shaders/sim.comp
new file mode 100644
index 0000000..4a79ce1
--- /dev/null
+++ b/examples/spheres/shaders/sim.comp
@@ -0,0 +1,86 @@
+#version 450
+#extension GL_GOOGLE_include_directive : require
+// The three-body problem, one system per thread: every copy of the system
+// at once, each a hair apart from system 0, so the cloud they make shows
+// how far apart chaos takes them (a stable orbit keeps it a thin line).
+// The physics and the voices are physics.glsl's and voices.glsl's, which
+// the look-ahead shares.
+//
+// System 0 also leaves its trail, reports its state, and sings: from its
+// own motion, or, while a chord is held, from the look-ahead's snapshot
+// that sings it. It can also adopt a snapshot, stepping into that future.
+layout(local_size_x = 64) in;
+
+#include "SimParams.glsl"
+#include "physics.glsl"
+#include "voices.glsl"
+
+// The look-ahead's snapshots: 3 vec4s each (position xy, velocity zw).
+layout(set = 0, binding = 0) readonly buffer Ahead { vec4 ahead[]; };
+// Position xy, velocity zw: system s's bodies are 3s, 3s + 1, 3s + 2.
+layout(set = 1, binding = 0) buffer Bodies { vec4 bodies[]; };
+// System 0's positions: body b's ring at b * TRAIL.
+layout(set = 1, binding = 1) buffer Trail { vec2 trail[]; };
+// layouts.voices_*: voices 0..2 as the synthesiser last used them, 3..5
+// now; coupling rows 6..8 last used, 9..11 now.
+layout(set = 1, binding = 2) buffer Voices { vec4 voices[]; };
+// layouts.Lead: bodies 0..2, voices 3..5, coupling 6..8, (energy, time) 9.
+layout(set = 1, binding = 3) buffer Lead { vec4 lead[]; };
+
+// Match layouts.zig.
+const uint TRAIL = 1024;
+
+void main() {
+ uint s = gl_GlobalInvocationID.x;
+ if (s >= u.systems) return;
+ vec3 m = u.masses.xyz;
+ vec2 p[3];
+ vec2 v[3];
+ for (int i = 0; i < 3; i++) {
+ vec4 b = s == 0u && u.adopt != 0u ? ahead[3u * (u.adopt - 1u) + uint(i)] : bodies[3u * s + uint(i)];
+ p[i] = b.xy;
+ v[i] = b.zw;
+ }
+ vec2 a[3];
+ accelerations(p, m, u.softening, a);
+ // System 0 leaves trail points as it goes, by simulated time, so a fast
+ // travel draws as smooth a path as running does.
+ uint written = 0u;
+ for (uint step = 0u; step < u.steps; step++) {
+ leapfrog(p, v, a, u.dt, m, u.softening, 512.0);
+ if (s == 0u && written < u.trail_points && step + 1u >= u.trail_first && (step + 1u - u.trail_first) % u.trail_every == 0u) {
+ for (int i = 0; i < 3; i++) trail[uint(i) * TRAIL + (u.trail_head + written) % TRAIL] = p[i];
+ written++;
+ }
+ }
+ for (int i = 0; i < 3; i++) bodies[3u * s + uint(i)] = vec4(p[i], v[i]);
+ if (s != 0u) return;
+
+ float kinetic = 0.0;
+ float potential = 0.0;
+ for (int i = 0; i < 3; i++) {
+ kinetic += 0.5 * m[i] * dot(v[i], v[i]);
+ for (int j = i + 1; j < 3; j++) potential -= m[i] * m[j] * inversesqrt(dot(p[j] - p[i], p[j] - p[i]) + u.softening * u.softening);
+ lead[i] = vec4(p[i], v[i]);
+ }
+
+ vec2 sp[3];
+ vec2 sv[3];
+ for (int i = 0; i < 3; i++) {
+ vec4 b = u.voice_source != 0u ? ahead[3u * (u.voice_source - 1u) + uint(i)] : vec4(p[i], v[i]);
+ sp[i] = b.xy;
+ sv[i] = b.zw;
+ }
+ vec4 sung[3];
+ vec4 coupled[3];
+ sing(sp, sv, Mapping(u.base, u.speed_ref, u.depth_scale, u.couple_scale, u.quantize), sung, coupled);
+ for (int i = 0; i < 3; i++) {
+ voices[3 + i] = sung[i];
+ lead[3 + i] = sung[i];
+ // A quarter of the way each frame: pairs hand over smoothly.
+ vec4 row = mix(voices[9 + i], coupled[i], 0.25);
+ voices[9 + i] = row;
+ lead[6 + i] = row;
+ }
+ lead[9] = vec4(kinetic + potential, lead[9].y + float(u.steps) * u.dt, 0.0, 0.0);
+}
diff --git a/examples/spheres/shaders/sprite.frag b/examples/spheres/shaders/sprite.frag
new file mode 100644
index 0000000..d39e7e4
--- /dev/null
+++ b/examples/spheres/shaders/sprite.frag
@@ -0,0 +1,11 @@
+#version 450
+// A Gaussian glow, premultiplied, for additive blending.
+layout(location = 0) in vec2 corner;
+layout(location = 1) in vec4 color;
+layout(location = 0) out vec4 out_color;
+
+void main() {
+ float r2 = dot(corner, corner);
+ float glow = exp(-5.0 * r2) * (1.0 - smoothstep(0.8, 1.0, r2));
+ out_color = color * glow;
+}
diff --git a/examples/spheres/shaders/sprite.vert b/examples/spheres/shaders/sprite.vert
new file mode 100644
index 0000000..13e1c73
--- /dev/null
+++ b/examples/spheres/shaders/sprite.vert
@@ -0,0 +1,23 @@
+#version 450
+#extension GL_GOOGLE_include_directive : require
+// A soft disc per body: of every system from `first` for `count` systems,
+// at `radius` pixels, coloured by body. Six vertices make each quad.
+layout(location = 0) out vec2 corner;
+layout(location = 1) out vec4 color;
+
+#include "SkyView.glsl"
+
+layout(set = 0, binding = 0) readonly buffer Bodies { vec4 bodies[]; };
+
+const vec2 corners[6] = vec2[](vec2(-1, -1), vec2(1, -1), vec2(1, 1), vec2(-1, -1), vec2(1, 1), vec2(-1, 1));
+// Match main.zig's palette.
+const vec3 palette[3] = vec3[](vec3(0.40, 0.85, 1.0), vec3(1.0, 0.45, 0.82), vec3(1.0, 0.80, 0.35));
+
+void main() {
+ uint sprite = uint(gl_VertexIndex) / 6u;
+ uint index = 3u * u.first + sprite;
+ vec2 at = (bodies[index].xy - u.center) / u.per_pixel + corners[uint(gl_VertexIndex) % 6u] * u.radius;
+ gl_Position = vec4(at * 2.0 / u.size, 0.0, 1.0);
+ corner = corners[uint(gl_VertexIndex) % 6u];
+ color = vec4(palette[index % 3u], 1.0) * u.alpha;
+}
diff --git a/examples/spheres/shaders/synth.comp b/examples/spheres/shaders/synth.comp
new file mode 100644
index 0000000..3a6c40c
--- /dev/null
+++ b/examples/spheres/shaders/synth.comp
@@ -0,0 +1,112 @@
+#version 450
+#extension GL_GOOGLE_include_directive : require
+// One audio block, one thread per sample: three voices from the bodies'
+// parameters, gliding from what the last block ended on to what sim.comp
+// set now, so blocks join without clicks.
+//
+// Each phase has a closed form, so every sample is computed alone: a
+// frequency gliding linearly from w0 to w1 (radians per sample) over N
+// samples has phase p0 + w0 n + (w1 - w0) n^2 / 2N after n of them.
+//
+// The modes, with carrier phase c, modulator phase m (at ratio times the
+// carrier's frequency) and depth d:
+// sine sin c
+// additive sum over harmonics k of r^(k-1) sin kc, r = d / (d + 2),
+// those under Nyquist, normalised
+// AM sin c (1 + a sin m) / (1 + a), a = min(d / 4, 1)
+// ring sin c sin m
+// FM sin of the integral of the carrier's frequency, pushed
+// d times the carrier's frequency either way by cos m: so the
+// index, deviation over modulator frequency, is d / ratio and
+// changes as the modulator does
+// PM sin(c + d sin m): the index is d, whatever the modulator
+// FM and PM sound alike for a steady modulator, and part when it moves.
+//
+// The closest pair (sim.comp) is one FM voice: the modulating body is
+// silent, and a sine at its frequency, times the index, pushes the other
+// body's carrier phase. Two operators, both moved by the bodies. The push
+// moves every harmonic of the additive voice alike, so its timbre bends
+// without turning harsh.
+layout(local_size_x = 64) in;
+
+#include "SynthParams.glsl"
+
+layout(set = 0, binding = 0) readonly buffer Voices { vec4 voices[]; };
+// Per voice: carrier phase, modulator phase, FM's phase.
+layout(set = 0, binding = 1) readonly buffer Phases { vec4 phases[]; };
+layout(set = 1, binding = 0) buffer Block { float block[]; };
+
+const float TAU = 6.28318530718;
+// Match layouts.Mode.
+const uint SINE = 0u;
+const uint ADDITIVE = 1u;
+const uint AM = 2u;
+const uint RING = 3u;
+const uint FM = 4u;
+
+float glide(float phase, float w0, float w1, float n, float count) {
+ return phase + w0 * n + (w1 - w0) * n * n / (2.0 * count);
+}
+
+// Voice i's signal, its carrier phase pushed by `push` radians.
+float voice(int i, float n, float count, float push) {
+ vec4 from = voices[i];
+ vec4 to = voices[3 + i];
+ vec4 phase = phases[i];
+ float t = n / count;
+ float wc0 = TAU * from.x / u.rate;
+ float wc1 = TAU * to.x / u.rate;
+ float c = glide(phase.x, wc0, wc1, n, count);
+ float m = glide(phase.y, wc0 * from.y, wc1 * to.y, n, count);
+ float depth = mix(from.z, to.z, t);
+ float ratio = mix(from.y, to.y, t);
+ float y;
+ if (u.mode == SINE) {
+ y = sin(c + push);
+ } else if (u.mode == ADDITIVE) {
+ float r = depth / (depth + 2.0);
+ float carrier = mix(from.x, to.x, t);
+ float sum = 0.0;
+ float norm = 0.0;
+ float weight = 1.0;
+ for (int k = 1; k <= 16; k++) {
+ if (float(k) * carrier >= 0.5 * u.rate) break;
+ sum += weight * sin(float(k) * c + push);
+ norm += weight;
+ weight *= r;
+ }
+ y = sum / max(norm, 1e-6);
+ } else if (u.mode == AM) {
+ float a = min(depth / 4.0, 1.0);
+ y = sin(c + push) * (1.0 + a * sin(m)) / (1.0 + a);
+ } else if (u.mode == RING) {
+ y = sin(c + push) * sin(m);
+ } else if (u.mode == FM) {
+ y = sin(phase.z + push + (c - phase.x) + depth / max(ratio, 1e-3) * (sin(m) - sin(phase.y)));
+ } else {
+ y = sin(c + push + depth * sin(m));
+ }
+ return y;
+}
+
+void main() {
+ uint n = gl_GlobalInvocationID.x;
+ if (n >= u.count) return;
+ float count = float(u.count);
+ float t = float(n) / count;
+ // Each body as a modulator: a sine at its carrier frequency.
+ vec3 sines;
+ for (int i = 0; i < 3; i++) {
+ float w0 = TAU * voices[i].x / u.rate;
+ float w1 = TAU * voices[3 + i].x / u.rate;
+ sines[i] = sin(glide(phases[i].x, w0, w1, float(n), count));
+ }
+ float sum = 0.0;
+ for (int i = 0; i < 3; i++) {
+ vec4 row = mix(voices[6 + i], voices[9 + i], t);
+ float audible = (1.0 - row.w) * mix(voices[i].w, voices[3 + i].w, t);
+ if (audible < 1e-4) continue;
+ sum += audible * voice(i, float(n), count, dot(row.xyz, sines));
+ }
+ block[n] = tanh(u.gain * sum);
+}
diff --git a/examples/spheres/shaders/trail.frag b/examples/spheres/shaders/trail.frag
new file mode 100644
index 0000000..8a82628
--- /dev/null
+++ b/examples/spheres/shaders/trail.frag
@@ -0,0 +1,7 @@
+#version 450
+layout(location = 0) in vec4 color;
+layout(location = 0) out vec4 out_color;
+
+void main() {
+ out_color = color;
+}
diff --git a/examples/spheres/shaders/trail.vert b/examples/spheres/shaders/trail.vert
new file mode 100644
index 0000000..7f9f35c
--- /dev/null
+++ b/examples/spheres/shaders/trail.vert
@@ -0,0 +1,48 @@
+#version 450
+#extension GL_GOOGLE_include_directive : require
+// System 0's trails: per body, a ribbon through its last positions,
+// `radius` pixels wide at the newest and tapering to nothing at the oldest,
+// fading as it goes. Six vertices per segment; segments past what has been
+// filled, or across a jump, collapse to nothing.
+layout(location = 0) out vec4 color;
+
+#include "SkyView.glsl"
+
+layout(set = 0, binding = 0) readonly buffer Trail { vec2 trail[]; };
+
+// Match layouts.zig and main.zig's palette.
+const uint TRAIL = 1024u;
+const vec3 palette[3] = vec3[](vec3(0.40, 0.85, 1.0), vec3(1.0, 0.45, 0.82), vec3(1.0, 0.80, 0.35));
+
+void main() {
+ uint segment = uint(gl_VertexIndex) / 6u;
+ uint corner = uint(gl_VertexIndex) % 6u;
+ uint body = segment / (TRAIL - 1u);
+ uint age = segment % (TRAIL - 1u);
+ if (age + 1u >= u.filled) {
+ gl_Position = vec4(0.0, 0.0, 2.0, 1.0);
+ color = vec4(0.0);
+ return;
+ }
+ // Corners 0, 3, 5 at the newer end, 1, 2, 4 at the older; 0, 1, 3 on
+ // one side, 2, 4, 5 on the other.
+ bool older = corner == 1u || corner == 2u || corner == 4u;
+ bool side = corner == 2u || corner == 4u || corner == 5u;
+ uint a = (u.head + TRAIL - age) % TRAIL;
+ uint b = (u.head + TRAIL - age - 1u) % TRAIL;
+ // A jump (system 0 stepping into a snapshot) breaks the trail.
+ if (distance(trail[body * TRAIL + a], trail[body * TRAIL + b]) > u.gap) {
+ gl_Position = vec4(0.0, 0.0, 2.0, 1.0);
+ color = vec4(0.0);
+ return;
+ }
+ vec2 pa = (trail[body * TRAIL + a] - u.center) / u.per_pixel;
+ vec2 pb = (trail[body * TRAIL + b] - u.center) / u.per_pixel;
+ vec2 along = pb - pa;
+ float len = length(along);
+ vec2 normal = len > 1e-4 ? vec2(-along.y, along.x) / len : vec2(0.0, 1.0);
+ float fade = 1.0 - float(older ? age + 1u : age) / float(u.filled);
+ vec2 at = (older ? pb : pa) + normal * (side ? 1.0 : -1.0) * u.radius * fade;
+ gl_Position = vec4(at * 2.0 / u.size, 0.0, 1.0);
+ color = vec4(palette[body], 1.0) * u.alpha * fade * fade;
+}
diff --git a/examples/spheres/shaders/voices.glsl b/examples/spheres/shaders/voices.glsl
new file mode 100644
index 0000000..c2fd56c
--- /dev/null
+++ b/examples/spheres/shaders/voices.glsl
@@ -0,0 +1,101 @@
+// From motion to sound, shared by sim.comp (what sounds) and lookahead.comp
+// (what would): each body a voice whose pitch follows its speed, whose
+// modulator ratio follows how lopsided its two distances are, and whose
+// depth follows how near its nearest neighbour is; and the closest pair one
+// FM voice, the faster body silent, modulating the other.
+
+struct Mapping {
+ float base;
+ float speed_ref;
+ float depth_scale;
+ float couple_scale;
+ // Match layouts.Scale: free, pentatonic, diatonic, chromatic.
+ uint scale;
+};
+
+// The nearest note of the scale, as a MIDI number: A minor pentatonic (A C
+// D E G), A minor / C major (the white keys), every semitone, or none.
+float snap(float midi, uint scale) {
+ if (scale == 0u) return midi;
+ if (scale == 3u) return round(midi);
+ float m = midi - 69.0;
+ float octave = floor(m / 12.0);
+ float degree = m - 12.0 * octave;
+ const float pentatonic[6] = float[](0.0, 3.0, 5.0, 7.0, 10.0, 12.0);
+ const float diatonic[8] = float[](0.0, 2.0, 3.0, 5.0, 7.0, 8.0, 10.0, 12.0);
+ float best = 0.0;
+ if (scale == 1u) {
+ for (int i = 1; i < 6; i++) if (abs(pentatonic[i] - degree) < abs(best - degree)) best = pentatonic[i];
+ } else {
+ for (int i = 1; i < 8; i++) if (abs(diatonic[i] - degree) < abs(best - degree)) best = diatonic[i];
+ }
+ return 69.0 + 12.0 * octave + best;
+}
+
+// Voices: (carrier Hz, ratio, depth, amplitude). Coupling rows: xyz the FM
+// index each voice gets from each other, w whether it is the silent
+// modulator.
+void sing(vec2 p[3], vec2 v[3], Mapping map, out vec4 voices[3], out vec4 coupling[3]) {
+ for (int i = 0; i < 3; i++) {
+ float speed = length(v[i]);
+ float octaves = clamp(log2(max(speed, 1e-4) / map.speed_ref), -2.0, 2.5);
+ float midi = 12.0 * log2(map.base / 440.0) + 69.0 + 12.0 * octaves;
+ midi = snap(midi, map.scale);
+ float d1 = distance(p[i], p[(i + 1) % 3]);
+ float d2 = distance(p[i], p[(i + 2) % 3]);
+ float near = min(d1, d2);
+ float far = max(d1, d2);
+ voices[i] = vec4(
+ 440.0 * exp2((midi - 69.0) / 12.0),
+ 0.5 + 4.0 * near / max(near + far, 1e-6),
+ clamp(map.depth_scale / max(near, 1e-3), 0.0, 12.0),
+ 0.2 + 0.15 * clamp(speed / (2.0 * map.speed_ref), 0.0, 1.0));
+ coupling[i] = vec4(0.0);
+ }
+ int first = 0;
+ int second = 1;
+ float closest = distance(p[0], p[1]);
+ if (distance(p[0], p[2]) < closest) { first = 0; second = 2; closest = distance(p[0], p[2]); }
+ if (distance(p[1], p[2]) < closest) { first = 1; second = 2; closest = distance(p[1], p[2]); }
+ int modulator = length(v[first]) > length(v[second]) ? first : second;
+ int carrier = modulator == first ? second : first;
+ coupling[carrier][modulator] = clamp(map.couple_scale / max(closest, 1e-3), 0.0, 4.0);
+ coupling[modulator].w = 1.0;
+}
+
+// The chord with its voicing, packed: bits 0-11 the pitch classes (the
+// chord), bit 12 set if it is playable, bits 16-19 the lowest note's pitch
+// class (for root position), bits 24-31 how bad it sounds, 0 to 255.
+// Playable: every note from E2 to A5, an octave and a fifth at most from
+// lowest to highest, and the FM pair's index at most 3; past those, the
+// same pitch classes are another sound, shrill, sprawling or a cloud of
+// sidebands. Within them, wider, higher and harder modulated cost more.
+uint voicing(vec4 voices[3], vec4 coupling[3]) {
+ int low = 1000;
+ int high = -1000;
+ int lowest_class = 0;
+ for (int i = 0; i < 3; i++) {
+ int midi = int(round(69.0 + 12.0 * log2(voices[i].x / 440.0)));
+ if (midi < low) {
+ low = midi;
+ lowest_class = ((midi % 12) + 12) % 12;
+ }
+ high = max(high, midi);
+ }
+ float index = 0.0;
+ for (int i = 0; i < 3; i++) index = max(index, max(coupling[i].x, max(coupling[i].y, coupling[i].z)));
+ int spread = high - low;
+ bool playable = low >= 40 && high <= 81 && spread <= 19 && index <= 3.0;
+ float bad = 6.0 * float(max(spread - 12, 0)) + 10.0 * float(max(high - 76, 0)) + 15.0 * index;
+ return (playable ? 1u << 12 : 0u) | (uint(lowest_class) << 16) | (uint(clamp(bad, 0.0, 255.0)) << 24);
+}
+
+// The pitch classes the three voices sing, as bits (C is bit 0): the chord.
+uint chordOf(vec4 voices[3]) {
+ uint mask = 0u;
+ for (int i = 0; i < 3; i++) {
+ int midi = int(round(69.0 + 12.0 * log2(voices[i].x / 440.0)));
+ mask |= 1u << uint(((midi % 12) + 12) % 12);
+ }
+ return mask;
+}
diff --git a/examples/spheres/src/chords.zig b/examples/spheres/src/chords.zig
new file mode 100644
index 0000000..54a4413
--- /dev/null
+++ b/examples/spheres/src/chords.zig
@@ -0,0 +1,311 @@
+//! spheres as an instrument: the CPU's side of the look-ahead. The GPU
+//! (lookahead.comp) integrates `alternatives` futures of system 0 from the
+//! preset's start, a few samples a frame, keeping a snapshot every
+//! `sample_dt` and the chord sung there: the pitch classes of the three
+//! voices (the silent modulator's counts: it sets the carrier's sidebands).
+//! The chords come back here, a frame or two later; the ones that fit the
+//! grid of buttons (a sanfona's bass side, see `Grid`) light up as found,
+//! and choosing one finds the nearest time it plays, in whichever future
+//! plays it soonest.
+const std = @import("std");
+const layouts = @import("layouts");
+
+/// The mapping from motion to voices (voices.glsl), which the shaders get
+/// as uniforms; and leapfrog's base step, as physics.glsl's callers use it.
+pub const base: f32 = 220;
+pub const speed_ref: f32 = 0.6;
+pub const depth_scale: f32 = 1.2;
+pub const couple_scale: f32 = 0.9;
+pub const base_step = 0.004;
+
+/// Futures integrated side by side: 0 is system 0's own, the rest nudged.
+pub const alternatives = layouts.alternatives;
+pub const horizon = layouts.horizon;
+pub const sample_dt = 0.05;
+/// Samples the look-ahead advances each frame: 0.4 s of simulated time,
+/// against the live system's 0.7 s a second, so it pulls well ahead.
+pub const per_frame = 8;
+/// What a pick costs besides its travel time, in seconds of travel: being
+/// in another future than the system's own; not having the root in the
+/// bass; and per unit of voicing badness (voices.glsl's 0 to 255: a
+/// sprawling, high or hard-modulated voicing costs up to 3 s more).
+const elsewhere = 0.5;
+const inverted = 0.6;
+const per_bad = 3.0 / 255.0;
+
+/// A snapshot's chord and voicing, as voices.glsl's `voicing` packs them.
+pub const Sung = packed struct(u32) {
+ chord: u12,
+ playable: bool,
+ _: u3,
+ lowest: u4,
+ _2: u4,
+ bad: u8,
+};
+
+/// The pitch classes three voices sing, as bits (C is bit 0): as
+/// voices.glsl's chordOf, for what is sounding.
+pub fn chordOf(voices: [3]layouts.Voice) u16 {
+ var mask: u16 = 0;
+ for (voices) |v| {
+ if (v.carrier <= 0) continue;
+ const midi: i32 = @intFromFloat(@round(69 + 12 * std.math.log2(v.carrier / 440)));
+ mask |= @as(u16, 1) << @intCast(@mod(midi, 12));
+ }
+ return mask;
+}
+
+const names = [12][]const u8{ "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
+
+fn bits(intervals: []const u4) u16 {
+ var m: u16 = 0;
+ for (intervals) |i| m |= @as(u16, 1) << i;
+ return m;
+}
+
+/// Chord shapes, most wanted first, as intervals over the root.
+const shapes = [_]struct { u16, []const u8 }{
+ .{ bits(&.{ 0, 4, 7 }), "" },
+ .{ bits(&.{ 0, 3, 7 }), "m" },
+ .{ bits(&.{ 0, 2, 7 }), "sus2" },
+ .{ bits(&.{ 0, 5, 7 }), "sus4" },
+ .{ bits(&.{ 0, 4, 10 }), "7" },
+ .{ bits(&.{ 0, 3, 10 }), "m7" },
+ .{ bits(&.{ 0, 4, 9 }), "6" },
+ .{ bits(&.{ 0, 3, 9 }), "m6" },
+ .{ bits(&.{ 0, 3, 6 }), "dim" },
+ .{ bits(&.{ 0, 4, 8 }), "aug" },
+ .{ bits(&.{ 0, 2, 4 }), "add9" },
+ .{ bits(&.{ 0, 5, 10 }), "7sus4" },
+ .{ bits(&.{ 0, 7, 10 }), "7no3" },
+ .{ bits(&.{ 0, 7 }), "5" },
+};
+
+/// A name for a set of pitch classes: a chord where one fits ("Am",
+/// "Csus2"), else the notes ("A+C+D").
+pub fn name(buf: []u8, mask: u16) []const u8 {
+ if (mask == 0) return "";
+ if (@popCount(mask) == 1) return names[@ctz(mask)];
+ for (shapes) |shape| for (0..12) |root| {
+ if (mask & (@as(u16, 1) << @intCast(root)) == 0) continue;
+ const r: u4 = @intCast(root);
+ const rotated = ((mask >> r) | (mask << @intCast(12 - @as(u5, r)))) & 0xfff;
+ if (rotated == shape[0]) return std.fmt.bufPrint(buf, "{s}{s}", .{ names[root], shape[1] }) catch "?";
+ };
+ var w: std.Io.Writer = .fixed(buf);
+ var first = true;
+ for (0..12) |pc| if (mask & (@as(u16, 1) << @intCast(pc)) != 0) {
+ w.print("{s}{s}", .{ if (first) "" else "+", names[pc] }) catch break;
+ first = false;
+ };
+ return w.buffered();
+}
+
+/// A snapshot: sample `sample` of future `alternative`, at `index` in the
+/// GPU's snapshot buffer.
+pub const Pick = struct {
+ sample: u32,
+ alternative: u32,
+
+ pub fn index(p: Pick) u32 {
+ return p.sample * alternatives + p.alternative;
+ }
+ pub fn time(p: Pick) f64 {
+ return @as(f64, @floatFromInt(p.sample)) * sample_dt;
+ }
+};
+
+/// The buttons, laid out as a sanfona's (Stradella) bass side: columns
+/// round the circle of fifths, so neighbours are related chords, and rows
+/// by quality, each half a button over from the one above, so a progression
+/// is the same shape of hand in any key.
+pub const Grid = struct {
+ pub const Quality = enum { major, minor, seventh, sus, power };
+ pub const rows = @typeInfo(Quality).@"enum".field_names.len;
+ pub const columns = 12;
+ /// Roots by column, by fifths from G flat to B, as pitch classes.
+ pub const roots = [columns]u4{ 6, 1, 8, 3, 10, 5, 0, 7, 2, 9, 4, 11 };
+ pub const root_names = [columns][]const u8{ "Gb", "Db", "Ab", "Eb", "Bb", "F", "C", "G", "D", "A", "E", "B" };
+
+ /// Three voices make triads at most: the seventh without its fifth.
+ pub fn shape(q: Quality) u16 {
+ return switch (q) {
+ .major => bits(&.{ 0, 4, 7 }),
+ .minor => bits(&.{ 0, 3, 7 }),
+ .seventh => bits(&.{ 0, 4, 10 }),
+ .sus => bits(&.{ 0, 5, 7 }),
+ .power => bits(&.{ 0, 7 }),
+ };
+ }
+
+ pub fn suffix(q: Quality) []const u8 {
+ return switch (q) {
+ .major => "",
+ .minor => "m",
+ .seventh => "7",
+ .sus => "sus",
+ .power => "5",
+ };
+ }
+
+ /// The chord of the button at `row`, `column`.
+ pub fn chord(row: usize, column: usize) u16 {
+ const s = shape(@enumFromInt(row));
+ const r: u4 = roots[column];
+ return ((s << r) | (s >> @intCast(12 - @as(u5, r)))) & 0xfff;
+ }
+
+ /// The button playing `mask`, if one does.
+ pub fn find(mask: u16) ?struct { row: usize, column: usize } {
+ for (0..rows) |row| for (0..columns) |column| {
+ if (chord(row, column) == mask) return .{ .row = row, .column = column };
+ };
+ return null;
+ }
+};
+
+pub const Ahead = struct {
+ /// The chords back from the GPU, with their voicings, sample-major as
+ /// it keeps them.
+ sung: [horizon][alternatives]Sung = undefined,
+ /// Samples asked of the GPU, and how many have come back.
+ asked: u32 = 0,
+ known: u32 = 0,
+ /// Every chord found in a playable voicing, by mask, and how many.
+ found: [1 << 12]bool = @splat(false),
+ distinct: u32 = 0,
+
+ pub fn reset(a: *Ahead) void {
+ a.asked = 0;
+ a.known = 0;
+ a.forget();
+ }
+
+ /// The chords again from nothing (another scale).
+ pub fn forget(a: *Ahead) void {
+ a.known = 0;
+ a.found = @splat(false);
+ a.distinct = 0;
+ }
+
+ /// Chords back from the GPU: samples from `first`, all alternatives.
+ pub fn arrived(a: *Ahead, first: u32, words: []const u32) void {
+ const samples: u32 = @intCast(words.len / alternatives);
+ for (0..samples) |s| {
+ const t = first + @as(u32, @intCast(s));
+ if (t >= horizon) break;
+ for (0..alternatives) |alt| {
+ const sung: Sung = @bitCast(words[s * alternatives + alt]);
+ a.sung[t][alt] = sung;
+ if (sung.playable) a.pad(sung.chord);
+ }
+ a.known = @max(a.known, t + 1);
+ }
+ }
+
+ fn pad(a: *Ahead, chord: u16) void {
+ if (chord == 0 or a.found[chord]) return;
+ a.found[chord] = true;
+ a.distinct += 1;
+ }
+
+ /// The best snapshot where `chord` plays in a playable voicing: near
+ /// `time`, in the system's own future, with `root` in the bass, and
+ /// sounding well, weighed against each other (see the costs above).
+ pub fn nearest(a: *const Ahead, chord: u16, root: u4, time: f64) ?Pick {
+ var best: ?Pick = null;
+ var cost: f64 = std.math.inf(f64);
+ for (a.sung[0..a.known], 0..) |row, t| for (row, 0..) |sung, alt| {
+ if (sung.chord != chord or !sung.playable) continue;
+ const pick: Pick = .{ .sample = @intCast(t), .alternative = @intCast(alt) };
+ const c = @abs(pick.time() - time) +
+ @as(f64, if (alt == 0) 0 else elsewhere) +
+ @as(f64, if (sung.lowest == root) 0 else inverted) +
+ per_bad * @as(f64, @floatFromInt(sung.bad));
+ if (c < cost) {
+ cost = c;
+ best = pick;
+ }
+ };
+ return best;
+ }
+};
+
+test "chords by name" {
+ var buf: [32]u8 = undefined;
+ const set = struct {
+ fn of(pcs: []const u5) u16 {
+ var m: u16 = 0;
+ for (pcs) |p| m |= @as(u16, 1) << @intCast(p);
+ return m;
+ }
+ }.of;
+ try std.testing.expectEqualStrings("Am", name(&buf, set(&.{ 9, 0, 4 })));
+ try std.testing.expectEqualStrings("C", name(&buf, set(&.{ 0, 4, 7 })));
+ try std.testing.expectEqualStrings("Csus2", name(&buf, set(&.{ 0, 2, 7 })));
+ try std.testing.expectEqualStrings("A5", name(&buf, set(&.{ 9, 4 })));
+ try std.testing.expectEqualStrings("E", name(&buf, set(&.{4})));
+ try std.testing.expectEqualStrings("C#+D", name(&buf, set(&.{ 1, 2 })));
+}
+
+fn word(chord: u12, playable: bool, lowest: u4, bad: u8) u32 {
+ return @bitCast(Sung{ .chord = chord, .playable = playable, ._ = 0, .lowest = lowest, ._2 = 0, .bad = bad });
+}
+
+test "a pick prefers the system's own future, unless another plays the chord much sooner" {
+ var a: Ahead = .{};
+ var words: [3 * alternatives]u32 = @splat(word(1, true, 0, 0));
+ // Chord 2 at sample 2 of future 0, and at sample 0 of future 5.
+ words[2 * alternatives + 0] = word(2, true, 1, 0);
+ words[0 * alternatives + 5] = word(2, true, 1, 0);
+ a.arrived(0, &words);
+ try std.testing.expectEqual(@as(u32, 3), a.known);
+ try std.testing.expect(a.found[1] and a.found[2]);
+ try std.testing.expectEqual(@as(u32, 2), a.distinct);
+ // From time 0.1: future 0 at 0.1 away beats future 5 at 0.1 + 0.5.
+ try std.testing.expectEqual(Pick{ .sample = 2, .alternative = 0 }, a.nearest(2, 1, 0.1).?);
+ // Ask for a chord no future plays: nothing.
+ try std.testing.expectEqual(@as(?Pick, null), a.nearest(4, 2, 0));
+}
+
+test "voicings: unplayable ones do not count, good ones win over near ones" {
+ var a: Ahead = .{};
+ var words: [3 * alternatives]u32 = @splat(word(1, true, 0, 0));
+ // Chord 2 now, but shrill and sprawling (unplayable); later, playable
+ // but inverted and harsh; later still, in root position and clean.
+ words[0] = word(2, false, 1, 0);
+ words[1 * alternatives] = word(2, true, 3, 200);
+ words[2 * alternatives] = word(2, true, 1, 0);
+ a.arrived(0, &words);
+ try std.testing.expectEqual(Pick{ .sample = 2, .alternative = 0 }, a.nearest(2, 1, 0).?);
+ // A chord heard only unplayably is not found.
+ var b: Ahead = .{};
+ var only: [alternatives]u32 = @splat(word(4, false, 2, 0));
+ b.arrived(0, &only);
+ try std.testing.expect(!b.found[4]);
+}
+
+test "the grid: fifths across, qualities down" {
+ var buf: [16]u8 = undefined;
+ // Column 6 is C, column 9 is A.
+ try std.testing.expectEqualStrings("C", name(&buf, Grid.chord(0, 6)));
+ try std.testing.expectEqualStrings("Am", name(&buf, Grid.chord(1, 9)));
+ try std.testing.expectEqualStrings("G5", name(&buf, Grid.chord(4, 7)));
+ const at = Grid.find(Grid.chord(2, 3)).?;
+ try std.testing.expectEqual(@as(usize, 2), at.row);
+ try std.testing.expectEqual(@as(usize, 3), at.column);
+ // Every button its own chord.
+ for (0..Grid.rows) |r| for (0..Grid.columns) |c| {
+ try std.testing.expectEqual(r, Grid.find(Grid.chord(r, c)).?.row);
+ };
+}
+
+test "voices to chords" {
+ const v = [3]layouts.Voice{
+ .{ .carrier = 220, .ratio = 1, .depth = 0, .amp = 1 },
+ .{ .carrier = 261.63, .ratio = 1, .depth = 0, .amp = 1 },
+ .{ .carrier = 329.63, .ratio = 1, .depth = 0, .amp = 1 },
+ };
+ var buf: [16]u8 = undefined;
+ try std.testing.expectEqualStrings("Am", name(&buf, chordOf(v)));
+}
diff --git a/examples/spheres/src/layouts.zig b/examples/spheres/src/layouts.zig
new file mode 100644
index 0000000..c282e16
--- /dev/null
+++ b/examples/spheres/src/layouts.zig
@@ -0,0 +1,163 @@
+//! What spheres' shaders read and write, as Zig structs: the only
+//! definition. The shaders include GLSL generated from the uniform blocks;
+//! storage layouts (std430) are mirrored by hand where noted. No imports.
+
+/// Copies of the system integrated side by side: system 0 is the one heard
+/// and drawn in full, the rest start a hair apart and show where it could
+/// have gone.
+pub const max_systems = 16384;
+pub const bodies = 3;
+/// Positions kept per body for the trail.
+pub const trail = 1024;
+/// The most samples synthesised in one frame.
+pub const max_block = 8192;
+/// The look-ahead (lookahead.comp): futures of system 0 integrated side by
+/// side, and snapshots kept of each, one every `chords.sample_dt`.
+pub const alternatives = 32;
+pub const horizon = 2400;
+
+/// One body of one system (std430: vec4).
+pub const Body = extern struct {
+ pos: [2]f32,
+ vel: [2]f32,
+};
+
+/// One voice's synthesis parameters (std430: vec4).
+pub const Voice = extern struct {
+ /// Hz.
+ carrier: f32,
+ /// Modulator over carrier frequency.
+ ratio: f32,
+ /// The modulation depth: PM's index; FM's deviation over the carrier;
+ /// AM's and the additive voice's brightness.
+ depth: f32,
+ amp: f32,
+};
+
+/// The voices buffer, in vec4s: what the synthesiser last used and what
+/// sim.comp set now, for the voices and the coupling between them.
+pub const voices_previous = 0;
+pub const voices_now = 3;
+/// Row i of the coupling: how much each voice's signal (x, y, z) pushes
+/// voice i's carrier phase. Only the closest pair couples.
+pub const coupling_previous = 6;
+pub const coupling_now = 9;
+pub const voices_len = 12;
+
+/// What sim.comp reports of system 0, for the CPU (std430).
+pub const Lead = extern struct {
+ bodies: [3]Body,
+ voices: [3]Voice,
+ /// Rows of the coupling, as in the voices buffer (w unused).
+ coupling: [3][4]f32,
+ /// Kinetic plus potential.
+ energy: f32,
+ /// Simulated time.
+ time: f32,
+ pad: [2]f32 = .{ 0, 0 },
+};
+
+pub const Mode = enum(u32) { sine, additive, am, ring, fm, pm };
+
+/// Where pitches snap; voices.glsl's `snap`. The uniforms carry it as a u32.
+pub const Scale = enum(u32) { free, pentatonic, diatonic, chromatic };
+
+/// sim.comp: one thread per system.
+pub const SimParams = extern struct {
+ systems: u32,
+ /// Substeps this frame, each `dt` (negative runs time backwards),
+ /// subdivided further where bodies pass close.
+ steps: u32,
+ dt: f32,
+ softening: f32,
+ masses: [4]f32,
+ /// Where system 0's positions go in the trail ring; past `trail`, none.
+ trail_head: u32,
+ quantize: u32,
+ /// The pitch at `speed_ref`, Hz.
+ base: f32,
+ speed_ref: f32,
+ /// Modulation depth at unit distance.
+ depth_scale: f32,
+ /// How hard the closest pair couples at unit distance.
+ couple_scale: f32,
+ /// A look-ahead snapshot, as its index plus one, or 0: system 0 sings
+ /// from it (a held chord) rather than from its own motion.
+ voice_source: u32 = 0,
+ /// Likewise: system 0 takes the snapshot's state before moving on.
+ adopt: u32 = 0,
+ /// Trail points this frame, by simulated time rather than by frame, so
+ /// a fast travel leaves as smooth a path as running does: after step
+ /// `trail_first` (1-based), then every `trail_every` steps, `trail_points`
+ /// of them, from slot `trail_head` on.
+ trail_points: u32 = 0,
+ trail_first: u32 = 1,
+ trail_every: u32 = 1,
+ pad0: u32 = 0,
+
+ pub const glsl = .{ .uniform = .{ .set = 2, .instance = "u" } };
+};
+
+/// lookahead.comp: alternatives `count` samples on from `first`; and
+/// rechord.comp: the chords of the first `count` snapshots again.
+pub const LookParams = extern struct {
+ alternatives: u32,
+ first: u32,
+ count: u32,
+ horizon: u32,
+ masses: [4]f32,
+ softening: f32,
+ quantize: u32,
+ base: f32,
+ speed_ref: f32,
+ depth_scale: f32,
+ couple_scale: f32,
+ sample_dt: f32,
+ pad: u32 = 0,
+
+ pub const glsl = .{ .uniform = .{ .set = 2, .instance = "u" } };
+};
+
+/// synth.comp: one thread per sample.
+pub const SynthParams = extern struct {
+ count: u32,
+ /// A `Mode`.
+ mode: u32,
+ rate: f32,
+ gain: f32,
+
+ pub const glsl = .{ .uniform = .{ .set = 2, .instance = "u" } };
+};
+
+/// The sky's camera and sprites (vertex uniforms).
+pub const SkyView = extern struct {
+ /// World point at the image's centre, and world units per pixel.
+ center: [2]f32,
+ size: [2]f32,
+ per_pixel: f32,
+ radius: f32,
+ alpha: f32,
+ first: u32,
+ count: u32,
+ /// Trail: where the newest point is, and how many are filled.
+ head: u32,
+ filled: u32,
+ /// Seconds, for what flows.
+ time: f32,
+ /// Trail segments longer than this (world units) are jumps, not motion
+ /// (system 0 stepping into a snapshot): not drawn.
+ gap: f32 = 1e9,
+ pad0: f32 = 0,
+ pad1: f32 = 0,
+ pad2: f32 = 0,
+
+ pub const glsl = .{ .uniform = .{ .set = 1, .instance = "u" } };
+};
+
+/// fade.frag: moves what is there `amount` of the way to `background`.
+pub const Fade = extern struct {
+ background: [3]f32,
+ amount: f32,
+
+ pub const glsl = .{ .uniform = .{ .set = 3, .instance = "u" } };
+};
diff --git a/examples/spheres/src/main.zig b/examples/spheres/src/main.zig
new file mode 100644
index 0000000..062aebd
--- /dev/null
+++ b/examples/spheres/src/main.zig
@@ -0,0 +1,1121 @@
+//! spheres: the three-body problem, heard. Three bodies attract each other;
+//! the GPU integrates thousands of copies of them at once, each a hair
+//! apart, and draws them as a cloud around the one it follows in full, so
+//! chaos shows as the cloud spreading (and a stable orbit as it staying a
+//! thin line). Each body is also a voice, synthesised on the GPU from its
+//! motion: speed is pitch, the balance of its two distances is the
+//! modulator's ratio, and the nearness of its closest neighbour is the
+//! modulation depth, as sine, additive, AM, ring, FM or PM synthesis. The
+//! scope shows the result: an oscilloscope, the spectrum with each voice's
+//! predicted partials marked, and a spectrogram.
+//!
+//! Memory by lifetime: State is the preset, the transport and the
+//! synthesis settings, changed by `update` and replayable. Session holds the
+//! GPU objects, the sound on its way to the speakers and the scope. No
+//! Store: a run is not worth keeping.
+const std = @import("std");
+const sk = @import("sketch");
+const gpu = sk.abi.gpu;
+const scope = @import("scope");
+const layouts = @import("layouts");
+const shaders = @import("shaders");
+const chords = @import("chords.zig");
+
+pub const name = "spheres";
+pub const width = 1280;
+pub const height = 800;
+
+/// The audio stream's key.
+const stream = 1;
+/// Systems integrated: system 0 and its cloud.
+const systems = layouts.max_systems;
+/// How far apart the copies start.
+const spread = 2e-4;
+const background = 0x05070d;
+/// Body colours; match the shaders' palette.
+const palette = [3]u24{ 0x66d9ff, 0xff73d1, 0xffcc59 };
+
+pub const Preset = enum {
+ figure_eight,
+ butterfly,
+ pythagorean,
+ lagrange,
+ random,
+
+ fn label(p: Preset) []const u8 {
+ return switch (p) {
+ .figure_eight => "figure eight",
+ .butterfly => "butterfly",
+ .pythagorean => "Pythagorean",
+ .lagrange => "Lagrange triangle",
+ .random => "random",
+ };
+ }
+};
+pub const Mode = layouts.Mode;
+pub const Scale = layouts.Scale;
+
+pub const State = struct {
+ preset: Preset = .figure_eight,
+ /// Starts the preset over, its copies spread with this seed.
+ reset: sk.Request(u32) = .{},
+ running: bool = true,
+ backward: bool = false,
+ /// Simulated time per second: a little under real time, so the
+ /// look-ahead's share of each frame keeps it well ahead.
+ speed: f32 = 0.7,
+ mode: Mode = .additive,
+ /// Where pitches snap: the more notes, the more chords.
+ scale: Scale = .diatonic,
+ muted: bool = false,
+ /// The voice whose partials the spectrum marks in full.
+ focus: u8 = 0,
+ /// Played as an instrument: chord pads, each sending the sky to the
+ /// nearest time its chord plays and holding the chord. Off, it runs on
+ /// by itself.
+ instrument: bool = false,
+ /// A chord to play, as its pitch classes (a grid button's).
+ chord: sk.Request(u16) = .{},
+};
+
+/// On the way to a pad's chord: where to, and how fast (simulated seconds
+/// a second).
+const Travel = struct { to: chords.Pick, speed: f64 };
+
+pub const Session = struct {
+ reset: sk.Handled = .{},
+ started: bool = false,
+ /// System 0 as last read back, and whether it has been.
+ lead: layouts.Lead = std.mem.zeroes(layouts.Lead),
+ have_lead: bool = false,
+ masses: [3]f32 = .{ 1, 1, 1 },
+ softening: f32 = 0.01,
+ /// The trail's newest slot, how many are filled, and the steps since its
+ /// last point.
+ trail_head: u32 = 0,
+ trail_filled: u32 = 0,
+ trail_carry: u32 = 0,
+ /// The camera: world point at the sky's centre, and the half-extent it
+ /// shows, smoothed.
+ center: [2]f32 = .{ 0, 0 },
+ extent: f32 = 1.5,
+ scope: scope.Scope = .{},
+ /// Simulated time since the preset started.
+ time: f64 = 0,
+ chord: sk.Handled = .{},
+ ahead: chords.Ahead = .{},
+ /// The scale the look-ahead's chords were found with.
+ scale: Scale = .diatonic,
+ travel: ?Travel = null,
+ /// The snapshot whose chord is held.
+ held: ?chords.Pick = null,
+ gpu: Gpu = .{},
+};
+
+const Gpu = struct {
+ ahead_state: sk.Buffer = .none,
+ snapshots: sk.Buffer = .none,
+ ahead_chords: sk.Buffer = .none,
+ ready: bool = false,
+ bodies: sk.Buffer = .none,
+ trail: sk.Buffer = .none,
+ voices: sk.Buffer = .none,
+ phases: sk.Buffer = .none,
+ lead: sk.Buffer = .none,
+ block: sk.Buffer = .none,
+ sky: sk.Image = .none,
+ overlay: sk.Image = .none,
+ size: [2]u32 = .{ 0, 0 },
+ clear_sky: bool = true,
+};
+
+/// Readback keys; from `chords_from`, look-ahead chords from that sample.
+const Readback = enum(u32) { audio = 1, lead = 2, _ };
+const chords_from = 0x10000;
+
+// ---------------------------------------------------------------------------
+// Layout.
+
+const Layout = struct {
+ w: f32,
+ h: f32,
+ narrow: bool,
+ sky: sk.Rect,
+ voices: sk.Rect,
+ oscilloscope: sk.Rect,
+ spectrum: sk.Rect,
+ spectrogram: sk.Rect,
+ /// As an instrument: the look-ahead's chords along time, and the grid.
+ strip: sk.Rect = .{},
+ grid: sk.Rect = .{},
+
+ const header = 36;
+ const Grid = chords.Grid;
+ /// The grid's columns on a phone: B flat to B, round C.
+ const narrow_columns = 8;
+ const narrow_first = 4;
+ /// Two rows of buttons, on a phone.
+ const toolbar = 104;
+ const per_row = buttons.len / 2;
+
+ /// Wide: the sky on the left, the sound on the right, buttons on top.
+ /// Narrow (a phone): the sky, then the sound, buttons along the bottom.
+ fn of(w: f32, h: f32, instrument: bool) Layout {
+ const narrow = w < 900;
+ if (narrow) {
+ const sky_h = @round(@min(w, h * if (instrument) @as(f32, 0.27) else 0.42));
+ const sky: sk.Rect = .{ .x = 0, .y = header, .w = w, .h = sky_h };
+ var y = sky.y + sky.h;
+ var strip: sk.Rect = .{};
+ var grid: sk.Rect = .{};
+ if (instrument) {
+ strip = .{ .x = 8, .y = y + 6, .w = w - 16, .h = 10 };
+ grid = .{ .x = 8, .y = strip.y + strip.h + 6, .w = w - 16, .h = Grid.rows * 36 - 4 };
+ y = grid.y + grid.h;
+ }
+ const voices: sk.Rect = .{ .x = 8, .y = y + 6, .w = w - 16, .h = 54 };
+ // As an instrument the grid takes the oscilloscope's room.
+ const oscilloscope: sk.Rect = if (instrument) .{ .x = 8, .y = voices.y + voices.h, .w = 0, .h = 0 } else .{ .x = 8, .y = voices.y + voices.h + 4, .w = w - 16, .h = 64 };
+ const spectrum: sk.Rect = .{ .x = 8, .y = oscilloscope.y + oscilloscope.h + 6, .w = w - 16, .h = if (instrument) 90 else 120 };
+ const rest = h - toolbar - (spectrum.y + spectrum.h + 22);
+ return .{ .w = w, .h = h, .narrow = true, .sky = sky, .voices = voices, .oscilloscope = oscilloscope, .spectrum = spectrum, .spectrogram = .{ .x = 8, .y = spectrum.y + spectrum.h + 18, .w = w - 16, .h = @max(rest, 40) }, .strip = strip, .grid = grid };
+ }
+ const sky_w = @round((w - 48) * 0.58);
+ const full: sk.Rect = .{ .x = 16, .y = header + 8, .w = sky_w, .h = h - header - 8 - 28 };
+ var sky = full;
+ var strip: sk.Rect = .{};
+ var grid: sk.Rect = .{};
+ if (instrument) {
+ const grid_h: f32 = Grid.rows * 30 - 4;
+ sky.h -= grid_h + 34;
+ strip = .{ .x = sky.x, .y = sky.y + sky.h + 8, .w = sky.w, .h = 10 };
+ grid = .{ .x = sky.x, .y = strip.y + strip.h + 8, .w = sky.w, .h = grid_h };
+ }
+ const x = sky.x + sky.w + 16;
+ const cw = w - 16 - x;
+ const voices: sk.Rect = .{ .x = x, .y = sky.y, .w = cw, .h = 66 };
+ const oscilloscope: sk.Rect = .{ .x = x, .y = voices.y + voices.h + 6, .w = cw, .h = 110 };
+ const spectrum: sk.Rect = .{ .x = x, .y = oscilloscope.y + oscilloscope.h + 10, .w = cw, .h = 210 };
+ const spectrogram_y = spectrum.y + spectrum.h + 20;
+ return .{ .w = w, .h = h, .narrow = false, .sky = sky, .voices = voices, .oscilloscope = oscilloscope, .spectrum = spectrum, .spectrogram = .{ .x = x, .y = spectrogram_y, .w = cw, .h = full.y + full.h - spectrogram_y }, .strip = strip, .grid = grid };
+ }
+
+ /// The grid's columns on screen: all twelve, or a phone's eight.
+ fn columns(l: Layout) struct { first: usize, count: usize } {
+ return if (l.narrow) .{ .first = narrow_first, .count = narrow_columns } else .{ .first = 0, .count = Grid.columns };
+ }
+
+ /// The button at `row` and grid `column`, if on screen: rows staggered
+ /// half a button right each, as on a sanfona.
+ fn key(l: Layout, row: usize, column: usize) ?sk.Rect {
+ const cols = l.columns();
+ if (column < cols.first or column >= cols.first + cols.count) return null;
+ const gap = 4;
+ const n: f32 = @floatFromInt(cols.count);
+ const w = (l.grid.w - (n - 1) * gap) / (n + @as(f32, Grid.rows - 1) * 0.5);
+ const h = (l.grid.h - (Grid.rows - 1) * gap) / Grid.rows;
+ const r: f32 = @floatFromInt(row);
+ const j: f32 = @floatFromInt(column - cols.first);
+ return .{ .x = l.grid.x + r * w * 0.5 + j * (w + gap), .y = l.grid.y + r * (h + gap), .w = w, .h = h };
+ }
+
+ fn keyAt(l: Layout, x: f32, y: f32) ?u16 {
+ for (0..Grid.rows) |row| for (0..Grid.columns) |column| {
+ if (l.key(row, column)) |r| if (r.contains(x, y)) return Grid.chord(row, column);
+ };
+ return null;
+ }
+
+ fn button(l: Layout, i: usize) sk.Rect {
+ const n: f32 = @floatFromInt(buttons.len);
+ const at: f32 = @floatFromInt(i);
+ if (l.narrow) {
+ const per: f32 = per_row;
+ const w = (l.w - 8 - (per - 1) * 4) / per;
+ const column = @mod(at, per);
+ const line = @floor(at / per);
+ return .{ .x = 4 + column * (w + 4), .y = l.h - toolbar + 6 + line * 48, .w = w, .h = 44 };
+ }
+ const w = 66;
+ return .{ .x = l.w - 16 - (n - at) * (w + 6) + 6, .y = 5, .w = w, .h = 26 };
+ }
+
+ fn buttonAt(l: Layout, x: f32, y: f32) ?Action {
+ for (buttons, 0..) |a, i| if (l.button(i).contains(x, y)) return a;
+ return null;
+ }
+};
+
+// ---------------------------------------------------------------------------
+// Update.
+
+const Action = enum { play, reverse, mode, preset, scale, mute, faster, slower, reset, focus, eight, random, instrument };
+
+const keys = [_]struct { sk.Key, Action }{
+ .{ .space, .play }, .{ .left, .reverse }, .{ .right, .reverse }, .{ .s, .mode }, .{ .p, .preset },
+ .{ .q, .scale }, .{ .m, .mute }, .{ .up, .faster }, .{ .down, .slower }, .{ .r, .reset },
+ .{ .tab, .focus }, .{ .e, .eight }, .{ .x, .random }, .{ .c, .instrument },
+};
+
+/// What touch screens reach by button; on a phone, in two rows of four.
+const buttons = [_]Action{ .play, .reverse, .mode, .mute, .eight, .random, .instrument, .scale };
+
+/// The computer keyboard as the grid: its rows are staggered like a
+/// sanfona's, so the number row plays majors, QWERTY minors, ASDF sevenths
+/// and ZXCV sus chords, column by column round the fifths.
+const grid_keys = [_][]const sk.Key{
+ &.{ .@"1", .@"2", .@"3", .@"4", .@"5", .@"6", .@"7", .@"8", .@"9", .@"0", .minus, .equals },
+ &.{ .q, .w, .e, .r, .t, .y, .u, .i, .o, .p, .left_bracket, .right_bracket },
+ &.{ .a, .s, .d, .f, .g, .h, .j, .k, .l, .semicolon, .apostrophe },
+ &.{ .z, .x, .c, .v, .b, .n, .m, .comma, .period, .slash },
+};
+
+fn isLetterOrDigit(k: sk.Key) bool {
+ const v = @intFromEnum(k);
+ return v >= @intFromEnum(sk.Key.a) and v <= @intFromEnum(sk.Key.@"0");
+}
+
+pub fn update(s: *State, in: *const sk.Input) void {
+ // As an instrument, letters and digits play chords; Escape leaves.
+ if (s.instrument) {
+ for (grid_keys, 0..) |row, r| for (row, 0..) |k, column| {
+ if (in.pressed(k)) s.chord.send(chords.Grid.chord(r, column));
+ };
+ if (in.pressed(sk.Key.escape)) s.instrument = false;
+ }
+ for (keys) |k| if (in.pressed(k[0]) and !(s.instrument and isLetterOrDigit(k[0]))) {
+ // Left and right choose the way rather than flip it.
+ if (k[0] == .left) s.backward = true else if (k[0] == .right) s.backward = false else act(s, k[1]);
+ if (k[0] == .left or k[0] == .right) s.running = true;
+ };
+ const l = Layout.of(in.width, in.height, s.instrument);
+ for (in.events) |e| if (e.kind == .mouse_down and e.code == 1) {
+ if (l.buttonAt(e.x, e.y)) |a| act(s, a);
+ if (s.instrument) if (l.keyAt(e.x, e.y)) |chord| s.chord.send(chord);
+ };
+}
+
+fn act(s: *State, a: Action) void {
+ switch (a) {
+ .play => s.running = !s.running,
+ .reverse => {
+ s.backward = !s.backward;
+ s.running = true;
+ },
+ .mode => s.mode = @enumFromInt((@intFromEnum(s.mode) + 1) % @typeInfo(Mode).@"enum".field_names.len),
+ .preset => choose(s, @enumFromInt((@intFromEnum(s.preset) + 1) % @typeInfo(Preset).@"enum".field_names.len)),
+ .scale => s.scale = @enumFromInt((@intFromEnum(s.scale) + 1) % @typeInfo(Scale).@"enum".field_names.len),
+ .mute => s.muted = !s.muted,
+ .faster => s.speed = @min(s.speed * 1.25, 8),
+ .slower => s.speed = @max(s.speed / 1.25, 0.05),
+ .reset => s.reset.send(s.reset.value +% 1),
+ .focus => s.focus = (s.focus + 1) % 3,
+ .eight => choose(s, .figure_eight),
+ // A new seed each time: new bodies.
+ .random => choose(s, .random),
+ .instrument => s.instrument = !s.instrument,
+ }
+}
+
+fn choose(s: *State, p: Preset) void {
+ s.preset = p;
+ s.backward = false;
+ s.running = true;
+ s.reset.send(s.reset.value +% 1);
+}
+
+// ---------------------------------------------------------------------------
+// The presets.
+
+const Start = struct { masses: [3]f32, bodies: [3]layouts.Body, softening: f32 = 0.01 };
+
+fn start(p: Preset, seed: u32) Start {
+ return switch (p) {
+ // Chenciner and Montgomery's: three equal masses chasing each
+ // other round one figure of eight. Stable: the cloud stays thin.
+ .figure_eight => .{ .masses = .{ 1, 1, 1 }, .bodies = .{
+ .{ .pos = .{ 0.97000436, -0.24308753 }, .vel = .{ 0.46620368, 0.43236573 } },
+ .{ .pos = .{ -0.97000436, 0.24308753 }, .vel = .{ 0.46620368, 0.43236573 } },
+ .{ .pos = .{ 0, 0 }, .vel = .{ -0.93240737, -0.86473146 } },
+ } },
+ // Šuvakov and Dmitrašinović's butterfly I: periodic, and not stable.
+ .butterfly => .{ .masses = .{ 1, 1, 1 }, .bodies = .{
+ .{ .pos = .{ -1, 0 }, .vel = .{ 0.30689, 0.12551 } },
+ .{ .pos = .{ 1, 0 }, .vel = .{ 0.30689, 0.12551 } },
+ .{ .pos = .{ 0, 0 }, .vel = .{ -0.61378, -0.25102 } },
+ } },
+ // Burrau's: masses 3, 4 and 5 at rest on a 3-4-5 triangle. Close
+ // passes, chaos, and in the end two bodies leave as a pair.
+ .pythagorean => .{ .masses = .{ 3, 4, 5 }, .bodies = centred(.{ 3, 4, 5 }, .{
+ .{ .pos = .{ 1, 3 }, .vel = .{ 0, 0 } },
+ .{ .pos = .{ -2, -1 }, .vel = .{ 0, 0 } },
+ .{ .pos = .{ 1, -1 }, .vel = .{ 0, 0 } },
+ }) },
+ // Lagrange's equilateral solution, turning rigidly. For equal
+ // masses it is unstable: the cloud shows it coming apart.
+ .lagrange => blk: {
+ const speed: f32 = @sqrt(1.0 / @sqrt(3.0));
+ var bodies: [3]layouts.Body = undefined;
+ for (&bodies, 0..) |*b, i| {
+ const a = @as(f32, @floatFromInt(i)) * std.math.tau / 3;
+ b.* = .{ .pos = .{ @cos(a), @sin(a) }, .vel = .{ -@sin(a) * speed, @cos(a) * speed } };
+ }
+ break :blk .{ .masses = .{ 1, 1, 1 }, .bodies = bodies };
+ },
+ .random => blk: {
+ var rng: std.Random.DefaultPrng = .init(seed);
+ const r = rng.random();
+ var masses: [3]f32 = undefined;
+ var bodies: [3]layouts.Body = undefined;
+ for (&masses, &bodies) |*m, *b| {
+ m.* = 0.6 + 0.8 * r.float(f32);
+ b.* = .{ .pos = .{ 2 * r.float(f32) - 1, 2 * r.float(f32) - 1 }, .vel = .{ 0.6 * (r.float(f32) - 0.5), 0.6 * (r.float(f32) - 0.5) } };
+ }
+ break :blk .{ .masses = masses, .bodies = centred(masses, bodies) };
+ },
+ };
+}
+
+/// The bodies moved and pushed so their centre of mass sits still at 0.
+fn centred(masses: [3]f32, bodies: [3]layouts.Body) [3]layouts.Body {
+ var total: f32 = 0;
+ var p: [2]f32 = .{ 0, 0 };
+ var v: [2]f32 = .{ 0, 0 };
+ for (masses, bodies) |m, b| {
+ total += m;
+ for (0..2) |k| {
+ p[k] += m * b.pos[k];
+ v[k] += m * b.vel[k];
+ }
+ }
+ var out = bodies;
+ for (&out) |*b| for (0..2) |k| {
+ b.pos[k] -= p[k] / total;
+ b.vel[k] -= v[k] / total;
+ };
+ return out;
+}
+
+// ---------------------------------------------------------------------------
+// Draw.
+
+pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void {
+ const in = f.in;
+ f.canvas(@intFromFloat(@max(in.window_width, 320)), @intFromFloat(@max(in.window_height, 400)));
+ f.clear(background);
+ if (!f.host.gpu()) {
+ f.text(16, 40, 2, "spheres needs a GPU: the host has none.", 0xff8080);
+ return;
+ }
+ const rate: f64 = @floatFromInt(in.sample_rate);
+ const dt: f32 = @floatCast(@min(@as(f64, @floatFromInt(in.dt)) / std.time.ns_per_s, 0.05));
+ const g = &ss.gpu;
+ setup(g, f);
+
+ // What came back: the sound, for the scope, and system 0.
+ for (in.downloads) |d| switch (@as(Readback, @enumFromInt(d.key))) {
+ .audio => {
+ const samples = std.mem.bytesAsSlice(f32, d.bytes[0 .. d.bytes.len / 4 * 4]);
+ const aligned = f.scratch.alloc(f32, samples.len) catch continue;
+ for (aligned, samples) |*to, from| to.* = from;
+ ss.scope.push(aligned);
+ },
+ .lead => if (d.bytes.len >= @sizeOf(layouts.Lead)) {
+ ss.lead = std.mem.bytesToValue(layouts.Lead, d.bytes[0..@sizeOf(layouts.Lead)]);
+ ss.have_lead = true;
+ },
+ _ => if (d.key >= chords_from) {
+ const words = f.scratch.alloc(u32, d.bytes.len / 4) catch continue;
+ @memcpy(std.mem.sliceAsBytes(words), d.bytes[0 .. words.len * 4]);
+ ss.ahead.arrived(d.key - chords_from, words);
+ },
+ };
+
+ if (!ss.started or ss.reset.take(s.reset) != null) restart(s, ss, f);
+ if (!s.instrument) {
+ ss.travel = null;
+ ss.held = null;
+ }
+ lookAhead(s, ss, f);
+
+ // A chord: the sound jumps to it now, the sky travels there.
+ if (ss.chord.take(s.chord)) |chord| if (s.instrument and ss.ahead.found[chord]) {
+ const root: u4 = if (chords.Grid.find(chord)) |at| chords.Grid.roots[at.column] else 0;
+ if (ss.ahead.nearest(chord, root, ss.time)) |pick| {
+ ss.held = pick;
+ ss.travel = .{ .to = pick, .speed = @max(@abs(pick.time() - ss.time) / 1.2, 2) };
+ f.audio(stream, &.{}, .{ .clear = true });
+ }
+ };
+
+ // The simulation: as much simulated time as `speed` asks, either way;
+ // or, travelling to a chord, as fast as it takes to arrive in a second
+ // or so, where system 0 takes the snapshot's state. It runs every frame,
+ // still or not, so system 0 always sings: a held chord, or its motion.
+ var span: f64 = 0;
+ var adopt: u32 = 0;
+ if (ss.travel) |travel| {
+ const remaining = travel.to.time() - ss.time;
+ const step = travel.speed * dt;
+ if (@abs(remaining) <= step) {
+ adopt = travel.to.index() + 1;
+ ss.time = travel.to.time();
+ ss.travel = null;
+ } else span = std.math.sign(remaining) * step;
+ } else if (s.running and !(s.instrument and ss.held != null)) {
+ // Arrived at a chord, the sky holds still on the moment that sings it.
+ span = s.speed * dt * @as(f64, if (s.backward) -1 else 1);
+ }
+ const steps: u32 = @intFromFloat(@min(@ceil(@abs(span) / chords.base_step), 256));
+ var trail = trailPoints(ss, steps, span);
+ // Travelling back retraces system 0's own path: its trail rewinds rather
+ // than drawing over itself, as far as it reaches.
+ if (ss.travel != null and span < 0 and trail.points < ss.trail_filled) {
+ ss.trail_head = (ss.trail_head + layouts.trail - trail.points) % layouts.trail;
+ ss.trail_filled -= trail.points;
+ trail.points = 0;
+ }
+ f.compute(.{
+ .label = "sim.comp",
+ .kernel = sim_kernel,
+ .readonly = &.{g.snapshots},
+ .readwrite = &.{ g.bodies, g.trail, g.voices, g.lead },
+ .uniforms = gpu.uniform(f.scratch, layouts.SimParams{
+ .systems = systems,
+ .steps = steps,
+ .dt = if (steps > 0) @floatCast(span / @as(f64, @floatFromInt(steps))) else 0,
+ .softening = ss.softening,
+ .masses = .{ ss.masses[0], ss.masses[1], ss.masses[2], 0 },
+ .trail_head = (ss.trail_head + 1) % layouts.trail,
+ .trail_points = trail.points,
+ .trail_first = trail.first,
+ .trail_every = trail.every,
+ .quantize = @intFromEnum(s.scale),
+ .base = chords.base,
+ .speed_ref = chords.speed_ref,
+ .depth_scale = chords.depth_scale,
+ .couple_scale = chords.couple_scale,
+ .voice_source = if (ss.held) |h| h.index() + 1 else 0,
+ .adopt = adopt,
+ }),
+ .groups = .{ (systems + 63) / 64, 1, 1 },
+ });
+ ss.time += span;
+ ss.trail_head = (ss.trail_head + trail.points) % layouts.trail;
+ ss.trail_filled = @min(ss.trail_filled + trail.points, layouts.trail);
+ f.download(g.lead, .{ .size = @sizeOf(layouts.Lead), .key = @intFromEnum(Readback.lead) });
+
+ // The sound: as much as keeps the host's lead queued, streamed straight
+ // from the GPU's block; and read back for the scope.
+ const want: u32 = @min(in.lead -| in.stream(stream).queued, layouts.max_block);
+ if (want > 0) {
+ const params = gpu.uniform(f.scratch, layouts.SynthParams{
+ .count = want,
+ .mode = @intFromEnum(s.mode),
+ .rate = @floatCast(rate),
+ // Loud enough for a phone's speaker; tanh rounds the peaks off.
+ .gain = if (s.muted) 0 else 1.4,
+ });
+ f.compute(.{
+ .label = "synth.comp",
+ .kernel = synth_kernel,
+ .readonly = &.{ g.voices, g.phases },
+ .readwrite = &.{g.block},
+ .uniforms = params,
+ .groups = .{ (want + 63) / 64, 1, 1 },
+ });
+ f.compute(.{ .label = "advance.comp", .kernel = advance_kernel, .readwrite = &.{ g.voices, g.phases }, .uniforms = params });
+ f.audioBuffer(stream, g.block, .{ .count = want });
+ f.download(g.block, .{ .size = want * @sizeOf(f32), .key = @intFromEnum(Readback.audio) });
+ }
+
+ const l = Layout.of(in.width, in.height, s.instrument);
+ follow(ss, dt);
+ drawSky(s, ss, f, l);
+ sound(s, ss, f, l, rate);
+ labels(s, ss, f, l, rate);
+}
+
+/// Simulated time between trail points: about a frame's at the default
+/// speed, and many points a frame when travelling.
+const trail_dt = 0.012;
+
+/// Which of this frame's `steps` leave trail points: every so many steps,
+/// carrying the remainder to the next frame, 64 at most.
+fn trailPoints(ss: *Session, steps: u32, span: f64) struct { points: u32, first: u32, every: u32 } {
+ if (steps == 0) return .{ .points = 0, .first = 1, .every = 1 };
+ const step_dt = @abs(span) / @as(f64, @floatFromInt(steps));
+ var every: u32 = @intFromFloat(@max(1, @round(trail_dt / step_dt)));
+ var first = every -| @min(ss.trail_carry, every - 1);
+ var points: u32 = if (first > steps) 0 else 1 + (steps - first) / every;
+ if (points > 64) {
+ every = (steps + 63) / 64;
+ first = every;
+ points = steps / every;
+ }
+ ss.trail_carry = if (points == 0) ss.trail_carry + steps else steps - (first + (points - 1) * every);
+ return .{ .points = points, .first = first, .every = every };
+}
+
+fn setup(g: *Gpu, f: *sk.Frame) void {
+ if (g.ready) return;
+ g.ready = true;
+ g.bodies = f.host.newBuffer(systems * layouts.bodies * @sizeOf(layouts.Body));
+ g.trail = f.host.newBuffer(layouts.bodies * layouts.trail * @sizeOf([2]f32));
+ g.voices = f.host.newBuffer(layouts.voices_len * @sizeOf([4]f32));
+ g.phases = f.host.newBuffer(3 * @sizeOf([4]f32));
+ g.lead = f.host.newBuffer(@sizeOf(layouts.Lead));
+ g.block = f.host.newBuffer(layouts.max_block * @sizeOf(f32));
+ g.ahead_state = f.host.newBuffer(layouts.alternatives * 3 * @sizeOf(layouts.Body));
+ g.snapshots = f.host.newBuffer(layouts.horizon * layouts.alternatives * 3 * @sizeOf(layouts.Body));
+ g.ahead_chords = f.host.newBuffer(layouts.horizon * layouts.alternatives * @sizeOf(u32));
+}
+
+fn lookParams(s: *const State, ss: *const Session, first: u32, count: u32) layouts.LookParams {
+ return .{
+ .alternatives = layouts.alternatives,
+ .first = first,
+ .count = count,
+ .horizon = layouts.horizon,
+ .masses = .{ ss.masses[0], ss.masses[1], ss.masses[2], 0 },
+ .softening = ss.softening,
+ .quantize = @intFromEnum(s.scale),
+ .base = chords.base,
+ .speed_ref = chords.speed_ref,
+ .depth_scale = chords.depth_scale,
+ .couple_scale = chords.couple_scale,
+ .sample_dt = chords.sample_dt,
+ };
+}
+
+/// The look-ahead: its futures a few samples further, their chords on
+/// their way back; and all the chords again when the scale changes.
+fn lookAhead(s: *const State, ss: *Session, f: *sk.Frame) void {
+ const g = &ss.gpu;
+ if (ss.scale != s.scale) {
+ ss.scale = s.scale;
+ const count = ss.ahead.asked * layouts.alternatives;
+ ss.ahead.forget();
+ if (count > 0) {
+ f.compute(.{
+ .label = "rechord.comp",
+ .kernel = rechord_kernel,
+ .readonly = &.{g.snapshots},
+ .readwrite = &.{g.ahead_chords},
+ .uniforms = gpu.uniform(f.scratch, lookParams(s, ss, 0, count)),
+ .groups = .{ (count + 63) / 64, 1, 1 },
+ });
+ f.download(g.ahead_chords, .{ .size = count * @sizeOf(u32), .key = chords_from });
+ }
+ }
+ if (ss.ahead.asked >= layouts.horizon) return;
+ const first = ss.ahead.asked;
+ const count: u32 = @min(chords.per_frame, layouts.horizon - first);
+ f.compute(.{
+ .label = "lookahead.comp",
+ .kernel = lookahead_kernel,
+ .readwrite = &.{ g.ahead_state, g.snapshots, g.ahead_chords },
+ .uniforms = gpu.uniform(f.scratch, lookParams(s, ss, first, count)),
+ });
+ f.download(g.ahead_chords, .{ .offset = first * layouts.alternatives * @sizeOf(u32), .size = count * layouts.alternatives * @sizeOf(u32), .key = chords_from + first });
+ ss.ahead.asked += count;
+}
+
+/// Puts the preset on the GPU: system 0 as given, the others each body
+/// moved by up to `spread`.
+fn restart(s: *const State, ss: *Session, f: *sk.Frame) void {
+ ss.started = true;
+ const p = start(s.preset, s.reset.value);
+ ss.masses = p.masses;
+ ss.softening = p.softening;
+ const all = f.scratch.alloc(layouts.Body, systems * layouts.bodies) catch return;
+ var rng: std.Random.DefaultPrng = .init(s.reset.value *% 0x9e3779b9 +% 1);
+ const r = rng.random();
+ for (0..systems) |i| for (0..3) |b| {
+ var body = p.bodies[b];
+ if (i > 0) for (&body.pos) |*x| {
+ x.* += spread * (2 * r.float(f32) - 1);
+ };
+ all[3 * i + b] = body;
+ };
+ f.upload(ss.gpu.bodies, 0, std.mem.sliceAsBytes(all));
+ // The voices glide from a quiet start, uncoupled; the trail starts empty.
+ const quiet = f.scratch.alloc([4]f32, layouts.voices_len) catch return;
+ for (quiet, 0..) |*v, i| v.* = if (i < layouts.coupling_previous) .{ 220, 1, 0, 0 } else .{ 0, 0, 0, 0 };
+ f.upload(ss.gpu.voices, 0, std.mem.sliceAsBytes(quiet));
+ const lead = f.scratch.create(layouts.Lead) catch return;
+ lead.* = std.mem.zeroes(layouts.Lead);
+ lead.bodies = p.bodies;
+ f.upload(ss.gpu.lead, 0, std.mem.asBytes(lead));
+ ss.lead = lead.*;
+ ss.have_lead = true;
+ ss.trail_filled = 0;
+ ss.trail_carry = 0;
+ // The look-ahead's futures: 0 as given, the rest nudged by growing
+ // amounts, so in a chaotic system they fan out.
+ const futures = f.scratch.alloc(layouts.Body, layouts.alternatives * 3) catch return;
+ for (0..layouts.alternatives) |a| for (0..3) |b| {
+ var body = p.bodies[b];
+ // Small enough that every future is recognisably this system,
+ // apart where chaos amplifies the difference.
+ const nudge = 2e-4 * @as(f32, @floatFromInt(a));
+ for (&body.pos) |*x| {
+ x.* += nudge * (2 * r.float(f32) - 1);
+ }
+ futures[3 * a + b] = body;
+ };
+ f.upload(ss.gpu.ahead_state, 0, std.mem.sliceAsBytes(futures));
+ ss.ahead.reset();
+ ss.scale = s.scale;
+ ss.time = 0;
+ ss.travel = null;
+ ss.held = null;
+ ss.gpu.clear_sky = true;
+ ss.extent = 1.5;
+}
+
+/// The camera keeps system 0's bodies in view: quick to widen, slow to
+/// close in.
+fn follow(ss: *Session, dt: f32) void {
+ var c: [2]f32 = .{ 0, 0 };
+ var total: f32 = 0;
+ for (ss.lead.bodies, ss.masses) |b, m| {
+ c[0] += m * b.pos[0];
+ c[1] += m * b.pos[1];
+ total += m;
+ }
+ c = .{ c[0] / total, c[1] / total };
+ var reach: f32 = 0;
+ for (ss.lead.bodies) |b| reach = @max(reach, @max(@abs(b.pos[0] - c[0]), @abs(b.pos[1] - c[1])));
+ const want = std.math.clamp(reach * 1.25, 1.2, 40);
+ const rate: f32 = if (want > ss.extent) 4 else 0.6;
+ ss.extent += (want - ss.extent) * (1 - @exp(-rate * dt));
+ for (&ss.center, c) |*x, to| x.* += (to - x.*) * (1 - @exp(-2 * dt));
+}
+
+const sim_kernel: gpu.Kernel = .{ .code = shaders.sim_comp, .readonly_buffers = 1, .readwrite_buffers = 4, .uniform_buffers = 1, .threads = .{ 64, 1, 1 } };
+const synth_kernel: gpu.Kernel = .{ .code = shaders.synth_comp, .readonly_buffers = 2, .readwrite_buffers = 1, .uniform_buffers = 1, .threads = .{ 64, 1, 1 } };
+const advance_kernel: gpu.Kernel = .{ .code = shaders.advance_comp, .readwrite_buffers = 2, .uniform_buffers = 1, .threads = .{ 1, 1, 1 } };
+const lookahead_kernel: gpu.Kernel = .{ .code = shaders.lookahead_comp, .readwrite_buffers = 3, .uniform_buffers = 1, .threads = .{ 32, 1, 1 } };
+const rechord_kernel: gpu.Kernel = .{ .code = shaders.rechord_comp, .readonly_buffers = 1, .readwrite_buffers = 1, .uniform_buffers = 1, .threads = .{ 64, 1, 1 } };
+
+const sky_pipelines = [_]gpu.Pipeline{
+ // 0: the fade, blended over what is there.
+ .{ .vertex = .{ .code = shaders.fullscreen_vert }, .fragment = .{ .code = shaders.fade_frag, .uniform_buffers = 1 }, .stride = 0, .attributes = &.{}, .blend = .premultiplied },
+ // 1: glows, added.
+ .{ .vertex = .{ .code = shaders.sprite_vert, .uniform_buffers = 1, .storage_buffers = 1 }, .fragment = .{ .code = shaders.sprite_frag }, .stride = 0, .attributes = &.{}, .blend = .additive },
+ // 2: trails, added.
+ .{ .vertex = .{ .code = shaders.trail_vert, .uniform_buffers = 1, .storage_buffers = 1 }, .fragment = .{ .code = shaders.trail_frag }, .stride = 0, .attributes = &.{}, .blend = .additive },
+ // 3: the cloud, layered: where copies crowd it takes their body's
+ // colour rather than adding up to white.
+ .{ .vertex = .{ .code = shaders.sprite_vert, .uniform_buffers = 1, .storage_buffers = 1 }, .fragment = .{ .code = shaders.sprite_frag }, .stride = 0, .attributes = &.{}, .blend = .premultiplied },
+ // 4: the coupling between the closest pair, added.
+ .{ .vertex = .{ .code = shaders.link_vert, .uniform_buffers = 1, .storage_buffers = 2 }, .fragment = .{ .code = shaders.link_frag }, .stride = 0, .attributes = &.{}, .blend = .additive },
+};
+
+/// The sky: the cloud of copies on a long exposure, and over it system 0's
+/// trails and bodies, drawn fresh each frame.
+fn drawSky(s: *const State, ss: *Session, f: *sk.Frame, l: Layout) void {
+ const g = &ss.gpu;
+ const size: [2]u32 = .{ @intFromFloat(@max(l.sky.w, 1)), @intFromFloat(@max(l.sky.h, 1)) };
+ if (g.sky == .none or g.size[0] != size[0] or g.size[1] != size[1]) {
+ if (g.sky != .none) f.host.freeImage(g.sky);
+ if (g.overlay != .none) f.host.freeImage(g.overlay);
+ g.sky = f.host.newImage(size[0], size[1]);
+ g.overlay = f.host.newImage(size[0], size[1]);
+ g.size = size;
+ g.clear_sky = true;
+ }
+ const bg = sk.Color.hex(background);
+ const bgf: [3]f32 = .{ @as(f32, @floatFromInt(bg.r)) / 255, @as(f32, @floatFromInt(bg.g)) / 255, @as(f32, @floatFromInt(bg.b)) / 255 };
+ const per_pixel = 2 * ss.extent / @as(f32, @floatFromInt(@min(size[0], size[1])));
+ const base: layouts.SkyView = .{
+ .center = ss.center,
+ .size = .{ @floatFromInt(size[0]), @floatFromInt(size[1]) },
+ .per_pixel = per_pixel,
+ .radius = 1.6,
+ .alpha = 0.06,
+ .first = 1,
+ .count = systems - 1,
+ .head = ss.trail_head,
+ .filled = ss.trail_filled,
+ .time = @floatCast(@mod(@as(f64, @floatFromInt(f.in.now)) / std.time.ns_per_s, 1000)),
+ };
+ var cloud = base;
+ cloud.radius = 2.2;
+ cloud.alpha = 0.18;
+ f.gpu(.{
+ .label = "sky cloud",
+ .image = g.sky,
+ .width = size[0],
+ .height = size[1],
+ .clear = if (g.clear_sky) .{ bgf[0], bgf[1], bgf[2], 1 } else null,
+ .pipelines = &sky_pipelines,
+ .draws = &.{
+ .{ .pipeline = 0, .vertex_count = 3, .fragment_uniforms = gpu.uniform(f.scratch, layouts.Fade{ .background = bgf, .amount = if (s.running) 0.08 else 0.02 }) },
+ .{ .pipeline = 3, .vertex_count = (systems - 1) * 3 * 6, .vertex_uniforms = gpu.uniform(f.scratch, cloud), .vertex_storage = &.{g.bodies} },
+ },
+ });
+ g.clear_sky = false;
+
+ var trails = base;
+ trails.radius = 2.2;
+ trails.alpha = 0.9;
+ // Points are 0.012 apart in time; anything this far is a jump.
+ trails.gap = @max(0.5, ss.extent * 0.25);
+ var link = base;
+ link.radius = 3;
+ link.alpha = 0.9;
+ var halo = base;
+ halo.first = 0;
+ halo.count = 1;
+ halo.radius = 34;
+ halo.alpha = 0.35;
+ var core = halo;
+ core.radius = 9;
+ core.alpha = 1;
+ f.gpu(.{
+ .label = "sky bodies",
+ .image = g.overlay,
+ .width = size[0],
+ .height = size[1],
+ .clear = .{ 0, 0, 0, 0 },
+ .pipelines = &sky_pipelines,
+ .draws = &.{
+ .{ .pipeline = 2, .vertex_count = 3 * (layouts.trail - 1) * 6, .vertex_uniforms = gpu.uniform(f.scratch, trails), .vertex_storage = &.{g.trail} },
+ .{ .pipeline = 4, .vertex_count = 6 * 6, .vertex_uniforms = gpu.uniform(f.scratch, link), .vertex_storage = &.{ g.bodies, g.voices } },
+ .{ .pipeline = 1, .vertex_count = 3 * 6, .vertex_uniforms = gpu.uniform(f.scratch, halo), .vertex_storage = &.{g.bodies} },
+ .{ .pipeline = 1, .vertex_count = 3 * 6, .vertex_uniforms = gpu.uniform(f.scratch, core), .vertex_storage = &.{g.bodies} },
+ },
+ });
+ f.image(g.sky, l.sky, .{});
+ f.image(g.overlay, l.sky, .{});
+}
+
+/// The scope: an oscilloscope steadied on the focused voice, the spectrum
+/// and the spectrogram.
+fn sound(s: *const State, ss: *Session, f: *sk.Frame, l: Layout, rate: f64) void {
+ const v = ss.lead.voices[s.focus];
+ const period: u32 = if (v.carrier > 1) @intFromFloat(@round(rate / v.carrier)) else 256;
+ ss.scope.draw(f, .{
+ .seconds = 8,
+ .spectrogram = l.spectrogram,
+ .spectrum = l.spectrum,
+ .oscilloscope = .{
+ .rect = l.oscilloscope,
+ .samples = std.math.clamp(4 * period, 256, 4096),
+ .end = @intCast(ss.scope.heard % @max(period, 1)),
+ },
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Text and marks.
+
+const dim = 0x7a8090;
+const bright = 0xe6e9ef;
+
+fn labels(s: *const State, ss: *const Session, f: *sk.Frame, l: Layout, rate: f64) void {
+ f.text(16, 10, 2, "spheres", 0xc9b6ff);
+ const room = if (l.narrow) l.w else l.button(0).x;
+ const lead = ss.lead;
+ const how = if (!s.running) " paused" else if (s.backward) " backwards" else "";
+ if (room > 420) {
+ f.print(140, 14, 1, dim, "{s} t {d:.1} energy {d:.4}{s}", .{ s.preset.label(), ss.time, lead.energy, how });
+ } else f.print(140, 14, 1, dim, "{s} t {d:.1}{s}", .{ s.preset.label(), ss.time, how });
+ for (buttons, 0..) |a, i| button(s, f, a, l.button(i));
+
+ // The voices, in their bodies' colours.
+ const v_rect = l.voices;
+ f.print(v_rect.x, v_rect.y, 1, bright, "{s} {s}", .{ modeName(s.mode), modeFormula(s.mode) });
+ for (lead.voices, 0..) |v, i| {
+ const y = v_rect.y + 16 + @as(f32, @floatFromInt(i)) * 14;
+ const mark = if (i == s.focus) ">" else " ";
+ const letter: u8 = 'A' + @as(u8, @intCast(i));
+ // Its role in the FM pair: modulating (silent), or modulated and by
+ // whom, at what index.
+ const row = lead.coupling[i];
+ var by: usize = 0;
+ for (0..3) |j| if (row[j] > row[by]) {
+ by = j;
+ };
+ const pushed = if (row[3] > 0.5)
+ f.format(" modulating", .{})
+ else if (row[by] > 0.05)
+ f.format(" FM by {c} {d:.2}", .{ @as(u8, 'A' + @as(u8, @intCast(by))), row[by] })
+ else
+ "";
+ if (l.narrow) {
+ f.print(v_rect.x, y, 1, palette[i], "{s}{c} {d:7.1} Hz r {d:4.2} d {d:5.2}{s}", .{ mark, letter, v.carrier, v.ratio, v.depth, pushed });
+ } else if (s.mode == .fm or s.mode == .pm) {
+ f.print(v_rect.x, y, 1, palette[i], "{s}{c} {d:7.1} Hz ratio {d:4.2} depth {d:5.2} index {d:5.2}{s}", .{ mark, letter, v.carrier, v.ratio, v.depth, index(s.mode, v), pushed });
+ } else f.print(v_rect.x, y, 1, palette[i], "{s}{c} {d:7.1} Hz ratio {d:4.2} depth {d:5.2}{s}", .{ mark, letter, v.carrier, v.ratio, v.depth, pushed });
+ }
+
+ // The spectrum's scale and each voice's partials where the theory puts
+ // them: the focused voice's all of them, the others' as small ticks.
+ spectrumMarks(s, ss, f, l.spectrum, rate);
+ instrumentView(s, ss, f, l);
+ f.text(l.oscilloscope.x + 4, l.oscilloscope.y + 4, 1, "oscilloscope", dim);
+ f.text(l.spectrogram.x + 4, l.spectrogram.y + 4, 1, "spectrogram, 8 s", sk.Color.white.alpha(150));
+ if (!l.narrow) f.text(16, l.h - 18, 1, if (s.instrument) "keys play the grid: 1 2 3 majors, Q W E minors, A S D sevenths, Z X C sus, by fifths ESC free SPACE pause" else "SPACE pause LEFT/RIGHT time's way UP/DOWN speed P/E/X preset C chords S synthesis Q scale M mute TAB voice R again", dim);
+}
+
+/// Grid rows' colours: majors gold, minors blue, sevenths orange, sus
+/// green, power chords violet.
+const row_colors = [chords.Grid.rows]u24{ 0xffcc59, 0x66b3ff, 0xff7a59, 0x69db7c, 0xb197fc };
+
+/// The chord sounding, over the sky; and as an instrument, the look-ahead's
+/// chords along time (system 0's own future) and the grid.
+fn instrumentView(s: *const State, ss: *const Session, f: *sk.Frame, l: Layout) void {
+ const Grid = chords.Grid;
+ var buf: [32]u8 = undefined;
+ const now = chords.chordOf(ss.lead.voices);
+ f.text(l.sky.x + 12, l.sky.y + 10, 2, f.format("{s}", .{chords.name(&buf, now)}), sk.Color.white.alpha(200));
+ if (!s.instrument) return;
+ f.print(l.sky.x + 12, l.sky.y + l.sky.h - 18, 1, sk.Color.white.alpha(120), "{d} chords found in {d} futures", .{ ss.ahead.distinct, layouts.alternatives });
+
+ const strip = l.strip;
+ const span = @as(f64, chords.horizon) * chords.sample_dt;
+ f.fill(strip, sk.Color.hex(0x10131c));
+ var t: u32 = 0;
+ while (t < ss.ahead.known) {
+ const sung = ss.ahead.sung[t][0];
+ const chord: u16 = if (sung.playable) sung.chord else 0;
+ var end = t + 1;
+ while (end < ss.ahead.known and @as(u16, if (ss.ahead.sung[end][0].playable) ss.ahead.sung[end][0].chord else 0) == chord) end += 1;
+ const x0 = strip.x + strip.w * @as(f32, @floatFromInt(t)) / chords.horizon;
+ const x1 = strip.x + strip.w * @as(f32, @floatFromInt(end)) / chords.horizon;
+ const color: sk.Color = if (Grid.find(chord)) |at| sk.Color.hex(row_colors[at.row]).alpha(170) else sk.Color.hex(0x2a2f3a);
+ f.fill(.{ .x = x0, .y = strip.y, .w = @max(x1 - x0, 1), .h = strip.h }, color);
+ t = end;
+ }
+ const at = struct {
+ fn x(r: sk.Rect, time: f64, total: f64) f32 {
+ return r.x + r.w * @as(f32, @floatCast(std.math.clamp(time / total, 0, 1)));
+ }
+ }.x;
+ if (ss.travel) |travel| f.fill(.{ .x = at(strip, travel.to.time(), span) - 1, .y = strip.y - 4, .w = 3, .h = strip.h + 8 }, sk.Color.hex(0xffd84d));
+ f.fill(.{ .x = at(strip, ss.time, span) - 1, .y = strip.y - 3, .w = 2, .h = strip.h + 6 }, sk.Color.white);
+
+ const held: ?u16 = if (ss.held) |h| ss.ahead.sung[h.sample][h.alternative].chord else null;
+ for (0..Grid.rows) |row| for (0..Grid.columns) |column| {
+ const r = l.key(row, column) orelse continue;
+ const chord = Grid.chord(row, column);
+ const found = ss.ahead.found[chord];
+ const lit = chord == now or chord == held;
+ const color = sk.Color.hex(row_colors[row]);
+ f.fill(r, if (lit) color.alpha(230) else if (found) color.alpha(70) else sk.Color.hex(0x12151d));
+ if (found) f.fill(.{ .x = r.x, .y = r.y + r.h - 2, .w = r.w, .h = 2 }, color);
+ const label = f.format("{s}{s}", .{ Grid.root_names[column], Grid.suffix(@enumFromInt(row)) });
+ const ink = if (lit) sk.Color.hex(0x05070d) else if (found) sk.Color.white else sk.Color.white.alpha(60);
+ f.text(r.x + (r.w - @as(f32, @floatFromInt(label.len * 8))) / 2, r.y + r.h / 2 - 4, 1, label, ink);
+ };
+}
+
+fn button(s: *const State, f: *sk.Frame, a: Action, r: sk.Rect) void {
+ const label: []const u8 = switch (a) {
+ .play => if (s.running) "PAUSE" else "PLAY",
+ .reverse => if (s.backward) "FWD" else "REV",
+ .mode => modeName(s.mode),
+ .preset => "NEXT",
+ .eight => "EIGHT",
+ .random => "RANDOM",
+ .instrument => if (s.instrument) "FREE" else "CHORDS",
+ .scale => switch (s.scale) {
+ .free => "UNSNAP",
+ .pentatonic => "PENTA",
+ .diatonic => "DIATON",
+ .chromatic => "CHROMA",
+ },
+ .mute => if (s.muted) "UNMUTE" else "MUTE",
+ else => "",
+ };
+ f.fill(r, sk.Color.hex(0x161a24));
+ f.fill(.{ .x = r.x, .y = r.y + r.h - 1, .w = r.w, .h = 1 }, sk.Color.hex(0x2e3440));
+ f.text(r.x + (r.w - @as(f32, @floatFromInt(label.len * 8))) / 2, r.y + r.h / 2 - 4, 1, label, bright);
+}
+
+fn modeName(m: Mode) []const u8 {
+ return switch (m) {
+ .sine => "SINE",
+ .additive => "ADD",
+ .am => "AM",
+ .ring => "RING",
+ .fm => "FM",
+ .pm => "PM",
+ };
+}
+
+fn modeFormula(m: Mode) []const u8 {
+ return switch (m) {
+ .sine => "sin c",
+ .additive => "sum r^(k-1) sin kc, r = d/(d+2)",
+ .am => "sin c (1 + a sin m)/(1 + a), a = min(d/4, 1)",
+ .ring => "sin c sin m",
+ .fm => "carrier swung d times its frequency by m: index d/ratio",
+ .pm => "sin(c + d sin m): index d",
+ };
+}
+
+/// The modulation index the theory works with: what sets the sidebands.
+fn index(m: Mode, v: layouts.Voice) f32 {
+ return switch (m) {
+ .fm => v.depth / @max(v.ratio, 1e-3),
+ .pm => v.depth,
+ else => 0,
+ };
+}
+
+/// A partial: frequency and amplitude relative to the voice's.
+const Partial = struct { hz: f64, amp: f64 };
+
+/// Where a voice's energy goes, by the textbook: FM and PM put
+/// |J_k(index)| at carrier + k modulator; AM puts a/2 at carrier ±
+/// modulator; ring modulation halves between the two; additive steps
+/// through harmonics.
+fn partials(m: Mode, v: layouts.Voice, out: []Partial) []Partial {
+ const fc: f64 = v.carrier;
+ const fm: f64 = fc * v.ratio;
+ var n: usize = 0;
+ switch (m) {
+ .sine => {
+ out[0] = .{ .hz = fc, .amp = 1 };
+ n = 1;
+ },
+ .additive => {
+ const r = v.depth / (v.depth + 2);
+ var norm: f64 = 0;
+ var w: f64 = 1;
+ for (0..16) |_| {
+ norm += w;
+ w *= r;
+ }
+ w = 1;
+ for (0..16) |k| {
+ out[n] = .{ .hz = fc * @as(f64, @floatFromInt(k + 1)), .amp = w / norm };
+ n += 1;
+ w *= r;
+ }
+ },
+ .am => {
+ const a = @min(v.depth / 4, 1);
+ out[0] = .{ .hz = fc, .amp = 1 / (1 + a) };
+ out[1] = .{ .hz = fc + fm, .amp = a / 2 / (1 + a) };
+ out[2] = .{ .hz = @abs(fc - fm), .amp = a / 2 / (1 + a) };
+ n = 3;
+ },
+ .ring => {
+ out[0] = .{ .hz = fc + fm, .amp = 0.5 };
+ out[1] = .{ .hz = @abs(fc - fm), .amp = 0.5 };
+ n = 2;
+ },
+ .fm, .pm => {
+ const beta: f64 = index(m, v);
+ var k: i32 = -12;
+ while (k <= 12) : (k += 1) {
+ out[n] = .{ .hz = @abs(fc + @as(f64, @floatFromInt(k)) * fm), .amp = @abs(bessel(@intCast(@abs(k)), beta)) };
+ n += 1;
+ }
+ },
+ }
+ return out[0..n];
+}
+
+/// A voice's partials with the FM pair's modulation on top: each of its own
+/// partials spread into sidebands |J_k(index)| at k times the modulating
+/// body's frequency (exact for sine and additive, whose harmonics all get
+/// the same push; a guide for the others).
+fn fmPair(m: Mode, v: layouts.Voice, voices: [3]layouts.Voice, row: [4]f32, own: []Partial, out: []Partial) []Partial {
+ const base = partials(m, v, own);
+ var by: usize = 0;
+ for (0..3) |j| if (row[j] > row[by]) {
+ by = j;
+ };
+ const beta: f64 = row[by];
+ if (beta < 0.05) return base;
+ const fm: f64 = voices[by].carrier;
+ var n: usize = 0;
+ for (base) |p| {
+ var k: i32 = -6;
+ while (k <= 6) : (k += 1) {
+ if (n == out.len) return out;
+ out[n] = .{ .hz = @abs(p.hz + @as(f64, @floatFromInt(k)) * fm), .amp = p.amp * @abs(bessel(@intCast(@abs(k)), beta)) };
+ n += 1;
+ }
+ }
+ return out[0..n];
+}
+
+/// J_n(x), the Bessel function of the first kind, by its series: enough
+/// terms for the indices here (x up to about 24).
+fn bessel(n: u32, x: f64) f64 {
+ const half = x / 2;
+ var term = std.math.pow(f64, half, @floatFromInt(n));
+ for (1..n + 1) |k| term /= @floatFromInt(k);
+ var sum = term;
+ for (1..80) |m| {
+ const mf: f64 = @floatFromInt(m);
+ term *= -half * half / (mf * (mf + @as(f64, @floatFromInt(n))));
+ sum += term;
+ if (@abs(term) < 1e-14 * @abs(sum) and m > 2 * @as(usize, @intFromFloat(@abs(x)))) break;
+ }
+ return sum;
+}
+
+fn spectrumMarks(s: *const State, ss: *const Session, f: *sk.Frame, r: sk.Rect, rate: f64) void {
+ for ([_]f64{ 50, 200, 1000, 5000, 20000 }) |hz| {
+ if (hz > scope.maxFreq(rate)) continue;
+ const x = r.x + scope.place(hz, rate) * r.w;
+ const label = if (hz >= 1000) f.format("{d}k", .{hz / 1000}) else f.format("{d}", .{hz});
+ f.text(@min(x + 3, r.x + r.w - 24), r.y + r.h + 4, 1, label, dim);
+ }
+ var own: [32]Partial = undefined;
+ var buf: [32 * 13]Partial = undefined;
+ for (ss.lead.voices, 0..) |v, i| {
+ const row = ss.lead.coupling[i];
+ if (row[3] > 0.5) continue;
+ const focused = i == s.focus;
+ const color = sk.Color.hex(palette[i]);
+ for (fmPair(s.mode, v, ss.lead.voices, row, &own, &buf)) |p| {
+ if (p.hz < scope.min_freq or p.hz > scope.maxFreq(rate) or p.amp < 1e-4) continue;
+ const x = @round(r.x + scope.place(p.hz, rate) * r.w);
+ // Level in dB of full scale, as the spectrum shows it.
+ const db = 20 * std.math.log10(@max(p.amp * v.amp, 1e-9));
+ const y = r.y + r.h * @as(f32, @floatCast(std.math.clamp(db / scope.floor_db, 0, 1)));
+ if (focused) {
+ f.fill(.{ .x = x, .y = y, .w = 1, .h = r.y + r.h - y }, color.alpha(70));
+ f.fill(.{ .x = x - 3, .y = y - 1, .w = 7, .h = 3 }, color.alpha(230));
+ } else f.fill(.{ .x = x - 2, .y = y, .w = 5, .h = 2 }, color.alpha(150));
+ }
+ }
+}
+
+test "the presets start with the centre of mass at rest" {
+ inline for (@typeInfo(Preset).@"enum".field_names) |field| {
+ const p = start(@field(Preset, field), 1);
+ var momentum: [2]f32 = .{ 0, 0 };
+ for (p.masses, p.bodies) |m, b| {
+ momentum[0] += m * b.vel[0];
+ momentum[1] += m * b.vel[1];
+ }
+ try std.testing.expectApproxEqAbs(@as(f32, 0), momentum[0], 1e-5);
+ try std.testing.expectApproxEqAbs(@as(f32, 0), momentum[1], 1e-5);
+ }
+}
+
+test "Bessel functions, against known values" {
+ try std.testing.expectApproxEqAbs(@as(f64, 1), bessel(0, 0), 1e-12);
+ try std.testing.expectApproxEqAbs(@as(f64, 0.7651976866), bessel(0, 1), 1e-9);
+ try std.testing.expectApproxEqAbs(@as(f64, 0.5767248078), bessel(1, 2), 1e-9);
+ // The first zero of J0: FM's carrier vanishes at index 2.405.
+ try std.testing.expectApproxEqAbs(@as(f64, 0), bessel(0, 2.404825558), 1e-8);
+ try std.testing.expectApproxEqAbs(@as(f64, -0.2459357645), bessel(0, 10), 1e-8);
+}
+
+test "PM's partials hold all the energy" {
+ var buf: [32]Partial = undefined;
+ var energy: f64 = 0;
+ for (partials(.pm, .{ .carrier = 220, .ratio = 1.5, .depth = 3, .amp = 1 }, &buf)) |p| energy += p.amp * p.amp;
+ try std.testing.expectApproxEqAbs(@as(f64, 1), energy, 1e-6);
+}
diff --git a/examples/spheres/test/play.script b/examples/spheres/test/play.script
new file mode 100644
index 0000000..8dbe978
--- /dev/null
+++ b/examples/spheres/test/play.script
@@ -0,0 +1,60 @@
+# Plays each preset and synthesis mode headless; screenshots land in
+# .zig-cache/spheres/ for review.
+frames 120
+# The GPU's blocks reach the speakers' stream.
+expect-audio 1
+expect running true
+expect preset figure_eight
+screenshot .zig-cache/spheres/figure-eight.png
+expect mode additive
+key s
+key s
+key s
+expect mode fm
+frames 30
+key p
+key p
+expect preset pythagorean
+frames 240
+screenshot .zig-cache/spheres/pythagorean.png
+# Time backwards, then paused.
+key left
+expect backward true
+frames 30
+key space
+expect running false
+frames 10
+key space
+key right
+expect backward false
+key tab
+expect focus 1
+key p
+frames 200
+screenshot .zig-cache/spheres/lagrange.png
+# The buttons do what the keys do: pause, a random system, the figure eight.
+click 727 18
+expect running false
+click 1087 18
+expect preset random
+expect running true
+frames 60
+screenshot .zig-cache/spheres/random.png
+click 1015 18
+expect preset figure_eight
+# As an instrument: the look-ahead finds chords, a grid button sends the sky
+# to the nearest time its chord plays, and the sky holds still there.
+key c
+expect instrument true
+frames 200
+# 7 is the number row's C column: C major (bits 0, 4, 7).
+key 7
+expect chord.value 145
+frames 90
+screenshot .zig-cache/spheres/chords.png
+# U is QWERTY's C column, a row down: C minor (bits 0, 3, 7).
+key u
+expect chord.value 137
+frames 60
+key escape
+expect instrument false
diff --git a/examples/spheres/web/icon-192.png b/examples/spheres/web/icon-192.png
new file mode 100644
index 0000000..2a47f3d
--- /dev/null
+++ b/examples/spheres/web/icon-192.png
Binary files differ
diff --git a/examples/spheres/web/icon-512.png b/examples/spheres/web/icon-512.png
new file mode 100644
index 0000000..fb096b8
--- /dev/null
+++ b/examples/spheres/web/icon-512.png
Binary files differ
diff --git a/examples/spheres/web/icon.svg b/examples/spheres/web/icon.svg
new file mode 100644
index 0000000..7ed8bf8
--- /dev/null
+++ b/examples/spheres/web/icon.svg
@@ -0,0 +1,28 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
+ <!-- spheres' icon: the figure-eight orbit, its three bodies glowing in
+ their colours. Full-bleed, so it also works masked. Rendered to the
+ PNGs beside it with: resvg -w N -h N icon.svg icon-N.png -->
+ <defs>
+ <filter id="glow" x="-1" y="-1" width="3" height="3">
+ <feGaussianBlur stdDeviation="14"/>
+ </filter>
+ <linearGradient id="orbit" gradientUnits="userSpaceOnUse" x1="76" y1="0" x2="436" y2="0">
+ <stop offset="0" stop-color="#ffcc59"/>
+ <stop offset="0.5" stop-color="#ff73d1"/>
+ <stop offset="1" stop-color="#66d9ff"/>
+ </linearGradient>
+ </defs>
+ <rect width="512" height="512" fill="#05070d"/>
+ <!-- the figure eight -->
+ <path d="M256 256 C 300 196 436 176 436 256 C 436 336 300 316 256 256 C 212 196 76 176 76 256 C 76 336 212 316 256 256 Z"
+ fill="none" stroke="url(#orbit)" stroke-width="10" opacity="0.8"/>
+ <!-- the bodies: glow, then core -->
+ <g filter="url(#glow)">
+ <circle cx="398" cy="205" r="30" fill="#66d9ff"/>
+ <circle cx="140" cy="307" r="30" fill="#ff73d1"/>
+ <circle cx="256" cy="256" r="30" fill="#ffcc59"/>
+ </g>
+ <circle cx="398" cy="205" r="15" fill="#e6f8ff"/>
+ <circle cx="140" cy="307" r="15" fill="#ffe6f6"/>
+ <circle cx="256" cy="256" r="15" fill="#fff4dc"/>
+</svg>
diff --git a/examples/talk.zig b/examples/talk.zig
new file mode 100644
index 0000000..2ad3d70
--- /dev/null
+++ b/examples/talk.zig
@@ -0,0 +1,160 @@
+//! A talk in a sketch of its own: the sketch keeps an `anim.Deck` in its
+//! State beside its own data, decides which keys and clicks step the talk,
+//! and paints with an `anim.Painter`. The talk is a function run from the
+//! top every frame; it may change the app in `update` (`anim.mutable`),
+//! so the slider below is laid out, drawn and hit-tested in one place.
+//!
+//! click, space, right, page down next step left, page up back
+//! ] / [ next / previous slide
+const std = @import("std");
+const sk = @import("sketch");
+const anim = @import("anim");
+/// This file's Typst, compiled at build time (`sb.addTypst`).
+const svgs = @import("typst");
+
+pub const name = "talk";
+pub const width = anim.width;
+pub const height = anim.height;
+
+pub const typst_preamble =
+ \\#set page(width: auto, height: auto, margin: 3pt, fill: none)
+ \\#set text(fill: rgb("#ece6e2"), size: 28pt)
+;
+pub const typst = struct {
+ pub const title = "#text(size: 40pt, weight: \"bold\")[Damping]";
+ pub const law = "$ x'' + 2 zeta x' + x = 0 $";
+ pub const hint = "#text(size: 18pt, fill: rgb(\"#58c4dd\"))[drag $zeta$, then go on]";
+ pub const rings = "#text(size: 24pt)[$zeta < 1$: it rings]";
+ pub const creeps = "#text(size: 24pt)[$zeta >= 1$: it creeps back]";
+ pub const end = "#text(size: 32pt)[$zeta = 1$: home fastest, no overshoot]";
+};
+/// What the build compiles.
+pub const scene = struct {
+ pub const typst_sources = anim.sources(.{typst});
+};
+
+const App = struct {
+ zeta: f32 = 0.2,
+ /// The slider is held.
+ dragging: bool = false,
+};
+
+pub const State = struct {
+ deck: anim.Deck = .{ .hold = 2 },
+ app: App = .{},
+};
+
+pub const Session = struct {
+ painter: anim.Painter = .{},
+};
+
+pub fn update(s: *State, in: *const sk.Input) void {
+ var ask: anim.Ask = .{};
+ for (in.events) |e| switch (e.kind) {
+ // Every click is the presenter's, unless the talk takes it.
+ .mouse_up => ask.next = true,
+ .key_down => switch (e.key()) {
+ .space, .right, .page_down => ask.next = true,
+ .left, .page_up => ask.back = true,
+ .right_bracket => ask.next_slide = true,
+ .left_bracket => ask.back_slide = true,
+ else => {},
+ },
+ else => {},
+ };
+ s.deck.update(in, ask, talk, .{&s.app});
+}
+
+pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void {
+ const mouse = anim.Deck.pointer(f.in, f.in.mouse_x, f.in.mouse_y);
+ const shot = s.deck.shot(f.scratch, f.in, mouse, talk, .{&s.app}) catch |err| return f.host.print("talk: {t}", .{err});
+ ss.painter.paint(f, shot, svgs, .{}) catch |err| f.host.print("paint: {t}", .{err});
+ if (f.in.exporting and s.deck.t >= shot.duration) f.quit();
+}
+
+/// Run in `update` with `app: *App`, and drawn with `app: *const App`.
+fn talk(s: *anim.Frame, app: anytype) void {
+ // Slide 1: the law, and a mass on a spring that bobs while we talk.
+ s.slide();
+ const title = s.typst(typst.title, .{ .y = -270 });
+ const law = s.typst(typst.law, .{ .y = -180 });
+ const mass = s.rect(.{ .w = 60, .h = 60, .fill = anim.blue });
+ s.play(.{ title.write(), law.write() }, .{});
+ s.play(.{mass.fadeIn()}, .{ .seconds = 0.5 });
+ s.loop(bob, .{mass});
+ s.pause();
+
+ // The slider, laid out before the gate it waits at: a click on it is
+ // its own, not the presenter's.
+ const plot = s.custom(s.new(Plot{ .zeta = app.zeta }), .{});
+ const hint = s.typst(typst.hint, .{ .y = 290 });
+ s.play(.{ mass.fadeOut(), plot.fadeIn(), hint.fadeIn() }, .{ .seconds = 0.6 });
+ if (anim.mutable(app)) |a| if (s.pose(plot).visible) drag(s, a);
+ // A choice: the regime the slider is in when the presenter goes on.
+ const regime = s.gate(if (s.next) @intFromBool(app.zeta >= 1) else null) orelse return;
+ const verdict = s.typst(if (regime == 0) typst.rings else typst.creeps, .{ .y = 290 });
+ s.play(.{ hint.fadeOut(), verdict.write() }, .{ .seconds = 1 });
+ s.pause();
+
+ // Slide 2, written while slide 1 goes.
+ s.beside(anim.Frame.clear, .{.{ .seconds = 0.8 }});
+ s.slide();
+ s.play(.{s.typst(typst.end, .{}).write()}, .{});
+}
+
+/// Down and up again, in a second.
+fn bob(s: *anim.Frame, mass: anim.Obj) void {
+ s.play(.{mass.move(.{ .y = 80 })}, .{ .seconds = 0.5 });
+ s.play(.{mass.move(.{ .y = 0 })}, .{ .seconds = 0.5 });
+}
+
+/// The slider's track, in scene units: zeta from 0 to 2 along it.
+const track: sk.Rect = .{ .x = -300, .y = 200, .w = 600, .h = 40 };
+
+/// The slider follows a press on it to where it is let go, and takes that
+/// click: it is not the presenter's next.
+fn drag(s: *anim.Frame, app: *App) void {
+ for (s.events) |e| {
+ if (e.kind != .mouse_down and e.kind != .mouse_move and e.kind != .mouse_up) continue;
+ if (e.kind == .mouse_down) app.dragging = track.contains(e.x, e.y);
+ if (!app.dragging) continue;
+ app.zeta = std.math.clamp((e.x - track.x) / track.w * 2, 0, 2);
+ if (e.kind == .mouse_up) {
+ app.dragging = false;
+ s.next = false;
+ }
+ }
+}
+
+/// The motion zeta makes, x(t) from x = 1 at rest, over the slider: a
+/// custom object at the scene's origin, so its units are scene units.
+const Plot = struct {
+ zeta: f32,
+
+ pub fn draw(p: *const Plot, f: *sk.Frame, at: anim.Placed) void {
+ var points: [121]sk.math.Vec = undefined;
+ for (&points, 0..) |*q, i| {
+ const t: f32 = @as(f32, @floatFromInt(i)) / 10;
+ q.* = .{ -300 + 50 * t, 60 - 120 * response(p.zeta, t) };
+ }
+ sk.draw.line(f, .{ -300, 60 }, .{ 300, 60 }, at.pen(.{ .stroke = .hex(0x8c8c8c), .width = 1 }));
+ sk.draw.polyline(f, &points, at.pen(.{ .stroke = .hex(anim.yellow), .width = 3 }));
+ sk.draw.rect(f, .{ .x = track.x, .y = track.y + 18, .w = track.w, .h = 4 }, at.pen(.{ .fill = .hex(0x8c8c8c) }));
+ sk.draw.circle(f, .{ track.x + p.zeta / 2 * track.w, track.y + 20 }, 14, at.pen(.{ .fill = .hex(anim.blue) }));
+ var label: [16]u8 = undefined;
+ at.text(f, track.x + p.zeta / 2 * track.w - 30, track.y - 22, 1.5, std.fmt.bufPrint(&label, "{d:.2}", .{p.zeta}) catch "", .white);
+ }
+};
+
+/// x(t) of x'' + 2 zeta x' + x = 0 from x = 1, x' = 0.
+fn response(zeta: f32, t: f32) f32 {
+ if (zeta < 1) {
+ const w = @sqrt(1 - zeta * zeta);
+ return @exp(-zeta * t) * (@cos(w * t) + zeta / w * @sin(w * t));
+ }
+ if (zeta == 1) return @exp(-t) * (1 + t);
+ const r = @sqrt(zeta * zeta - 1);
+ const a = -zeta + r;
+ const b = -zeta - r;
+ return (b * @exp(a * t) - a * @exp(b * t)) / (b - a);
+}
diff --git a/examples/vecanim/README.md b/examples/vecanim/README.md
index 7627fe4..cc6dc0e 100644
--- a/examples/vecanim/README.md
+++ b/examples/vecanim/README.md
@@ -18,18 +18,19 @@ zig build export -- - --size 3840x2160 --fps 60 |
ffmpeg -f rawvideo -pix_fmt rgba -s 3840x2160 -r 60 -i - -pix_fmt yuv420p intro.mp4
```
-Keys: space pause, click to continue after a `pause`, left/right
-previous/next play, `,`/`.` step a frame, home/end, up/down speed, B GPU/CPU,
-L loop, G guides (bounding boxes, origins and the scene's axes, with scene
-coordinates and the pointer's); drag and wheel to look around, R to reset
-the view.
+Keys: click, space or page down for the next step of a scene that pauses
+(space plays and pauses one that does not), page up back a step, `]`/`[`
+next/previous slide, P play/pause, left/right previous/next play, `,`/`.`
+step a frame, home/end, up/down speed, B GPU/CPU, L loop, G guides
+(bounding boxes, origins and the scene's axes, with scene coordinates and
+the pointer's); drag and wheel to look around, R to reset the view.
- `scenes/intro.zig`, compiled: shapes, Pythagoras morphing from one
equation to the next, a camera move with an updater swinging an arrow,
Typst math and a paragraph.
- `scenes/live.zig`, live, presented like slides: a wave of dots whose
- height the timeline animates, whose phase is the wall clock, and which
- rise to meet the mouse.
+ height the timeline animates, whose phase runs on while a pause waits,
+ and which rise to meet the mouse.
`build.zig` lists the scenes with the script `zig build test` plays each
through (screenshots in `.zig-cache/e2e`). `-Dscene` picks the one `run`,
diff --git a/examples/vecanim/scenes/live.zig b/examples/vecanim/scenes/live.zig
index cefdbc5..9b94d17 100644
--- a/examples/vecanim/scenes/live.zig
+++ b/examples/vecanim/scenes/live.zig
@@ -1,6 +1,7 @@
//! A live scene, presented like slides: `frame` runs every frame, so the
-//! code after the plays can follow the mouse, the clock or any data, and
-//! `pause` holds until a click. Everything it needs is in this file.
+//! code after the plays can follow the mouse, the time or any data, and
+//! what comes after a `pause` waits for a click while time runs on.
+//! Everything it needs is in this file.
const anim = @import("anim");
pub const typst_preamble =
@@ -28,7 +29,7 @@ fn frame(s: *anim.Frame) void {
s.play(.{ title.fadeOut(), hint.fadeOut() }, .{ .seconds = 0.6 });
// A wave of dots: its height is a value the timeline animates, its
- // phase the wall clock, which runs on through pauses.
+ // phase the scene's time, which runs on while a pause waits.
const wave = s.typst(typst.wave, .{ .y = -220, .scale = 1.2 });
const note = s.typst(typst.note, .{ .y = 230 });
const height = s.value(0);
@@ -61,7 +62,7 @@ fn frame(s: *anim.Frame) void {
for (dots) |d| {
const p = s.pose(d);
const envelope = 1 - s.get(damping) * (1 - @exp(-p.x * p.x / 1e5));
- p.y = s.get(height) * envelope * @sin(p.x / 90 - s.clock * 2);
+ p.y = s.get(height) * envelope * @sin(p.x / 90 - s.t * 2);
const near = @max(0, 1 - @abs(p.x - s.pointer[0]) / 120);
p.scale = 1 + near;
p.y -= 40 * near;
diff --git a/examples/vecanim/test/intro.script b/examples/vecanim/test/intro.script
index 75ce751..9dd61bb 100644
--- a/examples/vecanim/test/intro.script
+++ b/examples/vecanim/test/intro.script
@@ -2,28 +2,28 @@
# then the same instants on the CPU renderer.
frames 60
screenshot .zig-cache/e2e/title.png
-console set t 7.5
+console set deck.t 7.5
frames 1
screenshot .zig-cache/e2e/shapes.png
-console set t 13
+console set deck.t 13
frames 1
screenshot .zig-cache/e2e/morph.png
-console set t 16.5
+console set deck.t 16.5
frames 1
screenshot .zig-cache/e2e/zoom.png
-console set t 24
+console set deck.t 24
frames 1
screenshot .zig-cache/e2e/text.png
key b
expect backend cpu
-console set t 13
+console set deck.t 13
frames 1
screenshot .zig-cache/e2e/morph-cpu.png
-console set t 24
+console set deck.t 24
frames 1
screenshot .zig-cache/e2e/text-cpu.png
key g
expect guides true
-console set t 16.5
+console set deck.t 16.5
frames 1
screenshot .zig-cache/e2e/guides.png
diff --git a/examples/vecanim/test/live.script b/examples/vecanim/test/live.script
index a3ddcdc..d955b6f 100644
--- a/examples/vecanim/test/live.script
+++ b/examples/vecanim/test/live.script
@@ -1,5 +1,6 @@
-# Plays the live scene headless: it holds at each pause until a click, the
-# dots follow the pointer, and the guides draw over everything.
+# Plays the live scene headless: it waits at each pause for a click, the
+# wave running on, the dots follow the pointer, and the guides draw over
+# everything.
frames 150
expect t 2
screenshot .zig-cache/e2e/live-title.png
diff --git a/src/abi.zig b/src/abi.zig
index 7177f14..6411b0d 100644
--- a/src/abi.zig
+++ b/src/abi.zig
@@ -5,11 +5,13 @@
//! tagged unions, `std.mem.Allocator`. Two rules keep reloads safe:
//! - whatever outlives a call lives in host memory (host code is never
//! unloaded, so host allocators and function pointers stay valid);
-//! - `hash` covers the layout of every type here, and a host refuses a sketch
-//! built against different definitions instead of misreading its memory.
+//! - `hash` covers the layout of every type here and the compiler, backend
+//! and mode, and a host refuses a sketch built against different
+//! definitions or by another build instead of misreading its memory.
//!
//! Only `Event` and the reflected `Layout` are `extern`: they are written to disk.
const std = @import("std");
+const builtin = @import("builtin");
pub const layout = @import("layout.zig");
pub const Key = @import("keys.zig").Key;
@@ -114,6 +116,11 @@ pub const Event = extern struct {
/// `flags` bit for a held key's auto-repeat.
pub const repeat: u8 = 1;
+ /// The key of a `key_down` or `key_up`.
+ pub fn key(e: Event) Key {
+ return @fromBackingInt(@intCast(@as(u8, @truncate(e.code))));
+ }
+
/// For mouse and wheel events: the modifier keys held as it happened,
/// as `Key.Mod` bits. Read this rather than `Input.held`, which is the
/// state after the frame's events, and misses modifiers that come with
@@ -158,6 +165,9 @@ pub const Stream = struct {
queued: u32 = 0,
/// Samples pushed since the stream was last cleared.
pushed: u64 = 0,
+ /// Pushes that found it empty though the frame before had pushed to
+ /// it: each a gap in its sound.
+ underruns: u32 = 0,
};
/// Everything a sketch learns about the world for one call.
@@ -211,6 +221,11 @@ pub const Input = struct {
keys: std.StaticBitSet(256) = .empty,
streams: []const Stream = &.{},
sample_rate: u32 = 48_000,
+ /// How many samples a stream should hold after this frame's push, as
+ /// the host measures it: enough to outlast the slowest recent frame and
+ /// the device's next pull, and more after an underrun. A sketch that
+ /// makes its sound as it goes pushes `lead -| stream(key).queued`.
+ lead: u32 = 4800,
/// Mono samples at `sample_rate` recorded since the previous frame, while
/// `draw` declares `Command.microphone`. Only `draw` sees them: they come
/// from a device, not from events, so they do not replay.
@@ -296,13 +311,18 @@ pub const Voice = struct {
volume: f32 = 1,
/// Linear fade at both ends, in samples.
fade: u32 = 0,
+ /// Playback speed, as pitch: 2 is an octave up and half as long, 0
+ /// holds it. Changing it does not restart the voice.
+ rate: f32 = 1,
+ /// Whose gain (`Command.gain`) also scales it: music, speech, effects.
+ group: u3 = 0,
};
/// Slices must stay alive until the host consumes the frame, right after
/// `draw` returns. `sketch.Frame` copies the small ones (text, GPU
/// descriptions, uniforms) into scratch memory itself; bulk data (vertices,
-/// samples, pixels, uploads) must already live in scratch, session or store
-/// memory, or be a literal.
+/// samples, pixels, uploads) must already live in scratch or session memory,
+/// or be a literal.
pub const Command = union(enum) {
clear: Color,
rect: struct { dst: Rect, color: Color },
@@ -365,6 +385,15 @@ pub const Command = union(enum) {
voice: Voice,
/// Mono samples at `Input.sample_rate` for stream `key`.
audio: struct { key: u32, samples: []const f32, clear: bool = false },
+ /// `count` mono samples (f32) that a compute shader left in `buffer`
+ /// at `offset`, for stream `key`: queued like `audio`'s once the GPU
+ /// has made them. Natively that is within this frame (the host waits
+ /// for the GPU's work so far); on the web they arrive a frame or two
+ /// later and count as queued meanwhile.
+ audio_buffer: struct { key: u32, buffer: Buffer, offset: u32 = 0, count: u32 },
+ /// The gain of a group of voices (`Voice.group`) this frame; a group
+ /// not given one plays at 1. Declared like a voice, so it replays.
+ gain: struct { group: u3, gain: f32 },
/// RGBA8 rows of `w * 4` bytes into an image made by `Host.newImage`.
pixels: struct { image: Image, w: u32, h: u32, rgba: []const u8, premultiplied: bool = false },
/// Renders a GPU pass into an image made by `Host.newImage`, when
@@ -625,12 +654,16 @@ pub const Host = struct {
/// WAV, FLAC or Ogg Vorbis bytes in memory. Not cached. `.none` if
/// they do not decode.
decodeSound: *const fn (*anyopaque, []const u8) Audio,
+ /// Samples a sketch made, copied: see `Host.newSound`.
+ newSound: *const fn (*anyopaque, [*]const f32, usize) callconv(.c) Audio,
/// A loaded sound's samples: mono, at `Input.sample_rate`, alive as
/// long as the host. Empty for `.none`.
samples: *const fn (*anyopaque, Audio) []const f32,
/// The whole file, mapped for the life of the host; empty if missing.
readFile: *const fn (*anyopaque, []const u8) []const u8,
- env: *const fn (*anyopaque, []const u8) ?[]const u8,
+ /// See `Host.appendFile`: name, then bytes; `replace` for `writeFile`.
+ appendFile: *const fn (*anyopaque, [*]const u8, usize, [*]const u8, usize, bool) callconv(.c) [*:0]const u8,
+ env:*const fn (*anyopaque, []const u8) ?[]const u8,
/// A monotonic clock in nanoseconds, for measuring, not for state:
/// `update` must use `Input` time to stay replayable.
clock: *const fn (*anyopaque) u64,
@@ -689,12 +722,35 @@ pub const Host = struct {
pub fn decodeSound(h: Host, wav: []const u8) Audio {
return h.vtable.decodeSound(h.ctx, wav);
}
+ /// Mono samples at `Input.sample_rate`, copied into the host: a sound
+ /// for `Voice.audio` like a loaded one (synthesised one-shots become
+ /// voices, reconciled and replay-safe). Kept for the life of the host,
+ /// like every sound: make each once (in `setup`, or cached in Session).
+ /// `.none` if a sample is not finite.
+ pub fn newSound(h: Host, sound: []const f32) Audio {
+ return h.vtable.newSound(h.ctx, sound.ptr, sound.len);
+ }
pub fn samples(h: Host, audio: Audio) []const f32 {
return h.vtable.samples(h.ctx, audio);
}
pub fn readFile(h: Host, path: []const u8) []const u8 {
return h.vtable.readFile(h.ctx, path);
}
+ /// Appends `bytes` to the sketch's file `name` (no `/` in it),
+ /// creating it: `<stem>.<name>`, beside the save `<stem>.xitdb` (in
+ /// `.sketchbook/` under `zig build run`). Returns the file's path, for
+ /// `readFile`, or "" when nothing was written, which on the web is
+ /// always. Only `draw` and `command` can write, and a write is not
+ /// replayed, like sound. `readFile` maps a file once: what is appended
+ /// to it afterwards is not in what it returned.
+ pub fn appendFile(h: Host, name: []const u8, bytes: []const u8) []const u8 {
+ return std.mem.span(h.vtable.appendFile(h.ctx, name.ptr, name.len, bytes.ptr, bytes.len, false));
+ }
+ /// `appendFile` to a new, empty file of that name: what the old one
+ /// held is gone (a `readFile` of it keeps its bytes).
+ pub fn writeFile(h: Host, name: []const u8, bytes: []const u8) []const u8 {
+ return std.mem.span(h.vtable.appendFile(h.ctx, name.ptr, name.len, bytes.ptr, bytes.len, true));
+ }
pub fn env(h: Host, name: []const u8) ?[]const u8 {
return h.vtable.env(h.ctx, name);
}
@@ -714,12 +770,8 @@ pub const Context = struct {
/// This process: survives reloads; frees one allocation at a time, and
/// releases the rest when Session's layout changes.
session: std.mem.Allocator,
- /// On disk, next to the state file: survives reloads and restarts, at
- /// the same addresses, so Store may point into it.
- store: std.mem.Allocator,
- /// The sketch's `Session` and `Store` values.
+ /// The sketch's `Session` value.
session_root: [*]u8,
- store_root: [*]u8,
/// Filled by `draw`, using `scratch`.
commands: *std.ArrayList(Command),
};
@@ -768,13 +820,23 @@ pub const Info = struct {
height: u32,
state: Layout,
session: Layout,
- store: Layout,
/// Console completions offered by the sketch.
commands: []const []const u8 = &.{},
+ /// What the sketch was built from: its repository's revision ("jj:<commit>
+ /// <change>", "git:<sha>[+dirty]", or nothing), then `build`. Each
+ /// stretch of a recorded session keeps it.
+ source: []const u8 = "",
+ /// Whether the save keeps history, or only the present and the marks
+ /// (`App.Options.record`; Debug builds keep it unless told otherwise).
+ record: bool = false,
+ /// Samples the sound device takes at once, asked of SDL when the host
+ /// opens it (`SDL_AUDIO_DEVICE_SAMPLE_FRAMES` in the environment wins);
+ /// 0 is SDL's own, 1024 at 48 kHz. The app's `audio_pull`.
+ audio_pull: u32 = 0,
};
/// Which memory `sketch_defaults` fills.
-pub const Memory = enum(u8) { state, session, store };
+pub const Memory = enum(u8) { state, session };
/// The entry points of a sketch, exported from libraries under these names.
/// What became of a console line offered to a sketch.
@@ -796,8 +858,7 @@ pub const Sketch = struct {
setup: *const fn (*const Context) callconv(.c) bool,
/// Deterministic: new state from state and input, nothing else.
update: *const fn (*const Context, [*]u8) callconv(.c) void,
- /// Presentation: reads state, may change session and store, appends
- /// commands.
+ /// Presentation: reads state, may change session, appends commands.
draw: *const fn (*const Context, [*]const u8) callconv(.c) void,
/// A console line the host did not understand.
command: *const fn (*const Context, [*]u8, *const []const u8) callconv(.c) Outcome,
@@ -813,8 +874,16 @@ pub const Sketch = struct {
};
};
-/// Layout hash of everything above. Changes whenever a shared type does.
-pub const hash: u64 = blk: {
+/// `layout_hash` and `build`: changes whenever a shared type does, or the
+/// compiler, backend or optimize mode, since Zig's own calling convention
+/// (`Host.VTable`, every `std.mem.Allocator`) differs between them.
+/// `layout_hash` costs half a second of comptime, so build.zig has
+/// `abi_hash.zig` compute it once per change of these files and hands it
+/// over as the module `abi_hash`, instead of every sketch's compile doing it.
+pub const hash: u64 = std.hash.Wyhash.hash(@import("abi_hash").layout, build);
+
+/// Hash of every shared type's name and layout.
+pub const layout_hash: u64 = blk: {
@setEvalBranchQuota(1_000_000);
var h: u64 = 0;
for (.{ Rect, Color, BlendMode, Corners, Event, Mode, Stream, Input, Image, Audio, Cursor, Voice, Command, gpu.Pass, gpu.Pipeline, gpu.Draw, gpu.Dispatch, gpu.PostProcess, Host, Host.VTable, Context, Field, Layout, Info, Memory, Sketch }) |T| {
@@ -823,6 +892,10 @@ pub const hash: u64 = blk: {
break :blk h;
};
+/// The compiler, backend and mode of this build, exported by libraries as
+/// `sketch_build` so a host can say why it refuses one.
+pub const build = builtin.zig_version_string ++ " " ++ @tagName(builtin.zig_backend) ++ " " ++ @tagName(builtin.mode);
+
test "vertex attributes and std140 checks come from the types" {
const Vertex = extern struct { position: [2]f32, color: [4]u8, uv: [2]f32 };
const attrs = gpu.attributes(Vertex);
diff --git a/src/abi_hash.zig b/src/abi_hash.zig
new file mode 100644
index 0000000..9cd01cf
--- /dev/null
+++ b/src/abi_hash.zig
@@ -0,0 +1,9 @@
+//! Prints `abi.layout_hash` as Zig source: build.zig runs this once per change
+//! of the abi sources and hands the result to host and sketches as the module
+//! `abi_hash`.
+const std = @import("std");
+const abi = @import("abi");
+
+pub fn main(init: std.process.Init) !void {
+ try std.Io.File.stdout().writeStreamingAll(init.io, std.fmt.comptimePrint("pub const layout: u64 = 0x{x};\n", .{abi.layout_hash}));
+}
diff --git a/src/anim/Painter.zig b/src/anim/Painter.zig
new file mode 100644
index 0000000..f317dc1
--- /dev/null
+++ b/src/anim/Painter.zig
@@ -0,0 +1,262 @@
+//! Draws a scene's `Shot` with the vector library, on the GPU (or the CPU),
+//! the scene's frame fitted into the canvas, and the canvas the room the
+//! host has: the window, or an export's `--size`. The player paints with
+//! one, and so does a sketch that runs a `Deck` itself: a `Painter` in its
+//! Session, and `paint` once a frame.
+const std = @import("std");
+const sk = @import("sketch");
+const vector = @import("vector");
+const anim = @import("root.zig");
+const geom = vector.geom;
+
+const Painter = @This();
+
+/// A renderer per run of vector objects between custom ones (`paint`).
+gpu: std.ArrayList(vector.Renderer(.gpu)) = .empty,
+cpu: std.ArrayList(vector.Renderer(.cpu)) = .empty,
+/// Drawings by what they look like (`Object.id`), built on first use and
+/// dropped on reload, since the code that builds them may have changed.
+/// Their memory is the host's, kept across reloads.
+arena: ?std.heap.ArenaAllocator = null,
+drawings: std.AutoHashMapUnmanaged(u64, Built) = .empty,
+/// Shapes drawn in the last frame.
+shapes: usize = 0,
+
+pub const Options = struct {
+ /// The viewer's own pan and zoom, on top of the scene's camera.
+ view: sk.Camera = .{},
+ backend: vector.Backend = .gpu,
+ /// Boxes, origins and axes, in scene units, with their numbers.
+ guides: bool = false,
+ /// The page (0xRRGGBB).
+ background: u32 = anim.background,
+};
+
+const Built = struct { drawing: vector.Drawing, bounds: geom.Rect };
+
+/// Sets the canvas to the window and draws `shot` on it. `svgs` has
+/// `find(source) ?[]const u8` for its Typst objects (`sb.addTypst`).
+pub fn paint(p: *Painter, f: *sk.Frame, shot: anim.Shot, svgs: anytype, options: Options) !void {
+ // All the room there is: the window, or the size an export asks for.
+ const canvas: sk.Rect = .{ .w = @max(@floor(f.in.window_width), 1), .h = @max(@floor(f.in.window_height), 1) };
+ f.canvas(@intFromFloat(canvas.w), @intFromFloat(canvas.h));
+ if (p.arena == null) p.arena = .init(f.session);
+ // A live scene may make new drawings every frame: start over now and then.
+ if (f.in.reloaded or p.drawings.count() > 1024) {
+ _ = p.arena.?.reset(.retain_capacity);
+ p.drawings = .empty;
+ }
+ // Use the host's GPU when it has one.
+ if (options.backend == .gpu and f.host.gpu()) try p.paintLayers(&p.gpu, f, shot, svgs, canvas, options) else try p.paintLayers(&p.cpu, f, shot, svgs, canvas, options);
+}
+
+/// Canvas pixels per scene unit: the scene's frame, fitted into `canvas`.
+pub fn fit(canvas: sk.Rect) f32 {
+ return @min(canvas.w / anim.width, canvas.h / anim.height);
+}
+
+/// Object `o`'s drawing, centered on its origin, and its bounds.
+fn built(p: *Painter, o: anim.Object, svgs: anytype) anim.BuildError!Built {
+ const id = o.id();
+ if (p.drawings.get(id)) |b| return b;
+ const arena = p.arena.?.allocator();
+ // A part, or what is left of an object parts were taken from: shapes
+ // of a whole drawing, which is built (parsed) once.
+ const d = if (o.source == .part or o.cut.len > 0) try anim.sift(arena, (try p.built(o.whole(), svgs)).drawing, o) else try anim.build(arena, o, svgs);
+ const b: Built = .{ .drawing = d, .bounds = d.bounds().rect() };
+ try p.drawings.put(arena, id, b);
+ return b;
+}
+
+/// Scene units to canvas pixels: the scene's camera, then the viewer's.
+/// The scene's origin is the canvas center.
+fn stage(view: sk.Camera, cam: anim.Camera, canvas: sk.Rect) geom.Affine {
+ const k = fit(canvas) * cam.zoom;
+ return geom.Affine.translate(view.x, view.y)
+ .mul(.scale(view.zoom, view.zoom))
+ .mul(.translate(canvas.w / 2, canvas.h / 2))
+ .mul(.scale(k, k))
+ .mul(.rotate(-cam.rotation))
+ .mul(.translate(-cam.x, -cam.y));
+}
+
+/// The next of `layers`, begun: a renderer the size of the canvas.
+fn begun(layers: anytype, used: *usize, f: *sk.Frame, canvas: sk.Rect, clear: vector.Drawing.Color) !*@TypeOf(layers.items[0]) {
+ if (used.* == layers.items.len) try layers.append(f.session, try .init(f.session, f.host, @intFromFloat(canvas.w), @intFromFloat(canvas.h)));
+ const r = &layers.items[used.*];
+ used.* += 1;
+ r.begin(f, clear);
+ return r;
+}
+
+/// Draws `shot` with the renderers in `layers` (either backend), objects
+/// in the order they were added. Vector objects go into a renderer's image,
+/// which is then drawn on the canvas; a custom object draws on the canvas
+/// itself. So the vector objects before a custom one and those after it
+/// are separate images, one renderer each: every GPU pass of a frame runs
+/// before its first 2D command, and one image could only show the last.
+fn paintLayers(p: *Painter, layers: anytype, f: *sk.Frame, shot: anim.Shot, svgs: anytype, canvas: sk.Rect, options: Options) !void {
+ if (layers.items.len > 0 and (layers.items[0].width() != @as(u32, @intFromFloat(canvas.w)) or layers.items[0].height() != @as(u32, @intFromFloat(canvas.h)))) {
+ for (layers.items) |*r| r.deinit(f.host);
+ layers.clearRetainingCapacity();
+ }
+ const world = stage(options.view, shot.camera, canvas);
+ var used: usize = 0;
+ // The first layer is the background too.
+ var open: ?*@TypeOf(layers.items[0]) = try begun(layers, &used, f, canvas, anim.color(options.background));
+ var shapes: usize = 0;
+ for (shot.objects, shot.poses, 0..) |o, pose, i| {
+ if (!pose.visible or pose.opacity <= 0) continue;
+ const m = world.mul(model(pose));
+ if (o.source == .custom) {
+ if (open) |r| r.present(f, canvas);
+ open = null;
+ o.source.custom.draw(o.source.custom.ctx, f, .{ .t = shot.t, .pose = pose, .xf = m, .scale = m.scaleFactor(), .stage = world, .values = shot.values });
+ // It leaves no target, clip or blend behind.
+ f.target(.none);
+ f.blend(.alpha);
+ continue;
+ }
+ const r = open orelse try begun(layers, &used, f, canvas, .{ 0, 0, 0, 0 });
+ open = r;
+ const d = (try p.built(o, svgs)).drawing;
+ if (pose.into != anim.Pose.none and pose.morph > 0 and pose.morph < 1 and shot.objects[pose.into].source != .custom) {
+ // Morphing: from where this object began the transform to where
+ // its target will stand.
+ const morph = shot.morphs[i];
+ // Into the whole target, parts and all: parts taken from it
+ // once it is made stand where they were and show as it does.
+ var into = shot.objects[pose.into];
+ into.cut = &.{};
+ const target = (try p.built(into, svgs)).drawing;
+ const between = try vector.morph.between(f.scratch, d, world.mul(model(morph.from)), target, world.mul(model(morph.to)), pose.morph);
+ try r.draw(between, .identity, pose.opacity);
+ shapes += between.shapes.len;
+ continue;
+ }
+ try reveal(r, d, m, pose, fit(canvas));
+ shapes += d.shapes.len;
+ }
+ if (options.guides) {
+ const r = open orelse try begun(layers, &used, f, canvas, .{ 0, 0, 0, 0 });
+ open = r;
+ try r.draw(try p.guides(f.scratch, shot, svgs, world, canvas), .identity, 1);
+ }
+ if (open) |r| r.present(f, canvas);
+ p.shapes = shapes;
+ if (options.guides) try p.labels(f, shot, svgs, world);
+}
+
+fn model(p: anim.Pose) geom.Affine {
+ return geom.Affine.translate(p.x, p.y).mul(.rotate(p.rotation)).mul(.scale(p.scale, p.scale));
+}
+
+/// manim's reveals, shape by shape with a stagger: Write traces each outline
+/// then fills it; Create draws strokes along their length, then fills.
+/// Outlines are `k` canvas pixels to the scene unit wide.
+fn reveal(r: anytype, d: vector.Drawing, m: geom.Affine, pose: anim.Pose, k: f32) !void {
+ const n: f32 = @floatFromInt(d.shapes.len);
+ const lag: f32 = if (pose.drawn >= 1) 0 else 0.08;
+ const window = 1 / (1 + lag * @max(n - 1, 0));
+ const glow = pose.highlight;
+ for (d.shapes, 0..) |shape, i| {
+ const local = std.math.clamp((pose.drawn - @as(f32, @floatFromInt(i)) * lag * window) / window, 0, 1);
+ if (local <= 0) continue;
+ var o: vector.Options = .{ .alpha = pose.opacity };
+ switch (pose.reveal) {
+ .write => if (local < 1) {
+ o.trim = @min(local * 2, 1);
+ o.outline = .{ .width = 1.5 * k, .alpha = 1 - std.math.clamp(local * 2 - 1, 0, 1) };
+ o.stroke = false;
+ // Fill arrives in the second half.
+ var fill = o;
+ fill.outline = null;
+ fill.alpha = pose.opacity * std.math.clamp(local * 2 - 1, 0, 1);
+ try r.drawShape(d, shape, m, fill);
+ o.fill = false;
+ },
+ .create => if (local < 1) {
+ o.trim = local;
+ if (shape.style.stroke == .none) o.outline = .{ .width = 2 * k };
+ var fill = o;
+ fill.stroke = false;
+ fill.outline = null;
+ fill.alpha = pose.opacity * std.math.clamp(local * 3 - 2, 0, 1);
+ try r.drawShape(d, shape, m, fill);
+ o.fill = false;
+ },
+ }
+ try r.drawShape(d, shape, m, o);
+ if (glow > 0) {
+ // Indicate: a yellow glow over the shape.
+ var hot = shape;
+ hot.style.fill = if (shape.style.fill != .none) .{ .color = anim.color(anim.yellow) } else .none;
+ hot.style.stroke = if (shape.style.stroke != .none) .{ .color = anim.color(anim.yellow) } else .none;
+ try r.drawShape(d, hot, m, .{ .alpha = pose.opacity * glow });
+ }
+ }
+}
+
+/// Spacing of the guides' ticks, in scene units.
+const tick = 100;
+
+fn guideStyle(c: u32, w: f32) vector.Drawing.Style {
+ return .{ .fill = .none, .stroke = .{ .color = anim.color(c) }, .stroke_width = w };
+}
+
+/// The scene's axes with ticks, and each visible object's bounding box (a
+/// custom object has none) and origin, in canvas pixels.
+fn guides(p: *Painter, arena: std.mem.Allocator, shot: anim.Shot, svgs: anytype, world: geom.Affine, canvas: sk.Rect) !vector.Drawing {
+ var b: vector.Drawing.Builder = .init(arena);
+ const far = 100 * tick;
+ try b.lineTo(world.apply(.{ -far, 0 }), world.apply(.{ far, 0 }));
+ try b.closeSubpath(false);
+ try b.endShape(.identity, guideStyle(anim.red, 1.5));
+ try b.lineTo(world.apply(.{ 0, -far }), world.apply(.{ 0, far }));
+ try b.closeSubpath(false);
+ try b.endShape(.identity, guideStyle(anim.green, 1.5));
+ var i: f32 = -20;
+ while (i <= 20) : (i += 1) {
+ const x = world.apply(.{ i * tick, 0 });
+ const y = world.apply(.{ 0, i * tick });
+ try b.lineTo(x - geom.Vec{ 0, 5 }, x + geom.Vec{ 0, 5 });
+ try b.closeSubpath(false);
+ try b.lineTo(y - geom.Vec{ 5, 0 }, y + geom.Vec{ 5, 0 });
+ try b.closeSubpath(false);
+ }
+ try b.endShape(.identity, guideStyle(0x8c8c8c, 1));
+
+ for (shot.objects, shot.poses) |o, pose| {
+ if (!pose.visible or pose.opacity <= 0) continue;
+ const m = world.mul(model(pose));
+ if (o.source != .custom) {
+ const r = (try p.built(o, svgs)).bounds;
+ try b.polyline(&.{ m.apply(.{ r.x, r.y }), m.apply(.{ r.x + r.w, r.y }), m.apply(.{ r.x + r.w, r.y + r.h }), m.apply(.{ r.x, r.y + r.h }) }, true);
+ }
+ // The object's origin: where its pose puts it.
+ const c = m.apply(.{ 0, 0 });
+ try b.lineTo(c - geom.Vec{ 6, 0 }, c + geom.Vec{ 6, 0 });
+ try b.closeSubpath(false);
+ try b.lineTo(c - geom.Vec{ 0, 6 }, c + geom.Vec{ 0, 6 });
+ try b.closeSubpath(false);
+ }
+ try b.endShape(.identity, guideStyle(anim.yellow, 1));
+ return b.finish(.{ .w = canvas.w, .h = canvas.h }, canvas.w, canvas.h);
+}
+
+/// The guides' numbers: tick values, and each object's index and position.
+fn labels(p: *Painter, f: *sk.Frame, shot: anim.Shot, svgs: anytype, world: geom.Affine) !void {
+ var i: f32 = -20;
+ while (i <= 20) : (i += 2) {
+ const x = world.apply(.{ i * tick, 0 });
+ const y = world.apply(.{ 0, i * tick });
+ f.print(x[0] + 3, x[1] + 8, 1, 0x8c8c8c, "{d}", .{i * tick});
+ if (i != 0) f.print(y[0] + 8, y[1] - 3, 1, 0x8c8c8c, "{d}", .{i * tick});
+ }
+ for (shot.objects, shot.poses, 0..) |o, pose, n| {
+ if (!pose.visible or pose.opacity <= 0) continue;
+ const r: geom.Rect = if (o.source == .custom) .{} else (try p.built(o, svgs)).bounds;
+ const corner = world.mul(model(pose)).apply(.{ r.x, r.y });
+ f.print(corner[0], corner[1] - 11, 1, anim.yellow, "#{d} {d:.0},{d:.0}", .{ n, pose.x, pose.y });
+ }
+}
diff --git a/src/anim/player.zig b/src/anim/player.zig
index 090b6cb..b329714 100644
--- a/src/anim/player.zig
+++ b/src/anim/player.zig
@@ -1,20 +1,26 @@
//! The `anim` module's player: plays the scene file it is built around
//! (`sb.addScene`), compiled or live, as a manim-style animation drawn by
-//! the vector library on the GPU (or the CPU, with B). Time is state;
-//! everything else is a function of it (and, for a live scene, of the
-//! input).
+//! the vector library on the GPU (or the CPU, with B). Its state is an
+//! `anim.Deck`, the playhead and the gates opened, and the viewer's own
+//! settings; the picture is a function of them (and, for a live scene, of
+//! the input). A scene that pauses is a talk, and steps:
//!
-//! space pause / play left/right previous / next play
-//! click continue after a pause (`s.pause()` in the scene)
+//! click, space, page down next step: open the pause the talk waits at,
+//! or finish the step under way (in a scene with
+//! no pause, space plays or pauses)
+//! page up, backspace back a step: the picture before the last click
+//! ] / [ next / previous slide (`s.slide()`), at rest
+//! P play / pause left/right previous / next play
//! ,/. step back / ahead home/end start / end
//! up/down speed B GPU or CPU renderer
-//! G guides: boxes, origins and axes, in scene units
+//! L loop (not a talk) G guides: boxes, origins, axes
//! drag, wheel: look around R reset the view
//!
//! The scene's frame, 1280x720 scene units around its origin, is fitted
//! into the canvas, and the canvas is the room the host has: the window, or
//! an export's `--size`. Exported (`in.exporting`), the scene plays through
-//! once, without pauses or controls, and the player quits.
+//! once without controls, each pause held for the scene file's `hold`
+//! seconds (1 without one), and the player quits at the end.
const std = @import("std");
const sk = @import("sketch");
const vector = @import("vector");
@@ -23,71 +29,67 @@ const scene_file = @import("scene");
const scene = scene_file.scene;
/// The scene's Typst sources, compiled at build time.
const typst = @import("typst");
-const geom = vector.geom;
pub const name = if (@hasDecl(scene_file, "name")) scene_file.name else "anim";
/// The page: the scene file's `background` (0xRRGGBB), or manim's.
const background: u32 = if (@hasDecl(scene_file, "background")) scene_file.background else anim.background;
+/// Exported, how long each pause holds.
+const hold: f32 = if (@hasDecl(scene_file, "hold")) scene_file.hold else 1;
/// The scene's frame, in scene units: what shows at camera zoom 1.
-pub const width = 1280;
-pub const height = 720;
+pub const width = anim.width;
+pub const height = anim.height;
pub const State = struct {
- t: f32 = 0,
- playing: bool = true,
- speed: f32 = 1,
+ deck: anim.Deck = .{ .hold = hold },
looping: bool = true,
backend: vector.Backend = .gpu,
/// The viewer's own pan and zoom, on top of the scene's camera.
view: sk.Camera = .{},
dragging: bool = false,
- /// Where the left button went down: a click, not a drag, continues.
+ /// Where the left button went down: a click, not a drag, steps.
press: [2]f32 = .{ 0, 0 },
guides: bool = false,
};
pub const Session = struct {
- /// A renderer per run of vector objects between custom ones (`paint`).
- gpu: std.ArrayList(vector.Renderer(.gpu)) = .empty,
- cpu: std.ArrayList(vector.Renderer(.cpu)) = .empty,
- /// Drawings by what they look like (`Object.id`), built on first use and
- /// dropped on reload, since the code that builds them may have changed.
- /// Their memory is the host's, kept across reloads.
- arena: ?std.heap.ArenaAllocator = null,
- drawings: std.AutoHashMapUnmanaged(u64, Built) = .empty,
- /// Smoothed time to record a frame, and its shape count.
+ painter: anim.Painter = .{},
+ /// Smoothed time to record a frame.
render_ns: f32 = 0,
- shapes: usize = 0,
};
-const Built = struct { drawing: vector.Drawing, bounds: geom.Rect };
+/// A live scene's frame, or a compiled scene as a talk without gates.
+const talk = if (@hasDecl(scene, "frame")) scene.frame else struct {
+ fn frame(s: *anim.Frame) void {
+ s.cursor = scene.duration;
+ }
+}.frame;
pub fn update(s: *State, in: *const sk.Input) void {
- // The timeline as it stands: a live scene builds it as it runs.
- var arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator);
- defer arena.deinit();
- const shot = scene.shot(arena.allocator(), .{ .t = s.t }) catch return;
+ const d = &s.deck;
+ // A scene that waits somewhere is a talk: clicks and space step it.
+ const talking = d.gates > 0;
+ var ask: anim.Ask = .{};
+ var mark: enum { none, previous, next } = .none;
for (in.events) |e| switch (e.kind) {
- // Exported: nobody clicks, so straight through, once.
- .tick => if (in.exporting) {
- s.t += e.x;
- } else if (s.playing and !held(s.t, shot)) {
- const next = s.t + e.x * s.speed;
- s.t = stopBetween(s.t, next, shot) orelse next;
- if (s.t > shot.duration + 1) s.t = if (s.looping) 0 else shot.duration;
- },
- .key_down => if (e.flags & sk.Event.repeat == 0 or key(e) == .left or key(e) == .right or key(e) == .comma or key(e) == .period) switch (key(e)) {
- .space => if (s.playing and held(s.t, shot)) proceed(s) else {
- s.playing = !s.playing;
+ .key_down => if (e.flags & sk.Event.repeat == 0 or e.key() == .left or e.key() == .right or e.key() == .comma or e.key() == .period) switch (e.key()) {
+ .space => if (talking) {
+ ask.next = true;
+ } else {
+ d.playing = !d.playing;
},
- .home => s.t = 0,
- .end => s.t = shot.duration,
- .left => s.t = previousMark(s.t, shot),
- .right => s.t = nextMark(s.t, shot),
- .comma => s.t = @max(s.t - 1.0 / 30.0, 0),
- .period => s.t = @min(s.t + 1.0 / 30.0, shot.duration),
- .up => s.speed = @min(s.speed * 2, 8),
- .down => s.speed = @max(s.speed / 2, 0.125),
+ .page_down => ask.next = true,
+ .page_up, .backspace => ask.back = true,
+ .right_bracket => ask.next_slide = true,
+ .left_bracket => ask.back_slide = true,
+ .p => d.playing = !d.playing,
+ .home => ask.to = 0,
+ .end => ask.end = true,
+ .left => mark = .previous,
+ .right => mark = .next,
+ .comma => ask.to = @max((ask.to orelse d.t) - 1.0 / 30.0, 0),
+ .period => ask.to = @min((ask.to orelse d.t) + 1.0 / 30.0, d.duration),
+ .up => d.speed = @min(d.speed * 2, 8),
+ .down => d.speed = @max(d.speed / 2, 0.125),
.b => s.backend = if (s.backend == .gpu) .cpu else .gpu,
.g => s.guides = !s.guides,
.l => s.looping = !s.looping,
@@ -100,7 +102,7 @@ pub fn update(s: *State, in: *const sk.Input) void {
},
.mouse_up => {
const click = @abs(e.x - s.press[0]) + @abs(e.y - s.press[1]) < 4;
- if (s.dragging and click and held(s.t, shot)) proceed(s);
+ if (s.dragging and click and talking) ask.next = true;
s.dragging = false;
},
.cancel => s.dragging = false,
@@ -108,28 +110,26 @@ pub fn update(s: *State, in: *const sk.Input) void {
.wheel => s.view.zoomAt(e, e.wheel(), .{ .min = 0.2, .max = 20 }),
else => {},
};
+ if (mark != .none) {
+ // The plays as the scene lays them now.
+ var arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator);
+ defer arena.deinit();
+ if (shotNow(s, arena.allocator(), in, .{ 0, 0 })) |shot| {
+ ask.to = if (mark == .previous) previousMark(d.t, shot) else nextMark(d.t, shot);
+ } else |_| {}
+ }
+ // Played past the end: from the start again, or held there (a talk
+ // holds its last picture).
+ if (!in.exporting and d.t > d.duration + 1) {
+ if (s.looping and !talking) ask.to = 0 else d.t = d.duration;
+ }
+ d.update(in, ask, talk, .{});
}
-fn key(e: sk.Event) sk.Key {
- return @fromBackingInt(@intCast(@as(u8, @truncate(e.code))));
-}
-
-/// Waiting at a pause for a click.
-fn held(t: f32, shot: anim.Shot) bool {
- for (shot.stops) |stop| if (stop == t) return true;
- return false;
-}
-
-/// The first pause in `(from, to]`.
-fn stopBetween(from: f32, to: f32, shot: anim.Shot) ?f32 {
- for (shot.stops) |stop| if (stop > from and stop <= to) return stop;
- return null;
-}
-
-/// Past the pause the player waits at.
-fn proceed(s: *State) void {
- s.t += 1e-3;
- s.playing = true;
+/// The scene at the deck's `t`: a live one through the deck, with its gates.
+fn shotNow(s: *const State, arena: std.mem.Allocator, in: *const sk.Input, mouse: [2]f32) !anim.Shot {
+ if (@hasDecl(scene, "frame")) return s.deck.shot(arena, in, mouse, scene.frame, .{});
+ return scene.shot(arena, .{ .t = s.deck.t, .in = in, .pointer = mouse });
}
fn previousMark(t: f32, shot: anim.Shot) f32 {
@@ -145,33 +145,22 @@ fn nextMark(t: f32, shot: anim.Shot) f32 {
return shot.duration;
}
-/// Canvas pixels per scene unit: the scene's frame, fitted into `canvas`.
-fn fit(canvas: sk.Rect) f32 {
- return @min(canvas.w / width, canvas.h / height);
-}
-
/// The mouse in scene units from the canvas center, before the scene's
/// camera: the viewer's pan and zoom undone.
fn pointer(s: *const State, in: *const sk.Input, canvas: sk.Rect) [2]f32 {
- const k = fit(canvas);
+ const k = anim.Painter.fit(canvas);
return .{ ((in.mouse_x - s.view.x) / s.view.zoom - canvas.w / 2) / k, ((in.mouse_y - s.view.y) / s.view.zoom - canvas.h / 2) / k };
}
pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void {
// All the room there is: the window, or the size an export asks for.
const canvas: sk.Rect = .{ .w = @max(@floor(f.in.window_width), 1), .h = @max(@floor(f.in.window_height), 1) };
- f.canvas(@intFromFloat(canvas.w), @intFromFloat(canvas.h));
const started = f.host.clock();
- const shot = scene.shot(f.scratch, .{
- .t = s.t,
- .clock = @floatCast(@mod(@as(f64, @floatFromInt(f.in.now)) / std.time.ns_per_s, 3600)),
- .in = f.in,
- .pointer = pointer(s, f.in, canvas),
- }) catch |err| return f.host.print("scene: {t}", .{err});
- render(s, ss, f, shot, canvas) catch |err| f.host.print("render: {t}", .{err});
+ const shot = shotNow(s, f.scratch, f.in, pointer(s, f.in, canvas)) catch |err| return f.host.print("scene: {t}", .{err});
+ ss.painter.paint(f, shot, typst, .{ .view = s.view, .backend = s.backend, .guides = s.guides, .background = background }) catch |err| f.host.print("render: {t}", .{err});
if (f.in.exporting) {
// The frame that shows the end is the last.
- if (s.t >= shot.duration) f.quit();
+ if (s.deck.t >= shot.duration) f.quit();
return;
}
const elapsed: f32 = @floatFromInt(f.host.clock() -| started);
@@ -179,234 +168,31 @@ pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void {
hud(s, ss, f, shot, canvas);
}
-fn render(s: *const State, ss: *Session, f: *sk.Frame, shot: anim.Shot, canvas: sk.Rect) !void {
- if (ss.arena == null) ss.arena = .init(f.session);
- // A live scene may make new drawings every frame: start over now and then.
- if (f.in.reloaded or ss.drawings.count() > 1024) {
- _ = ss.arena.?.reset(.retain_capacity);
- ss.drawings = .empty;
- }
- // Use the host's GPU when it has one.
- if (s.backend == .gpu and f.host.gpu()) try paint(s, ss, &ss.gpu, f, shot, canvas) else try paint(s, ss, &ss.cpu, f, shot, canvas);
-}
-
-/// Object `o`'s drawing, centered on its origin, and its bounds.
-fn built(ss: *Session, o: anim.Object) !Built {
- const id = o.id();
- if (ss.drawings.get(id)) |b| return b;
- const arena = ss.arena.?.allocator();
- const d = try anim.build(arena, o, typst);
- const b: Built = .{ .drawing = d, .bounds = d.bounds().rect() };
- try ss.drawings.put(arena, id, b);
- return b;
-}
-
-/// Scene units to canvas pixels: the scene's camera, then the viewer's.
-/// The scene's origin is the canvas center.
-fn stage(s: *const State, cam: anim.Camera, canvas: sk.Rect) geom.Affine {
- const k = fit(canvas) * cam.zoom;
- return geom.Affine.translate(s.view.x, s.view.y)
- .mul(.scale(s.view.zoom, s.view.zoom))
- .mul(.translate(canvas.w / 2, canvas.h / 2))
- .mul(.scale(k, k))
- .mul(.rotate(-cam.rotation))
- .mul(.translate(-cam.x, -cam.y));
-}
-
-/// The next of `layers`, begun: a renderer the size of the canvas.
-fn begun(layers: anytype, used: *usize, f: *sk.Frame, canvas: sk.Rect, clear: vector.Drawing.Color) !*@TypeOf(layers.items[0]) {
- if (used.* == layers.items.len) try layers.append(f.session, try .init(f.session, f.host, @intFromFloat(canvas.w), @intFromFloat(canvas.h)));
- const r = &layers.items[used.*];
- used.* += 1;
- r.begin(f, clear);
- return r;
-}
-
-/// Draws `shot` with the renderers in `layers` (either backend), objects
-/// in the order they were added. Vector objects go into a renderer's image,
-/// which is then drawn on the canvas; a custom object draws on the canvas
-/// itself. So the vector objects before a custom one and those after it
-/// are separate images, one renderer each: every GPU pass of a frame runs
-/// before its first 2D command, and one image could only show the last.
-fn paint(s: *const State, ss: *Session, layers: anytype, f: *sk.Frame, shot: anim.Shot, canvas: sk.Rect) !void {
- if (layers.items.len > 0 and (layers.items[0].width() != @as(u32, @intFromFloat(canvas.w)) or layers.items[0].height() != @as(u32, @intFromFloat(canvas.h)))) {
- for (layers.items) |*r| r.deinit(f.host);
- layers.clearRetainingCapacity();
- }
- const world = stage(s, shot.camera, canvas);
- var used: usize = 0;
- // The first layer is the background too.
- var open: ?*@TypeOf(layers.items[0]) = try begun(layers, &used, f, canvas, anim.color(background));
- var shapes: usize = 0;
- for (shot.objects, shot.poses, 0..) |o, pose, i| {
- if (!pose.visible or pose.opacity <= 0) continue;
- const m = world.mul(model(pose));
- if (o.source == .custom) {
- if (open) |r| r.present(f, canvas);
- open = null;
- o.source.custom.draw(o.source.custom.ctx, f, .{ .t = s.t, .pose = pose, .xf = m, .scale = m.scaleFactor(), .stage = world, .values = shot.values });
- // It leaves no target, clip or blend behind.
- f.target(.none);
- f.blend(.alpha);
- continue;
- }
- const r = open orelse try begun(layers, &used, f, canvas, .{ 0, 0, 0, 0 });
- open = r;
- const d = (try built(ss, o)).drawing;
- if (pose.into != anim.Pose.none and pose.morph > 0 and pose.morph < 1 and shot.objects[pose.into].source != .custom) {
- // Morphing: from where this object began the transform to where
- // its target will stand.
- const morph = shot.morphs[i];
- const target = (try built(ss, shot.objects[pose.into])).drawing;
- const between = try vector.morph.between(f.scratch, d, world.mul(model(morph.from)), target, world.mul(model(morph.to)), pose.morph);
- try r.draw(between, .identity, pose.opacity);
- shapes += between.shapes.len;
- continue;
- }
- try reveal(r, d, m, pose, fit(canvas));
- shapes += d.shapes.len;
- }
- if (s.guides) {
- const r = open orelse try begun(layers, &used, f, canvas, .{ 0, 0, 0, 0 });
- open = r;
- try r.draw(try guides(ss, f.scratch, shot, world, canvas), .identity, 1);
- }
- if (open) |r| r.present(f, canvas);
- ss.shapes = shapes;
- if (s.guides) try labels(ss, f, shot, world);
-}
-
-fn model(p: anim.Pose) geom.Affine {
- return geom.Affine.translate(p.x, p.y).mul(.rotate(p.rotation)).mul(.scale(p.scale, p.scale));
-}
-
-/// manim's reveals, shape by shape with a stagger: Write traces each outline
-/// then fills it; Create draws strokes along their length, then fills.
-/// Outlines are `k` canvas pixels to the scene unit wide.
-fn reveal(r: anytype, d: vector.Drawing, m: geom.Affine, pose: anim.Pose, k: f32) !void {
- const n: f32 = @floatFromInt(d.shapes.len);
- const lag: f32 = if (pose.drawn >= 1) 0 else 0.08;
- const window = 1 / (1 + lag * @max(n - 1, 0));
- const glow = pose.highlight;
- for (d.shapes, 0..) |shape, i| {
- const local = std.math.clamp((pose.drawn - @as(f32, @floatFromInt(i)) * lag * window) / window, 0, 1);
- if (local <= 0) continue;
- var o: vector.Options = .{ .alpha = pose.opacity };
- switch (pose.reveal) {
- .write => if (local < 1) {
- o.trim = @min(local * 2, 1);
- o.outline = .{ .width = 1.5 * k, .alpha = 1 - std.math.clamp(local * 2 - 1, 0, 1) };
- o.stroke = false;
- // Fill arrives in the second half.
- var fill = o;
- fill.outline = null;
- fill.alpha = pose.opacity * std.math.clamp(local * 2 - 1, 0, 1);
- try r.drawShape(d, shape, m, fill);
- o.fill = false;
- },
- .create => if (local < 1) {
- o.trim = local;
- if (shape.style.stroke == .none) o.outline = .{ .width = 2 * k };
- var fill = o;
- fill.stroke = false;
- fill.outline = null;
- fill.alpha = pose.opacity * std.math.clamp(local * 3 - 2, 0, 1);
- try r.drawShape(d, shape, m, fill);
- o.fill = false;
- },
- }
- try r.drawShape(d, shape, m, o);
- if (glow > 0) {
- // Indicate: a yellow glow over the shape.
- var hot = shape;
- hot.style.fill = if (shape.style.fill != .none) .{ .color = anim.color(anim.yellow) } else .none;
- hot.style.stroke = if (shape.style.stroke != .none) .{ .color = anim.color(anim.yellow) } else .none;
- try r.drawShape(d, hot, m, .{ .alpha = pose.opacity * glow });
- }
- }
-}
-
-/// Spacing of the guides' ticks, in scene units.
-const tick = 100;
-
-fn guideStyle(c: u32, w: f32) vector.Drawing.Style {
- return .{ .fill = .none, .stroke = .{ .color = anim.color(c) }, .stroke_width = w };
-}
-
-/// The scene's axes with ticks, and each visible object's bounding box (a
-/// custom object has none) and origin, in canvas pixels.
-fn guides(ss: *Session, arena: std.mem.Allocator, shot: anim.Shot, world: geom.Affine, canvas: sk.Rect) !vector.Drawing {
- var b: vector.Drawing.Builder = .init(arena);
- const far = 100 * tick;
- try b.lineTo(world.apply(.{ -far, 0 }), world.apply(.{ far, 0 }));
- try b.closeSubpath(false);
- try b.endShape(.identity, guideStyle(anim.red, 1.5));
- try b.lineTo(world.apply(.{ 0, -far }), world.apply(.{ 0, far }));
- try b.closeSubpath(false);
- try b.endShape(.identity, guideStyle(anim.green, 1.5));
- var i: f32 = -20;
- while (i <= 20) : (i += 1) {
- const x = world.apply(.{ i * tick, 0 });
- const y = world.apply(.{ 0, i * tick });
- try b.lineTo(x - geom.Vec{ 0, 5 }, x + geom.Vec{ 0, 5 });
- try b.closeSubpath(false);
- try b.lineTo(y - geom.Vec{ 5, 0 }, y + geom.Vec{ 5, 0 });
- try b.closeSubpath(false);
- }
- try b.endShape(.identity, guideStyle(0x8c8c8c, 1));
-
- for (shot.objects, shot.poses) |o, pose| {
- if (!pose.visible or pose.opacity <= 0) continue;
- const m = world.mul(model(pose));
- if (o.source != .custom) {
- const r = (try built(ss, o)).bounds;
- try b.polyline(&.{ m.apply(.{ r.x, r.y }), m.apply(.{ r.x + r.w, r.y }), m.apply(.{ r.x + r.w, r.y + r.h }), m.apply(.{ r.x, r.y + r.h }) }, true);
- }
- // The object's origin: where its pose puts it.
- const c = m.apply(.{ 0, 0 });
- try b.lineTo(c - geom.Vec{ 6, 0 }, c + geom.Vec{ 6, 0 });
- try b.closeSubpath(false);
- try b.lineTo(c - geom.Vec{ 0, 6 }, c + geom.Vec{ 0, 6 });
- try b.closeSubpath(false);
- }
- try b.endShape(.identity, guideStyle(anim.yellow, 1));
- return b.finish(.{ .w = canvas.w, .h = canvas.h }, canvas.w, canvas.h);
-}
-
-/// The guides' numbers: tick values, and each object's index and position.
-fn labels(ss: *Session, f: *sk.Frame, shot: anim.Shot, world: geom.Affine) !void {
- var i: f32 = -20;
- while (i <= 20) : (i += 2) {
- const x = world.apply(.{ i * tick, 0 });
- const y = world.apply(.{ 0, i * tick });
- f.print(x[0] + 3, x[1] + 8, 1, 0x8c8c8c, "{d}", .{i * tick});
- if (i != 0) f.print(y[0] + 8, y[1] - 3, 1, 0x8c8c8c, "{d}", .{i * tick});
- }
- for (shot.objects, shot.poses, 0..) |o, pose, n| {
- if (!pose.visible or pose.opacity <= 0) continue;
- const r: geom.Rect = if (o.source == .custom) .{} else (try built(ss, o)).bounds;
- const corner = world.mul(model(pose)).apply(.{ r.x, r.y });
- f.print(corner[0], corner[1] - 11, 1, anim.yellow, "#{d} {d:.0},{d:.0}", .{ n, pose.x, pose.y });
- }
-}
-
fn hud(s: *const State, ss: *const Session, f: *sk.Frame, shot: anim.Shot, canvas: sk.Rect) void {
const w = canvas.w;
const h = canvas.h;
+ const d = &s.deck;
var play: usize = 0;
- for (shot.marks, 1..) |m, i| if (m <= s.t) {
+ for (shot.marks, 1..) |m, i| if (m <= d.t) {
play = i;
};
+ var buf: [64]u8 = undefined;
+ const steps = (if (d.slides > 0)
+ std.fmt.bufPrint(&buf, " slide {d}/{d} step {d}/{d}", .{ d.slide, d.slides, d.log.count(), d.gates })
+ else if (d.gates > 0)
+ std.fmt.bufPrint(&buf, " step {d}/{d}", .{ d.log.count(), d.gates })
+ else
+ std.fmt.bufPrint(&buf, "", .{})) catch "";
const backend = if (s.backend == .gpu and f.host.gpu()) "GPU" else "CPU";
- const status = if (!s.playing) " paused" else if (held(s.t, shot)) " click to continue" else "";
+ const status = if (!d.playing) " paused" else if (d.waiting) " click to continue" else "";
f.fill(sk.Rect{ .y = h - 28, .w = w, .h = 28 }, sk.Color{ .r = 0, .g = 0, .b = 0, .a = 150 });
- f.print(12, h - 19, 1, 0xece6e2, "{d:5.2}s / {d:.2}s play {d}/{d} {s} record {d:.3}ms {d} shapes speed x{d}{s}", .{
- s.t, shot.duration, play, shot.marks.len, backend, ss.render_ns / 1e6, ss.shapes, s.speed, status,
+ f.print(12, h - 19, 1, 0xece6e2, "{d:5.2}s / {d:.2}s play {d}/{d}{s} {s} record {d:.3}ms {d} shapes speed x{d}{s}", .{
+ d.t, shot.duration, play, shot.marks.len, steps, backend, ss.render_ns / 1e6, ss.painter.shapes, d.speed, status,
});
if (s.guides) {
const p = pointer(s, f.in, canvas);
f.print(w - 540, h - 19, 1, anim.yellow, "pointer {d:.0},{d:.0}", .{ p[0], p[1] });
}
- f.text(w - 400, h - 19, 1, "space click <- -> , . B G drag wheel", 0x8c8c8c);
+ f.text(w - 400, h - 19, 1, "click space pgup [ ] P <- -> , . B G drag", 0x8c8c8c);
f.cursor(.arrow);
}
diff --git a/src/anim/root.zig b/src/anim/root.zig
index a676f38..03abf11 100644
--- a/src/anim/root.zig
+++ b/src/anim/root.zig
@@ -44,13 +44,21 @@
//! Both are functions of time (and a live one, of the input too), so
//! scrubbing, seeking and hot reload are free.
//!
+//! **Talks** are live scenes with gates: `pause` waits for the presenter's
+//! click, `gate` for any condition, and time runs on while they wait, so
+//! loops (`loop`) and plays already running carry on. A talk is a function
+//! of its time and of the gates opened so far, both plain data in a `Deck`,
+//! which the stock player keeps and any sketch can keep in its own State.
+//!
//! Animations, as methods of an object handle: `write`, `create`,
//! `fadeIn`, `fadeOut`, `transformInto` (morph), `move`, `scaleTo`,
//! `rotate`, `indicate`; and `camera`, `Value.to`. `play` runs a tuple of
//! them together, with options `.seconds`, `.ease` (any `fn (f32) f32`,
-//! `ease.smooth` by default) and `.lag`. `wait` moves time on; `pause`
-//! holds the player there until a click, like a slide. Typst is compiled
-//! at build time (`sb.addScene`), from the scene's `typst_sources`.
+//! `ease.smooth` by default) and `.lag` (manim's lag ratio, 0 by
+//! default). `wait` moves time on; `pause`
+//! makes what follows wait for a click, like a slide step. Typst is
+//! compiled at build time (`sb.addScene`), from the scene's
+//! `typst_sources`.
//!
//! **Custom objects** (`s.custom(&data, .{ .x = 100 })`) are drawn by the
//! scene's own code, with `sketch.Frame` commands, in their place among
@@ -62,6 +70,7 @@ const tween = sk.tween;
const Drawing = vector.Drawing;
pub const ease = tween.ease;
+pub const Painter = @import("Painter.zig");
// manim's palette.
pub const blue: u32 = 0x58c4dd;
@@ -110,7 +119,6 @@ pub fn Key(comptime P: type) type {
start: f32,
end: f32,
ease: Ease,
- lag: f32 = 0,
from: P,
to: P,
@@ -133,6 +141,9 @@ pub const Source = union(enum) {
polygon: []const [2]f32,
/// Drawn by the scene's own code (`custom`).
custom: Custom,
+ /// The shapes of `of` whose bounds' centre lies in `area` (in `of`'s
+ /// units), around the area's centre (`part`).
+ part: struct { of: *const Object, area: vector.geom.Rect },
};
/// An object the scene draws itself with 2D commands (`f.fill`, `sk.draw`,
@@ -217,6 +228,8 @@ pub const Object = struct {
fill: ?u32 = null,
stroke: ?u32 = null,
width: f32 = 4,
+ /// Areas whose shapes parts were taken from it: it draws the rest.
+ cut: []const vector.geom.Rect = &.{},
/// Identifies what the object looks like (not where it is), to cache
/// its drawing by.
@@ -230,11 +243,25 @@ pub const Object = struct {
.circle => |c| h.update(std.mem.asBytes(&c.r)),
.line => |l| h.update(std.mem.asBytes(&[_]f32{ l.dx, l.dy, @floatFromInt(@intFromBool(l.arrow)) })),
.custom => |c| h.update(std.mem.asBytes(&[_]usize{ @intFromPtr(c.draw), @intFromPtr(c.ctx) })),
+ .part => |p| {
+ h.update(std.mem.asBytes(&p.of.id()));
+ h.update(std.mem.asBytes(&p.area));
+ },
}
h.update(std.mem.asBytes(&[_]u64{ o.fill orelse 1 << 32, o.stroke orelse 1 << 32 }));
h.update(std.mem.asBytes(&o.width));
+ h.update(std.mem.sliceAsBytes(o.cut));
return h.final();
}
+
+ /// What a part or a cut object is drawn from (`sift`): the object
+ /// without its cut, or the one a part was taken from.
+ pub fn whole(o: Object) Object {
+ if (o.cut.len == 0) return o.source.part.of.*;
+ var w = o;
+ w.cut = &.{};
+ return w;
+ }
};
/// Pose fields to animate towards; the others stay as they are.
@@ -360,7 +387,7 @@ const Play = struct {
animations: []const Animation,
/// `play`'s options: `.seconds` (1, or 2 with a write in it), `.ease`
- /// (`ease.smooth`) and `.lag` (0.08).
+ /// (`ease.smooth`) and `.lag` (0: all start together).
fn of(start: f32, animations: []const Animation, options: anytype) Play {
const O = @TypeOf(options);
var seconds: f32 = 1;
@@ -372,13 +399,18 @@ const Play = struct {
.start = start,
.seconds = seconds,
.ease = if (@hasField(O, "ease")) options.ease else ease.smooth,
- .lag = if (@hasField(O, "lag")) options.lag else 0.08,
+ .lag = if (@hasField(O, "lag")) options.lag else 0,
.animations = animations,
};
}
- fn key(p: Play, comptime P: type, from: P, to: P, with: ?Ease) Key(P) {
- return .{ .start = p.start, .end = p.start + p.seconds, .ease = with orelse p.ease, .lag = p.lag, .from = from, .to = to };
+ /// Animation `i`'s key. With a lag, manim's lag ratio: each animation
+ /// starts `lag` of its length after the one before, and all are as long
+ /// as lets the last end with the play.
+ fn key(p: Play, comptime P: type, i: usize, from: P, to: P, with: ?Ease) Key(P) {
+ const each = p.seconds / (1 + p.lag * @as(f32, @floatFromInt(@max(p.animations.len, 1) - 1)));
+ const start = p.start + @as(f32, @floatFromInt(i)) * p.lag * each;
+ return .{ .start = start, .end = start + each, .ease = with orelse p.ease, .from = from, .to = to };
}
};
@@ -396,16 +428,17 @@ fn count(comptime T: type) usize {
};
}
-/// What a play does to one object: the pose it starts from and ends on.
-const Change = struct { obj: u16, from: Pose, to: Pose, ease: ?Ease = null };
+/// What a play does to one object: the pose it starts from and ends on,
+/// timed as its first animation in the play (`at`).
+const Change = struct { obj: u16, at: usize, from: Pose, to: Pose, ease: ?Ease = null };
/// The changes `animations`, played together, make to objects standing in
/// their `settled` poses. `buf` needs two per animation.
fn changes(buf: []Change, settled: []const Pose, animations: []const Animation) []Change {
var n: usize = 0;
- for (animations) |a| switch (a) {
+ for (animations, 0..) |a, at| switch (a) {
.write, .create => |o| {
- const c = touch(buf, &n, settled, o);
+ const c = touch(buf, &n, at, settled, o);
c.from.visible = true;
c.from.drawn = 0;
if (c.from.opacity <= 0) c.from.opacity = 1;
@@ -414,7 +447,7 @@ fn changes(buf: []Change, settled: []const Pose, animations: []const Animation)
c.to.drawn = 1;
},
.fade_in => |o| {
- const c = touch(buf, &n, settled, o);
+ const c = touch(buf, &n, at, settled, o);
c.from.visible = true;
c.from.drawn = 1;
c.from.opacity = 0;
@@ -422,28 +455,28 @@ fn changes(buf: []Change, settled: []const Pose, animations: []const Animation)
c.to.opacity = 1;
},
.fade_out => |o| {
- const c = touch(buf, &n, settled, o);
+ const c = touch(buf, &n, at, settled, o);
c.to.opacity = 0;
c.to.visible = false;
},
.transform => |t| {
- const c = touch(buf, &n, settled, t.from);
+ const c = touch(buf, &n, at, settled, t.from);
c.from.into = @backingInt(t.to);
c.from.morph = 0;
c.to = c.from;
c.to.morph = 1;
c.to.visible = false;
- const d = touch(buf, &n, settled, t.to);
+ const d = touch(buf, &n, at, settled, t.to);
d.from.visible = false;
d.to = d.from;
d.to.visible = true;
d.to.drawn = 1;
d.to.opacity = 1;
},
- .move => |m| m.to.apply(&touch(buf, &n, settled, m.obj).to),
- .rotate => |r| touch(buf, &n, settled, r.obj).to.rotation += r.by,
+ .move => |m| m.to.apply(&touch(buf, &n, at, settled, m.obj).to),
+ .rotate => |r| touch(buf, &n, at, settled, r.obj).to.rotation += r.by,
.indicate => |o| {
- const c = touch(buf, &n, settled, o);
+ const c = touch(buf, &n, at, settled, o);
c.to.scale *= 1.2;
c.to.highlight = 1;
c.ease = ease.thereAndBack;
@@ -453,25 +486,28 @@ fn changes(buf: []Change, settled: []const Pose, animations: []const Animation)
return buf[0..n];
}
-fn touch(buf: []Change, n: *usize, settled: []const Pose, o: Obj) *Change {
+fn touch(buf: []Change, n: *usize, at: usize, settled: []const Pose, o: Obj) *Change {
const i = @backingInt(o);
for (buf[0..n.*]) |*c| if (c.obj == i) return c;
- buf[n.*] = .{ .obj = i, .from = settled[i], .to = settled[i] };
+ buf[n.*] = .{ .obj = i, .at = at, .from = settled[i], .to = settled[i] };
n.* += 1;
return &buf[n.* - 1];
}
-/// Where `animations` leave a camera standing at `view`, if they move it.
-fn aim(view: Camera, animations: []const Animation) ?Camera {
+/// Where `animations` leave a camera standing at `view`, if they move it,
+/// and the first of them that does (`Change.at`).
+fn aim(view: Camera, animations: []const Animation) ?struct { to: Camera, at: usize } {
var out: ?Camera = null;
- for (animations) |a| if (a == .camera) {
+ var first: usize = 0;
+ for (animations, 0..) |a, i| if (a == .camera) {
+ if (out == null) first = i;
var c = out orelse view;
inline for (@typeInfo(CameraTarget).@"struct".field_names) |name| if (@field(a.camera, name)) |v| {
@field(c, name) = v;
};
out = c;
};
- return out;
+ return .{ .to = out orelse return null, .at = first };
}
/// Adding objects, the same for both kinds of scene (anything with `add`).
@@ -518,6 +554,25 @@ const adding = struct {
}
};
+/// `part`'s area: `.x`, `.y` its centre (0 when left out), `.w`, `.h`.
+fn areaOf(spec: anytype) vector.geom.Rect {
+ const w: f32 = spec.w;
+ const h: f32 = spec.h;
+ return .{ .x = number(spec, "x", 0) - w / 2, .y = number(spec, "y", 0) - h / 2, .w = w, .h = h };
+}
+
+/// Where a part whose origin is `c` in its object's units stands, when the
+/// object stands at `p`.
+fn partPose(p: Pose, c: vector.geom.Vec) Pose {
+ var q = p;
+ const at = vector.geom.Affine.rotate(p.rotation).apply(c * vector.geom.splat(p.scale));
+ q.x += at[0];
+ q.y += at[1];
+ q.into = Pose.none;
+ q.morph = 0;
+ return q;
+}
+
fn primitive(source: Source, spec: anytype) Object {
var pose: Pose = .{};
inline for (.{ "x", "y", "scale", "rotation", "opacity", "visible" }) |name| {
@@ -545,14 +600,36 @@ pub const Builder = struct {
values: []const f32 = &.{},
plays: []const Play = &.{},
updaters: []const Updater = &.{},
- stops: []const f32 = &.{},
+ /// Parts, each following its object through the plays laid before it
+ /// was taken.
+ follows: []const Follow = &.{},
/// Where the next play starts.
cursor: f32 = 0,
+ const Follow = struct { obj: u16, of: u16, plays: usize, at: vector.geom.Vec };
+
pub fn add(b: *Builder, o: Object) Obj {
b.objects = b.objects ++ .{o};
return @fromBackingInt(@intCast(b.objects.len - 1));
}
+
+ /// The shapes of `of` whose bounds' centre lies in `area` (`.x`, `.y`
+ /// its centre, `.w`, `.h`, in `of`'s units: those of `s.rect` laid
+ /// over `of` at the origin, at scale 1), as an object of their own,
+ /// around the area's centre; `of` draws the rest. It stands where they
+ /// stood and shows as `of` does after the plays so far; plays after it
+ /// move one or the other. A shape goes to the first part that takes it.
+ pub fn part(b: *Builder, of: Obj, area: anytype) Obj {
+ const i = @backingInt(of);
+ const r = areaOf(area);
+ const whole = b.objects[i];
+ var cut = whole;
+ cut.cut = whole.cut ++ .{r};
+ b.objects = b.objects[0..i] ++ .{cut} ++ b.objects[i + 1 ..];
+ const o = b.add(.{ .source = .{ .part = .{ .of = &whole, .area = r } }, .pose = partPose(whole.pose, r.center()) });
+ b.follows = b.follows ++ .{Follow{ .obj = @backingInt(o), .of = i, .plays = b.plays.len, .at = r.center() }};
+ return o;
+ }
pub const svg = adding.svg;
pub const typst = adding.typst;
pub const rect = adding.rect;
@@ -580,11 +657,6 @@ pub const Builder = struct {
b.cursor += seconds;
}
- /// The player holds here until a click.
- pub fn pause(b: *Builder) void {
- b.stops = b.stops ++ .{b.cursor};
- }
-
/// From now on, every frame, `o`'s pose is `update(now, args...)`:
/// `args` (a tuple) is bound here, like a closure's captures, so an
/// updater can follow other objects or read values.
@@ -618,21 +690,31 @@ pub fn Scene(comptime construct: fn (*Builder) void) type {
var value_keys: [recorded.values.len][]const Key(f32) = @splat(&.{});
var camera_keys: []const Key(Camera) = &.{};
var marks: []const f32 = &.{};
- for (recorded.plays) |play| {
+ for (recorded.plays, 0..) |play, played| {
var buf: [2 * play.animations.len]Change = undefined;
+ var touched: [n]bool = @splat(false);
for (changes(&buf, &poses, play.animations)) |c| {
- const k = play.key(Pose, c.from, c.to, c.ease);
+ const k = play.key(Pose, c.at, c.from, c.to, c.ease);
keys[c.obj] = keys[c.obj] ++ .{k};
poses[c.obj] = k.at(k.end);
+ touched[c.obj] = true;
}
- for (play.animations) |a| if (a == .value) {
+ for (recorded.follows) |f| if (played < f.plays and touched[f.of]) {
+ var k = keys[f.of][keys[f.of].len - 1];
+ k.from = partPose(k.from, f.at);
+ k.to = partPose(k.to, f.at);
+ keys[f.obj] = keys[f.obj] ++ .{k};
+ poses[f.obj] = k.at(k.end);
+ touched[f.obj] = true;
+ };
+ for (play.animations, 0..) |a, at| if (a == .value) {
const i = @backingInt(a.value.value);
- value_keys[i] = value_keys[i] ++ .{play.key(f32, values[i], a.value.to, null)};
+ value_keys[i] = value_keys[i] ++ .{play.key(f32, at, values[i], a.value.to, null)};
values[i] = a.value.to;
};
if (aim(view, play.animations)) |to| {
- camera_keys = camera_keys ++ .{play.key(Camera, view, to, null)};
- view = to;
+ camera_keys = camera_keys ++ .{play.key(Camera, to.at, view, to.to, null)};
+ view = to.to;
}
marks = marks ++ .{play.start};
}
@@ -641,7 +723,6 @@ pub fn Scene(comptime construct: fn (*Builder) void) type {
const frozen_objects = recorded.objects[0..n].*;
const frozen_values = recorded.values[0..recorded.values.len].*;
const frozen_updaters = recorded.updaters[0..recorded.updaters.len].*;
- const frozen_stops = recorded.stops[0..recorded.stops.len].*;
const frozen_keys = compiled.keys;
const frozen_value_keys = compiled.value_keys;
const frozen_camera_keys = compiled.camera_keys[0..compiled.camera_keys.len].*;
@@ -663,7 +744,6 @@ pub fn Scene(comptime construct: fn (*Builder) void) type {
pub const camera_keys: []const Key(Camera) = &frozen_camera_keys;
/// Start times of every play, for chapter-style seeking.
pub const marks: []const f32 = &frozen_marks;
- pub const stops: []const f32 = &frozen_stops;
pub const duration: f32 = recorded.cursor;
/// Every Typst source, for the build step that compiles them.
pub const typst_sources: []const []const u8 = &typst_list;
@@ -678,7 +758,7 @@ pub fn Scene(comptime construct: fn (*Builder) void) type {
m.* = .{ .from = k.from, .to = pose(p.into, k.end) };
};
}
- return .{ .objects = objects, .poses = poses, .morphs = morphs, .values = try arena.dupe(f32, &values(now.t)), .camera = view(now.t), .duration = duration, .marks = marks, .stops = stops };
+ return .{ .t = now.t, .objects = objects, .poses = poses, .morphs = morphs, .values = try arena.dupe(f32, &values(now.t)), .camera = view(now.t), .duration = duration, .marks = marks, .stops = &.{} };
}
/// The key shaping object `i` at `t`: the last one to have started.
@@ -723,9 +803,12 @@ fn latest(comptime P: type, keys: []const Key(P), t: f32) ?Key(P) {
return found;
}
+pub const BuildError = error{ TypstNotCompiled, CustomHasNoDrawing } || vector.svg.Error;
+
/// The drawing of an object, centered on its origin, in pixels at scale 1.
/// `compiled` has `find(source) ?[]const u8` for Typst objects' SVGs.
-pub fn build(arena: std.mem.Allocator, o: Object, compiled: anytype) !Drawing {
+pub fn build(arena: std.mem.Allocator, o: Object, compiled: anytype) BuildError!Drawing {
+ if (o.source == .part or o.cut.len > 0) return sift(arena, try build(arena, o.whole(), compiled), o);
const document: ?[]const u8 = switch (o.source) {
.svg => |bytes| bytes,
.typst => |source| compiled.find(source) orelse return error.TypstNotCompiled,
@@ -738,8 +821,14 @@ pub fn build(arena: std.mem.Allocator, o: Object, compiled: anytype) !Drawing {
// Keep the SVG's pixel size (Typst's points are 4/3 px), centered.
const s = if (d.view.w > 0) d.width / d.view.w else 1;
const c = d.view.center();
+ const centring = vector.geom.Affine.scale(s, s).mul(.translate(-c[0], -c[1]));
const shapes = try arena.dupe(Drawing.Shape, d.shapes);
- for (shapes) |*shape| shape.transform = vector.geom.Affine.scale(s, s).mul(.translate(-c[0], -c[1])).mul(shape.transform);
+ for (shapes) |*shape| {
+ shape.transform = centring.mul(shape.transform);
+ if (shape.clip) |*q| for (q) |*v| {
+ v.* = centring.apply(v.*);
+ };
+ }
var out = d;
out.shapes = shapes;
out.view = .{ .x = -d.view.w * s / 2, .y = -d.view.h * s / 2, .w = d.view.w * s, .h = d.view.h * s };
@@ -779,13 +868,43 @@ pub fn build(arena: std.mem.Allocator, o: Object, compiled: anytype) !Drawing {
style.stroke = .none;
}
},
- .svg, .typst, .custom => unreachable,
+ .svg, .typst, .custom, .part => unreachable,
}
try b.endShape(.identity, style);
const r = @max(extent(o.source), 1);
return b.finish(.{ .x = -r, .y = -r, .w = 2 * r, .h = 2 * r }, 2 * r, 2 * r);
}
+/// The drawing of a part, or of an object parts were taken from, out of
+/// `whole`, the drawing of `o.whole()`: the shapes whose bounds' centre
+/// lies in the part's area, around the area's centre; or those in none of
+/// the object's `cut`, where they were. Shapes and geometry are shared.
+pub fn sift(arena: std.mem.Allocator, whole: Drawing, o: Object) error{OutOfMemory}!Drawing {
+ const areas: []const vector.geom.Rect = if (o.cut.len > 0) o.cut else &.{o.source.part.area};
+ const keep_inside = o.cut.len == 0;
+ const c: vector.geom.Vec = if (keep_inside) areas[0].center() else .{ 0, 0 };
+ const to = vector.geom.Affine.translate(-c[0], -c[1]);
+ var shapes: std.ArrayList(Drawing.Shape) = .empty;
+ for (whole.shapes) |shape| {
+ const b = whole.shapeBounds(shape);
+ const mid = shape.transform.apply((b.min + b.max) * vector.geom.splat(0.5));
+ const inside = for (areas) |a| {
+ if (mid[0] >= a.x and mid[0] < a.x + a.w and mid[1] >= a.y and mid[1] < a.y + a.h) break true;
+ } else false;
+ if (inside != keep_inside) continue;
+ var kept = shape;
+ kept.transform = to.mul(shape.transform);
+ if (kept.clip) |*q| for (q) |*v| {
+ v.* = to.apply(v.*);
+ };
+ try shapes.append(arena, kept);
+ }
+ var out = whole;
+ out.shapes = shapes.items;
+ if (keep_inside) out.view = .{ .x = -areas[0].w / 2, .y = -areas[0].h / 2, .w = areas[0].w, .h = areas[0].h };
+ return out;
+}
+
fn extent(s: Source) f32 {
return switch (s) {
.rect => |r| @max(r.w, r.h) / 2,
@@ -796,7 +915,7 @@ fn extent(s: Source) f32 {
for (pts) |p| m = @max(m, @max(@abs(p[0]), @abs(p[1])));
break :blk m;
},
- .svg, .typst, .custom => 0,
+ .svg, .typst, .custom, .part => 0,
};
}
@@ -816,40 +935,68 @@ pub fn color(c: u32) Drawing.Color {
/// A live scene: `frame` runs every frame, at runtime, and the scene is
/// whatever it builds. `typst` is a namespace whose declarations are the
-/// Typst sources `frame` uses, for the build to compile.
-pub fn Live(comptime frame: fn (*Frame) void, comptime typst: type) type {
- const decls = @typeInfo(typst).@"struct".decl_names;
- var sources: [decls.len][]const u8 = undefined;
- for (&sources, decls) |*s, name| s.* = @field(typst, name);
- const frozen_sources = sources;
+/// Typst sources `frame` uses, or a tuple of them (`sources`), for the
+/// build to compile.
+pub fn Live(comptime frame_fn: fn (*Frame) void, comptime typst: anytype) type {
return struct {
- pub const typst_sources: []const []const u8 = &frozen_sources;
+ pub const frame = frame_fn;
+ pub const typst_sources: []const []const u8 = sources(typst);
- /// The scene at `now`, for the player: `frame`, run once.
+ /// The scene at `now`, `frame` run once, its gates all closed.
pub fn shot(arena: std.mem.Allocator, now: Instant) !Shot {
- var s: Frame = .{ .t = now.t, .clock = now.clock, .in = now.in, .pointer = now.pointer, .arena = arena };
- frame(&s);
- const values = try arena.alloc(f32, s.values.items.len);
- for (values, s.values.items) |*v, own| v.* = own.shown;
- return .{ .objects = s.objects.items, .poses = s.shown.items, .morphs = s.morphs.items, .values = values, .camera = s.view, .duration = s.cursor, .marks = s.marks.items, .stops = s.stops.items };
+ var s: Frame = .{ .t = now.t, .in = now.in, .pointer = now.pointer, .arena = arena };
+ frame_fn(&s);
+ return s.shot();
}
};
}
+/// Every declaration of `namespaces` (a namespace, or a tuple of them),
+/// each a Typst source, for the build to compile: a sketch that draws
+/// Typst itself declares `pub const scene = struct { pub const
+/// typst_sources = anim.sources(.{typst}); };` for `sb.addTypst`.
+pub fn sources(comptime namespaces: anytype) []const []const u8 {
+ const frozen = comptime blk: {
+ const all = if (@TypeOf(namespaces) == type) .{namespaces} else namespaces;
+ var out: []const []const u8 = &.{};
+ for (all) |namespace| for (@typeInfo(namespace).@"struct".decl_names) |name| {
+ out = out ++ .{@as([]const u8, @field(namespace, name))};
+ };
+ break :blk out[0..out.len].*;
+ };
+ return &frozen;
+}
+
/// What a live scene's `frame` gets: the time, the input, and the same calls
/// as `Builder`, which take effect at `t` right away.
pub const Frame = struct {
- /// Scene time, in seconds.
+ /// Scene time, in seconds. In a talk it runs on through gates.
t: f32,
- /// Seconds on the wall clock, which runs on while the player pauses:
- /// for motion that should not stop.
- clock: f32,
in: *const sk.Input,
/// The mouse, in scene units from the canvas center (before the scene's
/// own camera).
pointer: [2]f32,
/// Lives for this frame.
arena: std.mem.Allocator,
+ /// The gates opened so far, in order (the deck's log).
+ gates: []const Gate = &.{},
+ /// The presenter asked for the next step (`Ask.next`) and nothing has
+ /// taken it yet: the `pause` it reaches opens. Code laid out before
+ /// that pause takes the click for itself by setting it false (a widget
+ /// the click landed on).
+ next: bool = false,
+ /// This update's events, pointer positions in scene units
+ /// (`Deck.pointer`): in the deck's `update` run only, empty when drawn.
+ events: []const sk.Event = &.{},
+ /// Where `gate` writes a gate that opens: the deck's `update` run only.
+ log: ?*Log = null,
+ /// Open every gate laid before `slides` slides, `hold` after it is
+ /// reached (or now, if that is later): `Ask.end`, `next_slide`, export.
+ lay: ?Lay = null,
+ /// A gate opened in this run: one click opens one gate.
+ opened: bool = false,
+ /// Where the first gate still closed is laid.
+ closed: ?f32 = null,
/// Where the next play starts.
cursor: f32 = 0,
objects: std.ArrayList(Object) = .empty,
@@ -861,7 +1008,12 @@ pub const Frame = struct {
settled_view: Camera = .{},
view: Camera = .{},
marks: std.ArrayList(f32) = .empty,
+ /// Where each gate is laid: the cursor when the code reached it.
stops: std.ArrayList(f32) = .empty,
+ /// Where each `slide` begins, and how many gates come before it.
+ slides: std.ArrayList(struct { at: f32, gates: u32 }) = .empty,
+
+ const Lay = struct { hold: f32, slides: usize };
pub fn add(s: *Frame, o: Object) Obj {
s.push(&s.objects, o);
@@ -879,6 +1031,19 @@ pub const Frame = struct {
pub const polygon = adding.polygon;
pub const custom = adding.custom;
+ /// The shapes of `of` inside `area`, as an object of their own, showing
+ /// as `of` does now; `of` draws the rest (see `Builder.part`).
+ pub fn part(s: *Frame, of: Obj, area: anytype) Obj {
+ const i = @backingInt(of);
+ const r = areaOf(area);
+ const whole = s.new(s.objects.items[i]);
+ s.objects.items[i].cut = std.mem.concat(s.arena, vector.geom.Rect, &.{ whole.cut, &.{r} }) catch @panic("anim: out of memory");
+ const o = s.add(.{ .source = .{ .part = .{ .of = whole, .area = r } }, .pose = partPose(whole.pose, r.center()) });
+ s.settled.items[@backingInt(o)] = partPose(s.settled.items[i], r.center());
+ s.shown.items[@backingInt(o)] = partPose(s.shown.items[i], r.center());
+ return o;
+ }
+
pub fn value(s: *Frame, initial: f32) Value {
s.push(&s.values, .{ .settled = initial, .shown = initial });
return @fromBackingInt(@intCast(s.values.items.len - 1));
@@ -904,29 +1069,32 @@ pub const Frame = struct {
/// they stand at `t`, then moves the cursor past them.
pub fn play(s: *Frame, animations: anytype, options: anytype) void {
const all = list(animations);
- const p = Play.of(s.cursor, &all, options);
- const started = s.t >= p.start;
var buf: [2 * all.len]Change = undefined;
- const touched = changes(&buf, s.settled.items, &all);
+ s.playAll(&all, &buf, Play.of(s.cursor, &all, options));
+ }
+
+ /// `play`, of animations known at runtime; `buf` holds two changes each.
+ fn playAll(s: *Frame, all: []const Animation, buf: []Change, p: Play) void {
+ const touched = changes(buf, s.settled.items, all);
for (touched) |c| {
- const k = p.key(Pose, c.from, c.to, c.ease);
+ const k = p.key(Pose, c.at, c.from, c.to, c.ease);
s.settled.items[c.obj] = k.at(k.end);
- if (started) s.shown.items[c.obj] = k.at(s.t);
+ if (s.t >= k.start) s.shown.items[c.obj] = k.at(s.t);
}
// A morph ends where its target settles.
- if (started) for (touched) |c| if (c.from.into != Pose.none) {
+ for (touched) |c| if (c.from.into != Pose.none and s.t >= p.key(Pose, c.at, c.from, c.to, c.ease).start) {
s.morphs.items[c.obj] = .{ .from = c.from, .to = s.settled.items[c.from.into] };
};
- for (all) |a| if (a == .value) {
+ for (all, 0..) |a, at| if (a == .value) {
const v = &s.values.items[@backingInt(a.value.value)];
- const k = p.key(f32, v.settled, a.value.to, null);
+ const k = p.key(f32, at, v.settled, a.value.to, null);
v.settled = a.value.to;
- if (started) v.shown = k.at(s.t);
+ if (s.t >= k.start) v.shown = k.at(s.t);
};
- if (aim(s.settled_view, &all)) |to| {
- const k = p.key(Camera, s.settled_view, to, null);
- s.settled_view = to;
- if (started) s.view = k.at(s.t);
+ if (aim(s.settled_view, all)) |to| {
+ const k = p.key(Camera, to.at, s.settled_view, to.to, null);
+ s.settled_view = to.to;
+ if (s.t >= k.start) s.view = k.at(s.t);
}
s.push(&s.marks, p.start);
s.cursor += p.seconds;
@@ -936,9 +1104,85 @@ pub const Frame = struct {
s.cursor += seconds;
}
- /// The player holds here until a click, like a slide.
- pub fn pause(s: *Frame) void {
+ /// A gate: the plays after it wait until it opens, while time runs on,
+ /// so plays already running, loops and code reading `t` carry on. It
+ /// opens in the deck's `update`, on the first frame at or after it is
+ /// reached on which `open` is not null, and from then on returns that
+ /// value, a choice to branch on; closed, it returns null. The cursor
+ /// moves to where it opened, or, closed, just past `t`, so what follows
+ /// waits in the future. Gates are known by the order they are reached.
+ pub fn gate(s: *Frame, open: ?u16) ?u16 {
+ const k = s.stops.items.len;
s.push(&s.stops, s.cursor);
+ if (k < s.gates.len) {
+ s.cursor += s.gates[k].wait;
+ return s.gates[k].value;
+ }
+ if (s.closed == null) if (s.log) |log| {
+ const laying = if (s.lay) |lay| s.slides.items.len < lay.slides else false;
+ const opens = if (laying) open orelse 0 else if (!s.opened and s.t >= s.cursor) open else null;
+ if (opens) |v| {
+ const wait_for = if (laying) @max(s.lay.?.hold, s.t - s.cursor) else s.t - s.cursor;
+ if (log.appendBounded(.{ .wait = wait_for, .value = v })) {
+ s.opened = true;
+ s.cursor += wait_for;
+ return v;
+ } else |_| {}
+ }
+ };
+ if (s.closed == null) s.closed = s.cursor;
+ s.cursor = @max(s.cursor, s.t + 1.0 / 60.0);
+ return null;
+ }
+
+ /// A gate the presenter opens (`Ask.next`: a click, space, page down),
+ /// like a slide's next step.
+ pub fn pause(s: *Frame) void {
+ _ = s.gate(if (s.next) 0 else null);
+ }
+
+ /// A slide begins: `Ask.next_slide` and `back_slide` go from slide to
+ /// slide, each shown at rest, held at its first gate.
+ pub fn slide(s: *Frame) void {
+ s.push(&s.slides, .{ .at = s.cursor, .gates = @intCast(s.stops.items.len) });
+ }
+
+ /// `f(s, args...)` beside the main line: its plays start at the cursor,
+ /// and the cursor is left where it was, so what follows runs alongside.
+ pub fn beside(s: *Frame, comptime f: anytype, args: anytype) void {
+ const at = s.cursor;
+ @call(.auto, f, .{s} ++ args);
+ s.cursor = at;
+ }
+
+ /// `f(s, args...)`, a run of plays that ends where it began, again and
+ /// again from the cursor until the gate laid right after it opens (for
+ /// ever while it is closed); the cycle running then completes. The
+ /// cursor is left where it was. `f` only plays: objects are made
+ /// outside it. It costs two runs of `f` a frame at most.
+ pub fn loop(s: *Frame, comptime f: anytype, args: anytype) void {
+ const start = s.cursor;
+ @call(.auto, f, .{s} ++ args); // the first cycle, which measures it
+ const period = s.cursor - start;
+ const k = s.stops.items.len;
+ const until = if (k < s.gates.len) start + s.gates[k].wait else std.math.inf(f32);
+ if (period > 0 and s.t >= start + period) {
+ var cycle = @floor((@min(s.t, until) - start) / period);
+ // One that would begin as the gate opens never runs.
+ if (cycle > 0 and start + cycle * period >= until) cycle -= 1;
+ s.cursor = start + cycle * period;
+ @call(.auto, f, .{s} ++ args); // the cycle in progress, which wins
+ }
+ s.cursor = start;
+ }
+
+ /// Fades out everything that shows once the plays so far are done, on
+ /// the main line (`play`'s options): the end of a slide.
+ pub fn clear(s: *Frame, options: anytype) void {
+ var all: std.ArrayList(Animation) = .empty;
+ for (s.settled.items, 0..) |p, i| if (p.visible and p.opacity > 0) s.push(&all, .{ .fade_out = @fromBackingInt(@intCast(i)) });
+ const buf = s.arena.alloc(Change, 2 * all.items.len) catch @panic("anim: out of memory");
+ s.playAll(all.items, buf, Play.of(s.cursor, all.items, options));
}
/// `data` in the arena, to change until the frame ends: what a custom
@@ -949,6 +1193,22 @@ pub const Frame = struct {
return kept;
}
+ /// What the run built, for the player.
+ fn shot(s: *Frame) !Shot {
+ const values = try s.arena.alloc(f32, s.values.items.len);
+ for (values, s.values.items) |*v, own| v.* = own.shown;
+ return .{ .t = s.t, .objects = s.objects.items, .poses = s.shown.items, .morphs = s.morphs.items, .values = values, .camera = s.view, .duration = s.cursor, .marks = s.marks.items, .stops = s.stops.items };
+ }
+
+ /// Slide `j`'s resting picture: where its first gate is laid, or, with
+ /// no gate of its own, where the next slide begins or the talk ends.
+ fn rest(s: *const Frame, j: usize) f32 {
+ const first = s.slides.items[j].gates;
+ const after = if (j + 1 < s.slides.items.len) s.slides.items[j + 1] else null;
+ if (first < s.stops.items.len and (after == null or first < after.?.gates)) return s.stops.items[first];
+ return if (after) |a| a.at else s.cursor;
+ }
+
/// Keeps scene code free of error handling: the frame arena running out
/// is fatal anyway.
fn push(s: *Frame, items: anytype, item: @TypeOf(items.items[0])) void {
@@ -957,13 +1217,215 @@ pub const Frame = struct {
};
// ---------------------------------------------------------------------------
+// Talks: a live scene with gates, and its playhead
+
+/// A gate opened: how long after it was reached, and the value it opened with.
+pub const Gate = struct { wait: f32 = 0, value: u16 = 0 };
+
+const Log = sk.List(Gate, 256);
+
+/// What the presenter asks of a deck this frame. The sketch decides which
+/// keys and clicks they are: the deck owns no input.
+pub const Ask = struct {
+ /// The next step: opens the pause the deck waits at, or, during a
+ /// step, finishes it (the playhead jumps to where the next gate is
+ /// laid; at the last step, to the end). A paused deck plays on.
+ next: bool = false,
+ /// Back a step: the picture held before the last gate opened.
+ back: bool = false,
+ /// The next or the previous slide (`Frame.slide`), at rest: held at
+ /// its first gate, every gate before it opened (at once, a choice with
+ /// 0) or undone.
+ next_slide: bool = false,
+ back_slide: bool = false,
+ /// A seek: the gates opened after it have not happened yet.
+ to: ?f32 = null,
+ /// The end: every gate opened where it is reached.
+ end: bool = false,
+};
+
+/// A talk's playhead: plain data for a sketch's State, so hot reload,
+/// snapshots, replay and the console see it like any field. The talk is
+/// `frame(s: *Frame, ctx...)`, a live scene's frame with more arguments,
+/// run from the top every frame: in `update`, given `ctx` as it is, so it
+/// may change the app (`mutable`), and in `shot`, given it read-only.
+pub const Deck = struct {
+ /// Talk time, in seconds: it runs on through gates.
+ t: f32 = 0,
+ playing: bool = true,
+ speed: f32 = 1,
+ /// Exported, each gate holds this long, then opens itself.
+ hold: f32 = 1,
+ /// The gates opened, in order: with `t`, all the talk depends on.
+ log: Log = .{},
+ /// When the last gate in `log` opened, as of the last update: an edit
+ /// that moves it moves `t` with it, so a reload keeps the same step, as
+ /// far into it.
+ anchor: f32 = 0,
+ /// The talk as the last update laid it, for a HUD and for scripts: its
+ /// end (a closed gate lays what follows it just past `t`), the gates
+ /// laid, opened or not, whether it waits at one, the slides begun by
+ /// `t`, and all the slides.
+ duration: f32 = 0,
+ gates: u32 = 0,
+ waiting: bool = false,
+ slide: u32 = 0,
+ slides: u32 = 0,
+
+ /// In `update`: time from the ticks, `ask` applied, and the talk run
+ /// once (more when asked to move), opening the gate it waits at.
+ /// Exported (`in.exporting`), it opens every gate `hold` after it is
+ /// reached, in the first frame's run, and runs at the export's pace.
+ pub fn update(d: *Deck, in: *const sk.Input, ask: Ask, comptime frame: anytype, ctx: anytype) void {
+ var arena_state: std.heap.ArenaAllocator = .init(std.heap.page_allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ for (in.events) |e| if (e.kind == .tick) {
+ if (in.exporting) {
+ d.t += e.x;
+ } else if (d.playing) d.t += e.x * d.speed;
+ };
+ if (ask.next) d.playing = true;
+ const events = arena.dupe(sk.Event, in.events) catch return;
+ for (events) |*e| switch (e.kind) {
+ .mouse_move, .mouse_down, .mouse_up, .wheel, .wheel_horizontal => {
+ const p = pointer(in, e.x, e.y);
+ e.x = p[0];
+ e.y = p[1];
+ },
+ else => {},
+ };
+ const all: Frame.Lay = .{ .hold = 0, .slides = std.math.maxInt(usize) };
+
+ // Elsewhere: against the talk as it is laid now.
+ const moves = ask.back or ask.to != null or ask.end or ask.next_slide or ask.back_slide;
+ if (moves) {
+ const m = d.run(arena, in, frame, readOnly(ctx), &.{}, false, false, null);
+ d.log.len = @min(d.log.count(), m.stops.items.len);
+ const n = d.log.count();
+ var on: u32 = 0;
+ for (m.slides.items) |sl| on += @intFromBool(sl.at <= d.t);
+ if (ask.back) {
+ d.t = if (n > 0) m.stops.items[n - 1] + d.log.buffer[n - 1].wait else 0;
+ d.log.len = n -| 1;
+ } else if (ask.to) |to| {
+ d.t = to;
+ while (d.log.count() > 0 and m.stops.items[d.log.count() - 1] + d.log.buffer[d.log.count() - 1].wait > to) d.log.len -= 1;
+ } else if (ask.back_slide) {
+ if (on < 2) {
+ d.t = 0;
+ d.log.len = 0;
+ } else {
+ d.log.len = m.slides.items[on - 2].gates;
+ d.t = m.rest(on - 2);
+ }
+ } else {
+ // Gates open up to the next slide's first, or all of them:
+ // a choice may be what lays the slides after it.
+ const l = d.run(arena, in, frame, readOnly(ctx), &.{}, true, false, if (ask.next_slide) .{ .hold = 0, .slides = on + 1 } else all);
+ d.t = if (ask.next_slide and on < l.slides.items.len) l.rest(on) else l.cursor;
+ }
+ }
+
+ const before = d.log.count();
+ var s = d.run(arena, in, frame, ctx, events, true, ask.next and !moves, if (in.exporting) .{ .hold = d.hold, .slides = all.slides } else null);
+ if (s.stops.items.len < before) {
+ // An edit took gates out: the ones it left are the talk's.
+ d.log.len = @intCast(s.stops.items.len);
+ } else if (!moves and before > 0) {
+ // An edit moved the last opened gate: so does `t`. That run's
+ // input is not taken again.
+ const now = s.stops.items[before - 1] + d.log.buffer[before - 1].wait;
+ if (now != d.anchor) {
+ d.log.len = before;
+ d.t += now - d.anchor;
+ s = d.run(arena, in, frame, readOnly(ctx), &.{}, false, false, null);
+ }
+ }
+ // A step under way, finished: the playhead to where it waits next.
+ if (ask.next and s.next and !s.opened and !moves) d.t = @max(d.t, s.closed orelse s.cursor);
+
+ const n = d.log.count();
+ d.anchor = if (n > 0) s.stops.items[n - 1] + d.log.buffer[n - 1].wait else 0;
+ d.duration = s.cursor;
+ d.gates = @intCast(s.stops.items.len);
+ d.waiting = if (s.closed) |c| d.t >= c else false;
+ d.slides = @intCast(s.slides.items.len);
+ d.slide = 0;
+ for (s.slides.items) |sl| d.slide += @intFromBool(sl.at <= d.t);
+ }
+
+ /// In `draw`: the talk now, for `Painter.paint`; `ctx` read-only and
+ /// the log too, so drawing changes nothing.
+ pub fn shot(d: *const Deck, arena: std.mem.Allocator, in: *const sk.Input, mouse: [2]f32, comptime frame: anytype, ctx: anytype) !Shot {
+ var s: Frame = .{ .t = d.t, .in = in, .pointer = mouse, .arena = arena, .gates = d.log.constSlice() };
+ @call(.auto, frame, .{&s} ++ readOnly(ctx));
+ return s.shot();
+ }
+
+ /// Window pixels to scene units from the center: the scene's frame
+ /// (`width` by `height`) fitted into the window, as `Painter` draws it.
+ pub fn pointer(in: *const sk.Input, x: f32, y: f32) [2]f32 {
+ const w = @max(@floor(in.window_width), 1);
+ const h = @max(@floor(in.window_height), 1);
+ const k = @min(w / width, h / height);
+ return .{ (x - w / 2) / k, (y - h / 2) / k };
+ }
+
+ /// One run of the talk at `t`, as the log stands.
+ fn run(d: *Deck, arena: std.mem.Allocator, in: *const sk.Input, comptime frame: anytype, ctx: anytype, events: []const sk.Event, logs: bool, next: bool, lay: ?Frame.Lay) Frame {
+ var s: Frame = .{
+ .t = d.t,
+ .in = in,
+ .pointer = pointer(in, in.mouse_x, in.mouse_y),
+ .arena = arena,
+ .gates = d.log.constSlice(),
+ .log = if (logs) &d.log else null,
+ .next = next,
+ .events = events,
+ .lay = lay,
+ };
+ @call(.auto, frame, .{&s} ++ ctx);
+ return s;
+ }
+};
+
+/// `app`, to change: a talk is given the app as `*App` in the deck's
+/// `update` run and as `*const App` when drawn, where this is null, so
+/// drawing cannot write to it. `if (anim.mutable(app)) |a| a.n += 1`.
+pub fn mutable(app: anytype) ?*@typeInfo(@TypeOf(app)).pointer.child {
+ return if (@typeInfo(@TypeOf(app)).pointer.attrs.@"const") null else app;
+}
+
+/// `ctx` with every pointer in it to const: what the runs that only look
+/// are given.
+fn readOnly(ctx: anytype) ReadOnly(@TypeOf(ctx)) {
+ var out: ReadOnly(@TypeOf(ctx)) = undefined;
+ inline for (0..ctx.len) |i| out[i] = ctx[i];
+ return out;
+}
+
+fn ReadOnly(comptime Ctx: type) type {
+ const types = @typeInfo(Ctx).@"struct".field_types;
+ var out: [types.len]type = undefined;
+ for (&out, types) |*o, T| o.* = switch (@typeInfo(T)) {
+ .pointer => |p| if (p.size == .one) *const p.child else T,
+ else => T,
+ };
+ return @Tuple(&out);
+}
+
+/// The scene's frame, in scene units: what shows at camera zoom 1.
+pub const width = 1280;
+pub const height = 720;
+
+// ---------------------------------------------------------------------------
// Both kinds, to the player
/// What a scene is asked for, each frame.
pub const Instant = struct {
/// Scene time, in seconds.
t: f32,
- clock: f32 = 0,
in: *const sk.Input = &no_input,
pointer: [2]f32 = .{ 0, 0 },
@@ -972,6 +1434,7 @@ pub const Instant = struct {
/// A scene at one instant: what the player draws.
pub const Shot = struct {
+ t: f32,
objects: []const Object,
poses: []const Pose,
/// For each object morphing (`pose.into`): the pose its morph started
@@ -983,7 +1446,7 @@ pub const Shot = struct {
duration: f32,
/// Start times of every play, for chapter-style seeking.
marks: []const f32,
- /// Where the player holds until a click (`pause`).
+ /// Where each gate is laid (`gate`, `pause`).
stops: []const f32,
};
@@ -1053,3 +1516,520 @@ test "a live scene shows what the compiled one does, at every instant" {
try std.testing.expectEqualSlices(f32, a.marks, b.marks);
}
}
+
+test "Typst sources come from a namespace or a tuple of them" {
+ const a = struct {
+ pub const title = "= A";
+ };
+ const b = struct {
+ pub const law = "$ x $";
+ pub const end = "= B";
+ };
+ try std.testing.expectEqual(@as(usize, 1), Live(liveScene, a).typst_sources.len);
+ try std.testing.expectEqualStrings("$ x $", Live(liveScene, .{ a, b }).typst_sources[1]);
+ try std.testing.expectEqual(@as(usize, 3), sources(.{ a, b }).len);
+ try std.testing.expect(Live(liveScene, a).frame == liveScene);
+}
+
+// ---------------------------------------------------------------------------
+// Talks: the semantics of the model in .scratch/sketch/anim/gates_model.zig
+// (pardes-code), on the real types, then the presenter's rulings.
+
+/// `d.update` with `before` and then a tick of `seconds`, in a window the
+/// size of the scene's frame (its center the scene's origin).
+fn step(d: *Deck, before: []const sk.Event, seconds: f32, ask: Ask, comptime frame: anytype, ctx: anytype) void {
+ var events: [8]sk.Event = undefined;
+ @memcpy(events[0..before.len], before);
+ events[before.len] = .{ .kind = .tick, .x = seconds };
+ d.update(&.{ .events = events[0 .. before.len + 1], .window_width = width, .window_height = height }, ask, frame, ctx);
+}
+
+/// Value 0 of the talk drawn now.
+fn shown(d: *const Deck, arena: std.mem.Allocator, comptime frame: anytype, ctx: anytype) !f32 {
+ return (try d.shot(arena, &Instant.no_input, .{ 0, 0 }, frame, ctx)).values[0];
+}
+
+/// Round 1's slide 2: a phase that runs from `spin`, through the hold at
+/// the second gate, until half a second after it opens; -1 otherwise.
+fn orbit(s: *Frame) void {
+ const phase = s.value(-1);
+ s.wait(2); // the title, written
+ s.pause();
+ s.wait(2.5); // out, and the equation in
+ const spin = s.cursor;
+ s.pause();
+ const leave = s.cursor;
+ s.wait(0.5);
+ if (s.t >= spin and s.t < leave + 0.5) s.values.items[@backingInt(phase)].shown = s.t - spin;
+}
+
+test "a loop runs on through the hold, and its phase is continuous across the click" {
+ var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
+ defer arena.deinit();
+ var d: Deck = .{};
+ step(&d, &.{}, 10, .{}, orbit, .{});
+ try std.testing.expect(d.waiting and d.log.count() == 0 and d.gates == 2);
+ step(&d, &.{}, 0, .{ .next = true }, orbit, .{});
+ try std.testing.expectEqual(@as(f32, 8), d.log.buffer[0].wait);
+ // Slide 2 is in at 12.5; at 15 the deck waits, the phase running.
+ step(&d, &.{}, 5, .{}, orbit, .{});
+ try std.testing.expect(d.waiting);
+ const before = try shown(&d, arena.allocator(), orbit, .{});
+ step(&d, &.{}, 0, .{ .next = true }, orbit, .{});
+ try std.testing.expect(!d.waiting and d.log.count() == 2);
+ try std.testing.expectEqual(before, try shown(&d, arena.allocator(), orbit, .{}));
+ try std.testing.expectApproxEqAbs(@as(f32, 2.5), before, 1e-4);
+ // Half a second after the click it has gone.
+ step(&d, &.{}, 0.6, .{}, orbit, .{});
+ try std.testing.expectEqual(@as(f32, -1), try shown(&d, arena.allocator(), orbit, .{}));
+}
+
+/// Round 1's equation, stepped: written to 1, then each step morphs it one
+/// further, to 4.
+fn equations(s: *Frame) void {
+ const form = s.value(0);
+ s.play(.{form.to(1)}, .{ .seconds = 2, .ease = ease.linear });
+ for (2..5) |i| {
+ s.pause();
+ s.play(.{form.to(@floatFromInt(i))}, .{ .seconds = 1.2, .ease = ease.linear });
+ }
+}
+
+test "back cuts to the picture held before the last click" {
+ var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
+ defer arena.deinit();
+ var d: Deck = .{};
+ // Clicks at 5, 9 and 20.
+ step(&d, &.{}, 5, .{ .next = true }, equations, .{});
+ step(&d, &.{}, 4, .{ .next = true }, equations, .{});
+ step(&d, &.{}, 11, .{ .next = true }, equations, .{});
+ try std.testing.expectEqual(@as(u32, 3), d.log.count());
+ step(&d, &.{}, 0.6, .{}, equations, .{});
+ try std.testing.expectApproxEqAbs(@as(f32, 3.5), try shown(&d, arena.allocator(), equations, .{}), 1e-3);
+ // Back, mid-morph: the third form at rest, held where the click was.
+ step(&d, &.{}, 0, .{ .back = true }, equations, .{});
+ try std.testing.expect(d.t == 20 and d.log.count() == 2 and d.waiting);
+ try std.testing.expectEqual(@as(f32, 3), try shown(&d, arena.allocator(), equations, .{}));
+ // Time runs on while held; nothing moves.
+ step(&d, &.{}, 40, .{}, equations, .{});
+ try std.testing.expectEqual(@as(f32, 3), try shown(&d, arena.allocator(), equations, .{}));
+ // Back again: the second form, at 9; then the first, at 5; then the start.
+ step(&d, &.{}, 0, .{ .back = true }, equations, .{});
+ try std.testing.expect(d.t == 9 and d.log.count() == 1);
+ try std.testing.expectEqual(@as(f32, 2), try shown(&d, arena.allocator(), equations, .{}));
+ step(&d, &.{}, 0, .{ .back = true }, equations, .{});
+ try std.testing.expect(d.t == 5 and d.log.count() == 0 and d.waiting);
+ step(&d, &.{}, 0, .{ .back = true }, equations, .{});
+ try std.testing.expect(d.t == 0 and !d.waiting);
+ // Forward after back plays the step again.
+ step(&d, &.{}, 3, .{ .next = true }, equations, .{});
+ step(&d, &.{}, 0.6, .{}, equations, .{});
+ try std.testing.expectApproxEqAbs(@as(f32, 1.5), try shown(&d, arena.allocator(), equations, .{}), 1e-3);
+}
+
+test "exported, each gate opens a fixed hold after it is reached: the same frames every run" {
+ var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
+ defer arena.deinit();
+ var runs: [2]Deck = .{ .{ .hold = 1 }, .{ .hold = 1 } };
+ var seen: [2][4]f32 = undefined;
+ for (&runs, &seen) |*d, *values| for (0..10 * 30) |frame| {
+ const tick = [_]sk.Event{.{ .kind = .tick, .x = 1.0 / 30.0 }};
+ d.update(&.{ .events = &tick, .exporting = true, .window_width = width, .window_height = height }, .{}, equations, .{});
+ if (frame % 75 == 0) values[frame / 75] = try shown(d, arena.allocator(), equations, .{});
+ };
+ for (runs) |d| {
+ try std.testing.expectEqual(@as(u32, 3), d.log.count());
+ for (d.log.constSlice()) |g| try std.testing.expectEqual(@as(f32, 1), g.wait);
+ try std.testing.expectApproxEqAbs(@as(f32, 2 + 3 * 2.2), d.duration, 1e-4);
+ }
+ try std.testing.expectEqualSlices(Gate, runs[0].log.constSlice(), runs[1].log.constSlice());
+ try std.testing.expectEqual(seen[0], seen[1]);
+}
+
+/// A talk that branches on the app's choice: proof (0) is two steps with a
+/// pause between, skip (1) one; both end on the same slide. Each part shows
+/// a circle: proof one, proof two, skipped, the end.
+fn branching(s: *Frame, app: anytype) void {
+ var parts: [4]Obj = undefined;
+ for (&parts) |*p| p.* = s.circle(.{ .r = 1 });
+ s.wait(2);
+ const pick = s.gate(app.pick) orelse return; // closed: nothing after it shows
+ switch (pick) {
+ 0 => {
+ s.play(.{parts[0].fadeIn()}, .{});
+ s.pause();
+ s.play(.{parts[1].fadeIn()}, .{});
+ },
+ else => s.play(.{parts[2].fadeIn()}, .{}),
+ }
+ s.play(.{parts[3].fadeIn()}, .{});
+}
+
+const Choice = struct { pick: ?u16 = null };
+
+fn showing(d: *const Deck, arena: std.mem.Allocator, app: *const Choice) ![4]bool {
+ const shot = try d.shot(arena, &Instant.no_input, .{ 0, 0 }, branching, .{app});
+ var out: [4]bool = undefined;
+ for (&out, shot.poses) |*o, p| o.* = p.visible;
+ return out;
+}
+
+test "a choice is logged in update, branched on, and replays from the log alone" {
+ var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
+ defer arena.deinit();
+ var app: Choice = .{};
+ var d: Deck = .{};
+ step(&d, &.{}, 3, .{}, branching, .{&app});
+ try std.testing.expect(d.waiting and d.log.count() == 0);
+ // A click is no choice.
+ step(&d, &.{}, 0, .{ .next = true }, branching, .{&app});
+ try std.testing.expect(d.waiting and d.log.count() == 0 and d.t == 3);
+ // The app says "skip": the gate opens with 1.
+ app.pick = 1;
+ step(&d, &.{}, 0, .{}, branching, .{&app});
+ try std.testing.expectEqual(Gate{ .wait = 1, .value = 1 }, d.log.buffer[0]);
+ // From the log alone, whatever the app says now: skipped, then the end.
+ app.pick = null;
+ d.t = 3.5;
+ try std.testing.expectEqual([4]bool{ false, false, true, false }, try showing(&d, arena.allocator(), &app));
+ d.t = 4.5;
+ try std.testing.expectEqual([4]bool{ false, false, true, true }, try showing(&d, arena.allocator(), &app));
+ // Another log takes the proof, whose pause is the second gate.
+ var proof: Deck = .{ .t = 4.5 };
+ try proof.log.appendBounded(.{ .wait = 1, .value = 0 });
+ try std.testing.expectEqual([4]bool{ true, false, false, false }, try showing(&proof, arena.allocator(), &app));
+ try proof.log.appendBounded(.{ .wait = 2 });
+ proof.t = 6.5;
+ try std.testing.expectEqual([4]bool{ true, true, false, false }, try showing(&proof, arena.allocator(), &app));
+}
+
+fn twoPauses(s: *Frame) void {
+ s.wait(2);
+ s.pause();
+ s.pause();
+}
+
+test "one click opens one gate, even when two are back to back" {
+ var d: Deck = .{};
+ step(&d, &.{}, 5, .{ .next = true }, twoPauses, .{});
+ try std.testing.expect(d.log.count() == 1 and d.waiting);
+ step(&d, &.{}, 0, .{ .next = true }, twoPauses, .{});
+ try std.testing.expect(d.log.count() == 2 and !d.waiting);
+}
+
+/// A swing of value `v` from 0 to 1 and back, in 1.5 s.
+fn swing(s: *Frame, v: Value) void {
+ s.play(.{v.to(1)}, .{ .seconds = 0.75, .ease = ease.linear });
+ s.play(.{v.to(0)}, .{ .seconds = 0.75, .ease = ease.linear });
+}
+
+fn swinging(s: *Frame) void {
+ const v = s.value(0);
+ s.wait(2);
+ s.loop(swing, .{v});
+ s.pause();
+}
+
+test "a loop repeats until the next gate opens, then finishes its cycle" {
+ var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
+ defer arena.deinit();
+ // Laid at 2: at 5.3 the third cycle is 0.3 s in.
+ var f: Frame = .{ .t = 5.3, .in = &Instant.no_input, .pointer = .{ 0, 0 }, .arena = arena.allocator() };
+ swinging(&f);
+ try std.testing.expectApproxEqAbs(@as(f32, 0.4), f.get(@fromBackingInt(0)), 1e-4);
+ // The gate opened at 6, in the third cycle (from 5): at 6.4 it is
+ // still swinging back, at 6.6 done, with no fourth.
+ const gates = [_]Gate{.{ .wait = 4 }};
+ var g: Frame = .{ .t = 6.4, .in = &Instant.no_input, .pointer = .{ 0, 0 }, .arena = arena.allocator(), .gates = &gates };
+ swinging(&g);
+ try std.testing.expectApproxEqAbs(@as(f32, 1 - 0.65 / 0.75), g.get(@fromBackingInt(0)), 1e-4);
+ var h: Frame = .{ .t = 6.6, .in = &Instant.no_input, .pointer = .{ 0, 0 }, .arena = arena.allocator(), .gates = &gates };
+ swinging(&h);
+ try std.testing.expectEqual(@as(f32, 0), h.get(@fromBackingInt(0)));
+}
+
+/// A three-step talk whose first step lasts `tempo.first`: value 0 is ten
+/// times the step shown plus how far into it.
+fn retimed(s: *Frame, tempo: anytype) void {
+ const at = s.value(0);
+ s.wait(tempo.first);
+ s.pause();
+ const one = s.cursor;
+ s.wait(1);
+ s.pause();
+ const two = s.cursor;
+ s.wait(1);
+ const v = &s.values.items[@backingInt(at)].shown;
+ if (s.t >= two) v.* = 20 + s.t - two else if (s.t >= one) v.* = 10 + s.t - one else v.* = s.t;
+}
+
+test "retiming a step above: waits plus re-anchoring keep the presenter where they were" {
+ var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
+ defer arena.deinit();
+ var tempo: struct { first: f32 } = .{ .first = 2 };
+ var d: Deck = .{};
+ // Opened after 3 s of waiting, then 4: half a second into step 2.
+ step(&d, &.{}, 5, .{ .next = true }, retimed, .{&tempo});
+ step(&d, &.{}, 5, .{ .next = true }, retimed, .{&tempo});
+ step(&d, &.{}, 0.5, .{}, retimed, .{&tempo});
+ try std.testing.expectApproxEqAbs(@as(f32, 20.5), try shown(&d, arena.allocator(), retimed, .{&tempo}), 1e-4);
+ // The first step is retimed to 5 s, and the library reloads: the same
+ // step, as far in, the log as it was.
+ tempo.first = 5;
+ step(&d, &.{}, 0, .{}, retimed, .{&tempo});
+ try std.testing.expectApproxEqAbs(@as(f32, 13.5), d.t, 1e-4);
+ try std.testing.expectApproxEqAbs(@as(f32, 20.5), try shown(&d, arena.allocator(), retimed, .{&tempo}), 1e-4);
+ try std.testing.expect(d.log.count() == 2 and d.log.buffer[0].wait == 3 and d.log.buffer[1].wait == 4);
+}
+
+/// Written in 2 s, a pause, then one more second.
+fn written(s: *Frame) void {
+ const v = s.value(0);
+ s.play(.{v.to(1)}, .{ .seconds = 2 });
+ s.pause();
+ s.play(.{v.to(2)}, .{ .seconds = 1 });
+}
+
+test "a click during a step finishes it, and the next click opens the gate (Keynote)" {
+ var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
+ defer arena.deinit();
+ var d: Deck = .{};
+ step(&d, &.{}, 1, .{}, written, .{});
+ try std.testing.expect(!d.waiting);
+ step(&d, &.{}, 0, .{ .next = true }, written, .{});
+ try std.testing.expect(d.t == 2 and d.waiting and d.log.count() == 0);
+ try std.testing.expectEqual(@as(f32, 1), try shown(&d, arena.allocator(), written, .{}));
+ // A paused deck plays on when asked for the next step.
+ d.playing = false;
+ step(&d, &.{}, 0, .{ .next = true }, written, .{});
+ try std.testing.expect(d.playing and d.log.count() == 1 and d.log.buffer[0].wait == 0);
+ // The last step, finished: the end.
+ step(&d, &.{}, 0.2, .{ .next = true }, written, .{});
+ try std.testing.expectEqual(@as(f32, 3), d.t);
+ try std.testing.expectEqual(@as(f32, 2), try shown(&d, arena.allocator(), written, .{}));
+}
+
+/// Three slides: the first holds one pause, the second two, the third none.
+fn slides(s: *Frame) void {
+ const v = s.value(0);
+ s.slide();
+ s.play(.{v.to(1)}, .{ .ease = ease.linear });
+ s.pause();
+ s.play(.{v.to(2)}, .{ .ease = ease.linear });
+ s.slide();
+ s.play(.{v.to(3)}, .{ .ease = ease.linear });
+ s.pause();
+ s.play(.{v.to(4)}, .{ .ease = ease.linear });
+ s.pause();
+ s.play(.{v.to(5)}, .{ .ease = ease.linear });
+ s.slide();
+ s.play(.{v.to(6)}, .{ .ease = ease.linear });
+}
+
+test "slides: next and previous go to each one's resting picture" {
+ var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
+ defer arena.deinit();
+ var d: Deck = .{};
+ step(&d, &.{}, 0.5, .{}, slides, .{});
+ try std.testing.expect(d.slide == 1 and d.slides == 3 and !d.waiting);
+ // Slide 2 at rest: slide 1's step done at once, held at slide 2's first pause.
+ step(&d, &.{}, 0, .{ .next_slide = true }, slides, .{});
+ try std.testing.expect(d.slide == 2 and d.t == 3 and d.log.count() == 1 and d.waiting);
+ try std.testing.expectEqual(@as(f32, 3), try shown(&d, arena.allocator(), slides, .{}));
+ // A step within it, then slide 3, which holds no pause: its end.
+ step(&d, &.{}, 0, .{ .next = true }, slides, .{});
+ try std.testing.expectEqual(@as(u32, 2), d.log.count());
+ step(&d, &.{}, 0.5, .{ .next_slide = true }, slides, .{});
+ try std.testing.expect(d.slide == 3 and d.log.count() == 3 and d.t == 6);
+ try std.testing.expectEqual(@as(f32, 6), try shown(&d, arena.allocator(), slides, .{}));
+ // Back to slide 2 at rest (its steps undone), then slide 1, then the start.
+ step(&d, &.{}, 0, .{ .back_slide = true }, slides, .{});
+ try std.testing.expect(d.slide == 2 and d.t == 3 and d.log.count() == 1 and d.waiting);
+ step(&d, &.{}, 0, .{ .back_slide = true }, slides, .{});
+ try std.testing.expect(d.slide == 1 and d.t == 1 and d.log.count() == 0 and d.waiting);
+ try std.testing.expectEqual(@as(f32, 1), try shown(&d, arena.allocator(), slides, .{}));
+ step(&d, &.{}, 0, .{ .back_slide = true }, slides, .{});
+ try std.testing.expect(d.t == 0 and d.log.count() == 0);
+ // Past the last slide: the end.
+ step(&d, &.{}, 0, .{ .end = true }, slides, .{});
+ try std.testing.expect(d.t == 6 and d.log.count() == 3 and d.slide == 3);
+}
+
+/// Slide 2 lies after a choice: it is laid once the choice is made.
+fn choosing(s: *Frame) void {
+ s.slide();
+ s.wait(1);
+ _ = s.gate(null) orelse return;
+ s.wait(1);
+ s.slide();
+ s.wait(1);
+ s.pause();
+}
+
+test "the next slide past a choice not made makes it, with 0" {
+ var d: Deck = .{};
+ step(&d, &.{}, 0, .{}, choosing, .{});
+ try std.testing.expect(d.slide == 1 and d.slides == 1);
+ step(&d, &.{}, 0, .{ .next_slide = true }, choosing, .{});
+ try std.testing.expect(d.slide == 2 and d.slides == 2 and d.t == 3 and d.waiting);
+ try std.testing.expect(d.log.count() == 1 and d.log.buffer[0].value == 0);
+}
+
+/// A button laid out before the pause it waits at, taking clicks on it.
+fn counting(s: *Frame, app: anytype) void {
+ s.wait(1);
+ const button: sk.Rect = .{ .x = -50, .y = -50, .w = 100, .h = 100 };
+ if (mutable(app)) |a| for (s.events) |e| if (e.kind == .mouse_up and button.contains(e.x, e.y)) {
+ a.n += 1;
+ s.next = false;
+ };
+ s.pause();
+}
+
+test "a click a widget takes is not the presenter's next as well" {
+ var app: struct { n: u32 = 0 } = .{};
+ var d: Deck = .{};
+ step(&d, &.{}, 2, .{}, counting, .{&app});
+ try std.testing.expect(d.waiting);
+ // On the button, at the window's center (the scene's origin): the
+ // button's. The sketch made it `next`, as it makes every click.
+ const on: sk.Event = .{ .kind = .mouse_up, .x = width / 2, .y = height / 2, .code = 1 };
+ step(&d, &.{on}, 0, .{ .next = true }, counting, .{&app});
+ try std.testing.expect(app.n == 1 and d.log.count() == 0 and d.waiting);
+ // Elsewhere: the presenter's.
+ const off: sk.Event = .{ .kind = .mouse_up, .x = 100, .y = 100, .code = 1 };
+ step(&d, &.{off}, 0, .{ .next = true }, counting, .{&app});
+ try std.testing.expect(app.n == 1 and d.log.count() == 1);
+ // Drawn, the talk gets the app read-only: nothing to write through.
+ const app_const: *const @TypeOf(app) = &app;
+ try std.testing.expect(mutable(app_const) == null);
+ try std.testing.expect(mutable(&app).? == &app);
+}
+
+fn fadeIn(s: *Frame, o: Obj) void {
+ s.play(.{o.fadeIn()}, .{ .seconds = 1 });
+}
+
+fn besideAndClear(s: *Frame) void {
+ const a = s.circle(.{ .r = 1 });
+ const b = s.circle(.{ .r = 1 });
+ s.beside(fadeIn, .{a});
+ s.play(.{b.fadeIn()}, .{ .seconds = 1 });
+ s.clear(.{ .seconds = 1 });
+}
+
+test "beside runs alongside the main line; clear fades out what shows" {
+ var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
+ defer arena.deinit();
+ const live = Live(besideAndClear, struct {});
+ const mid = try live.shot(arena.allocator(), .{ .t = 0.5 });
+ try std.testing.expectEqual(mid.poses[0], mid.poses[1]);
+ try std.testing.expect(mid.poses[0].visible and mid.poses[0].opacity > 0 and mid.poses[0].opacity < 1);
+ const out = try live.shot(arena.allocator(), .{ .t = 1.5 });
+ try std.testing.expectEqual(out.poses[0], out.poses[1]);
+ try std.testing.expect(out.poses[0].opacity < 1);
+ const gone = try live.shot(arena.allocator(), .{ .t = 2 });
+ try std.testing.expect(!gone.poses[0].visible and !gone.poses[1].visible and gone.duration == 2);
+}
+
+/// Three squares, 100 units each, the middle one red; the right one is
+/// taken as a part once the row shows, then each moves its own way.
+fn partScene(s: anytype) void {
+ const row = s.svg(
+ \\<svg viewBox="0 0 300 100" width="300" height="100"><rect width="100" height="100"/>
+ \\<rect x="100" width="100" height="100" fill="red"/><rect x="200" width="100" height="100"/></svg>
+ , .{ .x = 10, .scale = 2 });
+ s.play(.{row.fadeIn()}, .{});
+ const right = s.part(row, .{ .x = 100, .w = 80, .h = 80 });
+ s.play(.{ right.move(.{ .y = 50 }), row.move(.{ .x = 0 }) }, .{});
+}
+
+test "a part takes its shapes from its object, stands where they stood and follows it until taken" {
+ var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
+ defer arena.deinit();
+ const compiled = Scene(struct {
+ fn construct(s: *Builder) void {
+ partScene(s);
+ }
+ }.construct);
+ const live = Live(struct {
+ fn frame(s: *Frame) void {
+ partScene(s);
+ }
+ }.frame, struct {});
+ for ([_]f32{ 0, 0.5, 1, 1.5, 2, 3 }) |t| {
+ const a = try compiled.shot(arena.allocator(), .{ .t = t });
+ const b = try live.shot(arena.allocator(), .{ .t = t });
+ try std.testing.expectEqualSlices(Pose, a.poses, b.poses);
+ try std.testing.expectEqual(a.objects[0].id(), b.objects[0].id());
+ try std.testing.expectEqual(a.objects[1].id(), b.objects[1].id());
+ }
+ // Fading in with the row, before it was taken; where the right square
+ // stood (10 + 2 * 100) once it was; then on its own.
+ try std.testing.expectEqual(compiled.pose(0, 0.5).opacity, compiled.pose(1, 0.5).opacity);
+ try std.testing.expectEqual(Pose{ .x = 210, .scale = 2, .visible = true }, compiled.pose(1, 1));
+ try std.testing.expectEqual(@as(f32, 50), compiled.pose(1, 2).y);
+ try std.testing.expectEqual(@as(f32, 0), compiled.pose(0, 2).x);
+ try std.testing.expectEqual(@as(f32, 210), compiled.pose(1, 2).x);
+ // The row keeps two squares; the part is the third, around its centre.
+ const no_typst = struct {
+ fn find(_: []const u8) ?[]const u8 {
+ return null;
+ }
+ };
+ const rest = try build(arena.allocator(), compiled.objects[0], no_typst);
+ const taken = try build(arena.allocator(), compiled.objects[1], no_typst);
+ try std.testing.expectEqual(@as(usize, 2), rest.shapes.len);
+ try std.testing.expectEqual(@as(usize, 1), taken.shapes.len);
+ try std.testing.expectEqual(vector.geom.Rect{ .x = -50, .y = -50, .w = 100, .h = 100 }, taken.bounds().rect());
+ try std.testing.expectEqual(vector.geom.Rect{ .x = -150, .y = -50, .w = 200, .h = 100 }, rest.bounds().rect());
+}
+
+/// Four animations a lag of 0.5 apart, then two a whole one apart.
+fn lagScene(s: anytype) void {
+ const a = s.circle(.{ .r = 10 });
+ const b = s.circle(.{ .r = 10, .x = 50 });
+ const c = s.rect(.{ .w = 20, .h = 20, .x = 100 });
+ const k = s.value(0);
+ s.play(.{ a.fadeIn(), b.fadeIn(), camera(.{ .zoom = 2 }), k.to(1) }, .{ .seconds = 2.5, .lag = 0.5 });
+ s.play(.{ b.move(.{ .x = 0 }), a.transformInto(c) }, .{ .lag = 1 });
+}
+
+test "a play's lag starts each animation a fraction of its length after the one before, and the last ends with the play" {
+ var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
+ defer arena.deinit();
+ const compiled = Scene(struct {
+ fn construct(s: *Builder) void {
+ lagScene(s);
+ }
+ }.construct);
+ const live = Live(struct {
+ fn frame(s: *Frame) void {
+ lagScene(s);
+ }
+ }.frame, struct {});
+ for (0..16) |i| {
+ const t = @as(f32, @floatFromInt(i)) / 4;
+ const x = try compiled.shot(arena.allocator(), .{ .t = t });
+ const y = try live.shot(arena.allocator(), .{ .t = t });
+ try std.testing.expectEqualSlices(Pose, x.poses, y.poses);
+ try std.testing.expectEqualSlices(f32, x.values, y.values);
+ try std.testing.expectEqual(x.camera, y.camera);
+ try std.testing.expectEqual(x.duration, y.duration);
+ try std.testing.expectEqualSlices(f32, x.marks, y.marks);
+ if (x.poses[0].into != Pose.none) try std.testing.expectEqual(x.morphs[0], y.morphs[0]);
+ }
+ // 2.5 s for four, each 1 s long (2.5 / (1 + 3 * 0.5)), 0.5 s apart.
+ try std.testing.expectEqual(@as(f32, 3.5), compiled.duration);
+ try std.testing.expectApproxEqAbs(@as(f32, 0.5), compiled.pose(0, 0.5).opacity, 1e-6);
+ try std.testing.expectEqual(@as(f32, 0), compiled.pose(1, 0.5).opacity);
+ try std.testing.expectApproxEqAbs(@as(f32, 0.5), compiled.pose(1, 1).opacity, 1e-6);
+ try std.testing.expectEqual(@as(f32, 1), compiled.view(1).zoom);
+ try std.testing.expectEqual(@as(f32, 2), compiled.view(2).zoom);
+ try std.testing.expectEqual(@as(f32, 0), compiled.values(1.5)[0]);
+ try std.testing.expectEqual(@as(f32, 1), compiled.values(2.5)[0]);
+ // A lag of 1: one after the other, half the play each.
+ try std.testing.expectApproxEqAbs(@as(f32, 25), compiled.pose(1, 2.75).x, 1e-4);
+ try std.testing.expectEqual(@as(f32, 0), compiled.pose(0, 3).morph);
+ try std.testing.expectApproxEqAbs(@as(f32, 0.5), compiled.pose(0, 3.25).morph, 1e-6);
+}
diff --git a/src/anim/typst.zig b/src/anim/typst.zig
index d9df734..05a0d4e 100644
--- a/src/anim/typst.zig
+++ b/src/anim/typst.zig
@@ -50,12 +50,18 @@ pub fn generate(comptime SceneFile: type, comptime sources: []const []const u8,
try out.writeFile(io, .{ .sub_path = "typst.zig", .data = module });
}
-/// Runs `typst compile` on `preamble ++ source` and caches the SVG.
+/// Runs `typst compile` on `preamble ++ source` and caches the SVG. The
+/// root is `/`, so an absolute path in a source is the file's own path
+/// (`#image("/home/me/manual.pdf", page: 31)`) and a relative one is
+/// in the cache. Typst only reads what a source names, and a scene's
+/// sources are its author's code, built by a build that can already read
+/// anything. A file named this way is not part of the cache key: changed
+/// in place, it keeps its old SVG until its entry in the cache goes.
fn compile(gpa: std.mem.Allocator, io: std.Io, cache: std.Io.Dir, name: []const u8, preamble: []const u8, source: []const u8) ![]const u8 {
const typ = try std.fmt.allocPrint(gpa, "{s}.typ", .{name});
try cache.writeFile(io, .{ .sub_path = typ, .data = try std.mem.concat(gpa, u8, &.{ preamble, "\n", source, "\n" }) });
const result = try std.process.run(gpa, io, .{
- .argv = &.{ "typst", "compile", "--format", "svg", typ, name },
+ .argv = &.{ "typst", "compile", "--root", "/", "--format", "svg", typ, name },
.cwd = .{ .dir = cache },
});
if (result.term != .exited or result.term.exited != 0) {
diff --git a/src/gpu/Executor.zig b/src/gpu/Executor.zig
index 460b2d5..797dcbf 100644
--- a/src/gpu/Executor.zig
+++ b/src/gpu/Executor.zig
@@ -503,6 +503,32 @@ pub fn download(g: *Gpu, d: @FieldType(abi.Command, "download")) !void {
};
}
+/// Copies `out.len` bytes of a buffer from `offset` back now, waiting for
+/// the GPU to finish the work submitted before (sound that must be queued
+/// this frame).
+pub fn read(g: *Gpu, buffer: abi.Buffer, offset: u32, out: []u8) !void {
+ const source = g.storage(buffer) orelse return error.UnknownBuffer;
+ const size: u32 = @intCast(out.len);
+ if (size == 0 or @as(u64, offset) + size > source.size) return error.DownloadOutOfBounds;
+ const transfer = for (g.spare.items, 0..) |t, i| {
+ if (t.size >= size) break g.spare.swapRemove(i);
+ } else Transfer{
+ .buffer = c.SDL_CreateGPUTransferBuffer(g.device, &.{ .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_DOWNLOAD, .size = size, .props = 0 }) orelse return error.GpuBuffer,
+ .size = size,
+ };
+ defer g.spare.append(g.gpa, transfer) catch c.SDL_ReleaseGPUTransferBuffer(g.device, transfer.buffer);
+ const cmd = c.SDL_AcquireGPUCommandBuffer(g.device) orelse return error.GpuCommandBuffer;
+ const copy = c.SDL_BeginGPUCopyPass(cmd);
+ c.SDL_DownloadFromGPUBuffer(copy, &.{ .buffer = source.buffer, .offset = offset, .size = size }, &.{ .transfer_buffer = transfer.buffer, .offset = 0 });
+ c.SDL_EndGPUCopyPass(copy);
+ const fence = c.SDL_SubmitGPUCommandBufferAndAcquireFence(cmd) orelse return error.GpuSubmit;
+ defer c.SDL_ReleaseGPUFence(g.device, fence);
+ if (!c.SDL_WaitForGPUFences(g.device, true, &fence, 1)) return error.GpuFence;
+ const mapped: [*]const u8 = @ptrCast(c.SDL_MapGPUTransferBuffer(g.device, transfer.buffer, false) orelse return error.GpuMap);
+ defer c.SDL_UnmapGPUTransferBuffer(g.device, transfer.buffer);
+ @memcpy(out, mapped[0..size]);
+}
+
/// The downloads the GPU has finished, copied into `arena`, in the order
/// they were asked for.
pub fn collect(g: *Gpu, arena: std.mem.Allocator) ![]const abi.Download {
diff --git a/src/host/Console.zig b/src/host/Console.zig
index 0c44ea2..6fdfba4 100644
--- a/src/host/Console.zig
+++ b/src/host/Console.zig
@@ -1,22 +1,73 @@
//! The developer console: a line editor, a short log, and the host commands
-//! (snapshots, recordings, replay, field inspection). Lines the host does not
-//! know go to the sketch's `command`.
+//! (marks, clips, replay, sessions, field inspection). Lines the host does
+//! not know go to the sketch's `command`.
const Console = @This();
const std = @import("std");
const abi = @import("abi");
const Host = @import("Host.zig");
const fields = @import("fields.zig");
const memory = @import("memory.zig");
-const timeline = @import("timeline.zig");
+const Sessions = @import("Sessions.zig");
pub const panel_height = 144;
pub const Key = enum { left, right, home, end, backspace, delete, clear, tab, submit };
-const Line = struct { bytes: [118]u8 = @splat(0), len: usize = 0 };
+const Line = struct {
+ bytes: [width]u8 = @splat(0),
+ len: usize = 0,
+ const width = 118;
+};
+
+/// The console's words, a row each: what `help` prints, Tab completes,
+/// `execute` runs (its switch) and `Host.runLine` asks `moves_state` of.
+/// A line whose first word is none of them goes to the sketch.
+pub const Verb = enum { help, get, set, reset, save, load, diff, snapshot, marks, record, recording, clips, play, stop, pause, step, seek, sessions, @"export-session", import, overlay, timing, quit, exit };
+pub const Row = struct {
+ args: []const u8 = "",
+ doc: []const u8,
+ /// May change State other than through `update`: a jump.
+ moves_state: bool = false,
+};
+pub const verbs = std.enums.EnumArray(Verb, Row).init(.{
+ .help = .{ .args = "[VERB]", .doc = "the verbs, or what one does; then the sketch's help" },
+ .get = .{ .args = "FIELD", .doc = "a State field's value (`pos[0]`, `boids.buffer[3]`); a vector, array or struct shows every value in it, in memory order" },
+ .set = .{ .args = "FIELD VALUE...", .doc = "a field to a value (enums by name or number), or an array of numbers to all its values, in memory order", .moves_state = true },
+ .reset = .{ .doc = "State to its defaults, then the sketch's init; marks are kept", .moves_state = true },
+ .save = .{ .args = "[MARK]", .doc = "marks the State now, MARK or the snapshot one" },
+ .load = .{ .args = "[MARK|#K]", .doc = "brings a mark back (#K: the K-th in marks), migrated to today's layout", .moves_state = true },
+ .diff = .{ .args = "[MARK]", .doc = "live State against a mark, leaf by leaf" },
+ .snapshot = .{ .args = "MARK", .doc = "the mark save, load, diff and record use when given none" },
+ .marks = .{ .doc = "the last marks" },
+ .record = .{ .args = "[CLIP]", .doc = "starts a clip from the snapshot mark (saved first if new, else restored)", .moves_state = true },
+ .recording = .{ .args = "CLIP", .doc = "the clip record, play, seek and step use when given none" },
+ .clips = .{ .doc = "the last clips" },
+ .play = .{ .args = "session S [at SECONDS] | [CLIP]", .doc = "replays a past session (paused at SECONDS), or a clip", .moves_state = true },
+ .stop = .{ .doc = "ends the clip being recorded or played: live from here" },
+ .pause = .{ .doc = "pauses or resumes a replay" },
+ .step = .{ .args = "N", .doc = "N frames on (or back) in the replay", .moves_state = true },
+ .seek = .{ .args = "start|end|MS", .doc = "to a place in the replay", .moves_state = true },
+ .sessions = .{ .doc = "where this run records, and the last sessions" },
+ .@"export-session" = .{ .args = "[S] FILE", .doc = "session S (this run's) with its marks and clips, to a database of its own" },
+ .import = .{ .args = "FILE", .doc = "the sessions of such a file, its marks and clips as NAME@<file>" },
+ .overlay = .{ .args = "memory|sound|timing", .doc = "shows or hides an overlay" },
+ .timing = .{ .args = "[on|off|frame|work|reset|stats]", .doc = "the frame timing graph: shown, its metric, cleared, or its numbers" },
+ .quit = .{ .doc = "ends the run" },
+ .exit = .{ .doc = "ends the run" },
+});
-const host_commands = [_][]const u8{
- "help", "overlay memory", "overlay sound", "get", "set", "reset", "save", "load", "snapshot", "recording",
- "record", "stop", "play", "pause", "step", "seek start", "seek end", "diff", "quit", "exit",
- "overlay timing", "timing on", "timing off", "timing frame", "timing work", "timing reset", "timing stats",
+/// What Tab completes from: every verb, and with each of the words its
+/// first argument may be (`seek start`).
+const completions = blk: {
+ @setEvalBranchQuota(100_000);
+ var list: []const []const u8 = &.{};
+ for (std.enums.values(Verb)) |v| {
+ list = list ++ .{@tagName(v)};
+ const args = verbs.get(v).args;
+ var words = std.mem.tokenizeScalar(u8, std.mem.trim(u8, args[0 .. std.mem.indexOfScalar(u8, args, ' ') orelse args.len], "[]"), '|');
+ while (words.next()) |word| if (std.ascii.isLower(word[0])) {
+ list = list ++ .{@tagName(v) ++ " " ++ word};
+ };
+ }
+ break :blk list;
};
visible: bool = false,
@@ -24,11 +75,34 @@ buffer: [96]u8 = @splat(0),
len: usize = 0,
cursor: usize = 0,
lines: [5]Line = @splat(.{}),
-snapshot: usize = 1,
-recording: usize = 0,
+/// The mark `save`, `load`, `diff` and `record` use when given none.
+snapshot: Name = .of("1"),
+/// The clip `record`, `play`, `seek` and `step` use when given none.
+recording: Name = .of("0"),
overlay_memory: bool = false,
overlay_sound: bool = false,
+pub const Name = struct {
+ bytes: [Sessions.max_name]u8 = undefined,
+ len: usize = 0,
+
+ pub fn of(text_: []const u8) Name {
+ var n: Name = .{ .len = text_.len };
+ @memcpy(n.bytes[0..text_.len], text_);
+ return n;
+ }
+ pub fn get(n: *const Name) []const u8 {
+ return n.bytes[0..n.len];
+ }
+};
+
+/// A mark or clip name: a word of at most `Sessions.max_name` bytes.
+fn nameOr(arg: ?[]const u8, default: *const Name) ![]const u8 {
+ const n = arg orelse return default.get();
+ if (n.len > Sessions.max_name) return error.NameTooLong;
+ return n;
+}
+
pub fn text(self: *const Console) []const u8 {
return self.buffer[0..self.len];
}
@@ -86,7 +160,7 @@ fn complete(self: *Console, extra: []const []const u8) void {
var matches: [256]u8 = undefined;
var used: usize = 0;
var count: usize = 0;
- for ([_][]const []const u8{ &host_commands, extra }) |list| for (list) |candidate| {
+ for ([_][]const []const u8{ completions, extra }) |list| for (list) |candidate| {
if (!std.mem.startsWith(u8, candidate, self.text())) continue;
if (first) |previous| {
var i: usize = 0;
@@ -132,114 +206,199 @@ pub fn execute(self: *Console, host: *Host, line: []const u8, now: u64) ![]const
const command = words.next() orelse return &.{};
const arg = words.next();
const rest = words.rest();
-
- if (eq(command, "help")) {
- self.log("save|load [1..7] snapshot N | record|play [0..15] recording N | stop | pause | step N (frames) | seek start|end|<ms>");
- self.log("diff [N] | reset | get <field> | set <field> <value> | overlay memory|sound | quit");
- self.log("timing [on|off|frame|work|reset|stats] | overlay timing");
- if (host.forward(self, line, now) == .unknown) self.log("Backtick hides the console. Tab completes.");
- return &.{};
- }
- if (eq(command, "overlay")) {
- const name = arg orelse return error.ExpectedOverlay;
- if (rest.len != 0) return error.UnexpectedArgument;
- const flag = if (eq(name, "memory")) &self.overlay_memory else if (eq(name, "sound")) &self.overlay_sound else if (eq(name, "timing")) &host.timing.visible else return error.UnknownOverlay;
- flag.* = !flag.*;
- host.timing.dirty = true;
- self.print("{s} overlay: {s}", .{ name, if (flag.*) "on" else "off" });
- } else if (eq(command, "timing")) {
- if (rest.len != 0) return error.UnexpectedArgument;
- if (eq(arg orelse "", "stats")) {
- self.print("Timing: last {d}/240 frames; frame includes present, work excludes present (wall clock).", .{host.timing.count});
- inline for (.{ .frame, .work }) |metric| {
- const s = host.timing.stats(metric);
- self.print("{s}: avg {d:.3} ms | p90 {d:.3} ms | p99 {d:.3} ms | max {d:.3} ms", .{ @tagName(metric), s.mean, s.p90, s.p99, s.max });
- }
- } else {
- try host.timing.command(arg);
- self.print("Timing overlay: {s}, graph: {t}, samples: {d}", .{ if (host.timing.visible) "on" else "off", host.timing.metric, host.timing.count });
- }
- } else if (eq(command, "get")) {
- const path = arg orelse return error.ExpectedField;
- var buf: [160]u8 = undefined;
- var w: std.Io.Writer = .fixed(&buf);
- fields.formatPath(host.state.layout, host.live(), path, &w) catch |err| switch (err) {
- error.UnknownField => return error.UnknownField,
- error.WriteFailed => {}, // shown cut off
- };
- self.print("{s} = {s}", .{ path, w.buffered() });
- } else if (eq(command, "set")) {
- const path = arg orelse return error.ExpectedField;
- const leaf = host.state.layout.find(path) orelse return error.UnknownField;
- if (rest.len == 0) return error.ExpectedValue;
- h.stop(now);
- try fields.set(leaf, host.live(), std.mem.trim(u8, rest, " "));
- self.print("{s} = {s}", .{ path, std.mem.trim(u8, rest, " ") });
- } else if (eq(command, "quit") or eq(command, "exit")) {
- h.stop(now);
- host.quit = true;
- } else if (eq(command, "reset")) {
- h.stop(now);
- host.resetState();
- self.log("Live state reset. Snapshots are kept.");
- } else if (eq(command, "snapshot")) {
- self.snapshot = try slot(arg orelse return error.ExpectedSlot, 1, memory.slot_count - 1);
- } else if (eq(command, "recording")) {
- self.recording = try slot(arg orelse return error.ExpectedSlot, 0, timeline.recording_count - 1);
- } else if (eq(command, "save") or eq(command, "load")) {
- const index = if (arg) |a| try slot(a, 1, memory.slot_count - 1) else self.snapshot;
- if (eq(command, "load") and !h.bank.hasSnapshot(index)) return error.EmptySnapshot;
- h.stop(now);
- if (eq(command, "save")) {
- h.bank.save(index);
- self.print("Saved snapshot {d}. Recordings from its old contents are invalidated.", .{index});
- } else {
- try h.restore(index);
- self.print("Loaded snapshot {d}.", .{index});
- }
- } else if (eq(command, "record") or eq(command, "play")) {
- const index = if (arg) |a| try slot(a, 0, timeline.recording_count - 1) else self.recording;
- if (eq(command, "play")) _ = try h.bank.get(index);
- h.stop(now);
- if (eq(command, "record")) try h.startRecording(index, self.snapshot, now, host.build) else try h.play(index, now);
- self.recording = index;
- self.print("{s} recording {d} from snapshot {d}.", .{ if (eq(command, "record")) "Started" else "Playing", index, h.bank.recording(index).snapshot });
- if (eq(command, "play")) self.warnBuild(host, h.bank.recording(index));
- } else if (eq(command, "stop")) {
- h.stop(now);
- } else if (eq(command, "pause")) {
- if (h.mode != .playing and h.mode != .paused) return error.NotReplaying;
- h.pause(now);
- } else if (eq(command, "step") or eq(command, "seek")) {
- const value = arg orelse return error.ExpectedPosition;
- _ = try h.bank.get(if (h.mode == .live or h.mode == .recording) self.recording else h.selected);
- if (h.mode == .recording) h.stop(now);
- if (h.mode == .live) try h.play(self.recording, now);
- const r = try h.bank.get(h.selected);
- if (h.mode == .playing and h.cursor == 0) self.warnBuild(host, r);
- if (eq(command, "step")) return h.step(std.fmt.parseInt(i64, value, 10) catch return error.InvalidPosition);
- if (eq(value, "start")) return h.seekCount(0);
- if (eq(value, "end")) return h.seekCount(r.count);
- const ms = std.fmt.parseInt(u64, value, 10) catch return error.InvalidPosition;
- return h.seekTime(ms *| std.time.ns_per_ms);
- } else if (eq(command, "diff")) {
- const index = if (arg) |a| try slot(a, 1, memory.slot_count - 1) else self.snapshot;
- if (!h.bank.hasSnapshot(index)) return error.EmptySnapshot;
- const diff = h.bank.compare(0, index);
- if (diff.first) |first| {
- var buf: [96]u8 = undefined;
- var w: std.Io.Writer = .fixed(&buf);
- first.leaf.name(first.offset, &w) catch {};
- self.print("Live vs snapshot {d}: {d} differing values, first {s}", .{ index, diff.count, w.buffered() });
- } else self.print("Live vs snapshot {d}: same", .{index});
- } else {
+ const verb = std.meta.stringToEnum(Verb, command) orelse {
// Sketch commands edit state outside the recorded input.
- h.stop(now);
+ try stop(host);
switch (host.forward(self, line, now)) {
.unknown => return error.UnknownCommand,
.failed => return error.CommandFailed,
.done => {},
}
+ return &.{};
+ };
+ switch (verb) {
+ .help => {
+ if (std.meta.stringToEnum(Verb, arg orelse "")) |v| {
+ self.print("{t} {s}: {s}", .{ v, verbs.get(v).args, verbs.get(v).doc });
+ return &.{};
+ }
+ var buf: [Line.width + 3]u8 = undefined;
+ var w: std.Io.Writer = .fixed(&buf);
+ // Names only, so the sketch's help fits the log below them.
+ w.writeAll("help VERB says more:") catch {};
+ for (std.enums.values(Verb)) |v| {
+ if (w.end + @tagName(v).len + 1 > Line.width) {
+ self.log(w.buffered());
+ w.end = 0;
+ }
+ w.print(" {t}", .{v}) catch {};
+ }
+ self.log(w.buffered());
+ if (host.forward(self, line, now) == .unknown) self.log("Backtick hides the console. Tab completes.");
+ },
+ .overlay => {
+ const name = arg orelse return error.ExpectedOverlay;
+ if (rest.len != 0) return error.UnexpectedArgument;
+ const flag = if (eq(name, "memory")) &self.overlay_memory else if (eq(name, "sound")) &self.overlay_sound else if (eq(name, "timing")) &host.timing.visible else return error.UnknownOverlay;
+ flag.* = !flag.*;
+ host.timing.dirty = true;
+ self.print("{s} overlay: {s}", .{ name, if (flag.*) "on" else "off" });
+ },
+ .timing => {
+ if (rest.len != 0) return error.UnexpectedArgument;
+ if (eq(arg orelse "", "stats")) {
+ self.print("Timing: last {d}/240 frames; frame includes present, work excludes present (wall clock).", .{host.timing.count});
+ inline for (.{ .frame, .work }) |metric| {
+ const s = host.timing.stats(metric);
+ self.print("{s}: avg {d:.3} ms | p90 {d:.3} ms | p99 {d:.3} ms | max {d:.3} ms", .{ @tagName(metric), s.mean, s.p90, s.p99, s.max });
+ }
+ } else {
+ try host.timing.command(arg);
+ self.print("Timing overlay: {s}, graph: {t}, samples: {d}", .{ if (host.timing.visible) "on" else "off", host.timing.metric, host.timing.count });
+ }
+ },
+ .get => {
+ const path = arg orelse return error.ExpectedField;
+ var buf: [160]u8 = undefined;
+ var w: std.Io.Writer = .fixed(&buf);
+ fields.formatPath(host.state.layout, host.live(), path, &w) catch |err| switch (err) {
+ error.UnknownField => return error.UnknownField,
+ error.WriteFailed => {}, // shown cut off
+ };
+ self.print("{s} = {s}", .{ path, w.buffered() });
+ },
+ .set => {
+ const path = arg orelse return error.ExpectedField;
+ const leaf = host.state.layout.find(path) orelse return error.UnknownField;
+ if (rest.len == 0) return error.ExpectedValue;
+ try stop(host);
+ if (leaf.whole()) try fields.setRow(host.state.layout, host.live(), path, rest) else try fields.set(leaf, host.live(), std.mem.trim(u8, rest, " "));
+ self.print("{s} = {s}", .{ path, std.mem.trim(u8, rest, " ") });
+ },
+ .quit, .exit => {
+ try stop(host);
+ host.quit = true;
+ },
+ .reset => {
+ try stop(host);
+ host.resetState();
+ self.log("Live state reset. Snapshots are kept.");
+ },
+ .snapshot, .recording => {
+ const n = try nameOr(arg orelse return error.ExpectedName, &self.snapshot);
+ (if (verb == .snapshot) &self.snapshot else &self.recording).* = .of(n);
+ },
+ .save => {
+ const n = try nameOr(arg, &self.snapshot);
+ try stop(host);
+ _ = try host.sessions.mark(n, .mark, host.live());
+ self.print("Saved snapshot {s}.", .{n});
+ },
+ .load => {
+ const n = try nameOr(arg, &self.snapshot);
+ const key = try loadMark(host, n);
+ defer key.free(host.gpa);
+ try stop(host);
+ try h.restore(key);
+ self.print("Loaded snapshot {s}.", .{n});
+ },
+ .record => {
+ const n = try nameOr(arg, &self.recording);
+ const from = self.snapshot.get();
+ try stop(host);
+ // An unused mark captures the current state; an existing one is
+ // restored, so several clips can branch from exactly those bytes.
+ const k = if (try host.sessions.findMark(from) == null) try host.sessions.mark(from, .mark, host.live()) else blk: {
+ const key = try loadMark(host, from);
+ defer key.free(host.gpa);
+ try h.restore(key);
+ break :blk try host.sessions.keyframe(.jump, host.live());
+ };
+ // The input held now is restored first in the clip (Host.restoredInput).
+ h.restored = true;
+ try host.sessions.startClip(n, k);
+ h.startRecording();
+ self.recording = .of(n);
+ self.print("Started recording {s} from snapshot {s}.", .{ n, from });
+ },
+ .play => if (arg != null and eq(arg.?, "session")) {
+ var more = std.mem.tokenizeAny(u8, rest, " \t");
+ const index = std.fmt.parseInt(u64, more.next() orelse return error.ExpectedSession, 10) catch return error.InvalidSession;
+ var at: ?u64 = null;
+ if (more.next()) |word| {
+ if (!eq(word, "at")) return error.UnexpectedArgument;
+ const seconds = std.fmt.parseFloat(f64, more.next() orelse return error.ExpectedPosition) catch return error.InvalidPosition;
+ at = @intFromFloat(@max(0, seconds) * std.time.ns_per_s);
+ }
+ try stop(host);
+ return self.playSession(host, index, at, now);
+ } else {
+ const n = try nameOr(arg, &self.recording);
+ try stop(host);
+ try loadClip(host, n);
+ try h.play(now);
+ self.recording = .of(n);
+ self.print("Playing recording {s}.", .{n});
+ self.warnBuild(host);
+ },
+ .stop => {
+ try stop(host);
+ },
+ .pause => {
+ if (h.mode != .playing and h.mode != .paused) return error.NotReplaying;
+ h.pause(now);
+ },
+ .step, .seek => {
+ const value = arg orelse return error.ExpectedPosition;
+ if (h.mode == .live or h.mode == .recording) {
+ try stop(host);
+ try loadClip(host, self.recording.get());
+ try h.play(now);
+ self.warnBuild(host);
+ }
+ if (verb == .step) return h.step(std.fmt.parseInt(i64, value, 10) catch return error.InvalidPosition);
+ if (eq(value, "start")) return h.seekCount(0);
+ if (eq(value, "end")) return h.seekCount(h.events.items.len);
+ const ms = std.fmt.parseInt(u64, value, 10) catch return error.InvalidPosition;
+ return h.seekTime(ms *| std.time.ns_per_ms);
+ },
+ .diff => {
+ const n = try nameOr(arg, &self.snapshot);
+ var arena: std.heap.ArenaAllocator = .init(host.gpa);
+ defer arena.deinit();
+ const saved = try markState(host, arena.allocator(), n);
+ const diff = memory.compareKept(saved.layout, host.state.layout, host.live(), saved.bytes);
+ if (diff.first) |first| {
+ var buf: [96]u8 = undefined;
+ var w: std.Io.Writer = .fixed(&buf);
+ first.leaf.name(first.offset, &w) catch {};
+ self.print("Live vs snapshot {s}: {d} differing values, first {s}", .{ n, diff.count, w.buffered() });
+ } else self.print("Live vs snapshot {s}: same", .{n});
+ },
+ .sessions => {
+ if (arg != null) return error.UnexpectedArgument;
+ try self.listSessions(host);
+ },
+ .@"export-session" => {
+ const s = &host.sessions;
+ const first = arg orelse return error.ExpectedFile;
+ const index = if (rest.len == 0) s.session else std.fmt.parseInt(u64, first, 10) catch return error.InvalidSession;
+ const path = if (rest.len == 0) first else std.mem.trim(u8, rest, " \t");
+ try s.exportSession(index, path);
+ self.print("Exported session {d} to {s}.", .{ index, path });
+ },
+ .import => {
+ const path = arg orelse return error.ExpectedFile;
+ if (rest.len != 0) return error.UnexpectedArgument;
+ const s = &host.sessions;
+ const first = try s.import(path);
+ const n = try s.count(.sessions);
+ self.print("Imported {s} as session {d}..{d}; marks and clips are NAME@{s}.", .{ path, first, n - 1, std.fs.path.basename(path) });
+ },
+ .marks, .clips => {
+ if (arg != null) return error.UnexpectedArgument;
+ try self.listNamed(host, verb == .marks);
+ },
}
return &.{};
}
@@ -251,8 +410,12 @@ pub fn draw(self: *const Console, host: *Host, out: *std.ArrayList(abi.Command),
const width: f32 = @floatFromInt(host.canvas[0]);
const h = &host.timeline;
try out.append(arena, .{ .rect = .{ .dst = .{ .x = 0, .y = top, .w = width, .h = panel_height }, .color = .{ .r = 24, .g = 28, .b = 28 } } });
- const status = try std.fmt.allocPrint(arena, "{s} | {t} | snapshot {d} | recording {d} (active {d}) | event {d} | {d}ms", .{
- host.name, h.mode, self.snapshot, self.recording, h.selected, h.cursor, h.position / std.time.ns_per_ms,
+ const s = &host.sessions;
+ const playing = h.mode == .playing or h.mode == .paused;
+ const frame = if (playing) (if (h.key) |k| k.frame else 0) + h.fed else s.frames;
+ const at = (if (playing) h.position else s.last_time -| s.first_time) / std.time.ns_per_s;
+ const status = try std.fmt.allocPrint(arena, "{s} | {t} | session {d} frame {d} ({d}:{d:0>2}) | mark {s} | clip {s} | rec {t}", .{
+ host.name, h.mode, if (playing) h.session orelse s.session else s.session, frame, at / 60, at % 60, self.snapshot.get(), self.recording.get(), s.mode(),
});
try out.append(arena, .{ .text = .{ .x = 12, .y = top + 8, .scale = 1, .color = hint, .bytes = status } });
for (&self.lines, 0..) |*line, i| {
@@ -262,19 +425,134 @@ pub fn draw(self: *const Console, host: *Host, out: *std.ArrayList(abi.Command),
try out.append(arena, .{ .rect = .{ .dst = .{ .x = @floatFromInt(28 + self.cursor * 8), .y = top + 120, .w = 1, .h = 12 }, .color = hint } });
}
-/// A replay of a recording made by other code may diverge: say so.
-fn warnBuild(self: *Console, host: *const Host, r: *const timeline.Recording) void {
- if (r.build() != 0 and host.build != 0 and r.build() != host.build) self.log("Warning: recorded by another build of the sketch; the replay may differ.");
+/// Where this run records, then the last sessions: index, start, frames,
+/// stretches (loads), and how it ended.
+fn listSessions(self: *Console, host: *Host) !void {
+ const s = &host.sessions;
+ switch (s.mode()) {
+ .file => self.print("recording to {s}", .{s.path}),
+ .memory => self.log("recording in memory (scripted run)"),
+ .off => return self.log("not recording (an export)"),
+ }
+ const n = try s.count(.sessions);
+ var i = n -| 4;
+ while (i < n) : (i += 1) {
+ const m = try s.summary(i);
+ const secs = std.time.epoch.EpochSeconds{ .secs = m.started / std.time.ns_per_s };
+ const day = secs.getEpochDay().calculateYearDay();
+ const md = day.calculateMonthDay();
+ const ds = secs.getDaySeconds();
+ var end_buf: [32]u8 = undefined;
+ const end = if (i == s.session) "(this run)" else if (m.ended == 0) "(crashed)" else blk: {
+ const d = (m.ended -| m.started) / std.time.ns_per_s;
+ break :blk std.fmt.bufPrint(&end_buf, "{d}:{d:0>2}", .{ d / 60, d % 60 }) catch "";
+ };
+ self.print("{d}: {d:0>4}-{d:0>2}-{d:0>2} {d:0>2}:{d:0>2} builds {d} frames {d} {s} {s}", .{ i, day.year, md.month.numeric(), md.day_index + 1, ds.getHoursIntoDay(), ds.getMinutesIntoHour(), m.stretches, m.frames, end, m.from() });
+ }
}
-fn eq(a: []const u8, b: []const u8) bool {
- return std.mem.eql(u8, a, b);
+/// Ends a clip being recorded or played: live from here.
+fn stop(host: *Host) !void {
+ if (host.timeline.mode == .recording) try host.sessions.stopClip();
+ host.timeline.stop();
}
-fn slot(value: []const u8, min: usize, max: usize) !usize {
- const index = std.fmt.parseInt(usize, value, 10) catch return error.InvalidSlot;
- if (index < min or index > max) return error.InvalidSlot;
- return index;
+/// The keyframe of the newest mark `n`, or of mark number K for "#K".
+pub fn loadMark(host: *Host, n: []const u8) !Sessions.Loaded {
+ const s = &host.sessions;
+ const found = if (n.len > 1 and n[0] == '#')
+ try s.markAt(std.fmt.parseInt(u64, n[1..], 10) catch return error.InvalidName)
+ else
+ try s.findMark(n) orelse return error.EmptySnapshot;
+ return s.load(found.session, found.key);
+}
+
+/// Mark `n`'s State in today's layout (`arena`'s), and the layout it was
+/// taken in: compare them over the leaves migration kept (`memory.compareKept`).
+pub fn markState(host: *Host, arena: std.mem.Allocator, n: []const u8) !struct { bytes: []u8, layout: memory.Layout } {
+ const key = try loadMark(host, n);
+ defer key.free(host.gpa);
+ const bytes = try arena.alignedAlloc(u8, .fromByteUnits(memory.page), host.state.layout.size);
+ const layout = try memory.restore(arena, key.layout, key.state, host.state.layout, bytes, host.timeline.defaults);
+ return .{ .bytes = bytes, .layout = layout };
+}
+
+/// Makes clip `n` the one the timeline plays: its keyframe and frames.
+fn loadClip(host: *Host, n: []const u8) !void {
+ const s = &host.sessions;
+ const clip = try s.findClip(n) orelse return error.EmptyRecording;
+ const key = try s.load(clip.session, clip.key);
+ errdefer key.free(host.gpa);
+ var events: std.ArrayList(abi.Event) = .empty;
+ errdefer events.deinit(host.gpa);
+ // A clip a crash left open ends where its session does.
+ const end = if (clip.end != 0) clip.end else (try s.summary(clip.session)).frames;
+ try s.events(clip.session, key.batch, clip.start, end, &events);
+ host.timeline.load(key, events);
+}
+
+/// Plays session `index` from its start, or paused `at` nanoseconds into
+/// it: from the newest keyframe before then, replayed up to it.
+fn playSession(self: *Console, host: *Host, index: u64, at: ?u64, now: u64) ![]const abi.Event {
+ const s = &host.sessions;
+ const h = &host.timeline;
+ if (index == s.session) try s.commit(.none);
+ const sum = try s.summary(index);
+ if (sum.keys == 0) return error.EmptyRecording;
+ const t0 = (try s.keyAt(index, 0)).time;
+ const k = if (at) |t| try s.keyBefore(index, .time, t0 + t) orelse 0 else 0;
+ const key = try s.load(index, k);
+ errdefer key.free(host.gpa);
+ var events: std.ArrayList(abi.Event) = .empty;
+ errdefer events.deinit(host.gpa);
+ try s.events(index, key.batch, key.frame, sum.frames, &events);
+ var checks: @TypeOf(h.checks) = .empty;
+ errdefer checks.deinit(host.gpa);
+ for (k + 1..sum.keys) |j| {
+ const later = try s.keyAt(index, j);
+ try checks.append(host.gpa, .{ .frame = later.frame, .key = j, .observed = switch (later.why) {
+ .periodic, .mark, .before_reload, .exit => true,
+ else => false,
+ } });
+ }
+ h.load(key, events);
+ h.session = index;
+ h.checks = checks;
+ try h.play(now);
+ self.print("Playing session {d} from frame {d}.", .{ index, key.frame });
+ if (key.build != host.build or !eq(key.source, host.source)) self.print("session {d} frame {d} was built from {s}; replaying with {s}", .{ index, key.frame, key.source, host.source });
+ if (at) |t| return h.seekTime((t0 + t) -| h.base);
+ return &.{};
+}
+
+/// A replay of a clip made by other code may diverge: say so.
+fn warnBuild(self: *Console, host: *const Host) void {
+ const key = host.timeline.key orelse return;
+ if (key.build != 0 and host.build != 0 and key.build != host.build) self.log("Warning: recorded by another build of the sketch; the replay may differ.");
+}
+
+/// The last marks or clips: index, name, session and frame.
+fn listNamed(self: *Console, host: *Host, marks: bool) !void {
+ const s = &host.sessions;
+ const n = try s.count(if (marks) .marks else .clips);
+ if (n == 0) return self.log(if (marks) "No marks: save NAME makes one." else "No clips: record NAME makes one.");
+ var i = n -| 5;
+ while (i < n) : (i += 1) {
+ const e = if (marks) try s.markAt(i) else try s.clipAt(i);
+ const label = e.name();
+ if (marks) {
+ // An older mark of a name may have gone with history.
+ const key = s.keyAt(e.session, e.key) catch {
+ self.print("#{d} {s}: session {d}, dropped", .{ i, label, e.session });
+ continue;
+ };
+ self.print("#{d} {s}: session {d} frame {d}", .{ i, label, e.session, key.frame });
+ } else self.print("#{d} {s}: session {d} frames {d}..{d}", .{ i, label, e.session, e.start, e.end });
+ }
+}
+
+fn eq(a: []const u8, b: []const u8) bool {
+ return std.mem.eql(u8, a, b);
}
test "line editing, completion and submission" {
diff --git a/src/host/Host.zig b/src/host/Host.zig
index 035a004..0a8eeee 100644
--- a/src/host/Host.zig
+++ b/src/host/Host.zig
@@ -9,7 +9,6 @@ const abi = @import("abi");
const memory = @import("memory.zig");
const playback = @import("timeline.zig");
const Timeline = playback.Timeline;
-const mapRecordings = playback.mapRecordings;
const gfx = @import("gfx.zig");
const sound = @import("audio.zig");
const Gpu = @import("gpu");
@@ -20,6 +19,7 @@ const Presentation = @import("Presentation.zig");
const timing_marker = @import("timing_marker.zig");
const Control = @import("control.zig").Control;
const Library = @import("library.zig").Library;
+const Sessions = @import("Sessions.zig");
const Watch = @import("library.zig").Watch;
pub const Options = struct {
@@ -27,11 +27,17 @@ pub const Options = struct {
library: ?[]const u8 = null,
/// Local 9P control socket, opt-in.
ninep: ?[]const u8 = null,
- /// State file; recordings go next to it with an `.inputs` suffix.
- state: []const u8 = "sketch.state",
+ /// The save, a sessions database: `<stem>.xitdb`, for a path
+ /// `<stem>.xitdb`, `<stem>.state` (where a state file from before is
+ /// imported from) or `<stem>`. Empty: `$XDG_DATA_HOME/<name>/<name>.xitdb`
+ /// (`~/.local/share` without it), for a shipped game.
+ state: []const u8 = "",
+ /// Playing a script: from fresh state, sessions go to memory only.
+ script: bool = false,
/// Offscreen video, silent audio, no vsync: for scripts and CI.
headless: bool = false,
- /// Forget the state file's contents: scripts start from a known place.
+ /// Start from State's defaults, not the save's present: scripts start
+ /// from a known place.
fresh: bool = false,
/// Time every GPU command alone and print the times at exit.
profile_gpu: bool = false,
@@ -66,16 +72,16 @@ images: gfx.Images,
/// Plays the 2D commands: targets, blend, antialiased shapes.
painter: gfx.Painter,
audio: sound.Audio,
-state: memory.StateFile,
+state: memory.State,
session: memory.Session,
/// A failed resource setup disables app callbacks while keeping host controls alive.
session_ready: bool = false,
-store: memory.StoreFile,
/// Images and buffers the sketch made (`newImage`, `decodeImage`,
/// `newBuffer`): Session holds their handles, so they go when it resets.
made: struct { images: std.ArrayList(abi.Image) = .empty, buffers: std.ArrayList(abi.Buffer) = .empty } = .{},
-recordings: []align(memory.page) u8,
timeline: Timeline,
+/// This run's session and the ones before it (Sessions.zig).
+sessions: Sessions,
console: Console = .{},
timing: Timing = .{},
timing_atlas: overlay.TimingAtlas = .{},
@@ -83,12 +89,20 @@ sketch: abi.Sketch,
library: ?Library = null,
watch: ?Watch = null,
reloads: usize = 0,
-/// Identifies the running build of the sketch (a hash of its library or
-/// executable file): recordings carry it, and `play` warns on a mismatch.
+/// Identifies the running build of the sketch (its library or executable
+/// file's inode, size and modification time): sessions' stretches carry it,
+/// and `play` warns on a mismatch.
build: u64 = 0,
+/// The save's path when the host chose it (`Options.state`), `gpa`'s.
+state_path: []const u8 = "",
+/// `Options.state` without `.xitdb` or `.state`: the save is
+/// `<stem>.xitdb`, the sketch's own files `<stem>.<name>`.
+stem: []const u8 = "",
/// Copies of the sketch's info strings, replaced on every load.
info_arena: std.heap.ArenaAllocator,
name: []const u8 = "",
+/// The sketch's `Info.source`, for the session's stretches.
+source: []const u8 = "",
completions: []const []const u8 = &.{},
/// Frame lifetime: sketch scratch and this frame's commands.
frame_arena: std.heap.ArenaAllocator,
@@ -97,6 +111,11 @@ commands: std.ArrayList(abi.Command) = .empty,
pending: std.ArrayList(abi.Event) = .empty,
input: abi.Input = .{},
files: std.StringHashMapUnmanaged([]align(memory.page) const u8) = .empty,
+/// Mappings of files `writeFile` replaced: the sketch may still hold them.
+retired: std.ArrayList([]align(memory.page) const u8) = .empty,
+/// The paths `appendFile` wrote, each once, 0-terminated: the sketch keeps
+/// them.
+written: std.StringHashMapUnmanaged(void) = .empty,
canvas: [2]u32 = .{ 0, 0 },
cursor: abi.Cursor = .arrow,
quit: bool = false,
@@ -114,7 +133,8 @@ exported: u64 = 0,
dialog: Dialog = .{},
control: ?*Control = null,
-pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, options: Options, linked: ?abi.Sketch) !void {
+pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, given: Options, linked: ?abi.Sketch) !void {
+ var options = given;
if (options.headless) {
// Overriding: a plain hint loses to the environment, and a user's
// SDL_VIDEO_DRIVER=wayland would open real windows during tests.
@@ -128,7 +148,7 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std
var library: ?Library = null;
const sketch = linked orelse blk: {
const path = options.library orelse return error.NoSketch;
- library = try Library.openCopy(io, path, scratchDir(environ), 0);
+ library = try Library.openFresh(io, path, scratchDir(environ), 0);
break :blk library.?.sketch;
};
errdefer if (library) |*l| l.close();
@@ -158,17 +178,16 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std
// Colors carry alpha: fills blend, as they do on the web.
_ = c.SDL_SetRenderDrawBlendMode(renderer, c.SDL_BLENDMODE_BLEND);
- var state = try memory.StateFile.open(gpa, options.state);
- errdefer state.close();
- var inputs_buf: [std.fs.max_path_bytes]u8 = undefined;
- const recordings = try mapRecordings(try std.mem.print(&inputs_buf, "{s}.inputs", .{options.state}));
- errdefer std.posix.munmap(recordings);
- var store_buf: [std.fs.max_path_bytes]u8 = undefined;
- var store = memory.StoreFile.open(gpa, try std.mem.print(&store_buf, "{s}.store", .{options.state}), options.fresh) catch |err| {
- if (err == error.StoreInUse) std.log.err("{s}.store is open in another process", .{options.state});
- return err;
+ var data_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const state_path = if (given.state.len > 0) "" else blk: {
+ const data = environ.get("XDG_DATA_HOME") orelse try std.fmt.bufPrint(&data_buf, "{s}/.local/share", .{environ.get("HOME") orelse "."});
+ const path = try std.fmt.allocPrint(gpa, "{s}/{s}/{s}.xitdb", .{ data, info.name, info.name });
+ errdefer gpa.free(path);
+ try std.Io.Dir.cwd().createDirPath(io, std.fs.path.dirname(path).?);
+ break :blk path;
};
- errdefer store.close();
+ errdefer gpa.free(state_path);
+ if (state_path.len > 0) options.state = state_path;
self.* = .{
.gpa = gpa,
@@ -181,37 +200,37 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std
.images = .{ .gpa = gpa, .renderer = renderer.? },
.painter = .{ .renderer = renderer.?, .images = undefined, .smooth = gpu != null },
.audio = .{ .gpa = gpa },
- .state = state,
+ .state = .init(gpa),
.session = .init(gpa),
- .store = store,
- .recordings = recordings,
.timeline = undefined,
+ .sessions = .{ .gpa = gpa, .io = io },
.sketch = sketch,
.library = library,
+ .state_path = state_path,
+ .stem = stemOf(options.state),
.info_arena = .init(gpa),
.frame_arena = .init(gpa),
.input = .{ .exporting = options.export_to != null },
};
- self.timeline = .{ .bank = .{ .state = &self.state, .inputs = recordings } };
+ self.timeline = .{ .gpa = gpa, .state = &self.state, .defaults = sketch.defaults };
self.painter.images = &self.images;
if (gpu) |device| self.passes = .init(gpa, device);
if (options.profile_gpu) if (self.passes) |*g| {
g.profile = .init(gpa);
};
- self.audio.open() catch |err| std.log.warn("audio unavailable: {t}", .{err});
+ self.audio.open(info.audio_pull) catch |err| std.log.warn("audio unavailable: {t}", .{err});
if (options.library) |path| if (linked == null) {
self.watch = Watch.init(path) catch null;
};
const size = options.size orelse [2]u32{ info.width, info.height };
self.setCanvas(size[0], size[1]);
_ = c.SDL_StartTextInput(self.window);
- self.build = fileHash(options.library orelse "/proc/self/exe");
+ self.build = fileId(io, options.library orelse "/proc/self/exe");
try self.adopt(sketch);
- if (options.fresh) {
- self.state.header().used = 0;
- @memset(self.recordings, 0);
- self.resetState();
- }
+ self.openSessions(info.record);
+ // Before --fresh, which never touches the save.
+ self.openPresent();
+ if (options.fresh) self.resetState();
if (!options.headless and options.export_to == null) {
self.presentation = Presentation.init(gpa, self.window) catch null;
if (options.timing_marker) self.print("presentation tracing: {s}", .{if (self.presentation) |p| p.status else "disabled_or_allocation_failed"});
@@ -219,6 +238,7 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std
}
pub fn deinit(self: *Host) void {
+ self.sessions.close(self.live(), wallClock(self.io));
if (self.control) |control| control.deinit();
self.dialog.deinit();
if (self.watch) |w| w.deinit();
@@ -238,15 +258,25 @@ pub fn deinit(self: *Host) void {
std.posix.munmap(entry.value_ptr.*);
}
self.files.deinit(self.gpa);
- std.posix.munmap(self.recordings);
+ for (self.retired.items) |bytes| std.posix.munmap(bytes);
+ self.retired.deinit(self.gpa);
+ // A scripted run from fresh state, or an export, leaves no files.
+ const private = (self.options.script or self.options.export_to != null) and self.options.fresh;
+ var written = self.written.keyIterator();
+ while (written.next()) |path| {
+ if (private) std.Io.Dir.cwd().deleteFile(self.io, path.*) catch {};
+ self.gpa.free(path.ptr[0 .. path.len + 1]);
+ }
+ self.written.deinit(self.gpa);
+ self.timeline.deinit();
self.session.deinit(self.gpa);
- self.store.close();
self.made.images.deinit(self.gpa);
self.made.buffers.deinit(self.gpa);
- self.state.close();
+ self.state.deinit(self.gpa);
self.pending.deinit(self.gpa);
self.frame_arena.deinit();
self.info_arena.deinit();
+ self.gpa.free(self.state_path);
if (self.library) |*l| l.close();
c.SDL_Quit();
}
@@ -254,7 +284,15 @@ pub fn deinit(self: *Host) void {
/// The interactive loop. An export runs it on a clock of its own, frame k
/// at k/fps seconds (from 1 s, as scripts do), whatever the wall clock says.
pub fn run(self: *Host) !void {
- if (self.options.ninep) |path| self.control = try Control.init(self.gpa, path);
+ // A run a person watches posts its tree as sketchbook/<name>; --9p
+ // names another, or a socket path.
+ const o = self.options;
+ const ninep = o.ninep orelse if (o.headless or o.script or o.export_to != null) null else self.name;
+ if (ninep) |where| self.control = Control.open(self.gpa, self.environ, where) catch |err| blk: {
+ if (o.ninep != null) return err;
+ self.print("not posted as sketchbook/{s}: {t}", .{ where, err });
+ break :blk null;
+ };
while (!self.quit) {
if (self.control) |control| control.poll(self);
try self.poll();
@@ -282,7 +320,7 @@ pub fn run(self: *Host) !void {
frameTime(wall, if (self.presentation) |p| p.sampleNs(wall) else wall, self.last_now, self.timeline.mode, self.pending.items);
try self.frame(now);
}
- self.timeline.stop(c.SDL_GetTicksNS());
+ self.timeline.stop();
}
// Live animation uses the display clock, but a tick must not predate its input.
@@ -307,7 +345,7 @@ test "timing clock drives ordinary ticks without moving input or replay time" {
}
pub fn live(self: *Host) []u8 {
- return self.state.slot(0);
+ return self.state.live();
}
/// One frame: reload if a build replaced the library, feed input through
@@ -325,8 +363,11 @@ pub fn frame(self: *Host, now: u64) !void {
self.last_now = now;
const h = &self.timeline;
switch (h.mode) {
- .playing => self.update(h.tick(now)),
- .paused => {},
+ .playing => {
+ self.sessions.away = true;
+ self.update(h.tick(now));
+ },
+ .paused => self.sessions.away = true,
.live, .recording => {
// One frame: what was routed since the last one, then its tick.
// Recorded first, so `update` sees the times a replay will.
@@ -334,12 +375,14 @@ pub fn frame(self: *Host, now: u64) !void {
// An export's tick is 1/fps itself, not whole nanoseconds of it.
if (self.options.export_to != null and dt != 0) tick.x = 1 / @as(f32, @floatFromInt(self.options.fps));
try self.pending.append(self.gpa, tick);
- h.capture(self.pending.items) catch |err| self.print("Recording stopped: {t}", .{err});
+ const why: ?Sessions.Why = if (self.sessions.frames == 0) .start else if (self.reloaded) .after_reload else if (self.jumped or self.sessions.away) .jump else null;
+ self.sessions.away = false;
+ self.sessions.frame(self.pending.items, self.live(), why) catch |err| self.print("session: {t}", .{err});
self.update(self.pending.items);
},
}
self.pending.clearRetainingCapacity();
- const work = try self.draw(if (h.mode == .live or h.mode == .recording) now else h.position, started);
+ const work = try self.draw(if (h.mode == .live or h.mode == .recording) now else h.base + h.position, started);
const ended = c.SDL_GetTicksNS();
self.timing.add(.{ .frame = ended - (if (self.last_frame_end == 0) started else self.last_frame_end), .work = work });
self.last_frame_end = ended;
@@ -362,10 +405,42 @@ pub fn update(self: *Host, events: []const abi.Event) void {
self.started = false;
const ctx = self.context();
self.sketch.update(&ctx, self.live().ptr);
+ if (self.timeline.mode == .playing or self.timeline.mode == .paused) self.resync();
}
self.input.events = &.{};
}
+/// After a replayed frame of a past session: at each keyframe it reaches,
+/// live state is compared with the keyframe (over the leaves migration
+/// kept), any difference said, and the keyframe restored.
+fn resync(self: *Host) void {
+ const h = &self.timeline;
+ h.fed += 1;
+ const session = h.session orelse return;
+ const reached = h.key.?.frame + h.fed;
+ while (h.next_check < h.checks.items.len and h.checks.items[h.next_check].frame <= reached) {
+ const check = h.checks.items[h.next_check];
+ h.next_check += 1;
+ if (check.frame < reached) continue;
+ const key = self.sessions.load(session, check.key) catch |err| return self.print("session {d} keyframe {d}: {t}", .{ session, check.key, err });
+ defer key.free(self.gpa);
+ var arena: std.heap.ArenaAllocator = .init(self.gpa);
+ defer arena.deinit();
+ const saved = arena.allocator().alignedAlloc(u8, .fromByteUnits(memory.page), self.state.layout.size) catch return;
+ const from = memory.restore(arena.allocator(), key.layout, key.state, self.state.layout, saved, self.sketch.defaults) catch |err| return self.print("session {d} keyframe {d}: {t}", .{ session, check.key, err });
+ if (check.observed) {
+ const diff = memory.compareKept(from, self.state.layout, self.live(), saved);
+ if (diff.first) |first| {
+ var buf: [96]u8 = undefined;
+ var w: std.Io.Writer = .fixed(&buf);
+ first.leaf.name(first.offset, &w) catch {};
+ self.print("diverged before frame {d}: {d} values, first {s}", .{ reached, diff.count, w.buffered() });
+ }
+ }
+ @memcpy(self.live(), saved);
+ }
+}
+
/// After live state was restored from a snapshot: the pointer, buttons and
/// keys tracked so far belong to other bytes, so they start over. A new
/// recording then begins with events that bring back what is held now, so
@@ -380,7 +455,7 @@ fn restoredInput(self: *Host, now: u64) !void {
self.input.mouse_y = 0;
self.input.buttons = 0;
self.input.keys = .empty;
- if (h.mode != .recording or h.bank.recording(h.selected).count != 0) return;
+ if (h.mode != .recording) return;
var seed: std.ArrayList(abi.Event) = .empty;
defer seed.deinit(self.gpa);
if (was.mouse_x != 0 or was.mouse_y != 0) try seed.append(self.gpa, .{ .kind = .mouse_move, .time = now, .x = was.mouse_x, .y = was.mouse_y });
@@ -419,6 +494,7 @@ fn draw(self: *Host, now: u64, started: u64) !u64 {
}
}
self.input.streams = self.audio.streamStatus();
+ self.input.lead = self.audio.lead;
self.input.sample_rate = sound.sample_rate;
self.input.microphone = self.audio.record(arena);
self.input.downloads = if (self.passes) |*g| try g.collect(arena) else &.{};
@@ -444,7 +520,12 @@ fn draw(self: *Host, now: u64, started: u64) !u64 {
},
.cursor => |kind| self.cursor = kind,
.voice => |voice| self.audio.declare(voice),
+ .gain => |g| self.audio.gains[g.group] = g.gain,
.audio => |a| self.audio.push(a.key, a.samples, a.clear),
+ .audio_buffer => |a| if (self.passes) |*g| if (a.count > 0) {
+ const samples = try arena.alloc(f32, a.count);
+ if (g.read(a.buffer, a.offset, std.mem.sliceAsBytes(samples))) self.audio.push(a.key, samples, false) else |err| self.print("gpu audio: {t} ({s})", .{ err, c.SDL_GetError() });
+ },
.quit => self.quit = true,
.gpu => |pass| if (self.passes) |*g| self.runGpu(g, pass) catch |err| self.print("gpu pass: {t} ({s})", .{ err, c.SDL_GetError() }),
.post_process => |p| if (self.passes) |*g| self.runPostProcess(g, p.source, p.target, p.effect) catch |err| self.print("gpu postprocess: {t} ({s})", .{ err, c.SDL_GetError() }),
@@ -465,7 +546,7 @@ fn draw(self: *Host, now: u64, started: u64) !u64 {
if (self.console.overlay_memory) try overlay.drawMemory(&extra, arena, self.state.layout, self.live(), self.input.width);
if (self.console.overlay_sound) {
const samples = self.audio.scope.snapshot();
- try overlay.drawScope(&extra, arena, &samples, self.audio.scope.rate, self.canvas);
+ try overlay.drawScope(&extra, arena, &samples, self.audio.scope.rate, self.audio.pull, self.canvas);
}
if (self.timing.visible) {
if (self.timing_atlas.image == .none) self.timing_atlas = try overlay.TimingAtlas.init(&self.images, &self.painter);
@@ -592,9 +673,7 @@ fn context(self: *Host) abi.Context {
.input = &self.input,
.scratch = self.frame_arena.allocator(),
.session = self.session.heap.allocator(),
- .store = self.store.allocator(),
.session_root = self.session.bytes.ptr,
- .store_root = self.store.root(),
.commands = &self.commands,
};
}
@@ -636,24 +715,32 @@ pub fn runLine(self: *Host, line: []const u8, now: u64) !void {
defer zone.end();
const replay = self.console.execute(self, line, now) catch |err| {
// The sketch has printed its own error already.
- if (err != error.CommandFailed) self.console.print("{t}. Type help for usage.", .{err});
+ if (err == error.NotRecording) {
+ self.console.log("Not recording (an export): no marks or clips.");
+ } else if (err == error.HistoryDropped) {
+ self.console.log("That part of the history is gone: a save keeps 64 MiB, the newest.");
+ } else if (err == error.SaveFull) {
+ self.console.log("No room for a new mark: marks and the present fill the save. Save over a mark's name (its older one goes with history), or start another save (--state).");
+ } else if (err != error.CommandFailed) self.console.print("{t}. Type help for usage.", .{err});
if (self.timeline.restored) self.jumped = true;
try self.restoredInput(now);
return err;
};
- if (self.timeline.restored or movesState(line)) self.jumped = true;
+ if (self.timeline.restored or movesState(line)) {
+ self.jumped = true;
+ self.sessions.noteLine(line);
+ }
try self.restoredInput(now);
if (self.timeline.mode == .paused) self.update(replay);
}
/// Whether a console line that succeeded may have changed State other than
-/// through `update` (restoring a snapshot is caught apart from this).
+/// through `update` (restoring a snapshot is caught apart from this): a
+/// sketch's command may.
fn movesState(line: []const u8) bool {
var words = std.mem.tokenizeAny(u8, line, " \t");
- const verb = words.next() orelse return false;
- const still = [_][]const u8{ "help", "overlay", "timing", "get", "snapshot", "recording", "diff", "stop", "pause", "save", "quit", "exit" };
- for (still) |w| if (std.mem.eql(u8, verb, w)) return false;
- return true;
+ const verb = std.meta.stringToEnum(Console.Verb, words.next() orelse return false) orelse return true;
+ return Console.verbs.get(verb).moves_state;
}
/// Offers a line to the sketch.
@@ -674,7 +761,6 @@ pub fn resetState(self: *Host) void {
self.sketch.defaults(.state, bytes.ptr);
const ctx = self.context();
self.sketch.init(&ctx, bytes.ptr);
- self.state.markUsed(0, true);
}
/// Loads the watched library again.
@@ -684,47 +770,42 @@ pub fn reload(self: *Host) !void {
/// Replaces the running sketch with the library at `path`, keeping state.
pub fn load(self: *Host, path: []const u8) !void {
- var library = try Library.openCopy(self.io, path, scratchDir(self.environ), self.reloads + 1);
+ var library = try Library.openFresh(self.io, path, scratchDir(self.environ), self.reloads + 1);
errdefer library.close();
+ // The State in the layout it is leaving, before migration drops any of it.
+ if (self.sessions.mode() != .off) _ = self.sessions.keyframe(.before_reload, self.live()) catch |err| self.print("session: {t}", .{err});
try self.adopt(library.sketch);
if (self.library) |*old| old.close();
self.library = library;
self.reloads += 1;
- self.build = fileHash(path);
+ self.build = fileId(self.io, path);
+ self.sessions.stretch(.{ .build = self.build, .source = self.source, .layout = self.state.header }) catch |err| self.print("session: {t}", .{err});
self.print("reload {d}: {s}", .{ self.reloads, path });
}
fn adopt(self: *Host, sketch: abi.Sketch) !void {
const info = sketch.info();
if (info.abi != abi.hash) return error.AbiMismatch;
- const adoption = try self.state.adopt(self.gpa, info.state, sketch.defaults);
+ const migrated = try self.state.adopt(self.gpa, info.state, sketch.defaults);
const session_reset = try self.session.adopt(self.gpa, info.session, sketch.defaults);
if (session_reset) self.releaseMade();
- const stored = try self.store.adopt(self.gpa, info.store, sketch.defaults);
_ = self.info_arena.reset(.retain_capacity);
const arena = self.info_arena.allocator();
self.name = try arena.dupe(u8, info.name);
+ self.source = try arena.dupe(u8, info.source);
const completions = try arena.alloc([]const u8, info.commands.len);
for (completions, info.commands) |*to, from| to.* = try arena.dupe(u8, from);
self.completions = completions;
self.sketch = sketch;
+ self.timeline.defaults = sketch.defaults;
self.reloaded = true;
- switch (adoption) {
- .unchanged => {},
- .created => {},
- .migrated => |m| self.print("state layout changed: kept {d} fields, reset {d} to defaults", .{ m.kept, m.reset }),
- }
- if (!self.state.used(0)) self.resetState();
+ if (migrated) |m| self.print("state layout changed: kept {d} fields, reset {d} to defaults", .{ m.kept, m.reset });
if (session_reset) {
const ctx = self.context();
self.session_ready = self.sketch.setup(&ctx);
if (!self.session_ready) self.console.visible = true;
}
if (session_reset and self.reloads > 0) self.print("session layout changed: session reset", .{});
- switch (stored) {
- .unchanged, .created => {},
- .migrated => |m| self.print("store layout changed: kept {d} fields, reset {d} to defaults", .{ m.kept, m.reset }),
- }
}
/// Frees what the old Session made: its handles are gone with it.
@@ -868,15 +949,102 @@ fn consoleKey(e: abi.Event) ?Console.Key {
};
}
-/// A hash of a file's bytes; 0 when it cannot be read.
-fn fileHash(path: []const u8) u64 {
- const bytes = memory.mapReadOnly(path);
- if (bytes.len == 0) return 0;
- defer std.posix.munmap(bytes);
- return std.hash.Wyhash.hash(0, bytes) | 1;
+/// Opens the save (Sessions.zig) and starts this run's session in it: a
+/// file, `<stem>.xitdb`; in memory for a script from fresh state; nowhere
+/// for an export. A save that cannot be opened is said, and the run goes
+/// on unsaved.
+fn openSessions(self: *Host, record: bool) void {
+ const o = self.options;
+ const mode: Sessions.Mode = if (o.export_to != null) .off else if (o.script and o.fresh) .memory else .file;
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const path = std.fmt.bufPrint(&buf, "{s}.xitdb", .{self.stem}) catch "sketch.xitdb";
+ const first: Sessions.Stretch = .{ .build = self.build, .source = self.source, .layout = self.state.header };
+ self.sessions = Sessions.open(self.gpa, self.io, mode, path, first, wallClock(self.io)) catch |err| blk: {
+ self.print("not saved: {s}: {t}", .{ path, err });
+ break :blk .{ .gpa = self.gpa, .io = self.io };
+ };
+ // Without `.record`, history is trimmed to the present and the marks.
+ self.sessions.history = record;
+ if (o.headless or self.sessions.mode() != .file) return;
+ self.print("{s} to {s}", .{ if (record) "recording" else "saving", path });
+}
+
+/// The State this run starts from: the save's present, its newest keyframe
+/// and the frames logged after it, replayed; in a new save, a state file
+/// from before (`<stem>.state`), imported once and left as it was; else
+/// `init`'s.
+fn openPresent(self: *Host) void {
+ var events: std.ArrayList(abi.Event) = .empty;
+ defer events.deinit(self.gpa);
+ const found = self.sessions.present(&events) catch |err| blk: {
+ self.print("the save's present did not read ({t}): starting from defaults", .{err});
+ break :blk null;
+ };
+ const key = found orelse {
+ if (self.sessions.session != 0 or self.sessions.mode() != .file) return self.resetState();
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const old = std.fmt.bufPrint(&buf, "{s}.state", .{self.stem}) catch return self.resetState();
+ const n = importOld(self.gpa, old, &self.state, &self.sessions, self.sketch.defaults) catch |err| {
+ if (err != error.FileNotFound) self.print("{s} not imported ({t}): kept as it was", .{ old, err });
+ return self.resetState();
+ };
+ return self.print("{s} imported: its State, and {d} snapshots as marks; the file is kept as it was", .{ old, n });
+ };
+ defer key.free(self.gpa);
+ self.timeline.restore(key) catch |err| {
+ self.print("the save's present did not restore ({t}): starting from defaults", .{err});
+ return self.resetState();
+ };
+ self.timeline.restored = false;
+ var frames: usize = 0;
+ for (events.items) |e| frames += @intFromBool(e.kind == .tick);
+ if (frames == 0) return;
+ if (key.build != self.build) return self.print("{d} frames played after the save's last keyframe not replayed: another build", .{frames});
+ // As they were fed: `started` only for a run's first frame.
+ self.started = key.frame == 0;
+ self.update(events.items);
+ self.started = true;
+}
+
+/// A state file from before (`path`) into a new save: its live State into
+/// `state`, its snapshots (slots 1..7) marks "1".."7", in `state`'s layout;
+/// the file is left as it was. Returns the number of marks.
+fn importOld(gpa: std.mem.Allocator, path: []const u8, state: *memory.State, sessions: *Sessions, defaults: *const fn (abi.Memory, [*]u8) callconv(.c) void) !usize {
+ const old = try memory.OldState.open(path);
+ defer old.close();
+ var arena: std.heap.ArenaAllocator = .init(gpa);
+ defer arena.deinit();
+ const scratch = try arena.allocator().alignedAlloc(u8, .fromByteUnits(memory.page), state.layout.size);
+ var n: usize = 0;
+ for (1..old.slots) |i| if (old.slot(i)) |image| {
+ _ = try memory.restore(arena.allocator(), old.layoutBytes(), image, state.layout, scratch, defaults);
+ _ = try sessions.mark(&.{'0' + @as(u8, @intCast(i))}, .import, scratch);
+ n += 1;
+ };
+ _ = try memory.restore(arena.allocator(), old.layoutBytes(), old.slot(0) orelse return error.CorruptStateFile, state.layout, state.live(), defaults);
+ return n;
+}
+
+/// `path` without `.xitdb` or `.state`.
+pub fn stemOf(path: []const u8) []const u8 {
+ for ([_][]const u8{ ".xitdb", ".state" }) |suffix| if (std.mem.endsWith(u8, path, suffix)) return path[0 .. path.len - suffix.len];
+ return path;
+}
+
+fn wallClock(io: std.Io) u64 {
+ return @intCast(@max(0, std.Io.Timestamp.now(io, .real).nanoseconds));
}
-fn scratchDir(environ: *const std.process.Environ.Map) []const u8 {
+/// Identifies the file at `path` without reading it (a Debug library is tens
+/// of megabytes): a hash of its inode, size and modification time; 0 when
+/// there is none. A build replaces the file, so each build gets a new one.
+fn fileId(io: std.Io, path: []const u8) u64 {
+ const stat = std.Io.Dir.cwd().statFile(io, path, .{}) catch return 0;
+ const id = [3]u64{ stat.inode, stat.size, @truncate(@as(u96, @bitCast(stat.mtime.nanoseconds))) };
+ return std.hash.Wyhash.hash(0, std.mem.asBytes(&id)) | 1;
+}
+
+pub fn scratchDir(environ: *const std.process.Environ.Map) []const u8 {
return environ.get("XDG_RUNTIME_DIR") orelse "/tmp";
}
@@ -900,8 +1068,10 @@ const api: abi.Host.VTable = .{
.textSize = apiTextSize,
.loadSound = apiLoadSound,
.decodeSound = apiDecodeSound,
+ .newSound = apiNewSound,
.samples = apiSamples,
.readFile = apiReadFile,
+ .appendFile = apiAppendFile,
.env = apiEnv,
.clock = apiClock,
};
@@ -966,6 +1136,9 @@ fn apiLoadSound(ctx: *anyopaque, path: []const u8) abi.Audio {
fn apiDecodeSound(ctx: *anyopaque, wav: []const u8) abi.Audio {
return hostOf(ctx).audio.decode(wav);
}
+fn apiNewSound(ctx: *anyopaque, samples: [*]const f32, len: usize) callconv(.c) abi.Audio {
+ return hostOf(ctx).audio.new(samples[0..len]);
+}
fn apiReadFile(ctx: *anyopaque, path: []const u8) []const u8 {
const self = hostOf(ctx);
if (self.files.get(path)) |bytes| return bytes;
@@ -975,6 +1148,47 @@ fn apiReadFile(ctx: *anyopaque, path: []const u8) []const u8 {
self.files.put(self.gpa, key, bytes) catch self.gpa.free(key);
return bytes;
}
+fn apiAppendFile(ctx: *anyopaque, name_ptr: [*]const u8, name_len: usize, bytes: [*]const u8, len: usize, replace: bool) callconv(.c) [*:0]const u8 {
+ const self = hostOf(ctx);
+ const name = name_ptr[0..name_len];
+ if (name.len == 0 or std.mem.indexOfScalar(u8, name, '/') != null) {
+ self.print("appendFile: {s}: a name, not a path", .{name});
+ return "";
+ }
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const o = self.options;
+ const private = (o.script or o.export_to != null) and o.fresh;
+ // A scripted run from fresh state, or an export, writes files of its own
+ // (two runs of one build step may share a directory), gone at exit.
+ const path = (if (private) std.mem.print(&buf, "{s}.{d}.{s}", .{ self.stem, std.os.linux.getpid(), name }) else std.mem.print(&buf, "{s}.{s}", .{ self.stem, name })) catch return "";
+ if (replace) {
+ // A new file: a mapping of the old one stays valid.
+ std.Io.Dir.cwd().deleteFile(self.io, path) catch {};
+ if (self.files.fetchRemove(path)) |old| {
+ self.gpa.free(old.key);
+ self.retired.append(self.gpa, old.value) catch {};
+ }
+ }
+ const file = std.Io.Dir.cwd().createFile(self.io, path, .{ .truncate = false }) catch |err| {
+ self.print("appendFile: {s}: {t}", .{ path, err });
+ return "";
+ };
+ defer file.close(self.io);
+ const end = file.length(self.io) catch return "";
+ file.writePositionalAll(self.io, bytes[0..len], end) catch |err| {
+ self.print("appendFile: {s}: {t}", .{ path, err });
+ return "";
+ };
+ const kept = self.written.getOrPut(self.gpa, path) catch return "";
+ if (!kept.found_existing) {
+ const copy = self.gpa.dupeSentinel(u8, path, 0) catch {
+ self.written.removeByPtr(kept.key_ptr);
+ return "";
+ };
+ kept.key_ptr.* = copy;
+ }
+ return @ptrCast(kept.key_ptr.*.ptr);
+}
fn apiClock(_: *anyopaque) u64 {
return c.SDL_GetTicksNS();
}
@@ -1004,11 +1218,10 @@ test "session setup runs for restored state and layout reset, not same-layout re
const State = extern struct { value: u32 = 1 };
const Session1 = extern struct { ready: u32 = 0 };
const Session2 = extern struct { ready: u32 = 0, extra: u32 = 0 };
- const Store = struct {};
var setup_calls: usize = 0;
var init_calls: usize = 0;
var fail_setup = false;
- const description: abi.Info = .{ .abi = abi.hash, .name = "setup-test", .width = 1, .height = 1, .state = abi.layout.of(State, .state), .session = abi.layout.of(Session1, .session), .store = abi.layout.of(Store, .store) };
+ const description: abi.Info = .{ .abi = abi.hash, .name = "setup-test", .width = 1, .height = 1, .state = abi.layout.of(State, .state), .session = abi.layout.of(Session1, .session) };
const changed: abi.Info = blk: {
var value = description;
value.session = abi.layout.of(Session2, .session);
@@ -1024,7 +1237,6 @@ test "session setup runs for restored state and layout reset, not same-layout re
switch (kind) {
.state => @as(*State, @ptrCast(@alignCast(ptr))).* = .{},
.session => @as(*Session1, @ptrCast(@alignCast(ptr))).* = .{},
- .store => {},
}
}
fn defaults2(kind: abi.Memory, ptr: [*]u8) callconv(.c) void {
@@ -1049,26 +1261,11 @@ test "session setup runs for restored state and layout reset, not same-layout re
Fixture.init_calls = 0;
Fixture.fail_setup = false;
const a = std.testing.allocator;
- var tmp = std.testing.tmpDir(.{});
- defer tmp.cleanup();
- var state_buf: [std.fs.max_path_bytes]u8 = undefined;
- var store_buf: [std.fs.max_path_bytes]u8 = undefined;
- const state_path = try std.mem.print(&state_buf, ".zig-cache/tmp/{s}/setup.state", .{&tmp.sub_path});
- const store_path = try std.mem.print(&store_buf, ".zig-cache/tmp/{s}/setup.store", .{&tmp.sub_path});
- {
- var state = try memory.StateFile.open(a, state_path);
- defer state.close();
- _ = try state.adopt(a, Fixture.description.state, Fixture.defaults);
- @as(*Fixture.State, @ptrCast(state.slot(0).ptr)).value = 77;
- state.markUsed(0, true);
- }
- // Exercise adoption with real persisted memory, without opening SDL devices.
+ // Exercise adoption without opening SDL devices.
var host: Host = undefined;
host.gpa = a;
- host.state = try memory.StateFile.open(a, state_path);
- defer host.state.close();
- host.store = try memory.StoreFile.open(a, store_path, false);
- defer host.store.close();
+ host.state = .init(a);
+ defer host.state.deinit(a);
host.session = .init(a);
defer host.session.deinit(a);
host.info_arena = .init(a);
@@ -1083,7 +1280,8 @@ test "session setup runs for restored state and layout reset, not same-layout re
host.input = .{};
host.commands = .empty;
try host.adopt(Fixture.sketch);
- try std.testing.expectEqual(@as(u32, 77), @as(*Fixture.State, @ptrCast(@alignCast(host.live().ptr))).value);
+ // Defaults: the present or `init` comes after (openPresent).
+ try std.testing.expectEqual(@as(u32, 1), @as(*Fixture.State, @ptrCast(@alignCast(host.live().ptr))).value);
try std.testing.expectEqual(@as(usize, 0), Fixture.init_calls);
try std.testing.expectEqual(@as(usize, 1), Fixture.setup_calls);
const session_ptr = host.session.bytes.ptr;
@@ -1123,3 +1321,79 @@ test "setup writeBuffer propagates unavailable, unknown and out-of-bounds upload
try host.passes.?.buffers.append(a, .{ .buffer = undefined, .size = 4 });
try std.testing.expectError(error.UploadOutOfBounds, client.writeBuffer(@fromBackingInt(@intCast(1)), 2, "data"));
}
+
+test "a state file from before imports into a new save: its State live, its snapshots marks, the file as it was" {
+ const State = extern struct { v: u32 = 0 };
+ const D = struct {
+ fn f(_: abi.Memory, p: [*]u8) callconv(.c) void {
+ @as(*State, @ptrCast(@alignCast(p))).* = .{};
+ }
+ };
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const path = try std.mem.print(&buf, ".zig-cache/tmp/{s}/old.state", .{&tmp.sub_path});
+ var state: memory.State = .init(gpa);
+ defer state.deinit(gpa);
+ _ = try state.adopt(gpa, abi.layout.of(State, .state), D.f);
+ // An eight-slot SKETCH02 file, slots 0, 1 and 3 used, its header State's.
+ const stride = memory.page;
+ const old = try gpa.alloc(u8, memory.header_len + memory.old_slot_count * stride);
+ defer gpa.free(old);
+ @memset(old, 0);
+ @memcpy(old[0..state.header.len], state.header);
+ const h: *memory.Header = @ptrCast(@alignCast(old.ptr));
+ h.magic = memory.file_magic_v2;
+ h.used = 0b1011;
+ for ([_][2]u32{ .{ 0, 5 }, .{ 1, 11 }, .{ 3, 33 } }) |slot| std.mem.writeInt(u32, old[memory.header_len + slot[0] * stride ..][0..4], slot[1], .little);
+ try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = old });
+
+ var sessions = try Sessions.open(gpa, io, .memory, "", .{ .build = 1, .source = "", .layout = state.header }, 0);
+ defer sessions.deinit();
+ try std.testing.expectEqual(@as(usize, 2), try importOld(gpa, path, &state, &sessions, D.f));
+ for ([_][2]u32{ .{ '1', 11 }, .{ '3', 33 } }) |want| {
+ const m = (try sessions.findMark(&.{@intCast(want[0])})).?;
+ const key = try sessions.load(m.session, m.key);
+ defer key.free(gpa);
+ try std.testing.expectEqual(Sessions.Why.import, key.why);
+ try std.testing.expectEqual(want[1], std.mem.readInt(u32, key.state[0..4], .little));
+ }
+ try std.testing.expectEqual(@as(?Sessions.Entry, null), try sessions.findMark("2"));
+ try std.testing.expectEqual(@as(u32, 5), std.mem.readInt(u32, state.live()[0..4], .little));
+ const after = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .unlimited);
+ defer gpa.free(after);
+ try std.testing.expectEqualSlices(u8, old, after);
+}
+
+test "appendFile appends to a file beside the save and names it for readFile" {
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ var host: Host = undefined;
+ host.gpa = std.testing.allocator;
+ host.io = io;
+ host.written = .empty;
+ host.files = .empty;
+ host.options = .{};
+ host.stem = try std.mem.print(&buf, ".zig-cache/tmp/{s}/t", .{&tmp.sub_path});
+ defer {
+ var written = host.written.keyIterator();
+ while (written.next()) |path| host.gpa.free(path.ptr[0 .. path.len + 1]);
+ host.written.deinit(host.gpa);
+ }
+ const name = "take-1.f32";
+ const path = std.mem.span(apiAppendFile(&host, name, name.len, "ab", 2, false));
+ try std.testing.expect(std.mem.endsWith(u8, path, "/t.take-1.f32"));
+ try std.testing.expectEqual(path.ptr, apiAppendFile(&host, name, name.len, "cd", 2, false));
+ const bytes = try tmp.dir.readFileAlloc(io, "t.take-1.f32", host.gpa, .unlimited);
+ defer host.gpa.free(bytes);
+ try std.testing.expectEqualStrings("abcd", bytes);
+ // writeFile: a new file, its old bytes gone.
+ _ = apiAppendFile(&host, name, name.len, "e", 1, true);
+ const again = try tmp.dir.readFileAlloc(io, "t.take-1.f32", host.gpa, .unlimited);
+ defer host.gpa.free(again);
+ try std.testing.expectEqualStrings("e", again);
+}
diff --git a/src/host/Sessions.zig b/src/host/Sessions.zig
new file mode 100644
index 0000000..d6caf9c
--- /dev/null
+++ b/src/host/Sessions.zig
@@ -0,0 +1,1599 @@
+//! A sketch's save: one xitdb database holding every run of it, an
+//! append-only log of the frames live `update` was fed, and the State at
+//! the moments that matter (keyframes). The newest keyframe and the frames
+//! after it are the present a run starts from (`present`). Nothing in it
+//! is ever overwritten: marks and clips are names pointing into it.
+//!
+//! root = map {
+//! version 1
+//! sessions list of session, one a run
+//! marks list of { name, session, key }: a named keyframe (the newest of a name wins)
+//! clips list of { name, session, key, start, end }: frames start..end of a
+//! session, played from keyframe `key`; `end` 0 while recording
+//! }
+//! session = map {
+//! started wall-clock ns at open ended ns at a clean exit, else 0
+//! from "" or where it came from ("import <file>")
+//! stretches list of { frame, build, source, layout }: one a load (start, reloads);
+//! `layout` is State's header (memory.State.header, read by memory.layoutOf)
+//! batches list of bytes: a little-endian u64, the first frame's index, then
+//! whole frames of raw `abi.Event`s, each frame ending with its tick
+//! keys list of { frame, batch, stretch, why, time, size, pages, written, line }:
+//! the State before frame `frame` is fed, in stretch `stretch`'s
+//! layout; `batch` is where reading frames from it starts
+//! frames frames committed
+//! }
+//!
+//! A keyframe's State is `size` bytes in `pages`, a list of `page`-byte
+//! blobs (the last one shorter), an all-zero page an empty slot. A keyframe
+//! starts from the list of the one before it and writes only the pages
+//! whose hash changed (`written` bytes), so every page another keyframe
+//! holds unchanged is shared, never written twice. (Keyframes from before
+//! pages hold their State whole, as `state` bytes; `load` reads both.)
+//!
+//! One transaction (`commit`) a second of session time, and at once for a
+//! reload, a mark, a clip's start or end, and exit: a crash loses less than
+//! a second of play; fsync only at exit and for a mark. A file a crash or
+//! power loss tore opens at its last whole commit (`mend`).
+//!
+//! A save is at most `max_save`: a commit that leaves the file past it
+//! drops history oldest first and compacts the file to three quarters of
+//! it (`trim`); the present, the newest mark of each name and the newest
+//! clip of each name are never dropped. A build that does not record
+//! (`history` false) drops all it may at every keyframe, and compacts at
+//! exit: what it keeps is the present and the marks.
+const Sessions = @This();
+const std = @import("std");
+const xitdb = @import("xitdb");
+const abi = @import("abi");
+
+pub const Disk = xitdb.Database(.buffered_file, u64);
+pub const Memory = xitdb.Database(.memory, u64);
+
+/// `file` for every run but two: `memory` for a scripted run from fresh
+/// state (time travel, nothing on disk), `off` for an export.
+pub const Mode = enum { off, memory, file };
+pub const Why = enum(u64) { start, periodic, jump, before_reload, after_reload, mark, exit, import };
+
+/// Pending frames are committed once they span a second of session time
+/// (less a millisecond: 60 ticks of a 60 Hz clock that rounds down are one).
+pub const commit_ns: u64 = std.time.ns_per_s - std.time.ns_per_ms;
+/// A keyframe at least this often while the State changes.
+pub const periodic_ns: u64 = 60 * std.time.ns_per_s;
+/// Mark and clip names: no spaces, at most this long.
+pub const max_name = 32;
+/// A memory database (a scripted run's) stops recording at this size: ten
+/// hours or more of play at 60 Hz. What it holds stays readable.
+pub const memory_max: u64 = 256 << 20;
+/// The most a save's file holds (State is at most half of it,
+/// `abi.layout.max_state`, so history has room).
+pub const max_save: u64 = 64 << 20;
+
+pub const K = enum(u64) { version = 1, sessions, marks, clips, started, ended, from, stretches, batches, keys, frames, frame, build, source, layout, batch, stretch, why, time, state, line, name, session, key, start, end, pages, size, written };
+fn key(k: K) u64 {
+ return @intFromEnum(k);
+}
+
+pub const Stretch = struct { frame: u64 = 0, build: u64, source: []const u8, layout: []const u8 };
+
+/// A keyframe's page: the OS page, the grain of sharing.
+pub const page = 4096;
+
+/// A keyframe: `session`'s keyframe `key`.
+const At = struct { session: u64, key: u64 };
+
+/// A keyframe queued: the pages of its State that differ from keyframe
+/// `from`'s (`indices`, ascending; their bytes one after the other in
+/// `pages`, `page` apart).
+const Keyframe = struct { frame: u64, batch: u64, stretch: u64, why: Why, time: u64, size: u64, from: ?At, indices: []u64, pages: []u8, line: []u8 };
+
+gpa: std.mem.Allocator,
+/// Files and the wall clock; a memory database runs on `std.Io.failing`.
+io: std.Io,
+db: union(Mode) { off, memory: Memory, file: Disk } = .off,
+file: ?std.Io.File = null,
+/// The database's write buffer, an allocation of its own: the database
+/// points at it.
+buffer: ?*std.Io.Writer.Allocating = null,
+/// The database's path (file mode), owned.
+path: []const u8 = "",
+/// This run's index in `sessions`.
+session: u64 = 0,
+/// Frames logged, committed or not, and committed.
+frames: u64 = 0,
+committed: u64 = 0,
+/// This session's committed batches, its stretches and its keyframes
+/// (queued ones too).
+batches: u64 = 0,
+stretches: u64 = 0,
+keys: u64 = 0,
+/// The frames since the last commit, as the batch they become.
+batch: std.ArrayList(u8) = .empty,
+/// The first pending frame's tick.
+batch_time: u64 = 0,
+/// The first and latest event time logged: times never go back.
+first_time: u64 = 0,
+last_time: u64 = 0,
+/// The last keyframe's time and stretch.
+key_time: u64 = 0,
+key_stretch: u64 = 0,
+/// The keyframe the next one starts from (the last one, or the one a run
+/// started from), and the hashes of its pages.
+last: ?At = null,
+hashes: []u64 = &.{},
+queued: std.ArrayList(Keyframe) = .empty,
+/// The clip being recorded, an index into `clips`.
+recording: ?u64 = null,
+/// State may have changed other than by a logged live frame (a replay ran):
+/// the next live frame starts with a keyframe.
+away: bool = false,
+/// A memory database reached `memory_max`: nothing more is logged.
+full: bool = false,
+/// The console line that last changed State, for the next keyframe.
+line: [256]u8 = undefined,
+line_len: usize = 0,
+/// Keep history, up to `max_save`; else only the present and the marks.
+history: bool = true,
+
+/// Opens the database at `path` (file mode: created with its directory when
+/// missing; one a crash or power loss tore is opened at its last whole
+/// commit (`mend`); one still refused is renamed aside, never deleted) and
+/// starts this run's session in it.
+pub fn open(gpa: std.mem.Allocator, io: std.Io, want: Mode, path: []const u8, first: Stretch, started: u64) !Sessions {
+ var s: Sessions = .{ .gpa = gpa, .io = io };
+ if (want == .off) return s;
+ errdefer s.deinit();
+ const buffer = try gpa.create(std.Io.Writer.Allocating);
+ buffer.* = .init(gpa);
+ s.buffer = buffer;
+ switch (want) {
+ .off => unreachable,
+ .memory => s.db = .{ .memory = try Memory.init(std.Io.failing, .{ .buffer = buffer, .file_id = 0, .max_size = memory_max }) },
+ .file => {
+ s.path = try gpa.dupe(u8, path);
+ const cwd = std.Io.Dir.cwd();
+ if (std.fs.path.dirname(path)) |dir| try cwd.createDirPath(io, dir);
+ var aside = false;
+ while (true) {
+ const file = try cwd.createFile(io, path, .{ .read = true, .truncate = false });
+ if (Disk.init(io, .{ .file = file, .buffer = buffer, .fsync = false })) |db| {
+ s.db = .{ .file = db };
+ s.file = file;
+ break;
+ } else |err| {
+ switch (err) {
+ error.InvalidDatabase, error.InvalidVersion, error.InvalidHashSize, error.TruncatedDatabase, error.InvalidEnumTag, error.EndOfStream => {},
+ else => {
+ file.close(io);
+ return err;
+ },
+ }
+ if (mend(io, file, buffer)) |db| {
+ s.db = .{ .file = db };
+ s.file = file;
+ std.log.warn("{s} was torn after its last whole commit: opened at it", .{path});
+ break;
+ }
+ file.close(io);
+ if (aside) return err;
+ aside = true;
+ var buf: [std.fs.max_path_bytes + 32]u8 = undefined;
+ const to = try std.fmt.bufPrint(&buf, "{s}.broken.{d}", .{ path, started / std.time.ns_per_s });
+ try cwd.rename(path, cwd, to, io);
+ std.log.warn("{s} is no sessions database this host reads: moved to {s}", .{ path, to });
+ }
+ }
+ },
+ }
+ s.session = try s.count(.sessions);
+ try s.commit(.{ .open = .{ .started = started, .first = first } });
+ s.stretches = 1;
+ return s;
+}
+
+/// The database at `path`, read only and no session started in it: for
+/// its `present` with no run of the sketch (`fs` with the sketch closed).
+pub fn openRead(gpa: std.mem.Allocator, io: std.Io, path: []const u8) !Sessions {
+ var s: Sessions = .{ .gpa = gpa, .io = io };
+ errdefer s.deinit();
+ s.file = try std.Io.Dir.cwd().openFile(io, path, .{});
+ s.buffer = try gpa.create(std.Io.Writer.Allocating);
+ s.buffer.?.* = .init(gpa);
+ s.db = .{ .file = try Disk.init(io, .{ .file = s.file.?, .buffer = s.buffer.?, .fsync = false }) };
+ s.session = try s.count(.sessions);
+ return s;
+}
+
+pub fn deinit(s: *Sessions) void {
+ s.dropQueued();
+ s.queued.deinit(s.gpa);
+ s.batch.deinit(s.gpa);
+ s.gpa.free(s.hashes);
+ if (s.file) |f| f.close(s.io);
+ if (s.buffer) |b| {
+ b.deinit();
+ s.gpa.destroy(b);
+ }
+ s.gpa.free(s.path);
+ s.* = .{ .gpa = s.gpa, .io = s.io };
+}
+
+/// The last frames, an exit keyframe of `state`, and the session's end, in
+/// one transaction synced to disk; then closed. Without history the file is
+/// compacted, so the frames it dropped are gone from the disk too.
+pub fn close(s: *Sessions, state: []const u8, ended: u64) void {
+ defer s.deinit();
+ if (s.db == .off) return;
+ s.stopClip() catch {};
+ _ = s.keyframe(.exit, state) catch {};
+ s.commitSynced(.{ .end = ended }) catch |err| std.log.warn("sessions: last commit failed: {t}", .{err});
+ if (s.db == .file and !s.history) s.compact() catch |err| std.log.warn("sessions: not compacted: {t}", .{err});
+}
+
+/// Writes what the database holds now, without the nodes commits left
+/// behind, to `<path>.new`, synced, renames it over the file, and goes on
+/// in it.
+fn compact(s: *Sessions) !void {
+ const cwd = std.Io.Dir.cwd();
+ var buf: [std.fs.max_path_bytes + 8]u8 = undefined;
+ const new = try std.fmt.bufPrint(&buf, "{s}.new", .{s.path});
+ const file = try cwd.createFile(s.io, new, .{ .read = true, .truncate = true });
+ errdefer {
+ file.close(s.io);
+ cwd.deleteFile(s.io, new) catch {};
+ }
+ const buffer = try s.gpa.create(std.Io.Writer.Allocating);
+ buffer.* = .init(s.gpa);
+ errdefer {
+ buffer.deinit();
+ s.gpa.destroy(buffer);
+ }
+ var offsets: std.AutoHashMap(u64, u64) = .init(s.gpa);
+ defer offsets.deinit();
+ var db = try s.db.file.compact(.buffered_file, .{ .file = file, .buffer = buffer, .fsync = true }, &offsets);
+ db.core.file.fsync = false;
+ try cwd.rename(new, cwd, s.path, s.io);
+ s.file.?.close(s.io);
+ s.buffer.?.deinit();
+ s.gpa.destroy(s.buffer.?);
+ s.file = file;
+ s.buffer = buffer;
+ s.db = .{ .file = db };
+}
+
+/// Drops history oldest first, then compacts the file: until its keyframes'
+/// pages and frames are under three quarters of `max_save`, or, without
+/// history, all it may (compacted only past `max_save`; `close` does it
+/// at exit). A few rounds at most: what a dropped keyframe wrote may still
+/// be shared by one kept, so a round can free less than it counted.
+fn trim(s: *Sessions) !void {
+ const goal = max_save / 4 * 3;
+ var keep: u64 = if (s.history) goal else 0;
+ for (0..4) |_| {
+ var dropped: u64 = 0;
+ var left: u64 = 0;
+ try s.db.file.runContext(Trim(Disk){ .s = s, .keep = keep, .dropped = &dropped, .left = &left });
+ var size = try s.file.?.length(s.io);
+ if (!s.history and size <= max_save) return;
+ try s.compact();
+ size = try s.file.?.length(s.io);
+ if (size <= goal or dropped == 0) return;
+ // What the count leaves out (lists, maps, stretches) is the rest.
+ keep = left -| (size - goal);
+ }
+}
+
+/// A keyframe's pages or a batch of frames, for `trim`.
+const Item = struct { session: u64, index: u64, frame: u64, bytes: u64, batch: bool, keep: bool };
+
+/// The transaction of `trim`: drops a keyframe by removing its pages (its
+/// fields stay, so keyframe numbers and searches by frame still work) and
+/// a batch by emptying its slot, oldest first, until what is left counts at
+/// most `keep` bytes; a session left with nothing loses its keyframes,
+/// batches and stretches. Never the present (the newest keyframe and the
+/// batches from its own on), the keyframe of the newest mark or clip of a
+/// name, or a batch holding a frame of such a clip.
+fn Trim(comptime DB: type) type {
+ return struct {
+ s: *Sessions,
+ keep: u64,
+ /// Bytes dropped, and counted after.
+ dropped: *u64,
+ left: *u64,
+
+ const R = Read(DB);
+ const Map = DB.HashMap(.read_write);
+ const List = DB.ArrayList(.read_write);
+
+ pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void {
+ var arena: std.heap.ArenaAllocator = .init(ctx.s.gpa);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const root = try Map.init(cursor.*);
+ const all = try R.list(root.readOnly(), .sessions) orelse return;
+ const n = try all.count();
+ var pinned: std.AutoHashMapUnmanaged(At, void) = .empty;
+ const Clip = struct { session: u64, start: u64, end: u64 };
+ var clips: std.ArrayList(Clip) = .empty;
+ for ([_]K{ .marks, .clips }) |which| {
+ const list = try R.list(root.readOnly(), which) orelse continue;
+ var names: std.StringHashMapUnmanaged(void) = .empty;
+ var i = try list.count();
+ while (i > 0) {
+ i -= 1;
+ const e = try R.at(list, i);
+ var buf: [max_name]u8 = undefined;
+ const name = (try R.field(e, .name)).readBytes(&buf) catch return error.CorruptSession;
+ if ((try names.getOrPut(a, try a.dupe(u8, name))).found_existing) continue;
+ const at: At = .{ .session = try R.uint(e, .session), .key = try R.uint(e, .key) };
+ try pinned.put(a, at, {});
+ const end = if (which == .clips) try R.uint(e, .end) else continue;
+ try clips.append(a, .{ .session = at.session, .start = try R.uint(e, .start), .end = if (end == 0) std.math.maxInt(u64) else end });
+ }
+ }
+ // The present: the newest keyframe, and the batches from its own on.
+ var now: At = undefined;
+ var now_batch: u64 = 0;
+ var i = n;
+ while (true) {
+ if (i == 0) return;
+ i -= 1;
+ const keys = try R.list(try R.at(all, i), .keys) orelse continue;
+ const n_keys = try keys.count();
+ if (n_keys == 0) continue;
+ now = .{ .session = i, .key = n_keys - 1 };
+ now_batch = try R.uint(try R.at(keys, n_keys - 1), .batch);
+ break;
+ }
+ try pinned.put(a, now, {});
+ // What is not dropped yet, each session's in frame order.
+ var items: std.ArrayList(Item) = .empty;
+ var total: u64 = 0;
+ for (0..n) |si| {
+ const ses = try R.at(all, si);
+ const start = items.items.len;
+ if (try R.list(ses, .keys)) |keys| for (0..try keys.count()) |k| {
+ const e = try R.at(keys, k);
+ if (try e.getCursor(key(.pages)) == null) continue;
+ const written = if (try e.getCursor(key(.written))) |w| try w.readUint() else 0;
+ try items.append(a, .{ .session = si, .index = k, .frame = try R.uint(e, .frame), .bytes = written, .batch = false, .keep = pinned.contains(.{ .session = si, .key = k }) });
+ };
+ if (try R.list(ses, .batches)) |batches| for (0..try batches.count()) |b| {
+ var c = try batches.getCursor(@intCast(b)) orelse continue;
+ if ((try c.slot()).tag == .none) continue;
+ var buf: [8]u8 = undefined;
+ var reader = try c.reader(&buf);
+ var head: [8]u8 = undefined;
+ try reader.interface.readSliceAll(&head);
+ try items.append(a, .{ .session = si, .index = b, .frame = std.mem.readInt(u64, &head, .little), .bytes = reader.size, .batch = true, .keep = si == now.session and b >= now_batch });
+ };
+ const mine = items.items[start..];
+ std.mem.sort(Item, mine, {}, struct {
+ fn lessThan(_: void, x: Item, y: Item) bool {
+ return x.frame < y.frame or (x.frame == y.frame and !x.batch and y.batch);
+ }
+ }.lessThan);
+ // A batch holds frames up to the next batch's first.
+ const frames = try R.uint(ses, .frames);
+ var end: u64 = std.math.maxInt(u64);
+ var j = mine.len;
+ while (j > 0) {
+ j -= 1;
+ const it = &mine[j];
+ if (!it.batch) continue;
+ const last = @min(end, frames);
+ for (clips.items) |clip| if (clip.session == si and clip.start < last and it.frame < clip.end) {
+ it.keep = true;
+ };
+ end = it.frame;
+ }
+ for (mine) |it| total += it.bytes;
+ }
+ // Dropped oldest first.
+ const sessions = try List.init(try root.putCursor(key(.sessions)));
+ var left: std.ArrayList(u64) = .empty;
+ try left.appendNTimes(a, 0, n);
+ for (items.items) |it| {
+ if (it.keep or total <= ctx.keep) {
+ left.items[it.session] += 1;
+ continue;
+ }
+ const ses = try Map.init(try sessions.putCursor(@intCast(it.session)));
+ if (it.batch) {
+ try (try List.init(try ses.putCursor(key(.batches)))).put(@intCast(it.index), .{ .slot = null });
+ } else {
+ const k = try Map.init(try (try List.init(try ses.putCursor(key(.keys)))).putCursor(@intCast(it.index)));
+ _ = try k.remove(key(.pages));
+ try k.put(key(.written), .{ .uint = 0 });
+ }
+ total -= it.bytes;
+ ctx.dropped.* += it.bytes;
+ }
+ ctx.left.* = total;
+ for (left.items, 0..) |kept, si| {
+ if (kept > 0 or si >= now.session) continue;
+ var any = false;
+ var it = pinned.keyIterator();
+ while (it.next()) |at| any = any or at.session == si;
+ if (any) continue;
+ const ses = try Map.init(try sessions.putCursor(@intCast(si)));
+ for ([_]K{ .keys, .batches, .stretches }) |k| _ = try ses.remove(key(k));
+ }
+ }
+ };
+}
+
+/// The bytes of every session's batches and keyframes' pages (each written
+/// once): what compaction keeps.
+/// Reading them all is also what proves a mended file whole.
+fn liveSize(db: *Disk) !u64 {
+ const R = Read(Disk);
+ const sessions = try R.list(try R.root(db), .sessions) orelse return 0;
+ var live: u64 = 0;
+ var it = try sessions.iterator();
+ while (try it.next()) |c| {
+ const session = try R.Map.init(c);
+ if (try R.list(session, .batches)) |batches| {
+ var b = try batches.iterator();
+ while (try b.next()) |blob| live += if ((try blob.slot()).tag == .none) 0 else try blob.count();
+ }
+ if (try R.list(session, .keys)) |keys| {
+ var k = try keys.iterator();
+ while (try k.next()) |key_cursor| {
+ const e = try R.Map.init(key_cursor);
+ live += if (try e.getCursor(key(.written))) |w| try w.readUint() else try (try R.field(e, .state)).count();
+ }
+ }
+ }
+ return live;
+}
+
+// xitdb's layout, as `mend` reads it (zig-pkg's xitdb src/lib.zig): the
+// database header (its file id the last 8 of its 20 bytes, big endian), the
+// root header (the root slot's 9 bytes, then the committed size's 8), and
+// the trailer ending every commit (the root slot's 9 bytes, the commit id's
+// 8, and their CRC-64/XZ's 8, with the file id and its own position).
+const db_header_len = 20;
+const root_header_end = db_header_len + 17;
+const trailer_len = 25;
+const hash_map_tag = 4;
+
+/// A file xitdb refused because a crash or power loss tore its last commit
+/// (its root header written, the commit's bytes not all): opened at the last
+/// commit before the tear whose trailer verifies and whose sessions read
+/// whole, scanned back from the file's end, its root header put back at it.
+/// Null, the file as it was, when none does.
+fn mend(io: std.Io, file: std.Io.File, buffer: *std.Io.Writer.Allocating) ?Disk {
+ var head: [root_header_end]u8 = undefined;
+ if ((file.readPositionalAll(io, &head, 0) catch return null) != head.len or !std.mem.eql(u8, head[0..3], "xit")) return null;
+ const file_id = std.mem.readInt(u64, head[db_header_len - 8 .. db_header_len], .big);
+ var chunk: [64 << 10]u8 = undefined;
+ var end = file.length(io) catch return null;
+ while (end >= root_header_end + trailer_len) {
+ const start = @max(root_header_end, end - @min(end, chunk.len));
+ const got = file.readPositionalAll(io, chunk[0 .. end - start], start) catch return null;
+ if (got != end - start) return null;
+ var i = got;
+ while (i >= trailer_len) : (i -= 1) {
+ const t = chunk[i - trailer_len ..][0..trailer_len];
+ const at = start + i - trailer_len;
+ // The root is a map, at a slot written before its trailer.
+ if (t[0] & 0x7f != hash_map_tag or std.mem.readInt(u64, t[1..9], .big) >= at) continue;
+ var sum: [33]u8 = undefined;
+ std.mem.writeInt(u64, sum[0..8], file_id, .big);
+ std.mem.writeInt(u64, sum[8..16], at, .big);
+ @memcpy(sum[16..33], t[0..17]);
+ if (std.hash.crc.@"CRC-64/XZ".hash(&sum) != std.mem.readInt(u64, t[17..25], .big)) continue;
+ var root: [17]u8 = undefined;
+ @memcpy(root[0..9], t[0..9]);
+ std.mem.writeInt(u64, root[9..17], at + trailer_len, .big);
+ file.writePositionalAll(io, &root, db_header_len) catch return null;
+ var db = Disk.init(io, .{ .file = file, .buffer = buffer, .fsync = false }) catch continue;
+ _ = liveSize(&db) catch continue;
+ file.sync(io) catch {};
+ return db;
+ }
+ if (start == root_header_end) break;
+ end = start + trailer_len - 1;
+ }
+ file.writePositionalAll(io, head[db_header_len..], db_header_len) catch {};
+ return null;
+}
+
+pub fn mode(s: *const Sessions) Mode {
+ return s.db;
+}
+
+/// Remembers the console line that changed State, for the next keyframe.
+pub fn noteLine(s: *Sessions, line: []const u8) void {
+ s.line_len = @min(line.len, s.line.len);
+ @memcpy(s.line[0..s.line_len], line[0..s.line_len]);
+}
+
+/// One live frame, its tick last, before `update` is fed it: its times are
+/// made never to go back (what `update` then sees is what a replay will),
+/// and it is logged, after a keyframe of `state` when `why` says so or the
+/// last is a minute old.
+pub fn frame(s: *Sessions, one: []abi.Event, state: []const u8, why: ?Why) !void {
+ for (one) |*e| {
+ e.time = @max(e.time, s.last_time);
+ s.last_time = e.time;
+ }
+ if (s.db == .off or s.full) return;
+ const tick = one[one.len - 1].time;
+ if (s.batch.items.len > 0 and tick -| s.batch_time >= commit_ns) try s.commit(.none);
+ if (why) |w| {
+ _ = try s.keyframe(w, state);
+ } else if (tick -| s.key_time >= periodic_ns) _ = try s.keyframe(.periodic, state);
+ if (s.frames == 0) s.first_time = tick;
+ if (s.batch.items.len == 0) {
+ try s.batch.appendSlice(s.gpa, std.mem.asBytes(&std.mem.nativeToLittle(u64, s.frames)));
+ s.batch_time = tick;
+ }
+ try s.batch.appendSlice(s.gpa, std.mem.sliceAsBytes(one));
+ s.frames += 1;
+}
+
+/// Queues a keyframe of `state` before the next frame, and returns its
+/// index; an unchanged State is the last keyframe again (but for a
+/// `before_reload` one: the last word in the old layout). Only the pages
+/// whose hash differs from the last keyframe's are copied, and written.
+pub fn keyframe(s: *Sessions, why: Why, state: []const u8) !u64 {
+ if (s.db == .off) return error.NotRecording;
+ defer s.line_len = 0;
+ const hashes = try s.gpa.alloc(u64, std.math.divCeil(usize, state.len, page) catch unreachable);
+ errdefer s.gpa.free(hashes);
+ var changed: std.ArrayList(u64) = .empty;
+ defer changed.deinit(s.gpa);
+ for (hashes, 0..) |*h, i| {
+ h.* = std.hash.Wyhash.hash(0, state[i * page .. @min(state.len, (i + 1) * page)]);
+ if (i >= s.hashes.len or s.hashes[i] != h.*) try changed.append(s.gpa, i);
+ }
+ if (s.keys > 0 and why != .before_reload and changed.items.len == 0 and hashes.len == s.hashes.len and s.key_stretch == s.stretches - 1) {
+ s.gpa.free(hashes);
+ return s.keys - 1;
+ }
+ const pages = try s.gpa.alloc(u8, changed.items.len * page);
+ errdefer s.gpa.free(pages);
+ for (changed.items, 0..) |i, k| {
+ const bytes = state[i * page .. @min(state.len, (i + 1) * page)];
+ @memcpy(pages[k * page ..][0..bytes.len], bytes);
+ }
+ const indices = try changed.toOwnedSlice(s.gpa);
+ errdefer s.gpa.free(indices);
+ const line_copy = try s.gpa.dupe(u8, s.line[0..s.line_len]);
+ errdefer s.gpa.free(line_copy);
+ try s.queued.append(s.gpa, .{ .frame = s.frames, .batch = s.batches, .stretch = s.stretches - 1, .why = why, .time = s.last_time, .size = state.len, .from = s.last, .indices = indices, .pages = pages, .line = line_copy });
+ s.gpa.free(s.hashes);
+ s.hashes = hashes;
+ s.last = .{ .session = s.session, .key = s.keys };
+ s.key_time = s.last_time;
+ s.key_stretch = s.stretches - 1;
+ s.keys += 1;
+ return s.keys - 1;
+}
+
+/// A new stretch from the next frame: a reload's build, source and layout.
+pub fn stretch(s: *Sessions, st: Stretch) !void {
+ if (s.db == .off) return;
+ var with = st;
+ with.frame = s.frames;
+ try s.commit(.{ .stretch = with });
+ s.stretches += 1;
+}
+
+/// Mark `name`: a keyframe of `state` (`why`: `.mark`, or `.import`),
+/// synced to disk. Returns the keyframe's index. A mark of a new name needs
+/// room for a whole State under `max_save`, history dropped to make it
+/// (`trim`): without, it is refused (`error.SaveFull`). A mark over an
+/// existing name lets the older one go with history.
+pub fn mark(s: *Sessions, name: []const u8, why: Why, state: []const u8) !u64 {
+ if (s.db == .file and try s.file.?.length(s.io) + state.len > max_save and try s.findMark(name) == null) {
+ try s.trim();
+ if (try s.file.?.length(s.io) + state.len > max_save) return error.SaveFull;
+ }
+ const k = try s.keyframe(why, state);
+ try s.commitSynced(.{ .mark = .{ .name = name, .key = k } });
+ return k;
+}
+
+/// Starts clip `name` at the next frame, played from keyframe `k`.
+pub fn startClip(s: *Sessions, name: []const u8, k: u64) !void {
+ const index = try s.count(.clips);
+ try s.commit(.{ .clip = .{ .name = name, .key = k, .start = s.frames } });
+ s.recording = index;
+}
+
+/// Ends the clip being recorded after the frames logged so far.
+pub fn stopClip(s: *Sessions) !void {
+ const index = s.recording orelse return;
+ try s.commit(.{ .clip_end = .{ .index = index, .end = s.frames } });
+ s.recording = null;
+}
+
+fn dropQueued(s: *Sessions) void {
+ for (s.queued.items) |k| {
+ s.gpa.free(k.indices);
+ s.gpa.free(k.pages);
+ s.gpa.free(k.line);
+ }
+ s.queued.clearRetainingCapacity();
+}
+
+const Extra = union(enum) {
+ none,
+ open: struct { started: u64, first: Stretch },
+ stretch: Stretch,
+ mark: struct { name: []const u8, key: u64 },
+ clip: struct { name: []const u8, key: u64, start: u64 },
+ clip_end: struct { index: u64, end: u64 },
+ end: u64,
+};
+
+fn commitSynced(s: *Sessions, extra: Extra) !void {
+ if (s.db == .file) s.db.file.core.file.fsync = true;
+ defer if (s.db == .file) {
+ s.db.file.core.file.fsync = false;
+ };
+ try s.commit(extra);
+}
+
+/// One transaction: the pending frames, the queued keyframes and `extra`.
+pub fn commit(s: *Sessions, extra: Extra) !void {
+ switch (s.db) {
+ .off => return,
+ inline .memory, .file => |*db| db.runContext(Commit(@TypeOf(db.*)){ .s = s, .extra = extra }) catch |err| {
+ // A memory database that cannot grow (`memory_max`, or no
+ // memory left) stops recording, once.
+ if (s.db == .memory and !s.full) {
+ s.full = true;
+ s.batch.clearRetainingCapacity();
+ s.dropQueued();
+ std.log.warn("sessions: the memory database cannot grow ({t}; {d} MiB at most): no more frames recorded", .{ err, memory_max >> 20 });
+ }
+ return err;
+ },
+ }
+ if (s.batch.items.len > 0) {
+ s.batches += 1;
+ s.committed = s.frames;
+ s.batch.clearRetainingCapacity();
+ }
+ const keyed = s.queued.items.len > 0;
+ s.dropQueued();
+ if (s.db != .file) return;
+ if ((try s.file.?.length(s.io)) > max_save or (!s.history and keyed)) s.trim() catch |err| std.log.warn("sessions: history not trimmed: {t}", .{err});
+}
+
+fn Commit(comptime DB: type) type {
+ return struct {
+ s: *Sessions,
+ extra: Extra,
+
+ const Map = DB.HashMap(.read_write);
+ const List = DB.ArrayList(.read_write);
+
+ pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void {
+ const s = ctx.s;
+ const root = try Map.init(cursor.*);
+ const sessions = try List.init(try root.putCursor(key(.sessions)));
+ if (ctx.extra == .open) {
+ const o = ctx.extra.open;
+ try root.put(key(.version), .{ .uint = 1 });
+ const session = try Map.init(try sessions.appendCursor());
+ try session.put(key(.started), .{ .uint = o.started });
+ try session.put(key(.ended), .{ .uint = 0 });
+ try session.put(key(.from), .{ .bytes = "" });
+ try session.put(key(.frames), .{ .uint = 0 });
+ try putStretch(try List.init(try session.putCursor(key(.stretches))), o.first);
+ return;
+ }
+ const session = try Map.init(try sessions.putCursor(@intCast(s.session)));
+ if (s.batch.items.len > 0) {
+ try (try List.init(try session.putCursor(key(.batches)))).append(.{ .bytes = s.batch.items });
+ try session.put(key(.frames), .{ .uint = s.frames });
+ }
+ if (s.queued.items.len > 0) {
+ const keys = try List.init(try session.putCursor(key(.keys)));
+ for (s.queued.items) |q| {
+ const k = try Map.init(try keys.appendCursor());
+ try k.put(key(.frame), .{ .uint = q.frame });
+ try k.put(key(.batch), .{ .uint = q.batch });
+ try k.put(key(.stretch), .{ .uint = q.stretch });
+ try k.put(key(.why), .{ .uint = @intFromEnum(q.why) });
+ try k.put(key(.time), .{ .uint = q.time });
+ try k.put(key(.size), .{ .uint = q.size });
+ try k.put(key(.line), .{ .bytes = q.line });
+ // From the keyframe before's pages, copied as the
+ // transaction writes on (it may be in it too).
+ var from = try k.putCursor(key(.pages));
+ if (q.from) |at| if (try pagesSlot(root, at)) |slot| {
+ try from.write(.{ .slot = slot });
+ try from.freeze();
+ };
+ const pages = try List.init(from);
+ const had = try pages.count();
+ var written: u64 = 0;
+ for (q.indices, 0..) |i, j| {
+ const bytes = q.pages[j * page ..][0..@min(page, q.size - i * page)];
+ const zero = std.mem.allEqual(u8, bytes, 0);
+ if (!zero) written += bytes.len;
+ const data: DB.WriteableData = if (zero) .{ .slot = null } else .{ .bytes = bytes };
+ if (i < had) try pages.put(@intCast(i), data) else try pages.append(data);
+ }
+ const n = std.math.divCeil(u64, q.size, page) catch unreachable;
+ if (had > n) try pages.slice(n);
+ try k.put(key(.written), .{ .uint = written });
+ }
+ }
+ switch (ctx.extra) {
+ .none, .open => {},
+ .stretch => |st| try putStretch(try List.init(try session.putCursor(key(.stretches))), st),
+ .mark => |m| {
+ const item = try Map.init(try (try List.init(try root.putCursor(key(.marks)))).appendCursor());
+ try item.put(key(.name), .{ .bytes = m.name });
+ try item.put(key(.session), .{ .uint = s.session });
+ try item.put(key(.key), .{ .uint = m.key });
+ },
+ .clip => |c| {
+ const item = try Map.init(try (try List.init(try root.putCursor(key(.clips)))).appendCursor());
+ try item.put(key(.name), .{ .bytes = c.name });
+ try item.put(key(.session), .{ .uint = s.session });
+ try item.put(key(.key), .{ .uint = c.key });
+ try item.put(key(.start), .{ .uint = c.start });
+ try item.put(key(.end), .{ .uint = 0 });
+ },
+ .clip_end => |c| {
+ const item = try Map.init(try (try List.init(try root.putCursor(key(.clips)))).putCursor(@intCast(c.index)));
+ try item.put(key(.end), .{ .uint = c.end });
+ },
+ .end => |t| try session.put(key(.ended), .{ .uint = t }),
+ }
+ }
+
+ /// The slot of keyframe `at`'s pages; null for one from before pages.
+ fn pagesSlot(root: Map, at: At) !?xitdb.Slot {
+ const R = Read(DB);
+ const ses = try R.at(try R.list(root.readOnly(), .sessions) orelse return null, at.session);
+ return (try R.at(try R.list(ses, .keys) orelse return null, at.key)).getSlot(key(.pages));
+ }
+
+ fn putStretch(list: List, st: Stretch) !void {
+ const item = try Map.init(try list.appendCursor());
+ try item.put(key(.frame), .{ .uint = st.frame });
+ try item.put(key(.build), .{ .uint = st.build });
+ try item.put(key(.source), .{ .bytes = st.source });
+ try item.put(key(.layout), .{ .bytes = st.layout });
+ }
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Reading
+
+/// A mark (`start` and `end` 0) or a clip.
+pub const Entry = struct {
+ session: u64,
+ key: u64,
+ start: u64 = 0,
+ end: u64 = 0,
+ bytes: [max_name]u8 = undefined,
+ len: usize = 0,
+
+ pub fn name(e: *const Entry) []const u8 {
+ return e.bytes[0..e.len];
+ }
+};
+/// A keyframe, its bytes `gpa`'s (`free`).
+pub const Loaded = struct {
+ /// Stored in pages (not whole, from before them).
+ paged: bool = true,
+ frame: u64,
+ batch: u64,
+ why: Why,
+ time: u64,
+ state: []const u8,
+ line: []const u8,
+ /// Its stretch: the layout of `state`, and the build that wrote it.
+ stretch: u64,
+ build: u64,
+ source: []const u8,
+ layout: []const u8,
+
+ pub fn free(l: Loaded, gpa: std.mem.Allocator) void {
+ for ([_][]const u8{ l.state, l.line, l.source, l.layout }) |b| gpa.free(b);
+ }
+};
+
+pub fn markAt(s: *Sessions, i: u64) !Entry {
+ return s.entryAt(.marks, i);
+}
+pub fn clipAt(s: *Sessions, i: u64) !Entry {
+ return s.entryAt(.clips, i);
+}
+/// The newest mark named `name`.
+pub fn findMark(s: *Sessions, name: []const u8) !?Entry {
+ return s.findNamed(.marks, name);
+}
+/// The newest clip named `name`.
+pub fn findClip(s: *Sessions, name: []const u8) !?Entry {
+ return s.findNamed(.clips, name);
+}
+
+fn findNamed(s: *Sessions, which: K, name: []const u8) !?Entry {
+ var i = try s.count(which);
+ while (i > 0) {
+ i -= 1;
+ const e = try s.entryAt(which, i);
+ if (std.mem.eql(u8, e.name(), name)) return e;
+ }
+ return null;
+}
+
+fn entryAt(s: *Sessions, which: K, i: u64) !Entry {
+ switch (s.db) {
+ .off => return error.NotRecording,
+ inline .memory, .file => |*db| {
+ const R = Read(@TypeOf(db.*));
+ const e = try R.at(try R.list(try R.root(db), which) orelse return error.NoSuchEntry, i);
+ var out: Entry = .{ .session = try R.uint(e, .session), .key = try R.uint(e, .key) };
+ out.len = ((try R.field(e, .name)).readBytes(&out.bytes) catch return error.CorruptSession).len;
+ if (which == .clips) {
+ out.start = try R.uint(e, .start);
+ out.end = try R.uint(e, .end);
+ }
+ return out;
+ },
+ }
+}
+
+/// Entries in the root list `which`, or sessions.
+pub fn count(s: *Sessions, which: K) !u64 {
+ switch (s.db) {
+ .off => return error.NotRecording,
+ inline .memory, .file => |*db| {
+ const R = Read(@TypeOf(db.*));
+ return if (try R.list(try R.root(db), which)) |l| try l.count() else 0;
+ },
+ }
+}
+
+/// Keyframe `k` of `session`, with its stretch.
+pub fn load(s: *Sessions, session: u64, k: u64) !Loaded {
+ switch (s.db) {
+ .off => return error.NotRecording,
+ inline .memory, .file => |*db| {
+ const R = Read(@TypeOf(db.*));
+ const ses = try R.session(db, session);
+ const e = try R.at(try R.list(ses, .keys) orelse return error.NoSuchKeyframe, k);
+ const st = try R.uint(e, .stretch);
+ const stretch_entry = try R.at(try R.list(ses, .stretches) orelse return error.CorruptSession, st);
+ const why = std.enums.fromInt(Why, try R.uint(e, .why)) orelse return error.CorruptSession;
+ const pages = try R.list(e, .pages);
+ const state = if (pages) |list| try R.pages(list, try R.uint(e, .size), s.gpa) else if (try e.getCursor(key(.state))) |whole| try whole.readBytesAlloc(s.gpa, null) else return error.HistoryDropped;
+ errdefer s.gpa.free(state);
+ const line = try R.bytes(e, .line, s.gpa);
+ errdefer s.gpa.free(line);
+ const source = try R.bytes(stretch_entry, .source, s.gpa);
+ errdefer s.gpa.free(source);
+ return .{
+ .paged = pages != null,
+ .frame = try R.uint(e, .frame),
+ .batch = try R.uint(e, .batch),
+ .why = why,
+ .time = try R.uint(e, .time),
+ .state = state,
+ .line = line,
+ .stretch = st,
+ .build = try R.uint(stretch_entry, .build),
+ .source = source,
+ .layout = try R.bytes(stretch_entry, .layout, s.gpa),
+ };
+ },
+ }
+}
+
+/// The State a run starts from, the present: the newest keyframe of the
+/// sessions before this one, with the frames logged after it appended to
+/// `out` (replayed, they bring it to where that run stopped). Null in a
+/// new database. This run's first keyframe starts from its pages.
+pub fn present(s: *Sessions, out: *std.ArrayList(abi.Event)) !?Loaded {
+ if (s.db == .off) return null;
+ var i = s.session;
+ while (i > 0) {
+ i -= 1;
+ const sum = try s.summary(i);
+ if (sum.keys == 0) continue;
+ const newest = try s.load(i, sum.keys - 1);
+ errdefer newest.free(s.gpa);
+ try s.events(i, newest.batch, newest.frame, sum.frames, out);
+ if (newest.paged) {
+ const hashes = try s.gpa.alloc(u64, std.math.divCeil(usize, newest.state.len, page) catch unreachable);
+ for (hashes, 0..) |*h, j| h.* = std.hash.Wyhash.hash(0, newest.state[j * page .. @min(newest.state.len, (j + 1) * page)]);
+ s.gpa.free(s.hashes);
+ s.hashes = hashes;
+ s.last = .{ .session = i, .key = sum.keys - 1 };
+ }
+ return newest;
+ }
+ return null;
+}
+
+/// Keyframe `k`'s frame, time and why, without its bytes.
+pub fn keyAt(s: *Sessions, session: u64, k: u64) !struct { frame: u64, time: u64, why: Why } {
+ switch (s.db) {
+ .off => return error.NotRecording,
+ inline .memory, .file => |*db| {
+ const R = Read(@TypeOf(db.*));
+ const e = try R.at(try R.list(try R.session(db, session), .keys) orelse return error.NoSuchKeyframe, k);
+ return .{ .frame = try R.uint(e, .frame), .time = try R.uint(e, .time), .why = std.enums.fromInt(Why, try R.uint(e, .why)) orelse return error.CorruptSession };
+ },
+ }
+}
+
+/// The newest keyframe of `session` whose `by` (`.frame` or `.time`) is at
+/// most `value`: a binary search.
+pub fn keyBefore(s: *Sessions, session: u64, by: K, value: u64) !?u64 {
+ switch (s.db) {
+ .off => return error.NotRecording,
+ inline .memory, .file => |*db| {
+ const R = Read(@TypeOf(db.*));
+ const keys = try R.list(try R.session(db, session), .keys) orelse return null;
+ var lo: u64 = 0;
+ var hi = try keys.count();
+ while (lo < hi) {
+ const mid = lo + (hi - lo) / 2;
+ if (try R.uint(try R.at(keys, mid), by) <= value) lo = mid + 1 else hi = mid;
+ }
+ return if (lo == 0) null else lo - 1;
+ },
+ }
+}
+
+/// Appends to `out` the events of frames `start..end` of `session`, read
+/// from batch `from` on.
+pub fn events(s: *Sessions, session: u64, from: u64, start: u64, end: u64, out: *std.ArrayList(abi.Event)) !void {
+ switch (s.db) {
+ .off => return error.NotRecording,
+ inline .memory, .file => |*db| {
+ const R = Read(@TypeOf(db.*));
+ const batches = try R.list(try R.session(db, session), .batches) orelse return;
+ const n = try batches.count();
+ var i = from;
+ while (i < n) : (i += 1) {
+ const cursor = try batches.getCursor(@intCast(i)) orelse return error.CorruptSession;
+ if ((try cursor.slot()).tag == .none) return error.HistoryDropped;
+ const blob = try cursor.readBytesAlloc(s.gpa, null);
+ defer s.gpa.free(blob);
+ if (blob.len < 8 or (blob.len - 8) % @sizeOf(abi.Event) != 0) return error.CorruptSession;
+ var f = std.mem.readInt(u64, blob[0..8], .little);
+ if (f >= end) return;
+ var at: usize = 8;
+ while (at < blob.len) : (at += @sizeOf(abi.Event)) {
+ var e: abi.Event = undefined;
+ @memcpy(std.mem.asBytes(&e), blob[at..][0..@sizeOf(abi.Event)]);
+ if (f >= start) try out.append(s.gpa, e);
+ if (e.kind == .tick) f += 1;
+ if (f >= end) return;
+ }
+ }
+ },
+ }
+}
+
+/// Session `i`'s summary.
+pub const Summary = struct {
+ started: u64,
+ ended: u64,
+ frames: u64,
+ stretches: u64,
+ keys: u64,
+ /// Where it came from ("import <file name>"), cut short.
+ from_bytes: [48]u8 = undefined,
+ from_len: usize = 0,
+
+ pub fn from(m: *const Summary) []const u8 {
+ return m.from_bytes[0..m.from_len];
+ }
+};
+
+pub fn summary(s: *Sessions, i: u64) !Summary {
+ switch (s.db) {
+ .off => return error.NotRecording,
+ inline .memory, .file => |*db| {
+ const R = Read(@TypeOf(db.*));
+ const ses = try R.session(db, i);
+ var m: Summary = .{
+ .started = try R.uint(ses, .started),
+ .ended = try R.uint(ses, .ended),
+ .frames = try R.uint(ses, .frames),
+ .stretches = if (try R.list(ses, .stretches)) |l| try l.count() else 0,
+ .keys = if (try R.list(ses, .keys)) |l| try l.count() else 0,
+ };
+ const from = try R.bytes(ses, .from, s.gpa);
+ defer s.gpa.free(from);
+ m.from_len = @min(from.len, m.from_bytes.len);
+ @memcpy(m.from_bytes[0..m.from_len], from[0..m.from_len]);
+ return m;
+ },
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Export and import
+
+/// Writes session `i`, with the marks and clips in it (now of session 0), to
+/// a new database at `path` (written beside it, synced, then renamed): a
+/// playtest's sessions to send, which `import` reads.
+pub fn exportSession(s: *Sessions, i: u64, path: []const u8) !void {
+ if (s.db == .off) return error.NotRecording;
+ if (i == s.session) try s.commit(.none);
+ if (i >= try s.count(.sessions)) return error.NoSuchSession;
+ const cwd = std.Io.Dir.cwd();
+ var buf: [std.fs.max_path_bytes + 8]u8 = undefined;
+ const tmp = try std.fmt.bufPrint(&buf, "{s}.tmp", .{path});
+ const file = try cwd.createFile(s.io, tmp, .{ .read = true, .truncate = true });
+ errdefer cwd.deleteFile(s.io, tmp) catch {};
+ defer file.close(s.io);
+ var buffer: std.Io.Writer.Allocating = .init(s.gpa);
+ defer buffer.deinit();
+ var out = try Disk.init(s.io, .{ .file = file, .buffer = &buffer, .fsync = true });
+ switch (s.db) {
+ .off => unreachable,
+ inline .memory, .file => |*db| try out.runContext(Transfer(@TypeOf(db.*), Disk){ .gpa = s.gpa, .from = db, .only = i, .label = null }),
+ }
+ try cwd.rename(tmp, cwd, path, s.io);
+}
+
+/// Appends the sessions of the database at `path` (an `exportSession`'s) to
+/// this one, their `from` "import <file name>", with their marks and clips,
+/// named `<name>@<file name>` (cut to `max_name`). Returns the first one's
+/// index.
+pub fn import(s: *Sessions, path: []const u8) !u64 {
+ if (s.db == .off) return error.NotRecording;
+ const file = try std.Io.Dir.cwd().openFile(s.io, path, .{});
+ defer file.close(s.io);
+ if (try file.length(s.io) == 0) return error.NotASessionsDatabase;
+ var buffer: std.Io.Writer.Allocating = .init(s.gpa);
+ defer buffer.deinit();
+ var in = try Disk.init(s.io, .{ .file = file, .buffer = &buffer, .fsync = false });
+ const first = try s.count(.sessions);
+ switch (s.db) {
+ .off => unreachable,
+ inline .memory, .file => |*db| try db.runContext(Transfer(Disk, @TypeOf(db.*)){ .gpa = s.gpa, .from = &in, .only = null, .label = std.fs.path.basename(path) }),
+ }
+ return first;
+}
+
+/// A transaction appending database `from`'s sessions (`only` one, else
+/// all) to the one it runs in, with the marks and clips pointing into them;
+/// `label`, an import's file name, goes in their `from` and names.
+fn Transfer(comptime From: type, comptime To: type) type {
+ return struct {
+ gpa: std.mem.Allocator,
+ from: *From,
+ only: ?u64,
+ label: ?[]const u8,
+
+ const R = Read(From);
+ const Map = To.HashMap(.read_write);
+ const List = To.ArrayList(.read_write);
+
+ pub fn run(ctx: @This(), cursor: *To.Cursor(.read_write)) !void {
+ var copied: std.AutoHashMap(u64, xitdb.Slot) = .init(ctx.gpa);
+ defer copied.deinit();
+ const src = try R.root(ctx.from);
+ if (try R.uint(src, .version) != 1) return error.NotASessionsDatabase;
+ const all = try R.list(src, .sessions) orelse return error.NotASessionsDatabase;
+ const root = try Map.init(cursor.*);
+ try root.put(key(.version), .{ .uint = 1 });
+ const sessions = try List.init(try root.putCursor(key(.sessions)));
+ const base = try sessions.count();
+ var buf: [std.fs.max_path_bytes + 8]u8 = undefined;
+ for (0..try all.count()) |i| {
+ if (ctx.only) |o| if (o != i) continue;
+ var to = try sessions.appendCursor();
+ try copy(From, To, ctx.gpa, try all.getCursor(@intCast(i)) orelse return error.CorruptSession, &to, &copied);
+ if (ctx.label) |l| try (try Map.init(to)).put(key(.from), .{ .bytes = try std.fmt.bufPrint(&buf, "import {s}", .{l}) });
+ }
+ for ([_]K{ .marks, .clips }) |which| {
+ const entries = try R.list(src, which) orelse continue;
+ const list = try List.init(try root.putCursor(key(which)));
+ var it = try entries.iterator();
+ while (try it.next()) |e| {
+ const session = try R.uint(try R.Map.init(e), .session);
+ if (ctx.only) |o| if (o != session) continue;
+ var to = try list.appendCursor();
+ try copy(From, To, ctx.gpa, e, &to, &copied);
+ const item = try Map.init(to);
+ try item.put(key(.session), .{ .uint = base + if (ctx.only == null) session else 0 });
+ const l = ctx.label orelse continue;
+ var name: [max_name]u8 = undefined;
+ const old = (try R.field(try R.Map.init(e), .name)).readBytes(&name) catch return error.CorruptSession;
+ const new = std.fmt.bufPrint(&buf, "{s}@{s}", .{ old, l }) catch unreachable;
+ try item.put(key(.name), .{ .bytes = new[0..@min(new.len, max_name)] });
+ }
+ }
+ }
+ };
+}
+
+/// Copies the value at `from` (a uint, bytes, or a list or map of them) to
+/// `to`. Bytes `copied` already (a page keyframes share) are written once:
+/// it maps their place in `from` to their slot in `to`.
+fn copy(comptime From: type, comptime To: type, gpa: std.mem.Allocator, from: From.Cursor(.read_only), to: *To.Cursor(.read_write), copied: *std.AutoHashMap(u64, xitdb.Slot)) anyerror!void {
+ const slot = try from.slot();
+ switch (slot.tag) {
+ .none => try to.write(.{ .slot = null }),
+ .uint => try to.write(.{ .uint = try from.readUint() }),
+ .bytes, .short_bytes => {
+ if (slot.tag == .bytes) if (copied.get(slot.value)) |done| return to.write(.{ .slot = done });
+ const bytes = try from.readBytesAlloc(gpa, null);
+ defer gpa.free(bytes);
+ try to.write(.{ .bytes = bytes });
+ if (slot.tag == .bytes) try copied.put(slot.value, try to.slot());
+ },
+ .array_list => {
+ const list = try To.ArrayList(.read_write).init(to.*);
+ var it = try from.iterator();
+ while (try it.next()) |c| {
+ var next = try list.appendCursor();
+ try copy(From, To, gpa, c, &next, copied);
+ }
+ },
+ .hash_map => {
+ const map = try To.HashMap(.read_write).init(to.*);
+ var it = try from.iterator();
+ while (try it.next()) |c| {
+ const kv = try c.readKeyValuePair();
+ var next = try map.putCursor(kv.hash);
+ try copy(From, To, gpa, kv.value_cursor, &next, copied);
+ }
+ },
+ else => return error.CorruptSession,
+ }
+}
+
+fn Read(comptime DB: type) type {
+ return struct {
+ const Map = DB.HashMap(.read_only);
+ const List = DB.ArrayList(.read_only);
+
+ fn root(db: *DB) !Map {
+ return Map.init(db.rootCursor().readOnly());
+ }
+ fn session(db: *DB, i: u64) !Map {
+ return at(try list(try root(db), .sessions) orelse return error.NoSuchSession, i);
+ }
+ fn field(map: Map, k: K) !DB.Cursor(.read_only) {
+ return try map.getCursor(key(k)) orelse error.CorruptSession;
+ }
+ fn uint(map: Map, k: K) !u64 {
+ return (try field(map, k)).readUint();
+ }
+ fn bytes(map: Map, k: K, gpa: std.mem.Allocator) ![]const u8 {
+ return (try field(map, k)).readBytesAlloc(gpa, null);
+ }
+ /// `size` bytes from a keyframe's pages, `gpa`'s.
+ fn pages(l: List, size: u64, gpa: std.mem.Allocator) ![]u8 {
+ const out = try gpa.alloc(u8, size);
+ errdefer gpa.free(out);
+ @memset(out, 0);
+ for (0..try l.count()) |i| {
+ const c = try l.getCursor(@intCast(i)) orelse continue;
+ if ((try c.slot()).tag == .none) continue;
+ const into = out[@min(size, i * page)..@min(size, (i + 1) * page)];
+ if ((c.readBytes(into) catch return error.CorruptSession).len != into.len) return error.CorruptSession;
+ }
+ return out;
+ }
+ fn list(map: Map, k: K) !?List {
+ return try List.init(try map.getCursor(key(k)) orelse return null);
+ }
+ fn at(l: List, i: u64) !Map {
+ if (i >= try l.count()) return error.NoSuchEntry;
+ return Map.init(try l.getCursor(@intCast(i)) orelse return error.NoSuchEntry);
+ }
+ };
+}
+
+test "frames written to a session read back byte for byte, in memory and through a reopened file" {
+ const gpa = std.testing.allocator;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const path = try std.fmt.bufPrint(&buf, ".zig-cache/tmp/{s}/t.xitdb", .{&tmp.sub_path});
+ const layout = "a layout";
+ for ([_]Mode{ .memory, .file }) |m| {
+ var s = try open(gpa, std.testing.io, m, path, .{ .build = 7, .source = "jj:abc", .layout = layout }, 1000);
+ var live: std.ArrayList(abi.Event) = .empty;
+ defer live.deinit(gpa);
+ // Three seconds at 60 Hz, a move in every third frame; the state is
+ // the frame count, so keyframes differ.
+ var state: u64 = 0;
+ for (0..180) |f| {
+ const t = std.time.ns_per_s + f * std.time.ns_per_s / 60;
+ var frame_events: [2]abi.Event = .{ .{ .kind = .mouse_move, .time = t, .x = @floatFromInt(f) }, abi.Event.tick(t, std.time.ns_per_s / 60) };
+ const one = if (f % 3 == 0) frame_events[0..] else frame_events[1..];
+ try s.frame(one, std.mem.asBytes(&state), if (f == 0) .start else if (f == 90) .jump else null);
+ try live.appendSlice(gpa, one);
+ state += 1;
+ }
+ // Two commits of a second each; the third second is pending.
+ try std.testing.expectEqual(@as(u64, 2), s.batches);
+ try s.commit(.none);
+ try std.testing.expectEqual(@as(u64, 2), s.keys);
+ var back: std.ArrayList(abi.Event) = .empty;
+ defer back.deinit(gpa);
+ try s.events(s.session, 0, 0, 180, &back);
+ try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(live.items), std.mem.sliceAsBytes(back.items));
+ // From the jump's keyframe: frame 90 on, its state 90.
+ const k = (try s.keyBefore(s.session, .frame, 100)).?;
+ try std.testing.expectEqual(@as(u64, 1), k);
+ const loaded = try s.load(s.session, k);
+ defer loaded.free(gpa);
+ try std.testing.expectEqual(@as(u64, 90), loaded.frame);
+ try std.testing.expectEqual(@as(u64, 90), std.mem.bytesToValue(u64, loaded.state));
+ try std.testing.expectEqualStrings(layout, loaded.layout);
+ try std.testing.expectEqual(@as(u64, 7), loaded.build);
+ back.clearRetainingCapacity();
+ try s.events(s.session, loaded.batch, 90, 92, &back);
+ try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(live.items[120..][0..3]), std.mem.sliceAsBytes(back.items));
+ try std.testing.expectEqual(@as(?u64, 0), try s.keyBefore(s.session, .frame, 0));
+ if (m == .memory) {
+ s.deinit();
+ continue;
+ }
+ s.close(std.mem.asBytes(&state), 2000);
+ // Reopened: the first session ended, its frames all there; a new one.
+ var again = try open(gpa, std.testing.io, .file, path, .{ .build = 8, .source = "", .layout = layout }, 3000);
+ defer again.deinit();
+ try std.testing.expectEqual(@as(u64, 1), again.session);
+ const first = try again.summary(0);
+ try std.testing.expectEqual(@as(u64, 180), first.frames);
+ try std.testing.expectEqual(@as(u64, 2000), first.ended);
+ back.clearRetainingCapacity();
+ try again.events(0, 0, 0, 180, &back);
+ try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(live.items), std.mem.sliceAsBytes(back.items));
+ }
+}
+
+test "a session database torn inside its last commit opens at the one before, every earlier session and frame in it; one that cannot be mended is kept aside" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const path = try std.fmt.bufPrint(&buf, ".zig-cache/tmp/{s}/t.xitdb", .{&tmp.sub_path});
+ const first: Stretch = .{ .build = 7, .source = "", .layout = "a layout" };
+ var live: std.ArrayList(abi.Event) = .empty;
+ defer live.deinit(gpa);
+ var state: u64 = 0;
+ // Session 0: 120 frames, closed. Session 1: 180 frames in three commits
+ // of a second, then the process gone (no exit commit).
+ var before: u64 = 0;
+ var whole: u64 = 0;
+ for ([_]u64{ 120, 180 }, 0..) |frames, session| {
+ var s = try open(gpa, io, .file, path, first, 1000 + session);
+ for (0..frames) |f| {
+ const t = f * std.time.ns_per_s / 60;
+ var one = [_]abi.Event{abi.Event.tick(t, std.time.ns_per_s / 60)};
+ try s.frame(&one, std.mem.asBytes(&state), if (f == 0) .start else null);
+ try live.appendSlice(gpa, &one);
+ state += 1;
+ }
+ if (session == 0) {
+ s.close(std.mem.asBytes(&state), 2000);
+ continue;
+ }
+ before = try s.file.?.length(io);
+ try s.commit(.none);
+ whole = try s.file.?.length(io);
+ s.deinit();
+ }
+ const bytes = try tmp.dir.readFileAlloc(io, "t.xitdb", gpa, .unlimited);
+ defer gpa.free(bytes);
+ try std.testing.expectEqual(whole, bytes.len);
+ for ([_]u64{ before, before + 1, (before + whole) / 2, whole - trailer_len, whole - 10, whole - 1 }) |cut| {
+ errdefer std.debug.print("cut at {d} of {d}..{d}\n", .{ cut, before, whole });
+ try tmp.dir.writeFile(io, .{ .sub_path = "t.xitdb", .data = bytes[0..cut] });
+ var s = try open(gpa, io, .file, path, first, 3000);
+ defer s.deinit();
+ try std.testing.expectEqual(@as(u64, 2), s.session);
+ const s0 = try s.summary(0);
+ try std.testing.expectEqual(@as(u64, 120), s0.frames);
+ try std.testing.expectEqual(@as(u64, 2000), s0.ended);
+ const s1 = try s.summary(1);
+ try std.testing.expectEqual(@as(u64, 120), s1.frames);
+ try std.testing.expectEqual(@as(u64, 0), s1.ended);
+ var back: std.ArrayList(abi.Event) = .empty;
+ defer back.deinit(gpa);
+ try s.events(0, 0, 0, 120, &back);
+ try s.events(1, 0, 0, 120, &back);
+ try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(live.items[0..240]), std.mem.sliceAsBytes(back.items));
+ var dir = try tmp.dir.openDir(io, ".", .{ .iterate = true });
+ defer dir.close(io);
+ var it = dir.iterate();
+ while (try it.next(io)) |e| try std.testing.expectEqualStrings("t.xitdb", e.name);
+ }
+ // Nothing whole to open at: kept aside as it was, a new database begun.
+ var torn = try gpa.dupe(u8, bytes);
+ defer gpa.free(torn);
+ @memset(torn[root_header_end..], 0);
+ try tmp.dir.writeFile(io, .{ .sub_path = "t.xitdb", .data = torn });
+ var s = try open(gpa, io, .file, path, first, 4 * std.time.ns_per_s);
+ defer s.deinit();
+ try std.testing.expectEqual(@as(u64, 0), s.session);
+ const aside = try tmp.dir.readFileAlloc(io, "t.xitdb.broken.4", gpa, .unlimited);
+ defer gpa.free(aside);
+ try std.testing.expectEqualSlices(u8, torn, aside);
+}
+
+test "a compacted session database is smaller and holds every session and frame" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const path = try std.fmt.bufPrint(&buf, ".zig-cache/tmp/{s}/t.xitdb", .{&tmp.sub_path});
+ const first: Stretch = .{ .build = 7, .source = "", .layout = "a layout" };
+ var live: std.ArrayList(abi.Event) = .empty;
+ defer live.deinit(gpa);
+ var s = try open(gpa, io, .file, path, first, 1000);
+ var state: u64 = 0;
+ for (0..600) |f| {
+ const t = f * std.time.ns_per_s / 60;
+ var one = [_]abi.Event{abi.Event.tick(t, std.time.ns_per_s / 60)};
+ try s.frame(&one, std.mem.asBytes(&state), if (f == 0) .start else if (f % 100 == 0) .jump else null);
+ try live.appendSlice(gpa, &one);
+ state += 1;
+ }
+ try s.commit(.none);
+ const size = try s.file.?.length(io);
+ const live_size = try liveSize(&s.db.file);
+ // Six keyframes of 8 bytes, the first all zeros: an empty page.
+ try std.testing.expectEqual(@as(u64, 600 * @sizeOf(abi.Event) + 10 * 8 + 5 * 8), live_size);
+ try s.compact();
+ s.deinit();
+ const compacted = (try tmp.dir.statFile(io, "t.xitdb", .{})).size;
+ try std.testing.expect(compacted < size);
+ var again = try open(gpa, io, .file, path, first, 2000);
+ defer again.deinit();
+ try std.testing.expectEqual(@as(u64, 600), (try again.summary(0)).frames);
+ try std.testing.expectEqual(@as(u64, 6), (try again.summary(0)).keys);
+ var back: std.ArrayList(abi.Event) = .empty;
+ defer back.deinit(gpa);
+ try again.events(0, 0, 0, 600, &back);
+ try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(live.items), std.mem.sliceAsBytes(back.items));
+}
+
+test "a memory session stops recording at its bound, and what it holds still reads" {
+ const gpa = std.testing.allocator;
+ var s = try open(gpa, std.testing.io, .memory, "", .{ .build = 7, .source = "", .layout = "a layout" }, 0);
+ defer s.deinit();
+ s.db.memory.core.max_size = 64 << 10;
+ var live: std.ArrayList(abi.Event) = .empty;
+ defer live.deinit(gpa);
+ var state: u64 = 0;
+ var failed: usize = 0;
+ for (0..60 * 60) |f| {
+ const t = f * std.time.ns_per_s / 60;
+ var one = [_]abi.Event{abi.Event.tick(t, std.time.ns_per_s / 60)};
+ s.frame(&one, std.mem.asBytes(&state), if (f == 0) .start else null) catch |err| {
+ try std.testing.expectEqual(error.WriteFailed, err);
+ failed += 1;
+ };
+ try live.appendSlice(gpa, &one);
+ state += 1;
+ }
+ try std.testing.expectEqual(@as(usize, 1), failed);
+ const n = (try s.summary(s.session)).frames;
+ try std.testing.expect(n >= 60 and n < 60 * 60);
+ var back: std.ArrayList(abi.Event) = .empty;
+ defer back.deinit(gpa);
+ try s.events(s.session, 0, 0, n, &back);
+ try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(live.items[0..n]), std.mem.sliceAsBytes(back.items));
+}
+
+test "a session's keyframes write only the pages that changed: a State of megabytes edited each minute, and one never changed" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const path = try std.fmt.bufPrint(&buf, ".zig-cache/tmp/{s}/t.xitdb", .{&tmp.sub_path});
+ // 4 MiB, every page holding something, one u64 edited a minute.
+ const state = try gpa.alloc(u8, 4 << 20);
+ defer gpa.free(state);
+ for (state, 0..) |*b, i| b.* = @truncate(i *% 7 + 1);
+ var s = try open(gpa, io, .file, path, .{ .build = 7, .source = "", .layout = "a layout" }, 1000);
+ defer s.deinit();
+ const minutes = 10;
+ var sizes: [minutes + 1]u64 = undefined;
+ for (0..minutes * 60 * 60) |f| {
+ const t = f * std.time.ns_per_s / 60;
+ var one = [_]abi.Event{abi.Event.tick(t, std.time.ns_per_s / 60)};
+ if (f % 3600 == 1800) std.mem.writeInt(u64, state[(f / 3600) * 300_000 ..][0..8], f, .little);
+ try s.frame(&one, state, if (f == 0) .start else null);
+ if (f % 3600 == 0) {
+ try s.commit(.none);
+ sizes[f / 3600] = try s.file.?.length(io);
+ }
+ }
+ try s.commit(.none);
+ sizes[minutes] = try s.file.?.length(io);
+ // One keyframe a minute: at 0 s, 60 s, ...
+ try std.testing.expectEqual(@as(u64, minutes), s.keys);
+ // A minute is 216,000 bytes of ticks and a keyframe of one page with
+ // its copied path: under 230 KB a minute, where a whole State a
+ // keyframe was 4 MiB.
+ for (1..minutes) |m| try std.testing.expect(sizes[m + 1] - sizes[m] < 230_000);
+ // Every keyframe reads back whole: the edits made before it, and none after.
+ const want = try gpa.alloc(u8, state.len);
+ defer gpa.free(want);
+ for (0..minutes) |k| {
+ for (want, 0..) |*b, i| b.* = @truncate(i *% 7 + 1);
+ for (0..k) |m| std.mem.writeInt(u64, want[m * 300_000 ..][0..8], m * 3600 + 1800, .little);
+ const loaded = try s.load(s.session, k);
+ defer loaded.free(gpa);
+ try std.testing.expectEqual(@as(u64, k * 3600), loaded.frame);
+ try std.testing.expectEqualSlices(u8, want, loaded.state);
+ }
+ // A keyframe alone, in a commit of its own: one changed page is that
+ // page, its copied path and the keyframe's fields; no changed page (one
+ // kept before a reload) is the fields alone.
+ for ([_]bool{ true, false }) |edit| {
+ if (edit) state[123] +%= 1;
+ const before = try s.file.?.length(io);
+ _ = try s.keyframe(if (edit) .jump else .before_reload, state);
+ try s.commit(.none);
+ try std.testing.expect(try s.file.?.length(io) - before < @as(u64, if (edit) 12 << 10 else 8 << 10));
+ }
+ const last = try s.load(s.session, s.keys - 1);
+ defer last.free(gpa);
+ try std.testing.expectEqualSlices(u8, state, last.state);
+}
+
+test "an exported session keeps its keyframes' shared pages shared" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const path = try std.fmt.bufPrint(&buf, ".zig-cache/tmp/{s}/t.xitdb", .{&tmp.sub_path});
+ var out_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const out = try std.fmt.bufPrint(&out_buf, ".zig-cache/tmp/{s}/one.xitdb", .{&tmp.sub_path});
+ const state = try gpa.alloc(u8, 1 << 20);
+ defer gpa.free(state);
+ for (state, 0..) |*b, i| b.* = @truncate(i *% 13 + 1);
+ var s = try open(gpa, io, .file, path, .{ .build = 7, .source = "", .layout = "a layout" }, 1000);
+ defer s.deinit();
+ // Ten keyframes a byte apart.
+ for (0..600) |f| {
+ const t = f * std.time.ns_per_s / 60;
+ var one = [_]abi.Event{abi.Event.tick(t, std.time.ns_per_s / 60)};
+ if (f % 60 == 0) state[f * 100] +%= 1;
+ try s.frame(&one, state, if (f == 0) .start else if (f % 60 == 0) .jump else null);
+ }
+ try s.exportSession(0, out);
+ const size = (try std.Io.Dir.cwd().statFile(io, out, .{})).size;
+ // One State and nine pages, not ten States.
+ try std.testing.expect(size < state.len + state.len / 8);
+ var again = try open(gpa, io, .file, out, .{ .build = 7, .source = "", .layout = "a layout" }, 2000);
+ defer again.deinit();
+ const loaded = try again.load(0, 9);
+ defer loaded.free(gpa);
+ try std.testing.expectEqualSlices(u8, state, loaded.state);
+}
+
+test "a session database past max_save drops its oldest history: the present and the marks stay, the file under it" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const path = try std.fmt.bufPrint(&buf, ".zig-cache/tmp/{s}/t.xitdb", .{&tmp.sub_path});
+ // 2 MiB of State, its first half rewritten each second: a keyframe
+ // writes 1 MiB, so the cap is reached at about the 60th.
+ const state = try gpa.alloc(u8, 2 << 20);
+ defer gpa.free(state);
+ @memset(state, 1);
+ var s = try open(gpa, io, .file, path, .{ .build = 7, .source = "", .layout = "a layout" }, 1000);
+ defer s.deinit();
+ for (0..100) |k| {
+ @memset(state[0 .. 1 << 20], @truncate(k + 2));
+ var one = [_]abi.Event{abi.Event.tick(k * std.time.ns_per_s, std.time.ns_per_s)};
+ try s.frame(&one, state, if (k == 0) .start else .jump);
+ if (k == 5) _ = try s.mark("a", .mark, state);
+ if (k == 20) _ = try s.mark("b", .mark, state);
+ try std.testing.expect(try s.file.?.length(io) <= max_save);
+ }
+ try s.commit(.none);
+ // The oldest keyframes and frames are gone; the marks and the newest
+ // keyframe read back whole.
+ try std.testing.expectError(error.HistoryDropped, s.load(0, 1));
+ var log: std.ArrayList(abi.Event) = .empty;
+ defer log.deinit(gpa);
+ try std.testing.expectError(error.HistoryDropped, s.events(0, 0, 0, 2, &log));
+ for ([_]struct { []const u8, u8 }{ .{ "a", 7 }, .{ "b", 22 } }) |want| {
+ const m = (try s.findMark(want[0])).?;
+ const loaded = try s.load(m.session, m.key);
+ defer loaded.free(gpa);
+ try std.testing.expectEqual(want[1], loaded.state[0]);
+ try std.testing.expectEqual(@as(u8, 1), loaded.state[1 << 20]);
+ }
+ const newest = try s.load(0, s.keys - 1);
+ defer newest.free(gpa);
+ try std.testing.expectEqualSlices(u8, state, newest.state);
+ try s.events(0, newest.batch, newest.frame, s.frames, &log);
+}
+
+test "a session database without history keeps the present and the marks, and leaves nothing else at exit" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const path = try std.fmt.bufPrint(&buf, ".zig-cache/tmp/{s}/t.xitdb", .{&tmp.sub_path});
+ var state: [64 << 10]u8 = @splat(1);
+ var s = try open(gpa, io, .file, path, .{ .build = 7, .source = "", .layout = "a layout" }, 1000);
+ s.history = false;
+ for (0..20) |k| {
+ @memset(state[0 .. 32 << 10], @truncate(k + 2));
+ var one = [_]abi.Event{abi.Event.tick(k * std.time.ns_per_s, std.time.ns_per_s)};
+ try s.frame(&one, &state, if (k == 0) .start else .jump);
+ if (k == 3) _ = try s.mark("a", .mark, &state);
+ }
+ try s.commit(.none);
+ try std.testing.expectError(error.HistoryDropped, s.load(0, 1));
+ const m = (try s.findMark("a")).?;
+ const loaded = try s.load(m.session, m.key);
+ loaded.free(gpa);
+ s.close(&state, 2000);
+ // At exit: compacted to the present, the mark and the session's fields.
+ try std.testing.expect((try tmp.dir.statFile(io, "t.xitdb", .{})).size < 3 * state.len);
+ var again = try open(gpa, io, .file, path, .{ .build = 7, .source = "", .layout = "a layout" }, 3000);
+ defer again.deinit();
+ var log: std.ArrayList(abi.Event) = .empty;
+ defer log.deinit(gpa);
+ const now = (try again.present(&log)).?;
+ defer now.free(gpa);
+ try std.testing.expectEqualSlices(u8, &state, now.state);
+}
+
+test "a session database full of marks refuses a mark of a new name, and takes one over an old name" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const path = try std.fmt.bufPrint(&buf, ".zig-cache/tmp/{s}/t.xitdb", .{&tmp.sub_path});
+ // 2 MiB of State, all of it changed for each mark.
+ const state = try gpa.alloc(u8, 2 << 20);
+ defer gpa.free(state);
+ var s = try open(gpa, io, .file, path, .{ .build = 7, .source = "", .layout = "a layout" }, 1000);
+ defer s.deinit();
+ var name: [8]u8 = undefined;
+ var k: u8 = 0;
+ while (true) : (k += 1) {
+ @memset(state, k + 1);
+ _ = s.mark(try std.fmt.bufPrint(&name, "m{d}", .{k}), .mark, state) catch |err| {
+ try std.testing.expectEqual(error.SaveFull, err);
+ break;
+ };
+ try std.testing.expect(k < 40 and try s.file.?.length(io) <= max_save);
+ }
+ try std.testing.expect(k > 20);
+ @memset(state, 99);
+ try std.testing.expectError(error.SaveFull, s.mark("new", .mark, state));
+ _ = try s.mark("m3", .mark, state);
+ try s.commit(.none);
+ try std.testing.expect(try s.file.?.length(io) <= max_save);
+ // Every mark's newest keyframe is whole.
+ for (0..k) |i| {
+ const m = (try s.findMark(try std.fmt.bufPrint(&name, "m{d}", .{i}))).?;
+ const loaded = try s.load(m.session, m.key);
+ defer loaded.free(gpa);
+ try std.testing.expectEqual(@as(u8, if (i == 3) 99 else @intCast(i + 1)), loaded.state[state.len - 1]);
+ }
+}
diff --git a/src/host/audio.zig b/src/host/audio.zig
index aebb909..880be72 100644
--- a/src/host/audio.zig
+++ b/src/host/audio.zig
@@ -11,6 +11,9 @@ pub const sample_rate = 48_000;
const spec: c.SDL_AudioSpec = .{ .format = c.SDL_AUDIO_F32, .channels = 1, .freq = sample_rate };
/// A device block plus the next frame; 512 samples can underrun at 60 Hz.
const queue_samples = 2048;
+/// How far a group's gain moves a sample toward a new one: a full swing
+/// takes 10 ms, so a gain set in a step does not click.
+const gain_step = 1.0 / 480.0;
pub const Audio = struct {
gpa: std.mem.Allocator,
@@ -20,8 +23,24 @@ pub const Audio = struct {
clips: std.ArrayList([]f32) = .empty,
paths: std.StringHashMapUnmanaged(abi.Audio) = .empty,
voices: std.ArrayList(Playing) = .empty,
+ /// Each group's gain as declared this frame, and as the mix has got to.
+ gains: [8]f32 = @splat(1),
+ heard_gains: [8]f32 = @splat(1),
streams: std.ArrayList(Stream) = .empty,
status: std.ArrayList(abi.Stream) = .empty,
+ /// Samples the device takes from each stream at once.
+ pull: u32 = 1024,
+ /// The wall-clock time (ns) between the ends of the last frames'
+ /// commands, where pushes are done; and when the last ended.
+ intervals: [64]u64 = @splat(0),
+ frame: u64 = 0,
+ last_frame: u64 = 0,
+ /// Grown by underruns, shrinking back while there are none.
+ margin: u32 = 0,
+ /// A stream ran dry since the lead was last worked out.
+ dry: bool = false,
+ /// `Input.lead`: see `lead`.
+ lead: u32 = 4800,
scope: Scope = .{},
/// The default recording device, bound to this stream while declared.
microphone: ?*c.SDL_AudioStream = null,
@@ -29,13 +48,38 @@ pub const Audio = struct {
/// Set when opening failed, so it is tried once per declaration.
deaf: bool = false,
- const Playing = struct { voice: abi.Voice, cursor: usize = 0, done: bool = false, seen: bool = true };
- const Stream = struct { key: u32, out: *c.SDL_AudioStream, pushed: u64 = 0 };
+ const Playing = struct {
+ voice: abi.Voice,
+ /// Where in the sound, in its samples: fractional when `rate` is.
+ cursor: f64 = 0,
+ done: bool = false,
+ seen: bool = true,
+ /// Mixed since a script last asked (`expect-audio`).
+ sounded: bool = false,
+ };
+ const Stream = struct {
+ key: u32,
+ out: *c.SDL_AudioStream,
+ pushed: u64 = 0,
+ /// Pushed to this frame, and the last.
+ fed: bool = false,
+ was_fed: bool = false,
+ underruns: u32 = 0,
+ };
- pub fn open(self: *Audio) !void {
+ /// The default playback device, taking `pull` samples at once if asked
+ /// (`abi.Info.audio_pull`): a hint, so the environment's wins.
+ pub fn open(self: *Audio, pull: u32) !void {
+ var hint: [16]u8 = undefined;
+ if (pull > 0) _ = c.SDL_SetHint(c.SDL_HINT_AUDIO_DEVICE_SAMPLE_FRAMES, try std.fmt.bufPrintSentinel(&hint, "{d}", .{pull}, 0));
const device = c.SDL_OpenAudioDevice(c.SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &spec);
if (device == 0) return error.OpenAudio;
self.device = device;
+ var format: c.SDL_AudioSpec = undefined;
+ var frames: c_int = 0;
+ if (c.SDL_GetAudioDeviceFormat(device, &format, &frames) and frames > 0 and format.freq > 0) {
+ self.pull = @intCast(@divFloor(@as(i64, frames) * sample_rate + format.freq - 1, format.freq));
+ }
self.voices_out = try self.bind();
self.scope.attach(device) catch {};
}
@@ -81,6 +125,12 @@ pub const Audio = struct {
return self.add(decodeBytes(self.gpa, wav) catch return .none);
}
+ /// A copy of `samples`; `.none` if one is not finite.
+ pub fn new(self: *Audio, samples: []const f32) abi.Audio {
+ for (samples) |v| if (!std.math.isFinite(v)) return .none;
+ return self.add(self.gpa.dupe(f32, samples) catch return .none);
+ }
+
fn add(self: *Audio, samples: []f32) abi.Audio {
self.clips.append(self.gpa, samples) catch {
self.gpa.free(samples);
@@ -97,6 +147,7 @@ pub const Audio = struct {
pub fn beginFrame(self: *Audio) void {
for (self.voices.items) |*v| v.seen = false;
+ self.gains = @splat(1);
self.listening = false;
}
@@ -155,9 +206,18 @@ pub const Audio = struct {
if (clear) {
_ = c.SDL_ClearAudioStream(s.out);
s.pushed = 0;
+ s.was_fed = false;
}
if (samples.len == 0) return;
+ // Fed last frame and empty now: the device came up short since
+ // (counted at the push, as a pull before it would hide it by the
+ // next frame).
+ if (s.was_fed and !s.fed and c.SDL_GetAudioStreamQueued(s.out) == 0) {
+ s.underruns += 1;
+ self.dry = true;
+ }
if (c.SDL_PutAudioStreamData(s.out, samples.ptr, @intCast(samples.len * @sizeOf(f32)))) s.pushed += samples.len;
+ s.fed = true;
}
fn streamFor(self: *Audio, key: u32) ?*Stream {
@@ -171,14 +231,22 @@ pub const Audio = struct {
return &self.streams.items[self.streams.items.len - 1];
}
- /// Drops undeclared voices, keeps the voice mix queued ahead, and opens
- /// or closes the microphone.
+ /// Drops undeclared voices, works out the lead for the next frame, keeps
+ /// the voice mix queued ahead, and opens or closes the microphone.
pub fn endFrame(self: *Audio) void {
self.reconcileMicrophone();
var i: usize = 0;
while (i < self.voices.items.len) {
if (self.voices.items[i].seen) i += 1 else _ = self.voices.swapRemove(i);
}
+ const now = c.SDL_GetTicksNS();
+ if (self.last_frame != 0) {
+ self.intervals[self.frame % self.intervals.len] = now -| self.last_frame;
+ self.frame += 1;
+ }
+ self.last_frame = now;
+ self.lead = lead(self.intervals, self.pull, &self.margin, self.dry);
+ self.dry = false;
const out = self.voices_out orelse return;
const queued = c.SDL_GetAudioStreamQueued(out);
if (queued < 0) return;
@@ -189,45 +257,98 @@ pub const Audio = struct {
}
/// Mixes live voices into `output`; returns how many samples were written,
- /// stopping early once every voice has finished.
+ /// stopping early once every voice has finished. A voice at another
+ /// rate is resampled by linear interpolation between its neighbours
+ /// (at rate 1 it is its samples, exactly).
pub fn mix(self: *Audio, output: []f32) usize {
var count: usize = 0;
for (output) |*sample| {
var sum: f32 = 0;
var alive = false;
+ for (&self.heard_gains, self.gains) |*heard, gain| heard.* += std.math.clamp(gain - heard.*, -gain_step, gain_step);
for (self.voices.items) |*playing| {
if (playing.done) continue;
const samples = self.samplesOf(playing.voice.audio);
- if (playing.cursor >= samples.len) {
+ const len: f64 = @floatFromInt(samples.len);
+ // Also ends a cursor an infinite or NaN rate made.
+ if (!(playing.cursor < len)) {
playing.done = true;
continue;
}
alive = true;
+ playing.sounded = true;
const v = playing.voice;
- const edge = @min(playing.cursor + 1, samples.len - playing.cursor);
+ const i: usize = @intFromFloat(playing.cursor);
+ const t: f32 = @floatCast(playing.cursor - @floor(playing.cursor));
+ const next = if (i + 1 < samples.len) samples[i + 1] else if (v.loop) samples[0] else 0;
+ const at = if (t == 0) samples[i] else samples[i] + (next - samples[i]) * t;
+ const edge = @min(i + 1, samples.len - i);
const fade: f32 = if (v.fade == 0) 1 else @as(f32, @floatFromInt(@min(edge, v.fade))) / @as(f32, @floatFromInt(v.fade));
- sum += samples[playing.cursor] * v.volume * fade;
- playing.cursor += 1;
- if (playing.cursor == samples.len and v.loop) playing.cursor = 0;
+ sum += at * v.volume * self.heard_gains[v.group] * fade;
+ playing.cursor += @max(v.rate, 0);
+ if (playing.cursor >= len and v.loop) playing.cursor = @mod(playing.cursor, len);
}
if (!alive) break;
- // Bounded however many voices sound at once.
- sample.* = sum / (1 + @abs(sum));
+ sample.* = limit(sum);
count += 1;
}
return count;
}
+ /// Whether voice `key` was mixed since the last call: for scripts.
+ pub fn sounded(self: *Audio, key: u32) bool {
+ for (self.voices.items) |*playing| if (playing.voice.key == key) {
+ defer playing.sounded = false;
+ return playing.sounded;
+ };
+ return false;
+ }
+
+ /// The streams as a frame starts.
pub fn streamStatus(self: *Audio) []const abi.Stream {
self.status.clearRetainingCapacity();
- for (self.streams.items) |s| {
- const queued = c.SDL_GetAudioStreamQueued(s.out);
- self.status.append(self.gpa, .{ .key = s.key, .queued = @intCast(@divFloor(@max(queued, 0), @sizeOf(f32))), .pushed = s.pushed }) catch {};
+ for (self.streams.items) |*s| {
+ const queued: u32 = @intCast(@divFloor(@max(c.SDL_GetAudioStreamQueued(s.out), 0), @sizeOf(f32)));
+ s.was_fed = s.fed;
+ s.fed = false;
+ self.status.append(self.gpa, .{ .key = s.key, .queued = queued, .pushed = s.pushed, .underruns = s.underruns }) catch {};
}
return self.status.items;
}
};
+/// How many samples to keep queued: the slowest of the last frames' worth
+/// (pushes come once a frame, `intervals` apart), plus the device's pull
+/// (it takes that much at once), plus `margin`: half a pull more at each
+/// underrun (`dry`), back down by a sample a frame.
+fn lead(intervals: [64]u64, pull: u32, margin: *u32, dry: bool) u32 {
+ var slowest: u64 = 0;
+ for (intervals) |ns| slowest = @max(slowest, ns);
+ margin.* = if (dry) @min(margin.* + pull / 2, max_lead) else margin.* -| 1;
+ const frame: u32 = @intCast(@min(slowest * sample_rate / std.time.ns_per_s, 1 << 20));
+ return @min(frame + pull + margin.*, max_lead);
+}
+/// 170 ms: a frame slower than that is a stall, not a pace.
+const max_lead = 8192;
+
+/// Where the voice mix stops being passed through: -2.5 dBFS. Quieter
+/// mixes keep their true volume to the bit; a clip normalised to full scale
+/// only has its peaks bent (1 comes out at 0.875).
+pub const knee = 0.75;
+
+/// The voice mix, bounded however many voices sound at once: unity gain up
+/// to the knee, then `knee + (1 - knee)·u/(1 + u)` with `u` how far past the
+/// knee in units of the room left, which meets the line at the knee with
+/// its slope (1) and tends to 1. (With a knee of 0 it is the old
+/// `x/(1 + |x|)`.) Written `1 - 1/(1 + u)` so that every step rounds
+/// monotonically and infinity comes out at 1. No state, no lookahead.
+pub fn limit(x: f32) f32 {
+ const a = @abs(x);
+ if (a <= knee) return x;
+ const u = (a - knee) / (1 - knee);
+ return std.math.copysign(knee + (1 - knee) * (1 - 1 / (1 + u)), x);
+}
+
/// WAV, FLAC or Ogg Vorbis, by content (see `vendor/codecs.h`).
fn decodeBytes(gpa: std.mem.Allocator, bytes: []const u8) ![]f32 {
var channels: u32 = 0;
@@ -325,3 +446,116 @@ test "voices reconcile: one-shots finish and stay silent, new serials restart, u
try std.testing.expectEqual(@as(usize, 1), audio.voices.items.len);
try std.testing.expectEqual(@as(usize, 8), audio.mix(&out));
}
+
+test "voices play made sounds: copied, and refused when not finite" {
+ var audio: Audio = .{ .gpa = std.testing.allocator };
+ defer audio.deinit();
+ var made = [_]f32{ 0.25, -0.25 };
+ const sound = audio.new(&made);
+ made[0] = 1;
+ try std.testing.expectEqualSlices(f32, &.{ 0.25, -0.25 }, audio.samplesOf(sound));
+ try std.testing.expectEqual(abi.Audio.none, audio.new(&.{ 0, std.math.nan(f32) }));
+ try std.testing.expectEqual(abi.Audio.none, audio.new(&.{std.math.inf(f32)}));
+}
+
+test "the mixer passes the mix through below the knee and limits it to 1 above, rising" {
+ // Identity to the bit: every 997th float from 0 to the knee, both signs.
+ const knee_bits: u32 = @bitCast(@as(f32, knee));
+ var bits: u32 = 0;
+ while (bits <= knee_bits) : (bits += 997) {
+ const x: f32 = @bitCast(bits);
+ try std.testing.expectEqual(@as(u32, @bitCast(x)), @as(u32, @bitCast(limit(x))));
+ try std.testing.expectEqual(@as(u32, @bitCast(-x)), @as(u32, @bitCast(limit(-x))));
+ }
+ try std.testing.expectEqual(@as(f32, knee), limit(knee));
+ // Rising and at most 1, from the knee's neighbourhood (every float) to
+ // infinity (every 101st), and odd.
+ var last = limit(@bitCast(knee_bits - 100_000));
+ bits = knee_bits - 100_000;
+ const inf_bits: u32 = @bitCast(std.math.inf(f32));
+ while (bits <= inf_bits) : (bits += if (bits < knee_bits + 100_000) 1 else 101) {
+ const x: f32 = @bitCast(bits);
+ const y = limit(x);
+ try std.testing.expect(y >= last and y <= 1);
+ try std.testing.expectEqual(-y, limit(-x));
+ last = y;
+ }
+ try std.testing.expectEqual(@as(f32, 1), limit(std.math.inf(f32)));
+ // Slope 1 on both sides of the knee, and what a full-scale peak becomes.
+ const h = 1e-3;
+ try std.testing.expectApproxEqAbs(@as(f32, 1), (limit(knee + h) - limit(knee)) / h, 0.01);
+ try std.testing.expectEqual(@as(f32, 0.875), limit(1));
+}
+
+test "voices at another rate are resampled linearly, and a group's gain scales its voices smoothly" {
+ var audio: Audio = .{ .gpa = std.testing.allocator };
+ defer audio.deinit();
+ const clip = audio.new(&.{ 0, 0.1, 0.2, 0.3 });
+ var out: [1024]f32 = undefined;
+ // Half speed: twice as long, the halves interpolated (the last toward
+ // silence); double speed: every other sample.
+ audio.declare(.{ .key = 1, .audio = clip, .rate = 0.5 });
+ try std.testing.expectEqual(@as(usize, 8), audio.mix(&out));
+ for ([_]f32{ 0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.15 }, out[0..8]) |want, got| try std.testing.expectApproxEqAbs(want, got, 1e-6);
+ audio.declare(.{ .key = 1, .audio = clip, .rate = 2, .serial = 1 });
+ try std.testing.expectEqual(@as(usize, 2), audio.mix(&out));
+ try std.testing.expectEqualSlices(f32, &.{ 0, 0.2 }, out[0..2]);
+ // Rate 0 holds it; an infinite rate ends it.
+ audio.declare(.{ .key = 1, .audio = clip, .rate = 0, .serial = 2 });
+ try std.testing.expectEqual(@as(usize, 3), audio.mix(out[0..3]));
+ audio.declare(.{ .key = 1, .audio = clip, .rate = std.math.inf(f32), .serial = 3 });
+ try std.testing.expectEqual(@as(usize, 1), audio.mix(&out));
+
+ // A looping voice in group 1 and one in group 0, at 0.25 each: group 1
+ // set to 0.5 glides there in 10 ms and stays; group 0 is untouched.
+ const level = audio.new(&.{0.25});
+ audio.beginFrame();
+ audio.declare(.{ .key = 1, .audio = level, .loop = true, .group = 1 });
+ audio.declare(.{ .key = 2, .audio = level, .loop = true });
+ audio.gains[1] = 0.5;
+ try std.testing.expectEqual(out.len, audio.mix(&out));
+ try std.testing.expect(out[0] < 0.5 and out[0] > 0.49);
+ try std.testing.expect(out[100] > out[200] and out[200] > out[400]);
+ try std.testing.expectEqual(@as(f32, 0.375), out[480]);
+ try std.testing.expectEqual(@as(f32, 0.375), out[1023]);
+ // Undeclared next frame: back to 1, as smoothly.
+ audio.beginFrame();
+ audio.declare(.{ .key = 1, .audio = level, .loop = true, .group = 1 });
+ audio.declare(.{ .key = 2, .audio = level, .loop = true });
+ try std.testing.expectEqual(out.len, audio.mix(&out));
+ try std.testing.expect(out[0] > 0.375 and out[0] < 0.38);
+ try std.testing.expectEqual(@as(f32, 0.5), out[1023]);
+}
+
+test "the lead the mixer gives streams outlasts the slowest recent frame and the device's pull, more after an underrun" {
+ const expectEqual = std.testing.expectEqual;
+ var intervals: [64]u64 = @splat(20 * std.time.ns_per_ms);
+ var margin: u32 = 0;
+ // 50 Hz and a pull of 1024: a frame's 960 samples and the pull.
+ try expectEqual(@as(u32, 960 + 1024), lead(intervals, 1024, &margin, false));
+ // One 50 ms frame in the window sets it.
+ intervals[5] = 50 * std.time.ns_per_ms;
+ try expectEqual(@as(u32, 2400 + 1024), lead(intervals, 1024, &margin, false));
+ // An underrun adds half a pull, which goes a sample a frame.
+ try expectEqual(@as(u32, 2400 + 1024 + 512), lead(intervals, 1024, &margin, true));
+ try expectEqual(@as(u32, 2400 + 1024 + 511), lead(intervals, 1024, &margin, false));
+ // A stall is not a pace: the lead stops at 170 ms.
+ intervals[6] = std.time.ns_per_s;
+ try expectEqual(@as(u32, max_lead), lead(intervals, 1024, &margin, false));
+}
+
+test "the mixer's device takes at once what the sketch asks, SDL's own when it asks nothing, and the environment's over both" {
+ _ = c.SDL_SetHintWithPriority(c.SDL_HINT_AUDIO_DRIVER, "dummy", c.SDL_HINT_OVERRIDE);
+ try std.testing.expect(c.SDL_Init(c.SDL_INIT_AUDIO));
+ defer c.SDL_Quit();
+ defer _ = c.SDL_ResetHint(c.SDL_HINT_AUDIO_DEVICE_SAMPLE_FRAMES);
+ for ([_][3]u32{ .{ 0, 0, 1024 }, .{ 256, 0, 256 }, .{ 256, 512, 512 } }) |case| {
+ // SDL's copy of the environment, not the process's.
+ if (case[1] > 0) try std.testing.expect(c.SDL_SetEnvironmentVariable(c.SDL_GetEnvironment(), c.SDL_HINT_AUDIO_DEVICE_SAMPLE_FRAMES, "512", true));
+ defer _ = c.SDL_UnsetEnvironmentVariable(c.SDL_GetEnvironment(), c.SDL_HINT_AUDIO_DEVICE_SAMPLE_FRAMES);
+ var a: Audio = .{ .gpa = std.testing.allocator };
+ try a.open(case[0]);
+ defer a.deinit();
+ try std.testing.expectEqual(case[2], a.pull);
+ }
+}
diff --git a/src/host/control.zig b/src/host/control.zig
index 8cc8296..943316c 100644
--- a/src/host/control.zig
+++ b/src/host/control.zig
@@ -2,17 +2,45 @@
const std = @import("std");
const c9 = @import("cloud9");
const c = @import("c");
+const abi = @import("abi");
const Host = @import("Host.zig");
const Presentation = @import("Presentation.zig");
+const state_files = @import("state_files.zig");
+const script = @import("script.zig");
+const Console = @import("Console.zig");
const fs = c9.fs;
const transport = c9.transport;
const Backend = struct {
pub const Req = fs.Req;
pub const Reply = fs.Reply;
};
-const Server = fs.Server(Backend, .{ .fid_capacity = 32, .slot_capacity = 4 });
+const Server = fs.Server(Backend, .{ .fid_capacity = 32, .slot_capacity = 4, .name_capacity = 64 });
const msize = 16384;
-const names = [_][]const u8{ "/", "ctl", "status", "log", "screen.png", "profile", "profile-trace", "timing-trace", "presentation-trace" };
+/// The files, a row each: what lookup, readdir and getattr answer. A
+/// file's node is its number here.
+const File = enum(u64) { @"/" = 1, ctl, status, log, @"screen.png", profile, @"profile-trace", @"timing-trace", @"presentation-trace", README, commands, sketch = 1 << 63, state = @bitCast(state_files.root) };
+const files = std.enums.EnumArray(File, struct { mode: u16 = 0o400, doc: []const u8 }).init(.{
+ .@"/" = .{ .mode = 0o700, .doc = "" },
+ .ctl = .{ .mode = 0o600, .doc = "write a verb a line, of those below: ctl's own, the input a script plays (live, no frame of its own), the console's; any other line goes to the sketch (commands lists its words)" },
+ .status = .{ .doc = "name, canvas size, playback mode, gpu, and the screenshot's state" },
+ .log = .{ .doc = "the console's last five lines" },
+ .@"screen.png" = .{ .doc = "the next frame, as PNG: an open waits for it to be drawn, and pins its own copy" },
+ .profile = .{ .doc = "with --profile-gpu: label, count, mean, worst, p95 and p99 ms, tab-separated" },
+ .@"profile-trace" = .{ .doc = "with --profile-gpu: label,sample,ns, the samples kept, as CSV" },
+ .@"timing-trace" = .{ .doc = "index,frame_ns,work_ns,outside_work_ns, the frames kept, as CSV" },
+ .@"presentation-trace" = .{ .doc = "on Wayland: presentation feedback per frame, as CSV" },
+ .README = .{ .doc = "this: a line a file, ctl's verbs under it, a line a State file under state/" },
+ .commands = .{ .doc = "every verb ctl takes, a line each, the sketch's words last" },
+ .sketch = .{ .mode = 0o700, .doc = "the sketch's own files, which the host never serves: reserved, empty" },
+ .state = .{ .mode = 0o700, .doc = "the sketch's State: a directory per struct and array, a file per value; a read is the value, a write what set does (a jump); an array of numbers is one file of its values, blank-separated" },
+});
+
+/// The verbs `ctl` takes beside the console's lines.
+const Verb = enum { screenshot, @"profile-reset" };
+const verbs = std.enums.EnumArray(Verb, []const u8).init(.{
+ .screenshot = "captures the next frame (status says when); screen.png's open does it itself",
+ .@"profile-reset" = "clears profile's counters and frame count, keeping its labels",
+});
const Connection = struct {
fd: c_int = -1,
@@ -38,6 +66,9 @@ pub const Control = struct {
allocator: std.mem.Allocator,
path: [:0]u8,
listener: c_int,
+ /// Serving with no sketch running (`fs` with it closed): the State to
+ /// show and where it came from; the host is not touched.
+ offline: ?Offline = null,
connections: [4]Connection = @splat(.{}),
png: []u8 = &.{},
capture_pending: bool = false,
@@ -60,6 +91,36 @@ pub const Control = struct {
return self;
}
+ /// Listens at `where`: a socket path, or a name posted as
+ /// `$XDG_RUNTIME_DIR/9p/sketchbook/<where>` (a stale entry replaced, a
+ /// live one refused).
+ pub fn open(a: std.mem.Allocator, environ: *const std.process.Environ.Map, where: []const u8) !*Control {
+ if (std.mem.startsWith(u8, where, "/")) return init(a, where);
+ var buf: [c9.post.sun_path_len]u8 = undefined;
+ const path = try registered(environ, where, &buf);
+ const dir = path[0..std.mem.lastIndexOfScalar(u8, path, '/').?];
+ var dir_buf: [c9.post.sun_path_len]u8 = undefined;
+ for ([_]usize{ dir.len - "/sketchbook".len, dir.len }) |n| _ = std.c.mkdir(std.fmt.bufPrintSentinel(&dir_buf, "{s}", .{dir[0..n]}, 0) catch unreachable, 0o700);
+ switch (c9.post.probe(path)) {
+ .live => return error.AlreadyPosted,
+ .stale => _ = std.c.unlink(path),
+ .none => {},
+ }
+ return init(a, path);
+ }
+
+ /// Serves one client on `fd` until it hangs up: `fs` with no sketch
+ /// running, on a thread of its own.
+ pub fn serveOffline(self: *Control, fd: c_int) void {
+ const conn = self.allocator.create(Connection) catch return transport.close(fd);
+ defer self.allocator.destroy(conn);
+ conn.* = .{ .fd = fd };
+ conn.server = .init(.{ .in = &conn.input, .out = &conn.output, .root = 1 });
+ var host: Host = undefined; // Offline, nothing reads it.
+ while (true) self.service(&host, conn) catch break;
+ conn.close(self.allocator);
+ }
+
pub fn deinit(self: *Control) void {
for (&self.connections) |*conn| conn.close(self.allocator);
transport.close(self.listener);
@@ -97,7 +158,8 @@ pub const Control = struct {
conn.used -= consumed;
progressed = consumed != 0;
}
- while (conn.server.next()) |req| self.answer(host, conn, req);
+ while (conn.server.retry()) |req| self.answer(host, conn, req, true);
+ while (conn.server.next()) |req| self.answer(host, conn, req, false);
if (conn.server.protocol.dead) return error.Closed;
if (conn.server.output().len > 0) {
if (try transport.write(conn.fd, conn.server.output())) |n| {
@@ -117,42 +179,58 @@ pub const Control = struct {
}
}
- fn answer(self: *Control, host: *Host, conn: *Connection, req: fs.Req) void {
+ /// Answers a request, or parks it: an open of screen.png asks for the
+ /// next frame and waits for it, asked again (`retried`) each frame
+ /// until the capture has landed.
+ fn answer(self: *Control, host: *Host, conn: *Connection, req: fs.Req, retried: bool) void {
var reply: fs.Reply = .{ .tag = req.tag };
var buffer: [msize]u8 = undefined;
+ if (!retried and req.op == .open and req.node == @backingInt(File.@"screen.png")) {
+ self.capture_pending = true;
+ self.capture_error = null;
+ }
const bytes = self.respond(host, conn, req, &reply, &buffer) catch |err| blk: {
- reply = .{ .tag = req.tag, .status = .err, .errno = fs.E.INVAL, .ename = @errorName(err) };
+ reply = if (err == error.CapturePending) .{ .tag = req.tag, .status = .again } else .{ .tag = req.tag, .status = .err, .errno = fs.E.INVAL, .ename = if (err == error.SketchNotRunning) self.offline.?.from else @errorName(err) };
break :blk &.{};
};
conn.server.reply(&reply, bytes);
}
fn respond(self: *Control, host: *Host, conn: *Connection, req: fs.Req, reply: *fs.Reply, buffer: []u8) ![]const u8 {
- if (req.node < 1 or req.node > names.len) return error.UnknownFile;
+ // Nodes from 2^63 are the sketch's: none is served but sketch/.
+ if (req.node > @backingInt(File.sketch)) return error.UnknownFile;
+ if (req.node & @as(u64, @bitCast(state_files.root)) != 0) return stateRespond(self, host, conn, req, reply, buffer);
+ const file = std.enums.fromInt(File, req.node) orelse return error.UnknownFile;
+ if (self.offline != null and (req.op == .write or (req.op == .open or req.op == .read) and file != .README and file != .commands and file != .ctl and file != .@"/" and file != .sketch)) return error.SketchNotRunning;
switch (req.op) {
.lookup => {
- if (req.node != 1) return error.NotDirectory;
- for (names[1..], 2..) |name, node| if (std.mem.eql(u8, name, req.data)) {
- reply.attr = self.attr(node);
- return &.{};
- };
- return error.UnknownFile;
+ if (file == .sketch) return error.UnknownFile;
+ if (file != .@"/") return error.NotDirectory;
+ const found = std.meta.stringToEnum(File, req.data) orelse return error.UnknownFile;
+ if (found == .@"/") return error.UnknownFile;
+ reply.attr = self.attr(@backingInt(found));
},
.getattr => reply.attr = self.attr(req.node),
.open => {
- if (req.node == 5 or req.node == 7 or req.node == 8 or req.node == 9) {
- if (req.node == 5) {
+ if (file == .@"screen.png" or file == .@"profile-trace" or file == .@"timing-trace" or file == .@"presentation-trace" or file == .README or file == .commands) {
+ if (file == .@"screen.png") {
if (self.capture_pending) return error.CapturePending;
if (self.capture_error) |err| return err;
if (self.png.len == 0) return error.CaptureScreenshotFirst;
}
for (&conn.snapshots, 1..) |*slot, handle| if (slot.* == null) {
- slot.* = switch (req.node) {
- 5 => try self.allocator.dupe(u8, self.png),
- 7 => try self.trace(host),
- 8 => try self.timingTrace(host),
- 9 => try self.presentationTrace(host),
- else => unreachable,
+ slot.* = switch (file) {
+ .@"screen.png" => try self.allocator.dupe(u8, self.png),
+ .@"profile-trace" => try self.trace(host),
+ .@"timing-trace" => try self.timingTrace(host),
+ .README, .commands => blk: {
+ var text: std.Io.Writer.Allocating = .init(self.allocator);
+ defer text.deinit();
+ const layout = if (self.offline) |o| o.layout else host.state.layout;
+ if (file == .README) try readme(layout, &text.writer) else try verbLines(&text.writer, "", if (self.offline) |o| o.completions else host.completions);
+ break :blk try text.toOwnedSlice();
+ },
+ else => try self.presentationTrace(host),
};
reply.handle = @intCast(handle);
return &.{};
@@ -166,12 +244,14 @@ pub const Control = struct {
slot.* = null;
},
.readdir => {
- if (req.node != 1) return error.NotDirectory;
+ if (file == .sketch) return &.{};
+ if (file != .@"/") return error.NotDirectory;
var used: usize = 0;
- for (names[1..], 0..) |name, index| {
+ for (std.enums.values(File)[1..], 0..) |f, index| {
if (index < req.off) continue;
- std.mem.writeInt(u64, buffer[used..][0..8], index + 2, .little);
- buffer[used + 8] = 0;
+ const name = @tagName(f);
+ std.mem.writeInt(u64, buffer[used..][0..8], @backingInt(f), .little);
+ buffer[used + 8] = @intFromBool(f == .state or f == .sketch);
buffer[used + 9] = @intCast(name.len);
@memcpy(buffer[used + 10 ..][0..name.len], name);
used += 10 + name.len;
@@ -180,21 +260,21 @@ pub const Control = struct {
},
.read => {
var writer: std.Io.Writer = .fixed(buffer);
- const bytes: []const u8 = switch (req.node) {
- 2 => "Write one console command per line. screenshot captures the next frame.\n",
- 3 => blk: {
+ const bytes: []const u8 = switch (file) {
+ .ctl => "Write a verb a line: commands lists them, README says what each does.\n",
+ .status => blk: {
try writer.print("name {s}\nsize {d} {d}\nmode {t}\ngpu {s}\nscreenshot_pending {}\nscreenshot_generation {d}\nscreenshot_error {s}\n", .{ host.name, host.canvas[0], host.canvas[1], host.timeline.mode, if (host.gpu != null) "yes" else "no", self.capture_pending, self.generation, if (self.capture_error) |err| @errorName(err) else "none" });
break :blk writer.buffered();
},
- 4 => blk: {
+ .log => blk: {
for (host.console.lines) |line| {
try writer.writeAll(line.bytes[0..line.len]);
try writer.writeByte('\n');
}
break :blk writer.buffered();
},
- 5, 7, 8, 9 => if (req.handle > 0 and req.handle <= conn.snapshots.len) conn.snapshots[req.handle - 1] orelse return error.InvalidHandle else return error.InvalidHandle,
- 6 => blk: {
+ .@"screen.png", .@"profile-trace", .@"timing-trace", .@"presentation-trace", .README, .commands => if (req.handle > 0 and req.handle <= conn.snapshots.len) conn.snapshots[req.handle - 1] orelse return error.InvalidHandle else return error.InvalidHandle,
+ .profile => blk: {
const gpu = if (host.passes) |*gpu| gpu else return error.ProfilingDisabled;
const profile = if (gpu.profile) |*profile| profile else return error.ProfilingDisabled;
try writer.print("# CPU wall milliseconds including GPU submission and fence wait; not hardware timestamps\n# frames {d}\nlabel\tcount\tmean_ms\tworst_ms\tp95_ms\tp99_ms\n", .{gpu.frame - profile.start_frame});
@@ -207,30 +287,41 @@ pub const Control = struct {
}
break :blk writer.buffered();
},
- else => return error.NotFile,
+ .@"/", .state, .sketch => return error.NotFile,
};
return window(bytes, req.off, req.size);
},
.write => {
- if (req.node != 2) return error.ReadOnly;
+ if (file != .ctl) return error.ReadOnly;
if (req.data.len > 4096 or std.mem.indexOfScalar(u8, req.data, 0) != null) return error.InvalidCommand;
var lines = std.mem.tokenizeScalar(u8, req.data, '\n');
while (lines.next()) |raw| {
const line = std.mem.trim(u8, raw, " \t\r");
- if (std.mem.eql(u8, line, "screenshot")) {
- self.capture_pending = true;
- self.capture_error = null;
- } else if (std.mem.eql(u8, line, "profile-reset")) {
- const gpu = if (host.passes) |*gpu| gpu else return error.ProfilingDisabled;
- const profile = if (gpu.profile) |*profile| profile else return error.ProfilingDisabled;
- for (profile.entries.values()) |*entry| entry.* = .{};
- profile.start_frame = gpu.frame;
- } else try host.runLine(line, c.SDL_GetTicksNS());
+ const verb = std.meta.stringToEnum(Verb, line) orelse {
+ var words = std.mem.tokenizeAny(u8, line, " \t");
+ const input = std.meta.stringToEnum(script.Verb, words.next() orelse "");
+ if (input != null and script.verbs.get(input.?).input) {
+ try script.input(host, input.?, &words, c.SDL_GetTicksNS());
+ } else try host.runLine(line, c.SDL_GetTicksNS());
+ continue;
+ };
+ switch (verb) {
+ .screenshot => {
+ self.capture_pending = true;
+ self.capture_error = null;
+ },
+ .@"profile-reset" => {
+ const gpu = if (host.passes) |*gpu| gpu else return error.ProfilingDisabled;
+ const profile = if (gpu.profile) |*profile| profile else return error.ProfilingDisabled;
+ for (profile.entries.values()) |*entry| entry.* = .{};
+ profile.start_frame = gpu.frame;
+ },
+ }
}
reply.written = @intCast(req.data.len);
},
.setattr => {
- if (req.node != 2 or !req.truncate) return error.ReadOnly;
+ if (file != .ctl or !req.truncate) return error.ReadOnly;
reply.attr = self.attr(req.node);
},
}
@@ -279,7 +370,8 @@ pub const Control = struct {
}
fn attr(self: *Control, node: u64) fs.Attr {
- return .{ .name = names[@intCast(node - 1)], .node = node, .dir = node == 1, .mode = if (node == 1) 0o700 else if (node == 2) 0o600 else 0o400, .size = if (node == 5) self.png.len else 0, .version = if (node == 5) @truncate(self.generation) else 0 };
+ const file: File = @fromBackingInt(@intCast(node));
+ return .{ .name = @tagName(file), .node = node, .dir = file == .@"/" or file == .state or file == .sketch, .mode = files.get(file).mode, .size = if (file == .@"screen.png") self.png.len else 0, .version = if (file == .@"screen.png") @truncate(self.generation) else 0 };
}
pub fn capture(self: *Control, surface: *c.SDL_Surface) void {
@@ -303,6 +395,111 @@ pub const Control = struct {
}
};
+/// The README: a line a file, ctl's verbs indented under it and the
+/// State's files under state/, in the shape cloud9's `help` reads.
+fn readme(layout: @import("memory.zig").Layout, w: *std.Io.Writer) !void {
+ for (std.enums.values(File)[1..]) |f| {
+ const name = @tagName(f);
+ const dir = f == .state or f == .sketch;
+ try w.print("{s}{s}", .{ name, if (dir) "/" else "" });
+ try w.splatByteAll(' ', @max(1, 41 -| (name.len + @intFromBool(dir))));
+ try w.print("{s}\n", .{files.get(f).doc});
+ if (f == .ctl) try verbLines(w, " ", &.{});
+ if (f == .state) try state_files.readme(layout, w);
+ }
+}
+
+/// A line a verb ctl takes: ctl's own, the input verbs, the console's,
+/// then `sketch`'s words.
+fn verbLines(w: *std.Io.Writer, indent: []const u8, sketch: []const []const u8) !void {
+ for (std.enums.values(Verb)) |v| try verbLine(w, indent, @tagName(v), "", verbs.get(v));
+ for (std.enums.values(script.Verb)) |v| if (script.verbs.get(v).input) try verbLine(w, indent, @tagName(v), script.verbs.get(v).args, script.verbs.get(v).doc);
+ for (std.enums.values(Console.Verb)) |v| try verbLine(w, indent, @tagName(v), Console.verbs.get(v).args, Console.verbs.get(v).doc);
+ for (sketch) |word| try w.print("{s}{s}\n", .{ indent, word });
+}
+
+fn verbLine(w: *std.Io.Writer, indent: []const u8, name: []const u8, args: []const u8, doc: []const u8) !void {
+ try w.print("{s}{s}{s}{s}", .{ indent, name, if (args.len > 0) " " else "", args });
+ try w.splatByteAll(' ', @max(1, 37 -| (name.len + args.len + @intFromBool(args.len > 0))));
+ try w.print("{s}\n", .{doc});
+}
+
+/// Under `state/`: the live State as files (state_files.zig), a write
+/// run as the console's `set`.
+fn stateRespond(self: *Control, host: *Host, conn: *Connection, req: fs.Req, reply: *fs.Reply, buffer: []u8) ![]const u8 {
+ const layout = if (self.offline) |o| o.layout else host.state.layout;
+ const node: state_files.Node = @bitCast(req.node);
+ if (!state_files.valid(layout, node)) return error.StateLayoutChangedWalkAgain;
+ const dir = state_files.isDir(layout, node);
+ const mode: u16 = if (dir) 0o700 else if (state_files.writable(layout, node)) 0o600 else 0o400;
+ switch (req.op) {
+ .lookup => {
+ if (!dir) return error.NotDirectory;
+ const child = state_files.lookup(layout, node, req.data) orelse return error.UnknownField;
+ const child_dir = state_files.isDir(layout, child);
+ reply.attr = .{ .node = @bitCast(child), .dir = child_dir, .mode = if (child_dir) 0o700 else if (state_files.writable(layout, child)) 0o600 else 0o400 };
+ },
+ .getattr => reply.attr = .{ .node = req.node, .dir = dir, .mode = mode },
+ .setattr => {
+ if (mode != 0o600 or !req.truncate) return error.ReadOnly;
+ reply.attr = .{ .node = req.node, .mode = mode };
+ },
+ // A value is read as it was at the open: it changes every frame,
+ // and its length with it.
+ .open => if (!dir) for (&conn.snapshots, 1..) |*slot, handle| if (slot.* == null) {
+ var text: std.Io.Writer.Allocating = .init(self.allocator);
+ defer text.deinit();
+ try state_files.read(layout, if (self.offline) |o| o.bytes else host.live(), node, &text.writer);
+ slot.* = try text.toOwnedSlice();
+ reply.handle = @intCast(handle);
+ break;
+ } else return error.TooManySnapshots,
+ .release => if (req.opened and req.handle > 0 and req.handle <= conn.snapshots.len) {
+ const slot = &conn.snapshots[req.handle - 1];
+ if (slot.*) |bytes| self.allocator.free(bytes);
+ slot.* = null;
+ },
+ .readdir => {
+ if (!dir) return error.NotDirectory;
+ return buffer[0..state_files.readdir(layout, node, req.off, buffer)];
+ },
+ .read => {
+ if (dir) return error.NotFile;
+ const bytes = if (req.handle > 0 and req.handle <= conn.snapshots.len) conn.snapshots[req.handle - 1] orelse return error.InvalidHandle else return error.InvalidHandle;
+ return window(bytes, req.off, req.size);
+ },
+ .write => {
+ if (mode != 0o600) return error.ReadOnly;
+ if (self.offline != null) return error.SketchNotRunning;
+ var w: std.Io.Writer = .fixed(buffer);
+ w.writeAll("set ") catch unreachable;
+ state_files.path(layout, node, &w) catch return error.ValueTooLong;
+ w.writeByte(' ') catch return error.ValueTooLong;
+ for (std.mem.trim(u8, req.data, " \t\r\n")) |byte| w.writeByte(if (byte == '\n') ' ' else byte) catch return error.ValueTooLong;
+ try host.runLine(w.buffered(), c.SDL_GetTicksNS());
+ reply.written = @intCast(req.data.len);
+ },
+ }
+ return &.{};
+}
+
+/// The State `fs` shows with no sketch running, and its words for what a
+/// running one would answer.
+pub const Offline = struct {
+ layout: @import("memory.zig").Layout,
+ bytes: []const u8,
+ completions: []const []const u8,
+ /// "drat-meout is not running: ..."
+ from: []const u8,
+};
+
+/// `$XDG_RUNTIME_DIR/9p/sketchbook/<name>`, where a sketch posts its tree.
+pub fn registered(environ: *const std.process.Environ.Map, name: []const u8, buf: []u8) ![:0]u8 {
+ if (!c9.post.legalName(name)) return error.IllegalName;
+ const runtime = environ.get("XDG_RUNTIME_DIR") orelse return error.NotRuntimeDir;
+ return std.fmt.bufPrintSentinel(buf, "{s}/9p/sketchbook/{s}", .{ runtime, name }, 0) catch error.NameTooLong;
+}
+
fn window(bytes: []const u8, offset: u64, count: u32) []const u8 {
if (offset >= bytes.len) return &.{};
const start: usize = @intCast(offset);
@@ -452,3 +649,59 @@ test "control writes reject presentation trace mutations and opens own independe
_ = try control.respond(&host, &conn, .{ .tag = 1, .op = .release, .node = 9, .handle = second, .opened = true }, &reply, &buf);
try std.testing.expect(conn.snapshots[first - 1] == null and conn.snapshots[second - 1] == null);
}
+
+test "control writes take input verbs live, and the README and commands read the tables" {
+ const a = std.testing.allocator;
+ var control: Control = .{ .allocator = a, .path = undefined, .listener = -1 };
+ var host: Host = undefined;
+ host.gpa = a;
+ host.console = .{};
+ host.input = .{};
+ host.pending = .empty;
+ defer host.pending.deinit(a);
+ const S = struct { scene: enum(u8) { room, street } = .room, talk: struct { text: [3]u8 = @splat(0) } = .{} };
+ var arena: std.heap.ArenaAllocator = .init(a);
+ defer arena.deinit();
+ host.state.layout = try @import("memory.zig").Layout.copy(arena.allocator(), @import("abi").layout.of(S, .state));
+ host.completions = &.{ "scene room", "scene street" };
+ var conn: Connection = .{};
+ var reply: fs.Reply = .{ .tag = 1 };
+ var buf: [512]u8 = undefined;
+ _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .write, .node = 2, .data = "click 10 20\nhold left_shift\n" }, &reply, &buf);
+ try std.testing.expectEqual(@as(usize, 4), host.pending.items.len);
+ try std.testing.expectEqual(abi.Event.Kind.mouse_up, host.pending.items[2].kind);
+ try std.testing.expectEqual(@as(f32, 20), host.pending.items[2].y);
+ try std.testing.expectEqual(abi.Event.Kind.key_down, host.pending.items[3].kind);
+ try std.testing.expectError(error.ExpectedPoint, control.respond(&host, &conn, .{ .tag = 1, .op = .write, .node = 2, .data = "click 10" }, &reply, &buf));
+ for ([_]File{ .README, .commands }) |f| {
+ _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .open, .node = @backingInt(f) }, &reply, &buf);
+ const handle = reply.handle;
+ const text = conn.snapshots[handle - 1].?;
+ if (f == .README) {
+ try std.testing.expect(std.mem.startsWith(u8, text, "ctl write a verb a line"));
+ try std.testing.expect(std.mem.indexOf(u8, text, "\n screenshot captures the next frame") != null);
+ try std.testing.expect(std.mem.indexOf(u8, text, "\n click X Y move there") != null);
+ try std.testing.expect(std.mem.indexOf(u8, text, "\n set FIELD VALUE... a field to a value") != null);
+ try std.testing.expect(std.mem.indexOf(u8, text, "\nstate/ the sketch's State") != null);
+ try std.testing.expect(std.mem.indexOf(u8, text, "\nsketch/ the sketch's own files") != null);
+ try std.testing.expect(std.mem.endsWith(u8, text, "\nstate/scene .room .street\nstate/talk/text 3 u8, blank-separated\n"));
+ } else {
+ try std.testing.expect(std.mem.startsWith(u8, text, "screenshot captures"));
+ try std.testing.expect(std.mem.endsWith(u8, text, "\nscene room\nscene street\n"));
+ }
+ _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .release, .node = @backingInt(f), .handle = handle, .opened = true }, &reply, &buf);
+ }
+}
+
+test "control writes leave the sketch's directory and nodes alone" {
+ var control: Control = .{ .allocator = std.testing.allocator, .path = undefined, .listener = -1 };
+ var host: Host = undefined;
+ var conn: Connection = .{};
+ var reply: fs.Reply = .{ .tag = 1 };
+ var buf: [256]u8 = undefined;
+ _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .lookup, .node = 1, .data = "sketch" }, &reply, &buf);
+ try std.testing.expect(reply.attr.dir and reply.attr.node == 1 << 63);
+ try std.testing.expectEqual(@as(usize, 0), (try control.respond(&host, &conn, .{ .tag = 1, .op = .readdir, .node = 1 << 63 }, &reply, &buf)).len);
+ try std.testing.expectError(error.UnknownFile, control.respond(&host, &conn, .{ .tag = 1, .op = .lookup, .node = 1 << 63, .data = "buffer" }, &reply, &buf));
+ for ([_]u64{ (1 << 63) + 1, (1 << 63) | (1 << 62), std.math.maxInt(u64) }) |node| try std.testing.expectError(error.UnknownFile, control.respond(&host, &conn, .{ .tag = 1, .op = .getattr, .node = node }, &reply, &buf));
+}
diff --git a/src/host/fields.zig b/src/host/fields.zig
index 2e70414..fc1a1e7 100644
--- a/src/host/fields.zig
+++ b/src/host/fields.zig
@@ -123,6 +123,25 @@ pub fn set(leaf: Leaf, memory: []u8, text: []const u8) !void {
}
}
+/// Sets every value of the row of scalars `path` names (an array of
+/// numbers, a vector, `grid[1]` of a `grid: [3][2]u16`), in memory order,
+/// from `text`'s words, one each; nothing when one is not a value.
+pub fn setRow(layout: Layout, memory: []u8, path: []const u8, text: []const u8) !void {
+ for (layout.fields) |leaf| {
+ if (leaf.whole() or !std.mem.endsWith(u8, leaf.path, "[]")) continue;
+ const at = abi.layout.match(leaf.path[0 .. leaf.path.len - 2], leaf.dims[0 .. leaf.dims.len - 1], path) orelse continue;
+ const d = leaf.dims[leaf.dims.len - 1];
+ var scratch: [16]u8 = undefined;
+ var words = std.mem.tokenizeAny(u8, text, " \t\n");
+ for (0..d.count) |_| try set(leaf.at(0), &scratch, words.next() orelse return error.TooFewValues);
+ if (words.next() != null) return error.TooManyValues;
+ words.reset();
+ for (0..d.count) |i| try set(leaf.at(leaf.offset + at + i * d.stride), memory, words.next().?);
+ return;
+ }
+ return error.UnsupportedField;
+}
+
/// True when the field's formatted value equals `text` (enum names compare
/// with or without the leading dot).
pub fn matches(leaf: Leaf, memory: []const u8, text: []const u8) bool {
@@ -206,6 +225,24 @@ test "fields format, parse and compare by kind" {
try std.testing.expectError(error.InvalidValue, set(layout.find("x").?, bytes, "banana"));
}
+test "a row of scalars is set from its words, all or none" {
+ const S = struct { grid: [3][2]i16 = @splat(@splat(0)), pos: @Vector(2, f32) = .{ 0, 0 } };
+ var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
+ defer arena.deinit();
+ const layout = try Layout.copy(arena.allocator(), abi.layout.of(S, .state));
+ var s: S = .{};
+ const bytes = std.mem.asBytes(&s);
+ try setRow(layout, bytes, "grid[1]", "4 -5");
+ try std.testing.expectEqual([2]i16{ 4, -5 }, s.grid[1]);
+ try setRow(layout, bytes, "pos", "1.5\n2");
+ try std.testing.expectEqual(@as(f32, 2), s.pos[1]);
+ try std.testing.expectError(error.TooFewValues, setRow(layout, bytes, "grid[2]", "7"));
+ try std.testing.expectError(error.TooManyValues, setRow(layout, bytes, "grid[2]", "7 8 9"));
+ try std.testing.expectError(error.InvalidValue, setRow(layout, bytes, "grid[2]", "7 x"));
+ try std.testing.expectEqual([2]i16{ 0, 0 }, s.grid[2]);
+ try std.testing.expectError(error.UnsupportedField, setRow(layout, bytes, "grid", "1 2"));
+}
+
test "indexed paths reach array elements and vector lanes" {
const S = struct { pos: @Vector(2, f32) = .{ 250, 3 }, boids: struct { buffer: [4]struct { pos: [2]f32 = .{ 0, 0 }, mood: enum(u8) { calm = 1, wild = 2 } = .calm } = @splat(.{}), len: u32 = 0 } = .{} };
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
diff --git a/src/host/library.zig b/src/host/library.zig
index 6958eec..6619d5b 100644
--- a/src/host/library.zig
+++ b/src/host/library.zig
@@ -1,9 +1,13 @@
//! Loading sketch libraries, and noticing when a build replaces one.
//!
//! `dlopen` returns the handle it already has for a path it loaded before, so
-//! every load goes through a private copy with a fresh name. The copy is
-//! deleted right after loading: the mapping keeps the code alive, and nothing
-//! is left behind if the host dies.
+//! every load goes through a symlink with a fresh name to an fd open on the
+//! library: what loads is the file that was opened, whatever a build renames
+//! over it meanwhile. Link and fd live as long as the library is loaded: the
+//! name dlopen was given is where a panic's trace reads the sketch's debug
+//! info, so a host that dies leaves its dangling links behind. A library
+//! rewritten in place instead (same inode) would not load again, and would
+//! change the code under the running host.
const std = @import("std");
const linux = std.os.linux;
const c = @import("c");
@@ -12,8 +16,14 @@ const abi = @import("abi");
pub const Library = struct {
object: *c.SDL_SharedObject,
sketch: abi.Sketch,
+ /// What the link names (the library, or its fixed copy) and where the
+ /// link is, for `openFresh`'s libraries; -1 for `open`'s.
+ fd: i32 = -1,
+ scratch_dir: []const u8 = "",
+ serial: usize = 0,
- pub fn open(path: [:0]const u8) !Library {
+ /// Loads the library at `path`; `source` names it in messages.
+ pub fn open(path: [:0]const u8, source: []const u8) !Library {
const object = c.SDL_LoadObject(path.ptr) orelse return error.LoadLibrary;
errdefer c.SDL_UnloadObject(object);
var sketch: abi.Sketch = undefined;
@@ -22,25 +32,109 @@ pub const Library = struct {
const address = c.SDL_LoadFunction(object, symbol) orelse return error.MissingEntryPoint;
@field(sketch, name) = @ptrCast(address);
}
- if (sketch.info().abi != abi.hash) return error.AbiMismatch;
+ if (sketch.info().abi != abi.hash) {
+ const address = c.SDL_LoadFunction(object, "sketch_build") orelse {
+ std.log.err("{s}: built by an older sketchbook: rebuild it", .{source});
+ return error.AbiMismatch;
+ };
+ const build = std.mem.span(@as([*:0]const u8, @ptrFromInt(@intFromPtr(address))));
+ if (std.mem.eql(u8, build, abi.build)) {
+ std.log.err("{s}: built against other abi types: restart the host to load it", .{source});
+ } else {
+ const mode = build[std.mem.lastIndexOfScalar(u8, build, ' ').? + 1 ..];
+ std.log.err("{s}: built by zig {s}, this host by zig {s}; Zig calls cross the boundary, so both need the same compiler, backend and mode: build the host like the library (`zig build run -Doptimize={s}`) or the library like the host", .{ source, build, abi.build, mode });
+ }
+ return error.AbiMismatch;
+ }
return .{ .object = object, .sketch = sketch };
}
- /// Loads `source` through a uniquely named copy in `scratch_dir`.
- pub fn openCopy(io: std.Io, source: []const u8, scratch_dir: []const u8, serial: usize) !Library {
- var buf: [std.fs.max_path_bytes]u8 = undefined;
- const copy = try std.mem.printSentinel(&buf, "{s}/sketchbook-{d}-{d}.so", .{ scratch_dir, linux.getpid(), serial }, 0);
+ /// Loads `source` through a uniquely named symlink in `scratch_dir`.
+ pub fn openFresh(io: std.Io, source: []const u8, scratch_dir: []const u8, serial: usize) !Library {
const cwd = std.Io.Dir.cwd();
- try cwd.copyFile(source, cwd, copy, io, .{});
- defer cwd.deleteFile(io, copy) catch {};
- return open(copy);
+ const file = try cwd.openFile(io, source, .{});
+ const fixed = withoutVersym(file.handle) catch |err| {
+ file.close(io);
+ return err;
+ };
+ if (fixed != null) file.close(io);
+ const fd = fixed orelse file.handle;
+ errdefer _ = linux.close(fd);
+ var target_buf: [32]u8 = undefined;
+ const target = try std.mem.print(&target_buf, "/proc/self/fd/{d}", .{fd});
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const link = try linkName(&buf, scratch_dir, serial);
+ try cwd.symLink(io, target, link, .{});
+ errdefer cwd.deleteFile(io, link) catch {};
+ var library = try open(link, source);
+ library.fd = fd;
+ library.scratch_dir = scratch_dir;
+ library.serial = serial;
+ return library;
}
pub fn close(self: *Library) void {
c.SDL_UnloadObject(self.object);
+ if (self.fd < 0) return;
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ _ = linux.unlink(linkName(&buf, self.scratch_dir, self.serial) catch unreachable);
+ _ = linux.close(self.fd);
+ }
+
+ fn linkName(buf: []u8, scratch_dir: []const u8, serial: usize) ![:0]u8 {
+ return std.mem.printSentinel(buf, "{s}/sketchbook-{d}-{d}.so", .{ scratch_dir, linux.getpid(), serial }, 0);
}
};
+// ponytail: Zig 0.17.1's new ELF linker (which `-fincremental` selects)
+// writes DT_VERSYM without DT_VERDEF or DT_VERNEED when nothing is
+// versioned, and glibc's dlopen then reads a null version table and
+// faults. Such a library has nothing versioned, so a copy without
+// DT_VERSYM, in an anonymous memory file, loads instead (the build's own
+// file is never written: the watch would see the write). Never fires on a
+// correct library; dead once Zig has commit 6d27011edb (0.18): delete it.
+fn withoutVersym(fd: i32) !?i32 {
+ const elf = std.elf;
+ var ehdr: elf.Elf64.Ehdr = undefined;
+ try pread(fd, std.mem.asBytes(&ehdr), 0);
+ if (!std.mem.eql(u8, &ehdr.ident.magic, elf.MAGIC) or ehdr.ident.class != .@"64" or ehdr.phnum > 32) return null;
+ var phdrs: [32]elf.Elf64.Phdr = undefined;
+ try pread(fd, std.mem.sliceAsBytes(phdrs[0..ehdr.phnum]), ehdr.phoff);
+ for (phdrs[0..ehdr.phnum]) |ph| {
+ if (ph.type != .DYNAMIC) continue;
+ var dyn: [64]elf.Elf64_Dyn = undefined;
+ const len = @min(dyn.len, ph.filesz / @sizeOf(elf.Elf64_Dyn));
+ try pread(fd, std.mem.sliceAsBytes(dyn[0..len]), ph.offset);
+ var versym: ?usize = null;
+ var end: usize = 0;
+ while (end < len and dyn[end].d_tag != elf.DT_NULL) : (end += 1) switch (dyn[end].d_tag) {
+ elf.DT_VERSYM => versym = end,
+ elf.DT_VERDEF, elf.DT_VERNEED => return null,
+ else => {},
+ };
+ const at = versym orelse return null;
+ if (end == len) return null;
+ const copy: i32 = @intCast(@as(isize, @bitCast(linux.memfd_create("sketchbook", linux.MFD.CLOEXEC))));
+ if (copy < 0) return error.MemfdFailed;
+ errdefer _ = linux.close(copy);
+ var offset: i64 = 0;
+ while (true) {
+ const rc = linux.sendfile(copy, fd, &offset, 1 << 30);
+ if (linux.errno(rc) != .SUCCESS) return error.CopyFailed;
+ if (rc == 0) break;
+ }
+ std.mem.copyForwards(elf.Elf64_Dyn, dyn[at..end], dyn[at + 1 .. end + 1]);
+ const bytes = std.mem.sliceAsBytes(dyn[at..end]);
+ if (linux.pwrite(copy, bytes.ptr, bytes.len, @intCast(ph.offset + at * @sizeOf(elf.Elf64_Dyn))) != bytes.len) return error.WriteFailed;
+ return copy;
+ }
+ return null;
+}
+
+fn pread(fd: i32, buf: []u8, offset: u64) !void {
+ if (linux.pread(fd, buf.ptr, buf.len, @intCast(offset)) != buf.len) return error.ShortRead;
+}
+
/// inotify on a library's directory, filtered to its file name. Builds
/// replace files by renaming (`MOVED_TO`) or rewrite them (`CLOSE_WRITE`).
pub const Watch = struct {
diff --git a/src/host/memory.zig b/src/host/memory.zig
index 5fbb88f..2749ea1 100644
--- a/src/host/memory.zig
+++ b/src/host/memory.zig
@@ -1,13 +1,12 @@
//! Sketch memory by lifetime.
//!
-//! `StateFile`: one `MAP_SHARED` file holding the live state and its snapshot
-//! slots, plus a header describing the layout, so the state outlives restarts,
-//! a probe can read it from another process, and a reload with a changed
-//! layout can carry the old values over field by field.
+//! `State`: process memory in the layout the sketch declares; a reload
+//! with a changed layout carries the old values over field by field. It
+//! outlives the process in the sessions database (Sessions.zig), whose
+//! stretches keep its layout in the header format below.
//!
-//! `StoreFile`: a heap in a file, mapped at the same address in every run,
-//! so what it holds may point into it: the sketch's `Store` and everything
-//! allocated for it outlive restarts.
+//! `OldState`: a state file from before the database held the present,
+//! read once to import it.
//!
//! `Session`: this process's memory, kept across reloads.
const std = @import("std");
@@ -17,13 +16,16 @@ const abi = @import("abi");
const field_value = @import("fields.zig");
pub const page = std.heap.page_size_min;
-/// Slot 0 is live; 1..7 are snapshots.
-pub const slot_count = 8;
pub const header_len = 64 * 1024;
-/// Layouts with element leaves (`list[].x`, `StoredField` with `dims`).
-pub const file_magic = "SKETCH02".*;
+/// A layout header, and an old file's one slot, the live state.
+pub const file_magic = "SKETCH03".*;
+/// Before sessions: slot 0 live and 1..7 snapshots (`old_slot_count`), which
+/// the host imports as marks and then drops (`dropSnapshots`).
+pub const file_magic_v2 = "SKETCH02".*;
+pub const old_slot_count = 8;
/// What hosts before element leaves wrote: arrays are whole leaves
-/// (`StoredFieldV1`). Read, and rewritten as `file_magic` on adopt.
+/// (`StoredFieldV1`), and eight slots. Read, and rewritten as
+/// `file_magic_v2` on adopt.
pub const file_magic_v1 = "SKETCH01".*;
pub const Header = extern struct {
@@ -31,7 +33,8 @@ pub const Header = extern struct {
size: u64,
alignment: u64,
hash: u64,
- /// Distance between slots, page aligned.
+ /// The slot's size, page aligned (and the distance between an old
+ /// file's slots).
stride: u64,
/// Bit `i`: slot `i` holds state.
used: u32,
@@ -260,9 +263,14 @@ pub const Diff = struct {
/// Compares two copies of state leaf by leaf, so padding (a Debug
/// `@Vector`'s spare lane, the gaps between fields) never differs.
pub fn compare(layout: Layout, a: []const u8, b: []const u8) Diff {
+ return compareKept(layout, layout, a, b);
+}
+
+/// `compare` over the leaves `migrate` from `from` keeps (`keeps`).
+pub fn compareKept(from: Layout, layout: Layout, a: []const u8, b: []const u8) Diff {
var diff: Diff = .{};
for (layout.fields) |leaf| {
- if (leaf.whole()) continue;
+ if (leaf.whole() or (from.hash != layout.hash and !keeps(from, leaf))) continue;
var it = leaf.elements();
while (it.next()) |offset| {
if (std.mem.eql(u8, a[offset..][0..leaf.size], b[offset..][0..leaf.size])) continue;
@@ -282,141 +290,120 @@ fn remapEnum(from: Layout.Leaf, old: []const u8, to: Layout.Leaf, new: []u8) boo
return true;
}
-pub const StateFile = struct {
- fd: posix.fd_t,
- map: []align(page) u8,
- /// Layout of the bytes in the file, owned by `arena`.
- layout: Layout,
+/// Live State: page aligned, in the running sketch's layout; `header` is
+/// that layout as `layoutOf` reads it back, for the sessions' stretches.
+pub const State = struct {
+ bytes: []align(page) u8 = &.{},
+ layout: Layout = .{},
+ header: []const u8 = "",
+ /// Owns `layout` and `header`.
arena: std.heap.ArenaAllocator,
- /// Opens or creates `path`. A new (empty) file has no layout and no used
- /// slots: the first `adopt` fills it. A file that is not a state file
- /// this host can read is refused, never truncated: it may be someone's
- /// work, written by another build.
- pub fn open(gpa: std.mem.Allocator, path: []const u8) !StateFile {
- const fd = try posix.openat(posix.AT.FDCWD, path, .{ .ACCMODE = .RDWR, .CREAT = true }, 0o600);
- errdefer _ = posix.system.close(fd);
- var self: StateFile = .{ .fd = fd, .map = &.{}, .layout = .{}, .arena = .init(gpa) };
- errdefer self.arena.deinit();
- const len = try fileSize(fd);
- if (len > 0) {
- if (len < header_len) return error.NotAStateFile;
- self.map = try mapFile(fd, @intCast(len), .{ .READ = true, .WRITE = true });
- errdefer posix.munmap(self.map);
- try self.check();
- self.layout = try readLayout(self.arena.allocator(), self.map) orelse .{};
- return self;
- }
- try self.resize(0);
- self.header().* = .{ .size = 0, .alignment = 1, .hash = 0, .stride = 0, .used = 0, .field_count = 0, .strings_len = 0 };
- return self;
+ pub fn init(gpa: std.mem.Allocator) State {
+ return .{ .arena = .init(gpa) };
}
- pub fn close(self: *StateFile) void {
- if (self.map.len != 0) posix.munmap(self.map);
- _ = posix.system.close(self.fd);
+ pub fn deinit(self: *State, gpa: std.mem.Allocator) void {
+ gpa.free(self.bytes);
self.arena.deinit();
}
- pub fn header(self: *StateFile) *Header {
- return @ptrCast(self.map.ptr);
+ pub fn live(self: *State) []align(page) u8 {
+ return self.bytes[0..self.layout.size];
}
- pub fn slot(self: *StateFile, index: usize) []align(page) u8 {
- std.debug.assert(index < slot_count);
- const h = self.header();
- const start = header_len + index * h.stride;
- return @alignCast(self.map[start..][0..h.size]);
+ /// Makes State hold `new`'s layout: a new allocation of its defaults
+ /// (`defaults`), then every leaf `migrate` keeps of the old State. Null
+ /// when the layout is unchanged, or there was none.
+ pub fn adopt(self: *State, gpa: std.mem.Allocator, new: abi.Layout, defaults: *const fn (abi.Memory, [*]u8) callconv(.c) void) !?Migration {
+ const first = self.bytes.len == 0;
+ if (!first and self.layout.hash == new.hash and self.layout.size == new.size) return null;
+ var arena: std.heap.ArenaAllocator = .init(gpa);
+ errdefer arena.deinit();
+ const layout = try Layout.copy(arena.allocator(), new);
+ const region = try arena.allocator().alignedAlloc(u8, .of(Header), header_len);
+ @memset(region, 0);
+ const h: *Header = @ptrCast(region.ptr);
+ h.* = .{ .size = new.size, .alignment = new.alignment, .hash = new.hash, .stride = std.mem.alignForward(usize, @max(new.size, 1), page), .used = 1, .field_count = 0, .strings_len = 0 };
+ try writeLayout(region, layout);
+ const bytes = try gpa.alignedAlloc(u8, .fromByteUnits(page), @max(new.size, 1));
+ @memset(bytes, 0);
+ defaults(.state, bytes.ptr);
+ const m = if (first) null else migrate(self.layout, self.live(), layout, bytes);
+ self.deinit(gpa);
+ self.* = .{ .bytes = bytes, .layout = layout, .header = region[0 .. @sizeOf(Header) + @as(usize, h.field_count) * @sizeOf(StoredField) + h.strings_len], .arena = arena };
+ return m;
}
+};
- pub fn used(self: *StateFile, index: usize) bool {
- return self.header().used & (@as(u32, 1) << @intCast(index)) != 0;
- }
+/// A state file from before the sessions database held the present: a
+/// layout header, then one slot (`file_magic`), or eight (`file_magic_v2`,
+/// `file_magic_v1`), the first live State and the others snapshots. Mapped
+/// read-only: imported once, never changed.
+pub const OldState = struct {
+ map: []align(page) const u8,
+ slots: usize,
- pub fn markUsed(self: *StateFile, index: usize, value: bool) void {
- const bit = @as(u32, 1) << @intCast(index);
- if (value) self.header().used |= bit else self.header().used &= ~bit;
+ /// error.FileNotFound when `path` is missing or empty; a file that is
+ /// no state file this host reads is refused.
+ pub fn open(path: []const u8) !OldState {
+ const map = mapReadOnly(path);
+ if (map.len == 0) return error.FileNotFound;
+ errdefer posix.munmap(map);
+ if (map.len < header_len) return error.NotAStateFile;
+ const h: *const Header = @ptrCast(map.ptr);
+ const slots: usize = if (std.mem.eql(u8, &h.magic, &file_magic)) 1 else if (std.mem.eql(u8, &h.magic, &file_magic_v2) or std.mem.eql(u8, &h.magic, &file_magic_v1)) old_slot_count else return error.NotAStateFile;
+ if (map.len < header_len + slots * h.stride or h.size > h.stride) return error.CorruptStateFile;
+ return .{ .map = map, .slots = slots };
}
- pub const Adoption = union(enum) {
- unchanged,
- created,
- migrated: Migration,
- };
-
- /// Makes the file hold `new`'s layout. Used slots are migrated: `defaults`
- /// writes the new default values, then unchanged fields are copied over.
- pub fn adopt(self: *StateFile, gpa: std.mem.Allocator, new: abi.Layout, defaults: *const fn (abi.Memory, [*]u8) callconv(.c) void) !Adoption {
- if (self.layout.hash == new.hash and self.layout.size == new.size and self.header().used & 1 != 0) {
- // Same type, older header: describe it again, bytes untouched.
- if (std.mem.eql(u8, &self.header().magic, &file_magic_v1)) {
- var kept = self.arena;
- defer kept.deinit();
- self.arena = .init(gpa);
- self.layout = try Layout.copy(self.arena.allocator(), new);
- try writeLayout(self.map[0..header_len], self.layout);
- self.header().magic = file_magic;
- }
- return .unchanged;
- }
- const had_state = self.header().used & 1 != 0;
-
- // Keep the old bytes and layout while the file is rebuilt.
- var old_arena: std.heap.ArenaAllocator = .init(gpa);
- defer old_arena.deinit();
- const old_layout = self.layout;
- var old_slots: [slot_count]?[]u8 = @splat(null);
- for (&old_slots, 0..) |*copy, i| {
- if (self.used(i)) copy.* = try old_arena.allocator().dupe(u8, self.slot(i));
- }
- const old_used = self.header().used;
- // `old_layout` points into `self.arena`: move it aside before resetting.
- var kept = self.arena;
- defer kept.deinit();
- self.arena = .init(gpa);
-
- self.layout = try Layout.copy(self.arena.allocator(), new);
- const stride = std.mem.alignForward(usize, @max(new.size, 1), page);
- try self.resize(stride);
- const h = self.header();
- h.* = .{ .magic = file_magic, .size = new.size, .alignment = new.alignment, .hash = new.hash, .stride = stride, .used = old_used, .field_count = 0, .strings_len = 0 };
- try writeLayout(self.map[0..header_len], self.layout);
-
- var total: Migration = .{};
- for (old_slots, 0..) |maybe_old, i| {
- const old = maybe_old orelse continue;
- const bytes = self.slot(i);
- @memset(bytes, 0);
- defaults(.state, bytes.ptr);
- const m = migrate(old_layout, old, self.layout, bytes);
- total.kept += m.kept;
- if (i == 0) total.reset = m.reset;
- }
- if (!had_state) {
- self.markUsed(0, false);
- return .created;
- }
- return .{ .migrated = total };
+ pub fn close(self: OldState) void {
+ posix.munmap(self.map);
}
- fn check(self: *StateFile) !void {
- const h = self.header();
- if (!std.mem.eql(u8, &h.magic, &file_magic) and !std.mem.eql(u8, &h.magic, &file_magic_v1)) return error.NotAStateFile;
- if (self.map.len < header_len + slot_count * h.stride or h.size > h.stride) return error.CorruptStateFile;
+ /// The header and layout, as `restore` and `layoutOf` take them.
+ pub fn layoutBytes(self: OldState) []const u8 {
+ return self.map[0..header_len];
}
- fn resize(self: *StateFile, stride: usize) !void {
- const len = header_len + slot_count * stride;
- if (self.map.len != 0) posix.munmap(self.map);
- self.map = &.{};
- switch (posix.errno(posix.system.ftruncate(self.fd, @intCast(len)))) {
- .SUCCESS => {},
- else => |err| return posix.unexpectedErrno(err),
- }
- self.map = try mapFile(self.fd, len, .{ .READ = true, .WRITE = true });
+ /// Slot `i`'s State, null when the slot is unused.
+ pub fn slot(self: OldState, i: usize) ?[]const u8 {
+ const h: *const Header = @ptrCast(self.map.ptr);
+ if (h.used & (@as(u32, 1) << @intCast(i)) == 0) return null;
+ return self.map[header_len + i * h.stride ..][0..h.size];
}
};
+/// Fills `live` (laid out as `to`) from `image`, state kept in another
+/// layout, described by `layout_bytes` (a header as `State.header` holds
+/// it): `defaults`, then every leaf `migrate` keeps. Returns the
+/// image's layout, `arena`'s.
+pub fn restore(arena: std.mem.Allocator, layout_bytes: []const u8, image: []const u8, to: Layout, live: []u8, defaults: *const fn (abi.Memory, [*]u8) callconv(.c) void) !Layout {
+ const from = try layoutOf(arena, layout_bytes);
+ if (image.len != from.size) return error.CorruptKeyframe;
+ @memset(live, 0);
+ defaults(.state, live.ptr);
+ _ = migrate(from, image, to, live);
+ return from;
+}
+
+/// The layout in a header as `State.header` holds it, `arena`'s.
+pub fn layoutOf(arena: std.mem.Allocator, layout_bytes: []const u8) !Layout {
+ if (layout_bytes.len < @sizeOf(Header) or layout_bytes.len > header_len) return error.CorruptKeyframe;
+ const region = try arena.alignedAlloc(u8, .of(Header), header_len);
+ @memset(region, 0);
+ @memcpy(region[0..layout_bytes.len], layout_bytes);
+ return try readLayout(arena, region) orelse .{};
+}
+
+/// Whether `migrate` from `from` keeps `leaf`'s value: compared on these
+/// only, state restored across a layout change differs nowhere it was reset.
+pub fn keeps(from: Layout, leaf: Layout.Leaf) bool {
+ const before = from.pattern(leaf.path) orelse return false;
+ if (before.dims.len != leaf.dims.len) return false;
+ return (before.hash == leaf.hash and before.size == leaf.size) or (before.kind == .@"enum" and leaf.kind == .@"enum");
+}
+
/// Writes `layout`'s leaves after the `Header` at the start of `region`,
/// in the current format (`StoredField`); the caller sets the magic.
fn writeLayout(region: []u8, layout: Layout) !void {
@@ -453,14 +440,14 @@ fn writeLayout(region: []u8, layout: Layout) !void {
h.strings_len = @intCast(strings);
}
-/// The layout stored in a state or store file's header, or null if it has
-/// none. Reads both formats, by magic: a v1 header (`file_magic_v1`,
-/// `store_layout_magic_v1`) has no element leaves, so its arrays are whole
-/// leaves only, which migrate while their type is unchanged.
+/// The layout stored in a state file's header, or null if it has none.
+/// Reads both formats, by magic: a v1 header (`file_magic_v1`) has no
+/// element leaves, so its arrays are whole leaves only, which migrate while
+/// their type is unchanged.
pub fn readLayout(arena: std.mem.Allocator, map: []const u8) !?Layout {
const h: *const Header = @ptrCast(@alignCast(map.ptr));
if (h.hash == 0 and h.field_count == 0) return null;
- const v1 = std.mem.eql(u8, &h.magic, &file_magic_v1) or std.mem.eql(u8, &h.magic, &store_layout_magic_v1);
+ const v1 = std.mem.eql(u8, &h.magic, &file_magic_v1);
const stride: usize = if (v1) @sizeOf(StoredFieldV1) else @sizeOf(StoredField);
const strings_start = @sizeOf(Header) + @as(usize, h.field_count) * stride;
if (strings_start + h.strings_len > header_len or map.len < header_len) return error.CorruptHeader;
@@ -498,10 +485,6 @@ pub fn readLayout(arena: std.mem.Allocator, map: []const u8) !?Layout {
return .{ .size = h.size, .alignment = h.alignment, .hash = h.hash, .fields = leaves };
}
-pub fn mapFile(fd: posix.fd_t, len: usize, prot: posix.PROT) ![]align(page) u8 {
- return posix.mmap(null, len, prot, .{ .TYPE = .SHARED }, fd, 0);
-}
-
pub fn fileSize(fd: posix.fd_t) !u64 {
var stat: linux.Statx = undefined;
switch (linux.errno(linux.statx(fd, "", linux.AT.EMPTY_PATH, .{ .SIZE = true }, &stat))) {
@@ -520,208 +503,6 @@ pub fn mapReadOnly(path: []const u8) []align(page) const u8 {
return posix.mmap(null, @intCast(len), .{ .READ = true }, .{ .TYPE = .SHARED }, fd, 0) catch &.{};
}
-/// Where every store is mapped, in every process: far from where Linux puts
-/// executables (0x55...) and mappings (0x7f...).
-pub const store_base: usize = 0x2000_0000_0000;
-/// The most a store can grow to. Only reserved: pages exist as they are used.
-pub const store_reserve: usize = 64 << 30;
-/// The allocator's record (`Meta`); unchanged by the layout format.
-pub const store_magic = "SKSTORE1".*;
-/// The store's layout header, like `file_magic` and `file_magic_v1`.
-pub const store_layout_magic = "SKSTORE2".*;
-pub const store_layout_magic_v1 = "SKSTORE1".*;
-/// The layout region is a state file header; the allocator's own record
-/// follows, then the heap.
-const meta_offset = header_len;
-const heap_offset = 2 * header_len;
-
-/// A heap in a file, with the sketch's `Store` at its root. Mapped at
-/// `store_base` in every run, so pointers it holds into itself stay valid
-/// across restarts. Not crash-safe: a crash in the middle of an allocation
-/// can leave it inconsistent (`--fresh` starts over).
-///
-/// Blocks come in power-of-two sizes, each class with a free list threaded
-/// through the free blocks, so growing a list by doubling reuses what it
-/// frees. The file grows by mapping more of it in place: nothing moves.
-pub const StoreFile = struct {
- fd: posix.fd_t,
- /// Bytes of the file mapped at `store_base`.
- len: usize,
- /// The root's layout, owned by `arena`.
- layout: Layout,
- arena: std.heap.ArenaAllocator,
-
- const Meta = extern struct {
- magic: [8]u8 = store_magic,
- base: u64 = store_base,
- /// Offset of the first byte never handed out.
- top: u64 = heap_offset,
- /// Offset of the sketch's Store, or 0 before the first adopt.
- root: u64 = 0,
- /// Offsets of the first free block of each size class (2^i bytes), 0
- /// when none; a free block's first 8 bytes hold the next one's.
- free: [64]u64 = @splat(0),
- };
-
- pub fn open(gpa: std.mem.Allocator, path: []const u8, fresh: bool) !StoreFile {
- const fd = try posix.openat(posix.AT.FDCWD, path, .{ .ACCMODE = .RDWR, .CREAT = true }, 0o600);
- errdefer _ = posix.system.close(fd);
- // The same file mapped by two processes would be two heaps writing
- // over each other.
- if (linux.errno(linux.flock(fd, posix.LOCK.EX | posix.LOCK.NB)) != .SUCCESS) return error.StoreInUse;
- const reserved = posix.mmap(@ptrFromInt(store_base), store_reserve, .{}, .{ .TYPE = .PRIVATE, .ANONYMOUS = true, .NORESERVE = true, .FIXED_NOREPLACE = true }, -1, 0) catch return error.StoreAddressTaken;
- // Old kernels treat FIXED_NOREPLACE as a hint.
- if (@intFromPtr(reserved.ptr) != store_base) {
- posix.munmap(reserved);
- return error.StoreAddressTaken;
- }
- errdefer posix.munmap(reserved);
- var self: StoreFile = .{ .fd = fd, .len = 0, .layout = .{}, .arena = .init(gpa) };
- errdefer self.arena.deinit();
- const size: usize = @intCast(try fileSize(fd));
- if (!fresh and size > 0) {
- // Checked before mapping, which may lengthen the file: a file
- // that is not a store is refused untouched, never wiped.
- var m: Meta = undefined;
- const read = linux.pread(fd, std.mem.asBytes(&m), @sizeOf(Meta), meta_offset);
- if (size < heap_offset or read != @sizeOf(Meta) or !std.mem.eql(u8, &m.magic, &store_magic) or m.base != store_base or m.top > size) return error.NotAStoreFile;
- try self.grow(size);
- self.layout = try readLayout(self.arena.allocator(), self.region()) orelse .{};
- return self;
- }
- try self.wipe();
- return self;
- }
-
- pub fn close(self: *StoreFile) void {
- posix.munmap(@as([*]align(page) u8, @ptrFromInt(store_base))[0..store_reserve]);
- _ = posix.system.close(self.fd);
- self.arena.deinit();
- }
-
- /// Empties the store: no root, nothing allocated.
- fn wipe(self: *StoreFile) !void {
- // Mapped pages past the new end would fault: map the reserve back.
- if (self.len > heap_offset) {
- _ = try posix.mmap(@ptrFromInt(store_base + heap_offset), self.len - heap_offset, .{}, .{ .TYPE = .PRIVATE, .ANONYMOUS = true, .NORESERVE = true, .FIXED = true }, -1, 0);
- self.len = heap_offset;
- }
- try truncate(self.fd, heap_offset);
- try self.grow(heap_offset);
- @memset(self.region(), 0);
- self.header().* = .{ .magic = store_layout_magic, .size = 0, .alignment = 1, .hash = 0, .stride = 0, .used = 0, .field_count = 0, .strings_len = 0 };
- self.meta().* = .{};
- self.layout = .{};
- }
-
- /// Maps the file up to `need` bytes, growing it when it is shorter.
- fn grow(self: *StoreFile, need: usize) !void {
- if (need <= self.len) return;
- const len = std.mem.alignForward(usize, @max(need, self.len * 2, 1 << 20), page);
- if (len > store_reserve) return error.StoreFull;
- if (try fileSize(self.fd) < len) try truncate(self.fd, len);
- _ = try posix.mmap(@ptrFromInt(store_base + self.len), len - self.len, .{ .READ = true, .WRITE = true }, .{ .TYPE = .SHARED, .FIXED = true }, self.fd, self.len);
- self.len = len;
- }
-
- fn region(_: *StoreFile) []u8 {
- return @as([*]u8, @ptrFromInt(store_base))[0..header_len];
- }
- fn header(_: *StoreFile) *Header {
- return @ptrFromInt(store_base);
- }
- fn meta(_: *StoreFile) *Meta {
- return @ptrFromInt(store_base + meta_offset);
- }
-
- /// The sketch's Store.
- pub fn root(self: *StoreFile) [*]u8 {
- const offset = self.meta().root;
- return @ptrFromInt(store_base + if (offset == 0) heap_offset else offset);
- }
-
- pub const Adoption = StateFile.Adoption;
-
- /// Makes the root hold `new`'s layout: the new defaults, then every field
- /// whose path and type are unchanged, copied over. Pointer fields keep
- /// pointing where they did, since the store never moves.
- pub fn adopt(self: *StoreFile, gpa: std.mem.Allocator, new: abi.Layout, defaults: *const fn (abi.Memory, [*]u8) callconv(.c) void) !Adoption {
- const m = self.meta();
- if (m.root != 0 and self.layout.hash == new.hash and self.layout.size == new.size) return .unchanged;
- const a = self.allocator();
- const alignment: std.mem.Alignment = .fromByteUnits(@max(new.alignment, 1));
- const fresh = a.rawAlloc(@max(new.size, 1), alignment, @returnAddress()) orelse return error.StoreFull;
- @memset(fresh[0..@max(new.size, 1)], 0);
- defaults(.store, fresh);
-
- var kept = self.arena;
- defer kept.deinit();
- self.arena = .init(gpa);
- const old_layout = self.layout;
- self.layout = try Layout.copy(self.arena.allocator(), new);
- var result: Adoption = .created;
- if (m.root != 0) {
- const old: [*]u8 = @ptrFromInt(store_base + m.root);
- result = .{ .migrated = migrate(old_layout, old[0..old_layout.size], self.layout, fresh[0..new.size]) };
- a.rawFree(old[0..@max(old_layout.size, 1)], .fromByteUnits(@max(old_layout.alignment, 1)), @returnAddress());
- }
- self.header().* = .{ .magic = store_layout_magic, .size = new.size, .alignment = new.alignment, .hash = new.hash, .stride = 0, .used = 1, .field_count = 0, .strings_len = 0 };
- try writeLayout(self.region(), self.layout);
- m.root = @intFromPtr(fresh) - store_base;
- return result;
- }
-
- pub fn allocator(self: *StoreFile) std.mem.Allocator {
- return .{ .ptr = self, .vtable = &.{ .alloc = alloc, .resize = resize, .remap = remap, .free = free } };
- }
-
- fn class(len: usize, alignment: std.mem.Alignment) u6 {
- return @intCast(std.math.log2_int_ceil(usize, @max(len, alignment.toByteUnits(), 16)));
- }
-
- fn alloc(ctx: *anyopaque, len: usize, alignment: std.mem.Alignment, _: usize) ?[*]u8 {
- const self: *StoreFile = @ptrCast(@alignCast(ctx));
- const m = self.meta();
- const c = class(len, alignment);
- const size = @as(usize, 1) << c;
- if (m.free[c] != 0) {
- const block: [*]u8 = @ptrFromInt(store_base + m.free[c]);
- if (alignment.check(@intFromPtr(block))) {
- m.free[c] = @as(*const u64, @ptrCast(@alignCast(block))).*;
- return block;
- }
- }
- const offset = std.mem.alignForward(usize, m.top, @max(@min(size, page), alignment.toByteUnits()));
- self.grow(offset + size) catch return null;
- m.top = offset + size;
- return @ptrFromInt(store_base + offset);
- }
-
- /// In place within the block's size class.
- fn resize(_: *anyopaque, memory: []u8, alignment: std.mem.Alignment, new_len: usize, _: usize) bool {
- return class(memory.len, alignment) == class(new_len, alignment);
- }
-
- fn remap(ctx: *anyopaque, memory: []u8, alignment: std.mem.Alignment, new_len: usize, ret: usize) ?[*]u8 {
- return if (resize(ctx, memory, alignment, new_len, ret)) memory.ptr else null;
- }
-
- fn free(ctx: *anyopaque, memory: []u8, alignment: std.mem.Alignment, _: usize) void {
- const self: *StoreFile = @ptrCast(@alignCast(ctx));
- const m = self.meta();
- const c = class(memory.len, alignment);
- @as(*u64, @ptrCast(@alignCast(memory.ptr))).* = m.free[c];
- m.free[c] = @intFromPtr(memory.ptr) - store_base;
- }
-};
-
-fn truncate(fd: posix.fd_t, len: usize) !void {
- switch (posix.errno(posix.system.ftruncate(fd, @intCast(len)))) {
- .SUCCESS => {},
- else => |err| return posix.unexpectedErrno(err),
- }
-}
-
/// Session memory: survives reloads while its layout hash is unchanged.
/// Everything allocated from `heap` is released with it.
pub const Session = struct {
@@ -859,7 +640,7 @@ test "migration keeps unchanged fields and defaults the rest" {
try std.testing.expectEqual(@as(usize, 1), m.reset);
}
-test "state file migrates live state and snapshots, and a reopen reads the layout back" {
+test "State migrates to a changed layout, and keeps itself when it is unchanged" {
const V1 = extern struct { score: u32 = 0, name: [4]u8 = "none".* };
const V2 = extern struct { level: u16 = 1, score: u32 = 0 };
const D = struct {
@@ -870,71 +651,20 @@ test "state file migrates live state and snapshots, and a reopen reads the layou
@as(*V2, @ptrCast(@alignCast(p))).* = .{};
}
};
- var tmp = std.testing.tmpDir(.{});
- defer tmp.cleanup();
- var buf: [std.fs.max_path_bytes]u8 = undefined;
- const path = try std.mem.print(&buf, ".zig-cache/tmp/{s}/test.state", .{&tmp.sub_path});
- const gpa = std.testing.allocator;
- {
- var file = try StateFile.open(gpa, path);
- defer file.close();
- try std.testing.expectEqual(StateFile.Adoption.created, try file.adopt(gpa, abi.layout.of(V1, .state), D.v1));
- file.markUsed(0, true);
- @as(*V1, @ptrCast(file.slot(0).ptr)).score = 99;
- @memcpy(file.slot(3), file.slot(0));
- file.markUsed(3, true);
- }
- var file = try StateFile.open(gpa, path);
- defer file.close();
- try std.testing.expectEqual(abi.layout.hash(V1), file.layout.hash);
- const adoption = try file.adopt(gpa, abi.layout.of(V2, .state), D.v2);
- try std.testing.expectEqual(@as(usize, 1), adoption.migrated.reset);
- for ([_]usize{ 0, 3 }) |i| {
- const s: *V2 = @ptrCast(file.slot(i).ptr);
- try std.testing.expectEqual(V2{ .level = 1, .score = 99 }, s.*);
- }
- try std.testing.expect(!file.used(1));
-}
-
-test "a store keeps its root and what it points to across a reopen, and migrates by field" {
- const V1 = struct { list: std.ArrayList(u32) = .empty, count: u32 = 0 };
- const V2 = struct { added: u8 = 7, list: std.ArrayList(u32) = .empty };
- const D = struct {
- fn v1(_: abi.Memory, p: [*]u8) callconv(.c) void {
- @as(*V1, @ptrCast(@alignCast(p))).* = .{};
- }
- fn v2(_: abi.Memory, p: [*]u8) callconv(.c) void {
- @as(*V2, @ptrCast(@alignCast(p))).* = .{};
- }
- };
- var tmp = std.testing.tmpDir(.{});
- defer tmp.cleanup();
- var buf: [std.fs.max_path_bytes]u8 = undefined;
- const path = try std.mem.print(&buf, ".zig-cache/tmp/{s}/test.store", .{&tmp.sub_path});
const gpa = std.testing.allocator;
- {
- var store = try StoreFile.open(gpa, path, false);
- defer store.close();
- try std.testing.expectEqual(StoreFile.Adoption.created, try store.adopt(gpa, abi.layout.of(V1, .store), D.v1));
- const v: *V1 = @ptrCast(@alignCast(store.root()));
- for (0..10_000) |i| try v.list.append(store.allocator(), @intCast(i));
- v.count = 3;
- try std.testing.expectError(error.StoreInUse, StoreFile.open(gpa, path, false));
- }
- {
- var store = try StoreFile.open(gpa, path, false);
- defer store.close();
- try std.testing.expectEqual(StoreFile.Adoption.unchanged, try store.adopt(gpa, abi.layout.of(V1, .store), D.v1));
- const adoption = try store.adopt(gpa, abi.layout.of(V2, .store), D.v2);
- try std.testing.expectEqual(@as(usize, 1), adoption.migrated.reset);
- const v: *V2 = @ptrCast(@alignCast(store.root()));
- try std.testing.expectEqual(@as(u8, 7), v.added);
- try std.testing.expectEqual(@as(u32, 9999), v.list.items[9999]);
- v.list.deinit(store.allocator());
- }
- var store = try StoreFile.open(gpa, path, true);
- defer store.close();
- try std.testing.expectEqual(StoreFile.Adoption.created, try store.adopt(gpa, abi.layout.of(V2, .store), D.v2));
+ var state: State = .init(gpa);
+ defer state.deinit(gpa);
+ try std.testing.expectEqual(@as(?Migration, null), try state.adopt(gpa, abi.layout.of(V1, .state), D.v1));
+ @as(*V1, @ptrCast(state.live().ptr)).score = 99;
+ try std.testing.expectEqual(@as(?Migration, null), try state.adopt(gpa, abi.layout.of(V1, .state), D.v1));
+ try std.testing.expectEqual(@as(u32, 99), @as(*V1, @ptrCast(state.live().ptr)).score);
+ const m = (try state.adopt(gpa, abi.layout.of(V2, .state), D.v2)).?;
+ try std.testing.expectEqual(@as(usize, 1), m.reset);
+ try std.testing.expectEqual(V2{ .level = 1, .score = 99 }, @as(*V2, @ptrCast(@alignCast(state.live().ptr))).*);
+ // The header reads back as the layout.
+ var arena: std.heap.ArenaAllocator = .init(gpa);
+ defer arena.deinit();
+ try std.testing.expectEqual(abi.layout.hash(V2), (try layoutOf(arena.allocator(), state.header)).hash);
}
test "arrays migrate element by element: fields, enums by name, shrink and growth" {
@@ -1049,14 +779,15 @@ test "a file that is not a state file is refused, untouched" {
defer std.testing.allocator.free(text);
@memset(text, 'x');
try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = text });
- try std.testing.expectError(error.NotAStateFile, StateFile.open(std.testing.allocator, path));
+ try std.testing.expectError(error.NotAStateFile, OldState.open(path));
const after = try std.Io.Dir.cwd().readFileAlloc(io, path, std.testing.allocator, .unlimited);
defer std.testing.allocator.free(after);
try std.testing.expectEqualSlices(u8, text, after);
}
+ try std.testing.expectError(error.FileNotFound, OldState.open(try testPath(&buf, tmp, "none.state")));
}
-test "a state file from before element leaves (drat-meout's) keeps every value" {
+test "a state file from before element leaves (drat-meout's) imports with every value" {
const gpa = std.testing.allocator;
const io = std.testing.io;
var tmp = std.testing.tmpDir(.{});
@@ -1076,30 +807,29 @@ test "a state file from before element leaves (drat-meout's) keeps every value"
const h: *const Header = @ptrCast(@alignCast(original.ptr));
const live = original[header_len..][0..h.size];
- // The layout the game had when it wrote the file, as a sketch would
- // describe it: unchanged, so nothing migrates and the header is
- // rewritten in the new format.
- const same = try asSketchLayout(a, old, &.{});
- {
- var file = try StateFile.open(gpa, path);
- defer file.close();
- try std.testing.expectEqual(StateFile.Adoption.unchanged, try file.adopt(gpa, same, NoDefaults.f));
- try std.testing.expectEqualStrings(&file_magic, &file.header().magic);
- }
- var file = try StateFile.open(gpa, path);
+ const file = try OldState.open(path);
defer file.close();
- try std.testing.expectEqual(old.fields.len, file.layout.fields.len);
- try std.testing.expectEqualSlices(u8, live, file.slot(0));
-
- // A changed layout (one field gone, one new): every other leaf keeps
- // its value, the songs included (an unchanged array type, so whole).
- const changed = try asSketchLayout(a, old, "scene");
- _ = try file.adopt(gpa, changed, NoDefaults.f);
- for (old.fields) |leaf| {
- if (std.mem.eql(u8, leaf.path, "scene")) continue;
- try std.testing.expectEqualSlices(u8, leaf.bytes(live), leaf.bytes(file.slot(0)));
+ try std.testing.expectEqual(@as(usize, old_slot_count), file.slots);
+ // Into the layout the game had when it wrote the file, as a sketch would
+ // describe it: every byte; then into a changed one (one field gone, one
+ // new): every other leaf keeps its value, the songs included (an
+ // unchanged array type, so whole).
+ for ([_][]const u8{ "", "scene" }) |drop| {
+ var state: State = .init(gpa);
+ defer state.deinit(gpa);
+ _ = try state.adopt(gpa, try asSketchLayout(a, old, drop), NoDefaults.f);
+ @memset(state.live(), 0);
+ _ = try restore(a, file.layoutBytes(), file.slot(0).?, state.layout, state.live(), NoDefaults.f);
+ if (drop.len == 0) try std.testing.expectEqualSlices(u8, live, state.live());
+ for (old.fields) |leaf| {
+ if (drop.len > 0 and std.mem.eql(u8, leaf.path, drop)) continue;
+ try std.testing.expectEqualSlices(u8, leaf.bytes(live), leaf.bytes(state.live()));
+ }
}
- try std.testing.expectEqual(@as(u8, 0), file.slot(0)[h.size]);
+ // The file is as it was.
+ const after = try tmp.dir.readFileAlloc(io, "game.state", gpa, .unlimited);
+ defer gpa.free(after);
+ try std.testing.expectEqualSlices(u8, original, after);
}
const NoDefaults = struct {
diff --git a/src/host/overlay.zig b/src/host/overlay.zig
index e1fc45d..ec040e7 100644
--- a/src/host/overlay.zig
+++ b/src/host/overlay.zig
@@ -111,7 +111,7 @@ pub fn drawMemory(out: *List, arena: std.mem.Allocator, layout: memory.Layout, s
}
}
-pub fn drawScope(out: *List, arena: std.mem.Allocator, samples: []const f32, rate: u32, canvas: [2]u32) !void {
+pub fn drawScope(out: *List, arena: std.mem.Allocator, samples: []const f32, rate: u32, pull: u32, canvas: [2]u32) !void {
const green: abi.Color = .{ .r = 105, .g = 245, .b = 160 };
const x = @as(f32, @floatFromInt(canvas[0])) - 526;
const top = @as(f32, @floatFromInt(canvas[1])) - 130;
@@ -119,7 +119,7 @@ pub fn drawScope(out: *List, arena: std.mem.Allocator, samples: []const f32, rat
try out.append(arena, .{ .rect = .{ .dst = .{ .x = x, .y = top, .w = 514, .h = 118 }, .color = .{ .r = 24, .g = 24, .b = 24 } } });
try out.append(arena, .{ .rect = .{ .dst = .{ .x = x + 1, .y = mid, .w = 512, .h = 1 }, .color = .{ .r = 60, .g = 85, .b = 65 } } });
const ms = @as(f32, @floatFromInt(samples.len * 1000)) / @as(f32, @floatFromInt(@max(rate, 1)));
- try out.append(arena, .{ .text = .{ .x = x + 8, .y = top + 10, .scale = 1, .color = green, .bytes = try std.fmt.allocPrint(arena, "OUTPUT ch1 / {d:.1}ms / overlay sound to hide", .{ms}) } });
+ try out.append(arena, .{ .text = .{ .x = x + 8, .y = top + 10, .scale = 1, .color = green, .bytes = try std.fmt.allocPrint(arena, "OUTPUT ch1 / {d:.1}ms / pull {d} / overlay sound to hide", .{ ms, pull }) } });
for (samples, 0..) |sample, i| {
const a = std.math.clamp(if (std.math.isFinite(sample)) sample else 0, -1, 1);
const previous = samples[i -| 1];
diff --git a/src/host/probe.zig b/src/host/probe.zig
deleted file mode 100644
index d8ed166..0000000
--- a/src/host/probe.zig
+++ /dev/null
@@ -1,86 +0,0 @@
-//! sketchbook-probe: prints the live state of any running sketch, from its
-//! state file alone. The file header carries the layout, so the probe needs
-//! no knowledge of the sketch: it maps the same pages read-only.
-const std = @import("std");
-const memory = @import("memory.zig");
-const fields = @import("fields.zig");
-
-const usage =
- \\usage: sketchbook-probe [--watch] [--interval MS] STATE_FILE
- \\Prints every field of the live state; --watch prints again on change.
- \\
-;
-
-pub fn main(init: std.process.Init) !void {
- var path: ?[]const u8 = null;
- var watch = false;
- var interval_ms: i64 = 100;
- var args = init.minimal.args.iterate();
- _ = args.skip();
- while (args.next()) |arg| {
- if (std.mem.eql(u8, arg, "--watch")) {
- watch = true;
- } else if (std.mem.eql(u8, arg, "--interval")) {
- interval_ms = std.fmt.parseInt(i64, args.next() orelse "", 10) catch fatal("--interval needs milliseconds");
- } else if (std.mem.startsWith(u8, arg, "-")) {
- std.debug.print("{s}", .{usage});
- return;
- } else path = arg;
- }
- const file = path orelse fatal("no state file given");
- const map = memory.mapReadOnly(file);
- if (map.len < memory.header_len) fatal("not a sketchbook state file");
- const magic = map[0..8];
- if (!std.mem.eql(u8, magic, &memory.file_magic) and !std.mem.eql(u8, magic, &memory.file_magic_v1)) fatal("not a sketchbook state file");
- defer std.posix.munmap(map);
- var arena: std.heap.ArenaAllocator = .init(init.gpa);
- defer arena.deinit();
- const layout = (try memory.readLayout(arena.allocator(), map)) orelse fatal("state file has no layout yet");
- const header: *const memory.Header = @ptrCast(@alignCast(map.ptr));
- const live = map[memory.header_len..][0..header.size];
-
- const shown = try arena.allocator().dupe(u8, live);
- show(file, layout, live);
- while (watch) {
- try std.Io.sleep(init.io, .fromMilliseconds(interval_ms), .awake);
- if (std.mem.eql(u8, shown, live)) continue;
- @memcpy(shown, live);
- show(file, layout, live);
- }
-}
-
-fn show(path: []const u8, layout: memory.Layout, live: []const u8) void {
- var buf: [4096]u8 = undefined;
- var w: std.Io.Writer = .fixed(&buf);
- std.debug.print("{s}: {d} bytes, layout {x:0>16}\n", .{ path, live.len, layout.hash });
- for (layout.fields) |leaf| {
- // Whole arrays are shown by their elements' leaves.
- if (leaf.whole()) continue;
- w.end = 0;
- if (leaf.dims.len == 0) {
- fields.format(leaf, live, &w) catch {};
- } else {
- // Elements in index order, the first few.
- var it = leaf.elements();
- var n: usize = 0;
- while (it.next()) |offset| : (n += 1) {
- if (n == 8) {
- w.writeAll(" ...") catch {};
- break;
- }
- if (n > 0) w.writeAll(" ") catch {};
- fields.format(leaf.at(offset), live, &w) catch {};
- }
- }
- var name: [128]u8 = undefined;
- var nw: std.Io.Writer = .fixed(&name);
- nw.writeAll(leaf.path) catch {};
- for (leaf.dims) |d| nw.print(" [{d}]", .{d.count}) catch {};
- std.debug.print(" +0x{x:0>4} {s:<28} {s}\n", .{ leaf.offset, nw.buffered(), w.buffered() });
- }
-}
-
-fn fatal(message: []const u8) noreturn {
- std.debug.print("sketchbook-probe: {s}\n{s}", .{ message, usage });
- std.process.exit(2);
-}
diff --git a/src/host/root.zig b/src/host/root.zig
index 158f894..f15493b 100644
--- a/src/host/root.zig
+++ b/src/host/root.zig
@@ -1,20 +1,6 @@
//! The sketchbook host: runs a sketch linked in, or loaded from a library
-//! that it hot-reloads whenever a build replaces it.
-//!
-//! sketchbook [options] [LIBRARY]
-//! --state FILE persistent state (default: <name>.state)
-//! --headless offscreen video, silent audio
-//! --script FILE play a script instead of reading devices
-//! --fresh start from default state: no snapshots or recordings
-//! --timing-marker encode frame ID and draw sample time for video analysis
-//! --profile-gpu time each GPU command alone, print the times at exit
-//! --console LINE run a console line once the sketch is loaded (repeatable)
-//! --define NAME=VALUE substitute {NAME} in the script
-//! --export DIR|- headless, from fresh state: every frame as DIR/000000.png, ...
-//! or for - as raw RGBA on stdout, until the sketch quits
-//! --fps N export: frames a second (60); each tick is exactly 1/N s
-//! --frames N export: stop after N frames
-//! --size WxH the first canvas and, headless, the room for it
+//! that it hot-reloads whenever a build replaces it. Its options are
+//! `flags`, which parse the command line and print `--help`.
const std = @import("std");
const c = @import("c");
const abi = @import("abi");
@@ -23,6 +9,10 @@ pub const memory = @import("memory.zig");
pub const fields = @import("fields.zig");
pub const script = @import("script.zig");
pub const timeline = @import("timeline.zig");
+const c9 = @import("cloud9");
+const control = @import("control.zig");
+const Sessions = @import("Sessions.zig");
+const Library = @import("library.zig").Library;
/// Entry point for both the generic host (`linked == null`) and apps that
/// link their sketch in.
@@ -38,76 +28,63 @@ pub fn main(init: std.process.Init, linked: ?abi.Sketch) !void {
var args = init.minimal.args.iterate();
_ = args.skip();
while (args.next()) |arg| {
- if (std.mem.eql(u8, arg, "--state")) {
- options.state = args.next() orelse fatal("--state needs a file");
- } else if (std.mem.eql(u8, arg, "--9p")) {
- options.ninep = args.next() orelse fatal("--9p needs a socket path");
- } else if (std.mem.eql(u8, arg, "--fresh")) {
- options.fresh = true;
- } else if (std.mem.eql(u8, arg, "--headless")) {
- options.headless = true;
- } else if (std.mem.eql(u8, arg, "--timing-marker")) {
- options.timing_marker = true;
- } else if (std.mem.eql(u8, arg, "--profile-gpu")) {
- options.profile_gpu = true;
- } else if (std.mem.eql(u8, arg, "--console")) {
- try lines.append(gpa, args.next() orelse fatal("--console needs a line"));
- } else if (std.mem.eql(u8, arg, "--script")) {
- script_path = args.next() orelse fatal("--script needs a file");
- } else if (std.mem.eql(u8, arg, "--define")) {
- const pair = args.next() orelse fatal("--define needs NAME=VALUE");
- const eq = std.mem.indexOfScalar(u8, pair, '=') orelse fatal("--define needs NAME=VALUE");
- try defines.append(gpa, .{ pair[0..eq], pair[eq + 1 ..] });
- } else if (std.mem.eql(u8, arg, "--export")) {
- options.export_to = args.next() orelse fatal("--export needs a directory, or - for stdout");
- options.headless = true;
- options.fresh = true;
- } else if (std.mem.eql(u8, arg, "--fps")) {
- options.fps = std.fmt.parseInt(u32, args.next() orelse "", 10) catch 0;
- if (options.fps == 0) fatal("--fps needs a whole number of frames a second");
- } else if (std.mem.eql(u8, arg, "--frames")) {
- options.frames = std.fmt.parseInt(u64, args.next() orelse "", 10) catch fatal("--frames needs a number");
- } else if (std.mem.eql(u8, arg, "--size")) {
- const size = args.next() orelse "";
- const x = std.mem.indexOfScalar(u8, size, 'x') orelse fatal("--size needs WxH");
- const w = std.fmt.parseInt(u32, size[0..x], 10) catch 0;
- const h = std.fmt.parseInt(u32, size[x + 1 ..], 10) catch 0;
- if (w == 0 or h == 0) fatal("--size needs WxH");
- options.size = .{ w, h };
- } else if (std.mem.eql(u8, arg, "-h") or std.mem.eql(u8, arg, "--help")) {
- std.debug.print("{s}", .{usage});
- return;
- } else if (std.mem.startsWith(u8, arg, "-")) {
- fatal("unknown option (see --help)");
- } else {
+ if (std.mem.eql(u8, arg, "fs")) {
+ var words: std.ArrayList([]const u8) = .empty;
+ defer words.deinit(gpa);
+ while (args.next()) |word| try words.append(gpa, word);
+ std.process.exit(try fs(init, linked, options, words.items));
+ }
+ if (!std.mem.startsWith(u8, arg, "-")) {
options.library = arg;
+ continue;
+ }
+ const flag: Flag = if (std.mem.eql(u8, arg, "-h")) .help else (if (std.mem.startsWith(u8, arg, "--")) std.meta.stringToEnum(Flag, arg[2..]) else null) orelse fatal("{s} is no option (see --help)", .{arg});
+ const v = if (flags.get(flag).arg.len == 0) "" else args.next() orelse fatal("{s} needs {s}", .{ arg, flags.get(flag).arg });
+ switch (flag) {
+ .@"9p" => options.ninep = v,
+ .state => options.state = v,
+ .headless => options.headless = true,
+ .script => {
+ script_path = v;
+ options.script = true;
+ },
+ .fresh => options.fresh = true,
+ .@"timing-marker" => options.timing_marker = true,
+ .@"profile-gpu" => options.profile_gpu = true,
+ .console => try lines.append(gpa, v),
+ .define => {
+ const eq = std.mem.indexOfScalar(u8, v, '=') orelse fatal("{s} needs {s}", .{ arg, "NAME=VALUE" });
+ try defines.append(gpa, .{ v[0..eq], v[eq + 1 ..] });
+ },
+ .@"export" => {
+ options.export_to = v;
+ options.headless = true;
+ options.fresh = true;
+ },
+ .fps => options.fps = std.fmt.parseInt(u32, v, 10) catch 0,
+ .frames => options.frames = std.fmt.parseInt(u64, v, 10) catch fatal("{s} needs {s}", .{ arg, "a number" }),
+ .size => {
+ const x = std.mem.indexOfScalar(u8, v, 'x') orelse 0;
+ const w = std.fmt.parseInt(u32, v[0..x], 10) catch 0;
+ const h = std.fmt.parseInt(u32, v[x + 1 ..], 10) catch 0;
+ if (w == 0 or h == 0) fatal("{s} needs {s}", .{ arg, "WxH" });
+ options.size = .{ w, h };
+ },
+ .help => return std.debug.print("{s}", .{usage}),
}
+ if (options.fps == 0) fatal("{s} needs {s}", .{ arg, "a whole number of frames a second" });
}
- if (linked == null and options.library == null) fatal("no sketch library given (see --help)");
+ if (linked == null and options.library == null) fatal("no sketch library given (see --help)", .{});
if (options.export_to) |to| {
- if (script_path != null) fatal("--export plays no script: it runs the sketch on its own");
+ if (script_path != null) fatal("--export plays no script: it runs the sketch on its own", .{});
if (!std.mem.eql(u8, to, "-")) {
try std.Io.Dir.cwd().createDirPath(init.io, to);
- } else if (try std.Io.File.stdout().isTty(init.io)) fatal("--export -: stdout is a terminal; pipe it to ffmpeg");
+ } else if (try std.Io.File.stdout().isTty(init.io)) fatal("--export -: stdout is a terminal; pipe it to ffmpeg", .{});
}
- // A scripted run from fresh state works on files of its own, moved to
- // the given path at exit: two runs of one build step (two `zig build`s
- // at once share its output path) never share a state, store or
- // recordings file, nor fail on the store's lock. An export's are
- // removed instead: nothing reads them, and a player may have the given
- // ones open.
- var private_buf: [std.fs.max_path_bytes]u8 = undefined;
- const given = options.state;
- const private = (script_path != null or options.export_to != null) and options.fresh;
- if (private) options.state = std.mem.print(&private_buf, "{s}.{d}", .{ given, std.os.linux.getpid() }) catch fatal("--state path too long");
- defer if (private) for ([_][]const u8{ "", ".inputs", ".store" }) |suffix| {
- var from: [std.fs.max_path_bytes + 16]u8 = undefined;
- var to: [std.fs.max_path_bytes + 16]u8 = undefined;
- const a = std.mem.printSentinel(&from, "{s}{s}", .{ options.state, suffix }, 0) catch continue;
- const b = std.mem.printSentinel(&to, "{s}{s}", .{ given, suffix }, 0) catch continue;
- _ = if (options.export_to != null) std.os.linux.unlink(a.ptr) else std.os.linux.rename(a.ptr, b.ptr);
- };
+ if (options.state.len == 0 and (script_path != null or options.export_to != null)) options.state = "sketch.xitdb";
+ // A scripted run from fresh state, or an export, touches no save.
+ if (!((script_path != null or options.export_to != null) and options.fresh)) sketchbookDir(init.io, options.state);
sdl_heap.install();
{
@@ -124,27 +101,144 @@ pub fn main(init: std.process.Init, linked: ?abi.Sketch) !void {
if (sdl_heap.leaked()) return error.LeakedSdlMemory;
}
-const usage =
- \\usage: sketchbook [options] [LIBRARY]
- \\ --9p SOCKET local 9P controls: ctl, status, log, screen.png
- \\ --state FILE persistent state (default: sketch.state)
- \\ --headless offscreen video, silent audio, no vsync
- \\ --script FILE play a script instead of reading devices
- \\ --fresh start from default state: no snapshots or recordings
- \\ --timing-marker encode frame ID and draw sample time for video analysis
- \\ --profile-gpu time each GPU command alone, print the times at exit
- \\ --console LINE run a console line once the sketch is loaded (repeatable)
- \\ --define NAME=VALUE substitute {NAME} in the script
- \\ --export DIR|- headless, from fresh state: every frame as DIR/000000.png, ...
- \\ or for - as raw RGBA on stdout, until the sketch quits
- \\ --fps N export: frames a second (60); each tick is exactly 1/N s
- \\ --frames N export: stop after N frames
- \\ --size WxH the first canvas and, headless, the room for it
- \\
-;
+/// The options: a row each, what parses the command line (the switch in
+/// `main` sets what each one means) and prints `--help`.
+const Flag = enum { @"9p", state, headless, script, fresh, @"timing-marker", @"profile-gpu", console, define, @"export", fps, frames, size, help };
+const flags = std.enums.EnumArray(Flag, struct { arg: []const u8 = "", doc: []const u8 }).init(.{
+ .@"9p" = .{ .arg = "NAME|/SOCKET", .doc = "the 9P tree (README, ctl, state/, screen.png...), posted as sketchbook/NAME\n(a run in a window posts its own name), or at a socket path" },
+ .state = .{ .arg = "FILE", .doc = "the save, one file: FILE, or FILE.xitdb for a FILE.state (where a\nstate file from before is imported from, once); default:\n$XDG_DATA_HOME/<name>/<name>.xitdb, sketch.xitdb for --script, --export" },
+ .headless = .{ .doc = "offscreen video, silent audio, no vsync" },
+ .script = .{ .arg = "FILE", .doc = "play a script instead of reading devices" },
+ .fresh = .{ .doc = "start from default state (the save's history is kept)" },
+ .@"timing-marker" = .{ .doc = "encode frame ID and draw sample time for video analysis" },
+ .@"profile-gpu" = .{ .doc = "time each GPU command alone, print the times at exit" },
+ .console = .{ .arg = "LINE", .doc = "run a console line once the sketch is loaded (repeatable)" },
+ .define = .{ .arg = "NAME=VALUE", .doc = "substitute {NAME} in the script" },
+ .@"export" = .{ .arg = "DIR|-", .doc = "headless, from fresh state: every frame as DIR/000000.png, ...\nor for - as raw RGBA on stdout, until the sketch quits" },
+ .fps = .{ .arg = "N", .doc = "export: frames a second (60); each tick is exactly 1/N s" },
+ .frames = .{ .arg = "N", .doc = "export: stop after N frames" },
+ .size = .{ .arg = "WxH", .doc = "the first canvas and, headless, the room for it" },
+ .help = .{ .doc = "this, also -h" },
+});
+
+/// `--help`: a line per flag, its doc's lines under one another.
+const usage = blk: {
+ @setEvalBranchQuota(100_000);
+ const pad: [23]u8 = @splat(' ');
+ var text: []const u8 = "usage: sketchbook [options] [LIBRARY] [fs VERB [PATH [WORDS...]]]\n";
+ for (std.enums.values(Flag)) |flag| {
+ const f = flags.get(flag);
+ const head = " --" ++ @tagName(flag) ++ (if (f.arg.len > 0) " " ++ f.arg else "");
+ text = text ++ head ++ pad[@min(head.len, pad.len)..];
+ var lines = std.mem.splitScalar(u8, f.doc, '\n');
+ text = text ++ lines.first() ++ "\n";
+ while (lines.next()) |more| text = text ++ pad ++ more ++ "\n";
+ }
+ break :blk text;
+};
+
+/// `fs VERB [PATH [WORDS]]`: cloud9's verbs on the sketch's tree. The
+/// running sketch's, posted as sketchbook/<name> (or at --9p); with none,
+/// the same tree served here from the save's newest State (--state's, or
+/// the default save), else from the State's defaults: README, commands,
+/// state/ answer, and the rest say the sketch is not running. No window.
+fn fs(init: std.process.Init, linked: ?abi.Sketch, options: Host.Options, words: []const []const u8) !u8 {
+ const gpa = init.gpa;
+ const io = init.io;
+ const env = init.environ_map;
+ var in_buf: [4096]u8 = undefined;
+ var out_buf: [4096]u8 = undefined;
+ var err_buf: [1024]u8 = undefined;
+ var in = std.Io.File.stdin().reader(io, &in_buf);
+ var out = std.Io.File.stdout().writer(io, &out_buf);
+ var err = std.Io.File.stderr().writer(io, &err_buf);
+ const user = env.get("USER") orelse "sketchbook";
+ var library: ?Library = null;
+ defer if (library) |*l| l.close();
+ const sketch = linked orelse blk: {
+ library = try Library.openFresh(io, options.library orelse fatal("fs needs the sketch library first: sketchbook LIBRARY fs ...", .{}), Host.scratchDir(env), 0);
+ break :blk library.?.sketch;
+ };
+ const info = sketch.info();
+ const no_env = [_:null]?[*:0]const u8{};
+ var f: c9.Fsys = undefined;
+ var path_buf: [c9.post.sun_path_len]u8 = undefined;
+ const where = options.ninep orelse info.name;
+ const path = if (std.mem.startsWith(u8, where, "/")) where else control.registered(env, where, &path_buf) catch "";
+ if (f.dial(io, &no_env, path, user)) |_| {
+ defer f.close();
+ return c9.verbs.run(&f, words, &in.interface, &out.interface, &err.interface);
+ } else |_| {}
+
+ var arena: std.heap.ArenaAllocator = .init(gpa);
+ defer arena.deinit();
+ const layout = try memory.Layout.copy(arena.allocator(), info.state);
+ const bytes = try arena.allocator().alignedAlloc(u8, .fromByteUnits(memory.page), layout.size);
+ @memset(bytes, 0);
+ sketch.defaults(.state, bytes.ptr);
+ var from = try std.fmt.allocPrint(arena.allocator(), "{s} is not running: this is its State's defaults (no save)", .{info.name});
+ var data_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const save = if (options.state.len > 0)
+ try std.fmt.allocPrint(arena.allocator(), "{s}.xitdb", .{Host.stemOf(options.state)})
+ else
+ try std.fmt.allocPrint(arena.allocator(), "{s}/{s}/{s}.xitdb", .{ env.get("XDG_DATA_HOME") orelse try std.fmt.bufPrint(&data_buf, "{s}/.local/share", .{env.get("HOME") orelse "."}), info.name, info.name });
+ if (Sessions.openRead(gpa, io, save)) |opened| {
+ var s = opened;
+ defer s.deinit();
+ var events: std.ArrayList(abi.Event) = .empty;
+ defer events.deinit(gpa);
+ if (try s.present(&events)) |key| {
+ defer key.free(gpa);
+ _ = try memory.restore(arena.allocator(), key.layout, key.state, layout, bytes, sketch.defaults);
+ from = try std.fmt.allocPrint(arena.allocator(), "{s} is not running: this is its save's newest State, frame {d} of {s}", .{ info.name, key.frame, save });
+ }
+ } else |_| {}
+ const commands = try arena.allocator().alloc([]const u8, info.commands.len);
+ for (commands, info.commands) |*to, word| to.* = word;
+ var server: control.Control = .{ .allocator = gpa, .path = undefined, .listener = -1, .offline = .{ .layout = layout, .bytes = bytes, .completions = commands, .from = from } };
+ var fds: [2]i32 = undefined;
+ if (std.c.socketpair(std.c.AF.UNIX, std.c.SOCK.STREAM | std.c.SOCK.CLOEXEC, 0, &fds) != 0) return error.SocketPair;
+ const thread = try std.Thread.spawn(.{}, control.Control.serveOffline, .{ &server, fds[0] });
+ defer thread.join();
+ try f.init(io, .{ .socket = .{ .handle = fds[1], .address = undefined } }, user);
+ defer f.close();
+ // A read answered here is not the running sketch's: said on stderr, so
+ // a script that reads before the sketch is up does not take it for one.
+ if (words.len > 0 and std.mem.eql(u8, words[0], "read")) {
+ try err.interface.print("{s}\n", .{from});
+ try err.interface.flush();
+ }
+ return c9.verbs.run(&f, words, &in.interface, &out.interface, &err.interface);
+}
+
+/// A save in a directory named `.sketchbook` (`zig build run`'s): the
+/// directory is made, with a `.gitignore` of `*` (the save grows, and a jj
+/// snapshot would commit it), and the state file an older build kept beside
+/// it (`<stem>.state`) is moved in, once, to be imported. A file is never
+/// replaced: when both exist, nothing moves.
+fn sketchbookDir(io: std.Io, state: []const u8) void {
+ const dir = std.fs.path.dirname(state) orelse return;
+ if (!std.mem.eql(u8, std.fs.path.basename(dir), ".sketchbook")) return;
+ const cwd = std.Io.Dir.cwd();
+ cwd.createDirPath(io, dir) catch return;
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const ignore = std.fmt.bufPrint(&buf, "{s}/.gitignore", .{dir}) catch return;
+ cwd.writeFile(io, .{ .sub_path = ignore, .data = "*\n", .flags = .{ .exclusive = true } }) catch {};
+ var from_buf: [std.fs.max_path_bytes]u8 = undefined;
+ var to_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const parent = std.fs.path.dirname(dir) orelse ".";
+ const stem = Host.stemOf(std.fs.path.basename(state));
+ const from = std.fmt.bufPrintSentinel(&from_buf, "{s}/{s}.state", .{ parent, stem }, 0) catch return;
+ const to = std.fmt.bufPrintSentinel(&to_buf, "{s}/{s}.state", .{ dir, stem }, 0) catch return;
+ switch (std.os.linux.errno(std.os.linux.renameat2(std.os.linux.AT.FDCWD, from.ptr, std.os.linux.AT.FDCWD, to.ptr, .{ .NOREPLACE = true }))) {
+ .SUCCESS => std.debug.print("sketchbook: moved {s} to {s}\n", .{ from, to }),
+ .EXIST => std.debug.print("sketchbook: {s} and {s} both exist: nothing moved, {s} is used\n", .{ from, to, to }),
+ else => {},
+ }
+}
-fn fatal(message: []const u8) noreturn {
- std.debug.print("sketchbook: {s}\n", .{message});
+fn fatal(comptime fmt: []const u8, args: anytype) noreturn {
+ std.debug.print("sketchbook: " ++ fmt ++ "\n", args);
std.process.exit(2);
}
@@ -202,8 +296,10 @@ test {
_ = memory;
_ = fields;
_ = timeline;
+ _ = @import("Sessions.zig");
_ = @import("audio.zig");
_ = @import("Console.zig");
_ = @import("control.zig");
+ _ = @import("state_files.zig");
_ = @import("timing_marker.zig");
}
diff --git a/src/host/script.zig b/src/host/script.zig
index 7818c6b..e3976e0 100644
--- a/src/host/script.zig
+++ b/src/host/script.zig
@@ -1,58 +1,60 @@
//! End-to-end scripts: plain text that plays a sketch like a person would,
-//! through the same routing and frames, on a fixed 60 Hz clock.
-//!
-//! # comment
-//! click 710 320 move there, press and release the left button
-//! move|down|up X Y one pointer event, then a frame
-//! wheel|wheel-x X Y DELTA
-//! cancel what losing focus sends
-//! key NAME press and release a key (`sketch.Key` names)
-//! type TEXT text input, as typed into a focused field
-//! console LINE run a console command (`console get`
-//! takes no frame: it only reads)
-//! frames N advance N frames without input
-//! expect FIELD VALUE compare a state field (enums by name or number);
-//! FIELD may index arrays and vector lanes,
-//! `boids.buffer[3].pos[0]`
-//! expect FIELD VALUE ~T numbers within T of VALUE
-//! await FIELD VALUE [~T] run frames until it holds (a minute at most)
-//! print FIELD write a field's value to stderr (a vector,
-//! array or struct: every value in it), no frame
-//! expect-snapshot N live state equals snapshot N, leaf by leaf
-//! (padding ignored), exactly
-//! expect-log TEXT a recent console line contains TEXT
-//! expect-no-log TEXT no recent console line does
-//! expect-audio KEY stream KEY has received samples
-//! screenshot FILE save the next frame as PNG
-//! expect-same-screenshot A B [MAX [X Y W H]]
-//! two saved PNGs match, every channel within MAX
-//! (default 0), in the rect if given (pixels)
-//! expect-different-screenshot A B [X Y W H]
-//! two saved PNGs differ somewhere (in the rect)
-//! expect-pixel FILE X Y R G B A [TOL]
-//! a saved PNG's pixel, every channel within TOL
-//! load LIBRARY swap in another build of the sketch
-//! reload load the watched library again
-//! await-reload SECONDS run frames until a build replaces the library
-//!
-//! `{name}` is replaced by `--define name=value` from the command line.
-//!
-//! Each line but `frames`, `print`, `console get`, the expectations and
-//! `await-reload` is followed by one frame; `update` gets one call per
-//! frame, live or replayed, so
-//! `console play` then `frames N` replays N recorded frames at the
-//! script's 60 Hz.
+//! through the same routing and frames, on a fixed 60 Hz clock. A line is
+//! a verb of `verbs` and its words; `# comment`; `{name}` is replaced by
+//! `--define name=value` from the command line. `update` gets one call per
+//! frame, live or replayed, so `console play` then `frames N` replays N
+//! recorded frames at the script's 60 Hz.
const std = @import("std");
const c = @import("c");
const abi = @import("abi");
const Host = @import("Host.zig");
const fields = @import("fields.zig");
const memory = @import("memory.zig");
+const Console = @import("Console.zig");
+const Sessions = @import("Sessions.zig");
pub const frame_ns: u64 = std.time.ns_per_s / 60;
/// The most frames `await` plays: a minute.
const await_limit = 60 * 60;
+/// The script's verbs, a row each. A verb with `frame` is followed by one
+/// frame; the `input` verbs are also what a 9P `ctl` takes live (`input`).
+pub const Verb = enum { click, move, down, up, wheel, @"wheel-x", cancel, key, hold, release, type, console, frames, expect, await, print, @"expect-snapshot", @"expect-key", @"expect-log", @"expect-no-log", @"expect-audio", @"expect-no-audio", screenshot, @"expect-same-screenshot", @"expect-different-screenshot", @"expect-pixel", load, reload, @"await-reload", kill, quit };
+pub const Row = struct { args: []const u8 = "", doc: []const u8, frame: bool = false, input: bool = false };
+pub const verbs = std.enums.EnumArray(Verb, Row).init(.{
+ .click = .{ .args = "X Y", .doc = "move there, press and release the left button", .frame = true, .input = true },
+ .move = .{ .args = "X Y", .doc = "a pointer move", .frame = true, .input = true },
+ .down = .{ .args = "X Y", .doc = "the left button down there", .frame = true, .input = true },
+ .up = .{ .args = "X Y", .doc = "the left button up there", .frame = true, .input = true },
+ .wheel = .{ .args = "X Y DELTA", .doc = "a wheel turn", .frame = true, .input = true },
+ .@"wheel-x" = .{ .args = "X Y DELTA", .doc = "a sideways wheel turn", .frame = true, .input = true },
+ .cancel = .{ .doc = "what losing focus sends", .frame = true, .input = true },
+ .key = .{ .args = "NAME", .doc = "press and release a key (`sketch.Key` names)", .frame = true, .input = true },
+ .hold = .{ .args = "NAME", .doc = "a key down until released, for modifiers", .frame = true, .input = true },
+ .release = .{ .args = "NAME", .doc = "a held key up", .frame = true, .input = true },
+ .type = .{ .args = "TEXT", .doc = "text input, as typed into a focused field", .frame = true, .input = true },
+ .console = .{ .args = "LINE", .doc = "a console line (`console get` takes no frame: it only reads); one that fails fails the script", .frame = true },
+ .frames = .{ .args = "N", .doc = "N frames without input" },
+ .expect = .{ .args = "FIELD VALUE [~T]", .doc = "a State field holds VALUE (enums by name or number; numbers within T); FIELD may index arrays and vector lanes, `boids.buffer[3].pos[0]`" },
+ .await = .{ .args = "FIELD VALUE [~T]", .doc = "frames until expect holds, a minute at most" },
+ .print = .{ .args = "FIELD", .doc = "a field's value to stderr (a vector, array or struct: every value in it)" },
+ .@"expect-snapshot" = .{ .args = "NAME", .doc = "live State equals the newest mark NAME, leaf by leaf (padding, and leaves a layout change reset, ignored)" },
+ .@"expect-key" = .{ .args = "WHY FIELD VALUE", .doc = "the newest keyframe of this session taken for WHY (`Sessions.Why`: before_reload, mark...) holds VALUE, read in its own layout" },
+ .@"expect-log" = .{ .args = "TEXT", .doc = "a recent console line contains TEXT" },
+ .@"expect-no-log" = .{ .args = "TEXT", .doc = "no recent console line does" },
+ .@"expect-audio" = .{ .args = "KEY", .doc = "stream KEY has received samples, or voice KEY sounded since the last check of it" },
+ .@"expect-no-audio" = .{ .args = "KEY", .doc = "voice KEY did not sound since the last check" },
+ .screenshot = .{ .args = "FILE", .doc = "save the next frame as PNG", .frame = true },
+ .@"expect-same-screenshot" = .{ .args = "A B [MAX [X Y W H]]", .doc = "two saved PNGs match, every channel within MAX (0), in the rect if given (pixels)" },
+ .@"expect-different-screenshot" = .{ .args = "A B [X Y W H]", .doc = "two saved PNGs differ somewhere (in the rect)" },
+ .@"expect-pixel" = .{ .args = "FILE X Y R G B A [TOL]", .doc = "a saved PNG's pixel, every channel within TOL" },
+ .load = .{ .args = "LIBRARY", .doc = "swap in another build of the sketch", .frame = true },
+ .reload = .{ .doc = "load the watched library again", .frame = true },
+ .@"await-reload" = .{ .args = "SECONDS", .doc = "frames until a build replaces the library" },
+ .kill = .{ .doc = "die by SIGKILL, as a crash would" },
+ .quit = .{ .doc = "end the run" },
+});
+
pub fn run(host: *Host, source: []const u8, defines: []const [2][]const u8) !void {
var arena: std.heap.ArenaAllocator = .init(host.gpa);
defer arena.deinit();
@@ -65,9 +67,9 @@ pub fn run(host: *Host, source: []const u8, defines: []const [2][]const u8) !voi
const line = try substitute(arena.allocator(), std.mem.trim(u8, raw, " \t\r"), defines);
if (line.len == 0 or line[0] == '#') continue;
var words = std.mem.tokenizeAny(u8, line, " \t");
- const command = words.next().?;
+ const verb = std.meta.stringToEnum(Verb, words.next().?);
const rest = std.mem.trim(u8, words.rest(), " \t");
- step(host, arena.allocator(), command, rest, &words, &now) catch |err| {
+ (if (verb) |v| step(host, arena.allocator(), v, rest, &words, &now) else error.UnknownScriptCommand) catch |err| {
failures += 1;
std.debug.print("script:{d}: {s}: {t}\n", .{ number, line, err });
if (err != error.ExpectationFailed) break;
@@ -77,160 +79,210 @@ pub fn run(host: *Host, source: []const u8, defines: []const [2][]const u8) !voi
if (failures > 0) return error.ScriptFailed;
}
-fn step(host: *Host, arena: std.mem.Allocator, command: []const u8, rest: []const u8, words: anytype, now: *u64) !void {
- const eq = std.mem.eql;
- if (eq(u8, command, "click")) {
- const x, const y = try point(words);
- try host.route(.{ .kind = .mouse_move, .time = now.*, .x = x, .y = y, .flags = held(host) });
- try host.route(.{ .kind = .mouse_down, .time = now.*, .x = x, .y = y, .code = 1, .flags = held(host) });
- try host.route(.{ .kind = .mouse_up, .time = now.*, .x = x, .y = y, .code = 1, .flags = held(host) });
- } else if (eq(u8, command, "move") or eq(u8, command, "down") or eq(u8, command, "up")) {
- const x, const y = try point(words);
- const kind: abi.Event.Kind = if (eq(u8, command, "move")) .mouse_move else if (eq(u8, command, "down")) .mouse_down else .mouse_up;
- try host.route(.{ .kind = kind, .time = now.*, .x = x, .y = y, .code = if (kind == .mouse_move) 0 else 1, .flags = held(host) });
- } else if (eq(u8, command, "wheel") or eq(u8, command, "wheel-x")) {
- const x, const y = try point(words);
- const delta = try std.fmt.parseFloat(f32, words.next() orelse return error.ExpectedDelta);
- try host.route(.{ .kind = if (eq(u8, command, "wheel-x")) .wheel_horizontal else .wheel, .time = now.*, .x = x, .y = y, .value = @bitCast(delta), .flags = held(host) });
- } else if (eq(u8, command, "cancel")) {
- try host.route(.{ .kind = .cancel, .time = now.* });
- } else if (eq(u8, command, "key")) {
- const key = std.meta.stringToEnum(abi.Key, rest) orelse return error.UnknownKey;
- try host.route(.{ .kind = .key_down, .time = now.*, .code = @backingInt(key) });
- try host.route(.{ .kind = .key_up, .time = now.*, .code = @backingInt(key) });
- } else if (eq(u8, command, "hold") or eq(u8, command, "release")) {
- const key = std.meta.stringToEnum(abi.Key, rest) orelse return error.UnknownKey;
- try host.route(.{ .kind = if (eq(u8, command, "hold")) .key_down else .key_up, .time = now.*, .code = @backingInt(key) });
- } else if (eq(u8, command, "type")) {
- for (rest) |byte| try host.route(.{ .kind = .text, .time = now.*, .value = byte });
- } else if (eq(u8, command, "console")) {
- // A failing console line fails the script, like a failed expect.
- host.runLine(rest, now.*) catch |err| {
- std.debug.print(" console {s}: {t}\n", .{ rest, err });
- return err;
- };
- if (std.mem.startsWith(u8, rest, "get ")) return;
- } else if (eq(u8, command, "print")) {
- const path = words.next() orelse return error.ExpectedField;
- var buf: [4096]u8 = undefined;
- var w: std.Io.Writer = .fixed(&buf);
- fields.formatPath(host.state.layout, host.live(), path, &w) catch |err| switch (err) {
- error.UnknownField => return error.UnknownField,
- error.WriteFailed => {},
- };
- std.debug.print("{s} = {s}\n", .{ path, w.buffered() });
- return;
- } else if (eq(u8, command, "frames")) {
- const count = try std.fmt.parseInt(usize, rest, 10);
- for (0..count) |_| try advance(host, now);
- return;
- } else if (eq(u8, command, "expect") or eq(u8, command, "await")) {
- const path = words.next() orelse return error.ExpectedField;
- const want, const tolerance = try expected(std.mem.trim(u8, words.rest(), " \t"));
- // Looked up again after each frame: a reload may move the field.
- _ = host.state.layout.find(path) orelse return error.UnknownField;
- // `await` plays frames until the field holds the value, for up to a
- // minute: for waits whose length is the sketch's business.
- if (eq(u8, command, "await")) {
- var waited: usize = 0;
- while (!holds(host, path, want, tolerance) and waited < await_limit) : (waited += 1) try advance(host, now);
- }
- if (!holds(host, path, want, tolerance)) {
- var buf: [128]u8 = undefined;
+/// Routes an input verb's events at `now`, no frame after: a script's
+/// line, or a 9P `ctl` line live.
+pub fn input(host: *Host, verb: Verb, words: *std.mem.TokenIterator(u8, .any), now: u64) !void {
+ const rest = std.mem.trim(u8, words.rest(), " \t");
+ switch (verb) {
+ .click => {
+ const x, const y = try point(words);
+ try host.route(.{ .kind = .mouse_move, .time = now, .x = x, .y = y, .flags = held(host) });
+ try host.route(.{ .kind = .mouse_down, .time = now, .x = x, .y = y, .code = 1, .flags = held(host) });
+ try host.route(.{ .kind = .mouse_up, .time = now, .x = x, .y = y, .code = 1, .flags = held(host) });
+ },
+ .move, .down, .up => {
+ const x, const y = try point(words);
+ const kind: abi.Event.Kind = switch (verb) {
+ .move => .mouse_move,
+ .down => .mouse_down,
+ else => .mouse_up,
+ };
+ try host.route(.{ .kind = kind, .time = now, .x = x, .y = y, .code = if (kind == .mouse_move) 0 else 1, .flags = held(host) });
+ },
+ .wheel, .@"wheel-x" => {
+ const x, const y = try point(words);
+ const delta = try std.fmt.parseFloat(f32, words.next() orelse return error.ExpectedDelta);
+ try host.route(.{ .kind = if (verb == .@"wheel-x") .wheel_horizontal else .wheel, .time = now, .x = x, .y = y, .value = @bitCast(delta), .flags = held(host) });
+ },
+ .cancel => try host.route(.{ .kind = .cancel, .time = now }),
+ .key => {
+ const key = std.meta.stringToEnum(abi.Key, rest) orelse return error.UnknownKey;
+ try host.route(.{ .kind = .key_down, .time = now, .code = @backingInt(key) });
+ try host.route(.{ .kind = .key_up, .time = now, .code = @backingInt(key) });
+ },
+ .hold, .release => {
+ const key = std.meta.stringToEnum(abi.Key, rest) orelse return error.UnknownKey;
+ try host.route(.{ .kind = if (verb == .hold) .key_down else .key_up, .time = now, .code = @backingInt(key) });
+ },
+ .type => for (rest) |byte| try host.route(.{ .kind = .text, .time = now, .value = byte }),
+ else => return error.NotInput,
+ }
+}
+
+fn step(host: *Host, arena: std.mem.Allocator, verb: Verb, rest: []const u8, words: *std.mem.TokenIterator(u8, .any), now: *u64) !void {
+ switch (verb) {
+ .click, .move, .down, .up, .wheel, .@"wheel-x", .cancel, .key, .hold, .release, .type => try input(host, verb, words, now.*),
+ .console => {
+ // A failing console line fails the script, like a failed expect.
+ host.runLine(rest, now.*) catch |err| {
+ std.debug.print(" console {s}: {t}\n", .{ rest, err });
+ return err;
+ };
+ if (std.mem.startsWith(u8, rest, "get ")) return;
+ },
+ .print => {
+ const path = words.next() orelse return error.ExpectedField;
+ var buf: [4096]u8 = undefined;
var w: std.Io.Writer = .fixed(&buf);
fields.formatPath(host.state.layout, host.live(), path, &w) catch |err| switch (err) {
- error.UnknownField => w.writeAll("no such field") catch {},
+ error.UnknownField => return error.UnknownField,
error.WriteFailed => {},
};
- if (tolerance) |t| {
- std.debug.print(" {s}: expected {s} ~{d}, found {s}\n", .{ path, want, t, w.buffered() });
- } else std.debug.print(" {s}: expected {s}, found {s}\n", .{ path, want, w.buffered() });
- return error.ExpectationFailed;
- }
- return;
- } else if (eq(u8, command, "expect-snapshot")) {
- const index = std.fmt.parseInt(usize, rest, 10) catch return error.InvalidSlot;
- if (!host.timeline.bank.hasSnapshot(index)) return error.EmptySnapshot;
- if (!same(host, index)) return error.ExpectationFailed;
- return;
- } else if (eq(u8, command, "expect-log") or eq(u8, command, "expect-no-log")) {
- var found = false;
- for (&host.console.lines) |*l| {
- if (std.mem.indexOf(u8, l.bytes[0..l.len], rest) != null) found = true;
- }
- if (found != eq(u8, command, "expect-log")) {
- std.debug.print(" console log:\n", .{});
- for (&host.console.lines) |*l| std.debug.print(" {s}\n", .{l.bytes[0..l.len]});
- return error.ExpectationFailed;
- }
- return;
- } else if (eq(u8, command, "expect-same-screenshot") or eq(u8, command, "expect-different-screenshot")) {
- const a = words.next() orelse return error.ExpectedFile;
- const b = words.next() orelse return error.ExpectedFile;
- const want_same = eq(u8, command, "expect-same-screenshot");
- const max: u8 = if (!want_same) 0 else if (words.next()) |m| std.fmt.parseInt(u8, m, 10) catch return error.InvalidValue else 0;
- var rect: ?[4]usize = null;
- if (words.next()) |x| {
- var r: [4]usize = undefined;
- r[0] = std.fmt.parseInt(usize, x, 10) catch return error.InvalidRect;
- for (r[1..]) |*v| v.* = std.fmt.parseInt(usize, words.next() orelse return error.InvalidRect, 10) catch return error.InvalidRect;
- rect = r;
- }
- const diff = try comparePng(arena, a, b, max, rect);
- if ((diff.count == 0) != want_same) {
- if (want_same) {
- std.debug.print(" {s} vs {s}: {d} pixels differ by more than {d}, first at {d},{d}\n", .{ a, b, diff.count, max, diff.first[0], diff.first[1] });
- } else std.debug.print(" {s} and {s} are the same\n", .{ a, b });
+ std.debug.print("{s} = {s}\n", .{ path, w.buffered() });
+ },
+ .frames => {
+ const count = try std.fmt.parseInt(usize, rest, 10);
+ for (0..count) |_| try advance(host, now);
+ },
+ .expect, .await => {
+ const path = words.next() orelse return error.ExpectedField;
+ const want, const tolerance = try expected(std.mem.trim(u8, words.rest(), " \t"));
+ // Looked up again after each frame: a reload may move the field.
+ _ = host.state.layout.find(path) orelse return error.UnknownField;
+ // `await` plays frames until the field holds the value, for up to a
+ // minute: for waits whose length is the sketch's business.
+ if (verb == .await) {
+ var waited: usize = 0;
+ while (!holds(host, path, want, tolerance) and waited < await_limit) : (waited += 1) try advance(host, now);
+ }
+ if (!holds(host, path, want, tolerance)) {
+ var buf: [128]u8 = undefined;
+ var w: std.Io.Writer = .fixed(&buf);
+ fields.formatPath(host.state.layout, host.live(), path, &w) catch |err| switch (err) {
+ error.UnknownField => w.writeAll("no such field") catch {},
+ error.WriteFailed => {},
+ };
+ if (tolerance) |t| {
+ std.debug.print(" {s}: expected {s} ~{d}, found {s}\n", .{ path, want, t, w.buffered() });
+ } else std.debug.print(" {s}: expected {s}, found {s}\n", .{ path, want, w.buffered() });
+ return error.ExpectationFailed;
+ }
+ },
+ .@"expect-snapshot" => {
+ const saved = try Console.markState(host, arena, rest);
+ if (!same(host, saved.layout, saved.bytes, rest)) return error.ExpectationFailed;
+ },
+ .@"expect-key" => {
+ const why = std.meta.stringToEnum(Sessions.Why, words.next() orelse "") orelse return error.UnknownWhy;
+ const path = words.next() orelse return error.ExpectedField;
+ const want = std.mem.trim(u8, words.rest(), " \t");
+ const s = &host.sessions;
+ try s.commit(.none);
+ var k = s.keys;
+ while (k > 0) {
+ k -= 1;
+ const key = try s.load(s.session, k);
+ defer key.free(host.gpa);
+ if (key.why != why) continue;
+ const leaf = (try memory.layoutOf(arena, key.layout)).find(path) orelse return error.UnknownField;
+ if (fields.matches(leaf, key.state, want)) return;
+ var buf: [128]u8 = undefined;
+ var w: std.Io.Writer = .fixed(&buf);
+ fields.format(leaf, key.state, &w) catch {};
+ std.debug.print(" {s} keyframe {d}: {s} expected {s}, found {s}\n", .{ @tagName(why), k, path, want, w.buffered() });
+ return error.ExpectationFailed;
+ }
+ std.debug.print(" no {s} keyframe in this session\n", .{@tagName(why)});
return error.ExpectationFailed;
- }
- return;
- } else if (eq(u8, command, "expect-pixel")) {
- const file = words.next() orelse return error.ExpectedFile;
- var n: [7]u8 = .{ 0, 0, 0, 0, 0, 0, 0 };
- var x: usize = 0;
- var y: usize = 0;
- for (0..7) |i| {
- const word = words.next() orelse if (i == 6) break else return error.ExpectedPixel;
- if (i < 2) {
- (if (i == 0) &x else &y).* = std.fmt.parseInt(usize, word, 10) catch return error.ExpectedPixel;
- } else n[i - 2] = std.fmt.parseInt(u8, word, 0) catch return error.ExpectedPixel;
- }
- const tol = n[4];
- const surface = try loadPng(arena, file);
- defer c.SDL_DestroySurface(surface);
- if (x >= surface.*.w or y >= surface.*.h) return error.OutsideScreenshot;
- const p = (@as([*]const u8, @ptrCast(surface.*.pixels.?)) + y * @as(usize, @intCast(surface.*.pitch)) + x * 4)[0..4];
- for (p, n[0..4]) |got, want| if (@max(got, want) - @min(got, want) > tol) {
- std.debug.print(" {s} at {d},{d}: expected {d} {d} {d} {d}, found {d} {d} {d} {d}\n", .{ file, x, y, n[0], n[1], n[2], n[3], p[0], p[1], p[2], p[3] });
- return error.ExpectationFailed;
- };
- return;
- } else if (eq(u8, command, "expect-audio")) {
- const key = try std.fmt.parseInt(u32, rest, 10);
- if (host.input.stream(key).pushed == 0) return error.ExpectationFailed;
- return;
- } else if (eq(u8, command, "screenshot")) {
- if (std.fs.path.dirname(rest)) |dir| try std.Io.Dir.cwd().createDirPath(host.io, dir);
- host.screenshot = try arena.dupeSentinel(u8, rest, 0);
- } else if (eq(u8, command, "load")) {
- try host.load(rest);
- } else if (eq(u8, command, "reload")) {
- try host.reload();
- } else if (eq(u8, command, "await-reload")) {
- const seconds = try std.fmt.parseInt(u64, rest, 10);
- const start = host.reloads;
- const deadline = std.Io.Timestamp.now(host.io, .awake).nanoseconds + @as(i96, seconds) * std.time.ns_per_s;
- while (host.reloads == start) {
- if (std.Io.Timestamp.now(host.io, .awake).nanoseconds > deadline) return error.NoReload;
- try advance(host, now);
- try std.Io.sleep(host.io, .fromMilliseconds(10), .awake);
- }
- return;
- } else if (eq(u8, command, "quit")) {
- host.quit = true;
- return;
- } else return error.UnknownScriptCommand;
- try advance(host, now);
+ },
+ .@"expect-log", .@"expect-no-log" => {
+ var found = false;
+ for (&host.console.lines) |*l| {
+ if (std.mem.indexOf(u8, l.bytes[0..l.len], rest) != null) found = true;
+ }
+ if (found != (verb == .@"expect-log")) {
+ std.debug.print(" console log:\n", .{});
+ for (&host.console.lines) |*l| std.debug.print(" {s}\n", .{l.bytes[0..l.len]});
+ return error.ExpectationFailed;
+ }
+ },
+ .@"expect-same-screenshot", .@"expect-different-screenshot" => {
+ const a = words.next() orelse return error.ExpectedFile;
+ const b = words.next() orelse return error.ExpectedFile;
+ const want_same = verb == .@"expect-same-screenshot";
+ const max: u8 = if (!want_same) 0 else if (words.next()) |m| std.fmt.parseInt(u8, m, 10) catch return error.InvalidValue else 0;
+ var rect: ?[4]usize = null;
+ if (words.next()) |x| {
+ var r: [4]usize = undefined;
+ r[0] = std.fmt.parseInt(usize, x, 10) catch return error.InvalidRect;
+ for (r[1..]) |*v| v.* = std.fmt.parseInt(usize, words.next() orelse return error.InvalidRect, 10) catch return error.InvalidRect;
+ rect = r;
+ }
+ const diff = try comparePng(arena, a, b, max, rect);
+ if ((diff.count == 0) != want_same) {
+ if (want_same) {
+ std.debug.print(" {s} vs {s}: {d} pixels differ by more than {d}, first at {d},{d}\n", .{ a, b, diff.count, max, diff.first[0], diff.first[1] });
+ } else std.debug.print(" {s} and {s} are the same\n", .{ a, b });
+ return error.ExpectationFailed;
+ }
+ },
+ .@"expect-pixel" => {
+ const file = words.next() orelse return error.ExpectedFile;
+ var n: [7]u8 = .{ 0, 0, 0, 0, 0, 0, 0 };
+ var x: usize = 0;
+ var y: usize = 0;
+ for (0..7) |i| {
+ const word = words.next() orelse if (i == 6) break else return error.ExpectedPixel;
+ if (i < 2) {
+ (if (i == 0) &x else &y).* = std.fmt.parseInt(usize, word, 10) catch return error.ExpectedPixel;
+ } else n[i - 2] = std.fmt.parseInt(u8, word, 0) catch return error.ExpectedPixel;
+ }
+ const tol = n[4];
+ const surface = try loadPng(arena, file);
+ defer c.SDL_DestroySurface(surface);
+ if (x >= surface.*.w or y >= surface.*.h) return error.OutsideScreenshot;
+ const p = (@as([*]const u8, @ptrCast(surface.*.pixels.?)) + y * @as(usize, @intCast(surface.*.pitch)) + x * 4)[0..4];
+ for (p, n[0..4]) |got, want| if (@max(got, want) - @min(got, want) > tol) {
+ std.debug.print(" {s} at {d},{d}: expected {d} {d} {d} {d}, found {d} {d} {d} {d}\n", .{ file, x, y, n[0], n[1], n[2], n[3], p[0], p[1], p[2], p[3] });
+ return error.ExpectationFailed;
+ };
+ },
+ .@"expect-audio" => {
+ const key = try std.fmt.parseInt(u32, rest, 10);
+ if (host.input.stream(key).pushed == 0 and !host.audio.sounded(key)) return error.ExpectationFailed;
+ },
+ .@"expect-no-audio" => {
+ if (host.audio.sounded(try std.fmt.parseInt(u32, rest, 10))) return error.ExpectationFailed;
+ },
+ .screenshot => {
+ if (std.fs.path.dirname(rest)) |dir| try std.Io.Dir.cwd().createDirPath(host.io, dir);
+ host.screenshot = try arena.dupeSentinel(u8, rest, 0);
+ },
+ .load => {
+ try host.load(rest);
+ },
+ .reload => {
+ try host.reload();
+ },
+ .@"await-reload" => {
+ const seconds = try std.fmt.parseInt(u64, rest, 10);
+ const start = host.reloads;
+ const deadline = std.Io.Timestamp.now(host.io, .awake).nanoseconds + @as(i96, seconds) * std.time.ns_per_s;
+ while (host.reloads == start) {
+ if (std.Io.Timestamp.now(host.io, .awake).nanoseconds > deadline) return error.NoReload;
+ try advance(host, now);
+ try std.Io.sleep(host.io, .fromMilliseconds(10), .awake);
+ }
+ },
+ .kill => {
+ // A crash, for tests of what survives one: SIGKILL, no cleanup.
+ _ = std.os.linux.kill(std.os.linux.getpid(), .KILL);
+ },
+ .quit => {
+ host.quit = true;
+ },
+ }
+ if (verbs.get(verb).frame) try advance(host, now);
}
/// The modifiers `hold` has down, for a pointer event's `flags`.
@@ -258,15 +310,14 @@ fn holds(host: *Host, path: []const u8, want: []const u8, tolerance: ?f64) bool
return @abs(value - target) <= t;
}
-/// Live state against snapshot `index`, leaf by leaf; prints the first few
-/// differences.
-fn same(host: *Host, index: usize) bool {
+/// Live state against mark `name`'s (`saved`, taken in layout `from`), leaf
+/// by leaf over the leaves migration kept; prints the first few differences.
+fn same(host: *Host, from: memory.Layout, saved: []const u8, name: []const u8) bool {
const layout = host.state.layout;
const live = host.live();
- const saved = host.timeline.bank.slot(index);
var count: usize = 0;
for (layout.fields) |leaf| {
- if (leaf.whole()) continue;
+ if (leaf.whole() or (from.hash != layout.hash and !memory.keeps(from, leaf))) continue;
var it = leaf.elements();
while (it.next()) |offset| {
if (std.mem.eql(u8, live[offset..][0..leaf.size], saved[offset..][0..leaf.size])) continue;
@@ -277,7 +328,7 @@ fn same(host: *Host, index: usize) bool {
leaf.name(offset, &w) catch {};
w.writeAll(": live ") catch {};
fields.format(leaf.at(offset), live, &w) catch {};
- w.print(", snapshot {d} ", .{index}) catch {};
+ w.print(", snapshot {s} ", .{name}) catch {};
fields.format(leaf.at(offset), saved, &w) catch {};
std.debug.print(" {s}\n", .{w.buffered()});
}
diff --git a/src/host/state_files.zig b/src/host/state_files.zig
new file mode 100644
index 0000000..ed796c9
--- /dev/null
+++ b/src/host/state_files.zig
@@ -0,0 +1,303 @@
+//! The State as files: a directory per struct and per array, a file per
+//! value, `state/tracker/songs/3/bpm`. An array of scalars (a vector's
+//! lanes, `talk.text`) is one file, its values blank-separated; an array
+//! of arrays is a directory of such rows, so a file is always one value or
+//! one row, the run of values one `set` names. Everything here reads a
+//! `(Layout, bytes)` alone: the running host's, the save's newest State,
+//! or a sketch's defaults.
+//!
+//! A node names a leaf of the layout (its first under a directory), how
+//! many names deep it is, and the offset of the element it stands for:
+//! the indices on its way, every later one zero. Nodes have bit 62 set;
+//! bit 63 is the sketch's (control.zig).
+const std = @import("std");
+const memory = @import("memory.zig");
+const fields = @import("fields.zig");
+const Layout = memory.Layout;
+const Leaf = Layout.Leaf;
+
+pub const Node = packed struct(u64) {
+ offset: u40 = 0,
+ depth: u6 = 0,
+ leaf: u16 = 0,
+ state: u1 = 1,
+ sketch: u1 = 0,
+};
+
+/// `state/` itself.
+pub const root: Node = .{};
+
+/// The names of a leaf's pattern: a field's name, or `[]` for an index.
+const Pieces = struct {
+ rest: []const u8,
+
+ fn next(p: *Pieces) ?[]const u8 {
+ if (p.rest.len > 0 and p.rest[0] == '.') p.rest = p.rest[1..];
+ if (p.rest.len == 0) return null;
+ const end = if (std.mem.startsWith(u8, p.rest, "[]")) 2 else std.mem.indexOfAny(u8, p.rest, ".[") orelse p.rest.len;
+ defer p.rest = p.rest[end..];
+ return p.rest[0..end];
+ }
+};
+
+/// How deep a leaf's file is: its names, an innermost index not counted
+/// (a row of scalars is one file).
+fn fileDepth(leaf: Leaf) usize {
+ var p: Pieces = .{ .rest = leaf.path };
+ var n: usize = 0;
+ while (p.next()) |_| n += 1;
+ return if (std.mem.endsWith(u8, leaf.path, "[]")) n - 1 else n;
+}
+
+/// Where `leaf` is under `dir`: its offset at the directory's indices (the
+/// rest zero), and how many of its dimensions they used; null when it is
+/// not under it.
+fn under(layout: Layout, dir: Node, leaf: Leaf) ?struct { offset: usize, dim: usize } {
+ if (leaf.kind == .array or fileDepth(leaf) < dir.depth) return null;
+ if (dir.depth == 0) return .{ .offset = leaf.offset, .dim = 0 };
+ const own = layout.fields[dir.leaf];
+ var a: Pieces = .{ .rest = own.path };
+ var b: Pieces = .{ .rest = leaf.path };
+ var rest: usize = @intCast(dir.offset -| own.offset);
+ var dim: usize = 0;
+ var offset: usize = leaf.offset;
+ for (0..dir.depth) |_| {
+ const x = a.next() orelse return null;
+ if (!std.mem.eql(u8, x, b.next() orelse return null)) return null;
+ if (x[0] != '[') continue;
+ const index = rest / own.dims[dim].stride;
+ rest %= own.dims[dim].stride;
+ if (index >= leaf.dims[dim].count) return null;
+ offset += index * leaf.dims[dim].stride;
+ dim += 1;
+ }
+ return .{ .offset = offset, .dim = dim };
+}
+
+/// The name a leaf has `depth` names down.
+fn pieceAt(leaf: Leaf, depth: usize) []const u8 {
+ var p: Pieces = .{ .rest = leaf.path };
+ for (0..depth) |_| _ = p.next();
+ return p.next().?;
+}
+
+/// Whether `node` still names something in `layout` (a reload may have
+/// changed it under an open fid).
+pub fn valid(layout: Layout, node: Node) bool {
+ if (node.depth == 0) return true;
+ if (node.leaf >= layout.fields.len) return false;
+ const leaf = layout.fields[node.leaf];
+ return leaf.kind != .array and node.depth <= fileDepth(leaf) and node.offset >= leaf.offset and node.offset < layout.size;
+}
+
+pub fn isDir(layout: Layout, node: Node) bool {
+ return node.depth == 0 or node.depth < fileDepth(layout.fields[node.leaf]);
+}
+
+/// The child of directory `dir` called `child`.
+pub fn lookup(layout: Layout, dir: Node, child: []const u8) ?Node {
+ for (layout.fields, 0..) |leaf, j| {
+ const at = under(layout, dir, leaf) orelse continue;
+ if (fileDepth(leaf) == dir.depth) continue;
+ const piece = pieceAt(leaf, dir.depth);
+ var offset = at.offset;
+ if (piece[0] == '[') {
+ if (child.len == 0 or !std.ascii.isDigit(child[0])) return null;
+ const index = std.fmt.parseInt(u32, child, 10) catch return null;
+ if (index >= leaf.dims[at.dim].count) return null;
+ offset += index * leaf.dims[at.dim].stride;
+ } else if (!std.mem.eql(u8, piece, child)) continue;
+ return .{ .leaf = @intCast(j), .depth = dir.depth + 1, .offset = @intCast(offset) };
+ }
+ return null;
+}
+
+/// The entries of directory `dir` from the `from`-th, as cloud9's readdir
+/// records (`node:u64le dir:u8 len:u8 name`), as many as `out` holds: the
+/// bytes written.
+pub fn readdir(layout: Layout, dir: Node, from: u64, out: []u8) usize {
+ var used: usize = 0;
+ var index: u64 = 0;
+ var last: []const u8 = "";
+ for (layout.fields, 0..) |leaf, j| {
+ const at = under(layout, dir, leaf) orelse continue;
+ if (fileDepth(leaf) == dir.depth) continue;
+ const piece = pieceAt(leaf, dir.depth);
+ if (std.mem.eql(u8, piece, last)) continue;
+ last = piece;
+ const is_dir = fileDepth(leaf) > dir.depth + 1;
+ const count = if (piece[0] == '[') leaf.dims[at.dim].count else 1;
+ for (0..count) |i| {
+ defer index += 1;
+ if (index < from) continue;
+ var buf: [16]u8 = undefined;
+ const text = if (piece[0] == '[') std.fmt.bufPrint(&buf, "{d}", .{i}) catch unreachable else piece;
+ if (used + 10 + text.len > out.len) return used;
+ const offset = at.offset + if (piece[0] == '[') i * leaf.dims[at.dim].stride else 0;
+ const node: Node = .{ .leaf = @intCast(j), .depth = dir.depth + 1, .offset = @intCast(offset) };
+ std.mem.writeInt(u64, out[used..][0..8], @bitCast(node), .little);
+ out[used + 8] = @intFromBool(is_dir);
+ out[used + 9] = @intCast(text.len);
+ @memcpy(out[used + 10 ..][0..text.len], text);
+ used += 10 + text.len;
+ }
+ }
+ return used;
+}
+
+/// The row of scalars at a file node: its first element and its length
+/// and stride; null for a file of one value.
+fn rowOf(layout: Layout, node: Node) ?struct { first: Leaf, count: usize, stride: usize } {
+ const leaf = layout.fields[node.leaf];
+ if (!std.mem.endsWith(u8, leaf.path, "[]") or node.depth != fileDepth(leaf)) return null;
+ const d = leaf.dims[leaf.dims.len - 1];
+ return .{ .first = leaf.at(node.offset), .count = d.count, .stride = d.stride };
+}
+
+/// A file's value, as `get` shows one value, a row's blank-separated,
+/// and a newline.
+pub fn read(layout: Layout, bytes: []const u8, node: Node, w: *std.Io.Writer) std.Io.Writer.Error!void {
+ if (rowOf(layout, node)) |row| {
+ for (0..row.count) |i| {
+ if (i > 0) try w.writeByte(' ');
+ try fields.format(row.first.at(row.first.offset + i * row.stride), bytes, w);
+ }
+ } else try fields.format(layout.fields[node.leaf].at(node.offset), bytes, w);
+ try w.writeByte('\n');
+}
+
+/// The path `get` and `set` take for a node: `tracker.songs[3].bpm`, and
+/// for a row the array's (`talk.text`).
+pub fn path(layout: Layout, node: Node, w: *std.Io.Writer) std.Io.Writer.Error!void {
+ const leaf = layout.fields[node.leaf];
+ var p: Pieces = .{ .rest = leaf.path };
+ var rest: usize = @intCast(node.offset - leaf.offset);
+ var dim: usize = 0;
+ for (0..node.depth) |k| {
+ const piece = p.next().?;
+ if (piece[0] == '[') {
+ try w.print("[{d}]", .{rest / leaf.dims[dim].stride});
+ rest %= leaf.dims[dim].stride;
+ dim += 1;
+ } else try w.print("{s}{s}", .{ if (k == 0) "" else ".", piece });
+ }
+}
+
+/// Whether `set` takes the file: numbers, bools and enums.
+pub fn writable(layout: Layout, node: Node) bool {
+ return switch (layout.fields[node.leaf].kind) {
+ .int, .uint, .float, .bool, .@"enum" => true,
+ else => false,
+ };
+}
+
+/// A README line for every file of the layout: its path, `<n>` for an
+/// index, and what it holds.
+pub fn readme(layout: Layout, w: *std.Io.Writer) std.Io.Writer.Error!void {
+ for (layout.fields) |leaf| {
+ if (leaf.kind == .array) continue;
+ var line: [256]u8 = undefined;
+ var lw: std.Io.Writer = .fixed(&line);
+ var p: Pieces = .{ .rest = leaf.path };
+ const depth = fileDepth(leaf);
+ lw.writeAll("state") catch {};
+ for (0..depth) |_| {
+ const piece = p.next().?;
+ lw.print("/{s}", .{if (piece[0] == '[') "<n>" else piece}) catch {};
+ }
+ const row = std.mem.endsWith(u8, leaf.path, "[]");
+ try w.print("{s}", .{lw.buffered()});
+ try w.splatByteAll(' ', @max(1, 41 -| lw.buffered().len));
+ if (row) try w.print("{d} ", .{leaf.dims[leaf.dims.len - 1].count});
+ switch (leaf.kind) {
+ .int, .uint, .float => try w.print("{s}{d}", .{ switch (leaf.kind) {
+ .int => "i",
+ .uint => "u",
+ else => "f",
+ }, leaf.size * 8 }),
+ .bool => try w.writeAll("bool"),
+ .@"enum" => {
+ var tags = std.mem.tokenizeScalar(u8, leaf.tags, ',');
+ var first = true;
+ while (tags.next()) |pair| : (first = false) try w.print("{s}.{s}", .{ if (first) "" else " ", pair[0 .. std.mem.indexOfScalar(u8, pair, '=') orelse pair.len] });
+ },
+ else => try w.print("{d} bytes, read-only", .{leaf.size}),
+ }
+ if (row) try w.writeAll(", blank-separated");
+ try w.writeByte('\n');
+ }
+}
+
+const testing = std.testing;
+
+fn walk(layout: Layout, to: []const u8) ?Node {
+ var node = root;
+ var names = std.mem.tokenizeScalar(u8, to, '/');
+ while (names.next()) |n| node = lookup(layout, node, n) orelse return null;
+ return node;
+}
+
+/// The names in a directory, a blank after each, a slash after a directory's.
+fn ls(layout: Layout, dir: Node, buf: []u8) []const u8 {
+ var records: [4096]u8 = undefined;
+ const bytes = records[0..readdir(layout, dir, 0, &records)];
+ var w: std.Io.Writer = .fixed(buf);
+ var i: usize = 0;
+ while (i < bytes.len) : (i += 10 + bytes[i + 9]) {
+ const node: Node = @bitCast(std.mem.readInt(u64, bytes[i..][0..8], .little));
+ // Each entry is what a lookup of its name answers.
+ const text = bytes[i + 10 ..][0..bytes[i + 9]];
+ std.debug.assert(lookup(layout, dir, text).? == node);
+ w.print("{s}{s} ", .{ text, if (bytes[i + 8] != 0) "/" else "" }) catch {};
+ }
+ return w.buffered();
+}
+
+test "the State as files: a directory per struct and array, a file per value or row" {
+ const S = struct {
+ scene: enum(u8) { room, street } = .street,
+ talk: struct { text: [4]u8 = .{ 104, 105, 0, 0 }, len: u8 = 2 } = .{},
+ songs: [2]struct { bpm: u16 = 120, patterns: [2][3]struct { pitch: u8 = 0, velocity: u8 = 0 } = @splat(@splat(.{})) } = @splat(.{}),
+ grid: [2][3]i16 = @splat(@splat(0)),
+ pos: @Vector(2, f32) = .{ 250, 3 },
+ };
+ var arena: std.heap.ArenaAllocator = .init(testing.allocator);
+ defer arena.deinit();
+ const layout = try Layout.copy(arena.allocator(), @import("abi").layout.of(S, .state));
+ var s: S = .{};
+ s.songs[1].patterns[1][2].pitch = 64;
+ s.grid[1] = .{ 1, -2, 3 };
+ const bytes = std.mem.asBytes(&s);
+ var buf: [256]u8 = undefined;
+ try testing.expectEqualStrings("scene talk/ songs/ grid/ pos ", ls(layout, root, &buf));
+ try testing.expectEqualStrings("text len ", ls(layout, walk(layout, "talk").?, &buf));
+ try testing.expectEqualStrings("0/ 1/ ", ls(layout, walk(layout, "songs").?, &buf));
+ try testing.expectEqualStrings("bpm patterns/ ", ls(layout, walk(layout, "songs/1").?, &buf));
+ try testing.expectEqualStrings("0/ 1/ 2/ ", ls(layout, walk(layout, "songs/1/patterns/1").?, &buf));
+ try testing.expectEqualStrings("0 1 ", ls(layout, walk(layout, "grid").?, &buf));
+ const cases = [_][3][]const u8{
+ .{ "scene", "scene", ".street\n" },
+ .{ "talk/text", "talk.text", "104 105 0 0\n" },
+ .{ "songs/1/bpm", "songs[1].bpm", "120\n" },
+ .{ "songs/1/patterns/1/2/pitch", "songs[1].patterns[1][2].pitch", "64\n" },
+ .{ "grid/1", "grid[1]", "1 -2 3\n" },
+ .{ "pos", "pos", "250 3\n" },
+ };
+ for (cases) |case| {
+ const node = walk(layout, case[0]).?;
+ try testing.expect(!isDir(layout, node) and valid(layout, node) and writable(layout, node));
+ var w: std.Io.Writer = .fixed(&buf);
+ try path(layout, node, &w);
+ try testing.expectEqualStrings(case[1], w.buffered());
+ w = .fixed(&buf);
+ try read(layout, bytes, node, &w);
+ try testing.expectEqualStrings(case[2], w.buffered());
+ }
+ for ([_][]const u8{ "nope", "songs/2", "songs/x", "songs/01x", "grid/1/0", "scene/x", "talk/text/0" }) |bad| try testing.expect(walk(layout, bad) == null);
+ var out: std.Io.Writer.Allocating = .init(testing.allocator);
+ defer out.deinit();
+ try readme(layout, &out.writer);
+ try testing.expect(std.mem.indexOf(u8, out.written(), "state/scene .room .street\n") != null);
+ try testing.expect(std.mem.indexOf(u8, out.written(), "state/songs/<n>/patterns/<n>/<n>/pitch u8\n") != null);
+ try testing.expect(std.mem.indexOf(u8, out.written(), "state/grid/<n> 3 i16, blank-separated\n") != null);
+}
diff --git a/src/host/timeline.zig b/src/host/timeline.zig
index b52c74d..e755433 100644
--- a/src/host/timeline.zig
+++ b/src/host/timeline.zig
@@ -1,47 +1,18 @@
-//! Snapshots, input recordings and replay: generic over state bytes and
-//! `abi.Event`s, so any sketch gets time travel for free.
+//! Clips and replay: generic over state bytes and `abi.Event`s, so any
+//! sketch gets time travel for free.
//!
//! Playback is host state, not sketch state: wall clocks, modes and cursors
//! must not contaminate byte comparisons between two runs of a sketch.
//!
-//! Recordings are frames: each frame's events, then its `tick`. Playback,
-//! seek and step only ever stop between frames, and `frames` cuts a run of
-//! events into them, so `update` sees exactly the frames it saw live, one
-//! call each.
+//! A clip is whole frames of a session (Sessions.zig) and the keyframe they
+//! start from: each frame's events, then its `tick`. Playback, seek and step
+//! only ever stop between frames, and `frames` cuts a run of events into
+//! them, so `update` sees exactly the frames it saw live, one call each,
+//! at the times it saw.
const std = @import("std");
-const posix = std.posix;
const abi = @import("abi");
const memory = @import("memory.zig");
-
-pub const recording_len = 4 * 1024 * 1024;
-pub const recording_count = 16;
-pub const recordings_len = recording_len * recording_count;
-const recording_magic = 0x52454305;
-pub const capacity = (recording_len - 32) / @sizeOf(abi.Event);
-
-pub const Recording = extern struct {
- duration: u64,
- count: u32,
- snapshot: u32,
- magic: u32,
- /// The build that recorded it (`build`, two halves), 0 when unknown.
- build_low: u32,
- build_high: u32,
- reserved: u32,
- events: [capacity]abi.Event,
- slack: [recording_len - 32 - capacity * @sizeOf(abi.Event)]u8,
-
- pub fn slice(r: *const Recording) []const abi.Event {
- return r.events[0..r.count];
- }
- pub fn build(r: *const Recording) u64 {
- return @as(u64, r.build_high) << 32 | r.build_low;
- }
- /// Events up to the end of the last whole frame.
- pub fn whole(r: *const Recording) usize {
- return frameStart(r.slice(), r.count);
- }
-};
+const Sessions = @import("Sessions.zig");
/// The largest frame boundary at or before `index`: 0, or just after a tick.
pub fn frameStart(events: []const abi.Event, index: usize) usize {
@@ -72,119 +43,92 @@ pub const Frames = struct {
}
};
-comptime {
- std.debug.assert(@sizeOf(Recording) == recording_len);
-}
-
-/// Snapshot slots of a state file, and the recordings that start from them.
-pub const Bank = struct {
- state: *memory.StateFile,
- inputs: []align(memory.page) u8,
-
- pub fn slot(self: Bank, index: usize) []u8 {
- return self.state.slot(index);
- }
- pub fn recording(self: Bank, index: usize) *Recording {
- std.debug.assert(index < recording_count);
- return @ptrCast(@alignCast(self.inputs[index * recording_len ..].ptr));
- }
- pub fn hasSnapshot(self: Bank, index: usize) bool {
- return index > 0 and index < memory.slot_count and self.state.used(index);
- }
- pub fn save(self: Bank, index: usize) void {
- std.debug.assert(index > 0 and index < memory.slot_count);
- for (0..recording_count) |i| {
- const r = self.recording(i);
- if (r.snapshot == index) r.magic = 0;
- }
- @memcpy(self.slot(index), self.slot(0));
- self.state.markUsed(index, true);
- }
- pub fn restore(self: Bank, index: usize) !void {
- if (!self.hasSnapshot(index)) return error.EmptySnapshot;
- @memcpy(self.slot(0), self.slot(index));
- }
- pub fn get(self: Bank, index: usize) !*Recording {
- const r = self.recording(index);
- if (r.magic != recording_magic or r.count > capacity or !self.hasSnapshot(r.snapshot)) return error.EmptyRecording;
- return r;
- }
- /// Leaf by leaf (`memory.compare`): padding never differs.
- pub fn compare(self: Bank, a: usize, b: usize) memory.Diff {
- return memory.compare(self.state.layout, self.slot(a), self.slot(b));
- }
-};
-
pub const Timeline = struct {
- bank: Bank,
+ gpa: std.mem.Allocator,
+ /// Live State.
+ state: *memory.State,
+ /// The running sketch's: a restore starts from its defaults.
+ defaults: *const fn (abi.Memory, [*]u8) callconv(.c) void,
mode: abi.Mode = .live,
- selected: usize = 0,
+ /// The clip loaded: its start keyframe and its frames, `gpa`'s.
+ key: ?Sessions.Loaded = null,
+ events: std.ArrayList(abi.Event) = .empty,
+ /// The clip's first tick: positions count from it.
+ base: u64 = 0,
cursor: usize = 0,
position: u64 = 0,
clock: u64 = 0,
- /// Set whenever live state is restored from a snapshot, for the host
+ /// Set whenever live state is restored from a keyframe, for the host
/// to reset the input state that went with the old bytes.
restored: bool = false,
+ /// Frames fed since the keyframe was restored.
+ fed: u64 = 0,
+ /// A past session played (`play session`), not a clip: its index, and
+ /// its keyframes after the one played from, checked against the replay
+ /// as their frames are reached (Host.resync).
+ session: ?u64 = null,
+ checks: std.ArrayList(Check) = .empty,
+ next_check: usize = 0,
- /// Restores a snapshot into live state.
- pub fn restore(self: *Timeline, index: usize) !void {
- try self.bank.restore(index);
+ pub const Check = struct {
+ frame: u64,
+ key: u64,
+ /// Taken of what `update` made (periodic, a mark, before a reload,
+ /// at exit): a replay must match it. Other keyframes follow a jump
+ /// the log does not hold, and are restored without a word.
+ observed: bool,
+ };
+
+ pub fn deinit(self: *Timeline) void {
+ if (self.key) |k| k.free(self.gpa);
+ self.key = null;
+ self.events.deinit(self.gpa);
+ self.checks.deinit(self.gpa);
+ }
+
+ /// Puts a keyframe, in whatever layout it was taken, into live state.
+ pub fn restore(self: *Timeline, key: Sessions.Loaded) !void {
+ var arena: std.heap.ArenaAllocator = .init(self.gpa);
+ defer arena.deinit();
+ _ = try memory.restore(arena.allocator(), key.layout, key.state, self.state.layout, self.state.live(), self.defaults);
self.restored = true;
+ self.fed = 0;
+ self.next_check = 0;
+ }
+
+ /// Makes a clip, its start keyframe and its frames, the one played; both
+ /// become the timeline's.
+ pub fn load(self: *Timeline, key: Sessions.Loaded, events: std.ArrayList(abi.Event)) void {
+ self.deinit();
+ self.key = key;
+ self.events = events;
+ self.session = null;
+ self.checks = .empty;
+ var it = frames(events.items);
+ const first = it.next();
+ self.base = if (first) |f| f[f.len - 1].time else 0;
+ }
+
+ fn at(self: *const Timeline, i: usize) u64 {
+ return self.events.items[i].time -| self.base;
+ }
+
+ /// The last whole frame's tick, from the first.
+ fn duration(self: *const Timeline) u64 {
+ const end = frameStart(self.events.items, self.events.items.len);
+ return if (end == 0) 0 else self.at(end - 1);
}
- /// `build` identifies the code recording (0: unknown); `play` warns
- /// when it differs.
- pub fn startRecording(self: *Timeline, index: usize, snapshot: usize, now: u64, build: u64) !void {
- // An unused snapshot captures the current state; an existing one is
- // restored, so several recordings can branch from exactly those bytes.
- if (!self.bank.hasSnapshot(snapshot)) self.bank.save(snapshot);
- try self.restore(snapshot);
- const r = self.bank.recording(index);
- @memset(std.mem.asBytes(r)[0..32], 0);
- r.magic = recording_magic;
- r.snapshot = @intCast(snapshot);
- r.build_low = @truncate(build);
- r.build_high = @truncate(build >> 32);
- self.selected = index;
+ pub fn startRecording(self: *Timeline) void {
self.cursor = 0;
self.position = 0;
- self.clock = now;
self.mode = .recording;
}
- /// Records one frame (its events, then its tick) and rewrites their
- /// times as recorded, so live `update` sees exactly what a replay will.
- /// A frame that does not fit ends the recording before it.
- pub fn capture(self: *Timeline, frame: []abi.Event) !void {
- if (self.mode != .recording) return;
- const r = self.bank.recording(self.selected);
- if (frame.len > capacity - r.count) {
- self.mode = .live;
- return error.RecordingFull;
- }
- for (frame) |*e| {
- // Queued events can predate the start command. Keep insertion
- // order and nondecreasing times, including several events at the
- // same timestamp.
- e.time = @max(e.time -| self.clock, r.duration);
- r.events[r.count] = e.*;
- r.count += 1;
- r.duration = e.time;
- }
- self.position = r.duration;
- self.cursor = r.count;
- }
- pub fn stop(self: *Timeline, now: u64) void {
- if (self.mode == .recording) {
- const r = self.bank.recording(self.selected);
- r.duration = @max(r.duration, now -| self.clock);
- self.position = r.duration;
- }
+ pub fn stop(self: *Timeline) void {
self.mode = .live;
}
- pub fn play(self: *Timeline, index: usize, now: u64) !void {
- const r = try self.bank.get(index);
- try self.restore(r.snapshot);
- self.selected = index;
+ pub fn play(self: *Timeline, now: u64) !void {
+ try self.restore(self.key orelse return error.EmptyRecording);
self.cursor = 0;
self.position = 0;
self.clock = now;
@@ -203,35 +147,33 @@ pub const Timeline = struct {
/// due). Feed them to the same `update` that live input goes through.
pub fn tick(self: *Timeline, now: u64) []const abi.Event {
if (self.mode != .playing) return &.{};
- const r = self.bank.recording(self.selected);
- self.position = @min(r.duration, self.position +| (now -| self.clock));
+ const end = self.duration();
+ self.position = @min(end, self.position +| (now -| self.clock));
self.clock = now;
const start = self.cursor;
var i = self.cursor;
- while (i < r.count and r.events[i].time <= self.position) : (i += 1) {
- if (r.events[i].kind == .tick) self.cursor = i + 1;
+ while (i < self.events.items.len and self.at(i) <= self.position) : (i += 1) {
+ if (self.events.items[i].kind == .tick) self.cursor = i + 1;
}
- if (self.position == r.duration) self.mode = .paused;
- return r.events[start..self.cursor];
+ if (self.position == end) self.mode = .paused;
+ return self.events.items[start..self.cursor];
}
- /// Restores the snapshot and returns the frames that make up the first
- /// `count` events (rounded down to a whole frame) to replay, so seeking
- /// backwards works too.
+ /// Restores the start keyframe and returns the frames that make up the
+ /// first `count` events (rounded down to a whole frame) to replay, so
+ /// seeking backwards works too.
pub fn seekCount(self: *Timeline, count: usize) ![]const abi.Event {
- const r = try self.bank.get(self.selected);
- try self.restore(r.snapshot);
- self.cursor = frameStart(r.slice(), count);
- self.position = if (self.cursor == 0) 0 else r.events[self.cursor - 1].time;
+ try self.restore(self.key orelse return error.EmptyRecording);
+ self.cursor = frameStart(self.events.items, count);
+ self.position = if (self.cursor == 0) 0 else self.at(self.cursor - 1);
self.mode = .paused;
- return r.events[0..self.cursor];
+ return self.events.items[0..self.cursor];
}
- /// To the last frame whose tick is at or before `time`.
+ /// To the last frame whose tick is at or before `time` into the clip.
pub fn seekTime(self: *Timeline, time: u64) ![]const abi.Event {
- const r = try self.bank.get(self.selected);
- const position = @min(time, r.duration);
+ const position = @min(time, self.duration());
var count: usize = 0;
- for (r.slice(), 0..) |e, i| {
- if (e.time > position) break;
+ for (self.events.items, 0..) |e, i| {
+ if (self.at(i) > position) break;
if (e.kind == .tick) count = i + 1;
}
const events = try self.seekCount(count);
@@ -240,13 +182,12 @@ pub const Timeline = struct {
}
/// Moves by `steps` frames, forwards or back.
pub fn step(self: *Timeline, steps: i64) ![]const abi.Event {
- const r = try self.bank.get(self.selected);
- const events = r.slice();
+ const events = self.events.items;
var cursor = frameStart(events, self.cursor);
var remaining = @abs(steps);
+ const end = frameStart(events, events.len);
while (remaining > 0) : (remaining -= 1) {
if (steps > 0) {
- const end = r.whole();
if (cursor == end) break;
cursor += 1;
while (cursor < end and events[cursor - 1].kind != .tick) cursor += 1;
@@ -259,62 +200,42 @@ pub const Timeline = struct {
}
};
-/// Maps the recordings file next to a state file, creating it when missing.
-pub fn mapRecordings(path: []const u8) ![]align(memory.page) u8 {
- const fd = try posix.openat(posix.AT.FDCWD, path, .{ .ACCMODE = .RDWR, .CREAT = true }, 0o600);
- defer _ = posix.system.close(fd);
- if (try memory.fileSize(fd) != recordings_len) switch (posix.errno(posix.system.ftruncate(fd, recordings_len))) {
- .SUCCESS => {},
- else => |err| return posix.unexpectedErrno(err),
+test "frames are whole: input waits for its tick, in playback, seek and step" {
+ const gpa = std.testing.allocator;
+ // Live State: 8 bytes, no fields.
+ const D = struct {
+ fn f(_: abi.Memory, _: [*]u8) callconv(.c) void {}
};
- return memory.mapFile(fd, recordings_len, .{ .READ = true, .WRITE = true });
-}
-
-test "frames are whole: input waits for its tick, live and in playback" {
- var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
- defer arena.deinit();
- const a = arena.allocator();
- // A bank on plain memory: one slot of 8 bytes, snapshot 1 used.
- var file: memory.StateFile = undefined;
- file.map = try a.alignedAlloc(u8, .fromByteUnits(memory.page), memory.header_len + memory.slot_count * memory.page);
- @memset(file.map, 0);
- file.header().* = .{ .size = 8, .alignment = 1, .hash = 1, .stride = memory.page, .used = 0b11, .field_count = 0, .strings_len = 0 };
- file.layout = .{};
- const inputs = try a.alignedAlloc(u8, .fromByteUnits(memory.page), recording_len);
- @memset(inputs, 0);
- var t: Timeline = .{ .bank = .{ .state = &file, .inputs = inputs } };
- // Frame k: a move at 10k ms, its tick at 10k + 5 ms; then a move with
- // no tick (a frame cut off).
- try t.startRecording(0, 1, 1000, 7);
- try std.testing.expect(t.restored);
+ var state: memory.State = .init(gpa);
+ defer state.deinit(gpa);
+ _ = try state.adopt(gpa, .{ .size = 8, .alignment = 1, .hash = 1, .fields = &.{} }, D.f);
+ var t: Timeline = .{ .gpa = gpa, .state = &state, .defaults = D.f };
+ defer t.deinit();
+ // Frame k: a move at 10k ms, its tick 5 ms later; then a move with no
+ // tick (a frame cut off).
+ var events: std.ArrayList(abi.Event) = .empty;
for (0..4) |k| {
- var frame = [_]abi.Event{
- .{ .kind = .mouse_move, .time = 1000 + k * 10_000_000, .x = @floatFromInt(k) },
- abi.Event.tick(1000 + k * 10_000_000 + 5_000_000, 16_666_667),
- };
- try t.capture(&frame);
- // Live update sees the recorded times.
- try std.testing.expectEqual(@as(u64, k * 10_000_000 + 5_000_000), frame[1].time);
- try std.testing.expectEqual(abi.Event.tick(0, 16_666_667).tickDt(), frame[1].tickDt());
+ try events.append(gpa, .{ .kind = .mouse_move, .time = 1000 + k * 10_000_000, .x = @floatFromInt(k) });
+ try events.append(gpa, abi.Event.tick(1000 + k * 10_000_000 + 5_000_000, 16_666_667));
}
- const r = t.bank.recording(0);
- r.events[r.count] = .{ .kind = .mouse_move, .time = 40_000_000 };
- r.count += 1;
- t.stop(1000 + 41_000_000);
- try std.testing.expectEqual(@as(u64, 7), r.build());
+ try events.append(gpa, .{ .kind = .mouse_move, .time = 40_000_000 });
+ const key: Sessions.Loaded = .{ .frame = 0, .batch = 0, .why = .mark, .time = 0, .stretch = 0, .build = 7, .state = try gpa.dupe(u8, &@as([8]u8, @splat(0))), .line = try gpa.dupe(u8, ""), .source = try gpa.dupe(u8, ""), .layout = try gpa.dupe(u8, state.header) };
+ t.load(key, events);
- try t.play(0, 0);
+ try t.play(0);
+ try std.testing.expect(t.restored);
var delivered: usize = 0;
// Every moment between 0 and the end, 1 ms apart.
var now: u64 = 0;
while (t.mode == .playing) : (now += 1_000_000) {
- const events = t.tick(now);
- if (events.len == 0) continue;
- try std.testing.expectEqual(abi.Event.Kind.tick, events[events.len - 1].kind);
- var it = frames(events);
+ const due = t.tick(now);
+ if (due.len == 0) continue;
+ try std.testing.expectEqual(abi.Event.Kind.tick, due[due.len - 1].kind);
+ var it = frames(due);
while (it.next()) |frame| {
try std.testing.expectEqual(@as(usize, 2), frame.len);
- try std.testing.expectEqual(abi.Event.tick(0, 16_666_667).tickDt(), frame[1].tickDt());
+ // Fed at the times it was recorded at.
+ try std.testing.expectEqual(1000 + delivered * 10_000_000 + 5_000_000, frame[1].time);
delivered += 1;
}
}
@@ -322,13 +243,13 @@ test "frames are whole: input waits for its tick, live and in playback" {
try std.testing.expectEqual(@as(usize, 8), t.cursor);
// A seek between a frame's input and its tick stops before the frame.
- try std.testing.expectEqual(@as(usize, 4), (try t.seekTime(22_000_000)).len);
- try std.testing.expectEqual(@as(usize, 8), (try t.seekCount(r.count)).len);
+ try std.testing.expectEqual(@as(usize, 6), (try t.seekTime(27_000_000)).len);
+ try std.testing.expectEqual(@as(usize, 8), (try t.seekCount(t.events.items.len)).len);
try std.testing.expectEqual(@as(usize, 6), (try t.step(-1)).len);
try std.testing.expectEqual(@as(usize, 8), (try t.step(5)).len);
try std.testing.expectEqual(@as(usize, 2), (try t.step(-3)).len);
// The cut-off frame is never fed.
- var it = frames(r.slice());
+ var it = frames(t.events.items);
var n: usize = 0;
while (it.next()) |_| n += 1;
try std.testing.expectEqual(@as(usize, 4), n);
diff --git a/src/layout.zig b/src/layout.zig
index 3fb381b..c585d71 100644
--- a/src/layout.zig
+++ b/src/layout.zig
@@ -13,23 +13,28 @@
//! against a leaf's pattern at lookup time.
//!
//! What each kind of sketch memory may hold:
-//! - State is saved to disk and snapshotted: no pointers, and no host
-//! handles (images, sounds, buffers), which only mean something in the
-//! process that made them.
+//! - State is saved, the one thing a sketch keeps, in keyframes of its
+//! save: no pointers, and no host handles (images, sounds, buffers),
+//! which only mean something in the process that made them; at most
+//! `max_state` bytes.
//! - Session lives in this process: anything, as long as pointers go into
//! memory the host owns (its heaps, mapped files), never into the sketch
//! library, which a reload unmaps.
-//! - Store is a file mapped at the same address in every run: pointers into
-//! the store itself, but no host handles.
const std = @import("std");
const abi = @import("abi.zig");
+/// The most a State may be, in bytes: half of the 64 MiB a save holds, so
+/// history has room (Sessions.max_save).
+pub const max_state = 32 << 20;
+
pub fn of(comptime T: type, comptime memory: abi.Memory) abi.Layout {
return comptime blk: {
@setEvalBranchQuota(1_000_000);
switch (memory) {
- .state => check(T, "State", @typeName(T), false),
- .store => check(T, "Store", @typeName(T), true),
+ .state => {
+ check(T, @typeName(T));
+ if (@sizeOf(T) > max_state) @compileError(std.fmt.comptimePrint("State is {d} bytes, and may be {d} MiB, half of a save, so history has room: lower a capacity (an array, an sk.List), or keep what need not be saved in Session.", .{ @sizeOf(T), max_state >> 20 }));
+ },
.session => {},
}
const Leaves = struct {
@@ -101,7 +106,7 @@ fn leaf(comptime T: type, comptime path: []const u8, comptime offset: usize, com
};
const stored = dims[0..dims.len].*;
return .{
- .path = std.fmt.comptimePrint("{s}", .{path}),
+ .path = (path ++ "\x00")[0..path.len :0],
.offset = offset,
.size = @sizeOf(T),
.kind = kind,
@@ -155,17 +160,16 @@ pub fn resolve(fields: []const abi.Field, path: []const u8) ?Resolved {
return null;
}
-fn check(comptime T: type, comptime memory: []const u8, comptime path: []const u8, comptime pointers: bool) void {
+fn check(comptime T: type, comptime path: []const u8) void {
comptime {
- if (T == abi.Image or T == abi.Audio or T == abi.Buffer) @compileError(memory ++ " cannot hold host handles (" ++ path ++ "): they mean nothing to the next process. Keep them in Session.");
+ if (T == abi.Image or T == abi.Audio or T == abi.Buffer) @compileError("State cannot hold host handles (" ++ path ++ "): they mean nothing to the next process. Keep them in Session.");
switch (@typeInfo(T)) {
- // Not followed: types can point to themselves.
- .pointer => if (!pointers) @compileError(memory ++ " cannot hold pointers (" ++ path ++ "): it is saved to disk and outlives every address. Keep indices or offsets, or put it in Store or Session."),
- .array => |a| check(a.child, memory, path ++ "[]", pointers),
- .vector => |v| check(v.child, memory, path ++ "[]", pointers),
- .optional => |o| check(o.child, memory, path, pointers),
- .@"struct" => |s| for (s.field_names, s.field_types) |name, F| check(F, memory, path ++ "." ++ name, pointers),
- .@"union" => |u| for (u.field_names, u.field_types) |name, F| check(F, memory, path ++ "." ++ name, pointers),
+ .pointer => @compileError("State cannot hold pointers (" ++ path ++ "): it is saved to disk and outlives every address. Keep indices or offsets, or put it in Session."),
+ .array => |a| check(a.child, path ++ "[]"),
+ .vector => |v| check(v.child, path ++ "[]"),
+ .optional => |o| check(o.child, path),
+ .@"struct" => |s| for (s.field_names, s.field_types) |name, F| check(F, path ++ "." ++ name),
+ .@"union" => |u| for (u.field_names, u.field_types) |name, F| check(F, path ++ "." ++ name),
else => {},
}
}
@@ -176,9 +180,9 @@ fn tags(comptime E: type) [:0]const u8 {
var text: []const u8 = "";
const e = @typeInfo(E).@"enum";
for (e.field_names, e.field_values, 0..) |name, value, i| {
- text = text ++ (if (i == 0) "" else ",") ++ std.fmt.comptimePrint("{s}={d}", .{ name, value });
+ text = text ++ (if (i == 0) "" else ",") ++ name ++ "=" ++ decimal(value);
}
- return std.fmt.comptimePrint("{s}", .{text});
+ return (text ++ "\x00")[0..text.len :0];
}
}
@@ -191,32 +195,40 @@ pub fn hash(comptime T: type) u64 {
};
}
+/// `n` in decimal, as `{d}` prints it: `std.fmt.comptimePrint` costs about a
+/// millisecond of comptime a call, and a signature makes hundreds.
+fn decimal(comptime n: comptime_int) []const u8 {
+ if (n < 0) return "-" ++ decimal(-n);
+ if (n < 10) return &[_]u8{'0' + n};
+ return decimal(n / 10) ++ &[_]u8{'0' + n % 10};
+}
+
pub fn signature(comptime T: type) []const u8 {
comptime {
return switch (@typeInfo(T)) {
- .int => |i| std.fmt.comptimePrint("{c}{d}", .{ if (i.signedness == .signed) 'i' else 'u', i.bits }),
- .float => |f| std.fmt.comptimePrint("f{d}", .{f.bits}),
+ .int => |i| (if (i.signedness == .signed) "i" else "u") ++ decimal(i.bits),
+ .float => |f| "f" ++ decimal(f.bits),
.bool => "b",
.void => "v",
.@"enum" => |e| "e(" ++ signature(e.tag_type) ++ ":" ++ tags(T) ++ ")",
- .array => |a| std.fmt.comptimePrint("[{d}]", .{a.len}) ++ signature(a.child),
- .vector => |v| std.fmt.comptimePrint("@{d}", .{v.len}) ++ signature(v.child),
+ .array => |a| "[" ++ decimal(a.len) ++ "]" ++ signature(a.child),
+ .vector => |v| "@" ++ decimal(v.len) ++ signature(v.child),
.optional => |o| "?" ++ signature(o.child),
.@"struct" => |s| blk: {
- var text: []const u8 = std.fmt.comptimePrint("s{d}{{", .{@sizeOf(T)});
+ var text: []const u8 = "s" ++ decimal(@sizeOf(T)) ++ "{";
for (s.field_names, s.field_types, s.field_attrs) |name, F, attrs| {
if (attrs.@"comptime") continue;
- text = text ++ std.fmt.comptimePrint("{s}@{d}:", .{ name, @offsetOf(T, name) }) ++ signature(F) ++ ";";
+ text = text ++ name ++ "@" ++ decimal(@offsetOf(T, name)) ++ ":" ++ signature(F) ++ ";";
}
break :blk text ++ "}";
},
.@"union" => |u| blk: {
- var text: []const u8 = std.fmt.comptimePrint("u{d}{{", .{@sizeOf(T)});
+ var text: []const u8 = "u" ++ decimal(@sizeOf(T)) ++ "{";
if (u.tag_type) |tag| text = text ++ signature(tag) ++ "|";
for (u.field_names, u.field_types) |name, F| text = text ++ name ++ ":" ++ signature(F) ++ ";";
break :blk text ++ "}";
},
- .pointer => |p| std.fmt.comptimePrint("*{s}:{s}", .{ @tagName(p.size), @typeName(p.child) }),
+ .pointer => |p| "*" ++ @tagName(p.size) ++ ":" ++ @typeName(p.child),
.@"opaque" => "opaque",
.@"fn" => @typeName(T),
else => @compileError("unsupported type in sketch memory: " ++ @typeName(T)),
diff --git a/src/scope/root.zig b/src/scope/root.zig
index a71fa53..098e2d0 100644
--- a/src/scope/root.zig
+++ b/src/scope/root.zig
@@ -16,6 +16,10 @@
//! Columns of the scrolling views are analysed once, when everything their
//! windows reach has arrived, into rings the views read from the oldest; so
//! the spectrogram runs `reach` samples (about 130 ms) behind the newest.
+//!
+//! A sketch that analyses buffers of its own (a tape of takes, say) uses the
+//! same shaders through `kernels` and `pipelines`, with the parameter and
+//! view blocks in `layouts`; `midi`, `hz` and `note_names` name pitches.
const std = @import("std");
const sk = @import("sketch");
const gpu = sk.abi.gpu;
@@ -43,6 +47,10 @@ pub const Views = struct {
oscilloscope: ?Oscilloscope = null,
gain: f32 = 1,
tint: Tint = .live,
+ /// When given, the rects are in its world: the views are made at their
+ /// size there and drawn at `camera.toScreen(rect)`, so moving or zooming
+ /// the camera recomputes nothing.
+ camera: ?sk.Camera = null,
pub const Oscilloscope = struct {
rect: sk.Rect,
@@ -66,6 +74,8 @@ pub const Scope = struct {
filled: u32 = 0,
columns: u32 = 0,
spp: u32 = 0,
+ /// `gpu.tape` holds `samples` on the GPU, as of the last `draw` (a
+ /// `history`-sample buffer, oldest first), for kernels of a sketch's own.
gpu: Gpu = .{},
pub fn push(s: *Scope, heard: []const f32) void {
@@ -91,7 +101,7 @@ pub const Scope = struct {
defer s.fresh = false;
if (v.wave orelse v.spectrogram) |r| s.scroll(f, v, r, rate);
- if (v.spectrum) |r| s.spectrum(f, r, rate);
+ if (v.spectrum) |r| s.spectrum(f, v, r, rate);
if (v.oscilloscope) |o| s.oscilloscope(f, v, o);
}
@@ -121,7 +131,7 @@ pub const Scope = struct {
const slot: u32 = @intCast(s.next % columns);
if (v.wave != null) f.compute(.{
.label = "scope waveform.comp",
- .kernel = waveform_kernel,
+ .kernel = kernels.waveform,
.readonly = &.{g.tape},
.readwrite = &.{g.wave.columns},
.uniforms = gpu.uniform(f.scratch, layouts.WaveParams{ .offset = 0, .first = first, .samples = history, .columns = count, .spp = @floatFromInt(spp), .slot = slot, .ring = columns }),
@@ -129,7 +139,7 @@ pub const Scope = struct {
});
if (v.spectrogram != null) f.compute(.{
.label = "scope spectrogram.comp",
- .kernel = spectrogram_kernel,
+ .kernel = kernels.spectrogram,
.readonly = &.{g.tape},
.readwrite = &.{g.levels},
.uniforms = gpu.uniform(f.scratch, layouts.SpectrogramParams{
@@ -163,7 +173,7 @@ pub const Scope = struct {
.filled = s.filled,
};
if (g.wave.redraw(std.hash.Wyhash.hash(0, std.mem.asBytes(&view)))) wavePass(f, &g.wave, size, view);
- f.image(g.wave.image, wr, .{});
+ f.image(g.wave.image, if (v.camera) |c| c.toScreen(wr) else wr, .{});
}
if (v.spectrogram) |sr| {
const size = target(f, &g.spectrogram, sr, rows);
@@ -181,21 +191,21 @@ pub const Scope = struct {
.width = size[0],
.height = size[1],
.clear = null,
- .pipelines = &spectrogram_pipelines,
+ .pipelines = &pipelines.spectrogram,
.draws = &.{.{ .pipeline = 0, .vertex_count = 3, .fragment_uniforms = gpu.uniform(f.scratch, view), .fragment_storage = &.{g.levels} }},
});
- f.image(g.spectrogram.image, sr, .{});
+ f.image(g.spectrogram.image, if (v.camera) |c| c.toScreen(sr) else sr, .{});
}
}
/// The spectrum of the newest samples, smoothed frame to frame.
- fn spectrum(s: *Scope, f: *sk.Frame, r: sk.Rect, rate: f64) void {
+ fn spectrum(s: *Scope, f: *sk.Frame, v: Views, r: sk.Rect, rate: f64) void {
const g = &s.gpu;
const size = target(f, &g.spectrum, r, layouts.max_rows);
const dt: f64 = @min(@as(f64, @floatFromInt(f.in.dt)) / std.time.ns_per_s, 0.1);
f.compute(.{
.label = "scope spectrum.comp",
- .kernel = spectrum_kernel,
+ .kernel = kernels.spectrum,
.readonly = &.{g.tape},
.readwrite = &.{ g.scratch, g.spectrum.columns },
.uniforms = gpu.uniform(f.scratch, layouts.SpectrumParams{
@@ -217,7 +227,7 @@ pub const Scope = struct {
.width = size[0],
.height = size[1],
.clear = null,
- .pipelines = &spectrum_pipelines,
+ .pipelines = &pipelines.spectrum,
.draws = &.{.{
.pipeline = 0,
.vertex_count = 3,
@@ -231,7 +241,7 @@ pub const Scope = struct {
.fragment_storage = &.{g.spectrum.columns},
}},
});
- f.image(g.spectrum.image, r, .{});
+ f.image(g.spectrum.image, if (v.camera) |c| c.toScreen(r) else r, .{});
}
/// The newest `samples` (less `end`), as a line.
@@ -243,7 +253,7 @@ pub const Scope = struct {
const first: u32 = history - n - end;
f.compute(.{
.label = "scope oscilloscope",
- .kernel = waveform_kernel,
+ .kernel = kernels.waveform,
.readonly = &.{g.tape},
.readwrite = &.{g.oscilloscope.columns},
.uniforms = gpu.uniform(f.scratch, layouts.WaveParams{
@@ -265,7 +275,7 @@ pub const Scope = struct {
.scroll = 0,
.filled = size[0],
});
- f.image(g.oscilloscope.image, o.rect, .{});
+ f.image(g.oscilloscope.image, if (v.camera) |c| c.toScreen(o.rect) else o.rect, .{});
}
};
@@ -274,12 +284,26 @@ pub fn maxFreq(rate: f64) f32 {
return @floatCast(@min(20_000, rate / 2));
}
-/// Where `hz` falls across a spectrum view (or up a spectrogram, from its
+/// Where `freq` falls across a spectrum view (or up a spectrogram, from its
/// bottom): 0 to 1, log frequency.
-pub fn place(hz: f64, rate: f64) f32 {
- return @floatCast(@log(hz / min_freq) / @log(maxFreq(rate) / min_freq));
+pub fn place(freq: f64, rate: f64) f32 {
+ return @floatCast(@log(freq / min_freq) / @log(maxFreq(rate) / min_freq));
+}
+
+/// The MIDI note number of `freq` Hz, fractional (69 is A4, at `a4` Hz:
+/// 440 unless the sketch tunes otherwise).
+pub fn midi(freq: f32, a4: f32) f32 {
+ return 69 + 12 * std.math.log2(freq / a4);
}
+/// The frequency of MIDI note `note`, fractional, in Hz.
+pub fn hz(note: f32, a4: f32) f32 {
+ return a4 * std.math.pow(f32, 2, (note - 69) / 12);
+}
+
+/// Pitch classes by `@mod(note, 12)`, C first.
+pub const note_names = [12][]const u8{ "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
+
// ---------------------------------------------------------------------------
// GPU objects.
@@ -358,7 +382,7 @@ fn wavePass(f: *sk.Frame, v: *View, size: [2]u32, view: layouts.WaveView) void {
.width = size[0],
.height = size[1],
.clear = null,
- .pipelines = &wave_pipelines,
+ .pipelines = &pipelines.wave,
.draws = &.{.{ .pipeline = 0, .vertex_count = 3, .fragment_uniforms = gpu.uniform(f.scratch, view), .fragment_storage = &.{v.columns} }},
});
}
@@ -372,13 +396,26 @@ fn viewPipeline(fragment: []const u8) gpu.Pipeline {
.blend = .none,
};
}
-const wave_pipelines = [_]gpu.Pipeline{viewPipeline(shaders.waveform_frag)};
-const spectrum_pipelines = [_]gpu.Pipeline{viewPipeline(shaders.spectrum_frag)};
-const spectrogram_pipelines = [_]gpu.Pipeline{viewPipeline(shaders.spectrogram_frag)};
-const spectrum_kernel: gpu.Kernel = .{ .code = shaders.spectrum_comp, .readonly_buffers = 1, .readwrite_buffers = 2, .uniform_buffers = 1, .threads = .{ 256, 1, 1 } };
-const spectrogram_kernel: gpu.Kernel = .{ .code = shaders.spectrogram_comp, .readonly_buffers = 1, .readwrite_buffers = 1, .uniform_buffers = 1, .threads = .{ 256, 1, 1 } };
-const waveform_kernel: gpu.Kernel = .{ .code = shaders.waveform_comp, .readonly_buffers = 1, .readwrite_buffers = 1, .uniform_buffers = 1, .threads = .{ 64, 1, 1 } };
+/// The views' passes: one full-screen triangle each (`vertex_count = 3`),
+/// its `layouts.*View` as fragment uniforms and its analysis as fragment
+/// storage (the waveform's or spectrum's columns, the spectrogram's levels).
+pub const pipelines = struct {
+ pub const wave = [_]gpu.Pipeline{viewPipeline(shaders.waveform_frag)};
+ pub const spectrum = [_]gpu.Pipeline{viewPipeline(shaders.spectrum_frag)};
+ pub const spectrogram = [_]gpu.Pipeline{viewPipeline(shaders.spectrogram_frag)};
+};
+
+/// The analyses, over `samples` samples of a read-only buffer from `offset`
+/// (see each `layouts.*Params`): waveform columns ([4]f32 each, a group per
+/// column), the spectrogram's levels (`rows` per column, a group per
+/// column) and the spectrum's columns ([2]f32 each, one group, with an FFT
+/// scratch buffer of `layouts.fft_size * 2` [2]f32 before them).
+pub const kernels = struct {
+ pub const waveform: gpu.Kernel = .{ .code = shaders.waveform_comp, .readonly_buffers = 1, .readwrite_buffers = 1, .uniform_buffers = 1, .threads = .{ 64, 1, 1 } };
+ pub const spectrogram: gpu.Kernel = .{ .code = shaders.spectrogram_comp, .readonly_buffers = 1, .readwrite_buffers = 1, .uniform_buffers = 1, .threads = .{ 256, 1, 1 } };
+ pub const spectrum: gpu.Kernel = .{ .code = shaders.spectrum_comp, .readonly_buffers = 1, .readwrite_buffers = 2, .uniform_buffers = 1, .threads = .{ 256, 1, 1 } };
+};
test "the history keeps the newest samples in order" {
var s: Scope = .{};
@@ -392,3 +429,13 @@ test "frequencies place on a log axis" {
try std.testing.expectEqual(@as(f32, 0), place(min_freq, 48_000));
try std.testing.expectApproxEqAbs(@as(f32, 1), place(20_000, 48_000), 1e-6);
}
+
+test "notes and frequencies convert both ways" {
+ try std.testing.expectApproxEqAbs(@as(f32, 69), midi(440, 440), 1e-4);
+ try std.testing.expectApproxEqAbs(@as(f32, 40), midi(82.4069, 440), 1e-3);
+ try std.testing.expectApproxEqAbs(@as(f32, 261.626), hz(60, 440), 1e-2);
+ try std.testing.expectApproxEqAbs(@as(f32, 69), midi(442, 442), 1e-4);
+ try std.testing.expectApproxEqAbs(@as(f32, 61.5), midi(hz(61.5, 432), 432), 1e-4);
+ try std.testing.expectEqualStrings("A", note_names[@mod(69, 12)]);
+ try std.testing.expectEqualStrings("C", note_names[@mod(60, 12)]);
+}
diff --git a/src/sketch/request.zig b/src/sketch/request.zig
index 0b8b400..4a8e414 100644
--- a/src/sketch/request.zig
+++ b/src/sketch/request.zig
@@ -1,5 +1,5 @@
//! Requests from `update` that `draw` carries out once. `update` sees only
-//! State and input, so when a key should do something to Session or Store
+//! State and input, so when a key should do something to Session
//! (start the microphone, open a dialog, seek a stream), State holds the
//! request and Session remembers which ones it has handled:
//!
diff --git a/src/sketch/root.zig b/src/sketch/root.zig
index cb20ab9..755e446 100644
--- a/src/sketch/root.zig
+++ b/src/sketch/root.zig
@@ -7,19 +7,18 @@
//! pub const height = 600;
//! pub const State = struct { ... }; // saved, snapshotted, replayed: no pointers
//! pub const Session = struct { ... }; // this process: survives reloads
-//! pub const Store = struct { ... }; // on disk: survives restarts too
//! pub const commands = .{"hello"}; // console completions
//! pub fn init(state: *State, host: sk.Host) void
//! pub fn setup(session: *Session, init: *sk.Init) !void
//! pub fn update(state: *State, in: *const sk.Input) void
-//! pub fn draw(state: *const State, session: *Session, store: *Store, f: *sk.Frame) void
-//! pub fn command(state: *State, store: *Store, c: *sk.Console, line: []const u8) !bool
+//! pub fn draw(state: *const State, session: *Session, f: *sk.Frame) void
+//! pub fn command(state: *State, session: *Session, c: *sk.Console, line: []const u8) !bool
//!
//! Functions take the parameters they name, by type, in any order: `draw`
-//! may ask for `*Session`, `*Store`, both or neither. `update` must be
+//! may ask for `*Session` or not. `update` must be
//! deterministic, so it gets `State` and `Input` only: the host replays
//! recorded input through it. `draw` presents state as pictures and sound,
-//! and changes only Session and Store. Geometry and colors are duck-typed:
+//! and changes only Session. Geometry and colors are duck-typed:
//! see `shape`.
const std = @import("std");
pub const abi = @import("abi");
@@ -41,6 +40,8 @@ pub const List = @import("list.zig").List;
/// Data computed in draw from a few State fields, kept in Session and rebuilt when they change (or after a reload).
pub const Derived = @import("derived.zig").Derived;
pub const web = @import("web.zig");
+/// sfxr's sound effects, rendered to samples for `host.newSound`.
+pub const sfxr = @import("sfxr.zig");
const request = @import("request.zig");
pub const Request = request.Request;
pub const Handled = request.Handled;
@@ -65,7 +66,6 @@ pub const Face = abi.Face;
pub const Init = struct {
host: Host,
session: std.mem.Allocator,
- store: std.mem.Allocator,
};
/// What `draw` receives: input, host services, memory by lifetime and the
@@ -80,14 +80,12 @@ pub const Frame = struct {
scratch: std.mem.Allocator,
/// For Session: this process.
session: std.mem.Allocator,
- /// For Store: on disk, across restarts.
- store: std.mem.Allocator,
/// A library's own state for this frame (canim's table of places), in
/// `scratch`: null at each frame's start.
user: ?*anyopaque = null,
pub fn init(ctx: *const abi.Context) Frame {
- return .{ .ctx = ctx, .in = ctx.input, .host = ctx.host, .scratch = ctx.scratch, .session = ctx.session, .store = ctx.store };
+ return .{ .ctx = ctx, .in = ctx.input, .host = ctx.host, .scratch = ctx.scratch, .session = ctx.session };
}
pub fn emit(f: *Frame, command: abi.Command) void {
@@ -210,9 +208,20 @@ pub const Frame = struct {
pub fn voice(f: *Frame, v: Voice) void {
f.emit(.{ .voice = v });
}
+ /// Scales every voice of `group` this frame (1 when not declared).
+ pub fn gain(f: *Frame, group: u3, value: f32) void {
+ f.emit(.{ .gain = .{ .group = group, .gain = value } });
+ }
pub fn audio(f: *Frame, key: u32, samples: []const f32, options: struct { clear: bool = false }) void {
f.emit(.{ .audio = .{ .key = key, .samples = samples, .clear = options.clear } });
}
+ /// Streams `count` samples a compute shader wrote to `buffer` (f32 from
+ /// `offset`) on stream `key`, as `audio` streams samples: a GPU synth's
+ /// output, heard without a readback of the sketch's own. Make
+ /// `in.lead -| in.stream(key).queued` of them a frame.
+ pub fn audioBuffer(f: *Frame, key: u32, buffer: abi.Buffer, options: struct { offset: u32 = 0, count: u32 }) void {
+ f.emit(.{ .audio_buffer = .{ .key = key, .buffer = buffer, .offset = options.offset, .count = options.count } });
+ }
pub fn pixels(f: *Frame, img: Image, w: u32, h: u32, rgba: []const u8, options: struct { premultiplied: bool = false }) void {
f.emit(.{ .pixels = .{ .image = img, .w = w, .h = h, .rgba = rgba, .premultiplied = options.premultiplied } });
}
@@ -285,12 +294,11 @@ fn paint(value: anytype) Color {
}
/// What `command` receives: somewhere to answer, the current input, and the
-/// allocators for Session and Store.
+/// allocator for Session.
pub const Console = struct {
host: Host,
in: *const Input,
session: std.mem.Allocator,
- store: std.mem.Allocator,
pub fn log(c: *Console, message: []const u8) void {
c.host.log(message);
@@ -300,15 +308,24 @@ pub const Console = struct {
}
};
+/// What the build knows of a sketch and passes to `sketch` and
+/// `exportSketch` (build.zig's generated roots fill it in).
+pub const Build = struct {
+ /// The repository revision the sketch was built from, "" when unknown.
+ source: []const u8 = "",
+ /// Keep history in the save (`abi.Info.record`).
+ record: bool = false,
+};
+
/// The entry points of `App`, for a host that links it statically.
-pub fn sketch(comptime App: type) abi.Sketch {
- const G = Glue(App);
+pub fn sketch(comptime App: type, comptime made: Build) abi.Sketch {
+ const G = Glue(App, made);
return .{ .info = G.info, .defaults = G.defaults, .init = G.init, .setup = G.setup, .update = G.update, .draw = G.draw, .command = G.command };
}
/// Exports `App` under `abi.Sketch.symbols`, for a hot-reloaded library.
-pub fn exportSketch(comptime App: type) void {
- const G = Glue(App);
+pub fn exportSketch(comptime App: type, comptime made: Build) void {
+ const G = Glue(App, made);
const names = abi.Sketch.symbols;
@export(&G.info, .{ .name = names.info });
@export(&G.defaults, .{ .name = names.defaults });
@@ -317,13 +334,15 @@ pub fn exportSketch(comptime App: type) void {
@export(&G.update, .{ .name = names.update });
@export(&G.draw, .{ .name = names.draw });
@export(&G.command, .{ .name = names.command });
+ @export(&G.build, .{ .name = "sketch_build" });
}
-pub fn Glue(comptime App: type) type {
+pub fn Glue(comptime App: type, comptime made: Build) type {
return struct {
pub const State = if (@hasDecl(App, "State")) App.State else struct {};
pub const Session = if (@hasDecl(App, "Session")) App.Session else struct {};
- pub const Store = if (@hasDecl(App, "Store")) App.Store else struct {};
+
+ const build: [abi.build.len:0]u8 = abi.build.*;
pub const description: abi.Info = .{
.abi = abi.hash,
@@ -332,8 +351,10 @@ pub fn Glue(comptime App: type) type {
.height = if (@hasDecl(App, "height")) App.height else 600,
.state = abi.layout.of(State, .state),
.session = abi.layout.of(Session, .session),
- .store = abi.layout.of(Store, .store),
.commands = if (@hasDecl(App, "commands")) &App.commands else &.{},
+ .source = made.source ++ " " ++ abi.build,
+ .record = made.record,
+ .audio_pull = if (@hasDecl(App, "audio_pull")) App.audio_pull else 0,
};
/// What a call can offer, by type.
@@ -357,10 +378,10 @@ pub fn Glue(comptime App: type) type {
return std.mem.eql(u8, name, n);
}
};
- if (comptime is.named("update") and (T == *Session or T == *Store))
+ if (comptime is.named("update") and T == *Session)
@compileError("update must be deterministic: it gets State and Input only, so a replay reproduces it");
if (comptime is.named("setup") and (T == *State or T == *const State or T == *const Input))
- @compileError("setup initializes resources: it gets Session, Store, Init and Host only");
+ @compileError("setup initializes resources: it gets Session, Init and Host only");
if (comptime (T == *Init or T == *const Init) and !is.named("setup")) @compileError(name ++ " gets no Init: only setup does");
if (comptime is.named("draw") and T == *State) @compileError("draw only reads State: take *const State");
if (comptime T == *Frame and !is.named("draw")) @compileError(name ++ " gets no Frame: only draw does");
@@ -369,8 +390,6 @@ pub fn Glue(comptime App: type) type {
@ptrCast(@alignCast(offer.state))
else if (T == *Session or T == *const Session)
@ptrCast(@alignCast(offer.ctx.session_root))
- else if (T == *Store or T == *const Store)
- @ptrCast(@alignCast(offer.ctx.store_root))
else if (T == *const Input)
offer.ctx.input
else if (T == Host)
@@ -396,7 +415,6 @@ pub fn Glue(comptime App: type) type {
switch (which) {
.state => @as(*State, @ptrCast(@alignCast(ptr))).* = .{},
.session => @as(*Session, @ptrCast(@alignCast(ptr))).* = .{},
- .store => @as(*Store, @ptrCast(@alignCast(ptr))).* = .{},
}
}
pub fn init(ctx: *const abi.Context, s: [*]u8) callconv(.c) void {
@@ -404,7 +422,7 @@ pub fn Glue(comptime App: type) type {
}
pub fn setup(ctx: *const abi.Context) callconv(.c) bool {
if (!@hasDecl(App, "setup")) return true;
- var resource_init: Init = .{ .host = ctx.host, .session = ctx.session, .store = ctx.store };
+ var resource_init: Init = .{ .host = ctx.host, .session = ctx.session };
const result = call(App.setup, "setup", .{ .ctx = ctx, .state = undefined, .resource_init = &resource_init });
if (@typeInfo(@TypeOf(result)) == .error_union) result catch |err| {
ctx.host.print("session setup failed: {t}", .{err});
@@ -422,7 +440,7 @@ pub fn Glue(comptime App: type) type {
}
pub fn command(ctx: *const abi.Context, s: [*]u8, line: *const []const u8) callconv(.c) abi.Outcome {
if (!@hasDecl(App, "command")) return .unknown;
- var c: Console = .{ .host = ctx.host, .in = ctx.input, .session = ctx.session, .store = ctx.store };
+ var c: Console = .{ .host = ctx.host, .in = ctx.input, .session = ctx.session };
const taken = call(App.command, "command", .{ .ctx = ctx, .state = s, .console = &c, .line = line.* }) catch |err| {
c.print("{t}. Type help for usage.", .{err});
return .failed;
@@ -442,6 +460,7 @@ test {
_ = @import("clock.zig");
_ = @import("list.zig");
_ = @import("derived.zig");
+ _ = sfxr;
}
test "setup receives session resources without a Frame and reports errors" {
@@ -467,8 +486,7 @@ test "setup receives session resources without a Frame and reports errors" {
ctx.host = .{ .ctx = &seen, .vtable = &vtable };
ctx.session_root = std.mem.asBytes(&session);
ctx.session = std.testing.allocator;
- ctx.store = std.testing.allocator;
- const app = sketch(App);
+ const app = sketch(App, .{});
try std.testing.expect(!app.setup(&ctx));
defer std.testing.allocator.free(session.bytes);
try std.testing.expectEqualStrings("ready", session.bytes);
diff --git a/src/sketch/sfxr.zig b/src/sketch/sfxr.zig
new file mode 100644
index 0000000..01657b5
--- /dev/null
+++ b/src/sketch/sfxr.zig
@@ -0,0 +1,267 @@
+//! sfxr, DrPetter's sound-effect generator (blips, coins, lasers,
+//! explosions): one waveform through an envelope, pitch slides, vibrato,
+//! arpeggio, duty sweep, a phaser and two filters, 8× oversampled. Pure and
+//! deterministic: the same `Params` and rate give the same samples, so a
+//! sketch renders its sounds whenever it likes and plays them as voices:
+//!
+//! const n = sk.sfxr.render(.{ .freq = 0.5, .decay = 0.2 }, f.in.sample_rate, &buf);
+//! ss.blip = f.host.newSound(buf[0..n]);
+//!
+//! Ported from 02-dont-rat-me-out's synth.zig. sfxr's knobs count in
+//! samples at 44.1 kHz; at another rate every length, step and filter
+//! coefficient is scaled to keep the same durations, pitches and cutoffs
+//! (to first order for the slides and filters), and at 44.1 kHz the
+//! samples are the original's to the bit.
+const std = @import("std");
+
+/// The rate sfxr's knobs were tuned at.
+pub const reference_rate = 44_100;
+
+pub const Wave = enum(u8) { square, sawtooth, sine, noise };
+
+/// All sfxr knobs. Most are 0..1, a few -1..1.
+pub const Params = struct {
+ wave: Wave = .square,
+ // envelope
+ attack: f32 = 0.0,
+ sustain: f32 = 0.3,
+ punch: f32 = 0.0,
+ decay: f32 = 0.4,
+ // frequency
+ freq: f32 = 0.3,
+ freq_limit: f32 = 0.0,
+ freq_ramp: f32 = 0.0,
+ freq_dramp: f32 = 0.0,
+ // vibrato
+ vibrato_depth: f32 = 0.0,
+ vibrato_speed: f32 = 0.0,
+ // arpeggio
+ arp_mod: f32 = 0.0,
+ arp_speed: f32 = 0.0,
+ // square duty
+ duty: f32 = 0.0,
+ duty_ramp: f32 = 0.0,
+ // phaser
+ phaser_offset: f32 = 0.0,
+ phaser_ramp: f32 = 0.0,
+ // filters
+ lpf_freq: f32 = 1.0,
+ lpf_ramp: f32 = 0.0,
+ lpf_resonance: f32 = 0.0,
+ hpf_freq: f32 = 0.0,
+ hpf_ramp: f32 = 0.0,
+ // repeat
+ repeat_speed: f32 = 0.0,
+ // output
+ volume: f32 = 0.5,
+};
+
+inline fn sq(x: f32) f32 {
+ return x * x;
+}
+inline fn cube(x: f32) f32 {
+ return x * x * x;
+}
+inline fn xs(s: *u32) u32 {
+ s.* ^= s.* << 13;
+ s.* ^= s.* >> 17;
+ s.* ^= s.* << 5;
+ return s.*;
+}
+fn frnd(s: *u32, range: f32) f32 {
+ return @as(f32, @floatFromInt(xs(s))) / 4294967295.0 * range;
+}
+
+/// Synthesizes `p` at `rate` samples a second into `out` (mono, -1..1).
+/// Returns the number of samples written: the envelope's length, or less
+/// when `out` is shorter or the pitch falls to `freq_limit`.
+pub fn render(p: Params, rate: u32, out: []f32) usize {
+ // Samples at `rate` per sample at 44.1 kHz: lengths grow by it, steps
+ // per sample shrink by it.
+ const k: f64 = @as(f64, @floatFromInt(rate)) / reference_rate;
+ const kf: f32 = @floatCast(k);
+ var rng: u32 = 0x52ad4326;
+
+ var fperiod: f64 = 100.0 / (@as(f64, p.freq) * p.freq + 0.001) * k;
+ var period: i32 = @intFromFloat(fperiod);
+ const fmaxperiod: f64 = 100.0 / (@as(f64, p.freq_limit) * p.freq_limit + 0.001) * k;
+ var fslide: f64 = 1.0 - @as(f64, cube(p.freq_ramp)) * 0.01 / k;
+ const fdslide: f64 = -@as(f64, cube(p.freq_dramp)) * 0.000001 / (k * k);
+
+ var square_duty: f32 = 0.5 - p.duty * 0.5;
+ const square_slide: f32 = -p.duty_ramp * 0.00005 / kf;
+
+ const arp_mod: f64 = if (p.arp_mod >= 0) 1.0 - @as(f64, sq(p.arp_mod)) * 0.9 else 1.0 + @as(f64, sq(p.arp_mod)) * 10.0;
+ var arp_time: i32 = 0;
+ var arp_limit: i32 = @intFromFloat((sq(p.arp_speed) * 20000 + 32) * kf);
+ if (p.arp_speed == 1.0) arp_limit = 0;
+
+ var env_vol: f32 = 0;
+ var env_stage: usize = 0;
+ var env_time: i32 = 0;
+ const env_length = [3]i32{
+ @intFromFloat(p.attack * p.attack * 100000 * kf),
+ @intFromFloat(p.sustain * p.sustain * 100000 * kf),
+ @intFromFloat(p.decay * p.decay * 100000 * kf),
+ };
+
+ var fphase: f32 = sq(p.phaser_offset) * 1020 * kf;
+ if (p.phaser_offset < 0) fphase = -fphase;
+ var fdphase: f32 = sq(p.phaser_ramp) * 1.0;
+ if (p.phaser_ramp < 0) fdphase = -fdphase;
+ var iphase: i32 = @intFromFloat(@min(@abs(fphase), 1023));
+ var ipp: i32 = 0;
+ var phaser_buffer: [1024]f32 = @splat(0);
+
+ var noise_buffer: [32]f32 = undefined;
+ for (&noise_buffer) |*nb| nb.* = frnd(&rng, 2) - 1;
+
+ var fltp: f32 = 0;
+ var fltdp: f32 = 0;
+ var fltw: f32 = cube(p.lpf_freq) * 0.1 / kf;
+ const fltw_d: f32 = 1.0 + p.lpf_ramp * 0.0001 / kf;
+ var fltdmp: f32 = 5.0 / (1.0 + sq(p.lpf_resonance) * 20) * (0.01 + fltw);
+ if (fltdmp > 0.8) fltdmp = 0.8;
+ var fltphp: f32 = 0;
+ var flthp: f32 = sq(p.hpf_freq) * 0.1 / kf;
+ const flthp_d: f32 = 1.0 + p.hpf_ramp * 0.0003 / kf;
+
+ var vib_phase: f32 = 0;
+ const vib_speed: f32 = sq(p.vibrato_speed) * 0.01 / kf;
+ const vib_amp: f32 = p.vibrato_depth * 0.5;
+
+ var rep_time: i32 = 0;
+ var rep_limit: i32 = @intFromFloat((sq(1 - p.repeat_speed) * 20000 + 32) * kf);
+ if (p.repeat_speed == 0) rep_limit = 0;
+
+ var phase: i32 = 0;
+ var n: usize = 0;
+ var finished = false;
+ while (!finished and n < out.len) : (n += 1) {
+ rep_time += 1;
+ if (rep_limit != 0 and rep_time >= rep_limit) {
+ rep_time = 0;
+ fperiod = 100.0 / (@as(f64, p.freq) * p.freq + 0.001) * k;
+ period = @intFromFloat(fperiod);
+ fslide = 1.0 - @as(f64, cube(p.freq_ramp)) * 0.01 / k;
+ arp_time = 0;
+ arp_limit = @intFromFloat((sq(p.arp_speed) * 20000 + 32) * kf);
+ if (p.arp_speed == 1.0) arp_limit = 0;
+ }
+
+ arp_time += 1;
+ if (arp_limit != 0 and arp_time >= arp_limit) {
+ arp_limit = 0;
+ fperiod *= arp_mod;
+ }
+
+ fslide += fdslide;
+ fperiod *= fslide;
+ if (fperiod > fmaxperiod) {
+ fperiod = fmaxperiod;
+ if (p.freq_limit > 0) finished = true;
+ }
+
+ var rfperiod: f32 = @floatCast(fperiod);
+ if (vib_amp > 0) {
+ vib_phase += vib_speed;
+ rfperiod = @floatCast(fperiod * (1.0 + @as(f64, @sin(vib_phase) * vib_amp)));
+ }
+ period = @intFromFloat(rfperiod);
+ if (period < 8) period = 8;
+
+ square_duty += square_slide;
+ square_duty = std.math.clamp(square_duty, 0, 0.5);
+
+ env_time += 1;
+ if (env_time > env_length[env_stage]) {
+ env_time = 0;
+ env_stage += 1;
+ if (env_stage == 3) finished = true;
+ }
+ env_vol = switch (env_stage) {
+ 0 => @as(f32, @floatFromInt(env_time)) / @as(f32, @floatFromInt(@max(1, env_length[0]))),
+ 1 => 1.0 + (1.0 - @as(f32, @floatFromInt(env_time)) / @as(f32, @floatFromInt(@max(1, env_length[1])))) * 2.0 * p.punch,
+ else => 1.0 - @as(f32, @floatFromInt(env_time)) / @as(f32, @floatFromInt(@max(1, env_length[2]))),
+ };
+
+ fphase += fdphase;
+ iphase = @intFromFloat(@min(@abs(fphase), 1023));
+
+ flthp *= flthp_d;
+ flthp = std.math.clamp(flthp, 0.00001, 0.1);
+
+ var ssample: f32 = 0;
+ var oi: u32 = 0;
+ while (oi < 8) : (oi += 1) {
+ var sample: f32 = 0;
+ phase += 1;
+ if (phase >= period) {
+ phase = @mod(phase, period);
+ if (p.wave == .noise) for (&noise_buffer) |*nb| {
+ nb.* = frnd(&rng, 2) - 1;
+ };
+ }
+ const fp: f32 = @as(f32, @floatFromInt(phase)) / @as(f32, @floatFromInt(period));
+ sample = switch (p.wave) {
+ .square => if (fp < square_duty) 0.5 else -0.5,
+ .sawtooth => 1.0 - fp * 2,
+ .sine => @sin(fp * 2.0 * std.math.pi),
+ .noise => noise_buffer[@intCast(@as(i32, @intFromFloat(fp * 32)) & 31)],
+ };
+
+ const pp = fltp;
+ fltw *= fltw_d;
+ fltw = std.math.clamp(fltw, 0, 0.1);
+ if (p.lpf_freq != 1.0) {
+ fltdp += (sample - fltp) * fltw;
+ fltdp -= fltdp * fltdmp;
+ } else {
+ fltp = sample;
+ fltdp = 0;
+ }
+ fltp += fltdp;
+ fltphp += fltp - pp;
+ fltphp -= fltphp * flthp;
+ sample = fltphp;
+ phaser_buffer[@intCast(ipp & 1023)] = sample;
+ sample += phaser_buffer[@intCast((ipp - iphase + 1024) & 1023)];
+ ipp = (ipp + 1) & 1023;
+
+ ssample += sample * env_vol;
+ }
+ ssample = ssample / 8.0 * p.volume * 2.0;
+ out[n] = std.math.clamp(ssample, -1, 1);
+ }
+ return n;
+}
+
+/// One parameter set per wave, between them every knob: a coin with punch,
+/// arpeggio and a duty sweep; an explosion through both filters; a laser
+/// with vibrato, phaser, repeat and a pitch limit; a rising sine.
+const sets = [_]Params{
+ .{ .wave = .square, .sustain = 0.1, .punch = 0.5, .decay = 0.3, .freq = 0.45, .freq_ramp = -0.2, .arp_mod = 0.4, .arp_speed = 0.6, .duty = 0.3, .duty_ramp = 0.2 },
+ .{ .wave = .noise, .sustain = 0.2, .decay = 0.4, .freq = 0.2, .freq_ramp = -0.1, .lpf_freq = 0.6, .lpf_ramp = -0.1, .lpf_resonance = 0.4, .hpf_freq = 0.1, .hpf_ramp = 0.05 },
+ .{ .wave = .sawtooth, .sustain = 0.25, .decay = 0.2, .freq = 0.5, .freq_limit = 0.1, .freq_dramp = 0.1, .vibrato_depth = 0.3, .vibrato_speed = 0.5, .phaser_offset = 0.3, .phaser_ramp = -0.1, .repeat_speed = 0.5 },
+ .{ .wave = .sine, .attack = 0.2, .sustain = 0.2, .decay = 0.2, .freq = 0.3, .freq_ramp = 0.1, .freq_limit = 0.2, .volume = 0.8 },
+};
+
+test "sfxr renders the original's samples at 44.1 kHz, and as long a sound at 48 kHz" {
+ // Length and Wyhash of the samples the original (02-dont-rat-me-out
+ // synth.zig) rendered for each set at 44.1 kHz.
+ const original = [_]struct { usize, u64 }{
+ .{ 10003, 0xb969b441e8bd800 },
+ .{ 20003, 0x5fc62aaf3122de5a },
+ .{ 10253, 0x8d81ee15b98f33ac },
+ .{ 12003, 0xe656fadd21b7dedb },
+ };
+ const out = try std.testing.allocator.alloc(f32, 2 * 48_000);
+ defer std.testing.allocator.free(out);
+ for (sets, original) |p, want| {
+ const n = render(p, reference_rate, out);
+ try std.testing.expectEqual(want[0], n);
+ try std.testing.expectEqual(want[1], std.hash.Wyhash.hash(0, std.mem.sliceAsBytes(out[0..n])));
+ const at48 = render(p, 48_000, out);
+ try std.testing.expectApproxEqRel(@as(f64, @floatFromInt(n)) * 48_000 / reference_rate, @as(f64, @floatFromInt(at48)), 0.01);
+ }
+}
diff --git a/src/sketch/web.zig b/src/sketch/web.zig
index 937b491..804a4df 100644
--- a/src/sketch/web.zig
+++ b/src/sketch/web.zig
@@ -2,7 +2,7 @@
//! the imports below: drawing on a 2D canvas, GPU work on WebGPU, sound and
//! the microphone on Web Audio, files through the page. State, `update` and
//! `draw` are the same Zig as on native. There is no timeline, and nothing
-//! persists: Store lasts as long as the page.
+//! persists.
const std = @import("std");
const abi = @import("abi");
const root = @import("root.zig");
@@ -48,6 +48,8 @@ const js = struct {
extern "gpu" fn download(id: u32, offset: u32, size: u32, key: u32) void;
extern "audio" fn rate() u32;
extern "audio" fn push(key: u32, ptr: [*]const f32, len: usize, clear: u32) void;
+ /// `count` samples from a GPU buffer, queued on arrival.
+ extern "audio" fn buffer(key: u32, id: u32, offset: u32, count: u32) void;
extern "audio" fn queued(key: u32) u32;
/// Keeps the microphone open; it answers through `sk_microphone`.
extern "audio" fn listen() void;
@@ -76,14 +78,12 @@ pub fn exportWeb(comptime App: type) void {
}
fn Driver(comptime App: type) type {
- const G = root.Glue(App);
+ const G = root.Glue(App, .{});
const gpa = std.heap.wasm_allocator;
return struct {
var ready = false;
var state: G.State = undefined;
var session: G.Session = undefined;
- // No disk on the web: the store lasts as long as the page.
- var store: G.Store = undefined;
var events: [1024]abi.Event = undefined;
var event_count: usize = 0;
var input: abi.Input = .{};
@@ -105,9 +105,7 @@ fn Driver(comptime App: type) type {
.input = &input,
.scratch = scratch.allocator(),
.session = gpa,
- .store = gpa,
.session_root = std.mem.asBytes(&session),
- .store_root = std.mem.asBytes(&store),
.commands = &commands,
};
}
@@ -115,7 +113,6 @@ fn Driver(comptime App: type) type {
fn init() callconv(.c) void {
G.defaults(.state, std.mem.asBytes(&state));
G.defaults(.session, std.mem.asBytes(&session));
- G.defaults(.store, std.mem.asBytes(&store));
input.width = G.description.width;
input.height = G.description.height;
if (input.window_width == 0) {
@@ -225,6 +222,10 @@ fn Driver(comptime App: type) type {
s.pushed += v.samples.len;
js.push(v.key, v.samples.ptr, v.samples.len, @intFromBool(v.clear));
},
+ .audio_buffer => |v| {
+ stream(v.key).pushed += v.count;
+ js.buffer(v.key, @backingInt(v.buffer), v.offset, v.count);
+ },
.microphone => js.listen(),
.upload => |v| _ = js.write(@backingInt(v.buffer), v.offset, v.bytes.ptr, v.bytes.len),
.compute => |v| {
@@ -241,9 +242,9 @@ fn Driver(comptime App: type) type {
},
.download => |v| js.download(@backingInt(v.buffer), v.offset, v.size, v.key),
.open_file => |v| js.openFile(v.command.ptr, v.command.len, v.pattern.ptr, v.pattern.len),
- // Synthesised voices are not on the web yet; quitting a page
+ // Voices (and so their groups) are not on the web yet; quitting a page
// means nothing; `run` lines go after the frame.
- .voice, .quit, .run, .backdrop => {},
+ .voice, .gain, .quit, .run, .backdrop => {},
}
}
@@ -411,8 +412,10 @@ fn Driver(comptime App: type) type {
.textSize = textSize,
.loadSound = loadSound,
.decodeSound = unsupportedSound,
+ .newSound = newSound,
.samples = samples,
.readFile = readFile,
+ .appendFile = appendFile,
.env = env,
.clock = clock,
};
@@ -460,6 +463,16 @@ fn Driver(comptime App: type) type {
fn unsupportedSound(_: *anyopaque, _: []const u8) abi.Audio {
return .none;
}
+ /// Kept, unnamed, for `samples` (voices are silent on the web).
+ fn newSound(_: *anyopaque, ptr: [*]const f32, len: usize) callconv(.c) abi.Audio {
+ for (ptr[0..len]) |v| if (!std.math.isFinite(v)) return .none;
+ const copy = gpa.dupe(f32, ptr[0..len]) catch return .none;
+ sounds.append(gpa, .{ .name = "", .samples = copy }) catch {
+ gpa.free(copy);
+ return .none;
+ };
+ return @fromBackingInt(@intCast(sounds.items.len));
+ }
fn samples(_: *anyopaque, a: abi.Audio) []const f32 {
const i = @backingInt(a);
return if (i == 0 or i > sounds.items.len) &.{} else sounds.items[i - 1].samples;
@@ -467,6 +480,10 @@ fn Driver(comptime App: type) type {
fn readFile(_: *anyopaque, _: []const u8) []const u8 {
return &.{};
}
+ /// No files on the web: nothing is written, and the path is "".
+ fn appendFile(_: *anyopaque, _: [*]const u8, _: usize, _: [*]const u8, _: usize, _: bool) callconv(.c) [*:0]const u8 {
+ return "";
+ }
fn env(_: *anyopaque, _: []const u8) ?[]const u8 {
return null;
}
diff --git a/src/vector/morph.zig b/src/vector/morph.zig
index f285c7e..a05037d 100644
--- a/src/vector/morph.zig
+++ b/src/vector/morph.zig
@@ -2,7 +2,9 @@
//! in order; each pair's subpaths, then each subpath's cubics, are made equal
//! in number by splitting the longest curves; then every control point and
//! color is interpolated. A shape without a partner collapses to (or grows
-//! from) the other drawing's center.
+//! from) the other drawing's center. Outer contours pair with outer ones
+//! and holes with holes, so a glyph's counter stays a counter; a hole
+//! without a partner shrinks to nothing (or grows) inside its shape.
const std = @import("std");
const geom = @import("math");
const Drawing = @import("Drawing.zig");
@@ -22,10 +24,14 @@ pub fn between(arena: std.mem.Allocator, a: Drawing, ma: geom.Affine, b: Drawing
// The missing side is the other side, shrunk to a point.
const pa = try placed(arena, a, sa, ma, sb, b, mb, cb);
const pb = try placed(arena, b, sb, mb, sa, a, ma, ca);
- const count = @max(pa.len, pb.len);
- for (0..count) |k| {
- const from = try pad(arena, pa, k, if (pa.len > 0) lastPoint(pa) else ca);
- const to = try pad(arena, pb, k, if (pb.len > 0) lastPoint(pb) else cb);
+ // Outer contours pair up, then holes; a missing shape's subpaths
+ // are its partner's, in order.
+ const ha = if (sa != null and sb != null) try holesLast(arena, pa) else 0;
+ const hb = if (sa != null and sb != null) try holesLast(arena, pb) else 0;
+ const outers = @max(pa.len - ha, pb.len - hb);
+ for (0..outers + @max(ha, hb)) |k| {
+ const from = try side(arena, pa, ha, pb, hb, k, outers, ca);
+ const to = try side(arena, pb, hb, pa, ha, k, outers, cb);
const aligned = try align2(arena, from.cubics, to.cubics);
for (aligned[0], aligned[1]) |x, y| {
var c: Cubic = undefined;
@@ -78,6 +84,50 @@ fn pad(arena: std.mem.Allocator, paths: []const Path, k: usize, point: Vec) !Pat
return .{ .cubics = one, .closed = false };
}
+/// Puts the holes of `paths` (wound against the largest, as a font's
+/// counters are) after its outer contours, each in order; returns how many.
+fn holesLast(arena: std.mem.Allocator, paths: []Path) !usize {
+ const areas = try arena.alloc(f32, paths.len);
+ var main: f32 = 0;
+ for (areas, paths) |*area, p| {
+ area.* = geom.cross(p.cubics[p.cubics.len - 1][3], p.cubics[0][0]);
+ for (p.cubics) |c| area.* += geom.cross(c[0], c[1]) + geom.cross(c[1], c[2]) + geom.cross(c[2], c[3]);
+ if (@abs(area.*) > @abs(main)) main = area.*;
+ }
+ const all = try arena.dupe(Path, paths);
+ var n: usize = 0;
+ var holes: usize = 0;
+ for ([_]bool{ false, true }) |hole| for (all, areas) |p, area| if ((area * main < 0) == hole) {
+ paths[n] = p;
+ n += 1;
+ holes += @intFromBool(hole);
+ };
+ return holes;
+}
+
+/// One side's path for pair `k`: its outer contours, then its holes. One it
+/// lacks is a point: an outer contour's where its last one ends (or at its
+/// drawing's `middle`); a hole's where the other side's hole has its middle,
+/// relative to the outer contours' bounds on each side, so that a hole with
+/// no partner shrinks to nothing (or grows) inside its shape, moving with it.
+fn side(arena: std.mem.Allocator, own: []const Path, holes: usize, other: []const Path, other_holes: usize, k: usize, outers: usize, middle: Vec) !Path {
+ const shell = own[0 .. own.len - holes];
+ if (k < outers) return pad(arena, shell, k, if (shell.len > 0) lastPoint(shell) else middle);
+ const j = k - outers;
+ if (j < holes) return own[own.len - holes + j];
+ const there = extent(other[0 .. other.len - other_holes]);
+ const here = extent(shell);
+ const hole = extent(other[other.len - other_holes + j ..][0..1]);
+ const at = ((hole.min + hole.max) / geom.splat(2) - there.min) / (there.max - there.min);
+ return pad(arena, &.{}, 0, here.min + at * (here.max - here.min));
+}
+
+fn extent(paths: []const Path) geom.Bounds {
+ var b: geom.Bounds = .{};
+ for (paths) |p| for (p.cubics) |c| for (c) |q| b.add(q);
+ return b;
+}
+
fn lastPoint(paths: []const Path) Vec {
const last = paths[paths.len - 1].cubics;
return last[last.len - 1][3];
diff --git a/src/vector/svg.zig b/src/vector/svg.zig
index 31d9b15..f1b7daf 100644
--- a/src/vector/svg.zig
+++ b/src/vector/svg.zig
@@ -4,11 +4,12 @@
//! `ellipse`, `line`, `polyline`, `polygon`. Styling: presentation
//! attributes and `style="..."`, inherited as SVG specifies; solid colors,
//! linear and radial gradients; fill rules; stroke width, caps, joins, miter
-//! limit and dashes; `opacity`, `fill-opacity`, `stroke-opacity`.
+//! limit and dashes; `opacity`, `fill-opacity`, `stroke-opacity`. Images
+//! that are SVG documents in base64 data URIs (Typst's SVG and PDF images).
//!
//! Not supported: text (Typst outlines it), filters, masks, clipping,
-//! patterns, markers, images, CSS stylesheets. Group opacity is approximated
-//! by multiplying it into each shape.
+//! patterns, markers, raster images, CSS stylesheets. Group opacity is
+//! approximated by multiplying it into each shape.
const std = @import("std");
const geom = @import("math");
const Drawing = @import("Drawing.zig");
@@ -23,23 +24,26 @@ pub fn parse(arena: std.mem.Allocator, source: []const u8) Error!Drawing {
const root = doc.root orelse return error.InvalidSvg;
if (!std.mem.eql(u8, doc.nodes.items[root].name, "svg")) return error.InvalidSvg;
- var p: Parser = .{ .doc = &doc, .b = .init(arena), .arena = arena, .view = .{} };
- const n = doc.nodes.items[root];
- const w = doc.attr(n, "width");
- const h = doc.attr(n, "height");
+ const port = viewport(&doc, doc.nodes.items[root]);
+ var p: Parser = .{ .doc = &doc, .b = .init(arena), .arena = arena, .view = port.view };
+ try p.children(root, .identity, .{});
+ return p.b.finish(port.view, port.width, port.height);
+}
+
+/// A root `svg` element's view box and size in pixels, each standing in
+/// for the other when missing.
+fn viewport(doc: *const Document, n: Node) struct { view: geom.Rect, width: f32, height: f32 } {
var view: geom.Rect = .{};
if (doc.attr(n, "viewBox")) |vb| {
var nums = Numbers{ .text = vb };
view = .{ .x = nums.next() orelse 0, .y = nums.next() orelse 0, .w = nums.next() orelse 0, .h = nums.next() orelse 0 };
}
- var width = if (w) |v| lengthPx(v, view.w) else view.w;
- var height = if (h) |v| lengthPx(v, view.h) else view.h;
+ var width = if (doc.attr(n, "width")) |v| lengthPx(v, view.w) else view.w;
+ var height = if (doc.attr(n, "height")) |v| lengthPx(v, view.h) else view.h;
if (view.w <= 0 or view.h <= 0) view = .{ .w = width, .h = height };
if (width <= 0) width = view.w;
if (height <= 0) height = view.h;
- p.view = view;
- try p.children(root, .identity, .{});
- return p.b.finish(view, width, height);
+ return .{ .view = view, .width = width, .height = height };
}
// ---------------------------------------------------------------------------
@@ -183,7 +187,7 @@ const Parser = struct {
fn element(p: *Parser, index: u32, parent_transform: Affine, parent: Inherited) Error!void {
const n = p.doc.nodes.items[index];
const name = n.name;
- const skip = [_][]const u8{ "defs", "symbol", "linearGradient", "radialGradient", "clipPath", "mask", "pattern", "marker", "style", "title", "desc", "metadata", "filter", "text", "image", "foreignObject" };
+ const skip = [_][]const u8{ "defs", "symbol", "linearGradient", "radialGradient", "clipPath", "mask", "pattern", "marker", "style", "title", "desc", "metadata", "filter", "text", "foreignObject" };
for (skip) |s| if (std.mem.eql(u8, name, s)) return;
if (p.depth > 64) return;
var inherited = parent;
@@ -229,6 +233,52 @@ const Parser = struct {
}
return p.element(target, transform, inherited);
}
+ if (std.mem.eql(u8, name, "image")) {
+ // An SVG as a base64 data URI, Typst's way to place an SVG or a
+ // PDF page: its document, mapped into the image's box. Raster
+ // images draw nothing.
+ const href = p.doc.attr(n, "href") orelse p.doc.attr(n, "xlink:href") orelse return;
+ const prefix = "data:image/svg+xml;base64,";
+ if (!std.mem.startsWith(u8, href, prefix)) return;
+ const decoder = std.base64.standard.Decoder;
+ const bytes = try p.arena.alloc(u8, decoder.calcSizeForSlice(href[prefix.len..]) catch return);
+ decoder.decode(bytes, href[prefix.len..]) catch return;
+ var doc = Document.parse(p.arena, bytes) catch |err| switch (err) {
+ error.OutOfMemory => return err,
+ error.InvalidSvg => return,
+ };
+ const root = doc.root orelse return;
+ if (!std.mem.eql(u8, doc.nodes.items[root].name, "svg")) return;
+ const port = viewport(&doc, doc.nodes.items[root]);
+ const v = port.view;
+ const w = if (p.doc.attr(n, "width")) |a| lengthPx(a, p.view.w) else port.width;
+ const h = if (p.doc.attr(n, "height")) |a| lengthPx(a, p.view.h) else port.height;
+ if (v.w <= 0 or v.h <= 0 or w <= 0 or h <= 0) return;
+ transform = transform.mul(.translate(p.number(n, "x"), p.number(n, "y")));
+ // Stretched with `preserveAspectRatio="none"`, else centered at
+ // the largest scale that fits; drawn unclipped.
+ if (std.mem.startsWith(u8, std.mem.trim(u8, p.doc.attr(n, "preserveAspectRatio") orelse "", " "), "none")) {
+ transform = transform.mul(.scale(w / v.w, h / v.h));
+ } else {
+ const s = @min(w / v.w, h / v.h);
+ transform = transform.mul(.translate((w - v.w * s) / 2, (h - v.h * s) / 2)).mul(.scale(s, s));
+ }
+ transform = transform.mul(.translate(-v.x, -v.y));
+ // A document of its own: its ids, gradients and percentages, and
+ // nothing inherited but opacity.
+ const outer = p.*;
+ defer {
+ p.doc = outer.doc;
+ p.view = outer.view;
+ p.gradients = outer.gradients;
+ }
+ p.doc = &doc;
+ p.view = v;
+ p.gradients = .empty;
+ p.depth += 1;
+ defer p.depth -= 1;
+ return p.children(root, transform, .{ .style = .{ .opacity = inherited.style.opacity } });
+ }
const b = &p.b;
if (std.mem.eql(u8, name, "path")) {
@@ -766,3 +816,23 @@ test "colors and lengths" {
try std.testing.expectEqual(@as(f32, 20), parseLength("15pt"));
try std.testing.expectEqual(@as(f32, 0.5), parseOpacity("50%"));
}
+
+test "an SVG image in a data URI: its own ids, placed, stretched or fitted" {
+ var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
+ defer arena.deinit();
+ // <svg viewBox="0 0 10 20"><defs><path id="p" d="M0 0h10v20h-10z"/></defs><use href="#p" fill="#00ff00"/></svg>
+ const inner = "data:image/svg+xml;base64,PHN2ZyB2aWV3Qm94PSIwIDAgMTAgMjAiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGRlZnM+PHBhdGggaWQ9InAiIGQ9Ik0wIDBoMTB2MjBoLTEweiIvPjwvZGVmcz48dXNlIGhyZWY9IiNwIiBmaWxsPSIjMDBmZjAwIi8+PC9zdmc+";
+ const d = try parse(arena.allocator(), "<svg viewBox=\"0 0 100 100\"><defs><path id=\"p\" d=\"M0 0h1v1z\"/></defs>" ++
+ "<image x=\"5\" y=\"5\" width=\"20\" height=\"20\" preserveAspectRatio=\"none\" href=\"" ++ inner ++ "\"/>" ++
+ "<image x=\"5\" y=\"5\" width=\"20\" height=\"20\" xlink:href=\"" ++ inner ++ "\"/>" ++
+ "<image href=\"data:image/png;base64,AAAA\"/></svg>");
+ try std.testing.expectEqual(@as(usize, 2), d.shapes.len);
+ for (d.shapes) |shape| try std.testing.expectEqual(Drawing.Color{ 0, 1, 0, 1 }, shape.style.fill.color);
+ // The far corner (10, 20) of the image's own path: stretched to the
+ // box's corner, or fitted into its middle.
+ for (d.shapes, [_]geom.Vec{ .{ 25, 25 }, .{ 20, 25 } }) |shape, corner| {
+ const far = d.cubicsOf(d.subpathsOf(shape)[0])[1][3];
+ try std.testing.expectEqual(geom.vec(10, 20), far);
+ try std.testing.expectEqual(corner, shape.transform.apply(far));
+ }
+}
diff --git a/test/kill.script b/test/kill.script
new file mode 100644
index 0000000..824b741
--- /dev/null
+++ b/test/kill.script
@@ -0,0 +1,5 @@
+# A run without --fresh records to a file; it dies by SIGKILL after 255
+# frames, the last 15 of them not yet committed (test/killed.script).
+move 100 80
+frames 254
+kill
diff --git a/test/killed.script b/test/killed.script
new file mode 100644
index 0000000..7d0899c
--- /dev/null
+++ b/test/killed.script
@@ -0,0 +1,6 @@
+# After test/kill.script: its session kept the four commits of 60 frames it
+# made before it was killed, and says it crashed; this run starts from them,
+# replayed.
+expect updates 240
+console sessions
+expect-log frames 240 (crashed)
diff --git a/test/manual.script b/test/manual.script
new file mode 100644
index 0000000..707e5cc
--- /dev/null
+++ b/test/manual.script
@@ -0,0 +1,131 @@
+# The manual example (examples/manual.zig) on Vol. 2 of the Intel SDM:
+# Figure 2-1, then ADD's row 80 /0 ib becoming SUB's 80 /5 ib, stepped
+# through in the stock player, and exported twice. Built only when the PDF
+# is there (-Dmanual).
+frames 150
+expect deck.waiting true
+expect deck.log.len 0
+screenshot .zig-cache/manual/page.png
+# The page on its paper, the whole of it in view.
+expect-pixel .zig-cache/manual/page.png 400 650 255 255 255 255 2
+# Onto the figure; the rest of the page greys.
+key space
+await deck.waiting true
+screenshot .zig-cache/manual/figure.png
+expect-pixel .zig-cache/manual/figure.png 460 160 255 255 255 255 2
+# Each field in turn, tinted: the third is ModR/M.
+key space
+await deck.waiting true
+key space
+await deck.waiting true
+key space
+await deck.waiting true
+expect deck.log.len 4
+screenshot .zig-cache/manual/modrm.png
+expect-pixel .zig-cache/manual/modrm.png 460 160 192 233 242 255 3
+expect-pixel .zig-cache/manual/modrm.png 300 160 255 255 255 255 2
+# Back a step: Opcode's tint again, ModR/M's gone.
+key page_up
+expect deck.log.len 3
+frames 2
+screenshot .zig-cache/manual/opcode.png
+expect-pixel .zig-cache/manual/opcode.png 460 160 255 255 255 255 2
+expect-pixel .zig-cache/manual/opcode.png 300 160 192 233 242 255 3
+key space
+await deck.waiting true
+key space
+await deck.waiting true
+key space
+await deck.waiting true
+key space
+await deck.waiting true
+# 83 C0 01 written below, where the footnotes were.
+key space
+await deck.waiting true
+screenshot .zig-cache/manual/bytes.png
+# Into their fields: ModR/M's label gives way to C0.
+key space
+await deck.waiting true
+screenshot .zig-cache/manual/flown.png
+expect-different-screenshot .zig-cache/manual/bytes.png .zig-cache/manual/flown.png 440 140 180 90
+# C0 down into its boxes as bits, then split over Mod, Reg and R/M.
+key space
+await deck.waiting true
+screenshot .zig-cache/manual/bits.png
+expect-pixel .zig-cache/manual/bits.png 527 185 255 255 255 255 2
+key space
+await deck.waiting true
+screenshot .zig-cache/manual/split.png
+expect-different-screenshot .zig-cache/manual/bits.png .zig-cache/manual/split.png 280 420 310 70
+expect deck.log.len 11
+# Back to the page, filled in: the end of slide 1.
+key space
+await deck.waiting true
+expect deck.log.len 12
+expect deck.slide 1
+screenshot .zig-cache/manual/end.png
+expect-different-screenshot .zig-cache/manual/page.png .zig-cache/manual/end.png 470 260 340 120
+# Slide 2: ADD's page, its opcode table out of it.
+key space
+await deck.waiting true
+expect deck.slide 2
+expect deck.log.len 13
+screenshot .zig-cache/manual/add.png
+expect-pixel .zig-cache/manual/add.png 640 300 255 255 255 255 2
+# The table, written in row by row.
+key space
+await deck.waiting true
+screenshot .zig-cache/manual/table.png
+expect-different-screenshot .zig-cache/manual/add.png .zig-cache/manual/table.png 415 90 445 310
+# Onto the row 80 /0 ib, then its opcode cell tinted.
+key space
+await deck.waiting true
+screenshot .zig-cache/manual/row.png
+expect-pixel .zig-cache/manual/row.png 230 362 255 255 255 255 2
+key space
+await deck.waiting true
+screenshot .zig-cache/manual/cell.png
+expect-pixel .zig-cache/manual/cell.png 230 362 192 233 242 255 3
+# The digit after the slash becomes SUB's 5, closer in; back a step is the
+# picture before it (the bar under it aside: it shows the time).
+key space
+await deck.waiting true
+expect deck.log.len 17
+screenshot .zig-cache/manual/digit.png
+expect-different-screenshot .zig-cache/manual/cell.png .zig-cache/manual/digit.png 0 0 1280 680
+key page_up
+expect deck.log.len 16
+frames 2
+screenshot .zig-cache/manual/undone.png
+expect-same-screenshot .zig-cache/manual/cell.png .zig-cache/manual/undone.png 2 0 0 1280 680
+key space
+await deck.waiting true
+expect deck.log.len 17
+# The rest of the row follows, on SUB's page.
+key space
+await deck.waiting true
+screenshot .zig-cache/manual/sub.png
+expect-different-screenshot .zig-cache/manual/digit.png .zig-cache/manual/sub.png 0 0 1280 680
+# ADD's row over SUB's, what differs marked: the end of the talk.
+key space
+frames 240
+expect deck.log.len 19
+expect deck.waiting false
+screenshot .zig-cache/manual/rows.png
+expect-pixel .zig-cache/manual/rows.png 75 300 251 236 183 255 3
+expect-pixel .zig-cache/manual/rows.png 962 357 251 236 183 255 3
+# Exported ({a}, {b}: 10 fps, half size), each step held 1.5 s: the same
+# frames twice, and the talk moves through them (Figure 2-1 at 4, 20 and
+# 34 s; ADD's table being written at 45, its digit morphing at 56.5, the two
+# rows at the end, 66).
+expect-same-screenshot {a}/000040.png {b}/000040.png
+expect-same-screenshot {a}/000200.png {b}/000200.png
+expect-same-screenshot {a}/000340.png {b}/000340.png
+expect-same-screenshot {a}/000450.png {b}/000450.png
+expect-same-screenshot {a}/000565.png {b}/000565.png
+expect-same-screenshot {a}/000660.png {b}/000660.png
+expect-different-screenshot {a}/000040.png {a}/000200.png
+expect-different-screenshot {a}/000200.png {a}/000340.png
+expect-different-screenshot {a}/000340.png {a}/000450.png
+expect-different-screenshot {a}/000450.png {a}/000565.png
+expect-different-screenshot {a}/000565.png {a}/000660.png
diff --git a/test/past.script b/test/past.script
new file mode 100644
index 0000000..8ac9c25
--- /dev/null
+++ b/test/past.script
@@ -0,0 +1,8 @@
+# Session 0 of test-past (see build.zig): pointer driven, a mark at frame
+# 30, a jump (`set`) at frame 60, 300 frames in all.
+move 300 200
+frames 29
+console save probe
+frames 29
+console set velocity[0] 5
+frames 240
diff --git a/test/past_diverged.script b/test/past_diverged.script
new file mode 100644
index 0000000..6d275a2
--- /dev/null
+++ b/test/past_diverged.script
@@ -0,0 +1,6 @@
+# Session 0, replayed by a build whose pointer chase differs: it diverges
+# before the mark and is put back on it.
+console play session 0
+expect-log was built from
+frames 40
+expect-log diverged before frame 30
diff --git a/test/past_replay.script b/test/past_replay.script
new file mode 100644
index 0000000..0f11c64
--- /dev/null
+++ b/test/past_replay.script
@@ -0,0 +1,12 @@
+# Session 0 again, by the same build: from its start, half a second in is
+# the mark's State exactly; two seconds in, from the jump's keyframe, is
+# frame 120's.
+console play session 0
+console seek 499
+expect-snapshot probe
+expect-no-log diverged
+console play session 0 at 2
+expect updates 121
+console pause
+frames 30
+expect-no-log diverged
diff --git a/test/reload.script b/test/reload.script
index d2b2b36..72d1571 100644
--- a/test/reload.script
+++ b/test/reload.script
@@ -17,7 +17,9 @@ expect clicks 2
expect label warm
console snapshot 3
console save
+console set retired 3.5
load {v2}
+expect-key before_reload retired 3.5
expect clicks 2
expect label warm
expect streak 7 ~0.5
diff --git a/test/same_sessions.zig b/test/same_sessions.zig
new file mode 100644
index 0000000..af13be0
--- /dev/null
+++ b/test/same_sessions.zig
@@ -0,0 +1,66 @@
+//! test-same (build.zig): `same_sessions A B` exits 0 when two sessions
+//! databases hold the same values apart from the wall clock's (a session's
+//! `started` and `ended`), and otherwise names the first that differs.
+const std = @import("std");
+const Sessions = @import("Sessions");
+const DB = Sessions.Disk;
+const Cursor = DB.Cursor(.read_only);
+
+pub fn main(init: std.process.Init) !void {
+ const io = init.io;
+ const gpa = init.arena.allocator();
+ var args = init.minimal.args.iterate();
+ _ = args.skip();
+ var dbs: [2]DB = undefined;
+ var buffers: [2]std.Io.Writer.Allocating = undefined;
+ for (&dbs, &buffers) |*db, *buffer| {
+ const file = try std.Io.Dir.cwd().openFile(io, args.next() orelse return error.Usage, .{});
+ buffer.* = .init(gpa);
+ db.* = try DB.init(io, .{ .file = file, .buffer = buffer, .fsync = false });
+ }
+ if (!try same(gpa, dbs[0].rootCursor().readOnly(), dbs[1].rootCursor().readOnly(), "root")) std.process.exit(1);
+}
+
+fn same(gpa: std.mem.Allocator, a: Cursor, b: Cursor, at: []const u8) anyerror!bool {
+ const tag = (try a.slot()).tag;
+ if (tag != (try b.slot()).tag) return differ(at, "kinds");
+ switch (tag) {
+ .uint => if (try a.readUint() != try b.readUint()) return differ(at, "numbers"),
+ .bytes, .short_bytes => {
+ if (!std.mem.eql(u8, try a.readBytesAlloc(gpa, null), try b.readBytesAlloc(gpa, null))) return differ(at, "bytes");
+ },
+ .array_list => {
+ if (try a.count() != try b.count()) return differ(at, "lengths");
+ var ia = try a.iterator();
+ var ib = try b.iterator();
+ var i: usize = 0;
+ while (try ia.next()) |ca| : (i += 1) {
+ if (!try same(gpa, ca, (try ib.next()).?, try std.fmt.allocPrint(gpa, "{s}[{d}]", .{ at, i }))) return false;
+ }
+ },
+ .hash_map => {
+ const mb = try DB.HashMap(.read_only).init(b);
+ var n: usize = 0;
+ var ia = try a.iterator();
+ while (try ia.next()) |kv_cursor| {
+ const kv = try kv_cursor.readKeyValuePair();
+ n += 1;
+ const name = if (std.enums.fromInt(Sessions.K, kv.hash)) |k| @tagName(k) else "?";
+ const there = try std.fmt.allocPrint(gpa, "{s}.{s}", .{ at, name });
+ const cb = try mb.getCursor(kv.hash) orelse return differ(there, "presence");
+ if (std.mem.eql(u8, name, "started") or std.mem.eql(u8, name, "ended")) continue;
+ if (!try same(gpa, kv.value_cursor, cb, there)) return false;
+ }
+ var ib = try b.iterator();
+ while (try ib.next()) |_| n -%= 1;
+ if (n != 0) return differ(at, "fields");
+ },
+ else => return differ(at, "kinds (unknown)"),
+ }
+ return true;
+}
+
+fn differ(at: []const u8, what: []const u8) bool {
+ std.debug.print("same_sessions: the databases' {s} differ at {s}\n", .{ what, at });
+ return false;
+}
diff --git a/test/scene_compiled.script b/test/scene_compiled.script
index 3c9ef44..df2d62f 100644
--- a/test/scene_compiled.script
+++ b/test/scene_compiled.script
@@ -2,7 +2,7 @@
# 30 fps, 640x360, so half size, played once without the player's controls).
frames 30
screenshot .zig-cache/anim/compiled-written.png
-console set t 1.5
+console set deck.t 1.5
frames 1
screenshot .zig-cache/anim/compiled-morph.png
# Frame 68 is 2.27 s in: the dot over the panel's corner, at half size.
diff --git a/test/scene_live.script b/test/scene_live.script
index 30b2087..e480d8d 100644
--- a/test/scene_live.script
+++ b/test/scene_live.script
@@ -1,6 +1,9 @@
-# The live test scene, through the player. It holds at the pause.
+# The live test scene, through the player. At the pause it waits for a
+# click, time running on and nothing after the pause starting.
frames 150
-expect t 2
+expect deck.waiting true
+expect deck.t 2.5 ~0.02
+expect deck.log.len 0
screenshot .zig-cache/anim/live.png
# The custom panel is over the circle added before it,
expect-pixel .zig-cache/anim/live.png 600 330 32 64 96 255 1
@@ -11,23 +14,25 @@ expect-pixel .zig-cache/anim/live.png 725 400 131 193 103 255 1
expect-pixel .zig-cache/anim/live.png 600 390 240 172 95 255 1
expect-pixel .zig-cache/anim/live.png 680 390 32 64 96 255 1
# Half way through its move it is half way.
-console set playing false
-console set t 1.5
+console set deck.playing false
+console set deck.t 1.5
screenshot .zig-cache/anim/live-moving.png
expect-pixel .zig-cache/anim/live-moving.png 400 330 32 64 96 255 1
expect-pixel .zig-cache/anim/live-moving.png 600 330 252 98 85 255 1
# The CPU renderer layers the same way.
-console set t 2
+console set deck.t 2
key b
expect backend cpu
screenshot .zig-cache/anim/live-cpu.png
expect-pixel .zig-cache/anim/live-cpu.png 600 330 32 64 96 255 1
expect-pixel .zig-cache/anim/live-cpu.png 725 400 131 193 103 255 1
key b
-# A click continues: the camera zooms to 2 and the panel fades to half,
-# over the background where it now reaches.
+# A click opens the pause and plays on: the camera zooms to 2 and the
+# panel fades to half, over the background where it now reaches.
click 640 360
-expect playing true
+expect deck.playing true
+expect deck.log.len 1
+expect deck.waiting false
frames 70
screenshot .zig-cache/anim/live-zoom.png
expect-pixel .zig-cache/anim/live-zoom.png 800 300 30 46 64 255 2
diff --git a/test/scene_morph.script b/test/scene_morph.script
new file mode 100644
index 0000000..0da4670
--- /dev/null
+++ b/test/scene_morph.script
@@ -0,0 +1,46 @@
+# Holes through morphs (test/scene_morph.zig), a quarter, half and three
+# quarters of the way, on the GPU and then on the CPU: the middle of each
+# hole is the background, the ring around it drawn (the 0 into the 5 while
+# its hole is half its size or more); at the end the disc fills it.
+console set deck.playing false
+console set deck.t 1
+screenshot .zig-cache/anim/morph-1.png
+expect-pixel .zig-cache/anim/morph-1.png 300 360 255 255 255 255 1
+expect-pixel .zig-cache/anim/morph-1.png 240 360 28 28 31 255 1
+expect-pixel .zig-cache/anim/morph-1.png 640 360 28 28 31 255 1
+expect-pixel .zig-cache/anim/morph-1.png 1040 360 28 28 31 255 1
+console set deck.t 2
+screenshot .zig-cache/anim/morph-2.png
+expect-pixel .zig-cache/anim/morph-2.png 300 360 255 255 255 255 1
+expect-pixel .zig-cache/anim/morph-2.png 240 360 28 28 31 255 1
+expect-pixel .zig-cache/anim/morph-2.png 640 360 28 28 31 255 1
+expect-pixel .zig-cache/anim/morph-2.png 1040 360 28 28 31 255 1
+console set deck.t 3
+screenshot .zig-cache/anim/morph-3.png
+expect-pixel .zig-cache/anim/morph-3.png 300 360 255 255 255 255 1
+expect-pixel .zig-cache/anim/morph-3.png 240 360 28 28 31 255 1
+expect-pixel .zig-cache/anim/morph-3.png 1040 360 28 28 31 255 1
+key b
+expect backend cpu
+console set deck.t 1
+screenshot .zig-cache/anim/morph-cpu-1.png
+expect-pixel .zig-cache/anim/morph-cpu-1.png 300 360 255 255 255 255 1
+expect-pixel .zig-cache/anim/morph-cpu-1.png 240 360 28 28 31 255 1
+expect-pixel .zig-cache/anim/morph-cpu-1.png 640 360 28 28 31 255 1
+expect-pixel .zig-cache/anim/morph-cpu-1.png 1040 360 28 28 31 255 1
+console set deck.t 2
+screenshot .zig-cache/anim/morph-cpu-2.png
+expect-pixel .zig-cache/anim/morph-cpu-2.png 300 360 255 255 255 255 1
+expect-pixel .zig-cache/anim/morph-cpu-2.png 240 360 28 28 31 255 1
+expect-pixel .zig-cache/anim/morph-cpu-2.png 640 360 28 28 31 255 1
+expect-pixel .zig-cache/anim/morph-cpu-2.png 1040 360 28 28 31 255 1
+console set deck.t 3
+screenshot .zig-cache/anim/morph-cpu-3.png
+expect-pixel .zig-cache/anim/morph-cpu-3.png 300 360 255 255 255 255 1
+expect-pixel .zig-cache/anim/morph-cpu-3.png 240 360 28 28 31 255 1
+expect-pixel .zig-cache/anim/morph-cpu-3.png 1040 360 28 28 31 255 1
+console set deck.t 4
+screenshot .zig-cache/anim/morph-cpu-4.png
+expect-pixel .zig-cache/anim/morph-cpu-4.png 240 360 255 255 255 255 1
+expect-pixel .zig-cache/anim/morph-cpu-4.png 640 360 255 255 255 255 1
+expect-pixel .zig-cache/anim/morph-cpu-4.png 1040 360 28 28 31 255 1
diff --git a/test/scene_morph.zig b/test/scene_morph.zig
new file mode 100644
index 0000000..fbde51d
--- /dev/null
+++ b/test/scene_morph.zig
@@ -0,0 +1,25 @@
+//! Holes through a morph (vector/morph.zig), for test/scene_morph.script:
+//! a ring into a disc, a 0 into a 5, and a 0 whose path has its hole first
+//! into a ring, side by side, together over 4 s at a steady pace.
+const anim = @import("anim");
+
+pub const scene = anim.Scene(construct);
+
+const disc = "M 40 0 C 40 22 22 40 0 40 C -22 40 -40 22 -40 0 C -40 -22 -22 -40 0 -40 C 22 -40 40 -22 40 0 Z ";
+const ring_hole = "M 20 0 C 20 -11 11 -20 0 -20 C -11 -20 -20 -11 -20 0 C -20 11 -11 20 0 20 C 11 20 20 11 20 0 Z ";
+const zero = "M 0 -45 C 25 -45 30 -20 30 0 C 30 20 25 45 0 45 C -25 45 -30 20 -30 0 C -30 -20 -25 -45 0 -45 Z ";
+const zero_hole = "M 0 -25 C -12 -25 -14 -12 -14 0 C -14 12 -12 25 0 25 C 12 25 14 12 14 0 C 14 -12 12 -25 0 -25 Z ";
+const five = "M -25 -45 H 25 V -33 H -13 V -8 H 5 L 20 -3 L 28 10 V 25 L 20 40 L 5 45 H -25 V 33 H 5 L 14 25 V 10 L 5 4 H -25 Z ";
+
+const head = "<svg viewBox=\"-50 -50 100 100\" width=\"100\" height=\"100\"><path fill=\"white\" d=\"";
+const tail = "\"/></svg>";
+
+fn construct(s: *anim.Builder) void {
+ const pairs = .{ .{ disc ++ ring_hole, disc, -400 }, .{ zero ++ zero_hole, five, 0 }, .{ zero_hole ++ zero, disc ++ ring_hole, 400 } };
+ var morphs: [pairs.len]anim.Animation = undefined;
+ inline for (pairs, &morphs) |p, *m| {
+ const from = s.svg(head ++ p[0] ++ tail, .{ .x = p[2], .scale = 2, .visible = true });
+ m.* = from.transformInto(s.svg(head ++ p[1] ++ tail, .{ .x = p[2], .scale = 2 }));
+ }
+ s.play(morphs, .{ .seconds = 4, .ease = anim.ease.linear });
+}
diff --git a/test/session_export.script b/test/session_export.script
new file mode 100644
index 0000000..a90587e
--- /dev/null
+++ b/test/session_export.script
@@ -0,0 +1,3 @@
+# test-import (see build.zig): session 0 of test/past.script's database,
+# written to a file of its own, as a playtester would send it.
+console export-session 0 {file}
diff --git a/test/session_import.script b/test/session_import.script
new file mode 100644
index 0000000..bcc3126
--- /dev/null
+++ b/test/session_import.script
@@ -0,0 +1,13 @@
+# test-import: the session test/session_export.script wrote, imported into
+# another database as its session 1, plays there as it did where it was
+# recorded: half a second in is the mark's State exactly (the mark came
+# with it, renamed), two seconds in is frame 120's.
+console import {file}
+console sessions
+expect-log import one.xitdb
+console play session 1
+console seek 499
+expect-snapshot [email protected]
+expect-no-log diverged
+console play session 1 at 2
+expect updates 121
diff --git a/test/svg/image.svg b/test/svg/image.svg
new file mode 100644
index 0000000..f5a5d8e
--- /dev/null
+++ b/test/svg/image.svg
@@ -0,0 +1,9 @@
+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 200 100" width="200" height="100">
+ <!-- SVG documents as data-URI images (how Typst places an SVG or a PDF
+ page): placed, stretched or fitted into their boxes, with their own ids
+ and gradients, and an id the outer document also uses. -->
+ <defs><radialGradient id="g"><stop offset="0" stop-color="#58c4dd"/><stop offset="1" stop-color="#9a72ac"/></radialGradient></defs>
+ <rect x="150" y="10" width="40" height="80" fill="url(#g)"/>
+ <image x="10" y="10" width="40" height="80" xlink:href="data:image/svg+xml;base64,PHN2ZyB2aWV3Qm94PSIwIDAgNDAgNDAiIHdpZHRoPSI0MHB0IiBoZWlnaHQ9IjQwcHQiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPgo8ZGVmcz48cmFkaWFsR3JhZGllbnQgaWQ9ImciPjxzdG9wIG9mZnNldD0iMCIgc3RvcC1jb2xvcj0iI2Y3ZDk2ZiIvPjxzdG9wIG9mZnNldD0iMSIgc3RvcC1jb2xvcj0iI2ZjNjI1NSIvPjwvcmFkaWFsR3JhZGllbnQ+CjxzeW1ib2wgaWQ9ImxlYWYiIG92ZXJmbG93PSJ2aXNpYmxlIj48cGF0aCBkPSJNMCAwIEM4IC04IDE2IC04IDIwIDAgQzE2IDggOCA4IDAgMFoiLz48L3N5bWJvbD48L2RlZnM+CjxjaXJjbGUgY3g9IjIwIiBjeT0iMjAiIHI9IjE4IiBmaWxsPSJ1cmwoI2cpIi8+Cjx1c2UgeGxpbms6aHJlZj0iI2xlYWYiIHg9IjEwIiB5PSIyMCIgZmlsbD0iIzgzYzE2NyIvPgo8L3N2Zz4="/>
+ <image x="55" y="20" width="90" height="60" preserveAspectRatio="none" href="data:image/svg+xml;base64,PHN2ZyB2aWV3Qm94PSIwIDAgNDAgNDAiIHdpZHRoPSI0MHB0IiBoZWlnaHQ9IjQwcHQiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPgo8ZGVmcz48cmFkaWFsR3JhZGllbnQgaWQ9ImciPjxzdG9wIG9mZnNldD0iMCIgc3RvcC1jb2xvcj0iI2Y3ZDk2ZiIvPjxzdG9wIG9mZnNldD0iMSIgc3RvcC1jb2xvcj0iI2ZjNjI1NSIvPjwvcmFkaWFsR3JhZGllbnQ+CjxzeW1ib2wgaWQ9ImxlYWYiIG92ZXJmbG93PSJ2aXNpYmxlIj48cGF0aCBkPSJNMCAwIEM4IC04IDE2IC04IDIwIDAgQzE2IDggOCA4IDAgMFoiLz48L3N5bWJvbD48L2RlZnM+CjxjaXJjbGUgY3g9IjIwIiBjeT0iMjAiIHI9IjE4IiBmaWxsPSJ1cmwoI2cpIi8+Cjx1c2UgeGxpbms6aHJlZj0iI2xlYWYiIHg9IjEwIiB5PSIyMCIgZmlsbD0iIzgzYzE2NyIvPgo8L3N2Zz4=" transform="rotate(10 100 50)"/>
+</svg>
diff --git a/test/svg/typst-image.typ b/test/svg/typst-image.typ
new file mode 100644
index 0000000..2c88207
--- /dev/null
+++ b/test/svg/typst-image.typ
@@ -0,0 +1,6 @@
+// An SVG placed by Typst: an <image> with the document as a data URI.
+#set page(width: auto, height: auto, margin: 6pt, fill: none)
+#stack(dir: ltr, spacing: 8pt,
+ image("use.svg", width: 120pt),
+ image("gradients.svg", width: 80pt, height: 60pt, fit: "stretch"),
+)
diff --git a/test/talk.script b/test/talk.script
new file mode 100644
index 0000000..e123d59
--- /dev/null
+++ b/test/talk.script
@@ -0,0 +1,104 @@
+# The talk example (examples/talk.zig): a Deck in the sketch's own State,
+# stepped by the clicks and keys the sketch turns into asks.
+frames 90
+expect deck.waiting false
+expect deck.slide 1
+# Slide 2 lies after the choice, which has not been made.
+expect deck.slides 1
+# A click during the first step finishes it: held at the first pause.
+click 100 100
+expect deck.t 2.5 ~0.0001
+expect deck.waiting true
+expect deck.log.len 0
+# The mass bobs while the deck waits.
+screenshot .zig-cache/talk/bob-a.png
+frames 14
+screenshot .zig-cache/talk/bob-b.png
+expect-different-screenshot .zig-cache/talk/bob-a.png .zig-cache/talk/bob-b.png
+# The next click opens the pause where it lands: the slider comes in, and
+# the deck waits at the choice.
+click 100 100
+expect deck.log.len 1
+expect deck.log.buffer[0].wait 0.2833 ~0.001
+await deck.waiting true
+frames 5
+# Reloaded mid-wait, the first step retimed from 2 s to 3: the same step,
+# as far into it, a second later.
+console set deck.playing false
+expect deck.t 3.4833 ~0.001
+load {v2}
+expect deck.t 4.4833 ~0.001
+expect deck.waiting true
+expect deck.log.len 1
+expect deck.log.buffer[0].wait 0.2833 ~0.001
+console set deck.playing true
+# A click on the slider is the slider's: zeta goes there, the deck stays.
+click 790 580
+expect app.zeta 1.5 ~0.01
+expect deck.log.len 1
+expect deck.waiting true
+# So is a drag along it, let go and all.
+down 640 580
+move 400 580
+up 400 580
+expect app.zeta 0.2 ~0.01
+expect app.dragging false
+expect deck.log.len 1
+expect deck.waiting true
+# Going on chooses by the slider: under 1, it rings; slide 2 is laid.
+key space
+expect deck.log.len 2
+expect deck.log.buffer[1].value 0
+expect deck.slides 2
+frames 90
+screenshot .zig-cache/talk/rings.png
+# Back: held at the choice again; over 1, it creeps.
+key page_up
+expect deck.log.len 1
+expect deck.waiting true
+click 840 580
+expect app.zeta 1.667 ~0.01
+key space
+expect deck.log.len 2
+expect deck.log.buffer[1].value 1
+frames 90
+screenshot .zig-cache/talk/creeps.png
+expect-different-screenshot .zig-cache/talk/rings.png .zig-cache/talk/creeps.png
+# Slide 2 at rest: it holds no pause, so its end.
+key right_bracket
+expect deck.slide 2
+expect deck.log.len 3
+expect deck.waiting false
+# Back a slide: slide 1 at rest, held at its first pause (3 s of writing
+# in this build, then the mass).
+key left_bracket
+expect deck.slide 1
+expect deck.log.len 0
+expect deck.t 3.5 ~0.0001
+expect deck.waiting true
+# Recorded, clicks, the slider and keys replay to the same State: the deck
+# opens gates in update, from events and State alone.
+console record 0
+click 100 100
+frames 40
+click 790 580
+key space
+frames 30
+key page_up
+key right_bracket
+frames 10
+console save 2
+console play 0
+frames 120
+expect-snapshot 2
+console stop
+# Exported ({a}, {b}: 30 fps, half size), each gate holds 2 s: the mass
+# bobs through the first hold (to 4.5 s), nothing moves at the choice
+# (5.1 to 7.1 s), and the verdict writes after it. Twice, the same frames.
+expect-different-screenshot {a}/000080.png {a}/000090.png
+expect-different-screenshot {a}/000130.png {a}/000170.png
+expect-same-screenshot {a}/000170.png {a}/000200.png
+expect-different-screenshot {a}/000200.png {a}/000230.png
+expect-same-screenshot {a}/000080.png {b}/000080.png
+expect-same-screenshot {a}/000230.png {b}/000230.png
+expect-same-screenshot {a}/000350.png {b}/000350.png
diff --git a/test/voices.script b/test/voices.script
new file mode 100644
index 0000000..4b444d0
--- /dev/null
+++ b/test/voices.script
@@ -0,0 +1,29 @@
+# A sound made with host.newSound is a voice like a loaded one: it sounds
+# once for its serial, a replay that keeps declaring that serial does not
+# sound it again, and a new serial does.
+frames 3
+expect-no-audio 1
+key space
+expect coins 1
+expect-audio 1
+frames 10
+expect-no-audio 1
+# Recorded while the blip is declared but finished, then played back,
+# stepped and seeked over: the same serial all along, so it stays silent.
+console record 0
+frames 20
+console stop
+console play 0
+frames 30
+expect-no-audio 1
+console seek start
+console step 5
+console seek end
+expect-no-audio 1
+console stop
+# A new serial starts it again.
+key space
+expect coins 2
+expect-audio 1
+frames 10
+expect-no-audio 1
diff --git a/test/voices.zig b/test/voices.zig
new file mode 100644
index 0000000..141e562
--- /dev/null
+++ b/test/voices.zig
@@ -0,0 +1,26 @@
+//! A sound the sketch made itself, played as a voice: space bumps the
+//! serial that starts it (test/voices.script). The README's sfxr blip.
+const sk = @import("sketch");
+
+pub const name = "voices";
+pub const width = 160;
+pub const height = 120;
+
+pub const State = struct { coins: u32 = 0 };
+pub const Session = struct { blip: sk.Audio = .none };
+
+pub fn update(s: *State, in: *const sk.Input) void {
+ if (in.pressed(sk.Key.space)) s.coins += 1;
+}
+
+pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void {
+ f.clear(0x202020);
+ // About 1300 samples: shorter than the host's lead (2048), so the first
+ // frame that declares it mixes all of it.
+ 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 });
+}
diff --git a/tools/bench.zig b/tools/bench.zig
index faa769e..5412866 100644
--- a/tools/bench.zig
+++ b/tools/bench.zig
@@ -1,17 +1,29 @@
//! How long a frame of vector graphics takes, per stage, in release mode:
//! parsing the SVG, turning it into polygons and coverage (CPU backend), or
//! into a GPU pass description (GPU backend; the GPU's own time is not
-//! measured here).
+//! measured here). The objects: the compiled test scene's, and the manual
+//! example's page of the Intel SDM (when the build has the PDF), thousands
+//! of shapes, with a budget of its own.
const std = @import("std");
const vector = @import("vector");
const scene = @import("scene").scene;
const typst = @import("typst");
+const manual = @import("manual").scene;
+const manual_typst = @import("manual_typst");
const width = 1280;
const height = 720;
const runs = 300;
/// Drawings up to this many shapes count as simple: they must take < 1ms.
const simple_shapes = 30;
+/// Drawings of more count as a page (Figure 2-1's page of the SDM is 1954
+/// shapes; measured on a loaded 16-core machine: parse 6-12 ms, CPU draw
+/// 2-5 ms, GPU record 0.85-1.7 ms). Parsing is once per object, drawing
+/// every frame.
+const page_shapes = 1000;
+const page_parse_ms = 25;
+const page_cpu_ms = 10;
+const page_gpu_ms = 4;
/// Stand-in for `sketch.Host`: the renderers only need images (and to free
/// the GPU backend's paint buffer, which this bench never makes).
@@ -34,48 +46,59 @@ pub fn main(init: std.process.Init) !void {
defer objects_arena.deinit();
const shot = try scene.shot(objects_arena.allocator(), .{ .t = 0 });
for (shot.objects, 0..) |object, index| if (object.source == .typst) {
- const svg = typst.find(object.source.typst).?;
- var arena: std.heap.ArenaAllocator = .init(gpa);
- defer arena.deinit();
- var cpu: vector.Renderer(.cpu) = try .init(gpa, Host{}, width, height);
- defer cpu.deinit(Host{});
- var gpu: vector.Renderer(.gpu) = try .init(gpa, Host{}, width, height);
- defer gpu.deinit(Host{});
- const Frame = struct { scratch: std.mem.Allocator };
-
- var parse_ns: [runs]u64 = undefined;
- var cpu_ns: [runs]u64 = undefined;
- var gpu_ns: [runs]u64 = undefined;
- var shapes: usize = 0;
- for (0..runs) |i| {
- _ = arena.reset(.retain_capacity);
- const t0 = now(io);
- const d = try vector.svg.parse(arena.allocator(), svg);
- const t1 = now(io);
- // Fit to the canvas, as large as it goes: the worst case.
- const m = vector.fit(d, .{ .w = width, .h = height });
- cpu.begin(Frame{ .scratch = arena.allocator() }, .{ 0, 0, 0, 1 });
- try cpu.draw(d, m, 1);
- const t2 = now(io);
- gpu.begin(Frame{ .scratch = arena.allocator() }, .{ 0, 0, 0, 1 });
- try gpu.draw(d, m, 1);
- std.mem.doNotOptimizeAway(gpu.target.pass());
- const t3 = now(io);
- parse_ns[i] = t1 - t0;
- cpu_ns[i] = t2 - t1;
- gpu_ns[i] = t3 - t2;
- shapes = d.shapes.len;
- }
- const p = median(&parse_ns);
- const c = median(&cpu_ns);
- const g = median(&gpu_ns);
- std.debug.print("{d:>2} {s:<21} {d:>7} {d:>8.3}ms {d:>8.3}ms {d:>8.3}ms {d:>8.3}ms\n", .{ index, label(object.source.typst), shapes, ms(p), ms(c), ms(g), ms(p + c) });
- if (shapes <= simple_shapes and (p + c > std.time.ns_per_ms or p + g > std.time.ns_per_ms)) failed = true;
+ if (try bench(gpa, io, index, object.source.typst, typst.find(object.source.typst).?)) failed = true;
+ };
+ // The manual's page of the SDM, when the build has the PDF.
+ for (manual.typst_sources, 0..) |source, index| if (std.mem.startsWith(u8, source, "#image(")) {
+ if (try bench(gpa, io, index, source, manual_typst.find(source).?)) failed = true;
};
- std.debug.print("\nup to {d} shapes must parse and draw in under 1ms at {d}x{d}, filling the canvas.\n", .{ simple_shapes, width, height });
+ std.debug.print("\nup to {d} shapes must parse and draw in under 1ms at {d}x{d}, filling the canvas;\n", .{ simple_shapes, width, height });
+ std.debug.print("a page (over {d}) parse in under {d}ms, draw on the CPU in {d}ms and record for the GPU in {d}ms.\n", .{ page_shapes, page_parse_ms, page_cpu_ms, page_gpu_ms });
if (failed) return error.TooSlow;
}
+/// Times one SVG, prints its line, and says whether it is over budget.
+fn bench(gpa: std.mem.Allocator, io: std.Io, index: usize, source: []const u8, svg: []const u8) !bool {
+ var arena: std.heap.ArenaAllocator = .init(gpa);
+ defer arena.deinit();
+ var cpu: vector.Renderer(.cpu) = try .init(gpa, Host{}, width, height);
+ defer cpu.deinit(Host{});
+ var gpu: vector.Renderer(.gpu) = try .init(gpa, Host{}, width, height);
+ defer gpu.deinit(Host{});
+ const Frame = struct { scratch: std.mem.Allocator };
+
+ var parse_ns: [runs]u64 = undefined;
+ var cpu_ns: [runs]u64 = undefined;
+ var gpu_ns: [runs]u64 = undefined;
+ var shapes: usize = 0;
+ for (0..runs) |i| {
+ _ = arena.reset(.retain_capacity);
+ const t0 = now(io);
+ const d = try vector.svg.parse(arena.allocator(), svg);
+ const t1 = now(io);
+ // Fit to the canvas, as large as it goes: the worst case.
+ const m = vector.fit(d, .{ .w = width, .h = height });
+ cpu.begin(Frame{ .scratch = arena.allocator() }, .{ 0, 0, 0, 1 });
+ try cpu.draw(d, m, 1);
+ const t2 = now(io);
+ gpu.begin(Frame{ .scratch = arena.allocator() }, .{ 0, 0, 0, 1 });
+ try gpu.draw(d, m, 1);
+ std.mem.doNotOptimizeAway(gpu.target.pass());
+ const t3 = now(io);
+ parse_ns[i] = t1 - t0;
+ cpu_ns[i] = t2 - t1;
+ gpu_ns[i] = t3 - t2;
+ shapes = d.shapes.len;
+ }
+ const p = median(&parse_ns);
+ const c = median(&cpu_ns);
+ const g = median(&gpu_ns);
+ std.debug.print("{d:>2} {s:<21} {d:>7} {d:>8.3}ms {d:>8.3}ms {d:>8.3}ms {d:>8.3}ms\n", .{ index, label(source), shapes, ms(p), ms(c), ms(g), ms(p + c) });
+ if (shapes <= simple_shapes) return p + c > std.time.ns_per_ms or p + g > std.time.ns_per_ms;
+ if (shapes > page_shapes) return p > page_parse_ms * std.time.ns_per_ms or c > page_cpu_ms * std.time.ns_per_ms or g > page_gpu_ms * std.time.ns_per_ms;
+ return false;
+}
+
/// The start of a Typst source's first line.
fn label(source: []const u8) []const u8 {
const line = source[0 .. std.mem.indexOfScalar(u8, source, '\n') orelse source.len];
diff --git a/web/host.js b/web/host.js
index efc335d..32bdbfb 100644
--- a/web/host.js
+++ b/web/host.js
@@ -314,13 +314,16 @@ const gpu = {
// Reads a buffer back; it reaches the sketch before a later frame.
arrived: [],
download(id, offset, size, key) {
+ gpu.read(id, offset, size, bytes => gpu.arrived.push({key, bytes}));
+ },
+ read(id, offset, size, then) {
const staging = gpu.spare.find(b => b.size >= size) ?? gpu.device.createBuffer({size: Math.max(size, 256), usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST});
gpu.spare = gpu.spare.filter(b => b !== staging);
const commands = gpu.device.createCommandEncoder();
commands.copyBufferToBuffer(gpu.buffers[id], offset, staging, 0, size);
gpu.device.queue.submit([commands.finish()]);
staging.mapAsync(GPUMapMode.READ, 0, size).then(() => {
- gpu.arrived.push({key, bytes: new Uint8Array(staging.getMappedRange(0, size)).slice()});
+ then(new Uint8Array(staging.getMappedRange(0, size)).slice());
staging.unmap();
gpu.spare.push(staging);
}, () => {});
@@ -392,7 +395,8 @@ const sound = {
}
},
queue(key) {
- if (!sound.queues.has(key)) sound.queues.set(key, {chunks: [], at: 0, queued: 0});
+ // `waiting`: GPU buffers on their way, in order (counted as queued).
+ if (!sound.queues.has(key)) sound.queues.set(key, {chunks: [], waiting: [], at: 0, queued: 0});
return sound.queues.get(key);
},
listen() {
@@ -660,9 +664,21 @@ const imports = {
push(key, ptr, len, clear) {
if (len) sound.hint();
const q = sound.queue(key);
- if (clear) { q.chunks = []; q.at = 0; q.queued = 0; }
+ if (clear) { q.chunks = []; q.waiting = []; q.at = 0; q.queued = 0; }
if (len) { q.chunks.push(new Float32Array(wasm.memory.buffer.slice(ptr, ptr + len * 4))); q.queued += len; }
},
+ buffer(key, id, offset, count) {
+ if (!gpu.buffers[id]) return;
+ sound.hint();
+ const q = sound.queue(key);
+ const chunk = {samples: null};
+ q.waiting.push(chunk);
+ q.queued += count;
+ gpu.read(id, offset, count * 4, bytes => {
+ chunk.samples = new Float32Array(bytes.buffer);
+ while (q.waiting.length && q.waiting[0].samples) q.chunks.push(q.waiting.shift().samples);
+ });
+ },
queued: key => sound.queues.get(key)?.queued ?? 0,
listen: () => sound.listen(),
},