diff --git a/.gitignore b/.gitignore
index b037d9d3..a711a09f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,5 +1,8 @@
# build output
/target/
+# sample plug-ins built by examples/plugins/build.sh (sources are committed, binaries never)
+/examples/plugins/dist/
+/examples/plugins/target/
# generated screenshots and exports (regenerate with --screenshot / anicraft-cli)
/shots/
@@ -12,3 +15,6 @@
*.swp
.DS_Store
Thumbs.db
+
+# parallel milestone worktrees (AGENTS.md › Milestone tracks)
+/.worktrees/
diff --git a/AGENTS.md b/AGENTS.md
index f6ccc090..1ece78e5 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -9,6 +9,7 @@ is written **AniCraft**; machine names are lowercase (`anicraft-*`). Read `docs/
```text
crates/geom L0 Vec2, Affine (decompose/compose), Rect, Path, flattening, hit testing
crates/xml L0 Bounded XML element reader shared by the importers (XFL, SVG)
+crates/plugins L0 Sandboxed WebAssembly plug-ins: wasmi host, ABI v1, limits, registry (ADR 0017)
crates/doc L1 Document model, easing, timeline evaluation, sample scene
crates/text L1 Fonts on this computer, shaping and line layout into outlines (ADR 0012)
crates/render L2 CPU oracle renderer (coverage accumulation, paints, strokes, PNG)
@@ -91,6 +92,18 @@ a new crate needs a row here and in its `LAYERS` table.
Run `git config core.hooksPath scripts/git-hooks` once per clone.
* Branches marked hidden in your local git config (`git config --add anicraft.hidden `)
never leave the machine: `pre-push` refuses them and anything built on them.
+* **Milestone tracks.** Milestones that don't depend on unfinished work run in parallel, one
+ agent per track (`docs/roadmap.md` › Parallel tracks). Each track works in its own git
+ worktree under `.worktrees/
+
+
+
+
+
AniCraft
@@ -16,16 +21,15 @@
A native 2D vector animation editor with timeline, layers, keyframes, classic and shape tweens,
onion skinning, and an egui stage. It runs natively on macOS, Windows, Linux and FreeBSD,
- and in the browser via WebAssembly.
- By the ArtCraft team.
+ and in the browser via WebAssembly. Built by the ArtCraft team.
-
-
-
-
-
+
+
+
+
+
@@ -40,117 +44,157 @@
-> [!NOTE]
-> **ArtCraft is a community of artists from all walks of life.** Painters, photographers,
-> filmmakers, illustrators, designers, animators, hobbyists, and people who picked up a pencil
-> last week. If you make things, you're one of us. **[Come say hi on Discord](https://discord.gg/artcraft).**
-
-
+> [!NOTE]
+> **ArtCraft is a community of artists from all walks of life.** Painters, animators, filmmakers,
+> illustrators, game makers — if you make things, you're one of us. **[Come say hi on Discord](https://discord.gg/artcraft).**
+
+
- Stage, tools, timeline, layers, keyframes, properties and library are where your hands expect them. If you know Adobe Animate or Flash, you already know AniCraft.
-
-
-
⚡ Native and fast
- A pure Rust engine with a deterministic analytic anti-aliasing CPU oracle renderer, GPU-ready via wgpu / egui, and rayon row parallelism. No Electron, no webview, no waiting.
-
-
-
🎞️ Vector tweens
- Classic tweens with easing presets and shape tweens with arbitrary contour morphing (geom::morph). The document is plain data, and the picture at a frame is a pure function evaluate(doc, frame).
-
-
-
🤖 Headless first
- Every action is an engine command. Drive the exact same engine from the UI, the CLI or the JSON-lines agent channel.
-
-
+
+
+
+
Subselection, Pen and Pencil: real Bézier anchors and handles, curve-fitted freehand lines
+
+
+
+
Timeline: frame ranges across layers, keyframes you drag, classic and shape tweens
+
+
+
+
+
+
Free Transform and symbols: scale, rotate and move instances with nested timelines
+
+
+
+
Command palette: every engine command, one search away (Ctrl+K)
+
+
+
+
+
+
Shortcut editor: rebind, add or clear the key for any command or tool (F1)
+
+
+
+
Preferences: fonts, interface scale, stage rendering and confirmations
+
+
-
+## Made in AniCraft
+
+The sample animation, exported as an animated GIF by AniCraft's own renderer from the command line
+(`anicraft-cli gif --sample --out sample.gif --scale 0.5`).
+
+
+
+ Sample animation: classic tweens with easing, symbols with their own timelines, 48 frames at 24 fps
+
## Why AniCraft
-AniCraft is a clean-room, native 2D vector animation studio designed for animators, motion designers,
-and game developers. Built from scratch in pure Rust, it delivers a modern, lightweight, high-performance
-alternative to Adobe Animate with zero runtime bloat:
-
-* **Pure Rust & memory safe**: No webviews, no Electron, and no unsafe code (`unsafe_code = "forbid"`).
-* **Deterministic CPU oracle renderer**: Analytic anti-aliasing via signed-area coverage accumulation, non-zero and even-odd fill rules, linear and radial gradients, round-join strokes, and multi-threaded band rendering.
-* **Non-destructive & live**: Edits render live in the same frame. Layered architecture with structural sharing (`Arc`) keeps undo and history instant and memory-proportional.
-* **Interchange ready**: Open Adobe Animate documents (`.fla`, `.xfl`, XFL folders), import SVG drawings straight to the stage, export PNG frames and sequences, animated GIFs with palette quantization, and SVG vector frames.
+- **Familiar.** Stage, tools, timeline, layers, keyframes, Properties and Library are where your hands
+ expect them. If you know Adobe Animate or Flash, you already know AniCraft.
+- **Fast.** A pure Rust engine with a deterministic, analytic anti-aliasing CPU renderer, band-parallel
+ rendering, a tiled stage and a background render worker. No Electron, no webview, no waiting.
+- **Robust.** No `unsafe` code (`unsafe_code = "forbid"`), no panics on input, every command fuzzed, and
+ undo with structural sharing (`Arc`), so history stays instant and memory-proportional.
+- **Time is a function.** The document is plain data, and the picture at a frame is a pure function,
+ `evaluate(doc, frame)`. Classic tweens with easing presets and shape tweens with contour morphing.
+- **Open.** A documented native format (`.anicraft`, JSON). Opens Adobe Animate documents (`.fla`,
+ `.xfl`, XFL folders), imports SVG to the stage, and exports PNG frames and sequences, animated GIF,
+ SVG frames, sprite sheets, Lottie, and WebM/MP4 through your own ffmpeg.
+- **Agent-native.** Every action is an engine command. Drive the same engine from the UI, the CLI, a
+ JSON-lines channel or the **MCP server**, so Claude and other agents can draw, animate and export.
## Features
-### Stage and Drawing Tools
-* **Selection & Subselection**: Select, move, nudge with arrow keys, anchor and Bézier handle editing on paths (`Subselection (A)`), add and delete points.
-* **Vector Drawing**: Pen (`P`) with smooth handles and corner conversion, Pencil (`Shift+Y`) with Schneider curve fitting and smoothing, Rectangle (with corner radii), Oval, PolyStar, and Line tools.
-* **Free Transform (`Q`)**: Interactive scaling, corner/edge handles with proportional Shift and centre Alt modifiers, and rotation with 15° snapping.
-* **Fills and Strokes**: Paint Bucket (`K`) with smart gap closure detection, Ink Bottle (`S`), solid colors, linear/radial gradients, and stroke styling.
-* **Arrangement & Alignment**: Align left/center/right/top/middle/bottom (with stage alignment support), distribute, rotate 90° CW/CCW, and horizontal/vertical flipping.
+### Stage and drawing tools
+* **Selection & Subselection**: select, move, nudge with arrow keys, anchor and Bézier handle editing on paths (`Subselection (A)`), add and delete points.
+* **Vector drawing**: Pen (`P`) with smooth handles and corner conversion, Pencil (`Shift+Y`) with Schneider curve fitting and smoothing, Rectangle (with corner radii), Oval, PolyStar, Line and Text (`T`).
+* **Free Transform (`Q`)**: interactive scaling, corner/edge handles with proportional Shift and centre Alt modifiers, and rotation with 15° snapping.
+* **Fills and strokes**: Paint Bucket (`K`) with gap closing, Ink Bottle (`S`), solid colours, linear/radial gradients, bitmap fills and stroke styling.
+* **Arrangement & alignment**: align left/center/right/top/middle/bottom (with stage alignment), distribute, rotate 90° CW/CCW, and horizontal/vertical flipping.
-### Timeline & Animation
-* **Layers & Organization**: Normal layers, guide layers, and mask layers (stencil grouping where masked layers clip cleanly under the mask).
-* **Frame Management**: Keyframes (`F6`), blank keyframes (`F7`), frame insertion (`F5`), frame span dragging, multi-frame selection across layers, and cut/copy/paste frames.
-* **Classic & Shape Tweens**: Classic tweens with 8 easing presets and custom ease curves; shape tweens morphing between arbitrary vector contours.
-* **Onion Skinning**: Visual range before and after the playhead for precise in-betweening.
-* **Symbols & Instances**: Graphic symbols with nested timelines, independent loop modes (Loop, Play Once, Single Frame), and first-frame offsets.
+### Timeline and animation
+* **Layers & organization**: normal, guide, motion-guide and mask layers, and nestable layer folders.
+* **Frame management**: keyframes (`F6`), blank keyframes (`F7`), frame insertion (`F5`), span dragging, multi-frame selection across layers, and cut/copy/paste frames.
+* **Classic & shape tweens**: classic tweens with 8 easing presets and custom ease curves; shape tweens morphing between arbitrary vector contours.
+* **Onion skinning**: a visual range before and after the playhead for in-betweening.
+* **Symbols & instances**: graphic symbols with nested timelines and loop modes (Loop, Play Once, Single Frame), movie clips, filters and blend modes, and scenes.
-### Workflow & Customization
-* **Shortcut Editor (`F1`)**: Interactive keymap editor to customize, rebind, or clear any tool or command shortcut.
-* **Command Palette (`Ctrl+K`)**: Quick fuzzy search and execution of all engine commands.
-* **Safety & Recovery**: Tiered confirmation for destructive actions, unsaved changes guards, and non-overwriting untitled imports.
+### Workflow and customization
+* **Shortcut editor (`F1`)**: interactive keymap editor to customize, rebind or clear any tool or command shortcut.
+* **Command palette (`Ctrl+K`)**: quick fuzzy search and execution of all engine commands.
+* **Safety & recovery**: tiered confirmation for destructive actions, unsaved-changes guards, crash-recovery autosave, and non-overwriting untitled imports.
-## Build and run
+## Quick start
```sh
-cargo build # whole workspace
-cargo run # desktop app with the sample animation
-cargo run -- --screenshot shots/now.png # draw ~120 frames, save the window, exit
-cargo test # all crates
+git clone https://github.com/storytold/anicraft
+cd anicraft
+
+cargo run --release # desktop app with the sample animation
+cargo run --release -- --screenshot shots/now.png # draw ~120 frames, save the window, exit
+cargo run --release -p anicraft-cli -- info --sample
+cargo run --release -p anicraft-cli -- render --sample --frame 12 --out frame12.png
+cargo run --release -p anicraft-cli -- render-seq --sample --out-dir frames --scale 0.5
+cargo run --release -p anicraft-cli -- gif --sample --out animation.gif
+cargo run --release -p anicraft-cli -- commands # the command registry as JSON
+cargo run --release -p anicraft-cli -- exec --sample draw.rect '{"x":10,"y":10,"w":80,"h":40}' --save out.anicraft
+cargo run --release -p anicraft-cli -- serve --sample # JSON-lines on stdin/stdout
+cargo test # all crates
```
-## Headless / agents
+The interface typefaces (Inter and JetBrains Mono) come from [storytold/craft-fonts](https://github.com/storytold/craft-fonts),
+an optional build input: `CRAFT_FONTS_DIR="$PWD/../craft-fonts" cargo run --release` (an absolute path). Without it, AniCraft
+uses egui's built-in fonts. See [`docs/development.md`](docs/development.md).
-AniCraft is headless first: every action in the UI is an engine command, accessible through the CLI or over JSON-lines.
+The `serve` protocol takes one JSON request per line, `{"id": 1, "cmd": "timeline.insert_keyframe", "params": {"frame": 10}}`,
+and answers with its status, `{"id": 1, "ok": true, "result": {}, "revision": 7, "frame": 0}`. Send `{"cmd": "quit"}` to exit.
+
+### Use it from Claude Code and other agents
+
+Register the MCP server with Claude Code:
```sh
-cargo run -p anicraft-cli -- info --sample
-cargo run -p anicraft-cli -- render --sample --frame 12 --out frame12.png
-cargo run -p anicraft-cli -- render-seq --sample --out-dir frames --scale 0.5
-cargo run -p anicraft-cli -- gif --sample --out animation.gif --fps 24
-cargo run -p anicraft-cli -- commands # the registry as JSON
-cargo run -p anicraft-cli -- exec --sample draw.rect '{"x":10,"y":10,"w":80,"h":40}' --save out.anicraft
-cargo run -p anicraft-cli -- serve --sample # JSON-lines on stdin/stdout
-cargo run -p anicraft-cli -- mcp --sample # MCP server for AI assistants (docs/mcp.md)
+claude mcp add anicraft -- /path/to/anicraft-cli mcp
```
-The `serve` protocol accepts one JSON request per line:
-```json
-{"id": 1, "cmd": "timeline.insert_keyframe", "params": {"frame": 10}}
-```
-And returns structured status:
-```json
-{"id": 1, "ok": true, "result": {}, "revision": 7, "frame": 0}
-```
-Send `{"cmd": "quit"}` to exit.
+The details, including the server entry for other MCP clients, are in [`docs/mcp.md`](docs/mcp.md).
-## Architecture
+## Status
-The codebase enforces strict downward-only layering:
+> [!IMPORTANT]
+> **Early alpha: not yet for production animation work.** The core document model, vector renderer,
+> egui shell, classic and shape tweens, and the first XFL and SVG imports work; much is still to come.
+
+[**docs/roadmap.md**](docs/roadmap.md) has the honest status by dimension, milestones M0–M8 and what's next.
+
+**What's missing:** motion tweens and the Motion Editor, shape hints, audio layers, ActionScript (frame scripts are counted
+on import but not kept yet, ADR 0013), motion tweens from XFL, a GPU renderer, and macOS and Linux CI runners
+(AniCraft is verified on Windows so far).
+
+**Workspace:** strict downward-only layering, checked by `cargo test`:
```text
crates/geom L0 Vec2, Affine (decompose/compose), Rect, Path, flattening, hit testing
@@ -165,28 +209,19 @@ crates/cli L4 anicraft-cli: info/render/render-seq/commands/exec/run/new/s
src/ L5 egui shell (app, menus, stage, timeline, panels, theme)
```
-No code below `src/` depends on egui, eframe, or windowing libraries.
+No code below `src/` depends on egui, eframe or windowing libraries.
-### Documents
-* [`docs/requirements.md`](docs/requirements.md): Scope, functional requirements, and technology choices
-* [`docs/architecture.md`](docs/architecture.md): Philosophy, crate map, document model, renderer, and engine
-* [`docs/roadmap.md`](docs/roadmap.md): Milestones M0–M8 and current progress
-* [`docs/product-principles.md`](docs/product-principles.md): Design and user experience principles
-* [`docs/development.md`](docs/development.md): Development setup, testing, and build hygiene
-* [`AGENTS.md`](AGENTS.md): Guide for contributors and AI agents
-
-## Status
-
-> [!IMPORTANT]
-> **Status: Early Alpha (Not yet for public consumption).**
-> AniCraft is under active early development. The core document model, vector rendering oracle,
-> egui shell, classic and shape tweens, and initial XFL/SVG imports are functional, but it is not yet
-> ready for production animation work. See [`docs/roadmap.md`](docs/roadmap.md) for milestones M0–M8
-> and honest progress.
+Agent and contributor rules (clean room, the asset policy, no panics in shipped code) are in [`AGENTS.md`](AGENTS.md).
+[`docs/requirements.md`](docs/requirements.md) has the scope, [`docs/architecture.md`](docs/architecture.md) the design,
+[`docs/product-principles.md`](docs/product-principles.md) the design and user experience principles, and
+[`docs/development.md`](docs/development.md) the setup, testing and build hygiene. Every bundled asset is listed
+with its licence in [`ATTRIBUTION.md`](ATTRIBUTION.md).
## Downloads
-On GitHub, the [latest release](https://github.com/storytold/anicraft/releases/latest) has every build listed below, and [all releases](https://github.com/storytold/anicraft/releases) has earlier versions and their notes. `` in the file names is the version number, and `SHA256SUMS.txt` lists a checksum for every file.
+**New to AniCraft?** Download it from the [AniCraft page on getartcraft.com](https://getartcraft.com/apps/anicraft). That's the easiest way to install it.
+
+**Want a specific build or format?** On GitHub, the [latest release](https://github.com/storytold/anicraft/releases/latest) has every build listed below, and [all releases](https://github.com/storytold/anicraft/releases) has earlier versions and their notes. `` in the file names is the version number, and `SHA256SUMS.txt` lists a checksum for every file.
### Windows
@@ -244,8 +279,16 @@ stand on its own.
| | **PdfCraft** | Reading, organizing and protecting PDFs | [GitHub](https://github.com/storytold/pdfcraft) | [Website](https://getartcraft.com/apps/pdfcraft) |
| | **EffectCraft** | Motion graphics and visual effects | [GitHub](https://github.com/storytold/effectcraft) | [Website](https://getartcraft.com/apps/effectcraft) |
| | **DesignCraft** | Page layout and publishing | [GitHub](https://github.com/storytold/designcraft) | [Website](https://getartcraft.com/apps/designcraft) |
-| | **CADCraft** | Computer-aided design and drafting | [GitHub](https://github.com/storytold/cadcraft) | [Website](https://getartcraft.com/apps/cadcraft) |
-| | **AniCraft** | **2D vector animation studio · you are here** | [GitHub](https://github.com/storytold/anicraft) | [Website](https://getartcraft.com/apps/anicraft) |
+| | **FigCraft** | Interface design and prototyping | [GitHub](https://github.com/storytold/figcraft) | [Website](https://getartcraft.com/apps/figcraft) |
+| | **WordCraft** | Word processing and documents | [GitHub](https://github.com/storytold/wordcraft) | [Website](https://getartcraft.com/apps/wordcraft) |
+| | **SoundCraft** | Audio recording and editing | [GitHub](https://github.com/storytold/soundcraft) | [Website](https://getartcraft.com/apps/soundcraft) |
+| | **DeckCraft** | Presentations and slide decks | [GitHub](https://github.com/storytold/deckcraft) | [Website](https://getartcraft.com/apps/deckcraft) |
+| | **CADCraft** | Computer-aided design | [GitHub](https://github.com/storytold/cadcraft) | [Website](https://getartcraft.com/apps/cadcraft) |
+| | **GridCraft** | Spreadsheets and data | [GitHub](https://github.com/storytold/gridcraft) | [Website](https://getartcraft.com/apps/gridcraft) |
+| | **TextureCraft** | 3D texture painting | [GitHub](https://github.com/storytold/texturecraft) | [Website](https://getartcraft.com/apps/texturecraft) |
+| | **Craft Anything** | See how any software works, then build your own | [GitHub](https://github.com/storytold/craft-anything) | [Website](https://getartcraft.com/apps/craft-anything) |
+| | **AniCraft** | **2D vector animation · you are here** | [GitHub](https://github.com/storytold/anicraft) | [Website](https://getartcraft.com/apps/anicraft) |
+| | **SolidCraft** | Parametric 3D CAD by Tangency Labs (community app) | [GitHub](https://github.com/tangency-labs/solidcraft) | |
And [**ArtCraft**](https://getartcraft.com/) itself, our AI image and video studio for artists who want real control.
@@ -271,7 +314,9 @@ And [**ArtCraft**](https://getartcraft.com/) itself, our AI image and video stud
AniCraft
----
+## Star history
+
+[](https://www.star-history.com/?repos=storytold%2Fanicraft&type=date&legend=top-left)
## License and credits
@@ -281,6 +326,9 @@ Copyright (c) 2026 ArtCraft Team and the AniCraft contributors. Required notices
Bundled fonts, icons, images and other assets keep their own open licenses; each one is listed
with its author, source and license in [ATTRIBUTION.md](ATTRIBUTION.md).
+The app icon (an engraved rabbit on AniCraft yellow, `#dac604`) is the owner's original artwork; its
+palette and files are in [`assets/app-icon/`](assets/app-icon/README.md).
+
The ArtCraft name, wordmark and logos in [`docs/brand/`](docs/brand/) are trademarks of the
ArtCraft Team and are not covered by this license. They may be used only unmodified, and only as
part of this repository and AniCraft, under [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt).
diff --git a/assets/app-icon/LICENSE.txt b/assets/app-icon/LICENSE.txt
new file mode 100644
index 00000000..7d1882a9
--- /dev/null
+++ b/assets/app-icon/LICENSE.txt
@@ -0,0 +1,12 @@
+AniCraft app icon (anicraft.svg, anicraft-small.svg and every file derived from them in this
+directory: anicraft-1024.png, anicraft-padded-1024.png, anicraft-macos-512.png, anicraft.ico, hicolor/).
+
+Original artwork made for this project by the project owner, drawn in ArtCraft and vectorised for
+AniCraft (no third-party material). Licensed like the rest of AniCraft, under either of
+
+ * Apache License, Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0)
+ * MIT license (https://opensource.org/licenses/MIT)
+
+at your option.
+
+Regenerate the derived files with scripts/icons.sh.
diff --git a/assets/app-icon/README.md b/assets/app-icon/README.md
new file mode 100644
index 00000000..13bafc11
--- /dev/null
+++ b/assets/app-icon/README.md
@@ -0,0 +1,53 @@
+# AniCraft app icon
+
+**Creature:** an engraved rabbit, AniCraft's mascot.
+
+**Style:** an engraving-style portrait in the Crafting Apps template: a head-and-shoulders portrait on a
+full-bleed field, no frame or roundel, with the body running off the tile.
+
+**Palette** (exactly three colours):
+
+| Colour | Hex | Used for |
+|---|---|---|
+| Ink | `#0b0b0c` | line work and contour |
+| Paper | `#f2f1ee` | the figure (a neutral white, so the rabbit doesn't read as cream on the yellow) |
+| AniCraft colour | `#dac604` | the full-bleed field |
+
+**Tile:** `viewBox="0 0 512 512"`, a rounded square with `rx=112`, the same tile as every Crafting App.
+The art is clipped 6 units inside it (a concentric rounded square, `x=y=6`, `500×500`, `rx=106`), so a
+band of field colour runs round every edge where the rabbit runs off, as on the other icons. The padded files add Apple's transparent margin (tile = 824/1024 of the canvas); Windows
+and Linux use the tile edge to edge.
+
+**Provenance:** the owner's original ArtCraft drawing, vectorised with `trace.py`. `anicraft.svg` is the
+canonical artwork. Licence: see `LICENSE.txt`.
+
+## Files
+
+| File | What | Used by |
+|---|---|---|
+| `anicraft.svg` | master vector (traced at 1600 px, about 275 KB) | source for everything below |
+| `anicraft-small.svg` | lighter vector (traced at 1000 px, about 170 KB) | `hicolor/scalable` |
+| `anicraft-1024.png` | full tile, 1024 px | docs, store listings |
+| `anicraft-padded-1024.png` | tile with Apple's margin, 1024 px | landing pages, store listings |
+| `anicraft-macos-512.png` | tile with Apple's margin, 512 px | runtime Dock icon on macOS (`src/main.rs`) |
+| `anicraft.ico` | Windows icon, 16 to 256 px | `build.rs` (embedded in `anicraft.exe`) |
+| `hicolor//apps/ai.storyteller.anicraft.png` | Linux theme icons, 16 to 512 px; the 256 one is also the runtime icon on Windows and Linux, the 128 one the mark in Help › About (`src/app.rs`) | Linux packaging, the Crafting Apps tables |
+| `hicolor/scalable/apps/ai.storyteller.anicraft.svg` | Linux scalable icon | as above |
+| `trace.py` | traces the 2000 px source drawing into the master SVG | regenerating the vectors |
+
+## How it reaches each OS
+
+- **macOS:** the app sets the Dock / app-switcher icon at runtime (`ViewportBuilder::with_icon`).
+- **Windows:** `build.rs` embeds `anicraft.ico` with `winresource` (taskbar, Start menu, Explorer,
+ Alt-Tab); the runtime icon covers the title bar.
+- **Linux:** the runtime icon covers the window; install `hicolor/` to `share/icons/` for launchers.
+
+## Regenerate
+
+```sh
+# From the 2000 px source drawing (needs numpy, Pillow, SciPy and vtracer; svgo 3.3.2 shrinks the paths):
+python trace.py rabbit.webp master.svg 1600 4 1960 && npx svgo@3.3.2 -p 1 master.svg -o anicraft.svg
+python trace.py rabbit.webp small.svg 1000 4 1960 && npx svgo@3.3.2 -p 1 small.svg -o anicraft-small.svg
+# Every render (needs resvg on PATH and Python with Pillow):
+scripts/icons.sh
+```
diff --git a/assets/app-icon/anicraft-1024.png b/assets/app-icon/anicraft-1024.png
new file mode 100644
index 00000000..349232f7
Binary files /dev/null and b/assets/app-icon/anicraft-1024.png differ
diff --git a/assets/app-icon/anicraft-macos-512.png b/assets/app-icon/anicraft-macos-512.png
new file mode 100644
index 00000000..4e761120
Binary files /dev/null and b/assets/app-icon/anicraft-macos-512.png differ
diff --git a/assets/app-icon/anicraft-padded-1024.png b/assets/app-icon/anicraft-padded-1024.png
new file mode 100644
index 00000000..8114aaa9
Binary files /dev/null and b/assets/app-icon/anicraft-padded-1024.png differ
diff --git a/assets/app-icon/anicraft-small.svg b/assets/app-icon/anicraft-small.svg
new file mode 100644
index 00000000..06f4f216
--- /dev/null
+++ b/assets/app-icon/anicraft-small.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/assets/app-icon/anicraft.ico b/assets/app-icon/anicraft.ico
new file mode 100644
index 00000000..2283e106
Binary files /dev/null and b/assets/app-icon/anicraft.ico differ
diff --git a/assets/app-icon/anicraft.svg b/assets/app-icon/anicraft.svg
new file mode 100644
index 00000000..ef370351
--- /dev/null
+++ b/assets/app-icon/anicraft.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/assets/app-icon/hicolor/128x128/apps/ai.storyteller.anicraft.png b/assets/app-icon/hicolor/128x128/apps/ai.storyteller.anicraft.png
new file mode 100644
index 00000000..441fa275
Binary files /dev/null and b/assets/app-icon/hicolor/128x128/apps/ai.storyteller.anicraft.png differ
diff --git a/assets/app-icon/hicolor/16x16/apps/ai.storyteller.anicraft.png b/assets/app-icon/hicolor/16x16/apps/ai.storyteller.anicraft.png
new file mode 100644
index 00000000..95d01e33
Binary files /dev/null and b/assets/app-icon/hicolor/16x16/apps/ai.storyteller.anicraft.png differ
diff --git a/assets/app-icon/hicolor/24x24/apps/ai.storyteller.anicraft.png b/assets/app-icon/hicolor/24x24/apps/ai.storyteller.anicraft.png
new file mode 100644
index 00000000..62df5df6
Binary files /dev/null and b/assets/app-icon/hicolor/24x24/apps/ai.storyteller.anicraft.png differ
diff --git a/assets/app-icon/hicolor/256x256/apps/ai.storyteller.anicraft.png b/assets/app-icon/hicolor/256x256/apps/ai.storyteller.anicraft.png
new file mode 100644
index 00000000..5d62f5af
Binary files /dev/null and b/assets/app-icon/hicolor/256x256/apps/ai.storyteller.anicraft.png differ
diff --git a/assets/app-icon/hicolor/32x32/apps/ai.storyteller.anicraft.png b/assets/app-icon/hicolor/32x32/apps/ai.storyteller.anicraft.png
new file mode 100644
index 00000000..6c5bda2b
Binary files /dev/null and b/assets/app-icon/hicolor/32x32/apps/ai.storyteller.anicraft.png differ
diff --git a/assets/app-icon/hicolor/48x48/apps/ai.storyteller.anicraft.png b/assets/app-icon/hicolor/48x48/apps/ai.storyteller.anicraft.png
new file mode 100644
index 00000000..4a1faba7
Binary files /dev/null and b/assets/app-icon/hicolor/48x48/apps/ai.storyteller.anicraft.png differ
diff --git a/assets/app-icon/hicolor/512x512/apps/ai.storyteller.anicraft.png b/assets/app-icon/hicolor/512x512/apps/ai.storyteller.anicraft.png
new file mode 100644
index 00000000..f1e3b7e5
Binary files /dev/null and b/assets/app-icon/hicolor/512x512/apps/ai.storyteller.anicraft.png differ
diff --git a/assets/app-icon/hicolor/64x64/apps/ai.storyteller.anicraft.png b/assets/app-icon/hicolor/64x64/apps/ai.storyteller.anicraft.png
new file mode 100644
index 00000000..cd4ad6dd
Binary files /dev/null and b/assets/app-icon/hicolor/64x64/apps/ai.storyteller.anicraft.png differ
diff --git a/assets/app-icon/hicolor/scalable/apps/ai.storyteller.anicraft.svg b/assets/app-icon/hicolor/scalable/apps/ai.storyteller.anicraft.svg
new file mode 100644
index 00000000..06f4f216
--- /dev/null
+++ b/assets/app-icon/hicolor/scalable/apps/ai.storyteller.anicraft.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/assets/app-icon/trace.py b/assets/app-icon/trace.py
new file mode 100644
index 00000000..2e52ecfa
--- /dev/null
+++ b/assets/app-icon/trace.py
@@ -0,0 +1,73 @@
+"""Trace the rabbit artwork into the app icon's master SVG.
+
+Needs numpy, Pillow, SciPy and vtracer (`pip install vtracer`); see README.md for the exact run.
+usage: python trace.py SOURCE OUT_SVG WORK_PX SPECKLE CROP_PX
+
+CROP_PX keeps the top-left CROP_PX square of the source: the drawing stops short of its right and
+bottom edges, so the crop lets the body run off the tile like the other Crafting Apps icons.
+"""
+
+import re
+import sys
+import tempfile
+from pathlib import Path
+
+import numpy as np
+import vtracer
+from PIL import Image, ImageFilter
+from scipy import ndimage
+
+# Ink and paper are the Crafting Apps' shared engraving colours; the paper is a neutral white so
+# the rabbit doesn't read as cream against the yellow.
+INK, PAPER, FIELD = "#0b0b0c", "#f2f1ee", "#dac604"
+
+
+def trace(mask: np.ndarray, speckle: int, d: Path) -> str:
+ """One colour layer: vtracer's binary trace of `mask`, as path elements."""
+ png, svg = d / "mask.png", d / "mask.svg"
+ Image.fromarray(np.where(mask, 0, 255).astype(np.uint8)).filter(ImageFilter.MedianFilter(3)).save(png)
+ vtracer.convert_image_to_svg_py(
+ str(png), str(svg), colormode="binary", mode="spline", filter_speckle=speckle,
+ corner_threshold=60, length_threshold=4.0, splice_threshold=45, path_precision=1,
+ )
+ found = re.findall(r']*transform="translate\(([-\d.]+),([-\d.]+)\)"', svg.read_text())
+ return "".join(f'' for p, x, y in found)
+
+
+def main() -> None:
+ src, out, n, speckle, crop = sys.argv[1], Path(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4]), int(sys.argv[5])
+ im = Image.open(src).convert("RGB").crop((0, 0, crop, crop)).resize((n, n), Image.LANCZOS)
+ a = np.asarray(im).astype(np.int32)
+ r, g, b = a[..., 0], a[..., 1], a[..., 2]
+ # The field is saturated yellow: blue far below red and green (ink over it stays yellowish).
+ yellow = (np.minimum(r, g) - b) > 0.55 * np.maximum(r, 1)
+ dark = 0.299 * r + 0.587 * g + 0.114 * b < 120
+
+ # The tile's rounding is done by SVG clips, so the art runs past it here. Only the source's own
+ # dark olive margin goes: the dark regions joined to an image corner.
+ olive, _ = ndimage.label(dark & (b < 0.25 * np.maximum(r, 1)))
+ margin = np.isin(olive, [c for c in {olive[0, 0], olive[0, -1], olive[-1, 0], olive[-1, -1]} if c])
+ inside = ~ndimage.binary_dilation(margin, iterations=2)
+
+ # Paper is the rabbit's silhouette: everything not yellow, opened so whiskers and stray fur
+ # strokes over the field stay ink on yellow (no white halo), holes filled.
+ disk = np.hypot(*np.mgrid[-3:4, -3:4]) <= 3.2
+ silhouette = ndimage.binary_fill_holes(ndimage.binary_opening(inside & ~yellow, structure=disk, iterations=max(1, n // 1000)))
+
+ with tempfile.TemporaryDirectory() as d:
+ paper = trace(silhouette & inside, speckle, Path(d))
+ ink = trace(inside & dark, speckle, Path(d))
+ # The Crafting Apps tile (rx 112 of 512) filled with the field, and the art clipped 6 units inside
+ # it (a concentric rx 106), so a band of field colour runs round every edge as on the other icons.
+ out.write_text(
+ '\n',
+ encoding="utf-8",
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/build.rs b/build.rs
index 8180bf5b..ea1e8c98 100644
--- a/build.rs
+++ b/build.rs
@@ -1,4 +1,5 @@
-//! Optional font build input (the Craft family convention, as in PhotoCraft).
+//! Optional font build input (the Craft family convention, as in PhotoCraft), and the app icon
+//! embedded in the Windows executable.
//!
//! `CRAFT_FONTS_DIR= cargo build` embeds the UI typefaces chosen in
//! ADR 0005: Inter (prose) and JetBrains Mono (data), both SIL OFL 1.1. Font files are never
@@ -49,7 +50,22 @@ fn discover() -> Option {
None
}
+/// Windows only: embed the app icon into `anicraft.exe` (taskbar, Start menu, Explorer, Alt-Tab).
+/// A missing resource compiler is a warning, so a cross-compile still links.
+fn windows_icon() {
+ println!("cargo:rerun-if-changed=assets/app-icon/anicraft.ico");
+ if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
+ return;
+ }
+ let mut res = winresource::WindowsResource::new();
+ res.set_icon("assets/app-icon/anicraft.ico").set("ProductName", "AniCraft").set("FileDescription", "AniCraft 2D vector animation studio");
+ if let Err(e) = res.compile() {
+ println!("cargo:warning=anicraft.exe built without its icon: {e}");
+ }
+}
+
fn main() {
+ windows_icon();
println!("cargo:rerun-if-env-changed=CRAFT_FONTS_DIR");
println!("cargo:rerun-if-changed=build.rs");
let dir = discover();
diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs
index 452ce47a..e37503ff 100644
--- a/crates/cli/src/lib.rs
+++ b/crates/cli/src/lib.rs
@@ -30,6 +30,10 @@ USAGE:
anicraft-cli mcp [file|--sample] Model Context Protocol server on stdin/stdout,
for AI assistants (see docs/mcp.md)
+ --plugins loads the WebAssembly plug-ins in a folder first (also the
+ ANICRAFT_PLUGINS environment variable); see docs/plugins.md.
+ Without it, headless runs use no plug-ins, so they are repeatable.
+
Frames on the command line are 1-based, as in the timeline.";
/// Parsed flags: positional args plus `--key value` pairs.
@@ -77,6 +81,19 @@ pub fn open_session(src: Option<&str>) -> Result {
}
}
+/// [`open_session`], with the plug-ins of `--plugins ` (or `ANICRAFT_PLUGINS`) loaded.
+pub fn session(a: &Args, src: Option<&str>) -> Result {
+ let mut s = open_session(src)?;
+ let folder = a.flag("plugins").map(str::to_string).or_else(|| std::env::var("ANICRAFT_PLUGINS").ok().filter(|v| !v.trim().is_empty()));
+ if let Some(folder) = folder {
+ let r = exec(&mut s, "plugin.reload", &json!({"folder": folder}))?;
+ for f in r["failed"].as_array().into_iter().flatten() {
+ eprintln!("plug-in {} not loaded: {}", f["file"].as_str().unwrap_or(""), f["error"].as_str().unwrap_or(""));
+ }
+ }
+ Ok(s)
+}
+
fn exec(s: &mut Session, id: &str, params: &Value) -> Result {
s.execute(id, params).map_err(|e| format!("{id}: {e}"))
}
@@ -101,11 +118,11 @@ pub fn run(argv: &[String]) -> Result {
serde_json::to_string_pretty(&list).map_err(|e| e.to_string())
}
"info" => {
- let s = open_session(Some(src.ok_or("info needs a file or --sample")?))?;
+ let s = session(&a, Some(src.ok_or("info needs a file or --sample")?))?;
serde_json::to_string_pretty(&s.info()).map_err(|e| e.to_string())
}
"render" => {
- let mut s = open_session(Some(src.ok_or("render needs a file or --sample")?))?;
+ let mut s = session(&a, Some(src.ok_or("render needs a file or --sample")?))?;
let out = a.flag("out").ok_or("render needs --out ")?;
let mut p = json!({"path": out, "frame": one_based(&a, "frame")?.unwrap_or(0)});
if let Some(sc) = a.num::("scale")? {
@@ -114,7 +131,7 @@ pub fn run(argv: &[String]) -> Result {
exec(&mut s, "file.export_png", &p).map(|v| v.to_string())
}
"render-seq" => {
- let mut s = open_session(Some(src.ok_or("render-seq needs a file or --sample")?))?;
+ let mut s = session(&a, Some(src.ok_or("render-seq needs a file or --sample")?))?;
let dir = a.flag("out-dir").ok_or("render-seq needs --out-dir ")?;
let mut p = json!({"dir": dir});
if let Some(f) = one_based(&a, "from")? {
@@ -129,7 +146,7 @@ pub fn run(argv: &[String]) -> Result {
exec(&mut s, "file.export_png_sequence", &p).map(|v| v.to_string())
}
"gif" => {
- let mut s = open_session(Some(src.ok_or("gif needs a file or --sample")?))?;
+ let mut s = session(&a, Some(src.ok_or("gif needs a file or --sample")?))?;
let out = a.flag("out").ok_or("gif needs --out ")?;
let mut p = json!({"path": out});
if let Some(f) = one_based(&a, "from")? {
@@ -162,7 +179,7 @@ pub fn run(argv: &[String]) -> Result {
exec(&mut s, "file.save", &json!({"path": out})).map(|v| v.to_string())
}
"exec" => {
- let mut s = open_session(Some(src.ok_or("exec needs a file or --sample")?))?;
+ let mut s = session(&a, Some(src.ok_or("exec needs a file or --sample")?))?;
let id = a.positional.get(1).ok_or("exec needs a command id")?;
let params: Value = match a.positional.get(2) {
Some(t) => serde_json::from_str(t).map_err(|e| format!("params are not JSON: {e}"))?,
@@ -175,7 +192,7 @@ pub fn run(argv: &[String]) -> Result {
Ok(v.to_string())
}
"run" => {
- let mut s = open_session(Some(src.ok_or("run needs a file or --sample")?))?;
+ let mut s = session(&a, Some(src.ok_or("run needs a file or --sample")?))?;
let script = a.positional.get(1).ok_or("run needs a script.json")?;
let text = std::fs::read_to_string(script).map_err(|e| format!("{script}: {e}"))?;
// Windows editors often save UTF-8 with a byte-order mark; JSON parsers reject it.
@@ -193,14 +210,14 @@ pub fn run(argv: &[String]) -> Result {
}
"bench" => bench(&a),
"serve" => {
- let mut s = open_session(src)?;
+ let mut s = session(&a, src)?;
let stdin = std::io::stdin();
let mut stdout = std::io::stdout();
serve(&mut s, stdin.lock(), &mut stdout).map_err(|e| e.to_string())?;
Ok(String::new())
}
"mcp" => {
- let mut s = open_session(src)?;
+ let mut s = session(&a, src)?;
let stdin = std::io::stdin();
let mut stdout = std::io::stdout();
mcp::serve(&mut s, stdin.lock(), &mut stdout).map_err(|e| e.to_string())?;
@@ -236,8 +253,42 @@ pub const TIME_BUDGETS: &[(&str, &str, f64)] = &[
("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),
+ ("autosave.ui_us", "autosave: time on the editing thread (µs)", 1000.0),
+ ("autosave.background_ms", "autosave the 65 MB file in the background (ms)", 2000.0),
];
+/// One crash-recovery autosave of `doc` as the app does it: an `Autosaver` in a scratch
+/// recovery folder, timing what the editing thread pays (the hand-off) apart from the
+/// background serialize + atomic write (temp file, flush to disk, rename).
+fn bench_autosave(doc: &anicraft_doc::Document) -> Value {
+ use anicraft_engine::recovery::{Autosaver, Outcome, SessionLock};
+ let dir = std::env::temp_dir().join(format!("anicraft-bench-recovery-{}", std::process::id()));
+ let Ok(mut saver) = SessionLock::acquire(&dir).and_then(Autosaver::start) else { return json!({"error": "no scratch folder"}) };
+ let t = Instant::now();
+ saver.write(doc.clone(), None);
+ let ui_us = t.elapsed().as_secs_f64() * 1e6;
+ let mut out = json!({"error": "timed out"});
+ while t.elapsed().as_secs() < 120 {
+ if let Some(o) = saver.poll().into_iter().next() {
+ let background_ms = t.elapsed().as_secs_f64() * 1000.0;
+ out = match o {
+ Outcome::Written { stats, .. } => json!({
+ "ui_us": round(ui_us), "background_ms": round(background_ms),
+ "serialize_ms": round(stats.serialize_ms), "write_ms": round(stats.write_ms),
+ "mb": round(stats.bytes as f64 / 1048576.0),
+ }),
+ Outcome::Failed { error, .. } => json!({"error": error}),
+ Outcome::Cleared { .. } => out,
+ };
+ break;
+ }
+ std::thread::sleep(std::time::Duration::from_millis(1));
+ }
+ saver.finish(None);
+ let _ = std::fs::remove_dir_all(&dir);
+ out
+}
+
/// 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();
@@ -287,6 +338,8 @@ pub fn bench(a: &Args) -> Result {
let _ = format::from_json(&json_text);
});
+ let autosave = bench_autosave(&doc);
+
let eval_ms = avg_ms(48, |i| {
let _ = evaluate(&doc, (i * 5) % frames.max(1));
});
@@ -332,6 +385,7 @@ pub fn bench(a: &Args) -> Result {
"document": {"layers": layers, "shapes_per_layer": shapes, "frames": frames, "element_instances": instances,
"estimated_mb": round(document_bytes(&s.doc) as f64 / 1048576.0), "build_ms": round(build_ms)},
"file": {"json_mb": round(json_text.len() as f64 / 1048576.0), "save_ms": round(save_ms), "load_ms": round(load_ms)},
+ "autosave": autosave,
"evaluate_ms_per_frame": round(eval_ms),
"render_1080p_ms_per_frame": round(render_ms), "render_shapes_drawn": drawn,
"render_zoom400_ms_per_frame": round(zoom_ms), "render_zoom400_culled": culled,
@@ -472,7 +526,7 @@ mod tests {
#[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}});
+ "render_1080p_ms_per_frame": 20.0, "render_zoom400_ms_per_frame": 10.0, "hit_test_us": 50.0, "file": {"save_ms": 100.0}, "autosave": {"ui_us": 5.0, "background_ms": 300.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"]);
@@ -485,6 +539,17 @@ mod tests {
}
}
+ #[test]
+ fn plugins_folder_flag() {
+ let dir = std::env::temp_dir().join(format!("anicraft-cli-plugins-{}", std::process::id()));
+ let argv: Vec = ["--sample", "--plugins", dir.to_str().unwrap()].iter().map(|s| s.to_string()).collect();
+ let a = Args::parse(&argv).unwrap();
+ let s = session(&a, Some("--sample")).unwrap();
+ // A folder that doesn't exist yet is the plug-ins folder, with nothing in it.
+ assert_eq!(s.plugins.folder(), Some(dir.as_path()));
+ assert!(s.plugins.is_empty());
+ }
+
#[test]
fn usage_and_errors() {
assert!(run(&[]).unwrap().contains("USAGE"));
diff --git a/crates/doc/src/easing.rs b/crates/doc/src/easing.rs
index ffd1d8e0..1d538803 100644
--- a/crates/doc/src/easing.rs
+++ b/crates/doc/src/easing.rs
@@ -42,6 +42,30 @@ impl Easing {
}
}
+ /// The cubic Bézier `(x1, y1, x2, y2)` that draws this ease, as the Motion Editor's handles:
+ /// exact for linear, the quad and cubic in/out eases and the classic slider; the two in-out
+ /// polynomials (two curves joined at the middle) get their usual one-curve approximations.
+ pub fn as_bezier(&self) -> (f32, f32, f32, f32) {
+ const THIRD: f32 = 1.0 / 3.0;
+ match *self {
+ Easing::Linear => (THIRD, THIRD, 2.0 * THIRD, 2.0 * THIRD),
+ // t² and t³ and their mirrors, with x(s) = s.
+ Easing::QuadIn => (THIRD, 0.0, 2.0 * THIRD, THIRD),
+ Easing::QuadOut => (THIRD, 2.0 * THIRD, 2.0 * THIRD, 1.0),
+ Easing::CubicIn => (THIRD, 0.0, 2.0 * THIRD, 0.0),
+ Easing::CubicOut => (THIRD, 1.0, 2.0 * THIRD, 1.0),
+ Easing::QuadInOut => (0.45, 0.0, 0.55, 1.0),
+ Easing::CubicInOut => (0.65, 0.0, 0.35, 1.0),
+ Easing::Classic(strength) => {
+ // The quadratic 2(1 − t)t·c + t², raised to a cubic.
+ let s = if strength.is_finite() { strength.clamp(-100.0, 100.0) / 100.0 } else { 0.0 };
+ let c = 0.5 + 0.5 * s;
+ (THIRD, 2.0 * c * THIRD, 2.0 * THIRD, (2.0 * c + 1.0) * THIRD)
+ }
+ Easing::CubicBezier(a, b, c, d) => (a, b, c, d),
+ }
+ }
+
pub fn apply(&self, t: f32) -> f32 {
let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 };
match *self {
@@ -168,6 +192,24 @@ mod tests {
assert!(Easing::Classic(f32::INFINITY).apply(0.5).is_finite());
}
+ #[test]
+ fn bezier_forms_draw_the_same_curves() {
+ // Exact for everything but the two in-out polynomials.
+ for e in [Easing::Linear, Easing::QuadIn, Easing::QuadOut, Easing::CubicIn, Easing::CubicOut, Easing::Classic(-60.0), Easing::Classic(100.0), Easing::CubicBezier(0.2, 1.4, 0.6, -0.3)] {
+ let (a, b, c, d) = e.as_bezier();
+ let bez = Easing::CubicBezier(a, b, c, d);
+ for i in 0..=20 {
+ let t = i as f32 / 20.0;
+ assert!((e.apply(t) - bez.apply(t)).abs() < 1e-3, "{e:?} at {t}");
+ }
+ }
+ for e in [Easing::QuadInOut, Easing::CubicInOut] {
+ let (a, b, c, d) = e.as_bezier();
+ let bez = Easing::CubicBezier(a, b, c, d);
+ assert!((0..=20).all(|i| (e.apply(i as f32 / 20.0) - bez.apply(i as f32 / 20.0)).abs() < 0.08), "{e:?}");
+ }
+ }
+
#[test]
fn ease_in_is_slow_at_start() {
assert!(Easing::QuadIn.apply(0.25) < 0.25);
diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs
index 1bc0191d..bdb854a7 100644
--- a/crates/doc/src/eval.rs
+++ b/crates/doc/src/eval.rs
@@ -136,6 +136,15 @@ pub fn evaluate_layer_elements(layer: &Layer, frame: u32) -> Option<(u32, Cow<'_
pub fn evaluate_guided<'a>(layer: &'a Layer, frame: u32, guide: Option<&PathWalk>) -> Option<(u32, Cow<'a, [Arc]>)> {
let idx = layer.keyframe_index_at(frame)?;
let kf = layer.keyframes.get(idx)?;
+ // A motion tween: its target follows the property curves; anything else on the key holds.
+ if let Some(m) = &kf.motion {
+ let Some(i) = m.target_index(&kf.elements).filter(|_| !m.tracks.is_empty()) else { return Some((kf.start, Cow::Borrowed(&kf.elements))) };
+ let mut els = kf.elements.clone();
+ if let Some(slot) = els.get_mut(i) {
+ *slot = Arc::new(m.apply(slot, (frame - kf.start) as f32));
+ }
+ return Some((kf.start, Cow::Owned(els)));
+ }
let Some(tween) = kf.tween else { return Some((kf.start, Cow::Borrowed(&kf.elements))) };
let Some(next) = layer.keyframes.get(idx + 1) else { return Some((kf.start, Cow::Borrowed(&kf.elements))) };
if next.start != kf.end() || frame == kf.start {
diff --git a/crates/doc/src/eval_tests.rs b/crates/doc/src/eval_tests.rs
index 85341c8e..fa4c1ace 100644
--- a/crates/doc/src/eval_tests.rs
+++ b/crates/doc/src/eval_tests.rs
@@ -326,3 +326,70 @@ fn movie_clips_play_their_own_timeline_graphics_keep_step_buttons_hold_up() {
layer0(&mut d).keyframes[1] = Arc::new(k1b);
assert_eq!(x(&d, 7), 1020.0);
}
+
+/// A 24-frame motion tween on one shape: X keyed at 0, 12 (ease in) and 23; alpha keyed at 23.
+fn motion_doc() -> Document {
+ use crate::{MotionTween, Property};
+ let mut d = Document::default();
+ let mut k = Keyframe::new(0, 24);
+ k.elements.push(Arc::new(shape_el(10, 0.0)));
+ let mut m = MotionTween::new(ElementId(10));
+ m.set_key(Property::X, 12, 120.0, 0.0);
+ m.set_key(Property::X, 23, 120.0, 0.0);
+ if let Some(t) = m.track_mut(Property::X) {
+ t.keys[0].ease = Easing::QuadIn;
+ }
+ m.set_key(Property::Alpha, 23, 0.0, 100.0);
+ k.motion = Some(m);
+ // A classic tween on the same span is ignored: the motion tween wins.
+ k.tween = Some(Tween::default());
+ layer0(&mut d).keyframes = vec![Arc::new(k)];
+ d
+}
+
+#[test]
+fn a_motion_tween_drives_each_property_on_its_own_curve() {
+ let d = motion_doc();
+ let at = |f| {
+ let dl = evaluate(&d, f);
+ (dl.items[0].transform.translation().x, dl.items[0].color.alpha)
+ };
+ assert_eq!(at(0), (0.0, 1.0));
+ // X eases in over 0..12 (a quarter of the way at half time); alpha runs linearly over 0..23.
+ let (x6, a6) = at(6);
+ assert!((x6 - 30.0).abs() < 1e-3, "{x6}");
+ assert!((a6 - (1.0 - 6.0 / 23.0)).abs() < 1e-5, "{a6}");
+ // X holds on 12..23 while alpha keeps fading.
+ let (x18, a18) = at(18);
+ assert!((x18 - 120.0).abs() < 1e-3 && a18 < a6);
+ assert_eq!(at(23).1, 0.0);
+ // Y, scale and rotation were never keyed: they stay the element's own.
+ let item = &evaluate(&d, 18).items[0];
+ let dc = item.transform.decompose();
+ assert!(dc.ty.abs() < 1e-4 && (dc.sx - 1.0).abs() < 1e-5 && dc.rotation.abs() < 1e-5);
+}
+
+#[test]
+fn motion_tweens_survive_a_file_round_trip_and_old_files_have_none() {
+ let d = motion_doc();
+ let json = serde_json::to_string(&d).unwrap();
+ let back: Document = serde_json::from_str(&json).unwrap();
+ assert_eq!(back, d);
+ assert!(back.timeline(0).layers[0].keyframes[0].motion.is_some());
+ // A keyframe written before motion tweens existed loads with none.
+ let old: Keyframe = serde_json::from_str(r#"{"start": 0, "duration": 3}"#).unwrap();
+ assert!(old.motion.is_none());
+ // Loading repairs a hostile tween and drops a classic tween beside it.
+ let mut d2 = d.clone();
+ let k = layer0(&mut d2).keyframe_mut(0).unwrap();
+ if let Some(m) = k.motion.as_mut() {
+ m.tracks[0].keys.reverse();
+ m.tracks[0].keys[0].value = f32::INFINITY;
+ }
+ d2.sanitize();
+ let k = &d2.timeline(0).layers[0].keyframes[0];
+ assert!(k.tween.is_none() && k.motion.as_ref().is_some_and(crate::MotionTween::is_sane));
+ for f in 0..30 {
+ assert!(evaluate(&d2, f).items.iter().all(|i| i.transform.is_finite()));
+ }
+}
diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs
index 00b280e0..c0db418f 100644
--- a/crates/doc/src/lib.rs
+++ b/crates/doc/src/lib.rs
@@ -8,12 +8,14 @@ mod bitmap;
mod filter;
mod easing;
mod eval;
+pub mod motion;
pub mod path_table;
pub mod sample;
pub use filter::{Filter, MAX_BLUR, MAX_QUALITY};
pub use bitmap::{Bitmap, BitmapId, ImageError, MAX_BITMAP_EDGE, Pixels, base64_encode, decode_png, image_to_png};
pub use easing::Easing;
+pub use motion::{MotionTween, Property, PropertyKey, Props, Track};
pub use eval::{DisplayItem, DisplayList, Group, MAX_SYMBOL_DEPTH, evaluate, evaluate_guided, evaluate_layer_elements, evaluate_scene};
use anicraft_geom::{Affine, FillRule, Path, Rect, Vec2};
@@ -491,19 +493,23 @@ pub struct Keyframe {
pub elements: Vec>,
#[serde(default)]
pub tween: Option,
+ /// A motion tween over this span (ADR 0016). A span has a classic or shape tween (`tween`)
+ /// or a motion tween, never both; commands keep it so, and a motion tween wins.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub motion: Option,
#[serde(default)]
pub label: String,
}
impl PartialEq for Keyframe {
fn eq(&self, o: &Keyframe) -> bool {
- self.start == o.start && self.duration == o.duration && self.tween == o.tween && self.label == o.label && arcs_eq(&self.elements, &o.elements)
+ self.start == o.start && self.duration == o.duration && self.tween == o.tween && self.motion == o.motion && self.label == o.label && arcs_eq(&self.elements, &o.elements)
}
}
impl Keyframe {
pub fn new(start: u32, duration: u32) -> Self {
- Keyframe { start, duration: duration.max(1), elements: Vec::new(), tween: None, label: String::new() }
+ Keyframe { start, duration: duration.max(1), elements: Vec::new(), tween: None, motion: None, label: String::new() }
}
/// Mutable access to the elements whose ids satisfy `pick`, cloning only those.
pub fn elements_mut_where(&mut self, mut pick: impl FnMut(ElementId) -> bool) -> Vec<&mut Element> {
@@ -618,6 +624,16 @@ impl Layer {
/// Restores invariants after edits: sorted, durations ≥ 1, no overlaps. Touches (and so
/// un-shares) only keyframes whose duration actually changes.
pub fn normalize(&mut self) {
+ // A loaded motion tween is repaired, and it replaces a classic tween on the same span.
+ for i in 0..self.keyframes.len() {
+ let bad = self.keyframes.get(i).is_some_and(|k| k.motion.as_ref().is_some_and(|m| !m.is_sane() || k.tween.is_some()));
+ if bad && let Some(k) = self.keyframe_mut(i) {
+ k.tween = None;
+ if let Some(m) = k.motion.as_mut() {
+ m.sanitize();
+ }
+ }
+ }
if !self.keyframes.is_sorted_by_key(|k| k.start) {
self.keyframes.sort_by_key(|k| k.start);
}
diff --git a/crates/doc/src/motion.rs b/crates/doc/src/motion.rs
new file mode 100644
index 00000000..188a2acc
--- /dev/null
+++ b/crates/doc/src/motion.rs
@@ -0,0 +1,532 @@
+//! Motion tweens (ADR 0016): one object's properties, each on its own curve.
+//!
+//! A classic tween interpolates a whole keyframe into the next one. A motion tween instead
+//! belongs to one keyframe span and one object in it (its *target*). Each property (x, y,
+//! scale, rotation, skew, alpha, tint) may have a [`Track`] of property keyframes anywhere in
+//! the span; between two keys the value follows the segment's [`Easing`], which may be a custom
+//! cubic Bézier. A property without a track keeps the target's own value (its *base*: how it
+//! looks on the span's first frame). Evaluation is pure: [`MotionTween::apply`] maps the base
+//! element and a frame offset to the element as it looks then.
+
+use crate::{Element, ElementId, Easing};
+use anicraft_geom::{Affine, Decomposed};
+use serde::{Deserialize, Serialize};
+use std::sync::Arc;
+
+/// Most keys one track keeps (files and commands alike).
+pub const MAX_KEYS: usize = 10_000;
+
+/// A property a motion tween animates. Values are in the units the Motion Editor shows:
+/// pixels, percent and degrees.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum Property {
+ /// Registration point, stage pixels.
+ X,
+ Y,
+ /// Percent (100 = natural size; negative flips).
+ ScaleX,
+ ScaleY,
+ /// Degrees, clockwise on screen; not wrapped, so 0 → 720 turns twice.
+ Rotation,
+ /// Degrees of horizontal skew, within ±89.
+ Skew,
+ /// Colour effect: opacity and tint amount, percent.
+ Alpha,
+ Tint,
+}
+
+impl Property {
+ pub const ALL: [Property; 8] = [Property::X, Property::Y, Property::ScaleX, Property::ScaleY, Property::Rotation, Property::Skew, Property::Alpha, Property::Tint];
+
+ /// The name used in files and commands (`x`, `scale_x`, `alpha`…).
+ pub fn key(self) -> &'static str {
+ match self {
+ Property::X => "x",
+ Property::Y => "y",
+ Property::ScaleX => "scale_x",
+ Property::ScaleY => "scale_y",
+ Property::Rotation => "rotation",
+ Property::Skew => "skew",
+ Property::Alpha => "alpha",
+ Property::Tint => "tint",
+ }
+ }
+
+ pub fn label(self) -> &'static str {
+ match self {
+ Property::X => "X",
+ Property::Y => "Y",
+ Property::ScaleX => "Scale X",
+ Property::ScaleY => "Scale Y",
+ Property::Rotation => "Rotation",
+ Property::Skew => "Skew",
+ Property::Alpha => "Alpha",
+ Property::Tint => "Tint",
+ }
+ }
+
+ pub fn unit(self) -> &'static str {
+ match self {
+ Property::X | Property::Y => "px",
+ Property::ScaleX | Property::ScaleY | Property::Alpha | Property::Tint => "%",
+ Property::Rotation | Property::Skew => "°",
+ }
+ }
+
+ /// The Motion Editor's groups: Position, Transform, Colour effect.
+ pub fn group(self) -> &'static str {
+ match self {
+ Property::X | Property::Y => "Position",
+ Property::ScaleX | Property::ScaleY | Property::Rotation | Property::Skew => "Transform",
+ Property::Alpha | Property::Tint => "Colour effect",
+ }
+ }
+
+ pub fn from_key(s: &str) -> Option {
+ let s = s.trim().to_ascii_lowercase().replace([' ', '-'], "_");
+ let s = match s.as_str() {
+ "scalex" => "scale_x",
+ "scaley" => "scale_y",
+ "rotate" => "rotation",
+ "opacity" => "alpha",
+ other => other,
+ };
+ Property::ALL.into_iter().find(|p| p.key() == s)
+ }
+
+ /// Values a key may hold (commands reject others; files are clamped into it).
+ pub fn range(self) -> std::ops::RangeInclusive {
+ match self {
+ Property::X | Property::Y => -1_000_000.0..=1_000_000.0,
+ Property::ScaleX | Property::ScaleY => -1_000_000.0..=1_000_000.0,
+ Property::Rotation => -100_000.0..=100_000.0,
+ Property::Skew => -89.0..=89.0,
+ Property::Alpha | Property::Tint => 0.0..=100.0,
+ }
+ }
+
+ fn index(self) -> usize {
+ Property::ALL.iter().position(|p| *p == self).unwrap_or(0)
+ }
+
+ fn is_transform(self) -> bool {
+ !matches!(self, Property::Alpha | Property::Tint)
+ }
+
+ fn clamp(self, v: f32) -> f32 {
+ let r = self.range();
+ if v.is_finite() { v.clamp(*r.start(), *r.end()) } else { 0.0 }
+ }
+}
+
+/// Every property's value, indexed like [`Property::ALL`].
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct Props(pub [f32; 8]);
+
+impl Props {
+ /// An element's own values.
+ pub fn of(el: &Element) -> Props {
+ let d = el.transform.decompose();
+ Props([d.tx, d.ty, d.sx * 100.0, d.sy * 100.0, d.rotation.to_degrees(), d.skew.atan().to_degrees(), el.color.alpha * 100.0, el.color.tint_amount * 100.0])
+ }
+ pub fn get(&self, p: Property) -> f32 {
+ self.0.get(p.index()).copied().unwrap_or(0.0)
+ }
+ pub fn set(&mut self, p: Property, v: f32) {
+ if let Some(x) = self.0.get_mut(p.index()) {
+ *x = v;
+ }
+ }
+ /// The transform these values describe.
+ pub fn transform(&self) -> Affine {
+ // Scale never reaches zero (that would collapse the artwork and lose its rotation).
+ let scale = |pct: f32| {
+ let s = Property::ScaleX.clamp(pct) / 100.0;
+ if s.abs() < 1e-4 { 1e-4f32.copysign(s) } else { s }
+ };
+ Decomposed {
+ tx: Property::X.clamp(self.get(Property::X)),
+ ty: Property::Y.clamp(self.get(Property::Y)),
+ sx: scale(self.get(Property::ScaleX)),
+ sy: scale(self.get(Property::ScaleY)),
+ rotation: Property::Rotation.clamp(self.get(Property::Rotation)).to_radians(),
+ skew: Property::Skew.clamp(self.get(Property::Skew)).to_radians().tan(),
+ }
+ .compose()
+ }
+}
+
+/// A property keyframe.
+#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
+pub struct PropertyKey {
+ /// Frames from the span's first frame.
+ pub frame: u32,
+ pub value: f32,
+ /// How the value travels from this key to the next one.
+ #[serde(default, skip_serializing_if = "is_linear")]
+ pub ease: Easing,
+}
+
+fn is_linear(e: &Easing) -> bool {
+ *e == Easing::Linear
+}
+
+/// One property's keys, sorted by frame, one per frame.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct Track {
+ pub property: Property,
+ #[serde(default)]
+ pub keys: Vec,
+}
+
+impl Track {
+ /// The value at `frame` (fractional frames sample the curve between frames): the first
+ /// key's value before it, the last key's after it, the segment's ease in between.
+ pub fn value_at(&self, frame: f32) -> Option {
+ let first = self.keys.first()?;
+ let last = self.keys.last()?;
+ if !frame.is_finite() || frame <= first.frame as f32 {
+ return Some(first.value);
+ }
+ if frame >= last.frame as f32 {
+ return Some(last.value);
+ }
+ // The segment [a, b) holding `frame`: binary search on the key frames.
+ let i = self.keys.partition_point(|k| k.frame as f32 <= frame);
+ let (a, b) = (self.keys.get(i.checked_sub(1)?)?, self.keys.get(i)?);
+ let span = (b.frame - a.frame).max(1) as f32;
+ let t = a.ease.apply((frame - a.frame as f32) / span);
+ Some(a.value + (b.value - a.value) * t)
+ }
+
+ /// Index of the key at exactly `frame`.
+ pub fn key_at(&self, frame: u32) -> Option {
+ self.keys.binary_search_by_key(&frame, |k| k.frame).ok()
+ }
+
+ /// Index of the key starting the segment that holds `frame` (`None` at or after the last
+ /// key, where no segment follows).
+ pub fn segment_at(&self, frame: u32) -> Option {
+ let i = self.keys.partition_point(|k| k.frame <= frame).checked_sub(1)?;
+ (i + 1 < self.keys.len()).then_some(i)
+ }
+
+ /// Sets the key at `frame` (keeping its ease), or adds one that eases like the segment it
+ /// splits.
+ pub fn set(&mut self, frame: u32, value: f32) {
+ let value = self.property.clamp(value);
+ match self.keys.binary_search_by_key(&frame, |k| k.frame) {
+ Ok(i) => {
+ if let Some(k) = self.keys.get_mut(i) {
+ k.value = value;
+ }
+ }
+ Err(i) => {
+ let ease = i.checked_sub(1).and_then(|p| self.keys.get(p)).map_or(Easing::Linear, |k| k.ease);
+ if self.keys.len() < MAX_KEYS {
+ self.keys.insert(i, PropertyKey { frame, value, ease });
+ }
+ }
+ }
+ }
+
+ fn sanitize(&mut self) {
+ self.keys.retain(|k| k.value.is_finite());
+ for k in &mut self.keys {
+ k.value = self.property.clamp(k.value);
+ }
+ if !self.keys.is_sorted_by_key(|k| k.frame) {
+ self.keys.sort_by_key(|k| k.frame);
+ }
+ self.keys.dedup_by_key(|k| k.frame);
+ self.keys.truncate(MAX_KEYS);
+ }
+
+ fn is_sane(&self) -> bool {
+ self.keys.len() <= MAX_KEYS && self.keys.windows(2).all(|w| matches!(w, [a, b] if a.frame < b.frame)) && self.keys.iter().all(|k| self.property.range().contains(&k.value))
+ }
+}
+
+/// A motion tween on a keyframe span (see the module docs).
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct MotionTween {
+ /// The object it animates. When no element has this id but the keyframe holds exactly one
+ /// element, that one is the target (so edits that replace the object keep its motion).
+ pub target: ElementId,
+ /// At most one per property, in [`Property::ALL`] order.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub tracks: Vec