From 64a816dbe194c05e089729ac1fdc15061afdd903 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 16 Nov 2026 22:51:49 -0300 Subject: 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. --- build.zig | 11 +- examples/vecanim/scenes/live.zig | 2 +- src/anim/player.zig | 1 - src/anim/root.zig | 818 +++++++++++++++++++++++++++++++++++++-- 4 files changed, 792 insertions(+), 40 deletions(-) diff --git a/build.zig b/build.zig index 1933d92..9c6085c 100644 --- a/build.zig +++ b/build.zig @@ -164,13 +164,17 @@ pub fn build(b: *Build) void { for ([_]*Build.Module{ b.createModule(.{ .root_source_file = b.path("src/vector/root.zig"), .target = target, .optimize = optimize, .imports = vector_imports }), b.createModule(.{ .root_source_file = b.path("src/scope/root.zig"), .target = target, .optimize = optimize, .imports = scope_imports }), - b.createModule(.{ .root_source_file = b.path("src/anim/root.zig"), .target = target, .optimize = optimize, .imports = anim_imports }), b.createModule(.{ .root_source_file = b.path("src/glsl.zig"), .target = target, .optimize = optimize }), b.createModule(.{ .root_source_file = b.path("src/abi.zig"), .target = target, .optimize = optimize }), b.createModule(.{ .root_source_file = b.path("src/sketch/root.zig"), .target = target, .optimize = optimize, .imports = sketch_imports }), b.createModule(.{ .root_source_file = b.path("src/math/root.zig"), .target = target, .optimize = optimize }), b.createModule(.{ .root_source_file = b.path("src/host/root.zig"), .target = target, .optimize = optimize, .imports = &.{ .{ .name = "abi", .module = abi }, .{ .name = "c", .module = c }, .{ .name = "gpu", .module = gpu }, .{ .name = "tracy", .module = tracy }, .{ .name = "cloud9", .module = cloud9 } } }), }) |module| test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = module })).step); + // The anim module alone: its unit tests, and below the player's scenes. + const test_anim = b.step("test-anim", "Test the anim module: its unit tests and the player on its test scenes"); + const anim_tests = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("src/anim/root.zig"), .target = target, .optimize = optimize, .imports = anim_imports }) })); + test_anim.dependOn(&anim_tests.step); + test_step.dependOn(&anim_tests.step); // The noise tests again on wasm32 as the web builds it, under Node's // WASI: the golden bits must come out the same in the browser as @@ -234,13 +238,16 @@ pub fn build(b: *Build) void { // custom object between vector objects, and a compiled one, which is // also exported, at half size. const live = sb.addScene(.{ .root_source_file = b.path("test/scene_live.zig") }); - test_step.dependOn(&live.app.addScript(live.app.addExecutable(), b.path("test/scene_live.script"), .{}).step); + const live_script = live.app.addScript(live.app.addExecutable(), b.path("test/scene_live.script"), .{}); + test_step.dependOn(&live_script.step); + test_anim.dependOn(&live_script.step); const compiled = sb.addScene(.{ .root_source_file = b.path("test/scene_compiled.zig") }); const compiled_exe = compiled.app.addExecutable(); const compiled_script = compiled.app.addScript(compiled_exe, b.path("test/scene_compiled.script"), .{}); compiled_script.addArg("--define"); compiled_script.addPrefixedDirectoryArg("frames=", compiled.app.addExport(compiled_exe, .{ .fps = 30, .size = .{ 640, 360 }, .frames = 200 }).frames); test_step.dependOn(&compiled_script.step); + test_anim.dependOn(&compiled_script.step); // Both vector renderers against resvg, through the host (tools/svgdiff.py). const svgview = sb.app(.{ .name = "svgview", .root_source_file = b.path("test/svgview.zig"), .imports = &.{.{ .name = "vector", .module = sb.modules.vector }} }); diff --git a/examples/vecanim/scenes/live.zig b/examples/vecanim/scenes/live.zig index cefdbc5..4af7998 100644 --- a/examples/vecanim/scenes/live.zig +++ b/examples/vecanim/scenes/live.zig @@ -61,7 +61,7 @@ fn frame(s: *anim.Frame) void { for (dots) |d| { const p = s.pose(d); const envelope = 1 - s.get(damping) * (1 - @exp(-p.x * p.x / 1e5)); - p.y = s.get(height) * envelope * @sin(p.x / 90 - s.clock * 2); + p.y = s.get(height) * envelope * @sin(p.x / 90 - s.t * 2); const near = @max(0, 1 - @abs(p.x - s.pointer[0]) / 120); p.scale = 1 + near; p.y -= 40 * near; diff --git a/src/anim/player.zig b/src/anim/player.zig index 090b6cb..9d29e95 100644 --- a/src/anim/player.zig +++ b/src/anim/player.zig @@ -164,7 +164,6 @@ pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void { 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}); 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 { @@ -956,6 +1084,209 @@ 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 @@ -963,7 +1294,6 @@ pub const Frame = struct { 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); +} -- cgit v1.3 From 0c10f9668b3ef67ce1eb83db435aaa94b35df012 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 16 Nov 2026 22:53:41 -0300 Subject: anim: the player's render path moves into anim.Painter render, paint, reveal, built, stage, guides and labels move verbatim from player.zig into src/anim/Painter.zig, with the viewer's settings and the Typst module as parameters, so a sketch that runs a Deck itself paints its shot the same way: a Painter in its Session and paint() once a frame. The scene's frame size is anim.width/height and a Shot carries its t. Pixels unchanged: the scene tests' screenshots and all 92 exported frames match the previous build's. --- src/anim/Painter.zig | 256 +++++++++++++++++++++++++++++++++++++++++++++++++++ src/anim/player.zig | 242 ++---------------------------------------------- src/anim/root.zig | 1 + 3 files changed, 264 insertions(+), 235 deletions(-) create mode 100644 src/anim/Painter.zig diff --git a/src/anim/Painter.zig b/src/anim/Painter.zig new file mode 100644 index 0000000..b5d492f --- /dev/null +++ b/src/anim/Painter.zig @@ -0,0 +1,256 @@ +//! 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) !Built { + const id = o.id(); + if (p.drawings.get(id)) |b| return b; + const arena = p.arena.?.allocator(); + const d = try anim.build(arena, o, svgs); + 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]; + const target = (try p.built(shot.objects[pose.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 9d29e95..c9f2169 100644 --- a/src/anim/player.zig +++ b/src/anim/player.zig @@ -23,14 +23,13 @@ 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; /// 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, @@ -47,21 +46,11 @@ pub const State = struct { }; 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 }; - 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); @@ -145,29 +134,23 @@ 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, .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}); + 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(); @@ -178,217 +161,6 @@ 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; @@ -400,7 +172,7 @@ fn hud(s: *const State, ss: *const Session, f: *sk.Frame, shot: anim.Shot, canva const status = if (!s.playing) " paused" else if (held(s.t, shot)) " 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, + s.t, shot.duration, play, shot.marks.len, backend, ss.render_ns / 1e6, ss.painter.shapes, s.speed, status, }); if (s.guides) { const p = pointer(s, f.in, canvas); diff --git a/src/anim/root.zig b/src/anim/root.zig index ea57ed2..4acecb3 100644 --- a/src/anim/root.zig +++ b/src/anim/root.zig @@ -69,6 +69,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; -- cgit v1.3 From 7e3475a779f9e8dcb14b96cfc59e2b92a20c0cda Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 16 Nov 2026 22:55:10 -0300 Subject: anim: the stock player runs on the Deck The player's State is an anim.Deck plus the viewer's settings; keys and clicks become an Ask: click, space and page down step (space plays or pauses a scene with no pause), page up and backspace go back a step, ] and [ go a slide, P plays or pauses, left/right/home/end/,/. seek through Ask.to and Ask.end. A compiled scene is a talk without gates. The HUD shows the slide and step, and when the talk waits. Exported, each pause holds the scene file's hold (1 s). Its frozen hold (held, stopBetween, proceed) is gone. Scripts read deck.t and deck.playing where they read t and playing. --- examples/vecanim/test/intro.script | 14 ++-- src/anim/player.zig | 141 +++++++++++++++++++++---------------- test/scene_compiled.script | 2 +- test/scene_live.script | 21 +++--- 4 files changed, 101 insertions(+), 77 deletions(-) diff --git a/examples/vecanim/test/intro.script b/examples/vecanim/test/intro.script index 75ce751..9dd61bb 100644 --- a/examples/vecanim/test/intro.script +++ b/examples/vecanim/test/intro.script @@ -2,28 +2,28 @@ # then the same instants on the CPU renderer. frames 60 screenshot .zig-cache/e2e/title.png -console set t 7.5 +console set deck.t 7.5 frames 1 screenshot .zig-cache/e2e/shapes.png -console set t 13 +console set deck.t 13 frames 1 screenshot .zig-cache/e2e/morph.png -console set t 16.5 +console set deck.t 16.5 frames 1 screenshot .zig-cache/e2e/zoom.png -console set t 24 +console set deck.t 24 frames 1 screenshot .zig-cache/e2e/text.png key b expect backend cpu -console set t 13 +console set deck.t 13 frames 1 screenshot .zig-cache/e2e/morph-cpu.png -console set t 24 +console set deck.t 24 frames 1 screenshot .zig-cache/e2e/text-cpu.png key g expect guides true -console set t 16.5 +console set deck.t 16.5 frames 1 screenshot .zig-cache/e2e/guides.png diff --git a/src/anim/player.zig b/src/anim/player.zig index c9f2169..3b0662d 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"); @@ -27,20 +33,20 @@ const typst = @import("typst"); 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 = 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, }; @@ -51,32 +57,39 @@ pub const Session = struct { render_ns: f32 = 0, }; +/// 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; + .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, @@ -89,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, @@ -97,28 +110,30 @@ 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,15 +160,11 @@ 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) }; const started = f.host.clock(); - const shot = scene.shot(f.scratch, .{ - .t = s.t, - .in = f.in, - .pointer = pointer(s, f.in, canvas), - }) catch |err| return f.host.print("scene: {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); @@ -164,20 +175,28 @@ pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void { 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.painter.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/test/scene_compiled.script b/test/scene_compiled.script index 3c9ef44..df2d62f 100644 --- a/test/scene_compiled.script +++ b/test/scene_compiled.script @@ -2,7 +2,7 @@ # 30 fps, 640x360, so half size, played once without the player's controls). frames 30 screenshot .zig-cache/anim/compiled-written.png -console set t 1.5 +console set deck.t 1.5 frames 1 screenshot .zig-cache/anim/compiled-morph.png # Frame 68 is 2.27 s in: the dot over the panel's corner, at half size. diff --git a/test/scene_live.script b/test/scene_live.script index 30b2087..e480d8d 100644 --- a/test/scene_live.script +++ b/test/scene_live.script @@ -1,6 +1,9 @@ -# The live test scene, through the player. It holds at the pause. +# The live test scene, through the player. At the pause it waits for a +# click, time running on and nothing after the pause starting. frames 150 -expect t 2 +expect deck.waiting true +expect deck.t 2.5 ~0.02 +expect deck.log.len 0 screenshot .zig-cache/anim/live.png # The custom panel is over the circle added before it, expect-pixel .zig-cache/anim/live.png 600 330 32 64 96 255 1 @@ -11,23 +14,25 @@ expect-pixel .zig-cache/anim/live.png 725 400 131 193 103 255 1 expect-pixel .zig-cache/anim/live.png 600 390 240 172 95 255 1 expect-pixel .zig-cache/anim/live.png 680 390 32 64 96 255 1 # Half way through its move it is half way. -console set playing false -console set t 1.5 +console set deck.playing false +console set deck.t 1.5 screenshot .zig-cache/anim/live-moving.png expect-pixel .zig-cache/anim/live-moving.png 400 330 32 64 96 255 1 expect-pixel .zig-cache/anim/live-moving.png 600 330 252 98 85 255 1 # The CPU renderer layers the same way. -console set t 2 +console set deck.t 2 key b expect backend cpu screenshot .zig-cache/anim/live-cpu.png expect-pixel .zig-cache/anim/live-cpu.png 600 330 32 64 96 255 1 expect-pixel .zig-cache/anim/live-cpu.png 725 400 131 193 103 255 1 key b -# A click continues: the camera zooms to 2 and the panel fades to half, -# over the background where it now reaches. +# A click opens the pause and plays on: the camera zooms to 2 and the +# panel fades to half, over the background where it now reaches. click 640 360 -expect playing true +expect deck.playing true +expect deck.log.len 1 +expect deck.waiting false frames 70 screenshot .zig-cache/anim/live-zoom.png expect-pixel .zig-cache/anim/live-zoom.png 800 300 30 46 64 255 2 -- cgit v1.3 From 6b07c3b2ee86592a28a713b4c6c40007c28eb6b8 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 16 Nov 2026 22:59:59 -0300 Subject: examples: a talk that runs its own Deck, and its script examples/talk.zig keeps an anim.Deck in its State beside its own data, turns clicks and keys into asks and paints with an anim.Painter: two slides, a mass that bobs (loop) while the deck waits, a damping slider laid out and hit-tested in the talk (it takes its clicks), a choice gate that branches on it, and slide 1 cleared beside slide 2's writing. test/talk.script (zig build test-talk) steps it, finishes a step on a click, goes back, jumps slides, drags the slider without advancing, reloads mid-wait with the first step retimed (same step, t a second later) and checks two exports with 2 s holds frame by frame. The vecanim live scene's words follow the new pause. --- build.zig | 22 ++++++ examples/talk.zig | 160 ++++++++++++++++++++++++++++++++++++++ examples/vecanim/scenes/live.zig | 7 +- examples/vecanim/test/live.script | 5 +- test/talk.script | 104 +++++++++++++++++++++++++ 5 files changed, 293 insertions(+), 5 deletions(-) create mode 100644 examples/talk.zig create mode 100644 test/talk.script diff --git a/build.zig b/build.zig index 9c6085c..3739bcf 100644 --- a/build.zig +++ b/build.zig @@ -249,6 +249,28 @@ pub fn build(b: *Build) void { test_step.dependOn(&compiled_script.step); test_anim.dependOn(&compiled_script.step); + // The talk example: a Deck in a sketch's own State, stepped, sent back, + // jumped by slides, clicked on its slider, reloaded mid-wait with its + // first step retimed, and exported twice, with the same frames. + const talk_imports: []const Build.Module.Import = &.{ .{ .name = "anim", .module = sb.modules.anim }, .{ .name = "sketch", .module = sketch } }; + const talk = sb.app(.{ .name = "talk", .root_source_file = b.path("examples/talk.zig"), .imports = &.{ + .{ .name = "anim", .module = sb.modules.anim }, + .{ .name = "typst", .module = sb.addTypst(b.createModule(.{ .root_source_file = b.path("examples/talk.zig"), .imports = talk_imports })) }, + } }); + const talk_check = talk.addReloadCheck(.{ .script = b.path("test/talk.script"), .edits = &.{.{ + .file = "examples/talk.zig", + .old = "s.play(.{ title.write(), law.write() }, .{});", + .new = "s.play(.{ title.write(), law.write() }, .{ .seconds = 3 });", + }} }); + const talk_exe = talk.addExecutable(); + for ([_][]const u8{ "a", "b" }, [_]u64{ 400, 401 }) |define, frames| { + talk_check.run.addArg("--define"); + talk_check.run.addPrefixedDirectoryArg(b.fmt("{s}=", .{define}), talk.addExport(talk_exe, .{ .fps = 30, .frames = frames, .size = .{ 640, 360 } }).frames); + } + const test_talk = b.step("test-talk", "Play the talk example: steps, back, slides, its slider, a reload mid-wait and its export"); + test_talk.dependOn(&talk_check.run.step); + test_step.dependOn(&talk_check.run.step); + // Both vector renderers against resvg, through the host (tools/svgdiff.py). const svgview = sb.app(.{ .name = "svgview", .root_source_file = b.path("test/svgview.zig"), .imports = &.{.{ .name = "vector", .module = sb.modules.vector }} }); const diff = b.addSystemCommand(&.{ "python3", "tools/svgdiff.py" }); diff --git a/examples/talk.zig b/examples/talk.zig new file mode 100644 index 0000000..f2a2d9c --- /dev/null +++ b/examples/talk.zig @@ -0,0 +1,160 @@ +//! A talk in a sketch of its own: the sketch keeps an `anim.Deck` in its +//! State beside its own data, decides which keys and clicks step the talk, +//! and paints with an `anim.Painter`. The talk is a function run from the +//! top every frame; it may change the app in `update` (`anim.mutable`), +//! so the slider below is laid out, drawn and hit-tested in one place. +//! +//! click, space, right, page down next step left, page up back +//! ] / [ next / previous slide +const std = @import("std"); +const sk = @import("sketch"); +const anim = @import("anim"); +/// This file's Typst, compiled at build time (`sb.addTypst`). +const svgs = @import("typst"); + +pub const name = "talk"; +pub const width = anim.width; +pub const height = anim.height; + +pub const typst_preamble = + \\#set page(width: auto, height: auto, margin: 3pt, fill: none) + \\#set text(fill: rgb("#ece6e2"), size: 28pt) +; +pub const typst = struct { + pub const title = "#text(size: 40pt, weight: \"bold\")[Damping]"; + pub const law = "$ x'' + 2 zeta x' + x = 0 $"; + pub const hint = "#text(size: 18pt, fill: rgb(\"#58c4dd\"))[drag $zeta$, then go on]"; + pub const rings = "#text(size: 24pt)[$zeta < 1$: it rings]"; + pub const creeps = "#text(size: 24pt)[$zeta >= 1$: it creeps back]"; + pub const end = "#text(size: 32pt)[$zeta = 1$: home fastest, no overshoot]"; +}; +/// What the build compiles. +pub const scene = struct { + pub const typst_sources = anim.sources(.{typst}); +}; + +const App = struct { + zeta: f32 = 0.2, + /// The slider is held. + dragging: bool = false, +}; + +pub const State = struct { + deck: anim.Deck = .{ .hold = 2 }, + app: App = .{}, +}; + +pub const Session = struct { + painter: anim.Painter = .{}, +}; + +pub fn update(s: *State, in: *const sk.Input) void { + var ask: anim.Ask = .{}; + for (in.events) |e| switch (e.kind) { + // Every click is the presenter's, unless the talk takes it. + .mouse_up => ask.next = true, + .key_down => switch (@as(sk.Key, @fromBackingInt(@intCast(@as(u8, @truncate(e.code)))))) { + .space, .right, .page_down => ask.next = true, + .left, .page_up => ask.back = true, + .right_bracket => ask.next_slide = true, + .left_bracket => ask.back_slide = true, + else => {}, + }, + else => {}, + }; + s.deck.update(in, ask, talk, .{&s.app}); +} + +pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void { + const mouse = anim.Deck.pointer(f.in, f.in.mouse_x, f.in.mouse_y); + const shot = s.deck.shot(f.scratch, f.in, mouse, talk, .{&s.app}) catch |err| return f.host.print("talk: {t}", .{err}); + ss.painter.paint(f, shot, svgs, .{}) catch |err| f.host.print("paint: {t}", .{err}); + if (f.in.exporting and s.deck.t >= shot.duration) f.quit(); +} + +/// Run in `update` with `app: *App`, and drawn with `app: *const App`. +fn talk(s: *anim.Frame, app: anytype) void { + // Slide 1: the law, and a mass on a spring that bobs while we talk. + s.slide(); + const title = s.typst(typst.title, .{ .y = -270 }); + const law = s.typst(typst.law, .{ .y = -180 }); + const mass = s.rect(.{ .w = 60, .h = 60, .fill = anim.blue }); + s.play(.{ title.write(), law.write() }, .{}); + s.play(.{mass.fadeIn()}, .{ .seconds = 0.5 }); + s.loop(bob, .{mass}); + s.pause(); + + // The slider, laid out before the gate it waits at: a click on it is + // its own, not the presenter's. + const plot = s.custom(s.new(Plot{ .zeta = app.zeta }), .{}); + const hint = s.typst(typst.hint, .{ .y = 290 }); + s.play(.{ mass.fadeOut(), plot.fadeIn(), hint.fadeIn() }, .{ .seconds = 0.6 }); + if (anim.mutable(app)) |a| if (s.pose(plot).visible) drag(s, a); + // A choice: the regime the slider is in when the presenter goes on. + const regime = s.gate(if (s.next) @intFromBool(app.zeta >= 1) else null) orelse return; + const verdict = s.typst(if (regime == 0) typst.rings else typst.creeps, .{ .y = 290 }); + s.play(.{ hint.fadeOut(), verdict.write() }, .{ .seconds = 1 }); + s.pause(); + + // Slide 2, written while slide 1 goes. + s.beside(anim.Frame.clear, .{.{ .seconds = 0.8 }}); + s.slide(); + s.play(.{s.typst(typst.end, .{}).write()}, .{}); +} + +/// Down and up again, in a second. +fn bob(s: *anim.Frame, mass: anim.Obj) void { + s.play(.{mass.move(.{ .y = 80 })}, .{ .seconds = 0.5 }); + s.play(.{mass.move(.{ .y = 0 })}, .{ .seconds = 0.5 }); +} + +/// The slider's track, in scene units: zeta from 0 to 2 along it. +const track: sk.Rect = .{ .x = -300, .y = 200, .w = 600, .h = 40 }; + +/// The slider follows a press on it to where it is let go, and takes that +/// click: it is not the presenter's next. +fn drag(s: *anim.Frame, app: *App) void { + for (s.events) |e| { + if (e.kind != .mouse_down and e.kind != .mouse_move and e.kind != .mouse_up) continue; + if (e.kind == .mouse_down) app.dragging = track.contains(e.x, e.y); + if (!app.dragging) continue; + app.zeta = std.math.clamp((e.x - track.x) / track.w * 2, 0, 2); + if (e.kind == .mouse_up) { + app.dragging = false; + s.next = false; + } + } +} + +/// The motion zeta makes, x(t) from x = 1 at rest, over the slider: a +/// custom object at the scene's origin, so its units are scene units. +const Plot = struct { + zeta: f32, + + pub fn draw(p: *const Plot, f: *sk.Frame, at: anim.Placed) void { + var points: [121]sk.math.Vec = undefined; + for (&points, 0..) |*q, i| { + const t: f32 = @as(f32, @floatFromInt(i)) / 10; + q.* = .{ -300 + 50 * t, 60 - 120 * response(p.zeta, t) }; + } + sk.draw.line(f, .{ -300, 60 }, .{ 300, 60 }, at.pen(.{ .stroke = .hex(0x8c8c8c), .width = 1 })); + sk.draw.polyline(f, &points, at.pen(.{ .stroke = .hex(anim.yellow), .width = 3 })); + sk.draw.rect(f, .{ .x = track.x, .y = track.y + 18, .w = track.w, .h = 4 }, at.pen(.{ .fill = .hex(0x8c8c8c) })); + sk.draw.circle(f, .{ track.x + p.zeta / 2 * track.w, track.y + 20 }, 14, at.pen(.{ .fill = .hex(anim.blue) })); + var label: [16]u8 = undefined; + at.text(f, track.x + p.zeta / 2 * track.w - 30, track.y - 22, 1.5, std.fmt.bufPrint(&label, "{d:.2}", .{p.zeta}) catch "", .white); + } +}; + +/// x(t) of x'' + 2 zeta x' + x = 0 from x = 1, x' = 0. +fn response(zeta: f32, t: f32) f32 { + if (zeta < 1) { + const w = @sqrt(1 - zeta * zeta); + return @exp(-zeta * t) * (@cos(w * t) + zeta / w * @sin(w * t)); + } + if (zeta == 1) return @exp(-t) * (1 + t); + const r = @sqrt(zeta * zeta - 1); + const a = -zeta + r; + const b = -zeta - r; + return (b * @exp(a * t) - a * @exp(b * t)) / (b - a); +} diff --git a/examples/vecanim/scenes/live.zig b/examples/vecanim/scenes/live.zig index 4af7998..9b94d17 100644 --- a/examples/vecanim/scenes/live.zig +++ b/examples/vecanim/scenes/live.zig @@ -1,6 +1,7 @@ //! A live scene, presented like slides: `frame` runs every frame, so the -//! code after the plays can follow the mouse, the clock or any data, and -//! `pause` holds until a click. Everything it needs is in this file. +//! code after the plays can follow the mouse, the time or any data, and +//! what comes after a `pause` waits for a click while time runs on. +//! Everything it needs is in this file. const anim = @import("anim"); pub const typst_preamble = @@ -28,7 +29,7 @@ fn frame(s: *anim.Frame) void { s.play(.{ title.fadeOut(), hint.fadeOut() }, .{ .seconds = 0.6 }); // A wave of dots: its height is a value the timeline animates, its - // phase the wall clock, which runs on through pauses. + // phase the scene's time, which runs on while a pause waits. const wave = s.typst(typst.wave, .{ .y = -220, .scale = 1.2 }); const note = s.typst(typst.note, .{ .y = 230 }); const height = s.value(0); diff --git a/examples/vecanim/test/live.script b/examples/vecanim/test/live.script index a3ddcdc..d955b6f 100644 --- a/examples/vecanim/test/live.script +++ b/examples/vecanim/test/live.script @@ -1,5 +1,6 @@ -# Plays the live scene headless: it holds at each pause until a click, the -# dots follow the pointer, and the guides draw over everything. +# Plays the live scene headless: it waits at each pause for a click, the +# wave running on, the dots follow the pointer, and the guides draw over +# everything. frames 150 expect t 2 screenshot .zig-cache/e2e/live-title.png diff --git a/test/talk.script b/test/talk.script new file mode 100644 index 0000000..e123d59 --- /dev/null +++ b/test/talk.script @@ -0,0 +1,104 @@ +# The talk example (examples/talk.zig): a Deck in the sketch's own State, +# stepped by the clicks and keys the sketch turns into asks. +frames 90 +expect deck.waiting false +expect deck.slide 1 +# Slide 2 lies after the choice, which has not been made. +expect deck.slides 1 +# A click during the first step finishes it: held at the first pause. +click 100 100 +expect deck.t 2.5 ~0.0001 +expect deck.waiting true +expect deck.log.len 0 +# The mass bobs while the deck waits. +screenshot .zig-cache/talk/bob-a.png +frames 14 +screenshot .zig-cache/talk/bob-b.png +expect-different-screenshot .zig-cache/talk/bob-a.png .zig-cache/talk/bob-b.png +# The next click opens the pause where it lands: the slider comes in, and +# the deck waits at the choice. +click 100 100 +expect deck.log.len 1 +expect deck.log.buffer[0].wait 0.2833 ~0.001 +await deck.waiting true +frames 5 +# Reloaded mid-wait, the first step retimed from 2 s to 3: the same step, +# as far into it, a second later. +console set deck.playing false +expect deck.t 3.4833 ~0.001 +load {v2} +expect deck.t 4.4833 ~0.001 +expect deck.waiting true +expect deck.log.len 1 +expect deck.log.buffer[0].wait 0.2833 ~0.001 +console set deck.playing true +# A click on the slider is the slider's: zeta goes there, the deck stays. +click 790 580 +expect app.zeta 1.5 ~0.01 +expect deck.log.len 1 +expect deck.waiting true +# So is a drag along it, let go and all. +down 640 580 +move 400 580 +up 400 580 +expect app.zeta 0.2 ~0.01 +expect app.dragging false +expect deck.log.len 1 +expect deck.waiting true +# Going on chooses by the slider: under 1, it rings; slide 2 is laid. +key space +expect deck.log.len 2 +expect deck.log.buffer[1].value 0 +expect deck.slides 2 +frames 90 +screenshot .zig-cache/talk/rings.png +# Back: held at the choice again; over 1, it creeps. +key page_up +expect deck.log.len 1 +expect deck.waiting true +click 840 580 +expect app.zeta 1.667 ~0.01 +key space +expect deck.log.len 2 +expect deck.log.buffer[1].value 1 +frames 90 +screenshot .zig-cache/talk/creeps.png +expect-different-screenshot .zig-cache/talk/rings.png .zig-cache/talk/creeps.png +# Slide 2 at rest: it holds no pause, so its end. +key right_bracket +expect deck.slide 2 +expect deck.log.len 3 +expect deck.waiting false +# Back a slide: slide 1 at rest, held at its first pause (3 s of writing +# in this build, then the mass). +key left_bracket +expect deck.slide 1 +expect deck.log.len 0 +expect deck.t 3.5 ~0.0001 +expect deck.waiting true +# Recorded, clicks, the slider and keys replay to the same State: the deck +# opens gates in update, from events and State alone. +console record 0 +click 100 100 +frames 40 +click 790 580 +key space +frames 30 +key page_up +key right_bracket +frames 10 +console save 2 +console play 0 +frames 120 +expect-snapshot 2 +console stop +# Exported ({a}, {b}: 30 fps, half size), each gate holds 2 s: the mass +# bobs through the first hold (to 4.5 s), nothing moves at the choice +# (5.1 to 7.1 s), and the verdict writes after it. Twice, the same frames. +expect-different-screenshot {a}/000080.png {a}/000090.png +expect-different-screenshot {a}/000130.png {a}/000170.png +expect-same-screenshot {a}/000170.png {a}/000200.png +expect-different-screenshot {a}/000200.png {a}/000230.png +expect-same-screenshot {a}/000080.png {b}/000080.png +expect-same-screenshot {a}/000230.png {b}/000230.png +expect-same-screenshot {a}/000350.png {b}/000350.png -- cgit v1.3 From 87e8d3dee3bd57d28c42672d35ae214bbc058b9a Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 16 Nov 2026 23:01:20 -0300 Subject: README: talks in the Animation section: the Deck, gates, sub-animations, slides, a talk with a widget, export holds; the player's new keys --- README.md | 131 ++++++++++++++++++++++++++++++++++++++++----- examples/vecanim/README.md | 15 +++--- 2 files changed, 125 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 225f87c..fb0beb4 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,7 @@ The standalone example packages live in [`examples/`](examples/): - [`noc`](examples/noc/): 21 Nature of Code sketches. Select one with `-Dsketch=flocking`. - [`shaders`](examples/shaders/): five shader examples in both Zig and GLSL. - [`vecanim`](examples/vecanim/): vector animation scenes. Select one with `-Dscene=scenes/live.zig`. +- [`talk.zig`](examples/talk.zig): a talk with a slider in it, a sketch that runs its own `anim.Deck` (`zig build test-talk` plays it). Run `zig build run` inside a package, with `zig build lib --watch` in a second terminal for hot reload. `zig build test` runs its headless checks; @@ -439,8 +440,8 @@ stb_vorbis): WAV, FLAC and Ogg Vorbis, chosen by content. ## Animation The `anim` module (`sb.modules.anim`) is manim-style animation written as -code: Typst for text and math, shapes, cameras, morphs, slide-style -pauses, and objects the scene draws itself. A scene is one file, and +code: Typst for text and math, shapes, cameras, morphs, talks that wait +for clicks, and objects the scene draws itself. A scene is one file, and `sb.addScene` builds the player around it: ```zig @@ -480,8 +481,8 @@ returns a handle. Animations are methods of the handle: `write`, `create`, .opacity })`, `scaleTo`, `rotate`, `indicate`; plus `anim.camera(...)` and `value.to(x)`. `play` runs a tuple (or array) of them together; its options are `.seconds`, `.ease` (any `fn (f32) f32`) and `.lag` (manim's -lag ratio). `wait` moves time on, `pause()` holds the player there until a -click, like a slide. Positions are scene units: 1280x720 of them show at +lag ratio). `wait` moves time on; in a live scene, `pause()` makes what +follows wait for a click (see Talks). Positions are scene units: 1280x720 of them show at camera zoom 1, the origin in the middle, y down. The page behind them is the scene file's `pub const background = 0xRRGGBB` (manim's grey without one). @@ -499,13 +500,15 @@ A scene is one of two kinds, which share every call: frame, at runtime. Each `play` takes effect at once against `s.t`, so the code after it reads and changes what shows, with no callbacks: `s.pose(obj).y = ...`, `s.get(value)`, `s.camera()`, the mouse - (`s.pointer`), the wall clock (`s.clock`, which runs on through pauses) - or any runtime data. Its Typst sources are the declarations of the - namespace it is given, since the build cannot run it to find them. + (`s.pointer`), the time (`s.t`, which runs on while a pause waits) or + any runtime data. Its Typst sources are the declarations of the + namespace it is given (or a tuple of namespaces), since the build cannot + run it to find them. Both answer the player the same way (`shot`: objects, poses, values, -camera, plays and pauses at an instant), so the only state is `t`, and -scrubbing, seeking and hot reload are free. A test checks that a live +camera, plays and gates at an instant), so the only state is the time and +the pauses clicked through, and scrubbing, seeking and hot reload are +free. A test checks that a live scene and a compiled one with the same timeline show the same poses at every instant. @@ -566,11 +569,16 @@ a custom object's commands keep their own order. **The player** (`src/anim/player.zig`) fits the scene's frame into the canvas, and its canvas is the room it has: the window, or an export's -`--size`. Keys: space pause, click to continue after a `pause`, left/right -previous/next play, `,`/`.` step a frame, home/end, up/down speed, B GPU or -CPU renderer, L loop, G guides (boxes, origins and the scene's axes, in -scene units); drag and wheel to look around, R to reset the view. Exported, -it plays through once, without pauses or controls, and quits at the end: +`--size`. Its State is an `anim.Deck` (`deck.t`, `deck.playing`, ...) +and the viewer's settings. Keys: click, space or page down for the next +step of a talk (space plays and pauses a scene with no pause), page up or +backspace back a step, `]`/`[` the next/previous slide, P play/pause, +left/right previous/next play, `,`/`.` step a frame, home/end, up/down +speed, B GPU or CPU renderer, L loop (a talk holds its end instead), G +guides (boxes, origins and the scene's axes, in scene units); drag and +wheel to look around, R to reset the view. Exported, it plays through once without controls, each pause +held for the scene file's `pub const hold` seconds (1 without one), and +quits at the end: ```sh zig build export -- frames --size 3840x2160 @@ -593,6 +601,101 @@ the scene file besides `anim` and `sketch`. `test/scene_live.zig` and `test/scene_compiled.zig` are small scenes of each kind, with a custom object. +### Talks + +A talk is a live scene that waits: run from the top every frame, it is a +function of its time and of the gates opened so far. Time never stops at +a gate. What was laid before it (plays still running, a `loop`, code +reading `s.t`) carries on, and what comes after waits in the future until +the gate opens. So a talk seeks, steps back and hot-reloads like any live +scene. + +- `s.pause()` waits for the presenter's next step (a click, space, page + down). A click while a step plays finishes it, like Keynote: the + picture jumps to where the next pause is laid; the next click opens it. + Back cuts to the picture held before the last click. +- `s.gate(open)` waits for anything: it opens on the first frame at or + after it is reached on which `open` is not null, and returns that value + from then on (null before), a choice to branch on: + `const pick = s.gate(app.answer) orelse return;`. Code after a closed + gate would show nothing, so `orelse return` is the usual end. A gate + opens only in `update`, from what `update` sees (events and State), so + a recording replays to the same talk. One click opens one gate. +- `s.beside(f, args)` runs `f(s, args...)`, plays and all, from the + cursor, and leaves the cursor where it was: what follows runs alongside + (`s.beside(anim.Frame.clear, .{.{}})` fades a slide out while the next + one writes). `s.loop(f, args)` plays `f` again and again from the + cursor until the gate laid right after it opens; the cycle running then + completes. `f` only plays, and ends where it began. `s.clear(options)` + fades out everything that shows. +- `s.slide()` begins a slide. Next/previous slide goes to a slide's + resting picture: held at its first gate (the end of the slide if it has + none), every gate before it opened at once (a choice with 0) or undone. + +The playhead is `anim.Deck`, plain data (`t`, `playing`, `speed`, `hold`, +and `log`, each gate opened: how long after it was reached, and its +value), so hot reload, snapshots, replay, scripts and the console see it +like any field; `deck.waiting`, `deck.slide`, `deck.gates` and +`deck.duration` say where the talk stands. The stock player keeps one, and +any sketch can keep its own beside its data: its `update` decides which +events ask for what (`anim.Ask`: `next`, `back`, `next_slide`, +`back_slide`, `to`, `end`), so the deck never owns the keyboard. The talk +takes the sketch's data after the frame: in `update` as `*App`, so the +talk may change it, and when drawn as `*const App`, so drawing cannot. +`anim.mutable(app)` is the app to write to, null when drawn; `s.events` +are this update's events in scene units (none when drawn); a widget laid +out before the pause it waits at takes a click by setting `s.next = +false`. `anim.Painter` draws a shot as the player does: + +```zig +pub const typst = struct { pub const law = "$ x'' + 2 zeta x' + x = 0 $"; }; +pub const scene = struct { pub const typst_sources = anim.sources(.{typst}); }; // for sb.addTypst +pub const State = struct { deck: anim.Deck = .{}, app: App = .{} }; +pub const Session = struct { painter: anim.Painter = .{} }; +const App = struct { presses: u32 = 0 }; +const button: sk.Rect = .{ .x = -30, .y = 150, .w = 60, .h = 60 }; // scene units + +pub fn update(s: *State, in: *const sk.Input) void { + s.deck.update(in, .{ .next = in.mouseReleased(.left) != null, .back = in.pressed(sk.Key.left) }, talk, .{&s.app}); +} + +pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void { + const shot = s.deck.shot(f.scratch, f.in, .{ 0, 0 }, talk, .{&s.app}) catch return; + ss.painter.paint(f, shot, @import("typst"), .{}) catch {}; +} + +fn talk(s: *anim.Frame, app: anytype) void { + const law = s.typst(typst.law, .{}); + s.play(.{law.write()}, .{}); + s.loop(pulse, .{law}); // runs on while the deck waits + s.pause(); + const knob = s.circle(.{ .r = 30, .y = 180, .fill = anim.blue }); + s.play(.{knob.fadeIn()}, .{}); + if (anim.mutable(app)) |a| for (s.events) |e| if (e.kind == .mouse_up and button.contains(e.x, e.y)) { + a.presses += 1; // the knob's click, not the presenter's next + s.next = false; + }; + const many = s.gate(if (s.next) @intFromBool(app.presses > 2) else null) orelse return; // a choice + s.play(.{if (many == 1) knob.scaleTo(2) else knob.fadeOut()}, .{}); +} + +fn pulse(s: *anim.Frame, o: anim.Obj) void { + s.play(.{o.indicate()}, .{ .seconds = 1.5 }); +} +``` + +`sb.addTypst(module)` compiles the Typst of a module that declares +`scene.typst_sources` (a module of the sketch's file without the `typst` +import, see `build.zig`'s talk). Gates are known by the order they are +reached: insert a pause above where a talk stands and it lands a step +earlier. An edit that moves the last opened gate (a step above retimed) +moves `t` with it on reload, so the presenter stays on the same step, as +far into it. Exported (`in.exporting`), every gate opens `deck.hold` +seconds after it is reached, in the first frame's run, so the video shows +each wait for that long, loops running, and the frames are the same every +run; a sketch quits at `deck.t >= shot.duration`. `examples/talk.zig` is +a talk with a slider, a loop, a choice, two slides and `beside`. + ## The host - **Hot reload.** It watches the library file and loads each new build through diff --git a/examples/vecanim/README.md b/examples/vecanim/README.md index 7627fe4..cc6dc0e 100644 --- a/examples/vecanim/README.md +++ b/examples/vecanim/README.md @@ -18,18 +18,19 @@ zig build export -- - --size 3840x2160 --fps 60 | ffmpeg -f rawvideo -pix_fmt rgba -s 3840x2160 -r 60 -i - -pix_fmt yuv420p intro.mp4 ``` -Keys: space pause, click to continue after a `pause`, left/right -previous/next play, `,`/`.` step a frame, home/end, up/down speed, B GPU/CPU, -L loop, G guides (bounding boxes, origins and the scene's axes, with scene -coordinates and the pointer's); drag and wheel to look around, R to reset -the view. +Keys: click, space or page down for the next step of a scene that pauses +(space plays and pauses one that does not), page up back a step, `]`/`[` +next/previous slide, P play/pause, left/right previous/next play, `,`/`.` +step a frame, home/end, up/down speed, B GPU/CPU, L loop, G guides +(bounding boxes, origins and the scene's axes, with scene coordinates and +the pointer's); drag and wheel to look around, R to reset the view. - `scenes/intro.zig`, compiled: shapes, Pythagoras morphing from one equation to the next, a camera move with an updater swinging an arrow, Typst math and a paragraph. - `scenes/live.zig`, live, presented like slides: a wave of dots whose - height the timeline animates, whose phase is the wall clock, and which - rise to meet the mouse. + height the timeline animates, whose phase runs on while a pause waits, + and which rise to meet the mouse. `build.zig` lists the scenes with the script `zig build test` plays each through (screenshots in `.zig-cache/e2e`). `-Dscene` picks the one `run`, -- cgit v1.3 From bc6fe168278957ad15cf87826c8410e7358e0849 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 16 Nov 2026 23:07:39 -0300 Subject: anim: Event.key, and the talk example runs in a window An Event says its key (abi.Event.key), which the player and the talk example each spelled out by hand; `zig build talk` shows examples/talk.zig in a window on the generic host, its state under .zig-cache, and `zig build talk-lib --watch` beside it reloads every edit in place. Co-Authored-By: Claude Fable 5.2 --- build.zig | 5 +++++ examples/talk.zig | 2 +- src/abi.zig | 5 +++++ src/anim/player.zig | 6 +----- 4 files changed, 12 insertions(+), 6 deletions(-) diff --git a/build.zig b/build.zig index 3739bcf..cb47d8a 100644 --- a/build.zig +++ b/build.zig @@ -267,6 +267,11 @@ pub fn build(b: *Build) void { talk_check.run.addArg("--define"); talk_check.run.addPrefixedDirectoryArg(b.fmt("{s}=", .{define}), talk.addExport(talk_exe, .{ .fps = 30, .frames = frames, .size = .{ 640, 360 } }).frames); } + // `zig build talk` shows it in a window; `zig build talk-lib --watch` + // beside it reloads every edit in place. + const talk_lib = talk.addLibrary(); + b.step("talk", "Run the talk example in a window (reload edits with `zig build talk-lib --watch`)").dependOn(&talk.addRun(talk_lib, .{ .state = ".zig-cache/talk.state" }).step); + b.step("talk-lib", "Build and install the talk example's hot-reloadable library").dependOn(&b.addInstallArtifact(talk_lib, .{}).step); const test_talk = b.step("test-talk", "Play the talk example: steps, back, slides, its slider, a reload mid-wait and its export"); test_talk.dependOn(&talk_check.run.step); test_step.dependOn(&talk_check.run.step); diff --git a/examples/talk.zig b/examples/talk.zig index f2a2d9c..2ad3d70 100644 --- a/examples/talk.zig +++ b/examples/talk.zig @@ -53,7 +53,7 @@ pub fn update(s: *State, in: *const sk.Input) void { for (in.events) |e| switch (e.kind) { // Every click is the presenter's, unless the talk takes it. .mouse_up => ask.next = true, - .key_down => switch (@as(sk.Key, @fromBackingInt(@intCast(@as(u8, @truncate(e.code)))))) { + .key_down => switch (e.key()) { .space, .right, .page_down => ask.next = true, .left, .page_up => ask.back = true, .right_bracket => ask.next_slide = true, diff --git a/src/abi.zig b/src/abi.zig index 7177f14..af106af 100644 --- a/src/abi.zig +++ b/src/abi.zig @@ -114,6 +114,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 diff --git a/src/anim/player.zig b/src/anim/player.zig index 3b0662d..b329714 100644 --- a/src/anim/player.zig +++ b/src/anim/player.zig @@ -71,7 +71,7 @@ pub fn update(s: *State, in: *const sk.Input) void { var ask: anim.Ask = .{}; var mark: enum { none, previous, next } = .none; for (in.events) |e| switch (e.kind) { - .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)) { + .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 { @@ -126,10 +126,6 @@ pub fn update(s: *State, in: *const sk.Input) void { d.update(in, ask, talk, .{}); } -fn key(e: sk.Event) sk.Key { - return @fromBackingInt(@intCast(@as(u8, @truncate(e.code)))); -} - /// 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, .{}); -- cgit v1.3