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. --- examples/vecanim/scenes/live.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'examples') 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; -- 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(-) (limited to 'examples') 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 (limited to 'examples') 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(-) (limited to 'examples') 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(-) (limited to 'examples') 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