diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-16 22:51:49 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-17 12:15:01 -0300 |
| commit | 64a816dbe194c05e089729ac1fdc15061afdd903 (patch) | |
| tree | 5b424f1eee653a5c607a41262a04bf843c262054 /src/anim/root.zig | |
| parent | 1cb36ee39a8bbc2cf61c28003670d760841d6d3e (diff) | |
| download | sketchbook-64a816dbe194c05e089729ac1fdc15061afdd903.tar.gz sketchbook-64a816dbe194c05e089729ac1fdc15061afdd903.zip | |
anim: talks: gates that let time run on, pause, beside, loop, clear, slides and the Deck
A talk is a live scene re-run from the top every frame, a function of its
time and of the gates opened so far. Frame.gate(open) waits while time runs
on and records the value it opened with; pause() is the presenter's click.
beside and loop are the sub-animations, slide() the second navigation
level, clear() the end of a slide. anim.Deck is the playhead and the gate
log as plain data for any sketch's State: update() takes an Ask (next,
back, next_slide, back_slide, to, end) and runs the talk with the app
mutable, shot() runs it read-only for drawing. A click during a step
finishes it; back cuts to the picture held before the last click; an edit
that moves the last opened gate moves t with it; exported, every gate
holds Deck.hold. Live takes a namespace or a tuple of them (sources) and
exposes frame. Builder.pause, Instant.clock and Frame.clock are gone: t
runs through gates. A test-anim step runs the module's tests and the
player's scenes.
Diffstat (limited to 'src/anim/root.zig')
| -rw-r--r-- | src/anim/root.zig | 818 |
1 files changed, 782 insertions, 36 deletions
diff --git a/src/anim/root.zig b/src/anim/root.zig index a676f38..ea57ed2 100644 --- a/src/anim/root.zig +++ b/src/anim/root.zig @@ -44,13 +44,20 @@ //! 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`. +//! 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 @@ -545,7 +552,6 @@ pub const Builder = struct { values: []const f32 = &.{}, plays: []const Play = &.{}, updaters: []const Updater = &.{}, - stops: []const f32 = &.{}, /// Where the next play starts. cursor: f32 = 0, @@ -580,11 +586,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. @@ -641,7 +642,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 +663,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 +677,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. @@ -816,40 +815,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 +888,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); @@ -904,10 +936,14 @@ 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 started = s.t >= p.start; + const touched = changes(buf, s.settled.items, all); for (touched) |c| { const k = p.key(Pose, c.from, c.to, c.ease); s.settled.items[c.obj] = k.at(k.end); @@ -923,7 +959,7 @@ pub const Frame = struct { v.settled = a.value.to; if (started) v.shown = k.at(s.t); }; - if (aim(s.settled_view, &all)) |to| { + 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); @@ -936,9 +972,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 +1061,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 +1085,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 +1302,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 +1314,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 +1384,418 @@ 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); +} |
