summaryrefslogtreecommitdiff
path: root/anim
diff options
context:
space:
mode:
Diffstat (limited to 'anim')
-rw-r--r--anim/.gitignore6
-rw-r--r--anim/README.md126
-rw-r--r--anim/build.zig204
-rw-r--r--anim/build.zig.zon12
-rw-r--r--anim/scenes/fib.zig59
-rw-r--r--anim/scenes/list.zig52
-rw-r--r--anim/scenes/sort.zig63
-rw-r--r--anim/scenes/syscalls.zig49
-rw-r--r--anim/scenes/title.zig22
-rw-r--r--anim/scenes/zoom.zig50
-rw-r--r--anim/src/Recording.zig670
-rw-r--r--anim/src/array.zig189
-rw-r--r--anim/src/calls.zig160
-rw-r--r--anim/src/context.zig485
-rw-r--r--anim/src/cursor.zig638
-rw-r--r--anim/src/heap.zig105
-rw-r--r--anim/src/hexdump.zig114
-rw-r--r--anim/src/memory.zig444
-rw-r--r--anim/src/nodes.zig273
-rw-r--r--anim/src/objects.zig166
-rw-r--r--anim/src/registers.zig117
-rw-r--r--anim/src/root.zig303
-rw-r--r--anim/src/source.zig193
-rw-r--r--anim/src/syscalls.zig382
-rw-r--r--anim/src/theme.zig911
-rw-r--r--anim/src/ties.zig139
-rw-r--r--anim/src/ui.zig598
-rw-r--r--anim/src/words.zig216
-rw-r--r--anim/test/fib.script11
-rw-r--r--anim/test/list.script11
-rw-r--r--anim/test/recordings.zig101
-rw-r--r--anim/test/sort.script11
-rw-r--r--anim/test/syscalls.script11
-rw-r--r--anim/test/title.script4
-rw-r--r--anim/test/zoom.script11
-rw-r--r--anim/tools/__pycache__/chart.cpython-314.pycbin0 -> 2973 bytes
-rw-r--r--anim/tools/bench.zig91
-rw-r--r--anim/tools/chart.py42
-rw-r--r--anim/tools/fib.c12
-rw-r--r--anim/tools/hello.c11
-rw-r--r--anim/tools/list.c44
-rw-r--r--anim/tools/motion.py210
-rw-r--r--anim/tools/note1
-rw-r--r--anim/tools/sort.c22
l---------anim/zig-pkg1
45 files changed, 7340 insertions, 0 deletions
diff --git a/anim/.gitignore b/anim/.gitignore
new file mode 100644
index 0000000..88da448
--- /dev/null
+++ b/anim/.gitignore
@@ -0,0 +1,6 @@
+.zig-cache/
+zig-out/
+out/
+*.state
+*.state.store
+zig-pkg
diff --git a/anim/README.md b/anim/README.md
new file mode 100644
index 0000000..9878765
--- /dev/null
+++ b/anim/README.md
@@ -0,0 +1,126 @@
+# canim
+
+Animations of how a program ran, from a `ztrace` recording, on sketchbook's
+`anim` (live scenes). The frame is a debugger's whole context, as pwndbg
+shows it, with one lens beside it; how it looks is `../design/README.md`
+(revision 2) and how it moves is `../design/motion.md`.
+
+**State of this tree: mid-change, handed over.** The motion model (a step as
+a sentence) and the context frame are in and every scene builds and runs;
+the look was not checked against the design's mocks after the last round of
+changes, and the scripted tests only check that scenes run. See "What is
+not done" at the end.
+
+```sh
+zig build record # the recordings, into zig-out/recordings
+zig build run -Dscene=fib # a scene in a window, hot reload (zig build lib --watch)
+zig build export -Dscene=fib -- DIR --fps 60 --size 1920x1080 # frames as PNGs (or - for raw RGBA)
+zig build videos -Doptimize=ReleaseFast # every scene: out/NAME-1080.mp4 and out/NAME-2160.mp4 (x264, 60 fps)
+zig build test # unit tests, and each scene run headless
+zig build bench # what a recording costs a frame
+zig build bench -- NAME BY [FUNCTION] # a recording's steps (BY: moment, line, over), with what each changed
+python3 tools/chart.py chart out/fib-1080.mp4 --out out/motion/fib # the designer's timing chart and five checks
+```
+
+Needs what sketchbook and ztrace need, and `setarch`, `clang++` and
+`llvm-config` (the pass plugin), `ffmpeg` (videos), python with numpy and
+Pillow (charts). Dependencies are by path (`..` is ztrace, `../../sketchbook`,
+`../../02-pardes-code`); `zig-pkg` is a symlink to pardes's.
+
+## A scene
+
+```zig
+const anim = @import("anim");
+const canim = @import("canim");
+const recordings = @import("recordings");
+
+pub const background = canim.background;
+pub const scene = anim.Live(frame, struct {});
+
+fn frame(s: *anim.Frame) void {
+ const rec = canim.open(recordings.steps); // a recording the build made and embedded
+ const split = canim.layout.split.beside; // how the program column is shared
+ var at = canim.cursor(s, rec, rec.lineMoment(10, rec.call("main", 0).enter));
+ at.levels = .{ .idea = .calls, .source_rows = 8 }; // what a step is timed by
+ at.journey(.line, rec.call("fib", 0).exit.?); // the clock's whole way
+ const ctx = canim.context(s, at, .{ .split = split }); // source, disassembly, registers, stack, backtrace, clock
+ const tree = canim.callTree(s, .{ .cursor = at, .box = split.lens, .function = "fib", .focus = true });
+ const joins = canim.ties(s, .{ .cursor = at }); // connections between panes; add it last
+ var says: canim.Narrator = .{};
+
+ canim.establish(s, .{ ctx.clock, ctx.source, ctx.disasm, ctx.registers, ctx.stack, ctx.backtrace, tree, joins });
+ says.line(s, "`fib` calls itself."); // old caption out, a gap, new one in, then stillness
+ at.walk(s, .line, rec.lineMoment(6, rec.call("fib", 0).enter)); // each step in full, timed by its content
+ at.hurry(s, .line, rec.call("fib", 4).enter, .{}); // a run: ramps in and out, counted on the clock
+ at.hurry(s, .line, rec.call("fib", 10).exit.?, .{ .pace = canim.theme.time.sprint });
+ s.wait(canim.theme.time.before_cut);
+}
+```
+
+`frame` runs every frame and builds the whole timeline each time; a
+component is an `anim` object (`fadeIn`, `fadeOut`) that draws the program's
+state at the cursor.
+
+**The cursor** (`src/cursor.zig`) moves in steps from one moment straight to
+a later one (`Recording.Stop`: `.moment`, `.line`, `.over`, `.call`,
+`.syscall`). For each step it writes a timetable, a `Plan`: the line fires
+(0.20 s); each level the step touched strikes 0.30 s after the one before, in
+the order CPU, memory, idea (a level the scene does not show, or the step did
+not touch, gives up its slot); a hold to read; the mark advances last; a rest.
+`walk` plays steps in full, `hurry` ramps the pace down and up again (each
+step 0.6 of the one before) to a run (0.30 s a step) or a sprint, `step`
+takes an explicit `Plan` (`Array.swap`, `syscalls.step`). Components read it
+through `Cursor.now(at)`: `landed(level)`, `shown(level)`, `written(addr,
+size, level, delay)`, `register(i, delay)`, `reading(level)`, `moving(level,
+lead, seconds)`, `fires(view)`, `advancing()`, `marks`.
+
+## The blocks
+
+| Block | File | Reads | Use |
+| --- | --- | --- | --- |
+| `Recording` | `src/Recording.zig` | every moment once, at open | the index: lines, calls, syscalls, allocations, which registers and bytes each moment changed; `next`, `lineMoment`, `call`, `variable`, `assigned`, `instruction`, `viewFirst` |
+| `ui.Ui` | `src/ui.zig` | | rects, text on a baseline, `panel`, `value` (a value by its class), `chainArrow`, `struck`/`readFrame` (marks in the context), `written`/`readMark` (marks in a lens's cell), `arrow`, `clip`, `veil` |
+| `context.chain` | `src/context.zig` | `zt.telescope.chase` | a value followed as far as it points, each link in its region's ink |
+| `Registers` | `src/context.zig` | `Moment.regs`, mappings | 18 rows: sixteen, rip (a current mark), the flags; options `syscalls`, `quiet` |
+| `Stack` | `src/context.zig` | `Moment.regs`, `Moment.read` | eight words from rsp as a telescope, plaques for rsp and rbp, frame notes |
+| `Backtrace` | `src/context.zig` | `zt.telescope.backtrace` | the call chain by frame pointer, newest on top |
+| `Disasm` | `src/context.zig` | the recorded instructions | rows round the pc in address order, the pc's row fixed |
+| `Source` | `src/source.zig` | `Moment.line` (the index) | the whole file in a window, pardes's colours, the current mark and its trail |
+| `Clock` | `src/words.zig` | the cursor | the progress rule over the caption, `moment N of M`, the step counter |
+| `Caption`, `Narrator` | `src/words.zig`, `src/root.zig` | | the narrator's sentence, one at a time |
+| `CallTree` | `src/calls.zig` | the index of calls | lens: every call of a function as a tree |
+| `Nodes` | `src/nodes.zig` | `Moment.variables`, `Moment.read`, `Moment.allocation`, types | lens: structs the program's pointers reach, as nodes and arrows, with variable tags |
+| `Hexdump` | `src/hexdump.zig` | `Moment.read`, `Moment.allocation`, types | lens: sixteen bytes a row, each word marked as what it is |
+| `Array` | `src/array.zig` | `Moment.variables`, `Moment.read`, reads and writes | lens: an array's cells, index tags, values in flight |
+| `Crossing` | `src/syscalls.zig` | the index of syscalls | lens: the kernel's side of a system call, on vellum |
+| `Ties` | `src/ties.zig` | anchors the others publish | connections between panes: the gold thread, the step's link, a written word and its node |
+| `Camera` | `src/root.zig` | | announced moves: `go(box, zoom, others)`, `back(others)`, `apply` |
+| `Locals`, `Memory`, `Heap`, `Timeline`, `Legend`, `Label`, `Veil` | `src/registers.zig`, `memory.zig`, `heap.zig`, `syscalls.zig`, `words.zig` | | first-pass blocks, still built; only `Legend` and `Label` are used (the title card) |
+
+## The recordings
+
+`build.zig` records four programs of `tools/` under `ztrace record` (the
+debugger: registers, the stack, what they point at, the instructions round
+the pc, at every stop), each by a bare name in a directory of its own with
+an empty environment, without address randomisation:
+
+| Name | Program | Stops | Also |
+| --- | --- | --- | --- |
+| `steps` | `fib.c`, static musl, `-O0` | every instruction | |
+| `hello` | `hello.c`, static musl | every line | reads `tools/note` |
+| `sort` | `sort.c` built by `ztrace cc` (`calls,vars,stores,loads`) | every line | `--ring` |
+| `list` | `list.c` built by `ztrace cc` (`calls,vars,stores`) | every line | `--alloc --preload` the agent |
+
+## What is not done
+
+- The look was not compared with `design/mock/09` to `11` after the frame
+ changed; the designer's later notes (a catalogue of blocks, ties as a
+ design form, the disassembly's annotations) are not in.
+- The disassembly has no operand note, no call, jump or return annotation
+ (`touch` and `branch` events are not read).
+- The motion checks (`tools/chart.py`) were last run before the frame
+ changed; no scene is known to pass them now.
+- `test/*.script` only run each scene to three instants; there are no pixel
+ assertions and no gallery.
+- 4K exports and performance at the context's density were not measured
+ after the change.
diff --git a/anim/build.zig b/anim/build.zig
new file mode 100644
index 0000000..f410fb9
--- /dev/null
+++ b/anim/build.zig
@@ -0,0 +1,204 @@
+//! canim: the animation library (`src/`, the module `canim`), the small C
+//! programs it records (`tools/`), and its scenes (`scenes/`), each a
+//! player built by sketchbook.
+//!
+//! zig build record the recordings, into zig-out/recordings
+//! zig build run -Dscene=list a scene in a window, with hot reload
+//! zig build export -Dscene=list -- DIR its frames (see sketchbook's README)
+//! zig build videos -Doptimize=ReleaseFast every scene as out/NAME-1080.mp4 and -2160
+//! zig build test unit tests and the scripted runs
+//! zig build bench what a recording costs a frame
+//! zig build motion -Dscene=list -Doptimize=ReleaseFast how a scene moves: contact sheets and change plots in out/motion/list
+//!
+//! Needs, besides what sketchbook and ztrace need: `setarch`, and for
+//! `videos`, `ffmpeg`.
+const std = @import("std");
+const sketchbook = @import("sketchbook");
+
+const scenes = [_][]const u8{ "title", "fib", "list", "sort", "syscalls", "zoom" };
+
+pub fn build(b: *std.Build) void {
+ const target = b.standardTargetOptions(.{});
+ const optimize = b.standardOptimizeOption(.{});
+ const chosen = b.option([]const u8, "scene", "The scene `run`, `lib` and `export` are about (default fib)") orelse "fib";
+
+ const sb = sketchbook.init(b, .{ .target = target, .optimize = optimize });
+ const zt = b.dependency("ztrace", .{ .target = target, .optimize = optimize });
+ const pardes = b.dependency("pardes", .{ .target = target, .optimize = optimize, .@"tree-sitter" = .minimal });
+ const ztrace = zt.artifact("ztrace");
+
+ const imports: []const std.Build.Module.Import = &.{
+ .{ .name = "anim", .module = sb.modules.anim },
+ .{ .name = "sketch", .module = sb.modules.sketch },
+ .{ .name = "ztrace", .module = zt.module("ztrace") },
+ .{ .name = "ztrace-types", .module = zt.module("ztrace-types") },
+ .{ .name = "pardes-syntax", .module = pardes.module("pardes-syntax") },
+ };
+ const canim = b.addModule("canim", .{ .root_source_file = b.path("src/root.zig"), .imports = imports });
+
+ // ---- The recordings: each program of tools/ run once under ztrace's
+ // debugger, without address randomisation (`setarch -R`), so a recording
+ // and the frames made from it are the same on every build.
+ const record_step = b.step("record", "Record the programs of tools/ into zig-out/recordings");
+ const embedded = b.addWriteFiles();
+ var table: std.ArrayList(u8) = .empty;
+
+ // The pass as ztrace's own build makes it.
+ // shortcut: its recipe is repeated here; the root package should name the plugin (`addNamedLazyPath`).
+ const cxx = b.addSystemCommand(&.{ "sh", "-c", "exec clang++ -shared -fPIC -O2 -fno-rtti $(llvm-config --cxxflags) \"$0\" -o \"$1\"" });
+ cxx.addFileArg(zt.path("llvm/pass.cpp"));
+ const plugin = cxx.addOutputFileArg("ztrace-pass.so");
+ // The agent to preload: of the two artifacts of that name, the shared one.
+ const agent = for (zt.builder.install_tls.step.dependencies.items) |step| {
+ const installed = step.cast(std.Build.Step.InstallArtifact) orelse continue;
+ if (std.mem.eql(u8, installed.artifact.name, "ztrace-agent") and installed.artifact.isDynamicLibrary()) break installed.artifact;
+ } else @panic("ztrace has no shared libztrace-agent");
+ const musl = b.resolveTargetQuery(.{ .cpu_arch = .x86_64, .os_tag = .linux, .abi = .musl });
+
+ const Recording = struct {
+ name: []const u8,
+ source: []const u8,
+ /// Where the debugger stops it: every instruction, or every line.
+ /// Each stop records the registers, the stack under them, what
+ /// they point at, and the instructions at the pc.
+ by: []const u8,
+ /// Compiled by `ztrace cc` to tell these of itself as well (its
+ /// calls, its variables with their types, every store and load);
+ /// null for the program as the compiler alone makes it (static,
+ /// unoptimised), whose instructions are then all its own.
+ instr: ?[]const u8 = null,
+ /// With the agent preloaded: `malloc` and `free` too.
+ alloc: bool = false,
+ /// A file of tools/ it reads, by its bare name.
+ reads: ?[]const u8 = null,
+ };
+ for ([_]Recording{
+ .{ .name = "steps", .source = "fib.c", .by = "insn" },
+ .{ .name = "hello", .source = "hello.c", .by = "line", .reads = "note" },
+ .{ .name = "sort", .source = "sort.c", .by = "line", .instr = "calls,vars,stores,loads" },
+ .{ .name = "list", .source = "list.c", .by = "line", .instr = "calls,vars,stores", .alloc = true },
+ }) |r| {
+ const source = b.path(b.fmt("tools/{s}", .{r.source}));
+ var program: std.Build.LazyPath = undefined;
+ if (r.instr) |instr| {
+ const cc = b.addRunArtifact(ztrace);
+ cc.addArgs(&.{ "cc", "--instr", instr, "--plugin" });
+ cc.addFileArg(plugin);
+ cc.addArg("--rt");
+ cc.addArtifactArg(zt.artifact("ztrace-rt"));
+ cc.addArgs(&.{ "--", "clang", "-O0", "-g" });
+ cc.addFileArg(source);
+ cc.addArg("-o");
+ program = cc.addOutputFileArg(r.name);
+ } else {
+ const mod = b.createModule(.{ .target = musl, .optimize = .Debug, .link_libc = true, .omit_frame_pointer = false, .sanitize_c = .off, .stack_protector = false });
+ mod.addCSourceFile(.{ .file = source, .flags = &.{ "-O0", "-g" } });
+ program = b.addExecutable(.{ .name = r.name, .root_module = mod, .linkage = .static }).getEmittedBin();
+ }
+ // It runs by a bare name in a directory of its own, with no
+ // environment: the strings on its stack (its name, its variables)
+ // end up on screen, and should say nothing of the machine it was made on.
+ const where = b.addWriteFiles();
+ _ = where.addCopyFile(program, r.name);
+ if (r.reads) |name| _ = where.addCopyFile(b.path(b.fmt("tools/{s}", .{name})), name);
+ const run = b.addSystemCommand(&.{ "env", "-i", "setarch", "-R" });
+ run.addArtifactArg(ztrace);
+ run.addArgs(&.{ "record", "--by", r.by, "--stack", "256", "-s", "64" });
+ // What an instrumented program tells of itself comes through a ring.
+ if (r.instr != null) run.addArg("--ring");
+ if (r.alloc) {
+ run.addArgs(&.{ "--alloc", "--preload" });
+ run.addArtifactArg(agent);
+ }
+ run.addArg("-o");
+ const trace = run.addOutputFileArg(b.fmt("{s}.ztrace", .{r.name}));
+ run.addArgs(&.{ "--", b.fmt("./{s}", .{r.name}) });
+ run.setCwd(where.getDirectory());
+ run.expectExitCode(0);
+ run.expectStdErrMatch("exit 0");
+
+ // Into the scene's own binary: the recording's bytes and the source it ran.
+ const file = b.fmt("{s}.ztrace", .{r.name});
+ record_step.dependOn(&b.addInstallFile(trace, b.fmt("recordings/{s}", .{file})).step);
+ _ = embedded.addCopyFile(trace, file);
+ _ = embedded.addCopyFile(source, r.source);
+ table.print(b.allocator, "pub const {s}: Program = .{{ .trace = @embedFile(\"{s}\"), .file = \"{s}\", .source = @embedFile(\"{s}\") }};\n", .{ r.name, file, r.source, r.source }) catch @panic("OOM");
+ }
+ const recordings = b.createModule(.{ .root_source_file = embedded.add("recordings.zig", b.fmt(
+ \\//! Generated by canim's build.zig: the recordings and the sources they ran.
+ \\pub const Program = struct {{ trace: []const u8, file: []const u8, source: []const u8 }};
+ \\{s}
+ , .{table.items})) });
+
+ // ---- Tests: the library's own, then on the real recordings.
+ const test_step = b.step("test", "Unit tests and the scripted runs");
+ test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("src/root.zig"), .target = target, .optimize = optimize, .imports = imports }) })).step);
+ test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{
+ .root_source_file = b.path("test/recordings.zig"),
+ .target = target,
+ .optimize = optimize,
+ .imports = &.{ .{ .name = "canim", .module = canim }, .{ .name = "recordings", .module = recordings }, .{ .name = "anim", .module = sb.modules.anim }, .{ .name = "ztrace", .module = zt.module("ztrace") } },
+ }) })).step);
+
+ // What a recording costs a frame: always optimized, whatever the build is.
+ const fast = b.createModule(.{ .root_source_file = b.path("src/root.zig"), .target = target, .optimize = .ReleaseFast, .imports = imports });
+ const bench = b.addRunArtifact(b.addExecutable(.{ .name = "bench", .root_module = b.createModule(.{
+ .root_source_file = b.path("tools/bench.zig"),
+ .target = target,
+ .optimize = .ReleaseFast,
+ .imports = &.{ .{ .name = "canim", .module = fast }, .{ .name = "recordings", .module = recordings }, .{ .name = "ztrace", .module = zt.module("ztrace") } },
+ }) }));
+ bench.has_side_effects = true;
+ bench.addPassthruArgs();
+ b.step("bench", "Time opening each recording and the queries a frame makes of it").dependOn(&bench.step);
+
+ // ---- Scenes.
+ const videos = b.step("videos", "Export every scene to out/NAME-1080.mp4 and out/NAME-2160.mp4 (use -Doptimize=ReleaseFast)");
+ for (scenes) |name| {
+ const scene = sb.addScene(.{ .root_source_file = b.path(b.fmt("scenes/{s}.zig", .{name})), .imports = &.{
+ .{ .name = "canim", .module = canim },
+ .{ .name = "recordings", .module = recordings },
+ } });
+ const exe = scene.app.addExecutable();
+ if (std.mem.eql(u8, name, chosen)) {
+ b.installArtifact(exe);
+ const library = scene.app.addLibrary();
+ b.step("run", "Play -Dscene with hot reload (rebuild with `zig build lib --watch`)").dependOn(&scene.app.addRun(library, .{}).step);
+ b.step("lib", "Build and install -Dscene's hot-reloadable library").dependOn(&b.addInstallArtifact(library, .{}).step);
+ const exporting = b.addRunArtifact(exe);
+ exporting.addArgs(&.{ "--state", b.fmt("{s}.state", .{name}), "--export" });
+ exporting.addPassthruArgs();
+ exporting.setCwd(b.path("."));
+ exporting.stdio = .inherit;
+ b.step("export", "Export -Dscene's frames: -- DIR for PNGs, or - for raw RGBA on stdout; then --fps N, --frames N, --size WxH").dependOn(&exporting.step);
+ // How it moves: contact sheets of every transition and plots of
+ // what changes from frame to frame (tools/motion.py).
+ const motion = b.addSystemCommand(&.{ "python3", "tools/motion.py" });
+ motion.addArtifactArg(exe);
+ motion.addArg(b.fmt("out/motion/{s}", .{name}));
+ motion.addPassthruArgs();
+ motion.setCwd(b.path("."));
+ motion.stdio = .inherit;
+ b.step("motion", "Judge -Dscene's motion: out/motion/NAME/ gets contact sheets of each transition and plots of change per frame").dependOn(&motion.step);
+ }
+ test_step.dependOn(&scene.app.addScript(exe, b.path(b.fmt("test/{s}.script", .{name})), .{}).step);
+
+ for ([_][]const u8{ "1920x1080", "3840x2160" }) |size| {
+ // The design's master: x264 from the raw frames, tagged bt709.
+ const video = b.addSystemCommand(&.{ "sh", "-c",
+ \\set -e
+ \\mkdir -p out
+ \\"$0" --state "$1" --export - --size "$2" --fps 60 |
+ \\ ffmpeg -loglevel error -y -f rawvideo -pix_fmt rgba -s "$2" -r 60 -i - \
+ \\ -c:v libx264 -crf 14 -preset slow -pix_fmt yuv420p \
+ \\ -colorspace bt709 -color_primaries bt709 -color_trc bt709 -color_range tv "$3"
+ });
+ video.addArtifactArg(exe);
+ _ = video.addOutputFileArg(b.fmt("{s}-video.state", .{name}));
+ video.addArgs(&.{ size, b.fmt("out/{s}-{s}.mp4", .{ name, size[5..] }) });
+ video.setCwd(b.path("."));
+ video.has_side_effects = true;
+ videos.dependOn(&video.step);
+ }
+ }
+}
diff --git a/anim/build.zig.zon b/anim/build.zig.zon
new file mode 100644
index 0000000..3112a1a
--- /dev/null
+++ b/anim/build.zig.zon
@@ -0,0 +1,12 @@
+.{
+ .name = .canim,
+ .version = "0.0.1",
+ .dependencies = .{
+ .ztrace = .{ .path = ".." },
+ .sketchbook = .{ .path = "../../sketchbook" },
+ .pardes = .{ .path = "../../02-pardes-code" },
+ },
+ .minimum_zig_version = "0.17.0",
+ .paths = .{""},
+ .fingerprint = 0x5e5f41c730876c03,
+}
diff --git a/anim/scenes/fib.zig b/anim/scenes/fib.zig
new file mode 100644
index 0000000..e98727d
--- /dev/null
+++ b/anim/scenes/fib.zig
@@ -0,0 +1,59 @@
+//! Recursion: fib(5), a call at a time. The debugger's whole context, from
+//! one recording of every instruction, and beside it the lens: every call
+//! of fib as a tree.
+//!
+//! How it moves (design/motion.md): the picture is established, then one
+//! call is walked in full (the line fires, `rdi` and `rsp` strike, the
+//! stack's words, then the backtrace's row and the tree's node; last the
+//! marks move on); the way down the first branch is hurried, a run that
+//! ramps in and out; the first return is walked (the answer in `rax`, the
+//! frame leaving); the rest of the tree is a sprint with the context
+//! veiled; and the last return, `fib(5)` itself, is walked again.
+const anim = @import("anim");
+const canim = @import("canim");
+const recordings = @import("recordings");
+
+pub const background = canim.background;
+pub const scene = anim.Live(frame, struct {});
+
+fn frame(s: *anim.Frame) void {
+ const rec = canim.open(recordings.steps);
+ // The calls of fib, in the order they are made: fib(5), fib(4), fib(3), fib(2), fib(1), fib(0), ...
+ const call = struct {
+ fn of(r: *canim.Recording, nth: usize) canim.Recording.Call {
+ return r.call("fib", nth);
+ }
+ }.of;
+ const split = canim.layout.split.beside;
+ // From main's line, about to call fib(5), to where fib(5) has returned to it.
+ var at = canim.cursor(s, rec, rec.lineMoment(10, rec.call("main", 0).enter));
+ at.levels = .{ .idea = .calls, .source_rows = 8 };
+ at.journey(.line, call(rec, 0).exit.?);
+ const ctx = canim.context(s, at, .{ .split = split });
+ // The lens: every call of fib as a tree, beside the frames they are on the stack.
+ const tree = canim.callTree(s, .{ .cursor = at, .box = split.lens, .function = "fib", .focus = true });
+ var says: canim.Narrator = .{};
+
+ // Staging: the whole picture, still, before a word; the words, before a step.
+ const joins = canim.ties(s, .{ .cursor = at });
+ canim.establish(s, .{ ctx.clock, ctx.source, ctx.disasm, ctx.registers, ctx.stack, ctx.backtrace, tree, joins });
+ says.line(s, "`fib` calls itself. A call is a frame on the stack and a node\nin the tree; its argument arrives in `rdi`.");
+ // The call, once, in full; and the two lines that lead to the next one.
+ at.walk(s, .line, rec.lineMoment(6, call(rec, 0).enter));
+ s.wait(canim.theme.time.beat);
+
+ // Pacing: the same three lines three times more. Seen once, so
+ // hurried: down the first branch at a run, to the call that does not call.
+ at.hurry(s, .line, rec.lineMoment(5, call(rec, 4).enter), .{});
+
+ says.line(s, "`fib(1)` needs no other call. Its answer leaves in `rax`,\nand its frame goes.");
+ // The return, in full: what recursion is for.
+ at.walk(s, .line, call(rec, 4).exit.?);
+
+ says.line(s, "And so on through every branch: fifteen calls,\nto add up `fib(5)`.");
+ // The pattern is known: the rest of the tree at a sprint, the tree its
+ // subject, slowing into the last answers.
+ at.hurry(s, .line, call(rec, 10).exit.?, .{ .pace = canim.theme.time.sprint });
+ at.walk(s, .line, call(rec, 0).exit.?);
+ s.wait(canim.theme.time.before_cut);
+}
diff --git a/anim/scenes/list.zig b/anim/scenes/list.zig
new file mode 100644
index 0000000..5f2c843
--- /dev/null
+++ b/anim/scenes/list.zig
@@ -0,0 +1,52 @@
+//! A linked list reversed in place: no node moves, each `next` is rewritten
+//! to point the other way. The debugger's context, and beside it the lens:
+//! the nodes and their arrows over a hexdump of the heap they are made of.
+//!
+//! How it moves (design/motion.md): the picture is established; the first
+//! trip round the loop is walked (each local strikes on the stack and in
+//! the table, then its tag slides to its node; the pointer's rewrite is
+//! armed with its old arrow going dashed, strikes, and the new arrow grows
+//! to the node it lands on); the second trip is hurried, with a rest; the
+//! third is walked again, and `head` takes the last node.
+const anim = @import("anim");
+const canim = @import("canim");
+const recordings = @import("recordings");
+
+pub const background = canim.background;
+pub const scene = anim.Live(frame, struct {});
+
+/// Each a pigment, the same on its tag in the list and in the table.
+const tracked = [_][]const u8{ "prev", "cur", "next" };
+
+fn frame(s: *anim.Frame) void {
+ const rec = canim.open(recordings.list);
+ const t = canim.theme.time;
+ const reverse = rec.call("reverse", 0);
+ // From reverse's first line (the list of three is built) to its last.
+ var at = canim.cursor(s, rec, rec.lineMoment(18, reverse.enter));
+ // The nodes are the idea; a tag slides and an arrow grows after its strike.
+ at.levels = .{ .cpu = false, .idea = .data, .follow = t.move, .source_rows = 5 };
+ const end = rec.lineMoment(27, reverse.enter);
+ at.journey(.line, end);
+ // The idea is the subject: the lens a size up, the nodes over the bytes they are.
+ const split = canim.layout.split.subject;
+ const ctx = canim.context(s, at, .{ .split = split, .quiet = true });
+ const lens = split.lens;
+ const list = canim.nodes(s, .{ .cursor = at, .box = .{ .x = lens.x, .y = lens.y, .w = lens.w, .h = 192 }, .root = "head", .track = &tracked, .focus = true });
+ const bytes = canim.hexdump(s, .{ .cursor = at, .box = .{ .x = lens.x, .y = lens.y + 204, .w = lens.w, .h = lens.h - 204 }, .base = rec.allocations[0].ptr - 16 });
+ var says: canim.Narrator = .{};
+
+ const joins = canim.ties(s, .{ .cursor = at });
+ canim.establish(s, .{ ctx.clock, ctx.source, ctx.disasm, ctx.registers, ctx.stack, ctx.backtrace, list, bytes, joins });
+ says.line(s, "A list is nodes on the heap, each holding the address of the next.\nReversing it moves no node: it rewrites every `next`.");
+ // Three names are set up, then the first trip round the loop, in full.
+ at.walk(s, .line, rec.lineMoment(20, rec.lineMoment(24, reverse.enter)));
+ says.line(s, "`next` remembers the way on, `cur->next` is turned round,\nand `prev` and `cur` each step along.");
+ // Pacing: the second trip is the same, so hurried; it keeps its rest.
+ at.hurry(s, .line, rec.lineMoment(20, rec.lineMoment(24, at.moment(s))), .{});
+ // The third in full again: the last `next` turns, and `cur` runs off the end.
+ at.walk(s, .line, rec.lineMoment(26, at.moment(s)));
+ says.line(s, "`head` takes the last node: the same three nodes,\nin the same places, read the other way.");
+ at.walk(s, .line, end);
+ s.wait(t.before_cut);
+}
diff --git a/anim/scenes/sort.zig b/anim/scenes/sort.zig
new file mode 100644
index 0000000..0f14269
--- /dev/null
+++ b/anim/scenes/sort.zig
@@ -0,0 +1,63 @@
+//! Insertion sort: neighbours compared, and swapped while the left is larger.
+//!
+//! How it moves (design/motion.md): it opens where `i` has reached 12, the
+//! first value out of order; the compare is walked (its two cells framed:
+//! the swap's anticipation), the caption about the swap stands two
+//! seconds before it, and the swap is two flights on arcs, the second a
+//! little behind the first, each cell struck as its value lands. The next
+//! trips are a run, the long middle a sprint, and the last swap is walked.
+const anim = @import("anim");
+const canim = @import("canim");
+const recordings = @import("recordings");
+
+pub const background = canim.background;
+pub const scene = anim.Live(frame, struct {});
+
+fn frame(s: *anim.Frame) void {
+ const rec = canim.open(recordings.sort);
+ const t = canim.theme.time;
+ const sort = rec.call("sort", 0);
+ // The `while`, about to compare 31 with 12: the stop before the one that calls swap.
+ var start = sort.enter;
+ while (rec.next(.over, rec.next(.over, start)) < rec.call("swap", 0).enter) start = rec.next(.over, start);
+ var at = canim.cursor(s, rec, start);
+ // The array is the idea; `i` and `j` are memory, and strike a beat before their tags slide.
+ at.levels = .{ .cpu = false, .idea = .data, .follow = t.quick, .source_rows = 8 };
+ // Its last compare: nothing larger is left of 20.
+ const last = rec.call("swap", 9);
+ const end = rec.next(.over, rec.next(.over, last.exit.?));
+ at.journey(.over, end);
+ // The context is the instrumented program's: its registers are unmarked.
+ const split = canim.layout.split.beside;
+ const ctx = canim.context(s, at, .{ .split = split, .quiet = true });
+ // The lens: the array as cells, and the two indices that walk it.
+ const cells = canim.array(s, .{ .cursor = at, .box = split.lens, .variable = "a", .indices = &.{ "i", "j" }, .focus = true });
+ var says: canim.Narrator = .{};
+ // A swap, start to finish, as one step of sort(): over the call.
+ const swap = struct {
+ fn step(c: canim.Cursor, frame_: *anim.Frame, r: *canim.Recording) void {
+ c.step(frame_, r.next(.over, c.moment(frame_)), canim.Array.swap, canim.Array.swap.total);
+ }
+ }.step;
+
+ const joins = canim.ties(s, .{ .cursor = at });
+ canim.establish(s, .{ ctx.clock, ctx.source, ctx.disasm, ctx.registers, ctx.stack, ctx.backtrace, cells, joins });
+ says.line(s, "`i` walks right. Everything left of it is in order,\nand 12 is not yet in its place.");
+ // The compare: both cells framed. It is the swap's anticipation.
+ at.walk(s, .over, rec.next(.over, start));
+ says.line(s, "While the one on the left is larger, they trade places,\nand `j` follows the smaller value down.");
+ // The caption of the step the scene is about stands a second longer.
+ s.wait(t.caption_lead);
+ // Arcs: the two values fly past each other, one over, one under.
+ swap(at, s, rec);
+ at.walk(s, .over, rec.next(.over, at.moment(s)));
+
+ // Pacing: the same again, so at a run; then the long way 5 has to go,
+ // at a sprint; slowing for the last swap.
+ at.hurry(s, .over, rec.call("swap", 3).enter - 1, .{ .to = t.run, .settle = false });
+ at.hurry(s, .over, last.enter - 1, .{ .pace = t.sprint, .from = t.run });
+ swap(at, s, rec);
+ at.walk(s, .over, end);
+ says.line(s, "Nothing larger is left of 20. The array is sorted.");
+ s.wait(t.before_cut - t.caption_lead);
+}
diff --git a/anim/scenes/syscalls.zig b/anim/scenes/syscalls.zig
new file mode 100644
index 0000000..1516251
--- /dev/null
+++ b/anim/scenes/syscalls.zig
@@ -0,0 +1,49 @@
+//! A program that needs the kernel four times: open, read, close, write.
+//! The debugger's context, and the kernel's side of each call as the lens.
+//!
+//! How it moves (design/motion.md): no effect before its cause. Each call
+//! has its own caption, up a second before the line fires; the registers
+//! that carry it are framed one at a time; the arrow goes down through
+//! the line, and only then does the kernel's side take the call: its
+//! name, its rows, its card. The bytes are copied two frames apart; the
+//! arrow comes back; `rax` is struck. A call is as long as what it does.
+const anim = @import("anim");
+const canim = @import("canim");
+const recordings = @import("recordings");
+
+pub const background = canim.background;
+pub const scene = anim.Live(frame, struct {});
+
+/// What the narrator says before each of main's calls, in order.
+const lines = [_][]const u8{
+ "`open`: a name goes down, and a small number comes back.\nThat number is the file from now on.",
+ "`read`: the kernel copies the file's bytes into `buf`,\nand says how many.",
+ "`close`: the number is handed back.",
+ "`write`: the same bytes go the other way,\nfrom `buf` to file number 1, the output.",
+};
+
+fn frame(s: *anim.Frame) void {
+ const rec = canim.open(recordings.hello);
+ // From main's first call to its last line.
+ var at = canim.cursor(s, rec, rec.lineMoment(6, rec.call("main", 0).enter));
+ at.journey(.line, rec.lineMoment(10, at.first));
+ const split = canim.layout.split.beside;
+ at.levels = .{ .source_rows = 8 };
+ const ctx = canim.context(s, at, .{ .split = split, .syscalls = true });
+ // The lens: the kernel's side of each call.
+ const kernel = canim.crossing(s, .{ .cursor = at, .box = split.lens, .focus = true });
+ var says: canim.Narrator = .{};
+ const t = canim.theme.time;
+
+ const joins = canim.ties(s, .{ .cursor = at });
+ canim.establish(s, .{ ctx.clock, ctx.source, ctx.disasm, ctx.registers, ctx.stack, ctx.backtrace, kernel, joins });
+ says.line(s, "A program cannot open a file or reach the screen itself.\nIt asks the kernel, and waits.");
+
+ // One call a phrase: its caption while nothing moves, then the crossing.
+ for (lines) |line| {
+ says.line(s, line);
+ canim.syscalls.step(at, s, .line);
+ s.wait(t.phrase_rest);
+ }
+ s.wait(t.before_cut - t.phrase_rest);
+}
diff --git a/anim/scenes/title.zig b/anim/scenes/title.zig
new file mode 100644
index 0000000..3646da4
--- /dev/null
+++ b/anim/scenes/title.zig
@@ -0,0 +1,22 @@
+//! The card before the scenes: what the series is, and the marks every
+//! picture in it uses.
+const anim = @import("anim");
+const canim = @import("canim");
+
+pub const background = canim.background;
+pub const scene = anim.Live(frame, struct {});
+
+fn frame(s: *anim.Frame) void {
+ const size = canim.theme.size.sans;
+ const text = canim.theme.color.text;
+ const series = canim.label(s, .{ .text = "How programs really run", .box = .{ .x = 64, .y = 138, .w = 900, .h = 48 }, .size = size.kicker, .color = text.dim });
+ const title = canim.label(s, .{ .text = "Five small programs,\none step at a time", .box = .{ .x = 64, .y = 220, .w = 1792, .h = size.title_leading }, .face = .sans_bold, .size = size.title, .color = text.bright });
+ const under = canim.label(s, .{ .text = "recorded as they ran: every line, register and byte", .box = .{ .x = 64, .y = 500, .w = 1792, .h = 60 }, .face = .sans, .size = size.subtitle, .color = text.dim });
+ const marks = canim.legend(s, .{ .box = canim.theme.cols(0, 12, 512, 256) });
+ const t = canim.theme.time;
+ s.play(.{ series.fadeIn(), title.fadeIn() }, .{ .seconds = t.layout, .ease = canim.ease.enter });
+ s.play(.{under.fadeIn()}, .{ .seconds = t.move });
+ s.wait(t.beat);
+ s.play(.{marks.fadeIn()}, .{ .seconds = t.travel });
+ s.wait(4);
+}
diff --git a/anim/scenes/zoom.zig b/anim/scenes/zoom.zig
new file mode 100644
index 0000000..6eb3248
--- /dev/null
+++ b/anim/scenes/zoom.zig
@@ -0,0 +1,50 @@
+//! One line of C, all the way down: the instructions it is, the registers
+//! they change, the words they write on the stack. Every level is on
+//! screen the whole time; the scene steps an instruction at a time and
+//! says which one to look at.
+//!
+//! How it moves (design/motion.md): a step is an instruction: the pc's
+//! row fires in the disassembly, the registers it changed strike, then
+//! the stack, and the mark walks down the listing. The camera goes
+//! nearer once, announced (its target framed, the rest cleared first),
+//! for the call: the eight bytes of the way back, and the frame built
+//! under them; then back, and the line is where it was, one call deeper.
+const anim = @import("anim");
+const canim = @import("canim");
+const recordings = @import("recordings");
+
+pub const background = canim.background;
+pub const scene = anim.Live(frame, struct {});
+
+fn frame(s: *anim.Frame) void {
+ const rec = canim.open(recordings.steps);
+ const t = canim.theme.time;
+ // fib(5), about to run line 6: `return fib(n-1) + fib(n-2);`. Its first call is fib(4).
+ const call = rec.call("fib", 1);
+ var at = canim.cursor(s, rec, rec.lineMoment(6, rec.call("fib", 0).enter));
+ const end = rec.lineMoment(6, call.enter);
+ at.journey(.moment, end);
+ // A step is an instruction: it fires on the pc's row.
+ at.levels = .{ .fire = .disasm, .source_rows = 14 };
+ const split = canim.layout.split.none;
+ const ctx = canim.context(s, at, .{ .split = split });
+ var cam: canim.Camera = .{};
+ var says: canim.Narrator = .{};
+
+ const joins = canim.ties(s, .{ .cursor = at });
+ canim.establish(s, .{ ctx.clock, ctx.source, ctx.disasm, ctx.registers, ctx.stack, ctx.backtrace, joins });
+ says.line(s, "A line of C is a handful of instructions.\nThis one calls `fib(n-1)`: follow it down.");
+ // The CPU's level: an instruction a step. The argument is worked out in `rdi`.
+ at.walk(s, .moment, call.enter - 1);
+
+ says.line(s, "`call` writes eight bytes on the stack: the way back.\nThe new frame saves `rbp` under them, then its own `n`.");
+ // Nearer, for the bytes: the stack alone, twice the size.
+ cam.go(s, canim.layout.stack, 2, .{ ctx.source, ctx.disasm, ctx.registers, ctx.backtrace });
+ at.walk(s, .moment, call.enter + 4);
+ cam.back(s, .{ ctx.source, ctx.disasm, ctx.registers, ctx.backtrace });
+
+ says.line(s, "Eleven instructions and three words of stack later\n`fib(4)` begins: the same lines, one call deeper.");
+ at.walk(s, .line, end);
+ s.wait(t.before_cut);
+ cam.apply(s);
+}
diff --git a/anim/src/Recording.zig b/anim/src/Recording.zig
new file mode 100644
index 0000000..aeaacf9
--- /dev/null
+++ b/anim/src/Recording.zig
@@ -0,0 +1,670 @@
+//! A recording, open for a scene: the trace, the thread the components
+//! show, and an index made once by reading every moment in order (calls as
+//! a tree, syscalls, marks, allocations, the source line after each moment,
+//! which registers and bytes each moment changed, every string). Components
+//! read the program's state through `moment`; scenes find where to go with
+//! `next` and the functions after it.
+const std = @import("std");
+const zt = @import("ztrace");
+const pardes = @import("pardes-syntax");
+pub const types = @import("ztrace-types");
+const store = zt.store;
+
+const Recording = @This();
+
+pub const Moment = store.Moment;
+pub const Variable = store.Variable;
+
+/// One call, from the `call` event to its `ret`.
+pub const Call = struct {
+ /// A string id: `name(function)`.
+ function: u64,
+ parent: ?u32,
+ /// Calls it is inside of.
+ depth: u32,
+ /// The stack pointer as it was entered.
+ sp: u64,
+ /// The moments that hold its `call` and its `ret` (null: never returned).
+ enter: u64,
+ exit: ?u64 = null,
+ /// Its first argument, as far as the recording tells: the first
+ /// variable declared in it (`parameter`: where, how many bytes), else
+ /// `rdi` as it was called.
+ arg: ?u64 = null,
+ parameter: ?Span = null,
+ /// That variable's name, a string id; null when the recording names none.
+ parameter_name: ?u64 = null,
+ result: u64 = 0,
+
+ /// On the stack at moment `i`.
+ pub fn active(c: Call, i: u64) bool {
+ return c.enter <= i and (c.exit == null or c.exit.? > i);
+ }
+};
+
+pub const Syscall = struct {
+ nr: u16,
+ args: [6]u64,
+ /// The string or buffer its first pointer argument points at, when the
+ /// recorder captured it (a path, the bytes written).
+ text: []const u8 = "",
+ /// The moment that holds its entry, and its exit (null: it never came back).
+ enter: u64,
+ exit: ?u64 = null,
+ result: u64 = 0,
+};
+
+pub const Mark = struct { moment: u64, text: []const u8 };
+
+/// An allocation ever made: its place in this list is its identity, the
+/// same in every view.
+pub const Born = struct { ptr: u64, size: u64, moment: u64, event: u64 };
+
+/// A run of bytes a moment changed, or read.
+pub const Span = struct { addr: u64, len: u64 };
+
+/// Where a cursor's step may end.
+pub const Stop = enum {
+ /// The next moment, whatever the recorder made one: an instruction, a line.
+ moment,
+ /// The next moment on another line of the program's source.
+ line,
+ /// The same, not counting lines inside calls made on the way: step over.
+ over,
+ /// The next call or return.
+ call,
+ /// The next syscall.
+ syscall,
+};
+
+trace: zt.Trace,
+/// What `open` was given: the recording's bytes, to know it again.
+key: [*]const u8,
+/// The source file the recording's lines are in, and its text.
+file: []const u8,
+source: []const u8,
+/// Its functions, as pardes outlines them, and how many lines it has.
+functions: []const Function = &.{},
+line_count: u32 = 0,
+/// The thread shown: the first to make an event.
+tid: u32 = 0,
+/// The source line `tid` is on after each moment (line 0: none yet), in
+/// whatever file; and the last line of `file` it was on, which is where
+/// the program's own source stands while a library runs.
+lines: []store.Line = &.{},
+own: []u32 = &.{},
+/// Whether each moment reached a line of `file`: a `line` event of its own.
+reached: []bool = &.{},
+/// How many calls deep `tid` is after each moment.
+depths: []u32 = &.{},
+calls: []Call = &.{},
+syscalls: []Syscall = &.{},
+marks: []Mark = &.{},
+allocations: []Born = &.{},
+/// For each moment, a bit for each register of `Regs.names` it changed.
+registers: []u32 = &.{},
+write_spans: Spans = .{},
+read_spans: Spans = .{},
+strings: std.AutoHashMapUnmanaged(u64, []const u8) = .empty,
+arena: std.heap.ArenaAllocator,
+
+const gpa = std.heap.smp_allocator;
+
+/// Recordings opened so far. They live as long as the process: a scene's
+/// `frame` runs every frame and asks again.
+var opened: std.ArrayList(*Recording) = .empty;
+
+/// A recording as the build embeds it in `recordings`: a `.ztrace` file's
+/// bytes (`trace`), the source it ran (`source`) and its name (`file`).
+/// Opened and indexed the first time.
+pub fn open(program: anytype) *Recording {
+ for (opened.items) |r| if (r.key == program.trace.ptr) return r;
+ const r = load(program.trace, program.file, program.source) catch |err| std.debug.panic("canim: cannot open the recording of {s}: {t}", .{ program.file, err });
+ opened.append(gpa, r) catch @panic("canim: out of memory");
+ return r;
+}
+
+fn load(bytes: []const u8, file: []const u8, source: []const u8) !*Recording {
+ // The trace reads a file: give it one in memory.
+ const linux = std.os.linux;
+ const rc = linux.memfd_create("canim", linux.MFD.CLOEXEC);
+ if (linux.errno(rc) != .SUCCESS) return error.NoMemfd;
+ const fd: linux.fd_t = @intCast(rc);
+ defer _ = linux.close(fd);
+ var done: usize = 0;
+ while (done < bytes.len) {
+ const n = linux.write(fd, bytes[done..].ptr, bytes.len - done);
+ if (linux.errno(n) != .SUCCESS) return error.WriteFailed;
+ done += n;
+ }
+ var path_buf: [64]u8 = undefined;
+ const path = try std.fmt.bufPrint(&path_buf, "/proc/self/fd/{d}", .{fd});
+
+ const r = try gpa.create(Recording);
+ errdefer gpa.destroy(r);
+ r.* = .{ .trace = try .open(gpa, std.Io.Threaded.global_single_threaded.io(), path), .key = bytes.ptr, .file = file, .source = source, .arena = .init(gpa) };
+ if (r.trace.len == 0) return error.EmptyRecording;
+ r.functions = try outline(r.arena.allocator(), source, file);
+ r.line_count = @intCast(std.mem.count(u8, source, "\n") + @intFromBool(source.len > 0 and source[source.len - 1] != '\n'));
+ try r.index();
+ return r;
+}
+
+/// The instruction at `addr` as the debugger disassembled it at moment
+/// `i` (`text` is Intel syntax, in `buf`); null where it recorded none.
+/// `back` is how long the instruction before it in its function is (0: not known).
+pub fn instruction(r: *const Recording, i: u64, addr: u64, buf: []u8) ?struct { len: u8, back: u8, text: []const u8 } {
+ const found = (zt.telescope.instruction(r.moment(i), addr, buf) catch return null) orelse return null;
+ return .{ .len = found.len, .back = found.back, .text = found.text };
+}
+
+/// The first line a source panel of `fit` lines shows when the program is
+/// on `line`: the whole file when it fits; else a window that has the line
+/// in its middle third, and is the same window for every line of that
+/// third, so that the text moves only when the program has moved on.
+pub fn viewFirst(r: *const Recording, fit: u32, line: u32) u32 {
+ if (r.line_count <= fit or fit < 3) return 1;
+ const third = fit / 3;
+ const band = (@max(line, 1) - 1) / third;
+ return std.math.clamp(@as(u32, @intCast(@max(@as(i64, band) - 1, 0))) * third + 1, 1, r.line_count - fit + 1);
+}
+
+/// Runs of bytes, a list for each moment.
+const Spans = struct {
+ all: []Span = &.{},
+ /// Where each moment's end in `all`.
+ ends: []u32 = &.{},
+
+ /// Those of the moments after `from`, up to `to`.
+ fn of(s: Spans, from: u64, to: u64) []const Span {
+ if (to >= s.ends.len or from >= to) return &.{};
+ return s.all[s.ends[from]..s.ends[to]];
+ }
+};
+
+/// shortcut: reads the whole recording at open (about 5 us a moment) and
+/// follows one thread; a recording of millions of moments wants this stored
+/// in the file by the recorder.
+fn index(r: *Recording) !void {
+ const arena = r.arena.allocator();
+ var lines: std.ArrayList(store.Line) = .empty;
+ var own: std.ArrayList(u32) = .empty;
+ var reached: std.ArrayList(bool) = .empty;
+ var depths: std.ArrayList(u32) = .empty;
+ var calls: std.ArrayList(Call) = .empty;
+ var syscalls: std.ArrayList(Syscall) = .empty;
+ var marks: std.ArrayList(Mark) = .empty;
+ var allocations: std.ArrayList(Born) = .empty;
+ var registers: std.ArrayList(u32) = .empty;
+ var writes: std.ArrayList(Span) = .empty;
+ var write_ends: std.ArrayList(u32) = .empty;
+ var reads: std.ArrayList(Span) = .empty;
+ var read_ends: std.ArrayList(u32) = .empty;
+ var open_calls: std.ArrayList(u32) = .empty;
+ defer open_calls.deinit(gpa);
+ // A recording of instructions tells no calls: they are read off the
+ // open_calls pointer, until its first `call` event says otherwise.
+ var derived: std.ArrayList(u64) = .empty;
+ defer derived.deinit(gpa);
+ var told = false;
+ var before: ?zt.Regs = null;
+ var count: u64 = 0;
+ // Which bytes any moment so far has recorded, 64 to a word of bits.
+ var seen: std.AutoHashMapUnmanaged(u64, u64) = .empty;
+ defer seen.deinit(gpa);
+ // For each write of the moment in hand: whether the debugger saw it (a
+ // snapshot of memory at a stop) and no store of the program's told it.
+ var snapshots: std.ArrayList(bool) = .empty;
+ defer snapshots.deinit(gpa);
+
+ for (0..r.trace.len) |i| {
+ const m = try r.trace.moment(i);
+ var events = try m.events(gpa);
+ defer events.deinit(gpa);
+ const first_call = calls.items.len;
+ const first_write = writes.items.len;
+ var line_at: ?u64 = null;
+ var line_file: ?u64 = null;
+ var stepped = false;
+ var takes_nothing = false;
+ // An instrumented program's own events are drained before the
+ // debugger reports its stop: what follows its line is the debugger's.
+ var debugger_spoke = false;
+ snapshots.clearRetainingCapacity();
+ while (events.next()) |item| {
+ const ev = item.ev;
+ count += 1;
+ if (ev.kind == .string) try r.strings.put(arena, ev.a[0], try arena.dupe(u8, item.payload));
+ if (ev.tid == 0) continue;
+ if (r.tid == 0) r.tid = ev.tid;
+ if (ev.tid != r.tid) continue;
+ switch (ev.kind) {
+ .call => {
+ told = true;
+ try calls.append(arena, .{ .function = ev.a[0], .parent = open_calls.getLastOrNull(), .depth = @intCast(open_calls.items.len), .sp = ev.a[2], .enter = i });
+ try open_calls.append(gpa, @intCast(calls.items.len - 1));
+ },
+ .ret => if (open_calls.pop()) |c| {
+ calls.items[c].exit = i;
+ calls.items[c].result = ev.a[1];
+ },
+ .syscall_enter => try syscalls.append(arena, .{ .nr = ev.aux, .args = ev.a, .enter = i, .text = if (item.payload.len != @sizeOf(zt.Regs)) try arena.dupe(u8, item.payload) else "" }),
+ .syscall_exit => if (syscalls.items.len > 0) {
+ const last = &syscalls.items[syscalls.items.len - 1];
+ if (last.exit == null) {
+ last.exit = i;
+ last.result = ev.a[0];
+ }
+ },
+ .mark => try marks.append(arena, .{ .moment = i, .text = try arena.dupe(u8, item.payload) }),
+ .alloc => try allocations.append(arena, .{ .ptr = ev.a[0], .size = ev.a[1], .moment = i, .event = count }),
+ // A store that left the bytes as they were is told too, with no payload: it is still a write.
+ .mem_write => if (ev.a[1] > 0) {
+ try writes.append(arena, .{ .addr = ev.a[0], .len = ev.a[1] });
+ try snapshots.append(gpa, !told or debugger_spoke);
+ },
+ .mem_read => if (ev.a[1] > 0) try reads.append(arena, .{ .addr = ev.a[0], .len = ev.a[1] }),
+ .variable => if (open_calls.getLastOrNull()) |c| {
+ // The first variable of a function that takes something is what it was given.
+ const takes = for (r.functions) |f| {
+ if (std.mem.eql(u8, f.name, r.name(calls.items[c].function))) break f.takes;
+ } else true;
+ if (takes and calls.items[c].parameter == null and ev.a[1] <= 8) {
+ calls.items[c].parameter = .{ .addr = ev.a[0], .len = ev.a[1] };
+ calls.items[c].parameter_name = ev.a[2];
+ }
+ },
+ .line => {
+ line_at = ev.a[3];
+ line_file = ev.a[0];
+ // The pass counts its strings from 1; the debugger's ids are hashes with the top bit set.
+ if (ev.a[0] >> 63 != 0) debugger_spoke = true;
+ },
+ .step, .breakpoint => stepped = true,
+ else => {},
+ }
+ }
+ const regs = try m.regs(r.tid);
+ // A debugger records the stack it can see, not what the program
+ // stores: bytes seen for the first time were not written by this
+ // step, unless it pushed them (the stack pointer went down a word).
+ var kept = first_write;
+ for (writes.items[first_write..], snapshots.items) |span, snapshot| {
+ var fresh = true;
+ for (0..span.len) |b| {
+ const gop = try seen.getOrPut(gpa, (span.addr + b) / 64);
+ if (!gop.found_existing) gop.value_ptr.* = 0;
+ const bit = @as(u64, 1) << @intCast((span.addr + b) % 64);
+ if (gop.value_ptr.* & bit != 0) fresh = false;
+ gop.value_ptr.* |= bit;
+ }
+ var keep: ?Span = span;
+ if (stepped and fresh and snapshot) {
+ const pushed = regs != null and before != null and regs.?.rsp + 8 == before.?.rsp and span.addr <= regs.?.rsp and span.addr + span.len >= regs.?.rsp + 8;
+ keep = if (pushed) .{ .addr = regs.?.rsp, .len = 8 } else null;
+ }
+ if (keep) |span_kept| {
+ writes.items[kept] = span_kept;
+ kept += 1;
+ }
+ }
+ writes.shrinkRetainingCapacity(kept);
+ try write_ends.append(arena, @intCast(writes.items.len));
+ try read_ends.append(arena, @intCast(reads.items.len));
+ const line = (try m.line(r.tid)) orelse store.Line{};
+ try lines.append(arena, line);
+ const ours = line.line != 0 and std.mem.eql(u8, std.fs.path.basename(r.name(line.file)), r.file);
+ try own.append(arena, if (ours) line.line else if (own.items.len > 0) own.items[own.items.len - 1] else 0);
+ try reached.append(arena, ours and line_file != null);
+ try registers.append(arena, if (regs != null and before != null) changedRegisters(before.?, regs.?) else 0);
+
+ if (!told and stepped and regs != null and before != null) {
+ const now = regs.?;
+ const was = before.?;
+ // Back where the newest call was made from, its frame gone.
+ if (derived.getLastOrNull()) |back| {
+ const top = &calls.items[open_calls.getLast()];
+ if (now.rip == back and now.rsp == top.sp + 8) {
+ _ = derived.pop();
+ _ = open_calls.pop();
+ top.exit = i;
+ top.result = now.rax;
+ }
+ }
+ // A call pushes the address after itself and lands on a line of ours.
+ if (now.rsp + 8 == was.rsp and line_at == now.rip and ours) {
+ if (try word(m, now.rsp, 8)) |back| if (back > was.rip and back - was.rip <= 15) {
+ const function = r.functionAt(line.line);
+ takes_nothing = function != null and !function.?.takes;
+ try calls.append(arena, .{ .function = try r.intern(if (function) |fun| fun.name else "?"), .parent = open_calls.getLastOrNull(), .depth = @intCast(open_calls.items.len), .sp = now.rsp, .enter = i });
+ try open_calls.append(gpa, @intCast(calls.items.len - 1));
+ try derived.append(gpa, back);
+ };
+ }
+ }
+ if (regs) |g| before = g;
+ try depths.append(arena, @intCast(open_calls.items.len));
+
+ // What each open call was given, once the recording has it: the
+ // value of its first variable, or for one read off the registers, rdi.
+ for (calls.items[first_call..]) |*c| {
+ if (!told and regs != null and !takes_nothing) c.arg = regs.?.rdi;
+ }
+ // (Once it is stored: until then that stretch of stack holds what was there before.)
+ for (open_calls.items) |c| {
+ const call_made = &calls.items[c];
+ if (call_made.arg != null) continue;
+ if (call_made.parameter) |p| if (touches(writes.items[first_write..], p.addr, p.len)) {
+ call_made.arg = try word(m, p.addr, @intCast(p.len));
+ };
+ }
+ }
+ // An instrumented program under the debugger says "call" a few stops
+ // after the debugger has stopped on the callee's first line: the call
+ // began at that stop.
+ if (told) for (calls.items) |*c| {
+ var at = c.enter;
+ var back: usize = 0;
+ while (at > 0 and back < 64 and !reached.items[at]) : (back += 1) at -= 1;
+ if (!reached.items[at] or at == c.enter) continue;
+ for (depths.items[at..c.enter]) |*depth| depth.* += 1;
+ c.enter = at;
+ };
+ r.lines = lines.items;
+ r.own = own.items;
+ r.reached = reached.items;
+ r.depths = depths.items;
+ r.calls = calls.items;
+ r.syscalls = syscalls.items;
+ r.marks = marks.items;
+ r.allocations = allocations.items;
+ r.registers = registers.items;
+ r.write_spans = .{ .all = writes.items, .ends = write_ends.items };
+ r.read_spans = .{ .all = reads.items, .ends = read_ends.items };
+}
+
+/// A string id for `text`, for names the recording did not define itself.
+fn intern(r: *Recording, text: []const u8) !u64 {
+ const id = std.hash.Wyhash.hash(0, text) | 1 << 63;
+ if (!r.strings.contains(id)) try r.strings.put(r.arena.allocator(), id, try r.arena.allocator().dupe(u8, text));
+ return id;
+}
+
+pub const Function = struct {
+ name: []const u8,
+ /// Whether it has parameters: `main(void)` has none.
+ takes: bool,
+ /// Its declaration's first line (from 1) and last.
+ first: u32,
+ last: u32,
+};
+
+/// The functions of `source`, as pardes outlines them: a name is the word
+/// before the first parenthesis of a declaration's header.
+pub fn outline(arena: std.mem.Allocator, source: []const u8, file: []const u8) ![]Function {
+ var analysis = pardes.analyzeSource(gpa, file, source, true, false) catch return &.{};
+ defer analysis.deinit(gpa);
+ var found: std.ArrayList(Function) = .empty;
+ for (analysis.declarations) |d| {
+ const header = source[d.start_byte..d.header_end_byte];
+ const paren = std.mem.indexOfScalar(u8, header, '(') orelse continue;
+ var from = paren;
+ while (from > 0 and (std.ascii.isAlphanumeric(header[from - 1]) or header[from - 1] == '_')) from -= 1;
+ if (from == paren) continue;
+ const close = std.mem.indexOfScalarPos(u8, header, paren, ')') orelse header.len;
+ const params = std.mem.trim(u8, header[paren + 1 .. close], " ");
+ try found.append(arena, .{ .name = header[from..paren], .takes = params.len > 0 and !std.mem.eql(u8, params, "void"), .first = @intCast(d.start_line + 1), .last = @intCast(d.end_line + 1) });
+ }
+ return found.items;
+}
+
+/// The function whose declaration holds `line` (from 1): the innermost.
+pub fn functionAt(r: *const Recording, line: u32) ?Function {
+ var found: ?Function = null;
+ for (r.functions) |f| if (line >= f.first and line <= f.last) {
+ found = f;
+ };
+ return found;
+}
+
+/// `size` bytes at `addr` as a little-endian number; null where a byte of
+/// it was never recorded.
+pub fn word(m: Moment, addr: u64, size: usize) !?u64 {
+ var bytes: [8]u8 = @splat(0);
+ var known: [8]bool = undefined;
+ try m.read(addr, bytes[0..size], known[0..size]);
+ for (known[0..size]) |k| if (!k) return null;
+ return std.mem.readInt(u64, &bytes, .little);
+}
+
+pub fn len(r: *const Recording) u64 {
+ return r.trace.len;
+}
+
+/// The last moment.
+pub fn end(r: *const Recording) u64 {
+ return r.trace.len - 1;
+}
+
+/// The program's state at moment `i` (the last one, past the end).
+pub fn moment(r: *const Recording, i: u64) Moment {
+ return r.trace.moment(@min(i, r.end())) catch unreachable;
+}
+
+/// Register `reg` of the thread shown at moment `i`; 0 when the recording
+/// has no registers there.
+pub fn register(r: *const Recording, i: u64, reg: []const u8) u64 {
+ const regs = (r.moment(i).regs(r.tid) catch null) orelse return 0;
+ return regs.named(reg) orelse 0;
+}
+
+/// A string id's text; "?" for one the recording never defined.
+pub fn name(r: *const Recording, id: u64) []const u8 {
+ return r.strings.get(id) orelse "?";
+}
+
+/// The live variable called `text`: the innermost of that name.
+pub fn variable(r: *const Recording, scratch: std.mem.Allocator, m: Moment, text: []const u8) ?Variable {
+ const all = m.variables(scratch) catch return null;
+ var found: ?Variable = null;
+ for (all) |v| {
+ if (std.mem.eql(u8, r.name(v.name), text) and (found == null or v.depth > found.?.depth)) found = v;
+ }
+ return found;
+}
+
+/// A variable's type, as the compiler pass described it, with a named type
+/// (`struct node`, a typedef) followed to what it is. Null when the
+/// recording has no description (it was not made by `ztrace cc`).
+pub fn typeOf(r: *const Recording, scratch: std.mem.Allocator, id: u64) ?types.Type {
+ return r.resolve(scratch, types.parse(scratch, r.strings.get(id) orelse return null) catch return null);
+}
+
+/// `t`, or what its name stands for.
+pub fn resolve(r: *const Recording, scratch: std.mem.Allocator, t: types.Type) ?types.Type {
+ var at = t;
+ // A typedef of a typedef of a struct, and no further.
+ for (0..8) |_| {
+ if (at != .named) return at;
+ at = types.parse(scratch, r.strings.get(types.defId(at.named)) orelse return null) catch return null;
+ }
+ return null;
+}
+
+/// Whether variable `v` has been stored to since the call it lives in
+/// began: until then its bytes are whatever that stretch of stack held
+/// before, and a picture should not show them as its value.
+pub fn assigned(r: *const Recording, v: Variable, i: u64) bool {
+ if (v.depth == 0) return true;
+ var enter: u64 = 0;
+ for (r.calls) |c| {
+ if (c.enter > i) break;
+ if (c.active(i) and c.depth + 1 == v.depth) enter = c.enter;
+ }
+ return touches(r.written(enter -| 1, i), v.addr, v.size);
+}
+
+/// Which allocation ever made holds `addr` at moment `m`: the same number
+/// for the same object in every view, null outside the heap.
+pub fn identity(r: *const Recording, m: Moment, addr: u64) ?usize {
+ const a = (m.allocation(addr) catch return null) orelse return null;
+ for (r.allocations, 0..) |b, i| if (b.event == a.born) return i;
+ return null;
+}
+
+/// The calls open at moment `i`, outermost first, in `scratch`.
+/// shortcut: looks at every call made by then; a recording of a million calls wants each call's stack kept as a chain of parents.
+pub fn stack(r: *const Recording, scratch: std.mem.Allocator, i: u64) []const Call {
+ var out: std.ArrayList(Call) = .empty;
+ for (r.calls) |c| {
+ if (c.enter > i) break;
+ if (c.active(i)) out.append(scratch, c) catch break;
+ }
+ return out.items;
+}
+
+// ---------------------------------------------------------------------------
+// Finding moments. Each returns the last moment when there is none: a
+// cursor sent there plays to the end.
+
+/// The first moment after `from` that is a stop of kind `by`.
+pub fn next(r: *const Recording, by: Stop, from: u64) u64 {
+ if (from >= r.end()) return r.end();
+ switch (by) {
+ .moment => return from + 1,
+ .line, .over => {
+ const depth = r.depths[from];
+ for (from + 1..r.len()) |i| {
+ // A line of the program's own, newly reached: another line,
+ // or the same one in another call (fib's, a level down).
+ if (!r.reached[i] or (r.own[i] == r.own[from] and r.depths[i] == depth)) continue;
+ if (by == .line or r.depths[i] <= depth) return i;
+ }
+ },
+ .call => {
+ var best = r.end();
+ for (r.calls) |c| {
+ if (c.enter > from) best = @min(best, c.enter);
+ if (c.exit) |e| if (e > from) {
+ best = @min(best, e);
+ };
+ }
+ return best;
+ },
+ .syscall => for (r.syscalls) |s| if (s.enter > from) return s.enter,
+ }
+ return r.end();
+}
+
+/// The first moment at or after `from` on line `line` of the program's source.
+pub fn lineMoment(r: *const Recording, line: u32, from: u64) u64 {
+ for (r.own[@min(from, r.len())..], from..) |l, i| if (l == line) return i;
+ return r.end();
+}
+
+/// The first moment after `from` that changes a byte in `addr .. addr + size`.
+pub fn nextWrite(r: *const Recording, addr: u64, size: u64, from: u64) u64 {
+ var i = from + 1;
+ while (i < r.len()) : (i += 1) if (touches(r.written(i - 1, i), addr, size)) return i;
+ return r.end();
+}
+
+/// The moment of the mark `text`. A scene asking for a mark the program
+/// never made is a mistake in the scene.
+pub fn mark(r: *const Recording, text: []const u8) u64 {
+ for (r.marks) |m| if (std.mem.eql(u8, m.text, text)) return m.moment;
+ std.debug.panic("canim: the recording has no mark \"{s}\"", .{text});
+}
+
+/// The `nth` call (from 0) of the function called `function`.
+pub fn call(r: *const Recording, function: []const u8, nth: usize) Call {
+ var seen: usize = 0;
+ for (r.calls) |c| if (std.mem.eql(u8, r.name(c.function), function)) {
+ if (seen == nth) return c;
+ seen += 1;
+ };
+ std.debug.panic("canim: the recording has no call {d} of \"{s}\"", .{ nth, function });
+}
+
+// ---------------------------------------------------------------------------
+// What changed.
+
+/// The bytes the moments after `from`, up to `to`, changed.
+pub fn written(r: *const Recording, from: u64, to: u64) []const Span {
+ return r.write_spans.of(from, to);
+}
+
+/// The bytes they read.
+pub fn read(r: *const Recording, from: u64, to: u64) []const Span {
+ return r.read_spans.of(from, to);
+}
+
+/// A bit for each register of `Regs.names` they changed.
+pub fn registersChanged(r: *const Recording, from: u64, to: u64) u32 {
+ var mask: u32 = 0;
+ if (to < r.registers.len and from < to) for (r.registers[from + 1 .. to + 1]) |m| {
+ mask |= m;
+ };
+ return mask;
+}
+
+pub fn touches(list: []const Span, addr: u64, size: u64) bool {
+ for (list) |s| if (s.addr < addr + size and s.addr + s.len > addr) return true;
+ return false;
+}
+
+/// A bit for each register of `Regs.names` that differs between `a` and `b`.
+pub fn changedRegisters(a: zt.Regs, b: zt.Regs) u32 {
+ var mask: u32 = 0;
+ inline for (zt.Regs.names, 0..) |reg, i| {
+ if (@field(a, reg) != @field(b, reg)) mask |= 1 << i;
+ }
+ return mask;
+}
+
+test "registers that differ are told by their place in Regs.names" {
+ const a: zt.Regs = .{ .rax = 1, .rip = 0x1000, .rsp = 8 };
+ var b = a;
+ b.rax = 2;
+ b.rip = 0x1004;
+ try std.testing.expectEqualStrings("rax", zt.Regs.names[0]);
+ const mask = changedRegisters(a, b);
+ try std.testing.expect(mask & 1 != 0);
+ try std.testing.expectEqual(@as(u32, 2), @popCount(mask));
+ try std.testing.expectEqual(@as(u32, 0), changedRegisters(a, a));
+}
+
+test "spans touch the ranges they overlap" {
+ const list = [_]Span{ .{ .addr = 0x100, .len = 4 }, .{ .addr = 0x200, .len = 1 } };
+ try std.testing.expect(touches(&list, 0x100, 8));
+ try std.testing.expect(touches(&list, 0x0fc, 5));
+ try std.testing.expect(!touches(&list, 0x0fc, 4));
+ try std.testing.expect(!touches(&list, 0x104, 8));
+ try std.testing.expect(touches(&list, 0x1f9, 8));
+}
+
+test "a function is named by the declaration that holds the line" {
+ const source =
+ \\#include <stdio.h>
+ \\
+ \\long fib(long n) {
+ \\ if (n < 2)
+ \\ return n;
+ \\ return fib(n - 1) + fib(n - 2);
+ \\}
+ \\
+ \\int main(void) {
+ \\ printf("%ld\\n", fib(5));
+ \\ return 0;
+ \\}
+ ;
+ var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
+ defer arena.deinit();
+ const r: Recording = .{ .trace = undefined, .key = undefined, .file = "fib.c", .source = source, .arena = undefined, .functions = try outline(arena.allocator(), source, "fib.c") };
+ try std.testing.expectEqualStrings("fib", r.functionAt(3).?.name);
+ try std.testing.expect(r.functionAt(6).?.takes);
+ try std.testing.expectEqualStrings("main", r.functionAt(10).?.name);
+ try std.testing.expect(!r.functionAt(10).?.takes);
+ try std.testing.expect(r.functionAt(8) == null);
+ try std.testing.expectEqual(@as(u32, 7), r.functionAt(5).?.last);
+}
diff --git a/anim/src/array.zig b/anim/src/array.zig
new file mode 100644
index 0000000..5d6b471
--- /dev/null
+++ b/anim/src/array.zig
@@ -0,0 +1,189 @@
+//! An array as cells: a variable the recording describes as `T name[N]`,
+//! each element a cell with its index, the index variables that point into
+//! it as tags, the cells a step compared framed as read, and a value a
+//! step copied from one cell to another flying there on an arc, to land as
+//! a write (a swap is two flights, one over and one under, the second a
+//! little behind the first).
+//! This is the idea drawn from memory: it changes a beat after the bytes do.
+//! Reads `Moment.variables`, `Moment.read`, and the index of reads and writes.
+const std = @import("std");
+const sk = @import("sketch");
+const anim = @import("anim");
+const ui = @import("ui.zig");
+const cursors = @import("cursor.zig");
+const Recording = @import("Recording.zig");
+const objects = @import("objects.zig");
+const theme = ui.theme;
+const time = theme.time;
+const Rect = ui.Rect;
+const t = theme.color.text;
+const fl = time.flight;
+
+/// How long a value flies, by how far: duration follows distance.
+fn flightTime(units: f32) f32 {
+ return if (units <= 200) fl.near else if (units <= 400) fl.mid else fl.far;
+}
+
+pub const Array = struct {
+ cursor: cursors.Cursor,
+ box: Rect,
+ /// The array's name in the program.
+ variable: []const u8,
+ /// Variables that index it, shown as tags in the cell they point at.
+ indices: []const []const u8 = &.{},
+ focus: bool = false,
+
+ /// The timetable of a step that swaps two neighbouring cells (give it
+ /// to `Cursor.step`): the line fires, the first value lifts and
+ /// flies, the second a little behind it; each lands with a strike;
+ /// then the hold, and the mark moves on. 2.1 s.
+ pub const swap: cursors.Plan = blk: {
+ const lands = time.fire + fl.lift + fl.near;
+ const advance = lands + fl.second + time.read_value;
+ break :blk .{ .at = .{ time.cascade, time.cascade, lands }, .advance = advance, .travel = time.step, .total = advance + time.step + time.rest };
+ };
+
+ pub fn draw(g: *const Array, f: *sk.Frame, at: anim.Placed) void {
+ const u: ui.Ui = .{ .f = f, .at = at };
+ const now = g.cursor.now(at);
+ const rec = g.cursor.rec;
+ const moment = now.shown(.idea);
+ const v = rec.variable(f.scratch, moment, g.variable) orelse {
+ _ = u.panel(g.box.w, g.box.h, g.variable, .{ .focus = g.focus });
+ return;
+ };
+ const kind = rec.typeOf(f.scratch, v.type);
+ // Its declaration, and where it is: the address the context's pointers to it end in.
+ const body = u.panel(g.box.w, g.box.h, g.variable, .{ .focus = g.focus, .note = u.print("{s} at \u{2026}{x:0>4}", .{ objects.declare(f.scratch, rec, v), v.addr & 0xffff }) });
+ // An array of numbers; anything else is read as 4-byte ones.
+ const elem: u64 = if (kind != null and kind.? == .array) kind.?.array.elem.size() orelse 4 else 4;
+ const signed = kind == null or kind.? != .array or kind.?.array.elem.* != .scalar or kind.?.array.elem.scalar.kind == .int;
+ const count: usize = @intCast(@min(v.size / elem, 32));
+ if (count == 0) return;
+
+ const room = body.w - 2 * theme.metric.panel.pad_x;
+ const hero = @as(f32, @floatFromInt(count)) * theme.metric.hero_cell[0] <= room;
+ // Beside the context there is less room: the cells are as wide as fit.
+ const compact = !hero and @as(f32, @floatFromInt(count)) * theme.metric.cell[0] > room;
+ const cell: [2]f32 = if (hero) theme.metric.hero_cell else if (compact) .{ @floor(room / @as(f32, @floatFromInt(count))), theme.metric.cell[1] } else theme.metric.cell;
+ const size: f32 = if (hero) theme.size.mono.hero else if (compact) theme.size.mono.data else theme.size.mono.value;
+ const left = (body.w - @as(f32, @floatFromInt(count)) * cell[0]) / 2;
+ const top = body.y + (body.h - cell[1]) / 2 - @as(f32, if (compact) 30 else 0);
+ const walking = now.walking();
+
+ // What moved: a cell written with what another cell held, which this step read.
+ const Flight = struct { from: usize, to: usize };
+ var flights: std.ArrayList(Flight) = .empty;
+ const values = f.scratch.alloc(?i64, count) catch return;
+ const old = f.scratch.alloc(?i64, count) catch return;
+ for (values, old, 0..) |*value, *was, i| {
+ value.* = number(now.moment(), v.addr + i * elem, elem, signed);
+ was.* = number(now.before(), v.addr + i * elem, elem, signed);
+ }
+ if (now.plan.gait != .sprint and !now.resting()) for (0..count) |to| {
+ if (now.writeAge(v.addr + to * elem, elem) != 0 or values[to] == null) continue;
+ for (0..count) |from| {
+ if (from != to and old[from] == values[to] and now.wasRead(v.addr + from * elem, elem)) {
+ flights.append(f.scratch, .{ .from = from, .to = to }) catch {};
+ break;
+ }
+ }
+ };
+
+ for (0..count) |i| {
+ const r: Rect = .{ .x = left + @as(f32, @floatFromInt(i)) * cell[0], .y = top, .w = cell[0] - 2, .h = cell[1] };
+ const addr = v.addr + i * elem;
+ // The cell a value is flying to is struck when it lands: the second a little after the first.
+ const flown: ?usize = for (flights.items, 0..) |flight, k| {
+ if (flight.to == i) break k;
+ } else null;
+ const delay = if (flown) |k| @as(f32, @floatFromInt(k)) * fl.second else 0;
+ const pending = !now.landed(.idea, delay) and now.writeAge(addr, elem) == 0;
+ var heat = now.written(addr, elem, .idea, delay);
+ // The value on its way is the anticipation: no frame as well.
+ if (flown != null) heat.arm = 0;
+ const ink = u.written(r, heat, theme.color.raised);
+ // Staging: the compare is seen (framed as read) before anything moves.
+ if (now.wasRead(addr, elem) and now.writeAge(addr, elem) != 0) u.readMark(r, now.reading(.idea, 0));
+ u.text(.mono, if (compact) theme.size.mono.context else theme.size.mono.small, r.x + @as(f32, if (compact) 6 else 14), r.y + @as(f32, if (compact) 24 else 34), u.print("{d}", .{i}), if (ink.face == .mono_bold) ink.ink else ui.rgb(t.faint));
+ // Until its new value lands a cell keeps the old one, faint once
+ // the new is in the air: a copy does not erase.
+ const shown = if (pending) old[i] else values[i];
+ const digits: Rect = .{ .x = r.x, .y = r.y + 18, .w = r.w, .h = r.h - 18 };
+ const leaving = pending and flown != null and (!walking or now.since(.idea, delay) >= -(flightTime(cell[0]) + fl.lift));
+ if (shown) |n| u.label(ink.face, size, digits, .center, u.print("{d}", .{n}), if (leaving) ui.rgb(t.faint) else ink.ink) else u.unknown(digits);
+ }
+
+ // Index variables: tags that slide from cell to cell as the idea strikes.
+ for (g.indices, 0..) |name, nth| {
+ const iv = rec.variable(f.scratch, now.moment(), name) orelse continue;
+ const here = number(now.moment(), iv.addr, @min(iv.size, 8), true) orelse continue;
+ var x = left + (@as(f32, @floatFromInt(here)) + 1) * cell[0];
+ if (number(now.before(), iv.addr, @min(iv.size, 8), true)) |was| {
+ x = std.math.lerp(left + (@as(f32, @floatFromInt(was)) + 1) * cell[0], x, cursors.standard(now.moving(.idea, 0, time.move)));
+ }
+ if (here < 0 or here >= count) continue;
+ // Under the tags of the indices before it that are in the same cell.
+ var slot: f32 = 0;
+ for (g.indices[0..nth]) |other| {
+ const ov = rec.variable(f.scratch, moment, other) orelse continue;
+ if (number(moment, ov.addr, @min(ov.size, 8), true) == here) slot += 1;
+ }
+ const w = u.width(.mono_bold, theme.size.mono.small, name) + 16;
+ // In a narrow cell the tags hang under it, not in it.
+ const tag: Rect = if (compact) .{ .x = x - cell[0] / 2 - w / 2, .y = top + cell[1] + 8 + slot * 38, .w = w, .h = 34 } else .{ .x = x - 2 - 10 - w, .y = top + 10 + slot * 38, .w = w, .h = 34 };
+ u.fill(tag, t.ink);
+ u.label(.mono_bold, theme.size.mono.small, tag, .center, name, t.primary);
+ }
+
+ // Values in flight, over everything: one over, the next under.
+ for (flights.items, 0..) |flight, k| {
+ const from = ui.Vec{ left + (@as(f32, @floatFromInt(flight.from)) + 0.5) * cell[0], top + cell[1] / 2 + 9 };
+ const to = ui.Vec{ left + (@as(f32, @floatFromInt(flight.to)) + 0.5) * cell[0], top + cell[1] / 2 + 9 };
+ const far = @abs(to[0] - from[0]);
+ const seconds = flightTime(far);
+ // Seconds until it lands. Anticipation: it lifts out of its
+ // cell before it goes, and is back to size as it comes down.
+ const left_to_go = -now.since(.idea, @as(f32, @floatFromInt(k)) * fl.second);
+ if (left_to_go <= 0) continue;
+ var along: f32 = undefined;
+ var lifted: f32 = undefined;
+ if (walking) {
+ if (left_to_go > seconds + fl.lift) continue;
+ along = 1 - std.math.clamp(left_to_go / seconds, 0, 1);
+ lifted = @min(std.math.clamp((seconds + fl.lift - left_to_go) / fl.lift, 0, 1), std.math.clamp(left_to_go / fl.lift, 0, 1));
+ } else {
+ // At a run: the same arc, eased, in the step's first frames.
+ along = now.moving(.idea, 0, 0);
+ lifted = 0;
+ if (along >= 1) continue;
+ }
+ // Arcs: an idea moves on a curve, slow out of one cell and into the other, quickest over the top.
+ const eased = cursors.glide(along);
+ const rise = std.math.clamp(fl.arc * far, fl.arc_min, fl.arc_max) + cell[1] / 2;
+ const way: f32 = if (k % 2 == 0) -1 else 1;
+ const c = sk.math.mix(from, to, eased) + ui.Vec{ 0, way * rise * @sin(std.math.pi * eased) };
+ const grown = std.math.lerp(1, fl.lift_scale, lifted);
+ const w = (if (compact) cell[0] + 4 else @max(theme.metric.flight_card[0], cell[0] * 0.6)) * grown;
+ const h = (if (compact) theme.metric.flight_card[1] - 8 else theme.metric.flight_card[1]) * grown;
+ const card: Rect = .{ .x = c[0] - w / 2, .y = c[1] - h / 2, .w = w, .h = h };
+ u.fill(card, theme.color.page);
+ u.frame(card, t.bright, theme.stroke.line);
+ if (values[flight.to]) |n| u.label(.mono_bold, if (compact) theme.size.mono.value else theme.size.mono.flight, card, .center, u.print("{d}", .{n}), t.bright);
+ }
+ }
+};
+
+/// `bytes` at `addr` as a number, null where never recorded.
+fn number(moment: Recording.Moment, addr: u64, bytes: u64, signed: bool) ?i64 {
+ const n: usize = @intCast(@min(bytes, 8));
+ const raw = (Recording.word(moment, addr, n) catch return null) orelse return null;
+ if (!signed) return @bitCast(raw);
+ const shift: u6 = @intCast(64 - 8 * n);
+ return @as(i64, @bitCast(raw << shift)) >> shift;
+}
+
+test "a swap of neighbours is 2.1 seconds" {
+ try std.testing.expectApproxEqAbs(@as(f32, 2.1), Array.swap.total, 1e-3);
+ try std.testing.expect(flightTime(168) == fl.near and flightTime(336) == fl.mid and flightTime(900) == fl.far);
+}
diff --git a/anim/src/calls.zig b/anim/src/calls.zig
new file mode 100644
index 0000000..af0893d
--- /dev/null
+++ b/anim/src/calls.zig
@@ -0,0 +1,160 @@
+//! Calls as an idea, a lens on the stack: the tree of every call of one
+//! function, which grows as the program runs (the frames themselves are
+//! `context.Backtrace` and the stack's words). It reads the recording's
+//! index of calls and returns, with what each was given and gave back,
+//! and is the last level a step reaches: a node appears after the
+//! registers that carried its argument have struck.
+const std = @import("std");
+const sk = @import("sketch");
+const anim = @import("anim");
+const ui = @import("ui.zig");
+const cursors = @import("cursor.zig");
+const Cursor = cursors.Cursor;
+const Recording = @import("Recording.zig");
+const theme = ui.theme;
+const time = theme.time;
+const Rect = ui.Rect;
+const t = theme.color.text;
+
+/// A return's follow-through: its frame leaves the backtrace as the idea
+/// strikes, and the tree's badge is struck this long after.
+const badge_after = 0.20;
+
+pub const Tree = struct {
+ cursor: Cursor,
+ box: Rect,
+ /// The function whose calls are the tree.
+ function: []const u8,
+ focus: bool = false,
+
+ pub fn draw(k: *const Tree, f: *sk.Frame, at: anim.Placed) void {
+ const u: ui.Ui = .{ .f = f, .at = at };
+ const now = k.cursor.now(at);
+ const rec = k.cursor.rec;
+ const m = struct {
+ const radius = 18;
+ const level = 44;
+ const badge = 24;
+ };
+ const body = u.panel(k.box.w, k.box.h, u.print("calls of {s}", .{k.function}), .{ .focus = k.focus, .note = "each call a node \u{00b7} its result on the shoulder \u{00b7} the frames are the stack's" });
+ const nodes = layout(f.scratch, rec, k.function) catch return;
+ if (nodes.len == 0) return;
+ var leaves: f32 = 0;
+ for (nodes) |n| leaves = @max(leaves, n.x + 1);
+ const pitch = @min(4.5 * m.radius, (body.w - 2 * theme.metric.panel.pad_x - 2 * m.radius) / @max(leaves - 1, 1));
+ const left = (body.w - (leaves - 1) * pitch) / 2;
+ const top = body.y + m.radius + 12;
+ var deepest_level: f32 = 1;
+ for (nodes) |n| deepest_level = @max(deepest_level, @as(f32, @floatFromInt(n.level)));
+ const level_h = @min(m.level, (body.h - 2 * m.radius - 24) / deepest_level);
+ // A call: its edge draws from the caller's node, then the node
+ // fades in, gold, and the caller's goes from gold to a waiting
+ // ring. A return: the badge is struck a little after the card's
+ // result, and the node goes from gold to done.
+ const since = now.since(.idea, 0);
+ const returned = now.walking() and rec.depths[now.stops[0]] < rec.depths[now.stops[1]];
+ const moment = if (now.plan.gait == .sprint or since >= (if (returned) @as(f32, badge_after) else 0)) now.stops[0] else now.stops[1];
+ const edge = cursors.standard(now.moving(.idea, time.quick, time.quick));
+ const appears = now.moving(.idea, 0, time.snap);
+
+ // Edges under nodes: the waiting path in vellum.
+ for (nodes) |n| {
+ const parent = n.parent orelse continue;
+ if (n.call.enter > now.stops[0]) continue;
+ const from = ui.Vec{ left + nodes[parent].x * pitch, top + @as(f32, @floatFromInt(nodes[parent].level)) * level_h };
+ var to = ui.Vec{ left + n.x * pitch, top + @as(f32, @floatFromInt(n.level)) * level_h };
+ if (n.call.enter > now.stops[1]) to = sk.math.mix(from, to, edge);
+ const live = n.call.active(moment);
+ u.line(from, to, if (live or n.call.enter > moment) ui.rgb(t.primary) else ui.rgb(theme.color.rule), if (live or n.call.enter > moment) theme.stroke.arrow else theme.stroke.line);
+ }
+ const deepest = deepestActive(nodes, moment);
+ for (nodes, 0..) |n, i| {
+ if (n.call.enter > moment) continue;
+ const c = ui.Vec{ left + n.x * pitch, top + @as(f32, @floatFromInt(n.level)) * level_h };
+ const v = if (n.call.enter > now.stops[1]) u.faded(appears) else u;
+ if (deepest == i) {
+ v.disc(c, m.radius, ui.rgb(theme.mark(.current).solid), null, 0);
+ } else if (n.call.active(moment)) {
+ v.disc(c, m.radius - theme.stroke.arrow / 2, ui.rgb(theme.color.page), ui.rgb(t.primary), theme.stroke.arrow);
+ } else v.disc(c, m.radius, ui.rgb(theme.color.raised), null, 0);
+ }
+ // Then the words, so shapes and text each go in one run.
+ const size = theme.size.mono.context;
+ for (nodes, 0..) |n, i| {
+ if (n.call.enter > moment) continue;
+ const cx = left + n.x * pitch;
+ const cy = top + @as(f32, @floatFromInt(n.level)) * level_h;
+ const active = n.call.active(moment);
+ const words = if (n.call.arg) |arg| u.print("{d}", .{@as(i64, @bitCast(arg))}) else "?";
+ const cell: Rect = .{ .x = cx - m.radius, .y = cy - m.radius, .w = 2 * m.radius, .h = 2 * m.radius };
+ const v = if (n.call.enter > now.stops[1]) u.faded(appears) else u;
+ if (deepest == i) {
+ v.label(.mono_bold, size, cell, .center, words, theme.mark(.current).on_solid);
+ } else v.label(.mono, size, cell, .center, words, if (active) t.primary else t.dim);
+ if (active) continue;
+ // Done: what it returned, on its shoulder; struck as it lands.
+ const badge: Rect = .{ .x = cx + 10, .y = cy - m.radius - 12, .w = m.badge, .h = m.badge };
+ const heat: ui.Heat = if (n.call.exit.? > now.stops[1]) now.heat(0, null, since - badge_after) else .none;
+ const ink = u.written(badge, heat, theme.color.page);
+ if (heat.level < 1) u.frame(badge, t.faint, theme.stroke.rule);
+ u.label(ink.face, size, badge, .center, u.print("{d}", .{@as(i64, @bitCast(n.call.result))}), if (heat.level >= 1) ink.ink else ui.rgb(t.primary));
+ }
+ }
+};
+
+pub const Node = struct {
+ call: Recording.Call,
+ parent: ?usize,
+ level: u32,
+ /// In leaf slots: a leaf has a whole number, a parent sits over the
+ /// middle of its children.
+ x: f32,
+};
+
+fn deepestActive(nodes: []const Node, moment: u64) ?usize {
+ var best: ?usize = null;
+ for (nodes, 0..) |n, i| {
+ if (n.call.active(moment) and (best == null or n.level >= nodes[best.?].level)) best = i;
+ }
+ return best;
+}
+
+/// Every call of `function`, placed as a tidy tree of the whole run, so a
+/// node is where it will always be from the moment it appears.
+pub fn layout(arena: std.mem.Allocator, rec: *const Recording, function: []const u8) ![]Node {
+ var nodes: std.ArrayList(Node) = .empty;
+ // Calls come in the order they were made: a parent before its children.
+ var index: std.AutoHashMapUnmanaged(u32, usize) = .empty;
+ for (rec.calls, 0..) |call, i| {
+ if (!std.mem.eql(u8, rec.name(call.function), function)) continue;
+ const parent: ?usize = if (call.parent) |p| index.get(p) else null;
+ try index.put(arena, @intCast(i), nodes.items.len);
+ try nodes.append(arena, .{ .call = call, .parent = parent, .level = if (parent) |p| nodes.items[p].level + 1 else 0, .x = -1 });
+ }
+ // Leaves left to right in call order; then each parent over its children,
+ // deepest first (children come after their parent, so backwards).
+ const lo = try arena.alloc(f32, nodes.items.len);
+ const hi = try arena.alloc(f32, nodes.items.len);
+ @memset(lo, std.math.inf(f32));
+ @memset(hi, -std.math.inf(f32));
+ var next_leaf: f32 = 0;
+ for (nodes.items, 0..) |*n, i| {
+ const leaf = for (nodes.items[i + 1 ..]) |other| {
+ if (other.parent == i) break false;
+ } else true;
+ if (!leaf) continue;
+ n.x = next_leaf;
+ next_leaf += 1;
+ }
+ var i = nodes.items.len;
+ while (i > 0) {
+ i -= 1;
+ const n = &nodes.items[i];
+ if (n.x < 0) n.x = (lo[i] + hi[i]) / 2;
+ if (n.parent) |p| {
+ lo[p] = @min(lo[p], n.x);
+ hi[p] = @max(hi[p], n.x);
+ }
+ }
+ return nodes.items;
+}
diff --git a/anim/src/context.zig b/anim/src/context.zig
new file mode 100644
index 0000000..8d59112
--- /dev/null
+++ b/anim/src/context.zig
@@ -0,0 +1,485 @@
+//! The debugger's context, as pwndbg shows it, and always on screen: every
+//! register followed as far as it points (`Registers`), the top of the
+//! stack as a telescope (`Stack`), the call chain (`Backtrace`), and the
+//! instructions at the pc (`Disasm`). An address's ink is where it points;
+//! a chain reads "this, which points to that, which holds this"; code is
+//! named and strings are quoted. A scene's lens sits beside this; it never
+//! replaces it.
+//!
+//! Ink says what a thing is, paper what happened to it: a register written
+//! is armed (a thin frame), struck (solid behind the value, its digits
+//! bold in ink), and then keeps a tick at its left for three steps; a
+//! value read is framed. The pc's row is the current mark of the CPU's
+//! level: it moves on last, with the source's.
+//! Reads `Moment.regs`, `Moment.read`, the mappings (through
+//! `zt.telescope`), and the names and instructions the debugger recorded.
+const std = @import("std");
+const sk = @import("sketch");
+const anim = @import("anim");
+const zt = @import("ztrace");
+const ui = @import("ui.zig");
+const cursors = @import("cursor.zig");
+const Recording = @import("Recording.zig");
+const syscalls = @import("syscalls.zig");
+const ties = @import("ties.zig");
+const theme = ui.theme;
+const time = theme.time;
+const Rect = ui.Rect;
+const t = theme.color.text;
+const m = theme.metric.context;
+const size = theme.size.mono.context;
+const adv = size * 3 / 5;
+
+/// What an address into `region` is inked in.
+pub fn ink(region: zt.telescope.Region) u24 {
+ const c = theme.color.region;
+ return switch (region) {
+ .none => c.number,
+ .code, .rwx => c.code_,
+ .stack => c.stack,
+ .heap => c.heap,
+ .data => c.data,
+ .rodata => c.rodata,
+ };
+}
+
+pub fn regionOf(moment: Recording.Moment, value: u64) zt.telescope.Region {
+ return zt.telescope.region(moment, value) catch .none;
+}
+
+/// Where a mark goes behind a value drawn from `x` on the row at `y`.
+pub fn cell(x: f32, y: f32, moment: Recording.Moment, value: u64) Rect {
+ return .{ .x = x - 3, .y = y + 2, .w = ui.Value.of(value, regionOf(moment, value) != .none).width() + 6, .h = m.row - 4 };
+}
+
+/// `value` followed as far as it points at `moment`, along the row at `y`
+/// from `x`: an address in its region's ink; an arrow to what it points
+/// to; an arrow back before what the chain holds at its end (a number, by
+/// its class; a string, quoted); a code address's name after it. `first`
+/// is the ink of the first link while a strike is under it. A chain that
+/// runs out of row, or was still a pointer where the recording stopped
+/// following, ends in an arrow and dots: nothing is taken from its middle.
+pub fn chain(u: ui.Ui, x: f32, y: f32, moment: Recording.Moment, value: u64, max_x: f32, first: ?ui.Ink) void {
+ var links_buf: [6]zt.telescope.Link = undefined;
+ var text_buf: [48]u8 = undefined;
+ const links = zt.telescope.chase(moment, value, &links_buf, &text_buf) catch return;
+ const base = theme.baseline(y, m.row, size);
+ const mid = y + m.row / 2;
+ var at = x;
+ for (links, 0..) |link, i| {
+ const pointer = link.region != .none;
+ const w = ui.Value.of(link.value, pointer).width();
+ // Room for it, and for saying that there is more.
+ const more: f32 = if (i + 1 < links.len or link.text.len > 0) m.arrow_w + 3 * adv else 0;
+ if (i > 0 and at + m.arrow_w + w + more > max_x) return dots(u, at, mid, base);
+ if (i > 0) {
+ u.chainArrow(at, mid, !pointer);
+ at += m.arrow_w;
+ }
+ const end = u.value(at, base, link.value, pointer, if (i == 0 and first != null) first.? else .{ .ink = ui.rgb(ink(link.region)) });
+ // Writable and executable: worth a look of its own.
+ if (link.region == .rwx) u.fill(.{ .x = at, .y = base + 3, .w = w, .h = theme.stroke.rule }, ink(.rwx));
+ at = end;
+ if (link.text.len > 0) {
+ const fits: usize = @intFromFloat(@max((max_x - at - @as(f32, if (link.string) m.arrow_w else 10)) / adv, 0));
+ if (link.string) {
+ // What a pointer leads to, when it is text: quoted, cut to the room there is.
+ if (fits < m.string_min + 2) return;
+ u.chainArrow(at, mid, true);
+ const whole = link.text.len + 2 <= fits;
+ u.text(.mono, size, at + m.arrow_w, base, if (whole) u.print("\"{s}\"", .{link.text}) else u.print("\"{s}\u{2026}", .{link.text[0 .. fits - 2]}), theme.color.string);
+ } else if (fits >= 3) u.text(.mono, size, at + 10, base, u.print("{s}", .{link.text[0..@min(link.text.len, fits)]}), t.primary);
+ return;
+ }
+ // Still a pointer where the recording stopped following.
+ if (i + 1 == links.len and pointer and link.region != .code and link.region != .rwx and at + m.arrow_w + 3 * adv <= max_x) return dots(u, at, mid, base);
+ }
+}
+
+fn dots(u: ui.Ui, x: f32, mid: f32, base: f32) void {
+ u.chainArrow(x, mid, false);
+ u.text(.mono, size, x + m.arrow_w, base, "\u{2026}", t.faint);
+}
+
+fn veiled(u: ui.Ui, body: Rect, amount: f32) void {
+ // Staging: what cannot be read at a sprint is dimmed, not removed.
+ u.veil(.{ .x = theme.stroke.rule, .y = body.y, .w = body.w - 2 * theme.stroke.rule, .h = body.h - theme.stroke.rule }, amount);
+}
+
+pub const Registers = struct {
+ cursor: cursors.Cursor,
+ box: Rect = theme.layout.registers,
+ /// The rows, in order: none is hidden and they never reorder.
+ names: []const []const u8 = &theme.metric.all_registers,
+ /// A step that makes a system call frames, as read, the registers
+ /// that carry it, one at a time; and rax is struck when it returns.
+ syscalls: bool = false,
+ /// No strikes: for a program whose instrumentation uses the registers
+ /// between any two lines, so that nearly all of them change at every one.
+ quiet: bool = false,
+ focus: bool = false,
+
+ const Shown = struct { regs: zt.Regs, moment: Recording.Moment };
+
+ pub fn draw(r: *const Registers, f: *sk.Frame, at: anim.Placed) void {
+ const u: ui.Ui = .{ .f = f, .at = at };
+ const now = r.cursor.now(at);
+ const rec = r.cursor.rec;
+ var is: Shown = .{ .regs = (now.moment().regs(rec.tid) catch null) orelse zt.Regs{}, .moment = now.moment() };
+ var was: Shown = .{ .regs = (now.before().regs(rec.tid) catch null) orelse is.regs, .moment = now.before() };
+ if (r.syscalls) {
+ // The registers as the newest call crossed with them: the
+ // library's own use of them after it returns is not the story.
+ if (syscalls.latest(rec, now.stops[0])) |n| is = shownAt(rec, rec.syscalls[n].enter) orelse is;
+ if (syscalls.latest(rec, now.stops[1])) |n| was = shownAt(rec, rec.syscalls[n].enter) orelse was;
+ }
+ const body = u.panel(r.box.w, r.box.h, "registers", .{ .focus = r.focus, .legend = true });
+ // A link from a register leaves from the panel's edge, not through its name.
+ ties.anchor(u, .{ .register = 1 << 20 }, .{ .x = 0, .y = 0, .w = r.box.w, .h = r.box.h });
+ const room: usize = @intFromFloat(@floor((body.h - 2 * m.pad) / m.row));
+ // Overlapping action: of the registers one step wrote, each strikes a little after the one above it.
+ var struck: f32 = 0;
+ for (r.names[0..@min(r.names.len, room)], 0..) |reg, i| r.row(u, now, is, was, reg, body.y + m.pad + @as(f32, @floatFromInt(i)) * m.row, &struck);
+ veiled(u, body, now.veil);
+ }
+
+ fn shownAt(rec: *const Recording, i: u64) ?Shown {
+ const moment = rec.moment(i);
+ return .{ .regs = (moment.regs(rec.tid) catch return null) orelse return null, .moment = moment };
+ }
+
+ fn row(r: *const Registers, u: ui.Ui, now: cursors.Now, is: Shown, was: Shown, reg: []const u8, y: f32, struck: *f32) void {
+ const rec = r.cursor.rec;
+ const base = theme.baseline(y, m.row, size);
+ const max_x = r.box.w - m.side;
+ if (std.mem.eql(u8, reg, "rip")) {
+ // Never written: where execution is, a current mark like the
+ // source's and the disassembly's. It follows them: its value
+ // changes as the mark moves on, a few frames behind.
+ const current = theme.mark(.current);
+ u.fill(.{ .x = theme.stroke.rule, .y = y, .w = r.box.w - 2 * theme.stroke.rule, .h = m.row }, current.ember);
+ u.fill(.{ .x = theme.stroke.rule, .y = y, .w = m.name_w - 2, .h = m.row }, current.solid);
+ u.text(.mono_bold, size, m.side, base, reg, current.on_solid);
+ const at = now.marks[if (now.advancingAfter(2 * time.stagger) >= 0.5) 1 else 0];
+ return chain(u, m.chain_x, y, rec.moment(at), rec.register(at, "rip"), max_x, null);
+ }
+ u.text(.mono, size, m.side, base, reg, t.dim);
+ var landed = now.landed(.cpu, 0);
+ if (std.mem.eql(u8, reg, "flags")) {
+ // The value, then the eight names: a set flag upper case and
+ // bright on a chip, a clear one lower case and faint.
+ const flags = (if (landed) is else was).regs.eflags;
+ var x = u.value(m.chain_x + adv, base, flags, false, .{}) + 2 * adv;
+ inline for (.{ .{ "cf", "CF", 0 }, .{ "pf", "PF", 2 }, .{ "af", "AF", 4 }, .{ "zf", "ZF", 6 }, .{ "sf", "SF", 7 }, .{ "if", "IF", 9 }, .{ "df", "DF", 10 }, .{ "of", "OF", 11 } }) |flag| {
+ const set = flags >> flag[2] & 1 != 0;
+ if (set) u.fill(.{ .x = x - 3, .y = y + 2, .w = 2 * adv + 6, .h = m.row - 4 }, theme.color.raised);
+ u.text(if (set) .mono_bold else .mono, size, x, base, if (set) flag[1] else flag[0], if (set) t.bright else t.faint);
+ // Secondary action: the tick of one this step changed. It only fades.
+ if (!r.quiet and landed and set != (was.regs.eflags >> flag[2] & 1 != 0)) u.faded(now.since(.cpu, 0) / time.quick).fill(.{ .x = x - m.tick - 5, .y = y + 3, .w = m.tick, .h = m.row - 6 }, theme.mark(.write).solid);
+ x += 4 * adv;
+ }
+ return;
+ }
+ const index = for (zt.Regs.names, 0..) |known, i| {
+ if (std.mem.eql(u8, known, reg)) break i;
+ } else return;
+ const value_now = is.regs.named(reg) orelse return;
+ const value_was = was.regs.named(reg) orelse value_now;
+ var mark: ?ui.Ink = null;
+ if (if (r.syscalls) syscalls.inStep(now) else null) |made| {
+ const plan = syscalls.Plan.of(made);
+ const is_rax = std.mem.eql(u8, reg, "rax");
+ const carrier: ?usize = if (is_rax) 0 else for (syscalls.carried(made), 1..) |name, k| {
+ if (std.mem.eql(u8, name, reg)) break k;
+ } else null;
+ // What carries the call is framed as read, one register at a
+ // time: they are what crosses the line.
+ const framed = now.time - plan.registers - @as(f32, @floatFromInt(carrier orelse 0)) * time.flight.second;
+ const read = @min(std.math.clamp(framed / time.read.in, 0, 1), now.reading(.cpu, 0));
+ landed = framed >= 0;
+ if (is_rax) {
+ // rax: the call's number going in, the result coming back.
+ const back = now.time - plan.returns;
+ const result = back >= time.strike.in / 2.0;
+ const value: u64 = if (result) value_now else if (landed) made.nr else value_was;
+ const shown = if (result) is.moment else was.moment;
+ if (back < -time.strike.arm) u.readFrame(cell(m.chain_x, y, shown, value), read) else mark = u.struck(cell(m.chain_x, y, shown, value), now.heat(0, null, back));
+ return chain(u, m.chain_x, y, shown, value, max_x, mark);
+ }
+ if (carrier != null) u.readFrame(cell(m.chain_x, y, if (landed) is.moment else was.moment, if (landed) value_now else value_was), read);
+ } else if (r.quiet) {
+ // Unmarked: the values change as the mark moves on.
+ landed = now.advancing() >= 0.5;
+ } else {
+ const age = now.registerAge(index);
+ const delay = if (age == 0) @min(struck.* * time.stagger, time.stagger_max) else 0;
+ if (age == 0) struck.* += 1;
+ landed = now.landed(.cpu, delay);
+ mark = u.struck(cell(m.chain_x, y, if (landed) is.moment else was.moment, if (landed) value_now else value_was), now.register(index, delay));
+ }
+ ties.anchor(u, .{ .register = index }, cell(m.chain_x, y, if (landed) is.moment else was.moment, if (landed) value_now else value_was));
+ chain(u, m.chain_x, y, if (landed) is.moment else was.moment, if (landed) value_now else value_was, max_x, mark);
+ }
+};
+
+/// The top of the stack: eight words from the stack pointer up, low
+/// addresses on top, each followed as far as it points. In the lane at the
+/// left a register's plaque sits at the row it points at. The window is
+/// anchored at `rsp`: when a step moves it the rows slide (what persists
+/// slides), and the words that come into view are the new frame's.
+pub const Stack = struct {
+ cursor: cursors.Cursor,
+ box: Rect = theme.layout.stack,
+ focus: bool = false,
+
+ /// The lane: two plaques side by side.
+ const lane = 104;
+
+ pub fn draw(k: *const Stack, f: *sk.Frame, at: anim.Placed) void {
+ const u: ui.Ui = .{ .f = f, .at = at };
+ const now = k.cursor.now(at);
+ const rec = k.cursor.rec;
+ const body = u.panel(k.box.w, k.box.h, "stack", .{ .focus = k.focus, .note = "words from rsp \u{00b7} low addresses on top" });
+ const is = (now.moment().regs(rec.tid) catch null) orelse return;
+ const was = (now.before().regs(rec.tid) catch null) orelse is;
+ const calls = rec.stack(f.scratch, now.stop(.cpu));
+ // Rows it has moved by, still to slide: the stack pointer is the CPU's, and moves with it.
+ const p = cursors.glide(now.moving(.cpu, 0, time.move));
+ const moved = @as(f32, @floatFromInt(@as(i64, @bitCast(is.rsp -% was.rsp)))) / 8;
+ const slide: f32 = if (@abs(moved) > 16) 0 else moved * (1 - p);
+ const top = body.y + m.pad;
+ const room: i64 = @intFromFloat(@floor((body.h - 2 * m.pad) / m.row));
+ u.clip(.{ .x = theme.stroke.rule, .y = body.y + 2, .w = k.box.w - 2 * theme.stroke.rule, .h = body.h - 4 });
+ var n: i64 = @as(i64, @intFromFloat(@floor(-slide))) - 1;
+ while (n <= room - @as(i64, @intFromFloat(@floor(slide)))) : (n += 1) {
+ const y = top + (@as(f32, @floatFromInt(n)) + slide) * m.row;
+ if (y + m.row < body.y or y > body.y + body.h) continue;
+ const addr = is.rsp +% @as(u64, @bitCast(n * 8));
+ const base = theme.baseline(y, m.row, size);
+ const end = u.value(lane, base, addr, true, .{ .ink = ui.rgb(theme.color.region.stack) });
+ // The word there: memory, struck a beat after the registers.
+ const landed = now.landed(.memory, 0);
+ const moment = if (landed) now.moment() else now.before();
+ const held = (Recording.word(moment, addr, 8) catch null) orelse {
+ u.unknown(.{ .x = end + m.arrow_w, .y = y, .w = 3 * adv, .h = m.row });
+ continue;
+ };
+ const value_x = end + m.arrow_w;
+ ties.anchor(u, .{ .word = addr }, .{ .x = Stack.lane - 4, .y = y + 1, .w = k.box.w - Stack.lane - 4, .h = m.row - 2 });
+ const mark = u.struck(cell(value_x, y, moment, held), now.written(addr, 8, .memory, 0));
+ if (now.wasRead(addr, 8) and now.writeAge(addr, 8) != 0) u.readFrame(cell(value_x, y, moment, held), now.reading(.memory, 0));
+ // What the frame pointer says a word is, at the row's end.
+ var note: []const u8 = "";
+ for (calls) |call| {
+ if (call.sp == addr) note = "return address";
+ if (call.sp == addr +% 8 and addr == (if (now.landed(.cpu, 0)) is else was).rbp) note = u.print("{s}'s saved rbp", .{rec.name(call.function)});
+ }
+ const note_w = u.width(.sans, theme.size.sans.micro, note);
+ u.text(.sans, theme.size.sans.micro, k.box.w - m.side - note_w, base, note, t.faint);
+ u.chainArrow(end, y + m.row / 2, regionOf(moment, held) == .none);
+ chain(u, value_x, y, moment, held, k.box.w - m.side - (if (note.len > 0) note_w + 12 else 0), mark);
+ }
+ // The lane: who points at a row. A plaque slides to the row its
+ // register now points at, as the register is struck.
+ inline for (.{ "rsp", "rbp" }, 0..) |reg, i| {
+ const rows = [2]f32{
+ @as(f32, @floatFromInt(@as(i64, @bitCast(@field(was, reg) -% was.rsp)))) / 8,
+ @as(f32, @floatFromInt(@as(i64, @bitCast(@field(is, reg) -% is.rsp)))) / 8,
+ };
+ const visible = [2]bool{ rows[0] >= 0 and rows[0] < @as(f32, @floatFromInt(room)), rows[1] >= 0 and rows[1] < @as(f32, @floatFromInt(room)) };
+ if (visible[0] or visible[1]) {
+ const at_row = if (visible[0] and visible[1]) std.math.lerp(rows[0], rows[1], p) else if (visible[1]) rows[1] else rows[0];
+ const v = if (!visible[0]) u.faded(p) else if (!visible[1]) u.faded(1 - p) else u;
+ const plaque: Rect = .{ .x = 8 + @as(f32, @floatFromInt(i)) * 46, .y = top + at_row * m.row + 2, .w = 44, .h = m.row - 4 };
+ v.fill(plaque, theme.color.page);
+ v.frame(plaque, t.primary, theme.stroke.rule);
+ v.label(.mono, size, plaque, .center, reg, t.primary);
+ }
+ }
+ u.unclip();
+ veiled(u, body, now.veil);
+ }
+};
+
+/// The call chain, a row a frame, newest on top, walked by frame pointer
+/// from what the debugger recorded: `#0` on a gold plaque, the function
+/// and the offset in it, and for the program's own frame the file and
+/// line. Three rows; a deeper chain is counted in the tag. It is the idea
+/// of the stack, and changes last: a call's row arrives after the others
+/// have made room; a return's leaves, and then they close up.
+pub const Backtrace = struct {
+ cursor: cursors.Cursor,
+ box: Rect = theme.layout.backtrace,
+ focus: bool = false,
+
+ pub fn draw(b: *const Backtrace, f: *sk.Frame, at: anim.Placed) void {
+ const u: ui.Ui = .{ .f = f, .at = at };
+ const now = b.cursor.now(at);
+ const rec = b.cursor.rec;
+ var buf: [2][24]u64 = undefined;
+ const before = b.frames(now.stops[1], &buf[0]);
+ const after = b.frames(now.stops[0], &buf[1]);
+ const deep = if (now.landed(.idea, 0)) after.len else before.len;
+ const body = u.panel(b.box.w, b.box.h, "backtrace", .{ .focus = b.focus, .note = if (deep > 3) u.print("newest on top \u{00b7} {d} frames", .{deep}) else "newest on top" });
+ const top = body.y + m.pad;
+ const room: f32 = @floor((body.h - 2 * m.pad) / m.row);
+ u.clip(.{ .x = theme.stroke.rule, .y = body.y + 2, .w = b.box.w - 2 * theme.stroke.rule, .h = body.h - 4 });
+ defer u.unclip();
+ // A call: the rows make room, then the new one fades in. A return:
+ // its row fades out, then the rest close up.
+ const called = after.len > before.len;
+ const d: f32 = @floatFromInt(@max(after.len, before.len) - @min(after.len, before.len));
+ const makes_room = cursors.standard(now.moving(.idea, time.quick, time.cascade));
+ const arrives = now.moving(.idea, time.snap, time.quick);
+ const closes = cursors.standard(std.math.clamp(now.moving(.idea, -time.quick, time.cascade), 0, 1));
+ const shown = if (called or now.moving(.idea, 0, time.quick) >= 1) after else before;
+ const leaving = !called and shown.ptr == before.ptr;
+ const current = theme.mark(.current);
+ for (shown, 0..) |pc, i| {
+ const new = called and @as(f32, @floatFromInt(i)) < d;
+ const gone = leaving and @as(f32, @floatFromInt(i)) < d;
+ // Where it is: among the frames after the step, or (a row on its way out) before it.
+ const place = if (called) @as(f32, @floatFromInt(i)) - (1 - makes_room) * d else if (leaving) @as(f32, @floatFromInt(i)) else @as(f32, @floatFromInt(i)) + (1 - closes) * d;
+ if (place >= room or (new and arrives <= 0)) continue;
+ const y = top + @max(place, if (new) @as(f32, @floatFromInt(i)) else place) * m.row;
+ const v = if (new) u.faded(arrives) else if (gone) u.faded(1 - now.moving(.idea, 0, time.quick)) else u;
+ const base = theme.baseline(y, m.row, size);
+ // Gold is the newest frame's, once it has arrived.
+ const newest = if (called and arrives < 1) @as(f32, @floatFromInt(i)) == d else i == 0;
+ if (newest) {
+ v.fill(.{ .x = theme.stroke.rule, .y = y, .w = b.box.w - 2 * theme.stroke.rule, .h = m.row }, current.ember);
+ v.fill(.{ .x = theme.stroke.rule, .y = y, .w = 44, .h = m.row }, current.solid);
+ }
+ v.text(if (newest) .mono_bold else .mono, size, m.side, base, u.print("#{d}", .{i}), if (newest) current.on_solid else t.faint);
+ const name = rec.strings.get(pc) orelse u.print("{x}", .{pc});
+ v.text(.mono, size, m.side + 4 * adv, base, name[0..@min(name.len, 22)], t.primary);
+ // The program's own frame says where in its source it is.
+ if (i == 0) v.text(.mono, size, m.side + 22 * adv, base, u.print("{s}:{d}", .{ rec.file, rec.own[now.marked()] }), t.dim);
+ }
+ veiled(u, body, now.veil);
+ }
+
+ /// The pcs of the call chain at moment `i`: the pc, then each return address outwards.
+ fn frames(b: *const Backtrace, i: u64, out: []u64) []const u64 {
+ const rec = b.cursor.rec;
+ const moment = rec.moment(i);
+ const regs = (moment.regs(rec.tid) catch return &.{}) orelse return &.{};
+ return zt.telescope.backtrace(moment, &regs, out) catch &.{};
+ }
+};
+
+/// The instructions round the pc, as the debugger disassembled them, in
+/// address order: as many above it as under it. The pc's row is the current mark of the CPU's level and stays
+/// where it is: when execution moves on to an instruction in view the
+/// rows slide up under it; when it goes elsewhere they give way to the
+/// rows there.
+pub const Disasm = struct {
+ cursor: cursors.Cursor,
+ box: Rect,
+ focus: bool = false,
+
+ const Line = struct { addr: u64, text: []const u8 };
+
+ pub fn draw(d: *const Disasm, f: *sk.Frame, at: anim.Placed) void {
+ const u: ui.Ui = .{ .f = f, .at = at };
+ const now = d.cursor.now(at);
+ const rec = d.cursor.rec;
+ // It follows the source's mark, a stagger behind.
+ const going = now.advancingAfter(time.stagger);
+ const pc = [2]u64{ rec.register(now.marks[0], "rip"), rec.register(now.marks[1], "rip") };
+ // Where it is: the function's name, in the tag.
+ const name = rec.strings.get(pc[if (going >= 0.5) 1 else 0]) orelse "";
+ const body = u.panel(d.box.w, d.box.h, "disassembly", .{ .focus = d.focus, .note = name[0 .. std.mem.indexOfScalar(u8, name, '+') orelse name.len] });
+ const room: usize = @intFromFloat(@floor((body.h - 2 * m.pad) / m.row));
+ // As many rows above the pc as under it: what just ran, and what is to come.
+ const trail = (room -| 1) / 2;
+ const from = d.listing(u, now.marks[0], room, trail);
+ const to = d.listing(u, now.marks[1], room, trail);
+ // The instruction it goes to is in view under the pc: the rows slide up to it.
+ const ahead: usize = for (from[@min(trail, from.len)..], 0..) |line, i| {
+ if (i > 0 and line.addr == pc[1]) break i;
+ } else 0;
+ const top = body.y + m.pad;
+ const current = theme.mark(.current);
+ const out = now.fires(.disasm);
+ const mark_y = top + @as(f32, @floatFromInt(trail)) * m.row;
+ u.fill(.{ .x = theme.stroke.rule, .y = mark_y, .w = d.box.w - 2 * theme.stroke.rule, .h = m.row }, current.ember);
+ u.clip(.{ .x = theme.stroke.rule, .y = body.y + 2, .w = d.box.w - 2 * theme.stroke.rule, .h = body.h - 4 });
+ if (ahead > 0) {
+ d.rows(u, to, top + (1 - cursors.standard(going)) * @as(f32, @floatFromInt(ahead)) * m.row, pc[1], going >= 0.5);
+ } else if (pc[0] == pc[1] or going >= 1) {
+ d.rows(u, to, top, pc[1], true);
+ } else {
+ // Elsewhere: what leaves has left before what replaces it arrives.
+ d.rows(u.faded(@abs(2 * going - 1)), if (going >= 0.5) to else from, top, pc[if (going >= 0.5) 1 else 0], true);
+ }
+ u.unclip();
+ // The marker, on its plaque: the one thing here that does not move.
+ u.fill(.{ .x = theme.stroke.rule - out, .y = mark_y - out, .w = 26 + 2 * out, .h = m.row + 2 * out }, current.solid);
+ sk.draw.polygon(u.f, &.{ .{ 10, mark_y + 6 }, .{ 20, mark_y + m.row / 2 }, .{ 10, mark_y + m.row - 6 } }, u.at.pen(.{ .fill = ui.rgb(current.on_solid) }));
+ ties.anchor(u, .pc, .{ .x = 0, .y = mark_y, .w = 26, .h = m.row });
+ veiled(u, body, now.veil);
+ }
+
+ fn rows(d: *const Disasm, u: ui.Ui, lines: []const Line, top: f32, pc: u64, lit: bool) void {
+ const rec = d.cursor.rec;
+ // An offset in its function, to match rip and the backtrace: the pc's, and from it the others'.
+ const name = rec.strings.get(pc) orelse "";
+ const plus = std.mem.lastIndexOfScalar(u8, name, '+');
+ const pc_offset: ?i64 = if (plus) |at| std.fmt.parseInt(i64, name[at + 1 ..], 10) catch null else null;
+ for (lines, 0..) |line, i| {
+ if (line.text.len == 0) continue;
+ const y = top + @as(f32, @floatFromInt(i)) * m.row;
+ const base = theme.baseline(y, m.row, size);
+ const on = lit and line.addr == pc;
+ const end = u.value(34, base, line.addr, true, .{ .ink = ui.rgb(theme.color.region.code_) });
+ if (pc_offset) |offset| {
+ const here = offset + @as(i64, @bitCast(line.addr -% pc));
+ if (here >= 0) u.text(.mono, size, end + adv, base, u.print("+{d}", .{here}), t.faint);
+ }
+ // The mnemonic, as a keyword; then what it works on.
+ const space = std.mem.indexOfScalar(u8, line.text, ' ') orelse line.text.len;
+ // After a twelve-digit address and its offset.
+ const text_x = 34 + 18 * adv;
+ const fits: usize = @intFromFloat(@max((d.box.w - m.side - text_x) / adv, 0));
+ u.text(.mono_bold, size, text_x, base, line.text[0..@min(space, fits)], if (on) t.bright else theme.color.code.keyword);
+ if (space < @min(line.text.len, fits)) u.text(.mono, size, text_x + @max(@as(f32, @floatFromInt(space)), 5) * adv, base, line.text[space..@min(line.text.len, fits)], if (on) t.bright else theme.color.code.plain);
+ }
+ }
+
+ /// The rows at moment `i`, in address order as pwndbg lists them: up
+ /// to `trail` instructions above the pc (each as long as the recording
+ /// says the one before is), the one at the pc, and those after it.
+ /// Rows above that the recording does not know are left empty: the
+ /// pc's row keeps its place.
+ fn listing(d: *const Disasm, u: ui.Ui, i: u64, room: usize, trail: usize) []const Line {
+ const rec = d.cursor.rec;
+ const lines = u.f.scratch.alloc(Line, @max(room, trail + 1)) catch return &.{};
+ const pc = rec.register(i, "rip");
+ var buf: [96]u8 = undefined;
+ var n = trail;
+ var addr = pc;
+ @memset(lines[0..trail], .{ .addr = 0, .text = "" });
+ while (n > 0) {
+ const here = rec.instruction(i, addr, &buf) orelse break;
+ if (here.back == 0) break;
+ addr -= here.back;
+ const above = rec.instruction(i, addr, &buf) orelse break;
+ n -= 1;
+ lines[n] = .{ .addr = addr, .text = u.print("{s}", .{above.text}) };
+ }
+ n = trail;
+ addr = pc;
+ while (n < lines.len) : (n += 1) {
+ const one = rec.instruction(i, addr, &buf) orelse break;
+ lines[n] = .{ .addr = addr, .text = u.print("{s}", .{one.text}) };
+ addr += one.len;
+ }
+ return lines[0..n];
+ }
+};
+
+test "a mark goes behind a value's digits" {
+ try std.testing.expectEqual(@as(f32, 12 * adv), ui.Value.of(0x7fffffffd8c0, true).width());
+ try std.testing.expectEqual(@as(f32, adv), ui.Value.of(5, false).width());
+}
diff --git a/anim/src/cursor.zig b/anim/src/cursor.zig
new file mode 100644
index 0000000..2ca8a97
--- /dev/null
+++ b/anim/src/cursor.zig
@@ -0,0 +1,638 @@
+//! The cursor: where in the recording the picture is, as numbers on the
+//! scene's timeline. It moves in steps, each from one moment straight to a
+//! later one (the next instruction, the next source line, the line after a
+//! call returns, the next syscall: `Recording.Stop`), and remembers the
+//! last few places it stopped.
+//!
+//! A step is a sentence (design/motion.md): the line about to run fires;
+//! what it did lands a level at a time, the CPU, then memory, then the idea
+//! drawn from them, each armed and then struck; it is held to be read; and
+//! last the current mark moves on. The cursor writes that timetable (a
+//! `Plan`) for each step from what the step changed, so a walk has the
+//! program's rhythm and not a clock's, and every component reads it
+//! (`Cursor.now`) with no state of its own.
+const std = @import("std");
+const anim = @import("anim");
+const zt = @import("ztrace");
+const Recording = @import("Recording.zig");
+const ui = @import("ui.zig");
+const theme = ui.theme;
+const time = theme.time;
+
+/// A mark lasts this many steps, then one more to leave in.
+const history = time.strike.ember_steps + 2;
+
+/// Slow in and slow out, for things with weight: a value in flight, a
+/// layout, a colour cooling. Quickest at the middle.
+pub fn glide(t: f32) f32 {
+ return theme.ease(.glide, t);
+}
+
+/// For things that answer the program (the mark, cards, tags, an arrow
+/// growing): off promptly, a long settle.
+pub fn standard(t: f32) f32 {
+ return theme.ease(.standard, t);
+}
+
+/// The levels a step's effects land on, in the order they are caused.
+pub const Level = enum(u2) { cpu, memory, idea };
+
+/// What is on screen for the cursor to time a step by. A level the scene
+/// does not show gives up its place in the cascade.
+pub const Levels = struct {
+ cpu: bool = true,
+ memory: bool = true,
+ /// The idea drawn from them, when one is shown: the calls (cards, a
+ /// tree), or the data (nodes, an array's cells).
+ idea: enum { none, calls, data } = .none,
+ /// Follow-through: seconds the data's view goes on moving after its
+ /// strike (an arrow redrawn, a tag sliding), before the hold begins.
+ follow: f32 = 0,
+ /// Where a step fires: on the source line, or (a scene that steps by
+ /// instruction) on the pc's row of the disassembly. One place: two
+ /// views of the same thing start together, and only one of them pulses.
+ fire: enum { source, disasm } = .source,
+ /// How many lines the source panel shows (the split's): a step that
+ /// takes the program out of its window has the window's glide to wait for.
+ source_rows: u32 = 12,
+};
+
+/// How a step is drawn. Walk: everything, as a sentence. Run: the mark and
+/// structures eased, values as embers. Sprint: structures grow, embers.
+pub const Gait = enum(u2) { walk, run, sprint };
+
+/// A step's timetable, in seconds from its first frame.
+pub const Plan = struct {
+ gait: Gait = .walk,
+ /// When each level strikes (`Level` is the index).
+ at: [3]f32 = @splat(time.cascade),
+ /// When the mark sets off for the next line, and how long it takes.
+ advance: f32 = time.fire,
+ travel: f32 = time.step,
+ /// The whole step: the advance, then a rest in which the next line is read.
+ total: f32 = time.fire + time.step + time.rest,
+
+ /// Once the pattern is known: the levels a stagger apart from the
+ /// first frame, the mark after them, in `seconds`.
+ pub fn running(seconds: f32) Plan {
+ return .{ .gait = .run, .at = .{ 0, time.stagger, 2 * time.stagger }, .advance = time.run_ease, .travel = time.run_ease, .total = seconds };
+ }
+
+ pub fn sprinting(seconds: f32) Plan {
+ return .{ .gait = .sprint, .at = @splat(0), .advance = 0, .travel = 0, .total = seconds };
+ }
+};
+
+/// Registers whose change is no value to read: where execution is, and the flags.
+const quiet: u32 = blk: {
+ var mask: u32 = 0;
+ for (zt.Regs.names, 0..) |name, i| {
+ if (std.mem.eql(u8, name, "rip") or std.mem.eql(u8, name, "eflags")) mask |= 1 << i;
+ }
+ break :blk mask;
+};
+
+pub const Cursor = struct {
+ rec: *Recording,
+ /// Where it is (or is arriving), where it came from, and before that.
+ stops: [history]anim.Value,
+ /// 0 to 1 through the step it is taking; 1 at rest.
+ phase: anim.Value,
+ /// The step's `Plan`, a value a field.
+ plan: [7]anim.Value,
+ /// The moment the current mark was on, and the one it is on (or going to).
+ marks: [2]anim.Value,
+ /// 1 while steps are hurried (the head counts them), and while what
+ /// cannot be read at that pace is veiled.
+ hurried: anim.Value,
+ veil: anim.Value,
+ /// Steps taken.
+ count: anim.Value,
+ /// The levels the scene shows: set before the first step.
+ levels: Levels = .{},
+ /// The scene's whole way, for the head's progress line and counter (`journey`).
+ first: u64,
+ last: u64,
+ of: u32 = 0,
+
+ /// A cursor at rest at moment `start`.
+ pub fn init(s: *anim.Frame, rec: *Recording, start: u64) Cursor {
+ const here: f32 = @floatFromInt(start);
+ const plan: Plan = .{};
+ var c: Cursor = .{
+ .rec = rec,
+ .stops = undefined,
+ .phase = s.value(1),
+ .plan = .{ s.value(0), s.value(plan.at[0]), s.value(plan.at[1]), s.value(plan.at[2]), s.value(plan.advance), s.value(plan.travel), s.value(plan.total) },
+ .marks = .{ s.value(here), s.value(here) },
+ .hurried = s.value(0),
+ .veil = s.value(0),
+ .count = s.value(0),
+ .first = start,
+ .last = start,
+ };
+ // shortcut: an f32 holds whole moments up to 16 million; a longer recording needs two values a stop.
+ for (&c.stops) |*stop| stop.* = s.value(here);
+ return c;
+ }
+
+ /// Where the timeline has taken the cursor so far: for scene code that
+ /// finds the next place from the last.
+ pub fn moment(c: Cursor, s: *const anim.Frame) u64 {
+ return @intFromFloat(settled(s, c.stops[0]));
+ }
+
+ /// Tells the cursor how far the scene will take it, in steps of `by`:
+ /// what the head's progress line and step counter are measured against.
+ pub fn journey(c: *Cursor, by: Recording.Stop, until: u64) void {
+ c.last = until;
+ c.of = c.steps(by, c.first, until);
+ }
+
+ /// How many steps of `by` from `from` to `until`.
+ pub fn steps(c: Cursor, by: Recording.Stop, from: u64, until: u64) u32 {
+ var n: u32 = 0;
+ var here = from;
+ while (here < until) : (n += 1) here = @min(c.rec.next(by, here), until);
+ return n;
+ }
+
+ /// One step, straight to moment `to`, drawn as `plan` says and played
+ /// in `seconds` (a plan played in less than its `total` is the same
+ /// sentence said faster).
+ pub fn step(c: Cursor, s: *anim.Frame, to: u64, plan: Plan, seconds: f32) void {
+ const from = c.moment(s);
+ var set: [history + 11]anim.Animation = undefined;
+ for (1..history) |i| set[i] = c.stops[i].to(settled(s, c.stops[i - 1]));
+ set[0] = c.stops[0].to(@floatFromInt(to));
+ for (c.plan, [_]f32{ @floatFromInt(@intFromEnum(plan.gait)), plan.at[0], plan.at[1], plan.at[2], plan.advance, plan.travel, plan.total }, history..) |value, is, n| set[n] = value.to(is);
+ // At a sprint the mark is seen only where a phrase ends.
+ const was = settled(s, c.marks[1]);
+ set[history + 7] = c.marks[0].to(was);
+ set[history + 8] = c.marks[1].to(if (plan.gait == .sprint and !c.phraseEnds(from, to)) was else @floatFromInt(to));
+ set[history + 9] = c.phase.to(0);
+ set[history + 10] = c.count.to(settled(s, c.count) + 1);
+ s.play(set, .{ .seconds = 0 });
+ s.play(.{c.phase.to(1)}, .{ .seconds = seconds, .ease = anim.ease.linear });
+ }
+
+ /// Steps of `by` up to moment `until`, each shown in full and as long
+ /// as what it changed takes to read (`reading`), with a beat's rest
+ /// where a phrase ends. For the first time anything happens, and
+ /// whatever the narration names.
+ pub fn walk(c: Cursor, s: *anim.Frame, by: Recording.Stop, until: u64) void {
+ var here = c.moment(s);
+ while (here < until) {
+ const next = @min(c.rec.next(by, here), until);
+ const plan = c.reading(here, next);
+ c.step(s, next, plan, plan.total);
+ if (c.phraseEnds(here, next)) s.wait(time.phrase_rest);
+ here = next;
+ }
+ }
+
+ /// Timing: the timetable a walked step from `from` to `to` deserves.
+ /// Fire; a slot of the cascade for each level it touched; the idea's
+ /// follow-through; a hold as long as the values take to read; the
+ /// advance; a rest. A line and no more comes to 0.8 s, one value to
+ /// 1.5, a register and memory to 2.0, a call through three levels 2.5.
+ pub fn reading(c: Cursor, from: u64, to: u64) Plan {
+ const rec = c.rec;
+ const regs: f32 = @floatFromInt(@popCount(rec.registersChanged(from, to) & ~quiet));
+ const wrote: f32 = @floatFromInt(rec.written(from, to).len);
+ const touched = wrote > 0 or rec.read(from, to).len > 0;
+ const deeper = rec.depths[to] > rec.depths[from];
+ const back = rec.depths[to] < rec.depths[from];
+ const levels = [3]bool{
+ c.levels.cpu and regs > 0,
+ c.levels.memory and touched,
+ switch (c.levels.idea) {
+ .none => false,
+ .calls => deeper or back,
+ .data => touched,
+ },
+ };
+ var plan: Plan = .{ .travel = c.travel(from, to) };
+ var slot: f32 = 0;
+ for (levels, &plan.at) |is, *strikes| {
+ if (is) slot += time.cascade;
+ strikes.* = @max(slot, time.cascade);
+ }
+ if (slot > 0) {
+ // What there is to read: a level's worth each. (In the whole
+ // context a line changes more registers than anyone reads;
+ // the hold is for the one the scene is about.)
+ var values: f32 = 0;
+ for (levels) |is| values += @floatFromInt(@intFromBool(is));
+ // A card leaves after its result is read; an arrow lands after its word strikes.
+ const follow: f32 = if (!levels[2]) 0 else switch (c.levels.idea) {
+ .none => 0,
+ .calls => if (back) time.returning else time.snap,
+ .data => c.levels.follow,
+ };
+ plan.advance = slot + follow + @min(time.read_value + time.read_more * (values - 1), time.read_most);
+ }
+ plan.total = plan.advance + plan.travel + time.rest;
+ return plan;
+ }
+
+ /// How long the mark takes to the next line: a slide by how far, or a
+ /// jump (out, then in) into or out of a call, or further than a few rows.
+ fn travel(c: Cursor, from: u64, to: u64) f32 {
+ const rec = c.rec;
+ // The source's window moves with it: by whole lines, and never a cut.
+ if (rec.viewFirst(c.levels.source_rows, rec.own[from]) != rec.viewFirst(c.levels.source_rows, rec.own[to])) return time.move;
+ if (jumps(rec, from, to)) return 2 * time.current_jump;
+ const rows: f32 = @floatFromInt(@max(rec.own[from], rec.own[to]) - @min(rec.own[from], rec.own[to]));
+ return @min(time.step + time.step_per_row * @max(rows - 1, 0), time.step_max);
+ }
+
+ /// A phrase ends where a call returns, or a loop comes round again.
+ pub fn phraseEnds(c: Cursor, from: u64, to: u64) bool {
+ const rec = c.rec;
+ return rec.depths[to] < rec.depths[from] or (rec.depths[to] == rec.depths[from] and rec.own[to] < rec.own[from]);
+ }
+
+ pub const Hurry = struct {
+ /// Seconds a step, once up to speed: `time.run`, or `time.sprint`.
+ pace: f32 = time.run,
+ /// What the pace was before, and is to be after.
+ from: f32 = time.walk,
+ to: f32 = time.walk,
+ /// Veil what cannot be read at that pace (null: at a sprint).
+ veil: ?bool = null,
+ /// Lift the veil and rest a beat afterwards: not when another
+ /// stretch at another pace follows at once.
+ settle: bool = true,
+ };
+
+ /// Pacing: steps of `by` up to `until`, hurried, for a pattern already
+ /// seen in full. A change of pace is never a switch: each step is
+ /// `time.ramp` of the one before on the way down from `from`, and on
+ /// the way back up to `to`, and then the picture is still for a beat.
+ /// A step with time enough is still a whole sentence, said faster;
+ /// shorter, it is a run (the mark and structures eased, values as
+ /// embers), with a short rest where a phrase ends; shorter still, a
+ /// sprint. The head counts the steps while it lasts.
+ pub fn hurry(c: Cursor, s: *anim.Frame, by: Recording.Stop, until: u64, options: Hurry) void {
+ var here = c.moment(s);
+ const n: f32 = @floatFromInt(c.steps(by, here, until));
+ if (n == 0) return;
+ // Anticipation: the veil and the counter come with the first shortened step.
+ const veiled = options.veil orelse (options.pace < time.run);
+ const start = s.cursor;
+ s.play(.{ c.hurried.to(1), c.veil.to(if (veiled) 1 else 0) }, .{ .seconds = time.veil, .ease = anim.ease.linear });
+ s.cursor = start;
+ var k: f32 = 0;
+ while (here < until) : (k += 1) {
+ const next = @min(c.rec.next(by, here), until);
+ const natural = c.reading(here, next);
+ const down = options.from * std.math.pow(f32, time.ramp, k + 1);
+ const up = options.to * std.math.pow(f32, time.ramp, n - k);
+ // Whole frames, at 30 a second as at 60.
+ const seconds = @round(@min(natural.total, @max(options.pace, @min(down, up))) * 30) / 30;
+ const plan: Plan = if (seconds >= time.walk_least) natural else if (seconds > 1.5 * time.sprint) .running(seconds) else .sprinting(seconds);
+ c.step(s, next, plan, seconds);
+ if (plan.gait != .sprint and c.phraseEnds(here, next)) s.wait(time.phrase_rest_running);
+ here = next;
+ }
+ if (!options.settle) return;
+ s.play(.{ c.hurried.to(0), c.veil.to(0) }, .{ .seconds = time.veil, .ease = anim.ease.linear });
+ s.wait(time.beat);
+ }
+
+ /// There at once, with nothing struck: a cut.
+ pub fn jump(c: Cursor, s: *anim.Frame, to: u64) void {
+ var all: [history + 3]anim.Animation = undefined;
+ for (c.stops, 0..) |stop_value, i| all[i] = stop_value.to(@floatFromInt(to));
+ all[history] = c.phase.to(1);
+ all[history + 1] = c.marks[0].to(@floatFromInt(to));
+ all[history + 2] = c.marks[1].to(@floatFromInt(to));
+ s.play(all, .{ .seconds = 0 });
+ }
+
+ /// For a component, while it draws.
+ pub fn now(c: Cursor, placed: anim.Placed) Now {
+ const rec = c.rec;
+ var n: Now = .{
+ .rec = rec,
+ .stops = undefined,
+ .time = std.math.inf(f32),
+ .plan = .{
+ .gait = @enumFromInt(@as(u2, @intFromFloat(std.math.clamp(@round(placed.value(c.plan[0])), 0, 2)))),
+ .at = .{ placed.value(c.plan[1]), placed.value(c.plan[2]), placed.value(c.plan[3]) },
+ .advance = placed.value(c.plan[4]),
+ .travel = placed.value(c.plan[5]),
+ .total = placed.value(c.plan[6]),
+ },
+ .marks = .{ whole(rec, placed.value(c.marks[0])), whole(rec, placed.value(c.marks[1])) },
+ .hurried = placed.value(c.hurried),
+ .veil = placed.value(c.veil),
+ .count = @intFromFloat(@max(placed.value(c.count), 0)),
+ .of = c.of,
+ .place = 0,
+ .fired = c.levels.fire,
+ .way = .{ c.first, c.last },
+ };
+ for (&n.stops, c.stops) |*stop_at, v| stop_at.* = whole(rec, placed.value(v));
+ const phase = placed.value(c.phase);
+ if (phase < 1) n.time = phase * n.plan.total;
+ if (c.last > c.first) {
+ // Linear: time itself.
+ const here = std.math.lerp(@as(f32, @floatFromInt(n.stops[1])), @as(f32, @floatFromInt(n.stops[0])), std.math.clamp(phase, 0, 1));
+ n.place = std.math.clamp((here - @as(f32, @floatFromInt(c.first))) / @as(f32, @floatFromInt(c.last - c.first)), 0, 1);
+ }
+ return n;
+ }
+};
+
+fn whole(rec: *const Recording, value: f32) u64 {
+ return @min(@as(u64, @intFromFloat(@max(value, 0))), rec.end());
+}
+
+fn settled(s: *const anim.Frame, v: anim.Value) f32 {
+ return s.values.items[@backingInt(v)].settled;
+}
+
+/// Whether the mark jumps from the line of moment `from` to that of `to`
+/// (fades out there and in here) and does not slide: a call is not a
+/// journey across the lines between.
+pub fn jumps(rec: *const Recording, from: u64, to: u64) bool {
+ const rows = @max(rec.own[from], rec.own[to]) - @min(rec.own[from], rec.own[to]);
+ return rec.depths[from] != rec.depths[to] or rows > time.current_jump_rows;
+}
+
+/// The cursor at one instant.
+pub const Now = struct {
+ rec: *const Recording,
+ /// `stops[0]` is the moment shown, `stops[1]` where the step came
+ /// from: the step is every moment after it up to the one shown.
+ stops: [history]u64,
+ /// Seconds into the step's plan; infinite at rest.
+ time: f32,
+ plan: Plan,
+ /// The moment whose line the current mark is leaving, and the one it goes to.
+ marks: [2]u64,
+ /// 0 to 1: steps are hurried; what cannot be read is veiled.
+ hurried: f32,
+ veil: f32,
+ /// Steps taken, of how many in the scene (0: not told).
+ count: u32,
+ of: u32,
+ /// 0 to 1 along the scene's way through the recording.
+ place: f32,
+ /// Where the scene's steps fire (`Levels.fire`).
+ fired: @FieldType(Levels, "fire") = .source,
+ /// The scene's way through the recording: its first moment and its last.
+ way: [2]u64 = .{ 0, 0 },
+
+ /// The program's state as shown.
+ pub fn moment(n: Now) Recording.Moment {
+ return n.rec.moment(n.stops[0]);
+ }
+
+ /// Its state before this step.
+ pub fn before(n: Now) Recording.Moment {
+ return n.rec.moment(n.stops[1]);
+ }
+
+ pub fn resting(n: Now) bool {
+ return std.math.isInf(n.time);
+ }
+
+ /// A step shown in full: fire, arm, strike, hold.
+ pub fn walking(n: Now) bool {
+ return n.plan.gait == .walk and !n.resting();
+ }
+
+ /// Seconds since `level` struck, for the one of several that strikes
+ /// `delay` after the first: negative before, infinite at rest.
+ pub fn since(n: Now, level: Level, delay: f32) f32 {
+ return n.time - n.plan.at[@intFromEnum(level)] - delay;
+ }
+
+ /// Whether `level`'s changes show yet: until then a component draws
+ /// the state before the step. The digits change as the fill comes in.
+ pub fn landed(n: Now, level: Level, delay: f32) bool {
+ return n.since(level, delay) >= time.strike.in / 2.0;
+ }
+
+ /// The state to draw for `level`.
+ pub fn shown(n: Now, level: Level) Recording.Moment {
+ return if (n.landed(level, 0)) n.moment() else n.before();
+ }
+
+ /// The moment to ask the recording's index about, for `level`.
+ pub fn stop(n: Now, level: Level) u64 {
+ return if (n.landed(level, 0)) n.stops[0] else n.stops[1];
+ }
+
+ /// How far (0 to 1, to be eased) a thing has got that moves as `level`
+ /// strikes: it sets off `lead` seconds before the strike and takes
+ /// `seconds`. At a run it sets off with its level and takes
+ /// `time.run_ease`; at a sprint, and at rest, it is there.
+ pub fn moving(n: Now, level: Level, lead: f32, seconds: f32) f32 {
+ return switch (n.plan.gait) {
+ .walk => std.math.clamp((n.since(level, 0) + lead) / seconds, 0, 1),
+ .run => std.math.clamp(n.since(level, 0) / time.run_ease, 0, 1),
+ .sprint => 1,
+ };
+ }
+
+ /// The fire: how far out (in units) the edges of the mark's plaque
+ /// are, on the line about to run. The step's first beat, alone.
+ pub fn fire(n: Now) f32 {
+ return if (n.walking() and n.time < time.fire) theme.pulse(n.time / time.fire) else 0;
+ }
+
+ /// The same for the view the scene fires in, 0 for the other.
+ pub fn fires(n: Now, in: @FieldType(Levels, "fire")) f32 {
+ return if (n.fired == in) n.fire() else 0;
+ }
+
+ /// 0 to 1 (to be eased) through the mark's move to the next line: the
+ /// step's follow-through, and the next step's anticipation.
+ pub fn advancing(n: Now) f32 {
+ return n.advancingAfter(0);
+ }
+
+ /// The same for another view of where execution is (the pc's row, the
+ /// value of rip), which follows the source's mark `delay` seconds
+ /// behind: three panels do not start on one frame.
+ pub fn advancingAfter(n: Now, delay: f32) f32 {
+ if (n.resting() or n.plan.travel <= 0) return 1;
+ return std.math.clamp((n.time - n.plan.advance - delay) / @max(n.plan.travel - delay, 1.0 / 60.0), 0, 1);
+ }
+
+ /// The moment the current mark stands for: the step's own line until
+ /// the mark has left it.
+ pub fn marked(n: Now) u64 {
+ return if (n.advancing() >= 0.5) n.marks[1] else n.marks[0];
+ }
+
+ /// How many steps ago (0: in this one) the bytes `addr .. addr + size`
+ /// last changed; null when longer ago than a mark lasts.
+ pub fn writeAge(n: Now, addr: u64, size: u64) ?u64 {
+ return n.writeAgeFrom(addr, size, 0);
+ }
+
+ /// The same, not counting the `skip` newest steps.
+ fn writeAgeFrom(n: Now, addr: u64, size: u64, skip: usize) ?u64 {
+ for (skip..history - 1) |age| {
+ if (Recording.touches(n.rec.written(n.stops[age + 1], n.stops[age]), addr, size)) return age;
+ }
+ return null;
+ }
+
+ /// The same for a register, by its place in `Regs.names`.
+ pub fn registerAge(n: Now, reg: usize) ?u64 {
+ return n.registerAgeFrom(reg, 0);
+ }
+
+ fn registerAgeFrom(n: Now, reg: usize, skip: usize) ?u64 {
+ for (skip..history - 1) |age| {
+ if (n.rec.registersChanged(n.stops[age + 1], n.stops[age]) >> @intCast(reg) & 1 != 0) return age;
+ }
+ return null;
+ }
+
+ /// Whether this step read any of `addr .. addr + size`.
+ pub fn wasRead(n: Now, addr: u64, size: u64) bool {
+ return Recording.touches(n.rec.read(n.stops[1], n.stops[0]), addr, size);
+ }
+
+ /// How far into the run of bytes this step wrote `addr` is: bytes of
+ /// one write strike a frame apart, low address first.
+ pub fn writeOffset(n: Now, addr: u64) u64 {
+ for (n.rec.written(n.stops[1], n.stops[0])) |span| {
+ if (addr >= span.addr and addr < span.addr + span.len) return addr - span.addr;
+ }
+ return 0;
+ }
+
+ /// What a step `age` steps ago left on a thing it wrote: an ember for
+ /// three steps, leaving in the one after.
+ fn left(n: Now, age: ?u64) ui.Heat {
+ const s = time.strike;
+ const a = age orelse return .none;
+ if (a == 0 or a > s.ember_steps) return .none;
+ if (a < s.ember_steps) return .ember;
+ // Linear: a fade. Gone by the time this step is over.
+ return .{ .level = 1 - std.math.clamp(n.time / s.out, 0, 1) };
+ }
+
+ /// The mark of a thing last changed `age` steps ago (`older`: not
+ /// counting this step), whose strike came `since_strike` seconds ago.
+ /// Anticipation: armed first, a frame round the old value. Then the
+ /// strike: the fill comes in (never in one frame) with a pulse of its
+ /// edges, the one exaggeration there is. Held solid while the line
+ /// that did it is still gold; cooled as the mark leaves.
+ pub fn heat(n: Now, age: ?u64, older: ?u64, since_strike: f32) ui.Heat {
+ const s = time.strike;
+ if (age != 0) return n.left(age);
+ const was = n.left(older);
+ switch (n.plan.gait) {
+ // Faster than a strike can be seen: embers only.
+ .sprint => return .ember,
+ .run => return if (was.level >= 1 or n.resting()) .ember else .{ .level = std.math.clamp(since_strike / time.snap, 0, 1) },
+ .walk => {},
+ }
+ if (n.resting()) return .ember;
+ if (since_strike < 0) {
+ var armed = was;
+ if (since_strike >= -s.arm) armed.arm = std.math.clamp((since_strike + s.arm) / time.stagger, 0, 1);
+ return armed;
+ }
+ return .{
+ .level = 1,
+ .solid = 1 - glide(std.math.clamp((n.time - n.plan.advance) / s.cool, 0, 1)),
+ .in = std.math.clamp(since_strike / s.in, 0, 1),
+ .from = if (was.level >= 1) .ember else .nothing,
+ .out = if (since_strike < s.pulse) theme.pulse(since_strike / s.pulse) else 0,
+ };
+ }
+
+ /// The mark of the bytes `addr .. addr + size`, which strike with
+ /// `level`, `delay` seconds after its first.
+ pub fn written(n: Now, addr: u64, size: u64, level: Level, delay: f32) ui.Heat {
+ return n.heat(n.writeAge(addr, size), n.writeAgeFrom(addr, size, 1), n.since(level, delay));
+ }
+
+ /// The mark of a register: the CPU's level.
+ pub fn register(n: Now, reg: usize, delay: f32) ui.Heat {
+ return n.heat(n.registerAge(reg), n.registerAgeFrom(reg, 1), n.since(.cpu, delay));
+ }
+
+ /// How much (0 to 1) the frame round a thing this step read shows: in
+ /// with its level, never armed or pulsed, held while the line is
+ /// gold, and out as the mark leaves, gone before the next line fires.
+ pub fn reading(n: Now, level: Level, delay: f32) f32 {
+ return switch (n.plan.gait) {
+ .walk => n.held(n.plan.at[@intFromEnum(level)] + delay),
+ .run => if (n.resting()) 0 else @min(std.math.clamp(n.since(level, 0) / time.stagger, 0, 1), std.math.clamp((n.plan.total - n.time) / time.snap, 0, 1)),
+ .sprint => 0,
+ };
+ }
+
+ /// The same for a frame that comes in `from` seconds into a walked step.
+ pub fn held(n: Now, from: f32) f32 {
+ const r = time.read;
+ if (!n.walking()) return 0;
+ return @min(std.math.clamp((n.time - from) / r.in, 0, 1), 1 - std.math.clamp((n.time - n.plan.advance) / r.out, 0, 1));
+ }
+};
+
+fn instant(seconds: f32, plan: Plan) Now {
+ return .{ .rec = undefined, .stops = undefined, .time = seconds, .plan = plan, .marks = undefined, .hurried = 0, .veil = 0, .count = 0, .of = 0, .place = 0 };
+}
+
+test "a write is armed, strikes, holds, cools with the advance, and leaves after three steps" {
+ const s = time.strike;
+ const expect = std.testing.expect;
+ const expectEqual = std.testing.expectEqual;
+ // One register written: struck at 0.30, the mark leaves at 0.90.
+ const plan: Plan = .{ .at = @splat(0.30), .advance = 0.90, .total = 1.50 };
+ // Armed: a frame, and no fill yet.
+ var h = instant(0.20, plan).heat(0, null, 0.20 - 0.30);
+ try expect(h.arm == 1 and h.level == 0);
+ // Not before its arm.
+ try expectEqual(ui.Heat.none, instant(0.05, plan).heat(0, null, 0.05 - 0.30));
+ // Struck: the fill half in, the edges out.
+ h = instant(0.35, plan).heat(0, null, 0.05);
+ try expect(h.level == 1 and h.solid == 1 and @abs(h.in - 0.5) < 1e-3 and h.out > 2 and h.arm == 0);
+ // Held solid until the mark leaves, then cooled, halfway at the middle.
+ h = instant(0.89, plan).heat(0, null, 0.59);
+ try expect(h.solid == 1 and h.in == 1 and h.out == 0);
+ h = instant(0.90 + s.cool / 2.0, plan).heat(0, null, 0.8);
+ try std.testing.expectApproxEqAbs(@as(f32, 0.5), h.solid, 1e-3);
+ // At rest, and for the steps after: the ember; then it goes.
+ const rest = instant(std.math.inf(f32), plan);
+ try expectEqual(ui.Heat.ember, rest.heat(0, null, std.math.inf(f32)));
+ try expectEqual(ui.Heat.ember, rest.heat(2, 2, 0));
+ try expectEqual(ui.Heat.none, rest.heat(4, 4, 0));
+ try expectEqual(ui.Heat.none, rest.heat(null, null, 0));
+ try std.testing.expectApproxEqAbs(@as(f32, 0.5), instant(s.out / 2.0, plan).heat(s.ember_steps, s.ember_steps, 0).level, 1e-3);
+ // Struck again over its ember: armed with the ember still under it.
+ h = instant(0.20, plan).heat(0, 1, -0.10);
+ try expect(h.level == 1 and h.arm == 1 and h.solid == 0);
+ // Running: an ember and no more. Sprinting: the same, at once.
+ try expect(instant(0.2, Plan.running(0.3)).heat(0, null, 0.2).solid == 0);
+ try expectEqual(ui.Heat.ember, instant(0.01, Plan.sprinting(0.05)).heat(0, null, 0.01));
+}
+
+test "what a step read is framed while its line is gold" {
+ const plan: Plan = .{ .at = @splat(0.30), .advance = 0.90, .total = 1.50 };
+ try std.testing.expectEqual(@as(f32, 0), instant(0.2, plan).reading(.memory, 0));
+ try std.testing.expectEqual(@as(f32, 1), instant(0.6, plan).reading(.memory, 0));
+ try std.testing.expectEqual(@as(f32, 0), instant(0.9 + time.read.out, plan).reading(.memory, 0));
+ try std.testing.expectEqual(@as(f32, 0), instant(std.math.inf(f32), plan).reading(.memory, 0));
+}
+
+test "the mark fires first and moves last" {
+ const plan: Plan = .{ .at = @splat(0.30), .advance = 0.90, .travel = 0.20, .total = 1.50 };
+ try std.testing.expect(instant(0.10, plan).fire() > 3.9);
+ try std.testing.expectEqual(@as(f32, 0), instant(0.30, plan).fire());
+ try std.testing.expectEqual(@as(f32, 0), instant(0.89, plan).advancing());
+ try std.testing.expectEqual(@as(f32, 1), instant(1.10, plan).advancing());
+ try std.testing.expectEqual(@as(f32, 1), instant(std.math.inf(f32), plan).advancing());
+}
diff --git a/anim/src/heap.zig b/anim/src/heap.zig
new file mode 100644
index 0000000..e9a0dcf
--- /dev/null
+++ b/anim/src/heap.zig
@@ -0,0 +1,105 @@
+//! The heap, to scale: a strip along the addresses malloc handed out, each
+//! live allocation a green block with the name of what points at it, each
+//! freed one hollow and dashed, the allocator's own bytes between them
+//! filled, and the bytes this step wrote in vermilion where they are.
+//! Reads `Moment.heap`, and the recording's index of every allocation made.
+const std = @import("std");
+const sk = @import("sketch");
+const anim = @import("anim");
+const ui = @import("ui.zig");
+const cursors = @import("cursor.zig");
+const Cursor = cursors.Cursor;
+const Recording = @import("Recording.zig");
+const objects = @import("objects.zig");
+const theme = ui.theme;
+const Rect = ui.Rect;
+const t = theme.color.text;
+
+pub const Heap = struct {
+ cursor: Cursor,
+ box: Rect,
+ /// Variables each with a pigment (by its place here), as elsewhere.
+ track: []const []const u8 = &.{},
+ focus: bool = false,
+
+ pub fn draw(h: *const Heap, f: *sk.Frame, at: anim.Placed) void {
+ const u: ui.Ui = .{ .f = f, .at = at };
+ const now = h.cursor.now(at);
+ const rec = h.cursor.rec;
+ // The heap is memory: what a step did to it shows when memory strikes.
+ const moment = now.shown(.memory);
+ const at_moment = now.stop(.memory);
+ // Not "heap": a grid of the same bytes beside it has that name.
+ const body = u.panel(h.box.w, h.box.h, "heap map", .{ .focus = h.focus, .note = "to scale · low addresses on the left" });
+ if (rec.allocations.len == 0) return;
+ // The whole run's span, so nothing moves as chunks come and go.
+ var lo: u64 = std.math.maxInt(u64);
+ var hi: u64 = 0;
+ for (rec.allocations) |a| {
+ lo = @min(lo, a.ptr);
+ hi = @max(hi, a.ptr + a.size);
+ }
+ lo -|= 16;
+ const pad = theme.metric.panel.pad_x + 8;
+ const scale = @min(theme.metric.heap.units_per_byte, (body.w - 2 * pad - 60) / @as(f32, @floatFromInt(hi - lo)));
+ const strip_h: f32 = if (body.h < 220) theme.metric.heap.strip_h_stacked else theme.metric.heap.strip_h;
+ const y = body.y + (body.h - strip_h) / 2 - 6;
+ const live = moment.heap(f.scratch) catch return;
+
+ // Never used: a rule frame. The allocator's own bytes, filled:
+ // whatever lies between what it has handed out so far.
+ var used = lo;
+ for (rec.allocations) |a| {
+ if (a.moment <= at_moment) used = @max(used, a.ptr + a.size);
+ }
+ u.frame(.{ .x = pad, .y = y, .w = @as(f32, @floatFromInt(hi - lo)) * scale, .h = strip_h }, theme.color.rule, theme.stroke.rule);
+ u.fill(.{ .x = pad, .y = y, .w = @as(f32, @floatFromInt(used - lo)) * scale, .h = strip_h }, theme.color.rule);
+ // Where it goes on.
+ for (0..3) |i| u.fill(.{ .x = pad + @as(f32, @floatFromInt(hi - lo)) * scale + 16 + @as(f32, @floatFromInt(i)) * 14, .y = y + strip_h / 2 - 3, .w = 6, .h = 6 }, t.faint);
+
+ for (rec.allocations, 0..) |a, i| {
+ if (a.moment > at_moment) continue;
+ // The newest allocation at this address is the one to draw.
+ const newest = for (rec.allocations[i + 1 ..]) |later| {
+ if (later.ptr == a.ptr and later.moment <= at_moment) break false;
+ } else true;
+ if (!newest) continue;
+ const r: Rect = .{ .x = pad + @as(f32, @floatFromInt(a.ptr - lo)) * scale, .y = y, .w = @as(f32, @floatFromInt(a.size)) * scale - 2, .h = strip_h };
+ const is_live = for (live) |l| {
+ if (l.ptr == a.ptr and l.born == a.event) break true;
+ } else false;
+ u.fill(r, theme.color.page);
+ if (is_live) {
+ const mark = theme.mark(.allocated);
+ const fresh = a.moment > now.stops[1];
+ const p = if (fresh) now.moving(.memory, 0, theme.time.quick) else 1;
+ u.faded(p).fill(r, mark.ember);
+ u.faded(p).frame(r, mark.solid, theme.stroke.line);
+ // The bytes this step wrote, where they are.
+ var b: u64 = 0;
+ while (b < a.size) : (b += 8) {
+ // The same strike as the words beside it, at scale: no arm, no pulse.
+ var heat = now.written(a.ptr + b, @min(8, a.size - b), .memory, 0);
+ heat.arm = 0;
+ heat.out = 0;
+ if (heat.level > 0) _ = u.written(.{ .x = r.x + @as(f32, @floatFromInt(b)) * scale + 3, .y = y + 3, .w = @as(f32, @floatFromInt(@min(8, a.size - b))) * scale - 4, .h = strip_h - 6 }, heat, null);
+ }
+ // Who points at it.
+ var x = r.x + 6;
+ for (objects.pointing(f.scratch, rec, moment, a.ptr)) |v| {
+ const name = rec.name(v.name);
+ const w = u.width(.mono, theme.size.mono.small, name);
+ if (x + w > r.x + r.w - 4) break;
+ const tracked = for (h.track, 0..) |want, k| {
+ if (std.mem.eql(u8, want, name)) break k;
+ } else null;
+ if (tracked) |k| u.fill(.{ .x = x - 4, .y = y + strip_h - 36, .w = w + 8, .h = 30 }, theme.color.pigment[k % theme.color.pigment.len]);
+ u.text(.mono, theme.size.mono.small, x, y + strip_h - 12, name, t.primary);
+ x += w + 12;
+ }
+ } else u.dashedFrame(r, theme.mark(.freed).solid, theme.stroke.line);
+ // Its address under it: the end that tells chunks apart.
+ u.text(.mono, theme.size.mono.small, r.x, y + strip_h + 30, u.print("{x:0>4}", .{a.ptr & 0xffff}), t.faint);
+ }
+ }
+};
diff --git a/anim/src/hexdump.zig b/anim/src/hexdump.zig
new file mode 100644
index 0000000..e4b0908
--- /dev/null
+++ b/anim/src/hexdump.zig
@@ -0,0 +1,114 @@
+//! Memory as a hexdump, for a lens that shows what its idea is made of: an
+//! address gutter, sixteen bytes a row, the same bytes as text; and every
+//! run of bytes marked as what it is, from the types of what the program's
+//! pointers reach: a struct's number plain, its pointer in the ink of
+//! where it points, the allocator's own bytes between allocations faint,
+//! bytes never observed two dots. A line under a run says which field it
+//! is (the legend is in the tag). Bytes a step wrote are struck here a
+//! beat before the idea drawn from them changes: the words are the cause.
+//! Reads `Moment.read` (with what is known), `Moment.allocation`, and the
+//! recording's types.
+const std = @import("std");
+const sk = @import("sketch");
+const anim = @import("anim");
+const ui = @import("ui.zig");
+const cursors = @import("cursor.zig");
+const contexts = @import("context.zig");
+const Recording = @import("Recording.zig");
+const objects = @import("objects.zig");
+const theme = ui.theme;
+const Rect = ui.Rect;
+const t = theme.color.text;
+const m = theme.metric.context;
+const size = theme.size.mono.context;
+const adv = size * 3 / 5;
+/// A byte's two digits, and the gap to the next; a wider one in the middle of a row.
+const pitch = 28;
+const middle = 12;
+
+pub const Hexdump = struct {
+ cursor: cursors.Cursor,
+ box: Rect,
+ title: []const u8 = "heap",
+ /// The first row's address; rounded down to sixteen.
+ base: u64,
+ focus: bool = false,
+
+ const Kind = enum { number, pointer, allocated, allocator, unknown };
+
+ pub fn draw(g: *const Hexdump, f: *sk.Frame, at: anim.Placed) void {
+ const u: ui.Ui = .{ .f = f, .at = at };
+ const now = g.cursor.now(at);
+ const rec = g.cursor.rec;
+ const body = u.panel(g.box.w, g.box.h, g.title, .{ .focus = g.focus, .note = "sixteen bytes a row \u{00b7} underlined: a field of a node; faint: the allocator's own" });
+ const things = objects.reach(f.scratch, rec, now.moment(), null);
+ const rows: usize = @intFromFloat(@floor((body.h - 2 * m.pad) / m.row));
+ const bytes_x = m.side + 14 * adv + 8;
+ const text_x = bytes_x + 16 * pitch + middle + 12;
+ for (0..rows) |row| {
+ const addr = (g.base & ~@as(u64, 15)) + row * 16;
+ const y = body.y + m.pad + @as(f32, @floatFromInt(row)) * m.row;
+ const base = theme.baseline(y, m.row, size);
+ _ = u.value(m.side, base, addr, true, .{ .ink = ui.rgb(contexts.ink(contexts.regionOf(now.moment(), addr))) });
+ var is: [16]u8 = undefined;
+ var known: [16]bool = undefined;
+ now.moment().read(addr, &is, &known) catch return;
+ var was: [16]u8 = undefined;
+ var was_known: [16]bool = undefined;
+ now.before().read(addr, &was, &was_known) catch return;
+ // A word at a time: a mark, and a field's line, go under a run of bytes, not under each.
+ for (0..2) |half| {
+ const word = addr + half * 8;
+ const x = bytes_x + @as(f32, @floatFromInt(half)) * (8 * pitch + middle);
+ const span: Rect = .{ .x = x - 3, .y = y + 2, .w = 8 * pitch - 4 + 2, .h = m.row - 4 };
+ @import("ties.zig").anchor(u, .{ .word = word }, span);
+ const landed = now.landed(.memory, 0);
+ const mark = u.struck(span, now.written(word, 8, .memory, 0));
+ if (now.wasRead(word, 8) and now.writeAge(word, 8) != 0) u.readFrame(span, now.reading(.memory, 0));
+ const kind = g.kindOf(things, now.moment(), word);
+ // What the eight bytes are, if they are an address: its ink.
+ const held = Recording.word(if (landed) now.moment() else now.before(), word, 8) catch null;
+ const region = if (held) |value| contexts.regionOf(now.moment(), value) else .none;
+ const color: ui.Color = if (mark) |struck| struck.ink else switch (kind) {
+ .pointer => if (region != .none) ui.rgb(contexts.ink(region)) else ui.rgb(t.dim),
+ .number => ui.rgb(t.primary),
+ .allocated => ui.rgb(t.dim),
+ .allocator, .unknown => ui.rgb(t.faint),
+ };
+ for (0..8) |i| {
+ const n = half * 8 + i;
+ const bx = x + @as(f32, @floatFromInt(i)) * pitch;
+ if (!(if (landed) known[n] else was_known[n])) {
+ u.unknown(.{ .x = bx, .y = y, .w = 2 * adv, .h = m.row });
+ continue;
+ }
+ const byte = if (landed) is[n] else was[n];
+ u.text(if (mark != null) .mono_bold else .mono, size, bx, base, u.print("{x:0>2}", .{byte}), color);
+ // The same byte as text.
+ const tx = text_x + @as(f32, @floatFromInt(n)) * adv;
+ if (std.ascii.isPrint(byte) and byte != ' ') u.text(.mono, size, tx, base, &.{byte}, t.dim) else u.fill(.{ .x = tx + 4, .y = y + m.row / 2 - 2, .w = 4, .h = 4 }, t.faint);
+ }
+ // Which field: a line under the run, in the field's ink.
+ if (kind == .number or kind == .pointer) u.fill(.{ .x = x, .y = y + m.row - 3, .w = 8 * pitch - 4, .h = theme.stroke.rule }, if (kind == .pointer) theme.color.region.heap else t.primary);
+ }
+ }
+ u.veil(.{ .x = theme.stroke.rule, .y = body.y, .w = body.w - 2 * theme.stroke.rule, .h = body.h - theme.stroke.rule }, now.veil);
+ }
+
+ /// What the word at `addr` is: a field of a struct the program's
+ /// pointers reach (by its type), other allocated bytes, the
+ /// allocator's own between allocations, or never observed.
+ fn kindOf(g: *const Hexdump, things: []const objects.Object, moment: Recording.Moment, addr: u64) Kind {
+ _ = g;
+ for (things) |o| {
+ if (!o.holds(addr)) continue;
+ for (o.type.record.fields) |field| if (o.addr + field.offset == addr) return if (field.type == .pointer) .pointer else .number;
+ return .allocated;
+ }
+ var bytes: [8]u8 = undefined;
+ var known: [8]bool = undefined;
+ moment.read(addr, &bytes, &known) catch return .unknown;
+ if (std.mem.indexOfScalar(bool, &known, true) == null) return .unknown;
+ return if ((moment.allocation(addr) catch null) != null) .allocated else .allocator;
+ }
+};
diff --git a/anim/src/memory.zig b/anim/src/memory.zig
new file mode 100644
index 0000000..8749bb9
--- /dev/null
+++ b/anim/src/memory.zig
@@ -0,0 +1,444 @@
+//! The memory grid: one 8-byte word a row, low addresses on top, every row
+//! at a fixed place (nothing a step does moves a row). From the left:
+//! registers and tracked variables that hold a row's address (plaques that
+//! slide from row to row), the address, a lane for pointer arrows, the
+//! eight bytes (or the word they make), the same bytes as text, and what
+//! the row is. Bytes this step wrote are armed and struck, bytes it read
+//! are framed, bytes never recorded are two dots, and a word that holds
+//! the address of another row on screen is framed and joined to it by an
+//! arrow. With `frames`, a rule names the call each stretch of stack
+//! belongs to.
+//! Reads `Moment.read` (with what is known), `Moment.regs`,
+//! `Moment.variables`, and the recording's index of writes, reads and calls.
+const std = @import("std");
+const sk = @import("sketch");
+const anim = @import("anim");
+const zt = @import("ztrace");
+const ui = @import("ui.zig");
+const cursors = @import("cursor.zig");
+const Recording = @import("Recording.zig");
+const objects = @import("objects.zig");
+const syscalls = @import("syscalls.zig");
+const theme = ui.theme;
+const time = theme.time;
+const Rect = ui.Rect;
+const t = theme.color.text;
+const pitch = theme.metric.byte.pitch;
+const side = theme.metric.byte.side;
+const size = theme.size.mono.data;
+const small = theme.size.mono.small;
+const row_h = theme.metric.row_pitch;
+/// Bytes of one write strike a frame apart, low address first.
+const byte_apart = 1.0 / 60.0;
+
+pub const Memory = struct {
+ cursor: cursors.Cursor,
+ box: Rect,
+ title: []const u8 = "memory",
+ note: []const u8 = "one word a row · low addresses on top",
+ /// The first row's address; rounded down to a word.
+ base: u64,
+ /// Bytes in a grid; each word as one number; or, for a string, eight
+ /// characters a row, each over its byte, with nothing else beside them.
+ form: enum { bytes, words, text } = .bytes,
+ /// The bytes again as text, right of them.
+ text: bool = true,
+ /// How many bytes to show (0: as many rows as fit).
+ bytes: u64 = 0,
+ /// How many words to show at most (0: as many as fit): fewer, when a
+ /// camera will come nearer and must not cut a row.
+ rows: usize = 0,
+ /// Stack: a rule where each call's frame begins, with the call's name.
+ frames: bool = false,
+ /// Registers shown beside the row whose address they hold.
+ registers: []const []const u8 = &.{ "rsp", "rbp" },
+ /// Variables each with a pigment (by its place here), shown beside the
+ /// row they point at: the same list a node-link view of them is given.
+ track: []const []const u8 = &.{},
+ focus: bool = false,
+
+ const Row = union(enum) { word: u64, elision: u64 };
+ const Columns = struct { gutter: f32, cells: f32, cell_w: f32, text: f32, names: f32, digits: usize };
+
+ pub fn draw(g: *const Memory, f: *sk.Frame, at: anim.Placed) void {
+ const u: ui.Ui = .{ .f = f, .at = at };
+ const now = g.cursor.now(at);
+ const rec = g.cursor.rec;
+ const body = u.panel(g.box.w, g.box.h, g.title, .{ .focus = g.focus, .note = g.note });
+ if (g.form == .text) return g.string(u, now, body);
+ // Memory is the second level a step reaches: until its changes
+ // land, the bytes are those from before the step.
+ const moment = now.shown(.memory);
+ const calls = if (g.frames) rec.stack(f.scratch, now.stop(.cpu)) else &.{};
+ const regs = now.shown(.cpu).regs(rec.tid) catch null;
+ const things = objects.reach(f.scratch, rec, moment, null);
+
+ // Columns. The lane on the left is as wide as two plaques side by side.
+ var widest = [2]f32{ 0, 0 };
+ for ([_][]const []const u8{ g.registers, g.track }) |names| for (names) |name| {
+ const w = u.width(.mono, small, name) + 20;
+ if (w > widest[0]) {
+ widest = .{ w, widest[0] };
+ } else widest[1] = @max(widest[1], w);
+ };
+ const digits: usize = if (g.box.w < 1100) 8 else 12;
+ const gutter_x = theme.metric.panel.pad_x + @max(theme.metric.mark_lane, widest[0] + widest[1] + 8 + 14);
+ const cells_x = gutter_x + ui.hexWidth(digits, small) + theme.metric.arrow_lane + 2 * theme.stroke.lane_pitch;
+ const cell_w: f32 = if (g.form == .words) ui.hexWidth(16, size) + 24 else 8 * pitch - 2;
+ const text_x = cells_x + cell_w + 22;
+ const cols: Columns = .{ .gutter = gutter_x, .cells = cells_x, .cell_w = cell_w, .text = text_x, .names = if (g.text and g.form == .bytes) text_x + 8 * ui.advance(size) + 30 else text_x, .digits = digits };
+
+ // Rows, as many as fit, each where it will always be. Words the
+ // recording never saw at all are one row of dots; a word it will
+ // see later has its place already.
+ const ever = rec.moment(rec.end());
+ var rows: std.ArrayList(Row) = .empty;
+ var ys: std.ArrayList(f32) = .empty;
+ var y = body.y + theme.metric.panel.pad_y;
+ const bottom = body.y + body.h - 8;
+ var addr = g.base & ~@as(u64, 7);
+ var words: usize = 0;
+ while (y + row_h <= bottom and (g.rows == 0 or words < g.rows)) : (words += 1) {
+ var unseen: u64 = 0;
+ while (!g.frames and unseen < 4096 and !knownAny(ever, addr + unseen)) unseen += 8;
+ if (unseen > 8) {
+ rows.append(f.scratch, .{ .elision = unseen }) catch break;
+ ys.append(f.scratch, y) catch break;
+ y += theme.metric.elision_h + 8;
+ addr += unseen;
+ if (unseen >= 4096) break;
+ continue;
+ }
+ rows.append(f.scratch, .{ .word = addr }) catch break;
+ ys.append(f.scratch, y) catch break;
+ y += row_h;
+ addr += 8;
+ }
+ const grid: Grid = .{ .rows = rows.items, .ys = ys.items };
+
+ // Pointers first: frames and arrows under nothing, in one run of shapes.
+ var lane: f32 = 0;
+ for (rows.items, ys.items) |row, row_y| {
+ if (row != .word) continue;
+ const fresh = now.walking() and now.writeAge(row.word, 8) == 0;
+ const since = now.since(.memory, 0);
+ const new = pointee(grid, now.moment(), row.word);
+ const old = pointee(grid, now.before(), row.word);
+ const held = if (now.landed(.memory, 0)) new else old;
+ if (held == null and !(fresh and old != null)) continue;
+ const cy = row_y + row_h / 2;
+ const out = theme.metric.pointer_frame_outset;
+ const frame: Rect = .{ .x = cells_x - out, .y = row_y + (row_h - side) / 2 - out, .w = cell_w + 2 * out, .h = side + 2 * out };
+ const x_lane = cells_x - out - 18 - lane;
+ lane = @mod(lane + theme.stroke.lane_pitch, 3 * theme.stroke.lane_pitch);
+ const purple = theme.mark(.pointer).solid;
+ const way = struct {
+ fn to(scratch: std.mem.Allocator, from_x: f32, from_y: f32, lane_x: f32, to_x: f32, to_y: f32) []const ui.Vec {
+ const points = scratch.alloc(ui.Vec, 4) catch return &.{};
+ points[0..4].* = .{ .{ from_x, from_y }, .{ lane_x, from_y }, .{ lane_x, to_y }, .{ to_x, to_y } };
+ return points;
+ }
+ }.to;
+ if (!fresh or old == new) {
+ // As it stands; at a run a new arrow still grows to its target.
+ if (held) |to_y| u.arrow(way(f.scratch, frame.x, cy, x_lane, cells_x - 2, to_y + row_h / 2), purple, .{ .progress = if (now.writeAge(row.word, 8) == 0) cursors.standard(now.moving(.memory, 0, time.redirect.head)) else 1 });
+ } else {
+ // A pointer rewritten. Anticipation: with the arm its old
+ // arrow goes dashed and faint. Follow-through: the word
+ // strikes, then the new arrow grows along its lane, and
+ // the row it lands on answers with a bright frame.
+ if (old) |to_y| {
+ const ghost = if (since < -time.strike.arm) u else u.faded(1 - std.math.clamp((since - time.redirect.ghost_hold) / time.redirect.ghost_out, 0, 1));
+ ghost.arrow(way(f.scratch, frame.x, cy, x_lane, cells_x - 2, to_y + row_h / 2), if (since < -time.strike.arm) ui.rgb(purple) else ui.rgb(t.faint), .{ .dashed = since >= -time.strike.arm, .head = if (since < -time.strike.arm) theme.stroke.head else null, .width = if (since < -time.strike.arm) theme.stroke.arrow else theme.stroke.line });
+ }
+ if (new) |to_y| {
+ const drawn = std.math.clamp((since - time.snap) / time.redirect.head, 0, 1);
+ u.arrow(way(f.scratch, frame.x, cy, x_lane, cells_x - 2, to_y + row_h / 2), purple, .{ .progress = cursors.standard(drawn) });
+ const landed = since - time.snap - time.redirect.head;
+ if (landed >= 0 and landed < time.redirect.landing) u.faded(1 - landed / time.redirect.landing).frame(.{ .x = frame.x, .y = to_y + (row_h - side) / 2 - out, .w = frame.w, .h = frame.h }, theme.mark(.attention).solid, theme.stroke.line);
+ }
+ }
+ if (held != null) u.frame(frame, purple, theme.stroke.arrow);
+ }
+
+ for (rows.items, ys.items, 0..) |row, row_y, i| switch (row) {
+ .elision => |bytes| u.elision(cells_x, row_y, if (bytes >= 4096) "nothing seen here yet" else u.print("{d} bytes not seen", .{bytes})),
+ .word => |a| {
+ g.word(u, now, things, calls, a, row_y, cols);
+ // Where a call's frame begins: a rule in the gap above its
+ // first row, and its name. No row moves to make room for it.
+ if (!g.frames) continue;
+ const owner = frameOf(calls, regs, a) orelse continue;
+ if (i > 0 and rows.items[i - 1] == .word and frameOf(calls, regs, rows.items[i - 1].word) == owner) continue;
+ const call = calls[owner];
+ const name = if (call.arg) |arg| u.print("{s}({d})", .{ rec.name(call.function), @as(i64, @bitCast(arg)) }) else rec.name(call.function);
+ const w = u.width(.sans_medium, theme.size.sans.micro, name);
+ const rule_y = row_y + (row_h - side) / 2 - 8;
+ u.fill(.{ .x = gutter_x, .y = rule_y, .w = g.box.w - theme.metric.panel.pad_x - gutter_x - w - 12, .h = theme.stroke.rule }, if (owner == calls.len - 1) theme.mark(.current).solid else theme.color.rule);
+ u.text(.sans_medium, theme.size.sans.micro, g.box.w - theme.metric.panel.pad_x - w, rule_y + 8, name, if (owner == calls.len - 1) t.primary else t.dim);
+ },
+ };
+ g.plaques(u, now, grid, gutter_x);
+ // Staging: bytes cannot be read at a sprint.
+ u.veil(.{ .x = theme.stroke.rule, .y = body.y, .w = body.w - 2 * theme.stroke.rule, .h = body.h - theme.stroke.rule }, now.veil);
+ }
+
+ const Grid = struct {
+ rows: []const Row,
+ ys: []const f32,
+
+ fn rowY(grid: Grid, addr: u64) ?f32 {
+ for (grid.rows, grid.ys) |row, y| if (row == .word and row.word == addr & ~@as(u64, 7)) return y;
+ return null;
+ }
+ };
+
+ /// Where the row is that the word at `addr` points at, at `moment`.
+ fn pointee(grid: Grid, moment: Recording.Moment, addr: u64) ?f32 {
+ const target = (Recording.word(moment, addr, 8) catch null) orelse return null;
+ if (target == addr or target == 0) return null;
+ return grid.rowY(target);
+ }
+
+ /// Left of the gutter: who holds a row's address. What persists
+ /// slides: a plaque moves to its new row as its level strikes, and
+ /// fades only where it has no row to come from or go to.
+ fn plaques(g: *const Memory, u: ui.Ui, now: cursors.Now, grid: Grid, gutter_x: f32) void {
+ const rec = g.cursor.rec;
+ const states = [2]Recording.Moment{ now.before(), now.moment() };
+ const indices = [2]u64{ now.stops[1], now.stops[0] };
+ // In each state, the row each name is at (registers, then tracked variables).
+ const count = g.registers.len + g.track.len;
+ const held = u.f.scratch.alloc([2]?u64, count) catch return;
+ for (states, indices, 0..) |state, index, k| {
+ const regs = state.regs(rec.tid) catch null;
+ for (g.registers, 0..) |reg, i| held[i][k] = if (regs) |r| r.named(reg) else null;
+ for (g.track, g.registers.len..) |name, i| {
+ held[i][k] = null;
+ const v = rec.variable(u.f.scratch, state, name) orelse continue;
+ if (rec.assigned(v, index)) held[i][k] = Recording.word(state, v.addr, 8) catch null;
+ }
+ }
+ for (0..count) |i| {
+ const is_register = i < g.registers.len;
+ const name = if (is_register) g.registers[i] else g.track[i - g.registers.len];
+ const w = u.width(.mono, small, name) + 20;
+ var places: [2]?ui.Vec = .{ null, null };
+ for (&places, 0..) |*place, k| {
+ const addr = held[i][k] orelse continue;
+ const y = grid.rowY(addr) orelse continue;
+ if (addr & 7 != 0) continue;
+ // Right to left, in order, among those on the same row.
+ var x = gutter_x - 14 - w;
+ for (0..i) |other| if (held[other][k] == addr) {
+ x -= u.width(.mono, small, if (other < g.registers.len) g.registers[other] else g.track[other - g.registers.len]) + 28;
+ };
+ place.* = .{ x, y + (row_h - side) / 2 + 3 };
+ }
+ const p = cursors.standard(now.moving(if (is_register) .cpu else .memory, 0, time.move));
+ const at_place = if (places[0] != null and places[1] != null) sk.math.mix(places[0].?, places[1].?, p) else places[1] orelse places[0] orelse continue;
+ const v = if (places[0] == null) u.faded(p) else if (places[1] == null) u.faded(1 - p) else u;
+ const plaque: Rect = .{ .x = at_place[0], .y = at_place[1], .w = w, .h = side - 6 };
+ if (is_register) {
+ v.fill(plaque, theme.color.raised);
+ v.frame(plaque, theme.mark(.pointer).solid, theme.stroke.rule);
+ } else v.fill(plaque, theme.color.pigment[(i - g.registers.len) % theme.color.pigment.len]);
+ v.label(.mono, small, plaque, .center, name, t.primary);
+ }
+ }
+
+ /// A string: the character over its byte, eight to a row.
+ fn string(g: *const Memory, u: ui.Ui, now: cursors.Now, body: Rect) void {
+ const h = theme.metric.byte.text_h;
+ const gutter_x = theme.metric.panel.pad_x;
+ const cells_x = gutter_x + ui.hexWidth(8, small) + 24;
+ // A system call's work on these bytes: the kernel fills them (a
+ // read), or reads them (a write), once the call is down there.
+ const call = syscalls.inStep(now);
+ const plan: syscalls.Plan = if (call) |made| .of(made) else .{};
+ const filled: ?Recording.Span = if (call) |made| syscalls.fills(made) else null;
+ const kernel_read: ?Recording.Span = if (call) |made| syscalls.bufferRead(made) else null;
+ var addr = g.base & ~@as(u64, 7);
+ var y = body.y + theme.metric.panel.pad_y + 8;
+ const end = if (g.bytes == 0) std.math.maxInt(u64) else g.base + g.bytes;
+ while (y + h <= body.y + body.h - 8 and addr < end) : ({
+ y += h + 20;
+ addr += 8;
+ }) {
+ u.address(gutter_x, theme.baseline(y, h, small), addr, 8);
+ var bytes: [8]u8 = undefined;
+ var known: [8]bool = undefined;
+ now.moment().read(addr, &bytes, &known) catch return;
+ var old: [8]u8 = undefined;
+ var was_known: [8]bool = undefined;
+ now.before().read(addr, &old, &was_known) catch return;
+ // The bytes a syscall read, as one frame round their run.
+ var first_read: ?usize = null;
+ var last_read: usize = 0;
+ const read_shows = now.held(plan.work);
+ for (0..8) |i| {
+ const cell: Rect = .{ .x = cells_x + @as(f32, @floatFromInt(i)) * pitch, .y = y, .w = side, .h = h };
+ const a = addr + i;
+ if (a >= end) break;
+ // Copied by the kernel two frames apart; by the program, one.
+ const by_kernel = filled != null and Recording.touches(&.{filled.?}, a, 1);
+ const delay = if (by_kernel) @as(f32, @floatFromInt(a - filled.?.addr)) * syscalls.Plan.byte else @as(f32, @floatFromInt(@min(now.writeOffset(a), 16))) * byte_apart;
+ const landed = now.landed(.memory, delay);
+ if (!(if (landed) known[i] else was_known[i])) {
+ u.unknown(cell);
+ continue;
+ }
+ const byte = if (landed) bytes[i] else old[i];
+ // Seen for the first time and not written: it begins, so it fades in; it is not struck.
+ const cell_u = if (!was_known[i] and now.writeAge(a, 1) != 0) u.faded(now.since(.memory, 0) / time.quick) else u;
+ const was_read = kernel_read != null and Recording.touches(&.{kernel_read.?}, a, 1);
+ var heat = now.written(a, 1, .memory, delay);
+ // The flow up from the kernel is their anticipation: no arm, and no pulse.
+ if (by_kernel) heat.arm = 0;
+ if (by_kernel) heat.out = 0;
+ // What is being read is not also "changed a while ago".
+ if (was_read) heat.level *= 1 - read_shows;
+ const ink = cell_u.written(cell, heat, theme.color.raised);
+ if (was_read) {
+ cell_u.faded(read_shows).fill(cell, theme.mark(.read).ember);
+ if (first_read == null) first_read = i;
+ last_read = i;
+ }
+ const top: Rect = .{ .x = cell.x, .y = y + 6, .w = side, .h = 42 };
+ if (std.ascii.isPrint(byte) and byte != ' ') {
+ cell_u.label(ink.face, size, top, .center, &.{byte}, ink.ink);
+ } else if (byte == '\n') {
+ cell_u.label(ink.face, size, top, .center, "\\n", ink.ink);
+ } else if (byte == ' ') {
+ // A space, drawn: the font's own is nothing to see.
+ const sx = cell.x + side / 2 - 8;
+ cell_u.fill(.{ .x = sx, .y = y + 34, .w = 16, .h = 3 }, ink.ink);
+ cell_u.fill(.{ .x = sx, .y = y + 28, .w = 3, .h = 6 }, ink.ink);
+ cell_u.fill(.{ .x = sx + 13, .y = y + 28, .w = 3, .h = 6 }, ink.ink);
+ }
+ cell_u.label(.mono, small, .{ .x = cell.x, .y = y + 46, .w = side, .h = 34 }, .center, u.print("{x:0>2}", .{byte}), if (ink.face == .mono_bold) ink.ink else ui.rgb(t.dim));
+ }
+ if (first_read) |from| u.faded(read_shows).frame(.{ .x = cells_x + @as(f32, @floatFromInt(from)) * pitch - 4, .y = y - 4, .w = @as(f32, @floatFromInt(last_read - from + 1)) * pitch + 6, .h = h + 8 }, theme.mark(.read).solid, theme.stroke.line);
+ }
+ }
+
+ fn word(g: *const Memory, u: ui.Ui, now: cursors.Now, things: []const objects.Object, calls: []const Recording.Call, addr: u64, y: f32, cols: Columns) void {
+ const rec = g.cursor.rec;
+ const cell_y = y + (row_h - side) / 2;
+ const base = theme.baseline(cell_y, side, size);
+ u.address(cols.gutter, theme.baseline(cell_y, side, small), addr, cols.digits);
+
+ var bytes: [8]u8 = undefined;
+ var known: [8]bool = undefined;
+ now.moment().read(addr, &bytes, &known) catch return;
+ var old: [8]u8 = undefined;
+ var was_known: [8]bool = undefined;
+ now.before().read(addr, &old, &was_known) catch return;
+ const moment = now.shown(.memory);
+ const read_shows = now.reading(.memory, 0);
+ if (g.form == .words) {
+ const whole: Rect = .{ .x = cols.cells, .y = cell_y, .w = cols.cell_w, .h = side };
+ const landed = now.landed(.memory, 0);
+ const is_known = std.mem.indexOfScalar(bool, if (landed) &known else &was_known, false) == null;
+ const heat = now.written(addr, 8, .memory, 0);
+ if (!is_known) {
+ _ = u.written(whole, heat, null);
+ u.unknown(whole);
+ } else {
+ // Known for the first time and not written: it fades in, with no mark.
+ const v = if (std.mem.indexOfScalar(bool, &was_known, false) != null and now.writeAge(addr, 8) != 0) u.faded(now.since(.memory, 0) / time.quick) else u;
+ const ink = v.written(whole, heat, theme.color.raised);
+ if (now.wasRead(addr, 8) and now.writeAge(addr, 8) != 0) u.readMark(whole, read_shows);
+ v.hex(size, whole.x + (whole.w - ui.hexWidth(16, size)) / 2, base, std.mem.readInt(u64, if (landed) &bytes else &old, .little), 16, ink);
+ }
+ } else for (0..8) |i| {
+ const cell: Rect = .{ .x = cols.cells + @as(f32, @floatFromInt(i)) * pitch, .y = cell_y, .w = side, .h = side };
+ const a = addr + i;
+ const delay = @as(f32, @floatFromInt(@min(now.writeOffset(a), 16))) * byte_apart;
+ const landed = now.landed(.memory, delay);
+ const heat = now.written(a, 1, .memory, delay);
+ if (!(if (landed) known[i] else was_known[i])) {
+ _ = u.written(cell, heat, null);
+ u.unknown(cell);
+ continue;
+ }
+ const byte = if (landed) bytes[i] else old[i];
+ const v = if (!was_known[i] and now.writeAge(a, 1) != 0) u.faded(now.since(.memory, 0) / time.quick) else u;
+ var ink = v.written(cell, heat, theme.color.raised);
+ if (now.wasRead(a, 1) and now.writeAge(a, 1) != 0) u.readMark(cell, read_shows);
+ // A zero byte is quiet, so data stands out of padding.
+ if (byte == 0 and ink.face == .mono and heat.solid == 0) ink.ink = ui.rgb(t.faint);
+ v.label(ink.face, size, cell, .center, u.print("{x:0>2}", .{byte}), ink.ink);
+ if (g.text) {
+ const tx = cols.text + @as(f32, @floatFromInt(i)) * ui.advance(size);
+ if (std.ascii.isPrint(byte) and byte != ' ') {
+ v.text(.mono, size, tx, base, &.{byte}, t.primary);
+ } else v.fill(.{ .x = tx + 7, .y = cell_y + side / 2 - 2, .w = 4, .h = 4 }, t.faint);
+ }
+ }
+
+ // What the row is: a variable, a struct's field, what a call left.
+ if (variableAt(u, rec, moment, addr)) |v| {
+ u.text(.mono, small, cols.names, base, rec.name(v.name), t.primary);
+ } else if (fieldAt(things, addr)) |found| {
+ u.text(.mono, small, cols.names, base, found.field.name, t.dim);
+ if (found.field.type == .scalar) {
+ if ((Recording.word(moment, addr, @intCast(@min(8, found.field.type.size() orelse 8))) catch null)) |n| u.text(.mono, small, cols.names + 6 * ui.advance(small), base, u.print("= {d}", .{@as(i64, @bitCast(n))}), t.dim);
+ } else if (found.field.type == .pointer and (Recording.word(moment, addr, 8) catch null) == 0) u.text(.mono, small, cols.names + 6 * ui.advance(small), base, "= NULL", t.dim);
+ } else for (calls) |call| {
+ if (call.sp == addr) u.text(.sans, theme.size.sans.note, cols.names, base, "return to", t.dim);
+ }
+ }
+};
+
+/// Whether any byte of the word at `addr` was ever recorded.
+fn knownAny(moment: Recording.Moment, addr: u64) bool {
+ var bytes: [8]u8 = undefined;
+ var known: [8]bool = undefined;
+ moment.read(addr, &bytes, &known) catch return false;
+ return std.mem.indexOfScalar(bool, &known, true) != null;
+}
+
+/// The call whose frame holds stack address `addr`: the newest whose
+/// return address sits at or above it. Null below the stack pointer.
+pub fn frameOf(calls: []const Recording.Call, regs: ?zt.Regs, addr: u64) ?usize {
+ if (regs) |r| if (addr < r.rsp & ~@as(u64, 7)) return null;
+ var i = calls.len;
+ while (i > 0) {
+ i -= 1;
+ if (calls[i].sp >= addr) return i;
+ }
+ return null;
+}
+
+/// The variable that begins in the word at `addr`.
+fn variableAt(u: ui.Ui, rec: *const Recording, moment: Recording.Moment, addr: u64) ?Recording.Variable {
+ const all = moment.variables(u.f.scratch) catch return null;
+ for (all) |v| if (v.addr >= addr and v.addr < addr + 8 and rec.name(v.name).len > 0) return v;
+ return null;
+}
+
+const Found = struct { object: objects.Object, field: Recording.types.Field };
+
+/// The struct field that begins at `addr`, of the structs pointers reach.
+fn fieldAt(things: []const objects.Object, addr: u64) ?Found {
+ for (things) |o| {
+ if (!o.holds(addr)) continue;
+ for (o.type.record.fields) |f| if (o.addr + f.offset == addr) return .{ .object = o, .field = f };
+ }
+ return null;
+}
+
+test "a stack address belongs to the newest frame at or above it" {
+ const calls = [_]Recording.Call{
+ .{ .function = 1, .parent = null, .depth = 0, .sp = 0x1000, .enter = 0 },
+ .{ .function = 2, .parent = 0, .depth = 1, .sp = 0x0fc0, .enter = 1 },
+ };
+ const regs: zt.Regs = .{ .rsp = 0x0fa0 };
+ try std.testing.expectEqual(@as(?usize, 1), frameOf(&calls, regs, 0x0fa0));
+ try std.testing.expectEqual(@as(?usize, 1), frameOf(&calls, regs, 0x0fc0));
+ try std.testing.expectEqual(@as(?usize, 0), frameOf(&calls, regs, 0x0fc8));
+ try std.testing.expectEqual(@as(?usize, 0), frameOf(&calls, regs, 0x1000));
+ try std.testing.expectEqual(@as(?usize, null), frameOf(&calls, regs, 0x1008));
+ try std.testing.expectEqual(@as(?usize, null), frameOf(&calls, regs, 0x0f98));
+}
diff --git a/anim/src/nodes.zig b/anim/src/nodes.zig
new file mode 100644
index 0000000..1326837
--- /dev/null
+++ b/anim/src/nodes.zig
@@ -0,0 +1,273 @@
+//! Data structures as nodes and arrows: the structs the program's pointers
+//! reach from a root variable (`objects.reach`: no offsets are given by
+//! hand, the recording's type descriptions say which fields are pointers
+//! and which is the value). A node's place is its allocation's (the order
+//! it was made in), so nodes stay where they are while pointers change: a
+//! list reversing is its arrows turning round. Variables that point at a
+//! node are tags under it, tracked ones in their pigment, and slide from
+//! node to node as they change; one that holds NULL waits at the row's
+//! end. A node whose memory was freed is hollow and dashed.
+//! This is the idea drawn from memory: it changes a beat after the bytes do.
+//! Reads `Moment.variables`, `Moment.read`, `Moment.allocation`.
+const std = @import("std");
+const sk = @import("sketch");
+const anim = @import("anim");
+const ui = @import("ui.zig");
+const cursors = @import("cursor.zig");
+const Recording = @import("Recording.zig");
+const objects = @import("objects.zig");
+const theme = ui.theme;
+const time = theme.time;
+const Rect = ui.Rect;
+const t = theme.color.text;
+/// A node of a lens beside the context.
+const size = struct {
+ const w = 116;
+ const h = 44;
+ const pointer_w = 44;
+};
+
+pub const Nodes = struct {
+ cursor: cursors.Cursor,
+ box: Rect,
+ title: []const u8 = "the list",
+ note: []const u8 = "what the code means",
+ /// The variable the structure hangs from.
+ root: []const u8,
+ /// Variables each with a pigment (by its place here): the same list a
+ /// memory grid of them is given.
+ track: []const []const u8 = &.{},
+ /// How nodes are placed: in a row (a list), or a row for each distance
+ /// from the root (a tree, a graph). Either way a node's column is its own.
+ arrange: enum { row, levels } = .row,
+ focus: bool = false,
+
+ pub fn draw(g: *const Nodes, f: *sk.Frame, at: anim.Placed) void {
+ const u: ui.Ui = .{ .f = f, .at = at };
+ const now = g.cursor.now(at);
+ const rec = g.cursor.rec;
+ const moment = now.shown(.idea);
+ const body = u.panel(g.box.w, g.box.h, g.title, .{ .focus = g.focus, .note = g.note });
+ const things = objects.reach(f.scratch, rec, moment, null);
+ const before = objects.reach(f.scratch, rec, now.before(), null);
+ if (things.len == 0) {
+ const root = rec.variable(f.scratch, moment, g.root);
+ const empty = root != null and (Recording.word(moment, root.?.addr, 8) catch null) == 0;
+ return u.text(.sans, theme.size.sans.note, theme.metric.panel.pad_x, body.y + 52, if (empty) u.print("empty: {s} is NULL", .{g.root}) else "nothing yet", t.faint);
+ }
+
+ // Columns: one for every node the program will ever make, so no
+ // node moves when another comes or goes. And one more, where a
+ // variable that holds NULL waits.
+ var slots: usize = 0;
+ for (rec.allocations) |a| slots += @intFromBool(a.size == things[0].type.record.size);
+ slots = @max(slots, 1);
+ const count: f32 = @floatFromInt(slots);
+ const park_w = 76;
+ // As a lens beside the context a node is 116 by 44; a gap for an arrow.
+ const node_w = @min(size.w, @floor((body.w - 2 * 20 - park_w) / count) - 28);
+ const gap = @min(56, (body.w - 2 * 20 - park_w - count * node_w) / count);
+ const left: f32 = 24;
+ const row_y = body.y + 36;
+ const park: ui.Vec = .{ left + count * (node_w + gap), row_y - 12 };
+
+ const places = f.scratch.alloc(Rect, things.len) catch return;
+ for (things, places, 0..) |o, *place, i| {
+ const level: f32 = if (g.arrange == .levels) @floatFromInt(distance(f.scratch, rec, moment, things, g.root, i)) else 0;
+ place.* = .{ .x = left + @as(f32, @floatFromInt(o.slot orelse i)) * (node_w + gap), .y = if (g.arrange == .levels) body.y + 40 + level * (size.h + 56) else row_y, .w = node_w, .h = size.h };
+ @import("ties.zig").anchor(u, .{ .node = o.addr }, place.*);
+ // Where it is in the heap, under it: the address the registers' chains to it show, in heap's ink.
+ _ = u.value(place.x, place.y + place.h + 20, o.addr, true, .{ .ink = ui.rgb(theme.color.region.heap) });
+ }
+
+ // Arrows under the nodes they leave.
+ const since = now.since(.idea, 0);
+ var lane: f32 = 0;
+ for (things, places) |o, place| for (o.type.record.fields) |field| {
+ if (field.type != .pointer) continue;
+ const from_addr = o.addr + field.offset;
+ const start = ui.Vec{ place.x + place.w - pointerW(place.w) / 2, place.y + size.h / 2 };
+ const new = if (Recording.word(now.moment(), from_addr, 8) catch null) |target| placeOf(things, places, target) else null;
+ const old = if (Recording.word(now.before(), from_addr, 8) catch null) |target| placeOf(things, places, target) else null;
+ const fresh = now.writeAge(from_addr, 8) == 0;
+ lane += 1;
+ const purple = theme.color.region.heap;
+ if (!fresh or !now.walking()) {
+ // As it stands; at a run a new arrow still grows to its node.
+ if (if (now.landed(.idea, 0)) new else old) |to| u.arrow(route(u, start, place, to, lane), purple, .{ .progress = if (fresh) cursors.standard(now.moving(.idea, 0, time.redirect.head)) else 1 });
+ continue;
+ }
+ // A pointer rewritten, a beat after its word in memory.
+ // Anticipation: as the square is armed the old arrow goes
+ // dashed and faint. Follow-through: the square strikes, the
+ // new arrow grows to the node it now points at, and that
+ // node answers with a bright frame. The old one lingers.
+ const armed = since >= -time.strike.arm;
+ if (old) |to| {
+ const ghost = if (armed) u.faded(1 - std.math.clamp((since - time.redirect.ghost_hold) / time.redirect.ghost_out, 0, 1)) else u;
+ ghost.arrow(route(u, start, place, to, 0), if (armed) ui.rgb(t.faint) else ui.rgb(purple), .{ .dashed = armed, .head = if (armed) null else theme.stroke.head, .width = if (armed) theme.stroke.line else theme.stroke.arrow });
+ }
+ if (new) |to| {
+ u.arrow(route(u, start, place, to, lane), purple, .{ .progress = cursors.standard(std.math.clamp((since - time.snap) / time.redirect.head, 0, 1)) });
+ const landed = since - time.snap - time.redirect.head;
+ const out = theme.metric.pointer_frame_outset;
+ if (landed >= 0 and landed < time.redirect.landing) u.faded(1 - landed / time.redirect.landing).frame(.{ .x = to.x - out, .y = to.y - out, .w = to.w + 2 * out, .h = to.h + 2 * out }, theme.mark(.attention).solid, theme.stroke.line);
+ }
+ };
+
+ for (things, places) |o, place| {
+ const new = for (before) |b| {
+ if (b.addr == o.addr) break false;
+ } else true;
+ // What begins fades in; it does not pop.
+ g.node(if (new) u.faded(now.moving(.idea, 0, time.quick)) else u, now, o, place);
+ }
+ g.tags(u, now, things, places, park);
+ }
+
+ fn node(g: *const Nodes, u: ui.Ui, now: cursors.Now, o: objects.Object, r: Rect) void {
+ _ = g;
+ const moment = now.shown(.idea);
+ const value_w = r.w - pointerW(r.w);
+ const value: Rect = .{ .x = r.x, .y = r.y, .w = value_w, .h = r.h };
+ const pointer: Rect = .{ .x = r.x + value_w, .y = r.y, .w = pointerW(r.w), .h = r.h };
+ if (o.freed) {
+ // Handed back: its bytes are still there, and nobody owns them.
+ u.dashedFrame(r, theme.mark(.freed).solid, theme.stroke.line);
+ } else {
+ // A node is its own colour whoever points at it: pigment is for the names.
+ u.fill(value, theme.color.raised);
+ u.fill(pointer, ui.mix(theme.color.raised, theme.color.page, 0.45));
+ u.fill(.{ .x = pointer.x, .y = r.y, .w = theme.stroke.rule, .h = r.h }, theme.color.page);
+ }
+ if (o.valueField()) |field| {
+ const bytes: usize = @intCast(@min(8, field.type.size() orelse 8));
+ var ink: ui.Ink = .{};
+ if (!o.freed) ink = u.written(value, now.written(o.addr + field.offset, bytes, .idea, 0), null);
+ if (Recording.word(moment, o.addr + field.offset, bytes) catch null) |n| {
+ const shift: u6 = @intCast(64 - 8 * bytes);
+ const signed = @as(i64, @bitCast(n << shift)) >> shift;
+ u.label(ink.face, theme.size.mono.small, value, .center, u.print("{d}", .{signed}), if (o.freed) ui.rgb(t.faint) else ink.ink);
+ } else u.unknown(value);
+ }
+ // The first pointer field: the square its arrow leaves from, or a slash for null.
+ for (o.type.record.fields) |field| {
+ if (field.type != .pointer) continue;
+ const held = Recording.word(moment, o.addr + field.offset, 8) catch null;
+ // On the solid of a strike the square is ink, like digits.
+ const struck = !o.freed and u.written(pointer, now.written(o.addr + field.offset, 8, .idea, 0), null).face == .mono_bold;
+ if (held == null) {
+ u.unknown(pointer);
+ } else if (held.? == 0) {
+ u.line(.{ pointer.x + 12, pointer.y + pointer.h - 10 }, .{ pointer.x + pointer.w - 12, pointer.y + 10 }, if (struck) t.ink else t.dim, theme.stroke.line);
+ } else u.fill(.{ .x = pointer.x + pointer.w / 2 - 7, .y = pointer.y + pointer.h / 2 - 7, .w = 14, .h = 14 }, if (struck) t.ink else theme.color.region.heap);
+ break;
+ }
+ }
+
+ /// The names: the root and the tracked variables, each a tag under
+ /// the node it points at, or at the row's end when it holds NULL.
+ /// What persists slides: a tag goes to its new place as the idea
+ /// strikes, and fades only where it has nowhere to come from.
+ fn tags(g: *const Nodes, u: ui.Ui, now: cursors.Now, things: []const objects.Object, places: []const Rect, park: ui.Vec) void {
+ const rec = g.cursor.rec;
+ const small = theme.size.mono.context;
+ const h = 22;
+ const states = [2]Recording.Moment{ now.before(), now.moment() };
+ const count = 1 + g.track.len;
+ // In each state, where each name points: an address, 0 for NULL, null for nowhere to draw.
+ const held = u.f.scratch.alloc([2]?u64, count) catch return;
+ var parked = false;
+ for (0..count) |i| for (states, 0..) |state, k| {
+ held[i][k] = null;
+ const v = rec.variable(u.f.scratch, state, if (i == 0) g.root else g.track[i - 1]) orelse continue;
+ if (!rec.assigned(v, state.index)) continue;
+ const to = (Recording.word(state, v.addr, 8) catch null) orelse continue;
+ if (to == 0 or placeOf(things, places, to) != null) held[i][k] = to;
+ if (to == 0) parked = true;
+ };
+ if (parked) u.text(.mono, small, park[0], park[1] + 16, "NULL", t.faint);
+ const p = cursors.glide(now.moving(.idea, 0, time.move));
+ for (0..count) |i| {
+ const name = if (i == 0) g.root else g.track[i - 1];
+ var at_place: [2]?ui.Vec = .{ null, null };
+ for (&at_place, 0..) |*place, k| {
+ const to = held[i][k] orelse continue;
+ // Under the names already at the same place.
+ var above: f32 = 0;
+ for (0..i) |other| above += @floatFromInt(@intFromBool(held[other][k] == to));
+ // Beside the names already at the same place: under the node's address, or at the row's end.
+ var width: f32 = 0;
+ for (0..i) |other| if (held[other][k] == to) {
+ width += u.width(.mono, small, if (other == 0) g.root else g.track[other - 1]) + 16 + 4;
+ };
+ place.* = if (to == 0) .{ park[0], park[1] + 24 + above * (h + 2) } else if (placeOf(things, places, to)) |r| .{ r.x + width, r.y + r.h + 28 } else null;
+ }
+ const xy = if (at_place[0] != null and at_place[1] != null) sk.math.mix(at_place[0].?, at_place[1].?, p) else at_place[1] orelse at_place[0] orelse continue;
+ const v = if (at_place[0] == null) u.faded(p) else if (at_place[1] == null) u.faded(1 - p) else u;
+ const tag: Rect = .{ .x = xy[0], .y = xy[1], .w = u.width(.mono, small, name) + 16, .h = h };
+ if (i > 0) v.fill(tag, theme.color.pigment[(i - 1) % theme.color.pigment.len]) else v.frame(tag, t.faint, theme.stroke.rule);
+ v.label(.mono, small, tag, .center, name, t.primary);
+ }
+ }
+};
+
+/// The pointer's square, of a node `w` wide.
+fn pointerW(w: f32) f32 {
+ return @min(size.pointer_w, @round(w * 0.4));
+}
+
+fn placeOf(things: []const objects.Object, places: []const Rect, addr: u64) ?Rect {
+ for (things, places) |o, place| if (o.addr == addr) return place;
+ return null;
+}
+
+/// From the pointer square at `start` (in the node at `from`) to the left
+/// edge of the node at `to`: straight to the neighbour on the right, else
+/// up and over, in a lane of its own.
+fn route(u: ui.Ui, start: ui.Vec, from: Rect, to: Rect, lane: f32) []const ui.Vec {
+ const enter = ui.Vec{ to.x - 2, to.y + to.h / 2 };
+ const out = u.f.scratch.alloc(ui.Vec, 5) catch return &.{};
+ if (@abs(to.y - from.y) < 1 and to.x > from.x and to.x - (from.x + from.w) < 100) {
+ out[0] = start;
+ out[1] = enter;
+ return out[0..2];
+ }
+ // Over the top when going back, under when going on past a neighbour.
+ const over = to.x < from.x or @abs(to.y - from.y) > 1;
+ const y = if (over) @min(from.y, to.y) - 12 - @mod(lane, 2) * 8 else @max(from.y + from.h, to.y + to.h) + 64 + @mod(lane, 2) * theme.stroke.lane_pitch;
+ out[0] = .{ start[0], if (over) from.y else from.y + from.h };
+ out[1] = .{ start[0], y };
+ out[2] = .{ to.x - 26, y };
+ out[3] = .{ to.x - 26, enter[1] };
+ out[4] = enter;
+ return out;
+}
+
+/// How many pointers from the root variable to `things[i]`, at least.
+fn distance(scratch: std.mem.Allocator, rec: *const Recording, moment: Recording.Moment, things: []const objects.Object, root: []const u8, i: usize) usize {
+ const dist = scratch.alloc(usize, things.len) catch return 0;
+ @memset(dist, things.len);
+ if (rec.variable(scratch, moment, root)) |v| if (Recording.word(moment, v.addr, 8) catch null) |first| {
+ for (things, 0..) |o, k| if (o.addr == first) {
+ dist[k] = 0;
+ };
+ };
+ // Few nodes: relax until nothing changes.
+ var changed = true;
+ while (changed) {
+ changed = false;
+ for (things, 0..) |o, k| {
+ if (dist[k] == things.len) continue;
+ for (o.type.record.fields) |field| {
+ if (field.type != .pointer) continue;
+ const target = (Recording.word(moment, o.addr + field.offset, 8) catch null) orelse continue;
+ for (things, 0..) |other, j| if (other.addr == target and dist[j] > dist[k] + 1) {
+ dist[j] = dist[k] + 1;
+ changed = true;
+ };
+ }
+ }
+ }
+ return if (dist[i] == things.len) 0 else dist[i];
+}
diff --git a/anim/src/objects.zig b/anim/src/objects.zig
new file mode 100644
index 0000000..57e2b11
--- /dev/null
+++ b/anim/src/objects.zig
@@ -0,0 +1,166 @@
+//! What the program's pointers reach: the structs found by following typed
+//! pointers through recorded memory, from the live variables (`ztrace cc`
+//! describes every variable's type, and each struct's fields). The
+//! node-link view draws them; the memory grid names their rows after them.
+const std = @import("std");
+const Recording = @import("Recording.zig");
+const types = Recording.types;
+
+pub const Object = struct {
+ addr: u64,
+ /// A struct or union: `record.fields`, `record.size`.
+ type: types.Type,
+ /// Its place among the objects of its kind, for good: the order its
+ /// allocation was made in. Null for one that is not on the heap.
+ slot: ?usize,
+ /// Its allocation is gone: something still points at freed memory.
+ freed: bool,
+
+ pub fn holds(o: Object, addr: u64) bool {
+ return addr >= o.addr and addr - o.addr < o.type.record.size;
+ }
+
+ /// The first field that is a plain number: what a node shows as its value.
+ pub fn valueField(o: Object) ?types.Field {
+ for (o.type.record.fields) |f| if (f.type == .scalar) return f;
+ return null;
+ }
+};
+
+/// A pointer field of a struct, or a pointer variable: where it is and what
+/// it holds (null: bytes never recorded).
+pub const Link = struct { from: u64, to: ?u64 };
+
+/// Every struct reachable at `m` from the live pointer variables (from the
+/// one called `root`, when given), nearest first, in `scratch`.
+/// shortcut: 64 objects at most; a bigger structure wants a view of part of it.
+pub fn reach(scratch: std.mem.Allocator, rec: *const Recording, m: Recording.Moment, root: ?[]const u8) []Object {
+ var found: std.ArrayList(Object) = .empty;
+ const variables = m.variables(scratch) catch return &.{};
+ for (variables) |v| {
+ if (root) |name| if (!std.mem.eql(u8, rec.name(v.name), name)) continue;
+ // A local its call has yet to assign points wherever that stretch of stack did before.
+ if (!rec.assigned(v, m.index)) continue;
+ const t = rec.typeOf(scratch, v.type) orelse continue;
+ if (t == .pointer) follow(scratch, rec, m, &found, v.addr, t.pointer.*);
+ }
+ // Then what they point at, and so on: `found` grows as it is read.
+ var i: usize = 0;
+ while (i < found.items.len) : (i += 1) {
+ const o = found.items[i];
+ for (o.type.record.fields) |f| if (f.type == .pointer) follow(scratch, rec, m, &found, o.addr + f.offset, f.type.pointer.*);
+ }
+ return found.items;
+}
+
+/// Adds the struct the pointer at `at` points to, if it is one and is new.
+fn follow(scratch: std.mem.Allocator, rec: *const Recording, m: Recording.Moment, found: *std.ArrayList(Object), at: u64, pointee: types.Type) void {
+ if (found.items.len >= 64) return;
+ const t = rec.resolve(scratch, pointee) orelse return;
+ if (t != .record) return;
+ const addr = (Recording.word(m, at, 8) catch return) orelse return;
+ if (addr == 0) return;
+ for (found.items) |o| if (o.addr == addr) return;
+ const live = (m.allocation(addr) catch null) != null;
+ found.append(scratch, .{ .addr = addr, .type = t, .slot = slotOf(rec, addr, m), .freed = !live and wasAllocated(rec, addr, m.index) }) catch {};
+}
+
+/// The place of the allocation at `addr` among every allocation of its
+/// size ever made, in the order they were made: it never changes, so a
+/// node drawn there stays there as the structure grows and shrinks.
+/// shortcut: other things of the same size allocated between nodes leave gaps.
+pub fn slotOf(rec: *const Recording, addr: u64, m: Recording.Moment) ?usize {
+ const born = latest(rec, addr, m.index) orelse return null;
+ var slot: usize = 0;
+ for (rec.allocations[0..born]) |a| slot += @intFromBool(a.size == rec.allocations[born].size);
+ return slot;
+}
+
+fn wasAllocated(rec: *const Recording, addr: u64, moment: u64) bool {
+ return latest(rec, addr, moment) != null;
+}
+
+/// The newest allocation at `addr` made by `moment`.
+fn latest(rec: *const Recording, addr: u64, moment: u64) ?usize {
+ var i = rec.allocations.len;
+ while (i > 0) {
+ i -= 1;
+ const a = rec.allocations[i];
+ if (a.moment <= moment and a.ptr == addr) return i;
+ }
+ return null;
+}
+
+/// A type as C spells it (the programs recorded are C): `int`, `node *`.
+pub fn spell(scratch: std.mem.Allocator, t: types.Type) []const u8 {
+ return switch (t) {
+ .void => "void",
+ .scalar => |s| switch (s.kind) {
+ .int => switch (s.bits) {
+ 8 => "signed char",
+ 16 => "short",
+ 32 => "int",
+ else => "long",
+ },
+ .uint => switch (s.bits) {
+ 8 => "unsigned char",
+ 16 => "unsigned short",
+ 32 => "unsigned",
+ else => "unsigned long",
+ },
+ .float => if (s.bits == 32) "float" else "double",
+ .char => "char",
+ .bool => "bool",
+ .@"opaque" => "?",
+ },
+ .pointer => |to| std.fmt.allocPrint(scratch, "{s} *", .{spell(scratch, to.*)}) catch "?",
+ .array => |a| std.fmt.allocPrint(scratch, "{s} [{d}]", .{ spell(scratch, a.elem.*), a.len }) catch "?",
+ .named => |name| name,
+ .record => "struct",
+ .@"enum" => "enum",
+ .function => "function",
+ };
+}
+
+/// A variable as C declares it: `int a[8]`, `node *prev`, `long n`.
+pub fn declare(scratch: std.mem.Allocator, rec: *const Recording, v: Recording.Variable) []const u8 {
+ const name = rec.name(v.name);
+ const t = types.parse(scratch, rec.strings.get(v.type) orelse return name) catch return name;
+ return switch (t) {
+ .array => |a| std.fmt.allocPrint(scratch, "{s} {s}[{d}]", .{ spell(scratch, a.elem.*), name, a.len }) catch name,
+ .pointer => std.fmt.allocPrint(scratch, "{s}{s}", .{ spell(scratch, t), name }) catch name,
+ else => std.fmt.allocPrint(scratch, "{s} {s}", .{ spell(scratch, t), name }) catch name,
+ };
+}
+
+/// The live variables that hold `addr`: the names a node goes by. Not one
+/// its call has yet to assign: what its stretch of stack held before is
+/// not its value.
+pub fn pointing(scratch: std.mem.Allocator, rec: *const Recording, m: Recording.Moment, addr: u64) []Recording.Variable {
+ var out: std.ArrayList(Recording.Variable) = .empty;
+ const variables = m.variables(scratch) catch return &.{};
+ for (variables) |v| {
+ if (v.size != 8 or rec.name(v.name).len == 0 or !rec.assigned(v, m.index)) continue;
+ if ((Recording.word(m, v.addr, 8) catch null) == addr) out.append(scratch, v) catch break;
+ }
+ return out.items;
+}
+
+/// Which of `tracked` (variable names, each with a pigment by its place)
+/// holds `addr`: the first, null when none does.
+pub fn pigment(scratch: std.mem.Allocator, rec: *const Recording, m: Recording.Moment, tracked: []const []const u8, addr: u64) ?usize {
+ for (tracked, 0..) |name, i| {
+ const v = rec.variable(scratch, m, name) orelse continue;
+ if (rec.assigned(v, m.index) and (Recording.word(m, v.addr, 8) catch null) == addr) return i;
+ }
+ return null;
+}
+
+test "types are spelled as C spells them" {
+ var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
+ defer arena.deinit();
+ const int: types.Type = .{ .scalar = .{ .kind = .int, .bits = 32 } };
+ try std.testing.expectEqualStrings("int", spell(arena.allocator(), int));
+ try std.testing.expectEqualStrings("node *", spell(arena.allocator(), .{ .pointer = &.{ .named = "node" } }));
+ try std.testing.expectEqualStrings("int [8]", spell(arena.allocator(), .{ .array = .{ .len = 8, .elem = &int } }));
+}
diff --git a/anim/src/registers.zig b/anim/src/registers.zig
new file mode 100644
index 0000000..5f08d6f
--- /dev/null
+++ b/anim/src/registers.zig
@@ -0,0 +1,117 @@
+//! The variables of the innermost call, as a table: names, types as C
+//! spells them, values, each struck when memory is (a variable is
+//! memory). The registers are `context.Registers`.
+//! Reads `Moment.variables`, `Moment.read`.
+const std = @import("std");
+const sk = @import("sketch");
+const anim = @import("anim");
+const ui = @import("ui.zig");
+const cursors = @import("cursor.zig");
+const Cursor = cursors.Cursor;
+const Recording = @import("Recording.zig");
+const objects = @import("objects.zig");
+const theme = ui.theme;
+const Rect = ui.Rect;
+const size = theme.size.mono.dense;
+const m = struct {
+ const row_h = theme.metric.dense.row_h;
+ const name_x = theme.metric.panel.pad_x;
+ const value_pad = 4;
+};
+/// Of two things one step does the same to, the second follows the first.
+const second = theme.time.flight.second;
+
+pub const Locals = struct {
+ cursor: Cursor,
+ box: Rect,
+ /// Names to show, in order; empty for every variable of the innermost
+ /// call, then the globals.
+ names: []const []const u8 = &.{},
+ focus: bool = false,
+
+ pub fn draw(l: *const Locals, f: *sk.Frame, at: anim.Placed) void {
+ const u: ui.Ui = .{ .f = f, .at = at };
+ const now = l.cursor.now(at);
+ const rec = l.cursor.rec;
+ const moment = now.moment();
+ const calls = rec.stack(f.scratch, now.stops[0]);
+ const where = if (calls.len > 0) u.print("{s}()", .{rec.name(calls[calls.len - 1].function)}) else "";
+ const body = u.panel(l.box.w, l.box.h, "locals", .{ .focus = l.focus, .note = where });
+ const all = moment.variables(f.scratch) catch return;
+ const depth: u32 = @intCast(calls.len);
+
+ var y = body.y + 8;
+ const room: usize = @intFromFloat(@floor((body.h - 16) / m.row_h));
+ var shown: usize = 0;
+ var struck: f32 = 0;
+ if (l.names.len > 0) {
+ for (l.names) |name| {
+ const v = rec.variable(f.scratch, moment, name) orelse continue;
+ if (shown < room) l.row(u, now, v, y, &struck);
+ y += m.row_h;
+ shown += 1;
+ }
+ return;
+ }
+ // The innermost call's, then the globals.
+ for ([_]u32{ depth, 0 }) |want| for (all) |v| {
+ if (v.depth != want or rec.name(v.name).len == 0 or shown == room) continue;
+ l.row(u, now, v, y, &struck);
+ y += m.row_h;
+ shown += 1;
+ };
+ }
+
+ fn row(l: *const Locals, u: ui.Ui, now: cursors.Now, v: Recording.Variable, y: f32, struck: *f32) void {
+ const rec = l.cursor.rec;
+ const base = theme.baseline(y, m.row_h, size);
+ const adv = ui.advance(size);
+ const small = size;
+ const name = rec.name(v.name);
+ u.text(.mono, size, m.name_x, base, name, theme.color.text.primary);
+ const type_x = m.name_x + @max(5, @as(f32, @floatFromInt(name.len)) + 2) * adv;
+ const kind = if (Recording.types.parse(u.f.scratch, rec.strings.get(v.type) orelse "")) |t| objects.spell(u.f.scratch, t) else |_| "";
+ u.text(.mono, small, type_x, base, kind[0..@min(kind.len, 8)], theme.color.text.faint);
+
+ const value_x = type_x + 9 * ui.advance(small);
+ // A variable is memory: it changes when memory does, the second
+ // one a step wrote a little after the first.
+ const age = now.writeAge(v.addr, v.size);
+ const delay = if (age == 0) struck.* * second else 0;
+ if (age == 0) struck.* += 1;
+ const landed = now.landed(.memory, delay);
+ // Not yet assigned in this call: its bytes are not its value.
+ const text = (if (rec.assigned(v, if (landed) now.stops[0] else now.stops[1])) describe(u, rec, if (landed) now.moment() else now.before(), v) else null) orelse {
+ _ = u.written(.{ .x = value_x - m.value_pad, .y = y + 2, .w = 3 * adv + 2 * m.value_pad, .h = m.row_h - 4 }, now.written(v.addr, v.size, .memory, delay), null);
+ return u.unknown(.{ .x = value_x, .y = y, .w = 3 * adv, .h = m.row_h });
+ };
+ const cell: Rect = .{ .x = value_x - m.value_pad, .y = y + 2, .w = @as(f32, @floatFromInt(text.len)) * adv + 2 * m.value_pad, .h = m.row_h - 4 };
+ const ink = u.written(cell, now.written(v.addr, v.size, .memory, delay), null);
+ if (now.wasRead(v.addr, v.size) and age != 0) u.readMark(cell, now.reading(.memory, 0));
+ u.text(ink.face, size, value_x, base, text, ink.ink);
+ }
+};
+
+/// A variable's value as its type says to read it: a number in decimal, a
+/// pointer in hex, an array as its first elements.
+fn describe(u: ui.Ui, rec: *const Recording, moment: Recording.Moment, v: Recording.Variable) ?[]const u8 {
+ const t = rec.typeOf(u.f.scratch, v.type) orelse return plain(u, moment, v.addr, v.size, false);
+ return switch (t) {
+ .scalar => |s| plain(u, moment, v.addr, v.size, s.kind == .int),
+ .pointer => blk: {
+ const to = (Recording.word(moment, v.addr, 8) catch return null) orelse return null;
+ var buf: [20]u8 = undefined;
+ break :blk if (to == 0) "NULL" else u.print("{s}", .{ui.grouped(&buf, to)});
+ },
+ .array => |a| u.print("[{d}]", .{a.len}),
+ else => null,
+ };
+}
+
+fn plain(u: ui.Ui, moment: Recording.Moment, addr: u64, bytes: u64, signed: bool) ?[]const u8 {
+ if (bytes == 0 or bytes > 8) return null;
+ const raw = (Recording.word(moment, addr, @intCast(bytes)) catch return null) orelse return null;
+ if (!signed) return u.print("{d}", .{raw});
+ const shift: u6 = @intCast(64 - 8 * bytes);
+ return u.print("{d}", .{@as(i64, @bitCast(raw << shift)) >> shift});
+}
diff --git a/anim/src/root.zig b/anim/src/root.zig
new file mode 100644
index 0000000..82cf8d3
--- /dev/null
+++ b/anim/src/root.zig
@@ -0,0 +1,303 @@
+//! canim: animations of how a program ran, from a ztrace recording, on
+//! sketchbook's `anim`. A scene is a short function:
+//!
+//! const canim = @import("canim");
+//! const rec = canim.open(recordings.sort);
+//! const at = canim.cursor(s, rec, 0); // where the picture is
+//! const ctx = canim.context(s, at, .{}); // the debugger's whole context
+//! canim.establish(s, .{ ctx.clock, ctx.source, ctx.disasm, ctx.registers, ctx.stack, ctx.backtrace });
+//! at.walk(s, .line, rec.call("sort", 0).enter); // play the program forward
+//!
+//! Every component is an `anim` object (`fadeIn`, `move`, ...) that draws
+//! the program's state at the cursor, and what the step being taken does,
+//! in the order it would be said: the line fires, its effects land a level
+//! at a time, the mark moves on (design/motion.md).
+const std = @import("std");
+const anim = @import("anim");
+
+pub const theme = @import("theme.zig");
+pub const layout = theme.layout;
+pub const ui = @import("ui.zig");
+pub const Rect = theme.Rect;
+pub const Recording = @import("Recording.zig");
+const cursors = @import("cursor.zig");
+pub const Cursor = cursors.Cursor;
+pub const Now = cursors.Now;
+pub const Plan = cursors.Plan;
+pub const Levels = cursors.Levels;
+
+pub const Source = @import("source.zig").Source;
+const contexts = @import("context.zig");
+pub const Registers = contexts.Registers;
+pub const Stack = contexts.Stack;
+pub const Backtrace = contexts.Backtrace;
+pub const Disasm = contexts.Disasm;
+pub const Locals = @import("registers.zig").Locals;
+pub const calls = @import("calls.zig");
+pub const CallTree = calls.Tree;
+pub const Memory = @import("memory.zig").Memory;
+pub const Nodes = @import("nodes.zig").Nodes;
+pub const Heap = @import("heap.zig").Heap;
+pub const Hexdump = @import("hexdump.zig").Hexdump;
+const tying = @import("ties.zig");
+pub const Ties = tying.Ties;
+pub const Place = tying.Place;
+pub const Array = @import("array.zig").Array;
+pub const syscalls = @import("syscalls.zig");
+pub const Crossing = syscalls.Crossing;
+pub const Timeline = syscalls.Timeline;
+pub const objects = @import("objects.zig");
+const words = @import("words.zig");
+pub const Clock = words.Clock;
+pub const Caption = words.Caption;
+pub const Label = words.Label;
+pub const Veil = words.Veil;
+pub const Legend = words.Legend;
+
+/// The page behind every scene: `pub const background = canim.background;`.
+pub const background: u32 = theme.color.page;
+
+pub const open = Recording.open;
+pub const lookAt = ui.lookAt;
+
+/// A cursor on `rec`, at rest at moment `start`.
+pub fn cursor(s: *anim.Frame, rec: *Recording, start: u64) Cursor {
+ return .init(s, rec, start);
+}
+
+/// The design's easing curves, as `play` takes them.
+pub const ease = struct {
+ pub fn standard(t: f32) f32 {
+ return theme.ease(.standard, t);
+ }
+ pub fn enter(t: f32) f32 {
+ return theme.ease(.enter, t);
+ }
+ pub fn exit(t: f32) f32 {
+ return theme.ease(.exit, t);
+ }
+ pub fn glide(t: f32) f32 {
+ return theme.ease(.glide, t);
+ }
+};
+
+const time = theme.time;
+
+/// Brings `views` (a tuple of them) in, each a little after the one
+/// before, in the order given: the source first (overlapping action).
+/// Opacity is linear: a fade has no weight.
+pub fn enter(s: *anim.Frame, views: anytype) void {
+ const start = s.cursor;
+ inline for (views, 0..) |o, i| {
+ s.cursor = start + @as(f32, @floatFromInt(i)) * time.snap;
+ s.play(.{o.fadeIn()}, .{ .seconds = time.cascade, .ease = anim.ease.linear });
+ }
+}
+
+/// A scene's opening: the clock and the panels come in (`enter`), and
+/// then the picture is still long enough to be read, a second and half a
+/// second for each panel, before a word is said about it.
+pub fn establish(s: *anim.Frame, views: anytype) void {
+ enter(s, views);
+ s.wait(time.establish + time.establish_per_panel * @as(f32, @floatFromInt(views.len - 1)));
+}
+
+/// And takes them away: quicker than they came.
+pub fn leave(s: *anim.Frame, views: anytype) void {
+ if (views.len == 0) return;
+ var all: [views.len]anim.Animation = undefined;
+ inline for (views, 0..) |o, i| all[i] = o.fadeOut();
+ s.play(all, .{ .seconds = time.camera_clear, .ease = anim.ease.linear });
+}
+
+/// The narrator: one caption at a time, and only while nothing else
+/// moves. The old one leaves, then nothing, then the new one arrives (two
+/// crossfading are an unreadable third); and the stage stays still after
+/// it, longer after a scene's first: the eye reads, then is shown.
+pub const Narrator = struct {
+ current: ?anim.Obj = null,
+
+ pub fn line(n: *Narrator, s: *anim.Frame, text: []const u8) void {
+ const next = add(s, Caption{ .text = text });
+ if (n.current) |old| {
+ s.play(.{old.fadeOut()}, .{ .seconds = time.caption_out, .ease = ease.exit });
+ s.wait(time.caption_gap);
+ }
+ s.play(.{next.fadeIn()}, .{ .seconds = time.caption_in, .ease = ease.enter });
+ s.wait(if (n.current == null) time.caption_lead_first else time.caption_lead);
+ n.current = next;
+ }
+};
+
+/// The camera, directed: a way of reading the context, not a place to be
+/// instead of it. It never leaves unannounced: its target is framed
+/// bright, everything else on the stage is gone before it moves (the
+/// clock and the caption stay), it moves alone, and then the picture is
+/// still; and it comes back to the whole frame every time. Call `apply`
+/// last in the scene's `frame`.
+pub const Camera = struct {
+ at: anim.Camera = .{},
+ moves: [8]Move = undefined,
+ count: usize = 0,
+
+ const Move = struct { from: anim.Camera, to: anim.Camera, p: anim.Value };
+
+ /// Nearer: to design rect `box` at `zoom` (1.5, 2 or 4), with `others`
+ /// (a tuple of the views that are not its subject) cleared first.
+ pub fn go(c: *Camera, s: *anim.Frame, box: Rect, zoom: f32, others: anytype) void {
+ // Anticipation: where it is going, before it goes.
+ const frame = add(s, words.Outline{ .box = box });
+ const start = s.cursor;
+ s.play(.{frame.fadeIn()}, .{ .seconds = time.snap, .ease = anim.ease.linear });
+ s.cursor = start + time.quick;
+ leave(s, others);
+ s.cursor = @max(s.cursor, start + time.camera_before);
+ const moving = s.cursor;
+ s.play(.{frame.fadeOut()}, .{ .seconds = time.quick, .ease = anim.ease.linear });
+ s.cursor = moving;
+ c.move(s, ui.framing(box, zoom), time.camera);
+ s.wait(time.camera_after);
+ }
+
+ /// Back to the whole frame: the move, then `others` come in again, then stillness.
+ pub fn back(c: *Camera, s: *anim.Frame, others: anytype) void {
+ c.move(s, .{}, time.camera);
+ enter(s, others);
+ s.wait(time.camera_after);
+ }
+
+ fn move(c: *Camera, s: *anim.Frame, to: anim.Camera, seconds: f32) void {
+ const p = s.value(0);
+ c.moves[c.count] = .{ .from = c.at, .to = to, .p = p };
+ c.count += 1;
+ c.at = to;
+ // Slow in and slow out: the camera has weight.
+ s.play(.{p.to(1)}, .{ .seconds = seconds, .ease = ease.glide });
+ }
+
+ /// Puts the scene's camera where the moves so far have it at this instant.
+ pub fn apply(c: *const Camera, s: *anim.Frame) void {
+ var view: anim.Camera = .{};
+ for (c.moves[0..c.count]) |m| {
+ const p = s.get(m.p);
+ if (p > 0) view = ui.between(m.from, m.to, p);
+ }
+ s.camera().* = view;
+ }
+};
+
+/// The debugger's whole context, the same in every scene: the state
+/// column (every register followed as far as it points, the stack as a
+/// telescope, the backtrace), and in the program column the source (all
+/// of it, in a window) and the disassembly at the pc; and the clock.
+/// A scene adds its lens at `split.lens`: a lens is never shown instead
+/// of the machine it is drawn from.
+pub const Context = struct {
+ clock: anim.Obj,
+ source: anim.Obj,
+ disasm: anim.Obj,
+ registers: anim.Obj,
+ stack: anim.Obj,
+ backtrace: anim.Obj,
+
+ pub const Options = struct {
+ /// How the program column is shared (`layout.split`).
+ split: layout.Split = layout.split.beside,
+ /// A program that makes system calls: see `Registers.syscalls`.
+ syscalls: bool = false,
+ /// An instrumented program: see `Registers.quiet`.
+ quiet: bool = false,
+ };
+};
+
+pub fn context(s: *anim.Frame, at: Cursor, options: Context.Options) Context {
+ const source_at = add(s, Source{ .cursor = at, .box = options.split.source });
+ const disasm_at = add(s, Disasm{ .cursor = at, .box = options.split.disasm });
+ const registers_at = add(s, Registers{ .cursor = at, .syscalls = options.syscalls, .quiet = options.quiet });
+ const stack_at = add(s, Stack{ .cursor = at });
+ const backtrace_at = add(s, Backtrace{ .cursor = at });
+ return .{ .clock = add(s, Clock{ .cursor = at }), .source = source_at, .disasm = disasm_at, .registers = registers_at, .stack = stack_at, .backtrace = backtrace_at };
+}
+
+/// Any component (a struct of this module with a `box`), in the scene
+/// where its box says. The functions below are this, by name.
+pub fn add(s: *anim.Frame, component: anytype) anim.Obj {
+ return ui.place(s, component, component.box.x, component.box.y);
+}
+
+pub fn source(s: *anim.Frame, options: Source) anim.Obj {
+ return add(s, options);
+}
+pub fn registers(s: *anim.Frame, options: Registers) anim.Obj {
+ return add(s, options);
+}
+pub fn stack(s: *anim.Frame, options: Stack) anim.Obj {
+ return add(s, options);
+}
+pub fn disasm(s: *anim.Frame, options: Disasm) anim.Obj {
+ return add(s, options);
+}
+pub fn locals(s: *anim.Frame, options: Locals) anim.Obj {
+ return add(s, options);
+}
+pub fn callTree(s: *anim.Frame, options: CallTree) anim.Obj {
+ return add(s, options);
+}
+pub fn memory(s: *anim.Frame, options: Memory) anim.Obj {
+ return add(s, options);
+}
+pub fn nodes(s: *anim.Frame, options: Nodes) anim.Obj {
+ return add(s, options);
+}
+pub fn heap(s: *anim.Frame, options: Heap) anim.Obj {
+ return add(s, options);
+}
+pub fn hexdump(s: *anim.Frame, options: Hexdump) anim.Obj {
+ return add(s, options);
+}
+/// The connections between panes. Add it after every view it is to join.
+pub fn ties(s: *anim.Frame, options: Ties) anim.Obj {
+ return add(s, options);
+}
+pub fn array(s: *anim.Frame, options: Array) anim.Obj {
+ return add(s, options);
+}
+/// The kernel's ground. Make a step that crosses it with `syscalls.step`.
+pub fn crossing(s: *anim.Frame, options: Crossing) anim.Obj {
+ return add(s, options);
+}
+pub fn timeline(s: *anim.Frame, options: Timeline) anim.Obj {
+ return add(s, options);
+}
+pub fn caption(s: *anim.Frame, text: []const u8) anim.Obj {
+ return add(s, Caption{ .text = text });
+}
+pub fn label(s: *anim.Frame, options: Label) anim.Obj {
+ return add(s, options);
+}
+pub fn veil(s: *anim.Frame, around: Rect) anim.Obj {
+ return add(s, Veil{ .box = around });
+}
+pub fn legend(s: *anim.Frame, options: Legend) anim.Obj {
+ return add(s, options);
+}
+
+test {
+ _ = theme;
+ _ = ui;
+ _ = Recording;
+ _ = cursors;
+ _ = @import("source.zig");
+ _ = @import("registers.zig");
+ _ = contexts;
+ _ = tying;
+ _ = @import("hexdump.zig");
+ _ = calls;
+ _ = @import("memory.zig");
+ _ = @import("nodes.zig");
+ _ = @import("heap.zig");
+ _ = @import("array.zig");
+ _ = @import("syscalls.zig");
+ _ = objects;
+ _ = words;
+}
diff --git a/anim/src/source.zig b/anim/src/source.zig
new file mode 100644
index 0000000..6c10b50
--- /dev/null
+++ b/anim/src/source.zig
@@ -0,0 +1,193 @@
+//! The source panel: the program's text as pardes colours it, line numbers,
+//! the current mark (gold: a band along the line and a plaque over its
+//! number), and the three lines before it (the trail, gold cooling). The
+//! mark fires on the line about to run, and moves on last, when what the
+//! line did has been seen: a slide to a line near by, a jump (out, then
+//! in) into a call or out of one.
+//! Reads `Moment.line` (through the recording's index of it).
+const std = @import("std");
+const sk = @import("sketch");
+const anim = @import("anim");
+const pardes = @import("pardes-syntax");
+const ui = @import("ui.zig");
+const cursors = @import("cursor.zig");
+const Cursor = cursors.Cursor;
+const theme = ui.theme;
+const Rect = ui.Rect;
+
+const gpa = std.heap.smp_allocator;
+
+pub const Source = struct {
+ cursor: Cursor,
+ box: Rect,
+ focus: bool = false,
+
+ pub fn draw(p: *const Source, f: *sk.Frame, at: anim.Placed) void {
+ const u: ui.Ui = .{ .f = f, .at = at };
+ const rec = p.cursor.rec;
+ const now = p.cursor.now(at);
+ const size = theme.size.mono.context;
+ const adv = ui.advance(size);
+ const text = prepared(rec.source, rec.file) orelse return;
+ const fit: u32 = @intFromFloat(@floor((p.box.h - m.tag - 2 * m.pad) / m.row));
+ // The mark: leaving the line of one moment for that of the next.
+ const was = rec.own[now.marks[0]];
+ const here = rec.own[now.marks[1]];
+ const on_line = rec.own[now.marked()];
+ // The window: where the line it is on has it, and (as the mark
+ // moves on) gliding to where the next one does. It never cuts.
+ const going = now.advancing();
+ const windows = [2]f32{ @floatFromInt(rec.viewFirst(fit, was)), @floatFromInt(rec.viewFirst(fit, here)) };
+ const first = std.math.lerp(windows[0], windows[1], cursors.glide(going));
+ const from: u32 = @intFromFloat(@floor(first));
+ const last: u32 = @min(from + fit, rec.line_count);
+ const body = u.panel(p.box.w, p.box.h, rec.file, .{ .focus = p.focus, .note = if (rec.line_count > fit) u.print("lines {d} to {d} of {d}", .{ from, @min(from + fit - 1, rec.line_count), rec.line_count }) else u.print("{d} lines", .{rec.line_count}) });
+ const top = body.y + m.pad;
+ const gutter = 3 * adv + 22;
+ const code_x = gutter + 12;
+ const max_chars: usize = @intFromFloat(@floor((p.box.w - code_x - m.side) / adv));
+
+ // Where the mark is, and how much of it.
+ const current = theme.mark(.current);
+ const travel = now.plan.travel;
+ const moved = going * travel;
+ const scrolls = windows[0] != windows[1];
+ var mark_line = here;
+ var mark_at: f32 = @floatFromInt(here);
+ var shows: f32 = 1;
+ if (going < 1) {
+ if (!cursors.jumps(rec, now.marks[0], now.marks[1])) {
+ // A line near by: it slides, off promptly and settling on
+ // the next. The step's follow-through.
+ mark_at = std.math.lerp(@as(f32, @floatFromInt(was)), mark_at, cursors.standard(going));
+ if (@abs(mark_at - @as(f32, @floatFromInt(was))) < 0.5) mark_line = was;
+ } else {
+ // A call, a return, a line far off: a jump. Out there, then
+ // in here; it does not cross the lines between.
+ const half = @min(theme.time.current_jump, travel / 2);
+ if (moved < travel - half) {
+ mark_line = was;
+ mark_at = @floatFromInt(was);
+ shows = 1 - std.math.clamp(moved / half, 0, 1);
+ } else shows = std.math.clamp((moved - (travel - half)) / half, 0, 1);
+ }
+ }
+ const mark_y = top + (mark_at - first) * m.row;
+ u.clip(.{ .x = theme.stroke.rule, .y = body.y + 2, .w = p.box.w - 2 * theme.stroke.rule, .h = body.h - 4 });
+ const marked = u.faded(shows);
+ if (shows > 0) marked.fill(.{ .x = theme.stroke.rule, .y = mark_y, .w = p.box.w - 2 * theme.stroke.rule, .h = m.row }, current.ember);
+
+ // The trail: the last three other lines it was on. It shifts without animation.
+ var trail: [3]u32 = @splat(0);
+ var found: usize = 0;
+ var back = now.marked();
+ while (back > 0 and found < trail.len) {
+ back -= 1;
+ const l = rec.own[back];
+ if (l == 0 or l == on_line or std.mem.indexOfScalar(u32, trail[0..found], l) != null) continue;
+ trail[found] = l;
+ found += 1;
+ }
+ for (trail[0..found], 0..) |l, k| u.fill(.{ .x = theme.stroke.rule, .y = top + (@as(f32, @floatFromInt(l)) - first) * m.row + 2, .w = 4, .h = m.row - 4 }, theme.color.trail[k]);
+
+ // The plaque over the number. Fire: on the line about to run its
+ // edges go out and come back, once, and nothing else moves.
+ const out = now.fires(.source);
+ if (shows > 0) marked.fill(.{ .x = theme.stroke.rule - out, .y = mark_y - out, .w = gutter - 2 + 2 * out, .h = m.row + 2 * out }, current.solid);
+ if (shows >= 1 and mark_y >= body.y and mark_y + m.row <= body.y + body.h) @import("ties.zig").anchor(u, .source, .{ .x = 0, .y = mark_y, .w = gutter, .h = m.row });
+
+ var line = @max(from, 1);
+ while (line <= last) : (line += 1) {
+ const y = top + (@as(f32, @floatFromInt(line)) - first) * m.row;
+ const row: Rect = .{ .x = 0, .y = y, .w = gutter - 10, .h = m.row };
+ // The number under the plaque is the one in ink.
+ const on = shows >= 0.5 and line == mark_line and !(scrolls and going > 0 and going < 1 and line != here);
+ u.label(if (on) .mono_bold else .mono, size, row, .right, u.print("{d}", .{line}), if (on) current.on_solid else theme.color.text.faint);
+ const span = text.lines[line - 1];
+ const bytes = text.bytes[span[0]..span[1]];
+ const styles = text.styles[span[0]..span[1]];
+ // Runs of one class, each set where its column is.
+ var i: usize = 0;
+ const end = @min(bytes.len, max_chars);
+ while (i < end) {
+ var j = i + 1;
+ while (j < end and styles[j] == styles[i]) j += 1;
+ const class: pardes.Syn = @enumFromInt(styles[i]);
+ const x = code_x + @as(f32, @floatFromInt(i)) * adv;
+ if (std.mem.indexOfNone(u8, bytes[i..j], " ") != null) u.text(face(class), size, x, theme.baseline(y, m.row, size), bytes[i..j], ink(class));
+ i = j;
+ }
+ // A line longer than the panel is cut, and says so.
+ if (bytes.len > max_chars) u.text(.mono, size, code_x + @as(f32, @floatFromInt(max_chars)) * adv, theme.baseline(y, m.row, size), "\u{2026}", theme.color.text.faint);
+ }
+ u.unclip();
+ }
+};
+
+const m = theme.metric.context;
+
+fn ink(class: pardes.Syn) u24 {
+ const c = theme.color.code;
+ return switch (class) {
+ .none => c.plain,
+ .keyword => c.keyword,
+ .string, .number => c.literal,
+ .comment => c.comment,
+ };
+}
+
+fn face(class: pardes.Syn) ui.Face {
+ return switch (class) {
+ .keyword => .mono_bold,
+ .comment => .mono_italic,
+ else => .mono,
+ };
+}
+
+/// A source ready to draw: a class for each byte, and where each line is.
+const Text = struct {
+ bytes: []const u8,
+ styles: []const u8,
+ lines: []const [2]usize,
+};
+
+/// Made once for each source and kept: a scene draws the same few.
+var texts: std.ArrayList(Text) = .empty;
+
+fn prepared(source: []const u8, file: []const u8) ?*const Text {
+ for (texts.items) |*t| if (t.bytes.ptr == source.ptr) return t;
+ texts.append(gpa, prepare(source, file) catch return null) catch return null;
+ return &texts.items[texts.items.len - 1];
+}
+
+fn prepare(source: []const u8, file: []const u8) !Text {
+ var analysis = try pardes.analyzeSource(gpa, file, source, false, true);
+ var lines: std.ArrayList([2]usize) = .empty;
+ var start: usize = 0;
+ while (start < source.len) {
+ const end = std.mem.indexOfScalarPos(u8, source, start, '\n') orelse source.len;
+ try lines.append(gpa, .{ start, end });
+ start = end + 1;
+ }
+ // A language pardes has no grammar for is drawn plain.
+ if (analysis.colors.len != source.len) {
+ analysis.deinit(gpa);
+ const plain = try gpa.alloc(u8, source.len);
+ @memset(plain, 0);
+ analysis.colors = plain;
+ }
+ return .{ .bytes = source, .styles = analysis.colors, .lines = try lines.toOwnedSlice(gpa) };
+}
+
+test "a source is cut into lines and classed byte by byte" {
+ const source = "int main(void) {\n return 0; // done\n}\n";
+ const text = try prepare(source, "main.c");
+ defer gpa.free(text.lines);
+ defer gpa.free(text.styles);
+ try std.testing.expectEqual(@as(usize, 3), text.lines.len);
+ try std.testing.expectEqualStrings(" return 0; // done", source[text.lines[1][0]..text.lines[1][1]]);
+ const at = std.mem.indexOf(u8, source, "return").?;
+ try std.testing.expectEqual(pardes.Syn.keyword, @as(pardes.Syn, @enumFromInt(text.styles[at])));
+ try std.testing.expectEqual(pardes.Syn.number, @as(pardes.Syn, @enumFromInt(text.styles[at + 7])));
+ try std.testing.expectEqual(pardes.Syn.comment, @as(pardes.Syn, @enumFromInt(text.styles[at + 10])));
+}
diff --git a/anim/src/syscalls.zig b/anim/src/syscalls.zig
new file mode 100644
index 0000000..9136ebb
--- /dev/null
+++ b/anim/src/syscalls.zig
@@ -0,0 +1,382 @@
+//! The other side of a system call. `Crossing` is the kernel as a lens,
+//! on solid vellum: the call the current
+//! step made, decoded (its name, each argument in the register that
+//! carried it, what it pointed at, and what came back in rax), the calls
+//! before it, and the arrow that crosses the line and returns. `Timeline`
+//! is the same boundary from far away: every call of the run as a block
+//! under the line, the current one in gold.
+//! Both read the recording's index of `syscall_enter` and `syscall_exit`.
+const std = @import("std");
+const sk = @import("sketch");
+const anim = @import("anim");
+const zt = @import("ztrace");
+const ui = @import("ui.zig");
+const cursors = @import("cursor.zig");
+const Recording = @import("Recording.zig");
+const theme = ui.theme;
+const time = theme.time;
+const Rect = ui.Rect;
+const k = theme.color.on_kernel;
+
+/// A crossing's timetable, in seconds into its step (design/motion.md, "A
+/// system call"). Staging, one thing at a time and no effect before its
+/// cause: the line fires; the registers that carry the call are framed,
+/// one by one; the arrow goes down through the line; only then does the
+/// kernel's side change, the last call giving way to this one, its name,
+/// its rows, its card; the work is done a byte at a time (a call with
+/// none skips it); the arrow comes back, and what came back strikes rax.
+/// So a call is as long as what it does: `close` 3.7 s, a `read` of
+/// fifteen bytes 4.8.
+pub const Plan = struct {
+ registers: f32 = time.cascade,
+ enters: f32 = 0.80,
+ /// The kernel's side: the last call out, this one's name in, its
+ /// rows (one every `row`), its card pushed.
+ leaves: f32 = 1.00,
+ name: f32 = 1.20,
+ rows: f32 = 1.40,
+ card: f32 = 1.70,
+ /// The work: a flow between the kernel and the program's bytes, then
+ /// the bytes, one every `byte`, `bytes` of them.
+ work: f32 = 2.00,
+ fills: f32 = 2.40,
+ bytes: f32 = 0,
+ /// The arrow back sets off; rax is struck; the mark moves on.
+ back: f32 = 2.00,
+ returns: f32 = 2.40,
+ advance: f32 = 3.10,
+ total: f32 = 3.70,
+
+ pub const cross = 0.40;
+ pub const row = 0.10;
+ pub const byte = 2.0 / 60.0;
+
+ pub fn of(call: Recording.Syscall) Plan {
+ var p: Plan = .{};
+ // Down: the bytes it was given. Up: the bytes it wrote into the program.
+ const down: usize = @min(call.text.len, shown_bytes);
+ const up: u64 = if (fills(call)) |span| span.len else 0;
+ p.bytes = @floatFromInt(@max(down, @min(up, 32)));
+ if (p.bytes > 0) p.back = p.fills + p.bytes * byte + 10.0 / 60.0;
+ p.returns = p.back + cross;
+ p.advance = p.returns + row + time.read_value;
+ p.total = p.advance + time.step + time.rest;
+ return p;
+ }
+
+ /// The same as the cursor's plan: the registers are the CPU's level,
+ /// the bytes memory's.
+ pub fn step(p: Plan) cursors.Plan {
+ return .{ .at = .{ p.registers, p.fills, p.fills }, .advance = p.advance, .travel = time.step, .total = p.total };
+ }
+};
+
+/// How many of the bytes a call was given the kernel's side shows.
+const shown_bytes = 2 * 11;
+
+/// One line of the program and the call into the kernel it makes, as one
+/// step of the cursor, timed by the crossing. A line that makes no call
+/// is walked like any other.
+pub fn step(c: cursors.Cursor, s: *anim.Frame, by: Recording.Stop) void {
+ const from = c.moment(s);
+ const to = c.rec.next(by, from);
+ const made = for (c.rec.syscalls) |made| {
+ if (made.enter > from and made.enter <= to) break made;
+ } else return c.walk(s, by, to);
+ const p = Plan.of(made);
+ c.step(s, to, p.step(), p.total);
+}
+
+/// The argument registers of a syscall, in order.
+const carriers = [_][]const u8{ "rdi", "rsi", "rdx", "r10", "r8", "r9" };
+
+/// The newest syscall entered by moment `i`.
+pub fn latest(rec: *const Recording, i: u64) ?usize {
+ var found: ?usize = null;
+ for (rec.syscalls, 0..) |s, n| {
+ if (s.enter > i) break;
+ found = n;
+ }
+ return found;
+}
+
+/// The syscall the cursor's step made (the newest, when it made several).
+pub fn inStep(now: cursors.Now) ?Recording.Syscall {
+ const n = latest(now.rec, now.stops[0]) orelse return null;
+ const call = now.rec.syscalls[n];
+ return if (call.enter > now.stops[1]) call else null;
+}
+
+/// The registers that carried `call`'s arguments, in order.
+pub fn carried(call: Recording.Syscall) []const []const u8 {
+ return carriers[0..@min(zt.syscalls.signature(call.nr).len, carriers.len)];
+}
+
+/// The bytes the kernel read from the program for `call`: the buffer of a
+/// write. Null for a call that is given none.
+pub fn bufferRead(call: Recording.Syscall) ?Recording.Span {
+ const signature = zt.syscalls.signature(call.nr);
+ const at = std.mem.indexOfScalar(u8, signature, 'b') orelse return null;
+ return .{ .addr = call.args[at], .len = call.args[at + 1] };
+}
+
+/// The bytes the kernel wrote into the program for `call`: what a read
+/// put in its buffer. Null for a call that fills none.
+/// shortcut: `read` alone; the recorder tells the bytes of any call, and a scene of `pread` or `recv` wants them named here.
+pub fn fills(call: Recording.Syscall) ?Recording.Span {
+ const got: i64 = @bitCast(call.result);
+ return if (call.nr == @intFromEnum(std.os.linux.SYS.read) and got > 0) .{ .addr = call.args[1], .len = @intCast(got) } else null;
+}
+
+/// The kernel as a lens: solid vellum, and nothing else on the frame is.
+/// The call the step made, decoded (its name, a row an argument by the
+/// argument's own name, what came back), the calls before it, the bytes it
+/// was given; and the arrow that crosses into it from the registers'
+/// side and returns.
+pub const Crossing = struct {
+ cursor: cursors.Cursor,
+ box: Rect = theme.layout.split.beside.lens,
+ focus: bool = false,
+
+ const row_h = theme.metric.context.row;
+ const size = theme.size.mono.context;
+
+ pub fn draw(c: *const Crossing, f: *sk.Frame, placed: anim.Placed) void {
+ const u: ui.Ui = .{ .f = f, .at = placed };
+ const now = c.cursor.now(placed);
+ const rec = c.cursor.rec;
+ const body = u.panel(c.box.w, c.box.h, "kernel", .{ .focus = c.focus, .note = "the other side of a system call" });
+ u.fill(.{ .x = theme.stroke.rule, .y = body.y, .w = body.w - 2 * theme.stroke.rule, .h = body.h - theme.stroke.rule }, theme.color.kernel);
+ u.text(.sans, theme.size.sans.micro, 12, body.y + 22, "calls so far", k.dim);
+ const newest = latest(rec, now.stops[0]) orelse return;
+ const live = rec.syscalls[newest].enter > now.stops[1] and now.walking();
+ const p = Plan.of(rec.syscalls[newest]);
+ const t: f32 = if (live) now.time else std.math.inf(f32);
+ if (t >= p.enters) c.arrows(u, body, t, p, rec.syscalls[newest]);
+ // No effect before its cause: until the arrow is through the
+ // line the kernel knows nothing of this call, and shows the last.
+ if (t < p.name) {
+ if (newest > 0) c.call(u.faded(1 - theme.ease(.exit, std.math.clamp((t - p.leaves) / (p.name - p.leaves), 0, 1))), body, rec.syscalls[newest - 1], .{}, std.math.inf(f32));
+ } else c.call(u, body, rec.syscalls[newest], p, t);
+
+ // The calls so far, newest on top. This one's row pushes in when
+ // the kernel has taken the call: the others make room first.
+ const pushed = cursors.standard(std.math.clamp((t - p.card) / theme.time.quick, 0, 1));
+ const arrived = std.math.clamp((t - p.card - theme.time.snap) / theme.time.quick, 0, 1);
+ const top = body.y + 32;
+ var i = newest + 1;
+ while (i > 0) {
+ i -= 1;
+ const place = @as(f32, @floatFromInt(newest - i)) - (if (i == newest) 0 else 1 - pushed);
+ const y = top + place * (row_h + 4) - (if (i == newest) (1 - arrived) * 8 else 0);
+ if (y + row_h > body.y + body.h - 6) continue;
+ const v = if (i == newest) u.faded(arrived) else u;
+ const card: Rect = .{ .x = 12, .y = y, .w = 196, .h = row_h };
+ const done = rec.syscalls[i];
+ const gold = if (i == newest) arrived >= 1 else i + 1 == newest and arrived < 1;
+ if (gold) v.fill(card, theme.mark(.current).solid);
+ v.frame(card, k.ink, theme.stroke.rule);
+ const name = zt.syscalls.name(done.nr) orelse "?";
+ v.text(if (gold) .mono_bold else .mono, size, card.x + 8, theme.baseline(card.y, card.h, size), name[0..@min(name.len, 11)], k.ink);
+ if ((i != newest or t >= p.returns + Plan.row) and done.exit != null) {
+ const words = result(u, done);
+ if (words.len <= 4) v.text(.mono, size, card.x + card.w - 8 - u.width(.mono, size, words), theme.baseline(card.y, card.h, size), words, k.dim);
+ }
+ }
+ }
+
+ /// A call, decoded: its name, a row for each argument, what came
+ /// back; and to the right the bytes it was given, as the kernel
+ /// copies them.
+ fn call(c: *const Crossing, u: ui.Ui, body: Rect, made: Recording.Syscall, p: Plan, t: f32) void {
+ _ = c;
+ const x = 236;
+ const name = zt.syscalls.name(made.nr) orelse "syscall";
+ // The name arrives rising, as a caption does.
+ const named = theme.ease(.enter, std.math.clamp((t - p.name) / theme.time.quick, 0, 1));
+ const title = u.faded(named);
+ const rise = (1 - named) * theme.time.caption_rise;
+ title.text(.mono_bold, theme.size.mono.value, x, body.y + 46 + rise, name, k.ink);
+ title.text(.sans, theme.size.sans.micro, x + u.width(.mono_bold, theme.size.mono.value, name) + 16, body.y + 44 + rise, u.print("system call {d}", .{made.nr}), k.dim);
+ const signature = zt.syscalls.signature(made.nr);
+ var row_y: f32 = body.y + 62;
+ var text_used = false;
+ const row = struct {
+ fn draw(v: ui.Ui, y: f32, register: []const u8, meaning: []const u8, words: []const u8) void {
+ v.fill(.{ .x = x, .y = y, .w = 300, .h = theme.stroke.rule }, k.rule);
+ const base = theme.baseline(y, row_h + 4, size);
+ v.text(.mono, size, x, base, register, k.dim);
+ v.text(.sans_medium, theme.size.sans.tag, x + 52, base, meaning, k.ink);
+ v.text(.mono, size, x + 130, base, words, k.ink);
+ }
+ }.draw;
+ for (signature, 0..) |kind, arg| {
+ if (arg >= 4) break;
+ const shows = std.math.clamp((t - p.rows - @as(f32, @floatFromInt(arg)) * Plan.row) / Plan.row, 0, 1);
+ row(u.faded(shows), row_y, carriers[arg], what(made.nr, kind, arg), value(u, made, kind, arg, &text_used));
+ row_y += row_h + 4;
+ }
+ const back = t >= p.returns + Plan.row and made.exit != null;
+ row(u.faded(std.math.clamp((t - p.rows - @as(f32, @floatFromInt(@min(signature.len, 4))) * Plan.row) / Plan.row, 0, 1)), row_y, "rax", "returns", if (back) result(u, made) else "\u{2014}");
+
+ if (made.text.len == 0) return;
+ const bytes_x = 564;
+ const framed = u.faded(std.math.clamp((t - p.work) / Plan.row, 0, 1));
+ framed.text(.sans, theme.size.sans.micro, bytes_x, body.y + 22, if (std.mem.indexOfScalar(u8, signature, 's') != null) "the path it was given" else "the bytes it was given", k.dim);
+ const shown = @min(made.text.len, shown_bytes);
+ for (made.text[0..shown], 0..) |byte, j| {
+ const cell: Rect = .{ .x = bytes_x + @as(f32, @floatFromInt(j % 11)) * 28, .y = body.y + 32 + @as(f32, @floatFromInt(j / 11)) * 30, .w = 26, .h = 26 };
+ // Each fills as it is copied, two frames a byte: struck, then held.
+ const since = t - p.fills - @as(f32, @floatFromInt(j)) * Plan.byte;
+ if (since < 0) {
+ framed.frame(cell, k.rule, theme.stroke.rule);
+ continue;
+ }
+ const in = std.math.clamp(since / theme.time.strike.in, 0, 1);
+ u.fill(cell, ui.mix(theme.color.kernel, ui.mix(theme.mark(.write).solid, k.held, std.math.clamp((since - theme.time.quick) / theme.time.strike.cool, 0, 1)), in));
+ u.frame(cell, k.ink, theme.stroke.rule);
+ if (in < 0.5) continue;
+ if (std.ascii.isPrint(byte) and byte != ' ') u.label(.mono, size, cell, .center, &.{byte}, k.ink) else if (byte == '\n') u.label(.mono, size, cell, .center, "\\n", k.dim);
+ }
+ }
+
+ /// The crossing itself: in from the side the registers are on as the
+ /// call enters, and back out as it returns. Vellum outside the
+ /// kernel, ink inside it. Machines do not lob: straight.
+ fn arrows(c: *const Crossing, u: ui.Ui, body: Rect, t: f32, p: Plan, made: Recording.Syscall) void {
+ const edge = c.box.w;
+ // Off promptly, and settling in the kernel.
+ const down = cursors.standard(std.math.clamp((t - p.enters) / Plan.cross, 0, 1));
+ const gone = std.math.clamp((t - p.returns - theme.time.quick) / theme.time.read.out, 0, 1);
+ const v = u.faded(1 - gone);
+ if (t < p.back) across(v, body.y + 190, edge + 26, edge + 26 - down * 86, edge);
+ if (made.exit != null and t > p.back) across(v, body.y + 226, edge - 60, edge - 60 + cursors.standard(std.math.clamp((t - p.back) / Plan.cross, 0, 1)) * 86, edge);
+ }
+
+ /// An arrow along the row at `y` from `from` to `to`, in the colour of
+ /// the ground it is over: ink inside the kernel (left of `edge`), vellum outside.
+ fn across(u: ui.Ui, y: f32, from: f32, to: f32, edge: f32) void {
+ if (@abs(to - from) < 1) return;
+ const w = theme.stroke.arrow;
+ const head = theme.stroke.flow_head;
+ const dir: f32 = if (to > from) 1 else -1;
+ const neck = to - dir * (head[0] - 2);
+ const lo = @min(from, neck);
+ const hi = @max(from, neck);
+ if ((neck - from) * dir > 0) {
+ if (lo < edge) u.fill(.{ .x = lo, .y = y - w / 2, .w = @min(hi, edge) - lo, .h = w }, k.ink);
+ if (hi > edge) u.fill(.{ .x = @max(lo, edge), .y = y - w / 2, .w = hi - @max(lo, edge), .h = w }, theme.color.kernel);
+ }
+ if (@abs(to - from) < head[0]) return;
+ sk.draw.polygon(u.f, &.{ .{ to, y }, .{ to - dir * head[0], y - head[1] / 2 }, .{ to - dir * head[0], y + head[1] / 2 } }, u.at.pen(.{ .fill = if (to - dir * head[0] / 2 < edge) ui.rgb(k.ink) else ui.rgb(theme.color.kernel) }));
+ }
+};
+
+/// What an argument is called: by the call's own names where they are
+/// known, else from its letter in `zt.syscalls.signature`.
+/// shortcut: four calls named; the recorder's table should carry every call's argument names.
+fn what(nr: u16, kind: u8, arg: usize) []const u8 {
+ const names: []const []const u8 = switch (std.enums.fromInt(std.os.linux.SYS, nr) orelse .restart_syscall) {
+ .open => &.{ "path", "flags", "mode" },
+ .read, .write => &.{ "fd", "buf", "count" },
+ .close => &.{"fd"},
+ else => &.{},
+ };
+ if (arg < names.len) return names[arg];
+ return switch (kind) {
+ 'i' => "number",
+ 'd' => "size",
+ 's' => "path",
+ 'b' => "buffer",
+ else => "pointer",
+ };
+}
+
+fn value(u: ui.Ui, made: Recording.Syscall, kind: u8, arg: usize, text_used: *bool) []const u8 {
+ const a = made.args[arg];
+ switch (kind) {
+ 'i' => return u.print("{d}", .{@as(i32, @bitCast(@as(u32, @truncate(a))))}),
+ 'd' => return u.print("{d}", .{a}),
+ 's' => if (made.text.len > 0 and !text_used.*) {
+ text_used.* = true;
+ const base = std.fs.path.basename(made.text);
+ return u.print("\"{s}\"", .{base[0..@min(base.len, 14)]});
+ },
+ else => {},
+ }
+ return grouped(u, a);
+}
+
+/// Hex in groups of four, as everywhere.
+fn grouped(u: ui.Ui, n: u64) []const u8 {
+ return ui.grouped(u.f.scratch.alloc(u8, 20) catch return "?", n);
+}
+
+/// What came back: a count, an address, or an error by name.
+fn result(u: ui.Ui, made: Recording.Syscall) []const u8 {
+ const ret: i64 = @bitCast(made.result);
+ if (ret < 0 and ret > -4096) {
+ if (std.enums.fromInt(std.os.linux.E, -ret)) |e| return u.print("{d} E{t}", .{ ret, e });
+ return u.print("{d}", .{ret});
+ }
+ return if (ret > 0xffffff or ret < 0) grouped(u, made.result) else u.print("{d}", .{ret});
+}
+
+pub const Timeline = struct {
+ cursor: cursors.Cursor,
+ box: Rect,
+ focus: bool = false,
+
+ pub fn draw(g: *const Timeline, f: *sk.Frame, at: anim.Placed) void {
+ const u: ui.Ui = .{ .f = f, .at = at };
+ const now = g.cursor.now(at);
+ const rec = g.cursor.rec;
+ const m = theme.metric.timeline;
+ const txt = theme.color.text;
+ const body = u.panel(g.box.w, g.box.h, "system calls", .{ .focus = g.focus, .note = "time runs right · a block is a call into the kernel" });
+ const pad = theme.metric.panel.pad_x;
+ const line_y = body.y + @min(body.h / 2 - 24, 84);
+ u.text(.sans, theme.size.sans.note, pad, line_y - 14, "user", txt.dim);
+ u.text(.sans, theme.size.sans.note, pad, line_y + 32, "kernel", txt.dim);
+ u.fill(.{ .x = theme.stroke.rule, .y = line_y, .w = g.box.w - 2 * theme.stroke.rule, .h = m.baseline }, theme.color.kernel);
+ if (rec.syscalls.len == 0) return;
+ // shortcut: equal blocks; under ptrace a call's time is the tracer's, so widths would say nothing.
+ const room = g.box.w - 2 * pad - 110;
+ const apart = @min(96, room / @as(f32, @floatFromInt(rec.syscalls.len)));
+ const w = @max(m.min_block, apart - m.min_gap);
+ const current = latest(rec, now.stops[0]);
+ var last_name_end: f32 = 0;
+ for (rec.syscalls, 0..) |call, i| {
+ const x = pad + 110 + @as(f32, @floatFromInt(i)) * apart;
+ const block: Rect = .{ .x = x, .y = line_y + m.baseline, .w = w, .h = m.block_h };
+ // Not yet made: hollow.
+ if (call.enter > now.stops[0]) u.frame(block, theme.color.rule, theme.stroke.rule) else u.fill(block, theme.color.kernel);
+ const name = zt.syscalls.name(call.nr) orelse "?";
+ const name_w = u.width(.mono, theme.size.mono.small, name);
+ const here = current == i;
+ const name_x = x + w / 2 - name_w / 2;
+ const base = block.y + block.h + 34;
+ if (here) {
+ const gold = theme.mark(.current);
+ u.fill(.{ .x = x + w / 2 - m.now / 2, .y = line_y - 40, .w = m.now, .h = block.h + 52 }, gold.solid);
+ u.fill(.{ .x = name_x - 10, .y = base - 28, .w = name_w + 20, .h = 38 }, gold.solid);
+ u.text(.mono_bold, theme.size.mono.small, name_x, base, name, gold.on_solid);
+ last_name_end = name_x + name_w + 24;
+ } else if (name_x > last_name_end and (current == null or @abs(@as(f32, @floatFromInt(i)) - @as(f32, @floatFromInt(current.?))) * apart > name_w / 2 + 40)) {
+ // Names wherever one fits.
+ u.text(.mono, theme.size.mono.small, name_x, base, name, txt.dim);
+ last_name_end = name_x + name_w + 16;
+ }
+ }
+ }
+};
+
+test "a crossing is as long as what the call does" {
+ // A call with no work: 3.7 s. Fifteen bytes copied up: 4.8.
+ try std.testing.expectApproxEqAbs(@as(f32, 3.70), Plan.of(.{ .nr = 3, .args = @splat(0), .enter = 0 }).total, 1e-3);
+ const read = Plan.of(.{ .nr = 0, .args = .{ 3, 0x1000, 32, 0, 0, 0 }, .enter = 0, .exit = 0, .result = 15 });
+ try std.testing.expectApproxEqAbs(@as(f32, 4.77), read.total, 1e-2);
+ // Nothing on the kernel's side before the arrow is through the line.
+ try std.testing.expect(read.leaves >= read.enters and read.name >= read.enters + Plan.cross);
+ try std.testing.expect(read.fills > read.name and read.returns > read.fills + 15 * Plan.byte);
+}
diff --git a/anim/src/theme.zig b/anim/src/theme.zig
new file mode 100644
index 0000000..9b18e59
--- /dev/null
+++ b/anim/src/theme.zig
@@ -0,0 +1,911 @@
+//! canim's look, as numbers: grounds and inks, the marks that mean something,
+//! type sizes, component metrics, and how long things take.
+//! `design/README.md` gives the reasons; `design/mock/` shows them drawn.
+//!
+//! Units are logical: the canvas is 1920 by 1080 of them whatever the export
+//! size, so a 4K master draws each as two pixels and nothing here changes.
+//! Colours are 0xRRGGBB and opaque. Nothing is tinted by alpha: an accent's
+//! quiet form is its own colour (its ember), because gold blended over lapis
+//! goes grey. The one translucent thing is `color.veil`.
+
+const std = @import("std");
+
+pub const Rect = struct { x: f32, y: f32, w: f32, h: f32 };
+
+// ---------------------------------------------------------------- canvas
+
+pub const canvas = struct {
+ pub const width = 1920;
+ pub const height = 1080;
+ /// Only the page, and the kernel's ground, come nearer an edge than this.
+ pub const margin_x = 64;
+ pub const margin_y = 48;
+ /// Twelve columns of 120 with gutters of 32 fill the 1792 between the margins.
+ pub const columns = 12;
+ pub const column = 120;
+ pub const gutter = 32;
+ /// Between panels one above another in a column.
+ pub const row_gap = 12;
+ /// The module: cells, rows, tags and code lines are multiples of 12.
+ pub const unit = 12;
+
+ /// Where the context and the lens go: 35 rows of 24. (Revision 2: the
+ /// running head is gone, and its rows went to the stage.)
+ pub const stage: Rect = .{ .x = 64, .y = 48, .w = 1792, .h = 840 };
+ /// The clock: a rule the width of the stage over the caption, gold
+ /// along it as far as the recording has run, the count under its right end.
+ pub const clock_y = 900;
+ /// Where the narrator's sentence goes. No data is ever drawn below y = 888:
+ /// the player's controls and its subtitles cover this band.
+ pub const caption: Rect = .{ .x = 64, .y = 912, .w = 1792, .h = 120 };
+ /// Baselines: a one-line caption, then the two lines of a two-line one.
+ pub const caption_baseline = [3]f32{ 990, 964, 1018 };
+ /// A caption line is no wider: about 64 characters at `size.caption`.
+ pub const caption_max_width = 1400;
+};
+
+/// Left edge of column `i` (0 to 11).
+pub fn colX(i: u8) f32 {
+ return @floatFromInt(@as(u32, canvas.margin_x) + @as(u32, i) * (canvas.column + canvas.gutter));
+}
+
+/// Width of `n` columns with the gutters between them.
+pub fn span(n: u8) f32 {
+ return @floatFromInt(@as(u32, n) * canvas.column + (@as(u32, n) - 1) * canvas.gutter);
+}
+
+/// `n` columns starting at column `first`, `y` below the stage's top, `h` tall.
+pub fn cols(first: u8, n: u8, y: f32, h: f32) Rect {
+ return .{ .x = colX(first), .y = canvas.stage.y + y, .w = span(n), .h = h };
+}
+
+/// How views share the stage. The order in each is the order of abstraction:
+/// source is leftmost, then the CPU, then memory; a lower level is never left
+/// of or above a higher one, and the kernel is always underneath.
+pub const layout = struct {
+ /// Two columns of 880. The program column: the lens, the source, the
+ /// disassembly, top to bottom (the idea, its text, its instructions).
+ /// The state column: what they act on, the same in every frame of
+ /// every scene.
+ pub const program = cols(0, 6, 0, canvas.stage.h);
+ pub const state = cols(6, 6, 0, canvas.stage.h);
+
+ /// The state column: every register (sixteen, rip, the flags), eight
+ /// words of stack, three frames of backtrace.
+ pub const registers = rows(state, 0, 18);
+ pub const stack = below(registers, 8);
+ pub const backtrace = below(stack, 3);
+
+ /// How the program column is shared: the one thing about the layout a
+ /// scene chooses. `lens` has no height where there is none.
+ pub const Split = struct { lens: Rect, source: Rect, disasm: Rect };
+ pub const split = struct {
+ /// The machine alone: the source over the disassembly, eight
+ /// instructions above the pc and eight below.
+ pub const none: Split = .{ .lens = .{ .x = program.x, .y = program.y, .w = program.w, .h = 0 }, .source = rows(program, 0, 14), .disasm = below(rows(program, 0, 14), 17) };
+ /// The default: the machine is the subject, the lens beside it.
+ /// (The user's direction after the design's revision: more of the
+ /// disassembly, so the source's window is shorter than the design's.)
+ pub const beside: Split = shared(312, 8, 10);
+ /// The idea is the subject: the lens a size up.
+ pub const subject: Split = shared(432, 5, 8);
+
+ fn shared(lens_h: f32, source_rows: f32, disasm_rows: f32) Split {
+ const lens: Rect = .{ .x = program.x, .y = program.y, .w = program.w, .h = lens_h };
+ const source: Rect = .{ .x = program.x, .y = lens.y + lens.h + canvas.row_gap, .w = program.w, .h = panelH(source_rows) };
+ return .{ .lens = lens, .source = source, .disasm = below(source, disasm_rows) };
+ }
+ };
+
+ /// A panel of `n` rows: a tag, the padding, the rows.
+ pub fn panelH(n: f32) f32 {
+ return metric.context.tag + 2 * metric.context.pad + n * metric.context.row;
+ }
+
+ fn rows(column: Rect, y: f32, n: f32) Rect {
+ return .{ .x = column.x, .y = column.y + y, .w = column.w, .h = panelH(n) };
+ }
+
+ fn below(r: Rect, n: f32) Rect {
+ return .{ .x = r.x, .y = r.y + r.h + canvas.row_gap, .w = r.w, .h = panelH(n) };
+ }
+};
+
+
+// ---------------------------------------------------------------- colour
+
+pub const color = struct {
+ /// The page: lapis, deep. Panels' bodies are the page too.
+ pub const page: u24 = 0x0a1030;
+ /// Tags, cells, cards, node bodies: anything that is a thing on the page.
+ pub const raised: u24 = 0x16245f;
+ /// Rules round panels, hollow cells, wedges, dividers, and the fill of
+ /// bookkeeping (allocator headers, pages merely present). 2 units wide as a
+ /// line; never the only carrier of anything, it is the first thing a
+ /// low-bitrate stream loses.
+ pub const rule: u24 = 0x3a4a8a;
+ /// The kernel's ground: vellum. Solid vellum means kernel at every scale
+ /// (the slab, a block on the timeline, a row of the page map) and nothing else.
+ pub const kernel: u24 = 0xeee6d2;
+
+ pub const text = struct {
+ /// Titles, and a value in flight.
+ pub const bright: u24 = 0xfff8e8;
+ /// Anything to be read. 14.9:1 on the page, 11.6:1 on `raised`.
+ pub const primary: u24 = 0xeee6d2;
+ /// Names, notes, things said about the data. 7.8:1 and 6.1:1.
+ pub const dim: u24 = 0x9aa6d9;
+ /// Furniture: leading zeros, the unchanging end of an address, line
+ /// numbers, column heads. 4.5:1 and 3.5:1; never the only carrier.
+ pub const faint: u24 = 0x6a7ab8;
+ /// Letters on a solid accent.
+ pub const ink: u24 = 0x050a24;
+ };
+
+ /// On the kernel's ground the page's colour is the ink, accents stay solid
+ /// inside a 2 unit ink frame, and there are no embers.
+ pub const on_kernel = struct {
+ pub const ink: u24 = 0x0a1030;
+ pub const dim: u24 = 0x4a5488;
+ pub const rule: u24 = 0xb9ad8e;
+ /// A byte the kernel changed a moment ago (the ember's stand-in).
+ pub const held: u24 = 0xf3b9a0;
+ };
+
+ /// Source code. Hue on letters is syntax and nothing else, and it is quiet:
+ /// keywords are also bold, comments also italic. The four are pardes's
+ /// classes (`kw`, `str` and `num`, `comment`); its `bg`, `fg` and `lineno`
+ /// are `page`, `text.primary` and `text.faint`.
+ pub const code = struct {
+ pub const plain: u24 = 0xeee6d2;
+ pub const keyword: u24 = 0xc0dcff;
+ pub const literal: u24 = 0xb5e8c8;
+ pub const comment: u24 = 0x9aa6d9;
+ };
+
+ /// A pointer is coloured by the memory it points into, as pwndbg colours
+ /// it: the stack yellow, the heap blue, code red, writable data purple;
+ /// a constant, and a number that is no pointer, plain. Memory that is
+ /// both writable and executable is code's colour, underlined.
+ /// (The debugger's whole context on screen: the user's direction, ahead
+ /// of the design's revision for it, which wins where it differs.)
+ pub const region = struct {
+ pub const stack: u24 = 0xf2d675;
+ pub const heap: u24 = 0x86b6ff;
+ pub const code_: u24 = 0xff8f9a;
+ pub const data: u24 = 0xd59cf5;
+ pub const rodata: u24 = 0xeee6d2;
+ pub const number: u24 = 0xeee6d2;
+ };
+ /// A string a pointer leads to, in quotes.
+ pub const string: u24 = 0xb5e8c8;
+
+ /// Where execution was: the last three places, newest first, gold cooling.
+ pub const trail = [3]u24{ 0xae9350, 0x746235, 0x463b20 };
+
+ /// Pigments: which object, thread or variable this is, the same in every
+ /// view. Dark bodies under `text.primary` (4.5:1 or better), so the bright
+ /// marks still read on top of them. Use them in this order, at most four in
+ /// a scene; only the first two are safe apart for every viewer, so each
+ /// also carries its name.
+ pub const pigment = [6]u24{
+ 0x8a5e0c, // ochre
+ 0x17707c, // teal
+ 0xa03060, // madder
+ 0x1c7450, // malachite
+ 0x6a3fb0, // violet
+ 0x2f5fc4, // azurite
+ };
+
+ /// Drawn over everything that is not the subject, to dim it.
+ pub const veil: u24 = page;
+ pub const veil_alpha: f32 = 0.65;
+};
+
+/// What a mark means. The same everywhere: a byte, a register, a source line,
+/// a tree node, a page, a block of time.
+pub const Role = enum {
+ /// Where execution is: the line, the instruction, rip, the newest frame.
+ current,
+ /// Written by this step; in its ember, changed within the last few.
+ write,
+ /// Read by this step.
+ read,
+ /// Holds an address, and the arrow to it.
+ pointer,
+ /// Handed out by an allocator.
+ allocated,
+ /// Handed back. No colour: its bytes are still there, and nobody owns them.
+ freed,
+ /// A signal, a failed call. Write's colour in a hazard band, always named.
+ fault,
+ /// What the narration is about now: framed, and the rest veiled.
+ attention,
+ /// A value on its way from one place to another.
+ flow,
+ /// Bytes the recording never observed.
+ unknown,
+ /// The other side of the system call boundary.
+ kernel,
+};
+
+/// How a role is drawn. No two roles share a form, so none is told by hue alone.
+pub const Form = enum {
+ /// A solid plaque on the thing's label and its ember across the row.
+ plaque,
+ /// A solid fill with ink letters, cooling to its ember and a solid bar along the bottom.
+ fill,
+ /// A frame, with its ember inside.
+ frame,
+ /// A frame round the bytes and an arrow from it, elbows filleted, head filled.
+ arrow,
+ /// Its ember inside a solid frame.
+ block,
+ /// Nothing inside a dashed frame; hatched where there is room.
+ hollow,
+ /// Diagonal bands of `solid` and ink round an ink plaque that names it.
+ hazard,
+ /// A bright frame, and the veil over everything else.
+ spotlight,
+ /// A thin arrow that is gone a second after it lands.
+ thin_arrow,
+ /// Two small squares where the digits would be.
+ dots,
+ /// The ground itself.
+ ground,
+};
+
+pub const Mark = struct {
+ /// Full strength: a strike's fill, a plaque, a stroke.
+ solid: u24,
+ /// The quiet form: a fill under `text.primary`. `solid` again where a role has none.
+ ember: u24,
+ /// Letters on `solid`.
+ on_solid: u24,
+ form: Form,
+};
+
+pub fn mark(role: Role) Mark {
+ const t = color.text;
+ return switch (role) {
+ .current => .{ .solid = 0xe8c46a, .ember = 0x4a3d1c, .on_solid = t.ink, .form = .plaque },
+ .write => .{ .solid = 0xff6a4a, .ember = 0x5a2218, .on_solid = t.ink, .form = .fill },
+ .read => .{ .solid = 0x6fd6e6, .ember = 0x1c4652, .on_solid = t.ink, .form = .frame },
+ .pointer => .{ .solid = 0xd59cf5, .ember = 0x45305a, .on_solid = t.ink, .form = .arrow },
+ .allocated => .{ .solid = 0x7fdc9a, .ember = 0x1f4a33, .on_solid = t.ink, .form = .block },
+ // The dashed frame, and the hatch.
+ .freed => .{ .solid = t.dim, .ember = color.rule, .on_solid = t.ink, .form = .hollow },
+ // The band, and the plaque inside it, lettered in `text.bright`.
+ .fault => .{ .solid = 0xff6a4a, .ember = t.ink, .on_solid = t.ink, .form = .hazard },
+ .attention => .{ .solid = t.bright, .ember = t.bright, .on_solid = t.ink, .form = .spotlight },
+ .flow => .{ .solid = t.primary, .ember = t.primary, .on_solid = t.ink, .form = .thin_arrow },
+ .unknown => .{ .solid = t.faint, .ember = t.faint, .on_solid = t.ink, .form = .dots },
+ .kernel => .{ .solid = color.kernel, .ember = color.kernel, .on_solid = color.on_kernel.ink, .form = .ground },
+ };
+}
+
+pub const roles = [_]Role{ .current, .write, .read, .pointer, .allocated, .freed, .fault, .attention, .flow, .unknown, .kernel };
+
+/// WCAG relative luminance of 0xRRGGBB.
+pub fn luminance(rgb: u24) f64 {
+ var sum: f64 = 0;
+ const weight = [3]f64{ 0.2126, 0.7152, 0.0722 };
+ for (weight, 0..) |w, i| {
+ const shift: u5 = @intCast(16 - 8 * i);
+ const c = @as(f64, @floatFromInt((rgb >> shift) & 0xff)) / 255.0;
+ sum += w * (if (c <= 0.04045) c / 12.92 else std.math.pow(f64, (c + 0.055) / 1.055, 2.4));
+ }
+ return sum;
+}
+
+/// WCAG contrast of two colours, 1 to 21.
+pub fn contrast(a: u24, b: u24) f64 {
+ const x = luminance(a);
+ const y = luminance(b);
+ return (@max(x, y) + 0.05) / (@min(x, y) + 0.05);
+}
+
+// ------------------------------------------------------------------ type
+
+/// The Go fonts (Bigelow & Holmes; BSD-3-Clause, the Go licence), from
+/// golang.org/x/image/font/gofont/ttfs or the `ttf-go` package. Mono is for
+/// what the machine holds, sans for what is said about it.
+pub const Face = struct { family: []const u8, file: []const u8 };
+pub const font = struct {
+ /// Data and code. The renderer's built-in face.
+ pub const mono: Face = .{ .family = "Go Mono", .file = "Go-Mono.ttf" };
+ /// Keywords, a struck value, the letters on a plaque.
+ pub const mono_bold: Face = .{ .family = "Go Mono", .file = "Go-Mono-Bold.ttf" };
+ /// Comments.
+ pub const mono_italic: Face = .{ .family = "Go Mono", .file = "Go-Mono-Italic.ttf" };
+ /// Captions, notes.
+ pub const sans: Face = .{ .family = "Go", .file = "Go-Regular.ttf" };
+ /// Tags, labels, the running head.
+ pub const sans_medium: Face = .{ .family = "Go Medium", .file = "Go-Medium.ttf" };
+ /// Titles.
+ pub const sans_bold: Face = .{ .family = "Go", .file = "Go-Bold.ttf" };
+};
+
+pub const size = struct {
+ /// Mono sizes are multiples of 5: Go Mono advances 0.6 em, so a character
+ /// is a whole number of units (15, 18, 21, 27, 36), a hex pair is 36, and
+ /// the layout is the same arithmetic at 1080p and at 4K.
+ pub const mono = struct {
+ /// The debugger's context, where a lot is on screen at once:
+ /// chains of pointers, the disassembly, the stack.
+ pub const context = 20;
+ /// Address gutters, types, small tags. Furniture.
+ pub const small = 25;
+ /// Bytes, words, registers, code. The smallest size for anything the
+ /// narration depends on; nothing mono that must be read is smaller.
+ pub const data = 30;
+ /// Values in nodes and chunks.
+ pub const value = 35;
+ /// A value in flight.
+ pub const flight = 45;
+ /// Values in hero cells, a system call's name.
+ pub const hero = 60;
+ };
+ pub const sans = struct {
+ /// Notes in a tag, glosses, the level rail. Furniture: lost at 480p, and that is allowed.
+ pub const micro = 18;
+ /// A panel's title.
+ pub const tag = 20;
+ /// A sentence beside a row: a gloss the narration also says aloud.
+ pub const note = 24;
+ /// Tags, names beside rows, the running head, legend names. The
+ /// smallest sans for anything that identifies something.
+ pub const label = 28;
+ pub const kicker = 30;
+ /// The narrator's sentence; code inside it is mono at 35.
+ pub const caption = 40;
+ pub const caption_leading = 54;
+ pub const subtitle = 44;
+ pub const title = 116;
+ pub const title_leading = 128;
+ };
+ /// Nothing that must be read is smaller, in either face.
+ pub const min_read = 20;
+ /// Nothing at all is smaller.
+ pub const min_any = 18;
+};
+
+/// Width of one Go Mono character at a mono size.
+pub fn monoAdvance(mono_size: u16) u16 {
+ return mono_size * 3 / 5;
+}
+
+/// Hex is set in groups of four digits, half a character apart, lower case,
+/// no `0x`. A register is 16 digits, an address 12 (or its last 8 in a narrow
+/// panel whose tag gives the rest); leading zeros are `text.faint`, and in an
+/// address gutter only the last group is `text.primary`.
+pub fn hexWidth(digits: u16, mono_size: u16) u16 {
+ const adv = monoAdvance(mono_size);
+ return digits * adv + (digits / 4 - 1) * ((adv + 1) / 2);
+}
+
+/// Baseline that centres capitals and digits of `text_size` in a box at `y`, `h` tall.
+pub fn baseline(y: f32, h: f32, text_size: f32) f32 {
+ return y + h / 2 + 0.36 * text_size;
+}
+
+// --------------------------------------------------------------- strokes
+
+pub const stroke = struct {
+ /// Rules, hollow cells, the gap between cells. The thinnest line there is.
+ pub const rule = 2;
+ /// Frames (read, allocated, freed, attention), flows, brackets.
+ /// The thinnest line that carries meaning.
+ pub const line = 3;
+ /// Pointer arrows and pointer frames, tree and graph edges.
+ pub const arrow = 4;
+ /// The bar under a cooled change, a crossing into the kernel.
+ pub const heavy = 6;
+ /// A pointer's head: a filled triangle, length and width.
+ pub const head = [2]f32{ 18, 16 };
+ pub const flow_head = [2]f32{ 16, 14 };
+ pub const crossing_head = [2]f32{ 24, 24 };
+ /// Arrows turn square corners with this fillet.
+ pub const elbow_radius = 12;
+ /// Arrows sharing a lane sit this far apart, the longest outermost.
+ pub const lane_pitch = 22;
+ /// Freed outlines and links on their way out: on, off.
+ pub const dash = [2]f32{ 12, 8 };
+ /// The hatch in a freed block: band width and pitch, at 45 degrees.
+ pub const hatch = [2]f32{ 5, 20 };
+ /// A fault's band: each colour's width, at 45 degrees.
+ pub const hazard = 12;
+ /// Elision marks and the dots of an unknown byte: squares this big.
+ pub const dot = 6;
+};
+
+// ------------------------------------------------------------ components
+
+pub const metric = struct {
+ /// A panel is an acme window: a tag with a square box, a rule, a body.
+ pub const panel = struct {
+ pub const tag_h = 48;
+ /// The box: filled `current` in the panel the narration is in, hollow elsewhere.
+ pub const box = 20;
+ pub const box_inset = 14;
+ pub const title_x = 48;
+ pub const title_baseline = 34;
+ pub const pad_x = 20;
+ pub const pad_y = 16;
+ };
+
+ /// One byte: two hex digits in a 46 square on a 48 pitch.
+ pub const byte = struct {
+ pub const pitch = 48;
+ pub const side = 46;
+ /// A character over its byte, for strings: this tall.
+ pub const text_h = 84;
+ };
+ /// Memory rows, bytes or words: 60 apart, which leaves room for a pointer's frame.
+ pub const row_pitch = 60;
+ /// A word is drawn on the footprint of its bytes (8 of them: 382 wide), so
+ /// bytes and their number can change into each other in place.
+ pub const pointer_frame_outset = 6;
+ /// The bar along the bottom of a cooled change.
+ pub const ember_bar = 6;
+ /// Bytes not shown: three dots and a note, this tall.
+ pub const elision_h = 24;
+ /// Left of an address gutter: register and variable marks that point at the row.
+ pub const mark_lane = 88;
+ /// Between gutter and bytes: where pointer arrows run.
+ pub const arrow_lane = 52;
+
+ /// Registers, and any table of names and values.
+ pub const table = struct {
+ pub const row_h = 48;
+ pub const name_x = 18;
+ /// The value cell overhangs its digits by this on each side.
+ pub const value_pad = 10;
+ pub const flag = [2]f32{ 60, 36 };
+ pub const flag_gap = 12;
+ };
+ /// Shown unless a scene says otherwise, in this order: where it is, the
+ /// result, the arguments, the frame. Any other register appears when a
+ /// step touches it and leaves once its ember has gone.
+ pub const default_registers = [_][]const u8{ "rip", "rax", "rdi", "rsi", "rdx", "rcx", "rsp", "rbp" };
+ pub const default_flags = [_][]const u8{ "CF", "ZF", "SF", "OF" };
+ /// The registers' rows, in pwndbg's order: sixteen, rip, the flags.
+ pub const all_registers = [_][]const u8{ "rax", "rbx", "rcx", "rdx", "rsi", "rdi", "rbp", "rsp", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15", "rip", "flags" };
+
+ /// The context: every panel of it is rows of 24 under a tag of 24.
+ pub const context = struct {
+ pub const row = 24;
+ pub const tag = 24;
+ /// Above and below the rows; at a panel's sides.
+ pub const pad = 6;
+ pub const side = 12;
+ /// A register's name: five characters. Its value starts here.
+ pub const name_w = 60;
+ pub const chain_x = 72;
+ /// Both arrows of a chain: a 2-unit shaft, a head 8 by 10.
+ pub const arrow_w = 30;
+ pub const arrow_head = [2]f32{ 8, 10 };
+ /// Between groups of four hex digits: half an advance.
+ pub const group_gap = 6;
+ /// Changed a moment ago: a tick at the value's left.
+ pub const tick = 4;
+ pub const read_frame = 2;
+ pub const pulse_outset = 3;
+ pub const string_min = 6;
+ pub const source_chars = 67;
+ };
+
+ pub const code = struct {
+ pub const line_h = 48;
+ /// Line numbers: three digits and this, then the code.
+ pub const gutter_pad = 16;
+ pub const text_gap = 20;
+ /// Characters a panel of n columns holds at `size.mono.data`: write the
+ /// C for a video to fit the panel it will be shown in.
+ pub const chars_in_5_columns = 34;
+ pub const chars_in_6_columns = 42;
+ pub const chars_in_7_columns = 51;
+ /// The trail bar at the left edge, and the instruction marker in an unfolded line.
+ pub const trail_bar = 6;
+ pub const unfold_indent = 36;
+ pub const instruction_bar = 8;
+ };
+
+ /// Call stack cards, newest on top.
+ pub const card = struct {
+ pub const h = 56;
+ pub const gap = 12;
+ pub const spine = 12;
+ };
+ /// A linked-list node: value, then a pointer compartment.
+ pub const node = struct {
+ pub const w = 180;
+ pub const h = 72;
+ pub const pointer_w = 72;
+ /// The square in the pointer compartment that its arrow leaves from.
+ pub const origin = 14;
+ };
+ /// Tree and graph nodes: circles; the tree's levels this far apart.
+ pub const tree = struct {
+ pub const radius = 24;
+ pub const radius_solo = 36;
+ pub const level = 54;
+ pub const badge = 28;
+ };
+ /// Array cells: in a panel among others, and as the subject.
+ pub const cell = [2]f32{ 96, 84 };
+ pub const hero_cell = [2]f32{ 168, 132 };
+ /// A value in flight: its card.
+ pub const flight_card = [2]f32{ 100, 60 };
+
+ /// The heap, to scale.
+ pub const heap = struct {
+ pub const units_per_byte = 4;
+ pub const strip_h = 88;
+ pub const strip_h_stacked = 56;
+ };
+ /// The page map: one square a page.
+ pub const page = struct {
+ pub const pitch = 24;
+ pub const side = 22;
+ pub const row_pitch = 42;
+ };
+ /// The system call strip: time spent in the kernel hangs below the line.
+ pub const timeline = struct {
+ pub const baseline = 3;
+ pub const block_h = 44;
+ pub const min_block = 12;
+ pub const min_gap = 16;
+ pub const now = 4;
+ };
+ pub const legend = struct {
+ pub const sample_w = 94;
+ pub const text_x = 110;
+ pub const row_h = 96;
+ };
+ /// A plaque: a name in a box (hollow for a value, filled for a place).
+ pub const plaque = struct {
+ pub const h = 40;
+ pub const pad = 12;
+ };
+
+ /// No panel shows more rows of data than this; past it, elide or zoom.
+ pub const max_rows = 10;
+ /// No scene tracks more objects by pigment.
+ pub const max_pigments = 4;
+};
+
+// ---------------------------------------------------------------- motion
+
+pub const Ease = enum {
+ /// Time itself: the progress line, a counter, the playhead; and opacity.
+ linear,
+ /// Things that answer the program: the mark, cards, tags, arrows
+ /// growing, rows making room. Quickest a quarter of the way in.
+ standard,
+ /// A fade that arrives rising.
+ enter,
+ /// A fade that leaves.
+ exit,
+ /// Things with weight: a value in flight, the camera, a layout, a
+ /// colour cooling. Quickest at the middle.
+ glide,
+};
+
+/// Control points x1, y1, x2, y2 of the curve from (0, 0) to (1, 1).
+pub fn bezier(e: Ease) [4]f32 {
+ return switch (e) {
+ .linear => .{ 0, 0, 1, 1 },
+ .standard => .{ 0.3, 0, 0.2, 1 },
+ .enter => .{ 0, 0, 0.2, 1 },
+ .exit => .{ 0.4, 0, 1, 1 },
+ .glide => .{ 0.45, 0, 0.55, 1 },
+ };
+}
+
+/// Progress at time `t`, both 0 to 1. Fits vecanim's `.ease` (`fn (f32) f32`)
+/// once the curve is bound: `fn standard(t: f32) f32 { return theme.ease(.standard, t); }`.
+pub fn ease(e: Ease, t: f32) f32 {
+ if (t <= 0) return 0;
+ if (t >= 1) return 1;
+ const p = bezier(e);
+ var lo: f32 = 0;
+ var hi: f32 = 1;
+ var s: f32 = t;
+ for (0..24) |_| {
+ s = (lo + hi) / 2;
+ if (cubic(p[0], p[2], s) < t) lo = s else hi = s;
+ }
+ return cubic(p[1], p[3], s);
+}
+
+fn cubic(a: f32, b: f32, s: f32) f32 {
+ const r = 1 - s;
+ return 3 * r * r * s * a + 3 * r * s * s * b + s * s * s;
+}
+
+/// The one overshoot there is: a struck cell's edges go out this many
+/// units on every side and come back, `t` from 0 to 1 over
+/// `time.strike.pulse`. An outset, not a scale: the same on a byte and on a
+/// register, and the digits do not move.
+pub fn pulse(t: f32) f32 {
+ return 4 * @sin(std.math.pi * std.math.clamp(t, 0, 1));
+}
+
+/// Seconds. Export at 60 frames a second; every figure is a whole number of frames.
+pub const time = struct {
+ pub const fps = 60;
+
+ /// A colour changing where nothing moves.
+ pub const snap = 0.10;
+ /// Leaving; a small change of state.
+ pub const quick = 0.20;
+ /// The current mark moving to the next row; `step_per_row` more for
+ /// each further row, `step_max` at most. Further than
+ /// `current_jump_rows`, or into or out of a call, it jumps.
+ pub const step = 0.20;
+ pub const step_per_row = 2.0 / 60.0;
+ pub const step_max = 0.40;
+ /// Something moving within a panel, up to 400 units.
+ pub const move = 0.40;
+ /// Something moving between panels, or further.
+ pub const travel = 0.60;
+ /// Panels changing layout.
+ pub const layout = 0.80;
+ /// A camera move up to twice or down to half the scale; a larger one.
+ pub const camera = 1.20;
+ pub const camera_far = 1.60;
+
+ /// A step is a sentence. Fire: the mark's plaque pulses on the line
+ /// about to run, and nothing else moves.
+ pub const fire = 0.20;
+ /// Then its effects, a level at a time, this far apart: the registers,
+ /// memory, the idea drawn from them.
+ pub const cascade = 0.30;
+ /// Then they are read: this long after the last strike, `read_more`
+ /// for each further value, `read_most` in all.
+ pub const read_value = 0.60;
+ pub const read_more = 0.20;
+ pub const read_most = 1.40;
+ /// Then the mark advances (`step`), and the next line is read.
+ pub const rest = 0.40;
+
+ /// A write: armed (a frame round the cell, the old value still in
+ /// it), struck (the fill fades in, with a pulse of its edges), held
+ /// solid until the mark leaves the line, cooled to its ember and bar,
+ /// kept while the thing has changed within `ember_steps` steps (or
+ /// `ember_seconds` where time runs free), then gone.
+ pub const strike = struct {
+ pub const arm = 0.20;
+ pub const in = 0.10;
+ pub const pulse = 0.20;
+ pub const hold = 0.50;
+ pub const cool = 0.40;
+ pub const ember_steps = 3;
+ pub const ember_seconds = 4.0;
+ pub const out = 0.60;
+ };
+ /// A read: framed for the step, never pulsed.
+ pub const read = struct {
+ pub const in = 0.10;
+ pub const min_hold = 0.50;
+ pub const out = 0.30;
+ };
+ /// The current marker slides to a neighbour and jumps (out, then in) further than this many rows.
+ pub const current_jump_rows = 8;
+ pub const current_jump = 0.10;
+ /// A pointer changing target: the head travels; the old path stays dashed, then goes.
+ pub const redirect = struct {
+ pub const head = 0.40;
+ pub const ghost_hold = 0.80;
+ pub const ghost_out = 0.30;
+ /// What the arrow lands on is framed bright, this long.
+ pub const landing = 0.20;
+ };
+ /// A value moving: lift, fly an arc, land with a strike. The place it left keeps its digits, faint.
+ pub const flight = struct {
+ pub const lift = 0.10;
+ pub const lift_scale = 1.12;
+ /// How long it flies, by how far: to 200 units, to 400, beyond.
+ pub const near = 0.50;
+ pub const mid = 0.60;
+ pub const far = 0.80;
+ /// Of two that fly together, the second sets off this much later.
+ pub const second = 0.10;
+ /// The arc's height as a share of the distance, and its limits in units.
+ pub const arc = 0.25;
+ pub const arc_min = 34;
+ pub const arc_max = 120;
+ /// A flow's arrow outlives the landing by this.
+ pub const linger = 1.0;
+ };
+ /// The veil that dims everything but the subject.
+ pub const veil = 0.30;
+ /// A telescope extends: the links after one that changed are followed
+ /// again one at a time, this far apart.
+ pub const unroll = 4.0 / 60.0;
+ /// A tie between two panes: this long to draw (after what it leaves
+ /// from has struck), and to go, as the marks advance.
+ pub const link = struct {
+ pub const in = 0.40;
+ pub const out = 0.30;
+ };
+ /// A source line opening into its instructions, and closing.
+ pub const unfold = 0.40;
+ /// A wedge drawing from a thing to its enlargement.
+ pub const wedge = 0.30;
+ /// A caption leaves, then nothing, then the next arrives rising this
+ /// many units; never typed out, never crossfaded. The stage stays
+ /// still `caption_lead` after it (`caption_lead_first` after a scene's
+ /// first): the eye reads, then is shown.
+ pub const caption_out = 0.20;
+ pub const caption_gap = 0.10;
+ pub const caption_in = 0.30;
+ pub const caption_rise = 8;
+ pub const caption_lead = 1.00;
+ pub const caption_lead_first = 2.00;
+
+ /// Things arriving together start this far apart, in reading order, and
+ /// the last starts no later than `stagger_max` after the first.
+ pub const stagger = 2.0 / 60.0;
+ pub const stagger_max = 0.30;
+ /// The same as a lag ratio for vecanim's `.lag`, for `n` things over `seconds`.
+ pub fn lag(n: u32, seconds: f32) f32 {
+ if (n < 2) return 0;
+ const total: f32 = @min(stagger * @as(f32, @floatFromInt(n - 1)), stagger_max);
+ return total / (seconds * @as(f32, @floatFromInt(n - 1)));
+ }
+
+ /// Pacing. A beat is the unit of stillness.
+ pub const beat = 0.50;
+ /// What a step that writes one value comes to. Not a pace: a walked
+ /// step is as long as its content (`cursor.reading`).
+ pub const walk = 1.50;
+ /// Once the pattern is known: the mark and structures eased, values
+ /// as embers. `run_max_steps` at most; beyond that, sprint.
+ pub const run = 0.30;
+ pub const run_max_steps = 24;
+ /// What moves at a run (the mark, a card, an arrow) takes this long.
+ pub const run_ease = 8.0 / 60.0;
+ /// A hurried step with this long or more is still a whole sentence,
+ /// said faster; with less, it is a run.
+ pub const walk_least = 0.70;
+ /// A return's follow-through: its card is struck with the result,
+ /// leaves, and the cards under it move up, before the hold begins.
+ pub const returning = 0.90;
+ /// At this a step or faster, single changes are not drawn: structures
+ /// grow, embers, and a counter.
+ pub const sprint = 4.0 / 60.0;
+ /// A phrase (a trip round a loop, a call and its return) ends with a rest.
+ pub const phrase_rest = 0.50;
+ pub const phrase_rest_running = 0.20;
+ /// A change of pace is never a switch: each step of it is this much
+ /// of the one before.
+ pub const ramp = 0.6;
+ /// Stillness at a scene's opening, for the picture to be read:
+ /// `establish` and `establish_per_panel` for each panel.
+ pub const establish = 1.00;
+ pub const establish_per_panel = 0.50;
+ /// Stillness after the stage is rearranged, and on the last picture.
+ pub const settle = 0.80;
+ pub const before_cut = 2.00;
+ /// A camera move: its target framed (`camera_before`), the rest of
+ /// the stage cleared (`camera_clear`), the move, then still
+ /// (`camera_after`). Never longer than `camera_dwell_max` nearer
+ /// without a change.
+ pub const camera_before = 0.40;
+ pub const camera_clear = 0.30;
+ pub const camera_after = 0.60;
+ pub const camera_dwell_max = 2.00;
+
+ /// How long a caption of `chars` characters stays up, at least.
+ pub fn caption(chars: u32) f32 {
+ return 1.5 + 0.06 * @as(f32, @floatFromInt(chars));
+ }
+};
+
+/// The camera only ever shows the frame, a panel, or a few cells; it never turns.
+pub const camera = struct {
+ pub const scales = [4]f32{ 1, 1.5, 2, 4 };
+ /// Units a second, at most, at scale 1.
+ pub const max_speed = 1200;
+};
+
+/// At once: one thing moves because the program did something, and at most
+/// two more move because of it. The camera and the layout move alone.
+pub const max_moving = 3;
+
+// ----------------------------------------------------------------- tests
+
+const expect = std.testing.expect;
+
+test "text reads on its grounds" {
+ const t = color.text;
+ try expect(contrast(t.primary, color.page) >= 11);
+ try expect(contrast(t.primary, color.raised) >= 11);
+ try expect(contrast(t.dim, color.page) >= 7);
+ try expect(contrast(t.dim, color.raised) >= 6);
+ try expect(contrast(t.faint, color.page) >= 4.5);
+ try expect(contrast(t.faint, color.raised) >= 3.5);
+ try expect(contrast(color.on_kernel.ink, color.kernel) >= 11);
+ try expect(contrast(color.on_kernel.dim, color.kernel) >= 5.5);
+ for ([_]u24{ color.code.plain, color.code.keyword, color.code.literal, color.code.comment }) |c|
+ try expect(contrast(c, color.page) >= 7);
+ for (color.pigment) |p| try expect(contrast(t.primary, p) >= 4.5);
+}
+
+test "every mark stands off the page, and letters read on it" {
+ for (roles) |r| {
+ const m = mark(r);
+ try expect(contrast(m.solid, color.page) >= 4.5);
+ try expect(contrast(m.on_solid, m.solid) >= 4.5);
+ // A role with a quiet form: text reads on it, and it is not the page.
+ if (m.ember != m.solid and r != .freed and r != .fault) {
+ try expect(contrast(color.text.primary, m.ember) >= 7);
+ try expect(contrast(m.ember, color.page) >= 1.4);
+ }
+ }
+ // The strokes that carry meaning on their own.
+ for ([_]Role{ .current, .write, .read, .pointer, .allocated }) |r|
+ try expect(contrast(mark(r).solid, color.page) >= 6.5);
+ try expect(contrast(color.text.ink, mark(.write).solid) >= 6.5);
+}
+
+test "no two roles are drawn the same way" {
+ for (roles, 0..) |a, i| for (roles[i + 1 ..]) |b| try expect(mark(a).form != mark(b).form);
+}
+
+test "mono advances are whole units" {
+ const m = size.mono;
+ for ([_]u16{ m.context, m.small, m.data, m.value, m.flight, m.hero }) |s| try expect(s % 5 == 0);
+ try expect(monoAdvance(m.context) == 12 and m.context >= size.min_read);
+ try expect(monoAdvance(m.data) == 18);
+ try expect(hexWidth(16, m.data) == 315);
+ try expect(hexWidth(12, m.small) == 196);
+ // A byte's two digits fit its cell; a register's sixteen fit a word's footprint.
+ try expect(2 * monoAdvance(m.data) <= metric.byte.side - 8);
+ try expect(hexWidth(16, m.data) <= 8 * metric.byte.pitch - 2 - 24);
+ try expect(m.data >= size.min_read and size.sans.label >= size.min_read and size.sans.micro >= size.min_any);
+}
+
+test "layouts fill the stage" {
+ try expect(colX(11) + canvas.column == canvas.width - canvas.margin_x);
+ try expect(span(12) == canvas.stage.w);
+ try expect(layout.program.w == 880 and layout.state.x == 976);
+ // The state column: 468, 228 and 108, twelve apart.
+ try expect(layout.registers.h == 468 and layout.stack.h == 228 and layout.backtrace.h == 108);
+ try expect(layout.backtrace.y + layout.backtrace.h <= canvas.stage.y + canvas.stage.h);
+ for ([_]layout.Split{ layout.split.none, layout.split.beside, layout.split.subject }) |split| {
+ try expect(split.disasm.y + split.disasm.h <= canvas.stage.y + canvas.stage.h);
+ try expect(split.source.y >= split.lens.y + split.lens.h);
+ }
+ try expect(layout.split.beside.source.h == 228 and layout.split.beside.disasm.h == 276);
+}
+
+test "easing runs from 0 to 1 without turning back" {
+ for ([_]Ease{ .linear, .standard, .enter, .exit, .glide }) |e| {
+ try expect(ease(e, 0) == 0 and ease(e, 1) == 1);
+ var last: f32 = 0;
+ for (1..61) |i| {
+ const v = ease(e, @as(f32, @floatFromInt(i)) / 60);
+ try expect(v >= last - 1e-4 and v <= 1 + 1e-4);
+ last = v;
+ }
+ }
+ try expect(@abs(ease(.linear, 0.3) - 0.3) < 1e-3);
+ // `standard` is ahead of time and `glide` is symmetrical.
+ try expect(ease(.standard, 0.5) > 0.6);
+ try expect(@abs(ease(.glide, 0.5) - 0.5) < 1e-3);
+ try expect(pulse(0.5) > 3.9 and pulse(0) == 0);
+}
+
+test "durations are whole frames" {
+ const t = time;
+ for ([_]f32{ t.snap, t.quick, t.step, t.step_per_row, t.step_max, t.move, t.travel, t.layout, t.camera, t.camera_far, t.fire, t.cascade, t.read_value, t.read_more, t.rest, t.strike.arm, t.strike.in, t.strike.pulse, t.strike.hold, t.strike.cool, t.strike.out, t.read.out, t.current_jump, t.flight.lift, t.flight.near, t.flight.second, t.veil, t.unfold, t.wedge, t.caption_in, t.caption_out, t.caption_gap, t.walk, t.run, t.sprint, t.phrase_rest, t.before_cut }) |d| {
+ const frames = d * t.fps;
+ try expect(@abs(frames - @round(frames)) < 1e-3);
+ }
+ try expect(t.lag(1, 0.4) == 0);
+ try expect(@abs(t.lag(8, 0.4) * 0.4 * 7 - 7 * t.stagger) < 1e-4);
+ try expect(@abs(t.lag(40, 0.4) * 0.4 * 39 - t.stagger_max) < 1e-4);
+}
diff --git a/anim/src/ties.zig b/anim/src/ties.zig
new file mode 100644
index 0000000..426a667
--- /dev/null
+++ b/anim/src/ties.zig
@@ -0,0 +1,139 @@
+//! Ties: one pane is a view of another, and a line between them says so.
+//! Any component can say where a thing of its own is on screen (`anchor`:
+//! a register's row, a word of memory, a node, the source's current line,
+//! the pc's row), and `Ties`, added last, draws the connections between
+//! places in different panels, routed along the gutters and never across
+//! a panel's text:
+//!
+//! - standing ties, declared by the scene (the source line and the
+//! instruction it is at: the gold thread);
+//! - the step's link: from the register a step has just struck to the
+//! row or node whose address it now holds, in the ink of where it
+//! points. It draws after the strike and goes as the marks advance;
+//! - a word a step wrote and the node it is part of: the bytes are the
+//! cause, the idea drawn from them the effect.
+//!
+//! A tie arrives, stays and leaves in the theme's time (`time.link`).
+const std = @import("std");
+const sk = @import("sketch");
+const anim = @import("anim");
+const zt = @import("ztrace");
+const ui = @import("ui.zig");
+const cursors = @import("cursor.zig");
+const contexts = @import("context.zig");
+const Recording = @import("Recording.zig");
+const theme = ui.theme;
+const time = theme.time;
+const Rect = ui.Rect;
+
+/// A thing with a place on screen.
+pub const Place = union(enum) {
+ /// A register's value, by its place in `Regs.names`.
+ register: usize,
+ /// The word of memory at this address, wherever it is shown.
+ word: u64,
+ /// The object at this address, as an idea.
+ node: u64,
+ /// The source's current line; the disassembly's.
+ source,
+ pc,
+
+ fn key(p: Place) u64 {
+ return switch (p) {
+ .register => |i| 1 << 60 | @as(u64, i),
+ .word => |a| 2 << 60 | (a & (1 << 60) - 1),
+ .node => |a| 3 << 60 | (a & (1 << 60) - 1),
+ .source => 4 << 60,
+ .pc => 5 << 60,
+ };
+ }
+};
+
+/// What this frame's components have said so far, in canvas pixels: left, top, right, bottom.
+/// shortcut: one table for the process, emptied by `Ties.draw`; a scene with two players at once wants it on the frame.
+var table: [256]struct { key: u64, box: [4]f32 } = undefined;
+var said: usize = 0;
+
+/// `r` (in `u`'s units) is where `place` is, this frame.
+pub fn anchor(u: ui.Ui, place: Place, r: Rect) void {
+ if (said == table.len) return;
+ const a = u.at.xf.apply(.{ r.x, r.y });
+ const b = u.at.xf.apply(.{ r.x + r.w, r.y + r.h });
+ table[said] = .{ .key = place.key(), .box = .{ a[0], a[1], b[0], b[1] } };
+ said += 1;
+}
+
+fn find(place: Place) ?[4]f32 {
+ for (table[0..said]) |entry| if (entry.key == place.key()) return entry.box;
+ return null;
+}
+
+pub const Ties = struct {
+ cursor: cursors.Cursor,
+ box: Rect = theme.canvas.stage,
+ /// Ties that stand for the whole scene.
+ standing: []const [2]Place = &.{.{ .source, .pc }},
+
+ pub fn draw(g: *const Ties, f: *sk.Frame, at: anim.Placed) void {
+ defer said = 0;
+ const now = g.cursor.now(at);
+ const rec = g.cursor.rec;
+ // In canvas pixels, `k` of them a unit: anchors come from panels anywhere.
+ var raw: ui.Ui = .{ .f = f, .at = at };
+ raw.at.xf = .identity;
+ const k = at.scale;
+ // The gutter between the two columns, and the margin left of the program's.
+ const gutter = at.xf.apply(.{ theme.layout.state.x - 16 - g.box.x, 0 })[0];
+ const margin = at.xf.apply(.{ -12, 0 })[0];
+
+ for (g.standing) |tie| {
+ const a = find(tie[0]) orelse continue;
+ const b = find(tie[1]) orelse continue;
+ // The gold thread: two views of where execution is, joined down the margin.
+ const lane = @min(margin, @min(a[0], b[0]) - 6 * k);
+ raw.arrow(&.{ .{ a[0], (a[1] + a[3]) / 2 }, .{ lane, (a[1] + a[3]) / 2 }, .{ lane, (b[1] + b[3]) / 2 }, .{ b[0], (b[1] + b[3]) / 2 } }, theme.mark(.current).solid, .{ .width = theme.stroke.rule * k, .head = null });
+ }
+ if (!now.walking()) return;
+ // The step's link: the first register it struck that now holds
+ // the address of something on screen. It draws once the strike
+ // is in, and goes as the marks advance.
+ const leaves = 1 - std.math.clamp((now.time - now.plan.advance) / time.link.out, 0, 1);
+ const regs = (now.moment().regs(rec.tid) catch null) orelse return;
+ for (zt.Regs.names, 0..) |name, index| {
+ if (now.registerAge(index) != 0 or std.mem.eql(u8, name, "rip") or std.mem.eql(u8, name, "rsp") or std.mem.eql(u8, name, "rbp")) continue;
+ const value = regs.named(name) orelse continue;
+ const from = find(.{ .register = index }) orelse continue;
+ const to = find(.{ .node = value }) orelse find(.{ .word = value & ~@as(u64, 7) }) orelse continue;
+ const drawn = cursors.standard(std.math.clamp((now.since(.cpu, 0) - time.strike.in) / time.link.in, 0, 1));
+ const color = contexts.ink(contexts.regionOf(now.moment(), value));
+ const y = (from[1] + from[3]) / 2;
+ const to_y = (to[1] + to[3]) / 2;
+ // Out of the panel's edge, along the gutter, to the side of what it lands on.
+ const edge = find(.{ .register = 1 << 20 }) orelse from;
+ const lands_at = if (to[2] < gutter) to[2] + 2 * k else to[0] - 2 * k;
+ raw.faded(leaves).arrow(&.{ .{ edge[0], y }, .{ gutter, y }, .{ gutter, to_y }, .{ lands_at, to_y } }, color, .{ .width = theme.stroke.line * k, .head = .{ 12 * k, 10 * k }, .progress = drawn });
+ // What it lands on answers with a frame.
+ if (drawn >= 1) raw.faded(leaves).frame(.{ .x = to[0] - 2 * k, .y = to[1] - 2 * k, .w = to[2] - to[0] + 4 * k, .h = to[3] - to[1] + 4 * k }, color, theme.stroke.rule * k);
+ break;
+ }
+ // A word written and the node it is part of: the bytes, then the idea.
+ for (rec.written(now.stops[1], now.stops[0])) |span| {
+ const word = find(.{ .word = span.addr & ~@as(u64, 7) }) orelse continue;
+ const node = for (table[0..said]) |entry| {
+ // The node whose bytes hold the word: nodes are sixteen bytes here.
+ if (entry.key >> 60 == 3 and (span.addr & (1 << 60) - 1) -% (entry.key & (1 << 60) - 1) < 16) break entry.box;
+ } else continue;
+ const drawn = cursors.standard(std.math.clamp(now.since(.memory, 0) / time.cascade, 0, 1));
+ const x = (word[0] + word[2]) / 2;
+ const node_x = (node[0] + node[2]) / 2;
+ const between = (node[3] + word[1]) / 2 + 18 * k;
+ raw.faded(leaves).arrow(&.{ .{ x, word[1] }, .{ x, between }, .{ node_x, between }, .{ node_x, node[3] + 2 * k } }, theme.mark(.write).solid, .{ .width = theme.stroke.line * k, .head = .{ 12 * k, 10 * k }, .progress = drawn });
+ break;
+ }
+ }
+};
+
+test "places have keys of their own" {
+ try std.testing.expect((Place{ .word = 0x1000 }).key() != (Place{ .node = 0x1000 }).key());
+ try std.testing.expect((Place{ .source = {} }).key() != (Place{ .pc = {} }).key());
+}
diff --git a/anim/src/ui.zig b/anim/src/ui.zig
new file mode 100644
index 0000000..9d92e28
--- /dev/null
+++ b/anim/src/ui.zig
@@ -0,0 +1,598 @@
+//! What every component draws with, in the design's units (1920 by 1080; a
+//! component's origin is its own top left corner): rects and rules snapped
+//! to pixels, text in the design's faces set on a baseline, hex in groups
+//! of four, the panel, the marks (written, read, unknown), and arrows.
+const std = @import("std");
+const sk = @import("sketch");
+const anim = @import("anim");
+pub const theme = @import("theme.zig");
+
+pub const Rect = theme.Rect;
+pub const Color = sk.Color;
+pub const Face = sk.Face;
+pub const Vec = sk.math.Vec;
+
+/// Scene units to a design unit: `anim` frames 1280 by 720.
+pub const scale = 1280.0 / @as(comptime_float, theme.canvas.width);
+
+/// Adds `data` (a component: something with `draw(f, at)`) to the scene,
+/// its origin at design `x, y` and its units the design's. Like any
+/// object, it shows once something plays it in (`fadeIn`).
+pub fn place(s: *anim.Frame, data: anytype, x: f32, y: f32) anim.Obj {
+ return s.custom(s.new(data), .{ .x = x * scale - 640, .y = y * scale - 360, .scale = scale });
+}
+
+/// A camera move that puts the middle of design rect `r` in the middle of
+/// the stage (the band between the head and the caption, which stay put),
+/// at `zoom` (the design allows 1, 2 and 4).
+pub fn lookAt(r: Rect, zoom: f32) anim.Animation {
+ const to = framing(r, zoom);
+ return anim.camera(.{ .x = to.x, .y = to.y, .zoom = to.zoom });
+}
+
+/// Where the camera is when the middle of design rect `r` is in the middle
+/// of the stage, at `zoom`.
+pub fn framing(r: Rect, zoom: f32) anim.Camera {
+ const stage = theme.canvas.stage;
+ const off = (theme.canvas.height / 2.0 - (stage.y + stage.h / 2)) / zoom;
+ return .{ .x = (r.x + r.w / 2) * scale - 640, .y = (r.y + r.h / 2 + off) * scale - 360, .zoom = zoom };
+}
+
+/// The camera `p` of the way from `a` to `b`. Arcs: it moves in a straight
+/// line and zooms by ratio (the logarithm of the scale is what is
+/// interpolated), about the one point that stays where it is on screen,
+/// or the first half of a move to twice the size looks twice as fast as
+/// the second.
+pub fn between(a: anim.Camera, b: anim.Camera, p: f32) anim.Camera {
+ if (@abs(a.zoom - b.zoom) < 1e-4) return .{ .x = std.math.lerp(a.x, b.x, p), .y = std.math.lerp(a.y, b.y, p), .zoom = b.zoom };
+ const zoom = a.zoom * std.math.pow(f32, b.zoom / a.zoom, p);
+ const still = [2]f32{ (b.x * b.zoom - a.x * a.zoom) / (b.zoom - a.zoom), (b.y * b.zoom - a.y * a.zoom) / (b.zoom - a.zoom) };
+ return .{ .x = still[0] - (still[0] - a.x) * a.zoom / zoom, .y = still[1] - (still[1] - a.y) * a.zoom / zoom, .zoom = zoom };
+}
+
+/// A theme colour (`0xRRGGBB`) or a `Color` already.
+pub fn rgb(c: anytype) Color {
+ return if (@TypeOf(c) == Color) c else .hex(c);
+}
+
+pub fn mix(a: anytype, b: anytype, t: f32) Color {
+ return sk.tween.lerp(rgb(a), rgb(b), std.math.clamp(t, 0, 1));
+}
+
+/// The face a text is set in: every monospace is JetBrains Mono NL, and
+/// under 30 its medium weight (light letters on a dark ground lose their
+/// thin strokes first in a video stream).
+fn set(face: Face, size: f32) Face {
+ return switch (face) {
+ .mono => if (size < 30) .code_medium else .code,
+ .mono_bold => .code_bold,
+ .mono_italic => .code_italic,
+ else => face,
+ };
+}
+
+/// `n` in hex, a space between groups of four from the right, into `out`
+/// (20 bytes is enough): nobody reads twelve digits unbroken.
+pub fn grouped(out: []u8, n: u64) []const u8 {
+ var buf: [16]u8 = undefined;
+ const digits = std.fmt.bufPrint(&buf, "{x}", .{n}) catch unreachable;
+ var at: usize = 0;
+ for (digits, 0..) |d, i| {
+ if (i > 0 and (digits.len - i) % 4 == 0) {
+ out[at] = ' ';
+ at += 1;
+ }
+ out[at] = d;
+ at += 1;
+ }
+ return out[0..at];
+}
+
+/// Width of one mono character at `size`: the mono faces advance 0.6 em, a
+/// whole number of pixels at the design's sizes.
+pub fn advance(size: f32) f32 {
+ return size * 3 / 5;
+}
+
+/// The space between groups of four hex digits: half a character, a whole unit.
+pub fn hexGap(size: f32) f32 {
+ return @ceil(advance(size) / 2);
+}
+
+/// Width of `digits` hex digits in groups of four, half a character apart.
+pub fn hexWidth(digits: usize, size: f32) f32 {
+ const groups: f32 = @floatFromInt((digits + 3) / 4);
+ return @as(f32, @floatFromInt(digits)) * advance(size) + (groups - 1) * hexGap(size);
+}
+
+pub const Align = enum { left, center, right };
+
+/// What digits are set in: leading zeros in `lead`, the rest in `ink`.
+pub const Ink = struct {
+ ink: Color = rgb(theme.color.text.primary),
+ lead: Color = rgb(theme.color.text.faint),
+ face: Face = .mono,
+
+ /// One colour for every digit: on a solid fill.
+ pub fn all(c: anytype, face: Face) Ink {
+ return .{ .ink = rgb(c), .lead = rgb(c), .face = face };
+ }
+};
+
+pub const Ui = struct {
+ f: *sk.Frame,
+ at: anim.Placed,
+
+ /// The same, at `opacity` of what it had: a thing arriving or leaving.
+ pub fn faded(u: Ui, opacity: f32) Ui {
+ var out = u;
+ out.at.pose.opacity *= std.math.clamp(opacity, 0, 1);
+ return out;
+ }
+
+ fn point(u: Ui, x: f32, y: f32) Vec {
+ return u.at.xf.apply(.{ x, y });
+ }
+
+ /// A filled rect, its edges on whole pixels.
+ pub fn fill(u: Ui, r: Rect, c: anytype) void {
+ const a = u.point(r.x, r.y);
+ const b = u.point(r.x + r.w, r.y + r.h);
+ const x = @round(a[0]);
+ const y = @round(a[1]);
+ u.f.fill(sk.Rect{ .x = x, .y = y, .w = @round(b[0]) - x, .h = @round(b[1]) - y }, u.at.faded(rgb(c)));
+ }
+
+ /// A stroke `w` wide, wholly inside `r`.
+ pub fn frame(u: Ui, r: Rect, c: anytype, w: f32) void {
+ u.fill(.{ .x = r.x, .y = r.y, .w = r.w, .h = w }, c);
+ u.fill(.{ .x = r.x, .y = r.y + r.h - w, .w = r.w, .h = w }, c);
+ u.fill(.{ .x = r.x, .y = r.y + w, .w = w, .h = r.h - 2 * w }, c);
+ u.fill(.{ .x = r.x + r.w - w, .y = r.y + w, .w = w, .h = r.h - 2 * w }, c);
+ }
+
+ /// A dashed frame inside `r`: nobody's bytes.
+ pub fn dashedFrame(u: Ui, r: Rect, c: anytype, w: f32) void {
+ const h = w / 2;
+ const pts = [_]Vec{ .{ r.x + h, r.y + h }, .{ r.x + r.w - h, r.y + h }, .{ r.x + r.w - h, r.y + r.h - h }, .{ r.x + h, r.y + r.h - h }, .{ r.x + h, r.y + h } };
+ sk.draw.dashed(u.f, &pts, theme.stroke.dash, u.at.pen(.{ .stroke = rgb(c), .width = w, .cap = .butt }));
+ }
+
+ /// Text on a baseline. The host places a line by the top of its box,
+ /// which is the font's ascent above the baseline.
+ pub fn text(u: Ui, face: Face, size: f32, x: f32, baseline: f32, bytes: []const u8, c: anytype) void {
+ if (bytes.len == 0) return;
+ // Go's ascent is 0.945 em; JetBrains Mono's, which every monospace is set in, 1.02.
+ const at = u.point(x, baseline - @as(f32, if (set(face, size) == face) 0.945 else 1.02) * size);
+ const drawn = size / 13.0 * u.at.scale;
+ // The camera rests at 1, 2 and 4: there text is shaped for its
+ // size, sharp. On the way between, it is the text of the nearer
+ // rest scaled, so letters do not shift against each other.
+ const one = @min(@floor(u.f.in.window_width) / theme.canvas.width, @floor(u.f.in.window_height) / theme.canvas.height);
+ const zoom = u.at.scale / one;
+ const rest: f32 = for (theme.camera.scales) |s| {
+ if (zoom <= s * 1.002) break s;
+ } else theme.camera.scales[theme.camera.scales.len - 1];
+ if (@abs(zoom - rest) <= rest * 0.002) {
+ u.f.textIn(set(face, size), at[0], at[1], drawn, bytes, u.at.faded(rgb(c)));
+ } else u.f.textScaled(set(face, size), at[0], at[1], drawn, size / 13.0 * one * rest, bytes, u.at.faded(rgb(c)));
+ }
+
+ pub fn width(u: Ui, face: Face, size: f32, bytes: []const u8) f32 {
+ return switch (face) {
+ .mono, .mono_bold, .mono_italic => @as(f32, @floatFromInt(std.unicode.utf8CountCodepoints(bytes) catch bytes.len)) * advance(size),
+ else => u.at.textSizeIn(u.f, face, size / 13.0, bytes)[0],
+ };
+ }
+
+ /// Text with its capitals centred in `r`'s height, ranged in its width.
+ pub fn label(u: Ui, face: Face, size: f32, r: Rect, how: Align, bytes: []const u8, c: anytype) void {
+ const x = switch (how) {
+ .left => r.x,
+ .center => r.x + (r.w - u.width(face, size, bytes)) / 2,
+ .right => r.x + r.w - u.width(face, size, bytes),
+ };
+ u.text(face, size, x, theme.baseline(r.y, r.h, size), bytes, c);
+ }
+
+ /// Formats into the frame's scratch memory.
+ pub fn print(u: Ui, comptime fmt: []const u8, args: anytype) []const u8 {
+ return u.f.format(fmt, args);
+ }
+
+ /// `value` as `digits` hex digits, in groups of four half a character
+ /// apart, from `x` rightwards.
+ pub fn hex(u: Ui, size: f32, x: f32, baseline: f32, v: u64, digits: usize, ink: Ink) void {
+ var buf: [16]u8 = undefined;
+ const all = std.fmt.bufPrint(&buf, "{x:0>16}", .{v}) catch unreachable;
+ const shown = all[16 - digits ..];
+ // Leading zeros, but never the last digit.
+ var zeros: usize = 0;
+ while (zeros < digits - 1 and shown[zeros] == '0') zeros += 1;
+ const adv = advance(size);
+ var at_x = x;
+ var i: usize = 0;
+ while (i < digits) {
+ // A group ends where the digits left are a multiple of four.
+ const end = i + ((digits - i - 1) % 4) + 1;
+ const split = std.math.clamp(zeros, i, end);
+ u.text(ink.face, size, at_x, baseline, shown[i..split], ink.lead);
+ u.text(ink.face, size, at_x + @as(f32, @floatFromInt(split - i)) * adv, baseline, shown[split..end], ink.ink);
+ at_x += @as(f32, @floatFromInt(end - i)) * adv + hexGap(size);
+ i = end;
+ }
+ }
+
+ /// An address in a gutter: its last group is the end that changes from
+ /// row to row, so only that one is in full ink.
+ pub fn address(u: Ui, x: f32, baseline: f32, addr: u64, digits: usize) void {
+ const size = theme.size.mono.small;
+ const adv = advance(size);
+ var buf: [16]u8 = undefined;
+ const all = std.fmt.bufPrint(&buf, "{x:0>16}", .{addr}) catch unreachable;
+ const shown = all[16 - digits ..];
+ var i: usize = 0;
+ var at_x = x;
+ while (i < digits) : (i += 4) {
+ u.text(.mono, size, at_x, baseline, shown[i .. i + 4], if (i + 4 == digits) theme.color.text.primary else theme.color.text.faint);
+ at_x += 4 * adv + hexGap(size);
+ }
+ }
+
+ /// An acme window `w` by `h` at the origin: a tag one row high (a box,
+ /// gold where the narration is; the title; a note ranged right, or the
+ /// legend of the regions), and a rule round the body. Returns the body.
+ pub fn panel(u: Ui, w: f32, h: f32, title: []const u8, options: struct { focus: bool = false, note: []const u8 = "", legend: bool = false }) Rect {
+ u.region(title, .{ .x = 0, .y = 0, .w = w, .h = h });
+ const m = theme.metric.context;
+ const t = theme.color.text;
+ u.fill(.{ .x = 0, .y = 0, .w = w, .h = m.tag }, theme.color.raised);
+ u.frame(.{ .x = 0, .y = 0, .w = w, .h = h }, theme.color.rule, theme.stroke.rule);
+ const box: Rect = .{ .x = 8, .y = 6, .w = 12, .h = 12 };
+ if (options.focus) u.fill(box, theme.mark(.current).solid) else u.frame(box, t.faint, theme.stroke.rule);
+ const base = theme.baseline(0, m.tag, theme.size.sans.tag);
+ u.text(.sans_medium, theme.size.sans.tag, 28, base, title, if (options.focus) t.primary else t.dim);
+ const micro = theme.size.sans.micro;
+ if (options.legend) {
+ // What an address's ink says, always on screen, as pwndbg's legend is.
+ const c = theme.color.region;
+ var x = w - 10;
+ inline for (.{ .{ "read-only", c.rodata }, .{ "rwx", c.code_ }, .{ "data", c.data }, .{ "code", c.code_ }, .{ "heap", c.heap }, .{ "stack", c.stack } }) |entry| {
+ x -= u.width(.sans_medium, micro, entry[0]);
+ u.text(.sans_medium, micro, x, base, entry[0], entry[1]);
+ if (comptime std.mem.eql(u8, entry[0], "rwx")) u.fill(.{ .x = x, .y = base + 3, .w = u.width(.sans_medium, micro, entry[0]), .h = theme.stroke.rule }, entry[1]);
+ x -= 16;
+ }
+ } else u.text(.sans, micro, w - 10 - u.width(.sans, micro, options.note), base, options.note, t.faint);
+ return .{ .x = 0, .y = m.tag, .w = w, .h = h - m.tag };
+ }
+
+ /// For tools/motion.py, which plots how much of each panel changes
+ /// from frame to frame: with CANIM_PANELS in the environment, every
+ /// frame tells where on the canvas (as fractions of it) `r` is.
+ pub fn region(u: Ui, name: []const u8, r: Rect) void {
+ if (u.f.host.env("CANIM_PANELS") == null) return;
+ const a = u.point(r.x, r.y);
+ const b = u.point(r.x + r.w, r.y + r.h);
+ const w = @floor(u.f.in.window_width);
+ const h = @floor(u.f.in.window_height);
+ std.debug.print("canim-panel {d:.4} {d:.4} {d:.4} {d:.4} {s}\n", .{ a[0] / w, a[1] / h, b[0] / w, b[1] / h, name });
+ }
+
+ /// The ground of a thing a step wrote, as hot as `h` says: armed (a
+ /// frame, the old value still in it), struck (the fill coming in,
+ /// its edges pulsing out and back), solid, cooling to its ember with a
+ /// bar along the bottom, `ground` (null: nothing) once that has gone.
+ /// Returns what to set its digits in.
+ pub fn written(u: Ui, r: Rect, h: Heat, ground: ?u24) Ink {
+ const w = theme.mark(.write);
+ const under: Color = rgb(ground orelse theme.color.page);
+ var body = if (h.level < 1) mix(under, w.ember, h.level) else mix(w.ember, w.solid, h.solid);
+ // Timing: a strike arrives over a tenth of a second, not in a frame.
+ if (h.in < 1) body = mix(if (h.from == .ember) rgb(w.ember) else under, body, h.in);
+ // The pulse is an outset, the same on a byte and on a register,
+ // and the digits do not move with it.
+ // shortcut: a neighbour drawn after covers its side of the outset; struck cells in two passes when that shows.
+ if (h.level > 0 or ground != null) u.fill(.{ .x = r.x - h.out, .y = r.y - h.out, .w = r.w + 2 * h.out, .h = r.h + 2 * h.out }, body);
+ const bar = theme.metric.ember_bar;
+ if (h.level >= 1 and (h.in >= 1 or h.from == .ember)) u.fill(.{ .x = r.x, .y = r.y + r.h - bar, .w = r.w, .h = bar }, w.solid);
+ // Anticipation: where the write will land, before it does.
+ if (h.arm > 0) u.faded(h.arm).frame(r, w.solid, theme.stroke.line);
+ // Bold ink on the solid. The face changes at the middle of the
+ // cool, where the colour is moving fastest and hides it.
+ const heat = h.solid * h.in;
+ if (h.level < 1 or heat <= 0) return .{};
+ const cooled: Ink = .{};
+ return .{ .ink = mix(cooled.ink, w.on_solid, heat), .lead = mix(cooled.lead, w.on_solid, heat), .face = if (heat >= 0.5) .mono_bold else .mono };
+ }
+
+ /// A thing a step read: its ember inside a frame, `shows` of it (0 to
+ /// 1: it fades in and out, and is never armed or pulsed).
+ pub fn readMark(u: Ui, r: Rect, shows: f32) void {
+ if (shows <= 0) return;
+ const m = theme.mark(.read);
+ const v = u.faded(shows);
+ v.fill(r, m.ember);
+ v.frame(r, m.solid, theme.stroke.line);
+ }
+
+ /// The same in the context, at mono 20, where a value has no cell of
+ /// its own: armed is a thin frame; a strike is solid behind the value
+ /// (its edges out a little and back), and for as long as it is solid
+ /// "written now" is all the value says: the ink this returns, bold on
+ /// the solid. It cools to nothing, and what is left for three steps is
+ /// a tick in the gap at the value's left: a held change never sits
+ /// under the digits it marks, whose ink is where they point.
+ pub fn struck(u: Ui, r: Rect, h: Heat) ?Ink {
+ const w = theme.mark(.write);
+ const m = theme.metric.context;
+ if (h.level > 0) u.fill(.{ .x = r.x - m.tick - 2, .y = r.y + 1, .w = m.tick, .h = r.h - 2 }, mix(theme.color.page, w.solid, h.level));
+ if (h.arm > 0) u.faded(h.arm).frame(r, w.solid, m.read_frame);
+ const solid = if (h.level >= 1) h.solid * h.in else 0;
+ if (solid <= 0) return null;
+ const out = @min(h.out, m.pulse_outset);
+ u.fill(.{ .x = r.x - out, .y = r.y - out, .w = r.w + 2 * out, .h = r.h + 2 * out }, mix(theme.color.page, w.solid, solid));
+ return if (solid >= 0.5) Ink.all(w.on_solid, .mono_bold) else null;
+ }
+
+ /// A thing a step read, in the context: a thin frame outside the digits, and no fill.
+ pub fn readFrame(u: Ui, r: Rect, shows: f32) void {
+ if (shows > 0) u.faded(shows).frame(r, theme.mark(.read).solid, theme.metric.context.read_frame);
+ }
+
+ /// One arrow of a chain, `metric.context.arrow_w` wide from `x`, on the
+ /// row whose middle is `y`: pointing right ("points to") or back
+ /// ("holds"). Faint: it is grammar, not data.
+ pub fn chainArrow(u: Ui, x: f32, y: f32, back: bool) void {
+ const m = theme.metric.context;
+ const c = theme.color.text.faint;
+ const a = x + 5;
+ const b = x + m.arrow_w - 5;
+ const head = m.arrow_head;
+ const pen = u.at.pen(.{ .fill = rgb(c) });
+ if (back) {
+ u.fill(.{ .x = a + head[0] - 1, .y = y - 1, .w = b - a - head[0] + 1, .h = 2 }, c);
+ sk.draw.polygon(u.f, &.{ .{ a, y }, .{ a + head[0], y - head[1] / 2 }, .{ a + head[0], y + head[1] / 2 } }, pen);
+ } else {
+ u.fill(.{ .x = a, .y = y - 1, .w = b - a - head[0] + 1, .h = 2 }, c);
+ sk.draw.polygon(u.f, &.{ .{ b, y }, .{ b - head[0], y - head[1] / 2 }, .{ b - head[0], y + head[1] / 2 } }, pen);
+ }
+ }
+
+ /// A value as its class is set (design/README.md, "What a value shows
+ /// as"), from `x` on `baseline` at mono 20: an address (`pointer`) as
+ /// long as it is, in `ink`; a number under 10 as the digit; up to
+ /// 0xffff as hex with its decimal after it, faint; larger, hex with
+ /// `0x`; within 4096 of 2^64, a small negative. Returns where it ends (the faint
+ /// decimal apart: `Value.width` is what a mark goes behind).
+ pub fn value(u: Ui, x: f32, baseline: f32, v: u64, pointer: bool, ink: Ink) f32 {
+ const size = theme.size.mono.context;
+ const adv = advance(size);
+ const shown = Value.of(v, pointer);
+ var at = x;
+ if (shown.prefix.len > 0) {
+ u.text(ink.face, size, at, baseline, shown.prefix, ink.ink);
+ at += @as(f32, @floatFromInt(shown.prefix.len)) * adv;
+ }
+ var i: usize = 0;
+ const digits = shown.digits();
+ while (i < digits.len) {
+ // A group ends where the digits left are a multiple of four.
+ const end = if (shown.grouped) i + ((digits.len - i - 1) % 4) + 1 else digits.len;
+ u.text(ink.face, size, at, baseline, u.print("{s}", .{digits[i..end]}), ink.ink);
+ at += @as(f32, @floatFromInt(end - i)) * adv + @as(f32, if (end < digits.len) theme.metric.context.group_gap else 0);
+ i = end;
+ }
+ if (shown.decimal) {
+ u.text(.mono, size, at + theme.metric.context.group_gap, baseline, u.print("{d}", .{v}), theme.color.text.faint);
+ at += theme.metric.context.group_gap + @as(f32, @floatFromInt(std.fmt.count("{d}", .{v}))) * adv;
+ }
+ return at;
+ }
+
+ /// The veil over what cannot be read at the pace: `amount` of it, 0 to 1.
+ pub fn veil(u: Ui, r: Rect, amount: f32) void {
+ if (amount > 0) u.fill(r, rgb(theme.color.veil).alphaFloat(theme.color.veil_alpha * std.math.clamp(amount, 0, 1)));
+ }
+
+ /// Draws only inside `r` until `unclip`: text scrolling in its panel.
+ pub fn clip(u: Ui, r: Rect) void {
+ const a = u.point(r.x, r.y);
+ const b = u.point(r.x + r.w, r.y + r.h);
+ u.f.clip(sk.Rect{ .x = @round(a[0]), .y = @round(a[1]), .w = @round(b[0]) - @round(a[0]), .h = @round(b[1]) - @round(a[1]) });
+ }
+
+ pub fn unclip(u: Ui) void {
+ u.f.clip(null);
+ }
+
+ /// Never observed: two dots where the digits would be, centred in `r`.
+ pub fn unknown(u: Ui, r: Rect) void {
+ const d = theme.stroke.dot;
+ const y = r.y + (r.h - d) / 2;
+ u.fill(.{ .x = r.x + r.w / 2 - d - 3, .y = y, .w = d, .h = d }, theme.color.text.faint);
+ u.fill(.{ .x = r.x + r.w / 2 + 3, .y = y, .w = d, .h = d }, theme.color.text.faint);
+ }
+
+ /// Bytes that are there and not shown: three dots and what they are.
+ pub fn elision(u: Ui, x: f32, y: f32, note: []const u8) void {
+ const d = theme.stroke.dot;
+ const h = theme.metric.elision_h;
+ for (0..3) |i| u.fill(.{ .x = x + @as(f32, @floatFromInt(i)) * 14, .y = y + (h - d) / 2, .w = d, .h = d }, theme.color.text.faint);
+ u.text(.sans, theme.size.sans.micro, x + 56, theme.baseline(y, h, theme.size.sans.micro), note, theme.color.text.faint);
+ }
+
+ /// A name in a box 40 tall at `x, y`: hollow (a value) with `fill`
+ /// null, else filled (a place, a tracked object). Returns its width.
+ pub fn plaque(u: Ui, x: f32, y: f32, face: Face, size: f32, bytes: []const u8, ink: anytype, fill_color: ?u24, stroke: ?u24) f32 {
+ const m = theme.metric.plaque;
+ const w = u.width(face, size, bytes) + 2 * m.pad;
+ const r: Rect = .{ .x = x, .y = y, .w = w, .h = m.h };
+ if (fill_color) |c| u.fill(r, c);
+ if (stroke) |c| u.frame(r, c, theme.stroke.rule);
+ u.text(face, size, x + m.pad, theme.baseline(y, m.h, size), bytes, ink);
+ return w;
+ }
+
+ /// A path through `points` with filleted corners, `progress` of its
+ /// length drawn (an arrow growing to its target), dashed or whole, with
+ /// a filled head at its end or none.
+ pub fn arrow(u: Ui, points: []const Vec, c: anytype, options: struct { width: f32 = theme.stroke.arrow, head: ?[2]f32 = theme.stroke.head, dashed: bool = false, progress: f32 = 1 }) void {
+ if (points.len < 2 or options.progress <= 0) return;
+ var path: std.ArrayList(Vec) = .empty;
+ const gpa = u.f.scratch;
+ path.append(gpa, points[0]) catch return;
+ for (1..points.len - 1) |i| {
+ // The corner as a quadratic through its fillet's ends.
+ const a = points[i - 1];
+ const b = points[i];
+ const z = points[i + 1];
+ const r = @min(theme.stroke.elbow_radius, @min(sk.math.distance(a, b), sk.math.distance(b, z)) / 2);
+ const from = b + sk.math.withLength(a - b, r);
+ const to = b + sk.math.withLength(z - b, r);
+ for (0..7) |k| {
+ const t = @as(f32, @floatFromInt(k)) / 6;
+ path.append(gpa, sk.math.mix(sk.math.mix(from, b, t), sk.math.mix(b, to, t), t)) catch return;
+ }
+ }
+ path.append(gpa, points[points.len - 1]) catch return;
+
+ // Cut to `progress` of its length, and short of the head.
+ var total: f32 = 0;
+ for (path.items[0 .. path.items.len - 1], path.items[1..]) |a, b| total += sk.math.distance(a, b);
+ const head_len: f32 = if (options.head) |h| h[0] else 0;
+ const tip_at = total * std.math.clamp(options.progress, 0, 1);
+ var keep = @max(tip_at - @max(head_len - 2, 0), 0);
+ var tip = path.items[0];
+ var dir: Vec = sk.math.normalize(path.items[1] - path.items[0]);
+ var body: std.ArrayList(Vec) = .empty;
+ body.append(gpa, path.items[0]) catch return;
+ var walked: f32 = 0;
+ for (path.items[0 .. path.items.len - 1], path.items[1..]) |a, b| {
+ const len = sk.math.distance(a, b);
+ if (len == 0) continue;
+ if (keep > 0) body.append(gpa, if (keep >= len) b else sk.math.mix(a, b, keep / len)) catch return;
+ keep -= len;
+ if (walked <= tip_at) {
+ dir = sk.math.normalize(b - a);
+ tip = if (tip_at - walked >= len) b else sk.math.mix(a, b, (tip_at - walked) / len);
+ }
+ walked += len;
+ }
+ const pen = u.at.pen(.{ .stroke = rgb(c), .fill = rgb(c), .width = options.width, .join = .round, .cap = .butt });
+ var stroke = pen;
+ stroke.fill = null;
+ if (body.items.len > 1) {
+ if (options.dashed) sk.draw.dashed(u.f, body.items, theme.stroke.dash, stroke) else sk.draw.polyline(u.f, body.items, stroke);
+ }
+ if (options.head) |h| {
+ const back = tip - sk.math.scale(dir, h[0]);
+ const side = sk.math.scale(sk.math.perp(dir), h[1] / 2);
+ var solid = pen;
+ solid.stroke = null;
+ sk.draw.polygon(u.f, &.{ tip, back + side, back - side }, solid);
+ }
+ }
+
+ /// A straight line between two points (a tree's edge).
+ pub fn line(u: Ui, a: Vec, b: Vec, c: anytype, w: f32) void {
+ sk.draw.line(u.f, a, b, u.at.pen(.{ .stroke = rgb(c), .width = w, .cap = .butt }));
+ }
+
+ pub fn disc(u: Ui, center: Vec, radius: f32, fill_color: ?Color, stroke: ?Color, w: f32) void {
+ sk.draw.circle(u.f, center, radius, u.at.pen(.{ .fill = fill_color, .stroke = stroke, .width = w }));
+ }
+};
+
+/// How a value is set, by its class.
+pub const Value = struct {
+ buf: [20]u8 = undefined,
+ len: usize = 0,
+ prefix: []const u8 = "",
+ /// In groups of four from the right.
+ grouped: bool = false,
+ /// Its decimal follows, faint: a small number that may be either.
+ decimal: bool = false,
+
+ pub fn of(v: u64, pointer: bool) Value {
+ var shown: Value = .{};
+ const negative = !pointer and v > std.math.maxInt(u64) - 4096;
+ if (negative) {
+ shown.len = (std.fmt.bufPrint(&shown.buf, "-{d}", .{0 -% v}) catch unreachable).len;
+ } else if (!pointer and v < 10) {
+ shown.len = (std.fmt.bufPrint(&shown.buf, "{d}", .{v}) catch unreachable).len;
+ } else {
+ shown.len = (std.fmt.bufPrint(&shown.buf, "{x}", .{v}) catch unreachable).len;
+ // The user's direction: hex unbroken, as a debugger prints it (the design had groups of four).
+ shown.grouped = false;
+ shown.decimal = !pointer and v <= 0xffff;
+ if (!pointer) shown.prefix = "0x";
+ }
+ return shown;
+ }
+
+ pub fn digits(shown: *const Value) []const u8 {
+ return shown.buf[0..shown.len];
+ }
+
+ /// Units its digits take at mono 20 (the faint decimal apart).
+ pub fn width(shown: *const Value) f32 {
+ const adv = advance(theme.size.mono.context);
+ const groups: f32 = if (shown.grouped) @floatFromInt((shown.len + 3) / 4) else 1;
+ return @as(f32, @floatFromInt(shown.prefix.len + shown.len)) * adv + (groups - 1) * theme.metric.context.group_gap;
+ }
+};
+
+/// How hot a written thing is, from `cursor.Now.heat`.
+pub const Heat = struct {
+ /// 0 no mark, up to 1 the mark in full (less while it leaves).
+ level: f32 = 0,
+ /// 1 solid, 0 cooled to the ember.
+ solid: f32 = 0,
+ /// 0 to 1 as the strike's fill comes in over what was there (`from`).
+ in: f32 = 1,
+ /// What it strikes over: the mark the steps before left.
+ from: enum { nothing, ember } = .nothing,
+ /// 0 to 1: armed, a frame round the cell before it is struck.
+ arm: f32 = 0,
+ /// The strike's pulse: how far out its edges are, in units.
+ out: f32 = 0,
+
+ pub const none: Heat = .{};
+ pub const ember: Heat = .{ .level = 1 };
+};
+
+test "the camera zooms by ratio and ends where it was sent" {
+ const a: anim.Camera = .{};
+ const b = framing(.{ .x = 64, .y = 528, .w = 728, .h = 360 }, 2);
+ try std.testing.expectApproxEqAbs(@sqrt(2.0), between(a, b, 0.5).zoom, 1e-4);
+ try std.testing.expectApproxEqAbs(a.x, between(a, b, 0).x, 1e-3);
+ try std.testing.expectApproxEqAbs(b.x, between(a, b, 1).x, 1e-3);
+ try std.testing.expectApproxEqAbs(b.y, between(a, b, 1).y, 1e-3);
+}
+
+test "a value is set by its class" {
+ const expectEqualStrings = std.testing.expectEqualStrings;
+ try expectEqualStrings("4", Value.of(4, false).digits());
+ try std.testing.expect(Value.of(0x21, false).decimal and std.mem.eql(u8, Value.of(0x21, false).prefix, "0x"));
+ try expectEqualStrings("-1", Value.of(std.math.maxInt(u64), false).digits());
+ // An address: as long as it is, no `0x`, unbroken.
+ const address = Value.of(0x7ffe970f17b0, true);
+ try expectEqualStrings("7ffe970f17b0", address.digits());
+ try std.testing.expectEqual(@as(f32, 12 * 12), address.width());
+ try std.testing.expect(address.prefix.len == 0 and !address.decimal);
+}
+
+test "hex is grouped in fours" {
+ var buf: [20]u8 = undefined;
+ try std.testing.expectEqualStrings("7fff ffff d8c0", grouped(&buf, 0x7fffffffd8c0));
+ try std.testing.expectEqualStrings("8000", grouped(&buf, 0x8000));
+ try std.testing.expectEqualStrings("1 0000", grouped(&buf, 0x10000));
+}
+
+test "hex widths are whole units at the design's sizes" {
+ try std.testing.expectEqual(@as(f32, 18), advance(theme.size.mono.data));
+ try std.testing.expectEqual(@as(f32, 315), hexWidth(16, theme.size.mono.data));
+ try std.testing.expectEqual(@as(f32, 196), hexWidth(12, theme.size.mono.small));
+ try std.testing.expectEqual(@as(f32, 36), hexWidth(2, theme.size.mono.data));
+}
diff --git a/anim/src/words.zig b/anim/src/words.zig
new file mode 100644
index 0000000..ff9c5c1
--- /dev/null
+++ b/anim/src/words.zig
@@ -0,0 +1,216 @@
+//! Words on the frame, and what frames them: the clock over the caption,
+//! the narrator's caption, labels and titles, the legend, and the veil
+//! that dims everything but the subject. The clock and the caption stay
+//! where they are while the camera moves.
+const std = @import("std");
+const sk = @import("sketch");
+const anim = @import("anim");
+const ui = @import("ui.zig");
+const Cursor = @import("cursor.zig").Cursor;
+const theme = ui.theme;
+const Rect = ui.Rect;
+const t = theme.color.text;
+
+/// The clock: a rule the width of the stage, over the caption, gold along
+/// it as far as the recording has run (linear: time itself; still at a
+/// walk, sweeping at a sprint, the one thing on screen that says "fast"),
+/// and under its right end the count of moments; while steps are hurried
+/// it counts them too. Add it after the panels and before the first
+/// caption: it also covers the margins round the stage, so that a camera
+/// gone nearer shows nothing outside it.
+pub const Clock = struct {
+ cursor: Cursor,
+ box: Rect = .{ .x = theme.canvas.stage.x, .y = theme.canvas.clock_y - 12, .w = theme.canvas.stage.w, .h = 24 },
+
+ pub fn draw(k: *const Clock, f: *sk.Frame, at: anim.Placed) void {
+ const u = fixed(f, at, 0);
+ const c = theme.canvas;
+ const now = k.cursor.now(at);
+ const stage = c.stage;
+ // The margins are the page's, whatever the camera has brought under them.
+ u.fill(.{ .x = -c.width, .y = -c.height, .w = 3 * c.width, .h = c.height + stage.y }, theme.color.page);
+ u.fill(.{ .x = -c.width, .y = stage.y + stage.h, .w = 3 * c.width, .h = 2 * c.height }, theme.color.page);
+ u.fill(.{ .x = -c.width, .y = 0, .w = c.width + stage.x - 8, .h = c.height }, theme.color.page);
+ u.fill(.{ .x = stage.x + stage.w + 8, .y = 0, .w = c.width, .h = c.height }, theme.color.page);
+ u.fill(.{ .x = stage.x, .y = c.clock_y - 1, .w = stage.w, .h = theme.stroke.rule }, theme.color.rule);
+ u.fill(.{ .x = stage.x, .y = c.clock_y - 2, .w = stage.w * now.place, .h = 4 }, theme.mark(.current).solid);
+ const size = theme.size.mono.context;
+ const base = c.clock_y + 28;
+ const count = u.print("moment {d} of {d}", .{ now.stops[0] -| now.way[0], now.way[1] -| now.way[0] });
+ const count_x = stage.x + stage.w - u.width(.mono, size, count);
+ u.text(.mono, size, count_x, base, count, t.faint);
+ // Secondary action: the pace, said quietly. It only fades.
+ if (now.hurried > 0) {
+ const steps = if (now.of > 0) u.print("step {d} of {d}", .{ now.count, now.of }) else u.print("step {d}", .{now.count});
+ u.faded(now.hurried).text(.mono, size, count_x - u.width(.mono, size, steps) - 3 * ui.advance(size), base, steps, t.dim);
+ }
+ }
+};
+
+/// A bright frame round `box`: where the camera is about to go.
+pub const Outline = struct {
+ box: Rect,
+
+ pub fn draw(o: *const Outline, f: *sk.Frame, at: anim.Placed) void {
+ const out = theme.metric.pointer_frame_outset;
+ (ui.Ui{ .f = f, .at = at }).frame(.{ .x = -out, .y = -out, .w = o.box.w + 2 * out, .h = o.box.h + 2 * out }, theme.mark(.attention).solid, theme.stroke.line);
+ }
+};
+
+/// The narrator's sentence: one or two lines (split at a newline), sans,
+/// with `code` between backticks in mono. It fades in rising, and stays
+/// where it is while the camera moves.
+pub const Caption = struct {
+ text: []const u8,
+ box: Rect = theme.canvas.caption,
+
+ pub fn draw(c: *const Caption, f: *sk.Frame, at: anim.Placed) void {
+ const u = fixed(f, at, (1 - at.pose.opacity) * theme.time.caption_rise);
+ const two = std.mem.indexOfScalar(u8, c.text, '\n') != null;
+ var lines = std.mem.splitScalar(u8, c.text, '\n');
+ var n: usize = if (two) 1 else 0;
+ while (lines.next()) |line| : (n += 1) {
+ if (n > 2) break;
+ _ = runs(u, theme.canvas.margin_x, theme.canvas.caption_baseline[n], line, .sans, theme.size.sans.caption, theme.size.mono.value, t.primary);
+ }
+ }
+};
+
+/// Text with `code` between backticks set in mono, from `x` on `baseline`.
+/// Returns where it ends.
+pub fn runs(u: ui.Ui, x: f32, baseline: f32, text: []const u8, face: ui.Face, size: f32, mono_size: f32, ink: anytype) f32 {
+ var at_x = x;
+ var parts = std.mem.splitScalar(u8, text, '`');
+ var code = false;
+ while (parts.next()) |part| : (code = !code) {
+ const part_face: ui.Face = if (code) .mono else face;
+ const part_size = if (code) mono_size else size;
+ u.text(part_face, part_size, at_x, baseline, part, ink);
+ at_x += u.width(part_face, part_size, part);
+ }
+ return at_x;
+}
+
+/// A line of text anywhere: a label (sans medium 28), a note, a title.
+pub const Label = struct {
+ text: []const u8,
+ box: Rect,
+ face: ui.Face = .sans_medium,
+ size: f32 = theme.size.sans.label,
+ color: u24 = t.primary,
+ how: ui.Align = .left,
+
+ pub fn draw(l: *const Label, f: *sk.Frame, at: anim.Placed) void {
+ const u: ui.Ui = .{ .f = f, .at = at };
+ var lines = std.mem.splitScalar(u8, l.text, '\n');
+ var y: f32 = 0;
+ while (lines.next()) |line| : (y += l.box.h) u.label(l.face, l.size, .{ .x = 0, .y = y, .w = l.box.w, .h = l.box.h }, l.how, line, l.color);
+ }
+};
+
+/// Dims everything added before it except `box`, which gets a bright
+/// frame: what the narration is about now.
+pub const Veil = struct {
+ /// The subject, in the design's units.
+ box: Rect,
+
+ pub fn draw(v: *const Veil, f: *sk.Frame, at: anim.Placed) void {
+ const u: ui.Ui = .{ .f = f, .at = at };
+ const far = 4 * theme.canvas.width;
+ const shade = ui.rgb(theme.color.veil).alphaFloat(theme.color.veil_alpha);
+ const b = v.box;
+ // Four rects round the subject, in its own units (the origin is its corner).
+ u.fill(.{ .x = -far, .y = -far, .w = 2 * far + b.w, .h = far }, shade);
+ u.fill(.{ .x = -far, .y = b.h, .w = 2 * far + b.w, .h = far }, shade);
+ u.fill(.{ .x = -far, .y = 0, .w = far, .h = b.h }, shade);
+ u.fill(.{ .x = b.w, .y = 0, .w = far, .h = b.h }, shade);
+ const out = theme.metric.pointer_frame_outset;
+ u.frame(.{ .x = -out, .y = -out, .w = b.w + 2 * out, .h = b.h + 2 * out }, theme.mark(.attention).solid, theme.stroke.line);
+ }
+};
+
+/// The marks, each drawn as the components draw it, with its name and what
+/// it means: the same in every picture.
+pub const Legend = struct {
+ box: Rect,
+ entries: []const Entry = &.{ .current, .written, .changed, .read, .pointer, .allocated, .freed, .unknown, .kernel },
+
+ pub const Entry = enum { current, written, changed, read, pointer, allocated, freed, unknown, kernel };
+
+ pub fn draw(l: *const Legend, f: *sk.Frame, at: anim.Placed) void {
+ const u: ui.Ui = .{ .f = f, .at = at };
+ const body = u.panel(l.box.w, l.box.h, "legend", .{ .note = "the same marks in every picture" });
+ const m = theme.metric.legend;
+ const per_row = @max(1, (l.entries.len + 1) / 2);
+ const pitch = (body.w - 2 * theme.metric.panel.pad_x) / @as(f32, @floatFromInt(per_row));
+ for (l.entries, 0..) |entry, i| {
+ const x = theme.metric.panel.pad_x + @as(f32, @floatFromInt(i % per_row)) * pitch;
+ const y = body.y + 24 + @as(f32, @floatFromInt(i / per_row)) * m.row_h;
+ const sample: Rect = .{ .x = x, .y = y, .w = m.sample_w, .h = 46 };
+ const words: [2][]const u8 = switch (entry) {
+ .current => .{ "current", "execution is here" },
+ .written => .{ "written", "by this step" },
+ .changed => .{ "changed", "a moment ago" },
+ .read => .{ "read", "by this step" },
+ .pointer => .{ "pointer", "holds an address" },
+ .allocated => .{ "allocated", "handed out" },
+ .freed => .{ "freed", "handed back" },
+ .unknown => .{ "not seen", "never observed" },
+ .kernel => .{ "kernel", "the other side" },
+ };
+ drawSample(u, entry, sample);
+ u.text(.sans_medium, theme.size.sans.label, x + m.text_x, y + 22, words[0], t.primary);
+ u.text(.sans, theme.size.sans.micro, x + m.text_x, y + 50, words[1], t.dim);
+ }
+ }
+
+ fn drawSample(u: ui.Ui, entry: Entry, r: Rect) void {
+ const size = theme.size.mono.data;
+ const half: Rect = .{ .x = r.x, .y = r.y, .w = 46, .h = 46 };
+ const other: Rect = .{ .x = r.x + 48, .y = r.y, .w = 46, .h = 46 };
+ switch (entry) {
+ .current => {
+ u.fill(r, theme.mark(.current).solid);
+ u.label(.mono_bold, size, r, .center, "rip", theme.mark(.current).on_solid);
+ },
+ .written, .changed => for ([_]Rect{ half, other }, [_][]const u8{ "2a", "00" }) |cell, digits| {
+ const ink = u.written(cell, if (entry == .written) .{ .level = 1, .solid = 1 } else .ember, null);
+ u.label(ink.face, size, cell, .center, digits, ink.ink);
+ },
+ .read => for ([_]Rect{ half, other }, [_][]const u8{ "2a", "00" }) |cell, digits| {
+ u.readMark(cell, 1);
+ u.label(.mono, size, cell, .center, digits, t.primary);
+ },
+ .pointer => {
+ u.fill(half, theme.color.raised);
+ u.frame(half, theme.mark(.pointer).solid, theme.stroke.arrow);
+ u.arrow(&.{ .{ r.x + 46, r.y + 23 }, .{ r.x + r.w, r.y + 23 } }, theme.mark(.pointer).solid, .{});
+ },
+ .allocated => {
+ u.fill(r, theme.mark(.allocated).ember);
+ u.frame(r, theme.mark(.allocated).solid, theme.stroke.line);
+ },
+ .freed => u.dashedFrame(r, theme.mark(.freed).solid, theme.stroke.line),
+ .unknown => {
+ u.unknown(half);
+ u.unknown(other);
+ },
+ .kernel => {
+ u.fill(r, theme.color.kernel);
+ u.label(.mono_bold, size, r, .center, "sys", theme.color.on_kernel.ink);
+ },
+ }
+ }
+};
+
+/// A `Ui` in the design's units that the camera does not move: the frame
+/// fitted into the canvas, as at zoom 1. `drop` lowers it by that many units.
+pub fn fixed(f: *sk.Frame, at: anim.Placed, drop: f32) ui.Ui {
+ const w = @max(@floor(f.in.window_width), 1);
+ const h = @max(@floor(f.in.window_height), 1);
+ const k = @min(w / theme.canvas.width, h / theme.canvas.height);
+ var still = at;
+ still.scale = k;
+ still.xf = sk.math.Affine.translate(w / 2, h / 2).mul(.scale(k, k)).mul(.translate(-theme.canvas.width / 2.0, -theme.canvas.height / 2.0 + drop));
+ return .{ .f = f, .at = still };
+}
diff --git a/anim/test/fib.script b/anim/test/fib.script
new file mode 100644
index 0000000..a300d19
--- /dev/null
+++ b/anim/test/fib.script
@@ -0,0 +1,11 @@
+# The fib scene, headless: it runs to three instants of its timeline without failing.
+# (The pixel assertions written for the first layout were dropped when the
+# frame became the debugger's context; new ones want a settled design: see anim/README.md.)
+frames 2
+console set playing false
+console set t 5
+screenshot .zig-cache/canim/fib-early.png
+console set t 14
+screenshot .zig-cache/canim/fib-mid.png
+console set t 999
+screenshot .zig-cache/canim/fib-end.png
diff --git a/anim/test/list.script b/anim/test/list.script
new file mode 100644
index 0000000..7f4bcbb
--- /dev/null
+++ b/anim/test/list.script
@@ -0,0 +1,11 @@
+# The list scene, headless: it runs to three instants of its timeline without failing.
+# (The pixel assertions written for the first layout were dropped when the
+# frame became the debugger's context; new ones want a settled design: see anim/README.md.)
+frames 2
+console set playing false
+console set t 5
+screenshot .zig-cache/canim/list-early.png
+console set t 14
+screenshot .zig-cache/canim/list-mid.png
+console set t 999
+screenshot .zig-cache/canim/list-end.png
diff --git a/anim/test/recordings.zig b/anim/test/recordings.zig
new file mode 100644
index 0000000..ef97d31
--- /dev/null
+++ b/anim/test/recordings.zig
@@ -0,0 +1,101 @@
+//! canim on its real recordings (made by the build, under ztrace's
+//! debugger): finding moments, what a step changed, calls, pointers
+//! followed, and the cursor's timetable for a step.
+const std = @import("std");
+const canim = @import("canim");
+const anim = @import("anim");
+const recordings = @import("recordings");
+
+const Recording = canim.Recording;
+const expect = std.testing.expect;
+const expectEqual = std.testing.expectEqual;
+
+test "steps by line stop on lines of the program's own source, and no step stands still" {
+ inline for (.{ recordings.steps, recordings.hello, recordings.sort, recordings.list }) |program| {
+ const rec = canim.open(program);
+ var at = rec.call("main", 0).enter;
+ var stops: usize = 0;
+ while (at < rec.end() and stops < 400) : (stops += 1) {
+ const next = rec.next(.line, at);
+ try expect(next > at);
+ if (next < rec.end()) try expect(rec.reached[next]);
+ at = next;
+ }
+ try expect(stops > 4);
+ }
+}
+
+test "calls are a tree: fib(5) makes fifteen, each with what it was given and gave back" {
+ const rec = canim.open(recordings.steps);
+ var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
+ defer arena.deinit();
+ const nodes = try canim.calls.layout(arena.allocator(), rec, "fib");
+ try expectEqual(@as(usize, 15), nodes.len);
+ try expectEqual(@as(?u64, 5), rec.call("fib", 0).arg);
+ try expectEqual(@as(u64, 5), rec.call("fib", 0).result);
+ try expectEqual(@as(?u64, 1), rec.call("fib", 4).arg);
+ // A node is where it will always be: a parent over the middle of its children.
+ for (nodes) |n| if (n.parent) |p| try expect(nodes[p].level + 1 == n.level);
+}
+
+test "an instrumented program under the debugger tells its calls, variables and stores" {
+ const rec = canim.open(recordings.list);
+ var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
+ defer arena.deinit();
+ const reverse = rec.call("reverse", 0);
+ try expectEqual(@as(usize, 3), rec.allocations.len);
+ // The call begins where the debugger stopped on entering it: the line of its header.
+ try expectEqual(@as(u32, 17), rec.own[reverse.enter]);
+ // A local is not its value until its call has stored to it.
+ const first = rec.lineMoment(18, reverse.enter);
+ const cur = rec.variable(arena.allocator(), rec.moment(first), "cur").?;
+ try expect(!rec.assigned(cur, first));
+ try expect(rec.assigned(cur, rec.lineMoment(21, reverse.enter)));
+ // Three nodes are reached from the program's pointers, each in the place its allocation gives it.
+ const things = canim.objects.reach(arena.allocator(), rec, rec.moment(rec.lineMoment(21, reverse.enter)), null);
+ try expectEqual(@as(usize, 3), things.len);
+ for (things) |o| try expect(o.slot.? < 3);
+}
+
+test "the program's four system calls are found, with what each was given" {
+ const rec = canim.open(recordings.hello);
+ var names: [4][]const u8 = undefined;
+ var n: usize = 0;
+ for (rec.syscalls) |call| {
+ if (call.enter < rec.call("main", 0).enter or n == names.len) continue;
+ names[n] = @import("ztrace").syscalls.name(call.nr) orelse "?";
+ n += 1;
+ }
+ try expectEqual(@as(usize, 4), n);
+ try std.testing.expectEqualStrings("open", names[0]);
+ try std.testing.expectEqualStrings("read", names[1]);
+ try std.testing.expectEqualStrings("close", names[2]);
+ try std.testing.expectEqualStrings("write", names[3]);
+}
+
+test "a walked step is as long as what it changed: fire, a slot a level, the hold, the advance, the rest" {
+ const rec = canim.open(recordings.steps);
+ const scene = struct {
+ var at: canim.Cursor = undefined;
+ fn frame(s: *anim.Frame) void {
+ const r = canim.open(recordings.steps);
+ at = canim.cursor(s, r, r.lineMoment(10, r.call("main", 0).enter));
+ at.levels = .{ .idea = .calls };
+ }
+ };
+ var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
+ defer arena.deinit();
+ var frame: anim.Frame = .{ .t = 0, .clock = 0, .in = undefined, .pointer = .{ 0, 0 }, .arena = arena.allocator() };
+ scene.frame(&frame);
+ const t = canim.theme.time;
+ // main's line calls fib(5): registers, the stack, the call. Three levels, 0.30 s apart.
+ const from = rec.lineMoment(10, rec.call("main", 0).enter);
+ const call = scene.at.reading(from, rec.next(.line, from));
+ try std.testing.expectApproxEqAbs(@as(f32, 3 * t.cascade), call.at[2], 1e-4);
+ try expect(call.total > 2.0 and call.total < 3.0);
+ // A line that changes nothing shown: fire, advance, rest.
+ var quiet = scene.at;
+ quiet.levels = .{ .cpu = false, .memory = false };
+ const line = quiet.reading(rec.lineMoment(4, from), rec.lineMoment(6, from));
+ try std.testing.expectApproxEqAbs(t.fire + t.step + t.rest + t.step_per_row, line.total, 1e-3);
+}
diff --git a/anim/test/sort.script b/anim/test/sort.script
new file mode 100644
index 0000000..4823051
--- /dev/null
+++ b/anim/test/sort.script
@@ -0,0 +1,11 @@
+# The sort scene, headless: it runs to three instants of its timeline without failing.
+# (The pixel assertions written for the first layout were dropped when the
+# frame became the debugger's context; new ones want a settled design: see anim/README.md.)
+frames 2
+console set playing false
+console set t 5
+screenshot .zig-cache/canim/sort-early.png
+console set t 14
+screenshot .zig-cache/canim/sort-mid.png
+console set t 999
+screenshot .zig-cache/canim/sort-end.png
diff --git a/anim/test/syscalls.script b/anim/test/syscalls.script
new file mode 100644
index 0000000..cb9d2f4
--- /dev/null
+++ b/anim/test/syscalls.script
@@ -0,0 +1,11 @@
+# The syscalls scene, headless: it runs to three instants of its timeline without failing.
+# (The pixel assertions written for the first layout were dropped when the
+# frame became the debugger's context; new ones want a settled design: see anim/README.md.)
+frames 2
+console set playing false
+console set t 5
+screenshot .zig-cache/canim/syscalls-early.png
+console set t 14
+screenshot .zig-cache/canim/syscalls-mid.png
+console set t 999
+screenshot .zig-cache/canim/syscalls-end.png
diff --git a/anim/test/title.script b/anim/test/title.script
new file mode 100644
index 0000000..9207ea6
--- /dev/null
+++ b/anim/test/title.script
@@ -0,0 +1,4 @@
+frames 2
+console set playing false
+console set t 999
+screenshot .zig-cache/canim/title-end.png
diff --git a/anim/test/zoom.script b/anim/test/zoom.script
new file mode 100644
index 0000000..d508bb0
--- /dev/null
+++ b/anim/test/zoom.script
@@ -0,0 +1,11 @@
+# The zoom scene, headless: it runs to three instants of its timeline without failing.
+# (The pixel assertions written for the first layout were dropped when the
+# frame became the debugger's context; new ones want a settled design: see anim/README.md.)
+frames 2
+console set playing false
+console set t 5
+screenshot .zig-cache/canim/zoom-early.png
+console set t 14
+screenshot .zig-cache/canim/zoom-mid.png
+console set t 999
+screenshot .zig-cache/canim/zoom-end.png
diff --git a/anim/tools/__pycache__/chart.cpython-314.pyc b/anim/tools/__pycache__/chart.cpython-314.pyc
new file mode 100644
index 0000000..2d61f61
--- /dev/null
+++ b/anim/tools/__pycache__/chart.cpython-314.pyc
Binary files differ
diff --git a/anim/tools/bench.zig b/anim/tools/bench.zig
new file mode 100644
index 0000000..ad6fe4b
--- /dev/null
+++ b/anim/tools/bench.zig
@@ -0,0 +1,91 @@
+//! What a recording costs a frame: `zig build bench` opens each recording
+//! (which indexes it) and times the queries components make of a moment,
+//! walking forward a moment at a time as a playing scene does, and jumping
+//! about as a seek does. Always built ReleaseFast.
+//! `zig build bench -- NAME BY [FUNCTION]` lists a recording's steps instead.
+const std = @import("std");
+const canim = @import("canim");
+const recordings = @import("recordings");
+
+fn now() u64 {
+ var ts: std.os.linux.timespec = undefined;
+ _ = std.os.linux.clock_gettime(.MONOTONIC, &ts);
+ return @as(u64, @intCast(ts.sec)) * std.time.ns_per_s + @as(u64, @intCast(ts.nsec));
+}
+
+/// `bench NAME BY [FUNCTION]`: every stop of kind BY (moment, line, over) in
+/// recording NAME (from FUNCTION's first call on), with what the step to it changed. What a scene's author needs to
+/// know to pace it.
+fn steps(rec: *canim.Recording, by: canim.Recording.Stop, function: ?[]const u8) void {
+ var at: u64 = if (function) |name| rec.call(name, 0).enter else 0;
+ var n: usize = 0;
+ while (at < rec.end()) : (n += 1) {
+ const to = rec.next(by, at);
+ var bytes: u64 = 0;
+ for (rec.written(at, to)) |w| bytes += w.len;
+ std.debug.print("{d:>4} moment {d:>5} line {d:>3} depth {d} wrote {d:>3} bytes in {d} read {d} regs", .{ n, to, rec.own[to], rec.depths[to], bytes, rec.written(at, to).len, rec.read(at, to).len });
+ const mask = rec.registersChanged(at, to);
+ for (@import("ztrace").Regs.names, 0..) |reg, i| if (mask >> @intCast(i) & 1 != 0) std.debug.print(" {s}", .{reg});
+ for (rec.syscalls) |call| if (call.enter > at and call.enter <= to) std.debug.print(" syscall {d}", .{call.nr});
+ std.debug.print("\n", .{});
+ at = to;
+ }
+}
+
+pub fn main(init: std.process.Init) !void {
+ const gpa = init.gpa;
+ const args = try init.minimal.args.toSlice(init.arena.allocator());
+ if (args.len >= 3) {
+ inline for (@typeInfo(recordings).@"struct".decl_names) |name| {
+ if (@TypeOf(@field(recordings, name)) == recordings.Program and std.mem.eql(u8, name, args[1]))
+ return steps(canim.open(@field(recordings, name)), std.meta.stringToEnum(canim.Recording.Stop, args[2]) orelse return error.NoSuchStop, if (args.len > 3) args[3] else null);
+ }
+ return error.NoSuchRecording;
+ }
+ std.debug.print("{s:<8} {s:>7} {s:>9} {s:>8} | ns a query, moments in order: {s:>6} {s:>6} {s:>6} {s:>6} {s:>6} {s:>6} | {s:>9}\n", .{ "", "moments", "bytes", "open ms", "regs", "read64", "vars", "heap", "stack", "reach", "seek us" });
+ inline for (@typeInfo(recordings).@"struct".decl_names) |name| {
+ if (@TypeOf(@field(recordings, name)) != recordings.Program) continue;
+ const program = @field(recordings, name);
+ const start = now();
+ const rec = canim.open(program);
+ const opened = now() - start;
+ // Somewhere memory was written, to read back.
+ const addr: u64 = if (rec.write_spans.all.len > 0) rec.write_spans.all[rec.write_spans.all.len / 2].addr else 0;
+ var took: [6]u64 = @splat(0);
+ var arena: std.heap.ArenaAllocator = .init(gpa);
+ defer arena.deinit();
+ const rounds = @max(1, 20_000 / rec.len());
+ for (0..rounds) |_| for (0..rec.len()) |i| {
+ _ = arena.reset(.retain_capacity);
+ const m = rec.moment(i);
+ var t = now();
+ _ = try m.regs(rec.tid);
+ took[0] += now() - t;
+ t = now();
+ var buf: [64]u8 = undefined;
+ var known: [64]bool = undefined;
+ try m.read(addr, &buf, &known);
+ took[1] += now() - t;
+ t = now();
+ _ = try m.variables(arena.allocator());
+ took[2] += now() - t;
+ t = now();
+ _ = try m.heap(arena.allocator());
+ took[3] += now() - t;
+ t = now();
+ _ = rec.stack(arena.allocator(), i);
+ took[4] += now() - t;
+ t = now();
+ _ = canim.objects.reach(arena.allocator(), rec, m, null);
+ took[5] += now() - t;
+ };
+ // A seek: moments far apart, each replayed from its keyframe.
+ var rng: std.Random.DefaultPrng = .init(1);
+ const seeks = 200;
+ const seek_start = now();
+ for (0..seeks) |_| _ = try rec.moment(rng.random().uintLessThan(u64, rec.len())).regs(rec.tid);
+ const seek = (now() - seek_start) / seeks;
+ const n = rounds * rec.len();
+ std.debug.print("{s:<8} {d:>7} {d:>9} {d:>8.2} | {s:>29} {d:>6} {d:>6} {d:>6} {d:>6} {d:>6} {d:>6} | {d:>9.1}\n", .{ name, rec.len(), program.trace.len, @as(f64, @floatFromInt(opened)) / 1e6, "", took[0] / n, took[1] / n, took[2] / n, took[3] / n, took[4] / n, took[5] / n, @as(f64, @floatFromInt(seek)) / 1e3 });
+ }
+}
diff --git a/anim/tools/chart.py b/anim/tools/chart.py
new file mode 100644
index 0000000..ca783dc
--- /dev/null
+++ b/anim/tools/chart.py
@@ -0,0 +1,42 @@
+#!/usr/bin/env python3
+"""The designer's motion instrument (design/motion/motion.py: timing chart,
+five rule checks, contact sheets), told where canim's panels are now.
+
+ chart.py chart|auto|sheet|onion|track VIDEO ... as motion.py takes them
+
+The video's file name (fib-1080.mp4 -> fib) picks its regions.
+"""
+import os, sys
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "design", "motion"))
+import motion
+
+W = motion.W
+# theme.layout (design revision 2): the state column is the same in every scene; the program
+# column is shared by the scene's split (lens, source, disassembly). The clock is over the caption.
+def panel(rows):
+ return 36 + 24 * rows
+
+def split(lens, source, disasm):
+ y = 48 + (lens + 12 if lens else 0)
+ out = {"lens": (64, 48, 880, lens)} if lens else {}
+ out["source"] = (64, y, 880, panel(source))
+ out["disasm"] = (64, y + panel(source) + 12, 880, panel(disasm))
+ return out
+
+# The clock is under the name the instrument gives to words that are not panels ("head"):
+# its progress line moves with every step and must not count as a panel starting.
+state = {"head": (0, 888, W, 46), "registers": (976, 48, 880, panel(18)), "stack": (976, 528, 880, panel(8)), "backtrace": (976, 768, 880, panel(3))}
+CAPTION = (0, 934, W, 146)
+beside, subject, none = split(312, 8, 10), split(432, 5, 8), split(0, 14, 17)
+motion.REGIONS.update({
+ "fib": {**beside, **state, "caption": CAPTION},
+ "sort": {**beside, **state, "caption": CAPTION},
+ "syscalls": {**beside, **state, "caption": CAPTION},
+ "list": {**subject, **state, "caption": CAPTION},
+ "zoom": {**none, **state, "caption": CAPTION},
+})
+_regions_for = motion.regions_for
+motion.regions_for = lambda video, name: _regions_for(video, name or os.path.basename(video).split("-")[0].split(".")[0])
+
+if __name__ == "__main__":
+ motion.main() if hasattr(motion, "main") else sys.exit("design/motion/motion.py has no main()")
diff --git a/anim/tools/fib.c b/anim/tools/fib.c
new file mode 100644
index 0000000..975f1a6
--- /dev/null
+++ b/anim/tools/fib.c
@@ -0,0 +1,12 @@
+#include <stdio.h>
+
+long fib(long n) {
+ if (n < 2)
+ return n;
+ return fib(n-1) + fib(n-2);
+}
+
+int main(void) {
+ printf("%ld\n", fib(5));
+ return 0;
+}
diff --git a/anim/tools/hello.c b/anim/tools/hello.c
new file mode 100644
index 0000000..8f3bb7d
--- /dev/null
+++ b/anim/tools/hello.c
@@ -0,0 +1,11 @@
+#include <fcntl.h>
+#include <unistd.h>
+
+int main(void) {
+ char buf[32];
+ int f = open("note", 0);
+ int n = read(f, buf, 32);
+ close(f);
+ write(1, buf, n);
+ return 0;
+}
diff --git a/anim/tools/list.c b/anim/tools/list.c
new file mode 100644
index 0000000..99836c5
--- /dev/null
+++ b/anim/tools/list.c
@@ -0,0 +1,44 @@
+#include <stdlib.h>
+
+typedef struct node {
+ long value;
+ struct node *next;
+} node;
+
+node *head;
+
+void push(long value) {
+ node *n = malloc(sizeof *n);
+ n->value = value;
+ n->next = head;
+ head = n;
+}
+
+void reverse(void) {
+ node *prev = NULL;
+ node *cur = head;
+ while (cur) {
+ node *next = cur->next;
+ cur->next = prev;
+ prev = cur;
+ cur = next;
+ }
+ head = prev;
+}
+
+void clear(void) {
+ while (head) {
+ node *n = head;
+ head = n->next;
+ free(n);
+ }
+}
+
+int main(void) {
+ push(7);
+ push(12);
+ push(9);
+ reverse();
+ clear();
+ return 0;
+}
diff --git a/anim/tools/motion.py b/anim/tools/motion.py
new file mode 100644
index 0000000..9bf0a39
--- /dev/null
+++ b/anim/tools/motion.py
@@ -0,0 +1,210 @@
+#!/usr/bin/env python3
+"""Motion, made visible: a scene judged by how it moves, not by its stills.
+
+ motion.py SCENE_EXE OUT_DIR [--size 960x540] [--fps 60]
+
+Exports the scene twice (it is deterministic) and writes into OUT_DIR:
+
+ change.png how much of the picture changes from each frame to the
+ next: the whole frame on top (log scale), then a lane for
+ each panel, the head and the caption. Holds are gaps,
+ a metronome is evenly spaced spikes, overlapping action
+ is lanes that light one after another.
+ change-NN.png the same, ten seconds a picture, a frame about two pixels.
+ sheet-NN.png contact sheets: a row for each transition (a run of
+ frames in which something changes), six frames of it
+ side by side, cropped to where the change is, with its
+ length and the hold after it.
+ transitions.txt every transition: when, how long, how much, which panels
+ in what order, and the hold that follows.
+
+and prints the summary: how many transitions, how long the holds are, how
+regular the beat is.
+"""
+import os, subprocess, sys
+import numpy as np
+from PIL import Image, ImageDraw
+import matplotlib
+matplotlib.use("Agg")
+import matplotlib.pyplot as plt
+
+args = [a for a in sys.argv[1:] if not a.startswith("--")]
+opts = dict(zip(sys.argv[1:], sys.argv[2:]))
+exe, out = args[0], args[1]
+W, H = (int(v) for v in opts.get("--size", "960x540").split("x"))
+FPS = int(opts.get("--fps", "60"))
+os.makedirs(out, exist_ok=True)
+for old in os.listdir(out):
+ if old.startswith(("sheet-", "change")) or old == "transitions.txt":
+ os.remove(os.path.join(out, old))
+
+# A pixel has changed when any channel moved by more than this: above what
+# antialiasing does to a still edge, below the faintest ember.
+THRESHOLD = 10
+# A frame is moving when this share of it changed; transitions closer than
+# GAP frames are one (a strike, then its cooling).
+ACTIVE = 0.0002
+GAP = 4
+
+
+def frames(want=None):
+ """The scene's frames in order, as H x W x 3 arrays; with `want` (a set of indices), those alone."""
+ env = dict(os.environ, CANIM_PANELS="1")
+ # The scene says where its panels are, a line a panel a frame: kept aside, read once.
+ log = open(os.path.join(out, "panels.log"), "w+")
+ p = subprocess.Popen([exe, "--state", os.path.join(out, "motion.state"), "--export", "-", "--size", f"{W}x{H}", "--fps", str(FPS)],
+ stdout=subprocess.PIPE, stderr=log, env=env)
+ size, i = W * H * 4, 0
+ while True:
+ raw = p.stdout.read(size)
+ if len(raw) < size:
+ break
+ if want is None or i in want:
+ yield i, np.frombuffer(raw, np.uint8).reshape(H, W, 4)[:, :, :3]
+ i += 1
+ p.wait()
+ log.seek(0)
+ frames.stderr = log.read()
+ log.close()
+ os.remove(os.path.join(out, "panels.log"))
+
+
+# Pass one: what changes, frame by frame, in the whole picture and in each region.
+regions = {"head": (0, 0, W, int(H * 112 / 1080)), "caption": (0, int(H * 896 / 1080), W, H)}
+# The scene says where its panels are on frame 45, so each frame's change
+# is kept small (a 96 x 54 map of where) and cut into lanes afterwards.
+whole, maps, boxes, prev, n = [], [], [], None, 0
+for i, frame in frames():
+ n = i + 1
+ # Every second pixel each way is enough to see what moves, four times sooner.
+ now = frame[::2, ::2].copy()
+ changed = np.zeros(now.shape[:2], bool) if prev is None else ((np.maximum(now, prev) - np.minimum(now, prev)).max(axis=2) > THRESHOLD)
+ prev = now
+ whole.append(float(changed.mean()))
+ maps.append(changed.reshape(54, changed.shape[0] // 54, 96, changed.shape[1] // 96).mean(axis=(1, 3)).astype(np.float32))
+ ys, xs = np.nonzero(changed)
+ boxes.append((2 * xs.min(), 2 * ys.min(), 2 * xs.max() + 2, 2 * ys.max() + 2) if len(xs) else None)
+whole = np.array(whole)
+
+# Where each panel is when it first shows (before any camera move).
+for line in frames.stderr.splitlines():
+ if line.startswith("canim-panel "):
+ x0, y0, x1, y1, name = line.split(" ", 5)[1:]
+ if name not in regions:
+ regions[name] = (max(0, int(float(x0) * W)), max(0, int(float(y0) * H)), min(W, int(float(x1) * W)), min(H, int(float(y1) * H)))
+lanes = {}
+for name, (x0, y0, x1, y1) in regions.items():
+ cx0, cy0, cx1, cy1 = x0 * 96 // W, y0 * 54 // H, max(x1 * 96 // W, x0 * 96 // W + 1), max(y1 * 54 // H, y0 * 54 // H + 1)
+ lanes[name] = np.array([m[cy0:cy1, cx0:cx1].mean() for m in maps])
+
+# Transitions: runs of moving frames, bridged over short gaps.
+moving = whole > ACTIVE
+runs, i = [], 0
+while i < n:
+ if not moving[i]:
+ i += 1
+ continue
+ j = i
+ while j + 1 < n and (moving[j + 1] or moving[j + 1:j + 1 + GAP].any()):
+ j += 1
+ runs.append((i, j))
+ i = j + 1
+
+def order(a, b):
+ """The panels that move in frames a..b, each with the frame it starts at after a."""
+ firsts = []
+ for name, lane in lanes.items():
+ hit = np.nonzero(lane[a:b + 1] > ACTIVE * 4)[0]
+ if len(hit):
+ firsts.append((int(hit[0]), name))
+ return sorted(firsts)
+
+with open(os.path.join(out, "transitions.txt"), "w") as f:
+ f.write(f"{exe}: {n} frames, {n / FPS:.2f} s at {FPS} fps; {len(runs)} transitions\n")
+ f.write(" # start frames length peak hold after panels, in the order they start (frames after the first)\n")
+ for k, (a, b) in enumerate(runs):
+ hold = (runs[k + 1][0] if k + 1 < len(runs) else n) - b - 1
+ who = " ".join(f"{name}+{d}" for d, name in order(a, b))
+ f.write(f"{k:3d} {a / FPS:7.2f}s {a:5d}-{b:<5d} {(b - a + 1) / FPS:6.2f}s {whole[a:b + 1].max() * 100:5.1f}% {hold / FPS:6.2f}s {who}\n")
+
+# The plot: the whole frame, then a lane each.
+names = list(regions)
+def plot(path, a, b):
+ t = np.arange(a, b) / FPS
+ fig, axes = plt.subplots(2, 1, figsize=(min(20, max(8, (b - a) / FPS * 1.8)), 2.4 + 0.32 * len(names)), sharex=True,
+ gridspec_kw={"height_ratios": [2.2, 0.32 * len(names) + 0.4]})
+ ax = axes[0]
+ ax.fill_between(t, np.maximum(whole[a:b] * 100, 0.005), 0.005, color="#ff6a4a", step="mid", linewidth=0)
+ ax.set_yscale("log"); ax.set_ylim(0.005, 100); ax.set_ylabel("% of frame changed")
+ for (s, e) in runs:
+ if e >= a and s < b:
+ ax.axvspan(s / FPS, (e + 1) / FPS, color="#e8c46a", alpha=0.18, linewidth=0)
+ ax.grid(True, which="major", axis="both", alpha=0.25)
+ grid = np.array([lanes[name][a:b] for name in names])
+ axes[1].imshow(np.sqrt(grid), aspect="auto", cmap="magma", vmin=0, vmax=0.5, extent=(a / FPS, b / FPS, len(names), 0), interpolation="nearest")
+ axes[1].set_yticks(np.arange(len(names)) + 0.5); axes[1].set_yticklabels(names)
+ axes[1].set_xlabel("seconds")
+ fig.tight_layout(); fig.savefig(path, dpi=110); plt.close(fig)
+
+plot(os.path.join(out, "change.png"), 0, n)
+for k, a in enumerate(range(0, n, 10 * FPS)):
+ plot(os.path.join(out, f"change-{k:02d}.png"), a, min(n, a + 10 * FPS))
+
+# Contact sheets: six frames of each transition, cropped to where it happens.
+TILE, COLS, ROWS = (320, 180), 6, 5
+picks = {}
+for k, (a, b) in enumerate(runs):
+ # From two frames before to where it has settled, evenly.
+ span = np.linspace(max(a - 2, 0), min(b + 3, n - 1), COLS).round().astype(int)
+ picks[k] = list(span)
+want = {int(i) for span in picks.values() for i in span}
+kept = {i: frame.copy() for i, frame in frames(want)}
+
+def crop(a, b):
+ """The box the change of frames a..b happens in, grown to the tile's shape, at least a quarter of the frame."""
+ found = [bx for bx in boxes[a:b + 1] if bx is not None]
+ if not found:
+ return (0, 0, W, H)
+ x0, y0 = min(bx[0] for bx in found), min(bx[1] for bx in found)
+ x1, y1 = max(bx[2] for bx in found), max(bx[3] for bx in found)
+ w = max(x1 - x0 + 40, W // 4, int((y1 - y0 + 40) * 16 / 9))
+ w = min(W, w); h = min(H, int(w * 9 / 16))
+ cx, cy = (x0 + x1) // 2, (y0 + y1) // 2
+ left = min(max(cx - w // 2, 0), W - w); top = min(max(cy - h // 2, 0), H - h)
+ return (left, top, left + w, top + h)
+
+for s in range(0, len(runs), ROWS):
+ sheet = Image.new("RGB", (COLS * TILE[0], min(ROWS, len(runs) - s) * (TILE[1] + 22)), "#000000")
+ draw = ImageDraw.Draw(sheet)
+ for r, k in enumerate(range(s, min(s + ROWS, len(runs)))):
+ a, b = runs[k]
+ box = crop(a, b)
+ hold = (runs[k + 1][0] if k + 1 < len(runs) else n) - b - 1
+ y = r * (TILE[1] + 22)
+ draw.text((6, y + 4), f"#{k} {a / FPS:.2f}s frames {a}-{b} {(b - a + 1) / FPS:.2f}s long, then still {hold / FPS:.2f}s " + " ".join(f"{name}+{d}" for d, name in order(a, b)), fill="#eee6d2")
+ for c, i in enumerate(picks[k]):
+ tile = Image.fromarray(kept[int(i)]).crop(box).resize(TILE, Image.LANCZOS)
+ sheet.paste(tile, (c * TILE[0], y + 22))
+ draw.text((c * TILE[0] + 6, y + 26), f"{int(i)}", fill="#e8c46a")
+ sheet.save(os.path.join(out, f"sheet-{s // ROWS:02d}.png"))
+
+# The summary: the beat, and whether it is a metronome.
+starts = np.array([a for a, _ in runs]) / FPS
+lengths = np.array([b - a + 1 for a, b in runs]) / FPS
+holds = np.array([(runs[k + 1][0] if k + 1 < len(runs) else n) - runs[k][1] - 1 for k in range(len(runs))]) / FPS
+gaps = np.diff(starts)
+print(f"{os.path.basename(exe)}: {n / FPS:.1f} s, {len(runs)} transitions; moving {moving.mean() * 100:.0f}% of the time")
+if len(runs) > 2:
+ print(f" transitions last {np.median(lengths):.2f} s (median), {lengths.min():.2f} to {lengths.max():.2f}")
+ print(f" holds: median {np.median(holds):.2f} s, shortest {holds.min():.2f} s; {int((holds < 0.25).sum())} under 0.25 s")
+ same = np.abs(gaps[1:] - gaps[:-1]) < 0.02
+ longest, cur = 0, 0
+ for v in same:
+ cur = cur + 1 if v else 0
+ longest = max(longest, cur)
+ print(f" beat: {len(set(np.round(gaps, 2)))} different intervals between starts; longest run of equal ones: {longest + 1}")
+print(f" sheets and plots in {out}")
+try:
+ os.remove(os.path.join(out, "motion.state"))
+except OSError:
+ pass
diff --git a/anim/tools/note b/anim/tools/note
new file mode 100644
index 0000000..de75b8f
--- /dev/null
+++ b/anim/tools/note
@@ -0,0 +1 @@
+Hello, kernel!
diff --git a/anim/tools/sort.c b/anim/tools/sort.c
new file mode 100644
index 0000000..5816390
--- /dev/null
+++ b/anim/tools/sort.c
@@ -0,0 +1,22 @@
+int a[8] = {4, 9, 17, 31, 12, 26, 5, 20};
+
+void swap(int *x, int *y) {
+ int t = *x;
+ *x = *y;
+ *y = t;
+}
+
+void sort(int n) {
+ for (int i = 1; i < n; i++) {
+ int j = i;
+ while (j > 0 && a[j - 1] > a[j]) {
+ swap(&a[j - 1], &a[j]);
+ j--;
+ }
+ }
+}
+
+int main(void) {
+ sort(8);
+ return 0;
+}
diff --git a/anim/zig-pkg b/anim/zig-pkg
new file mode 120000
index 0000000..466b201
--- /dev/null
+++ b/anim/zig-pkg
@@ -0,0 +1 @@
+../../02-pardes-code/zig-pkg \ No newline at end of file