diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index eaca5026..95ac7731 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -19,7 +19,7 @@ shaders or SDK code). | Hack Regular (via `epaint_default_fonts`) | UI monospace font | Source Foundry Authors; Bitstream (Vera) | | MIT + Bitstream Vera licence, [`licenses/fonts/LICENSE-Hack.txt`](licenses/fonts/LICENSE-Hack.txt) | | Noto Emoji (via `epaint_default_fonts`) | Symbol fallback | Google | | SIL OFL 1.1, [`licenses/fonts/OFL-1.1-NotoEmoji.txt`](licenses/fonts/OFL-1.1-NotoEmoji.txt) | | emoji-icon-font (via `epaint_default_fonts`) | Symbol fallback | John Slegers | | MIT, [`licenses/fonts/LICENSE-emoji-icon-font.txt`](licenses/fonts/LICENSE-emoji-icon-font.txt) | -| `assets/icons/anicraft-*.svg` (17 files: align, distribute, mask and masked layer, width tool, camera, brush, eraser, eyedropper, muted sound, magnet) | Align panel, layer-type, Width tool, Camera, Brush, Eraser and Eyedropper tool icons, the timeline's mute toggle, Snap to Objects | AniCraft contributors | Original work, drawn on Lucide's 24-unit grid and stroke style (the muted sound keeps the speaker of Lucide's `volume-2`, ISC, crossed out) | MIT OR Apache-2.0 | +| `assets/icons/anicraft-*.svg` (18 files: align, distribute, mask and masked layer, width tool, camera, brush, eraser, eyedropper, muted sound, magnet, bone) | Align panel, layer-type, Width tool, Camera, Brush, Eraser, Eyedropper and Bone tool icons, the timeline's mute toggle, Snap to Objects | AniCraft contributors | Original work, drawn on Lucide's 24-unit grid and stroke style (the muted sound keeps the speaker of Lucide's `volume-2`, ISC, crossed out) | MIT OR Apache-2.0 | | `crates/svg/fixtures/clips-masks-text.svg` | SVG import test drawing (clip paths, a mask, text) | AniCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/*.svg` except `anicraft-*` (33 files: tools, transport, layer toggles, folders, guide, image, text, sound, chevrons) | UI icons, stroked by `src/icons.rs` | Lucide Icons and Contributors (some derived from Feather by Cole Bemis) | (`icons/.svg`), copied unchanged from the PhotoCraft sibling project's set (`volume-2.svg` from Lucide 0.512.0) | ISC (Lucide) and MIT (Feather), [`licenses/icons/LICENSE-lucide.txt`](licenses/icons/LICENSE-lucide.txt) | | `assets/app-icon/` (`anicraft.svg`, `anicraft-small.svg` and every render: PNGs, `anicraft.ico`, `hicolor/`) | App icon (engraved rabbit): window, Dock, taskbar, `anicraft.exe`, Help › About | Project owner (ArtCraft team) | Original artwork drawn in ArtCraft for AniCraft, vectorised by `assets/app-icon/trace.py` and rendered by `scripts/icons.sh` | MIT OR Apache-2.0 ([`assets/app-icon/LICENSE.txt`](assets/app-icon/LICENSE.txt)) | diff --git a/assets/icons/anicraft-bone.svg b/assets/icons/anicraft-bone.svg new file mode 100644 index 00000000..f0cb8553 --- /dev/null +++ b/assets/icons/anicraft-bone.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/crates/doc/src/armature.rs b/crates/doc/src/armature.rs new file mode 100644 index 00000000..4850c090 --- /dev/null +++ b/crates/doc/src/armature.rs @@ -0,0 +1,462 @@ +//! Armatures (ADR 0043): bones that join symbol instances on an armature layer, poses that +//! turn them, and inverse kinematics that finds a pose from a dragged bone end. +//! +//! An armature is a tree of [`Bone`]s on a [`LayerKind::Armature`](crate::LayerKind) layer. +//! Each bone starts at a **joint** on its *parent* instance (its head) and ends on its *child* +//! instance (its tail); the child turns about the joint, carrying everything below it. An +//! instance is the child of at most one bone, and the instance no bone ends in is the root: it +//! keeps its own transform, so moving it moves the whole armature. +//! +//! A **pose** is a joint angle per bone ([`Pose`]), stored on each keyframe of the armature +//! layer and tweened between keyframes with the keyframe's easing. Angles are relative: 0 is the +//! bone as it was drawn, measured against its parent, so turning a parent carries its children. +//! Forward kinematics ([`place`]) turns a pose into the instances' transforms; it is pure, and +//! [`crate::evaluate_layer_elements`] applies it, so every renderer, export and the player see +//! the posed instances. +//! +//! Inverse kinematics ([`solve`]) is cyclic coordinate descent (CCD): sweeping from the dragged +//! bone up its chain, each joint turns so the effector points at the target, clamped to the +//! joint's limits. It works on joint angles directly, so limits are a clamp per step and the +//! result is a pose by construction. + +use crate::{Element, ElementId, Keyframe, Layer}; +use anicraft_geom::{Affine, Vec2}; +use serde::{Deserialize, Serialize}; +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; + +/// Most bones in one armature. +pub const MAX_BONES: usize = 256; +/// Longest bone name kept (bytes). +pub const MAX_NAME: usize = 256; +/// Joint limits stay within a turn either way (radians). +pub const MAX_LIMIT: f32 = std::f32::consts::TAU; +/// Largest joint angle kept (radians): many turns, never infinity. +pub const MAX_ANGLE: f32 = 64.0 * std::f32::consts::TAU; +/// IK stops once the effector is this close to its target (layer units, pixels). +pub const IK_TOLERANCE: f32 = 0.01; +/// Most CCD sweeps one solve takes. +pub const IK_SWEEPS: usize = 256; + +/// Unique id of a bone within a document (from the document's id counter). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +pub struct BoneId(pub u64); + +/// How far a joint may turn either way from where the bone was drawn (radians, `min ≤ 0 ≤ max` +/// is usual but not required). +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct Limits { + pub min: f32, + pub max: f32, +} + +impl Limits { + /// `a` kept inside the limits. + pub fn clamp(&self, a: f32) -> f32 { + a.clamp(self.min, self.max) + } + + /// Finite, ordered and within [`MAX_LIMIT`]; `None` when nothing sane is left. + pub fn sanitized(self) -> Option { + if !(self.min.is_finite() && self.max.is_finite()) { + return None; + } + let (a, b) = (self.min.clamp(-MAX_LIMIT, MAX_LIMIT), self.max.clamp(-MAX_LIMIT, MAX_LIMIT)); + Some(Limits { min: a.min(b), max: a.max(b) }) + } +} + +/// A bone: from a joint on its parent instance to its child instance, which it turns. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Bone { + pub id: BoneId, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub name: String, + /// The instance the bone starts on (the joint is a point on it). + pub parent: ElementId, + /// The instance the bone moves. + pub child: ElementId, + /// The joint, in the parent instance's local space: the child turns about it. + pub head: Vec2, + /// The bone's end, in the child instance's local space (where a drag pulls it). + pub tail: Vec2, + /// The child's transform in the parent's local space at joint angle 0 (as it was drawn). + pub rest: Affine, + /// How far the joint may turn; `None`: freely. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub limits: Option, + /// Pinned: inverse kinematics never turns it (nor the bones it hangs from), so its end stays + /// where it is while the rest of the armature follows a drag. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub pinned: bool, +} + +impl Bone { + /// `a` as this joint allows it (finite, within its limits). + pub fn allow(&self, a: f32) -> f32 { + let a = if a.is_finite() { a.clamp(-MAX_ANGLE, MAX_ANGLE) } else { 0.0 }; + self.limits.map_or(a, |l| l.clamp(a)) + } + + fn is_sane(&self) -> bool { + self.parent != self.child && self.head.x.is_finite() && self.head.y.is_finite() && self.tail.x.is_finite() && self.tail.y.is_finite() && self.rest.is_finite() && self.rest.inverse().is_some() + } +} + +/// The bones of an armature layer, each listed after the bone it hangs from. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct Armature { + #[serde(default)] + pub bones: Vec, +} + +impl Armature { + pub fn is_empty(&self) -> bool { + self.bones.is_empty() + } + + pub fn bone(&self, id: BoneId) -> Option<&Bone> { + self.bones.iter().find(|b| b.id == id) + } + + pub fn bone_mut(&mut self, id: BoneId) -> Option<&mut Bone> { + self.bones.iter_mut().find(|b| b.id == id) + } + + /// The bone that moves instance `el` (ends in it), if any. + pub fn bone_into(&self, el: ElementId) -> Option<&Bone> { + self.bones.iter().find(|b| b.child == el) + } + + /// The bone `b` hangs from: the one that moves its parent instance. + pub fn parent_bone(&self, b: &Bone) -> Option<&Bone> { + self.bone_into(b.parent) + } + + /// Whether instance `el` is part of the armature. + pub fn contains(&self, el: ElementId) -> bool { + self.bones.iter().any(|b| b.parent == el || b.child == el) + } + + /// Every instance in the armature, roots first. + pub fn members(&self) -> Vec { + let mut out: Vec = self.roots(); + for b in &self.bones { + if !out.contains(&b.child) { + out.push(b.child); + } + } + out + } + + /// The instances no bone moves (one for an armature made with the Bone tool). + pub fn roots(&self) -> Vec { + let mut out = Vec::new(); + for b in &self.bones { + if self.bone_into(b.parent).is_none() && !out.contains(&b.parent) { + out.push(b.parent); + } + } + out + } + + /// Bone `id` and every bone below it, in armature order. + pub fn subtree(&self, id: BoneId) -> Vec { + let mut inside: HashSet = HashSet::new(); + let mut out = Vec::new(); + for b in &self.bones { + if b.id == id || inside.contains(&b.parent) { + inside.insert(b.child); + out.push(b.id); + } + } + out + } + + /// The chain from bone `id` up to its root, `id` first (bounded by the bone count). + pub fn chain(&self, id: BoneId) -> Vec<&Bone> { + let mut out = Vec::new(); + let mut cur = self.bone(id); + while let Some(b) = cur { + if out.len() >= self.bones.len() || out.iter().any(|o: &&Bone| o.id == b.id) { + break; + } + out.push(b); + cur = self.parent_bone(b); + } + out + } + + /// Repairs a loaded armature: drops bones with non-finite numbers, repeated ids, a second + /// bone into one instance and bones in cycles; keeps every bone after its parent; keeps at + /// most [`MAX_BONES`]. Returns whether anything changed. + pub fn sanitize(&mut self) -> bool { + let before = self.bones.clone(); + let mut seen_id = HashSet::new(); + let mut seen_child = HashSet::new(); + let mut kept: Vec = Vec::new(); + for mut b in std::mem::take(&mut self.bones) { + if !b.is_sane() || !seen_id.insert(b.id) || !seen_child.insert(b.child) { + continue; + } + b.limits = b.limits.and_then(Limits::sanitized); + if b.name.len() > MAX_NAME { + let cut = (0..=MAX_NAME).rev().find(|&i| b.name.is_char_boundary(i)).unwrap_or(0); + b.name.truncate(cut); + } + kept.push(b); + } + // Order: a bone after the bone moving its parent. What never gets placed is a cycle. + let children: HashSet = kept.iter().map(|b| b.child).collect(); + let mut placed: HashSet = kept.iter().map(|b| b.parent).filter(|p| !children.contains(p)).collect(); + let mut ordered = Vec::with_capacity(kept.len()); + let mut rest = kept; + loop { + let (ready, wait): (Vec, Vec) = rest.into_iter().partition(|b| placed.contains(&b.parent)); + if ready.is_empty() { + break; + } + for b in ready { + placed.insert(b.child); + ordered.push(b); + } + rest = wait; + } + ordered.truncate(MAX_BONES); + self.bones = ordered; + self.bones != before + } +} + +/// One joint's angle in a pose (radians, 0 as drawn). +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct JointAngle { + pub bone: BoneId, + pub angle: f32, +} + +/// A pose: joint angles by bone. A bone it doesn't list is as drawn (angle 0). +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(transparent)] +pub struct Pose(pub Vec); + +impl Pose { + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + + /// The angle of bone `b` (0 when the pose doesn't list it). + pub fn angle(&self, b: BoneId) -> f32 { + self.0.iter().find(|j| j.bone == b).map_or(0.0, |j| j.angle) + } + + pub fn set(&mut self, b: BoneId, angle: f32) { + match self.0.iter_mut().find(|j| j.bone == b) { + Some(j) => j.angle = angle, + None => self.0.push(JointAngle { bone: b, angle }), + } + } + + /// Keeps only the bones in `keep`. + pub fn retain(&mut self, keep: impl Fn(BoneId) -> bool) { + self.0.retain(|j| keep(j.bone)); + } + + /// Every bone of `arm` at the angle its joint allows: the pose as it shows. + pub fn allowed(&self, arm: &Armature) -> Pose { + Pose(arm.bones.iter().map(|b| JointAngle { bone: b.id, angle: b.allow(self.angle(b.id)) }).collect()) + } + + /// The pose `t` of the way to `o`, joint by joint (angles blend linearly, so a joint that + /// turned a whole way round between keys turns that way in the tween). + pub fn lerp(&self, o: &Pose, t: f32, arm: &Armature) -> Pose { + Pose(arm.bones.iter().map(|b| JointAngle { bone: b.id, angle: b.allow(anicraft_geom::lerp(self.angle(b.id), o.angle(b.id), t)) }).collect()) + } + + /// Repairs a loaded pose: finite angles in range, one per bone, at most [`MAX_BONES`]. + /// Returns whether anything changed. + pub fn sanitize(&mut self) -> bool { + let before = self.0.len(); + let mut changed = false; + let mut seen = HashSet::new(); + self.0.retain(|j| seen.insert(j.bone)); + self.0.truncate(MAX_BONES); + for j in &mut self.0 { + let a = if j.angle.is_finite() { j.angle.clamp(-MAX_ANGLE, MAX_ANGLE) } else { 0.0 }; + if a.to_bits() != j.angle.to_bits() { + j.angle = a; + changed = true; + } + } + changed || self.0.len() != before + } +} + +/// `R(angle)` about point `j`. +fn turn_about(j: Vec2, angle: f32) -> Affine { + Affine::translate(j.x, j.y).mul(&Affine::rotate(angle)).mul(&Affine::translate(-j.x, -j.y)) +} + +/// Forward kinematics: the transform (in the layer's space) of every instance in `elements` +/// once `pose` turns the armature's joints. A root keeps its own transform; a child is placed +/// from its parent: `R_joint(angle) · parent · rest`. An instance whose parent isn't on the +/// keyframe keeps its own transform. +pub fn place(arm: &Armature, elements: &[Arc], pose: &Pose) -> HashMap { + let mut world: HashMap = elements.iter().map(|e| (e.id, e.transform)).collect(); + for b in &arm.bones { + let Some(wp) = world.get(&b.parent).copied() else { continue }; + if !world.contains_key(&b.child) { + continue; + } + let j = wp.apply(b.head); + let wc = turn_about(j, b.allow(pose.angle(b.id))).mul(&wp.mul(&b.rest)); + if wc.is_finite() { + world.insert(b.child, wc); + } + } + world +} + +/// Puts the instances of `elements` where `pose` has them (copy-on-write: only instances that +/// move are cloned). Returns whether any moved. +pub fn apply(arm: &Armature, elements: &mut [Arc], pose: &Pose) -> bool { + if arm.is_empty() { + return false; + } + let world = place(arm, elements, pose); + let mut moved = false; + for e in elements.iter_mut() { + if arm.bone_into(e.id).is_none() { + continue; + } + if let Some(m) = world.get(&e.id) + && *m != e.transform + { + Arc::make_mut(e).transform = *m; + moved = true; + } + } + moved +} + +/// The pose layer `layer` has at `frame`: its covering keyframe's, or, inside a tween, the pose +/// between that keyframe's and the next one's at the tween's eased time. Exact at keyframes. +/// `None` without an armature or on an empty frame. +pub fn pose_at(layer: &Layer, frame: u32) -> Option { + let arm = layer.armature.as_deref().filter(|_| layer.kind == crate::LayerKind::Armature)?; + let idx = layer.keyframe_index_at(frame)?; + let kf: &Keyframe = layer.keyframes.get(idx)?; + let here = kf.pose.allowed(arm); + let (Some(tween), None) = (kf.tween, &kf.motion) else { return Some(here) }; + let Some(next) = layer.keyframes.get(idx + 1) else { return Some(here) }; + if next.start != kf.end() || frame == kf.start { + return Some(here); + } + let t = tween.easing.apply((frame - kf.start) as f32 / kf.duration.max(1) as f32); + Some(kf.pose.lerp(&next.pose, t, arm)) +} + +/// Where a bone is drawn: its joint (head) and end (tail), in the layer's space. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct BoneAt { + pub id: BoneId, + pub head: Vec2, + pub tail: Vec2, + /// The joint angle (radians, as the joint allows it). + pub angle: f32, +} + +/// Every bone's joint and end with the instances in `elements` placed as they show (posed: +/// what [`crate::evaluate_layer_elements`] gives on an armature layer). +pub fn bones_at(arm: &Armature, elements: &[Arc], pose: &Pose) -> Vec { + let world: HashMap = elements.iter().map(|e| (e.id, e.transform)).collect(); + arm.bones + .iter() + .filter_map(|b| { + let (wp, wc) = (world.get(&b.parent)?, world.get(&b.child)?); + Some(BoneAt { id: b.id, head: wp.apply(b.head), tail: wc.apply(b.tail), angle: b.allow(pose.angle(b.id)) }) + }) + .collect() +} + +/// What a solve came to. +#[derive(Clone, Debug, PartialEq)] +pub struct Solved { + /// The new pose (every bone of the armature). + pub pose: Pose, + /// How far the effector ended from the target. + pub error: f32, + /// How many bones the drag could turn (0: the bone is pinned, or hangs from a pinned one). + pub chain: usize, +} + +/// The bones a drag of bone `id` may turn: `id` and the bones it hangs from, up to the first +/// that must stay put: a pinned bone, or one a pinned bone hangs from (turning it would move +/// the pinned bone). +pub fn movable_chain(arm: &Armature, id: BoneId) -> Vec<&Bone> { + let frozen: HashSet = arm.bones.iter().filter(|b| b.pinned).flat_map(|p| arm.chain(p.id)).map(|b| b.id).collect(); + arm.chain(id).into_iter().take_while(|b| !frozen.contains(&b.id)).collect() +} + +/// Inverse kinematics: the pose that brings point `local` of bone `id`'s child instance (its +/// local space; the bone's tail when dragging the bone end) to `target` (layer space), turning +/// only the bones [`movable_chain`] allows. `elements` are the keyframe's instances (the roots +/// at their own transforms), `pose` the pose to start from. Cyclic coordinate descent: each +/// sweep turns the joints from the dragged bone upward so the effector points at the target, +/// each clamped to its limits, until the effector is within [`IK_TOLERANCE`] or stops moving. +/// An unreachable target leaves the chain stretched straight toward it, the root where it was. +/// `None` when the armature has no bone `id` or its instances aren't on the keyframe. +pub fn solve(arm: &Armature, elements: &[Arc], pose: &Pose, id: BoneId, local: Vec2, target: Vec2) -> Option { + let bone = arm.bone(id)?; + if !(local.x.is_finite() && local.y.is_finite() && target.x.is_finite() && target.y.is_finite()) { + return None; + } + let chain: Vec<(BoneId, ElementId, Vec2)> = movable_chain(arm, id).iter().map(|b| (b.id, b.parent, b.head)).collect(); + let mut pose = pose.allowed(arm); + let effector = |pose: &Pose| -> Option<(HashMap, Vec2)> { + let world = place(arm, elements, pose); + let e = world.get(&bone.child)?.apply(local); + Some((world, e)) + }; + let (_, start) = effector(&pose)?; + let mut error = start.distance(target); + for _ in 0..IK_SWEEPS { + if error <= IK_TOLERANCE || chain.is_empty() { + break; + } + let Some((world, mut e)) = effector(&pose) else { break }; + let mut turned = 0.0f32; + // From the dragged bone up: turning a joint moves only what is below it, so the joints + // above keep the places this sweep began with. + for &(b, parent, head) in &chain { + let Some(wp) = world.get(&parent) else { continue }; + let Some(joint) = arm.bone(b) else { continue }; + let j = wp.apply(head); + let (u, v) = (e - j, target - j); + if u.length() < 1e-6 || v.length() < 1e-6 { + continue; + } + let want = u.cross(v).atan2(u.dot(v)); + let cur = pose.angle(b); + let next = joint.allow(cur + want); + let by = next - cur; + if by != 0.0 { + pose.set(b, next); + e = turn_about(j, by).apply(e); + turned = turned.max(by.abs()); + } + } + let Some((_, e)) = effector(&pose) else { break }; + let was = error; + error = e.distance(target); + // Stuck (limits, or stretched straight at an unreachable target). + if turned < 1e-7 || ((was - error).abs() < 1e-6 * was.max(1.0) && turned < 1e-4) { + break; + } + } + Some(Solved { pose, error, chain: chain.len() }) +} + +#[cfg(test)] +#[path = "armature_tests.rs"] +mod tests; diff --git a/crates/doc/src/armature_tests.rs b/crates/doc/src/armature_tests.rs new file mode 100644 index 00000000..a74b7665 --- /dev/null +++ b/crates/doc/src/armature_tests.rs @@ -0,0 +1,232 @@ +//! Armatures, poses and inverse kinematics (ADR 0043). + +use super::*; +use crate::{BlendMode, ColorEffect, Document, Easing, ElementKind, Keyframe, LayerId, LayerKind, LoopMode, Paint, Rgba, Shape, Symbol, SymbolId, SymbolKind, Timeline, Tween, evaluate, evaluate_layer_elements}; +use anicraft_geom::Path; +use std::f32::consts::FRAC_PI_2; + +const ROOT: ElementId = ElementId(10); +const ARM: ElementId = ElementId(11); +const HAND: ElementId = ElementId(12); +const B1: BoneId = BoneId(20); +const B2: BoneId = BoneId(21); +const SEG: SymbolId = SymbolId(1); + +fn instance(id: ElementId, x: f32, y: f32) -> Arc { + let kind = ElementKind::Symbol { symbol: SEG, loop_mode: LoopMode::Loop, first_frame: 0, blend: BlendMode::Normal, filters: Vec::new(), events: Vec::new() }; + Arc::new(Element { id, name: String::new(), transform: Affine::translate(x, y), color: ColorEffect::default(), kind }) +} + +fn bone(id: BoneId, parent: ElementId, child: ElementId) -> Bone { + // Every segment is 100 px long from its registration point; bones join end to start. + Bone { id, name: String::new(), parent, child, head: Vec2::new(100.0, 0.0), tail: Vec2::new(100.0, 0.0), rest: Affine::translate(100.0, 0.0), limits: None, pinned: false } +} + +/// A three-segment chain lying along y = 100: the root from x = 100, the arm from 200 (its +/// joint), the hand from 300; the hand's end at 400. The arm and hand reach 200 px from the +/// shoulder joint at (200, 100). +fn chain() -> (Armature, Vec>) { + let arm = Armature { bones: vec![bone(B1, ROOT, ARM), bone(B2, ARM, HAND)] }; + (arm, vec![instance(ROOT, 100.0, 100.0), instance(ARM, 200.0, 100.0), instance(HAND, 300.0, 100.0)]) +} + +fn hand_end(arm: &Armature, els: &[Arc], pose: &Pose) -> Vec2 { + place(arm, els, pose)[&HAND].apply(Vec2::new(100.0, 0.0)) +} + +fn close(a: Vec2, b: Vec2, tol: f32) -> bool { + a.distance(b) <= tol +} + +#[test] +fn forward_kinematics_turns_children_about_their_joints() { + let (arm, els) = chain(); + let rest = place(&arm, &els, &Pose::default()); + assert!(close(rest[&HAND].translation(), Vec2::new(300.0, 100.0), 1e-4), "the rest pose is the drawing"); + let mut pose = Pose::default(); + pose.set(B1, FRAC_PI_2); + let w = place(&arm, &els, &pose); + // The arm turns a quarter clockwise about the shoulder (200, 100): it now points down. + assert!(close(w[&ARM].translation(), Vec2::new(200.0, 100.0), 1e-4)); + assert!(close(w[&HAND].translation(), Vec2::new(200.0, 200.0), 1e-3), "{:?}", w[&HAND]); + assert!(close(hand_end(&arm, &els, &pose), Vec2::new(200.0, 300.0), 1e-3)); + // The elbow turns relative to the arm: a quarter back makes the hand point right again. + pose.set(B2, -FRAC_PI_2); + assert!(close(hand_end(&arm, &els, &pose), Vec2::new(300.0, 200.0), 1e-3)); + // The root keeps its own transform. + assert_eq!(place(&arm, &els, &pose)[&ROOT], Affine::translate(100.0, 100.0)); +} + +#[test] +fn ik_reaches_a_reachable_target_within_half_a_pixel() { + let (arm, els) = chain(); + for target in [Vec2::new(300.0, 180.0), Vec2::new(150.0, 200.0), Vec2::new(250.0, 20.0), Vec2::new(390.0, 110.0), Vec2::new(210.0, 120.0)] { + let s = solve(&arm, &els, &Pose::default(), B2, Vec2::new(100.0, 0.0), target).unwrap(); + let end = hand_end(&arm, &els, &s.pose); + assert!(close(end, target, 0.5), "{target:?}: ended at {end:?} ({} px off)", s.error); + assert!((s.error - end.distance(target)).abs() < 1e-3); + assert_eq!(s.chain, 2); + // The root never moves. + assert_eq!(place(&arm, &els, &s.pose)[&ROOT], Affine::translate(100.0, 100.0)); + } +} + +#[test] +fn ik_respects_joint_limits() { + let (mut arm, els) = chain(); + let lim = Limits { min: -10f32.to_radians(), max: 10f32.to_radians() }; + arm.bone_mut(B2).unwrap().limits = Some(lim); + // A target that needs a sharp elbow: the elbow stops at its limit. + let s = solve(&arm, &els, &Pose::default(), B2, Vec2::new(100.0, 0.0), Vec2::new(200.0, 160.0)).unwrap(); + let a = s.pose.angle(B2); + assert!((lim.min..=lim.max).contains(&a), "elbow at {}°", a.to_degrees()); + // Evaluation clamps too, whatever a file says. + let mut wild = Pose::default(); + wild.set(B2, 3.0); + assert_eq!(wild.allowed(&arm).angle(B2), lim.max); + // A joint that may not turn at all keeps its angle. + arm.bone_mut(B1).unwrap().limits = Some(Limits { min: 0.0, max: 0.0 }); + let s = solve(&arm, &els, &Pose::default(), B2, Vec2::new(100.0, 0.0), Vec2::new(300.0, 300.0)).unwrap(); + assert_eq!(s.pose.angle(B1), 0.0); +} + +#[test] +fn an_unreachable_target_stretches_the_chain_straight_and_the_root_stays() { + let (arm, els) = chain(); + let target = Vec2::new(700.0, 500.0); + let mut start = Pose::default(); + start.set(B1, 0.7); + start.set(B2, -1.2); + let s = solve(&arm, &els, &start, B2, Vec2::new(100.0, 0.0), target).unwrap(); + let w = place(&arm, &els, &s.pose); + let (shoulder, elbow, end) = (Vec2::new(200.0, 100.0), w[&HAND].translation(), hand_end(&arm, &els, &s.pose)); + let (d1, d2, dt) = ((elbow - shoulder).normalized(), (end - elbow).normalized(), (target - shoulder).normalized()); + assert!(d1.cross(d2).abs() < 1e-3 && d1.dot(d2) > 0.999, "straight: {d1:?} {d2:?}"); + assert!(d1.dot(dt) > 0.999, "pointing at the target"); + assert!((s.error - (target.distance(shoulder) - 200.0)).abs() < 0.05, "{}", s.error); + assert_eq!(w[&ROOT], Affine::translate(100.0, 100.0), "the root stays put"); +} + +#[test] +fn pinned_bones_stay_put() { + let (mut arm, els) = chain(); + arm.bone_mut(B1).unwrap().pinned = true; + let s = solve(&arm, &els, &Pose::default(), B2, Vec2::new(100.0, 0.0), Vec2::new(250.0, 180.0)).unwrap(); + assert_eq!(s.pose.angle(B1), 0.0, "the pinned shoulder never turns"); + assert_eq!(s.chain, 1); + // Dragging the pinned bone itself moves nothing. + let s = solve(&arm, &els, &Pose::default(), B1, Vec2::new(100.0, 0.0), Vec2::new(0.0, 0.0)).unwrap(); + assert_eq!((s.chain, s.pose.angle(B1)), (0, 0.0)); + // A pin locks the bones it hangs from too. + arm.bone_mut(B1).unwrap().pinned = false; + arm.bone_mut(B2).unwrap().pinned = true; + assert!(movable_chain(&arm, B1).is_empty(), "turning the shoulder would move the pinned hand"); + assert!(movable_chain(&arm, B2).is_empty()); +} + +/// An armature layer: the chain at frame 0 posed straight, at frame 10 with the shoulder a +/// quarter turned, tweened with `easing`. +fn armature_layer(easing: Easing) -> Layer { + let (arm, els) = chain(); + let mut l = Layer::new(LayerId(1), "Armature_1"); + l.kind = LayerKind::Armature; + l.armature = Some(Arc::new(arm)); + let mut a = Keyframe::new(0, 10); + a.elements = els.clone(); + a.tween = Some(Tween { easing, ..Tween::default() }); + let mut b = Keyframe::new(10, 5); + b.elements = els; + b.pose.set(B1, FRAC_PI_2); + l.keyframes = vec![Arc::new(a), Arc::new(b)]; + l +} + +#[test] +fn poses_tween_and_are_exact_at_keyframes() { + let l = armature_layer(Easing::Linear); + assert_eq!(pose_at(&l, 0).unwrap().angle(B1), 0.0); + assert_eq!(pose_at(&l, 10).unwrap().angle(B1), FRAC_PI_2, "exact at the key"); + assert_eq!(pose_at(&l, 14).unwrap().angle(B1), FRAC_PI_2, "held after the last key"); + assert!((pose_at(&l, 5).unwrap().angle(B1) - FRAC_PI_2 * 0.5).abs() < 1e-6); + // The existing easing shapes the tween. + let eased = armature_layer(Easing::QuadIn); + assert!((pose_at(&eased, 5).unwrap().angle(B1) - FRAC_PI_2 * 0.25).abs() < 1e-6); + // Evaluation places the instances by the pose: at the key, exactly forward kinematics. + let (_, els) = evaluate_layer_elements(&l, 10).unwrap(); + let hand = els.iter().find(|e| e.id == HAND).unwrap(); + assert!(close(hand.transform.translation(), Vec2::new(200.0, 200.0), 1e-3)); + // Half way the hand has swung through 45° about the shoulder. + let (_, els) = evaluate_layer_elements(&l, 5).unwrap(); + let hand = els.iter().find(|e| e.id == HAND).unwrap(); + let r = std::f32::consts::FRAC_1_SQRT_2 * 100.0; + assert!(close(hand.transform.translation(), Vec2::new(200.0 + r, 100.0 + r), 1e-3), "{:?}", hand.transform); + // Without the tween the first pose holds. + let mut held = armature_layer(Easing::Linear); + Arc::make_mut(&mut held.keyframes[0]).tween = None; + assert_eq!(pose_at(&held, 9).unwrap().angle(B1), 0.0); +} + +#[test] +fn every_export_sees_the_pose() { + let mut d = Document::default(); + let mut seg = Layer::new(LayerId(2), "seg"); + let mut k = Keyframe::new(0, 1); + k.elements.push(Arc::new(Element { id: ElementId(3), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Shape(Shape::filled(Path::rect(0.0, -5.0, 100.0, 10.0), Paint::Solid(Rgba::BLACK))) })); + seg.keyframes = vec![Arc::new(k)]; + d.library.push(Arc::new(Symbol { id: SEG, name: "Seg".into(), kind: SymbolKind::Graphic, linkage: None, timeline: Timeline { layers: vec![Arc::new(seg)] } })); + d.timeline_mut(0).layers = vec![Arc::new(armature_layer(Easing::Linear))]; + d.sanitize(); + let dl = evaluate(&d, 10); + let hand = dl.items.iter().find(|i| i.element == HAND).unwrap(); + assert!(close(hand.transform.apply(Vec2::new(100.0, 0.0)), Vec2::new(200.0, 300.0), 1e-3), "the display list draws the posed hand"); + // The file keeps the armature and poses. + let back: Document = serde_json::from_str(&serde_json::to_string(&d).unwrap()).unwrap(); + assert_eq!(back, d); + assert_eq!(back.timeline(0).layers[0].keyframes[1].pose.angle(B1), FRAC_PI_2); +} + +#[test] +fn sanitize_repairs_hostile_armatures() { + let (mut arm, _) = chain(); + // Listed child first, a cycle, a second bone into the hand, a bone into itself, NaN. + let mut cyc = bone(BoneId(30), ElementId(40), ElementId(41)); + cyc.head = Vec2::new(0.0, 0.0); + let back = bone(BoneId(31), ElementId(41), ElementId(40)); + let twice = bone(BoneId(32), ROOT, HAND); + let selfie = bone(BoneId(33), ROOT, ROOT); + let mut nan = bone(BoneId(34), HAND, ElementId(50)); + nan.rest = Affine { m: [f32::NAN, 0.0, 0.0, 1.0, 0.0, 0.0] }; + let mut wide = bone(BoneId(35), HAND, ElementId(51)); + wide.limits = Some(Limits { min: 100.0, max: f32::NEG_INFINITY }); + let mut limited = bone(BoneId(36), HAND, ElementId(52)); + limited.limits = Some(Limits { min: 1.0, max: -1.0 }); + arm.bones.reverse(); + arm.bones.extend([cyc, back, twice, selfie, nan, wide, limited]); + assert!(arm.sanitize()); + let ids: Vec = arm.bones.iter().map(|b| b.id.0).collect(); + assert_eq!(ids, vec![20, 21, 35, 36], "ordered parent first; cycles, repeats and NaN gone"); + assert_eq!(arm.bone(BoneId(35)).unwrap().limits, None); + assert_eq!(arm.bone(BoneId(36)).unwrap().limits, Some(Limits { min: -1.0, max: 1.0 })); + assert!(!arm.sanitize(), "sanitizing twice changes nothing"); + let mut p = Pose(vec![JointAngle { bone: B1, angle: f32::NAN }, JointAngle { bone: B1, angle: 1.0 }, JointAngle { bone: B2, angle: 1e30 }]); + assert!(p.sanitize()); + assert_eq!(p.0.len(), 2); + assert_eq!((p.angle(B1), p.angle(B2)), (0.0, MAX_ANGLE)); + // Hostile solves return nothing rather than panicking. + let (arm, els) = chain(); + assert!(solve(&arm, &els, &Pose::default(), BoneId(999), Vec2::new(0.0, 0.0), Vec2::new(1.0, 1.0)).is_none()); + assert!(solve(&arm, &els, &Pose::default(), B2, Vec2::new(f32::NAN, 0.0), Vec2::new(1.0, 1.0)).is_none()); + assert!(solve(&arm, &[], &Pose::default(), B2, Vec2::new(0.0, 0.0), Vec2::new(1.0, 1.0)).is_none()); +} + +#[test] +fn tree_queries() { + let (arm, _) = chain(); + assert_eq!(arm.roots(), vec![ROOT]); + assert_eq!(arm.members(), vec![ROOT, ARM, HAND]); + assert_eq!(arm.subtree(B1), vec![B1, B2]); + assert_eq!(arm.subtree(B2), vec![B2]); + assert_eq!(arm.chain(B2).iter().map(|b| b.id).collect::>(), vec![B2, B1]); + assert_eq!(arm.bone_into(HAND).map(|b| b.id), Some(B2)); + assert!(arm.contains(ROOT) && !arm.contains(ElementId(99))); +} diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 176b9d91..501f104a 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -183,7 +183,19 @@ pub fn evaluate_layer_elements(layer: &Layer, frame: u32) -> Option<(u32, Cow<'_ /// [`evaluate_layer_elements`] with a motion guide: tweened elements travel along `guide` (in /// the layer's own space) from the point nearest their start to the point nearest their end, /// turning with it when the tween orients to the path. +/// +/// On an armature layer (ADR 0043) the instances are then placed by the pose at the frame +/// (tweened between pose keyframes): forward kinematics from the root's own transform. pub fn evaluate_guided<'a>(layer: &'a Layer, frame: u32, guide: Option<&PathWalk>) -> Option<(u32, Cow<'a, [Arc]>)> { + let (start, els) = evaluate_tweened(layer, frame, guide)?; + let Some(arm) = layer.armature.as_deref().filter(|a| layer.kind == crate::LayerKind::Armature && !a.is_empty()) else { return Some((start, els)) }; + let pose = crate::armature::pose_at(layer, frame).unwrap_or_default(); + let mut els = els.into_owned(); + crate::armature::apply(arm, &mut els, &pose); + Some((start, Cow::Owned(els))) +} + +fn evaluate_tweened<'a>(layer: &'a Layer, frame: u32, guide: Option<&PathWalk>) -> Option<(u32, Cow<'a, [Arc]>)> { let idx = layer.keyframe_index_at(frame)?; let kf = layer.keyframes.get(idx)?; // A motion tween: its target follows the property curves (and its motion path, ADR 0030); diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 1a24639c..444d6aa5 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -7,6 +7,7 @@ pub use anicraft_audio as audio; pub use anicraft_actions as actions; +pub mod armature; mod bitmap; pub mod camera; mod filter; @@ -28,6 +29,7 @@ pub use motion::{MotionTween, OnPath, Property, PropertyKey, Props, Track, motio pub use sound::{EnvelopePoint, FrameSound, Sound, SoundEffect, SoundFormat, SoundId, SoundSync}; pub use width::{MAX_WIDTH_FACTOR, MAX_WIDTH_POINTS, ProfilePreset, WidthPoint, WidthProfile}; pub use camera::Camera; +pub use armature::{Armature, Bone, BoneId, JointAngle, Limits, Pose}; pub use eval::{DisplayItem, DisplayList, Group, MAX_SYMBOL_DEPTH, evaluate, evaluate_guided, evaluate_layer_elements, evaluate_player, evaluate_scene, evaluate_scene_camera, guide_walk, instance_start}; pub use actions::{Action, ButtonEvent, EventHandler, FrameScript, Language, PluginScript, SourceScript}; @@ -586,17 +588,20 @@ pub struct Keyframe { /// script (ADR 0024). Rendering and exports ignore it. #[serde(default, skip_serializing_if = "Option::is_none")] pub script: Option, + /// On an armature layer: the joint angles this keyframe poses the armature with (ADR 0043). + #[serde(default, skip_serializing_if = "Pose::is_empty")] + pub pose: Pose, } impl PartialEq for Keyframe { fn eq(&self, o: &Keyframe) -> bool { - self.start == o.start && self.duration == o.duration && self.tween == o.tween && self.motion == o.motion && self.hints == o.hints && self.label == o.label && self.sound == o.sound && self.script == o.script && arcs_eq(&self.elements, &o.elements) + self.start == o.start && self.duration == o.duration && self.tween == o.tween && self.motion == o.motion && self.hints == o.hints && self.label == o.label && self.sound == o.sound && self.script == o.script && self.pose == o.pose && arcs_eq(&self.elements, &o.elements) } } impl Keyframe { pub fn new(start: u32, duration: u32) -> Self { - Keyframe { start, duration: duration.max(1), elements: Vec::new(), tween: None, motion: None, hints: Vec::new(), label: String::new(), sound: None, script: None } + Keyframe { start, duration: duration.max(1), elements: Vec::new(), tween: None, motion: None, hints: Vec::new(), label: String::new(), sound: None, script: None, pose: Pose::default() } } /// Mutable access to the elements whose ids satisfy `pick`, cloning only those. pub fn elements_mut_where(&mut self, mut pick: impl FnMut(ElementId) -> bool) -> Vec<&mut Element> { @@ -625,6 +630,9 @@ pub enum LayerKind { /// The camera (ADR 0027): at most one per scene timeline, always the top layer; its /// keyframes hold the camera, which views every other layer. Draws nothing itself. Camera, + /// An armature (ADR 0043): symbol instances joined by bones ([`Layer::armature`]), posed + /// on each keyframe ([`Keyframe::pose`]) and tweened between poses. + Armature, } /// Deepest nesting of folders (and a mask inside them) that is kept. @@ -662,6 +670,9 @@ pub struct Layer { /// The layer's sounds are silent (in playback and every export). #[serde(default, skip_serializing_if = "is_false")] pub muted: bool, + /// An armature layer's bones (ADR 0043); `None` on every other kind of layer. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub armature: Option>, } fn is_zero(v: &f32) -> bool { @@ -687,6 +698,10 @@ impl PartialEq for Layer { && self.depth.to_bits() == o.depth.to_bits() && self.volume.to_bits() == o.volume.to_bits() && self.muted == o.muted + && match (&self.armature, &o.armature) { + (Some(a), Some(b)) => arc_eq(a, b), + (a, b) => a.is_none() && b.is_none(), + } && arcs_eq(&self.keyframes, &o.keyframes) } } @@ -713,6 +728,7 @@ impl Layer { depth: 0.0, volume: 1.0, muted: false, + armature: None, } } /// The gain this layer gives its sounds: its volume, or silence when muted. @@ -1185,6 +1201,9 @@ impl Document { let mut max_id = 0u64; let scan = |l: &Layer, max_id: &mut u64| { *max_id = (*max_id).max(l.id.0); + for b in l.armature.iter().flat_map(|a| &a.bones) { + *max_id = (*max_id).max(b.id.0); + } for k in &l.keyframes { for e in &k.elements { *max_id = (*max_id).max(e.id.0); @@ -1204,6 +1223,7 @@ impl Document { Arc::make_mut(l).normalize(); sanitize_scripts(l); sanitize_depth(l); + sanitize_armature(l); scan(l, &mut max_id); } tl.repair_masks(); @@ -1226,6 +1246,7 @@ impl Document { Arc::make_mut(l).kind = LayerKind::Normal; } sanitize_depth(l); + sanitize_armature(l); scan(l, &mut max_id); } tl.repair_masks(); @@ -1248,6 +1269,36 @@ fn sanitize_depth(layer: &mut Arc) { } } +/// Repairs a loaded layer's armature (ADR 0043): only an armature layer has one, its bones are +/// sane and ordered, and its keyframes' poses are finite. Touches only what needs it. +fn sanitize_armature(layer: &mut Arc) { + let is_armature = layer.kind == LayerKind::Armature; + // (A pose on another layer's keyframe, pasted from an armature, is kept and plays no part.) + if !is_armature { + if layer.armature.is_some() { + Arc::make_mut(layer).armature = None; + } + return; + } + if let Some(a) = &layer.armature { + let mut fixed = (**a).clone(); + if fixed.sanitize() { + Arc::make_mut(layer).armature = Some(Arc::new(fixed)); + } + } + let bad = |k: &Keyframe| { + let mut p = k.pose.clone(); + p.sanitize() + }; + if layer.keyframes.iter().any(|k| bad(k)) { + for k in &mut Arc::make_mut(layer).keyframes { + if bad(k) { + Arc::make_mut(k).pose.sanitize(); + } + } + } +} + /// Repairs a loaded layer's frame scripts and instance event handlers (ADR 0024). Touches (and /// so un-shares) only keyframes that need it. fn sanitize_scripts(layer: &mut Arc) { diff --git a/crates/engine/src/cmds_bone.rs b/crates/engine/src/cmds_bone.rs new file mode 100644 index 00000000..a2d67fd8 --- /dev/null +++ b/crates/engine/src/cmds_bone.rs @@ -0,0 +1,445 @@ +//! Bone commands (ADR 0043): join symbol instances into an armature, take bones away, limit and +//! pin joints, pose the armature at a frame by joint angle or by inverse kinematics, and read +//! it back. +//! +//! The armature lives on an armature layer: `bone.add` moves the instances there (making the +//! layer for the first bone). Poses go through [`Session::editable_keyframe_in`], so inside a +//! pose tween they key the frame with the pose it shows, as editing any tweened object does; +//! a drag sends many `bone.solve` calls inside one gesture: one undo step. After every pose +//! edit the keyframe's instances are placed by the pose, so the file holds what shows. + +use crate::cmds_timeline::insert_keyframe_at; +use crate::params::*; +use crate::{CommandSpec, EngineError, KeyEdit, MAX_FRAME, Result, Session}; +use anicraft_doc::armature::{self, Armature, Bone, BoneId, Limits, MAX_BONES, MAX_LIMIT, MAX_NAME}; +use anicraft_doc::{Element, ElementId, ElementKind, Keyframe, Layer, LayerId, LayerKind, Rgba, Tween, evaluate_layer_elements}; +use anicraft_geom::{Affine, Vec2}; +use serde_json::{Value, json}; +use std::sync::Arc; + +pub fn specs() -> Vec { + let c = |id, label, params, mutates, run| CommandSpec { id, label, menu: "", shortcut: None, params, mutates, run }; + vec![ + c( + "bone.add", + "Add Bone", + "{from (instance id: the bone starts on it), to (instance id: the bone moves it), head?: [x, y] (the joint, stage px; default the end of the bone into `from`, else its registration point), tail?: [x, y] (default `to`'s registration point), name?} → {bone, layer}. Both instances go to an armature layer (made for the first bone)", + true, + add as crate::RunFn, + ), + c("bone.remove", "Remove Bone", "{bone} removes it and the bones below it; the instances they moved go to a layer of their own as they look at the playhead (with the last bone, the whole armature does); asks first when the armature has more than one pose", true, remove), + c("bone.set_limits", "Joint Limits", "{bone, constrain?: bool (false: turns freely), min?, max? (°, −360…360, from where it was drawn)} limits how far the joint turns, in every pose", true, set_limits), + c("bone.pin", "Pin Bone", "{bone, pinned: bool} a pinned bone (and the bones it hangs from) stays put while dragging bones below it", true, pin), + c("bone.pose", "Pose Bone", "{bone?, angle? (°, the joint angle: 0 as drawn), rotate_by? (°), dx?, dy? (moves the whole armature), layer? (the armature layer, when no bone is given), frame?} keys the pose at the frame", true, pose), + c("bone.solve", "Drag Bone", "{bone, x, y (stage px: where the bone's end goes), local?: [x, y] (the point dragged, in the bone's instance's space; default its end), frame?} → {reached, error (px), chain}; inverse kinematics turns the bone and the bones above it (limits respected, pinned bones kept)", true, solve), + c("bone.info", "Armatures", "{frame?, layer?} → every armature on the scene at the frame: its bones with joint and end (stage px), joint angle and limits (°), pinned", false, info), + ] +} + +/// Where an instance is at the playhead. +struct Found { + layer: LayerId, + index: usize, + kind: LayerKind, + el: Arc, +} + +/// Instance `id` on the scene at the playhead (as it shows: tweened, posed). +fn find_instance(s: &Session, id: ElementId) -> Option { + let tl = s.doc.timeline(s.scene); + tl.layers.iter().enumerate().find_map(|(index, l)| { + let (_, els) = evaluate_layer_elements(l, s.frame)?; + let el = els.iter().find(|e| e.id == id)?.clone(); + Some(Found { layer: l.id, index, kind: l.kind, el }) + }) +} + +/// The armature layer holding bone `id`, and its armature. +fn find_bone(s: &Session, id: BoneId) -> Result<(LayerId, Arc)> { + s.doc + .timeline(s.scene) + .layers + .iter() + .filter(|l| l.kind == LayerKind::Armature) + .find_map(|l| l.armature.as_ref().filter(|a| a.bone(id).is_some()).map(|a| (l.id, a.clone()))) + .ok_or_else(|| EngineError::State(format!("no bone with id {} in this scene", id.0))) +} + +fn bone_param(p: &Value) -> Result { + opt_u64(p, "bone")?.map(BoneId).ok_or_else(|| EngineError::Param("param 'bone' (a bone id; see bone.info) is required".into())) +} + +/// Largest stage coordinate a bone point may have. +const MAX_COORD: f32 = 1_000_000.0; + +fn opt_point(p: &Value, key: &str) -> Result> { + let bad = || EngineError::Param(format!("param '{key}' must be [x, y] (finite numbers within ±1,000,000)")); + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::Array(a)) if a.len() == 2 => { + 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(Some(Vec2::new(n(0)?, n(1)?))) + } + Some(_) => Err(bad()), + } +} + +fn unlocked(s: &Session, id: LayerId) -> Result<()> { + let tl = s.doc.timeline(s.scene); + let l = tl.layer(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?; + if l.locked || tl.locked_by_folder(id) { + return Err(EngineError::State(format!("layer '{}' is locked", l.name))); + } + Ok(()) +} + +/// Takes instance `id` off the keyframe covering the playhead on layer `layer`. +fn take_off(s: &mut Session, layer: LayerId, id: ElementId) -> Result<()> { + let frame = s.frame; + let l = s.layer_mut(Some(layer))?; + if let Some(k) = l.keyframe_index_at(frame).and_then(|i| l.keyframe_mut(i)) { + k.elements.retain(|e| e.id != id); + } + Ok(()) +} + +/// A layer name `base_N` no layer of the scene has yet. +fn fresh_name(s: &Session, base: &str) -> String { + let tl = s.doc.timeline(s.scene); + (1..).map(|n| format!("{base}{n}")).find(|n| tl.layers.iter().all(|l| &l.name != n)).unwrap_or_else(|| base.to_string()) +} + +/// Places the instances of every keyframe of `layer` by its pose (after the armature changed). +fn rebake(layer: &mut Layer) { + let Some(arm) = layer.armature.clone() else { return }; + for k in &mut layer.keyframes { + let k = Arc::make_mut(k); + let pose = k.pose.allowed(&arm); + armature::apply(&arm, &mut k.elements, &pose); + } +} + +fn add(s: &mut Session, p: &Value) -> Result { + let req = |k: &str| opt_u64(p, k)?.map(ElementId).ok_or_else(|| EngineError::Param(format!("param '{k}' (an instance id) is required"))); + let (from, to) = (req("from")?, req("to")?); + let (head, tail) = (opt_point(p, "head")?, opt_point(p, "tail")?); + let name = opt_str(p, "name")?.unwrap_or("").trim().to_string(); + if name.len() > MAX_NAME { + return Err(EngineError::Param(format!("param 'name' must be at most {MAX_NAME} bytes"))); + } + if from == to { + return Err(EngineError::Param("a bone joins two different instances".into())); + } + let missing = |id: ElementId| EngineError::State(format!("no instance with id {} on the stage at frame {}", id.0, s.frame + 1)); + let f = find_instance(s, from).ok_or_else(|| missing(from))?; + let t = find_instance(s, to).ok_or_else(|| missing(to))?; + for x in [&f, &t] { + if !matches!(x.el.kind, ElementKind::Symbol { .. }) { + return Err(EngineError::State("bones join symbol instances: convert the artwork to a symbol first (Modify › Convert to Symbol, F8)".into())); + } + if !matches!(x.kind, LayerKind::Normal | LayerKind::Armature) { + return Err(EngineError::State("bones join instances on normal layers (not on guide or mask layers)".into())); + } + unlocked(s, x.layer)?; + } + let tl = s.doc.timeline(s.scene); + let arm_of = |x: &Found| (x.kind == LayerKind::Armature).then(|| tl.layer(x.layer).and_then(|l| l.armature.clone()).unwrap_or_default()); + let (fa, ta) = (arm_of(&f), arm_of(&t)); + match (&fa, &ta) { + (_, Some(a)) if f.layer == t.layer && a.bone_into(to).is_some() => return Err(EngineError::State("that instance already hangs from a bone; each instance has one bone into it".into())), + (_, Some(_)) if f.layer == t.layer => return Err(EngineError::State("that instance is the armature's root: drag from the root to the other instances instead".into())), + (None, Some(_)) => return Err(EngineError::State("start the bone on the armature: drag from one of its instances to the new one".into())), + (Some(_), Some(_)) => return Err(EngineError::State("those instances are in different armatures".into())), + _ => {} + } + if fa.as_ref().is_some_and(|a| a.bones.len() >= MAX_BONES) { + return Err(EngineError::State(format!("an armature has at most {MAX_BONES} bones"))); + } + let (wf, wt) = (f.el.transform, t.el.transform); + let singular = || EngineError::State("an instance scaled to nothing can't hold a bone".into()); + let (inv_f, inv_t) = (wf.inverse().ok_or_else(singular)?, wt.inverse().ok_or_else(singular)?); + // The joint: given, else the end of the bone into `from` (a chain joins end to start), else + // its registration point. + let into_from = fa.as_ref().and_then(|a| a.bone_into(from)).map(|b| wf.apply(b.tail)); + let head = head.or(into_from).unwrap_or(wf.translation()); + let tail = tail.unwrap_or(wt.translation()); + let rest = inv_f.mul(&wt); + if !rest.is_finite() || rest.inverse().is_none() { + return Err(singular()); + } + let id = BoneId(s.doc.alloc_id()); + let bone = Bone { id, name, parent: from, child: to, head: inv_f.apply(head), tail: inv_t.apply(tail), rest, limits: None, pinned: false }; + take_off(s, t.layer, to)?; + let lid = match fa { + Some(_) => { + // Another bone on this armature: the new instance joins every pose, at angle 0. + let l = s.layer_mut(Some(f.layer))?; + let mut arm = l.armature.as_deref().cloned().unwrap_or_default(); + arm.bones.push(bone); + l.armature = Some(Arc::new(arm)); + for k in &mut l.keyframes { + Arc::make_mut(k).elements.push(t.el.clone()); + } + rebake(l); + f.layer + } + None => { + // The first bone: both instances move to a new armature layer above them, whose one + // pose spans from their keyframe to the end of the timeline. + let (start, end) = s.doc.timeline(s.scene).layer(f.layer).and_then(|l| l.keyframe_at(s.frame)).map_or((s.frame, s.frame + 1), |k| (k.start, k.end())); + let end = end.max(s.frame_count()); + take_off(s, f.layer, from)?; + if s.doc.timeline(s.scene).layers.len() >= 1000 { + return Err(EngineError::State("too many layers (limit 1000)".into())); + } + let lid = LayerId(s.doc.alloc_id()); + let mut layer = Layer::new(lid, fresh_name(s, "Armature_")); + layer.kind = LayerKind::Armature; + // Bones show in the layer colour: a green that reads on light and dark artwork. + layer.color = Rgba::hex(0x2fb67c); + layer.armature = Some(Arc::new(Armature { bones: vec![bone] })); + let mut k = Keyframe::new(start, end.saturating_sub(start).max(1)); + k.elements = vec![f.el.clone(), t.el.clone()]; + k.tween = Some(Tween::default()); + layer.keyframes = vec![Arc::new(k)]; + let index = f.index.min(t.index); + let tl = s.doc.timeline_mut(s.scene); + layer.parent = tl.container_at(index, LayerKind::Armature); + tl.layers.insert(index.min(tl.layers.len()), Arc::new(layer)); + tl.repair_masks(); + lid + } + }; + s.layer = lid; + s.selection.clear(); + Ok(json!({"bone": id.0, "layer": lid.0, "created": lid != f.layer})) +} + +/// How many keyframes of an armature layer hold a pose of their own (more than one: the +/// armature is animated). +pub(crate) fn poses(l: &Layer) -> usize { + l.keyframes.iter().filter(|k| !k.elements.is_empty()).count() +} + +fn remove(s: &mut Session, p: &Value) -> Result { + let id = bone_param(p)?; + let (lid, arm) = find_bone(s, id)?; + unlocked(s, lid)?; + let gone = arm.subtree(id); + let mut left = (*arm).clone(); + left.bones.retain(|b| !gone.contains(&b.id)); + let dissolve = left.is_empty(); + let freed: Vec = if dissolve { arm.members() } else { arm.bones.iter().filter(|b| gone.contains(&b.id)).map(|b| b.child).collect() }; + let tl = s.doc.timeline(s.scene); + let index = tl.layers.iter().position(|l| l.id == lid).ok_or_else(|| EngineError::State("the armature layer went away".into()))?; + let layer = tl.layer(lid).ok_or_else(|| EngineError::State("the armature layer went away".into()))?; + let (start, end) = (layer.keyframes.first().map_or(0, |k| k.start), layer.end_frame()); + // The freed instances as they look at the playhead (or at the armature's first frame). + let at = s.frame.clamp(start, end.saturating_sub(1).max(start)); + let shown: Vec> = evaluate_layer_elements(layer, at).map(|(_, e)| e.iter().filter(|e| freed.contains(&e.id)).cloned().collect()).unwrap_or_default(); + let folder = layer.parent.filter(|p| tl.layer(*p).is_some_and(|x| x.kind == LayerKind::Folder)); + let new_id = LayerId(s.doc.alloc_id()); + let mut freed_layer = Layer::new(new_id, fresh_name(s, "Layer ")); + freed_layer.parent = folder; + let mut k = Keyframe::new(start, end.saturating_sub(start).max(1)); + k.elements = shown; + freed_layer.keyframes = vec![Arc::new(k)]; + let tl = s.doc.timeline_mut(s.scene); + if dissolve { + tl.layers.retain(|l| l.id != lid); + tl.layers.insert(index.min(tl.layers.len()), Arc::new(freed_layer)); + } else { + let l = tl.layer_mut(lid).ok_or_else(|| EngineError::State("the armature layer went away".into()))?; + for k in &mut l.keyframes { + let k = Arc::make_mut(k); + k.elements.retain(|e| !freed.contains(&e.id)); + k.pose.retain(|b| !gone.contains(&b)); + } + l.armature = Some(Arc::new(left)); + rebake(l); + tl.layers.insert((index + 1).min(tl.layers.len()), Arc::new(freed_layer)); + } + tl.repair_masks(); + s.layer = if dissolve { new_id } else { lid }; + s.selection.clear(); + Ok(json!({"removed": gone.iter().map(|b| b.0).collect::>(), "freed": freed.iter().map(|e| e.0).collect::>(), "layer": new_id.0, "armature_removed": dissolve})) +} + +fn set_limits(s: &mut Session, p: &Value) -> Result { + let id = bone_param(p)?; + let constrain = opt_bool(p, "constrain")?; + let (min, max) = (opt_f32(p, "min")?, opt_f32(p, "max")?); + let deg = MAX_LIMIT.to_degrees(); + for v in [min, max].into_iter().flatten() { + if !(-deg..=deg).contains(&v) { + return Err(EngineError::Param(format!("joint limits must be between −{deg:.0}° and {deg:.0}°"))); + } + } + let (lid, arm) = find_bone(s, id)?; + unlocked(s, lid)?; + let cur = arm.bone(id).and_then(|b| b.limits); + let limits = if constrain == Some(false) { + None + } else { + // Turning limits on without numbers: a quarter turn either way. + let base = cur.unwrap_or(Limits { min: -std::f32::consts::FRAC_PI_2, max: std::f32::consts::FRAC_PI_2 }); + let l = Limits { min: min.map_or(base.min, f32::to_radians), max: max.map_or(base.max, f32::to_radians) }; + if l.min > l.max { + return Err(EngineError::Param("the joint's min must be at most its max".into())); + } + Some(l) + }; + let l = s.layer_mut(Some(lid))?; + let mut arm = (*arm).clone(); + if let Some(b) = arm.bone_mut(id) { + b.limits = limits; + } + // Every pose keeps to the new limits. + for k in &mut l.keyframes { + if let Some(b) = arm.bone(id) { + let a = k.pose.angle(id); + if b.allow(a) != a { + Arc::make_mut(k).pose.set(id, b.allow(a)); + } + } + } + l.armature = Some(Arc::new(arm)); + rebake(l); + Ok(json!({"bone": id.0, "constrain": limits.is_some(), "min": limits.map(|l| l.min.to_degrees()), "max": limits.map(|l| l.max.to_degrees())})) +} + +fn pin(s: &mut Session, p: &Value) -> Result { + let id = bone_param(p)?; + let pinned = opt_bool(p, "pinned")?.ok_or_else(|| EngineError::Param("param 'pinned' (true or false) is required".into()))?; + let (lid, arm) = find_bone(s, id)?; + unlocked(s, lid)?; + let mut arm = (*arm).clone(); + if let Some(b) = arm.bone_mut(id) { + b.pinned = pinned; + } + s.layer_mut(Some(lid))?.armature = Some(Arc::new(arm)); + Ok(json!({"bone": id.0, "pinned": pinned})) +} + +/// Runs `edit` on the keyframe of armature layer `lid` that a pose at `frame` changes (keying +/// the frame inside a pose tween, extending the layer past its end), then places the +/// keyframe's instances by its pose. +fn edit_pose(s: &mut Session, lid: LayerId, frame: u32, edit: impl FnOnce(&Armature, &mut Keyframe) -> Result) -> Result { + if frame > MAX_FRAME { + return Err(EngineError::Param(format!("param 'frame' must be at most {MAX_FRAME}"))); + } + let arm = s.doc.timeline(s.scene).layer(lid).and_then(|l| l.armature.clone()).ok_or_else(|| EngineError::State("that is not an armature layer".into()))?; + // Past the end a pose carries on from the last one (not a blank keyframe). + { + let l = s.layer_mut(Some(lid))?; + if l.keyframe_at(frame).is_none() && frame >= l.end_frame() && !l.locked { + insert_keyframe_at(l, frame, true)?; + } + } + let (layer, at) = (s.layer, s.frame); + s.layer = lid; + s.frame = frame; + let out = (|| { + let kf = s.editable_keyframe_in(KeyEdit::Pose)?; + let v = edit(&arm, kf)?; + kf.pose = kf.pose.allowed(&arm); + armature::apply(&arm, &mut kf.elements, &kf.pose); + Ok(v) + })(); + s.layer = layer; + s.frame = at; + out +} + +fn pose(s: &mut Session, p: &Value) -> Result { + let bone = opt_u64(p, "bone")?.map(BoneId); + let (angle, rotate_by, dx, dy) = (opt_f32(p, "angle")?, opt_f32(p, "rotate_by")?, opt_f32(p, "dx")?, opt_f32(p, "dy")?); + let frame = opt_u32(p, "frame")?.unwrap_or(s.frame); + let lid = match (bone, opt_u64(p, "layer")?) { + (Some(b), _) => find_bone(s, b)?.0, + (None, Some(l)) => LayerId(l), + (None, None) => s.layer, + }; + if bone.is_none() && (angle.is_some() || rotate_by.is_some()) { + return Err(EngineError::Param("param 'bone' says which joint 'angle' or 'rotate_by' turns".into())); + } + let v = edit_pose(s, lid, frame, |arm, kf| { + let mut out = json!({"layer": lid.0}); + if let Some(b) = bone.and_then(|b| arm.bone(b)) { + let cur = kf.pose.angle(b.id); + let next = b.allow(angle.map_or(cur, f32::to_radians) + rotate_by.unwrap_or(0.0).to_radians()); + kf.pose.set(b.id, next); + out["bone"] = json!(b.id.0); + out["angle"] = json!(next.to_degrees()); + } + if dx.is_some() || dy.is_some() { + let by = Affine::translate(dx.unwrap_or(0.0), dy.unwrap_or(0.0)); + let roots = arm.roots(); + for e in kf.elements.iter_mut().filter(|e| roots.contains(&e.id)) { + let m = by.mul(&e.transform); + let t = m.translation(); + if m.is_finite() && t.x.abs() <= MAX_COORD && t.y.abs() <= MAX_COORD { + Arc::make_mut(e).transform = m; + } + } + } + Ok(out) + })?; + Ok(v) +} + +fn solve(s: &mut Session, p: &Value) -> Result { + let id = bone_param(p)?; + let target = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?); + if target.x.abs() > MAX_COORD || target.y.abs() > MAX_COORD { + return Err(EngineError::Param("the target must be within ±1,000,000 px".into())); + } + let local = opt_point(p, "local")?; + let frame = opt_u32(p, "frame")?.unwrap_or(s.frame); + let (lid, arm) = find_bone(s, id)?; + if armature::movable_chain(&arm, id).is_empty() { + return Err(EngineError::State("that bone is pinned, or hangs from a pinned bone: unpin it to drag it".into())); + } + let tail = arm.bone(id).map_or(Vec2::new(0.0, 0.0), |b| b.tail); + edit_pose(s, lid, frame, |arm, kf| { + let r = armature::solve(arm, &kf.elements, &kf.pose, id, local.unwrap_or(tail), target).ok_or_else(|| EngineError::State("the bone's instances aren't on this frame".into()))?; + kf.pose = r.pose; + Ok(json!({"bone": id.0, "reached": r.error <= 0.5, "error": r.error, "chain": r.chain})) + }) +} + +fn info(s: &mut Session, p: &Value) -> Result { + let frame = opt_u32(p, "frame")?.unwrap_or(s.frame).min(MAX_FRAME); + let only = opt_u64(p, "layer")?.map(LayerId); + let tl = s.doc.timeline(s.scene); + let deg = |v: f32| v.to_degrees(); + let pt = |v: Vec2| json!([v.x, v.y]); + let list: Vec = tl + .layers + .iter() + .filter(|l| l.kind == LayerKind::Armature && only.is_none_or(|o| o == l.id)) + .filter_map(|l| { + let arm = l.armature.as_deref()?; + let pose = armature::pose_at(l, frame).unwrap_or_default(); + let (_, els) = evaluate_layer_elements(l, frame).unwrap_or((0, std::borrow::Cow::Borrowed(&[]))); + let at = armature::bones_at(arm, &els, &pose); + let bones: Vec = arm + .bones + .iter() + .map(|b| { + let g = at.iter().find(|g| g.id == b.id); + json!({ + "id": b.id.0, "name": b.name, "from": b.parent.0, "to": b.child.0, + "parent_bone": arm.parent_bone(b).map(|x| x.id.0), + "head": g.map(|g| pt(g.head)), "tail": g.map(|g| pt(g.tail)), + "angle": deg(b.allow(pose.angle(b.id))), + "min": b.limits.map(|l| deg(l.min)), "max": b.limits.map(|l| deg(l.max)), + "pinned": b.pinned, + }) + }) + .collect(); + Some(json!({"layer": l.id.0, "name": l.name, "roots": arm.roots().iter().map(|e| e.0).collect::>(), "poses": poses(l), "bones": bones})) + }) + .collect(); + Ok(json!({"frame": frame, "armatures": list})) +} diff --git a/crates/engine/src/cmds_camera.rs b/crates/engine/src/cmds_camera.rs index 2f099232..e8fd10a3 100644 --- a/crates/engine/src/cmds_camera.rs +++ b/crates/engine/src/cmds_camera.rs @@ -132,7 +132,7 @@ fn set(s: &mut Session, p: &Value) -> Result { s.layer = id; s.frame = frame; let out: Result = (|| { - let kf = s.editable_keyframe_in(true)?; + let kf = s.editable_keyframe_in(crate::KeyEdit::Camera)?; let i = match kf.elements.iter().position(|e| matches!(e.kind, ElementKind::Camera)) { Some(i) => i, None => { diff --git a/crates/engine/src/cmds_motion.rs b/crates/engine/src/cmds_motion.rs index 3b864a9f..46c941ad 100644 --- a/crates/engine/src/cmds_motion.rs +++ b/crates/engine/src/cmds_motion.rs @@ -416,6 +416,9 @@ pub(crate) fn create(s: &mut Session, p: &Value) -> Result { if layer.kind == LayerKind::Folder { return Err(EngineError::State("a folder holds layers, not frames; pick a layer inside it".into())); } + if layer.kind == LayerKind::Armature { + return Err(EngineError::State("an armature layer tweens its poses: add a pose at another frame and Create Classic Tween between them".into())); + } let k = layer.keyframe_at(frame).ok_or_else(|| EngineError::State(format!("frame {} is empty on this layer", frame + 1)))?; if let Some(m) = &k.motion { return Ok(json!({"motion": k.start, "target": m.target.0, "frames": k.duration, "converted": false})); diff --git a/crates/engine/src/cmds_plugin.rs b/crates/engine/src/cmds_plugin.rs index 6f0b26b0..659f7dbb 100644 --- a/crates/engine/src/cmds_plugin.rs +++ b/crates/engine/src/cmds_plugin.rs @@ -31,7 +31,7 @@ const MAX_ELEMENTS: usize = 10_000; /// a namespace this list doesn't know is refused until someone decides (a test checks that /// every registered namespace is known). pub fn plugin_may_call(id: &str) -> std::result::Result<(), &'static str> { - const DOCUMENT: &[&str] = &["draw", "edit", "element", "symbol", "arrange", "modify", "library", "text", "scene", "path", "paint", "timeline", "layer", "align", "doc", "motion", "sound", "stroke", "tween", "actions", "instance", "camera", "script", "raw"]; + const DOCUMENT: &[&str] = &["draw", "edit", "element", "symbol", "arrange", "modify", "library", "text", "scene", "path", "paint", "timeline", "layer", "align", "doc", "motion", "sound", "stroke", "tween", "actions", "instance", "camera", "bone", "script", "raw"]; match id { "edit.undo" | "edit.redo" => Err("a plug-in run is one undo step; it can't undo or redo"), "edit.cut" | "edit.copy" | "edit.paste" | "edit.paste_in_place" | "timeline.cut_frames" | "timeline.copy_frames" | "timeline.paste_frames" => { diff --git a/crates/engine/src/cmds_timeline.rs b/crates/engine/src/cmds_timeline.rs index e601f92d..59e0ac94 100644 --- a/crates/engine/src/cmds_timeline.rs +++ b/crates/engine/src/cmds_timeline.rs @@ -135,6 +135,9 @@ fn set_type(s: &mut Session, id: LayerId, ty: &str) -> Result<()> { if tl.layers.get(i).is_some_and(|l| l.kind == LayerKind::Camera) { return Err(EngineError::State("the camera layer holds the camera; it can't become another kind of layer (Remove Camera takes it away)".into())); } + if tl.layers.get(i).is_some_and(|l| l.kind == LayerKind::Armature) { + return Err(EngineError::State("an armature layer holds its armature; it can't become another kind of layer (removing its bones frees the instances)".into())); + } // Whatever the type, the layer stays in the folder it is in. let folder = tl.folder_of(i); let (kind, parent) = match ty { @@ -169,6 +172,7 @@ fn layer_type_json(s: &Session, id: LayerId) -> Value { LayerKind::Guide => "guide", LayerKind::Folder => "folder", LayerKind::Camera => "camera", + LayerKind::Armature => "armature", LayerKind::Normal if masked_by.is_some() => "masked", LayerKind::Normal if guided_by.is_some() => "guided", LayerKind::Normal => "normal", @@ -326,11 +330,14 @@ pub(crate) fn insert_keyframe_at(layer: &mut Layer, frame: u32, copy: bool) -> R k.elements.clear(); k.tween = None; k.motion = None; + k.pose = anicraft_doc::Pose::default(); } } return Ok(()); } let elements = if copy { evaluate_layer_elements(layer, frame).map(|(_, e)| e.into_owned()) } else { None }; + // On an armature layer a copy keeps the pose the frame shows (tweened between keys). + let pose = if copy { anicraft_doc::armature::pose_at(layer, frame) } else { None }; // Past the end of a motion tween, a copy starts from how its object looks at the end. let last_state = match layer.keyframes.iter().rposition(|k| k.start < frame) { Some(i) if copy && layer.keyframe_index_at(frame).is_none() => { @@ -357,6 +364,7 @@ pub(crate) fn insert_keyframe_at(layer: &mut Layer, frame: u32, copy: bool) -> R nk.elements = elements.unwrap_or_default(); nk.tween = tween; nk.motion = motion; + nk.pose = pose.unwrap_or_default(); layer.keyframes.insert(i + 1, Arc::new(nk)); } None => { @@ -368,6 +376,7 @@ pub(crate) fn insert_keyframe_at(layer: &mut Layer, frame: u32, copy: bool) -> R if let Some(k) = layer.keyframe_mut(i) { if copy { nk.elements = last_state.unwrap_or_else(|| k.elements.clone()); + nk.pose = k.pose.clone(); } k.duration = frame - k.start; } diff --git a/crates/engine/src/confirm.rs b/crates/engine/src/confirm.rs index 53a2cba6..138d0fa0 100644 --- a/crates/engine/src/confirm.rs +++ b/crates/engine/src/confirm.rs @@ -156,6 +156,27 @@ pub fn confirmation(s: &Session, id: &str, p: &Value) -> Option { }) } "camera.remove" => camera_removal(s, s.doc.timeline(s.scene).camera_layer()?), + "bone.remove" => { + // The bone's moves in every pose go with it (ADR 0043); one pose loses nothing. + let id = anicraft_doc::BoneId(p.get("bone").and_then(Value::as_u64)?); + let l = s.doc.timeline(s.scene).layers.iter().find(|l| l.armature.as_ref().is_some_and(|a| a.bone(id).is_some()))?; + let arm = l.armature.as_deref()?; + let n = crate::cmds_bone::poses(l); + let below = arm.subtree(id).len().saturating_sub(1); + let name = arm.bone(id).map(|b| if b.name.is_empty() { "The bone".to_string() } else { format!("“{}”", b.name) })?; + (n > 1).then(|| Confirmation { + title: "Remove bone?".into(), + message: format!( + "{name}{} {} posed over {}; removing takes {} out of every pose. The instances stay where they are now, on a layer of their own. You can undo this.", + if below > 0 { format!(" and the {} below it", plural(below, "bone")) } else { String::new() }, + if below > 0 { "are" } else { "is" }, + plural(n, "keyframe"), + if below > 0 { "them" } else { "it" }, + ), + action: "Remove Bone".into(), + irreversible: false, + }) + } "layer.delete" => { let l = target_layer(s, p)?; if l.kind == anicraft_doc::LayerKind::Camera { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 466aa3ed..7318a1f5 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -6,6 +6,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] mod cmds_actions; +mod cmds_bone; pub mod cmds_brush; mod cmds_camera; mod cmds_draw; @@ -103,6 +104,7 @@ pub fn commands() -> Vec { v.extend(cmds_recovery::specs()); v.extend(cmds_timeline::specs()); v.extend(cmds_camera::specs()); + v.extend(cmds_bone::specs()); v.extend(cmds_motion::specs()); v.extend(cmds_hints::specs()); v.extend(cmds_scene::specs()); @@ -759,20 +761,24 @@ impl Session { /// The keyframe on the active layer that edits at the playhead should change. Creates a /// keyframe when the playhead is inside a tween (auto-key) or past the layer's end. pub(crate) fn editable_keyframe(&mut self) -> Result<&mut Keyframe> { - self.editable_keyframe_in(false) + self.editable_keyframe_in(KeyEdit::Artwork) } - /// [`Session::editable_keyframe`]; with `camera`, on the camera layer (which holds only the - /// camera: every other edit is refused there, ADR 0027). - pub(crate) fn editable_keyframe_in(&mut self, camera: bool) -> Result<&mut Keyframe> { + /// [`Session::editable_keyframe`] for `what`: the camera layer holds only the camera (ADR + /// 0027) and an armature layer only its posed armature (ADR 0043); every other edit is + /// refused there. + pub(crate) fn editable_keyframe_in(&mut self, what: KeyEdit) -> Result<&mut Keyframe> { let frame = self.frame; let tl = self.doc.timeline(self.scene); if let Some(l) = tl.layer(self.layer) { if l.kind == LayerKind::Folder { return Err(EngineError::State(format!("'{}' is a folder; pick a layer inside it to draw on", l.name))); } - if (l.kind == LayerKind::Camera) != camera { - return Err(EngineError::State(if camera { "that is not the camera layer".into() } else { format!("'{}' is the camera layer: it holds the camera, not artwork. Pick another layer to draw on, or move the camera with the Camera tool", l.name) })); + if (l.kind == LayerKind::Camera) != (what == KeyEdit::Camera) { + return Err(EngineError::State(if what == KeyEdit::Camera { "that is not the camera layer".into() } else { format!("'{}' is the camera layer: it holds the camera, not artwork. Pick another layer to draw on, or move the camera with the Camera tool", l.name) })); + } + if (l.kind == LayerKind::Armature) != (what == KeyEdit::Pose) { + return Err(EngineError::State(if what == KeyEdit::Pose { "that is not an armature layer".into() } else { format!("'{}' is an armature layer: it holds the armature's instances, posed by their bones. Drag a bone (or an instance) to pose it, drag the root instance to move it all, or pick another layer to draw on", l.name) })); } if tl.locked_by_folder(l.id) { return Err(EngineError::State(format!("layer '{}' is in a locked folder", l.name))); @@ -853,6 +859,17 @@ impl Session { } } +/// What [`Session::editable_keyframe_in`] is asked to edit. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum KeyEdit { + /// Artwork: any layer but the camera and armature layers. + Artwork, + /// The camera, on the camera layer. + Camera, + /// A pose, on an armature layer. + Pose, +} + /// Short human label for an element (properties panel, library, CLI). pub fn element_label(doc: &Document, e: &Element) -> String { let kind = match &e.kind { @@ -894,6 +911,8 @@ mod tests_script; #[cfg(test)] mod tests_camera; #[cfg(test)] +mod tests_bone; +#[cfg(test)] mod merge_tests; #[cfg(test)] mod raw_tests; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index eb3b8abb..1b72779f 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -597,6 +597,15 @@ fn panic_hunt_every_command() { json!({"text": "\u{0}\r\n]]>\u{202e}stop();", "language": "other", "class": "a.b", "base": "c", "symbol": 1}), json!({"text": "x".repeat(1 << 20), "language": 3, "class": "not a class", "base": ""}), json!({"text": "", "language": "ActionScript3", "class": "", "base": "Orphan"}), + // Bones (ADR 0043): the rigged session's bones are 100 and 102 (its armature layer 101), + // its instances 10–12. + json!({"bone": 102, "x": 1e30, "y": -1e30, "local": [1e9, "a"], "frame": 99_999}), + json!({"bone": 102, "x": 0, "y": 0, "local": [f64::MAX, 0], "angle": 1e9, "rotate_by": -1e9, "dx": 1e7, "dy": -1e7}), + json!({"bone": 100, "min": 400, "max": -400, "constrain": true, "pinned": "x"}), + json!({"bone": 100, "min": 10, "max": 10, "constrain": "yes", "pinned": true, "x": 250, "y": 250}), + json!({"from": 10, "to": 12, "head": [0, 0], "tail": [1e30, 0], "name": "x".repeat(300)}), + json!({"from": 12, "to": 10, "head": [5], "tail": "x", "bone": u64::MAX}), + json!({"from": 11, "to": 13, "head": [-1e6, 1e6], "layer": 101}), ]; // File commands are exercised separately (they touch the disk). let skip = |id: &str| id.starts_with("file."); @@ -630,7 +639,14 @@ fn panic_hunt_every_command() { for p in [json!({"x": 0, "y": 0, "w": 60, "h": 60}), json!({"x": 30, "y": 30, "w": 60, "h": 60, "fill": "#ff0000"}), json!({"x": 1, "y": 1, "w": 10, "h": 10, "radius": 5})] { raw.execute("draw.rect", &p).unwrap(); } - for start in [Session::default(), Session::new(sample::demo()), Session::new(with_sound), on_path, raw] { + // An armature: two bones, posed at two frames with a limit and a pin (ADR 0043). + let (mut rig, b1, b2) = crate::tests_bone::rigged(); + for (id, p) in [("bone.pose", json!({"bone": b1, "angle": 30, "frame": 8})), ("bone.set_limits", json!({"bone": b2, "min": -30, "max": 30})), ("bone.pin", json!({"bone": b1, "pinned": true}))] { + rig.execute(id, &p).unwrap(); + } + assert_eq!((b1, b2), (100, 102), "the hostile params name these bones"); + rig.set_frame(4); + for start in [Session::default(), Session::new(sample::demo()), Session::new(with_sound), on_path, raw, rig] { let mut s = start; for spec in commands().iter().filter(|c| !skip(c.id)) { for p in &hostile { diff --git a/crates/engine/src/tests_bone.rs b/crates/engine/src/tests_bone.rs new file mode 100644 index 00000000..bdf3b972 --- /dev/null +++ b/crates/engine/src/tests_bone.rs @@ -0,0 +1,255 @@ +//! Bones and inverse kinematics end to end (ADR 0043): building an armature with the Bone +//! tool's commands, posing by angle and by IK, pose tweens, limits and pins, removal, undo, +//! the file format, refusals, analytic renders and plug-in policy. + +use super::*; +use anicraft_doc::{BlendMode, ColorEffect, Document, ElementKind, LoopMode, Paint, Rgba, Shape, Stage, Symbol, SymbolId, SymbolKind, Timeline}; +use anicraft_geom::{Affine, Path}; +use anicraft_render::render_frame; +use serde_json::json; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + match s.execute(id, &p) { + Ok(v) => v, + Err(e) => panic!("{id} {p}: {e}"), + } +} + +pub(crate) const ROOT: u64 = 10; +pub(crate) const ARM: u64 = 11; +pub(crate) const HAND: u64 = 12; +const SHAPE: u64 = 13; + +/// A 500 × 300 stage, 20 frames, with three instances of a 100 × 10 black bar (registration at +/// its left end) along y = 100 from x = 100, 200 and 300, and a plain shape below them. +pub(crate) fn three_bars() -> Session { + let mut d = Document { stage: Stage { width: 500, height: 300, ..Stage::default() }, ..Document::default() }; + let bar = SymbolId(1); + let mut inner = Layer::new(LayerId(2), "bar"); + inner.keyframes[0] = Arc::new({ + let mut k = Keyframe::new(0, 1); + k.elements.push(Arc::new(Element { id: ElementId(3), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Shape(Shape::filled(Path::rect(0.0, -5.0, 100.0, 10.0), Paint::Solid(Rgba::BLACK))) })); + k + }); + d.library.push(Arc::new(Symbol { id: bar, name: "Bar".into(), kind: SymbolKind::Graphic, linkage: None, timeline: Timeline { layers: vec![Arc::new(inner)] } })); + let inst = |id: u64, x: f32| Arc::new(Element { id: ElementId(id), name: String::new(), transform: Affine::translate(x, 100.0), color: ColorEffect::default(), kind: ElementKind::Symbol { symbol: bar, loop_mode: LoopMode::Loop, first_frame: 0, blend: BlendMode::Normal, filters: Vec::new(), events: Vec::new() } }); + let shape = Arc::new(Element { id: ElementId(SHAPE), name: String::new(), transform: Affine::translate(100.0, 250.0), color: ColorEffect::default(), kind: ElementKind::Shape(Shape::filled(Path::rect(0.0, 0.0, 20.0, 20.0), Paint::Solid(Rgba::BLACK))) }); + 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![inst(ROOT, 100.0), inst(ARM, 200.0), inst(HAND, 300.0), shape]; + k + })]; + d.next_id = 100; + Session::new(d) +} + +/// [`three_bars`] rigged as a chain: shoulder (200, 100) → elbow (300, 100) → wrist (400, 100). +pub(crate) fn rigged() -> (Session, u64, u64) { + let mut s = three_bars(); + let b1 = run(&mut s, "bone.add", json!({"from": ROOT, "to": ARM, "head": [200, 100], "tail": [300, 100]}))["bone"].as_u64().unwrap(); + let b2 = run(&mut s, "bone.add", json!({"from": ARM, "to": HAND, "tail": [400, 100]}))["bone"].as_u64().unwrap(); + (s, b1, b2) +} + +fn bone_at(s: &mut Session, frame: u32, bone: u64) -> Value { + let v = run(s, "bone.info", json!({"frame": frame})); + v["armatures"][0]["bones"].as_array().unwrap().iter().find(|b| b["id"] == bone).cloned().unwrap() +} + +fn pt(v: &Value) -> Vec2 { + Vec2::new(v[0].as_f64().unwrap() as f32, v[1].as_f64().unwrap() as f32) +} + +fn transform_of(s: &Session, frame: u32, id: u64) -> Affine { + let tl = s.doc.timeline(s.scene); + tl.layers.iter().find_map(|l| evaluate_layer_elements(l, frame).and_then(|(_, e)| e.iter().find(|e| e.id.0 == id).map(|e| e.transform))).unwrap() +} + +#[test] +fn the_bone_tool_moves_instances_onto_an_armature_layer() { + let (mut s, b1, b2) = rigged(); + let tl = s.doc.timeline(0); + assert_eq!(tl.layers.len(), 2); + let arm = &tl.layers[0]; + assert_eq!(arm.kind, LayerKind::Armature); + assert_eq!(arm.name, "Armature_1"); + assert_eq!(s.layer, arm.id, "the armature layer is active"); + let ids: Vec = arm.keyframes[0].elements.iter().map(|e| e.id.0).collect(); + assert_eq!(ids, vec![ROOT, ARM, HAND]); + assert_eq!((arm.keyframes[0].start, arm.keyframes[0].duration), (0, 20), "the pose spans the timeline"); + let rest: Vec = tl.layers[1].keyframes[0].elements.iter().map(|e| e.id.0).collect(); + assert_eq!(rest, vec![SHAPE], "the instances left their layer; the shape stayed"); + // Nothing moved on the stage. + assert_eq!(transform_of(&s, 0, HAND), Affine::translate(300.0, 100.0)); + let b = bone_at(&mut s, 0, b2); + assert!(pt(&b["head"]).distance(Vec2::new(300.0, 100.0)) < 1e-3, "the second bone starts where the first ends"); + assert!(pt(&b["tail"]).distance(Vec2::new(400.0, 100.0)) < 1e-3); + assert_eq!(b["parent_bone"], b1); + assert_eq!(bone_at(&mut s, 0, b1)["parent_bone"], Value::Null); +} + +#[test] +fn bone_add_refuses_what_cant_be_joined() { + let mut s = three_bars(); + let bad = |s: &mut Session, p: Value| s.execute("bone.add", &p).unwrap_err().to_string(); + assert!(bad(&mut s, json!({"from": ROOT, "to": ROOT})).contains("two different")); + assert!(bad(&mut s, json!({"from": ROOT, "to": SHAPE})).contains("symbol")); + assert!(bad(&mut s, json!({"from": ROOT, "to": 999})).contains("no instance")); + assert!(bad(&mut s, json!({"from": ROOT})).contains("required")); + assert!(bad(&mut s, json!({"from": ROOT, "to": ARM, "head": [1, "x"]})).contains("[x, y]")); + run(&mut s, "bone.add", json!({"from": ROOT, "to": ARM})); + assert!(bad(&mut s, json!({"from": HAND, "to": ARM})).contains("armature"), "start on the armature"); + assert!(bad(&mut s, json!({"from": ARM, "to": ROOT})).contains("root")); + run(&mut s, "bone.add", json!({"from": ROOT, "to": HAND})); + assert!(bad(&mut s, json!({"from": ARM, "to": HAND})).contains("already")); + assert_eq!(s.history_len(), 2, "refusals leave no undo steps"); +} + +#[test] +fn ik_drags_reach_and_one_drag_is_one_undo_step() { + let (mut s, b1, b2) = rigged(); + let steps = s.history_len(); + s.begin_gesture("Drag Bone"); + let mut last = Value::Null; + for i in 0..=20 { + let t = i as f32 / 20.0; + last = run(&mut s, "bone.solve", json!({"bone": b2, "x": 400.0 - 100.0 * t, "y": 100.0 + 80.0 * t})); + } + s.end_gesture(); + assert_eq!(s.history_len(), steps + 1, "one drag, one undo step"); + assert_eq!(last["reached"], true, "{last}"); + let end = pt(&bone_at(&mut s, 0, b2)["tail"]); + assert!(end.distance(Vec2::new(300.0, 180.0)) < 0.5, "{end:?}"); + // The root stays where it was; the shoulder and elbow turned. + assert_eq!(transform_of(&s, 0, ROOT), Affine::translate(100.0, 100.0)); + assert!(bone_at(&mut s, 0, b1)["angle"].as_f64().unwrap().abs() > 1.0); + // An unreachable target: the chain points straight at it, the root still put. + let v = run(&mut s, "bone.solve", json!({"bone": b2, "x": 200, "y": 320})); + assert_eq!(v["reached"], false); + assert!(bone_at(&mut s, 0, b2)["angle"].as_f64().unwrap().abs() < 0.1, "straight"); + let tail = pt(&bone_at(&mut s, 0, b2)["tail"]); + assert!(tail.distance(Vec2::new(200.0, 300.0)) < 0.05, "{tail:?}"); + assert_eq!(transform_of(&s, 0, ROOT), Affine::translate(100.0, 100.0)); + s.undo().unwrap(); + s.undo().unwrap(); + assert_eq!(transform_of(&s, 0, HAND), Affine::translate(300.0, 100.0), "undo puts the pose back"); +} + +#[test] +fn limits_and_pins_hold_in_every_pose() { + let (mut s, b1, b2) = rigged(); + run(&mut s, "bone.pose", json!({"bone": b2, "angle": 60})); + let v = run(&mut s, "bone.set_limits", json!({"bone": b2, "min": -20, "max": 20})); + assert_eq!(v["constrain"], true); + assert!((bone_at(&mut s, 0, b2)["angle"].as_f64().unwrap() - 20.0).abs() < 1e-3, "the pose came inside the new limits"); + run(&mut s, "bone.solve", json!({"bone": b2, "x": 230, "y": 160})); + let a = bone_at(&mut s, 0, b2)["angle"].as_f64().unwrap(); + assert!((-20.0 - 1e-3..=20.0 + 1e-3).contains(&a), "{a}"); + assert!(s.execute("bone.set_limits", &json!({"bone": b2, "min": 30, "max": 10})).is_err()); + assert!(s.execute("bone.set_limits", &json!({"bone": b2, "min": -400})).is_err()); + run(&mut s, "bone.set_limits", json!({"bone": b2, "constrain": false})); + assert_eq!(bone_at(&mut s, 0, b2)["min"], Value::Null); + // Pinned: the shoulder keeps its angle while the elbow follows the drag. + let before = bone_at(&mut s, 0, b1)["angle"].as_f64().unwrap(); + run(&mut s, "bone.pin", json!({"bone": b1, "pinned": true})); + run(&mut s, "bone.solve", json!({"bone": b2, "x": 350, "y": 60})); + assert_eq!(bone_at(&mut s, 0, b1)["angle"].as_f64().unwrap(), before); + assert!(s.execute("bone.solve", &json!({"bone": b1, "x": 0, "y": 0})).unwrap_err().to_string().contains("pinned")); +} + +#[test] +fn poses_key_frames_and_tween_with_easing() { + let (mut s, b1, _) = rigged(); + run(&mut s, "bone.pose", json!({"bone": b1, "angle": 90, "frame": 10})); + let l = s.doc.timeline(0).layers[0].clone(); + assert_eq!(l.keyframes.iter().map(|k| k.start).collect::>(), vec![0, 10], "a pose keyed at frame 10"); + let a = |s: &mut Session, f| bone_at(s, f, b1)["angle"].as_f64().unwrap(); + assert_eq!(a(&mut s, 0), 0.0, "exact at the first key"); + assert!((a(&mut s, 10) - 90.0).abs() < 1e-4, "exact at the second key"); + assert!((a(&mut s, 5) - 45.0).abs() < 1e-3, "half way"); + // The hand rides the shoulder: at frame 10 it hangs straight down from it. + assert!(transform_of(&s, 10, HAND).translation().distance(Vec2::new(200.0, 200.0)) < 1e-3); + // The span's easing shapes the pose tween. + run(&mut s, "timeline.set_easing", json!({"frame": 0, "easing": "QuadIn"})); + assert!((a(&mut s, 5) - 22.5).abs() < 1e-3, "{}", a(&mut s, 5)); + // Posing inside the tween keys that frame with the pose it showed. + run(&mut s, "bone.pose", json!({"bone": b1, "rotate_by": 10, "frame": 5})); + assert!((a(&mut s, 5) - 32.5).abs() < 1e-3); + assert_eq!(s.doc.timeline(0).layers[0].keyframes.len(), 3); + // Moving the root moves the whole armature, in that pose. + run(&mut s, "bone.pose", json!({"dx": 10, "dy": 5, "frame": 10})); + assert!(transform_of(&s, 10, HAND).translation().distance(Vec2::new(210.0, 205.0)) < 1e-3); +} + +#[test] +fn artwork_edits_are_refused_on_the_armature_layer() { + let (mut s, _, _) = rigged(); + s.selection = vec![ElementId(HAND)]; + for (id, p) in [("draw.rect", json!({"x": 0, "y": 0, "w": 5, "h": 5})), ("element.translate", json!({"dx": 5, "dy": 0})), ("edit.delete", json!({})), ("timeline.create_motion_tween", json!({}))] { + let e = s.execute(id, &p).unwrap_err().to_string(); + assert!(e.contains("armature"), "{id}: {e}"); + } + assert!(s.execute("layer.set_type", &json!({"type": "normal"})).is_err()); +} + +#[test] +fn removing_bones_frees_the_instances_where_they_are() { + let (mut s, b1, b2) = rigged(); + run(&mut s, "bone.pose", json!({"bone": b1, "angle": 90})); + run(&mut s, "bone.pose", json!({"bone": b1, "angle": 0, "frame": 10})); + // Two poses: removing asks first (undoable tier). + let c = s.confirmation("bone.remove", &json!({"bone": b2})).unwrap(); + assert!(!c.irreversible && c.message.contains("2 keyframes"), "{}", c.message); + let hand = transform_of(&s, 0, HAND); + let v = run(&mut s, "bone.remove", json!({"bone": b2})); + assert_eq!(v["armature_removed"], false); + let tl = s.doc.timeline(0); + assert_eq!(tl.layers.len(), 3); + assert_eq!(tl.layers[1].keyframes[0].elements[0].id.0, HAND, "the hand is on a layer of its own"); + assert!(tl.layers[0].keyframes.iter().all(|k| k.pose.0.iter().all(|j| j.bone.0 != b2))); + assert_eq!(transform_of(&s, 0, HAND), hand, "where it was"); + // The last bone takes the armature with it; the instances stay as they look. + let arm = transform_of(&s, 0, ARM); + let v = run(&mut s, "bone.remove", json!({"bone": b1})); + assert_eq!(v["armature_removed"], true); + assert!(s.doc.timeline(0).layers.iter().all(|l| l.kind != LayerKind::Armature)); + assert_eq!(transform_of(&s, 0, ARM), arm); + s.undo().unwrap(); + s.undo().unwrap(); + assert_eq!(s.doc.timeline(0).layers[0].armature.as_ref().unwrap().bones.len(), 2); +} + +#[test] +fn armatures_survive_a_file_round_trip_and_render_the_pose() { + let (mut s, b1, b2) = rigged(); + run(&mut s, "bone.set_limits", json!({"bone": b2, "min": -45, "max": 45})); + run(&mut s, "bone.pin", json!({"bone": b1, "pinned": true})); + run(&mut s, "bone.pin", json!({"bone": b1, "pinned": false})); + run(&mut s, "bone.pose", json!({"bone": b1, "angle": 90, "frame": 10})); + let text = crate::format::to_json(&s.doc).unwrap(); + let back = crate::format::from_json(&text).unwrap(); + assert_eq!(back, s.doc); + for f in [0, 5, 10] { + assert_eq!(render_frame(&back, f, 1.0).unwrap().data, render_frame(&s.doc, f, 1.0).unwrap().data); + } + // At frame 10 the arm hangs from the shoulder: the bar covers (200, 150), not (250, 100). + let pm = render_frame(&s.doc, 10, 1.0).unwrap(); + assert!(pm.pixel(200, 150).unwrap()[0] < 0.1, "the arm points down"); + assert!(pm.pixel(250, 100).unwrap()[0] > 0.9, "and is no longer along the line"); + // Older files (no armature) load as before; a file's armature on another kind of layer is + // dropped. + let old = crate::format::from_json(&crate::format::to_json(&Document::default()).unwrap()).unwrap(); + assert!(old.timeline(0).layers.iter().all(|l| l.armature.is_none())); + let mut odd = s.doc.clone(); + Arc::make_mut(&mut odd.timeline_mut(0).layers[0]).kind = LayerKind::Normal; + let odd = crate::format::from_json(&crate::format::to_json(&odd).unwrap()).unwrap(); + assert!(odd.timeline(0).layers[0].armature.is_none()); +} + +#[test] +fn plug_ins_may_pose_armatures() { + for id in ["bone.add", "bone.remove", "bone.set_limits", "bone.pin", "bone.pose", "bone.solve", "bone.info"] { + assert!(crate::cmds_plugin::plugin_may_call(id).is_ok(), "{id}"); + } +} diff --git a/src/icons.rs b/src/icons.rs index 2c1fef4a..0140a399 100644 --- a/src/icons.rs +++ b/src/icons.rs @@ -66,11 +66,13 @@ pub enum Icon { SoundOff, Camera, Magnet, + Bone, } impl Icon { #[cfg(test)] - pub const ALL: [Icon; 52] = [ + pub const ALL: [Icon; 53] = [ + Icon::Bone, Icon::Magnet, Icon::SoundOff, Icon::Camera, @@ -196,6 +198,8 @@ impl Icon { Icon::Camera => ("anicraft-camera", false), // A horseshoe magnet, poles up (AniCraft original, on Lucide's grid): Snap to Objects. Icon::Magnet => ("anicraft-magnet", false), + // A bone: a wedge from its joint to its end (AniCraft original, on Lucide's grid). + Icon::Bone => ("anicraft-bone", false), Icon::FolderOpen => ("folder-open", false), } } @@ -250,6 +254,7 @@ static FILES: &[(&str, &str)] = &[ ("anicraft-eyedropper", include_str!("../assets/icons/anicraft-eyedropper.svg")), ("anicraft-masked", include_str!("../assets/icons/anicraft-masked.svg")), ("anicraft-camera", include_str!("../assets/icons/anicraft-camera.svg")), + ("anicraft-bone", include_str!("../assets/icons/anicraft-bone.svg")), ("folder", include_str!("../assets/icons/folder.svg")), ("folder-open", include_str!("../assets/icons/folder-open.svg")), ]; diff --git a/src/timeline.rs b/src/timeline.rs index 1edad23d..0814bd06 100644 --- a/src/timeline.rs +++ b/src/timeline.rs @@ -364,6 +364,10 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { type_icon(x0 + 7.0, Icon::Camera); x0 + 20.0 } + LayerKind::Armature => { + type_icon(x0 + 7.0, Icon::Bone); + x0 + 20.0 + } _ => x0 + 4.0, }; painter.text(pos2(name_x, left.center().y), Align2::LEFT_CENTER, &layer.name, font(Type::Body), name_color); @@ -408,6 +412,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { LayerKind::Mask => "mask layer", LayerKind::Guide => "guide layer", LayerKind::Camera => "camera layer", + LayerKind::Armature => "armature layer", LayerKind::Normal if masked => "masked layer", LayerKind::Normal => "layer", };