From 6e8749ff4ba4e2ab56cccd27ded36752a6cf95fd Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Fri, 13 Nov 2026 19:03:15 -0700 Subject: [PATCH] feat(engine): bone.paint_weights, bone.set_weight, and Subselection edits that reshape a bound shape at rest (M7) --- crates/doc/src/weights.rs | 5 +- crates/engine/src/cmds_bone.rs | 149 +++++++++++++++- crates/engine/src/cmds_path.rs | 135 +++++++------- crates/engine/src/lib.rs | 2 + crates/engine/src/tests_shape_weights.rs | 215 +++++++++++++++++++++++ 5 files changed, 440 insertions(+), 66 deletions(-) create mode 100644 crates/engine/src/tests_shape_weights.rs diff --git a/crates/doc/src/weights.rs b/crates/doc/src/weights.rs index 0bc87992..ec47f7f4 100644 --- a/crates/doc/src/weights.rs +++ b/crates/doc/src/weights.rs @@ -97,8 +97,9 @@ pub fn with_share(b: &Binding, bone: BoneId, w: f32, fallback: impl FnOnce() -> out } -/// The bones automatic binding gives a point at `p` (as drawn) leaving out `bone`. -fn others_at(segments: &[(BoneId, Vec2, Vec2)], bone: BoneId, p: Vec2) -> Vec { +/// 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(); 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 772f9b19..7236506d 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1129,6 +1129,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 merge_tests; diff --git a/crates/engine/src/tests_shape_weights.rs b/crates/engine/src/tests_shape_weights.rs new file mode 100644 index 00000000..b68c4e6a --- /dev/null +++ b/crates/engine/src/tests_shape_weights.rs @@ -0,0 +1,215 @@ +//! 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}"); + } +}