From 58d56d18af6aeb593a033a9e7f9fe5e95168c240 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Thu, 12 Nov 2026 00:15:59 -0700 Subject: [PATCH 01/18] docs(adr): reserve ADR 0071 for shape armatures (M7) --- docs/adr/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/adr/README.md b/docs/adr/README.md index 8a35fed1..322068dc 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,3 +23,4 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | +| 0071 | m7/shape-armatures | Shape armatures (bones inside a shape) | From 97f7d5c50d5c408581c355d6ff0b6706a1b24034 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Thu, 12 Nov 2026 00:21:06 -0700 Subject: [PATCH 02/18] feat(doc): shape armatures: skins, automatic binding and linear blend skinning (M7) --- crates/doc/src/armature.rs | 45 ++++- crates/doc/src/armature_tests.rs | 4 +- crates/doc/src/lib.rs | 4 +- crates/doc/src/skin.rs | 320 +++++++++++++++++++++++++++++++ crates/doc/src/skin_tests.rs | 301 +++++++++++++++++++++++++++++ crates/engine/src/cmds_bone.rs | 2 +- 6 files changed, 663 insertions(+), 13 deletions(-) create mode 100644 crates/doc/src/skin.rs create mode 100644 crates/doc/src/skin_tests.rs diff --git a/crates/doc/src/armature.rs b/crates/doc/src/armature.rs index 61d9123d..2fe247b9 100644 --- a/crates/doc/src/armature.rs +++ b/crates/doc/src/armature.rs @@ -19,6 +19,7 @@ //! joint's limits. It works on joint angles directly, so limits are a clamp per step and the //! result is a pose by construction. +use crate::skin::{self, Skin}; use crate::{Element, ElementId, Keyframe, Layer}; use anicraft_geom::{Affine, Vec2}; use serde::{Deserialize, Serialize}; @@ -111,6 +112,11 @@ impl Bone { pub struct Armature { #[serde(default)] pub bones: Vec, + /// A shape armature (ADR 0071): the bones are inside this shape and bend its outline. Its + /// bones join joint nodes (ids that are no element) instead of instances; see + /// [`crate::skin`]. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub skin: Option, } impl Armature { @@ -118,6 +124,12 @@ impl Armature { self.bones.is_empty() } + /// The shape a shape armature's bones are inside (ADR 0071); `None` for an armature of + /// symbol instances. + pub fn skin_shape(&self) -> Option { + self.skin.as_ref().map(|s| s.shape) + } + pub fn bone(&self, id: BoneId) -> Option<&Bone> { self.bones.iter().find(|b| b.id == id) } @@ -152,8 +164,12 @@ impl Armature { out } - /// The instances no bone moves (one for an armature made with the Bone tool). + /// The instances no bone moves (one for an armature made with the Bone tool; a shape + /// armature's shape). pub fn roots(&self) -> Vec { + if let Some(s) = self.skin_shape() { + return vec![s]; + } let mut out = Vec::new(); for b in &self.bones { if self.bone_into(b.parent).is_none() && !out.contains(&b.parent) { @@ -210,8 +226,12 @@ impl Armature { kept.push(b); } // Order: a bone after the bone moving its parent. What never gets placed is a cycle. + // A shape armature's bones all hang from its shape. let children: HashSet = kept.iter().map(|b| b.child).collect(); - let mut placed: HashSet = kept.iter().map(|b| b.parent).filter(|p| !children.contains(p)).collect(); + let mut placed: HashSet = match self.skin_shape() { + Some(s) => HashSet::from([s]), + None => kept.iter().map(|b| b.parent).filter(|p| !children.contains(p)).collect(), + }; let mut ordered = Vec::with_capacity(kept.len()); let mut rest = kept; loop { @@ -227,7 +247,8 @@ impl Armature { } ordered.truncate(MAX_BONES); self.bones = ordered; - self.bones != before + let skin_changed = skin::sanitize(self); + self.bones != before || skin_changed } } @@ -296,19 +317,21 @@ impl Pose { } /// `R(angle)` about point `j`. -fn turn_about(j: Vec2, angle: f32) -> Affine { +pub(crate) fn turn_about(j: Vec2, angle: f32) -> Affine { Affine::translate(j.x, j.y).mul(&Affine::rotate(angle)).mul(&Affine::translate(-j.x, -j.y)) } /// Forward kinematics: the transform (in the layer's space) of every instance in `elements` /// once `pose` turns the armature's joints. A root keeps its own transform; a child is placed /// from its parent: `R_joint(angle) · parent · rest`. An instance whose parent isn't on the -/// keyframe keeps its own transform. +/// keyframe keeps its own transform. A shape armature's joint nodes (ADR 0071) are placed +/// the same way from the shape's transform. pub fn place(arm: &Armature, elements: &[Arc], pose: &Pose) -> HashMap { let mut world: HashMap = elements.iter().map(|e| (e.id, e.transform)).collect(); + let nodes = arm.skin.is_some(); for b in &arm.bones { let Some(wp) = world.get(&b.parent).copied() else { continue }; - if !world.contains_key(&b.child) { + if !nodes && !world.contains_key(&b.child) { continue; } let j = wp.apply(b.head); @@ -320,12 +343,15 @@ pub fn place(arm: &Armature, elements: &[Arc], pose: &Pose) -> HashMap< world } -/// Puts the instances of `elements` where `pose` has them (copy-on-write: only instances that -/// move are cloned). Returns whether any moved. +/// Puts the instances of `elements` where `pose` has them, and bends a shape armature's shape +/// (copy-on-write: only what changes is cloned). Returns whether anything changed. pub fn apply(arm: &Armature, elements: &mut [Arc], pose: &Pose) -> bool { if arm.is_empty() { return false; } + if arm.skin.is_some() { + return skin::apply(arm, elements, pose); + } let world = place(arm, elements, pose); let mut moved = false; for e in elements.iter_mut() { @@ -372,7 +398,8 @@ pub struct BoneAt { /// Every bone's joint and end with the instances in `elements` placed as they show (posed: /// what [`crate::evaluate_layer_elements`] gives on an armature layer). pub fn bones_at(arm: &Armature, elements: &[Arc], pose: &Pose) -> Vec { - let world: HashMap = elements.iter().map(|e| (e.id, e.transform)).collect(); + // A shape armature's joint nodes are no elements: forward kinematics places them. + let world: HashMap = if arm.skin.is_some() { place(arm, elements, pose) } else { elements.iter().map(|e| (e.id, e.transform)).collect() }; arm.bones .iter() .filter_map(|b| { diff --git a/crates/doc/src/armature_tests.rs b/crates/doc/src/armature_tests.rs index 2e4c6f4d..f2f5d993 100644 --- a/crates/doc/src/armature_tests.rs +++ b/crates/doc/src/armature_tests.rs @@ -26,7 +26,7 @@ fn bone(id: BoneId, parent: ElementId, child: ElementId) -> Bone { /// joint), the hand from 300; the hand's end at 400. The arm and hand reach 200 px from the /// shoulder joint at (200, 100). fn chain() -> (Armature, Vec>) { - let arm = Armature { bones: vec![bone(B1, ROOT, ARM), bone(B2, ARM, HAND)] }; + let arm = Armature { bones: vec![bone(B1, ROOT, ARM), bone(B2, ARM, HAND)], skin: None }; (arm, vec![instance(ROOT, 100.0, 100.0), instance(ARM, 200.0, 100.0), instance(HAND, 300.0, 100.0)]) } @@ -242,7 +242,7 @@ fn long_chains_and_collinear_targets_converge() { bones.push(Bone { id: BoneId(5000 + i as u64), ..bone(BoneId(0), p, c) }); els.push(instance(c, 100.0 * (i + 1) as f32, 0.0)); } - let arm = Armature { bones }; + let arm = Armature { bones, skin: None }; let last = BoneId(5000 + n as u64 - 1); let reach = 100.0 * n as f32; for k in 0..12 { diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 8e45e760..f4003bab 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -8,6 +8,7 @@ pub use anicraft_audio as audio; pub use anicraft_actions as actions; pub mod armature; +pub mod skin; mod bitmap; mod color_effect; pub mod camera; @@ -1431,7 +1432,8 @@ impl Document { let scan = |l: &Layer, max_id: &mut u64| { *max_id = (*max_id).max(l.id.0); for b in l.armature.iter().flat_map(|a| &a.bones) { - *max_id = (*max_id).max(b.id.0); + // A shape armature's joint nodes take ids from the same counter (ADR 0071). + *max_id = (*max_id).max(b.id.0).max(b.child.0).max(b.parent.0); } for k in &l.keyframes { for e in &k.elements { diff --git a/crates/doc/src/skin.rs b/crates/doc/src/skin.rs new file mode 100644 index 00000000..d0a46902 --- /dev/null +++ b/crates/doc/src/skin.rs @@ -0,0 +1,320 @@ +//! Shape armatures (ADR 0071): bones drawn inside one shape, whose outline bends with them. +//! +//! A shape armature is an [`Armature`] with a [`Skin`]. Its bones join *joint nodes* instead of +//! symbol instances: the root bones start on the shape itself (its element id) and every other +//! bone starts on the node of the bone it hangs from. A node is a frame that the bone into it +//! turns; at rest every node's frame is the shape's own local space, so a bone's head and tail +//! are points of the shape as it was drawn, and a node's transform under a pose is the bone's +//! **skinning matrix**. Forward and inverse kinematics are ADR 0043's ([`crate::armature::place`], +//! [`crate::armature::solve`]): nothing about posing is new. +//! +//! The skin keeps the outline as it was drawn (`rest`) and one [`Binding`] per anchor of it +//! (every `MoveTo`, `LineTo`, `QuadTo` and `CubicTo` end, in path order): the bones the anchor +//! follows and how much. Automatic binding ([`auto_binding`]) weighs each bone by the inverse +//! fourth power of the anchor's distance to the bone's segment, keeps the strongest +//! [`MAX_INFLUENCES`] and normalises them to sum to 1; the Bind tool (`bone.bind`) overrides +//! anchors by hand. The posed outline ([`deform`]) is linear blend skinning: each anchor moves +//! by the weighted sum of its bones' matrices, and each handle by the blend of the anchor it +//! belongs to, so curves stay smooth through a bend. Stroke width is drawn after the outline +//! (the shape's own transform is untouched), so strokes keep their width. +//! +//! Linear blend skinning is the standard method (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, which names it skeleton subspace deformation). + +use crate::armature::{Armature, BoneId, Pose}; +use crate::{Element, ElementId, ElementKind}; +use anicraft_geom::{Affine, Path, PathCmd, Vec2, segment_distance}; +use serde::{Deserialize, Serialize}; +use std::collections::HashMap; +use std::sync::Arc; + +/// Most bones one anchor follows. +pub const MAX_INFLUENCES: usize = 4; +/// Most anchors a shape with bones may have (a hand-drawn shape has tens to a few thousand). +pub const MAX_SKIN_POINTS: usize = 20_000; +/// Distances below this count as this (px), so an anchor on a bone has a finite weight. +const NEAR: f32 = 0.5; +/// A bone whose share is below this after normalising is dropped from the anchor. +const FAINT: f32 = 0.01; + +/// One bone's share of an anchor: `[bone, weight]` in files. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct Influence(pub BoneId, pub f32); + +/// The bones one anchor follows. Weights are positive and sum to 1; an anchor with none stays +/// where it was drawn. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct Binding { + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub bones: Vec, + /// Set with the Bind tool: automatic binding (after adding or removing a bone) leaves it. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub manual: bool, +} + +impl Binding { + /// The share bone `b` has of this anchor (0 when it doesn't follow it). + pub fn weight(&self, b: BoneId) -> f32 { + self.bones.iter().find(|i| i.0 == b).map_or(0.0, |i| i.1) + } + + /// Keeps positive, finite weights of bones in `keep` (one each, the strongest + /// [`MAX_INFLUENCES`]) and scales them to sum to 1. Returns whether anything changed. + pub fn normalize(&mut self, keep: impl Fn(BoneId) -> bool) -> bool { + let before = self.bones.clone(); + let mut seen = Vec::with_capacity(self.bones.len()); + self.bones.retain(|i| i.1.is_finite() && i.1 > 0.0 && keep(i.0) && !seen.contains(&i.0) && { + seen.push(i.0); + true + }); + self.bones.sort_by(|a, b| b.1.total_cmp(&a.1)); + self.bones.truncate(MAX_INFLUENCES); + let sum: f32 = self.bones.iter().map(|i| i.1).sum(); + if sum > 0.0 && sum.is_finite() { + for i in &mut self.bones { + i.1 /= sum; + } + } else { + self.bones.clear(); + } + self.bones != before + } +} + +/// How a shape is bound to its armature's bones. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Skin { + /// The shape the bones are inside (an element of the armature layer's keyframes). + pub shape: ElementId, + /// The outline as it was drawn, in the shape's local space: the pose of every bone at 0. + pub rest: Arc, + /// One per anchor of `rest`, in path order. + #[serde(default)] + pub points: Vec, +} + +impl Skin { + /// A skin for `shape` drawn as `rest`, its anchors not yet bound. + pub fn new(shape: ElementId, rest: Arc) -> Skin { + let points = vec![Binding::default(); anchors(&rest).len()]; + Skin { shape, rest, points } + } +} + +/// The anchors of `path` in order: every command's end point. +pub fn anchors(path: &Path) -> Vec { + path.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() +} + +/// Where every bone of a shape armature lies as drawn, in the shape's space: its joint and end. +pub fn rest_segments(arm: &Armature) -> Vec<(BoneId, Vec2, Vec2)> { + // Every node's rest frame is the shape's space (`rest` is the identity for shape bones), so + // composing the rests places each bone; a hand-edited file with other rests still works. + let mut node: HashMap = HashMap::new(); + let root = arm.skin.as_ref().map(|s| s.shape); + arm.bones + .iter() + .filter_map(|b| { + let wp = if Some(b.parent) == root { Affine::IDENTITY } else { *node.get(&b.parent)? }; + let wc = wp.mul(&b.rest); + node.insert(b.child, wc); + Some((b.id, wp.apply(b.head), wc.apply(b.tail))) + }) + .collect() +} + +/// Automatic binding of an anchor at `p` (the shape's space, as drawn): each bone weighs +/// `1 / max(d, 0.5)⁴` where `d` is the distance from `p` to the bone's segment; the strongest +/// [`MAX_INFLUENCES`] are kept, faint ones (under 1 %) dropped, and the rest sum to 1. An anchor +/// near one bone follows it alone; one near a joint shares it between the bones that meet +/// there, so the outline bends smoothly. Empty only without bones. +pub fn auto_binding(segments: &[(BoneId, Vec2, Vec2)], p: Vec2) -> Binding { + let mut bones: Vec = segments + .iter() + .map(|&(id, a, b)| { + let d = segment_distance(p, a, b).max(NEAR); + Influence(id, 1.0 / (d * d * d * d)) + }) + .filter(|i| i.1.is_finite() && i.1 > 0.0) + .collect(); + // Weighed relative to the nearest bone, so a far-away shape keeps finite numbers. + let top = bones.iter().map(|i| i.1).fold(0.0f32, f32::max); + if top > 0.0 { + for i in &mut bones { + i.1 /= top; + } + } + let mut out = Binding { bones, manual: false }; + out.normalize(|_| true); + let before = out.bones.len(); + out.bones.retain(|i| i.1 >= FAINT); + if out.bones.len() != before { + out.normalize(|_| true); + } + out +} + +/// Binds every anchor not bound by hand afresh (after the bones changed), and repairs the hand +/// bound ones: bones that went away leave them, and one left with none goes back to automatic +/// (an anchor unbound by hand on purpose stays unbound). Keeps one binding per anchor. +pub fn rebind(arm: &mut Armature) { + let segments = rest_segments(arm); + let ids: Vec = arm.bones.iter().map(|b| b.id).collect(); + let Some(skin) = arm.skin.as_mut() else { return }; + let pts = anchors(&skin.rest); + skin.points.resize(pts.len(), Binding::default()); + for (b, &p) in skin.points.iter_mut().zip(&pts) { + if b.manual { + let had = !b.bones.is_empty(); + b.normalize(|id| ids.contains(&id)); + if !had || !b.bones.is_empty() { + continue; + } + } + *b = auto_binding(&segments, p); + } +} + +/// Every bone's skinning matrix under `pose`: how the pose moves the shape's space near it (the +/// identity at rest, exactly). +pub fn matrices(arm: &Armature, pose: &Pose) -> HashMap { + let Some(skin) = &arm.skin else { return HashMap::new() }; + let mut node: HashMap = HashMap::new(); + node.insert(skin.shape, Affine::IDENTITY); + let mut out = HashMap::with_capacity(arm.bones.len()); + for b in &arm.bones { + let Some(wp) = node.get(&b.parent).copied() else { continue }; + let a = b.allow(pose.angle(b.id)); + let wc = if a == 0.0 { wp.mul(&b.rest) } else { crate::armature::turn_about(wp.apply(b.head), a).mul(&wp.mul(&b.rest)) }; + if wc.is_finite() { + node.insert(b.child, wc); + out.insert(b.id, wc); + } + } + out +} + +/// The blend of `binding`'s bone matrices; `None` when it doesn't move (no bones, or every one +/// of them at rest), so a point at rest is kept bit for bit. +fn blend(binding: &Binding, m: &HashMap) -> Option { + let mut moved = false; + let mut acc = [0.0f32; 6]; + let mut total = 0.0f32; + for &Influence(b, w) in &binding.bones { + let x = m.get(&b).copied().unwrap_or(Affine::IDENTITY); + moved |= x != Affine::IDENTITY; + for (a, v) in acc.iter_mut().zip(x.m) { + *a += w * v; + } + total += w; + } + if !moved || total <= 0.0 { + return None; + } + // Weights sum to 1; dividing keeps a hand-edited file's rounding from scaling the shape. + Some(Affine { m: acc.map(|v| v / total) }) +} + +fn mix(a: Option, b: Option) -> Option { + match (a, b) { + (None, None) => None, + (a, b) => { + let (a, b) = (a.unwrap_or(Affine::IDENTITY), b.unwrap_or(Affine::IDENTITY)); + let mut m = [0.0f32; 6]; + for (i, v) in m.iter_mut().enumerate() { + *v = 0.5 * (a.m.get(i).copied().unwrap_or(0.0) + b.m.get(i).copied().unwrap_or(0.0)); + } + Some(Affine { m }) + } + } +} + +/// The outline `pose` bends the skin's shape into (the shape's space): linear blend skinning of +/// every anchor, each cubic handle moving with the anchor it leaves or enters and a quadratic's +/// control with the mean of its two ends. At rest (or where no bound bone turned) points are +/// exactly as drawn. +pub fn deform(arm: &Armature, pose: &Pose) -> Option> { + let skin = arm.skin.as_ref()?; + let m = matrices(arm, pose); + if m.values().all(|x| *x == Affine::IDENTITY) { + return Some(skin.rest.clone()); + } + let none = Binding::default(); + let mut idx = 0usize; + let at = |i: usize| blend(skin.points.get(i).unwrap_or(&none), &m); + let on = |x: Option, p: Vec2| x.map_or(p, |x| x.apply(p)); + let mut prev: Option = None; + let mut cmds = Vec::with_capacity(skin.rest.cmds.len()); + for c in &skin.rest.cmds { + let next = match *c { + PathCmd::Close => { + cmds.push(PathCmd::Close); + continue; + } + _ => at(idx), + }; + idx += 1; + cmds.push(match *c { + PathCmd::MoveTo(p) => PathCmd::MoveTo(on(next, p)), + PathCmd::LineTo(p) => PathCmd::LineTo(on(next, p)), + PathCmd::QuadTo(q, p) => PathCmd::QuadTo(on(mix(prev, next), q), on(next, p)), + PathCmd::CubicTo(c1, c2, p) => PathCmd::CubicTo(on(prev, c1), on(next, c2), on(next, p)), + PathCmd::Close => PathCmd::Close, + }); + prev = next; + } + Some(Arc::new(Path { cmds })) +} + +/// Puts the skin's shape in `elements` in the outline `pose` bends it into (copy-on-write). +/// Returns whether it changed. +pub fn apply(arm: &Armature, elements: &mut [Arc], pose: &Pose) -> bool { + let Some(skin) = &arm.skin else { return false }; + let Some(e) = elements.iter_mut().find(|e| e.id == skin.shape) else { return false }; + let ElementKind::Shape(s) = &e.kind else { return false }; + let Some(path) = deform(arm, pose) else { return false }; + if Arc::ptr_eq(&s.path, &path) || *s.path == *path { + return false; + } + if let ElementKind::Shape(s) = &mut Arc::make_mut(e).kind { + s.path = path; + } + true +} + +/// Repairs a loaded skin against its armature: the rest outline within [`MAX_SKIN_POINTS`] +/// anchors (else the skin goes), one binding per anchor, weights of bones that exist, positive +/// and summing to 1; unbound automatic anchors are bound. Returns whether anything changed. +pub fn sanitize(arm: &mut Armature) -> bool { + let Some(skin) = &arm.skin else { return false }; + let n = anchors(&skin.rest).len(); + if n > MAX_SKIN_POINTS || arm.bones.iter().any(|b| b.child == skin.shape) { + arm.skin = None; + return true; + } + let before = arm.skin.clone(); + let ids: Vec = arm.bones.iter().map(|b| b.id).collect(); + let segments = rest_segments(arm); + let Some(skin) = arm.skin.as_mut() else { return false }; + let pts = anchors(&skin.rest); + skin.points.resize(n, Binding::default()); + for (b, &p) in skin.points.iter_mut().zip(&pts) { + b.normalize(|id| ids.contains(&id)); + if b.bones.is_empty() && !b.manual { + *b = auto_binding(&segments, p); + } + } + arm.skin != before +} + +#[cfg(test)] +#[path = "skin_tests.rs"] +mod tests; diff --git a/crates/doc/src/skin_tests.rs b/crates/doc/src/skin_tests.rs new file mode 100644 index 00000000..d5d3a025 --- /dev/null +++ b/crates/doc/src/skin_tests.rs @@ -0,0 +1,301 @@ +//! Shape armatures: binding, skinning, posing and files (ADR 0071). + +use super::*; +use crate::armature::{Bone, place, pose_at, solve}; +use crate::{ColorEffect, Document, Easing, Keyframe, Layer, LayerId, LayerKind, Paint, Rgba, Shape, Tween, evaluate, evaluate_layer_elements}; +use std::f32::consts::FRAC_PI_2; + +const TAIL: ElementId = ElementId(10); +const B1: BoneId = BoneId(20); +const B2: BoneId = BoneId(21); +const N1: ElementId = ElementId(30); +const N2: ElementId = ElementId(31); + +fn bone(id: BoneId, parent: ElementId, child: ElementId, head: Vec2, tail: Vec2) -> Bone { + Bone { id, name: String::new(), parent, child, head, tail, rest: Affine::IDENTITY, limits: None, pinned: false } +} + +/// A tail 200 px long and 20 px thick along y = 0 (anchors every 25 px along both edges), with +/// a cubic tip, drawn at (100, 100) on the stage; two bones along its middle meet at x = 100. +fn outline() -> Path { + let mut p = Path::new(); + p.move_to(Vec2::new(0.0, -10.0)); + for i in 1..=8 { + p.line_to(Vec2::new(25.0 * i as f32, -10.0)); + } + p.cubic_to(Vec2::new(215.0, -10.0), Vec2::new(215.0, 10.0), Vec2::new(200.0, 10.0)); + for i in (0..8).rev() { + p.line_to(Vec2::new(25.0 * i as f32, 10.0)); + } + p.close(); + p +} + +fn rig() -> (Armature, Vec>) { + let path = Arc::new(outline()); + let mut arm = Armature { + bones: vec![bone(B1, TAIL, N1, Vec2::new(0.0, 0.0), Vec2::new(100.0, 0.0)), bone(B2, N1, N2, Vec2::new(100.0, 0.0), Vec2::new(200.0, 0.0))], + skin: Some(Skin::new(TAIL, path.clone())), + }; + rebind(&mut arm); + let shape = Shape { path, ..Shape::filled(Path::new(), Paint::Solid(Rgba::BLACK)) }.with_stroke(Rgba::BLACK, 3.0); + let el = Arc::new(Element { id: TAIL, name: String::new(), transform: Affine::translate(100.0, 100.0), color: ColorEffect::default(), kind: ElementKind::Shape(shape) }); + (arm, vec![el]) +} + +fn path_of(els: &[Arc]) -> Arc { + match &els[0].kind { + ElementKind::Shape(s) => s.path.clone(), + _ => panic!("not a shape"), + } +} + +fn close(a: Vec2, b: Vec2, tol: f32) -> bool { + a.distance(b) <= tol +} + +/// `p` turned by `a` about `j`. +fn turned(p: Vec2, j: Vec2, a: f32) -> Vec2 { + let (s, c) = a.sin_cos(); + let d = p - j; + Vec2::new(j.x + d.x * c - d.y * s, j.y + d.x * s + d.y * c) +} + +#[test] +fn automatic_weights_sum_to_one_and_follow_the_nearest_bone() { + let (arm, _) = rig(); + let skin = arm.skin.as_ref().unwrap(); + let pts = anchors(&skin.rest); + assert_eq!(skin.points.len(), pts.len(), "one binding per anchor"); + for (b, p) in skin.points.iter().zip(&pts) { + let sum: f32 = b.bones.iter().map(|i| i.1).sum(); + assert!((sum - 1.0).abs() < 1e-5, "{p:?}: weights sum to {sum}"); + assert!(b.bones.len() <= MAX_INFLUENCES && b.bones.iter().all(|i| i.1 > 0.0)); + } + // Far along each bone an anchor follows it alone; at the joint the two share it equally. + let at = |x: f32| skin.points.iter().zip(&pts).find(|(_, p)| **p == Vec2::new(x, -10.0)).map(|(b, _)| b.clone()).unwrap(); + assert_eq!(at(25.0).bones, vec![Influence(B1, 1.0)]); + assert_eq!(at(175.0).bones, vec![Influence(B2, 1.0)]); + let joint = at(100.0); + assert!((joint.weight(B1) - 0.5).abs() < 1e-5 && (joint.weight(B2) - 0.5).abs() < 1e-5, "{joint:?}"); + // In between the nearer bone weighs more. + let near = at(125.0); + assert!(near.weight(B2) > near.weight(B1) && near.weight(B1) > 0.0, "{near:?}"); +} + +#[test] +fn the_rest_pose_reproduces_the_shape_exactly() { + let (arm, mut els) = rig(); + let drawn = path_of(&els); + // No pose, and a pose that lists every bone at 0. + for pose in [Pose::default(), Pose(vec![crate::JointAngle { bone: B1, angle: 0.0 }, crate::JointAngle { bone: B2, angle: 0.0 }])] { + let rest = deform(&arm, &pose).unwrap(); + assert!(Arc::ptr_eq(&rest, &drawn), "the very path as drawn"); + assert!(!apply(&arm, &mut els, &pose), "nothing changes"); + } + // A pose that turns one bone leaves the anchors only the other bone moves bit for bit. + let mut pose = Pose::default(); + pose.set(B2, 0.7); + let bent = deform(&arm, &pose).unwrap(); + assert_eq!(bent.cmds[1], drawn.cmds[1], "x = 25 follows the first bone only"); + assert_eq!(bent.cmds[0], drawn.cmds[0]); +} + +#[test] +fn a_quarter_bend_turns_bound_points_about_the_joint() { + let (arm, mut els) = rig(); + let drawn = path_of(&els); + let mut pose = Pose::default(); + pose.set(B2, FRAC_PI_2); + assert!(apply(&arm, &mut els, &pose)); + let bent = path_of(&els); + let skin = arm.skin.as_ref().unwrap(); + let joint = Vec2::new(100.0, 0.0); + let (rest, now) = (anchors(&drawn), anchors(&bent)); + for ((b, r), n) in skin.points.iter().zip(&rest).zip(&now) { + let w2 = b.weight(B2); + if w2 == 1.0 { + assert!(close(*n, turned(*r, joint, FRAC_PI_2), 1e-3), "{r:?} → {n:?}"); + } else if w2 == 0.0 { + assert_eq!(n, r, "{r:?} follows the first bone, which didn't turn"); + } else { + // A shared anchor moves part of the way: the blend of rest and the full turn. + let want = *r * (1.0 - w2) + turned(*r, joint, FRAC_PI_2) * w2; + assert!(close(*n, want, 1e-3), "{r:?}: {n:?} vs {want:?}"); + } + } + // The tip (200, ±10) swings down to (90…110, 100), and its cubic handles turn with it. + assert!(close(now[8], Vec2::new(110.0, 100.0), 1e-3), "{:?}", now[8]); + let PathCmd::CubicTo(c1, c2, end) = bent.cmds[9] else { panic!("{:?}", bent.cmds[9]) }; + assert!(close(c1, turned(Vec2::new(215.0, -10.0), joint, FRAC_PI_2), 1e-3)); + assert!(close(c2, turned(Vec2::new(215.0, 10.0), joint, FRAC_PI_2), 1e-3)); + assert!(close(end, Vec2::new(90.0, 100.0), 1e-3)); + // The shape keeps its transform and its stroke's width. + assert_eq!(els[0].transform, Affine::translate(100.0, 100.0)); + let ElementKind::Shape(s) = &els[0].kind else { panic!("not a shape") }; + assert_eq!(s.stroke.as_ref().map(|s| s.width), Some(3.0)); + // Turning the first bone carries the second: the tip goes round the root joint too. + let mut pose = Pose::default(); + pose.set(B1, FRAC_PI_2); + let tip = anchors(&deform(&arm, &pose).unwrap())[8]; + assert!(close(tip, turned(Vec2::new(200.0, -10.0), Vec2::new(0.0, 0.0), FRAC_PI_2), 1e-3), "{tip:?}"); +} + +#[test] +fn joint_nodes_are_placed_by_forward_kinematics() { + let (arm, els) = rig(); + let mut pose = Pose::default(); + pose.set(B2, FRAC_PI_2); + let w = place(&arm, &els, &pose); + // The second bone's end, on the stage: the shape is at (100, 100), the joint at (200, 100). + assert!(close(w[&N2].apply(Vec2::new(200.0, 0.0)), Vec2::new(200.0, 200.0), 1e-3)); + let at = crate::armature::bones_at(&arm, &els, &pose); + assert_eq!(at.len(), 2, "bones of a shape show although their nodes are no elements"); + assert!(close(at[1].head, Vec2::new(200.0, 100.0), 1e-4) && close(at[1].tail, Vec2::new(200.0, 200.0), 1e-3)); + assert_eq!(arm.roots(), vec![TAIL]); +} + +#[test] +fn inverse_kinematics_bends_the_shape() { + let (arm, els) = rig(); + // Drag the tail's end (stage (300, 100)) up to (250, 0): both bones turn. + let target = Vec2::new(250.0, 0.0); + let s = solve(&arm, &els, &Pose::default(), B2, Vec2::new(200.0, 0.0), target).unwrap(); + assert!(s.error <= 0.01, "{} px off", s.error); + assert_eq!(s.chain, 2); + let tip = place(&arm, &els, &s.pose)[&N2].apply(Vec2::new(200.0, 0.0)); + assert!(close(tip, target, 0.02)); + // The outline's anchors on the bone's end follow it (they're bound to the end bone only). + let mut moved = els.clone(); + apply(&arm, &mut moved, &s.pose); + let tip_anchor = moved[0].transform.apply(anchors(&path_of(&moved))[8]); + assert!(tip_anchor.distance(target) < 11.0, "{tip_anchor:?}"); +} + +fn tail_layer(easing: Easing) -> Layer { + let (arm, els) = rig(); + let mut l = Layer::new(LayerId(1), "Armature_1"); + l.kind = LayerKind::Armature; + l.armature = Some(Arc::new(arm)); + let mut a = Keyframe::new(0, 10); + a.elements = els.clone(); + a.tween = Some(Tween { easing, ..Tween::default() }); + let mut b = Keyframe::new(10, 5); + b.elements = els; + b.pose.set(B2, FRAC_PI_2); + l.keyframes = vec![Arc::new(a), Arc::new(b)]; + l +} + +#[test] +fn poses_tween_the_outline_with_easing() { + let l = tail_layer(Easing::Linear); + let tip = |f: u32| { + let (_, els) = evaluate_layer_elements(&l, f).unwrap(); + anchors(&path_of(&els))[8] + }; + let rest = Vec2::new(200.0, -10.0); + let joint = Vec2::new(100.0, 0.0); + assert_eq!(tip(0), rest, "exact at the first key"); + assert!(close(tip(10), turned(rest, joint, FRAC_PI_2), 1e-3), "exact at the second key"); + // Half way the tip has turned 45°: angles tween, the outline follows (not a straight morph). + assert!(close(tip(5), turned(rest, joint, FRAC_PI_2 * 0.5), 1e-3), "{:?}", tip(5)); + let eased = tail_layer(Easing::QuadIn); + assert!((pose_at(&eased, 5).unwrap().angle(B2) - FRAC_PI_2 * 0.25).abs() < 1e-6); +} + +#[test] +fn every_export_sees_the_bent_shape_and_files_keep_it() { + let mut d = Document::default(); + d.timeline_mut(0).layers = vec![Arc::new(tail_layer(Easing::Linear))]; + d.sanitize(); + let dl = evaluate(&d, 10); + let item = dl.items.iter().find(|i| i.element == TAIL).unwrap(); + let tip = item.transform.apply(anchors(&item.path)[8]); + assert!(close(tip, Vec2::new(210.0, 200.0), 1e-3), "the display list draws the bent tail: {tip:?}"); + let json = serde_json::to_string(&d).unwrap(); + let back: Document = serde_json::from_str(&json).unwrap(); + assert_eq!(back, d); + assert!(back.timeline(0).layers[0].armature.as_ref().unwrap().skin.is_some()); + // The joint nodes' ids are counted, so new ids never collide with them. + assert!(d.next_id > N2.0); + // An armature written before shape armatures reads as one without a skin. + let old: Armature = serde_json::from_str(r#"{"bones": []}"#).unwrap(); + assert!(old.skin.is_none()); + assert!(!serde_json::to_string(&old).unwrap().contains("skin")); +} + +#[test] +fn sanitize_repairs_hostile_skins() { + let (mut arm, _) = rig(); + let skin = arm.skin.as_mut().unwrap(); + skin.points.truncate(3); + skin.points[0] = Binding { bones: vec![Influence(B1, f32::NAN), Influence(BoneId(99), 1.0), Influence(B2, 3.0), Influence(B2, 1.0)], manual: true }; + skin.points[1] = Binding { bones: vec![Influence(B1, -1.0)], manual: false }; + skin.points[2] = Binding { bones: vec![], manual: true }; + assert!(arm.sanitize()); + let skin = arm.skin.as_ref().unwrap(); + assert_eq!(skin.points.len(), anchors(&skin.rest).len(), "one per anchor again"); + assert_eq!(skin.points[0].bones, vec![Influence(B2, 1.0)], "unknown bones, NaN and repeats go; the rest sums to 1"); + assert!(!skin.points[1].bones.is_empty(), "an automatic anchor left with nothing is bound again"); + assert!(skin.points[2].bones.is_empty(), "an anchor unbound by hand stays unbound"); + assert!(!arm.sanitize(), "sanitizing twice changes nothing"); + // A bone that starts somewhere other than the shape, and a shape that is a bone's node. + let (mut arm, _) = rig(); + arm.bones.push(bone(BoneId(40), ElementId(77), ElementId(78), Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.0))); + arm.sanitize(); + assert_eq!(arm.bones.len(), 2, "every bone of a shape armature hangs from the shape"); + let (mut arm, _) = rig(); + arm.bones.push(bone(BoneId(41), N2, TAIL, Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.0))); + arm.sanitize(); + assert!(arm.skin.is_none() || arm.bones.iter().all(|b| b.child != TAIL)); +} + +#[test] +fn hand_binding_survives_new_bones() { + let (mut arm, _) = rig(); + let skin = arm.skin.as_mut().unwrap(); + skin.points[1] = Binding { bones: vec![Influence(B2, 1.0)], manual: true }; + skin.points[2] = Binding { bones: vec![], manual: true }; + arm.bones.push(bone(BoneId(22), N2, ElementId(32), Vec2::new(200.0, 0.0), Vec2::new(210.0, 0.0))); + rebind(&mut arm); + let skin = arm.skin.as_ref().unwrap(); + assert_eq!(skin.points[1].bones, vec![Influence(B2, 1.0)], "kept as bound by hand"); + assert!(skin.points[2].bones.is_empty(), "kept unbound"); + // Taking its bone away sends a hand-bound anchor back to automatic. + let mut arm = arm.clone(); + arm.bones.retain(|b| b.id != B2 && b.id != BoneId(22)); + rebind(&mut arm); + assert_eq!(arm.skin.as_ref().unwrap().points[1].bones, vec![Influence(B1, 1.0)]); +} + +/// Skinning cost: a shape of 2,000 anchors on 16 bones, posed (debug builds are slower). +#[test] +fn skinning_is_fast() { + let mut p = Path::new(); + p.move_to(Vec2::new(0.0, -10.0)); + for i in 1..1000 { + p.line_to(Vec2::new(i as f32 * 0.8, -10.0)); + } + for i in (0..1000).rev() { + p.line_to(Vec2::new(i as f32 * 0.8, 10.0)); + } + p.close(); + let mut bones = Vec::new(); + for i in 0..16u64 { + let parent = if i == 0 { TAIL } else { ElementId(100 + i - 1) }; + bones.push(bone(BoneId(200 + i), parent, ElementId(100 + i), Vec2::new(50.0 * i as f32, 0.0), Vec2::new(50.0 * (i + 1) as f32, 0.0))); + } + let mut arm = Armature { bones, skin: Some(Skin::new(TAIL, Arc::new(p))) }; + let t = std::time::Instant::now(); + rebind(&mut arm); + let bind = t.elapsed(); + let pose = Pose(arm.bones.iter().map(|b| crate::JointAngle { bone: b.id, angle: 0.1 }).collect()); + let t = std::time::Instant::now(); + for _ in 0..10 { + std::hint::black_box(deform(&arm, &pose)); + } + let per = t.elapsed() / 10; + println!("2,000 anchors × 16 bones: bind {bind:?}, deform {per:?}"); + assert!(per.as_millis() < 50, "{per:?}"); +} diff --git a/crates/engine/src/cmds_bone.rs b/crates/engine/src/cmds_bone.rs index d18defb7..26e3631d 100644 --- a/crates/engine/src/cmds_bone.rs +++ b/crates/engine/src/cmds_bone.rs @@ -197,7 +197,7 @@ fn add(s: &mut Session, p: &Value) -> Result { layer.kind = LayerKind::Armature; // Bones show in the layer colour: a green that reads on light and dark artwork. layer.color = Rgba::hex(0x2fb67c); - layer.armature = Some(Arc::new(Armature { bones: vec![bone] })); + layer.armature = Some(Arc::new(Armature { bones: vec![bone], skin: None })); let mut k = Keyframe::new(start, end.saturating_sub(start).max(1)); k.elements = vec![f.el.clone(), t.el.clone()]; k.tween = Some(Tween::default()); From 77fe2d152ee325dc520f30453de0b5592cbd5cb8 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Thu, 12 Nov 2026 00:30:43 -0700 Subject: [PATCH 03/18] feat(engine): bone.add_in_shape and bone.bind for shape armatures (M7) --- crates/engine/src/cmds_bone.rs | 260 ++++++++++++++++++++--- crates/engine/src/lib.rs | 2 + crates/engine/src/tests.rs | 20 +- crates/engine/src/tests_shape_bone.rs | 292 ++++++++++++++++++++++++++ 4 files changed, 545 insertions(+), 29 deletions(-) create mode 100644 crates/engine/src/tests_shape_bone.rs diff --git a/crates/engine/src/cmds_bone.rs b/crates/engine/src/cmds_bone.rs index 26e3631d..8949d4fa 100644 --- a/crates/engine/src/cmds_bone.rs +++ b/crates/engine/src/cmds_bone.rs @@ -12,6 +12,7 @@ use crate::cmds_timeline::insert_keyframe_at; use crate::params::*; use crate::{CommandSpec, EngineError, KeyEdit, MAX_FRAME, Result, Session}; use anicraft_doc::armature::{self, Armature, Bone, BoneId, Limits, MAX_BONES, MAX_LIMIT, MAX_NAME}; +use anicraft_doc::skin::{self, Binding, Influence, MAX_SKIN_POINTS, Skin}; use anicraft_doc::{Element, ElementId, ElementKind, Keyframe, Layer, LayerId, LayerKind, Rgba, Tween, evaluate_layer_elements}; use anicraft_geom::{Affine, Vec2}; use serde_json::{Value, json}; @@ -27,12 +28,20 @@ pub fn specs() -> Vec { true, add as crate::RunFn, ), + c( + "bone.add_in_shape", + "Add Bone in Shape", + "{shape? (shape id: the first bone, or another bone from the shape), parent? (bone id: continue the chain from its end), head?: [x, y] (the joint, stage px; default the parent bone's end), tail: [x, y] (stage px), name?} → {bone, layer, created, points}. The first bone moves the shape to an armature layer of its own, as an object (merge drawing leaves it alone); the shape's points are bound to the nearest bones", + true, + add_in_shape, + ), + c("bone.bind", "Bind Points", "{bone, points?: [point index…] (default every point; see bone.info with points), mode?: \"only\" (the points follow just this bone; default) | \"add\" (they share it with the bones they follow) | \"remove\" | \"auto\" (back to automatic binding)} → {bone, changed, bound (how many points the bone moves)}. A shape armature's binding: which points of the shape follow which bone", true, bind), c("bone.remove", "Remove Bone", "{bone} removes it and the bones below it; the instances they moved go to a layer of their own as they look at the playhead (with the last bone, the whole armature does); asks first when the armature has more than one pose", true, remove), c("bone.set_limits", "Joint Limits", "{bone, constrain?: bool (false: turns freely), min?, max? (°, −360…360, from where it was drawn)} limits how far the joint turns, in every pose", true, set_limits), c("bone.pin", "Pin Bone", "{bone, pinned: bool} a pinned bone (and the bones it hangs from) stays put while dragging bones below it", true, pin), c("bone.pose", "Pose Bone", "{bone?, angle? (°, the joint angle: 0 as drawn), rotate_by? (°), dx?, dy? (moves the whole armature), layer? (the armature layer, when no bone is given), frame?} keys the pose at the frame", true, pose), c("bone.solve", "Drag Bone", "{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)", true, solve), - c("bone.info", "Armatures", "{frame?, layer?} → every armature on the scene at the frame: its bones with joint and end (stage px), joint angle and limits (°), pinned", false, info), + c("bone.info", "Armatures", "{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", false, info), ] } @@ -119,6 +128,32 @@ fn rebake(layer: &mut Layer) { } } +/// A new armature layer at `index` holding `arm` and `elements` on one pose that spans from the +/// keyframe of `from` at the playhead to the end of the timeline (a classic tween on it, so +/// poses keyed later tween). +fn armature_layer(s: &mut Session, from: LayerId, index: usize, elements: Vec>, arm: Armature) -> Result { + let (start, end) = s.timeline().layer(from).and_then(|l| l.keyframe_at(s.frame)).map_or((s.frame, s.frame + 1), |k| (k.start, k.end())); + let end = end.max(s.frame_count()); + if s.timeline().layers.len() >= 1000 { + return Err(EngineError::State("too many layers (limit 1000)".into())); + } + let lid = LayerId(s.doc.alloc_id()); + let mut layer = Layer::new(lid, fresh_name(s, "Armature_")); + layer.kind = LayerKind::Armature; + // Bones show in the layer colour: a green that reads on light and dark artwork. + layer.color = Rgba::hex(0x2fb67c); + layer.armature = Some(Arc::new(arm)); + let mut k = Keyframe::new(start, end.saturating_sub(start).max(1)); + k.elements = elements; + k.tween = Some(Tween::default()); + layer.keyframes = vec![Arc::new(k)]; + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing); + layer.parent = tl.container_at(index, LayerKind::Armature); + tl.layers.insert(index.min(tl.layers.len()), Arc::new(layer)); + tl.repair_masks(); + Ok(lid) +} + fn add(s: &mut Session, p: &Value) -> Result { let req = |k: &str| opt_u64(p, k)?.map(ElementId).ok_or_else(|| EngineError::Param(format!("param '{k}' (an instance id) is required"))); let (from, to) = (req("from")?, req("to")?); @@ -184,30 +219,10 @@ fn add(s: &mut Session, p: &Value) -> Result { f.layer } None => { - // The first bone: both instances move to a new armature layer above them, whose one - // pose spans from their keyframe to the end of the timeline. - let (start, end) = s.timeline().layer(f.layer).and_then(|l| l.keyframe_at(s.frame)).map_or((s.frame, s.frame + 1), |k| (k.start, k.end())); - let end = end.max(s.frame_count()); + // The first bone: both instances move to a new armature layer above them. take_off(s, f.layer, from)?; - if s.timeline().layers.len() >= 1000 { - return Err(EngineError::State("too many layers (limit 1000)".into())); - } - let lid = LayerId(s.doc.alloc_id()); - let mut layer = Layer::new(lid, fresh_name(s, "Armature_")); - layer.kind = LayerKind::Armature; - // Bones show in the layer colour: a green that reads on light and dark artwork. - layer.color = Rgba::hex(0x2fb67c); - layer.armature = Some(Arc::new(Armature { bones: vec![bone], skin: None })); - let mut k = Keyframe::new(start, end.saturating_sub(start).max(1)); - k.elements = vec![f.el.clone(), t.el.clone()]; - k.tween = Some(Tween::default()); - layer.keyframes = vec![Arc::new(k)]; - let index = f.index.min(t.index); - let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing); - layer.parent = tl.container_at(index, LayerKind::Armature); - tl.layers.insert(index.min(tl.layers.len()), Arc::new(layer)); - tl.repair_masks(); - lid + let arm = Armature { bones: vec![bone], skin: None }; + armature_layer(s, f.layer, f.index.min(t.index), vec![f.el.clone(), t.el.clone()], arm)? } }; s.layer = lid; @@ -229,7 +244,10 @@ fn remove(s: &mut Session, p: &Value) -> Result { let mut left = (*arm).clone(); left.bones.retain(|b| !gone.contains(&b.id)); let dissolve = left.is_empty(); - let freed: Vec = if dissolve { arm.members() } else { arm.bones.iter().filter(|b| gone.contains(&b.id)).map(|b| b.child).collect() }; + // A shape armature's bones move no instances: only without bones does its shape go. + let skinned = arm.skin.is_some(); + skin::rebind(&mut left); + let freed: Vec = if dissolve { arm.members() } else if skinned { Vec::new() } else { arm.bones.iter().filter(|b| gone.contains(&b.id)).map(|b| b.child).collect() }; let tl = s.timeline(); let index = tl.layers.iter().position(|l| l.id == lid).ok_or_else(|| EngineError::State("the armature layer went away".into()))?; let layer = tl.layer(lid).ok_or_else(|| EngineError::State("the armature layer went away".into()))?; @@ -257,12 +275,15 @@ fn remove(s: &mut Session, p: &Value) -> Result { } l.armature = Some(Arc::new(left)); rebake(l); - tl.layers.insert((index + 1).min(tl.layers.len()), Arc::new(freed_layer)); + if !skinned { + tl.layers.insert((index + 1).min(tl.layers.len()), Arc::new(freed_layer)); + } } tl.repair_masks(); s.layer = if dissolve { new_id } else { lid }; s.selection.clear(); - Ok(json!({"removed": gone.iter().map(|b| b.0).collect::>(), "freed": freed.iter().map(|e| e.0).collect::>(), "layer": new_id.0, "armature_removed": dissolve})) + let layer = if dissolve || !skinned { new_id } else { lid }; + Ok(json!({"removed": gone.iter().map(|b| b.0).collect::>(), "freed": freed.iter().map(|e| e.0).collect::>(), "layer": layer.0, "armature_removed": dissolve})) } fn set_limits(s: &mut Session, p: &Value) -> Result { @@ -411,6 +432,7 @@ fn solve(s: &mut Session, p: &Value) -> Result { fn info(s: &mut Session, p: &Value) -> Result { let frame = opt_u32(p, "frame")?.unwrap_or(s.frame).min(MAX_FRAME); let only = opt_u64(p, "layer")?.map(LayerId); + let with_points = opt_bool(p, "points")?.unwrap_or(false); let tl = s.timeline(); let deg = |v: f32| v.to_degrees(); let pt = |v: Vec2| json!([v.x, v.y]); @@ -435,11 +457,193 @@ fn info(s: &mut Session, p: &Value) -> Result { "angle": deg(b.allow(pose.angle(b.id))), "min": b.limits.map(|l| deg(l.min)), "max": b.limits.map(|l| deg(l.max)), "pinned": b.pinned, + "points": arm.skin.as_ref().map(|k| k.points.iter().filter(|x| x.weight(b.id) > 0.0).count()), }) }) .collect(); - Some(json!({"layer": l.id.0, "name": l.name, "roots": arm.roots().iter().map(|e| e.0).collect::>(), "poses": poses(l), "bones": bones})) + let mut out = json!({"layer": l.id.0, "name": l.name, "roots": arm.roots().iter().map(|e| e.0).collect::>(), "poses": poses(l), "bones": bones, "shape": arm.skin_shape().map(|e| e.0)}); + if with_points && let Some(k) = &arm.skin { + out["points"] = json!(shape_points(arm, &els).iter().zip(&k.points).map(|(at, b)| json!({"at": pt(*at), "bones": b.bones.iter().map(|i| json!([i.0.0, i.1])).collect::>(), "manual": b.manual})).collect::>()); + } + Some(out) }) .collect(); Ok(json!({"frame": frame, "armatures": list})) } + +/// The points of a shape armature's shape as they show (stage px, in point order): the +/// anchors of its posed outline. +pub fn shape_points(arm: &Armature, elements: &[Arc]) -> Vec { + let Some(id) = arm.skin_shape() else { return Vec::new() }; + elements + .iter() + .find(|e| e.id == id) + .and_then(|e| match &e.kind { + ElementKind::Shape(sh) => Some(skin::anchors(&sh.path).into_iter().map(|p| e.transform.apply(p)).collect()), + _ => None, + }) + .unwrap_or_default() +} + +fn add_in_shape(s: &mut Session, p: &Value) -> Result { + let shape = opt_u64(p, "shape")?.map(ElementId); + let parent = opt_u64(p, "parent")?.map(BoneId); + let head = opt_point(p, "head")?; + let tail = opt_point(p, "tail")?.ok_or_else(|| EngineError::Param("param 'tail' ([x, y], stage px: where the bone ends) is required".into()))?; + let name = opt_str(p, "name")?.unwrap_or("").trim().to_string(); + if name.len() > MAX_NAME { + return Err(EngineError::Param(format!("param 'name' must be at most {MAX_NAME} bytes"))); + } + let frame = s.frame; + // The armature the bone joins (none yet for the first bone), the shape, the node the bone + // starts on, and its joint on the stage. + let (existing, found, from, head) = match (parent, shape) { + (Some(b), _) => { + let (lid, arm) = find_bone(s, b)?; + let sh = arm.skin_shape().ok_or_else(|| EngineError::State("that bone joins symbol instances: continue it with bone.add".into()))?; + if shape.is_some_and(|x| x != sh) { + return Err(EngineError::Param("that bone is in another shape".into())); + } + let f = find_instance(s, sh).ok_or_else(|| EngineError::State(format!("the armature's shape isn't on the stage at frame {}", frame + 1)))?; + let node = arm.bone(b).map(|x| x.child).ok_or_else(|| EngineError::State("no such bone".into()))?; + let end = s.timeline().layer(lid).and_then(|l| { + let (_, els) = evaluate_layer_elements(l, frame)?; + let pose = armature::pose_at(l, frame).unwrap_or_default(); + armature::bones_at(&arm, &els, &pose).into_iter().find(|g| g.id == b).map(|g| g.tail) + }); + let head = head.or(end).ok_or_else(|| EngineError::State(format!("the bone isn't on the stage at frame {}", frame + 1)))?; + (Some((lid, arm)), f, node, head) + } + (None, Some(sh)) => { + let f = find_instance(s, sh).ok_or_else(|| EngineError::State(format!("no shape with id {} on the stage at frame {}", sh.0, frame + 1)))?; + let ElementKind::Shape(shp) = &f.el.kind else { + return Err(EngineError::State("bones inside a shape need a shape: for symbol instances, drag from one to another (bone.add)".into())); + }; + let head = head.ok_or_else(|| EngineError::Param("param 'head' ([x, y], stage px: where the bone starts, inside the shape) is required".into()))?; + let existing = match f.kind { + LayerKind::Normal => None, + LayerKind::Armature => { + let arm = s.timeline().layer(f.layer).and_then(|l| l.armature.clone()).filter(|a| a.skin_shape() == Some(sh)).ok_or_else(|| EngineError::State("that shape isn't the armature's".into()))?; + Some((f.layer, arm)) + } + _ => return Err(EngineError::State("bones go inside shapes on normal layers (not on guide or mask layers)".into())), + }; + // A bone starts inside the shape (on its fill, or on its line). + let reach = shp.stroke.as_ref().map_or(0.0, |k| k.width * 0.5 * f.el.transform.mean_scale()) + 2.0; + let inside = (shp.fill.is_some() && shp.path.contains(head, &f.el.transform, shp.fill_rule)) || shp.path.distance_to_edge(head, &f.el.transform) <= reach; + if !inside { + return Err(EngineError::State("start the bone inside the shape".into())); + } + (existing, f, sh, head) + } + (None, None) => return Err(EngineError::Param("give 'shape' (the shape's id, for the first bone) or 'parent' (a bone to continue from)".into())), + }; + unlocked(s, found.layer)?; + if head.distance(tail) < 1.0 { + return Err(EngineError::Param("a bone needs a length: drag from its joint to its end".into())); + } + let ElementKind::Shape(shp) = &found.el.kind else { return Err(EngineError::State("that isn't a shape".into())) }; + // The node the bone starts on, as placed at the playhead: the bone's points go back through + // it to the shape as drawn (a new bone is at rest in every pose). + let node = match &existing { + Some((lid, arm)) => { + let l = s.timeline().layer(*lid).ok_or_else(|| EngineError::State("the armature layer went away".into()))?; + let (_, els) = evaluate_layer_elements(l, frame).ok_or_else(|| EngineError::State("the armature isn't on this frame".into()))?; + let pose = armature::pose_at(l, frame).unwrap_or_default(); + armature::place(arm, &els, &pose).get(&from).copied() + } + None => Some(found.el.transform), + }; + let inv = node.and_then(|m| m.inverse()).ok_or_else(|| EngineError::State("a shape scaled to nothing can't hold a bone".into()))?; + let (h, t) = (inv.apply(head), inv.apply(tail)); + if !(h.x.is_finite() && h.y.is_finite() && t.x.is_finite() && t.y.is_finite()) { + return Err(EngineError::State("a shape scaled to nothing can't hold a bone".into())); + } + if existing.as_ref().is_some_and(|(_, a)| a.bones.len() >= MAX_BONES) { + return Err(EngineError::State(format!("an armature has at most {MAX_BONES} bones"))); + } + if existing.is_none() && skin::anchors(&shp.path).len() > MAX_SKIN_POINTS { + return Err(EngineError::State(format!("bones go inside shapes of at most {MAX_SKIN_POINTS} points: simplify it first (Modify › Shape › Optimize)"))); + } + let id = BoneId(s.doc.alloc_id()); + let child = ElementId(s.doc.alloc_id()); + let bone = Bone { id, name, parent: from, child, head: h, tail: t, rest: Affine::IDENTITY, limits: None, pinned: false }; + let (lid, created) = match existing { + Some((lid, arm)) => { + let mut arm = (*arm).clone(); + arm.bones.push(bone); + skin::rebind(&mut arm); + let l = s.layer_mut(Some(lid))?; + l.armature = Some(Arc::new(arm)); + rebake(l); + (lid, false) + } + None => { + // An armature's shape is an object: merge drawing (ADR 0031) no longer cuts it. + let mut el = (*found.el).clone(); + if let ElementKind::Shape(x) = &mut el.kind { + x.merge = false; + } + let mut arm = Armature { bones: vec![bone], skin: Some(Skin::new(found.el.id, shp.path.clone())) }; + skin::rebind(&mut arm); + take_off(s, found.layer, found.el.id)?; + (armature_layer(s, found.layer, found.index, vec![Arc::new(el)], arm)?, true) + } + }; + s.layer = lid; + s.selection.clear(); + let bound = s.timeline().layer(lid).and_then(|l| l.armature.as_ref()).and_then(|a| a.skin.as_ref()).map_or(0, |k| k.points.iter().filter(|b| b.weight(id) > 0.0).count()); + Ok(json!({"bone": id.0, "layer": lid.0, "created": created, "points": bound})) +} + +fn bind(s: &mut Session, p: &Value) -> Result { + let id = bone_param(p)?; + let mode = opt_str(p, "mode")?.unwrap_or("only"); + if !matches!(mode, "only" | "add" | "remove" | "auto") { + return Err(EngineError::Param("param 'mode' must be \"only\", \"add\", \"remove\" or \"auto\"".into())); + } + let (lid, arm) = find_bone(s, id)?; + unlocked(s, lid)?; + let n = arm.skin.as_ref().map(|k| k.points.len()).ok_or_else(|| EngineError::State("that bone joins symbol instances: only bones inside a shape bind its points".into()))?; + let bad = || EngineError::Param(format!("param 'points' must be a list of point indices below {n} (see bone.info with points)")); + let points: Vec = match p.get("points") { + None | Some(Value::Null) => (0..n).collect(), + Some(Value::Array(a)) if a.len() <= MAX_SKIN_POINTS => a.iter().map(|v| v.as_u64().and_then(|i| usize::try_from(i).ok()).filter(|i| *i < n).ok_or_else(bad)).collect::>()?, + Some(_) => return Err(bad()), + }; + let mut arm = (*arm).clone(); + let segments = skin::rest_segments(&arm); + let Some(k) = arm.skin.as_mut() else { return Err(EngineError::State("that bone isn't inside a shape".into())) }; + let anchors = skin::anchors(&k.rest); + let mut changed = 0usize; + for i in points { + let (Some(b), Some(&at)) = (k.points.get_mut(i), anchors.get(i)) else { continue }; + let next = match mode { + "only" => Binding { bones: vec![Influence(id, 1.0)], manual: true }, + "add" if b.weight(id) > 0.0 => continue, + "add" => { + // An equal share with the bones the point already follows. + let share = 1.0 / (b.bones.len() + 1) as f32; + let mut x = Binding { bones: b.bones.iter().map(|i| Influence(i.0, i.1 * (1.0 - share))).collect(), manual: true }; + x.bones.push(Influence(id, share)); + x.normalize(|_| true); + x + } + "remove" => { + let mut x = Binding { bones: b.bones.iter().copied().filter(|i| i.0 != id).collect(), manual: true }; + x.normalize(|_| true); + x + } + _ => skin::auto_binding(&segments, at), + }; + if *b != next { + *b = next; + changed += 1; + } + } + let bound = k.points.iter().filter(|b| b.weight(id) > 0.0).count(); + let l = s.layer_mut(Some(lid))?; + l.armature = Some(Arc::new(arm)); + rebake(l); + Ok(json!({"bone": id.0, "changed": changed, "bound": bound})) +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 5dfa57e4..aed62c54 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1015,6 +1015,8 @@ mod tests_camera; #[cfg(test)] mod tests_bone; #[cfg(test)] +mod tests_shape_bone; +#[cfg(test)] mod merge_tests; #[cfg(test)] mod raw_tests; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 96a3bf36..50e2061e 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -623,6 +623,11 @@ fn panic_hunt_every_command() { json!({"from": 10, "to": 12, "head": [0, 0], "tail": [1e30, 0], "name": "x".repeat(300)}), json!({"from": 12, "to": 10, "head": [5], "tail": "x", "bone": u64::MAX}), json!({"from": 11, "to": 13, "head": [-1e6, 1e6], "layer": 101}), + // Shape armatures (ADR 0071): the shaped session's tail is 3, its bones 100 and 103. + json!({"shape": 3, "head": [1e30, 0], "tail": [-1e30, 0], "parent": 103, "points": [0, 1, u64::MAX], "mode": "add"}), + json!({"shape": 3, "head": [150, 150], "tail": [150, 150], "bone": 103, "points": (0..30).collect::>(), "mode": "remove"}), + json!({"parent": 100, "tail": [250, 290], "bone": 100, "points": [], "mode": "auto", "points_": true}), + json!({"bone": 100, "points": ["a", -1, 1e30], "mode": 7}), // Edit Multiple Frames (ADR 0047): ranges past the end or reversed, items that aren't // there or aren't triples, moves at the limits. json!({"first": 0, "last": 99_999, "dx": 1e7, "dy": -1e7, "items": [[0, 0, 1], "x", [u64::MAX, u64::MAX, u64::MAX]]}), @@ -691,6 +696,19 @@ fn panic_hunt_every_command() { } assert_eq!((b1, b2), (100, 102), "the hostile params name these bones"); rig.set_frame(4); + // A shape armature: a tail with two bones, bent at frame 8, a point bound by hand (ADR 0071). + let mut shaped = Session::default(); + shaped.style.object_drawing = false; + shaped.execute("draw.rect", &json!({"x": 100, "y": 140, "w": 200, "h": 20})).unwrap(); + shaped.doc.next_id = 100; + let tail = shaped.doc.timeline(0).layers[0].keyframes[0].elements[0].id.0; + let sb1 = shaped.execute("bone.add_in_shape", &json!({"shape": tail, "head": [100, 150], "tail": [200, 150]})).unwrap()["bone"].as_u64().unwrap(); + let sb2 = shaped.execute("bone.add_in_shape", &json!({"parent": sb1, "tail": [300, 150]})).unwrap()["bone"].as_u64().unwrap(); + for (id, p) in [("bone.pose", json!({"bone": sb2, "angle": 60, "frame": 8})), ("bone.bind", json!({"bone": sb1, "points": [0], "mode": "add"}))] { + shaped.execute(id, &p).unwrap(); + } + assert_eq!((tail, sb1, sb2), (3, 100, 103), "the hostile params name these"); + shaped.set_frame(4); // 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(); @@ -785,7 +803,7 @@ fn panic_hunt_every_command() { if let Some(id) = button.doc.library.iter().find(|x| x.kind == anicraft_doc::SymbolKind::Button).map(|x| x.id) { button.execute("symbol.edit", &json!({"symbol": id.0})).unwrap(); } - for start in [Session::default(), Session::new(sample::demo()), Session::new(with_sound), on_path, raw, rig, layered, in_symbol, keyed, library, button] { + for start in [Session::default(), Session::new(sample::demo()), Session::new(with_sound), on_path, raw, rig, shaped, layered, in_symbol, keyed, library, button] { 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_shape_bone.rs b/crates/engine/src/tests_shape_bone.rs new file mode 100644 index 00000000..564ee773 --- /dev/null +++ b/crates/engine/src/tests_shape_bone.rs @@ -0,0 +1,292 @@ +//! Shape armatures end to end (ADR 0071): bones drawn inside a shape, automatic binding, the +//! Bind tool's command, posing by angle and by IK, pose tweens, removal, undo, refusals, the +//! file format, analytic renders and plug-in policy. + +use super::*; +use anicraft_doc::{ColorEffect, Document, ElementKind, Paint, Rgba, Shape, Stage}; +use anicraft_geom::{Affine, Path, PathCmd}; +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}"), + } +} + +const TAIL: u64 = 10; + +/// A 400 × 300 stage, 20 frames, with a black tail 200 × 20 px lying along y = 150 from +/// x = 100 (anchors every 25 px along both edges, part of the layer's merged drawing). +fn tail() -> Session { + let mut d = Document { stage: Stage { width: 400, height: 300, ..Stage::default() }, ..Document::default() }; + let mut p = Path::new(); + p.move_to(Vec2::new(0.0, -10.0)); + for i in 1..=8 { + p.line_to(Vec2::new(25.0 * i as f32, -10.0)); + } + for i in (0..=8).rev() { + p.line_to(Vec2::new(25.0 * i as f32, 10.0)); + } + p.close(); + let shape = Shape { merge: true, ..Shape::filled(p, Paint::Solid(Rgba::BLACK)) }; + let el = Arc::new(Element { id: ElementId(TAIL), name: String::new(), transform: Affine::translate(100.0, 150.0), color: ColorEffect::default(), kind: ElementKind::Shape(shape) }); + let l = Arc::make_mut(&mut d.timeline_mut(0).layers[0]); + l.keyframes = vec![Arc::new({ + let mut k = Keyframe::new(0, 20); + k.elements = vec![el]; + k + })]; + d.next_id = 100; + Session::new(d) +} + +/// [`tail`] with two bones along its middle: (100, 150) → (200, 150) → (300, 150). +fn rigged() -> (Session, u64, u64) { + let mut s = tail(); + let v = run(&mut s, "bone.add_in_shape", json!({"shape": TAIL, "head": [100, 150], "tail": [200, 150]})); + assert_eq!(v["created"], true); + let b1 = v["bone"].as_u64().unwrap(); + let b2 = run(&mut s, "bone.add_in_shape", json!({"parent": b1, "tail": [300, 150]}))["bone"].as_u64().unwrap(); + (s, b1, b2) +} + +fn shape_at(s: &Session, frame: u32) -> (Affine, Arc, bool) { + let tl = s.doc.timeline(s.scene); + tl.layers + .iter() + .find_map(|l| { + let (_, els) = evaluate_layer_elements(l, frame)?; + els.iter().find(|e| e.id.0 == TAIL).and_then(|e| match &e.kind { + ElementKind::Shape(sh) => Some((e.transform, sh.path.clone(), sh.merge)), + _ => None, + }) + }) + .unwrap() +} + +/// The tail's anchors on the stage at `frame`. +fn points(s: &Session, frame: u32) -> Vec { + let (m, p, _) = shape_at(s, frame); + anicraft_doc::skin::anchors(&p).into_iter().map(|a| m.apply(a)).collect() +} + +fn turned(p: Vec2, j: Vec2, a: f32) -> Vec2 { + let (sn, c) = a.sin_cos(); + let d = p - j; + Vec2::new(j.x + d.x * c - d.y * sn, j.y + d.x * sn + d.y * c) +} + +fn black(s: &Session, frame: u32, x: u32, y: u32) -> bool { + render_frame(&s.doc, frame, 1.0).unwrap().pixel(x, y).unwrap()[0] < 0.1 +} + +#[test] +fn bones_inside_a_shape_move_it_to_an_armature_layer_as_drawn() { + let before = render_frame(&tail().doc, 0, 1.0).unwrap().data; + let drawn = points(&tail(), 0); + let (mut s, b1, b2) = rigged(); + let tl = s.doc.timeline(0); + assert_eq!(tl.layers.len(), 2); + let arm = &tl.layers[0]; + assert_eq!(arm.kind, LayerKind::Armature); + assert_eq!(s.layer, arm.id, "the armature layer is active"); + assert!(tl.layers[1].keyframes[0].elements.is_empty(), "the shape left its layer"); + let (m, _, merge) = shape_at(&s, 0); + assert_eq!(m, Affine::translate(100.0, 150.0)); + assert!(!merge, "an armature's shape is an object: merge drawing leaves it"); + // The rest pose is the drawing, exactly. + assert_eq!(points(&s, 0), drawn); + assert_eq!(render_frame(&s.doc, 0, 1.0).unwrap().data, before); + let v = run(&mut s, "bone.info", json!({"points": true})); + let a = &v["armatures"][0]; + assert_eq!(a["shape"], TAIL); + assert_eq!(a["roots"], json!([TAIL])); + let bones = a["bones"].as_array().unwrap(); + assert_eq!((bones[0]["id"].as_u64(), bones[1]["id"].as_u64()), (Some(b1), Some(b2))); + assert_eq!(bones[1]["parent_bone"], b1); + assert_eq!(bones[1]["head"], json!([200.0, 150.0]), "the chain joins end to start"); + // Every point is bound, its weights summing to 1. + let pts = a["points"].as_array().unwrap(); + assert_eq!(pts.len(), drawn.len()); + for p in pts { + let sum: f64 = p["bones"].as_array().unwrap().iter().map(|i| i[1].as_f64().unwrap()).sum(); + assert!((sum - 1.0).abs() < 1e-5, "{p}"); + } + let (n1, n2) = (bones[0]["points"].as_u64().unwrap(), bones[1]["points"].as_u64().unwrap()); + assert!(n1 > 0 && n2 > 0 && n1 + n2 >= drawn.len() as u64, "{n1} + {n2}"); +} + +#[test] +fn a_quarter_bend_swings_the_tail_and_tweens_through_the_middle() { + let (mut s, _, b2) = rigged(); + let drawn = points(&s, 0); + // Key the bend at frame 10 (the rest pose at 0 tweens into it). + run(&mut s, "bone.pose", json!({"bone": b2, "angle": 90, "frame": 10})); + let joint = Vec2::new(200.0, 150.0); + let bent = points(&s, 10); + // The tip's corners (the 8th and 9th points) follow the second bone alone. + for i in [8, 9] { + assert!(bent[i].distance(turned(drawn[i], joint, std::f32::consts::FRAC_PI_2)) < 1e-3, "{i}: {:?}", bent[i]); + } + // The root half didn't move. + assert_eq!(bent[1], drawn[1]); + assert_eq!(bent[0], drawn[0]); + // Half way the tip has turned 45°. + let mid = points(&s, 5); + assert!(mid[8].distance(turned(drawn[8], joint, std::f32::consts::FRAC_PI_4)) < 1e-3, "{:?}", mid[8]); + // The render shows it: the tail now hangs down from x = 200, its old tip area is empty. + assert!(black(&s, 0, 280, 150) && !black(&s, 0, 200, 230)); + assert!(!black(&s, 10, 280, 150) && black(&s, 10, 200, 230)); +} + +#[test] +fn dragging_a_shape_bone_bends_it_by_ik_in_one_undo_step() { + let (mut s, _, b2) = rigged(); + let steps = s.history_len(); + s.begin_gesture("Pose Armature"); + for t in [[290.0, 120.0], [270.0, 90.0], [250.0, 60.0]] { + run(&mut s, "bone.solve", json!({"bone": b2, "x": t[0], "y": t[1]})); + } + s.end_gesture(); + assert_eq!(s.history_len(), steps + 1); + let v = run(&mut s, "bone.info", json!({})); + let tail = &v["armatures"][0]["bones"][1]["tail"]; + let end = Vec2::new(tail[0].as_f64().unwrap() as f32, tail[1].as_f64().unwrap() as f32); + assert!(end.distance(Vec2::new(250.0, 60.0)) < 0.5, "{end:?}"); + // The outline follows the bones; the file holds what shows. + let shown = points(&s, 0); + assert!(shown[8].distance(Vec2::new(250.0, 60.0)) < 11.0, "{:?}", shown[8]); + let k = &s.doc.timeline(0).layers[0].keyframes[0]; + let ElementKind::Shape(sh) = &k.elements[0].kind else { panic!("not a shape") }; + assert_eq!(anicraft_doc::skin::anchors(&sh.path).iter().map(|p| Affine::translate(100.0, 150.0).apply(*p)).collect::>(), shown); + s.undo().unwrap(); + assert_eq!(points(&s, 0), points(&rigged().0, 0), "undo puts the rest pose back"); +} + +#[test] +fn binding_points_by_hand() { + let (mut s, b1, b2) = rigged(); + let tip = 8usize; + // The tip follows only the first bone: bending the second leaves it. + let v = run(&mut s, "bone.bind", json!({"bone": b1, "points": [tip, 9]})); + assert_eq!(v["changed"], 2); + run(&mut s, "bone.pose", json!({"bone": b2, "angle": 90})); + let drawn = points(&tail(), 0); + let now = points(&s, 0); + assert_eq!(now[tip], drawn[tip], "bound to the bone that didn't turn"); + assert_ne!(now[7], drawn[7], "its neighbours bend"); + // Shared: half way between staying and turning. + run(&mut s, "bone.bind", json!({"bone": b2, "points": [tip], "mode": "add"})); + let want = (drawn[tip] + turned(drawn[tip], Vec2::new(200.0, 150.0), std::f32::consts::FRAC_PI_2)) * 0.5; + assert!(points(&s, 0)[tip].distance(want) < 1e-3); + let info = run(&mut s, "bone.info", json!({"points": true})); + let p = &info["armatures"][0]["points"][tip]; + assert_eq!(p["manual"], true); + assert_eq!(p["bones"].as_array().unwrap().len(), 2); + // Removed from both: it stays where it was drawn. + run(&mut s, "bone.bind", json!({"bone": b1, "points": [tip], "mode": "remove"})); + run(&mut s, "bone.bind", json!({"bone": b2, "points": [tip], "mode": "remove"})); + assert_eq!(points(&s, 0)[tip], drawn[tip]); + // Automatic again: it follows the second bone round. + run(&mut s, "bone.bind", json!({"bone": b2, "points": [tip], "mode": "auto"})); + assert!(points(&s, 0)[tip].distance(turned(drawn[tip], Vec2::new(200.0, 150.0), std::f32::consts::FRAC_PI_2)) < 1e-3); + // Each bind is one undo step. + s.undo().unwrap(); + assert_eq!(points(&s, 0)[tip], drawn[tip]); +} + +#[test] +fn shape_bones_refuse_what_cant_be_done() { + let mut s = tail(); + let steps = s.history_len(); + for (p, want) in [ + (json!({"shape": TAIL, "head": [100, 50], "tail": [200, 50]}), "inside"), + (json!({"shape": TAIL, "head": [150, 150], "tail": [150.5, 150]}), "length"), + (json!({"shape": TAIL, "tail": [200, 150]}), "head"), + (json!({"shape": TAIL, "head": [150, 150]}), "tail"), + (json!({"shape": 999, "head": [150, 150], "tail": [200, 150]}), "no shape"), + (json!({"head": [150, 150], "tail": [200, 150]}), "shape"), + (json!({"parent": 999, "tail": [200, 150]}), "no bone"), + ] { + let e = s.execute("bone.add_in_shape", &p).unwrap_err().to_string(); + assert!(e.contains(want), "{p}: {e}"); + } + assert_eq!(s.history_len(), steps, "refusals leave no undo steps"); + let (mut s, b1, _) = rigged(); + for (p, want) in [(json!({"bone": b1, "points": [9999]}), "below"), (json!({"bone": b1, "mode": "glue"}), "mode"), (json!({"bone": b1, "points": "all"}), "points"), (json!({"bone": 4242}), "no bone")] { + let e = s.execute("bone.bind", &p).unwrap_err().to_string(); + assert!(e.contains(want), "{p}: {e}"); + } + // The shape's outline is the armature's: artwork edits are refused on its layer. + s.select_only([ElementId(TAIL)]); + for (id, p) in [("element.translate", json!({"dx": 5, "dy": 0})), ("edit.delete", json!({})), ("draw.rect", json!({"x": 0, "y": 0, "w": 5, "h": 5}))] { + let e = s.execute(id, &p).unwrap_err().to_string(); + assert!(e.contains("armature"), "{id}: {e}"); + } + // Bones of symbol instances bind nothing; instances don't join a shape's armature. + let (mut inst, ib1, _) = crate::tests_bone::rigged(); + assert!(inst.execute("bone.bind", &json!({"bone": ib1})).unwrap_err().to_string().contains("instances")); + assert!(inst.execute("bone.add_in_shape", &json!({"parent": ib1, "tail": [0, 0]})).unwrap_err().to_string().contains("instances")); + let e = inst.execute("bone.add_in_shape", &json!({"shape": crate::tests_bone::ROOT, "head": [150, 100], "tail": [190, 100]})).unwrap_err().to_string(); + assert!(e.contains("shape"), "{e}"); +} + +#[test] +fn merged_drawing_leaves_the_armature_shape_alone() { + let (mut s, _, _) = rigged(); + let drawn = shape_at(&s, 0).1; + let other = s.doc.timeline(0).layers[1].id; + run(&mut s, "layer.select", json!({"layer": other.0})); + run(&mut s, "draw.rect", json!({"x": 150, "y": 100, "w": 60, "h": 100})); + assert_eq!(*shape_at(&s, 0).1, *drawn, "a shape drawn over it on another layer doesn't cut it"); +} + +#[test] +fn removing_shape_bones_rebinds_and_the_last_frees_the_shape_as_it_looks() { + let (mut s, b1, b2) = rigged(); + run(&mut s, "bone.pose", json!({"bone": b1, "angle": 30})); + let v = run(&mut s, "bone.remove", json!({"bone": b2})); + assert_eq!(v["armature_removed"], false); + let tl = s.doc.timeline(0); + assert_eq!(tl.layers.len(), 2, "no layer for freed instances: a shape's bones move none"); + let arm = tl.layers[0].armature.as_ref().unwrap(); + assert!(arm.skin.as_ref().unwrap().points.iter().all(|p| p.bones == vec![anicraft_doc::skin::Influence(anicraft_doc::BoneId(b1), 1.0)]), "every point follows the bone that's left"); + let shown = points(&s, 0); + run(&mut s, "bone.remove", json!({"bone": b1})); + let tl = s.doc.timeline(0); + assert!(tl.layers.iter().all(|l| l.kind != LayerKind::Armature)); + assert_eq!(points(&s, 0), shown, "the shape stays as it looked, now a drawing object"); + s.undo().unwrap(); + s.undo().unwrap(); + assert_eq!(s.doc.timeline(0).layers[0].armature.as_ref().unwrap().bones.len(), 2); +} + +#[test] +fn shape_armatures_survive_a_file_round_trip_and_render_the_same() { + let (mut s, b1, b2) = rigged(); + run(&mut s, "bone.bind", json!({"bone": b1, "points": [3], "mode": "add"})); + run(&mut s, "bone.set_limits", json!({"bone": b2, "min": -100, "max": 100})); + run(&mut s, "bone.pose", json!({"bone": b2, "angle": 90, "frame": 10})); + let text = crate::format::to_json(&s.doc).unwrap(); + let back = crate::format::from_json(&text).unwrap(); + assert_eq!(back, s.doc); + for f in [0, 5, 10] { + assert_eq!(render_frame(&back, f, 1.0).unwrap().data, render_frame(&s.doc, f, 1.0).unwrap().data, "frame {f}"); + } + // The file stores the outline as drawn, so a keyframe's bent outline never drifts. + let skin = back.timeline(0).layers[0].armature.as_ref().unwrap().skin.clone().unwrap(); + assert_eq!(skin.rest.cmds.first(), Some(&PathCmd::MoveTo(Vec2::new(0.0, -10.0)))); + // New ids never collide with the bones' joint nodes. + let mut back = Session::new(back); + let v = run(&mut back, "bone.add_in_shape", json!({"parent": b2, "tail": [200, 280]})); + assert!(v["bone"].as_u64().unwrap() > b2); +} + +#[test] +fn plug_ins_may_rig_shapes() { + for id in ["bone.add_in_shape", "bone.bind"] { + assert!(crate::cmds_plugin::plugin_may_call(id).is_ok(), "{id}"); + } +} From 430ebb04ec064371fc3915b44bdd80ddf4d538da Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Thu, 12 Nov 2026 00:40:12 -0700 Subject: [PATCH 04/18] feat(ui): bones inside shapes with the Bone tool, and the Bind tool (M7) --- ATTRIBUTION.md | 2 +- assets/icons/anicraft-bind.svg | 8 ++ crates/doc/src/skin.rs | 14 +++ crates/engine/src/cmds_bone.rs | 16 +-- docs/guide/reference/commands.md | 8 +- docs/guide/reference/shortcuts.md | 1 + src/a11y.rs | 4 +- src/app.rs | 36 ++++++- src/bind_tool.rs | 155 ++++++++++++++++++++++++++++++ src/bone_tool.rs | 77 ++++++++++++--- src/i18n/tests.rs | 4 +- src/icons.rs | 7 +- src/keymap.rs | 1 + src/main.rs | 1 + src/panels.rs | 21 +++- src/stage.rs | 8 +- 16 files changed, 320 insertions(+), 43 deletions(-) create mode 100644 assets/icons/anicraft-bind.svg create mode 100644 src/bind_tool.rs diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 8d8b43d3..c2d0e8b5 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` (21 files: align, distribute, layer, mask and masked layer, width tool, camera, brush, paint brush, eraser, eyedropper, muted sound, magnet, bone, edit multiple frames) | Align panel, layer-type, Width tool, Camera, Brush, Paint Brush, Eraser, Eyedropper and Bone tool icons, the timeline's mute toggle, Snap to Objects, Edit Multiple Frames | 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` (22 files: align, distribute, layer, mask and masked layer, width tool, camera, brush, paint brush, eraser, eyedropper, muted sound, magnet, bone, bind, edit multiple frames) | Align panel, layer-type, Width tool, Camera, Brush, Paint Brush, Eraser, Eyedropper, Bone and Bind tool icons, the timeline's mute toggle, Snap to Objects, Edit Multiple Frames | 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 | | `assets/icons/*.svg` except `anicraft-*` (33 files: tools, transport, layer toggles, folders, guide, image, text, sound, chevrons) | 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) | ISC (Lucide) and MIT (Feather), [`licenses/icons/LICENSE-lucide.txt`](licenses/icons/LICENSE-lucide.txt) | | `assets/app-icon/` (`anicraft.svg`, `anicraft-small.svg` and every render: PNGs, `anicraft.ico`, `hicolor/`) | App icon (engraved rabbit): window, Dock, taskbar, `anicraft.exe`, Help › About | Project owner (ArtCraft team) | Original artwork drawn in ArtCraft for AniCraft, vectorised by `assets/app-icon/trace.py` and rendered by `scripts/icons.sh` | MIT OR Apache-2.0 ([`assets/app-icon/LICENSE.txt`](assets/app-icon/LICENSE.txt)) | diff --git a/assets/icons/anicraft-bind.svg b/assets/icons/anicraft-bind.svg new file mode 100644 index 00000000..c7842936 --- /dev/null +++ b/assets/icons/anicraft-bind.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/crates/doc/src/skin.rs b/crates/doc/src/skin.rs index d0a46902..6af97ef6 100644 --- a/crates/doc/src/skin.rs +++ b/crates/doc/src/skin.rs @@ -290,6 +290,20 @@ pub fn apply(arm: &Armature, elements: &mut [Arc], pose: &Pose) -> bool true } +/// The points of a shape armature's shape in `elements` (evaluated: posed), in point order, in +/// the layer's space: the anchors of its outline as it shows. +pub fn points_shown(arm: &Armature, elements: &[Arc]) -> Vec { + let Some(skin) = &arm.skin else { return Vec::new() }; + elements + .iter() + .find(|e| e.id == skin.shape) + .and_then(|e| match &e.kind { + ElementKind::Shape(sh) => Some(anchors(&sh.path).into_iter().map(|p| e.transform.apply(p)).collect()), + _ => None, + }) + .unwrap_or_default() +} + /// Repairs a loaded skin against its armature: the rest outline within [`MAX_SKIN_POINTS`] /// anchors (else the skin goes), one binding per anchor, weights of bones that exist, positive /// and summing to 1; unbound automatic anchors are bound. Returns whether anything changed. diff --git a/crates/engine/src/cmds_bone.rs b/crates/engine/src/cmds_bone.rs index 8949d4fa..a88ed77f 100644 --- a/crates/engine/src/cmds_bone.rs +++ b/crates/engine/src/cmds_bone.rs @@ -463,7 +463,7 @@ fn info(s: &mut Session, p: &Value) -> Result { .collect(); let mut out = json!({"layer": l.id.0, "name": l.name, "roots": arm.roots().iter().map(|e| e.0).collect::>(), "poses": poses(l), "bones": bones, "shape": arm.skin_shape().map(|e| e.0)}); if with_points && let Some(k) = &arm.skin { - out["points"] = json!(shape_points(arm, &els).iter().zip(&k.points).map(|(at, b)| json!({"at": pt(*at), "bones": b.bones.iter().map(|i| json!([i.0.0, i.1])).collect::>(), "manual": b.manual})).collect::>()); + out["points"] = json!(skin::points_shown(arm, &els).iter().zip(&k.points).map(|(at, b)| json!({"at": pt(*at), "bones": b.bones.iter().map(|i| json!([i.0.0, i.1])).collect::>(), "manual": b.manual})).collect::>()); } Some(out) }) @@ -471,20 +471,6 @@ fn info(s: &mut Session, p: &Value) -> Result { Ok(json!({"frame": frame, "armatures": list})) } -/// The points of a shape armature's shape as they show (stage px, in point order): the -/// anchors of its posed outline. -pub fn shape_points(arm: &Armature, elements: &[Arc]) -> Vec { - let Some(id) = arm.skin_shape() else { return Vec::new() }; - elements - .iter() - .find(|e| e.id == id) - .and_then(|e| match &e.kind { - ElementKind::Shape(sh) => Some(skin::anchors(&sh.path).into_iter().map(|p| e.transform.apply(p)).collect()), - _ => None, - }) - .unwrap_or_default() -} - fn add_in_shape(s: &mut Session, p: &Value) -> Result { let shape = opt_u64(p, "shape")?.map(ElementId); let parent = opt_u64(p, "parent")?.map(BoneId); diff --git a/docs/guide/reference/commands.md b/docs/guide/reference/commands.md index 1a5d1b38..dece311f 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 258 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 260 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. @@ -287,6 +287,10 @@ These commands have no menu item: the panels, the stage and the timeline use the Parameters: `{depth (px behind the stage, −500…10000; deeper layers move less when the camera pans), layer?}` - **Add Bone** `bone.add` · changes the document Parameters: ``{from (instance id: the bone starts on it), to (instance id: the bone moves it), head?: [x, y] (the joint, stage px; default the end of the bone into `from`, else its registration point), tail?: [x, y] (default `to`'s registration point), name?} → {bone, layer}. Both instances go to an armature layer (made for the first bone)`` +- **Add Bone in Shape** `bone.add_in_shape` · changes the document + Parameters: `{shape? (shape id: the first bone, or another bone from the shape), parent? (bone id: continue the chain from its end), head?: [x, y] (the joint, stage px; default the parent bone's end), tail: [x, y] (stage px), name?} → {bone, layer, created, points}. The first bone moves the shape to an armature layer of its own, as an object (merge drawing leaves it alone); the shape's points are bound to the nearest bones` +- **Bind Points** `bone.bind` · changes the document + Parameters: `{bone, points?: [point index…] (default every point; see bone.info with points), mode?: "only" (the points follow just this bone; default) | "add" (they share it with the bones they follow) | "remove" | "auto" (back to automatic binding)} → {bone, changed, bound (how many points the bone moves)}. A shape armature's binding: which points of the shape follow which bone` - **Remove Bone** `bone.remove` · changes the document Parameters: `{bone} removes it and the bones below it; the instances they moved go to a layer of their own as they look at the playhead (with the last bone, the whole armature does); asks first when the armature has more than one pose` - **Joint Limits** `bone.set_limits` · changes the document @@ -298,7 +302,7 @@ These commands have no menu item: the panels, the stage and the timeline use the - **Drag Bone** `bone.solve` · changes the document 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?} → every armature on the scene at the frame: its bones with joint and end (stage px), joint angle and limits (°), pinned` + 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` - **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 diff --git a/docs/guide/reference/shortcuts.md b/docs/guide/reference/shortcuts.md index d7b87187..6203d1f3 100644 --- a/docs/guide/reference/shortcuts.md +++ b/docs/guide/reference/shortcuts.md @@ -23,6 +23,7 @@ This page is generated from the editor's shortcut map, so it always matches the | Free Transform | Q | Q | | Width | U | U | | Bone | M | M | +| Bind | Shift+M | ⇧M | | Pen | P | P | | Text | T | T | | Pencil | Shift+Y | ⇧Y | diff --git a/src/a11y.rs b/src/a11y.rs index 8f93ffd3..2dc1001c 100644 --- a/src/a11y.rs +++ b/src/a11y.rs @@ -371,10 +371,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::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::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", "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", "brushlibrary", "brushcurve", "paintbrush"] { + 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", "brushlibrary", "brushcurve", "paintbrush"] { found.extend(check(panel, |a, _| a.open_panel(Some(panel)))); } // Test Movie in a window of its own (ADR 0062): its controls, named in that window. diff --git a/src/app.rs b/src/app.rs index 6dccf28e..1250c081 100644 --- a/src/app.rs +++ b/src/app.rs @@ -17,6 +17,7 @@ pub enum Tool { Transform, Width, Bone, + Bind, Pen, Text, Pencil, @@ -67,7 +68,7 @@ impl GapSize { } impl Tool { - pub const ALL: [Tool; 21] = [Tool::Select, Tool::Subselect, Tool::Transform, Tool::Width, Tool::Bone, 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; 22] = [Tool::Select, Tool::Subselect, Tool::Transform, 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 { @@ -76,6 +77,7 @@ impl Tool { Tool::Transform => tr_noop!("Free Transform"), Tool::Width => tr_noop!("Width"), Tool::Bone => tr_noop!("Bone"), + Tool::Bind => tr_noop!("Bind"), Tool::Pen => tr_noop!("Pen"), Tool::Text => tr_noop!("Text"), Tool::Pencil => tr_noop!("Pencil"), @@ -102,6 +104,7 @@ impl Tool { Tool::Transform => Some("Q"), Tool::Width => Some("U"), Tool::Bone => Some("M"), + Tool::Bind => Some("Shift+M"), Tool::Pen => Some("P"), Tool::Text => Some("T"), Tool::Pencil => Some("Shift+Y"), @@ -132,7 +135,8 @@ impl Tool { Tool::PaintBrush => tr_noop!("Drag to draw a line in the stroke colour whose width follows the pen's pressure and the brush's tapers. Shape it afterwards with the Width tool. [ and ] change the size; the options set the brush and its pressure curve."), Tool::Eraser => tr_noop!("Drag to erase lines and fills drawn with Object Drawing off (drawing objects and symbols are kept). [ and ] change the size; the options set the shape and erase mode, and the Faucet deletes a whole fill or line with a click. Double-click the tool to erase everything on the stage."), 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); 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::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::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."), @@ -233,8 +237,11 @@ pub enum Drag { CameraPan { last: egui::Pos2 }, CameraRotate { last: f32 }, CameraWheel { until: f64 }, - /// Bone tool (ADR 0043): drawing a bone from instance `from`, joint `head` to `cur` (stage). + /// Bone tool (ADR 0043): drawing a bone from instance `from` (or inside shape `from`, or on + /// from a shape bone's joint node, ADR 0071), joint `head` to `cur` (stage). Bone { from: anicraft_engine::doc::ElementId, head: egui::Pos2, cur: egui::Pos2 }, + /// Bind tool (ADR 0071): a box from `start` to `cur` (stage) binding the points inside it. + BindMarquee { start: egui::Pos2, cur: egui::Pos2 }, /// Posing by inverse kinematics: point `local` of the bone's instance follows the pointer. BonePose { bone: anicraft_engine::doc::BoneId, local: egui::Pos2 }, /// Moving a whole armature by its root, from stage point `last` last frame. @@ -1713,6 +1720,29 @@ impl App { self.bone_sel = Some(anicraft_engine::doc::BoneId(b2)); self.tool = Tool::Select; } + Some("shapebones") => { + // A tail with bones inside it (ADR 0071): four bones, curled at frame 1 and the + // other way at frame 24, the second bone picked with the Bind tool in hand. + self.run("layer.new", json!({"name": "Tail"})); + let d = "M220 260 C300 252 420 250 540 262 C660 274 760 280 860 296 C872 300 872 306 860 308 C760 318 660 318 540 316 C420 314 300 334 220 340 C200 340 200 260 220 260 Z"; + let id = |v: Option, k: &str| v.and_then(|v| v[k].as_u64()).unwrap_or(0); + let shape = id(self.run("draw.path", json!({"d": d, "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 bone = id(self.run("bone.add_in_shape", json!({"shape": shape, "head": [220, 300], "tail": [380, 296]})), "bone"); + let mut bones = vec![bone]; + for x in [540, 700, 850] { + bone = id(self.run("bone.add_in_shape", json!({"parent": bone, "tail": [x, 298]})), "bone"); + bones.push(bone); + } + for (b, (a, z)) in bones.iter().zip([(-4, 3), (-12, 10), (-16, 14), (-20, 18)]) { + self.run("bone.pose", json!({"bone": b, "angle": a, "frame": 0})); + self.run("bone.pose", json!({"bone": b, "angle": z, "frame": 23})); + } + self.run("timeline.goto", json!({"frame": 0})); + self.bone_sel = bones.get(1).copied().map(anicraft_engine::doc::BoneId); + self.tool = Tool::Bind; + } Some("tlwide") => { // Zoomed in: wide frames, playhead on frame 1 and frame 4. self.tl_cell_w = 48.0; diff --git a/src/bind_tool.rs b/src/bind_tool.rs new file mode 100644 index 00000000..80dc5215 --- /dev/null +++ b/src/bind_tool.rs @@ -0,0 +1,155 @@ +//! The Bind tool (ADR 0071): which points of a shape follow which of its bones. +//! +//! With the tool in hand, every shape armature on the stage shows its points: a square for a +//! point that follows one bone, a triangle for one that several bones share (as in Animate). +//! Click a bone to pick it: the points it moves fill in the selection colour. Then a click on a +//! point makes it follow only that bone, Shift-click shares it with the bones it follows, +//! Ctrl-click (⌘ on macOS) takes it from the bone, and a box dragged on empty stage does the +//! same to every point inside it. Each is one `bone.bind`, one undo step. + +use crate::app::{App, Drag}; +use crate::bone_tool; +use crate::pathtools::Xf; +use crate::theme::{T, to_color32}; +use anicraft_engine::doc::skin::points_shown; +use anicraft_engine::doc::{BoneId, LayerId, LayerKind, evaluate_layer_elements}; +use anicraft_engine::geom::Vec2; +use egui::{Color32, Pos2, Rect, Stroke, StrokeKind, pos2, vec2}; +use serde_json::json; + +/// How close (screen points) a click must be to a point to bind it, and the size points draw. +const GRAB: f32 = 6.0; +const SIZE: f32 = 3.5; + +/// One shape armature's points as the stage shows them at the playhead. +struct Points { + layer: LayerId, + color: Color32, + locked: bool, + /// Stage position, the bones it follows. + points: Vec<(Vec2, Vec)>, +} + +fn shown(app: &App) -> Vec { + let tl = app.s.timeline(); + tl.layers + .iter() + .enumerate() + .filter(|(i, l)| l.kind == LayerKind::Armature && l.visible && !tl.hidden_by_folder(*i)) + .filter_map(|(_, l)| { + let arm = l.armature.as_deref()?; + let skin = arm.skin.as_ref()?; + let (_, els) = evaluate_layer_elements(l, app.s.frame)?; + let at = points_shown(arm, &els); + let points = at.into_iter().zip(&skin.points).map(|(p, b)| (p, b.bones.iter().map(|i| i.0).collect())).collect(); + Some(Points { layer: l.id, color: to_color32(l.color), locked: l.locked || tl.locked_by_folder(l.id), points }) + }) + .collect() +} + +/// What a press with `command` and `shift` held does to the points: Ctrl/⌘ takes them from the +/// bone, Shift shares it, otherwise they follow only it. +fn mode(shift: bool, command: bool) -> &'static str { + if command { + "remove" + } else if shift { + "add" + } else { + "only" + } +} + +/// The picked bone, when it is inside a shape on layer `layer`. +fn picked_in(app: &App, layer: LayerId) -> Option { + let id = app.bone_sel?; + app.s.timeline().layer(layer)?.armature.as_ref().filter(|a| a.skin.is_some() && a.bone(id).is_some()).map(|_| id) +} + +fn bind(app: &mut App, bone: BoneId, points: Vec, shift: bool, command: bool) { + let n = points.len(); + let m = mode(shift, command); + if let Some(v) = app.run("bone.bind", json!({"bone": bone.0, "points": points, "mode": m})) { + let bound = v["bound"].as_u64().unwrap_or(0); + let msg = match m { + "remove" => trn!("Took {n} point from the bone; it follows {bound} points.", "Took {n} points from the bone; it follows {bound} points.", n, bound = bound), + "add" => trn!("{n} point now shares the bone; it moves {bound} points.", "{n} points now share the bone; it moves {bound} points.", n, bound = bound), + _ => trn!("{n} point now follows only this bone; it moves {bound} points.", "{n} points now follow only this bone; it moves {bound} points.", n, bound = bound), + }; + app.status_ok(msg); + } +} + +/// A Bind tool click at screen point `p`: picks the bone there, or binds the point there to the +/// picked bone. +pub fn click(app: &mut App, xf: Xf, p: Pos2, shift: bool, command: bool) { + if let Some((layer, id, _)) = bone_tool::hit(app, xf, p) { + bone_tool::select(app, layer, Some(id)); + return; + } + for s in shown(app).into_iter().rev().filter(|s| !s.locked) { + let Some(i) = s.points.iter().position(|(at, _)| xf.to_screen(*at).distance(p) <= GRAB) else { continue }; + match picked_in(app, s.layer) { + Some(bone) => bind(app, bone, vec![i], shift, command), + None => app.status_ok(tr!("Pick a bone of this shape first (click it), then click the points it should move.")), + } + return; + } + app.bone_sel = None; +} + +/// A Bind tool drag from screen point `press`: a box that binds the points inside it (a drag +/// that starts on a bone or a point does nothing more than a click). +pub fn drag_start(app: &mut App, xf: Xf, press: Pos2) -> Drag { + let sp = xf.to_stage(press); + if app.bone_sel.is_none() { + app.status_ok(tr!("Pick a bone of a shape first (click it), then drag a box around the points it should move.")); + return Drag::None; + } + Drag::BindMarquee { start: pos2(sp.x, sp.y), cur: pos2(sp.x, sp.y) } +} + +/// Ends a box drag: binds every point inside it (on the picked bone's shape) to the bone. +pub fn drag_end(app: &mut App, start: Pos2, cur: Pos2, shift: bool, command: bool) { + let r = Rect::from_two_pos(start, cur); + for s in shown(app).into_iter().filter(|s| !s.locked) { + let Some(bone) = picked_in(app, s.layer) else { continue }; + let inside: Vec = s.points.iter().enumerate().filter(|(_, (at, _))| r.contains(pos2(at.x, at.y))).map(|(i, _)| i).collect(); + if inside.is_empty() { + app.status_ok(tr!("No points of the bone's shape inside the box.")); + } else { + bind(app, bone, inside, shift, command); + } + return; + } +} + +/// Every shape armature's points (with the Bind tool in hand), and the box being dragged. +pub fn draw(app: &App, painter: &egui::Painter, xf: Xf) { + if app.tool != crate::app::Tool::Bind { + return; + } + for s in shown(app) { + let picked = picked_in(app, s.layer); + let fade = |c: Color32| if s.locked { c.gamma_multiply(0.5) } else { c }; + for (at, bones) in &s.points { + let c = xf.to_screen(*at); + let mine = picked.is_some_and(|b| bones.contains(&b)); + let edge = Stroke::new(1.0, fade(if mine { T.selection } else { s.color })); + let fill = fade(if mine { T.selection } else { Color32::WHITE }); + if bones.len() > 1 { + // Shared by several bones: a triangle. + let pts = vec![c + vec2(0.0, -SIZE * 1.2), c + vec2(SIZE * 1.1, SIZE * 0.8), c + vec2(-SIZE * 1.1, SIZE * 0.8)]; + painter.add(egui::Shape::convex_polygon(pts, fill, edge)); + } else { + let r = Rect::from_center_size(c, vec2(SIZE * 2.0, SIZE * 2.0)); + painter.rect_filled(r, 0.0, fill); + painter.rect_stroke(r, 0.0, edge, StrokeKind::Middle); + } + } + } + if let Drag::BindMarquee { start, cur } = app.drag { + let r = Rect::from_two_pos(xf.to_screen(Vec2::new(start.x, start.y)), xf.to_screen(Vec2::new(cur.x, cur.y))); + painter.rect_filled(r, 0.0, T.selection.gamma_multiply(0.12)); + painter.rect_stroke(r, 0.0, Stroke::new(1.0, T.selection), StrokeKind::Middle); + } +} diff --git a/src/bone_tool.rs b/src/bone_tool.rs index d9a59e03..c1ba60b0 100644 --- a/src/bone_tool.rs +++ b/src/bone_tool.rs @@ -1,18 +1,20 @@ -//! The Bone tool and armatures on the stage (ADR 0043). +//! The Bone tool and armatures on the stage (ADR 0043, ADR 0071). //! //! Bones show over the artwork of every visible armature layer as wedges, wide at the round //! joint they turn about and narrowing to a smaller round end, in the layer's colour; the //! selected bone in the selection colour. With the **Bone tool** a drag from one symbol -//! instance to another adds a bone (a drag starting on a bone's end continues the chain from -//! it), and a click picks a bone. With the **Selection tool** a drag on a bone, or on an +//! instance to another adds a bone; a drag inside a shape draws a bone inside it (the shape +//! bends with it: a shape armature); a drag starting on a bone's end continues the chain from +//! it, and a click picks a bone. With the **Selection tool** a drag on a bone, or on an //! instance a bone moves, poses the armature by inverse kinematics; a drag on the root instance -//! moves the whole armature. Each drag is one undo step, and the pose keys the frame. +//! (or a shape armature's shape) moves the whole armature. Each drag is one undo step, and the +//! pose keys the frame. use crate::app::{App, Drag, Tool}; use crate::pathtools::Xf; use crate::theme::{T, to_color32}; use anicraft_engine::doc::armature::{self, BoneAt}; -use anicraft_engine::doc::{BoneId, ElementId, ElementKind, LayerId, LayerKind, evaluate_layer_elements}; +use anicraft_engine::doc::{BoneId, Element, ElementId, ElementKind, Layer, LayerId, LayerKind, evaluate_layer_elements}; use anicraft_engine::geom::Vec2; use egui::{Color32, Key, Modifiers, Pos2, Stroke, pos2}; use serde_json::json; @@ -84,6 +86,22 @@ fn segment_distance(p: Pos2, a: Pos2, b: Pos2) -> f32 { /// The topmost symbol instance under stage point `sp` other than `skip`, on an unlocked layer: /// its layer and id. fn instance_at(app: &App, sp: Vec2, slop: f32, skip: Option) -> Option<(LayerId, ElementId)> { + item_at(app, sp, slop, skip, |_, e| matches!(e.kind, ElementKind::Symbol { .. })) +} + +/// What a Bone tool press can start a bone on: an instance, a shape on a normal layer, or a +/// shape armature's shape. +fn rig_target(l: &Layer, e: &Element) -> bool { + match e.kind { + ElementKind::Symbol { .. } => true, + ElementKind::Shape(_) => l.kind == LayerKind::Normal || l.armature.as_ref().and_then(|a| a.skin_shape()) == Some(e.id), + _ => false, + } +} + +/// The topmost item under stage point `sp` other than `skip`, on an unlocked layer, that `want` +/// accepts: its layer and id. +fn item_at(app: &App, sp: Vec2, slop: f32, skip: Option, want: impl Fn(&Layer, &Element) -> bool) -> Option<(LayerId, ElementId)> { let dl = app.s.display_list(); let tl = app.s.timeline(); for item in dl.items.iter().rev() { @@ -99,8 +117,8 @@ fn instance_at(app: &App, sp: Vec2, slop: f32, skip: Option) -> Optio if !(inside || item.path.distance_to_edge(sp, &item.transform) <= hw + slop) { continue; } - let is_instance = evaluate_layer_elements(layer, app.s.frame).is_some_and(|(_, els)| els.iter().any(|e| e.id == item.element && matches!(e.kind, ElementKind::Symbol { .. }))); - if is_instance { + let wanted = evaluate_layer_elements(layer, app.s.frame).is_some_and(|(_, els)| els.iter().any(|e| e.id == item.element && want(layer, e))); + if wanted { return Some((layer.id, item.element)); } } @@ -127,18 +145,51 @@ pub fn drag_start(app: &mut App, xf: Xf, press: Pos2) -> Drag { let head = pos2(b.tail.x, b.tail.y); return Drag::Bone { from: child, head, cur: head }; } - match instance_at(app, sp, 3.0 / xf.zoom.max(1e-3), None) { + match item_at(app, sp, 3.0 / xf.zoom.max(1e-3), None, rig_target) { Some((_, from)) => Drag::Bone { from, head: pos2(sp.x, sp.y), cur: pos2(sp.x, sp.y) }, None => { - app.status_ok(tr!("Start a bone on a symbol instance (convert artwork with F8), then drag to the instance it moves.")); + app.status_ok(tr!("Start a bone inside a shape, or on a symbol instance and drag to the instance it moves.")); Drag::None } } } -/// Ends a Bone tool drag: adds the bone if it ends on another instance. +/// What a bone drawn from `from` goes into: a shape armature's bone it continues, or a shape. +enum InShape { + Parent(BoneId), + Shape(ElementId), +} + +fn in_shape(app: &App, from: ElementId) -> Option { + let tl = app.s.timeline(); + for l in tl.layers.iter().filter(|l| l.kind == LayerKind::Armature) { + let Some(a) = l.armature.as_deref().filter(|a| a.skin.is_some()) else { continue }; + if let Some(b) = a.bone_into(from) { + return Some(InShape::Parent(b.id)); + } + } + tl.layers.iter().find_map(|l| { + let (_, els) = evaluate_layer_elements(l, app.s.frame)?; + els.iter().find(|e| e.id == from && matches!(e.kind, ElementKind::Shape(_))).map(|_| InShape::Shape(from)) + }) +} + +/// Ends a Bone tool drag: adds the bone if it ends on another instance, or inside a shape +/// where it was released. pub fn drag_end(app: &mut App, xf: Xf, from: ElementId, head: Pos2, cur: Pos2) { let tail = Vec2::new(cur.x, cur.y); + if let Some(target) = in_shape(app, from) { + let p = match target { + InShape::Parent(b) => json!({"parent": b.0, "tail": [tail.x, tail.y]}), + InShape::Shape(id) => json!({"shape": id.0, "head": [head.x, head.y], "tail": [tail.x, tail.y]}), + }; + if let Some(v) = app.run("bone.add_in_shape", p) { + let (layer, bone) = (LayerId(v["layer"].as_u64().unwrap_or(0)), v["bone"].as_u64().map(BoneId)); + select(app, layer, bone); + app.status_ok(tr!("Added a bone inside the shape; its points follow the nearest bones. Drag a bone with the Selection tool to bend it, or adjust the points with the Bind tool. {undo} to undo.", undo = app.undo_key())); + } + return; + } let Some((_, to)) = instance_at(app, tail, 3.0 / xf.zoom.max(1e-3), Some(from)) else { app.status_ok(tr!("A bone ends on another symbol instance: release over the instance it should move.")); return; @@ -167,7 +218,7 @@ pub fn select_drag_start(app: &mut App, xf: Xf, press: Pos2) -> Option { let (layer, bone, local) = match hit(app, xf, press) { Some((layer, id, _)) => (layer, Some(id), None), None => { - let (layer, el) = instance_at(app, sp, 3.0 / xf.zoom.max(1e-3), None).filter(|(l, _)| tl.layer(*l).is_some_and(|l| l.kind == LayerKind::Armature))?; + let (layer, el) = item_at(app, sp, 3.0 / xf.zoom.max(1e-3), None, rig_target).filter(|(l, _)| tl.layer(*l).is_some_and(|l| l.kind == LayerKind::Armature))?; let l = tl.layer(layer)?; let into = l.armature.as_ref().and_then(|a| a.bone_into(el)).map(|b| b.id); // The point grabbed, in the instance's own space: it follows the pointer. @@ -217,7 +268,7 @@ pub fn drag_to(app: &mut App, drag: &mut Drag, c: Pos2) { /// Delete removes the selected bone (and those below it); Esc deselects it. pub fn consume_keys(app: &mut App, ctx: &egui::Context) { let Some(id) = app.bone_sel else { return }; - if !matches!(app.tool, Tool::Bone | Tool::Select) { + if !matches!(app.tool, Tool::Bone | Tool::Bind | Tool::Select) { return; } let take = |k: Key| ctx.input_mut(|i| i.consume_key(Modifiers::NONE, k)); @@ -240,7 +291,7 @@ pub fn upkeep(app: &mut App) { /// The bones of every visible armature, and the bone being drawn. pub fn draw(app: &App, painter: &egui::Painter, xf: Xf) { - let tool = matches!(app.tool, Tool::Bone | Tool::Select); + let tool = matches!(app.tool, Tool::Bone | Tool::Bind | Tool::Select); for s in shown(app) { for b in &s.bones { let picked = app.bone_sel == Some(b.id); diff --git a/src/i18n/tests.rs b/src/i18n/tests.rs index e08e5f9d..2e952094 100644 --- a/src/i18n/tests.rs +++ b/src/i18n/tests.rs @@ -594,7 +594,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", "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", "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). @@ -756,7 +756,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] { + 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] { 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 6fb8ff40..00315214 100644 --- a/src/icons.rs +++ b/src/icons.rs @@ -68,13 +68,15 @@ pub enum Icon { Camera, Magnet, Bone, + Bind, EditMultiple, Layer, } impl Icon { #[cfg(test)] - pub const ALL: [Icon; 56] = [ + pub const ALL: [Icon; 57] = [ + Icon::Bind, Icon::Layer, Icon::EditMultiple, Icon::Bone, @@ -209,6 +211,8 @@ impl Icon { Icon::Magnet => ("anicraft-magnet", false), // A bone: a wedge from its joint to its end (AniCraft original, on Lucide's grid). 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), // 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), @@ -271,6 +275,7 @@ static FILES: &[(&str, &str)] = &[ ("anicraft-layer", include_str!("../assets/icons/anicraft-layer.svg")), ("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-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 a3b99f90..8822c139 100644 --- a/src/keymap.rs +++ b/src/keymap.rs @@ -64,6 +64,7 @@ pub fn tool_id(t: Tool) -> &'static str { Tool::Eyedropper => "tool.eyedropper", Tool::Camera => "tool.camera", Tool::Bone => "tool.bone", + Tool::Bind => "tool.bind", Tool::Hand => "tool.hand", Tool::Zoom => "tool.zoom", } diff --git a/src/main.rs b/src/main.rs index 594d1051..bd722c1c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -31,6 +31,7 @@ mod envelope; mod find_panel; mod publish_panel; mod erasertool; +mod bind_tool; mod bone_tool; mod camera_tool; mod convert_symbol; diff --git a/src/panels.rs b/src/panels.rs index c7a79b2d..612e2395 100644 --- a/src/panels.rs +++ b/src/panels.rs @@ -32,6 +32,7 @@ fn tool_icon(tool: Tool) -> Icon { Tool::Eyedropper => Icon::Eyedropper, Tool::Camera => Icon::Camera, Tool::Bone => Icon::Bone, + Tool::Bind => Icon::Bind, Tool::Hand => Icon::Hand, Tool::Zoom => Icon::Zoom, } @@ -1491,12 +1492,28 @@ fn bone_props(app: &mut App, ui: &mut egui::Ui, id: anicraft_engine::doc::BoneId } }); } + // A bone inside a shape (ADR 0071): how many of the shape's points it moves. + let skin = layer.armature.as_ref().and_then(|a| a.skin.as_ref()).map(|k| (k.points.iter().filter(|p| p.weight(id) > 0.0).count(), k.points.len())); + if let Some((mine, total)) = skin { + row(ui, tr!("Points"), |ui| { + ui.label(text(Type::Data, format!("{mine} / {total}"))).on_hover_text(tr!("How many of the shape's points this bone moves. Adjust them with the Bind tool")); + }); + } ui.horizontal_wrapped(|ui| { - if ui.button(tr!("Remove Bone")).named(tr!("Remove bone")).on_hover_text(tr!("Removes the bone and the bones below it; their instances stay where they are, on a layer of their own")).clicked() { + if skin.is_some() { + if ui.button(tr!("Bind Tool")).named(tr!("Bind tool")).on_hover_text(tr!("Choose which points of the shape follow this bone")).clicked() { + app.tool = crate::app::Tool::Bind; + } + if ui.button(tr!("Rebind All")).named(tr!("Rebind all points")).on_hover_text(tr!("Binds every point of the shape to its nearest bones again, dropping changes made with the Bind tool")).clicked() { + app.run("bone.bind", json!({"bone": id.0, "mode": "auto"})); + } + } + let hint = if skin.is_some() { tr!("Removes the bone and the bones below it; the shape's points follow the bones that are left") } else { tr!("Removes the bone and the bones below it; their instances stay where they are, on a layer of their own") }; + if ui.button(tr!("Remove Bone")).named(tr!("Remove bone")).on_hover_text(hint).clicked() { app.request("bone.remove", json!({"bone": id.0})); } }); - ui.label(text(Type::Caption, tr!("Drag bones or instances with the Selection tool to pose; a pose at another frame keys it, and poses tween."))); + ui.label(text(Type::Caption, if skin.is_some() { tr!("Drag bones with the Selection tool to bend the shape; a pose at another frame keys it, and poses tween.") } else { tr!("Drag bones or instances with the Selection tool to pose; a pose at another frame keys it, and poses tween.") })); } fn document_props(app: &mut App, ui: &mut egui::Ui) { diff --git a/src/stage.rs b/src/stage.rs index 405dc44f..8406102c 100644 --- a/src/stage.rs +++ b/src/stage.rs @@ -340,7 +340,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 => 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 => CursorIcon::Crosshair, Tool::Text => CursorIcon::Text, Tool::Zoom => { if alt { @@ -444,6 +444,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::Width => crate::widthtool::drag_start(app, press, xf), Tool::Pencil => { app.pencil = vec![to_v(sp)]; @@ -581,7 +582,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { crate::pathtools::move_points(app, Vec2::new(d.x, d.y), !alt); } } - (Drag::PointMarquee { cur: m, .. }, Some(c)) => *m = c, + (Drag::PointMarquee { cur: m, .. } | Drag::BindMarquee { cur: m, .. }, Some(c)) => *m = c, (d @ Drag::Width { .. }, Some(c)) => { let d = *d; crate::widthtool::drag_to(app, d, to_v(c), alt, zoom); @@ -615,6 +616,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { Drag::Width { .. } => crate::widthtool::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), Drag::Pencil => crate::pathtools::commit_pencil(app, xf), Drag::Brush => crate::brushtool::commit(app, xf), Drag::Eraser => crate::erasertool::commit(app, xf), @@ -676,6 +678,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::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)), @@ -965,6 +968,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); let sel_stroke = Stroke::new(1.0, T.selection); let raw = raw_ids(app); if app.tool == Tool::Select && app.drag == Drag::None From 415429c70ddbf1b2724fefe73fda92c0e15e4bf4 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Thu, 12 Nov 2026 00:41:55 -0700 Subject: [PATCH 05/18] docs: ADR 0071 shape armatures, guide, roadmap and changelog (M7) --- ATTRIBUTION.md | 1 + CHANGELOG.md | 10 ++ docs/adr/0043-bones-and-inverse-kinematics.md | 8 +- docs/adr/0071-shape-armatures.md | 113 ++++++++++++++++++ docs/adr/README.md | 1 - docs/guide/coming-from-animate.md | 5 +- docs/guide/masks-guides-camera-bones.md | 35 +++++- docs/roadmap.md | 6 +- 8 files changed, 168 insertions(+), 11 deletions(-) create mode 100644 docs/adr/0071-shape-armatures.md diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index c2d0e8b5..276bcd28 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -123,6 +123,7 @@ 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). | +| 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). | | 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 830479e0..8c19a8b3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,16 @@ ## Unreleased +* **Bones inside shapes** (ADR 0071, M7). + * The **Bone** tool now also draws bones inside a shape, so the shape itself bends like a tail + or a tentacle. Its points follow the nearest bones, and the bend stays smooth through the + joints. Lines keep their width, and the shape as drawn comes back exactly at rest. + * Pose by dragging bones with the Selection tool. Poses key per frame and tween with easing, + as symbol armatures do, and every export, Test Movie and the stage show the bend. + * The new **Bind** tool (**Shift+M**) shows which points follow which bone, and changes it by + click, Shift-click, Ctrl-click or a box. **Properties › Bone** counts the bone's points and + has **Rebind All**. + * Headless: `bone.add_in_shape`, `bone.bind`, and `bone.info` with `points`. * **CI on macOS and Windows** (ADR 0067, M8). Every pull request that changes code now builds, tests and lints the workspace on macOS (arm64) and Windows (x64) runners as well as Linux, so macOS-only and Windows-only code is checked before it merges. Documentation-only changes skip diff --git a/docs/adr/0043-bones-and-inverse-kinematics.md b/docs/adr/0043-bones-and-inverse-kinematics.md index 105f51ce..c5e9371a 100644 --- a/docs/adr/0043-bones-and-inverse-kinematics.md +++ b/docs/adr/0043-bones-and-inverse-kinematics.md @@ -91,8 +91,10 @@ list, and every edit is a command. ## Not yet -* Shape armatures (bones inside a shape, with binding of its points), spring and damping, - joint translation (Animate's X/Y joint constraints), Animate's runtime armatures (poses that - ActionScript drives), the Bind tool, and XFL import of armature layers. +* ~~Shape armatures (bones inside a shape, with binding of its points) and the Bind tool~~: + ADR 0071. Their bones join joint nodes inside the shape and reuse this ADR's poses, forward + kinematics and CCD solver unchanged. +* Spring and damping, joint translation (Animate's X/Y joint constraints), Animate's runtime + armatures (poses that ActionScript drives), and XFL import of armature layers. * Editing instance properties of armature members in place; armature layers under masks and motion guides; an IK drag that keeps pinned bones *below* the dragged one in place. diff --git a/docs/adr/0071-shape-armatures.md b/docs/adr/0071-shape-armatures.md new file mode 100644 index 00000000..cace49a3 --- /dev/null +++ b/docs/adr/0071-shape-armatures.md @@ -0,0 +1,113 @@ +# ADR 0071: Shape armatures (bones inside a shape) and the Bind tool + +* Status: accepted (2026-11-12) +* Relates to: roadmap M7 (Bone/IK tool), ADR 0043 (symbol-instance armatures, which this + extends), ADR 0031 (merge drawing), ADR 0004 (destructive actions), ADR 0003 (file format) + +## Context + +ADR 0043 joins symbol instances with bones. Animate can also draw bones inside one raw shape, +so the outline bends like a tail, a limb or a strand of hair. Its points follow the bones +automatically, and its Bind tool changes which points follow which bone. Behaviour was learned +from Adobe's public help pages and from watching the program; no code was copied. The questions +are how to model the bones, the binding and the bent outline without a second IK solver, while +keeping `evaluate` pure and drawing the same shape everywhere. + +## Decision + +1. **Same armature, different nodes.** A shape armature is an ordinary `Armature` (ADR 0043) + on an armature layer, with `Armature.skin: Option` (`#[serde(default, + skip_serializing_if)]`, so files without it read and write exactly as before). Its bones join + **joint nodes**, not instances. The root bones start on the shape's own element id, and + every other bone starts on the node of the bone it hangs from. The node ids come from the + document's id counter and are counted on load, so they never collide with new ids. Every + node's rest frame is the shape's local space (`rest` is the identity), so a bone's head and + tail are points of the shape as drawn. Forward kinematics (`armature::place`), inverse + kinematics (`armature::solve`, CCD with limits and pins), poses keyed per frame, tweens + with easing and every `bone.*` command are ADR 0043's, unchanged. `place` now also places + nodes that are no element, and `bones_at` uses it to draw them. +2. **The skin.** `Skin { shape, rest, points }` keeps the outline as drawn (`rest`, the shape's + space) and one `Binding` per **anchor** of it (every `MoveTo`/`LineTo`/`QuadTo`/`CubicTo` + end, in path order): up to four `[bone, weight]` pairs summing to 1, plus a `manual` flag. + Weights live on the armature, not on keyframes: one binding serves every pose. Artwork + commands are refused on armature layers (ADR 0043), so the outline, and therefore the point + indices, never change under the binding. +3. **Automatic binding** (as Animate does): each bone weighs `1 / max(d, 0.5 px)⁴`, where `d` + is the anchor's distance to the bone's segment at rest. The strongest four are kept, + anything under 1 % is dropped, and the rest are normalised. A point near one bone follows + it alone, and a point near a joint is shared by the bones that meet there. The fourth power + was chosen over the inverse square so that a long bone's middle doesn't drift with distant + bones. Adding or removing a bone rebinds every point not bound by hand. A hand-bound point + keeps its binding (bones that go away leave it, and one left with none goes back to + automatic). A point unbound by hand on purpose stays where it was drawn. +4. **The bent outline is linear blend skinning** (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). Each bone's skinning matrix is its node's transform under the pose (the + identity at rest). Each anchor moves by the weighted sum of its bones' matrices. Each cubic + handle moves with the anchor it leaves or enters, and a quadratic's control point with the + mean of its two ends, so curves stay smooth through a bend and the path keeps its commands. + **At rest the outline is the drawing bit for bit**: the rest pose returns the very `Arc` of + the drawn path, and a point whose bones didn't turn is left untouched rather than recomputed. + The shape's transform is untouched, and strokes are drawn after the outline, so **strokes + keep their width** (width profiles keep their place along the path). Dual-quaternion + skinning avoids LBS's thinning at sharp bends, but for 2D rotations about joints the blend + of two rotations about nearby centres differs little, and LBS is what a 2D animator expects. + It is the place to start if collapse at sharp bends becomes a problem. +5. **Pure evaluation, every output.** `armature::apply` (behind `evaluate_guided`, so + `evaluate`, the player, the HTML exporter, every raster and vector export, onion skins, Test + Movie and the GPU stage) replaces the shape's path with the outline bent by the pose at the + frame, tweened between pose keyframes. Commands also write the bent outline into each + keyframe's element, as ADR 0043 does with transforms, so the file holds what shows. It is + always recomputed from `rest`, so poses never accumulate drift. Measured (release, this + machine): binding 2,000 anchors to 16 bones takes 0.83 ms, and bending them takes 0.042 ms + per frame. +6. **Merge drawing treats an armature's shape as an object.** The first bone moves the shape + (raw or a drawing object) to a new armature layer of its own with `merge` off. Shapes drawn + on other layers never cut it, and removing the last bone gives it back as a drawing object, + bent as it looked at the playhead. +7. **Commands** (in the `bone.*` namespace plug-ins may already call): + `bone.add_in_shape {shape | parent, head?, tail, name?}`. The first bone needs `head` + inside the shape (on its fill or its line). With `parent` the joint defaults to that bone's + end. Points given at a posed frame are mapped back through the parent node to the shape as + drawn, and a new bone is at rest (angle 0) in every pose. Shapes are limited to 20,000 + points, with a message pointing to Optimize. Then + `bone.bind {bone, points?, mode: only | add | remove | auto}`: `only` makes the points + follow just that bone, `add` gives the bone an equal share alongside the bones they already + follow, `remove` takes the bone away (renormalising), and `auto` rebinds them automatically. + Each is one undo step. `bone.info` reports the armature's `shape`, how many points each bone + moves, and with `points: true` every point on the stage with its bones. `bone.remove` on a + shape armature rebinds the remaining points. It makes no layer for freed instances, because + there are none, and it still asks first when the armature has more than one pose. + `bone.pose`'s `dx/dy` moves the shape, which is the root. +8. **The shell.** The **Bone tool** draws a bone inside a shape by dragging from inside it + (from a bone's end it continues the chain; releasing anywhere sets the end). The + **Selection tool** bends the shape by dragging its bones and moves it by dragging the + shape. The new **Bind tool** (Shift+M, next to the Bone tool) shows every point of shapes + with bones: a square for a point that follows one bone, a triangle for one shared by + several (Animate's convention). Clicking a bone picks it and fills the points it moves in + the selection colour. Clicking a point makes it follow only that bone, Shift-click shares + the bone, Ctrl-click (⌘ on macOS) takes the bone away, and a box drag does the same to + every point inside it. Properties › Bone shows how many points the bone moves, plus **Bind + Tool** and **Rebind All** buttons. Rebind All is undoable, so it follows ADR 0004's + routine tier and doesn't ask. + +## Consequences + +* No renderer, exporter or the GPU stage changed: the bent outline is just a path in the + display list. Hit testing, onion skins and selection outlines follow it. +* Files without shape armatures are written exactly as before. An older AniCraft reading a + newer file ignores `skin` (an unknown field). It shows each keyframe's bent outline (the file + holds what shows), and its bones draw but move nothing, so the file still opens. +* A skin whose shape is a bone's node, or whose outline is over the point limit, is dropped on + load. Bones of a shape armature that don't hang from the shape are dropped. Weights of + missing bones, non-finite or non-positive weights and repeats go, and the rest renormalise. + +## Not yet + +* Instances and shapes in one armature; more than one shape per armature; reshaping the + outline after binding (Animate allows Subselection edits on the rest pose). +* Dragging points onto a bone with the Bind tool (only clicks and boxes for now), painting + weights, and a falloff setting. +* Dual-quaternion or other volume-keeping skinning, spring, joint translation, runtime + armatures, XFL import of shape armatures (`` on a shape). diff --git a/docs/adr/README.md b/docs/adr/README.md index 322068dc..8a35fed1 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,4 +23,3 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | -| 0071 | m7/shape-armatures | Shape armatures (bones inside a shape) | diff --git a/docs/guide/coming-from-animate.md b/docs/guide/coming-from-animate.md index 75206b82..ab24edcc 100644 --- a/docs/guide/coming-from-animate.md +++ b/docs/guide/coming-from-animate.md @@ -45,7 +45,8 @@ Each tool has the key you already know. | Subselection | **A** | Points and handles, on raw drawings and drawing objects. | | Free Transform | **Q** | Scale, rotate and move; Shift and Alt as you'd expect. | | Width | **U** | Variable-width strokes, with profiles in Properties. | -| Bone | **M** | Joins symbol instances into an armature. | +| Bone | **M** | Joins symbol instances into an armature, or draws bones inside a shape. | +| Bind | **Shift+M** | Chooses which points of a shape follow which bone. | | Pen | **P** | Alt-click adds a point to a path. | | Text | **T** | Static, dynamic and input text. | | Pencil | **Shift+Y** | Smooth, Straighten and Ink modes. | @@ -189,7 +190,7 @@ Besides the tools and keys above, these are still to come: * groups, saved workspaces and several open documents at once; * motion tweens and bones from Animate documents; -* shape armatures, spring and joint translation for bones; +* spring and joint translation for bones, and armatures mixing symbols and shapes; * the Brush's Paint Selection and Paint Inside modes, pressure curves and a brush library; * per-character text styles and text on a path; * full screen and zoom in Test Movie; diff --git a/docs/guide/masks-guides-camera-bones.md b/docs/guide/masks-guides-camera-bones.md index b35111b7..e722055e 100644 --- a/docs/guide/masks-guides-camera-bones.md +++ b/docs/guide/masks-guides-camera-bones.md @@ -174,8 +174,39 @@ Select a bone to see **Properties › Bone**: where they are, on a layer of their own. If the armature has more than one pose, AniCraft asks first. -Not there yet: bones inside shapes (shape armatures), springs, joints that slide, armatures -that scripts pose while the movie plays, and armatures from Animate files. +### Bones inside a shape + +A shape can have bones of its own, so the shape itself bends, like a tail, a tentacle or a +strand of hair, with no symbols needed. + +1. Draw the shape. A shape with points along its length bends more smoothly. +2. With the **Bone** tool (**M**), drag from inside the shape to where the first bone ends. + The shape moves to a new armature layer. It becomes a drawing object, so shapes you draw + later don't cut into it. +3. Drag from the end of the last bone to add the next one, or from inside the shape to start + a branch. + +Every point of the outline follows the bones nearest to it. Points near a joint are shared by +the bones that meet there, so the shape bends smoothly. Pose and animate it as you would any +armature: drag its bones with the **Selection** tool, and drag the shape to move it. Lines keep +their width as the shape bends. + +**The Bind tool** (**Shift+M**) changes which points follow which bone. With it, the shape's +points show as small squares, or as triangles where several bones share a point. Click a bone +to pick it, and the points it moves fill in. Then: + +* click a point (or drag a box around several) to make it follow only that bone; +* **Shift**-click to share the bone with the bones the point already follows; +* **Ctrl**-click (**⌘**-click on a Mac) to take the point away from the bone. A point that no + bone moves stays where it was drawn. + +**Properties › Bone** shows how many of the shape's points the bone moves. **Rebind All** goes +back to the automatic binding. Adding or removing bones rebinds the points you haven't bound +by hand. + +Not there yet: symbols and shapes in one armature, reshaping a shape after it has bones, +springs, joints that slide, armatures that scripts pose while the movie plays, and armatures +from Animate files. ## Next steps diff --git a/docs/roadmap.md b/docs/roadmap.md index 8b54161e..55fd59c7 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -10,7 +10,7 @@ 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, 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. **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, buttons and right-click menu) act on the whole selection; 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, branches allowed, up to 256 bones); bones show as wedges in the layer colour; the Selection tool drags a bone 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. Not yet: shape armatures, spring, joint translation, runtime armatures, XFL import, editing members' properties in place. **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`. Not yet: editing through the preview, perspective depth, XFL camera import. **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. | +| Timeline | **Frame selection**: click, Shift-click or drag across frames and layers; F5/Shift+F5, F6/F7 and Shift+F6 (keys, buttons and right-click menu) act on the whole selection; 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, branches allowed, up to 256 bones); bones show as wedges in the layer colour; the Selection tool drags a bone 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`. Not yet: editing through the preview, perspective depth, XFL camera import. **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, 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. | | 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; Web Audio for Event/Start/Stop/Stream sounds; filters, Subtract/Invert, bitmap tints and plug-in frame scripts reported. **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. | @@ -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 and text 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); 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: shape armatures, spring, joint translation, runtime armatures, XFL armature import, editing member instances' properties in place); ~~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; not yet: editing while previewing, perspective depth, brightness/advanced colour, attaching layers to the camera, 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: 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; not yet: editing while previewing, perspective depth, brightness/advanced colour, attaching layers to the camera, 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. | | **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; next: 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), next: live screen-reader passes on each platform, a light 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). | ## 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), ~~Bone tool and IK~~ ✅ first slice (ADR 0043), ~~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), ~~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 | | 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); ~~CI on macOS and Windows~~ ✅ (ADR 0067); 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 From 34de21d1d17c05bb766e81ffb65eb4a2cdd8c2fd Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Thu, 12 Nov 2026 00:15:44 -0700 Subject: [PATCH 06/18] docs(adr): reserve ADR 0070 for soft masks and text on a path (M4) --- docs/adr/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/adr/README.md b/docs/adr/README.md index 8a35fed1..74a33e72 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,3 +23,4 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | +| 0070 | m4/svg-soft-masks-textpath | Soft masks and text on a path | From 8cc0384bc180223be879ec6d1088694a7ae2f592 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Thu, 12 Nov 2026 00:19:39 -0700 Subject: [PATCH 07/18] feat(render): soft masks: mask layers reveal by their artwork's opacity or luminance (M4) --- crates/doc/src/eval.rs | 34 ++++++- crates/doc/src/eval_tests.rs | 21 +++++ crates/doc/src/lib.rs | 52 +++++++++++ crates/engine/src/onion.rs | 3 + crates/gpu/src/lib.rs | 4 +- crates/gpu/src/tests.rs | 30 +++--- crates/render/src/lib.rs | 171 +++++++++++++++++++++++++++++------ crates/render/src/stroke.rs | 2 +- crates/render/src/svg.rs | 16 ++-- 9 files changed, 281 insertions(+), 52 deletions(-) diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index a17dcd6f..90a1179c 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -3,7 +3,7 @@ use crate::camera::Camera; use crate::nine_slice::Slicing; use crate::player::PlayerState; -use crate::{ColorTransform, Document, Element, ElementId, ElementKind, Layer, LayerId, LayerKind, Paint, Rgba, Shape, Stroke, SymbolId, SymbolKind, Timeline, TweenKind}; +use crate::{ColorTransform, Document, Element, ElementId, ElementKind, Layer, LayerId, LayerKind, MaskMode, Paint, Rgba, Shape, Stroke, SymbolId, SymbolKind, Timeline, TweenKind}; use anicraft_geom::walk::PathWalk; use anicraft_geom::{Affine, FillRule, Path}; use std::borrow::Cow; @@ -30,7 +30,9 @@ pub struct DisplayItem { pub outline: Option, /// Drawn only inside this clip (an index into [`DisplayList::clip_parents`]). pub clip: Option, - /// Mask artwork: not drawn; its fill area (strokes and opacity ignored) forms this clip. + /// Mask artwork: not drawn; it forms this clip: its fill area (strokes and opacity + /// ignored), or for a soft clip ([`DisplayList::clip_mode`]) its opacity or brightness as + /// drawn. pub masks: Option, /// Guide artwork: shown while editing, never in output. pub guide: bool, @@ -51,6 +53,9 @@ pub struct DisplayList { /// One entry per clip: the enclosing clip it is intersected with. A parent always has a /// lower index than its children. A clip with no mask artwork hides everything in it. pub clip_parents: Vec>, + /// How each clip's artwork reveals (ADR 0070), by clip index. Sparse: a clip past its end + /// is [`MaskMode::Coverage`], so lists that don't care leave it empty. + pub clip_modes: Vec, /// Groups that fade as one: a symbol instance with an opacity below 1 composites its /// items together, then blends the result at `alpha`, so overlapping parts don't show /// through each other. A group's items are one unbroken run of `items`, nested runs for @@ -72,6 +77,24 @@ pub struct Group { } impl DisplayList { + /// How clip `c`'s artwork reveals (coverage when unset). + pub fn clip_mode(&self, c: u32) -> MaskMode { + self.clip_modes.get(c as usize).copied().unwrap_or_default() + } + + /// Sets clip `c`'s mode (only a soft mode is stored; coverage stays implicit). + pub fn set_clip_mode(&mut self, c: u32, mode: MaskMode) { + let i = c as usize; + if mode.is_soft() && i < self.clip_parents.len() { + if self.clip_modes.len() <= i { + self.clip_modes.resize(i + 1, MaskMode::Coverage); + } + if let Some(m) = self.clip_modes.get_mut(i) { + *m = mode; + } + } + } + /// The opacity an item ends up with: its own times every group's it is in (what an item /// looks like when nothing overlaps it; also what picking and outlines use). pub fn effective_alpha(&self, item: &DisplayItem) -> f32 { @@ -107,6 +130,9 @@ impl DisplayList { let gbase = self.groups.len() as u32; let gshift = |g: Option| g.map(|g| g + gbase); self.clip_parents.extend(other.clip_parents.into_iter().map(shift)); + for (i, m) in other.clip_modes.into_iter().enumerate() { + self.set_clip_mode(base + i as u32, m); + } self.groups.extend(other.groups.into_iter().map(|g| Group { parent: gshift(g.parent), alpha: g.alpha, blend: g.blend, filters: g.filters, clip: shift(g.clip) })); self.items.extend(other.items.into_iter().map(|mut i| { i.clip = shift(i.clip); @@ -398,8 +424,10 @@ fn eval_timeline(doc: &Document, tl: &Timeline, frame: u32, cx: &Ctx, out: &mut let mut clips: Vec<(LayerId, u32)> = Vec::new(); if cx.masks.is_none() { for layer in tl.layers.iter().filter(|l| l.kind == LayerKind::Mask && l.visible) { - clips.push((layer.id, out.clip_parents.len() as u32)); + let c = out.clip_parents.len() as u32; + clips.push((layer.id, c)); out.clip_parents.push(cx.clip); + out.set_clip_mode(c, layer.mask_mode); } } let clip_of = |id: LayerId| clips.iter().find(|(l, _)| *l == id).map(|(_, c)| *c); diff --git a/crates/doc/src/eval_tests.rs b/crates/doc/src/eval_tests.rs index fbaaab5e..ce50d93c 100644 --- a/crates/doc/src/eval_tests.rs +++ b/crates/doc/src/eval_tests.rs @@ -156,6 +156,27 @@ fn masks_inside_symbols_nest_in_the_instance_clip() { assert_eq!(inner, vec![(Some(0), None), (Some(1), None), (Some(1), None), (Some(0), Some(1))]); } +#[test] +fn a_soft_mask_layer_gives_its_clip_its_mode() { + let mut d = mask_doc(); + assert_eq!((evaluate(&d, 0).clip_mode(0), evaluate(&d, 0).clip_modes.len()), (crate::MaskMode::Coverage, 0), "coverage stays implicit"); + Arc::make_mut(&mut d.timeline_mut(0).layers[0]).mask_mode = crate::MaskMode::Luminance; + let dl = evaluate(&d, 0); + assert_eq!(dl.clip_mode(0), crate::MaskMode::Luminance); + // Appended lists keep their modes on their renumbered clips. + let mut a = evaluate(&mask_doc(), 0); + a.append(dl); + assert_eq!((a.clip_mode(0), a.clip_mode(1)), (crate::MaskMode::Coverage, crate::MaskMode::Luminance)); + // The mode is saved only when it isn't coverage, and older files (without it) open as coverage. + let json = serde_json::to_string(&*d.timeline(0).layers[0]).unwrap(); + assert!(json.contains("\"mask_mode\":\"luminance\""), "{json}"); + let plain = serde_json::to_string(&*mask_doc().timeline(0).layers[0]).unwrap(); + assert!(!plain.contains("mask_mode")); + let back: Layer = serde_json::from_str(&json).unwrap(); + assert_eq!(back.mask_mode, crate::MaskMode::Luminance); + assert_eq!(serde_json::from_str::(&plain).unwrap().mask_mode, crate::MaskMode::Coverage); +} + #[test] fn appending_lists_renumbers_clips() { let d = mask_doc(); diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 8e45e760..c600136f 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -820,8 +820,59 @@ pub struct Layer { /// An armature layer's bones (ADR 0043); `None` on every other kind of layer. #[serde(default, skip_serializing_if = "Option::is_none")] pub armature: Option>, + /// How a mask layer's artwork reveals what it masks (ADR 0070): its fill area (Animate's + /// masks), or its opacity or brightness (soft masks). Ignored on other kinds of layer. + #[serde(default, skip_serializing_if = "MaskMode::is_coverage")] + pub mask_mode: MaskMode, } +/// How a mask layer's artwork reveals the layers it masks (ADR 0070). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum MaskMode { + /// Its fills' area, fully opaque: colours, opacity and strokes don't matter (as in Animate). + #[default] + Coverage, + /// Its artwork as drawn (fills, strokes, gradients, bitmaps, opacity): the artwork's + /// opacity reveals (Animate users get this with alpha-gradient masks; SVG `mask-type: alpha`). + Alpha, + /// Its artwork's brightness times its opacity reveals: white shows, black hides (SVG's + /// default `mask`). Luminance uses the sRGB coefficients 0.2125, 0.7154, 0.0721. + Luminance, +} + +impl MaskMode { + pub const ALL: [MaskMode; 3] = [MaskMode::Coverage, MaskMode::Alpha, MaskMode::Luminance]; + pub fn is_coverage(&self) -> bool { + *self == MaskMode::Coverage + } + /// Whether the artwork's colours and opacity count (not just its area). + pub fn is_soft(self) -> bool { + self != MaskMode::Coverage + } + pub fn key(self) -> &'static str { + match self { + MaskMode::Coverage => "coverage", + MaskMode::Alpha => "alpha", + MaskMode::Luminance => "luminance", + } + } + pub fn from_key(k: &str) -> Option { + MaskMode::ALL.into_iter().find(|m| m.key() == k) + } + /// How much a premultiplied colour reveals in this mode, `0..=1`. + pub fn reveal(self, premul: [f32; 4]) -> f32 { + let v = match self { + MaskMode::Coverage | MaskMode::Alpha => premul[3], + MaskMode::Luminance => LUMA[0] * premul[0] + LUMA[1] * premul[1] + LUMA[2] * premul[2], + }; + if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 } + } +} + +/// The luminance coefficients of a luminance mask (SVG's `luminanceToAlpha`, on sRGB values). +pub const LUMA: [f32; 3] = [0.2125, 0.7154, 0.0721]; + fn is_zero(v: &f32) -> bool { *v == 0.0 } @@ -892,6 +943,7 @@ impl Layer { volume: 1.0, muted: false, armature: None, + mask_mode: MaskMode::Coverage, } } /// The row height in normal rows, `1..=MAX_LAYER_HEIGHT` whatever a file says. diff --git a/crates/engine/src/onion.rs b/crates/engine/src/onion.rs index 156dd8a8..a32b55c7 100644 --- a/crates/engine/src/onion.rs +++ b/crates/engine/src/onion.rs @@ -308,6 +308,9 @@ fn interleave(tl: &Timeline, parts: Vec) -> (DisplayList, Vec| c.map(|c| c + base); let gshift = move |g: Option| g.map(|g| g + gbase); dl.clip_parents.extend(part.clip_parents.into_iter().map(shift)); + for (i, m) in part.clip_modes.into_iter().enumerate() { + dl.set_clip_mode(base + i as u32, m); + } dl.groups.extend(part.groups.into_iter().map(|g| anicraft_doc::Group { parent: gshift(g.parent), clip: shift(g.clip), ..g })); iters.push( part.items diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index 9117fb2c..a2660d59 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -452,7 +452,7 @@ impl GpuRenderer { blurred.group = Some(0); let filters = Arc::from(vec![Filter::Blur { blur_x: 3.0, blur_y: 2.0, quality: 2 }, Filter::AdjustColor { brightness: 10.0, contrast: 0.0, saturation: -50.0, hue: 30.0 }]); let groups = vec![Group { parent: None, alpha: 1.0, blend: anicraft_doc::BlendMode::Normal, filters, clip: None }]; - let dl = DisplayList { items: vec![solid(2.0, Rgba::new(1.0, 0.0, 0.0, 1.0)), solid(14.0, Rgba::new(0.0, 0.0, 1.0, 0.5)), bitmap, blurred], groups, ..Default::default() }; + let dl = DisplayList { clip_modes: Vec::new(), items: vec![solid(2.0, Rgba::new(1.0, 0.0, 0.0, 1.0)), solid(14.0, Rgba::new(0.0, 0.0, 1.0, 0.5)), bitmap, blurred], groups, ..Default::default() }; let view = View { transform: Affine::IDENTITY, width: 24, height: 20, background: Some(Rgba::WHITE) }; let (oracle, _) = anicraft_render::render(&dl, &view).map_err(|e| GpuError::Unavailable(e.to_string()))?; let oracle = oracle.to_premul_rgba8(); @@ -473,7 +473,7 @@ impl GpuRenderer { check("through a texture", &self.read_texture(&t)?)?; // Binned on the GPU (the plain fills; the bitmap and the symbol bin on the CPU): if that // comes back wrong, only the binning stays on the CPU here. - let plain = DisplayList { items: dl.items.iter().take(3).cloned().collect(), ..Default::default() }; + let plain = DisplayList { clip_modes: Vec::new(), items: dl.items.iter().take(3).cloned().collect(), ..Default::default() }; let (want, _) = anicraft_render::render(&plain, &view).map_err(|e| GpuError::Unavailable(e.to_string()))?; let why = match self.render_with(&plain, &view, Output::Premul8, Binning::Gpu) { Ok(got) => match compare_premul8(&got.premul8, &want.to_premul_rgba8()) { diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index 4423a4a4..47e1f621 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -36,7 +36,7 @@ fn item(path: Path, fill: Paint) -> DisplayItem { } fn list(items: Vec) -> DisplayList { - DisplayList { items, ..Default::default() } + DisplayList { clip_modes: Vec::new(), items, ..Default::default() } } fn view(w: u32, h: u32, bg: Option) -> View { @@ -170,6 +170,7 @@ fn composited_scenes() -> Vec<(&'static str, DisplayList, View)> { let mut out = Vec::new(); // A mask: a gradient seen through a circle, an unclipped shape over it, and one under it. let dl = DisplayList { + clip_modes: Vec::new(), items: vec![item(Path::rect(70.0, 0.0, 50.0, 100.0), Paint::Solid(green)), clipped(item(Path::rect(0.0, 0.0, 120.0, 100.0), grad()), 0), mask(Path::ellipse(50.0, 50.0, 37.3, 33.1), 0), item(Path::rect(10.0, 60.0, 30.0, 30.0), Paint::Solid(blue))], clip_parents: vec![None], groups: Vec::new(), @@ -191,10 +192,11 @@ fn composited_scenes() -> Vec<(&'static str, DisplayList, View)> { } let mut items = stripes; items.extend([eo, mask(Path::ellipse(95.0, 20.0, 30.0, 18.0), 0), star]); - out.push(("nested masks", DisplayList { items, clip_parents: vec![None, Some(0)], groups: Vec::new() }, view(130, 110, Some(Rgba::new(0.95, 0.95, 0.9, 1.0))))); + out.push(("nested masks", DisplayList { clip_modes: Vec::new(), items, clip_parents: vec![None, Some(0)], groups: Vec::new() }, view(130, 110, Some(Rgba::new(0.95, 0.95, 0.9, 1.0))))); // Group alpha: overlapping shapes fade as one; nested groups multiply; a group spans tiles // and the render bands; a top-level shape between two groups. let dl = DisplayList { + clip_modes: Vec::new(), items: vec![ in_group(item(Path::rect(5.0, 5.0, 60.0, 50.0), Paint::Solid(red)), 0), in_group(item(Path::ellipse(55.0, 40.0, 35.0, 30.0), grad()), 0), @@ -221,9 +223,10 @@ fn composited_scenes() -> Vec<(&'static str, DisplayList, View)> { items.push(in_group(item(Path::ellipse(x + 12.0, 30.0, 11.0, 28.0), grad()), g)); items.push(in_group(item(Path::rect(x + 2.0, 60.0, 20.0, 30.0), Paint::Solid(Rgba::new(0.9, 0.5, 0.2, 0.7))), g)); } - out.push(("blend modes", DisplayList { items, clip_parents: Vec::new(), groups }, view(14 * 24, 96, Some(Rgba::new(0.3, 0.3, 0.5, 0.8))))); + out.push(("blend modes", DisplayList { clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups }, view(14 * 24, 96, Some(Rgba::new(0.3, 0.3, 0.5, 0.8))))); // Masks inside groups and groups inside masks, with a blend mode, on transparent. let dl = DisplayList { + clip_modes: Vec::new(), items: vec![ in_group(clipped(item(Path::rect(0.0, 0.0, 100.0, 60.0), grad()), 0), 0), in_group(item(Path::ellipse(70.0, 40.0, 30.0, 30.0), Paint::Solid(blue)), 0), @@ -239,6 +242,7 @@ fn composited_scenes() -> Vec<(&'static str, DisplayList, View)> { // Malformed links, as the oracle treats them: a clip whose parent is later (empty, hides // what it clips), a group whose parent is later (top-level), a clip index past the list. let dl = DisplayList { + clip_modes: Vec::new(), items: vec![ clipped(item(Path::rect(0.0, 0.0, 40.0, 40.0), Paint::Solid(red)), 0), mask(Path::rect(0.0, 0.0, 30.0, 30.0), 0), @@ -569,6 +573,7 @@ fn binning_shapes_the_scene_into_tiles() { // A group in one tile: open, the fill, close; a clipped fill: the clip's level first. In // the middle tile the mask has no artwork, so the clipped fill is left out there. let dl = DisplayList { + clip_modes: Vec::new(), items: vec![ in_group(item(Path::rect(1.0, 1.0, 4.0, 4.0), Paint::Solid(Rgba::BLACK)), 0), clipped(item(Path::rect(0.0, 0.0, 40.0, 16.0), Paint::Solid(Rgba::BLACK)), 0), @@ -597,6 +602,7 @@ fn binning_shapes_the_scene_into_tiles() { #[test] fn nesting_deeper_than_the_shader_holds_goes_to_the_cpu() { let deep = |n: usize| DisplayList { + clip_modes: Vec::new(), items: vec![in_group(item(Path::rect(0.0, 0.0, 8.0, 8.0), Paint::Solid(Rgba::BLACK)), n as u32 - 1)], clip_parents: Vec::new(), groups: (0..n).map(|i| group(i.checked_sub(1).map(|p| p as u32), 0.9, BlendMode::Normal)).collect(), @@ -608,7 +614,7 @@ fn nesting_deeper_than_the_shader_holds_goes_to_the_cpu() { let masks = |n: usize| { let mut items: Vec = (0..n).map(|c| mask(Path::rect(0.0, 0.0, 8.0, 8.0), c as u32)).collect(); items.push(clipped(item(Path::rect(0.0, 0.0, 8.0, 8.0), Paint::Solid(Rgba::BLACK)), n as u32 - 1)); - DisplayList { items, clip_parents: (0..n).map(|i| i.checked_sub(1).map(|p| p as u32)).collect(), groups: Vec::new() } + DisplayList { clip_modes: Vec::new(), items, clip_parents: (0..n).map(|i| i.checked_sub(1).map(|p| p as u32)).collect(), groups: Vec::new() } }; assert!(bin(&masks(bn::MAX_CLIP_DEPTH)).is_ok()); assert_eq!(bin(&masks(bn::MAX_CLIP_DEPTH + 1)).err(), Some(NeedsFull::Clips)); @@ -779,7 +785,7 @@ fn gpu_hands_back_what_it_does_not_draw_and_stays_usable() { .collect(); let mut it = in_group(item(Path::rect(2.0, 2.0, 8.0, 8.0), Paint::Solid(Rgba::BLACK)), depth as u32 - 1); it.color = ColorTransform::alpha(0.5); - DisplayList { items: vec![it], clip_parents: Vec::new(), groups } + DisplayList { clip_modes: Vec::new(), items: vec![it], clip_parents: Vec::new(), groups } }; let deep = nested(MAX_FILTER_DEPTH + 1); assert!(matches!(g.render(&deep, &view(12, 12, None), Output::Premul8), Err(GpuError::NeedsFull(NeedsFull::Filters)))); @@ -857,7 +863,7 @@ fn bitmap_scenes() -> Vec<(&'static str, DisplayList, View)> { // Inside a mask and a faded group, over a gradient. let grad = item(Path::rect(0.0, 0.0, 80.0, 60.0), Paint::Linear { start: Vec2::new(0.0, 0.0), end: Vec2::new(80.0, 60.0), stops: stops(&[(0.0, Rgba::BLACK), (1.0, Rgba::new(1.0, 0.8, 0.0, 1.0))]) }); let inside = in_group(clipped(bitmap_item(Path::rect(4.0, 4.0, 72.0, 52.0), &a, true, turned), 0), 0); - let dl = DisplayList { items: vec![grad, inside, mask(Path::ellipse(40.0, 30.0, 30.0, 22.0), 0)], clip_parents: vec![None], groups: vec![group(None, 0.7, BlendMode::Multiply)] }; + let dl = DisplayList { clip_modes: Vec::new(), items: vec![grad, inside, mask(Path::ellipse(40.0, 30.0, 30.0, 22.0), 0)], clip_parents: vec![None], groups: vec![group(None, 0.7, BlendMode::Multiply)] }; out.push(("bitmap masked and multiplied", dl, view(80, 60, white))); // Without smoothing (ADR 0050): the nearest pixel, magnified, turned and repeated. let mut hard = bitmap_item(Path::rect(2.0, 3.0, 90.0, 70.0), &a, false, turned); @@ -940,7 +946,7 @@ fn gpu_matches_the_oracle_on_every_filter() { for (name, f) in filters_to_test() { let mut items = vec![backdrop.clone()]; items.extend(symbol_items(0)); - let dl = DisplayList { items, clip_parents: Vec::new(), groups: vec![filtered_group(vec![f])] }; + let dl = DisplayList { clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![filtered_group(vec![f])] }; // At 1:1; zoomed, so sizes scale; and panned so the layer reaches past the surface. for v in [view(70, 60, Some(Rgba::WHITE)), View { transform: Affine::scale(1.5, 1.5), width: 105, height: 90, background: None }, View { transform: Affine::translate(-20.0, -15.0), width: 40, height: 33, background: Some(Rgba::WHITE) }] { let d = assert_parity(g, name, &dl, &v); @@ -965,7 +971,7 @@ fn gpu_matches_the_oracle_on_filtered_symbols_in_context() { (grp.alpha, grp.blend) = (0.7, BlendMode::Multiply); let mut items = vec![bg.clone()]; items.extend(symbol_items(0)); - scenes.push(("filters in a row, faded and multiplied", DisplayList { items, clip_parents: Vec::new(), groups: vec![grp] })); + scenes.push(("filters in a row, faded and multiplied", DisplayList { clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![grp] })); // A filtered symbol inside a filtered symbol, inside a faded one. let mut outer = filtered_group(vec![shadow.clone()]); outer.parent = Some(0); @@ -973,22 +979,22 @@ fn gpu_matches_the_oracle_on_filtered_symbols_in_context() { inner.parent = Some(1); let mut items = vec![bg.clone(), in_group(item(Path::rect(4.0, 40.0, 30.0, 16.0), Paint::Solid(Rgba::new(0.9, 0.6, 0.0, 1.0))), 1)]; items.extend(symbol_items(2)); - scenes.push(("nested filtered symbols", DisplayList { items, clip_parents: Vec::new(), groups: vec![group(None, 0.8, BlendMode::Normal), outer, inner] })); + scenes.push(("nested filtered symbols", DisplayList { clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![group(None, 0.8, BlendMode::Normal), outer, inner] })); // Masked from outside (after filtering) and inside (before). let mut clipped_grp = filtered_group(vec![glow.clone()]); clipped_grp.clip = Some(0); let mut items = vec![bg.clone()]; items.extend(symbol_items(0).into_iter().map(|i| clipped(i, 0))); items.push(mask(Path::ellipse(36.0, 30.0, 24.0, 20.0), 0)); - scenes.push(("masked after filtering", DisplayList { items, clip_parents: vec![None], groups: vec![clipped_grp] })); + scenes.push(("masked after filtering", DisplayList { clip_modes: Vec::new(), items, clip_parents: vec![None], groups: vec![clipped_grp] })); let mut items = vec![bg.clone()]; items.extend(symbol_items(0).into_iter().map(|i| clipped(i, 0))); items.push(in_group(mask(Path::rect(20.0, 10.0, 16.0, 40.0), 0), 0)); - scenes.push(("masked inside the symbol", DisplayList { items, clip_parents: vec![None], groups: vec![filtered_group(vec![shadow.clone()])] })); + scenes.push(("masked inside the symbol", DisplayList { clip_modes: Vec::new(), items, clip_parents: vec![None], groups: vec![filtered_group(vec![shadow.clone()])] })); // A bitmap inside a filtered symbol. let px = pixels(9, 7, 4); let items = vec![bg.clone(), in_group(bitmap_item(Path::ellipse(40.0, 32.0, 26.0, 20.0), &px, true, Affine::scale(4.0, 4.0)), 0)]; - scenes.push(("filtered bitmap", DisplayList { items, clip_parents: Vec::new(), groups: vec![filtered_group(vec![blur, glow])] })); + scenes.push(("filtered bitmap", DisplayList { clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![filtered_group(vec![blur, glow])] })); for (name, dl) in scenes { for v in [view(80, 64, white), View { transform: Affine::translate(-37.0, -5.0).mul(&Affine::scale(1.3, 1.3)), width: 48, height: 48, background: white }] { let d = assert_parity(g, name, &dl, &v); diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 3cd1695f..ae793e24 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -13,7 +13,7 @@ pub mod html; pub mod lottie; pub mod svg; -use anicraft_doc::{BlendMode, ColorTransform, DisplayItem, DisplayList, Document, Paint, Rgba, evaluate}; +use anicraft_doc::{BlendMode, ColorTransform, DisplayItem, DisplayList, Document, MaskMode, Paint, Rgba, evaluate}; use anicraft_geom::{Affine, FillRule, Rect, Vec2}; use paint::{Premul, Shader, premultiply}; use raster::{Coverage, IRect}; @@ -158,7 +158,7 @@ pub fn render(dl: &DisplayList, view: &View) -> Result<(Pixmap, RenderStats), Re // Phase 1 (parallel over items): cull, flatten, stroke and build shaders. Output keeps // display-list order. - let mut prepared: Vec> = dl.items.par_iter().zip(&in_run).map(|(item, &skip)| if skip { Vec::new() } else { prepare(item, &view.transform, surface) }).collect(); + let mut prepared: Vec> = dl.items.par_iter().zip(&in_run).map(|(item, &skip)| if skip { Vec::new() } else { prepare(item, &view.transform, surface, soft_art(dl, item)) }).collect(); for r in &runs { if let (Some(op), Some(slot)) = (filtered_group(dl, r, view, surface)?, prepared.get_mut(r.start)) { slot.push(op); @@ -175,7 +175,7 @@ pub fn render(dl: &DisplayList, view: &View) -> Result<(Pixmap, RenderStats), Re if op.masks.is_some() { mask_ops.push(op) } else { ops.push(op) } } } - let clips = Clips::new(&dl.clip_parents, mask_ops); + let clips = Clips::new(&dl.clip_parents, &dl.clip_modes, mask_ops); // A clipped op can only touch its clip's area; an op whose clip is empty draws nothing. ops.retain_mut(|op| { let Some(c) = op.clip else { return true }; @@ -329,7 +329,11 @@ pub struct ClipLayer { /// The clip this one is inside (always an earlier one; a malformed link is already `None` /// and its bounds empty, as [`render`] treats it). pub parent: Option, - /// The mask artwork: solid fill areas whose coverages unite (`a + b − ab`). + /// How the artwork reveals (ADR 0070). Coverage: `art` is solid fill areas whose coverages + /// unite (`a + b − ab`). Alpha or luminance: `art` is painted fills (their strokes too) + /// composited src-over onto transparent, and the result's opacity, or its luminance + /// ([`MaskMode::reveal`]), is the clip's coverage. + pub mode: MaskMode, pub art: Vec, /// Where the clip, and so anything drawn inside it, can be non-zero. pub bounds: IRect, @@ -366,7 +370,7 @@ pub fn prepare_scene(dl: &DisplayList, view: &View) -> Result<(Scene, RenderStat let surface = IRect { x0: 0, y0: 0, x1: view.width as i32, y1: view.height as i32 }; let runs = filtered_runs(dl); let in_run = in_runs(dl, &runs); - let mut prepared: Vec> = dl.items.par_iter().zip(&in_run).map(|(item, &skip)| if skip { Vec::new() } else { prepare(item, &view.transform, surface) }).collect(); + let mut prepared: Vec> = dl.items.par_iter().zip(&in_run).map(|(item, &skip)| if skip { Vec::new() } else { prepare(item, &view.transform, surface, soft_art(dl, item)) }).collect(); let mut layers = Vec::new(); for r in &runs { if let (Some(setup), Some(slot)) = (filter_setup(dl, r, view, surface), prepared.get_mut(r.start)) { @@ -388,7 +392,7 @@ pub fn prepare_scene(dl: &DisplayList, view: &View) -> Result<(Scene, RenderStat } } // The same clips, bounds and culling of clipped fills as `render`. - let clips = Clips::new(&dl.clip_parents, mask_ops); + let clips = Clips::new(&dl.clip_parents, &dl.clip_modes, mask_ops); ops.retain_mut(|op| { let Some(c) = op.clip else { return true }; op.bounds = op.bounds.intersect(&clips.bounds(c)); @@ -402,8 +406,8 @@ pub fn prepare_scene(dl: &DisplayList, view: &View) -> Result<(Scene, RenderStat fills.push(fill(op)); } stats.drawn = fills.len(); - let Clips { parents, art, bounds } = clips; - let clips = parents.into_iter().zip(art).zip(bounds).map(|((parent, art), bounds)| ClipLayer { parent, art: art.into_iter().map(fill).collect(), bounds }).collect(); + let Clips { parents, modes, art, bounds } = clips; + let clips = parents.into_iter().zip(modes).zip(art).zip(bounds).map(|(((parent, mode), art), bounds)| ClipLayer { parent, mode, art: art.into_iter().map(fill).collect(), bounds }).collect(); let groups = group_chains(&dl.groups) .into_iter() .zip(&dl.groups) @@ -528,6 +532,7 @@ fn filter_setup(dl: &DisplayList, run: &FilteredRun, view: &View, surface: IRect let list = DisplayList { items: items.iter().map(|i| DisplayItem { clip: i.clip.filter(|c| inner.contains(c)), ..i.clone() }).collect(), clip_parents: dl.clip_parents.iter().map(|p| p.filter(|c| inner.contains(c))).collect(), + clip_modes: dl.clip_modes.clone(), groups, }; let sub_view = View { transform: Affine::translate(-b.x0 as f32, -b.y0 as f32).mul(&view.transform), width: b.width() as u32, height: b.height() as u32, background: None }; @@ -675,6 +680,7 @@ struct Prepared { /// The clips of a display list: their mask artwork and where each can be non-zero. struct Clips { parents: Vec>, + modes: Vec, /// Mask artwork, grouped by clip. art: Vec>, bounds: Vec, @@ -683,8 +689,9 @@ struct Clips { const NO_PIXELS: IRect = IRect { x0: 0, y0: 0, x1: 0, y1: 0 }; impl Clips { - fn new(parents: &[Option], mask_ops: Vec) -> Clips { + fn new(parents: &[Option], modes: &[MaskMode], mask_ops: Vec) -> Clips { let n = parents.len(); + let modes = (0..n).map(|i| modes.get(i).copied().unwrap_or_default()).collect(); let mut art: Vec> = (0..n).map(|_| Vec::new()).collect(); for op in mask_ops { if let Some(a) = op.masks.and_then(|c| art.get_mut(c as usize)) { @@ -705,7 +712,7 @@ impl Clips { bounds.push(b); clean.push(parent.filter(|&p| (p as usize) < i)); } - Clips { parents: clean, art, bounds } + Clips { parents: clean, modes, art, bounds } } fn bounds(&self, c: u32) -> IRect { @@ -730,8 +737,28 @@ impl BandClips { } let parent = clips.parents.get(i).copied().flatten().map(|p| self.get(clips, p, band, w, cov, row)); let mut buf = vec![0.0f32; w * band.height()]; + let mode = clips.modes.get(i).copied().unwrap_or_default(); + if mode.is_soft() { + // A soft mask: its artwork painted onto transparent, then each pixel's opacity or + // luminance. + let mut px: Vec = vec![[0.0; 4]; w * band.height()]; + for op in clips.art.get(i).into_iter().flatten() { + let b = op.bounds.intersect(&band); + if b.is_empty() { + continue; + } + cov.reset(b); + for poly in &op.polys { + cov.add_polygon(poly); + } + composite(cov, op, b, band.y0, w, &mut px, row, None); + } + for (d, p) in buf.iter_mut().zip(&px) { + *d = mode.reveal(*p); + } + } // Union of the artwork's coverage (a ∪ b = a + b − ab), anti-aliased like any fill. - for op in clips.art.get(i).into_iter().flatten() { + for op in clips.art.get(i).into_iter().flatten().filter(|_| !mode.is_soft()) { let b = op.bounds.intersect(&band); if b.is_empty() { continue; @@ -765,8 +792,15 @@ impl BandClips { } } -/// Turns a display item into fill operations (fill, then stroke), or none when culled. -fn prepare(item: &DisplayItem, view: &Affine, surface: IRect) -> Vec { +/// Whether `item` is artwork of a soft mask (drawn with its paint, ADR 0070). +fn soft_art(dl: &DisplayList, item: &DisplayItem) -> bool { + item.masks.is_some_and(|c| dl.clip_mode(c).is_soft()) +} + +/// Turns a display item into fill operations (fill, then stroke), or none when culled. `soft`: +/// the item is a soft mask's artwork, prepared with its paints like any artwork (still marked +/// as mask artwork). +fn prepare(item: &DisplayItem, view: &Affine, surface: IRect, soft: bool) -> Vec { let mut out = Vec::new(); let m = view.mul(&item.transform); if !m.is_finite() { @@ -776,8 +810,9 @@ fn prepare(item: &DisplayItem, view: &Affine, surface: IRect) -> Vec { if item.guide { return out; } - // Mask artwork is its fill area only: no strokes, no opacity (as animators expect). - let is_mask = item.masks.is_some(); + // Mask artwork is its fill area only: no strokes, no opacity (as animators expect); a soft + // mask's artwork is drawn as it looks. + let is_mask = item.masks.is_some() && !soft; if is_mask && item.fill.is_none() { return out; } @@ -794,7 +829,7 @@ fn prepare(item: &DisplayItem, view: &Affine, surface: IRect) -> Vec { } let (clip, masks, group) = (item.clip, item.masks, item.group); // (Mask artwork is never outlined: it draws nothing of its own.) - if let Some(color) = item.outline.filter(|_| !is_mask) { + if let Some(color) = item.outline.filter(|_| item.masks.is_none()) { // Outline mode: a hairline in the layer colour, no fill (ADR 0048). let shader = Shader::Solid(premultiply(color)); if shader.is_solid().is_some_and(|c| c[3] <= 0.0) { @@ -934,7 +969,90 @@ mod tests { } fn list(items: Vec) -> DisplayList { - DisplayList { items, clip_parents: Vec::new(), groups: Vec::new() } + DisplayList { clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: Vec::new() } + } + + /// A 40 × 40 opaque blue square masked by `art` in `mode`, on transparent. + fn soft(mode: MaskMode, art: Vec) -> Pixmap { + let mut square = item(Path::rect(0.0, 0.0, 40.0, 40.0), Paint::Solid(Rgba::new(0.0, 0.0, 1.0, 1.0))); + square.clip = Some(0); + let mut items = vec![square]; + items.extend(art.into_iter().map(|mut a| { + a.masks = Some(0); + a + })); + let mut dl = DisplayList { items, clip_parents: vec![None], ..Default::default() }; + dl.set_clip_mode(0, mode); + render(&dl, &view(40, 40)).unwrap().0 + } + + #[test] + fn soft_masks_reveal_by_opacity_or_luminance() { + let close = |a: f32, b: f32| (a - b).abs() < 1e-4; + let half_red = || item(Path::rect(0.0, 0.0, 40.0, 40.0), Paint::Solid(Rgba::new(1.0, 0.0, 0.0, 0.5))); + // Alpha: the artwork's opacity is the coverage; its colour doesn't matter. + let pm = soft(MaskMode::Alpha, vec![half_red()]); + assert!(close(pm.pixel(20, 20).unwrap()[3], 0.5) && close(pm.pixel(20, 20).unwrap()[2], 0.5), "{:?}", pm.pixel(20, 20)); + // Coverage (today's masks): the same artwork reveals fully. + assert_eq!(soft(MaskMode::Coverage, vec![half_red()]).pixel(20, 20).unwrap(), [0.0, 0.0, 1.0, 1.0]); + // Luminance: 0.2125 r + 0.7154 g + 0.0721 b, times the opacity. + let pm = soft(MaskMode::Luminance, vec![half_red()]); + assert!(close(pm.pixel(20, 20).unwrap()[3], 0.2125 * 0.5), "{:?}", pm.pixel(20, 20)); + for (c, want) in [(Rgba::WHITE, 1.0), (Rgba::BLACK, 0.0), (Rgba::new(0.0, 1.0, 0.0, 1.0), 0.7154), (Rgba::new(0.5, 0.5, 0.5, 1.0), 0.5)] { + let pm = soft(MaskMode::Luminance, vec![item(Path::rect(0.0, 0.0, 40.0, 40.0), Paint::Solid(c))]); + assert!(close(pm.pixel(5, 5).unwrap()[3], want), "{c:?}: {:?}", pm.pixel(5, 5)); + } + // Overlapping artwork composites (src-over) before it masks: two 0.5 layers give 0.75. + let pm = soft(MaskMode::Alpha, vec![half_red(), half_red()]); + assert!(close(pm.pixel(20, 20).unwrap()[3], 0.75)); + // The artwork's colour effect (an instance's alpha) counts. + let mut faded = item(Path::rect(0.0, 0.0, 40.0, 40.0), Paint::Solid(Rgba::WHITE)); + faded.color = ColorTransform::alpha(0.25); + assert!(close(soft(MaskMode::Alpha, vec![faded]).pixel(20, 20).unwrap()[3], 0.25)); + // Strokes count in a soft mask (not in a coverage one). + let mut ring = item(Path::rect(10.0, 10.0, 20.0, 20.0), Paint::Solid(Rgba::TRANSPARENT)); + ring.stroke = Some(anicraft_doc::Stroke::new(Rgba::WHITE, 4.0)); + assert!(close(soft(MaskMode::Alpha, vec![ring.clone()]).pixel(10, 20).unwrap()[3], 1.0)); + assert_eq!(soft(MaskMode::Coverage, vec![ring]).pixel(10, 1).unwrap()[3], 0.0); + // Outside the artwork nothing shows. + let small = item(Path::rect(0.0, 0.0, 10.0, 10.0), Paint::Solid(Rgba::WHITE)); + assert_eq!(soft(MaskMode::Alpha, vec![small]).pixel(30, 30).unwrap()[3], 0.0); + } + + #[test] + fn an_alpha_gradient_mask_fades_linearly() { + // Transparent at x = 0 to opaque at x = 40: pixel x reveals (x + 0.5) / 40. + let stops = vec![anicraft_doc::GradientStop { offset: 0.0, color: Rgba::new(1.0, 1.0, 1.0, 0.0) }, anicraft_doc::GradientStop { offset: 1.0, color: Rgba::WHITE }]; + let grad = item(Path::rect(0.0, 0.0, 40.0, 40.0), Paint::Linear { start: Vec2::new(0.0, 0.0), end: Vec2::new(40.0, 0.0), stops }); + let pm = soft(MaskMode::Alpha, vec![grad.clone()]); + for x in [0u32, 10, 20, 30, 39] { + let a = pm.pixel(x, 20).unwrap()[3]; + // The gradient table has 256 steps: within one step. + assert!((a - (x as f32 + 0.5) / 40.0).abs() < 1.0 / 255.0 + 1e-3, "x {x}: {a}"); + } + // White to transparent as luminance: the same ramp (white's luminance is 1). + let lum = soft(MaskMode::Luminance, vec![grad]); + assert!(pm.data.iter().zip(&lum.data).all(|(a, b)| (a[3] - b[3]).abs() < 1e-4)); + } + + #[test] + fn a_soft_mask_inside_another_mask_multiplies() { + // Clip 1 (alpha, 0.5) inside clip 0 (coverage, left half): right half hidden, left at 0.5. + let mut square = item(Path::rect(0.0, 0.0, 40.0, 40.0), Paint::Solid(Rgba::new(0.0, 0.0, 1.0, 1.0))); + square.clip = Some(1); + let mut outer = item(Path::rect(0.0, 0.0, 20.0, 40.0), Paint::Solid(Rgba::WHITE)); + outer.masks = Some(0); + let mut inner = item(Path::rect(0.0, 0.0, 40.0, 40.0), Paint::Solid(Rgba::new(1.0, 1.0, 1.0, 0.5))); + inner.masks = Some(1); + inner.clip = Some(0); + let mut dl = DisplayList { items: vec![square, outer, inner], clip_parents: vec![None, Some(0)], ..Default::default() }; + dl.set_clip_mode(1, MaskMode::Alpha); + let (pm, _) = render(&dl, &view(40, 40)).unwrap(); + assert!((pm.pixel(5, 5).unwrap()[3] - 0.5).abs() < 1e-4); + assert_eq!(pm.pixel(30, 5).unwrap()[3], 0.0); + // And the scene a GPU renderer gets carries the mode. + let (scene, _) = prepare_scene(&dl, &view(40, 40)).unwrap(); + assert_eq!(scene.clips.iter().map(|c| c.mode).collect::>(), vec![MaskMode::Coverage, MaskMode::Alpha]); } #[test] @@ -946,7 +1064,7 @@ mod tests { let mut mask = item(Path::ellipse(20.0, 20.0, 10.0, 10.0), Paint::Solid(Rgba::new(1.0, 0.0, 0.0, 0.2))); mask.masks = Some(0); mask.stroke = Some(anicraft_doc::Stroke::new(Rgba::BLACK, 8.0)); - let dl = DisplayList { items: vec![square, mask], clip_parents: vec![None], groups: Vec::new() }; + let dl = DisplayList { clip_modes: Vec::new(), items: vec![square, mask], clip_parents: vec![None], groups: Vec::new() }; let (pm, _) = render(&dl, &view(40, 40)).unwrap(); // Pixel for pixel, the same as the circle drawn in the square's colour. let circle = item(Path::ellipse(20.0, 20.0, 10.0, 10.0), Paint::Solid(Rgba::new(0.0, 0.0, 1.0, 1.0))); @@ -1014,7 +1132,7 @@ mod tests { let mut blue = item(Path::rect(4.0, 0.0, 8.0, 4.0), Paint::Solid(Rgba::new(0.0, 0.0, 1.0, 1.0))); red.group = Some(0); blue.group = Some(0); - let grouped = DisplayList { items: vec![red.clone(), blue.clone()], clip_parents: vec![], groups: vec![anicraft_doc::Group { parent: None, alpha: 0.5, blend: Default::default(), filters: Default::default(), clip: None }] }; + let grouped = DisplayList { clip_modes: Vec::new(), items: vec![red.clone(), blue.clone()], clip_parents: vec![], groups: vec![anicraft_doc::Group { parent: None, alpha: 0.5, blend: Default::default(), filters: Default::default(), clip: None }] }; let (pm, _) = render(&grouped, &white).unwrap(); let near = |p: Premul, q: [f32; 4]| p.iter().zip(q).all(|(a, b)| (a - b).abs() < 1e-4); // In the overlap only the top square shows through: half blue, half white, no red. @@ -1031,6 +1149,7 @@ mod tests { let mut inner = item(Path::rect(0.0, 0.0, 12.0, 4.0), Paint::Solid(Rgba::BLACK)); inner.group = Some(1); let nested = DisplayList { + clip_modes: Vec::new(), items: vec![inner], clip_parents: vec![], groups: vec![anicraft_doc::Group { parent: None, alpha: 0.5, blend: Default::default(), filters: Default::default(), clip: None }, anicraft_doc::Group { parent: Some(0), alpha: 0.5, blend: Default::default(), filters: Default::default(), clip: None }], @@ -1044,7 +1163,7 @@ mod tests { // Spanning several render bands changes nothing. let mut tall = item(Path::rect(0.0, 0.0, 4.0, 100.0), Paint::Solid(Rgba::BLACK)); tall.group = Some(0); - let (t, _) = render(&DisplayList { items: vec![tall], clip_parents: vec![], groups: vec![anicraft_doc::Group { parent: None, alpha: 0.25, blend: Default::default(), filters: Default::default(), clip: None }] }, &View { background: Some(Rgba::WHITE), ..view(4, 100) }).unwrap(); + let (t, _) = render(&DisplayList { clip_modes: Vec::new(), items: vec![tall], clip_parents: vec![], groups: vec![anicraft_doc::Group { parent: None, alpha: 0.25, blend: Default::default(), filters: Default::default(), clip: None }] }, &View { background: Some(Rgba::WHITE), ..view(4, 100) }).unwrap(); assert!((0..100).all(|y| near(t.pixel(1, y).unwrap(), [0.75, 0.75, 0.75, 1.0]))); } @@ -1074,7 +1193,7 @@ mod tests { inner.masks = Some(1); let mut lost = clipped.clone(); lost.clip = Some(2); - let dl = DisplayList { items: vec![clipped, outer, inner, lost], clip_parents: vec![None, Some(0), Some(9)], groups: Vec::new() }; + let dl = DisplayList { clip_modes: Vec::new(), items: vec![clipped, outer, inner, lost], clip_parents: vec![None, Some(0), Some(9)], groups: Vec::new() }; let (scene, st) = prepare_scene(&dl, &view(16, 16)).unwrap(); let (_, rst) = render(&dl, &view(16, 16)).unwrap(); assert_eq!((st.drawn, st.edges, st.pixels_touched), (rst.drawn, rst.edges, rst.pixels_touched)); @@ -1087,7 +1206,7 @@ mod tests { let mut grouped = sq.clone(); grouped.group = Some(1); let g = |parent, alpha| anicraft_doc::Group { parent, alpha, blend: BlendMode::Multiply, filters: Default::default(), clip: None }; - let dl = DisplayList { items: vec![grouped], clip_parents: vec![], groups: vec![g(None, 2.0), g(Some(0), f32::NAN)] }; + let dl = DisplayList { clip_modes: Vec::new(), items: vec![grouped], clip_parents: vec![], groups: vec![g(None, 2.0), g(Some(0), f32::NAN)] }; let (scene, _) = prepare_scene(&dl, &view(16, 16)).unwrap(); assert!(scene.fills.iter().all(|f| f.group == Some(1))); assert_eq!((scene.groups[1].chain.clone(), scene.groups[0].alpha, scene.groups[1].alpha, scene.groups[1].blend), (vec![0, 1], 1.0, 1.0, BlendMode::Multiply)); @@ -1129,7 +1248,7 @@ mod tests { let mut clipped = item(Path::rect(0.0, 0.0, 8.0, 8.0), Paint::Solid(Rgba::BLACK)); clipped.clip = Some(0); let free = item(Path::rect(0.0, 0.0, 2.0, 2.0), Paint::Solid(Rgba::BLACK)); - let (pm, st) = render(&DisplayList { items: vec![clipped, free.clone()], clip_parents: vec![None], groups: Vec::new() }, &view(8, 8)).unwrap(); + let (pm, st) = render(&DisplayList { clip_modes: Vec::new(), items: vec![clipped, free.clone()], clip_parents: vec![None], groups: Vec::new() }, &view(8, 8)).unwrap(); assert_eq!(st.drawn, 1); assert_eq!(pm, render(&list(vec![free]), &view(8, 8)).unwrap().0); } @@ -1144,11 +1263,11 @@ mod tests { inner.masks = Some(1); let items = vec![fill, outer, inner]; // Clip 1 lies inside clip 0: a 32 × 32 square across two render bands survives. - let (pm, _) = render(&DisplayList { items: items.clone(), clip_parents: vec![None, Some(0)], groups: Vec::new() }, &view(64, 64)).unwrap(); + let (pm, _) = render(&DisplayList { clip_modes: Vec::new(), items: items.clone(), clip_parents: vec![None, Some(0)], groups: Vec::new() }, &view(64, 64)).unwrap(); assert!((alpha_sum(&pm) - 32.0 * 32.0).abs() < 1e-2, "{}", alpha_sum(&pm)); // A parent link pointing forward (malformed) or out of range masks everything out. for parents in [vec![Some(1), Some(1)], vec![None, Some(9)]] { - let (pm, _) = render(&DisplayList { items: items.clone(), clip_parents: parents, groups: Vec::new() }, &view(64, 64)).unwrap(); + let (pm, _) = render(&DisplayList { clip_modes: Vec::new(), items: items.clone(), clip_parents: parents, groups: Vec::new() }, &view(64, 64)).unwrap(); assert_eq!(alpha_sum(&pm), 0.0); } } @@ -1370,7 +1489,7 @@ mod tests { let bg = item(Path::rect(0.0, 0.0, 20.0, 10.0), Paint::Solid(Rgba::new(0.5, 0.5, 1.0, 1.0))); let mut top = item(Path::rect(0.0, 0.0, 10.0, 10.0), Paint::Solid(Rgba::new(1.0, 0.0, 0.0, 1.0))); top.group = Some(0); - let dl = DisplayList { items: vec![bg, top], clip_parents: vec![], groups: vec![anicraft_doc::Group { parent: None, alpha: 1.0, blend: BlendMode::Multiply, filters: Default::default(), clip: None }] }; + let dl = DisplayList { clip_modes: Vec::new(), items: vec![bg, top], clip_parents: vec![], groups: vec![anicraft_doc::Group { parent: None, alpha: 1.0, blend: BlendMode::Multiply, filters: Default::default(), clip: None }] }; let (pm, _) = render(&dl, &View { background: Some(Rgba::WHITE), ..view(20, 10) }).unwrap(); let p = pm.pixel(5, 5).unwrap(); assert!((p[0] - 0.5).abs() < 1e-3 && p[1].abs() < 1e-3 && p[2].abs() < 1e-3, "red × lavender: {p:?}"); diff --git a/crates/render/src/stroke.rs b/crates/render/src/stroke.rs index 96b790d9..88f3f137 100644 --- a/crates/render/src/stroke.rs +++ b/crates/render/src/stroke.rs @@ -656,7 +656,7 @@ pub fn outline_variable_strokes(dl: &DisplayList) -> std::borrow::Cow<'_, Displa items.push(DisplayItem { path: std::sync::Arc::new(outline), transform: Affine::IDENTITY, fill: Some(anicraft_doc::Paint::Solid(st.color)), stroke: None, fill_rule: anicraft_geom::FillRule::NonZero, image: None, ..it.clone() }); } } - std::borrow::Cow::Owned(DisplayList { items, clip_parents: dl.clip_parents.clone(), groups: dl.groups.clone() }) + std::borrow::Cow::Owned(DisplayList { clip_modes: dl.clip_modes.clone(), items, clip_parents: dl.clip_parents.clone(), groups: dl.groups.clone() }) } #[cfg(test)] diff --git a/crates/render/src/svg.rs b/crates/render/src/svg.rs index 44b1c7bc..14d24ada 100644 --- a/crates/render/src/svg.rs +++ b/crates/render/src/svg.rs @@ -477,10 +477,10 @@ mod tests { let mut b = item(Path::rect(0.0, 0.0, 10.0, 10.0), Some(Paint::Bitmap { bitmap: anicraft_doc::BitmapId(1), repeat: true, matrix: Affine::IDENTITY })); b.image = Some(px); b.color = ColorTransform::alpha(0.5); - let svg = to_svg(&DisplayList { items: vec![b.clone()], ..Default::default() }, &stage()); + let svg = to_svg(&DisplayList { clip_modes: Vec::new(), items: vec![b.clone()], ..Default::default() }, &stage()); assert!(svg.contains("fill-opacity=\"0.5\"") && !svg.contains("feColorMatrix"), "{svg}"); b.color = ColorTransform { mul: [-1.0, 0.5, 1.0, 0.8], add: [1.0, 0.25, 0.0, 0.1] }; - let svg = to_svg(&DisplayList { items: vec![b], ..Default::default() }, &stage()); + let svg = to_svg(&DisplayList { clip_modes: Vec::new(), items: vec![b], ..Default::default() }, &stage()); assert!(svg.contains(""), "{svg}"); assert!(svg.contains("filter=\"url(#cm") && !svg.contains("fill-opacity"), "{svg}"); } @@ -492,7 +492,7 @@ mod tests { a.stroke = Some(Stroke::new(Rgba::BLACK, 3.0)); a.color = ColorTransform::alpha(0.5); a.fill_rule = FillRule::EvenOdd; - let svg = to_svg(&DisplayList { items: vec![a], clip_parents: vec![], groups: Vec::new() }, &stage()); + let svg = to_svg(&DisplayList { clip_modes: Vec::new(), items: vec![a], clip_parents: vec![], groups: Vec::new() }, &stage()); assert!(svg.starts_with("")); assert!(svg.contains(""), "background"); assert!(svg.contains("d=\"M5 7L25 7L25 27L5 27Z\" fill=\"#ff0000\" fill-opacity=\"0.5\" fill-rule=\"evenodd\""), "{svg}"); @@ -507,7 +507,7 @@ mod tests { let mut a = item(Path::line(Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0)), None); a.transform = Affine::scale(2.0, 2.0); a.stroke = Some(st); - to_svg(&DisplayList { items: vec![a], clip_parents: vec![], groups: Vec::new() }, &stage()) + to_svg(&DisplayList { clip_modes: Vec::new(), items: vec![a], clip_parents: vec![], groups: Vec::new() }, &stage()) }; // The default style is written as before: round, no dashes. let svg = svg_of(Stroke::new(Rgba::BLACK, 3.0)); @@ -527,7 +527,7 @@ mod tests { fn variable_width_strokes_are_written_as_filled_outlines() { let mut a = item(Path::line(Vec2::new(0.0, 10.0), Vec2::new(80.0, 10.0)), Some(Paint::Solid(Rgba::hex(0xff0000)))); a.stroke = Some(Stroke::new(Rgba::hex(0x0000ff), 6.0).with_profile(anicraft_doc::ProfilePreset::TaperBoth.profile())); - let svg = to_svg(&DisplayList { items: vec![a], clip_parents: vec![], groups: Vec::new() }, &stage()); + let svg = to_svg(&DisplayList { clip_modes: Vec::new(), items: vec![a], clip_parents: vec![], groups: Vec::new() }, &stage()); assert!(!svg.contains("stroke-width"), "no SVG stroke: {svg}"); assert!(svg.contains("fill=\"#0000ff\""), "the outline is filled in the stroke colour"); assert!(svg.contains("fill=\"#ff0000\""), "the shape's own fill stays"); @@ -544,7 +544,7 @@ mod tests { outer.masks = Some(0); let mut inner = item(Path::ellipse(25.0, 25.0, 10.0, 10.0), Some(Paint::Solid(Rgba::BLACK))); inner.masks = Some(1); - let svg = to_svg(&DisplayList { items: vec![g, outer, inner], clip_parents: vec![None, Some(0)], groups: Vec::new() }, &stage()); + let svg = to_svg(&DisplayList { clip_modes: Vec::new(), items: vec![g, outer, inner], clip_parents: vec![None, Some(0)], groups: Vec::new() }, &stage()); assert!(svg.contains("gradientTransform=\"matrix(1 0 0 1 20 0)\" x1=\"0\" y1=\"0\" x2=\"10\" y2=\"0\""), "{svg}"); assert!(svg.contains("")); assert!(svg.contains(""), "nested clip"); @@ -566,7 +566,7 @@ mod tests { let clear = item(Path::rect(0.0, 0.0, 1.0, 1.0), Some(Paint::Solid(Rgba::TRANSPARENT))); let mut lost = item(Path::rect(0.0, 0.0, 1.0, 1.0), Some(Paint::Solid(Rgba::BLACK))); lost.clip = Some(7); - let svg = to_svg(&DisplayList { items: vec![bad, empty, clear, lost], clip_parents: vec![Some(3)], groups: Vec::new() }, &stage()); + let svg = to_svg(&DisplayList { clip_modes: Vec::new(), items: vec![bad, empty, clear, lost], clip_parents: vec![Some(3)], groups: Vec::new() }, &stage()); assert_eq!(svg.matches(""), "a malformed clip clips everything"); assert!(!svg.contains("NaN") && !svg.contains("inf")); @@ -599,7 +599,7 @@ mod group_tests { image: None, smooth: true, }; - let dl = DisplayList { 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 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 }); assert!(svg.contains("") && svg.contains(""), "{svg}"); assert_eq!(svg.matches("").count(), "balanced"); From 960203fcdedc0375f5852251d13118e1ec48bdd8 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Thu, 12 Nov 2026 00:21:05 -0700 Subject: [PATCH 08/18] feat(gpu): soft masks on the GPU stage, at parity with the oracle (M4) --- crates/gpu/src/binning.rs | 22 +++++++++--- crates/gpu/src/fine.wgsl | 31 ++++++++++++++-- crates/gpu/src/tests.rs | 76 +++++++++++++++++++++++++++++++-------- 3 files changed, 108 insertions(+), 21 deletions(-) diff --git a/crates/gpu/src/binning.rs b/crates/gpu/src/binning.rs index fced063d..9ebdcb0a 100644 --- a/crates/gpu/src/binning.rs +++ b/crates/gpu/src/binning.rs @@ -78,7 +78,8 @@ const IMAGE: u32 = 4; /// Op header flag: the fill is drawn inside the current clip. pub const CLIPPED: u32 = 1; -/// Op header flag: the op is clip artwork (its coverage joins the current level's union). +/// Op header flag: the op is clip artwork (its coverage joins the current level's union; in a +/// soft mask its paint composites into the level's colour). pub const ART: u32 = 2; /// An entry whose first word has this bit is a control entry, not a fill. @@ -89,11 +90,23 @@ pub const OPEN: u32 = CTRL | 1; pub const CLOSE: u32 = CTRL | 2; /// The clip coverage starts at 1 (a new clip's chain follows). pub const MASK_RESET: u32 = CTRL | 3; -/// One level of the clip chain starts: its union of artwork coverage starts at 0. +/// `[LEVEL_BEGIN, mask mode, 0, 0]`: one level of the clip chain starts: its union of artwork +/// coverage starts at 0, or for a soft mask ([`mask_code`]) its artwork's colour starts +/// transparent. pub const LEVEL_BEGIN: u32 = CTRL | 4; -/// The level ends: the clip coverage is multiplied by its union. +/// The level ends: the clip coverage is multiplied by its union (or by the soft mask's +/// opacity or luminance, ADR 0070). pub const LEVEL_END: u32 = CTRL | 5; +/// Mask modes as the shader numbers them (`fine.wgsl` › `LEVEL_END`). +pub fn mask_code(m: anicraft_doc::MaskMode) -> u32 { + match m { + anicraft_doc::MaskMode::Coverage => 0, + anicraft_doc::MaskMode::Alpha => 1, + anicraft_doc::MaskMode::Luminance => 2, + } +} + /// Blend modes as the shader numbers them (`fine.wgsl` › `blend`). pub fn blend_code(m: BlendMode) -> u32 { match m { @@ -540,7 +553,8 @@ fn tile_stream(fills: &[[u32; 4]], arts: &[[u32; 4]], t: &Tables, out: &mut Vec< } out.push([MASK_RESET, 0, 0, 0]); for &l in chain { - out.push([LEVEL_BEGIN, 0, 0, 0]); + let mode = t.scene.clips.get(l as usize).map_or(0, |c| mask_code(c.mode)); + out.push([LEVEL_BEGIN, mode, 0, 0]); out.extend_from_slice(level(l)); out.push([LEVEL_END, 0, 0, 0]); } diff --git a/crates/gpu/src/fine.wgsl b/crates/gpu/src/fine.wgsl index 6ac724fa..17026be1 100644 --- a/crates/gpu/src/fine.wgsl +++ b/crates/gpu/src/fine.wgsl @@ -10,7 +10,8 @@ // pixel centre to its nearest segment (crates/render/src/hairline.rs). // // Masks and groups (ADR 0029) are control entries in the same list, mirroring the oracle's band -// compositor (crates/render/src/lib.rs): clip artwork unites into a level's coverage, levels +// compositor (crates/render/src/lib.rs): clip artwork unites into a level's coverage (a soft +// mask's, ADR 0070, composites its paint and gives its opacity or luminance), levels // multiply into the clip coverage that clipped fills are scaled by; a group pushes the colour // so far and continues on transparent, and its close blends it into the colour below at the // group's alpha, in its blend mode (the W3C separable formulas, as the oracle's `blend`). @@ -359,6 +360,10 @@ fn pixel(wg: vec3, lid: vec3) -> vec4 { var depth = 0u; var mask = 1.0; var level = 0.0; + // A soft mask's level (ADR 0070): its mode (0 coverage, 1 alpha, 2 luminance) and its + // artwork's colour so far. + var level_mode = 0u; + var level_colour = vec4(0.0); let start = index[tile * 2u]; let count = index[tile * 2u + 1u]; for (var i = 0u; i < count; i++) { @@ -380,8 +385,20 @@ fn pixel(wg: vec3, lid: vec3) -> vec4 { } } case MASK_RESET: { mask = 1.0; } - case LEVEL_BEGIN: { level = 0.0; } - case LEVEL_END: { mask *= level; } + case LEVEL_BEGIN: { + level = 0.0; + level_mode = index[e + 1u]; + level_colour = vec4(0.0); + } + case LEVEL_END: { + // The oracle's MaskMode::reveal: opacity, or luminance (sRGB coefficients). + if level_mode == 1u { + level = level_colour.a; + } else if level_mode == 2u { + level = dot(level_colour.rgb, vec3(0.2125, 0.7154, 0.0721)); + } + mask *= clamp(level, 0.0, 1.0); + } default: {} } continue; @@ -415,6 +432,14 @@ fn pixel(wg: vec3, lid: vec3) -> vec4 { } let flags = index[h + 3u]; if (flags & ART) != 0u { + if level_mode != 0u { + // Soft mask artwork composites as drawn (the oracle's `composite`). + if cov > 1e-4 { + let s = shade(op, index[h], index[h + 2u], centre, x, y); + level_colour = s * cov + level_colour * (1.0 - s.a * cov); + } + continue; + } let k = clamp(cov, 0.0, 1.0); level = level + k - level * k; continue; diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index 47e1f621..5a17d78c 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -7,7 +7,7 @@ use super::*; use crate::binning::{self as bn, Binned, PAINT_VEC4S, TILE, piece_cover, solid_of}; -use anicraft_doc::{BlendMode, ColorEffect, ColorTransform, DisplayItem, ElementId, ElementKind, GradientStop, Group, LayerId, LayerKind, Paint, Rgba, Stroke, sample}; +use anicraft_doc::{BlendMode, ColorEffect, ColorTransform, DisplayItem, ElementId, ElementKind, GradientStop, Group, LayerId, LayerKind, MaskMode, Paint, Rgba, Stroke, sample}; use anicraft_geom::{Affine, FillRule, Path, Vec2}; use anicraft_render::{paint::Premul, render}; use std::sync::OnceLock; @@ -254,6 +254,39 @@ fn composited_scenes() -> Vec<(&'static str, DisplayList, View)> { groups: vec![group(Some(1), 0.5, BlendMode::Normal), group(Some(1), 0.5, BlendMode::Difference)], }; out.push(("malformed links", dl, view(50, 50, Some(Rgba::WHITE)))); + // Soft masks (ADR 0070): an alpha gradient fading a shape out, a luminance mask with a + // stroke and overlapping faded art, and a soft mask inside a coverage one. + let fade = Paint::Linear { start: Vec2::new(10.0, 0.0), end: Vec2::new(110.0, 0.0), stops: stops(&[(0.0, Rgba::new(1.0, 1.0, 1.0, 0.0)), (1.0, Rgba::new(0.2, 0.9, 0.4, 1.0))]) }; + let soft_art = |path: Path, paint: Paint, clip: u32| { + let mut m = item(path, paint); + m.masks = Some(clip); + m + }; + let mut ring = soft_art(Path::ellipse(60.0, 50.0, 30.0, 26.0), Paint::Solid(Rgba::new(0.5, 0.5, 0.5, 0.7)), 1); + ring.stroke = Some(Stroke::new(Rgba::WHITE, 6.0)); + let mut faded = soft_art(Path::rect(50.0, 10.0, 60.0, 30.0), Paint::Solid(Rgba::new(0.9, 0.2, 0.1, 1.0)), 1); + faded.color = ColorTransform::alpha(0.6); + let mut inner = soft_art(Path::rect(0.0, 0.0, 120.0, 100.0), Paint::Solid(Rgba::new(1.0, 1.0, 1.0, 0.5)), 3); + inner.clip = Some(2); + let mut dl = DisplayList { + items: vec![ + item(Path::rect(0.0, 0.0, 120.0, 100.0), Paint::Solid(Rgba::new(0.95, 0.9, 0.8, 1.0))), + clipped(item(Path::rect(0.0, 0.0, 120.0, 50.0), grad()), 0), + soft_art(Path::rect(10.0, 0.0, 100.0, 60.0), fade, 0), + clipped(item(Path::rect(0.0, 30.0, 120.0, 70.0), Paint::Solid(red)), 1), + ring, + faded, + clipped(item(Path::star(60.0, 60.0, 40.0, 15.0, 5), Paint::Solid(blue)), 3), + mask(Path::rect(20.0, 40.0, 50.0, 60.0), 2), + inner, + ], + clip_parents: vec![None, None, None, Some(2)], + ..Default::default() + }; + dl.set_clip_mode(0, MaskMode::Alpha); + dl.set_clip_mode(1, MaskMode::Luminance); + dl.set_clip_mode(3, MaskMode::Alpha); + out.push(("soft masks", dl, view(120, 100, Some(Rgba::WHITE)))); out } @@ -270,6 +303,7 @@ fn emulate(b: &Binned, v: &View) -> Vec { let mut c = bg; let mut stack: Vec = Vec::new(); let (mut mask, mut level) = (1.0f32, 0.0f32); + let (mut level_mode, mut level_colour) = (0u32, [0.0f32; 4]); for i in 0..count { let e = b.entries_at as usize + (start + i) * 4; let (op, first, n, bd) = (b.index[e] as usize, b.index[e + 1] as usize, b.index[e + 2] as usize, b.index[e + 3]); @@ -291,10 +325,13 @@ fn emulate(b: &Binned, v: &View) -> Vec { } bn::LEVEL_BEGIN => { level = 0.0; + level_mode = b.index[e + 1]; + level_colour = [0.0; 4]; continue; } bn::LEVEL_END => { - mask *= level; + let mode = [MaskMode::Coverage, MaskMode::Alpha, MaskMode::Luminance][level_mode as usize]; + mask *= if mode.is_soft() { mode.reveal(level_colour) } else { level }; continue; } k => assert_eq!(k & bn::CTRL, 0, "unknown control entry {k:x}"), @@ -302,18 +339,7 @@ fn emulate(b: &Binned, v: &View) -> Vec { let hd = op * 4; let mut cov = entry_cover(&b.geo[first..first + n], bd, b.op_heads[hd + 1], lx, ly); let flags = b.op_heads[hd + 3]; - if flags & bn::ART != 0 { - let k = cov.clamp(0.0, 1.0); - level = level + k - level * k; - continue; - } - if flags & bn::CLIPPED != 0 { - cov *= mask; - } - if cov <= 1e-4 { - continue; - } - let s = match b.op_heads[hd] { + let shade = || match b.op_heads[hd] { 0 => solid_of(b, op), kind => { let base = op * PAINT_VEC4S; @@ -326,6 +352,28 @@ fn emulate(b: &Binned, v: &View) -> Vec { b.paints[b.op_heads[hd + 2] as usize + i] } }; + if flags & bn::ART != 0 { + if level_mode != 0 { + if cov > 1e-4 { + let s = shade(); + let sa = s[3] * cov; + for k in 0..4 { + level_colour[k] = s[k] * cov + level_colour[k] * (1.0 - sa); + } + } + continue; + } + let k = cov.clamp(0.0, 1.0); + level = level + k - level * k; + continue; + } + if flags & bn::CLIPPED != 0 { + cov *= mask; + } + if cov <= 1e-4 { + continue; + } + let s = shade(); let sa = s[3] * cov; for k in 0..4 { c[k] = s[k] * cov + c[k] * (1.0 - sa); From 27b919f38099f39477be9f9def1bc2e33adbb215 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Thu, 12 Nov 2026 00:24:02 -0700 Subject: [PATCH 09/18] feat(render): soft masks in SVG export (mask with mask-type) and Lottie (alpha and luma track mattes) (M4) --- crates/render/src/lottie.rs | 141 +++++++++++++++++++++++++++++++++--- crates/render/src/svg.rs | 130 ++++++++++++++++++++++++++------- 2 files changed, 233 insertions(+), 38 deletions(-) diff --git a/crates/render/src/lottie.rs b/crates/render/src/lottie.rs index ce0d2af9..5f04704a 100644 --- a/crates/render/src/lottie.rs +++ b/crates/render/src/lottie.rs @@ -11,6 +11,9 @@ //! round dashes; ADR 0046); variable-width strokes are filled outlines (the polygons the //! renderer fills, dashes included). //! +//! 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 //! 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. @@ -142,6 +145,33 @@ struct Sample { opacity: f32, /// Mask outlines this artwork shows through (their union). masks: Vec, + /// A soft mask (ADR 0070) this artwork shows through: a track matte. + matte: Option, +} + +/// A soft mask as a track matte: its artwork as drawn, and whether its luminance (not its +/// opacity) reveals. +#[derive(Clone, PartialEq)] +struct Matte { + luma: bool, + art: Vec, +} + +/// What a sample's look must keep for its values to be keyframed: its structure, fill kind, +/// gradient stop count and stroke style. +type Look = (Structure, u8, usize, Option<(u8, u8, usize)>); + +fn look(s: &Sample) -> Look { + let fill = match &s.fill { + None => 0, + Some(Fill::Solid { rule: r, .. }) => 1 + rule(*r), + Some(Fill::Gradient { radial, rule: r, .. }) => 3 + u8::from(*radial) * 2 + rule(*r), + }; + let stops = match &s.fill { + Some(Fill::Gradient { stops, .. }) => stops.len(), + _ => 0, + }; + (s.paths.iter().map(|b| (b.closed, b.v.len())).collect(), fill, stops, s.stroke.as_ref().map(|l| (l.cap, l.join, l.dash.len()))) } /// A stroke in one frame, in stage space. @@ -203,6 +233,8 @@ struct Key { masks: Structure, /// Lottie layer blend mode (`bm`). blend: u8, + /// A track matte's kind (luma or alpha) and the look of each piece of its artwork. + matte: Option<(bool, Vec)>, } struct Track { @@ -295,7 +327,7 @@ fn sample(item: &DisplayItem, opacity: f32, masks: Vec, report: &mut HashSe }); (fill, stroke) }; - (fill.is_some() || stroke.is_some()).then_some(Sample { paths, fill, stroke, opacity, masks }) + (fill.is_some() || stroke.is_some()).then_some(Sample { paths, fill, stroke, opacity, masks, matte: None }) } /// The movie's frames `from..=to` (movie frames, 0-based) as a Lottie animation named `name`. @@ -316,6 +348,14 @@ pub fn to_lottie(doc: &Document, name: &str, from: u32, to: u32, background: boo let dl = crate::stroke::outline_variable_strokes(&full); // Mask artwork per clip, in stage space. let mut clip_art: Vec> = vec![Vec::new(); dl.clip_parents.len()]; + // Soft masks' artwork as drawn, per clip (ADR 0070). + let mut soft_art: Vec> = vec![Vec::new(); dl.clip_parents.len()]; + for item in dl.items.iter().filter(|i| i.masks.is_some_and(|c| dl.clip_mode(c).is_soft()) && !i.guide) { + let mut ignored = HashSet::new(); + if let (Some(a), Some(s)) = (item.masks.and_then(|c| soft_art.get_mut(c as usize)), sample(item, 1.0, Vec::new(), &mut ignored)) { + a.push(s); + } + } for item in dl.items.iter().filter(|i| i.fill.is_some()) { if let Some(a) = item.masks.and_then(|c| clip_art.get_mut(c as usize)) { a.extend(beziers(&item.path, &item.transform).into_iter().map(|mut b| { @@ -332,16 +372,24 @@ pub fn to_lottie(doc: &Document, name: &str, from: u32, to: u32, background: boo continue; } let mut flags: HashSet<&'static str> = HashSet::new(); + let mut matte = None; let masks = match item.clip { None => Vec::new(), Some(c) => { if dl.clip_parents.get(c as usize).copied().flatten().is_some() { flags.insert("nested masks (only the innermost is kept)"); } - match clip_art.get(c as usize) { - // A clip with no mask artwork hides everything in it. - Some(a) if !a.is_empty() => a.clone(), - _ => continue, + let art = if dl.clip_mode(c).is_soft() { soft_art.get(c as usize).map(Vec::len) } else { clip_art.get(c as usize).map(Vec::len) }; + // A clip with no mask artwork hides everything in it. + if art.unwrap_or(0) == 0 { + continue; + } + if dl.clip_mode(c).is_soft() { + // A soft mask is a track matte: alpha, or luma. + matte = soft_art.get(c as usize).map(|a| Matte { luma: dl.clip_mode(c) == anicraft_doc::MaskMode::Luminance, art: a.clone() }); + Vec::new() + } else { + clip_art.get(c as usize).cloned().unwrap_or_default() } } }; @@ -373,11 +421,12 @@ pub fn to_lottie(doc: &Document, name: &str, from: u32, to: u32, background: boo flags.insert(if blend.is_some() { "blend modes (applied shape by shape)" } else { "Subtract, Invert, Alpha and Erase blending (Lottie has no equivalent; drawn normally)" }); } let blend = blend.unwrap_or(0); - let Some(s) = sample(item, opacity, masks, &mut flags) else { + let Some(mut s) = sample(item, opacity, masks, &mut flags) else { // Not exported: counted by element (ids above every track index). record(&mut notes, flags, usize::MAX - (item.element.0 as usize).min(usize::MAX / 2)); continue; }; + s.matte = matte; let shape: Structure = s.paths.iter().map(|b| (b.closed, b.v.len())).collect(); let occurrence = { let c = seen.entry((item.layer.0, item.element.0, shape.clone())).or_insert(0); @@ -401,6 +450,7 @@ pub fn to_lottie(doc: &Document, name: &str, from: u32, to: u32, background: boo stroke: s.stroke.as_ref().map(|l| (l.cap, l.join, l.dash.len())), masks: s.masks.iter().map(|b| (b.closed, b.v.len())).collect(), blend, + matte: s.matte.as_ref().map(|m| (m.luma, m.art.iter().map(look).collect())), }; let ti = match open.get(&key).copied().filter(|&ti| tracks.get(ti).is_some_and(|tr| tr.last + 1 == t)) { Some(ti) => ti, @@ -464,15 +514,23 @@ pub fn to_lottie(doc: &Document, name: &str, from: u32, to: u32, background: boo let frames = to - from + 1; let mut layers: Vec = Vec::with_capacity(tracks.len() + 1); - // Lottie lists layers top first. - for (ind, &ti) in bottom_up.iter().rev().enumerate() { + // Lottie lists layers top first; a track matte comes just above the layer it mattes. + for &ti in bottom_up.iter().rev() { let Some(tr) = tracks.get(ti) else { continue }; - layers.push(layer(tr, ind + 1)); + if let Some(m) = matte_layer(tr, layers.len() + 1) { + layers.push(m); + let mut l = layer(tr, layers.len() + 1); + l["tt"] = json!(if tr.key.matte.as_ref().is_some_and(|(luma, _)| *luma) { 3 } else { 1 }); + layers.push(l); + } else { + layers.push(layer(tr, layers.len() + 1)); + } } - let shape_layers = layers.len(); + let shape_layers = layers.iter().filter(|l| l.get("td").is_none()).count(); + let mattes = layers.len() - shape_layers; if background { let bg = doc.stage.background.sanitized(); - layers.push(json!({"ddd": 0, "ind": shape_layers + 1, "ty": 1, "nm": "Stage", "sr": 1, "ks": static_ks(), "ao": 0, "ip": 0, "op": frames, "st": 0, "bm": 0, + layers.push(json!({"ddd": 0, "ind": shape_layers + mattes + 1, "ty": 1, "nm": "Stage", "sr": 1, "ks": static_ks(), "ao": 0, "ip": 0, "op": frames, "st": 0, "bm": 0, "sc": bg.to_hex(), "sw": doc.stage.width, "sh": doc.stage.height})); } let root = json!({ @@ -519,6 +577,25 @@ fn static_ks() -> Value { json!({"o": {"a": 0, "k": 100}, "r": {"a": 0, "k": 0}, "p": {"a": 0, "k": [0, 0, 0]}, "a": {"a": 0, "k": [0, 0, 0]}, "s": {"a": 0, "k": [100, 100, 100]}}) } +/// The track matte a track shows through (a soft mask, ADR 0070), as a matte layer (`td`): each +/// piece of the mask's artwork as a group, top first, with its paint and opacity. +fn matte_layer(tr: &Track, ind: usize) -> Option { + let (_, looks) = tr.key.matte.as_ref()?; + let mut groups: Vec = Vec::with_capacity(looks.len()); + for (k, (shape, _, _, stroke)) in looks.iter().enumerate().rev() { + let frames: Vec<(u32, Sample)> = tr.frames.iter().filter_map(|(t, s)| Some((*t, s.matte.as_ref()?.art.get(k)?.clone()))).collect(); + let key = Key { shape: shape.clone(), stroke: *stroke, masks: Vec::new(), blend: 0, matte: None, ..tr.key.clone() }; + let piece = Track { key, name: String::new(), first: tr.first, last: tr.last, frames, first_index: 0 }; + if let Some(g) = layer(&piece, 0).get_mut("shapes").and_then(|v| v.get_mut(0)).map(Value::take) { + groups.push(g); + } + } + Some(json!({ + "ddd": 0, "ind": ind, "ty": 4, "nm": format!("{} matte", tr.name), "sr": 1, "ks": static_ks(), "ao": 0, + "ip": tr.first, "op": tr.last + 1, "st": 0, "bm": 0, "td": 1, "shapes": groups + })) +} + /// One track as a shape layer: its outlines, then (drawn on top first, as Lottie lists them) /// the stroke and the fill, and the group transform carrying its opacity. fn layer(tr: &Track, ind: usize) -> Value { @@ -620,6 +697,48 @@ mod tests { serde_json::from_str(&e.json).unwrap() } + /// A mask layer (in `mode`) whose artwork is a white-to-clear gradient, over a masked red square. + pub(crate) fn soft_mask_doc(mode: anicraft_doc::MaskMode) -> Document { + use anicraft_doc::{ColorEffect, Element, ElementId, ElementKind, GradientStop, Layer, LayerId, LayerKind, Scene, Shape}; + use std::sync::Arc; + let mut d = Document { scenes: vec![Arc::new(Scene::new("Scene 1"))], ..Document::default() }; + let stops = vec![GradientStop { offset: 0.0, color: Rgba::WHITE }, GradientStop { offset: 1.0, color: Rgba::new(1.0, 1.0, 1.0, 0.0) }]; + let art = Shape::filled(Path::rect(0.0, 0.0, 200.0, 200.0), Paint::Linear { start: Vec2::new(0.0, 0.0), end: Vec2::new(200.0, 0.0), stops }); + let square = Shape::filled(Path::rect(20.0, 20.0, 160.0, 160.0), Paint::Solid(Rgba::new(1.0, 0.0, 0.0, 1.0))); + for (id, kind, parent, shape) in [(1, LayerKind::Mask, None, art), (2, LayerKind::Normal, Some(LayerId(1)), square)] { + let mut l = Layer::new(LayerId(id), format!("L{id}")); + l.kind = kind; + l.parent = parent; + l.mask_mode = if kind == LayerKind::Mask { mode } else { Default::default() }; + Arc::make_mut(&mut l.keyframes[0]).elements.push(Arc::new(Element { id: ElementId(100 + id), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Shape(shape) })); + d.timeline_mut(0).layers.push(Arc::new(l)); + } + d + } + + #[test] + fn soft_masks_become_track_mattes() { + use anicraft_doc::MaskMode; + for (mode, tt) in [(MaskMode::Alpha, 1), (MaskMode::Luminance, 3)] { + let e = to_lottie(&soft_mask_doc(mode), "soft", 0, 0, false); + let v = parse(&e); + let layers = v["layers"].as_array().unwrap(); + assert_eq!((e.layers, layers.len()), (1, 2), "{mode:?}: one shape layer and its matte"); + // The matte comes first (above), marked td; the layer under it uses it. + assert_eq!(layers[0]["td"], 1); + assert_eq!(layers[1]["tt"], tt); + assert!(layers[1].get("masksProperties").is_none(), "no layer mask for a soft mask"); + // The matte holds the mask's artwork as drawn: its gradient fill. + let it = &layers[0]["shapes"][0]["it"]; + assert!(it.as_array().unwrap().iter().any(|x| x["ty"] == "gf"), "{it}"); + assert_eq!((layers[0]["ind"].as_u64(), layers[1]["ind"].as_u64()), (Some(1), Some(2))); + } + // A coverage mask stays a layer mask. + let v = parse(&to_lottie(&soft_mask_doc(MaskMode::Coverage), "hard", 0, 0, false)); + assert_eq!(v["layers"].as_array().unwrap().len(), 1); + assert_eq!(v["layers"][0]["hasMask"], true); + } + #[test] fn beziers_bake_lines_quads_and_closing_points() { let mut p = Path::new(); diff --git a/crates/render/src/svg.rs b/crates/render/src/svg.rs index 14d24ada..f0f55234 100644 --- a/crates/render/src/svg.rs +++ b/crates/render/src/svg.rs @@ -9,7 +9,8 @@ //! * colour effects (every style, ADR 0056) are baked into every colour and stop, and drawn //! on bitmaps through an `feColorMatrix` (alpha alone as `fill-opacity`); //! * masks become `clipPath`s (fill areas only, nested through `clip-path` on the clip), and an -//! empty mask clips everything, as on the stage; +//! empty mask clips everything, as on the stage; soft masks (ADR 0070) become `mask`s with +//! their `mask-type` (alpha, or the default luminance), their artwork drawn as it looks; //! * outline-mode layers are hairlines in the layer colour; //! * variable-width strokes are filled outlines: the polygons the renderer fills. //! @@ -31,12 +32,37 @@ pub fn to_svg(dl: &DisplayList, stage: &Stage) -> String { // Each bitmap is embedded once (by its pixels), then used by every fill that shows it. let mut images: Vec<(usize, bool, String)> = Vec::new(); - // Clips, in order (a parent always precedes its children; anything else clips all). + // Clips, in order (a parent always precedes its children; anything else clips all). A + // coverage clip is a `clipPath`; a soft one (ADR 0070) a `mask` with its `mask-type`, its + // artwork drawn as it looks inside whatever clips the mask itself. for (i, parent) in dl.clip_parents.iter().enumerate() { let parent = parent.filter(|&p| (p as usize) < i); let malformed = dl.clip_parents.get(i).copied().flatten().is_some() && parent.is_none(); + let mode = dl.clip_mode(i as u32); + if mode.is_soft() { + let kind = if mode == anicraft_doc::MaskMode::Alpha { " mask-type=\"alpha\"" } else { "" }; + let mut art = String::new(); + if !malformed { + for item in dl.items.iter().filter(|it| it.masks == Some(i as u32) && !it.guide) { + if let Some(d) = stage_path(item) { + draw(item, &d, "", &mut art, &mut defs, &mut grad, &mut images); + } + } + } + let _ = write!(defs, ""); + match parent { + Some(p) => { + let _ = write!(defs, "{art}", clip_attrs(dl, p)); + } + None => defs.push_str(&art), + } + defs.push_str(""); + continue; + } let _ = write!(defs, "'); @@ -76,30 +102,8 @@ pub fn to_svg(dl: &DisplayList, stage: &Stage) -> String { let _ = write!(body, "", num(a)); open.push(g); } - let clip = item.clip.filter(|&c| (c as usize) < dl.clip_parents.len()).map(|c| format!(" clip-path=\"url(#c{c})\"")).unwrap_or_default(); - if let Some(color) = item.outline { - // Outline mode: a hairline in the layer colour, no fill. - let _ = write!(body, "", color_attrs("stroke", color)); - continue; - } - if let Some(fill) = &item.fill - && let Some(paint) = paint_attr(fill, &item.transform, &item.color, &mut defs, &mut grad, item.image.as_ref().map(|px| (px, item.smooth)), &mut images) - { - let _ = write!(body, "", rule_attr("fill-rule", item.fill_rule)); - } - if let Some(st) = &item.stroke { - let width = st.width * item.transform.mean_scale(); - if width.is_finite() && width > 0.0 { - let c = item.color.apply(st.color); - let _ = write!( - body, - "", - color_attrs("stroke", c), - num(width), - style_attrs(st, item.transform.mean_scale()) - ); - } - } + let clip = item.clip.filter(|&c| (c as usize) < dl.clip_parents.len()).map(|c| clip_attrs(dl, c)).unwrap_or_default(); + draw(item, &d, &clip, &mut body, &mut defs, &mut grad, &mut images); } for _ in open { body.push_str(""); @@ -120,6 +124,47 @@ pub fn to_svg(dl: &DisplayList, stage: &Stage) -> String { out } +/// What clips something drawn in clip `c`: `clip-path` for a coverage clip (its coverage +/// parents chained in the `clipPath`s) and `mask` for the first soft clip on the way out (which +/// carries every clip around it), or `mask` alone when `c` is soft. +fn clip_attrs(dl: &DisplayList, c: u32) -> String { + if dl.clip_mode(c).is_soft() { + return format!(" mask=\"url(#c{c})\""); + } + let mut out = format!(" clip-path=\"url(#c{c})\""); + let mut at = c; + for _ in 0..dl.clip_parents.len() { + let Some(p) = dl.clip_parents.get(at as usize).copied().flatten().filter(|&p| p < at) else { break }; + if dl.clip_mode(p).is_soft() { + let _ = write!(out, " mask=\"url(#c{p})\""); + break; + } + at = p; + } + out +} + +/// One item's fill and stroke (or its outline-mode hairline), clipped by `clip`'s attributes. +fn draw(item: &DisplayItem, d: &str, clip: &str, body: &mut String, defs: &mut String, grad: &mut usize, images: &mut Vec<(usize, bool, String)>) { + if let Some(color) = item.outline { + // Outline mode: a hairline in the layer colour, no fill. + let _ = write!(body, "", color_attrs("stroke", color)); + return; + } + 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)); + } + if let Some(st) = &item.stroke { + let width = st.width * item.transform.mean_scale(); + if width.is_finite() && width > 0.0 { + let c = item.color.apply(st.color); + let _ = write!(body, "", color_attrs("stroke", c), num(width), style_attrs(st, item.transform.mean_scale())); + } + } +} + /// 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() { @@ -552,6 +597,37 @@ mod tests { assert_eq!(svg.matches(""), "{svg}"); + assert!(svg.contains(""), "luminance is the default type: {svg}"); + // A soft mask's artwork keeps its paint, opacity and stroke. + assert!(svg.contains("fill=\"#ff0000\" fill-opacity=\"0.5\"") && svg.contains("stroke=\"#ffffff\" stroke-width=\"2\""), "{svg}"); + // Masked shapes: by the mask, or by the clip path plus the first mask around it. + assert!(svg.contains("mask=\"url(#c1)\"/>") && svg.contains("mask=\"url(#c2)\"/>")); + assert!(svg.contains(""), "no clip-path to a mask: {svg}"); + assert!(svg.contains("clip-path=\"url(#c3)\" mask=\"url(#c2)\"/>"), "{svg}"); + } + #[test] fn the_sample_exports_deterministically_and_hostile_input_is_safe() { let d = sample::demo(); From 02842502f74c1843a6c7b77c326df29a4914f617 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Thu, 12 Nov 2026 00:25:05 -0700 Subject: [PATCH 10/18] feat(render): soft masks in the HTML canvas export (M4) --- crates/render/src/html.rs | 12 ++++++++- crates/render/src/html/canvas.js | 44 ++++++++++++++++++++++++-------- crates/render/src/html/player.js | 10 +++++--- crates/render/src/html_tests.rs | 11 ++++++++ 4 files changed, 62 insertions(+), 15 deletions(-) diff --git a/crates/render/src/html.rs b/crates/render/src/html.rs index dead1671..b8d54f92 100644 --- a/crates/render/src/html.rs +++ b/crates/render/src/html.rs @@ -30,7 +30,7 @@ use crate::stroke::stroke_outline; use anicraft_doc::actions::as3::Decls; use anicraft_doc::actions::{Action, FrameRef, Seg, Target}; use anicraft_doc::player::TimelineRef; -use anicraft_doc::{BlendMode, ColorTransform, Document, Element, ElementKind, FIELD_GUTTER, FrameScript, Join, Layer, LayerKind, MAX_FIELD_CHARS, Paint, Rgba, SoundFormat, SoundSync, SymbolId, SymbolKind, TextAlign, Timeline, base64_encode, evaluate_guided, guide_walk, instance_start}; +use anicraft_doc::{BlendMode, ColorTransform, Document, Element, ElementKind, FIELD_GUTTER, FrameScript, Join, Layer, LayerKind, MAX_FIELD_CHARS, MaskMode, Paint, Rgba, SoundFormat, SoundSync, SymbolId, SymbolKind, TextAlign, Timeline, base64_encode, evaluate_guided, guide_walk, instance_start}; use anicraft_geom::{Affine, FillRule, Path, PathCmd}; use serde_json::{Map, Value, json}; use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque}; @@ -590,6 +590,16 @@ impl<'a> Bake<'a> { } if layer.kind == LayerKind::Mask { entry.insert("mk".into(), json!(slots.get(&layer.id.0).copied().unwrap_or(0))); + // A soft mask (ADR 0070): 1 alpha, 2 luminance. + match layer.mask_mode { + MaskMode::Coverage => {} + MaskMode::Alpha => { + entry.insert("mm".into(), json!(1)); + } + MaskMode::Luminance => { + entry.insert("mm".into(), json!(2)); + } + } } else if let Some(&slot) = layer.parent.and_then(|p| slots.get(&p.0)) { entry.insert("c".into(), json!(slot)); } diff --git a/crates/render/src/html/canvas.js b/crates/render/src/html/canvas.js index b7fdad72..997c0cbe 100644 --- a/crates/render/src/html/canvas.js +++ b/crates/render/src/html/canvas.js @@ -380,16 +380,22 @@ item: function (it) { const path = paths[it.p]; if (!path || !AniCraft.finite(it.m)) return; + let g = stack[stack.length - 1].ctx; if (it.masks !== null) { - // Mask artwork: its fill area only, opaque. const mk = masks.get(it.masks); - if (!mk || it.f < 0) return; - set(mk.ctx, it.m); - mk.ctx.fillStyle = "#000"; - mk.ctx.fill(path, it.eo ? "evenodd" : "nonzero"); - return; + if (!mk) return; + if (mk.mode) { + // A soft mask's artwork (ADR 0070) is drawn as it looks. + g = mk.l.ctx; + } else { + // Mask artwork: its fill area only, opaque. + if (it.f < 0) return; + set(mk.l.ctx, it.m); + mk.l.ctx.fillStyle = "#000"; + mk.l.ctx.fill(path, it.eo ? "evenodd" : "nonzero"); + return; + } } - const g = stack[stack.length - 1].ctx; if (it.f >= 0) { const style = paintStyle(g, it.f, it.c); if (style) { @@ -455,13 +461,29 @@ clipEnd: function () { release(stack.pop()); }, - maskBegin: function (id) { - masks.set(id, layer()); + maskBegin: function (id, mode) { + masks.set(id, { l: layer(), mode: mode }); }, maskEnd: function (id, open) { - const mk = masks.get(id); + const entry = masks.get(id); masks.delete(id); - if (!mk) return; + if (!entry) return; + const mk = entry.l; + if (open && entry.mode === 2) { + // A luminance mask: each pixel's luminance (sRGB coefficients) times its opacity + // becomes its opacity. + mk.ctx.setTransform(1, 0, 0, 1, 0, 0); + const img = mk.ctx.getImageData(0, 0, mk.canvas.width, mk.canvas.height); + const d = img.data; + for (let i = 0; i < d.length; i += 4) { + const l = (0.2125 * d[i] + 0.7154 * d[i + 1] + 0.0721 * d[i + 2]) * (d[i + 3] / 255); + d[i] = 0; + d[i + 1] = 0; + d[i + 2] = 0; + d[i + 3] = Math.round(l); + } + mk.ctx.putImageData(img, 0, 0); + } if (open) { const l = stack.pop(); l.ctx.setTransform(1, 0, 0, 1, 0, 0); diff --git a/crates/render/src/html/player.js b/crates/render/src/html/player.js index e6cd07f9..94a47958 100644 --- a/crates/render/src/html/player.js +++ b/crates/render/src/html/player.js @@ -292,7 +292,7 @@ var AniCraft = (function () { // the group they fade with; `clips` holds each clip's parent, `groups` each group. `v`, when // given, hears every item and where clips and groups open and close (canvas.js draws so). function evaluate(M, st, v) { - const dl = { items: [], clips: [], groups: [] }; + const dl = { items: [], clips: [], modes: [], groups: [] }; const scene = M.scenes[st.scene]; const tli = scene ? scene.tl : 0; // A scene seen through its camera: the camera's tint colours everything. @@ -320,7 +320,11 @@ var AniCraft = (function () { for (const L of content(M, tl, frame).l) { let clip = cx.clip, masks = cx.masks; const isMask = cx.masks === null && L.mk !== undefined; - if (isMask) masks = slots[L.mk]; + if (isMask) { + masks = slots[L.mk]; + // A soft mask's mode (ADR 0070): 1 alpha, 2 luminance; coverage when absent. + if (L.mm) dl.modes[masks] = L.mm; + } else if (cx.masks === null && L.c !== undefined) clip = slots[L.c]; if (v && cx.masks === null && !isMask) { // Masked layers draw into their clip; one that never meets its mask stays hidden. @@ -334,7 +338,7 @@ var AniCraft = (function () { open = want; } } - if (v && isMask) v.maskBegin(masks); + if (v && isMask) v.maskBegin(masks, L.mm || 0); const lcx = L.v ? Object.assign({}, cx, { xf: L.v }) : cx; for (const e of L.e) evalElement(M, e, lcx, clip, masks, dl, play, v); if (v && isMask) { diff --git a/crates/render/src/html_tests.rs b/crates/render/src/html_tests.rs index 4bf23777..01b8fd7d 100644 --- a/crates/render/src/html_tests.rs +++ b/crates/render/src/html_tests.rs @@ -94,6 +94,8 @@ fn fixture() -> Document { }); let mut mask = Layer::new(LayerId(6), "mask"); mask.kind = LayerKind::Mask; + // A soft mask (ADR 0070): the player numbers its clip's mode as the evaluator does. + mask.mask_mode = anicraft_doc::MaskMode::Luminance; mask.keyframes = vec![kf(0, 30, vec![rect(5005, 400.0, 0.0, 20.0, 100.0, 0)], vec![], "")]; let mut masked = Layer::new(LayerId(7), "masked"); masked.parent = Some(LayerId(6)); @@ -291,6 +293,15 @@ fn same_display_list(js: &mut Js, m: &Movie, doc: &Document, st: &PlayerState, w } let clips: Vec> = ours["clips"].as_array().unwrap().iter().map(|v| v.as_u64().map(|x| x as u32)).collect(); assert_eq!(clips, dl.clip_parents, "{when}: clips"); + let modes = ours["modes"].as_array().unwrap(); + for c in 0..dl.clip_parents.len() { + let want = match dl.clip_mode(c as u32) { + anicraft_doc::MaskMode::Coverage => 0, + anicraft_doc::MaskMode::Alpha => 1, + anicraft_doc::MaskMode::Luminance => 2, + }; + assert_eq!(modes.get(c).and_then(Value::as_u64).unwrap_or(0), want, "{when}: clip {c} mode"); + } let groups = ours["groups"].as_array().unwrap(); assert_eq!(groups.len(), dl.groups.len(), "{when}: groups"); for (a, b) in groups.iter().zip(&dl.groups) { From 623fb1f82010e3a8390ce32c4c911dda97e1752f Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Thu, 12 Nov 2026 00:28:21 -0700 Subject: [PATCH 11/18] feat(engine): mask type command and Layer Properties: shape, alpha or luminance masks (M4) --- crates/doc/src/lib.rs | 1 + crates/engine/src/cmds_layer.rs | 41 +++++++++++++++++++++++++-- crates/engine/src/cmds_layer_tests.rs | 27 +++++++++++++++++- src/layer_props.rs | 40 +++++++++++++++++++++++++- 4 files changed, 104 insertions(+), 5 deletions(-) diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index c600136f..1d38ab1c 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -910,6 +910,7 @@ impl PartialEq for Layer { && self.depth.to_bits() == o.depth.to_bits() && self.volume.to_bits() == o.volume.to_bits() && self.muted == o.muted + && self.mask_mode == o.mask_mode && match (&self.armature, &o.armature) { (Some(a), Some(b)) => arc_eq(a, b), (a, b) => a.is_none() && b.is_none(), diff --git a/crates/engine/src/cmds_layer.rs b/crates/engine/src/cmds_layer.rs index 23b03ca3..6036f174 100644 --- a/crates/engine/src/cmds_layer.rs +++ b/crates/engine/src/cmds_layer.rs @@ -1,13 +1,15 @@ //! Layer view properties saved in the document (ADR 0061): each layer's onion skin toggle, its //! colour (outlines and the timeline bar), View as Outlines, its row height, and Layer //! Properties, which sets several of them (and the name, type, show and lock) as one step. +//! A mask layer's mask type (ADR 0070) is set here too: by area (Animate's masks), by the +//! artwork's opacity, or by its brightness. //! //! Behaviour learned from Adobe's public help pages on layers and onion skinning and from //! watching the program; nothing was copied. use crate::params::*; use crate::{CommandSpec, EngineError, Result, Session}; -use anicraft_doc::{Layer, LayerId, LayerKind, MAX_LAYER_HEIGHT}; +use anicraft_doc::{Layer, LayerId, LayerKind, MAX_LAYER_HEIGHT, MaskMode}; use serde_json::{Value, json}; use std::sync::Arc; @@ -29,16 +31,25 @@ pub fn specs() -> Vec { ), c("layer.set_color", "Layer Colour", "", None, "{color: \"#rrggbb\", layer?} the layer's colour: its outlines in outline mode and its bar on the timeline", true, set_color), c("layer.set_height", "Layer Height", "", None, "{height: 100 | 200 | 300 (percent of a normal row), layer?} the layer's row height on the timeline", true, set_height), + c( + "layer.set_mask", + "Mask Type", + "", + None, + "{mask: coverage|alpha|luminance, layer?} how a mask layer reveals the layers it masks: coverage (its fills' area, as in Animate), alpha (its artwork's opacity: gradients and faded shapes make soft edges) or luminance (its brightness: white shows, black hides; SVG's mask) (ADR 0070)", + true, + set_mask, + ), c( "layer.set_properties", "Layer Properties", "Modify/Timeline", None, - "{layer?, name?, type?: normal|mask|masked|guide|guided, 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", + "{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", true, set_properties, ), - c("layer.properties", "Get Layer Properties", "", None, "{layer?} the layer's name, type, colour, outline, height (percent), visible, locked and onion", false, |s, p| properties(s, layer_id(s, p)?)), + c("layer.properties", "Get Layer Properties", "", None, "{layer?} the layer's name, type, mask type (mask layers), colour, outline, height (percent), visible, locked and onion", false, |s, p| properties(s, layer_id(s, p)?)), ] } @@ -101,6 +112,22 @@ fn set_height(s: &mut Session, p: &Value) -> Result { Ok(json!({"height": u32::from(l.height()) * 100})) } +/// `mask`: a mask type's key. +fn mask_param(p: &Value) -> Result> { + opt_str(p, "mask")?.map(|k| MaskMode::from_key(k).ok_or_else(|| EngineError::Param(format!("'mask' is coverage, alpha or luminance, not '{k}'")))).transpose() +} + +fn set_mask(s: &mut Session, p: &Value) -> Result { + let mode = mask_param(p)?.ok_or_else(|| EngineError::Param("param 'mask' (coverage, alpha or luminance) is required".into()))?; + let id = layer_id(s, p)?; + let l = s.layer_mut(Some(id))?; + if l.kind != LayerKind::Mask { + return Err(EngineError::State("only a mask layer has a mask type".into())); + } + l.mask_mode = mode; + Ok(json!({"layer": id.0, "mask": mode.key()})) +} + fn set_properties(s: &mut Session, p: &Value) -> Result { let id = layer_id(s, p)?; // Every param is read (and checked) before anything changes. @@ -112,6 +139,7 @@ fn set_properties(s: &mut Session, p: &Value) -> Result { let color = opt_color(p, "color")?; let outline = opt_bool(p, "outline")?; let height = height_param(p)?; + let mask = mask_param(p)?; let (visible, locked, onion) = (opt_bool(p, "visible")?, opt_bool(p, "locked")?, opt_bool(p, "onion")?); if let Some(ty) = ty { let now = crate::cmds_timeline::layer_type_json(s, id); @@ -120,6 +148,12 @@ fn set_properties(s: &mut Session, p: &Value) -> Result { } } let l = s.layer_mut(Some(id))?; + if let Some(m) = mask { + if l.kind != LayerKind::Mask { + return Err(EngineError::State("only a mask layer has a mask type".into())); + } + l.mask_mode = m; + } if let Some(n) = name { l.name = n; } @@ -151,6 +185,7 @@ fn properties(s: &Session, id: LayerId) -> Result { "layer": id.0, "name": l.name, "type": ty, + "mask": (l.kind == LayerKind::Mask).then(|| l.mask_mode.key()), "color": l.color.to_hex(), "outline": l.outline, "height": u32::from(l.height()) * 100, diff --git a/crates/engine/src/cmds_layer_tests.rs b/crates/engine/src/cmds_layer_tests.rs index b7af3b2a..92006344 100644 --- a/crates/engine/src/cmds_layer_tests.rs +++ b/crates/engine/src/cmds_layer_tests.rs @@ -154,7 +154,7 @@ fn layer_properties_set_everything_as_one_step_or_nothing() { let (mut s, top, bottom) = two_walks(); let undo = s.history.undo_len(); let r = run(&mut s, "layer.set_properties", json!({"layer": bottom.0, "name": "Sky", "color": "#123456", "outline": true, "height": 200, "locked": true, "visible": false, "onion": false, "type": "guide"})); - assert_eq!(r, json!({"layer": bottom.0, "name": "Sky", "type": "guide", "color": "#123456", "outline": true, "height": 200, "visible": false, "locked": true, "onion": false})); + assert_eq!(r, json!({"layer": bottom.0, "name": "Sky", "type": "guide", "mask": null, "color": "#123456", "outline": true, "height": 200, "visible": false, "locked": true, "onion": false})); assert_eq!(s.history.undo_len(), undo + 1, "one undo step"); assert_eq!(run(&mut s, "layer.properties", json!({"layer": bottom.0})), r); // The same type again changes nothing (a masked layer stays masked by the same mask). @@ -174,6 +174,31 @@ fn layer_properties_set_everything_as_one_step_or_nothing() { assert!(s.execute("layer.properties", &json!({"layer": 999_999})).is_err()); } +#[test] +fn a_mask_layer_takes_a_mask_type() { + let (mut s, top, bottom) = two_walks(); + // Only a mask layer has one. + assert!(s.execute("layer.set_mask", &json!({"layer": top.0, "mask": "alpha"})).is_err()); + assert!(s.execute("layer.set_properties", &json!({"layer": top.0, "name": "X", "mask": "alpha"})).is_err()); + assert_eq!(layer(&s, top).name, "Layer 2", "nothing changed"); + // Made a mask and soft in one step; then by itself. + let r = run(&mut s, "layer.set_properties", json!({"layer": top.0, "type": "mask", "mask": "luminance"})); + assert_eq!((r["type"].as_str(), r["mask"].as_str()), (Some("mask"), Some("luminance"))); + assert_eq!(layer(&s, top).mask_mode, anicraft_doc::MaskMode::Luminance); + assert_eq!(run(&mut s, "layer.set_mask", json!({"layer": top.0, "mask": "alpha"}))["mask"], "alpha"); + assert!(s.execute("layer.set_mask", &json!({"layer": top.0, "mask": "soft"})).is_err()); + assert!(s.execute("layer.set_mask", &json!({"layer": top.0})).is_err()); + assert_eq!(run(&mut s, "layer.properties", json!({"layer": bottom.0}))["mask"], Value::Null); + // The stage shows it at once: the masked square at its edge (art opaque → fully shown). + run(&mut s, "layer.set_properties", json!({"layer": bottom.0, "type": "masked"})); + let dl = s.display_list(); + assert_eq!(dl.clip_mode(0), anicraft_doc::MaskMode::Alpha); + // Undo goes back to luminance, then to coverage. + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + assert_eq!(layer(&s, top).mask_mode, anicraft_doc::MaskMode::Luminance); +} + #[test] fn onion_and_height_are_saved_and_older_files_open_with_the_defaults() { let (mut s, top, bottom) = two_walks(); diff --git a/src/layer_props.rs b/src/layer_props.rs index 0b3e0322..a84ba0b0 100644 --- a/src/layer_props.rs +++ b/src/layer_props.rs @@ -1,5 +1,6 @@ //! The Layer Properties dialog (ADR 0061), as in Animate: name, show and lock, type, outline -//! colour, View layer as outlines, onion skin and layer height. Opened by double-clicking a +//! colour, View layer as outlines, onion skin and layer height; a mask layer's mask type (ADR +//! 0070: by shape, as in Animate, or soft, by alpha or luminance). Opened by double-clicking a //! layer's icon, from the layer's right-click menu or Modify › Timeline. OK sends one //! `layer.set_properties` (one undo step) with what changed; Cancel changes nothing. @@ -20,6 +21,8 @@ pub struct LayerPropsDialog { /// `camera`, `armature`). pub ty: String, pub color: [u8; 3], + /// A mask layer's mask type: `coverage`, `alpha` or `luminance`. + pub mask: String, pub outline: bool, pub onion: bool, /// Rows: 1, 2 or 3 (100, 200, 300 %). @@ -48,6 +51,7 @@ pub fn open(app: &mut App, layer: Option) { locked: l.locked, ty: p.get("type").and_then(Value::as_str).unwrap_or("normal").to_string(), color: [c.r(), c.g(), c.b()], + mask: l.mask_mode.key().to_string(), outline: l.outline, onion: l.onion, height: l.height(), @@ -61,6 +65,15 @@ fn types() -> [(&'static str, &'static str); 5] { [("normal", tr!("Normal")), ("guide", tr!("Guide")), ("guided", tr!("Guided")), ("mask", tr!("Mask")), ("masked", tr!("Masked"))] } +/// The mask types, with their names and what each does. +fn mask_types() -> [(&'static str, &'static str, &'static str); 3] { + [ + ("coverage", tr!("Shape"), tr!("The mask's fills reveal fully, whatever their colour or opacity (as in Animate)")), + ("alpha", tr!("Alpha"), tr!("The mask's opacity reveals: gradients to transparent and faded shapes give soft edges")), + ("luminance", tr!("Luminance"), tr!("The mask's brightness reveals: white shows, black hides, greys show partly")), + ] +} + fn type_label(ty: &str) -> &'static str { match ty { "folder" => tr!("Folder"), @@ -127,6 +140,17 @@ pub fn window(app: &mut App, ctx: &egui::Context) { } }); }); + if d.ty == "mask" { + form_row(ui, FORM_LABEL_DIALOG, tr!("Mask type"), |ui| { + ui.horizontal(|ui| { + for (k, name, what) in mask_types() { + if ui.radio(d.mask == k, name).on_hover_text(what).clicked() { + d.mask = k.to_string(); + } + } + }); + }); + } form_row(ui, FORM_LABEL_DIALOG, tr!("Outline colour"), |ui| { ui.color_edit_button_srgb(&mut d.color).named(tr!("Outline colour")).on_hover_text(tr!("The colour of the layer's outlines and of its bar on the timeline")); }); @@ -183,6 +207,11 @@ pub fn changes(d: &LayerPropsDialog) -> Value { "onion": d.onion, "height": u32::from(d.height) * 100, }); + let mut now = now; + // The mask type is a mask layer's (and only sent when it changes). + if d.ty == "mask" { + now["mask"] = json!(d.mask); + } let mut out = json!({"layer": d.layer.0}); if let (Some(now), Some(o)) = (now.as_object(), out.as_object_mut()) { for (k, v) in now { @@ -232,6 +261,15 @@ mod tests { open(&mut app, Some(id)); accept(&mut app); assert_eq!(app.s.history().undo_len(), steps + 1); + // A mask layer's mask type, by itself. + app.s.execute("layer.set_properties", &json!({"layer": id.0, "type": "mask"})).unwrap(); + open(&mut app, Some(id)); + let d = app.layer_props.as_mut().unwrap(); + assert_eq!(changes(d), json!({"layer": id.0})); + d.mask = "alpha".into(); + assert_eq!(changes(d), json!({"layer": id.0, "mask": "alpha"})); + accept(&mut app); + assert_eq!(app.s.timeline().layer(id).unwrap().mask_mode, anicraft_engine::doc::MaskMode::Alpha); // The menu command opens it too. app.invoke("layer.set_properties"); assert!(app.layer_props.is_some()); From a0c4a91cfa9ba4ae81eea7f4ab289c44a024d3ab Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Thu, 12 Nov 2026 00:32:06 -0700 Subject: [PATCH 12/18] feat(svg): import soft masks onto soft mask layers (luminance by default, mask-type alpha) (M4) --- crates/engine/src/cmds_file.rs | 2 + crates/engine/src/tests.rs | 52 ++++++++++++++ crates/svg/src/clip.rs | 120 +++++++++++++++++++++++---------- crates/svg/src/clip_tests.rs | 40 +++++++++-- crates/svg/src/lib.rs | 3 + 5 files changed, 179 insertions(+), 38 deletions(-) diff --git a/crates/engine/src/cmds_file.rs b/crates/engine/src/cmds_file.rs index c858d5c9..da824d59 100644 --- a/crates/engine/src/cmds_file.rs +++ b/crates/engine/src/cmds_file.rs @@ -384,6 +384,7 @@ pub(crate) fn import_to_stage(s: &mut Session, p: &Value) -> Result { let mut ml = new_layer(s, label, anicraft_doc::LayerKind::Mask, Some(fid)); // Mask layers are locked, as Animate keeps them: the mask shows, its edge hides. ml.locked = true; + ml.mask_mode = mask.mode; ml.keyframes = keys(elements(s, mask.elements)); inside = Some(ml.id); stack.push(ml); @@ -469,6 +470,7 @@ pub(crate) fn import_svg_symbol(s: &mut Session, path: &std::path::Path, name: O let mut ml = Layer::new(LayerId(s.doc.alloc_id()), if mask.name.is_empty() { "Mask".to_string() } else { mask.name.clone() }); ml.kind = LayerKind::Mask; ml.locked = true; + ml.mask_mode = mask.mode; ml.keyframes = one_key(elements(s, mask.elements)); parent = Some(ml.id); layers.push(Arc::new(ml)); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 96a3bf36..2fd1e223 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1505,6 +1505,58 @@ fn masked_frames_round_trip_through_svg_onto_mask_layers() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn soft_masks_round_trip_through_svg_onto_soft_mask_layers() { + // A grey ellipse as a luminance mask (ADR 0070) over an orange rect, on a dark background. + let mut src = Session::default(); + run(&mut src, "draw.rect", json!({"x": 0, "y": 0, "w": 640, "h": 360, "fill": "#20304a"})); + run(&mut src, "layer.new", json!({"name": "Art"})); + run(&mut src, "draw.rect", json!({"x": 100, "y": 60, "w": 400, "h": 240, "fill": "#ff6b4a"})); + run(&mut src, "layer.new", json!({"name": "Mask"})); + run(&mut src, "draw.ellipse", json!({"x": 180, "y": 80, "w": 260, "h": 200, "fill": "#808080", "stroke": null})); + run(&mut src, "layer.toggle_mask", json!({})); + run(&mut src, "layer.set_mask", json!({"mask": "luminance"})); + // The middle shows half the orange (grey #808080 is 0.502 bright) over the background. + let pm = anicraft_render::render_frame(&src.doc, 0, 1.0).unwrap(); + let px = pm.pixel(310, 180).unwrap(); + let k = 128.0 / 255.0; + let want = [k * 1.0 + (1.0 - k) * 0x20 as f32 / 255.0, k * 0x6b as f32 / 255.0 + (1.0 - k) * 0x30 as f32 / 255.0]; + assert!((px[0] - want[0]).abs() < 2e-3 && (px[1] - want[1]).abs() < 2e-3, "{px:?} vs {want:?}"); + let svg_text = crate::cmds_file::frame_svg(&src.doc, 0); + assert!(svg_text.contains("() / a.len() as f64; + assert!(mean < 0.01 && worst <= 2, "mean {mean:.3}, worst {worst} of 255"); + assert_eq!(crate::cmds_file::frame_svg(&s.doc, 0).matches(">, /// Conservative drawing-space bounds. bounds: Rect, + /// Coverage, or a soft mask's mode (then `parts` are drawn as they look and `convex` is + /// `None`: a soft region never "cuts nothing"). + mode: MaskMode, } /// Conservative drawing-space bounds of an element's artwork. @@ -59,7 +63,13 @@ impl Region { [ImportedElement { kind: ElementKind::Shape(s), transform, .. }] => convex_polygon(&s.path.transformed(transform)), _ => None, }; - Rc::new(Region { key, name: name.chars().take(128).collect(), parts, convex, bounds }) + Rc::new(Region { key, name: name.chars().take(128).collect(), parts, convex, bounds, mode: MaskMode::Coverage }) + } + + /// A soft mask's region: its content as drawn. + fn soft(key: String, name: &str, parts: Vec, mode: MaskMode) -> Rc { + let bounds = parts.iter().fold(Rect::EMPTY, |r, p| r.union(&element_bounds(p))); + Rc::new(Region { key, name: name.chars().take(128).collect(), parts, convex: None, bounds, mode }) } /// Whether the region is convex and holds all of `r`. @@ -79,9 +89,34 @@ impl Region { }) } - /// This region cut to the convex region `other`, exactly. - fn intersect(&self, other: &Region) -> Rc { - let Some(poly) = &other.convex else { return Region::new(self.key.clone(), &self.name, self.parts.clone()) }; + /// This region cut to the convex region `other`, exactly. A soft region keeps its parts' + /// paints: unstroked shapes are cut in their own space; stroked shapes, text and symbols + /// reaching outside are kept whole (reported). + fn intersect(&self, other: &Region, report: &mut Report) -> Rc { + let Some(poly) = &other.convex else { return Rc::new(Region { key: self.key.clone(), name: self.name.clone(), parts: self.parts.clone(), convex: self.convex.clone(), bounds: self.bounds, mode: self.mode }) }; + if self.mode.is_soft() { + let mut parts = Vec::with_capacity(self.parts.len()); + for p in &self.parts { + if other.contains(&element_bounds(p)) { + parts.push(p.clone()); + continue; + } + let local = p.transform.inverse().map(|inv| poly.iter().map(|q| inv.apply(*q)).collect::>()); + match (&p.kind, local) { + (ElementKind::Shape(s), Some(lp)) if s.stroke.is_none() => { + let cut = clip_convex(&s.path, &lp); + if !cut.is_empty() { + parts.push(ImportedElement { kind: ElementKind::Shape(Shape { path: Arc::new(cut), ..s.clone() }), ..p.clone() }); + } + } + _ => { + report.skip("soft mask artwork crossing its mask's edge (kept whole)"); + parts.push(p.clone()); + } + } + } + return Region::soft(format!("{}&{}", self.key, other.key), &self.name, parts, self.mode); + } let mut parts = Vec::new(); for p in &self.parts { let (path, rule) = match &p.kind { @@ -98,6 +133,13 @@ impl Region { } } +impl Region { + /// Whether nothing of what this region masks shows. + fn hides_all(&self) -> bool { + self.parts.is_empty() + } +} + /// What an item's clips come to. enum Effective { /// Nothing of it shows. @@ -296,35 +338,39 @@ impl<'a> Builder<'a> { self.children(target, &content_m, &style, 1.0, depth + 1, 0); self.resolving.pop(); let content: Vec = self.items.drain(mark..).collect(); - // Only an opaque mask is the coverage of its shapes: full alpha, no strokes, and for a - // luminance mask, white. + // An opaque mask is the coverage of its shapes (an Animate mask): full alpha, no strokes, + // and for a luminance mask, white. Any other is a soft mask (ADR 0070), its content as + // drawn. let opaque = |c: Rgba| c.a >= 0.999 && (alpha_mask || (c.r >= 0.996 && c.g >= 0.996 && c.b >= 0.996)); - let mut parts = Vec::new(); - let mut soft = false; - for it in content { - let e = it.el; - let ok = it.clips.is_empty() + let is_opaque = |it: &Item| { + let e = &it.el; + it.clips.is_empty() && e.alpha >= 0.999 && match &e.kind { ElementKind::Shape(s) => s.stroke.is_none() && matches!(s.fill, Some(Paint::Solid(c)) if opaque(c)), ElementKind::Text(t) => opaque(t.color), ElementKind::Symbol { .. } | ElementKind::Camera => false, - }; - if !ok { - soft = true; - break; - } - parts.push(match &e.kind { - ElementKind::Shape(s) => mask_part(e.name.clone(), (*s.path).clone(), e.transform, s.fill_rule), - _ => e, - }); - } - if soft { - self.report.skip("soft, faded or coloured masks (drawn unmasked)"); - return Some(Vec::new()); - } + } + }; let area = mask_part(String::new(), Path::rect(rect.min.x, rect.min.y, rect.width(), rect.height()), *m, FillRule::NonZero); - Some(vec![Region::new(format!("mask:{target:p}:{:?}", content_m.m), id, parts), Region::new(format!("maskarea:{target:p}:{:?}:{rect:?}", m.m), id, vec![area])]) + let area = Region::new(format!("maskarea:{target:p}:{:?}:{rect:?}", m.m), id, vec![area]); + let key = format!("mask:{target:p}:{:?}", content_m.m); + if !content.iter().all(is_opaque) { + if content.iter().any(|it| !it.clips.is_empty()) { + self.report.skip("clip paths and masks inside a mask (ignored)"); + } + let mode = if alpha_mask { MaskMode::Alpha } else { MaskMode::Luminance }; + let parts = content.into_iter().map(|it| it.el).collect(); + return Some(vec![Region::soft(key, id, parts, mode), area]); + } + let parts = content + .into_iter() + .map(|it| match &it.el.kind { + ElementKind::Shape(s) => mask_part(it.el.name.clone(), (*s.path).clone(), it.el.transform, s.fill_rule), + _ => it.el, + }) + .collect(); + Some(vec![Region::new(key, id, parts), area]) } /// What an item's clips come to (combinations are cached by key; `None` = hidden). @@ -332,7 +378,7 @@ impl<'a> Builder<'a> { let b = element_bounds(&it.el); let mut keep: Vec> = Vec::new(); for r in &it.clips { - if r.parts.is_empty() || r.bounds.intersect(&b).is_empty() { + if r.hides_all() || r.bounds.intersect(&b).is_empty() { return Effective::Hidden; } if r.contains(&b) || keep.iter().any(|k| k.key == r.key) { @@ -361,12 +407,18 @@ impl<'a> Builder<'a> { if curved.len() > 1 { self.report.skip("curved clips inside curved clips (drawn with the inner one)"); } + // A soft mask is kept over a curved clip (it is what the artwork fades by). + let mut curved = curved; + if let Some(i) = curved.iter().position(|r| r.mode.is_soft()) { + curved.swap(0, i); + } let mut rest = convex.into_iter(); let base = match curved.first() { Some(c) => Some(c.clone()), None => rest.next(), }; - let r = base.map(|base| rest.fold(base, |acc, c| acc.intersect(&c))).filter(|r| !r.parts.is_empty()); + let report = &mut self.report; + let r = base.map(|base| rest.fold(base, |acc, c| acc.intersect(&c, report))).filter(|r| !r.parts.is_empty()); cache.insert(key, r.clone()); r } @@ -407,6 +459,6 @@ impl<'a> Builder<'a> { _ => runs.push((region, vec![it.el])), } } - runs.into_iter().map(|(r, elements)| ImportedLayer { mask: r.map(|r| ImportedMask { name: r.name.clone(), elements: r.parts.clone() }), elements }).collect() + runs.into_iter().map(|(r, elements)| ImportedLayer { mask: r.map(|r| ImportedMask { name: r.name.clone(), elements: r.parts.clone(), mode: r.mode }), elements }).collect() } } diff --git a/crates/svg/src/clip_tests.rs b/crates/svg/src/clip_tests.rs index 9a95aca4..145269a3 100644 --- a/crates/svg/src/clip_tests.rs +++ b/crates/svg/src/clip_tests.rs @@ -1,6 +1,7 @@ //! Clip paths and masks → mask layers (ADR 0021), on self-authored drawings. use super::*; +use anicraft_doc::{MaskMode, Paint, Rgba}; fn imp(svg: &str) -> SvgImport { match import_with_fonts(svg.as_bytes(), &Fonts::from_faces(Vec::new())) { @@ -126,7 +127,7 @@ fn shapes_sharing_one_clip_share_one_mask_layer() { } #[test] -fn opaque_masks_become_mask_layers_and_soft_ones_are_reported() { +fn opaque_masks_become_mask_layers_and_soft_ones_soft_mask_layers() { let i = imp(r##" @@ -140,16 +141,47 @@ fn opaque_masks_become_mask_layers_and_soft_ones_are_reported() { "##); let shape: Vec<(Option<&str>, Vec<&str>)> = i.layers.iter().map(|l| (l.mask.as_ref().map(|m| m.name.as_str()), names(l))).collect(); - assert_eq!(shape, [(Some("white"), vec!["a"]), (Some("alpha"), vec!["b"]), (None, vec!["c", "d"]), (Some("tight"), vec!["e"])]); + assert_eq!(shape, [(Some("white"), vec!["a"]), (Some("alpha"), vec!["b"]), (Some("grey"), vec!["c"]), (Some("faded"), vec!["d"]), (Some("tight"), vec!["e"])]); + let modes: Vec = i.layers.iter().map(|l| l.mask.as_ref().unwrap().mode).collect(); + // Opaque masks stay Animate's masks (by area); the grey and the faded one are soft + // luminance masks (ADR 0070), their artwork as drawn. + assert_eq!(modes, [MaskMode::Coverage, MaskMode::Coverage, MaskMode::Luminance, MaskMode::Luminance, MaskMode::Coverage]); let white = i.layers[0].mask.as_ref().unwrap(); assert_eq!(white.elements.len(), 2, "the default mask region (bounding box + 10%) holds the content and cuts nothing"); assert!(in_mask(white, Vec2::new(5.0, 5.0)) && in_mask(white, Vec2::new(50.0, 50.0)) && !in_mask(white, Vec2::new(90.0, 10.0))); - assert_eq!(i.report.skipped.get("soft, faded or coloured masks (drawn unmasked)"), Some(&2)); + let grey = &i.layers[2].mask.as_ref().unwrap().elements[0]; + assert!(matches!(&grey.kind, ElementKind::Shape(s) if s.fill == Some(Paint::Solid(Rgba::hex(0x808080)))), "{grey:?}"); + assert_eq!(i.layers[3].mask.as_ref().unwrap().elements[0].alpha, 0.5, "the content's opacity stays"); + assert!(i.report.skipped.is_empty(), "{:?}", i.report); // A mask region cuts the mask: the full-size rect becomes the middle quarter. - let tight = path_of(&i.layers[3].mask.as_ref().unwrap().elements[0]).bounds(); + let tight = path_of(&i.layers[4].mask.as_ref().unwrap().elements[0]).bounds(); assert_eq!(tight, Rect::new(25.0, 25.0, 75.0, 75.0)); } +#[test] +fn soft_masks_keep_gradients_and_their_region_cuts_them() { + let i = imp(r##" + + + + + + + "##); + assert_eq!(i.layers.len(), 2, "{:?}", i.layers); + let a = i.layers[0].mask.as_ref().unwrap(); + assert_eq!(a.mode, MaskMode::Alpha); + // The region (x 0..50) cuts the gradient-filled rect in its own space; the paint stays. + let ElementKind::Shape(s) = &a.elements[0].kind else { panic!() }; + assert!(matches!(s.fill, Some(Paint::Linear { .. }))); + let b = path_of(&a.elements[0]).bounds(); + assert!((b.max.x - 50.0).abs() < 1e-3 && b.min.x.abs() < 1e-3, "{b:?}"); + // Luminance by default; the stroke stays too. + let l = i.layers[1].mask.as_ref().unwrap(); + assert_eq!(l.mode, MaskMode::Luminance); + assert!(matches!(&l.elements[0].kind, ElementKind::Shape(s) if s.stroke.is_some() && matches!(s.fill, Some(Paint::Linear { .. })))); +} + #[test] fn loops_and_floods_of_clips_stay_bounded() { let start = std::time::Instant::now(); diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index d19291ba..6f6d4dd1 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -114,6 +114,9 @@ pub struct ImportedMask { /// The clip path's or mask's `id`, if it had one. pub name: String, pub elements: Vec, + /// How the mask layer reveals (ADR 0070): coverage for clip paths and opaque masks, else + /// the `mask`'s `mask-type` (luminance by default, or alpha), its artwork as drawn. + pub mode: anicraft_doc::MaskMode, } /// Artwork drawn together on one layer, bottom first; masked by `mask` when there is one. From b5a45bd96ca621530fe6e194505dbc9ca59d7317 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Thu, 12 Nov 2026 00:33:48 -0700 Subject: [PATCH 13/18] feat(text): glyphs on their own, and glyphs set along a path by arc length (M4) --- crates/text/src/lib.rs | 205 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 201 insertions(+), 4 deletions(-) diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 2599a6f0..99839b1a 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -4,6 +4,10 @@ //! glyph's outline with `skrifa` into one [`Path`], in pixels, with the layout box's top-left //! corner at the origin. The engine stores that path with the text element (ADR 0012), so //! rendering never depends on which fonts are installed. +//! +//! [`Fonts::layout_glyphs`] also hands back each glyph on its own ([`PlacedGlyph`]), for text +//! placed glyph by glyph: along a path ([`on_path`], ADR 0070) or at SVG's per-character +//! positions. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] use anicraft_geom::{Path, PathCmd, Vec2}; @@ -76,6 +80,104 @@ pub struct Layout { /// Where a caret can stand, one entry per laid-out line, top first (ADR 0066: text fields /// that viewers type into). pub carets: Vec, + /// Each glyph on its own, in drawing order: only from [`Fonts::layout_glyphs`] (empty + /// otherwise). + pub glyphs: Vec, +} + +/// One laid-out glyph on its own. +#[derive(Clone, Debug, PartialEq)] +pub struct PlacedGlyph { + /// Its outline, with its pen position on the baseline at the origin (pixels, y down). + pub outline: Path, + /// Its pen position in the block: from the box's left edge (alignment applied), and its + /// line's baseline from the box's top. + pub x: f32, + pub baseline: f32, + /// How far the pen moves past it (letter spacing included). + pub advance: f32, + /// The character it starts at (`char`s of the whole text, line breaks included). + pub index: u32, +} + +/// How text follows a path (ADR 0070). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct PathPlacement { + /// Where the text is anchored, as a distance along the path: left-aligned text starts + /// there, centred text is centred on it, right-aligned text ends there. + pub offset: f32, + /// Along the path backwards: on its other side, upside down to the path's direction. + pub flip: bool, + pub align: Align, +} + +/// Glyphs set along a path. +#[derive(Clone, Debug, PartialEq)] +pub struct PathText { + /// Every glyph shown, in the path's space. + pub outline: Path, + /// The path's length. + pub length: f32, + /// Each shown glyph's character, the point on the path under its middle and its angle + /// (radians, the direction of travel). + pub placed: Vec<(u32, Vec2, f32)>, + /// Glyphs whose middle falls past an open path's ends (not drawn, as SVG leaves them). + pub hidden: usize, +} + +/// The glyphs of a one-line layout set along `path`'s first subpath (ADR 0070): each glyph's +/// middle at its distance along the path (measured on the curve itself), the glyph turned to +/// the path's direction there, its baseline on the path, standing on the path's left (above a +/// path drawn left to right; `flip` walks it backwards, onto the other side). On a closed path +/// glyphs wrap round; on an open one those past its ends are left out. `None` when the path has +/// no length. +pub fn on_path(glyphs: &[PlacedGlyph], path: &Path, how: PathPlacement) -> Option { + let walk = anicraft_geom::walk::CurveWalk::new(path)?; + let length = walk.length(); + let closed = first_subpath_closed(path); + // The run's width: from its pen start (0) to the end of its last glyph. + let width = glyphs.iter().map(|g| g.x + g.advance).filter(|w| w.is_finite()).fold(0.0f32, f32::max); + let offset = if how.offset.is_finite() { how.offset.clamp(-1e6, 1e6) } else { 0.0 }; + let start = offset + - match how.align { + Align::Left => 0.0, + Align::Center => width * 0.5, + Align::Right => width, + }; + let mut out = PathText { outline: Path::new(), length, placed: Vec::with_capacity(glyphs.len()), hidden: 0 }; + for g in glyphs { + let mid = start + g.x + g.advance * 0.5; + if !mid.is_finite() { + out.hidden += 1; + continue; + } + let s = if closed { + mid.rem_euclid(length) + } else if (0.0..=length).contains(&mid) { + mid + } else { + out.hidden += 1; + continue; + }; + let (p, t) = if how.flip { (walk.at(length - s), walk.tangent(length - s) * -1.0) } else { (walk.at(s), walk.tangent(s)) }; + let angle = t.y.atan2(t.x); + let m = anicraft_geom::Affine::translate(p.x, p.y).mul(&anicraft_geom::Affine::rotate(angle)).mul(&anicraft_geom::Affine::translate(-g.advance * 0.5, 0.0)); + out.outline.cmds.extend(g.outline.transformed(&m).cmds); + out.placed.push((g.index, p, angle)); + } + Some(out) +} + +/// Whether a path's first subpath ends with a close. +fn first_subpath_closed(path: &Path) -> bool { + for (i, c) in path.cmds.iter().enumerate() { + match c { + PathCmd::Close => return true, + PathCmd::MoveTo(_) if i > 0 => return false, + _ => {} + } + } + false } /// One laid-out line's characters and caret positions. Indices count `char`s of the whole text @@ -261,6 +363,15 @@ impl Fonts { /// Lays `text` out in `style`. pub fn layout(&self, text: &str, style: &Style) -> Result { + self.lay_out_with(text, style, false) + } + + /// Lays `text` out in `style`, with each glyph on its own too ([`Layout::glyphs`]). + pub fn layout_glyphs(&self, text: &str, style: &Style) -> Result { + self.lay_out_with(text, style, true) + } + + fn lay_out_with(&self, text: &str, style: &Style, glyphs: bool) -> Result { if text.chars().count() > MAX_CHARS { return Err(TextError::TooLong); } @@ -272,7 +383,7 @@ impl Fonts { style: if style.italic { fontdb::Style::Italic } else { fontdb::Style::Normal }, }; let id = self.db.query(&q).ok_or(TextError::NoFonts)?; - let laid = self.db.with_face_data(id, |data, index| lay_out(data, index, text, style)).flatten().ok_or(TextError::NoFonts)?; + let laid = self.db.with_face_data(id, |data, index| lay_out(data, index, text, style, glyphs)).flatten().ok_or(TextError::NoFonts)?; Ok(Layout { family, ..laid }) } } @@ -324,7 +435,7 @@ struct Glyph { advance: f32, } -fn lay_out(data: &[u8], index: u32, text: &str, style: &Style) -> Option { +fn lay_out(data: &[u8], index: u32, text: &str, style: &Style, want_glyphs: bool) -> Option { let style = sanitize(style); let font = skrifa::FontRef::from_index(data, index).ok()?; let size = skrifa::instance::Size::new(style.size); @@ -422,6 +533,7 @@ fn lay_out(data: &[u8], index: u32, text: &str, style: &Style) -> Option let box_width = style.width.unwrap_or_else(|| lines.iter().map(|(w, _)| *w).fold(0.0, f32::max)); let mut outline = Path::new(); + let mut placed: Vec = Vec::new(); for (row, (width, line)) in lines.iter().enumerate() { let shift = match style.align { Align::Left => 0.0, @@ -429,16 +541,25 @@ fn lay_out(data: &[u8], index: u32, text: &str, style: &Style) -> Option Align::Right => box_width - width, }; let baseline = ascent + row as f32 * line_height; + let span = spans.get(row); for (g, gx) in line { let Some(glyph) = glyphs.get(g.id) else { continue }; - let mut pen = Pen { cmds: &mut outline.cmds, x: shift + gx + g.x_offset, y: baseline - g.y_offset }; + if want_glyphs { + let settings = skrifa::outline::DrawSettings::unhinted(size, skrifa::instance::LocationRef::default()); + let mut own = Path::new(); + let mut pen = Pen { cmds: &mut own.cmds, x: g.x_offset, y: -g.y_offset }; + let _ = glyph.draw(settings, &mut pen); + let index = span.map_or(0, |(pstart, plen, to_char)| pstart + to_char.get(g.cluster).copied().unwrap_or(*plen).min(*plen)); + placed.push(PlacedGlyph { outline: own, x: shift + gx, baseline, advance: g.advance, index }); + } let settings = skrifa::outline::DrawSettings::unhinted(size, skrifa::instance::LocationRef::default()); + let mut pen = Pen { cmds: &mut outline.cmds, x: shift + gx + g.x_offset, y: baseline - g.y_offset }; let _ = glyph.draw(settings, &mut pen); } } let height = (lines.len().max(1) as f32 - 1.0) * line_height + (metrics.ascent - metrics.descent); let carets = caret_lines(&lines, &spans, box_width, style.align); - Some(Layout { outline, width: box_width.max(0.0), height: height.max(0.0), family: String::new(), missing, lines: lines.len().max(1), line_height, ascent, carets }) + Some(Layout { outline, width: box_width.max(0.0), height: height.max(0.0), family: String::new(), missing, lines: lines.len().max(1), line_height, ascent, carets, glyphs: placed }) } /// The caret positions of laid-out lines (see [`CaretLine`]). @@ -644,6 +765,82 @@ mod tests { assert!(b.max.y > one.ascent - 1.0 && b.min.y < one.ascent, "glyphs sit on the baseline: {b:?}"); } + #[test] + fn glyphs_on_their_own_add_up_to_the_outline() { + let Some(fonts) = fonts() else { return }; + let l = fonts.layout_glyphs("AVA b", &style(30.0)).unwrap(); + assert_eq!(l.outline, fonts.layout("AVA b", &style(30.0)).unwrap().outline, "the same outline"); + assert_eq!(fonts.layout("AVA b", &style(30.0)).unwrap().glyphs, Vec::new(), "only when asked"); + assert_eq!(l.glyphs.iter().map(|g| g.index).collect::>(), vec![0, 1, 2, 3, 4]); + let mut joined = Path::new(); + for g in &l.glyphs { + joined.cmds.extend(g.outline.transformed(&anicraft_geom::Affine::translate(g.x, g.baseline)).cmds); + assert_eq!(g.baseline, l.ascent); + } + let (a, b) = (joined.bounds(), l.outline.bounds()); + assert!((a.min - b.min).length() < 1e-3 && (a.max - b.max).length() < 1e-3, "{a:?} vs {b:?}"); + let last = l.glyphs.last().unwrap(); + assert!((last.x + last.advance - l.width).abs() < 1e-3); + } + + /// Synthetic glyphs: a 10 × 20 box standing on the baseline, `n` of them 10 apart. + fn boxes(n: u32) -> Vec { + (0..n).map(|i| PlacedGlyph { outline: Path::rect(0.0, -20.0, 10.0, 20.0), x: i as f32 * 10.0, baseline: 20.0, advance: 10.0, index: i }).collect() + } + + #[test] + fn glyphs_follow_a_path_by_arc_length() { + let left = PathPlacement { offset: 0.0, flip: false, align: Align::Left }; + // A straight line: glyph k's middle at 10 k + 5, upright, standing on the line (above it). + let mut line = Path::new(); + line.cmds = vec![PathCmd::MoveTo(Vec2::new(0.0, 100.0)), PathCmd::LineTo(Vec2::new(200.0, 100.0))]; + let t = on_path(&boxes(3), &line, left).unwrap(); + assert_eq!(t.length, 200.0); + for (k, (i, p, a)) in t.placed.iter().enumerate() { + assert_eq!(*i, k as u32); + assert!((p.x - (10.0 * k as f32 + 5.0)).abs() < 1e-3 && (p.y - 100.0).abs() < 1e-3 && a.abs() < 1e-4, "{p:?} {a}"); + } + let b = t.outline.bounds(); + assert!((b.min.x).abs() < 1e-3 && (b.max.x - 30.0).abs() < 1e-3 && (b.min.y - 80.0).abs() < 1e-3 && (b.max.y - 100.0).abs() < 1e-3, "{b:?}"); + // Offset, centring and right alignment move the run along the path. + let at = |offset, align| on_path(&boxes(3), &line, PathPlacement { offset, flip: false, align }).unwrap().placed[0].1.x; + assert!((at(50.0, Align::Left) - 55.0).abs() < 1e-3); + assert!((at(100.0, Align::Center) - 90.0).abs() < 1e-3); + assert!((at(200.0, Align::Right) - 175.0).abs() < 1e-3); + // Past an open path's end, glyphs are left out. + let off = on_path(&boxes(3), &line, PathPlacement { offset: 180.0, flip: false, align: Align::Left }).unwrap(); + assert_eq!((off.placed.len(), off.hidden), (2, 1)); + // Flipped: walked from the other end, upside down, below the line. + let f = on_path(&boxes(1), &line, PathPlacement { offset: 0.0, flip: true, align: Align::Left }).unwrap(); + let (_, p, a) = f.placed[0]; + assert!((p.x - 195.0).abs() < 1e-3 && (a.abs() - std::f32::consts::PI).abs() < 1e-3, "{p:?} {a}"); + assert!(f.outline.bounds().min.y >= 100.0 - 1e-3, "{:?}", f.outline.bounds()); + } + + #[test] + fn glyphs_turn_with_a_circle_and_wrap_round_it() { + // A circle of radius 100 (clockwise on screen, from the right): a glyph at distance s + // sits at angle s / r, turned a quarter more. + let circle = Path::ellipse(0.0, 0.0, 100.0, 100.0); + let walk = anicraft_geom::walk::CurveWalk::new(&circle).unwrap(); + let len = walk.length(); + assert!((len - 2.0 * std::f32::consts::PI * 100.0).abs() < 0.5, "{len}"); + let t = on_path(&boxes(4), &circle, PathPlacement { offset: len - 15.0, flip: false, align: Align::Left }).unwrap(); + assert_eq!((t.placed.len(), t.hidden), (4, 0), "wrapped past the start of a closed path"); + for (_, p, a) in &t.placed { + assert!((p.length() - 100.0).abs() < 0.05, "on the circle: {p:?}"); + let tangent = Vec2::new(a.cos(), a.sin()); + assert!(tangent.dot(*p).abs() < 0.5, "turned along it: {p:?} {a}"); + } + // The second glyph's middle is at distance 0: the path's start. + let (_, p, _) = t.placed[1]; + assert!((p - walk.at(0.0)).length() < 0.05, "{p:?}"); + // No length, no text. + let mut dot = Path::new(); + dot.cmds = vec![PathCmd::MoveTo(Vec2::ZERO), PathCmd::LineTo(Vec2::ZERO)]; + assert!(on_path(&boxes(1), &dot, PathPlacement { offset: 0.0, flip: false, align: Align::Left }).is_none()); + } + #[test] fn carets_stand_at_every_boundary_line_by_line() { let Some(fonts) = fonts() else { return }; From bdb7515e3c01047b275c8d8921c3fa20333fa5ba Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Thu, 12 Nov 2026 00:41:58 -0700 Subject: [PATCH 14/18] feat(engine): text on a path: attach to a shape, move along, flip, release; edits keep it on its path (M4) --- crates/doc/src/field_tests.rs | 2 +- crates/doc/src/lib.rs | 21 +++ crates/doc/src/player_tests.rs | 2 +- crates/engine/src/cmds_text.rs | 194 +++++++++++++++++++++++++-- crates/engine/src/find.rs | 7 +- crates/engine/src/find_tests.rs | 2 +- crates/engine/src/lib.rs | 2 + crates/engine/src/path_text_tests.rs | 164 ++++++++++++++++++++++ crates/render/src/html_tests.rs | 2 +- crates/svg/src/text.rs | 1 + crates/xfl/src/text.rs | 2 + 11 files changed, 385 insertions(+), 14 deletions(-) create mode 100644 crates/engine/src/path_text_tests.rs diff --git a/crates/doc/src/field_tests.rs b/crates/doc/src/field_tests.rs index 1120264a..a1d8e5c4 100644 --- a/crates/doc/src/field_tests.rs +++ b/crates/doc/src/field_tests.rs @@ -2,7 +2,7 @@ use super::*; use crate::{Rgba, TextAlign}; fn block(text: &str, f: TextField) -> TextBlock { - TextBlock { text: text.into(), font: "Mono".into(), size: 10.0, bold: false, italic: false, color: Rgba::BLACK, align: TextAlign::Left, letter_spacing: 0.0, line_spacing: 0.0, width: None, outline: Arc::new(Path::new()), box_width: 54.0, box_height: 24.0, field: Some(f) } + TextBlock { text: text.into(), font: "Mono".into(), size: 10.0, bold: false, italic: false, color: Rgba::BLACK, align: TextAlign::Left, letter_spacing: 0.0, line_spacing: 0.0, width: None, outline: Arc::new(Path::new()), box_width: 54.0, box_height: 24.0, field: Some(f), on_path: None } } /// Runs edits on a field as the player does: each change of text lays it out again (10 px per diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 1d38ab1c..a0d72838 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -471,8 +471,29 @@ pub struct TextBlock { /// A dynamic or input text field (ADR 0066); `None`: static text. #[serde(default, skip_serializing_if = "Option::is_none")] pub field: Option, + /// Text on a path (ADR 0070): its baseline follows this path instead of running in lines; + /// `outline` holds the glyphs set along it. Static text only. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub on_path: Option, } +/// The path a text block follows (ADR 0070), and where along it the text sits. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct TextPath { + /// The baseline's path, in the block's own space (its first subpath counts). + pub path: Path, + /// Where the text is anchored along the path (pixels from its start): the block's + /// alignment says how (left: starts there, centre: centred on it, right: ends there). + #[serde(default)] + pub offset: f32, + /// The text runs along the path backwards, on its other side. + #[serde(default, skip_serializing_if = "is_false")] + pub flip: bool, +} + +/// Longest stretch along a path a text's offset may be (pixels either way). +pub const MAX_PATH_OFFSET: f32 = 1_000_000.0; + impl TextBlock { /// What kind of text it is: static, dynamic or input. pub fn kind(&self) -> TextKind { diff --git a/crates/doc/src/player_tests.rs b/crates/doc/src/player_tests.rs index b4048fa0..2114efba 100644 --- a/crates/doc/src/player_tests.rs +++ b/crates/doc/src/player_tests.rs @@ -722,7 +722,7 @@ impl ScriptHost for Mono { } fn field(id: u64, name: &str, text: &str, kind: TextKind, x: f32, y: f32) -> Arc { - let block = TextBlock { text: text.into(), font: "Mono".into(), size: 10.0, bold: false, italic: false, color: Rgba::BLACK, align: crate::TextAlign::Left, letter_spacing: 0.0, line_spacing: 0.0, width: None, outline: Arc::new(Path::rect(2.0, 2.0, 8.0, 8.0)), box_width: 104.0, box_height: 14.0, field: Some(TextField { border: true, ..TextField::new(kind) }) }; + let block = TextBlock { text: text.into(), font: "Mono".into(), size: 10.0, bold: false, italic: false, color: Rgba::BLACK, align: crate::TextAlign::Left, letter_spacing: 0.0, line_spacing: 0.0, width: None, outline: Arc::new(Path::rect(2.0, 2.0, 8.0, 8.0)), box_width: 104.0, box_height: 14.0, field: Some(TextField { border: true, ..TextField::new(kind) }), on_path: None }; Arc::new(Element { id: ElementId(id), name: name.into(), transform: Affine::translate(x, y), color: ColorEffect::default(), kind: ElementKind::Text(Arc::new(block)) }) } diff --git a/crates/engine/src/cmds_text.rs b/crates/engine/src/cmds_text.rs index b1cb65c5..b45c33ac 100644 --- a/crates/engine/src/cmds_text.rs +++ b/crates/engine/src/cmds_text.rs @@ -4,11 +4,15 @@ //! Dynamic and input text fields (ADR 0066): `text.field` sets a block's Text type and field //! options. A field's box is fixed and its text is laid out inside the gutter, aligned in the box; //! [`field_layout`] does that for the commands and for the player while a movie plays. +//! +//! Text on a path (ADR 0070): `text.attach_path` sets static text along a shape's outline (a +//! copy of it, in the text's own space), `text.path` moves it along, flips it or releases it. +//! The glyphs are set by arc length and stored as outlines, as all text is. use crate::params::*; use crate::{CommandSpec, EngineError, Result, Session}; -use anicraft_doc::{ColorEffect, Element, ElementId, ElementKind, FIELD_GUTTER, LineType, MAX_FIELD_CHARS, MAX_FIELD_NAME, Rgba, TextAlign, TextBlock, TextField, TextKind}; -use anicraft_geom::{Affine, Path}; +use anicraft_doc::{ColorEffect, Element, ElementId, ElementKind, FIELD_GUTTER, LineType, MAX_FIELD_CHARS, MAX_FIELD_NAME, MAX_PATH_OFFSET, Rgba, TextAlign, TextBlock, TextField, TextKind, TextPath}; +use anicraft_geom::{Affine, Path, Vec2}; use anicraft_text::{Align, Fonts}; use serde_json::{Value, json}; use std::sync::Arc; @@ -39,6 +43,17 @@ pub fn specs() -> Vec { c("text.create", "New Text", "", None, "{text (may be empty for an input field), type?: static|dynamic|input, x?, y? (top-left; default: centred), font?, size?, bold?, italic?, color?, align?, letter_spacing?, line_spacing?, width?}", true, create as crate::RunFn), c("text.edit", "Edit Text", "", None, "{text?, font?, size? (px), bold?, italic?, color?, align?: left|center|right, letter_spacing?, line_spacing?, width? (px, wraps; null: one line per paragraph)} on the selected text", true, |s, p| s.each_layer(false, |s| edit(s, p))), c("text.fonts", "Fonts", "", None, "{}", false, fonts), + c( + "text.attach_path", + "Attach Text to Path", + "Modify/Text", + None, + "{path?: element id of a shape (default: the other selected element, a shape), x?, y? (pick the shape at this stage point instead), offset? (px along the path; default by the text's alignment: its start, middle or end), flip?: bool} sets the selected static text along a copy of the shape's outline (its first contour); the shape stays as it is (ADR 0070)", + true, + attach_path as crate::RunFn, + ), + c("text.path", "Text on Path", "", None, "{offset? (px along the path), flip?: bool (along the path backwards, on its other side), release?: bool (back to lines of text where it starts)} on the selected text on a path (ADR 0070)", true, |s, p| s.each_layer(false, |s| set_path(s, p))), + c("text.release_path", "Release Text from Path", "Modify/Text", None, "{} the selected text on a path goes back to lines of text (ADR 0070)", true, |s, _| s.each_layer(false, |s| set_path(s, &json!({"release": true})))), c("text.field", "Text Type", "", None, "{type?: static|dynamic|input, lines?: single|multiline|multiline_no_wrap|password (input only), width?, height? (the field's box, px), selectable?, border?, background?, border_color?, background_color?, max_chars? (input; 0: no limit), variable? (kept, not run)} on the selected text; dynamic and input fields are named with instance.set_name and scripted in Test Movie and the HTML export (ADR 0066)", true, |s, p| s.each_layer(false, |s| set_field(s, p))), ] } @@ -126,6 +141,7 @@ pub(crate) fn lay_out(text: &str, style: &TextStyle, width: Option) -> Resu box_width: layout.width, box_height: layout.height, field: None, + on_path: None, }; Ok((block, note)) } @@ -192,19 +208,177 @@ pub(crate) fn lay_out_field(text: &str, style: &TextStyle, field: &TextField, bo box_width, box_height, field: Some(field.clone()), + on_path: None, }; Ok((block, note)) } +/// Text on a path (ADR 0070): `text` on one line (line breaks become spaces) set along `on`'s +/// path. The block's space is moved so its box (the path and the glyphs together) starts at +/// the origin, as every text box does: the second value is where that origin was, which the +/// element's transform must move by (`transform × translate(shift)`) for nothing to move. +pub(crate) fn lay_out_on_path(text: &str, style: &TextStyle, on: &TextPath) -> Result<(TextBlock, Option, Vec2)> { + let fonts = Fonts::get(); + let line: String = text.chars().map(|c| if c == '\n' || c == '\r' { ' ' } else { c }).collect(); + let layout = fonts + .layout_glyphs(&line, &anicraft_text::Style { family: style.font.clone(), size: style.size, bold: style.bold, italic: style.italic, align: Align::Left, letter_spacing: style.letter_spacing, line_spacing: 0.0, width: None }) + .map_err(|e| EngineError::State(format!("can't lay out text: {e}")))?; + let note = (!style.font.trim().is_empty() && !layout.family.eq_ignore_ascii_case(style.font.trim())).then(|| format!("“{}” isn't installed on this computer; used {}", style.font.trim(), layout.family)); + let align = match style.align { + TextAlign::Left => Align::Left, + TextAlign::Center => Align::Center, + TextAlign::Right => Align::Right, + }; + let offset = if on.offset.is_finite() { on.offset.clamp(-MAX_PATH_OFFSET, MAX_PATH_OFFSET) } else { 0.0 }; + let set = anicraft_text::on_path(&layout.glyphs, &on.path, anicraft_text::PathPlacement { offset, flip: on.flip, align }).ok_or_else(|| EngineError::State("the path has no length to set text along".into()))?; + // The box: the path and the glyphs, from the origin. + let b = set.outline.bounds().union(&on.path.bounds()); + let shift = if b.min.x.is_finite() && b.min.y.is_finite() { b.min } else { Vec2::ZERO }; + let back = Affine::translate(-shift.x, -shift.y); + let block = TextBlock { + text: text.to_string(), + font: layout.family, + size: style.size, + bold: style.bold, + italic: style.italic, + color: style.color, + align: style.align, + letter_spacing: style.letter_spacing, + line_spacing: style.line_spacing, + width: None, + outline: Arc::new(set.outline.transformed(&back)), + box_width: if b.width().is_finite() { b.width().max(0.0) } else { 0.0 }, + box_height: if b.height().is_finite() { b.height().max(0.0) } else { 0.0 }, + field: None, + on_path: Some(TextPath { path: on.path.transformed(&back), offset, flip: on.flip }), + }; + Ok((block, note, shift)) +} + /// The block `t` with new text or style: a field keeps its box (or takes `width` as its new -/// width); static text wraps at `width`. -fn relay(t: &TextBlock, text: &str, style: &TextStyle, width: Option) -> Result<(TextBlock, Option)> { - match &t.field { - Some(f) => lay_out_field(text, style, f, width.unwrap_or(t.box_width), t.box_height), - None => lay_out(text, style, width), +/// width); static text wraps at `width`; text on a path stays on it. With where the block's +/// origin moved to ([`lay_out_on_path`]; zero for the others). +pub(crate) fn relay(t: &TextBlock, text: &str, style: &TextStyle, width: Option) -> Result<(TextBlock, Option, Vec2)> { + match (&t.field, &t.on_path) { + (_, Some(on)) => lay_out_on_path(text, style, on), + (Some(f), None) => lay_out_field(text, style, f, width.unwrap_or(t.box_width), t.box_height).map(|(b, n)| (b, n, Vec2::ZERO)), + (None, None) => lay_out(text, style, width).map(|(b, n)| (b, n, Vec2::ZERO)), } } +/// What Find and Replace lays text out with: as before (static text, its fields' boxes +/// dropped), except that text on a path stays on its path. +pub(crate) fn relay_static(t: &TextBlock, text: &str, style: &TextStyle) -> Result<(TextBlock, Option, Vec2)> { + match &t.on_path { + Some(on) => lay_out_on_path(text, style, on), + None => lay_out(text, style, t.width).map(|(b, n)| (b, n, Vec2::ZERO)), + } +} + +/// The selected static text, along a copy of a shape's outline (ADR 0070). +fn attach_path(s: &mut Session, p: &Value) -> Result { + let by_id = opt_u64(p, "path")?.map(ElementId); + let at = 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 neither".into())), + }; + let flip = opt_bool(p, "flip")?.unwrap_or(false); + let offset = opt_f32(p, "offset")?; + if offset.is_some_and(|o| !(-MAX_PATH_OFFSET..=MAX_PATH_OFFSET).contains(&o)) { + return Err(EngineError::Param(format!("'offset' must be within ±{MAX_PATH_OFFSET} px"))); + } + // The shape: by id or by point, on any layer of what is being edited; else the selection's. + let wanted = match (by_id, at) { + (Some(id), _) => Some(id), + (None, Some(pt)) => Some(s.hit_test(pt, 2.0).map(|(_, e)| e).ok_or_else(|| EngineError::State("there is no shape there to set the text along".into()))?), + (None, None) => None, + }; + let texts: Vec = s.selected_elements_mut()?.iter().filter(|e| matches!(&e.kind, ElementKind::Text(t) if t.field.is_none())).map(|e| e.id).collect(); + let [text_id] = texts.as_slice() else { + return Err(EngineError::State(if texts.is_empty() { "select a static text block to set along a path".into() } else { "select one text block to set along a path".into() })); + }; + // The shapes on the timeline being edited at this frame (in its space, as the text is): + // the one asked for, or the selected one. + let selected = s.selection.on(s.layer); + let mut candidates: Vec = Vec::new(); + for l in &s.timeline().layers { + let Some((_, els)) = anicraft_doc::evaluate_layer_elements(l, s.frame) else { continue }; + for e in els.iter() { + let ElementKind::Shape(sh) = &e.kind else { continue }; + let pick = match wanted { + Some(w) => w == e.id, + None => l.id == s.layer && selected.contains(&e.id), + }; + if pick { + candidates.push(sh.path.transformed(&e.transform)); + } + } + } + let path = match candidates.as_slice() { + [path] => path.clone(), + [] => return Err(EngineError::State("pick a shape to set the text along".into())), + _ => return Err(EngineError::State("select the text and one shape (or pick the shape)".into())), + }; + // Its first contour, in the timeline's space (the text takes the path's place). + let first: Path = Path { cmds: path.cmds.iter().enumerate().take_while(|(i, c)| *i == 0 || !matches!(c, anicraft_geom::PathCmd::MoveTo(_))).map(|(_, c)| *c).collect() }; + let length = anicraft_geom::walk::CurveWalk::new(&first).map(|w| w.length()).ok_or_else(|| EngineError::State("the shape's outline has no length to set text along".into()))?; + let mut out = Value::Null; + for e in s.selected_elements_mut()? { + if e.id != *text_id { + continue; + } + let ElementKind::Text(t) = &e.kind else { continue }; + let style = style_of(t); + let offset = offset.unwrap_or(match t.align { + TextAlign::Left => 0.0, + TextAlign::Center => length * 0.5, + TextAlign::Right => length, + }); + let (block, note, shift) = lay_out_on_path(&t.text, &style, &TextPath { path: first.clone(), offset, flip })?; + // The path is in stage space; the text's new space is the path's, moved to its box. + e.transform = Affine::translate(shift.x, shift.y); + out = json!({"element": e.id.0, "length": length, "offset": offset, "flip": flip, "note": note}); + e.kind = ElementKind::Text(Arc::new(block)); + } + s.select_only([*text_id]); + Ok(out) +} + +/// Moves, flips or releases the selected text on a path. +fn set_path(s: &mut Session, p: &Value) -> Result { + let offset = opt_f32(p, "offset")?; + if offset.is_some_and(|o| !(-MAX_PATH_OFFSET..=MAX_PATH_OFFSET).contains(&o)) { + return Err(EngineError::Param(format!("'offset' must be within ±{MAX_PATH_OFFSET} px"))); + } + let flip = opt_bool(p, "flip")?; + let release = opt_bool(p, "release")?.unwrap_or(false); + let mut changed = 0; + for e in s.selected_elements_mut()? { + let ElementKind::Text(t) = &e.kind else { continue }; + let Some(on) = &t.on_path else { continue }; + let style = style_of(t); + if release { + // Back to a line of text, its box where the text started along the path. + let start = t.outline.bounds(); + let (block, _) = lay_out(&t.text, &style, None)?; + let at = if start.min.x.is_finite() { start.min } else { Vec2::ZERO }; + e.transform = e.transform.mul(&Affine::translate(at.x, at.y)); + e.kind = ElementKind::Text(Arc::new(block)); + } else { + let on = TextPath { offset: offset.unwrap_or(on.offset), flip: flip.unwrap_or(on.flip), ..on.clone() }; + let (block, _, shift) = lay_out_on_path(&t.text, &style, &on)?; + e.transform = e.transform.mul(&Affine::translate(shift.x, shift.y)); + e.kind = ElementKind::Text(Arc::new(block)); + } + changed += 1; + } + if changed == 0 { + return Err(EngineError::State("the selection has no text on a path".into())); + } + Ok(json!({"changed": changed})) +} + /// The box a block becomes a field in: the text's own size and the gutters (at least 20 px wide). fn field_box(t: &TextBlock) -> (f32, f32) { ((t.width.unwrap_or(t.box_width) + 2.0 * FIELD_GUTTER).max(20.0), t.box_height + 2.0 * FIELD_GUTTER) @@ -236,6 +410,9 @@ fn set_field(s: &mut Session, p: &Value) -> Result { let mut notes = Vec::new(); for e in s.selected_elements_mut()? { let ElementKind::Text(t) = &e.kind else { continue }; + if t.on_path.is_some() && kind.is_some_and(|k| k != TextKind::Static) { + return Err(EngineError::State("text on a path is static text (release it from the path first)".into())); + } let to = kind.unwrap_or(t.kind()); let style = style_of(t); let (block, note) = if to == TextKind::Static { @@ -340,9 +517,10 @@ fn edit(s: &mut Session, p: &Value) -> Result { return Err(EngineError::Param("'text' is empty (delete the text instead)".into())); } let width = if t.field.is_some() { width_param(p, Some(t.box_width))?.or(Some(t.box_width)).map(|w| w.max(1.0)) } else { width_param(p, t.width)? }; - let (block, note) = relay(t, &text, &style, width)?; + let (block, note, shift) = relay(t, &text, &style, width)?; notes.extend(note); last_style = Some(TextStyle { font: block.font.clone(), ..style }); + e.transform = e.transform.mul(&Affine::translate(shift.x, shift.y)); e.kind = ElementKind::Text(Arc::new(block)); edited += 1; } diff --git a/crates/engine/src/find.rs b/crates/engine/src/find.rs index 03b6cdd5..ce601a20 100644 --- a/crates/engine/src/find.rs +++ b/crates/engine/src/find.rs @@ -890,18 +890,21 @@ fn apply_element(e: &mut anicraft_doc::Element, f: Field, q: &Query, with: &With t.skipped += 1; t.note("a text field can't be left empty (delete it instead)".into()); } else { - let (block, note) = crate::cmds_text::lay_out(&n, &crate::cmds_text::style_of(tb), tb.width)?; + // Laid out again as it is: text on a path stays on it (ADR 0070). + let (block, note, shift) = crate::cmds_text::relay_static(tb, &n, &crate::cmds_text::style_of(tb))?; t.note_opt(note); *tb = Arc::new(block); + e.transform = e.transform.mul(&anicraft_geom::Affine::translate(shift.x, shift.y)); t.replaced += 1; } } } (Field::Font, ElementKind::Text(tb), With::Font(family)) => { let style = crate::cmds_text::TextStyle { font: family.clone(), ..crate::cmds_text::style_of(tb) }; - let (block, note) = crate::cmds_text::lay_out(&tb.text, &style, tb.width)?; + let (block, note, shift) = crate::cmds_text::relay_static(tb, &tb.text, &style)?; t.note_opt(note); *tb = Arc::new(block); + e.transform = e.transform.mul(&anicraft_geom::Affine::translate(shift.x, shift.y)); t.replaced += 1; } (Field::TextColor, ElementKind::Text(tb), With::Color(c)) => { diff --git a/crates/engine/src/find_tests.rs b/crates/engine/src/find_tests.rs index 764ee72b..c21c1ce8 100644 --- a/crates/engine/src/find_tests.rs +++ b/crates/engine/src/find_tests.rs @@ -38,7 +38,7 @@ impl Build { self.doc.alloc_id() } pub fn text(&mut self, t: &str, color: Rgba) -> Element { - let block = TextBlock { text: t.into(), font: "Test Sans".into(), size: 20.0, bold: false, italic: false, color, align: TextAlign::Left, letter_spacing: 0.0, line_spacing: 0.0, width: None, outline: Arc::new(Path::new()), box_width: 10.0, box_height: 10.0, field: None }; + let block = TextBlock { text: t.into(), font: "Test Sans".into(), size: 20.0, bold: false, italic: false, color, align: TextAlign::Left, letter_spacing: 0.0, line_spacing: 0.0, width: None, outline: Arc::new(Path::new()), box_width: 10.0, box_height: 10.0, field: None, on_path: None }; Element { id: ElementId(self.id()), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Text(Arc::new(block)) } } pub fn rect(&mut self, fill: Paint, stroke: Option) -> Element { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 5dfa57e4..746d8021 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1044,3 +1044,5 @@ mod drop_tests; mod template_tests; #[cfg(test)] mod timeline_drop_tests; +#[cfg(test)] +mod path_text_tests; diff --git a/crates/engine/src/path_text_tests.rs b/crates/engine/src/path_text_tests.rs new file mode 100644 index 00000000..ff4f6f0e --- /dev/null +++ b/crates/engine/src/path_text_tests.rs @@ -0,0 +1,164 @@ +//! Text on a path (ADR 0070): attaching text to a shape's outline, by selection or by picking, +//! moving it along, flipping and releasing it, edits keeping it on the path, undo, the file. + +use crate::Session; +use anicraft_doc::{ElementId, ElementKind, TextBlock}; +use serde_json::{Value, json}; +use std::sync::Arc; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")) +} + +fn fonts() -> bool { + let ok = !anicraft_text::Fonts::get().families().is_empty(); + if !ok { + eprintln!("no fonts on this computer: text on a path tests skipped"); + } + ok +} + +fn text_of(s: &Session, id: ElementId) -> (anicraft_geom::Affine, Arc) { + let e = s.visible_elements().into_iter().find(|e| e.id == id).unwrap(); + match &e.kind { + ElementKind::Text(t) => (e.transform, t.clone()), + other => panic!("not text: {other:?}"), + } +} + +/// A session with "Along the line" and a 400 px line from (100, 300) to (500, 300). +fn text_and_line() -> (Session, ElementId, ElementId) { + let mut s = Session::default(); + let text = ElementId(run(&mut s, "text.create", json!({"text": "Along the line", "x": 50, "y": 50, "size": 24}))["element"].as_u64().unwrap()); + let line = ElementId(run(&mut s, "draw.line", json!({"x0": 100, "y0": 300, "x1": 500, "y1": 300}))["element"].as_u64().unwrap()); + (s, text, line) +} + +#[test] +fn text_attaches_to_a_selected_shape_and_sits_on_it() { + if !fonts() { + return; + } + let (mut s, text, line) = text_and_line(); + run(&mut s, "element.select", json!({"ids": [text.0, line.0]})); + let steps = s.history().undo_len(); + let v = run(&mut s, "text.attach_path", json!({})); + assert_eq!(s.history().undo_len(), steps + 1, "one undo step"); + assert!((v["length"].as_f64().unwrap() - 400.0).abs() < 0.5, "{v}"); + assert_eq!(v["offset"], 0.0, "left-aligned text starts at the path's start"); + let (xf, t) = text_of(&s, text); + let on = t.on_path.as_ref().expect("on a path"); + // In stage space the glyphs stand on the line, starting at its start. + let b = t.outline.bounds().transformed(&xf); + assert!(b.max.y <= 300.0 + 8.0 && b.max.y > 295.0 && b.min.y < 290.0, "standing on y 300 (descenders a little below): {b:?}"); + assert!((b.min.x - 100.0).abs() < 4.0, "{b:?}"); + let path = on.path.transformed(&xf).bounds(); + assert!((path.min.x - 100.0).abs() < 1e-3 && (path.max.x - 500.0).abs() < 1e-3); + // The box holds the path and the glyphs from the origin. + let local = t.outline.bounds().union(&on.path.bounds()); + assert!(local.min.x.abs() < 1e-3 && local.min.y.abs() < 1e-3 && (local.width() - t.box_width).abs() < 1e-3 && (local.height() - t.box_height).abs() < 1e-3, "{local:?}"); + // The shape is left as it is, and only the text is selected. + assert!(s.visible_elements().iter().any(|e| e.id == line)); + assert_eq!(s.selection.on(s.layer), vec![text]); + // Undo puts the text back in its lines. + s.undo().unwrap(); + assert!(text_of(&s, text).1.on_path.is_none()); +} + +#[test] +fn offset_flip_alignment_and_edits_keep_text_on_its_path() { + if !fonts() { + return; + } + let (mut s, text, line) = text_and_line(); + run(&mut s, "element.select", json!({"ids": [text.0]})); + // Picking the shape at a stage point (the stage's pick mode does this). + run(&mut s, "text.attach_path", json!({"x": 300, "y": 300})); + let left = |s: &Session| { + let (xf, t) = text_of(s, text); + t.outline.bounds().transformed(&xf) + }; + let at0 = left(&s); + run(&mut s, "text.path", json!({"offset": 100})); + let at100 = left(&s); + assert!((at100.min.x - at0.min.x - 100.0).abs() < 0.5, "{at0:?} → {at100:?}"); + // Flipped: from the other end, below the line. + run(&mut s, "text.path", json!({"flip": true})); + let f = left(&s); + assert!(f.min.y > 290.0 && f.max.y > 310.0 && (f.max.x - 400.0).abs() < 1.0, "{f:?}"); + run(&mut s, "text.path", json!({"flip": false, "offset": 200})); + // Centred text is centred on its offset. + run(&mut s, "text.edit", json!({"align": "center"})); + let c = left(&s); + assert!((c.center().x - 300.0).abs() < 3.0, "centred on x 300: {c:?}"); + // Editing the words or the size keeps it on the path, where it was. + run(&mut s, "text.edit", json!({"text": "Hi", "size": 40})); + let (xf, t) = text_of(&s, text); + assert_eq!(t.text, "Hi"); + assert!(t.on_path.is_some()); + assert!((t.on_path.as_ref().unwrap().path.transformed(&xf).bounds().min.x - 100.0).abs() < 1e-3, "the path doesn't move"); + assert!((left(&s).center().x - 300.0).abs() < 3.0); + // Text on a path is static text. + assert!(s.execute("text.field", &json!({"type": "dynamic"})).is_err()); + // Released: back to a line of text where it started. + let before = left(&s); + run(&mut s, "text.release_path", json!({})); + let (_, t) = text_of(&s, text); + assert!(t.on_path.is_none()); + let after = left(&s); + assert!((after.min.x - before.min.x).abs() < 6.0 && (after.min.y - before.min.y).abs() < 12.0, "{before:?} → {after:?}"); + assert!(s.execute("text.path", &json!({"offset": 5})).is_err(), "no text on a path selected"); + let _ = line; +} + +#[test] +fn bad_requests_change_nothing() { + if !fonts() { + return; + } + let (mut s, text, line) = text_and_line(); + // No shape anywhere selected or there. + run(&mut s, "element.select", json!({"ids": [text.0]})); + assert!(s.execute("text.attach_path", &json!({})).is_err()); + assert!(s.execute("text.attach_path", &json!({"x": 5, "y": 5})).is_err()); + assert!(s.execute("text.attach_path", &json!({"x": 5})).is_err()); + assert!(s.execute("text.attach_path", &json!({"path": line.0, "offset": 1e9})).is_err()); + // Only the shape selected: no text. + run(&mut s, "element.select", json!({"ids": [line.0]})); + assert!(s.execute("text.attach_path", &json!({})).is_err()); + assert!(text_of(&s, text).1.on_path.is_none()); + // By id works from another layer too. + run(&mut s, "layer.new", json!({})); + let other = ElementId(run(&mut s, "draw.ellipse", json!({"x": 100, "y": 100, "w": 200, "h": 200}))["element"].as_u64().unwrap()); + let base = s.timeline().layers.last().unwrap().id; + run(&mut s, "layer.select", json!({"layer": base.0})); + run(&mut s, "element.select", json!({"ids": [text.0]})); + run(&mut s, "text.attach_path", json!({"path": other.0})); + assert!(text_of(&s, text).1.on_path.is_some()); +} + +#[test] +fn text_on_a_path_is_saved_and_older_files_open_without_it() { + if !fonts() { + return; + } + let (mut s, text, line) = text_and_line(); + run(&mut s, "element.select", json!({"ids": [text.0, line.0]})); + run(&mut s, "text.attach_path", json!({"offset": 12.5, "flip": true})); + let (_, t) = text_of(&s, text); + let json = serde_json::to_string(&*t).unwrap(); + assert!(json.contains("\"on_path\"") && json.contains("\"offset\":12.5") && json.contains("\"flip\":true"), "{json}"); + let back: TextBlock = serde_json::from_str(&json).unwrap(); + assert_eq!(back, *t); + // The whole document round-trips through the file format. + let saved = crate::format::to_json(&s.doc).unwrap(); + let doc = crate::format::from_json(&saved).unwrap(); + assert_eq!(doc, s.doc); + // A block saved before text on a path opens as plain text. + let mut v: Value = serde_json::from_str(&json).unwrap(); + v.as_object_mut().unwrap().remove("on_path"); + assert!(serde_json::from_value::(v).unwrap().on_path.is_none()); + // It renders from its outlines alone: the same pixels without the font. + let a = anicraft_render::render_frame(&s.doc, 0, 0.5).unwrap(); + assert!(a.data.iter().any(|p| p[0] < 0.5), "the text draws"); +} diff --git a/crates/render/src/html_tests.rs b/crates/render/src/html_tests.rs index 01b8fd7d..4b0ef876 100644 --- a/crates/render/src/html_tests.rs +++ b/crates/render/src/html_tests.rs @@ -892,7 +892,7 @@ fn the_js_player_draws_random_numbers_like_the_rust_player() { /// (layout isn't compared: neither player lays text out here). fn field_el(id: u64, name: &str, at: Vec2, (w, h): (f32, f32), text: &str, f: Option) -> Arc { let n = text.chars().count() as f32; - let t = anicraft_doc::TextBlock { text: text.into(), font: "Inter".into(), size: 14.0, bold: true, italic: false, color: Rgba::hex(0x112233), align: anicraft_doc::TextAlign::Center, letter_spacing: 0.5, line_spacing: 2.0, width: None, outline: Arc::new(Path::rect(2.0, 2.0, 8.0 * n, 12.0)), box_width: w, box_height: h, field: f }; + let t = anicraft_doc::TextBlock { text: text.into(), font: "Inter".into(), size: 14.0, bold: true, italic: false, color: Rgba::hex(0x112233), align: anicraft_doc::TextAlign::Center, letter_spacing: 0.5, line_spacing: 2.0, width: None, outline: Arc::new(Path::rect(2.0, 2.0, 8.0 * n, 12.0)), box_width: w, box_height: h, field: f, on_path: None }; Arc::new(Element { id: ElementId(id), name: name.into(), transform: Affine::translate(at.x, at.y), color: ColorEffect::default(), kind: ElementKind::Text(Arc::new(t)) }) } diff --git a/crates/svg/src/text.rs b/crates/svg/src/text.rs index f7d23103..69c9b444 100644 --- a/crates/svg/src/text.rs +++ b/crates/svg/src/text.rs @@ -292,6 +292,7 @@ impl<'a> Builder<'a> { box_width: layout.width, box_height: layout.height, field: None, + on_path: None, }; Ok(Some((block, ascent))) } diff --git a/crates/xfl/src/text.rs b/crates/xfl/src/text.rs index 549c5030..d54633f7 100644 --- a/crates/xfl/src/text.rs +++ b/crates/xfl/src/text.rs @@ -264,6 +264,7 @@ pub fn field(el: &X, fonts: &Fonts, faces: &mut HashMap, repo box_width: layout.width, box_height: layout.height, field: None, + on_path: None, }; out.push(Placed { block, offset: Vec2::new(origin.x + st.left_margin, origin.y + y) }); y += layout.lines as f32 * layout.line_height; @@ -367,6 +368,7 @@ fn text_field(el: &X, fonts: &Fonts, faces: &mut HashMap, rep box_width, box_height, field: Some(field), + on_path: None, }; Some(Placed { block, offset: Vec2::new(el.f32("left").unwrap_or(0.0), el.f32("top").unwrap_or(0.0)) }) } From 16a871e7edde2c735fff343ad8ec5da03ff2dea3 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Thu, 12 Nov 2026 00:47:00 -0700 Subject: [PATCH 15/18] feat(shell): Attach to Path by picking a shape on the stage, path rows in Properties, the path shown on selection; soft mask and path text screenshots (M4) --- docs/guide/reference/commands.md | 14 ++++++++--- src/a11y.rs | 2 +- src/app.rs | 37 ++++++++++++++++++++++++++++ src/main.rs | 2 +- src/panels.rs | 41 +++++++++++++++++++++++++++++++- src/stage.rs | 22 +++++++++++++++++ 6 files changed, 112 insertions(+), 6 deletions(-) diff --git a/docs/guide/reference/commands.md b/docs/guide/reference/commands.md index 1a5d1b38..834d0819 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 258 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 262 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. @@ -137,7 +137,7 @@ This page is generated from the command registry, so it always matches the versi - **Mask** `layer.toggle_mask` · Modify › Timeline · changes the document Parameters: `{layer?}` - **Layer Properties** `layer.set_properties` · Modify › Timeline · changes the document - Parameters: `{layer?, name?, type?: normal|mask|masked|guide|guided, 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` + 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 Shape Hint** `tween.add_hint` · Modify › Shape · **Ctrl+Shift+H** (macOS **⇧⌘H**) · changes the document @@ -192,6 +192,10 @@ This page is generated from the command registry, so it always matches the versi Parameters: `{}` - **Distribute Vertical Centers** `align.distribute_v` · Modify › Align · changes the document Parameters: `{}` +- **Attach Text to Path** `text.attach_path` · Modify › Text · changes the document + Parameters: `{path?: element id of a shape (default: the other selected element, a shape), x?, y? (pick the shape at this stage point instead), offset? (px along the path; default by the text's alignment: its start, middle or end), flip?: bool} sets the selected static text along a copy of the shape's outline (its first contour); the shape stays as it is (ADR 0070)` +- **Release Text from Path** `text.release_path` · Modify › Text · changes the document + Parameters: `{} the selected text on a path goes back to lines of text (ADR 0070)` ## Commands @@ -277,8 +281,10 @@ These commands have no menu item: the panels, the stage and the timeline use the Parameters: `{color: "#rrggbb", layer?} the layer's colour: its outlines in outline mode and its bar on the timeline` - **Layer Height** `layer.set_height` · changes the document Parameters: `{height: 100 | 200 | 300 (percent of a normal row), layer?} the layer's row height on the timeline` +- **Mask Type** `layer.set_mask` · changes the document + Parameters: `{mask: coverage|alpha|luminance, layer?} how a mask layer reveals the layers it masks: coverage (its fills' area, as in Animate), alpha (its artwork's opacity: gradients and faded shapes make soft edges) or luminance (its brightness: white shows, black hides; SVG's mask) (ADR 0070)` - **Get Layer Properties** `layer.properties` - Parameters: `{layer?} the layer's name, type, colour, outline, height (percent), visible, locked and onion` + Parameters: `{layer?} the layer's name, type, mask type (mask layers), colour, outline, height (percent), visible, locked and onion` - **Camera** `camera.set` · changes the document Parameters: `{x?, y? (camera centre, stage px), dx?, dy? (pan by), zoom? (%, 5–2000), zoom_by? (factor), rotation? (°), rotate_by? (°), tint? (#rrggbb), tint_amount? (%), reset?: bool, frame?}` - **Camera Info** `camera.info` @@ -497,6 +503,8 @@ These commands have no menu item: the panels, the stage and the timeline use the Parameters: `{text?, font?, size? (px), bold?, italic?, color?, align?: left|center|right, letter_spacing?, line_spacing?, width? (px, wraps; null: one line per paragraph)} on the selected text` - **Fonts** `text.fonts` Parameters: `{}` +- **Text on Path** `text.path` · changes the document + Parameters: `{offset? (px along the path), flip?: bool (along the path backwards, on its other side), release?: bool (back to lines of text where it starts)} on the selected text on a path (ADR 0070)` - **Text Type** `text.field` · changes the document Parameters: `{type?: static|dynamic|input, lines?: single|multiline|multiline_no_wrap|password (input only), width?, height? (the field's box, px), selectable?, border?, background?, border_color?, background_color?, max_chars? (input; 0: no limit), variable? (kept, not run)} on the selected text; dynamic and input fields are named with instance.set_name and scripted in Test Movie and the HTML export (ADR 0066)` - **Width Profile** `stroke.set_profile` · changes the document diff --git a/src/a11y.rs b/src/a11y.rs index 8f93ffd3..1cf66791 100644 --- a/src/a11y.rs +++ b/src/a11y.rs @@ -374,7 +374,7 @@ mod tests { for tool in [Tool::Bone, 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", "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", "brushlibrary", "brushcurve", "paintbrush"] { + for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "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", "brushlibrary", "brushcurve", "paintbrush"] { found.extend(check(panel, |a, _| a.open_panel(Some(panel)))); } // Test Movie in a window of its own (ADR 0062): its controls, named in that window. diff --git a/src/app.rs b/src/app.rs index 6dccf28e..d0a1e7e0 100644 --- a/src/app.rs +++ b/src/app.rs @@ -337,6 +337,8 @@ pub struct App { pub library: crate::library::LibraryView, /// Text being typed on the stage. pub text_edit: Option, + /// Attach to Path is waiting for a click on a shape (ADR 0070): the text to set along it. + pub path_pick: Option, /// Font families on this computer, listed once on first need. pub font_families: Option>, pub star_points: u32, @@ -584,6 +586,7 @@ impl App { library_sel, library: Default::default(), text_edit: None, + path_pick: None, font_families: None, star_points: 5, rect_radius: 0.0, @@ -1309,6 +1312,40 @@ impl App { crate::test_movie::demo_pointer(self); } } + Some(which @ ("softmask" | "pathtext")) => { + // Soft masks and text on a path (ADR 0070): colour bands seen through a radial + // gradient on an alpha mask layer, and a line of text along an oval. `softmask` + // opens the mask layer's Layer Properties; `pathtext` selects the text. + self.perform("file.new", json!({"width": 640, "height": 400})); + self.run("draw.rect", json!({"x": 0, "y": 0, "w": 640, "h": 400, "fill": "#1d3557", "stroke": null})); + self.run("layer.new", json!({"name": "Bands"})); + for (i, c) in ["#e76f51", "#f4a261", "#e9c46a", "#2a9d8f", "#8ab17d"].iter().enumerate() { + self.run("draw.rect", json!({"x": 120 + 80 * i, "y": 40, "w": 80, "h": 320, "fill": c, "stroke": null})); + } + let mask = self.run("layer.new", json!({"name": "Soft mask"})).and_then(|v| v["layer"].as_u64()); + let stops = vec![anicraft_engine::doc::GradientStop { offset: 0.0, color: anicraft_engine::doc::Rgba::WHITE }, anicraft_engine::doc::GradientStop { offset: 1.0, color: anicraft_engine::doc::Rgba::WHITE.with_alpha(0.0) }]; + let swatch = std::mem::replace(&mut self.s.style.fill_paint, Some(anicraft_engine::doc::Paint::Radial { center: anicraft_engine::geom::Vec2::new(320.0, 200.0), radius: 190.0, stops })); + self.run("draw.ellipse", json!({"x": 130, "y": 10, "w": 380, "h": 380, "stroke": null})); + self.s.style.fill_paint = swatch; + self.run("layer.toggle_mask", json!({})); + self.run("layer.set_mask", json!({"mask": "alpha"})); + self.run("layer.new", json!({"name": "Title"})); + // i18n-exempt: document content + let text = self.run("text.create", json!({"text": "Soft masks · text on a path", "x": 40, "y": 40, "size": 26, "color": "#f1faee", "align": "center"})).and_then(|v| v["element"].as_u64()); + let oval = self.run("draw.ellipse", json!({"x": 70, "y": 25, "w": 500, "h": 350, "fill": null, "stroke": "#f1faee", "stroke_width": 1})).and_then(|v| v["element"].as_u64()); + if let (Some(t), Some(o)) = (text, oval) { + self.run("element.select", json!({"ids": [t]})); + self.run("text.attach_path", json!({"path": o, "offset": 1080})); + self.run("element.select", json!({"ids": [o]})); + self.run("edit.delete", json!({})); + self.run("element.select", json!({"ids": [t]})); + } + if which == "softmask" + && let Some(m) = mask + { + crate::layer_props::open(self, Some(anicraft_engine::doc::LayerId(m))); + } + } Some(which @ ("textfields" | "testtext")) => { // Dynamic and input text fields (ADR 0066): a score a script sets, a name field // and a multiline notes field. `textfields` selects the name field for its diff --git a/src/main.rs b/src/main.rs index 594d1051..8bd2b7dd 100644 --- a/src/main.rs +++ b/src/main.rs @@ -226,7 +226,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 wgpu|gl] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--open palette|shortcuts|lastscene|start|drop|droplibrary|select|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|symboledit|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|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testmovieinside|testscript|textfields|testtext|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|library|librarymenu|colour|layerprops|frameview|layercolour|timelinepolish]\n\ +const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png [--shot-width ]] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--open palette|shortcuts|lastscene|start|drop|droplibrary|select|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|symboledit|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|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]\n\ --renderer force the GPU backend (also ANICRAFT_RENDERER); default wgpu, 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/panels.rs b/src/panels.rs index c7a79b2d..e0967d89 100644 --- a/src/panels.rs +++ b/src/panels.rs @@ -3,7 +3,7 @@ use crate::app::{App, Tool}; use crate::icons::{self, Icon}; use crate::theme::{Section, T, TARGET, TOOL_BUTTON, TOOL_ICON, Type, color, section, text, to_color32, with_type}; -use anicraft_engine::doc::{ColorEffect, ColorStyle, ElementKind, LibraryItem, LineType, Paint, Rgba, SymbolKind, TextKind, evaluate_layer_elements}; +use anicraft_engine::doc::{ColorEffect, ColorStyle, ElementKind, LibraryItem, LineType, MAX_PATH_OFFSET, Paint, Rgba, SymbolKind, TextKind, evaluate_layer_elements}; use crate::a11y::{self, Named}; use egui::{Color32, Pos2, Rect, Sense, Stroke, StrokeKind, WidgetType, pos2, vec2}; use serde_json::{Value, json}; @@ -795,6 +795,7 @@ fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::E app.text_edit = Some(crate::app::TextEditing { at: pos2(at.x, at.y), element: Some(e.id), text: t.text.clone(), original: t.text.clone(), focus: true }); } }); + text_path_rows(app, ui, e, t); } if let ElementKind::Shape(sh) = &e.kind { ui.add_space(4.0); @@ -882,6 +883,44 @@ fn bitmap_row(app: &mut App, ui: &mut egui::Ui, current: anicraft_engine::doc::B }); } +/// Text on a path (ADR 0070): Attach to Path (then a click on a shape) for static text; for text +/// on a path, where it sits along it, its side, and Release. +fn text_path_rows(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::Element, t: &anicraft_engine::doc::TextBlock) { + if t.field.is_some() { + return; + } + let Some(on) = &t.on_path else { + row_prose(ui, tr!("Path"), |ui| { + let waiting = app.path_pick == Some(e.id); + let label = if waiting { tr!("Click a shape…") } else { tr!("Attach to Path") }; + if ui.selectable_label(waiting, label).on_hover_text(tr!("Then click a shape on the stage: the text follows its outline (Esc cancels)")).clicked() { + if waiting { + app.path_pick = None; + } else { + app.path_pick = Some(e.id); + app.status_ok(tr!("Click a shape to set the text along its outline. Esc cancels.")); + } + } + }); + return; + }; + let mut offset = on.offset; + row(ui, tr!("Path"), |ui| { + if ui.add(egui::DragValue::new(&mut offset).prefix(format!("{} ", tr!("Offset"))).suffix(" px").speed(0.5).range(-MAX_PATH_OFFSET..=MAX_PATH_OFFSET).max_decimals(1)).named(tr!("Offset along the path")).on_hover_text(tr!("Where the text sits along the path: its alignment decides whether it starts, is centred or ends there")).changed() { + live(app, tr_noop!("Text on Path"), "text.path", json!({"offset": offset})); + } + }); + row_prose(ui, tr!("Side"), |ui| { + let mut flip = on.flip; + if crate::theme::checkbox(ui, &mut flip, tr!("Flip")).on_hover_text(tr!("Run the text along the path the other way, on its other side")).changed() { + app.run("text.path", json!({"flip": flip})); + } + if ui.button(tr!("Release")).on_hover_text(tr!("Back to lines of text, where the text starts")).clicked() { + app.run("text.release_path", json!({})); + } + }); +} + /// A text type's name, as the Properties panel shows it. pub(crate) fn text_kind_label(kind: TextKind) -> &'static str { match kind { diff --git a/src/stage.rs b/src/stage.rs index 405dc44f..3b193a5e 100644 --- a/src/stage.rs +++ b/src/stage.rs @@ -633,11 +633,22 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { app.snap_ring = None; } + // Attach to Path (ADR 0070) waits for a click on a shape; Escape gives up. + if app.path_pick.is_some() && ui.input(|i| i.key_pressed(egui::Key::Escape)) { + app.path_pick = None; + app.status_ok(tr!("Attach to Path cancelled.")); + } if resp.clicked() && !paused && let Some(p) = resp.interact_pointer_pos() { let sp = to_stage(p); match app.tool { + _ if !panning && let Some(text) = app.path_pick.take() => { + app.s.selection = anicraft_engine::Selection::only(app.s.layer, [text]); + if app.run("text.attach_path", json!({"x": sp.x, "y": sp.y})).is_some() { + app.status_ok(tr!("The text follows the shape's outline. {undo} to undo.", undo = app.undo_key())); + } + } Tool::Subselect if !panning => { if !crate::motion_path::click(app, p, xf, shift) { crate::pathtools::subselect_click(app, p, shift, xf); @@ -1017,6 +1028,17 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { continue; } painter.rect_stroke(r, 0.0, sel_stroke, StrokeKind::Middle); + // Text on a path shows the path it follows (ADR 0070). + if let anicraft_engine::doc::ElementKind::Text(t) = &e.kind + && let Some(on) = &t.on_path + && let Some(item) = app.s.display_list().items.iter().find(|i| i.element == id) + { + let to_px = Affine::translate(origin.x, origin.y).mul(&Affine::scale(zoom, zoom)).mul(&item.transform); + for pl in on.path.flatten(&to_px, 0.5) { + let pts: Vec = pl.points.iter().map(|p| pos2(p.x, p.y)).collect(); + painter.add(if pl.closed { egui::Shape::closed_line(pts, sel_stroke) } else { egui::Shape::line(pts, sel_stroke) }); + } + } for c in [r.left_top(), r.right_top(), r.left_bottom(), r.right_bottom(), r.center_top(), r.center_bottom(), r.left_center(), r.right_center()] { let h = Rect::from_center_size(c, vec2(6.0, 6.0)); painter.rect_filled(h, 0.0, Color32::WHITE); From d146fa4ebbfcc0ed58ea241ad835cc4e2dd1bce2 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Thu, 12 Nov 2026 00:52:25 -0700 Subject: [PATCH 16/18] feat(svg): textPath onto text on a path; per-character x, y, dx, dy and rotate where simple; fixture with goldens (M4) --- crates/engine/src/cmds_text.rs | 15 +- crates/engine/src/tests.rs | 41 +++ crates/svg/fixtures/soft-masks-text-paths.svg | 14 + crates/svg/src/text.rs | 294 ++++++++++++++++-- crates/svg/src/text_tests.rs | 81 ++++- crates/text/src/lib.rs | 23 ++ 6 files changed, 433 insertions(+), 35 deletions(-) create mode 100644 crates/svg/fixtures/soft-masks-text-paths.svg diff --git a/crates/engine/src/cmds_text.rs b/crates/engine/src/cmds_text.rs index b45c33ac..9947d15d 100644 --- a/crates/engine/src/cmds_text.rs +++ b/crates/engine/src/cmds_text.rs @@ -230,11 +230,8 @@ pub(crate) fn lay_out_on_path(text: &str, style: &TextStyle, on: &TextPath) -> R TextAlign::Right => Align::Right, }; let offset = if on.offset.is_finite() { on.offset.clamp(-MAX_PATH_OFFSET, MAX_PATH_OFFSET) } else { 0.0 }; - let set = anicraft_text::on_path(&layout.glyphs, &on.path, anicraft_text::PathPlacement { offset, flip: on.flip, align }).ok_or_else(|| EngineError::State("the path has no length to set text along".into()))?; - // The box: the path and the glyphs, from the origin. - let b = set.outline.bounds().union(&on.path.bounds()); - let shift = if b.min.x.is_finite() && b.min.y.is_finite() { b.min } else { Vec2::ZERO }; - let back = Affine::translate(-shift.x, -shift.y); + let set = anicraft_text::on_path_boxed(&layout.glyphs, &on.path, anicraft_text::PathPlacement { offset, flip: on.flip, align }).ok_or_else(|| EngineError::State("the path has no length to set text along".into()))?; + let shift = set.shift; let block = TextBlock { text: text.to_string(), font: layout.family, @@ -246,11 +243,11 @@ pub(crate) fn lay_out_on_path(text: &str, style: &TextStyle, on: &TextPath) -> R letter_spacing: style.letter_spacing, line_spacing: style.line_spacing, width: None, - outline: Arc::new(set.outline.transformed(&back)), - box_width: if b.width().is_finite() { b.width().max(0.0) } else { 0.0 }, - box_height: if b.height().is_finite() { b.height().max(0.0) } else { 0.0 }, + outline: Arc::new(set.outline), + box_width: set.width, + box_height: set.height, field: None, - on_path: Some(TextPath { path: on.path.transformed(&back), offset, flip: on.flip }), + on_path: Some(TextPath { path: set.path, offset, flip: on.flip }), }; Ok((block, note, shift)) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 2fd1e223..e79a1592 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1557,6 +1557,47 @@ fn soft_masks_round_trip_through_svg_onto_soft_mask_layers() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn the_soft_mask_and_text_path_fixture_imports_with_its_goldens() { + // crates/svg/fixtures/soft-masks-text-paths.svg (ADR 0070): pixel values worked out from + // the drawing itself. + let dir = std::env::temp_dir().join(format!("anicraft-svg-fixture-0070-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let svg = dir.join("fixture.svg"); + std::fs::write(&svg, include_str!("../../svg/fixtures/soft-masks-text-paths.svg")).unwrap(); + let mut s = Session::default(); + run(&mut s, "file.new", json!({"width": 200, "height": 100})); + run(&mut s, "file.import", json!({"path": svg.display().to_string(), "x": 0, "y": 0})); + let tl = s.doc.timeline(s.scene); + let mut modes: Vec = tl.layers.iter().filter(|l| l.kind == anicraft_doc::LayerKind::Mask).map(|l| l.mask_mode).collect(); + modes.sort_by_key(|m| m.key()); + assert_eq!(modes, [anicraft_doc::MaskMode::Alpha, anicraft_doc::MaskMode::Luminance]); + let pm = anicraft_render::render_frame(&s.doc, 0, 1.0).unwrap(); + let px = |x, y| pm.pixel(x, y).unwrap(); + // Alpha mask: red fades out left to right, x 25 → 1 − 25.5 / 100. + for (x, y) in [(25u32, 10u32), (75, 10)] { + let want = 1.0 - (x as f32 + 0.5) / 100.0; + assert!((px(x, y)[0] - want).abs() < 6e-3 && px(x, y)[1] < 1e-3, "({x}, {y}): {:?} vs {want}", px(x, y)); + } + // Luminance mask: #808080 shows 128 / 255 of the green. + assert!((px(150, 95)[1] - 128.0 / 255.0).abs() < 3e-3 && px(150, 95)[0] < 1e-3, "{:?}", px(150, 95)); + // The text follows the arc, centred on it, when this computer has fonts. + if !anicraft_text::Fonts::get().families().is_empty() { + let els: Vec> = s.timeline().layers.iter().filter_map(|l| anicraft_doc::evaluate_layer_elements(l, 0)).flat_map(|(_, e)| e.into_owned()).collect(); + let text = els.into_iter().find_map(|e| match &e.kind { + anicraft_doc::ElementKind::Text(t) => Some((e.transform, t.clone())), + _ => None, + }); + let (xf, t) = text.expect("the text"); + assert_eq!(t.text, "on the arc"); + let on = t.on_path.as_ref().expect("on its path"); + assert!(t.align == anicraft_doc::TextAlign::Center && on.offset > 50.0); + let b = t.outline.bounds().transformed(&xf); + assert!((b.center().x - 100.0).abs() < 4.0 && b.min.y > 20.0 && b.max.y < 70.0, "{b:?}"); + } + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn imported_svg_text_is_editable_text() { if anicraft_text::Fonts::get().families().is_empty() { diff --git a/crates/svg/fixtures/soft-masks-text-paths.svg b/crates/svg/fixtures/soft-masks-text-paths.svg new file mode 100644 index 00000000..050025db --- /dev/null +++ b/crates/svg/fixtures/soft-masks-text-paths.svg @@ -0,0 +1,14 @@ + + + + + + + + + + + + on the arc + diff --git a/crates/svg/src/text.rs b/crates/svg/src/text.rs index 69c9b444..925fa7ae 100644 --- a/crates/svg/src/text.rs +++ b/crates/svg/src/text.rs @@ -6,6 +6,11 @@ //! An AniCraft block has one style, so a chunk whose pieces differ in style takes the style of //! most of its visible characters, and the report counts it (as in ADR 0014). Whitespace is //! collapsed as browsers do, unless `xml:space="preserve"`. +//! +//! ADR 0070: a `textPath` becomes text on a path (its `startOffset`, `side` and the +//! `text-anchor`), and per-character positions are kept where they are simple: a character +//! with its own `x`/`y`, a `dx`/`dy` shift or a `rotate` angle starts a block of its own there +//! (rotated about its baseline origin), the next continuing after the text before it. use crate::{Anchor, Builder, ImportedElement, PaintSpec, Style, declarations, get, hidden, length, local, name_of}; use anicraft_doc::{ElementKind, Paint, TextAlign, TextBlock}; @@ -26,9 +31,33 @@ struct Chunk { anchor: Anchor, pieces: Vec<(String, Style)>, chars: usize, + /// `x` is a shift from where the text before it ended (a `dx`), not a position. + follow: bool, + /// Degrees, about the chunk's baseline origin (a per-character `rotate`). + rotate: f32, + /// Set along a path (`textPath`). + path: Option, +} + +/// A `textPath`'s path in the text's user space, and where along it the text is anchored. +struct OnPath { + path: anicraft_geom::Path, + offset: f32, + flip: bool, } impl Chunk { + fn at(x: f32, y: f32, anchor: Anchor) -> Chunk { + Chunk { x, y, anchor, pieces: Vec::new(), chars: 0, follow: false, rotate: 0.0, path: None } + } +} + +impl Chunk { + /// Characters it holds, whitespace included (what moves the pen on). + fn len(&self) -> usize { + self.pieces.iter().map(|(t, _)| t.chars().count()).sum() + } + fn has_text(&self) -> bool { self.pieces.iter().any(|(t, _)| !t.trim().is_empty()) } @@ -38,8 +67,10 @@ impl Chunk { #[derive(Default)] struct Flags { per_char: bool, - rotated: bool, - on_path: bool, + nested_chars: bool, + lost_path: bool, + after_path: bool, + anchored_chars: bool, decorated: bool, vertical: bool, cut: bool, @@ -65,6 +96,44 @@ fn families(css: &str) -> Vec { css.split(',').map(|n| n.trim().trim_matches(['"', '\'']).trim().to_string()).filter(|n| !n.is_empty()).take(16).collect() } +/// A `textPath`'s text (its `tspan`s flattened into pieces of their styles). +fn gather(el: &X, style: &Style, c: &mut Chunk, report: &mut crate::Report, depth: usize) { + for child in &el.children { + match local(&child.name) { + anicraft_xml::TEXT_NODE => { + let room = MAX_CHARS.saturating_sub(c.chars); + c.chars += child.text.chars().count().min(room); + c.pieces.push((child.text.chars().take(room).collect(), style.clone())); + } + "tspan" | "a" if depth < MAX_TSPAN_DEPTH => { + let d = declarations(child); + if get(&d, "display") == Some("none") || hidden(&d) { + continue; + } + let st = style.with(child, report); + gather(child, &st, c, report, depth + 1); + } + _ => {} + } + } +} + +/// One text node's whitespace collapsed as browsers do (line breaks and tabs are spaces, runs +/// of spaces one), leading spaces dropped when `at_start`. +fn collapse_str(t: &str, at_start: bool) -> String { + let mut out = String::with_capacity(t.len()); + let mut prev_space = at_start; + for ch in t.chars() { + let ch = if matches!(ch, '\n' | '\r' | '\t') { ' ' } else { ch }; + if ch == ' ' && prev_space { + continue; + } + prev_space = ch == ' '; + out.push(ch); + } + out +} + /// Collapses whitespace across the chunks as browsers do: line breaks and tabs are spaces, /// runs of spaces are one, and spaces at the start go. `xml:space="preserve"` keeps them. fn collapse(chunks: &mut [Chunk]) { @@ -99,8 +168,10 @@ impl<'a> Builder<'a> { collapse(&mut chunks); let report = [ (flags.per_char, "per-character text positions (ignored)"), - (flags.rotated, "rotated characters (drawn upright)"), - (flags.on_path, "text on a path"), + (flags.nested_chars, "per-character positions running into nested tspans (ignored there)"), + (flags.lost_path, "text on a path whose path is missing (drawn on a line)"), + (flags.after_path, "text after a text path (placed at the text's start)"), + (flags.anchored_chars, "per-character shifts in centred or right-anchored text (approximate)"), (flags.decorated, "underlined or struck-through text (lines left out)"), (flags.vertical, "vertical text (drawn horizontal)"), (flags.cut, "text cut to 100,000 characters per block"), @@ -111,8 +182,20 @@ impl<'a> Builder<'a> { } } let mut out = Vec::new(); + // Where the text before ends (a following chunk continues there). + let mut pen_x = 0.0f32; + let mut space: Option = None; for c in chunks { + let start_x = if c.follow { pen_x + c.x } else { c.x }; if !c.has_text() { + // Only spaces: they still move the pen on. + if c.path.is_none() { + let n = c.len() as f32; + if n > 0.0 && let Some((_, st)) = c.pieces.first() { + let w = *space.get_or_insert_with(|| self.space_width(st)); + pen_x = start_x + n * w; + } + } continue; } // The style most of the visible characters have (the first on a tie). @@ -136,6 +219,26 @@ impl<'a> Builder<'a> { let Some((_, st)) = best.and_then(|(i, _)| c.pieces.get(i)) else { continue }; let st = st.clone(); let text: String = c.pieces.iter().map(|(t, _)| t.as_str()).collect(); + let trailing = text.chars().rev().take_while(|ch| *ch == ' ').count() as f32; + let align = match c.anchor { + Anchor::Start => TextAlign::Left, + Anchor::Middle => TextAlign::Center, + Anchor::End => TextAlign::Right, + }; + if let Some(on) = &c.path { + match self.path_block(text, &st, alpha, on, align) { + Ok(Some((block, shift))) => { + let transform = m.mul(&Affine::translate(shift.x, shift.y)); + if transform.is_finite() { + let name = if out.is_empty() { name_of(el) } else { String::new() }; + out.push(ImportedElement { name, transform, alpha, kind: ElementKind::Text(Arc::new(block)) }); + } + } + Ok(None) => {} + Err(()) => break, + } + continue; + } match self.text_block(text, &st, alpha) { Ok(Some((block, ascent))) => { let w = block.box_width; @@ -144,13 +247,18 @@ impl<'a> Builder<'a> { Anchor::Middle => -w * 0.5, Anchor::End => -w, }; - let transform = m.mul(&Affine::translate(c.x + shift, c.y - ascent)); + pen_x = start_x + shift + w + if trailing > 0.0 { trailing * *space.get_or_insert_with(|| self.space_width(&st)) } else { 0.0 }; + let transform = if c.rotate != 0.0 { + m.mul(&Affine::translate(start_x + shift, c.y)).mul(&Affine::rotate(c.rotate.to_radians())).mul(&Affine::translate(0.0, -ascent)) + } else { + m.mul(&Affine::translate(start_x + shift, c.y - ascent)) + }; if !transform.is_finite() { continue; } let name = if out.is_empty() { name_of(el) } else { String::new() }; let block_alpha = alpha; - let block = TextBlock { align: match c.anchor { Anchor::Start => TextAlign::Left, Anchor::Middle => TextAlign::Center, Anchor::End => TextAlign::Right }, ..block }; + let block = TextBlock { align, ..block }; out.push(ImportedElement { name, transform, alpha: block_alpha, kind: ElementKind::Text(Arc::new(block)) }); } Ok(None) => {} @@ -163,12 +271,12 @@ impl<'a> Builder<'a> { /// Reads `el`'s positions and content into chunks. fn text_content(&mut self, el: &'a X, style: &Style, chunks: &mut Vec, flags: &mut Flags, depth: usize) { let (vw, vh) = self.viewport; - let list = |key: &str, reference: f32| -> Vec { el.attr(key).map(|v| v.split([' ', ',', '\t', '\n', '\r']).filter(|p| !p.is_empty()).filter_map(|p| length(p, reference)).collect()).unwrap_or_default() }; + let list = |key: &str, reference: f32| -> Vec { el.attr(key).map(|v| v.split([' ', ',', '\t', '\n', '\r']).filter(|p| !p.is_empty()).take(MAX_CHARS).filter_map(|p| length(p, reference)).collect()).unwrap_or_default() }; let (xs, ys, dxs, dys) = (list("x", vw), list("y", vh), list("dx", vw), list("dy", vh)); - if xs.len() > 1 || ys.len() > 1 || dxs.len() > 1 || dys.len() > 1 { - flags.per_char = true; - } - flags.rotated |= el.attr("rotate").is_some_and(|r| r.split([' ', ',']).any(|v| v.trim().parse::().is_ok_and(|a| a != 0.0))); + let rotates: Vec = list("rotate", 1.0).into_iter().map(|a| if a.is_finite() { a } else { 0.0 }).collect(); + // Per-character positions (ADR 0070): the first values place the element's start (as + // before); the rest go to its own characters, in order. + let per_char = xs.len() > 1 || ys.len() > 1 || dxs.len() > 1 || dys.len() > 1 || rotates.iter().any(|a| *a != 0.0); let d = declarations(el); flags.decorated |= get(&d, "text-decoration").is_some_and(|v| v != "none"); flags.vertical |= get(&d, "writing-mode").is_some_and(|v| v.starts_with("tb") || v.starts_with("vertical")); @@ -179,13 +287,12 @@ impl<'a> Builder<'a> { return; } let y = ys.first().copied().or_else(|| chunks.last().map(|c| c.y)).unwrap_or(0.0); - chunks.push(Chunk { x: xs.first().copied().unwrap_or(0.0), y, anchor: style.anchor, pieces: Vec::new(), chars: 0 }); + chunks.push(Chunk::at(xs.first().copied().unwrap_or(0.0), y, style.anchor)); } else if let Some(&y) = ys.first() { - // A new line without a new x continues after the text before it, which only the - // layout knows: kept on the line when there is text already. + // A new line without a new x continues after the text before it. match chunks.last_mut() { Some(c) if !c.has_text() => c.y = y, - _ => flags.per_char = true, + _ => chunks.push(Chunk { follow: true, ..Chunk::at(0.0, y, style.anchor) }), } } let (dx, dy) = (dxs.first().copied().unwrap_or(0.0), dys.first().copied().unwrap_or(0.0)); @@ -195,35 +302,174 @@ impl<'a> Builder<'a> { c.x += dx; c.y += dy; } - _ => flags.per_char = true, + Some(c) => { + let y = c.y + dy; + chunks.push(Chunk { follow: true, ..Chunk::at(dx, y, style.anchor) }); + } + None => {} } } + // The character of this element's own text reached so far (for per-character values). + let mut k = 0usize; + let mut last_rotate = 0.0f32; for child in &el.children { match local(&child.name) { anicraft_xml::TEXT_NODE => { - let Some(c) = chunks.last_mut() else { continue }; - let room = MAX_CHARS.saturating_sub(c.chars); - let n = child.text.chars().count(); - if n > room { - flags.cut = true; + if !per_char { + let Some(c) = chunks.last_mut() else { continue }; + if c.path.is_some() { + // Text after a text path: on a line of its own at the text's start. + if !child.text.trim().is_empty() { + flags.after_path = true; + } + let (x, y) = (0.0, c.y); + chunks.push(Chunk::at(x, y, style.anchor)); + } + let Some(c) = chunks.last_mut() else { continue }; + let room = MAX_CHARS.saturating_sub(c.chars); + let n = child.text.chars().count(); + if n > room { + flags.cut = true; + } + c.chars += n.min(room); + c.pieces.push((child.text.chars().take(room).collect(), style.clone())); + continue; + } + // Character by character: one starts a chunk where it has its own position, + // shift or angle (or follows a rotated one). + let text = if style.preserve { child.text.clone() } else { collapse_str(&child.text, k == 0 && chunks.last().is_none_or(|c| !c.has_text())) }; + for ch in text.chars() { + let rot = rotates.get(k).or(rotates.last()).copied().unwrap_or(0.0); + let (ax, ay) = (xs.get(k).copied().filter(|_| k > 0), ys.get(k).copied().filter(|_| k > 0)); + let (ddx, ddy) = if k > 0 { (dxs.get(k).copied().unwrap_or(0.0), dys.get(k).copied().unwrap_or(0.0)) } else { (0.0, 0.0) }; + let has_text = chunks.last().is_some_and(Chunk::has_text); + let fresh = ax.is_some() || ay.is_some() || ddx != 0.0 || ddy != 0.0 || ((rot != 0.0 || last_rotate != 0.0) && has_text); + if fresh { + if chunks.len() >= MAX_CHUNKS { + flags.cut = true; + return; + } + let y = ay.or_else(|| chunks.last().map(|c| c.y)).unwrap_or(0.0) + ddy; + let c = match ax { + Some(x) => Chunk::at(x + ddx, y, style.anchor), + None => { + if style.anchor != Anchor::Start { + flags.anchored_chars = true; + } + Chunk { follow: true, ..Chunk::at(ddx, y, Anchor::Start) } + } + }; + chunks.push(c); + } + let Some(c) = chunks.last_mut() else { break }; + if c.chars >= MAX_CHARS { + flags.cut = true; + break; + } + c.rotate = rot; + c.chars += 1; + match c.pieces.last_mut() { + Some((t, st)) if same_look(st, style) && st.preserve == style.preserve => t.push(ch), + _ => c.pieces.push((ch.to_string(), style.clone())), + } + last_rotate = rot; + k += 1; } - c.chars += n.min(room); - c.pieces.push((child.text.chars().take(room).collect(), style.clone())); } "tspan" | "a" => { let cd = declarations(child); if get(&cd, "display") == Some("none") || hidden(&cd) || depth >= MAX_TSPAN_DEPTH { continue; } + if per_char && (k < xs.len().max(ys.len()).max(dxs.len()).max(dys.len()) || rotates.iter().skip(k).any(|a| *a != 0.0)) { + flags.nested_chars = true; + } let st = style.with(child, &mut self.report); self.text_content(child, &st, chunks, flags, depth + 1); } - "textPath" => flags.on_path = true, + "textPath" => { + let st = style.with(child, &mut self.report); + match self.text_path(child) { + Some(on) => { + if chunks.len() >= MAX_CHUNKS { + flags.cut = true; + return; + } + let y = chunks.last().map_or(0.0, |c| c.y); + let mut c = Chunk { path: Some(on), ..Chunk::at(0.0, y, st.anchor) }; + gather(child, &st, &mut c, &mut self.report, 0); + chunks.push(c); + } + None => { + flags.lost_path = true; + self.text_content(child, &st, chunks, flags, depth + 1); + } + } + } _ => {} } } } + /// A `textPath`'s path (`href`: a path or basic shape, with its own transform) and its + /// `startOffset` (a length or a percentage of the path's length) and `side`. + fn text_path(&mut self, tp: &'a X) -> Option { + let href = tp.attr("href").or_else(|| tp.attr("xlink:href"))?.trim().trim_start_matches('#'); + let target = self.ids.get(href).copied()?; + let name = local(&target.name); + if !matches!(name, "path" | "rect" | "circle" | "ellipse" | "polyline" | "polygon" | "line") { + return None; + } + let (path, _) = self.geometry(target, name)?; + let path = path.transformed(&target.attr("transform").map_or(Affine::IDENTITY, crate::transform)); + let len = anicraft_geom::walk::CurveWalk::new(&path)?.length(); + let offset = tp.attr("startOffset").map(str::trim).and_then(|v| match v.strip_suffix('%') { + Some(p) => p.trim().parse::().ok().map(|p| p / 100.0 * len), + None => length(v, len), + }); + let offset = offset.filter(|o| o.is_finite()).unwrap_or(0.0).clamp(-anicraft_doc::MAX_PATH_OFFSET, anicraft_doc::MAX_PATH_OFFSET); + Some(OnPath { path, offset, flip: tp.attr("side") == Some("right") }) + } + + /// The width a space takes in style `st` (pixels). + fn space_width(&mut self, st: &Style) -> f32 { + let fonts = self.fonts(); + let face = self.face(fonts, &st.font_family); + let style = anicraft_text::Style { family: face.family.unwrap_or_default(), size: st.font_size, bold: st.bold || face.bold, italic: st.italic || face.italic, letter_spacing: st.letter_spacing, ..anicraft_text::Style::default() }; + let w = |t: &str| fonts.layout(t, &style).map_or(0.0, |l| l.width); + (w("x x") - w("xx")).max(0.0) + } + + /// Lays one chunk out along its path: the block (on its path, boxed from the origin) and + /// where that origin is in the text's user space. `Ok(None)` draws nothing; `Err` means no + /// text can be laid out at all. + fn path_block(&mut self, text: String, st: &Style, alpha: f32, on: &OnPath, align: TextAlign) -> Result, ()> { + let Some((block, _)) = self.text_block(text, st, alpha)? else { return Ok(None) }; + let fonts = self.fonts(); + let style = anicraft_text::Style { family: block.font.clone(), size: block.size, bold: block.bold, italic: block.italic, letter_spacing: block.letter_spacing, ..anicraft_text::Style::default() }; + let line: String = block.text.chars().map(|c| if c == '\n' || c == '\r' { ' ' } else { c }).collect(); + let Ok(layout) = fonts.layout_glyphs(&line, &style) else { return Ok(None) }; + let how = anicraft_text::PathPlacement { + offset: on.offset, + flip: on.flip, + align: match align { + TextAlign::Left => Align::Left, + TextAlign::Center => Align::Center, + TextAlign::Right => Align::Right, + }, + }; + let Some(set) = anicraft_text::on_path_boxed(&layout.glyphs, &on.path, how) else { return Ok(None) }; + let block = TextBlock { + align, + outline: Arc::new(set.outline), + box_width: set.width, + box_height: set.height, + on_path: Some(anicraft_doc::TextPath { path: set.path, offset: on.offset, flip: on.flip }), + ..block + }; + Ok(Some((block, set.shift))) + } + /// Lays one chunk out: the block (aligned left, at the origin) and its first baseline. /// `Ok(None)` draws nothing; `Err` means no text can be laid out at all. fn text_block(&mut self, text: String, st: &Style, alpha: f32) -> Result, ()> { diff --git a/crates/svg/src/text_tests.rs b/crates/svg/src/text_tests.rs index 5c9b0471..7ed11db1 100644 --- a/crates/svg/src/text_tests.rs +++ b/crates/svg/src/text_tests.rs @@ -91,11 +91,19 @@ fn missing_fonts_and_unsupported_text_are_reported() { "##, fonts, ); - assert_eq!(t.len(), 3, "{:?}", t.iter().map(|(_, b)| &b.text).collect::>()); + // Per-character x positions split "Three" where they place characters (ADR 0070); a text + // path whose path is missing is drawn on a line. + let words: Vec<&str> = t.iter().map(|(_, b)| b.text.as_str()).collect(); + assert_eq!(words, ["One", "Two", "T", "h", "ree", "Four"]); + for (k, x) in [(3, 10.0), (4, 20.0)] { + let r = ink(&t[k].0, &t[k].1); + assert!(r.min.x >= x - 0.5 && r.min.x < x + 4.0, "{}: {r:?}", t[k].1.text); + } assert_eq!(report.missing_fonts.iter().map(String::as_str).collect::>(), ["Zz Missing Face"]); assert!(fonts.families().contains(report.fallback_font.as_ref().unwrap())); assert!(report.summary().contains("Fonts not on this computer, drawn in"), "{}", report.summary()); - for k in ["underlined or struck-through text (lines left out)", "per-character text positions (ignored)", "strokes on text (left out)", "text on a path", "outlined text without a fill (left out)"] { + assert_eq!(report.skipped.get("strokes on text (left out)"), Some(&3), "once per block"); + for k in ["underlined or struck-through text (lines left out)", "text on a path whose path is missing (drawn on a line)", "outlined text without a fill (left out)"] { assert_eq!(report.skipped.get(k), Some(&1), "{k}: {report:?}"); } } @@ -115,3 +123,72 @@ fn text_can_be_a_clip_and_needs_fonts() { let mask = i.layers.iter().find_map(|l| l.mask.as_ref()).expect("a mask layer"); assert!(matches!(&mask.elements[0].kind, ElementKind::Text(b) if b.text == "REVEAL"), "the mask stays editable text"); } + +#[test] +fn text_paths_become_text_on_a_path() { + let Some(fonts) = fonts() else { return }; + let (t, report) = texts( + r##" + + Start here + Middle + Under + Around the ring + "##, + fonts, + ); + assert!(report.skipped.is_empty(), "{report:?}"); + let words: Vec<&str> = t.iter().map(|(_, b)| b.text.as_str()).collect(); + assert_eq!(words, ["Start here", "Middle", "Under", "Around the ring"]); + for (_, b) in &t { + assert!(b.on_path.is_some(), "{}", b.text); + } + // On the line, standing on it, from its start. + let r = ink(&t[0].0, &t[0].1); + assert!((r.min.x - 50.0).abs() < 4.0 && r.max.y <= 206.0 && r.max.y > 195.0, "{r:?}"); + // startOffset 50% with text-anchor middle: centred on x 200. + assert_eq!(t[1].1.align, TextAlign::Center); + assert!((ink(&t[1].0, &t[1].1).center().x - 200.0).abs() < 3.0); + assert!((t[1].1.on_path.as_ref().unwrap().offset - 150.0).abs() < 0.01); + // side="right": walked backwards from the end, under the line. + let u = ink(&t[2].0, &t[2].1); + let on = t[2].1.on_path.as_ref().unwrap(); + assert!(on.flip && u.min.y > 195.0 && u.max.x <= 331.0, "{u:?}"); + // The ring keeps its own transform: glyphs sit round (200, 110), radius 60. + let ring = ink(&t[3].0, &t[3].1); + assert!(ring.min.x > 200.0 - 90.0 && ring.max.x < 200.0 + 90.0 && ring.min.y > 110.0 - 90.0 && ring.max.y < 110.0 + 90.0, "{ring:?}"); + let path = t[3].1.on_path.as_ref().unwrap().path.transformed(&t[3].0.transform).bounds(); + assert!((path.center().y - 110.0).abs() < 0.5 && (path.width() - 120.0).abs() < 0.5, "{path:?}"); +} + +#[test] +fn per_character_shifts_and_rotations_place_their_characters() { + let Some(fonts) = fonts() else { return }; + let (t, report) = texts( + r##" + abcd + xyz + ok + AB + "##, + fonts, + ); + assert!(report.skipped.is_empty(), "{report:?}"); + let words: Vec<&str> = t.iter().map(|(_, b)| b.text.as_str()).collect(); + assert_eq!(words, ["ab", "cd", "x", "y", "z", "o", "k", "A", "B"]); + // dx 30 on "c": it starts 30 px after "ab" ends. + let (ab, cd) = (ink(&t[0].0, &t[0].1), ink(&t[1].0, &t[1].1)); + let gap = cd.min.x - (t[0].0.transform.translation().x + t[0].1.box_width); + assert!((gap - 30.0).abs() < 3.0, "{ab:?} {cd:?} gap {gap}"); + assert!((ab.max.y - cd.max.y).abs() < 2.0, "same baseline"); + // dy moves each later character down, cumulatively. + let (x, y, z) = (ink(&t[2].0, &t[2].1), ink(&t[3].0, &t[3].1), ink(&t[4].0, &t[4].1)); + assert!((y.min.y - x.min.y - 10.0).abs() < 2.0 && (z.min.y - x.min.y - 20.0).abs() < 2.0, "{x:?} {y:?} {z:?}"); + assert!(y.min.x > x.max.x - 1.0, "continues after the x"); + // rotate 90 on "k": turned a quarter about its baseline origin (taller than wide, below). + let k = ink(&t[6].0, &t[6].1); + assert!(k.min.y > 140.0 && t[6].0.transform.m[1].abs() > 0.99, "{k:?} {:?}", t[6].0.transform); + // Absolute x and y lists place each character. + let b = ink(&t[8].0, &t[8].1); + assert!(b.min.x >= 40.0 && b.min.x < 44.0 && (b.max.y - 220.0).abs() < 1.5, "{b:?}"); +} diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 99839b1a..ce73b89d 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -168,6 +168,29 @@ pub fn on_path(glyphs: &[PlacedGlyph], path: &Path, how: PathPlacement) -> Optio Some(out) } +/// Text on a path in a box of its own, as text blocks keep it (ADR 0070): the glyphs set along +/// the path, then the glyphs and the path moved together so their bounds start at the origin. +#[derive(Clone, Debug, PartialEq)] +pub struct BoxedPathText { + pub outline: Path, + pub path: Path, + pub width: f32, + pub height: f32, + /// Where the box's origin is in the path's space: what to translate by to put it back. + pub shift: Vec2, + pub hidden: usize, +} + +/// [`on_path`], boxed ([`BoxedPathText`]). +pub fn on_path_boxed(glyphs: &[PlacedGlyph], path: &Path, how: PathPlacement) -> Option { + let set = on_path(glyphs, path, how)?; + let b = set.outline.bounds().union(&path.bounds()); + let shift = if b.min.x.is_finite() && b.min.y.is_finite() { b.min } else { Vec2::ZERO }; + let back = anicraft_geom::Affine::translate(-shift.x, -shift.y); + let size = |v: f32| if v.is_finite() { v.max(0.0) } else { 0.0 }; + Some(BoxedPathText { outline: set.outline.transformed(&back), path: path.transformed(&back), width: size(b.width()), height: size(b.height()), shift, hidden: set.hidden }) +} + /// Whether a path's first subpath ends with a close. fn first_subpath_closed(path: &Path) -> bool { for (i, c) in path.cmds.iter().enumerate() { From c574da20b16be437d0a48ac17a407ed876b7dfc8 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Thu, 12 Nov 2026 00:53:48 -0700 Subject: [PATCH 17/18] docs: ADR 0070 soft masks and text on a path; notes on ADR 0010, 0012, 0021; roadmap, changelog, guide, attribution (M4) --- ATTRIBUTION.md | 2 + CHANGELOG.md | 14 +++ docs/adr/0010-mask-layers.md | 6 ++ docs/adr/0012-text.md | 5 + docs/adr/0021-svg-clips-masks-text.md | 6 ++ .../adr/0070-soft-masks-and-text-on-a-path.md | 100 ++++++++++++++++++ docs/adr/README.md | 1 - docs/guide/images-and-sound.md | 9 +- docs/guide/masks-guides-camera-bones.md | 16 +++ docs/guide/text.md | 23 ++++ docs/roadmap.md | 6 +- 11 files changed, 180 insertions(+), 8 deletions(-) create mode 100644 docs/adr/0070-soft-masks-and-text-on-a-path.md diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 8d8b43d3..fb572a75 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -21,6 +21,7 @@ shaders or SDK code). | 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` (21 files: align, distribute, layer, mask and masked layer, width tool, camera, brush, paint brush, eraser, eyedropper, muted sound, magnet, bone, edit multiple frames) | Align panel, layer-type, Width tool, Camera, Brush, Paint Brush, Eraser, Eyedropper and Bone tool icons, the timeline's mute toggle, Snap to Objects, Edit Multiple Frames | 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-*` (33 files: tools, transport, layer toggles, folders, guide, image, text, sound, chevrons) | 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) | ISC (Lucide) and MIT (Feather), [`licenses/icons/LICENSE-lucide.txt`](licenses/icons/LICENSE-lucide.txt) | | `assets/app-icon/` (`anicraft.svg`, `anicraft-small.svg` and every render: PNGs, `anicraft.ico`, `hicolor/`) | App icon (engraved rabbit): window, Dock, taskbar, `anicraft.exe`, Help › About | Project owner (ArtCraft team) | Original artwork drawn in ArtCraft for AniCraft, vectorised by `assets/app-icon/trace.py` and rendered by `scripts/icons.sh` | MIT OR Apache-2.0 ([`assets/app-icon/LICENSE.txt`](assets/app-icon/LICENSE.txt)) | | `packaging/macos/dmg/` (`background.tiff`, `dmg-layout.DS_Store`) | macOS DMG window background and Finder layout | AniCraft contributors | Original work drawn by `packaging/macos/dmg/generate.py` in the app icon's colours; layout approach as in the PhotoCraft sibling project | MIT OR Apache-2.0 | @@ -116,6 +117,7 @@ OR Apache-2.0) is noted in the table. | Least-squares cubic Bézier curve fitting (Pencil "Smooth", Brush centre lines and outlines; deleting a motion path point refits its neighbours, `Path::merge_at`; deleting a raw drawing's point joins its edges, `raw::join`, ADR 0045) | `crates/geom/src/fit.rs`, `crates/geom/src/edit.rs`, `crates/geom/src/raw.rs` | P. J. Schneider, *An Algorithm for Automatically Fitting Digitized Curves*, Graphics Gems (1990) | Ported from PhotoCraft's mask tracer and adapted for open strokes. Published algorithm. | | Monotone cubic interpolation of stroke widths (width profiles) | `crates/doc/src/width.rs` | F. N. Fritsch and R. E. Carlson, *Monotone Piecewise Cubic Interpolation*, SIAM J. Numer. Anal. 17(2), 1980 | Published algorithm (harmonic-mean tangents). | | Stroke caps, joins, miter limit and dash patterns (`butt`/`square` caps, miter length and limit, dash arrays restarting per subpath, zero-length round-capped dashes as dots) | `crates/doc/src/stroke_style.rs`, `crates/render/src/stroke.rs`, SVG/HTML/Lottie export, `crates/svg` | W3C SVG 1.1 §11.4 and SVG 2 / CSS Fill and Stroke Module Level 3 (stroke properties); WHATWG HTML canvas line styles; the public Lottie JSON schema (`lc`, `lj`, `ml`, `d`); public descriptions of XFL `SolidStroke`/`DashedStroke`/`DottedStroke` attributes | W3C Royalty-Free Patent Policy; open specifications. | +| Soft masks (alpha and luminance masks, `luminanceToAlpha` coefficients, `mask-type`) and text on a path (`textPath`, `startOffset`, `side`, glyph midpoints on the path, per-character `x`/`y`/`dx`/`dy`/`rotate`) | `crates/render`, `crates/gpu`, `crates/text`, `crates/svg` | W3C CSS Masking Module Level 1 (§7 mask types); W3C SVG 1.1 §10.13 and §14.4, SVG 2 §11.8 (text on a path); W3C Filter Effects (`luminanceToAlpha`); the public Lottie JSON schema (track mattes `td`/`tt`); WHATWG HTML canvas compositing | W3C Royalty-Free Patent Policy; open specifications. Own implementation (ADR 0070). | | Variable-width stroke outlines (trapezoids, outer round joins, caps) | `crates/render/src/stroke.rs` | Standard stroking construction from the public computer-graphics literature | Own implementation (ADR 0018); built-in profiles are AniCraft's own. | | Brush outlines (the swept tip as a signed distance field: exact distance to the convex hull of two tips, L2 for round and L∞ for square tips, minimised in closed form; traced at level zero) | `crates/geom/src/brush.rs` | Standard sweep and distance-field constructions from the public computer-graphics literature; behaviour of Animate's Brush tool learned from Adobe's public help and observation | Own implementation (ADR 0033); no Adobe code or presets. | | Pressure curves (monotone cubic through the curve's points: Fritsch–Butland tangents with the Fritsch–Carlson limits), Paint Brush width profiles simplified by Ramer–Douglas–Peucker, the Chalk brush's worn edge (two-octave value noise from SplitMix64's finaliser, subtracted from the brush's distance field) | `crates/geom/src/pressure.rs`, `crates/geom/src/brush.rs`, `crates/engine/src/cmds_brush.rs` | F. N. Fritsch & R. E. Carlson, *Monotone Piecewise Cubic Interpolation*, SIAM J. Numer. Anal. (1980); F. N. Fritsch & J. Butland (1984); Ramer (1972) and Douglas & Peucker (1973); S. Vigna's SplitMix64 (public domain); value noise from the public graphics literature; brush library behaviour learned from Adobe's public help and observation | Own implementation (ADR 0068); the built-in brushes are AniCraft's own parameter sets, no Adobe presets. | diff --git a/CHANGELOG.md b/CHANGELOG.md index 830479e0..70c4c3c1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,20 @@ ## Unreleased +* **Soft masks and text on a path** (ADR 0070, M4). + * **Soft masks**: Layer Properties › **Mask type** on a mask layer: *Shape* (as in Animate), + *Alpha* (the mask's opacity reveals: a gradient to transparent fades the artwork out) or + *Luminance* (the mask's brightness reveals: white shows, black hides). On the stage, on the + GPU stage, in Test Movie and in every export: SVG writes a `mask`, Lottie a track matte, the + HTML canvas composites it. `layer.set_mask` does it headless. + * **Text on a path**: Properties › Path › **Attach to Path**, then click a shape: static text + follows its outline (a copy of it; the shape stays). Move it along with **Offset**, put it on + the other side with **Flip**, and **Release** it back to lines of text. The alignment says + whether the text starts, is centred or ends at the offset. Editing the words, the font or + the size keeps it on its path. Also Modify › Text › Attach Text to Path. + * **SVG import**: soft masks come in as soft mask layers (luminance, or alpha with + `mask-type: alpha`) instead of being drawn unmasked; `textPath` comes in as text on a path; + per-character `x`, `y`, `dx`, `dy` and `rotate` are kept where they are simple. * **CI on macOS and Windows** (ADR 0067, M8). Every pull request that changes code now builds, tests and lints the workspace on macOS (arm64) and Windows (x64) runners as well as Linux, so macOS-only and Windows-only code is checked before it merges. Documentation-only changes skip diff --git a/docs/adr/0010-mask-layers.md b/docs/adr/0010-mask-layers.md index 135fb31c..5e5ed3b6 100644 --- a/docs/adr/0010-mask-layers.md +++ b/docs/adr/0010-mask-layers.md @@ -41,3 +41,9 @@ Imported Animate files use masks often. Artists used to that step lose nothing: locking still works and also hides the edge. * A future GPU renderer must implement the same clip semantics; the CPU tests are the oracle. * Folders can reuse `parent` without a format change. + +## Note (2026-11-12): soft masks + +A mask layer now has a mask type (ADR 0070): Shape (this ADR's coverage, the default), Alpha or +Luminance. Soft masks use the same clips, nesting and stage edge; only how the artwork reveals +changes. diff --git a/docs/adr/0012-text.md b/docs/adr/0012-text.md index e126b149..c43fd737 100644 --- a/docs/adr/0012-text.md +++ b/docs/adr/0012-text.md @@ -55,3 +55,8 @@ Dynamic and input text fields are built on this model (ADR 0066): a block with f whose box is the field's and whose stored outline is its authored text laid out inside the box, so rendering still uses only the outlines. Text a script sets or a viewer types is laid out by the player's host with the fonts on the computer that plays it. + +## Note (2026-11-12): text on a path + +Static text can follow a path (ADR 0070): the block keeps a copy of the path, glyphs are set +along it by arc length and stored as outlines as before, so rendering still needs no fonts. diff --git a/docs/adr/0021-svg-clips-masks-text.md b/docs/adr/0021-svg-clips-masks-text.md index f85535d0..cbef3e1b 100644 --- a/docs/adr/0021-svg-clips-masks-text.md +++ b/docs/adr/0021-svg-clips-masks-text.md @@ -80,3 +80,9 @@ and from self-authored drawings. * Not yet: soft (luminance and alpha) masks, booleans between two curved clips, per-character positions and rotation, text on a path, multi-line blocks from stacked chunks, dashes (another track owns strokes), images and style sheets. + +## Note (2026-11-12): soft masks, text paths, per-character positions + +ADR 0070 imports soft masks onto soft mask layers (luminance by default, `mask-type: alpha`), +`textPath` onto text on a path, and per-character `x`, `y`, `dx`, `dy` and `rotate` where they +are simple (a block per positioned character). diff --git a/docs/adr/0070-soft-masks-and-text-on-a-path.md b/docs/adr/0070-soft-masks-and-text-on-a-path.md new file mode 100644 index 00000000..8b6099aa --- /dev/null +++ b/docs/adr/0070-soft-masks-and-text-on-a-path.md @@ -0,0 +1,100 @@ +# ADR 0070: Soft masks and text on a path + +* Status: accepted (2026-11-12) +* Relates to: ADR 0010 (mask layers), ADR 0012 (text), ADR 0021 (SVG clips, masks and text), + ADR 0019 / 0029 (GPU stage and its masks), ADR 0046 (stroke styles), roadmap M4 + +## Context + +SVG import (ADR 0021) brought clip paths and opaque masks onto mask layers, but drew soft +(luminance or faded) masks unmasked and reported `textPath` and per-character positions. Both are +common in design-tool exports. They are also features in their own right: Animate users fade +artwork out with alpha-gradient masks (in Animate through a masking movie clip with cache-as- +bitmap and scripting), and type on a curve is a basic layout task Animate itself lacks. + +## Decision + +### Soft masks + +1. **A mode on the mask layer, not a new layer kind.** `Layer::mask_mode` is `coverage` (today's + masks: the fills' area, colour, opacity and strokes ignored), `alpha` (the artwork as drawn: + its opacity reveals) or `luminance` (its brightness times its opacity reveals: white shows, + black hides). It is saved only when not `coverage` (`#[serde(default)]`), so older files open + unchanged and files without soft masks are byte-for-byte as before. Every existing mask rule + (parents, folders, the stage showing the mask's edge, picking) stays as it is. +2. **Luminance is SVG's**: `0.2125 R + 0.7154 G + 0.0721 B` on premultiplied sRGB values + (`luminanceToAlpha`), which is what browsers and the SVG mask default compute + (`MaskMode::reveal`). +3. **The display list carries the mode per clip** (`DisplayList::clip_modes`, sparse: a clip past + its end is coverage, so the many lists built by hand stay as they are). Mask artwork items are + the same items as before; for a soft clip the renderers draw them with their paint. +4. **The CPU oracle** composites a soft mask's artwork src-over (fills, strokes, gradients, + bitmaps, colour effects) onto a transparent band buffer and takes each pixel's opacity or + luminance as the clip's coverage, then multiplies by the parent clip as before. Overlapping + soft artwork composites rather than unites (two 50 % shapes give 75 %). Analytic tests pin + opacity, luminance, linear gradient ramps, colour effects, strokes and nesting. +5. **The GPU stage** gets the mode in the `LEVEL_BEGIN` control word; a soft level shades its + artwork with the same paint code and composites it per pixel, and `LEVEL_END` takes the + opacity or luminance. Measured parity on the analytic soft-mask scene: mean error 0.00006 of + a step, worst 1 step of 255 (RTX 5090, Vulkan). +6. **Exports**: SVG writes a soft clip as `` with + `mask-type="alpha"` (luminance is the default), its artwork drawn as it looks, wrapped in a + group carrying its parent clip; a `clipPath` can only be clipped by a clip path, so a coverage + clip inside a soft one is applied as `clip-path` plus `mask` where it is used. Lottie writes a + track matte (`td` layer above, `tt` 1 alpha / 3 luma) with the mask's artwork for every layer + it shows through. The HTML canvas draws the artwork into the mask's offscreen layer and, for + luminance, turns each pixel's luminance into its opacity before `destination-in`. +7. **SVG import** keeps opaque masks as coverage masks (an Animate-style mask stays the simplest + thing), and imports any other `mask` as a soft mask layer: luminance by default, alpha with + `mask-type: alpha`, the content as drawn (gradients, strokes, opacity). The mask's region cuts + unstroked artwork exactly in its own space; artwork that crosses it otherwise is kept whole + and reported. A soft mask is preferred over a curved clip when both apply. +8. **Where artists find it**: Layer Properties shows *Mask type: Shape · Alpha · Luminance* on + mask layers (Shape is the default and means what Animate's masks do); `layer.set_mask` and + `layer.set_properties {mask}` do it headless. + +### Text on a path + +9. **The text block holds a copy of the path** (`TextBlock::on_path`: the path in the block's + own space, the offset along it and whether it is flipped). Attaching copies the shape's first + contour; the shape is left as it is (nothing is deleted; artists delete or hide it if they + want). We chose a copy over a live link to the shape: a link would make text depend on + another element's lifetime, order and keyframes, and every edit to either would need to + relayout the other; a copy keeps "time is a function" and rendering untouched. +10. **Layout by arc length, outlines stored as today.** The text crate lays glyphs out on one + line (line breaks become spaces) and sets each glyph's middle at its distance along the path + (`CurveWalk`, on the Bézier curve itself), turned to the path's direction there, its baseline + on the path, standing on the path's left (above a path drawn left to right). The block's + alignment decides the anchor (left: starts at the offset, centre: centred on it, right: ends + there), as SVG's `text-anchor` with `startOffset`. On a closed path glyphs wrap round; on an + open one glyphs whose middle falls past the ends are left out, as SVG does. *Flip* walks the + path backwards (SVG 2's `side="right"`). The outline is stored with the block, so rendering, + every export and Break Apart never need the font. +11. **The box is the path and the glyphs**: the block's space is moved so both start at the + origin (text boxes always start there), and the element's transform moves the other way, so + nothing moves on the stage when the text or its size changes. +12. **Commands**: `text.attach_path` (the selected text and a selected shape, a shape id, or the + shape at a stage point), `text.path` (offset, flip, release) and `text.release_path`. Text + edits, alignment, Find and Replace keep text on its path. Text on a path is static text + (fields can't be on a path). The shell: Properties › Path › *Attach to Path* waits for a + click on a shape (Esc cancels); then Offset, Flip and Release; the selected text shows its + path. +13. **SVG import**: `textPath` (`href` to a path or basic shape, with that element's transform) + becomes text on a path with its `startOffset` (length or percentage), `side` and + `text-anchor`. Per-character `x`, `y`, `dx`, `dy` and `rotate` are kept where simple: a + character with its own position, shift or angle starts a block of its own (rotated about its + baseline origin), the next continuing after the text before it. Values running into nested + `tspan`s and shifts in centred or right-anchored text are approximate and reported. + +## Consequences + +* Soft edges, vignettes and fades are one gradient on a mask layer away, on the stage, in Test + Movie and in every export; SVG files with soft masks import editable. +* Soft masks cost a band buffer per clip per band where used (as clips already did) and shade + their artwork once per band; coverage masks cost exactly what they did. +* Text on a path is editable text everywhere; the path it follows is its own copy. +* Not yet: soft masks inside soft mask artwork composited as groups (a symbol fading inside a + soft mask fades shape by shape), mask modes in XFL import/export (Animate has no equivalent + field), editing the copied path in place (release, reshape the shape, attach again), several + lines on a path, vertical text and per-character styles on a path; per-character positions + stay positions on import (editing the text lays it out again normally). diff --git a/docs/adr/README.md b/docs/adr/README.md index 74a33e72..8a35fed1 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,4 +23,3 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | -| 0070 | m4/svg-soft-masks-textpath | Soft masks and text on a path | diff --git a/docs/guide/images-and-sound.md b/docs/guide/images-and-sound.md index 36f9d58a..44154a44 100644 --- a/docs/guide/images-and-sound.md +++ b/docs/guide/images-and-sound.md @@ -76,9 +76,12 @@ SVG files from illustration tools come in as artwork you can keep editing, not a * **Clip paths and masks.** A drawing with clipping comes in as a layer folder named after the file. Each clipped group sits on a masked layer under a mask layer that holds the clip's shape, so you can move or reshape the mask afterwards. Clips that cut nothing, like the frame clip - many design tools add, are dropped. Masks come across when they are solid shapes. + many design tools add, are dropped. Solid masks become ordinary (Shape) masks; faded, grey or + gradient masks become **soft masks** (mask type Luminance, or Alpha when the SVG says so). * **Text** comes in as text you can edit, one block per positioned line, with its font, size, - weight, italic, colour, letter spacing and alignment. Fonts that aren't on your computer fall + weight, italic, colour, letter spacing and alignment. Text on a path comes in as text on a + path. Characters the SVG places one by one (moved, shifted or turned) come in as small blocks + of their own where they are. Fonts that aren't on your computer fall back to the default, and the status bar names them. ### What doesn't come across yet @@ -86,8 +89,6 @@ SVG files from illustration tools come in as artwork you can keep editing, not a AniCraft lists these in the status bar after the import, instead of guessing: * images embedded in the SVG, filters, style sheets (inline styles are read) and pattern fills; -* soft, faded or coloured masks (drawn unmasked); -* per-character positions and text on a path; * gradient strokes (drawn in one colour), and repeated or reflected gradients (drawn padded). ### An SVG as a symbol diff --git a/docs/guide/masks-guides-camera-bones.md b/docs/guide/masks-guides-camera-bones.md index b35111b7..17bf511c 100644 --- a/docs/guide/masks-guides-camera-bones.md +++ b/docs/guide/masks-guides-camera-bones.md @@ -36,6 +36,22 @@ group takes it out of the mask. * A mask moves with its whole group when you reorder layers. Masks work inside folders and inside symbols too. +### Soft masks + +A mask doesn't have to have hard edges. Double-click the mask layer's icon (or right-click it and +choose **Properties…**) and pick a **Mask type**: + +* **Shape**: the mask's fills reveal fully, whatever their colour or opacity. This is what + Animate's masks do, and it's the default. +* **Alpha**: the mask's opacity reveals. Fill the mask with a gradient that goes to transparent + and the artwork fades out with it; a shape at 50 % opacity shows the artwork at half strength. + Strokes, bitmaps and colour effects on the mask count too. +* **Luminance**: the mask's brightness reveals: white shows, black hides, greys show partly. + This is how SVG masks work. + +Soft masks show on the stage and in Test Movie, and export to SVG, Lottie (as track mattes) and +HTML. + ## Guide layers A **guide** layer holds artwork that helps you draw, such as a layout sketch, a grid or safe diff --git a/docs/guide/text.md b/docs/guide/text.md index 82e5bdbc..49e86d7e 100644 --- a/docs/guide/text.md +++ b/docs/guide/text.md @@ -104,6 +104,29 @@ Not there yet for fields: formatted (HTML) text, different styles inside one fie change a field's colour or format, listening for each change as the viewer types, Cut, double-clicking to select a word, a blinking caret and scrolling a field with the mouse wheel. +## Text on a path + +Static text can follow the outline of a shape: an arc, a circle, a wave. + +1. Select the text block. +2. In **Properties**, under **Path**, click **Attach to Path**. +3. Click the shape on the stage. (Press **Esc** to give up.) + +The text now runs along a copy of the shape's outline, standing on it. The shape itself stays as +it was: delete or hide it if you only want the text. With a shape and the text both selected, +**Modify › Text › Attach Text to Path** does the same in one go. + +* **Offset** moves the text along the path. The text's alignment says how: left-aligned text + starts at the offset, centred text is centred on it, right-aligned text ends at it. +* **Flip** runs the text the other way along the path, on its other side (under an arc instead + of over it). +* **Release** turns it back into a line of text where it started. + +Changing the words, font, size or spacing keeps the text on its path. On a closed shape the text +wraps round; on an open one, letters that would run past the ends don't show. The selected text +shows the path it follows. Text on a path is always static text, and it is drawn from its own +outlines like all text, so it looks the same on every computer. + ## Turning text into shapes To reshape the letters themselves, select the text and choose **Modify › Break Apart** diff --git a/docs/roadmap.md b/docs/roadmap.md index 8b54161e..ce1f68e8 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -9,7 +9,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | Dimension | Status | |---|---| | 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, 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. **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. | +| Rendering | CPU oracle with analytic AA, non-zero/even-odd, solid + linear/radial gradients, 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, buttons and right-click menu) act on the whole selection; 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, branches allowed, up to 256 bones); bones show as wedges in the layer colour; the Selection tool drags a bone 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. Not yet: shape armatures, spring, joint translation, runtime armatures, XFL import, editing members' properties in place. **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`. Not yet: editing through the preview, perspective depth, XFL camera import. **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, 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. | | 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. | @@ -38,7 +38,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | **M2** | Model at scale | ~~`Arc` structural sharing (O(changed) undo)~~ done early (ADR 0001); ~~scenes~~ ✅ (ADR 0011); ~~layer folders~~ ✅, ~~guide and motion-guide layers~~ ✅; ~~mask layers~~ ✅; ~~Movie Clip and Button behaviours~~ ✅ (playback; button states and scripting come with M6); ~~group alpha / offscreen compositing~~ ✅; ~~shape tween~~ ✅, ~~shape hints~~ ✅ (ADR 0023); ~~motion tween + Motion Editor curves~~ ✅ first slice (ADR 0016); ~~motion paths on the stage with orient to path~~ ✅ first slice (ADR 0030), ~~path point add/delete/convert and moving the whole path~~ ✅ (ADR 0038), ~~anchors pinned to frames~~ ✅ (ADR 0049; 3D and XFL import later); ~~library management~~ ✅ first slice (ADR 0050: folders, rename, duplicate, Swap Symbol, use counts and unused items, sort, search, preview, Allow Smoothing), ~~Library and Properties polish~~ ✅ (ADR 0053: drag onto the stage, Swap Bitmap, Convert to Symbol folders, mixed on every Properties row), ~~9-slice scaling~~ ✅ first slice (ADR 0055); ~~colour effects, complete~~ ✅ (ADR 0056: Properties' Style menu with None, Brightness, Tint, Advanced and Alpha, one exact colour transform in the CPU oracle, the GPU stage, SVG `feColorMatrix`, HTML canvas and Lottie, XFL `Color` import with a corpus package, classic tweens across styles, motion tween tint colour, brightness and Advanced tracks; not yet: camera colour effects beyond tint, a colour picker for the Motion Editor's tint colour); ~~MCP server~~ ✅; perf budgets ✅ (machine-independent ones gate every PR; timing via `bench --check` on a known machine, CI once a benchmark runner exists); ~~layering check~~ ✅ (`src/architecture_tests.rs`, runs with `cargo test`). | | **M3** | GPU stage *(in progress; the default stage renderer since ADR 0032)* | ~~wgpu renderer behind a feature flag~~ ✅ first slice (ADR 0019: the oracle's fills, CPU tile binning with backdrops, compute coverage; gradient tables in a storage buffer); ~~per-pixel parity tests vs the CPU oracle~~ ✅ (max 1/255, mean < 0.0001/255); ~~4K at 60 fps for 1,000 shapes~~ ✅ (8.8–9.0 ms); ~~no-readback textures, masks/groups/blend modes on the GPU~~ ✅ second slice (ADR 0029: window's device, 4K 10k shapes in 10.2 ms as tiles); ~~GPU binning~~ ✅ fourth slice (ADR 0048: heavy frames without masks or groups binned on the GPU, 50k shapes at 4K 122 → 22.5 ms in one texture; outline mode's hairlines as fast as tinted onion skin); ~~bitmaps and filters on the GPU~~ ✅ third slice (ADR 0032: bitmaps byte-identical, filters max 1/255; 4K filtered sample 3.9 ms, 200 bitmaps 4.4 ms); ~~hardware breadth~~ ✅ Vulkan and DX12 (FXC), software adapters refused, oracle-checked self-test; ~~GPU as the default stage renderer~~ ✅ (`gpu-stage` on by default for the app, automatic CPU fallback); next: GPU binning inside masks and groups, shared filtered layers across tiles, an image atlas, GPU exports. | | **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 and text 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. | +| **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); 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: shape armatures, spring, joint translation, runtime armatures, XFL armature import, editing member instances' properties in place); ~~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; not yet: editing while previewing, perspective depth, brightness/advanced colour, attaching layers to the camera, 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. | | **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; next: 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), next: live screen-reader passes on each platform, a light 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). | @@ -118,7 +118,7 @@ Next, in order: ~~every scene~~ ✅, ~~bitmaps~~ ✅ (PNG/JPEG data), ~~text~~ ✅ (one style per line; per-character styles with the text model), motion tweens, and ~~a larger self-authored corpus checked by render tests~~ ✅ (ADR 0035). -2. ~~SVG import~~ ✅ and ~~SVG frame export~~ ✅, ~~text, clip paths and masks (onto mask layers)~~ ✅ (ADR 0021). ~~dashes~~ ✅ (ADR 0046). Next for SVG: soft (luminance) masks, per-character text positions and text on a path. +2. ~~SVG import~~ ✅ and ~~SVG frame export~~ ✅, ~~text, clip paths and masks (onto mask layers)~~ ✅ (ADR 0021). ~~dashes~~ ✅ (ADR 0046). ~~soft masks (luminance and alpha), text on a path (`textPath`) and per-character positions where simple~~ ✅ (ADR 0070). Next for SVG: booleans between two curved clips, multi-line blocks from stacked chunks, images and style sheets. ## Risks From 2c72898510d662dc24d806453c58006120dcb1a2 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Thu, 12 Nov 2026 00:56:48 -0700 Subject: [PATCH 18/18] fix(shell): Option::replace in the soft mask screenshot setup (M4) --- src/app.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/app.rs b/src/app.rs index d0a1e7e0..3f1120e9 100644 --- a/src/app.rs +++ b/src/app.rs @@ -1324,7 +1324,7 @@ impl App { } let mask = self.run("layer.new", json!({"name": "Soft mask"})).and_then(|v| v["layer"].as_u64()); let stops = vec![anicraft_engine::doc::GradientStop { offset: 0.0, color: anicraft_engine::doc::Rgba::WHITE }, anicraft_engine::doc::GradientStop { offset: 1.0, color: anicraft_engine::doc::Rgba::WHITE.with_alpha(0.0) }]; - let swatch = std::mem::replace(&mut self.s.style.fill_paint, Some(anicraft_engine::doc::Paint::Radial { center: anicraft_engine::geom::Vec2::new(320.0, 200.0), radius: 190.0, stops })); + let swatch = self.s.style.fill_paint.replace(anicraft_engine::doc::Paint::Radial { center: anicraft_engine::geom::Vec2::new(320.0, 200.0), radius: 190.0, stops }); self.run("draw.ellipse", json!({"x": 130, "y": 10, "w": 380, "h": 380, "stroke": null})); self.s.style.fill_paint = swatch; self.run("layer.toggle_mask", json!({}));