diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-10 11:27:39 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-12 13:22:02 -0300 |
| commit | 71e534631bf68f33f802d64794340870374b9f69 (patch) | |
| tree | 2a45229ce238a4e2ce355683f0e75a7725d4851a | |
| parent | 00605f7a109845a99f16621b267305a8b995dddc (diff) | |
| download | sketchbook-71e534631bf68f33f802d64794340870374b9f69.tar.gz sketchbook-71e534631bf68f33f802d64794340870374b9f69.zip | |
sketchbook: anim, manim-style scenes as a module (from the game's vecanim), with objects a scene draws itself
The player takes its canvas from the room it has and fits the scene's
frame into it, plays through and quits when exported, and draws vector
objects in runs around custom ones. The renderers' resvg comparison and
the timings come along as `zig build diff` and `zig build bench`; the
comparison's reference is padded to whole blocks rather than squeezed,
which had put Typst text over the limit.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
| -rw-r--r-- | README.md | 204 | ||||
| -rw-r--r-- | build.zig | 150 | ||||
| -rw-r--r-- | src/anim/player.zig | 410 | ||||
| -rw-r--r-- | src/anim/root.zig | 1043 | ||||
| -rw-r--r-- | src/anim/typst.zig | 66 | ||||
| -rw-r--r-- | test/scene_compiled.script | 13 | ||||
| -rw-r--r-- | test/scene_compiled.zig | 34 | ||||
| -rw-r--r-- | test/scene_live.script | 37 | ||||
| -rw-r--r-- | test/scene_live.zig | 38 | ||||
| -rw-r--r-- | test/svg/dashes.svg | 6 | ||||
| -rw-r--r-- | test/svg/fill-rules.svg | 6 | ||||
| -rw-r--r-- | test/svg/gradients.svg | 16 | ||||
| -rw-r--r-- | test/svg/opacity.svg | 7 | ||||
| -rw-r--r-- | test/svg/paths.svg | 8 | ||||
| -rw-r--r-- | test/svg/shapes.svg | 8 | ||||
| -rw-r--r-- | test/svg/strokes.svg | 11 | ||||
| -rw-r--r-- | test/svg/transforms.svg | 13 | ||||
| -rw-r--r-- | test/svg/typst-equation.typ | 3 | ||||
| -rw-r--r-- | test/svg/typst-shapes.typ | 8 | ||||
| -rw-r--r-- | test/svg/typst-text.typ | 5 | ||||
| -rw-r--r-- | test/svg/use.svg | 11 | ||||
| -rw-r--r-- | test/svgview.zig | 78 | ||||
| -rw-r--r-- | tools/bench.zig | 96 | ||||
| -rw-r--r-- | tools/svgdiff.py | 116 | ||||
| -rw-r--r-- | vendor/fonts/README.md | 4 |
25 files changed, 2379 insertions, 12 deletions
@@ -347,7 +347,8 @@ geometry; and `vector.Renderer(.gpu)` or `vector.Renderer(.cpu)`. The CPU backend computes exact coverage and runs anywhere, wasm included. The GPU backend describes one pass (8× MSAA, gradients in a shader): convex fills drawn directly, the rest stencil-then-cover, all batched into layers of -non-overlapping fills, a few draws per layer whatever the shape count. Both are tested against resvg (see `sketches/vecanim` in the game repository). +non-overlapping fills, a few draws per layer whatever the shape count. +Both are tested against resvg (`zig build diff`, below). **GPU work is data.** A sketch describes pipelines (shader code, vertex layout, blend, stencil) and passes (`f.gpu(.{ .image, .pipelines, .draws, @@ -382,6 +383,161 @@ while declared, and the next frame's `input.microphone` holds what it heard Sounds decode with single-file C libraries in `vendor/` (dr_wav, dr_flac, 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 +`sb.addScene` builds the player around it: + +```zig +const std = @import("std"); +const anim = @import("anim"); + +pub const typst_preamble = "#set text(fill: white)"; +pub const scene = anim.Scene(construct); + +fn construct(s: *anim.Builder) void { + const eq = s.typst("$ a^2 + b^2 = c^2 $", .{ .y = 220, .scale = 1.4 }); + const eq2 = s.typst("$ c = sqrt(a^2 + b^2) $", .{ .y = 220, .scale = 1.4 }); + const square = s.rect(.{ .w = 180, .h = 180, .x = -320, .stroke = anim.blue }); + s.play(.{eq.write()}, .{}); + s.play(.{ square.create(), square.rotate(std.math.pi / 4.0) }, .{ .seconds = 1.5 }); + s.play(.{eq.transformInto(eq2)}, .{}); + s.wait(1); + + // Updaters run every frame, on top of the timeline. Their extra + // arguments are bound here, like a closure's captures. + const swing = s.value(0); + s.always(square, wobble, .{swing}); + s.play(.{ swing.to(0.3), anim.camera(.{ .zoom = 1.4 }) }, .{ .ease = anim.ease.outBack }); +} + +fn wobble(now: anim.Now, swing: anim.Value) anim.Pose { + var p = now.pose; + p.rotation += now.value(swing) * @sin(now.t * 4); + return p; +} +``` + +Objects are added (`typst`, `svg`, `rect`, `circle`, `line`, `arrow`, +`polygon`, `custom`) and show in the order they were added; each call +returns a handle. Animations are methods of the handle: `write`, `create`, +`fadeIn`, `fadeOut`, `transformInto`, `move(.{ .x, .y, .scale, .rotation, +.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 +camera zoom 1, the origin in the middle, y down. + +A scene is one of two kinds, which share every call: + +- **Compiled** (`anim.Scene(construct)`): `construct` runs at comptime, + and what it recorded is played once, still at comptime, into keyframes + per object: a `from` and a `to` pose (plain structs), a time span and an + easing. Drawing an instant is a lookup and a `tween.lerp`, then the + object's updaters. The whole timeline is data before the first frame, a + morph can look ahead to where its target ends, a broken scene is a + compile error, and Typst strings are written inline. +- **Live** (`anim.Live(frame, typst)`): `frame(s: *anim.Frame)` runs every + 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. + +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 +scene and a compiled one with the same timeline show the same poses at +every instant. + +**Typst.** `s.typst(source, pose)` takes Typst markup; the scene's +`typst_preamble` goes in front of each (by default a transparent page +that fits its content). The build runs a generator that imports the scene +file, reads `scene.typst_sources`, compiles each with `typst compile` +(cached by content in `.zig-cache/typst`) and embeds the SVGs. Nothing +scans files, and a scene without Typst needs no `typst`. + +**Custom objects** are drawn by the scene's own code with 2D commands +(`sk.draw`, `f.fill`, `f.text`): what is runtime data, a register table, a +memory grid, a code panel. `s.custom(&data, pose)` adds one, where `data` +has `pub fn draw(self: *const T, f: *sk.Frame, at: anim.Placed) void`. It +is an object like the others: the same camera, pose, `play`, `fadeIn`, +`move` and place in the order. + +```zig +const Bar = struct { + level: f32, + + pub fn draw(b: *const Bar, f: *sk.Frame, at: anim.Placed) void { + // In the object's own units, around its origin. + sk.draw.rect(f, .{ .x = -100, .y = -20, .w = 200, .h = 40 }, at.pen(.{ .stroke = .white, .width = 2 })); + sk.draw.rect(f, .{ .x = -100, .y = -20, .w = 200 * b.level, .h = 40 }, at.pen(.{ .fill = .hex(0xf0ac5f) })); + at.text(f, -100, 26, 1.5, "rax", .white); + } +}; + +fn frame(s: *anim.Frame) void { + const bar = s.new(Bar{ .level = 0 }); // lives for this frame + const obj = s.custom(bar, .{ .x = -200 }); + const level = s.value(0); + s.play(.{ obj.fadeIn(), level.to(1) }, .{}); + s.play(.{obj.move(.{ .x = 200, .scale = 1.5 })}, .{}); + bar.level = s.get(level); // after the plays: as it stands now +} +``` + +`at` (`anim.Placed`) is where the object stands: `xf`, its units to +canvas pixels (camera, then pose); `scale`, pixels per unit; `pose` +(`opacity`; `drawn`, 0 to 1 while a `write` or `create` plays, to reveal +by; `highlight`); `stage`, scene units to pixels; `t`; and `value(v)`, +every `Value` now, which is how a compiled scene's custom object (its +data a constant) moves. `at.pen(pen)` is a `sk.draw.Pen` in the object's +units at its opacity, `at.text` and `at.textSize` are `f.text` and +`host.textSize` likewise. Text scales and moves with the object but does +not turn. A custom object has no outline to `transformInto`. + +Vector objects are drawn on the GPU into an image, then the image onto +the canvas; a custom object draws onto the canvas directly. So the +picture is built in runs: the vector objects up to a custom one, that +object's 2D commands, the vector objects after it, and so on, each run +its own image (8x multisampled, at the canvas's size: about 140 MiB of +GPU memory at 1920x1080 and 560 at 3840x2160, so add custom objects next +to each other in the order where it does not matter). Within its `draw`, +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: + +```sh +zig build export -- frames --size 3840x2160 +zig build export -- - --size 1920x1080 --fps 60 | + ffmpeg -f rawvideo -pix_fmt rgba -s 1920x1080 -r 60 -i - -pix_fmt yuv420p scene.mp4 +``` + +A package of scenes is a few lines of `build.zig`: + +```zig +const sb = sketchbook.init(b, .{ .target = target, .optimize = optimize }); +const scene = sb.addScene(.{ .root_source_file = b.path("scenes/intro.zig") }); +_ = scene.app.addSteps(.{ .scripts = &.{b.path("test/intro.script")} }); +``` + +`scene.app` is an app like any other (`run` with hot reload: save the +scene and the animation carries on from the same instant; `lib`, `web`, +`export`, `e2e`), named after the scene file; `.imports` are modules for +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. + ## The host - **Hot reload.** It watches the library file and loads each new build through @@ -458,7 +614,11 @@ stb_vorbis): WAV, FLAC and Ogg Vorbis, chosen by content. for the canvas (`in.window_width`/`height`, and the first canvas): a sketch that sets its canvas to the room exports at any size. An export keeps state files of its own and removes them, so it can run beside a - player. `--export` plays no script. + player. `--export` plays no script. In a release build on an RTX 3050, + an `anim` scene takes 6 ms a frame as raw RGBA and 21 as PNG at + 1920x1080, 19 and 73 at 3840x2160; with ffmpeg encoding x264 from the + pipe, 11 and 41. The PNG encoder is the slow part: pipe, when the frames + are only on their way to a video. - **GPU.** The host's 2D renderer runs on an SDL GPU device, which also runs sketches' GPU passes. Without a GPU it falls back to any renderer. `--profile-gpu` times every upload, dispatch and pass alone on an idle @@ -527,6 +687,7 @@ and returns plain `std.Build` objects: | Call | Returns | | --- | --- | +| `sb.addScene(.{ .root_source_file, .name, .imports })` | an `anim` scene file's player: `.app`, and `.module` and `.typst` (its Typst as SVG) | | `app.addLibrary()` | the hot-reloadable shared library | | `app.addExecutable()` | host and sketch linked into one binary | | `app.addScriptExecutable()` | the same, built in `script_optimize` mode, as `e2e` plays scripts with | @@ -613,11 +774,14 @@ languages. Tools: `glslc` (shaderc, or the Vulkan SDK's) for shaders, for web builds with shaders `naga` (`cargo install naga-cli`; found on PATH or in cargo's -directory), and for `serve`, `miniserve` and `openssl`. This repository's -own tests also run `node` (noise on wasm32, under WASI) and, for `zig build -test-web`, Chrome. +directory), `typst` for scenes with Typst in them, and for `serve`, +`miniserve` and `openssl`. This repository's own tests also run `node` +(noise on wasm32, under WASI), `typst`, `resvg` and `python3` with numpy +and Pillow (the renderers against resvg), `ffmpeg` if there is one, and, +for `zig build test-web`, Chrome. -`sb.modules`, `sb.host_exe` and `sb.probe_exe` are exposed for anything else. +`sb.modules` (`abi`, `sketch`, `host`, `vector`, `scope`, `anim`), +`sb.host_exe` and `sb.probe_exe` are exposed for anything else. Add `.sketchbook = .{ .path = "..." }` to your `build.zig.zon`. ## Known limits @@ -674,3 +838,31 @@ test-web` draws the shape and render cases in headless Chrome, compares them with the native screenshots (`tools/chrome.mjs`), and times 5000 circles a frame (software Canvas2D here: about 12 ms as 5000 shapes, 8 ms batched). + +And the rest: `test/text.zig` (a box of `textSize` under each line), +`test/export.zig` (two builds export the same frames, frame k at k/fps; +the raw stream's length; a video from ffmpeg with as many frames), and the +`anim` player on its two test scenes: the live one checks, pixel by +pixel, that a custom object sits over the vector object added before it +and under the one added after, moves, fades and zooms with the timeline +and camera, on both renderers; the compiled one is also exported at half +size. + +`zig build diff` (part of `test`) renders a corpus (`test/svg`: every +path command, fill rules, joins, caps, dashes, transforms, opacity, +gradients, symbols, and Typst documents) with resvg as the reference, and +with both vector backends through the real host, headless +(`test/svgview.zig`, `tools/svgdiff.py`). Every case is under 0.7 mean +channel error, with no more than 0.01% of pixels off by more than 48; +side-by-side images land in `.zig-cache/svgdiff`. Two details make the +reference fair: resvg samples coverage on four sub-scanlines, so it +renders at 4x and is box-filtered down (padded to whole blocks, not +squeezed); and sizes in `pt` make it round to whole pixels before +scaling, so the harness gives it unit-free sizes. + +`zig build bench` (part of `test`, after the rest) times each Typst +object of the compiled test scene at 1280x720, the drawing filling the +canvas, in release mode, and fails if a simple one (30 shapes) takes 1 ms +to parse and draw: an equation of 8 shapes parses in 0.02 ms, draws on the +CPU in 0.25 ms, and is recorded as a GPU pass in 0.02 ms (the GPU's own +time is not measured). @@ -11,7 +11,8 @@ //! //! or pick the pieces: `app.addLibrary()`, `app.addExecutable()`, //! `app.addWeb(...)`, `app.addRun(...)`, `app.addScript(...)`, -//! `app.addProbe(...)`, `app.addTest(...)`. GPU shaders are GLSL, built by +//! `app.addProbe(...)`, `app.addTest(...)`. `sb.addScene(...)` is the app +//! that plays an `anim` scene file. GPU shaders are GLSL, built by //! `sb.addShaders(...)` into SPIR-V for native hosts and WGSL for the web; //! `sb.addGlslLayouts(...)` and `sb.addGlslc(...)` are its pieces. Each //! returns the ordinary `std.Build` objects, so anything can be extended or @@ -19,8 +20,8 @@ //! //! Tools, found on PATH when a step needs them: `glslc` (shaderc or the //! Vulkan SDK) for any shader, `naga` (`cargo install naga-cli`) only for -//! the web build of a sketch with shaders, and `miniserve` and `openssl` -//! only for `serve`. +//! the web build of a sketch with shaders, `typst` only for a scene with +//! Typst in it, and `miniserve` and `openssl` only for `serve`. const std = @import("std"); const Build = std.Build; const translate_c = @import("translate_c"); @@ -67,7 +68,7 @@ pub fn build(b: *Build) void { }); b.installArtifact(probe); - var sb: Sketchbook = .{ .b = b, .target = target, .optimize = optimize, .modules = .{ .abi = abi, .sketch = sketch, .host = host, .vector = undefined, .scope = undefined }, .host_exe = host_exe, .probe_exe = probe, .web = b.path("web"), .glsl = b.path("src/glsl.zig"), .tools = b.path("tools"), .script_optimize = optimize, .shared = .create(b) }; + var sb: Sketchbook = .{ .b = b, .target = target, .optimize = optimize, .modules = .{ .abi = abi, .sketch = sketch, .host = host, .vector = undefined, .scope = undefined, .anim = undefined }, .host_exe = host_exe, .probe_exe = probe, .web = b.path("web"), .glsl = b.path("src/glsl.zig"), .tools = b.path("tools"), .anim_dir = b.path("src/anim"), .script_optimize = optimize, .shared = .create(b) }; // Vector graphics: built with the same shader step apps use. Both forms // of its shaders are exported, so apps' web builds can swap them too. @@ -86,6 +87,10 @@ pub fn build(b: *Build) void { }; sb.modules.vector = b.addModule("vector", .{ .root_source_file = b.path("src/vector/root.zig"), .imports = vector_imports }); + // manim-style animation: scenes as code, played by `src/anim/player.zig`. + const anim_imports: []const Build.Module.Import = &.{ .{ .name = "sketch", .module = sketch }, .{ .name = "vector", .module = sb.modules.vector } }; + sb.modules.anim = b.addModule("anim", .{ .root_source_file = b.path("src/anim/root.zig"), .imports = anim_imports }); + // Sound scopes: waveform, spectrogram, spectrum and oscilloscope of a // stream of samples, analysed and drawn on the GPU. const scope_layouts = b.createModule(.{ .root_source_file = b.path("src/scope/layouts.zig") }); @@ -114,6 +119,7 @@ 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 }), @@ -179,6 +185,51 @@ pub fn build(b: *Build) void { // `Host.textSize` against the text drawn (test/text.zig). const text = sb.app(.{ .name = "text", .root_source_file = b.path("test/text.zig") }); test_step.dependOn(&text.addScript(text.addExecutable(), b.path("test/text.script"), .{}).step); + // The anim module's player on its test scenes: a live one with a + // 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 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); + + // 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.addArtifactArg(svgview.addExecutable()); + diff.addDirectoryArg(b.path("test/svg")); + diff.addArg(".zig-cache/svgdiff"); + diff.setCwd(b.path(".")); + diff.has_side_effects = true; + b.step("diff", "Compare the CPU and GPU vector renderers with resvg").dependOn(&diff.step); + test_step.dependOn(&diff.step); + + // Timings always in release mode: a debug build measures nothing useful. + const bench = b.addRunArtifact(b.addExecutable(.{ + .name = "bench", + .root_module = b.createModule(.{ + .root_source_file = b.path("tools/bench.zig"), + .target = target, + .optimize = .ReleaseFast, + .imports = &.{ + .{ .name = "vector", .module = sb.modules.vector }, + .{ .name = "abi", .module = abi }, + .{ .name = "anim", .module = sb.modules.anim }, + .{ .name = "scene", .module = compiled.module }, + .{ .name = "typst", .module = compiled.typst }, + }, + }), + })); + bench.has_side_effects = true; + b.step("bench", "Time parsing and drawing a scene's Typst (release mode, must be under 1ms)").dependOn(&bench.step); + // After the tests above, not beside them: it measures time. + for (test_step.dependencies.items) |step| bench.step.dependOn(step); + test_step.dependOn(&bench.step); + // The examples, so they always compile. for ([_][]const u8{ "pen", "flock" }) |example| { test_step.dependOn(&sb.app(.{ .name = example, .root_source_file = b.path(b.fmt("examples/{s}.zig", .{example})) }).addLibrary().step); @@ -380,12 +431,13 @@ pub fn init(b: *Build, options: Options) Sketchbook { .b = b, .target = options.target, .optimize = options.optimize, - .modules = .{ .abi = dep.module("abi"), .sketch = dep.module("sketch"), .host = dep.module("host"), .vector = dep.module("vector"), .scope = dep.module("scope") }, + .modules = .{ .abi = dep.module("abi"), .sketch = dep.module("sketch"), .host = dep.module("host"), .vector = dep.module("vector"), .scope = dep.module("scope"), .anim = dep.module("anim") }, .host_exe = dep.artifact("sketchbook"), .probe_exe = dep.artifact("sketchbook-probe"), .web = dep.path("web"), .glsl = dep.path("src/glsl.zig"), .tools = dep.path("tools"), + .anim_dir = dep.path("src/anim"), .script_optimize = options.script_optimize orelse options.optimize, .shared = shared, }; @@ -423,7 +475,8 @@ pub const Sketchbook = struct { optimize: std.builtin.OptimizeMode, /// `vector`: SVG, cubic geometry, and CPU and GPU renderers. `scope`: /// waveform, spectrogram, spectrum and oscilloscope views of a sound. - modules: struct { abi: *Build.Module, sketch: *Build.Module, host: *Build.Module, vector: *Build.Module, scope: *Build.Module }, + /// `anim`: manim-style scenes as code (see `addScene`). + modules: struct { abi: *Build.Module, sketch: *Build.Module, host: *Build.Module, vector: *Build.Module, scope: *Build.Module, anim: *Build.Module }, /// The generic host: loads and hot-reloads a sketch library. host_exe: *Build.Step.Compile, /// Prints any sketch's state file. @@ -434,6 +487,8 @@ pub const Sketchbook = struct { glsl: Build.LazyPath, /// Build-time tools (`spirv_strip.zig`, `reload_edit.zig`, ...). tools: Build.LazyPath, + /// The `anim` module's player and Typst generator (see `addScene`). + anim_dir: Build.LazyPath, /// The optimize mode of executables that play scripts (`e2e`): Debug /// is slow for per-pixel loops, and that is often the only reason to /// build a script run differently from the rest. @@ -719,6 +774,89 @@ pub const Sketchbook = struct { return copy; } + pub const SceneOptions = struct { + /// The app's name; the scene file's by default (`scenes/intro.zig` + /// is `intro`). + name: ?[]const u8 = null, + /// The scene: a file with `pub const scene = anim.Scene(construct)` + /// or `anim.Live(frame, typst)`. + root_source_file: Build.LazyPath, + /// Imports for the scene file, besides `anim` and `sketch`. + imports: []const Build.Module.Import = &.{}, + }; + + pub const Scene = struct { + /// The player built around the scene: an app like any other + /// (`addSteps`, `addExecutable`, `addScript`, `addExport`). + app: App, + /// The scene file's module. + module: *Build.Module, + /// Its Typst sources as SVG: `find(source) ?[]const u8`. + typst: *Build.Module, + }; + + /// The `anim` player (`src/anim/player.zig`) built around one scene + /// file, whose Typst is compiled here, at build time. + pub fn addScene(sb: Sketchbook, options: SceneOptions) Scene { + const b = sb.b; + const imports = b.allocator.alloc(Build.Module.Import, options.imports.len + 2) catch @panic("OOM"); + imports[0] = .{ .name = "anim", .module = sb.modules.anim }; + imports[1] = .{ .name = "sketch", .module = sb.modules.sketch }; + @memcpy(imports[2..], options.imports); + const scene = b.createModule(.{ .root_source_file = options.root_source_file, .imports = imports }); + const typst = sb.addTypst(scene); + return .{ + .app = sb.app(.{ + .name = options.name orelse std.fs.path.stem(fileName(options.root_source_file)), + .root_source_file = sb.anim_dir.path(b, "player.zig"), + .imports = &.{ + .{ .name = "vector", .module = sb.modules.vector }, + .{ .name = "anim", .module = sb.modules.anim }, + .{ .name = "scene", .module = scene }, + .{ .name = "typst", .module = typst }, + }, + }), + .module = scene, + .typst = typst, + }; + } + + /// Compiles the Typst sources a scene declares (`scene.typst_sources`), + /// after its `typst_preamble`, with the `typst` CLI, and returns the + /// module the player finds them in (see `src/anim/typst.zig`). `scene` + /// is the scene file's module. A scene without Typst runs no `typst`. + pub fn addTypst(sb: Sketchbook, scene: *Build.Module) *Build.Module { + const b = sb.b; + const tool = b.addExecutable(.{ + .name = "typst-scene", + .root_module = b.createModule(.{ + .root_source_file = b.addWriteFiles().add("typst_scene.zig", + \\const std = @import("std"); + \\const scene = @import("scene"); + \\pub fn main(init: std.process.Init) !void { + \\ var args = init.minimal.args.iterate(); + \\ _ = args.skip(); + \\ const out = args.next().?; + \\ const cache = args.next().?; + \\ try @import("typst").generate(scene, scene.scene.typst_sources, init.arena.allocator(), init.io, out, cache); + \\} + ), + .target = b.graph.host, + .imports = &.{ + .{ .name = "typst", .module = b.createModule(.{ .root_source_file = sb.anim_dir.path(b, "typst.zig") }) }, + .{ .name = "scene", .module = scene }, + }, + }), + }); + const run = b.addRunArtifact(tool); + const dir = run.addOutputDirectoryArg("typst"); + // A cache that outlives the build cache's own entries: the local + // .zig-cache, relative to the project root. + run.setCwd(b.path(".")); + run.addArg(".zig-cache/typst"); + return b.createModule(.{ .root_source_file = dir.path(b, "typst.zig") }); + } + pub fn app(sb: Sketchbook, options: App.Options) App { const imports = sb.b.allocator.alloc(Build.Module.Import, options.imports.len + 1) catch @panic("OOM"); imports[0] = .{ .name = "sketch", .module = sb.modules.sketch }; diff --git a/src/anim/player.zig b/src/anim/player.zig new file mode 100644 index 0000000..bac5178 --- /dev/null +++ b/src/anim/player.zig @@ -0,0 +1,410 @@ +//! 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). +//! +//! space pause / play left/right previous / next play +//! click continue after a pause (`s.pause()` in the scene) +//! ,/. step back / ahead home/end start / end +//! up/down speed B GPU or CPU renderer +//! G guides: boxes, origins and axes, in scene units +//! 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. +const std = @import("std"); +const sk = @import("sketch"); +const vector = @import("vector"); +const anim = @import("anim"); +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 scene's frame, in scene units: what shows at camera zoom 1. +pub const width = 1280; +pub const height = 720; + +pub const State = struct { + t: f32 = 0, + playing: bool = true, + speed: f32 = 1, + 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. + press: [2]f32 = .{ 0, 0 }, + guides: bool = false, +}; + +pub const Session = struct { + /// A renderer per run of vector objects between custom ones (`paint`). + gpu: std.ArrayList(vector.Renderer(.gpu)) = .empty, + cpu: std.ArrayList(vector.Renderer(.cpu)) = .empty, + /// Drawings by what they look like (`Object.id`), built on first use and + /// dropped on reload, since the code that builds them may have changed. + /// Their memory is the host's, kept across reloads. + arena: ?std.heap.ArenaAllocator = null, + drawings: std.AutoHashMapUnmanaged(u64, Built) = .empty, + /// Smoothed time to record a frame, and its shape count. + 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); + defer arena.deinit(); + const shot = scene.shot(arena.allocator(), .{ .t = s.t }) catch return; + 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; + }, + .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), + .b => s.backend = if (s.backend == .gpu) .cpu else .gpu, + .g => s.guides = !s.guides, + .l => s.looping = !s.looping, + .r => s.view = .{}, + else => {}, + }, + .mouse_down => if (e.code == 1) { + s.dragging = true; + s.press = .{ e.x, e.y }; + }, + .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); + s.dragging = false; + }, + .cancel => s.dragging = false, + .mouse_move => if (s.dragging) s.view.pan(.{ .x = e.x - in.mouse_x, .y = e.y - in.mouse_y }), + .wheel => s.view.zoomAt(e, e.wheel(), .{ .min = 0.2, .max = 20 }), + else => {}, + }; +} + +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; +} + +fn previousMark(t: f32, shot: anim.Shot) f32 { + var best: f32 = 0; + for (shot.marks) |m| if (m < t - 0.25) { + best = m; + }; + return best; +} + +fn nextMark(t: f32, shot: anim.Shot) f32 { + for (shot.marks) |m| if (m > t + 0.01) return m; + 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); + return .{ ((in.mouse_x - s.view.x) / s.view.zoom - canvas.w / 2) / k, ((in.mouse_y - s.view.y) / s.view.zoom - canvas.h / 2) / k }; +} + +pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void { + // All the room there is: the window, or the size an export asks for. + const canvas: sk.Rect = .{ .w = @max(@floor(f.in.window_width), 1), .h = @max(@floor(f.in.window_height), 1) }; + f.canvas(@intFromFloat(canvas.w), @intFromFloat(canvas.h)); + const started = f.host.clock(); + const shot = scene.shot(f.scratch, .{ + .t = s.t, + .clock = @floatCast(@mod(@as(f64, @floatFromInt(f.in.now)) / std.time.ns_per_s, 3600)), + .in = f.in, + .pointer = pointer(s, f.in, canvas), + }) catch |err| return f.host.print("scene: {t}", .{err}); + render(s, ss, f, shot, canvas) catch |err| f.host.print("render: {t}", .{err}); + if (f.in.exporting) { + // The frame that shows the end is the last. + if (s.t >= shot.duration) f.quit(); + return; + } + const elapsed: f32 = @floatFromInt(f.host.clock() -| started); + ss.render_ns = if (ss.render_ns == 0) elapsed else ss.render_ns * 0.9 + elapsed * 0.1; + 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(anim.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; + var play: usize = 0; + for (shot.marks, 1..) |m, i| if (m <= s.t) { + play = i; + }; + 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 ""; + 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, + }); + 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.cursor(.arrow); +} diff --git a/src/anim/root.zig b/src/anim/root.zig new file mode 100644 index 0000000..00e9362 --- /dev/null +++ b/src/anim/root.zig @@ -0,0 +1,1043 @@ +//! manim-style animation, written as code. A scene is one file, of one of +//! two kinds, drawn by the same player. +//! +//! **Compiled** (`Scene`): `construct` runs once, at comptime, recording +//! objects and plays, which become keyframes per object (a `from` pose, a +//! `to` pose, a time span and an easing). The whole timeline is data before +//! the first frame, and drawing an instant is a lookup and a `tween.lerp`. +//! Updaters (`always`) add motion on top. +//! +//! pub const scene = anim.Scene(construct); +//! +//! fn construct(s: *anim.Builder) void { +//! const title = s.typst("= Hello", .{ .y = -200 }); +//! s.play(.{title.write()}, .{}); +//! s.always(title, bob, .{20}); +//! s.play(.{anim.camera(.{ .zoom = 1.5 })}, .{ .ease = anim.ease.outBack }); +//! } +//! +//! fn bob(now: anim.Now, height: f32) anim.Pose { +//! var p = now.pose; +//! p.y += height * @sin(now.t * 3); +//! return p; +//! } +//! +//! **Live** (`Live`): `frame` runs every frame, at runtime, with the time +//! and the input. The same calls add objects and play animations, but each +//! `play` takes effect at once, against `s.t`, so the code after it can read +//! and change what shows: updaters are plain code, and a scene can follow +//! the mouse or any runtime data. Its Typst sources sit in a namespace, for +//! the build to find. +//! +//! pub const typst = struct { +//! pub const title = "= Hello"; +//! }; +//! pub const scene = anim.Live(frame, typst); +//! +//! fn frame(s: *anim.Frame) void { +//! const title = s.typst(typst.title, .{ .y = -200 }); +//! s.play(.{title.write()}, .{}); +//! s.pause(); +//! s.pose(title).x = s.pointer[0]; +//! } +//! +//! Both are functions of time (and a live one, of the input too), so +//! scrubbing, seeking and hot reload are free. +//! +//! 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`. +//! +//! **Custom objects** (`s.custom(&data, .{ .x = 100 })`) are drawn by the +//! scene's own code, with `sketch.Frame` commands, in their place among +//! the others: same camera, same pose, same animations (see `Placed`). +const std = @import("std"); +const sk = @import("sketch"); +const vector = @import("vector"); +const tween = sk.tween; +const Drawing = vector.Drawing; + +pub const ease = tween.ease; + +// manim's palette. +pub const blue: u32 = 0x58c4dd; +pub const teal: u32 = 0x5cd0b3; +pub const green: u32 = 0x83c167; +pub const yellow: u32 = 0xf7d96f; +pub const gold: u32 = 0xf0ac5f; +pub const red: u32 = 0xfc6255; +pub const maroon: u32 = 0xc55f73; +pub const purple: u32 = 0x9a72ac; +pub const white: u32 = 0xece6e2; +pub const background: u32 = 0x1c1c1f; + +/// Where an object is and how much of it shows. Every field interpolates. +pub const Pose = struct { + x: f32 = 0, + y: f32 = 0, + scale: f32 = 1, + rotation: f32 = 0, + opacity: f32 = 1, + visible: bool = false, + /// Write/create progress: 0 nothing, 1 complete. + drawn: f32 = 1, + reveal: Reveal = .write, + /// Morph progress into `into`. + morph: f32 = 0, + into: u16 = none, + /// Indicate's glow. + highlight: f32 = 0, + + pub const none = std.math.maxInt(u16); + pub const Reveal = enum { write, create }; +}; + +pub const Camera = struct { + x: f32 = 0, + y: f32 = 0, + zoom: f32 = 1, + rotation: f32 = 0, +}; + +pub const Ease = *const fn (f32) f32; + +pub fn Key(comptime P: type) type { + return struct { + start: f32, + end: f32, + ease: Ease, + lag: f32 = 0, + from: P, + to: P, + + pub fn at(k: @This(), t: f32) P { + return tween.lerp(k.from, k.to, k.ease(tween.progress(t, k.start, k.end))); + } + }; +} + +// --------------------------------------------------------------------------- +// Objects + +pub const Source = union(enum) { + svg: []const u8, + /// Typst source, compiled to SVG at build time. + typst: []const u8, + rect: struct { w: f32, h: f32, radius: f32 = 0 }, + circle: struct { r: f32 }, + line: struct { dx: f32, dy: f32, arrow: bool = false }, + polygon: []const [2]f32, + /// Drawn by the scene's own code (`custom`). + custom: Custom, +}; + +/// An object the scene draws itself with 2D commands (`f.fill`, `sk.draw`, +/// `f.text`): runtime data as a table, a memory grid, a code panel. It is +/// an object like the others: posed, animated and ordered among them. +/// `draw` runs while the frame is painted, when the object shows +/// (`visible`, `opacity` above 0); `ctx` must live until then (a live +/// scene's `s.arena` does). +pub const Custom = struct { + draw: *const fn (ctx: *const anyopaque, f: *sk.Frame, at: Placed) void, + ctx: *const anyopaque, +}; + +/// What a custom object's `draw` gets: where it stands at this instant. +pub const Placed = struct { + /// Scene time, in seconds. + t: f32, + /// The object's pose now. `x`, `y`, `scale` and `rotation` are in `xf` + /// already; `opacity` is for `draw` to honour (`pen` and `text` do), + /// and so are `drawn` (0 to 1 as a `write` or `create` plays: reveal + /// what you like by it) and `highlight` (`indicate`). + pose: Pose, + /// The object's units (its origin where the pose puts it, y down) to + /// canvas pixels: the camera, then the pose. + xf: sk.math.Affine, + /// Canvas pixels per unit of the object: for text sizes. + scale: f32, + /// Scene units to canvas pixels: the camera alone. + stage: sk.math.Affine, + /// Every `Value` of the scene, now. + values: []const f32, + + pub fn value(p: Placed, v: Value) f32 { + return p.values[@backingInt(v)]; + } + + /// `base` in the object's units and at its opacity, for `sk.draw`: + /// `sk.draw.rect(f, r, at.pen(.{ .fill = .white }))`. + pub fn pen(p: Placed, base: sk.draw.Pen) sk.draw.Pen { + var out = base.transformed(p.xf); + if (out.fill) |c| out.fill = p.faded(c); + if (out.stroke) |c| out.stroke = p.faded(c); + return out; + } + + /// `f.text` in the object's units and at its opacity: `x, y` is the + /// line's top left, scale 1 a 13-unit font. Text does not turn: a + /// rotated object's text moves with it and stays level. + pub fn text(p: Placed, f: *sk.Frame, x: f32, y: f32, scale: f32, bytes: []const u8, ink: sk.Color) void { + const at = p.xf.apply(.{ x, y }); + f.text(at[0], at[1], scale * p.scale, bytes, p.faded(ink)); + } + + /// The width and line height `text` covers, in the object's units. + pub fn textSize(p: Placed, f: *sk.Frame, scale: f32, bytes: []const u8) [2]f32 { + const size = f.host.textSize(scale * p.scale, bytes); + return .{ size[0] / p.scale, size[1] / p.scale }; + } + + /// `ink` at the pose's opacity. + pub fn faded(p: Placed, ink: sk.Color) sk.Color { + return ink.alphaFloat(@as(f32, @floatFromInt(ink.a)) / 255 * p.pose.opacity); + } +}; + +pub const Object = struct { + source: Source, + pose: Pose, + /// Styling for primitives; SVGs keep their own. + fill: ?u32 = null, + stroke: ?u32 = null, + width: f32 = 4, + + /// Identifies what the object looks like (not where it is), to cache + /// its drawing by. + pub fn id(o: Object) u64 { + var h: std.hash.Wyhash = .init(0); + h.update(@tagName(o.source)); + switch (o.source) { + .svg, .typst => |text| h.update(text), + .polygon => |points| h.update(std.mem.sliceAsBytes(points)), + .rect => |r| h.update(std.mem.asBytes(&[_]f32{ r.w, r.h, r.radius })), + .circle => |c| h.update(std.mem.asBytes(&c.r)), + .line => |l| h.update(std.mem.asBytes(&[_]f32{ l.dx, l.dy, @floatFromInt(@intFromBool(l.arrow)) })), + .custom => |c| h.update(std.mem.asBytes(&[_]usize{ @intFromPtr(c.draw), @intFromPtr(c.ctx) })), + } + h.update(std.mem.asBytes(&[_]u64{ o.fill orelse 1 << 32, o.stroke orelse 1 << 32 })); + h.update(std.mem.asBytes(&o.width)); + return h.final(); + } +}; + +/// Pose fields to animate towards; the others stay as they are. +pub const Target = struct { + x: ?f32 = null, + y: ?f32 = null, + scale: ?f32 = null, + rotation: ?f32 = null, + opacity: ?f32 = null, + + fn of(fields: anytype) Target { + var t: Target = .{}; + inline for (@typeInfo(@TypeOf(fields)).@"struct".field_names) |name| @field(t, name) = @field(fields, name); + return t; + } + fn apply(t: Target, p: *Pose) void { + inline for (@typeInfo(Target).@"struct".field_names) |name| if (@field(t, name)) |v| { + @field(p, name) = v; + }; + } +}; + +pub const CameraTarget = struct { + x: ?f32 = null, + y: ?f32 = null, + zoom: ?f32 = null, + rotation: ?f32 = null, +}; + +/// A handle to an object added to a scene. +pub const Obj = enum(u16) { + _, + + pub fn write(o: Obj) Animation { + return .{ .write = o }; + } + pub fn create(o: Obj) Animation { + return .{ .create = o }; + } + pub fn fadeIn(o: Obj) Animation { + return .{ .fade_in = o }; + } + pub fn fadeOut(o: Obj) Animation { + return .{ .fade_out = o }; + } + /// Morphs into `other`, which takes over when done. + pub fn transformInto(o: Obj, other: Obj) Animation { + return .{ .transform = .{ .from = o, .to = other } }; + } + /// Towards any of `x`, `y`, `scale`, `rotation`, `opacity`. + pub fn move(o: Obj, to: anytype) Animation { + return .{ .move = .{ .obj = o, .to = .of(to) } }; + } + pub fn scaleTo(o: Obj, scale: f32) Animation { + return .{ .move = .{ .obj = o, .to = .{ .scale = scale } } }; + } + /// By `radians`, from wherever it is. + pub fn rotate(o: Obj, radians: f32) Animation { + return .{ .rotate = .{ .obj = o, .by = radians } }; + } + pub fn indicate(o: Obj) Animation { + return .{ .indicate = o }; + } +}; + +/// A number animated along the timeline, for updaters (or live code) to read. +pub const Value = enum(u16) { + _, + + pub fn to(v: Value, target: f32) Animation { + return .{ .value = .{ .value = v, .to = target } }; + } +}; + +/// Moves the camera towards any of `x`, `y`, `zoom`, `rotation`. +pub fn camera(to: anytype) Animation { + var t: CameraTarget = .{}; + inline for (@typeInfo(@TypeOf(to)).@"struct".field_names) |name| @field(t, name) = @field(to, name); + return .{ .camera = t }; +} + +pub const Animation = union(enum) { + write: Obj, + create: Obj, + fade_in: Obj, + fade_out: Obj, + transform: struct { from: Obj, to: Obj }, + move: struct { obj: Obj, to: Target }, + rotate: struct { obj: Obj, by: f32 }, + indicate: Obj, + camera: CameraTarget, + value: struct { value: Value, to: f32 }, +}; + +/// What an updater sees each frame. +pub const Now = struct { + /// Scene time, in seconds. + t: f32, + /// The object's pose from the timeline (and earlier updaters). + pose: Pose, + values: []const f32, + + pub fn value(n: Now, v: Value) f32 { + return n.values[@backingInt(v)]; + } +}; + +pub const Updater = struct { + obj: Obj, + /// From this time on. + since: f32, + update: *const fn (Now) Pose, +}; + +// --------------------------------------------------------------------------- +// Playing animations, the same for both kinds of scene + +const Play = struct { + start: f32, + seconds: f32, + ease: Ease, + lag: f32, + animations: []const Animation, + + /// `play`'s options: `.seconds` (1, or 2 with a write in it), `.ease` + /// (`ease.smooth`) and `.lag` (0.08). + fn of(start: f32, animations: []const Animation, options: anytype) Play { + const O = @TypeOf(options); + var seconds: f32 = 1; + for (animations) |a| if (a == .write) { + seconds = 2; + }; + if (@hasField(O, "seconds")) seconds = options.seconds; + return .{ + .start = start, + .seconds = seconds, + .ease = if (@hasField(O, "ease")) options.ease else ease.smooth, + .lag = if (@hasField(O, "lag")) options.lag else 0.08, + .animations = animations, + }; + } + + fn key(p: Play, comptime P: type, from: P, to: P, with: ?Ease) Key(P) { + return .{ .start = p.start, .end = p.start + p.seconds, .ease = with orelse p.ease, .lag = p.lag, .from = from, .to = to }; + } +}; + +/// Animations as an array, from a tuple or an array. +fn list(animations: anytype) [count(@TypeOf(animations))]Animation { + var out: [count(@TypeOf(animations))]Animation = undefined; + inline for (animations, 0..) |a, i| out[i] = a; + return out; +} + +fn count(comptime T: type) usize { + return switch (@typeInfo(T)) { + .array => |a| a.len, + else => @typeInfo(T).@"struct".field_names.len, + }; +} + +/// What a play does to one object: the pose it starts from and ends on. +const Change = struct { obj: u16, from: Pose, to: Pose, ease: ?Ease = null }; + +/// The changes `animations`, played together, make to objects standing in +/// their `settled` poses. `buf` needs two per animation. +fn changes(buf: []Change, settled: []const Pose, animations: []const Animation) []Change { + var n: usize = 0; + for (animations) |a| switch (a) { + .write, .create => |o| { + const c = touch(buf, &n, settled, o); + c.from.visible = true; + c.from.drawn = 0; + if (c.from.opacity <= 0) c.from.opacity = 1; + c.from.reveal = if (a == .write) .write else .create; + c.to = c.from; + c.to.drawn = 1; + }, + .fade_in => |o| { + const c = touch(buf, &n, settled, o); + c.from.visible = true; + c.from.drawn = 1; + c.from.opacity = 0; + c.to = c.from; + c.to.opacity = 1; + }, + .fade_out => |o| { + const c = touch(buf, &n, settled, o); + c.to.opacity = 0; + c.to.visible = false; + }, + .transform => |t| { + const c = touch(buf, &n, settled, t.from); + c.from.into = @backingInt(t.to); + c.from.morph = 0; + c.to = c.from; + c.to.morph = 1; + c.to.visible = false; + const d = touch(buf, &n, settled, t.to); + d.from.visible = false; + d.to = d.from; + d.to.visible = true; + d.to.drawn = 1; + d.to.opacity = 1; + }, + .move => |m| m.to.apply(&touch(buf, &n, settled, m.obj).to), + .rotate => |r| touch(buf, &n, settled, r.obj).to.rotation += r.by, + .indicate => |o| { + const c = touch(buf, &n, settled, o); + c.to.scale *= 1.2; + c.to.highlight = 1; + c.ease = ease.thereAndBack; + }, + .camera, .value => {}, + }; + return buf[0..n]; +} + +fn touch(buf: []Change, n: *usize, settled: []const Pose, o: Obj) *Change { + const i = @backingInt(o); + for (buf[0..n.*]) |*c| if (c.obj == i) return c; + buf[n.*] = .{ .obj = i, .from = settled[i], .to = settled[i] }; + n.* += 1; + return &buf[n.* - 1]; +} + +/// Where `animations` leave a camera standing at `view`, if they move it. +fn aim(view: Camera, animations: []const Animation) ?Camera { + var out: ?Camera = null; + for (animations) |a| if (a == .camera) { + var c = out orelse view; + inline for (@typeInfo(CameraTarget).@"struct".field_names) |name| if (@field(a.camera, name)) |v| { + @field(c, name) = v; + }; + out = c; + }; + return out; +} + +/// Adding objects, the same for both kinds of scene (anything with `add`). +const adding = struct { + /// An SVG document, placed by `at`'s fields: `x`, `y`, `scale`, + /// `rotation`, `opacity`, `visible`. + fn svg(s: anytype, bytes: []const u8, at: anytype) Obj { + return s.add(.{ .source = .{ .svg = bytes }, .pose = tween.toward(Pose{}, at, 1) }); + } + /// Typst markup (after the scene's `typst_preamble`), placed like `svg`. + fn typst(s: anytype, source: []const u8, at: anytype) Obj { + return s.add(.{ .source = .{ .typst = source }, .pose = tween.toward(Pose{}, at, 1) }); + } + /// Primitives take their size, `fill`, `stroke`, `width`, and the pose + /// fields, in one literal. + fn rect(s: anytype, spec: anytype) Obj { + return s.add(primitive(.{ .rect = .{ .w = spec.w, .h = spec.h, .radius = number(spec, "radius", 0) } }, spec)); + } + fn circle(s: anytype, spec: anytype) Obj { + return s.add(primitive(.{ .circle = .{ .r = spec.r } }, spec)); + } + fn line(s: anytype, spec: anytype) Obj { + return s.add(primitive(.{ .line = .{ .dx = spec.dx, .dy = spec.dy } }, spec)); + } + fn arrow(s: anytype, spec: anytype) Obj { + return s.add(primitive(.{ .line = .{ .dx = spec.dx, .dy = spec.dy, .arrow = true } }, spec)); + } + /// `.points` is a slice of `[2]f32`, kept by reference. + fn polygon(s: anytype, spec: anytype) Obj { + return s.add(primitive(.{ .polygon = spec.points }, spec)); + } + /// An object drawn by `data.draw(f, placed)` (`f: *sk.Frame`, `placed: + /// Placed`), placed like `svg`. `data` is a pointer, kept: in a live + /// scene to something in `s.arena`, which the code after the plays may + /// still change; in a compiled one to a constant. + fn custom(s: anytype, data: anytype, at: anytype) Obj { + const T = @typeInfo(@TypeOf(data)).pointer.child; + const erased = struct { + fn draw(ctx: *const anyopaque, f: *sk.Frame, placed: Placed) void { + @as(*const T, @ptrCast(@alignCast(ctx))).draw(f, placed); + } + }; + return s.add(.{ .source = .{ .custom = .{ .draw = erased.draw, .ctx = data } }, .pose = tween.toward(Pose{}, at, 1) }); + } +}; + +fn primitive(source: Source, spec: anytype) Object { + var pose: Pose = .{}; + inline for (.{ "x", "y", "scale", "rotation", "opacity", "visible" }) |name| { + if (@hasField(@TypeOf(spec), name)) @field(pose, name) = @field(spec, name); + } + return .{ + .source = source, + .pose = pose, + .fill = if (@hasField(@TypeOf(spec), "fill")) spec.fill else null, + .stroke = if (@hasField(@TypeOf(spec), "stroke")) spec.stroke else null, + .width = number(spec, "width", 4), + }; +} + +fn number(spec: anytype, comptime name: []const u8, default: f32) f32 { + return if (@hasField(@TypeOf(spec), name)) @field(spec, name) else default; +} + +// --------------------------------------------------------------------------- +// Compiled scenes + +/// What `construct` receives. Every method runs at comptime. +pub const Builder = struct { + objects: []const Object = &.{}, + values: []const f32 = &.{}, + plays: []const Play = &.{}, + updaters: []const Updater = &.{}, + stops: []const f32 = &.{}, + /// Where the next play starts. + cursor: f32 = 0, + + pub fn add(b: *Builder, o: Object) Obj { + b.objects = b.objects ++ .{o}; + return @fromBackingInt(@intCast(b.objects.len - 1)); + } + pub const svg = adding.svg; + pub const typst = adding.typst; + pub const rect = adding.rect; + pub const circle = adding.circle; + pub const line = adding.line; + pub const arrow = adding.arrow; + pub const polygon = adding.polygon; + pub const custom = adding.custom; + + pub fn value(b: *Builder, initial: f32) Value { + b.values = b.values ++ .{initial}; + return @fromBackingInt(@intCast(b.values.len - 1)); + } + + /// Runs `animations` (a tuple or an array) together, then moves time + /// past them. + pub fn play(b: *Builder, animations: anytype, options: anytype) void { + const all = list(animations); + const p = Play.of(b.cursor, &all, options); + b.plays = b.plays ++ .{p}; + b.cursor += p.seconds; + } + + pub fn wait(b: *Builder, seconds: f32) void { + 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. + pub fn always(b: *Builder, o: Obj, comptime update: anytype, comptime args: anytype) void { + const bound = struct { + fn call(now: Now) Pose { + return @call(.auto, update, .{now} ++ args); + } + }; + b.updaters = b.updaters ++ .{Updater{ .obj = o, .since = b.cursor, .update = bound.call }}; + } +}; + +/// Runs `construct` at comptime and compiles what it recorded. +pub fn Scene(comptime construct: fn (*Builder) void) type { + @setEvalBranchQuota(10_000_000); + const recorded = comptime blk: { + var b: Builder = .{}; + construct(&b); + break :blk b; + }; + const n = recorded.objects.len; + + // Play the timeline once, at comptime, recording keyframes. + const compiled = comptime blk: { + var poses: [n]Pose = undefined; + for (&poses, recorded.objects) |*p, o| p.* = o.pose; + var values: [recorded.values.len]f32 = recorded.values[0..recorded.values.len].*; + var view: Camera = .{}; + var keys: [n][]const Key(Pose) = @splat(&.{}); + var value_keys: [recorded.values.len][]const Key(f32) = @splat(&.{}); + var camera_keys: []const Key(Camera) = &.{}; + var marks: []const f32 = &.{}; + for (recorded.plays) |play| { + var buf: [2 * play.animations.len]Change = undefined; + for (changes(&buf, &poses, play.animations)) |c| { + const k = play.key(Pose, c.from, c.to, c.ease); + keys[c.obj] = keys[c.obj] ++ .{k}; + poses[c.obj] = k.at(k.end); + } + for (play.animations) |a| if (a == .value) { + const i = @backingInt(a.value.value); + value_keys[i] = value_keys[i] ++ .{play.key(f32, values[i], a.value.to, null)}; + values[i] = a.value.to; + }; + if (aim(view, play.animations)) |to| { + camera_keys = camera_keys ++ .{play.key(Camera, view, to, null)}; + view = to; + } + marks = marks ++ .{play.start}; + } + break :blk .{ .keys = keys, .value_keys = value_keys, .camera_keys = camera_keys, .marks = marks }; + }; + 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].*; + const frozen_marks = compiled.marks[0..compiled.marks.len].*; + const typst_list = comptime blk: { + var out: []const []const u8 = &.{}; + for (recorded.objects) |o| if (o.source == .typst) { + out = out ++ .{o.source.typst}; + }; + break :blk out[0..out.len].*; + }; + + return struct { + pub const objects: []const Object = &frozen_objects; + pub const initial_values: []const f32 = &frozen_values; + pub const updaters: []const Updater = &frozen_updaters; + pub const keys: [n][]const Key(Pose) = frozen_keys; + pub const value_keys = frozen_value_keys; + 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; + + /// The scene at `now`, for the player. + pub fn shot(arena: std.mem.Allocator, now: Instant) !Shot { + const poses = try arena.alloc(Pose, n); + const morphs = try arena.alloc(Morph, n); + for (poses, morphs, 0..) |*p, *m, i| { + p.* = pose(i, now.t); + if (p.into != Pose.none) if (key(i, now.t)) |k| { + 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 }; + } + + /// The key shaping object `i` at `t`: the last one to have started. + pub fn key(i: usize, t: f32) ?Key(Pose) { + return latest(Pose, keys[i], t); + } + + /// Every value at `t`. + pub fn values(t: f32) [frozen_values.len]f32 { + var out = frozen_values; + for (&out, value_keys) |*v, own| if (latest(f32, own, t)) |k| { + v.* = k.at(t); + }; + return out; + } + + /// Where object `i` is at `t`: the timeline, then its updaters. + pub fn pose(i: usize, t: f32) Pose { + var p = if (key(i, t)) |k| k.at(t) else objects[i].pose; + if (updaters.len > 0) { + const now_values = values(t); + for (updaters) |u| if (@backingInt(u.obj) == i and t >= u.since) { + p = u.update(.{ .t = t, .pose = p, .values = &now_values }); + }; + } + return p; + } + + /// The camera at `t`. + pub fn view(t: f32) Camera { + return if (latest(Camera, camera_keys, t)) |k| k.at(t) else .{}; + } + }; +} + +fn latest(comptime P: type, keys: []const Key(P), t: f32) ?Key(P) { + var found: ?Key(P) = null; + for (keys) |k| { + if (k.start > t) break; + found = k; + } + return found; +} + +/// The drawing of an object, centered on its origin, in pixels at scale 1. +/// `compiled` has `find(source) ?[]const u8` for Typst objects' SVGs. +pub fn build(arena: std.mem.Allocator, o: Object, compiled: anytype) !Drawing { + const document: ?[]const u8 = switch (o.source) { + .svg => |bytes| bytes, + .typst => |source| compiled.find(source) orelse return error.TypstNotCompiled, + .custom => return error.CustomHasNoDrawing, + else => null, + }; + if (document) |bytes| { + { + const d = try vector.svg.parse(arena, bytes); + // Keep the SVG's pixel size (Typst's points are 4/3 px), centered. + const s = if (d.view.w > 0) d.width / d.view.w else 1; + const c = d.view.center(); + const shapes = try arena.dupe(Drawing.Shape, d.shapes); + for (shapes) |*shape| shape.transform = vector.geom.Affine.scale(s, s).mul(.translate(-c[0], -c[1])).mul(shape.transform); + var out = d; + out.shapes = shapes; + out.view = .{ .x = -d.view.w * s / 2, .y = -d.view.h * s / 2, .w = d.view.w * s, .h = d.view.h * s }; + return out; + } + } + var b: Drawing.Builder = .init(arena); + var style: Drawing.Style = .{ + .fill = if (o.fill) |c| .{ .color = color(c) } else .none, + .stroke = if (o.stroke) |c| .{ .color = color(c) } else .none, + .stroke_width = o.width, + .cap = .round, + .join = .round, + }; + switch (o.source) { + .rect => |r| try b.rect(.{ .x = -r.w / 2, .y = -r.h / 2, .w = r.w, .h = r.h }, r.radius), + .circle => |c| try b.ellipse(.{ 0, 0 }, c.r, c.r), + .polygon => |pts| { + var points: [64]vector.geom.Vec = undefined; + for (pts[0..@min(pts.len, 64)], 0..) |p, i| points[i] = p; + try b.polyline(points[0..@min(pts.len, 64)], true); + }, + .line => |l| { + const a: vector.geom.Vec = .{ -l.dx / 2, -l.dy / 2 }; + const z: vector.geom.Vec = .{ l.dx / 2, l.dy / 2 }; + try b.lineTo(a, z); + try b.closeSubpath(false); + if (l.arrow) { + try b.endShape(.identity, style); + // The head, filled in the stroke color. + const dir = vector.geom.normalize(z - a); + const n = vector.geom.perp(dir); + const head = @max(o.width * 3, 12); + const back = z - dir * vector.geom.splat(head); + try b.polyline(&.{ z + dir * vector.geom.splat(o.width), back + n * vector.geom.splat(head / 2), back - n * vector.geom.splat(head / 2) }, true); + style.fill = style.stroke; + style.stroke = .none; + } + }, + .svg, .typst, .custom => unreachable, + } + try b.endShape(.identity, style); + const r = @max(extent(o.source), 1); + return b.finish(.{ .x = -r, .y = -r, .w = 2 * r, .h = 2 * r }, 2 * r, 2 * r); +} + +fn extent(s: Source) f32 { + return switch (s) { + .rect => |r| @max(r.w, r.h) / 2, + .circle => |c| c.r, + .line => |l| @max(@abs(l.dx), @abs(l.dy)) / 2, + .polygon => |pts| blk: { + var m: f32 = 0; + for (pts) |p| m = @max(m, @max(@abs(p[0]), @abs(p[1]))); + break :blk m; + }, + .svg, .typst, .custom => 0, + }; +} + +/// `0xRRGGBB`, or `0xRRGGBBAA` when above 24 bits. +pub fn color(c: u32) Drawing.Color { + const rgba: u32 = if (c > 0xffffff) c else (c << 8) | 0xff; + return .{ + @as(f32, @floatFromInt(rgba >> 24)) / 255, + @as(f32, @floatFromInt((rgba >> 16) & 0xff)) / 255, + @as(f32, @floatFromInt((rgba >> 8) & 0xff)) / 255, + @as(f32, @floatFromInt(rgba & 0xff)) / 255, + }; +} + +// --------------------------------------------------------------------------- +// Live scenes + +/// 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; + return struct { + pub const typst_sources: []const []const u8 = &frozen_sources; + + /// The scene at `now`, for the player: `frame`, run once. + 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 }; + } + }; +} + +/// 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. + 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, + /// Where the next play starts. + cursor: f32 = 0, + objects: std.ArrayList(Object) = .empty, + /// Each object's pose after every play so far, and as it shows at `t`. + settled: std.ArrayList(Pose) = .empty, + shown: std.ArrayList(Pose) = .empty, + morphs: std.ArrayList(Morph) = .empty, + values: std.ArrayList(struct { settled: f32, shown: f32 }) = .empty, + settled_view: Camera = .{}, + view: Camera = .{}, + marks: std.ArrayList(f32) = .empty, + stops: std.ArrayList(f32) = .empty, + + pub fn add(s: *Frame, o: Object) Obj { + s.push(&s.objects, o); + s.push(&s.settled, o.pose); + s.push(&s.shown, o.pose); + s.push(&s.morphs, undefined); + return @fromBackingInt(@intCast(s.objects.items.len - 1)); + } + pub const svg = adding.svg; + pub const typst = adding.typst; + pub const rect = adding.rect; + pub const circle = adding.circle; + pub const line = adding.line; + pub const arrow = adding.arrow; + pub const polygon = adding.polygon; + pub const custom = adding.custom; + + pub fn value(s: *Frame, initial: f32) Value { + s.push(&s.values, .{ .settled = initial, .shown = initial }); + return @fromBackingInt(@intCast(s.values.items.len - 1)); + } + + /// Value `v` at `t`. + pub fn get(s: *const Frame, v: Value) f32 { + return s.values.items[@backingInt(v)].shown; + } + + /// How `o` shows at `t`, to change in place. Code runs in order: a later + /// play that has started by `t` sets it again. + pub fn pose(s: *Frame, o: Obj) *Pose { + return &s.shown.items[@backingInt(o)]; + } + + /// The camera at `t`, to change in place, like `pose`. + pub fn camera(s: *Frame) *Camera { + return &s.view; + } + + /// Runs `animations` (a tuple or an array) together from the cursor, as + /// 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); + for (touched) |c| { + const k = p.key(Pose, c.from, c.to, c.ease); + s.settled.items[c.obj] = k.at(k.end); + if (started) s.shown.items[c.obj] = k.at(s.t); + } + // A morph ends where its target settles. + if (started) for (touched) |c| if (c.from.into != Pose.none) { + s.morphs.items[c.obj] = .{ .from = c.from, .to = s.settled.items[c.from.into] }; + }; + for (all) |a| if (a == .value) { + const v = &s.values.items[@backingInt(a.value.value)]; + const k = p.key(f32, v.settled, a.value.to, null); + v.settled = a.value.to; + if (started) v.shown = k.at(s.t); + }; + if (aim(s.settled_view, &all)) |to| { + const k = p.key(Camera, s.settled_view, to, null); + s.settled_view = to; + if (started) s.view = k.at(s.t); + } + s.push(&s.marks, p.start); + s.cursor += p.seconds; + } + + pub fn wait(s: *Frame, seconds: f32) void { + s.cursor += seconds; + } + + /// The player holds here until a click, like a slide. + pub fn pause(s: *Frame) void { + s.push(&s.stops, s.cursor); + } + + /// `data` in the arena, to change until the frame ends: what a custom + /// object draws. + pub fn new(s: *Frame, data: anytype) *@TypeOf(data) { + const kept = s.arena.create(@TypeOf(data)) catch @panic("anim: out of memory"); + kept.* = data; + return kept; + } + + /// 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 { + items.append(s.arena, item) catch @panic("anim: out of memory"); + } +}; + +// --------------------------------------------------------------------------- +// Both kinds, to the player + +/// What a scene is asked for, each frame. +pub const Instant = struct { + /// Scene time, in seconds. + t: f32, + clock: f32 = 0, + in: *const sk.Input = &no_input, + pointer: [2]f32 = .{ 0, 0 }, + + const no_input: sk.Input = .{}; +}; + +/// A scene at one instant: what the player draws. +pub const Shot = struct { + objects: []const Object, + poses: []const Pose, + /// For each object morphing (`pose.into`): the pose its morph started + /// from, and where its target ends up. + morphs: []const Morph, + /// Every `Value`, by handle. + values: []const f32, + camera: Camera, + duration: f32, + /// Start times of every play, for chapter-style seeking. + marks: []const f32, + /// Where the player holds until a click (`pause`). + stops: []const f32, +}; + +pub const Morph = struct { from: Pose, to: Pose }; + +// --------------------------------------------------------------------------- + +fn testScene(s: *Builder) void { + const a = s.circle(.{ .r = 10, .fill = blue }); + const b = s.rect(.{ .w = 20, .h = 20, .x = 100 }); + const k = s.value(0); + s.play(.{a.create()}, .{}); + s.wait(0.5); + s.play(.{ a.move(.{ .x = 50 }), camera(.{ .zoom = 2 }), k.to(10) }, .{ .seconds = 2 }); + s.always(b, follow, .{k}); + s.play(.{a.transformInto(b)}, .{}); +} + +fn follow(now: Now, k: Value) Pose { + var p = now.pose; + p.y = now.value(k); + return p; +} + +test "construct records a timeline that compiles to settling keyframes" { + const S = Scene(testScene); + try std.testing.expectEqual(@as(f32, 4.5), S.duration); + try std.testing.expectEqual(@as(f32, 1), S.pose(0, 1).drawn); + try std.testing.expectApproxEqAbs(@as(f32, 25), S.pose(0, 2.5).x, 1e-3); + try std.testing.expectEqual(@as(f32, 2), S.view(10).zoom); + try std.testing.expectApproxEqAbs(@as(f32, 5), S.values(2.5)[0], 1e-3); + // The updater only runs from where it was added. + try std.testing.expectEqual(@as(f32, 0), S.pose(1, 1).y); + try std.testing.expectEqual(@as(f32, 10), S.pose(1, 4).y); + const mid = S.pose(0, 4.0); + try std.testing.expect(mid.visible and mid.morph > 0 and mid.into == 1); + try std.testing.expect(!S.pose(0, 4.5).visible); + try std.testing.expect(S.pose(1, 4.5).visible); + try std.testing.expectEqual(@as(usize, 3), S.marks.len); +} + +/// `testScene`, live: the updater is a line of code after the plays. +fn liveScene(s: *Frame) void { + const a = s.circle(.{ .r = 10, .fill = blue }); + const b = s.rect(.{ .w = 20, .h = 20, .x = 100 }); + const k = s.value(0); + s.play(.{a.create()}, .{}); + s.wait(0.5); + s.play(.{ a.move(.{ .x = 50 }), camera(.{ .zoom = 2 }), k.to(10) }, .{ .seconds = 2 }); + const since = s.cursor; + s.play(.{a.transformInto(b)}, .{}); + if (s.t >= since) s.pose(b).y = s.get(k); +} + +test "a live scene shows what the compiled one does, at every instant" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const compiled = Scene(testScene); + const live = Live(liveScene, struct {}); + for ([_]f32{ 0, 0.5, 1, 1.7, 2.5, 3.5, 4, 4.5, 9 }) |t| { + const a = try compiled.shot(arena.allocator(), .{ .t = t }); + const b = try live.shot(arena.allocator(), .{ .t = t }); + try std.testing.expectEqualSlices(Pose, a.poses, b.poses); + try std.testing.expectEqualSlices(f32, a.values, b.values); + try std.testing.expectEqual(a.camera, b.camera); + try std.testing.expectEqual(a.duration, b.duration); + try std.testing.expectEqualSlices(f32, a.marks, b.marks); + } +} diff --git a/src/anim/typst.zig b/src/anim/typst.zig new file mode 100644 index 0000000..d9df734 --- /dev/null +++ b/src/anim/typst.zig @@ -0,0 +1,66 @@ +//! Build-time Typst for a scene file. `sb.addTypst` builds a small generator +//! around this file that imports the scene, whose `construct` has already +//! run at comptime and listed its Typst objects (`scene.typst_sources`), +//! compiles each with the `typst` CLI after the scene's `typst_preamble`, +//! and writes a module the player uses to find the SVGs by source: +//! +//! typst.find(source) ?[]const u8 +const std = @import("std"); + +/// Used when the scene declares no `typst_preamble`. +pub const default_preamble = + \\#set page(width: auto, height: auto, margin: 3pt, fill: none) +; + +pub fn generate(comptime SceneFile: type, comptime sources: []const []const u8, gpa: std.mem.Allocator, io: std.Io, out_path: []const u8, cache_path: []const u8) !void { + const preamble: []const u8 = if (@hasDecl(SceneFile, "typst_preamble")) SceneFile.typst_preamble else default_preamble; + const cwd = std.Io.Dir.cwd(); + var out = try cwd.createDirPathOpen(io, out_path, .{}); + defer out.close(io); + var cache = try cwd.createDirPathOpen(io, cache_path, .{}); + defer cache.close(io); + + var table: std.ArrayList(u8) = .empty; + var seen: std.AutoHashMapUnmanaged(u64, void) = .empty; + for (sources) |source| { + const key = std.hash.Wyhash.hash(0, source); + if ((try seen.getOrPut(gpa, key)).found_existing) continue; + const name = try std.fmt.allocPrint(gpa, "{x:0>16}.svg", .{key}); + // Cached by preamble and source together. + const cache_name = try std.fmt.allocPrint(gpa, "{x:0>16}-{s}", .{ std.hash.Wyhash.hash(0, preamble), name }); + const svg = cache.readFileAlloc(io, cache_name, gpa, .limited(64 << 20)) catch try compile(gpa, io, cache, cache_name, preamble, source); + try out.writeFile(io, .{ .sub_path = name, .data = svg }); + try table.print(gpa, " .{{ 0x{x:0>16}, @embedFile(\"{s}\") }},\n", .{ key, name }); + } + const module = try std.fmt.allocPrint(gpa, + \\//! Generated by sketchbook's src/anim/typst.zig: the scene's Typst objects, as SVG. + \\const std = @import("std"); + \\ + \\const table = [_]struct {{ u64, []const u8 }}{{ + \\{s}}}; + \\ + \\/// The SVG compiled from Typst `source`, if the scene declared it. + \\pub fn find(source: []const u8) ?[]const u8 {{ + \\ const key = std.hash.Wyhash.hash(0, source); + \\ for (table) |entry| if (entry[0] == key) return entry[1]; + \\ return null; + \\}} + \\ + , .{table.items}); + try out.writeFile(io, .{ .sub_path = "typst.zig", .data = module }); +} + +/// Runs `typst compile` on `preamble ++ source` and caches the SVG. +fn compile(gpa: std.mem.Allocator, io: std.Io, cache: std.Io.Dir, name: []const u8, preamble: []const u8, source: []const u8) ![]const u8 { + const typ = try std.fmt.allocPrint(gpa, "{s}.typ", .{name}); + try cache.writeFile(io, .{ .sub_path = typ, .data = try std.mem.concat(gpa, u8, &.{ preamble, "\n", source, "\n" }) }); + const result = try std.process.run(gpa, io, .{ + .argv = &.{ "typst", "compile", "--format", "svg", typ, name }, + .cwd = .{ .dir = cache }, + }); + if (result.term != .exited or result.term.exited != 0) { + std.debug.print("typst failed on:\n{s}\n{s}\n", .{ source, result.stderr }); + return error.TypstFailed; + } + return cache.readFileAlloc(io, name, gpa, .limited(64 << 20)); +} diff --git a/test/scene_compiled.script b/test/scene_compiled.script new file mode 100644 index 0000000..3c9ef44 --- /dev/null +++ b/test/scene_compiled.script @@ -0,0 +1,13 @@ +# The compiled test scene, through the player, and exported ({frames}: +# 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 +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. +expect-pixel {frames}/000068.png 400 240 88 196 221 255 1 +expect-pixel {frames}/000068.png 250 235 42 42 48 255 1 +# No bar of controls along the bottom, and the last frame is the end, 3 s. +expect-pixel {frames}/000068.png 8 352 28 28 31 255 +expect-pixel {frames}/000090.png 0 0 28 28 31 255 diff --git a/test/scene_compiled.zig b/test/scene_compiled.zig new file mode 100644 index 0000000..f4a917c --- /dev/null +++ b/test/scene_compiled.zig @@ -0,0 +1,34 @@ +//! The anim module's test scene, compiled: Typst written and morphed, and +//! a custom object whose data is a constant, shown as far as it is `drawn`. +const anim = @import("anim"); +const sk = @import("sketch"); + +pub const typst_preamble = + \\#set page(width: auto, height: auto, margin: 3pt, fill: none) + \\#set text(fill: white, size: 28pt) +; +pub const scene = anim.Scene(construct); + +/// Lines of code in a panel of 320x120 units around its origin. +const Code = struct { + lines: []const []const u8, + + pub fn draw(c: *const Code, f: *sk.Frame, at: anim.Placed) void { + sk.draw.rect(f, .{ .x = -160, .y = -60, .w = 320, .h = 120 }, at.pen(.{ .fill = .hex(0x2a2a30) })); + const count: f32 = @floatFromInt(c.lines.len); + const shown: usize = @intFromFloat(at.pose.drawn * count); + for (c.lines[0..shown], 0..) |line, i| at.text(f, -150, -50 + 24 * @as(f32, @floatFromInt(i)), 1.5, line, .white); + } +}; +const code: Code = .{ .lines = &.{ "mov rax, 1", "add rax, rbx", "ret" } }; + +fn construct(s: *anim.Builder) void { + const pythagoras = s.typst("$ a^2 + b^2 = c^2 $", .{ .y = -200 }); + const solved = s.typst("$ c = sqrt(a^2 + b^2) $", .{ .y = -200 }); + const panel = s.custom(&code, .{ .y = 60 }); + const dot = s.circle(.{ .r = 20, .x = 160, .y = 120, .fill = anim.blue }); + s.play(.{ pythagoras.write(), panel.write() }, .{ .seconds = 1 }); + s.play(.{ pythagoras.transformInto(solved), dot.fadeIn() }, .{ .seconds = 1 }); + s.wait(0.5); + s.play(.{anim.camera(.{ .zoom = 1.5 })}, .{ .seconds = 0.5 }); +} diff --git a/test/scene_live.script b/test/scene_live.script new file mode 100644 index 0000000..30b2087 --- /dev/null +++ b/test/scene_live.script @@ -0,0 +1,37 @@ +# The live test scene, through the player. It holds at the pause. +frames 150 +expect t 2 +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 +expect-pixel .zig-cache/anim/live.png 450 360 252 98 85 255 1 +# under the square added after it, +expect-pixel .zig-cache/anim/live.png 725 400 131 193 103 255 1 +# and its bar is as full as the value the timeline moved to 0.5. +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 +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 +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. +click 640 360 +expect playing true +frames 70 +screenshot .zig-cache/anim/live-zoom.png +expect-pixel .zig-cache/anim/live-zoom.png 800 300 30 46 64 255 2 +# Guides draw over everything. +key g +expect guides true +screenshot .zig-cache/anim/live-guides.png diff --git a/test/scene_live.zig b/test/scene_live.zig new file mode 100644 index 0000000..cb21b9b --- /dev/null +++ b/test/scene_live.zig @@ -0,0 +1,38 @@ +//! The anim module's test scene, live: a custom object drawn with 2D +//! commands between two vector objects, on the same timeline and camera. +const anim = @import("anim"); +const sk = @import("sketch"); + +pub const typst = struct { + pub const title = "#text(fill: white, size: 30pt)[registers]"; +}; +pub const scene = anim.Live(frame, typst); + +/// A panel of 200x100 units around its origin, with a label and a bar. +const Panel = struct { + label: []const u8, + /// How much of the bar is full, 0 to 1. + level: f32, + + pub fn draw(p: *const Panel, f: *sk.Frame, at: anim.Placed) void { + sk.draw.rect(f, .{ .x = -100, .y = -50, .w = 200, .h = 100 }, at.pen(.{ .fill = .hex(0x204060) })); + sk.draw.rect(f, .{ .x = -100, .y = 10, .w = 200 * p.level, .h = 40 }, at.pen(.{ .fill = .hex(0xf0ac5f) })); + at.text(f, -92, -42, 1.5, p.label, .white); + } +}; + +fn frame(s: *anim.Frame) void { + const title = s.typst(typst.title, .{ .y = -250 }); + // Added in this order, shown in this order: circle, panel, square. + const under = s.circle(.{ .r = 120, .x = -100, .fill = anim.red }); + const panel = s.new(Panel{ .label = "rax", .level = 0 }); + const table = s.custom(panel, .{ .x = -300 }); + const over = s.rect(.{ .w = 60, .h = 60, .x = 100, .y = 50, .fill = anim.green }); + const level = s.value(0); + s.play(.{ title.fadeIn(), under.fadeIn(), table.fadeIn(), over.fadeIn() }, .{ .seconds = 1 }); + s.play(.{ table.move(.{ .x = 0 }), level.to(0.5) }, .{ .seconds = 1 }); + s.pause(); + s.play(.{ anim.camera(.{ .zoom = 2 }), table.move(.{ .opacity = 0.5 }) }, .{ .seconds = 1 }); + // After the plays: the value as it stands now. + panel.level = s.get(level); +} diff --git a/test/svg/dashes.svg b/test/svg/dashes.svg new file mode 100644 index 0000000..ebd9ce6 --- /dev/null +++ b/test/svg/dashes.svg @@ -0,0 +1,6 @@ +<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 120" width="200" height="120"> + <line x1="10" y1="20" x2="190" y2="20" stroke="#58c4dd" stroke-width="6" stroke-dasharray="20 10"/> + <line x1="10" y1="45" x2="190" y2="45" stroke="#83c167" stroke-width="6" stroke-dasharray="5" stroke-dashoffset="3"/> + <circle cx="60" cy="85" r="28" fill="none" stroke="#fc6255" stroke-width="5" stroke-dasharray="12 6 2 6"/> + <rect x="120" y="60" width="60" height="50" fill="none" stroke="#f7d96f" stroke-width="4" stroke-dasharray="15 5" stroke-linecap="round"/> +</svg> diff --git a/test/svg/fill-rules.svg b/test/svg/fill-rules.svg new file mode 100644 index 0000000..af0e3b8 --- /dev/null +++ b/test/svg/fill-rules.svg @@ -0,0 +1,6 @@ +<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 220 110" width="220" height="110"> + <!-- The same self-intersecting star and nested squares under both rules. --> + <path d="M55 5 L85 95 L10 40 L100 40 L25 95 Z" fill="#fc6255" fill-rule="nonzero"/> + <path d="M165 5 L195 95 L120 40 L210 40 L135 95 Z" fill="#fc6255" fill-rule="evenodd"/> + <path d="M5 100 h40 v8 h-40z M15 102 h20 v4 h-20z" fill="#58c4dd" fill-rule="evenodd"/> +</svg> diff --git a/test/svg/gradients.svg b/test/svg/gradients.svg new file mode 100644 index 0000000..a5f2c81 --- /dev/null +++ b/test/svg/gradients.svg @@ -0,0 +1,16 @@ +<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 240 160" width="240" height="160"> + <defs> + <linearGradient id="lin"><stop offset="0" stop-color="#58c4dd"/><stop offset="1" stop-color="#fc6255"/></linearGradient> + <linearGradient id="diag" x1="0" y1="0" x2="1" y2="1"><stop offset="0%" stop-color="#f7d96f"/><stop offset="50%" stop-color="#83c167"/><stop offset="100%" stop-color="#1c1c1f"/></linearGradient> + <linearGradient id="user" gradientUnits="userSpaceOnUse" x1="10" y1="0" x2="60" y2="0" spreadMethod="reflect"><stop offset="0" stop-color="#ece6e2"/><stop offset="1" stop-color="#9a72ac"/></linearGradient> + <linearGradient id="derived" xlink:href="#lin" gradientTransform="rotate(90 0.5 0.5)"/> + <radialGradient id="rad"><stop offset="0" stop-color="#ffffff"/><stop offset="1" stop-color="#58c4dd" stop-opacity="0.2"/></radialGradient> + <radialGradient id="focus" cx="0.5" cy="0.5" r="0.5" fx="0.3" fy="0.3"><stop offset="0" stop-color="#f7d96f"/><stop offset="1" stop-color="#c55f73"/></radialGradient> + </defs> + <rect x="10" y="10" width="100" height="40" fill="url(#lin)"/> + <rect x="130" y="10" width="100" height="60" fill="url(#diag)"/> + <rect x="10" y="60" width="110" height="30" fill="url(#user)"/> + <rect x="10" y="100" width="50" height="50" fill="url(#derived)"/> + <circle cx="110" cy="125" r="30" fill="url(#rad)"/> + <ellipse cx="190" cy="115" rx="40" ry="35" fill="url(#focus)" stroke="url(#lin)" stroke-width="4"/> +</svg> diff --git a/test/svg/opacity.svg b/test/svg/opacity.svg new file mode 100644 index 0000000..c0d0b8a --- /dev/null +++ b/test/svg/opacity.svg @@ -0,0 +1,7 @@ +<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 120" width="200" height="120"> + <rect x="10" y="10" width="80" height="80" fill="#58c4dd"/> + <circle cx="90" cy="60" r="40" fill="#fc6255" fill-opacity="0.5"/> + <circle cx="150" cy="60" r="40" fill="#83c167" opacity="0.4" stroke="#ece6e2" stroke-width="8" stroke-opacity="0.8"/> + <g opacity="0.6"><rect x="20" y="95" width="160" height="15" fill="#f7d96f"/></g> + <rect x="120" y="20" width="60" height="20" style="fill: rgb(154, 114, 172); fill-opacity: 70%"/> +</svg> diff --git a/test/svg/paths.svg b/test/svg/paths.svg new file mode 100644 index 0000000..173ec9e --- /dev/null +++ b/test/svg/paths.svg @@ -0,0 +1,8 @@ +<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 120" width="200" height="120"> + <!-- Every path command, absolute and relative, with implicit repeats. --> + <path d="M10 10 L60 10 l20 20 H120 v30 h-40 Z" fill="#58c4dd"/> + <path d="M140 10 C160 0 190 30 180 50 S150 80 140 60 Q130 40 150 30 T170 20" fill="none" stroke="#fc6255" stroke-width="3"/> + <path d="M20 80 a30 20 0 1 0 60 0 a30 20 0 1 0 -60 0z" fill="#83c167"/> + <path d="M100 110A40 40 0 0 1 180 110" fill="none" stroke="#f7d96f" stroke-width="4"/> + <path d="M100,70 l10-10 10,10-10,10z" fill="#9a72ac"/> +</svg> diff --git a/test/svg/shapes.svg b/test/svg/shapes.svg new file mode 100644 index 0000000..07aa01a --- /dev/null +++ b/test/svg/shapes.svg @@ -0,0 +1,8 @@ +<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 240 140" width="240" height="140"> + <rect x="10" y="10" width="60" height="40" fill="#58c4dd"/> + <rect x="80" y="10" width="60" height="40" rx="12" fill="#83c167" stroke="#ece6e2" stroke-width="3"/> + <rect x="150" y="10" width="80" height="40" rx="30" ry="10" fill="#9a72ac"/> + <circle cx="40" cy="95" r="30" fill="#fc6255"/> + <ellipse cx="120" cy="95" rx="40" ry="20" fill="#f7d96f"/> + <polygon points="180,70 230,90 210,130 170,120" fill="#5cd0b3" stroke="#1c1c1f" stroke-width="2"/> +</svg> diff --git a/test/svg/strokes.svg b/test/svg/strokes.svg new file mode 100644 index 0000000..6a25a16 --- /dev/null +++ b/test/svg/strokes.svg @@ -0,0 +1,11 @@ +<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 240 160" width="240" height="160"> + <!-- Joins, caps, miter limits and thin lines. --> + <polyline points="10,50 40,10 70,50" fill="none" stroke="#58c4dd" stroke-width="10" stroke-linejoin="miter"/> + <polyline points="90,50 120,10 150,50" fill="none" stroke="#83c167" stroke-width="10" stroke-linejoin="round"/> + <polyline points="170,50 200,10 230,50" fill="none" stroke="#f7d96f" stroke-width="10" stroke-linejoin="bevel"/> + <line x1="20" y1="80" x2="220" y2="80" stroke="#fc6255" stroke-width="12" stroke-linecap="butt"/> + <line x1="20" y1="105" x2="220" y2="105" stroke="#fc6255" stroke-width="12" stroke-linecap="round"/> + <line x1="20" y1="130" x2="220" y2="130" stroke="#fc6255" stroke-width="12" stroke-linecap="square"/> + <polyline points="10,150 120,145 230,150" fill="none" stroke="#ece6e2" stroke-width="6" stroke-miterlimit="1"/> + <line x1="10" y1="157" x2="230" y2="157" stroke="#ece6e2" stroke-width="0.5"/> +</svg> diff --git a/test/svg/transforms.svg b/test/svg/transforms.svg new file mode 100644 index 0000000..0eb7756 --- /dev/null +++ b/test/svg/transforms.svg @@ -0,0 +1,13 @@ +<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 150" width="200" height="150"> + <g transform="translate(50 50)"> + <rect x="-20" y="-20" width="40" height="40" fill="#58c4dd" transform="rotate(30)"/> + </g> + <g transform="translate(140 50) scale(1.5 0.7)"> + <circle r="25" fill="#83c167" stroke="#ece6e2" stroke-width="4"/> + </g> + <rect x="20" y="100" width="40" height="30" fill="#fc6255" transform="skewX(30)"/> + <g transform="matrix(0.8 0.3 -0.3 0.8 130 95)"> + <path d="M0 0 h40 v30 h-40z" fill="#f7d96f"/> + </g> + <rect x="150" y="100" width="30" height="30" fill="#9a72ac" transform="rotate(45 165 115)"/> +</svg> diff --git a/test/svg/typst-equation.typ b/test/svg/typst-equation.typ new file mode 100644 index 0000000..da0c34c --- /dev/null +++ b/test/svg/typst-equation.typ @@ -0,0 +1,3 @@ +#set page(width: auto, height: auto, margin: 6pt, fill: none) +#set text(fill: rgb("#ece6e2"), size: 28pt) +$ integral_0^infinity e^(-x^2) dif x = sqrt(pi) / 2 $ diff --git a/test/svg/typst-shapes.typ b/test/svg/typst-shapes.typ new file mode 100644 index 0000000..b9bcdff --- /dev/null +++ b/test/svg/typst-shapes.typ @@ -0,0 +1,8 @@ +#set page(width: auto, height: auto, margin: 6pt, fill: none) +#stack(dir: ltr, spacing: 8pt, + rect(width: 60pt, height: 30pt, stroke: 2pt + red, fill: blue, radius: 5pt), + circle(radius: 16pt, fill: gradient.linear(red, blue)), + circle(radius: 16pt, fill: gradient.radial(yellow, purple)), + line(length: 60pt, stroke: (paint: green, thickness: 3pt, dash: "dashed")), + polygon(fill: teal, stroke: 1pt + white, (0pt, 20pt), (20pt, 0pt), (40pt, 20pt)), +) diff --git a/test/svg/typst-text.typ b/test/svg/typst-text.typ new file mode 100644 index 0000000..ce6281d --- /dev/null +++ b/test/svg/typst-text.typ @@ -0,0 +1,5 @@ +#set page(width: 300pt, height: auto, margin: 6pt, fill: none) +#set text(fill: rgb("#ece6e2"), size: 12pt) += Vector sketches +The quick brown fox jumps over the lazy dog. *Bold*, _italic_, `mono`, and +Unicode: é ß ñ — “quotes” — 1 ≤ 2 → ∞. diff --git a/test/svg/use.svg b/test/svg/use.svg new file mode 100644 index 0000000..5336f01 --- /dev/null +++ b/test/svg/use.svg @@ -0,0 +1,11 @@ +<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 200 100" width="200" height="100"> + <!-- Symbols and uses, with style inherited from the use element. --> + <defs> + <symbol id="leaf"><path d="M0 0 C20 -20 40 -20 50 0 C40 20 20 20 0 0Z"/></symbol> + <circle id="dot" r="8"/> + </defs> + <use xlink:href="#leaf" x="10" y="30" fill="#83c167"/> + <use href="#leaf" x="70" y="30" fill="#5cd0b3" transform="rotate(20 95 30)"/> + <g fill="#fc6255"><use href="#dot" x="150" y="30"/><use href="#dot" x="175" y="30" fill="#f7d96f"/></g> + <g color="#58c4dd"><rect x="20" y="60" width="160" height="25" fill="currentColor"/></g> +</svg> diff --git a/test/svgview.zig b/test/svgview.zig new file mode 100644 index 0000000..0675c83 --- /dev/null +++ b/test/svgview.zig @@ -0,0 +1,78 @@ +//! svgview: shows one SVG from a list, fitted to its own canvas size, with +//! either renderer. The differential tests drive it headless: set `index` +//! and `backend` from the console, screenshot, compare with resvg. +//! +//! The list is `$SVGVIEW_LIST` (default `svgview.txt`): one `path width +//! height` per line. +const std = @import("std"); +const sk = @import("sketch"); +const vector = @import("vector"); + +pub const name = "svgview"; +pub const width = 512; +pub const height = 512; + +pub const State = struct { + index: u32 = 0, + backend: vector.Backend = .gpu, +}; + +pub const Session = struct { + gpu: ?vector.Renderer(.gpu) = null, + cpu: ?vector.Renderer(.cpu) = null, +}; + +const Entry = struct { path: []const u8, w: u32, h: u32 }; + +fn entry(host: sk.Host, index: u32) ?Entry { + const list = host.readFile(host.env("SVGVIEW_LIST") orelse "svgview.txt"); + var lines = std.mem.tokenizeScalar(u8, list, '\n'); + var i: u32 = 0; + while (lines.next()) |line| : (i += 1) { + if (i != index) continue; + var words = std.mem.tokenizeScalar(u8, line, ' '); + const path = words.next() orelse return null; + const w = std.fmt.parseInt(u32, words.next() orelse return null, 10) catch return null; + const h = std.fmt.parseInt(u32, words.next() orelse return null, 10) catch return null; + return .{ .path = path, .w = w, .h = h }; + } + return null; +} + +pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void { + const e = entry(f.host, s.index) orelse { + f.clear(0x400000); + f.text(8, 8, 2, "no such entry", 0xffffff); + return; + }; + f.canvas(e.w, e.h); + show(s, ss, f, e) catch |err| { + f.clear(0x400000); + f.print(8, 8, 2, 0xffffff, "{s}: {t}", .{ e.path, err }); + }; +} + +fn show(s: *const State, ss: *Session, f: *sk.Frame, e: Entry) !void { + const d = try vector.svg.parse(f.scratch, f.host.readFile(e.path)); + // As resvg -w does: scale to the width, from the top-left corner (the + // height is rounded, so fitting both would drift by a fraction). + const s_ = @as(f32, @floatFromInt(e.w)) / d.view.w; + const place = vector.geom.Affine.scale(s_, s_).mul(.translate(-d.view.x, -d.view.y)); + switch (s.backend) { + .gpu => try render(&ss.gpu, f, d, place, e), + .cpu => try render(&ss.cpu, f, d, place, e), + } +} + +fn render(slot: anytype, f: *sk.Frame, d: vector.Drawing, place: vector.geom.Affine, e: Entry) !void { + if (slot.*) |*r| if (r.width() != e.w or r.height() != e.h) { + r.deinit(f.host); + slot.* = null; + }; + if (slot.* == null) slot.* = try .init(f.session, f.host, e.w, e.h); + const r = &slot.*.?; + // resvg's `--background '#808080'`. + r.begin(f, .{ 128.0 / 255.0, 128.0 / 255.0, 128.0 / 255.0, 1 }); + try r.draw(d, place, 1); + r.present(f, sk.Rect{ .w = @floatFromInt(e.w), .h = @floatFromInt(e.h) }); +} diff --git a/tools/bench.zig b/tools/bench.zig new file mode 100644 index 0000000..faa769e --- /dev/null +++ b/tools/bench.zig @@ -0,0 +1,96 @@ +//! How long a frame of vector graphics takes, per stage, in release mode: +//! parsing the SVG, turning it into polygons and coverage (CPU backend), or +//! into a GPU pass description (GPU backend; the GPU's own time is not +//! measured here). +const std = @import("std"); +const vector = @import("vector"); +const scene = @import("scene").scene; +const typst = @import("typst"); + +const width = 1280; +const height = 720; +const runs = 300; +/// Drawings up to this many shapes count as simple: they must take < 1ms. +const simple_shapes = 30; + +/// Stand-in for `sketch.Host`: the renderers only need images (and to free +/// the GPU backend's paint buffer, which this bench never makes). +const Host = struct { + pub fn newImage(_: Host, _: u32, _: u32) @import("abi").Image { + return @fromBackingInt(@intCast(1)); + } + pub fn freeImage(_: Host, _: @import("abi").Image) void {} + pub fn freeBuffer(_: Host, _: @import("abi").Buffer) void {} +}; + +pub fn main(init: std.process.Init) !void { + const gpa = std.heap.smp_allocator; + const io = init.io; + var failed = false; + std.debug.print("{s:<24} {s:>7} {s:>10} {s:>10} {s:>10} {s:>10}\n", .{ "object", "shapes", "parse", "cpu draw", "gpu record", "cpu total" }); + // Every Typst object of the scene being played (a live scene adds them + // all whatever the time). + var objects_arena: std.heap.ArenaAllocator = .init(gpa); + defer objects_arena.deinit(); + const shot = try scene.shot(objects_arena.allocator(), .{ .t = 0 }); + for (shot.objects, 0..) |object, index| if (object.source == .typst) { + const svg = typst.find(object.source.typst).?; + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + var cpu: vector.Renderer(.cpu) = try .init(gpa, Host{}, width, height); + defer cpu.deinit(Host{}); + var gpu: vector.Renderer(.gpu) = try .init(gpa, Host{}, width, height); + defer gpu.deinit(Host{}); + const Frame = struct { scratch: std.mem.Allocator }; + + var parse_ns: [runs]u64 = undefined; + var cpu_ns: [runs]u64 = undefined; + var gpu_ns: [runs]u64 = undefined; + var shapes: usize = 0; + for (0..runs) |i| { + _ = arena.reset(.retain_capacity); + const t0 = now(io); + const d = try vector.svg.parse(arena.allocator(), svg); + const t1 = now(io); + // Fit to the canvas, as large as it goes: the worst case. + const m = vector.fit(d, .{ .w = width, .h = height }); + cpu.begin(Frame{ .scratch = arena.allocator() }, .{ 0, 0, 0, 1 }); + try cpu.draw(d, m, 1); + const t2 = now(io); + gpu.begin(Frame{ .scratch = arena.allocator() }, .{ 0, 0, 0, 1 }); + try gpu.draw(d, m, 1); + std.mem.doNotOptimizeAway(gpu.target.pass()); + const t3 = now(io); + parse_ns[i] = t1 - t0; + cpu_ns[i] = t2 - t1; + gpu_ns[i] = t3 - t2; + shapes = d.shapes.len; + } + const p = median(&parse_ns); + const c = median(&cpu_ns); + const g = median(&gpu_ns); + std.debug.print("{d:>2} {s:<21} {d:>7} {d:>8.3}ms {d:>8.3}ms {d:>8.3}ms {d:>8.3}ms\n", .{ index, label(object.source.typst), shapes, ms(p), ms(c), ms(g), ms(p + c) }); + if (shapes <= simple_shapes and (p + c > std.time.ns_per_ms or p + g > std.time.ns_per_ms)) failed = true; + }; + std.debug.print("\nup to {d} shapes must parse and draw in under 1ms at {d}x{d}, filling the canvas.\n", .{ simple_shapes, width, height }); + if (failed) return error.TooSlow; +} + +/// The start of a Typst source's first line. +fn label(source: []const u8) []const u8 { + const line = source[0 .. std.mem.indexOfScalar(u8, source, '\n') orelse source.len]; + return line[0..@min(line.len, 21)]; +} + +fn now(io: std.Io) u64 { + return @intCast(std.Io.Timestamp.now(io, .awake).nanoseconds); +} + +fn median(samples: []u64) u64 { + std.mem.sort(u64, samples, {}, std.sort.asc(u64)); + return samples[samples.len / 2]; +} + +fn ms(ns: u64) f64 { + return @as(f64, @floatFromInt(ns)) / std.time.ns_per_ms; +} diff --git a/tools/svgdiff.py b/tools/svgdiff.py new file mode 100644 index 0000000..80e15a9 --- /dev/null +++ b/tools/svgdiff.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Differential test of the vector renderers against resvg. + +Every SVG (and every Typst document, compiled to SVG first) in the corpus is +rendered by resvg as the reference, then by sketchbook's CPU and GPU +backends through the real host, headless. Each result is compared with the +reference, and GPU with CPU; side-by-side images of every case land in the +output directory. + +usage: svgdiff.py SVGVIEW_EXE CORPUS_DIR OUT_DIR +""" +import re +import subprocess +import sys +from pathlib import Path + +import numpy as np +from PIL import Image + +WIDTH = 480 +BACKGROUND = "#808080" +# resvg samples coverage on four sub-scanlines, so thin edges come out in +# quarter steps. Rendering it 4x larger and box-filtering down gives the +# reference exact-enough coverage to hold both renderers to. +SUPERSAMPLE = 4 +# Per case: mean absolute channel error, and the share of pixels whose worst +# channel is off by more than `EDGE` (anti-aliasing differences sit below it). +MEAN_LIMIT = 1.0 +EDGE = 48 +BAD_LIMIT = 0.005 + + +def load(path): + return np.asarray(Image.open(path).convert("RGB"), dtype=np.int16) + + +def compare(a, b): + if a.shape != b.shape: + return float("inf"), 1.0 + diff = np.abs(a - b) + return float(diff.mean()), float((diff.max(axis=2) > EDGE).mean()) + + +def strip(img, ref, ours): + """Reference | ours | difference, amplified.""" + diff = np.clip(np.abs(ref - ours) * 4, 0, 255) + return Image.fromarray(np.concatenate([ref, ours, diff], axis=1).astype(np.uint8)).save(img) + + +def main(): + exe, corpus, out = Path(sys.argv[1]).resolve(), Path(sys.argv[2]), Path(sys.argv[3]) + out.mkdir(parents=True, exist_ok=True) + cases = [] + for source in sorted(corpus.iterdir()): + if source.suffix == ".typ": + svg = out / (source.stem + ".svg") + subprocess.run(["typst", "compile", "--format", "svg", source, svg], check=True) + # Sizes in pt make resvg round to whole pixels before scaling, + # which shifts its picture by a fraction; give it plain units. + text = svg.read_text() + box = re.search(r'viewBox="0 0 ([\d.]+) ([\d.]+)"', text) + text = re.sub(r'width="[\d.]+pt" height="[\d.]+pt"', f'width="{box[1]}" height="{box[2]}"', text, count=1) + svg.write_text(text) + elif source.suffix == ".svg": + svg = source + else: + continue + ref = out / f"{source.stem}-resvg.png" + big = out / f"{source.stem}-resvg-x{SUPERSAMPLE}.png" + subprocess.run(["resvg", "-w", str(WIDTH * SUPERSAMPLE), "--background", BACKGROUND, svg, big], check=True) + hi = Image.open(big).convert("RGB") + # Whole blocks only: a height that is no multiple is padded, not + # squeezed, which would shift every edge below by a fraction. + w, h = WIDTH, -(-hi.size[1] // SUPERSAMPLE) + whole = Image.new("RGB", (w * SUPERSAMPLE, h * SUPERSAMPLE), BACKGROUND) + whole.paste(hi, (0, 0)) + whole.resize((w, h), Image.BOX).save(ref) + cases.append((source.stem, svg.resolve(), ref, w, h)) + + listing = out / "list.txt" + listing.write_text("".join(f"{svg} {w} {h}\n" for _, svg, _, w, h in cases)) + script = out / "render.script" + lines = [] + for i, (stem, *_rest) in enumerate(cases): + for backend in ("gpu", "cpu"): + lines += [f"console set index {i}", f"console set backend {backend}", "frames 2", + f"screenshot {out.resolve()}/{stem}-{backend}.png"] + script.write_text("\n".join(lines) + "\n") + subprocess.run([exe, "--headless", "--fresh", "--state", out / "svgview.state", "--script", script], + check=True, env={"SVGVIEW_LIST": str(listing.resolve()), **__import__("os").environ}) + + failed = [] + print(f"{'case':<18} {'cpu mean':>9} {'cpu bad':>8} {'gpu mean':>9} {'gpu bad':>8} {'gpu~cpu':>8}") + for stem, _svg, ref_path, _w, _h in cases: + ref = load(ref_path) + row = [stem] + results = {} + for backend in ("cpu", "gpu"): + ours = load(out / f"{stem}-{backend}.png") + mean, bad = compare(ref, ours) + results[backend] = (mean, bad) + strip(out / f"{stem}-{backend}-diff.png", ref, ours) + row += [f"{mean:9.3f}", f"{bad * 100:7.2f}%"] + if mean > MEAN_LIMIT or bad > BAD_LIMIT: + failed.append(f"{stem} ({backend})") + mean, _ = compare(load(out / f"{stem}-cpu.png"), load(out / f"{stem}-gpu.png")) + row.append(f"{mean:8.3f}") + print(f"{row[0]:<18} " + " ".join(row[1:])) + print(f"\nlimits: mean < {MEAN_LIMIT}, pixels off by > {EDGE}: < {BAD_LIMIT * 100:.0f}%. Images in {out}") + if failed: + print("FAILED: " + ", ".join(failed)) + sys.exit(1) + + +if __name__ == "__main__": + main() diff --git a/vendor/fonts/README.md b/vendor/fonts/README.md index f86058e..d1bf9d9 100644 --- a/vendor/fonts/README.md +++ b/vendor/fonts/README.md @@ -25,6 +25,10 @@ arbitrary byte boundaries. Pango shapes each supplied string independently; applications still perform wrapping and clipping. Explicit newlines are not a layout API. Other platforms retain SDL's debug-font fallback for now. +`sk_text_measure` lays a string out the same way and returns its advance +width and line height (`Host.textSize`). `SKETCHBOOK_FONT`, in the +environment, names an installed family to put before Go Mono. + Text is rasterized at the renderer's physical pixel density (including logical presentation scale), and texture origins snap to physical pixels. Whole-run textures retain antialiasing and shaping; no scaled 8×8 bitmap text is involved. |
