A drawing app built for agent/human collaboration
Rust
Bones and IK: fixes from review
Indicode BVb7cebd68249d
diff --git a/crates/app/src/editor.rs b/crates/app/src/editor.rsindex 970ca1e..d3d837e 100644--- a/crates/app/src/editor.rs+++ b/crates/app/src/editor.rs@@ -656,6 +656,7 @@ pub(crate) struct Editor {key_ease: klad_core::keys::Ease,bindings: crate::commands::Bindings,capturing: Option<Cmd>,+ keys_busy: bool,key_filter: String,selection: Option<String>,drag: Option<Drag>,@@ -831,6 +832,7 @@ impl Editor {key_ease: klad_core::keys::Ease::Linear,bindings: crate::commands::Bindings::default(),capturing: None,+ keys_busy: false,key_filter: String::new(),selection: None,drag: None,@@ -2158,6 +2160,9 @@ impl Editor {if self.tool != Tool::Pen {return self.commit_pen(false);}+ if self.keys_busy {+ return Ok(());+ }let (finish, cancel) = ui.input_mut(|i| {(i.consume_key(egui::Modifiers::NONE, Key::Enter),diff --git a/crates/app/src/editor/bones.rs b/crates/app/src/editor/bones.rsindex 95dc8a8..9af05e8 100644--- a/crates/app/src/editor/bones.rs+++ b/crates/app/src/editor/bones.rs@@ -6,7 +6,10 @@ use anyhow::{Context, Result, bail};use egui::{Color32, Key, Modifiers, Pos2, RichText, Vec2};use klad_core::doc::Kind;use klad_core::ops::{BendSpec, BoneSpec, IkSpec, Op, WeightsSpec};-use klad_core::rig::{Bend, Bone, CELL, Ik, Pose, Reach, Weights, applied, moved, painted, subtree, tips, weights_for};+use klad_core::rig::{+ Bend, Bone, CELL, Ik, Pose, Reach, Weights, applied, bent_against, limb_of, moved, near_degrees, painted, subtree,+ target_for_end, tips, weights_for,+};use std::collections::BTreeMap;use std::path::PathBuf;@@ -45,6 +48,7 @@ pub(super) struct Chain {pub head: [f32; 2],pub joined: bool,pub drawn: Vec<String>,+ pub undone: Vec<String>,pub to: Vec2,pub pressed: bool,}@@ -68,6 +72,7 @@ pub(super) struct BoneTool {pub root: [f32; 2],pub reach: BTreeMap<String, Reach>,pub loaded: Option<(u32, String, Option<Pose>)>,+ pub sent: bool,pub posing: Option<Posing>,pub name: String,pub heat: Option<(String, u64, egui::TextureHandle)>,@@ -87,6 +92,7 @@ impl Default for BoneTool {root: [0.0, 0.0],reach: BTreeMap::new(),loaded: None,+ sent: false,posing: None,name: String::new(),heat: None,@@ -112,15 +118,6 @@ fn at(p: [f32; 2]) -> Vec2 {Vec2::new(p[0], p[1])}-fn limb(bones: &[Bone], k: &Ik) -> Vec<String> {- let parent = bones- .iter()- .find(|b| b.name == k.bone)- .and_then(|b| b.parent.clone())- .filter(|_| k.chain == 2);- std::iter::once(k.bone.clone()).chain(parent).collect()-}-pub(super) fn pose_args(bundle: &std::path::Path, owner: &str, frame: u32, pose: &Pose) -> Vec<String> {let mut args = vec!["pose".to_string(),@@ -200,7 +197,8 @@ impl Editor {pub(super) fn bone_keys(&mut self, ui: &mut egui::Ui) {self.tend_chain();self.tend_pose();- if self.bones.chain.is_none() {+ self.tend_bone_pick();+ if self.bones.chain.is_none() || self.keys_busy {return;}let (enter, escape) = ui.input_mut(|i| {@@ -230,9 +228,23 @@ impl Editor {}let bones = self.rig_bones();let exists = |n: &str| bones.iter().any(|b| b.name == n);+ if chain.joined+ && chain.parent.as_deref().is_some_and(|p| !exists(p))+ && let Some(renamed) = bones+ .iter()+ .find(|b| (at(b.tail) - at(chain.head)).length() <= JOINED && !chain.drawn.contains(&b.name))+ {+ let (was, now) = (chain.parent.clone().unwrap_or_default(), renamed.name.clone());+ chain+ .drawn+ .iter_mut()+ .filter(|n| **n == was)+ .for_each(|n| *n = now.clone());+ chain.parent = Some(now);+ }if chain.parent.as_deref().is_some_and(|p| !exists(p)) {while chain.drawn.last().is_some_and(|n| !exists(n)) {- chain.drawn.pop();+ chain.undone.extend(chain.drawn.pop());}let Some(last) = chain.drawn.last() else {return;@@ -240,6 +252,16 @@ impl Editor {chain.parent = Some(last.clone());chain.joined = true;}+ while let Some(back) = chain.undone.last().cloned()+ && bones+ .iter()+ .any(|b| b.name == back && b.parent == chain.parent && b.parent.is_some())+ {+ chain.undone.pop();+ chain.drawn.push(back.clone());+ chain.parent = Some(back);+ chain.joined = true;+ }if chain.joined&& let Some(p) = chain.parent.as_ref().and_then(|p| bones.iter().find(|b| &b.name == p)){@@ -248,9 +270,27 @@ impl Editor {self.bones.chain = Some(chain);}+ fn tend_bone_pick(&mut self) {+ let Some(picked) = self.bones.selected.clone() else {+ return;+ };+ let bones = self.rig_bones();+ if bones.iter().any(|b| b.name == picked) {+ return;+ }+ let next = self+ .bones+ .chain+ .as_ref()+ .and_then(|c| c.parent.clone())+ .filter(|p| bones.iter().any(|b| &b.name == p));+ self.bones.name = next.clone().unwrap_or_default();+ self.bones.selected = next;+ self.bones.heat = None;+ }+fn tend_pose(&mut self) {- if self.bones.mode != Mode::Pose {- self.bones.loaded = None;+ if self.bones.posing.is_some() {return;}let Some(owner) = self.rig_owner() else {@@ -261,6 +301,18 @@ impl Editor {if self.bones.loaded.as_ref() == Some(&key) {return;}+ if self.bones.sent+ && self+ .bones+ .loaded+ .as_ref()+ .is_some_and(|(f, o, _)| (*f, o) == (key.0, &key.1))+ {+ self.bones.sent = false;+ self.bones.loaded = Some(key);+ return;+ }+ self.bones.sent = false;let pose = stored.unwrap_or_default();self.bones.pose = pose.angles;self.bones.root = pose.root;@@ -316,6 +368,7 @@ impl Editor {head: if sibling { made.head } else { made.tail },joined: !sibling || joined(made),drawn,+ undone: Vec::new(),to: at(made.tail),pressed: false,});@@ -332,7 +385,7 @@ impl Editor {if let Some(c) = self.bones.chain.as_mut() {c.pressed = false;}- if (chain.to - at(chain.head)).length() * self.zoom() < CLICK {+ if (chain.to - at(chain.head)).length() * self.zoom() <= NEAR {self.end_chain();return Ok(());}@@ -348,28 +401,72 @@ impl Editor {self.rig_ik().into_iter().filter(|k| self.bones.reach.get(&k.bone).is_some_and(|r| r.mix > 0.0))- .find(|k| limb(&bones, k).iter().any(|b| b == name))+ .find(|k| limb_of(&bones, k).iter().any(|b| b == name)).map(|k| k.bone)}- fn ik_on(&mut self, end: &str) {- let bones = self.rig_bones();- let Some(i) = bones.iter().position(|b| b.name == end) else {- return;+ fn ik_on(&mut self, end: &str) -> Option<[f32; 2]> {+ let (bones, ik) = (self.rig_bones(), self.rig_ik());+ let shown = self.shown_pose();+ let target = target_for_end(&bones, &ik, &shown, end)?;+ if bent_against(&bones, &ik, &shown, end) {+ let side = match ik.iter().find(|k| k.bone == end).map(|k| k.bend) {+ Some(Bend::Counterclockwise) => "counterclockwise",+ _ => "clockwise",+ };+ self.say(+ Tone::Info,+ format!(+ "{end}'s IK bends {side}, so the joint turns over to that side; flip it in draw mode's IK menu"+ ),+ );+ }+ self.bones.reach.insert(end.to_string(), Reach { target, mix: 1.0 });+ Some(target)+ }++ fn neighbour_turns(&self, end: &str) -> BTreeMap<String, f32> {+ let (bones, ik) = (self.rig_bones(), self.rig_ik());+ let Some(owner) = self.rig_owner().and_then(|o| self.scene.bundle.doc.layer(&o).cloned()) else {+ return BTreeMap::new();};- let tip = tips(&bones, &self.rig_ik(), &self.shown_pose())[i].1;- self.bones- .reach- .insert(end.to_string(), Reach { target: tip, mix: 1.0 });+ let frame = self.scene.frame;+ let here = self.stored_pose(&owner.id).map(|p| p.rest);+ let limb: Vec<String> = ik+ .iter()+ .find(|k| k.bone == end)+ .map(|k| limb_of(&bones, k))+ .unwrap_or_default();+ painted(&owner)+ .first()+ .and_then(|l| {+ l.cels()+ .iter()+ .filter(|c| c.frame < frame)+ .filter_map(|c| c.pose.as_ref())+ .rfind(|p| here.as_ref().is_none_or(|r| &p.rest == r))+ .cloned()+ })+ .map(|p| applied(&bones, &ik, &p))+ .unwrap_or_default()+ .into_iter()+ .filter(|(b, _)| limb.contains(b))+ .collect()}fn ik_off(&mut self, end: &str) {let (bones, ik) = (self.rig_bones(), self.rig_ik());let solved = applied(&bones, &ik, &self.shown_pose());+ let before = self.neighbour_turns(end);if let Some(k) = ik.iter().find(|k| k.bone == end) {- limb(&bones, k).into_iter().for_each(|b| {+ limb_of(&bones, k).into_iter().for_each(|b| {if let Some(v) = solved.get(&b) {- self.bones.pose.insert(b, *v);+ let to = before+ .get(&b)+ .or_else(|| self.bones.pose.get(&b))+ .copied()+ .unwrap_or(0.0);+ self.bones.pose.insert(b, near_degrees(*v, to));}});}@@ -527,12 +624,10 @@ impl Editor {}).min_by(|a, b| a.0.total_cmp(&b.0));if !alt && let Some((_, end, target)) = handle {- let target = self- .bones- .reach- .entry(end.clone())- .or_insert(Reach { target, mix: 1.0 })- .target;+ let target = match self.bones.reach.get(&end) {+ Some(r) => r.target,+ None => self.ik_on(&end).unwrap_or(target),+ };self.bones.posing = Some(Posing::Reach(end.clone(), at(target) - c));self.pick_bone(Some(end));return;@@ -622,7 +717,39 @@ impl Editor {}}+ fn flush_name(&mut self) -> Result<()> {+ let Some(picked) = self.bones.selected.clone() else {+ return Ok(());+ };+ let to = self.bones.name.trim().to_string();+ let bones = self.rig_bones();+ if to.is_empty()+ || to == picked+ || !bones.iter().any(|b| b.name == picked)+ || bones.iter().any(|b| b.name == to)+ {+ return Ok(());+ }+ self.bone_edit(|s| {+ s.rename = Some(picked.clone());+ s.to_name = Some(to.clone());+ })?;+ if let Some(Drag {+ what: Dragging::Bone(n, _) | Dragging::New(Some(n)),+ ..+ }) = self.bones.drag.as_mut()+ && *n == picked+ {+ *n = to.clone();+ }+ self.bones.selected = Some(to);+ Ok(())+ }+pub(super) fn bone_up(&mut self) -> Result<()> {+ if self.bones.mode == Mode::Draw {+ self.flush_name()?;+ }match self.bones.mode {Mode::Draw if self.bones.chain.is_some() => self.chain_up()?,Mode::Draw => {@@ -712,6 +839,7 @@ impl Editor {},failure: |_, err| super::tweens::failure(err),});+ self.bones.sent = true;Ok(())}@@ -732,7 +860,7 @@ impl Editor {match ik.iter().find(|k| k.bone == picked) {Some(k) => {let label = match (k.chain, &parent) {- (2, Some(p)) => format!("IK: limb with {p}"),+ (2, Some(_)) => "IK: limb".to_string(),_ => "IK: aim".to_string(),};ui.menu_button(label, |ui| {@@ -799,7 +927,12 @@ impl Editor {}}).response- .hint("this bone's IK: in pose mode, drag its end and the limb follows");+ .hint(match (k.chain, &parent) {+ (2, Some(p)) => {+ format!("this bone's IK, a limb with {p}: in pose mode, drag its end and the limb follows")+ }+ _ => "this bone's IK, an aim: in pose mode, drag its end and the bone points there".to_string(),+ });}None => {ui.menu_button("add IK", |ui| {@@ -863,7 +996,6 @@ impl Editor {.clicked(){self.bones.mode = *mode;- self.bones.loaded = None;self.bones.posing = None;}});@@ -879,7 +1011,10 @@ impl Editor {let r = ui.add(egui::TextEdit::singleline(&mut self.bones.name).desired_width(110.0)).labelled_by(label.id)- .hint("the picked bone's name; Return renames it");+ .hint(match self.bones.chain {+ Some(_) => "the picked bone's name; Return renames it",+ None => "the picked bone's name; Return renames it. Drag its ends or middle to move it; alt drag from its end starts a chain from there; a drag on empty canvas starts a new chain",+ });if r.lost_focus() && self.bones.name.trim() != picked && !self.bones.name.trim().is_empty() {let to = self.bones.name.trim().to_string();run = Some(Box::new(move |e| {@@ -903,21 +1038,20 @@ impl Editor {}));}}- let (hint, more) = match (&self.bones.chain, &self.bones.selected) {- (Some(_), _) => (+ let said = match (&self.bones.chain, &self.bones.selected) {+ (Some(_), _) => Some(("click: the next bone; Esc: done","each click places the next bone of the chain; shift as you let go starts the next one from the same joint; Esc, Enter, a right click or a click on the chain's open end ends it",- ),- (None, Some(_)) => (- "drag its ends or middle; alt drag: a child",- "drag an end or the middle to move it; alt drag from its end starts a chain from there; a drag on empty canvas starts a new chain",- ),- (None, None) => (+ )),+ (None, Some(_)) => None,+ (None, None) => Some(("drag to draw a chain of bones","a drag draws a bone and the chain carries on from its end: each click adds the next; click a bone to pick it",- ),+ )),};- ui.label(RichText::new(hint).color(theme::WEAK)).hint(more);+ if let Some((hint, more)) = said {+ ui.label(RichText::new(hint).color(theme::WEAK)).hint(more);+ }}Mode::Weights => {ui.add(@@ -996,7 +1130,7 @@ impl Editor {.bones.selected.as_ref()- .and_then(|p| ik.iter().find(|k| limb(&bones, k).contains(p)))+ .and_then(|p| ik.iter().find(|k| limb_of(&bones, k).contains(p))).map(|k| k.bone.clone());let how = "drag a bone's end to turn it; drag the end of an IK limb and the limb reaches for it; drag a root bone's head to move the whole while IK ends stay; alt drag turns a bone by hand, taking its limb off IK";match held {@@ -1010,7 +1144,9 @@ impl Editor {.changed(){match on {- true => self.ik_on(&end),+ true => {+ self.ik_on(&end);+ }false => self.ik_off(&end),}}@@ -1222,7 +1358,7 @@ impl Editor {let held: Vec<String> = ik.iter().filter(|k| pose.ik.get(&k.bone).is_some_and(|r| r.mix > 0.0))- .flat_map(|k| limb(&bones, k))+ .flat_map(|k| limb_of(&bones, k)).collect();bones.iter().zip(&shown).for_each(|(b, (h, t))| {let (a, z) = (place(at(*h)), place(at(*t)));@@ -1302,6 +1438,7 @@ impl Editor {}if editing&& self.bones.drag.is_none()+ && self.bones.chain.is_none()&& let Some(p) = hover{let cursor = match (self.modifiers.alt, self.grip_at(p)) {diff --git a/crates/app/src/editor/panels.rs b/crates/app/src/editor/panels.rsindex 038e21e..a88f9d9 100644--- a/crates/app/src/editor/panels.rs+++ b/crates/app/src/editor/panels.rs@@ -73,6 +73,10 @@ impl Editor {lock(&self.stats).frame_ms.push(dt * 1000.0);}self.pointer = ui.input(|i| i.pointer.latest_pos()).or(self.pointer);+ self.keys_busy = ctx.egui_wants_keyboard_input()+ || self.palette.is_some()+ || self.windows.settings+ || self.capturing.is_some();self.check(|e| e.sync());self.tend_jobs();self.check(|e| e.tab_keys());diff --git a/crates/app/src/editor/ui_tests.rs b/crates/app/src/editor/ui_tests.rsindex 8b21098..6e86436 100644--- a/crates/app/src/editor/ui_tests.rs+++ b/crates/app/src/editor/ui_tests.rs@@ -3370,6 +3370,20 @@ fn bones_are_drawn_as_a_chain_that_fans_ends_and_takes_back_its_last_bone() {h.key_press_modifiers(Modifiers::COMMAND, Key::Z);h.run_steps(3);assert_eq!(bones(&h).len(), 2, "cmd Z takes back the last bone");+ assert_eq!(+ h.state().bones.selected.as_deref(),+ Some("bone 2"),+ "and picks the one the chain goes on from"+ );+ h.key_press_modifiers(Modifiers::COMMAND | Modifiers::SHIFT, Key::Z);+ h.run_steps(3);+ assert_eq!(+ h.state().bones.chain.as_ref().and_then(|c| c.parent.clone()).as_deref(),+ Some("bone 3"),+ "redo brings the chain back to the bone it brought back"+ );+ h.key_press_modifiers(Modifiers::COMMAND, Key::Z);+ h.run_steps(3);let again = canvas_at(&h, 230.0, 40.0);click_with(&mut h, again, Modifiers::NONE);let redrawn = bones(&h);@@ -3380,11 +3394,11 @@ fn bones_are_drawn_as_a_chain_that_fans_ends_and_takes_back_its_last_bone() {"and the chain carries on from the one before");assert_eq!(redrawn[2].head, redrawn[1].tail);- let joint = canvas_at(&h, redrawn[2].tail[0], redrawn[2].tail[1]);+ let joint = canvas_at(&h, redrawn[2].tail[0], redrawn[2].tail[1]) + vec2(7.0, 0.0);click_with(&mut h, joint, Modifiers::NONE);assert!(h.state().bones.chain.is_none(),- "a click on the open end ends the chain"+ "a click on the open end's ring ends the chain");assert_eq!(bones(&h).len(), 3);let (root, hand) = (canvas_at(&h, 400.0, 300.0), canvas_at(&h, 400.0, 220.0));@@ -3433,6 +3447,89 @@ fn bones_are_drawn_as_a_chain_that_fans_ends_and_takes_back_its_last_bone() {let _ = std::fs::remove_dir_all(&cli);}+#[test]+fn a_bone_renamed_while_its_chain_is_drawn_stays_the_parent_of_the_next() {+ let path = sample("chain-rename");+ let mut h = harness(editor(&path), vec2(1440.0, 1000.0));+ activate(&mut h, "lines");+ h.key_press(Key::J);+ h.run_steps(2);+ let bones = |h: &Harness<'static, Editor>| h.state().scene.bundle.doc.layer("l6").unwrap().bones.clone();+ let (a, b, c) = (+ canvas_at(&h, 40.0, 40.0),+ canvas_at(&h, 120.0, 80.0),+ canvas_at(&h, 200.0, 90.0),+ );+ drag(&mut h, a, b);+ h.run_steps(2);+ h.state_mut().bones.name = "thigh".into();+ drag(&mut h, c, c + vec2(1.0, 1.0));+ h.run_steps(2);+ let made = bones(&h);+ assert_eq!(made[0].name, "thigh", "the name typed in the field is kept: {made:?}");+ assert_eq!(+ made[1].parent.as_deref(),+ Some("thigh"),+ "and the chain carries on from it"+ );+ assert_eq!(made[1].head, made[0].tail);+ let _ = std::fs::remove_dir_all(&path);+}++#[test]+fn return_and_esc_go_to_the_palette_while_a_chain_is_drawn() {+ let path = sample("chain-keys");+ let mut h = harness(editor(&path), vec2(1440.0, 1000.0));+ activate(&mut h, "lines");+ h.key_press(Key::J);+ h.run_steps(2);+ let (a, b) = (canvas_at(&h, 40.0, 40.0), canvas_at(&h, 120.0, 80.0));+ drag(&mut h, a, b);+ h.run_steps(2);+ h.key_press_modifiers(Modifiers::COMMAND, Key::K);+ h.run_steps(2);+ assert!(h.state().palette.is_some());+ h.key_press(Key::Escape);+ h.run_steps(2);+ assert!(h.state().palette.is_none(), "Esc closes the palette");+ assert!(h.state().bones.chain.is_some(), "and leaves the chain alone");+ let _ = std::fs::remove_dir_all(&path);+}++#[test]+fn the_bone_options_stay_one_row_whatever_is_picked() {+ let path = sample("bone-bar");+ Bundle::open(&path)+ .unwrap()+ .apply(+ &parse_lines(+ r#"{"op":"bone","layer":"l6","chain":["thigh","shin"],"through":[[100,60],[100,160],[110,260]]}+{"op":"ik","layer":"l6","add":"shin"}"#,+ )+ .unwrap(),+ )+ .unwrap();+ [vec2(1280.0, 800.0), vec2(1440.0, 900.0), vec2(1512.0, 982.0)]+ .into_iter()+ .for_each(|size| {+ let mut h = harness(editor(&path), size);+ activate(&mut h, "lines");+ h.key_press(Key::J);+ h.run_steps(3);+ let top = h.state().canvas_rect.min.y;+ ["thigh", "shin"].into_iter().for_each(|bone| {+ h.state_mut().pick_bone(Some(bone.into()));+ h.run_steps(3);+ assert_eq!(+ h.state().canvas_rect.min.y,+ top,+ "{size:?}: picking {bone} keeps the canvas where it is"+ );+ });+ });+ let _ = std::fs::remove_dir_all(&path);+}+#[test]fn a_leg_gets_its_ik_in_the_options_and_its_foot_is_dragged_and_planted_in_pose_mode() {let path = sample("leg-ik");@@ -3459,7 +3556,7 @@ fn a_leg_gets_its_ik_in_the_options_and_its_foot_is_dragged_and_planted_in_pose_assert_eq!(ik.len(), 1, "{ik:?}");assert_eq!((ik[0].bone.as_str(), ik[0].chain), ("shin", 2));assert!(- h.query_by_label_contains("IK: limb with thigh").is_some(),+ h.query_by_label_contains("IK: limb").is_some(),"the options show the bone's IK");h.get_by_label("pose").click();@@ -3502,6 +3599,14 @@ fn a_leg_gets_its_ik_in_the_options_and_its_foot_is_dragged_and_planted_in_pose_(root[0] - 30.0).abs() < 1.5 && (root[1] - 10.0).abs() < 1.5,"the root's head moves it all: {root:?}");+ h.get_by_label("draw").click();+ h.run_steps(2);+ h.get_by_label("pose").click();+ h.run_steps(2);+ assert!(+ h.state().bones.reach.contains_key("shin") && h.state().bones.root == root,+ "a trip to draw mode keeps the pose being built"+ );let planted = shown(&h)[1].1;assert!((planted[0] - target[0]).abs() < 0.01 && (planted[1] - target[1]).abs() < 0.01,diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rsindex 51c2890..7e2819a 100644--- a/crates/cli/src/main.rs+++ b/crates/cli/src/main.rs@@ -1852,7 +1852,15 @@ fn mark_transform(fn parse_numbers(text: &str) -> Result<Vec<f32>> {text.split(',')- .map(|v| v.trim().parse::<f32>().map_err(|e| anyhow!("{v:?}: {e}")))+ .map(|v| {+ v.trim()+ .parse::<f32>()+ .map_err(|e| anyhow!("{v:?}: {e}"))+ .and_then(|n| match n.is_finite() {+ true => Ok(n),+ false => Err(anyhow!("{v:?} is not a number klad can draw with")),+ })+ }).collect()}diff --git a/crates/cli/src/rig.rs b/crates/cli/src/rig.rsindex 0938a20..d3d8297 100644--- a/crates/cli/src/rig.rs+++ b/crates/cli/src/rig.rs@@ -269,26 +269,24 @@ pub fn list(bundle: &Bundle, as_json: bool) -> Result<()> {.iter().filter_map(|c| c.pose.as_ref().map(|p| (c, p))).for_each(|(c, p)| {- let angles: Vec<String> = p.angles.iter().map(|(k, v)| format!("{k}={v}")).collect();- let root = match p.root == [0.0, 0.0] {- true => String::new(),- false => format!(" root {},{}", p.root[0], p.root[1]),- };- let targets: Vec<String> =- p.ik.iter()- .map(|(k, r)| match r.mix == 1.0 {- true => format!(" target {k}={},{}", r.target[0], r.target[1]),- false => format!(" target {k}={},{} mix {}", r.target[0], r.target[1], r.mix),- })+ let mut said: Vec<String> = p.angles.iter().map(|(k, v)| format!("{k}={v}")).collect();+ if p.root != [0.0, 0.0] {+ said.push(format!("root {},{}", p.root[0], p.root[1]));+ }+ p.ik.iter().for_each(|(k, r)| {+ said.push(match r.mix == 1.0 {+ true => format!("target {k}={},{}", r.target[0], r.target[1]),+ false => format!("target {k}={},{} mix {}", r.target[0], r.target[1], r.mix),+ })+ });+ if !p.ik.is_empty() && !o.ik.is_empty() {+ let solved: Vec<String> = applied(&o.bones, &o.ik, p)+ .iter()+ .map(|(k, v)| format!("{k}={v:.2}")).collect();- println!(- " pose {} at {} from {}: {}{root}{}",- c.id,- c.frame,- p.rest,- angles.join(" "),- targets.concat()- );+ said.push(format!("solved {}", solved.join(" ")));+ }+ println!(" pose {} at {} from {}: {}", c.id, c.frame, p.rest, said.join(" "));})});});@@ -489,6 +487,10 @@ mod tests {values.iter().any(|v| (v - wanted).abs() < 1e-3),"the rig exports the solved turn {wanted}: {values:?}");+ assert!(+ text.contains("NodePath(\"Skeleton2D/upper:position\")") && text.contains("Vector2(140, 170)"),+ "the root move goes to Godot too, so the planted end stays put there"+ );edit(&dir, r#"{"op":"ik","layer":"l1","rm":"fore"}"#).unwrap();let bundle = Bundle::open(&dir).unwrap();let kept = bundlediff --git a/crates/cli/src/scene.rs b/crates/cli/src/scene.rsindex c6342a6..01ee590 100644--- a/crates/cli/src/scene.rs+++ b/crates/cli/src/scene.rs@@ -405,6 +405,33 @@ pub fn rig(path: &Path, dir: Option<PathBuf>) -> Result<Vec<PathBuf>> {values.iter().map(|v| real(*v)).collect::<Vec<_>>().join(", "))})+ .chain(+ bones+ .iter()+ .enumerate()+ .filter(|(_, b)| b.parent.as_ref().is_none_or(|p| !bones.iter().any(|o| &o.name == p)))+ .enumerate()+ .map(|(k, (i, b))| {+ let j = bones.len() + k;+ let values: Vec<String> = poses+ .iter()+ .map(|(_, p)| {+ format!(+ "Vector2({}, {})",+ number(b.head[0] + p.root[0]),+ number(b.head[1] + p.root[1])+ )+ })+ .collect();+ format!(+ "tracks/{j}/type = \"value\"\ntracks/{j}/imported = false\ntracks/{j}/enabled = true\ntracks/{j}/path = NodePath(\"Skeleton2D/{}:position\")\ntracks/{j}/interp = 0\ntracks/{j}/loop_wrap = true\ntracks/{j}/keys = {{\n\"times\": {},\n\"transitions\": {},\n\"update\": 0,\n\"values\": [{}]\n}}\n",+ paths[i],+ floats(×),+ floats(&vec![1.0; times.len()]),+ values.join(", ")+ )+ }),+ ).collect();format!("[sub_resource type=\"Animation\" id=\"Animation_{k}\"]\nresource_name = {}\nlength = {}\nloop_mode = {}\nstep = {}\n{tracks}\n",diff --git a/crates/cli/tests/binary.rs b/crates/cli/tests/binary.rsindex 5082c9e..a393b8d 100644--- a/crates/cli/tests/binary.rs+++ b/crates/cli/tests/binary.rs@@ -308,7 +308,26 @@ fn a_chain_and_its_ik_are_set_up_and_posed_from_the_command_line() {listed.contains("ik shin: a limb with thigh, bending counterclockwise, softness 4 px"),"{listed}");- assert!(listed.contains("root -10,0 target shin=180,240 mix 0.5"), "{listed}");+ assert!(+ listed.contains("root -10,0 target shin=180,240 mix 0.5 solved shin="),+ "{listed}"+ );+ let nan = Command::new(env!("CARGO_BIN_EXE_klad"))+ .args([+ "pose",+ path,+ "l1",+ "--from",+ "0",+ "--to",+ "4",+ "--target",+ "shin=nan,240",+ ])+ .output()+ .unwrap();+ assert!(!nan.status.success(), "a target that is not a number is refused");+ klad(&["ls", path]);let json: serde_json::Value = serde_json::from_str(&klad(&["bones", path, "--json"])).unwrap();assert_eq!(json[0]["ik"][0]["bone"], "shin");assert!(json[0]["poses"][0]["solved"]["thigh"].is_number());diff --git a/crates/core/src/doc.rs b/crates/core/src/doc.rsindex edd70bd..770b9be 100644--- a/crates/core/src/doc.rs+++ b/crates/core/src/doc.rs@@ -1228,6 +1228,13 @@ impl Document {{bail!("layer {}: depth {depth} must be 0 or more", layer.id);}+ layer+ .cels()+ .iter()+ .filter_map(|c| c.pose.as_ref().map(|p| (c, p)))+ .try_for_each(|(c, p)| {+ crate::rig::check_pose(p).with_context(|| format!("layer {}: cel {}", layer.id, c.id))+ })?;if !layer.bones.is_empty() || !layer.ik.is_empty() {if !matches!(layer.kind(), Kind::Paint | Kind::Group) {bail!("layer {}: bones go on a paint layer or a group", layer.id);diff --git a/crates/core/src/ops.rs b/crates/core/src/ops.rsindex b073a06..2582cba 100644--- a/crates/core/src/ops.rs+++ b/crates/core/src/ops.rs@@ -31,8 +31,11 @@ const LAYER_KEYS: &[&str] = &["adjust","depth","reference",+ "bones",+ "ik",+ "keys",];-const CEL_KEYS: &[&str] = &["id", "frame", "hold", "link", "tween", "nodes"];+const CEL_KEYS: &[&str] = &["id", "frame", "hold", "link", "tween", "nodes", "parts", "pose"];const NODE_KEYS: &[&str] = &["id","name",@@ -44,10 +47,13 @@ const NODE_KEYS: &[&str] = &["blur","clip","visible",+ "keys",];const TRANSFORM_KEYS: &[&str] = &["x", "y", "rotate", "sx", "sy", "pivot"];const STROKE_KEYS: &[&str] = &["paint", "width", "cap", "join", "dash"];-const STRUCTURE: &[&str] = &["id", "kind", "type", "cels", "children", "nodes", "mask"];+const STRUCTURE: &[&str] = &[+ "id", "kind", "type", "cels", "children", "nodes", "mask", "bones", "ik", "keys", "pose", "parts",+];fn shape_keys(kind: &str) -> Result<&'static [&'static str]> {Ok(match kind {@@ -1789,12 +1795,25 @@ fn bone(doc: &mut Document, spec: &BoneSpec, out: &mut Applied) -> Result<()> {.filter(|c| gone.contains(&c.bone)).map(|c| c.bone.clone()).collect();- bake(doc, &path, &bones, &ik, &held);+ let also = bake(doc, &path, &bones, &ik, &held, &gone);ik.retain(|c| !held.contains(&c.bone));bones.retain(|b| !gone.contains(&b.name));+ crate::doc::family_paths(doc, &path).iter().for_each(|p| {+ if let Some(cels) = doc.layer_at_mut(p).cels_mut() {+ cels.iter_mut().filter_map(|c| c.pose.as_mut()).for_each(|pose| {+ pose.angles.retain(|b, _| !gone.contains(b));+ pose.ik.retain(|b, _| !gone.contains(b));+ });+ }+ });out.notes.push(match held.is_empty() {true => format!("removed {}", gone.join(", ")),- false => format!("removed {} and the IK on {}", gone.join(", "), held.join(", ")),+ false => format!(+ "removed {} and the IK on {}{}",+ gone.join(", "),+ held.join(", "),+ kept_note(&also)+ ),});}(None, None, Some(name), None, None) => {@@ -1859,18 +1878,24 @@ fn bone(doc: &mut Document, spec: &BoneSpec, out: &mut Applied) -> Result<()> {_ => bail!("a bone op takes one of add, chain, rm, rename, move or reparent"),}crate::rig::check(&bones)?;- let broken: Vec<String> = ik+ let broken: Vec<(String, String)> = ik.iter()- .filter(|c| crate::rig::check_ik(&bones, std::slice::from_ref(c)).is_err())- .map(|c| c.bone.clone())+ .filter_map(|c| {+ crate::rig::check_ik(&bones, std::slice::from_ref(c))+ .err()+ .map(|e| (c.bone.clone(), e.to_string()))+ }).collect();if !broken.is_empty() {- bake(doc, &path, &before, &ik, &broken);- ik.retain(|c| !broken.contains(&c.bone));- out.notes.push(format!(- "removed the IK on {}: its limb no longer has a parent to turn (its poses keep their look as turns)",- broken.join(", ")- ));+ let names: Vec<String> = broken.iter().map(|(b, _)| b.clone()).collect();+ let also = bake(doc, &path, &before, &ik, &names, &[]);+ ik.retain(|c| !names.contains(&c.bone));+ broken.iter().for_each(|(_, why)| {+ out.notes.push(format!(+ "removed {why}{}; the poses that used it keep its turns, but its limb changed: pose them again",+ kept_note(&also)+ ))+ });}crate::rig::check_ik(&bones, &ik)?;let layer = doc.layer_at_mut(&path);@@ -1880,40 +1905,100 @@ fn bone(doc: &mut Document, spec: &BoneSpec, out: &mut Applied) -> Result<()> {Ok(())}-fn bake(doc: &mut Document, path: &[usize], bones: &[crate::rig::Bone], ik: &[crate::rig::Ik], held: &[String]) {+fn bake(+ doc: &mut Document,+ path: &[usize],+ bones: &[crate::rig::Bone],+ ik: &[crate::rig::Ik],+ held: &[String],+ gone: &[String],+) -> Vec<String> {+ use crate::rig::{applied, limb_of, near_degrees};if held.is_empty() {- return;+ return Vec::new();}- let driven: Vec<String> = ik- .iter()- .filter(|c| held.contains(&c.bone))- .flat_map(|c| {- let parent = bones- .iter()- .find(|b| b.name == c.bone)- .and_then(|b| b.parent.clone())- .filter(|_| c.chain == 2);- std::iter::once(c.bone.clone()).chain(parent)- })- .collect();+ let shares = |x: &crate::rig::Ik, y: &crate::rig::Ik| {+ let mine = limb_of(bones, x);+ limb_of(bones, y).iter().any(|b| mine.contains(b))+ };+ let mut also = BTreeSet::new();crate::doc::family_paths(doc, path).iter().for_each(|p| {- if let Some(cels) = doc.layer_at_mut(p).cels_mut() {- cels.iter_mut()- .filter_map(|c| c.pose.as_mut())- .filter(|pose| held.iter().any(|h| pose.ik.contains_key(h)))- .for_each(|pose| {- let solved = crate::rig::applied(bones, ik, pose);- driven.iter().for_each(|b| {- if let Some(v) = solved.get(b) {- pose.angles.insert(b.clone(), *v);+ let Some(cels) = doc.layer_at_mut(p).cels_mut() else {+ return;+ };+ let mut shown: BTreeMap<String, BTreeMap<String, f32>> = BTreeMap::new();+ cels.iter_mut().filter_map(|c| c.pose.as_mut()).for_each(|pose| {+ let solved = applied(bones, ik, pose);+ let mut looks = solved.clone();+ if held.iter().any(|h| pose.ik.contains_key(h)) {+ let active: Vec<&crate::rig::Ik> = ik.iter().filter(|c| pose.ik.contains_key(&c.bone)).collect();+ let mut part: Vec<&crate::rig::Ik> =+ active.iter().copied().filter(|c| held.contains(&c.bone)).collect();+ loop {+ let more: Vec<&crate::rig::Ik> = active+ .iter()+ .copied()+ .filter(|c| !part.iter().any(|q| q.bone == c.bone) && part.iter().any(|q| shares(q, c)))+ .collect();+ if more.is_empty() {+ break;+ }+ part.extend(more);+ }+ let before = shown.get(&pose.rest);+ part.iter()+ .flat_map(|c| limb_of(bones, c))+ .filter(|b| !gone.contains(b))+ .for_each(|b| {+ if let Some(v) = solved.get(&b) {+ let to = before+ .and_then(|m| m.get(&b))+ .or_else(|| pose.angles.get(&b))+ .copied()+ .unwrap_or(0.0);+ let kept = near_degrees(*v, to);+ looks.insert(b.clone(), kept);+ pose.angles.insert(b, kept);}});- held.iter().for_each(|h| {- pose.ik.remove(h);- });+ part.iter().for_each(|c| {+ pose.ik.remove(&c.bone);+ if !held.contains(&c.bone) {+ also.insert(c.bone.clone());+ }});- }+ }+ shown.insert(pose.rest.clone(), looks);+ });});+ also.into_iter().collect()+}++fn kept_note(also: &[String]) -> String {+ match also.is_empty() {+ true => String::new(),+ false => format!(+ "; the IK on {} shares a bone with it, so its targets in those poses became turns too",+ also.join(", ")+ ),+ }+}++fn posed_with(doc: &Document, path: &[usize], bone: &str) -> Vec<u32> {+ let mut frames: Vec<u32> = crate::doc::family_paths(doc, path)+ .iter()+ .flat_map(|p| {+ doc.layer_at(p)+ .cels()+ .iter()+ .filter(|c| c.pose.as_ref().is_some_and(|pose| pose.ik.contains_key(bone)))+ .map(|c| c.frame)+ .collect::<Vec<_>>()+ })+ .collect();+ frames.sort_unstable();+ frames.dedup();+ frames}fn ik(doc: &mut Document, spec: &IkSpec, out: &mut Applied) -> Result<()> {@@ -2000,17 +2085,27 @@ fn ik(doc: &mut Document, spec: &IkSpec, out: &mut Applied) -> Result<()> {c.chain = spec.chain.unwrap_or(c.chain);c.bend = bend(c.bend, rest);c.softness = spec.softness.unwrap_or(c.softness);- out.notes.push(said(c));+ let made = said(c);+ let using = posed_with(doc, &path, name);+ out.notes.push(match using.is_empty() {+ true => made,+ false => format!(+ "{made}; the poses at {} solve with it now, but their drawings are bent the old way: pose them again (klad pose) and remake their in-betweens",+ using.iter().map(|f| format!("frame {f}")).collect::<Vec<_>>().join(", ")+ ),+ });}(None, None, Some(name)) => {find(&ik, name)?;if spec.chain.is_some() || spec.bend.is_some() || spec.softness.is_some() {bail!("rm takes no chain, bend or softness");}- bake(doc, &path, &bones, &ik, std::slice::from_ref(name));+ let also = bake(doc, &path, &bones, &ik, std::slice::from_ref(name), &[]);ik.retain(|c| &c.bone != name);- out.notes- .push(format!("removed the IK on {name}; its poses keep their look as turns"));+ out.notes.push(format!(+ "removed the IK on {name}; its poses keep their look as turns{}",+ kept_note(&also)+ ));}_ => bail!("an ik op takes one of add, set or rm"),}@@ -3570,6 +3665,130 @@ mod tests {assert_eq!(solved["thigh"], baked.angles["thigh"]);}+ fn leg_with(lines: &[Value]) -> (Document, String, Vec<usize>) {+ let doc = base();+ let ink = doc.find_layer("ink").unwrap().id.clone();+ let mut all = vec![+ json!({"op":"bone","layer":ink,"chain":["thigh","shin","foot"],"through":[[100,100],[100,200],[90,300],[140,300]]}),+ ];+ all.extend(lines.iter().cloned().map(|mut l| {+ l["layer"] = json!(ink);+ l+ }));+ let (doc, _) = apply_all(&doc, &ops(&all)).unwrap();+ let path = layer_path(&doc, &ink).unwrap();+ (doc, ink, path)+ }++ fn posed(doc: &mut Document, path: &[usize], at: usize, pose: crate::rig::Pose) {+ doc.layer_at_mut(path).cels_mut().unwrap()[at].pose = Some(pose);+ }++ fn reach(pairs: &[(&str, [f32; 2], f32)]) -> crate::rig::Pose {+ crate::rig::Pose {+ rest: "c0".into(),+ ik: pairs+ .iter()+ .map(|(b, t, m)| (b.to_string(), crate::rig::Reach { target: *t, mix: *m }))+ .collect(),+ ..Default::default()+ }+ }++ #[test]+ fn removing_one_of_two_iks_on_a_shared_bone_keeps_the_pose() {+ use crate::rig::tips;+ [("foot", 1.0), ("shin", 1.0), ("foot", 0.5), ("shin", 0.5)]+ .into_iter()+ .for_each(|(gone, mix)| {+ let (mut doc, ink, path) =+ leg_with(&[json!({"op":"ik","add":"shin"}), json!({"op":"ik","add":"foot"})]);+ posed(+ &mut doc,+ &path,+ 0,+ reach(&[("shin", [150.0, 180.0], 1.0), ("foot", [180.0, 240.0], mix)]),+ );+ let layer = doc.layer(&ink).unwrap();+ let before = tips(&layer.bones, &layer.ik, layer.cels()[0].pose.as_ref().unwrap());+ let (doc, made) = apply_all(&doc, &ops(&[json!({"op":"ik","layer":ink,"rm":gone})])).unwrap();+ let layer = doc.layer(&ink).unwrap();+ let after = tips(&layer.bones, &layer.ik, layer.cels()[0].pose.as_ref().unwrap());+ assert!(+ before+ .iter()+ .zip(&after)+ .all(|(a, b)| (a.1[0] - b.1[0]).abs() < 1e-2 && (a.1[1] - b.1[1]).abs() < 1e-2),+ "removing {gone} at mix {mix}: {before:?} {after:?}"+ );+ assert!(+ made.notes.iter().any(|n| n.contains("shares a bone")),+ "{:?}",+ made.notes+ );+ });+ }++ #[test]+ fn baked_turns_stay_the_short_way_between_poses() {+ let (mut doc, ink, path) = leg_with(&[json!({"op":"ik","add":"shin"})]);+ let at = |frame: u32, id: &str| crate::doc::Cel {+ id: id.into(),+ frame,+ ..doc.layer(&ink).unwrap().cels()[0].clone()+ };+ let (four, eight) = (at(4, "k4"), at(8, "k8"));+ doc.layer_at_mut(&path).cels_mut().unwrap().extend([four, eight]);+ posed(&mut doc, &path, 1, reach(&[("shin", [70.0, -300.0], 1.0)]));+ posed(&mut doc, &path, 2, reach(&[("shin", [130.0, -300.0], 1.0)]));+ let (doc, _) = apply_all(&doc, &ops(&[json!({"op":"ik","layer":ink,"rm":"shin"})])).unwrap();+ let cels = doc.layer(&ink).unwrap().cels();+ let turn = |i: usize, b: &str| cels[i].pose.as_ref().unwrap().angles[b];+ ["thigh", "shin"].iter().for_each(|b| {+ assert!(+ (turn(1, b) - turn(2, b)).abs() < 180.0,+ "{b}: {} then {}, so an in-between goes the short way",+ turn(1, b),+ turn(2, b)+ )+ });+ }++ #[test]+ fn removing_a_bone_takes_its_turns_out_of_the_poses_and_set_still_works_on_rigs() {+ let (mut doc, ink, path) = leg_with(&[json!({"op":"ik","add":"shin"})]);+ let mut pose = reach(&[("shin", [150.0, 180.0], 1.0)]);+ pose.angles.insert("foot".into(), 12.0);+ posed(&mut doc, &path, 0, pose);+ let cel = doc.layer(&ink).unwrap().cels()[0].id.clone();+ let (doc, _) = apply_all(+ &doc,+ &ops(&[+ json!({"op":"set","id":ink,"opacity":0.5,"name":"leg"}),+ json!({"op":"set","id":cel,"hold":3}),+ ]),+ )+ .unwrap();+ assert_eq!(+ doc.layer(&ink).unwrap().opacity,+ 0.5,+ "set works on a layer with bones and IK"+ );+ assert!(+ apply_all(&doc, &ops(&[json!({"op":"set","id":ink,"ik":[]})])).is_err(),+ "but cannot write the IK itself"+ );+ let (doc, _) = apply_all(&doc, &ops(&[json!({"op":"bone","layer":ink,"rm":"shin"})])).unwrap();+ let kept = doc.layer(&ink).unwrap().cels()[0].pose.clone().unwrap();+ assert!(+ kept.angles.keys().all(|b| b == "thigh") && kept.ik.is_empty(),+ "only the thigh's turn is left: {kept:?}"+ );+ let mut doc = doc;+ posed(&mut doc, &path, 0, reach(&[("thigh", [f32::NAN, 1.0], 1.0)]));+ assert!(doc.validate().is_err(), "a target that is not a number is never saved");+ }+#[test]fn layers_and_nodes_get_ids_and_land_where_asked() {let doc = base();diff --git a/crates/core/src/rig.rs b/crates/core/src/rig.rsindex b6e4f55..9f04039 100644--- a/crates/core/src/rig.rs+++ b/crates/core/src/rig.rs@@ -120,36 +120,54 @@ fn is_origin(p: &[f32; 2]) -> bool {p[0] == 0.0 && p[1] == 0.0}+pub fn near_degrees(angle: f32, to: f32) -> f32 {+ to + ((angle - to + 180.0).rem_euclid(360.0) - 180.0)+}++pub fn limb_of(bones: &[Bone], c: &Ik) -> Vec<String> {+ let parent = bones+ .iter()+ .find(|b| b.name == c.bone)+ .and_then(|b| b.parent.clone())+ .filter(|_| c.chain == 2);+ std::iter::once(c.bone.clone()).chain(parent).collect()+}++fn as_turns(bones: &[Bone], ik: &[Ik], keyed: &mut Pose, other: &Pose, ends: &[&Ik]) {+ let solved = applied(bones, ik, keyed);+ ends.iter().for_each(|c| {+ limb_of(bones, c).into_iter().for_each(|b| {+ if let Some(v) = solved.get(&b) {+ let to = other.angles.get(&b).copied().unwrap_or(0.0);+ keyed.angles.insert(b, near_degrees(*v, to));+ }+ });+ keyed.ik.remove(&c.bone);+ });+}+pub fn between(bones: &[Bone], ik: &[Ik], a: &Pose, b: &Pose, t: f32) -> Pose {let lerp = |x: f32, y: f32| x + (y - x) * t;- let names: std::collections::BTreeSet<&String> = a.angles.keys().chain(b.angles.keys()).collect();- let end = |pose: &Pose, bone: &str| {- bones- .iter()- .position(|o| o.name == bone)- .map_or([0.0, 0.0], |i| tips(bones, ik, pose)[i].1)+ let (mut a, mut b) = (a.clone(), b.clone());+ let only = |p: &Pose, q: &Pose| -> Vec<&Ik> {+ ik.iter()+ .filter(|c| p.ik.contains_key(&c.bone) && !q.ik.contains_key(&c.bone))+ .collect()};+ let (in_a, in_b) = (only(&a, &b), only(&b, &a));+ if !in_a.is_empty() {+ let other = b.clone();+ as_turns(bones, ik, &mut a, &other, &in_a);+ }+ if !in_b.is_empty() {+ let other = a.clone();+ as_turns(bones, ik, &mut b, &other, &in_b);+ }+ let names: std::collections::BTreeSet<String> = a.angles.keys().chain(b.angles.keys()).cloned().collect();let reaches = ik.iter().filter_map(|c| {- let (x, y) = match (a.ik.get(&c.bone), b.ik.get(&c.bone)) {- (None, None) => return None,- (Some(x), Some(y)) => (x.clone(), y.clone()),- (Some(x), None) => (- x.clone(),- Reach {- target: end(b, &c.bone),- mix: 0.0,- },- ),- (None, Some(y)) => (- Reach {- target: end(a, &c.bone),- mix: 0.0,- },- y.clone(),- ),- };+ let (x, y) = (a.ik.get(&c.bone)?, b.ik.get(&c.bone)?);Some((c.bone.clone(),Reach {@@ -164,8 +182,9 @@ pub fn between(bones: &[Bone], ik: &[Ik], a: &Pose, b: &Pose, t: f32) -> Pose {angles: names.into_iter().map(|n| {- let at = |p: &Pose| p.angles.get(n).copied().unwrap_or(0.0);- (n.clone(), lerp(at(a), at(b)))+ let at = |p: &Pose| p.angles.get(&n).copied().unwrap_or(0.0);+ let v = lerp(at(&a), at(&b));+ (n, v)}).collect(),root: [lerp(a.root[0], b.root[0]), lerp(a.root[1], b.root[1])],@@ -173,6 +192,55 @@ pub fn between(bones: &[Bone], ik: &[Ik], a: &Pose, b: &Pose, t: f32) -> Pose {}}+pub fn target_for_end(bones: &[Bone], ik: &[Ik], pose: &Pose, bone: &str) -> Option<[f32; 2]> {+ let c = ik.iter().find(|c| c.bone == bone)?;+ let end = bones.iter().position(|b| b.name == bone)?;+ let shown = tips(bones, ik, pose);+ let tip = shown[end].1;+ let Some(a) = parent_of(bones, end).filter(|_| c.chain == 2) else {+ return Some(tip);+ };+ let (upper, lower) = (&bones[a], &bones[end]);+ let l1 = libm::hypot(+ (lower.head[0] - upper.head[0]) as f64,+ (lower.head[1] - upper.head[1]) as f64,+ );+ let reach = l1 + lower.length() as f64;+ let softness = c.softness as f64;+ let s = shown[a].0;+ let (dx, dy) = ((tip[0] - s[0]) as f64, (tip[1] - s[1]) as f64);+ let r = libm::hypot(dx, dy);+ if softness <= 0.0 || r <= reach - softness || r < NEAR {+ return Some(tip);+ }+ let d = match r >= reach {+ true => reach + softness,+ false => reach - softness + 2.0 * softness * (1.0 - ((reach - r) / softness).sqrt()),+ };+ Some([(s[0] as f64 + dx * d / r) as f32, (s[1] as f64 + dy * d / r) as f32])+}++pub fn bent_against(bones: &[Bone], ik: &[Ik], pose: &Pose, bone: &str) -> bool {+ let Some(c) = ik.iter().find(|c| c.bone == bone && c.chain == 2) else {+ return false;+ };+ let Some(end) = bones.iter().position(|b| b.name == bone) else {+ return false;+ };+ let Some(a) = parent_of(bones, end) else {+ return false;+ };+ let shown = tips(bones, ik, pose);+ let (s, e, q) = (shown[a].0, shown[end].0, shown[end].1);+ let first = libm::atan2((e[1] - s[1]) as f64, (e[0] - s[0]) as f64);+ let second = libm::atan2((q[1] - e[1]) as f64, (q[0] - e[0]) as f64);+ let kappa = wrap(second - first);+ match c.bend {+ Bend::Clockwise => kappa < -RAD,+ Bend::Counterclockwise => kappa > RAD,+ }+}+pub fn check(bones: &[Bone]) -> Result<()> {bones.iter().enumerate().try_for_each(|(i, b)| {if b.name.trim().is_empty() {@@ -186,6 +254,9 @@ pub fn check(bones: &[Bone]) -> Result<()> {{bail!("bone {}: its parent {p} must come before it", b.name);}+ if !b.head.iter().chain(&b.tail).all(|v| v.is_finite()) {+ bail!("bone {}: its head and tail must be numbers", b.name);+ }if b.length() < 1e-3 {bail!("bone {}: its head and tail are the same point", b.name);}@@ -193,6 +264,27 @@ pub fn check(bones: &[Bone]) -> Result<()> {})}+pub fn check_pose(pose: &Pose) -> Result<()> {+ if let Some((bone, _)) = pose.angles.iter().find(|(_, a)| !a.is_finite()) {+ bail!("pose: the turn of {bone} must be a number");+ }+ if !pose.root.iter().all(|v| v.is_finite()) {+ bail!("pose: root must be two numbers");+ }+ pose.ik.iter().try_for_each(|(bone, r)| {+ if !r.target.iter().all(|v| v.is_finite()) {+ bail!("pose: the target of {bone} must be two numbers");+ }+ if !(0.0..=1.0).contains(&r.mix) {+ bail!(+ "pose: the mix of {bone} goes from 0 (its turns) to 1 (the target), not {}",+ r.mix+ );+ }+ Ok(())+ })+}+pub fn check_ik(bones: &[Bone], ik: &[Ik]) -> Result<()> {ik.iter().enumerate().try_for_each(|(i, c)| {let Some(at) = bones.iter().position(|b| b.name == c.bone) else {@@ -1266,6 +1358,91 @@ mod tests {);}+ #[test]+ fn a_limb_handed_over_from_one_key_never_jumps_whatever_its_mix() {+ let bones = vec![+ bone("upper", None, [300.0, 300.0], [400.0, 300.0]),+ bone("fore", Some("upper"), [400.0, 300.0], [500.0, 300.0]),+ ];+ let ik = vec![limb_on("fore", Bend::Clockwise, 0.0)];+ let mut b = Pose::default();+ b.angles.insert("upper".into(), -150.0);+ [1.0, 0.5].into_iter().for_each(|mix| {+ let a = reaching(&[("fore", [150.0, 300.0], mix)]);+ let at = |t: f32| end_of(&bones, &ik, &between(&bones, &ik, &a, &b, t), "fore");+ assert!(+ apart(at(0.0), end_of(&bones, &ik, &a, "fore")) < 0.01,+ "mix {mix}: starts as the key shows"+ );+ assert!(+ apart(at(1.0), end_of(&bones, &ik, &b, "fore")) < 0.01,+ "mix {mix}: ends on the other key"+ );+ let path: Vec<[f32; 2]> = (0..=400).map(|i| at(i as f32 / 400.0)).collect();+ let step = path.windows(2).map(|w| apart(w[0], w[1])).fold(0.0, f32::max);+ assert!(step < 3.0, "mix {mix}: the hand never jumps, at most {step} px a step");+ });+ }++ #[test]+ fn a_target_made_at_a_limbs_end_moves_nothing_even_with_softness() {+ let straight = vec![+ bone("thigh", None, [300.0, 100.0], [300.0, 200.0]),+ bone("shin", Some("thigh"), [300.0, 200.0], [300.0, 300.0]),+ ];+ let bent = vec![+ straight[0].clone(),+ bone("shin", Some("thigh"), [300.0, 200.0], [320.0, 297.0]),+ ];+ [(&straight, 20.0), (&bent, 20.0), (&bent, 0.0)]+ .into_iter()+ .for_each(|(bones, softness)| {+ let ik = vec![limb_on("shin", rest_bend(bones, "shin"), softness)];+ let fk = tips(bones, &ik, &Pose::default());+ let target = target_for_end(bones, &ik, &Pose::default(), "shin").unwrap();+ let held = tips(bones, &ik, &reaching(&[("shin", target, 1.0)]));+ assert!(+ held.iter()+ .zip(&fk)+ .all(|(a, b)| apart(a.0, b.0) < 1e-3 && apart(a.1, b.1) < 1e-3),+ "softness {softness}: {held:?} {fk:?}"+ );+ });+ let ik = vec![limb_on("shin", Bend::Clockwise, 0.0)];+ let mut against = Pose::default();+ against.angles.insert("thigh".into(), 20.0);+ against.angles.insert("shin".into(), -40.0);+ assert!(+ bent_against(&straight, &ik, &against, "shin"),+ "a knee turned the other way is noticed"+ );+ let mut along = Pose::default();+ along.angles.insert("shin".into(), 40.0);+ assert!(!bent_against(&straight, &ik, &along, "shin"));+ }++ #[test]+ fn poses_that_are_not_numbers_or_mix_out_of_range_are_refused() {+ let good = reaching(&[("shin", [1.0, 2.0], 0.5)]);+ assert!(check_pose(&good).is_ok());+ let wrong = |pose: Pose| check_pose(&pose).unwrap_err().to_string();+ assert!(wrong(reaching(&[("shin", [f32::NAN, 2.0], 1.0)])).contains("target of shin"));+ assert!(wrong(reaching(&[("shin", [1.0, 2.0], 7.0)])).contains("mix of shin"));+ assert!(+ wrong(Pose {+ root: [f32::INFINITY, 0.0],+ ..Pose::default()+ })+ .contains("root")+ );+ let mut turned = Pose::default();+ turned.angles.insert("thigh".into(), f32::NAN);+ assert!(wrong(turned).contains("thigh"));+ let mut far = bone("far", None, [0.0, 0.0], [1.0, 0.0]);+ far.tail[0] = f32::INFINITY;+ assert!(check(&[far]).is_err());+ }+#[test]fn the_solver_gives_the_same_numbers_everywhere() {let bones = vec![diff --git a/docs/DESIGN.md b/docs/DESIGN.mdindex f799bff..aa85ca7 100644--- a/docs/DESIGN.md+++ b/docs/DESIGN.md@@ -247,7 +247,7 @@ Every layer has `blend`, `opacity`, `visible`, `locked`, optional `mask`, `clip`- **Foliage (M5, S5.27).** `foliage` is a shape op (CLI only, principle 7): each closed shape becomes a clump built from leaf strokes on a jittered grid, each coloured from the clump lit as a round form (a normal from its bounding ellipse, mixed with the normal of an optional `mass` shape so clumps turn with the whole crown, a key light or a lamp, the underside darker) and stepped into three value families between `shade`, `color` and `lit` (OKLab; by default darker and cooler, lighter and warmer), with more variety in the light; then leaves along the outline, kept more where the outline faces the light or the sky, a few in `glow` on the shadow edge. Strokes are sorted dark to light so lit leaves land on top. It puts how foliage is painted (light families on the clump, the big mass before the texture, a broken silhouette) into one op, so an agent does not scatter leaves like confetti.- **No agent inside the editor (M8).** A first version ran a model in an Agent pane with the user's Claude API key; it was removed on 2026-11-06 in favour of an MCP server that any agent client can use (planned). Agents work on a drawing through the `klad` CLI, and the person reaches them through notes, the selection and the shared history.- **Rigs (M6).** A paint layer or a group gets `bones` (format 9): each a name, an optional parent that comes before it, a head and a tail in canvas px. A group's skeleton poses every paint layer in it together, so a character's lines, colour and shading layers stay in step. Each bone has a weight map in `weights/<owner>.weights` (zstd: a JSON header with the grid size and bone names, then one byte per cell per bone, cells of 4 px), written by `Bundle::apply` with the edit and kept in its history step; weights are normalised across bones when read (bilinear between cells), and a place no bone weighs follows the nearest bone. Automatic weights are 1/(d + 0.15 L + 1)^3 by distance to each bone segment (L its length), so joints blend over a short stretch; `set` paints soft dabs (smoothstep falloff towards a value), `part` gives a named part's cells to one bone at 1 and the others 0, `smooth` blurs every map once. A pose (`pose` on a cel: its rest drawing's id, an angle per bone in degrees from rest, a root move) is linear blend skinning: each bone's rest matrix (head, angle) and posed matrix (its parent's posed matrix times the rest offset times its turn) give a skin matrix, and every stroke sample moves by the weighted sum; stroke sizes scale by the mean local stretch (the Jacobian's determinant, square-rooted); polygon fills move their points; flood fills are warped through a 4 px triangle mesh over their coverage (each posed triangle rasterised, sampling the rest coverage by barycentric position). The rest pose returns the marks untouched. `pose` (computed by the CLI, `cli/src/rig.rs`) makes or re-poses a drawing at `to` on every paint layer under the skeleton from the rest drawing shown at `from` (a posed drawing's own rest when `from` shows one). In-betweens of two poses of one rest drawing (or a pose and its rest) mix the angles and root by t instead of matching strokes (`rig::posed_pair`), and keep the mixed pose. A bone `move` with a `tail` takes along the heads of the children that start at the old tail (within half a pixel), and `by` moves a bone with all its children (`rig::moved`, which the editor also draws while dragging). The editor's bone tool (J) has three modes (draw, weights, pose) and in every mode a skeleton list in its options (each bone under its parent; picking one highlights it on the canvas); with no skeleton on the active layer the options name the layers and groups that have one, each a button that makes it active. Picking on the canvas is a click in draw and pose mode and cmd click (ctrl outside macOS) in weights mode. In draw mode a drag on empty canvas draws a root bone and starts a chain (S6.9, as Spine's create tool makes the new bone the next one's parent, but welded: Spine has no snapping and its users have asked for it): the next bone runs from the last tail to the pointer and each release (a click or a drag) adds it, its head exactly on that tail, so `rig::moved` and the joint grips treat it as a joint; shift as you let go keeps the joint and parent for the next bone (a fan); Esc, Enter, a right click, a click on the open end, or a change of mode, tool or skeleton owner ends it; a chain only commits on a release whose press reached the canvas, and each bone is its own undo step, so after cmd Z the chain (checked every frame against the bones) carries on from the last bone still there. With no chain, a press on a bone picks it and drags what is under the pointer (the picked bone shows handles at both ends): an end moves that end, the middle moves the bone and its children, and the head of a child that starts at its parent's tail is that joint, so dragging it moves the parent's tail; alt drag from a tail starts a chain from it (from a bone's middle, a child starting there); the options rename, reparent (a parent menu without the bone's own children), add or change the picked bone's IK, and remove. Draw and weights modes show the skeleton at rest. Weights are painted in the editor's own process (`klad_core::rig::weights_for`) over a tint of the picked bone's map, and pose mode turns bones, committing the pose (angles, root and targets) through `klad pose` as a job; it loads the pose of the frame shown again whenever the frame, the owner or that pose changes; the drawing is not deformed live while posing, only the skeleton.-- **IK (M6, S6.10).** Taken from Spine (constraints on one or two bones, a bend side, softness, a mix, solved parent first, posing a limb by its end) with two changes: a target is a point kept in each pose (`pose.ik`), not a bone, because klad bones carry weight maps and go to Godot as `Bone2D`s, and constraints are ordered by the skeleton itself (the limb's top bone, then its bone), so there is no order to keep by hand. Constraints (`layer.ik`: bone, chain 1 or 2, bend, softness) live on the skeleton; a pose without a target for one leaves that limb to its angles, so adding a constraint changes no pose, and removing one (or a bone it holds, or a reparent that leaves a limb without its parent, which drops it as Spine does) first writes its solved turns into the angles of every pose that used it (`ops::bake`), so those poses keep their look. `rig::applied` solves (f64, libm): FK frames from the angles and root, then per constraint an aim (atan2 to the target) or a limb by two circles meeting (the upper segment runs from the parent's head to the bone's head, so a child that starts off its parent's tail is exact), with Spine-like softness as a quadratic ease into full reach (r = d - (d - L + s)^2 / 4s between L - s and L + s, smooth at both ends, straight at L + s), and the mix along the short way round from the angle. `skinning`, `tips` and `Rig::new` take the constraints, so every place a pose bends a drawing or draws a skeleton (the CLI's poses, in-betweens, the bones overlay, the Godot export's rotation tracks, the editor) uses the solved turns. In-betweens mix the targets, not the solved angles: a 100 + 100 px leg whose hip moves 120 px over a planted foot keeps the foot exactly with mixed targets and pushes it 9.7 px through the floor with mixed angles (`rig::tests`). Joint limits, stretch and chains of three or more bones (Spine refuses them: the result would depend on earlier frames) are not built. The editor's pose mode: a press near an IK limb's end or its target drags the target (making one at the end, so nothing jumps, when the pose had none); near a root bone's head moves the root, the targets staying where they are; on a bone an IK holds moves its target with the pointer; anywhere else it turns the bone, and alt turns a bone by hand after writing its limb's solved turns into the angles (IK off). The options show an IK switch and a mix for the picked bone's limb.+- **IK (M6, S6.10).** Taken from Spine (constraints on one or two bones, a bend side, softness, a mix, solved parent first, posing a limb by its end) with two changes: a target is a point kept in each pose (`pose.ik`), not a bone, because klad bones carry weight maps and go to Godot as `Bone2D`s, and constraints are ordered by the skeleton itself (the limb's top bone, then its bone), so there is no order to keep by hand. Constraints (`layer.ik`: bone, chain 1 or 2, bend, softness) live on the skeleton; a pose without a target for one leaves that limb to its angles, so adding a constraint changes no pose, and removing one (or a bone it holds) first writes its solved turns into the angles of every pose that used it (`ops::bake`, in frame order, each turn within half a turn of the pose before, so in-betweens made later go the short way), so those poses keep their look; where another IK in the same pose shares a bone with it, that one's target becomes turns too, since no stored turn survives a second solve. A bone edit that breaks a limb (a reparent that leaves it without a parent, a move that puts its head on its parent's head) drops the IK as Spine does and writes its turns, but the limb changed, so those poses need posing again, and the note says so; `ik --set` also lists the poses that now solve differently from how their drawings were bent. `rig::applied` solves (f64, libm): FK frames from the angles and root, then per constraint an aim (atan2 to the target) or a limb by two circles meeting (the upper segment runs from the parent's head to the bone's head, so a child that starts off its parent's tail is exact), with Spine-like softness as a quadratic ease into full reach (r = d - (d - L + s)^2 / 4s between L - s and L + s, smooth at both ends, straight at L + s), and the mix along the short way round from the angle. `skinning`, `tips` and `Rig::new` take the constraints, so every place a pose bends a drawing or draws a skeleton (the CLI's poses, in-betweens, the bones overlay, the Godot export's rotation tracks, the editor) uses the solved turns. In-betweens mix the targets, not the solved angles: a 100 + 100 px leg whose hip moves 120 px over a planted foot keeps the foot exactly with mixed targets and pushes it 9.7 px through the floor with mixed angles (`rig::tests`). A constraint in one key only is handed over as turns: that key's limb takes its solved turns, each within half a turn of the other key's, and the in-betweens turn it (fading the IK out instead flipped elbows when the solve and the angles stored under it were over half a turn apart). Pose values that are not finite, and mixes outside 0 to 1, are refused by `Document::validate`, since JSON would store them as null. Joint limits, stretch and chains of three or more bones (Spine refuses them: the result would depend on earlier frames) are not built. The editor's pose mode: a press near an IK limb's end or its target drags the target (making one where the solve gives back the limb as shown, `rig::target_for_end`, which inverts the softness ease, so nothing jumps, when the pose had none; a limb posed against its IK's bend side turns over, and a message says so); near a root bone's head moves the root, the targets staying where they are; on a bone an IK holds moves its target with the pointer; anywhere else it turns the bone, and alt turns a bone by hand after writing its limb's solved turns into the angles (IK off). The options show an IK switch and a mix for the picked bone's limb. The pose being built stays across mode switches; it is loaded again when the frame, the owner or the frame's stored pose changes, never mid-drag, and after "make this pose a drawing" what was posed since is kept. Chains end with Return or Esc only when no field, palette, settings window or key capture has the keyboard (`keys_busy`, read at the top of the frame; the pen's Return and Esc follow it too). The options bar stays one row: the picked bone's hints live in tooltips.- **Keys (M6, S6.5).** Layers, groups and vector nodes keep `keys`: per property (`x`, `y`, `rotate`, `sx`, `sy`, `opacity`) a sorted list of frame, value and ease (linear, in, out, in-out, step, or a cubic curve x1,y1,x2,y2 solved by bisection). A segment follows its first key's ease; values hold before the first key and after the last. Layers and groups composite with their keyed opacity and, when moved, with their keyed transform about the canvas centre (drawn whole, not tile by tile, while moved); nodes take keyed transforms and opacity when rasterised (`nodes_at`). The editor's frame and plane caches hash the keyed values; its vector raster cache does not follow node keys yet, so keyed shapes move in `klad render` and the exports, not in the editor.- **Godot scenes (M6, S6.6, S6.7).** `export --godot-scene` flattens each visible top-level layer (with its fog; the background with the first) into a texture on a `Parallax2D` with `scroll_scale` 1/(1 + depth), the factor the editor's depth preview (hold D) uses. `export --godot-rig` writes per skeleton: each part of the rest drawing (named parts of each paint layer's rest drawing, the loose marks as one) replayed alone, trimmed, on a `Polygon2D` with a 16 px triangle mesh over its pixels (one cell of margin), UVs, and per-vertex weights sampled from the maps; a `Skeleton2D` with a `Bone2D` per bone at rest (local position and angle against the parent, `rest`, `length`); and an `AnimationPlayer` with one animation per clip (or one for the timeline) whose value tracks hold each bone's rest angle plus its pose at the frame each posed drawing starts (stepped, so drawings hold as in klad); frames that are not poses of the rest drawing are listed for the frames export. Re-exports keep their uids. `samples/rig` builds a figure with all of it.- **Paint over (M5, S5.29).** `paintover` (`cli/src/paintover.rs`, resolved before the shape ops, alone in its batch) flattens the source (the `from` layers, or every visible layer below the target's top-level layer with the background) into OKLab, then follows Hertzmann's painterly method: for each brush size, biggest first, the source is blurred to that size, a grid at half the size finds cells whose mean difference from the painting so far (an estimate made by stamping discs of each stroke's colour) exceeds `threshold`, and a stroke starts at each such cell's worst pixel in a seeded random order. A stroke walks in steps of half its size across the luminance gradient (Sobel), turning towards it by `curve` times how sure the gradient is (weak gradients keep the stroke's direction; with none, a smooth seeded field of mostly level angles), and stops past its minimum length when the source there is closer to the painting than to the stroke's colour, at a colour change over twice the threshold, at the edge of the region or at its maximum length. `focus` keeps the last size to a shape grown by three of those sizes. Each stroke becomes a stroke op with a press-in and lift-off pressure, its size a little varied, its colour broken by `vary` from a hash of its seed, in the part `part`. `like <cel>` carries a paint-over to another drawing: every source paint layer's two drawings are paired as in-betweens pair them; each stroke rides the topmost source mark under its centre (a stroke within half its size, a polygon fill, a flood fill's coverage) with `tween::carry` along that mark's line (still marks: it stays; marks gone: it fades to opacity 0); it keeps its seed and is recoloured from the new source at its start, faded when it would now cross an edge; new strokes, in `<part> added`, only go where the source changed (its colour or alpha, grown by the biggest size) or where carried strokes left a gap. `--frames a-b` repeats that drawing to drawing, making a drawing on the target wherever a source layer starts one (a link where they link). `samples/paintover` paints over the lemons and carries a paint-over through the creature's walk; frame to frame its background changes by 0.03 of 255 on average.diff --git a/docs/format.md b/docs/format.mdindex 2574b4b..67a95c0 100644--- a/docs/format.md+++ b/docs/format.md@@ -221,7 +221,7 @@ A pose turns each bone about its head by its angle, its children with it, and mo- **Softness** s eases the reach: r = d up to l1 + l2 - s; r = d - (d - l1 - l2 + s)^2 / (4 s) up to l1 + l2 + s; then r = l1 + l2. So the limb slows before full reach and is straight only once the target is s past it.- **Mix** m blends each turned bone from the pose's angle a to the solved angle b the short way round: a + m wrap(b - a), wrap taking an angle to -180 to 180 degrees.-Constraints are solved parent first, by the position of the limb's top bone (A for a limb, the bone for an aim) in `bones`, then of its bone; each sees the bones as the ones before it left them. The solve is in 64-bit floats with deterministic maths, so it gives the same turns everywhere. A pose without an entry for a constraint leaves that limb to its angles. In-betweens of two poses of one rest drawing mix the angles, the root, each target and each mix by t (a constraint in one key only counts, in the other, as mix 0 with its target at that key's limb end), then solve.+Constraints are solved parent first, by the position of the limb's top bone (A for a limb, the bone for an aim) in `bones`, then of its bone; each sees the bones as the ones before it left them. The solve is in 64-bit floats with deterministic maths, so it gives the same turns everywhere. A pose without an entry for a constraint leaves that limb to its angles. In-betweens of two poses of one rest drawing mix the angles, the root, each target and each mix by t, then solve. A constraint in one key only is handed over as turns: that key's limb bones take their solved turns, each within 180 degrees of the other key's angle, and the in-between has no entry for it. Pose angles, root and targets must be finite and mixes within 0 to 1.## Stroke files