diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 3026f85f..6d2d2567 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -19,7 +19,7 @@ shaders or SDK code). | Hack Regular (via `epaint_default_fonts`) | UI monospace font | Source Foundry Authors; Bitstream (Vera) | | MIT + Bitstream Vera licence, [`licenses/fonts/LICENSE-Hack.txt`](licenses/fonts/LICENSE-Hack.txt) | | Noto Emoji (via `epaint_default_fonts`) | Symbol fallback | Google | | SIL OFL 1.1, [`licenses/fonts/OFL-1.1-NotoEmoji.txt`](licenses/fonts/OFL-1.1-NotoEmoji.txt) | | emoji-icon-font (via `epaint_default_fonts`) | Symbol fallback | John Slegers | | MIT, [`licenses/fonts/LICENSE-emoji-icon-font.txt`](licenses/fonts/LICENSE-emoji-icon-font.txt) | -| `assets/icons/anicraft-*.svg` (27 files: align, distribute, layer, mask and masked layer, width tool, gradient transform tool, camera, brush, paint brush, eraser, eyedropper, muted sound, magnet, bone, bind, edit multiple frames, insert frame, keyframe and blank keyframe, clip to the stage) | Align panel, layer-type, Width tool, Gradient Transform tool, Camera, Brush, Paint Brush, Eraser, Eyedropper, Bone and Bind tool icons, the timeline's mute toggle, Snap to Objects, Edit Multiple Frames, the timeline's Insert Frame / Keyframe / Blank Keyframe buttons, Clip Content Outside the Stage | AniCraft contributors | Original work, drawn on Lucide's 24-unit grid and stroke style (the muted sound keeps the speaker of Lucide's `volume-2`, ISC, crossed out) | MIT OR Apache-2.0 | +| `assets/icons/anicraft-*.svg` (28 files: align, distribute, layer, mask and masked layer, width tool, gradient transform tool, camera, brush, paint brush, eraser, eyedropper, muted sound, magnet, bone, bind, asset warp, edit multiple frames, insert frame, keyframe and blank keyframe, clip to the stage) | Align panel, layer-type, Width tool, Gradient Transform tool, Camera, Brush, Paint Brush, Eraser, Eyedropper, Bone, Bind and Asset Warp tool icons, the timeline's mute toggle, Snap to Objects, Edit Multiple Frames, the timeline's Insert Frame / Keyframe / Blank Keyframe buttons, Clip Content Outside the Stage | AniCraft contributors | Original work, drawn on Lucide's 24-unit grid and stroke style (the muted sound keeps the speaker of Lucide's `volume-2`, ISC, crossed out) | MIT OR Apache-2.0 | | `crates/svg/fixtures/clips-masks-text.svg` | SVG import test drawing (clip paths, a mask, text) | AniCraft contributors | Original work | MIT OR Apache-2.0 | | `crates/svg/fixtures/soft-masks-text-paths.svg` | SVG import test drawing (an alpha and a luminance mask, text on a path) | AniCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/*.svg` except `anicraft-*` (37 files: tools, transport, layer toggles, folders, guide, image, text, sound, chevrons, plus, trash, copy, ellipsis) | UI icons, stroked by `src/icons.rs` | Lucide Icons and Contributors (some derived from Feather by Cole Bemis) | (`icons/.svg`), copied unchanged from the PhotoCraft sibling project's set (`volume-2.svg` from Lucide 0.512.0; `plus.svg`, `trash.svg`, `copy.svg` and `ellipsis.svg` from Lucide's `main` branch, 2026-11) | ISC (Lucide) and MIT (Feather), [`licenses/icons/LICENSE-lucide.txt`](licenses/icons/LICENSE-lucide.txt) | @@ -125,7 +125,9 @@ OR Apache-2.0) is noted in the table. | WebAssembly plug-in host (module validation, limits, fuel, resumable host calls) | `crates/plugins` | W3C WebAssembly Core Specification 1.0 / 2.0 (W3C Royalty-Free Patent Policy); the `wasmi` interpreter (MIT OR Apache-2.0) | Host model ported from PhotoCraft's filter plug-ins (same project family and licence) and extended with the AniCraft request ABI (ADR 0017). | | Selection tool on raw shapes: bending an edge (least-squares control-point move), following a bent edge in every shape that shares it, snapping, a marquee that cuts | `crates/geom/src/raw.rs`, `crates/geom/src/planar.rs`, `crates/engine/src/cmds_raw.rs` | Bernstein polynomials and least squares (public mathematical results); behaviour of Animate's Selection tool learned from issue #42, Adobe's public help and observation | Own implementation (ADR 0041); no Adobe code. | | Inverse kinematics by cyclic coordinate descent (bone drags, `bone.solve`), with joint limits as a clamp per step | `crates/doc/src/armature.rs` | L.-C. T. Wang and C. C. Chen, *A combined optimization method for solving the inverse kinematics problem of mechanical manipulators*, IEEE Trans. Robotics and Automation 7(4), 1991; C. Welman, *Inverse Kinematics and Geometric Constraints for Articulated Figure Manipulation*, MSc thesis, Simon Fraser University, 1993 | Published algorithm; own implementation (ADR 0043). | +| Asset Warp: rigid moving-least-squares deformation of a warp mesh's vertices by pins (weights `1 / d²`, the best rotation from the weighted dot and cross of the centred pins), piecewise affine between them | `crates/doc/src/warp.rs`, `crates/render/src/warp.rs` | S. Schaefer, T. McPhail and J. Warren, *Image deformation using moving least squares*, SIGGRAPH 2006, §2.3 | Published method; own implementation (ADR 0079). | | Linear blend skinning of a shape's outline by its bones (shape armatures: anchors blended by bone weights, handles with their anchors), with weights from the inverse fourth power of the distance to each bone | `crates/doc/src/skin.rs` | N. Magnenat-Thalmann, R. Laperrière and D. Thalmann, *Joint-dependent local deformations for hand animation and object grasping*, Graphics Interface 1988; J. P. Lewis, M. Cordner and N. Fong, *Pose space deformation*, SIGGRAPH 2000, §2 | Published method; own implementation (ADR 0071). | +| Envelope: bicubic Bézier patch warp, inner points from a bicubic Coons patch (ADR 0080) | `crates/geom/src/envelope.rs` | S. A. Coons, *Surfaces for Computer-Aided Design of Space Forms*, MIT Project MAC TR-41, 1967; G. Farin, *Curves and Surfaces for CAGD*, 5th ed., Morgan Kaufmann, 2002 (tensor-product Bézier patches) | Published mathematics; own implementation. | | De Casteljau subdivision, Ramer–Douglas–Peucker simplification | `crates/geom/src/edit.rs` | Public mathematical results (de Casteljau 1959; Ramer 1972; Douglas & Peucker 1973) | | | WAV (RIFF WAVE) reading and writing: PCM 8/16/24/32-bit, IEEE float, `WAVE_FORMAT_EXTENSIBLE` | `crates/audio/src/wav.rs` | Microsoft/IBM, *Multimedia Programming Interface and Data Specifications 1.0* (1991), and Microsoft's public `WAVE_FORMAT_EXTENSIBLE` description | Public file format descriptions. | | Resampling by cubic Hermite (Catmull-Rom) interpolation | `crates/audio/src/mix.rs` | E. Catmull and R. Rom, *A class of local interpolating splines* (1974); R. Keys, *Cubic convolution interpolation for digital image processing* (1981) | Public mathematical results. | diff --git a/CHANGELOG.md b/CHANGELOG.md index b863791e..a700776b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,36 @@ * Changed: depth now also scales under the camera's zoom (it was pan-only); files with a depth and a zoomed camera look different. +* **Drawing parity leftovers** (ADR 0080, M1). + * **PolyStar options**: Shape (**Polygon** or **Star**), **Sides**/**Points** (3 to 32) and + **Point size** (0 to 1; at 1 a star is the polygon through its tips) in the tool's options. + It merges or draws objects like the other shape tools. + * **Paint Selection** and **Paint Inside** brush modes: the paint is clipped exactly to the + selected fills, or to the fill (or the empty area closed off) where the stroke starts, and + never covers lines. Paint Selection keeps the selection for the next stroke. + * **Double-click a drawing object** (or Ctrl+E) to edit it in place, as groups and symbols + open: inside, its raw shapes merge only with each other. It closes as one drawing object + again; opening and closing it without an edit changes nothing. + * **Modify › Transform › Envelope**: corner and tangent handles bend the selected shapes and + drawing objects through a Bézier patch, one undo step per drag. Like Animate, the bend is + baked into the shapes, so there is no Delete Envelope. + * Headless: `shape`, `sides`, `point_size` on `draw.star`; `selection` and `inside` modes on + `draw.brush`; drawing objects on `symbol.edit`; `modify.envelope`, + `modify.envelope_move`, `modify.envelope_close`. + +* **Asset Warp** (M7, ADR 0079; refs #213). + * **Added**: the **Asset Warp** tool (**Shift+Q**). Click a shape or a bitmap to pin it (the + first pin covers it with a warp mesh), drag a pin to bend the artwork around the others, + live, one undo step per drag; Delete removes the picked pin. Bending is rigid moving least + squares, so the artwork stays as rigid as it can near the pins. + * **Added**: pin poses per keyframe, tweened with classic tweens and their easing; a pin added + later lands on every keyframe of the artwork. Properties › Asset Warp sets the mesh's + resolution and removes pins or the whole warp (also in Modify › Asset Warp). + * **Added**: bitmaps bend in the renderer and on the GPU stage (the same prepared image, so + they match exactly) and in every raster export; SVG writes a bent bitmap as an image; HTML + and Lottie report it. Warped shapes are bent outlines everywhere. + * **Added**: commands `warp.add`, `warp.pin_add`, `warp.pin_move`, `warp.pin_remove`, + `warp.remove` and `warp.info`, for scripts, plug-ins, the CLI and MCP. * **Swatches panel** (M1, ADR 0078). * **Added**: **Window › Swatches**, the document's saved colours and gradients, saved in the document (new documents and older files start with a default set). Click a swatch to apply diff --git a/assets/icons/anicraft-warp.svg b/assets/icons/anicraft-warp.svg new file mode 100644 index 00000000..a9fe693a --- /dev/null +++ b/assets/icons/anicraft-warp.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 93f7dccc..79eae544 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -44,6 +44,10 @@ pub struct DisplayItem { /// Whether `image` is filtered between its pixels (the bitmap's Allow Smoothing, ADR 0050); /// off, each pixel is a hard-edged square. pub smooth: bool, + /// A warped bitmap fill (ADR 0079): the mesh, in the item's local space, that carries the + /// image as drawn (`rest`) to where it shows (`shown`); renderers draw the image through + /// its triangles. `None` for everything else (a warped shape's path is already bent). + pub warp: Option>, } /// Back-to-front list of shapes. @@ -287,7 +291,14 @@ fn evaluate_tweened<'a>(layer: &'a Layer, frame: u32, guide: Option<&PathWalk>) fn interpolate(a: &Element, b: &Element, t: f32, morph: bool, hints: &[(anicraft_geom::Vec2, anicraft_geom::Vec2)], guide: Option<(&PathWalk, bool)>) -> Option { let kind = match (&a.kind, &b.kind) { (ElementKind::Shape(sa), ElementKind::Shape(sb)) => { - let path = if Arc::ptr_eq(&sa.path, &sb.path) && hints.is_empty() { + // Warped on both keyframes (ADR 0079): the pins tween and bend the outline as drawn. + let warp = match (sa.live_warp(), sb.live_warp()) { + (Some(wa), Some(wb)) if !morph || hints.is_empty() => wa.lerp(wb, t), + _ => None, + }; + let path = if let Some(w) = &warp { + w.outline() + } else if Arc::ptr_eq(&sa.path, &sb.path) && hints.is_empty() { sa.path.clone() } else if morph { anicraft_geom::morph::morph_hinted(&sa.path, &sb.path, hints, t).map(Arc::new).unwrap_or_else(|| sa.path.clone()) @@ -302,7 +313,15 @@ fn interpolate(a: &Element, b: &Element, t: f32, morph: bool, hints: &[(anicraft (Some(x), Some(y)) => Some(x.lerp(y, t)), (x, _) => x.clone(), }; - ElementKind::Shape(Shape { path, fill, stroke, fill_rule: sa.fill_rule, merge: sa.merge }) + let warp = match warp { + Some(mut w) => { + w.shown = crate::warp::fingerprint(&path); + Some(Arc::new(w)) + } + // Not tweening the pins: the shape keeps its warp only while it shows it. + None => sa.warp.clone().filter(|w| w.shows(&path)), + }; + ElementKind::Shape(Shape { path, fill, stroke, fill_rule: sa.fill_rule, merge: sa.merge, warp }) } (ElementKind::Symbol { symbol: s1, .. }, ElementKind::Symbol { symbol: s2, .. }) if s1 == s2 => a.kind.clone(), // Text tweens its placement and colour effect; the words stay the first keyframe's. @@ -529,6 +548,7 @@ fn eval_element(doc: &Document, cx: &Ctx, lc: &LayerCtx<'_>, el: &Element, out: // Inside a 9-slice instance, the shape's outline is cut and mapped (bitmap // fills scale normally, as in Animate). let sliced = cx.slice.filter(|_| !matches!(s.fill, Some(Paint::Bitmap { .. }))).map(|sl| sliced_shape(s, &el.transform, &sl)); + let is_sliced = sliced.is_some(); let (path, transform, fill, stroke) = match sliced { Some(x) => x, None => (s.path.clone(), xf, s.fill.clone(), s.stroke.clone()), @@ -555,6 +575,11 @@ fn eval_element(doc: &Document, cx: &Ctx, lc: &LayerCtx<'_>, el: &Element, out: Some(Paint::Bitmap { bitmap, .. }) => doc.bitmap(*bitmap).is_none_or(|b| b.smoothing), _ => true, }, + // A bitmap bent by its warp is drawn through the mesh (ADR 0079). + warp: match &s.fill { + Some(Paint::Bitmap { .. }) if !is_sliced => s.live_warp().filter(|w| !w.at_rest()).and_then(crate::warp::Warp::mesh).map(Arc::new), + _ => None, + }, }); } ElementKind::Text(t) => { @@ -574,6 +599,7 @@ fn eval_element(doc: &Document, cx: &Ctx, lc: &LayerCtx<'_>, el: &Element, out: group: cx.group, image: None, smooth: true, + warp: None, }; match &t.field { // Mask artwork: a field's text masks; its box and border don't. diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 28abc53c..53127efe 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -10,6 +10,7 @@ pub use anicraft_actions as actions; pub mod aids; pub mod armature; pub mod skin; +pub mod warp; mod bitmap; mod color_effect; pub mod camera; @@ -484,17 +485,30 @@ pub struct Shape { /// Otherwise a drawing object, which keeps to itself. #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub merge: bool, + /// Asset Warp (ADR 0079): the mesh and pins that bend the outline (and a bitmap fill). The + /// path is the bent outline; the warp keeps the outline as drawn. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub warp: Option>, } impl PartialEq for Shape { fn eq(&self, o: &Shape) -> bool { - arc_eq(&self.path, &o.path) && self.fill == o.fill && self.stroke == o.stroke && self.fill_rule == o.fill_rule && self.merge == o.merge + arc_eq(&self.path, &o.path) + && self.fill == o.fill + && self.stroke == o.stroke + && self.fill_rule == o.fill_rule + && self.merge == o.merge + && match (&self.warp, &o.warp) { + (Some(a), Some(b)) => arc_eq(a, b), + (None, None) => true, + _ => false, + } } } impl Shape { pub fn filled(path: Path, fill: Paint) -> Shape { - Shape { path: Arc::new(path), fill: Some(fill), stroke: None, fill_rule: FillRule::NonZero, merge: false } + Shape { path: Arc::new(path), fill: Some(fill), stroke: None, fill_rule: FillRule::NonZero, merge: false, warp: None } } pub fn with_stroke(mut self, color: Rgba, width: f32) -> Shape { self.stroke = Some(Stroke::new(color, width)); @@ -1852,6 +1866,12 @@ impl Document { for k in &l.keyframes { for e in &k.elements { *max_id = (*max_id).max(e.id.0); + // Warp pins take ids from the same counter (ADR 0079). + if let ElementKind::Shape(s) = &e.kind { + for p in s.warp.iter().flat_map(|w| &w.pins) { + *max_id = (*max_id).max(p.id.0); + } + } } } }; @@ -1872,6 +1892,7 @@ impl Document { sanitize_scripts(l); sanitize_depth(l); sanitize_armature(l); + sanitize_warps(l); scan(l, &mut max_id); sanitize_groups(l, 0, &mut max_id); } @@ -1914,6 +1935,7 @@ impl Document { } sanitize_depth(l); sanitize_armature(l); + sanitize_warps(l); scan(l, &mut max_id); sanitize_groups(l, 0, &mut max_id); } @@ -1997,6 +2019,38 @@ fn sanitize_groups(layer: &mut Arc, depth: usize, max_id: &mut u64) { } } +/// Repairs the warps on a loaded layer's shapes (ADR 0079): a warp with nothing usable left +/// goes (the shape keeps the outline it shows), and hostile pins are dropped. Touches only what +/// needs it. +fn sanitize_warps(layer: &mut Arc) { + let bad = |e: &Element| match &e.kind { + ElementKind::Shape(Shape { warp: Some(w), .. }) => { + let mut x = (**w).clone(); + !x.sanitize() || x != **w + } + _ => false, + }; + if !layer.keyframes.iter().any(|k| k.elements.iter().any(|e| bad(e))) { + return; + } + for k in &mut Arc::make_mut(layer).keyframes { + if !k.elements.iter().any(|e| bad(e)) { + continue; + } + for e in &mut Arc::make_mut(k).elements { + if !bad(e) { + continue; + } + if let ElementKind::Shape(s) = &mut Arc::make_mut(e).kind + && let Some(w) = &s.warp + { + let mut x = (**w).clone(); + s.warp = x.sanitize().then(|| Arc::new(x)); + } + } + } +} + /// Keeps a loaded layer's depth and depth keys finite and in range (touching it only if they /// aren't). fn sanitize_depth(layer: &mut Arc) { diff --git a/crates/doc/src/path_table.rs b/crates/doc/src/path_table.rs index 12ad97e8..5ce8d324 100644 --- a/crates/doc/src/path_table.rs +++ b/crates/doc/src/path_table.rs @@ -41,6 +41,13 @@ pub fn build_table(doc: &Document) -> Vec> { for layer in &tl.layers { for k in &layer.keyframes { for e in &k.elements { + // A warped shape's outline as drawn (ADR 0079) is written once too. + if let ElementKind::Shape(s) = &e.kind + && let Some(w) = &s.warp + && seen.insert(Arc::as_ptr(&w.rest) as usize, ()).is_none() + { + out.push(w.rest.clone()); + } let path = match &e.kind { ElementKind::Shape(s) => &s.path, ElementKind::Text(t) => &t.outline, diff --git a/crates/doc/src/sample.rs b/crates/doc/src/sample.rs index 2313b7e8..2ebf2d77 100644 --- a/crates/doc/src/sample.rs +++ b/crates/doc/src/sample.rs @@ -249,7 +249,7 @@ pub fn stress(layers: u32, shapes: u32, frames: u32) -> Document { name: String::new(), transform: pose(x + dx, y + dy, 1.0, 1.0, phase * 20.0), color: ColorEffect::default(), - kind: ElementKind::Shape(Shape { path: path.clone(), fill: Some(fill.clone()), stroke: None, fill_rule: Default::default(), merge: false }), + kind: ElementKind::Shape(Shape { path: path.clone(), fill: Some(fill.clone()), stroke: None, fill_rule: Default::default(), merge: false, warp: None }), }) }) .collect(); diff --git a/crates/doc/src/templates.rs b/crates/doc/src/templates.rs index d809c45c..988308f2 100644 --- a/crates/doc/src/templates.rs +++ b/crates/doc/src/templates.rs @@ -51,12 +51,12 @@ fn element(d: &mut Document, name: &str, transform: Affine, shape: Shape) -> Arc fn line(d: &mut Document, name: &str, a: (f32, f32), b: (f32, f32), color: u32, width: f32) -> Arc { let mut p = Path::new(); p.move_to(Vec2::new(a.0, a.1)).line_to(Vec2::new(b.0, b.1)); - element(d, name, Affine::IDENTITY, Shape { path: Arc::new(p), fill: None, stroke: Some(Stroke::new(Rgba::hex(color), width)), fill_rule: Default::default(), merge: false }) + element(d, name, Affine::IDENTITY, Shape { path: Arc::new(p), fill: None, stroke: Some(Stroke::new(Rgba::hex(color), width)), fill_rule: Default::default(), merge: false, warp: None }) } /// A stroked rectangle outline, `(x, y, w, h)`. fn outline(d: &mut Document, name: &str, (x, y, w, h): (f32, f32, f32, f32), color: u32, width: f32) -> Arc { - element(d, name, Affine::IDENTITY, Shape { path: Arc::new(Path::rect(x, y, w, h)), fill: None, stroke: Some(Stroke::new(Rgba::hex(color), width)), fill_rule: Default::default(), merge: false }) + element(d, name, Affine::IDENTITY, Shape { path: Arc::new(Path::rect(x, y, w, h)), fill: None, stroke: Some(Stroke::new(Rgba::hex(color), width)), fill_rule: Default::default(), merge: false, warp: None }) } /// A layer holding `elements` in one keyframe `frames` long. @@ -221,7 +221,7 @@ fn lip_sync() -> Document { inner.keyframes = keys; d.library.push(Arc::new(Symbol { id: sym_id, name: "Mouth".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid: None, scale_grid_kept: None, timeline: Timeline { layers: vec![Arc::new(inner)] } })); let (cx, cy) = (640.0, 340.0); - let face = element(&mut d, "Head", Affine::IDENTITY, Shape { path: Arc::new(Path::ellipse(cx, cy, 200.0, 250.0)), fill: None, stroke: Some(Stroke::new(Rgba::hex(GUIDE), 2.0)), fill_rule: Default::default(), merge: false }); + let face = element(&mut d, "Head", Affine::IDENTITY, Shape { path: Arc::new(Path::ellipse(cx, cy, 200.0, 250.0)), fill: None, stroke: Some(Stroke::new(Rgba::hex(GUIDE), 2.0)), fill_rule: Default::default(), merge: false, warp: None }); let guides = vec![ face, line(&mut d, "Eye line", (cx - 200.0, cy), (cx + 200.0, cy), GUIDE_SOFT, 1.0), diff --git a/crates/doc/src/warp.rs b/crates/doc/src/warp.rs new file mode 100644 index 00000000..61a11805 --- /dev/null +++ b/crates/doc/src/warp.rs @@ -0,0 +1,641 @@ +//! Asset Warp (ADR 0079): a deformation mesh over a shape or a bitmap, bent by pins. +//! +//! A [`Warp`] sits on a [`Shape`] (a bitmap on the stage is a shape filled with its image). It +//! keeps the artwork's outline as it was drawn (`rest`), a mesh **resolution**, and the +//! **pins**: each a point of the artwork as drawn (`rest`) and where it is now (`at`), both in +//! the shape's own space. The mesh is not stored: it is a grid over the rest outline's bounds, +//! `resolution` cells along the longer side (square-ish cells, each split into two triangles, +//! the diagonals alternating so the grid has no preferred direction), so it is always the same +//! for the same artwork. +//! +//! **Deformation** is the rigid moving-least-squares deformation of S. Schaefer, T. McPhail and +//! J. Warren, *Image deformation using moving least squares* (SIGGRAPH 2006, §2.3), evaluated at +//! the mesh's vertices: each vertex `v` moves by the rotation and translation that best carry +//! the pins near it (weighted `1 / |p − v|²`) to where they are. It interpolates the pins +//! exactly, is as rigid as possible locally (no shear, no scale), is a closed form per vertex +//! (no solver, no iterations, nothing to converge), and depends only on the pins, so it is +//! deterministic and its cost is bounded: vertices × pins. Between vertices the mesh is +//! piecewise affine, so a bitmap is drawn as textured triangles and a shape's outline maps +//! through the same triangles: the shape and the bitmap bend the same way. +//! +//! **The outline.** Straight edges are split where they cross the mesh's edges, so a line +//! maps exactly to the mesh's image of it (a bitmap's outline is exactly the mesh's border). +//! Curves are split into pieces no longer than half a cell, each end mapped through the mesh +//! and each handle by the triangle of the end it belongs to, so curves stay smooth. **At rest** +//! (every pin where it was placed) the outline is the drawing, bit for bit: the very `Arc` of +//! the rest path. +//! +//! **The file holds what shows.** Commands write the bent outline into the shape's `path` and +//! its fingerprint into `shown`. A shape whose path no longer has that fingerprint was edited +//! by another tool since: its warp is stale, [`Shape::live_warp`] ignores it, and the next warp +//! command starts again from the shape as it now is ([`Warp::rebased`]). Pins tween between +//! keyframes with the keyframe's easing (as bone poses do, ADR 0043): `evaluate` blends the +//! pins and bends the rest outline, so a tween never accumulates drift. + +use crate::Shape; +use anicraft_geom::{Path, PathCmd, Vec2}; +use serde::{Deserialize, Serialize}; +use std::sync::Arc; + +/// Fewest and most cells along the mesh's longer side, and the resolution a new warp has. +pub const MIN_RESOLUTION: u32 = 2; +pub const MAX_RESOLUTION: u32 = 48; +pub const DEFAULT_RESOLUTION: u32 = 12; +/// Most pins on one warp. +pub const MAX_PINS: usize = 128; +/// Most anchors a warped outline may have (Optimize first beyond it). +pub const MAX_WARP_POINTS: usize = 20_000; +/// Most commands a bent outline may have; past it curves and lines are not split. +const MAX_BENT_CMDS: usize = 400_000; +/// Most pieces one curve is split into. +const MAX_SPLIT: usize = 32; +/// Largest artwork a warp covers (local units on either side). +pub const MAX_EXTENT: f32 = 1_000_000.0; +/// Two pins closer than this (local units, as drawn) are one place. +pub const PIN_SPACING: f32 = 0.5; + +/// Unique id of a pin within a document (from the document's id counter). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +pub struct PinId(pub u64); + +/// A pin: a point of the artwork as drawn, and where it is now (the shape's space). +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct Pin { + pub id: PinId, + pub rest: Vec2, + pub at: Vec2, +} + +fn default_resolution() -> u32 { + DEFAULT_RESOLUTION +} + +/// A warp mesh on a shape (see the module docs). +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct Warp { + /// The outline as it was drawn, in the shape's space. + #[serde(with = "crate::path_table")] + pub rest: Arc, + /// Cells along the mesh's longer side ([`MIN_RESOLUTION`]..=[`MAX_RESOLUTION`]). + #[serde(default = "default_resolution")] + pub resolution: u32, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub pins: Vec, + /// Fingerprint of the outline the warp gave the shape ([`fingerprint`]). + #[serde(default)] + pub shown: u64, +} + +impl PartialEq for Warp { + fn eq(&self, o: &Warp) -> bool { + crate::arc_eq(&self.rest, &o.rest) && self.resolution == o.resolution && self.pins == o.pins && self.shown == o.shown + } +} + +/// The deformation mesh as drawn: every vertex as drawn (`rest`) and bent (`shown`), and the +/// triangles (indices into both), in the shape's space, in drawing order. +#[derive(Clone, Debug, PartialEq)] +pub struct WarpMesh { + pub rest: Vec, + pub shown: Vec, + pub tris: Vec<[u32; 3]>, +} + +/// The mesh's grid: `nx × ny` cells from `min` to `max`. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Grid { + pub min: Vec2, + pub max: Vec2, + pub nx: u32, + pub ny: u32, +} + +impl Grid { + /// The grid over `rest`'s control-point bounds with `resolution` cells along the longer side + /// (an extent under 1 unit is widened to 1, about its middle). `None` for an empty or + /// unbounded outline. + pub fn of(rest: &Path, resolution: u32) -> Option { + let b = rest.bounds(); + if !(b.min.is_finite() && b.max.is_finite()) || b.max.x < b.min.x || b.max.y < b.min.y { + return None; + } + if b.min.x.abs().max(b.min.y.abs()).max(b.max.x.abs()).max(b.max.y.abs()) > MAX_EXTENT { + return None; + } + let widen = |lo: f32, hi: f32| if hi - lo < 1.0 { ((lo + hi) * 0.5 - 0.5, (lo + hi) * 0.5 + 0.5) } else { (lo, hi) }; + let (x0, x1) = widen(b.min.x, b.max.x); + let (y0, y1) = widen(b.min.y, b.max.y); + let (w, h) = (x1 - x0, y1 - y0); + let r = resolution.clamp(MIN_RESOLUTION, MAX_RESOLUTION); + let size = w.max(h) / r as f32; + let cells = |len: f32| { + let n = (len / size).ceil(); + if n.is_finite() { (n as u32).clamp(1, r) } else { 1 } + }; + Some(Grid { min: Vec2::new(x0, y0), max: Vec2::new(x1, y1), nx: cells(w), ny: cells(h) }) + } + + /// The x of column line `i` (exactly the bounds at either end). + pub fn x(&self, i: u32) -> f32 { + if i >= self.nx { self.max.x } else { self.min.x + (self.max.x - self.min.x) * i as f32 / self.nx as f32 } + } + + /// The y of row line `j`. + pub fn y(&self, j: u32) -> f32 { + if j >= self.ny { self.max.y } else { self.min.y + (self.max.y - self.min.y) * j as f32 / self.ny as f32 } + } + + /// Vertices, row by row: `(nx + 1) × (ny + 1)`. + pub fn vertices(&self) -> Vec { + let mut out = Vec::with_capacity(((self.nx + 1) * (self.ny + 1)) as usize); + for j in 0..=self.ny { + for i in 0..=self.nx { + out.push(Vec2::new(self.x(i), self.y(j))); + } + } + out + } + + fn vertex(&self, i: u32, j: u32) -> u32 { + j * (self.nx + 1) + i + } + + /// Whether cell `(i, j)`'s diagonal runs from its top-left to its bottom-right corner (else + /// from its top-right to its bottom-left): they alternate like a chequerboard. + fn falling(i: u32, j: u32) -> bool { + (i + j).is_multiple_of(2) + } + + /// The two triangles of cell `(i, j)`, as vertex indices. + fn cell_tris(&self, i: u32, j: u32) -> [[u32; 3]; 2] { + let (a, b, c, d) = (self.vertex(i, j), self.vertex(i + 1, j), self.vertex(i, j + 1), self.vertex(i + 1, j + 1)); + if Grid::falling(i, j) { [[a, b, d], [a, d, c]] } else { [[a, b, c], [b, d, c]] } + } + + /// Every triangle, cell by cell, row by row. + pub fn triangles(&self) -> Vec<[u32; 3]> { + let mut out = Vec::with_capacity((2 * self.nx * self.ny) as usize); + for j in 0..self.ny { + for i in 0..self.nx { + out.extend(self.cell_tris(i, j)); + } + } + out + } + + /// The cell `p` falls in (clamped to the grid, so points just outside use the edge cells). + fn cell(&self, p: Vec2) -> (u32, u32) { + let at = |v: f32, lo: f32, hi: f32, n: u32| { + let k = ((v - lo) / (hi - lo) * n as f32).floor(); + if k.is_finite() { (k.max(0.0) as u32).min(n - 1) } else { 0 } + }; + (at(p.x, self.min.x, self.max.x, self.nx), at(p.y, self.min.y, self.max.y, self.ny)) + } + + /// The triangle (vertex indices) of the grid that holds `p`. + pub fn locate(&self, p: Vec2) -> [u32; 3] { + let (i, j) = self.cell(p); + let [t0, t1] = self.cell_tris(i, j); + let (x0, y0) = (self.x(i), self.y(j)); + let (cw, ch) = ((self.x(i + 1) - x0).max(1e-12), (self.y(j + 1) - y0).max(1e-12)); + let (u, v) = ((p.x - x0) / cw, (p.y - y0) / ch); + let first = if Grid::falling(i, j) { u >= v } else { u + v <= 1.0 }; + if first { t0 } else { t1 } + } + + /// The parameters in `(0, 1)` where the segment `a → b` crosses an edge of the mesh, in + /// order: column and row lines, then each cell's diagonal. + fn crossings(&self, a: Vec2, b: Vec2, out: &mut Vec) { + out.clear(); + let d = b - a; + if d.x != 0.0 { + for i in 1..self.nx { + let t = (self.x(i) - a.x) / d.x; + if t > 0.0 && t < 1.0 { + out.push(t); + } + } + } + if d.y != 0.0 { + for j in 1..self.ny { + let t = (self.y(j) - a.y) / d.y; + if t > 0.0 && t < 1.0 { + out.push(t); + } + } + } + out.sort_by(f32::total_cmp); + out.dedup_by(|x, y| (*x - *y).abs() < 1e-6); + // Inside each cell the segment may still cross the cell's diagonal. + let mut diag = Vec::new(); + let mut t0 = 0.0f32; + for &t1 in out.iter().chain(std::iter::once(&1.0)) { + let mid = a + d * ((t0 + t1) * 0.5); + let (i, j) = self.cell(mid); + let (p, q) = if Grid::falling(i, j) { (Vec2::new(self.x(i), self.y(j)), Vec2::new(self.x(i + 1), self.y(j + 1))) } else { (Vec2::new(self.x(i + 1), self.y(j)), Vec2::new(self.x(i), self.y(j + 1))) }; + let e = q - p; + let den = d.cross(e); + if den.abs() > 1e-12 { + let t = (p - a).cross(e) / den; + if t > t0 + 1e-6 && t < t1 - 1e-6 { + diag.push(t); + } + } + t0 = t1; + } + out.extend(diag); + out.sort_by(f32::total_cmp); + } +} + +/// Barycentric coordinates of `p` in triangle `(a, b, c)` (extrapolated outside it); `None` for +/// a triangle with no area. +fn barycentric(a: Vec2, b: Vec2, c: Vec2, p: Vec2) -> Option<(f32, f32, f32)> { + let det = (b - a).cross(c - a); + if det.abs() <= 1e-12 || det.is_nan() { + return None; + } + let l1 = (p - a).cross(c - a) / det; + let l2 = (b - a).cross(p - a) / det; + Some((1.0 - l1 - l2, l1, l2)) +} + +/// The rigid moving-least-squares deformation (Schaefer et al. 2006, §2.3) of `v` by pins +/// `(from, to)`, with weights `1 / |from − v|²`: the rotation and translation that best carry +/// the pins near `v` where they go, applied to `v`. A point on a pin goes with it; with one pin +/// everything moves with it; with none nothing moves. Computed in `f64`. +pub fn mls_rigid(pins: &[(Vec2, Vec2)], v: Vec2) -> Vec2 { + if pins.is_empty() { + return v; + } + let (vx, vy) = (f64::from(v.x), f64::from(v.y)); + let (mut sw, mut px, mut py, mut qx, mut qy) = (0.0f64, 0.0, 0.0, 0.0, 0.0); + let mut ws = Vec::with_capacity(pins.len()); + for &(p, q) in pins { + let (dx, dy) = (f64::from(p.x) - vx, f64::from(p.y) - vy); + let d2 = dx * dx + dy * dy; + if d2 < 1e-12 { + return q; + } + let w = 1.0 / d2; + ws.push(w); + sw += w; + px += w * f64::from(p.x); + py += w * f64::from(p.y); + qx += w * f64::from(q.x); + qy += w * f64::from(q.y); + } + if !(sw > 0.0 && sw.is_finite()) { + return v; + } + let (px, py, qx, qy) = (px / sw, py / sw, qx / sw, qy / sw); + // The best rotation: its cosine and sine are the weighted dot and cross of the centred pins. + let (mut dot, mut cross) = (0.0f64, 0.0f64); + for (&(p, q), &w) in pins.iter().zip(&ws) { + let (ax, ay) = (f64::from(p.x) - px, f64::from(p.y) - py); + let (bx, by) = (f64::from(q.x) - qx, f64::from(q.y) - qy); + dot += w * (ax * bx + ay * by); + cross += w * (ax * by - ay * bx); + } + let r = dot.hypot(cross); + let (c, s) = if r > 1e-18 && r.is_finite() { (dot / r, cross / r) } else { (1.0, 0.0) }; + let (dx, dy) = (vx - px, vy - py); + let out = Vec2::new((qx + c * dx - s * dy) as f32, (qy + s * dx + c * dy) as f32); + if out.is_finite() { out } else { v } +} + +/// A fingerprint of `path`'s commands and coordinates (FNV-1a over their bits): how a warp +/// knows the outline is still the one it gave the shape. +pub fn fingerprint(path: &Path) -> u64 { + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + let mut eat = |bits: u32| { + for b in bits.to_le_bytes() { + h ^= u64::from(b); + h = h.wrapping_mul(0x0000_0100_0000_01b3); + } + }; + for c in &path.cmds { + let (tag, pts): (u32, [Option; 3]) = match *c { + PathCmd::MoveTo(p) => (1, [Some(p), None, None]), + PathCmd::LineTo(p) => (2, [Some(p), None, None]), + PathCmd::QuadTo(a, p) => (3, [Some(a), Some(p), None]), + PathCmd::CubicTo(a, b, p) => (4, [Some(a), Some(b), Some(p)]), + PathCmd::Close => (5, [None, None, None]), + }; + eat(tag); + for p in pts.into_iter().flatten() { + eat(p.x.to_bits()); + eat(p.y.to_bits()); + } + } + h +} + +/// How many anchors (command ends) `path` has. +pub fn anchor_count(path: &Path) -> usize { + path.cmds.iter().filter(|c| !matches!(c, PathCmd::Close)).count() +} + +/// The bent mesh: the grid's vertices as drawn and where the pins carry them. +struct Bent { + grid: Grid, + rest: Vec, + shown: Vec, +} + +impl Bent { + fn at(&self, i: u32) -> (Vec2, Vec2) { + let i = i as usize; + (self.rest.get(i).copied().unwrap_or_default(), self.shown.get(i).copied().unwrap_or_default()) + } + + /// `p` (as drawn) mapped through triangle `tri`'s affine map (extrapolated outside it). + fn through(&self, tri: [u32; 3], p: Vec2) -> Vec2 { + let [(ra, sa), (rb, sb), (rc, sc)] = tri.map(|i| self.at(i)); + match barycentric(ra, rb, rc, p) { + Some((l0, l1, l2)) => { + let out = sa * l0 + sb * l1 + sc * l2; + if out.is_finite() { out } else { p } + } + None => p + (sa - ra), + } + } + + /// `p` (as drawn) where the mesh carries it, and the triangle that did. + fn map(&self, p: Vec2) -> (Vec2, [u32; 3]) { + let tri = self.grid.locate(p); + (self.through(tri, p), tri) + } +} + +impl Warp { + /// A warp of the outline `rest` with no pins. + pub fn new(rest: Arc, resolution: u32) -> Warp { + let shown = fingerprint(&rest); + Warp { rest, resolution: resolution.clamp(MIN_RESOLUTION, MAX_RESOLUTION), pins: Vec::new(), shown } + } + + /// Every pin where it was placed: the artwork shows as drawn. + pub fn at_rest(&self) -> bool { + self.pins.iter().all(|p| p.at == p.rest) + } + + pub fn pin(&self, id: PinId) -> Option<&Pin> { + self.pins.iter().find(|p| p.id == id) + } + + pub fn grid(&self) -> Option { + Grid::of(&self.rest, self.resolution) + } + + fn bent(&self) -> Option { + let grid = self.grid()?; + let rest = grid.vertices(); + let pins: Vec<(Vec2, Vec2)> = self.pins.iter().map(|p| (p.rest, p.at)).collect(); + let shown = if self.at_rest() { rest.clone() } else { rest.iter().map(|&v| mls_rigid(&pins, v)).collect() }; + Some(Bent { grid, rest, shown }) + } + + /// The mesh as it shows (`None` for an outline with no extent). + pub fn mesh(&self) -> Option { + let b = self.bent()?; + Some(WarpMesh { tris: b.grid.triangles(), rest: b.rest, shown: b.shown }) + } + + /// Where point `p` of the artwork as drawn shows now. + pub fn map(&self, p: Vec2) -> Vec2 { + if self.at_rest() { + return p; + } + self.bent().map_or(p, |b| b.map(p).0) + } + + /// The point of the artwork as drawn that shows at `p` (the topmost triangle there, as the + /// mesh draws); `None` off the mesh. + pub fn unmap(&self, p: Vec2) -> Option { + let b = self.bent()?; + if self.at_rest() { + return (p.x >= b.grid.min.x && p.x <= b.grid.max.x && p.y >= b.grid.min.y && p.y <= b.grid.max.y).then_some(p); + } + let tris = b.grid.triangles(); + for tri in tris.iter().rev() { + let [(ra, sa), (rb, sb), (rc, sc)] = tri.map(|i| b.at(i)); + let Some((l0, l1, l2)) = barycentric(sa, sb, sc, p) else { continue }; + let eps = -1e-4; + if l0 >= eps && l1 >= eps && l2 >= eps { + let r = ra * l0 + rb * l1 + rc * l2; + return r.is_finite().then_some(r); + } + } + None + } + + /// The outline as the pins bend it (the rest path itself, shared, at rest). + pub fn outline(&self) -> Arc { + if self.at_rest() { + return self.rest.clone(); + } + match self.bent() { + Some(b) => Arc::new(bend(&self.rest, &b)), + None => self.rest.clone(), + } + } + + /// Whether `path` is the outline this warp last gave its shape. + pub fn shows(&self, path: &Path) -> bool { + fingerprint(path) == self.shown + } + + /// The warp of `path` (the shape as it now is, edited since by another tool), its pins kept + /// where they show: they are its new rest, so nothing moves. + pub fn rebased(&self, path: Arc) -> Warp { + let mut w = Warp::new(path, self.resolution); + w.pins = self.pins.iter().map(|p| Pin { id: p.id, rest: p.at, at: p.at }).collect(); + w + } + + /// This warp's pins blended `t` of the way to `o`'s (pins pair by id; one without a partner + /// holds). `None` unless both bend the same artwork on the same mesh. + pub fn lerp(&self, o: &Warp, t: f32) -> Option { + if !(crate::arc_eq(&self.rest, &o.rest) && self.resolution == o.resolution) { + return None; + } + let mut w = self.clone(); + for p in &mut w.pins { + if let Some(q) = o.pin(p.id) { + p.at = p.at.lerp(q.at, t); + } + } + Some(w) + } + + /// Repairs a loaded warp: the resolution in range, finite pins (one per id, at most + /// [`MAX_PINS`]). `false` when nothing usable is left (no extent, too many points): the + /// shape keeps the outline it shows. + pub fn sanitize(&mut self) -> bool { + if self.grid().is_none() || anchor_count(&self.rest) > MAX_WARP_POINTS { + return false; + } + self.resolution = self.resolution.clamp(MIN_RESOLUTION, MAX_RESOLUTION); + let near = |v: Vec2| v.is_finite() && v.x.abs() <= MAX_EXTENT && v.y.abs() <= MAX_EXTENT; + let mut seen = Vec::with_capacity(self.pins.len()); + self.pins.retain(|p| { + let keep = near(p.rest) && near(p.at) && !seen.contains(&p.id); + seen.push(p.id); + keep + }); + self.pins.truncate(MAX_PINS); + true + } +} + +impl Shape { + /// The shape's warp while its outline is still the one the warp gave it. + pub fn live_warp(&self) -> Option<&Warp> { + self.warp.as_deref().filter(|w| w.shows(&self.path)) + } + + /// Sets the shape's warp to `w` and its outline to what `w` bends it into. + pub fn set_warp(&mut self, mut w: Warp) { + let path = w.outline(); + w.shown = fingerprint(&path); + self.path = path; + self.warp = Some(Arc::new(w)); + } +} + +/// Splits cubic `(p0, c1, c2, p3)` at `t`. +fn split_cubic(p0: Vec2, c1: Vec2, c2: Vec2, p3: Vec2, t: f32) -> ([Vec2; 4], [Vec2; 4]) { + let (a, b, c) = (p0.lerp(c1, t), c1.lerp(c2, t), c2.lerp(p3, t)); + let (d, e) = (a.lerp(b, t), b.lerp(c, t)); + let f = d.lerp(e, t); + ([p0, a, d, f], [f, e, c, p3]) +} + +fn split_quad(p0: Vec2, c: Vec2, p2: Vec2, t: f32) -> ([Vec2; 3], [Vec2; 3]) { + let (a, b) = (p0.lerp(c, t), c.lerp(p2, t)); + let m = a.lerp(b, t); + ([p0, a, m], [m, b, p2]) +} + +/// How many pieces a curve with control polygon length `len` is split into. +fn pieces(len: f32, step: f32) -> usize { + let n = (len / step).ceil(); + if n.is_finite() { (n as usize).clamp(1, MAX_SPLIT) } else { 1 } +} + +/// `rest` bent through the mesh (see the module docs). +fn bend(rest: &Path, b: &Bent) -> Path { + let g = &b.grid; + let step = (((g.max.x - g.min.x) / g.nx as f32).min((g.max.y - g.min.y) / g.ny as f32) * 0.5).max(1e-3); + // Splitting is skipped past the command budget (each anchor still maps through the mesh). + let split = rest.cmds.len().saturating_mul(MAX_SPLIT) <= MAX_BENT_CMDS || estimate(rest, g, step) <= MAX_BENT_CMDS; + let mut out: Vec = Vec::with_capacity(rest.cmds.len() * 4); + let mut ts = Vec::new(); + let mut cur = Vec2::ZERO; + let mut start = Vec2::ZERO; + // The last anchor's triangle: a cubic's first handle moves with it. + let mut cur_tri = g.locate(cur); + let line = |out: &mut Vec, a: Vec2, p: Vec2, ts: &mut Vec| { + if split { + g.crossings(a, p, ts); + for &t in ts.iter() { + out.push(PathCmd::LineTo(b.map(a.lerp(p, t)).0)); + } + } + let (q, tri) = b.map(p); + out.push(PathCmd::LineTo(q)); + tri + }; + for c in &rest.cmds { + match *c { + PathCmd::MoveTo(p) => { + let (q, tri) = b.map(p); + out.push(PathCmd::MoveTo(q)); + (cur, start, cur_tri) = (p, p, tri); + } + PathCmd::LineTo(p) => { + cur_tri = line(&mut out, cur, p, &mut ts); + cur = p; + } + PathCmd::QuadTo(c, p) => { + let n = if split { pieces(cur.distance(c) + c.distance(p), step) } else { 1 }; + let mut rest_q = [cur, c, p]; + for k in 0..n { + let left = n - k; + let (piece, tail) = if left > 1 { split_quad(rest_q[0], rest_q[1], rest_q[2], 1.0 / left as f32) } else { (rest_q, rest_q) }; + let (q, tri) = b.map(piece[2]); + out.push(PathCmd::QuadTo(b.map(piece[1]).0, q)); + cur_tri = tri; + rest_q = tail; + } + cur = p; + } + PathCmd::CubicTo(c1, c2, p) => { + let n = if split { pieces(cur.distance(c1) + c1.distance(c2) + c2.distance(p), step) } else { 1 }; + let mut rest_c = [cur, c1, c2, p]; + for k in 0..n { + let left = n - k; + let (piece, tail) = if left > 1 { split_cubic(rest_c[0], rest_c[1], rest_c[2], rest_c[3], 1.0 / left as f32) } else { (rest_c, rest_c) }; + let (q, tri) = b.map(piece[3]); + out.push(PathCmd::CubicTo(b.through(cur_tri, piece[1]), b.through(tri, piece[2]), q)); + cur_tri = tri; + rest_c = tail; + } + cur = p; + } + PathCmd::Close => { + // The closing edge is a straight line too: split it like one. + if cur != start { + if split { + g.crossings(cur, start, &mut ts); + for &t in &ts { + out.push(PathCmd::LineTo(b.map(cur.lerp(start, t)).0)); + } + } + let (q, tri) = b.map(start); + out.push(PathCmd::LineTo(q)); + cur_tri = tri; + } + out.push(PathCmd::Close); + cur = start; + } + } + } + Path { cmds: out } +} + +/// A cheap upper bound of the bent outline's commands. +fn estimate(rest: &Path, g: &Grid, step: f32) -> usize { + let lines = (g.nx + g.ny) as usize * 2 + 1; + let mut cur = Vec2::ZERO; + let mut n = 0usize; + for c in &rest.cmds { + n = n.saturating_add(match *c { + PathCmd::MoveTo(p) => { + cur = p; + 1 + } + PathCmd::LineTo(p) => { + cur = p; + lines + } + PathCmd::QuadTo(a, p) => { + let k = pieces(cur.distance(a) + a.distance(p), step); + cur = p; + k + } + PathCmd::CubicTo(a, b, p) => { + let k = pieces(cur.distance(a) + a.distance(b) + b.distance(p), step); + cur = p; + k + } + PathCmd::Close => lines + 1, + }); + } + n +} + +#[cfg(test)] +#[path = "warp_tests.rs"] +mod tests; diff --git a/crates/doc/src/warp_tests.rs b/crates/doc/src/warp_tests.rs new file mode 100644 index 00000000..59578c45 --- /dev/null +++ b/crates/doc/src/warp_tests.rs @@ -0,0 +1,244 @@ +use super::*; +use crate::{Easing, Element, ElementId, ElementKind, Keyframe, Layer, LayerId, Paint, Rgba, Tween, evaluate_layer_elements}; +use anicraft_geom::Affine; + +fn pin(id: u64, rest: (f32, f32), at: (f32, f32)) -> Pin { + Pin { id: PinId(id), rest: Vec2::new(rest.0, rest.1), at: Vec2::new(at.0, at.1) } +} + +fn blob() -> Arc { + Arc::new(Path::ellipse(100.0, 50.0, 100.0, 50.0)) +} + +fn anchors(p: &Path) -> Vec { + p.cmds + .iter() + .filter_map(|c| match *c { + PathCmd::MoveTo(p) | PathCmd::LineTo(p) | PathCmd::QuadTo(_, p) | PathCmd::CubicTo(_, _, p) => Some(p), + PathCmd::Close => None, + }) + .collect() +} + +#[test] +fn rest_pose_reproduces_the_artwork_exactly() { + let rest = blob(); + let mut w = Warp::new(rest.clone(), 12); + // No pins, then pins exactly where they were placed: the very path, shared. + assert!(Arc::ptr_eq(&w.outline(), &rest)); + w.pins = vec![pin(1, (10.0, 50.0), (10.0, 50.0)), pin(2, (190.0, 50.0), (190.0, 50.0))]; + assert!(w.at_rest()); + assert!(Arc::ptr_eq(&w.outline(), &rest)); + assert_eq!(w.map(Vec2::new(33.3, 12.5)), Vec2::new(33.3, 12.5)); + assert_eq!(w.mesh().map(|m| m.rest == m.shown), Some(true)); +} + +#[test] +fn mls_interpolates_pins_and_is_rigid_with_one_or_two() { + // One pin: everything moves with it. + let one = [(Vec2::new(0.0, 0.0), Vec2::new(5.0, -3.0))]; + assert_eq!(mls_rigid(&one, Vec2::new(40.0, 40.0)), Vec2::new(45.0, 37.0)); + // Two pins turned a quarter turn about their middle: every point turns with them. + let two = [(Vec2::new(-10.0, 0.0), Vec2::new(0.0, -10.0)), (Vec2::new(10.0, 0.0), Vec2::new(0.0, 10.0))]; + for v in [Vec2::new(3.0, 7.0), Vec2::new(-20.0, 4.0), Vec2::new(0.0, 0.0)] { + let f = mls_rigid(&two, v); + let want = Vec2::new(-v.y, v.x); + assert!(f.distance(want) < 1e-3, "{v:?} → {f:?}, want {want:?}"); + } + // On a pin: exactly its target. + assert_eq!(mls_rigid(&two, Vec2::new(10.0, 0.0)), Vec2::new(0.0, 10.0)); + assert_eq!(mls_rigid(&[], Vec2::new(1.0, 2.0)), Vec2::new(1.0, 2.0)); +} + +#[test] +fn a_single_moved_pin_moves_nearby_points_most() { + let mut w = Warp::new(Arc::new(Path::rect(0.0, 0.0, 300.0, 100.0)), 12); + // Three pins along the strip; the right one is pulled down. + w.pins = vec![pin(1, (10.0, 50.0), (10.0, 50.0)), pin(2, (150.0, 50.0), (150.0, 50.0)), pin(3, (290.0, 50.0), (290.0, 90.0))]; + let moved = |x: f32| w.map(Vec2::new(x, 50.0)).distance(Vec2::new(x, 50.0)); + let (near, mid, far) = (moved(270.0), moved(200.0), moved(40.0)); + assert!(near > mid && mid > far, "{near} > {mid} > {far}"); + assert!(near > 25.0 && far < 3.0, "near {near}, far {far}"); + // The pins themselves are where they were put (to within the mesh's interpolation). + for p in &w.pins { + assert!(w.map(p.rest).distance(p.at) < 1.5, "{p:?} → {:?}", w.map(p.rest)); + } +} + +#[test] +fn deformation_is_as_rigid_as_possible() { + // Rigidity: how much each triangle's map stretches or shears (its singular values' distance + // from 1). A pure turn of the pins turns the mesh rigidly; a bend stays near rigid. + let distortion = |w: &Warp| { + let m = w.mesh().unwrap_or_else(unreachable_mesh); + let mut worst = 0.0f32; + for t in &m.tris { + let [a, b, c] = t.map(|i| i as usize); + let (r0, r1, r2) = (m.rest[a], m.rest[b], m.rest[c]); + let (s0, s1, s2) = (m.shown[a], m.shown[b], m.shown[c]); + // The linear part J with J·(r1 − r0, r2 − r0) = (s1 − s0, s2 − s0). + let (e1, e2, f1, f2) = (r1 - r0, r2 - r0, s1 - s0, s2 - s0); + let det = e1.cross(e2); + let inv = [e2.y / det, -e2.x / det, -e1.y / det, e1.x / det]; + let j = [f1.x * inv[0] + f2.x * inv[2], f1.x * inv[1] + f2.x * inv[3], f1.y * inv[0] + f2.y * inv[2], f1.y * inv[1] + f2.y * inv[3]]; + let (p, q, r, s) = (j[0], j[1], j[2], j[3]); + let e = (p * p + q * q + r * r + s * s) * 0.5; + let d = (p * s - q * r).abs(); + let disc = (e * e - d * d).max(0.0).sqrt(); + let (big, small) = ((e + disc).sqrt(), (e - disc).max(0.0).sqrt()); + worst = worst.max((big - 1.0).abs()).max((small - 1.0).abs()); + } + worst + }; + let mut w = Warp::new(Arc::new(Path::rect(0.0, 0.0, 200.0, 100.0)), 10); + let turn = Affine::translate(100.0, 50.0).mul(&Affine::rotate(0.6)).mul(&Affine::translate(-100.0, -50.0)); + w.pins = [(20.0, 20.0), (180.0, 30.0), (100.0, 90.0)].iter().enumerate().map(|(i, &(x, y))| Pin { id: PinId(i as u64), rest: Vec2::new(x, y), at: turn.apply(Vec2::new(x, y)) }).collect(); + assert!(distortion(&w) < 1e-3, "a turn is rigid: {}", distortion(&w)); + // A bend: one end of a strip turned down by 30°. + w.pins = vec![pin(1, (10.0, 50.0), (10.0, 50.0)), pin(2, (100.0, 50.0), (100.0, 50.0)), pin(3, (190.0, 50.0), (178.0, 95.0))]; + let d = distortion(&w); + assert!(d < 0.25, "a bend stays near rigid: {d}"); +} + +fn unreachable_mesh() -> WarpMesh { + WarpMesh { rest: Vec::new(), shown: Vec::new(), tris: Vec::new() } +} + +#[test] +fn straight_edges_follow_the_mesh_exactly() { + // A bitmap's outline is a rectangle: bent, it is exactly the mesh's border. + let mut w = Warp::new(Arc::new(Path::rect(0.0, 0.0, 120.0, 60.0)), 6); + w.pins = vec![pin(1, (0.0, 0.0), (0.0, 0.0)), pin(2, (120.0, 60.0), (150.0, 90.0))]; + let m = w.mesh().unwrap_or_else(unreachable_mesh); + let g = w.grid().unwrap_or(Grid { min: Vec2::ZERO, max: Vec2::ZERO, nx: 1, ny: 1 }); + assert_eq!((g.nx, g.ny), (6, 3)); + let pts = anchors(&w.outline()); + // Every border vertex of the mesh is on the bent outline. + for (i, v) in m.rest.iter().enumerate() { + let border = v.x == 0.0 || v.y == 0.0 || v.x == 120.0 || v.y == 60.0; + if border { + assert!(pts.iter().any(|p| p.distance(m.shown[i]) < 1e-3), "border vertex {v:?} missing"); + } + } + // And the outline has no point the border doesn't (straight lines between them). + assert_eq!(pts.len(), 2 * (6 + 3) + 1); +} + +#[test] +fn curves_split_and_stay_close_to_the_true_deformation() { + let mut w = Warp::new(blob(), 16); + w.pins = vec![pin(1, (0.0, 50.0), (0.0, 50.0)), pin(2, (100.0, 50.0), (100.0, 50.0)), pin(3, (200.0, 50.0), (190.0, 100.0))]; + let bent = w.outline(); + assert!(bent.cmds.len() > blob().cmds.len()); + // Points of the bent outline lie near where the exact MLS deformation puts the drawn curve. + let pins: Vec<(Vec2, Vec2)> = w.pins.iter().map(|p| (p.rest, p.at)).collect(); + let truth: Vec = (0..400).map(|i| { + let a = i as f32 / 400.0 * std::f32::consts::TAU; + mls_rigid(&pins, Vec2::new(100.0 + 100.0 * a.cos(), 50.0 + 50.0 * a.sin())) + }).collect(); + for p in anchors(&bent) { + let d = truth.iter().map(|t| t.distance(p)).fold(f32::MAX, f32::min); + assert!(d < 2.0, "{p:?} is {d} from the true curve"); + } +} + +#[test] +fn unmap_finds_the_drawn_point() { + let mut w = Warp::new(Arc::new(Path::rect(0.0, 0.0, 200.0, 100.0)), 8); + w.pins = vec![pin(1, (20.0, 50.0), (20.0, 50.0)), pin(2, (180.0, 50.0), (200.0, 80.0))]; + for p in [Vec2::new(50.0, 30.0), Vec2::new(150.0, 70.0), Vec2::new(190.0, 10.0)] { + let shown = w.map(p); + let back = w.unmap(shown).unwrap_or(Vec2::new(f32::NAN, 0.0)); + assert!(back.distance(p) < 1e-2, "{p:?} → {shown:?} → {back:?}"); + } + assert_eq!(w.unmap(Vec2::new(-500.0, 0.0)), None); +} + +#[test] +fn deterministic_and_bounded() { + let mut w = Warp::new(blob(), 1000); + assert_eq!(w.resolution, MAX_RESOLUTION); + w.pins = (0..MAX_PINS as u64).map(|i| pin(i, (i as f32, 50.0), (i as f32 + 3.0, 50.0 + (i % 7) as f32))).collect(); + let (a, b) = (w.outline(), w.outline()); + assert_eq!(fingerprint(&a), fingerprint(&b)); + let m = w.mesh().unwrap_or_else(unreachable_mesh); + assert!(m.rest.len() <= ((MAX_RESOLUTION + 1) * (MAX_RESOLUTION + 1)) as usize); + // Tiny, flat and enormous artwork never fails. + for p in [Path::line(Vec2::new(0.0, 0.0), Vec2::new(0.0, 0.0)), Path::line(Vec2::new(0.0, 5.0), Vec2::new(300.0, 5.0)), Path::rect(0.0, 0.0, 1e7, 1.0), Path::default()] { + let mut w = Warp::new(Arc::new(p), 12); + w.pins = vec![pin(1, (0.0, 5.0), (40.0, 9.0)), pin(2, (100.0, 5.0), (100.0, 5.0))]; + let out = w.outline(); + assert!(out.cmds.iter().all(|c| match *c { + PathCmd::MoveTo(p) | PathCmd::LineTo(p) => p.is_finite(), + _ => true, + })); + } + // Hostile pins are dropped on load; the rest stays. + let mut h = Warp::new(blob(), 0); + h.pins = vec![pin(1, (f32::NAN, 0.0), (0.0, 0.0)), pin(2, (1.0, 1.0), (2.0, 2.0)), pin(2, (3.0, 3.0), (3.0, 3.0))]; + assert!(h.sanitize()); + assert_eq!(h.pins.len(), 1); + assert_eq!(h.resolution, MIN_RESOLUTION); +} + +fn warped_layer(at_end: (f32, f32), easing: Easing) -> (Layer, Warp) { + let mut shape = Shape::filled(Path::rect(0.0, 0.0, 200.0, 100.0), Paint::Solid(Rgba::hex(0x3080ff))); + let mut w = Warp::new(shape.path.clone(), 8); + w.pins = vec![pin(1, (10.0, 50.0), (10.0, 50.0)), pin(2, (190.0, 50.0), (190.0, 50.0))]; + shape.set_warp(w.clone()); + let el = |s: Shape| Arc::new(Element { id: ElementId(5), name: String::new(), transform: Affine::IDENTITY, color: Default::default(), kind: ElementKind::Shape(s) }); + let mut end = shape.clone(); + let mut w2 = w.clone(); + if let Some(p) = w2.pins.get_mut(1) { + p.at = Vec2::new(at_end.0, at_end.1); + } + end.set_warp(w2); + let mut layer = Layer::new(LayerId(1), "Art"); + let mut a = Keyframe::new(0, 10); + a.elements = vec![el(shape)]; + a.tween = Some(Tween { easing, ..Default::default() }); + let mut b = Keyframe::new(10, 1); + b.elements = vec![el(end)]; + layer.keyframes = vec![Arc::new(a), Arc::new(b)]; + (layer, w) +} + +fn shape_at(layer: &Layer, frame: u32) -> Shape { + let (_, els) = evaluate_layer_elements(layer, frame).unwrap_or((0, std::borrow::Cow::Owned(Vec::new()))); + match els.first().map(|e| &e.kind) { + Some(ElementKind::Shape(s)) => s.clone(), + _ => Shape::filled(Path::default(), Paint::Solid(Rgba::BLACK)), + } +} + +#[test] +fn pins_tween_between_keyframes() { + let (layer, w) = warped_layer((190.0, 150.0), Easing::Linear); + let mid = shape_at(&layer, 5); + let mw = mid.live_warp().cloned().unwrap_or_else(|| w.clone()); + // Halfway the pulled pin is halfway, and the outline is the mesh bent by the halfway pins. + assert_eq!(mw.pin(PinId(2)).map(|p| p.at), Some(Vec2::new(190.0, 100.0))); + let mut want = w.clone(); + if let Some(p) = want.pins.get_mut(1) { + p.at = Vec2::new(190.0, 100.0); + } + assert_eq!(*mid.path, *want.outline()); + // At the keyframes: exactly what they hold. + assert!(Arc::ptr_eq(&shape_at(&layer, 0).path, &w.rest)); + // Easing applies to the pins as it does to bone poses. + let (eased, _) = warped_layer((190.0, 150.0), Easing::QuadIn); + let ep = shape_at(&eased, 5).live_warp().and_then(|w| w.pin(PinId(2)).map(|p| p.at.y)).unwrap_or(0.0); + assert!(ep < 100.0 && ep > 50.0, "{ep}"); +} + +#[test] +fn a_shape_edited_by_another_tool_drops_out_of_its_warp() { + let (layer, _) = warped_layer((190.0, 150.0), Easing::Linear); + let mut s = shape_at(&layer, 10); + assert!(s.live_warp().is_some()); + s.path = Arc::new(s.path.transformed(&Affine::translate(1.0, 0.0))); + assert!(s.live_warp().is_none()); + let w = s.warp.as_deref().cloned().unwrap_or_else(|| Warp::new(blob(), 4)).rebased(s.path.clone()); + // Rebased, nothing moves: the edited outline is the new rest and the pins stay where they show. + assert!(w.at_rest() && w.pins.iter().any(|p| p.rest == Vec2::new(190.0, 150.0))); +} diff --git a/crates/engine/src/brush_tests.rs b/crates/engine/src/brush_tests.rs index dcd3d2b3..c748001c 100644 --- a/crates/engine/src/brush_tests.rs +++ b/crates/engine/src/brush_tests.rs @@ -196,7 +196,7 @@ fn bad_params_are_errors() { json!({"points": [[0, 0]], "size": 0}), json!({"points": [[0, 0]], "size": 1e9}), json!({"points": [[0, 0]], "shape": "star"}), - json!({"points": [[0, 0]], "mode": "inside"}), + json!({"points": [[0, 0]], "mode": "outside"}), json!({"points": [[0, 0]], "roundness": 1}), json!({"points": [[0, 0]], "smoothing": 101}), json!({"points": [[0, 0], [1e7, 0]]}), diff --git a/crates/engine/src/cmds_brush.rs b/crates/engine/src/cmds_brush.rs index 567d81cf..d26a71f8 100644 --- a/crates/engine/src/cmds_brush.rs +++ b/crates/engine/src/cmds_brush.rs @@ -8,8 +8,9 @@ use crate::merge::{self, Order}; use crate::params::*; use crate::{CommandSpec, EngineError, Result, Session}; use anicraft_doc::{ColorEffect, Element, ElementId, ElementKind, MAX_WIDTH_POINTS, Paint, Rgba, Shape, Stroke, WidthPoint, WidthProfile}; +use anicraft_geom::planar; use anicraft_geom::brush::{MAX_SAMPLES, Sample, Tip, TipShape, centre_stroke, outline_shaped}; -use anicraft_geom::{Affine, FillRule, PathCmd, Vec2}; +use anicraft_geom::{Affine, FillRule, Path, PathCmd, Vec2}; use serde_json::{Value, json}; use std::sync::Arc; @@ -19,7 +20,7 @@ pub fn specs() -> Vec { c( "draw.brush", "Brush Stroke", - "{points: [[x, y] or [x, y, pressure 0..1 (clamped)], ..] (one point paints a dab), preset? (a brush from brush.preset_list, by key or name: its settings are the defaults for the rest), size? (stage units, default 10), shape?: round|square, angle? (degrees), roundness? (5..100 %, default 100), smoothing? (0..100, default 50), curve?: linear|soft|firm|[[pressure, output], ..] (how pressure maps, both 0..1), pressure_size? (default true: pressure varies the size from 10 to 100 %), pressure_opacity? (default false: the stroke's average pressure sets its opacity), taper_start?, taper_end? (0..50 % of the stroke's length), spacing? (0 continuous, or 5..1000 % of the size between dabs), jitter? (0..50 % of the size: a ragged edge), as_stroke? (default false; true: the Paint Brush, a variable-width stroke in the stroke colour, editable with the Width tool), mode?: normal|fills|behind (Paint Normal covers fills and lines, Paint Fills leaves lines, Paint Behind paints only empty areas), color? (default: the fill colour, or the stroke colour as a stroke), unit? (stage units per screen point, default 1: smoothing and accuracy follow it), object?}", + "{points: [[x, y] or [x, y, pressure 0..1 (clamped)], ..] (one point paints a dab), preset? (a brush from brush.preset_list, by key or name: its settings are the defaults for the rest), size? (stage units, default 10), shape?: round|square, angle? (degrees), roundness? (5..100 %, default 100), smoothing? (0..100, default 50), curve?: linear|soft|firm|[[pressure, output], ..] (how pressure maps, both 0..1), pressure_size? (default true: pressure varies the size from 10 to 100 %), pressure_opacity? (default false: the stroke's average pressure sets its opacity), taper_start?, taper_end? (0..50 % of the stroke's length), spacing? (0 continuous, or 5..1000 % of the size between dabs), jitter? (0..50 % of the size: a ragged edge), as_stroke? (default false; true: the Paint Brush, a variable-width stroke in the stroke colour, editable with the Width tool), mode?: normal|fills|behind|selection|inside (Paint Normal covers fills and lines, Paint Fills leaves lines, Paint Behind paints only empty areas, Paint Selection only inside the selected fills, Paint Inside only inside the fill the stroke starts on or the empty area closed off around it; ADR 0080), color? (default: the fill colour, or the stroke colour as a stroke), unit? (stage units per screen point, default 1: smoothing and accuracy follow it), object?}", true, draw_brush as crate::RunFn, ), @@ -42,16 +43,22 @@ pub enum PaintMode { Normal, Fills, Behind, + /// Only inside the selected fills (ADR 0080). + Selection, + /// Only inside the fill the stroke starts on (ADR 0080). + Inside, } impl PaintMode { - pub const ALL: [PaintMode; 3] = [PaintMode::Normal, PaintMode::Fills, PaintMode::Behind]; + pub const ALL: [PaintMode; 5] = [PaintMode::Normal, PaintMode::Fills, PaintMode::Behind, PaintMode::Selection, PaintMode::Inside]; pub fn key(self) -> &'static str { match self { PaintMode::Normal => "normal", PaintMode::Fills => "fills", PaintMode::Behind => "behind", + PaintMode::Selection => "selection", + PaintMode::Inside => "inside", } } pub fn label(self) -> &'static str { @@ -59,6 +66,8 @@ impl PaintMode { PaintMode::Normal => "Paint Normal", PaintMode::Fills => "Paint Fills", PaintMode::Behind => "Paint Behind", + PaintMode::Selection => "Paint Selection", + PaintMode::Inside => "Paint Inside", } } pub fn hint(self) -> &'static str { @@ -66,12 +75,15 @@ impl PaintMode { PaintMode::Normal => "Paints over lines and fills on the layer.", PaintMode::Fills => "Paints over fills and empty areas, leaving lines alone.", PaintMode::Behind => "Paints only empty areas, behind the lines and fills on the layer.", + PaintMode::Selection => "Paints only inside the selected fills, leaving lines alone.", + PaintMode::Inside => "Paints only inside the fill where the stroke starts, leaving lines alone. Started on empty stage, it paints only the empty area there.", } } fn order(self) -> Order { match self { PaintMode::Normal => Order::Top, - PaintMode::Fills => Order::UnderLines, + // Clipped paint never covers a line either (ADR 0080). + PaintMode::Fills | PaintMode::Selection | PaintMode::Inside => Order::UnderLines, PaintMode::Behind => Order::Behind, } } @@ -80,6 +92,49 @@ impl PaintMode { } } +/// Where Paint Selection and Paint Inside may paint (ADR 0080). +enum Region { + /// Inside this outline (keyframe space, even-odd). + Clip(Path), + /// Only empty areas: Paint Inside started on open, empty stage (as Paint Behind). + Empty, + /// Nowhere, and why. + Nowhere(&'static str), +} + +const TOO_MUCH: &str = "there is too much artwork there to paint inside at once; paint a smaller area"; + +/// The region a clipped paint mode paints in: the union of the selected shapes' fills on the +/// active layer (Paint Selection), or the topmost fill under `start` there, else the empty area +/// the lines and fills close off around it (Paint Inside). Merged paint lies under drawing +/// objects, so off Object Drawing only raw fills count (an object is edited inside it). +fn paint_region(s: &mut Session, mode: PaintMode, start: Vec2, object: bool) -> Result { + let els = s.editable_keyframe()?.elements.clone(); + let filled = |e: &Element| match &e.kind { + ElementKind::Shape(sh) if sh.fill.is_some() && (object || sh.merge) => Some((sh.path.transformed(&e.transform), sh.fill_rule)), + _ => None, + }; + let too_much = || EngineError::State(TOO_MUCH.into()); + if mode == PaintMode::Selection { + let here = s.layer; + let picked: Vec<(Path, FillRule)> = els.iter().filter(|e| s.selection.contains(here, e.id)).filter_map(|e| filled(e)).collect(); + if picked.is_empty() { + return Ok(Region::Nowhere(if s.selection.on(here).is_empty() { "select the fills to paint inside first" } else { "the selection has no fills to paint inside" })); + } + let refs: Vec<(&Path, FillRule)> = picked.iter().map(|(p, r)| (p, *r)).collect(); + return Ok(Region::Clip(planar::union(&refs).ok_or_else(too_much)?)); + } + let on = els.iter().rev().find_map(|e| filled(e).filter(|(p, r)| p.contains(start, &Affine::IDENTITY, *r))); + if let Some((path, rule)) = on { + // The fill's own rule, as even-odd loops. + return Ok(Region::Clip(planar::union(&[(&path, rule)]).ok_or_else(too_much)?)); + } + Ok(match merge::enclosed_area(&els, start) { + Some(area) => Region::Clip(area), + None => Region::Empty, + }) +} + pub(crate) fn samples(p: &Value) -> Result> { let bad = || EngineError::Param("param 'points' must be a list of [x, y] or [x, y, pressure]".into()); let list = p.get("points").and_then(Value::as_array).ok_or_else(bad)?; @@ -166,7 +221,7 @@ fn draw_brush(s: &mut Session, p: &Value) -> Result { let as_stroke = opt_bool(p, "as_stroke")?.unwrap_or(false); let unit = ranged(p, "unit", 0.001..=1000.0, 1.0)?; let mode_key = opt_str(p, "mode")?.unwrap_or("normal"); - let mode = PaintMode::from_key(mode_key).ok_or_else(|| EngineError::Param(format!("unknown paint mode '{mode_key}' (normal, fills or behind)")))?; + let mode = PaintMode::from_key(mode_key).ok_or_else(|| EngineError::Param(format!("unknown paint mode '{mode_key}' (normal, fills, behind, selection or inside)")))?; let color = opt_color(p, "color")?.unwrap_or(if as_stroke { s.style.stroke } else { s.style.fill }); let color = Rgba { a: color.a * pressure_opacity(&b, &pts), ..color }; let object = object_param(s, p)?; @@ -181,10 +236,46 @@ fn draw_brush(s: &mut Session, p: &Value) -> Result { if as_stroke { return paint_stroke(s, &pts, &b, smoothing, tol, color, object); } - let path = outline_shaped(&pts, &tip, &b.shaping(), smoothing, tol); + let start = pts.first().map_or(Vec2::ZERO, |x| x.at); + let mut path = outline_shaped(&pts, &tip, &b.shaping(), smoothing, tol); if !path.cmds.iter().any(|c| matches!(c, PathCmd::CubicTo(..) | PathCmd::LineTo(..))) { return Err(EngineError::Param("the stroke is too small to paint".into())); } + // Paint Selection and Paint Inside (ADR 0080): the outline clipped to the region, then + // merged as usual. Nothing changes when nothing is painted (no keyframe made, no step). + let mut order = mode.order(); + // Paint Selection keeps the selection: the region, to select again after the merge. + let mut kept_region: Option = None; + if matches!(mode, PaintMode::Selection | PaintMode::Inside) { + let before = s.doc.clone(); + let region = paint_region(s, mode, start, object); + let clipped = match region { + Ok(Region::Clip(r)) => { + let c = planar::intersect(&path, FillRule::EvenOdd, &r).ok_or_else(|| EngineError::State(TOO_MUCH.into())); + kept_region = (mode == PaintMode::Selection).then_some(r); + Some(c) + } + Ok(Region::Empty) => None, + Ok(Region::Nowhere(why)) => { + s.doc = before; + return Ok(json!({"painted": false, "mode": mode.key(), "elements": [], "reason": why})); + } + Err(e) => Some(Err(e)), + }; + match clipped { + None => order = Order::Behind, + Some(Err(e)) => { + s.doc = before; + return Err(e); + } + Some(Ok(p)) if !p.cmds.iter().any(|c| matches!(c, PathCmd::CubicTo(..) | PathCmd::LineTo(..))) => { + s.doc = before; + let why = if mode == PaintMode::Selection { "the stroke doesn't reach the selected fills" } else { "nothing to paint there" }; + return Ok(json!({"painted": false, "mode": mode.key(), "elements": [], "reason": why})); + } + Some(Ok(p)) => path = p, + } + } let c = path.bounds().center(); let local = path.transformed(&Affine::translate(-c.x, -c.y)); // A gradient or bitmap in the fill swatch paints too, locked or fitted (ADR 0074), unless a @@ -199,27 +290,53 @@ fn draw_brush(s: &mut Session, p: &Value) -> Result { name: String::new(), transform: Affine::translate(c.x, c.y), color: ColorEffect::default(), - kind: ElementKind::Shape(Shape { path: Arc::new(local), fill: Some(fill), stroke: None, fill_rule: FillRule::EvenOdd, merge: !object }), + kind: ElementKind::Shape(Shape { path: Arc::new(local), fill: Some(fill), stroke: None, fill_rule: FillRule::EvenOdd, merge: !object, warp: None }), }; if s.editable_keyframe()?.elements.len() >= 100_000 { return Err(EngineError::State("too many elements on this keyframe".into())); } if object { let kf = s.editable_keyframe()?; - match mode { + match order { // Behind everything on the layer. - PaintMode::Behind => kf.elements.insert(0, Arc::new(el)), - PaintMode::Normal | PaintMode::Fills => kf.elements.push(Arc::new(el)), + Order::Behind => kf.elements.insert(0, Arc::new(el)), + Order::Top | Order::UnderLines => kf.elements.push(Arc::new(el)), + } + // Paint Selection: the selected objects stay selected, for the next stroke. + if kept_region.is_none() { + s.select_only([id]); } - s.select_only([id]); return Ok(json!({"element": id.0, "elements": [id.0], "mode": mode.key(), "merged": false})); } - let merged = merge::merge_in_order(s, vec![el], mode.order())?; - s.select_only(merged); - let ids: Vec = s.selection.id_list(); + let merged = merge::merge_in_order(s, vec![el], order)?; + let ids: Vec = merged.iter().map(|e| e.0).collect(); + match &kept_region { + // Paint Selection: what lies in the region (the selected fills' pieces and the paint) + // stays selected, for the next stroke. + Some(region) => { + let inside = pieces_in(s, region); + s.select_only(inside); + } + None => s.select_only(merged), + } Ok(json!({"element": ids.first(), "elements": ids, "mode": mode.key(), "merged": true})) } +/// The raw fills on the active keyframe that cover part of `region` (keyframe space, even-odd). +fn pieces_in(s: &mut Session, region: &Path) -> Vec { + let Ok(kf) = s.editable_keyframe() else { return Vec::new() }; + let bounds = region.bounds(); + kf.elements + .iter() + .filter(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.merge && sh.fill.is_some() && !sh.path.bounds().transformed(&e.transform).intersect(&bounds).is_empty())) + .filter(|e| match &e.kind { + ElementKind::Shape(sh) => planar::intersect(&sh.path.transformed(&e.transform), sh.fill_rule, region).is_some_and(|p| !p.is_empty()), + _ => false, + }) + .map(|e| e.id) + .collect() +} + /// Width points a Paint Brush stroke's profile is simplified from (evenly along its length). const PROFILE_SAMPLES: usize = 256; /// How closely the simplified profile follows the brush's widths (a factor of the size). diff --git a/crates/engine/src/cmds_draw.rs b/crates/engine/src/cmds_draw.rs index 1c224619..be9a0490 100644 --- a/crates/engine/src/cmds_draw.rs +++ b/crates/engine/src/cmds_draw.rs @@ -12,7 +12,7 @@ pub fn specs() -> Vec { vec![ c("draw.rect", "Rectangle", "", None, "{x, y, w, h, radius?, fill?, stroke?, stroke_width?, profile?, cap?, join?, style?, dash?, object?}", true, draw_rect as crate::RunFn), c("draw.ellipse", "Oval", "", None, "{x, y, w, h, fill?, stroke?, stroke_width?, profile?, cap?, join?, style?, dash?, object?}", true, draw_ellipse), - c("draw.star", "PolyStar", "", None, "{cx, cy, outer, inner?, points?, fill?, stroke?, profile?, cap?, join?, style?, dash?, object?}", true, draw_star), + c("draw.star", "PolyStar", "", None, "{cx, cy, outer (the corners' radius), shape?: star|polygon (default star; the PolyStar Tool Settings, ADR 0080), sides? (or points; 3..64, default 5), point_size? (0..1, default 0.5: how deep a star's points are, 1 is the polygon through its tips), inner? (an exact inner radius instead of point_size), fill?, stroke?, stroke_width?, profile?, cap?, join?, style?, dash? (the line style), object?}", true, draw_star), c("draw.line", "Line", "", None, "{x0, y0, x1, y1, stroke?, stroke_width?, profile? (a width profile name or [[t, left, right], ..]), cap?, join?, miter?, style?, dash?, dash_offset?, dot_spacing? (the line style, as stroke.set_style; default: the tool's), object? (true: a drawing object; default: Object Drawing, off: it merges with the raw shapes it touches)}", true, draw_line), c("draw.object_drawing", "Object Drawing", "", Some("J"), "{on?: bool} (default: toggle)", false, object_drawing), c("draw.snap_to_objects", "Snap to Objects", "View/Snapping", Some("Ctrl+Shift+/"), "{on?: bool} (default: toggle) dragged points and selections, and the points the Line, Rectangle, Oval, PolyStar and Pen tools draw, snap to points, lines and fill edges (while it is off, the `snap` params of element.translate, raw.move_point and draw.snap only snap to guides, the grid and pixels, as View › Guides, Grid and Snapping say)", false, snap_to_objects), @@ -118,7 +118,7 @@ pub(crate) fn add_shape(s: &mut Session, name: &str, local: Path, origin: Vec2, name: String::new(), transform: Affine::translate(origin.x, origin.y), color: ColorEffect::default(), - kind: ElementKind::Shape(Shape { path: Arc::new(local), fill, stroke, fill_rule: Default::default(), merge }), + kind: ElementKind::Shape(Shape { path: Arc::new(local), fill, stroke, fill_rule: Default::default(), merge, warp: None }), }; if merge { let merged = crate::merge::merge_in(s, vec![el])?; @@ -158,13 +158,36 @@ fn draw_star(s: &mut Session, p: &Value) -> Result { if !(0.5..=MAX_EXTENT).contains(&outer) { return Err(EngineError::Param("param 'outer' must be between 0.5 and 1,000,000".into())); } - let inner = opt_f32(p, "inner")?.unwrap_or(outer * 0.5).clamp(0.0, MAX_EXTENT); - let points = opt_u32(p, "points")?.unwrap_or(5); + // PolyStar's Tool Settings (ADR 0080): a polygon or a star, its sides (or points) and the + // star's point size. + let polygon = match opt_str(p, "shape")?.unwrap_or("star") { + "star" => false, + "polygon" => true, + other => return Err(EngineError::Param(format!("unknown PolyStar style '{other}' (polygon or star)"))), + }; + let points = match (opt_u32(p, "sides")?, opt_u32(p, "points")?) { + (Some(n), _) | (None, Some(n)) => n, + (None, None) => 5, + }; if !(3..=64).contains(&points) { - return Err(EngineError::Param("param 'points' must be between 3 and 64".into())); + return Err(EngineError::Param("param 'sides' (or 'points') must be between 3 and 64".into())); } + let point_size = match opt_f32(p, "point_size")? { + None => 0.5, + Some(v) if (0.0..=1.0).contains(&v) => v, + Some(_) => return Err(EngineError::Param("param 'point_size' must be between 0 and 1".into())), + }; let (fill, stroke) = style(s, p, true)?; - add_shape(s, "star", Path::star(0.0, 0.0, outer, inner, points), Vec2::new(cx, cy), fill, stroke, object_param(s, p)?) + let object = object_param(s, p)?; + if polygon { + return add_shape(s, "polygon", Path::polystar(0.0, 0.0, outer, points, false, point_size), Vec2::new(cx, cy), fill, stroke, object); + } + // An explicit inner radius (scripts written before the point size) still wins. + let path = match opt_f32(p, "inner")? { + Some(inner) => Path::star(0.0, 0.0, outer, inner.clamp(0.0, MAX_EXTENT), points), + None => Path::polystar(0.0, 0.0, outer, points, true, point_size), + }; + add_shape(s, "star", path, Vec2::new(cx, cy), fill, stroke, object) } fn draw_line(s: &mut Session, p: &Value) -> Result { @@ -1096,6 +1119,7 @@ fn place_bitmap(s: &mut Session, bitmap: anicraft_doc::BitmapId, x: f32, y: f32) stroke: None, fill_rule: anicraft_geom::FillRule::NonZero, merge: false, + warp: None, }), }; s.editable_keyframe()?.elements.push(Arc::new(el)); diff --git a/crates/engine/src/cmds_envelope.rs b/crates/engine/src/cmds_envelope.rs new file mode 100644 index 00000000..bc71d8b3 --- /dev/null +++ b/crates/engine/src/cmds_envelope.rs @@ -0,0 +1,258 @@ +//! Envelope (ADR 0080): Modify › Transform › Envelope bends the selected shapes and drawing +//! objects by a mesh of handles around them (`anicraft_geom::envelope`, a bicubic Bézier patch). +//! +//! The envelope is open while its shapes are the ones it made: each move bends the shapes as they +//! were when it opened (so moves never compound their approximation), and is one undo step. Like +//! Animate, it is baked: the shapes stay ordinary paths, so there is nothing to delete (no Delete +//! Envelope). Undo and redo go back to the mesh that made the shapes they restore: the session +//! keeps each mesh with the shapes it made, and finds the one whose shapes are on the stage. + +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session}; +use anicraft_doc::{Element, ElementId, ElementKind, LayerId, Shape}; +use anicraft_geom::envelope::{self, Mesh}; +use anicraft_geom::{Affine, Rect, Vec2}; +use serde_json::{Value, json}; +use std::sync::Arc; + +pub fn specs() -> Vec { + let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; + vec![ + c( + "modify.envelope", + "Envelope", + "Modify/Transform", + None, + "{} opens an envelope around the selected shapes and drawing objects on the active layer (ADR 0080): a mesh of 4 × 4 Bézier control points over their bounds, at rest → {points: [[x, y] × 16] (row by row from the top-left), bounds: [x, y, w, h], shapes}. Then modify.envelope_move bends them. Symbols, text, groups and bitmaps can't be bent: break them apart first", + false, + open as crate::RunFn, + ), + c( + "modify.envelope_move", + "Envelope", + "", + None, + "{points: [[x, y] × 16] (the whole mesh) | index: 0..15, x, y (one control point; a corner or side handle moves the inner points with it, as a Coons patch), tolerance? (stage units, default 0.05)} bends the open envelope's shapes from where they were when it opened → {points, shapes}. One undo step", + true, + move_points, + ), + c( + "modify.envelope_close", + "Close Envelope", + "", + None, + "{} closes the open envelope: bent raw shapes merge with the drawing they now touch (as after a move). Nothing to close is no error → {closed}", + true, + close, + ), + ] +} + +/// Most meshes remembered for undo and redo. +const MAX_STATES: usize = 256; +/// Most shapes one envelope bends. +const MAX_SHAPES: usize = 10_000; + +/// An open envelope. +#[derive(Clone, Debug)] +pub struct Envelope { + pub layer: LayerId, + /// The rest rectangle (keyframe space) and the shapes as they were when it opened. + pub rest: Rect, + originals: Vec>, + /// Each mesh used, with the shapes it made (the first is the rest mesh and the originals). + states: Vec<(Mesh, Vec>)>, + /// The gesture (by the state it started from) whose move made the last of `states`: a + /// drag's moves are one undo step, so only its last needs remembering. + live: Option, +} + +impl Envelope { + #[cfg(test)] + pub(crate) fn states_len(&self) -> usize { + self.states.len() + } + + /// The mesh that made the shapes now on `els`, if they are still what one of its moves made. + fn current(&self, els: &[Arc]) -> Option { + let now: Vec>> = self.originals.iter().map(|o| els.iter().find(|e| e.id == o.id)).collect(); + self.states + .iter() + .rev() + .find(|(_, made)| made.len() == now.len() && made.iter().zip(&now).all(|(m, n)| n.is_some_and(|n| Arc::ptr_eq(m, n) || **m == **n))) + .map(|(mesh, _)| *mesh) + } +} + +impl Session { + /// The open envelope's layer, rest rectangle and current mesh (keyframe space), while its + /// shapes are selected and still the ones it made (an edit to them, or a new selection, + /// ends it). + pub fn envelope(&self) -> Option<(LayerId, Rect, Mesh)> { + let env = self.envelope.as_ref()?; + if env.layer != self.layer || !env.originals.iter().all(|o| self.selection.contains(env.layer, o.id)) { + return None; + } + let mesh = env.current(&self.elements_on(env.layer))?; + Some((env.layer, env.rest, mesh)) + } +} + +fn mesh_json(m: &Mesh) -> Value { + json!(m.iter().map(|p| [p.x, p.y]).collect::>()) +} + +/// What an envelope can bend: shapes (raw and drawing objects). +fn bendable(e: &Element) -> bool { + matches!(e.kind, ElementKind::Shape(_)) +} + +/// The tight bounds of shapes' outlines in keyframe space. +fn outline_bounds(els: &[Arc]) -> Rect { + let mut r = Rect::EMPTY; + for e in els { + if let ElementKind::Shape(sh) = &e.kind { + for pl in sh.path.flatten(&e.transform, 0.05) { + pl.points.iter().for_each(|p| r.include(*p)); + } + } + } + r +} + +fn open(s: &mut Session, _: &Value) -> Result { + let here = s.layer; + let sel = s.selection.on(here); + let els = s.elements_on(here); + let picked: Vec> = els.iter().filter(|e| sel.contains(&e.id)).cloned().collect(); + if picked.is_empty() { + return Err(EngineError::State("select the shapes or drawing objects to bend with an envelope".into())); + } + if !picked.iter().all(|e| bendable(e)) { + return Err(EngineError::State("an envelope bends shapes and drawing objects only: break symbols, text, groups and bitmaps apart first (Modify › Break Apart)".into())); + } + // A warp (ADR 0079) bends the outline as drawn on every keyframe of its layer: baking an + // envelope into one of them would fight it. + if picked.iter().any(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.warp.is_some())) { + return Err(EngineError::State("an envelope can't bend warped artwork (Asset Warp): remove its warp first (Modify › Asset Warp › Remove Warp)".into())); + } + if picked.len() > MAX_SHAPES { + return Err(EngineError::State(format!("an envelope bends at most {MAX_SHAPES} shapes at once"))); + } + let mut rest = outline_bounds(&picked); + // A straight line has no height (or width): give the mesh some room. + if rest.is_empty() || !rest.min.x.is_finite() { + return Err(EngineError::State("the selection has no outline to bend".into())); + } + let pad = |lo: f32, hi: f32| if hi - lo < 1.0 { ((lo + hi) * 0.5 - 0.5, (lo + hi) * 0.5 + 0.5) } else { (lo, hi) }; + let ((x0, x1), (y0, y1)) = (pad(rest.min.x, rest.max.x), pad(rest.min.y, rest.max.y)); + rest = Rect::new(x0, y0, x1, y1); + let mesh = envelope::rest_mesh(&rest); + s.envelope = Some(Envelope { layer: here, rest, originals: picked.clone(), states: vec![(mesh, picked.clone())], live: None }); + Ok(json!({"points": mesh_json(&mesh), "bounds": [rest.min.x, rest.min.y, rest.width(), rest.height()], "shapes": picked.len()})) +} + +/// The mesh asked for: the whole of it, or the current one with one point moved. +fn asked(p: &Value, current: &Mesh) -> Result { + if let Some(list) = p.get("points") { + let bad = || EngineError::Param("param 'points' must be 16 points [x, y], row by row from the top-left".into()); + let list = list.as_array().filter(|l| l.len() == 16).ok_or_else(bad)?; + let mut m = [Vec2::ZERO; 16]; + for (slot, v) in m.iter_mut().zip(list) { + let xy = v.as_array().filter(|a| a.len() == 2).ok_or_else(bad)?; + let n = |i: usize| xy.get(i).and_then(Value::as_f64).map(|f| f as f32).filter(|f| f.is_finite() && f.abs() <= crate::cmds_draw::MAX_EXTENT); + *slot = Vec2::new(n(0).ok_or_else(bad)?, n(1).ok_or_else(bad)?); + } + return Ok(m); + } + let i = opt_u32(p, "index")?.ok_or_else(|| EngineError::Param("give the whole mesh ('points') or one point ('index', 'x', 'y')".into()))? as usize; + if i >= 16 { + return Err(EngineError::Param("param 'index' must be 0 to 15".into())); + } + let to = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?); + if !(to.x.abs() <= crate::cmds_draw::MAX_EXTENT && to.y.abs() <= crate::cmds_draw::MAX_EXTENT) { + return Err(EngineError::Param("the point is too far away".into())); + } + let mut m = *current; + if let Some(slot) = m.get_mut(i) { + *slot = to; + } + // A boundary handle bends the inside with it; an inner point moves alone. + if envelope::BOUNDARY.contains(&i) { + envelope::coons_interior(&mut m); + } + Ok(m) +} + +/// `shape` (placed by `m`) bent in keyframe space, as an element placed at its centre. +fn bent(e: &Element, sh: &Shape, mesh: &Mesh, rest: &Rect, tol: f32) -> Option { + let path = envelope::warp(&sh.path.transformed(&e.transform), mesh, rest, tol)?; + let c = path.bounds().center(); + let to_local = Affine::translate(-c.x, -c.y); + let k = e.transform.mean_scale(); + let shape = Shape { + path: Arc::new(path.transformed(&to_local)), + // Gradients and bitmaps stay where they were on the stage (they don't bend, as in Animate). + fill: sh.fill.as_ref().map(|f| f.transformed(&to_local.mul(&e.transform))), + stroke: sh.stroke.as_ref().map(|st| st.scaled(k)), + ..sh.clone() + }; + Some(Element { id: e.id, name: e.name.clone(), transform: Affine::translate(c.x, c.y), color: e.color, kind: ElementKind::Shape(shape) }) +} + +fn move_points(s: &mut Session, p: &Value) -> Result { + let none = || EngineError::State("no envelope is open: select shapes and choose Modify › Transform › Envelope".into()); + let (_, rest, current) = s.envelope().ok_or_else(none)?; + let mesh = asked(p, ¤t)?; + let tol = match opt_f32(p, "tolerance")? { + None => 0.05, + Some(t) if (0.001..=100.0).contains(&t) => t, + Some(_) => return Err(EngineError::Param("param 'tolerance' must be between 0.001 and 100".into())), + }; + let originals = s.envelope.as_ref().map(|e| e.originals.clone()).unwrap_or_default(); + let made: Vec> = originals + .iter() + .map(|o| match &o.kind { + ElementKind::Shape(sh) => bent(o, sh, &mesh, &rest, tol).map(Arc::new).ok_or_else(|| EngineError::State("the envelope bends those shapes too far to draw; move the handles back a little".into())), + _ => Ok(o.clone()), + }) + .collect::>()?; + let kf = s.editable_keyframe()?; + for m in &made { + if let Some(slot) = kf.elements.iter_mut().find(|e| e.id == m.id) { + *slot = m.clone(); + } + } + let gesture = s.gesture.as_ref().map(|g| g.state); + if let Some(env) = s.envelope.as_mut() { + // Another move of the same drag replaces the one before it. + if gesture.is_some() && env.live == gesture && env.states.len() > 1 { + env.states.pop(); + } + env.live = gesture; + if env.states.len() >= MAX_STATES { + // Keep the rest state; forget the oldest move. + env.states.remove(1); + } + env.states.push((mesh, made.clone())); + } + Ok(json!({"points": mesh_json(&mesh), "shapes": made.len()})) +} + +fn close(s: &mut Session, _: &Value) -> Result { + let Some(env) = s.envelope.take() else { return Ok(json!({"closed": false})) }; + let ids: Vec = env.originals.iter().map(|e| e.id).collect(); + // Bent raw shapes merge where they now lie, as after a move (ADR 0031). + let here = s.elements_on(env.layer); + let raw = here.iter().any(|e| ids.contains(&e.id) && crate::merge::mergeable(e).is_some()); + if raw && env.layer == s.layer { + let keep = s.selection.clone(); + s.selection = crate::Selection::only(env.layer, ids.iter().copied()); + crate::merge::drop_selected(s)?; + // What the merge selected, else what was selected. + if s.selection.is_empty() { + s.selection = keep; + } + } + Ok(json!({"closed": true})) +} diff --git a/crates/engine/src/cmds_file.rs b/crates/engine/src/cmds_file.rs index b4dfe67c..190caf69 100644 --- a/crates/engine/src/cmds_file.rs +++ b/crates/engine/src/cmds_file.rs @@ -505,6 +505,7 @@ fn import_image(s: &mut Session, path: &std::path::Path, bytes: Vec) -> Resu stroke: None, fill_rule: anicraft_geom::FillRule::NonZero, merge: false, + warp: None, }; Ok(anicraft_svg::SvgImport::single(w, h, vec![anicraft_svg::ImportedElement { name, transform: anicraft_geom::Affine::IDENTITY, alpha: 1.0, kind: anicraft_doc::ElementKind::Shape(shape) }])) } diff --git a/crates/engine/src/cmds_group.rs b/crates/engine/src/cmds_group.rs index b8823800..a77f893d 100644 --- a/crates/engine/src/cmds_group.rs +++ b/crates/engine/src/cmds_group.rs @@ -71,8 +71,8 @@ pub(crate) fn group_depth(e: &Element) -> usize { } /// How many groups are open around the timeline being edited (inside the innermost open symbol). -fn open_groups(s: &Session) -> usize { - s.editing.iter().rev().take_while(|l| l.open == crate::editing::Opened::Group).count() +pub(crate) fn open_groups(s: &Session) -> usize { + s.editing.iter().rev().take_while(|l| l.open.is_group()).count() } fn group(s: &mut Session, _: &Value) -> Result { @@ -226,7 +226,7 @@ fn object(doc: &mut anicraft_doc::Document, path: &Path, fill: Option Result { name: String::new(), transform: Affine::translate(c.x, c.y), color: ColorEffect::default(), - kind: ElementKind::Shape(Shape { fill: Some(given.unwrap_or_else(|| s.style.fill_paint_for(&Affine::translate(-c.x, -c.y), &local.bounds()))), path: Arc::new(local), stroke: None, fill_rule: FillRule::EvenOdd, merge: !object }), + kind: ElementKind::Shape(Shape { fill: Some(given.unwrap_or_else(|| s.style.fill_paint_for(&Affine::translate(-c.x, -c.y), &local.bounds()))), path: Arc::new(local), stroke: None, fill_rule: FillRule::EvenOdd, merge: !object, warp: None }), }; if !object { // Raw: behind the drawing, so it takes only what is empty and joins the fills of its diff --git a/crates/engine/src/cmds_plugin.rs b/crates/engine/src/cmds_plugin.rs index 13e6ca2d..805ecdab 100644 --- a/crates/engine/src/cmds_plugin.rs +++ b/crates/engine/src/cmds_plugin.rs @@ -31,7 +31,7 @@ const MAX_ELEMENTS: usize = 10_000; /// a namespace this list doesn't know is refused until someone decides (a test checks that /// every registered namespace is known). pub fn plugin_may_call(id: &str) -> std::result::Result<(), &'static str> { - const DOCUMENT: &[&str] = &["draw", "edit", "element", "symbol", "arrange", "modify", "library", "text", "scene", "path", "paint", "timeline", "layer", "align", "doc", "motion", "sound", "stroke", "tween", "actions", "instance", "camera", "bone", "script", "raw", "frames", "find", "explorer"]; + const DOCUMENT: &[&str] = &["draw", "edit", "element", "symbol", "arrange", "modify", "library", "text", "scene", "path", "paint", "timeline", "layer", "align", "doc", "motion", "sound", "stroke", "tween", "actions", "instance", "camera", "bone", "warp", "script", "raw", "frames", "find", "explorer"]; match id { "edit.undo" | "edit.redo" => Err("a plug-in run is one undo step; it can't undo or redo"), "edit.cut" | "edit.copy" | "edit.paste" | "edit.paste_in_place" | "timeline.cut_frames" | "timeline.copy_frames" | "timeline.paste_frames" | "frames.cut" | "frames.copy" | "frames.paste" => { diff --git a/crates/engine/src/cmds_text.rs b/crates/engine/src/cmds_text.rs index 9947d15d..46dd5568 100644 --- a/crates/engine/src/cmds_text.rs +++ b/crates/engine/src/cmds_text.rs @@ -539,5 +539,5 @@ fn fonts(_: &mut Session, _: &Value) -> Result { /// A text block as a plain shape with the same outlines (Break Apart). pub(crate) fn to_shape(t: &TextBlock) -> anicraft_doc::Shape { let path: Arc = t.outline.clone(); - anicraft_doc::Shape { path, fill: Some(anicraft_doc::Paint::Solid(t.color)), stroke: None, fill_rule: anicraft_geom::FillRule::NonZero, merge: false } + anicraft_doc::Shape { path, fill: Some(anicraft_doc::Paint::Solid(t.color)), stroke: None, fill_rule: anicraft_geom::FillRule::NonZero, merge: false, warp: None } } diff --git a/crates/engine/src/cmds_warp.rs b/crates/engine/src/cmds_warp.rs new file mode 100644 index 00000000..3d3d923b --- /dev/null +++ b/crates/engine/src/cmds_warp.rs @@ -0,0 +1,397 @@ +//! Asset Warp commands (ADR 0079): a warp mesh on a shape or a bitmap, pins on it, and moving +//! them to bend the artwork. +//! +//! The mesh belongs to the artwork: `warp.add` (and the first `warp.pin_add`) puts it on the +//! element at the playhead and on every keyframe of its layer that holds the same artwork, so +//! keyframes made from it bend the same mesh. Pins are added to and removed from all of those +//! keyframes (where the artwork shows there, so nothing moves), while `warp.pin_move` moves a +//! pin on the keyframe at the playhead only: that is the pose, and poses tween with classic +//! tweens. Inside a tween a move keys the frame with what it shows, as editing any tweened +//! object does. A drag sends many `warp.pin_move` calls inside one gesture: one undo step. +//! +//! A shape edited since by another tool (its outline no longer the one its warp gave it) starts +//! again from how it now looks: its pins stay where they show and become its rest. + +use crate::params::*; +use crate::{CommandSpec, EngineError, KeyEdit, MAX_FRAME, Result, Session}; +use anicraft_doc::warp::{self, MAX_EXTENT, MAX_PINS, MAX_RESOLUTION, MAX_WARP_POINTS, MIN_RESOLUTION, PIN_SPACING, Pin, PinId, Warp}; +use anicraft_doc::{Element, ElementId, ElementKind, LayerId, Paint, Shape, evaluate_layer_elements}; +use anicraft_geom::{Affine, Path, Vec2}; +use serde_json::{Value, json}; +use std::sync::Arc; + +pub fn specs() -> Vec { + let c = |id, label, menu, params, mutates, run| CommandSpec { id, label, menu, shortcut: None, params, mutates, run }; + vec![ + c( + "warp.add", + "Add Warp Mesh", + "Modify/Asset Warp", + "{element? (a shape or bitmap; default the one selected), resolution? (cells along the longer side, 2…48; default 12)} → {element, created, resolution, columns, rows}. Covers the artwork with a warp mesh on every keyframe of its layer that holds it (it becomes a drawing object); on artwork that has one, changes the mesh's resolution", + true, + add as crate::RunFn, + ), + c( + "warp.pin_add", + "Add Warp Pin", + "", + "{element?, x, y (stage px, on the artwork)} → {element, pin, created}. Pins the artwork there (adding the mesh first if it has none), on every keyframe that bends the same mesh; nothing moves", + true, + pin_add, + ), + c("warp.pin_move", "Move Warp Pin", "", "{element?, pin, x?, y? (stage px: where the pin goes), dx?, dy? (stage px: by how much), frame?} → {element, pin, at}. Bends the artwork at the frame (keying it inside a tween); pins tween between keyframes", true, pin_move), + c("warp.pin_remove", "Remove Warp Pin", "", "{element?, pin} removes the pin from every keyframe that bends the same mesh; the artwork follows the pins that are left", true, pin_remove), + c("warp.remove", "Remove Warp", "Modify/Asset Warp", "{element?} takes the warp mesh and its pins off the artwork on every keyframe of its layer: it shows as drawn again", true, remove), + c("warp.info", "Warp Mesh", "", "{element?, frame?} → the artwork's warp at the frame: resolution, the mesh's columns, rows, vertices and triangles, whether it is bent, and its pins (id, where they show in stage px, and where they were placed on the artwork as drawn, in its own space)", false, info), + ] +} + +/// The element a warp command acts on: `element`, or the one selected element on the active +/// layer. +fn element_param(s: &Session, p: &Value) -> Result { + if let Some(id) = opt_u64(p, "element")? { + return Ok(ElementId(id)); + } + match s.selection.on(s.layer).as_slice() { + [one] => Ok(*one), + [] => Err(EngineError::State("select a shape or a bitmap first (or give 'element')".into())), + _ => Err(EngineError::State("select just one shape or bitmap to warp".into())), + } +} + +/// Where element `id` is at `frame`, as it shows (tweened): its layer and the element. +fn find(s: &Session, id: ElementId, frame: u32) -> Result<(LayerId, Arc)> { + s.timeline() + .layers + .iter() + .find_map(|l| { + let (_, els) = evaluate_layer_elements(l, frame)?; + Some((l.id, els.iter().find(|e| e.id == id)?.clone())) + }) + .ok_or_else(|| EngineError::State(format!("no element with id {} on the stage at frame {}", id.0, frame + 1))) +} + +fn shape_of(el: &Element) -> Result<&Shape> { + match &el.kind { + ElementKind::Shape(sh) => Ok(sh), + _ => Err(EngineError::State("Asset Warp bends shapes and bitmaps; break a symbol or text apart first (Modify › Break Apart)".into())), + } +} + +fn frame_param(s: &Session, p: &Value) -> Result { + let f = opt_u32(p, "frame")?.unwrap_or(s.frame); + if f > MAX_FRAME { + return Err(EngineError::Param(format!("param 'frame' must be at most {MAX_FRAME}"))); + } + Ok(f) +} + +/// The warp a command starts from on `sh`: its own while it shows it, rebased when the shape +/// was edited since, `None` without one. +fn current(sh: &Shape) -> Option { + let w = sh.warp.as_deref()?; + Some(if w.shows(&sh.path) { w.clone() } else { w.rebased(sh.path.clone()) }) +} + +fn check_artwork(path: &Path) -> Result<()> { + if warp::anchor_count(path) > MAX_WARP_POINTS { + return Err(EngineError::State(format!("that artwork has more than {MAX_WARP_POINTS} points: simplify it first (Modify › Shape › Optimize)"))); + } + if Warp::new(Arc::new(path.clone()), MIN_RESOLUTION).grid().is_none() { + return Err(EngineError::State("that artwork has no extent to warp".into())); + } + Ok(()) +} + +/// Runs `edit` on element `id` in the keyframe of `layer` that an edit at `frame` changes (keying +/// the frame inside a classic or shape tween), with the shape and the stage → local map. +fn edit_at(s: &mut Session, layer: LayerId, frame: u32, id: ElementId, edit: impl FnOnce(&mut Shape, &Affine) -> Result) -> Result { + let tl = s.timeline(); + let l = tl.layer(layer).ok_or_else(|| EngineError::State("the layer went away".into()))?; + if l.keyframe_at(frame).is_some_and(|k| k.motion.is_some()) { + return Err(EngineError::State("Asset Warp pins tween with classic tweens: this frame is in a motion tween".into())); + } + let (was_layer, was_frame) = (s.layer, s.frame); + s.layer = layer; + s.frame = frame; + let out = (|| { + let kf = s.editable_keyframe_in(KeyEdit::Artwork)?; + let e = kf.elements.iter_mut().find(|e| e.id == id).ok_or_else(|| EngineError::State("that element isn't on this keyframe".into()))?; + let el = Arc::make_mut(e); + let inv = el.transform.inverse().ok_or_else(|| EngineError::State("artwork scaled to nothing can't be warped".into()))?; + let ElementKind::Shape(sh) = &mut el.kind else { return Err(EngineError::State("Asset Warp bends shapes and bitmaps".into())) }; + edit(sh, &inv) + })(); + s.layer = was_layer; + s.frame = was_frame; + out +} + +/// Runs `f` on every other keyframe of `layer` (not the one starting at `skip`) whose element +/// `id` is warped on the same mesh as `rest` (it shows its warp), then bends it again. +fn each_other(s: &mut Session, layer: LayerId, skip: Option, id: ElementId, rest: &Arc, resolution: u32, mut f: impl FnMut(&mut Warp, &mut Shape)) -> Result { + let l = s.layer_mut(Some(layer))?; + let mut n = 0; + for k in &mut l.keyframes { + if Some(k.start) == skip { + continue; + } + let same = |e: &Arc| e.id == id && matches!(&e.kind, ElementKind::Shape(sh) if sh.live_warp().is_some_and(|w| anicraft_doc::arc_eq(&w.rest, rest) && w.resolution == resolution)); + if !k.elements.iter().any(same) { + continue; + } + for e in Arc::make_mut(k).elements.iter_mut().filter(|e| same(e)) { + if let ElementKind::Shape(sh) = &mut Arc::make_mut(e).kind + && let Some(mut w) = sh.warp.as_deref().cloned() + { + f(&mut w, sh); + if sh.warp.is_some() { + sh.set_warp(w); + } + n += 1; + } + } + } + Ok(n) +} + +/// The start of the keyframe of `layer` covering `frame`. +fn key_start(s: &Session, layer: LayerId, frame: u32) -> Option { + s.timeline().layer(layer).and_then(|l| l.keyframe_at(frame)).map(|k| k.start) +} + +fn resolution_param(p: &Value) -> Result> { + match opt_u32(p, "resolution")? { + Some(r) if !(MIN_RESOLUTION..=MAX_RESOLUTION).contains(&r) => Err(EngineError::Param(format!("param 'resolution' must be {MIN_RESOLUTION}…{MAX_RESOLUTION}"))), + r => Ok(r), + } +} + +/// Puts a warp on element `id` at the playhead (and on every keyframe holding the same +/// artwork), or changes its resolution. Returns whether it was made, and the warp. +fn ensure(s: &mut Session, layer: LayerId, id: ElementId, resolution: Option) -> Result<(bool, Warp)> { + let frame = s.frame; + // The artwork as it is on the keyframe at the playhead (before any keying), to find copies. + let before: Option> = s.timeline().layer(layer).and_then(|l| l.keyframe_at(frame)).and_then(|k| k.elements.iter().find(|e| e.id == id)).and_then(|e| match &e.kind { + ElementKind::Shape(sh) => Some(sh.path.clone()), + _ => None, + }); + let (created, w, old) = edit_at(s, layer, frame, id, |sh, _| { + let old = sh.live_warp().map(|w| (w.rest.clone(), w.resolution)); + let (created, mut w) = match current(sh) { + Some(w) => (false, w), + None => { + check_artwork(&sh.path)?; + (true, Warp::new(sh.path.clone(), resolution.unwrap_or(warp::DEFAULT_RESOLUTION))) + } + }; + if let Some(r) = resolution { + w.resolution = r; + } + // A warped shape is a drawing object: drawing over it never cuts its outline. + sh.merge = false; + sh.set_warp(w.clone()); + Ok((created, w, old)) + })?; + let skip = key_start(s, layer, frame); + match old { + // A new resolution: every keyframe on the same mesh takes it. + Some((rest, r)) if !created && Some(r) != resolution && resolution.is_some() => { + each_other(s, layer, skip, id, &rest, r, |x, _| x.resolution = w.resolution)?; + } + Some(_) => {} + None => { + // A new mesh: every other keyframe holding the very artwork it covers gets it too. + let Some(path) = before else { return Ok((created, w)) }; + let l = s.layer_mut(Some(layer))?; + for k in &mut l.keyframes { + if Some(k.start) == skip { + continue; + } + let same = |e: &Arc| e.id == id && matches!(&e.kind, ElementKind::Shape(sh) if sh.warp.is_none() && (Arc::ptr_eq(&sh.path, &path) || *sh.path == *path)); + if k.elements.iter().any(same) { + for e in Arc::make_mut(k).elements.iter_mut().filter(|e| same(e)) { + if let ElementKind::Shape(sh) = &mut Arc::make_mut(e).kind { + sh.merge = false; + let mut x = w.clone(); + x.rest = sh.path.clone(); + sh.set_warp(x); + } + } + } + } + } + } + Ok((created, w)) +} + +fn add(s: &mut Session, p: &Value) -> Result { + let id = element_param(s, p)?; + let resolution = resolution_param(p)?; + let (layer, el) = find(s, id, s.frame)?; + shape_of(&el)?; + let (created, w) = ensure(s, layer, id, resolution)?; + let g = w.grid(); + Ok(json!({"element": id.0, "created": created, "resolution": w.resolution, "columns": g.map_or(0, |g| g.nx), "rows": g.map_or(0, |g| g.ny)})) +} + +fn stage_point(p: &Value) -> Result { + let v = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?); + if v.x.abs() > MAX_EXTENT || v.y.abs() > MAX_EXTENT { + return Err(EngineError::Param("the point must be within ±1,000,000 px".into())); + } + Ok(v) +} + +fn pin_add(s: &mut Session, p: &Value) -> Result { + let id = element_param(s, p)?; + let at = stage_point(p)?; + let (layer, el) = find(s, id, s.frame)?; + shape_of(&el)?; + let (created, _) = ensure(s, layer, id, None)?; + let pin = PinId(s.doc.alloc_id()); + let frame = s.frame; + let (rest, mesh) = edit_at(s, layer, frame, id, |sh, inv| { + let mut w = current(sh).ok_or_else(|| EngineError::State("the artwork has no warp mesh".into()))?; + if w.pins.len() >= MAX_PINS { + return Err(EngineError::State(format!("a warp has at most {MAX_PINS} pins"))); + } + let local = inv.apply(at); + let r = w.unmap(local).ok_or_else(|| EngineError::State("click on the artwork to pin it".into()))?; + if w.pins.iter().any(|q| q.rest.distance(r) < PIN_SPACING) { + return Err(EngineError::State("there is a pin there already".into())); + } + w.pins.push(Pin { id: pin, rest: r, at: local }); + let mesh = (w.rest.clone(), w.resolution); + sh.set_warp(w); + Ok((r, mesh)) + })?; + // The same pin on every other keyframe bending this mesh, where that point shows there. + let skip = key_start(s, layer, frame); + each_other(s, layer, skip, id, &mesh.0, mesh.1, |w, _| { + if w.pins.len() < MAX_PINS && w.pin(pin).is_none() { + let shown = w.map(rest); + w.pins.push(Pin { id: pin, rest, at: shown }); + } + })?; + Ok(json!({"element": id.0, "pin": pin.0, "created": created})) +} + +fn pin_id(p: &Value) -> Result { + opt_u64(p, "pin")?.map(PinId).ok_or_else(|| EngineError::Param("param 'pin' (a pin id; see warp.info) is required".into())) +} + +fn pin_move(s: &mut Session, p: &Value) -> Result { + let id = element_param(s, p)?; + let pin = pin_id(p)?; + let frame = frame_param(s, p)?; + let to = match (opt_f32(p, "x")?, opt_f32(p, "y")?) { + (Some(x), Some(y)) => Some(Vec2::new(x, y)), + (None, None) => None, + _ => return Err(EngineError::Param("give both 'x' and 'y' (or 'dx' and 'dy')".into())), + }; + let by = Vec2::new(opt_f32(p, "dx")?.unwrap_or(0.0), opt_f32(p, "dy")?.unwrap_or(0.0)); + let (layer, el) = find(s, id, frame)?; + shape_of(&el)?; + let xf = el.transform; + let at = edit_at(s, layer, frame, id, |sh, inv| { + let mut w = current(sh).ok_or_else(|| EngineError::State("the artwork has no warp mesh: add pins with the Warp tool first".into()))?; + let q = w.pins.iter_mut().find(|q| q.id == pin).ok_or_else(|| EngineError::State(format!("no pin with id {} on that artwork", pin.0)))?; + let local = match to { + Some(t) => inv.apply(t), + None => q.at + inv.apply_vector(by), + }; + if !(local.is_finite() && local.x.abs() <= MAX_EXTENT && local.y.abs() <= MAX_EXTENT) { + return Err(EngineError::Param("the pin must stay within ±1,000,000 px".into())); + } + q.at = local; + sh.set_warp(w); + Ok(local) + })?; + let shown = xf.apply(at); + Ok(json!({"element": id.0, "pin": pin.0, "at": [shown.x, shown.y]})) +} + +fn pin_remove(s: &mut Session, p: &Value) -> Result { + let id = element_param(s, p)?; + let pin = pin_id(p)?; + let (layer, el) = find(s, id, s.frame)?; + shape_of(&el)?; + let frame = s.frame; + let mesh = edit_at(s, layer, frame, id, |sh, _| { + let mut w = current(sh).ok_or_else(|| EngineError::State("the artwork has no warp mesh".into()))?; + let before = w.pins.len(); + w.pins.retain(|q| q.id != pin); + if w.pins.len() == before { + return Err(EngineError::State(format!("no pin with id {} on that artwork", pin.0))); + } + let mesh = (w.rest.clone(), w.resolution); + sh.set_warp(w); + Ok(mesh) + })?; + let skip = key_start(s, layer, frame); + let n = each_other(s, layer, skip, id, &mesh.0, mesh.1, |w, _| w.pins.retain(|q| q.id != pin))?; + Ok(json!({"element": id.0, "pin": pin.0, "keyframes": n + 1})) +} + +fn remove(s: &mut Session, p: &Value) -> Result { + let id = element_param(s, p)?; + let (layer, el) = find(s, id, s.frame)?; + let sh = shape_of(&el)?; + let frame = s.frame; + let Some(w) = sh.live_warp().cloned() else { + if sh.warp.is_some() { + // Edited since by another tool: the stale warp just goes; the shape stays as it is. + edit_at(s, layer, frame, id, |sh, _| { + sh.warp = None; + Ok(()) + })?; + return Ok(json!({"element": id.0, "keyframes": 1})); + } + return Err(EngineError::State("that artwork has no warp mesh".into())); + }; + edit_at(s, layer, frame, id, |sh, _| { + sh.path = w.rest.clone(); + sh.warp = None; + Ok(()) + })?; + let skip = key_start(s, layer, frame); + let n = each_other(s, layer, skip, id, &w.rest, w.resolution, |w, sh| { + sh.path = w.rest.clone(); + sh.warp = None; + })?; + Ok(json!({"element": id.0, "keyframes": n + 1})) +} + +fn info(s: &mut Session, p: &Value) -> Result { + let id = element_param(s, p)?; + let frame = frame_param(s, p)?; + let (layer, el) = find(s, id, frame)?; + let sh = shape_of(&el)?; + let bitmap = matches!(sh.fill, Some(Paint::Bitmap { .. })); + let Some(w) = sh.live_warp() else { + return Ok(json!({"element": id.0, "layer": layer.0, "warped": false, "bitmap": bitmap, "stale": sh.warp.is_some()})); + }; + let g = w.grid(); + let pins: Vec = w + .pins + .iter() + .map(|q| { + let at = el.transform.apply(q.at); + json!({"pin": q.id.0, "at": [at.x, at.y], "rest": [q.rest.x, q.rest.y]}) + }) + .collect(); + Ok(json!({ + "element": id.0, + "layer": layer.0, + "warped": true, + "bitmap": bitmap, + "bent": !w.at_rest(), + "resolution": w.resolution, + "columns": g.map_or(0, |g| g.nx), + "rows": g.map_or(0, |g| g.ny), + "vertices": g.map_or(0, |g| (g.nx + 1) * (g.ny + 1)), + "triangles": g.map_or(0, |g| 2 * g.nx * g.ny), + "pins": pins, + })) +} diff --git a/crates/engine/src/editing.rs b/crates/engine/src/editing.rs index 3e4de0e7..5024ceb3 100644 --- a/crates/engine/src/editing.rs +++ b/crates/engine/src/editing.rs @@ -27,7 +27,7 @@ pub fn specs() -> Vec { "Edit Symbols", "Edit", Some("Ctrl+E"), - "{id?: instance element id, symbol?: library symbol id} opens a symbol's timeline for editing: the instance `id` (default: the selected instance) in place, or a Library symbol at the stage's centre. Every command then works inside it. With nothing to open while a symbol is open, goes back to the document (Animate's Ctrl+E)", + "{id?: instance element id, symbol?: library symbol id} opens a symbol's timeline for editing: the instance `id` (default: the selected instance) in place, or a Library symbol at the stage's centre. A group (ADR 0073) or a drawing object (ADR 0080) opens in place the same way: inside, its raw shapes merge only with each other, and a drawing object closes as one object again (a group of its pieces when an edit left several). Every command then works inside it. With nothing to open while a symbol is open, goes back to the document (Animate's Ctrl+E)", false, edit as crate::RunFn, ), @@ -48,6 +48,17 @@ pub enum Opened { /// A group's members (ADR 0073): the group is [`EditLevel::instance`] on the timeline below, /// on the keyframe at [`EditLevel::frame`]. Group, + /// A drawing object opened in place (ADR 0080): while it is open it is a group of its raw + /// shapes, as [`Opened::Group`]; closing it makes it one drawing object again when it holds + /// one shape (a group of its pieces when it holds several, as Combine Objects' Union). + Drawing, +} + +impl Opened { + /// Whether this level opens a group's members (a group, or a drawing object being edited). + pub fn is_group(self) -> bool { + matches!(self, Opened::Group | Opened::Drawing) + } } /// A symbol or group open for editing, and what to go back to. @@ -62,6 +73,9 @@ pub struct EditLevel { pub layer: LayerId, pub frame: u32, pub selection: Selection, + /// A drawing object opened in place (ADR 0080): the document and state from before it was + /// opened, and the state right after, so closing it without an edit puts both back. + pub back: Option>, } impl EditLevel { @@ -69,7 +83,7 @@ impl EditLevel { pub fn symbol(&self) -> Option { match self.open { Opened::Symbol(id) => Some(id), - Opened::Group => None, + Opened::Group | Opened::Drawing => None, } } } @@ -103,7 +117,7 @@ fn walk<'a>(doc: &'a Document, scene: usize, editing: &[EditLevel]) -> (usize, & for (i, l) in editing.iter().enumerate() { let next = match l.open { Opened::Symbol(id) => doc.symbol(id).map(|s| &s.timeline), - Opened::Group => group_in(tl, l), + Opened::Group | Opened::Drawing => group_in(tl, l), }; match next { Some(t) => tl = t, @@ -199,7 +213,12 @@ impl Session { /// Whether a group is open for editing (ADR 0073). pub fn editing_group(&self) -> bool { - self.editing.last().is_some_and(|l| l.open == Opened::Group) + self.editing.last().is_some_and(|l| l.open.is_group()) + } + + /// Whether a drawing object is open for editing (ADR 0080). + pub fn editing_drawing(&self) -> bool { + self.editing.last().is_some_and(|l| l.open == Opened::Drawing) } /// Closes levels whose symbol or group is gone (an undo, a Library deletion, an ungroup), @@ -212,7 +231,7 @@ impl Session { } fn enter_level(&mut self, open: Opened, instance: Option<(LayerId, ElementId)>, transform: Affine, frame: u32) { - self.editing.push(EditLevel { open, instance, transform, layer: self.layer, frame: self.frame, selection: std::mem::take(&mut self.selection) }); + self.editing.push(EditLevel { open, instance, transform, layer: self.layer, frame: self.frame, selection: std::mem::take(&mut self.selection), back: None }); // The top layer inside, at the frame the instance shows. self.layer = self.timeline().layers.first().map_or(LayerId(0), |l| l.id); self.frame = frame.min(self.timeline().frame_count().saturating_sub(1)); @@ -224,9 +243,11 @@ impl Session { /// none is open. pub(crate) fn exit_level(&mut self) -> bool { let Some(l) = self.editing.pop() else { return false }; + let gone = l.open == Opened::Drawing && self.close_drawing(&l); self.layer = l.layer; self.frame = l.frame; self.selection = match l.instance { + Some(_) if gone => Selection::default(), Some((layer, id)) => Selection::only(layer, [id]), None => l.selection, }; @@ -364,6 +385,82 @@ fn placed(doc: &mut Document, timeline: Timeline, transform: Affine, frame: u32, Arc::new(layer) } +impl Session { + /// Opens the drawing object `id` on `layer` in place (ADR 0080): it becomes a group of one + /// raw shape (its own, unmoved), which the level opens. The picture doesn't change, so this + /// is no undo step; [`Session::close_drawing`] turns it back. + fn open_drawing(&mut self, layer: LayerId, id: ElementId) -> Result<()> { + let inner = ElementId(self.doc.alloc_id()); + let inner_layer = LayerId(self.doc.alloc_id()); + let frame = self.frame; + let tl = edited_mut(&mut self.doc, self.scene, &self.editing)?; + let l = tl.layer_mut(layer).ok_or_else(|| EngineError::State("that drawing object's layer is gone".into()))?; + let k = l.keyframe_index_at(frame).ok_or_else(|| EngineError::State("no keyframe here".into()))?; + let kf = l.keyframe_mut(k).ok_or_else(|| EngineError::State("no keyframe here".into()))?; + let at = kf.elements.iter().position(|e| e.id == id).ok_or_else(|| EngineError::State("that drawing object is not on this keyframe".into()))?; + let Some(el) = kf.elements.get(at).cloned() else { return Err(EngineError::State("that drawing object is not on this keyframe".into())) }; + let ElementKind::Shape(sh) = &el.kind else { return Err(EngineError::State("that is not a drawing object".into())) }; + let shape = Element { id: inner, name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::None, kind: ElementKind::Shape(anicraft_doc::Shape { merge: true, ..sh.clone() }) }; + let group = Element { id, name: el.name.clone(), transform: el.transform, color: el.color, kind: ElementKind::group(inner_layer, vec![Arc::new(shape)]) }; + if let Some(slot) = kf.elements.get_mut(at) { + *slot = Arc::new(group); + } + Ok(()) + } + + /// Closes a drawing object opened in place (level `l`, just taken off the stack): one shape + /// left inside is one drawing object again, exactly as it shows (its id, name and place); + /// nothing left, and it is gone; several, and they stay a group of raw shapes (what Combine + /// Objects' Union makes of shapes of several colours). Opening and closing it without an + /// edit leaves the document as it was, state and all. True when it is gone. + fn close_drawing(&mut self, l: &EditLevel) -> bool { + // Nothing changed since it was opened: the document goes back exactly as it was. + if let Some(back) = &l.back + && back.2 == self.state + { + self.doc = back.0.clone(); + self.state = back.1; + self.dl_cache.replace(None); + return false; + } + let Some((layer, id)) = l.instance else { return false }; + let below = self.editing.clone(); + let Ok(tl) = edited_mut(&mut self.doc, self.scene, &below) else { return false }; + let Some(lay) = tl.layer_mut(layer) else { return false }; + let Some(k) = lay.keyframe_index_at(l.frame) else { return false }; + let Some(kf) = lay.keyframe_mut(k) else { return false }; + let Some(at) = kf.elements.iter().position(|e| e.id == id) else { return false }; + let Some(group) = kf.elements.get(at).cloned() else { return false }; + let ElementKind::Group { members } = &group.kind else { return false }; + let inside: Vec> = members.layers.iter().filter_map(|m| m.keyframe_at(0)).flat_map(|k| k.elements.iter().cloned()).collect(); + let one_layer = members.layers.len() == 1; + let mut gone = false; + match inside.as_slice() { + [] if one_layer => { + kf.elements.remove(at); + gone = true; + } + [only] if one_layer => { + // Two colour effects only nest as one when one of them is none. + let color = match (group.color, only.color) { + (c, ColorEffect::None) | (ColorEffect::None, c) => Some(c), + _ => None, + }; + if let (ElementKind::Shape(sh), Some(color)) = (&only.kind, color) { + let object = Element { id, name: group.name.clone(), transform: group.transform.mul(&only.transform), color, kind: ElementKind::Shape(anicraft_doc::Shape { merge: false, ..sh.clone() }) }; + if let Some(slot) = kf.elements.get_mut(at) { + *slot = Arc::new(object); + } + } + } + _ => {} + } + self.state = crate::history::fresh_state(); + self.dl_cache.replace(None); + gone + } +} + /// Whether an instance of `sym` placed in the open symbol would put a symbol inside itself: `sym` /// is open, or uses an open one, however deep. pub(crate) fn would_nest(s: &Session, sym: SymbolId) -> bool { @@ -404,6 +501,17 @@ fn without(mut tl: Timeline, which: Option<(LayerId, ElementId)>) -> Timeline { tl } +/// Whether `symbol.edit` opens `e`: a symbol instance, a group or a drawing object. +pub fn opens(e: &Element) -> bool { + match &e.kind { + ElementKind::Symbol { .. } | ElementKind::Group { .. } => true, + // A warped shape (ADR 0079) keeps its outline as drawn under its mesh: it is edited + // through its pins, not opened. + ElementKind::Shape(sh) => !sh.merge && sh.warp.is_none(), + _ => false, + } +} + /// The instance `id` on a layer at the playhead of the timeline being edited, and its layer. fn instance(s: &Session, id: ElementId) -> Option<(LayerId, Arc)> { s.timeline().layers.iter().map(|l| l.id).find_map(|l| s.elements_on(l).into_iter().find(|e| e.id == id).map(|e| (l, e))) @@ -429,7 +537,7 @@ pub(crate) fn edit(s: &mut Session, p: &Value) -> Result { let id = match opt_u64(p, "id")? { Some(i) => ElementId(i), None => { - let picked: Vec = s.selection.on(s.layer).into_iter().filter(|id| instance(s, *id).is_some_and(|(_, e)| matches!(e.kind, ElementKind::Symbol { .. } | ElementKind::Group { .. }))).collect(); + let picked: Vec = s.selection.on(s.layer).into_iter().filter(|id| instance(s, *id).is_some_and(|(_, e)| opens(&e))).collect(); match picked.as_slice() { [one] => *one, // Nothing to open: Ctrl+E goes back to the document, as in Animate. @@ -437,8 +545,8 @@ pub(crate) fn edit(s: &mut Session, p: &Value) -> Result { s.exit_all(); return Ok(editing_json(s)); } - [] => return Err(EngineError::State("select a symbol instance or a group to edit it (or double-click it)".into())), - _ => return Err(EngineError::State("select one symbol instance or group to edit".into())), + [] => return Err(EngineError::State("select a symbol instance, a group or a drawing object to edit it (or double-click it)".into())), + _ => return Err(EngineError::State("select one symbol instance, group or drawing object to edit".into())), } } }; @@ -453,7 +561,24 @@ pub(crate) fn edit(s: &mut Session, p: &Value) -> Result { s.enter_level(Opened::Group, Some((layer, id)), below.mul(&el.transform), 0); return Ok(editing_json(s)); } - let ElementKind::Symbol { symbol, loop_mode, first_frame, .. } = el.kind else { return Err(EngineError::State("that is not a symbol instance or a group".into())) }; + // A drawing object opens the same way (ADR 0080), as a group of its one raw shape. + if matches!(&el.kind, ElementKind::Shape(sh) if !sh.merge && sh.warp.is_some()) { + return Err(EngineError::State("that drawing object is warped (Asset Warp): edit it with its pins, or remove its warp to edit its outline".into())); + } + if matches!(&el.kind, ElementKind::Shape(sh) if !sh.merge) { + if crate::cmds_group::open_groups(s) + 1 > anicraft_doc::MAX_GROUP_DEPTH { + return Err(EngineError::State(format!("groups nest at most {} deep", anicraft_doc::MAX_GROUP_DEPTH))); + } + let (was, state) = (s.doc.clone(), s.state); + s.open_drawing(layer, id)?; + s.state = crate::history::fresh_state(); + s.enter_level(Opened::Drawing, Some((layer, id)), below.mul(&el.transform), 0); + if let Some(l) = s.editing.last_mut() { + l.back = Some(Arc::new((was, state, s.state))); + } + return Ok(editing_json(s)); + } + let ElementKind::Symbol { symbol, loop_mode, first_frame, .. } = el.kind else { return Err(EngineError::State("that is not a symbol instance, a group or a drawing object".into())) }; let sym = s.doc.symbol(symbol).ok_or_else(|| EngineError::State("that instance's symbol is missing from the Library".into()))?; if s.editing.iter().any(|l| l.symbol() == Some(symbol)) { return Err(EngineError::State("that symbol is open already".into())); @@ -485,6 +610,7 @@ pub(crate) fn editing_json(s: &Session) -> Value { .iter() .map(|l| match l.symbol() { Some(id) => json!({"symbol": id.0, "name": s.doc.symbol(id).map(|x| x.name.clone()), "instance": l.instance.map(|(_, e)| e.0)}), + None if l.open == Opened::Drawing => json!({"drawing": l.instance.map(|(_, e)| e.0), "name": "Drawing Object", "instance": l.instance.map(|(_, e)| e.0)}), None => json!({"group": l.instance.map(|(_, e)| e.0), "name": "Group", "instance": l.instance.map(|(_, e)| e.0)}), }) .collect(); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 7f985cf7..99729b0e 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -8,9 +8,11 @@ mod anim; mod cmds_actions; mod cmds_bone; +mod cmds_warp; pub mod cmds_brush; mod cmds_camera; mod cmds_draw; +pub mod cmds_envelope; pub mod cmds_drop; pub mod cmds_erase; mod cmds_file; @@ -127,6 +129,7 @@ impl CommandSpec { pub fn commands() -> Vec { let mut v = Vec::new(); v.extend(cmds_file::specs()); + v.extend(cmds_envelope::specs()); v.extend(publish::specs()); v.extend(cmds_recent::specs()); v.extend(cmds_drop::specs()); @@ -135,6 +138,7 @@ pub fn commands() -> Vec { v.extend(cmds_layer::specs()); v.extend(cmds_camera::specs()); v.extend(cmds_bone::specs()); + v.extend(cmds_warp::specs()); v.extend(cmds_motion::specs()); v.extend(cmds_hints::specs()); v.extend(cmds_scene::specs()); @@ -356,6 +360,8 @@ pub struct Session { /// The user's own brush presets (ADR 0068). Like recent files they belong to the session /// and survive New and Open; the desktop app keeps them in its preferences. pub brushes: brush_library::BrushLibrary, + /// The open envelope (ADR 0080): view state over the shapes it bends, like a gesture. + pub(crate) envelope: Option, } /// Each piece of a marquee's cut, with the shape it was cut from. @@ -427,6 +433,7 @@ impl Session { published: std::collections::BTreeSet::new(), recent: cmds_recent::RecentFiles::default(), brushes: brush_library::BrushLibrary::default(), + envelope: None, } } @@ -1082,6 +1089,8 @@ mod tests_bone; #[cfg(test)] mod tests_shape_bone; #[cfg(test)] +mod tests_warp; +#[cfg(test)] mod merge_tests; #[cfg(test)] mod raw_tests; @@ -1125,3 +1134,5 @@ mod path_text_tests; mod group_tests; #[cfg(test)] mod swatch_tests; +#[cfg(test)] +mod parity_tests; diff --git a/crates/engine/src/merge.rs b/crates/engine/src/merge.rs index e4af024a..114ca901 100644 --- a/crates/engine/src/merge.rs +++ b/crates/engine/src/merge.rs @@ -197,7 +197,7 @@ fn remerge_doc(doc: &mut Document, parts: &[Part], cutter: Option<&Path>) -> Opt name: String::new(), transform: Affine::translate(c.x, c.y), color, - kind: ElementKind::Shape(Shape { path: Arc::new(piece.path.transformed(&Affine::translate(-c.x, -c.y))), fill: fill.map(|f| f.transformed(&Affine::translate(-c.x, -c.y))), stroke, fill_rule: Default::default(), merge: true }), + kind: ElementKind::Shape(Shape { path: Arc::new(piece.path.transformed(&Affine::translate(-c.x, -c.y))), fill: fill.map(|f| f.transformed(&Affine::translate(-c.x, -c.y))), stroke, fill_rule: Default::default(), merge: true, warp: None }), })); } Some(Remerged { out, picked, inside, from }) @@ -279,6 +279,11 @@ fn index_of(table: &mut Vec, v: T) -> u32 { /// `draw.drop`: the selected raw shapes go back into the drawing, on top (Animate merges a moved /// shape when it is let go). fn drop(s: &mut Session, _: &Value) -> Result { + drop_selected(s) +} + +/// [`drop`] on the active layer (also when an envelope closes, ADR 0080). +pub(crate) fn drop_selected(s: &mut Session) -> Result { let sel = s.selection.on(s.layer); let kf = s.editable_keyframe()?; let mut moving = Vec::new(); diff --git a/crates/engine/src/parity_tests.rs b/crates/engine/src/parity_tests.rs new file mode 100644 index 00000000..8d869360 --- /dev/null +++ b/crates/engine/src/parity_tests.rs @@ -0,0 +1,549 @@ +//! Drawing parity leftovers (ADR 0080): PolyStar options, Paint Selection and Paint Inside, +//! drawing objects edited in place, Envelope. + +use crate::Session; +use crate::cmds_erase::measure_els; +use anicraft_doc::{ElementKind, Paint, Rgba, Shape}; +use anicraft_geom::{Affine, Vec2}; +use serde_json::{Value, json}; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}")) +} + +fn blank(object: bool) -> Session { + let mut s = Session::new(anicraft_doc::Document::default()); + run(&mut s, "draw.object_drawing", json!({"on": object})); + s +} + +/// The keyframe's shapes, bottom to top, with their transforms. +fn shapes(s: &Session) -> Vec<(Shape, Affine)> { + s.visible_elements() + .iter() + .filter_map(|e| match &e.kind { + ElementKind::Shape(sh) => Some((sh.clone(), e.transform)), + _ => None, + }) + .collect() +} + +/// Total fill area on the active layer, raw shapes and drawing objects (even-odd loops summed +/// by sign; exact for polygons, within the flattening for curves). +fn fill_area(s: &Session) -> f64 { + let raw = measure_els(&s.visible_elements()).0; + let objects: f64 = shapes(s).iter().filter(|(sh, _)| sh.fill.is_some() && !sh.merge).map(|(sh, m)| area_of(&sh.path, m)).sum(); + raw + objects +} + +fn area_of(path: &anicraft_geom::Path, m: &Affine) -> f64 { + path.flatten(m, 0.005) + .iter() + .map(|pl| { + let n = pl.points.len(); + (0..n).map(|i| { + let (a, b) = (pl.points[i], pl.points[(i + 1) % n]); + f64::from(a.x) * f64::from(b.y) - f64::from(b.x) * f64::from(a.y) + }).sum::() * 0.5 + }) + .sum::() + .abs() +} + +/// What colour covers stage point `p` (the topmost shape containing it). +fn top_at(s: &Session, p: Vec2) -> Option { + shapes(s).iter().rev().find(|(sh, m)| sh.fill.is_some() && sh.path.contains(p, m, sh.fill_rule)).and_then(|(sh, _)| match sh.fill { + Some(Paint::Solid(c)) => Some(c), + _ => None, + }) +} + +// ----- PolyStar ---------------------------------------------------------------------------------- + +/// A polygon of n sides has area n/2 · r² · sin(2π/n); a star at point size 1 covers the same. +#[test] +fn polystar_polygon_and_star_areas() { + for object in [false, true] { + for n in [3u32, 6, 32] { + let mut s = blank(object); + run(&mut s, "draw.star", json!({"cx": 100, "cy": 100, "outer": 50, "shape": "polygon", "sides": n, "stroke": null, "fill": "#336699"})); + let want = f64::from(n) / 2.0 * 2500.0 * (std::f64::consts::TAU / f64::from(n)).sin(); + assert!((fill_area(&s) - want).abs() < want * 1e-4, "polygon {n} object {object}: {} vs {want}", fill_area(&s)); + let mut t = blank(object); + let v = run(&mut t, "draw.star", json!({"cx": 100, "cy": 100, "outer": 50, "sides": n, "point_size": 1.0, "stroke": null, "fill": "#336699"})); + assert_eq!(v["kind"], "star"); + assert!((fill_area(&t) - want).abs() < want * 1e-4, "star {n} at size 1"); + } + } +} + +/// A star's area is n · r · r_in · sin(π/n), r_in = r · size · cos(π/n); the old `inner` and +/// `points` params still work. +#[test] +fn polystar_star_follows_point_size() { + let mut s = blank(true); + run(&mut s, "draw.star", json!({"cx": 0, "cy": 0, "outer": 40, "sides": 5, "point_size": 0.3, "stroke": null, "fill": "#ff0000"})); + let half = std::f64::consts::PI / 5.0; + let inner = 40.0 * 0.3 * half.cos(); + let want = 5.0 * 40.0 * inner * half.sin(); + assert!((fill_area(&s) - want).abs() < want * 1e-4); + let mut t = blank(true); + run(&mut t, "draw.star", json!({"cx": 0, "cy": 0, "outer": 40, "inner": 10, "points": 6, "stroke": null, "fill": "#ff0000"})); + let want = 6.0 * 40.0 * 10.0 * (std::f64::consts::PI / 6.0).sin(); + assert!((fill_area(&t) - want).abs() < want * 1e-4); +} + +#[test] +fn polystar_refuses_bad_options() { + let mut s = blank(false); + for p in [ + json!({"cx": 0, "cy": 0, "outer": 40, "shape": "hexagon"}), + json!({"cx": 0, "cy": 0, "outer": 40, "sides": 2}), + json!({"cx": 0, "cy": 0, "outer": 40, "sides": 65}), + json!({"cx": 0, "cy": 0, "outer": 40, "point_size": 1.5}), + json!({"cx": 0, "cy": 0, "outer": 40, "point_size": -0.1}), + ] { + assert!(s.execute("draw.star", &p).is_err(), "{p}"); + } + assert!(s.visible_elements().is_empty()); +} + +/// Merge drawing: a polygon drawn over a raw fill of another colour cuts into it, as the other +/// shape tools do (ADR 0031). +#[test] +fn polystar_merges_like_the_other_shape_tools() { + let mut s = blank(false); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 200, "h": 200, "stroke": null, "fill": "#0000ff"})); + run(&mut s, "draw.star", json!({"cx": 100, "cy": 100, "outer": 50, "shape": "polygon", "sides": 4, "stroke": null, "fill": "#ff0000"})); + // The square's area stays: the polygon replaced what it covers. + assert!((fill_area(&s) - 40_000.0).abs() < 1.0, "{}", fill_area(&s)); + assert_eq!(top_at(&s, Vec2::new(100.0, 100.0)), Some(Rgba::hex(0xff0000))); + assert_eq!(top_at(&s, Vec2::new(5.0, 5.0)), Some(Rgba::hex(0x0000ff))); + assert!(shapes(&s).iter().all(|(sh, _)| sh.merge)); +} + +// ----- Paint Selection and Paint Inside ---------------------------------------------------------- + +/// Fill area of one colour on the active layer. +fn area_in(s: &Session, color: u32) -> f64 { + shapes(s).iter().filter(|(sh, _)| matches!(sh.fill, Some(Paint::Solid(c)) if c == Rgba::hex(color))).map(|(sh, m)| area_of(&sh.path, m)).sum() +} + +/// A blue square at 0..100 and a green one at 200..300 (raw fills, no lines). +fn two_squares() -> Session { + let mut s = blank(false); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "stroke": null, "fill": "#0000ff"})); + run(&mut s, "draw.rect", json!({"x": 200, "y": 0, "w": 100, "h": 100, "stroke": null, "fill": "#00ff00"})); + run(&mut s, "edit.deselect", json!({})); + s +} + +fn brush(s: &mut Session, mode: &str, from: [f32; 2], to: [f32; 2]) -> Value { + let pts: Vec<[f32; 2]> = (0..=40).map(|i| { + let t = i as f32 / 40.0; + [from[0] + (to[0] - from[0]) * t, from[1] + (to[1] - from[1]) * t] + }).collect(); + run(s, "draw.brush", json!({"points": pts, "size": 20, "smoothing": 0, "mode": mode, "color": "#ff0000"})) +} + +fn blue_id(s: &Session) -> u64 { + s.visible_elements().iter().find(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.fill == Some(Paint::Solid(Rgba::hex(0x0000ff))))).map(|e| e.id.0).expect("the blue square") +} + +/// Paint Selection: a stroke across both squares paints only the selected one, exactly over +/// the 100 × 20 band inside it. +#[test] +fn paint_selection_clips_to_the_selected_fills() { + let mut s = two_squares(); + let blue = blue_id(&s); + run(&mut s, "element.select", json!({"ids": [blue]})); + let v = brush(&mut s, "selection", [-60.0, 50.0], [360.0, 50.0]); + assert_eq!(v["merged"], true, "{v}"); + let red = area_in(&s, 0xff0000); + assert!((red - 2000.0).abs() < 2.0, "the band inside the blue square: {red}"); + assert!((area_in(&s, 0x0000ff) - 8000.0).abs() < 2.0, "the rest of the blue square: {}", area_in(&s, 0x0000ff)); + assert!((area_in(&s, 0x00ff00) - 10_000.0).abs() < 0.5, "the green square is not selected"); + assert_eq!(top_at(&s, Vec2::new(250.0, 50.0)), Some(Rgba::hex(0x00ff00))); + assert_eq!(top_at(&s, Vec2::new(150.0, 50.0)), None, "nothing between them"); + assert_eq!(top_at(&s, Vec2::new(50.0, 50.0)), Some(Rgba::hex(0xff0000))); + // The selection stays on the blue square's pieces and the paint, for the next stroke. + let sel = s.selection.on(s.layer); + let els = s.visible_elements(); + assert!(sel.len() >= 2, "{sel:?}"); + for id in &sel { + let e = els.iter().find(|e| e.id == *id).expect("selected element"); + let ElementKind::Shape(sh) = &e.kind else { panic!("a shape") }; + let b = sh.path.bounds().transformed(&e.transform); + assert!(b.min.x > -0.5 && b.max.x < 100.5, "inside the blue square: {b:?}"); + } + let v = brush(&mut s, "selection", [-60.0, 20.0], [360.0, 20.0]); + assert!(v["elements"].as_array().is_some_and(|a| !a.is_empty()), "a second stroke paints too"); + assert!((area_in(&s, 0xff0000) - 4000.0).abs() < 4.0, "{}", area_in(&s, 0xff0000)); +} + +/// With nothing selected (or a stroke that misses the selection), nothing changes and there is +/// no undo step. +#[test] +fn paint_selection_without_a_selection_changes_nothing() { + let mut s = two_squares(); + let steps = s.history_len(); + let doc = s.doc.clone(); + let v = brush(&mut s, "selection", [-60.0, 50.0], [360.0, 50.0]); + assert_eq!(v["painted"], false); + assert_eq!(s.history_len(), steps); + assert!(s.doc == doc); + let blue = blue_id(&s); + run(&mut s, "element.select", json!({"ids": [blue]})); + let v = brush(&mut s, "selection", [150.0, 300.0], [160.0, 400.0]); + assert_eq!(v["painted"], false, "{v}"); + assert_eq!(s.history_len(), steps); +} + +/// Paint Inside: started in the blue square, the stroke stays inside it (a half-round start +/// cap and a 50 × 20 band) and never reaches the green one. +#[test] +fn paint_inside_clips_to_the_fill_it_starts_on() { + let mut s = two_squares(); + brush(&mut s, "inside", [50.0, 50.0], [250.0, 50.0]); + let want = 50.0 * 20.0 + std::f64::consts::PI * 100.0 / 2.0; + let red = area_in(&s, 0xff0000); + assert!((red - want).abs() < want * 0.01, "{red} vs {want}"); + assert!((area_in(&s, 0x00ff00) - 10_000.0).abs() < 0.5); + assert!((area_in(&s, 0x0000ff) + red - 10_000.0).abs() < 2.0, "the paint replaced its part of the blue square"); +} + +/// Paint Inside started on empty stage inside a closed outline paints only that empty area, +/// under the line; started on open stage, only empty areas (as Paint Behind). +#[test] +fn paint_inside_empty_areas() { + let mut s = blank(false); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "fill": null, "stroke": "#000000", "stroke_width": 2})); + let lines = measure_els(&s.visible_elements()).1; + brush(&mut s, "inside", [50.0, 50.0], [250.0, 50.0]); + let want = 50.0 * 20.0 + std::f64::consts::PI * 100.0 / 2.0; + let red = area_in(&s, 0xff0000); + assert!((red - want).abs() < want * 0.01, "{red} vs {want}"); + assert_eq!(top_at(&s, Vec2::new(200.0, 50.0)), None, "nothing outside the outline"); + assert!((measure_els(&s.visible_elements()).1 - lines).abs() < 0.5, "the outline is whole"); + + let mut t = two_squares(); + brush(&mut t, "inside", [-100.0, 50.0], [50.0, 50.0]); + assert!((area_in(&t, 0x0000ff) - 10_000.0).abs() < 0.5, "the blue square is untouched"); + assert!(area_in(&t, 0xff0000) > 1000.0, "the empty stage took the paint"); +} + +/// A line across the selected fill stays: clipped paint goes under lines. +#[test] +fn paint_selection_leaves_lines() { + let mut s = two_squares(); + run(&mut s, "draw.line", json!({"x0": 50, "y0": -20, "x1": 50, "y1": 120, "stroke": "#000000", "stroke_width": 2})); + let lines = measure_els(&s.visible_elements()).1; + run(&mut s, "edit.select_all", json!({})); + brush(&mut s, "selection", [-60.0, 50.0], [360.0, 50.0]); + assert!((measure_els(&s.visible_elements()).1 - lines).abs() < 0.5, "the line is whole"); + // Both squares were selected: the band in each. + assert!((area_in(&s, 0xff0000) - 4000.0).abs() < 4.0, "{}", area_in(&s, 0xff0000)); +} + +/// As drawing objects, the clipped paint is an object of exactly the clipped outline. +#[test] +fn paint_inside_as_a_drawing_object() { + let mut s = blank(true); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "stroke": null, "fill": "#0000ff"})); + brush(&mut s, "inside", [50.0, 50.0], [250.0, 50.0]); + let want = 50.0 * 20.0 + std::f64::consts::PI * 100.0 / 2.0; + assert!((area_in(&s, 0xff0000) - want).abs() < want * 0.01); + assert!((area_in(&s, 0x0000ff) - 10_000.0).abs() < 0.5, "objects don't cut each other"); +} + +// ----- drawing objects edited in place ----------------------------------------------------------- + +/// A drawing object (an orange rectangle at 100..300 × 100..200) beside a raw blue square on the +/// same layer; returns the object's id. +fn object_and_raw() -> (Session, u64) { + let mut s = blank(false); + run(&mut s, "draw.rect", json!({"x": 400, "y": 100, "w": 100, "h": 100, "stroke": null, "fill": "#0000ff"})); + let v = run(&mut s, "draw.rect", json!({"x": 100, "y": 100, "w": 200, "h": 100, "stroke": null, "fill": "#ff8800", "object": true})); + let id = v["element"].as_u64().expect("the object"); + run(&mut s, "edit.deselect", json!({})); + (s, id) +} + +/// Double-clicking a drawing object opens it in place; opening and closing it without an edit +/// changes nothing: the same document and state, no undo step, the object selected. +#[test] +fn drawing_object_opens_and_closes_unchanged() { + let (mut s, id) = object_and_raw(); + let (doc, state, steps) = (s.doc.clone(), s.state, s.history_len()); + let v = run(&mut s, "symbol.edit", json!({"id": id})); + assert_eq!(v["editing"][0]["drawing"], id, "{v}"); + assert!(s.editing_drawing() && s.editing_group()); + // Inside, its one raw shape, where it showed. + let inside = s.visible_elements(); + assert_eq!(inside.len(), 1); + assert!(matches!(&inside[0].kind, ElementKind::Shape(sh) if sh.merge)); + run(&mut s, "symbol.exit", json!({})); + assert!(s.doc == doc, "the document is as it was"); + assert_eq!(s.state, state, "no unsaved change"); + assert_eq!(s.history_len(), steps); + assert_eq!(s.selection.id_list(), vec![id]); + assert!(s.visible_elements().iter().any(|e| e.id.0 == id && matches!(&e.kind, ElementKind::Shape(sh) if !sh.merge))); +} + +/// Inside, a line drawn across merges only with the object's own shape: it splits the fill, the +/// raw square outside is untouched, and closing it leaves a group of the pieces (several +/// shapes stay one object, as Combine Objects' Union makes them). +#[test] +fn drawing_object_merges_only_inside() { + let (mut s, id) = object_and_raw(); + run(&mut s, "symbol.edit", json!({"id": id})); + // Positions inside are in the object's own space (its centre at the origin). + run(&mut s, "draw.line", json!({"x0": 0, "y0": -100, "x1": 0, "y1": 100, "stroke": "#000000", "stroke_width": 2, "object": false})); + let inside = s.visible_elements(); + let fills = inside.iter().filter(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.fill.is_some())).count(); + assert_eq!(fills, 2, "the line cut the fill in two"); + run(&mut s, "symbol.exit", json!({})); + let els = s.visible_elements(); + let obj = els.iter().find(|e| e.id.0 == id).expect("the object stays, with its id"); + assert!(matches!(obj.kind, ElementKind::Group { .. }), "several pieces: a group"); + assert!((area_in(&s, 0x0000ff) - 10_000.0).abs() < 0.5, "the raw square outside is whole"); + assert_eq!(els.len(), 2); +} + +/// An edit that leaves one shape makes it one drawing object again, moved as edited; undo goes +/// back inside, and closing then gives the object as it was. +#[test] +fn drawing_object_edit_keeps_one_object() { + let (mut s, id) = object_and_raw(); + let before = s.element_bounds(anicraft_doc::ElementId(id)); + run(&mut s, "symbol.edit", json!({"id": id})); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "element.translate", json!({"dx": 30, "dy": 10})); + run(&mut s, "symbol.exit", json!({})); + let els = s.visible_elements(); + let obj = els.iter().find(|e| e.id.0 == id).expect("the object"); + assert!(matches!(&obj.kind, ElementKind::Shape(sh) if !sh.merge), "one drawing object again"); + let after = s.element_bounds(anicraft_doc::ElementId(id)); + assert!((after.min.x - before.min.x - 30.0).abs() < 1e-3 && (after.min.y - before.min.y - 10.0).abs() < 1e-3, "{before:?} → {after:?}"); + // Undo: inside again, before the move. + run(&mut s, "edit.undo", json!({})); + assert!(s.editing_drawing()); + run(&mut s, "symbol.exit", json!({})); + assert!((s.element_bounds(anicraft_doc::ElementId(id)).min.x - before.min.x).abs() < 1e-3); +} + +/// Everything inside deleted: closing it removes the object. +#[test] +fn an_emptied_drawing_object_is_gone() { + let (mut s, id) = object_and_raw(); + run(&mut s, "symbol.edit", json!({"id": id})); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "edit.delete", json!({})); + run(&mut s, "symbol.exit", json!({})); + assert!(s.visible_elements().iter().all(|e| e.id.0 != id)); + assert!(s.selection.is_empty()); + assert_eq!(s.visible_elements().len(), 1, "the raw square stays"); +} + +/// Raw shapes don't open (they are the drawing itself); the timeline stays one frame inside. +#[test] +fn only_drawing_objects_open() { + let (mut s, _) = object_and_raw(); + let raw = s.visible_elements().iter().find(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.merge)).map(|e| e.id.0).expect("raw"); + assert!(s.execute("symbol.edit", &json!({"id": raw})).is_err()); + let id = s.visible_elements().iter().find(|e| matches!(&e.kind, ElementKind::Shape(sh) if !sh.merge)).map(|e| e.id.0).expect("object"); + run(&mut s, "symbol.edit", json!({"id": id})); + assert!(s.execute("timeline.insert_keyframe", &json!({})).is_err(), "one frame inside"); +} + +// ----- Envelope ---------------------------------------------------------------------------------- + +fn points_of(v: &Value) -> Vec<[f32; 2]> { + v["points"].as_array().expect("points").iter().map(|p| [p[0].as_f64().unwrap_or(0.0) as f32, p[1].as_f64().unwrap_or(0.0) as f32]).collect() +} + +/// A 100 × 50 orange drawing object at (10, 20), selected, with an envelope open on it. +fn enveloped() -> (Session, Value) { + let mut s = blank(true); + run(&mut s, "draw.rect", json!({"x": 10, "y": 20, "w": 100, "h": 50, "stroke": null, "fill": "#ff8800"})); + let v = run(&mut s, "modify.envelope", json!({})); + (s, v) +} + +/// At rest the envelope is the identity: its mesh is evenly over the bounds, and moving it to +/// the rest mesh changes nothing. +#[test] +fn envelope_identity_at_rest() { + let (mut s, v) = enveloped(); + assert_eq!(v["bounds"], json!([10.0, 20.0, 100.0, 50.0])); + let pts = points_of(&v); + assert_eq!(pts.len(), 16); + assert_eq!(pts[0], [10.0, 20.0]); + assert_eq!(pts[15], [110.0, 70.0]); + let before = shapes(&s); + run(&mut s, "modify.envelope_move", json!({"points": v["points"]})); + let after = shapes(&s); + assert_eq!(before.len(), after.len()); + let flat = |sh: &Shape, m: &Affine| sh.path.flatten(m, 0.01).into_iter().flat_map(|p| p.points).collect::>(); + for ((a, ma), (b, mb)) in before.iter().zip(&after) { + let (pa, pb) = (flat(a, ma), flat(b, mb)); + assert_eq!(pa.len(), pb.len()); + assert!(pa.iter().zip(&pb).all(|(x, y)| x.distance(*y) < 1e-3)); + } + assert!((fill_area(&s) - 5000.0).abs() < 0.01); +} + +/// Lifting the top side's two handles by 30 bends the top edge up: the area grows by +/// lift · width / 2 (∫ B₁ + B₂ = ½), and each move is one undo step. +#[test] +fn envelope_bends_by_the_mesh() { + let (mut s, v) = enveloped(); + let steps = s.history_len(); + let pts = points_of(&v); + run(&mut s, "modify.envelope_move", json!({"index": 1, "x": pts[1][0], "y": pts[1][1] - 30.0})); + let v = run(&mut s, "modify.envelope_move", json!({"index": 2, "x": pts[2][0], "y": pts[2][1] - 30.0})); + assert_eq!(s.history_len(), steps + 2, "one step per move"); + let want = 5000.0 + 30.0 * 100.0 / 2.0; + assert!((fill_area(&s) - want).abs() < want * 1e-3, "{} vs {want}", fill_area(&s)); + // The inner points followed the side (Coons). + let now = points_of(&v); + assert!(now[5][1] < pts[5][1] - 1.0 && now[6][1] < pts[6][1] - 1.0); + // Undo: the mesh that made the shapes on the stage. + run(&mut s, "edit.undo", json!({})); + let (_, _, mesh) = s.envelope().expect("still open"); + assert!((mesh[2].y - pts[2][1]).abs() < 1e-4 && (mesh[1].y - (pts[1][1] - 30.0)).abs() < 1e-4); + run(&mut s, "edit.undo", json!({})); + let (_, rest, mesh) = s.envelope().expect("still open"); + assert_eq!(mesh, anicraft_geom::envelope::rest_mesh(&rest)); + assert!((fill_area(&s) - 5000.0).abs() < 0.01); +} + +/// Moves bend the shapes as they were when the envelope opened, so a move and its reverse +/// leave them exactly as they were. +#[test] +fn envelope_moves_do_not_compound() { + let (mut s, v) = enveloped(); + let pts = points_of(&v); + let before = shapes(&s); + run(&mut s, "modify.envelope_move", json!({"index": 15, "x": 160, "y": 120})); + run(&mut s, "modify.envelope_move", json!({"index": 15, "x": pts[15][0], "y": pts[15][1]})); + let after = shapes(&s); + assert!((fill_area(&s) - 5000.0).abs() < 0.01); + assert_eq!(before[0].0.path.cmds.len(), after[0].0.path.cmds.len()); +} + +/// Symbols, text and groups can't be bent; nothing open is an error for a move. +#[test] +fn envelope_refuses_what_it_cannot_bend() { + let mut s = blank(true); + assert!(s.execute("modify.envelope", &json!({})).is_err(), "nothing selected"); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 50, "h": 50, "fill": "#ff0000"})); + run(&mut s, "modify.convert_to_symbol", json!({})); + assert!(s.execute("modify.envelope", &json!({})).is_err(), "a symbol instance"); + assert!(s.execute("modify.envelope_move", &json!({"index": 0, "x": 1, "y": 1})).is_err()); + let (mut t, _) = enveloped(); + for p in [json!({"index": 16, "x": 0, "y": 0}), json!({"points": [[0, 0]]}), json!({"index": 0, "x": 1e9, "y": 0}), json!({})] { + assert!(t.execute("modify.envelope_move", &p).is_err(), "{p}"); + } + // A new selection ends it. + run(&mut t, "edit.deselect", json!({})); + assert!(t.envelope().is_none()); +} + +/// Raw shapes bent by an envelope merge with the drawing they land on when it closes. +#[test] +fn envelope_close_merges_raw_shapes() { + let mut s = blank(false); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "stroke": null, "fill": "#0000ff"})); + run(&mut s, "draw.rect", json!({"x": 200, "y": 0, "w": 100, "h": 100, "stroke": null, "fill": "#ff0000"})); + // The red square is selected (the last drawn): bend its left side over the blue one. + let v = run(&mut s, "modify.envelope", json!({})); + let pts = points_of(&v); + let mut m = pts.clone(); + for i in [0usize, 4, 8, 12] { + m[i][0] -= 150.0; + } + run(&mut s, "modify.envelope_move", json!({"points": m})); + run(&mut s, "modify.envelope_close", json!({})); + assert!(s.envelope().is_none()); + // The red covers 50 of the blue square's width now. + assert!((area_in(&s, 0x0000ff) - 5000.0).abs() < 5.0, "{}", area_in(&s, 0x0000ff)); + assert!((area_in(&s, 0xff0000) - 25_000.0).abs() < 25.0, "{}", area_in(&s, 0xff0000)); +} + +/// A drag's moves are one undo step and remember only the last mesh; undo goes back to before +/// the drag with the envelope still open. +#[test] +fn envelope_drag_is_one_step() { + let (mut s, v) = enveloped(); + let pts = points_of(&v); + let steps = s.history_len(); + s.begin_gesture("Envelope"); + for k in 1..=300 { + run(&mut s, "modify.envelope_move", json!({"index": 15, "x": pts[15][0] + k as f32 * 0.1, "y": pts[15][1]})); + } + s.end_gesture(); + assert_eq!(s.history_len(), steps + 1); + assert!(s.envelope.as_ref().is_some_and(|e| e.states_len() == 2)); + run(&mut s, "edit.undo", json!({})); + let (_, rest, mesh) = s.envelope().expect("open"); + assert_eq!(mesh, anicraft_geom::envelope::rest_mesh(&rest)); + run(&mut s, "edit.redo", json!({})); + let (_, _, mesh) = s.envelope().expect("open"); + assert!((mesh[15].x - (pts[15][0] + 30.0)).abs() < 1e-3); +} + +/// Timings for ADR 0080 (`cargo test --release -p anicraft-engine parity_timings -- --ignored --nocapture`). +#[test] +#[ignore = "a measurement"] +fn parity_timings() { + let median = |mut v: Vec| { + v.sort_by(f64::total_cmp); + v[v.len() / 2] + }; + let wave: Vec<[f32; 2]> = (0..=400).map(|i| [20.0 + i as f32 * 2.5, 300.0 + (i as f32 * 0.05).sin() * 120.0]).collect(); + for mode in ["normal", "inside", "selection"] { + let mut times = Vec::new(); + for _ in 0..9 { + let mut s = blank(false); + run(&mut s, "draw.ellipse", json!({"x": 100, "y": 100, "w": 800, "h": 400, "fill": "#3d8bfd", "stroke": "#000000", "stroke_width": 2})); + run(&mut s, "edit.deselect", json!({})); + if mode == "selection" { + run(&mut s, "edit.select_all", json!({})); + } + let t = std::time::Instant::now(); + run(&mut s, "draw.brush", json!({"points": wave, "size": 30, "mode": mode, "color": "#ff0000"})); + times.push(t.elapsed().as_secs_f64() * 1e3); + } + eprintln!("brush 1000 px wave, size 30, {mode}: {:.2} ms", median(times)); + } + let mut times = Vec::new(); + for _ in 0..9 { + let mut s = blank(true); + run(&mut s, "draw.star", json!({"cx": 400, "cy": 300, "outer": 250, "sides": 32, "point_size": 0.5, "fill": "#ff0000"})); + run(&mut s, "draw.ellipse", json!({"x": 100, "y": 100, "w": 600, "h": 400, "fill": "#00ff00"})); + run(&mut s, "edit.select_all", json!({})); + let v = run(&mut s, "modify.envelope", json!({})); + let pts = points_of(&v); + let t = std::time::Instant::now(); + for k in 0..10 { + run(&mut s, "modify.envelope_move", json!({"index": 1, "x": pts[1][0], "y": pts[1][1] - 10.0 * k as f32})); + } + times.push(t.elapsed().as_secs_f64() * 1e3 / 10.0); + } + eprintln!("envelope move, a 32-point star and an oval: {:.2} ms", median(times)); +} + +/// Warped artwork (ADR 0079) neither opens in place nor takes an envelope: its warp keeps the +/// outline as drawn on every keyframe. +#[test] +fn warped_objects_refuse_envelope_and_editing() { + let mut s = blank(true); + let v = run(&mut s, "draw.rect", json!({"x": 10, "y": 20, "w": 100, "h": 50, "stroke": null, "fill": "#ff8800"})); + let id = v["element"].as_u64().expect("the object"); + run(&mut s, "warp.add", json!({"element": id})); + run(&mut s, "element.select", json!({"ids": [id]})); + assert!(s.execute("modify.envelope", &json!({})).is_err()); + assert!(s.execute("symbol.edit", &json!({"id": id})).is_err()); + assert!(s.editing.is_empty()); +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 1bae2426..06acd4a2 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -714,6 +714,25 @@ fn panic_hunt_every_command() { } assert_eq!((tail, sb1, sb2), (3, 100, 103), "the hostile params name these"); shaped.set_frame(4); + // Asset Warp (ADR 0079): a warped rectangle and bitmap, a pin moved at frame 8 inside a + // tween, the playhead mid-tween, the rectangle selected. + let (mut warped, wr, wb) = crate::tests_warp::warped(); + let pin = |s: &mut Session, el: u64, x: f32, y: f32| s.execute("warp.pin_add", &json!({"element": el, "x": x, "y": y})).unwrap()["pin"].as_u64().unwrap(); + let (wp1, wp2) = (pin(&mut warped, wr, 110.0, 140.0), pin(&mut warped, wr, 290.0, 140.0)); + let wp3 = pin(&mut warped, wb, 290.0, 230.0); + for (id, p) in [("timeline.goto", json!({"frame": 8})), ("timeline.insert_keyframe", json!({})), ("timeline.goto", json!({"frame": 0})), ("timeline.create_tween", json!({})), ("warp.pin_move", json!({"element": wr, "pin": wp2, "x": 300, "y": 220, "frame": 8}))] { + warped.execute(id, &p).unwrap(); + } + warped.selection = crate::Selection::only(warped.layer, [anicraft_doc::ElementId(wr)]); + warped.set_frame(4); + hostile.extend([ + json!({"element": wr, "pin": wp2, "x": 1e30, "y": -1e30, "dx": 1e7, "dy": -1e7, "frame": 99_999, "resolution": 0}), + json!({"element": wr, "pin": wp1, "x": 200, "y": 140, "dx": f64::NAN, "resolution": 48}), + json!({"element": wb, "pin": wp3, "x": 0, "y": 0, "dx": -1e6, "dy": 1e6, "resolution": u64::MAX}), + json!({"element": wb, "pin": u64::MAX, "x": 290, "y": 231, "frame": 4, "resolution": 2}), + json!({"element": u64::MAX, "pin": "a", "x": "b", "y": [1], "resolution": -3}), + json!({"element": wr, "x": 299.9, "y": 179.9, "pin": wp1, "dx": 0.0001}), + ]); // Raw drawings and an object on two layers, selected on both through a marquee's cut that // is still provisional (ADR 0041, 0044). let mut layered = Session::default(); @@ -830,7 +849,7 @@ fn panic_hunt_every_command() { let inner = grouped.visible_elements().into_iter().find(|e| matches!(e.kind, anicraft_doc::ElementKind::Group { .. })).map(|e| e.id.0).unwrap(); grouped.execute("symbol.edit", &json!({"id": inner})).unwrap(); assert_eq!(grouped.editing.len(), 2, "the fuzz starts inside a group inside a group"); - for start in [Session::default(), Session::new(sample::demo()), Session::new(with_sound), on_path, raw, rig, shaped, layered, in_symbol, keyed, library, button, grouped] { + for start in [Session::default(), Session::new(sample::demo()), Session::new(with_sound), on_path, raw, rig, shaped, warped, layered, in_symbol, keyed, library, button, grouped] { let mut s = start; for spec in commands().iter().filter(|c| !skip(c.id)) { for p in &hostile { diff --git a/crates/engine/src/tests_warp.rs b/crates/engine/src/tests_warp.rs new file mode 100644 index 00000000..1a3aab39 --- /dev/null +++ b/crates/engine/src/tests_warp.rs @@ -0,0 +1,264 @@ +//! Asset Warp end to end (ADR 0079): meshes on a shape and a bitmap, pins added, moved and +//! removed, keyframed and tweened, undo, refusals, stale artwork, the file format, renders and +//! exports, and plug-in policy. + +use super::*; +use anicraft_doc::warp::PinId; +use anicraft_doc::{Document, ElementKind, Shape, Stage}; +use anicraft_geom::{Path, Vec2}; +use anicraft_render::render_frame; +use serde_json::json; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + match s.execute(id, &p) { + Ok(v) => v, + Err(e) => panic!("{id} {p}: {e}"), + } +} + +fn err(s: &mut Session, id: &str, p: Value) -> String { + match s.execute(id, &p) { + Ok(v) => panic!("{id} {p} should fail, gave {v}"), + Err(e) => e.to_string(), + } +} + +/// The shape of element `id` as it shows at `frame`. +fn shape_at(s: &Session, id: u64, frame: u32) -> Shape { + s.timeline() + .layers + .iter() + .find_map(|l| { + let (_, els) = evaluate_layer_elements(l, frame)?; + els.iter().find(|e| e.id.0 == id).and_then(|e| match &e.kind { + ElementKind::Shape(sh) => Some(sh.clone()), + _ => None, + }) + }) + .unwrap_or_else(|| panic!("no shape {id} at frame {frame}")) +} + +/// A 400 × 300 stage, 20 frames, with a blue 200 × 80 drawing object at (100, 100) and a +/// 40 × 20 bitmap placed at (300, 230). Returns the session, the rectangle and the bitmap. +pub(crate) fn warped() -> (Session, u64, u64) { + let d = Document { stage: Stage { width: 400, height: 300, ..Stage::default() }, ..Document::default() }; + let mut s = Session::new(d); + let rect = run(&mut s, "draw.rect", json!({"x": 100, "y": 100, "w": 200, "h": 80, "fill": "#3080ff", "object": true}))["element"].as_u64().unwrap(); + let bm = anicraft_doc::BitmapId(s.doc.alloc_id()); + let mut rgba = Vec::new(); + for y in 0..20u32 { + for x in 0..40u32 { + rgba.extend_from_slice(&[(x * 6) as u8, (y * 12) as u8, 128, 255]); + } + } + let png = anicraft_render::encode_png(40, 20, &rgba).unwrap(); + s.doc.bitmaps.push(Arc::new(anicraft_doc::Bitmap::from_png(bm, "ramp.png", png).unwrap())); + let bitmap = run(&mut s, "library.place", json!({"bitmap": bm.0, "x": 300, "y": 230}))["element"].as_u64().unwrap(); + run(&mut s, "timeline.insert_frame", json!({"frame": 19})); + run(&mut s, "timeline.goto", json!({"frame": 0})); + (s, rect, bitmap) +} + +fn pin_add(s: &mut Session, el: u64, x: f32, y: f32) -> u64 { + run(s, "warp.pin_add", json!({"element": el, "x": x, "y": y}))["pin"].as_u64().unwrap() +} + +#[test] +fn pins_bend_a_shape_and_the_rest_pose_is_the_drawing() { + let (mut s, rect, _) = warped(); + let drawn = shape_at(&s, rect, 0).path.clone(); + let before = render_frame(&s.doc, 0, 1.0).unwrap().data; + let v = run(&mut s, "warp.add", json!({"element": rect})); + assert_eq!((v["created"].as_bool(), v["resolution"].as_u64(), v["columns"].as_u64(), v["rows"].as_u64()), (Some(true), Some(12), Some(12), Some(5))); + let a = pin_add(&mut s, rect, 110.0, 140.0); + let b = pin_add(&mut s, rect, 200.0, 140.0); + let c = pin_add(&mut s, rect, 290.0, 140.0); + // Pins alone move nothing: the outline is the drawing, bit for bit, and so is the render. + let sh = shape_at(&s, rect, 0); + assert_eq!(*sh.path, *drawn); + assert_eq!(render_frame(&s.doc, 0, 1.0).unwrap().data, before); + let info = run(&mut s, "warp.info", json!({"element": rect})); + assert_eq!((info["pins"].as_array().map(Vec::len), info["bent"].as_bool()), (Some(3), Some(false))); + // Dragging the right pin down bends the right end most. + run(&mut s, "warp.pin_move", json!({"element": rect, "pin": c, "x": 290, "y": 200})); + let w = shape_at(&s, rect, 0).live_warp().cloned().unwrap(); + // The rectangle's own space is centred on it. + let local = |x: f32, y: f32| Vec2::new(x - 200.0, y - 140.0); + let moved = |x: f32| w.map(local(x, 140.0)).distance(local(x, 140.0)); + assert!(moved(280.0) > 40.0 && moved(250.0) > moved(150.0) && moved(120.0) < 3.0, "{} {} {}", moved(280.0), moved(250.0), moved(120.0)); + assert!(w.pin(PinId(a)).is_some() && w.pin(PinId(b)).is_some()); + assert_ne!(render_frame(&s.doc, 0, 1.0).unwrap().data, before); + // Off the artwork there is nothing to pin; a pin can't go twice in one place. + assert!(err(&mut s, "warp.pin_add", json!({"element": rect, "x": 10, "y": 10})).contains("on the artwork")); + assert!(err(&mut s, "warp.pin_add", json!({"element": rect, "x": 110, "y": 140})).contains("already")); +} + +#[test] +fn a_drag_is_one_undo_step_and_remove_restores_the_drawing() { + let (mut s, rect, _) = warped(); + let drawn = shape_at(&s, rect, 0).path.clone(); + pin_add(&mut s, rect, 110.0, 140.0); + let p = pin_add(&mut s, rect, 290.0, 140.0); + let at = |s: &Session| shape_at(s, rect, 0).live_warp().and_then(|w| w.pin(PinId(p)).map(|q| q.at)).unwrap(); + s.begin_gesture("Move Pin"); + for i in 1..=10 { + run(&mut s, "warp.pin_move", json!({"element": rect, "pin": p, "dx": 0, "dy": 3})); + assert_eq!(at(&s).y, 3.0 * i as f32); + } + s.end_gesture(); + s.undo().unwrap(); + assert_eq!(at(&s), Vec2::new(90.0, 0.0), "the whole drag undoes at once"); + s.redo().unwrap(); + assert_eq!(at(&s).y, 30.0); + // Removing a pin: the artwork follows the pins that are left (one pin: it just moves). + run(&mut s, "warp.pin_remove", json!({"element": rect, "pin": p})); + assert!(shape_at(&s, rect, 0).live_warp().unwrap().at_rest()); + run(&mut s, "warp.remove", json!({"element": rect})); + let sh = shape_at(&s, rect, 0); + assert!(sh.warp.is_none() && *sh.path == *drawn); + assert!(err(&mut s, "warp.remove", json!({"element": rect})).contains("no warp")); +} + +#[test] +fn pin_poses_tween_between_keyframes_with_easing() { + let (mut s, rect, _) = warped(); + pin_add(&mut s, rect, 110.0, 140.0); + let p = pin_add(&mut s, rect, 290.0, 140.0); + // A keyframe at frame 11 holding the same mesh, a classic tween, then the pose there. + let lid = s.timeline().layers[0].id.0; + run(&mut s, "layer.select", json!({"layer": lid})); + run(&mut s, "timeline.goto", json!({"frame": 10})); + run(&mut s, "timeline.insert_keyframe", json!({})); + run(&mut s, "timeline.goto", json!({"frame": 0})); + run(&mut s, "timeline.create_tween", json!({})); + run(&mut s, "warp.pin_move", json!({"element": rect, "pin": p, "x": 290, "y": 240, "frame": 10})); + let pin_y = |s: &Session, f: u32| shape_at(s, rect, f).live_warp().and_then(|w| w.pin(PinId(p)).map(|q| q.at.y)).unwrap(); + assert_eq!((pin_y(&s, 0), pin_y(&s, 10)), (0.0, 100.0)); + assert!((pin_y(&s, 5) - 50.0).abs() < 1e-3, "halfway: {}", pin_y(&s, 5)); + // The tweened outline is the mesh bent by the halfway pins (not a blend of two outlines). + let mid = shape_at(&s, rect, 5); + let mut want = shape_at(&s, rect, 0).live_warp().cloned().unwrap(); + if let Some(q) = want.pins.iter_mut().find(|q| q.id == PinId(p)) { + q.at.y = 50.0; + } + assert_eq!(*mid.path, *want.outline()); + // Easing applies to the pins. + run(&mut s, "timeline.set_easing", json!({"easing": "quad_in"})); + assert!(pin_y(&s, 5) < 40.0, "eased in: {}", pin_y(&s, 5)); + // A pin added later lands on both keyframes, where the artwork shows on each. + let late = pin_add(&mut s, rect, 200.0, 110.0); + for f in [0, 10] { + assert!(shape_at(&s, rect, f).live_warp().unwrap().pin(PinId(late)).is_some(), "frame {f}"); + } + // Moving a pin mid-tween keys the frame with what it shows. + run(&mut s, "warp.pin_move", json!({"element": rect, "pin": late, "dx": 0, "dy": -5, "frame": 4})); + assert!(s.timeline().layers[0].keyframe_starting_at(4).is_some()); +} + +#[test] +fn a_bitmap_bends_in_every_renderer_and_export() { + let (mut s, _, bmp) = warped(); + let before = render_frame(&s.doc, 0, 1.0).unwrap(); + pin_add(&mut s, bmp, 285.0, 230.0); + let p = pin_add(&mut s, bmp, 315.0, 230.0); + assert_eq!(render_frame(&s.doc, 0, 1.0).unwrap().data, before.data, "pinned, not yet moved: exactly as drawn"); + run(&mut s, "warp.pin_move", json!({"element": bmp, "pin": p, "x": 315, "y": 270})); + let after = render_frame(&s.doc, 0, 1.0).unwrap(); + // The bent image covers pixels below where the image was. + let covered = |pm: &anicraft_render::Pixmap, x: u32, y: u32| pm.pixel(x, y).is_some_and(|c| c[2] > 0.45 && c[0] < 0.95); + assert!(!covered(&before, 318, 262) && covered(&after, 318, 262)); + let info = run(&mut s, "warp.info", json!({"element": bmp})); + assert_eq!((info["bitmap"].as_bool(), info["bent"].as_bool()), (Some(true), Some(true))); + // SVG bakes the bent image; the HTML page reports it. + let svg = crate::cmds_file::frame_svg(&s.doc, 0); + assert!(svg.contains(" p); + // Older files (no warp) still read; a warped file read by this build keeps its shape. + let plain = crate::format::to_json(&warped().0.doc).unwrap(); + assert!(!plain.contains("\"warp\"")); + // Another tool changes the outline: the warp no longer shows, and the next pin move + // starts from the shape as it is, with its pins where they show (nothing jumps). + let edited = { + let l = Arc::make_mut(&mut t.doc.timeline_mut(0).layers[0]); + let k = Arc::make_mut(&mut l.keyframes[0]); + let e = k.elements.iter_mut().find(|e| e.id.0 == rect).unwrap(); + let ElementKind::Shape(sh) = &mut Arc::make_mut(e).kind else { panic!() }; + sh.path = Arc::new(sh.path.transformed(&anicraft_geom::Affine::translate(5.0, 0.0))); + sh.path.clone() + }; + assert!(shape_at(&t, rect, 0).live_warp().is_none()); + assert_eq!(*shape_at(&t, rect, 0).path, *edited); + run(&mut t, "warp.pin_move", json!({"element": rect, "pin": p, "dx": 0, "dy": 0})); + let sh = shape_at(&t, rect, 0); + assert!(sh.live_warp().is_some_and(|w| w.at_rest()) && *sh.path == *edited); +} + +#[test] +fn warp_refusals() { + let (mut s, rect, _) = warped(); + // Nothing selected and no element. + s.selection.clear(); + assert!(err(&mut s, "warp.add", json!({})).contains("select")); + assert!(err(&mut s, "warp.add", json!({"element": rect, "resolution": 1})).contains("resolution")); + assert!(err(&mut s, "warp.add", json!({"element": 999_999})).contains("no element")); + assert!(err(&mut s, "warp.pin_move", json!({"element": rect, "pin": 5, "x": 1, "y": 1})).contains("no warp")); + // Symbols and text aren't warped. + let sym = run(&mut s, "draw.ellipse", json!({"x": 10, "y": 10, "w": 30, "h": 30, "object": true}))["element"].as_u64().unwrap(); + run(&mut s, "modify.convert_to_symbol", json!({"name": "Dot"})); + let inst = s.selection.on(s.layer).first().map(|e| e.0).unwrap_or(sym); + assert!(err(&mut s, "warp.add", json!({"element": inst})).contains("shapes and bitmaps")); + // A locked layer. + let lid = s.timeline().layers[0].id.0; + run(&mut s, "layer.toggle_lock", json!({"layer": lid})); + assert!(err(&mut s, "warp.pin_add", json!({"element": rect, "x": 150, "y": 140})).contains("locked")); +} + +#[test] +fn plug_ins_may_warp() { + assert!(crate::cmds_plugin::plugin_may_call("warp.pin_move").is_ok()); + assert!(crate::cmds_plugin::plugin_may_call("warp.add").is_ok()); +} + +#[test] +fn warp_measured() { + // A 1,200-anchor outline on a 48 × 48 mesh with 32 pins, bent: release numbers go in the ADR. + let mut p = Path::new(); + p.move_to(Vec2::new(0.0, 0.0)); + for i in 1..600 { + p.line_to(Vec2::new(i as f32, (i as f32 * 0.05).sin() * 20.0)); + } + for i in (0..600).rev() { + p.line_to(Vec2::new(i as f32, 200.0 + (i as f32 * 0.05).cos() * 20.0)); + } + p.close(); + let mut w = anicraft_doc::warp::Warp::new(Arc::new(p), 48); + w.pins = (0..32).map(|i| anicraft_doc::warp::Pin { id: PinId(i), rest: Vec2::new(i as f32 * 18.0, 100.0), at: Vec2::new(i as f32 * 18.0, 100.0 + (i % 5) as f32 * 9.0) }).collect(); + let t = std::time::Instant::now(); + let n = 20; + let mut cmds = 0; + for _ in 0..n { + cmds += w.outline().cmds.len(); + } + eprintln!("warp: bend 1,200 anchors on 48×48 with 32 pins: {:.3} ms per frame ({} commands)", t.elapsed().as_secs_f64() * 1000.0 / f64::from(n), cmds / n as usize); +} diff --git a/crates/geom/src/envelope.rs b/crates/geom/src/envelope.rs new file mode 100644 index 00000000..1ab79870 --- /dev/null +++ b/crates/geom/src/envelope.rs @@ -0,0 +1,256 @@ +//! Envelope (ADR 0080): bending outlines by a bicubic Bézier patch, as Animate's Modify › +//! Transform › Envelope does. +//! +//! The patch has 4 × 4 control points over a rest rectangle. A point at `(u, v)` of the +//! rectangle (0 to 1 across and down) goes to `Σ Bᵢ(u) Bⱼ(v) Pᵢⱼ`, the Bernstein polynomials of +//! degree 3. At rest the control points are evenly spaced (a third of the way apart), and the +//! map is exactly the identity (Bernstein polynomials reproduce linear functions). +//! +//! The image of a cubic under the patch is a curve of degree 9, so it is approximated: each +//! segment is cut in halves until the cubic through its mapped control points is within the +//! tolerance of the true image at its quarter points. A straight segment that stays straight (any +//! affine part of the patch) stays one line. + +use crate::{Path, PathCmd, Rect, Vec2}; + +/// Most times a segment is halved. +const MAX_DEPTH: u32 = 10; +/// Most commands a bent path may have; beyond it [`warp`] declines. +pub const MAX_COMMANDS: usize = 200_000; + +/// The patch's control points, row by row from the top-left (`points[4 * row + column]`). +pub type Mesh = [Vec2; 16]; + +/// The mesh that leaves everything where it is: control points evenly over `rest`. +pub fn rest_mesh(rest: &Rect) -> Mesh { + let mut m = [Vec2::ZERO; 16]; + for (k, p) in m.iter_mut().enumerate() { + let (i, j) = ((k % 4) as f32, (k / 4) as f32); + *p = Vec2::new(rest.min.x + rest.width() * i / 3.0, rest.min.y + rest.height() * j / 3.0); + } + m +} + +/// The indices of the boundary handles, clockwise from the top-left corner: corners and the two +/// tangent points of each side (the inner four follow them, [`coons_interior`]). +pub const BOUNDARY: [usize; 12] = [0, 1, 2, 3, 7, 11, 15, 14, 13, 12, 8, 4]; +/// The corners, clockwise from the top-left. +pub const CORNERS: [usize; 4] = [0, 3, 15, 12]; + +/// Sets the four inner control points from the boundary, as a bicubic Coons patch does: the +/// sides bend the inside smoothly, and a rest boundary gives the rest mesh. +pub fn coons_interior(m: &mut Mesh) { + let p = |r: usize, c: usize| m[4 * r + c]; + let blend = |a: Vec2, b: Vec2, c: Vec2, d: Vec2, e: Vec2, f: Vec2, g: Vec2, h: Vec2| (a * -4.0 + (b + c) * 6.0 - (d + e) * 2.0 + (f + g) * 3.0 - h) * (1.0 / 9.0); + let p11 = blend(p(0, 0), p(0, 1), p(1, 0), p(0, 3), p(3, 0), p(3, 1), p(1, 3), p(3, 3)); + let p12 = blend(p(0, 3), p(0, 2), p(1, 3), p(0, 0), p(3, 3), p(3, 2), p(1, 0), p(3, 0)); + let p21 = blend(p(3, 0), p(3, 1), p(2, 0), p(3, 3), p(0, 0), p(0, 1), p(2, 3), p(0, 3)); + let p22 = blend(p(3, 3), p(3, 2), p(2, 3), p(3, 0), p(0, 3), p(0, 2), p(2, 0), p(0, 0)); + m[5] = p11; + m[6] = p12; + m[9] = p21; + m[10] = p22; +} + +fn bernstein(t: f64) -> [f64; 4] { + let u = 1.0 - t; + [u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t] +} + +/// Where the patch puts `p` (a point of the rest rectangle's plane; outside it, the patch's +/// polynomial carries on). +pub fn map(mesh: &Mesh, rest: &Rect, p: Vec2) -> Vec2 { + let (w, h) = (f64::from(rest.width()), f64::from(rest.height())); + if !(w > 1e-9 && h > 1e-9) { + return p; + } + let u = (f64::from(p.x) - f64::from(rest.min.x)) / w; + let v = (f64::from(p.y) - f64::from(rest.min.y)) / h; + let (bu, bv) = (bernstein(u), bernstein(v)); + let (mut x, mut y) = (0.0f64, 0.0f64); + for (k, q) in mesh.iter().enumerate() { + let wgt = bu[k % 4] * bv[k / 4]; + x += wgt * f64::from(q.x); + y += wgt * f64::from(q.y); + } + Vec2::new(x as f32, y as f32) +} + +fn cubic_at(c: &[Vec2; 4], t: f32) -> Vec2 { + let u = 1.0 - t; + c[0] * (u * u * u) + c[1] * (3.0 * u * u * t) + c[2] * (3.0 * u * t * t) + c[3] * (t * t * t) +} + +fn split(c: &[Vec2; 4]) -> ([Vec2; 4], [Vec2; 4]) { + let (ab, bc, cd) = (c[0].lerp(c[1], 0.5), c[1].lerp(c[2], 0.5), c[2].lerp(c[3], 0.5)); + let (abc, bcd) = (ab.lerp(bc, 0.5), bc.lerp(cd, 0.5)); + let m = abc.lerp(bcd, 0.5); + ([c[0], ab, abc, m], [m, bcd, cd, c[3]]) +} + +/// Whether every mesh point is finite and the rest rectangle has an area. +pub fn valid(mesh: &Mesh, rest: &Rect) -> bool { + mesh.iter().all(|p| p.x.is_finite() && p.y.is_finite()) && rest.width() > 1e-6 && rest.height() > 1e-6 && rest.min.x.is_finite() && rest.min.y.is_finite() && rest.max.x.is_finite() && rest.max.y.is_finite() +} + +/// `path` bent by the patch (both in the same space), within `tol`. `None` when the bent path +/// would be too large ([`MAX_COMMANDS`]) or the mesh isn't valid. +pub fn warp(path: &Path, mesh: &Mesh, rest: &Rect, tol: f32) -> Option { + if !valid(mesh, rest) { + return None; + } + let tol = if tol.is_finite() { tol.max(1e-4) } else { 0.05 }; + let mut out = Path::new(); + let (mut start, mut cur) = (Vec2::ZERO, Vec2::ZERO); + let line = |a: Vec2, b: Vec2| [a, a.lerp(b, 1.0 / 3.0), a.lerp(b, 2.0 / 3.0), b]; + for c in &path.cmds { + match *c { + PathCmd::MoveTo(p) => { + out.move_to(map(mesh, rest, p)); + start = p; + cur = p; + } + PathCmd::LineTo(p) => { + segment(&mut out, &line(cur, p), true, mesh, rest, tol, 0); + cur = p; + } + PathCmd::QuadTo(q, p) => { + segment(&mut out, &[cur, cur.lerp(q, 2.0 / 3.0), p.lerp(q, 2.0 / 3.0), p], false, mesh, rest, tol, 0); + cur = p; + } + PathCmd::CubicTo(a, b, p) => { + segment(&mut out, &[cur, a, b, p], false, mesh, rest, tol, 0); + cur = p; + } + PathCmd::Close => { + // The closing edge bends too: when it no longer is straight, draw it, then + // close on the start. + if cur != start && !stays_straight(&line(cur, start), mesh, rest, tol) { + segment(&mut out, &line(cur, start), true, mesh, rest, tol, 0); + } + out.close(); + cur = start; + } + } + if out.cmds.len() > MAX_COMMANDS { + return None; + } + } + Some(out) +} + +/// Whether the line `c` (as a cubic) stays straight: its image's quarter points are on the +/// chord between its mapped ends, evenly. +fn stays_straight(c: &[Vec2; 4], mesh: &Mesh, rest: &Rect, tol: f32) -> bool { + let (a, b) = (map(mesh, rest, c[0]), map(mesh, rest, c[3])); + [0.25f32, 0.5, 0.75].iter().all(|&t| map(mesh, rest, cubic_at(c, t)).distance(a.lerp(b, t)) <= tol) +} + +/// One segment (as a cubic, `straight` when it is a line), bent and appended. +fn segment(out: &mut Path, c: &[Vec2; 4], straight: bool, mesh: &Mesh, rest: &Rect, tol: f32, depth: u32) { + let m = [map(mesh, rest, c[0]), map(mesh, rest, c[1]), map(mesh, rest, c[2]), map(mesh, rest, c[3])]; + let err = [0.25f32, 0.5, 0.75].iter().map(|&t| map(mesh, rest, cubic_at(c, t)).distance(cubic_at(&m, t))).fold(0.0f32, f32::max); + if straight && stays_straight(c, mesh, rest, tol) { + out.line_to(m[3]); + return; + } + if err <= tol || depth >= MAX_DEPTH || out.cmds.len() > MAX_COMMANDS { + out.cubic_to(m[1], m[2], m[3]); + return; + } + let (a, b) = split(c); + segment(out, &a, false, mesh, rest, tol, depth + 1); + segment(out, &b, false, mesh, rest, tol, depth + 1); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Affine; + + fn rest() -> Rect { + Rect::new(10.0, 20.0, 110.0, 70.0) + } + + /// At rest the map is the identity, and a bent path is the path itself, command for command. + #[test] + fn identity_at_rest() { + let r = rest(); + let m = rest_mesh(&r); + for p in [Vec2::new(10.0, 20.0), Vec2::new(60.0, 45.0), Vec2::new(110.0, 70.0), Vec2::new(-30.0, 200.0)] { + assert!(map(&m, &r, p).distance(p) < 1e-3, "{p:?}"); + } + let mut path = Path::rounded_rect(10.0, 20.0, 100.0, 50.0, 12.0); + path.cmds.extend(Path::star(60.0, 45.0, 20.0, 8.0, 5).cmds); + let bent = warp(&path, &m, &r, 0.01).expect("bends"); + assert_eq!(bent.cmds.len(), path.cmds.len(), "nothing is subdivided at rest"); + for (a, b) in bent.cmds.iter().zip(&path.cmds) { + assert_eq!(std::mem::discriminant(a), std::mem::discriminant(b), "lines stay lines"); + } + let (fa, fb) = (bent.flatten(&Affine::IDENTITY, 0.01), path.flatten(&Affine::IDENTITY, 0.01)); + for (pa, pb) in fa.iter().zip(&fb) { + for (x, y) in pa.points.iter().zip(&pb.points) { + assert!(x.distance(*y) < 1e-3); + } + } + } + + /// A rest boundary gives the rest interior; moving every point by the same affine map + /// moves the path by it, lines staying lines. + #[test] + fn coons_and_affine_meshes() { + let r = rest(); + let mut m = rest_mesh(&r); + let want = m; + m[5] = Vec2::ZERO; + m[10] = Vec2::new(1e3, 1e3); + coons_interior(&mut m); + for (a, b) in m.iter().zip(&want) { + assert!(a.distance(*b) < 1e-3); + } + let xf = Affine::translate(5.0, -3.0).mul(&Affine::rotate(0.4)).mul(&Affine::scale(1.5, 0.75)); + let moved: Mesh = want.map(|p| xf.apply(p)); + let path = Path::rect(20.0, 30.0, 40.0, 20.0); + let bent = warp(&path, &moved, &r, 0.01).expect("bends"); + assert!(bent.cmds.iter().all(|c| !matches!(c, PathCmd::CubicTo(..))), "an affine envelope keeps lines straight"); + let pts = bent.flatten(&Affine::IDENTITY, 0.01); + for (p, q) in pts[0].points.iter().zip(path.flatten(&xf, 0.01)[0].points.iter()) { + assert!(p.distance(*q) < 1e-2, "{p:?} vs {q:?}"); + } + } + + /// A bulged top side bends a straight top edge into a curve through the bulge, within the + /// tolerance of the exact image everywhere. + #[test] + fn bending_is_within_tolerance() { + let r = rest(); + let mut m = rest_mesh(&r); + m[1].y -= 30.0; + m[2].y -= 30.0; + coons_interior(&mut m); + let path = Path::rect(10.0, 20.0, 100.0, 50.0); + let tol = 0.05; + let bent = warp(&path, &m, &r, tol).expect("bends"); + assert!(bent.cmds.iter().any(|c| matches!(c, PathCmd::CubicTo(..)))); + // The top edge's middle rose by ¾ of the handles' lift (B₁ + B₂ at ½). + let top = map(&m, &r, Vec2::new(60.0, 20.0)); + assert!((top.y - (20.0 - 22.5)).abs() < 1e-3, "{top:?}"); + // Every point of the exact image of the top edge is near the bent outline. + let poly = &bent.flatten(&Affine::IDENTITY, 0.005)[0].points; + for i in 0..=50 { + let exact = map(&m, &r, Vec2::new(10.0 + 2.0 * i as f32, 20.0)); + let d = poly.windows(2).map(|w| crate::segment_distance(exact, w[0], w[1])).fold(f32::MAX, f32::min); + assert!(d < tol * 2.0, "{i}: {d}"); + } + } + + #[test] + fn invalid_meshes_decline() { + let r = rest(); + let mut m = rest_mesh(&r); + m[3].x = f32::NAN; + assert!(warp(&Path::rect(0.0, 0.0, 1.0, 1.0), &m, &r, 0.1).is_none()); + let flat = Rect::new(0.0, 0.0, 10.0, 0.0); + assert!(warp(&Path::rect(0.0, 0.0, 1.0, 1.0), &rest_mesh(&flat), &flat, 0.1).is_none()); + } +} diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index f8dc787e..9f740d0b 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -8,6 +8,7 @@ mod affine; pub mod brush; pub mod clip; pub mod edit; +pub mod envelope; pub mod morph; pub mod planar; pub mod pressure; @@ -21,7 +22,7 @@ pub mod walk; pub use affine::{Affine, Decomposed}; pub use fit::fit_curve; -pub use path::{FillRule, Path, PathCmd, Polyline, segment_distance}; +pub use path::{FillRule, POLYSTAR_MAX_SIDES, Path, PathCmd, Polyline, polystar_corners, segment_distance, star_inner_radius}; use serde::{Deserialize, Serialize}; use std::ops::{Add, Mul, Neg, Sub}; diff --git a/crates/geom/src/path.rs b/crates/geom/src/path.rs index 5c29dd2f..c1813a49 100644 --- a/crates/geom/src/path.rs +++ b/crates/geom/src/path.rs @@ -203,6 +203,36 @@ const MAX_SEGMENTS_PER_CURVE: usize = 1024; /// Bézier circle constant. const KAPPA: f32 = 0.552_284_8; +/// Most corners a PolyStar has on each side of its outline (sides or points). +pub const POLYSTAR_MAX_SIDES: u32 = 256; + +/// The inner radius of a star of `points` points for a point size from 0 to 1 (ADR 0080): at 1 +/// the inner corners lie on the edges of the polygon through the tips (the star is that polygon), +/// at 0 they meet in the centre (needle points), and in between the depth is proportional. Out +/// of range or not a number, the point size is clamped (or 0.5). +pub fn star_inner_radius(outer: f32, points: u32, point_size: f32) -> f32 { + let n = points.clamp(3, POLYSTAR_MAX_SIDES) as f32; + let size = if point_size.is_finite() { point_size.clamp(0.0, 1.0) } else { 0.5 }; + outer * size * (std::f32::consts::PI / n).cos() +} + +/// The corners of [`Path::polystar`], in order (clockwise on screen, y down), the first straight +/// up: `sides` of them for a polygon, `2 × sides` (tip, inner, tip, …) for a star. `sides` is +/// clamped to 3..=[`POLYSTAR_MAX_SIDES`]. +pub fn polystar_corners(cx: f32, cy: f32, radius: f32, sides: u32, star: bool, point_size: f32) -> Vec { + let n = sides.clamp(3, POLYSTAR_MAX_SIDES) as usize; + let inner = star_inner_radius(radius, sides, point_size); + let steps = if star { n * 2 } else { n }; + (0..steps) + .map(|i| { + let r = if star && i % 2 == 1 { inner } else { radius }; + // f64 so the corners of a big polygon stay where they belong. + let a = -std::f64::consts::FRAC_PI_2 + i as f64 * std::f64::consts::TAU / steps as f64; + Vec2::new(cx + r * a.cos() as f32, cy + r * a.sin() as f32) + }) + .collect() +} + impl Path { pub fn new() -> Self { Self::default() @@ -274,6 +304,22 @@ impl Path { p } + /// The PolyStar tool's outline (ADR 0080): a regular polygon of `sides` corners, or a star of + /// `sides` points whose inner corners are at [`star_inner_radius`] for `point_size`, centred + /// at `(cx, cy)` with the first corner straight up. + pub fn polystar(cx: f32, cy: f32, radius: f32, sides: u32, star: bool, point_size: f32) -> Path { + let mut p = Path::new(); + for (i, v) in polystar_corners(cx, cy, radius, sides, star, point_size).into_iter().enumerate() { + if i == 0 { + p.move_to(v); + } else { + p.line_to(v); + } + } + p.close(); + p + } + /// Star (or polygon when `inner == outer`) with `points` tips, first tip pointing up. pub fn star(cx: f32, cy: f32, outer: f32, inner: f32, points: u32) -> Path { let n = points.clamp(3, 256) as usize; @@ -499,6 +545,71 @@ pub fn segment_distance(p: Vec2, a: Vec2, b: Vec2) -> f32 { mod tests { use super::*; + /// Shoelace area of a polygon. + fn poly_area(pts: &[Vec2]) -> f64 { + let n = pts.len(); + (0..n).map(|i| { + let (a, b) = (pts[i], pts[(i + 1) % n]); + f64::from(a.x) * f64::from(b.y) - f64::from(b.x) * f64::from(a.y) + }).sum::() * 0.5 + } + + /// ADR 0080: a regular polygon's corners are on its circle, its first straight up, and its + /// area is n/2 · r² · sin(2π/n). + #[test] + fn polystar_polygon_is_regular() { + for n in [3u32, 4, 5, 6, 8, 12, 32] { + let r = 50.0; + let pts = polystar_corners(10.0, -20.0, r, n, false, 0.3); + assert_eq!(pts.len(), n as usize); + assert!((pts[0].x - 10.0).abs() < 1e-4 && (pts[0].y - (-20.0 - r)).abs() < 1e-4, "first corner straight up: {:?}", pts[0]); + for p in &pts { + assert!(((*p - Vec2::new(10.0, -20.0)).length() - r).abs() < 1e-3); + } + let want = f64::from(n) / 2.0 * f64::from(r * r) * (std::f64::consts::TAU / f64::from(n)).sin(); + let got = poly_area(&pts); + assert!((got.abs() - want).abs() < want * 1e-5, "n {n}: {got} vs {want}"); + // Clockwise on screen (y down): positive shoelace area. + assert!(got > 0.0); + // The path is the same polygon. + let path = Path::polystar(10.0, -20.0, r, n, false, 0.3); + assert_eq!(path.cmds.len(), n as usize + 1); + } + } + + /// ADR 0080: a star's inner corners are at r · size · cos(π/n): at 1 they lie on the + /// polygon's edges (the star covers exactly the polygon), at 0 in the centre, and its area + /// is n · r · r_in · sin(π/n). + #[test] + fn polystar_star_point_size() { + let r = 80.0f32; + for n in [3u32, 5, 7, 32] { + let half = std::f64::consts::PI / f64::from(n); + for size in [0.0f32, 0.25, 0.5, 1.0] { + let pts = polystar_corners(0.0, 0.0, r, n, true, size); + assert_eq!(pts.len(), 2 * n as usize); + let inner = f64::from(r) * f64::from(size) * half.cos(); + assert!((f64::from(star_inner_radius(r, n, size)) - inner).abs() < 1e-3); + for (i, p) in pts.iter().enumerate() { + let want = if i % 2 == 0 { f64::from(r) } else { inner }; + assert!((f64::from(p.length()) - want).abs() < 1e-3, "n {n} size {size} corner {i}"); + } + let want = f64::from(n) * f64::from(r) * inner * half.sin(); + assert!((poly_area(&pts) - want).abs() <= want * 1e-4 + 1e-3, "n {n} size {size}"); + } + // Point size 1: the area of the polygon through the tips. + let full = poly_area(&polystar_corners(0.0, 0.0, r, n, true, 1.0)); + let poly = poly_area(&polystar_corners(0.0, 0.0, r, n, false, 1.0)); + assert!((full - poly).abs() < poly * 1e-5); + } + // Out of range and not a number: clamped, or the default. + assert_eq!(star_inner_radius(10.0, 5, 3.0), star_inner_radius(10.0, 5, 1.0)); + assert_eq!(star_inner_radius(10.0, 5, -1.0), 0.0); + assert_eq!(star_inner_radius(10.0, 5, f32::NAN), star_inner_radius(10.0, 5, 0.5)); + assert_eq!(polystar_corners(0.0, 0.0, 1.0, 0, false, 0.5).len(), 3); + assert_eq!(polystar_corners(0.0, 0.0, 1.0, u32::MAX, false, 0.5).len(), POLYSTAR_MAX_SIDES as usize); + } + #[test] fn flatten_rect_is_closed_polygon() { let pls = Path::rect(0.0, 0.0, 10.0, 5.0).flatten(&Affine::IDENTITY, 0.1); diff --git a/crates/geom/src/planar.rs b/crates/geom/src/planar.rs index d21de9d1..b52c3e6e 100644 --- a/crates/geom/src/planar.rs +++ b/crates/geom/src/planar.rs @@ -75,6 +75,33 @@ pub fn merge_cut(items: &[Item], cutter: &Path) -> Option { merge_with(items, Some(cutter)) } +/// The area `paths` cover together (each filled by its own rule), as one path of loops that +/// don't overlap: even-odd and non-zero fill it alike. Empty when they cover nothing; `None` +/// when there is too much to merge at once. +pub fn union(paths: &[(&Path, FillRule)]) -> Option { + let items: Vec = paths.iter().map(|&(path, fill_rule)| Item { path, fill: Some(0), fill_rule, stroke: None }).collect(); + let merged = merge(&items)?; + Some(join(merged.fills.into_iter().map(|p| p.path))) +} + +/// The part of `subject` (filled by `rule`) inside `region` (filled even-odd, such as a +/// [`union`]): a boolean intersection, exact to [`SNAP`], as one path of loops that don't +/// overlap (ADR 0080: the Brush's Paint Selection and Paint Inside). Empty when they don't +/// overlap; `None` when there is too much to merge at once. +pub fn intersect(subject: &Path, rule: FillRule, region: &Path) -> Option { + let merged = merge_cut(&[Item { path: subject, fill: Some(0), fill_rule: rule, stroke: None }], region)?; + Some(join(merged.fills.into_iter().filter(|p| p.inside).map(|p| p.path))) +} + +/// Pieces' paths, one after another. +fn join(pieces: impl Iterator) -> Path { + let mut out = Path::new(); + for p in pieces { + out.cmds.extend(p.cmds); + } + out +} + /// The item number the cutter's segments carry. const CUTTER: usize = usize::MAX; diff --git a/crates/geom/src/planar_tests.rs b/crates/geom/src/planar_tests.rs index 6ee8526e..a951c2ba 100644 --- a/crates/geom/src/planar_tests.rs +++ b/crates/geom/src/planar_tests.rs @@ -330,3 +330,43 @@ fn a_cutter_over_a_curve_cuts_exact_pieces() { assert!(near(inside * 4.0, all, 1.0), "{inside} of {all}"); assert_eq!(m.fills.len(), 2); } + +// ----- union and intersection (ADR 0080) -------------------------------------------------------- + +/// Two overlapping squares: the union covers 10² + 10² − 5·5, and the even-odd area of the +/// joined path agrees (no overlapping loops). +#[test] +fn union_of_overlapping_squares() { + let (a, b) = (rect(0.0, 0.0, 10.0, 10.0), rect(5.0, 5.0, 10.0, 10.0)); + let u = union(&[(&a, FillRule::NonZero), (&b, FillRule::NonZero)]).expect("merges"); + assert!((area(&u) - 175.0).abs() < 0.05, "{}", area(&u)); + assert!(u.contains(Vec2::new(12.0, 12.0), &crate::Affine::IDENTITY, FillRule::EvenOdd)); + assert!(u.contains(Vec2::new(7.0, 7.0), &crate::Affine::IDENTITY, FillRule::EvenOdd), "the overlap is covered once"); + assert!(!u.contains(Vec2::new(12.0, 2.0), &crate::Affine::IDENTITY, FillRule::EvenOdd)); + assert!(union(&[]).expect("nothing to merge").is_empty()); +} + +/// A bar across a square keeps only the part inside it; a disc inside a square with a hole +/// loses the hole. +#[test] +fn intersect_clips_to_the_region() { + let bar = rect(-20.0, 4.0, 60.0, 2.0); + let square = rect(0.0, 0.0, 10.0, 10.0); + let clipped = intersect(&bar, FillRule::NonZero, &square).expect("merges"); + assert!((area(&clipped) - 20.0).abs() < 0.05, "{}", area(&clipped)); + // Nothing in common. + let far = rect(100.0, 100.0, 5.0, 5.0); + assert!(intersect(&far, FillRule::NonZero, &square).expect("merges").is_empty()); + // A ring (square with a square hole, even-odd) clipping a square that covers it all. + let mut ring = rect(0.0, 0.0, 30.0, 30.0); + ring.cmds.extend(rect(10.0, 10.0, 10.0, 10.0).cmds); + let cover = rect(-5.0, -5.0, 40.0, 40.0); + let inside = intersect(&cover, FillRule::NonZero, &ring).expect("merges"); + assert!((area(&inside) - 800.0).abs() < 0.1, "{}", area(&inside)); + assert!(!inside.contains(Vec2::new(15.0, 15.0), &crate::Affine::IDENTITY, FillRule::EvenOdd), "the hole stays empty"); + // A circle's quarter: exact to the curve. + let disc = Path::ellipse(0.0, 0.0, 10.0, 10.0); + let quarter = intersect(&disc, FillRule::NonZero, &rect(0.0, 0.0, 20.0, 20.0)).expect("merges"); + let want = std::f32::consts::PI * 100.0 / 4.0; + assert!((area(&quarter) - want).abs() < want * 0.002, "{} vs {want}", area(&quarter)); +} diff --git a/crates/gpu/examples/gpu_bench.rs b/crates/gpu/examples/gpu_bench.rs index 772614c6..770e4d19 100644 --- a/crates/gpu/examples/gpu_bench.rs +++ b/crates/gpu/examples/gpu_bench.rs @@ -87,7 +87,7 @@ fn bitmap_layer(id: u64, n: u32, bitmaps: &[Arc], frames: u32) -> Arc Document { let mut layer = bitmap_layer(91_000, 0, std::slice::from_ref(&sky), frames); let l = Arc::make_mut(&mut layer); let fill = Paint::Bitmap { bitmap: sky.id, repeat: true, matrix: Affine::scale(5.0, 5.0) }; - let shape = Shape { merge: false, path: Arc::new(Path::rect(0.0, 0.0, 1280.0, 300.0)), fill: Some(fill), stroke: None, fill_rule: FillRule::NonZero }; + let shape = Shape { merge: false, path: Arc::new(Path::rect(0.0, 0.0, 1280.0, 300.0)), fill: Some(fill), stroke: None, fill_rule: FillRule::NonZero, warp: None }; if let Some(k) = l.keyframes.first_mut() { Arc::make_mut(k).elements.push(Arc::new(Element { id: ElementId(91_001), name: "sky".into(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Shape(shape) })); } diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index a2660d59..c1d0d1bb 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -444,6 +444,7 @@ impl GpuRenderer { group: None, image: None, smooth: true, + warp: None, }; let solid = |x: f32, c: Rgba| item(Path::rect(x, 2.0, 8.0, 16.0), Paint::Solid(c)); let mut bitmap = item(Path::rect(2.0, 18.0, 20.0, 2.0), Paint::Bitmap { bitmap: anicraft_doc::BitmapId(1), repeat: true, matrix: Affine::scale(3.0, 1.0) }); diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index 8257369d..ca847d49 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -32,6 +32,7 @@ fn item(path: Path, fill: Paint) -> DisplayItem { group: None, image: None, smooth: true, + warp: None, } } @@ -946,6 +947,16 @@ fn bitmap_scenes() -> Vec<(&'static str, DisplayList, View)> { let mut hard_tiled = bitmap_item(Path::ellipse(50.0, 40.0, 45.0, 35.0), &c, true, Affine::scale(4.0, 3.0)); hard_tiled.smooth = false; out.push(("bitmaps without smoothing", list(vec![hard_tiled, hard]), view(100, 80, white))); + // Warped (ADR 0079): bent by three pins, folded a little, faded; the oracle's prepared image. + use anicraft_doc::warp::{Pin, PinId, Warp}; + let pin = |id: u64, rest: (f32, f32), at: (f32, f32)| Pin { id: PinId(id), rest: Vec2::new(rest.0, rest.1), at: Vec2::new(at.0, at.1) }; + let mut warp = Warp::new(Arc::new(Path::rect(0.0, 0.0, 40.0, 30.0)), 8); + warp.pins = vec![pin(1, (2.0, 15.0), (6.0, 20.0)), pin(2, (20.0, 15.0), (24.0, 14.0)), pin(3, (38.0, 15.0), (52.0, 40.0))]; + let mut bent = bitmap_item(warp.outline().as_ref().clone(), &c, false, Affine::IDENTITY); + bent.warp = warp.mesh().map(Arc::new); + bent.transform = Affine::scale(1.4, 1.4); + bent.color = ColorTransform::alpha(0.8); + out.push(("warped bitmap", list(vec![bent]), view(90, 72, white))); out } @@ -1100,7 +1111,7 @@ fn filtered_sample() -> anicraft_doc::Document { } } } - let shape = anicraft_doc::Shape { path: Arc::new(Path::rect(0.0, 0.0, 1280.0, 300.0)), merge: false, fill: Some(Paint::Bitmap { bitmap: anicraft_doc::BitmapId(77), repeat: true, matrix: Affine::scale(5.0, 5.0) }), stroke: None, fill_rule: FillRule::NonZero }; + let shape = anicraft_doc::Shape { path: Arc::new(Path::rect(0.0, 0.0, 1280.0, 300.0)), merge: false, fill: Some(Paint::Bitmap { bitmap: anicraft_doc::BitmapId(77), repeat: true, matrix: Affine::scale(5.0, 5.0) }), stroke: None, fill_rule: FillRule::NonZero, warp: None }; let sky = anicraft_doc::Element { id: ElementId(9_100), name: "sky".into(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Shape(shape) }; let frames = doc.frame_count(); let mut k = anicraft_doc::Keyframe::new(0, frames); diff --git a/crates/render/src/html.rs b/crates/render/src/html.rs index df8d6b5f..7d2945f6 100644 --- a/crates/render/src/html.rs +++ b/crates/render/src/html.rs @@ -103,6 +103,7 @@ const PLUGIN_SCRIPTS: &str = "plug-in frame scripts (not exported; they need the const KEPT_SCRIPTS: &str = "kept frame scripts outside the ActionScript subset (not run; kept in the document only)"; const NINE_SLICE: &str = "9-slice scaling (scaled as a whole)"; const OUTSIDE_CALLS: &str = "script calls that reach outside the movie (ignored)"; +const WARPED_BITMAPS: &str = "warped bitmaps (the image shows unbent inside its bent outline; warped shapes come across)"; const FIELD_FONTS: &str = "text fields (their authored text keeps its outlines; text a script or the viewer changes is drawn with the browser's fonts)"; /// A number rounded to `1/scale`, written as an integer when it is one. @@ -595,6 +596,10 @@ impl<'a> Bake<'a> { } match &el.kind { ElementKind::Shape(s) => { + // A bent image needs the mesh, which canvas 2D can't draw (ADR 0079). + if matches!(s.fill, Some(Paint::Bitmap { .. })) && s.live_warp().is_some_and(|w| !w.at_rest()) { + self.notes.entry(WARPED_BITMAPS).or_default().insert(el.id.0); + } let stroke = s.stroke.as_ref().filter(|st| st.width.is_finite() && st.width > 0.0); match stroke.filter(|st| st.profile.is_some()) { // A variable-width stroke is the filled outline the renderer fills (its diff --git a/crates/render/src/html_tests.rs b/crates/render/src/html_tests.rs index ebb721ac..dc4d1304 100644 --- a/crates/render/src/html_tests.rs +++ b/crates/render/src/html_tests.rs @@ -493,7 +493,7 @@ fn frames_are_baked_and_stored_once() { fn variable_width_strokes_become_filled_outlines() { use anicraft_doc::{ProfilePreset, Stroke}; let mut doc = Document::default(); - let shape = Shape { path: Arc::new(Path::line(Vec2::new(10.0, 10.0), Vec2::new(200.0, 10.0))), fill: None, stroke: Some(Stroke::new(Rgba::hex(0x00ff00), 10.0).with_profile(ProfilePreset::TaperEnd.profile())), fill_rule: FillRule::NonZero, merge: false }; + let shape = Shape { path: Arc::new(Path::line(Vec2::new(10.0, 10.0), Vec2::new(200.0, 10.0))), fill: None, stroke: Some(Stroke::new(Rgba::hex(0x00ff00), 10.0).with_profile(ProfilePreset::TaperEnd.profile())), fill_rule: FillRule::NonZero, merge: false, warp: None }; let el = Element { id: ElementId(77), name: String::new(), transform: Affine::translate(5.0, 0.0), color: Default::default(), kind: ElementKind::Shape(shape) }; Arc::make_mut(&mut doc.timeline_mut(0).layers[0]).keyframe_mut(0).unwrap().elements.push(Arc::new(el)); let m = movie(&doc, &HtmlOptions::default()); @@ -508,7 +508,7 @@ fn stroke_caps_joins_and_dashes_reach_the_page() { use anicraft_doc::{Cap, Dash, Join, Stroke, StrokeStyle}; let mut doc = Document::default(); let style = StrokeStyle { cap: Cap::Butt, join: Join::Miter, miter_limit: 6.0, dash: Some(Dash::Dashed { lengths: vec![4.0, 1.5].into(), offset: 1.0 }) }; - let line = |y: f32, st: Stroke| Shape { path: Arc::new(Path::line(Vec2::new(10.0, y), Vec2::new(200.0, y))), fill: None, stroke: Some(st), fill_rule: FillRule::NonZero, merge: false }; + let line = |y: f32, st: Stroke| Shape { path: Arc::new(Path::line(Vec2::new(10.0, y), Vec2::new(200.0, y))), fill: None, stroke: Some(st), fill_rule: FillRule::NonZero, merge: false, warp: None }; let shapes = [line(10.0, Stroke::new(Rgba::BLACK, 3.0)), line(30.0, Stroke::new(Rgba::BLACK, 3.0).with_style(style)), line(50.0, Stroke::new(Rgba::BLACK, 3.0).with_style(StrokeStyle { dash: Dash::dotted(2.0), ..StrokeStyle::default() }))]; for (i, sh) in shapes.into_iter().enumerate() { let el = Element { id: ElementId(70 + i as u64), name: String::new(), transform: Affine::scale(2.0, 2.0), color: Default::default(), kind: ElementKind::Shape(sh) }; diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 2c61238a..3be94917 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -12,6 +12,7 @@ pub mod hairline; pub mod html; pub mod lottie; pub mod svg; +pub mod warp; use anicraft_doc::{BlendMode, ColorTransform, DisplayItem, DisplayList, Document, MaskMode, Paint, Rgba, evaluate}; use anicraft_geom::{Affine, FillRule, Rect, Vec2}; @@ -876,7 +877,19 @@ fn prepare(item: &DisplayItem, view: &Affine, surface: IRect, soft: bool) -> Vec }); if let Some(fill) = &item.fill { let polys: Vec> = lines.into_iter().map(|l| l.points).collect(); - push(polys, item.fill_rule, Shader::new(fill, &m, &item.color, item.image.as_ref()).smoothed(item.smooth)); + let shader = match (&item.warp, fill, &item.image) { + // A warped bitmap (ADR 0079): the image drawn through its mesh, prepared once over + // the fill's pixels and shown one image pixel per surface pixel. + (Some(mesh), Paint::Bitmap { repeat, matrix, .. }, Some(px)) => { + let prepared = pixel_bounds(&polys, surface).and_then(|b| Some((warp::texture(mesh, &m, matrix, *repeat, px, item.smooth, b)?, b))); + match prepared { + Some((tex, b)) => Shader::Bitmap { inv: Affine::translate(-(b.x0 as f32), -(b.y0 as f32)), pixels: tex, repeat: false, fx: item.color, smooth: false }, + None => Shader::Solid([0.0; 4]), + } + } + _ => Shader::new(fill, &m, &item.color, item.image.as_ref()).smoothed(item.smooth), + }; + push(polys, item.fill_rule, shader); } if let Some((polys, shader)) = stroke { push(polys, FillRule::NonZero, shader); @@ -965,6 +978,7 @@ mod tests { group: None, image: None, smooth: true, + warp: None, } } @@ -1497,3 +1511,7 @@ mod tests { assert!((q[2] - 1.0).abs() < 1e-3, "outside the group unchanged: {q:?}"); } } + +#[cfg(test)] +#[path = "warp_tests.rs"] +mod warp_tests; diff --git a/crates/render/src/lottie.rs b/crates/render/src/lottie.rs index 9f0dc15f..fd2bad8d 100644 --- a/crates/render/src/lottie.rs +++ b/crates/render/src/lottie.rs @@ -14,7 +14,9 @@ //! Soft masks (ADR 0070) become track mattes (alpha, or luma for luminance masks): a matte layer //! with the mask's artwork as drawn, just above each layer it shows through. //! -//! Not carried across (counted in the report): bitmap fills; nested masks keep only the +//! Warped shapes (ADR 0079) are their bent outlines like any other. +//! +//! Not carried across (counted in the report): bitmap fills (warped or not); nested masks keep only the //! innermost mask; a symbol fading as one group is faded shape by shape; stretched radial //! gradients become circles; and draw-order changes that one fixed layer order can't show. @@ -836,7 +838,7 @@ mod tests { fn variable_width_strokes_export_as_filled_outlines() { use anicraft_doc::{Document, Element, ElementId, ElementKind, ProfilePreset, Shape, Stroke}; let mut doc = Document::default(); - let shape = Shape { path: std::sync::Arc::new(Path::line(Vec2::new(10.0, 10.0), Vec2::new(200.0, 10.0))), fill: None, stroke: Some(Stroke::new(Rgba::hex(0x00ff00), 10.0).with_profile(ProfilePreset::TaperEnd.profile())), fill_rule: FillRule::NonZero, merge: false }; + let shape = Shape { path: std::sync::Arc::new(Path::line(Vec2::new(10.0, 10.0), Vec2::new(200.0, 10.0))), fill: None, stroke: Some(Stroke::new(Rgba::hex(0x00ff00), 10.0).with_profile(ProfilePreset::TaperEnd.profile())), fill_rule: FillRule::NonZero, merge: false, warp: None }; let el = Element { id: ElementId(77), name: String::new(), transform: Affine::IDENTITY, color: Default::default(), kind: ElementKind::Shape(shape) }; let layer = std::sync::Arc::make_mut(&mut doc.timeline_mut(0).layers[0]); layer.keyframe_mut(0).unwrap().elements.push(std::sync::Arc::new(el)); @@ -853,7 +855,7 @@ mod tests { use anicraft_doc::{Cap, Dash, Document, Element, ElementId, ElementKind, Join, Shape, Stroke, StrokeStyle}; let export = |st: Stroke| { let mut doc = Document::default(); - let shape = Shape { path: std::sync::Arc::new(Path::line(Vec2::new(10.0, 10.0), Vec2::new(200.0, 10.0))), fill: None, stroke: Some(st), fill_rule: FillRule::NonZero, merge: false }; + let shape = Shape { path: std::sync::Arc::new(Path::line(Vec2::new(10.0, 10.0), Vec2::new(200.0, 10.0))), fill: None, stroke: Some(st), fill_rule: FillRule::NonZero, merge: false, warp: None }; let el = Element { id: ElementId(77), name: String::new(), transform: Affine::scale(2.0, 2.0), color: Default::default(), kind: ElementKind::Shape(shape) }; let layer = std::sync::Arc::make_mut(&mut doc.timeline_mut(0).layers[0]); layer.keyframe_mut(0).unwrap().elements.push(std::sync::Arc::new(el)); diff --git a/crates/render/src/paint.rs b/crates/render/src/paint.rs index a3b280c7..ee6acf37 100644 --- a/crates/render/src/paint.rs +++ b/crates/render/src/paint.rs @@ -171,7 +171,7 @@ impl Shader { /// A sample at bitmap position `q` (pixel (i, j) covers [i, i+1) × [j, j+1)), bilinear when /// `smooth`, else the pixel `q` is in, with the colour effect applied and premultiplied. /// Outside a non-repeating bitmap: transparent. -fn sample(px: &Pixels, q: Vec2, repeat: bool, smooth: bool, fx: &ColorTransform) -> Premul { +pub(crate) fn sample(px: &Pixels, q: Vec2, repeat: bool, smooth: bool, fx: &ColorTransform) -> Premul { let (w, h) = (px.width as f32, px.height as f32); if !(q.x.is_finite() && q.y.is_finite()) || w < 1.0 || h < 1.0 { return [0.0; 4]; diff --git a/crates/render/src/svg.rs b/crates/render/src/svg.rs index 7ec0471b..c92217a4 100644 --- a/crates/render/src/svg.rs +++ b/crates/render/src/svg.rs @@ -151,7 +151,13 @@ fn draw(item: &DisplayItem, d: &str, clip: &str, body: &mut String, defs: &mut S let _ = write!(body, "", color_attrs("stroke", color)); return; } - if let Some(fill) = &item.fill + // A warped bitmap (ADR 0079) has no SVG equivalent: it is baked as the image the + // renderer draws, at twice the stage's resolution, where it shows. + if item.warp.is_some() && matches!(item.fill, Some(Paint::Bitmap { .. })) { + if let Some((x, y, w, h, png)) = bake(item) { + let _ = write!(body, "", num(x), num(y), num(w), num(h), anicraft_doc::base64_encode(&png)); + } + } else if let Some(fill) = &item.fill && let Some(paint) = paint_attr(fill, &item.transform, &item.color, defs, grad, item.image.as_ref().map(|px| (px, item.smooth)), images) { let _ = write!(body, "", rule_attr("fill-rule", item.fill_rule)); @@ -165,6 +171,29 @@ fn draw(item: &DisplayItem, d: &str, clip: &str, body: &mut String, defs: &mut S } } +/// Pixels per stage unit a warped bitmap is baked at, and the largest edge it may have. +const BAKE_SCALE: f32 = 2.0; +const BAKE_EDGE: f32 = 4096.0; + +/// `item`'s fill drawn on its own by the renderer (its colour effect included, no stroke): +/// where it goes on the stage (x, y, width, height) and the PNG. `None` when it is empty. +fn bake(item: &DisplayItem) -> Option<(f32, f32, f32, f32, Vec)> { + let r = item.path.bounds().transformed(&item.transform); + if r.is_empty() || !(r.min.is_finite() && r.max.is_finite()) { + return None; + } + let (x0, y0) = (r.min.x.floor(), r.min.y.floor()); + let (w, h) = (r.max.x.ceil() - x0, r.max.y.ceil() - y0); + let k = BAKE_SCALE.min(BAKE_EDGE / w.max(h).max(1.0)); + let (pw, ph) = ((w * k).ceil().max(1.0), (h * k).ceil().max(1.0)); + let only = DisplayItem { clip: None, masks: None, group: None, guide: false, stroke: None, outline: None, ..item.clone() }; + let dl = DisplayList { items: vec![only], ..Default::default() }; + let view = crate::View { transform: Affine::scale(k, k).mul(&Affine::translate(-x0, -y0)), width: pw as u32, height: ph as u32, background: None }; + let (pm, _) = crate::render(&dl, &view).ok()?; + let png = pm.encode_png().ok()?; + Some((x0, y0, pw / k, ph / k, png)) +} + /// The item's path in stage space, or `None` when it has no geometry or a broken transform. fn stage_path(item: &DisplayItem) -> Option { if !item.transform.is_finite() || item.path.is_empty() { @@ -531,6 +560,7 @@ mod tests { group: None, image: None, smooth: true, + warp: None, } } @@ -719,6 +749,7 @@ mod group_tests { group: g, image: None, smooth: true, + warp: None, }; let dl = DisplayList { clip_modes: Vec::new(), items: vec![it(None), it(Some(0)), it(Some(1)), it(Some(0)), it(None)], clip_parents: vec![], groups: vec![Group { parent: None, alpha: 0.5, blend: Default::default(), filters: Default::default(), clip: None }, Group { parent: Some(0), alpha: 0.25, blend: Default::default(), filters: Default::default(), clip: None }] }; let svg = to_svg(&dl, &Stage { width: 4, height: 4, fps: 24.0, background: Rgba::WHITE }); diff --git a/crates/render/src/warp.rs b/crates/render/src/warp.rs new file mode 100644 index 00000000..72545c95 --- /dev/null +++ b/crates/render/src/warp.rs @@ -0,0 +1,138 @@ +//! Warped bitmaps (ADR 0079): an image drawn through the triangles of its warp mesh. +//! +//! The oracle prepares a warped bitmap fill as an image of its own, in surface pixels over the +//! fill's bounds: each mesh triangle carries its pixels' centres back to the image as drawn +//! (the triangle's affine map, exact) and samples it there, bilinear with Allow Smoothing, +//! else the nearest pixel, exactly as an unwarped bitmap is sampled. Triangles are written in +//! mesh order, so where the mesh folds over itself the later one shows. A pixel at the +//! outline's edge whose centre falls in no triangle takes its neighbour's colour, so the +//! outline's antialiasing has a colour to fade. The fill then draws that image as a +//! [`Shader::Bitmap`](crate::paint::Shader) of one image pixel per surface pixel, nearest, with +//! the item's colour effect: the GPU stage takes the very same prepared fill, so the two agree. +//! +//! Every pixel is written by one task (rows in bands, in parallel), so the result is the same +//! whatever the thread count. + +use crate::paint::sample; +use crate::raster::IRect; +use anicraft_doc::{ColorTransform, Pixels, warp::WarpMesh}; +use anicraft_geom::{Affine, Vec2}; +use rayon::prelude::*; +use std::sync::Arc; + +/// Most pixels a warped bitmap's prepared image may have (256 MB of RGBA). +pub const MAX_TEXTURE_PIXELS: usize = 1 << 26; +/// Rows per parallel band. +const BAND: usize = 32; + +/// One triangle in surface pixels: its corners, the map from a pixel back to the image, and +/// the rows it touches. +struct Tri { + p: [Vec2; 3], + to_image: Affine, + y0: i32, + y1: i32, +} + +/// The image of the bitmap `px` (its fill matrix `matrix`, tiled when `repeat`) as `mesh` +/// bends it under `m` (local → surface pixels), over `b` (surface pixels): straight RGBA8, +/// `b`'s size, transparent where no triangle is. `None` when it can't be drawn (a collapsed +/// fill matrix, an empty or oversized area). +pub fn texture(mesh: &WarpMesh, m: &Affine, matrix: &Affine, repeat: bool, px: &Pixels, smooth: bool, b: IRect) -> Option> { + let (w, h) = (b.width(), b.height()); + if w == 0 || h == 0 || w.checked_mul(h)? > MAX_TEXTURE_PIXELS { + return None; + } + let to_image = matrix.inverse()?; + let corner = |pts: &[Vec2], i: u32| pts.get(i as usize).copied(); + let tris: Vec = mesh + .tris + .iter() + .filter_map(|t| { + let [s0, s1, s2] = [corner(&mesh.shown, t[0])?, corner(&mesh.shown, t[1])?, corner(&mesh.shown, t[2])?].map(|v| m.apply(v)); + let [r0, r1, r2] = [corner(&mesh.rest, t[0])?, corner(&mesh.rest, t[1])?, corner(&mesh.rest, t[2])?]; + // Surface → local as drawn: R · S⁻¹ (S and R take the unit triangle to each). + let s = Affine { m: [s1.x - s0.x, s1.y - s0.y, s2.x - s0.x, s2.y - s0.y, s0.x, s0.y] }; + let r = Affine { m: [r1.x - r0.x, r1.y - r0.y, r2.x - r0.x, r2.y - r0.y, r0.x, r0.y] }; + let map = to_image.mul(&r.mul(&s.inverse()?)); + if !map.is_finite() { + return None; + } + let (lo, hi) = (s0.y.min(s1.y).min(s2.y), s0.y.max(s1.y).max(s2.y)); + if !(lo.is_finite() && hi.is_finite()) { + return None; + } + Some(Tri { p: [s0, s1, s2], to_image: map, y0: (lo.floor() as i32).max(b.y0), y1: (hi.ceil() as i32 + 1).min(b.y1) }) + }) + .filter(|t| t.y0 < t.y1) + .collect(); + let fx = ColorTransform::default(); + let mut rgba = vec![0u8; w * h * 4]; + let mut set = vec![false; w * h]; + rgba.par_chunks_mut(w * 4 * BAND).zip(set.par_chunks_mut(w * BAND)).enumerate().for_each(|(band, (out, seen))| { + let top = b.y0 + (band * BAND) as i32; + let rows = seen.len() / w; + let bottom = top + rows as i32; + for t in tris.iter().filter(|t| t.y0 < bottom && t.y1 > top) { + fill_tri(t, b, top, bottom, w, px, repeat, smooth, &fx, out, seen); + } + }); + bleed(&mut rgba, &set, w, h); + Some(Arc::new(Pixels { width: w as u32, height: h as u32, rgba })) +} + +/// Writes the pixels of rows `top..bottom` whose centres `t` holds. +#[allow(clippy::too_many_arguments)] +fn fill_tri(t: &Tri, b: IRect, top: i32, bottom: i32, w: usize, px: &Pixels, repeat: bool, smooth: bool, fx: &ColorTransform, out: &mut [u8], seen: &mut [bool]) { + let [a, p1, p2] = t.p; + let area = (p1 - a).cross(p2 - a); + if area.abs() <= 1e-9 || area.is_nan() { + return; + } + // Edge functions, oriented so the inside is positive; centres on an edge count (a hair of + // slack so the triangles of a cell leave no crack between them). + let sign = area.signum(); + let edges = [(a, p1), (p1, p2), (p2, a)]; + let slack = -1e-4 * area.abs(); + let (xs0, xs1) = (a.x.min(p1.x).min(p2.x), a.x.max(p1.x).max(p2.x)); + let x0 = (xs0.floor() as i32).max(b.x0); + let x1 = (xs1.ceil() as i32 + 1).min(b.x1); + for y in t.y0.max(top)..t.y1.min(bottom) { + let cy = y as f32 + 0.5; + let row = (y - top) as usize; + for x in x0..x1 { + let c = Vec2::new(x as f32 + 0.5, cy); + if edges.iter().any(|&(e0, e1)| sign * (e1 - e0).cross(c - e0) < slack) { + continue; + } + let i = row * w + (x - b.x0) as usize; + let s = sample(px, t.to_image.apply(c), repeat, smooth, fx); + let a = s[3]; + let straight = |v: f32| if a > 0.0 { (v / a).clamp(0.0, 1.0) } else { 0.0 }; + let q = |v: f32| (v * 255.0 + 0.5) as u8; + if let (Some(o), Some(flag)) = (out.get_mut(i * 4..i * 4 + 4), seen.get_mut(i)) { + o.copy_from_slice(&[q(straight(s[0])), q(straight(s[1])), q(straight(s[2])), q(a.clamp(0.0, 1.0))]); + *flag = true; + } + } + } +} + +/// Gives each pixel no triangle wrote the colour of a written neighbour (left, right, up, +/// down, the first there is), so the outline's antialiased edge has a colour to fade. +fn bleed(rgba: &mut [u8], set: &[bool], w: usize, h: usize) { + let src = rgba.to_vec(); + for y in 0..h { + for x in 0..w { + let i = y * w + x; + if set.get(i).copied().unwrap_or(true) { + continue; + } + let near = [(x > 0).then(|| i - 1), (x + 1 < w).then(|| i + 1), (y > 0).then(|| i - w), (y + 1 < h).then(|| i + w)]; + let Some(n) = near.into_iter().flatten().find(|&n| set.get(n).copied().unwrap_or(false)) else { continue }; + if let (Some(from), Some(to)) = (src.get(n * 4..n * 4 + 4), rgba.get_mut(i * 4..i * 4 + 4)) { + to.copy_from_slice(from); + } + } + } +} diff --git a/crates/render/src/warp_tests.rs b/crates/render/src/warp_tests.rs new file mode 100644 index 00000000..fa0fa7a1 --- /dev/null +++ b/crates/render/src/warp_tests.rs @@ -0,0 +1,158 @@ +//! Warped bitmaps in the oracle (ADR 0079): analytic checks against the same image moved by a +//! plain transform. + +use super::*; +use anicraft_doc::warp::{Pin, PinId, Warp}; +use anicraft_doc::{BitmapId, ElementId, LayerId, Pixels, Shape}; +use anicraft_geom::Path; +use std::sync::Arc; + +/// A 32 × 16 image: a horizontal red ramp, green rows, blue on every fourth column. +fn image() -> Arc { + let (w, h) = (32u32, 16u32); + let mut rgba = Vec::new(); + for y in 0..h { + for x in 0..w { + rgba.extend_from_slice(&[(x * 8) as u8, (y * 16) as u8, if x % 4 == 0 { 255 } else { 0 }, 255]); + } + } + Arc::new(Pixels { width: w, height: h, rgba }) +} + +fn bitmap_shape() -> Shape { + Shape::filled(Path::rect(0.0, 0.0, 32.0, 16.0), Paint::Bitmap { bitmap: BitmapId(1), repeat: false, matrix: Affine::IDENTITY }) +} + +/// The display item of `shape` (its warp's mesh when it bends it), placed by `transform`. +fn item(shape: &Shape, transform: Affine, smooth: bool) -> DisplayItem { + DisplayItem { + path: shape.path.clone(), + transform, + fill: shape.fill.clone(), + stroke: None, + fill_rule: FillRule::NonZero, + color: ColorTransform::IDENTITY, + layer: LayerId(0), + element: ElementId(0), + outline: None, + clip: None, + masks: None, + guide: false, + group: None, + image: Some(image()), + smooth, + warp: shape.live_warp().filter(|w| !w.at_rest()).and_then(Warp::mesh).map(Arc::new), + } +} + +fn draw(items: Vec, w: u32, h: u32) -> Pixmap { + let dl = DisplayList { items, ..Default::default() }; + let view = View { transform: Affine::IDENTITY, width: w, height: h, background: None }; + render(&dl, &view).map(|(p, _)| p).unwrap_or_else(|_| Pixmap { width: 0, height: 0, data: Vec::new() }) +} + +fn pin(id: u64, rest: (f32, f32), at: (f32, f32)) -> Pin { + Pin { id: PinId(id), rest: anicraft_geom::Vec2::new(rest.0, rest.1), at: anicraft_geom::Vec2::new(at.0, at.1) } +} + +fn warped(pins: Vec, resolution: u32) -> Shape { + let mut s = bitmap_shape(); + let mut w = Warp::new(s.path.clone(), resolution); + w.pins = pins; + s.set_warp(w); + s +} + +/// Largest channel difference over pixels both images cover fully (alpha 1 in `a`). +fn worst(a: &Pixmap, b: &Pixmap) -> f32 { + a.data.iter().zip(&b.data).filter(|(p, _)| p[3] > 0.999).map(|(p, q)| (0..4).map(|k| (p[k] - q[k]).abs()).fold(0.0, f32::max)).fold(0.0, f32::max) +} + +#[test] +fn a_warp_that_only_moves_draws_the_image_moved() { + // One pin moved: the whole image moves with it, exactly as a translated bitmap draws. + let s = warped(vec![pin(1, (16.0, 8.0), (26.0, 13.0))], 8); + for smooth in [true, false] { + let got = draw(vec![item(&s, Affine::IDENTITY, smooth)], 64, 40); + let want = draw(vec![item(&bitmap_shape(), Affine::translate(10.0, 5.0), smooth)], 64, 40); + let covered = got.data.iter().filter(|p| p[3] > 0.999).count(); + assert_eq!(covered, 32 * 16, "the image's pixels, no more and no fewer"); + assert!(worst(&got, &want) <= 1.0 / 255.0 + 1e-6, "smooth {smooth}: {}", worst(&got, &want)); + } +} + +#[test] +fn a_warp_that_turns_draws_the_image_turned() { + // Two pins turned a quarter turn about the image's centre: every triangle turns with them. + let c = (16.0, 8.0); + let turn = |(x, y): (f32, f32)| (c.0 - (y - c.1) + 24.0, c.1 + (x - c.0) + 16.0); + let s = warped(vec![pin(1, (4.0, 8.0), turn((4.0, 8.0))), pin(2, (28.0, 8.0), turn((28.0, 8.0)))], 8); + let xf = Affine::translate(c.0 + 24.0, c.1 + 16.0).mul(&Affine::rotate(std::f32::consts::FRAC_PI_2)).mul(&Affine::translate(-c.0, -c.1)); + let got = draw(vec![item(&s, Affine::IDENTITY, false)], 80, 64); + let want = draw(vec![item(&bitmap_shape(), xf, false)], 80, 64); + assert!(got.data.iter().filter(|p| p[3] > 0.999).count() >= 32 * 16 - 64); + assert!(worst(&got, &want) <= 1.0 / 255.0 + 1e-6, "{}", worst(&got, &want)); +} + +#[test] +fn a_bent_image_has_no_cracks_and_is_deterministic() { + let s = warped(vec![pin(1, (2.0, 8.0), (2.0, 8.0)), pin(2, (16.0, 8.0), (16.0, 8.0)), pin(3, (30.0, 8.0), (34.0, 20.0))], 12); + let a = draw(vec![item(&s, Affine::scale(3.0, 3.0), true)], 140, 110); + let b = draw(vec![item(&s, Affine::scale(3.0, 3.0), true)], 140, 110); + assert_eq!(a.data, b.data); + // Inside the bent outline every pixel is opaque: the triangles leave no seam. + let outline = s.path.clone(); + let m = Affine::scale(3.0, 3.0); + let mut inside = 0; + for y in 0..110 { + for x in 0..140 { + let p = anicraft_geom::Vec2::new(x as f32 + 0.5, y as f32 + 0.5); + if outline.contains(p, &m, FillRule::NonZero) && outline.distance_to_edge(p, &m) > 1.0 { + inside += 1; + let px = a.data[y * 140 + x]; + assert!(px[3] > 0.999, "a crack at ({x}, {y}): {px:?}"); + } + } + } + assert!(inside > 3000); +} + +#[test] +fn the_gpu_stage_gets_the_same_prepared_fill() { + // `prepare_scene` hands the warped bitmap over as a plain image shader: what the GPU draws. + let s = warped(vec![pin(1, (16.0, 8.0), (20.0, 8.0)), pin(2, (2.0, 2.0), (2.0, 2.0))], 6); + let dl = DisplayList { items: vec![item(&s, Affine::IDENTITY, true)], ..Default::default() }; + let view = View { transform: Affine::IDENTITY, width: 48, height: 24, background: None }; + let (scene, _) = prepare_scene(&dl, &view).unwrap_or_else(|_| (Scene { fills: Vec::new(), clips: Vec::new(), groups: Vec::new(), layers: Vec::new() }, RenderStats::default())); + assert_eq!(scene.fills.len(), 1); + assert!(matches!(&scene.fills[0].shader, paint::Shader::Bitmap { smooth: false, repeat: false, .. })); +} + +#[test] +fn svg_bakes_a_warped_bitmap_as_the_image_drawn() { + let s = warped(vec![pin(1, (2.0, 8.0), (2.0, 8.0)), pin(2, (30.0, 8.0), (36.0, 18.0))], 8); + let dl = DisplayList { items: vec![item(&s, Affine::translate(5.0, 5.0), true)], ..Default::default() }; + let stage = anicraft_doc::Stage { width: 64, height: 48, ..Default::default() }; + let svg = crate::svg::to_svg(&dl, &stage); + assert!(svg.contains(" Rect { /// A fill-only shape for mask artwork (its colour doesn't matter: a mask is its fills' area). fn mask_part(name: String, path: Path, transform: Affine, rule: FillRule) -> ImportedElement { - let shape = Shape { path: Arc::new(path), fill: Some(Paint::Solid(Rgba::BLACK)), stroke: None, fill_rule: rule, merge: false }; + let shape = Shape { path: Arc::new(path), fill: Some(Paint::Solid(Rgba::BLACK)), stroke: None, fill_rule: rule, merge: false, warp: None }; ImportedElement { name, transform, alpha: 1.0, kind: ElementKind::Shape(shape) } } diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index 987f0e75..4eb53b66 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -854,7 +854,7 @@ impl<'a> Builder<'a> { if fill.is_none() && stroke.is_none() { return; } - let shape = Shape { path: Arc::new(path), fill, stroke, fill_rule: style.fill_rule, merge: false }; + let shape = Shape { path: Arc::new(path), fill, stroke, fill_rule: style.fill_rule, merge: false, warp: None }; self.items.push(Item { el: ImportedElement { name: name_of(el), transform: *m, alpha, kind: ElementKind::Shape(shape) }, clips: Vec::new() }); } } diff --git a/crates/xfl/src/import.rs b/crates/xfl/src/import.rs index cb4351f6..879cbd60 100644 --- a/crates/xfl/src/import.rs +++ b/crates/xfl/src/import.rs @@ -288,14 +288,14 @@ impl<'a> Builder<'a> { let (Some(p), true) = (p, index > 0) else { continue }; let path = edges::fill_path(&edges, index); if !path.is_empty() { - out.push(self.element(ElementKind::Shape(Shape { path: Arc::new(path), fill: Some(p), stroke: None, fill_rule: FillRule::EvenOdd, merge }), m, ColorEffect::default())); + out.push(self.element(ElementKind::Shape(Shape { path: Arc::new(path), fill: Some(p), stroke: None, fill_rule: FillRule::EvenOdd, merge, warp: None }), m, ColorEffect::default())); } } for (index, s) in strokes { let (Some(s), true) = (s, index > 0) else { continue }; let path = edges::stroke_path(&edges, index); if !path.is_empty() { - out.push(self.element(ElementKind::Shape(Shape { path: Arc::new(path), fill: None, stroke: Some(s), fill_rule: FillRule::NonZero, merge }), m, ColorEffect::default())); + out.push(self.element(ElementKind::Shape(Shape { path: Arc::new(path), fill: None, stroke: Some(s), fill_rule: FillRule::NonZero, merge, warp: None }), m, ColorEffect::default())); } } } @@ -312,7 +312,7 @@ impl<'a> Builder<'a> { let stroke = el.child("stroke").and_then(|s| s.children.first()).and_then(|d| stroke(d, &self.bitmaps, &mut self.report)); if fill.is_some() || stroke.is_some() { let m = parent.mul(&matrix(el)); - out.push(self.element(ElementKind::Shape(Shape { path: Arc::new(path), fill, stroke, fill_rule: FillRule::NonZero, merge: false }), m, ColorEffect::default())); + out.push(self.element(ElementKind::Shape(Shape { path: Arc::new(path), fill, stroke, fill_rule: FillRule::NonZero, merge: false, warp: None }), m, ColorEffect::default())); } } @@ -323,7 +323,7 @@ impl<'a> Builder<'a> { self.report.skip("instances of missing bitmaps"); return; }; - let shape = Shape { path: Arc::new(Path::rect(0.0, 0.0, w, h)), fill: Some(Paint::Bitmap { bitmap, repeat: false, matrix: Affine::IDENTITY }), stroke: None, fill_rule: FillRule::NonZero, merge: false }; + let shape = Shape { path: Arc::new(Path::rect(0.0, 0.0, w, h)), fill: Some(Paint::Bitmap { bitmap, repeat: false, matrix: Affine::IDENTITY }), stroke: None, fill_rule: FillRule::NonZero, merge: false, warp: None }; out.push(self.element(ElementKind::Shape(shape), parent.mul(&matrix(el)), ColorEffect::default())); } diff --git a/docs/adr/0079-asset-warp.md b/docs/adr/0079-asset-warp.md new file mode 100644 index 00000000..702991fd --- /dev/null +++ b/docs/adr/0079-asset-warp.md @@ -0,0 +1,115 @@ +# ADR 0079: Asset Warp: warp meshes, pins and the Asset Warp tool + +* Status: accepted (2026-11-12) +* Relates to: roadmap M7, issue #213 (mesh and warp deformers), ADR 0043 (bone poses, which + pin poses mirror), ADR 0071 (shape armatures), ADR 0032 (bitmaps on the GPU), ADR 0004 + (destructive actions), ADR 0003 (file format) + +## Context + +Animate's Asset Warp tool puts pins on a shape or a bitmap; the artwork is covered by a +deformation mesh, and dragging pins bends it. Pins are posed per keyframe and tween. Behaviour +was learned from Adobe's public help pages and from watching the program; no code was copied. +We need: where the mesh and pins live, which deformation, how a bent bitmap is drawn by the CPU +oracle and the GPU stage, how pins tween, and what exports do, while `evaluate` stays pure and +everything is bounded. + +## Decision + +1. **The warp is on the shape.** A bitmap on the stage is already a shape filled with its image, + so `Shape.warp: Option>` (`#[serde(default, skip_serializing_if)]`: files without + it read and write as before) covers both. `Warp { rest, resolution, pins, shown }`: the + outline as drawn, cells along the mesh's longer side (2–48, default 12), pins + `{id, rest, at}` (the point of the artwork as drawn and where it is now, in the shape's + space; ids from the document's counter, counted on load) and a fingerprint of the outline it + gave the shape. The shape's `path` is the bent outline, so the file holds what shows. +2. **The mesh is a grid, not stored.** A grid over the rest outline's control-point bounds, + square-ish cells, each split into two triangles with the diagonals alternating like a + chequerboard (no preferred direction). It is a pure function of `rest` and `resolution`, so + it is never out of date and costs nothing in the file. At most 49 × 49 vertices. +3. **Deformation: rigid moving least squares** (S. Schaefer, T. McPhail and J. Warren, *Image + deformation using moving least squares*, SIGGRAPH 2006, §2.3), evaluated at the mesh's + vertices, piecewise affine between them. Each vertex moves by the rotation and translation + that best carry the pins (weighted `1 / d²`) where they are. We chose it over the two-step + as-rigid-as-possible method of Igarashi, Moscovich and Hughes (SIGGRAPH 2005) because it is a + closed form per vertex: no sparse factorisation to write and refactor when pins change, no + iterations to cap or converge, exactly deterministic, and its cost is bounded by + vertices × pins (at most 2,401 × 128). It interpolates the pins, moves rigidly with one or + two pins, and is near-rigid elsewhere (tested: a turn has distortion < 10⁻³; a 30° bend + < 0.25). What ARAP on a mesh that follows the outline would add is topology awareness (two + legs that touch don't drag each other); that is the place to go next (not yet). +4. **Outlines map through the mesh.** Straight edges are split where they cross the mesh's + edges, so a line maps exactly to the mesh's image of it (a bitmap's outline is exactly the + mesh's border). Curves are split into pieces no longer than half a cell; each end maps + through its triangle, and a cubic's handles through the triangle of the end they belong to, + so smooth points stay smooth. **At rest** (every pin where it was placed) the outline is the + drawing's very `Arc`, so the rest pose reproduces the artwork bit for bit (tested on the + path and on rendered pixels). +5. **Stale warps.** Other tools may change a warped shape's path. The warp then no longer shows + (its fingerprint differs): `evaluate` draws the path as it is and ignores the warp, and the + next warp command starts again from the shape as it now is, its pins kept where they show + (`Warp::rebased`), so nothing jumps. A fingerprint is used rather than recomputing and + comparing the outline, so floating-point differences between machines can never drop a warp. +6. **Pins per keyframe, tweened.** Adding a warp puts it on every keyframe of the layer holding + the same artwork; adding or removing a pin does so on every keyframe bending the same mesh + (an added pin sits where that point shows there). Moving a pin is the pose of the keyframe at + the frame (keyed inside a classic or shape tween, as editing tweened objects is; motion tweens + are refused). A classic tween between two keyframes on the same mesh blends the pins with the + span's easing and bends the rest outline (`evaluate`'s `interpolate`), so a tween never + blends two bent outlines and never drifts. A tweened element carries its blended warp, so a + frame keyed mid-tween captures the pins. +7. **Bitmaps: textured triangles in the oracle, the same fill on the GPU.** `DisplayItem.warp` + carries the bent mesh for a bent bitmap fill. The CPU oracle prepares the fill as an image of + its own over the fill's pixel bounds: each triangle carries its pixel centres back to the + image (its exact affine map) and samples it as an unwarped bitmap is sampled (bilinear, or the + nearest pixel without Allow Smoothing); later triangles win where the mesh folds; edge pixels + no triangle covers take a neighbour's colour so the outline's antialiasing has a colour. The + fill is then a `Shader::Bitmap` of that image, one pixel per surface pixel, nearest, with the + item's colour effect. `prepare_scene` hands the GPU stage that very fill, so the GPU needed no + change and matches the oracle exactly (the parity test: 0 of 6,480 pixels differ). A GPU + textured-triangle path, which would avoid preparing the image on the CPU each frame, is not + yet. +8. **Exports through `evaluate`.** Raster exports (PNG, GIF, APNG, WebP, video) are the renderer. + SVG and Lottie write warped shapes as their bent outlines; SVG bakes a bent bitmap into a + PNG `` at twice the stage's resolution where it shows (canvas and SVG have no mesh + fills); Lottie already reports bitmap fills; the HTML export reports bent bitmaps (the image + shows unbent in its bent outline). +9. **Commands** (`warp.*`, a namespace plug-ins may call): `warp.add {element?, resolution?}` + (or the resolution of an existing warp; in Modify › Asset Warp), `warp.pin_add {element?, x, + y}` (adds the mesh when there is none), `warp.pin_move {element?, pin, x?, y? | dx?, dy?, + frame?}`, `warp.pin_remove`, `warp.remove` (the artwork as drawn again on every keyframe; in + Modify › Asset Warp; undoable, so ADR 0004's routine tier: no confirmation) and `warp.info`. + A warped shape becomes a drawing object, so merge drawing never cuts it. +10. **The shell.** The **Asset Warp** tool (Shift+Q, after Free Transform, as Animate groups + it): a click on artwork pins it (the first pin makes the mesh) and picks the pin, a click on + a pin picks it, a drag on a pin moves it live (many `warp.pin_move` in one gesture: one undo + step), a drag on artwork adds a pin and drags it (one step), Delete removes the picked pin + and Esc drops the pick. The mesh shows faintly in the layer's colour, pins as white dots + (the picked one in the selection colour). Properties › Asset Warp: resolution, pin count, + Remove Pin, Remove Warp. + +## Bounds and numbers + +Resolution 2–48; 128 pins; 20,000 anchors per warped outline (Optimize first beyond it); a bent +outline of at most 400,000 commands (past it nothing is split); coordinates within ±1,000,000; +a prepared bitmap image of at most 2²⁶ pixels. Measured (optimised dev profile, this machine): +bending a 1,200-anchor outline on a 48 × 48 mesh with 32 pins takes 0.36 ms per frame; drawing +a 960 × 480 px bent bitmap with a 48-cell mesh takes 7.9 ms against 3.9 ms flat. + +## Consequences + +* Files without warps are written exactly as before. An older AniCraft reading a newer file + ignores `warp` and shows each keyframe's bent outline (a bitmap unbent inside it); pin poses + hold instead of tweening. +* A warp with no extent or too many points is dropped on load (the shape keeps what it shows); + non-finite and repeated pins are dropped. +* The `panic_hunt_every_command` fuzz runs a warped session (a rectangle and a bitmap, a pin + posed inside a tween) with hostile warp params. + +## Not yet + +* As-rigid-as-possible solving on a mesh that follows the outline; meshes for symbols and text; + warp pins bound to bones (Animate's bones on warped assets); a warp deformer over several + layers (Live2D's, from #213). +* A GPU textured-triangle path; bent bitmaps in HTML canvas and Lottie. +* XFL import of warped assets. diff --git a/docs/adr/0080-drawing-parity-leftovers.md b/docs/adr/0080-drawing-parity-leftovers.md new file mode 100644 index 00000000..dc6880cd --- /dev/null +++ b/docs/adr/0080-drawing-parity-leftovers.md @@ -0,0 +1,145 @@ +# ADR 0080: Drawing parity leftovers + +* Status: accepted (2026-11-12) +* Relates to: ADR 0031 (merge drawing), ADR 0033 (Brush tool), ADR 0045 (symbols in place), + ADR 0073 (groups and Combine Objects), ADR 0004 (destructive actions), ADR 0002 (render + pipeline) + +## Context + +The user guide's drawing chapter listed everyday Animate drawing features AniCraft still +lacked: PolyStar's Polygon option, the Brush's Paint Selection and Paint Inside modes, entering a +drawing object with a double-click, Envelope (and Delete Envelope), and gradient and bitmap +strokes. Artists coming from Animate reach for these without thinking. We learned the behaviour +from Adobe's public help pages and by watching the program; nothing was copied. + +## Decision + +### 1. PolyStar options + +`draw.star` takes `shape` (`star` or `polygon`), `sides` (3 to 64; `points` still works) and +`point_size` (0 to 1). The tool shows them inline in its options (Shape, Sides or Points, +Point size), not as Animate's modal Tool Settings dialog: our tools keep their settings in +Properties, and the principles ask for no modal interruptions. The row is called **Shape** +because **Style** already names the line style just above it. + +**Point size**, our definition: the inner corners lie at `r · size · cos(π/n)`. At 1 they are on +the edges of the polygon through the tips, so the star *is* that polygon; at 0 they meet in the +centre (needle points); between, the depth is proportional. Animate documents only the range and +"closer to 0, narrower points", which this matches. An explicit `inner` radius still wins, so +older scripts draw what they drew. The outline goes through `add_shape`, so it merges or is a +drawing object exactly as the other shape tools (ADR 0031). Geometry: `Path::polystar`, +`polystar_corners`, `star_inner_radius` in `anicraft_geom`, tested analytically (polygon area +n/2 · r² · sin(2π/n), star area n · r · r_in · sin(π/n)). + +### 2. Paint Selection and Paint Inside + +ADR 0033 left them out because the merge couldn't clip paint to a region. It can now: +`planar::intersect(subject, rule, region)` is `merge_cut` of the subject alone, keeping the +pieces inside the cutter; `planar::union` merges fills of one style into non-overlapping loops. +Both are exact to the merge's snap (0.2 units), like everything else on the planar map. + +* **Paint Selection**: the brush outline is clipped to the union of the selected fills on the + active layer. Afterwards the selection is what lies in that region (the fills' pieces and the + paint), so the next stroke paints there too, as in Animate. +* **Paint Inside**: clipped to the topmost fill under the stroke's first point. Started on empty + stage, it is clipped to the empty area the lines and fills close off there (the Paint + Bucket's `enclosed_area`); if that area is open, it paints only empty areas (Paint Behind). +* Both go **under the lines** (`Order::UnderLines`): clipped paint never covers a line. +* Off Object Drawing only raw fills count as regions (merged paint lies under drawing objects, + so painting "inside" one would be hidden; it is edited inside it, §3). On Object Drawing any + fill counts, and the clipped paint is a drawing object. +* Nothing painted (no selection, or the stroke misses the region) changes nothing: no keyframe, + no undo step, `{"painted": false, "reason": …}`; the shell says why in the status bar. + +The live preview still shows the raw sweep (ADR 0033); the clipped result appears on release. + +### 3. Editing a drawing object in place + +A double-click (or Ctrl+E, `symbol.edit`) opens a drawing object as groups open (ADR 0073), a new +editing level `Opened::Drawing`. On opening, the object is replaced *in place* by a group of its +one raw shape (same id, name, transform and colour effect; the shape unmoved inside), so every +command, merge drawing included, works inside it unchanged, and its raw shapes merge only with +each other. The picture doesn't change, so opening is no undo step. + +Closing turns it back: one shape left becomes one drawing object again (its id, name and place; +the transforms compose); nothing left removes it; several pieces stay a **group of raw shapes**, +which is what Combine Objects' Union already makes of shapes of several colours (ADR 0073). A +drawing object of several pieces needs no new element kind. Opening and closing without an +edit restores the document and its state id exactly (the level keeps them), so it never looks +unsaved. Undo inside goes back inside (the level is in the snapshot, ADR 0045). + +*Rejected:* a `drawing` flag on groups, or a multi-shape drawing object kind: a second +representation of an existing concept, in the file format, every exporter and the importers, +for no visible difference. + +### 4. Envelope + +**Modify › Transform › Envelope** opens an envelope on the selected shapes and drawing objects +(not symbols, text, groups or bitmaps, as in Animate). The bend is a **bicubic Bézier patch** +(`anicraft_geom::envelope`): 4 × 4 control points over the selection's outline bounds. At rest +they are a third of the way apart and the map is exactly the identity (Bernstein polynomials +reproduce linear functions; tested command for command). The shell shows the 12 boundary +handles: squares for corners (a corner's two tangents move with it) and circles for tangents. +The four inner points follow the boundary as a Coons patch, so a side bends the inside smoothly. + +The image of a cubic under the patch is degree 9, so each segment is halved until the cubic +through its mapped control points is within 0.05 units of the true image at its quarter points +(at most 10 halvings, 200 000 commands). A line that stays straight (any affine part of the +mesh) stays one line. + +**Baked, as Animate bakes it.** The shapes stay ordinary paths; there is no envelope in the +model, so there is nothing for Delete Envelope to delete, and it isn't added. Each move bends the +shapes *as they were when the envelope opened*, so moves never compound their approximation. +The session keeps, with each mesh, the shapes it made, and finds the mesh whose shapes are on +the stage: undo and redo restore the mesh with the shapes, with no change to the undo +snapshots. A drag (one gesture, one undo step) keeps only its last mesh. The envelope ends when +its shapes are no longer the selection or are edited otherwise; the shell then sends +`modify.envelope_close`, which merges bent raw shapes with the drawing they lie on (as after a +move). Gradients and bitmaps in the fills stay where they were (Animate doesn't bend them +either). + +Commands: `modify.envelope` (opens; returns the mesh), `modify.envelope_move` (`points`, the +whole mesh, or `index`, `x`, `y`; one undo step), `modify.envelope_close`. They are in the +`modify` namespace, which plug-ins may already call. + +### 5. Gradient and bitmap strokes: proposed, not in this slice + +The CPU renderer path is straightforward: a stroke's outline is filled, so its shader could take +any `Paint` (`Shader::new(&Paint::Solid(st.color), …)` becomes the stroke's paint). The model +change would be `Stroke { paint: Option }` beside `color` (`#[serde(default)]`; `color` +stays the solid colour older readers and the merge's style table use). But every consumer of +`Stroke::color` must carry it: the GPU stage's stroke path, SVG, HTML Canvas and Lottie export, +XFL import of ``, the merge's stroke styles, Ink Bottle, Eyedropper, +mixed-selection Properties and the colour picker. That is about 35 sites and its own golden +tests, so it is the next PR, not a corner of this one. + +## Consequences + +* Measured in release (median of 9, one thread): + + | Operation | Time | + | --- | --- | + | Brush, 1000 px wave, size 30, over an outlined oval, Paint Normal | 4.9 ms | + | Same, Paint Inside (clip, then a smaller merge) | 4.7 ms | + | Same, Paint Selection (union, clip, reselect) | 6.6 ms | + | Envelope move on a 32-point star and an oval | 0.03 ms | + +* Tests: PolyStar areas (analytic, merge and object), bad options; Paint Selection and Inside + areas (a 100 × 20 band; a half-round cap plus a band), lines left whole, empty areas, no step + when nothing paints; drawing objects opened and closed unchanged (document and state), + merged only inside, kept as one object, removed when emptied, undo inside; Envelope identity + at rest, an analytic bend (area + lift · width / 2), undo restoring the mesh, a 300-move drag + as one step, moves that don't compound, refusals, raw shapes merging on close; `planar` + union and intersection areas; the patch's identity, affine and tolerance properties. The + `panic_hunt_every_command` fuzz covers the new commands and params. +* Saving while a drawing object is open saves it as a group of its pieces; it opens as a group. +* Warped artwork (Asset Warp, ADR 0079) neither opens in place nor takes an envelope: its warp + keeps the outline as drawn on every keyframe of its layer, and either edit would fight it. + The message says to edit its pins or remove the warp first. + +## Not yet + +Gradient and bitmap strokes (§5); envelope handles from the keyboard (the menu command and the +`modify.envelope_move` command work without a pointer, the handles don't take focus yet); an +envelope that remembers itself after it closes; the brush's live preview clipped as it paints. diff --git a/docs/guide/drawing.md b/docs/guide/drawing.md index 84450989..cd213d9e 100644 --- a/docs/guide/drawing.md +++ b/docs/guide/drawing.md @@ -29,7 +29,7 @@ your hand. | Eraser | **E** | Rub out lines and fills | | Rectangle | **R** | Draw rectangles and squares | | Oval | **O** | Draw ovals and circles | -| PolyStar | none | Draw stars | +| PolyStar | none | Draw polygons and stars | | Line | **N** | Draw straight lines | | Paint Bucket | **K** | Fill enclosed areas, or recolour fills | | Ink Bottle | **S** | Give a shape the current stroke | @@ -73,6 +73,13 @@ The Eraser only erases merged drawing. Drawing objects, symbols and text are lef it. To turn a drawing object back into merged drawing, select it and choose **Modify › Break Apart** (**Ctrl+B**): it merges with the merged shapes it touches. +To change a drawing object's shape, **double-click** it (or select it and press **Ctrl+E**). +It opens in place, as a group does (see [Grouping](#grouping)): the rest of the stage dims, and +the bar above the stage shows **Scene 1 › Drawing Object**. Inside, its lines and fills are +merged drawing, cutting and joining only each other, and every tool works on them. +Double-click empty stage to go back. It stays one object; if your edits left it in several +pieces, it becomes a group of them. + As in Animate, what you've just drawn isn't selected, so no box gets in the way of the next stroke. Switch to the Selection tool (**V**) to pick it up. @@ -110,9 +117,11 @@ unlocked layer at once. **Edit › Deselect All** is **Ctrl+Shift+A**. * **Rectangle** (**R**): drag to draw. **Shift** draws a square. Set **Corners** in the options for rounded corners. * **Oval** (**O**): drag to draw. **Shift** draws a circle. -* **PolyStar**: drag from the centre to draw a star. **Points** in the options sets how many - points it has (3 to 32). It has no shortcut by default, because P is the Pen, as in Animate. - Polygons aren't available yet. +* **PolyStar**: drag from the centre to draw a polygon or a star. Its options (Animate's Tool + Settings) are the **Shape**, **Polygon** or **Star**; **Sides** (or **Points**), 3 to 32; + and for a star, the **Point size**, 0 to 1: near 0 the points are thin spikes, and at 1 the + star is the polygon through its tips. It has no shortcut by default, because P is the Pen, as + in Animate. * **Line** (**N**): drag to draw. **Shift** keeps the angle to steps of 45°. * **Pencil** (**Shift+Y**): drag to draw freehand. Choose a mode in the options: **Smooth** evens out your line into flowing curves, **Straighten** turns it into straight @@ -130,8 +139,17 @@ takes back the last point, and **Alt**-click on a line or a selected shape adds The **Brush** (**B**) paints filled shapes in the fill colour: the shape is exactly the area the tip sweeps. A click paints a single dab. The options set the **Size** (or press **[** and **]**), **Shape** (Round or Square), **Angle** and **Roundness** for calligraphic tips, -**Smoothing** to steady a shaky hand, and the **Mode**: **Paint Normal** covers lines and -fills, **Paint Fills** leaves lines alone, and **Paint Behind** paints only empty areas. With +**Smoothing** to steady a shaky hand, and the **Mode**: + +* **Paint Normal** covers lines and fills. +* **Paint Fills** leaves lines alone. +* **Paint Behind** paints only empty areas. +* **Paint Selection** paints only inside the selected fills. Select them with the Selection tool + first; they stay selected, so you can keep painting. +* **Paint Inside** paints only inside the fill where your stroke starts, however far you go + past its edge. Started on empty stage inside an outline, it fills only that empty area. + +The last three never cover lines. With a pen tablet, pressure sets the width, from 10 % to the full size. **Snapping while you draw**: with **Snap to Objects** on (the magnet under the tools, or **Ctrl+Shift+/**), the Line, @@ -315,6 +333,17 @@ the proportions, **Alt** scales from the centre), just outside a corner to **rot **Break Apart** turns text into shapes, a symbol instance into the artwork inside it, and a drawing object into merged drawing. +### Envelope + +**Modify › Transform › Envelope** bends the selected shapes and drawing objects. A mesh of +handles appears around them, with the Free Transform tool: **squares** move a corner (its +side's handles move with it) and **circles** bend a side. Each drag is one undo step, and +undo puts the mesh back where it was too. The envelope ends when you select something else or +pick another tool; bent merged drawing then joins what it lies on. The bend is part of the +shapes from then on, as in Animate, so there is nothing to delete (Animate's Delete Envelope +isn't needed). Symbols, text, groups and bitmaps can't be bent: break them apart first. Artwork with an Asset +Warp mesh can't either: remove its warp first. + ## Copying, arranging and aligning ### Clipboard and duplicates @@ -439,8 +468,7 @@ without snapping. Rulers, the grid and guides never show in Test Movie or in exp ## Not there yet -Not in AniCraft yet: Envelope and **Delete Envelope**; gradient and bitmap -strokes; swatch folders, bitmap swatches and the swatches inside Animate files; entering a drawing object -with a double-click; PolyStar's Polygon option; the Paint Selection and Paint Inside -brush modes, brush libraries and tilt; erasing inside symbols; and Animate's ragged, stipple -and hatched line styles (drawn solid when you open an Animate file). +Not in AniCraft yet: gradient and bitmap strokes; swatch folders, bitmap swatches and the +swatches inside Animate files; moving the Envelope's handles from the keyboard; pen tilt for +brushes; erasing inside symbols; and Animate's ragged, stipple and hatched line styles (drawn +solid when you open an Animate file). diff --git a/docs/guide/masks-guides-camera-bones.md b/docs/guide/masks-guides-camera-bones.md index 6faf9634..3d1ad3d4 100644 --- a/docs/guide/masks-guides-camera-bones.md +++ b/docs/guide/masks-guides-camera-bones.md @@ -1,7 +1,7 @@ # Masks, guides, camera and bones Some layers do a special job. This chapter covers mask layers, guide layers and motion guides, -the camera layer, and bones for posing a character. +the camera layer, bones for posing a character, and Asset Warp for bending artwork with pins. A note on keys: AniCraft uses **Ctrl** on Windows and Linux and **⌘** (Command) on macOS, and **Alt** is **⌥** (Option) on macOS. So **Ctrl+Z** is **⌘Z** on a Mac. @@ -251,6 +251,43 @@ Not there yet: symbols and shapes in one armature, reshaping a shape after it ha springs, joints that slide, armatures that scripts pose while the movie plays, and armatures from Animate files. +## Asset Warp + +Asset Warp bends a shape or a bitmap with pins, without bones: a flag in the wind, a squashed +ball, a character's sleeve, a photo curled at one corner. + +1. Pick the **Asset Warp** tool (**Shift+Q**, next to Free Transform). +2. Click the artwork to pin it there. The first pin covers it with a **warp mesh**, a fine grid + that shows faintly while the tool is in hand. Add a few more pins: where the artwork should + hold still, and where you want to pull it. +3. Drag a pin. The artwork bends around the other pins as you drag, keeping its parts as + rigid as it can (no shearing or squashing near the pins). With only one pin, the whole thing + moves. Dragging artwork where there is no pin adds one there and drags it. Each drag is one + undo step. + +Click a pin to pick it (it turns blue), then press **Delete** to remove it, or **Esc** to let +it go. Pins don't move anything when you add them, and the artwork with all its pins where you +placed them looks exactly as you drew it. + +**Animating a warp.** Pins live on keyframes, like a pose. Make a keyframe (**F6**), move the +pins there, and add a classic tween between the keyframes: the pins tween with the span's +easing and the artwork bends smoothly between the two shapes. Moving a pin in the middle of a +tween adds a keyframe there. A pin you add later appears on every keyframe of the artwork. + +**Properties › Asset Warp** shows the mesh's **resolution** (cells along the artwork's longer +side: more cells bend more smoothly, fewer are faster), how many pins it has, **Remove Pin** +and **Remove Warp** (the artwork goes back to how you drew it, on every keyframe). The same +commands are in **Modify › Asset Warp**. + +The warped artwork becomes a drawing object, so shapes you draw later don't cut into it. If you +reshape it with another tool afterwards, the warp starts again from the new shape, with its +pins where they are. A gradient fill keeps its place while the outline bends; a bitmap bends +with the mesh. Every export shows the bent artwork. SVG writes a bent bitmap as an image, and +HTML and Lottie can't bend a bitmap yet (the export report says so). + +Not there yet: warping symbols and text, tying pins to bones, and warped artwork from Animate +files. + ## Next steps * More on layers and keyframes: [The timeline](timeline.md). diff --git a/docs/guide/reference/commands.md b/docs/guide/reference/commands.md index 8fd24b33..8f38334b 100644 --- a/docs/guide/reference/commands.md +++ b/docs/guide/reference/commands.md @@ -1,6 +1,6 @@ # Command reference -Everything you can do in AniCraft is a command: the menus, the shortcuts, the command palette (**Ctrl+K**, macOS **⌘K**), `anicraft-cli` and AI assistants over MCP all run the same 302 commands, listed here by menu. The id is what scripts and [working headless](../working-headless.md) use; the parameters are what a command takes as JSON. Commands that change the document are one undo step each. Your own shortcuts (**F1**) replace the defaults shown here; see the [shortcut reference](shortcuts.md). +Everything you can do in AniCraft is a command: the menus, the shortcuts, the command palette (**Ctrl+K**, macOS **⌘K**), `anicraft-cli` and AI assistants over MCP all run the same 311 commands, listed here by menu. The id is what scripts and [working headless](../working-headless.md) use; the parameters are what a command takes as JSON. Commands that change the document are one undo step each. Your own shortcuts (**F1**) replace the defaults shown here; see the [shortcut reference](shortcuts.md). This page is generated from the command registry, so it always matches the version of AniCraft it came with. @@ -82,7 +82,7 @@ This page is generated from the command registry, so it always matches the versi - **Paste in Place** `edit.paste_in_place` · **Ctrl+Shift+V** (macOS **⇧⌘V**) · changes the document Parameters: `{} (layers as edit.paste)` - **Edit Symbols** `symbol.edit` · **Ctrl+E** (macOS **⌘E**) - Parameters: ``{id?: instance element id, symbol?: library symbol id} opens a symbol's timeline for editing: the instance `id` (default: the selected instance) in place, or a Library symbol at the stage's centre. Every command then works inside it. With nothing to open while a symbol is open, goes back to the document (Animate's Ctrl+E)`` + Parameters: ``{id?: instance element id, symbol?: library symbol id} opens a symbol's timeline for editing: the instance `id` (default: the selected instance) in place, or a Library symbol at the stage's centre. A group (ADR 0073) or a drawing object (ADR 0080) opens in place the same way: inside, its raw shapes merge only with each other, and a drawing object closes as one object again (a group of its pieces when an edit left several). Every command then works inside it. With nothing to open while a symbol is open, goes back to the document (Animate's Ctrl+E)`` - **Edit Document** `symbol.exit` Parameters: `{all?: bool} closes the open symbol (default: one level; all: back to the scene), selecting the instance it was opened from` - **Find and Replace** `find.search` · **Ctrl+F** (macOS **⌘F**) @@ -150,6 +150,8 @@ This page is generated from the command registry, so it always matches the versi - **Document Settings** `doc.set_stage` · changes the document Parameters: `{width?, height?, fps?, background?: "#rrggbb"}` +- **Envelope** `modify.envelope` · Modify › Transform + Parameters: `{} opens an envelope around the selected shapes and drawing objects on the active layer (ADR 0080): a mesh of 4 × 4 Bézier control points over their bounds, at rest → {points: [[x, y] × 16] (row by row from the top-left), bounds: [x, y, w, h], shapes}. Then modify.envelope_move bends them. Symbols, text, groups and bitmaps can't be bent: break them apart first` - **Delete Layer** `layer.delete` · Modify › Timeline · changes the document Parameters: `{layer? (a folder goes with its contents)}` - **Move Layer Up** `layer.move_up` · Modify › Timeline · changes the document @@ -162,6 +164,10 @@ This page is generated from the command registry, so it always matches the versi Parameters: `{layer?, name?, type?: normal|mask|masked|guide|guided, mask?: coverage|alpha|luminance (a mask layer's mask type), color?, outline?: bool (view as outlines), height?: 100|200|300, visible?, locked?, onion?} sets several at once, as one undo step; answers with the layer's properties` - **Remove Camera** `camera.remove` · Modify › Timeline · changes the document Parameters: `{} (removes the camera layer and its moves; asks first when the camera is animated)` +- **Add Warp Mesh** `warp.add` · Modify › Asset Warp · changes the document + Parameters: `{element? (a shape or bitmap; default the one selected), resolution? (cells along the longer side, 2…48; default 12)} → {element, created, resolution, columns, rows}. Covers the artwork with a warp mesh on every keyframe of its layer that holds it (it becomes a drawing object); on artwork that has one, changes the mesh's resolution` +- **Remove Warp** `warp.remove` · Modify › Asset Warp · changes the document + Parameters: `{element?} takes the warp mesh and its pins off the artwork on every keyframe of its layer: it shows as drawn again` - **Add Shape Hint** `tween.add_hint` · Modify › Shape · **Ctrl+Shift+H** (macOS **⇧⌘H**) · changes the document Parameters: `{layer?, frame? (in the shape tween, or the keyframe it ends on)} → the new hint's letter; it starts at the shapes' centre, unplaced` - **Remove All Hints** `tween.clear_hints` · Modify › Shape · changes the document @@ -267,6 +273,10 @@ These commands have no menu item: the panels, the stage and the timeline use the Parameters: `{folder, name, category?, confirm}: removes a user template and its picture (cannot be undone)` - **List Templates** `file.templates` Parameters: `{folder? (the user templates folder)} → {builtin: [{id, name, category, description, width, height, fps, frames}], user: [{name, category, path, thumbnail}]}` +- **Envelope** `modify.envelope_move` · changes the document + Parameters: `{points: [[x, y] × 16] (the whole mesh) | index: 0..15, x, y (one control point; a corner or side handle moves the inner points with it, as a Coons patch), tolerance? (stage units, default 0.05)} bends the open envelope's shapes from where they were when it opened → {points, shapes}. One undo step` +- **Close Envelope** `modify.envelope_close` · changes the document + Parameters: `{} closes the open envelope: bent raw shapes merge with the drawing they now touch (as after a move). Nothing to close is no error → {closed}` - **Publish Settings** `publish.settings_set` · changes the document Parameters: `{profile? (a whole profile, as publish.settings_get returns it), format? (html | gif | apng | webp | video | lottie | sprite_sheet | png_sequence | png | svg | audio), enabled?, output? (relative to the document's folder; {name} is the document's name), and that format's options: title, sound, fit (html); from, to, scale, loop (gif); from, to, scale, loop (true, false or how many times it plays; 0: forever), background (apng, webp); from, to, scale, audio (video); from, to, background (lottie); from, to, scale, columns, padding, background (sprite_sheet); from, to, scale (png_sequence); frame, scale (png); frame (svg); from, to, rate, bits (audio). from/to/frame are movie frames, null for the movie's ends}` - **Open Recent** `file.open_recent` @@ -349,6 +359,14 @@ These commands have no menu item: the panels, the stage and the timeline use the Parameters: `{bone, x, y (stage px: where the bone's end goes), local?: [x, y] (the point dragged, in the bone's instance's space; default its end), frame?} → {reached, error (px), chain}; inverse kinematics turns the bone and the bones above it (limits respected, pinned bones kept)` - **Armatures** `bone.info` Parameters: `{frame?, layer?, points?: bool} → every armature on the scene at the frame: its bones with joint and end (stage px), joint angle and limits (°), pinned; a shape armature's shape, how many points each bone moves, and with points the shape's points (stage px) and the bones each follows` +- **Add Warp Pin** `warp.pin_add` · changes the document + Parameters: `{element?, x, y (stage px, on the artwork)} → {element, pin, created}. Pins the artwork there (adding the mesh first if it has none), on every keyframe that bends the same mesh; nothing moves` +- **Move Warp Pin** `warp.pin_move` · changes the document + Parameters: `{element?, pin, x?, y? (stage px: where the pin goes), dx?, dy? (stage px: by how much), frame?} → {element, pin, at}. Bends the artwork at the frame (keying it inside a tween); pins tween between keyframes` +- **Remove Warp Pin** `warp.pin_remove` · changes the document + Parameters: `{element?, pin} removes the pin from every keyframe that bends the same mesh; the artwork follows the pins that are left` +- **Warp Mesh** `warp.info` + Parameters: `{element?, frame?} → the artwork's warp at the frame: resolution, the mesh's columns, rows, vertices and triangles, whether it is bent, and its pins (id, where they show in stage px, and where they were placed on the artwork as drawn, in its own space)` - **Property Keyframe** `motion.set_key` · changes the document Parameters: `{property: x|y|scale_x|scale_y|rotation|skew|alpha|brightness|tint (amount)|tint_red|tint_green|tint_blue (0..255)|red_multiplier|green_multiplier|blue_multiplier|alpha_multiplier (%)|red_offset|green_offset|blue_offset|alpha_offset (-255..255), value (px, %, °), frame?, layer?} (colour properties of several styles compose into Advanced, ADR 0056)` - **Remove Property Keyframe** `motion.remove_key` · changes the document @@ -406,7 +424,7 @@ These commands have no menu item: the panels, the stage and the timeline use the - **Oval** `draw.ellipse` · changes the document Parameters: `{x, y, w, h, fill?, stroke?, stroke_width?, profile?, cap?, join?, style?, dash?, object?}` - **PolyStar** `draw.star` · changes the document - Parameters: `{cx, cy, outer, inner?, points?, fill?, stroke?, profile?, cap?, join?, style?, dash?, object?}` + Parameters: `{cx, cy, outer (the corners' radius), shape?: star|polygon (default star; the PolyStar Tool Settings, ADR 0080), sides? (or points; 3..64, default 5), point_size? (0..1, default 0.5: how deep a star's points are, 1 is the polygon through its tips), inner? (an exact inner radius instead of point_size), fill?, stroke?, stroke_width?, profile?, cap?, join?, style?, dash? (the line style), object?}` - **Line** `draw.line` · changes the document Parameters: `{x0, y0, x1, y1, stroke?, stroke_width?, profile? (a width profile name or [[t, left, right], ..]), cap?, join?, miter?, style?, dash?, dash_offset?, dot_spacing? (the line style, as stroke.set_style; default: the tool's), object? (true: a drawing object; default: Object Drawing, off: it merges with the raw shapes it touches)}` - **Object Drawing** `draw.object_drawing` · **J** @@ -522,7 +540,7 @@ These commands have no menu item: the panels, the stage and the timeline use the - **Movie Explorer** `explorer.tree` Parameters: `{scope?: document (default) | scene, show?: {text?, symbols?, scripts?, media?, frames? (layers and keyframes)} (each default true), definitions?: bool (the Library's symbols; default true), expanded?: [row keys] (default: the top rows), all?: bool (everything open), filter?: text (rows whose names hold it, and the rows above them), offset?, limit? (default 1000, at most 10000)} → {rows: [{key, depth, kind, type?, name, extra, frame?, children, open, go: find.goto params}], total, truncated}` - **Brush Stroke** `draw.brush` · changes the document - Parameters: `{points: [[x, y] or [x, y, pressure 0..1 (clamped)], ..] (one point paints a dab), preset? (a brush from brush.preset_list, by key or name: its settings are the defaults for the rest), size? (stage units, default 10), shape?: round|square, angle? (degrees), roundness? (5..100 %, default 100), smoothing? (0..100, default 50), curve?: linear|soft|firm|[[pressure, output], ..] (how pressure maps, both 0..1), pressure_size? (default true: pressure varies the size from 10 to 100 %), pressure_opacity? (default false: the stroke's average pressure sets its opacity), taper_start?, taper_end? (0..50 % of the stroke's length), spacing? (0 continuous, or 5..1000 % of the size between dabs), jitter? (0..50 % of the size: a ragged edge), as_stroke? (default false; true: the Paint Brush, a variable-width stroke in the stroke colour, editable with the Width tool), mode?: normal|fills|behind (Paint Normal covers fills and lines, Paint Fills leaves lines, Paint Behind paints only empty areas), color? (default: the fill colour, or the stroke colour as a stroke), unit? (stage units per screen point, default 1: smoothing and accuracy follow it), object?}` + Parameters: `{points: [[x, y] or [x, y, pressure 0..1 (clamped)], ..] (one point paints a dab), preset? (a brush from brush.preset_list, by key or name: its settings are the defaults for the rest), size? (stage units, default 10), shape?: round|square, angle? (degrees), roundness? (5..100 %, default 100), smoothing? (0..100, default 50), curve?: linear|soft|firm|[[pressure, output], ..] (how pressure maps, both 0..1), pressure_size? (default true: pressure varies the size from 10 to 100 %), pressure_opacity? (default false: the stroke's average pressure sets its opacity), taper_start?, taper_end? (0..50 % of the stroke's length), spacing? (0 continuous, or 5..1000 % of the size between dabs), jitter? (0..50 % of the size: a ragged edge), as_stroke? (default false; true: the Paint Brush, a variable-width stroke in the stroke colour, editable with the Width tool), mode?: normal|fills|behind|selection|inside (Paint Normal covers fills and lines, Paint Fills leaves lines, Paint Behind paints only empty areas, Paint Selection only inside the selected fills, Paint Inside only inside the fill the stroke starts on or the empty area closed off around it; ADR 0080), color? (default: the fill colour, or the stroke colour as a stroke), unit? (stage units per screen point, default 1: smoothing and accuracy follow it), object?}` - **Brush Presets** `brush.preset_list` Parameters: `{} the built-in brushes and yours, with their settings` - **Save Brush** `brush.preset_save` diff --git a/docs/guide/reference/shortcuts.md b/docs/guide/reference/shortcuts.md index 418f93aa..a5e006f1 100644 --- a/docs/guide/reference/shortcuts.md +++ b/docs/guide/reference/shortcuts.md @@ -21,6 +21,7 @@ This page is generated from the editor's shortcut map, so it always matches the | Selection | V | V | | Subselection | A | A | | Free Transform | Q | Q | +| Asset Warp | Shift+Q | ⇧Q | | Gradient Transform | F | F | | Width | U | U | | Bone | M | M | diff --git a/docs/roadmap.md b/docs/roadmap.md index fbc1f784..a04984e9 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -10,8 +10,8 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a |---|---| | Architecture | M0 skeleton in place: geom → doc → render → engine → cli → shell, layering enforced by `cargo test` (`src/architecture_tests.rs`: lower layers only, no UI crates below the shell, and the AGENTS.md map must match). | | Rendering | CPU oracle with analytic AA, non-zero/even-odd, solid + linear/radial gradients (with reflect/repeat, focal points, elliptical radials and linear RGB, ADR 0074), round-join strokes. **Mask clipping**: the display list carries nested clips; a clip is the anti-aliased union of its mask fills (strokes and opacity ignored), intersected with any enclosing clip, computed once per render band; an empty mask hides everything under it. **Soft masks** (ADR 0070): a mask layer's mask type is Shape (coverage), Alpha (its artwork's opacity as drawn: gradients, faded shapes, strokes, bitmaps) or Luminance (brightness × opacity, SVG's coefficients), in the CPU oracle (analytic tests), the GPU stage (parity: mean 0.00006, worst 1 step of 255), SVG export (`` with `mask-type`), Lottie (alpha and luma track mattes) and the HTML canvas; Layer Properties › Mask type. **Group alpha**: a symbol instance below full opacity is a group in the display list; each render band composites the group's run of ops into its own buffer (nested groups stack) and blends it once at the group's alpha, so overlaps don't show through; SVG export writes ``. **Blend modes** (Animate's 14, on movie clip and button instances): an instance with one is an isolated group that blends at its close with the W3C separable formulas on premultiplied colour (Alpha and Erase keep or clear the backdrop); SVG gets CSS `mix-blend-mode`, Lottie the layer `bm`. **Bitmaps**: `Paint::Bitmap` fills (once or tiled) with bilinear sampling in premultiplied space, colour effects per sample; PNG/JPEG import to stage (a rectangle of the image's size); stored in the document as PNG (base64 in `.anicraft`), decoded once on first use; SVG export embeds each image once as a pattern. **Filters**: a filtered group is drawn on its own (by the same renderer, recursively, so nested filters work) into a buffer over its artwork grown by the filters' reach, filtered (box-blur passes; shadow and glow from the blurred, offset opacity; **bevel and gradient bevel** from the difference of the blurred opacity offset towards and away from the light, **gradient glow** from the glow's intensity, both through a colour ramp whose rest stop is pinned transparent, inner/outer/full and knockout, ADR 0025; colour matrix), and composited back as one image in its group, so alpha and blend apply; clips from inside the symbol apply before filtering and the instance's own clip after. **GPU stage, first slice** (M3, ADR 0019; `--features gpu-stage`, off by default): Preferences › Stage › Renderer *GPU (preview)* draws the stage with wgpu compute from the oracle's own prepared fills (tile binning with per-row backdrops on the CPU, exact area coverage and src-over per pixel on the GPU): solid and gradient fills and strokes, non-zero and even-odd; masks, group opacity, blend modes, filters and bitmaps fall back to the CPU per tile, and the status bar says so. Parity with the oracle: max 1/255, mean < 0.0001/255 on the sample, stress and analytic scenes (tests skip without an adapter). 4K with 1,000 shapes: 8.8–9.0 ms vs the CPU's 17.4–17.8 ms. **Second slice** (ADR 0029): on the window's wgpu device the stage tiles are drawn straight into textures egui shows (no readback; a headless device with readback when the window is on OpenGL); **masks** (nested, united artwork), **group opacity** and **all 14 blend modes** on the GPU, same parity (max 1/255, mean ≤ 0.0011/255); 4K: 1,000 shapes in 2.1–2.4 ms, 10k shapes in 10.2 ms as stage tiles, masked scenes 7× the CPU. **Third slice** (ADR 0032): **bitmap fills** (textures uploaded once per image and cached under a 256 MB budget, sampled with the oracle's own bilinear filter, colour effect and repeat rules: byte-identical) and **all seven filters** (each filtered symbol drawn into a layer of its own and filtered by compute passes that run the oracle's resolved steps: max 1/255, mean ≤ 0.007/255) on the GPU; the shaders now build with Direct3D's FXC, so DX12 windows get the GPU stage too (parity suite green on Vulkan and DX12); software adapters are refused (the CPU is faster), the start-up self-test compares with the oracle. **The GPU is the default stage renderer**: the shell's `gpu-stage` feature is on by default, Preferences › Stage › Renderer defaults to *Graphics card (GPU)*, and the CPU draws whenever there is no usable card, a tile is past the GPU's limits (more than 16 images, filters nested deeper than 4) or anything fails. 4K: the filtered sample in 3.9 ms (CPU 31.5), 200 bitmap fills in 4.4 ms (CPU 37.2). **Fourth slice** (ADR 0048): **tile binning on the GPU** for heavy frames without masks or groups (count, prefix sum, scatter and tile-list passes, no atomics, no readback; the CPU binning stays the reference and does the rest; one tile format for both: an integer backdrop per tile and steps on the tiles' left edges): on Vulkan, 10k shapes at 4K in one texture 21.7 → 4.7 ms, 50k shapes 122 → 22.5 ms, the 50k-shape 4K stage 75 → 37 ms (Direct3D 12 keeps CPU binning: slower there in stage tiles); and **hairlines** for outline mode in both renderers (coverage by distance, one edge per segment): onion outlines on the 2,000-item stress scene as fast as tinted (GPU stage 73 → 10 ms, CPU stage 34–39 → 17 ms at 1080p). Not yet: sharing a filtered layer across a frame's tiles, more than 16 images per tile, GPU binning inside masks and groups, flattening and stroking on the GPU, buffer reuse and fewer dispatches across tiles, hairlines for sub-pixel strokes, GPU exports, a GPU runner in CI; the CPU stays the oracle and the export path. | -| Timeline | **Frame selection**: click, Shift-click or drag across frames and layers; F5/Shift+F5, F6/F7 and Shift+F6 (keys, icon buttons and right-click menu) act on the whole selection; with no frame selection F5 extends every layer with frames at or after the playhead, and F5/F6/F7 move the playhead on as in Animate (F6/F7 on a keyframe key the next frame; `all_layers`/`advance` headless); drag selected keyframes left or right to move them, and up or down onto other layers (the source keeps empty frames, as in Animate) (with a drop outline; one undo step; keys they land on are replaced, and spans fill the frames left behind); removing or clearing selected frames that hold artwork asks first. **Cut/Copy/Paste Frames** (Ctrl+Alt+X/C/V, and plain Ctrl+X/C/V after clicking the timeline): own clipboard, copies cut exactly at the selection edges (mid-tween state kept), paste inserts like Animate, several layers paste onto the layers below (missing ones are created), fresh element ids, symbols travel with them. **Span length by dragging its end** (resize cursor, live outline with the length in frames and seconds; later frames move with it). Headless: `layers`/`count` on the frame commands, `timeline.move_keyframes`, `timeline.cut_frames/copy_frames/paste_frames`. Layers (show/lock/outline), **timeline polish** (ADR 0061): a per-layer **onion skin toggle** column (Alt-click solos; left-out layers aren't onion-skinned; Edit Multiple Frames unaffected), the colour square toggles **View as Outlines** in the layer colour **on the stage only** (exports, Test Movie and the player draw the artwork as it is), the **colour chip** opens the layer colour (swatches, hex, More…), **onion frames of the parent timeline** dimmed around a symbol edited in place, **Layer Height** 100/200/300 %, **Layer Properties** (double-click the layer icon; name, show/lock, type, outline colour, outlines, onion, height; one undo step), **Frame View** (Tiny/Small/Normal/Medium/Large, Short rows) with the frame zoom in the timeline's bottom bar (the header fits at the default window size, tested); headless `layer.set_onion/set_color/set_height/set_properties/properties`; XFL `heightMultiplier`. Not yet: folder onion toggles, onion of deeper parent timelines, multi-layer Layer Properties and layer transparency, frame thumbnails (Preview). Keyframes, blank keyframes, insert/remove frames, classic tweens with 8 easing presets + curve preview, **shape tweens** (morph between any two shapes: segments made cubic, subpaths paired by size and grown from or shrunk to a point when counts differ, segment counts equalized by subdivision, windings matched and start points aligned; amber spans; classic ⇄ shape keeps the easing; **shape hints** (ADR 0023): Modify › Shape › Add Shape Hint (Ctrl+Shift+H) adds lettered markers `a`–`z` that the artist drags onto an edge on the first and last keyframe (rose until placed, amber placed on the first, mint on the last; right-click removes), the morph cuts both outlines at the hinted points and matches the pieces in order by length; `tween.add_hint/move_hint/remove_hint/clear_hints/hints`; not yet: View › Show Shape Hints, hints inside symbols edited in place), auto-key when editing inside a tween, frame labels, symbol nesting: graphics keep step with their timeline (loop, play once, single frame, first frame; set in Properties), movie clips loop their own timeline from when the instance appears (continuous across keyframes holding the same instance), buttons show their Up frame, looping playback. **Onion skin and Edit Multiple Frames** (ADR 0047): onion markers on the frame ruler (drag the start and end brackets; Always Show Markers, Anchor Markers, Onion 2 / Onion 5 / Onion All, also on a right-click on the ruler), frames before and after the playhead tinted in their own colours (theme blue and green, changeable in the onion menu, Reset) and fading with distance, Outlines, Keyframes Only, locked layers left out as in Animate, each layer's onion frames under its own artwork and over the layers below; options saved in the preferences; the stage's frame cache keys every look apart. **Edit Multiple Frames** shows every keyframe within the markers at full strength and selects (click, Shift-click, marquee, Select All) and moves (drag, arrow keys) artwork across them, one undo step, motion tween paths moving with their objects. Headless: `frames.artwork`, `frames.edit_multiple`. **Edit Multiple Frames, complete** (ADR 0051): Cut, Copy, Paste (current frame), Paste in Place (back keyframe by keyframe, or a one-frame copy onto every keyframe between the markers), Clear, Align (Ctrl+Alt+1…6, To Stage), Rotate 90° and Flip, and **Free Transform** of the selection on every keyframe about one shared pivot (one box, one undo step per drag); raw shapes moved, transformed or pasted merge again on their own keyframe; **onion skin and Edit Multiple Frames inside a symbol edited in place**, on its own timeline and markers. Headless: `frames.transform`, `frames.align`, `frames.delete`, `frames.copy`, `frames.cut`, `frames.paste`, `frames.merge`, `merge` on `frames.edit_multiple`. Not yet: per-layer onion toggles, Duplicate/Distribute/Arrange and recolouring across keyframes, scaling a motion tween's object on several frames, a draggable pivot, onion frames of the timeline around an open symbol. **Mask layers**: right-click a layer › Mask turns it into a mask over the layer below (Masked adds more layers to it); masked layers are indented under a stencil icon; the mask applies on the stage and in every export alike, and while the mask layer is unlocked its edge shows in the layer colour so it can be picked and reshaped; masked-away parts cannot be picked; layers moved in under a mask join it, moved out leave it, and a mask moves with its whole group; masks inside symbols nest. Headless: `layer.toggle_mask`, `layer.set_type`. **Scenes** (ADR 0011): the movie is an ordered list of scenes, each its own timeline, edited one at a time (scene menu on the edit bar, Insert › Scene, Modify › Scene, Shift+PageUp/PageDown); add, duplicate (fresh ids), rename, reorder and remove (asks when the scene has artwork; undoable); PNG-sequence and GIF exports play every scene in order. **Layer folders**: nestable folders (depth ≤ 16) holding layers and masks through `Layer.parent`, one invariant (`Timeline::repair_masks`: a child sits below its parent inside the parent's unbroken run; broken links fall back to the nearest valid ancestor); hiding or locking a folder hides or locks its contents (rendering, picking, drawing); folders open and close on the timeline (view state); layers move in and out with Up/Down, a folder moves with its contents; deleting a folder deletes its contents (asks first). **Motion tweens** (ADR 0016): a span's object animated property by property (x, y, scale, rotation, skew, alpha, tint), each property its own curve of property keyframes with a per-segment ease (presets or a custom cubic Bézier, overshoot allowed); auto-key turns any edit of the object inside the span into property keys (every command, through the session), F6 keys every property, splits and copies keep the motion; sky-blue spans with property-key diamonds; **Motion Editor** tab beside the timeline: property list with values at the playhead, curve graph with draggable keys and Bézier handles, one undo step per drag. **Motion paths** (ADR 0030): a motion tween may carry a cubic path its object travels by arc length, timed by the X/Y curves (a straight path reproduces them exactly, overshoot included); shown on the stage in the motion colour with a dot per frame when the object or span is selected; Selection drags the path to bend it and its ends to move them, Subselection drags anchors and handles; moving the object reshapes the path; Orient to path and Straighten in Properties; splits cut the path. **Path points** (ADR 0038): with Subselection, double-click the path to add a point (shape and motion unchanged), Shift-click to select several anchors, Delete to remove them (the path refits through the rest; the ends stay), right-click for smooth/corner and Straighten; the Pen's Alt-click adds a point to a motion path or a selected shape; Ctrl-drag (⌘-drag) the path or its object, or edit Properties › Path start, to move the whole path with its timing exact. **Anchors pinned to frames** (ADR 0049): moving the object at a frame pins a path point there (a new anchor where it was put; after the last position key the path carries on), and the object passes every pinned point exactly on its frame, the X/Y eases timing it between pins; pinned points are diamonds with their frame number on the stage, blue keys in the Motion Editor's X/Y (dragging one moves its point) and holed diamonds on the timeline; Subselection's right-click pins to the playhead's frame or unpins, Properties › Frame has Pin Here / Unpin, F6 pins where the object is; point edits keep pins on their anchors; files without pins evaluate exactly as before. Headless: `timeline.create_motion_tween`, `motion.*` (`motion.set_path/clear_path/orient/add_point/delete_points/convert_point/move_path/pin_point/unpin_point`; `motion.info` reports `pins`). Not yet: retiming a pin by dragging its key in time, two pins on one anchor, XFL motion path keyframes, a marquee over path anchors, nudging or transforming a whole path, retiming keys, rescaling keys with the span, XFL motion-tween import. **Bones and IK, first slice** (ADR 0043): the Bone tool (M) drags from one symbol instance to another to join them with a bone on an armature layer (chains join end to start: a bone from a chained instance always starts at its joint; branches allowed, up to 256 bones); bones show as wedges in the layer colour; the Selection tool drags a bone (the grabbed point follows) or a posed instance to pose by cyclic coordinate descent (joint limits, pinned bones, one undo step per drag) and the root to move it all; poses are joint angles keyed per frame and tweened with the span's easing; Properties › Bone (angle, constrain min/max, pin, remove); `bone.*` headless; every export sees the pose. **Shape armatures** (ADR 0071): the Bone tool draws bones inside a shape (it moves to an armature layer as an object, outside merge drawing); its points are bound to the nearest bones automatically (weights by distance to each bone, up to four, summing to 1) and bend by linear blend skinning (handles with their anchors, strokes keep their width, the rest pose exact); the **Bind tool** (Shift+M) shows the points (squares, triangles where shared) and binds them by click, Shift/Ctrl-click or box; the same IK, poses and tweens; `bone.add_in_shape`, `bone.bind`, `bone.info {points}`. Not yet: spring, joint translation, runtime armatures, XFL import, editing members' properties in place, mixing instances and shapes in one armature, reshaping a bound shape, painted weights. **Camera layer** (ADR 0027): the camera button in the timeline header or the Camera tool (C) adds a Camera layer on top; its frame shows on the stage in orange; drag to pan, turn with the round handle, wheel to zoom (one undo step per drag); Properties › Camera (position, zoom, rotation, tint, reset); keyframes and classic or motion tweens animate it; layer Depth gives pan parallax; View › Preview Through Camera shows the movie's picture (artwork tools pause there); hiding the camera layer turns it off; every export, Test Movie and the GPU stage see it. Headless: `camera.add/remove/set/info`, `layer.set_depth`. **Camera, second slice** (ADR 0082): layer depth in a pinhole perspective (deeper layers move and zoom less, draw behind nearer ones; depth 0 bit-exact), depth keyed over time (linear between keys), **Window › Layer Depth** (layers by depth, drag nearer or farther, key, attach), **Attach Layer to Camera** (timeline toggle; HUDs stay on screen), camera colour effects (Brightness, Tint, Advanced), and the Selection tool picking and moving artwork while previewing through the camera; headless `layer.set_depth {key, frame}`, `layer.remove_depth_key`, `layer.set_attached`, `layer.depths`, `element.pick {view: camera}`. Not yet: other tools while previewing, depth inside symbols, depth keys moving with inserted frames, XFL camera and layer-depth import (no public format description). **Motion guides**: guided layers (children of a guide through `Layer.parent`) have their classic tweens follow the guide's first path by arc length, from the point nearest each start keyframe to the point nearest its end (`geom::walk::PathWalk`), optionally orienting to the path; guide artwork is listed for picking and editing, drawn on the stage as a line, and never rendered or exported. | -| Drawing | Selection (click, shift-add, marquee, drag-move, arrow nudge; **across layers**, ADR 0044: a selection holds artwork on several visible, unlocked layers, the timeline marks them, Properties shows mixed values), **Free Transform (Q)**: scale from corner/edge handles (Shift proportional, Alt from centre), rotate outside corners (Shift snaps 15°), move; one undo step per drag. Rectangle (corner radius), oval, PolyStar, line (45° snap), hand, zoom. **Pen (P)**: click for corners, drag for smooth handles (Alt breaks them), close on the first point, Enter/Esc/last-point click finishes, Backspace takes back a point; one undo step per path. **Pencil (Shift+Y)**: Smooth (Schneider curve fitting with corner detection), Straighten and Ink modes, smoothing relative to the screen. **Subselection (A)**: anchors and handles on selected shapes, drag points/handles (anchors bring their handles; one undo step per drag), point marquee, double-click an edge to add a point, Delete removes points, right-click Make Smooth/Corner; closed shapes' start point and closing edge edit like any other. **Cut/Copy/Paste in Center/Paste in Place** (the clipboard carries symbols across documents). **Rotate 90° CW/CCW, Flip H/V. Align** left/centre/right/top/middle/bottom (Ctrl+Alt+1…6; a single element aligns to the stage) and distribute. Convert to symbol / break apart; arrange; duplicate. Headless: `draw.path`, `draw.freehand`, `path.move_points/add_point/delete_points/convert_point`. **Paint Bucket (K)**: click a fill to recolour it, or inside an outline (one shape or several) to fill the enclosed area; gap size None/Small/Medium/Large closes openings; the fill is traced and curve-fitted into a new shape placed under its lines; open areas say so instead of flooding. **Ink Bottle (S)**: gives the clicked shape the current stroke. Headless: `paint.bucket`, `paint.ink`. Tool options show first in Properties while a drawing tool is active. **Text (T)** (ADR 0012): click to type on the stage, click or double-click text to edit it; font (installed families, plus the embedded Inter), size, colour, under or over the artwork, snap accuracy up to Always); Snap to Pixels; one snap engine for every drawing tool, the Selection tool's moves and Free Transform's handles (point › guide › line › grid › pixel, guides and grid per axis); stage only, never exported, on the CPU and GPU stage. Headless: `view.rulers`, `view.grid_show/grid_snap/grid_set`, `view.guides_show/guides_lock/guides_snap/guides_set`, `view.guide_add/guide_move/guide_delete/guides_clear`, `view.snap_pixels`, `view.aids`, `moving` on `draw.snap`. *Not yet:* units other than px, a movable ruler origin, a symbol's own guides, guides and grid from Animate files, Snap Align and Edit Snapping, snapping while rotating. bold, italic, alignment, letter/line spacing, wrap width; the last style is kept for new text; laid out by `anicraft-text` (`fontdb` discovery, `harfrust` shaping, `skrifa` outlines) and stored as outlines with the source, so rendering never needs the font; Break Apart makes a shape. **Variable-width strokes** (ADR 0018): a stroke's width varies along it through width points (position by arc length, a width on each side as a factor of the stroke width, smooth monotone interpolation); built-in profiles (Uniform, Taper both ends, Taper start, Taper end, Bulge, Pinch) in Properties › Width with a picture of each, and in the drawing tools' options for new strokes; the **Width tool (U)**: hover a stroke to see its width points, drag a handle to widen or narrow (Alt: one side), drag the dot to slide a point, drag anywhere on the stroke to add one, Delete removes; one undo step per drag; rendered by the oracle as trapezoids with outer round joins and cross-section caps, written by SVG and Lottie export as the same filled outlines; shape tweens blend profiles; `.anicraft` keeps them (older files open as uniform). Headless: `stroke.set_profile`, `stroke.set_width_point`, `stroke.delete_width_point`, `stroke.width_at`, `profile` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: width data from or to Animate files, saved custom profiles, pressure. **Stroke styles** (ADR 0046): Properties › Style (Solid, Dashed with dash and gap, Dotted with spacing), Cap (None, Round, Square), Join (Miter, Round, Bevel) and Miter limit, also in the drawing tools' options for new strokes; drawn exactly by the oracle (butt and square caps, miters bevelled past the limit, dashes by arc length restarting per subpath, round dots, dashes keeping a width profile's widths; sub-pixel patterns solid and faded) and so by the GPU stage; the Ink Bottle carries the style and the Eyedropper picks it; merge drawing keeps it on cut pieces; shape tweens blend miter limits and dash lengths; SVG, HTML canvas and Lottie export write it. Headless: `stroke.set_style`, and `cap`, `join`, `miter`, `style`, `dash`, `dash_offset`, `dot_spacing` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: Animate's ragged, stipple and hatched styles, multi-dash patterns in Properties (kept and editable by command), stroke scale modes and hairlines. **Merge drawing** (ADR 0031, first slice): with Object Drawing (J) off, the editor's default, the shape tools, Pen and Pencil draw raw strokes and fills that cut and join the raw shapes they touch (a fill on top replaces what it covers or joins the same colour, lines cut each other and the fills they cross, a fill hides the lines under it, points within 0.2 px are one; exact Bézier pieces, `anicraft_geom::planar`); one element per fill region and stroke run, selected with Animate's dot pattern; double-click selects connected strokes, or a fill with its outline; a dragged or nudged raw shape merges where it lands; arrows move 1 screen pixel (Shift 10). Headless: `object` on the drawing commands (scripts draw objects by default), `draw.object_drawing`, `draw.drop`, `element.select_connected`. **Selection tool on raw shapes** (ADR 0041): drag an unselected segment or fill edge to bend it through the pointer (every shape sharing the edge bends with it), an unselected corner or end to move it with every raw shape that shares it, a fill to move only that fill; points and selections snap to points, strokes and fill edges within 10 screen px (snap ring), and arrow nudges join ends within 0.2 px at their midpoint or onto a line that stays put; a corner or curve mark by the pointer shows what a drag does; the marquee selects the parts of raw fills and strokes under it, cut at its edges (taken back if nothing uses them, no undo step), and objects wholly inside; each drag one undo step, merged on release. Headless: `path.bend_segment`, `raw.move_point`, `raw.select_rect`, `raw.merge`, `raw.hit`, `snap` on `element.translate`. **Subselection on raw shapes and merging everywhere** (ADR 0042): with Subselection (A), a click on a raw line or fill shows the anchors of everything connected to it (once per shared point; hollow, selected ones solid) and the handles of the selected anchors' curves and of the clicked edge; drag an anchor to move it with the other selected ones and every shape on them, a handle to change the curve in every shape that has the edge, a line or fill to move everything connected; Shift adds or removes anchors; the marquee takes whole shapes on the active layer and selects the anchors inside; arrows nudge 1 screen px (Shift 10); one undo step per gesture, merged on release. **Snap to Objects** (View › Snapping, a magnet under the tools, the selection tools' options) switches the Selection and Subselection tools' snapping. The Paint Bucket's raw fills are exact (up to the lines and fill edges, from the planar merge) and join fills of their colour; pasted raw shapes cut what they land on; raw shapes from Animate files open raw and merged; gradient and bitmap fills take part in the merge. Headless: `raw.subselect`, `raw.subselect_rect`, `raw.points`, `raw.move_handle`, `with` on `raw.move_point`, `draw.snap_to_objects`, `object` on `paint.bucket`. Not yet: width profiles in the merge. **Raw points and symbols in place** (ADR 0045): add a point on a raw edge (Pen Alt-click, Subselection double-click; every shape on the edge gets it, the curve unchanged), delete raw points (Delete; the shapes on each are joined across it so the drawing stays connected; points where three edges meet are kept), Make Smooth / Corner on raw points, smooth handle pairs (Alt breaks them; drawing objects too); the Line, Rectangle, Oval, PolyStar and Pen tools snap their points within 10 screen px (Snap to Objects, Ctrl+Shift+/); a double-click on an instance (or Ctrl+E, or a double-click in the Library) opens the symbol in place, the stage dimmed around it, the edit bar showing the path back, and every tool and command works on its timeline. Headless: `raw.add_point`, `raw.delete_points`, `raw.convert_points`, `draw.snap`, `smooth` on `raw.move_handle` and `path.move_points`, `symbol.edit`, `symbol.exit`. Not yet: rotated instances in place (they open upright). Onion skin and Edit Multiple Frames work inside a symbol since ADR 0051. **Brush (B)** (ADR 0033, first slice): paints filled shapes in the fill colour, the exact area the tip sweeps (a distance field traced and fitted with cubics); round or square tip with size, angle and roundness (oval and flat calligraphic tips), pen pressure from a tablet (10–100 % of the size; a mouse paints full size), smoothing relative to the screen, Paint Normal, Paint Fills and Paint Behind; a raw shape that merges with the drawing, or a drawing object with Object Drawing on; a click paints a dab; live preview while dragging; `[` and `]` change the size; one undo step per stroke. Headless: `draw.brush`. Not yet: Paint Selection and Paint Inside. **Brush library, pressure curves and the Paint Brush (Y)** (ADR 0068, first slice): Window › Brush Library with seven built-in brushes made only of parameters (Pencil, Ink Pen, Flat Calligraphy, Round Taper, Marker, Chalk with a deterministic worn edge, Dotted stamps), each with a stroke preview drawn by the renderer; brushes of your own saved by name in your preferences, renamed, deleted (asks first) and moved between computers as a JSON brush set; a pressure curve editor (Linear, Soft, Firm, or your own points) driving size and, optionally, the stroke's opacity; tapers, dab spacing and a rough edge in Properties; Velocity (mouse speed as pressure, off by default); the Paint Brush draws a width-profiled stroke in the stroke colour that the Width tool edits. Headless: `brush.preset_list/save/rename/delete/export/import`, `preset`, `curve`, `as_stroke` and the shaping params on `draw.brush`. Not yet: pen tilt (egui doesn't report it), opacity varying along a stroke, textured or art brushes, Eraser presets and pressure. **Eraser (E)** (ADR 0034, first slice): sweeps the Brush's tip and takes what it covers out of the raw shapes on the active layer (the sweep is a fill in the planar merge that comes out empty); Erase Normal, Erase Fills, Erase Lines, Erase Selected Fills and Erase Inside; the Faucet deletes a whole fill or line with a click; drawing objects, symbols and text are kept; a stroke that erases nothing leaves no undo step; live preview, `[` and `]` sizes, one undo step per stroke; double-clicking the tool (or Erase Everything… in its options) clears the visible, unlocked layers at this frame after asking. **Eyedropper (I)** (first slice): a click on a fill picks its paint (solid, or a gradient or bitmap kept where it is on the stage, as Lock Fill) into the fill swatch, a click on a line picks its colour, width and profile; with shapes selected it applies the style to them; then it becomes the Paint Bucket or the Ink Bottle; Shift-click picks into the other swatch only. Headless: `draw.erase`, `draw.faucet`, `draw.erase_all`, `paint.pick`, `paint.apply_style`. Not yet: erasing inside symbols, erasing width-profiled shapes (gradient fills erase since ADR 0042), eraser pressure, picking a bitmap's pixel colour or text styles, an eyedropper cursor. **Colour picker and drawing-tool fixes from user reports** (M1): every colour swatch (the Tools panel's fill and stroke squares too) opens one picker with Animate's web-safe swatches (216 colours, greys and primaries), the colours mixed or typed this session, a hex field and the full mixer; the Tools squares offer No Colour and recolour selected shapes; drawing tools leave nothing selected after a stroke and the Selection tool's box has no handles (they are Free Transform's); Break Apart turns drawing objects into merged drawing; Ctrl-drag on a raw edge adds a corner point; the Pencil and Line show no fill. Not yet: entering a drawing object by double-click. **Swatches panel** (ADR 0078): Window › Swatches, the document's saved colours and gradients (in the `.anicraft` file; a default set for new documents and older files); click applies to the selection and the tool colour, to the stroke or fill that is active (Tools squares, Colour panel or the panel's toggle; gradients always to the fill); + adds the active colour or gradient, Duplicate, Delete, drag (or Alt+arrows) to reorder, names on hover, Clear (keeps black and white) and Load Default Swatches (ask first, undoable); import and export as a JSON swatch file, GIMP `.gpl` import; the colour picker shows the document's swatches and the fill picker its gradient swatches. Headless: `swatch.list/add/remove/move/duplicate/rename/apply/clear/reset/import/export`. Not yet: swatch folders, sorting by colour, bitmap swatches, Save as Default, XFL swatch import (no public description), Adobe `.aco`/`.ase`/`.clr` (proprietary). The layer footer is icon buttons (New Layer, Delete, New Folder, Up, Down) that fit at any size and language. **Groups and Combine Objects** (ADR 0073): Modify › Group (Ctrl+G) / Ungroup (Ctrl+Shift+G), a group element whose members are a one-layer, one-frame timeline, opened in place by a double-click like a symbol (every tool works inside; raw shapes merge only with each other); nested groups; exports, player, sounds and the Library see inside; XFL `DOMGroup` imports as groups. Combine Objects › Union, Intersect, Punch, Crop on the planar map (analytic area tests). Selection tool: Alt-drag copies, Shift constrains to 45° (Ctrl/⌘-drag corners: #257). *Not yet:* Envelope / Delete Envelope, drawing objects edited without opening them (#181), Combine across layers. **Rulers, grid and guides** (ADR 0076): View › Rulers (stage pixels, following zoom and pan, pointer marked); guides per scene saved in the document, dragged from a ruler, moved with the Selection tool, dragged back to delete, Show/Lock/Snap/Edit/Add/Clear (Edit Guides lists and adds them from the keyboard); a grid (spacing, | +| Timeline | **Frame selection**: click, Shift-click or drag across frames and layers; F5/Shift+F5, F6/F7 and Shift+F6 (keys, icon buttons and right-click menu) act on the whole selection; with no frame selection F5 extends every layer with frames at or after the playhead, and F5/F6/F7 move the playhead on as in Animate (F6/F7 on a keyframe key the next frame; `all_layers`/`advance` headless); drag selected keyframes left or right to move them, and up or down onto other layers (the source keeps empty frames, as in Animate) (with a drop outline; one undo step; keys they land on are replaced, and spans fill the frames left behind); removing or clearing selected frames that hold artwork asks first. **Cut/Copy/Paste Frames** (Ctrl+Alt+X/C/V, and plain Ctrl+X/C/V after clicking the timeline): own clipboard, copies cut exactly at the selection edges (mid-tween state kept), paste inserts like Animate, several layers paste onto the layers below (missing ones are created), fresh element ids, symbols travel with them. **Span length by dragging its end** (resize cursor, live outline with the length in frames and seconds; later frames move with it). Headless: `layers`/`count` on the frame commands, `timeline.move_keyframes`, `timeline.cut_frames/copy_frames/paste_frames`. Layers (show/lock/outline), **timeline polish** (ADR 0061): a per-layer **onion skin toggle** column (Alt-click solos; left-out layers aren't onion-skinned; Edit Multiple Frames unaffected), the colour square toggles **View as Outlines** in the layer colour **on the stage only** (exports, Test Movie and the player draw the artwork as it is), the **colour chip** opens the layer colour (swatches, hex, More…), **onion frames of the parent timeline** dimmed around a symbol edited in place, **Layer Height** 100/200/300 %, **Layer Properties** (double-click the layer icon; name, show/lock, type, outline colour, outlines, onion, height; one undo step), **Frame View** (Tiny/Small/Normal/Medium/Large, Short rows) with the frame zoom in the timeline's bottom bar (the header fits at the default window size, tested); headless `layer.set_onion/set_color/set_height/set_properties/properties`; XFL `heightMultiplier`. Not yet: folder onion toggles, onion of deeper parent timelines, multi-layer Layer Properties and layer transparency, frame thumbnails (Preview). Keyframes, blank keyframes, insert/remove frames, classic tweens with 8 easing presets + curve preview, **shape tweens** (morph between any two shapes: segments made cubic, subpaths paired by size and grown from or shrunk to a point when counts differ, segment counts equalized by subdivision, windings matched and start points aligned; amber spans; classic ⇄ shape keeps the easing; **shape hints** (ADR 0023): Modify › Shape › Add Shape Hint (Ctrl+Shift+H) adds lettered markers `a`–`z` that the artist drags onto an edge on the first and last keyframe (rose until placed, amber placed on the first, mint on the last; right-click removes), the morph cuts both outlines at the hinted points and matches the pieces in order by length; `tween.add_hint/move_hint/remove_hint/clear_hints/hints`; not yet: View › Show Shape Hints, hints inside symbols edited in place), auto-key when editing inside a tween, frame labels, symbol nesting: graphics keep step with their timeline (loop, play once, single frame, first frame; set in Properties), movie clips loop their own timeline from when the instance appears (continuous across keyframes holding the same instance), buttons show their Up frame, looping playback. **Onion skin and Edit Multiple Frames** (ADR 0047): onion markers on the frame ruler (drag the start and end brackets; Always Show Markers, Anchor Markers, Onion 2 / Onion 5 / Onion All, also on a right-click on the ruler), frames before and after the playhead tinted in their own colours (theme blue and green, changeable in the onion menu, Reset) and fading with distance, Outlines, Keyframes Only, locked layers left out as in Animate, each layer's onion frames under its own artwork and over the layers below; options saved in the preferences; the stage's frame cache keys every look apart. **Edit Multiple Frames** shows every keyframe within the markers at full strength and selects (click, Shift-click, marquee, Select All) and moves (drag, arrow keys) artwork across them, one undo step, motion tween paths moving with their objects. Headless: `frames.artwork`, `frames.edit_multiple`. **Edit Multiple Frames, complete** (ADR 0051): Cut, Copy, Paste (current frame), Paste in Place (back keyframe by keyframe, or a one-frame copy onto every keyframe between the markers), Clear, Align (Ctrl+Alt+1…6, To Stage), Rotate 90° and Flip, and **Free Transform** of the selection on every keyframe about one shared pivot (one box, one undo step per drag); raw shapes moved, transformed or pasted merge again on their own keyframe; **onion skin and Edit Multiple Frames inside a symbol edited in place**, on its own timeline and markers. Headless: `frames.transform`, `frames.align`, `frames.delete`, `frames.copy`, `frames.cut`, `frames.paste`, `frames.merge`, `merge` on `frames.edit_multiple`. Not yet: per-layer onion toggles, Duplicate/Distribute/Arrange and recolouring across keyframes, scaling a motion tween's object on several frames, a draggable pivot, onion frames of the timeline around an open symbol. **Mask layers**: right-click a layer › Mask turns it into a mask over the layer below (Masked adds more layers to it); masked layers are indented under a stencil icon; the mask applies on the stage and in every export alike, and while the mask layer is unlocked its edge shows in the layer colour so it can be picked and reshaped; masked-away parts cannot be picked; layers moved in under a mask join it, moved out leave it, and a mask moves with its whole group; masks inside symbols nest. Headless: `layer.toggle_mask`, `layer.set_type`. **Scenes** (ADR 0011): the movie is an ordered list of scenes, each its own timeline, edited one at a time (scene menu on the edit bar, Insert › Scene, Modify › Scene, Shift+PageUp/PageDown); add, duplicate (fresh ids), rename, reorder and remove (asks when the scene has artwork; undoable); PNG-sequence and GIF exports play every scene in order. **Layer folders**: nestable folders (depth ≤ 16) holding layers and masks through `Layer.parent`, one invariant (`Timeline::repair_masks`: a child sits below its parent inside the parent's unbroken run; broken links fall back to the nearest valid ancestor); hiding or locking a folder hides or locks its contents (rendering, picking, drawing); folders open and close on the timeline (view state); layers move in and out with Up/Down, a folder moves with its contents; deleting a folder deletes its contents (asks first). **Motion tweens** (ADR 0016): a span's object animated property by property (x, y, scale, rotation, skew, alpha, tint), each property its own curve of property keyframes with a per-segment ease (presets or a custom cubic Bézier, overshoot allowed); auto-key turns any edit of the object inside the span into property keys (every command, through the session), F6 keys every property, splits and copies keep the motion; sky-blue spans with property-key diamonds; **Motion Editor** tab beside the timeline: property list with values at the playhead, curve graph with draggable keys and Bézier handles, one undo step per drag. **Motion paths** (ADR 0030): a motion tween may carry a cubic path its object travels by arc length, timed by the X/Y curves (a straight path reproduces them exactly, overshoot included); shown on the stage in the motion colour with a dot per frame when the object or span is selected; Selection drags the path to bend it and its ends to move them, Subselection drags anchors and handles; moving the object reshapes the path; Orient to path and Straighten in Properties; splits cut the path. **Path points** (ADR 0038): with Subselection, double-click the path to add a point (shape and motion unchanged), Shift-click to select several anchors, Delete to remove them (the path refits through the rest; the ends stay), right-click for smooth/corner and Straighten; the Pen's Alt-click adds a point to a motion path or a selected shape; Ctrl-drag (⌘-drag) the path or its object, or edit Properties › Path start, to move the whole path with its timing exact. **Anchors pinned to frames** (ADR 0049): moving the object at a frame pins a path point there (a new anchor where it was put; after the last position key the path carries on), and the object passes every pinned point exactly on its frame, the X/Y eases timing it between pins; pinned points are diamonds with their frame number on the stage, blue keys in the Motion Editor's X/Y (dragging one moves its point) and holed diamonds on the timeline; Subselection's right-click pins to the playhead's frame or unpins, Properties › Frame has Pin Here / Unpin, F6 pins where the object is; point edits keep pins on their anchors; files without pins evaluate exactly as before. Headless: `timeline.create_motion_tween`, `motion.*` (`motion.set_path/clear_path/orient/add_point/delete_points/convert_point/move_path/pin_point/unpin_point`; `motion.info` reports `pins`). Not yet: retiming a pin by dragging its key in time, two pins on one anchor, XFL motion path keyframes, a marquee over path anchors, nudging or transforming a whole path, retiming keys, rescaling keys with the span, XFL motion-tween import. **Bones and IK, first slice** (ADR 0043): the Bone tool (M) drags from one symbol instance to another to join them with a bone on an armature layer (chains join end to start: a bone from a chained instance always starts at its joint; branches allowed, up to 256 bones); bones show as wedges in the layer colour; the Selection tool drags a bone (the grabbed point follows) or a posed instance to pose by cyclic coordinate descent (joint limits, pinned bones, one undo step per drag) and the root to move it all; poses are joint angles keyed per frame and tweened with the span's easing; Properties › Bone (angle, constrain min/max, pin, remove); `bone.*` headless; every export sees the pose. **Shape armatures** (ADR 0071): the Bone tool draws bones inside a shape (it moves to an armature layer as an object, outside merge drawing); its points are bound to the nearest bones automatically (weights by distance to each bone, up to four, summing to 1) and bend by linear blend skinning (handles with their anchors, strokes keep their width, the rest pose exact); the **Bind tool** (Shift+M) shows the points (squares, triangles where shared) and binds them by click, Shift/Ctrl-click or box; the same IK, poses and tweens; `bone.add_in_shape`, `bone.bind`, `bone.info {points}`. Not yet: spring, joint translation, runtime armatures, XFL import, editing members' properties in place, mixing instances and shapes in one armature, reshaping a bound shape, painted weights. **Asset Warp** (ADR 0079): the **Asset Warp tool** (Shift+Q) pins a shape or a bitmap (the first pin covers it with a warp mesh: a grid over its bounds, 2–48 cells along the longer side, Properties › Asset Warp); dragging a pin bends the artwork around the other pins by rigid moving least squares (Schaefer et al. 2006) at the mesh's vertices, live, one undo step per drag; Delete removes a pin; pins are added to every keyframe holding the artwork and their poses tween with classic tweens and easing; shapes bend through the mesh (straight edges exactly, curves split), bitmaps are drawn through its triangles by the CPU oracle (bilinear) and the GPU stage takes the same prepared fill (parity exact); the rest pose is the drawing bit for bit; every raster export, SVG (a bent bitmap baked as an image), Lottie and HTML (a bent bitmap reported) go through `evaluate`; `warp.add`, `warp.pin_add`, `warp.pin_move`, `warp.pin_remove`, `warp.remove`, `warp.info`. Not yet: as-rigid-as-possible solving on a mesh that follows the outline, symbols and text, binding warp pins to bones, a GPU textured-triangle path, bent bitmaps in HTML and Lottie, XFL import of warped assets. **Camera layer** (ADR 0027): the camera button in the timeline header or the Camera tool (C) adds a Camera layer on top; its frame shows on the stage in orange; drag to pan, turn with the round handle, wheel to zoom (one undo step per drag); Properties › Camera (position, zoom, rotation, tint, reset); keyframes and classic or motion tweens animate it; layer Depth gives pan parallax; View › Preview Through Camera shows the movie's picture (artwork tools pause there); hiding the camera layer turns it off; every export, Test Movie and the GPU stage see it. Headless: `camera.add/remove/set/info`, `layer.set_depth`. **Camera, second slice** (ADR 0082): layer depth in a pinhole perspective (deeper layers move and zoom less, draw behind nearer ones; depth 0 bit-exact), depth keyed over time (linear between keys), **Window › Layer Depth** (layers by depth, drag nearer or farther, key, attach), **Attach Layer to Camera** (timeline toggle; HUDs stay on screen), camera colour effects (Brightness, Tint, Advanced), and the Selection tool picking and moving artwork while previewing through the camera; headless `layer.set_depth {key, frame}`, `layer.remove_depth_key`, `layer.set_attached`, `layer.depths`, `element.pick {view: camera}`. Not yet: other tools while previewing, depth inside symbols, depth keys moving with inserted frames, XFL camera and layer-depth import (no public format description). **Motion guides**: guided layers (children of a guide through `Layer.parent`) have their classic tweens follow the guide's first path by arc length, from the point nearest each start keyframe to the point nearest its end (`geom::walk::PathWalk`), optionally orienting to the path; guide artwork is listed for picking and editing, drawn on the stage as a line, and never rendered or exported. | +| Drawing | Selection (click, shift-add, marquee, drag-move, arrow nudge; **across layers**, ADR 0044: a selection holds artwork on several visible, unlocked layers, the timeline marks them, Properties shows mixed values), **Free Transform (Q)**: scale from corner/edge handles (Shift proportional, Alt from centre), rotate outside corners (Shift snaps 15°), move; one undo step per drag. Rectangle (corner radius), oval, PolyStar, line (45° snap), hand, zoom. **Pen (P)**: click for corners, drag for smooth handles (Alt breaks them), close on the first point, Enter/Esc/last-point click finishes, Backspace takes back a point; one undo step per path. **Pencil (Shift+Y)**: Smooth (Schneider curve fitting with corner detection), Straighten and Ink modes, smoothing relative to the screen. **Subselection (A)**: anchors and handles on selected shapes, drag points/handles (anchors bring their handles; one undo step per drag), point marquee, double-click an edge to add a point, Delete removes points, right-click Make Smooth/Corner; closed shapes' start point and closing edge edit like any other. **Cut/Copy/Paste in Center/Paste in Place** (the clipboard carries symbols across documents). **Rotate 90° CW/CCW, Flip H/V. Align** left/centre/right/top/middle/bottom (Ctrl+Alt+1…6; a single element aligns to the stage) and distribute. Convert to symbol / break apart; arrange; duplicate. Headless: `draw.path`, `draw.freehand`, `path.move_points/add_point/delete_points/convert_point`. **Paint Bucket (K)**: click a fill to recolour it, or inside an outline (one shape or several) to fill the enclosed area; gap size None/Small/Medium/Large closes openings; the fill is traced and curve-fitted into a new shape placed under its lines; open areas say so instead of flooding. **Ink Bottle (S)**: gives the clicked shape the current stroke. Headless: `paint.bucket`, `paint.ink`. Tool options show first in Properties while a drawing tool is active. **Text (T)** (ADR 0012): click to type on the stage, click or double-click text to edit it; font (installed families, plus the embedded Inter), size, colour, under or over the artwork, snap accuracy up to Always); Snap to Pixels; one snap engine for every drawing tool, the Selection tool's moves and Free Transform's handles (point › guide › line › grid › pixel, guides and grid per axis); stage only, never exported, on the CPU and GPU stage. Headless: `view.rulers`, `view.grid_show/grid_snap/grid_set`, `view.guides_show/guides_lock/guides_snap/guides_set`, `view.guide_add/guide_move/guide_delete/guides_clear`, `view.snap_pixels`, `view.aids`, `moving` on `draw.snap`. *Not yet:* units other than px, a movable ruler origin, a symbol's own guides, guides and grid from Animate files, Snap Align and Edit Snapping, snapping while rotating. bold, italic, alignment, letter/line spacing, wrap width; the last style is kept for new text; laid out by `anicraft-text` (`fontdb` discovery, `harfrust` shaping, `skrifa` outlines) and stored as outlines with the source, so rendering never needs the font; Break Apart makes a shape. **Variable-width strokes** (ADR 0018): a stroke's width varies along it through width points (position by arc length, a width on each side as a factor of the stroke width, smooth monotone interpolation); built-in profiles (Uniform, Taper both ends, Taper start, Taper end, Bulge, Pinch) in Properties › Width with a picture of each, and in the drawing tools' options for new strokes; the **Width tool (U)**: hover a stroke to see its width points, drag a handle to widen or narrow (Alt: one side), drag the dot to slide a point, drag anywhere on the stroke to add one, Delete removes; one undo step per drag; rendered by the oracle as trapezoids with outer round joins and cross-section caps, written by SVG and Lottie export as the same filled outlines; shape tweens blend profiles; `.anicraft` keeps them (older files open as uniform). Headless: `stroke.set_profile`, `stroke.set_width_point`, `stroke.delete_width_point`, `stroke.width_at`, `profile` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: width data from or to Animate files, saved custom profiles, pressure. **Stroke styles** (ADR 0046): Properties › Style (Solid, Dashed with dash and gap, Dotted with spacing), Cap (None, Round, Square), Join (Miter, Round, Bevel) and Miter limit, also in the drawing tools' options for new strokes; drawn exactly by the oracle (butt and square caps, miters bevelled past the limit, dashes by arc length restarting per subpath, round dots, dashes keeping a width profile's widths; sub-pixel patterns solid and faded) and so by the GPU stage; the Ink Bottle carries the style and the Eyedropper picks it; merge drawing keeps it on cut pieces; shape tweens blend miter limits and dash lengths; SVG, HTML canvas and Lottie export write it. Headless: `stroke.set_style`, and `cap`, `join`, `miter`, `style`, `dash`, `dash_offset`, `dot_spacing` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: Animate's ragged, stipple and hatched styles, multi-dash patterns in Properties (kept and editable by command), stroke scale modes and hairlines. **Merge drawing** (ADR 0031, first slice): with Object Drawing (J) off, the editor's default, the shape tools, Pen and Pencil draw raw strokes and fills that cut and join the raw shapes they touch (a fill on top replaces what it covers or joins the same colour, lines cut each other and the fills they cross, a fill hides the lines under it, points within 0.2 px are one; exact Bézier pieces, `anicraft_geom::planar`); one element per fill region and stroke run, selected with Animate's dot pattern; double-click selects connected strokes, or a fill with its outline; a dragged or nudged raw shape merges where it lands; arrows move 1 screen pixel (Shift 10). Headless: `object` on the drawing commands (scripts draw objects by default), `draw.object_drawing`, `draw.drop`, `element.select_connected`. **Selection tool on raw shapes** (ADR 0041): drag an unselected segment or fill edge to bend it through the pointer (every shape sharing the edge bends with it), an unselected corner or end to move it with every raw shape that shares it, a fill to move only that fill; points and selections snap to points, strokes and fill edges within 10 screen px (snap ring), and arrow nudges join ends within 0.2 px at their midpoint or onto a line that stays put; a corner or curve mark by the pointer shows what a drag does; the marquee selects the parts of raw fills and strokes under it, cut at its edges (taken back if nothing uses them, no undo step), and objects wholly inside; each drag one undo step, merged on release. Headless: `path.bend_segment`, `raw.move_point`, `raw.select_rect`, `raw.merge`, `raw.hit`, `snap` on `element.translate`. **Subselection on raw shapes and merging everywhere** (ADR 0042): with Subselection (A), a click on a raw line or fill shows the anchors of everything connected to it (once per shared point; hollow, selected ones solid) and the handles of the selected anchors' curves and of the clicked edge; drag an anchor to move it with the other selected ones and every shape on them, a handle to change the curve in every shape that has the edge, a line or fill to move everything connected; Shift adds or removes anchors; the marquee takes whole shapes on the active layer and selects the anchors inside; arrows nudge 1 screen px (Shift 10); one undo step per gesture, merged on release. **Snap to Objects** (View › Snapping, a magnet under the tools, the selection tools' options) switches the Selection and Subselection tools' snapping. The Paint Bucket's raw fills are exact (up to the lines and fill edges, from the planar merge) and join fills of their colour; pasted raw shapes cut what they land on; raw shapes from Animate files open raw and merged; gradient and bitmap fills take part in the merge. Headless: `raw.subselect`, `raw.subselect_rect`, `raw.points`, `raw.move_handle`, `with` on `raw.move_point`, `draw.snap_to_objects`, `object` on `paint.bucket`. Not yet: width profiles in the merge. **Raw points and symbols in place** (ADR 0045): add a point on a raw edge (Pen Alt-click, Subselection double-click; every shape on the edge gets it, the curve unchanged), delete raw points (Delete; the shapes on each are joined across it so the drawing stays connected; points where three edges meet are kept), Make Smooth / Corner on raw points, smooth handle pairs (Alt breaks them; drawing objects too); the Line, Rectangle, Oval, PolyStar and Pen tools snap their points within 10 screen px (Snap to Objects, Ctrl+Shift+/); a double-click on an instance (or Ctrl+E, or a double-click in the Library) opens the symbol in place, the stage dimmed around it, the edit bar showing the path back, and every tool and command works on its timeline. Headless: `raw.add_point`, `raw.delete_points`, `raw.convert_points`, `draw.snap`, `smooth` on `raw.move_handle` and `path.move_points`, `symbol.edit`, `symbol.exit`. Not yet: rotated instances in place (they open upright). Onion skin and Edit Multiple Frames work inside a symbol since ADR 0051. **Brush (B)** (ADR 0033, first slice): paints filled shapes in the fill colour, the exact area the tip sweeps (a distance field traced and fitted with cubics); round or square tip with size, angle and roundness (oval and flat calligraphic tips), pen pressure from a tablet (10–100 % of the size; a mouse paints full size), smoothing relative to the screen, Paint Normal, Paint Fills and Paint Behind; a raw shape that merges with the drawing, or a drawing object with Object Drawing on; a click paints a dab; live preview while dragging; `[` and `]` change the size; one undo step per stroke. Headless: `draw.brush`. **Paint Selection and Paint Inside** (ADR 0080): the paint is clipped to the selected fills' union, or to the fill (or closed-off empty area) the stroke starts in, exactly on the planar map, then merged under the lines; Paint Selection keeps the selection for the next stroke. Not yet: the live preview clipped as it paints. **Brush library, pressure curves and the Paint Brush (Y)** (ADR 0068, first slice): Window › Brush Library with seven built-in brushes made only of parameters (Pencil, Ink Pen, Flat Calligraphy, Round Taper, Marker, Chalk with a deterministic worn edge, Dotted stamps), each with a stroke preview drawn by the renderer; brushes of your own saved by name in your preferences, renamed, deleted (asks first) and moved between computers as a JSON brush set; a pressure curve editor (Linear, Soft, Firm, or your own points) driving size and, optionally, the stroke's opacity; tapers, dab spacing and a rough edge in Properties; Velocity (mouse speed as pressure, off by default); the Paint Brush draws a width-profiled stroke in the stroke colour that the Width tool edits. Headless: `brush.preset_list/save/rename/delete/export/import`, `preset`, `curve`, `as_stroke` and the shaping params on `draw.brush`. Not yet: pen tilt (egui doesn't report it), opacity varying along a stroke, textured or art brushes, Eraser presets and pressure. **Eraser (E)** (ADR 0034, first slice): sweeps the Brush's tip and takes what it covers out of the raw shapes on the active layer (the sweep is a fill in the planar merge that comes out empty); Erase Normal, Erase Fills, Erase Lines, Erase Selected Fills and Erase Inside; the Faucet deletes a whole fill or line with a click; drawing objects, symbols and text are kept; a stroke that erases nothing leaves no undo step; live preview, `[` and `]` sizes, one undo step per stroke; double-clicking the tool (or Erase Everything… in its options) clears the visible, unlocked layers at this frame after asking. **Eyedropper (I)** (first slice): a click on a fill picks its paint (solid, or a gradient or bitmap kept where it is on the stage, as Lock Fill) into the fill swatch, a click on a line picks its colour, width and profile; with shapes selected it applies the style to them; then it becomes the Paint Bucket or the Ink Bottle; Shift-click picks into the other swatch only. Headless: `draw.erase`, `draw.faucet`, `draw.erase_all`, `paint.pick`, `paint.apply_style`. Not yet: erasing inside symbols, erasing width-profiled shapes (gradient fills erase since ADR 0042), eraser pressure, picking a bitmap's pixel colour or text styles, an eyedropper cursor. **Colour picker and drawing-tool fixes from user reports** (M1): every colour swatch (the Tools panel's fill and stroke squares too) opens one picker with Animate's web-safe swatches (216 colours, greys and primaries), the colours mixed or typed this session, a hex field and the full mixer; the Tools squares offer No Colour and recolour selected shapes; drawing tools leave nothing selected after a stroke and the Selection tool's box has no handles (they are Free Transform's); Break Apart turns drawing objects into merged drawing; Ctrl-drag on a raw edge adds a corner point; the Pencil and Line show no fill. **Swatches panel** (ADR 0078): Window › Swatches, the document's saved colours and gradients (in the `.anicraft` file; a default set for new documents and older files); click applies to the selection and the tool colour, to the stroke or fill that is active (Tools squares, Colour panel or the panel's toggle; gradients always to the fill); + adds the active colour or gradient, Duplicate, Delete, drag (or Alt+arrows) to reorder, names on hover, Clear (keeps black and white) and Load Default Swatches (ask first, undoable); import and export as a JSON swatch file, GIMP `.gpl` import; the colour picker shows the document's swatches and the fill picker its gradient swatches. Headless: `swatch.list/add/remove/move/duplicate/rename/apply/clear/reset/import/export`. Not yet: swatch folders, sorting by colour, bitmap swatches, Save as Default, XFL swatch import (no public description), Adobe `.aco`/`.ase`/`.clr` (proprietary). The layer footer is icon buttons (New Layer, Delete, New Folder, Up, Down) that fit at any size and language. **Groups and Combine Objects** (ADR 0073): Modify › Group (Ctrl+G) / Ungroup (Ctrl+Shift+G), a group element whose members are a one-layer, one-frame timeline, opened in place by a double-click like a symbol (every tool works inside; raw shapes merge only with each other); nested groups; exports, player, sounds and the Library see inside; XFL `DOMGroup` imports as groups. Combine Objects › Union, Intersect, Punch, Crop on the planar map (analytic area tests). Selection tool: Alt-drag copies, Shift constrains to 45° (Ctrl/⌘-drag corners: #257). **Drawing parity leftovers** (ADR 0080): PolyStar's Shape (Polygon or Star), sides 3–32 and star point size 0–1 in its options (`shape`, `sides`, `point_size` on `draw.star`); a double-click (or Ctrl+E) opens a drawing object in place, its raw shapes merging only with each other, and it closes as one object again (a group of the pieces when an edit leaves several); **Modify › Transform › Envelope**: a Bézier mesh of corner and tangent handles bends the selected shapes and drawing objects, one undo step per drag, baked like Animate's (no Delete Envelope needed), undo restoring the mesh; headless `modify.envelope`, `modify.envelope_move`, `modify.envelope_close`. *Not yet:* gradient and bitmap strokes (proposed in ADR 0080), envelope handles from the keyboard, an envelope on symbols, text or groups, drawing objects edited without opening them (#181), Combine across layers. **Rulers, grid and guides** (ADR 0076): View › Rulers (stage pixels, following zoom and pan, pointer marked); guides per scene saved in the document, dragged from a ruler, moved with the Selection tool, dragged back to delete, Show/Lock/Snap/Edit/Add/Clear (Edit Guides lists and adds them from the keyboard); a grid (spacing, | | Plug-ins | **WebAssembly plug-ins** (ADR 0017, `docs/plugins.md`): sandboxed modules run by `wasmi` with no imports but the AniCraft ABI (`anicraft.call`/`anicraft.response`: JSON requests that run registry commands, read a compact document view or the active layer's elements, and log); fuel (10⁹ instructions), memory (256 MiB), wall-clock (5 s), request, size and log limits, a fresh instance per run; file, plug-in, undo and clipboard commands refused. `plugin.install/list/run/remove/reload`; a run is atomic and one undo step named after the plug-in. App: **Commands** menu (Plug-ins, Install, Manage, Reload), palette entries, a dialog generated from the manifest's parameters with a live preview; plug-ins load from `/plugins` or `ANICRAFT_PLUGINS`; CLI `--plugins`. Samples in Rust (Star Field, Jitter Selection, guest SDK) in `examples/plugins`. Frame scripts: see Interactivity. Not yet: exporter and easing kinds, background runs with cancel, a binary document view. | | Interactivity | **Frame actions, frame scripts and Test Movie, first slice** (ADR 0024): a typed timeline action IR (`anicraft-actions`: stop, play, go to a frame or label in a scene, next/previous frame and scene, trace, set x/y/alpha/visible/rotation/scale, instance-name target paths) on keyframes and on button and movie clip instances (click, press, release, over, out); a pure, deterministic, budgeted player in `anicraft-doc` (`step(doc, &state, &events)`; movie clip playheads, button Up/Over/Down states with Hit-frame hit tests, script-set properties) drawn by `evaluate_player`, while `evaluate` and exports stay script-free. **Actions panel** (F9: structured lists, targets/labels/scenes picked from the document; movie clip timelines too), instance name and events in Properties, an "a" on keyframes with actions. **Frame scripts** on the plug-in host (`kind: "frame-script"`, entry points, `player`/`action` ops, 20 M instructions per frame shared, no document access). **Test Movie** (Control › Test Movie, Ctrl+Enter): the player at the document frame rate in its own window with the pointer, restart/pause/step and an Output panel. **A window of its own on the desktop** (ADR 0062): sized to the stage at 100 % (smaller to fit the screen), titled with the document, back where it was last (not on Wayland, where the desktop places windows), with the keyboard when it opens; Esc or Ctrl+W (⌘W) closes it, Ctrl+Enter restarts it in place, and the editor's Ctrl/Alt shortcuts work from it; floating inside the editor in the web build, where the system can't open windows (it says so), or by choice in Preferences › Test Movie. Not yet: full screen, zoom in the movie window, remembering its size. Headless: `actions.set/clear/list`, `instance.set_name`, `control.test_movie` (timed pointer events, returns output and state). **HTML canvas export** (ADR 0028, `file.export_html`, File › Export › Export HTML Canvas…): one self-contained page (data, player and drawing code inline; images and sounds embedded) that plays in any browser with canvas 2D; every used timeline baked frame by frame (tweens of every kind exact, identical paths, paints and frames stored once), movie clips, buttons with Hit areas and every action run by `player.js`, a port of the Rust player checked against it step by step in Boa (state, output and display list); masks and fading/blending groups on offscreen layers; **filters and Subtract/Invert in the page** (ADR 0072: `filters.js`, a port of the renderer's filters run over the group's pixels on a layer that reaches past the canvas by the filters' reach, Subtract and Invert composited per pixel, results kept while the group is unchanged; equal to the oracle's pixels within 9.3e-4 in Boa; 3.4 ms a frame for the demo's filters at 1080p while they change); Web Audio for Event/Start/Stop/Stream sounds; bitmap tints, 9-slice scaling and plug-in frame scripts reported. Not yet: 9-slice in the page, keeping a moving filtered group's pixels, filters off the main thread. **Kept frame scripts** (ADR 0013 tier 1): scripts written in another language (an Animate document's ActionScript) kept verbatim on keyframes with their language, symbol linkage classes and the document class; the Actions panel's **Script** view (monospace editor with line numbers, language, live and undoable), the same "a" marker, Class rows in Properties; `script.set/clear/list/set_class`; **ActionScript timeline subset runs** (ADR 0013 tier 2): a hand-written, bounded lexer and parser (`anicraft_actions::as3`) lower stop/play/go to/next and previous frame and scene on instance-name paths, mouse listeners (click, down, up, roll over and out; named or inline functions, `currentTarget`), `trace` and property settings to the action IR, compiled once per script; anything else is reported with line and column and the script doesn't run (never half-run), `navigateToURL` and the like are ignored and noted; the player keeps listeners per instance, Test Movie's Output says which scripts run and which don't and why, the Script view lists problems in place, the XFL report and `script.list/check` say what runs, and the HTML page runs the same steps (`player.js` checked against the Rust player). **ActionScript small logic** (ADR 0052): scripts compile to a small typed script IR evaluated by the player with fuel (100,000 per script or listener call, 1,000,000 per step; an endless loop or a run-time error stops its script with an Output line and the movie plays on): typed variables (Number, int, uint, Boolean, String, untyped) kept per timeline instance across its frame scripts, expressions as ECMA-262 has them, `if`/`else`, `for`/`while`/`do`, functions with parameters, results and recursion, called from any frame of the same timeline (a timeline-level link step; names that aren't there keep the script from running, said in place), property reads of instances and timelines (`x`, `y`, `alpha`, `visible`, `rotation`, `scaleX/Y`, `currentFrame`, `totalFrames`, `currentLabel`, `mouseX/Y`, `name`), `removeEventListener`, `Event.ENTER_FRAME`, `KeyboardEvent.KEY_DOWN/KEY_UP` on the stage with `e.keyCode`, `e.target`/`e.currentTarget`, seeded `Math.random()`; keyboard in Test Movie and the HTML page, `control.test_movie` key events and `seed`; `player.js` mirrors the evaluator, checked step by step in Boa. Not yet: ActionScript `switch`, `for in`, arrays and objects, string methods, closures, event bubbling, mouse listeners on the stage, ActionScript 1.0/2.0, scripts on instances, filters and keyboard focus in the HTML page, sound actions, keyboard events, variables, persistent script state, masks in hit tests, a separate OS window. **Buttons, complete** (ADR 0057): a button open in place names its frames Up, Over, Down and Hit on the timeline and shows its Hit area translucent over the other states; Test Movie has **Show hit areas**; sounds on its frames play as its state changes. | | Headless | CLI: info, render, render-seq, **gif**, **apng**, **webp**, commands, exec, run, serve (JSON-lines). **MCP server** (`anicraft-cli mcp`, `docs/mcp.md`): stdio JSON-RPC, protocol 2025-06-18 (and 2025-03-26, 2024-11-05); five tools over the command registry (list, run, run a script, describe the document, render a frame as a PNG picture); confirmation tiers and undo apply as in the app. | @@ -40,7 +40,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | **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); ~~larger self-authored corpus with golden render tests~~ ✅ (ADR 0035: twelve packages covering every mapped feature, exact report expectations, hostile variants, CPU-oracle goldens); ~~`.fla` variants of the corpus and a hardened zip reader~~ ✅ (ADR 0054: nine zip layouts imported identically to the folder, ZIP64, CP437 names, a 9,664-archive hostile fuzz; a 54.6 MB `.fla` imports in 0.31 s); not yet: sound and video items, self-extracting and top-folder `.fla` archives; ~~SVG import (Import to Stage)~~ ✅, ~~SVG frame export~~ ✅; ~~Lottie export~~ ✅ (frame-accurate; easing curves instead of per-frame keys later); ~~sprite sheet + JSON~~ ✅; ~~MP4/WebM via ffmpeg pipe~~ ✅; ~~animated PNG and WebP~~ ✅ (ADR 0063; lossless WebP; lossy WebP not yet). | | **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, outlines stored with the text; per-character styles later); ~~text on a path~~ ✅ first slice (ADR 0070: a copy of a shape's outline in the block, glyphs set by arc length and stored as outlines, offset, flip and alignment, Attach to Path by picking a shape, SVG `textPath`; editing the path in place and several lines on a path later); ~~dynamic and input text fields~~ ✅ first slice (ADR 0066: Text type in Properties, instance names, `field.text`/`appendText`/`length` in scripts, typing with caret, selection, max chars and passwords in Test Movie, native inputs in the HTML export, XFL fields kept; `htmlText`, change events, embedded fonts in HTML and other `TextField` API later); ~~bitmap import and bitmap fills~~ ✅; ~~audio layers, waveform display, stream sync~~ ✅ first slice (ADR 0020: WAV, Ogg Vorbis, MP3; `cpal` output); ~~effect envelopes, layer volume and mute, sounds inside symbols~~ ✅ (ADR 0039); ~~button sounds and hit-area editing~~ ✅ (ADR 0057: state sounds in Test Movie and HTML, state names on the timeline, the Hit area over the other states, Show hit areas in Test Movie, XFL sounds in the package); ~~filters (blur, drop shadow, glow, colour matrix)~~ ✅, ~~bevel, gradient glow and gradient bevel~~ ✅ (ADR 0025; SVG export and XFL import; filter presets, reordering, on/off and tweened filter values later) and ~~blend modes~~ ✅ on Movie Clips. | | **M6** | Interactivity & extensibility | **Plug-ins: the Craft-family WebAssembly system** (same host model as PhotoCraft: `wasmi` sandbox, `plugin.*` commands; AniCraft ABI for vector/timeline operations and exporters): first slice ✅ (command plug-ins over the registry, ADR 0017; exporter and easing kinds later); ~~frame scripts on the same sandbox~~ ✅ and ~~button states in test-movie preview~~ ✅ first slice (ADR 0024: action IR, pure player, Actions panel, Test Movie); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028: one self-contained page, baked frames, a JS port of the player tested against it; ~~filters, Subtract and Invert in the page~~ ✅, ADR 0072); command macros. **ActionScript compatibility, low priority** (ADR 0013), last in M6 and free to slip past M8: ~~tier 1 keeps scripts~~ ✅ (XFL frame scripts and class names stored verbatim, the Actions panel's Script view, `script.*` commands); ~~tier 2 runs the ActionScript 3 timeline subset (stop, play, go to frame or label, named instances, button events) in Test Movie and HTML canvas export through the same action IR as WebAssembly frame scripts~~ ✅; ~~tier 2.5 small logic (typed variables, expressions, `if` and loops, property reads, functions across frames, enter-frame and keyboard listeners, seeded random, ADR 0052)~~ ✅. The full language, the `flash.*` API and SWF bytecode are not planned. | -| **M7** | Advanced animation | ~~Bone/IK tool~~ ✅ first slice (ADR 0043: symbol-instance armatures on an armature layer, Bone tool, joint-angle poses tweened with easing, CCD inverse kinematics with joint limits and pins, posing with the Selection tool, Bone properties, every export; not yet: spring, joint translation, runtime armatures, XFL armature import, editing member instances' properties in place); ~~shape armatures~~ ✅ first slice (ADR 0071: bones inside one shape, automatic binding, linear blend skinning, Bind tool; not yet: instances and shapes in one armature, reshaping a bound shape, painted weights); ~~camera layer with depth~~ ✅ first slice (ADR 0027: one camera layer per scene, pan/zoom/rotate/tint, classic and motion tweens, pan-only layer depth, Camera tool, Preview Through Camera, every export); ~~layer depth in perspective, keyed over time, Layer Depth panel, attaching layers, camera colour effects, editing while previewing~~ ✅ second slice (ADR 0082; not yet: tools other than Selection while previewing, depth inside symbols, XFL camera import); ~~variable-width strokes~~ ✅ first slice (ADR 0018: width profiles, Width tool, exports, tweens); ~~Brush tool~~ ✅ first slice (ADR 0033: filled sweeps, tips, pressure, Paint Normal/Fills/Behind; not yet: Paint Selection/Inside); ~~brush library, pressure curves and the Paint Brush~~ ✅ first slice (ADR 0068: parameter presets, user brushes and brush sets, curve editor, velocity, stroke mode; not yet: tilt, textured brushes); ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034: five erase modes, Faucet, Erase Everything; picks solid, gradient, bitmap and line styles; not yet: erasing inside symbols, gradients and width profiles in the merge) and brush library; asset warp; graph-based easing presets library. | +| **M7** | Advanced animation | ~~Bone/IK tool~~ ✅ first slice (ADR 0043: symbol-instance armatures on an armature layer, Bone tool, joint-angle poses tweened with easing, CCD inverse kinematics with joint limits and pins, posing with the Selection tool, Bone properties, every export; not yet: outline-following ARAP meshes, symbols, pins bound to bones, a GPU textured path, bent bitmaps in HTML/Lottie); not yet: spring, joint translation, runtime armatures, XFL armature import, editing member instances' properties in place); ~~shape armatures~~ ✅ first slice (ADR 0071: bones inside one shape, automatic binding, linear blend skinning, Bind tool; not yet: instances and shapes in one armature, reshaping a bound shape, painted weights); ~~asset warp~~ ✅ first slice (ADR 0079: warp meshes on shapes and bitmaps, pins, rigid MLS, pin poses tweened, Asset Warp tool, ~~camera layer with depth~~ ✅ first slice (ADR 0027: one camera layer per scene, pan/zoom/rotate/tint, classic and motion tweens, pan-only layer depth, Camera tool, Preview Through Camera, every export); ~~layer depth in perspective, keyed over time, Layer Depth panel, attaching layers, camera colour effects, editing while previewing~~ ✅ second slice (ADR 0082; not yet: tools other than Selection while previewing, depth inside symbols, XFL camera import); ~~variable-width strokes~~ ✅ first slice (ADR 0018: width profiles, Width tool, exports, tweens); ~~Brush tool~~ ✅ first slice (ADR 0033: filled sweeps, tips, pressure, Paint Normal/Fills/Behind; not yet: Paint Selection/Inside); ~~brush library, pressure curves and the Paint Brush~~ ✅ first slice (ADR 0068: parameter presets, user brushes and brush sets, curve editor, velocity, stroke mode; not yet: tilt, textured brushes); ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034: five erase modes, Faucet, Erase Everything; picks solid, gradient, bitmap and line styles; not yet: erasing inside symbols, gradients and width profiles in the merge) and brush library; graph-based easing presets library. | | **M8** | Release quality | ~~Installers and signing for Windows/macOS/Linux~~ ✅ first slice (ADR 0026: family `packaging/` layout, MSI, DMG, AppImage/deb/rpm/Flatpak/tar.gz, `.anicraft` registered everywhere, signing wired to the release environment; ~~opening documents from Finder~~ ✅ (ADR 0062, to be checked on a Mac); next: AppImage desktop integration, portable mode, store submissions); ~~web build (wasm) of the editor~~ ✅ first slice (ADR 0036: browser file picker and downloads, autosave in browser storage, CPU stage, CI wasm build and tests in Node, the release zip made by `packaging/web/package.sh` and checked in CI (#210); next: releases carrying it and a hosted copy, once the team decides where, Web Audio, WebGPU stage, verified in browsers); ~~localisation~~ ✅ first slice (ADR 0040: `tr!` everywhere in the shell, craft-i18n catalogs, Preferences language, pseudo-locale; next: AniCraft's catalog in craft-i18n, engine messages, right to left once egui can lay it out); accessibility: first pass ✅ (ADR 0022: screen-reader names for every control, Ctrl+F6 panel focus, high-contrast theme, 200 % scale), second pass ✅ (ADR 0064: stage elements and timeline frames for screen readers, keyboard selection on the stage, keyboard menu bar, following the system's contrast setting), ~~a light theme~~ ✅ (ADR 0077: Light palette, Follow system for light or dark, #227), next: live screen-reader passes on each platform, a light high-contrast palette; ~~crash-recovery autosave~~ ✅ (ADR 0015); ~~Find and Replace and the Movie Explorer~~ ✅ first slice (ADR 0058: `find.search`/`find.replace`/`find.goto` over text, fonts, colours, symbols, sounds and bitmaps, scene or document, linear-time patterns, Replace All as one undo step asking above 100 places, going there opens symbols in place; `explorer.tree` paged, Show filters and search, the Movie Explorer tab beside the Library, lists drawing only the rows in view; not yet: action parameters and ActionScript strings apart from code, font size and style, colour tolerance, renaming in the Movie Explorer); ~~files from the desktop, recent files and a start screen~~ ✅ first slice (ADR 0059: drops route by type and target in one undo step, Open Recent with pins and missing files, start screen with presets and thumbnails); ~~templates, SVG into the Library, drops on the timeline~~ ✅ first slice (ADR 0065: six built-in templates built in code, Save as Template with category and picture, SVG as a graphic symbol, sounds onto a frame's keyframe and media into a keyframe made there; next: exact desktop drop positions once eframe moves to winit 0.31, user template descriptions and renaming); ~~Publish Settings and Publish~~ ✅ first slice (ADR 0060: the publish profile in the document, every format with its export options and an output relative to the document's folder with `{name}`, Shift+F12 publishing in the background with progress, Cancel and one report, overwriting asked once per session, presets in Preferences, the browser's downloads as one ZIP; not yet: Animate's PublishSettings.xml from XFL, more placeholders, outputs outside the document's folder, progress inside HTML, Lottie and audio); ~~documentation book~~ ✅ first slice (ADR 0069: the user guide in `docs/guide/`, generated command and shortcut references, Help › User Guide offline; next: translated guides, search, PDF, context help); ~~dockable panels and workspaces~~ ✅ first slice (ADR 0075, #249: every panel docks on any side of the stage, stacks as tabs, resizes, folds, floats in a window of its own with ADR 0062's fallback, closes and reopens where it was from the Window menu; Essentials, Animator, Designer and your own workspaces with Reset, kept in the preferences; new Colour and Output panels; Ctrl+F6 follows the layout; not yet: moving the tools, dragging a floating window back into a dock, several tabs in one floating window, deleting and renaming workspaces, docks collapsed to icons). | ## Releases @@ -61,7 +61,7 @@ titled with its milestone. | M4 | Text from Animate files | XFL import, text engine (M5 first slice) | | M5 | Audio layers: import, waveform, playback sync | timeline, layers | | M6 | ~~WebAssembly plug-ins (U2)~~ ✅ first slice (ADR 0017); ~~frame scripts and Test Movie on the plug-in host~~ ✅ first slice (ADR 0024); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028); ~~ActionScript tier 1: keep scripts~~ ✅ (ADR 0013); ~~ActionScript tier 2: run the timeline subset~~ ✅ (ADR 0013); ~~ActionScript tier 2.5: small logic~~ ✅ (ADR 0052); next: command macros, or growing the ActionScript subset (`switch`, arrays, event bubbling) | command registry, plug-in host, action IR and player | -| M7 | ~~Variable-width strokes~~ ✅ (ADR 0018), ~~camera layer with depth~~ ✅ first slice (ADR 0027), ~~camera depth, attaching and colour~~ ✅ (ADR 0082), ~~Bone tool and IK~~ ✅ first slice (ADR 0043), ~~shape armatures and the Bind tool~~ ✅ first slice (ADR 0071), ~~Brush tool~~ ✅ first slice (ADR 0033), ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034); ~~brush library and pressure curves~~ ✅ first slice (ADR 0068); next: Paint Selection/Inside, tilt | strokes, Pen and Pencil, width profiles, timeline evaluation | +| M7 | ~~Variable-width strokes~~ ✅ (ADR 0018), ~~camera layer with depth~~ ✅ first slice (ADR 0027), ~~camera depth, attaching and colour~~ ✅ (ADR 0082), ~~Bone tool and IK~~ ✅ first slice (ADR 0043), ~~shape armatures and the Bind tool~~ ✅ first slice (ADR 0071), ~~Asset Warp~~ ✅ first slice (ADR 0079), ~~Brush tool~~ ✅ first slice (ADR 0033), ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034); ~~brush library and pressure curves~~ ✅ first slice (ADR 0068); next: Paint Selection/Inside, tilt | strokes, Pen and Pencil, width profiles, timeline evaluation | | M8 | ~~Crash-recovery autosave~~ ✅, ~~accessibility first pass~~ ✅ (ADR 0022), ~~installers and signing~~ ✅ first slice (ADR 0026), ~~web build~~ ✅ first slice (ADR 0036), ~~localisation~~ ✅ first slice (ADR 0040), ~~Find and Replace and the Movie Explorer~~ ✅ first slice (ADR 0058), ~~drops, recent files and the start screen~~ ✅ first slice (ADR 0059); ~~templates and drops on the timeline~~ ✅ first slice (ADR 0065); ~~Publish Settings and Publish~~ ✅ first slice (ADR 0060); ~~Test Movie in its own window and macOS document opening~~ ✅ first slice (ADR 0062); ~~accessibility second pass~~ ✅ (ADR 0064); ~~a light theme~~ ✅ (ADR 0077); ~~CI on macOS and Windows~~ ✅ (ADR 0067); ~~dockable panels and workspaces~~ ✅ first slice (ADR 0075); next: live screen-reader passes | `.anicraft` format, session, AccessKit in eframe | Tasks that wait on an open track: XFL motion tweens (on M2's motion tweens); frame scripts and diff --git a/src/a11y.rs b/src/a11y.rs index 08976db8..f2ca5f92 100644 --- a/src/a11y.rs +++ b/src/a11y.rs @@ -411,10 +411,10 @@ mod tests { fn every_interactive_node_has_a_name_and_a_role() { let mut found = Vec::new(); found.extend(check("default", |_, _| {})); - for tool in [Tool::Bone, Tool::Bind, Tool::Rect, Tool::Star, Tool::Text, Tool::Pencil, Tool::Brush, Tool::PaintBrush, Tool::Eraser, Tool::PaintBucket, Tool::InkBottle, Tool::Eyedropper, Tool::Pen] { + for tool in [Tool::Bone, Tool::Bind, Tool::Warp, Tool::Rect, Tool::Star, Tool::Text, Tool::Pencil, Tool::Brush, Tool::PaintBrush, Tool::Eraser, Tool::PaintBucket, Tool::InkBottle, Tool::Eyedropper, Tool::Pen] { found.extend(check(&format!("{tool:?} tool"), |a, _| a.tool = tool)); } - for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "shapebones", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple", "library", "librarymenu", "edittransform", "onionsymbol", "layerprops", "frameview", "layercolour", "timelinepolish", "convert", "mixed", "bitmap", "nineslice", "nineslicedit", "find", "explorer", "publish", "publishreport", "publishanim", "start", "drop", "droplibrary", "testmovie", "testmovieinside", "templates", "savetemplate", "droptimeline", "textfields", "testtext", "softmask", "pathtext", "gradient", "gradientbucket", "swatches", "swatchpanel", "brushlibrary", "brushcurve", "paintbrush"] { + for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "shapebones", "warp", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple", "library", "librarymenu", "edittransform", "onionsymbol", "layerprops", "frameview", "layercolour", "timelinepolish", "convert", "mixed", "bitmap", "nineslice", "nineslicedit", "find", "explorer", "publish", "publishreport", "publishanim", "start", "drop", "droplibrary", "testmovie", "testmovieinside", "templates", "savetemplate", "droptimeline", "textfields", "testtext", "softmask", "pathtext", "gradient", "gradientbucket", "swatches", "swatchpanel", "brushlibrary", "brushcurve", "paintbrush"] { found.extend(check(panel, |a, _| a.open_panel(Some(panel)))); } // Every panel in front where it docks, and floating (ADR 0075); the other workspaces. diff --git a/src/app.rs b/src/app.rs index c41d4877..aa9c074b 100644 --- a/src/app.rs +++ b/src/app.rs @@ -15,6 +15,8 @@ pub enum Tool { Select, Subselect, Transform, + /// Asset Warp (ADR 0079): pins on shapes and bitmaps that bend them. + Warp, GradientTransform, Width, Bone, @@ -69,13 +71,14 @@ impl GapSize { } impl Tool { - pub const ALL: [Tool; 23] = [Tool::Select, Tool::Subselect, Tool::Transform, Tool::GradientTransform, Tool::Width, Tool::Bone, Tool::Bind, Tool::Pen, Tool::Text, Tool::Pencil, Tool::Brush, Tool::PaintBrush, Tool::Eraser, Tool::Rect, Tool::Oval, Tool::Star, Tool::Line, Tool::PaintBucket, Tool::InkBottle, Tool::Eyedropper, Tool::Camera, Tool::Hand, Tool::Zoom]; + pub const ALL: [Tool; 24] = [Tool::Select, Tool::Subselect, Tool::Transform, Tool::Warp, Tool::GradientTransform, Tool::Width, Tool::Bone, Tool::Bind, Tool::Pen, Tool::Text, Tool::Pencil, Tool::Brush, Tool::PaintBrush, Tool::Eraser, Tool::Rect, Tool::Oval, Tool::Star, Tool::Line, Tool::PaintBucket, Tool::InkBottle, Tool::Eyedropper, Tool::Camera, Tool::Hand, Tool::Zoom]; pub fn label(self) -> &'static str { match self { Tool::Select => tr_noop!("Selection"), Tool::Subselect => tr_noop!("Subselection"), Tool::Transform => tr_noop!("Free Transform"), + Tool::Warp => tr_noop!("Asset Warp"), Tool::GradientTransform => tr_noop!("Gradient Transform"), Tool::Width => tr_noop!("Width"), Tool::Bone => tr_noop!("Bone"), @@ -104,6 +107,7 @@ impl Tool { Tool::Select => Some("V"), Tool::Subselect => Some("A"), Tool::Transform => Some("Q"), + Tool::Warp => Some("Shift+Q"), Tool::GradientTransform => Some("F"), Tool::Width => Some("U"), Tool::Bone => Some("M"), @@ -140,11 +144,12 @@ impl Tool { Tool::Width => tr_noop!("Hover a stroke to see its width points. Drag a point's handle to widen or narrow the stroke there (Alt: one side only), drag its dot to slide it along, or drag anywhere on the stroke to add a point. Click a point and press Delete to remove it."), Tool::Bone => tr_noop!("Drag from one symbol instance to another to join them with a bone (they move to an armature layer), or drag inside a shape to draw a bone in it (the shape bends with its bones); start on a bone's end to continue the chain. Click a bone to select it. Pose the armature by dragging bones or instances with the Selection tool."), Tool::Bind => tr_noop!("Shows the points of shapes with bones: a square follows one bone, a triangle several. Click a bone to see the points it moves (filled). Click a point, or drag a box around points, to make them follow only that bone; Shift shares the bone with the ones they follow, Ctrl takes them from it."), + Tool::Warp => tr_noop!("Click a shape or a bitmap to pin it (the first pin covers it with a warp mesh). Drag a pin to bend the artwork around the other pins; with one pin it moves. Click a pin and press Delete to remove it. A pin moved at another frame keys it, and pins tween."), Tool::GradientTransform => tr_noop!("Click a shape with a gradient or bitmap fill to show its handles. Drag the centre to move the fill, the square to change its width, the circle to change its size, the knob to rotate it (Shift: 15° steps) and, on a radial gradient, the triangle to move its focal point. A bitmap fill also has a square for its height and diamonds to skew it. Each drag is one undo step."), Tool::Transform => tr_noop!("Drag a corner or edge to scale (Shift keeps proportions, Alt scales from the centre), just outside a corner to rotate (Shift snaps 15°), inside to move."), Tool::Rect => tr_noop!("Drag to draw a rectangle. Shift draws a square."), Tool::Oval => tr_noop!("Drag to draw an oval. Shift draws a circle."), - Tool::Star => tr_noop!("Drag from the centre to draw a star."), + Tool::Star => tr_noop!("Drag from the centre to draw a star or a polygon (Shape in the options)."), Tool::Line => tr_noop!("Drag to draw a line. Shift snaps to 45°."), Tool::PaintBucket => tr_noop!("Click inside an outline to fill it (on the layer's lines), or on a fill to recolour it. The gap size closes small openings."), Tool::InkBottle => tr_noop!("Click a shape to give it the current stroke colour and width."), @@ -229,6 +234,9 @@ pub enum Drag { /// Gradient Transform tool (ADR 0074): dragging `grip` of shape `id`'s fill, whose frame was /// `frame` when the drag began at stage point `press`. Gradient { id: anicraft_engine::doc::ElementId, grip: crate::gradient_tool::Grip, frame: anicraft_engine::geom::Affine, press: egui::Pos2 }, + /// Envelope (ADR 0080): dragging boundary handle `index` of the mesh `mesh` (as it was when + /// the drag began at stage point `press`). + Envelope { index: usize, mesh: anicraft_engine::geom::envelope::Mesh, press: anicraft_engine::geom::Vec2 }, /// Free transform: `applied` is the transform already sent to the engine this gesture. Transform { kind: XfKind, start: egui::Pos2, bounds: [f32; 4], applied: anicraft_engine::geom::Affine }, /// Dragging shape hint `index` on the side the frame shows (ADR 0023). @@ -253,6 +261,8 @@ pub enum Drag { BonePose { bone: anicraft_engine::doc::BoneId, local: egui::Pos2 }, /// Moving a whole armature by its root, from stage point `last` last frame. ArmatureMove { layer: anicraft_engine::doc::LayerId, last: egui::Pos2 }, + /// Asset Warp (ADR 0079): pin `pin` of `element` follows the pointer. + WarpPin { element: anicraft_engine::doc::ElementId, pin: anicraft_engine::doc::warp::PinId }, /// Moving one of the open symbol's 9-slice guides (ADR 0055). SliceGuide { guide: crate::scale_grid::Guide }, /// Selection tool: moving the scene's guide `index` (ADR 0076); `off`: the pointer is over a @@ -300,6 +310,28 @@ pub const SHOT_FRAMES: u32 = 120; /// The item picked in the Library panel (view state). pub use anicraft_engine::doc::LibraryItem; +/// The PolyStar tool's settings (ADR 0080): a polygon or a star, how many sides or points (3 to +/// 32), and how deep a star's points are (0 to 1). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct PolyStarOptions { + pub star: bool, + pub sides: u32, + pub point_size: f32, +} + +impl Default for PolyStarOptions { + fn default() -> Self { + PolyStarOptions { star: true, sides: 5, point_size: 0.5 } + } +} + +impl PolyStarOptions { + /// `draw.star`'s shape params. + pub fn params(&self) -> serde_json::Value { + serde_json::json!({"shape": if self.star { "star" } else { "polygon" }, "sides": self.sides.clamp(3, 32), "point_size": self.point_size.clamp(0.0, 1.0)}) + } +} + pub struct App { #[cfg(not(target_arch = "wasm32"))] pub(crate) updates: crate::updates::Updates, @@ -359,7 +391,10 @@ pub struct App { pub path_pick: Option, /// Font families on this computer, listed once on first need. pub font_families: Option>, - pub star_points: u32, + /// The PolyStar tool's settings (ADR 0080), as Animate's Tool Settings. + pub polystar: PolyStarOptions, + /// An envelope is open (ADR 0080): it closes when it no longer shows. + pub envelope_open: bool, pub rect_radius: f32, /// Pen path being drawn (view state until it is committed as one command). pub pen: Option, @@ -411,6 +446,8 @@ pub struct App { pub open_fill_swatch: bool, /// The bone picked on the stage (ADR 0043; view state). pub bone_sel: Option, + /// The warp pin picked with the Warp tool, and the artwork it is on (ADR 0079; view state). + pub warp_pin: Option<(anicraft_engine::doc::ElementId, anicraft_engine::doc::warp::PinId)>, /// Subselection: the selected motion path anchors, whose handles show (ADR 0030, 0038). pub motion_anchors: Vec, /// The motion path as it was when the drag on it began. @@ -622,7 +659,8 @@ impl App { text_edit: None, path_pick: None, font_families: None, - star_points: 5, + polystar: PolyStarOptions::default(), + envelope_open: false, rect_radius: 0.0, pen: None, pencil: Vec::new(), @@ -650,6 +688,7 @@ impl App { width_sel: None, open_fill_swatch: false, bone_sel: None, + warp_pin: None, motion_anchors: Vec::new(), motion_drag: None, frame_sel: None, @@ -1221,6 +1260,49 @@ impl App { } self.run("element.select", json!({"ids": ids})); } + Some("warp") => { + // Asset Warp (ADR 0079): a checkered bitmap and a striped banner, each pinned at + // three points and bent at frame 1, bent the other way at frame 24 (a classic + // tween between), with the tool in hand and the bitmap's right pin picked. + self.run("layer.new", json!({"name": "Warp"})); + let dir = std::env::temp_dir().join("anicraft-shot-warp"); + let _ = std::fs::create_dir_all(&dir); + let (w, h) = (240u32, 150u32); + let mut rgba = Vec::with_capacity((w * h * 4) as usize); + for y in 0..h { + for x in 0..w { + let on = ((x / 30) + (y / 30)) % 2 == 0; + let t = x as f32 / w as f32; + let c = if on { [(60.0 + 180.0 * t) as u8, 90, (230.0 - 150.0 * t) as u8, 255] } else { [250, 244, 230, 255] }; + rgba.extend_from_slice(&c); + } + } + let path = dir.join("checker.png"); + let bitmap = anicraft_engine::render::encode_png(w, h, &rgba).ok().filter(|png| std::fs::write(&path, png).is_ok()).and_then(|_| self.run("file.import_to_library", json!({"path": path.display().to_string(), "name": "checker.png"}))).and_then(|v| v["bitmap"].as_u64()); + let id = |v: Option, k: &str| v.and_then(|v| v[k].as_u64()).unwrap_or(0); + let img = bitmap.map_or(0, |b| id(self.run("library.place", json!({"bitmap": b, "x": 380, "y": 330})), "element")); + let banner = id(self.run("draw.rect", json!({"x": 700, "y": 270, "w": 320, "h": 120, "fill": "#e8833a", "stroke": "#4a2c14", "stroke_width": 3, "object": true})), "element"); + self.run("timeline.insert_frame", json!({"frame": 23})); + self.run("timeline.goto", json!({"frame": 0})); + let mut pins = Vec::new(); + for (el, x0, x1, y) in [(img, 270.0, 490.0, 330.0), (banner, 712.0, 1008.0, 330.0)] { + let mid = (x0 + x1) * 0.5; + let p = [x0, mid, x1].map(|x| id(self.run("warp.pin_add", json!({"element": el, "x": x, "y": y})), "pin")); + pins.push((el, p, x1, y)); + } + self.run("timeline.goto", json!({"frame": 23})); + self.run("timeline.insert_keyframe", json!({})); + self.run("timeline.goto", json!({"frame": 0})); + self.run("timeline.create_tween", json!({})); + for &(el, p, x1, y) in &pins { + self.run("warp.pin_move", json!({"element": el, "pin": p[1], "dx": 0, "dy": -30, "frame": 0})); + self.run("warp.pin_move", json!({"element": el, "pin": p[2], "x": x1 - 20.0, "y": y + 80.0, "frame": 0})); + self.run("warp.pin_move", json!({"element": el, "pin": p[2], "x": x1 - 10.0, "y": y - 70.0, "frame": 23})); + } + self.run("timeline.goto", json!({"frame": 0})); + self.warp_pin = pins.first().map(|&(el, p, _, _)| (anicraft_engine::doc::ElementId(el), anicraft_engine::doc::warp::PinId(p[2]))); + self.tool = Tool::Warp; + } Some(which @ ("onion" | "onionmenu")) => { // Onion skin ±5 on a frame with frames before and after it, the markers on the // ruler; with its menu open, in outlines (ADR 0047). @@ -1776,6 +1858,70 @@ impl App { self.drag = Drag::Brush; } } + Some(which @ ("polystar" | "paintinside" | "drawingedit" | "shapeenvelope")) => { + // Drawing parity (ADR 0080) on a new layer: polygons and stars of several sides + // and point sizes; brush strokes clipped by Paint Inside and Paint Selection; a + // drawing object open in place with a line merged across it; an envelope bending + // a drawing object. + self.run("layer.new", json!({"name": "Parity"})); + self.run("draw.object_drawing", json!({"on": which != "paintinside"})); + let ink = json!({"stroke": "#1b2a4a", "stroke_width": 3}); + let with = |mut p: Value| { + for (k, v) in ink.as_object().into_iter().flatten() { + p[k] = v.clone(); + } + p + }; + match which { + "polystar" => { + for (k, (shape, sides, size, fill)) in [("polygon", 3, 0.5, "#e8553b"), ("polygon", 6, 0.5, "#f2c14e"), ("star", 5, 0.5, "#3d8bfd"), ("star", 8, 0.2, "#7cc576"), ("star", 12, 0.8, "#d6336c")].into_iter().enumerate() { + self.run("draw.star", with(json!({"cx": 170 + k as i32 * 190, "cy": 300, "outer": 80, "shape": shape, "sides": sides, "point_size": size, "fill": fill}))); + } + self.run("edit.deselect", json!({})); + self.tool = Tool::Star; + self.polystar = PolyStarOptions { star: true, sides: 8, point_size: 0.2 }; + } + "paintinside" => { + self.run("draw.rect", with(json!({"x": 120, "y": 160, "w": 360, "h": 300, "fill": "#f2c14e"}))); + self.run("draw.ellipse", with(json!({"x": 600, "y": 160, "w": 360, "h": 300, "fill": "#3d8bfd"}))); + self.run("edit.deselect", json!({})); + let wave = |y: f32| -> Vec<[f32; 2]> { (0..=80).map(|i| [60.0 + i as f32 * 12.0, y + (i as f32 * 0.25).sin() * 30.0]).collect() }; + // Started in the yellow rectangle: it paints only there. + self.run("draw.brush", json!({"points": wave(250.0).into_iter().skip(10).collect::>(), "size": 36, "mode": "inside", "color": "#e8553b"})); + // The blue oval selected: Paint Selection keeps to it. + if let Some(oval) = self.s.visible_elements().iter().find(|e| matches!(&e.kind, anicraft_engine::doc::ElementKind::Shape(sh) if sh.fill == Some(anicraft_engine::doc::Paint::Solid(anicraft_engine::doc::Rgba::hex(0x3d8bfd))))).map(|e| e.id.0) { + self.run("element.select", json!({"ids": [oval]})); + self.run("draw.brush", json!({"points": wave(380.0), "size": 30, "mode": "selection", "color": "#7cc576"})); + } + self.run("edit.deselect", json!({})); + self.tool = Tool::Brush; + self.brush.mode = anicraft_engine::cmds_brush::PaintMode::Inside; + } + "drawingedit" => { + self.run("draw.rect", with(json!({"x": 140, "y": 180, "w": 300, "h": 220, "radius": 24, "fill": "#e8553b"}))); + let v = self.run("draw.ellipse", with(json!({"x": 520, "y": 170, "w": 320, "h": 240, "fill": "#f2c14e"}))); + if let Some(id) = v.and_then(|v| v["element"].as_u64()) { + self.run("symbol.edit", json!({"id": id})); + // Inside, in the object's own space: a line across merges with it alone. + self.run("draw.line", json!({"x0": -200, "y0": -40, "x1": 200, "y1": 60, "stroke": "#1b2a4a", "stroke_width": 3, "object": false})); + self.run("edit.deselect", json!({})); + } + self.tool = Tool::Select; + } + _ => { + self.run("draw.star", with(json!({"cx": 300, "cy": 320, "outer": 120, "shape": "star", "sides": 5, "point_size": 0.5, "fill": "#3d8bfd"}))); + self.run("draw.rect", with(json!({"x": 560, "y": 200, "w": 360, "h": 220, "fill": "#e8553b"}))); + crate::shape_envelope::open(self); + if let Some((_, _, mesh)) = self.s.envelope() { + let mut m = crate::shape_envelope::moved(&mesh, 1, anicraft_engine::geom::Vec2::new(0.0, -80.0)); + m = crate::shape_envelope::moved(&m, 13, anicraft_engine::geom::Vec2::new(30.0, 60.0)); + m = crate::shape_envelope::moved(&m, 3, anicraft_engine::geom::Vec2::new(40.0, -20.0)); + let points: Vec<[f32; 2]> = m.iter().map(|p| [p.x, p.y]).collect(); + self.run("modify.envelope_move", json!({"points": points})); + } + } + } + } Some(which @ ("eraser" | "erasing")) => { // Erased artwork on a new layer (ADR 0034): a band through an outlined raw // rectangle (Erase Normal), the outline of a raw oval erased but not its fill @@ -2438,6 +2584,11 @@ impl App { } return; } + if id == "modify.envelope" { + // The envelope's handles, with the Free Transform tool (ADR 0080). + crate::shape_envelope::open(self); + return; + } if id == "modify.convert_to_symbol" { // Name, type and Library folder (ADR 0053). crate::convert_symbol::open(self); @@ -2723,6 +2874,7 @@ impl App { pathtools::consume_keys(self, ctx); crate::widthtool::consume_keys(self, ctx); crate::bone_tool::consume_keys(self, ctx); + crate::warp_tool::consume_keys(self, ctx); } crate::library::consume_keys(self, ctx); let mut fire: Vec<&'static str> = Vec::new(); @@ -3153,6 +3305,7 @@ impl App { crate::motion_path::upkeep(self); crate::widthtool::upkeep(self); crate::bone_tool::upkeep(self); + crate::warp_tool::upkeep(self); // An open button shows its hit area over its other states, in the theme's colour (ADR 0057). self.s.hit_area = Some(theme::hit_area()); self.tick_playback(&ctx); diff --git a/src/brushtool.rs b/src/brushtool.rs index 4df0536c..6fe6a80a 100644 --- a/src/brushtool.rs +++ b/src/brushtool.rs @@ -263,10 +263,16 @@ pub fn commit(app: &mut App, xf: Xf) { } return; } - if let Some(v) = app.draw("draw.brush", params) + // Paint Selection keeps the selection it paints in, for the next stroke (ADR 0080). + let v = if o.mode == PaintMode::Selection { app.run("draw.brush", params) } else { app.draw("draw.brush", params) }; + if let Some(v) = v && v["elements"].as_array().is_some_and(Vec::is_empty) { - app.status_ok(tr!("Nothing to paint behind there: Paint Behind only paints empty areas.")); + match o.mode { + PaintMode::Selection => app.status_ok(tr!("Nothing painted: Paint Selection paints only inside the selected fills. Select them with the Selection tool first.")), + PaintMode::Inside => app.status_ok(tr!("Nothing painted: Paint Inside paints only inside the fill where the stroke starts.")), + _ => app.status_ok(tr!("Nothing to paint behind there: Paint Behind only paints empty areas.")), + } } } diff --git a/src/i18n/tests.rs b/src/i18n/tests.rs index 5b08021d..afdd6b6f 100644 --- a/src/i18n/tests.rs +++ b/src/i18n/tests.rs @@ -596,7 +596,7 @@ fn every_control_can_be_used_in_the_pseudo_locale() { a.run("element.set_color_effect", serde_json::json!({"style": style})); })); } - for panel in ["sound", "camera", "shapebones", "motion", "motionpins", "actions", "script", "prefs", "envelope", "onionmenu", "editmultiple", "edittransform", "onionsymbol", "find", "explorer", "publish", "publishreport", "publishanim", "start", "testmovie", "testmovieinside", "templates", "savetemplate", "brushlibrary", "brushcurve"] { + for panel in ["sound", "camera", "shapebones", "warp", "motion", "motionpins", "actions", "script", "prefs", "envelope", "onionmenu", "editmultiple", "edittransform", "onionsymbol", "find", "explorer", "publish", "publishreport", "publishanim", "start", "testmovie", "testmovieinside", "templates", "savetemplate", "brushlibrary", "brushcurve"] { found.extend(click_everything(panel, |a, _| a.open_panel(Some(panel)))); } // Test Movie in a window of its own (ADR 0062; egui stands in for the window system here). @@ -758,7 +758,7 @@ fn screen_reader_names_are_translated_too() { // the source guideline can't see: ones passed through variables or built at run time). use crate::app::Tool; let mut found = untranslated_names("default", |_, _| {}); - for tool in [Tool::Rect, Tool::Star, Tool::Text, Tool::Pencil, Tool::Brush, Tool::Eraser, Tool::PaintBucket, Tool::Eyedropper, Tool::Pen, Tool::Camera, Tool::Bone, Tool::Bind] { + for tool in [Tool::Rect, Tool::Star, Tool::Text, Tool::Pencil, Tool::Brush, Tool::Eraser, Tool::PaintBucket, Tool::Eyedropper, Tool::Pen, Tool::Camera, Tool::Bone, Tool::Bind, Tool::Warp] { found.extend(untranslated_names(&format!("{tool:?} tool"), |a, _| a.tool = tool)); } // Selections and states that change what Properties, the timeline and the dialogs show. diff --git a/src/icons.rs b/src/icons.rs index de99dd2d..db29ae7e 100644 --- a/src/icons.rs +++ b/src/icons.rs @@ -70,6 +70,7 @@ pub enum Icon { Magnet, Bone, Bind, + Warp, EditMultiple, Layer, InsertFrame, @@ -84,7 +85,8 @@ pub enum Icon { impl Icon { #[cfg(test)] - pub const ALL: [Icon; 66] = [ + pub const ALL: [Icon; 67] = [ + Icon::Warp, Icon::Plus, Icon::Trash, Icon::Copy, @@ -233,6 +235,8 @@ impl Icon { Icon::Bone => ("anicraft-bone", false), // A bone whose end is tied to two points (AniCraft original, on Lucide's grid): Bind. Icon::Bind => ("anicraft-bind", false), + // A mesh bent around a pin (AniCraft original, on Lucide's grid): Asset Warp. + Icon::Warp => ("anicraft-warp", false), // Frames stacked one behind the other, all edited at once (AniCraft original, on // Lucide's grid): Edit Multiple Frames. Icon::EditMultiple => ("anicraft-edit-multiple", false), @@ -315,6 +319,7 @@ static FILES: &[(&str, &str)] = &[ ("anicraft-camera", include_str!("../assets/icons/anicraft-camera.svg")), ("anicraft-bone", include_str!("../assets/icons/anicraft-bone.svg")), ("anicraft-bind", include_str!("../assets/icons/anicraft-bind.svg")), + ("anicraft-warp", include_str!("../assets/icons/anicraft-warp.svg")), ("anicraft-edit-multiple", include_str!("../assets/icons/anicraft-edit-multiple.svg")), ("folder", include_str!("../assets/icons/folder.svg")), ("folder-open", include_str!("../assets/icons/folder-open.svg")), diff --git a/src/keymap.rs b/src/keymap.rs index cc1b76c0..d5d2c48a 100644 --- a/src/keymap.rs +++ b/src/keymap.rs @@ -66,6 +66,7 @@ pub fn tool_id(t: Tool) -> &'static str { Tool::Camera => "tool.camera", Tool::Bone => "tool.bone", Tool::Bind => "tool.bind", + Tool::Warp => "tool.warp", Tool::Hand => "tool.hand", Tool::Zoom => "tool.zoom", } diff --git a/src/main.rs b/src/main.rs index 624ab693..3d341783 100644 --- a/src/main.rs +++ b/src/main.rs @@ -35,6 +35,7 @@ mod find_panel; mod publish_panel; mod erasertool; mod bind_tool; +mod warp_tool; mod bone_tool; mod camera_tool; mod convert_symbol; @@ -65,6 +66,7 @@ mod prefs; mod recent; mod rulers; mod scale_grid; +mod shape_envelope; mod sound; mod shape_hints; mod stage; @@ -253,7 +255,7 @@ fn parse_args(args: impl IntoIterator) -> Result { /// `--help` (the console's text, in English). #[cfg(not(target_arch = "wasm32"))] // i18n-exempt: the --help console text -const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png [--shot-width ]] [--renderer gl|wgpu|vulkan|dx12|metal] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--open palette|shortcuts|lastscene|start|drop|droplibrary|select|selectzoom|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|rulers|editguides|editgrid|symboledit|groups|combine|nineslice|nineslicedit|brush|brushing|brushlibrary|brushcurve|paintbrush|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|layerdepth|layerdepthview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testmovieinside|testscript|textfields|testtext|softmask|pathtext|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|library|librarymenu|colour|layerprops|frameview|layercolour|timelinepolish|dock|animator|designer|gradient|gradientbucket|swatches|swatchpanel]\n\ +const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png [--shot-width ]] [--renderer gl|wgpu|vulkan|dx12|metal] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--open palette|shortcuts|lastscene|start|drop|droplibrary|select|selectzoom|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|rulers|editguides|editgrid|symboledit|groups|combine|nineslice|nineslicedit|brush|brushing|polystar|paintinside|drawingedit|shapeenvelope|brushlibrary|brushcurve|paintbrush|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|layerdepth|layerdepthview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testmovieinside|testscript|textfields|testtext|softmask|pathtext|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|library|librarymenu|colour|layerprops|frameview|layercolour|timelinepolish|dock|animator|designer|gradient|gradientbucket|swatches|swatchpanel]\n\ --renderer the window's graphics (also ANICRAFT_RENDERER); default automatic, falling back to OpenGL\n\ --open shows a panel at start (handy with --screenshot for visual checks)\n\ --shot-width scales the screenshot down to this width (the user guide's pictures)\n\ diff --git a/src/menus.rs b/src/menus.rs index fd841937..2741e099 100644 --- a/src/menus.rs +++ b/src/menus.rs @@ -427,7 +427,7 @@ fn enabled(app: &App, id: &str) -> bool { "scene.delete" => app.s.doc.scenes.len() > 1, // Ctrl+E opens the selected instance, or goes back to the document (ADR 0045). "symbol.exit" => !app.s.editing.is_empty(), - "symbol.edit" => !app.s.editing.is_empty() || app.s.selected_elements().iter().any(|(_, e)| matches!(e.kind, anicraft_engine::doc::ElementKind::Symbol { .. } | anicraft_engine::doc::ElementKind::Group { .. })), + "symbol.edit" => !app.s.editing.is_empty() || app.s.selected_elements().iter().any(|(_, e)| anicraft_engine::editing::opens(e)), // Groups and Combine Objects (ADR 0073). "modify.group" => !app.s.selection.is_empty(), "modify.ungroup" => app.s.selected_elements().iter().any(|(_, e)| matches!(e.kind, anicraft_engine::doc::ElementKind::Group { .. })), diff --git a/src/panels.rs b/src/panels.rs index 79171d72..d3d1679d 100644 --- a/src/panels.rs +++ b/src/panels.rs @@ -34,6 +34,7 @@ fn tool_icon(tool: Tool) -> Icon { Tool::Camera => Icon::Camera, Tool::Bone => Icon::Bone, Tool::Bind => Icon::Bind, + Tool::Warp => Icon::Warp, Tool::Hand => Icon::Hand, Tool::Zoom => Icon::Zoom, } @@ -248,8 +249,18 @@ pub fn edit_bar(app: &mut App, ui: &mut egui::Ui) { .set_name(tr!("Scene")); // The symbols open for editing (ADR 0045), as in Animate's edit bar: a click on one // goes back to it; the last is the one being edited. - // A group (ADR 0073) shows as "Group", as Animate's edit bar does. - let open: Vec = app.s.editing.iter().map(|l| l.symbol().map_or_else(|| tr!("Group").to_string(), |id| app.s.doc.symbol(id).map_or_else(String::new, |s| s.name.clone()))).collect(); + // A group (ADR 0073) shows as "Group" and a drawing object (ADR 0080) as "Drawing + // Object", as Animate's edit bar does. + let open: Vec = app + .s + .editing + .iter() + .map(|l| match l.symbol() { + Some(id) => app.s.doc.symbol(id).map_or_else(String::new, |s| s.name.clone()), + None if l.open == anicraft_engine::editing::Opened::Drawing => tr!("Drawing Object").to_string(), + None => tr!("Group").to_string(), + }) + .collect(); let mut back: Option = None; for (i, name) in open.iter().enumerate() { ui.label(text(Type::Caption, "›")); @@ -586,6 +597,14 @@ pub(crate) fn properties(app: &mut App, ui: &mut egui::Ui) { section(ui, "prop_bone", Section::Rule, &title, None, |ui| bone_props(app, ui, id)); } } + // ---- Asset Warp (ADR 0079): the warped artwork picked with the tool, or selected ---- + let warp_target = app.warp_pin.map(|(e, _)| e).or_else(|| match sel.as_slice() { + [e] if matches!(&e.kind, ElementKind::Shape(sh) if sh.live_warp().is_some()) => Some(e.id), + _ => None, + }); + if app.tool == Tool::Warp || warp_target.is_some() { + section(ui, "prop_warp", Section::Rule, tr!("Asset Warp"), None, |ui| warp_props(app, ui, warp_target)); + } if let Some(e) = sel.first() { // One count per template: the layers' phrase is its own plural, with its preposition, so // its grammar travels with it, and the outer sentence places it. @@ -1641,6 +1660,54 @@ fn camera_props(app: &mut App, ui: &mut egui::Ui) { /// The selected bone: its joint angle at the playhead (editing it keys the pose), the joint's /// limits, the pin, and removal. +/// A warped shape or bitmap (ADR 0079): its mesh's resolution, its pins, and taking the warp +/// off. Without one, how to start. +fn warp_props(app: &mut App, ui: &mut egui::Ui, target: Option) { + let frame = app.s.frame; + let warp = target.and_then(|id| { + app.s.timeline().layers.iter().find_map(|l| { + let (_, els) = anicraft_engine::doc::evaluate_layer_elements(l, frame)?; + els.iter().find(|e| e.id == id).and_then(|e| match &e.kind { + ElementKind::Shape(sh) => sh.live_warp().cloned(), + _ => None, + }) + }) + }); + let (Some(id), Some(warp)) = (target, warp) else { + ui.label(text(Type::Caption, tr!("Click a shape or a bitmap with the Asset Warp tool to pin it; drag a pin to bend it around the others."))); + return; + }; + let mut res = warp.resolution; + let (cols, rows) = warp.grid().map_or((0, 0), |g| (g.nx, g.ny)); + row(ui, tr!("Mesh"), |ui| { + let r = ui + .add(egui::DragValue::new(&mut res).range(anicraft_engine::doc::warp::MIN_RESOLUTION..=anicraft_engine::doc::warp::MAX_RESOLUTION).speed(0.1)) + .named(tr!("Mesh resolution")) + .on_hover_text(tr!("Cells along the artwork's longer side: more bends more smoothly, fewer is faster")); + if r.changed() { + live(app, tr_noop!("Warp Mesh Resolution"), "warp.add", json!({"element": id.0, "resolution": res})); + } + ui.label(text(Type::Data, format!("{cols} × {rows}"))); + }); + let pins = warp.pins.len(); + row(ui, tr!("Pins"), |ui| { + ui.label(text(Type::Data, pins.to_string())); + }); + ui.horizontal_wrapped(|ui| { + if let Some((el, pin)) = app.warp_pin.filter(|(el, _)| *el == id) + && ui.button(tr!("Remove Pin")).named(tr!("Remove warp pin")).on_hover_text(tr!("Removes the picked pin from every keyframe (Delete)")).clicked() + { + app.run("warp.pin_remove", json!({"element": el.0, "pin": pin.0})); + app.warp_pin = None; + } + if ui.button(tr!("Remove Warp")).named(tr!("Remove warp")).on_hover_text(tr!("Takes the mesh and its pins off the artwork on every keyframe: it shows as drawn again")).clicked() { + app.run("warp.remove", json!({"element": id.0})); + app.warp_pin = None; + } + }); + ui.label(text(Type::Caption, tr!("Drag pins with the Asset Warp tool to bend the artwork; a pin moved at another frame keys it, and pins tween."))); +} + fn bone_props(app: &mut App, ui: &mut egui::Ui, id: anicraft_engine::doc::BoneId) { let tl = app.s.timeline(); let Some((layer, bone)) = tl.layers.iter().find_map(|l| l.armature.as_ref().and_then(|a| a.bone(id)).map(|b| (l.clone(), b.clone()))) else { return }; @@ -2117,9 +2184,7 @@ fn tool_props(app: &mut App, ui: &mut egui::Ui) { Tool::Rect => row(ui, tr!("Corners"), |ui| { ui.add(egui::DragValue::new(&mut app.rect_radius).suffix(" px").range(0.0..=500.0)).set_name(tr!("Corner radius")); }), - Tool::Star => row(ui, tr!("Points"), |ui| { - ui.add(egui::DragValue::new(&mut app.star_points).range(3..=32)).set_name(tr!("Star points")); - }), + Tool::Star => polystar_props(app, ui), Tool::PaintBucket => row_prose(ui, tr!("Gap size"), |ui| { egui::ComboBox::from_id_salt("bucket_gap").width(170.0).selected_text(crate::i18n::t(app.bucket_gap.label())).show_ui(ui, |ui| { for g in crate::app::GapSize::ALL { @@ -2140,6 +2205,27 @@ fn tool_props(app: &mut App, ui: &mut egui::Ui) { } } +/// PolyStar's Tool Settings (ADR 0080), inline as the other tools' options: the style, the number +/// of sides (or points) and, for a star, its point size. +fn polystar_props(app: &mut App, ui: &mut egui::Ui) { + let o = &mut app.polystar; + // "Shape", not Animate's "Style": the line style's row above is Style. + row_prose(ui, tr!("Shape"), |ui| { + ui.selectable_value(&mut o.star, false, tr!("Polygon")).on_hover_text(tr!("Draws a regular polygon.")); + ui.selectable_value(&mut o.star, true, tr!("Star")).on_hover_text(tr!("Draws a star.")); + }); + row(ui, if o.star { tr!("Points") } else { tr!("Sides") }, |ui| { + ui.add(egui::DragValue::new(&mut o.sides).range(3..=32)).set_name(if o.star { tr!("Number of points") } else { tr!("Number of sides") }); + }); + if o.star { + row(ui, tr!("Point size"), |ui| { + ui.add(egui::DragValue::new(&mut o.point_size).range(0.0..=1.0).speed(0.01).fixed_decimals(2)) + .on_hover_text(tr!("How deep the points are: near 0 they are thin spikes, at 1 the star is the polygon through its tips.")) + .set_name(tr!("Star point size")); + }); + } +} + /// The Eraser's options (ADR 0034): the Faucet, size, shape and erase mode, as in Animate. fn eraser_props(app: &mut App, ui: &mut egui::Ui) { use crate::brushtool::{SIZE_MAX, SIZE_MIN}; diff --git a/src/shape_envelope.rs b/src/shape_envelope.rs new file mode 100644 index 00000000..57fd1594 --- /dev/null +++ b/src/shape_envelope.rs @@ -0,0 +1,165 @@ +//! Envelope (ADR 0080): Modify › Transform › Envelope puts a mesh of handles around the selected +//! shapes and drawing objects, with the Free Transform tool, as in Animate. Squares are the +//! corners, circles the tangent handles of each side (a corner's tangents move with it). +//! Dragging one bends the shapes through `modify.envelope_move`: one undo step per drag. The +//! envelope ends when the selection changes or another tool is chosen; bent raw shapes then +//! merge with the drawing they lie on (`modify.envelope_close`). + +use crate::app::{App, Drag, Tool}; +use crate::pathtools::Xf; +use crate::theme::T; +use anicraft_engine::geom::envelope::{BOUNDARY, CORNERS, Mesh, coons_interior}; +use anicraft_engine::geom::{Rect, Vec2}; +use egui::{Color32, Pos2, Stroke, StrokeKind, vec2}; +use serde_json::json; + +/// Pick radius for handles, in screen points. +const PICK: f32 = 7.0; +/// Handle size, in screen points. +const HANDLE: f32 = 7.0; + +/// The open envelope's rest rectangle and mesh, while the Free Transform tool shows it. +pub fn shown(app: &App) -> Option<(Rect, Mesh)> { + (app.tool == Tool::Transform).then(|| app.s.envelope()).flatten().map(|(_, rest, mesh)| (rest, mesh)) +} + +/// Opens an envelope on the selection (Modify › Transform › Envelope) and takes the Free +/// Transform tool, which shows its handles. +pub fn open(app: &mut App) { + if app.run("modify.envelope", json!({})).is_some() { + app.tool = Tool::Transform; + app.envelope_open = true; + app.status_ok(tr!("Drag the handles to bend the shapes. Squares move a corner, circles bend a side.")); + } +} + +/// Ends an envelope that is no longer shown (another tool, another selection): bent raw shapes +/// merge where they lie. Runs every frame, before the stage handles input. +pub fn settle(app: &mut App) { + if app.envelope_open && app.drag == Drag::None && shown(app).is_none() { + app.envelope_open = false; + // Ended by a new selection: that stays. By another tool: what the merge selected. + let keep = (app.tool == Tool::Transform).then(|| app.s.selection.clone()); + app.run("modify.envelope_close", json!({})); + if let Some(keep) = keep { + app.s.selection = keep; + } + } +} + +/// The handle under screen point `p`. +fn hit(mesh: &Mesh, xf: Xf, p: Pos2) -> Option { + BOUNDARY + .iter() + .copied() + .filter_map(|i| mesh.get(i).map(|q| (i, xf.to_screen(*q).distance(p)))) + .filter(|(_, d)| *d <= PICK) + .min_by(|a, b| a.1.total_cmp(&b.1)) + .map(|(i, _)| i) +} + +/// Whether a drag from `press` grabs a handle (the cursor shows a grab there). +pub fn over_handle(app: &App, xf: Xf, p: Pos2) -> bool { + shown(app).is_some_and(|(_, mesh)| hit(&mesh, xf, p).is_some()) +} + +/// A drag on a handle starts one undo step. +pub fn drag_start(app: &mut App, xf: Xf, press: Pos2) -> Option { + let (_, mesh) = shown(app)?; + let index = hit(&mesh, xf, press)?; + app.s.begin_gesture(tr_noop!("Envelope")); + Some(Drag::Envelope { index, mesh, press: xf.to_stage(press) }) +} + +/// The tangent handles beside corner `i` (they move with it). +fn tangents(i: usize) -> [usize; 2] { + match i { + 0 => [1, 4], + 3 => [2, 7], + 15 => [11, 14], + 12 => [8, 13], + _ => [i, i], + } +} + +/// `start` with handle `index` moved by `d` (a corner takes its tangents along), the inside +/// following the sides. +pub fn moved(start: &Mesh, index: usize, d: Vec2) -> Mesh { + let mut m = *start; + let mut grip = vec![index]; + if CORNERS.contains(&index) { + grip.extend(tangents(index)); + } + grip.sort_unstable(); + grip.dedup(); + for i in grip { + if let (Some(slot), Some(s)) = (m.get_mut(i), start.get(i)) { + *slot = *s + d; + } + } + coons_interior(&mut m); + m +} + +pub fn drag_to(app: &mut App, drag: Drag, cur: Vec2) { + let Drag::Envelope { index, mesh, press } = drag else { return }; + let m = moved(&mesh, index, cur - press); + let points: Vec<[f32; 2]> = m.iter().map(|p| [p.x, p.y]).collect(); + app.run("modify.envelope_move", json!({"points": points, "tolerance": 0.05})); +} + +pub fn drag_end(app: &mut App) { + app.s.end_gesture(); +} + +/// The mesh's outline (its four sides as cubics), tangent lines and handles. +pub fn draw_overlay(app: &App, painter: &egui::Painter, xf: Xf, pointer: Option) { + let Some((_, mesh)) = shown(app) else { return }; + let at = |i: usize| xf.to_screen(mesh.get(i).copied().unwrap_or(Vec2::ZERO)); + let line = Stroke::new(1.5, T.selection); + let thin = Stroke::new(1.0, T.selection); + // The sides, clockwise: top, right, bottom, left. + for side in [[0, 1, 2, 3], [3, 7, 11, 15], [15, 14, 13, 12], [12, 8, 4, 0]] { + let [a, b, c, d] = side.map(at); + painter.add(egui::epaint::CubicBezierShape::from_points_stroke([a, b, c, d], false, Color32::TRANSPARENT, line)); + painter.line_segment([a, b], thin); + painter.line_segment([d, c], thin); + } + let hot = pointer.and_then(|p| hit(&mesh, xf, p)); + for i in BOUNDARY { + let p = at(i); + let fill = if hot == Some(i) { T.selection } else { Color32::WHITE }; + if CORNERS.contains(&i) { + let r = egui::Rect::from_center_size(p, vec2(HANDLE, HANDLE)); + painter.rect_filled(r, 0.0, fill); + painter.rect_stroke(r, 0.0, Stroke::new(1.0, T.selection), StrokeKind::Middle); + } else { + painter.circle(p, HANDLE * 0.45, fill, Stroke::new(1.0, T.selection)); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use anicraft_engine::geom::envelope::rest_mesh; + + /// A corner drags its two tangents along; a tangent moves alone; the inside follows. + #[test] + fn corners_take_their_tangents() { + let rest = rest_mesh(&Rect::new(0.0, 0.0, 90.0, 60.0)); + let d = Vec2::new(10.0, -5.0); + let m = moved(&rest, 0, d); + for i in [0usize, 1, 4] { + assert_eq!(m[i], rest[i] + d, "{i}"); + } + assert_eq!(m[2], rest[2]); + assert_eq!(m[3], rest[3]); + let t = moved(&rest, 2, d); + assert_eq!(t[2], rest[2] + d); + assert_eq!(t[1], rest[1]); + assert_ne!(t[6], rest[6], "the inner points follow the side"); + // No move: the rest mesh. + assert_eq!(moved(&rest, 7, Vec2::ZERO), rest); + } +} diff --git a/src/stage.rs b/src/stage.rs index 92fe605d..8936b32a 100644 --- a/src/stage.rs +++ b/src/stage.rs @@ -212,6 +212,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { let (canvas, bars) = crate::rulers::layout(app, ui.max_rect()); let now = ui.input(|i| i.time); crate::camera_tool::on_tool_change(app); + crate::shape_envelope::settle(app); crate::camera_tool::tick(app, ui.ctx(), now); app.stage_cache.canvas = canvas; let resp = ui.allocate_rect(canvas, Sense::click_and_drag()); @@ -359,7 +360,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { _ if let Some(i) = guide_hot => crate::rulers::cursor(app, i), _ if let Drag::SliceGuide { guide } = app.drag => guide.cursor(), _ if let Some(guide) = slice_hot => guide.cursor(), - _ if matches!(app.drag, Drag::Hint { .. } | Drag::CameraPan { .. } | Drag::BonePose { .. }) => CursorIcon::Grabbing, + _ if matches!(app.drag, Drag::Hint { .. } | Drag::CameraPan { .. } | Drag::BonePose { .. } | Drag::WarpPin { .. }) => CursorIcon::Grabbing, _ if matches!(app.drag, Drag::ArmatureMove { .. }) => CursorIcon::Move, Tool::Select if app.drag == Drag::None && pointer.is_some_and(|p| crate::bone_tool::hit(app, xf, p).is_some()) => CursorIcon::Grab, _ if paused => CursorIcon::NotAllowed, @@ -372,6 +373,8 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { _ if pen_hot.is_some() => CursorIcon::Copy, Tool::Width => crate::widthtool::cursor(app, pointer, xf), Tool::GradientTransform => crate::gradient_tool::cursor(app, pointer, xf), + Tool::Transform if matches!(app.drag, Drag::Envelope { .. }) => CursorIcon::Grabbing, + Tool::Transform if app.drag == Drag::None && pointer.is_some_and(|p| crate::shape_envelope::over_handle(app, xf, p)) => CursorIcon::Grab, Tool::Transform => { let zone = match app.drag { Drag::Transform { kind, .. } | Drag::MultiTransform { kind, .. } => Some(kind), @@ -387,7 +390,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { None => CursorIcon::Default, } } - Tool::Rect | Tool::Oval | Tool::Star | Tool::Line | Tool::Pen | Tool::Pencil | Tool::Brush | Tool::PaintBrush | Tool::Eraser | Tool::PaintBucket | Tool::InkBottle | Tool::Eyedropper | Tool::Bone | Tool::Bind => CursorIcon::Crosshair, + Tool::Rect | Tool::Oval | Tool::Star | Tool::Line | Tool::Pen | Tool::Pencil | Tool::Brush | Tool::PaintBrush | Tool::Eraser | Tool::PaintBucket | Tool::InkBottle | Tool::Eyedropper | Tool::Bone | Tool::Bind | Tool::Warp => CursorIcon::Crosshair, Tool::Text => CursorIcon::Text, Tool::Zoom => { if alt { @@ -436,6 +439,8 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { match tool { // Edit Multiple Frames (ADR 0047): artwork on every keyframe between the markers; // Free Transform's handles transform it all about one pivot (ADR 0051). + // An open envelope's handles (ADR 0080). + Tool::Transform if !multi && let Some(d) = crate::shape_envelope::drag_start(app, xf, press) => d, Tool::Transform if multi && let (Some(kind), Some(bounds)) = (sel_rect.and_then(|r| xf_zone(r, press)), sel_bounds) => { app.s.begin_gesture(tr_noop!("Free Transform")); Drag::MultiTransform { kind, start: sp, bounds, applied: Affine::IDENTITY } @@ -470,6 +475,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { Tool::Subselect => crate::pathtools::subselect_drag_start(app, press, shift, xf), Tool::Bone => crate::bone_tool::drag_start(app, xf, press), Tool::Bind => crate::bind_tool::drag_start(app, xf, press), + Tool::Warp => crate::warp_tool::drag_start(app, xf, press), Tool::Width => crate::widthtool::drag_start(app, press, xf), Tool::GradientTransform => crate::gradient_tool::drag_start(app, press, xf), Tool::Pencil => { @@ -622,6 +628,10 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { } } (Drag::PointMarquee { cur: m, .. } | Drag::BindMarquee { cur: m, .. }, Some(c)) => *m = c, + (Drag::WarpPin { element, pin }, Some(c)) => { + let (element, pin) = (*element, *pin); + crate::warp_tool::drag_to(app, element, pin, c); + } (d @ Drag::Width { .. }, Some(c)) => { let d = *d; crate::widthtool::drag_to(app, d, to_v(c), alt, zoom); @@ -630,6 +640,10 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { let d = *d; crate::gradient_tool::drag_to(app, d, to_v(c), shift); } + (d @ Drag::Envelope { .. }, Some(c)) => { + let d = *d; + crate::shape_envelope::drag_to(app, d, to_v(c)); + } (Drag::Pencil, Some(c)) => crate::pathtools::pencil_sample(app, to_v(c), xf), (Drag::Brush, Some(c)) => crate::brushtool::sample(app, to_v(c), pressure, xf, now), (Drag::Eraser, Some(c)) => crate::brushtool::sample(app, to_v(c), None, xf, now), @@ -646,11 +660,12 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { app.s.end_gesture(); } Drag::Bend { .. } | Drag::RawPoint { .. } | Drag::RawHandle { .. } => end_raw_drag(app), - Drag::Transform { .. } | Drag::SliceGuide { .. } | Drag::Points { .. } | Drag::Hint { .. } | Drag::MotionMove { .. } | Drag::CameraPan { .. } | Drag::CameraRotate { .. } | Drag::BonePose { .. } | Drag::ArmatureMove { .. } => app.s.end_gesture(), + Drag::Transform { .. } | Drag::SliceGuide { .. } | Drag::Points { .. } | Drag::Hint { .. } | Drag::MotionMove { .. } | Drag::CameraPan { .. } | Drag::CameraRotate { .. } | Drag::BonePose { .. } | Drag::ArmatureMove { .. } | Drag::WarpPin { .. } => app.s.end_gesture(), Drag::Bone { from, head, cur } => crate::bone_tool::drag_end(app, xf, from, head, cur), Drag::Guide { index, .. } => crate::rulers::drag_end(app, index, geo, ui.input(|i| i.pointer.latest_pos())), Drag::Width { .. } => crate::widthtool::drag_end(app), Drag::Gradient { .. } => crate::gradient_tool::drag_end(app), + Drag::Envelope { .. } => crate::shape_envelope::drag_end(app), Drag::MotionPath { .. } => crate::motion_path::drag_end(app), Drag::PointMarquee { start, cur } => crate::pathtools::marquee_points(app, start, cur, shift), Drag::BindMarquee { start, cur } => crate::bind_tool::drag_end(app, start, cur, shift, command), @@ -733,6 +748,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { } Tool::Bone if !panning => crate::bone_tool::click(app, xf, p), Tool::Bind if !panning => crate::bind_tool::click(app, xf, p, shift, command), + Tool::Warp if !panning => crate::warp_tool::click(app, xf, p), Tool::Select | Tool::Transform if !panning && multi => crate::onion::click(app, sp, shift, zoom), // A click on a bone picks it (ADR 0043). Tool::Select if !panning && let Some((layer, bone, _)) = crate::bone_tool::hit(app, xf, p) => crate::bone_tool::select(app, layer, Some(bone)), @@ -778,8 +794,9 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { let slop = 3.0 / zoom.max(1e-3); if !open_text_at(app, sp, slop) { match app.s.hit_test(to_v(sp), slop) { - // A symbol instance (ADR 0045) or a group (ADR 0073) opens for editing in place. - Some((layer, id)) if app.s.elements_on(layer).iter().any(|e| e.id == id && matches!(e.kind, anicraft_engine::doc::ElementKind::Symbol { .. } | anicraft_engine::doc::ElementKind::Group { .. })) => { + // A symbol instance (ADR 0045), a group (ADR 0073) or a drawing object (ADR 0080) + // opens for editing in place. + Some((layer, id)) if app.s.elements_on(layer).iter().any(|e| e.id == id && anicraft_engine::editing::opens(e)) => { app.run("symbol.edit", json!({"id": id.0})); } // Raw artwork (ADR 0031): a stroke and the strokes joined to it, or a fill and @@ -1045,6 +1062,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { // Armatures' bones over their artwork (ADR 0043). crate::bone_tool::draw(app, &painter, xf); crate::bind_tool::draw(app, &painter, xf); + crate::warp_tool::draw(app, &painter, xf); let sel_stroke = Stroke::new(1.0, T.selection); let raw = raw_ids(app); if app.tool == Tool::Select && app.drag == Drag::None @@ -1062,6 +1080,8 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { } } let transforming = app.tool == Tool::Transform; + // An open envelope (ADR 0080) shows its mesh instead of boxes. + let enveloped = crate::shape_envelope::shown(app).is_some(); // Selected raw shapes (ADR 0031) show Animate's dot pattern over themselves, with no box. if app.tool == Tool::Select && !preview { let to_px = Affine::translate(origin.x, origin.y).mul(&Affine::scale(zoom, zoom)); @@ -1106,6 +1126,9 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { if app.tool == Tool::Select && raw.contains(&(layer, id)) { continue; // dots above } + if transforming && enveloped { + continue; + } if transforming { // Free transform shows one box for the whole selection (below); members get a hint. painter.rect_stroke(r, 0.0, Stroke::new(1.0, T.selection.gamma_multiply(0.45)), StrokeKind::Middle); @@ -1131,7 +1154,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { } // Free transform box: recomputed every frame so it follows the artwork while you drag. let xf_box = if multi { crate::onion::selection_bounds(app) } else { bounds_arr(app.s.selection_bounds()) }; - if transforming && let Some(b) = xf_box { + if transforming && !enveloped && let Some(b) = xf_box { let r = Rect::from_min_max(to_screen(Vec2::new(b[0], b[1])), to_screen(Vec2::new(b[2], b[3]))).expand(1.0); painter.rect_stroke(r, 0.0, Stroke::new(1.5, T.selection), StrokeKind::Middle); for (h, _, _) in handles(r) { @@ -1148,6 +1171,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { crate::pathtools::draw_overlay(app, &painter, xf, pointer.filter(|p| canvas.contains(*p))); crate::widthtool::draw_overlay(app, &painter, xf, pointer.filter(|p| canvas.contains(*p))); crate::gradient_tool::draw_overlay(app, &painter, xf, pointer.filter(|p| canvas.contains(*p) && !panning)); + crate::shape_envelope::draw_overlay(app, &painter, xf, pointer.filter(|p| canvas.contains(*p) && !panning)); crate::brushtool::draw_overlay(app, &painter, xf, pointer.filter(|p| canvas.contains(*p) && !panning && !paused)); crate::erasertool::draw_overlay(app, &painter, xf, pointer.filter(|p| canvas.contains(*p) && !panning && !paused)); // After this frame's edits, so a drag on the path shows where it is now. @@ -1715,6 +1739,7 @@ mod pattern_tests { group: None, image: None, smooth: true, + warp: None, } } @@ -1958,8 +1983,11 @@ fn create_shape(app: &mut App, start: Pos2, cur: Pos2) { app.draw("draw.ellipse", json!({"x": start.x, "y": start.y, "w": d.x, "h": d.y})); } Tool::Star => { - let r = d.length(); - app.draw("draw.star", json!({"cx": start.x, "cy": start.y, "outer": r, "inner": r * 0.45, "points": app.star_points})); + let mut p = app.polystar.params(); + p["cx"] = json!(start.x); + p["cy"] = json!(start.y); + p["outer"] = json!(d.length()); + app.draw("draw.star", p); } Tool::Line => { app.draw("draw.line", json!({"x0": start.x, "y0": start.y, "x1": cur.x, "y1": cur.y})); @@ -1990,15 +2018,9 @@ fn draw_preview(app: &App, painter: &egui::Painter, a: Pos2, b: Pos2, zoom: f32) painter.add(egui::Shape::convex_polygon(pts, fill, stroke)); } Tool::Star => { - let rr = (b - a).length(); - let n = app.star_points.clamp(3, 64) as usize; - let pts: Vec = (0..n * 2) - .map(|i| { - let r = if i % 2 == 0 { rr } else { rr * 0.45 }; - let t = -std::f32::consts::FRAC_PI_2 + i as f32 * std::f32::consts::PI / n as f32; - a + vec2(r * t.cos(), r * t.sin()) - }) - .collect(); + // The same corners the command draws (ADR 0080). + let o = app.polystar; + let pts: Vec = anicraft_engine::geom::polystar_corners(a.x, a.y, (b - a).length(), o.sides.clamp(3, 32), o.star, o.point_size).into_iter().map(|v| Pos2::new(v.x, v.y)).collect(); painter.add(egui::Shape::closed_line(pts, stroke)); } Tool::Line => { diff --git a/src/warp_tool.rs b/src/warp_tool.rs new file mode 100644 index 00000000..37269604 --- /dev/null +++ b/src/warp_tool.rs @@ -0,0 +1,189 @@ +//! The Asset Warp tool (ADR 0079): pins on shapes and bitmaps that bend them. +//! +//! With the tool in hand every warped shape or bitmap on the stage shows its mesh (faint, in +//! its layer's colour) and its pins. A click on artwork pins it there (the first pin covers it +//! with a warp mesh) and picks the pin; a click on a pin picks it; a click on empty stage drops +//! the pick. Dragging a pin bends the artwork around the other pins, live; dragging artwork +//! where there is no pin adds one there and drags it. Either drag is one undo step. Delete (or +//! Backspace) removes the picked pin, Esc drops the pick. Everything goes through the `warp.*` +//! commands. + +use crate::app::{App, Drag, Tool}; +use crate::pathtools::Xf; +use crate::theme::{T, to_color32}; +use anicraft_engine::doc::warp::PinId; +use anicraft_engine::doc::{ElementId, ElementKind, LayerId, LayerKind, evaluate_layer_elements}; +use anicraft_engine::geom::{Affine, Vec2}; +use egui::{Color32, Key, Modifiers, Pos2, Stroke}; +use serde_json::json; + +/// How close (screen points) a press must be to a pin to grab it, and the pin's radius. +const GRAB: f32 = 8.0; +const RADIUS: f32 = 4.5; + +/// One warped artwork as the stage shows it at the playhead. +struct Shown { + element: ElementId, + color: Color32, + locked: bool, + /// The mesh's edges, in stage space. + edges: Vec<(Vec2, Vec2)>, + /// Pins: id and where they show (stage). + pins: Vec<(PinId, Vec2)>, +} + +fn shown(app: &App) -> Vec { + let tl = app.s.timeline(); + let mut out = Vec::new(); + for (i, l) in tl.layers.iter().enumerate() { + if !l.visible || tl.hidden_by_folder(i) || !matches!(l.kind, LayerKind::Normal) { + continue; + } + let Some((_, els)) = evaluate_layer_elements(l, app.s.frame) else { continue }; + for e in els.iter() { + let ElementKind::Shape(sh) = &e.kind else { continue }; + let Some(w) = sh.live_warp() else { continue }; + let Some(mesh) = w.mesh() else { continue }; + let m: Affine = e.transform; + let at = |i: u32| mesh.shown.get(i as usize).map(|v| m.apply(*v)); + let mut edges = Vec::with_capacity(mesh.tris.len() * 2); + for t in &mesh.tris { + // Each triangle's first two edges draw the grid and its diagonals once. + if let (Some(a), Some(b), Some(c)) = (at(t[0]), at(t[1]), at(t[2])) { + edges.push((a, b)); + edges.push((b, c)); + } + } + let pins = w.pins.iter().map(|p| (p.id, m.apply(p.at))).collect(); + out.push(Shown { element: e.id, color: to_color32(l.color), locked: l.locked || tl.locked_by_folder(l.id), edges, pins }); + } + } + out +} + +/// The unlocked pin under screen point `p`, topmost first. +fn pin_at(app: &App, xf: Xf, p: Pos2) -> Option<(ElementId, PinId)> { + shown(app).into_iter().rev().filter(|s| !s.locked).find_map(|s| s.pins.iter().find(|(_, at)| xf.to_screen(*at).distance(p) <= GRAB).map(|(id, _)| (s.element, *id))) +} + +/// The topmost shape or bitmap under stage point `sp` on an unlocked normal layer. +fn artwork_at(app: &App, sp: Vec2) -> Option<(LayerId, ElementId)> { + let dl = app.s.display_list(); + let tl = app.s.timeline(); + for item in dl.items.iter().rev() { + if item.guide || item.masks.is_some() || item.fill.is_none() { + continue; + } + let Some(layer) = tl.layer(item.layer).filter(|l| l.kind == LayerKind::Normal && !l.locked && !tl.locked_by_folder(l.id)) else { continue }; + if item.clip.is_some_and(|c| !dl.clip_contains(c, sp)) || !item.path.contains(sp, &item.transform, item.fill_rule) { + continue; + } + let shape = evaluate_layer_elements(layer, app.s.frame).is_some_and(|(_, els)| els.iter().any(|e| e.id == item.element && matches!(e.kind, ElementKind::Shape(_)))); + if shape { + return Some((layer.id, item.element)); + } + // Something else (a symbol, text) is on top: nothing to warp here. + return None; + } + None +} + +/// Pins the artwork under stage point `sp`; picks the new pin. +fn add_pin(app: &mut App, layer: LayerId, el: ElementId, sp: Vec2) -> Option { + if app.s.layer != layer { + app.run("layer.select", json!({"layer": layer.0})); + } + let v = app.run("warp.pin_add", json!({"element": el.0, "x": sp.x, "y": sp.y}))?; + let pin = PinId(v["pin"].as_u64()?); + app.warp_pin = Some((el, pin)); + if v["created"].as_bool() == Some(true) { + app.status_ok(tr!("The artwork has a warp mesh. Add more pins, then drag one to bend it around the others.")); + } + Some(pin) +} + +/// A Warp tool click at screen point `p`. +pub fn click(app: &mut App, xf: Xf, p: Pos2) { + if let Some(hit) = pin_at(app, xf, p) { + app.warp_pin = Some(hit); + return; + } + let sp = xf.to_stage(p); + match artwork_at(app, sp) { + Some((layer, el)) => { + add_pin(app, layer, el, sp); + } + None => app.warp_pin = None, + } +} + +/// A Warp tool drag from screen point `press`: a pin (or a new one, on artwork) follows the +/// pointer, as one undo step. +pub fn drag_start(app: &mut App, xf: Xf, press: Pos2) -> Drag { + if let Some((element, pin)) = pin_at(app, xf, press) { + app.warp_pin = Some((element, pin)); + app.s.begin_gesture(tr_noop!("Move Warp Pin")); + return Drag::WarpPin { element, pin }; + } + let sp = xf.to_stage(press); + let Some((layer, el)) = artwork_at(app, sp) else { return Drag::None }; + app.s.begin_gesture(tr_noop!("Add Warp Pin")); + match add_pin(app, layer, el, sp) { + Some(pin) => Drag::WarpPin { element: el, pin }, + None => { + app.s.end_gesture(); + Drag::None + } + } +} + +/// Continues a pin drag to stage point `c`. +pub fn drag_to(app: &mut App, element: ElementId, pin: PinId, c: Pos2) { + app.run("warp.pin_move", json!({"element": element.0, "pin": pin.0, "x": c.x, "y": c.y})); +} + +/// Delete removes the picked pin; Esc drops the pick. +pub fn consume_keys(app: &mut App, ctx: &egui::Context) { + let Some((el, pin)) = app.warp_pin else { return }; + if app.tool != Tool::Warp { + return; + } + let take = |k: Key| ctx.input_mut(|i| i.consume_key(Modifiers::NONE, k)); + if take(Key::Delete) || take(Key::Backspace) { + if app.run("warp.pin_remove", json!({"element": el.0, "pin": pin.0})).is_some() { + app.status_ok(tr!("Pin removed. {undo} to undo.", undo = app.undo_key())); + } + app.warp_pin = None; + } else if take(Key::Escape) { + app.warp_pin = None; + } +} + +/// Drops a picked pin that no longer shows. +pub fn upkeep(app: &mut App) { + if let Some((el, pin)) = app.warp_pin + && !shown(app).iter().any(|s| s.element == el && s.pins.iter().any(|(id, _)| *id == pin)) + { + app.warp_pin = None; + } +} + +/// With the tool in hand: every warped artwork's mesh and pins. +pub fn draw(app: &App, painter: &egui::Painter, xf: Xf) { + if app.tool != Tool::Warp { + return; + } + for s in shown(app) { + let fade = |c: Color32| if s.locked { c.gamma_multiply(0.4) } else { c }; + let line = Stroke::new(1.0, fade(s.color.gamma_multiply(0.45))); + for (a, b) in &s.edges { + painter.line_segment([xf.to_screen(*a), xf.to_screen(*b)], line); + } + for (id, at) in &s.pins { + let c = xf.to_screen(*at); + let picked = app.warp_pin == Some((s.element, *id)); + let fill = fade(if picked { T.selection } else { Color32::WHITE }); + painter.circle(c, RADIUS, fill, Stroke::new(1.5, fade(if picked { Color32::WHITE } else { s.color }))); + } + } +}