diff --git a/CHANGELOG.md b/CHANGELOG.md index 23db6760..61124f96 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,19 @@ ## Unreleased +* **Shape armatures, second slice: painted weights and reshaping** (ADR 0090, M7). + * The **Bind** tool's **Paint Weights** (Properties › Bone) brushes a bone's influence onto + the points of its shape: **Add**, **Subtract** or **Smooth**, with a size (`[` and `]`) + and a strength, fading to the brush's rim. The bone's share shows live as a heat map on the + outline and its points, blue (none) to red (all). Each point's weights always add up to + 100 %, painted points stay as painted when bones are added, and a stroke is one undo step. + * **Weights as numbers**: Properties › Bone shows a point's share of the bone as a field to + type in, and every bone the point follows. Click a point or type its number. + * **Reshaping a shape with bones**: at the rest pose, Subselection moves, adds, deletes and + converts its points. The bones keep their binding: new points blend their neighbours' + weights, deleted ones drop theirs, and every pose bends the new outline. + * Headless: `bone.paint_weights`, `bone.set_weight`; the `path.*` point commands reshape a + bound shape at rest. * **Filters, second slice: order, on/off, copy and paste, presets** (ADR 0091, M5). * **Reorder filters** in Properties › Filters: drag a filter by its grip, or focus the grip and press Alt+Up/Alt+Down, or right-click for Move Up/Down. The order changes the picture diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 0e59c30b..84caf250 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -11,6 +11,7 @@ pub mod aids; pub mod armature; pub mod spring; pub mod skin; +pub mod weights; pub mod warp; mod bitmap; mod color_effect; diff --git a/crates/doc/src/weights.rs b/crates/doc/src/weights.rs new file mode 100644 index 00000000..ec47f7f4 --- /dev/null +++ b/crates/doc/src/weights.rs @@ -0,0 +1,304 @@ +//! Painted weights and reshaping a bound shape (ADR 0090), on top of shape armatures (ADR 0071). +//! +//! **Painting.** The Bind tool's brush changes how much one bone moves the points under it: each +//! dab reaches the points within its radius with a smooth falloff (`(1 − (d/r)²)²`, 1 at the +//! centre, 0 at the rim, with no kink at either), times the brush's strength. *Add* raises the +//! bone's share, *Subtract* lowers it, *Smooth* pulls it toward the falloff-weighted mean of the +//! bone's share at the points around it. After every change the point's weights are normalised +//! ([`with_share`]): the bone keeps the share it was painted to and the point's other bones share +//! what is left in the proportions they had, so the weights always sum to 1. A point that +//! followed only the painted bone gives what it loses to the bones automatic binding would give +//! it (its nearest other bones), so subtracting is never a no-op on a multi-bone shape. Painted +//! points become hand-bound (`manual`), so adding a bone later doesn't undo the painting. +//! +//! **Reshaping.** Editing the outline at rest (Subselection: moving, adding, deleting or +//! converting points) gives the skin a new rest outline. [`reshape`] carries the binding over: +//! anchors are matched old to new in path order by exact position (an edit that keeps the number +//! of anchors keeps every binding by index), deleted anchors drop theirs, and each new anchor +//! gets the weights of its matched neighbours along its subpath, blended by its distance along +//! the outline between them. A new subpath with no neighbours is bound automatically. Nothing +//! else changes, so the rest pose shows the edited outline bit for bit. + +use crate::armature::BoneId; +use crate::skin::{Binding, Influence, Skin, anchors, auto_binding}; +use anicraft_geom::{Path, PathCmd, Vec2}; +use std::collections::HashMap; +use std::sync::Arc; + +/// Largest brush radius (px). +pub const MAX_RADIUS: f32 = 2000.0; +/// Most dabs one paint command takes. +pub const MAX_DABS: usize = 4096; + +/// What a dab does to the painted bone's share. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Brush { + Add, + Subtract, + Smooth, +} + +impl Brush { + pub fn key(self) -> &'static str { + match self { + Brush::Add => "add", + Brush::Subtract => "subtract", + Brush::Smooth => "smooth", + } + } + + pub fn parse(s: &str) -> Option { + match s { + "add" => Some(Brush::Add), + "subtract" => Some(Brush::Subtract), + "smooth" => Some(Brush::Smooth), + _ => None, + } + } +} + +/// One brush: what it does, its radius (px) and its strength at the centre (0…1). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Dab { + pub brush: Brush, + pub radius: f32, + pub strength: f32, +} + +/// How much a dab of radius `r` reaches a point `d` away: `(1 − (d/r)²)²` inside, 0 outside. +pub fn falloff(d: f32, r: f32) -> f32 { + if !(r > 0.0 && d.is_finite()) || d >= r { + return 0.0; + } + let x = d / r; + let u = 1.0 - x * x; + u * u +} + +/// `b` with bone `bone`'s share set to `w` (clamped to 0…1) and the point's other bones sharing +/// the rest in their old proportions; when it has no other bones, `fallback` names the bones +/// that take the rest (by weight). Normalised (the strongest four, summing to 1) and hand-bound. +/// With no other bone at all the bone keeps the whole point, or none of it when `w` is 0. +pub fn with_share(b: &Binding, bone: BoneId, w: f32, fallback: impl FnOnce() -> Vec) -> Binding { + let w = if w.is_finite() { w.clamp(0.0, 1.0) } else { b.weight(bone) }; + let mut others: Vec = b.bones.iter().copied().filter(|i| i.0 != bone && i.1.is_finite() && i.1 > 0.0).collect(); + if others.is_empty() && w < 1.0 { + others = fallback().into_iter().filter(|i| i.0 != bone && i.1.is_finite() && i.1 > 0.0).collect(); + } + let rest: f32 = others.iter().map(|i| i.1).sum(); + let mut out = Binding { bones: Vec::with_capacity(others.len() + 1), manual: true }; + if w > 0.0 { + out.bones.push(Influence(bone, w)); + } + if rest > 0.0 && rest.is_finite() { + out.bones.extend(others.iter().map(|i| Influence(i.0, i.1 / rest * (1.0 - w)))); + } + out.normalize(|_| true); + out +} + +/// The bones automatic binding gives a point at `p` (as drawn) leaving out `bone`: who takes a +/// point's weight when the only bone it followed gives some up. +pub fn others_at(segments: &[(BoneId, Vec2, Vec2)], bone: BoneId, p: Vec2) -> Vec { + let without: Vec<(BoneId, Vec2, Vec2)> = segments.iter().copied().filter(|s| s.0 != bone).collect(); + if without.is_empty() { + return Vec::new(); + } + auto_binding(&without, p).bones +} + +/// Paints bone `bone`'s share onto the skin's points: one dab of `with` at each of `dabs`, +/// reaching the points within its radius (both measured where `shown` has the points: on the +/// stage as they show). `segments` are the bones as drawn +/// ([`crate::skin::rest_segments`]). Returns how many points changed. +pub fn paint(skin: &mut Skin, segments: &[(BoneId, Vec2, Vec2)], shown: &[Vec2], bone: BoneId, dabs: &[Vec2], with: Dab) -> usize { + let brush = with.brush; + let radius = if with.radius.is_finite() { with.radius.clamp(0.0, MAX_RADIUS) } else { 0.0 }; + let strength = if with.strength.is_finite() { with.strength.clamp(0.0, 1.0) } else { 0.0 }; + if radius <= 0.0 || strength <= 0.0 { + return 0; + } + let rest = anchors(&skin.rest); + let n = skin.points.len().min(shown.len()).min(rest.len()); + let mut changed = vec![false; n]; + let mut near: Vec<(usize, f32)> = Vec::new(); + for &c in dabs.iter().take(MAX_DABS) { + if !(c.x.is_finite() && c.y.is_finite()) { + continue; + } + near.clear(); + for (i, p) in shown.iter().take(n).enumerate() { + // A cheap box test first: most points are far from a dab. + if (p.x - c.x).abs() >= radius || (p.y - c.y).abs() >= radius { + continue; + } + let f = falloff(p.distance(c), radius); + if f > 0.0 { + near.push((i, f)); + } + } + // Smoothing pulls toward the mean before this dab changed anything. + let mean = if brush == Brush::Smooth { + let (sum, wsum) = near.iter().fold((0.0f32, 0.0f32), |(s, t), &(i, f)| (s + f * skin.points.get(i).map_or(0.0, |b| b.weight(bone)), t + f)); + if wsum > 0.0 { sum / wsum } else { 0.0 } + } else { + 0.0 + }; + for &(i, f) in &near { + let (Some(b), Some(&at)) = (skin.points.get_mut(i), rest.get(i)) else { continue }; + let w = b.weight(bone); + let target = match brush { + Brush::Add => w + strength * f, + Brush::Subtract => w - strength * f, + Brush::Smooth => w + strength * f * (mean - w), + } + .clamp(0.0, 1.0); + if (target - w).abs() <= 1e-6 { + continue; + } + let next = with_share(b, bone, target, || others_at(segments, bone, at)); + if next != *b { + *b = next; + if let Some(c) = changed.get_mut(i) { + *c = true; + } + } + } + } + changed.iter().filter(|c| **c).count() +} + +/// Which subpath each anchor of `path` is on, and each subpath's anchor range and whether it is +/// closed (a `Close`, or ending where it starts). +fn subpaths(path: &Path) -> (Vec, Vec<(usize, usize, bool)>) { + let mut of = Vec::new(); + let mut subs: Vec<(usize, usize, bool)> = Vec::new(); + for c in &path.cmds { + match c { + PathCmd::MoveTo(_) => { + subs.push((of.len(), of.len() + 1, false)); + of.push(subs.len() - 1); + } + PathCmd::Close => { + if let Some(s) = subs.last_mut() { + s.2 = true; + } + } + _ => { + if subs.is_empty() { + subs.push((0, 0, false)); + } + let k = subs.len() - 1; + if let Some(s) = subs.last_mut() { + s.1 = of.len() + 1; + } + of.push(k); + } + } + } + let pts = anchors(path); + for s in &mut subs { + if let (Some(a), Some(b)) = (pts.get(s.0), pts.get(s.1.saturating_sub(1))) { + s.2 |= s.1 > s.0 + 1 && a == b; + } + } + (of, subs) +} + +/// The binding of a new rest outline `path` for `skin`'s bindings (see the module docs): +/// matched anchors keep theirs, new ones blend their neighbours', deleted ones drop theirs. +/// `segments` bind a new subpath that has no neighbours. One binding per anchor of `path`. +pub fn reshape(skin: &Skin, path: &Path, segments: &[(BoneId, Vec2, Vec2)]) -> Vec { + let old = anchors(&skin.rest); + let new = anchors(path); + let none = Binding::default(); + if old.len() == new.len() { + // Points moved or turned smooth: the same anchors, the same bindings. + return (0..new.len()).map(|i| skin.points.get(i).cloned().unwrap_or_default()).collect(); + } + // Match in path order by exact position: each new anchor takes the first old anchor after + // the last match that sits where it does. + let key = |p: Vec2| (p.x.to_bits(), p.y.to_bits()); + let mut at: HashMap<(u32, u32), Vec> = HashMap::with_capacity(old.len()); + for (i, p) in old.iter().enumerate() { + at.entry(key(*p)).or_default().push(i); + } + let mut matched: Vec> = Vec::with_capacity(new.len()); + let mut next_old = 0usize; + for p in &new { + let m = at.get(&key(*p)).and_then(|v| { + let k = v.partition_point(|&i| i < next_old); + v.get(k).copied() + }); + if let Some(i) = m { + next_old = i + 1; + } + matched.push(m); + } + let (of, subs) = subpaths(path); + let binding = |i: usize| skin.points.get(i).unwrap_or(&none); + (0..new.len()) + .map(|j| { + if let Some(i) = matched.get(j).copied().flatten() { + return binding(i).clone(); + } + let p = new.get(j).copied().unwrap_or(Vec2::ZERO); + let Some(&(s, e, closed)) = of.get(j).and_then(|k| subs.get(*k)) else { return auto_binding(segments, p) }; + let len = e.saturating_sub(s).max(1); + // Walks from `j` one way along its subpath (wrapping round a closed one) to the + // nearest matched anchor, adding up the distance between anchors on the way. + let walk = |forward: bool| -> Option<(usize, f32)> { + let (mut k, mut d) = (j, 0.0f32); + for _ in 1..len { + let step = if forward { + if k + 1 < e { k + 1 } else if closed { s } else { return None } + } else if k > s { + k - 1 + } else if closed { + e - 1 + } else { + return None; + }; + d += new.get(k).zip(new.get(step)).map_or(0.0, |(a, b)| a.distance(*b)); + k = step; + if let Some(i) = matched.get(k).copied().flatten() { + return Some((i, d)); + } + } + None + }; + match (walk(false), walk(true)) { + (Some((a, da)), Some((b, db))) => { + let t = if da + db > 0.0 { da / (da + db) } else { 0.5 }; + blend(binding(a), binding(b), t) + } + (Some((a, _)), None) | (None, Some((a, _))) => binding(a).clone(), + (None, None) => auto_binding(segments, p), + } + }) + .collect() +} + +/// `(1 − t)·a + t·b`, normalised; hand-bound when either is. +fn blend(a: &Binding, b: &Binding, t: f32) -> Binding { + let mut bones: Vec = a.bones.iter().map(|i| Influence(i.0, i.1 * (1.0 - t))).collect(); + for i in &b.bones { + match bones.iter_mut().find(|x| x.0 == i.0) { + Some(x) => x.1 += i.1 * t, + None => bones.push(Influence(i.0, i.1 * t)), + } + } + let mut out = Binding { bones, manual: a.manual || b.manual }; + out.normalize(|_| true); + out +} + +/// `skin` with its rest outline replaced by `path` and its binding carried over ([`reshape`]). +pub fn reshaped(skin: &Skin, path: Arc, segments: &[(BoneId, Vec2, Vec2)]) -> Skin { + let points = reshape(skin, &path, segments); + Skin { shape: skin.shape, rest: path, points } +} + +#[cfg(test)] +#[path = "weights_tests.rs"] +mod tests; diff --git a/crates/doc/src/weights_tests.rs b/crates/doc/src/weights_tests.rs new file mode 100644 index 00000000..1ea3ff22 --- /dev/null +++ b/crates/doc/src/weights_tests.rs @@ -0,0 +1,264 @@ +//! Painted weights and reshaping (ADR 0090). + +use super::*; +use crate::armature::{Armature, Bone, Pose}; +use crate::skin::{deform, rebind, rest_segments}; +use crate::ElementId; +use anicraft_geom::Affine; + +const SHAPE: ElementId = ElementId(10); +const B1: BoneId = BoneId(20); +const B2: BoneId = BoneId(21); + +/// A bar 200 px long, 20 px thick along y = 0 with anchors every 25 px on both edges, and two +/// bones along its middle meeting at x = 100 (the shape drawn at the origin). +fn rig() -> Armature { + 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 bones = vec![ + Bone::new(B1, SHAPE, ElementId(30), Vec2::new(0.0, 0.0), Vec2::new(100.0, 0.0), Affine::IDENTITY), + Bone::new(B2, ElementId(30), ElementId(31), Vec2::new(100.0, 0.0), Vec2::new(200.0, 0.0), Affine::IDENTITY), + ]; + let mut arm = Armature { bones, skin: Some(Skin::new(SHAPE, Arc::new(p))), ..Default::default() }; + rebind(&mut arm); + arm +} + +fn skin(arm: &Armature) -> &Skin { + arm.skin.as_ref().expect("a skin") +} + +fn sums_to_one(b: &Binding) -> bool { + b.bones.is_empty() || ((b.bones.iter().map(|i| i.1).sum::() - 1.0).abs() < 1e-5 && b.bones.len() <= crate::skin::MAX_INFLUENCES && b.bones.iter().all(|i| i.1 > 0.0)) +} + +fn paint_on(arm: &mut Armature, bone: BoneId, dabs: &[Vec2], radius: f32, strength: f32, brush: Brush) -> usize { + let segments = rest_segments(arm); + let shown = anchors(&skin(arm).rest); + let k = arm.skin.as_mut().expect("a skin"); + paint(k, &segments, &shown, bone, dabs, Dab { brush, radius, strength }) +} + +#[test] +fn falloff_is_one_at_the_centre_and_zero_at_the_rim() { + assert_eq!(falloff(0.0, 10.0), 1.0); + assert_eq!(falloff(10.0, 10.0), 0.0); + assert_eq!(falloff(20.0, 10.0), 0.0); + assert!(falloff(5.0, 10.0) > 0.5 && falloff(5.0, 10.0) < 0.6); + assert_eq!(falloff(1.0, 0.0), 0.0); + assert_eq!(falloff(f32::NAN, 10.0), 0.0); +} + +#[test] +fn painted_weights_stay_normalised() { + let mut arm = rig(); + for brush in [Brush::Add, Brush::Subtract, Brush::Smooth, Brush::Add] { + for bone in [B1, B2] { + let dabs: Vec = (0..40).map(|i| Vec2::new(5.0 * i as f32, if i % 2 == 0 { -10.0 } else { 10.0 })).collect(); + paint_on(&mut arm, bone, &dabs, 30.0, 0.35, brush); + assert!(skin(&arm).points.iter().all(sums_to_one), "{brush:?} on {bone:?}: {:?}", skin(&arm).points); + } + } +} + +#[test] +fn painting_is_local_to_the_radius() { + let mut arm = rig(); + let before = skin(&arm).points.clone(); + let centre = Vec2::new(25.0, -10.0); + let changed = paint_on(&mut arm, B2, &[centre], 30.0, 1.0, Brush::Add); + let pts = anchors(&skin(&arm).rest); + assert!(changed > 0); + for (i, p) in pts.iter().enumerate() { + if p.distance(centre) >= 30.0 { + assert_eq!(skin(&arm).points[i], before[i], "point {i} at {p:?} is outside the brush"); + } + } + // The point under the centre now follows B2 entirely (strength 100 at the centre), and is + // hand-bound, so a new bone doesn't undo it. + assert_eq!(skin(&arm).points[1].weight(B2), 1.0); + assert!(skin(&arm).points[1].manual); +} + +#[test] +fn add_raises_subtract_lowers_and_smooth_evens_out() { + let mut arm = rig(); + let at = Vec2::new(100.0, -10.0); + let w0 = skin(&arm).points[4].weight(B1); + paint_on(&mut arm, B1, &[at], 20.0, 0.2, Brush::Add); + let w1 = skin(&arm).points[4].weight(B1); + assert!(w1 > w0, "{w0} → {w1}"); + paint_on(&mut arm, B1, &[at, at, at], 20.0, 0.2, Brush::Subtract); + let w2 = skin(&arm).points[4].weight(B1); + assert!(w2 < w1, "{w1} → {w2}"); + // A point that follows only B1 gives what it loses to B2, its nearest other bone. + let mut arm = rig(); + assert_eq!(skin(&arm).points[1].weight(B1), 1.0); + paint_on(&mut arm, B1, &[Vec2::new(25.0, -10.0)], 5.0, 0.5, Brush::Subtract); + let b = &skin(&arm).points[1]; + assert!((b.weight(B1) - 0.5).abs() < 1e-5 && (b.weight(B2) - 0.5).abs() < 1e-5, "{b:?}"); + // Smoothing a sharp step makes the bone's shares closer to each other. + let mut arm = rig(); + let spread = |arm: &Armature| { + let w: Vec = skin(arm).points.iter().map(|b| b.weight(B1)).collect(); + w.iter().cloned().fold(f32::MIN, f32::max) - w.iter().cloned().fold(f32::MAX, f32::min) + }; + let before = spread(&arm); + let dabs: Vec = (0..=16).map(|i| Vec2::new(12.5 * i as f32, 0.0)).collect(); + for _ in 0..10 { + paint_on(&mut arm, B1, &dabs, 400.0, 1.0, Brush::Smooth); + } + assert!(spread(&arm) < before * 0.5, "{before} → {}", spread(&arm)); + assert!(skin(&arm).points.iter().all(sums_to_one)); +} + +#[test] +fn nothing_paints_without_strength_or_radius() { + let mut arm = rig(); + let before = skin(&arm).points.clone(); + assert_eq!(paint_on(&mut arm, B1, &[Vec2::new(25.0, -10.0)], 0.0, 1.0, Brush::Add), 0); + assert_eq!(paint_on(&mut arm, B1, &[Vec2::new(25.0, -10.0)], 30.0, 0.0, Brush::Add), 0); + assert_eq!(paint_on(&mut arm, B1, &[Vec2::new(f32::NAN, 0.0)], 30.0, 1.0, Brush::Add), 0); + assert_eq!(skin(&arm).points, before); +} + +#[test] +fn with_share_keeps_the_other_bones_proportions() { + let b = Binding { bones: vec![Influence(B1, 0.5), Influence(B2, 0.3), Influence(BoneId(9), 0.2)], manual: false }; + let x = with_share(&b, B1, 0.8, Vec::new); + assert!((x.weight(B1) - 0.8).abs() < 1e-6); + assert!((x.weight(B2) - 0.12).abs() < 1e-6 && (x.weight(BoneId(9)) - 0.08).abs() < 1e-6); + assert!(x.manual && sums_to_one(&x)); + // Without other bones, the fallback takes the rest; without any, the bone keeps it all. + let only = Binding { bones: vec![Influence(B1, 1.0)], manual: false }; + assert!((with_share(&only, B1, 0.25, || vec![Influence(B2, 1.0)]).weight(B2) - 0.75).abs() < 1e-6); + assert_eq!(with_share(&only, B1, 0.25, Vec::new).weight(B1), 1.0); + assert!(with_share(&only, B1, 0.0, Vec::new).bones.is_empty()); +} + +/// The shape's rest outline with its edges' anchors where `edit` puts them. +fn edited(arm: &Armature, edit: impl FnOnce(&mut Path)) -> Path { + let mut p = (*skin(arm).rest).clone(); + edit(&mut p); + p +} + +#[test] +fn moving_points_keeps_every_binding() { + let arm = rig(); + let p = edited(&arm, |p| { + if let Some(PathCmd::LineTo(q)) = p.cmds.get_mut(3) { + q.y -= 15.0; + } + }); + let out = reshape(skin(&arm), &p, &rest_segments(&arm)); + assert_eq!(out, skin(&arm).points); +} + +#[test] +fn an_inserted_point_blends_its_neighbours() { + let mut arm = rig(); + // Make the neighbours different by hand: anchor 3 (x = 75) follows B1, anchor 4 (x = 100) B2. + if let Some(k) = arm.skin.as_mut() { + k.points[3] = Binding { bones: vec![Influence(B1, 1.0)], manual: true }; + k.points[4] = Binding { bones: vec![Influence(B2, 1.0)], manual: true }; + } + // A point a quarter of the way from x = 75 to x = 100. + let p = edited(&arm, |p| { + p.cmds.insert(4, PathCmd::LineTo(Vec2::new(81.25, -10.0))); + }); + let out = reshape(skin(&arm), &p, &rest_segments(&arm)); + assert_eq!(out.len(), anchors(&p).len()); + let b = &out[4]; + assert!((b.weight(B1) - 0.75).abs() < 1e-5 && (b.weight(B2) - 0.25).abs() < 1e-5, "{b:?}"); + assert!(b.manual && sums_to_one(b)); + // Every other anchor keeps its binding. + assert_eq!(&out[..4], &skin(&arm).points[..4]); + assert_eq!(&out[5..], &skin(&arm).points[4..]); +} + +#[test] +fn a_deleted_point_drops_its_binding() { + let mut arm = rig(); + if let Some(k) = arm.skin.as_mut() { + k.points[5] = Binding { bones: vec![Influence(B1, 0.6), Influence(B2, 0.4)], manual: true }; + } + let p = edited(&arm, |p| { + p.cmds.remove(4); + }); + let out = reshape(skin(&arm), &p, &rest_segments(&arm)); + let mut want = skin(&arm).points.clone(); + want.remove(4); + assert_eq!(out, want); +} + +#[test] +fn a_new_subpath_is_bound_automatically_and_closing_points_copy_the_start() { + let arm = rig(); + let p = edited(&arm, |p| { + p.move_to(Vec2::new(150.0, -5.0)); + p.line_to(Vec2::new(160.0, -5.0)); + p.line_to(Vec2::new(160.0, 5.0)); + p.close(); + }); + let segments = rest_segments(&arm); + let out = reshape(skin(&arm), &p, &segments); + let n = skin(&arm).points.len(); + assert_eq!(out.len(), n + 3); + assert_eq!(out[n], auto_binding(&segments, Vec2::new(150.0, -5.0))); + // An explicit closing point at the start of a closed subpath takes the start's weights. + let p = edited(&arm, |p| { + let close = p.cmds.len() - 1; + p.cmds.insert(close, PathCmd::LineTo(Vec2::new(0.0, -10.0))); + }); + let out = reshape(skin(&arm), &p, &segments); + assert_eq!(out.last(), skin(&arm).points.first()); +} + +#[test] +fn the_rest_pose_is_the_reshaped_outline_bit_for_bit() { + let arm = rig(); + let p = Arc::new(edited(&arm, |p| { + p.cmds.insert(4, PathCmd::LineTo(Vec2::new(87.5, -10.0))); + if let Some(PathCmd::LineTo(q)) = p.cmds.get_mut(10) { + q.y -= 3.0; + } + })); + let mut arm2 = arm.clone(); + arm2.skin = Some(reshaped(skin(&arm), p.clone(), &rest_segments(&arm))); + let rest = deform(&arm2, &Pose::default()).expect("an outline"); + assert!(Arc::ptr_eq(&rest, &p)); + // Bent, the new point moves with the bones like its neighbours: between them. + let mut pose = Pose::default(); + pose.set(B2, std::f32::consts::FRAC_PI_2); + let bent = anchors(&deform(&arm2, &pose).expect("an outline")); + assert_eq!(bent.len(), anchors(&p).len()); + assert!(bent.iter().all(|q| q.x.is_finite() && q.y.is_finite())); +} + +#[test] +fn painting_a_large_shape_is_fast() { + // 20,000 points in a row, 32 dabs of radius 40. + let mut p = Path::new(); + p.move_to(Vec2::new(0.0, 0.0)); + for i in 1..20_000 { + p.line_to(Vec2::new(i as f32 * 0.1, (i % 7) as f32)); + } + let bones = vec![Bone::new(B1, SHAPE, ElementId(30), Vec2::new(0.0, 0.0), Vec2::new(1000.0, 0.0), Affine::IDENTITY), Bone::new(B2, ElementId(30), ElementId(31), Vec2::new(1000.0, 0.0), Vec2::new(2000.0, 0.0), Affine::IDENTITY)]; + let mut arm = Armature { bones, skin: Some(Skin::new(SHAPE, Arc::new(p))), ..Default::default() }; + rebind(&mut arm); + let dabs: Vec = (0..32).map(|i| Vec2::new(900.0 + 10.0 * i as f32, 3.0)).collect(); + let t = std::time::Instant::now(); + let n = paint_on(&mut arm, B2, &dabs, 40.0, 0.3, Brush::Add); + let ms = t.elapsed().as_secs_f64() * 1000.0; + eprintln!("painting 32 dabs over 20,000 points changed {n} in {ms:.2} ms"); + assert!(n > 0); + assert!(ms < 2000.0); +} diff --git a/crates/engine/src/cmds_bone.rs b/crates/engine/src/cmds_bone.rs index edfb7110..d9e7a587 100644 --- a/crates/engine/src/cmds_bone.rs +++ b/crates/engine/src/cmds_bone.rs @@ -13,7 +13,8 @@ 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, MAX_SLIDE, Spring}; 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_doc::weights::{self, Brush, Dab, MAX_DABS, MAX_RADIUS}; +use anicraft_doc::{Element, ElementId, ElementKind, Keyframe, Layer, LayerId, LayerKind, Rgba, Shape, Tween, evaluate_layer_elements}; use anicraft_geom::{Affine, Vec2}; use serde_json::{Value, json}; use std::sync::Arc; @@ -36,6 +37,8 @@ pub fn specs() -> Vec { 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.paint_weights", "Paint Weights", "{bone, at: [[x, y]…] (dab centres, stage px, at most 4096), radius? (px, 1–2000, default 20), strength? (0–100 at the centre, default 25), mode?: \"add\" (default) | \"subtract\" | \"smooth\", frame?} → {bone, changed, bound}. The Bind tool's brush: raises, lowers or evens out how much the bone moves the shape's points within the radius of each dab (a smooth falloff to the rim); each point's weights stay normalised (its other bones share what is left) and the points become hand-bound. A drag sends many in one gesture: one undo step", true, paint_weights), + c("bone.set_weight", "Set Point Weight", "{bone, points: [point index…] (see bone.info with points), weight (0–100: the bone's share of each point)} sets exactly how much the bone moves the points; their other bones share the rest in proportion (a point that followed only this bone gives the rest to its nearest other bones). Hand-bound", true, set_weight), 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.set_translation", "Joint Translation", "{bone, axis: \"x\" | \"y\" (along the axes of what the bone starts on, as it is turned), enabled?: bool (false: the joint doesn't slide that way), constrain?: bool (false: slides freely), min?, max? (px, ±10,000, from where it was drawn)} lets the joint slide, in every pose; posing (bone.solve, the Selection tool) slides it only where turning can't reach", true, set_translation), @@ -759,3 +762,147 @@ fn bind(s: &mut Session, p: &Value) -> Result { rebake(l); Ok(json!({"bone": id.0, "changed": changed, "bound": bound})) } + +/// The point indices in param `key`, each below `n`. +fn point_list(p: &Value, key: &str, n: usize) -> Result> { + let bad = || EngineError::Param(format!("param '{key}' must be a list of point indices below {n} (see bone.info with points)")); + match p.get(key) { + 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(), + _ => Err(bad()), + } +} + +/// How many points bone `id` moves. +fn bound_count(arm: &Armature, id: BoneId) -> usize { + arm.skin.as_ref().map_or(0, |k| k.points.iter().filter(|b| b.weight(id) > 0.0).count()) +} + +/// A bone inside a shape, its unlocked armature layer and the armature. +fn shape_bone(s: &Session, id: BoneId) -> Result<(LayerId, Arc)> { + let (lid, arm) = find_bone(s, id)?; + unlocked(s, lid)?; + if arm.skin.is_none() { + return Err(EngineError::State("that bone joins symbol instances: only bones inside a shape have weights on its points".into())); + } + Ok((lid, arm)) +} + +fn paint_weights(s: &mut Session, p: &Value) -> Result { + let id = bone_param(p)?; + let bad = || EngineError::Param(format!("param 'at' must be a list of at most {MAX_DABS} [x, y] points (stage px, within ±1,000,000)")); + let list = p.get("at").and_then(Value::as_array).filter(|a| a.len() <= MAX_DABS).ok_or_else(bad)?; + let dabs: Vec = list + .iter() + .map(|v| { + let a = v.as_array().filter(|a| a.len() == 2).ok_or_else(bad)?; + let n = |i: usize| a.get(i).and_then(Value::as_f64).filter(|v| v.is_finite() && v.abs() <= f64::from(MAX_COORD)).map(|v| v as f32).ok_or_else(bad); + Ok(Vec2::new(n(0)?, n(1)?)) + }) + .collect::>()?; + let radius = opt_f32(p, "radius")?.unwrap_or(20.0); + if !(1.0..=MAX_RADIUS).contains(&radius) { + return Err(EngineError::Param(format!("param 'radius' must be between 1 and {MAX_RADIUS} px"))); + } + let strength = opt_f32(p, "strength")?.unwrap_or(25.0); + if !(0.0..=100.0).contains(&strength) { + return Err(EngineError::Param("param 'strength' must be between 0 and 100".into())); + } + let brush = match opt_str(p, "mode")? { + None => Brush::Add, + Some(m) => Brush::parse(m).ok_or_else(|| EngineError::Param("param 'mode' must be \"add\", \"subtract\" or \"smooth\"".into()))?, + }; + let frame = opt_u32(p, "frame")?.unwrap_or(s.frame).min(MAX_FRAME); + let (lid, arm) = shape_bone(s, id)?; + // The points where the stage shows them at the frame: the brush paints what the artist sees. + let shown = s.timeline().layer(lid).and_then(|l| evaluate_layer_elements(l, frame)).map(|(_, els)| skin::points_shown(&arm, &els)).unwrap_or_default(); + if shown.is_empty() { + return Err(EngineError::State(format!("the bone's shape isn't on the stage at frame {}", frame + 1))); + } + let mut arm = (*arm).clone(); + let segments = skin::rest_segments(&arm); + let changed = match arm.skin.as_mut() { + Some(k) => weights::paint(k, &segments, &shown, id, &dabs, Dab { brush, radius, strength: strength / 100.0 }), + None => 0, + }; + let bound = bound_count(&arm, id); + if changed > 0 { + let l = s.layer_mut(Some(lid))?; + l.armature = Some(Arc::new(arm)); + rebake(l); + } + Ok(json!({"bone": id.0, "changed": changed, "bound": bound, "mode": brush.key()})) +} + +fn set_weight(s: &mut Session, p: &Value) -> Result { + let id = bone_param(p)?; + let w = f32_req(p, "weight")?; + if !(0.0..=100.0).contains(&w) { + return Err(EngineError::Param("param 'weight' must be between 0 and 100".into())); + } + let (lid, arm) = shape_bone(s, id)?; + let n = arm.skin.as_ref().map_or(0, |k| k.points.len()); + let points = point_list(p, "points", n)?; + 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 rest = skin::anchors(&k.rest); + let mut changed = 0usize; + for &i in &points { + let (Some(b), Some(&at)) = (k.points.get_mut(i), rest.get(i)) else { continue }; + let next = weights::with_share(b, id, w / 100.0, || weights::others_at(&segments, id, at)); + if *b != next { + *b = next; + changed += 1; + } + } + let shares: Vec = points.iter().map(|&i| json!(k.points.get(i).map(|b| b.bones.iter().map(|x| json!([x.0.0, x.1 * 100.0])).collect::>()).unwrap_or_default())).collect(); + let bound = bound_count(&arm, id); + let l = s.layer_mut(Some(lid))?; + l.armature = Some(Arc::new(arm)); + rebake(l); + Ok(json!({"bone": id.0, "changed": changed, "bound": bound, "weights": shares})) +} + +/// Whether element `id` is the shape of the shape armature on the active layer (so point edits +/// reshape the skin instead of a keyframe's artwork). +pub(crate) fn is_skin_shape(s: &Session, id: ElementId) -> bool { + s.timeline().layer(s.layer).is_some_and(|l| l.kind == LayerKind::Armature && l.armature.as_ref().and_then(|a| a.skin_shape()) == Some(id)) +} + +/// Reshaping a bound shape (ADR 0090): `edit` changes the shape's outline as drawn (its rest +/// outline, with the shape's transform at the playhead), which needs the armature at rest there. +/// The binding is carried over to the new outline (moved points keep their weights, new points +/// blend their neighbours', deleted ones drop theirs) and every pose bends the new outline. One +/// undo step, like any command. +pub(crate) fn reshape(s: &mut Session, id: ElementId, edit: impl FnOnce(&mut Shape, Affine) -> Result) -> Result { + let (lid, frame) = (s.layer, s.frame); + unlocked(s, lid)?; + let tl = s.timeline(); + let l = tl.layer(lid).ok_or_else(|| EngineError::State("the armature layer went away".into()))?; + let arm = l.armature.clone().ok_or_else(|| EngineError::State("that is not an armature layer".into()))?; + let k = arm.skin.as_ref().filter(|k| k.shape == id).ok_or_else(|| EngineError::State("that shape isn't the armature's".into()))?; + let pose = armature::pose_at(l, frame).ok_or_else(|| EngineError::State(format!("the armature isn't on frame {}", frame + 1)))?; + if skin::matrices(&arm, &pose).values().any(|m| *m != Affine::IDENTITY) { + return Err(EngineError::State("reshape a shape with bones at its rest pose: go to a frame where every bone is as drawn (angle 0, no slide), or pose them back".into())); + } + let (_, els) = evaluate_layer_elements(l, frame).ok_or_else(|| EngineError::State(format!("the armature isn't on frame {}", frame + 1)))?; + let el = els.iter().find(|e| e.id == id).ok_or_else(|| EngineError::State(format!("element {} is not on the active layer at this frame", id.0)))?; + let ElementKind::Shape(shape) = &el.kind else { return Err(EngineError::State("that isn't a shape".into())) }; + let mut shape = shape.clone(); + shape.path = k.rest.clone(); + let out = edit(&mut shape, el.transform)?; + if *shape.path == *k.rest { + return Ok(out); + } + let n = skin::anchors(&shape.path).len(); + if n > MAX_SKIN_POINTS { + return Err(EngineError::State(format!("a shape with bones has at most {MAX_SKIN_POINTS} points"))); + } + let skin = weights::reshaped(k, shape.path.clone(), &skin::rest_segments(&arm)); + let mut arm = (*arm).clone(); + arm.skin = Some(skin); + let l = s.layer_mut(Some(lid))?; + l.armature = Some(Arc::new(arm)); + rebake(l); + Ok(out) +} diff --git a/crates/engine/src/cmds_path.rs b/crates/engine/src/cmds_path.rs index a5bcdf34..eeaf2714 100644 --- a/crates/engine/src/cmds_path.rs +++ b/crates/engine/src/cmds_path.rs @@ -116,17 +116,22 @@ fn draw_freehand(s: &mut Session, p: &Value) -> Result { // ----- point editing ---------------------------------------------------------------------- -/// The shape element `id` in the editable keyframe (copy-on-write), with its transform. -fn shape_mut<'a>(s: &'a mut Session, p: &Value) -> Result<(&'a mut Shape, Affine)> { +/// Runs `edit` on shape element `id` (param `id`) in the editable keyframe (copy-on-write), with +/// its transform. The shape of a shape armature is reshaped at rest instead, keeping its binding +/// (ADR 0090). +fn edit_shape(s: &mut Session, p: &Value, edit: impl FnOnce(&mut Shape, Affine) -> Result) -> Result { let id = ElementId(opt_u64(p, "id")?.ok_or_else(|| EngineError::Param("param 'id' is required".into()))?); if !s.visible_elements().iter().any(|e| e.id == id) { return Err(EngineError::State(format!("element {} is not on the active layer at this frame", id.0))); } + if crate::cmds_bone::is_skin_shape(s, id) { + return crate::cmds_bone::reshape(s, id, edit); + } let kf = s.editable_keyframe()?; let el: &mut Element = kf.elements_mut_where(|e| e == id).into_iter().next().ok_or_else(|| EngineError::State(format!("no element {}", id.0)))?; let m = el.transform; match &mut el.kind { - ElementKind::Shape(sh) => Ok((sh, m)), + ElementKind::Shape(sh) => edit(sh, m), ElementKind::Symbol { .. } => Err(EngineError::State("symbol instances have no points to edit (double-click to edit the symbol)".into())), ElementKind::Text(_) => Err(EngineError::State("text has no points to edit; break it apart (Ctrl+B) to edit its outlines".into())), ElementKind::Camera => Err(EngineError::State("the camera has no points to edit".into())), @@ -151,39 +156,40 @@ fn move_points(s: &mut Session, p: &Value) -> Result { wanted.push((usize::try_from(cmd).unwrap_or(usize::MAX), slot as u8)); } let smooth = opt_bool(p, "smooth")?.unwrap_or(true); - let (sh, m) = shape_mut(s, p)?; - let inv = m.inverse().ok_or_else(|| EngineError::State("the shape is scaled to zero".into()))?; - let local = inv.apply_vector(d); - if !local.is_finite() { - return Err(EngineError::Param("the move is too large".into())); - } - let path = Arc::make_mut(&mut sh.path); - // Anchors bring their handles and their twin at a closed start; each point moves once. - let mut set = BTreeSet::new(); - for (cmd, slot) in wanted { - if path.point(cmd, slot).is_none() { - return Err(EngineError::Param(format!("no point ({cmd}, {slot}) on this path"))); + edit_shape(s, p, |sh, m| { + let inv = m.inverse().ok_or_else(|| EngineError::State("the shape is scaled to zero".into()))?; + let local = inv.apply_vector(d); + if !local.is_finite() { + return Err(EngineError::Param("the move is too large".into())); } - if slot == ANCHOR { - set.extend(path.anchor_group(cmd)); - } else { - set.insert((cmd, slot)); + let path = Arc::make_mut(&mut sh.path); + // Anchors bring their handles and their twin at a closed start; each point moves once. + let mut set = BTreeSet::new(); + for (cmd, slot) in wanted { + if path.point(cmd, slot).is_none() { + return Err(EngineError::Param(format!("no point ({cmd}, {slot}) on this path"))); + } + if slot == ANCHOR { + set.extend(path.anchor_group(cmd)); + } else { + set.insert((cmd, slot)); + } } - } - // The other handle of a smooth anchor whose handle moves alone (ADR 0045), as it was. - let partners: Vec<(usize, u8, Vec2, Vec2)> = if smooth { set.iter().filter_map(|&(cmd, slot)| partner(path, &set, cmd, slot)).collect() } else { Vec::new() }; - for &(cmd, slot) in &set { - if let Some(q) = path.point(cmd, slot) { - path.set_point(cmd, slot, q + local); + // The other handle of a smooth anchor whose handle moves alone (ADR 0045), as it was. + let partners: Vec<(usize, u8, Vec2, Vec2)> = if smooth { set.iter().filter_map(|&(cmd, slot)| partner(path, &set, cmd, slot)).collect() } else { Vec::new() }; + for &(cmd, slot) in &set { + if let Some(q) = path.point(cmd, slot) { + path.set_point(cmd, slot, q + local); + } } - } - for (cmd, slot, anchor, handle) in partners { - if let Some(k) = path.point(cmd, slot) { - path.set_point(cmd, slot, anicraft_geom::raw::turned_opposite(anchor, handle + local, k)); + for (cmd, slot, anchor, handle) in partners { + if let Some(k) = path.point(cmd, slot) { + path.set_point(cmd, slot, anicraft_geom::raw::turned_opposite(anchor, handle + local, k)); + } } - } - check_path(path)?; - Ok(json!({"moved": set.len()})) + check_path(path)?; + Ok(json!({"moved": set.len()})) + }) } /// For handle `(cmd, slot)` moving alone: the other handle of its anchor when the anchor is smooth @@ -209,46 +215,49 @@ fn partner(path: &Path, moving: &BTreeSet<(usize, u8)>, cmd: usize, slot: u8) -> fn add_point(s: &mut Session, p: &Value) -> Result { let at = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?); let slop = opt_f32(p, "slop")?.unwrap_or(4.0).clamp(0.0, 1000.0); - let (sh, m) = shape_mut(s, p)?; - let path = Arc::make_mut(&mut sh.path); - path.close_explicitly(); - let (cmd, t, dist) = path.nearest_segment(at, &m).ok_or_else(|| EngineError::State("the path has no segments".into()))?; - if dist > slop { - return Err(EngineError::State("no segment there".into())); - } - if path.cmds.len() >= MAX_CMDS || !path.split_segment(cmd, t) { - return Err(EngineError::State("cannot add a point there".into())); - } - Ok(json!({"cmd": cmd})) + edit_shape(s, p, |sh, m| { + let path = Arc::make_mut(&mut sh.path); + path.close_explicitly(); + let (cmd, t, dist) = path.nearest_segment(at, &m).ok_or_else(|| EngineError::State("the path has no segments".into()))?; + if dist > slop { + return Err(EngineError::State("no segment there".into())); + } + if path.cmds.len() >= MAX_CMDS || !path.split_segment(cmd, t) { + return Err(EngineError::State("cannot add a point there".into())); + } + Ok(json!({"cmd": cmd})) + }) } fn delete_points(s: &mut Session, p: &Value) -> Result { let cmds = index_list(p, "cmds")?; - let (sh, _) = shape_mut(s, p)?; - let path = Arc::make_mut(&mut sh.path); - // Highest first, so earlier indices stay valid; twins collapse onto one anchor. - let order: BTreeSet = cmds.iter().map(|&c| path.canonical_anchor(c)).collect(); - let mut removed = 0; - for cmd in order.into_iter().rev() { - if path.remove_anchor(cmd) { - removed += 1; + edit_shape(s, p, |sh, _| { + let path = Arc::make_mut(&mut sh.path); + // Highest first, so earlier indices stay valid; twins collapse onto one anchor. + let order: BTreeSet = cmds.iter().map(|&c| path.canonical_anchor(c)).collect(); + let mut removed = 0; + for cmd in order.into_iter().rev() { + if path.remove_anchor(cmd) { + removed += 1; + } } - } - if removed == 0 { - return Err(EngineError::State("a path keeps at least two points (delete the shape instead)".into())); - } - Ok(json!({"deleted": removed})) + if removed == 0 { + return Err(EngineError::State("a path keeps at least two points (delete the shape instead)".into())); + } + Ok(json!({"deleted": removed})) + }) } fn convert_point(s: &mut Session, p: &Value) -> Result { let cmd = opt_u64(p, "cmd")?.ok_or_else(|| EngineError::Param("param 'cmd' is required".into()))?; let cmd = usize::try_from(cmd).unwrap_or(usize::MAX); let smooth = opt_bool(p, "smooth")?.ok_or_else(|| EngineError::Param("param 'smooth' is required".into()))?; - let (sh, _) = shape_mut(s, p)?; - let path = Arc::make_mut(&mut sh.path); - if path.point(cmd, ANCHOR).is_none() { - return Err(EngineError::Param(format!("no anchor {cmd} on this path"))); - } - let changed = if smooth { path.make_smooth(cmd) } else { path.make_corner(cmd) }; - Ok(json!({"changed": changed})) + edit_shape(s, p, |sh, _| { + let path = Arc::make_mut(&mut sh.path); + if path.point(cmd, ANCHOR).is_none() { + return Err(EngineError::Param(format!("no anchor {cmd} on this path"))); + } + let changed = if smooth { path.make_smooth(cmd) } else { path.make_corner(cmd) }; + Ok(json!({"changed": changed})) + }) } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ef0592cb..1db14f0e 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1144,6 +1144,8 @@ mod tests_bone_spring; #[cfg(test)] mod tests_shape_bone; #[cfg(test)] +mod tests_shape_weights; +#[cfg(test)] mod tests_warp; #[cfg(test)] mod tests_filter; diff --git a/crates/engine/src/tests_shape_weights.rs b/crates/engine/src/tests_shape_weights.rs new file mode 100644 index 00000000..048e79c4 --- /dev/null +++ b/crates/engine/src/tests_shape_weights.rs @@ -0,0 +1,224 @@ +//! Painted weights and reshaping a bound shape end to end (ADR 0090): the brush, numeric +//! weights, undo per stroke, Subselection edits at rest keeping the binding, refusals and +//! plug-in policy. + +use super::*; +use anicraft_doc::{BoneId, ColorEffect, Document, ElementKind, Paint, Rgba, Shape, Stage}; +use anicraft_geom::{Affine, Path}; +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; + +/// The tail outline of `tests_shape_bone`: 200 × 20 px, anchors every 25 px on both edges. +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)); + } + for i in (0..=8).rev() { + p.line_to(Vec2::new(25.0 * i as f32, 10.0)); + } + p.close(); + p +} + +/// A tail at (100, 150) with two bones along its middle: (100, 150) → (200, 150) → (300, 150). +fn rigged() -> (Session, u64, u64) { + let mut d = Document { stage: Stage { width: 400, height: 300, ..Stage::default() }, ..Document::default() }; + let shape = Shape { merge: true, ..Shape::filled(outline(), 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; + let mut s = Session::new(d); + let b1 = run(&mut s, "bone.add_in_shape", json!({"shape": TAIL, "head": [100, 150], "tail": [200, 150]}))["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 skin(s: &Session) -> anicraft_doc::skin::Skin { + s.timeline().layers.iter().find_map(|l| l.armature.as_ref().and_then(|a| a.skin.clone())).unwrap() +} + +fn weight(s: &Session, point: usize, bone: u64) -> f32 { + skin(s).points[point].weight(BoneId(bone)) +} + +fn shown_path(s: &Session, frame: u32) -> Arc { + s.timeline() + .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(sh.path.clone()), + _ => None, + }) + }) + .unwrap() +} + +fn normalised(s: &Session) -> bool { + skin(s).points.iter().all(|b| b.bones.is_empty() || ((b.bones.iter().map(|i| i.1).sum::() - 1.0).abs() < 1e-5 && b.bones.len() <= 4)) +} + +#[test] +fn a_brush_stroke_paints_locally_and_undoes_in_one_step() { + let (mut s, _, b2) = rigged(); + let before = skin(&s).points.clone(); + assert_eq!(weight(&s, 1, b2), 0.0); + // A stroke of three moves over the point at (125, 140), as the Bind tool sends it. + s.begin_gesture("Paint Weights"); + for x in [120.0, 125.0, 130.0] { + run(&mut s, "bone.paint_weights", json!({"bone": b2, "at": [[x, 140.0]], "radius": 12, "strength": 50})); + } + s.end_gesture(); + assert!(weight(&s, 1, b2) > 0.5, "{}", weight(&s, 1, b2)); + assert!(normalised(&s)); + // Only points within the radius of a dab changed. + let rest = anicraft_doc::skin::anchors(&skin(&s).rest); + for (i, p) in rest.iter().enumerate() { + let at = *p + Vec2::new(100.0, 150.0); + if [120.0, 125.0, 130.0].iter().all(|x| at.distance(Vec2::new(*x, 140.0)) >= 12.0) { + assert_eq!(skin(&s).points[i], before[i], "point {i}"); + } + } + s.undo().unwrap(); + assert_eq!(skin(&s).points, before); +} + +#[test] +fn painted_weights_bend_the_shape_and_stay_normalised() { + let (mut s, b1, b2) = rigged(); + for (mode, bone) in [("add", b2), ("subtract", b1), ("smooth", b2), ("subtract", b2), ("add", b1)] { + let at: Vec<[f32; 2]> = (0..30).map(|i| [100.0 + 7.0 * i as f32, if i % 2 == 0 { 140.0 } else { 160.0 }]).collect(); + run(&mut s, "bone.paint_weights", json!({"bone": bone, "at": at, "radius": 30, "strength": 40, "mode": mode})); + assert!(normalised(&s), "{mode}"); + } + // Point 1 painted onto B2 entirely now turns with B2. + run(&mut s, "bone.set_weight", json!({"bone": b2, "points": [1], "weight": 100})); + run(&mut s, "bone.pose", json!({"bone": b2, "angle": 90, "frame": 10})); + let bent = anicraft_doc::skin::anchors(&shown_path(&s, 10)); + let rest = anicraft_doc::skin::anchors(&skin(&s).rest); + assert!(bent[1].distance(rest[1]) > 10.0, "{:?} vs {:?}", bent[1], rest[1]); +} + +#[test] +fn weights_are_editable_numerically_per_point() { + let (mut s, b1, b2) = rigged(); + let v = run(&mut s, "bone.set_weight", json!({"bone": b1, "points": [1, 2], "weight": 30})); + assert_eq!(v["changed"], 2); + assert!((weight(&s, 1, b1) - 0.3).abs() < 1e-6 && (weight(&s, 1, b2) - 0.7).abs() < 1e-6); + assert!(skin(&s).points[1].manual); + // bone.info reports them. + let info = run(&mut s, "bone.info", json!({"points": true})); + let bones = info["armatures"][0]["points"][1]["bones"].as_array().unwrap().clone(); + assert_eq!(bones.len(), 2); + // Refusals: out-of-range weights and points, and bones of instance armatures. + assert!(s.execute("bone.set_weight", &json!({"bone": b1, "points": [1], "weight": 101})).is_err()); + assert!(s.execute("bone.set_weight", &json!({"bone": b1, "points": [999], "weight": 10})).is_err()); + assert!(s.execute("bone.set_weight", &json!({"bone": b1, "weight": 10})).is_err()); + assert!(s.execute("bone.paint_weights", &json!({"bone": b1, "at": [[1, 2]], "radius": 0})).is_err()); + assert!(s.execute("bone.paint_weights", &json!({"bone": b1, "at": [[1, 2]], "mode": "blur"})).is_err()); + assert!(s.execute("bone.paint_weights", &json!({"bone": b1, "at": [[1, "x"]]})).is_err()); + assert!(s.execute("bone.paint_weights", &json!({"bone": 4242, "at": [[1, 2]]})).is_err()); +} + +#[test] +fn reshaping_at_rest_keeps_the_binding_and_is_exact() { + let (mut s, b1, b2) = rigged(); + let k0 = skin(&s); + // Hand-bind the neighbours apart: anchor 3 (x = 75) to B1, anchor 4 (x = 100) to B2. + run(&mut s, "bone.bind", json!({"bone": b1, "points": [3], "mode": "only"})); + run(&mut s, "bone.bind", json!({"bone": b2, "points": [4], "mode": "only"})); + // Subselection's double-click on the top edge a quarter of the way from x = 75 to x = 100. + let lid = s.layer; + let v = run(&mut s, "path.add_point", json!({"id": TAIL, "x": 181.25, "y": 140.0})); + assert_eq!(s.layer, lid); + let cmd = v["cmd"].as_u64().unwrap() as usize; + let k = skin(&s); + let n = anicraft_doc::skin::anchors(&k.rest).len(); + assert_eq!(k.points.len(), n); + assert!(n > k0.points.len()); + // The new anchor blends its neighbours by where it sits between them. + let i = cmd; + assert!((k.points[i].weight(BoneId(b1)) - 0.75).abs() < 1e-3 && (k.points[i].weight(BoneId(b2)) - 0.25).abs() < 1e-3, "{:?}", k.points[i]); + // The rest pose shows exactly the edited outline: what the same edit gives an unbound shape. + let mut want = outline(); + want.close_explicitly(); + let (c, t, _) = want.nearest_segment(Vec2::new(181.25, 140.0), &Affine::translate(100.0, 150.0)).unwrap(); + assert!(want.split_segment(c, t)); + assert_eq!(*k.rest, want); + assert_eq!(*shown_path(&s, 0), want); + assert!(Arc::ptr_eq(&shown_path(&s, 0), &k.rest)); + // Moving a point keeps every binding; deleting one drops its own. + run(&mut s, "path.move_points", json!({"id": TAIL, "points": [[cmd, 0]], "dx": 0, "dy": -6})); + assert_eq!(skin(&s).points, k.points); + run(&mut s, "path.delete_points", json!({"id": TAIL, "cmds": [cmd]})); + let mut left = k.points.clone(); + left.remove(i); + assert_eq!(skin(&s).points, left); + // Undo walks back through each edit. + s.undo().unwrap(); + s.undo().unwrap(); + s.undo().unwrap(); + assert_eq!(*skin(&s).rest, outline()); +} + +#[test] +fn a_posed_frame_bends_the_reshaped_outline_and_refuses_reshaping() { + let (mut s, _, b2) = rigged(); + run(&mut s, "bone.pose", json!({"bone": b2, "angle": 45, "frame": 10})); + run(&mut s, "path.add_point", json!({"id": TAIL, "x": 281.25, "y": 140.0})); + let n = anicraft_doc::skin::anchors(&skin(&s).rest).len(); + // Every keyframe holds the new outline, bent by its pose. + assert_eq!(anicraft_doc::skin::anchors(&shown_path(&s, 10)).len(), n); + assert_ne!(*shown_path(&s, 10), *skin(&s).rest); + s.set_frame(10); + let e = s.execute("path.move_points", &json!({"id": TAIL, "points": [[2, 0]], "dx": 0, "dy": -6})).unwrap_err(); + assert!(e.to_string().contains("rest pose"), "{e}"); + // A locked armature layer refuses too. + s.set_frame(0); + let lid = s.layer; + Arc::make_mut(s.doc.timeline_mut(0).layers.iter_mut().find(|l| l.id == lid).unwrap()).locked = true; + assert!(s.execute("path.move_points", &json!({"id": TAIL, "points": [[2, 0]], "dx": 0, "dy": -6})).is_err()); +} + +#[test] +fn files_keep_painted_and_reshaped_bindings() { + let (mut s, _, b2) = rigged(); + run(&mut s, "bone.paint_weights", json!({"bone": b2, "at": [[150, 140]], "radius": 30, "strength": 60})); + run(&mut s, "path.add_point", json!({"id": TAIL, "x": 181.25, "y": 140.0})); + let text = crate::format::to_json(&s.doc).unwrap(); + let back = crate::format::from_json(&text).unwrap(); + let k = back.timeline(0).layers.iter().find_map(|l| l.armature.as_ref().and_then(|a| a.skin.clone())).unwrap(); + assert_eq!(k, skin(&s)); +} + +#[test] +fn plug_ins_may_paint_weights() { + for id in ["bone.paint_weights", "bone.set_weight"] { + assert!(crate::cmds_plugin::plugin_may_call(id).is_ok(), "{id}"); + } +} + +#[test] +fn subselection_picks_the_bound_shape_to_show_its_points() { + let (mut s, _, _) = rigged(); + run(&mut s, "element.pick", json!({"x": 150, "y": 150})); + assert!(s.selection.contains(s.layer, ElementId(TAIL))); + // It is a drawing object, so the Subselection tool lists its own points. + assert!(s.visible_elements().iter().any(|e| e.id.0 == TAIL && matches!(&e.kind, ElementKind::Shape(sh) if !sh.merge))); +} diff --git a/docs/adr/0090-painted-weights-and-reshaping-bound-shapes.md b/docs/adr/0090-painted-weights-and-reshaping-bound-shapes.md new file mode 100644 index 00000000..7c634d9b --- /dev/null +++ b/docs/adr/0090-painted-weights-and-reshaping-bound-shapes.md @@ -0,0 +1,119 @@ +# ADR 0090: Painted weights and reshaping a bound shape + +* Status: accepted (2026-11-13) +* Relates to: roadmap M7 (Bone/IK tool), ADR 0071 (shape armatures, which this extends), + ADR 0084 (springs, translation, and the proposal for mixed armatures), ADR 0043 (armatures), + ADR 0042/0045 (Subselection), ADR 0004 (destructive actions), ADR 0005 (UI guidelines) + +## Context + +ADR 0071 binds a shape's points to its bones automatically and lets the Bind tool override +whole points: a point follows one bone, shares one more equally, or drops one. Artists rigging +a tail or a sleeve need finer control. They want *how much* a bone moves the points across a +region, with soft transitions between bones, and an exact number when it matters. They also +redraw the outline after rigging. ADR 0071 refused that: the binding was indexed by point, so +any edit that added or removed a point would have scrambled it. + +Animate's Bind tool and Subselection-at-rest behaviour was learned from Adobe's public help +pages and from watching the program. The weight brush follows what artists know from 2D and 3D +skinning tools in general (add / subtract / smooth with a soft falloff), not any one product's +code. Nothing was copied. + +## Decision + +1. **The binding stays where ADR 0071 put it.** `Skin.points` is still one `Binding` per anchor: + up to four `[bone, weight]` pairs summing to 1, and the `manual` flag. Painting only changes + the numbers, so **the file format is unchanged**: older files open as they are, and an older + AniCraft opens newer files. The new code is pure functions in `anicraft_doc::weights`, with + no state and nothing in `evaluate`. The posed outline is still ADR 0071's linear blend + skinning, from the weights as they are. +2. **The brush** (`weights::paint`). A dab at a stage point reaches every point within its + radius, measured where the stage shows the points at the frame (posed), so the brush + paints what the artist sees. The falloff is `(1 − (d/r)²)²`: 1 at the centre, 0 at the rim, + with no kink at either end, times the strength (0–100 %). *Add* raises the bone's share by + that much and *Subtract* lowers it, additively, so 100 % at the centre sets the share + outright. *Smooth* moves it that fraction toward the falloff-weighted mean share of the + points under the dab, taken before the dab changed anything. The result doesn't depend on + the order of points in the path. +3. **Normalisation per point** (`weights::with_share`). After every change the bone keeps the + share it was painted to, and the point's other bones share the rest in the proportions they + had. If the point followed only the painted bone, the rest goes to the bones automatic + binding would give it without that bone, its nearest others. So Subtract always does + something on a shape with two or more bones, and the point stays put the way a nearby bone + moves it, which is what an artist expects. Then ADR 0071's rule applies: the strongest four + are kept and they sum to 1. With no other bone at all, the bone keeps the whole point, or + none of it at 0 (the point stays where it was drawn, as `bone.bind remove` leaves it). + Painted points become hand-bound (`manual`), so adding a bone later doesn't undo the + painting. +4. **Strokes and undo.** The shell spaces dabs a quarter of the radius apart along the + pointer's path, so a stroke paints the same at any speed. It sends them as + `bone.paint_weights` calls inside one gesture, which makes a stroke one undo step. A click + is one dab. Headless callers give a list of dab centres (at most 4096 per call), so + painting is scriptable and deterministic. Measured (release, this machine): 32 dabs of + radius 40 over a 20,000-point shape (the limit), 1.15 ms. +5. **Numbers for the keyboard.** `bone.set_weight {bone, points, weight}` sets a bone's share of + points exactly, normalising the same way. Properties › Bone shows a *focused point* (clicked + with the Bind tool, or typed by number), the bone's share of it as a percentage field, and + every bone the point follows with its share. Painting and binding move the focus to the point + touched, and the stage rings it. This meets the accessibility rule (ADR 0064): everything the + brush does can be done with typed numbers. +6. **The heat overlay.** With Paint Weights on, the picked bone's share shows on the outline and + its points as a heat ramp: blue (none), cyan, green, yellow, red (all). It is drawn over the + artwork, so it is the same in every palette (`theme::HEAT`, the only place its colours live), + and it updates live as the stroke goes. The brush shows as a ring of its radius on the + stage. Off, the Bind tool shows ADR 0071's squares and triangles. +7. **Reshaping at rest** (`weights::reshape`, `cmds_bone::reshape`). The Subselection commands + on a drawing object (`path.move_points`, `path.add_point`, `path.delete_points`, + `path.convert_point`) recognise the shape of a shape armature on the active layer. Then they + edit the skin's rest outline instead of a keyframe, and carry the binding over: + * the same number of anchors (moving points and handles, smooth/corner): every binding by + index; + * otherwise, anchors are matched old to new in path order by exact position (each new + anchor takes the first old anchor after the last match that sits where it does). Deleted + anchors drop their bindings. Each new anchor blends the bindings of the nearest matched + anchors on either side along its subpath (wrapping round a closed one), weighted by + distance along the outline between them, then normalised. It is hand-bound if either + neighbour is. A new subpath with no neighbours is bound automatically. + + This is a general diff, not a contract with each command, so later point commands get it + for free. Then every keyframe is re-bent from the new rest outline. **At rest the shown + outline is the edited path bit for bit**: `deform` returns the very `Arc` of the rest path. + Reshaping needs every bone at rest at the playhead (no angle, no slide). At a posed frame the + command refuses with a message saying so: inverting a blend of bone matrices to map an edit + back to the rest pose isn't well defined where weights mix, and Animate also edits bound + shapes at rest. Each edit is one undo step, and none destroys anything, so none asks + (ADR 0004). +8. **Commands** (in the `bone.*` namespace plug-ins may already call; the `path.*` ones were + already callable): `bone.paint_weights {bone, at, radius?, strength?, mode?, frame?}` and + `bone.set_weight {bone, points, weight}`. `bone.info {points: true}` already lists each point's + bones and weights. Both are covered by the `panic_hunt_every_command` fuzz. + +## Instances and shapes in one armature: proposed again, not built + +It still doesn't fit cleanly, for the reasons ADR 0084 gives. `Armature.skin` is one shape, and +`place`, `roots`, `sanitize`, `bone.remove`, `bone.add` and the Bind and Bone tools all branch +on "skinned or not". Mixing the two needs `Armature.skins: Vec` keyed by shape, nodes +that may be an instance or a joint node inside a shape, rules for what removing a bone frees +(instances to a layer, a shape's points rebound), and a Bone tool drag from a shape's bone end +onto an instance. That changes the file format (a list where there was one skin) and every +branch above. A slice whose subject is weights shouldn't carry it, so it stays its own ADR and +PR. Nothing in this ADR makes it harder: weights and reshaping are per skin. + +## Consequences + +* No renderer, exporter, the GPU stage or the file format changed. Weights and the rest outline + are data ADR 0071 already stored, and every output sees them through `evaluate`. +* Hand-bound points are more common now (anything painted). **Rebind All** (`bone.bind auto`) + still returns every point to automatic binding in one undoable step. +* Matching by exact position can mismatch when an edit both moves and adds points at once and + a new point lands exactly on an old one further along. No single command does that today, + and the result would still be normalised, finite weights. + +## Not yet + +* Instances and shapes in one armature (above); more than one shape per armature. +* Reshaping at a posed frame (the Pen's Alt-click to add a point works, as it is + `path.add_point`); drawing new subpaths into a bound shape; a weight brush that paints across several bones at once (normalise-locked bones, mirror). +* A filled heat mesh across the shape's interior (the overlay is on its outline and points), + dragging points onto a bone with the Bind tool, a global falloff setting for automatic + binding. diff --git a/docs/guide/masks-guides-camera-bones.md b/docs/guide/masks-guides-camera-bones.md index 5eddb445..08106d8b 100644 --- a/docs/guide/masks-guides-camera-bones.md +++ b/docs/guide/masks-guides-camera-bones.md @@ -269,10 +269,38 @@ to pick it, and the points it moves fill in. Then: back to the automatic binding. Adding or removing bones rebinds the points you haven't bound by hand. +**Painting weights.** For a softer or more exact bend than clicks give, paint how much a bone +moves each point. Pick a bone with the **Bind** tool, then turn on **Paint Weights** in +**Properties › Bone**. The outline and its points turn into a heat map of that bone's share: +blue where it moves nothing, through green and yellow, to red where it moves the point alone. +Drag over the shape to paint: + +* **Add** gives the bone more of the points under the brush, **Subtract** gives it less, and + **Smooth** evens out its share, softening a hard edge between two bones; +* **Size** is the brush's radius (**[** and **]** change it), and **Strength** is how much one + pass changes the weights at its centre. The effect fades to nothing at the rim. + +A point's shares always add up to 100 %. What one bone gains the point's other bones lose, in +proportion. A point taken from its only bone goes to the next nearest bone. Each stroke is one +step to undo. Painted points count as bound by hand, so adding a bone later leaves them alone. + +**Typing a weight.** Properties › Bone also shows one point's weights as numbers. Click a +point with the Bind tool, or type its number in **Point**. Then type the bone's share in +**Weight**, and **Follows** lists every bone the point follows. Keyboard users can do all of +this without the stage. + +**Reshaping a shape that has bones.** At the rest pose (every bone as drawn), use the +**Subselection** tool to edit the shape's outline. You can move points and handles, +double-click the outline to add a point, delete points, or make them smooth or corners. The +bones keep their binding. Moved points keep their weights, and a new point takes the weights +of the points on either side, blended by where it sits between them. A deleted point's +weights go with it. Every pose bends the new outline. At a posed frame AniCraft asks you to go +to the rest pose first. + Bones inside a shape take joint translation and springs too. -Not there yet: symbols and shapes in one armature, reshaping a shape after it has bones, -armatures that scripts pose while the movie plays, and armatures from Animate files. +Not there yet: symbols and shapes in one armature, reshaping at a posed frame, armatures +that scripts pose while the movie plays, and armatures from Animate files. ## Asset Warp diff --git a/docs/guide/reference/commands.md b/docs/guide/reference/commands.md index b41c2a64..697a811b 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 347 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 349 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. @@ -357,6 +357,10 @@ These commands have no menu item: the panels, the stage and the timeline use the 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` +- **Paint Weights** `bone.paint_weights` · changes the document + Parameters: `{bone, at: [[x, y]…] (dab centres, stage px, at most 4096), radius? (px, 1–2000, default 20), strength? (0–100 at the centre, default 25), mode?: "add" (default) | "subtract" | "smooth", frame?} → {bone, changed, bound}. The Bind tool's brush: raises, lowers or evens out how much the bone moves the shape's points within the radius of each dab (a smooth falloff to the rim); each point's weights stay normalised (its other bones share what is left) and the points become hand-bound. A drag sends many in one gesture: one undo step` +- **Set Point Weight** `bone.set_weight` · changes the document + Parameters: `{bone, points: [point index…] (see bone.info with points), weight (0–100: the bone's share of each point)} sets exactly how much the bone moves the points; their other bones share the rest in proportion (a point that followed only this bone gives the rest to its nearest other bones). Hand-bound` - **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 diff --git a/docs/roadmap.md b/docs/roadmap.md index 56ad142b..6bee8502 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 (with reflect/repeat, focal points, elliptical radials and linear RGB, ADR 0074), round-join strokes. **Mask clipping**: the display list carries nested clips; a clip is the anti-aliased union of its mask fills (strokes and opacity ignored), intersected with any enclosing clip, computed once per render band; an empty mask hides everything under it. **Soft masks** (ADR 0070): a mask layer's mask type is Shape (coverage), Alpha (its artwork's opacity as drawn: gradients, faded shapes, strokes, bitmaps) or Luminance (brightness × opacity, SVG's coefficients), in the CPU oracle (analytic tests), the GPU stage (parity: mean 0.00006, worst 1 step of 255), SVG export (`` with `mask-type`), Lottie (alpha and luma track mattes) and the HTML canvas; Layer Properties › Mask type. **Group alpha**: a symbol instance below full opacity is a group in the display list; each render band composites the group's run of ops into its own buffer (nested groups stack) and blends it once at the group's alpha, so overlaps don't show through; SVG export writes ``. **Blend modes** (Animate's 14, on movie clip and button instances): an instance with one is an isolated group that blends at its close with the W3C separable formulas on premultiplied colour (Alpha and Erase keep or clear the backdrop); SVG gets CSS `mix-blend-mode`, Lottie the layer `bm`. **Bitmaps**: `Paint::Bitmap` fills (once or tiled) with bilinear sampling in premultiplied space, colour effects per sample; PNG/JPEG import to stage (a rectangle of the image's size); stored in the document as PNG (base64 in `.anicraft`), decoded once on first use; SVG export embeds each image once as a pattern. **Filters**: a filtered group is drawn on its own (by the same renderer, recursively, so nested filters work) into a buffer over its artwork grown by the filters' reach, filtered (box-blur passes; shadow and glow from the blurred, offset opacity; **bevel and gradient bevel** from the difference of the blurred opacity offset towards and away from the light, **gradient glow** from the glow's intensity, both through a colour ramp whose rest stop is pinned transparent, inner/outer/full and knockout, ADR 0025; colour matrix), and composited back as one image in its group, so alpha and blend apply; clips from inside the symbol apply before filtering and the instance's own clip after. Filters apply in list order and may be switched off (ADR 0091): `evaluate` leaves switched-off ones out, so every renderer and export draws them as absent. **GPU stage, first slice** (M3, ADR 0019; `--features gpu-stage`, off by default): Preferences › Stage › Renderer *GPU (preview)* draws the stage with wgpu compute from the oracle's own prepared fills (tile binning with per-row backdrops on the CPU, exact area coverage and src-over per pixel on the GPU): solid and gradient fills and strokes, non-zero and even-odd; masks, group opacity, blend modes, filters and bitmaps fall back to the CPU per tile, and the status bar says so. Parity with the oracle: max 1/255, mean < 0.0001/255 on the sample, stress and analytic scenes (tests skip without an adapter). 4K with 1,000 shapes: 8.8–9.0 ms vs the CPU's 17.4–17.8 ms. **Second slice** (ADR 0029): on the window's wgpu device the stage tiles are drawn straight into textures egui shows (no readback; a headless device with readback when the window is on OpenGL); **masks** (nested, united artwork), **group opacity** and **all 14 blend modes** on the GPU, same parity (max 1/255, mean ≤ 0.0011/255); 4K: 1,000 shapes in 2.1–2.4 ms, 10k shapes in 10.2 ms as stage tiles, masked scenes 7× the CPU. **Third slice** (ADR 0032): **bitmap fills** (textures uploaded once per image and cached under a 256 MB budget, sampled with the oracle's own bilinear filter, colour effect and repeat rules: byte-identical) and **all seven filters** (each filtered symbol drawn into a layer of its own and filtered by compute passes that run the oracle's resolved steps: max 1/255, mean ≤ 0.007/255) on the GPU; the shaders now build with Direct3D's FXC, so DX12 windows get the GPU stage too (parity suite green on Vulkan and DX12); software adapters are refused (the CPU is faster), the start-up self-test compares with the oracle. **The GPU is the default stage renderer**: the shell's `gpu-stage` feature is on by default, Preferences › Stage › Renderer defaults to *Graphics card (GPU)*, and the CPU draws whenever there is no usable card, a tile is past the GPU's limits (more than 16 images, filters nested deeper than 4) or anything fails. 4K: the filtered sample in 3.9 ms (CPU 31.5), 200 bitmap fills in 4.4 ms (CPU 37.2). **Fourth slice** (ADR 0048): **tile binning on the GPU** for heavy frames without masks or groups (count, prefix sum, scatter and tile-list passes, no atomics, no readback; the CPU binning stays the reference and does the rest; one tile format for both: an integer backdrop per tile and steps on the tiles' left edges): on Vulkan, 10k shapes at 4K in one texture 21.7 → 4.7 ms, 50k shapes 122 → 22.5 ms, the 50k-shape 4K stage 75 → 37 ms (Direct3D 12 keeps CPU binning: slower there in stage tiles); and **hairlines** for outline mode in both renderers (coverage by distance, one edge per segment): onion outlines on the 2,000-item stress scene as fast as tinted (GPU stage 73 → 10 ms, CPU stage 34–39 → 17 ms at 1080p). Not yet: sharing a filtered layer across a frame's tiles, more than 16 images per tile, GPU binning inside masks and groups, flattening and stroking on the GPU, buffer reuse and fewer dispatches across tiles, hairlines for sub-pixel strokes, GPU exports, a GPU runner in CI; the CPU stays the oracle and the export path. | -| Timeline | **Frame selection**: click, Shift-click or drag across frames and layers; F5/Shift+F5, F6/F7 and Shift+F6 (keys, icon buttons and right-click menu) act on the whole selection; with no frame selection F5 extends every layer with frames at or after the playhead, and F5/F6/F7 move the playhead on as in Animate (F6/F7 on a keyframe key the next frame; `all_layers`/`advance` headless); drag selected keyframes left or right to move them, and up or down onto other layers (the source keeps empty frames, as in Animate) (with a drop outline; one undo step; keys they land on are replaced, and spans fill the frames left behind); removing or clearing selected frames that hold artwork asks first. **Cut/Copy/Paste Frames** (Ctrl+Alt+X/C/V, and plain Ctrl+X/C/V after clicking the timeline): own clipboard, copies cut exactly at the selection edges (mid-tween state kept), paste inserts like Animate, several layers paste onto the layers below (missing ones are created), fresh element ids, symbols travel with them. **Span length by dragging its end** (resize cursor, live outline with the length in frames and seconds; later frames move with it; a motion tween's keys stretch in proportion, ADR 0083). Side dock tab strips never run under the panel menu (names shrink with an ellipsis, then the strip scrolls). 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 **ease presets and custom eases** (ADR 0081: Classic Ease with a strength and Quad, Cubic, Quart, Quint, Sine, Back, Circ, Bounce and Elastic In/Out/In Out; custom eases of up to 64 Bézier points in the Custom Ease window, x kept monotonic, overshoot allowed, keyboard operable, **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, colour, filters, and instance filters tween; XFL custom and per-property eases import exactly; `ease.*` headless) + curve preview, rotation, skew, alpha, tint), each property its own curve of property keyframes with a per-segment ease (any preset, saved ease or custom ease of several segments, ADR 0081; 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. **Retiming** (ADR 0083): keys drag sideways in time (snapped to frames, never past a neighbour), Shift-click picks keys across properties, an All lane picks a frame's keys, Left/Right move picked keys with the curve focused; dragging a span's end stretches a motion tween's keys in proportion (Shift keeps them); a click picks a whole motion span and dragging (or a selection of whole tween spans) moves it at its length, Alt-drag copies; **Split Motion** / **Join Motion** (split then join is exact). Headless: `motion.move_keys`, `timeline.resize_span`, `timeline.move_spans`, `motion.split`, `motion.join`. Not yet: joining two independent motion paths, retiming from a span's left edge. **Motion paths** (ADR 0030): a motion tween may carry a cubic path its object travels by arc length, timed by the X/Y curves (a straight path reproduces them exactly, overshoot included); shown on the stage in the motion colour with a dot per frame when the object or span is selected; Selection drags the path to bend it and its ends to move them, Subselection drags anchors and handles; moving the object reshapes the path; Orient to path and Straighten in Properties; splits cut the path. **Path points** (ADR 0038): with Subselection, double-click the path to add a point (shape and motion unchanged), Shift-click to select several anchors, Delete to remove them (the path refits through the rest; the ends stay), right-click for smooth/corner and Straighten; the Pen's Alt-click adds a point to a motion path or a selected shape; Ctrl-drag (⌘-drag) the path or its object, or edit Properties › Path start, to move the whole path with its timing exact. **Anchors pinned to frames** (ADR 0049): moving the object at a frame pins a path point there (a new anchor where it was put; after the last position key the path carries on), and the object passes every pinned point exactly on its frame, the X/Y eases timing it between pins; pinned points are diamonds with their frame number on the stage, blue keys in the Motion Editor's X/Y (dragging one moves its point) and holed diamonds on the timeline; Subselection's right-click pins to the playhead's frame or unpins, Properties › Frame has Pin Here / Unpin, F6 pins where the object is; point edits keep pins on their anchors; files without pins evaluate exactly as before. Headless: `timeline.create_motion_tween`, `motion.*` (`motion.set_path/clear_path/orient/add_point/delete_points/convert_point/move_path/pin_point/unpin_point`; `motion.info` reports `pins`). Not yet: retiming a pin by dragging its key in time, two pins on one anchor, XFL motion path keyframes, a marquee over path anchors, nudging or transforming a whole path, retiming keys, rescaling keys with the span, XFL motion-tween import. **Bones and IK, first slice** (ADR 0043): the Bone tool (M) drags from one symbol instance to another to join them with a bone on an armature layer (chains join end to start: a bone from a chained instance always starts at its joint; branches allowed, up to 256 bones); bones show as wedges in the layer colour; the Selection tool drags a bone (the grabbed point follows) or a posed instance to pose by cyclic coordinate descent (joint limits, pinned bones, one undo step per drag) and the root to move it all; poses are joint angles keyed per frame and tweened with the span's easing; Properties › Bone (angle, constrain min/max, pin, remove); `bone.*` headless; every export sees the pose. **Shape armatures** (ADR 0071): the Bone tool draws bones inside a shape (it moves to an armature layer as an object, outside merge drawing); its points are bound to the nearest bones automatically (weights by distance to each bone, up to four, summing to 1) and bend by linear blend skinning (handles with their anchors, strokes keep their width, the rest pose exact); the **Bind tool** (Shift+M) shows the points (squares, triangles where shared) and binds them by click, Shift/Ctrl-click or box; the same IK, poses and tweens; `bone.add_in_shape`, `bone.bind`, `bone.info {points}`. **Springs, joint translation and members in place** (ADR 0084): joints slide along X/Y of what they start on, freely or within pixel limits, as part of each pose (IK slides only where turning can't reach); per-bone Spring and Damping swing bones after the motion and settle, evaluated as a pure replay of up to six seconds of motion (seeking equals playing bit for bit; 0.33 ms a frame for 16 sprung bones), shown on the stage, in Test Movie and every export, switched off per armature for posing; a picked bone's instance takes colour effect, blending and filters in place on every pose; `bone.set_translation`, `bone.set_spring`, `bone.enable_springs`. Not yet: runtime armatures, XFL import, mixing instances and shapes in one armature (proposed in ADR 0084), reshaping a bound shape, painted weights, gravity and wind. **Asset Warp** (ADR 0079): the **Asset Warp tool** (Shift+Q) pins a shape or a bitmap (the first pin covers it with a warp mesh: a grid over its bounds, 2–48 cells along the longer side, Properties › Asset Warp); dragging a pin bends the artwork around the other pins by rigid moving least squares (Schaefer et al. 2006) at the mesh's vertices, live, one undo step per drag; Delete removes a pin; pins are added to every keyframe holding the artwork and their poses tween with classic tweens and easing; shapes bend through the mesh (straight edges exactly, curves split), bitmaps are drawn through its triangles by the CPU oracle (bilinear) and the GPU stage takes the same prepared fill (parity exact); the rest pose is the drawing bit for bit; every raster export, SVG (a bent bitmap baked as an image), Lottie and HTML (a bent bitmap reported) go through `evaluate`; `warp.add`, `warp.pin_add`, `warp.pin_move`, `warp.pin_remove`, `warp.remove`, `warp.info`. Not yet: as-rigid-as-possible solving on a mesh that follows the outline, symbols and text, binding warp pins to bones, a GPU textured-triangle path, bent bitmaps in HTML and Lottie, XFL import of warped assets. eases saved in the document and offered everywhere; copy/paste of an ease; classic tweens eased per property group: position, **Camera layer** (ADR 0027): the camera button in the timeline header or the Camera tool (C) adds a Camera layer on top; its frame shows on the stage in orange; drag to pan, turn with the round handle, wheel to zoom (one undo step per drag); Properties › Camera (position, zoom, rotation, tint, reset); keyframes and classic or motion tweens animate it; layer Depth gives pan parallax; View › Preview Through Camera shows the movie's picture (artwork tools pause there); hiding the camera layer turns it off; every export, Test Movie and the GPU stage see it. Headless: `camera.add/remove/set/info`, `layer.set_depth`. **Camera, second slice** (ADR 0082): layer depth in a pinhole perspective (deeper layers move and zoom less, draw behind nearer ones; depth 0 bit-exact), depth keyed over time (linear between keys), **Window › Layer Depth** (layers by depth, drag nearer or farther, key, attach), **Attach Layer to Camera** (timeline toggle; HUDs stay on screen), camera colour effects (Brightness, Tint, Advanced), and the Selection tool picking and moving artwork while previewing through the camera; headless `layer.set_depth {key, frame}`, `layer.remove_depth_key`, `layer.set_attached`, `layer.depths`, `element.pick {view: camera}`. Not yet: other tools while previewing, depth inside symbols, depth keys moving with inserted frames, XFL camera and layer-depth import (no public format description). **Motion guides**: guided layers (children of a guide through `Layer.parent`) have their classic tweens follow the guide's first path by arc length, from the point nearest each start keyframe to the point nearest its end (`geom::walk::PathWalk`), optionally orienting to the path; guide artwork is listed for picking and editing, drawn on the stage as a line, and never rendered or exported. | +| Timeline | **Frame selection**: click, Shift-click or drag across frames and layers; F5/Shift+F5, F6/F7 and Shift+F6 (keys, icon buttons and right-click menu) act on the whole selection; with no frame selection F5 extends every layer with frames at or after the playhead, and F5/F6/F7 move the playhead on as in Animate (F6/F7 on a keyframe key the next frame; `all_layers`/`advance` headless); drag selected keyframes left or right to move them, and up or down onto other layers (the source keeps empty frames, as in Animate) (with a drop outline; one undo step; keys they land on are replaced, and spans fill the frames left behind); removing or clearing selected frames that hold artwork asks first. **Cut/Copy/Paste Frames** (Ctrl+Alt+X/C/V, and plain Ctrl+X/C/V after clicking the timeline): own clipboard, copies cut exactly at the selection edges (mid-tween state kept), paste inserts like Animate, several layers paste onto the layers below (missing ones are created), fresh element ids, symbols travel with them. **Span length by dragging its end** (resize cursor, live outline with the length in frames and seconds; later frames move with it; a motion tween's keys stretch in proportion, ADR 0083). Side dock tab strips never run under the panel menu (names shrink with an ellipsis, then the strip scrolls). 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 **ease presets and custom eases** (ADR 0081: Classic Ease with a strength and Quad, Cubic, Quart, Quint, Sine, Back, Circ, Bounce and Elastic In/Out/In Out; custom eases of up to 64 Bézier points in the Custom Ease window, x kept monotonic, overshoot allowed, keyboard operable, **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, colour, filters, and instance filters tween; XFL custom and per-property eases import exactly; `ease.*` headless) + curve preview, rotation, skew, alpha, tint), each property its own curve of property keyframes with a per-segment ease (any preset, saved ease or custom ease of several segments, ADR 0081; 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. **Retiming** (ADR 0083): keys drag sideways in time (snapped to frames, never past a neighbour), Shift-click picks keys across properties, an All lane picks a frame's keys, Left/Right move picked keys with the curve focused; dragging a span's end stretches a motion tween's keys in proportion (Shift keeps them); a click picks a whole motion span and dragging (or a selection of whole tween spans) moves it at its length, Alt-drag copies; **Split Motion** / **Join Motion** (split then join is exact). Headless: `motion.move_keys`, `timeline.resize_span`, `timeline.move_spans`, `motion.split`, `motion.join`. Not yet: joining two independent motion paths, retiming from a span's left edge. **Motion paths** (ADR 0030): a motion tween may carry a cubic path its object travels by arc length, timed by the X/Y curves (a straight path reproduces them exactly, overshoot included); shown on the stage in the motion colour with a dot per frame when the object or span is selected; Selection drags the path to bend it and its ends to move them, Subselection drags anchors and handles; moving the object reshapes the path; Orient to path and Straighten in Properties; splits cut the path. **Path points** (ADR 0038): with Subselection, double-click the path to add a point (shape and motion unchanged), Shift-click to select several anchors, Delete to remove them (the path refits through the rest; the ends stay), right-click for smooth/corner and Straighten; the Pen's Alt-click adds a point to a motion path or a selected shape; Ctrl-drag (⌘-drag) the path or its object, or edit Properties › Path start, to move the whole path with its timing exact. **Anchors pinned to frames** (ADR 0049): moving the object at a frame pins a path point there (a new anchor where it was put; after the last position key the path carries on), and the object passes every pinned point exactly on its frame, the X/Y eases timing it between pins; pinned points are diamonds with their frame number on the stage, blue keys in the Motion Editor's X/Y (dragging one moves its point) and holed diamonds on the timeline; Subselection's right-click pins to the playhead's frame or unpins, Properties › Frame has Pin Here / Unpin, F6 pins where the object is; point edits keep pins on their anchors; files without pins evaluate exactly as before. Headless: `timeline.create_motion_tween`, `motion.*` (`motion.set_path/clear_path/orient/add_point/delete_points/convert_point/move_path/pin_point/unpin_point`; `motion.info` reports `pins`). Not yet: retiming a pin by dragging its key in time, two pins on one anchor, XFL motion path keyframes, a marquee over path anchors, nudging or transforming a whole path, retiming keys, rescaling keys with the span, XFL motion-tween import. **Bones and IK, first slice** (ADR 0043): the Bone tool (M) drags from one symbol instance to another to join them with a bone on an armature layer (chains join end to start: a bone from a chained instance always starts at its joint; branches allowed, up to 256 bones); bones show as wedges in the layer colour; the Selection tool drags a bone (the grabbed point follows) or a posed instance to pose by cyclic coordinate descent (joint limits, pinned bones, one undo step per drag) and the root to move it all; poses are joint angles keyed per frame and tweened with the span's easing; Properties › Bone (angle, constrain min/max, pin, remove); `bone.*` headless; every export sees the pose. **Shape armatures** (ADR 0071): the Bone tool draws bones inside a shape (it moves to an armature layer as an object, outside merge drawing); its points are bound to the nearest bones automatically (weights by distance to each bone, up to four, summing to 1) and bend by linear blend skinning (handles with their anchors, strokes keep their width, the rest pose exact); the **Bind tool** (Shift+M) shows the points (squares, triangles where shared) and binds them by click, Shift/Ctrl-click or box; the same IK, poses and tweens; `bone.add_in_shape`, `bone.bind`, `bone.info {points}`. **Painted weights and reshaping** (ADR 0090): the Bind tool's **Paint Weights** brush (Add, Subtract, Smooth; size with `[`/`]`, strength; soft falloff) paints a bone's share onto the points under it, shown live as a heat map (blue none to red all) on the outline and points; weights stay normalised per point (the other bones share the rest, a point's only bone gives way to its nearest other bones), painted points are hand-bound, one undo step per stroke (1.15 ms for 32 dabs over 20,000 points); a focused point's weights as numbers in Properties › Bone (keyboard); Subselection edits a bound shape's outline at the rest pose (move, add, delete, smooth/corner) keeping the binding: moved points keep their weights, new points blend their neighbours', deleted points drop theirs, the rest pose exact; `bone.paint_weights`, `bone.set_weight`. **Springs, joint translation and members in place** (ADR 0084): joints slide along X/Y of what they start on, freely or within pixel limits, as part of each pose (IK slides only where turning can't reach); per-bone Spring and Damping swing bones after the motion and settle, evaluated as a pure replay of up to six seconds of motion (seeking equals playing bit for bit; 0.33 ms a frame for 16 sprung bones), shown on the stage, in Test Movie and every export, switched off per armature for posing; a picked bone's instance takes colour effect, blending and filters in place on every pose; `bone.set_translation`, `bone.set_spring`, `bone.enable_springs`. Not yet: runtime armatures, XFL import, mixing instances and shapes in one armature (proposed in ADR 0084 and 0090), reshaping at a posed frame, gravity and wind. **Asset Warp** (ADR 0079): the **Asset Warp tool** (Shift+Q) pins a shape or a bitmap (the first pin covers it with a warp mesh: a grid over its bounds, 2–48 cells along the longer side, Properties › Asset Warp); dragging a pin bends the artwork around the other pins by rigid moving least squares (Schaefer et al. 2006) at the mesh's vertices, live, one undo step per drag; Delete removes a pin; pins are added to every keyframe holding the artwork and their poses tween with classic tweens and easing; shapes bend through the mesh (straight edges exactly, curves split), bitmaps are drawn through its triangles by the CPU oracle (bilinear) and the GPU stage takes the same prepared fill (parity exact); the rest pose is the drawing bit for bit; every raster export, SVG (a bent bitmap baked as an image), Lottie and HTML (a bent bitmap reported) go through `evaluate`; `warp.add`, `warp.pin_add`, `warp.pin_move`, `warp.pin_remove`, `warp.remove`, `warp.info`. Not yet: as-rigid-as-possible solving on a mesh that follows the outline, symbols and text, binding warp pins to bones, a GPU textured-triangle path, bent bitmaps in HTML and Lottie, XFL import of warped assets. eases saved in the document and offered everywhere; copy/paste of an ease; classic tweens eased per property group: position, **Camera layer** (ADR 0027): the camera button in the timeline header or the Camera tool (C) adds a Camera layer on top; its frame shows on the stage in orange; drag to pan, turn with the round handle, wheel to zoom (one undo step per drag); Properties › Camera (position, zoom, rotation, tint, reset); keyframes and classic or motion tweens animate it; layer Depth gives pan parallax; View › Preview Through Camera shows the movie's picture (artwork tools pause there); hiding the camera layer turns it off; every export, Test Movie and the GPU stage see it. Headless: `camera.add/remove/set/info`, `layer.set_depth`. **Camera, second slice** (ADR 0082): layer depth in a pinhole perspective (deeper layers move and zoom less, draw behind nearer ones; depth 0 bit-exact), depth keyed over time (linear between keys), **Window › Layer Depth** (layers by depth, drag nearer or farther, key, attach), **Attach Layer to Camera** (timeline toggle; HUDs stay on screen), camera colour effects (Brightness, Tint, Advanced), and the Selection tool picking and moving artwork while previewing through the camera; headless `layer.set_depth {key, frame}`, `layer.remove_depth_key`, `layer.set_attached`, `layer.depths`, `element.pick {view: camera}`. Not yet: other tools while previewing, depth inside symbols, depth keys moving with inserted frames, XFL camera and layer-depth import (no public format description). **Motion guides**: guided layers (children of a guide through `Layer.parent`) have their classic tweens follow the guide's first path by arc length, from the point nearest each start keyframe to the point nearest its end (`geom::walk::PathWalk`), optionally orienting to the path; guide artwork is listed for picking and editing, drawn on the stage as a line, and never rendered or exported. | | Drawing | Selection (click, shift-add, marquee, drag-move, arrow nudge; **across layers**, ADR 0044: a selection holds artwork on several visible, unlocked layers, the timeline marks them, Properties shows mixed values), **Free Transform (Q)**: scale from corner/edge handles (Shift proportional, Alt from centre), rotate outside corners (Shift snaps 15°), move; one undo step per drag. Rectangle (corner radius), oval, PolyStar, line (45° snap), hand, zoom. **Pen (P)**: click for corners, drag for smooth handles (Alt breaks them), close on the first point, Enter/Esc/last-point click finishes, Backspace takes back a point; one undo step per path. **Pencil (Shift+Y)**: Smooth (Schneider curve fitting with corner detection), Straighten and Ink modes, smoothing relative to the screen. **Subselection (A)**: anchors and handles on selected shapes, drag points/handles (anchors bring their handles; one undo step per drag), point marquee, double-click an edge to add a point, Delete removes points, right-click Make Smooth/Corner; closed shapes' start point and closing edge edit like any other. **Cut/Copy/Paste in Center/Paste in Place** (the clipboard carries symbols across documents). **Rotate 90° CW/CCW, Flip H/V. Align** left/centre/right/top/middle/bottom (Ctrl+Alt+1…6; a single element aligns to the stage) and distribute. Convert to symbol / break apart; arrange; duplicate. Headless: `draw.path`, `draw.freehand`, `path.move_points/add_point/delete_points/convert_point`. **Paint Bucket (K)**: click a fill to recolour it, or inside an outline (one shape or several) to fill the enclosed area; gap size None/Small/Medium/Large closes openings; the fill is traced and curve-fitted into a new shape placed under its lines; open areas say so instead of flooding. **Ink Bottle (S)**: gives the clicked shape the current stroke. Headless: `paint.bucket`, `paint.ink`. Tool options show first in Properties while a drawing tool is active. **Text (T)** (ADR 0012): click to type on the stage, click or double-click text to edit it; font (installed families, plus the embedded Inter), size, colour, under or over the artwork, snap accuracy up to Always); Snap to Pixels; one snap engine for every drawing tool, the Selection tool's moves and Free Transform's handles (point › guide › line › grid › pixel, guides and grid per axis); stage only, never exported, on the CPU and GPU stage. Headless: `view.rulers`, `view.grid_show/grid_snap/grid_set`, `view.guides_show/guides_lock/guides_snap/guides_set`, `view.guide_add/guide_move/guide_delete/guides_clear`, `view.snap_pixels`, `view.aids`, `moving` on `draw.snap`. *Not yet:* units other than px, a movable ruler origin, a symbol's own guides, guides and grid from Animate files, Snap Align and Edit Snapping, snapping while rotating. bold, italic, alignment, letter/line spacing, wrap width; the last style is kept for new text; laid out by `anicraft-text` (`fontdb` discovery, `harfrust` shaping, `skrifa` outlines) and stored as outlines with the source, so rendering never needs the font; Break Apart makes a shape. **Variable-width strokes** (ADR 0018): a stroke's width varies along it through width points (position by arc length, a width on each side as a factor of the stroke width, smooth monotone interpolation); built-in profiles (Uniform, Taper both ends, Taper start, Taper end, Bulge, Pinch) in Properties › Width with a picture of each, and in the drawing tools' options for new strokes; the **Width tool (U)**: hover a stroke to see its width points, drag a handle to widen or narrow (Alt: one side), drag the dot to slide a point, drag anywhere on the stroke to add one, Delete removes; one undo step per drag; rendered by the oracle as trapezoids with outer round joins and cross-section caps, written by SVG and Lottie export as the same filled outlines; shape tweens blend profiles; `.anicraft` keeps them (older files open as uniform). Headless: `stroke.set_profile`, `stroke.set_width_point`, `stroke.delete_width_point`, `stroke.width_at`, `profile` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: width data from or to Animate files, saved custom profiles, pressure. **Stroke styles** (ADR 0046): Properties › Style (Solid, Dashed with dash and gap, Dotted with spacing), Cap (None, Round, Square), Join (Miter, Round, Bevel) and Miter limit, also in the drawing tools' options for new strokes; drawn exactly by the oracle (butt and square caps, miters bevelled past the limit, dashes by arc length restarting per subpath, round dots, dashes keeping a width profile's widths; sub-pixel patterns solid and faded) and so by the GPU stage; the Ink Bottle carries the style and the Eyedropper picks it; merge drawing keeps it on cut pieces; shape tweens blend miter limits and dash lengths; SVG, HTML canvas and Lottie export write it. Headless: `stroke.set_style`, and `cap`, `join`, `miter`, `style`, `dash`, `dash_offset`, `dot_spacing` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: Animate's ragged, stipple and hatched styles, multi-dash patterns in Properties (kept and editable by command), stroke scale modes and hairlines. **Merge drawing** (ADR 0031, first slice): with Object Drawing (J) off, the editor's default, the shape tools, Pen and Pencil draw raw strokes and fills that cut and join the raw shapes they touch (a fill on top replaces what it covers or joins the same colour, lines cut each other and the fills they cross, a fill hides the lines under it, points within 0.2 px are one; exact Bézier pieces, `anicraft_geom::planar`); one element per fill region and stroke run, selected with Animate's dot pattern; double-click selects connected strokes, or a fill with its outline; a dragged or nudged raw shape merges where it lands; arrows move 1 screen pixel (Shift 10). Headless: `object` on the drawing commands (scripts draw objects by default), `draw.object_drawing`, `draw.drop`, `element.select_connected`. **Selection tool on raw shapes** (ADR 0041): drag an unselected segment or fill edge to bend it through the pointer (every shape sharing the edge bends with it), an unselected corner or end to move it with every raw shape that shares it, a fill to move only that fill; points and selections snap to points, strokes and fill edges within 10 screen px (snap ring), and arrow nudges join ends within 0.2 px at their midpoint or onto a line that stays put; a corner or curve mark by the pointer shows what a drag does; the marquee selects the parts of raw fills and strokes under it, cut at its edges (taken back if nothing uses them, no undo step), and objects wholly inside; each drag one undo step, merged on release. Headless: `path.bend_segment`, `raw.move_point`, `raw.select_rect`, `raw.merge`, `raw.hit`, `snap` on `element.translate`. **Subselection on raw shapes and merging everywhere** (ADR 0042): with Subselection (A), a click on a raw line or fill shows the anchors of everything connected to it (once per shared point; hollow, selected ones solid) and the handles of the selected anchors' curves and of the clicked edge; drag an anchor to move it with the other selected ones and every shape on them, a handle to change the curve in every shape that has the edge, a line or fill to move everything connected; Shift adds or removes anchors; the marquee takes whole shapes on the active layer and selects the anchors inside; arrows nudge 1 screen px (Shift 10); one undo step per gesture, merged on release. **Snap to Objects** (View › Snapping, a magnet under the tools, the selection tools' options) switches the Selection and Subselection tools' snapping. The Paint Bucket's raw fills are exact (up to the lines and fill edges, from the planar merge) and join fills of their colour; pasted raw shapes cut what they land on; raw shapes from Animate files open raw and merged; gradient and bitmap fills take part in the merge. Headless: `raw.subselect`, `raw.subselect_rect`, `raw.points`, `raw.move_handle`, `with` on `raw.move_point`, `draw.snap_to_objects`, `object` on `paint.bucket`. Not yet: width profiles in the merge. **Raw points and symbols in place** (ADR 0045): add a point on a raw edge (Pen Alt-click, Subselection double-click; every shape on the edge gets it, the curve unchanged), delete raw points (Delete; the shapes on each are joined across it so the drawing stays connected; points where three edges meet are kept), Make Smooth / Corner on raw points, smooth handle pairs (Alt breaks them; drawing objects too); the Line, Rectangle, Oval, PolyStar and Pen tools snap their points within 10 screen px (Snap to Objects, Ctrl+Shift+/); a double-click on an instance (or Ctrl+E, or a double-click in the Library) opens the symbol in place, the stage dimmed around it, the edit bar showing the path back, and every tool and command works on its timeline. Headless: `raw.add_point`, `raw.delete_points`, `raw.convert_points`, `draw.snap`, `smooth` on `raw.move_handle` and `path.move_points`, `symbol.edit`, `symbol.exit`. Not yet: rotated instances in place (they open upright). Onion skin and Edit Multiple Frames work inside a symbol since ADR 0051. **Brush (B)** (ADR 0033, first slice): paints filled shapes in the fill colour, the exact area the tip sweeps (a distance field traced and fitted with cubics); round or square tip with size, angle and roundness (oval and flat calligraphic tips), pen pressure from a tablet (10–100 % of the size; a mouse paints full size), smoothing relative to the screen, Paint Normal, Paint Fills and Paint Behind; a raw shape that merges with the drawing, or a drawing object with Object Drawing on; a click paints a dab; live preview while dragging; `[` and `]` change the size; one undo step per stroke. Headless: `draw.brush`. **Paint Selection and Paint Inside** (ADR 0080): the paint is clipped to the selected fills' union, or to the fill (or closed-off empty area) the stroke starts in, exactly on the planar map, then merged under the lines; Paint Selection keeps the selection for the next stroke. Not yet: the live preview clipped as it paints. **Brush library, pressure curves and the Paint Brush (Y)** (ADR 0068, first slice): Window › Brush Library with seven built-in brushes made only of parameters (Pencil, Ink Pen, Flat Calligraphy, Round Taper, Marker, Chalk with a deterministic worn edge, Dotted stamps), each with a stroke preview drawn by the renderer; brushes of your own saved by name in your preferences, renamed, deleted (asks first) and moved between computers as a JSON brush set; a pressure curve editor (Linear, Soft, Firm, or your own points) driving size and, optionally, the stroke's opacity; tapers, dab spacing and a rough edge in Properties; Velocity (mouse speed as pressure, off by default); the Paint Brush draws a width-profiled stroke in the stroke colour that the Width tool edits. Headless: `brush.preset_list/save/rename/delete/export/import`, `preset`, `curve`, `as_stroke` and the shaping params on `draw.brush`. Not yet: pen tilt (egui doesn't report it), opacity varying along a stroke, textured or art brushes, Eraser presets and pressure. **Eraser (E)** (ADR 0034, first slice): sweeps the Brush's tip and takes what it covers out of the raw shapes on the active layer (the sweep is a fill in the planar merge that comes out empty); Erase Normal, Erase Fills, Erase Lines, Erase Selected Fills and Erase Inside; the Faucet deletes a whole fill or line with a click; drawing objects, symbols and text are kept; a stroke that erases nothing leaves no undo step; live preview, `[` and `]` sizes, one undo step per stroke; double-clicking the tool (or Erase Everything… in its options) clears the visible, unlocked layers at this frame after asking. **Eyedropper (I)** (first slice): a click on a fill picks its paint (solid, or a gradient or bitmap kept where it is on the stage, as Lock Fill) into the fill swatch, a click on a line picks its colour, width and profile; with shapes selected it applies the style to them; then it becomes the Paint Bucket or the Ink Bottle; Shift-click picks into the other swatch only. Headless: `draw.erase`, `draw.faucet`, `draw.erase_all`, `paint.pick`, `paint.apply_style`. Not yet: erasing inside symbols, erasing width-profiled shapes (gradient fills erase since ADR 0042), eraser pressure, picking a bitmap's pixel colour or text styles, an eyedropper cursor. **Colour picker and drawing-tool fixes from user reports** (M1): every colour swatch (the Tools panel's fill and stroke squares too) opens one picker with Animate's web-safe swatches (216 colours, greys and primaries), the colours mixed or typed this session, a hex field and the full mixer; the Tools squares offer No Colour and recolour selected shapes; drawing tools leave nothing selected after a stroke and the Selection tool's box has no handles (they are Free Transform's); Break Apart turns drawing objects into merged drawing; Ctrl-drag on a raw edge adds a corner point; the Pencil and Line show no fill. **Swatches panel** (ADR 0078): Window › Swatches, the document's saved colours and gradients (in the `.anicraft` file; a default set for new documents and older files); click applies to the selection and the tool colour, to the stroke or fill that is active (Tools squares, Colour panel or the panel's toggle; gradients always to the fill); + adds the active colour or gradient, Duplicate, Delete, drag (or Alt+arrows) to reorder, names on hover, Clear (keeps black and white) and Load Default Swatches (ask first, undoable); import and export as a JSON swatch file, GIMP `.gpl` import; the colour picker shows the document's swatches and the fill picker its gradient swatches. Headless: `swatch.list/add/remove/move/duplicate/rename/apply/clear/reset/import/export`. Not yet: swatch folders, sorting by colour, bitmap swatches, Save as Default, XFL swatch import (no public description), Adobe `.aco`/`.ase`/`.clr` (proprietary). The layer footer is icon buttons (New Layer, Delete, New Folder, Up, Down) that fit at any size and language. **Groups and Combine Objects** (ADR 0073): Modify › Group (Ctrl+G) / Ungroup (Ctrl+Shift+G), a group element whose members are a one-layer, one-frame timeline, opened in place by a double-click like a symbol (every tool works inside; raw shapes merge only with each other); nested groups; exports, player, sounds and the Library see inside; XFL `DOMGroup` imports as groups. Combine Objects › Union, Intersect, Punch, Crop on the planar map (analytic area tests). Selection tool: Alt-drag copies, Shift constrains to 45° (Ctrl/⌘-drag corners: #257). **Drawing parity leftovers** (ADR 0080): PolyStar's Shape (Polygon or Star), sides 3–32 and star point size 0–1 in its options (`shape`, `sides`, `point_size` on `draw.star`); a double-click (or Ctrl+E) opens a drawing object in place, its raw shapes merging only with each other, and it closes as one object again (a group of the pieces when an edit leaves several); **Modify › Transform › Envelope**: a Bézier mesh of corner and tangent handles bends the selected shapes and drawing objects, one undo step per drag, baked like Animate's (no Delete Envelope needed), undo restoring the mesh; headless `modify.envelope`, `modify.envelope_move`, `modify.envelope_close`. *Not yet:* gradient and bitmap strokes (proposed in ADR 0080), envelope handles from the keyboard, an envelope on symbols, text or groups, drawing objects edited without opening them (#181), Combine across layers. **Rulers, grid and guides** (ADR 0076): View › Rulers (stage pixels, following zoom and pan, pointer marked); guides per scene saved in the document, dragged from a ruler, moved with the Selection tool, dragged back to delete, Show/Lock/Snap/Edit/Add/Clear (Edit Guides lists and adds them from the keyboard); a grid (spacing, | | Plug-ins | **WebAssembly plug-ins** (ADR 0017, `docs/plugins.md`): sandboxed modules run by `wasmi` with no imports but the AniCraft ABI (`anicraft.call`/`anicraft.response`: JSON requests that run registry commands, read a compact document view or the active layer's elements, and log); fuel (10⁹ instructions), memory (256 MiB), wall-clock (5 s), request, size and log limits, a fresh instance per run; file, plug-in, undo and clipboard commands refused. `plugin.install/list/run/remove/reload`; a run is atomic and one undo step named after the plug-in. App: **Commands** menu (Plug-ins, Install, Manage, Reload), palette entries, a dialog generated from the manifest's parameters with a live preview; plug-ins load from `/plugins` or `ANICRAFT_PLUGINS`; CLI `--plugins`. Samples in Rust (Star Field, Jitter Selection, guest SDK) in `examples/plugins`. Frame scripts: see Interactivity. **Exporter and ease plug-ins** (ADR 0088): `kind: "exporter"` declares a format (name, extension, options) and gets evaluated frames (`movie`, `frame`: the flattened display list, never the document), returning the file's bytes from `ac_export` (64 MiB cap, 5·10¹⁰ instructions, 10 min); File › Export lists it with an Export window (options, frames, file, progress bar and Cancel on a worker thread); `file.export_plugin`, `file.export_formats`, `anicraft-cli export --format ` and `formats`. `kind: "ease"` declares named eases, `ac_ease(i, t)` sampled into 257 values at load (NaN, unbounded or end-missing eases refused); `Easing::Sampled` keeps the table in the document, so it plays the same without the plug-in; the ease menus list them under Plug-in eases; `{plugin, ease}` easing params. Samples: Plain Text Frames and Stepped Eases, built and run in CI. Not yet: plug-in formats in Publish, bitmaps' pixels and sounds for exporters, ease plug-ins with parameters, background runs of command plug-ins, a binary document view. | | Interactivity | **Frame actions, frame scripts and Test Movie, first slice** (ADR 0024): a typed timeline action IR (`anicraft-actions`: stop, play, go to a frame or label in a scene, next/previous frame and scene, trace, set x/y/alpha/visible/rotation/scale, instance-name target paths) on keyframes and on button and movie clip instances (click, press, release, over, out); a pure, deterministic, budgeted player in `anicraft-doc` (`step(doc, &state, &events)`; movie clip playheads, button Up/Over/Down states with Hit-frame hit tests, script-set properties) drawn by `evaluate_player`, while `evaluate` and exports stay script-free. **Actions panel** (F9: structured lists, targets/labels/scenes picked from the document; movie clip timelines too), instance name and events in Properties, an "a" on keyframes with actions. **Frame scripts** on the plug-in host (`kind: "frame-script"`, entry points, `player`/`action` ops, 20 M instructions per frame shared, no document access). **Test Movie** (Control › Test Movie, Ctrl+Enter): the player at the document frame rate in its own window with the pointer, restart/pause/step and an Output panel. **A window of its own on the desktop** (ADR 0062): sized to the stage at 100 % (smaller to fit the screen), titled with the document, back where it was last (not on Wayland, where the desktop places windows), with the keyboard when it opens; Esc or Ctrl+W (⌘W) closes it, Ctrl+Enter restarts it in place, and the editor's Ctrl/Alt shortcuts work from it; floating inside the editor in the web build, where the system can't open windows (it says so), or by choice in Preferences › Test Movie. Not yet: full screen, zoom in the movie window, remembering its size. Headless: `actions.set/clear/list`, `instance.set_name`, `control.test_movie` (timed pointer events, returns output and state). **HTML canvas export** (ADR 0028, `file.export_html`, File › Export › Export HTML Canvas…): one self-contained page (data, player and drawing code inline; images and sounds embedded) that plays in any browser with canvas 2D; every used timeline baked frame by frame (tweens of every kind exact, identical paths, paints and frames stored once), movie clips, buttons with Hit areas and every action run by `player.js`, a port of the Rust player checked against it step by step in Boa (state, output and display list); masks and fading/blending groups on offscreen layers; **filters and Subtract/Invert in the page** (ADR 0072: `filters.js`, a port of the renderer's filters run over the group's pixels on a layer that reaches past the canvas by the filters' reach, Subtract and Invert composited per pixel, results kept while the group is unchanged; equal to the oracle's pixels within 9.3e-4 in Boa; 3.4 ms a frame for the demo's filters at 1080p while they change); Web Audio for Event/Start/Stop/Stream sounds; bitmap tints, 9-slice scaling and plug-in frame scripts reported. Not yet: 9-slice in the page, keeping a moving filtered group's pixels, filters off the main thread. **Kept frame scripts** (ADR 0013 tier 1): scripts written in another language (an Animate document's ActionScript) kept verbatim on keyframes with their language, symbol linkage classes and the document class; the Actions panel's **Script** view (monospace editor with line numbers, language, live and undoable), the same "a" marker, Class rows in Properties; `script.set/clear/list/set_class`; **ActionScript timeline subset runs** (ADR 0013 tier 2): a hand-written, bounded lexer and parser (`anicraft_actions::as3`) lower stop/play/go to/next and previous frame and scene on instance-name paths, mouse listeners (click, down, up, roll over and out; named or inline functions, `currentTarget`), `trace` and property settings to the action IR, compiled once per script; anything else is reported with line and column and the script doesn't run (never half-run), `navigateToURL` and the like are ignored and noted; the player keeps listeners per instance, Test Movie's Output says which scripts run and which don't and why, the Script view lists problems in place, the XFL report and `script.list/check` say what runs, and the HTML page runs the same steps (`player.js` checked against the Rust player). **ActionScript small logic** (ADR 0052): scripts compile to a small typed script IR evaluated by the player with fuel (100,000 per script or listener call, 1,000,000 per step; an endless loop or a run-time error stops its script with an Output line and the movie plays on): typed variables (Number, int, uint, Boolean, String, untyped) kept per timeline instance across its frame scripts, expressions as ECMA-262 has them, `if`/`else`, `for`/`while`/`do`, functions with parameters, results and recursion, called from any frame of the same timeline (a timeline-level link step; names that aren't there keep the script from running, said in place), property reads of instances and timelines (`x`, `y`, `alpha`, `visible`, `rotation`, `scaleX/Y`, `currentFrame`, `totalFrames`, `currentLabel`, `mouseX/Y`, `name`), `removeEventListener`, `Event.ENTER_FRAME`, `KeyboardEvent.KEY_DOWN/KEY_UP` on the stage with `e.keyCode`, `e.target`/`e.currentTarget`, seeded `Math.random()`; keyboard in Test Movie and the HTML page, `control.test_movie` key events and `seed`; `player.js` mirrors the evaluator, checked step by step in Boa. Not yet: ActionScript `switch`, `for in`, arrays and objects, string methods, closures, event bubbling, mouse listeners on the stage, ActionScript 1.0/2.0, scripts on instances, filters and keyboard focus in the HTML page, sound actions, keyboard events, variables, persistent script state, masks in hit tests, a separate OS window. **Buttons, complete** (ADR 0057): a button open in place names its frames Up, Over, Down and Hit on the timeline and shows its Hit area translucent over the other states; Test Movie has **Show hit areas**; sounds on its frames play as its state changes. | @@ -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); ~~sound and video items, self-extracting and top-folder `.fla` archives~~ ✅ (ADR 0086: sound effects and custom envelopes, every sound and video that doesn't come across named with its format, Screen Video stills, zipped XFL folders and self-extracting stubs; not yet: sound in/out points, AIFF and compressed WAV, video playback); ~~SVG import (Import to Stage)~~ ✅, ~~SVG frame export~~ ✅; ~~Lottie export~~ ✅ (~~easing curves instead of per-frame keys~~ ✅, ADR 0089: keyframes with Bézier eases, moving artwork under group transforms, playback parity at every frame; not yet: motion along curved guides as spatial tangents, orient to path, nested tweens as nested transforms); ~~sprite sheet + JSON~~ ✅; ~~MP4/WebM via ffmpeg pipe~~ ✅; ~~animated PNG and WebP~~ ✅ (ADR 0063; lossless WebP; lossy WebP not yet). | | **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, outlines stored with the text; per-character styles later); ~~text on a path~~ ✅ first slice (ADR 0070: a copy of a shape's outline in the block, glyphs set by arc length and stored as outlines, offset, flip and alignment, Attach to Path by picking a shape, SVG `textPath`; editing the path in place and several lines on a path later); ~~dynamic and input text fields~~ ✅ first slice (ADR 0066: Text type in Properties, instance names, `field.text`/`appendText`/`length` in scripts, typing with caret, selection, max chars and passwords in Test Movie, native inputs in the HTML export, XFL fields kept; `htmlText`, change events, embedded fonts in HTML and other `TextField` API later); ~~bitmap import and bitmap fills~~ ✅; ~~audio layers, waveform display, stream sync~~ ✅ first slice (ADR 0020: WAV, Ogg Vorbis, MP3; `cpal` output); ~~effect envelopes, layer volume and mute, sounds inside symbols~~ ✅ (ADR 0039); ~~button sounds and hit-area editing~~ ✅ (ADR 0057: state sounds in Test Movie and HTML, state names on the timeline, the Hit area over the other states, Show hit areas in Test Movie, XFL sounds in the package); ~~filters (blur, drop shadow, glow, colour matrix)~~ ✅, ~~bevel, gradient glow and gradient bevel~~ ✅ (ADR 0025; SVG export and XFL import), ~~filter presets, reordering, on/off and tweened filter values~~ ✅ (ADR 0091: drag or Alt+arrows to reorder, an eye per filter that keeps its settings, Copy/Paste Filters, presets in your preferences with a JSON file to move them; classic tweens pair lists with switched-off filters; motion-tween tracks per filter property in the Motion Editor, filters on text fields and built-in presets 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 plug-ins~~ ✅ (ADR 0088); ~~frame scripts on the same sandbox~~ ✅ and ~~button states in test-movie preview~~ ✅ first slice (ADR 0024: action IR, pure player, Actions panel, Test Movie); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028: one self-contained page, baked frames, a JS port of the player tested against it; ~~filters, Subtract and Invert in the page~~ ✅, ADR 0072); command macros. **ActionScript compatibility, low priority** (ADR 0013), last in M6 and free to slip past M8: ~~tier 1 keeps scripts~~ ✅ (XFL frame scripts and class names stored verbatim, the Actions panel's Script view, `script.*` commands); ~~tier 2 runs the ActionScript 3 timeline subset (stop, play, go to frame or label, named instances, button events) in Test Movie and HTML canvas export through the same action IR as WebAssembly frame scripts~~ ✅; ~~tier 2.5 small logic (typed variables, expressions, `if` and loops, property reads, functions across frames, enter-frame and keyboard listeners, seeded random, ADR 0052)~~ ✅. The full language, the `flash.*` API and SWF bytecode are not planned. | -| **M7** | Advanced animation | ~~Bone/IK tool~~ ✅ first slice (ADR 0043: symbol-instance armatures on an armature layer, Bone tool, joint-angle poses tweened with easing, CCD inverse kinematics with joint limits and pins, posing with the Selection tool, Bone properties, every export; not yet: outline-following ARAP meshes, symbols, pins bound to bones, a GPU textured path, bent bitmaps in HTML/Lottie); ~~springs, joint translation, editing members in place~~ ✅ second slice (ADR 0084); not yet: runtime armatures, XFL armature import); ~~shape armatures~~ ✅ first slice (ADR 0071: bones inside one shape, automatic binding, linear blend skinning, Bind tool; not yet: instances and shapes in one armature, reshaping a bound shape, painted weights); ~~asset warp~~ ✅ first slice (ADR 0079: warp meshes on shapes and bitmaps, pins, rigid MLS, pin poses tweened, Asset Warp tool, ~~camera layer with depth~~ ✅ first slice (ADR 0027: one camera layer per scene, pan/zoom/rotate/tint, classic and motion tweens, pan-only layer depth, Camera tool, Preview Through Camera, every export); ~~layer depth in perspective, keyed over time, Layer Depth panel, attaching layers, camera colour effects, editing while previewing~~ ✅ second slice (ADR 0082; not yet: tools other than Selection while previewing, depth inside symbols, XFL camera import); ~~variable-width strokes~~ ✅ first slice (ADR 0018: width profiles, Width tool, exports, tweens); ~~Brush tool~~ ✅ first slice (ADR 0033: filled sweeps, tips, pressure, Paint Normal/Fills/Behind; not yet: Paint Selection/Inside); ~~brush library, pressure curves and the Paint Brush~~ ✅ first slice (ADR 0068: parameter presets, user brushes and brush sets, curve editor, velocity, stroke mode; not yet: tilt, textured brushes); ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034: five erase modes, Faucet, Erase Everything; picks solid, gradient, bitmap and line styles; not yet: erasing inside symbols, gradients and width profiles in the merge) and brush library; ~~graph-based easing presets library~~ ✅ first slice (ADR 0081: presets, custom multi-segment eases, saved eases, per-group classic eases, Motion Editor properties, XFL import; not yet: updating every tween that uses a saved ease, a user ease library shared between documents, Lottie-native eases instead of baked frames, motion-tween eases from XFL). | +| **M7** | Advanced animation | ~~Bone/IK tool~~ ✅ first slice (ADR 0043: symbol-instance armatures on an armature layer, Bone tool, joint-angle poses tweened with easing, CCD inverse kinematics with joint limits and pins, posing with the Selection tool, Bone properties, every export; not yet: outline-following ARAP meshes, symbols, pins bound to bones, a GPU textured path, bent bitmaps in HTML/Lottie); ~~springs, joint translation, editing members in place~~ ✅ second slice (ADR 0084); not yet: runtime armatures, XFL armature import); ~~shape armatures~~ ✅ first slice (ADR 0071: bones inside one shape, automatic binding, linear blend skinning, Bind tool); ~~painted weights and reshaping a bound shape~~ ✅ second slice (ADR 0090; not yet: instances and shapes in one armature, reshaping at a posed frame); ~~asset warp~~ ✅ first slice (ADR 0079: warp meshes on shapes and bitmaps, pins, rigid MLS, pin poses tweened, Asset Warp tool, ~~camera layer with depth~~ ✅ first slice (ADR 0027: one camera layer per scene, pan/zoom/rotate/tint, classic and motion tweens, pan-only layer depth, Camera tool, Preview Through Camera, every export); ~~layer depth in perspective, keyed over time, Layer Depth panel, attaching layers, camera colour effects, editing while previewing~~ ✅ second slice (ADR 0082; not yet: tools other than Selection while previewing, depth inside symbols, XFL camera import); ~~variable-width strokes~~ ✅ first slice (ADR 0018: width profiles, Width tool, exports, tweens); ~~Brush tool~~ ✅ first slice (ADR 0033: filled sweeps, tips, pressure, Paint Normal/Fills/Behind; not yet: Paint Selection/Inside); ~~brush library, pressure curves and the Paint Brush~~ ✅ first slice (ADR 0068: parameter presets, user brushes and brush sets, curve editor, velocity, stroke mode; not yet: tilt, textured brushes); ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034: five erase modes, Faucet, Erase Everything; picks solid, gradient, bitmap and line styles; not yet: erasing inside symbols, gradients and width profiles in the merge) and brush library; ~~graph-based easing presets library~~ ✅ first slice (ADR 0081: presets, custom multi-segment eases, saved eases, per-group classic eases, Motion Editor properties, XFL import; not yet: updating every tween that uses a saved ease, a user ease library shared between documents, Lottie-native eases instead of baked frames, motion-tween eases from XFL). | | **M8** | Release quality | ~~Installers and signing for Windows/macOS/Linux~~ ✅ first slice (ADR 0026: family `packaging/` layout, MSI, DMG, AppImage/deb/rpm/Flatpak/tar.gz, `.anicraft` registered everywhere, signing wired to the release environment; ~~opening documents from Finder~~ ✅ (ADR 0062, to be checked on a Mac); next: AppImage desktop integration, portable mode, store submissions); ~~web build (wasm) of the editor~~ ✅ first slice (ADR 0036: browser file picker and downloads, autosave in browser storage, CPU stage, CI wasm build and tests in Node, the release zip made by `packaging/web/package.sh` and checked in CI (#210); next: releases carrying it and a hosted copy, once the team decides where, Web Audio, WebGPU stage, verified in browsers); ~~localisation~~ ✅ first slice (ADR 0040: `tr!` everywhere in the shell, craft-i18n catalogs, Preferences language, pseudo-locale; next: AniCraft's catalog in craft-i18n, engine messages, right to left once egui can lay it out); accessibility: first pass ✅ (ADR 0022: screen-reader names for every control, Ctrl+F6 panel focus, high-contrast theme, 200 % scale), second pass ✅ (ADR 0064: stage elements and timeline frames for screen readers, keyboard selection on the stage, keyboard menu bar, following the system's contrast setting), ~~a light theme~~ ✅ (ADR 0077: Light palette, Follow system for light or dark, #227), next: live screen-reader passes on each platform, a light high-contrast palette; ~~crash-recovery autosave~~ ✅ (ADR 0015); ~~Find and Replace and the Movie Explorer~~ ✅ first slice (ADR 0058: `find.search`/`find.replace`/`find.goto` over text, fonts, colours, symbols, sounds and bitmaps, scene or document, linear-time patterns, Replace All as one undo step asking above 100 places, going there opens symbols in place; `explorer.tree` paged, Show filters and search, the Movie Explorer tab beside the Library, lists drawing only the rows in view; not yet: action parameters and ActionScript strings apart from code, font size and style, colour tolerance, renaming in the Movie Explorer); ~~files from the desktop, recent files and a start screen~~ ✅ first slice (ADR 0059: drops route by type and target in one undo step, Open Recent with pins and missing files, start screen with presets and thumbnails); ~~templates, SVG into the Library, drops on the timeline~~ ✅ first slice (ADR 0065: six built-in templates built in code, Save as Template with category and picture, SVG as a graphic symbol, sounds onto a frame's keyframe and media into a keyframe made there; next: exact desktop drop positions once eframe moves to winit 0.31, user template descriptions and renaming); ~~Publish Settings and Publish~~ ✅ first slice (ADR 0060: the publish profile in the document, every format with its export options and an output relative to the document's folder with `{name}`, Shift+F12 publishing in the background with progress, Cancel and one report, overwriting asked once per session, presets in Preferences, the browser's downloads as one ZIP; not yet: Animate's PublishSettings.xml from XFL, more placeholders, outputs outside the document's folder, progress inside HTML, Lottie and audio); ~~documentation book~~ ✅ first slice (ADR 0069: the user guide in `docs/guide/`, generated command and shortcut references, Help › User Guide offline; next: translated guides, search, PDF, context help); ~~dockable panels and workspaces~~ ✅ first slice (ADR 0075, #249: every panel docks on any side of the stage, stacks as tabs, resizes, folds, floats in a window of its own with ADR 0062's fallback, closes and reopens where it was from the Window menu; Essentials, Animator, Designer and your own workspaces with Reset, kept in the preferences; new Colour and Output panels; Ctrl+F6 follows the layout), second slice ✅ (ADR 0087: the tools move like any panel, as a slim bar on any side or a tab laid out in columns; floating windows hold several tabs and drag back into a dock by their grip or title bar with the drop targets shown; docks collapse to strips of panel icons with flyouts over the stage (Esc or a click outside closes them); Manage Workspaces renames and deletes your own (built-in ones reset only); every panel fits the narrowest dock (200 pt), form rows wrapping under their label, checked by test in English and the pseudo-locale; not yet: dragging between two windows of their own on mixed-DPI screens verified by hand, panels side by side inside a floating window, columns of groups in one dock, minimum sizes per panel, panel shortcut keys). | ## 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); ~~exporter and easing plug-ins~~ ✅ (ADR 0088); next: command macros, or growing the ActionScript subset (`switch`, arrays, event bubbling) | command registry, plug-in host, action IR and player | -| M7 | ~~Variable-width strokes~~ ✅ (ADR 0018), ~~camera layer with depth~~ ✅ first slice (ADR 0027), ~~camera depth, attaching and colour~~ ✅ (ADR 0082), ~~Bone tool and IK~~ ✅ first slice (ADR 0043), ~~shape armatures and the Bind tool~~ ✅ first slice (ADR 0071), ~~bone springs and joint translation~~ ✅ (ADR 0084), ~~Asset Warp~~ ✅ first slice (ADR 0079), ~~Brush tool~~ ✅ first slice (ADR 0033), ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034); ~~brush library and pressure curves~~ ✅ first slice (ADR 0068); next: Paint Selection/Inside, tilt | strokes, Pen and Pencil, width profiles, timeline evaluation | +| M7 | ~~Variable-width strokes~~ ✅ (ADR 0018), ~~camera layer with depth~~ ✅ first slice (ADR 0027), ~~camera depth, attaching and colour~~ ✅ (ADR 0082), ~~Bone tool and IK~~ ✅ first slice (ADR 0043), ~~shape armatures and the Bind tool~~ ✅ first slice (ADR 0071), ~~painted weights and reshaping~~ ✅ (ADR 0090), ~~bone springs and joint translation~~ ✅ (ADR 0084), ~~Asset Warp~~ ✅ first slice (ADR 0079), ~~Brush tool~~ ✅ first slice (ADR 0033), ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034); ~~brush library and pressure curves~~ ✅ first slice (ADR 0068); next: Paint Selection/Inside, tilt | strokes, Pen and Pencil, width profiles, timeline evaluation | | M8 | ~~Crash-recovery autosave~~ ✅, ~~accessibility first pass~~ ✅ (ADR 0022), ~~installers and signing~~ ✅ first slice (ADR 0026), ~~web build~~ ✅ first slice (ADR 0036), ~~localisation~~ ✅ first slice (ADR 0040), ~~Find and Replace and the Movie Explorer~~ ✅ first slice (ADR 0058), ~~drops, recent files and the start screen~~ ✅ first slice (ADR 0059); ~~templates and drops on the timeline~~ ✅ first slice (ADR 0065); ~~Publish Settings and Publish~~ ✅ first slice (ADR 0060); ~~Test Movie in its own window and macOS document opening~~ ✅ first slice (ADR 0062); ~~accessibility second pass~~ ✅ (ADR 0064); ~~a light theme~~ ✅ (ADR 0077); ~~CI on macOS and Windows~~ ✅ (ADR 0067); ~~dockable panels and workspaces~~ ✅ first and second slices (ADR 0075, ADR 0087); next: live screen-reader passes | `.anicraft` format, session, AccessKit in eframe | Tasks that wait on an open track: XFL motion tweens (on M2's motion tweens); frame scripts and diff --git a/src/a11y.rs b/src/a11y.rs index 9e6c7bd6..52c4c465 100644 --- a/src/a11y.rs +++ b/src/a11y.rs @@ -381,6 +381,18 @@ mod tests { assert_eq!((score.role(), score.value()), (Role::Label, Some("Hello, Ada Lovelace!"))); } + /// Painted weights (ADR 0090) are reachable without a pointer: the brush and a point's weight + /// are named fields, the weight a number to type. + #[test] + fn shape_weights_are_named_numeric_fields() { + let (t, _, _) = tree(|a, _| a.open_panel(Some("shapeweights"))); + for n in ["Paint Weights", "Weight brush size", "Weight brush strength", "Focused point", "Bone weight at the point"] { + assert!(t.nodes.iter().any(|(_, x)| x.label() == Some(n)), "no node named {n}"); + } + let w = t.nodes.iter().map(|(_, x)| x).find(|x| x.label() == Some("Bone weight at the point")).expect("the weight field"); + assert!(matches!(w.role(), Role::SpinButton | Role::Slider | Role::TextInput), "{:?}", w.role()); + } + /// The layer footer (after #265 cut "Delete" short): icon buttons only, each named, side /// by side inside the layer column at the default window size, none clipped or overlapping. #[test] @@ -414,7 +426,7 @@ mod tests { for tool in [Tool::Bone, Tool::Bind, Tool::Warp, Tool::Rect, Tool::Star, Tool::Text, Tool::Pencil, Tool::Brush, Tool::PaintBrush, Tool::Eraser, Tool::PaintBucket, Tool::InkBottle, Tool::Eyedropper, Tool::Pen] { found.extend(check(&format!("{tool:?} tool"), |a, _| a.tool = tool)); } - for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "springbones", "shapebones", "warp", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple", "library", "librarymenu", "edittransform", "onionsymbol", "layerprops", "frameview", "layercolour", "timelinepolish", "convert", "mixed", "bitmap", "nineslice", "nineslicedit", "find", "explorer", "publish", "publishreport", "publishanim", "start", "drop", "droplibrary", "testmovie", "testmovieinside", "templates", "savetemplate", "droptimeline", "textfields", "testtext", "softmask", "pathtext", "gradient", "gradientbucket", "swatches", "swatchpanel", "brushlibrary", "brushcurve", "paintbrush"] { + for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "springbones", "shapebones", "shapeweights", "warp", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple", "library", "librarymenu", "edittransform", "onionsymbol", "layerprops", "frameview", "layercolour", "timelinepolish", "convert", "mixed", "bitmap", "nineslice", "nineslicedit", "find", "explorer", "publish", "publishreport", "publishanim", "start", "drop", "droplibrary", "testmovie", "testmovieinside", "templates", "savetemplate", "droptimeline", "textfields", "testtext", "softmask", "pathtext", "gradient", "gradientbucket", "swatches", "swatchpanel", "brushlibrary", "brushcurve", "paintbrush"] { found.extend(check(panel, |a, _| a.open_panel(Some(panel)))); } // Every panel in front where it docks, and floating (ADR 0075); the other workspaces. diff --git a/src/app.rs b/src/app.rs index 5deceff5..f43e3e6a 100644 --- a/src/app.rs +++ b/src/app.rs @@ -143,7 +143,7 @@ impl Tool { 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), 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::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. Turn on Paint Weights in Properties to brush the bone's influence on, off or smooth, shown as a heat map."), Tool::Warp => tr_noop!("Click a shape or a bitmap to pin it (the first pin covers it with a warp mesh). Drag a pin to bend the artwork around the other pins; with one pin it moves. Click a pin and press Delete to remove it. A pin moved at another frame keys it, and pins tween."), Tool::GradientTransform => tr_noop!("Click a shape with a gradient or bitmap fill to show its handles. Drag the centre to move the fill, the square to change its width, the circle to change its size, the knob to rotate it (Shift: 15° steps) and, on a radial gradient, the triangle to move its focal point. A bitmap fill also has a square for its height and diamonds to skew it. Each drag is one undo step."), Tool::Transform => tr_noop!("Drag a corner or edge to scale (Shift keeps proportions, Alt scales from the centre), just outside a corner to rotate (Shift snaps 15°), inside to move."), @@ -257,6 +257,8 @@ pub enum Drag { 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 }, + /// Bind tool, Paint Weights (ADR 0090): a brush stroke whose last dab was at `last` (stage). + BindPaint { last: 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. @@ -448,6 +450,8 @@ pub struct App { pub open_fill_swatch: bool, /// The bone picked on the stage (ADR 0043; view state). pub bone_sel: Option, + /// The Bind tool's options: Paint Weights, the brush, the focused point (ADR 0090). + pub bind: crate::bind_tool::BindOptions, /// The warp pin picked with the Warp tool, and the artwork it is on (ADR 0079; view state). pub warp_pin: Option<(anicraft_engine::doc::ElementId, anicraft_engine::doc::warp::PinId)>, /// Subselection: the selected motion path anchors, whose handles show (ADR 0030, 0038). @@ -710,6 +714,7 @@ impl App { width_sel: None, open_fill_swatch: false, bone_sel: None, + bind: crate::bind_tool::BindOptions::default(), warp_pin: None, motion_anchors: Vec::new(), motion_drag: None, @@ -2257,6 +2262,47 @@ impl App { self.bone_sel = bones.get(1).copied().map(anicraft_engine::doc::BoneId); self.tool = Tool::Bind; } + Some("shapeweights") => { + // Painted weights (ADR 0090): the tail of `shapebones` at rest, a point added to + // its outline with Subselection, and the second bone's weights mid-stroke with + // the Bind tool's brush, shown as a heat map. + self.run("layer.new", json!({"name": "Tail"})); + // A tapering tail with a point every 20 px along both edges, so the heat map reads. + let half = |x: f32| 40.0 * (1.0 - (x - 220.0) / 700.0) + 4.0; + let mid = |x: f32| 300.0 - 0.00004 * (x - 220.0) * (x - 220.0); + let xs: Vec = (0..=32).map(|i| 220.0 + 20.0 * i as f32).collect(); + let mut d = String::new(); + for (i, x) in xs.iter().enumerate() { + d.push_str(&format!("{}{x} {} ", if i == 0 { "M" } else { "L" }, mid(*x) - half(*x))); + } + for x in xs.iter().rev() { + d.push_str(&format!("L{x} {} ", mid(*x) + half(*x))); + } + d.push('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": [222.0, mid(222.0)], "tail": [380.0, mid(380.0)]})), "bone"); + let mut bones = vec![bone]; + for x in [540.0, 700.0, 850.0] { + bone = id(self.run("bone.add_in_shape", json!({"parent": bone, "tail": [x, mid(x)]})), "bone"); + bones.push(bone); + } + for (b, z) in bones.iter().zip([3, 10, 14, 18]) { + self.run("bone.pose", json!({"bone": b, "angle": z, "frame": 23})); + } + self.run("timeline.goto", json!({"frame": 0})); + self.run("path.add_point", json!({"id": shape, "x": 470.0, "y": mid(470.0) - half(470.0), "slop": 8})); + let b2 = bones.get(1).copied().unwrap_or(0); + self.bone_sel = Some(anicraft_engine::doc::BoneId(b2)); + self.tool = Tool::Bind; + self.bind = crate::bind_tool::BindOptions { paint: true, radius: 55.0, strength: 35.0, point: Some(14), preview: Some(anicraft_engine::geom::Vec2::new(500.0, mid(500.0) - 20.0)), ..Default::default() }; + // A stroke along the top edge, still under way. + self.s.begin_gesture(tr_noop!("Paint Weights")); + let at: Vec<[f32; 2]> = (0..25).map(|i| 300.0 + 8.0 * i as f32).map(|x| [x, mid(x) - 20.0]).collect(); + self.run("bone.paint_weights", json!({"bone": b2, "at": at, "radius": 55, "strength": 35})); + } 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 index 80dc5215..fb58ed47 100644 --- a/src/bind_tool.rs +++ b/src/bind_tool.rs @@ -1,4 +1,5 @@ -//! The Bind tool (ADR 0071): which points of a shape follow which of its bones. +//! The Bind tool (ADR 0071, ADR 0090): which points of a shape follow which of its bones, and +//! how much. //! //! 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). @@ -6,28 +7,93 @@ //! 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. +//! +//! **Paint Weights** (Properties › Bone, or the tool's options) turns the pointer into a brush +//! (ADR 0090): dragging over the shape raises (Add), lowers (Subtract) or evens out (Smooth) the +//! picked bone's share of the points under it, with a soft falloff to the brush's rim. The points +//! show as a heat map of that share (blue none, red all) and the outline between them in the +//! same colours, live as the stroke goes. A stroke is one gesture, so one undo step; `[` and `]` +//! change the brush size. A point clicked or painted becomes the *focused* point, whose exact +//! share Properties › Bone shows and edits as a number (for the keyboard, `bone.set_weight`). -use crate::app::{App, Drag}; +use crate::app::{App, Drag, Tool}; 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 anicraft_engine::doc::weights::Brush; +use anicraft_engine::doc::{BoneId, ElementKind, LayerId, LayerKind, evaluate_layer_elements}; +use anicraft_engine::geom::{PathCmd, 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; +/// Brush size limits (px on the stage). +pub const RADIUS_MIN: f32 = 1.0; +pub const RADIUS_MAX: f32 = 500.0; +/// Most dabs one pointer move sends (a fast flick across the stage). +const MOST_DABS: usize = 256; + +/// The Bind tool's options (view state, kept for the session). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct BindOptions { + /// Paint weights instead of binding points by clicks and boxes. + pub paint: bool, + pub brush: Brush, + /// The brush's radius on the stage (px). + pub radius: f32, + /// Its strength at the centre, 0–100. + pub strength: f32, + /// The point whose weights Properties shows and edits (index into the shape's points). + pub point: Option, + /// Where the brush shows (stage) while no pointer is over the stage: the screenshot's. + pub preview: Option, +} + +impl Default for BindOptions { + fn default() -> Self { + BindOptions { paint: false, brush: Brush::Add, radius: 20.0, strength: 25.0, point: None, preview: None } + } +} + +/// A brush's label and hint, for Properties. +pub fn brush_label(b: Brush) -> (&'static str, &'static str) { + match b { + Brush::Add => (tr_noop!("Add"), tr_noop!("Raises how much the bone moves the points under the brush")), + Brush::Subtract => (tr_noop!("Subtract"), tr_noop!("Lowers how much the bone moves the points under the brush; their other bones take up the rest")), + Brush::Smooth => (tr_noop!("Smooth"), tr_noop!("Evens out the bone's share across the points under the brush, softening a hard edge between bones")), + } +} /// 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)>, + /// Stage position, the bones it follows with their weights. + points: Vec<(Vec2, Vec<(BoneId, f32)>)>, + /// The outline on the stage: per segment, its points (flattened) and the anchors it joins. + outline: Vec<(Vec, usize, usize)>, +} + +/// A few points along a segment from `a` (and its controls) to its end, for drawing. +fn along(cmd: &PathCmd, a: Vec2) -> Vec { + const N: usize = 8; + let lerp = |p: Vec2, q: Vec2, t: f32| p + (q - p) * t; + match *cmd { + PathCmd::LineTo(b) => vec![a, b], + PathCmd::QuadTo(c, b) => (0..=N).map(|i| i as f32 / N as f32).map(|t| lerp(lerp(a, c, t), lerp(c, b, t), t)).collect(), + PathCmd::CubicTo(c1, c2, b) => (0..=N) + .map(|i| i as f32 / N as f32) + .map(|t| { + let (p, q, r) = (lerp(a, c1, t), lerp(c1, c2, t), lerp(c2, b, t)); + lerp(lerp(p, q, t), lerp(q, r, t), t) + }) + .collect(), + PathCmd::MoveTo(_) | PathCmd::Close => Vec::new(), + } } fn shown(app: &App) -> Vec { @@ -41,8 +107,35 @@ fn shown(app: &App) -> Vec { 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 }) + let points = at.into_iter().zip(&skin.points).map(|(p, b)| (p, b.bones.iter().map(|i| (i.0, i.1)).collect())).collect(); + // The outline as it shows, segment by segment, with the anchors at its ends. + let mut outline = Vec::new(); + if let Some(e) = els.iter().find(|e| e.id == skin.shape) + && let ElementKind::Shape(sh) = &e.kind + { + let (mut idx, mut start, mut last, mut start_idx) = (0usize, Vec2::ZERO, Vec2::ZERO, 0usize); + for c in &sh.path.cmds { + match *c { + PathCmd::MoveTo(p) => { + (start, last, start_idx) = (p, p, idx); + idx += 1; + } + PathCmd::Close => { + if last != start { + outline.push((vec![e.transform.apply(last), e.transform.apply(start)], idx.saturating_sub(1), start_idx)); + } + last = start; + } + PathCmd::LineTo(p) | PathCmd::QuadTo(_, p) | PathCmd::CubicTo(_, _, p) => { + let pts = along(c, last).into_iter().map(|q| e.transform.apply(q)).collect(); + outline.push((pts, idx.saturating_sub(1), idx)); + last = p; + idx += 1; + } + } + } + } + Some(Points { layer: l.id, color: to_color32(l.color), locked: l.locked || tl.locked_by_folder(l.id), points, outline }) }) .collect() } @@ -65,6 +158,12 @@ fn picked_in(app: &App, layer: LayerId) -> Option { app.s.timeline().layer(layer)?.armature.as_ref().filter(|a| a.skin.is_some() && a.bone(id).is_some()).map(|_| id) } +/// The picked bone when it is inside a shape (any layer). +fn picked_shape_bone(app: &App) -> Option { + let id = app.bone_sel?; + app.s.timeline().layers.iter().any(|l| l.armature.as_ref().is_some_and(|a| a.skin.is_some() && a.bone(id).is_some())).then_some(id) +} + fn bind(app: &mut App, bone: BoneId, points: Vec, shift: bool, command: bool) { let n = points.len(); let m = mode(shift, command); @@ -79,35 +178,105 @@ fn bind(app: &mut App, bone: BoneId, points: Vec, shift: bool, command: b } } +/// The nearest unlocked shape point within grabbing reach of screen point `p`: its layer and index. +fn point_at(app: &App, xf: Xf, p: Pos2) -> Option<(LayerId, usize)> { + shown(app).into_iter().rev().filter(|s| !s.locked).find_map(|s| s.points.iter().position(|(at, _)| xf.to_screen(*at).distance(p) <= GRAB).map(|i| (s.layer, i))) +} + +/// Sends dabs at stage points `at` with the brush in hand (inside the stroke's gesture). +fn dab(app: &mut App, bone: BoneId, at: &[Vec2]) { + if at.is_empty() { + return; + } + let o = app.bind; + let pts: Vec<[f32; 2]> = at.iter().map(|p| [p.x, p.y]).collect(); + app.run("bone.paint_weights", json!({"bone": bone.0, "at": pts, "radius": o.radius, "strength": o.strength, "mode": o.brush.key()})); +} + /// A Bind tool click at screen point `p`: picks the bone there, or binds the point there to the -/// picked bone. +/// picked bone (with Paint Weights on, paints one dab there instead). 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), + let hit = point_at(app, xf, p); + if app.bind.paint { + let Some(bone) = picked_shape_bone(app) else { + app.status_ok(tr!("Pick a bone of a shape first (click it), then paint its weights.")); + return; + }; + if let Some((_, i)) = hit { + app.bind.point = Some(i); + } + app.s.begin_gesture(tr_noop!("Paint Weights")); + dab(app, bone, &[xf.to_stage(p)]); + app.s.end_gesture(); + return; + } + if let Some((layer, i)) = hit { + match picked_in(app, layer) { + Some(bone) => { + app.bind.point = Some(i); + 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; + app.bind.point = 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). +/// that starts on a bone or a point does nothing more than a click), or with Paint Weights on a +/// brush stroke. 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.")); + app.status_ok(if app.bind.paint { tr!("Pick a bone of a shape first (click it), then paint its weights.") } else { tr!("Pick a bone of a shape first (click it), then drag a box around the points it should move.") }); return Drag::None; } + if app.bind.paint { + let Some(bone) = picked_shape_bone(app) else { return Drag::None }; + // One stroke, one undo step. + app.s.begin_gesture(tr_noop!("Paint Weights")); + dab(app, bone, &[sp]); + return Drag::BindPaint { last: pos2(sp.x, sp.y) }; + } Drag::BindMarquee { start: pos2(sp.x, sp.y), cur: pos2(sp.x, sp.y) } } +/// The brush stroke reaching stage point `cur` from `last`: a dab every quarter of the brush's +/// radius along the way, so a stroke paints alike however fast the pointer moves. Returns where +/// the last dab went. +pub fn paint_to(app: &mut App, last: Pos2, cur: Pos2) -> Pos2 { + let Some(bone) = picked_shape_bone(app) else { return last }; + let spacing = (app.bind.radius * 0.25).max(0.5); + let (a, b) = (Vec2::new(last.x, last.y), Vec2::new(cur.x, cur.y)); + let d = a.distance(b); + if d.is_nan() || d < spacing { + return last; + } + let dir = (b - a) * (1.0 / d); + let n = ((d / spacing) as usize).min(MOST_DABS); + let at: Vec = (1..=n).map(|k| a + dir * (spacing * k as f32)).collect(); + let end = at.last().copied().unwrap_or(a); + dab(app, bone, &at); + pos2(end.x, end.y) +} + +/// Ends a brush stroke: one undo step, and a hint. +pub fn paint_end(app: &mut App) { + app.s.end_gesture(); + if let Some(bone) = picked_shape_bone(app) { + let n = app.s.timeline().layers.iter().find_map(|l| l.armature.as_ref().and_then(|a| a.skin.as_ref()).filter(|_| l.armature.as_ref().is_some_and(|a| a.bone(bone).is_some())).map(|k| k.points.iter().filter(|b| b.weight(bone) > 0.0).count())); + if let Some(n) = n { + app.status_ok(trn!("The bone moves {n} point. {undo} to undo the stroke.", "The bone moves {n} points. {undo} to undo the stroke.", n, undo = app.undo_key())); + } + } +} + /// 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); @@ -123,28 +292,54 @@ pub fn drag_end(app: &mut App, start: Pos2, cur: Pos2, shift: bool, command: boo } } -/// Every shape armature's points (with the Bind tool in hand), and the box being dragged. +/// Every shape armature's points (with the Bind tool in hand), and the box being dragged; with +/// Paint Weights on, the picked bone's weights as a heat map and the brush under the pointer. pub fn draw(app: &App, painter: &egui::Painter, xf: Xf) { - if app.tool != crate::app::Tool::Bind { + if app.tool != 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 (true, Some(bone)) = (app.bind.paint, picked) { + let w = |i: usize| s.points.get(i).and_then(|(_, b)| b.iter().find(|x| x.0 == bone)).map_or(0.0, |x| x.1); + // The outline, each segment blending the heat of the anchors it joins. + for (pts, a, b) in &s.outline { + let n = pts.len().saturating_sub(1).max(1) as f32; + for (k, seg) in pts.windows(2).enumerate() { + if let [p, q] = seg { + let t = (k as f32 + 0.5) / n; + let c = crate::theme::heat(w(*a) * (1.0 - t) + w(*b) * t); + painter.line_segment([xf.to_screen(*p), xf.to_screen(*q)], Stroke::new(3.0, fade(c))); + } + } } + for (i, (at, _)) in s.points.iter().enumerate() { + let c = xf.to_screen(*at); + painter.circle(c, SIZE + 0.5, fade(crate::theme::heat(w(i))), Stroke::new(1.0, fade(T.ink))); + } + } else { + for (at, bones) in &s.points { + let c = xf.to_screen(*at); + let mine = picked.is_some_and(|b| bones.iter().any(|x| x.0 == 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); + } + } + } + // The focused point (its weights are in Properties), ringed. + if picked.is_some() + && let Some((at, _)) = app.bind.point.and_then(|i| s.points.get(i)) + { + painter.circle_stroke(xf.to_screen(*at), SIZE + 4.0, Stroke::new(1.5, T.selection)); } } if let Drag::BindMarquee { start, cur } = app.drag { @@ -152,4 +347,71 @@ pub fn draw(app: &App, painter: &egui::Painter, xf: Xf) { 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); } + // The brush: its reach, and a dot where its strength is full. + let stroke_at = match app.drag { + Drag::BindPaint { last } => Some(xf.to_screen(Vec2::new(last.x, last.y))), + _ => app.bind.preview.map(|p| xf.to_screen(p)), + }; + if app.bind.paint + && let Some(p) = painter.ctx().pointer_hover_pos().filter(|p| painter.clip_rect().contains(*p)).or(stroke_at) + { + let r = app.bind.radius * xf.zoom; + painter.circle_stroke(p, r, Stroke::new(1.5, T.ink)); + painter.circle_stroke(p, r, Stroke::new(0.75, Color32::WHITE)); + painter.circle_filled(p, 1.5, T.selection); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use anicraft_engine::Session; + use anicraft_engine::doc::Document; + + /// An app with the `shapeweights` tail: its second bone picked, Paint Weights on. + fn app() -> (App, BoneId) { + let ctx = egui::Context::default(); + let mut app = App::with_context(&ctx, Session::new(Document::default()), Some(std::path::PathBuf::from("unused.png"))); + app.open_panel(Some("shapeweights")); + app.s.end_gesture(); + app.drag = Drag::None; + let bone = app.bone_sel.expect("a picked bone"); + (app, bone) + } + + fn weights(app: &App, bone: BoneId) -> Vec { + app.s.timeline().layers.iter().find_map(|l| l.armature.as_ref().and_then(|a| a.skin.as_ref())).map(|k| k.points.iter().map(|b| b.weight(bone)).collect()).unwrap_or_default() + } + + #[test] + fn a_stroke_dabs_every_quarter_radius_and_undoes_in_one_step() { + let (mut app, bone) = app(); + app.bind.radius = 40.0; + let before = weights(&app, bone); + let undo = app.s.undo_label().map(str::to_string); + app.s.begin_gesture("Paint Weights"); + // Less than a quarter of the radius: no dab yet, and the stroke stays where it was. + let last = paint_to(&mut app, pos2(600.0, 280.0), pos2(605.0, 280.0)); + assert_eq!(last, pos2(600.0, 280.0)); + assert_eq!(weights(&app, bone), before); + // 45 px: four dabs 10 px apart, the stroke at the fourth. + let last = paint_to(&mut app, last, pos2(645.0, 280.0)); + assert_eq!(last, pos2(640.0, 280.0)); + paint_end(&mut app); + assert_ne!(weights(&app, bone), before); + assert_eq!(app.s.undo_label(), Some("Paint Weights")); + app.s.undo().expect("undo"); + assert_eq!(weights(&app, bone), before); + assert_eq!(app.s.undo_label().map(str::to_string), undo); + } + + #[test] + fn heat_runs_from_blue_to_red() { + use crate::theme::{HEAT, heat}; + assert_eq!(heat(0.0), HEAT[0]); + assert_eq!(heat(1.0), HEAT[4]); + assert_eq!(heat(0.5), HEAT[2]); + assert_eq!(heat(f32::NAN), HEAT[0]); + assert_eq!(heat(7.0), HEAT[4]); + } } diff --git a/src/brushtool.rs b/src/brushtool.rs index 6fe6a80a..8e1ddb7a 100644 --- a/src/brushtool.rs +++ b/src/brushtool.rs @@ -163,6 +163,11 @@ pub fn resize(app: &mut App, larger: bool) { app.eraser.size = step_size(app.eraser.size, larger); app.status_ok(tr!("Eraser size {size} px", size = app.eraser.size)); } + // Painting weights (ADR 0090). + Tool::Bind if app.bind.paint => { + app.bind.radius = step_size(app.bind.radius, larger).clamp(crate::bind_tool::RADIUS_MIN, crate::bind_tool::RADIUS_MAX); + app.status_ok(tr!("Brush size {size} px", size = app.bind.radius)); + } _ => {} } } diff --git a/src/i18n/tests.rs b/src/i18n/tests.rs index 3c66432c..df80706d 100644 --- a/src/i18n/tests.rs +++ b/src/i18n/tests.rs @@ -599,7 +599,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", "springbones", "shapebones", "warp", "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", "springbones", "shapebones", "shapeweights", "warp", "motion", "motionpins", "actions", "script", "prefs", "envelope", "onionmenu", "editmultiple", "edittransform", "onionsymbol", "find", "explorer", "publish", "publishreport", "publishanim", "start", "testmovie", "testmovieinside", "templates", "savetemplate", "brushlibrary", "brushcurve"] { found.extend(click_everything(panel, |a, _| a.open_panel(Some(panel)))); } // Test Movie in a window of its own (ADR 0062; egui stands in for the window system here). diff --git a/src/main.rs b/src/main.rs index 0cc42e1e..7915f985 100644 --- a/src/main.rs +++ b/src/main.rs @@ -263,7 +263,7 @@ fn parse_args(args: impl IntoIterator) -> Result { /// `--help` (the console's text, in English). #[cfg(not(target_arch = "wasm32"))] // i18n-exempt: the --help console text -const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png [--shot-width ]] [--renderer gl|wgpu|vulkan|dx12|metal] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--open palette|shortcuts|lastscene|start|drop|droplibrary|select|selectzoom|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|rulers|editguides|editgrid|symboledit|groups|combine|nineslice|nineslicedit|brush|brushing|polystar|paintinside|drawingedit|shapeenvelope|brushlibrary|brushcurve|paintbrush|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|bones|springbones|shapebones|layerdepth|layerdepthview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testmovieinside|testscript|textfields|testtext|softmask|pathtext|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|ease|easepreset|plugineases|pluginexport|pluginexportwindow|library|librarymenu|libraryfolders|colour|layerprops|frameview|layercolour|timelinepolish|dock|dockicons|floattabs|docknarrow|workspaces|animator|designer|gradient|gradientbucket|swatches|swatchpanel]\n\ +const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png [--shot-width ]] [--renderer gl|wgpu|vulkan|dx12|metal] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--open palette|shortcuts|lastscene|start|drop|droplibrary|select|selectzoom|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|rulers|editguides|editgrid|symboledit|groups|combine|nineslice|nineslicedit|brush|brushing|polystar|paintinside|drawingedit|shapeenvelope|brushlibrary|brushcurve|paintbrush|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|bones|springbones|shapebones|shapeweights|layerdepth|layerdepthview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testmovieinside|testscript|textfields|testtext|softmask|pathtext|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|ease|easepreset|plugineases|pluginexport|pluginexportwindow|library|librarymenu|libraryfolders|colour|layerprops|frameview|layercolour|timelinepolish|dock|dockicons|floattabs|docknarrow|workspaces|animator|designer|gradient|gradientbucket|swatches|swatchpanel]\n\ --renderer the window's graphics (also ANICRAFT_RENDERER); default automatic, falling back to OpenGL\n\ --open shows a panel at start (handy with --screenshot for visual checks)\n\ --shot-width scales the screenshot down to this width (the user guide's pictures)\n\ diff --git a/src/panels.rs b/src/panels.rs index 6de60760..f1c6b95e 100644 --- a/src/panels.rs +++ b/src/panels.rs @@ -2121,6 +2121,7 @@ fn bone_props(app: &mut App, ui: &mut egui::Ui, id: anicraft_engine::doc::BoneId 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")); }); + bind_props(app, ui, id, &layer, total); } ui.horizontal_wrapped(|ui| { if skin.is_some() { @@ -2139,6 +2140,65 @@ fn bone_props(app: &mut App, ui: &mut egui::Ui, id: anicraft_engine::doc::BoneId 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.") })); } +/// A shape bone's weights (ADR 0090): with the Bind tool, Paint Weights and its brush; always, the +/// focused point's share of the bone as a number (keyboard users edit weights here) and the bones +/// the point follows. +fn bind_props(app: &mut App, ui: &mut egui::Ui, id: anicraft_engine::doc::BoneId, layer: &anicraft_engine::doc::Layer, total: usize) { + use crate::bind_tool::{RADIUS_MAX, RADIUS_MIN, brush_label}; + use anicraft_engine::doc::weights::Brush; + if app.tool == Tool::Bind { + let keys = [app.keymap.primary("view.brush_smaller"), app.keymap.primary("view.brush_larger")].into_iter().flatten().map(crate::platform::shortcut_label).collect::>().join(" / "); + let o = &mut app.bind; + row_prose(ui, tr!("Weights"), |ui| { + crate::theme::checkbox(ui, &mut o.paint, tr!("Paint Weights")).on_hover_text(tr!("Drag over the shape to brush this bone's influence onto its points, shown as a heat map: blue none, red all. Off: click or box points to bind them")); + }); + if o.paint { + row(ui, tr!("Brush"), |ui| { + for b in [Brush::Add, Brush::Subtract, Brush::Smooth] { + let (label, hint) = brush_label(b); + ui.selectable_value(&mut o.brush, b, crate::i18n::t(label)).on_hover_text(crate::i18n::t(hint)); + } + }); + row(ui, tr!("Size"), |ui| { + let r = ui.add(egui::DragValue::new(&mut o.radius).suffix(" px").speed(0.25).range(RADIUS_MIN..=RADIUS_MAX).max_decimals(1)).named(tr!("Weight brush size")); + if !keys.is_empty() { + r.on_hover_text(tr!("The brush's radius on the stage ({keys})", keys = keys)); + } + }); + row(ui, tr!("Strength"), |ui| { + ui.add(egui::DragValue::new(&mut o.strength).speed(0.5).range(1.0..=100.0).max_decimals(0)).named(tr!("Weight brush strength")).on_hover_text(tr!("How much one dab changes the weights at the brush's centre, 1 to 100; it fades to nothing at the rim")); + }); + } + } + if total == 0 { + return; + } + let point = app.bind.point.unwrap_or(0).min(total - 1); + let mut shown = point + 1; + row(ui, tr!("Point"), |ui| { + let r = ui.add(egui::DragValue::new(&mut shown).speed(0.1).range(1..=total)).named(tr!("Focused point")).on_hover_text(tr!("The point whose weights show below (ringed on the stage). Click one with the Bind tool, or type its number")); + if r.changed() { + app.bind.point = Some(shown.saturating_sub(1).min(total - 1)); + } + }); + let arm = layer.armature.as_ref(); + let binding = arm.and_then(|a| a.skin.as_ref()).and_then(|k| k.points.get(point)).cloned().unwrap_or_default(); + let mut w = binding.weight(id) * 100.0; + row(ui, tr!("Weight"), |ui| { + let r = ui.add(egui::DragValue::new(&mut w).suffix(" %").speed(0.5).range(0.0..=100.0).max_decimals(1)).named(tr!("Bone weight at the point")); + if r.on_hover_text(tr!("How much this bone moves the point, 0 to 100 %; the point's other bones share the rest")).changed() { + app.bind.point = Some(point); + live(app, tr_noop!("Set Point Weight"), "bone.set_weight", json!({"bone": id.0, "points": [point], "weight": w})); + } + }); + let name = |b: anicraft_engine::doc::BoneId| arm.and_then(|a| a.bone(b)).map(|x| x.name.clone()).filter(|n| !n.is_empty()).unwrap_or_else(|| format!("#{}", b.0)); + // Names and numbers are data; the note for an unbound point is prose. + let follows = if binding.bones.is_empty() { text(Type::Body, tr!("No bone: the point stays where it was drawn")) } else { text(Type::Data, binding.bones.iter().map(|i| format!("{} {:.0} %", name(i.0), i.1 * 100.0)).collect::>().join(" · ")) }; + row(ui, tr!("Follows"), |ui| { + ui.label(follows).on_hover_text(tr!("The bones that move the point, and their shares")); + }); +} + fn document_props(app: &mut App, ui: &mut egui::Ui) { { let st = app.s.doc.stage; diff --git a/src/stage.rs b/src/stage.rs index 8936b32a..b19c2f5a 100644 --- a/src/stage.rs +++ b/src/stage.rs @@ -628,6 +628,13 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { } } (Drag::PointMarquee { cur: m, .. } | Drag::BindMarquee { cur: m, .. }, Some(c)) => *m = c, + (Drag::BindPaint { last }, Some(c)) => { + let from = *last; + let to = crate::bind_tool::paint_to(app, from, c); + if let Drag::BindPaint { last } = &mut app.drag { + *last = to; + } + } (Drag::WarpPin { element, pin }, Some(c)) => { let (element, pin) = (*element, *pin); crate::warp_tool::drag_to(app, element, pin, c); @@ -669,6 +676,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { 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::BindPaint { .. } => crate::bind_tool::paint_end(app), Drag::Pencil => crate::pathtools::commit_pencil(app, xf), Drag::Brush => crate::brushtool::commit(app, xf), Drag::Eraser => crate::erasertool::commit(app, xf), diff --git a/src/theme.rs b/src/theme.rs index 28750415..429c9c22 100644 --- a/src/theme.rs +++ b/src/theme.rs @@ -827,6 +827,21 @@ pub fn to_rgba(c: Color32) -> anicraft_engine::doc::Rgba { anicraft_engine::doc::Rgba::new(f32::from(r) / 255.0, f32::from(g) / 255.0, f32::from(b) / 255.0, f32::from(a) / 255.0) } +/// The heat map of a bone's weights (ADR 0090), the same in every palette because it is drawn +/// over artwork: blue (none) through cyan, green and yellow to red (all of the point). +pub const HEAT: [Color32; 5] = [Color32::from_rgb(0x2b, 0x4c, 0xd9), Color32::from_rgb(0x1f, 0xb5, 0xd6), Color32::from_rgb(0x2f, 0xc2, 0x5a), Color32::from_rgb(0xf2, 0xd0, 0x2a), Color32::from_rgb(0xe8, 0x3a, 0x2a)]; + +/// The colour of weight `w` (0…1) on [`HEAT`], blended between its stops. +pub fn heat(w: f32) -> Color32 { + let w = if w.is_finite() { w.clamp(0.0, 1.0) } else { 0.0 }; + let x = w * (HEAT.len() - 1) as f32; + let i = (x as usize).min(HEAT.len() - 2); + let t = x - i as f32; + let (a, b) = (HEAT.get(i).copied().unwrap_or(Color32::BLACK), HEAT.get(i + 1).copied().unwrap_or(Color32::BLACK)); + let mix = |p: u8, q: u8| (f32::from(p) + (f32::from(q) - f32::from(p)) * t).round().clamp(0.0, 255.0) as u8; + Color32::from_rgb(mix(a.r(), b.r()), mix(a.g(), b.g()), mix(a.b(), b.b())) +} + pub fn to_color32(c: anicraft_engine::doc::Rgba) -> Color32 { let c = c.sanitized(); Color32::from_rgba_unmultiplied((c.r * 255.0).round() as u8, (c.g * 255.0).round() as u8, (c.b * 255.0).round() as u8, (c.a * 255.0).round() as u8)