summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--README.md252
-rw-r--r--build.zig146
-rw-r--r--examples/manual.zig155
-rw-r--r--examples/micscope/README.md11
-rw-r--r--examples/micscope/src/main.zig252
-rw-r--r--examples/micscope/test/record.script10
-rw-r--r--examples/micscope/test/transport.script22
-rw-r--r--src/abi.zig39
-rw-r--r--src/anim/Painter.zig12
-rw-r--r--src/anim/root.zig186
-rw-r--r--src/anim/typst.zig10
-rw-r--r--src/host/Console.zig9
-rw-r--r--src/host/Host.zig308
-rw-r--r--src/host/Sessions.zig631
-rw-r--r--src/host/memory.zig558
-rw-r--r--src/host/probe.zig86
-rw-r--r--src/host/root.zig67
-rw-r--r--src/host/timeline.zig22
-rw-r--r--src/layout.zig36
-rw-r--r--src/sketch/request.zig2
-rw-r--r--src/sketch/root.zig33
-rw-r--r--src/sketch/web.zig12
-rw-r--r--src/vector/svg.zig96
-rw-r--r--test/killed.script4
-rw-r--r--test/manual.script73
-rw-r--r--test/svg/image.svg9
-rw-r--r--test/svg/typst-image.typ6
-rw-r--r--tools/bench.zig101
28 files changed, 1987 insertions, 1161 deletions
diff --git a/README.md b/README.md
index 73f0311..58dae6c 100644
--- a/README.md
+++ b/README.md
@@ -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
diff --git a/build.zig b/build.zig
index 02d312e..aac8d16 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()`,
@@ -110,18 +110,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 }, .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.
@@ -183,6 +172,15 @@ pub fn build(b: *Build) void {
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 }, .{ .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 }) }));
@@ -300,6 +298,31 @@ pub fn build(b: *Build) void {
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 }} });
const diff = b.addSystemCommand(&.{ "python3", "tools/svgdiff.py" });
@@ -324,11 +347,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);
@@ -380,17 +405,22 @@ pub fn build(b: *Build) void {
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.
- // Its sketch records in every mode, so the test does in release builds too.
+ // 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"
- \\rm -f "$3" "$3.store" "$db"
- \\if "$0" --headless --script "$1" --state "$3" "$4"; then echo "killed run exited"; exit 1; else test $? = 137; fi
- \\"$0" --headless --script "$2" --state "$3" "$4"
+ \\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 "$3" "$3.store" "$db"
+ \\rm -f "$db"
+ \\done
});
killed.setName("a session survives kill -9");
killed.addArtifactArg(host_exe);
@@ -398,6 +428,7 @@ pub fn build(b: *Build) void {
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);
@@ -414,12 +445,12 @@ pub fn build(b: *Build) void {
const past = b.addSystemCommand(&.{ "sh", "-c",
\\set -e
\\db="${4%.state}.xitdb"
- \\rm -f "$4" "$4.store" "$db"
+ \\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" "$4.store" "$db"
+ \\rm -f "$4" "$db"
});
past.setName("past sessions replay");
past.addArtifactArg(host_exe);
@@ -459,7 +490,7 @@ pub fn build(b: *Build) void {
// 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 database at all.
+ // 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,
@@ -473,7 +504,7 @@ pub fn build(b: *Build) void {
\\"$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"
+ \\test ! -e "$d/c.state"; test ! -e "$d/c.xitdb"
\\rm -f "$d"/*
});
twice.setName("a script recorded twice");
@@ -487,34 +518,36 @@ pub fn build(b: *Build) void {
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, state and
- // sessions. In .sketchbook/ (`zig build run`'s): a .gitignore, and an
- // older build's state moved in, once, never over a file there.
+ // 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 -s data/replay/replay.state; test -s data/replay/replay.xitdb
- \\"$exe" --headless --state replay.state --console "set updates 7" --console quit "$lib"
- \\"$exe" --headless --state .sketchbook/replay.state --console quit "$lib" 2>err
- \\grep -q moved err; test ! -e replay.state; test ! -e replay.state.store; grep -qx '*' .sketchbook/.gitignore
+ \\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.state --script check.script "$lib"
- \\"$exe" --headless --state replay.state --console quit "$lib"
- \\"$exe" --headless --state .sketchbook/replay.state --console quit "$lib" 2>err
- \\grep -q 'both exist' err; test -e replay.state
- \\"$exe" --headless --state .sketchbook/replay.state --script check.script "$lib"
+ \\"$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("state and sessions paths");
+ 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 state and sessions files go").dependOn(&paths.step);
+ b.step("test-paths", "Check where the save goes").dependOn(&paths.step);
// Recorded input replays to the same state: played, seeked, stepped,
// and after a live pointer move (core host behaviour, not an API).
@@ -710,7 +743,6 @@ pub fn init(b: *Build, options: Options) Sketchbook {
.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") },
.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"),
@@ -762,8 +794,6 @@ pub const Sketchbook = struct {
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 },
/// 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`).
@@ -1223,8 +1253,9 @@ 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 = &.{},
- /// Record every interactive run's sessions to a file beside its
- /// state (src/host/Sessions.zig). Null: in Debug builds only. A
+ /// 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,
@@ -1423,9 +1454,8 @@ pub const App = struct {
}
pub const RunOptions = struct {
- /// State file, relative to the working directory;
- /// `.sketchbook/<name>.state` by default, where the host keeps the
- /// sessions database beside it, all ignored by git and jj.
+ /// 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,
@@ -1438,7 +1468,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(".sketchbook/{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;
@@ -1452,7 +1482,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.
@@ -1464,7 +1494,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("."));
@@ -1494,7 +1524,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}) });
@@ -1505,17 +1535,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(".sketchbook/{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 {
@@ -1760,7 +1779,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;
@@ -1771,7 +1790,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);
@@ -1783,7 +1801,7 @@ pub const App = struct {
// `--export` takes the first argument after `--`.
const exporting = b.addRunArtifact(exe);
- exporting.addArgs(&.{ "--state", b.fmt(".sketchbook/{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/examples/manual.zig b/examples/manual.zig
new file mode 100644
index 0000000..8b11247
--- /dev/null
+++ b/examples/manual.zig
@@ -0,0 +1,155 @@
+//! A page of the Intel SDM as a talk: Figure 2-1, the instruction format
+//! (Vol. 2, page 31), comes alive. The page is Typst's import of the PDF,
+//! every glyph and rule a vector shape; the fields are `part`s of it, 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). `83 C0 01`, `add eax, 1`, is written below, its bytes fly
+//! into their fields, and C0 splits into its ModR/M bits.
+//!
+//! 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
+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]";
+};
+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 {
+ // 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 });
+}
diff --git a/examples/micscope/README.md b/examples/micscope/README.md
index bd55ee0..875ebdf 100644
--- a/examples/micscope/README.md
+++ b/examples/micscope/README.md
@@ -148,6 +148,11 @@ with WebGPU (Chrome, Edge, Safari 26; Firefox on Linux with
browser has accepted its self-signed certificate (miniserve prints the
addresses as QR codes, for phones).
-The takes are the sketch's `Store`: they live in `micscope.state.store` and
-are still there after a restart. Takes stop at ten minutes; the strip holds
-64. A store from before the strip has its one tape as the first take.
+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/src/main.zig b/examples/micscope/src/main.zig
index 3b44ba0..99aac76 100644
--- a/examples/micscope/src/main.zig
+++ b/examples/micscope/src/main.zig
@@ -9,11 +9,13 @@
//! speakers.
//!
//! Memory by lifetime: State is the transport, the selection and the views,
-//! changed by `update` from keys and the mouse, and replayable. Store holds
-//! the takes, on disk: they are still there after a restart. Session is
-//! this process's playback cursor, the microphone's recent past and GPU
-//! objects. Transport changes, seeks and deletions are `sk.Request`s, which
-//! `draw` carries out once each.
+//! 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;
@@ -27,7 +29,7 @@ const tuner = @import("tuner.zig");
pub const name = "micscope";
pub const width = 1280;
pub const height = 900;
-pub const commands = .{ "open", "takes" };
+pub const commands = .{ "open", "next-id" };
/// The longest take: ten minutes at the host's rate.
const max_seconds = 600;
@@ -55,11 +57,12 @@ pub const State = struct {
seek: sk.Request(f32) = .{},
scrubbing: bool = false,
dialog: sk.Request(void) = .{},
- /// Deletes the take at this index.
- remove: sk.Request(u32) = .{},
- /// How many takes the Store holds. `update` keeps count as it records
- /// and deletes; `draw` corrects it with the `takes` command if not.
- takes: u32 = 0,
+ /// 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(.{}),
@@ -76,37 +79,36 @@ pub const State = struct {
};
pub const Take = struct {
- /// Its samples: `Store.tape[start..][0..len]`.
- start: usize = 0,
- len: usize = 0,
- /// Stays the same when earlier takes are deleted: GPU caches go by it.
+ /// 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,
- /// Where the listener is, in samples into the take.
- heard: f64 = 0,
/// A file's name, or empty for the microphone.
source: [64]u8 = @splat(0),
source_len: u32 = 0,
};
-pub const Store = struct {
- /// Every take's mono samples at `Input.sample_rate`, one after another,
- /// oldest first. A recording grows the last one.
- tape: std.ArrayList(f32) = .empty,
- takes: std.ArrayList(Take) = .empty,
- next_id: u32 = 1,
+/// 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 = .{},
- remove: 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 take being recorded, by id.
- recording: u32 = 0,
/// The microphone's recent past and the live view.
live: scope.Scope = .{},
/// Pitch, by tuner.comp: of the microphone (live, or recording), and
@@ -123,7 +125,7 @@ const Tuned = enum(u32) { input, take };
/// GPU objects, made on first use.
const Gpu = struct {
ready: bool = false,
- /// `Store.tape`, and how many of its samples are in it.
+ /// `Session.tape`, and how many of its samples are in it.
tape: sk.Buffer = .none,
capacity: usize = 0,
uploaded: usize = 0,
@@ -281,7 +283,7 @@ const World = struct {
live: bool,
fn of(s: *const State) World {
- return .{ .takes = s.takes, .live = s.transport.value != .recording };
+ return .{ .takes = s.takes.count(), .live = s.transport.value != .recording };
}
fn slots(w: World) u32 {
return w.takes + @intFromBool(w.live);
@@ -341,10 +343,10 @@ pub fn update(s: *State, in: *const sk.Input) void {
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 > 0) {
+ 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 - 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;
@@ -429,7 +431,7 @@ fn act(s: *State, a: Action, in: *const sk.Input) void {
.start => seekTo(s, 0),
.end => seekTo(s, 1),
.open => s.dialog.send({}),
- .delete => if (now != .recording and s.takes > 0) remove(s, in),
+ .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);
@@ -446,9 +448,9 @@ fn act(s: *State, a: Action, in: *const sk.Input) void {
/// 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 {
- if (s.takes >= max_takes) return;
- s.selected = s.takes;
- s.takes += 1;
+ 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);
@@ -483,12 +485,14 @@ fn panBy(s: *State, pixels: f32, in: *const sk.Input) void {
moveCamera(s, cam, in);
}
-/// Deletes the selected take and selects the one above it.
+/// 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 index = @min(s.selected, s.takes - 1);
- s.remove.send(index);
- std.mem.copyForwards(View, s.views[index .. s.takes - 1], s.views[index + 1 .. s.takes]);
- s.takes -= 1;
+ 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);
}
@@ -506,15 +510,14 @@ fn zoom(v: *View, at: f32, factor: f32) void {
v.hi = lo + span;
}
-/// `open PATH` adds a file as a take; `open` alone shows the dialog.
-/// `takes N` tells State how many takes the Store holds (`draw` sends it).
-pub fn command(s: *State, store: *Store, c: *sk.Console, line: []const u8) !bool {
+/// `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, "takes")) {
- const n = try std.fmt.parseInt(u32, words.next() orelse return error.ExpectedCount, 10);
- s.takes = @min(n, max_takes);
- s.selected = @min(s.selected, s.takes -| 1);
+ 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;
@@ -523,22 +526,24 @@ pub fn command(s: *State, store: *Store, c: *sk.Console, line: []const u8) !bool
s.dialog.send({});
return true;
}
- if (store.takes.items.len >= max_takes) return error.TooManyTakes;
+ 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 = .{ .start = store.tape.items.len, .len = kept.len, .id = store.next_id };
+ 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]);
- try store.takes.ensureUnusedCapacity(c.store, 1);
- try store.tape.appendSlice(c.store, kept);
- store.takes.appendAssumeCapacity(take);
- store.next_id += 1;
- s.takes = @intCast(store.takes.items.len);
- s.selected = s.takes - 1;
+ // 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);
@@ -549,7 +554,7 @@ pub fn command(s: *State, store: *Store, c: *sk.Console, line: []const u8) !bool
// ---------------------------------------------------------------------------
// Draw: the takes, the microphone, the speakers and the GPU.
-pub fn draw(s: *const State, ss: *Session, store: *Store, f: *sk.Frame) void {
+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);
@@ -557,24 +562,26 @@ pub fn draw(s: *const State, ss: *Session, store: *Store, f: *sk.Frame) void {
f.canvas(@intFromFloat(@max(in.window_width, min_width)), @intFromFloat(@max(in.window_height, min_height)));
f.clear(0x0b0c0f);
- adoptTape(store, f.store);
if (ss.dialog.take(s.dialog) != null) f.openFile("open", .{ .pattern = "wav;flac;ogg" });
- if (ss.remove.take(s.remove)) |index| removeTake(ss, store, index);
-
+ // 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);
- // Recording goes by the transport's value rather than the request, so a
- // fresh session that only caught up with the request still records.
- if (s.transport.value != .recording) {
- ss.recording = 0;
- } else if (store.takes.items.len == 0 or store.takes.items[store.takes.items.len - 1].id != ss.recording) {
- startTake(ss, store, f.store);
- }
- const takes = store.takes.items;
- if (s.takes != takes.len) f.run(f.format("takes {d}", .{takes.len}));
- const selected: ?*Take = if (takes.len > 0) &takes[@min(s.selected, takes.len - 1)] else null;
+ 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) {
@@ -606,15 +613,16 @@ pub fn draw(s: *const State, ss: *Session, store: *Store, f: *sk.Frame) void {
f.microphone();
ss.live.push(in.microphone);
switch (s.transport.value) {
- .recording => if (takes.len > 0 and takes[takes.len - 1].id == ss.recording) {
- const t = &takes[takes.len - 1];
+ // 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)];
- store.tape.appendSlice(f.store, heard) catch f.host.log("the store is full: recording stopped");
- t.len = store.tape.items.len - t.start;
+ 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, store.tape.items[t.start..][0..t.len], f, s.transport.value == .forward, queued, rate, dt),
+ .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 => {},
}
@@ -632,41 +640,48 @@ pub fn draw(s: *const State, ss: *Session, store: *Store, f: *sk.Frame) void {
f.text(16, Layout.header, 2, "micscope needs a GPU: the host has none.", 0xff8080);
return;
}
- render(s, ss, store, f, rate, dt);
+ render(s, ss, f, rate, dt);
}
-/// Stores from before the strip held one tape: it becomes the first take.
-fn adoptTape(store: *Store, a: std.mem.Allocator) void {
- if (store.takes.items.len > 0 or store.tape.items.len == 0) return;
- store.takes.append(a, .{ .len = store.tape.items.len, .id = store.next_id }) catch return;
- store.next_id += 1;
-}
-
-fn startTake(ss: *Session, store: *Store, a: std.mem.Allocator) void {
- store.takes.append(a, .{ .start = store.tape.items.len, .id = store.next_id }) catch {
- return;
+/// 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;
};
- ss.recording = store.next_id;
- store.next_id += 1;
}
-fn removeTake(ss: *Session, store: *Store, index: u32) void {
- if (index >= store.takes.items.len) return;
- const t = store.takes.orderedRemove(index);
- const tape = store.tape.items;
- std.mem.copyForwards(f32, tape[t.start .. tape.len - t.len], tape[t.start + t.len ..]);
- store.tape.shrinkRetainingCapacity(tape.len - t.len);
- for (store.takes.items[index..]) |*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();
- };
+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: *Take, tape: []const f32, f: *sk.Frame, forward: bool, queued: usize, rate: f64, dt: f64) void {
+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.
@@ -768,17 +783,17 @@ fn sync(g: *Gpu, f: *sk.Frame, tape: []const f32) void {
}
}
-fn render(s: *const State, ss: *Session, store: *Store, f: *sk.Frame, rate: f64, dt: f64) void {
+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, store.tape.items);
+ 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 = store.takes.items;
+ 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 = .{ .takes = @intCast(takes.len), .live = !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;
@@ -795,24 +810,23 @@ fn render(s: *const State, ss: *Session, store: *Store, f: *sk.Frame, rate: f64,
// 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;
- if (recording and takes.len > 0) {
- const t = takes[takes.len - 1];
+ 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) {
- const t = takes[selected];
+ 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, &takes[k], s.views[k], k == selected, tint, rate, dt);
+ 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, store, f, world, cam, rate);
+ labels(s, ss, f, world, cam, rate);
}
/// Finds the pitch of the `tuner_window` samples before `end` (of the
@@ -884,7 +898,7 @@ fn spectrum(g: *Gpu, f: *sk.Frame, tape: sk.Buffer, p: *Panel, size: [2]u32, par
});
}
-fn drawTake(s: *const State, g: *Gpu, f: *sk.Frame, size: Box, b: Box, t: *const Take, view: View, selected: bool, tint: layouts.Tint, rate: f64, dt: f64) void {
+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.
@@ -1041,8 +1055,8 @@ const red = 0xff5a5a;
const green = 0x6fdc8c;
const yellow = 0xffd84d;
-fn labels(s: *const State, ss: *const Session, store: *const Store, f: *sk.Frame, world: World, cam: sk.Camera, rate: f64) void {
- const takes = store.takes.items;
+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;
@@ -1055,14 +1069,13 @@ fn labels(s: *const State, ss: *const Session, store: *const Store, f: *sk.Frame
};
const l = Layout.of(f.in.width, f.in.height);
f.text(16, 10, 2, status[0], status[1]);
- if (takes.len > 0) {
- const t = takes[selected];
+ 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(&t) });
+ 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));
@@ -1087,14 +1100,14 @@ fn labels(s: *const State, ss: *const Session, store: *const Store, f: *sk.Frame
tunerOverlay(f, b.spectrum, ss.tuners[@intFromEnum(Tuned.input)].reading, s.a4, rate, cam.zoom >= 0.8);
continue;
}
- const t = &takes[k];
+ 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(t), seconds });
+ 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)));
@@ -1254,7 +1267,8 @@ test "the world stacks takes in order with the live view last" {
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 = .{ .takes = 5 };
+ 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);
diff --git a/examples/micscope/test/record.script b/examples/micscope/test/record.script
index 2750a18..843d802 100644
--- a/examples/micscope/test/record.script
+++ b/examples/micscope/test/record.script
@@ -1,9 +1,9 @@
# Records (from whatever microphone the host gives a headless run) into a
# new take, stops, and plays it back.
-expect takes 0
+expect takes.len 0
key r
expect transport.value recording
-expect takes 1
+expect takes.len 1
frames 60
screenshot .zig-cache/micscope/recording.png
key r
@@ -13,11 +13,11 @@ expect transport.value forward
frames 10
# Each recording is another take; opening a file while recording ends it.
key r
-expect takes 2
+expect takes.len 2
expect selected 1
console open test/sweep.wav
expect transport.value stopped
-expect takes 3
+expect takes.len 3
frames 2
-expect takes 3
+expect takes.len 3
screenshot .zig-cache/micscope/strip.png
diff --git a/examples/micscope/test/transport.script b/examples/micscope/test/transport.script
index f821a03..2015682 100644
--- a/examples/micscope/test/transport.script
+++ b/examples/micscope/test/transport.script
@@ -2,7 +2,7 @@
# 16 kHz) over a quiet 440 Hz tone.
console open test/sweep.wav
frames 2
-expect takes 1
+expect takes.len 1
expect selected 0
expect transport.value stopped
key right
@@ -36,7 +36,7 @@ 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 2
+expect takes.len 2
expect selected 1
key up
expect selected 0
@@ -47,14 +47,22 @@ click 400 150
expect selected 0
frames 2
screenshot .zig-cache/micscope/two-takes.png
-# Deleting it leaves the second.
+# Deleting it leaves the second. Its file stays: going back to before the
+# deletion reads it again.
+console save two
key delete
-expect takes 1
+expect takes.len 1
expect selected 0
-# State that miscounts the takes is told by draw.
-console set takes 0
+console load two
frames 2
-expect takes 1
+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
diff --git a/src/abi.zig b/src/abi.zig
index 271c6dc..2e80a35 100644
--- a/src/abi.zig
+++ b/src/abi.zig
@@ -321,8 +321,8 @@ pub const Voice = struct {
/// 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 },
@@ -661,7 +661,9 @@ pub const Host = struct {
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,
@@ -734,6 +736,21 @@ pub const Host = struct {
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);
}
@@ -753,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),
};
@@ -807,20 +820,19 @@ 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 host records sessions to a file (`App.Options.record`;
- /// Debug builds do unless told otherwise).
+ /// 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,
};
/// 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.
@@ -842,8 +854,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,
diff --git a/src/anim/Painter.zig b/src/anim/Painter.zig
index b5d492f..f317dc1 100644
--- a/src/anim/Painter.zig
+++ b/src/anim/Painter.zig
@@ -56,11 +56,13 @@ pub fn fit(canvas: sk.Rect) f32 {
}
/// Object `o`'s drawing, centered on its origin, and its bounds.
-fn built(p: *Painter, o: anim.Object, svgs: anytype) !Built {
+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();
- const d = try anim.build(arena, o, svgs);
+ // 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;
@@ -122,7 +124,11 @@ fn paintLayers(p: *Painter, layers: anytype, f: *sk.Frame, shot: anim.Shot, svgs
// Morphing: from where this object began the transform to where
// its target will stand.
const morph = shot.morphs[i];
- const target = (try p.built(shot.objects[pose.into], svgs)).drawing;
+ // 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;
diff --git a/src/anim/root.zig b/src/anim/root.zig
index 4acecb3..560d71b 100644
--- a/src/anim/root.zig
+++ b/src/anim/root.zig
@@ -141,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`,
@@ -225,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.
@@ -238,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.
@@ -526,6 +545,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| {
@@ -553,13 +591,36 @@ pub const Builder = struct {
values: []const f32 = &.{},
plays: []const Play = &.{},
updaters: []const Updater = &.{},
+ /// 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;
@@ -620,13 +681,23 @@ 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);
keys[c.obj] = keys[c.obj] ++ .{k};
poses[c.obj] = k.at(k.end);
+ touched[c.obj] = true;
}
+ 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) |a| if (a == .value) {
const i = @backingInt(a.value.value);
value_keys[i] = value_keys[i] ++ .{play.key(f32, values[i], a.value.to, null)};
@@ -723,9 +794,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 +812,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 +859,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 +906,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,
};
}
@@ -912,6 +1022,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));
@@ -1800,3 +1923,56 @@ test "beside runs alongside the main line; clear fades out what shows" {
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());
+}
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/host/Console.zig b/src/host/Console.zig
index 75da732..0d4cda0 100644
--- a/src/host/Console.zig
+++ b/src/host/Console.zig
@@ -350,7 +350,7 @@ fn listSessions(self: *Console, host: *Host) !void {
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 (release build: .record = true collects)"),
+ .off => return self.log("not recording (an export)"),
}
const n = try s.count(.sessions);
var i = n -| 4;
@@ -457,10 +457,13 @@ fn listNamed(self: *Console, host: *Host, marks: bool) !void {
var i = n -| 5;
while (i < n) : (i += 1) {
const e = if (marks) try s.markAt(i) else try s.clipAt(i);
- const key = try s.load(e.session, e.key);
- defer key.free(host.gpa);
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 });
}
diff --git a/src/host/Host.zig b/src/host/Host.zig
index dc21cc0..002c704 100644
--- a/src/host/Host.zig
+++ b/src/host/Host.zig
@@ -27,15 +27,17 @@ pub const Options = struct {
library: ?[]const u8 = null,
/// Local 9P control socket, opt-in.
ninep: ?[]const u8 = null,
- /// State file; the sessions database goes next to it, `<name>.xitdb`
- /// for `<name>.state`. Empty: `$XDG_DATA_HOME/<name>/<name>.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,
@@ -70,11 +72,10 @@ 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 } = .{},
@@ -92,8 +93,11 @@ reloads: usize = 0,
/// file's inode, size and modification time): sessions' stretches carry it,
/// and `play` warns on a mismatch.
build: u64 = 0,
-/// The state file's path when the host chose it (`Options.state`), `gpa`'s.
+/// 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 = "",
@@ -107,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,
@@ -172,21 +181,13 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std
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}.state", .{ data, info.name, info.name });
+ 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 gpa.free(state_path);
if (state_path.len > 0) options.state = state_path;
- var state = try memory.StateFile.open(gpa, options.state);
- errdefer state.close();
- 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;
- };
- errdefer store.close();
self.* = .{
.gpa = gpa,
@@ -199,14 +200,14 @@ 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,
.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 },
@@ -227,10 +228,8 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std
self.build = fileId(io, options.library orelse "/proc/self/exe");
try self.adopt(sketch);
self.openSessions(info.record);
- // Before --fresh: it never touches the history.
- if (importSnapshots(&self.state, &self.sessions)) |n| {
- if (n > 0) self.print("{d} snapshots of {s} are marks now", .{ n, options.state });
- } else |err| self.print("snapshots of {s} kept in it: {t}", .{ options.state, err });
+ // 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;
@@ -259,12 +258,21 @@ pub fn deinit(self: *Host) void {
std.posix.munmap(entry.value_ptr.*);
}
self.files.deinit(self.gpa);
+ 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();
@@ -329,7 +337,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
@@ -657,9 +665,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,
};
}
@@ -702,7 +708,11 @@ pub fn runLine(self: *Host, line: []const u8, now: u64) !void {
const replay = self.console.execute(self, line, now) catch |err| {
// The sketch has printed its own error already.
if (err == error.NotRecording) {
- self.console.log("Not recording (a release build: .record = true collects): no marks or clips.");
+ 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);
@@ -744,7 +754,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.
@@ -763,17 +772,16 @@ pub fn load(self: *Host, path: []const u8) !void {
self.library = library;
self.reloads += 1;
self.build = fileId(self.io, path);
- self.sessions.stretch(.{ .build = self.build, .source = self.source, .layout = self.state.layoutBytes() }) catch |err| self.print("session: {t}", .{err});
+ 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);
@@ -784,22 +792,13 @@ fn adopt(self: *Host, sketch: abi.Sketch) !void {
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.
@@ -943,42 +942,88 @@ fn consoleKey(e: abi.Event) ?Console.Key {
};
}
-/// Starts this run's session (Sessions.zig): in a file beside the state
-/// file when the build records, in memory for a script from fresh state,
-/// nowhere for an export. A database that cannot be opened is said, and
-/// the run goes on unrecorded.
+/// 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 if (record) .file else .off;
+ 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 stem = if (std.mem.endsWith(u8, o.state, ".state")) o.state[0 .. o.state.len - ".state".len] else o.state;
- const path = std.fmt.bufPrint(&buf, "{s}.xitdb", .{stem}) catch "sketch.xitdb";
- const first: Sessions.Stretch = .{ .build = self.build, .source = self.source, .layout = self.state.layoutBytes() };
+ 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 recording: {s}: {t}", .{ path, err });
+ self.print("not saved: {s}: {t}", .{ path, err });
break :blk .{ .gpa = self.gpa, .io = self.io };
};
- if (o.headless) return;
- switch (self.sessions.mode()) {
- .file => self.print("recording to {s}", .{path}),
- .memory => {},
- .off => if (o.export_to == null) self.print("not recording (release build: .record = true collects)", .{}),
- }
+ // 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;
}
-/// Snapshots of a state file from before sessions become marks "1".."7",
-/// then the file holds live state only. While nothing records, they stay.
-fn importSnapshots(state: *memory.StateFile, sessions: *Sessions) !usize {
- if (state.slots == 1 or sessions.mode() == .off) return 0;
+/// 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..state.slots) |i| if (state.used(i)) {
- _ = try sessions.mark(&.{'0' + @as(u8, @intCast(i))}, .import, state.slot(i));
+ 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 state.dropSnapshots();
+ _ = 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));
}
@@ -1019,6 +1064,7 @@ const api: abi.Host.VTable = .{
.newSound = apiNewSound,
.samples = apiSamples,
.readFile = apiReadFile,
+ .appendFile = apiAppendFile,
.env = apiEnv,
.clock = apiClock,
};
@@ -1095,6 +1141,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();
}
@@ -1124,11 +1211,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);
@@ -1144,7 +1230,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 {
@@ -1169,26 +1254,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);
@@ -1203,7 +1273,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;
@@ -1244,7 +1315,7 @@ test "setup writeBuffer propagates unavailable, unknown and out-of-bounds upload
try std.testing.expectError(error.UploadOutOfBounds, client.writeBuffer(@fromBackingInt(@intCast(1)), 2, "data"));
}
-test "a state file's snapshots from before sessions become marks, and the file one slot" {
+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 {
@@ -1257,32 +1328,24 @@ test "a state file's snapshots from before sessions become marks, and the file o
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});
- // An eight-slot SKETCH02 file, slots 0, 1 and 3 used: built from a new
- // one-slot file's header.
- {
- var file = try memory.StateFile.open(gpa, path);
- defer file.close();
- _ = try file.adopt(gpa, abi.layout.of(State, .state), D.f);
- }
- const one = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .unlimited);
- defer gpa.free(one);
+ 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..memory.header_len], one[0..memory.header_len]);
+ @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 state = try memory.StateFile.open(gpa, path);
- defer state.close();
- try std.testing.expectEqual(memory.old_slot_count, state.slots);
- var sessions = try Sessions.open(gpa, io, .memory, "", .{ .build = 1, .source = "", .layout = state.layoutBytes() }, 0);
+ 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 importSnapshots(&state, &sessions));
+ 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);
@@ -1291,12 +1354,39 @@ test "a state file's snapshots from before sessions become marks, and the file o
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"));
- // One slot now, live state kept, and it reopens so.
- try std.testing.expectEqual(@as(usize, 1), state.slots);
- try std.testing.expectEqual(@as(u32, 5), std.mem.readInt(u32, state.slot(0)[0..4], .little));
- var again = try memory.StateFile.open(gpa, path);
- defer again.close();
- try std.testing.expectEqualStrings(&memory.file_magic, &again.header().magic);
- try std.testing.expectEqual(@as(usize, 1), again.slots);
- try std.testing.expectEqual(@as(u32, 5), std.mem.readInt(u32, again.slot(0)[0..4], .little));
+ 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
index 751961d..cf0ab24 100644
--- a/src/host/Sessions.zig
+++ b/src/host/Sessions.zig
@@ -1,7 +1,8 @@
-//! Every run of a sketch, recorded: one xitdb database per sketch, beside
-//! its state file, holding an append-only log of the frames live `update`
-//! was fed, and the State at the moments that matter (keyframes). Nothing
-//! in it is ever overwritten: marks and clips are names pointing into it.
+//! 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
@@ -14,20 +15,33 @@
//! 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 the state file's header (memory.readLayout reads it)
+//! `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, state, line }: the
-//! State before frame `frame` is fed, in stretch `stretch`'s layout;
-//! `batch` is where reading frames from it starts
+//! 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 clean exit
-//! compacts one that commits left past twice its contents (`close`).
+//! 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");
@@ -36,9 +50,8 @@ const abi = @import("abi");
pub const Disk = xitdb.Database(.buffered_file, u64);
pub const Memory = xitdb.Database(.memory, u64);
-/// `file` for interactive runs of a build that records, `memory` for a
-/// scripted run from fresh state (time travel, nothing on disk), `off`
-/// otherwise (an export, a release build).
+/// `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 };
@@ -52,15 +65,27 @@ 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 };
+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 };
-const Keyframe = struct { frame: u64, batch: u64, stretch: u64, why: Why, time: u64, state: []u8, line: []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`.
@@ -89,10 +114,13 @@ 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, stretch and bytes' hash.
+/// The last keyframe's time and stretch.
key_time: u64 = 0,
key_stretch: u64 = 0,
-key_hash: 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,
@@ -104,6 +132,8 @@ 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
@@ -165,6 +195,7 @@ 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();
@@ -175,43 +206,212 @@ pub fn deinit(s: *Sessions) void {
}
/// The last frames, an exit keyframe of `state`, and the session's end, in
-/// one transaction synced to disk; then closed.
+/// 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) return;
- const size = s.file.?.length(s.io) catch return;
- if (size < compact_floor) return;
- const live = liveSize(&s.db.file) catch return;
- if (size > 2 * live + compact_floor) s.compact() catch |err| std.log.warn("sessions: not compacted: {t}", .{err});
+ if (s.db == .file and !s.history) s.compact() catch |err| std.log.warn("sessions: not compacted: {t}", .{err});
}
-/// The database's file compacted at a clean exit, once it is past twice what
-/// its batches and keyframes hold plus this: every commit leaves the
-/// nodes it copied behind.
-const compact_floor: u64 = 64 << 20;
-
/// Writes what the database holds now, without the nodes commits left
-/// behind, to `<path>.new`, synced, and renames it over the file.
+/// 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 cwd.deleteFile(s.io, new) catch {};
- defer file.close(s.io);
- var buffer: std.Io.Writer.Allocating = .init(s.gpa);
- defer buffer.deinit();
+ 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();
- _ = try s.db.file.compact(.buffered_file, .{ .file = file, .buffer = &buffer, .fsync = true }, &offsets);
+ 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: what compaction keeps.
+/// 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);
@@ -222,11 +422,14 @@ fn liveSize(db: *Disk) !u64 {
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 += try blob.count();
+ 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| live += try (try R.field(try R.Map.init(key_cursor), .state)).count();
+ 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;
@@ -320,19 +523,38 @@ pub fn frame(s: *Sessions, one: []abi.Event, state: []const u8, why: ?Why) !void
/// 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).
+/// `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;
- const hash = std.hash.Wyhash.hash(0, state);
defer s.line_len = 0;
- if (s.keys > 0 and why != .before_reload and hash == s.key_hash and s.key_stretch == s.stretches - 1) return s.keys - 1;
- const state_copy = try s.gpa.dupe(u8, state);
- errdefer s.gpa.free(state_copy);
+ 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, .state = state_copy, .line = 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_hash = hash;
s.key_stretch = s.stretches - 1;
s.keys += 1;
return s.keys - 1;
@@ -348,8 +570,15 @@ pub fn stretch(s: *Sessions, st: Stretch) !void {
}
/// Mark `name`: a keyframe of `state` (`why`: `.mark`, or `.import`),
-/// synced to disk. Returns the keyframe's index.
+/// 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;
@@ -371,7 +600,8 @@ pub fn stopClip(s: *Sessions) !void {
fn dropQueued(s: *Sessions) void {
for (s.queued.items) |k| {
- s.gpa.free(k.state);
+ s.gpa.free(k.indices);
+ s.gpa.free(k.pages);
s.gpa.free(k.line);
}
s.queued.clearRetainingCapacity();
@@ -416,7 +646,10 @@ pub fn commit(s: *Sessions, extra: Extra) !void {
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 {
@@ -456,8 +689,28 @@ fn Commit(comptime DB: type) type {
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(.state), .{ .bytes = q.state });
+ 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) {
@@ -485,6 +738,13 @@ fn Commit(comptime DB: type) type {
}
}
+ /// 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 });
@@ -513,6 +773,8 @@ pub const Entry = struct {
};
/// 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,
@@ -594,13 +856,15 @@ pub fn load(s: *Sessions, session: u64, k: u64) !Loaded {
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 state = try R.bytes(e, .state, s.gpa);
+ 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,
@@ -616,6 +880,32 @@ pub fn load(s: *Sessions, session: u64, k: u64) !Loaded {
}
}
+/// 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) {
@@ -658,7 +948,9 @@ pub fn events(s: *Sessions, session: u64, from: u64, start: u64, end: u64, out:
const n = try batches.count();
var i = from;
while (i < n) : (i += 1) {
- const blob = try (try batches.getCursor(@intCast(i)) orelse return error.CorruptSession).readBytesAlloc(s.gpa, null);
+ 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);
@@ -775,6 +1067,8 @@ fn Transfer(comptime From: type, comptime To: type) type {
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;
@@ -786,7 +1080,7 @@ fn Transfer(comptime From: type, comptime To: type) type {
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);
+ 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| {
@@ -797,7 +1091,7 @@ fn Transfer(comptime From: type, comptime To: type) type {
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);
+ 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;
@@ -811,21 +1105,27 @@ fn Transfer(comptime From: type, comptime To: type) type {
};
}
-/// Copies the value at `from` (a uint, bytes, or a list or map of them) to `to`.
-fn copy(comptime From: type, comptime To: type, gpa: std.mem.Allocator, from: From.Cursor(.read_only), to: *To.Cursor(.read_write)) anyerror!void {
- switch ((try from.slot()).tag) {
+/// 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);
+ try copy(From, To, gpa, c, &next, copied);
}
},
.hash_map => {
@@ -834,7 +1134,7 @@ fn copy(comptime From: type, comptime To: type, gpa: std.mem.Allocator, from: Fr
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);
+ try copy(From, To, gpa, kv.value_cursor, &next, copied);
}
},
else => return error.CorruptSession,
@@ -861,6 +1161,19 @@ fn Read(comptime DB: type) type {
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);
}
@@ -1025,7 +1338,8 @@ test "a compacted session database is smaller and holds every session and frame"
try s.commit(.none);
const size = try s.file.?.length(io);
const live_size = try liveSize(&s.db.file);
- try std.testing.expectEqual(@as(u64, 600 * @sizeOf(abi.Event) + 10 * 8 + 6 * 8), live_size);
+ // 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;
@@ -1067,3 +1381,206 @@ test "a memory session stops recording at its bound, and what it holds still rea
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/memory.zig b/src/host/memory.zig
index 044fc3b..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, 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");
@@ -18,7 +17,7 @@ const field_value = @import("fields.zig");
pub const page = std.heap.page_size_min;
pub const header_len = 64 * 1024;
-/// One slot, the live state: snapshots are marks in the sessions database.
+/// 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`).
@@ -291,167 +290,93 @@ 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,
- /// 1, or `old_slot_count` in a file from before sessions.
- slots: usize = 1,
- /// 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);
- }
-
- /// The header and the layout after it, as `readLayout` reads them back.
- pub fn layoutBytes(self: *StateFile) []const u8 {
- const h = self.header();
- return self.map[0 .. @sizeOf(Header) + @as(usize, h.field_count) * @sizeOf(StoredField) + h.strings_len];
+ 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 < self.slots);
- 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;
- }
-
- 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;
- }
-
- 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_v2;
- }
- 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: [old_slot_count]?[]u8 = @splat(null);
- for (old_slots[0..self.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 = if (self.slots == 1) file_magic else file_magic_v2, .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);
+/// 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,
- 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 };
+ /// 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 };
}
- /// Makes a file from before sessions one of a single slot, its
- /// snapshots (imported as marks by now) dropped.
- pub fn dropSnapshots(self: *StateFile) !void {
- if (self.slots == 1) return;
- const stride = self.header().stride;
- self.slots = 1;
- try self.resize(stride);
- self.header().magic = file_magic;
- self.header().used &= 1;
+ 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)) {
- self.slots = 1;
- } else if (std.mem.eql(u8, &h.magic, &file_magic_v2) or std.mem.eql(u8, &h.magic, &file_magic_v1)) {
- self.slots = old_slot_count;
- } else return error.NotAStateFile;
- if (self.map.len < header_len + self.slots * 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 + self.slots * 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 `StateFile.layoutBytes`
-/// gives it): `defaults`, then every leaf `migrate` keeps. Returns the
+/// 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);
@@ -462,7 +387,7 @@ pub fn restore(arena: std.mem.Allocator, layout_bytes: []const u8, image: []cons
return from;
}
-/// The layout in a header as `StateFile.layoutBytes` gives it, `arena`'s.
+/// 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);
@@ -515,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;
@@ -560,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))) {
@@ -582,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 {
@@ -921,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 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 {
@@ -932,65 +651,20 @@ test "state file migrates live state, and a reopen reads the layout back" {
@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;
- }
- 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);
- try std.testing.expectEqual(V2{ .level = 1, .score = 99 }, @as(*V2, @ptrCast(file.slot(0).ptr)).*);
-}
-
-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" {
@@ -1105,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(.{});
@@ -1132,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_v2, &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/probe.zig b/src/host/probe.zig
deleted file mode 100644
index 4b61153..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_v2) 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 5889b42..9c7ad77 100644
--- a/src/host/root.zig
+++ b/src/host/root.zig
@@ -2,11 +2,11 @@
//! that it hot-reloads whenever a build replaces it.
//!
//! sketchbook [options] [LIBRARY]
-//! --state FILE persistent state (default: $XDG_DATA_HOME/<name>/<name>.state;
-//! sketch.state for a script or an export)
+//! --state FILE the save (default: $XDG_DATA_HOME/<name>/<name>.xitdb;
+//! sketch.xitdb for a script or an export)
//! --headless offscreen video, silent audio
//! --script FILE play a script instead of reading devices
-//! --fresh start from default state (sessions, marks and clips are kept)
+//! --fresh start from default state (the save's history is kept)
//! --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)
@@ -93,25 +93,9 @@ pub fn main(init: std.process.Init, linked: ?abi.Sketch) !void {
} 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 or store file,
- // nor fail on the store's lock (its sessions are in memory). 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;
- if (options.state.len == 0 and (script_path != null or options.export_to != null)) options.state = "sketch.state";
- const given = options.state;
- const private = (script_path != null or options.export_to != null) and options.fresh;
- if (!private) sketchbookDir(init.io, given);
- 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{ "", ".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();
{
@@ -131,11 +115,12 @@ pub fn main(init: std.process.Init, linked: ?abi.Sketch) !void {
const usage =
\\usage: sketchbook [options] [LIBRARY]
\\ --9p SOCKET local 9P controls: ctl, status, log, screen.png
- \\ --state FILE persistent state; sessions are kept beside it (default:
- \\ $XDG_DATA_HOME/<name>/<name>.state, sketch.state for --script, --export)
+ \\ --state FILE the save, one file: FILE, or FILE.xitdb for a FILE.state (where a
+ \\ state file from before is imported from, once); default:
+ \\ $XDG_DATA_HOME/<name>/<name>.xitdb, sketch.xitdb for --script, --export
\\ --headless offscreen video, silent audio, no vsync
\\ --script FILE play a script instead of reading devices
- \\ --fresh start from default state (sessions, marks and clips are kept)
+ \\ --fresh start from default state (the save's history is kept)
\\ --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)
@@ -148,10 +133,10 @@ const usage =
\\
;
-/// A state file in a directory named `.sketchbook` (`zig build run`'s):
-/// the directory is made, with a `.gitignore` of `*` (its sessions database
-/// grows, and a jj snapshot would commit it), and the state and store files
-/// an older build kept beside it are moved in, once. A file is never
+/// 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;
@@ -161,20 +146,16 @@ fn sketchbookDir(io: std.Io, state: []const u8) void {
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 {};
- for ([_][]const u8{ "", ".store" }) |suffix| {
- 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 from = std.fmt.bufPrintSentinel(&from_buf, "{s}/{s}{s}", .{ parent, std.fs.path.basename(state), suffix }, 0) catch return;
- const to = std.fmt.bufPrintSentinel(&to_buf, "{s}{s}", .{ state, suffix }, 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 });
- return;
- },
- else => {},
- }
+ 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 => {},
}
}
diff --git a/src/host/timeline.zig b/src/host/timeline.zig
index c2eeff3..e755433 100644
--- a/src/host/timeline.zig
+++ b/src/host/timeline.zig
@@ -45,8 +45,8 @@ pub const Frames = struct {
pub const Timeline = struct {
gpa: std.mem.Allocator,
- /// Live state is its slot 0.
- state: *memory.StateFile,
+ /// 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,
@@ -90,7 +90,7 @@ pub const Timeline = struct {
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.slot(0), self.defaults);
+ _ = 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;
@@ -202,18 +202,14 @@ pub const Timeline = struct {
test "frames are whole: input waits for its tick, in playback, seek and step" {
const gpa = std.testing.allocator;
- // Live state on plain memory: 8 bytes, no fields.
- var file: memory.StateFile = undefined;
- file.map = try gpa.alignedAlloc(u8, .fromByteUnits(memory.page), memory.header_len + memory.page);
- defer gpa.free(file.map);
- @memset(file.map, 0);
- file.slots = 1;
- file.header().* = .{ .size = 8, .alignment = 1, .hash = 1, .stride = memory.page, .used = 1, .field_count = 0, .strings_len = 0 };
- file.layout = .{ .size = 8, .hash = 1 };
+ // Live State: 8 bytes, no fields.
const D = struct {
fn f(_: abi.Memory, _: [*]u8) callconv(.c) void {}
};
- var t: Timeline = .{ .gpa = gpa, .state = &file, .defaults = D.f };
+ 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).
@@ -223,7 +219,7 @@ test "frames are whole: input waits for its tick, in playback, seek and step" {
try events.append(gpa, abi.Event.tick(1000 + k * 10_000_000 + 5_000_000, 16_666_667));
}
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, file.layoutBytes()) };
+ 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);
diff --git a/src/layout.zig b/src/layout.zig
index 5e60e22..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 {
@@ -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 => {},
}
}
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 0ab04a7..2a7c64a 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");
@@ -67,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
@@ -82,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 {
@@ -298,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);
@@ -318,7 +313,7 @@ pub const Console = struct {
pub const Build = struct {
/// The repository revision the sketch was built from, "" when unknown.
source: []const u8 = "",
- /// Record sessions to a file (`abi.Info.record`).
+ /// Keep history in the save (`abi.Info.record`).
record: bool = false,
};
@@ -346,7 +341,6 @@ 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.*;
@@ -357,7 +351,6 @@ pub fn Glue(comptime App: type, comptime made: Build) 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,
@@ -384,10 +377,10 @@ pub fn Glue(comptime App: type, comptime made: Build) 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");
@@ -396,8 +389,6 @@ pub fn Glue(comptime App: type, comptime made: Build) 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)
@@ -423,7 +414,6 @@ pub fn Glue(comptime App: type, comptime made: Build) 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 {
@@ -431,7 +421,7 @@ pub fn Glue(comptime App: type, comptime made: Build) 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});
@@ -449,7 +439,7 @@ pub fn Glue(comptime App: type, comptime made: Build) 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;
@@ -495,7 +485,6 @@ 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, .{});
try std.testing.expect(!app.setup(&ctx));
defer std.testing.allocator.free(session.bytes);
diff --git a/src/sketch/web.zig b/src/sketch/web.zig
index a035117..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");
@@ -84,8 +84,6 @@ fn Driver(comptime App: type) type {
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 = .{};
@@ -107,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,
};
}
@@ -117,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) {
@@ -420,6 +415,7 @@ fn Driver(comptime App: type) type {
.newSound = newSound,
.samples = samples,
.readFile = readFile,
+ .appendFile = appendFile,
.env = env,
.clock = clock,
};
@@ -484,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/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/killed.script b/test/killed.script
index cceeb48..7d0899c 100644
--- a/test/killed.script
+++ b/test/killed.script
@@ -1,4 +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.
+# 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..3bc3c73
--- /dev/null
+++ b/test/manual.script
@@ -0,0 +1,73 @@
+# The manual example (examples/manual.zig) on Vol. 2 of the Intel SDM:
+# Figure 2-1 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, and the end of the talk.
+key space
+frames 120
+expect deck.log.len 12
+expect deck.waiting false
+screenshot .zig-cache/manual/end.png
+expect-different-screenshot .zig-cache/manual/page.png .zig-cache/manual/end.png 470 260 340 120
+# Exported ({a}, {b}: 10 fps, half size), each step held 1.5 s: the same
+# frames twice, and the talk moves through them.
+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-different-screenshot {a}/000040.png {a}/000200.png
+expect-different-screenshot {a}/000200.png {a}/000340.png
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/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];