diff options
Diffstat (limited to 'README.md')
| -rw-r--r-- | README.md | 252 |
1 files changed, 164 insertions, 88 deletions
@@ -32,6 +32,7 @@ The standalone example packages live in [`examples/`](examples/): - [`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, a PDF page as vector shapes and parts of it (`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; @@ -44,24 +45,23 @@ 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, kept in every session's keyframes and marks, replayed: what `update` changes. No pointers and no host handles (compile errors). | +| `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 @@ -82,14 +82,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. @@ -128,10 +125,10 @@ State. `imageAt`, `target`, `blend`, `text`, `print`, `clip`, `canvas`, `cursor`, `voice`, `gain`, `audio`, `audioBuffer`, `microphone`, `pixels`, `gpu`, `compute`, `upload`, `download`, `openFile`, `run`, `quit`, plus the three allocators and `f.host` (`loadImage`, `decodeImage`, `newImage`, `newBuffer`, `loadSound`, -`decodeSound`, `newSound`, `samples`, `readFile`, `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 @@ -168,8 +165,18 @@ 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 @@ -368,9 +375,8 @@ after a reload that shrinks it. The default buffer is the element's own defaults, never `std.mem.zeroes` (an enum may have no 0). **Data that grows.** State is kept in keyframes, replayed and migrated, so -it holds what `update` changes, at a size fixed in its type. Store is not -kept in keyframes or replayed, so what is in it does not follow a seek. Three -cases, by who needs the data: +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). @@ -384,7 +390,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`). @@ -547,8 +554,8 @@ 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 @@ -591,6 +598,55 @@ 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 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. 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 on Figure 2-1 of the SDM (Vol. 2, 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. `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` @@ -784,37 +840,40 @@ a talk with a slider, a loop, a choice, two slides and `beside`. 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. -- **State file.** `<name>.state` holds the live State, shared via - `MAP_SHARED`, so the file is up to date as it changes. Its header carries - the reflected layout, so a layout change migrates it field by field, with - enums matched by tag name, and `sketchbook-probe` can print any sketch's - state. Arrays and vectors migrate element by element: the elements both - layouts have, each field by field, so an element type can gain a field - and a capacity can grow (new elements take their defaults) or shrink (the - rest is dropped; a count field such as `sk.List`'s `len` is kept, and - `List` clamps it where it is read). An array whose type is unchanged is - copied whole. Files from before element leaves (`SKETCH01`) are read and - rewritten, and the snapshot slots of files from before sessions become - marks `1` to `7` in a run that records; 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. - Keyframes, marks and replays do not cover it (only `draw` and `command` - change it). -- **Where files go.** `zig build run`, `probe` and `export` keep a sketch's - files in `.sketchbook/`: `<name>.state`, `<name>.state.store` and - `<name>.xitdb`. The host makes the directory with a `.gitignore` of `*`, - so neither git nor jj takes in a database that grows (the jj snapshot a - build makes would commit one while it is under a megabyte), and moves in, - once, the state and store 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.state` in the working directory. -- **Sessions.** Every run of a build that records is a session in - `<name>.xitdb`, one xitdb database per sketch beside its state file: an - append-only log of the events live `update` was fed, in whole frames, and +- **The save.** A sketch keeps one thing, State, in one file, its save: + `<name>.xitdb`, an xitdb database. Live State is process memory; the save + holds the present, its newest keyframe and the frames logged after it, + which a run restores and replays through `update` (played by another + build, the keyframe alone, and the run says how many frames it left), + so a run starts where the last stopped; and the history before it + (Sessions, below). `--fresh` starts from defaults and leaves the save as + it is. A keyframe is State in 4 KiB pages and writes only the pages that + changed since the keyframe before it, an all-zero page nothing: about 5 + KB a keyframe for drat-meout's 20 KiB State, 10 KB for a 4 MiB State + edited once a minute. Each stretch carries the reflected layout, so a + keyframe from an older layout migrates field by field, with enums + matched by tag name, and so does live State at a reload. Arrays and + vectors migrate element by element: the elements both layouts have, each + field by field, so an element type can gain a field and a capacity can + grow (new elements take their defaults) or shrink (the rest is dropped; a + count field such as `sk.List`'s `len` is kept, and `List` clamps it where + it is read). An array whose type is unchanged is copied whole. A state + file from before (`<name>.state` beside the save, any of its formats) is + imported into a new save once: its State the present, its snapshot slots + marks `1` to `7`; the file is left as it was and not read again, and one + that is not a state file is said and left. +- **Where files go.** `zig build run` and `export` keep a sketch's files in + `.sketchbook/`: `<name>.xitdb` and the `<name>.<file>` it appends to. The + host makes the directory with a `.gitignore` of `*`, so neither git nor + jj takes in a save that grows (the jj snapshot a build makes would commit + one while it is under a megabyte), and moves in, once, the `<name>.state` + an older build kept in the project's root; when both exist, nothing moves + and the host says which is used. Without `--state`, a run keeps them in + `$XDG_DATA_HOME/<name>/` (`~/.local/share/<name>/` without it), which is + where a shipped game's go; a script or an export uses `sketch.xitdb` in + the working directory. `--state x.xitdb` and `--state x.state` both name + the save `x.xitdb`. +- **Sessions.** Every run is a session in the save: an append-only log of the events live `update` was fed, in whole frames, and keyframes, the State at the start, every minute while it changes, at every jump (`load`, `set`, `reset`, a seek, a sketch command), before and after a reload, at every mark and at exit. Each stretch of a session @@ -822,34 +881,53 @@ a talk with a slider, a loop, a choice, two slides and `beside`. 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; marks and clips are names pointing into it. + overwritten, only dropped, oldest first, at the cap (below); marks and + clips are names pointing into it. - `App.Options.record` decides who records, at build time: null, the - default, means Debug builds. 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. A build that does not record has no marks or - clips, and the console says so. The console's status line ends with - `rec file`, `rec memory` or `rec off`, and `sessions` says where. + `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: the session lists as `(crashed)`, and a clip it left - open ends where the session does. A power loss loses what the kernel had + 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. Live State is in the state file either way. + 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). - A minute of drat-meout's play is 268 KB with the pointer moving every - frame (16 MB an hour), 164 KB idle (86 KB of ticks, the rest keyframes). - Every commit leaves the nodes it copied behind, about a kilobyte; a clean - exit compacts the file once it is past twice what its sessions hold plus - 64 MiB. Nothing is compressed or forgotten yet. + **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 @@ -916,9 +994,9 @@ a talk with a slider, a loop, a choice, two slides and `beside`. `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; its sessions are in memory. + 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: @@ -938,8 +1016,8 @@ a talk with a slider, a loop, a choice, two slides and `beside`. 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 @@ -1002,7 +1080,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 @@ -1021,7 +1099,6 @@ and returns plain `std.Build` objects: | `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) | @@ -1031,8 +1108,8 @@ 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 })` records sessions in every mode (see -The host); null, the default, records in Debug builds only. +`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, @@ -1109,7 +1186,7 @@ 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.host_exe` is exposed for anything else. Add `.sketchbook = .{ .path = "..." }` to your `build.zig.zon`. ## Known limits @@ -1118,17 +1195,16 @@ 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) and no +- 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 |
