diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/abi.zig | 105 | ||||
| -rw-r--r-- | src/abi_hash.zig | 9 | ||||
| -rw-r--r-- | src/anim/Painter.zig | 262 | ||||
| -rw-r--r-- | src/anim/player.zig | 386 | ||||
| -rw-r--r-- | src/anim/root.zig | 1136 | ||||
| -rw-r--r-- | src/anim/typst.zig | 10 | ||||
| -rw-r--r-- | src/gpu/Executor.zig | 26 | ||||
| -rw-r--r-- | src/host/Console.zig | 526 | ||||
| -rw-r--r-- | src/host/Host.zig | 468 | ||||
| -rw-r--r-- | src/host/Sessions.zig | 1599 | ||||
| -rw-r--r-- | src/host/audio.zig | 266 | ||||
| -rw-r--r-- | src/host/control.zig | 339 | ||||
| -rw-r--r-- | src/host/fields.zig | 37 | ||||
| -rw-r--r-- | src/host/library.zig | 118 | ||||
| -rw-r--r-- | src/host/memory.zig | 586 | ||||
| -rw-r--r-- | src/host/overlay.zig | 4 | ||||
| -rw-r--r-- | src/host/probe.zig | 86 | ||||
| -rw-r--r-- | src/host/root.zig | 292 | ||||
| -rw-r--r-- | src/host/script.zig | 451 | ||||
| -rw-r--r-- | src/host/state_files.zig | 303 | ||||
| -rw-r--r-- | src/host/timeline.zig | 329 | ||||
| -rw-r--r-- | src/layout.zig | 66 | ||||
| -rw-r--r-- | src/scope/root.zig | 91 | ||||
| -rw-r--r-- | src/sketch/request.zig | 2 | ||||
| -rw-r--r-- | src/sketch/root.zig | 72 | ||||
| -rw-r--r-- | src/sketch/sfxr.zig | 267 | ||||
| -rw-r--r-- | src/sketch/web.zig | 35 | ||||
| -rw-r--r-- | src/vector/morph.zig | 60 | ||||
| -rw-r--r-- | src/vector/svg.zig | 96 |
29 files changed, 6217 insertions, 1810 deletions
diff --git a/src/abi.zig b/src/abi.zig index 7177f14..6411b0d 100644 --- a/src/abi.zig +++ b/src/abi.zig @@ -5,11 +5,13 @@ //! tagged unions, `std.mem.Allocator`. Two rules keep reloads safe: //! - whatever outlives a call lives in host memory (host code is never //! unloaded, so host allocators and function pointers stay valid); -//! - `hash` covers the layout of every type here, and a host refuses a sketch -//! built against different definitions instead of misreading its memory. +//! - `hash` covers the layout of every type here and the compiler, backend +//! and mode, and a host refuses a sketch built against different +//! definitions or by another build instead of misreading its memory. //! //! Only `Event` and the reflected `Layout` are `extern`: they are written to disk. const std = @import("std"); +const builtin = @import("builtin"); pub const layout = @import("layout.zig"); pub const Key = @import("keys.zig").Key; @@ -114,6 +116,11 @@ pub const Event = extern struct { /// `flags` bit for a held key's auto-repeat. pub const repeat: u8 = 1; + /// The key of a `key_down` or `key_up`. + pub fn key(e: Event) Key { + return @fromBackingInt(@intCast(@as(u8, @truncate(e.code)))); + } + /// For mouse and wheel events: the modifier keys held as it happened, /// as `Key.Mod` bits. Read this rather than `Input.held`, which is the /// state after the frame's events, and misses modifiers that come with @@ -158,6 +165,9 @@ pub const Stream = struct { queued: u32 = 0, /// Samples pushed since the stream was last cleared. pushed: u64 = 0, + /// Pushes that found it empty though the frame before had pushed to + /// it: each a gap in its sound. + underruns: u32 = 0, }; /// Everything a sketch learns about the world for one call. @@ -211,6 +221,11 @@ pub const Input = struct { keys: std.StaticBitSet(256) = .empty, streams: []const Stream = &.{}, sample_rate: u32 = 48_000, + /// How many samples a stream should hold after this frame's push, as + /// the host measures it: enough to outlast the slowest recent frame and + /// the device's next pull, and more after an underrun. A sketch that + /// makes its sound as it goes pushes `lead -| stream(key).queued`. + lead: u32 = 4800, /// Mono samples at `sample_rate` recorded since the previous frame, while /// `draw` declares `Command.microphone`. Only `draw` sees them: they come /// from a device, not from events, so they do not replay. @@ -296,13 +311,18 @@ pub const Voice = struct { volume: f32 = 1, /// Linear fade at both ends, in samples. fade: u32 = 0, + /// Playback speed, as pitch: 2 is an octave up and half as long, 0 + /// holds it. Changing it does not restart the voice. + rate: f32 = 1, + /// Whose gain (`Command.gain`) also scales it: music, speech, effects. + group: u3 = 0, }; /// Slices must stay alive until the host consumes the frame, right after /// `draw` returns. `sketch.Frame` copies the small ones (text, GPU /// descriptions, uniforms) into scratch memory itself; bulk data (vertices, -/// samples, pixels, uploads) must already live in scratch, session or store -/// memory, or be a literal. +/// samples, pixels, uploads) must already live in scratch or session memory, +/// or be a literal. pub const Command = union(enum) { clear: Color, rect: struct { dst: Rect, color: Color }, @@ -365,6 +385,15 @@ pub const Command = union(enum) { voice: Voice, /// Mono samples at `Input.sample_rate` for stream `key`. audio: struct { key: u32, samples: []const f32, clear: bool = false }, + /// `count` mono samples (f32) that a compute shader left in `buffer` + /// at `offset`, for stream `key`: queued like `audio`'s once the GPU + /// has made them. Natively that is within this frame (the host waits + /// for the GPU's work so far); on the web they arrive a frame or two + /// later and count as queued meanwhile. + audio_buffer: struct { key: u32, buffer: Buffer, offset: u32 = 0, count: u32 }, + /// The gain of a group of voices (`Voice.group`) this frame; a group + /// not given one plays at 1. Declared like a voice, so it replays. + gain: struct { group: u3, gain: f32 }, /// RGBA8 rows of `w * 4` bytes into an image made by `Host.newImage`. pixels: struct { image: Image, w: u32, h: u32, rgba: []const u8, premultiplied: bool = false }, /// Renders a GPU pass into an image made by `Host.newImage`, when @@ -625,12 +654,16 @@ pub const Host = struct { /// WAV, FLAC or Ogg Vorbis bytes in memory. Not cached. `.none` if /// they do not decode. decodeSound: *const fn (*anyopaque, []const u8) Audio, + /// Samples a sketch made, copied: see `Host.newSound`. + newSound: *const fn (*anyopaque, [*]const f32, usize) callconv(.c) Audio, /// A loaded sound's samples: mono, at `Input.sample_rate`, alive as /// long as the host. Empty for `.none`. samples: *const fn (*anyopaque, Audio) []const f32, /// The whole file, mapped for the life of the host; empty if missing. readFile: *const fn (*anyopaque, []const u8) []const u8, - env: *const fn (*anyopaque, []const u8) ?[]const u8, + /// See `Host.appendFile`: name, then bytes; `replace` for `writeFile`. + appendFile: *const fn (*anyopaque, [*]const u8, usize, [*]const u8, usize, bool) callconv(.c) [*:0]const u8, + env:*const fn (*anyopaque, []const u8) ?[]const u8, /// A monotonic clock in nanoseconds, for measuring, not for state: /// `update` must use `Input` time to stay replayable. clock: *const fn (*anyopaque) u64, @@ -689,12 +722,35 @@ pub const Host = struct { pub fn decodeSound(h: Host, wav: []const u8) Audio { return h.vtable.decodeSound(h.ctx, wav); } + /// Mono samples at `Input.sample_rate`, copied into the host: a sound + /// for `Voice.audio` like a loaded one (synthesised one-shots become + /// voices, reconciled and replay-safe). Kept for the life of the host, + /// like every sound: make each once (in `setup`, or cached in Session). + /// `.none` if a sample is not finite. + pub fn newSound(h: Host, sound: []const f32) Audio { + return h.vtable.newSound(h.ctx, sound.ptr, sound.len); + } pub fn samples(h: Host, audio: Audio) []const f32 { return h.vtable.samples(h.ctx, audio); } pub fn readFile(h: Host, path: []const u8) []const u8 { return h.vtable.readFile(h.ctx, path); } + /// Appends `bytes` to the sketch's file `name` (no `/` in it), + /// creating it: `<stem>.<name>`, beside the save `<stem>.xitdb` (in + /// `.sketchbook/` under `zig build run`). Returns the file's path, for + /// `readFile`, or "" when nothing was written, which on the web is + /// always. Only `draw` and `command` can write, and a write is not + /// replayed, like sound. `readFile` maps a file once: what is appended + /// to it afterwards is not in what it returned. + pub fn appendFile(h: Host, name: []const u8, bytes: []const u8) []const u8 { + return std.mem.span(h.vtable.appendFile(h.ctx, name.ptr, name.len, bytes.ptr, bytes.len, false)); + } + /// `appendFile` to a new, empty file of that name: what the old one + /// held is gone (a `readFile` of it keeps its bytes). + pub fn writeFile(h: Host, name: []const u8, bytes: []const u8) []const u8 { + return std.mem.span(h.vtable.appendFile(h.ctx, name.ptr, name.len, bytes.ptr, bytes.len, true)); + } pub fn env(h: Host, name: []const u8) ?[]const u8 { return h.vtable.env(h.ctx, name); } @@ -714,12 +770,8 @@ pub const Context = struct { /// This process: survives reloads; frees one allocation at a time, and /// releases the rest when Session's layout changes. session: std.mem.Allocator, - /// On disk, next to the state file: survives reloads and restarts, at - /// the same addresses, so Store may point into it. - store: std.mem.Allocator, - /// The sketch's `Session` and `Store` values. + /// The sketch's `Session` value. session_root: [*]u8, - store_root: [*]u8, /// Filled by `draw`, using `scratch`. commands: *std.ArrayList(Command), }; @@ -768,13 +820,23 @@ pub const Info = struct { height: u32, state: Layout, session: Layout, - store: Layout, /// Console completions offered by the sketch. commands: []const []const u8 = &.{}, + /// What the sketch was built from: its repository's revision ("jj:<commit> + /// <change>", "git:<sha>[+dirty]", or nothing), then `build`. Each + /// stretch of a recorded session keeps it. + source: []const u8 = "", + /// Whether the save keeps history, or only the present and the marks + /// (`App.Options.record`; Debug builds keep it unless told otherwise). + record: bool = false, + /// Samples the sound device takes at once, asked of SDL when the host + /// opens it (`SDL_AUDIO_DEVICE_SAMPLE_FRAMES` in the environment wins); + /// 0 is SDL's own, 1024 at 48 kHz. The app's `audio_pull`. + audio_pull: u32 = 0, }; /// Which memory `sketch_defaults` fills. -pub const Memory = enum(u8) { state, session, store }; +pub const Memory = enum(u8) { state, session }; /// The entry points of a sketch, exported from libraries under these names. /// What became of a console line offered to a sketch. @@ -796,8 +858,7 @@ pub const Sketch = struct { setup: *const fn (*const Context) callconv(.c) bool, /// Deterministic: new state from state and input, nothing else. update: *const fn (*const Context, [*]u8) callconv(.c) void, - /// Presentation: reads state, may change session and store, appends - /// commands. + /// Presentation: reads state, may change session, appends commands. draw: *const fn (*const Context, [*]const u8) callconv(.c) void, /// A console line the host did not understand. command: *const fn (*const Context, [*]u8, *const []const u8) callconv(.c) Outcome, @@ -813,8 +874,16 @@ pub const Sketch = struct { }; }; -/// Layout hash of everything above. Changes whenever a shared type does. -pub const hash: u64 = blk: { +/// `layout_hash` and `build`: changes whenever a shared type does, or the +/// compiler, backend or optimize mode, since Zig's own calling convention +/// (`Host.VTable`, every `std.mem.Allocator`) differs between them. +/// `layout_hash` costs half a second of comptime, so build.zig has +/// `abi_hash.zig` compute it once per change of these files and hands it +/// over as the module `abi_hash`, instead of every sketch's compile doing it. +pub const hash: u64 = std.hash.Wyhash.hash(@import("abi_hash").layout, build); + +/// Hash of every shared type's name and layout. +pub const layout_hash: u64 = blk: { @setEvalBranchQuota(1_000_000); var h: u64 = 0; for (.{ Rect, Color, BlendMode, Corners, Event, Mode, Stream, Input, Image, Audio, Cursor, Voice, Command, gpu.Pass, gpu.Pipeline, gpu.Draw, gpu.Dispatch, gpu.PostProcess, Host, Host.VTable, Context, Field, Layout, Info, Memory, Sketch }) |T| { @@ -823,6 +892,10 @@ pub const hash: u64 = blk: { break :blk h; }; +/// The compiler, backend and mode of this build, exported by libraries as +/// `sketch_build` so a host can say why it refuses one. +pub const build = builtin.zig_version_string ++ " " ++ @tagName(builtin.zig_backend) ++ " " ++ @tagName(builtin.mode); + test "vertex attributes and std140 checks come from the types" { const Vertex = extern struct { position: [2]f32, color: [4]u8, uv: [2]f32 }; const attrs = gpu.attributes(Vertex); diff --git a/src/abi_hash.zig b/src/abi_hash.zig new file mode 100644 index 0000000..9cd01cf --- /dev/null +++ b/src/abi_hash.zig @@ -0,0 +1,9 @@ +//! Prints `abi.layout_hash` as Zig source: build.zig runs this once per change +//! of the abi sources and hands the result to host and sketches as the module +//! `abi_hash`. +const std = @import("std"); +const abi = @import("abi"); + +pub fn main(init: std.process.Init) !void { + try std.Io.File.stdout().writeStreamingAll(init.io, std.fmt.comptimePrint("pub const layout: u64 = 0x{x};\n", .{abi.layout_hash})); +} diff --git a/src/anim/Painter.zig b/src/anim/Painter.zig new file mode 100644 index 0000000..f317dc1 --- /dev/null +++ b/src/anim/Painter.zig @@ -0,0 +1,262 @@ +//! Draws a scene's `Shot` with the vector library, on the GPU (or the CPU), +//! the scene's frame fitted into the canvas, and the canvas the room the +//! host has: the window, or an export's `--size`. The player paints with +//! one, and so does a sketch that runs a `Deck` itself: a `Painter` in its +//! Session, and `paint` once a frame. +const std = @import("std"); +const sk = @import("sketch"); +const vector = @import("vector"); +const anim = @import("root.zig"); +const geom = vector.geom; + +const Painter = @This(); + +/// A renderer per run of vector objects between custom ones (`paint`). +gpu: std.ArrayList(vector.Renderer(.gpu)) = .empty, +cpu: std.ArrayList(vector.Renderer(.cpu)) = .empty, +/// Drawings by what they look like (`Object.id`), built on first use and +/// dropped on reload, since the code that builds them may have changed. +/// Their memory is the host's, kept across reloads. +arena: ?std.heap.ArenaAllocator = null, +drawings: std.AutoHashMapUnmanaged(u64, Built) = .empty, +/// Shapes drawn in the last frame. +shapes: usize = 0, + +pub const Options = struct { + /// The viewer's own pan and zoom, on top of the scene's camera. + view: sk.Camera = .{}, + backend: vector.Backend = .gpu, + /// Boxes, origins and axes, in scene units, with their numbers. + guides: bool = false, + /// The page (0xRRGGBB). + background: u32 = anim.background, +}; + +const Built = struct { drawing: vector.Drawing, bounds: geom.Rect }; + +/// Sets the canvas to the window and draws `shot` on it. `svgs` has +/// `find(source) ?[]const u8` for its Typst objects (`sb.addTypst`). +pub fn paint(p: *Painter, f: *sk.Frame, shot: anim.Shot, svgs: anytype, options: Options) !void { + // All the room there is: the window, or the size an export asks for. + const canvas: sk.Rect = .{ .w = @max(@floor(f.in.window_width), 1), .h = @max(@floor(f.in.window_height), 1) }; + f.canvas(@intFromFloat(canvas.w), @intFromFloat(canvas.h)); + if (p.arena == null) p.arena = .init(f.session); + // A live scene may make new drawings every frame: start over now and then. + if (f.in.reloaded or p.drawings.count() > 1024) { + _ = p.arena.?.reset(.retain_capacity); + p.drawings = .empty; + } + // Use the host's GPU when it has one. + if (options.backend == .gpu and f.host.gpu()) try p.paintLayers(&p.gpu, f, shot, svgs, canvas, options) else try p.paintLayers(&p.cpu, f, shot, svgs, canvas, options); +} + +/// Canvas pixels per scene unit: the scene's frame, fitted into `canvas`. +pub fn fit(canvas: sk.Rect) f32 { + return @min(canvas.w / anim.width, canvas.h / anim.height); +} + +/// Object `o`'s drawing, centered on its origin, and its bounds. +fn built(p: *Painter, o: anim.Object, svgs: anytype) anim.BuildError!Built { + const id = o.id(); + if (p.drawings.get(id)) |b| return b; + const arena = p.arena.?.allocator(); + // A part, or what is left of an object parts were taken from: shapes + // of a whole drawing, which is built (parsed) once. + const d = if (o.source == .part or o.cut.len > 0) try anim.sift(arena, (try p.built(o.whole(), svgs)).drawing, o) else try anim.build(arena, o, svgs); + const b: Built = .{ .drawing = d, .bounds = d.bounds().rect() }; + try p.drawings.put(arena, id, b); + return b; +} + +/// Scene units to canvas pixels: the scene's camera, then the viewer's. +/// The scene's origin is the canvas center. +fn stage(view: sk.Camera, cam: anim.Camera, canvas: sk.Rect) geom.Affine { + const k = fit(canvas) * cam.zoom; + return geom.Affine.translate(view.x, view.y) + .mul(.scale(view.zoom, view.zoom)) + .mul(.translate(canvas.w / 2, canvas.h / 2)) + .mul(.scale(k, k)) + .mul(.rotate(-cam.rotation)) + .mul(.translate(-cam.x, -cam.y)); +} + +/// The next of `layers`, begun: a renderer the size of the canvas. +fn begun(layers: anytype, used: *usize, f: *sk.Frame, canvas: sk.Rect, clear: vector.Drawing.Color) !*@TypeOf(layers.items[0]) { + if (used.* == layers.items.len) try layers.append(f.session, try .init(f.session, f.host, @intFromFloat(canvas.w), @intFromFloat(canvas.h))); + const r = &layers.items[used.*]; + used.* += 1; + r.begin(f, clear); + return r; +} + +/// Draws `shot` with the renderers in `layers` (either backend), objects +/// in the order they were added. Vector objects go into a renderer's image, +/// which is then drawn on the canvas; a custom object draws on the canvas +/// itself. So the vector objects before a custom one and those after it +/// are separate images, one renderer each: every GPU pass of a frame runs +/// before its first 2D command, and one image could only show the last. +fn paintLayers(p: *Painter, layers: anytype, f: *sk.Frame, shot: anim.Shot, svgs: anytype, canvas: sk.Rect, options: Options) !void { + if (layers.items.len > 0 and (layers.items[0].width() != @as(u32, @intFromFloat(canvas.w)) or layers.items[0].height() != @as(u32, @intFromFloat(canvas.h)))) { + for (layers.items) |*r| r.deinit(f.host); + layers.clearRetainingCapacity(); + } + const world = stage(options.view, shot.camera, canvas); + var used: usize = 0; + // The first layer is the background too. + var open: ?*@TypeOf(layers.items[0]) = try begun(layers, &used, f, canvas, anim.color(options.background)); + var shapes: usize = 0; + for (shot.objects, shot.poses, 0..) |o, pose, i| { + if (!pose.visible or pose.opacity <= 0) continue; + const m = world.mul(model(pose)); + if (o.source == .custom) { + if (open) |r| r.present(f, canvas); + open = null; + o.source.custom.draw(o.source.custom.ctx, f, .{ .t = shot.t, .pose = pose, .xf = m, .scale = m.scaleFactor(), .stage = world, .values = shot.values }); + // It leaves no target, clip or blend behind. + f.target(.none); + f.blend(.alpha); + continue; + } + const r = open orelse try begun(layers, &used, f, canvas, .{ 0, 0, 0, 0 }); + open = r; + const d = (try p.built(o, svgs)).drawing; + if (pose.into != anim.Pose.none and pose.morph > 0 and pose.morph < 1 and shot.objects[pose.into].source != .custom) { + // Morphing: from where this object began the transform to where + // its target will stand. + const morph = shot.morphs[i]; + // Into the whole target, parts and all: parts taken from it + // once it is made stand where they were and show as it does. + var into = shot.objects[pose.into]; + into.cut = &.{}; + const target = (try p.built(into, svgs)).drawing; + const between = try vector.morph.between(f.scratch, d, world.mul(model(morph.from)), target, world.mul(model(morph.to)), pose.morph); + try r.draw(between, .identity, pose.opacity); + shapes += between.shapes.len; + continue; + } + try reveal(r, d, m, pose, fit(canvas)); + shapes += d.shapes.len; + } + if (options.guides) { + const r = open orelse try begun(layers, &used, f, canvas, .{ 0, 0, 0, 0 }); + open = r; + try r.draw(try p.guides(f.scratch, shot, svgs, world, canvas), .identity, 1); + } + if (open) |r| r.present(f, canvas); + p.shapes = shapes; + if (options.guides) try p.labels(f, shot, svgs, world); +} + +fn model(p: anim.Pose) geom.Affine { + return geom.Affine.translate(p.x, p.y).mul(.rotate(p.rotation)).mul(.scale(p.scale, p.scale)); +} + +/// manim's reveals, shape by shape with a stagger: Write traces each outline +/// then fills it; Create draws strokes along their length, then fills. +/// Outlines are `k` canvas pixels to the scene unit wide. +fn reveal(r: anytype, d: vector.Drawing, m: geom.Affine, pose: anim.Pose, k: f32) !void { + const n: f32 = @floatFromInt(d.shapes.len); + const lag: f32 = if (pose.drawn >= 1) 0 else 0.08; + const window = 1 / (1 + lag * @max(n - 1, 0)); + const glow = pose.highlight; + for (d.shapes, 0..) |shape, i| { + const local = std.math.clamp((pose.drawn - @as(f32, @floatFromInt(i)) * lag * window) / window, 0, 1); + if (local <= 0) continue; + var o: vector.Options = .{ .alpha = pose.opacity }; + switch (pose.reveal) { + .write => if (local < 1) { + o.trim = @min(local * 2, 1); + o.outline = .{ .width = 1.5 * k, .alpha = 1 - std.math.clamp(local * 2 - 1, 0, 1) }; + o.stroke = false; + // Fill arrives in the second half. + var fill = o; + fill.outline = null; + fill.alpha = pose.opacity * std.math.clamp(local * 2 - 1, 0, 1); + try r.drawShape(d, shape, m, fill); + o.fill = false; + }, + .create => if (local < 1) { + o.trim = local; + if (shape.style.stroke == .none) o.outline = .{ .width = 2 * k }; + var fill = o; + fill.stroke = false; + fill.outline = null; + fill.alpha = pose.opacity * std.math.clamp(local * 3 - 2, 0, 1); + try r.drawShape(d, shape, m, fill); + o.fill = false; + }, + } + try r.drawShape(d, shape, m, o); + if (glow > 0) { + // Indicate: a yellow glow over the shape. + var hot = shape; + hot.style.fill = if (shape.style.fill != .none) .{ .color = anim.color(anim.yellow) } else .none; + hot.style.stroke = if (shape.style.stroke != .none) .{ .color = anim.color(anim.yellow) } else .none; + try r.drawShape(d, hot, m, .{ .alpha = pose.opacity * glow }); + } + } +} + +/// Spacing of the guides' ticks, in scene units. +const tick = 100; + +fn guideStyle(c: u32, w: f32) vector.Drawing.Style { + return .{ .fill = .none, .stroke = .{ .color = anim.color(c) }, .stroke_width = w }; +} + +/// The scene's axes with ticks, and each visible object's bounding box (a +/// custom object has none) and origin, in canvas pixels. +fn guides(p: *Painter, arena: std.mem.Allocator, shot: anim.Shot, svgs: anytype, world: geom.Affine, canvas: sk.Rect) !vector.Drawing { + var b: vector.Drawing.Builder = .init(arena); + const far = 100 * tick; + try b.lineTo(world.apply(.{ -far, 0 }), world.apply(.{ far, 0 })); + try b.closeSubpath(false); + try b.endShape(.identity, guideStyle(anim.red, 1.5)); + try b.lineTo(world.apply(.{ 0, -far }), world.apply(.{ 0, far })); + try b.closeSubpath(false); + try b.endShape(.identity, guideStyle(anim.green, 1.5)); + var i: f32 = -20; + while (i <= 20) : (i += 1) { + const x = world.apply(.{ i * tick, 0 }); + const y = world.apply(.{ 0, i * tick }); + try b.lineTo(x - geom.Vec{ 0, 5 }, x + geom.Vec{ 0, 5 }); + try b.closeSubpath(false); + try b.lineTo(y - geom.Vec{ 5, 0 }, y + geom.Vec{ 5, 0 }); + try b.closeSubpath(false); + } + try b.endShape(.identity, guideStyle(0x8c8c8c, 1)); + + for (shot.objects, shot.poses) |o, pose| { + if (!pose.visible or pose.opacity <= 0) continue; + const m = world.mul(model(pose)); + if (o.source != .custom) { + const r = (try p.built(o, svgs)).bounds; + try b.polyline(&.{ m.apply(.{ r.x, r.y }), m.apply(.{ r.x + r.w, r.y }), m.apply(.{ r.x + r.w, r.y + r.h }), m.apply(.{ r.x, r.y + r.h }) }, true); + } + // The object's origin: where its pose puts it. + const c = m.apply(.{ 0, 0 }); + try b.lineTo(c - geom.Vec{ 6, 0 }, c + geom.Vec{ 6, 0 }); + try b.closeSubpath(false); + try b.lineTo(c - geom.Vec{ 0, 6 }, c + geom.Vec{ 0, 6 }); + try b.closeSubpath(false); + } + try b.endShape(.identity, guideStyle(anim.yellow, 1)); + return b.finish(.{ .w = canvas.w, .h = canvas.h }, canvas.w, canvas.h); +} + +/// The guides' numbers: tick values, and each object's index and position. +fn labels(p: *Painter, f: *sk.Frame, shot: anim.Shot, svgs: anytype, world: geom.Affine) !void { + var i: f32 = -20; + while (i <= 20) : (i += 2) { + const x = world.apply(.{ i * tick, 0 }); + const y = world.apply(.{ 0, i * tick }); + f.print(x[0] + 3, x[1] + 8, 1, 0x8c8c8c, "{d}", .{i * tick}); + if (i != 0) f.print(y[0] + 8, y[1] - 3, 1, 0x8c8c8c, "{d}", .{i * tick}); + } + for (shot.objects, shot.poses, 0..) |o, pose, n| { + if (!pose.visible or pose.opacity <= 0) continue; + const r: geom.Rect = if (o.source == .custom) .{} else (try p.built(o, svgs)).bounds; + const corner = world.mul(model(pose)).apply(.{ r.x, r.y }); + f.print(corner[0], corner[1] - 11, 1, anim.yellow, "#{d} {d:.0},{d:.0}", .{ n, pose.x, pose.y }); + } +} diff --git a/src/anim/player.zig b/src/anim/player.zig index 090b6cb..b329714 100644 --- a/src/anim/player.zig +++ b/src/anim/player.zig @@ -1,20 +1,26 @@ //! The `anim` module's player: plays the scene file it is built around //! (`sb.addScene`), compiled or live, as a manim-style animation drawn by -//! the vector library on the GPU (or the CPU, with B). Time is state; -//! everything else is a function of it (and, for a live scene, of the -//! input). +//! the vector library on the GPU (or the CPU, with B). Its state is an +//! `anim.Deck`, the playhead and the gates opened, and the viewer's own +//! settings; the picture is a function of them (and, for a live scene, of +//! the input). A scene that pauses is a talk, and steps: //! -//! space pause / play left/right previous / next play -//! click continue after a pause (`s.pause()` in the scene) +//! click, space, page down next step: open the pause the talk waits at, +//! or finish the step under way (in a scene with +//! no pause, space plays or pauses) +//! page up, backspace back a step: the picture before the last click +//! ] / [ next / previous slide (`s.slide()`), at rest +//! P play / pause left/right previous / next play //! ,/. step back / ahead home/end start / end //! up/down speed B GPU or CPU renderer -//! G guides: boxes, origins and axes, in scene units +//! L loop (not a talk) G guides: boxes, origins, axes //! drag, wheel: look around R reset the view //! //! The scene's frame, 1280x720 scene units around its origin, is fitted //! into the canvas, and the canvas is the room the host has: the window, or //! an export's `--size`. Exported (`in.exporting`), the scene plays through -//! once, without pauses or controls, and the player quits. +//! once without controls, each pause held for the scene file's `hold` +//! seconds (1 without one), and the player quits at the end. const std = @import("std"); const sk = @import("sketch"); const vector = @import("vector"); @@ -23,71 +29,67 @@ const scene_file = @import("scene"); const scene = scene_file.scene; /// The scene's Typst sources, compiled at build time. const typst = @import("typst"); -const geom = vector.geom; pub const name = if (@hasDecl(scene_file, "name")) scene_file.name else "anim"; /// The page: the scene file's `background` (0xRRGGBB), or manim's. const background: u32 = if (@hasDecl(scene_file, "background")) scene_file.background else anim.background; +/// Exported, how long each pause holds. +const hold: f32 = if (@hasDecl(scene_file, "hold")) scene_file.hold else 1; /// The scene's frame, in scene units: what shows at camera zoom 1. -pub const width = 1280; -pub const height = 720; +pub const width = anim.width; +pub const height = anim.height; pub const State = struct { - t: f32 = 0, - playing: bool = true, - speed: f32 = 1, + deck: anim.Deck = .{ .hold = hold }, looping: bool = true, backend: vector.Backend = .gpu, /// The viewer's own pan and zoom, on top of the scene's camera. view: sk.Camera = .{}, dragging: bool = false, - /// Where the left button went down: a click, not a drag, continues. + /// Where the left button went down: a click, not a drag, steps. press: [2]f32 = .{ 0, 0 }, guides: bool = false, }; pub const Session = struct { - /// A renderer per run of vector objects between custom ones (`paint`). - gpu: std.ArrayList(vector.Renderer(.gpu)) = .empty, - cpu: std.ArrayList(vector.Renderer(.cpu)) = .empty, - /// Drawings by what they look like (`Object.id`), built on first use and - /// dropped on reload, since the code that builds them may have changed. - /// Their memory is the host's, kept across reloads. - arena: ?std.heap.ArenaAllocator = null, - drawings: std.AutoHashMapUnmanaged(u64, Built) = .empty, - /// Smoothed time to record a frame, and its shape count. + painter: anim.Painter = .{}, + /// Smoothed time to record a frame. render_ns: f32 = 0, - shapes: usize = 0, }; -const Built = struct { drawing: vector.Drawing, bounds: geom.Rect }; +/// A live scene's frame, or a compiled scene as a talk without gates. +const talk = if (@hasDecl(scene, "frame")) scene.frame else struct { + fn frame(s: *anim.Frame) void { + s.cursor = scene.duration; + } +}.frame; pub fn update(s: *State, in: *const sk.Input) void { - // The timeline as it stands: a live scene builds it as it runs. - var arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator); - defer arena.deinit(); - const shot = scene.shot(arena.allocator(), .{ .t = s.t }) catch return; + const d = &s.deck; + // A scene that waits somewhere is a talk: clicks and space step it. + const talking = d.gates > 0; + var ask: anim.Ask = .{}; + var mark: enum { none, previous, next } = .none; for (in.events) |e| switch (e.kind) { - // Exported: nobody clicks, so straight through, once. - .tick => if (in.exporting) { - s.t += e.x; - } else if (s.playing and !held(s.t, shot)) { - const next = s.t + e.x * s.speed; - s.t = stopBetween(s.t, next, shot) orelse next; - if (s.t > shot.duration + 1) s.t = if (s.looping) 0 else shot.duration; - }, - .key_down => if (e.flags & sk.Event.repeat == 0 or key(e) == .left or key(e) == .right or key(e) == .comma or key(e) == .period) switch (key(e)) { - .space => if (s.playing and held(s.t, shot)) proceed(s) else { - s.playing = !s.playing; + .key_down => if (e.flags & sk.Event.repeat == 0 or e.key() == .left or e.key() == .right or e.key() == .comma or e.key() == .period) switch (e.key()) { + .space => if (talking) { + ask.next = true; + } else { + d.playing = !d.playing; }, - .home => s.t = 0, - .end => s.t = shot.duration, - .left => s.t = previousMark(s.t, shot), - .right => s.t = nextMark(s.t, shot), - .comma => s.t = @max(s.t - 1.0 / 30.0, 0), - .period => s.t = @min(s.t + 1.0 / 30.0, shot.duration), - .up => s.speed = @min(s.speed * 2, 8), - .down => s.speed = @max(s.speed / 2, 0.125), + .page_down => ask.next = true, + .page_up, .backspace => ask.back = true, + .right_bracket => ask.next_slide = true, + .left_bracket => ask.back_slide = true, + .p => d.playing = !d.playing, + .home => ask.to = 0, + .end => ask.end = true, + .left => mark = .previous, + .right => mark = .next, + .comma => ask.to = @max((ask.to orelse d.t) - 1.0 / 30.0, 0), + .period => ask.to = @min((ask.to orelse d.t) + 1.0 / 30.0, d.duration), + .up => d.speed = @min(d.speed * 2, 8), + .down => d.speed = @max(d.speed / 2, 0.125), .b => s.backend = if (s.backend == .gpu) .cpu else .gpu, .g => s.guides = !s.guides, .l => s.looping = !s.looping, @@ -100,7 +102,7 @@ pub fn update(s: *State, in: *const sk.Input) void { }, .mouse_up => { const click = @abs(e.x - s.press[0]) + @abs(e.y - s.press[1]) < 4; - if (s.dragging and click and held(s.t, shot)) proceed(s); + if (s.dragging and click and talking) ask.next = true; s.dragging = false; }, .cancel => s.dragging = false, @@ -108,28 +110,26 @@ pub fn update(s: *State, in: *const sk.Input) void { .wheel => s.view.zoomAt(e, e.wheel(), .{ .min = 0.2, .max = 20 }), else => {}, }; + if (mark != .none) { + // The plays as the scene lays them now. + var arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator); + defer arena.deinit(); + if (shotNow(s, arena.allocator(), in, .{ 0, 0 })) |shot| { + ask.to = if (mark == .previous) previousMark(d.t, shot) else nextMark(d.t, shot); + } else |_| {} + } + // Played past the end: from the start again, or held there (a talk + // holds its last picture). + if (!in.exporting and d.t > d.duration + 1) { + if (s.looping and !talking) ask.to = 0 else d.t = d.duration; + } + d.update(in, ask, talk, .{}); } -fn key(e: sk.Event) sk.Key { - return @fromBackingInt(@intCast(@as(u8, @truncate(e.code)))); -} - -/// Waiting at a pause for a click. -fn held(t: f32, shot: anim.Shot) bool { - for (shot.stops) |stop| if (stop == t) return true; - return false; -} - -/// The first pause in `(from, to]`. -fn stopBetween(from: f32, to: f32, shot: anim.Shot) ?f32 { - for (shot.stops) |stop| if (stop > from and stop <= to) return stop; - return null; -} - -/// Past the pause the player waits at. -fn proceed(s: *State) void { - s.t += 1e-3; - s.playing = true; +/// The scene at the deck's `t`: a live one through the deck, with its gates. +fn shotNow(s: *const State, arena: std.mem.Allocator, in: *const sk.Input, mouse: [2]f32) !anim.Shot { + if (@hasDecl(scene, "frame")) return s.deck.shot(arena, in, mouse, scene.frame, .{}); + return scene.shot(arena, .{ .t = s.deck.t, .in = in, .pointer = mouse }); } fn previousMark(t: f32, shot: anim.Shot) f32 { @@ -145,33 +145,22 @@ fn nextMark(t: f32, shot: anim.Shot) f32 { return shot.duration; } -/// Canvas pixels per scene unit: the scene's frame, fitted into `canvas`. -fn fit(canvas: sk.Rect) f32 { - return @min(canvas.w / width, canvas.h / height); -} - /// The mouse in scene units from the canvas center, before the scene's /// camera: the viewer's pan and zoom undone. fn pointer(s: *const State, in: *const sk.Input, canvas: sk.Rect) [2]f32 { - const k = fit(canvas); + const k = anim.Painter.fit(canvas); return .{ ((in.mouse_x - s.view.x) / s.view.zoom - canvas.w / 2) / k, ((in.mouse_y - s.view.y) / s.view.zoom - canvas.h / 2) / k }; } pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void { // All the room there is: the window, or the size an export asks for. const canvas: sk.Rect = .{ .w = @max(@floor(f.in.window_width), 1), .h = @max(@floor(f.in.window_height), 1) }; - f.canvas(@intFromFloat(canvas.w), @intFromFloat(canvas.h)); const started = f.host.clock(); - const shot = scene.shot(f.scratch, .{ - .t = s.t, - .clock = @floatCast(@mod(@as(f64, @floatFromInt(f.in.now)) / std.time.ns_per_s, 3600)), - .in = f.in, - .pointer = pointer(s, f.in, canvas), - }) catch |err| return f.host.print("scene: {t}", .{err}); - render(s, ss, f, shot, canvas) catch |err| f.host.print("render: {t}", .{err}); + const shot = shotNow(s, f.scratch, f.in, pointer(s, f.in, canvas)) catch |err| return f.host.print("scene: {t}", .{err}); + ss.painter.paint(f, shot, typst, .{ .view = s.view, .backend = s.backend, .guides = s.guides, .background = background }) catch |err| f.host.print("render: {t}", .{err}); if (f.in.exporting) { // The frame that shows the end is the last. - if (s.t >= shot.duration) f.quit(); + if (s.deck.t >= shot.duration) f.quit(); return; } const elapsed: f32 = @floatFromInt(f.host.clock() -| started); @@ -179,234 +168,31 @@ pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void { hud(s, ss, f, shot, canvas); } -fn render(s: *const State, ss: *Session, f: *sk.Frame, shot: anim.Shot, canvas: sk.Rect) !void { - if (ss.arena == null) ss.arena = .init(f.session); - // A live scene may make new drawings every frame: start over now and then. - if (f.in.reloaded or ss.drawings.count() > 1024) { - _ = ss.arena.?.reset(.retain_capacity); - ss.drawings = .empty; - } - // Use the host's GPU when it has one. - if (s.backend == .gpu and f.host.gpu()) try paint(s, ss, &ss.gpu, f, shot, canvas) else try paint(s, ss, &ss.cpu, f, shot, canvas); -} - -/// Object `o`'s drawing, centered on its origin, and its bounds. -fn built(ss: *Session, o: anim.Object) !Built { - const id = o.id(); - if (ss.drawings.get(id)) |b| return b; - const arena = ss.arena.?.allocator(); - const d = try anim.build(arena, o, typst); - const b: Built = .{ .drawing = d, .bounds = d.bounds().rect() }; - try ss.drawings.put(arena, id, b); - return b; -} - -/// Scene units to canvas pixels: the scene's camera, then the viewer's. -/// The scene's origin is the canvas center. -fn stage(s: *const State, cam: anim.Camera, canvas: sk.Rect) geom.Affine { - const k = fit(canvas) * cam.zoom; - return geom.Affine.translate(s.view.x, s.view.y) - .mul(.scale(s.view.zoom, s.view.zoom)) - .mul(.translate(canvas.w / 2, canvas.h / 2)) - .mul(.scale(k, k)) - .mul(.rotate(-cam.rotation)) - .mul(.translate(-cam.x, -cam.y)); -} - -/// The next of `layers`, begun: a renderer the size of the canvas. -fn begun(layers: anytype, used: *usize, f: *sk.Frame, canvas: sk.Rect, clear: vector.Drawing.Color) !*@TypeOf(layers.items[0]) { - if (used.* == layers.items.len) try layers.append(f.session, try .init(f.session, f.host, @intFromFloat(canvas.w), @intFromFloat(canvas.h))); - const r = &layers.items[used.*]; - used.* += 1; - r.begin(f, clear); - return r; -} - -/// Draws `shot` with the renderers in `layers` (either backend), objects -/// in the order they were added. Vector objects go into a renderer's image, -/// which is then drawn on the canvas; a custom object draws on the canvas -/// itself. So the vector objects before a custom one and those after it -/// are separate images, one renderer each: every GPU pass of a frame runs -/// before its first 2D command, and one image could only show the last. -fn paint(s: *const State, ss: *Session, layers: anytype, f: *sk.Frame, shot: anim.Shot, canvas: sk.Rect) !void { - if (layers.items.len > 0 and (layers.items[0].width() != @as(u32, @intFromFloat(canvas.w)) or layers.items[0].height() != @as(u32, @intFromFloat(canvas.h)))) { - for (layers.items) |*r| r.deinit(f.host); - layers.clearRetainingCapacity(); - } - const world = stage(s, shot.camera, canvas); - var used: usize = 0; - // The first layer is the background too. - var open: ?*@TypeOf(layers.items[0]) = try begun(layers, &used, f, canvas, anim.color(background)); - var shapes: usize = 0; - for (shot.objects, shot.poses, 0..) |o, pose, i| { - if (!pose.visible or pose.opacity <= 0) continue; - const m = world.mul(model(pose)); - if (o.source == .custom) { - if (open) |r| r.present(f, canvas); - open = null; - o.source.custom.draw(o.source.custom.ctx, f, .{ .t = s.t, .pose = pose, .xf = m, .scale = m.scaleFactor(), .stage = world, .values = shot.values }); - // It leaves no target, clip or blend behind. - f.target(.none); - f.blend(.alpha); - continue; - } - const r = open orelse try begun(layers, &used, f, canvas, .{ 0, 0, 0, 0 }); - open = r; - const d = (try built(ss, o)).drawing; - if (pose.into != anim.Pose.none and pose.morph > 0 and pose.morph < 1 and shot.objects[pose.into].source != .custom) { - // Morphing: from where this object began the transform to where - // its target will stand. - const morph = shot.morphs[i]; - const target = (try built(ss, shot.objects[pose.into])).drawing; - const between = try vector.morph.between(f.scratch, d, world.mul(model(morph.from)), target, world.mul(model(morph.to)), pose.morph); - try r.draw(between, .identity, pose.opacity); - shapes += between.shapes.len; - continue; - } - try reveal(r, d, m, pose, fit(canvas)); - shapes += d.shapes.len; - } - if (s.guides) { - const r = open orelse try begun(layers, &used, f, canvas, .{ 0, 0, 0, 0 }); - open = r; - try r.draw(try guides(ss, f.scratch, shot, world, canvas), .identity, 1); - } - if (open) |r| r.present(f, canvas); - ss.shapes = shapes; - if (s.guides) try labels(ss, f, shot, world); -} - -fn model(p: anim.Pose) geom.Affine { - return geom.Affine.translate(p.x, p.y).mul(.rotate(p.rotation)).mul(.scale(p.scale, p.scale)); -} - -/// manim's reveals, shape by shape with a stagger: Write traces each outline -/// then fills it; Create draws strokes along their length, then fills. -/// Outlines are `k` canvas pixels to the scene unit wide. -fn reveal(r: anytype, d: vector.Drawing, m: geom.Affine, pose: anim.Pose, k: f32) !void { - const n: f32 = @floatFromInt(d.shapes.len); - const lag: f32 = if (pose.drawn >= 1) 0 else 0.08; - const window = 1 / (1 + lag * @max(n - 1, 0)); - const glow = pose.highlight; - for (d.shapes, 0..) |shape, i| { - const local = std.math.clamp((pose.drawn - @as(f32, @floatFromInt(i)) * lag * window) / window, 0, 1); - if (local <= 0) continue; - var o: vector.Options = .{ .alpha = pose.opacity }; - switch (pose.reveal) { - .write => if (local < 1) { - o.trim = @min(local * 2, 1); - o.outline = .{ .width = 1.5 * k, .alpha = 1 - std.math.clamp(local * 2 - 1, 0, 1) }; - o.stroke = false; - // Fill arrives in the second half. - var fill = o; - fill.outline = null; - fill.alpha = pose.opacity * std.math.clamp(local * 2 - 1, 0, 1); - try r.drawShape(d, shape, m, fill); - o.fill = false; - }, - .create => if (local < 1) { - o.trim = local; - if (shape.style.stroke == .none) o.outline = .{ .width = 2 * k }; - var fill = o; - fill.stroke = false; - fill.outline = null; - fill.alpha = pose.opacity * std.math.clamp(local * 3 - 2, 0, 1); - try r.drawShape(d, shape, m, fill); - o.fill = false; - }, - } - try r.drawShape(d, shape, m, o); - if (glow > 0) { - // Indicate: a yellow glow over the shape. - var hot = shape; - hot.style.fill = if (shape.style.fill != .none) .{ .color = anim.color(anim.yellow) } else .none; - hot.style.stroke = if (shape.style.stroke != .none) .{ .color = anim.color(anim.yellow) } else .none; - try r.drawShape(d, hot, m, .{ .alpha = pose.opacity * glow }); - } - } -} - -/// Spacing of the guides' ticks, in scene units. -const tick = 100; - -fn guideStyle(c: u32, w: f32) vector.Drawing.Style { - return .{ .fill = .none, .stroke = .{ .color = anim.color(c) }, .stroke_width = w }; -} - -/// The scene's axes with ticks, and each visible object's bounding box (a -/// custom object has none) and origin, in canvas pixels. -fn guides(ss: *Session, arena: std.mem.Allocator, shot: anim.Shot, world: geom.Affine, canvas: sk.Rect) !vector.Drawing { - var b: vector.Drawing.Builder = .init(arena); - const far = 100 * tick; - try b.lineTo(world.apply(.{ -far, 0 }), world.apply(.{ far, 0 })); - try b.closeSubpath(false); - try b.endShape(.identity, guideStyle(anim.red, 1.5)); - try b.lineTo(world.apply(.{ 0, -far }), world.apply(.{ 0, far })); - try b.closeSubpath(false); - try b.endShape(.identity, guideStyle(anim.green, 1.5)); - var i: f32 = -20; - while (i <= 20) : (i += 1) { - const x = world.apply(.{ i * tick, 0 }); - const y = world.apply(.{ 0, i * tick }); - try b.lineTo(x - geom.Vec{ 0, 5 }, x + geom.Vec{ 0, 5 }); - try b.closeSubpath(false); - try b.lineTo(y - geom.Vec{ 5, 0 }, y + geom.Vec{ 5, 0 }); - try b.closeSubpath(false); - } - try b.endShape(.identity, guideStyle(0x8c8c8c, 1)); - - for (shot.objects, shot.poses) |o, pose| { - if (!pose.visible or pose.opacity <= 0) continue; - const m = world.mul(model(pose)); - if (o.source != .custom) { - const r = (try built(ss, o)).bounds; - try b.polyline(&.{ m.apply(.{ r.x, r.y }), m.apply(.{ r.x + r.w, r.y }), m.apply(.{ r.x + r.w, r.y + r.h }), m.apply(.{ r.x, r.y + r.h }) }, true); - } - // The object's origin: where its pose puts it. - const c = m.apply(.{ 0, 0 }); - try b.lineTo(c - geom.Vec{ 6, 0 }, c + geom.Vec{ 6, 0 }); - try b.closeSubpath(false); - try b.lineTo(c - geom.Vec{ 0, 6 }, c + geom.Vec{ 0, 6 }); - try b.closeSubpath(false); - } - try b.endShape(.identity, guideStyle(anim.yellow, 1)); - return b.finish(.{ .w = canvas.w, .h = canvas.h }, canvas.w, canvas.h); -} - -/// The guides' numbers: tick values, and each object's index and position. -fn labels(ss: *Session, f: *sk.Frame, shot: anim.Shot, world: geom.Affine) !void { - var i: f32 = -20; - while (i <= 20) : (i += 2) { - const x = world.apply(.{ i * tick, 0 }); - const y = world.apply(.{ 0, i * tick }); - f.print(x[0] + 3, x[1] + 8, 1, 0x8c8c8c, "{d}", .{i * tick}); - if (i != 0) f.print(y[0] + 8, y[1] - 3, 1, 0x8c8c8c, "{d}", .{i * tick}); - } - for (shot.objects, shot.poses, 0..) |o, pose, n| { - if (!pose.visible or pose.opacity <= 0) continue; - const r: geom.Rect = if (o.source == .custom) .{} else (try built(ss, o)).bounds; - const corner = world.mul(model(pose)).apply(.{ r.x, r.y }); - f.print(corner[0], corner[1] - 11, 1, anim.yellow, "#{d} {d:.0},{d:.0}", .{ n, pose.x, pose.y }); - } -} - fn hud(s: *const State, ss: *const Session, f: *sk.Frame, shot: anim.Shot, canvas: sk.Rect) void { const w = canvas.w; const h = canvas.h; + const d = &s.deck; var play: usize = 0; - for (shot.marks, 1..) |m, i| if (m <= s.t) { + for (shot.marks, 1..) |m, i| if (m <= d.t) { play = i; }; + var buf: [64]u8 = undefined; + const steps = (if (d.slides > 0) + std.fmt.bufPrint(&buf, " slide {d}/{d} step {d}/{d}", .{ d.slide, d.slides, d.log.count(), d.gates }) + else if (d.gates > 0) + std.fmt.bufPrint(&buf, " step {d}/{d}", .{ d.log.count(), d.gates }) + else + std.fmt.bufPrint(&buf, "", .{})) catch ""; const backend = if (s.backend == .gpu and f.host.gpu()) "GPU" else "CPU"; - const status = if (!s.playing) " paused" else if (held(s.t, shot)) " click to continue" else ""; + const status = if (!d.playing) " paused" else if (d.waiting) " click to continue" else ""; f.fill(sk.Rect{ .y = h - 28, .w = w, .h = 28 }, sk.Color{ .r = 0, .g = 0, .b = 0, .a = 150 }); - f.print(12, h - 19, 1, 0xece6e2, "{d:5.2}s / {d:.2}s play {d}/{d} {s} record {d:.3}ms {d} shapes speed x{d}{s}", .{ - s.t, shot.duration, play, shot.marks.len, backend, ss.render_ns / 1e6, ss.shapes, s.speed, status, + f.print(12, h - 19, 1, 0xece6e2, "{d:5.2}s / {d:.2}s play {d}/{d}{s} {s} record {d:.3}ms {d} shapes speed x{d}{s}", .{ + d.t, shot.duration, play, shot.marks.len, steps, backend, ss.render_ns / 1e6, ss.painter.shapes, d.speed, status, }); if (s.guides) { const p = pointer(s, f.in, canvas); f.print(w - 540, h - 19, 1, anim.yellow, "pointer {d:.0},{d:.0}", .{ p[0], p[1] }); } - f.text(w - 400, h - 19, 1, "space click <- -> , . B G drag wheel", 0x8c8c8c); + f.text(w - 400, h - 19, 1, "click space pgup [ ] P <- -> , . B G drag", 0x8c8c8c); f.cursor(.arrow); } diff --git a/src/anim/root.zig b/src/anim/root.zig index a676f38..03abf11 100644 --- a/src/anim/root.zig +++ b/src/anim/root.zig @@ -44,13 +44,21 @@ //! Both are functions of time (and a live one, of the input too), so //! scrubbing, seeking and hot reload are free. //! +//! **Talks** are live scenes with gates: `pause` waits for the presenter's +//! click, `gate` for any condition, and time runs on while they wait, so +//! loops (`loop`) and plays already running carry on. A talk is a function +//! of its time and of the gates opened so far, both plain data in a `Deck`, +//! which the stock player keeps and any sketch can keep in its own State. +//! //! Animations, as methods of an object handle: `write`, `create`, //! `fadeIn`, `fadeOut`, `transformInto` (morph), `move`, `scaleTo`, //! `rotate`, `indicate`; and `camera`, `Value.to`. `play` runs a tuple of //! them together, with options `.seconds`, `.ease` (any `fn (f32) f32`, -//! `ease.smooth` by default) and `.lag`. `wait` moves time on; `pause` -//! holds the player there until a click, like a slide. Typst is compiled -//! at build time (`sb.addScene`), from the scene's `typst_sources`. +//! `ease.smooth` by default) and `.lag` (manim's lag ratio, 0 by +//! default). `wait` moves time on; `pause` +//! makes what follows wait for a click, like a slide step. Typst is +//! compiled at build time (`sb.addScene`), from the scene's +//! `typst_sources`. //! //! **Custom objects** (`s.custom(&data, .{ .x = 100 })`) are drawn by the //! scene's own code, with `sketch.Frame` commands, in their place among @@ -62,6 +70,7 @@ const tween = sk.tween; const Drawing = vector.Drawing; pub const ease = tween.ease; +pub const Painter = @import("Painter.zig"); // manim's palette. pub const blue: u32 = 0x58c4dd; @@ -110,7 +119,6 @@ pub fn Key(comptime P: type) type { start: f32, end: f32, ease: Ease, - lag: f32 = 0, from: P, to: P, @@ -133,6 +141,9 @@ pub const Source = union(enum) { polygon: []const [2]f32, /// Drawn by the scene's own code (`custom`). custom: Custom, + /// The shapes of `of` whose bounds' centre lies in `area` (in `of`'s + /// units), around the area's centre (`part`). + part: struct { of: *const Object, area: vector.geom.Rect }, }; /// An object the scene draws itself with 2D commands (`f.fill`, `sk.draw`, @@ -217,6 +228,8 @@ pub const Object = struct { fill: ?u32 = null, stroke: ?u32 = null, width: f32 = 4, + /// Areas whose shapes parts were taken from it: it draws the rest. + cut: []const vector.geom.Rect = &.{}, /// Identifies what the object looks like (not where it is), to cache /// its drawing by. @@ -230,11 +243,25 @@ pub const Object = struct { .circle => |c| h.update(std.mem.asBytes(&c.r)), .line => |l| h.update(std.mem.asBytes(&[_]f32{ l.dx, l.dy, @floatFromInt(@intFromBool(l.arrow)) })), .custom => |c| h.update(std.mem.asBytes(&[_]usize{ @intFromPtr(c.draw), @intFromPtr(c.ctx) })), + .part => |p| { + h.update(std.mem.asBytes(&p.of.id())); + h.update(std.mem.asBytes(&p.area)); + }, } h.update(std.mem.asBytes(&[_]u64{ o.fill orelse 1 << 32, o.stroke orelse 1 << 32 })); h.update(std.mem.asBytes(&o.width)); + h.update(std.mem.sliceAsBytes(o.cut)); return h.final(); } + + /// What a part or a cut object is drawn from (`sift`): the object + /// without its cut, or the one a part was taken from. + pub fn whole(o: Object) Object { + if (o.cut.len == 0) return o.source.part.of.*; + var w = o; + w.cut = &.{}; + return w; + } }; /// Pose fields to animate towards; the others stay as they are. @@ -360,7 +387,7 @@ const Play = struct { animations: []const Animation, /// `play`'s options: `.seconds` (1, or 2 with a write in it), `.ease` - /// (`ease.smooth`) and `.lag` (0.08). + /// (`ease.smooth`) and `.lag` (0: all start together). fn of(start: f32, animations: []const Animation, options: anytype) Play { const O = @TypeOf(options); var seconds: f32 = 1; @@ -372,13 +399,18 @@ const Play = struct { .start = start, .seconds = seconds, .ease = if (@hasField(O, "ease")) options.ease else ease.smooth, - .lag = if (@hasField(O, "lag")) options.lag else 0.08, + .lag = if (@hasField(O, "lag")) options.lag else 0, .animations = animations, }; } - fn key(p: Play, comptime P: type, from: P, to: P, with: ?Ease) Key(P) { - return .{ .start = p.start, .end = p.start + p.seconds, .ease = with orelse p.ease, .lag = p.lag, .from = from, .to = to }; + /// Animation `i`'s key. With a lag, manim's lag ratio: each animation + /// starts `lag` of its length after the one before, and all are as long + /// as lets the last end with the play. + fn key(p: Play, comptime P: type, i: usize, from: P, to: P, with: ?Ease) Key(P) { + const each = p.seconds / (1 + p.lag * @as(f32, @floatFromInt(@max(p.animations.len, 1) - 1))); + const start = p.start + @as(f32, @floatFromInt(i)) * p.lag * each; + return .{ .start = start, .end = start + each, .ease = with orelse p.ease, .from = from, .to = to }; } }; @@ -396,16 +428,17 @@ fn count(comptime T: type) usize { }; } -/// What a play does to one object: the pose it starts from and ends on. -const Change = struct { obj: u16, from: Pose, to: Pose, ease: ?Ease = null }; +/// What a play does to one object: the pose it starts from and ends on, +/// timed as its first animation in the play (`at`). +const Change = struct { obj: u16, at: usize, from: Pose, to: Pose, ease: ?Ease = null }; /// The changes `animations`, played together, make to objects standing in /// their `settled` poses. `buf` needs two per animation. fn changes(buf: []Change, settled: []const Pose, animations: []const Animation) []Change { var n: usize = 0; - for (animations) |a| switch (a) { + for (animations, 0..) |a, at| switch (a) { .write, .create => |o| { - const c = touch(buf, &n, settled, o); + const c = touch(buf, &n, at, settled, o); c.from.visible = true; c.from.drawn = 0; if (c.from.opacity <= 0) c.from.opacity = 1; @@ -414,7 +447,7 @@ fn changes(buf: []Change, settled: []const Pose, animations: []const Animation) c.to.drawn = 1; }, .fade_in => |o| { - const c = touch(buf, &n, settled, o); + const c = touch(buf, &n, at, settled, o); c.from.visible = true; c.from.drawn = 1; c.from.opacity = 0; @@ -422,28 +455,28 @@ fn changes(buf: []Change, settled: []const Pose, animations: []const Animation) c.to.opacity = 1; }, .fade_out => |o| { - const c = touch(buf, &n, settled, o); + const c = touch(buf, &n, at, settled, o); c.to.opacity = 0; c.to.visible = false; }, .transform => |t| { - const c = touch(buf, &n, settled, t.from); + const c = touch(buf, &n, at, settled, t.from); c.from.into = @backingInt(t.to); c.from.morph = 0; c.to = c.from; c.to.morph = 1; c.to.visible = false; - const d = touch(buf, &n, settled, t.to); + const d = touch(buf, &n, at, settled, t.to); d.from.visible = false; d.to = d.from; d.to.visible = true; d.to.drawn = 1; d.to.opacity = 1; }, - .move => |m| m.to.apply(&touch(buf, &n, settled, m.obj).to), - .rotate => |r| touch(buf, &n, settled, r.obj).to.rotation += r.by, + .move => |m| m.to.apply(&touch(buf, &n, at, settled, m.obj).to), + .rotate => |r| touch(buf, &n, at, settled, r.obj).to.rotation += r.by, .indicate => |o| { - const c = touch(buf, &n, settled, o); + const c = touch(buf, &n, at, settled, o); c.to.scale *= 1.2; c.to.highlight = 1; c.ease = ease.thereAndBack; @@ -453,25 +486,28 @@ fn changes(buf: []Change, settled: []const Pose, animations: []const Animation) return buf[0..n]; } -fn touch(buf: []Change, n: *usize, settled: []const Pose, o: Obj) *Change { +fn touch(buf: []Change, n: *usize, at: usize, settled: []const Pose, o: Obj) *Change { const i = @backingInt(o); for (buf[0..n.*]) |*c| if (c.obj == i) return c; - buf[n.*] = .{ .obj = i, .from = settled[i], .to = settled[i] }; + buf[n.*] = .{ .obj = i, .at = at, .from = settled[i], .to = settled[i] }; n.* += 1; return &buf[n.* - 1]; } -/// Where `animations` leave a camera standing at `view`, if they move it. -fn aim(view: Camera, animations: []const Animation) ?Camera { +/// Where `animations` leave a camera standing at `view`, if they move it, +/// and the first of them that does (`Change.at`). +fn aim(view: Camera, animations: []const Animation) ?struct { to: Camera, at: usize } { var out: ?Camera = null; - for (animations) |a| if (a == .camera) { + var first: usize = 0; + for (animations, 0..) |a, i| if (a == .camera) { + if (out == null) first = i; var c = out orelse view; inline for (@typeInfo(CameraTarget).@"struct".field_names) |name| if (@field(a.camera, name)) |v| { @field(c, name) = v; }; out = c; }; - return out; + return .{ .to = out orelse return null, .at = first }; } /// Adding objects, the same for both kinds of scene (anything with `add`). @@ -518,6 +554,25 @@ const adding = struct { } }; +/// `part`'s area: `.x`, `.y` its centre (0 when left out), `.w`, `.h`. +fn areaOf(spec: anytype) vector.geom.Rect { + const w: f32 = spec.w; + const h: f32 = spec.h; + return .{ .x = number(spec, "x", 0) - w / 2, .y = number(spec, "y", 0) - h / 2, .w = w, .h = h }; +} + +/// Where a part whose origin is `c` in its object's units stands, when the +/// object stands at `p`. +fn partPose(p: Pose, c: vector.geom.Vec) Pose { + var q = p; + const at = vector.geom.Affine.rotate(p.rotation).apply(c * vector.geom.splat(p.scale)); + q.x += at[0]; + q.y += at[1]; + q.into = Pose.none; + q.morph = 0; + return q; +} + fn primitive(source: Source, spec: anytype) Object { var pose: Pose = .{}; inline for (.{ "x", "y", "scale", "rotation", "opacity", "visible" }) |name| { @@ -545,14 +600,36 @@ pub const Builder = struct { values: []const f32 = &.{}, plays: []const Play = &.{}, updaters: []const Updater = &.{}, - stops: []const f32 = &.{}, + /// Parts, each following its object through the plays laid before it + /// was taken. + follows: []const Follow = &.{}, /// Where the next play starts. cursor: f32 = 0, + const Follow = struct { obj: u16, of: u16, plays: usize, at: vector.geom.Vec }; + pub fn add(b: *Builder, o: Object) Obj { b.objects = b.objects ++ .{o}; return @fromBackingInt(@intCast(b.objects.len - 1)); } + + /// The shapes of `of` whose bounds' centre lies in `area` (`.x`, `.y` + /// its centre, `.w`, `.h`, in `of`'s units: those of `s.rect` laid + /// over `of` at the origin, at scale 1), as an object of their own, + /// around the area's centre; `of` draws the rest. It stands where they + /// stood and shows as `of` does after the plays so far; plays after it + /// move one or the other. A shape goes to the first part that takes it. + pub fn part(b: *Builder, of: Obj, area: anytype) Obj { + const i = @backingInt(of); + const r = areaOf(area); + const whole = b.objects[i]; + var cut = whole; + cut.cut = whole.cut ++ .{r}; + b.objects = b.objects[0..i] ++ .{cut} ++ b.objects[i + 1 ..]; + const o = b.add(.{ .source = .{ .part = .{ .of = &whole, .area = r } }, .pose = partPose(whole.pose, r.center()) }); + b.follows = b.follows ++ .{Follow{ .obj = @backingInt(o), .of = i, .plays = b.plays.len, .at = r.center() }}; + return o; + } pub const svg = adding.svg; pub const typst = adding.typst; pub const rect = adding.rect; @@ -580,11 +657,6 @@ pub const Builder = struct { b.cursor += seconds; } - /// The player holds here until a click. - pub fn pause(b: *Builder) void { - b.stops = b.stops ++ .{b.cursor}; - } - /// From now on, every frame, `o`'s pose is `update(now, args...)`: /// `args` (a tuple) is bound here, like a closure's captures, so an /// updater can follow other objects or read values. @@ -618,21 +690,31 @@ pub fn Scene(comptime construct: fn (*Builder) void) type { var value_keys: [recorded.values.len][]const Key(f32) = @splat(&.{}); var camera_keys: []const Key(Camera) = &.{}; var marks: []const f32 = &.{}; - for (recorded.plays) |play| { + for (recorded.plays, 0..) |play, played| { var buf: [2 * play.animations.len]Change = undefined; + var touched: [n]bool = @splat(false); for (changes(&buf, &poses, play.animations)) |c| { - const k = play.key(Pose, c.from, c.to, c.ease); + const k = play.key(Pose, c.at, c.from, c.to, c.ease); keys[c.obj] = keys[c.obj] ++ .{k}; poses[c.obj] = k.at(k.end); + touched[c.obj] = true; } - for (play.animations) |a| if (a == .value) { + for (recorded.follows) |f| if (played < f.plays and touched[f.of]) { + var k = keys[f.of][keys[f.of].len - 1]; + k.from = partPose(k.from, f.at); + k.to = partPose(k.to, f.at); + keys[f.obj] = keys[f.obj] ++ .{k}; + poses[f.obj] = k.at(k.end); + touched[f.obj] = true; + }; + for (play.animations, 0..) |a, at| if (a == .value) { const i = @backingInt(a.value.value); - value_keys[i] = value_keys[i] ++ .{play.key(f32, values[i], a.value.to, null)}; + value_keys[i] = value_keys[i] ++ .{play.key(f32, at, values[i], a.value.to, null)}; values[i] = a.value.to; }; if (aim(view, play.animations)) |to| { - camera_keys = camera_keys ++ .{play.key(Camera, view, to, null)}; - view = to; + camera_keys = camera_keys ++ .{play.key(Camera, to.at, view, to.to, null)}; + view = to.to; } marks = marks ++ .{play.start}; } @@ -641,7 +723,6 @@ pub fn Scene(comptime construct: fn (*Builder) void) type { const frozen_objects = recorded.objects[0..n].*; const frozen_values = recorded.values[0..recorded.values.len].*; const frozen_updaters = recorded.updaters[0..recorded.updaters.len].*; - const frozen_stops = recorded.stops[0..recorded.stops.len].*; const frozen_keys = compiled.keys; const frozen_value_keys = compiled.value_keys; const frozen_camera_keys = compiled.camera_keys[0..compiled.camera_keys.len].*; @@ -663,7 +744,6 @@ pub fn Scene(comptime construct: fn (*Builder) void) type { pub const camera_keys: []const Key(Camera) = &frozen_camera_keys; /// Start times of every play, for chapter-style seeking. pub const marks: []const f32 = &frozen_marks; - pub const stops: []const f32 = &frozen_stops; pub const duration: f32 = recorded.cursor; /// Every Typst source, for the build step that compiles them. pub const typst_sources: []const []const u8 = &typst_list; @@ -678,7 +758,7 @@ pub fn Scene(comptime construct: fn (*Builder) void) type { m.* = .{ .from = k.from, .to = pose(p.into, k.end) }; }; } - return .{ .objects = objects, .poses = poses, .morphs = morphs, .values = try arena.dupe(f32, &values(now.t)), .camera = view(now.t), .duration = duration, .marks = marks, .stops = stops }; + return .{ .t = now.t, .objects = objects, .poses = poses, .morphs = morphs, .values = try arena.dupe(f32, &values(now.t)), .camera = view(now.t), .duration = duration, .marks = marks, .stops = &.{} }; } /// The key shaping object `i` at `t`: the last one to have started. @@ -723,9 +803,12 @@ fn latest(comptime P: type, keys: []const Key(P), t: f32) ?Key(P) { return found; } +pub const BuildError = error{ TypstNotCompiled, CustomHasNoDrawing } || vector.svg.Error; + /// The drawing of an object, centered on its origin, in pixels at scale 1. /// `compiled` has `find(source) ?[]const u8` for Typst objects' SVGs. -pub fn build(arena: std.mem.Allocator, o: Object, compiled: anytype) !Drawing { +pub fn build(arena: std.mem.Allocator, o: Object, compiled: anytype) BuildError!Drawing { + if (o.source == .part or o.cut.len > 0) return sift(arena, try build(arena, o.whole(), compiled), o); const document: ?[]const u8 = switch (o.source) { .svg => |bytes| bytes, .typst => |source| compiled.find(source) orelse return error.TypstNotCompiled, @@ -738,8 +821,14 @@ pub fn build(arena: std.mem.Allocator, o: Object, compiled: anytype) !Drawing { // Keep the SVG's pixel size (Typst's points are 4/3 px), centered. const s = if (d.view.w > 0) d.width / d.view.w else 1; const c = d.view.center(); + const centring = vector.geom.Affine.scale(s, s).mul(.translate(-c[0], -c[1])); const shapes = try arena.dupe(Drawing.Shape, d.shapes); - for (shapes) |*shape| shape.transform = vector.geom.Affine.scale(s, s).mul(.translate(-c[0], -c[1])).mul(shape.transform); + for (shapes) |*shape| { + shape.transform = centring.mul(shape.transform); + if (shape.clip) |*q| for (q) |*v| { + v.* = centring.apply(v.*); + }; + } var out = d; out.shapes = shapes; out.view = .{ .x = -d.view.w * s / 2, .y = -d.view.h * s / 2, .w = d.view.w * s, .h = d.view.h * s }; @@ -779,13 +868,43 @@ pub fn build(arena: std.mem.Allocator, o: Object, compiled: anytype) !Drawing { style.stroke = .none; } }, - .svg, .typst, .custom => unreachable, + .svg, .typst, .custom, .part => unreachable, } try b.endShape(.identity, style); const r = @max(extent(o.source), 1); return b.finish(.{ .x = -r, .y = -r, .w = 2 * r, .h = 2 * r }, 2 * r, 2 * r); } +/// The drawing of a part, or of an object parts were taken from, out of +/// `whole`, the drawing of `o.whole()`: the shapes whose bounds' centre +/// lies in the part's area, around the area's centre; or those in none of +/// the object's `cut`, where they were. Shapes and geometry are shared. +pub fn sift(arena: std.mem.Allocator, whole: Drawing, o: Object) error{OutOfMemory}!Drawing { + const areas: []const vector.geom.Rect = if (o.cut.len > 0) o.cut else &.{o.source.part.area}; + const keep_inside = o.cut.len == 0; + const c: vector.geom.Vec = if (keep_inside) areas[0].center() else .{ 0, 0 }; + const to = vector.geom.Affine.translate(-c[0], -c[1]); + var shapes: std.ArrayList(Drawing.Shape) = .empty; + for (whole.shapes) |shape| { + const b = whole.shapeBounds(shape); + const mid = shape.transform.apply((b.min + b.max) * vector.geom.splat(0.5)); + const inside = for (areas) |a| { + if (mid[0] >= a.x and mid[0] < a.x + a.w and mid[1] >= a.y and mid[1] < a.y + a.h) break true; + } else false; + if (inside != keep_inside) continue; + var kept = shape; + kept.transform = to.mul(shape.transform); + if (kept.clip) |*q| for (q) |*v| { + v.* = to.apply(v.*); + }; + try shapes.append(arena, kept); + } + var out = whole; + out.shapes = shapes.items; + if (keep_inside) out.view = .{ .x = -areas[0].w / 2, .y = -areas[0].h / 2, .w = areas[0].w, .h = areas[0].h }; + return out; +} + fn extent(s: Source) f32 { return switch (s) { .rect => |r| @max(r.w, r.h) / 2, @@ -796,7 +915,7 @@ fn extent(s: Source) f32 { for (pts) |p| m = @max(m, @max(@abs(p[0]), @abs(p[1]))); break :blk m; }, - .svg, .typst, .custom => 0, + .svg, .typst, .custom, .part => 0, }; } @@ -816,40 +935,68 @@ pub fn color(c: u32) Drawing.Color { /// A live scene: `frame` runs every frame, at runtime, and the scene is /// whatever it builds. `typst` is a namespace whose declarations are the -/// Typst sources `frame` uses, for the build to compile. -pub fn Live(comptime frame: fn (*Frame) void, comptime typst: type) type { - const decls = @typeInfo(typst).@"struct".decl_names; - var sources: [decls.len][]const u8 = undefined; - for (&sources, decls) |*s, name| s.* = @field(typst, name); - const frozen_sources = sources; +/// Typst sources `frame` uses, or a tuple of them (`sources`), for the +/// build to compile. +pub fn Live(comptime frame_fn: fn (*Frame) void, comptime typst: anytype) type { return struct { - pub const typst_sources: []const []const u8 = &frozen_sources; + pub const frame = frame_fn; + pub const typst_sources: []const []const u8 = sources(typst); - /// The scene at `now`, for the player: `frame`, run once. + /// The scene at `now`, `frame` run once, its gates all closed. pub fn shot(arena: std.mem.Allocator, now: Instant) !Shot { - var s: Frame = .{ .t = now.t, .clock = now.clock, .in = now.in, .pointer = now.pointer, .arena = arena }; - frame(&s); - const values = try arena.alloc(f32, s.values.items.len); - for (values, s.values.items) |*v, own| v.* = own.shown; - return .{ .objects = s.objects.items, .poses = s.shown.items, .morphs = s.morphs.items, .values = values, .camera = s.view, .duration = s.cursor, .marks = s.marks.items, .stops = s.stops.items }; + var s: Frame = .{ .t = now.t, .in = now.in, .pointer = now.pointer, .arena = arena }; + frame_fn(&s); + return s.shot(); } }; } +/// Every declaration of `namespaces` (a namespace, or a tuple of them), +/// each a Typst source, for the build to compile: a sketch that draws +/// Typst itself declares `pub const scene = struct { pub const +/// typst_sources = anim.sources(.{typst}); };` for `sb.addTypst`. +pub fn sources(comptime namespaces: anytype) []const []const u8 { + const frozen = comptime blk: { + const all = if (@TypeOf(namespaces) == type) .{namespaces} else namespaces; + var out: []const []const u8 = &.{}; + for (all) |namespace| for (@typeInfo(namespace).@"struct".decl_names) |name| { + out = out ++ .{@as([]const u8, @field(namespace, name))}; + }; + break :blk out[0..out.len].*; + }; + return &frozen; +} + /// What a live scene's `frame` gets: the time, the input, and the same calls /// as `Builder`, which take effect at `t` right away. pub const Frame = struct { - /// Scene time, in seconds. + /// Scene time, in seconds. In a talk it runs on through gates. t: f32, - /// Seconds on the wall clock, which runs on while the player pauses: - /// for motion that should not stop. - clock: f32, in: *const sk.Input, /// The mouse, in scene units from the canvas center (before the scene's /// own camera). pointer: [2]f32, /// Lives for this frame. arena: std.mem.Allocator, + /// The gates opened so far, in order (the deck's log). + gates: []const Gate = &.{}, + /// The presenter asked for the next step (`Ask.next`) and nothing has + /// taken it yet: the `pause` it reaches opens. Code laid out before + /// that pause takes the click for itself by setting it false (a widget + /// the click landed on). + next: bool = false, + /// This update's events, pointer positions in scene units + /// (`Deck.pointer`): in the deck's `update` run only, empty when drawn. + events: []const sk.Event = &.{}, + /// Where `gate` writes a gate that opens: the deck's `update` run only. + log: ?*Log = null, + /// Open every gate laid before `slides` slides, `hold` after it is + /// reached (or now, if that is later): `Ask.end`, `next_slide`, export. + lay: ?Lay = null, + /// A gate opened in this run: one click opens one gate. + opened: bool = false, + /// Where the first gate still closed is laid. + closed: ?f32 = null, /// Where the next play starts. cursor: f32 = 0, objects: std.ArrayList(Object) = .empty, @@ -861,7 +1008,12 @@ pub const Frame = struct { settled_view: Camera = .{}, view: Camera = .{}, marks: std.ArrayList(f32) = .empty, + /// Where each gate is laid: the cursor when the code reached it. stops: std.ArrayList(f32) = .empty, + /// Where each `slide` begins, and how many gates come before it. + slides: std.ArrayList(struct { at: f32, gates: u32 }) = .empty, + + const Lay = struct { hold: f32, slides: usize }; pub fn add(s: *Frame, o: Object) Obj { s.push(&s.objects, o); @@ -879,6 +1031,19 @@ pub const Frame = struct { pub const polygon = adding.polygon; pub const custom = adding.custom; + /// The shapes of `of` inside `area`, as an object of their own, showing + /// as `of` does now; `of` draws the rest (see `Builder.part`). + pub fn part(s: *Frame, of: Obj, area: anytype) Obj { + const i = @backingInt(of); + const r = areaOf(area); + const whole = s.new(s.objects.items[i]); + s.objects.items[i].cut = std.mem.concat(s.arena, vector.geom.Rect, &.{ whole.cut, &.{r} }) catch @panic("anim: out of memory"); + const o = s.add(.{ .source = .{ .part = .{ .of = whole, .area = r } }, .pose = partPose(whole.pose, r.center()) }); + s.settled.items[@backingInt(o)] = partPose(s.settled.items[i], r.center()); + s.shown.items[@backingInt(o)] = partPose(s.shown.items[i], r.center()); + return o; + } + pub fn value(s: *Frame, initial: f32) Value { s.push(&s.values, .{ .settled = initial, .shown = initial }); return @fromBackingInt(@intCast(s.values.items.len - 1)); @@ -904,29 +1069,32 @@ pub const Frame = struct { /// they stand at `t`, then moves the cursor past them. pub fn play(s: *Frame, animations: anytype, options: anytype) void { const all = list(animations); - const p = Play.of(s.cursor, &all, options); - const started = s.t >= p.start; var buf: [2 * all.len]Change = undefined; - const touched = changes(&buf, s.settled.items, &all); + s.playAll(&all, &buf, Play.of(s.cursor, &all, options)); + } + + /// `play`, of animations known at runtime; `buf` holds two changes each. + fn playAll(s: *Frame, all: []const Animation, buf: []Change, p: Play) void { + const touched = changes(buf, s.settled.items, all); for (touched) |c| { - const k = p.key(Pose, c.from, c.to, c.ease); + const k = p.key(Pose, c.at, c.from, c.to, c.ease); s.settled.items[c.obj] = k.at(k.end); - if (started) s.shown.items[c.obj] = k.at(s.t); + if (s.t >= k.start) s.shown.items[c.obj] = k.at(s.t); } // A morph ends where its target settles. - if (started) for (touched) |c| if (c.from.into != Pose.none) { + for (touched) |c| if (c.from.into != Pose.none and s.t >= p.key(Pose, c.at, c.from, c.to, c.ease).start) { s.morphs.items[c.obj] = .{ .from = c.from, .to = s.settled.items[c.from.into] }; }; - for (all) |a| if (a == .value) { + for (all, 0..) |a, at| if (a == .value) { const v = &s.values.items[@backingInt(a.value.value)]; - const k = p.key(f32, v.settled, a.value.to, null); + const k = p.key(f32, at, v.settled, a.value.to, null); v.settled = a.value.to; - if (started) v.shown = k.at(s.t); + if (s.t >= k.start) v.shown = k.at(s.t); }; - if (aim(s.settled_view, &all)) |to| { - const k = p.key(Camera, s.settled_view, to, null); - s.settled_view = to; - if (started) s.view = k.at(s.t); + if (aim(s.settled_view, all)) |to| { + const k = p.key(Camera, to.at, s.settled_view, to.to, null); + s.settled_view = to.to; + if (s.t >= k.start) s.view = k.at(s.t); } s.push(&s.marks, p.start); s.cursor += p.seconds; @@ -936,9 +1104,85 @@ pub const Frame = struct { s.cursor += seconds; } - /// The player holds here until a click, like a slide. - pub fn pause(s: *Frame) void { + /// A gate: the plays after it wait until it opens, while time runs on, + /// so plays already running, loops and code reading `t` carry on. It + /// opens in the deck's `update`, on the first frame at or after it is + /// reached on which `open` is not null, and from then on returns that + /// value, a choice to branch on; closed, it returns null. The cursor + /// moves to where it opened, or, closed, just past `t`, so what follows + /// waits in the future. Gates are known by the order they are reached. + pub fn gate(s: *Frame, open: ?u16) ?u16 { + const k = s.stops.items.len; s.push(&s.stops, s.cursor); + if (k < s.gates.len) { + s.cursor += s.gates[k].wait; + return s.gates[k].value; + } + if (s.closed == null) if (s.log) |log| { + const laying = if (s.lay) |lay| s.slides.items.len < lay.slides else false; + const opens = if (laying) open orelse 0 else if (!s.opened and s.t >= s.cursor) open else null; + if (opens) |v| { + const wait_for = if (laying) @max(s.lay.?.hold, s.t - s.cursor) else s.t - s.cursor; + if (log.appendBounded(.{ .wait = wait_for, .value = v })) { + s.opened = true; + s.cursor += wait_for; + return v; + } else |_| {} + } + }; + if (s.closed == null) s.closed = s.cursor; + s.cursor = @max(s.cursor, s.t + 1.0 / 60.0); + return null; + } + + /// A gate the presenter opens (`Ask.next`: a click, space, page down), + /// like a slide's next step. + pub fn pause(s: *Frame) void { + _ = s.gate(if (s.next) 0 else null); + } + + /// A slide begins: `Ask.next_slide` and `back_slide` go from slide to + /// slide, each shown at rest, held at its first gate. + pub fn slide(s: *Frame) void { + s.push(&s.slides, .{ .at = s.cursor, .gates = @intCast(s.stops.items.len) }); + } + + /// `f(s, args...)` beside the main line: its plays start at the cursor, + /// and the cursor is left where it was, so what follows runs alongside. + pub fn beside(s: *Frame, comptime f: anytype, args: anytype) void { + const at = s.cursor; + @call(.auto, f, .{s} ++ args); + s.cursor = at; + } + + /// `f(s, args...)`, a run of plays that ends where it began, again and + /// again from the cursor until the gate laid right after it opens (for + /// ever while it is closed); the cycle running then completes. The + /// cursor is left where it was. `f` only plays: objects are made + /// outside it. It costs two runs of `f` a frame at most. + pub fn loop(s: *Frame, comptime f: anytype, args: anytype) void { + const start = s.cursor; + @call(.auto, f, .{s} ++ args); // the first cycle, which measures it + const period = s.cursor - start; + const k = s.stops.items.len; + const until = if (k < s.gates.len) start + s.gates[k].wait else std.math.inf(f32); + if (period > 0 and s.t >= start + period) { + var cycle = @floor((@min(s.t, until) - start) / period); + // One that would begin as the gate opens never runs. + if (cycle > 0 and start + cycle * period >= until) cycle -= 1; + s.cursor = start + cycle * period; + @call(.auto, f, .{s} ++ args); // the cycle in progress, which wins + } + s.cursor = start; + } + + /// Fades out everything that shows once the plays so far are done, on + /// the main line (`play`'s options): the end of a slide. + pub fn clear(s: *Frame, options: anytype) void { + var all: std.ArrayList(Animation) = .empty; + for (s.settled.items, 0..) |p, i| if (p.visible and p.opacity > 0) s.push(&all, .{ .fade_out = @fromBackingInt(@intCast(i)) }); + const buf = s.arena.alloc(Change, 2 * all.items.len) catch @panic("anim: out of memory"); + s.playAll(all.items, buf, Play.of(s.cursor, all.items, options)); } /// `data` in the arena, to change until the frame ends: what a custom @@ -949,6 +1193,22 @@ pub const Frame = struct { return kept; } + /// What the run built, for the player. + fn shot(s: *Frame) !Shot { + const values = try s.arena.alloc(f32, s.values.items.len); + for (values, s.values.items) |*v, own| v.* = own.shown; + return .{ .t = s.t, .objects = s.objects.items, .poses = s.shown.items, .morphs = s.morphs.items, .values = values, .camera = s.view, .duration = s.cursor, .marks = s.marks.items, .stops = s.stops.items }; + } + + /// Slide `j`'s resting picture: where its first gate is laid, or, with + /// no gate of its own, where the next slide begins or the talk ends. + fn rest(s: *const Frame, j: usize) f32 { + const first = s.slides.items[j].gates; + const after = if (j + 1 < s.slides.items.len) s.slides.items[j + 1] else null; + if (first < s.stops.items.len and (after == null or first < after.?.gates)) return s.stops.items[first]; + return if (after) |a| a.at else s.cursor; + } + /// Keeps scene code free of error handling: the frame arena running out /// is fatal anyway. fn push(s: *Frame, items: anytype, item: @TypeOf(items.items[0])) void { @@ -957,13 +1217,215 @@ pub const Frame = struct { }; // --------------------------------------------------------------------------- +// Talks: a live scene with gates, and its playhead + +/// A gate opened: how long after it was reached, and the value it opened with. +pub const Gate = struct { wait: f32 = 0, value: u16 = 0 }; + +const Log = sk.List(Gate, 256); + +/// What the presenter asks of a deck this frame. The sketch decides which +/// keys and clicks they are: the deck owns no input. +pub const Ask = struct { + /// The next step: opens the pause the deck waits at, or, during a + /// step, finishes it (the playhead jumps to where the next gate is + /// laid; at the last step, to the end). A paused deck plays on. + next: bool = false, + /// Back a step: the picture held before the last gate opened. + back: bool = false, + /// The next or the previous slide (`Frame.slide`), at rest: held at + /// its first gate, every gate before it opened (at once, a choice with + /// 0) or undone. + next_slide: bool = false, + back_slide: bool = false, + /// A seek: the gates opened after it have not happened yet. + to: ?f32 = null, + /// The end: every gate opened where it is reached. + end: bool = false, +}; + +/// A talk's playhead: plain data for a sketch's State, so hot reload, +/// snapshots, replay and the console see it like any field. The talk is +/// `frame(s: *Frame, ctx...)`, a live scene's frame with more arguments, +/// run from the top every frame: in `update`, given `ctx` as it is, so it +/// may change the app (`mutable`), and in `shot`, given it read-only. +pub const Deck = struct { + /// Talk time, in seconds: it runs on through gates. + t: f32 = 0, + playing: bool = true, + speed: f32 = 1, + /// Exported, each gate holds this long, then opens itself. + hold: f32 = 1, + /// The gates opened, in order: with `t`, all the talk depends on. + log: Log = .{}, + /// When the last gate in `log` opened, as of the last update: an edit + /// that moves it moves `t` with it, so a reload keeps the same step, as + /// far into it. + anchor: f32 = 0, + /// The talk as the last update laid it, for a HUD and for scripts: its + /// end (a closed gate lays what follows it just past `t`), the gates + /// laid, opened or not, whether it waits at one, the slides begun by + /// `t`, and all the slides. + duration: f32 = 0, + gates: u32 = 0, + waiting: bool = false, + slide: u32 = 0, + slides: u32 = 0, + + /// In `update`: time from the ticks, `ask` applied, and the talk run + /// once (more when asked to move), opening the gate it waits at. + /// Exported (`in.exporting`), it opens every gate `hold` after it is + /// reached, in the first frame's run, and runs at the export's pace. + pub fn update(d: *Deck, in: *const sk.Input, ask: Ask, comptime frame: anytype, ctx: anytype) void { + var arena_state: std.heap.ArenaAllocator = .init(std.heap.page_allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + for (in.events) |e| if (e.kind == .tick) { + if (in.exporting) { + d.t += e.x; + } else if (d.playing) d.t += e.x * d.speed; + }; + if (ask.next) d.playing = true; + const events = arena.dupe(sk.Event, in.events) catch return; + for (events) |*e| switch (e.kind) { + .mouse_move, .mouse_down, .mouse_up, .wheel, .wheel_horizontal => { + const p = pointer(in, e.x, e.y); + e.x = p[0]; + e.y = p[1]; + }, + else => {}, + }; + const all: Frame.Lay = .{ .hold = 0, .slides = std.math.maxInt(usize) }; + + // Elsewhere: against the talk as it is laid now. + const moves = ask.back or ask.to != null or ask.end or ask.next_slide or ask.back_slide; + if (moves) { + const m = d.run(arena, in, frame, readOnly(ctx), &.{}, false, false, null); + d.log.len = @min(d.log.count(), m.stops.items.len); + const n = d.log.count(); + var on: u32 = 0; + for (m.slides.items) |sl| on += @intFromBool(sl.at <= d.t); + if (ask.back) { + d.t = if (n > 0) m.stops.items[n - 1] + d.log.buffer[n - 1].wait else 0; + d.log.len = n -| 1; + } else if (ask.to) |to| { + d.t = to; + while (d.log.count() > 0 and m.stops.items[d.log.count() - 1] + d.log.buffer[d.log.count() - 1].wait > to) d.log.len -= 1; + } else if (ask.back_slide) { + if (on < 2) { + d.t = 0; + d.log.len = 0; + } else { + d.log.len = m.slides.items[on - 2].gates; + d.t = m.rest(on - 2); + } + } else { + // Gates open up to the next slide's first, or all of them: + // a choice may be what lays the slides after it. + const l = d.run(arena, in, frame, readOnly(ctx), &.{}, true, false, if (ask.next_slide) .{ .hold = 0, .slides = on + 1 } else all); + d.t = if (ask.next_slide and on < l.slides.items.len) l.rest(on) else l.cursor; + } + } + + const before = d.log.count(); + var s = d.run(arena, in, frame, ctx, events, true, ask.next and !moves, if (in.exporting) .{ .hold = d.hold, .slides = all.slides } else null); + if (s.stops.items.len < before) { + // An edit took gates out: the ones it left are the talk's. + d.log.len = @intCast(s.stops.items.len); + } else if (!moves and before > 0) { + // An edit moved the last opened gate: so does `t`. That run's + // input is not taken again. + const now = s.stops.items[before - 1] + d.log.buffer[before - 1].wait; + if (now != d.anchor) { + d.log.len = before; + d.t += now - d.anchor; + s = d.run(arena, in, frame, readOnly(ctx), &.{}, false, false, null); + } + } + // A step under way, finished: the playhead to where it waits next. + if (ask.next and s.next and !s.opened and !moves) d.t = @max(d.t, s.closed orelse s.cursor); + + const n = d.log.count(); + d.anchor = if (n > 0) s.stops.items[n - 1] + d.log.buffer[n - 1].wait else 0; + d.duration = s.cursor; + d.gates = @intCast(s.stops.items.len); + d.waiting = if (s.closed) |c| d.t >= c else false; + d.slides = @intCast(s.slides.items.len); + d.slide = 0; + for (s.slides.items) |sl| d.slide += @intFromBool(sl.at <= d.t); + } + + /// In `draw`: the talk now, for `Painter.paint`; `ctx` read-only and + /// the log too, so drawing changes nothing. + pub fn shot(d: *const Deck, arena: std.mem.Allocator, in: *const sk.Input, mouse: [2]f32, comptime frame: anytype, ctx: anytype) !Shot { + var s: Frame = .{ .t = d.t, .in = in, .pointer = mouse, .arena = arena, .gates = d.log.constSlice() }; + @call(.auto, frame, .{&s} ++ readOnly(ctx)); + return s.shot(); + } + + /// Window pixels to scene units from the center: the scene's frame + /// (`width` by `height`) fitted into the window, as `Painter` draws it. + pub fn pointer(in: *const sk.Input, x: f32, y: f32) [2]f32 { + const w = @max(@floor(in.window_width), 1); + const h = @max(@floor(in.window_height), 1); + const k = @min(w / width, h / height); + return .{ (x - w / 2) / k, (y - h / 2) / k }; + } + + /// One run of the talk at `t`, as the log stands. + fn run(d: *Deck, arena: std.mem.Allocator, in: *const sk.Input, comptime frame: anytype, ctx: anytype, events: []const sk.Event, logs: bool, next: bool, lay: ?Frame.Lay) Frame { + var s: Frame = .{ + .t = d.t, + .in = in, + .pointer = pointer(in, in.mouse_x, in.mouse_y), + .arena = arena, + .gates = d.log.constSlice(), + .log = if (logs) &d.log else null, + .next = next, + .events = events, + .lay = lay, + }; + @call(.auto, frame, .{&s} ++ ctx); + return s; + } +}; + +/// `app`, to change: a talk is given the app as `*App` in the deck's +/// `update` run and as `*const App` when drawn, where this is null, so +/// drawing cannot write to it. `if (anim.mutable(app)) |a| a.n += 1`. +pub fn mutable(app: anytype) ?*@typeInfo(@TypeOf(app)).pointer.child { + return if (@typeInfo(@TypeOf(app)).pointer.attrs.@"const") null else app; +} + +/// `ctx` with every pointer in it to const: what the runs that only look +/// are given. +fn readOnly(ctx: anytype) ReadOnly(@TypeOf(ctx)) { + var out: ReadOnly(@TypeOf(ctx)) = undefined; + inline for (0..ctx.len) |i| out[i] = ctx[i]; + return out; +} + +fn ReadOnly(comptime Ctx: type) type { + const types = @typeInfo(Ctx).@"struct".field_types; + var out: [types.len]type = undefined; + for (&out, types) |*o, T| o.* = switch (@typeInfo(T)) { + .pointer => |p| if (p.size == .one) *const p.child else T, + else => T, + }; + return @Tuple(&out); +} + +/// The scene's frame, in scene units: what shows at camera zoom 1. +pub const width = 1280; +pub const height = 720; + +// --------------------------------------------------------------------------- // Both kinds, to the player /// What a scene is asked for, each frame. pub const Instant = struct { /// Scene time, in seconds. t: f32, - clock: f32 = 0, in: *const sk.Input = &no_input, pointer: [2]f32 = .{ 0, 0 }, @@ -972,6 +1434,7 @@ pub const Instant = struct { /// A scene at one instant: what the player draws. pub const Shot = struct { + t: f32, objects: []const Object, poses: []const Pose, /// For each object morphing (`pose.into`): the pose its morph started @@ -983,7 +1446,7 @@ pub const Shot = struct { duration: f32, /// Start times of every play, for chapter-style seeking. marks: []const f32, - /// Where the player holds until a click (`pause`). + /// Where each gate is laid (`gate`, `pause`). stops: []const f32, }; @@ -1053,3 +1516,520 @@ test "a live scene shows what the compiled one does, at every instant" { try std.testing.expectEqualSlices(f32, a.marks, b.marks); } } + +test "Typst sources come from a namespace or a tuple of them" { + const a = struct { + pub const title = "= A"; + }; + const b = struct { + pub const law = "$ x $"; + pub const end = "= B"; + }; + try std.testing.expectEqual(@as(usize, 1), Live(liveScene, a).typst_sources.len); + try std.testing.expectEqualStrings("$ x $", Live(liveScene, .{ a, b }).typst_sources[1]); + try std.testing.expectEqual(@as(usize, 3), sources(.{ a, b }).len); + try std.testing.expect(Live(liveScene, a).frame == liveScene); +} + +// --------------------------------------------------------------------------- +// Talks: the semantics of the model in .scratch/sketch/anim/gates_model.zig +// (pardes-code), on the real types, then the presenter's rulings. + +/// `d.update` with `before` and then a tick of `seconds`, in a window the +/// size of the scene's frame (its center the scene's origin). +fn step(d: *Deck, before: []const sk.Event, seconds: f32, ask: Ask, comptime frame: anytype, ctx: anytype) void { + var events: [8]sk.Event = undefined; + @memcpy(events[0..before.len], before); + events[before.len] = .{ .kind = .tick, .x = seconds }; + d.update(&.{ .events = events[0 .. before.len + 1], .window_width = width, .window_height = height }, ask, frame, ctx); +} + +/// Value 0 of the talk drawn now. +fn shown(d: *const Deck, arena: std.mem.Allocator, comptime frame: anytype, ctx: anytype) !f32 { + return (try d.shot(arena, &Instant.no_input, .{ 0, 0 }, frame, ctx)).values[0]; +} + +/// Round 1's slide 2: a phase that runs from `spin`, through the hold at +/// the second gate, until half a second after it opens; -1 otherwise. +fn orbit(s: *Frame) void { + const phase = s.value(-1); + s.wait(2); // the title, written + s.pause(); + s.wait(2.5); // out, and the equation in + const spin = s.cursor; + s.pause(); + const leave = s.cursor; + s.wait(0.5); + if (s.t >= spin and s.t < leave + 0.5) s.values.items[@backingInt(phase)].shown = s.t - spin; +} + +test "a loop runs on through the hold, and its phase is continuous across the click" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + var d: Deck = .{}; + step(&d, &.{}, 10, .{}, orbit, .{}); + try std.testing.expect(d.waiting and d.log.count() == 0 and d.gates == 2); + step(&d, &.{}, 0, .{ .next = true }, orbit, .{}); + try std.testing.expectEqual(@as(f32, 8), d.log.buffer[0].wait); + // Slide 2 is in at 12.5; at 15 the deck waits, the phase running. + step(&d, &.{}, 5, .{}, orbit, .{}); + try std.testing.expect(d.waiting); + const before = try shown(&d, arena.allocator(), orbit, .{}); + step(&d, &.{}, 0, .{ .next = true }, orbit, .{}); + try std.testing.expect(!d.waiting and d.log.count() == 2); + try std.testing.expectEqual(before, try shown(&d, arena.allocator(), orbit, .{})); + try std.testing.expectApproxEqAbs(@as(f32, 2.5), before, 1e-4); + // Half a second after the click it has gone. + step(&d, &.{}, 0.6, .{}, orbit, .{}); + try std.testing.expectEqual(@as(f32, -1), try shown(&d, arena.allocator(), orbit, .{})); +} + +/// Round 1's equation, stepped: written to 1, then each step morphs it one +/// further, to 4. +fn equations(s: *Frame) void { + const form = s.value(0); + s.play(.{form.to(1)}, .{ .seconds = 2, .ease = ease.linear }); + for (2..5) |i| { + s.pause(); + s.play(.{form.to(@floatFromInt(i))}, .{ .seconds = 1.2, .ease = ease.linear }); + } +} + +test "back cuts to the picture held before the last click" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + var d: Deck = .{}; + // Clicks at 5, 9 and 20. + step(&d, &.{}, 5, .{ .next = true }, equations, .{}); + step(&d, &.{}, 4, .{ .next = true }, equations, .{}); + step(&d, &.{}, 11, .{ .next = true }, equations, .{}); + try std.testing.expectEqual(@as(u32, 3), d.log.count()); + step(&d, &.{}, 0.6, .{}, equations, .{}); + try std.testing.expectApproxEqAbs(@as(f32, 3.5), try shown(&d, arena.allocator(), equations, .{}), 1e-3); + // Back, mid-morph: the third form at rest, held where the click was. + step(&d, &.{}, 0, .{ .back = true }, equations, .{}); + try std.testing.expect(d.t == 20 and d.log.count() == 2 and d.waiting); + try std.testing.expectEqual(@as(f32, 3), try shown(&d, arena.allocator(), equations, .{})); + // Time runs on while held; nothing moves. + step(&d, &.{}, 40, .{}, equations, .{}); + try std.testing.expectEqual(@as(f32, 3), try shown(&d, arena.allocator(), equations, .{})); + // Back again: the second form, at 9; then the first, at 5; then the start. + step(&d, &.{}, 0, .{ .back = true }, equations, .{}); + try std.testing.expect(d.t == 9 and d.log.count() == 1); + try std.testing.expectEqual(@as(f32, 2), try shown(&d, arena.allocator(), equations, .{})); + step(&d, &.{}, 0, .{ .back = true }, equations, .{}); + try std.testing.expect(d.t == 5 and d.log.count() == 0 and d.waiting); + step(&d, &.{}, 0, .{ .back = true }, equations, .{}); + try std.testing.expect(d.t == 0 and !d.waiting); + // Forward after back plays the step again. + step(&d, &.{}, 3, .{ .next = true }, equations, .{}); + step(&d, &.{}, 0.6, .{}, equations, .{}); + try std.testing.expectApproxEqAbs(@as(f32, 1.5), try shown(&d, arena.allocator(), equations, .{}), 1e-3); +} + +test "exported, each gate opens a fixed hold after it is reached: the same frames every run" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + var runs: [2]Deck = .{ .{ .hold = 1 }, .{ .hold = 1 } }; + var seen: [2][4]f32 = undefined; + for (&runs, &seen) |*d, *values| for (0..10 * 30) |frame| { + const tick = [_]sk.Event{.{ .kind = .tick, .x = 1.0 / 30.0 }}; + d.update(&.{ .events = &tick, .exporting = true, .window_width = width, .window_height = height }, .{}, equations, .{}); + if (frame % 75 == 0) values[frame / 75] = try shown(d, arena.allocator(), equations, .{}); + }; + for (runs) |d| { + try std.testing.expectEqual(@as(u32, 3), d.log.count()); + for (d.log.constSlice()) |g| try std.testing.expectEqual(@as(f32, 1), g.wait); + try std.testing.expectApproxEqAbs(@as(f32, 2 + 3 * 2.2), d.duration, 1e-4); + } + try std.testing.expectEqualSlices(Gate, runs[0].log.constSlice(), runs[1].log.constSlice()); + try std.testing.expectEqual(seen[0], seen[1]); +} + +/// A talk that branches on the app's choice: proof (0) is two steps with a +/// pause between, skip (1) one; both end on the same slide. Each part shows +/// a circle: proof one, proof two, skipped, the end. +fn branching(s: *Frame, app: anytype) void { + var parts: [4]Obj = undefined; + for (&parts) |*p| p.* = s.circle(.{ .r = 1 }); + s.wait(2); + const pick = s.gate(app.pick) orelse return; // closed: nothing after it shows + switch (pick) { + 0 => { + s.play(.{parts[0].fadeIn()}, .{}); + s.pause(); + s.play(.{parts[1].fadeIn()}, .{}); + }, + else => s.play(.{parts[2].fadeIn()}, .{}), + } + s.play(.{parts[3].fadeIn()}, .{}); +} + +const Choice = struct { pick: ?u16 = null }; + +fn showing(d: *const Deck, arena: std.mem.Allocator, app: *const Choice) ![4]bool { + const shot = try d.shot(arena, &Instant.no_input, .{ 0, 0 }, branching, .{app}); + var out: [4]bool = undefined; + for (&out, shot.poses) |*o, p| o.* = p.visible; + return out; +} + +test "a choice is logged in update, branched on, and replays from the log alone" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + var app: Choice = .{}; + var d: Deck = .{}; + step(&d, &.{}, 3, .{}, branching, .{&app}); + try std.testing.expect(d.waiting and d.log.count() == 0); + // A click is no choice. + step(&d, &.{}, 0, .{ .next = true }, branching, .{&app}); + try std.testing.expect(d.waiting and d.log.count() == 0 and d.t == 3); + // The app says "skip": the gate opens with 1. + app.pick = 1; + step(&d, &.{}, 0, .{}, branching, .{&app}); + try std.testing.expectEqual(Gate{ .wait = 1, .value = 1 }, d.log.buffer[0]); + // From the log alone, whatever the app says now: skipped, then the end. + app.pick = null; + d.t = 3.5; + try std.testing.expectEqual([4]bool{ false, false, true, false }, try showing(&d, arena.allocator(), &app)); + d.t = 4.5; + try std.testing.expectEqual([4]bool{ false, false, true, true }, try showing(&d, arena.allocator(), &app)); + // Another log takes the proof, whose pause is the second gate. + var proof: Deck = .{ .t = 4.5 }; + try proof.log.appendBounded(.{ .wait = 1, .value = 0 }); + try std.testing.expectEqual([4]bool{ true, false, false, false }, try showing(&proof, arena.allocator(), &app)); + try proof.log.appendBounded(.{ .wait = 2 }); + proof.t = 6.5; + try std.testing.expectEqual([4]bool{ true, true, false, false }, try showing(&proof, arena.allocator(), &app)); +} + +fn twoPauses(s: *Frame) void { + s.wait(2); + s.pause(); + s.pause(); +} + +test "one click opens one gate, even when two are back to back" { + var d: Deck = .{}; + step(&d, &.{}, 5, .{ .next = true }, twoPauses, .{}); + try std.testing.expect(d.log.count() == 1 and d.waiting); + step(&d, &.{}, 0, .{ .next = true }, twoPauses, .{}); + try std.testing.expect(d.log.count() == 2 and !d.waiting); +} + +/// A swing of value `v` from 0 to 1 and back, in 1.5 s. +fn swing(s: *Frame, v: Value) void { + s.play(.{v.to(1)}, .{ .seconds = 0.75, .ease = ease.linear }); + s.play(.{v.to(0)}, .{ .seconds = 0.75, .ease = ease.linear }); +} + +fn swinging(s: *Frame) void { + const v = s.value(0); + s.wait(2); + s.loop(swing, .{v}); + s.pause(); +} + +test "a loop repeats until the next gate opens, then finishes its cycle" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + // Laid at 2: at 5.3 the third cycle is 0.3 s in. + var f: Frame = .{ .t = 5.3, .in = &Instant.no_input, .pointer = .{ 0, 0 }, .arena = arena.allocator() }; + swinging(&f); + try std.testing.expectApproxEqAbs(@as(f32, 0.4), f.get(@fromBackingInt(0)), 1e-4); + // The gate opened at 6, in the third cycle (from 5): at 6.4 it is + // still swinging back, at 6.6 done, with no fourth. + const gates = [_]Gate{.{ .wait = 4 }}; + var g: Frame = .{ .t = 6.4, .in = &Instant.no_input, .pointer = .{ 0, 0 }, .arena = arena.allocator(), .gates = &gates }; + swinging(&g); + try std.testing.expectApproxEqAbs(@as(f32, 1 - 0.65 / 0.75), g.get(@fromBackingInt(0)), 1e-4); + var h: Frame = .{ .t = 6.6, .in = &Instant.no_input, .pointer = .{ 0, 0 }, .arena = arena.allocator(), .gates = &gates }; + swinging(&h); + try std.testing.expectEqual(@as(f32, 0), h.get(@fromBackingInt(0))); +} + +/// A three-step talk whose first step lasts `tempo.first`: value 0 is ten +/// times the step shown plus how far into it. +fn retimed(s: *Frame, tempo: anytype) void { + const at = s.value(0); + s.wait(tempo.first); + s.pause(); + const one = s.cursor; + s.wait(1); + s.pause(); + const two = s.cursor; + s.wait(1); + const v = &s.values.items[@backingInt(at)].shown; + if (s.t >= two) v.* = 20 + s.t - two else if (s.t >= one) v.* = 10 + s.t - one else v.* = s.t; +} + +test "retiming a step above: waits plus re-anchoring keep the presenter where they were" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + var tempo: struct { first: f32 } = .{ .first = 2 }; + var d: Deck = .{}; + // Opened after 3 s of waiting, then 4: half a second into step 2. + step(&d, &.{}, 5, .{ .next = true }, retimed, .{&tempo}); + step(&d, &.{}, 5, .{ .next = true }, retimed, .{&tempo}); + step(&d, &.{}, 0.5, .{}, retimed, .{&tempo}); + try std.testing.expectApproxEqAbs(@as(f32, 20.5), try shown(&d, arena.allocator(), retimed, .{&tempo}), 1e-4); + // The first step is retimed to 5 s, and the library reloads: the same + // step, as far in, the log as it was. + tempo.first = 5; + step(&d, &.{}, 0, .{}, retimed, .{&tempo}); + try std.testing.expectApproxEqAbs(@as(f32, 13.5), d.t, 1e-4); + try std.testing.expectApproxEqAbs(@as(f32, 20.5), try shown(&d, arena.allocator(), retimed, .{&tempo}), 1e-4); + try std.testing.expect(d.log.count() == 2 and d.log.buffer[0].wait == 3 and d.log.buffer[1].wait == 4); +} + +/// Written in 2 s, a pause, then one more second. +fn written(s: *Frame) void { + const v = s.value(0); + s.play(.{v.to(1)}, .{ .seconds = 2 }); + s.pause(); + s.play(.{v.to(2)}, .{ .seconds = 1 }); +} + +test "a click during a step finishes it, and the next click opens the gate (Keynote)" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + var d: Deck = .{}; + step(&d, &.{}, 1, .{}, written, .{}); + try std.testing.expect(!d.waiting); + step(&d, &.{}, 0, .{ .next = true }, written, .{}); + try std.testing.expect(d.t == 2 and d.waiting and d.log.count() == 0); + try std.testing.expectEqual(@as(f32, 1), try shown(&d, arena.allocator(), written, .{})); + // A paused deck plays on when asked for the next step. + d.playing = false; + step(&d, &.{}, 0, .{ .next = true }, written, .{}); + try std.testing.expect(d.playing and d.log.count() == 1 and d.log.buffer[0].wait == 0); + // The last step, finished: the end. + step(&d, &.{}, 0.2, .{ .next = true }, written, .{}); + try std.testing.expectEqual(@as(f32, 3), d.t); + try std.testing.expectEqual(@as(f32, 2), try shown(&d, arena.allocator(), written, .{})); +} + +/// Three slides: the first holds one pause, the second two, the third none. +fn slides(s: *Frame) void { + const v = s.value(0); + s.slide(); + s.play(.{v.to(1)}, .{ .ease = ease.linear }); + s.pause(); + s.play(.{v.to(2)}, .{ .ease = ease.linear }); + s.slide(); + s.play(.{v.to(3)}, .{ .ease = ease.linear }); + s.pause(); + s.play(.{v.to(4)}, .{ .ease = ease.linear }); + s.pause(); + s.play(.{v.to(5)}, .{ .ease = ease.linear }); + s.slide(); + s.play(.{v.to(6)}, .{ .ease = ease.linear }); +} + +test "slides: next and previous go to each one's resting picture" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + var d: Deck = .{}; + step(&d, &.{}, 0.5, .{}, slides, .{}); + try std.testing.expect(d.slide == 1 and d.slides == 3 and !d.waiting); + // Slide 2 at rest: slide 1's step done at once, held at slide 2's first pause. + step(&d, &.{}, 0, .{ .next_slide = true }, slides, .{}); + try std.testing.expect(d.slide == 2 and d.t == 3 and d.log.count() == 1 and d.waiting); + try std.testing.expectEqual(@as(f32, 3), try shown(&d, arena.allocator(), slides, .{})); + // A step within it, then slide 3, which holds no pause: its end. + step(&d, &.{}, 0, .{ .next = true }, slides, .{}); + try std.testing.expectEqual(@as(u32, 2), d.log.count()); + step(&d, &.{}, 0.5, .{ .next_slide = true }, slides, .{}); + try std.testing.expect(d.slide == 3 and d.log.count() == 3 and d.t == 6); + try std.testing.expectEqual(@as(f32, 6), try shown(&d, arena.allocator(), slides, .{})); + // Back to slide 2 at rest (its steps undone), then slide 1, then the start. + step(&d, &.{}, 0, .{ .back_slide = true }, slides, .{}); + try std.testing.expect(d.slide == 2 and d.t == 3 and d.log.count() == 1 and d.waiting); + step(&d, &.{}, 0, .{ .back_slide = true }, slides, .{}); + try std.testing.expect(d.slide == 1 and d.t == 1 and d.log.count() == 0 and d.waiting); + try std.testing.expectEqual(@as(f32, 1), try shown(&d, arena.allocator(), slides, .{})); + step(&d, &.{}, 0, .{ .back_slide = true }, slides, .{}); + try std.testing.expect(d.t == 0 and d.log.count() == 0); + // Past the last slide: the end. + step(&d, &.{}, 0, .{ .end = true }, slides, .{}); + try std.testing.expect(d.t == 6 and d.log.count() == 3 and d.slide == 3); +} + +/// Slide 2 lies after a choice: it is laid once the choice is made. +fn choosing(s: *Frame) void { + s.slide(); + s.wait(1); + _ = s.gate(null) orelse return; + s.wait(1); + s.slide(); + s.wait(1); + s.pause(); +} + +test "the next slide past a choice not made makes it, with 0" { + var d: Deck = .{}; + step(&d, &.{}, 0, .{}, choosing, .{}); + try std.testing.expect(d.slide == 1 and d.slides == 1); + step(&d, &.{}, 0, .{ .next_slide = true }, choosing, .{}); + try std.testing.expect(d.slide == 2 and d.slides == 2 and d.t == 3 and d.waiting); + try std.testing.expect(d.log.count() == 1 and d.log.buffer[0].value == 0); +} + +/// A button laid out before the pause it waits at, taking clicks on it. +fn counting(s: *Frame, app: anytype) void { + s.wait(1); + const button: sk.Rect = .{ .x = -50, .y = -50, .w = 100, .h = 100 }; + if (mutable(app)) |a| for (s.events) |e| if (e.kind == .mouse_up and button.contains(e.x, e.y)) { + a.n += 1; + s.next = false; + }; + s.pause(); +} + +test "a click a widget takes is not the presenter's next as well" { + var app: struct { n: u32 = 0 } = .{}; + var d: Deck = .{}; + step(&d, &.{}, 2, .{}, counting, .{&app}); + try std.testing.expect(d.waiting); + // On the button, at the window's center (the scene's origin): the + // button's. The sketch made it `next`, as it makes every click. + const on: sk.Event = .{ .kind = .mouse_up, .x = width / 2, .y = height / 2, .code = 1 }; + step(&d, &.{on}, 0, .{ .next = true }, counting, .{&app}); + try std.testing.expect(app.n == 1 and d.log.count() == 0 and d.waiting); + // Elsewhere: the presenter's. + const off: sk.Event = .{ .kind = .mouse_up, .x = 100, .y = 100, .code = 1 }; + step(&d, &.{off}, 0, .{ .next = true }, counting, .{&app}); + try std.testing.expect(app.n == 1 and d.log.count() == 1); + // Drawn, the talk gets the app read-only: nothing to write through. + const app_const: *const @TypeOf(app) = &app; + try std.testing.expect(mutable(app_const) == null); + try std.testing.expect(mutable(&app).? == &app); +} + +fn fadeIn(s: *Frame, o: Obj) void { + s.play(.{o.fadeIn()}, .{ .seconds = 1 }); +} + +fn besideAndClear(s: *Frame) void { + const a = s.circle(.{ .r = 1 }); + const b = s.circle(.{ .r = 1 }); + s.beside(fadeIn, .{a}); + s.play(.{b.fadeIn()}, .{ .seconds = 1 }); + s.clear(.{ .seconds = 1 }); +} + +test "beside runs alongside the main line; clear fades out what shows" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const live = Live(besideAndClear, struct {}); + const mid = try live.shot(arena.allocator(), .{ .t = 0.5 }); + try std.testing.expectEqual(mid.poses[0], mid.poses[1]); + try std.testing.expect(mid.poses[0].visible and mid.poses[0].opacity > 0 and mid.poses[0].opacity < 1); + const out = try live.shot(arena.allocator(), .{ .t = 1.5 }); + try std.testing.expectEqual(out.poses[0], out.poses[1]); + try std.testing.expect(out.poses[0].opacity < 1); + const gone = try live.shot(arena.allocator(), .{ .t = 2 }); + try std.testing.expect(!gone.poses[0].visible and !gone.poses[1].visible and gone.duration == 2); +} + +/// Three squares, 100 units each, the middle one red; the right one is +/// taken as a part once the row shows, then each moves its own way. +fn partScene(s: anytype) void { + const row = s.svg( + \\<svg viewBox="0 0 300 100" width="300" height="100"><rect width="100" height="100"/> + \\<rect x="100" width="100" height="100" fill="red"/><rect x="200" width="100" height="100"/></svg> + , .{ .x = 10, .scale = 2 }); + s.play(.{row.fadeIn()}, .{}); + const right = s.part(row, .{ .x = 100, .w = 80, .h = 80 }); + s.play(.{ right.move(.{ .y = 50 }), row.move(.{ .x = 0 }) }, .{}); +} + +test "a part takes its shapes from its object, stands where they stood and follows it until taken" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const compiled = Scene(struct { + fn construct(s: *Builder) void { + partScene(s); + } + }.construct); + const live = Live(struct { + fn frame(s: *Frame) void { + partScene(s); + } + }.frame, struct {}); + for ([_]f32{ 0, 0.5, 1, 1.5, 2, 3 }) |t| { + const a = try compiled.shot(arena.allocator(), .{ .t = t }); + const b = try live.shot(arena.allocator(), .{ .t = t }); + try std.testing.expectEqualSlices(Pose, a.poses, b.poses); + try std.testing.expectEqual(a.objects[0].id(), b.objects[0].id()); + try std.testing.expectEqual(a.objects[1].id(), b.objects[1].id()); + } + // Fading in with the row, before it was taken; where the right square + // stood (10 + 2 * 100) once it was; then on its own. + try std.testing.expectEqual(compiled.pose(0, 0.5).opacity, compiled.pose(1, 0.5).opacity); + try std.testing.expectEqual(Pose{ .x = 210, .scale = 2, .visible = true }, compiled.pose(1, 1)); + try std.testing.expectEqual(@as(f32, 50), compiled.pose(1, 2).y); + try std.testing.expectEqual(@as(f32, 0), compiled.pose(0, 2).x); + try std.testing.expectEqual(@as(f32, 210), compiled.pose(1, 2).x); + // The row keeps two squares; the part is the third, around its centre. + const no_typst = struct { + fn find(_: []const u8) ?[]const u8 { + return null; + } + }; + const rest = try build(arena.allocator(), compiled.objects[0], no_typst); + const taken = try build(arena.allocator(), compiled.objects[1], no_typst); + try std.testing.expectEqual(@as(usize, 2), rest.shapes.len); + try std.testing.expectEqual(@as(usize, 1), taken.shapes.len); + try std.testing.expectEqual(vector.geom.Rect{ .x = -50, .y = -50, .w = 100, .h = 100 }, taken.bounds().rect()); + try std.testing.expectEqual(vector.geom.Rect{ .x = -150, .y = -50, .w = 200, .h = 100 }, rest.bounds().rect()); +} + +/// Four animations a lag of 0.5 apart, then two a whole one apart. +fn lagScene(s: anytype) void { + const a = s.circle(.{ .r = 10 }); + const b = s.circle(.{ .r = 10, .x = 50 }); + const c = s.rect(.{ .w = 20, .h = 20, .x = 100 }); + const k = s.value(0); + s.play(.{ a.fadeIn(), b.fadeIn(), camera(.{ .zoom = 2 }), k.to(1) }, .{ .seconds = 2.5, .lag = 0.5 }); + s.play(.{ b.move(.{ .x = 0 }), a.transformInto(c) }, .{ .lag = 1 }); +} + +test "a play's lag starts each animation a fraction of its length after the one before, and the last ends with the play" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const compiled = Scene(struct { + fn construct(s: *Builder) void { + lagScene(s); + } + }.construct); + const live = Live(struct { + fn frame(s: *Frame) void { + lagScene(s); + } + }.frame, struct {}); + for (0..16) |i| { + const t = @as(f32, @floatFromInt(i)) / 4; + const x = try compiled.shot(arena.allocator(), .{ .t = t }); + const y = try live.shot(arena.allocator(), .{ .t = t }); + try std.testing.expectEqualSlices(Pose, x.poses, y.poses); + try std.testing.expectEqualSlices(f32, x.values, y.values); + try std.testing.expectEqual(x.camera, y.camera); + try std.testing.expectEqual(x.duration, y.duration); + try std.testing.expectEqualSlices(f32, x.marks, y.marks); + if (x.poses[0].into != Pose.none) try std.testing.expectEqual(x.morphs[0], y.morphs[0]); + } + // 2.5 s for four, each 1 s long (2.5 / (1 + 3 * 0.5)), 0.5 s apart. + try std.testing.expectEqual(@as(f32, 3.5), compiled.duration); + try std.testing.expectApproxEqAbs(@as(f32, 0.5), compiled.pose(0, 0.5).opacity, 1e-6); + try std.testing.expectEqual(@as(f32, 0), compiled.pose(1, 0.5).opacity); + try std.testing.expectApproxEqAbs(@as(f32, 0.5), compiled.pose(1, 1).opacity, 1e-6); + try std.testing.expectEqual(@as(f32, 1), compiled.view(1).zoom); + try std.testing.expectEqual(@as(f32, 2), compiled.view(2).zoom); + try std.testing.expectEqual(@as(f32, 0), compiled.values(1.5)[0]); + try std.testing.expectEqual(@as(f32, 1), compiled.values(2.5)[0]); + // A lag of 1: one after the other, half the play each. + try std.testing.expectApproxEqAbs(@as(f32, 25), compiled.pose(1, 2.75).x, 1e-4); + try std.testing.expectEqual(@as(f32, 0), compiled.pose(0, 3).morph); + try std.testing.expectApproxEqAbs(@as(f32, 0.5), compiled.pose(0, 3.25).morph, 1e-6); +} diff --git a/src/anim/typst.zig b/src/anim/typst.zig index d9df734..05a0d4e 100644 --- a/src/anim/typst.zig +++ b/src/anim/typst.zig @@ -50,12 +50,18 @@ pub fn generate(comptime SceneFile: type, comptime sources: []const []const u8, try out.writeFile(io, .{ .sub_path = "typst.zig", .data = module }); } -/// Runs `typst compile` on `preamble ++ source` and caches the SVG. +/// Runs `typst compile` on `preamble ++ source` and caches the SVG. The +/// root is `/`, so an absolute path in a source is the file's own path +/// (`#image("/home/me/manual.pdf", page: 31)`) and a relative one is +/// in the cache. Typst only reads what a source names, and a scene's +/// sources are its author's code, built by a build that can already read +/// anything. A file named this way is not part of the cache key: changed +/// in place, it keeps its old SVG until its entry in the cache goes. fn compile(gpa: std.mem.Allocator, io: std.Io, cache: std.Io.Dir, name: []const u8, preamble: []const u8, source: []const u8) ![]const u8 { const typ = try std.fmt.allocPrint(gpa, "{s}.typ", .{name}); try cache.writeFile(io, .{ .sub_path = typ, .data = try std.mem.concat(gpa, u8, &.{ preamble, "\n", source, "\n" }) }); const result = try std.process.run(gpa, io, .{ - .argv = &.{ "typst", "compile", "--format", "svg", typ, name }, + .argv = &.{ "typst", "compile", "--root", "/", "--format", "svg", typ, name }, .cwd = .{ .dir = cache }, }); if (result.term != .exited or result.term.exited != 0) { diff --git a/src/gpu/Executor.zig b/src/gpu/Executor.zig index 460b2d5..797dcbf 100644 --- a/src/gpu/Executor.zig +++ b/src/gpu/Executor.zig @@ -503,6 +503,32 @@ pub fn download(g: *Gpu, d: @FieldType(abi.Command, "download")) !void { }; } +/// Copies `out.len` bytes of a buffer from `offset` back now, waiting for +/// the GPU to finish the work submitted before (sound that must be queued +/// this frame). +pub fn read(g: *Gpu, buffer: abi.Buffer, offset: u32, out: []u8) !void { + const source = g.storage(buffer) orelse return error.UnknownBuffer; + const size: u32 = @intCast(out.len); + if (size == 0 or @as(u64, offset) + size > source.size) return error.DownloadOutOfBounds; + const transfer = for (g.spare.items, 0..) |t, i| { + if (t.size >= size) break g.spare.swapRemove(i); + } else Transfer{ + .buffer = c.SDL_CreateGPUTransferBuffer(g.device, &.{ .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_DOWNLOAD, .size = size, .props = 0 }) orelse return error.GpuBuffer, + .size = size, + }; + defer g.spare.append(g.gpa, transfer) catch c.SDL_ReleaseGPUTransferBuffer(g.device, transfer.buffer); + const cmd = c.SDL_AcquireGPUCommandBuffer(g.device) orelse return error.GpuCommandBuffer; + const copy = c.SDL_BeginGPUCopyPass(cmd); + c.SDL_DownloadFromGPUBuffer(copy, &.{ .buffer = source.buffer, .offset = offset, .size = size }, &.{ .transfer_buffer = transfer.buffer, .offset = 0 }); + c.SDL_EndGPUCopyPass(copy); + const fence = c.SDL_SubmitGPUCommandBufferAndAcquireFence(cmd) orelse return error.GpuSubmit; + defer c.SDL_ReleaseGPUFence(g.device, fence); + if (!c.SDL_WaitForGPUFences(g.device, true, &fence, 1)) return error.GpuFence; + const mapped: [*]const u8 = @ptrCast(c.SDL_MapGPUTransferBuffer(g.device, transfer.buffer, false) orelse return error.GpuMap); + defer c.SDL_UnmapGPUTransferBuffer(g.device, transfer.buffer); + @memcpy(out, mapped[0..size]); +} + /// The downloads the GPU has finished, copied into `arena`, in the order /// they were asked for. pub fn collect(g: *Gpu, arena: std.mem.Allocator) ![]const abi.Download { diff --git a/src/host/Console.zig b/src/host/Console.zig index 0c44ea2..6fdfba4 100644 --- a/src/host/Console.zig +++ b/src/host/Console.zig @@ -1,22 +1,73 @@ //! The developer console: a line editor, a short log, and the host commands -//! (snapshots, recordings, replay, field inspection). Lines the host does not -//! know go to the sketch's `command`. +//! (marks, clips, replay, sessions, field inspection). Lines the host does +//! not know go to the sketch's `command`. const Console = @This(); const std = @import("std"); const abi = @import("abi"); const Host = @import("Host.zig"); const fields = @import("fields.zig"); const memory = @import("memory.zig"); -const timeline = @import("timeline.zig"); +const Sessions = @import("Sessions.zig"); pub const panel_height = 144; pub const Key = enum { left, right, home, end, backspace, delete, clear, tab, submit }; -const Line = struct { bytes: [118]u8 = @splat(0), len: usize = 0 }; +const Line = struct { + bytes: [width]u8 = @splat(0), + len: usize = 0, + const width = 118; +}; + +/// The console's words, a row each: what `help` prints, Tab completes, +/// `execute` runs (its switch) and `Host.runLine` asks `moves_state` of. +/// A line whose first word is none of them goes to the sketch. +pub const Verb = enum { help, get, set, reset, save, load, diff, snapshot, marks, record, recording, clips, play, stop, pause, step, seek, sessions, @"export-session", import, overlay, timing, quit, exit }; +pub const Row = struct { + args: []const u8 = "", + doc: []const u8, + /// May change State other than through `update`: a jump. + moves_state: bool = false, +}; +pub const verbs = std.enums.EnumArray(Verb, Row).init(.{ + .help = .{ .args = "[VERB]", .doc = "the verbs, or what one does; then the sketch's help" }, + .get = .{ .args = "FIELD", .doc = "a State field's value (`pos[0]`, `boids.buffer[3]`); a vector, array or struct shows every value in it, in memory order" }, + .set = .{ .args = "FIELD VALUE...", .doc = "a field to a value (enums by name or number), or an array of numbers to all its values, in memory order", .moves_state = true }, + .reset = .{ .doc = "State to its defaults, then the sketch's init; marks are kept", .moves_state = true }, + .save = .{ .args = "[MARK]", .doc = "marks the State now, MARK or the snapshot one" }, + .load = .{ .args = "[MARK|#K]", .doc = "brings a mark back (#K: the K-th in marks), migrated to today's layout", .moves_state = true }, + .diff = .{ .args = "[MARK]", .doc = "live State against a mark, leaf by leaf" }, + .snapshot = .{ .args = "MARK", .doc = "the mark save, load, diff and record use when given none" }, + .marks = .{ .doc = "the last marks" }, + .record = .{ .args = "[CLIP]", .doc = "starts a clip from the snapshot mark (saved first if new, else restored)", .moves_state = true }, + .recording = .{ .args = "CLIP", .doc = "the clip record, play, seek and step use when given none" }, + .clips = .{ .doc = "the last clips" }, + .play = .{ .args = "session S [at SECONDS] | [CLIP]", .doc = "replays a past session (paused at SECONDS), or a clip", .moves_state = true }, + .stop = .{ .doc = "ends the clip being recorded or played: live from here" }, + .pause = .{ .doc = "pauses or resumes a replay" }, + .step = .{ .args = "N", .doc = "N frames on (or back) in the replay", .moves_state = true }, + .seek = .{ .args = "start|end|MS", .doc = "to a place in the replay", .moves_state = true }, + .sessions = .{ .doc = "where this run records, and the last sessions" }, + .@"export-session" = .{ .args = "[S] FILE", .doc = "session S (this run's) with its marks and clips, to a database of its own" }, + .import = .{ .args = "FILE", .doc = "the sessions of such a file, its marks and clips as NAME@<file>" }, + .overlay = .{ .args = "memory|sound|timing", .doc = "shows or hides an overlay" }, + .timing = .{ .args = "[on|off|frame|work|reset|stats]", .doc = "the frame timing graph: shown, its metric, cleared, or its numbers" }, + .quit = .{ .doc = "ends the run" }, + .exit = .{ .doc = "ends the run" }, +}); -const host_commands = [_][]const u8{ - "help", "overlay memory", "overlay sound", "get", "set", "reset", "save", "load", "snapshot", "recording", - "record", "stop", "play", "pause", "step", "seek start", "seek end", "diff", "quit", "exit", - "overlay timing", "timing on", "timing off", "timing frame", "timing work", "timing reset", "timing stats", +/// What Tab completes from: every verb, and with each of the words its +/// first argument may be (`seek start`). +const completions = blk: { + @setEvalBranchQuota(100_000); + var list: []const []const u8 = &.{}; + for (std.enums.values(Verb)) |v| { + list = list ++ .{@tagName(v)}; + const args = verbs.get(v).args; + var words = std.mem.tokenizeScalar(u8, std.mem.trim(u8, args[0 .. std.mem.indexOfScalar(u8, args, ' ') orelse args.len], "[]"), '|'); + while (words.next()) |word| if (std.ascii.isLower(word[0])) { + list = list ++ .{@tagName(v) ++ " " ++ word}; + }; + } + break :blk list; }; visible: bool = false, @@ -24,11 +75,34 @@ buffer: [96]u8 = @splat(0), len: usize = 0, cursor: usize = 0, lines: [5]Line = @splat(.{}), -snapshot: usize = 1, -recording: usize = 0, +/// The mark `save`, `load`, `diff` and `record` use when given none. +snapshot: Name = .of("1"), +/// The clip `record`, `play`, `seek` and `step` use when given none. +recording: Name = .of("0"), overlay_memory: bool = false, overlay_sound: bool = false, +pub const Name = struct { + bytes: [Sessions.max_name]u8 = undefined, + len: usize = 0, + + pub fn of(text_: []const u8) Name { + var n: Name = .{ .len = text_.len }; + @memcpy(n.bytes[0..text_.len], text_); + return n; + } + pub fn get(n: *const Name) []const u8 { + return n.bytes[0..n.len]; + } +}; + +/// A mark or clip name: a word of at most `Sessions.max_name` bytes. +fn nameOr(arg: ?[]const u8, default: *const Name) ![]const u8 { + const n = arg orelse return default.get(); + if (n.len > Sessions.max_name) return error.NameTooLong; + return n; +} + pub fn text(self: *const Console) []const u8 { return self.buffer[0..self.len]; } @@ -86,7 +160,7 @@ fn complete(self: *Console, extra: []const []const u8) void { var matches: [256]u8 = undefined; var used: usize = 0; var count: usize = 0; - for ([_][]const []const u8{ &host_commands, extra }) |list| for (list) |candidate| { + for ([_][]const []const u8{ completions, extra }) |list| for (list) |candidate| { if (!std.mem.startsWith(u8, candidate, self.text())) continue; if (first) |previous| { var i: usize = 0; @@ -132,114 +206,199 @@ pub fn execute(self: *Console, host: *Host, line: []const u8, now: u64) ![]const const command = words.next() orelse return &.{}; const arg = words.next(); const rest = words.rest(); - - if (eq(command, "help")) { - self.log("save|load [1..7] snapshot N | record|play [0..15] recording N | stop | pause | step N (frames) | seek start|end|<ms>"); - self.log("diff [N] | reset | get <field> | set <field> <value> | overlay memory|sound | quit"); - self.log("timing [on|off|frame|work|reset|stats] | overlay timing"); - if (host.forward(self, line, now) == .unknown) self.log("Backtick hides the console. Tab completes."); - return &.{}; - } - if (eq(command, "overlay")) { - const name = arg orelse return error.ExpectedOverlay; - if (rest.len != 0) return error.UnexpectedArgument; - const flag = if (eq(name, "memory")) &self.overlay_memory else if (eq(name, "sound")) &self.overlay_sound else if (eq(name, "timing")) &host.timing.visible else return error.UnknownOverlay; - flag.* = !flag.*; - host.timing.dirty = true; - self.print("{s} overlay: {s}", .{ name, if (flag.*) "on" else "off" }); - } else if (eq(command, "timing")) { - if (rest.len != 0) return error.UnexpectedArgument; - if (eq(arg orelse "", "stats")) { - self.print("Timing: last {d}/240 frames; frame includes present, work excludes present (wall clock).", .{host.timing.count}); - inline for (.{ .frame, .work }) |metric| { - const s = host.timing.stats(metric); - self.print("{s}: avg {d:.3} ms | p90 {d:.3} ms | p99 {d:.3} ms | max {d:.3} ms", .{ @tagName(metric), s.mean, s.p90, s.p99, s.max }); - } - } else { - try host.timing.command(arg); - self.print("Timing overlay: {s}, graph: {t}, samples: {d}", .{ if (host.timing.visible) "on" else "off", host.timing.metric, host.timing.count }); - } - } else if (eq(command, "get")) { - const path = arg orelse return error.ExpectedField; - var buf: [160]u8 = undefined; - var w: std.Io.Writer = .fixed(&buf); - fields.formatPath(host.state.layout, host.live(), path, &w) catch |err| switch (err) { - error.UnknownField => return error.UnknownField, - error.WriteFailed => {}, // shown cut off - }; - self.print("{s} = {s}", .{ path, w.buffered() }); - } else if (eq(command, "set")) { - const path = arg orelse return error.ExpectedField; - const leaf = host.state.layout.find(path) orelse return error.UnknownField; - if (rest.len == 0) return error.ExpectedValue; - h.stop(now); - try fields.set(leaf, host.live(), std.mem.trim(u8, rest, " ")); - self.print("{s} = {s}", .{ path, std.mem.trim(u8, rest, " ") }); - } else if (eq(command, "quit") or eq(command, "exit")) { - h.stop(now); - host.quit = true; - } else if (eq(command, "reset")) { - h.stop(now); - host.resetState(); - self.log("Live state reset. Snapshots are kept."); - } else if (eq(command, "snapshot")) { - self.snapshot = try slot(arg orelse return error.ExpectedSlot, 1, memory.slot_count - 1); - } else if (eq(command, "recording")) { - self.recording = try slot(arg orelse return error.ExpectedSlot, 0, timeline.recording_count - 1); - } else if (eq(command, "save") or eq(command, "load")) { - const index = if (arg) |a| try slot(a, 1, memory.slot_count - 1) else self.snapshot; - if (eq(command, "load") and !h.bank.hasSnapshot(index)) return error.EmptySnapshot; - h.stop(now); - if (eq(command, "save")) { - h.bank.save(index); - self.print("Saved snapshot {d}. Recordings from its old contents are invalidated.", .{index}); - } else { - try h.restore(index); - self.print("Loaded snapshot {d}.", .{index}); - } - } else if (eq(command, "record") or eq(command, "play")) { - const index = if (arg) |a| try slot(a, 0, timeline.recording_count - 1) else self.recording; - if (eq(command, "play")) _ = try h.bank.get(index); - h.stop(now); - if (eq(command, "record")) try h.startRecording(index, self.snapshot, now, host.build) else try h.play(index, now); - self.recording = index; - self.print("{s} recording {d} from snapshot {d}.", .{ if (eq(command, "record")) "Started" else "Playing", index, h.bank.recording(index).snapshot }); - if (eq(command, "play")) self.warnBuild(host, h.bank.recording(index)); - } else if (eq(command, "stop")) { - h.stop(now); - } else if (eq(command, "pause")) { - if (h.mode != .playing and h.mode != .paused) return error.NotReplaying; - h.pause(now); - } else if (eq(command, "step") or eq(command, "seek")) { - const value = arg orelse return error.ExpectedPosition; - _ = try h.bank.get(if (h.mode == .live or h.mode == .recording) self.recording else h.selected); - if (h.mode == .recording) h.stop(now); - if (h.mode == .live) try h.play(self.recording, now); - const r = try h.bank.get(h.selected); - if (h.mode == .playing and h.cursor == 0) self.warnBuild(host, r); - if (eq(command, "step")) return h.step(std.fmt.parseInt(i64, value, 10) catch return error.InvalidPosition); - if (eq(value, "start")) return h.seekCount(0); - if (eq(value, "end")) return h.seekCount(r.count); - const ms = std.fmt.parseInt(u64, value, 10) catch return error.InvalidPosition; - return h.seekTime(ms *| std.time.ns_per_ms); - } else if (eq(command, "diff")) { - const index = if (arg) |a| try slot(a, 1, memory.slot_count - 1) else self.snapshot; - if (!h.bank.hasSnapshot(index)) return error.EmptySnapshot; - const diff = h.bank.compare(0, index); - if (diff.first) |first| { - var buf: [96]u8 = undefined; - var w: std.Io.Writer = .fixed(&buf); - first.leaf.name(first.offset, &w) catch {}; - self.print("Live vs snapshot {d}: {d} differing values, first {s}", .{ index, diff.count, w.buffered() }); - } else self.print("Live vs snapshot {d}: same", .{index}); - } else { + const verb = std.meta.stringToEnum(Verb, command) orelse { // Sketch commands edit state outside the recorded input. - h.stop(now); + try stop(host); switch (host.forward(self, line, now)) { .unknown => return error.UnknownCommand, .failed => return error.CommandFailed, .done => {}, } + return &.{}; + }; + switch (verb) { + .help => { + if (std.meta.stringToEnum(Verb, arg orelse "")) |v| { + self.print("{t} {s}: {s}", .{ v, verbs.get(v).args, verbs.get(v).doc }); + return &.{}; + } + var buf: [Line.width + 3]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + // Names only, so the sketch's help fits the log below them. + w.writeAll("help VERB says more:") catch {}; + for (std.enums.values(Verb)) |v| { + if (w.end + @tagName(v).len + 1 > Line.width) { + self.log(w.buffered()); + w.end = 0; + } + w.print(" {t}", .{v}) catch {}; + } + self.log(w.buffered()); + if (host.forward(self, line, now) == .unknown) self.log("Backtick hides the console. Tab completes."); + }, + .overlay => { + const name = arg orelse return error.ExpectedOverlay; + if (rest.len != 0) return error.UnexpectedArgument; + const flag = if (eq(name, "memory")) &self.overlay_memory else if (eq(name, "sound")) &self.overlay_sound else if (eq(name, "timing")) &host.timing.visible else return error.UnknownOverlay; + flag.* = !flag.*; + host.timing.dirty = true; + self.print("{s} overlay: {s}", .{ name, if (flag.*) "on" else "off" }); + }, + .timing => { + if (rest.len != 0) return error.UnexpectedArgument; + if (eq(arg orelse "", "stats")) { + self.print("Timing: last {d}/240 frames; frame includes present, work excludes present (wall clock).", .{host.timing.count}); + inline for (.{ .frame, .work }) |metric| { + const s = host.timing.stats(metric); + self.print("{s}: avg {d:.3} ms | p90 {d:.3} ms | p99 {d:.3} ms | max {d:.3} ms", .{ @tagName(metric), s.mean, s.p90, s.p99, s.max }); + } + } else { + try host.timing.command(arg); + self.print("Timing overlay: {s}, graph: {t}, samples: {d}", .{ if (host.timing.visible) "on" else "off", host.timing.metric, host.timing.count }); + } + }, + .get => { + const path = arg orelse return error.ExpectedField; + var buf: [160]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + fields.formatPath(host.state.layout, host.live(), path, &w) catch |err| switch (err) { + error.UnknownField => return error.UnknownField, + error.WriteFailed => {}, // shown cut off + }; + self.print("{s} = {s}", .{ path, w.buffered() }); + }, + .set => { + const path = arg orelse return error.ExpectedField; + const leaf = host.state.layout.find(path) orelse return error.UnknownField; + if (rest.len == 0) return error.ExpectedValue; + try stop(host); + if (leaf.whole()) try fields.setRow(host.state.layout, host.live(), path, rest) else try fields.set(leaf, host.live(), std.mem.trim(u8, rest, " ")); + self.print("{s} = {s}", .{ path, std.mem.trim(u8, rest, " ") }); + }, + .quit, .exit => { + try stop(host); + host.quit = true; + }, + .reset => { + try stop(host); + host.resetState(); + self.log("Live state reset. Snapshots are kept."); + }, + .snapshot, .recording => { + const n = try nameOr(arg orelse return error.ExpectedName, &self.snapshot); + (if (verb == .snapshot) &self.snapshot else &self.recording).* = .of(n); + }, + .save => { + const n = try nameOr(arg, &self.snapshot); + try stop(host); + _ = try host.sessions.mark(n, .mark, host.live()); + self.print("Saved snapshot {s}.", .{n}); + }, + .load => { + const n = try nameOr(arg, &self.snapshot); + const key = try loadMark(host, n); + defer key.free(host.gpa); + try stop(host); + try h.restore(key); + self.print("Loaded snapshot {s}.", .{n}); + }, + .record => { + const n = try nameOr(arg, &self.recording); + const from = self.snapshot.get(); + try stop(host); + // An unused mark captures the current state; an existing one is + // restored, so several clips can branch from exactly those bytes. + const k = if (try host.sessions.findMark(from) == null) try host.sessions.mark(from, .mark, host.live()) else blk: { + const key = try loadMark(host, from); + defer key.free(host.gpa); + try h.restore(key); + break :blk try host.sessions.keyframe(.jump, host.live()); + }; + // The input held now is restored first in the clip (Host.restoredInput). + h.restored = true; + try host.sessions.startClip(n, k); + h.startRecording(); + self.recording = .of(n); + self.print("Started recording {s} from snapshot {s}.", .{ n, from }); + }, + .play => if (arg != null and eq(arg.?, "session")) { + var more = std.mem.tokenizeAny(u8, rest, " \t"); + const index = std.fmt.parseInt(u64, more.next() orelse return error.ExpectedSession, 10) catch return error.InvalidSession; + var at: ?u64 = null; + if (more.next()) |word| { + if (!eq(word, "at")) return error.UnexpectedArgument; + const seconds = std.fmt.parseFloat(f64, more.next() orelse return error.ExpectedPosition) catch return error.InvalidPosition; + at = @intFromFloat(@max(0, seconds) * std.time.ns_per_s); + } + try stop(host); + return self.playSession(host, index, at, now); + } else { + const n = try nameOr(arg, &self.recording); + try stop(host); + try loadClip(host, n); + try h.play(now); + self.recording = .of(n); + self.print("Playing recording {s}.", .{n}); + self.warnBuild(host); + }, + .stop => { + try stop(host); + }, + .pause => { + if (h.mode != .playing and h.mode != .paused) return error.NotReplaying; + h.pause(now); + }, + .step, .seek => { + const value = arg orelse return error.ExpectedPosition; + if (h.mode == .live or h.mode == .recording) { + try stop(host); + try loadClip(host, self.recording.get()); + try h.play(now); + self.warnBuild(host); + } + if (verb == .step) return h.step(std.fmt.parseInt(i64, value, 10) catch return error.InvalidPosition); + if (eq(value, "start")) return h.seekCount(0); + if (eq(value, "end")) return h.seekCount(h.events.items.len); + const ms = std.fmt.parseInt(u64, value, 10) catch return error.InvalidPosition; + return h.seekTime(ms *| std.time.ns_per_ms); + }, + .diff => { + const n = try nameOr(arg, &self.snapshot); + var arena: std.heap.ArenaAllocator = .init(host.gpa); + defer arena.deinit(); + const saved = try markState(host, arena.allocator(), n); + const diff = memory.compareKept(saved.layout, host.state.layout, host.live(), saved.bytes); + if (diff.first) |first| { + var buf: [96]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + first.leaf.name(first.offset, &w) catch {}; + self.print("Live vs snapshot {s}: {d} differing values, first {s}", .{ n, diff.count, w.buffered() }); + } else self.print("Live vs snapshot {s}: same", .{n}); + }, + .sessions => { + if (arg != null) return error.UnexpectedArgument; + try self.listSessions(host); + }, + .@"export-session" => { + const s = &host.sessions; + const first = arg orelse return error.ExpectedFile; + const index = if (rest.len == 0) s.session else std.fmt.parseInt(u64, first, 10) catch return error.InvalidSession; + const path = if (rest.len == 0) first else std.mem.trim(u8, rest, " \t"); + try s.exportSession(index, path); + self.print("Exported session {d} to {s}.", .{ index, path }); + }, + .import => { + const path = arg orelse return error.ExpectedFile; + if (rest.len != 0) return error.UnexpectedArgument; + const s = &host.sessions; + const first = try s.import(path); + const n = try s.count(.sessions); + self.print("Imported {s} as session {d}..{d}; marks and clips are NAME@{s}.", .{ path, first, n - 1, std.fs.path.basename(path) }); + }, + .marks, .clips => { + if (arg != null) return error.UnexpectedArgument; + try self.listNamed(host, verb == .marks); + }, } return &.{}; } @@ -251,8 +410,12 @@ pub fn draw(self: *const Console, host: *Host, out: *std.ArrayList(abi.Command), const width: f32 = @floatFromInt(host.canvas[0]); const h = &host.timeline; try out.append(arena, .{ .rect = .{ .dst = .{ .x = 0, .y = top, .w = width, .h = panel_height }, .color = .{ .r = 24, .g = 28, .b = 28 } } }); - const status = try std.fmt.allocPrint(arena, "{s} | {t} | snapshot {d} | recording {d} (active {d}) | event {d} | {d}ms", .{ - host.name, h.mode, self.snapshot, self.recording, h.selected, h.cursor, h.position / std.time.ns_per_ms, + const s = &host.sessions; + const playing = h.mode == .playing or h.mode == .paused; + const frame = if (playing) (if (h.key) |k| k.frame else 0) + h.fed else s.frames; + const at = (if (playing) h.position else s.last_time -| s.first_time) / std.time.ns_per_s; + const status = try std.fmt.allocPrint(arena, "{s} | {t} | session {d} frame {d} ({d}:{d:0>2}) | mark {s} | clip {s} | rec {t}", .{ + host.name, h.mode, if (playing) h.session orelse s.session else s.session, frame, at / 60, at % 60, self.snapshot.get(), self.recording.get(), s.mode(), }); try out.append(arena, .{ .text = .{ .x = 12, .y = top + 8, .scale = 1, .color = hint, .bytes = status } }); for (&self.lines, 0..) |*line, i| { @@ -262,19 +425,134 @@ pub fn draw(self: *const Console, host: *Host, out: *std.ArrayList(abi.Command), try out.append(arena, .{ .rect = .{ .dst = .{ .x = @floatFromInt(28 + self.cursor * 8), .y = top + 120, .w = 1, .h = 12 }, .color = hint } }); } -/// A replay of a recording made by other code may diverge: say so. -fn warnBuild(self: *Console, host: *const Host, r: *const timeline.Recording) void { - if (r.build() != 0 and host.build != 0 and r.build() != host.build) self.log("Warning: recorded by another build of the sketch; the replay may differ."); +/// Where this run records, then the last sessions: index, start, frames, +/// stretches (loads), and how it ended. +fn listSessions(self: *Console, host: *Host) !void { + const s = &host.sessions; + switch (s.mode()) { + .file => self.print("recording to {s}", .{s.path}), + .memory => self.log("recording in memory (scripted run)"), + .off => return self.log("not recording (an export)"), + } + const n = try s.count(.sessions); + var i = n -| 4; + while (i < n) : (i += 1) { + const m = try s.summary(i); + const secs = std.time.epoch.EpochSeconds{ .secs = m.started / std.time.ns_per_s }; + const day = secs.getEpochDay().calculateYearDay(); + const md = day.calculateMonthDay(); + const ds = secs.getDaySeconds(); + var end_buf: [32]u8 = undefined; + const end = if (i == s.session) "(this run)" else if (m.ended == 0) "(crashed)" else blk: { + const d = (m.ended -| m.started) / std.time.ns_per_s; + break :blk std.fmt.bufPrint(&end_buf, "{d}:{d:0>2}", .{ d / 60, d % 60 }) catch ""; + }; + self.print("{d}: {d:0>4}-{d:0>2}-{d:0>2} {d:0>2}:{d:0>2} builds {d} frames {d} {s} {s}", .{ i, day.year, md.month.numeric(), md.day_index + 1, ds.getHoursIntoDay(), ds.getMinutesIntoHour(), m.stretches, m.frames, end, m.from() }); + } } -fn eq(a: []const u8, b: []const u8) bool { - return std.mem.eql(u8, a, b); +/// Ends a clip being recorded or played: live from here. +fn stop(host: *Host) !void { + if (host.timeline.mode == .recording) try host.sessions.stopClip(); + host.timeline.stop(); } -fn slot(value: []const u8, min: usize, max: usize) !usize { - const index = std.fmt.parseInt(usize, value, 10) catch return error.InvalidSlot; - if (index < min or index > max) return error.InvalidSlot; - return index; +/// The keyframe of the newest mark `n`, or of mark number K for "#K". +pub fn loadMark(host: *Host, n: []const u8) !Sessions.Loaded { + const s = &host.sessions; + const found = if (n.len > 1 and n[0] == '#') + try s.markAt(std.fmt.parseInt(u64, n[1..], 10) catch return error.InvalidName) + else + try s.findMark(n) orelse return error.EmptySnapshot; + return s.load(found.session, found.key); +} + +/// Mark `n`'s State in today's layout (`arena`'s), and the layout it was +/// taken in: compare them over the leaves migration kept (`memory.compareKept`). +pub fn markState(host: *Host, arena: std.mem.Allocator, n: []const u8) !struct { bytes: []u8, layout: memory.Layout } { + const key = try loadMark(host, n); + defer key.free(host.gpa); + const bytes = try arena.alignedAlloc(u8, .fromByteUnits(memory.page), host.state.layout.size); + const layout = try memory.restore(arena, key.layout, key.state, host.state.layout, bytes, host.timeline.defaults); + return .{ .bytes = bytes, .layout = layout }; +} + +/// Makes clip `n` the one the timeline plays: its keyframe and frames. +fn loadClip(host: *Host, n: []const u8) !void { + const s = &host.sessions; + const clip = try s.findClip(n) orelse return error.EmptyRecording; + const key = try s.load(clip.session, clip.key); + errdefer key.free(host.gpa); + var events: std.ArrayList(abi.Event) = .empty; + errdefer events.deinit(host.gpa); + // A clip a crash left open ends where its session does. + const end = if (clip.end != 0) clip.end else (try s.summary(clip.session)).frames; + try s.events(clip.session, key.batch, clip.start, end, &events); + host.timeline.load(key, events); +} + +/// Plays session `index` from its start, or paused `at` nanoseconds into +/// it: from the newest keyframe before then, replayed up to it. +fn playSession(self: *Console, host: *Host, index: u64, at: ?u64, now: u64) ![]const abi.Event { + const s = &host.sessions; + const h = &host.timeline; + if (index == s.session) try s.commit(.none); + const sum = try s.summary(index); + if (sum.keys == 0) return error.EmptyRecording; + const t0 = (try s.keyAt(index, 0)).time; + const k = if (at) |t| try s.keyBefore(index, .time, t0 + t) orelse 0 else 0; + const key = try s.load(index, k); + errdefer key.free(host.gpa); + var events: std.ArrayList(abi.Event) = .empty; + errdefer events.deinit(host.gpa); + try s.events(index, key.batch, key.frame, sum.frames, &events); + var checks: @TypeOf(h.checks) = .empty; + errdefer checks.deinit(host.gpa); + for (k + 1..sum.keys) |j| { + const later = try s.keyAt(index, j); + try checks.append(host.gpa, .{ .frame = later.frame, .key = j, .observed = switch (later.why) { + .periodic, .mark, .before_reload, .exit => true, + else => false, + } }); + } + h.load(key, events); + h.session = index; + h.checks = checks; + try h.play(now); + self.print("Playing session {d} from frame {d}.", .{ index, key.frame }); + if (key.build != host.build or !eq(key.source, host.source)) self.print("session {d} frame {d} was built from {s}; replaying with {s}", .{ index, key.frame, key.source, host.source }); + if (at) |t| return h.seekTime((t0 + t) -| h.base); + return &.{}; +} + +/// A replay of a clip made by other code may diverge: say so. +fn warnBuild(self: *Console, host: *const Host) void { + const key = host.timeline.key orelse return; + if (key.build != 0 and host.build != 0 and key.build != host.build) self.log("Warning: recorded by another build of the sketch; the replay may differ."); +} + +/// The last marks or clips: index, name, session and frame. +fn listNamed(self: *Console, host: *Host, marks: bool) !void { + const s = &host.sessions; + const n = try s.count(if (marks) .marks else .clips); + if (n == 0) return self.log(if (marks) "No marks: save NAME makes one." else "No clips: record NAME makes one."); + var i = n -| 5; + while (i < n) : (i += 1) { + const e = if (marks) try s.markAt(i) else try s.clipAt(i); + const label = e.name(); + if (marks) { + // An older mark of a name may have gone with history. + const key = s.keyAt(e.session, e.key) catch { + self.print("#{d} {s}: session {d}, dropped", .{ i, label, e.session }); + continue; + }; + self.print("#{d} {s}: session {d} frame {d}", .{ i, label, e.session, key.frame }); + } else self.print("#{d} {s}: session {d} frames {d}..{d}", .{ i, label, e.session, e.start, e.end }); + } +} + +fn eq(a: []const u8, b: []const u8) bool { + return std.mem.eql(u8, a, b); } test "line editing, completion and submission" { diff --git a/src/host/Host.zig b/src/host/Host.zig index 035a004..0a8eeee 100644 --- a/src/host/Host.zig +++ b/src/host/Host.zig @@ -9,7 +9,6 @@ const abi = @import("abi"); const memory = @import("memory.zig"); const playback = @import("timeline.zig"); const Timeline = playback.Timeline; -const mapRecordings = playback.mapRecordings; const gfx = @import("gfx.zig"); const sound = @import("audio.zig"); const Gpu = @import("gpu"); @@ -20,6 +19,7 @@ const Presentation = @import("Presentation.zig"); const timing_marker = @import("timing_marker.zig"); const Control = @import("control.zig").Control; const Library = @import("library.zig").Library; +const Sessions = @import("Sessions.zig"); const Watch = @import("library.zig").Watch; pub const Options = struct { @@ -27,11 +27,17 @@ pub const Options = struct { library: ?[]const u8 = null, /// Local 9P control socket, opt-in. ninep: ?[]const u8 = null, - /// State file; recordings go next to it with an `.inputs` suffix. - state: []const u8 = "sketch.state", + /// The save, a sessions database: `<stem>.xitdb`, for a path + /// `<stem>.xitdb`, `<stem>.state` (where a state file from before is + /// imported from) or `<stem>`. Empty: `$XDG_DATA_HOME/<name>/<name>.xitdb` + /// (`~/.local/share` without it), for a shipped game. + state: []const u8 = "", + /// Playing a script: from fresh state, sessions go to memory only. + script: bool = false, /// Offscreen video, silent audio, no vsync: for scripts and CI. headless: bool = false, - /// Forget the state file's contents: scripts start from a known place. + /// Start from State's defaults, not the save's present: scripts start + /// from a known place. fresh: bool = false, /// Time every GPU command alone and print the times at exit. profile_gpu: bool = false, @@ -66,16 +72,16 @@ images: gfx.Images, /// Plays the 2D commands: targets, blend, antialiased shapes. painter: gfx.Painter, audio: sound.Audio, -state: memory.StateFile, +state: memory.State, session: memory.Session, /// A failed resource setup disables app callbacks while keeping host controls alive. session_ready: bool = false, -store: memory.StoreFile, /// Images and buffers the sketch made (`newImage`, `decodeImage`, /// `newBuffer`): Session holds their handles, so they go when it resets. made: struct { images: std.ArrayList(abi.Image) = .empty, buffers: std.ArrayList(abi.Buffer) = .empty } = .{}, -recordings: []align(memory.page) u8, timeline: Timeline, +/// This run's session and the ones before it (Sessions.zig). +sessions: Sessions, console: Console = .{}, timing: Timing = .{}, timing_atlas: overlay.TimingAtlas = .{}, @@ -83,12 +89,20 @@ sketch: abi.Sketch, library: ?Library = null, watch: ?Watch = null, reloads: usize = 0, -/// Identifies the running build of the sketch (a hash of its library or -/// executable file): recordings carry it, and `play` warns on a mismatch. +/// Identifies the running build of the sketch (its library or executable +/// file's inode, size and modification time): sessions' stretches carry it, +/// and `play` warns on a mismatch. build: u64 = 0, +/// The save's path when the host chose it (`Options.state`), `gpa`'s. +state_path: []const u8 = "", +/// `Options.state` without `.xitdb` or `.state`: the save is +/// `<stem>.xitdb`, the sketch's own files `<stem>.<name>`. +stem: []const u8 = "", /// Copies of the sketch's info strings, replaced on every load. info_arena: std.heap.ArenaAllocator, name: []const u8 = "", +/// The sketch's `Info.source`, for the session's stretches. +source: []const u8 = "", completions: []const []const u8 = &.{}, /// Frame lifetime: sketch scratch and this frame's commands. frame_arena: std.heap.ArenaAllocator, @@ -97,6 +111,11 @@ commands: std.ArrayList(abi.Command) = .empty, pending: std.ArrayList(abi.Event) = .empty, input: abi.Input = .{}, files: std.StringHashMapUnmanaged([]align(memory.page) const u8) = .empty, +/// Mappings of files `writeFile` replaced: the sketch may still hold them. +retired: std.ArrayList([]align(memory.page) const u8) = .empty, +/// The paths `appendFile` wrote, each once, 0-terminated: the sketch keeps +/// them. +written: std.StringHashMapUnmanaged(void) = .empty, canvas: [2]u32 = .{ 0, 0 }, cursor: abi.Cursor = .arrow, quit: bool = false, @@ -114,7 +133,8 @@ exported: u64 = 0, dialog: Dialog = .{}, control: ?*Control = null, -pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, options: Options, linked: ?abi.Sketch) !void { +pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, given: Options, linked: ?abi.Sketch) !void { + var options = given; if (options.headless) { // Overriding: a plain hint loses to the environment, and a user's // SDL_VIDEO_DRIVER=wayland would open real windows during tests. @@ -128,7 +148,7 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std var library: ?Library = null; const sketch = linked orelse blk: { const path = options.library orelse return error.NoSketch; - library = try Library.openCopy(io, path, scratchDir(environ), 0); + library = try Library.openFresh(io, path, scratchDir(environ), 0); break :blk library.?.sketch; }; errdefer if (library) |*l| l.close(); @@ -158,17 +178,16 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std // Colors carry alpha: fills blend, as they do on the web. _ = c.SDL_SetRenderDrawBlendMode(renderer, c.SDL_BLENDMODE_BLEND); - var state = try memory.StateFile.open(gpa, options.state); - errdefer state.close(); - var inputs_buf: [std.fs.max_path_bytes]u8 = undefined; - const recordings = try mapRecordings(try std.mem.print(&inputs_buf, "{s}.inputs", .{options.state})); - errdefer std.posix.munmap(recordings); - var store_buf: [std.fs.max_path_bytes]u8 = undefined; - var store = memory.StoreFile.open(gpa, try std.mem.print(&store_buf, "{s}.store", .{options.state}), options.fresh) catch |err| { - if (err == error.StoreInUse) std.log.err("{s}.store is open in another process", .{options.state}); - return err; + var data_buf: [std.fs.max_path_bytes]u8 = undefined; + const state_path = if (given.state.len > 0) "" else blk: { + const data = environ.get("XDG_DATA_HOME") orelse try std.fmt.bufPrint(&data_buf, "{s}/.local/share", .{environ.get("HOME") orelse "."}); + const path = try std.fmt.allocPrint(gpa, "{s}/{s}/{s}.xitdb", .{ data, info.name, info.name }); + errdefer gpa.free(path); + try std.Io.Dir.cwd().createDirPath(io, std.fs.path.dirname(path).?); + break :blk path; }; - errdefer store.close(); + errdefer gpa.free(state_path); + if (state_path.len > 0) options.state = state_path; self.* = .{ .gpa = gpa, @@ -181,37 +200,37 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std .images = .{ .gpa = gpa, .renderer = renderer.? }, .painter = .{ .renderer = renderer.?, .images = undefined, .smooth = gpu != null }, .audio = .{ .gpa = gpa }, - .state = state, + .state = .init(gpa), .session = .init(gpa), - .store = store, - .recordings = recordings, .timeline = undefined, + .sessions = .{ .gpa = gpa, .io = io }, .sketch = sketch, .library = library, + .state_path = state_path, + .stem = stemOf(options.state), .info_arena = .init(gpa), .frame_arena = .init(gpa), .input = .{ .exporting = options.export_to != null }, }; - self.timeline = .{ .bank = .{ .state = &self.state, .inputs = recordings } }; + self.timeline = .{ .gpa = gpa, .state = &self.state, .defaults = sketch.defaults }; self.painter.images = &self.images; if (gpu) |device| self.passes = .init(gpa, device); if (options.profile_gpu) if (self.passes) |*g| { g.profile = .init(gpa); }; - self.audio.open() catch |err| std.log.warn("audio unavailable: {t}", .{err}); + self.audio.open(info.audio_pull) catch |err| std.log.warn("audio unavailable: {t}", .{err}); if (options.library) |path| if (linked == null) { self.watch = Watch.init(path) catch null; }; const size = options.size orelse [2]u32{ info.width, info.height }; self.setCanvas(size[0], size[1]); _ = c.SDL_StartTextInput(self.window); - self.build = fileHash(options.library orelse "/proc/self/exe"); + self.build = fileId(io, options.library orelse "/proc/self/exe"); try self.adopt(sketch); - if (options.fresh) { - self.state.header().used = 0; - @memset(self.recordings, 0); - self.resetState(); - } + self.openSessions(info.record); + // Before --fresh, which never touches the save. + self.openPresent(); + if (options.fresh) self.resetState(); if (!options.headless and options.export_to == null) { self.presentation = Presentation.init(gpa, self.window) catch null; if (options.timing_marker) self.print("presentation tracing: {s}", .{if (self.presentation) |p| p.status else "disabled_or_allocation_failed"}); @@ -219,6 +238,7 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std } pub fn deinit(self: *Host) void { + self.sessions.close(self.live(), wallClock(self.io)); if (self.control) |control| control.deinit(); self.dialog.deinit(); if (self.watch) |w| w.deinit(); @@ -238,15 +258,25 @@ pub fn deinit(self: *Host) void { std.posix.munmap(entry.value_ptr.*); } self.files.deinit(self.gpa); - std.posix.munmap(self.recordings); + for (self.retired.items) |bytes| std.posix.munmap(bytes); + self.retired.deinit(self.gpa); + // A scripted run from fresh state, or an export, leaves no files. + const private = (self.options.script or self.options.export_to != null) and self.options.fresh; + var written = self.written.keyIterator(); + while (written.next()) |path| { + if (private) std.Io.Dir.cwd().deleteFile(self.io, path.*) catch {}; + self.gpa.free(path.ptr[0 .. path.len + 1]); + } + self.written.deinit(self.gpa); + self.timeline.deinit(); self.session.deinit(self.gpa); - self.store.close(); self.made.images.deinit(self.gpa); self.made.buffers.deinit(self.gpa); - self.state.close(); + self.state.deinit(self.gpa); self.pending.deinit(self.gpa); self.frame_arena.deinit(); self.info_arena.deinit(); + self.gpa.free(self.state_path); if (self.library) |*l| l.close(); c.SDL_Quit(); } @@ -254,7 +284,15 @@ pub fn deinit(self: *Host) void { /// The interactive loop. An export runs it on a clock of its own, frame k /// at k/fps seconds (from 1 s, as scripts do), whatever the wall clock says. pub fn run(self: *Host) !void { - if (self.options.ninep) |path| self.control = try Control.init(self.gpa, path); + // A run a person watches posts its tree as sketchbook/<name>; --9p + // names another, or a socket path. + const o = self.options; + const ninep = o.ninep orelse if (o.headless or o.script or o.export_to != null) null else self.name; + if (ninep) |where| self.control = Control.open(self.gpa, self.environ, where) catch |err| blk: { + if (o.ninep != null) return err; + self.print("not posted as sketchbook/{s}: {t}", .{ where, err }); + break :blk null; + }; while (!self.quit) { if (self.control) |control| control.poll(self); try self.poll(); @@ -282,7 +320,7 @@ pub fn run(self: *Host) !void { frameTime(wall, if (self.presentation) |p| p.sampleNs(wall) else wall, self.last_now, self.timeline.mode, self.pending.items); try self.frame(now); } - self.timeline.stop(c.SDL_GetTicksNS()); + self.timeline.stop(); } // Live animation uses the display clock, but a tick must not predate its input. @@ -307,7 +345,7 @@ test "timing clock drives ordinary ticks without moving input or replay time" { } pub fn live(self: *Host) []u8 { - return self.state.slot(0); + return self.state.live(); } /// One frame: reload if a build replaced the library, feed input through @@ -325,8 +363,11 @@ pub fn frame(self: *Host, now: u64) !void { self.last_now = now; const h = &self.timeline; switch (h.mode) { - .playing => self.update(h.tick(now)), - .paused => {}, + .playing => { + self.sessions.away = true; + self.update(h.tick(now)); + }, + .paused => self.sessions.away = true, .live, .recording => { // One frame: what was routed since the last one, then its tick. // Recorded first, so `update` sees the times a replay will. @@ -334,12 +375,14 @@ pub fn frame(self: *Host, now: u64) !void { // An export's tick is 1/fps itself, not whole nanoseconds of it. if (self.options.export_to != null and dt != 0) tick.x = 1 / @as(f32, @floatFromInt(self.options.fps)); try self.pending.append(self.gpa, tick); - h.capture(self.pending.items) catch |err| self.print("Recording stopped: {t}", .{err}); + const why: ?Sessions.Why = if (self.sessions.frames == 0) .start else if (self.reloaded) .after_reload else if (self.jumped or self.sessions.away) .jump else null; + self.sessions.away = false; + self.sessions.frame(self.pending.items, self.live(), why) catch |err| self.print("session: {t}", .{err}); self.update(self.pending.items); }, } self.pending.clearRetainingCapacity(); - const work = try self.draw(if (h.mode == .live or h.mode == .recording) now else h.position, started); + const work = try self.draw(if (h.mode == .live or h.mode == .recording) now else h.base + h.position, started); const ended = c.SDL_GetTicksNS(); self.timing.add(.{ .frame = ended - (if (self.last_frame_end == 0) started else self.last_frame_end), .work = work }); self.last_frame_end = ended; @@ -362,10 +405,42 @@ pub fn update(self: *Host, events: []const abi.Event) void { self.started = false; const ctx = self.context(); self.sketch.update(&ctx, self.live().ptr); + if (self.timeline.mode == .playing or self.timeline.mode == .paused) self.resync(); } self.input.events = &.{}; } +/// After a replayed frame of a past session: at each keyframe it reaches, +/// live state is compared with the keyframe (over the leaves migration +/// kept), any difference said, and the keyframe restored. +fn resync(self: *Host) void { + const h = &self.timeline; + h.fed += 1; + const session = h.session orelse return; + const reached = h.key.?.frame + h.fed; + while (h.next_check < h.checks.items.len and h.checks.items[h.next_check].frame <= reached) { + const check = h.checks.items[h.next_check]; + h.next_check += 1; + if (check.frame < reached) continue; + const key = self.sessions.load(session, check.key) catch |err| return self.print("session {d} keyframe {d}: {t}", .{ session, check.key, err }); + defer key.free(self.gpa); + var arena: std.heap.ArenaAllocator = .init(self.gpa); + defer arena.deinit(); + const saved = arena.allocator().alignedAlloc(u8, .fromByteUnits(memory.page), self.state.layout.size) catch return; + const from = memory.restore(arena.allocator(), key.layout, key.state, self.state.layout, saved, self.sketch.defaults) catch |err| return self.print("session {d} keyframe {d}: {t}", .{ session, check.key, err }); + if (check.observed) { + const diff = memory.compareKept(from, self.state.layout, self.live(), saved); + if (diff.first) |first| { + var buf: [96]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + first.leaf.name(first.offset, &w) catch {}; + self.print("diverged before frame {d}: {d} values, first {s}", .{ reached, diff.count, w.buffered() }); + } + } + @memcpy(self.live(), saved); + } +} + /// After live state was restored from a snapshot: the pointer, buttons and /// keys tracked so far belong to other bytes, so they start over. A new /// recording then begins with events that bring back what is held now, so @@ -380,7 +455,7 @@ fn restoredInput(self: *Host, now: u64) !void { self.input.mouse_y = 0; self.input.buttons = 0; self.input.keys = .empty; - if (h.mode != .recording or h.bank.recording(h.selected).count != 0) return; + if (h.mode != .recording) return; var seed: std.ArrayList(abi.Event) = .empty; defer seed.deinit(self.gpa); if (was.mouse_x != 0 or was.mouse_y != 0) try seed.append(self.gpa, .{ .kind = .mouse_move, .time = now, .x = was.mouse_x, .y = was.mouse_y }); @@ -419,6 +494,7 @@ fn draw(self: *Host, now: u64, started: u64) !u64 { } } self.input.streams = self.audio.streamStatus(); + self.input.lead = self.audio.lead; self.input.sample_rate = sound.sample_rate; self.input.microphone = self.audio.record(arena); self.input.downloads = if (self.passes) |*g| try g.collect(arena) else &.{}; @@ -444,7 +520,12 @@ fn draw(self: *Host, now: u64, started: u64) !u64 { }, .cursor => |kind| self.cursor = kind, .voice => |voice| self.audio.declare(voice), + .gain => |g| self.audio.gains[g.group] = g.gain, .audio => |a| self.audio.push(a.key, a.samples, a.clear), + .audio_buffer => |a| if (self.passes) |*g| if (a.count > 0) { + const samples = try arena.alloc(f32, a.count); + if (g.read(a.buffer, a.offset, std.mem.sliceAsBytes(samples))) self.audio.push(a.key, samples, false) else |err| self.print("gpu audio: {t} ({s})", .{ err, c.SDL_GetError() }); + }, .quit => self.quit = true, .gpu => |pass| if (self.passes) |*g| self.runGpu(g, pass) catch |err| self.print("gpu pass: {t} ({s})", .{ err, c.SDL_GetError() }), .post_process => |p| if (self.passes) |*g| self.runPostProcess(g, p.source, p.target, p.effect) catch |err| self.print("gpu postprocess: {t} ({s})", .{ err, c.SDL_GetError() }), @@ -465,7 +546,7 @@ fn draw(self: *Host, now: u64, started: u64) !u64 { if (self.console.overlay_memory) try overlay.drawMemory(&extra, arena, self.state.layout, self.live(), self.input.width); if (self.console.overlay_sound) { const samples = self.audio.scope.snapshot(); - try overlay.drawScope(&extra, arena, &samples, self.audio.scope.rate, self.canvas); + try overlay.drawScope(&extra, arena, &samples, self.audio.scope.rate, self.audio.pull, self.canvas); } if (self.timing.visible) { if (self.timing_atlas.image == .none) self.timing_atlas = try overlay.TimingAtlas.init(&self.images, &self.painter); @@ -592,9 +673,7 @@ fn context(self: *Host) abi.Context { .input = &self.input, .scratch = self.frame_arena.allocator(), .session = self.session.heap.allocator(), - .store = self.store.allocator(), .session_root = self.session.bytes.ptr, - .store_root = self.store.root(), .commands = &self.commands, }; } @@ -636,24 +715,32 @@ pub fn runLine(self: *Host, line: []const u8, now: u64) !void { defer zone.end(); const replay = self.console.execute(self, line, now) catch |err| { // The sketch has printed its own error already. - if (err != error.CommandFailed) self.console.print("{t}. Type help for usage.", .{err}); + if (err == error.NotRecording) { + self.console.log("Not recording (an export): no marks or clips."); + } else if (err == error.HistoryDropped) { + self.console.log("That part of the history is gone: a save keeps 64 MiB, the newest."); + } else if (err == error.SaveFull) { + self.console.log("No room for a new mark: marks and the present fill the save. Save over a mark's name (its older one goes with history), or start another save (--state)."); + } else if (err != error.CommandFailed) self.console.print("{t}. Type help for usage.", .{err}); if (self.timeline.restored) self.jumped = true; try self.restoredInput(now); return err; }; - if (self.timeline.restored or movesState(line)) self.jumped = true; + if (self.timeline.restored or movesState(line)) { + self.jumped = true; + self.sessions.noteLine(line); + } try self.restoredInput(now); if (self.timeline.mode == .paused) self.update(replay); } /// Whether a console line that succeeded may have changed State other than -/// through `update` (restoring a snapshot is caught apart from this). +/// through `update` (restoring a snapshot is caught apart from this): a +/// sketch's command may. fn movesState(line: []const u8) bool { var words = std.mem.tokenizeAny(u8, line, " \t"); - const verb = words.next() orelse return false; - const still = [_][]const u8{ "help", "overlay", "timing", "get", "snapshot", "recording", "diff", "stop", "pause", "save", "quit", "exit" }; - for (still) |w| if (std.mem.eql(u8, verb, w)) return false; - return true; + const verb = std.meta.stringToEnum(Console.Verb, words.next() orelse return false) orelse return true; + return Console.verbs.get(verb).moves_state; } /// Offers a line to the sketch. @@ -674,7 +761,6 @@ pub fn resetState(self: *Host) void { self.sketch.defaults(.state, bytes.ptr); const ctx = self.context(); self.sketch.init(&ctx, bytes.ptr); - self.state.markUsed(0, true); } /// Loads the watched library again. @@ -684,47 +770,42 @@ pub fn reload(self: *Host) !void { /// Replaces the running sketch with the library at `path`, keeping state. pub fn load(self: *Host, path: []const u8) !void { - var library = try Library.openCopy(self.io, path, scratchDir(self.environ), self.reloads + 1); + var library = try Library.openFresh(self.io, path, scratchDir(self.environ), self.reloads + 1); errdefer library.close(); + // The State in the layout it is leaving, before migration drops any of it. + if (self.sessions.mode() != .off) _ = self.sessions.keyframe(.before_reload, self.live()) catch |err| self.print("session: {t}", .{err}); try self.adopt(library.sketch); if (self.library) |*old| old.close(); self.library = library; self.reloads += 1; - self.build = fileHash(path); + self.build = fileId(self.io, path); + self.sessions.stretch(.{ .build = self.build, .source = self.source, .layout = self.state.header }) catch |err| self.print("session: {t}", .{err}); self.print("reload {d}: {s}", .{ self.reloads, path }); } fn adopt(self: *Host, sketch: abi.Sketch) !void { const info = sketch.info(); if (info.abi != abi.hash) return error.AbiMismatch; - const adoption = try self.state.adopt(self.gpa, info.state, sketch.defaults); + const migrated = try self.state.adopt(self.gpa, info.state, sketch.defaults); const session_reset = try self.session.adopt(self.gpa, info.session, sketch.defaults); if (session_reset) self.releaseMade(); - const stored = try self.store.adopt(self.gpa, info.store, sketch.defaults); _ = self.info_arena.reset(.retain_capacity); const arena = self.info_arena.allocator(); self.name = try arena.dupe(u8, info.name); + self.source = try arena.dupe(u8, info.source); const completions = try arena.alloc([]const u8, info.commands.len); for (completions, info.commands) |*to, from| to.* = try arena.dupe(u8, from); self.completions = completions; self.sketch = sketch; + self.timeline.defaults = sketch.defaults; self.reloaded = true; - switch (adoption) { - .unchanged => {}, - .created => {}, - .migrated => |m| self.print("state layout changed: kept {d} fields, reset {d} to defaults", .{ m.kept, m.reset }), - } - if (!self.state.used(0)) self.resetState(); + if (migrated) |m| self.print("state layout changed: kept {d} fields, reset {d} to defaults", .{ m.kept, m.reset }); if (session_reset) { const ctx = self.context(); self.session_ready = self.sketch.setup(&ctx); if (!self.session_ready) self.console.visible = true; } if (session_reset and self.reloads > 0) self.print("session layout changed: session reset", .{}); - switch (stored) { - .unchanged, .created => {}, - .migrated => |m| self.print("store layout changed: kept {d} fields, reset {d} to defaults", .{ m.kept, m.reset }), - } } /// Frees what the old Session made: its handles are gone with it. @@ -868,15 +949,102 @@ fn consoleKey(e: abi.Event) ?Console.Key { }; } -/// A hash of a file's bytes; 0 when it cannot be read. -fn fileHash(path: []const u8) u64 { - const bytes = memory.mapReadOnly(path); - if (bytes.len == 0) return 0; - defer std.posix.munmap(bytes); - return std.hash.Wyhash.hash(0, bytes) | 1; +/// Opens the save (Sessions.zig) and starts this run's session in it: a +/// file, `<stem>.xitdb`; in memory for a script from fresh state; nowhere +/// for an export. A save that cannot be opened is said, and the run goes +/// on unsaved. +fn openSessions(self: *Host, record: bool) void { + const o = self.options; + const mode: Sessions.Mode = if (o.export_to != null) .off else if (o.script and o.fresh) .memory else .file; + var buf: [std.fs.max_path_bytes]u8 = undefined; + const path = std.fmt.bufPrint(&buf, "{s}.xitdb", .{self.stem}) catch "sketch.xitdb"; + const first: Sessions.Stretch = .{ .build = self.build, .source = self.source, .layout = self.state.header }; + self.sessions = Sessions.open(self.gpa, self.io, mode, path, first, wallClock(self.io)) catch |err| blk: { + self.print("not saved: {s}: {t}", .{ path, err }); + break :blk .{ .gpa = self.gpa, .io = self.io }; + }; + // Without `.record`, history is trimmed to the present and the marks. + self.sessions.history = record; + if (o.headless or self.sessions.mode() != .file) return; + self.print("{s} to {s}", .{ if (record) "recording" else "saving", path }); +} + +/// The State this run starts from: the save's present, its newest keyframe +/// and the frames logged after it, replayed; in a new save, a state file +/// from before (`<stem>.state`), imported once and left as it was; else +/// `init`'s. +fn openPresent(self: *Host) void { + var events: std.ArrayList(abi.Event) = .empty; + defer events.deinit(self.gpa); + const found = self.sessions.present(&events) catch |err| blk: { + self.print("the save's present did not read ({t}): starting from defaults", .{err}); + break :blk null; + }; + const key = found orelse { + if (self.sessions.session != 0 or self.sessions.mode() != .file) return self.resetState(); + var buf: [std.fs.max_path_bytes]u8 = undefined; + const old = std.fmt.bufPrint(&buf, "{s}.state", .{self.stem}) catch return self.resetState(); + const n = importOld(self.gpa, old, &self.state, &self.sessions, self.sketch.defaults) catch |err| { + if (err != error.FileNotFound) self.print("{s} not imported ({t}): kept as it was", .{ old, err }); + return self.resetState(); + }; + return self.print("{s} imported: its State, and {d} snapshots as marks; the file is kept as it was", .{ old, n }); + }; + defer key.free(self.gpa); + self.timeline.restore(key) catch |err| { + self.print("the save's present did not restore ({t}): starting from defaults", .{err}); + return self.resetState(); + }; + self.timeline.restored = false; + var frames: usize = 0; + for (events.items) |e| frames += @intFromBool(e.kind == .tick); + if (frames == 0) return; + if (key.build != self.build) return self.print("{d} frames played after the save's last keyframe not replayed: another build", .{frames}); + // As they were fed: `started` only for a run's first frame. + self.started = key.frame == 0; + self.update(events.items); + self.started = true; +} + +/// A state file from before (`path`) into a new save: its live State into +/// `state`, its snapshots (slots 1..7) marks "1".."7", in `state`'s layout; +/// the file is left as it was. Returns the number of marks. +fn importOld(gpa: std.mem.Allocator, path: []const u8, state: *memory.State, sessions: *Sessions, defaults: *const fn (abi.Memory, [*]u8) callconv(.c) void) !usize { + const old = try memory.OldState.open(path); + defer old.close(); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const scratch = try arena.allocator().alignedAlloc(u8, .fromByteUnits(memory.page), state.layout.size); + var n: usize = 0; + for (1..old.slots) |i| if (old.slot(i)) |image| { + _ = try memory.restore(arena.allocator(), old.layoutBytes(), image, state.layout, scratch, defaults); + _ = try sessions.mark(&.{'0' + @as(u8, @intCast(i))}, .import, scratch); + n += 1; + }; + _ = try memory.restore(arena.allocator(), old.layoutBytes(), old.slot(0) orelse return error.CorruptStateFile, state.layout, state.live(), defaults); + return n; +} + +/// `path` without `.xitdb` or `.state`. +pub fn stemOf(path: []const u8) []const u8 { + for ([_][]const u8{ ".xitdb", ".state" }) |suffix| if (std.mem.endsWith(u8, path, suffix)) return path[0 .. path.len - suffix.len]; + return path; +} + +fn wallClock(io: std.Io) u64 { + return @intCast(@max(0, std.Io.Timestamp.now(io, .real).nanoseconds)); } -fn scratchDir(environ: *const std.process.Environ.Map) []const u8 { +/// Identifies the file at `path` without reading it (a Debug library is tens +/// of megabytes): a hash of its inode, size and modification time; 0 when +/// there is none. A build replaces the file, so each build gets a new one. +fn fileId(io: std.Io, path: []const u8) u64 { + const stat = std.Io.Dir.cwd().statFile(io, path, .{}) catch return 0; + const id = [3]u64{ stat.inode, stat.size, @truncate(@as(u96, @bitCast(stat.mtime.nanoseconds))) }; + return std.hash.Wyhash.hash(0, std.mem.asBytes(&id)) | 1; +} + +pub fn scratchDir(environ: *const std.process.Environ.Map) []const u8 { return environ.get("XDG_RUNTIME_DIR") orelse "/tmp"; } @@ -900,8 +1068,10 @@ const api: abi.Host.VTable = .{ .textSize = apiTextSize, .loadSound = apiLoadSound, .decodeSound = apiDecodeSound, + .newSound = apiNewSound, .samples = apiSamples, .readFile = apiReadFile, + .appendFile = apiAppendFile, .env = apiEnv, .clock = apiClock, }; @@ -966,6 +1136,9 @@ fn apiLoadSound(ctx: *anyopaque, path: []const u8) abi.Audio { fn apiDecodeSound(ctx: *anyopaque, wav: []const u8) abi.Audio { return hostOf(ctx).audio.decode(wav); } +fn apiNewSound(ctx: *anyopaque, samples: [*]const f32, len: usize) callconv(.c) abi.Audio { + return hostOf(ctx).audio.new(samples[0..len]); +} fn apiReadFile(ctx: *anyopaque, path: []const u8) []const u8 { const self = hostOf(ctx); if (self.files.get(path)) |bytes| return bytes; @@ -975,6 +1148,47 @@ fn apiReadFile(ctx: *anyopaque, path: []const u8) []const u8 { self.files.put(self.gpa, key, bytes) catch self.gpa.free(key); return bytes; } +fn apiAppendFile(ctx: *anyopaque, name_ptr: [*]const u8, name_len: usize, bytes: [*]const u8, len: usize, replace: bool) callconv(.c) [*:0]const u8 { + const self = hostOf(ctx); + const name = name_ptr[0..name_len]; + if (name.len == 0 or std.mem.indexOfScalar(u8, name, '/') != null) { + self.print("appendFile: {s}: a name, not a path", .{name}); + return ""; + } + var buf: [std.fs.max_path_bytes]u8 = undefined; + const o = self.options; + const private = (o.script or o.export_to != null) and o.fresh; + // A scripted run from fresh state, or an export, writes files of its own + // (two runs of one build step may share a directory), gone at exit. + const path = (if (private) std.mem.print(&buf, "{s}.{d}.{s}", .{ self.stem, std.os.linux.getpid(), name }) else std.mem.print(&buf, "{s}.{s}", .{ self.stem, name })) catch return ""; + if (replace) { + // A new file: a mapping of the old one stays valid. + std.Io.Dir.cwd().deleteFile(self.io, path) catch {}; + if (self.files.fetchRemove(path)) |old| { + self.gpa.free(old.key); + self.retired.append(self.gpa, old.value) catch {}; + } + } + const file = std.Io.Dir.cwd().createFile(self.io, path, .{ .truncate = false }) catch |err| { + self.print("appendFile: {s}: {t}", .{ path, err }); + return ""; + }; + defer file.close(self.io); + const end = file.length(self.io) catch return ""; + file.writePositionalAll(self.io, bytes[0..len], end) catch |err| { + self.print("appendFile: {s}: {t}", .{ path, err }); + return ""; + }; + const kept = self.written.getOrPut(self.gpa, path) catch return ""; + if (!kept.found_existing) { + const copy = self.gpa.dupeSentinel(u8, path, 0) catch { + self.written.removeByPtr(kept.key_ptr); + return ""; + }; + kept.key_ptr.* = copy; + } + return @ptrCast(kept.key_ptr.*.ptr); +} fn apiClock(_: *anyopaque) u64 { return c.SDL_GetTicksNS(); } @@ -1004,11 +1218,10 @@ test "session setup runs for restored state and layout reset, not same-layout re const State = extern struct { value: u32 = 1 }; const Session1 = extern struct { ready: u32 = 0 }; const Session2 = extern struct { ready: u32 = 0, extra: u32 = 0 }; - const Store = struct {}; var setup_calls: usize = 0; var init_calls: usize = 0; var fail_setup = false; - const description: abi.Info = .{ .abi = abi.hash, .name = "setup-test", .width = 1, .height = 1, .state = abi.layout.of(State, .state), .session = abi.layout.of(Session1, .session), .store = abi.layout.of(Store, .store) }; + const description: abi.Info = .{ .abi = abi.hash, .name = "setup-test", .width = 1, .height = 1, .state = abi.layout.of(State, .state), .session = abi.layout.of(Session1, .session) }; const changed: abi.Info = blk: { var value = description; value.session = abi.layout.of(Session2, .session); @@ -1024,7 +1237,6 @@ test "session setup runs for restored state and layout reset, not same-layout re switch (kind) { .state => @as(*State, @ptrCast(@alignCast(ptr))).* = .{}, .session => @as(*Session1, @ptrCast(@alignCast(ptr))).* = .{}, - .store => {}, } } fn defaults2(kind: abi.Memory, ptr: [*]u8) callconv(.c) void { @@ -1049,26 +1261,11 @@ test "session setup runs for restored state and layout reset, not same-layout re Fixture.init_calls = 0; Fixture.fail_setup = false; const a = std.testing.allocator; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - var state_buf: [std.fs.max_path_bytes]u8 = undefined; - var store_buf: [std.fs.max_path_bytes]u8 = undefined; - const state_path = try std.mem.print(&state_buf, ".zig-cache/tmp/{s}/setup.state", .{&tmp.sub_path}); - const store_path = try std.mem.print(&store_buf, ".zig-cache/tmp/{s}/setup.store", .{&tmp.sub_path}); - { - var state = try memory.StateFile.open(a, state_path); - defer state.close(); - _ = try state.adopt(a, Fixture.description.state, Fixture.defaults); - @as(*Fixture.State, @ptrCast(state.slot(0).ptr)).value = 77; - state.markUsed(0, true); - } - // Exercise adoption with real persisted memory, without opening SDL devices. + // Exercise adoption without opening SDL devices. var host: Host = undefined; host.gpa = a; - host.state = try memory.StateFile.open(a, state_path); - defer host.state.close(); - host.store = try memory.StoreFile.open(a, store_path, false); - defer host.store.close(); + host.state = .init(a); + defer host.state.deinit(a); host.session = .init(a); defer host.session.deinit(a); host.info_arena = .init(a); @@ -1083,7 +1280,8 @@ test "session setup runs for restored state and layout reset, not same-layout re host.input = .{}; host.commands = .empty; try host.adopt(Fixture.sketch); - try std.testing.expectEqual(@as(u32, 77), @as(*Fixture.State, @ptrCast(@alignCast(host.live().ptr))).value); + // Defaults: the present or `init` comes after (openPresent). + try std.testing.expectEqual(@as(u32, 1), @as(*Fixture.State, @ptrCast(@alignCast(host.live().ptr))).value); try std.testing.expectEqual(@as(usize, 0), Fixture.init_calls); try std.testing.expectEqual(@as(usize, 1), Fixture.setup_calls); const session_ptr = host.session.bytes.ptr; @@ -1123,3 +1321,79 @@ test "setup writeBuffer propagates unavailable, unknown and out-of-bounds upload try host.passes.?.buffers.append(a, .{ .buffer = undefined, .size = 4 }); try std.testing.expectError(error.UploadOutOfBounds, client.writeBuffer(@fromBackingInt(@intCast(1)), 2, "data")); } + +test "a state file from before imports into a new save: its State live, its snapshots marks, the file as it was" { + const State = extern struct { v: u32 = 0 }; + const D = struct { + fn f(_: abi.Memory, p: [*]u8) callconv(.c) void { + @as(*State, @ptrCast(@alignCast(p))).* = .{}; + } + }; + const gpa = std.testing.allocator; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var buf: [std.fs.max_path_bytes]u8 = undefined; + const path = try std.mem.print(&buf, ".zig-cache/tmp/{s}/old.state", .{&tmp.sub_path}); + var state: memory.State = .init(gpa); + defer state.deinit(gpa); + _ = try state.adopt(gpa, abi.layout.of(State, .state), D.f); + // An eight-slot SKETCH02 file, slots 0, 1 and 3 used, its header State's. + const stride = memory.page; + const old = try gpa.alloc(u8, memory.header_len + memory.old_slot_count * stride); + defer gpa.free(old); + @memset(old, 0); + @memcpy(old[0..state.header.len], state.header); + const h: *memory.Header = @ptrCast(@alignCast(old.ptr)); + h.magic = memory.file_magic_v2; + h.used = 0b1011; + for ([_][2]u32{ .{ 0, 5 }, .{ 1, 11 }, .{ 3, 33 } }) |slot| std.mem.writeInt(u32, old[memory.header_len + slot[0] * stride ..][0..4], slot[1], .little); + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = old }); + + var sessions = try Sessions.open(gpa, io, .memory, "", .{ .build = 1, .source = "", .layout = state.header }, 0); + defer sessions.deinit(); + try std.testing.expectEqual(@as(usize, 2), try importOld(gpa, path, &state, &sessions, D.f)); + for ([_][2]u32{ .{ '1', 11 }, .{ '3', 33 } }) |want| { + const m = (try sessions.findMark(&.{@intCast(want[0])})).?; + const key = try sessions.load(m.session, m.key); + defer key.free(gpa); + try std.testing.expectEqual(Sessions.Why.import, key.why); + try std.testing.expectEqual(want[1], std.mem.readInt(u32, key.state[0..4], .little)); + } + try std.testing.expectEqual(@as(?Sessions.Entry, null), try sessions.findMark("2")); + try std.testing.expectEqual(@as(u32, 5), std.mem.readInt(u32, state.live()[0..4], .little)); + const after = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .unlimited); + defer gpa.free(after); + try std.testing.expectEqualSlices(u8, old, after); +} + +test "appendFile appends to a file beside the save and names it for readFile" { + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var buf: [std.fs.max_path_bytes]u8 = undefined; + var host: Host = undefined; + host.gpa = std.testing.allocator; + host.io = io; + host.written = .empty; + host.files = .empty; + host.options = .{}; + host.stem = try std.mem.print(&buf, ".zig-cache/tmp/{s}/t", .{&tmp.sub_path}); + defer { + var written = host.written.keyIterator(); + while (written.next()) |path| host.gpa.free(path.ptr[0 .. path.len + 1]); + host.written.deinit(host.gpa); + } + const name = "take-1.f32"; + const path = std.mem.span(apiAppendFile(&host, name, name.len, "ab", 2, false)); + try std.testing.expect(std.mem.endsWith(u8, path, "/t.take-1.f32")); + try std.testing.expectEqual(path.ptr, apiAppendFile(&host, name, name.len, "cd", 2, false)); + const bytes = try tmp.dir.readFileAlloc(io, "t.take-1.f32", host.gpa, .unlimited); + defer host.gpa.free(bytes); + try std.testing.expectEqualStrings("abcd", bytes); + // writeFile: a new file, its old bytes gone. + _ = apiAppendFile(&host, name, name.len, "e", 1, true); + const again = try tmp.dir.readFileAlloc(io, "t.take-1.f32", host.gpa, .unlimited); + defer host.gpa.free(again); + try std.testing.expectEqualStrings("e", again); +} diff --git a/src/host/Sessions.zig b/src/host/Sessions.zig new file mode 100644 index 0000000..d6caf9c --- /dev/null +++ b/src/host/Sessions.zig @@ -0,0 +1,1599 @@ +//! A sketch's save: one xitdb database holding every run of it, an +//! append-only log of the frames live `update` was fed, and the State at +//! the moments that matter (keyframes). The newest keyframe and the frames +//! after it are the present a run starts from (`present`). Nothing in it +//! is ever overwritten: marks and clips are names pointing into it. +//! +//! root = map { +//! version 1 +//! sessions list of session, one a run +//! marks list of { name, session, key }: a named keyframe (the newest of a name wins) +//! clips list of { name, session, key, start, end }: frames start..end of a +//! session, played from keyframe `key`; `end` 0 while recording +//! } +//! session = map { +//! started wall-clock ns at open ended ns at a clean exit, else 0 +//! from "" or where it came from ("import <file>") +//! stretches list of { frame, build, source, layout }: one a load (start, reloads); +//! `layout` is State's header (memory.State.header, read by memory.layoutOf) +//! batches list of bytes: a little-endian u64, the first frame's index, then +//! whole frames of raw `abi.Event`s, each frame ending with its tick +//! keys list of { frame, batch, stretch, why, time, size, pages, written, line }: +//! the State before frame `frame` is fed, in stretch `stretch`'s +//! layout; `batch` is where reading frames from it starts +//! frames frames committed +//! } +//! +//! A keyframe's State is `size` bytes in `pages`, a list of `page`-byte +//! blobs (the last one shorter), an all-zero page an empty slot. A keyframe +//! starts from the list of the one before it and writes only the pages +//! whose hash changed (`written` bytes), so every page another keyframe +//! holds unchanged is shared, never written twice. (Keyframes from before +//! pages hold their State whole, as `state` bytes; `load` reads both.) +//! +//! One transaction (`commit`) a second of session time, and at once for a +//! reload, a mark, a clip's start or end, and exit: a crash loses less than +//! a second of play; fsync only at exit and for a mark. A file a crash or +//! power loss tore opens at its last whole commit (`mend`). +//! +//! A save is at most `max_save`: a commit that leaves the file past it +//! drops history oldest first and compacts the file to three quarters of +//! it (`trim`); the present, the newest mark of each name and the newest +//! clip of each name are never dropped. A build that does not record +//! (`history` false) drops all it may at every keyframe, and compacts at +//! exit: what it keeps is the present and the marks. +const Sessions = @This(); +const std = @import("std"); +const xitdb = @import("xitdb"); +const abi = @import("abi"); + +pub const Disk = xitdb.Database(.buffered_file, u64); +pub const Memory = xitdb.Database(.memory, u64); + +/// `file` for every run but two: `memory` for a scripted run from fresh +/// state (time travel, nothing on disk), `off` for an export. +pub const Mode = enum { off, memory, file }; +pub const Why = enum(u64) { start, periodic, jump, before_reload, after_reload, mark, exit, import }; + +/// Pending frames are committed once they span a second of session time +/// (less a millisecond: 60 ticks of a 60 Hz clock that rounds down are one). +pub const commit_ns: u64 = std.time.ns_per_s - std.time.ns_per_ms; +/// A keyframe at least this often while the State changes. +pub const periodic_ns: u64 = 60 * std.time.ns_per_s; +/// Mark and clip names: no spaces, at most this long. +pub const max_name = 32; +/// A memory database (a scripted run's) stops recording at this size: ten +/// hours or more of play at 60 Hz. What it holds stays readable. +pub const memory_max: u64 = 256 << 20; +/// The most a save's file holds (State is at most half of it, +/// `abi.layout.max_state`, so history has room). +pub const max_save: u64 = 64 << 20; + +pub const K = enum(u64) { version = 1, sessions, marks, clips, started, ended, from, stretches, batches, keys, frames, frame, build, source, layout, batch, stretch, why, time, state, line, name, session, key, start, end, pages, size, written }; +fn key(k: K) u64 { + return @intFromEnum(k); +} + +pub const Stretch = struct { frame: u64 = 0, build: u64, source: []const u8, layout: []const u8 }; + +/// A keyframe's page: the OS page, the grain of sharing. +pub const page = 4096; + +/// A keyframe: `session`'s keyframe `key`. +const At = struct { session: u64, key: u64 }; + +/// A keyframe queued: the pages of its State that differ from keyframe +/// `from`'s (`indices`, ascending; their bytes one after the other in +/// `pages`, `page` apart). +const Keyframe = struct { frame: u64, batch: u64, stretch: u64, why: Why, time: u64, size: u64, from: ?At, indices: []u64, pages: []u8, line: []u8 }; + +gpa: std.mem.Allocator, +/// Files and the wall clock; a memory database runs on `std.Io.failing`. +io: std.Io, +db: union(Mode) { off, memory: Memory, file: Disk } = .off, +file: ?std.Io.File = null, +/// The database's write buffer, an allocation of its own: the database +/// points at it. +buffer: ?*std.Io.Writer.Allocating = null, +/// The database's path (file mode), owned. +path: []const u8 = "", +/// This run's index in `sessions`. +session: u64 = 0, +/// Frames logged, committed or not, and committed. +frames: u64 = 0, +committed: u64 = 0, +/// This session's committed batches, its stretches and its keyframes +/// (queued ones too). +batches: u64 = 0, +stretches: u64 = 0, +keys: u64 = 0, +/// The frames since the last commit, as the batch they become. +batch: std.ArrayList(u8) = .empty, +/// The first pending frame's tick. +batch_time: u64 = 0, +/// The first and latest event time logged: times never go back. +first_time: u64 = 0, +last_time: u64 = 0, +/// The last keyframe's time and stretch. +key_time: u64 = 0, +key_stretch: u64 = 0, +/// The keyframe the next one starts from (the last one, or the one a run +/// started from), and the hashes of its pages. +last: ?At = null, +hashes: []u64 = &.{}, +queued: std.ArrayList(Keyframe) = .empty, +/// The clip being recorded, an index into `clips`. +recording: ?u64 = null, +/// State may have changed other than by a logged live frame (a replay ran): +/// the next live frame starts with a keyframe. +away: bool = false, +/// A memory database reached `memory_max`: nothing more is logged. +full: bool = false, +/// The console line that last changed State, for the next keyframe. +line: [256]u8 = undefined, +line_len: usize = 0, +/// Keep history, up to `max_save`; else only the present and the marks. +history: bool = true, + +/// Opens the database at `path` (file mode: created with its directory when +/// missing; one a crash or power loss tore is opened at its last whole +/// commit (`mend`); one still refused is renamed aside, never deleted) and +/// starts this run's session in it. +pub fn open(gpa: std.mem.Allocator, io: std.Io, want: Mode, path: []const u8, first: Stretch, started: u64) !Sessions { + var s: Sessions = .{ .gpa = gpa, .io = io }; + if (want == .off) return s; + errdefer s.deinit(); + const buffer = try gpa.create(std.Io.Writer.Allocating); + buffer.* = .init(gpa); + s.buffer = buffer; + switch (want) { + .off => unreachable, + .memory => s.db = .{ .memory = try Memory.init(std.Io.failing, .{ .buffer = buffer, .file_id = 0, .max_size = memory_max }) }, + .file => { + s.path = try gpa.dupe(u8, path); + const cwd = std.Io.Dir.cwd(); + if (std.fs.path.dirname(path)) |dir| try cwd.createDirPath(io, dir); + var aside = false; + while (true) { + const file = try cwd.createFile(io, path, .{ .read = true, .truncate = false }); + if (Disk.init(io, .{ .file = file, .buffer = buffer, .fsync = false })) |db| { + s.db = .{ .file = db }; + s.file = file; + break; + } else |err| { + switch (err) { + error.InvalidDatabase, error.InvalidVersion, error.InvalidHashSize, error.TruncatedDatabase, error.InvalidEnumTag, error.EndOfStream => {}, + else => { + file.close(io); + return err; + }, + } + if (mend(io, file, buffer)) |db| { + s.db = .{ .file = db }; + s.file = file; + std.log.warn("{s} was torn after its last whole commit: opened at it", .{path}); + break; + } + file.close(io); + if (aside) return err; + aside = true; + var buf: [std.fs.max_path_bytes + 32]u8 = undefined; + const to = try std.fmt.bufPrint(&buf, "{s}.broken.{d}", .{ path, started / std.time.ns_per_s }); + try cwd.rename(path, cwd, to, io); + std.log.warn("{s} is no sessions database this host reads: moved to {s}", .{ path, to }); + } + } + }, + } + s.session = try s.count(.sessions); + try s.commit(.{ .open = .{ .started = started, .first = first } }); + s.stretches = 1; + return s; +} + +/// The database at `path`, read only and no session started in it: for +/// its `present` with no run of the sketch (`fs` with the sketch closed). +pub fn openRead(gpa: std.mem.Allocator, io: std.Io, path: []const u8) !Sessions { + var s: Sessions = .{ .gpa = gpa, .io = io }; + errdefer s.deinit(); + s.file = try std.Io.Dir.cwd().openFile(io, path, .{}); + s.buffer = try gpa.create(std.Io.Writer.Allocating); + s.buffer.?.* = .init(gpa); + s.db = .{ .file = try Disk.init(io, .{ .file = s.file.?, .buffer = s.buffer.?, .fsync = false }) }; + s.session = try s.count(.sessions); + return s; +} + +pub fn deinit(s: *Sessions) void { + s.dropQueued(); + s.queued.deinit(s.gpa); + s.batch.deinit(s.gpa); + s.gpa.free(s.hashes); + if (s.file) |f| f.close(s.io); + if (s.buffer) |b| { + b.deinit(); + s.gpa.destroy(b); + } + s.gpa.free(s.path); + s.* = .{ .gpa = s.gpa, .io = s.io }; +} + +/// The last frames, an exit keyframe of `state`, and the session's end, in +/// one transaction synced to disk; then closed. Without history the file is +/// compacted, so the frames it dropped are gone from the disk too. +pub fn close(s: *Sessions, state: []const u8, ended: u64) void { + defer s.deinit(); + if (s.db == .off) return; + s.stopClip() catch {}; + _ = s.keyframe(.exit, state) catch {}; + s.commitSynced(.{ .end = ended }) catch |err| std.log.warn("sessions: last commit failed: {t}", .{err}); + if (s.db == .file and !s.history) s.compact() catch |err| std.log.warn("sessions: not compacted: {t}", .{err}); +} + +/// Writes what the database holds now, without the nodes commits left +/// behind, to `<path>.new`, synced, renames it over the file, and goes on +/// in it. +fn compact(s: *Sessions) !void { + const cwd = std.Io.Dir.cwd(); + var buf: [std.fs.max_path_bytes + 8]u8 = undefined; + const new = try std.fmt.bufPrint(&buf, "{s}.new", .{s.path}); + const file = try cwd.createFile(s.io, new, .{ .read = true, .truncate = true }); + errdefer { + file.close(s.io); + cwd.deleteFile(s.io, new) catch {}; + } + const buffer = try s.gpa.create(std.Io.Writer.Allocating); + buffer.* = .init(s.gpa); + errdefer { + buffer.deinit(); + s.gpa.destroy(buffer); + } + var offsets: std.AutoHashMap(u64, u64) = .init(s.gpa); + defer offsets.deinit(); + var db = try s.db.file.compact(.buffered_file, .{ .file = file, .buffer = buffer, .fsync = true }, &offsets); + db.core.file.fsync = false; + try cwd.rename(new, cwd, s.path, s.io); + s.file.?.close(s.io); + s.buffer.?.deinit(); + s.gpa.destroy(s.buffer.?); + s.file = file; + s.buffer = buffer; + s.db = .{ .file = db }; +} + +/// Drops history oldest first, then compacts the file: until its keyframes' +/// pages and frames are under three quarters of `max_save`, or, without +/// history, all it may (compacted only past `max_save`; `close` does it +/// at exit). A few rounds at most: what a dropped keyframe wrote may still +/// be shared by one kept, so a round can free less than it counted. +fn trim(s: *Sessions) !void { + const goal = max_save / 4 * 3; + var keep: u64 = if (s.history) goal else 0; + for (0..4) |_| { + var dropped: u64 = 0; + var left: u64 = 0; + try s.db.file.runContext(Trim(Disk){ .s = s, .keep = keep, .dropped = &dropped, .left = &left }); + var size = try s.file.?.length(s.io); + if (!s.history and size <= max_save) return; + try s.compact(); + size = try s.file.?.length(s.io); + if (size <= goal or dropped == 0) return; + // What the count leaves out (lists, maps, stretches) is the rest. + keep = left -| (size - goal); + } +} + +/// A keyframe's pages or a batch of frames, for `trim`. +const Item = struct { session: u64, index: u64, frame: u64, bytes: u64, batch: bool, keep: bool }; + +/// The transaction of `trim`: drops a keyframe by removing its pages (its +/// fields stay, so keyframe numbers and searches by frame still work) and +/// a batch by emptying its slot, oldest first, until what is left counts at +/// most `keep` bytes; a session left with nothing loses its keyframes, +/// batches and stretches. Never the present (the newest keyframe and the +/// batches from its own on), the keyframe of the newest mark or clip of a +/// name, or a batch holding a frame of such a clip. +fn Trim(comptime DB: type) type { + return struct { + s: *Sessions, + keep: u64, + /// Bytes dropped, and counted after. + dropped: *u64, + left: *u64, + + const R = Read(DB); + const Map = DB.HashMap(.read_write); + const List = DB.ArrayList(.read_write); + + pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { + var arena: std.heap.ArenaAllocator = .init(ctx.s.gpa); + defer arena.deinit(); + const a = arena.allocator(); + const root = try Map.init(cursor.*); + const all = try R.list(root.readOnly(), .sessions) orelse return; + const n = try all.count(); + var pinned: std.AutoHashMapUnmanaged(At, void) = .empty; + const Clip = struct { session: u64, start: u64, end: u64 }; + var clips: std.ArrayList(Clip) = .empty; + for ([_]K{ .marks, .clips }) |which| { + const list = try R.list(root.readOnly(), which) orelse continue; + var names: std.StringHashMapUnmanaged(void) = .empty; + var i = try list.count(); + while (i > 0) { + i -= 1; + const e = try R.at(list, i); + var buf: [max_name]u8 = undefined; + const name = (try R.field(e, .name)).readBytes(&buf) catch return error.CorruptSession; + if ((try names.getOrPut(a, try a.dupe(u8, name))).found_existing) continue; + const at: At = .{ .session = try R.uint(e, .session), .key = try R.uint(e, .key) }; + try pinned.put(a, at, {}); + const end = if (which == .clips) try R.uint(e, .end) else continue; + try clips.append(a, .{ .session = at.session, .start = try R.uint(e, .start), .end = if (end == 0) std.math.maxInt(u64) else end }); + } + } + // The present: the newest keyframe, and the batches from its own on. + var now: At = undefined; + var now_batch: u64 = 0; + var i = n; + while (true) { + if (i == 0) return; + i -= 1; + const keys = try R.list(try R.at(all, i), .keys) orelse continue; + const n_keys = try keys.count(); + if (n_keys == 0) continue; + now = .{ .session = i, .key = n_keys - 1 }; + now_batch = try R.uint(try R.at(keys, n_keys - 1), .batch); + break; + } + try pinned.put(a, now, {}); + // What is not dropped yet, each session's in frame order. + var items: std.ArrayList(Item) = .empty; + var total: u64 = 0; + for (0..n) |si| { + const ses = try R.at(all, si); + const start = items.items.len; + if (try R.list(ses, .keys)) |keys| for (0..try keys.count()) |k| { + const e = try R.at(keys, k); + if (try e.getCursor(key(.pages)) == null) continue; + const written = if (try e.getCursor(key(.written))) |w| try w.readUint() else 0; + try items.append(a, .{ .session = si, .index = k, .frame = try R.uint(e, .frame), .bytes = written, .batch = false, .keep = pinned.contains(.{ .session = si, .key = k }) }); + }; + if (try R.list(ses, .batches)) |batches| for (0..try batches.count()) |b| { + var c = try batches.getCursor(@intCast(b)) orelse continue; + if ((try c.slot()).tag == .none) continue; + var buf: [8]u8 = undefined; + var reader = try c.reader(&buf); + var head: [8]u8 = undefined; + try reader.interface.readSliceAll(&head); + try items.append(a, .{ .session = si, .index = b, .frame = std.mem.readInt(u64, &head, .little), .bytes = reader.size, .batch = true, .keep = si == now.session and b >= now_batch }); + }; + const mine = items.items[start..]; + std.mem.sort(Item, mine, {}, struct { + fn lessThan(_: void, x: Item, y: Item) bool { + return x.frame < y.frame or (x.frame == y.frame and !x.batch and y.batch); + } + }.lessThan); + // A batch holds frames up to the next batch's first. + const frames = try R.uint(ses, .frames); + var end: u64 = std.math.maxInt(u64); + var j = mine.len; + while (j > 0) { + j -= 1; + const it = &mine[j]; + if (!it.batch) continue; + const last = @min(end, frames); + for (clips.items) |clip| if (clip.session == si and clip.start < last and it.frame < clip.end) { + it.keep = true; + }; + end = it.frame; + } + for (mine) |it| total += it.bytes; + } + // Dropped oldest first. + const sessions = try List.init(try root.putCursor(key(.sessions))); + var left: std.ArrayList(u64) = .empty; + try left.appendNTimes(a, 0, n); + for (items.items) |it| { + if (it.keep or total <= ctx.keep) { + left.items[it.session] += 1; + continue; + } + const ses = try Map.init(try sessions.putCursor(@intCast(it.session))); + if (it.batch) { + try (try List.init(try ses.putCursor(key(.batches)))).put(@intCast(it.index), .{ .slot = null }); + } else { + const k = try Map.init(try (try List.init(try ses.putCursor(key(.keys)))).putCursor(@intCast(it.index))); + _ = try k.remove(key(.pages)); + try k.put(key(.written), .{ .uint = 0 }); + } + total -= it.bytes; + ctx.dropped.* += it.bytes; + } + ctx.left.* = total; + for (left.items, 0..) |kept, si| { + if (kept > 0 or si >= now.session) continue; + var any = false; + var it = pinned.keyIterator(); + while (it.next()) |at| any = any or at.session == si; + if (any) continue; + const ses = try Map.init(try sessions.putCursor(@intCast(si))); + for ([_]K{ .keys, .batches, .stretches }) |k| _ = try ses.remove(key(k)); + } + } + }; +} + +/// The bytes of every session's batches and keyframes' pages (each written +/// once): what compaction keeps. +/// Reading them all is also what proves a mended file whole. +fn liveSize(db: *Disk) !u64 { + const R = Read(Disk); + const sessions = try R.list(try R.root(db), .sessions) orelse return 0; + var live: u64 = 0; + var it = try sessions.iterator(); + while (try it.next()) |c| { + const session = try R.Map.init(c); + if (try R.list(session, .batches)) |batches| { + var b = try batches.iterator(); + while (try b.next()) |blob| live += if ((try blob.slot()).tag == .none) 0 else try blob.count(); + } + if (try R.list(session, .keys)) |keys| { + var k = try keys.iterator(); + while (try k.next()) |key_cursor| { + const e = try R.Map.init(key_cursor); + live += if (try e.getCursor(key(.written))) |w| try w.readUint() else try (try R.field(e, .state)).count(); + } + } + } + return live; +} + +// xitdb's layout, as `mend` reads it (zig-pkg's xitdb src/lib.zig): the +// database header (its file id the last 8 of its 20 bytes, big endian), the +// root header (the root slot's 9 bytes, then the committed size's 8), and +// the trailer ending every commit (the root slot's 9 bytes, the commit id's +// 8, and their CRC-64/XZ's 8, with the file id and its own position). +const db_header_len = 20; +const root_header_end = db_header_len + 17; +const trailer_len = 25; +const hash_map_tag = 4; + +/// A file xitdb refused because a crash or power loss tore its last commit +/// (its root header written, the commit's bytes not all): opened at the last +/// commit before the tear whose trailer verifies and whose sessions read +/// whole, scanned back from the file's end, its root header put back at it. +/// Null, the file as it was, when none does. +fn mend(io: std.Io, file: std.Io.File, buffer: *std.Io.Writer.Allocating) ?Disk { + var head: [root_header_end]u8 = undefined; + if ((file.readPositionalAll(io, &head, 0) catch return null) != head.len or !std.mem.eql(u8, head[0..3], "xit")) return null; + const file_id = std.mem.readInt(u64, head[db_header_len - 8 .. db_header_len], .big); + var chunk: [64 << 10]u8 = undefined; + var end = file.length(io) catch return null; + while (end >= root_header_end + trailer_len) { + const start = @max(root_header_end, end - @min(end, chunk.len)); + const got = file.readPositionalAll(io, chunk[0 .. end - start], start) catch return null; + if (got != end - start) return null; + var i = got; + while (i >= trailer_len) : (i -= 1) { + const t = chunk[i - trailer_len ..][0..trailer_len]; + const at = start + i - trailer_len; + // The root is a map, at a slot written before its trailer. + if (t[0] & 0x7f != hash_map_tag or std.mem.readInt(u64, t[1..9], .big) >= at) continue; + var sum: [33]u8 = undefined; + std.mem.writeInt(u64, sum[0..8], file_id, .big); + std.mem.writeInt(u64, sum[8..16], at, .big); + @memcpy(sum[16..33], t[0..17]); + if (std.hash.crc.@"CRC-64/XZ".hash(&sum) != std.mem.readInt(u64, t[17..25], .big)) continue; + var root: [17]u8 = undefined; + @memcpy(root[0..9], t[0..9]); + std.mem.writeInt(u64, root[9..17], at + trailer_len, .big); + file.writePositionalAll(io, &root, db_header_len) catch return null; + var db = Disk.init(io, .{ .file = file, .buffer = buffer, .fsync = false }) catch continue; + _ = liveSize(&db) catch continue; + file.sync(io) catch {}; + return db; + } + if (start == root_header_end) break; + end = start + trailer_len - 1; + } + file.writePositionalAll(io, head[db_header_len..], db_header_len) catch {}; + return null; +} + +pub fn mode(s: *const Sessions) Mode { + return s.db; +} + +/// Remembers the console line that changed State, for the next keyframe. +pub fn noteLine(s: *Sessions, line: []const u8) void { + s.line_len = @min(line.len, s.line.len); + @memcpy(s.line[0..s.line_len], line[0..s.line_len]); +} + +/// One live frame, its tick last, before `update` is fed it: its times are +/// made never to go back (what `update` then sees is what a replay will), +/// and it is logged, after a keyframe of `state` when `why` says so or the +/// last is a minute old. +pub fn frame(s: *Sessions, one: []abi.Event, state: []const u8, why: ?Why) !void { + for (one) |*e| { + e.time = @max(e.time, s.last_time); + s.last_time = e.time; + } + if (s.db == .off or s.full) return; + const tick = one[one.len - 1].time; + if (s.batch.items.len > 0 and tick -| s.batch_time >= commit_ns) try s.commit(.none); + if (why) |w| { + _ = try s.keyframe(w, state); + } else if (tick -| s.key_time >= periodic_ns) _ = try s.keyframe(.periodic, state); + if (s.frames == 0) s.first_time = tick; + if (s.batch.items.len == 0) { + try s.batch.appendSlice(s.gpa, std.mem.asBytes(&std.mem.nativeToLittle(u64, s.frames))); + s.batch_time = tick; + } + try s.batch.appendSlice(s.gpa, std.mem.sliceAsBytes(one)); + s.frames += 1; +} + +/// Queues a keyframe of `state` before the next frame, and returns its +/// index; an unchanged State is the last keyframe again (but for a +/// `before_reload` one: the last word in the old layout). Only the pages +/// whose hash differs from the last keyframe's are copied, and written. +pub fn keyframe(s: *Sessions, why: Why, state: []const u8) !u64 { + if (s.db == .off) return error.NotRecording; + defer s.line_len = 0; + const hashes = try s.gpa.alloc(u64, std.math.divCeil(usize, state.len, page) catch unreachable); + errdefer s.gpa.free(hashes); + var changed: std.ArrayList(u64) = .empty; + defer changed.deinit(s.gpa); + for (hashes, 0..) |*h, i| { + h.* = std.hash.Wyhash.hash(0, state[i * page .. @min(state.len, (i + 1) * page)]); + if (i >= s.hashes.len or s.hashes[i] != h.*) try changed.append(s.gpa, i); + } + if (s.keys > 0 and why != .before_reload and changed.items.len == 0 and hashes.len == s.hashes.len and s.key_stretch == s.stretches - 1) { + s.gpa.free(hashes); + return s.keys - 1; + } + const pages = try s.gpa.alloc(u8, changed.items.len * page); + errdefer s.gpa.free(pages); + for (changed.items, 0..) |i, k| { + const bytes = state[i * page .. @min(state.len, (i + 1) * page)]; + @memcpy(pages[k * page ..][0..bytes.len], bytes); + } + const indices = try changed.toOwnedSlice(s.gpa); + errdefer s.gpa.free(indices); + const line_copy = try s.gpa.dupe(u8, s.line[0..s.line_len]); + errdefer s.gpa.free(line_copy); + try s.queued.append(s.gpa, .{ .frame = s.frames, .batch = s.batches, .stretch = s.stretches - 1, .why = why, .time = s.last_time, .size = state.len, .from = s.last, .indices = indices, .pages = pages, .line = line_copy }); + s.gpa.free(s.hashes); + s.hashes = hashes; + s.last = .{ .session = s.session, .key = s.keys }; + s.key_time = s.last_time; + s.key_stretch = s.stretches - 1; + s.keys += 1; + return s.keys - 1; +} + +/// A new stretch from the next frame: a reload's build, source and layout. +pub fn stretch(s: *Sessions, st: Stretch) !void { + if (s.db == .off) return; + var with = st; + with.frame = s.frames; + try s.commit(.{ .stretch = with }); + s.stretches += 1; +} + +/// Mark `name`: a keyframe of `state` (`why`: `.mark`, or `.import`), +/// synced to disk. Returns the keyframe's index. A mark of a new name needs +/// room for a whole State under `max_save`, history dropped to make it +/// (`trim`): without, it is refused (`error.SaveFull`). A mark over an +/// existing name lets the older one go with history. +pub fn mark(s: *Sessions, name: []const u8, why: Why, state: []const u8) !u64 { + if (s.db == .file and try s.file.?.length(s.io) + state.len > max_save and try s.findMark(name) == null) { + try s.trim(); + if (try s.file.?.length(s.io) + state.len > max_save) return error.SaveFull; + } + const k = try s.keyframe(why, state); + try s.commitSynced(.{ .mark = .{ .name = name, .key = k } }); + return k; +} + +/// Starts clip `name` at the next frame, played from keyframe `k`. +pub fn startClip(s: *Sessions, name: []const u8, k: u64) !void { + const index = try s.count(.clips); + try s.commit(.{ .clip = .{ .name = name, .key = k, .start = s.frames } }); + s.recording = index; +} + +/// Ends the clip being recorded after the frames logged so far. +pub fn stopClip(s: *Sessions) !void { + const index = s.recording orelse return; + try s.commit(.{ .clip_end = .{ .index = index, .end = s.frames } }); + s.recording = null; +} + +fn dropQueued(s: *Sessions) void { + for (s.queued.items) |k| { + s.gpa.free(k.indices); + s.gpa.free(k.pages); + s.gpa.free(k.line); + } + s.queued.clearRetainingCapacity(); +} + +const Extra = union(enum) { + none, + open: struct { started: u64, first: Stretch }, + stretch: Stretch, + mark: struct { name: []const u8, key: u64 }, + clip: struct { name: []const u8, key: u64, start: u64 }, + clip_end: struct { index: u64, end: u64 }, + end: u64, +}; + +fn commitSynced(s: *Sessions, extra: Extra) !void { + if (s.db == .file) s.db.file.core.file.fsync = true; + defer if (s.db == .file) { + s.db.file.core.file.fsync = false; + }; + try s.commit(extra); +} + +/// One transaction: the pending frames, the queued keyframes and `extra`. +pub fn commit(s: *Sessions, extra: Extra) !void { + switch (s.db) { + .off => return, + inline .memory, .file => |*db| db.runContext(Commit(@TypeOf(db.*)){ .s = s, .extra = extra }) catch |err| { + // A memory database that cannot grow (`memory_max`, or no + // memory left) stops recording, once. + if (s.db == .memory and !s.full) { + s.full = true; + s.batch.clearRetainingCapacity(); + s.dropQueued(); + std.log.warn("sessions: the memory database cannot grow ({t}; {d} MiB at most): no more frames recorded", .{ err, memory_max >> 20 }); + } + return err; + }, + } + if (s.batch.items.len > 0) { + s.batches += 1; + s.committed = s.frames; + s.batch.clearRetainingCapacity(); + } + const keyed = s.queued.items.len > 0; + s.dropQueued(); + if (s.db != .file) return; + if ((try s.file.?.length(s.io)) > max_save or (!s.history and keyed)) s.trim() catch |err| std.log.warn("sessions: history not trimmed: {t}", .{err}); +} + +fn Commit(comptime DB: type) type { + return struct { + s: *Sessions, + extra: Extra, + + const Map = DB.HashMap(.read_write); + const List = DB.ArrayList(.read_write); + + pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { + const s = ctx.s; + const root = try Map.init(cursor.*); + const sessions = try List.init(try root.putCursor(key(.sessions))); + if (ctx.extra == .open) { + const o = ctx.extra.open; + try root.put(key(.version), .{ .uint = 1 }); + const session = try Map.init(try sessions.appendCursor()); + try session.put(key(.started), .{ .uint = o.started }); + try session.put(key(.ended), .{ .uint = 0 }); + try session.put(key(.from), .{ .bytes = "" }); + try session.put(key(.frames), .{ .uint = 0 }); + try putStretch(try List.init(try session.putCursor(key(.stretches))), o.first); + return; + } + const session = try Map.init(try sessions.putCursor(@intCast(s.session))); + if (s.batch.items.len > 0) { + try (try List.init(try session.putCursor(key(.batches)))).append(.{ .bytes = s.batch.items }); + try session.put(key(.frames), .{ .uint = s.frames }); + } + if (s.queued.items.len > 0) { + const keys = try List.init(try session.putCursor(key(.keys))); + for (s.queued.items) |q| { + const k = try Map.init(try keys.appendCursor()); + try k.put(key(.frame), .{ .uint = q.frame }); + try k.put(key(.batch), .{ .uint = q.batch }); + try k.put(key(.stretch), .{ .uint = q.stretch }); + try k.put(key(.why), .{ .uint = @intFromEnum(q.why) }); + try k.put(key(.time), .{ .uint = q.time }); + try k.put(key(.size), .{ .uint = q.size }); + try k.put(key(.line), .{ .bytes = q.line }); + // From the keyframe before's pages, copied as the + // transaction writes on (it may be in it too). + var from = try k.putCursor(key(.pages)); + if (q.from) |at| if (try pagesSlot(root, at)) |slot| { + try from.write(.{ .slot = slot }); + try from.freeze(); + }; + const pages = try List.init(from); + const had = try pages.count(); + var written: u64 = 0; + for (q.indices, 0..) |i, j| { + const bytes = q.pages[j * page ..][0..@min(page, q.size - i * page)]; + const zero = std.mem.allEqual(u8, bytes, 0); + if (!zero) written += bytes.len; + const data: DB.WriteableData = if (zero) .{ .slot = null } else .{ .bytes = bytes }; + if (i < had) try pages.put(@intCast(i), data) else try pages.append(data); + } + const n = std.math.divCeil(u64, q.size, page) catch unreachable; + if (had > n) try pages.slice(n); + try k.put(key(.written), .{ .uint = written }); + } + } + switch (ctx.extra) { + .none, .open => {}, + .stretch => |st| try putStretch(try List.init(try session.putCursor(key(.stretches))), st), + .mark => |m| { + const item = try Map.init(try (try List.init(try root.putCursor(key(.marks)))).appendCursor()); + try item.put(key(.name), .{ .bytes = m.name }); + try item.put(key(.session), .{ .uint = s.session }); + try item.put(key(.key), .{ .uint = m.key }); + }, + .clip => |c| { + const item = try Map.init(try (try List.init(try root.putCursor(key(.clips)))).appendCursor()); + try item.put(key(.name), .{ .bytes = c.name }); + try item.put(key(.session), .{ .uint = s.session }); + try item.put(key(.key), .{ .uint = c.key }); + try item.put(key(.start), .{ .uint = c.start }); + try item.put(key(.end), .{ .uint = 0 }); + }, + .clip_end => |c| { + const item = try Map.init(try (try List.init(try root.putCursor(key(.clips)))).putCursor(@intCast(c.index))); + try item.put(key(.end), .{ .uint = c.end }); + }, + .end => |t| try session.put(key(.ended), .{ .uint = t }), + } + } + + /// The slot of keyframe `at`'s pages; null for one from before pages. + fn pagesSlot(root: Map, at: At) !?xitdb.Slot { + const R = Read(DB); + const ses = try R.at(try R.list(root.readOnly(), .sessions) orelse return null, at.session); + return (try R.at(try R.list(ses, .keys) orelse return null, at.key)).getSlot(key(.pages)); + } + + fn putStretch(list: List, st: Stretch) !void { + const item = try Map.init(try list.appendCursor()); + try item.put(key(.frame), .{ .uint = st.frame }); + try item.put(key(.build), .{ .uint = st.build }); + try item.put(key(.source), .{ .bytes = st.source }); + try item.put(key(.layout), .{ .bytes = st.layout }); + } + }; +} + +// --------------------------------------------------------------------------- +// Reading + +/// A mark (`start` and `end` 0) or a clip. +pub const Entry = struct { + session: u64, + key: u64, + start: u64 = 0, + end: u64 = 0, + bytes: [max_name]u8 = undefined, + len: usize = 0, + + pub fn name(e: *const Entry) []const u8 { + return e.bytes[0..e.len]; + } +}; +/// A keyframe, its bytes `gpa`'s (`free`). +pub const Loaded = struct { + /// Stored in pages (not whole, from before them). + paged: bool = true, + frame: u64, + batch: u64, + why: Why, + time: u64, + state: []const u8, + line: []const u8, + /// Its stretch: the layout of `state`, and the build that wrote it. + stretch: u64, + build: u64, + source: []const u8, + layout: []const u8, + + pub fn free(l: Loaded, gpa: std.mem.Allocator) void { + for ([_][]const u8{ l.state, l.line, l.source, l.layout }) |b| gpa.free(b); + } +}; + +pub fn markAt(s: *Sessions, i: u64) !Entry { + return s.entryAt(.marks, i); +} +pub fn clipAt(s: *Sessions, i: u64) !Entry { + return s.entryAt(.clips, i); +} +/// The newest mark named `name`. +pub fn findMark(s: *Sessions, name: []const u8) !?Entry { + return s.findNamed(.marks, name); +} +/// The newest clip named `name`. +pub fn findClip(s: *Sessions, name: []const u8) !?Entry { + return s.findNamed(.clips, name); +} + +fn findNamed(s: *Sessions, which: K, name: []const u8) !?Entry { + var i = try s.count(which); + while (i > 0) { + i -= 1; + const e = try s.entryAt(which, i); + if (std.mem.eql(u8, e.name(), name)) return e; + } + return null; +} + +fn entryAt(s: *Sessions, which: K, i: u64) !Entry { + switch (s.db) { + .off => return error.NotRecording, + inline .memory, .file => |*db| { + const R = Read(@TypeOf(db.*)); + const e = try R.at(try R.list(try R.root(db), which) orelse return error.NoSuchEntry, i); + var out: Entry = .{ .session = try R.uint(e, .session), .key = try R.uint(e, .key) }; + out.len = ((try R.field(e, .name)).readBytes(&out.bytes) catch return error.CorruptSession).len; + if (which == .clips) { + out.start = try R.uint(e, .start); + out.end = try R.uint(e, .end); + } + return out; + }, + } +} + +/// Entries in the root list `which`, or sessions. +pub fn count(s: *Sessions, which: K) !u64 { + switch (s.db) { + .off => return error.NotRecording, + inline .memory, .file => |*db| { + const R = Read(@TypeOf(db.*)); + return if (try R.list(try R.root(db), which)) |l| try l.count() else 0; + }, + } +} + +/// Keyframe `k` of `session`, with its stretch. +pub fn load(s: *Sessions, session: u64, k: u64) !Loaded { + switch (s.db) { + .off => return error.NotRecording, + inline .memory, .file => |*db| { + const R = Read(@TypeOf(db.*)); + const ses = try R.session(db, session); + const e = try R.at(try R.list(ses, .keys) orelse return error.NoSuchKeyframe, k); + const st = try R.uint(e, .stretch); + const stretch_entry = try R.at(try R.list(ses, .stretches) orelse return error.CorruptSession, st); + const why = std.enums.fromInt(Why, try R.uint(e, .why)) orelse return error.CorruptSession; + const pages = try R.list(e, .pages); + const state = if (pages) |list| try R.pages(list, try R.uint(e, .size), s.gpa) else if (try e.getCursor(key(.state))) |whole| try whole.readBytesAlloc(s.gpa, null) else return error.HistoryDropped; + errdefer s.gpa.free(state); + const line = try R.bytes(e, .line, s.gpa); + errdefer s.gpa.free(line); + const source = try R.bytes(stretch_entry, .source, s.gpa); + errdefer s.gpa.free(source); + return .{ + .paged = pages != null, + .frame = try R.uint(e, .frame), + .batch = try R.uint(e, .batch), + .why = why, + .time = try R.uint(e, .time), + .state = state, + .line = line, + .stretch = st, + .build = try R.uint(stretch_entry, .build), + .source = source, + .layout = try R.bytes(stretch_entry, .layout, s.gpa), + }; + }, + } +} + +/// The State a run starts from, the present: the newest keyframe of the +/// sessions before this one, with the frames logged after it appended to +/// `out` (replayed, they bring it to where that run stopped). Null in a +/// new database. This run's first keyframe starts from its pages. +pub fn present(s: *Sessions, out: *std.ArrayList(abi.Event)) !?Loaded { + if (s.db == .off) return null; + var i = s.session; + while (i > 0) { + i -= 1; + const sum = try s.summary(i); + if (sum.keys == 0) continue; + const newest = try s.load(i, sum.keys - 1); + errdefer newest.free(s.gpa); + try s.events(i, newest.batch, newest.frame, sum.frames, out); + if (newest.paged) { + const hashes = try s.gpa.alloc(u64, std.math.divCeil(usize, newest.state.len, page) catch unreachable); + for (hashes, 0..) |*h, j| h.* = std.hash.Wyhash.hash(0, newest.state[j * page .. @min(newest.state.len, (j + 1) * page)]); + s.gpa.free(s.hashes); + s.hashes = hashes; + s.last = .{ .session = i, .key = sum.keys - 1 }; + } + return newest; + } + return null; +} + +/// Keyframe `k`'s frame, time and why, without its bytes. +pub fn keyAt(s: *Sessions, session: u64, k: u64) !struct { frame: u64, time: u64, why: Why } { + switch (s.db) { + .off => return error.NotRecording, + inline .memory, .file => |*db| { + const R = Read(@TypeOf(db.*)); + const e = try R.at(try R.list(try R.session(db, session), .keys) orelse return error.NoSuchKeyframe, k); + return .{ .frame = try R.uint(e, .frame), .time = try R.uint(e, .time), .why = std.enums.fromInt(Why, try R.uint(e, .why)) orelse return error.CorruptSession }; + }, + } +} + +/// The newest keyframe of `session` whose `by` (`.frame` or `.time`) is at +/// most `value`: a binary search. +pub fn keyBefore(s: *Sessions, session: u64, by: K, value: u64) !?u64 { + switch (s.db) { + .off => return error.NotRecording, + inline .memory, .file => |*db| { + const R = Read(@TypeOf(db.*)); + const keys = try R.list(try R.session(db, session), .keys) orelse return null; + var lo: u64 = 0; + var hi = try keys.count(); + while (lo < hi) { + const mid = lo + (hi - lo) / 2; + if (try R.uint(try R.at(keys, mid), by) <= value) lo = mid + 1 else hi = mid; + } + return if (lo == 0) null else lo - 1; + }, + } +} + +/// Appends to `out` the events of frames `start..end` of `session`, read +/// from batch `from` on. +pub fn events(s: *Sessions, session: u64, from: u64, start: u64, end: u64, out: *std.ArrayList(abi.Event)) !void { + switch (s.db) { + .off => return error.NotRecording, + inline .memory, .file => |*db| { + const R = Read(@TypeOf(db.*)); + const batches = try R.list(try R.session(db, session), .batches) orelse return; + const n = try batches.count(); + var i = from; + while (i < n) : (i += 1) { + const cursor = try batches.getCursor(@intCast(i)) orelse return error.CorruptSession; + if ((try cursor.slot()).tag == .none) return error.HistoryDropped; + const blob = try cursor.readBytesAlloc(s.gpa, null); + defer s.gpa.free(blob); + if (blob.len < 8 or (blob.len - 8) % @sizeOf(abi.Event) != 0) return error.CorruptSession; + var f = std.mem.readInt(u64, blob[0..8], .little); + if (f >= end) return; + var at: usize = 8; + while (at < blob.len) : (at += @sizeOf(abi.Event)) { + var e: abi.Event = undefined; + @memcpy(std.mem.asBytes(&e), blob[at..][0..@sizeOf(abi.Event)]); + if (f >= start) try out.append(s.gpa, e); + if (e.kind == .tick) f += 1; + if (f >= end) return; + } + } + }, + } +} + +/// Session `i`'s summary. +pub const Summary = struct { + started: u64, + ended: u64, + frames: u64, + stretches: u64, + keys: u64, + /// Where it came from ("import <file name>"), cut short. + from_bytes: [48]u8 = undefined, + from_len: usize = 0, + + pub fn from(m: *const Summary) []const u8 { + return m.from_bytes[0..m.from_len]; + } +}; + +pub fn summary(s: *Sessions, i: u64) !Summary { + switch (s.db) { + .off => return error.NotRecording, + inline .memory, .file => |*db| { + const R = Read(@TypeOf(db.*)); + const ses = try R.session(db, i); + var m: Summary = .{ + .started = try R.uint(ses, .started), + .ended = try R.uint(ses, .ended), + .frames = try R.uint(ses, .frames), + .stretches = if (try R.list(ses, .stretches)) |l| try l.count() else 0, + .keys = if (try R.list(ses, .keys)) |l| try l.count() else 0, + }; + const from = try R.bytes(ses, .from, s.gpa); + defer s.gpa.free(from); + m.from_len = @min(from.len, m.from_bytes.len); + @memcpy(m.from_bytes[0..m.from_len], from[0..m.from_len]); + return m; + }, + } +} + +// --------------------------------------------------------------------------- +// Export and import + +/// Writes session `i`, with the marks and clips in it (now of session 0), to +/// a new database at `path` (written beside it, synced, then renamed): a +/// playtest's sessions to send, which `import` reads. +pub fn exportSession(s: *Sessions, i: u64, path: []const u8) !void { + if (s.db == .off) return error.NotRecording; + if (i == s.session) try s.commit(.none); + if (i >= try s.count(.sessions)) return error.NoSuchSession; + const cwd = std.Io.Dir.cwd(); + var buf: [std.fs.max_path_bytes + 8]u8 = undefined; + const tmp = try std.fmt.bufPrint(&buf, "{s}.tmp", .{path}); + const file = try cwd.createFile(s.io, tmp, .{ .read = true, .truncate = true }); + errdefer cwd.deleteFile(s.io, tmp) catch {}; + defer file.close(s.io); + var buffer: std.Io.Writer.Allocating = .init(s.gpa); + defer buffer.deinit(); + var out = try Disk.init(s.io, .{ .file = file, .buffer = &buffer, .fsync = true }); + switch (s.db) { + .off => unreachable, + inline .memory, .file => |*db| try out.runContext(Transfer(@TypeOf(db.*), Disk){ .gpa = s.gpa, .from = db, .only = i, .label = null }), + } + try cwd.rename(tmp, cwd, path, s.io); +} + +/// Appends the sessions of the database at `path` (an `exportSession`'s) to +/// this one, their `from` "import <file name>", with their marks and clips, +/// named `<name>@<file name>` (cut to `max_name`). Returns the first one's +/// index. +pub fn import(s: *Sessions, path: []const u8) !u64 { + if (s.db == .off) return error.NotRecording; + const file = try std.Io.Dir.cwd().openFile(s.io, path, .{}); + defer file.close(s.io); + if (try file.length(s.io) == 0) return error.NotASessionsDatabase; + var buffer: std.Io.Writer.Allocating = .init(s.gpa); + defer buffer.deinit(); + var in = try Disk.init(s.io, .{ .file = file, .buffer = &buffer, .fsync = false }); + const first = try s.count(.sessions); + switch (s.db) { + .off => unreachable, + inline .memory, .file => |*db| try db.runContext(Transfer(Disk, @TypeOf(db.*)){ .gpa = s.gpa, .from = &in, .only = null, .label = std.fs.path.basename(path) }), + } + return first; +} + +/// A transaction appending database `from`'s sessions (`only` one, else +/// all) to the one it runs in, with the marks and clips pointing into them; +/// `label`, an import's file name, goes in their `from` and names. +fn Transfer(comptime From: type, comptime To: type) type { + return struct { + gpa: std.mem.Allocator, + from: *From, + only: ?u64, + label: ?[]const u8, + + const R = Read(From); + const Map = To.HashMap(.read_write); + const List = To.ArrayList(.read_write); + + pub fn run(ctx: @This(), cursor: *To.Cursor(.read_write)) !void { + var copied: std.AutoHashMap(u64, xitdb.Slot) = .init(ctx.gpa); + defer copied.deinit(); + const src = try R.root(ctx.from); + if (try R.uint(src, .version) != 1) return error.NotASessionsDatabase; + const all = try R.list(src, .sessions) orelse return error.NotASessionsDatabase; + const root = try Map.init(cursor.*); + try root.put(key(.version), .{ .uint = 1 }); + const sessions = try List.init(try root.putCursor(key(.sessions))); + const base = try sessions.count(); + var buf: [std.fs.max_path_bytes + 8]u8 = undefined; + for (0..try all.count()) |i| { + if (ctx.only) |o| if (o != i) continue; + var to = try sessions.appendCursor(); + try copy(From, To, ctx.gpa, try all.getCursor(@intCast(i)) orelse return error.CorruptSession, &to, &copied); + if (ctx.label) |l| try (try Map.init(to)).put(key(.from), .{ .bytes = try std.fmt.bufPrint(&buf, "import {s}", .{l}) }); + } + for ([_]K{ .marks, .clips }) |which| { + const entries = try R.list(src, which) orelse continue; + const list = try List.init(try root.putCursor(key(which))); + var it = try entries.iterator(); + while (try it.next()) |e| { + const session = try R.uint(try R.Map.init(e), .session); + if (ctx.only) |o| if (o != session) continue; + var to = try list.appendCursor(); + try copy(From, To, ctx.gpa, e, &to, &copied); + const item = try Map.init(to); + try item.put(key(.session), .{ .uint = base + if (ctx.only == null) session else 0 }); + const l = ctx.label orelse continue; + var name: [max_name]u8 = undefined; + const old = (try R.field(try R.Map.init(e), .name)).readBytes(&name) catch return error.CorruptSession; + const new = std.fmt.bufPrint(&buf, "{s}@{s}", .{ old, l }) catch unreachable; + try item.put(key(.name), .{ .bytes = new[0..@min(new.len, max_name)] }); + } + } + } + }; +} + +/// Copies the value at `from` (a uint, bytes, or a list or map of them) to +/// `to`. Bytes `copied` already (a page keyframes share) are written once: +/// it maps their place in `from` to their slot in `to`. +fn copy(comptime From: type, comptime To: type, gpa: std.mem.Allocator, from: From.Cursor(.read_only), to: *To.Cursor(.read_write), copied: *std.AutoHashMap(u64, xitdb.Slot)) anyerror!void { + const slot = try from.slot(); + switch (slot.tag) { + .none => try to.write(.{ .slot = null }), + .uint => try to.write(.{ .uint = try from.readUint() }), + .bytes, .short_bytes => { + if (slot.tag == .bytes) if (copied.get(slot.value)) |done| return to.write(.{ .slot = done }); + const bytes = try from.readBytesAlloc(gpa, null); + defer gpa.free(bytes); + try to.write(.{ .bytes = bytes }); + if (slot.tag == .bytes) try copied.put(slot.value, try to.slot()); + }, + .array_list => { + const list = try To.ArrayList(.read_write).init(to.*); + var it = try from.iterator(); + while (try it.next()) |c| { + var next = try list.appendCursor(); + try copy(From, To, gpa, c, &next, copied); + } + }, + .hash_map => { + const map = try To.HashMap(.read_write).init(to.*); + var it = try from.iterator(); + while (try it.next()) |c| { + const kv = try c.readKeyValuePair(); + var next = try map.putCursor(kv.hash); + try copy(From, To, gpa, kv.value_cursor, &next, copied); + } + }, + else => return error.CorruptSession, + } +} + +fn Read(comptime DB: type) type { + return struct { + const Map = DB.HashMap(.read_only); + const List = DB.ArrayList(.read_only); + + fn root(db: *DB) !Map { + return Map.init(db.rootCursor().readOnly()); + } + fn session(db: *DB, i: u64) !Map { + return at(try list(try root(db), .sessions) orelse return error.NoSuchSession, i); + } + fn field(map: Map, k: K) !DB.Cursor(.read_only) { + return try map.getCursor(key(k)) orelse error.CorruptSession; + } + fn uint(map: Map, k: K) !u64 { + return (try field(map, k)).readUint(); + } + fn bytes(map: Map, k: K, gpa: std.mem.Allocator) ![]const u8 { + return (try field(map, k)).readBytesAlloc(gpa, null); + } + /// `size` bytes from a keyframe's pages, `gpa`'s. + fn pages(l: List, size: u64, gpa: std.mem.Allocator) ![]u8 { + const out = try gpa.alloc(u8, size); + errdefer gpa.free(out); + @memset(out, 0); + for (0..try l.count()) |i| { + const c = try l.getCursor(@intCast(i)) orelse continue; + if ((try c.slot()).tag == .none) continue; + const into = out[@min(size, i * page)..@min(size, (i + 1) * page)]; + if ((c.readBytes(into) catch return error.CorruptSession).len != into.len) return error.CorruptSession; + } + return out; + } + fn list(map: Map, k: K) !?List { + return try List.init(try map.getCursor(key(k)) orelse return null); + } + fn at(l: List, i: u64) !Map { + if (i >= try l.count()) return error.NoSuchEntry; + return Map.init(try l.getCursor(@intCast(i)) orelse return error.NoSuchEntry); + } + }; +} + +test "frames written to a session read back byte for byte, in memory and through a reopened file" { + const gpa = std.testing.allocator; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var buf: [std.fs.max_path_bytes]u8 = undefined; + const path = try std.fmt.bufPrint(&buf, ".zig-cache/tmp/{s}/t.xitdb", .{&tmp.sub_path}); + const layout = "a layout"; + for ([_]Mode{ .memory, .file }) |m| { + var s = try open(gpa, std.testing.io, m, path, .{ .build = 7, .source = "jj:abc", .layout = layout }, 1000); + var live: std.ArrayList(abi.Event) = .empty; + defer live.deinit(gpa); + // Three seconds at 60 Hz, a move in every third frame; the state is + // the frame count, so keyframes differ. + var state: u64 = 0; + for (0..180) |f| { + const t = std.time.ns_per_s + f * std.time.ns_per_s / 60; + var frame_events: [2]abi.Event = .{ .{ .kind = .mouse_move, .time = t, .x = @floatFromInt(f) }, abi.Event.tick(t, std.time.ns_per_s / 60) }; + const one = if (f % 3 == 0) frame_events[0..] else frame_events[1..]; + try s.frame(one, std.mem.asBytes(&state), if (f == 0) .start else if (f == 90) .jump else null); + try live.appendSlice(gpa, one); + state += 1; + } + // Two commits of a second each; the third second is pending. + try std.testing.expectEqual(@as(u64, 2), s.batches); + try s.commit(.none); + try std.testing.expectEqual(@as(u64, 2), s.keys); + var back: std.ArrayList(abi.Event) = .empty; + defer back.deinit(gpa); + try s.events(s.session, 0, 0, 180, &back); + try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(live.items), std.mem.sliceAsBytes(back.items)); + // From the jump's keyframe: frame 90 on, its state 90. + const k = (try s.keyBefore(s.session, .frame, 100)).?; + try std.testing.expectEqual(@as(u64, 1), k); + const loaded = try s.load(s.session, k); + defer loaded.free(gpa); + try std.testing.expectEqual(@as(u64, 90), loaded.frame); + try std.testing.expectEqual(@as(u64, 90), std.mem.bytesToValue(u64, loaded.state)); + try std.testing.expectEqualStrings(layout, loaded.layout); + try std.testing.expectEqual(@as(u64, 7), loaded.build); + back.clearRetainingCapacity(); + try s.events(s.session, loaded.batch, 90, 92, &back); + try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(live.items[120..][0..3]), std.mem.sliceAsBytes(back.items)); + try std.testing.expectEqual(@as(?u64, 0), try s.keyBefore(s.session, .frame, 0)); + if (m == .memory) { + s.deinit(); + continue; + } + s.close(std.mem.asBytes(&state), 2000); + // Reopened: the first session ended, its frames all there; a new one. + var again = try open(gpa, std.testing.io, .file, path, .{ .build = 8, .source = "", .layout = layout }, 3000); + defer again.deinit(); + try std.testing.expectEqual(@as(u64, 1), again.session); + const first = try again.summary(0); + try std.testing.expectEqual(@as(u64, 180), first.frames); + try std.testing.expectEqual(@as(u64, 2000), first.ended); + back.clearRetainingCapacity(); + try again.events(0, 0, 0, 180, &back); + try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(live.items), std.mem.sliceAsBytes(back.items)); + } +} + +test "a session database torn inside its last commit opens at the one before, every earlier session and frame in it; one that cannot be mended is kept aside" { + const gpa = std.testing.allocator; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var buf: [std.fs.max_path_bytes]u8 = undefined; + const path = try std.fmt.bufPrint(&buf, ".zig-cache/tmp/{s}/t.xitdb", .{&tmp.sub_path}); + const first: Stretch = .{ .build = 7, .source = "", .layout = "a layout" }; + var live: std.ArrayList(abi.Event) = .empty; + defer live.deinit(gpa); + var state: u64 = 0; + // Session 0: 120 frames, closed. Session 1: 180 frames in three commits + // of a second, then the process gone (no exit commit). + var before: u64 = 0; + var whole: u64 = 0; + for ([_]u64{ 120, 180 }, 0..) |frames, session| { + var s = try open(gpa, io, .file, path, first, 1000 + session); + for (0..frames) |f| { + const t = f * std.time.ns_per_s / 60; + var one = [_]abi.Event{abi.Event.tick(t, std.time.ns_per_s / 60)}; + try s.frame(&one, std.mem.asBytes(&state), if (f == 0) .start else null); + try live.appendSlice(gpa, &one); + state += 1; + } + if (session == 0) { + s.close(std.mem.asBytes(&state), 2000); + continue; + } + before = try s.file.?.length(io); + try s.commit(.none); + whole = try s.file.?.length(io); + s.deinit(); + } + const bytes = try tmp.dir.readFileAlloc(io, "t.xitdb", gpa, .unlimited); + defer gpa.free(bytes); + try std.testing.expectEqual(whole, bytes.len); + for ([_]u64{ before, before + 1, (before + whole) / 2, whole - trailer_len, whole - 10, whole - 1 }) |cut| { + errdefer std.debug.print("cut at {d} of {d}..{d}\n", .{ cut, before, whole }); + try tmp.dir.writeFile(io, .{ .sub_path = "t.xitdb", .data = bytes[0..cut] }); + var s = try open(gpa, io, .file, path, first, 3000); + defer s.deinit(); + try std.testing.expectEqual(@as(u64, 2), s.session); + const s0 = try s.summary(0); + try std.testing.expectEqual(@as(u64, 120), s0.frames); + try std.testing.expectEqual(@as(u64, 2000), s0.ended); + const s1 = try s.summary(1); + try std.testing.expectEqual(@as(u64, 120), s1.frames); + try std.testing.expectEqual(@as(u64, 0), s1.ended); + var back: std.ArrayList(abi.Event) = .empty; + defer back.deinit(gpa); + try s.events(0, 0, 0, 120, &back); + try s.events(1, 0, 0, 120, &back); + try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(live.items[0..240]), std.mem.sliceAsBytes(back.items)); + var dir = try tmp.dir.openDir(io, ".", .{ .iterate = true }); + defer dir.close(io); + var it = dir.iterate(); + while (try it.next(io)) |e| try std.testing.expectEqualStrings("t.xitdb", e.name); + } + // Nothing whole to open at: kept aside as it was, a new database begun. + var torn = try gpa.dupe(u8, bytes); + defer gpa.free(torn); + @memset(torn[root_header_end..], 0); + try tmp.dir.writeFile(io, .{ .sub_path = "t.xitdb", .data = torn }); + var s = try open(gpa, io, .file, path, first, 4 * std.time.ns_per_s); + defer s.deinit(); + try std.testing.expectEqual(@as(u64, 0), s.session); + const aside = try tmp.dir.readFileAlloc(io, "t.xitdb.broken.4", gpa, .unlimited); + defer gpa.free(aside); + try std.testing.expectEqualSlices(u8, torn, aside); +} + +test "a compacted session database is smaller and holds every session and frame" { + const gpa = std.testing.allocator; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var buf: [std.fs.max_path_bytes]u8 = undefined; + const path = try std.fmt.bufPrint(&buf, ".zig-cache/tmp/{s}/t.xitdb", .{&tmp.sub_path}); + const first: Stretch = .{ .build = 7, .source = "", .layout = "a layout" }; + var live: std.ArrayList(abi.Event) = .empty; + defer live.deinit(gpa); + var s = try open(gpa, io, .file, path, first, 1000); + var state: u64 = 0; + for (0..600) |f| { + const t = f * std.time.ns_per_s / 60; + var one = [_]abi.Event{abi.Event.tick(t, std.time.ns_per_s / 60)}; + try s.frame(&one, std.mem.asBytes(&state), if (f == 0) .start else if (f % 100 == 0) .jump else null); + try live.appendSlice(gpa, &one); + state += 1; + } + try s.commit(.none); + const size = try s.file.?.length(io); + const live_size = try liveSize(&s.db.file); + // Six keyframes of 8 bytes, the first all zeros: an empty page. + try std.testing.expectEqual(@as(u64, 600 * @sizeOf(abi.Event) + 10 * 8 + 5 * 8), live_size); + try s.compact(); + s.deinit(); + const compacted = (try tmp.dir.statFile(io, "t.xitdb", .{})).size; + try std.testing.expect(compacted < size); + var again = try open(gpa, io, .file, path, first, 2000); + defer again.deinit(); + try std.testing.expectEqual(@as(u64, 600), (try again.summary(0)).frames); + try std.testing.expectEqual(@as(u64, 6), (try again.summary(0)).keys); + var back: std.ArrayList(abi.Event) = .empty; + defer back.deinit(gpa); + try again.events(0, 0, 0, 600, &back); + try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(live.items), std.mem.sliceAsBytes(back.items)); +} + +test "a memory session stops recording at its bound, and what it holds still reads" { + const gpa = std.testing.allocator; + var s = try open(gpa, std.testing.io, .memory, "", .{ .build = 7, .source = "", .layout = "a layout" }, 0); + defer s.deinit(); + s.db.memory.core.max_size = 64 << 10; + var live: std.ArrayList(abi.Event) = .empty; + defer live.deinit(gpa); + var state: u64 = 0; + var failed: usize = 0; + for (0..60 * 60) |f| { + const t = f * std.time.ns_per_s / 60; + var one = [_]abi.Event{abi.Event.tick(t, std.time.ns_per_s / 60)}; + s.frame(&one, std.mem.asBytes(&state), if (f == 0) .start else null) catch |err| { + try std.testing.expectEqual(error.WriteFailed, err); + failed += 1; + }; + try live.appendSlice(gpa, &one); + state += 1; + } + try std.testing.expectEqual(@as(usize, 1), failed); + const n = (try s.summary(s.session)).frames; + try std.testing.expect(n >= 60 and n < 60 * 60); + var back: std.ArrayList(abi.Event) = .empty; + defer back.deinit(gpa); + try s.events(s.session, 0, 0, n, &back); + try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(live.items[0..n]), std.mem.sliceAsBytes(back.items)); +} + +test "a session's keyframes write only the pages that changed: a State of megabytes edited each minute, and one never changed" { + const gpa = std.testing.allocator; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var buf: [std.fs.max_path_bytes]u8 = undefined; + const path = try std.fmt.bufPrint(&buf, ".zig-cache/tmp/{s}/t.xitdb", .{&tmp.sub_path}); + // 4 MiB, every page holding something, one u64 edited a minute. + const state = try gpa.alloc(u8, 4 << 20); + defer gpa.free(state); + for (state, 0..) |*b, i| b.* = @truncate(i *% 7 + 1); + var s = try open(gpa, io, .file, path, .{ .build = 7, .source = "", .layout = "a layout" }, 1000); + defer s.deinit(); + const minutes = 10; + var sizes: [minutes + 1]u64 = undefined; + for (0..minutes * 60 * 60) |f| { + const t = f * std.time.ns_per_s / 60; + var one = [_]abi.Event{abi.Event.tick(t, std.time.ns_per_s / 60)}; + if (f % 3600 == 1800) std.mem.writeInt(u64, state[(f / 3600) * 300_000 ..][0..8], f, .little); + try s.frame(&one, state, if (f == 0) .start else null); + if (f % 3600 == 0) { + try s.commit(.none); + sizes[f / 3600] = try s.file.?.length(io); + } + } + try s.commit(.none); + sizes[minutes] = try s.file.?.length(io); + // One keyframe a minute: at 0 s, 60 s, ... + try std.testing.expectEqual(@as(u64, minutes), s.keys); + // A minute is 216,000 bytes of ticks and a keyframe of one page with + // its copied path: under 230 KB a minute, where a whole State a + // keyframe was 4 MiB. + for (1..minutes) |m| try std.testing.expect(sizes[m + 1] - sizes[m] < 230_000); + // Every keyframe reads back whole: the edits made before it, and none after. + const want = try gpa.alloc(u8, state.len); + defer gpa.free(want); + for (0..minutes) |k| { + for (want, 0..) |*b, i| b.* = @truncate(i *% 7 + 1); + for (0..k) |m| std.mem.writeInt(u64, want[m * 300_000 ..][0..8], m * 3600 + 1800, .little); + const loaded = try s.load(s.session, k); + defer loaded.free(gpa); + try std.testing.expectEqual(@as(u64, k * 3600), loaded.frame); + try std.testing.expectEqualSlices(u8, want, loaded.state); + } + // A keyframe alone, in a commit of its own: one changed page is that + // page, its copied path and the keyframe's fields; no changed page (one + // kept before a reload) is the fields alone. + for ([_]bool{ true, false }) |edit| { + if (edit) state[123] +%= 1; + const before = try s.file.?.length(io); + _ = try s.keyframe(if (edit) .jump else .before_reload, state); + try s.commit(.none); + try std.testing.expect(try s.file.?.length(io) - before < @as(u64, if (edit) 12 << 10 else 8 << 10)); + } + const last = try s.load(s.session, s.keys - 1); + defer last.free(gpa); + try std.testing.expectEqualSlices(u8, state, last.state); +} + +test "an exported session keeps its keyframes' shared pages shared" { + const gpa = std.testing.allocator; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var buf: [std.fs.max_path_bytes]u8 = undefined; + const path = try std.fmt.bufPrint(&buf, ".zig-cache/tmp/{s}/t.xitdb", .{&tmp.sub_path}); + var out_buf: [std.fs.max_path_bytes]u8 = undefined; + const out = try std.fmt.bufPrint(&out_buf, ".zig-cache/tmp/{s}/one.xitdb", .{&tmp.sub_path}); + const state = try gpa.alloc(u8, 1 << 20); + defer gpa.free(state); + for (state, 0..) |*b, i| b.* = @truncate(i *% 13 + 1); + var s = try open(gpa, io, .file, path, .{ .build = 7, .source = "", .layout = "a layout" }, 1000); + defer s.deinit(); + // Ten keyframes a byte apart. + for (0..600) |f| { + const t = f * std.time.ns_per_s / 60; + var one = [_]abi.Event{abi.Event.tick(t, std.time.ns_per_s / 60)}; + if (f % 60 == 0) state[f * 100] +%= 1; + try s.frame(&one, state, if (f == 0) .start else if (f % 60 == 0) .jump else null); + } + try s.exportSession(0, out); + const size = (try std.Io.Dir.cwd().statFile(io, out, .{})).size; + // One State and nine pages, not ten States. + try std.testing.expect(size < state.len + state.len / 8); + var again = try open(gpa, io, .file, out, .{ .build = 7, .source = "", .layout = "a layout" }, 2000); + defer again.deinit(); + const loaded = try again.load(0, 9); + defer loaded.free(gpa); + try std.testing.expectEqualSlices(u8, state, loaded.state); +} + +test "a session database past max_save drops its oldest history: the present and the marks stay, the file under it" { + const gpa = std.testing.allocator; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var buf: [std.fs.max_path_bytes]u8 = undefined; + const path = try std.fmt.bufPrint(&buf, ".zig-cache/tmp/{s}/t.xitdb", .{&tmp.sub_path}); + // 2 MiB of State, its first half rewritten each second: a keyframe + // writes 1 MiB, so the cap is reached at about the 60th. + const state = try gpa.alloc(u8, 2 << 20); + defer gpa.free(state); + @memset(state, 1); + var s = try open(gpa, io, .file, path, .{ .build = 7, .source = "", .layout = "a layout" }, 1000); + defer s.deinit(); + for (0..100) |k| { + @memset(state[0 .. 1 << 20], @truncate(k + 2)); + var one = [_]abi.Event{abi.Event.tick(k * std.time.ns_per_s, std.time.ns_per_s)}; + try s.frame(&one, state, if (k == 0) .start else .jump); + if (k == 5) _ = try s.mark("a", .mark, state); + if (k == 20) _ = try s.mark("b", .mark, state); + try std.testing.expect(try s.file.?.length(io) <= max_save); + } + try s.commit(.none); + // The oldest keyframes and frames are gone; the marks and the newest + // keyframe read back whole. + try std.testing.expectError(error.HistoryDropped, s.load(0, 1)); + var log: std.ArrayList(abi.Event) = .empty; + defer log.deinit(gpa); + try std.testing.expectError(error.HistoryDropped, s.events(0, 0, 0, 2, &log)); + for ([_]struct { []const u8, u8 }{ .{ "a", 7 }, .{ "b", 22 } }) |want| { + const m = (try s.findMark(want[0])).?; + const loaded = try s.load(m.session, m.key); + defer loaded.free(gpa); + try std.testing.expectEqual(want[1], loaded.state[0]); + try std.testing.expectEqual(@as(u8, 1), loaded.state[1 << 20]); + } + const newest = try s.load(0, s.keys - 1); + defer newest.free(gpa); + try std.testing.expectEqualSlices(u8, state, newest.state); + try s.events(0, newest.batch, newest.frame, s.frames, &log); +} + +test "a session database without history keeps the present and the marks, and leaves nothing else at exit" { + const gpa = std.testing.allocator; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var buf: [std.fs.max_path_bytes]u8 = undefined; + const path = try std.fmt.bufPrint(&buf, ".zig-cache/tmp/{s}/t.xitdb", .{&tmp.sub_path}); + var state: [64 << 10]u8 = @splat(1); + var s = try open(gpa, io, .file, path, .{ .build = 7, .source = "", .layout = "a layout" }, 1000); + s.history = false; + for (0..20) |k| { + @memset(state[0 .. 32 << 10], @truncate(k + 2)); + var one = [_]abi.Event{abi.Event.tick(k * std.time.ns_per_s, std.time.ns_per_s)}; + try s.frame(&one, &state, if (k == 0) .start else .jump); + if (k == 3) _ = try s.mark("a", .mark, &state); + } + try s.commit(.none); + try std.testing.expectError(error.HistoryDropped, s.load(0, 1)); + const m = (try s.findMark("a")).?; + const loaded = try s.load(m.session, m.key); + loaded.free(gpa); + s.close(&state, 2000); + // At exit: compacted to the present, the mark and the session's fields. + try std.testing.expect((try tmp.dir.statFile(io, "t.xitdb", .{})).size < 3 * state.len); + var again = try open(gpa, io, .file, path, .{ .build = 7, .source = "", .layout = "a layout" }, 3000); + defer again.deinit(); + var log: std.ArrayList(abi.Event) = .empty; + defer log.deinit(gpa); + const now = (try again.present(&log)).?; + defer now.free(gpa); + try std.testing.expectEqualSlices(u8, &state, now.state); +} + +test "a session database full of marks refuses a mark of a new name, and takes one over an old name" { + const gpa = std.testing.allocator; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var buf: [std.fs.max_path_bytes]u8 = undefined; + const path = try std.fmt.bufPrint(&buf, ".zig-cache/tmp/{s}/t.xitdb", .{&tmp.sub_path}); + // 2 MiB of State, all of it changed for each mark. + const state = try gpa.alloc(u8, 2 << 20); + defer gpa.free(state); + var s = try open(gpa, io, .file, path, .{ .build = 7, .source = "", .layout = "a layout" }, 1000); + defer s.deinit(); + var name: [8]u8 = undefined; + var k: u8 = 0; + while (true) : (k += 1) { + @memset(state, k + 1); + _ = s.mark(try std.fmt.bufPrint(&name, "m{d}", .{k}), .mark, state) catch |err| { + try std.testing.expectEqual(error.SaveFull, err); + break; + }; + try std.testing.expect(k < 40 and try s.file.?.length(io) <= max_save); + } + try std.testing.expect(k > 20); + @memset(state, 99); + try std.testing.expectError(error.SaveFull, s.mark("new", .mark, state)); + _ = try s.mark("m3", .mark, state); + try s.commit(.none); + try std.testing.expect(try s.file.?.length(io) <= max_save); + // Every mark's newest keyframe is whole. + for (0..k) |i| { + const m = (try s.findMark(try std.fmt.bufPrint(&name, "m{d}", .{i}))).?; + const loaded = try s.load(m.session, m.key); + defer loaded.free(gpa); + try std.testing.expectEqual(@as(u8, if (i == 3) 99 else @intCast(i + 1)), loaded.state[state.len - 1]); + } +} diff --git a/src/host/audio.zig b/src/host/audio.zig index aebb909..880be72 100644 --- a/src/host/audio.zig +++ b/src/host/audio.zig @@ -11,6 +11,9 @@ pub const sample_rate = 48_000; const spec: c.SDL_AudioSpec = .{ .format = c.SDL_AUDIO_F32, .channels = 1, .freq = sample_rate }; /// A device block plus the next frame; 512 samples can underrun at 60 Hz. const queue_samples = 2048; +/// How far a group's gain moves a sample toward a new one: a full swing +/// takes 10 ms, so a gain set in a step does not click. +const gain_step = 1.0 / 480.0; pub const Audio = struct { gpa: std.mem.Allocator, @@ -20,8 +23,24 @@ pub const Audio = struct { clips: std.ArrayList([]f32) = .empty, paths: std.StringHashMapUnmanaged(abi.Audio) = .empty, voices: std.ArrayList(Playing) = .empty, + /// Each group's gain as declared this frame, and as the mix has got to. + gains: [8]f32 = @splat(1), + heard_gains: [8]f32 = @splat(1), streams: std.ArrayList(Stream) = .empty, status: std.ArrayList(abi.Stream) = .empty, + /// Samples the device takes from each stream at once. + pull: u32 = 1024, + /// The wall-clock time (ns) between the ends of the last frames' + /// commands, where pushes are done; and when the last ended. + intervals: [64]u64 = @splat(0), + frame: u64 = 0, + last_frame: u64 = 0, + /// Grown by underruns, shrinking back while there are none. + margin: u32 = 0, + /// A stream ran dry since the lead was last worked out. + dry: bool = false, + /// `Input.lead`: see `lead`. + lead: u32 = 4800, scope: Scope = .{}, /// The default recording device, bound to this stream while declared. microphone: ?*c.SDL_AudioStream = null, @@ -29,13 +48,38 @@ pub const Audio = struct { /// Set when opening failed, so it is tried once per declaration. deaf: bool = false, - const Playing = struct { voice: abi.Voice, cursor: usize = 0, done: bool = false, seen: bool = true }; - const Stream = struct { key: u32, out: *c.SDL_AudioStream, pushed: u64 = 0 }; + const Playing = struct { + voice: abi.Voice, + /// Where in the sound, in its samples: fractional when `rate` is. + cursor: f64 = 0, + done: bool = false, + seen: bool = true, + /// Mixed since a script last asked (`expect-audio`). + sounded: bool = false, + }; + const Stream = struct { + key: u32, + out: *c.SDL_AudioStream, + pushed: u64 = 0, + /// Pushed to this frame, and the last. + fed: bool = false, + was_fed: bool = false, + underruns: u32 = 0, + }; - pub fn open(self: *Audio) !void { + /// The default playback device, taking `pull` samples at once if asked + /// (`abi.Info.audio_pull`): a hint, so the environment's wins. + pub fn open(self: *Audio, pull: u32) !void { + var hint: [16]u8 = undefined; + if (pull > 0) _ = c.SDL_SetHint(c.SDL_HINT_AUDIO_DEVICE_SAMPLE_FRAMES, try std.fmt.bufPrintSentinel(&hint, "{d}", .{pull}, 0)); const device = c.SDL_OpenAudioDevice(c.SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &spec); if (device == 0) return error.OpenAudio; self.device = device; + var format: c.SDL_AudioSpec = undefined; + var frames: c_int = 0; + if (c.SDL_GetAudioDeviceFormat(device, &format, &frames) and frames > 0 and format.freq > 0) { + self.pull = @intCast(@divFloor(@as(i64, frames) * sample_rate + format.freq - 1, format.freq)); + } self.voices_out = try self.bind(); self.scope.attach(device) catch {}; } @@ -81,6 +125,12 @@ pub const Audio = struct { return self.add(decodeBytes(self.gpa, wav) catch return .none); } + /// A copy of `samples`; `.none` if one is not finite. + pub fn new(self: *Audio, samples: []const f32) abi.Audio { + for (samples) |v| if (!std.math.isFinite(v)) return .none; + return self.add(self.gpa.dupe(f32, samples) catch return .none); + } + fn add(self: *Audio, samples: []f32) abi.Audio { self.clips.append(self.gpa, samples) catch { self.gpa.free(samples); @@ -97,6 +147,7 @@ pub const Audio = struct { pub fn beginFrame(self: *Audio) void { for (self.voices.items) |*v| v.seen = false; + self.gains = @splat(1); self.listening = false; } @@ -155,9 +206,18 @@ pub const Audio = struct { if (clear) { _ = c.SDL_ClearAudioStream(s.out); s.pushed = 0; + s.was_fed = false; } if (samples.len == 0) return; + // Fed last frame and empty now: the device came up short since + // (counted at the push, as a pull before it would hide it by the + // next frame). + if (s.was_fed and !s.fed and c.SDL_GetAudioStreamQueued(s.out) == 0) { + s.underruns += 1; + self.dry = true; + } if (c.SDL_PutAudioStreamData(s.out, samples.ptr, @intCast(samples.len * @sizeOf(f32)))) s.pushed += samples.len; + s.fed = true; } fn streamFor(self: *Audio, key: u32) ?*Stream { @@ -171,14 +231,22 @@ pub const Audio = struct { return &self.streams.items[self.streams.items.len - 1]; } - /// Drops undeclared voices, keeps the voice mix queued ahead, and opens - /// or closes the microphone. + /// Drops undeclared voices, works out the lead for the next frame, keeps + /// the voice mix queued ahead, and opens or closes the microphone. pub fn endFrame(self: *Audio) void { self.reconcileMicrophone(); var i: usize = 0; while (i < self.voices.items.len) { if (self.voices.items[i].seen) i += 1 else _ = self.voices.swapRemove(i); } + const now = c.SDL_GetTicksNS(); + if (self.last_frame != 0) { + self.intervals[self.frame % self.intervals.len] = now -| self.last_frame; + self.frame += 1; + } + self.last_frame = now; + self.lead = lead(self.intervals, self.pull, &self.margin, self.dry); + self.dry = false; const out = self.voices_out orelse return; const queued = c.SDL_GetAudioStreamQueued(out); if (queued < 0) return; @@ -189,45 +257,98 @@ pub const Audio = struct { } /// Mixes live voices into `output`; returns how many samples were written, - /// stopping early once every voice has finished. + /// stopping early once every voice has finished. A voice at another + /// rate is resampled by linear interpolation between its neighbours + /// (at rate 1 it is its samples, exactly). pub fn mix(self: *Audio, output: []f32) usize { var count: usize = 0; for (output) |*sample| { var sum: f32 = 0; var alive = false; + for (&self.heard_gains, self.gains) |*heard, gain| heard.* += std.math.clamp(gain - heard.*, -gain_step, gain_step); for (self.voices.items) |*playing| { if (playing.done) continue; const samples = self.samplesOf(playing.voice.audio); - if (playing.cursor >= samples.len) { + const len: f64 = @floatFromInt(samples.len); + // Also ends a cursor an infinite or NaN rate made. + if (!(playing.cursor < len)) { playing.done = true; continue; } alive = true; + playing.sounded = true; const v = playing.voice; - const edge = @min(playing.cursor + 1, samples.len - playing.cursor); + const i: usize = @intFromFloat(playing.cursor); + const t: f32 = @floatCast(playing.cursor - @floor(playing.cursor)); + const next = if (i + 1 < samples.len) samples[i + 1] else if (v.loop) samples[0] else 0; + const at = if (t == 0) samples[i] else samples[i] + (next - samples[i]) * t; + const edge = @min(i + 1, samples.len - i); const fade: f32 = if (v.fade == 0) 1 else @as(f32, @floatFromInt(@min(edge, v.fade))) / @as(f32, @floatFromInt(v.fade)); - sum += samples[playing.cursor] * v.volume * fade; - playing.cursor += 1; - if (playing.cursor == samples.len and v.loop) playing.cursor = 0; + sum += at * v.volume * self.heard_gains[v.group] * fade; + playing.cursor += @max(v.rate, 0); + if (playing.cursor >= len and v.loop) playing.cursor = @mod(playing.cursor, len); } if (!alive) break; - // Bounded however many voices sound at once. - sample.* = sum / (1 + @abs(sum)); + sample.* = limit(sum); count += 1; } return count; } + /// Whether voice `key` was mixed since the last call: for scripts. + pub fn sounded(self: *Audio, key: u32) bool { + for (self.voices.items) |*playing| if (playing.voice.key == key) { + defer playing.sounded = false; + return playing.sounded; + }; + return false; + } + + /// The streams as a frame starts. pub fn streamStatus(self: *Audio) []const abi.Stream { self.status.clearRetainingCapacity(); - for (self.streams.items) |s| { - const queued = c.SDL_GetAudioStreamQueued(s.out); - self.status.append(self.gpa, .{ .key = s.key, .queued = @intCast(@divFloor(@max(queued, 0), @sizeOf(f32))), .pushed = s.pushed }) catch {}; + for (self.streams.items) |*s| { + const queued: u32 = @intCast(@divFloor(@max(c.SDL_GetAudioStreamQueued(s.out), 0), @sizeOf(f32))); + s.was_fed = s.fed; + s.fed = false; + self.status.append(self.gpa, .{ .key = s.key, .queued = queued, .pushed = s.pushed, .underruns = s.underruns }) catch {}; } return self.status.items; } }; +/// How many samples to keep queued: the slowest of the last frames' worth +/// (pushes come once a frame, `intervals` apart), plus the device's pull +/// (it takes that much at once), plus `margin`: half a pull more at each +/// underrun (`dry`), back down by a sample a frame. +fn lead(intervals: [64]u64, pull: u32, margin: *u32, dry: bool) u32 { + var slowest: u64 = 0; + for (intervals) |ns| slowest = @max(slowest, ns); + margin.* = if (dry) @min(margin.* + pull / 2, max_lead) else margin.* -| 1; + const frame: u32 = @intCast(@min(slowest * sample_rate / std.time.ns_per_s, 1 << 20)); + return @min(frame + pull + margin.*, max_lead); +} +/// 170 ms: a frame slower than that is a stall, not a pace. +const max_lead = 8192; + +/// Where the voice mix stops being passed through: -2.5 dBFS. Quieter +/// mixes keep their true volume to the bit; a clip normalised to full scale +/// only has its peaks bent (1 comes out at 0.875). +pub const knee = 0.75; + +/// The voice mix, bounded however many voices sound at once: unity gain up +/// to the knee, then `knee + (1 - knee)·u/(1 + u)` with `u` how far past the +/// knee in units of the room left, which meets the line at the knee with +/// its slope (1) and tends to 1. (With a knee of 0 it is the old +/// `x/(1 + |x|)`.) Written `1 - 1/(1 + u)` so that every step rounds +/// monotonically and infinity comes out at 1. No state, no lookahead. +pub fn limit(x: f32) f32 { + const a = @abs(x); + if (a <= knee) return x; + const u = (a - knee) / (1 - knee); + return std.math.copysign(knee + (1 - knee) * (1 - 1 / (1 + u)), x); +} + /// WAV, FLAC or Ogg Vorbis, by content (see `vendor/codecs.h`). fn decodeBytes(gpa: std.mem.Allocator, bytes: []const u8) ![]f32 { var channels: u32 = 0; @@ -325,3 +446,116 @@ test "voices reconcile: one-shots finish and stay silent, new serials restart, u try std.testing.expectEqual(@as(usize, 1), audio.voices.items.len); try std.testing.expectEqual(@as(usize, 8), audio.mix(&out)); } + +test "voices play made sounds: copied, and refused when not finite" { + var audio: Audio = .{ .gpa = std.testing.allocator }; + defer audio.deinit(); + var made = [_]f32{ 0.25, -0.25 }; + const sound = audio.new(&made); + made[0] = 1; + try std.testing.expectEqualSlices(f32, &.{ 0.25, -0.25 }, audio.samplesOf(sound)); + try std.testing.expectEqual(abi.Audio.none, audio.new(&.{ 0, std.math.nan(f32) })); + try std.testing.expectEqual(abi.Audio.none, audio.new(&.{std.math.inf(f32)})); +} + +test "the mixer passes the mix through below the knee and limits it to 1 above, rising" { + // Identity to the bit: every 997th float from 0 to the knee, both signs. + const knee_bits: u32 = @bitCast(@as(f32, knee)); + var bits: u32 = 0; + while (bits <= knee_bits) : (bits += 997) { + const x: f32 = @bitCast(bits); + try std.testing.expectEqual(@as(u32, @bitCast(x)), @as(u32, @bitCast(limit(x)))); + try std.testing.expectEqual(@as(u32, @bitCast(-x)), @as(u32, @bitCast(limit(-x)))); + } + try std.testing.expectEqual(@as(f32, knee), limit(knee)); + // Rising and at most 1, from the knee's neighbourhood (every float) to + // infinity (every 101st), and odd. + var last = limit(@bitCast(knee_bits - 100_000)); + bits = knee_bits - 100_000; + const inf_bits: u32 = @bitCast(std.math.inf(f32)); + while (bits <= inf_bits) : (bits += if (bits < knee_bits + 100_000) 1 else 101) { + const x: f32 = @bitCast(bits); + const y = limit(x); + try std.testing.expect(y >= last and y <= 1); + try std.testing.expectEqual(-y, limit(-x)); + last = y; + } + try std.testing.expectEqual(@as(f32, 1), limit(std.math.inf(f32))); + // Slope 1 on both sides of the knee, and what a full-scale peak becomes. + const h = 1e-3; + try std.testing.expectApproxEqAbs(@as(f32, 1), (limit(knee + h) - limit(knee)) / h, 0.01); + try std.testing.expectEqual(@as(f32, 0.875), limit(1)); +} + +test "voices at another rate are resampled linearly, and a group's gain scales its voices smoothly" { + var audio: Audio = .{ .gpa = std.testing.allocator }; + defer audio.deinit(); + const clip = audio.new(&.{ 0, 0.1, 0.2, 0.3 }); + var out: [1024]f32 = undefined; + // Half speed: twice as long, the halves interpolated (the last toward + // silence); double speed: every other sample. + audio.declare(.{ .key = 1, .audio = clip, .rate = 0.5 }); + try std.testing.expectEqual(@as(usize, 8), audio.mix(&out)); + for ([_]f32{ 0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.15 }, out[0..8]) |want, got| try std.testing.expectApproxEqAbs(want, got, 1e-6); + audio.declare(.{ .key = 1, .audio = clip, .rate = 2, .serial = 1 }); + try std.testing.expectEqual(@as(usize, 2), audio.mix(&out)); + try std.testing.expectEqualSlices(f32, &.{ 0, 0.2 }, out[0..2]); + // Rate 0 holds it; an infinite rate ends it. + audio.declare(.{ .key = 1, .audio = clip, .rate = 0, .serial = 2 }); + try std.testing.expectEqual(@as(usize, 3), audio.mix(out[0..3])); + audio.declare(.{ .key = 1, .audio = clip, .rate = std.math.inf(f32), .serial = 3 }); + try std.testing.expectEqual(@as(usize, 1), audio.mix(&out)); + + // A looping voice in group 1 and one in group 0, at 0.25 each: group 1 + // set to 0.5 glides there in 10 ms and stays; group 0 is untouched. + const level = audio.new(&.{0.25}); + audio.beginFrame(); + audio.declare(.{ .key = 1, .audio = level, .loop = true, .group = 1 }); + audio.declare(.{ .key = 2, .audio = level, .loop = true }); + audio.gains[1] = 0.5; + try std.testing.expectEqual(out.len, audio.mix(&out)); + try std.testing.expect(out[0] < 0.5 and out[0] > 0.49); + try std.testing.expect(out[100] > out[200] and out[200] > out[400]); + try std.testing.expectEqual(@as(f32, 0.375), out[480]); + try std.testing.expectEqual(@as(f32, 0.375), out[1023]); + // Undeclared next frame: back to 1, as smoothly. + audio.beginFrame(); + audio.declare(.{ .key = 1, .audio = level, .loop = true, .group = 1 }); + audio.declare(.{ .key = 2, .audio = level, .loop = true }); + try std.testing.expectEqual(out.len, audio.mix(&out)); + try std.testing.expect(out[0] > 0.375 and out[0] < 0.38); + try std.testing.expectEqual(@as(f32, 0.5), out[1023]); +} + +test "the lead the mixer gives streams outlasts the slowest recent frame and the device's pull, more after an underrun" { + const expectEqual = std.testing.expectEqual; + var intervals: [64]u64 = @splat(20 * std.time.ns_per_ms); + var margin: u32 = 0; + // 50 Hz and a pull of 1024: a frame's 960 samples and the pull. + try expectEqual(@as(u32, 960 + 1024), lead(intervals, 1024, &margin, false)); + // One 50 ms frame in the window sets it. + intervals[5] = 50 * std.time.ns_per_ms; + try expectEqual(@as(u32, 2400 + 1024), lead(intervals, 1024, &margin, false)); + // An underrun adds half a pull, which goes a sample a frame. + try expectEqual(@as(u32, 2400 + 1024 + 512), lead(intervals, 1024, &margin, true)); + try expectEqual(@as(u32, 2400 + 1024 + 511), lead(intervals, 1024, &margin, false)); + // A stall is not a pace: the lead stops at 170 ms. + intervals[6] = std.time.ns_per_s; + try expectEqual(@as(u32, max_lead), lead(intervals, 1024, &margin, false)); +} + +test "the mixer's device takes at once what the sketch asks, SDL's own when it asks nothing, and the environment's over both" { + _ = c.SDL_SetHintWithPriority(c.SDL_HINT_AUDIO_DRIVER, "dummy", c.SDL_HINT_OVERRIDE); + try std.testing.expect(c.SDL_Init(c.SDL_INIT_AUDIO)); + defer c.SDL_Quit(); + defer _ = c.SDL_ResetHint(c.SDL_HINT_AUDIO_DEVICE_SAMPLE_FRAMES); + for ([_][3]u32{ .{ 0, 0, 1024 }, .{ 256, 0, 256 }, .{ 256, 512, 512 } }) |case| { + // SDL's copy of the environment, not the process's. + if (case[1] > 0) try std.testing.expect(c.SDL_SetEnvironmentVariable(c.SDL_GetEnvironment(), c.SDL_HINT_AUDIO_DEVICE_SAMPLE_FRAMES, "512", true)); + defer _ = c.SDL_UnsetEnvironmentVariable(c.SDL_GetEnvironment(), c.SDL_HINT_AUDIO_DEVICE_SAMPLE_FRAMES); + var a: Audio = .{ .gpa = std.testing.allocator }; + try a.open(case[0]); + defer a.deinit(); + try std.testing.expectEqual(case[2], a.pull); + } +} diff --git a/src/host/control.zig b/src/host/control.zig index 8cc8296..943316c 100644 --- a/src/host/control.zig +++ b/src/host/control.zig @@ -2,17 +2,45 @@ const std = @import("std"); const c9 = @import("cloud9"); const c = @import("c"); +const abi = @import("abi"); const Host = @import("Host.zig"); const Presentation = @import("Presentation.zig"); +const state_files = @import("state_files.zig"); +const script = @import("script.zig"); +const Console = @import("Console.zig"); const fs = c9.fs; const transport = c9.transport; const Backend = struct { pub const Req = fs.Req; pub const Reply = fs.Reply; }; -const Server = fs.Server(Backend, .{ .fid_capacity = 32, .slot_capacity = 4 }); +const Server = fs.Server(Backend, .{ .fid_capacity = 32, .slot_capacity = 4, .name_capacity = 64 }); const msize = 16384; -const names = [_][]const u8{ "/", "ctl", "status", "log", "screen.png", "profile", "profile-trace", "timing-trace", "presentation-trace" }; +/// The files, a row each: what lookup, readdir and getattr answer. A +/// file's node is its number here. +const File = enum(u64) { @"/" = 1, ctl, status, log, @"screen.png", profile, @"profile-trace", @"timing-trace", @"presentation-trace", README, commands, sketch = 1 << 63, state = @bitCast(state_files.root) }; +const files = std.enums.EnumArray(File, struct { mode: u16 = 0o400, doc: []const u8 }).init(.{ + .@"/" = .{ .mode = 0o700, .doc = "" }, + .ctl = .{ .mode = 0o600, .doc = "write a verb a line, of those below: ctl's own, the input a script plays (live, no frame of its own), the console's; any other line goes to the sketch (commands lists its words)" }, + .status = .{ .doc = "name, canvas size, playback mode, gpu, and the screenshot's state" }, + .log = .{ .doc = "the console's last five lines" }, + .@"screen.png" = .{ .doc = "the next frame, as PNG: an open waits for it to be drawn, and pins its own copy" }, + .profile = .{ .doc = "with --profile-gpu: label, count, mean, worst, p95 and p99 ms, tab-separated" }, + .@"profile-trace" = .{ .doc = "with --profile-gpu: label,sample,ns, the samples kept, as CSV" }, + .@"timing-trace" = .{ .doc = "index,frame_ns,work_ns,outside_work_ns, the frames kept, as CSV" }, + .@"presentation-trace" = .{ .doc = "on Wayland: presentation feedback per frame, as CSV" }, + .README = .{ .doc = "this: a line a file, ctl's verbs under it, a line a State file under state/" }, + .commands = .{ .doc = "every verb ctl takes, a line each, the sketch's words last" }, + .sketch = .{ .mode = 0o700, .doc = "the sketch's own files, which the host never serves: reserved, empty" }, + .state = .{ .mode = 0o700, .doc = "the sketch's State: a directory per struct and array, a file per value; a read is the value, a write what set does (a jump); an array of numbers is one file of its values, blank-separated" }, +}); + +/// The verbs `ctl` takes beside the console's lines. +const Verb = enum { screenshot, @"profile-reset" }; +const verbs = std.enums.EnumArray(Verb, []const u8).init(.{ + .screenshot = "captures the next frame (status says when); screen.png's open does it itself", + .@"profile-reset" = "clears profile's counters and frame count, keeping its labels", +}); const Connection = struct { fd: c_int = -1, @@ -38,6 +66,9 @@ pub const Control = struct { allocator: std.mem.Allocator, path: [:0]u8, listener: c_int, + /// Serving with no sketch running (`fs` with it closed): the State to + /// show and where it came from; the host is not touched. + offline: ?Offline = null, connections: [4]Connection = @splat(.{}), png: []u8 = &.{}, capture_pending: bool = false, @@ -60,6 +91,36 @@ pub const Control = struct { return self; } + /// Listens at `where`: a socket path, or a name posted as + /// `$XDG_RUNTIME_DIR/9p/sketchbook/<where>` (a stale entry replaced, a + /// live one refused). + pub fn open(a: std.mem.Allocator, environ: *const std.process.Environ.Map, where: []const u8) !*Control { + if (std.mem.startsWith(u8, where, "/")) return init(a, where); + var buf: [c9.post.sun_path_len]u8 = undefined; + const path = try registered(environ, where, &buf); + const dir = path[0..std.mem.lastIndexOfScalar(u8, path, '/').?]; + var dir_buf: [c9.post.sun_path_len]u8 = undefined; + for ([_]usize{ dir.len - "/sketchbook".len, dir.len }) |n| _ = std.c.mkdir(std.fmt.bufPrintSentinel(&dir_buf, "{s}", .{dir[0..n]}, 0) catch unreachable, 0o700); + switch (c9.post.probe(path)) { + .live => return error.AlreadyPosted, + .stale => _ = std.c.unlink(path), + .none => {}, + } + return init(a, path); + } + + /// Serves one client on `fd` until it hangs up: `fs` with no sketch + /// running, on a thread of its own. + pub fn serveOffline(self: *Control, fd: c_int) void { + const conn = self.allocator.create(Connection) catch return transport.close(fd); + defer self.allocator.destroy(conn); + conn.* = .{ .fd = fd }; + conn.server = .init(.{ .in = &conn.input, .out = &conn.output, .root = 1 }); + var host: Host = undefined; // Offline, nothing reads it. + while (true) self.service(&host, conn) catch break; + conn.close(self.allocator); + } + pub fn deinit(self: *Control) void { for (&self.connections) |*conn| conn.close(self.allocator); transport.close(self.listener); @@ -97,7 +158,8 @@ pub const Control = struct { conn.used -= consumed; progressed = consumed != 0; } - while (conn.server.next()) |req| self.answer(host, conn, req); + while (conn.server.retry()) |req| self.answer(host, conn, req, true); + while (conn.server.next()) |req| self.answer(host, conn, req, false); if (conn.server.protocol.dead) return error.Closed; if (conn.server.output().len > 0) { if (try transport.write(conn.fd, conn.server.output())) |n| { @@ -117,42 +179,58 @@ pub const Control = struct { } } - fn answer(self: *Control, host: *Host, conn: *Connection, req: fs.Req) void { + /// Answers a request, or parks it: an open of screen.png asks for the + /// next frame and waits for it, asked again (`retried`) each frame + /// until the capture has landed. + fn answer(self: *Control, host: *Host, conn: *Connection, req: fs.Req, retried: bool) void { var reply: fs.Reply = .{ .tag = req.tag }; var buffer: [msize]u8 = undefined; + if (!retried and req.op == .open and req.node == @backingInt(File.@"screen.png")) { + self.capture_pending = true; + self.capture_error = null; + } const bytes = self.respond(host, conn, req, &reply, &buffer) catch |err| blk: { - reply = .{ .tag = req.tag, .status = .err, .errno = fs.E.INVAL, .ename = @errorName(err) }; + reply = if (err == error.CapturePending) .{ .tag = req.tag, .status = .again } else .{ .tag = req.tag, .status = .err, .errno = fs.E.INVAL, .ename = if (err == error.SketchNotRunning) self.offline.?.from else @errorName(err) }; break :blk &.{}; }; conn.server.reply(&reply, bytes); } fn respond(self: *Control, host: *Host, conn: *Connection, req: fs.Req, reply: *fs.Reply, buffer: []u8) ![]const u8 { - if (req.node < 1 or req.node > names.len) return error.UnknownFile; + // Nodes from 2^63 are the sketch's: none is served but sketch/. + if (req.node > @backingInt(File.sketch)) return error.UnknownFile; + if (req.node & @as(u64, @bitCast(state_files.root)) != 0) return stateRespond(self, host, conn, req, reply, buffer); + const file = std.enums.fromInt(File, req.node) orelse return error.UnknownFile; + if (self.offline != null and (req.op == .write or (req.op == .open or req.op == .read) and file != .README and file != .commands and file != .ctl and file != .@"/" and file != .sketch)) return error.SketchNotRunning; switch (req.op) { .lookup => { - if (req.node != 1) return error.NotDirectory; - for (names[1..], 2..) |name, node| if (std.mem.eql(u8, name, req.data)) { - reply.attr = self.attr(node); - return &.{}; - }; - return error.UnknownFile; + if (file == .sketch) return error.UnknownFile; + if (file != .@"/") return error.NotDirectory; + const found = std.meta.stringToEnum(File, req.data) orelse return error.UnknownFile; + if (found == .@"/") return error.UnknownFile; + reply.attr = self.attr(@backingInt(found)); }, .getattr => reply.attr = self.attr(req.node), .open => { - if (req.node == 5 or req.node == 7 or req.node == 8 or req.node == 9) { - if (req.node == 5) { + if (file == .@"screen.png" or file == .@"profile-trace" or file == .@"timing-trace" or file == .@"presentation-trace" or file == .README or file == .commands) { + if (file == .@"screen.png") { if (self.capture_pending) return error.CapturePending; if (self.capture_error) |err| return err; if (self.png.len == 0) return error.CaptureScreenshotFirst; } for (&conn.snapshots, 1..) |*slot, handle| if (slot.* == null) { - slot.* = switch (req.node) { - 5 => try self.allocator.dupe(u8, self.png), - 7 => try self.trace(host), - 8 => try self.timingTrace(host), - 9 => try self.presentationTrace(host), - else => unreachable, + slot.* = switch (file) { + .@"screen.png" => try self.allocator.dupe(u8, self.png), + .@"profile-trace" => try self.trace(host), + .@"timing-trace" => try self.timingTrace(host), + .README, .commands => blk: { + var text: std.Io.Writer.Allocating = .init(self.allocator); + defer text.deinit(); + const layout = if (self.offline) |o| o.layout else host.state.layout; + if (file == .README) try readme(layout, &text.writer) else try verbLines(&text.writer, "", if (self.offline) |o| o.completions else host.completions); + break :blk try text.toOwnedSlice(); + }, + else => try self.presentationTrace(host), }; reply.handle = @intCast(handle); return &.{}; @@ -166,12 +244,14 @@ pub const Control = struct { slot.* = null; }, .readdir => { - if (req.node != 1) return error.NotDirectory; + if (file == .sketch) return &.{}; + if (file != .@"/") return error.NotDirectory; var used: usize = 0; - for (names[1..], 0..) |name, index| { + for (std.enums.values(File)[1..], 0..) |f, index| { if (index < req.off) continue; - std.mem.writeInt(u64, buffer[used..][0..8], index + 2, .little); - buffer[used + 8] = 0; + const name = @tagName(f); + std.mem.writeInt(u64, buffer[used..][0..8], @backingInt(f), .little); + buffer[used + 8] = @intFromBool(f == .state or f == .sketch); buffer[used + 9] = @intCast(name.len); @memcpy(buffer[used + 10 ..][0..name.len], name); used += 10 + name.len; @@ -180,21 +260,21 @@ pub const Control = struct { }, .read => { var writer: std.Io.Writer = .fixed(buffer); - const bytes: []const u8 = switch (req.node) { - 2 => "Write one console command per line. screenshot captures the next frame.\n", - 3 => blk: { + const bytes: []const u8 = switch (file) { + .ctl => "Write a verb a line: commands lists them, README says what each does.\n", + .status => blk: { try writer.print("name {s}\nsize {d} {d}\nmode {t}\ngpu {s}\nscreenshot_pending {}\nscreenshot_generation {d}\nscreenshot_error {s}\n", .{ host.name, host.canvas[0], host.canvas[1], host.timeline.mode, if (host.gpu != null) "yes" else "no", self.capture_pending, self.generation, if (self.capture_error) |err| @errorName(err) else "none" }); break :blk writer.buffered(); }, - 4 => blk: { + .log => blk: { for (host.console.lines) |line| { try writer.writeAll(line.bytes[0..line.len]); try writer.writeByte('\n'); } break :blk writer.buffered(); }, - 5, 7, 8, 9 => if (req.handle > 0 and req.handle <= conn.snapshots.len) conn.snapshots[req.handle - 1] orelse return error.InvalidHandle else return error.InvalidHandle, - 6 => blk: { + .@"screen.png", .@"profile-trace", .@"timing-trace", .@"presentation-trace", .README, .commands => if (req.handle > 0 and req.handle <= conn.snapshots.len) conn.snapshots[req.handle - 1] orelse return error.InvalidHandle else return error.InvalidHandle, + .profile => blk: { const gpu = if (host.passes) |*gpu| gpu else return error.ProfilingDisabled; const profile = if (gpu.profile) |*profile| profile else return error.ProfilingDisabled; try writer.print("# CPU wall milliseconds including GPU submission and fence wait; not hardware timestamps\n# frames {d}\nlabel\tcount\tmean_ms\tworst_ms\tp95_ms\tp99_ms\n", .{gpu.frame - profile.start_frame}); @@ -207,30 +287,41 @@ pub const Control = struct { } break :blk writer.buffered(); }, - else => return error.NotFile, + .@"/", .state, .sketch => return error.NotFile, }; return window(bytes, req.off, req.size); }, .write => { - if (req.node != 2) return error.ReadOnly; + if (file != .ctl) return error.ReadOnly; if (req.data.len > 4096 or std.mem.indexOfScalar(u8, req.data, 0) != null) return error.InvalidCommand; var lines = std.mem.tokenizeScalar(u8, req.data, '\n'); while (lines.next()) |raw| { const line = std.mem.trim(u8, raw, " \t\r"); - if (std.mem.eql(u8, line, "screenshot")) { - self.capture_pending = true; - self.capture_error = null; - } else if (std.mem.eql(u8, line, "profile-reset")) { - const gpu = if (host.passes) |*gpu| gpu else return error.ProfilingDisabled; - const profile = if (gpu.profile) |*profile| profile else return error.ProfilingDisabled; - for (profile.entries.values()) |*entry| entry.* = .{}; - profile.start_frame = gpu.frame; - } else try host.runLine(line, c.SDL_GetTicksNS()); + const verb = std.meta.stringToEnum(Verb, line) orelse { + var words = std.mem.tokenizeAny(u8, line, " \t"); + const input = std.meta.stringToEnum(script.Verb, words.next() orelse ""); + if (input != null and script.verbs.get(input.?).input) { + try script.input(host, input.?, &words, c.SDL_GetTicksNS()); + } else try host.runLine(line, c.SDL_GetTicksNS()); + continue; + }; + switch (verb) { + .screenshot => { + self.capture_pending = true; + self.capture_error = null; + }, + .@"profile-reset" => { + const gpu = if (host.passes) |*gpu| gpu else return error.ProfilingDisabled; + const profile = if (gpu.profile) |*profile| profile else return error.ProfilingDisabled; + for (profile.entries.values()) |*entry| entry.* = .{}; + profile.start_frame = gpu.frame; + }, + } } reply.written = @intCast(req.data.len); }, .setattr => { - if (req.node != 2 or !req.truncate) return error.ReadOnly; + if (file != .ctl or !req.truncate) return error.ReadOnly; reply.attr = self.attr(req.node); }, } @@ -279,7 +370,8 @@ pub const Control = struct { } fn attr(self: *Control, node: u64) fs.Attr { - return .{ .name = names[@intCast(node - 1)], .node = node, .dir = node == 1, .mode = if (node == 1) 0o700 else if (node == 2) 0o600 else 0o400, .size = if (node == 5) self.png.len else 0, .version = if (node == 5) @truncate(self.generation) else 0 }; + const file: File = @fromBackingInt(@intCast(node)); + return .{ .name = @tagName(file), .node = node, .dir = file == .@"/" or file == .state or file == .sketch, .mode = files.get(file).mode, .size = if (file == .@"screen.png") self.png.len else 0, .version = if (file == .@"screen.png") @truncate(self.generation) else 0 }; } pub fn capture(self: *Control, surface: *c.SDL_Surface) void { @@ -303,6 +395,111 @@ pub const Control = struct { } }; +/// The README: a line a file, ctl's verbs indented under it and the +/// State's files under state/, in the shape cloud9's `help` reads. +fn readme(layout: @import("memory.zig").Layout, w: *std.Io.Writer) !void { + for (std.enums.values(File)[1..]) |f| { + const name = @tagName(f); + const dir = f == .state or f == .sketch; + try w.print("{s}{s}", .{ name, if (dir) "/" else "" }); + try w.splatByteAll(' ', @max(1, 41 -| (name.len + @intFromBool(dir)))); + try w.print("{s}\n", .{files.get(f).doc}); + if (f == .ctl) try verbLines(w, " ", &.{}); + if (f == .state) try state_files.readme(layout, w); + } +} + +/// A line a verb ctl takes: ctl's own, the input verbs, the console's, +/// then `sketch`'s words. +fn verbLines(w: *std.Io.Writer, indent: []const u8, sketch: []const []const u8) !void { + for (std.enums.values(Verb)) |v| try verbLine(w, indent, @tagName(v), "", verbs.get(v)); + for (std.enums.values(script.Verb)) |v| if (script.verbs.get(v).input) try verbLine(w, indent, @tagName(v), script.verbs.get(v).args, script.verbs.get(v).doc); + for (std.enums.values(Console.Verb)) |v| try verbLine(w, indent, @tagName(v), Console.verbs.get(v).args, Console.verbs.get(v).doc); + for (sketch) |word| try w.print("{s}{s}\n", .{ indent, word }); +} + +fn verbLine(w: *std.Io.Writer, indent: []const u8, name: []const u8, args: []const u8, doc: []const u8) !void { + try w.print("{s}{s}{s}{s}", .{ indent, name, if (args.len > 0) " " else "", args }); + try w.splatByteAll(' ', @max(1, 37 -| (name.len + args.len + @intFromBool(args.len > 0)))); + try w.print("{s}\n", .{doc}); +} + +/// Under `state/`: the live State as files (state_files.zig), a write +/// run as the console's `set`. +fn stateRespond(self: *Control, host: *Host, conn: *Connection, req: fs.Req, reply: *fs.Reply, buffer: []u8) ![]const u8 { + const layout = if (self.offline) |o| o.layout else host.state.layout; + const node: state_files.Node = @bitCast(req.node); + if (!state_files.valid(layout, node)) return error.StateLayoutChangedWalkAgain; + const dir = state_files.isDir(layout, node); + const mode: u16 = if (dir) 0o700 else if (state_files.writable(layout, node)) 0o600 else 0o400; + switch (req.op) { + .lookup => { + if (!dir) return error.NotDirectory; + const child = state_files.lookup(layout, node, req.data) orelse return error.UnknownField; + const child_dir = state_files.isDir(layout, child); + reply.attr = .{ .node = @bitCast(child), .dir = child_dir, .mode = if (child_dir) 0o700 else if (state_files.writable(layout, child)) 0o600 else 0o400 }; + }, + .getattr => reply.attr = .{ .node = req.node, .dir = dir, .mode = mode }, + .setattr => { + if (mode != 0o600 or !req.truncate) return error.ReadOnly; + reply.attr = .{ .node = req.node, .mode = mode }; + }, + // A value is read as it was at the open: it changes every frame, + // and its length with it. + .open => if (!dir) for (&conn.snapshots, 1..) |*slot, handle| if (slot.* == null) { + var text: std.Io.Writer.Allocating = .init(self.allocator); + defer text.deinit(); + try state_files.read(layout, if (self.offline) |o| o.bytes else host.live(), node, &text.writer); + slot.* = try text.toOwnedSlice(); + reply.handle = @intCast(handle); + break; + } else return error.TooManySnapshots, + .release => if (req.opened and req.handle > 0 and req.handle <= conn.snapshots.len) { + const slot = &conn.snapshots[req.handle - 1]; + if (slot.*) |bytes| self.allocator.free(bytes); + slot.* = null; + }, + .readdir => { + if (!dir) return error.NotDirectory; + return buffer[0..state_files.readdir(layout, node, req.off, buffer)]; + }, + .read => { + if (dir) return error.NotFile; + const bytes = if (req.handle > 0 and req.handle <= conn.snapshots.len) conn.snapshots[req.handle - 1] orelse return error.InvalidHandle else return error.InvalidHandle; + return window(bytes, req.off, req.size); + }, + .write => { + if (mode != 0o600) return error.ReadOnly; + if (self.offline != null) return error.SketchNotRunning; + var w: std.Io.Writer = .fixed(buffer); + w.writeAll("set ") catch unreachable; + state_files.path(layout, node, &w) catch return error.ValueTooLong; + w.writeByte(' ') catch return error.ValueTooLong; + for (std.mem.trim(u8, req.data, " \t\r\n")) |byte| w.writeByte(if (byte == '\n') ' ' else byte) catch return error.ValueTooLong; + try host.runLine(w.buffered(), c.SDL_GetTicksNS()); + reply.written = @intCast(req.data.len); + }, + } + return &.{}; +} + +/// The State `fs` shows with no sketch running, and its words for what a +/// running one would answer. +pub const Offline = struct { + layout: @import("memory.zig").Layout, + bytes: []const u8, + completions: []const []const u8, + /// "drat-meout is not running: ..." + from: []const u8, +}; + +/// `$XDG_RUNTIME_DIR/9p/sketchbook/<name>`, where a sketch posts its tree. +pub fn registered(environ: *const std.process.Environ.Map, name: []const u8, buf: []u8) ![:0]u8 { + if (!c9.post.legalName(name)) return error.IllegalName; + const runtime = environ.get("XDG_RUNTIME_DIR") orelse return error.NotRuntimeDir; + return std.fmt.bufPrintSentinel(buf, "{s}/9p/sketchbook/{s}", .{ runtime, name }, 0) catch error.NameTooLong; +} + fn window(bytes: []const u8, offset: u64, count: u32) []const u8 { if (offset >= bytes.len) return &.{}; const start: usize = @intCast(offset); @@ -452,3 +649,59 @@ test "control writes reject presentation trace mutations and opens own independe _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .release, .node = 9, .handle = second, .opened = true }, &reply, &buf); try std.testing.expect(conn.snapshots[first - 1] == null and conn.snapshots[second - 1] == null); } + +test "control writes take input verbs live, and the README and commands read the tables" { + const a = std.testing.allocator; + var control: Control = .{ .allocator = a, .path = undefined, .listener = -1 }; + var host: Host = undefined; + host.gpa = a; + host.console = .{}; + host.input = .{}; + host.pending = .empty; + defer host.pending.deinit(a); + const S = struct { scene: enum(u8) { room, street } = .room, talk: struct { text: [3]u8 = @splat(0) } = .{} }; + var arena: std.heap.ArenaAllocator = .init(a); + defer arena.deinit(); + host.state.layout = try @import("memory.zig").Layout.copy(arena.allocator(), @import("abi").layout.of(S, .state)); + host.completions = &.{ "scene room", "scene street" }; + var conn: Connection = .{}; + var reply: fs.Reply = .{ .tag = 1 }; + var buf: [512]u8 = undefined; + _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .write, .node = 2, .data = "click 10 20\nhold left_shift\n" }, &reply, &buf); + try std.testing.expectEqual(@as(usize, 4), host.pending.items.len); + try std.testing.expectEqual(abi.Event.Kind.mouse_up, host.pending.items[2].kind); + try std.testing.expectEqual(@as(f32, 20), host.pending.items[2].y); + try std.testing.expectEqual(abi.Event.Kind.key_down, host.pending.items[3].kind); + try std.testing.expectError(error.ExpectedPoint, control.respond(&host, &conn, .{ .tag = 1, .op = .write, .node = 2, .data = "click 10" }, &reply, &buf)); + for ([_]File{ .README, .commands }) |f| { + _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .open, .node = @backingInt(f) }, &reply, &buf); + const handle = reply.handle; + const text = conn.snapshots[handle - 1].?; + if (f == .README) { + try std.testing.expect(std.mem.startsWith(u8, text, "ctl write a verb a line")); + try std.testing.expect(std.mem.indexOf(u8, text, "\n screenshot captures the next frame") != null); + try std.testing.expect(std.mem.indexOf(u8, text, "\n click X Y move there") != null); + try std.testing.expect(std.mem.indexOf(u8, text, "\n set FIELD VALUE... a field to a value") != null); + try std.testing.expect(std.mem.indexOf(u8, text, "\nstate/ the sketch's State") != null); + try std.testing.expect(std.mem.indexOf(u8, text, "\nsketch/ the sketch's own files") != null); + try std.testing.expect(std.mem.endsWith(u8, text, "\nstate/scene .room .street\nstate/talk/text 3 u8, blank-separated\n")); + } else { + try std.testing.expect(std.mem.startsWith(u8, text, "screenshot captures")); + try std.testing.expect(std.mem.endsWith(u8, text, "\nscene room\nscene street\n")); + } + _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .release, .node = @backingInt(f), .handle = handle, .opened = true }, &reply, &buf); + } +} + +test "control writes leave the sketch's directory and nodes alone" { + var control: Control = .{ .allocator = std.testing.allocator, .path = undefined, .listener = -1 }; + var host: Host = undefined; + var conn: Connection = .{}; + var reply: fs.Reply = .{ .tag = 1 }; + var buf: [256]u8 = undefined; + _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .lookup, .node = 1, .data = "sketch" }, &reply, &buf); + try std.testing.expect(reply.attr.dir and reply.attr.node == 1 << 63); + try std.testing.expectEqual(@as(usize, 0), (try control.respond(&host, &conn, .{ .tag = 1, .op = .readdir, .node = 1 << 63 }, &reply, &buf)).len); + try std.testing.expectError(error.UnknownFile, control.respond(&host, &conn, .{ .tag = 1, .op = .lookup, .node = 1 << 63, .data = "buffer" }, &reply, &buf)); + for ([_]u64{ (1 << 63) + 1, (1 << 63) | (1 << 62), std.math.maxInt(u64) }) |node| try std.testing.expectError(error.UnknownFile, control.respond(&host, &conn, .{ .tag = 1, .op = .getattr, .node = node }, &reply, &buf)); +} diff --git a/src/host/fields.zig b/src/host/fields.zig index 2e70414..fc1a1e7 100644 --- a/src/host/fields.zig +++ b/src/host/fields.zig @@ -123,6 +123,25 @@ pub fn set(leaf: Leaf, memory: []u8, text: []const u8) !void { } } +/// Sets every value of the row of scalars `path` names (an array of +/// numbers, a vector, `grid[1]` of a `grid: [3][2]u16`), in memory order, +/// from `text`'s words, one each; nothing when one is not a value. +pub fn setRow(layout: Layout, memory: []u8, path: []const u8, text: []const u8) !void { + for (layout.fields) |leaf| { + if (leaf.whole() or !std.mem.endsWith(u8, leaf.path, "[]")) continue; + const at = abi.layout.match(leaf.path[0 .. leaf.path.len - 2], leaf.dims[0 .. leaf.dims.len - 1], path) orelse continue; + const d = leaf.dims[leaf.dims.len - 1]; + var scratch: [16]u8 = undefined; + var words = std.mem.tokenizeAny(u8, text, " \t\n"); + for (0..d.count) |_| try set(leaf.at(0), &scratch, words.next() orelse return error.TooFewValues); + if (words.next() != null) return error.TooManyValues; + words.reset(); + for (0..d.count) |i| try set(leaf.at(leaf.offset + at + i * d.stride), memory, words.next().?); + return; + } + return error.UnsupportedField; +} + /// True when the field's formatted value equals `text` (enum names compare /// with or without the leading dot). pub fn matches(leaf: Leaf, memory: []const u8, text: []const u8) bool { @@ -206,6 +225,24 @@ test "fields format, parse and compare by kind" { try std.testing.expectError(error.InvalidValue, set(layout.find("x").?, bytes, "banana")); } +test "a row of scalars is set from its words, all or none" { + const S = struct { grid: [3][2]i16 = @splat(@splat(0)), pos: @Vector(2, f32) = .{ 0, 0 } }; + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const layout = try Layout.copy(arena.allocator(), abi.layout.of(S, .state)); + var s: S = .{}; + const bytes = std.mem.asBytes(&s); + try setRow(layout, bytes, "grid[1]", "4 -5"); + try std.testing.expectEqual([2]i16{ 4, -5 }, s.grid[1]); + try setRow(layout, bytes, "pos", "1.5\n2"); + try std.testing.expectEqual(@as(f32, 2), s.pos[1]); + try std.testing.expectError(error.TooFewValues, setRow(layout, bytes, "grid[2]", "7")); + try std.testing.expectError(error.TooManyValues, setRow(layout, bytes, "grid[2]", "7 8 9")); + try std.testing.expectError(error.InvalidValue, setRow(layout, bytes, "grid[2]", "7 x")); + try std.testing.expectEqual([2]i16{ 0, 0 }, s.grid[2]); + try std.testing.expectError(error.UnsupportedField, setRow(layout, bytes, "grid", "1 2")); +} + test "indexed paths reach array elements and vector lanes" { const S = struct { pos: @Vector(2, f32) = .{ 250, 3 }, boids: struct { buffer: [4]struct { pos: [2]f32 = .{ 0, 0 }, mood: enum(u8) { calm = 1, wild = 2 } = .calm } = @splat(.{}), len: u32 = 0 } = .{} }; var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); diff --git a/src/host/library.zig b/src/host/library.zig index 6958eec..6619d5b 100644 --- a/src/host/library.zig +++ b/src/host/library.zig @@ -1,9 +1,13 @@ //! Loading sketch libraries, and noticing when a build replaces one. //! //! `dlopen` returns the handle it already has for a path it loaded before, so -//! every load goes through a private copy with a fresh name. The copy is -//! deleted right after loading: the mapping keeps the code alive, and nothing -//! is left behind if the host dies. +//! every load goes through a symlink with a fresh name to an fd open on the +//! library: what loads is the file that was opened, whatever a build renames +//! over it meanwhile. Link and fd live as long as the library is loaded: the +//! name dlopen was given is where a panic's trace reads the sketch's debug +//! info, so a host that dies leaves its dangling links behind. A library +//! rewritten in place instead (same inode) would not load again, and would +//! change the code under the running host. const std = @import("std"); const linux = std.os.linux; const c = @import("c"); @@ -12,8 +16,14 @@ const abi = @import("abi"); pub const Library = struct { object: *c.SDL_SharedObject, sketch: abi.Sketch, + /// What the link names (the library, or its fixed copy) and where the + /// link is, for `openFresh`'s libraries; -1 for `open`'s. + fd: i32 = -1, + scratch_dir: []const u8 = "", + serial: usize = 0, - pub fn open(path: [:0]const u8) !Library { + /// Loads the library at `path`; `source` names it in messages. + pub fn open(path: [:0]const u8, source: []const u8) !Library { const object = c.SDL_LoadObject(path.ptr) orelse return error.LoadLibrary; errdefer c.SDL_UnloadObject(object); var sketch: abi.Sketch = undefined; @@ -22,25 +32,109 @@ pub const Library = struct { const address = c.SDL_LoadFunction(object, symbol) orelse return error.MissingEntryPoint; @field(sketch, name) = @ptrCast(address); } - if (sketch.info().abi != abi.hash) return error.AbiMismatch; + if (sketch.info().abi != abi.hash) { + const address = c.SDL_LoadFunction(object, "sketch_build") orelse { + std.log.err("{s}: built by an older sketchbook: rebuild it", .{source}); + return error.AbiMismatch; + }; + const build = std.mem.span(@as([*:0]const u8, @ptrFromInt(@intFromPtr(address)))); + if (std.mem.eql(u8, build, abi.build)) { + std.log.err("{s}: built against other abi types: restart the host to load it", .{source}); + } else { + const mode = build[std.mem.lastIndexOfScalar(u8, build, ' ').? + 1 ..]; + std.log.err("{s}: built by zig {s}, this host by zig {s}; Zig calls cross the boundary, so both need the same compiler, backend and mode: build the host like the library (`zig build run -Doptimize={s}`) or the library like the host", .{ source, build, abi.build, mode }); + } + return error.AbiMismatch; + } return .{ .object = object, .sketch = sketch }; } - /// Loads `source` through a uniquely named copy in `scratch_dir`. - pub fn openCopy(io: std.Io, source: []const u8, scratch_dir: []const u8, serial: usize) !Library { - var buf: [std.fs.max_path_bytes]u8 = undefined; - const copy = try std.mem.printSentinel(&buf, "{s}/sketchbook-{d}-{d}.so", .{ scratch_dir, linux.getpid(), serial }, 0); + /// Loads `source` through a uniquely named symlink in `scratch_dir`. + pub fn openFresh(io: std.Io, source: []const u8, scratch_dir: []const u8, serial: usize) !Library { const cwd = std.Io.Dir.cwd(); - try cwd.copyFile(source, cwd, copy, io, .{}); - defer cwd.deleteFile(io, copy) catch {}; - return open(copy); + const file = try cwd.openFile(io, source, .{}); + const fixed = withoutVersym(file.handle) catch |err| { + file.close(io); + return err; + }; + if (fixed != null) file.close(io); + const fd = fixed orelse file.handle; + errdefer _ = linux.close(fd); + var target_buf: [32]u8 = undefined; + const target = try std.mem.print(&target_buf, "/proc/self/fd/{d}", .{fd}); + var buf: [std.fs.max_path_bytes]u8 = undefined; + const link = try linkName(&buf, scratch_dir, serial); + try cwd.symLink(io, target, link, .{}); + errdefer cwd.deleteFile(io, link) catch {}; + var library = try open(link, source); + library.fd = fd; + library.scratch_dir = scratch_dir; + library.serial = serial; + return library; } pub fn close(self: *Library) void { c.SDL_UnloadObject(self.object); + if (self.fd < 0) return; + var buf: [std.fs.max_path_bytes]u8 = undefined; + _ = linux.unlink(linkName(&buf, self.scratch_dir, self.serial) catch unreachable); + _ = linux.close(self.fd); + } + + fn linkName(buf: []u8, scratch_dir: []const u8, serial: usize) ![:0]u8 { + return std.mem.printSentinel(buf, "{s}/sketchbook-{d}-{d}.so", .{ scratch_dir, linux.getpid(), serial }, 0); } }; +// ponytail: Zig 0.17.1's new ELF linker (which `-fincremental` selects) +// writes DT_VERSYM without DT_VERDEF or DT_VERNEED when nothing is +// versioned, and glibc's dlopen then reads a null version table and +// faults. Such a library has nothing versioned, so a copy without +// DT_VERSYM, in an anonymous memory file, loads instead (the build's own +// file is never written: the watch would see the write). Never fires on a +// correct library; dead once Zig has commit 6d27011edb (0.18): delete it. +fn withoutVersym(fd: i32) !?i32 { + const elf = std.elf; + var ehdr: elf.Elf64.Ehdr = undefined; + try pread(fd, std.mem.asBytes(&ehdr), 0); + if (!std.mem.eql(u8, &ehdr.ident.magic, elf.MAGIC) or ehdr.ident.class != .@"64" or ehdr.phnum > 32) return null; + var phdrs: [32]elf.Elf64.Phdr = undefined; + try pread(fd, std.mem.sliceAsBytes(phdrs[0..ehdr.phnum]), ehdr.phoff); + for (phdrs[0..ehdr.phnum]) |ph| { + if (ph.type != .DYNAMIC) continue; + var dyn: [64]elf.Elf64_Dyn = undefined; + const len = @min(dyn.len, ph.filesz / @sizeOf(elf.Elf64_Dyn)); + try pread(fd, std.mem.sliceAsBytes(dyn[0..len]), ph.offset); + var versym: ?usize = null; + var end: usize = 0; + while (end < len and dyn[end].d_tag != elf.DT_NULL) : (end += 1) switch (dyn[end].d_tag) { + elf.DT_VERSYM => versym = end, + elf.DT_VERDEF, elf.DT_VERNEED => return null, + else => {}, + }; + const at = versym orelse return null; + if (end == len) return null; + const copy: i32 = @intCast(@as(isize, @bitCast(linux.memfd_create("sketchbook", linux.MFD.CLOEXEC)))); + if (copy < 0) return error.MemfdFailed; + errdefer _ = linux.close(copy); + var offset: i64 = 0; + while (true) { + const rc = linux.sendfile(copy, fd, &offset, 1 << 30); + if (linux.errno(rc) != .SUCCESS) return error.CopyFailed; + if (rc == 0) break; + } + std.mem.copyForwards(elf.Elf64_Dyn, dyn[at..end], dyn[at + 1 .. end + 1]); + const bytes = std.mem.sliceAsBytes(dyn[at..end]); + if (linux.pwrite(copy, bytes.ptr, bytes.len, @intCast(ph.offset + at * @sizeOf(elf.Elf64_Dyn))) != bytes.len) return error.WriteFailed; + return copy; + } + return null; +} + +fn pread(fd: i32, buf: []u8, offset: u64) !void { + if (linux.pread(fd, buf.ptr, buf.len, @intCast(offset)) != buf.len) return error.ShortRead; +} + /// inotify on a library's directory, filtered to its file name. Builds /// replace files by renaming (`MOVED_TO`) or rewrite them (`CLOSE_WRITE`). pub const Watch = struct { diff --git a/src/host/memory.zig b/src/host/memory.zig index 5fbb88f..2749ea1 100644 --- a/src/host/memory.zig +++ b/src/host/memory.zig @@ -1,13 +1,12 @@ //! Sketch memory by lifetime. //! -//! `StateFile`: one `MAP_SHARED` file holding the live state and its snapshot -//! slots, plus a header describing the layout, so the state outlives restarts, -//! a probe can read it from another process, and a reload with a changed -//! layout can carry the old values over field by field. +//! `State`: process memory in the layout the sketch declares; a reload +//! with a changed layout carries the old values over field by field. It +//! outlives the process in the sessions database (Sessions.zig), whose +//! stretches keep its layout in the header format below. //! -//! `StoreFile`: a heap in a file, mapped at the same address in every run, -//! so what it holds may point into it: the sketch's `Store` and everything -//! allocated for it outlive restarts. +//! `OldState`: a state file from before the database held the present, +//! read once to import it. //! //! `Session`: this process's memory, kept across reloads. const std = @import("std"); @@ -17,13 +16,16 @@ const abi = @import("abi"); const field_value = @import("fields.zig"); pub const page = std.heap.page_size_min; -/// Slot 0 is live; 1..7 are snapshots. -pub const slot_count = 8; pub const header_len = 64 * 1024; -/// Layouts with element leaves (`list[].x`, `StoredField` with `dims`). -pub const file_magic = "SKETCH02".*; +/// A layout header, and an old file's one slot, the live state. +pub const file_magic = "SKETCH03".*; +/// Before sessions: slot 0 live and 1..7 snapshots (`old_slot_count`), which +/// the host imports as marks and then drops (`dropSnapshots`). +pub const file_magic_v2 = "SKETCH02".*; +pub const old_slot_count = 8; /// What hosts before element leaves wrote: arrays are whole leaves -/// (`StoredFieldV1`). Read, and rewritten as `file_magic` on adopt. +/// (`StoredFieldV1`), and eight slots. Read, and rewritten as +/// `file_magic_v2` on adopt. pub const file_magic_v1 = "SKETCH01".*; pub const Header = extern struct { @@ -31,7 +33,8 @@ pub const Header = extern struct { size: u64, alignment: u64, hash: u64, - /// Distance between slots, page aligned. + /// The slot's size, page aligned (and the distance between an old + /// file's slots). stride: u64, /// Bit `i`: slot `i` holds state. used: u32, @@ -260,9 +263,14 @@ pub const Diff = struct { /// Compares two copies of state leaf by leaf, so padding (a Debug /// `@Vector`'s spare lane, the gaps between fields) never differs. pub fn compare(layout: Layout, a: []const u8, b: []const u8) Diff { + return compareKept(layout, layout, a, b); +} + +/// `compare` over the leaves `migrate` from `from` keeps (`keeps`). +pub fn compareKept(from: Layout, layout: Layout, a: []const u8, b: []const u8) Diff { var diff: Diff = .{}; for (layout.fields) |leaf| { - if (leaf.whole()) continue; + if (leaf.whole() or (from.hash != layout.hash and !keeps(from, leaf))) continue; var it = leaf.elements(); while (it.next()) |offset| { if (std.mem.eql(u8, a[offset..][0..leaf.size], b[offset..][0..leaf.size])) continue; @@ -282,141 +290,120 @@ fn remapEnum(from: Layout.Leaf, old: []const u8, to: Layout.Leaf, new: []u8) boo return true; } -pub const StateFile = struct { - fd: posix.fd_t, - map: []align(page) u8, - /// Layout of the bytes in the file, owned by `arena`. - layout: Layout, +/// Live State: page aligned, in the running sketch's layout; `header` is +/// that layout as `layoutOf` reads it back, for the sessions' stretches. +pub const State = struct { + bytes: []align(page) u8 = &.{}, + layout: Layout = .{}, + header: []const u8 = "", + /// Owns `layout` and `header`. arena: std.heap.ArenaAllocator, - /// Opens or creates `path`. A new (empty) file has no layout and no used - /// slots: the first `adopt` fills it. A file that is not a state file - /// this host can read is refused, never truncated: it may be someone's - /// work, written by another build. - pub fn open(gpa: std.mem.Allocator, path: []const u8) !StateFile { - const fd = try posix.openat(posix.AT.FDCWD, path, .{ .ACCMODE = .RDWR, .CREAT = true }, 0o600); - errdefer _ = posix.system.close(fd); - var self: StateFile = .{ .fd = fd, .map = &.{}, .layout = .{}, .arena = .init(gpa) }; - errdefer self.arena.deinit(); - const len = try fileSize(fd); - if (len > 0) { - if (len < header_len) return error.NotAStateFile; - self.map = try mapFile(fd, @intCast(len), .{ .READ = true, .WRITE = true }); - errdefer posix.munmap(self.map); - try self.check(); - self.layout = try readLayout(self.arena.allocator(), self.map) orelse .{}; - return self; - } - try self.resize(0); - self.header().* = .{ .size = 0, .alignment = 1, .hash = 0, .stride = 0, .used = 0, .field_count = 0, .strings_len = 0 }; - return self; + pub fn init(gpa: std.mem.Allocator) State { + return .{ .arena = .init(gpa) }; } - pub fn close(self: *StateFile) void { - if (self.map.len != 0) posix.munmap(self.map); - _ = posix.system.close(self.fd); + pub fn deinit(self: *State, gpa: std.mem.Allocator) void { + gpa.free(self.bytes); self.arena.deinit(); } - pub fn header(self: *StateFile) *Header { - return @ptrCast(self.map.ptr); + pub fn live(self: *State) []align(page) u8 { + return self.bytes[0..self.layout.size]; } - pub fn slot(self: *StateFile, index: usize) []align(page) u8 { - std.debug.assert(index < slot_count); - const h = self.header(); - const start = header_len + index * h.stride; - return @alignCast(self.map[start..][0..h.size]); + /// Makes State hold `new`'s layout: a new allocation of its defaults + /// (`defaults`), then every leaf `migrate` keeps of the old State. Null + /// when the layout is unchanged, or there was none. + pub fn adopt(self: *State, gpa: std.mem.Allocator, new: abi.Layout, defaults: *const fn (abi.Memory, [*]u8) callconv(.c) void) !?Migration { + const first = self.bytes.len == 0; + if (!first and self.layout.hash == new.hash and self.layout.size == new.size) return null; + var arena: std.heap.ArenaAllocator = .init(gpa); + errdefer arena.deinit(); + const layout = try Layout.copy(arena.allocator(), new); + const region = try arena.allocator().alignedAlloc(u8, .of(Header), header_len); + @memset(region, 0); + const h: *Header = @ptrCast(region.ptr); + h.* = .{ .size = new.size, .alignment = new.alignment, .hash = new.hash, .stride = std.mem.alignForward(usize, @max(new.size, 1), page), .used = 1, .field_count = 0, .strings_len = 0 }; + try writeLayout(region, layout); + const bytes = try gpa.alignedAlloc(u8, .fromByteUnits(page), @max(new.size, 1)); + @memset(bytes, 0); + defaults(.state, bytes.ptr); + const m = if (first) null else migrate(self.layout, self.live(), layout, bytes); + self.deinit(gpa); + self.* = .{ .bytes = bytes, .layout = layout, .header = region[0 .. @sizeOf(Header) + @as(usize, h.field_count) * @sizeOf(StoredField) + h.strings_len], .arena = arena }; + return m; } +}; - pub fn used(self: *StateFile, index: usize) bool { - return self.header().used & (@as(u32, 1) << @intCast(index)) != 0; - } +/// A state file from before the sessions database held the present: a +/// layout header, then one slot (`file_magic`), or eight (`file_magic_v2`, +/// `file_magic_v1`), the first live State and the others snapshots. Mapped +/// read-only: imported once, never changed. +pub const OldState = struct { + map: []align(page) const u8, + slots: usize, - pub fn markUsed(self: *StateFile, index: usize, value: bool) void { - const bit = @as(u32, 1) << @intCast(index); - if (value) self.header().used |= bit else self.header().used &= ~bit; + /// error.FileNotFound when `path` is missing or empty; a file that is + /// no state file this host reads is refused. + pub fn open(path: []const u8) !OldState { + const map = mapReadOnly(path); + if (map.len == 0) return error.FileNotFound; + errdefer posix.munmap(map); + if (map.len < header_len) return error.NotAStateFile; + const h: *const Header = @ptrCast(map.ptr); + const slots: usize = if (std.mem.eql(u8, &h.magic, &file_magic)) 1 else if (std.mem.eql(u8, &h.magic, &file_magic_v2) or std.mem.eql(u8, &h.magic, &file_magic_v1)) old_slot_count else return error.NotAStateFile; + if (map.len < header_len + slots * h.stride or h.size > h.stride) return error.CorruptStateFile; + return .{ .map = map, .slots = slots }; } - pub const Adoption = union(enum) { - unchanged, - created, - migrated: Migration, - }; - - /// Makes the file hold `new`'s layout. Used slots are migrated: `defaults` - /// writes the new default values, then unchanged fields are copied over. - pub fn adopt(self: *StateFile, gpa: std.mem.Allocator, new: abi.Layout, defaults: *const fn (abi.Memory, [*]u8) callconv(.c) void) !Adoption { - if (self.layout.hash == new.hash and self.layout.size == new.size and self.header().used & 1 != 0) { - // Same type, older header: describe it again, bytes untouched. - if (std.mem.eql(u8, &self.header().magic, &file_magic_v1)) { - var kept = self.arena; - defer kept.deinit(); - self.arena = .init(gpa); - self.layout = try Layout.copy(self.arena.allocator(), new); - try writeLayout(self.map[0..header_len], self.layout); - self.header().magic = file_magic; - } - return .unchanged; - } - const had_state = self.header().used & 1 != 0; - - // Keep the old bytes and layout while the file is rebuilt. - var old_arena: std.heap.ArenaAllocator = .init(gpa); - defer old_arena.deinit(); - const old_layout = self.layout; - var old_slots: [slot_count]?[]u8 = @splat(null); - for (&old_slots, 0..) |*copy, i| { - if (self.used(i)) copy.* = try old_arena.allocator().dupe(u8, self.slot(i)); - } - const old_used = self.header().used; - // `old_layout` points into `self.arena`: move it aside before resetting. - var kept = self.arena; - defer kept.deinit(); - self.arena = .init(gpa); - - self.layout = try Layout.copy(self.arena.allocator(), new); - const stride = std.mem.alignForward(usize, @max(new.size, 1), page); - try self.resize(stride); - const h = self.header(); - h.* = .{ .magic = file_magic, .size = new.size, .alignment = new.alignment, .hash = new.hash, .stride = stride, .used = old_used, .field_count = 0, .strings_len = 0 }; - try writeLayout(self.map[0..header_len], self.layout); - - var total: Migration = .{}; - for (old_slots, 0..) |maybe_old, i| { - const old = maybe_old orelse continue; - const bytes = self.slot(i); - @memset(bytes, 0); - defaults(.state, bytes.ptr); - const m = migrate(old_layout, old, self.layout, bytes); - total.kept += m.kept; - if (i == 0) total.reset = m.reset; - } - if (!had_state) { - self.markUsed(0, false); - return .created; - } - return .{ .migrated = total }; + pub fn close(self: OldState) void { + posix.munmap(self.map); } - fn check(self: *StateFile) !void { - const h = self.header(); - if (!std.mem.eql(u8, &h.magic, &file_magic) and !std.mem.eql(u8, &h.magic, &file_magic_v1)) return error.NotAStateFile; - if (self.map.len < header_len + slot_count * h.stride or h.size > h.stride) return error.CorruptStateFile; + /// The header and layout, as `restore` and `layoutOf` take them. + pub fn layoutBytes(self: OldState) []const u8 { + return self.map[0..header_len]; } - fn resize(self: *StateFile, stride: usize) !void { - const len = header_len + slot_count * stride; - if (self.map.len != 0) posix.munmap(self.map); - self.map = &.{}; - switch (posix.errno(posix.system.ftruncate(self.fd, @intCast(len)))) { - .SUCCESS => {}, - else => |err| return posix.unexpectedErrno(err), - } - self.map = try mapFile(self.fd, len, .{ .READ = true, .WRITE = true }); + /// Slot `i`'s State, null when the slot is unused. + pub fn slot(self: OldState, i: usize) ?[]const u8 { + const h: *const Header = @ptrCast(self.map.ptr); + if (h.used & (@as(u32, 1) << @intCast(i)) == 0) return null; + return self.map[header_len + i * h.stride ..][0..h.size]; } }; +/// Fills `live` (laid out as `to`) from `image`, state kept in another +/// layout, described by `layout_bytes` (a header as `State.header` holds +/// it): `defaults`, then every leaf `migrate` keeps. Returns the +/// image's layout, `arena`'s. +pub fn restore(arena: std.mem.Allocator, layout_bytes: []const u8, image: []const u8, to: Layout, live: []u8, defaults: *const fn (abi.Memory, [*]u8) callconv(.c) void) !Layout { + const from = try layoutOf(arena, layout_bytes); + if (image.len != from.size) return error.CorruptKeyframe; + @memset(live, 0); + defaults(.state, live.ptr); + _ = migrate(from, image, to, live); + return from; +} + +/// The layout in a header as `State.header` holds it, `arena`'s. +pub fn layoutOf(arena: std.mem.Allocator, layout_bytes: []const u8) !Layout { + if (layout_bytes.len < @sizeOf(Header) or layout_bytes.len > header_len) return error.CorruptKeyframe; + const region = try arena.alignedAlloc(u8, .of(Header), header_len); + @memset(region, 0); + @memcpy(region[0..layout_bytes.len], layout_bytes); + return try readLayout(arena, region) orelse .{}; +} + +/// Whether `migrate` from `from` keeps `leaf`'s value: compared on these +/// only, state restored across a layout change differs nowhere it was reset. +pub fn keeps(from: Layout, leaf: Layout.Leaf) bool { + const before = from.pattern(leaf.path) orelse return false; + if (before.dims.len != leaf.dims.len) return false; + return (before.hash == leaf.hash and before.size == leaf.size) or (before.kind == .@"enum" and leaf.kind == .@"enum"); +} + /// Writes `layout`'s leaves after the `Header` at the start of `region`, /// in the current format (`StoredField`); the caller sets the magic. fn writeLayout(region: []u8, layout: Layout) !void { @@ -453,14 +440,14 @@ fn writeLayout(region: []u8, layout: Layout) !void { h.strings_len = @intCast(strings); } -/// The layout stored in a state or store file's header, or null if it has -/// none. Reads both formats, by magic: a v1 header (`file_magic_v1`, -/// `store_layout_magic_v1`) has no element leaves, so its arrays are whole -/// leaves only, which migrate while their type is unchanged. +/// The layout stored in a state file's header, or null if it has none. +/// Reads both formats, by magic: a v1 header (`file_magic_v1`) has no +/// element leaves, so its arrays are whole leaves only, which migrate while +/// their type is unchanged. pub fn readLayout(arena: std.mem.Allocator, map: []const u8) !?Layout { const h: *const Header = @ptrCast(@alignCast(map.ptr)); if (h.hash == 0 and h.field_count == 0) return null; - const v1 = std.mem.eql(u8, &h.magic, &file_magic_v1) or std.mem.eql(u8, &h.magic, &store_layout_magic_v1); + const v1 = std.mem.eql(u8, &h.magic, &file_magic_v1); const stride: usize = if (v1) @sizeOf(StoredFieldV1) else @sizeOf(StoredField); const strings_start = @sizeOf(Header) + @as(usize, h.field_count) * stride; if (strings_start + h.strings_len > header_len or map.len < header_len) return error.CorruptHeader; @@ -498,10 +485,6 @@ pub fn readLayout(arena: std.mem.Allocator, map: []const u8) !?Layout { return .{ .size = h.size, .alignment = h.alignment, .hash = h.hash, .fields = leaves }; } -pub fn mapFile(fd: posix.fd_t, len: usize, prot: posix.PROT) ![]align(page) u8 { - return posix.mmap(null, len, prot, .{ .TYPE = .SHARED }, fd, 0); -} - pub fn fileSize(fd: posix.fd_t) !u64 { var stat: linux.Statx = undefined; switch (linux.errno(linux.statx(fd, "", linux.AT.EMPTY_PATH, .{ .SIZE = true }, &stat))) { @@ -520,208 +503,6 @@ pub fn mapReadOnly(path: []const u8) []align(page) const u8 { return posix.mmap(null, @intCast(len), .{ .READ = true }, .{ .TYPE = .SHARED }, fd, 0) catch &.{}; } -/// Where every store is mapped, in every process: far from where Linux puts -/// executables (0x55...) and mappings (0x7f...). -pub const store_base: usize = 0x2000_0000_0000; -/// The most a store can grow to. Only reserved: pages exist as they are used. -pub const store_reserve: usize = 64 << 30; -/// The allocator's record (`Meta`); unchanged by the layout format. -pub const store_magic = "SKSTORE1".*; -/// The store's layout header, like `file_magic` and `file_magic_v1`. -pub const store_layout_magic = "SKSTORE2".*; -pub const store_layout_magic_v1 = "SKSTORE1".*; -/// The layout region is a state file header; the allocator's own record -/// follows, then the heap. -const meta_offset = header_len; -const heap_offset = 2 * header_len; - -/// A heap in a file, with the sketch's `Store` at its root. Mapped at -/// `store_base` in every run, so pointers it holds into itself stay valid -/// across restarts. Not crash-safe: a crash in the middle of an allocation -/// can leave it inconsistent (`--fresh` starts over). -/// -/// Blocks come in power-of-two sizes, each class with a free list threaded -/// through the free blocks, so growing a list by doubling reuses what it -/// frees. The file grows by mapping more of it in place: nothing moves. -pub const StoreFile = struct { - fd: posix.fd_t, - /// Bytes of the file mapped at `store_base`. - len: usize, - /// The root's layout, owned by `arena`. - layout: Layout, - arena: std.heap.ArenaAllocator, - - const Meta = extern struct { - magic: [8]u8 = store_magic, - base: u64 = store_base, - /// Offset of the first byte never handed out. - top: u64 = heap_offset, - /// Offset of the sketch's Store, or 0 before the first adopt. - root: u64 = 0, - /// Offsets of the first free block of each size class (2^i bytes), 0 - /// when none; a free block's first 8 bytes hold the next one's. - free: [64]u64 = @splat(0), - }; - - pub fn open(gpa: std.mem.Allocator, path: []const u8, fresh: bool) !StoreFile { - const fd = try posix.openat(posix.AT.FDCWD, path, .{ .ACCMODE = .RDWR, .CREAT = true }, 0o600); - errdefer _ = posix.system.close(fd); - // The same file mapped by two processes would be two heaps writing - // over each other. - if (linux.errno(linux.flock(fd, posix.LOCK.EX | posix.LOCK.NB)) != .SUCCESS) return error.StoreInUse; - const reserved = posix.mmap(@ptrFromInt(store_base), store_reserve, .{}, .{ .TYPE = .PRIVATE, .ANONYMOUS = true, .NORESERVE = true, .FIXED_NOREPLACE = true }, -1, 0) catch return error.StoreAddressTaken; - // Old kernels treat FIXED_NOREPLACE as a hint. - if (@intFromPtr(reserved.ptr) != store_base) { - posix.munmap(reserved); - return error.StoreAddressTaken; - } - errdefer posix.munmap(reserved); - var self: StoreFile = .{ .fd = fd, .len = 0, .layout = .{}, .arena = .init(gpa) }; - errdefer self.arena.deinit(); - const size: usize = @intCast(try fileSize(fd)); - if (!fresh and size > 0) { - // Checked before mapping, which may lengthen the file: a file - // that is not a store is refused untouched, never wiped. - var m: Meta = undefined; - const read = linux.pread(fd, std.mem.asBytes(&m), @sizeOf(Meta), meta_offset); - if (size < heap_offset or read != @sizeOf(Meta) or !std.mem.eql(u8, &m.magic, &store_magic) or m.base != store_base or m.top > size) return error.NotAStoreFile; - try self.grow(size); - self.layout = try readLayout(self.arena.allocator(), self.region()) orelse .{}; - return self; - } - try self.wipe(); - return self; - } - - pub fn close(self: *StoreFile) void { - posix.munmap(@as([*]align(page) u8, @ptrFromInt(store_base))[0..store_reserve]); - _ = posix.system.close(self.fd); - self.arena.deinit(); - } - - /// Empties the store: no root, nothing allocated. - fn wipe(self: *StoreFile) !void { - // Mapped pages past the new end would fault: map the reserve back. - if (self.len > heap_offset) { - _ = try posix.mmap(@ptrFromInt(store_base + heap_offset), self.len - heap_offset, .{}, .{ .TYPE = .PRIVATE, .ANONYMOUS = true, .NORESERVE = true, .FIXED = true }, -1, 0); - self.len = heap_offset; - } - try truncate(self.fd, heap_offset); - try self.grow(heap_offset); - @memset(self.region(), 0); - self.header().* = .{ .magic = store_layout_magic, .size = 0, .alignment = 1, .hash = 0, .stride = 0, .used = 0, .field_count = 0, .strings_len = 0 }; - self.meta().* = .{}; - self.layout = .{}; - } - - /// Maps the file up to `need` bytes, growing it when it is shorter. - fn grow(self: *StoreFile, need: usize) !void { - if (need <= self.len) return; - const len = std.mem.alignForward(usize, @max(need, self.len * 2, 1 << 20), page); - if (len > store_reserve) return error.StoreFull; - if (try fileSize(self.fd) < len) try truncate(self.fd, len); - _ = try posix.mmap(@ptrFromInt(store_base + self.len), len - self.len, .{ .READ = true, .WRITE = true }, .{ .TYPE = .SHARED, .FIXED = true }, self.fd, self.len); - self.len = len; - } - - fn region(_: *StoreFile) []u8 { - return @as([*]u8, @ptrFromInt(store_base))[0..header_len]; - } - fn header(_: *StoreFile) *Header { - return @ptrFromInt(store_base); - } - fn meta(_: *StoreFile) *Meta { - return @ptrFromInt(store_base + meta_offset); - } - - /// The sketch's Store. - pub fn root(self: *StoreFile) [*]u8 { - const offset = self.meta().root; - return @ptrFromInt(store_base + if (offset == 0) heap_offset else offset); - } - - pub const Adoption = StateFile.Adoption; - - /// Makes the root hold `new`'s layout: the new defaults, then every field - /// whose path and type are unchanged, copied over. Pointer fields keep - /// pointing where they did, since the store never moves. - pub fn adopt(self: *StoreFile, gpa: std.mem.Allocator, new: abi.Layout, defaults: *const fn (abi.Memory, [*]u8) callconv(.c) void) !Adoption { - const m = self.meta(); - if (m.root != 0 and self.layout.hash == new.hash and self.layout.size == new.size) return .unchanged; - const a = self.allocator(); - const alignment: std.mem.Alignment = .fromByteUnits(@max(new.alignment, 1)); - const fresh = a.rawAlloc(@max(new.size, 1), alignment, @returnAddress()) orelse return error.StoreFull; - @memset(fresh[0..@max(new.size, 1)], 0); - defaults(.store, fresh); - - var kept = self.arena; - defer kept.deinit(); - self.arena = .init(gpa); - const old_layout = self.layout; - self.layout = try Layout.copy(self.arena.allocator(), new); - var result: Adoption = .created; - if (m.root != 0) { - const old: [*]u8 = @ptrFromInt(store_base + m.root); - result = .{ .migrated = migrate(old_layout, old[0..old_layout.size], self.layout, fresh[0..new.size]) }; - a.rawFree(old[0..@max(old_layout.size, 1)], .fromByteUnits(@max(old_layout.alignment, 1)), @returnAddress()); - } - self.header().* = .{ .magic = store_layout_magic, .size = new.size, .alignment = new.alignment, .hash = new.hash, .stride = 0, .used = 1, .field_count = 0, .strings_len = 0 }; - try writeLayout(self.region(), self.layout); - m.root = @intFromPtr(fresh) - store_base; - return result; - } - - pub fn allocator(self: *StoreFile) std.mem.Allocator { - return .{ .ptr = self, .vtable = &.{ .alloc = alloc, .resize = resize, .remap = remap, .free = free } }; - } - - fn class(len: usize, alignment: std.mem.Alignment) u6 { - return @intCast(std.math.log2_int_ceil(usize, @max(len, alignment.toByteUnits(), 16))); - } - - fn alloc(ctx: *anyopaque, len: usize, alignment: std.mem.Alignment, _: usize) ?[*]u8 { - const self: *StoreFile = @ptrCast(@alignCast(ctx)); - const m = self.meta(); - const c = class(len, alignment); - const size = @as(usize, 1) << c; - if (m.free[c] != 0) { - const block: [*]u8 = @ptrFromInt(store_base + m.free[c]); - if (alignment.check(@intFromPtr(block))) { - m.free[c] = @as(*const u64, @ptrCast(@alignCast(block))).*; - return block; - } - } - const offset = std.mem.alignForward(usize, m.top, @max(@min(size, page), alignment.toByteUnits())); - self.grow(offset + size) catch return null; - m.top = offset + size; - return @ptrFromInt(store_base + offset); - } - - /// In place within the block's size class. - fn resize(_: *anyopaque, memory: []u8, alignment: std.mem.Alignment, new_len: usize, _: usize) bool { - return class(memory.len, alignment) == class(new_len, alignment); - } - - fn remap(ctx: *anyopaque, memory: []u8, alignment: std.mem.Alignment, new_len: usize, ret: usize) ?[*]u8 { - return if (resize(ctx, memory, alignment, new_len, ret)) memory.ptr else null; - } - - fn free(ctx: *anyopaque, memory: []u8, alignment: std.mem.Alignment, _: usize) void { - const self: *StoreFile = @ptrCast(@alignCast(ctx)); - const m = self.meta(); - const c = class(memory.len, alignment); - @as(*u64, @ptrCast(@alignCast(memory.ptr))).* = m.free[c]; - m.free[c] = @intFromPtr(memory.ptr) - store_base; - } -}; - -fn truncate(fd: posix.fd_t, len: usize) !void { - switch (posix.errno(posix.system.ftruncate(fd, @intCast(len)))) { - .SUCCESS => {}, - else => |err| return posix.unexpectedErrno(err), - } -} - /// Session memory: survives reloads while its layout hash is unchanged. /// Everything allocated from `heap` is released with it. pub const Session = struct { @@ -859,7 +640,7 @@ test "migration keeps unchanged fields and defaults the rest" { try std.testing.expectEqual(@as(usize, 1), m.reset); } -test "state file migrates live state and snapshots, and a reopen reads the layout back" { +test "State migrates to a changed layout, and keeps itself when it is unchanged" { const V1 = extern struct { score: u32 = 0, name: [4]u8 = "none".* }; const V2 = extern struct { level: u16 = 1, score: u32 = 0 }; const D = struct { @@ -870,71 +651,20 @@ test "state file migrates live state and snapshots, and a reopen reads the layou @as(*V2, @ptrCast(@alignCast(p))).* = .{}; } }; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - var buf: [std.fs.max_path_bytes]u8 = undefined; - const path = try std.mem.print(&buf, ".zig-cache/tmp/{s}/test.state", .{&tmp.sub_path}); - const gpa = std.testing.allocator; - { - var file = try StateFile.open(gpa, path); - defer file.close(); - try std.testing.expectEqual(StateFile.Adoption.created, try file.adopt(gpa, abi.layout.of(V1, .state), D.v1)); - file.markUsed(0, true); - @as(*V1, @ptrCast(file.slot(0).ptr)).score = 99; - @memcpy(file.slot(3), file.slot(0)); - file.markUsed(3, true); - } - var file = try StateFile.open(gpa, path); - defer file.close(); - try std.testing.expectEqual(abi.layout.hash(V1), file.layout.hash); - const adoption = try file.adopt(gpa, abi.layout.of(V2, .state), D.v2); - try std.testing.expectEqual(@as(usize, 1), adoption.migrated.reset); - for ([_]usize{ 0, 3 }) |i| { - const s: *V2 = @ptrCast(file.slot(i).ptr); - try std.testing.expectEqual(V2{ .level = 1, .score = 99 }, s.*); - } - try std.testing.expect(!file.used(1)); -} - -test "a store keeps its root and what it points to across a reopen, and migrates by field" { - const V1 = struct { list: std.ArrayList(u32) = .empty, count: u32 = 0 }; - const V2 = struct { added: u8 = 7, list: std.ArrayList(u32) = .empty }; - const D = struct { - fn v1(_: abi.Memory, p: [*]u8) callconv(.c) void { - @as(*V1, @ptrCast(@alignCast(p))).* = .{}; - } - fn v2(_: abi.Memory, p: [*]u8) callconv(.c) void { - @as(*V2, @ptrCast(@alignCast(p))).* = .{}; - } - }; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - var buf: [std.fs.max_path_bytes]u8 = undefined; - const path = try std.mem.print(&buf, ".zig-cache/tmp/{s}/test.store", .{&tmp.sub_path}); const gpa = std.testing.allocator; - { - var store = try StoreFile.open(gpa, path, false); - defer store.close(); - try std.testing.expectEqual(StoreFile.Adoption.created, try store.adopt(gpa, abi.layout.of(V1, .store), D.v1)); - const v: *V1 = @ptrCast(@alignCast(store.root())); - for (0..10_000) |i| try v.list.append(store.allocator(), @intCast(i)); - v.count = 3; - try std.testing.expectError(error.StoreInUse, StoreFile.open(gpa, path, false)); - } - { - var store = try StoreFile.open(gpa, path, false); - defer store.close(); - try std.testing.expectEqual(StoreFile.Adoption.unchanged, try store.adopt(gpa, abi.layout.of(V1, .store), D.v1)); - const adoption = try store.adopt(gpa, abi.layout.of(V2, .store), D.v2); - try std.testing.expectEqual(@as(usize, 1), adoption.migrated.reset); - const v: *V2 = @ptrCast(@alignCast(store.root())); - try std.testing.expectEqual(@as(u8, 7), v.added); - try std.testing.expectEqual(@as(u32, 9999), v.list.items[9999]); - v.list.deinit(store.allocator()); - } - var store = try StoreFile.open(gpa, path, true); - defer store.close(); - try std.testing.expectEqual(StoreFile.Adoption.created, try store.adopt(gpa, abi.layout.of(V2, .store), D.v2)); + var state: State = .init(gpa); + defer state.deinit(gpa); + try std.testing.expectEqual(@as(?Migration, null), try state.adopt(gpa, abi.layout.of(V1, .state), D.v1)); + @as(*V1, @ptrCast(state.live().ptr)).score = 99; + try std.testing.expectEqual(@as(?Migration, null), try state.adopt(gpa, abi.layout.of(V1, .state), D.v1)); + try std.testing.expectEqual(@as(u32, 99), @as(*V1, @ptrCast(state.live().ptr)).score); + const m = (try state.adopt(gpa, abi.layout.of(V2, .state), D.v2)).?; + try std.testing.expectEqual(@as(usize, 1), m.reset); + try std.testing.expectEqual(V2{ .level = 1, .score = 99 }, @as(*V2, @ptrCast(@alignCast(state.live().ptr))).*); + // The header reads back as the layout. + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + try std.testing.expectEqual(abi.layout.hash(V2), (try layoutOf(arena.allocator(), state.header)).hash); } test "arrays migrate element by element: fields, enums by name, shrink and growth" { @@ -1049,14 +779,15 @@ test "a file that is not a state file is refused, untouched" { defer std.testing.allocator.free(text); @memset(text, 'x'); try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = text }); - try std.testing.expectError(error.NotAStateFile, StateFile.open(std.testing.allocator, path)); + try std.testing.expectError(error.NotAStateFile, OldState.open(path)); const after = try std.Io.Dir.cwd().readFileAlloc(io, path, std.testing.allocator, .unlimited); defer std.testing.allocator.free(after); try std.testing.expectEqualSlices(u8, text, after); } + try std.testing.expectError(error.FileNotFound, OldState.open(try testPath(&buf, tmp, "none.state"))); } -test "a state file from before element leaves (drat-meout's) keeps every value" { +test "a state file from before element leaves (drat-meout's) imports with every value" { const gpa = std.testing.allocator; const io = std.testing.io; var tmp = std.testing.tmpDir(.{}); @@ -1076,30 +807,29 @@ test "a state file from before element leaves (drat-meout's) keeps every value" const h: *const Header = @ptrCast(@alignCast(original.ptr)); const live = original[header_len..][0..h.size]; - // The layout the game had when it wrote the file, as a sketch would - // describe it: unchanged, so nothing migrates and the header is - // rewritten in the new format. - const same = try asSketchLayout(a, old, &.{}); - { - var file = try StateFile.open(gpa, path); - defer file.close(); - try std.testing.expectEqual(StateFile.Adoption.unchanged, try file.adopt(gpa, same, NoDefaults.f)); - try std.testing.expectEqualStrings(&file_magic, &file.header().magic); - } - var file = try StateFile.open(gpa, path); + const file = try OldState.open(path); defer file.close(); - try std.testing.expectEqual(old.fields.len, file.layout.fields.len); - try std.testing.expectEqualSlices(u8, live, file.slot(0)); - - // A changed layout (one field gone, one new): every other leaf keeps - // its value, the songs included (an unchanged array type, so whole). - const changed = try asSketchLayout(a, old, "scene"); - _ = try file.adopt(gpa, changed, NoDefaults.f); - for (old.fields) |leaf| { - if (std.mem.eql(u8, leaf.path, "scene")) continue; - try std.testing.expectEqualSlices(u8, leaf.bytes(live), leaf.bytes(file.slot(0))); + try std.testing.expectEqual(@as(usize, old_slot_count), file.slots); + // Into the layout the game had when it wrote the file, as a sketch would + // describe it: every byte; then into a changed one (one field gone, one + // new): every other leaf keeps its value, the songs included (an + // unchanged array type, so whole). + for ([_][]const u8{ "", "scene" }) |drop| { + var state: State = .init(gpa); + defer state.deinit(gpa); + _ = try state.adopt(gpa, try asSketchLayout(a, old, drop), NoDefaults.f); + @memset(state.live(), 0); + _ = try restore(a, file.layoutBytes(), file.slot(0).?, state.layout, state.live(), NoDefaults.f); + if (drop.len == 0) try std.testing.expectEqualSlices(u8, live, state.live()); + for (old.fields) |leaf| { + if (drop.len > 0 and std.mem.eql(u8, leaf.path, drop)) continue; + try std.testing.expectEqualSlices(u8, leaf.bytes(live), leaf.bytes(state.live())); + } } - try std.testing.expectEqual(@as(u8, 0), file.slot(0)[h.size]); + // The file is as it was. + const after = try tmp.dir.readFileAlloc(io, "game.state", gpa, .unlimited); + defer gpa.free(after); + try std.testing.expectEqualSlices(u8, original, after); } const NoDefaults = struct { diff --git a/src/host/overlay.zig b/src/host/overlay.zig index e1fc45d..ec040e7 100644 --- a/src/host/overlay.zig +++ b/src/host/overlay.zig @@ -111,7 +111,7 @@ pub fn drawMemory(out: *List, arena: std.mem.Allocator, layout: memory.Layout, s } } -pub fn drawScope(out: *List, arena: std.mem.Allocator, samples: []const f32, rate: u32, canvas: [2]u32) !void { +pub fn drawScope(out: *List, arena: std.mem.Allocator, samples: []const f32, rate: u32, pull: u32, canvas: [2]u32) !void { const green: abi.Color = .{ .r = 105, .g = 245, .b = 160 }; const x = @as(f32, @floatFromInt(canvas[0])) - 526; const top = @as(f32, @floatFromInt(canvas[1])) - 130; @@ -119,7 +119,7 @@ pub fn drawScope(out: *List, arena: std.mem.Allocator, samples: []const f32, rat try out.append(arena, .{ .rect = .{ .dst = .{ .x = x, .y = top, .w = 514, .h = 118 }, .color = .{ .r = 24, .g = 24, .b = 24 } } }); try out.append(arena, .{ .rect = .{ .dst = .{ .x = x + 1, .y = mid, .w = 512, .h = 1 }, .color = .{ .r = 60, .g = 85, .b = 65 } } }); const ms = @as(f32, @floatFromInt(samples.len * 1000)) / @as(f32, @floatFromInt(@max(rate, 1))); - try out.append(arena, .{ .text = .{ .x = x + 8, .y = top + 10, .scale = 1, .color = green, .bytes = try std.fmt.allocPrint(arena, "OUTPUT ch1 / {d:.1}ms / overlay sound to hide", .{ms}) } }); + try out.append(arena, .{ .text = .{ .x = x + 8, .y = top + 10, .scale = 1, .color = green, .bytes = try std.fmt.allocPrint(arena, "OUTPUT ch1 / {d:.1}ms / pull {d} / overlay sound to hide", .{ ms, pull }) } }); for (samples, 0..) |sample, i| { const a = std.math.clamp(if (std.math.isFinite(sample)) sample else 0, -1, 1); const previous = samples[i -| 1]; diff --git a/src/host/probe.zig b/src/host/probe.zig deleted file mode 100644 index d8ed166..0000000 --- a/src/host/probe.zig +++ /dev/null @@ -1,86 +0,0 @@ -//! sketchbook-probe: prints the live state of any running sketch, from its -//! state file alone. The file header carries the layout, so the probe needs -//! no knowledge of the sketch: it maps the same pages read-only. -const std = @import("std"); -const memory = @import("memory.zig"); -const fields = @import("fields.zig"); - -const usage = - \\usage: sketchbook-probe [--watch] [--interval MS] STATE_FILE - \\Prints every field of the live state; --watch prints again on change. - \\ -; - -pub fn main(init: std.process.Init) !void { - var path: ?[]const u8 = null; - var watch = false; - var interval_ms: i64 = 100; - var args = init.minimal.args.iterate(); - _ = args.skip(); - while (args.next()) |arg| { - if (std.mem.eql(u8, arg, "--watch")) { - watch = true; - } else if (std.mem.eql(u8, arg, "--interval")) { - interval_ms = std.fmt.parseInt(i64, args.next() orelse "", 10) catch fatal("--interval needs milliseconds"); - } else if (std.mem.startsWith(u8, arg, "-")) { - std.debug.print("{s}", .{usage}); - return; - } else path = arg; - } - const file = path orelse fatal("no state file given"); - const map = memory.mapReadOnly(file); - if (map.len < memory.header_len) fatal("not a sketchbook state file"); - const magic = map[0..8]; - if (!std.mem.eql(u8, magic, &memory.file_magic) and !std.mem.eql(u8, magic, &memory.file_magic_v1)) fatal("not a sketchbook state file"); - defer std.posix.munmap(map); - var arena: std.heap.ArenaAllocator = .init(init.gpa); - defer arena.deinit(); - const layout = (try memory.readLayout(arena.allocator(), map)) orelse fatal("state file has no layout yet"); - const header: *const memory.Header = @ptrCast(@alignCast(map.ptr)); - const live = map[memory.header_len..][0..header.size]; - - const shown = try arena.allocator().dupe(u8, live); - show(file, layout, live); - while (watch) { - try std.Io.sleep(init.io, .fromMilliseconds(interval_ms), .awake); - if (std.mem.eql(u8, shown, live)) continue; - @memcpy(shown, live); - show(file, layout, live); - } -} - -fn show(path: []const u8, layout: memory.Layout, live: []const u8) void { - var buf: [4096]u8 = undefined; - var w: std.Io.Writer = .fixed(&buf); - std.debug.print("{s}: {d} bytes, layout {x:0>16}\n", .{ path, live.len, layout.hash }); - for (layout.fields) |leaf| { - // Whole arrays are shown by their elements' leaves. - if (leaf.whole()) continue; - w.end = 0; - if (leaf.dims.len == 0) { - fields.format(leaf, live, &w) catch {}; - } else { - // Elements in index order, the first few. - var it = leaf.elements(); - var n: usize = 0; - while (it.next()) |offset| : (n += 1) { - if (n == 8) { - w.writeAll(" ...") catch {}; - break; - } - if (n > 0) w.writeAll(" ") catch {}; - fields.format(leaf.at(offset), live, &w) catch {}; - } - } - var name: [128]u8 = undefined; - var nw: std.Io.Writer = .fixed(&name); - nw.writeAll(leaf.path) catch {}; - for (leaf.dims) |d| nw.print(" [{d}]", .{d.count}) catch {}; - std.debug.print(" +0x{x:0>4} {s:<28} {s}\n", .{ leaf.offset, nw.buffered(), w.buffered() }); - } -} - -fn fatal(message: []const u8) noreturn { - std.debug.print("sketchbook-probe: {s}\n{s}", .{ message, usage }); - std.process.exit(2); -} diff --git a/src/host/root.zig b/src/host/root.zig index 158f894..f15493b 100644 --- a/src/host/root.zig +++ b/src/host/root.zig @@ -1,20 +1,6 @@ //! The sketchbook host: runs a sketch linked in, or loaded from a library -//! that it hot-reloads whenever a build replaces it. -//! -//! sketchbook [options] [LIBRARY] -//! --state FILE persistent state (default: <name>.state) -//! --headless offscreen video, silent audio -//! --script FILE play a script instead of reading devices -//! --fresh start from default state: no snapshots or recordings -//! --timing-marker encode frame ID and draw sample time for video analysis -//! --profile-gpu time each GPU command alone, print the times at exit -//! --console LINE run a console line once the sketch is loaded (repeatable) -//! --define NAME=VALUE substitute {NAME} in the script -//! --export DIR|- headless, from fresh state: every frame as DIR/000000.png, ... -//! or for - as raw RGBA on stdout, until the sketch quits -//! --fps N export: frames a second (60); each tick is exactly 1/N s -//! --frames N export: stop after N frames -//! --size WxH the first canvas and, headless, the room for it +//! that it hot-reloads whenever a build replaces it. Its options are +//! `flags`, which parse the command line and print `--help`. const std = @import("std"); const c = @import("c"); const abi = @import("abi"); @@ -23,6 +9,10 @@ pub const memory = @import("memory.zig"); pub const fields = @import("fields.zig"); pub const script = @import("script.zig"); pub const timeline = @import("timeline.zig"); +const c9 = @import("cloud9"); +const control = @import("control.zig"); +const Sessions = @import("Sessions.zig"); +const Library = @import("library.zig").Library; /// Entry point for both the generic host (`linked == null`) and apps that /// link their sketch in. @@ -38,76 +28,63 @@ pub fn main(init: std.process.Init, linked: ?abi.Sketch) !void { var args = init.minimal.args.iterate(); _ = args.skip(); while (args.next()) |arg| { - if (std.mem.eql(u8, arg, "--state")) { - options.state = args.next() orelse fatal("--state needs a file"); - } else if (std.mem.eql(u8, arg, "--9p")) { - options.ninep = args.next() orelse fatal("--9p needs a socket path"); - } else if (std.mem.eql(u8, arg, "--fresh")) { - options.fresh = true; - } else if (std.mem.eql(u8, arg, "--headless")) { - options.headless = true; - } else if (std.mem.eql(u8, arg, "--timing-marker")) { - options.timing_marker = true; - } else if (std.mem.eql(u8, arg, "--profile-gpu")) { - options.profile_gpu = true; - } else if (std.mem.eql(u8, arg, "--console")) { - try lines.append(gpa, args.next() orelse fatal("--console needs a line")); - } else if (std.mem.eql(u8, arg, "--script")) { - script_path = args.next() orelse fatal("--script needs a file"); - } else if (std.mem.eql(u8, arg, "--define")) { - const pair = args.next() orelse fatal("--define needs NAME=VALUE"); - const eq = std.mem.indexOfScalar(u8, pair, '=') orelse fatal("--define needs NAME=VALUE"); - try defines.append(gpa, .{ pair[0..eq], pair[eq + 1 ..] }); - } else if (std.mem.eql(u8, arg, "--export")) { - options.export_to = args.next() orelse fatal("--export needs a directory, or - for stdout"); - options.headless = true; - options.fresh = true; - } else if (std.mem.eql(u8, arg, "--fps")) { - options.fps = std.fmt.parseInt(u32, args.next() orelse "", 10) catch 0; - if (options.fps == 0) fatal("--fps needs a whole number of frames a second"); - } else if (std.mem.eql(u8, arg, "--frames")) { - options.frames = std.fmt.parseInt(u64, args.next() orelse "", 10) catch fatal("--frames needs a number"); - } else if (std.mem.eql(u8, arg, "--size")) { - const size = args.next() orelse ""; - const x = std.mem.indexOfScalar(u8, size, 'x') orelse fatal("--size needs WxH"); - const w = std.fmt.parseInt(u32, size[0..x], 10) catch 0; - const h = std.fmt.parseInt(u32, size[x + 1 ..], 10) catch 0; - if (w == 0 or h == 0) fatal("--size needs WxH"); - options.size = .{ w, h }; - } else if (std.mem.eql(u8, arg, "-h") or std.mem.eql(u8, arg, "--help")) { - std.debug.print("{s}", .{usage}); - return; - } else if (std.mem.startsWith(u8, arg, "-")) { - fatal("unknown option (see --help)"); - } else { + if (std.mem.eql(u8, arg, "fs")) { + var words: std.ArrayList([]const u8) = .empty; + defer words.deinit(gpa); + while (args.next()) |word| try words.append(gpa, word); + std.process.exit(try fs(init, linked, options, words.items)); + } + if (!std.mem.startsWith(u8, arg, "-")) { options.library = arg; + continue; + } + const flag: Flag = if (std.mem.eql(u8, arg, "-h")) .help else (if (std.mem.startsWith(u8, arg, "--")) std.meta.stringToEnum(Flag, arg[2..]) else null) orelse fatal("{s} is no option (see --help)", .{arg}); + const v = if (flags.get(flag).arg.len == 0) "" else args.next() orelse fatal("{s} needs {s}", .{ arg, flags.get(flag).arg }); + switch (flag) { + .@"9p" => options.ninep = v, + .state => options.state = v, + .headless => options.headless = true, + .script => { + script_path = v; + options.script = true; + }, + .fresh => options.fresh = true, + .@"timing-marker" => options.timing_marker = true, + .@"profile-gpu" => options.profile_gpu = true, + .console => try lines.append(gpa, v), + .define => { + const eq = std.mem.indexOfScalar(u8, v, '=') orelse fatal("{s} needs {s}", .{ arg, "NAME=VALUE" }); + try defines.append(gpa, .{ v[0..eq], v[eq + 1 ..] }); + }, + .@"export" => { + options.export_to = v; + options.headless = true; + options.fresh = true; + }, + .fps => options.fps = std.fmt.parseInt(u32, v, 10) catch 0, + .frames => options.frames = std.fmt.parseInt(u64, v, 10) catch fatal("{s} needs {s}", .{ arg, "a number" }), + .size => { + const x = std.mem.indexOfScalar(u8, v, 'x') orelse 0; + const w = std.fmt.parseInt(u32, v[0..x], 10) catch 0; + const h = std.fmt.parseInt(u32, v[x + 1 ..], 10) catch 0; + if (w == 0 or h == 0) fatal("{s} needs {s}", .{ arg, "WxH" }); + options.size = .{ w, h }; + }, + .help => return std.debug.print("{s}", .{usage}), } + if (options.fps == 0) fatal("{s} needs {s}", .{ arg, "a whole number of frames a second" }); } - if (linked == null and options.library == null) fatal("no sketch library given (see --help)"); + if (linked == null and options.library == null) fatal("no sketch library given (see --help)", .{}); if (options.export_to) |to| { - if (script_path != null) fatal("--export plays no script: it runs the sketch on its own"); + if (script_path != null) fatal("--export plays no script: it runs the sketch on its own", .{}); if (!std.mem.eql(u8, to, "-")) { try std.Io.Dir.cwd().createDirPath(init.io, to); - } else if (try std.Io.File.stdout().isTty(init.io)) fatal("--export -: stdout is a terminal; pipe it to ffmpeg"); + } else if (try std.Io.File.stdout().isTty(init.io)) fatal("--export -: stdout is a terminal; pipe it to ffmpeg", .{}); } - // A scripted run from fresh state works on files of its own, moved to - // the given path at exit: two runs of one build step (two `zig build`s - // at once share its output path) never share a state, store or - // recordings file, nor fail on the store's lock. An export's are - // removed instead: nothing reads them, and a player may have the given - // ones open. - var private_buf: [std.fs.max_path_bytes]u8 = undefined; - const given = options.state; - const private = (script_path != null or options.export_to != null) and options.fresh; - if (private) options.state = std.mem.print(&private_buf, "{s}.{d}", .{ given, std.os.linux.getpid() }) catch fatal("--state path too long"); - defer if (private) for ([_][]const u8{ "", ".inputs", ".store" }) |suffix| { - var from: [std.fs.max_path_bytes + 16]u8 = undefined; - var to: [std.fs.max_path_bytes + 16]u8 = undefined; - const a = std.mem.printSentinel(&from, "{s}{s}", .{ options.state, suffix }, 0) catch continue; - const b = std.mem.printSentinel(&to, "{s}{s}", .{ given, suffix }, 0) catch continue; - _ = if (options.export_to != null) std.os.linux.unlink(a.ptr) else std.os.linux.rename(a.ptr, b.ptr); - }; + if (options.state.len == 0 and (script_path != null or options.export_to != null)) options.state = "sketch.xitdb"; + // A scripted run from fresh state, or an export, touches no save. + if (!((script_path != null or options.export_to != null) and options.fresh)) sketchbookDir(init.io, options.state); sdl_heap.install(); { @@ -124,27 +101,144 @@ pub fn main(init: std.process.Init, linked: ?abi.Sketch) !void { if (sdl_heap.leaked()) return error.LeakedSdlMemory; } -const usage = - \\usage: sketchbook [options] [LIBRARY] - \\ --9p SOCKET local 9P controls: ctl, status, log, screen.png - \\ --state FILE persistent state (default: sketch.state) - \\ --headless offscreen video, silent audio, no vsync - \\ --script FILE play a script instead of reading devices - \\ --fresh start from default state: no snapshots or recordings - \\ --timing-marker encode frame ID and draw sample time for video analysis - \\ --profile-gpu time each GPU command alone, print the times at exit - \\ --console LINE run a console line once the sketch is loaded (repeatable) - \\ --define NAME=VALUE substitute {NAME} in the script - \\ --export DIR|- headless, from fresh state: every frame as DIR/000000.png, ... - \\ or for - as raw RGBA on stdout, until the sketch quits - \\ --fps N export: frames a second (60); each tick is exactly 1/N s - \\ --frames N export: stop after N frames - \\ --size WxH the first canvas and, headless, the room for it - \\ -; +/// The options: a row each, what parses the command line (the switch in +/// `main` sets what each one means) and prints `--help`. +const Flag = enum { @"9p", state, headless, script, fresh, @"timing-marker", @"profile-gpu", console, define, @"export", fps, frames, size, help }; +const flags = std.enums.EnumArray(Flag, struct { arg: []const u8 = "", doc: []const u8 }).init(.{ + .@"9p" = .{ .arg = "NAME|/SOCKET", .doc = "the 9P tree (README, ctl, state/, screen.png...), posted as sketchbook/NAME\n(a run in a window posts its own name), or at a socket path" }, + .state = .{ .arg = "FILE", .doc = "the save, one file: FILE, or FILE.xitdb for a FILE.state (where a\nstate file from before is imported from, once); default:\n$XDG_DATA_HOME/<name>/<name>.xitdb, sketch.xitdb for --script, --export" }, + .headless = .{ .doc = "offscreen video, silent audio, no vsync" }, + .script = .{ .arg = "FILE", .doc = "play a script instead of reading devices" }, + .fresh = .{ .doc = "start from default state (the save's history is kept)" }, + .@"timing-marker" = .{ .doc = "encode frame ID and draw sample time for video analysis" }, + .@"profile-gpu" = .{ .doc = "time each GPU command alone, print the times at exit" }, + .console = .{ .arg = "LINE", .doc = "run a console line once the sketch is loaded (repeatable)" }, + .define = .{ .arg = "NAME=VALUE", .doc = "substitute {NAME} in the script" }, + .@"export" = .{ .arg = "DIR|-", .doc = "headless, from fresh state: every frame as DIR/000000.png, ...\nor for - as raw RGBA on stdout, until the sketch quits" }, + .fps = .{ .arg = "N", .doc = "export: frames a second (60); each tick is exactly 1/N s" }, + .frames = .{ .arg = "N", .doc = "export: stop after N frames" }, + .size = .{ .arg = "WxH", .doc = "the first canvas and, headless, the room for it" }, + .help = .{ .doc = "this, also -h" }, +}); + +/// `--help`: a line per flag, its doc's lines under one another. +const usage = blk: { + @setEvalBranchQuota(100_000); + const pad: [23]u8 = @splat(' '); + var text: []const u8 = "usage: sketchbook [options] [LIBRARY] [fs VERB [PATH [WORDS...]]]\n"; + for (std.enums.values(Flag)) |flag| { + const f = flags.get(flag); + const head = " --" ++ @tagName(flag) ++ (if (f.arg.len > 0) " " ++ f.arg else ""); + text = text ++ head ++ pad[@min(head.len, pad.len)..]; + var lines = std.mem.splitScalar(u8, f.doc, '\n'); + text = text ++ lines.first() ++ "\n"; + while (lines.next()) |more| text = text ++ pad ++ more ++ "\n"; + } + break :blk text; +}; + +/// `fs VERB [PATH [WORDS]]`: cloud9's verbs on the sketch's tree. The +/// running sketch's, posted as sketchbook/<name> (or at --9p); with none, +/// the same tree served here from the save's newest State (--state's, or +/// the default save), else from the State's defaults: README, commands, +/// state/ answer, and the rest say the sketch is not running. No window. +fn fs(init: std.process.Init, linked: ?abi.Sketch, options: Host.Options, words: []const []const u8) !u8 { + const gpa = init.gpa; + const io = init.io; + const env = init.environ_map; + var in_buf: [4096]u8 = undefined; + var out_buf: [4096]u8 = undefined; + var err_buf: [1024]u8 = undefined; + var in = std.Io.File.stdin().reader(io, &in_buf); + var out = std.Io.File.stdout().writer(io, &out_buf); + var err = std.Io.File.stderr().writer(io, &err_buf); + const user = env.get("USER") orelse "sketchbook"; + var library: ?Library = null; + defer if (library) |*l| l.close(); + const sketch = linked orelse blk: { + library = try Library.openFresh(io, options.library orelse fatal("fs needs the sketch library first: sketchbook LIBRARY fs ...", .{}), Host.scratchDir(env), 0); + break :blk library.?.sketch; + }; + const info = sketch.info(); + const no_env = [_:null]?[*:0]const u8{}; + var f: c9.Fsys = undefined; + var path_buf: [c9.post.sun_path_len]u8 = undefined; + const where = options.ninep orelse info.name; + const path = if (std.mem.startsWith(u8, where, "/")) where else control.registered(env, where, &path_buf) catch ""; + if (f.dial(io, &no_env, path, user)) |_| { + defer f.close(); + return c9.verbs.run(&f, words, &in.interface, &out.interface, &err.interface); + } else |_| {} + + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const layout = try memory.Layout.copy(arena.allocator(), info.state); + const bytes = try arena.allocator().alignedAlloc(u8, .fromByteUnits(memory.page), layout.size); + @memset(bytes, 0); + sketch.defaults(.state, bytes.ptr); + var from = try std.fmt.allocPrint(arena.allocator(), "{s} is not running: this is its State's defaults (no save)", .{info.name}); + var data_buf: [std.fs.max_path_bytes]u8 = undefined; + const save = if (options.state.len > 0) + try std.fmt.allocPrint(arena.allocator(), "{s}.xitdb", .{Host.stemOf(options.state)}) + else + try std.fmt.allocPrint(arena.allocator(), "{s}/{s}/{s}.xitdb", .{ env.get("XDG_DATA_HOME") orelse try std.fmt.bufPrint(&data_buf, "{s}/.local/share", .{env.get("HOME") orelse "."}), info.name, info.name }); + if (Sessions.openRead(gpa, io, save)) |opened| { + var s = opened; + defer s.deinit(); + var events: std.ArrayList(abi.Event) = .empty; + defer events.deinit(gpa); + if (try s.present(&events)) |key| { + defer key.free(gpa); + _ = try memory.restore(arena.allocator(), key.layout, key.state, layout, bytes, sketch.defaults); + from = try std.fmt.allocPrint(arena.allocator(), "{s} is not running: this is its save's newest State, frame {d} of {s}", .{ info.name, key.frame, save }); + } + } else |_| {} + const commands = try arena.allocator().alloc([]const u8, info.commands.len); + for (commands, info.commands) |*to, word| to.* = word; + var server: control.Control = .{ .allocator = gpa, .path = undefined, .listener = -1, .offline = .{ .layout = layout, .bytes = bytes, .completions = commands, .from = from } }; + var fds: [2]i32 = undefined; + if (std.c.socketpair(std.c.AF.UNIX, std.c.SOCK.STREAM | std.c.SOCK.CLOEXEC, 0, &fds) != 0) return error.SocketPair; + const thread = try std.Thread.spawn(.{}, control.Control.serveOffline, .{ &server, fds[0] }); + defer thread.join(); + try f.init(io, .{ .socket = .{ .handle = fds[1], .address = undefined } }, user); + defer f.close(); + // A read answered here is not the running sketch's: said on stderr, so + // a script that reads before the sketch is up does not take it for one. + if (words.len > 0 and std.mem.eql(u8, words[0], "read")) { + try err.interface.print("{s}\n", .{from}); + try err.interface.flush(); + } + return c9.verbs.run(&f, words, &in.interface, &out.interface, &err.interface); +} + +/// A save in a directory named `.sketchbook` (`zig build run`'s): the +/// directory is made, with a `.gitignore` of `*` (the save grows, and a jj +/// snapshot would commit it), and the state file an older build kept beside +/// it (`<stem>.state`) is moved in, once, to be imported. A file is never +/// replaced: when both exist, nothing moves. +fn sketchbookDir(io: std.Io, state: []const u8) void { + const dir = std.fs.path.dirname(state) orelse return; + if (!std.mem.eql(u8, std.fs.path.basename(dir), ".sketchbook")) return; + const cwd = std.Io.Dir.cwd(); + cwd.createDirPath(io, dir) catch return; + var buf: [std.fs.max_path_bytes]u8 = undefined; + const ignore = std.fmt.bufPrint(&buf, "{s}/.gitignore", .{dir}) catch return; + cwd.writeFile(io, .{ .sub_path = ignore, .data = "*\n", .flags = .{ .exclusive = true } }) catch {}; + var from_buf: [std.fs.max_path_bytes]u8 = undefined; + var to_buf: [std.fs.max_path_bytes]u8 = undefined; + const parent = std.fs.path.dirname(dir) orelse "."; + const stem = Host.stemOf(std.fs.path.basename(state)); + const from = std.fmt.bufPrintSentinel(&from_buf, "{s}/{s}.state", .{ parent, stem }, 0) catch return; + const to = std.fmt.bufPrintSentinel(&to_buf, "{s}/{s}.state", .{ dir, stem }, 0) catch return; + switch (std.os.linux.errno(std.os.linux.renameat2(std.os.linux.AT.FDCWD, from.ptr, std.os.linux.AT.FDCWD, to.ptr, .{ .NOREPLACE = true }))) { + .SUCCESS => std.debug.print("sketchbook: moved {s} to {s}\n", .{ from, to }), + .EXIST => std.debug.print("sketchbook: {s} and {s} both exist: nothing moved, {s} is used\n", .{ from, to, to }), + else => {}, + } +} -fn fatal(message: []const u8) noreturn { - std.debug.print("sketchbook: {s}\n", .{message}); +fn fatal(comptime fmt: []const u8, args: anytype) noreturn { + std.debug.print("sketchbook: " ++ fmt ++ "\n", args); std.process.exit(2); } @@ -202,8 +296,10 @@ test { _ = memory; _ = fields; _ = timeline; + _ = @import("Sessions.zig"); _ = @import("audio.zig"); _ = @import("Console.zig"); _ = @import("control.zig"); + _ = @import("state_files.zig"); _ = @import("timing_marker.zig"); } diff --git a/src/host/script.zig b/src/host/script.zig index 7818c6b..e3976e0 100644 --- a/src/host/script.zig +++ b/src/host/script.zig @@ -1,58 +1,60 @@ //! End-to-end scripts: plain text that plays a sketch like a person would, -//! through the same routing and frames, on a fixed 60 Hz clock. -//! -//! # comment -//! click 710 320 move there, press and release the left button -//! move|down|up X Y one pointer event, then a frame -//! wheel|wheel-x X Y DELTA -//! cancel what losing focus sends -//! key NAME press and release a key (`sketch.Key` names) -//! type TEXT text input, as typed into a focused field -//! console LINE run a console command (`console get` -//! takes no frame: it only reads) -//! frames N advance N frames without input -//! expect FIELD VALUE compare a state field (enums by name or number); -//! FIELD may index arrays and vector lanes, -//! `boids.buffer[3].pos[0]` -//! expect FIELD VALUE ~T numbers within T of VALUE -//! await FIELD VALUE [~T] run frames until it holds (a minute at most) -//! print FIELD write a field's value to stderr (a vector, -//! array or struct: every value in it), no frame -//! expect-snapshot N live state equals snapshot N, leaf by leaf -//! (padding ignored), exactly -//! expect-log TEXT a recent console line contains TEXT -//! expect-no-log TEXT no recent console line does -//! expect-audio KEY stream KEY has received samples -//! screenshot FILE save the next frame as PNG -//! expect-same-screenshot A B [MAX [X Y W H]] -//! two saved PNGs match, every channel within MAX -//! (default 0), in the rect if given (pixels) -//! expect-different-screenshot A B [X Y W H] -//! two saved PNGs differ somewhere (in the rect) -//! expect-pixel FILE X Y R G B A [TOL] -//! a saved PNG's pixel, every channel within TOL -//! load LIBRARY swap in another build of the sketch -//! reload load the watched library again -//! await-reload SECONDS run frames until a build replaces the library -//! -//! `{name}` is replaced by `--define name=value` from the command line. -//! -//! Each line but `frames`, `print`, `console get`, the expectations and -//! `await-reload` is followed by one frame; `update` gets one call per -//! frame, live or replayed, so -//! `console play` then `frames N` replays N recorded frames at the -//! script's 60 Hz. +//! through the same routing and frames, on a fixed 60 Hz clock. A line is +//! a verb of `verbs` and its words; `# comment`; `{name}` is replaced by +//! `--define name=value` from the command line. `update` gets one call per +//! frame, live or replayed, so `console play` then `frames N` replays N +//! recorded frames at the script's 60 Hz. const std = @import("std"); const c = @import("c"); const abi = @import("abi"); const Host = @import("Host.zig"); const fields = @import("fields.zig"); const memory = @import("memory.zig"); +const Console = @import("Console.zig"); +const Sessions = @import("Sessions.zig"); pub const frame_ns: u64 = std.time.ns_per_s / 60; /// The most frames `await` plays: a minute. const await_limit = 60 * 60; +/// The script's verbs, a row each. A verb with `frame` is followed by one +/// frame; the `input` verbs are also what a 9P `ctl` takes live (`input`). +pub const Verb = enum { click, move, down, up, wheel, @"wheel-x", cancel, key, hold, release, type, console, frames, expect, await, print, @"expect-snapshot", @"expect-key", @"expect-log", @"expect-no-log", @"expect-audio", @"expect-no-audio", screenshot, @"expect-same-screenshot", @"expect-different-screenshot", @"expect-pixel", load, reload, @"await-reload", kill, quit }; +pub const Row = struct { args: []const u8 = "", doc: []const u8, frame: bool = false, input: bool = false }; +pub const verbs = std.enums.EnumArray(Verb, Row).init(.{ + .click = .{ .args = "X Y", .doc = "move there, press and release the left button", .frame = true, .input = true }, + .move = .{ .args = "X Y", .doc = "a pointer move", .frame = true, .input = true }, + .down = .{ .args = "X Y", .doc = "the left button down there", .frame = true, .input = true }, + .up = .{ .args = "X Y", .doc = "the left button up there", .frame = true, .input = true }, + .wheel = .{ .args = "X Y DELTA", .doc = "a wheel turn", .frame = true, .input = true }, + .@"wheel-x" = .{ .args = "X Y DELTA", .doc = "a sideways wheel turn", .frame = true, .input = true }, + .cancel = .{ .doc = "what losing focus sends", .frame = true, .input = true }, + .key = .{ .args = "NAME", .doc = "press and release a key (`sketch.Key` names)", .frame = true, .input = true }, + .hold = .{ .args = "NAME", .doc = "a key down until released, for modifiers", .frame = true, .input = true }, + .release = .{ .args = "NAME", .doc = "a held key up", .frame = true, .input = true }, + .type = .{ .args = "TEXT", .doc = "text input, as typed into a focused field", .frame = true, .input = true }, + .console = .{ .args = "LINE", .doc = "a console line (`console get` takes no frame: it only reads); one that fails fails the script", .frame = true }, + .frames = .{ .args = "N", .doc = "N frames without input" }, + .expect = .{ .args = "FIELD VALUE [~T]", .doc = "a State field holds VALUE (enums by name or number; numbers within T); FIELD may index arrays and vector lanes, `boids.buffer[3].pos[0]`" }, + .await = .{ .args = "FIELD VALUE [~T]", .doc = "frames until expect holds, a minute at most" }, + .print = .{ .args = "FIELD", .doc = "a field's value to stderr (a vector, array or struct: every value in it)" }, + .@"expect-snapshot" = .{ .args = "NAME", .doc = "live State equals the newest mark NAME, leaf by leaf (padding, and leaves a layout change reset, ignored)" }, + .@"expect-key" = .{ .args = "WHY FIELD VALUE", .doc = "the newest keyframe of this session taken for WHY (`Sessions.Why`: before_reload, mark...) holds VALUE, read in its own layout" }, + .@"expect-log" = .{ .args = "TEXT", .doc = "a recent console line contains TEXT" }, + .@"expect-no-log" = .{ .args = "TEXT", .doc = "no recent console line does" }, + .@"expect-audio" = .{ .args = "KEY", .doc = "stream KEY has received samples, or voice KEY sounded since the last check of it" }, + .@"expect-no-audio" = .{ .args = "KEY", .doc = "voice KEY did not sound since the last check" }, + .screenshot = .{ .args = "FILE", .doc = "save the next frame as PNG", .frame = true }, + .@"expect-same-screenshot" = .{ .args = "A B [MAX [X Y W H]]", .doc = "two saved PNGs match, every channel within MAX (0), in the rect if given (pixels)" }, + .@"expect-different-screenshot" = .{ .args = "A B [X Y W H]", .doc = "two saved PNGs differ somewhere (in the rect)" }, + .@"expect-pixel" = .{ .args = "FILE X Y R G B A [TOL]", .doc = "a saved PNG's pixel, every channel within TOL" }, + .load = .{ .args = "LIBRARY", .doc = "swap in another build of the sketch", .frame = true }, + .reload = .{ .doc = "load the watched library again", .frame = true }, + .@"await-reload" = .{ .args = "SECONDS", .doc = "frames until a build replaces the library" }, + .kill = .{ .doc = "die by SIGKILL, as a crash would" }, + .quit = .{ .doc = "end the run" }, +}); + pub fn run(host: *Host, source: []const u8, defines: []const [2][]const u8) !void { var arena: std.heap.ArenaAllocator = .init(host.gpa); defer arena.deinit(); @@ -65,9 +67,9 @@ pub fn run(host: *Host, source: []const u8, defines: []const [2][]const u8) !voi const line = try substitute(arena.allocator(), std.mem.trim(u8, raw, " \t\r"), defines); if (line.len == 0 or line[0] == '#') continue; var words = std.mem.tokenizeAny(u8, line, " \t"); - const command = words.next().?; + const verb = std.meta.stringToEnum(Verb, words.next().?); const rest = std.mem.trim(u8, words.rest(), " \t"); - step(host, arena.allocator(), command, rest, &words, &now) catch |err| { + (if (verb) |v| step(host, arena.allocator(), v, rest, &words, &now) else error.UnknownScriptCommand) catch |err| { failures += 1; std.debug.print("script:{d}: {s}: {t}\n", .{ number, line, err }); if (err != error.ExpectationFailed) break; @@ -77,160 +79,210 @@ pub fn run(host: *Host, source: []const u8, defines: []const [2][]const u8) !voi if (failures > 0) return error.ScriptFailed; } -fn step(host: *Host, arena: std.mem.Allocator, command: []const u8, rest: []const u8, words: anytype, now: *u64) !void { - const eq = std.mem.eql; - if (eq(u8, command, "click")) { - const x, const y = try point(words); - try host.route(.{ .kind = .mouse_move, .time = now.*, .x = x, .y = y, .flags = held(host) }); - try host.route(.{ .kind = .mouse_down, .time = now.*, .x = x, .y = y, .code = 1, .flags = held(host) }); - try host.route(.{ .kind = .mouse_up, .time = now.*, .x = x, .y = y, .code = 1, .flags = held(host) }); - } else if (eq(u8, command, "move") or eq(u8, command, "down") or eq(u8, command, "up")) { - const x, const y = try point(words); - const kind: abi.Event.Kind = if (eq(u8, command, "move")) .mouse_move else if (eq(u8, command, "down")) .mouse_down else .mouse_up; - try host.route(.{ .kind = kind, .time = now.*, .x = x, .y = y, .code = if (kind == .mouse_move) 0 else 1, .flags = held(host) }); - } else if (eq(u8, command, "wheel") or eq(u8, command, "wheel-x")) { - const x, const y = try point(words); - const delta = try std.fmt.parseFloat(f32, words.next() orelse return error.ExpectedDelta); - try host.route(.{ .kind = if (eq(u8, command, "wheel-x")) .wheel_horizontal else .wheel, .time = now.*, .x = x, .y = y, .value = @bitCast(delta), .flags = held(host) }); - } else if (eq(u8, command, "cancel")) { - try host.route(.{ .kind = .cancel, .time = now.* }); - } else if (eq(u8, command, "key")) { - const key = std.meta.stringToEnum(abi.Key, rest) orelse return error.UnknownKey; - try host.route(.{ .kind = .key_down, .time = now.*, .code = @backingInt(key) }); - try host.route(.{ .kind = .key_up, .time = now.*, .code = @backingInt(key) }); - } else if (eq(u8, command, "hold") or eq(u8, command, "release")) { - const key = std.meta.stringToEnum(abi.Key, rest) orelse return error.UnknownKey; - try host.route(.{ .kind = if (eq(u8, command, "hold")) .key_down else .key_up, .time = now.*, .code = @backingInt(key) }); - } else if (eq(u8, command, "type")) { - for (rest) |byte| try host.route(.{ .kind = .text, .time = now.*, .value = byte }); - } else if (eq(u8, command, "console")) { - // A failing console line fails the script, like a failed expect. - host.runLine(rest, now.*) catch |err| { - std.debug.print(" console {s}: {t}\n", .{ rest, err }); - return err; - }; - if (std.mem.startsWith(u8, rest, "get ")) return; - } else if (eq(u8, command, "print")) { - const path = words.next() orelse return error.ExpectedField; - var buf: [4096]u8 = undefined; - var w: std.Io.Writer = .fixed(&buf); - fields.formatPath(host.state.layout, host.live(), path, &w) catch |err| switch (err) { - error.UnknownField => return error.UnknownField, - error.WriteFailed => {}, - }; - std.debug.print("{s} = {s}\n", .{ path, w.buffered() }); - return; - } else if (eq(u8, command, "frames")) { - const count = try std.fmt.parseInt(usize, rest, 10); - for (0..count) |_| try advance(host, now); - return; - } else if (eq(u8, command, "expect") or eq(u8, command, "await")) { - const path = words.next() orelse return error.ExpectedField; - const want, const tolerance = try expected(std.mem.trim(u8, words.rest(), " \t")); - // Looked up again after each frame: a reload may move the field. - _ = host.state.layout.find(path) orelse return error.UnknownField; - // `await` plays frames until the field holds the value, for up to a - // minute: for waits whose length is the sketch's business. - if (eq(u8, command, "await")) { - var waited: usize = 0; - while (!holds(host, path, want, tolerance) and waited < await_limit) : (waited += 1) try advance(host, now); - } - if (!holds(host, path, want, tolerance)) { - var buf: [128]u8 = undefined; +/// Routes an input verb's events at `now`, no frame after: a script's +/// line, or a 9P `ctl` line live. +pub fn input(host: *Host, verb: Verb, words: *std.mem.TokenIterator(u8, .any), now: u64) !void { + const rest = std.mem.trim(u8, words.rest(), " \t"); + switch (verb) { + .click => { + const x, const y = try point(words); + try host.route(.{ .kind = .mouse_move, .time = now, .x = x, .y = y, .flags = held(host) }); + try host.route(.{ .kind = .mouse_down, .time = now, .x = x, .y = y, .code = 1, .flags = held(host) }); + try host.route(.{ .kind = .mouse_up, .time = now, .x = x, .y = y, .code = 1, .flags = held(host) }); + }, + .move, .down, .up => { + const x, const y = try point(words); + const kind: abi.Event.Kind = switch (verb) { + .move => .mouse_move, + .down => .mouse_down, + else => .mouse_up, + }; + try host.route(.{ .kind = kind, .time = now, .x = x, .y = y, .code = if (kind == .mouse_move) 0 else 1, .flags = held(host) }); + }, + .wheel, .@"wheel-x" => { + const x, const y = try point(words); + const delta = try std.fmt.parseFloat(f32, words.next() orelse return error.ExpectedDelta); + try host.route(.{ .kind = if (verb == .@"wheel-x") .wheel_horizontal else .wheel, .time = now, .x = x, .y = y, .value = @bitCast(delta), .flags = held(host) }); + }, + .cancel => try host.route(.{ .kind = .cancel, .time = now }), + .key => { + const key = std.meta.stringToEnum(abi.Key, rest) orelse return error.UnknownKey; + try host.route(.{ .kind = .key_down, .time = now, .code = @backingInt(key) }); + try host.route(.{ .kind = .key_up, .time = now, .code = @backingInt(key) }); + }, + .hold, .release => { + const key = std.meta.stringToEnum(abi.Key, rest) orelse return error.UnknownKey; + try host.route(.{ .kind = if (verb == .hold) .key_down else .key_up, .time = now, .code = @backingInt(key) }); + }, + .type => for (rest) |byte| try host.route(.{ .kind = .text, .time = now, .value = byte }), + else => return error.NotInput, + } +} + +fn step(host: *Host, arena: std.mem.Allocator, verb: Verb, rest: []const u8, words: *std.mem.TokenIterator(u8, .any), now: *u64) !void { + switch (verb) { + .click, .move, .down, .up, .wheel, .@"wheel-x", .cancel, .key, .hold, .release, .type => try input(host, verb, words, now.*), + .console => { + // A failing console line fails the script, like a failed expect. + host.runLine(rest, now.*) catch |err| { + std.debug.print(" console {s}: {t}\n", .{ rest, err }); + return err; + }; + if (std.mem.startsWith(u8, rest, "get ")) return; + }, + .print => { + const path = words.next() orelse return error.ExpectedField; + var buf: [4096]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); fields.formatPath(host.state.layout, host.live(), path, &w) catch |err| switch (err) { - error.UnknownField => w.writeAll("no such field") catch {}, + error.UnknownField => return error.UnknownField, error.WriteFailed => {}, }; - if (tolerance) |t| { - std.debug.print(" {s}: expected {s} ~{d}, found {s}\n", .{ path, want, t, w.buffered() }); - } else std.debug.print(" {s}: expected {s}, found {s}\n", .{ path, want, w.buffered() }); - return error.ExpectationFailed; - } - return; - } else if (eq(u8, command, "expect-snapshot")) { - const index = std.fmt.parseInt(usize, rest, 10) catch return error.InvalidSlot; - if (!host.timeline.bank.hasSnapshot(index)) return error.EmptySnapshot; - if (!same(host, index)) return error.ExpectationFailed; - return; - } else if (eq(u8, command, "expect-log") or eq(u8, command, "expect-no-log")) { - var found = false; - for (&host.console.lines) |*l| { - if (std.mem.indexOf(u8, l.bytes[0..l.len], rest) != null) found = true; - } - if (found != eq(u8, command, "expect-log")) { - std.debug.print(" console log:\n", .{}); - for (&host.console.lines) |*l| std.debug.print(" {s}\n", .{l.bytes[0..l.len]}); - return error.ExpectationFailed; - } - return; - } else if (eq(u8, command, "expect-same-screenshot") or eq(u8, command, "expect-different-screenshot")) { - const a = words.next() orelse return error.ExpectedFile; - const b = words.next() orelse return error.ExpectedFile; - const want_same = eq(u8, command, "expect-same-screenshot"); - const max: u8 = if (!want_same) 0 else if (words.next()) |m| std.fmt.parseInt(u8, m, 10) catch return error.InvalidValue else 0; - var rect: ?[4]usize = null; - if (words.next()) |x| { - var r: [4]usize = undefined; - r[0] = std.fmt.parseInt(usize, x, 10) catch return error.InvalidRect; - for (r[1..]) |*v| v.* = std.fmt.parseInt(usize, words.next() orelse return error.InvalidRect, 10) catch return error.InvalidRect; - rect = r; - } - const diff = try comparePng(arena, a, b, max, rect); - if ((diff.count == 0) != want_same) { - if (want_same) { - std.debug.print(" {s} vs {s}: {d} pixels differ by more than {d}, first at {d},{d}\n", .{ a, b, diff.count, max, diff.first[0], diff.first[1] }); - } else std.debug.print(" {s} and {s} are the same\n", .{ a, b }); + std.debug.print("{s} = {s}\n", .{ path, w.buffered() }); + }, + .frames => { + const count = try std.fmt.parseInt(usize, rest, 10); + for (0..count) |_| try advance(host, now); + }, + .expect, .await => { + const path = words.next() orelse return error.ExpectedField; + const want, const tolerance = try expected(std.mem.trim(u8, words.rest(), " \t")); + // Looked up again after each frame: a reload may move the field. + _ = host.state.layout.find(path) orelse return error.UnknownField; + // `await` plays frames until the field holds the value, for up to a + // minute: for waits whose length is the sketch's business. + if (verb == .await) { + var waited: usize = 0; + while (!holds(host, path, want, tolerance) and waited < await_limit) : (waited += 1) try advance(host, now); + } + if (!holds(host, path, want, tolerance)) { + var buf: [128]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + fields.formatPath(host.state.layout, host.live(), path, &w) catch |err| switch (err) { + error.UnknownField => w.writeAll("no such field") catch {}, + error.WriteFailed => {}, + }; + if (tolerance) |t| { + std.debug.print(" {s}: expected {s} ~{d}, found {s}\n", .{ path, want, t, w.buffered() }); + } else std.debug.print(" {s}: expected {s}, found {s}\n", .{ path, want, w.buffered() }); + return error.ExpectationFailed; + } + }, + .@"expect-snapshot" => { + const saved = try Console.markState(host, arena, rest); + if (!same(host, saved.layout, saved.bytes, rest)) return error.ExpectationFailed; + }, + .@"expect-key" => { + const why = std.meta.stringToEnum(Sessions.Why, words.next() orelse "") orelse return error.UnknownWhy; + const path = words.next() orelse return error.ExpectedField; + const want = std.mem.trim(u8, words.rest(), " \t"); + const s = &host.sessions; + try s.commit(.none); + var k = s.keys; + while (k > 0) { + k -= 1; + const key = try s.load(s.session, k); + defer key.free(host.gpa); + if (key.why != why) continue; + const leaf = (try memory.layoutOf(arena, key.layout)).find(path) orelse return error.UnknownField; + if (fields.matches(leaf, key.state, want)) return; + var buf: [128]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + fields.format(leaf, key.state, &w) catch {}; + std.debug.print(" {s} keyframe {d}: {s} expected {s}, found {s}\n", .{ @tagName(why), k, path, want, w.buffered() }); + return error.ExpectationFailed; + } + std.debug.print(" no {s} keyframe in this session\n", .{@tagName(why)}); return error.ExpectationFailed; - } - return; - } else if (eq(u8, command, "expect-pixel")) { - const file = words.next() orelse return error.ExpectedFile; - var n: [7]u8 = .{ 0, 0, 0, 0, 0, 0, 0 }; - var x: usize = 0; - var y: usize = 0; - for (0..7) |i| { - const word = words.next() orelse if (i == 6) break else return error.ExpectedPixel; - if (i < 2) { - (if (i == 0) &x else &y).* = std.fmt.parseInt(usize, word, 10) catch return error.ExpectedPixel; - } else n[i - 2] = std.fmt.parseInt(u8, word, 0) catch return error.ExpectedPixel; - } - const tol = n[4]; - const surface = try loadPng(arena, file); - defer c.SDL_DestroySurface(surface); - if (x >= surface.*.w or y >= surface.*.h) return error.OutsideScreenshot; - const p = (@as([*]const u8, @ptrCast(surface.*.pixels.?)) + y * @as(usize, @intCast(surface.*.pitch)) + x * 4)[0..4]; - for (p, n[0..4]) |got, want| if (@max(got, want) - @min(got, want) > tol) { - std.debug.print(" {s} at {d},{d}: expected {d} {d} {d} {d}, found {d} {d} {d} {d}\n", .{ file, x, y, n[0], n[1], n[2], n[3], p[0], p[1], p[2], p[3] }); - return error.ExpectationFailed; - }; - return; - } else if (eq(u8, command, "expect-audio")) { - const key = try std.fmt.parseInt(u32, rest, 10); - if (host.input.stream(key).pushed == 0) return error.ExpectationFailed; - return; - } else if (eq(u8, command, "screenshot")) { - if (std.fs.path.dirname(rest)) |dir| try std.Io.Dir.cwd().createDirPath(host.io, dir); - host.screenshot = try arena.dupeSentinel(u8, rest, 0); - } else if (eq(u8, command, "load")) { - try host.load(rest); - } else if (eq(u8, command, "reload")) { - try host.reload(); - } else if (eq(u8, command, "await-reload")) { - const seconds = try std.fmt.parseInt(u64, rest, 10); - const start = host.reloads; - const deadline = std.Io.Timestamp.now(host.io, .awake).nanoseconds + @as(i96, seconds) * std.time.ns_per_s; - while (host.reloads == start) { - if (std.Io.Timestamp.now(host.io, .awake).nanoseconds > deadline) return error.NoReload; - try advance(host, now); - try std.Io.sleep(host.io, .fromMilliseconds(10), .awake); - } - return; - } else if (eq(u8, command, "quit")) { - host.quit = true; - return; - } else return error.UnknownScriptCommand; - try advance(host, now); + }, + .@"expect-log", .@"expect-no-log" => { + var found = false; + for (&host.console.lines) |*l| { + if (std.mem.indexOf(u8, l.bytes[0..l.len], rest) != null) found = true; + } + if (found != (verb == .@"expect-log")) { + std.debug.print(" console log:\n", .{}); + for (&host.console.lines) |*l| std.debug.print(" {s}\n", .{l.bytes[0..l.len]}); + return error.ExpectationFailed; + } + }, + .@"expect-same-screenshot", .@"expect-different-screenshot" => { + const a = words.next() orelse return error.ExpectedFile; + const b = words.next() orelse return error.ExpectedFile; + const want_same = verb == .@"expect-same-screenshot"; + const max: u8 = if (!want_same) 0 else if (words.next()) |m| std.fmt.parseInt(u8, m, 10) catch return error.InvalidValue else 0; + var rect: ?[4]usize = null; + if (words.next()) |x| { + var r: [4]usize = undefined; + r[0] = std.fmt.parseInt(usize, x, 10) catch return error.InvalidRect; + for (r[1..]) |*v| v.* = std.fmt.parseInt(usize, words.next() orelse return error.InvalidRect, 10) catch return error.InvalidRect; + rect = r; + } + const diff = try comparePng(arena, a, b, max, rect); + if ((diff.count == 0) != want_same) { + if (want_same) { + std.debug.print(" {s} vs {s}: {d} pixels differ by more than {d}, first at {d},{d}\n", .{ a, b, diff.count, max, diff.first[0], diff.first[1] }); + } else std.debug.print(" {s} and {s} are the same\n", .{ a, b }); + return error.ExpectationFailed; + } + }, + .@"expect-pixel" => { + const file = words.next() orelse return error.ExpectedFile; + var n: [7]u8 = .{ 0, 0, 0, 0, 0, 0, 0 }; + var x: usize = 0; + var y: usize = 0; + for (0..7) |i| { + const word = words.next() orelse if (i == 6) break else return error.ExpectedPixel; + if (i < 2) { + (if (i == 0) &x else &y).* = std.fmt.parseInt(usize, word, 10) catch return error.ExpectedPixel; + } else n[i - 2] = std.fmt.parseInt(u8, word, 0) catch return error.ExpectedPixel; + } + const tol = n[4]; + const surface = try loadPng(arena, file); + defer c.SDL_DestroySurface(surface); + if (x >= surface.*.w or y >= surface.*.h) return error.OutsideScreenshot; + const p = (@as([*]const u8, @ptrCast(surface.*.pixels.?)) + y * @as(usize, @intCast(surface.*.pitch)) + x * 4)[0..4]; + for (p, n[0..4]) |got, want| if (@max(got, want) - @min(got, want) > tol) { + std.debug.print(" {s} at {d},{d}: expected {d} {d} {d} {d}, found {d} {d} {d} {d}\n", .{ file, x, y, n[0], n[1], n[2], n[3], p[0], p[1], p[2], p[3] }); + return error.ExpectationFailed; + }; + }, + .@"expect-audio" => { + const key = try std.fmt.parseInt(u32, rest, 10); + if (host.input.stream(key).pushed == 0 and !host.audio.sounded(key)) return error.ExpectationFailed; + }, + .@"expect-no-audio" => { + if (host.audio.sounded(try std.fmt.parseInt(u32, rest, 10))) return error.ExpectationFailed; + }, + .screenshot => { + if (std.fs.path.dirname(rest)) |dir| try std.Io.Dir.cwd().createDirPath(host.io, dir); + host.screenshot = try arena.dupeSentinel(u8, rest, 0); + }, + .load => { + try host.load(rest); + }, + .reload => { + try host.reload(); + }, + .@"await-reload" => { + const seconds = try std.fmt.parseInt(u64, rest, 10); + const start = host.reloads; + const deadline = std.Io.Timestamp.now(host.io, .awake).nanoseconds + @as(i96, seconds) * std.time.ns_per_s; + while (host.reloads == start) { + if (std.Io.Timestamp.now(host.io, .awake).nanoseconds > deadline) return error.NoReload; + try advance(host, now); + try std.Io.sleep(host.io, .fromMilliseconds(10), .awake); + } + }, + .kill => { + // A crash, for tests of what survives one: SIGKILL, no cleanup. + _ = std.os.linux.kill(std.os.linux.getpid(), .KILL); + }, + .quit => { + host.quit = true; + }, + } + if (verbs.get(verb).frame) try advance(host, now); } /// The modifiers `hold` has down, for a pointer event's `flags`. @@ -258,15 +310,14 @@ fn holds(host: *Host, path: []const u8, want: []const u8, tolerance: ?f64) bool return @abs(value - target) <= t; } -/// Live state against snapshot `index`, leaf by leaf; prints the first few -/// differences. -fn same(host: *Host, index: usize) bool { +/// Live state against mark `name`'s (`saved`, taken in layout `from`), leaf +/// by leaf over the leaves migration kept; prints the first few differences. +fn same(host: *Host, from: memory.Layout, saved: []const u8, name: []const u8) bool { const layout = host.state.layout; const live = host.live(); - const saved = host.timeline.bank.slot(index); var count: usize = 0; for (layout.fields) |leaf| { - if (leaf.whole()) continue; + if (leaf.whole() or (from.hash != layout.hash and !memory.keeps(from, leaf))) continue; var it = leaf.elements(); while (it.next()) |offset| { if (std.mem.eql(u8, live[offset..][0..leaf.size], saved[offset..][0..leaf.size])) continue; @@ -277,7 +328,7 @@ fn same(host: *Host, index: usize) bool { leaf.name(offset, &w) catch {}; w.writeAll(": live ") catch {}; fields.format(leaf.at(offset), live, &w) catch {}; - w.print(", snapshot {d} ", .{index}) catch {}; + w.print(", snapshot {s} ", .{name}) catch {}; fields.format(leaf.at(offset), saved, &w) catch {}; std.debug.print(" {s}\n", .{w.buffered()}); } diff --git a/src/host/state_files.zig b/src/host/state_files.zig new file mode 100644 index 0000000..ed796c9 --- /dev/null +++ b/src/host/state_files.zig @@ -0,0 +1,303 @@ +//! The State as files: a directory per struct and per array, a file per +//! value, `state/tracker/songs/3/bpm`. An array of scalars (a vector's +//! lanes, `talk.text`) is one file, its values blank-separated; an array +//! of arrays is a directory of such rows, so a file is always one value or +//! one row, the run of values one `set` names. Everything here reads a +//! `(Layout, bytes)` alone: the running host's, the save's newest State, +//! or a sketch's defaults. +//! +//! A node names a leaf of the layout (its first under a directory), how +//! many names deep it is, and the offset of the element it stands for: +//! the indices on its way, every later one zero. Nodes have bit 62 set; +//! bit 63 is the sketch's (control.zig). +const std = @import("std"); +const memory = @import("memory.zig"); +const fields = @import("fields.zig"); +const Layout = memory.Layout; +const Leaf = Layout.Leaf; + +pub const Node = packed struct(u64) { + offset: u40 = 0, + depth: u6 = 0, + leaf: u16 = 0, + state: u1 = 1, + sketch: u1 = 0, +}; + +/// `state/` itself. +pub const root: Node = .{}; + +/// The names of a leaf's pattern: a field's name, or `[]` for an index. +const Pieces = struct { + rest: []const u8, + + fn next(p: *Pieces) ?[]const u8 { + if (p.rest.len > 0 and p.rest[0] == '.') p.rest = p.rest[1..]; + if (p.rest.len == 0) return null; + const end = if (std.mem.startsWith(u8, p.rest, "[]")) 2 else std.mem.indexOfAny(u8, p.rest, ".[") orelse p.rest.len; + defer p.rest = p.rest[end..]; + return p.rest[0..end]; + } +}; + +/// How deep a leaf's file is: its names, an innermost index not counted +/// (a row of scalars is one file). +fn fileDepth(leaf: Leaf) usize { + var p: Pieces = .{ .rest = leaf.path }; + var n: usize = 0; + while (p.next()) |_| n += 1; + return if (std.mem.endsWith(u8, leaf.path, "[]")) n - 1 else n; +} + +/// Where `leaf` is under `dir`: its offset at the directory's indices (the +/// rest zero), and how many of its dimensions they used; null when it is +/// not under it. +fn under(layout: Layout, dir: Node, leaf: Leaf) ?struct { offset: usize, dim: usize } { + if (leaf.kind == .array or fileDepth(leaf) < dir.depth) return null; + if (dir.depth == 0) return .{ .offset = leaf.offset, .dim = 0 }; + const own = layout.fields[dir.leaf]; + var a: Pieces = .{ .rest = own.path }; + var b: Pieces = .{ .rest = leaf.path }; + var rest: usize = @intCast(dir.offset -| own.offset); + var dim: usize = 0; + var offset: usize = leaf.offset; + for (0..dir.depth) |_| { + const x = a.next() orelse return null; + if (!std.mem.eql(u8, x, b.next() orelse return null)) return null; + if (x[0] != '[') continue; + const index = rest / own.dims[dim].stride; + rest %= own.dims[dim].stride; + if (index >= leaf.dims[dim].count) return null; + offset += index * leaf.dims[dim].stride; + dim += 1; + } + return .{ .offset = offset, .dim = dim }; +} + +/// The name a leaf has `depth` names down. +fn pieceAt(leaf: Leaf, depth: usize) []const u8 { + var p: Pieces = .{ .rest = leaf.path }; + for (0..depth) |_| _ = p.next(); + return p.next().?; +} + +/// Whether `node` still names something in `layout` (a reload may have +/// changed it under an open fid). +pub fn valid(layout: Layout, node: Node) bool { + if (node.depth == 0) return true; + if (node.leaf >= layout.fields.len) return false; + const leaf = layout.fields[node.leaf]; + return leaf.kind != .array and node.depth <= fileDepth(leaf) and node.offset >= leaf.offset and node.offset < layout.size; +} + +pub fn isDir(layout: Layout, node: Node) bool { + return node.depth == 0 or node.depth < fileDepth(layout.fields[node.leaf]); +} + +/// The child of directory `dir` called `child`. +pub fn lookup(layout: Layout, dir: Node, child: []const u8) ?Node { + for (layout.fields, 0..) |leaf, j| { + const at = under(layout, dir, leaf) orelse continue; + if (fileDepth(leaf) == dir.depth) continue; + const piece = pieceAt(leaf, dir.depth); + var offset = at.offset; + if (piece[0] == '[') { + if (child.len == 0 or !std.ascii.isDigit(child[0])) return null; + const index = std.fmt.parseInt(u32, child, 10) catch return null; + if (index >= leaf.dims[at.dim].count) return null; + offset += index * leaf.dims[at.dim].stride; + } else if (!std.mem.eql(u8, piece, child)) continue; + return .{ .leaf = @intCast(j), .depth = dir.depth + 1, .offset = @intCast(offset) }; + } + return null; +} + +/// The entries of directory `dir` from the `from`-th, as cloud9's readdir +/// records (`node:u64le dir:u8 len:u8 name`), as many as `out` holds: the +/// bytes written. +pub fn readdir(layout: Layout, dir: Node, from: u64, out: []u8) usize { + var used: usize = 0; + var index: u64 = 0; + var last: []const u8 = ""; + for (layout.fields, 0..) |leaf, j| { + const at = under(layout, dir, leaf) orelse continue; + if (fileDepth(leaf) == dir.depth) continue; + const piece = pieceAt(leaf, dir.depth); + if (std.mem.eql(u8, piece, last)) continue; + last = piece; + const is_dir = fileDepth(leaf) > dir.depth + 1; + const count = if (piece[0] == '[') leaf.dims[at.dim].count else 1; + for (0..count) |i| { + defer index += 1; + if (index < from) continue; + var buf: [16]u8 = undefined; + const text = if (piece[0] == '[') std.fmt.bufPrint(&buf, "{d}", .{i}) catch unreachable else piece; + if (used + 10 + text.len > out.len) return used; + const offset = at.offset + if (piece[0] == '[') i * leaf.dims[at.dim].stride else 0; + const node: Node = .{ .leaf = @intCast(j), .depth = dir.depth + 1, .offset = @intCast(offset) }; + std.mem.writeInt(u64, out[used..][0..8], @bitCast(node), .little); + out[used + 8] = @intFromBool(is_dir); + out[used + 9] = @intCast(text.len); + @memcpy(out[used + 10 ..][0..text.len], text); + used += 10 + text.len; + } + } + return used; +} + +/// The row of scalars at a file node: its first element and its length +/// and stride; null for a file of one value. +fn rowOf(layout: Layout, node: Node) ?struct { first: Leaf, count: usize, stride: usize } { + const leaf = layout.fields[node.leaf]; + if (!std.mem.endsWith(u8, leaf.path, "[]") or node.depth != fileDepth(leaf)) return null; + const d = leaf.dims[leaf.dims.len - 1]; + return .{ .first = leaf.at(node.offset), .count = d.count, .stride = d.stride }; +} + +/// A file's value, as `get` shows one value, a row's blank-separated, +/// and a newline. +pub fn read(layout: Layout, bytes: []const u8, node: Node, w: *std.Io.Writer) std.Io.Writer.Error!void { + if (rowOf(layout, node)) |row| { + for (0..row.count) |i| { + if (i > 0) try w.writeByte(' '); + try fields.format(row.first.at(row.first.offset + i * row.stride), bytes, w); + } + } else try fields.format(layout.fields[node.leaf].at(node.offset), bytes, w); + try w.writeByte('\n'); +} + +/// The path `get` and `set` take for a node: `tracker.songs[3].bpm`, and +/// for a row the array's (`talk.text`). +pub fn path(layout: Layout, node: Node, w: *std.Io.Writer) std.Io.Writer.Error!void { + const leaf = layout.fields[node.leaf]; + var p: Pieces = .{ .rest = leaf.path }; + var rest: usize = @intCast(node.offset - leaf.offset); + var dim: usize = 0; + for (0..node.depth) |k| { + const piece = p.next().?; + if (piece[0] == '[') { + try w.print("[{d}]", .{rest / leaf.dims[dim].stride}); + rest %= leaf.dims[dim].stride; + dim += 1; + } else try w.print("{s}{s}", .{ if (k == 0) "" else ".", piece }); + } +} + +/// Whether `set` takes the file: numbers, bools and enums. +pub fn writable(layout: Layout, node: Node) bool { + return switch (layout.fields[node.leaf].kind) { + .int, .uint, .float, .bool, .@"enum" => true, + else => false, + }; +} + +/// A README line for every file of the layout: its path, `<n>` for an +/// index, and what it holds. +pub fn readme(layout: Layout, w: *std.Io.Writer) std.Io.Writer.Error!void { + for (layout.fields) |leaf| { + if (leaf.kind == .array) continue; + var line: [256]u8 = undefined; + var lw: std.Io.Writer = .fixed(&line); + var p: Pieces = .{ .rest = leaf.path }; + const depth = fileDepth(leaf); + lw.writeAll("state") catch {}; + for (0..depth) |_| { + const piece = p.next().?; + lw.print("/{s}", .{if (piece[0] == '[') "<n>" else piece}) catch {}; + } + const row = std.mem.endsWith(u8, leaf.path, "[]"); + try w.print("{s}", .{lw.buffered()}); + try w.splatByteAll(' ', @max(1, 41 -| lw.buffered().len)); + if (row) try w.print("{d} ", .{leaf.dims[leaf.dims.len - 1].count}); + switch (leaf.kind) { + .int, .uint, .float => try w.print("{s}{d}", .{ switch (leaf.kind) { + .int => "i", + .uint => "u", + else => "f", + }, leaf.size * 8 }), + .bool => try w.writeAll("bool"), + .@"enum" => { + var tags = std.mem.tokenizeScalar(u8, leaf.tags, ','); + var first = true; + while (tags.next()) |pair| : (first = false) try w.print("{s}.{s}", .{ if (first) "" else " ", pair[0 .. std.mem.indexOfScalar(u8, pair, '=') orelse pair.len] }); + }, + else => try w.print("{d} bytes, read-only", .{leaf.size}), + } + if (row) try w.writeAll(", blank-separated"); + try w.writeByte('\n'); + } +} + +const testing = std.testing; + +fn walk(layout: Layout, to: []const u8) ?Node { + var node = root; + var names = std.mem.tokenizeScalar(u8, to, '/'); + while (names.next()) |n| node = lookup(layout, node, n) orelse return null; + return node; +} + +/// The names in a directory, a blank after each, a slash after a directory's. +fn ls(layout: Layout, dir: Node, buf: []u8) []const u8 { + var records: [4096]u8 = undefined; + const bytes = records[0..readdir(layout, dir, 0, &records)]; + var w: std.Io.Writer = .fixed(buf); + var i: usize = 0; + while (i < bytes.len) : (i += 10 + bytes[i + 9]) { + const node: Node = @bitCast(std.mem.readInt(u64, bytes[i..][0..8], .little)); + // Each entry is what a lookup of its name answers. + const text = bytes[i + 10 ..][0..bytes[i + 9]]; + std.debug.assert(lookup(layout, dir, text).? == node); + w.print("{s}{s} ", .{ text, if (bytes[i + 8] != 0) "/" else "" }) catch {}; + } + return w.buffered(); +} + +test "the State as files: a directory per struct and array, a file per value or row" { + const S = struct { + scene: enum(u8) { room, street } = .street, + talk: struct { text: [4]u8 = .{ 104, 105, 0, 0 }, len: u8 = 2 } = .{}, + songs: [2]struct { bpm: u16 = 120, patterns: [2][3]struct { pitch: u8 = 0, velocity: u8 = 0 } = @splat(@splat(.{})) } = @splat(.{}), + grid: [2][3]i16 = @splat(@splat(0)), + pos: @Vector(2, f32) = .{ 250, 3 }, + }; + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + const layout = try Layout.copy(arena.allocator(), @import("abi").layout.of(S, .state)); + var s: S = .{}; + s.songs[1].patterns[1][2].pitch = 64; + s.grid[1] = .{ 1, -2, 3 }; + const bytes = std.mem.asBytes(&s); + var buf: [256]u8 = undefined; + try testing.expectEqualStrings("scene talk/ songs/ grid/ pos ", ls(layout, root, &buf)); + try testing.expectEqualStrings("text len ", ls(layout, walk(layout, "talk").?, &buf)); + try testing.expectEqualStrings("0/ 1/ ", ls(layout, walk(layout, "songs").?, &buf)); + try testing.expectEqualStrings("bpm patterns/ ", ls(layout, walk(layout, "songs/1").?, &buf)); + try testing.expectEqualStrings("0/ 1/ 2/ ", ls(layout, walk(layout, "songs/1/patterns/1").?, &buf)); + try testing.expectEqualStrings("0 1 ", ls(layout, walk(layout, "grid").?, &buf)); + const cases = [_][3][]const u8{ + .{ "scene", "scene", ".street\n" }, + .{ "talk/text", "talk.text", "104 105 0 0\n" }, + .{ "songs/1/bpm", "songs[1].bpm", "120\n" }, + .{ "songs/1/patterns/1/2/pitch", "songs[1].patterns[1][2].pitch", "64\n" }, + .{ "grid/1", "grid[1]", "1 -2 3\n" }, + .{ "pos", "pos", "250 3\n" }, + }; + for (cases) |case| { + const node = walk(layout, case[0]).?; + try testing.expect(!isDir(layout, node) and valid(layout, node) and writable(layout, node)); + var w: std.Io.Writer = .fixed(&buf); + try path(layout, node, &w); + try testing.expectEqualStrings(case[1], w.buffered()); + w = .fixed(&buf); + try read(layout, bytes, node, &w); + try testing.expectEqualStrings(case[2], w.buffered()); + } + for ([_][]const u8{ "nope", "songs/2", "songs/x", "songs/01x", "grid/1/0", "scene/x", "talk/text/0" }) |bad| try testing.expect(walk(layout, bad) == null); + var out: std.Io.Writer.Allocating = .init(testing.allocator); + defer out.deinit(); + try readme(layout, &out.writer); + try testing.expect(std.mem.indexOf(u8, out.written(), "state/scene .room .street\n") != null); + try testing.expect(std.mem.indexOf(u8, out.written(), "state/songs/<n>/patterns/<n>/<n>/pitch u8\n") != null); + try testing.expect(std.mem.indexOf(u8, out.written(), "state/grid/<n> 3 i16, blank-separated\n") != null); +} diff --git a/src/host/timeline.zig b/src/host/timeline.zig index b52c74d..e755433 100644 --- a/src/host/timeline.zig +++ b/src/host/timeline.zig @@ -1,47 +1,18 @@ -//! Snapshots, input recordings and replay: generic over state bytes and -//! `abi.Event`s, so any sketch gets time travel for free. +//! Clips and replay: generic over state bytes and `abi.Event`s, so any +//! sketch gets time travel for free. //! //! Playback is host state, not sketch state: wall clocks, modes and cursors //! must not contaminate byte comparisons between two runs of a sketch. //! -//! Recordings are frames: each frame's events, then its `tick`. Playback, -//! seek and step only ever stop between frames, and `frames` cuts a run of -//! events into them, so `update` sees exactly the frames it saw live, one -//! call each. +//! A clip is whole frames of a session (Sessions.zig) and the keyframe they +//! start from: each frame's events, then its `tick`. Playback, seek and step +//! only ever stop between frames, and `frames` cuts a run of events into +//! them, so `update` sees exactly the frames it saw live, one call each, +//! at the times it saw. const std = @import("std"); -const posix = std.posix; const abi = @import("abi"); const memory = @import("memory.zig"); - -pub const recording_len = 4 * 1024 * 1024; -pub const recording_count = 16; -pub const recordings_len = recording_len * recording_count; -const recording_magic = 0x52454305; -pub const capacity = (recording_len - 32) / @sizeOf(abi.Event); - -pub const Recording = extern struct { - duration: u64, - count: u32, - snapshot: u32, - magic: u32, - /// The build that recorded it (`build`, two halves), 0 when unknown. - build_low: u32, - build_high: u32, - reserved: u32, - events: [capacity]abi.Event, - slack: [recording_len - 32 - capacity * @sizeOf(abi.Event)]u8, - - pub fn slice(r: *const Recording) []const abi.Event { - return r.events[0..r.count]; - } - pub fn build(r: *const Recording) u64 { - return @as(u64, r.build_high) << 32 | r.build_low; - } - /// Events up to the end of the last whole frame. - pub fn whole(r: *const Recording) usize { - return frameStart(r.slice(), r.count); - } -}; +const Sessions = @import("Sessions.zig"); /// The largest frame boundary at or before `index`: 0, or just after a tick. pub fn frameStart(events: []const abi.Event, index: usize) usize { @@ -72,119 +43,92 @@ pub const Frames = struct { } }; -comptime { - std.debug.assert(@sizeOf(Recording) == recording_len); -} - -/// Snapshot slots of a state file, and the recordings that start from them. -pub const Bank = struct { - state: *memory.StateFile, - inputs: []align(memory.page) u8, - - pub fn slot(self: Bank, index: usize) []u8 { - return self.state.slot(index); - } - pub fn recording(self: Bank, index: usize) *Recording { - std.debug.assert(index < recording_count); - return @ptrCast(@alignCast(self.inputs[index * recording_len ..].ptr)); - } - pub fn hasSnapshot(self: Bank, index: usize) bool { - return index > 0 and index < memory.slot_count and self.state.used(index); - } - pub fn save(self: Bank, index: usize) void { - std.debug.assert(index > 0 and index < memory.slot_count); - for (0..recording_count) |i| { - const r = self.recording(i); - if (r.snapshot == index) r.magic = 0; - } - @memcpy(self.slot(index), self.slot(0)); - self.state.markUsed(index, true); - } - pub fn restore(self: Bank, index: usize) !void { - if (!self.hasSnapshot(index)) return error.EmptySnapshot; - @memcpy(self.slot(0), self.slot(index)); - } - pub fn get(self: Bank, index: usize) !*Recording { - const r = self.recording(index); - if (r.magic != recording_magic or r.count > capacity or !self.hasSnapshot(r.snapshot)) return error.EmptyRecording; - return r; - } - /// Leaf by leaf (`memory.compare`): padding never differs. - pub fn compare(self: Bank, a: usize, b: usize) memory.Diff { - return memory.compare(self.state.layout, self.slot(a), self.slot(b)); - } -}; - pub const Timeline = struct { - bank: Bank, + gpa: std.mem.Allocator, + /// Live State. + state: *memory.State, + /// The running sketch's: a restore starts from its defaults. + defaults: *const fn (abi.Memory, [*]u8) callconv(.c) void, mode: abi.Mode = .live, - selected: usize = 0, + /// The clip loaded: its start keyframe and its frames, `gpa`'s. + key: ?Sessions.Loaded = null, + events: std.ArrayList(abi.Event) = .empty, + /// The clip's first tick: positions count from it. + base: u64 = 0, cursor: usize = 0, position: u64 = 0, clock: u64 = 0, - /// Set whenever live state is restored from a snapshot, for the host + /// Set whenever live state is restored from a keyframe, for the host /// to reset the input state that went with the old bytes. restored: bool = false, + /// Frames fed since the keyframe was restored. + fed: u64 = 0, + /// A past session played (`play session`), not a clip: its index, and + /// its keyframes after the one played from, checked against the replay + /// as their frames are reached (Host.resync). + session: ?u64 = null, + checks: std.ArrayList(Check) = .empty, + next_check: usize = 0, - /// Restores a snapshot into live state. - pub fn restore(self: *Timeline, index: usize) !void { - try self.bank.restore(index); + pub const Check = struct { + frame: u64, + key: u64, + /// Taken of what `update` made (periodic, a mark, before a reload, + /// at exit): a replay must match it. Other keyframes follow a jump + /// the log does not hold, and are restored without a word. + observed: bool, + }; + + pub fn deinit(self: *Timeline) void { + if (self.key) |k| k.free(self.gpa); + self.key = null; + self.events.deinit(self.gpa); + self.checks.deinit(self.gpa); + } + + /// Puts a keyframe, in whatever layout it was taken, into live state. + pub fn restore(self: *Timeline, key: Sessions.Loaded) !void { + var arena: std.heap.ArenaAllocator = .init(self.gpa); + defer arena.deinit(); + _ = try memory.restore(arena.allocator(), key.layout, key.state, self.state.layout, self.state.live(), self.defaults); self.restored = true; + self.fed = 0; + self.next_check = 0; + } + + /// Makes a clip, its start keyframe and its frames, the one played; both + /// become the timeline's. + pub fn load(self: *Timeline, key: Sessions.Loaded, events: std.ArrayList(abi.Event)) void { + self.deinit(); + self.key = key; + self.events = events; + self.session = null; + self.checks = .empty; + var it = frames(events.items); + const first = it.next(); + self.base = if (first) |f| f[f.len - 1].time else 0; + } + + fn at(self: *const Timeline, i: usize) u64 { + return self.events.items[i].time -| self.base; + } + + /// The last whole frame's tick, from the first. + fn duration(self: *const Timeline) u64 { + const end = frameStart(self.events.items, self.events.items.len); + return if (end == 0) 0 else self.at(end - 1); } - /// `build` identifies the code recording (0: unknown); `play` warns - /// when it differs. - pub fn startRecording(self: *Timeline, index: usize, snapshot: usize, now: u64, build: u64) !void { - // An unused snapshot captures the current state; an existing one is - // restored, so several recordings can branch from exactly those bytes. - if (!self.bank.hasSnapshot(snapshot)) self.bank.save(snapshot); - try self.restore(snapshot); - const r = self.bank.recording(index); - @memset(std.mem.asBytes(r)[0..32], 0); - r.magic = recording_magic; - r.snapshot = @intCast(snapshot); - r.build_low = @truncate(build); - r.build_high = @truncate(build >> 32); - self.selected = index; + pub fn startRecording(self: *Timeline) void { self.cursor = 0; self.position = 0; - self.clock = now; self.mode = .recording; } - /// Records one frame (its events, then its tick) and rewrites their - /// times as recorded, so live `update` sees exactly what a replay will. - /// A frame that does not fit ends the recording before it. - pub fn capture(self: *Timeline, frame: []abi.Event) !void { - if (self.mode != .recording) return; - const r = self.bank.recording(self.selected); - if (frame.len > capacity - r.count) { - self.mode = .live; - return error.RecordingFull; - } - for (frame) |*e| { - // Queued events can predate the start command. Keep insertion - // order and nondecreasing times, including several events at the - // same timestamp. - e.time = @max(e.time -| self.clock, r.duration); - r.events[r.count] = e.*; - r.count += 1; - r.duration = e.time; - } - self.position = r.duration; - self.cursor = r.count; - } - pub fn stop(self: *Timeline, now: u64) void { - if (self.mode == .recording) { - const r = self.bank.recording(self.selected); - r.duration = @max(r.duration, now -| self.clock); - self.position = r.duration; - } + pub fn stop(self: *Timeline) void { self.mode = .live; } - pub fn play(self: *Timeline, index: usize, now: u64) !void { - const r = try self.bank.get(index); - try self.restore(r.snapshot); - self.selected = index; + pub fn play(self: *Timeline, now: u64) !void { + try self.restore(self.key orelse return error.EmptyRecording); self.cursor = 0; self.position = 0; self.clock = now; @@ -203,35 +147,33 @@ pub const Timeline = struct { /// due). Feed them to the same `update` that live input goes through. pub fn tick(self: *Timeline, now: u64) []const abi.Event { if (self.mode != .playing) return &.{}; - const r = self.bank.recording(self.selected); - self.position = @min(r.duration, self.position +| (now -| self.clock)); + const end = self.duration(); + self.position = @min(end, self.position +| (now -| self.clock)); self.clock = now; const start = self.cursor; var i = self.cursor; - while (i < r.count and r.events[i].time <= self.position) : (i += 1) { - if (r.events[i].kind == .tick) self.cursor = i + 1; + while (i < self.events.items.len and self.at(i) <= self.position) : (i += 1) { + if (self.events.items[i].kind == .tick) self.cursor = i + 1; } - if (self.position == r.duration) self.mode = .paused; - return r.events[start..self.cursor]; + if (self.position == end) self.mode = .paused; + return self.events.items[start..self.cursor]; } - /// Restores the snapshot and returns the frames that make up the first - /// `count` events (rounded down to a whole frame) to replay, so seeking - /// backwards works too. + /// Restores the start keyframe and returns the frames that make up the + /// first `count` events (rounded down to a whole frame) to replay, so + /// seeking backwards works too. pub fn seekCount(self: *Timeline, count: usize) ![]const abi.Event { - const r = try self.bank.get(self.selected); - try self.restore(r.snapshot); - self.cursor = frameStart(r.slice(), count); - self.position = if (self.cursor == 0) 0 else r.events[self.cursor - 1].time; + try self.restore(self.key orelse return error.EmptyRecording); + self.cursor = frameStart(self.events.items, count); + self.position = if (self.cursor == 0) 0 else self.at(self.cursor - 1); self.mode = .paused; - return r.events[0..self.cursor]; + return self.events.items[0..self.cursor]; } - /// To the last frame whose tick is at or before `time`. + /// To the last frame whose tick is at or before `time` into the clip. pub fn seekTime(self: *Timeline, time: u64) ![]const abi.Event { - const r = try self.bank.get(self.selected); - const position = @min(time, r.duration); + const position = @min(time, self.duration()); var count: usize = 0; - for (r.slice(), 0..) |e, i| { - if (e.time > position) break; + for (self.events.items, 0..) |e, i| { + if (self.at(i) > position) break; if (e.kind == .tick) count = i + 1; } const events = try self.seekCount(count); @@ -240,13 +182,12 @@ pub const Timeline = struct { } /// Moves by `steps` frames, forwards or back. pub fn step(self: *Timeline, steps: i64) ![]const abi.Event { - const r = try self.bank.get(self.selected); - const events = r.slice(); + const events = self.events.items; var cursor = frameStart(events, self.cursor); var remaining = @abs(steps); + const end = frameStart(events, events.len); while (remaining > 0) : (remaining -= 1) { if (steps > 0) { - const end = r.whole(); if (cursor == end) break; cursor += 1; while (cursor < end and events[cursor - 1].kind != .tick) cursor += 1; @@ -259,62 +200,42 @@ pub const Timeline = struct { } }; -/// Maps the recordings file next to a state file, creating it when missing. -pub fn mapRecordings(path: []const u8) ![]align(memory.page) u8 { - const fd = try posix.openat(posix.AT.FDCWD, path, .{ .ACCMODE = .RDWR, .CREAT = true }, 0o600); - defer _ = posix.system.close(fd); - if (try memory.fileSize(fd) != recordings_len) switch (posix.errno(posix.system.ftruncate(fd, recordings_len))) { - .SUCCESS => {}, - else => |err| return posix.unexpectedErrno(err), +test "frames are whole: input waits for its tick, in playback, seek and step" { + const gpa = std.testing.allocator; + // Live State: 8 bytes, no fields. + const D = struct { + fn f(_: abi.Memory, _: [*]u8) callconv(.c) void {} }; - return memory.mapFile(fd, recordings_len, .{ .READ = true, .WRITE = true }); -} - -test "frames are whole: input waits for its tick, live and in playback" { - var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); - defer arena.deinit(); - const a = arena.allocator(); - // A bank on plain memory: one slot of 8 bytes, snapshot 1 used. - var file: memory.StateFile = undefined; - file.map = try a.alignedAlloc(u8, .fromByteUnits(memory.page), memory.header_len + memory.slot_count * memory.page); - @memset(file.map, 0); - file.header().* = .{ .size = 8, .alignment = 1, .hash = 1, .stride = memory.page, .used = 0b11, .field_count = 0, .strings_len = 0 }; - file.layout = .{}; - const inputs = try a.alignedAlloc(u8, .fromByteUnits(memory.page), recording_len); - @memset(inputs, 0); - var t: Timeline = .{ .bank = .{ .state = &file, .inputs = inputs } }; - // Frame k: a move at 10k ms, its tick at 10k + 5 ms; then a move with - // no tick (a frame cut off). - try t.startRecording(0, 1, 1000, 7); - try std.testing.expect(t.restored); + var state: memory.State = .init(gpa); + defer state.deinit(gpa); + _ = try state.adopt(gpa, .{ .size = 8, .alignment = 1, .hash = 1, .fields = &.{} }, D.f); + var t: Timeline = .{ .gpa = gpa, .state = &state, .defaults = D.f }; + defer t.deinit(); + // Frame k: a move at 10k ms, its tick 5 ms later; then a move with no + // tick (a frame cut off). + var events: std.ArrayList(abi.Event) = .empty; for (0..4) |k| { - var frame = [_]abi.Event{ - .{ .kind = .mouse_move, .time = 1000 + k * 10_000_000, .x = @floatFromInt(k) }, - abi.Event.tick(1000 + k * 10_000_000 + 5_000_000, 16_666_667), - }; - try t.capture(&frame); - // Live update sees the recorded times. - try std.testing.expectEqual(@as(u64, k * 10_000_000 + 5_000_000), frame[1].time); - try std.testing.expectEqual(abi.Event.tick(0, 16_666_667).tickDt(), frame[1].tickDt()); + try events.append(gpa, .{ .kind = .mouse_move, .time = 1000 + k * 10_000_000, .x = @floatFromInt(k) }); + try events.append(gpa, abi.Event.tick(1000 + k * 10_000_000 + 5_000_000, 16_666_667)); } - const r = t.bank.recording(0); - r.events[r.count] = .{ .kind = .mouse_move, .time = 40_000_000 }; - r.count += 1; - t.stop(1000 + 41_000_000); - try std.testing.expectEqual(@as(u64, 7), r.build()); + try events.append(gpa, .{ .kind = .mouse_move, .time = 40_000_000 }); + const key: Sessions.Loaded = .{ .frame = 0, .batch = 0, .why = .mark, .time = 0, .stretch = 0, .build = 7, .state = try gpa.dupe(u8, &@as([8]u8, @splat(0))), .line = try gpa.dupe(u8, ""), .source = try gpa.dupe(u8, ""), .layout = try gpa.dupe(u8, state.header) }; + t.load(key, events); - try t.play(0, 0); + try t.play(0); + try std.testing.expect(t.restored); var delivered: usize = 0; // Every moment between 0 and the end, 1 ms apart. var now: u64 = 0; while (t.mode == .playing) : (now += 1_000_000) { - const events = t.tick(now); - if (events.len == 0) continue; - try std.testing.expectEqual(abi.Event.Kind.tick, events[events.len - 1].kind); - var it = frames(events); + const due = t.tick(now); + if (due.len == 0) continue; + try std.testing.expectEqual(abi.Event.Kind.tick, due[due.len - 1].kind); + var it = frames(due); while (it.next()) |frame| { try std.testing.expectEqual(@as(usize, 2), frame.len); - try std.testing.expectEqual(abi.Event.tick(0, 16_666_667).tickDt(), frame[1].tickDt()); + // Fed at the times it was recorded at. + try std.testing.expectEqual(1000 + delivered * 10_000_000 + 5_000_000, frame[1].time); delivered += 1; } } @@ -322,13 +243,13 @@ test "frames are whole: input waits for its tick, live and in playback" { try std.testing.expectEqual(@as(usize, 8), t.cursor); // A seek between a frame's input and its tick stops before the frame. - try std.testing.expectEqual(@as(usize, 4), (try t.seekTime(22_000_000)).len); - try std.testing.expectEqual(@as(usize, 8), (try t.seekCount(r.count)).len); + try std.testing.expectEqual(@as(usize, 6), (try t.seekTime(27_000_000)).len); + try std.testing.expectEqual(@as(usize, 8), (try t.seekCount(t.events.items.len)).len); try std.testing.expectEqual(@as(usize, 6), (try t.step(-1)).len); try std.testing.expectEqual(@as(usize, 8), (try t.step(5)).len); try std.testing.expectEqual(@as(usize, 2), (try t.step(-3)).len); // The cut-off frame is never fed. - var it = frames(r.slice()); + var it = frames(t.events.items); var n: usize = 0; while (it.next()) |_| n += 1; try std.testing.expectEqual(@as(usize, 4), n); diff --git a/src/layout.zig b/src/layout.zig index 3fb381b..c585d71 100644 --- a/src/layout.zig +++ b/src/layout.zig @@ -13,23 +13,28 @@ //! against a leaf's pattern at lookup time. //! //! What each kind of sketch memory may hold: -//! - State is saved to disk and snapshotted: no pointers, and no host -//! handles (images, sounds, buffers), which only mean something in the -//! process that made them. +//! - State is saved, the one thing a sketch keeps, in keyframes of its +//! save: no pointers, and no host handles (images, sounds, buffers), +//! which only mean something in the process that made them; at most +//! `max_state` bytes. //! - Session lives in this process: anything, as long as pointers go into //! memory the host owns (its heaps, mapped files), never into the sketch //! library, which a reload unmaps. -//! - Store is a file mapped at the same address in every run: pointers into -//! the store itself, but no host handles. const std = @import("std"); const abi = @import("abi.zig"); +/// The most a State may be, in bytes: half of the 64 MiB a save holds, so +/// history has room (Sessions.max_save). +pub const max_state = 32 << 20; + pub fn of(comptime T: type, comptime memory: abi.Memory) abi.Layout { return comptime blk: { @setEvalBranchQuota(1_000_000); switch (memory) { - .state => check(T, "State", @typeName(T), false), - .store => check(T, "Store", @typeName(T), true), + .state => { + check(T, @typeName(T)); + if (@sizeOf(T) > max_state) @compileError(std.fmt.comptimePrint("State is {d} bytes, and may be {d} MiB, half of a save, so history has room: lower a capacity (an array, an sk.List), or keep what need not be saved in Session.", .{ @sizeOf(T), max_state >> 20 })); + }, .session => {}, } const Leaves = struct { @@ -101,7 +106,7 @@ fn leaf(comptime T: type, comptime path: []const u8, comptime offset: usize, com }; const stored = dims[0..dims.len].*; return .{ - .path = std.fmt.comptimePrint("{s}", .{path}), + .path = (path ++ "\x00")[0..path.len :0], .offset = offset, .size = @sizeOf(T), .kind = kind, @@ -155,17 +160,16 @@ pub fn resolve(fields: []const abi.Field, path: []const u8) ?Resolved { return null; } -fn check(comptime T: type, comptime memory: []const u8, comptime path: []const u8, comptime pointers: bool) void { +fn check(comptime T: type, comptime path: []const u8) void { comptime { - if (T == abi.Image or T == abi.Audio or T == abi.Buffer) @compileError(memory ++ " cannot hold host handles (" ++ path ++ "): they mean nothing to the next process. Keep them in Session."); + if (T == abi.Image or T == abi.Audio or T == abi.Buffer) @compileError("State cannot hold host handles (" ++ path ++ "): they mean nothing to the next process. Keep them in Session."); switch (@typeInfo(T)) { - // Not followed: types can point to themselves. - .pointer => if (!pointers) @compileError(memory ++ " cannot hold pointers (" ++ path ++ "): it is saved to disk and outlives every address. Keep indices or offsets, or put it in Store or Session."), - .array => |a| check(a.child, memory, path ++ "[]", pointers), - .vector => |v| check(v.child, memory, path ++ "[]", pointers), - .optional => |o| check(o.child, memory, path, pointers), - .@"struct" => |s| for (s.field_names, s.field_types) |name, F| check(F, memory, path ++ "." ++ name, pointers), - .@"union" => |u| for (u.field_names, u.field_types) |name, F| check(F, memory, path ++ "." ++ name, pointers), + .pointer => @compileError("State cannot hold pointers (" ++ path ++ "): it is saved to disk and outlives every address. Keep indices or offsets, or put it in Session."), + .array => |a| check(a.child, path ++ "[]"), + .vector => |v| check(v.child, path ++ "[]"), + .optional => |o| check(o.child, path), + .@"struct" => |s| for (s.field_names, s.field_types) |name, F| check(F, path ++ "." ++ name), + .@"union" => |u| for (u.field_names, u.field_types) |name, F| check(F, path ++ "." ++ name), else => {}, } } @@ -176,9 +180,9 @@ fn tags(comptime E: type) [:0]const u8 { var text: []const u8 = ""; const e = @typeInfo(E).@"enum"; for (e.field_names, e.field_values, 0..) |name, value, i| { - text = text ++ (if (i == 0) "" else ",") ++ std.fmt.comptimePrint("{s}={d}", .{ name, value }); + text = text ++ (if (i == 0) "" else ",") ++ name ++ "=" ++ decimal(value); } - return std.fmt.comptimePrint("{s}", .{text}); + return (text ++ "\x00")[0..text.len :0]; } } @@ -191,32 +195,40 @@ pub fn hash(comptime T: type) u64 { }; } +/// `n` in decimal, as `{d}` prints it: `std.fmt.comptimePrint` costs about a +/// millisecond of comptime a call, and a signature makes hundreds. +fn decimal(comptime n: comptime_int) []const u8 { + if (n < 0) return "-" ++ decimal(-n); + if (n < 10) return &[_]u8{'0' + n}; + return decimal(n / 10) ++ &[_]u8{'0' + n % 10}; +} + pub fn signature(comptime T: type) []const u8 { comptime { return switch (@typeInfo(T)) { - .int => |i| std.fmt.comptimePrint("{c}{d}", .{ if (i.signedness == .signed) 'i' else 'u', i.bits }), - .float => |f| std.fmt.comptimePrint("f{d}", .{f.bits}), + .int => |i| (if (i.signedness == .signed) "i" else "u") ++ decimal(i.bits), + .float => |f| "f" ++ decimal(f.bits), .bool => "b", .void => "v", .@"enum" => |e| "e(" ++ signature(e.tag_type) ++ ":" ++ tags(T) ++ ")", - .array => |a| std.fmt.comptimePrint("[{d}]", .{a.len}) ++ signature(a.child), - .vector => |v| std.fmt.comptimePrint("@{d}", .{v.len}) ++ signature(v.child), + .array => |a| "[" ++ decimal(a.len) ++ "]" ++ signature(a.child), + .vector => |v| "@" ++ decimal(v.len) ++ signature(v.child), .optional => |o| "?" ++ signature(o.child), .@"struct" => |s| blk: { - var text: []const u8 = std.fmt.comptimePrint("s{d}{{", .{@sizeOf(T)}); + var text: []const u8 = "s" ++ decimal(@sizeOf(T)) ++ "{"; for (s.field_names, s.field_types, s.field_attrs) |name, F, attrs| { if (attrs.@"comptime") continue; - text = text ++ std.fmt.comptimePrint("{s}@{d}:", .{ name, @offsetOf(T, name) }) ++ signature(F) ++ ";"; + text = text ++ name ++ "@" ++ decimal(@offsetOf(T, name)) ++ ":" ++ signature(F) ++ ";"; } break :blk text ++ "}"; }, .@"union" => |u| blk: { - var text: []const u8 = std.fmt.comptimePrint("u{d}{{", .{@sizeOf(T)}); + var text: []const u8 = "u" ++ decimal(@sizeOf(T)) ++ "{"; if (u.tag_type) |tag| text = text ++ signature(tag) ++ "|"; for (u.field_names, u.field_types) |name, F| text = text ++ name ++ ":" ++ signature(F) ++ ";"; break :blk text ++ "}"; }, - .pointer => |p| std.fmt.comptimePrint("*{s}:{s}", .{ @tagName(p.size), @typeName(p.child) }), + .pointer => |p| "*" ++ @tagName(p.size) ++ ":" ++ @typeName(p.child), .@"opaque" => "opaque", .@"fn" => @typeName(T), else => @compileError("unsupported type in sketch memory: " ++ @typeName(T)), diff --git a/src/scope/root.zig b/src/scope/root.zig index a71fa53..098e2d0 100644 --- a/src/scope/root.zig +++ b/src/scope/root.zig @@ -16,6 +16,10 @@ //! Columns of the scrolling views are analysed once, when everything their //! windows reach has arrived, into rings the views read from the oldest; so //! the spectrogram runs `reach` samples (about 130 ms) behind the newest. +//! +//! A sketch that analyses buffers of its own (a tape of takes, say) uses the +//! same shaders through `kernels` and `pipelines`, with the parameter and +//! view blocks in `layouts`; `midi`, `hz` and `note_names` name pitches. const std = @import("std"); const sk = @import("sketch"); const gpu = sk.abi.gpu; @@ -43,6 +47,10 @@ pub const Views = struct { oscilloscope: ?Oscilloscope = null, gain: f32 = 1, tint: Tint = .live, + /// When given, the rects are in its world: the views are made at their + /// size there and drawn at `camera.toScreen(rect)`, so moving or zooming + /// the camera recomputes nothing. + camera: ?sk.Camera = null, pub const Oscilloscope = struct { rect: sk.Rect, @@ -66,6 +74,8 @@ pub const Scope = struct { filled: u32 = 0, columns: u32 = 0, spp: u32 = 0, + /// `gpu.tape` holds `samples` on the GPU, as of the last `draw` (a + /// `history`-sample buffer, oldest first), for kernels of a sketch's own. gpu: Gpu = .{}, pub fn push(s: *Scope, heard: []const f32) void { @@ -91,7 +101,7 @@ pub const Scope = struct { defer s.fresh = false; if (v.wave orelse v.spectrogram) |r| s.scroll(f, v, r, rate); - if (v.spectrum) |r| s.spectrum(f, r, rate); + if (v.spectrum) |r| s.spectrum(f, v, r, rate); if (v.oscilloscope) |o| s.oscilloscope(f, v, o); } @@ -121,7 +131,7 @@ pub const Scope = struct { const slot: u32 = @intCast(s.next % columns); if (v.wave != null) f.compute(.{ .label = "scope waveform.comp", - .kernel = waveform_kernel, + .kernel = kernels.waveform, .readonly = &.{g.tape}, .readwrite = &.{g.wave.columns}, .uniforms = gpu.uniform(f.scratch, layouts.WaveParams{ .offset = 0, .first = first, .samples = history, .columns = count, .spp = @floatFromInt(spp), .slot = slot, .ring = columns }), @@ -129,7 +139,7 @@ pub const Scope = struct { }); if (v.spectrogram != null) f.compute(.{ .label = "scope spectrogram.comp", - .kernel = spectrogram_kernel, + .kernel = kernels.spectrogram, .readonly = &.{g.tape}, .readwrite = &.{g.levels}, .uniforms = gpu.uniform(f.scratch, layouts.SpectrogramParams{ @@ -163,7 +173,7 @@ pub const Scope = struct { .filled = s.filled, }; if (g.wave.redraw(std.hash.Wyhash.hash(0, std.mem.asBytes(&view)))) wavePass(f, &g.wave, size, view); - f.image(g.wave.image, wr, .{}); + f.image(g.wave.image, if (v.camera) |c| c.toScreen(wr) else wr, .{}); } if (v.spectrogram) |sr| { const size = target(f, &g.spectrogram, sr, rows); @@ -181,21 +191,21 @@ pub const Scope = struct { .width = size[0], .height = size[1], .clear = null, - .pipelines = &spectrogram_pipelines, + .pipelines = &pipelines.spectrogram, .draws = &.{.{ .pipeline = 0, .vertex_count = 3, .fragment_uniforms = gpu.uniform(f.scratch, view), .fragment_storage = &.{g.levels} }}, }); - f.image(g.spectrogram.image, sr, .{}); + f.image(g.spectrogram.image, if (v.camera) |c| c.toScreen(sr) else sr, .{}); } } /// The spectrum of the newest samples, smoothed frame to frame. - fn spectrum(s: *Scope, f: *sk.Frame, r: sk.Rect, rate: f64) void { + fn spectrum(s: *Scope, f: *sk.Frame, v: Views, r: sk.Rect, rate: f64) void { const g = &s.gpu; const size = target(f, &g.spectrum, r, layouts.max_rows); const dt: f64 = @min(@as(f64, @floatFromInt(f.in.dt)) / std.time.ns_per_s, 0.1); f.compute(.{ .label = "scope spectrum.comp", - .kernel = spectrum_kernel, + .kernel = kernels.spectrum, .readonly = &.{g.tape}, .readwrite = &.{ g.scratch, g.spectrum.columns }, .uniforms = gpu.uniform(f.scratch, layouts.SpectrumParams{ @@ -217,7 +227,7 @@ pub const Scope = struct { .width = size[0], .height = size[1], .clear = null, - .pipelines = &spectrum_pipelines, + .pipelines = &pipelines.spectrum, .draws = &.{.{ .pipeline = 0, .vertex_count = 3, @@ -231,7 +241,7 @@ pub const Scope = struct { .fragment_storage = &.{g.spectrum.columns}, }}, }); - f.image(g.spectrum.image, r, .{}); + f.image(g.spectrum.image, if (v.camera) |c| c.toScreen(r) else r, .{}); } /// The newest `samples` (less `end`), as a line. @@ -243,7 +253,7 @@ pub const Scope = struct { const first: u32 = history - n - end; f.compute(.{ .label = "scope oscilloscope", - .kernel = waveform_kernel, + .kernel = kernels.waveform, .readonly = &.{g.tape}, .readwrite = &.{g.oscilloscope.columns}, .uniforms = gpu.uniform(f.scratch, layouts.WaveParams{ @@ -265,7 +275,7 @@ pub const Scope = struct { .scroll = 0, .filled = size[0], }); - f.image(g.oscilloscope.image, o.rect, .{}); + f.image(g.oscilloscope.image, if (v.camera) |c| c.toScreen(o.rect) else o.rect, .{}); } }; @@ -274,12 +284,26 @@ pub fn maxFreq(rate: f64) f32 { return @floatCast(@min(20_000, rate / 2)); } -/// Where `hz` falls across a spectrum view (or up a spectrogram, from its +/// Where `freq` falls across a spectrum view (or up a spectrogram, from its /// bottom): 0 to 1, log frequency. -pub fn place(hz: f64, rate: f64) f32 { - return @floatCast(@log(hz / min_freq) / @log(maxFreq(rate) / min_freq)); +pub fn place(freq: f64, rate: f64) f32 { + return @floatCast(@log(freq / min_freq) / @log(maxFreq(rate) / min_freq)); +} + +/// The MIDI note number of `freq` Hz, fractional (69 is A4, at `a4` Hz: +/// 440 unless the sketch tunes otherwise). +pub fn midi(freq: f32, a4: f32) f32 { + return 69 + 12 * std.math.log2(freq / a4); } +/// The frequency of MIDI note `note`, fractional, in Hz. +pub fn hz(note: f32, a4: f32) f32 { + return a4 * std.math.pow(f32, 2, (note - 69) / 12); +} + +/// Pitch classes by `@mod(note, 12)`, C first. +pub const note_names = [12][]const u8{ "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" }; + // --------------------------------------------------------------------------- // GPU objects. @@ -358,7 +382,7 @@ fn wavePass(f: *sk.Frame, v: *View, size: [2]u32, view: layouts.WaveView) void { .width = size[0], .height = size[1], .clear = null, - .pipelines = &wave_pipelines, + .pipelines = &pipelines.wave, .draws = &.{.{ .pipeline = 0, .vertex_count = 3, .fragment_uniforms = gpu.uniform(f.scratch, view), .fragment_storage = &.{v.columns} }}, }); } @@ -372,13 +396,26 @@ fn viewPipeline(fragment: []const u8) gpu.Pipeline { .blend = .none, }; } -const wave_pipelines = [_]gpu.Pipeline{viewPipeline(shaders.waveform_frag)}; -const spectrum_pipelines = [_]gpu.Pipeline{viewPipeline(shaders.spectrum_frag)}; -const spectrogram_pipelines = [_]gpu.Pipeline{viewPipeline(shaders.spectrogram_frag)}; -const spectrum_kernel: gpu.Kernel = .{ .code = shaders.spectrum_comp, .readonly_buffers = 1, .readwrite_buffers = 2, .uniform_buffers = 1, .threads = .{ 256, 1, 1 } }; -const spectrogram_kernel: gpu.Kernel = .{ .code = shaders.spectrogram_comp, .readonly_buffers = 1, .readwrite_buffers = 1, .uniform_buffers = 1, .threads = .{ 256, 1, 1 } }; -const waveform_kernel: gpu.Kernel = .{ .code = shaders.waveform_comp, .readonly_buffers = 1, .readwrite_buffers = 1, .uniform_buffers = 1, .threads = .{ 64, 1, 1 } }; +/// The views' passes: one full-screen triangle each (`vertex_count = 3`), +/// its `layouts.*View` as fragment uniforms and its analysis as fragment +/// storage (the waveform's or spectrum's columns, the spectrogram's levels). +pub const pipelines = struct { + pub const wave = [_]gpu.Pipeline{viewPipeline(shaders.waveform_frag)}; + pub const spectrum = [_]gpu.Pipeline{viewPipeline(shaders.spectrum_frag)}; + pub const spectrogram = [_]gpu.Pipeline{viewPipeline(shaders.spectrogram_frag)}; +}; + +/// The analyses, over `samples` samples of a read-only buffer from `offset` +/// (see each `layouts.*Params`): waveform columns ([4]f32 each, a group per +/// column), the spectrogram's levels (`rows` per column, a group per +/// column) and the spectrum's columns ([2]f32 each, one group, with an FFT +/// scratch buffer of `layouts.fft_size * 2` [2]f32 before them). +pub const kernels = struct { + pub const waveform: gpu.Kernel = .{ .code = shaders.waveform_comp, .readonly_buffers = 1, .readwrite_buffers = 1, .uniform_buffers = 1, .threads = .{ 64, 1, 1 } }; + pub const spectrogram: gpu.Kernel = .{ .code = shaders.spectrogram_comp, .readonly_buffers = 1, .readwrite_buffers = 1, .uniform_buffers = 1, .threads = .{ 256, 1, 1 } }; + pub const spectrum: gpu.Kernel = .{ .code = shaders.spectrum_comp, .readonly_buffers = 1, .readwrite_buffers = 2, .uniform_buffers = 1, .threads = .{ 256, 1, 1 } }; +}; test "the history keeps the newest samples in order" { var s: Scope = .{}; @@ -392,3 +429,13 @@ test "frequencies place on a log axis" { try std.testing.expectEqual(@as(f32, 0), place(min_freq, 48_000)); try std.testing.expectApproxEqAbs(@as(f32, 1), place(20_000, 48_000), 1e-6); } + +test "notes and frequencies convert both ways" { + try std.testing.expectApproxEqAbs(@as(f32, 69), midi(440, 440), 1e-4); + try std.testing.expectApproxEqAbs(@as(f32, 40), midi(82.4069, 440), 1e-3); + try std.testing.expectApproxEqAbs(@as(f32, 261.626), hz(60, 440), 1e-2); + try std.testing.expectApproxEqAbs(@as(f32, 69), midi(442, 442), 1e-4); + try std.testing.expectApproxEqAbs(@as(f32, 61.5), midi(hz(61.5, 432), 432), 1e-4); + try std.testing.expectEqualStrings("A", note_names[@mod(69, 12)]); + try std.testing.expectEqualStrings("C", note_names[@mod(60, 12)]); +} diff --git a/src/sketch/request.zig b/src/sketch/request.zig index 0b8b400..4a8e414 100644 --- a/src/sketch/request.zig +++ b/src/sketch/request.zig @@ -1,5 +1,5 @@ //! Requests from `update` that `draw` carries out once. `update` sees only -//! State and input, so when a key should do something to Session or Store +//! State and input, so when a key should do something to Session //! (start the microphone, open a dialog, seek a stream), State holds the //! request and Session remembers which ones it has handled: //! diff --git a/src/sketch/root.zig b/src/sketch/root.zig index cb20ab9..755e446 100644 --- a/src/sketch/root.zig +++ b/src/sketch/root.zig @@ -7,19 +7,18 @@ //! pub const height = 600; //! pub const State = struct { ... }; // saved, snapshotted, replayed: no pointers //! pub const Session = struct { ... }; // this process: survives reloads -//! pub const Store = struct { ... }; // on disk: survives restarts too //! pub const commands = .{"hello"}; // console completions //! pub fn init(state: *State, host: sk.Host) void //! pub fn setup(session: *Session, init: *sk.Init) !void //! pub fn update(state: *State, in: *const sk.Input) void -//! pub fn draw(state: *const State, session: *Session, store: *Store, f: *sk.Frame) void -//! pub fn command(state: *State, store: *Store, c: *sk.Console, line: []const u8) !bool +//! pub fn draw(state: *const State, session: *Session, f: *sk.Frame) void +//! pub fn command(state: *State, session: *Session, c: *sk.Console, line: []const u8) !bool //! //! Functions take the parameters they name, by type, in any order: `draw` -//! may ask for `*Session`, `*Store`, both or neither. `update` must be +//! may ask for `*Session` or not. `update` must be //! deterministic, so it gets `State` and `Input` only: the host replays //! recorded input through it. `draw` presents state as pictures and sound, -//! and changes only Session and Store. Geometry and colors are duck-typed: +//! and changes only Session. Geometry and colors are duck-typed: //! see `shape`. const std = @import("std"); pub const abi = @import("abi"); @@ -41,6 +40,8 @@ pub const List = @import("list.zig").List; /// Data computed in draw from a few State fields, kept in Session and rebuilt when they change (or after a reload). pub const Derived = @import("derived.zig").Derived; pub const web = @import("web.zig"); +/// sfxr's sound effects, rendered to samples for `host.newSound`. +pub const sfxr = @import("sfxr.zig"); const request = @import("request.zig"); pub const Request = request.Request; pub const Handled = request.Handled; @@ -65,7 +66,6 @@ pub const Face = abi.Face; pub const Init = struct { host: Host, session: std.mem.Allocator, - store: std.mem.Allocator, }; /// What `draw` receives: input, host services, memory by lifetime and the @@ -80,14 +80,12 @@ pub const Frame = struct { scratch: std.mem.Allocator, /// For Session: this process. session: std.mem.Allocator, - /// For Store: on disk, across restarts. - store: std.mem.Allocator, /// A library's own state for this frame (canim's table of places), in /// `scratch`: null at each frame's start. user: ?*anyopaque = null, pub fn init(ctx: *const abi.Context) Frame { - return .{ .ctx = ctx, .in = ctx.input, .host = ctx.host, .scratch = ctx.scratch, .session = ctx.session, .store = ctx.store }; + return .{ .ctx = ctx, .in = ctx.input, .host = ctx.host, .scratch = ctx.scratch, .session = ctx.session }; } pub fn emit(f: *Frame, command: abi.Command) void { @@ -210,9 +208,20 @@ pub const Frame = struct { pub fn voice(f: *Frame, v: Voice) void { f.emit(.{ .voice = v }); } + /// Scales every voice of `group` this frame (1 when not declared). + pub fn gain(f: *Frame, group: u3, value: f32) void { + f.emit(.{ .gain = .{ .group = group, .gain = value } }); + } pub fn audio(f: *Frame, key: u32, samples: []const f32, options: struct { clear: bool = false }) void { f.emit(.{ .audio = .{ .key = key, .samples = samples, .clear = options.clear } }); } + /// Streams `count` samples a compute shader wrote to `buffer` (f32 from + /// `offset`) on stream `key`, as `audio` streams samples: a GPU synth's + /// output, heard without a readback of the sketch's own. Make + /// `in.lead -| in.stream(key).queued` of them a frame. + pub fn audioBuffer(f: *Frame, key: u32, buffer: abi.Buffer, options: struct { offset: u32 = 0, count: u32 }) void { + f.emit(.{ .audio_buffer = .{ .key = key, .buffer = buffer, .offset = options.offset, .count = options.count } }); + } pub fn pixels(f: *Frame, img: Image, w: u32, h: u32, rgba: []const u8, options: struct { premultiplied: bool = false }) void { f.emit(.{ .pixels = .{ .image = img, .w = w, .h = h, .rgba = rgba, .premultiplied = options.premultiplied } }); } @@ -285,12 +294,11 @@ fn paint(value: anytype) Color { } /// What `command` receives: somewhere to answer, the current input, and the -/// allocators for Session and Store. +/// allocator for Session. pub const Console = struct { host: Host, in: *const Input, session: std.mem.Allocator, - store: std.mem.Allocator, pub fn log(c: *Console, message: []const u8) void { c.host.log(message); @@ -300,15 +308,24 @@ pub const Console = struct { } }; +/// What the build knows of a sketch and passes to `sketch` and +/// `exportSketch` (build.zig's generated roots fill it in). +pub const Build = struct { + /// The repository revision the sketch was built from, "" when unknown. + source: []const u8 = "", + /// Keep history in the save (`abi.Info.record`). + record: bool = false, +}; + /// The entry points of `App`, for a host that links it statically. -pub fn sketch(comptime App: type) abi.Sketch { - const G = Glue(App); +pub fn sketch(comptime App: type, comptime made: Build) abi.Sketch { + const G = Glue(App, made); return .{ .info = G.info, .defaults = G.defaults, .init = G.init, .setup = G.setup, .update = G.update, .draw = G.draw, .command = G.command }; } /// Exports `App` under `abi.Sketch.symbols`, for a hot-reloaded library. -pub fn exportSketch(comptime App: type) void { - const G = Glue(App); +pub fn exportSketch(comptime App: type, comptime made: Build) void { + const G = Glue(App, made); const names = abi.Sketch.symbols; @export(&G.info, .{ .name = names.info }); @export(&G.defaults, .{ .name = names.defaults }); @@ -317,13 +334,15 @@ pub fn exportSketch(comptime App: type) void { @export(&G.update, .{ .name = names.update }); @export(&G.draw, .{ .name = names.draw }); @export(&G.command, .{ .name = names.command }); + @export(&G.build, .{ .name = "sketch_build" }); } -pub fn Glue(comptime App: type) type { +pub fn Glue(comptime App: type, comptime made: Build) type { return struct { pub const State = if (@hasDecl(App, "State")) App.State else struct {}; pub const Session = if (@hasDecl(App, "Session")) App.Session else struct {}; - pub const Store = if (@hasDecl(App, "Store")) App.Store else struct {}; + + const build: [abi.build.len:0]u8 = abi.build.*; pub const description: abi.Info = .{ .abi = abi.hash, @@ -332,8 +351,10 @@ pub fn Glue(comptime App: type) type { .height = if (@hasDecl(App, "height")) App.height else 600, .state = abi.layout.of(State, .state), .session = abi.layout.of(Session, .session), - .store = abi.layout.of(Store, .store), .commands = if (@hasDecl(App, "commands")) &App.commands else &.{}, + .source = made.source ++ " " ++ abi.build, + .record = made.record, + .audio_pull = if (@hasDecl(App, "audio_pull")) App.audio_pull else 0, }; /// What a call can offer, by type. @@ -357,10 +378,10 @@ pub fn Glue(comptime App: type) type { return std.mem.eql(u8, name, n); } }; - if (comptime is.named("update") and (T == *Session or T == *Store)) + if (comptime is.named("update") and T == *Session) @compileError("update must be deterministic: it gets State and Input only, so a replay reproduces it"); if (comptime is.named("setup") and (T == *State or T == *const State or T == *const Input)) - @compileError("setup initializes resources: it gets Session, Store, Init and Host only"); + @compileError("setup initializes resources: it gets Session, Init and Host only"); if (comptime (T == *Init or T == *const Init) and !is.named("setup")) @compileError(name ++ " gets no Init: only setup does"); if (comptime is.named("draw") and T == *State) @compileError("draw only reads State: take *const State"); if (comptime T == *Frame and !is.named("draw")) @compileError(name ++ " gets no Frame: only draw does"); @@ -369,8 +390,6 @@ pub fn Glue(comptime App: type) type { @ptrCast(@alignCast(offer.state)) else if (T == *Session or T == *const Session) @ptrCast(@alignCast(offer.ctx.session_root)) - else if (T == *Store or T == *const Store) - @ptrCast(@alignCast(offer.ctx.store_root)) else if (T == *const Input) offer.ctx.input else if (T == Host) @@ -396,7 +415,6 @@ pub fn Glue(comptime App: type) type { switch (which) { .state => @as(*State, @ptrCast(@alignCast(ptr))).* = .{}, .session => @as(*Session, @ptrCast(@alignCast(ptr))).* = .{}, - .store => @as(*Store, @ptrCast(@alignCast(ptr))).* = .{}, } } pub fn init(ctx: *const abi.Context, s: [*]u8) callconv(.c) void { @@ -404,7 +422,7 @@ pub fn Glue(comptime App: type) type { } pub fn setup(ctx: *const abi.Context) callconv(.c) bool { if (!@hasDecl(App, "setup")) return true; - var resource_init: Init = .{ .host = ctx.host, .session = ctx.session, .store = ctx.store }; + var resource_init: Init = .{ .host = ctx.host, .session = ctx.session }; const result = call(App.setup, "setup", .{ .ctx = ctx, .state = undefined, .resource_init = &resource_init }); if (@typeInfo(@TypeOf(result)) == .error_union) result catch |err| { ctx.host.print("session setup failed: {t}", .{err}); @@ -422,7 +440,7 @@ pub fn Glue(comptime App: type) type { } pub fn command(ctx: *const abi.Context, s: [*]u8, line: *const []const u8) callconv(.c) abi.Outcome { if (!@hasDecl(App, "command")) return .unknown; - var c: Console = .{ .host = ctx.host, .in = ctx.input, .session = ctx.session, .store = ctx.store }; + var c: Console = .{ .host = ctx.host, .in = ctx.input, .session = ctx.session }; const taken = call(App.command, "command", .{ .ctx = ctx, .state = s, .console = &c, .line = line.* }) catch |err| { c.print("{t}. Type help for usage.", .{err}); return .failed; @@ -442,6 +460,7 @@ test { _ = @import("clock.zig"); _ = @import("list.zig"); _ = @import("derived.zig"); + _ = sfxr; } test "setup receives session resources without a Frame and reports errors" { @@ -467,8 +486,7 @@ test "setup receives session resources without a Frame and reports errors" { ctx.host = .{ .ctx = &seen, .vtable = &vtable }; ctx.session_root = std.mem.asBytes(&session); ctx.session = std.testing.allocator; - ctx.store = std.testing.allocator; - const app = sketch(App); + const app = sketch(App, .{}); try std.testing.expect(!app.setup(&ctx)); defer std.testing.allocator.free(session.bytes); try std.testing.expectEqualStrings("ready", session.bytes); diff --git a/src/sketch/sfxr.zig b/src/sketch/sfxr.zig new file mode 100644 index 0000000..01657b5 --- /dev/null +++ b/src/sketch/sfxr.zig @@ -0,0 +1,267 @@ +//! sfxr, DrPetter's sound-effect generator (blips, coins, lasers, +//! explosions): one waveform through an envelope, pitch slides, vibrato, +//! arpeggio, duty sweep, a phaser and two filters, 8× oversampled. Pure and +//! deterministic: the same `Params` and rate give the same samples, so a +//! sketch renders its sounds whenever it likes and plays them as voices: +//! +//! const n = sk.sfxr.render(.{ .freq = 0.5, .decay = 0.2 }, f.in.sample_rate, &buf); +//! ss.blip = f.host.newSound(buf[0..n]); +//! +//! Ported from 02-dont-rat-me-out's synth.zig. sfxr's knobs count in +//! samples at 44.1 kHz; at another rate every length, step and filter +//! coefficient is scaled to keep the same durations, pitches and cutoffs +//! (to first order for the slides and filters), and at 44.1 kHz the +//! samples are the original's to the bit. +const std = @import("std"); + +/// The rate sfxr's knobs were tuned at. +pub const reference_rate = 44_100; + +pub const Wave = enum(u8) { square, sawtooth, sine, noise }; + +/// All sfxr knobs. Most are 0..1, a few -1..1. +pub const Params = struct { + wave: Wave = .square, + // envelope + attack: f32 = 0.0, + sustain: f32 = 0.3, + punch: f32 = 0.0, + decay: f32 = 0.4, + // frequency + freq: f32 = 0.3, + freq_limit: f32 = 0.0, + freq_ramp: f32 = 0.0, + freq_dramp: f32 = 0.0, + // vibrato + vibrato_depth: f32 = 0.0, + vibrato_speed: f32 = 0.0, + // arpeggio + arp_mod: f32 = 0.0, + arp_speed: f32 = 0.0, + // square duty + duty: f32 = 0.0, + duty_ramp: f32 = 0.0, + // phaser + phaser_offset: f32 = 0.0, + phaser_ramp: f32 = 0.0, + // filters + lpf_freq: f32 = 1.0, + lpf_ramp: f32 = 0.0, + lpf_resonance: f32 = 0.0, + hpf_freq: f32 = 0.0, + hpf_ramp: f32 = 0.0, + // repeat + repeat_speed: f32 = 0.0, + // output + volume: f32 = 0.5, +}; + +inline fn sq(x: f32) f32 { + return x * x; +} +inline fn cube(x: f32) f32 { + return x * x * x; +} +inline fn xs(s: *u32) u32 { + s.* ^= s.* << 13; + s.* ^= s.* >> 17; + s.* ^= s.* << 5; + return s.*; +} +fn frnd(s: *u32, range: f32) f32 { + return @as(f32, @floatFromInt(xs(s))) / 4294967295.0 * range; +} + +/// Synthesizes `p` at `rate` samples a second into `out` (mono, -1..1). +/// Returns the number of samples written: the envelope's length, or less +/// when `out` is shorter or the pitch falls to `freq_limit`. +pub fn render(p: Params, rate: u32, out: []f32) usize { + // Samples at `rate` per sample at 44.1 kHz: lengths grow by it, steps + // per sample shrink by it. + const k: f64 = @as(f64, @floatFromInt(rate)) / reference_rate; + const kf: f32 = @floatCast(k); + var rng: u32 = 0x52ad4326; + + var fperiod: f64 = 100.0 / (@as(f64, p.freq) * p.freq + 0.001) * k; + var period: i32 = @intFromFloat(fperiod); + const fmaxperiod: f64 = 100.0 / (@as(f64, p.freq_limit) * p.freq_limit + 0.001) * k; + var fslide: f64 = 1.0 - @as(f64, cube(p.freq_ramp)) * 0.01 / k; + const fdslide: f64 = -@as(f64, cube(p.freq_dramp)) * 0.000001 / (k * k); + + var square_duty: f32 = 0.5 - p.duty * 0.5; + const square_slide: f32 = -p.duty_ramp * 0.00005 / kf; + + const arp_mod: f64 = if (p.arp_mod >= 0) 1.0 - @as(f64, sq(p.arp_mod)) * 0.9 else 1.0 + @as(f64, sq(p.arp_mod)) * 10.0; + var arp_time: i32 = 0; + var arp_limit: i32 = @intFromFloat((sq(p.arp_speed) * 20000 + 32) * kf); + if (p.arp_speed == 1.0) arp_limit = 0; + + var env_vol: f32 = 0; + var env_stage: usize = 0; + var env_time: i32 = 0; + const env_length = [3]i32{ + @intFromFloat(p.attack * p.attack * 100000 * kf), + @intFromFloat(p.sustain * p.sustain * 100000 * kf), + @intFromFloat(p.decay * p.decay * 100000 * kf), + }; + + var fphase: f32 = sq(p.phaser_offset) * 1020 * kf; + if (p.phaser_offset < 0) fphase = -fphase; + var fdphase: f32 = sq(p.phaser_ramp) * 1.0; + if (p.phaser_ramp < 0) fdphase = -fdphase; + var iphase: i32 = @intFromFloat(@min(@abs(fphase), 1023)); + var ipp: i32 = 0; + var phaser_buffer: [1024]f32 = @splat(0); + + var noise_buffer: [32]f32 = undefined; + for (&noise_buffer) |*nb| nb.* = frnd(&rng, 2) - 1; + + var fltp: f32 = 0; + var fltdp: f32 = 0; + var fltw: f32 = cube(p.lpf_freq) * 0.1 / kf; + const fltw_d: f32 = 1.0 + p.lpf_ramp * 0.0001 / kf; + var fltdmp: f32 = 5.0 / (1.0 + sq(p.lpf_resonance) * 20) * (0.01 + fltw); + if (fltdmp > 0.8) fltdmp = 0.8; + var fltphp: f32 = 0; + var flthp: f32 = sq(p.hpf_freq) * 0.1 / kf; + const flthp_d: f32 = 1.0 + p.hpf_ramp * 0.0003 / kf; + + var vib_phase: f32 = 0; + const vib_speed: f32 = sq(p.vibrato_speed) * 0.01 / kf; + const vib_amp: f32 = p.vibrato_depth * 0.5; + + var rep_time: i32 = 0; + var rep_limit: i32 = @intFromFloat((sq(1 - p.repeat_speed) * 20000 + 32) * kf); + if (p.repeat_speed == 0) rep_limit = 0; + + var phase: i32 = 0; + var n: usize = 0; + var finished = false; + while (!finished and n < out.len) : (n += 1) { + rep_time += 1; + if (rep_limit != 0 and rep_time >= rep_limit) { + rep_time = 0; + fperiod = 100.0 / (@as(f64, p.freq) * p.freq + 0.001) * k; + period = @intFromFloat(fperiod); + fslide = 1.0 - @as(f64, cube(p.freq_ramp)) * 0.01 / k; + arp_time = 0; + arp_limit = @intFromFloat((sq(p.arp_speed) * 20000 + 32) * kf); + if (p.arp_speed == 1.0) arp_limit = 0; + } + + arp_time += 1; + if (arp_limit != 0 and arp_time >= arp_limit) { + arp_limit = 0; + fperiod *= arp_mod; + } + + fslide += fdslide; + fperiod *= fslide; + if (fperiod > fmaxperiod) { + fperiod = fmaxperiod; + if (p.freq_limit > 0) finished = true; + } + + var rfperiod: f32 = @floatCast(fperiod); + if (vib_amp > 0) { + vib_phase += vib_speed; + rfperiod = @floatCast(fperiod * (1.0 + @as(f64, @sin(vib_phase) * vib_amp))); + } + period = @intFromFloat(rfperiod); + if (period < 8) period = 8; + + square_duty += square_slide; + square_duty = std.math.clamp(square_duty, 0, 0.5); + + env_time += 1; + if (env_time > env_length[env_stage]) { + env_time = 0; + env_stage += 1; + if (env_stage == 3) finished = true; + } + env_vol = switch (env_stage) { + 0 => @as(f32, @floatFromInt(env_time)) / @as(f32, @floatFromInt(@max(1, env_length[0]))), + 1 => 1.0 + (1.0 - @as(f32, @floatFromInt(env_time)) / @as(f32, @floatFromInt(@max(1, env_length[1])))) * 2.0 * p.punch, + else => 1.0 - @as(f32, @floatFromInt(env_time)) / @as(f32, @floatFromInt(@max(1, env_length[2]))), + }; + + fphase += fdphase; + iphase = @intFromFloat(@min(@abs(fphase), 1023)); + + flthp *= flthp_d; + flthp = std.math.clamp(flthp, 0.00001, 0.1); + + var ssample: f32 = 0; + var oi: u32 = 0; + while (oi < 8) : (oi += 1) { + var sample: f32 = 0; + phase += 1; + if (phase >= period) { + phase = @mod(phase, period); + if (p.wave == .noise) for (&noise_buffer) |*nb| { + nb.* = frnd(&rng, 2) - 1; + }; + } + const fp: f32 = @as(f32, @floatFromInt(phase)) / @as(f32, @floatFromInt(period)); + sample = switch (p.wave) { + .square => if (fp < square_duty) 0.5 else -0.5, + .sawtooth => 1.0 - fp * 2, + .sine => @sin(fp * 2.0 * std.math.pi), + .noise => noise_buffer[@intCast(@as(i32, @intFromFloat(fp * 32)) & 31)], + }; + + const pp = fltp; + fltw *= fltw_d; + fltw = std.math.clamp(fltw, 0, 0.1); + if (p.lpf_freq != 1.0) { + fltdp += (sample - fltp) * fltw; + fltdp -= fltdp * fltdmp; + } else { + fltp = sample; + fltdp = 0; + } + fltp += fltdp; + fltphp += fltp - pp; + fltphp -= fltphp * flthp; + sample = fltphp; + phaser_buffer[@intCast(ipp & 1023)] = sample; + sample += phaser_buffer[@intCast((ipp - iphase + 1024) & 1023)]; + ipp = (ipp + 1) & 1023; + + ssample += sample * env_vol; + } + ssample = ssample / 8.0 * p.volume * 2.0; + out[n] = std.math.clamp(ssample, -1, 1); + } + return n; +} + +/// One parameter set per wave, between them every knob: a coin with punch, +/// arpeggio and a duty sweep; an explosion through both filters; a laser +/// with vibrato, phaser, repeat and a pitch limit; a rising sine. +const sets = [_]Params{ + .{ .wave = .square, .sustain = 0.1, .punch = 0.5, .decay = 0.3, .freq = 0.45, .freq_ramp = -0.2, .arp_mod = 0.4, .arp_speed = 0.6, .duty = 0.3, .duty_ramp = 0.2 }, + .{ .wave = .noise, .sustain = 0.2, .decay = 0.4, .freq = 0.2, .freq_ramp = -0.1, .lpf_freq = 0.6, .lpf_ramp = -0.1, .lpf_resonance = 0.4, .hpf_freq = 0.1, .hpf_ramp = 0.05 }, + .{ .wave = .sawtooth, .sustain = 0.25, .decay = 0.2, .freq = 0.5, .freq_limit = 0.1, .freq_dramp = 0.1, .vibrato_depth = 0.3, .vibrato_speed = 0.5, .phaser_offset = 0.3, .phaser_ramp = -0.1, .repeat_speed = 0.5 }, + .{ .wave = .sine, .attack = 0.2, .sustain = 0.2, .decay = 0.2, .freq = 0.3, .freq_ramp = 0.1, .freq_limit = 0.2, .volume = 0.8 }, +}; + +test "sfxr renders the original's samples at 44.1 kHz, and as long a sound at 48 kHz" { + // Length and Wyhash of the samples the original (02-dont-rat-me-out + // synth.zig) rendered for each set at 44.1 kHz. + const original = [_]struct { usize, u64 }{ + .{ 10003, 0xb969b441e8bd800 }, + .{ 20003, 0x5fc62aaf3122de5a }, + .{ 10253, 0x8d81ee15b98f33ac }, + .{ 12003, 0xe656fadd21b7dedb }, + }; + const out = try std.testing.allocator.alloc(f32, 2 * 48_000); + defer std.testing.allocator.free(out); + for (sets, original) |p, want| { + const n = render(p, reference_rate, out); + try std.testing.expectEqual(want[0], n); + try std.testing.expectEqual(want[1], std.hash.Wyhash.hash(0, std.mem.sliceAsBytes(out[0..n]))); + const at48 = render(p, 48_000, out); + try std.testing.expectApproxEqRel(@as(f64, @floatFromInt(n)) * 48_000 / reference_rate, @as(f64, @floatFromInt(at48)), 0.01); + } +} diff --git a/src/sketch/web.zig b/src/sketch/web.zig index 937b491..804a4df 100644 --- a/src/sketch/web.zig +++ b/src/sketch/web.zig @@ -2,7 +2,7 @@ //! the imports below: drawing on a 2D canvas, GPU work on WebGPU, sound and //! the microphone on Web Audio, files through the page. State, `update` and //! `draw` are the same Zig as on native. There is no timeline, and nothing -//! persists: Store lasts as long as the page. +//! persists. const std = @import("std"); const abi = @import("abi"); const root = @import("root.zig"); @@ -48,6 +48,8 @@ const js = struct { extern "gpu" fn download(id: u32, offset: u32, size: u32, key: u32) void; extern "audio" fn rate() u32; extern "audio" fn push(key: u32, ptr: [*]const f32, len: usize, clear: u32) void; + /// `count` samples from a GPU buffer, queued on arrival. + extern "audio" fn buffer(key: u32, id: u32, offset: u32, count: u32) void; extern "audio" fn queued(key: u32) u32; /// Keeps the microphone open; it answers through `sk_microphone`. extern "audio" fn listen() void; @@ -76,14 +78,12 @@ pub fn exportWeb(comptime App: type) void { } fn Driver(comptime App: type) type { - const G = root.Glue(App); + const G = root.Glue(App, .{}); const gpa = std.heap.wasm_allocator; return struct { var ready = false; var state: G.State = undefined; var session: G.Session = undefined; - // No disk on the web: the store lasts as long as the page. - var store: G.Store = undefined; var events: [1024]abi.Event = undefined; var event_count: usize = 0; var input: abi.Input = .{}; @@ -105,9 +105,7 @@ fn Driver(comptime App: type) type { .input = &input, .scratch = scratch.allocator(), .session = gpa, - .store = gpa, .session_root = std.mem.asBytes(&session), - .store_root = std.mem.asBytes(&store), .commands = &commands, }; } @@ -115,7 +113,6 @@ fn Driver(comptime App: type) type { fn init() callconv(.c) void { G.defaults(.state, std.mem.asBytes(&state)); G.defaults(.session, std.mem.asBytes(&session)); - G.defaults(.store, std.mem.asBytes(&store)); input.width = G.description.width; input.height = G.description.height; if (input.window_width == 0) { @@ -225,6 +222,10 @@ fn Driver(comptime App: type) type { s.pushed += v.samples.len; js.push(v.key, v.samples.ptr, v.samples.len, @intFromBool(v.clear)); }, + .audio_buffer => |v| { + stream(v.key).pushed += v.count; + js.buffer(v.key, @backingInt(v.buffer), v.offset, v.count); + }, .microphone => js.listen(), .upload => |v| _ = js.write(@backingInt(v.buffer), v.offset, v.bytes.ptr, v.bytes.len), .compute => |v| { @@ -241,9 +242,9 @@ fn Driver(comptime App: type) type { }, .download => |v| js.download(@backingInt(v.buffer), v.offset, v.size, v.key), .open_file => |v| js.openFile(v.command.ptr, v.command.len, v.pattern.ptr, v.pattern.len), - // Synthesised voices are not on the web yet; quitting a page + // Voices (and so their groups) are not on the web yet; quitting a page // means nothing; `run` lines go after the frame. - .voice, .quit, .run, .backdrop => {}, + .voice, .gain, .quit, .run, .backdrop => {}, } } @@ -411,8 +412,10 @@ fn Driver(comptime App: type) type { .textSize = textSize, .loadSound = loadSound, .decodeSound = unsupportedSound, + .newSound = newSound, .samples = samples, .readFile = readFile, + .appendFile = appendFile, .env = env, .clock = clock, }; @@ -460,6 +463,16 @@ fn Driver(comptime App: type) type { fn unsupportedSound(_: *anyopaque, _: []const u8) abi.Audio { return .none; } + /// Kept, unnamed, for `samples` (voices are silent on the web). + fn newSound(_: *anyopaque, ptr: [*]const f32, len: usize) callconv(.c) abi.Audio { + for (ptr[0..len]) |v| if (!std.math.isFinite(v)) return .none; + const copy = gpa.dupe(f32, ptr[0..len]) catch return .none; + sounds.append(gpa, .{ .name = "", .samples = copy }) catch { + gpa.free(copy); + return .none; + }; + return @fromBackingInt(@intCast(sounds.items.len)); + } fn samples(_: *anyopaque, a: abi.Audio) []const f32 { const i = @backingInt(a); return if (i == 0 or i > sounds.items.len) &.{} else sounds.items[i - 1].samples; @@ -467,6 +480,10 @@ fn Driver(comptime App: type) type { fn readFile(_: *anyopaque, _: []const u8) []const u8 { return &.{}; } + /// No files on the web: nothing is written, and the path is "". + fn appendFile(_: *anyopaque, _: [*]const u8, _: usize, _: [*]const u8, _: usize, _: bool) callconv(.c) [*:0]const u8 { + return ""; + } fn env(_: *anyopaque, _: []const u8) ?[]const u8 { return null; } diff --git a/src/vector/morph.zig b/src/vector/morph.zig index f285c7e..a05037d 100644 --- a/src/vector/morph.zig +++ b/src/vector/morph.zig @@ -2,7 +2,9 @@ //! in order; each pair's subpaths, then each subpath's cubics, are made equal //! in number by splitting the longest curves; then every control point and //! color is interpolated. A shape without a partner collapses to (or grows -//! from) the other drawing's center. +//! from) the other drawing's center. Outer contours pair with outer ones +//! and holes with holes, so a glyph's counter stays a counter; a hole +//! without a partner shrinks to nothing (or grows) inside its shape. const std = @import("std"); const geom = @import("math"); const Drawing = @import("Drawing.zig"); @@ -22,10 +24,14 @@ pub fn between(arena: std.mem.Allocator, a: Drawing, ma: geom.Affine, b: Drawing // The missing side is the other side, shrunk to a point. const pa = try placed(arena, a, sa, ma, sb, b, mb, cb); const pb = try placed(arena, b, sb, mb, sa, a, ma, ca); - const count = @max(pa.len, pb.len); - for (0..count) |k| { - const from = try pad(arena, pa, k, if (pa.len > 0) lastPoint(pa) else ca); - const to = try pad(arena, pb, k, if (pb.len > 0) lastPoint(pb) else cb); + // Outer contours pair up, then holes; a missing shape's subpaths + // are its partner's, in order. + const ha = if (sa != null and sb != null) try holesLast(arena, pa) else 0; + const hb = if (sa != null and sb != null) try holesLast(arena, pb) else 0; + const outers = @max(pa.len - ha, pb.len - hb); + for (0..outers + @max(ha, hb)) |k| { + const from = try side(arena, pa, ha, pb, hb, k, outers, ca); + const to = try side(arena, pb, hb, pa, ha, k, outers, cb); const aligned = try align2(arena, from.cubics, to.cubics); for (aligned[0], aligned[1]) |x, y| { var c: Cubic = undefined; @@ -78,6 +84,50 @@ fn pad(arena: std.mem.Allocator, paths: []const Path, k: usize, point: Vec) !Pat return .{ .cubics = one, .closed = false }; } +/// Puts the holes of `paths` (wound against the largest, as a font's +/// counters are) after its outer contours, each in order; returns how many. +fn holesLast(arena: std.mem.Allocator, paths: []Path) !usize { + const areas = try arena.alloc(f32, paths.len); + var main: f32 = 0; + for (areas, paths) |*area, p| { + area.* = geom.cross(p.cubics[p.cubics.len - 1][3], p.cubics[0][0]); + for (p.cubics) |c| area.* += geom.cross(c[0], c[1]) + geom.cross(c[1], c[2]) + geom.cross(c[2], c[3]); + if (@abs(area.*) > @abs(main)) main = area.*; + } + const all = try arena.dupe(Path, paths); + var n: usize = 0; + var holes: usize = 0; + for ([_]bool{ false, true }) |hole| for (all, areas) |p, area| if ((area * main < 0) == hole) { + paths[n] = p; + n += 1; + holes += @intFromBool(hole); + }; + return holes; +} + +/// One side's path for pair `k`: its outer contours, then its holes. One it +/// lacks is a point: an outer contour's where its last one ends (or at its +/// drawing's `middle`); a hole's where the other side's hole has its middle, +/// relative to the outer contours' bounds on each side, so that a hole with +/// no partner shrinks to nothing (or grows) inside its shape, moving with it. +fn side(arena: std.mem.Allocator, own: []const Path, holes: usize, other: []const Path, other_holes: usize, k: usize, outers: usize, middle: Vec) !Path { + const shell = own[0 .. own.len - holes]; + if (k < outers) return pad(arena, shell, k, if (shell.len > 0) lastPoint(shell) else middle); + const j = k - outers; + if (j < holes) return own[own.len - holes + j]; + const there = extent(other[0 .. other.len - other_holes]); + const here = extent(shell); + const hole = extent(other[other.len - other_holes + j ..][0..1]); + const at = ((hole.min + hole.max) / geom.splat(2) - there.min) / (there.max - there.min); + return pad(arena, &.{}, 0, here.min + at * (here.max - here.min)); +} + +fn extent(paths: []const Path) geom.Bounds { + var b: geom.Bounds = .{}; + for (paths) |p| for (p.cubics) |c| for (c) |q| b.add(q); + return b; +} + fn lastPoint(paths: []const Path) Vec { const last = paths[paths.len - 1].cubics; return last[last.len - 1][3]; diff --git a/src/vector/svg.zig b/src/vector/svg.zig index 31d9b15..f1b7daf 100644 --- a/src/vector/svg.zig +++ b/src/vector/svg.zig @@ -4,11 +4,12 @@ //! `ellipse`, `line`, `polyline`, `polygon`. Styling: presentation //! attributes and `style="..."`, inherited as SVG specifies; solid colors, //! linear and radial gradients; fill rules; stroke width, caps, joins, miter -//! limit and dashes; `opacity`, `fill-opacity`, `stroke-opacity`. +//! limit and dashes; `opacity`, `fill-opacity`, `stroke-opacity`. Images +//! that are SVG documents in base64 data URIs (Typst's SVG and PDF images). //! //! Not supported: text (Typst outlines it), filters, masks, clipping, -//! patterns, markers, images, CSS stylesheets. Group opacity is approximated -//! by multiplying it into each shape. +//! patterns, markers, raster images, CSS stylesheets. Group opacity is +//! approximated by multiplying it into each shape. const std = @import("std"); const geom = @import("math"); const Drawing = @import("Drawing.zig"); @@ -23,23 +24,26 @@ pub fn parse(arena: std.mem.Allocator, source: []const u8) Error!Drawing { const root = doc.root orelse return error.InvalidSvg; if (!std.mem.eql(u8, doc.nodes.items[root].name, "svg")) return error.InvalidSvg; - var p: Parser = .{ .doc = &doc, .b = .init(arena), .arena = arena, .view = .{} }; - const n = doc.nodes.items[root]; - const w = doc.attr(n, "width"); - const h = doc.attr(n, "height"); + const port = viewport(&doc, doc.nodes.items[root]); + var p: Parser = .{ .doc = &doc, .b = .init(arena), .arena = arena, .view = port.view }; + try p.children(root, .identity, .{}); + return p.b.finish(port.view, port.width, port.height); +} + +/// A root `svg` element's view box and size in pixels, each standing in +/// for the other when missing. +fn viewport(doc: *const Document, n: Node) struct { view: geom.Rect, width: f32, height: f32 } { var view: geom.Rect = .{}; if (doc.attr(n, "viewBox")) |vb| { var nums = Numbers{ .text = vb }; view = .{ .x = nums.next() orelse 0, .y = nums.next() orelse 0, .w = nums.next() orelse 0, .h = nums.next() orelse 0 }; } - var width = if (w) |v| lengthPx(v, view.w) else view.w; - var height = if (h) |v| lengthPx(v, view.h) else view.h; + var width = if (doc.attr(n, "width")) |v| lengthPx(v, view.w) else view.w; + var height = if (doc.attr(n, "height")) |v| lengthPx(v, view.h) else view.h; if (view.w <= 0 or view.h <= 0) view = .{ .w = width, .h = height }; if (width <= 0) width = view.w; if (height <= 0) height = view.h; - p.view = view; - try p.children(root, .identity, .{}); - return p.b.finish(view, width, height); + return .{ .view = view, .width = width, .height = height }; } // --------------------------------------------------------------------------- @@ -183,7 +187,7 @@ const Parser = struct { fn element(p: *Parser, index: u32, parent_transform: Affine, parent: Inherited) Error!void { const n = p.doc.nodes.items[index]; const name = n.name; - const skip = [_][]const u8{ "defs", "symbol", "linearGradient", "radialGradient", "clipPath", "mask", "pattern", "marker", "style", "title", "desc", "metadata", "filter", "text", "image", "foreignObject" }; + const skip = [_][]const u8{ "defs", "symbol", "linearGradient", "radialGradient", "clipPath", "mask", "pattern", "marker", "style", "title", "desc", "metadata", "filter", "text", "foreignObject" }; for (skip) |s| if (std.mem.eql(u8, name, s)) return; if (p.depth > 64) return; var inherited = parent; @@ -229,6 +233,52 @@ const Parser = struct { } return p.element(target, transform, inherited); } + if (std.mem.eql(u8, name, "image")) { + // An SVG as a base64 data URI, Typst's way to place an SVG or a + // PDF page: its document, mapped into the image's box. Raster + // images draw nothing. + const href = p.doc.attr(n, "href") orelse p.doc.attr(n, "xlink:href") orelse return; + const prefix = "data:image/svg+xml;base64,"; + if (!std.mem.startsWith(u8, href, prefix)) return; + const decoder = std.base64.standard.Decoder; + const bytes = try p.arena.alloc(u8, decoder.calcSizeForSlice(href[prefix.len..]) catch return); + decoder.decode(bytes, href[prefix.len..]) catch return; + var doc = Document.parse(p.arena, bytes) catch |err| switch (err) { + error.OutOfMemory => return err, + error.InvalidSvg => return, + }; + const root = doc.root orelse return; + if (!std.mem.eql(u8, doc.nodes.items[root].name, "svg")) return; + const port = viewport(&doc, doc.nodes.items[root]); + const v = port.view; + const w = if (p.doc.attr(n, "width")) |a| lengthPx(a, p.view.w) else port.width; + const h = if (p.doc.attr(n, "height")) |a| lengthPx(a, p.view.h) else port.height; + if (v.w <= 0 or v.h <= 0 or w <= 0 or h <= 0) return; + transform = transform.mul(.translate(p.number(n, "x"), p.number(n, "y"))); + // Stretched with `preserveAspectRatio="none"`, else centered at + // the largest scale that fits; drawn unclipped. + if (std.mem.startsWith(u8, std.mem.trim(u8, p.doc.attr(n, "preserveAspectRatio") orelse "", " "), "none")) { + transform = transform.mul(.scale(w / v.w, h / v.h)); + } else { + const s = @min(w / v.w, h / v.h); + transform = transform.mul(.translate((w - v.w * s) / 2, (h - v.h * s) / 2)).mul(.scale(s, s)); + } + transform = transform.mul(.translate(-v.x, -v.y)); + // A document of its own: its ids, gradients and percentages, and + // nothing inherited but opacity. + const outer = p.*; + defer { + p.doc = outer.doc; + p.view = outer.view; + p.gradients = outer.gradients; + } + p.doc = &doc; + p.view = v; + p.gradients = .empty; + p.depth += 1; + defer p.depth -= 1; + return p.children(root, transform, .{ .style = .{ .opacity = inherited.style.opacity } }); + } const b = &p.b; if (std.mem.eql(u8, name, "path")) { @@ -766,3 +816,23 @@ test "colors and lengths" { try std.testing.expectEqual(@as(f32, 20), parseLength("15pt")); try std.testing.expectEqual(@as(f32, 0.5), parseOpacity("50%")); } + +test "an SVG image in a data URI: its own ids, placed, stretched or fitted" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + // <svg viewBox="0 0 10 20"><defs><path id="p" d="M0 0h10v20h-10z"/></defs><use href="#p" fill="#00ff00"/></svg> + const inner = "data:image/svg+xml;base64,PHN2ZyB2aWV3Qm94PSIwIDAgMTAgMjAiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGRlZnM+PHBhdGggaWQ9InAiIGQ9Ik0wIDBoMTB2MjBoLTEweiIvPjwvZGVmcz48dXNlIGhyZWY9IiNwIiBmaWxsPSIjMDBmZjAwIi8+PC9zdmc+"; + const d = try parse(arena.allocator(), "<svg viewBox=\"0 0 100 100\"><defs><path id=\"p\" d=\"M0 0h1v1z\"/></defs>" ++ + "<image x=\"5\" y=\"5\" width=\"20\" height=\"20\" preserveAspectRatio=\"none\" href=\"" ++ inner ++ "\"/>" ++ + "<image x=\"5\" y=\"5\" width=\"20\" height=\"20\" xlink:href=\"" ++ inner ++ "\"/>" ++ + "<image href=\"data:image/png;base64,AAAA\"/></svg>"); + try std.testing.expectEqual(@as(usize, 2), d.shapes.len); + for (d.shapes) |shape| try std.testing.expectEqual(Drawing.Color{ 0, 1, 0, 1 }, shape.style.fill.color); + // The far corner (10, 20) of the image's own path: stretched to the + // box's corner, or fitted into its middle. + for (d.shapes, [_]geom.Vec{ .{ 25, 25 }, .{ 20, 25 } }) |shape, corner| { + const far = d.cubicsOf(d.subpathsOf(shape)[0])[1][3]; + try std.testing.expectEqual(geom.vec(10, 20), far); + try std.testing.expectEqual(corner, shape.transform.apply(far)); + } +} |
