diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs index c03c9e95..452ce47a 100644 --- a/crates/cli/src/lib.rs +++ b/crates/cli/src/lib.rs @@ -23,6 +23,8 @@ USAGE: anicraft-cli exec [] [--save ] anicraft-cli new --out [--width W] [--height H] [--fps F] anicraft-cli bench [--layers N] [--shapes N] [--frames N] performance probe (use --release) + anicraft-cli bench --check yes the default scenario against the budgets in + docs/performance.md; fails when one is missed anicraft-cli serve [file|--sample] JSON-lines on stdin/stdout: {\"id\":1,\"cmd\":\"draw.rect\",\"params\":{\"x\":10,\"y\":10,\"w\":50,\"h\":50}} anicraft-cli mcp [file|--sample] Model Context Protocol server on stdin/stdout, @@ -220,9 +222,53 @@ fn round(v: f64) -> f64 { (v * 1000.0).round() / 1000.0 } +/// Timing budgets for the default `bench` scenario (50 layers × 200 shapes × 240 frames, +/// 200k element instances), in release builds: `(key in the bench output, what, limit)`. +/// Keep in step with the table in `docs/performance.md`. Budgets that don't depend on the +/// machine (memory, sharing, file size, culling) are tests instead, run on every PR. +pub const TIME_BUDGETS: &[(&str, &str, f64)] = &[ + ("edit_command_ms", "edit command (ms)", 1.0), + ("undo_ms", "undo (ms)", 1.0), + ("snapshot_clone_us", "document snapshot (µs)", 50.0), + ("evaluate_ms_per_frame", "evaluate a frame (ms)", 4.0), + ("render_1080p_ms_per_frame", "render 1080p (ms)", 16.7), + ("render_zoom400_ms_per_frame", "render at 400% (ms)", 16.7), + ("hit_test_us", "hit test (µs)", 200.0), + ("file.save_ms", "save the 65 MB file (ms)", 500.0), + ("file.load_ms", "load the 65 MB file (ms)", 500.0), +]; + +/// Compares bench output with [`TIME_BUDGETS`]: one row per budget, and the ones missed. +pub fn check_budgets(out: &Value) -> (Vec, Vec) { + let mut rows = Vec::new(); + let mut missed = Vec::new(); + for (key, what, limit) in TIME_BUDGETS { + let value = key.split('.').try_fold(out, |v, k| v.get(k)).and_then(Value::as_f64); + let ok = value.is_some_and(|v| v <= *limit); + if !ok { + missed.push(match value { + Some(v) => format!("{what}: {v} (budget {limit})"), + None => format!("{what}: not measured"), + }); + } + rows.push(json!({"budget": what, "limit": limit, "measured": value, "ok": ok})); + } + (rows, missed) +} + /// Performance probe on a generated stress document. Run in release for meaningful numbers: -/// `cargo run --release -p anicraft-cli -- bench`. +/// `cargo run --release -p anicraft-cli -- bench`. With `--check yes`, the default scenario +/// is compared with [`TIME_BUDGETS`] and a missed budget is an error. pub fn bench(a: &Args) -> Result { + let check = a.flag("check").is_some_and(|v| v == "yes" || v == "true"); + if check { + if cfg!(debug_assertions) { + return Err("bench --check needs a release build: cargo run --release -p anicraft-cli -- bench --check yes".into()); + } + if ["layers", "shapes", "frames"].iter().any(|k| a.flag(k).is_some()) { + return Err("the budgets are for the default scenario; leave out --layers, --shapes and --frames with --check".into()); + } + } use anicraft_doc::{evaluate, sample}; use anicraft_engine::history::document_bytes; use anicraft_render::{View, render}; @@ -295,7 +341,16 @@ pub fn bench(a: &Args) -> Result { "threads": std::thread::available_parallelism().map_or(1, |n| n.get()), "build": if cfg!(debug_assertions) { "debug (use --release for real numbers)" } else { "release" }, }); - serde_json::to_string_pretty(&out).map_err(|e| e.to_string()) + if !check { + return serde_json::to_string_pretty(&out).map_err(|e| e.to_string()); + } + let (rows, missed) = check_budgets(&out); + let report = serde_json::to_string_pretty(&json!({"measured": out, "budgets": rows})).map_err(|e| e.to_string())?; + if missed.is_empty() { + Ok(report) + } else { + Err(format!("{report}\n\nover budget: {}", missed.join("; "))) + } } /// Answers one JSON request. @@ -374,6 +429,62 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// The budgets in docs/performance.md that don't depend on the machine, checked on every + /// build. (Timing budgets are `bench --check yes`, on a known machine.) + #[test] + fn machine_independent_budgets() { + use anicraft_doc::{evaluate, sample}; + use anicraft_engine::history::document_bytes; + // 20 layers × 500 shapes × 120 frames: 100k element instances. + let doc = sample::stress(20, 500, 120); + let instances: usize = doc.timeline(0).layers.iter().flat_map(|l| l.keyframes.iter()).map(|k| k.elements.len()).sum(); + assert_eq!(instances, 100_000); + + // A snapshot (for undo, the render worker, autosave) shares everything: O(1). + let snap = doc.clone(); + assert!(snap.scenes.iter().zip(&doc.scenes).all(|(a, b)| std::sync::Arc::ptr_eq(a, b))); + + // Undo memory per small edit < 16 KB, however large the document. + let mut s = Session::new(doc); + s.execute("layer.select", &json!({"index": 3})).unwrap(); + s.set_frame(30); + let id = s.visible_elements()[0].id.0; + s.execute("element.select", &json!({"ids": [id]})).unwrap(); + s.execute("element.translate", &json!({"dx": 5, "dy": 0})).unwrap(); + let step = s.history().bytes(); + assert!(step < 16 * 1024, "one edit kept {step} bytes of undo history (budget 16 KB)"); + assert!(step * 1000 < document_bytes(&s.doc), "an edit keeps what changed, not the document"); + + // File size: < 400 bytes per element instance (shared paths are written once). + let small = sample::stress(10, 100, 48); + let n: usize = small.timeline(0).layers.iter().flat_map(|l| l.keyframes.iter()).map(|k| k.elements.len()).sum(); + let bytes = format::to_json(&small).unwrap().len(); + assert!(bytes < n * 400, "{} bytes per instance (budget 400)", bytes / n.max(1)); + + // At 400% zoom on the stage centre, off-screen shapes are culled: at most 1/8 drawn. + let dl = evaluate(&small, 5); + let view = anicraft_render::View::stage(&small, 1.0); + let zoomed = anicraft_render::View { transform: anicraft_geom::Affine::translate(-2880.0, -1620.0).mul(&anicraft_geom::Affine::scale(4.0, 4.0)), ..view }; + let (_, st) = anicraft_render::render(&dl, &zoomed).unwrap(); + assert!(st.items >= 1000 && st.drawn * 8 <= st.items, "{} of {} shapes drawn at 400%", st.drawn, st.items); + } + + #[test] + fn budget_check_reads_bench_output() { + let mut out = json!({"edit_command_ms": 0.01, "undo_ms": 0.01, "snapshot_clone_us": 0.4, "evaluate_ms_per_frame": 1.5, + "render_1080p_ms_per_frame": 20.0, "render_zoom400_ms_per_frame": 10.0, "hit_test_us": 50.0, "file": {"save_ms": 100.0}}); + let (rows, missed) = check_budgets(&out); + assert_eq!(rows.len(), TIME_BUDGETS.len()); + assert_eq!(missed, ["render 1080p (ms): 20 (budget 16.7)", "load the 65 MB file (ms): not measured"]); + out["render_1080p_ms_per_frame"] = json!(16.0); + out["file"]["load_ms"] = json!(120.0); + assert!(check_budgets(&out).1.is_empty()); + // Debug builds and custom sizes can't be checked against the budgets. + if cfg!(debug_assertions) { + assert!(run(&["bench".into(), "--check".into(), "yes".into()]).unwrap_err().contains("release")); + } + } + #[test] fn usage_and_errors() { assert!(run(&[]).unwrap().contains("USAGE")); diff --git a/docs/performance.md b/docs/performance.md index 5710b00a..20209495 100644 --- a/docs/performance.md +++ b/docs/performance.md @@ -17,22 +17,42 @@ per-edit and per-undo time, history bytes per step and hit-test time. In the app bar shows render time, shapes drawn and culled, frame-cache size and hit rate, and history memory. -## Budgets (targets) +## Budgets -| Scenario | Budget | Measured 2026-10-28 (release, 32 threads) | -|---|---|---| -| Edit command on a 200k-instance document | < 1 ms | 0.011 ms ✅ | -| Undo / redo | < 1 ms | 0.009 ms ✅ | -| Undo memory per small edit | < 16 KB | 2.7 KB ✅ | -| Document snapshot | < 50 µs | 0.4 µs ✅ | -| Evaluate one frame (200k instances) | < 4 ms | 1.5 ms ✅ | -| Render 1080p, ~10k visible shapes | < 16.7 ms (60 fps) | 16.5 ms ✅ (tight) | -| Render at 400% zoom | < 16.7 ms | 10.9 ms ✅ | -| Hit test | < 200 µs | 51 µs ✅ | -| Save / load 65 MB file | < 500 ms | 118 / 142 ms ✅ | -| UI frame while rendering | never blocked | worker thread ✅ | +The default `bench` scenario: 50 layers × 200 shapes × 240 frames, 200k element instances. -Budgets become CI-enforced once the perf harness runs on a fixed machine (roadmap M2). +| Scenario | Budget | Measured 2026-11-06 (release, 32 threads) | Enforced by | +|---|---|---|---| +| Edit command on a 200k-instance document | < 1 ms | 0.013 ms ✅ | `bench --check` | +| Undo / redo | < 1 ms | 0.009 ms ✅ | `bench --check` | +| Undo memory per small edit | < 16 KB | 2.7 KB ✅ | test, every PR | +| Document snapshot | < 50 µs, shares everything | 0.04 µs ✅ | test (sharing) and `bench --check` | +| Evaluate one frame (200k instances) | < 4 ms | 1.7 ms ✅ | `bench --check` | +| Render 1080p, ~10k visible shapes | < 16.7 ms (60 fps) | **19.5–20.2 ms ❌** | `bench --check` | +| Render at 400% zoom | < 16.7 ms | 11.7 ms ✅ | `bench --check` | +| Shapes drawn at 400% zoom | ≤ 1/8 of the frame's shapes | 5.5% ✅ | test, every PR | +| Hit test | < 200 µs | 52 µs ✅ | `bench --check` | +| File size | < 400 bytes per element instance | 342 ✅ | test, every PR | +| Save / load 65 MB file | < 500 ms | 123 / 146 ms ✅ | `bench --check` | +| UI frame while rendering | never blocked | worker thread ✅ | design (ADR 0002) | + +**The 1080p render is over budget.** On the same machine on 2026-11-06, v0.1.0 measures +18.0–18.9 ms and today's `main` 19.4–20.2 ms (most of the difference came with bitmap fills). +The 16.5 ms recorded on 2026-10-28 was not reproduced. Getting back under 16.7 ms is the +next performance task. + +### How budgets are enforced + +* **Budgets that don't depend on the machine** (undo memory, snapshot sharing, file size, + culling) are a test (`machine_independent_budgets` in `crates/cli`), so the CI gate fails + any PR that breaks them. +* **Timing budgets** are `cargo run --release -p anicraft-cli -- bench --check yes`. It + prints every measurement next to its budget and fails when one is missed. Shared CI + runners vary too much in speed and core count to gate on time, so this runs on a known + machine before a release and after performance work. A dedicated benchmark runner would + let CI run it too. +* The limits live in `TIME_BUDGETS` in `crates/cli/src/lib.rs`; keep that list and this + table in step. ## Decisions diff --git a/docs/roadmap.md b/docs/roadmap.md index cc477578..8bb1eda1 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -18,7 +18,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | Ease of use & safety | **Visual language** (ADR 0008, revised): graphite palette, corners by role (square structure, softened controls, rounder menus and dialogs with soft depth), borders only between layout regions, flat buttons with a visible focus ring, vibrant timeline blocks (mint artwork, violet tweens), sentence-case headings, **collapsible sections with rules** (Preferences, Properties, dock, shortcut sheet), **Lucide icons** stroked as vectors via a new full SVG path reader; click targets ≥ 28 px (tools 40, rows 28, toggles 24); palette contrast, target sizes and "no raw colours or radii" are enforced by tests. Product principles written (`docs/product-principles.md`). Tiered destructive-action confirmations, enforced in the engine (ADR 0004). Unsaved-changes guard on close/new/open. Overwrite checks for saves and exports. "Ctrl+Z to undo" hints. Command palette (Ctrl+K). Shortcut sheet (F1). Right-click menus on stage, frames and layers. Save As (Ctrl+Shift+S). **Shortcut editor** (F1): every menu command, tool and view key can be rebound, given extra keys or unbound; recording asks before taking a key from another action, reserved keys (palette, editor, Preferences, quit, play, Esc, Space, Tab) stay fixed, per-action and global reset; only the changes are saved in preferences, so untouched actions follow new defaults; menus, tooltips and the palette show the keys in effect. | | Platforms & preferences | ADR 0006 platform layer: ⌘ shortcut labels and an AniCraft app menu with a unified title bar on macOS; Exit and Preferences (Ctrl+U) on Windows and Linux; native file dialogs (XDG portal on Linux, with a fallback switch); wgpu with automatic OpenGL fallback; per-OS settings folder. **Preferences** window: interface and data fonts (bundled default or any installed font), interface scale, stage render mode, file dialogs, reset confirmations. Edits render live (fixed the missing-repaint bug). Not yet: native macOS NSMenu, macOS/Linux CI runners. Verified on Windows only so far. | | Stage rendering & build | **Tiled stage** (ADR 0007): 512 px cached tiles, batched per frame with one scene evaluation per frame, look-ahead ring and playback prefetch, scaled older tiles instead of blank areas, pixel-aligned (no seams). **Space-biased build**: debug build 6.9 GB → 1.04 GB, fresh build 44 s, edit rebuild 4–6 s (`docs/development.md`). | -| Scale & performance | Pulled forward from M2: persistent document with snapshot undo (memory-budgeted history, save-point dirty tracking, History panel), background render worker with frame cache and playback look-ahead, band-parallel renderer with culling, compact streaming file format v2, `anicraft-cli bench`. Measured numbers are in `docs/performance.md`. Budgets are not yet CI-enforced. | +| Scale & performance | Pulled forward from M2: persistent document with snapshot undo (memory-budgeted history, save-point dirty tracking, History panel), background render worker with frame cache and playback look-ahead, band-parallel renderer with culling, compact streaming file format v2, `anicraft-cli bench`. Measured numbers are in `docs/performance.md`. Memory, sharing, file-size and culling budgets are a test on every PR; timing budgets are `anicraft-cli bench --check yes` (the 1080p render is over its 16.7 ms budget at about 19.5 ms). | ## Milestones @@ -26,7 +26,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a |---|---|---| | **M0** | Foundations *(this version)* | Workspace + layering; document model; timeline evaluation with classic tweens and easing; CPU oracle renderer; command registry with undo; `.anicraft`; CLI render + JSON-lines; egui shell with stage, tools, timeline, properties, library; `--screenshot`. | | **M1** | Authoring core ✅ *(v0.1.0)* | ~~Free transform tool with handles~~ ✅; ~~subselection and Bézier point editing~~ ✅; ~~Pen and Pencil~~ ✅; ~~Paint bucket / Ink bottle~~ ✅; ~~copy/paste~~ ✅, ~~duplicate, arrange~~ ✅, ~~align~~ ✅ (commands and menus; and the dock's Align panel ✅); ~~onion skin~~ ✅ (basic); ~~frame selection ranges in the timeline (multi-frame insert/remove/move keyframes by drag)~~ ✅ (including between layers); ~~PNG sequence + animated GIF export~~ ✅; ~~keyboard shortcut map editor~~ ✅. | -| **M2** | Model at scale | ~~`Arc` structural sharing (O(changed) undo)~~ done early (ADR 0001); ~~scenes~~ ✅ (ADR 0011); ~~layer folders~~ ✅, ~~guide and motion-guide layers~~ ✅; ~~mask layers~~ ✅; ~~Movie Clip and Button behaviours~~ ✅ (playback; button states and scripting come with M6); ~~group alpha / offscreen compositing~~ ✅; ~~shape tween~~ ✅ (shape hints still to do); motion tween + Motion Editor curves; ~~MCP server~~ ✅; perf budgets (criterion) with CI enforcement; ~~layering check~~ ✅ (`src/architecture_tests.rs`, runs with `cargo test`). | +| **M2** | Model at scale | ~~`Arc` structural sharing (O(changed) undo)~~ done early (ADR 0001); ~~scenes~~ ✅ (ADR 0011); ~~layer folders~~ ✅, ~~guide and motion-guide layers~~ ✅; ~~mask layers~~ ✅; ~~Movie Clip and Button behaviours~~ ✅ (playback; button states and scripting come with M6); ~~group alpha / offscreen compositing~~ ✅; ~~shape tween~~ ✅ (shape hints still to do); motion tween + Motion Editor curves; ~~MCP server~~ ✅; perf budgets ✅ (machine-independent ones gate every PR; timing via `bench --check` on a known machine, CI once a benchmark runner exists; 1080p render currently over budget); ~~layering check~~ ✅ (`src/architecture_tests.rs`, runs with `cargo test`). | | **M3** | GPU stage | wgpu renderer (sparse-strip coverage, tile binning, gradient ramps in a texture atlas) behind a feature flag; per-pixel parity tests vs the CPU oracle; becomes the default stage renderer once parity ≤ 1/255 mean error; 4K playback at 60 fps for 1,000 shapes. | | **M4** | Interchange *(in progress)* | **XFL import** (DOMDocument.xml, symbols, edges/fill styles decoded from the public format descriptions) with a corpus of self-authored files: first slice ✅ (see Files above); ~~SVG import (Import to Stage)~~ ✅, ~~SVG frame export~~ ✅; Lottie export; ~~sprite sheet + JSON~~ ✅; ~~MP4/WebM via ffmpeg pipe~~ ✅. | | **M5** | Rich media | Text engine (shaping via rustybuzz, glyph atlas); ~~bitmap import and bitmap fills~~ ✅; audio layers (symphonia + cpal), waveform display, stream sync; filters (blur, drop shadow, glow, colour matrix) and blend modes on Movie Clips. |