A drawing app built for agent/human collaboration
Rust
Bones live on a bones layer that any layer joins
Indicode BVbbc2f7be15e1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5c76ce5..97ce89f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,7 +4,7 @@The first builds, and klad's licences.-- Drawings are `.klad` folders in a fresh format, `klad/3` (drawings from the first builds, `klad/1` and `klad/2`, open as they are). Drawings from before (`.draw` folders) do not open and are not converted.+- Drawings are `.klad` folders in a fresh format, `klad/4` (drawings from the first builds open as they are, except their bones, which are dropped). Drawings from before (`.draw` folders) do not open and are not converted.- klad is source-available, not open source: the app is under the PolyForm Internal Use License 1.0.0, with permission for personal use, to propose contributions and to share the drawings you make (`LICENSE`); bought builds are under the same terms. The file format (`docs/format.md`), the command reference (`docs/cli.md`), the agent skill and the new `klad-client` crate are MIT (`LICENSE-MIT`), so any program or agent can read, write and make klad drawings. Contributions come in under a contributor licence agreement (`CLA.md`).- `klad-client`: run klad from Rust, apply edits as JSON ops, read drawings back as JSON, render them.- Builds for macOS (an app, Apple silicon and Intel in one) and Windows, sold on itch.io; Linux from source. Each has the `klad` command line, the editor, the fonts, the licences and the agent skill.@@ -17,9 +17,9 @@ The first builds, and klad's licences.- `klad arcs` follows the part of a foot on the ground: a heel-to-toe roll is no longer reported as a slide.- Help > Report a problem shows the report before it is copied (version, system, the last messages and lines of klad's log, with your home folder hidden) and can zip the drawing to attach; `klad report` prints the same. Errors and crashes are kept in a small log for it.- Messages say what happened and what to do next; when klad itself goes wrong it says so, and that your work is saved.-- Bones: a layer or group gets a skeleton (`klad bone`, the bone tool J), weights from the bones or painted (`klad weights`), and poses that bend the drawing (`klad pose`, pose mode); in-betweens of two poses turn the bones. The bone tool lists the skeleton, picks a bone in every mode, and moves ends, joints and whole bones with their children (`klad bone --move` with `--by`).+- Bones: a bones layer holds a skeleton (`klad bone`, the bone tool J), weights from the bones or painted (`klad weights`), and poses that bend the drawing (`klad pose`, pose mode); in-betweens of two poses turn the bones. The bone tool lists the skeleton, picks a bone in every mode, and moves ends, joints and whole bones with their children (`klad bone --move` with `--by`).- Transform a whole layer or group: cmd T puts handles round it, and a drag moves, turns or scales every drawing on it, its shapes, and its bones and poses (`klad transform --layer`).-- Attach a layer to a bone and it moves with that bone alone, as a cut-out: a character drawn in pieces needs no weights (`klad attach`, the picked bone's layers menu, or the bone button on a layer's row). Layers not attached bend by the weights. Pose mode shows the drawing posed as you drag; "make this pose a drawing" keeps it.+- Bones live on a bones layer (Layer > New bones layer, or the first bone you draw makes one; `klad add <file> layer bones`). Any paint layer in the drawing joins it: attached to a bone it moves with that bone alone, as a cut-out, so a character drawn in pieces needs no weights; or it bends with the skeleton by the weights (`klad attach`, the picked bone's layers menu, or the bone button on a layer's row). Pose mode shows the drawing posed as you drag; "make this pose a drawing" keeps it.- Bones are drawn as chains: letting go of a bone starts the next one from its end, each click adds one, shift fans them from one joint, Esc ends the chain (`klad bone --chain`).- IK: a bone and its parent become a limb (or a bone alone an aim) that reaches for a target, bending the way it is drawn, with softness so knees do not snap straight (`klad ik`, the bone tool's options). In pose mode, drag a limb's end and the limb follows; move the whole by a root bone's head and planted feet stay where they are (`klad pose --target`, `--mix`); in-betweens keep them planted. Exports to Godot carry the solved turns.- A first start: the start window welcomes, offers first steps (draw a shape, fill it, hand the drawing to an agent, ticked off as you go; Help > First steps opens them again) and six sample drawings that open as copies (`klad samples` lists and copies them).diff --git a/crates/app/src/commands.rs b/crates/app/src/commands.rsindex 99eea9a..2061c54 100644--- a/crates/app/src/commands.rs+++ b/crates/app/src/commands.rs@@ -135,6 +135,7 @@ pub enum Cmd {NudgeUp,NudgeDown,NewGroupLayer,+ NewBonesLayer,NewAdjustLayer,DuplicateLayer,DeleteLayer,@@ -492,7 +493,7 @@ use Repeat as R;use Trigger as T;impl Cmd {- pub const ALL: [Cmd; 165] = [+ pub const ALL: [Cmd; 166] = [Cmd::Brush,Cmd::Eraser,Cmd::Fill,@@ -624,6 +625,7 @@ impl Cmd {Cmd::NudgeUp,Cmd::NudgeDown,Cmd::NewGroupLayer,+ Cmd::NewBonesLayer,Cmd::NewAdjustLayer,Cmd::DuplicateLayer,Cmd::DeleteLayer,@@ -1841,6 +1843,15 @@ impl Cmd {R::No,"an empty group above the active layer; drag layers into it",),+ Cmd::NewBonesLayer => spec(+ "layer.new-bones",+ "new bones layer",+ icon::BONE,+ G::Layers,+ T::None,+ R::No,+ "a skeleton of its own above the active layer: draw its bones with the bone tool, then attach layers to them",+ ),Cmd::DuplicateLayer => spec("layer.duplicate","duplicate the layer",@@ -2276,6 +2287,7 @@ impl Cmd {Cmd::NudgeUp => "Nudge up",Cmd::NudgeDown => "Nudge down",Cmd::NewGroupLayer => "New group",+ Cmd::NewBonesLayer => "New bones layer",Cmd::NewAdjustLayer => "New adjustment layer",Cmd::DuplicateLayer => "Duplicate",Cmd::DeleteLayer => "Delete",@@ -2440,6 +2452,7 @@ pub const MENUS: [Menu; 9] = [Run(Cmd::NewVectorLayer),Run(Cmd::NewAdjustLayer),Run(Cmd::NewGroupLayer),+ Run(Cmd::NewBonesLayer),Line,Run(Cmd::DuplicateLayer),Run(Cmd::RenameLayer),diff --git a/crates/app/src/editor/bones.rs b/crates/app/src/editor/bones.rsindex 9578d9e..60c1460 100644--- a/crates/app/src/editor/bones.rs+++ b/crates/app/src/editor/bones.rs@@ -163,19 +163,27 @@ pub(super) fn pose_args(bundle: &std::path::Path, owner: &str, frame: u32, pose:impl Editor {pub(super) fn rig_owner(&self) -> Option<String> {let doc = &self.scene.bundle.doc;- let path = self.scene.active.clone();- (1..=path.len())- .rev()- .map(|n| doc.layer_at(&path[..n]))- .find(|l| !l.bones.is_empty())- .or_else(|| match path.len() {- 0 => None,- 1 => Some(doc.layer_at(&path)).filter(|l| matches!(l.kind(), Kind::Paint | Kind::Group)),- _ => Some(doc.layer_at(&path[..1])),- })+ let active = doc.locate_path(&self.scene.active);+ active+ .filter(|l| l.kind() == Kind::Bones)+ .or_else(|| active.and_then(|l| klad_core::rig::linked(doc, l)))+ .or_else(|| klad_core::rig::skeletons(doc).into_iter().next()).map(|l| l.id.clone())}+ pub(super) fn new_skeleton(&mut self) -> Result<String> {+ let taken: Vec<String> = klad_core::rig::skeletons(&self.scene.bundle.doc)+ .iter()+ .map(|s| s.name.clone())+ .collect();+ let name = std::iter::once("bones".to_string())+ .chain((2..).map(|n| format!("bones {n}")))+ .find(|n| !taken.contains(n))+ .unwrap_or_default();+ self.add_layer_value(serde_json::json!({"kind": "bones", "name": name}))?;+ self.rig_owner().context("the bones layer was not made")+ }+fn rig_bones(&self) -> Vec<Bone> {self.rig_owner().and_then(|id| self.scene.bundle.doc.layer(&id).map(|l| l.bones.clone()))@@ -240,7 +248,7 @@ impl Editor {self.bones.rests = Some((doc.rev, owner.clone(), weights, BTreeMap::new()));}let frame = self.scene.frame;- let wanted: Vec<(String, String)> = painted(&skeleton)+ let wanted: Vec<(String, String)> = painted(doc, &skeleton.id).iter().filter_map(|layer| {let cel = layer.content_at(frame)?;@@ -262,7 +270,7 @@ impl Editor {}});let (weights, rests) = (&*weights, &*marks);- let made: Vec<PosedCel> = painted(&skeleton)+ let made: Vec<PosedCel> = painted(&self.scene.bundle.doc, &skeleton.id).into_iter().filter_map(|layer| {let cel = layer.content_at(frame)?;@@ -273,7 +281,7 @@ impl Editor {..shown.clone()};let marks = klad_core::rig::Rig::new(&skeleton.bones, &skeleton.ik, weights, &pose)- .following(layer.bone.as_deref())+ .following(layer.follows()).pose(marks, canvas);Some(PosedCel {layer: layer.id.clone(),@@ -310,20 +318,15 @@ impl Editor {}fn bends(&self) -> bool {- self.rig_owner()- .and_then(|o| {- self.scene- .bundle- .doc- .layer(&o)- .map(|s| painted(s).iter().any(|l| l.bone.is_none()))- })- .unwrap_or(true)+ self.rig_owner().is_none_or(|o| {+ painted(&self.scene.bundle.doc, &o)+ .iter()+ .any(|l| l.follows().is_none())+ })}fn stored_pose(&self, owner: &str) -> Option<Pose> {- let layer = self.scene.bundle.doc.layer(owner)?;- painted(layer)+ painted(&self.scene.bundle.doc, owner).iter().find_map(|l| l.content_at(self.scene.frame).and_then(|c| c.pose.clone()))}@@ -456,9 +459,10 @@ impl Editor {}fn add_bone(&mut self, parent: Option<String>, head: [f32; 2], tail: [f32; 2]) -> Result<Bone> {- let owner = self- .rig_owner()- .context("pick the layer or group the bones go on first")?;+ let owner = match self.rig_owner() {+ Some(o) => o,+ None => self.new_skeleton()?,+ };let taken = self.rig_bones();let name = (1..).map(|n| format!("bone {n}"))@@ -571,7 +575,7 @@ impl Editor {.find(|k| k.bone == end).map(|k| limb_of(&bones, k)).unwrap_or_default();- painted(&owner)+ painted(&self.scene.bundle.doc, &owner.id).first().and_then(|l| {l.cels()@@ -1315,31 +1319,50 @@ impl Editor {fn attach_menu(&mut self, ui: &mut egui::Ui, picked: &str) -> Option<Later> {let owner = self.rig_owner()?;- let skeleton = self.scene.bundle.doc.layer(&owner)?;- let layers: Vec<(String, String, Option<String>)> = painted(skeleton)+ let doc = &self.scene.bundle.doc;+ let masks: Vec<&str> = doc+ .all_layers().iter()- .map(|l| (l.id.clone(), l.name.clone(), l.bone.clone()))+ .filter_map(|l| l.mask.as_deref().map(|m| m.id.as_str())).collect();- let on = layers.iter().filter(|l| l.2.as_deref() == Some(picked)).count();+ let layers: Vec<(String, String, Option<klad_core::rig::Link>)> = doc+ .all_layers()+ .iter()+ .filter(|l| l.kind() == Kind::Paint && !masks.contains(&l.id.as_str()))+ .map(|l| (l.id.clone(), l.name.clone(), l.rig.clone()))+ .collect();+ let mine = |link: &Option<klad_core::rig::Link>| {+ link.as_ref()+ .is_some_and(|k| k.skeleton == owner && k.bone.as_deref() == Some(picked))+ };+ let on = layers.iter().filter(|l| mine(&l.2)).count();let mut chosen = None;ui.menu_button(format!("layers: {on}"), |ui| {- layers.iter().for_each(|(id, name, bone)| {- let mut checked = bone.as_deref() == Some(picked);- let label = match bone {- Some(b) if b != picked => format!("{name} (follows {b})"),- _ => name.clone(),+ layers.iter().for_each(|(id, name, link)| {+ let mut checked = mine(link);+ let label = match link.as_ref().filter(|_| !checked) {+ Some(klad_core::rig::Link { bone: Some(b), .. }) => format!("{name} (follows {b})"),+ Some(_) => format!("{name} (bends)"),+ None => name.clone(),};if ui.checkbox(&mut checked, label).changed() {- chosen = Some((id.clone(), checked.then(|| picked.to_string())));+ chosen = Some((id.clone(), checked));}});}).response.hint(format!(- "the layers that move with {picked} alone when posed; a layer attached to no bone bends by the weights"+ "the layers that move with {picked} alone when posed; a layer's bone button in the layers panel can also make it bend with the skeleton"));- chosen.map(|(layer, bone)| -> Later {- Box::new(move |e| e.apply(vec![Op::Attach(klad_core::ops::AttachSpec { layer, bone })]))+ let (skeleton, bone) = (owner.clone(), picked.to_string());+ chosen.map(|(layer, on)| -> Later {+ Box::new(move |e| {+ e.apply(vec![Op::Attach(klad_core::ops::AttachSpec {+ layer,+ skeleton: on.then_some(skeleton),+ bone: on.then_some(bone),+ })])+ })})}@@ -1347,38 +1370,14 @@ impl Editor {let bones = self.rig_bones();let doc = &self.scene.bundle.doc;if bones.is_empty() {- let owners: Vec<(String, String)> = doc- .all_layers()- .into_iter()- .filter(|l| !l.bones.is_empty())- .map(|l| (l.id.clone(), l.name.clone()))- .collect();- if owners.is_empty() {- ui.label(RichText::new("no skeleton yet").color(theme::WEAK));- return None;- }- let here = self- .scene- .active_layer()- .map_or("this layer".to_string(), |l| l.name.clone());- ui.label(RichText::new(format!("{here} has no bones; skeletons are on")).color(theme::WEAK));- return owners.into_iter().fold(None, |run, (id, name)| {- let clicked = ui- .button(format!("{} {name}", theme::icon::BONE))- .hint(format!("make {name} the active layer to see and edit its bones"))- .clicked();- run.or_else(|| {- clicked.then(|| -> Later {- Box::new(move |e| {- let Some(klad_core::doc::Loc::Layer(path)) = e.scene.bundle.doc.locate(&id) else {- bail!("that layer is gone");- };- e.pick_bone(None);- e.activate(path)- })- })- })- });+ match self.rig_owner().and_then(|o| doc.layer(&o)) {+ Some(skeleton) => ui+ .label(RichText::new(format!("{} has no bones yet: drag on the canvas", skeleton.name)).color(theme::WEAK)),+ None => ui+ .label(RichText::new("no bones layer yet: drawing a bone makes one").color(theme::WEAK))+ .hint("a bones layer holds a skeleton and draws nothing; every paint layer can follow one of its bones, or bend with it"),+ };+ return None;}let owner = self.rig_owner()diff --git a/crates/app/src/editor/commands.rs b/crates/app/src/editor/commands.rsindex c592b6b..5faaeaa 100644--- a/crates/app/src/editor/commands.rs+++ b/crates/app/src/editor/commands.rs@@ -221,7 +221,11 @@ impl Editor {.then(|| "the timeline has one frame: insert a frame first (I)".to_string())}}),- Cmd::NewPaintLayer | Cmd::NewVectorLayer | Cmd::NewGroupLayer | Cmd::NewAdjustLayer => self.timeline_edit(),+ Cmd::NewPaintLayer+ | Cmd::NewVectorLayer+ | Cmd::NewGroupLayer+ | Cmd::NewBonesLayer+ | Cmd::NewAdjustLayer => self.timeline_edit(),Cmd::Unwrap => match self.selection.as_deref().map(|id| self.scene.bundle.doc.item(id)) {Some(Some(klad_core::doc::Item::Node(_, _, n))) if n.shape.generates() => None,_ => Some("select a repeat, scatter or mirror with V first".to_string()),@@ -621,6 +625,9 @@ impl Editor {}Cmd::NewPaintLayer => self.add_layer("paint")?,Cmd::NewGroupLayer => self.new_group(false)?,+ Cmd::NewBonesLayer => {+ self.new_skeleton()?;+ }Cmd::NewAdjustLayer => {self.add_layer_value(json!({"kind": "adjust", "name": "curves", "adjust": {"curves": {}}}))?}diff --git a/crates/app/src/editor/layers.rs b/crates/app/src/editor/layers.rsindex 8483082..fda9570 100644--- a/crates/app/src/editor/layers.rs+++ b/crates/app/src/editor/layers.rs@@ -35,8 +35,8 @@ pub(super) struct LayerRow {pub mask: bool,pub folded: bool,pub cel: Option<String>,- pub skeleton: Vec<String>,- pub bone: Option<String>,+ pub skeletons: Vec<(String, String, Vec<String>)>,+ pub rig: Option<klad_core::rig::Link>,}#[derive(Clone, Debug, PartialEq)]@@ -155,13 +155,20 @@ impl Editor {mask,folded,cel,- skeleton: match (mask, layer.kind()) {- (false, Kind::Paint) => klad_core::rig::skeleton_of(&self.scene.bundle.doc, path)- .map(|s| s.bones.iter().map(|b| b.name.clone()).collect())- .unwrap_or_default(),+ skeletons: match (mask, layer.kind()) {+ (false, Kind::Paint) => klad_core::rig::skeletons(&self.scene.bundle.doc)+ .iter()+ .map(|s| {+ (+ s.id.clone(),+ s.name.clone(),+ s.bones.iter().map(|b| b.name.clone()).collect(),+ )+ })+ .collect(),_ => Vec::new(),},- bone: layer.bone.clone(),+ rig: layer.rig.clone(),}}@@ -306,6 +313,7 @@ impl Editor {let kind = match (row.mask, row.kind) {(true, _) => icon::MASK,(_, Kind::Group) => icon::LAYERS,+ (_, Kind::Bones) => icon::BONE,(_, Kind::Adjust) => icon::ADJUST,(_, Kind::Vector) => icon::POINTS,_ => icon::BRUSH,@@ -416,35 +424,60 @@ impl Editor {self.timeline.masks.insert(row.id.clone());}}- if place == Where::Panel && !row.skeleton.is_empty() {- let glyph = RichText::new(icon::BONE).size(14.0).color(match row.bone {+ if place == Where::Panel && !row.skeletons.is_empty() {+ let glyph = RichText::new(icon::BONE).size(14.0).color(match row.rig {Some(_) => theme::ACCENT,None => theme::WEAK,});let button = egui::Button::new(glyph).frame(false).min_size(vec2(22.0, theme::TARGET));- egui::containers::menu::MenuButton::from_button(button).ui(ui, |ui| {- let mut chosen = None;- row.skeleton.iter().for_each(|b| {- if ui.radio(row.bone.as_ref() == Some(b), format!("follows {b}")).clicked() {- chosen = Some(Some(b.clone()));+ egui::containers::menu::MenuButton::from_button(button)+ .ui(ui, |ui| {+ let mut chosen = None;+ let link = |skeleton: &str, bone: Option<&str>| klad_core::rig::Link {+ skeleton: skeleton.to_string(),+ bone: bone.map(str::to_string),+ };+ row.skeletons.iter().for_each(|(id, name, bones)| {+ if row.skeletons.len() > 1 {+ ui.label(RichText::new(name).color(theme::WEAK));+ }+ bones.iter().for_each(|b| {+ let here = link(id, Some(b));+ if ui.radio(row.rig.as_ref() == Some(&here), format!("follows {b}")).clicked() {+ chosen = Some(Some(here));+ }+ });+ let bend = link(id, None);+ if ui+ .radio(row.rig.as_ref() == Some(&bend), format!("bends with {name}"))+ .clicked()+ {+ chosen = Some(Some(bend));+ }+ });+ if ui.radio(row.rig.is_none(), "not rigged").clicked() {+ chosen = Some(None);+ }+ if let Some(link) = chosen {+ ui.close();+ ops.push(Op::Attach(klad_core::ops::AttachSpec {+ layer: row.id.clone(),+ skeleton: link.as_ref().map(|l| l.skeleton.clone()),+ bone: link.and_then(|l| l.bone),+ }));}+ })+ .0+ .hint(match &row.rig {+ Some(klad_core::rig::Link { bone: Some(b), .. }) => {+ format!("{} follows {b}: posed, it moves with that bone alone", row.name)+ }+ Some(_) => format!("{} bends with its skeleton, by the weights", row.name),+ None => format!(+ "{} is not rigged: attach it to a bone, or let it bend with a skeleton",+ row.name+ ),});- if ui.radio(row.bone.is_none(), "bends by the weights").clicked() {- chosen = Some(None);- }- if let Some(bone) = chosen {- ui.close();- ops.push(Op::Attach(klad_core::ops::AttachSpec {- layer: row.id.clone(),- bone,- }));- }- })- .0- .hint(match &row.bone {- Some(b) => format!("{} follows {b}: posed, it moves with that bone alone", row.name),- None => format!("{} bends by the weights: attach it to a bone to move with that bone alone", row.name),- });}[(row.clip, icon::CLIP, "clipped to the layer below"), (row.lock_alpha, icon::LOCK, "alpha locked")].iter()@@ -605,6 +638,7 @@ impl Editor {(Cmd::NewPaintLayer, Some("paint")),(Cmd::NewVectorLayer, Some("vector")),(Cmd::NewGroupLayer, Some("group")),+ (Cmd::NewBonesLayer, Some("bones")),(Cmd::NewAdjustLayer, Some("adjust")),(Cmd::DuplicateLayer, None),(Cmd::GroupLayer, None),@@ -729,8 +763,8 @@ mod tests {mask,folded: false,cel: None,- skeleton: Vec::new(),- bone: None,+ skeletons: Vec::new(),+ rig: None,}}diff --git a/crates/app/src/editor/shift.rs b/crates/app/src/editor/shift.rsindex 197891a..4eec3d6 100644--- a/crates/app/src/editor/shift.rs+++ b/crates/app/src/editor/shift.rs@@ -148,6 +148,7 @@ impl Editor {};let kind = match self.scene.bundle.doc.layer(&s.layer).map(|l| l.kind()) {Some(Kind::Group) => "group",+ Some(Kind::Bones) => "bones layer",_ => "layer",};ui.label(RichText::new(format!("transforming the {kind} {}", s.found.name)).strong());diff --git a/crates/app/src/editor/timeline.rs b/crates/app/src/editor/timeline.rsindex 1fba92d..ba38123 100644--- a/crates/app/src/editor/timeline.rs+++ b/crates/app/src/editor/timeline.rs@@ -1157,6 +1157,11 @@ impl Editor {if layer.kind() == Kind::Adjust {return format!("{name} is an adjustment layer: it changes what is under it; pick a paint layer to draw");}+ if layer.kind() == Kind::Bones {+ return format!(+ "{name} is a bones layer: it holds a skeleton (the bone tool, J); pick a paint layer to draw"+ );+ }let span = |start: u32, end: u32| match end.min(frames) - start {1 => format!("frame {start}"),_ => format!("frames {start} to {}", end.min(frames) - 1),diff --git a/crates/app/src/editor/ui_tests.rs b/crates/app/src/editor/ui_tests.rsindex 7defa6a..8253aa2 100644--- a/crates/app/src/editor/ui_tests.rs+++ b/crates/app/src/editor/ui_tests.rs@@ -87,6 +87,12 @@ fn activate(h: &mut Harness<'static, Editor>, name: &str) {ready(h);}+fn skeleton(h: &Harness<'static, Editor>) -> Layer {+ klad_core::rig::skeletons(&h.state().scene.bundle.doc)+ .first()+ .map_or_else(|| Layer::skeleton("", ""), |l| (*l).clone())+}+fn ready(h: &mut Harness<'static, Editor>) {let start = std::time::Instant::now();while !h.state().canvas_current() && start.elapsed() < std::time::Duration::from_secs(20) {@@ -3377,9 +3383,17 @@ fn bones_are_drawn_weighted_and_posed_on_the_canvas() {drag(&mut h, b, c);h.event(egui::Event::ModifiersChanged(Modifiers::NONE));h.run_steps(2);- let bones = |h: &Harness<'static, Editor>| h.state().scene.bundle.doc.layer("l6").unwrap().bones.clone();+ let bones = |h: &Harness<'static, Editor>| skeleton(h).bones;let made = bones(&h);assert_eq!(made.len(), 2, "{made:?}");+ assert_eq!(+ (+ skeleton(&h).name.as_str(),+ h.state().scene.active_layer().map(|l| l.name.clone())+ ),+ ("bones", Some("bones".to_string())),+ "the first bone makes a bones layer, which becomes the active one"+ );assert_eq!(made[1].parent.as_deref(),Some("bone 1"),@@ -3402,7 +3416,7 @@ fn bones_are_drawn_weighted_and_posed_on_the_canvas() {let (dab, more) = (canvas_at(&h, 250.0, 170.0), canvas_at(&h, 260.0, 175.0));drag(&mut h, dab, more);h.run_steps(2);- let weights = h.state().scene.bundle.read_weights("l6").unwrap();+ let weights = h.state().scene.bundle.read_weights(&skeleton(&h).id).unwrap();assert!(weights.maps.contains_key("shin"),"painting weights writes the bone's map"@@ -3507,7 +3521,7 @@ fn bones_are_drawn_as_a_chain_that_fans_ends_and_takes_back_its_last_bone() {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 bones = |h: &Harness<'static, Editor>| skeleton(h).bones;let points = [[40.0, 40.0], [120.0, 80.0], [200.0, 90.0], [260.0, 150.0]];let screen: Vec<egui::Pos2> = points.iter().map(|p| canvas_at(&h, p[0], p[1])).collect();drag(&mut h, screen[0], screen[1]);@@ -3595,13 +3609,14 @@ fn bones_are_drawn_as_a_chain_that_fans_ends_and_takes_back_its_last_bone() {.unwrap().apply(&parse_lines(&format!(- r#"{{"op":"bone","layer":"l6","chain":["bone 1","bone 2","bone 3"],"through":{}}}"#,+ r#"{{"op":"add","layer":{{"id":"sk","kind":"bones","name":"bones"}}}}+{{"op":"bone","layer":"sk","chain":["bone 1","bone 2","bone 3"],"through":{}}}"#,serde_json::to_string(&[drawn[0].head, drawn[0].tail, drawn[1].tail, redrawn[2].tail]).unwrap())).unwrap(),).unwrap();- let made = Bundle::open(&cli).unwrap().doc.layer("l6").unwrap().bones.clone();+ let made = Bundle::open(&cli).unwrap().doc.layer("sk").unwrap().bones.clone();assert_eq!(made[..2], redrawn[..2], "the editor's chain is klad bone --chain");assert_eq!(made[2], redrawn[2]);let _ = std::fs::remove_dir_all(&path);@@ -3615,7 +3630,7 @@ fn a_bone_renamed_while_its_chain_is_drawn_stays_the_parent_of_the_next() {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 bones = |h: &Harness<'static, Editor>| skeleton(h).bones;let (a, b, c) = (canvas_at(&h, 40.0, 40.0),canvas_at(&h, 120.0, 80.0),@@ -3664,8 +3679,10 @@ fn the_bone_options_stay_one_row_whatever_is_picked() {.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"}"#,+ r#"{"op":"add","layer":{"id":"sk","kind":"bones","name":"bones"}}+{"op":"attach","layer":"l6","skeleton":"sk"}+{"op":"bone","layer":"sk","chain":["thigh","shin"],"through":[[100,60],[100,160],[110,260]]}+{"op":"ik","layer":"sk","add":"shin"}"#,).unwrap(),)@@ -3691,6 +3708,50 @@ fn the_bone_options_stay_one_row_whatever_is_picked() {let _ = std::fs::remove_dir_all(&path);}+#[test]+fn a_bones_layer_takes_any_layers_in_the_drawing() {+ let path = sample("bones-layer");+ let mut h = harness(editor(&path), vec2(1440.0, 1000.0));+ activate(&mut h, "lines");+ h.state_mut().invoke(Cmd::NewBonesLayer).unwrap();+ h.run_steps(2);+ let made = skeleton(&h);+ assert_eq!(+ h.state().scene.active_layer().map(|l| (l.id.clone(), l.kind())),+ Some((made.id.clone(), klad_core::doc::Kind::Bones)),+ "Layer > New bones layer makes one and makes it active"+ );+ h.key_press(Key::J);+ h.run_steps(2);+ let (a, b) = (canvas_at(&h, 60.0, 60.0), canvas_at(&h, 200.0, 120.0));+ drag(&mut h, a, b);+ h.run_steps(2);+ h.key_press(Key::Escape);+ h.run_steps(2);+ assert_eq!(skeleton(&h).bones.len(), 1, "the bone goes on the bones layer");+ h.state_mut().pick_bone(Some("bone 1".into()));+ h.run_steps(2);+ ["colour", "lines"].into_iter().enumerate().for_each(|(n, layer)| {+ h.get_by_role_and_label(Role::Button, &format!("layers: {n}")).click();+ h.run_steps(2);+ h.get_by_role_and_label(Role::CheckBox, layer).click();+ h.run_steps(3);+ });+ let doc = &h.state().scene.bundle.doc;+ ["colour", "lines"].into_iter().for_each(|name| {+ let layer = doc.find_layer(name).unwrap();+ assert_eq!(+ layer.rig,+ Some(klad_core::rig::Link {+ skeleton: made.id.clone(),+ bone: Some("bone 1".into())+ }),+ "{name}, a layer next to the bones layer, follows its bone"+ );+ });+ let _ = std::fs::remove_dir_all(&path);+}+#[test]fn a_layer_attached_to_a_bone_moves_with_it_live_in_pose_mode() {let path = sample("attach-live");@@ -3698,7 +3759,9 @@ fn a_layer_attached_to_a_bone_moves_with_it_live_in_pose_mode() {.unwrap().apply(&parse_lines(- r#"{"op":"bone","layer":"l6","chain":["thigh","shin"],"through":[[100,60],[100,160],[110,260]]}"#,+ r#"{"op":"add","layer":{"id":"sk","kind":"bones","name":"bones"}}+{"op":"attach","layer":"l6","skeleton":"sk"}+{"op":"bone","layer":"sk","chain":["thigh","shin"],"through":[[100,60],[100,160],[110,260]]}"#,).unwrap(),)@@ -3711,10 +3774,10 @@ fn a_layer_attached_to_a_bone_moves_with_it_live_in_pose_mode() {h.run_steps(2);h.get_by_role_and_label(Role::Button, "layers: 0").click();h.run_steps(2);- h.get_by_role_and_label(Role::CheckBox, "lines").click();+ h.get_by_role_and_label(Role::CheckBox, "lines (bends)").click();h.run_steps(3);assert_eq!(- h.state().scene.bundle.doc.layer("l6").unwrap().bone.as_deref(),+ h.state().scene.bundle.doc.layer("l6").unwrap().follows(),Some("shin"),"the picked bone's layers menu attaches a layer");@@ -3774,7 +3837,9 @@ fn a_leg_gets_its_ik_in_the_options_and_its_foot_is_dragged_and_planted_in_pose_.unwrap().apply(&parse_lines(- r#"{"op":"bone","layer":"l6","chain":["thigh","shin"],"through":[[100,60],[100,160],[110,260]]}"#,+ r#"{"op":"add","layer":{"id":"sk","kind":"bones","name":"bones"}}+{"op":"attach","layer":"l6","skeleton":"sk"}+{"op":"bone","layer":"sk","chain":["thigh","shin"],"through":[[100,60],[100,160],[110,260]]}"#,).unwrap(),)@@ -3789,7 +3854,7 @@ fn a_leg_gets_its_ik_in_the_options_and_its_foot_is_dragged_and_planted_in_pose_h.run_steps(2);h.get_by_label("limb: shin and thigh").click();h.run_steps(3);- let ik = h.state().scene.bundle.doc.layer("l6").unwrap().ik.clone();+ let ik = h.state().scene.bundle.doc.layer("sk").unwrap().ik.clone();assert_eq!(ik.len(), 1, "{ik:?}");assert_eq!((ik[0].bone.as_str(), ik[0].chain), ("shin", 2));assert!(@@ -3800,7 +3865,7 @@ fn a_leg_gets_its_ik_in_the_options_and_its_foot_is_dragged_and_planted_in_pose_h.run_steps(2);let shown = |h: &Harness<'static, Editor>| {let ed = h.state();- let layer = ed.scene.bundle.doc.layer("l6").unwrap();+ let layer = ed.scene.bundle.doc.layer("sk").unwrap();let pose = klad_core::rig::Pose {angles: ed.bones.pose.clone(),root: ed.bones.root,@@ -3883,26 +3948,26 @@ fn bones_are_picked_from_the_list_and_the_canvas_and_edited_in_place() {.unwrap().apply(&parse_lines(- r#"{"op":"bone","layer":"l6","add":"thigh","head":[100,60],"tail":[100,160]}-{"op":"bone","layer":"l6","add":"shin","parent":"thigh","head":[100,160],"tail":[100,260]}-{"op":"bone","layer":"l6","add":"tail","head":[300,100],"tail":[400,100]}"#,+ r#"{"op":"add","layer":{"id":"sk","kind":"bones","name":"bones"}}+{"op":"attach","layer":"l6","skeleton":"sk"}+{"op":"bone","layer":"sk","add":"thigh","head":[100,60],"tail":[100,160]}+{"op":"bone","layer":"sk","add":"shin","parent":"thigh","head":[100,160],"tail":[100,260]}+{"op":"bone","layer":"sk","add":"tail","head":[300,100],"tail":[400,100]}"#,).unwrap(),).unwrap();let mut h = harness(editor(&path), vec2(1440.0, 1000.0));- let bones = |h: &Harness<'static, Editor>| h.state().scene.bundle.doc.layer("l6").unwrap().bones.clone();+ let bones = |h: &Harness<'static, Editor>| skeleton(h).bones;let bone = |h: &Harness<'static, Editor>, name: &str| bones(h).into_iter().find(|b| b.name == name).unwrap();activate(&mut h, "colour");h.key_press(Key::J);h.run_steps(2);- assert!(- h.query_by_label_contains("colour has no bones").is_some(),- "a layer without bones says where the skeletons are"+ assert_eq!(+ h.state().rig_owner().as_deref(),+ Some("sk"),+ "with any layer active, the bone tool works on the drawing's bones layer");- h.get_by_label(&format!("{} lines", theme::icon::BONE)).click();- h.run_steps(3);- assert_eq!(h.state().scene.active_layer().unwrap().name, "lines");h.get_by_label_contains("pick a bone").click();h.run_steps(2);h.get_by_label("shin").click();diff --git a/crates/cli/src/agent.rs b/crates/cli/src/agent.rsindex 94610f4..94da176 100644--- a/crates/cli/src/agent.rs+++ b/crates/cli/src/agent.rs@@ -289,7 +289,7 @@ fn paint_marks(bundle: &Bundle, layers: &[Layer], frame: u32, out: &mut Vec<MarkOk(())}Kind::Group => paint_marks(bundle, layer.children(), frame, out),- Kind::Vector | Kind::Adjust => Ok(()),+ Kind::Vector | Kind::Adjust | Kind::Bones => Ok(()),})}@@ -320,7 +320,7 @@ fn layer_box(bundle: &Bundle, layer: &Layer, frame: u32) -> Result<Option<[f32;Kind::Group => layer.children().iter().try_fold(None, |acc, c| {Ok::<_, anyhow::Error>(union(acc, layer_box(bundle, c, frame)?))})?,- Kind::Adjust => None,+ Kind::Adjust | Kind::Bones => None,})}@@ -696,6 +696,9 @@ fn layer_summary(bundle: &Bundle, layer: &Layer, frame: u32) -> Result<Value> {if layer.locked {value["locked"] = json!(true);}+ if let Some(rig) = &layer.rig {+ value["rig"] = json!(rig);+ }if let Some(mask) = &layer.mask {let mut summary = layer_summary(bundle, mask, frame)?;summary["role"] = json!("mask");@@ -728,6 +731,16 @@ fn layer_summary(bundle: &Bundle, layer: &Layer, frame: u32) -> Result<Value> {value["children"] = Value::Array(children);bounds}+ Kind::Bones => {+ value["bones"] = json!(layer.bones.iter().map(|b| &b.name).collect::<Vec<_>>());+ value["attached"] = json!(+ klad_core::rig::painted(&bundle.doc, &layer.id)+ .iter()+ .map(|l| &l.id)+ .collect::<Vec<_>>()+ );+ None+ }Kind::Adjust => {if let Some(adjust) = layer.adjustment() {value["adjust"] = serde_json::to_value(adjust)?;diff --git a/crates/cli/src/inbetween.rs b/crates/cli/src/inbetween.rsindex 08fea96..d459406 100644--- a/crates/cli/src/inbetween.rs+++ b/crates/cli/src/inbetween.rs@@ -152,13 +152,17 @@ fn source(cel: &Cel) -> String {}fn paint_layers(doc: &Document, keys: &[String]) -> Result<Vec<String>> {- fn walk(layer: &Layer, out: &mut Vec<String>) -> Result<()> {+ fn walk(doc: &Document, layer: &Layer, out: &mut Vec<String>) -> Result<()> {match layer.kind() {Kind::Paint => {out.push(layer.id.clone());Ok(())}- Kind::Group => layer.children().iter().try_for_each(|c| walk(c, out)),+ Kind::Group => layer.children().iter().try_for_each(|c| walk(doc, c, out)),+ Kind::Bones => {+ out.extend(klad_core::rig::painted(doc, &layer.id).iter().map(|l| l.id.clone()));+ Ok(())+ }Kind::Vector => bail!("{} is a vector layer; in-betweens are made on paint layers", layer.id),Kind::Adjust => bail!("{} is an adjustment layer; in-betweens are made on paint layers",@@ -167,7 +171,7 @@ fn paint_layers(doc: &Document, keys: &[String]) -> Result<Vec<String>> {}}let mut out = Vec::new();- keys.iter().try_for_each(|k| walk(doc.find_layer(k)?, &mut out))?;+ keys.iter().try_for_each(|k| walk(doc, doc.find_layer(k)?, &mut out))?;let mut seen = BTreeSet::new();out.retain(|id| seen.insert(id.clone()));Ok(out)diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rsindex 234c365..4b09586 100644--- a/crates/cli/src/main.rs+++ b/crates/cli/src/main.rs@@ -497,7 +497,7 @@ enum Command {#[arg(help = "layer, cel, mask, rect, ellipse, path, group, rays, image, scatter, repeat, mirror or text")]what: String,#[arg(- help = "For layers the kind first (paint, vector, group, image with src=photo.jpg, or adjust and its type: hsl, levels, curves, balance, gradient-map, fill), then key=value pairs"+ help = "For layers the kind first (paint, vector, group, bones, image with src=photo.jpg, or adjust and its type: hsl, levels, curves, balance, gradient-map, fill), then key=value pairs")]rest: Vec<String>,#[command(flatten)]@@ -1236,15 +1236,27 @@ enum Command {flags: EditFlags,},#[command(- about = "Attach a layer to a bone, so it moves with that bone alone when posed",- long_about = "Attach a paint layer under a skeleton to one of its bones: posed, the whole layer moves rigidly with that bone, the way a cut-out arm follows its upper arm. Draw a character in pieces (upper arm, forearm, hand on their own layers), attach each to its bone and no weights are needed. A layer not attached bends by the weights instead (by distance to the bones, or as painted in the bone tool's weights mode): use that for a layer drawn in one piece across a joint. --off detaches a layer, so it bends again.\n\n klad attach art.klad forearm --bone fore\n klad attach art.klad forearm --off\n\nAlso an attach op: {\"op\":\"attach\",\"layer\":\"forearm\",\"bone\":\"fore\"}; without \"bone\" the layer bends by the weights. Renaming the bone keeps the layer on it; removing it leaves the layer bending."+ about = "Rig a layer: attach it to a bone, let it bend with a skeleton, or unrig it",+ long_about = "Bones live on bones layers (klad add <bundle> layer bones, or Layer > New bones layer); a bones layer draws nothing. Any paint layer in the drawing can be rigged to one: attached to a bone (--bone), it moves rigidly with that bone when posed, the way a cut-out arm follows its upper arm, so a character drawn in pieces (upper arm, forearm, hand on their own layers) needs no weights; set to bend (--bend), each of its points moves by the skeleton's weights, for a layer drawn in one piece across a joint. --off unrigs it: posing leaves it as it is. --skeleton names the bones layer when the drawing has more than one (with --bone, the one that has that bone is found).\n\n klad attach art.klad forearm --bone fore\n klad attach art.klad sleeve --bend --skeleton bones\n klad attach art.klad forearm --off\n\nAlso an attach op: {\"op\":\"attach\",\"layer\":\"forearm\",\"bone\":\"fore\"}; {\"op\":\"attach\",\"layer\":\"sleeve\",\"skeleton\":\"bones\"} bends; without either it unrigs. Renaming a bone keeps its layers on it; removing it unrigs them.")]Attach {bundle: PathBuf,layer: String,- #[arg(long, conflicts_with = "off", required_unless_present = "off")]+ #[arg(long, conflicts_with_all = ["off", "bend"], required_unless_present_any = ["off", "bend"])]bone: Option<String>,- #[arg(long, help = "detach: the layer bends by the weights again")]+ #[arg(+ long,+ conflicts_with = "off",+ help = "bend with the skeleton by its weights, instead of following one bone"+ )]+ bend: bool,+ #[arg(+ long,+ help = "the bones layer, when there is more than one",+ required_if_eq("bend", "true")+ )]+ skeleton: Option<String>,+ #[arg(long, help = "unrig: posing leaves the layer as it is")]off: bool,#[command(flatten)]flags: EditFlags,@@ -2992,11 +3004,14 @@ fn run() -> Result<()> {bundle,layer,bone,+ bend: _,+ skeleton,off: _,flags,} => {let spec = klad_core::ops::AttachSpec {layer: layer_id(&bundle, &layer)?,+ skeleton,bone,};agent::edit(&bundle, &[Op::Attach(spec)], &output(&flags, 0))?;diff --git a/crates/cli/src/rig.rs b/crates/cli/src/rig.rsindex c0a7c18..8b870c9 100644--- a/crates/cli/src/rig.rs+++ b/crates/cli/src/rig.rs@@ -2,18 +2,21 @@ use anyhow::{Context, Result, anyhow, bail};use klad_core::bundle::Bundle;use klad_core::doc::{Document, Layer};use klad_core::ops::{Applied, Op, PoseSpec, PosedCel, apply, rig_owner};-use klad_core::rig::{Bone, CELL, Ik, Pose, Rig, Weights, applied, between, family, painted, tips, weights_for};+use klad_core::rig::{Bone, CELL, Ik, Pose, Rig, Weights, applied, between, painted, tips, weights_for};use klad_core::stroke::Mark;use klad_render::overlay::Heat;use serde_json::json;use std::collections::BTreeMap;pub fn owners(doc: &Document) -> Vec<&Layer> {- doc.all_layers().into_iter().filter(|l| !l.bones.is_empty()).collect()+ klad_core::rig::skeletons(doc)+ .into_iter()+ .filter(|l| !l.bones.is_empty())+ .collect()}-fn pose_at(owner: &Layer, frame: u32) -> Pose {- painted(owner)+fn pose_at(doc: &Document, owner: &Layer, frame: u32) -> Pose {+ painted(doc, &owner.id).iter().find_map(|l| l.content_at(frame).and_then(|c| c.pose.clone())).unwrap_or_default()@@ -23,7 +26,7 @@ pub fn bones_at(bundle: &Bundle, frame: u32) -> Result<Vec<klad_render::overlay:Ok(owners(&bundle.doc).into_iter().flat_map(|owner| {- let pose = pose_at(owner, frame);+ let pose = pose_at(&bundle.doc, owner, frame);owner.bones.iter()@@ -38,7 +41,7 @@ pub fn targets_at(bundle: &Bundle, frame: u32) -> Vec<([f32; 2], [f32; 2])> {owners(&bundle.doc).into_iter().flat_map(|owner| {- let pose = pose_at(owner, frame);+ let pose = pose_at(&bundle.doc, owner, frame);let shown = tips(&owner.bones, &owner.ik, &pose);pose.ik.iter()@@ -103,7 +106,7 @@ fn posed(bundle: &Bundle, doc: &mut Document, spec: &PoseSpec, weights: &Weights);}let canvas = (doc.canvas.width, doc.canvas.height);- let layers: Vec<Layer> = painted(&owner).into_iter().cloned().collect();+ let layers: Vec<Layer> = painted(doc, &owner.id).into_iter().cloned().collect();layers.iter().filter_map(|layer| rest_of(layer, spec.from).map(|rest| (layer, rest)))@@ -116,7 +119,7 @@ fn posed(bundle: &Bundle, doc: &mut Document, spec: &PoseSpec, weights: &Weights};let marks = bundle.read_marks(&layer.id, &rest)?;let made = Rig::new(&owner.bones, &owner.ik, weights, &pose)- .following(layer.bone.as_deref())+ .following(layer.follows()).pose(&marks, canvas);let here = layer.cels().iter().find(|c| c.frame == spec.to);let (cel, fresh) = match here {@@ -214,8 +217,8 @@ pub fn list(bundle: &Bundle, as_json: bool) -> Result<()> {"bend": c.bend,"softness": c.softness,})).collect::<Vec<_>>(),- "layers": painted(o).iter().map(|l| json!({"layer": l.id, "name": l.name, "bone": l.bone})).collect::<Vec<_>>(),- "poses": painted(o).iter().flat_map(|l| l.cels().iter().filter_map(|c| c.pose.as_ref().map(|p| {+ "layers": painted(doc, &o.id).iter().map(|l| json!({"layer": l.id, "name": l.name, "bone": l.follows()})).collect::<Vec<_>>(),+ "poses": painted(doc, &o.id).iter().flat_map(|l| l.cels().iter().filter_map(|c| c.pose.as_ref().map(|p| {let mut entry = json!({"cel": c.id, "frame": c.frame, "rest": p.rest, "angles": p.angles, "root": p.root});if !p.ik.is_empty() {entry["ik"] = json!(p.ik);@@ -236,7 +239,7 @@ pub fn list(bundle: &Bundle, as_json: bool) -> Result<()> {owners(doc).iter().for_each(|o| {println!("{} ({})", o.name, o.id);let weights = bundle.read_weights(&o.id).ok();- let bending = painted(o).iter().any(|l| l.bone.is_none());+ let bending = painted(doc, &o.id).iter().any(|l| l.follows().is_none());o.bones.iter().for_each(|b: &Bone| {let painted = !bending || weights.as_ref().is_some_and(|w| w.maps.contains_key(&b.name));println!(@@ -268,11 +271,18 @@ pub fn list(bundle: &Bundle, as_json: bool) -> Result<()> {_ => println!(" ik {}: an aim", c.bone),}});- painted(o).iter().for_each(|l| match &l.bone {+ let linked = painted(doc, &o.id);+ if linked.is_empty() {+ println!(+ " no layers attached yet: klad attach <bundle> <layer> --bone <bone> (or --bend --skeleton {})",+ o.name+ );+ }+ linked.iter().for_each(|l| match l.follows() {Some(b) => println!(" layer {} follows {b}", l.name),None => println!(" layer {} bends by the weights", l.name),});- painted(o).iter().for_each(|l| {+ linked.iter().for_each(|l| {l.cels().iter().filter_map(|c| c.pose.as_ref().map(|p| (c, p)))@@ -346,7 +356,7 @@ pub fn posed_pair(bundle: &Bundle, layer: &str, a: &str, b: &str) -> Result<Opti}let Some(owner) = owners(doc).into_iter()- .find(|o| family(o).iter().any(|l| l.id == layer))+ .find(|o| paint.rig.as_ref().is_some_and(|r| r.skeleton == o.id))else {return Ok(None);};@@ -359,7 +369,7 @@ pub fn posed_pair(bundle: &Bundle, layer: &str, a: &str, b: &str) -> Result<Optibones: owner.bones.clone(),ik: owner.ik.clone(),weights,- bone: paint.bone.clone(),+ bone: paint.follows().map(str::to_string),a: pa.clone(),b: pb,rest: bundle.read_marks(layer, &pa.rest)?,@@ -386,12 +396,17 @@ mod tests {let dir = std::env::temp_dir().join(format!("klad-rig-{name}-{}", std::process::id()));let _ = std::fs::remove_dir_all(&dir);let mut doc = Document::new(600, 400);- doc.layers = vec![Layer::paint("l1", "arm", "c1")];+ doc.layers = vec![Layer::group(+ "g9",+ "figure",+ vec![Layer::paint("l1", "arm", "c1"), Layer::skeleton("b1", "bones")],+ )];doc.timeline.frames = 9;doc.next_id = 10;Bundle::create(&dir, doc).unwrap();let ops = r##"{"op":"stroke","layer":"l1","brush":"ink","size":20,"color":"#c06a3a","path":"M100 200 L 300 200 L 480 200","part":"arm"}-{"op":"fill","layer":"l1","polygon":[[470,185],[520,188],[522,212],[470,215]],"color":"#e0b080","part":"hand"}"##;+{"op":"fill","layer":"l1","polygon":[[470,185],[520,188],[522,212],[470,215]],"color":"#e0b080","part":"hand"}+{"op":"attach","layer":"l1","skeleton":"b1"}"##;crate::agent::edit(&dir, &parse_lines(ops).unwrap(), &quiet()).unwrap();dir}@@ -408,40 +423,57 @@ mod tests {}#[test]- fn an_attached_layer_moves_rigidly_with_its_bone_and_keeps_it_through_renames() {+ fn layers_anywhere_follow_the_bones_layer_and_keep_it_through_renames() {let dir = std::env::temp_dir().join(format!("klad-rig-attach-{}", std::process::id()));let _ = std::fs::remove_dir_all(&dir);let mut doc = Document::new(600, 400);- doc.layers = vec![Layer::group(- "g1",- "body",- vec![- Layer::paint("l1", "upper arm", "c1"),- Layer::paint("l2", "forearm", "c2"),- ],- )];+ doc.layers = vec![+ Layer::paint("l1", "upper arm", "c1"),+ Layer::group("g1", "front", vec![Layer::paint("l2", "forearm", "c2")]),+ Layer::skeleton("b1", "bones"),+ ];doc.timeline.frames = 9;doc.next_id = 10;Bundle::create(&dir, doc).unwrap();+ assert!(+ format!(+ "{:#}",+ edit(+ &dir,+ r#"{"op":"bone","layer":"l1","add":"upper","head":[0,0],"tail":[1,1]}"#+ )+ .unwrap_err()+ )+ .contains("bones layer"),+ "bones go on a bones layer only"+ );edit(&dir,r##"{"op":"stroke","layer":"l1","brush":"ink","size":20,"color":"#c06a3a","path":"M100 200 L 290 200"}{"op":"stroke","layer":"l2","brush":"ink","size":20,"color":"#c06a3a","path":"M260 200 L 480 200"}-{"op":"bone","layer":"g1","chain":["upper","fore"],"through":[[100,200],[300,200],[480,200]]}"##,+{"op":"bone","layer":"b1","chain":["upper","fore"],"through":[[100,200],[300,200],[480,200]]}"##,).unwrap();assert!(edit(&dir, r#"{"op":"attach","layer":"l2","bone":"wing"}"#).is_err(),- "only a bone the skeleton has"+ "only a bone the drawing has");edit(&dir,r#"{"op":"attach","layer":"l1","bone":"upper"}{"op":"attach","layer":"l2","bone":"fore"}-{"op":"pose","layer":"g1","from":0,"to":4,"bones":{"fore":90}}"#,+{"op":"pose","layer":"b1","from":0,"to":4,"bones":{"fore":90}}"#,).unwrap();let bundle = Bundle::open(&dir).unwrap();+ assert_eq!(+ bundle.doc.layer("l2").unwrap().rig,+ Some(klad_core::rig::Link {+ skeleton: "b1".into(),+ bone: Some("fore".into())+ }),+ "a layer in another group is rigged to the bones layer"+ );let line = |l: &str, f: u32| {let cel = bundle.doc.layer(l).unwrap().content_at(f).unwrap().id.clone();let marks = bundle.read_marks(l, &cel).unwrap();@@ -462,25 +494,37 @@ mod tests {(end.0 - 300.0).abs() < 0.5 && (end.1 - 380.0).abs() < 0.5,"and its end swings a quarter turn round the elbow: {end:?}");- edit(&dir, r#"{"op":"bone","layer":"g1","rename":"fore","as":"forearm"}"#).unwrap();+ edit(&dir, r#"{"op":"bone","layer":"b1","rename":"fore","as":"forearm"}"#).unwrap();let bundle = Bundle::open(&dir).unwrap();- assert_eq!(bundle.doc.layer("l2").unwrap().bone.as_deref(), Some("forearm"));- edit(&dir, r#"{"op":"bone","layer":"g1","rm":"upper"}"#).unwrap();+ assert_eq!(bundle.doc.layer("l2").unwrap().follows(), Some("forearm"));+ edit(&dir, r#"{"op":"bone","layer":"b1","rm":"upper"}"#).unwrap();let bundle = Bundle::open(&dir).unwrap();assert!(- ["l1", "l2"].iter().all(|l| bundle.doc.layer(l).unwrap().bone.is_none()),- "removing a bone (and the bones on it) lets their layers bend again"+ ["l1", "l2"].iter().all(|l| bundle.doc.layer(l).unwrap().rig.is_none()),+ "removing a bone (and the bones on it) unrigs their layers");edit(&dir,- r#"{"op":"bone","layer":"g1","chain":["upper","fore"],"through":[[100,200],[300,200],[480,200]]}-{"op":"attach","layer":"l2","bone":"fore"}-{"op":"attach","layer":"l2"}"#,+ r#"{"op":"bone","layer":"b1","chain":["upper","fore"],"through":[[100,200],[300,200],[480,200]]}+{"op":"attach","layer":"l2","skeleton":"bones"}"#,).unwrap();+ let bundle = Bundle::open(&dir).unwrap();+ assert_eq!(+ bundle+ .doc+ .layer("l2")+ .unwrap()+ .rig+ .as_ref()+ .map(|r| (r.skeleton.as_str(), r.bone.is_none())),+ Some(("b1", true)),+ "a skeleton without a bone bends"+ );+ edit(&dir, r#"{"op":"rm","ids":["b1"]}"#).unwrap();assert!(- Bundle::open(&dir).unwrap().doc.layer("l2").unwrap().bone.is_none(),- "no bone detaches"+ Bundle::open(&dir).unwrap().doc.layer("l2").unwrap().rig.is_none(),+ "removing the bones layer unrigs its layers");std::fs::remove_dir_all(&dir).unwrap();}@@ -490,19 +534,19 @@ mod tests {let dir = arm("ik");edit(&dir,- r#"{"op":"bone","layer":"l1","chain":["upper","fore","hand"],"through":[[100,200],[300,200],[480,200],[520,200]]}-{"op":"ik","layer":"l1","add":"fore"}-{"op":"weights","layer":"l1","auto":true}"#,+ r#"{"op":"bone","layer":"b1","chain":["upper","fore","hand"],"through":[[100,200],[300,200],[480,200],[520,200]]}+{"op":"ik","layer":"b1","add":"fore"}+{"op":"weights","layer":"b1","auto":true}"#,).unwrap();let bundle = Bundle::open(&dir).unwrap();- let owner = bundle.doc.layer("l1").unwrap().clone();+ let owner = bundle.doc.layer("b1").unwrap().clone();assert_eq!(owner.ik.len(), 1);assert_eq!(owner.bones[1].parent.as_deref(), Some("upper"));assert!(edit(&dir,- r#"{"op":"pose","layer":"l1","from":0,"to":4,"ik":{"hand":{"target":[1,1]}}}"#+ r#"{"op":"pose","layer":"b1","from":0,"to":4,"ik":{"hand":{"target":[1,1]}}}"#).is_err(),"a target needs an IK on that bone"@@ -510,8 +554,8 @@ mod tests {let target = [400.0, 300.0];edit(&dir,- r#"{"op":"pose","layer":"l1","from":0,"to":4,"ik":{"fore":{"target":[400,300]}}}-{"op":"pose","layer":"l1","from":0,"to":8,"root":[40,-30],"ik":{"fore":{"target":[400,300]}}}"#,+ r#"{"op":"pose","layer":"b1","from":0,"to":4,"ik":{"fore":{"target":[400,300]}}}+{"op":"pose","layer":"b1","from":0,"to":8,"root":[40,-30],"ik":{"fore":{"target":[400,300]}}}"#,).unwrap();edit(&dir, r#"{"op":"inbetween","layers":["l1"],"from":4,"to":8}"#).unwrap();@@ -582,7 +626,7 @@ mod tests {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();+ edit(&dir, r#"{"op":"ik","layer":"b1","rm":"fore"}"#).unwrap();let bundle = Bundle::open(&dir).unwrap();let kept = bundle.doc@@ -604,9 +648,9 @@ mod tests {let dir = arm("again");edit(&dir,- r#"{"op":"bone","layer":"l1","chain":["upper","fore"],"through":[[100,200],[300,200],[480,200]]}-{"op":"weights","layer":"l1","auto":true}-{"op":"pose","layer":"l1","from":0,"to":4,"bones":{"fore":-60}}"#,+ r#"{"op":"bone","layer":"b1","chain":["upper","fore"],"through":[[100,200],[300,200],[480,200]]}+{"op":"weights","layer":"b1","auto":true}+{"op":"pose","layer":"b1","from":0,"to":4,"bones":{"fore":-60}}"#,).unwrap();let make = r#"{"op":"inbetween","layers":["l1"],"from":0,"to":4}"#;@@ -643,7 +687,7 @@ mod tests {edit(&dir, make).expect("made again over the same keys, nobody drew on them");edit(&dir,- r#"{"op":"pose","layer":"l1","from":4,"to":4,"bones":{"fore":-90}}"#,+ r#"{"op":"pose","layer":"b1","from":4,"to":4,"bones":{"fore":-90}}"#,).unwrap();edit(&dir, r#"{"op":"inbetween","redo":true}"#).expect("redone after the key changed");@@ -688,32 +732,43 @@ mod tests {let dir = arm("shift");edit(&dir,- r#"{"op":"bone","layer":"l1","chain":["upper","fore","hand"],"through":[[100,200],[300,200],[480,200],[520,200]]}-{"op":"ik","layer":"l1","add":"fore"}-{"op":"weights","layer":"l1","auto":true}-{"op":"pose","layer":"l1","from":0,"to":4,"ik":{"fore":{"target":[400,300]}}}"#,+ r#"{"op":"bone","layer":"b1","chain":["upper","fore","hand"],"through":[[100,200],[300,200],[480,200],[520,200]]}+{"op":"ik","layer":"b1","add":"fore"}+{"op":"weights","layer":"b1","auto":true}+{"op":"pose","layer":"b1","from":0,"to":4,"ik":{"fore":{"target":[400,300]}}}"#,).unwrap();let before = Bundle::open(&dir).unwrap();let (rest, posed) = (end_of(&before, 0), end_of(&before, 4));let strongest = |b: &Bundle, at: [f32; 2]| {- let layer = b.doc.layer("l1").unwrap();- let w = b.read_weights("l1").unwrap().at(&layer.bones, at);+ let layer = b.doc.layer("b1").unwrap();+ let w = b.read_weights("b1").unwrap().at(&layer.bones, at);(0..w.len()).max_by(|x, y| w[*x].total_cmp(&w[*y])).unwrap()};let held = strongest(&before, [200.0, 200.0]);- edit(&dir, r#"{"op":"transform","layer":"l1","x":12,"y":20}"#).unwrap();+ edit(&dir, r#"{"op":"transform","layer":"g9","x":12,"y":20}"#).unwrap();let after = Bundle::open(&dir).unwrap();let moved = |a: (f32, f32), b: (f32, f32)| (b.0 - a.0 - 12.0).abs() < 0.01 && (b.1 - a.1 - 20.0).abs() < 0.01;assert!(moved(rest, end_of(&after, 0)), "the rest drawing moves");assert!(moved(posed, end_of(&after, 4)), "and the posed one");- let layer = after.doc.layer("l1").unwrap();- assert_eq!(layer.bones[0].head, [112.0, 220.0], "the bones move along");- let pose = layer.content_at(4).unwrap().pose.clone().unwrap();+ assert_eq!(+ after.doc.layer("b1").unwrap().bones[0].head,+ [112.0, 220.0],+ "the bones move along"+ );+ let pose = after+ .doc+ .layer("l1")+ .unwrap()+ .content_at(4)+ .unwrap()+ .pose+ .clone()+ .unwrap();assert_eq!(pose.ik["fore"].target, [412.0, 320.0], "so does the pose's target");assert_eq!(strongest(&after, [212.0, 220.0]), held, "and the weights");let was = end_of(&after, 0);- edit(&dir, r#"{"op":"transform","layer":"l1","rotate":90,"pivot":[300,200]}"#).unwrap();+ edit(&dir, r#"{"op":"transform","layer":"g9","rotate":90,"pivot":[300,200]}"#).unwrap();let turned = end_of(&Bundle::open(&dir).unwrap(), 0);let want = (300.0 - (was.1 - 200.0), 200.0 + (was.0 - 300.0));assert!(@@ -722,13 +777,13 @@ mod tests {);let once = Bundle::open(&dir).unwrap();let (zero, four) = (end_of(&once, 0), end_of(&once, 4));- edit(&dir, r#"{"op":"transform","layer":"l1","x":5,"only":4}"#).unwrap();+ edit(&dir, r#"{"op":"transform","layer":"g9","x":5,"only":4}"#).unwrap();let only = Bundle::open(&dir).unwrap();assert_eq!(end_of(&only, 0), zero, "only the drawing at frame 4 moves");assert!((end_of(&only, 4).0 - four.0 - 5.0).abs() < 0.01);assert_eq!(- only.doc.layer("l1").unwrap().bones,- once.doc.layer("l1").unwrap().bones,+ only.doc.layer("b1").unwrap().bones,+ once.doc.layer("b1").unwrap().bones,"and the bones stay");std::fs::remove_dir_all(&dir).unwrap();@@ -760,35 +815,35 @@ mod tests {let dir = arm("pose");edit(&dir,- r#"{"op":"bone","layer":"l1","add":"upper","head":[100,200],"tail":[300,200]}-{"op":"bone","layer":"l1","add":"fore","parent":"upper","head":[300,200],"tail":[480,200]}-{"op":"bone","layer":"l1","add":"hand","parent":"fore","head":[480,200],"tail":[520,200]}"#,+ r#"{"op":"bone","layer":"b1","add":"upper","head":[100,200],"tail":[300,200]}+{"op":"bone","layer":"b1","add":"fore","parent":"upper","head":[300,200],"tail":[480,200]}+{"op":"bone","layer":"b1","add":"hand","parent":"fore","head":[480,200],"tail":[520,200]}"#,).unwrap();assert!(edit(&dir,- r#"{"op":"bone","layer":"l1","add":"fore","head":[0,0],"tail":[1,1]}"#+ r#"{"op":"bone","layer":"b1","add":"fore","head":[0,0],"tail":[1,1]}"#).is_err());edit(&dir,- r#"{"op":"weights","layer":"l1","auto":true}-{"op":"weights","layer":"l1","bone":"hand","part":"hand"}"#,+ r#"{"op":"weights","layer":"b1","auto":true}+{"op":"weights","layer":"b1","bone":"hand","part":"hand"}"#,).unwrap();let bundle = Bundle::open(&dir).unwrap();- let w = bundle.read_weights("l1").unwrap();+ let w = bundle.read_weights("b1").unwrap();assert_eq!(w.maps.len(), 3);- let bones = &bundle.doc.layer("l1").unwrap().bones;+ let bones = &bundle.doc.layer("b1").unwrap().bones;assert!(w.at(bones, [500.0, 200.0])[2] > 0.99,"the hand part is the hand bone's alone");edit(&dir,- r#"{"op":"pose","layer":"l1","from":0,"to":4,"bones":{"fore":-90}}"#,+ r#"{"op":"pose","layer":"b1","from":0,"to":4,"bones":{"fore":-90}}"#,).unwrap();let bundle = Bundle::open(&dir).unwrap();@@ -801,7 +856,7 @@ mod tests {assert_eq!(posed.pose.as_ref().unwrap().rest, "c1");edit(&dir,- r#"{"op":"pose","layer":"l1","from":4,"to":4,"bones":{"fore":-45}}"#,+ r#"{"op":"pose","layer":"b1","from":4,"to":4,"bones":{"fore":-45}}"#,).unwrap();let bundle = Bundle::open(&dir).unwrap();@@ -821,9 +876,9 @@ mod tests {(reach - 180.0).abs() < 4.0,"the forearm keeps its length on bones: {reach}");- edit(&dir, r#"{"op":"bone","layer":"l1","rename":"fore","as":"forearm"}"#).unwrap();+ edit(&dir, r#"{"op":"bone","layer":"b1","rename":"fore","as":"forearm"}"#).unwrap();let bundle = Bundle::open(&dir).unwrap();- assert!(bundle.read_weights("l1").unwrap().maps.contains_key("forearm"));+ assert!(bundle.read_weights("b1").unwrap().maps.contains_key("forearm"));assert!(bundle.doc@@ -840,18 +895,18 @@ mod tests {let mut bundle = Bundle::open(&dir).unwrap();klad_core::history::step(&mut bundle, klad_core::history::Stack::Undo).unwrap();assert!(- bundle.read_weights("l1").unwrap().maps.contains_key("fore"),+ bundle.read_weights("b1").unwrap().maps.contains_key("fore"),"undo restores the weights file");- edit(&dir, r#"{"op":"bone","layer":"l1","move":"fore","tail":[470,230]}"#).unwrap();- let bones = Bundle::open(&dir).unwrap().doc.layer("l1").unwrap().bones.clone();+ edit(&dir, r#"{"op":"bone","layer":"b1","move":"fore","tail":[470,230]}"#).unwrap();+ let bones = Bundle::open(&dir).unwrap().doc.layer("b1").unwrap().bones.clone();assert_eq!(bones[2].head,[470.0, 230.0],"the hand starts where the forearm now ends");- edit(&dir, r#"{"op":"bone","layer":"l1","move":"upper","by":[0,-20]}"#).unwrap();- let lifted = Bundle::open(&dir).unwrap().doc.layer("l1").unwrap().bones.clone();+ edit(&dir, r#"{"op":"bone","layer":"b1","move":"upper","by":[0,-20]}"#).unwrap();+ let lifted = Bundle::open(&dir).unwrap().doc.layer("b1").unwrap().bones.clone();assert!(lifted.iter()@@ -859,9 +914,9 @@ mod tests {.all(|(a, b)| a.head == [b.head[0], b.head[1] - 20.0] && a.tail == [b.tail[0], b.tail[1] - 20.0]),"by moves a bone with its children: {lifted:?}");- edit(&dir, r#"{"op":"bone","layer":"l1","rm":"upper"}"#).unwrap();+ edit(&dir, r#"{"op":"bone","layer":"b1","rm":"upper"}"#).unwrap();assert!(- Bundle::open(&dir).unwrap().doc.layer("l1").unwrap().bones.is_empty(),+ Bundle::open(&dir).unwrap().doc.layer("b1").unwrap().bones.is_empty(),"removing a bone removes its children");std::fs::remove_dir_all(&dir).unwrap();diff --git a/crates/cli/src/scene.rs b/crates/cli/src/scene.rsindex fcc5692..72e6d89 100644--- a/crates/cli/src/scene.rs+++ b/crates/cli/src/scene.rs@@ -283,7 +283,7 @@ pub fn rig(path: &Path, dir: Option<PathBuf>) -> Result<Vec<PathBuf>> {};let name = file_safe(&owner.name);let mut parts: Vec<Part> = Vec::new();- klad_core::rig::painted(owner).iter().try_for_each(|layer| -> Result<()> {+ klad_core::rig::painted(doc, &owner.id).iter().try_for_each(|layer| -> Result<()> {let Some(rest) = rest_cel(layer) else {return Ok(());};@@ -335,7 +335,7 @@ pub fn rig(path: &Path, dir: Option<PathBuf>) -> Result<Vec<PathBuf>> {origin: [x0 as f32, y0 as f32],vertices,triangles,- bone: layer.bone.as_ref().and_then(|b| bones.iter().position(|o| &o.name == b)),+ bone: layer.follows().and_then(|b| bones.iter().position(|o| o.name == b)),});Ok(())})@@ -364,7 +364,10 @@ pub fn rig(path: &Path, dir: Option<PathBuf>) -> Result<Vec<PathBuf>> {.map(|c| (c.name.clone(), c.from, c.to, c.looping, c.fps.map_or(fps, |f| f as f32))).collect(),};- let first = klad_core::rig::painted(owner).into_iter().next().context("no paint layer under the bones")?;+ let first = klad_core::rig::painted(doc, &owner.id)+ .into_iter()+ .next()+ .context("no layer is attached to the bones: klad attach a layer to them first")?;let mut unposed = Vec::new();let animations: Vec<String> = clips.iter()@@ -560,7 +563,7 @@ var scene: Nodevar camera: Camera2Dfunc _initialize():- var rig = load("res://art/arm-arm-rig.tscn").instantiate()+ var rig = load("res://art/arm-arm_bones-rig.tscn").instantiate()root.add_child(rig)var player: AnimationPlayer = rig.get_node("AnimationPlayer")var bone: Bone2D = rig.get_node("Skeleton2D/upper/fore")@@ -621,7 +624,11 @@ func _process(_delta):let mut doc = Document::new(600, 400);doc.canvas.background = Some("#f0e8dc".into());doc.timeline.frames = 8;- doc.layers = vec![Layer::paint("far", "far", "c1"), Layer::paint("arm", "arm", "c2")];+ doc.layers = vec![+ Layer::paint("far", "far", "c1"),+ Layer::paint("arm", "arm", "c2"),+ Layer::skeleton("rig", "arm bones"),+ ];doc.layers[0].depth = Some(3.0);doc.next_id = 10;Bundle::create(&path, doc).unwrap();@@ -629,14 +636,15 @@ func _process(_delta):edit(r##"{"op":"fill","layer":"far","polygon":[[0,250],[600,250],[600,400],[0,400]],"color":"#8090a0"}{"op":"stroke","layer":"arm","brush":"ink","size":24,"color":"#c06a3a","path":"M100 200 L 300 200 L 480 200"}-{"op":"clip","add":"wave","from":0,"to":7,"loop":true}"##,+{"op":"clip","add":"wave","from":0,"to":7,"loop":true}+{"op":"attach","layer":"arm","skeleton":"rig"}"##,);edit(- r#"{"op":"bone","layer":"arm","add":"upper","head":[100,200],"tail":[300,200]}-{"op":"bone","layer":"arm","add":"fore","parent":"upper","head":[300,200],"tail":[480,200]}"#,+ r#"{"op":"bone","layer":"rig","add":"upper","head":[100,200],"tail":[300,200]}+{"op":"bone","layer":"rig","add":"fore","parent":"upper","head":[300,200],"tail":[480,200]}"#,);- edit(r#"{"op":"weights","layer":"arm","auto":true}"#);- edit(r#"{"op":"pose","layer":"arm","from":0,"to":4,"bones":{"fore":-70}}"#);+ edit(r#"{"op":"weights","layer":"rig","auto":true}"#);+ edit(r#"{"op":"pose","layer":"rig","from":0,"to":4,"bones":{"fore":-70}}"#);let made = rig(&path, Some(project.join("art"))).unwrap();let text = fs::read_to_string(made.last().unwrap()).unwrap();assert!(text.contains("type=\"Skeleton2D\"") && text.contains("NodePath(\"Skeleton2D/upper/fore:rotation\")"));diff --git a/crates/cli/tests/binary.rs b/crates/cli/tests/binary.rsindex a393b8d..b1b0012 100644--- a/crates/cli/tests/binary.rs+++ b/crates/cli/tests/binary.rs@@ -275,23 +275,26 @@ fn a_chain_and_its_ik_are_set_up_and_posed_from_the_command_line() {"--size","6",]);+ klad(&["add", path, "layer", "bones", "name=bones"]);let made = klad(&["bone",path,- "l1",+ "bones","--chain","thigh,shin","--through","100,100 100,200 100,300",]);assert!(made.contains("chain thigh, shin"), "{made}");- let ik = klad(&["ik", path, "l1", "--add", "shin", "--softness", "4"]);+ let rigged = klad(&["attach", path, "l1", "--bend", "--skeleton", "bones"]);+ assert!(rigged.contains("bends with bones"), "{rigged}");+ let ik = klad(&["ik", path, "bones", "--add", "shin", "--softness", "4"]);assert!(ik.contains("a limb with thigh") && ik.contains("softness 4"), "{ik}");- klad(&["ik", path, "l1", "--set", "shin", "--bend", "flip"]);+ klad(&["ik", path, "bones", "--set", "shin", "--bend", "flip"]);klad(&["pose",path,- "l1",+ "bones","--from","0","--to",@@ -316,7 +319,7 @@ fn a_chain_and_its_ik_are_set_up_and_posed_from_the_command_line() {.args(["pose",path,- "l1",+ "bones","--from","0","--to",diff --git a/crates/core/src/doc.rs b/crates/core/src/doc.rsindex 7e27a83..e0f1586 100644--- a/crates/core/src/doc.rs+++ b/crates/core/src/doc.rs@@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize};use std::borrow::Cow;use std::collections::{BTreeMap, BTreeSet};-pub const FORMAT: &str = "klad/3";+pub const FORMAT: &str = "klad/4";pub const MAX_SIZE: u32 = 16384;pub const MASK: usize = usize::MAX;@@ -150,7 +150,7 @@ pub struct Layer {#[serde(default, skip_serializing_if = "Vec::is_empty")]pub ik: Vec<crate::rig::Ik>,#[serde(default, skip_serializing_if = "Option::is_none")]- pub bone: Option<String>,+ pub rig: Option<crate::rig::Link>,#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]pub keys: crate::keys::Keys,}@@ -173,6 +173,7 @@ pub enum LayerContent {Adjust {adjust: Adjustment,},+ Bones {},}#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]@@ -181,6 +182,7 @@ pub enum Kind {Vector,Group,Adjust,+ Bones,}impl Kind {@@ -190,6 +192,7 @@ impl Kind {Kind::Vector => "vector",Kind::Group => "group",Kind::Adjust => "adjust",+ Kind::Bones => "bones",}}}@@ -526,7 +529,7 @@ impl Layer {reference: false,bones: Vec::new(),ik: Vec::new(),- bone: None,+ rig: None,keys: BTreeMap::new(),}}@@ -555,12 +558,21 @@ impl Layer {Self::with(id, name, LayerContent::Adjust { adjust })}+ pub fn skeleton(id: &str, name: &str) -> Self {+ Self::with(id, name, LayerContent::Bones {})+ }++ pub fn follows(&self) -> Option<&str> {+ self.rig.as_ref().and_then(|r| r.bone.as_deref())+ }+pub fn kind(&self) -> Kind {match self.content {LayerContent::Paint { .. } => Kind::Paint,LayerContent::Vector { .. } => Kind::Vector,LayerContent::Group { .. } => Kind::Group,LayerContent::Adjust { .. } => Kind::Adjust,+ LayerContent::Bones {} => Kind::Bones,}}@@ -578,14 +590,14 @@ impl Layer {pub fn cels(&self) -> &[Cel] {match &self.content {LayerContent::Paint { cels } | LayerContent::Vector { cels } => cels,- LayerContent::Group { .. } | LayerContent::Adjust { .. } => &[],+ LayerContent::Group { .. } | LayerContent::Adjust { .. } | LayerContent::Bones {} => &[],}}pub fn cels_mut(&mut self) -> Option<&mut Vec<Cel>> {match &mut self.content {LayerContent::Paint { cels } | LayerContent::Vector { cels } => Some(cels),- LayerContent::Group { .. } | LayerContent::Adjust { .. } => None,+ LayerContent::Group { .. } | LayerContent::Adjust { .. } | LayerContent::Bones {} => None,}}@@ -1238,16 +1250,20 @@ impl Document {.try_for_each(|(c, p)| {crate::rig::check_pose(p).with_context(|| format!("layer {}: cel {}", layer.id, c.id))})?;- if let Some(bone) = &layer.bone {+ if let Some(link) = &layer.rig {if layer.kind() != Kind::Paint {- bail!("layer {}: only paint layers follow a bone", layer.id);+ bail!("layer {}: only paint layers are rigged", layer.id);}- let Some(Loc::Layer(path)) = self.locate(&layer.id) else {- bail!("layer {} is not in the drawing", layer.id);- };- let owner = crate::rig::skeleton_of(self, &path)- .ok_or_else(|| anyhow!("layer {}: follows bone {bone}, but no skeleton holds it", layer.id))?;- if !owner.bones.iter().any(|b| &b.name == bone) {+ let owner = crate::rig::linked(self, layer).ok_or_else(|| {+ anyhow!(+ "layer {}: rigged to {}, which is not a bones layer",+ layer.id,+ link.skeleton+ )+ })?;+ if let Some(bone) = &link.bone+ && !owner.bones.iter().any(|b| &b.name == bone)+ {bail!("layer {}: follows bone {bone}, which {} does not have",layer.id,@@ -1256,8 +1272,8 @@ impl Document {}}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);+ if layer.kind() != Kind::Bones {+ bail!("layer {}: bones go on a bones layer", layer.id);}crate::rig::check(&layer.bones).with_context(|| format!("layer {}", layer.id))?;crate::rig::check_ik(&layer.bones, &layer.ik).with_context(|| format!("layer {}", layer.id))?;diff --git a/crates/core/src/migrate.rs b/crates/core/src/migrate.rsindex 34ad969..7117bc1 100644--- a/crates/core/src/migrate.rs+++ b/crates/core/src/migrate.rs@@ -10,9 +10,12 @@ pub fn migrate(value: Value) -> Result<Value> {.to_string();match format.as_str() {FORMAT => Ok(value),- "klad/1" | "klad/2" => {+ "klad/1" | "klad/2" | "klad/3" => {let mut value = value;value["format"] = Value::from(FORMAT);+ if let Some(layers) = value.get_mut("layers").and_then(Value::as_array_mut) {+ layers.iter_mut().for_each(unrig);+ }Ok(value)}old if old.starts_with("draw-anything/") => bail!(@@ -23,6 +26,28 @@ pub fn migrate(value: Value) -> Result<Value> {}}+fn unrig(layer: &mut Value) {+ let Some(map) = layer.as_object_mut() else {+ return;+ };+ ["bones", "ik", "bone", "rig"].iter().for_each(|k| {+ map.remove(*k);+ });+ if let Some(cels) = map.get_mut("cels").and_then(Value::as_array_mut) {+ cels.iter_mut().filter_map(Value::as_object_mut).for_each(|c| {+ c.remove("pose");+ });+ }+ ["children"].iter().for_each(|k| {+ if let Some(list) = map.get_mut(*k).and_then(Value::as_array_mut) {+ list.iter_mut().for_each(unrig);+ }+ });+ if let Some(mask) = map.get_mut("mask") {+ unrig(mask);+ }+}+#[cfg(test)]mod tests {use super::*;@@ -34,7 +59,7 @@ mod tests {assert_eq!(migrate(current.clone()).unwrap(), current);let old = migrate(json!({"format": "draw-anything/9"})).unwrap_err().to_string();assert!(old.contains("old .draw format") && old.contains(FORMAT), "{old}");- let first = json!({"format": "klad/1", "rev": 3, "layers": [{"id": "l1", "bones": [{"name": "hip", "head": [0, 0], "tail": [0, 9]}]}]});+ let first = json!({"format": "klad/1", "rev": 3, "layers": [{"id": "l1", "kind": "paint", "cels": [{"id": "c1", "frame": 0}]}]});let mut moved = first.clone();moved["format"] = json!(FORMAT);assert_eq!(@@ -42,6 +67,17 @@ mod tests {moved,"a klad/1 drawing opens as it was, in the new format");+ let rigged = json!({"format": "klad/3", "layers": [{"id": "g1", "kind": "group", "bones": [{"name": "hip", "head": [0, 0], "tail": [0, 9]}], "ik": [], "children": [+ {"id": "l1", "kind": "paint", "bone": "hip", "cels": [{"id": "c1", "frame": 0}, {"id": "c2", "frame": 4, "pose": {"rest": "c1", "angles": {"hip": 20}}}]}+ ]}]});+ let opened = migrate(rigged).unwrap();+ assert_eq!(+ opened,+ json!({"format": FORMAT, "layers": [{"id": "g1", "kind": "group", "children": [+ {"id": "l1", "kind": "paint", "cels": [{"id": "c1", "frame": 0}, {"id": "c2", "frame": 4}]}+ ]}]}),+ "rigs from before bones layers are dropped; the drawings, posed ones too, stay"+ );assert!(migrate(json!({"format": "klad/7"})).unwrap_err()diff --git a/crates/core/src/ops.rs b/crates/core/src/ops.rsindex 0f8f42b..2a9e4e6 100644--- a/crates/core/src/ops.rs+++ b/crates/core/src/ops.rs@@ -33,6 +33,7 @@ const LAYER_KEYS: &[&str] = &["reference","bones","ik",+ "rig","keys",];const CEL_KEYS: &[&str] = &["id", "frame", "hold", "link", "tween", "nodes", "parts", "pose"];@@ -52,7 +53,7 @@ const NODE_KEYS: &[&str] = &[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", "bones", "ik", "keys", "pose", "parts",+ "id", "kind", "type", "cels", "children", "nodes", "mask", "bones", "ik", "rig", "keys", "pose", "parts",];fn shape_keys(kind: &str) -> Result<&'static [&'static str]> {@@ -681,6 +682,8 @@ pub struct Shifted {pub struct AttachSpec {pub layer: String,#[serde(default)]+ pub skeleton: Option<String>,+ #[serde(default)]pub bone: Option<String>,}@@ -1736,8 +1739,12 @@ pub fn solo(doc: &Document, id: &str) -> Result<Vec<Op>> {pub fn rig_owner<'a>(doc: &'a Document, id: &str) -> Result<&'a Layer> {let layer = doc.find_layer(id)?;match layer.kind() {- Kind::Paint | Kind::Group => Ok(layer),- _ => bail!("bones go on a paint layer or a group; {} is neither", layer.name),+ Kind::Bones => Ok(layer),+ _ => bail!(+ "bones go on a bones layer; {} is a {} layer: add one with klad add <bundle> layer bones (or Layer > New bones layer) and attach layers to it",+ layer.name,+ layer.kind().name()+ ),}}@@ -1841,20 +1848,23 @@ fn bone(doc: &mut Document, spec: &BoneSpec, out: &mut Applied) -> Result<()> {.iter().filter_map(|p| {let layer = doc.layer_at_mut(p);- layer.bone.take_if(|b| gone.contains(b)).map(|_| layer.name.clone())+ let link = layer+ .rig+ .take_if(|l| l.bone.as_ref().is_some_and(|b| gone.contains(b)))?;+ link.bone.map(|_| layer.name.clone())}).collect();if !loose.is_empty() {out.notes.push(format!(- "{} followed a removed bone, so {} by the weights again",+ "{} followed a removed bone, so {} not rigged now",loose.join(", "),match loose.len() {- 1 => "it bends",- _ => "they bend",+ 1 => "it is",+ _ => "they are",}));}- crate::doc::family_paths(doc, &path).iter().for_each(|p| {+ crate::rig::painted_paths(doc, &id).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));@@ -1888,7 +1898,7 @@ fn bone(doc: &mut Document, spec: &BoneSpec, out: &mut Applied) -> Result<()> {ik.iter_mut().filter(|c| &c.bone == name).for_each(|c| c.bone = to.clone());- let rigged: Vec<Vec<usize>> = crate::doc::family_paths(doc, &path);+ let rigged: Vec<Vec<usize>> = crate::rig::painted_paths(doc, &id);rigged.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| {@@ -1903,8 +1913,8 @@ fn bone(doc: &mut Document, spec: &BoneSpec, out: &mut Applied) -> Result<()> {});followers(doc, &path).iter().for_each(|p| {let layer = doc.layer_at_mut(p);- if layer.bone.as_ref() == Some(name) {- layer.bone = Some(to.clone());+ if let Some(link) = layer.rig.as_mut().filter(|l| l.bone.as_ref() == Some(name)) {+ link.bone = Some(to.clone());}});out.renamed_bones.push((id.clone(), name.clone(), to.clone()));@@ -1968,11 +1978,7 @@ fn bone(doc: &mut Document, spec: &BoneSpec, out: &mut Applied) -> Result<()> {}fn followers(doc: &Document, owner: &[usize]) -> Vec<Vec<usize>> {- let id = &doc.layer_at(owner).id;- crate::doc::family_paths(doc, owner)- .into_iter()- .filter(|p| crate::rig::skeleton_of(doc, p).is_some_and(|s| &s.id == id))- .collect()+ crate::rig::painted_paths(doc, &doc.layer_at(owner).id)}fn attach(doc: &mut Document, spec: &AttachSpec, out: &mut Applied) -> Result<()> {@@ -1981,15 +1987,34 @@ fn attach(doc: &mut Document, spec: &AttachSpec, out: &mut Applied) -> Result<()};let layer = doc.layer_at(&path);if layer.kind() != crate::doc::Kind::Paint {- bail!("{} is not a paint layer: only paint layers follow a bone", layer.name);+ bail!("{} is not a paint layer: only paint layers are rigged", layer.name);}- let Some(owner) = crate::rig::skeleton_of(doc, &path) else {- bail!(- "{} is not under a skeleton: draw bones on it or on a group around it first",- layer.name- );+ let skeletons = crate::rig::skeletons(doc);+ if skeletons.is_empty() && (spec.skeleton.is_some() || spec.bone.is_some()) {+ bail!("this drawing has no bones layer: add one with klad add <bundle> layer bones, then draw its bones");+ }+ let skeleton = match (&spec.skeleton, &spec.bone) {+ (Some(s), _) => Some(rig_owner(doc, s)?),+ (None, Some(b)) => {+ let holding: Vec<&Layer> = skeletons+ .iter()+ .copied()+ .filter(|s| s.bones.iter().any(|o| &o.name == b))+ .collect();+ let current = crate::rig::linked(doc, layer).filter(|s| holding.iter().any(|h| h.id == s.id));+ match (current, holding.as_slice()) {+ (Some(s), _) => Some(s),+ (None, [one]) => Some(*one),+ (None, []) => bail!("no bones layer has a bone {b}"),+ (None, _) => bail!(+ "{} bones layers have a bone {b}: say which with \"skeleton\" (--skeleton)",+ holding.len()+ ),+ }+ }+ (None, None) => None,};- if let Some(b) = &spec.bone+ if let (Some(owner), Some(b)) = (skeleton, &spec.bone)&& !owner.bones.iter().any(|o| &o.name == b){bail!(@@ -2003,12 +2028,18 @@ fn attach(doc: &mut Document, spec: &AttachSpec, out: &mut Applied) -> Result<().join(", "));}- let (name, id) = (layer.name.clone(), layer.id.clone());- doc.layer_at_mut(&path).bone = spec.bone.clone();- out.notes.push(match &spec.bone {- Some(b) => format!("{name} follows {b}"),- None => format!("{name} bends by the weights"),+ let link = skeleton.map(|s| crate::rig::Link {+ skeleton: s.id.clone(),+ bone: spec.bone.clone(),});+ let said = match (&link, skeleton) {+ (Some(crate::rig::Link { bone: Some(b), .. }), _) => format!("{} follows {b}", layer.name),+ (Some(_), Some(s)) => format!("{} bends with {} by the weights", layer.name, s.name),+ _ => format!("{} is not rigged: posing leaves it as it is", layer.name),+ };+ let id = layer.id.clone();+ doc.layer_at_mut(&path).rig = link;+ out.notes.push(said);out.changed.push(id);Ok(())}@@ -2030,7 +2061,8 @@ fn bake(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| {+ let owner = doc.layer_at(path).id.clone();+ crate::rig::painted_paths(doc, &owner).iter().for_each(|p| {let Some(cels) = doc.layer_at_mut(p).cels_mut() else {return;};@@ -2093,7 +2125,7 @@ fn kept_note(also: &[String]) -> String {}fn posed_with(doc: &Document, path: &[usize], bone: &str) -> Vec<u32> {- let mut frames: Vec<u32> = crate::doc::family_paths(doc, path)+ let mut frames: Vec<u32> = crate::rig::painted_paths(doc, &doc.layer_at(path).id).iter().flat_map(|p| {doc.layer_at(p)@@ -2789,6 +2821,7 @@ fn assign_layer_ids(doc: &mut Document, taken: &mut BTreeSet<String>, value: &mu.try_for_each(|c| assign_layer_ids(doc, taken, c).map(|_| ()))?;}}+ "bones" => {}"adjust" => {if value.get("adjust").is_none() {bail!(@@ -2797,7 +2830,7 @@ fn assign_layer_ids(doc: &mut Document, taken: &mut BTreeSet<String>, value: &mu);}}- other => bail!("unknown layer kind {other:?}: use paint, vector, group or adjust"),+ other => bail!("unknown layer kind {other:?}: use paint, vector, group, adjust or bones"),}if let Some(mask) = value.get_mut("mask").filter(|m| !m.is_null()) {mask_defaults(mask)?;@@ -3150,6 +3183,33 @@ fn remove(doc: &mut Document, id: &str, out: &mut Applied) -> Result<()> {.ok_or_else(|| anyhow!("parent is not a group"))?;let layer = list.remove(index);out.dropped_cels.extend(paint_cels_of(&layer));+ let mut gone = vec![&layer];+ crate::doc::walk_children(&layer, &mut gone);+ let skeletons: Vec<String> = gone+ .iter()+ .filter(|l| l.kind() == Kind::Bones)+ .map(|l| l.id.clone())+ .collect();+ if !skeletons.is_empty() {+ let paths: Vec<Vec<usize>> = skeletons+ .iter()+ .flat_map(|s| crate::rig::painted_paths(doc, s))+ .collect();+ let names: Vec<String> = paths+ .iter()+ .map(|p| {+ let l = doc.layer_at_mut(p);+ l.rig = None;+ l.name.clone()+ })+ .collect();+ if !names.is_empty() {+ out.notes.push(format!(+ "{} lost their bones layer, so they are not rigged now",+ names.join(", ")+ ));+ }+ }}Loc::Cel(path, c) => {let layer = doc.layer_at_mut(&path);@@ -3224,6 +3284,7 @@ pub fn apply(doc: &mut Document, op: &Op, out: &mut Applied) -> Result<()> {LayerContent::Paint { cels } | LayerContent::Vector { cels } => cels,LayerContent::Group { .. } => bail!("{layer} is a group; cels go into paint or vector layers"),LayerContent::Adjust { .. } => bail!("{layer} is an adjustment; cels go into paint or vector layers"),+ LayerContent::Bones {} => bail!("{layer} is a bones layer; cels go into paint or vector layers"),};if cels.iter().any(|c| c.frame == cel.frame) {bail!("layer {layer} already has a cel starting at frame {}", cel.frame);@@ -3726,15 +3787,14 @@ mod tests {#[test]fn chains_and_iks_follow_renames_and_go_without_changing_a_pose() {use crate::rig::{Bend, Ik, Pose, Reach, applied, tips};- let doc = base();- let ink = doc.find_layer("ink").unwrap().id.clone();+ let (doc, ink, rig) = rigged();let (doc, applied_ops) = apply_all(&doc,- &ops(&[json!({"op":"bone","layer":ink,"chain":["thigh","shin","foot"],"through":[[100,100],[100,200],[90,300],[140,300]]})]),+ &ops(&[json!({"op":"bone","layer":rig,"chain":["thigh","shin","foot"],"through":[[100,100],[100,200],[90,300],[140,300]]})]),).unwrap();assert!(applied_ops.notes.iter().any(|n| n.contains("chain thigh, shin, foot")));- let bones = doc.layer(&ink).unwrap().bones.clone();+ let bones = doc.layer(&rig).unwrap().bones.clone();assert_eq!(bones.iter().map(|b| b.name.as_str()).collect::<Vec<_>>(),["thigh", "shin", "foot"]@@ -3748,15 +3808,15 @@ mod tests {);let short = apply_all(&doc,- &ops(&[json!({"op":"bone","layer":ink,"chain":["a","b"],"through":[[0,0],[9,9]]})]),+ &ops(&[json!({"op":"bone","layer":rig,"chain":["a","b"],"through":[[0,0],[9,9]]})]),).map(|_| ()).unwrap_err();let short = format!("{short:#}");assert!(short.contains("goes through 3 points"), "{short}");- let (doc, made) = apply_all(&doc, &ops(&[json!({"op":"ik","layer":ink,"add":"shin"})])).unwrap();+ let (doc, made) = apply_all(&doc, &ops(&[json!({"op":"ik","layer":rig,"add":"shin"})])).unwrap();assert_eq!(- doc.layer(&ink).unwrap().ik,+ doc.layer(&rig).unwrap().ik,[Ik {bone: "shin".into(),chain: 2,@@ -3772,12 +3832,12 @@ mod tests {);let (doc, _) = apply_all(&doc,- &ops(&[json!({"op":"ik","layer":ink,"set":"shin","bend":"flip","softness":6})]),+ &ops(&[json!({"op":"ik","layer":rig,"set":"shin","bend":"flip","softness":6})]),).unwrap();- let ik = doc.layer(&ink).unwrap().ik.clone();+ let ik = doc.layer(&rig).unwrap().ik.clone();assert_eq!((ik[0].bend, ik[0].softness), (Bend::Counterclockwise, 6.0));- let again = apply_all(&doc, &ops(&[json!({"op":"ik","layer":ink,"add":"shin"})]));+ let again = apply_all(&doc, &ops(&[json!({"op":"ik","layer":rig,"add":"shin"})]));assert!(format!("{:#}", again.map(|_| ()).unwrap_err()).contains("has an IK already"));let mut doc = doc;let path = layer_path(&doc, &ink).unwrap();@@ -3797,19 +3857,19 @@ mod tests {let looked = tips(&bones, &ik, &pose);let (doc, _) = apply_all(&doc,- &ops(&[json!({"op":"bone","layer":ink,"rename":"shin","as":"calf"})]),+ &ops(&[json!({"op":"bone","layer":rig,"rename":"shin","as":"calf"})]),).unwrap();- let layer = doc.layer(&ink).unwrap();- assert_eq!(layer.ik[0].bone, "calf", "the IK follows its bone's new name");+ let (layer, skel) = (doc.layer(&ink).unwrap(), doc.layer(&rig).unwrap());+ assert_eq!(skel.ik[0].bone, "calf", "the IK follows its bone's new name");let kept = layer.cels()[0].pose.clone().unwrap();assert!(kept.ik.contains_key("calf") && !kept.ik.contains_key("shin"));- let (doc, gone) = apply_all(&doc, &ops(&[json!({"op":"ik","layer":ink,"rm":"calf"})])).unwrap();+ let (doc, gone) = apply_all(&doc, &ops(&[json!({"op":"ik","layer":rig,"rm":"calf"})])).unwrap();assert!(gone.notes.iter().any(|n| n.contains("keep their look")));- let layer = doc.layer(&ink).unwrap();+ let (layer, skel) = (doc.layer(&ink).unwrap(), doc.layer(&rig).unwrap());let baked = layer.cels()[0].pose.clone().unwrap();- assert!(layer.ik.is_empty() && baked.ik.is_empty());- let now = tips(&layer.bones, &[], &baked);+ assert!(skel.ik.is_empty() && baked.ik.is_empty());+ let now = tips(&skel.bones, &[], &baked);assert!(now.iter().zip(&looked)@@ -3819,46 +3879,56 @@ mod tests {let (doc, _) = apply_all(&doc,&ops(&[- json!({"op":"ik","layer":ink,"add":"foot","chain":2}),- json!({"op":"bone","layer":ink,"reparent":"foot"}),+ json!({"op":"ik","layer":rig,"add":"foot","chain":2}),+ json!({"op":"bone","layer":rig,"reparent":"foot"}),]),).unwrap();assert!(- doc.layer(&ink).unwrap().ik.is_empty(),+ doc.layer(&rig).unwrap().ik.is_empty(),"a limb whose bone loses its parent goes");let (doc, _) = apply_all(&doc,&ops(&[- json!({"op":"bone","layer":ink,"reparent":"foot","parent":"calf"}),- json!({"op":"ik","layer":ink,"add":"foot"}),- json!({"op":"bone","layer":ink,"rm":"calf"}),+ json!({"op":"bone","layer":rig,"reparent":"foot","parent":"calf"}),+ json!({"op":"ik","layer":rig,"add":"foot"}),+ json!({"op":"bone","layer":rig,"rm":"calf"}),]),).unwrap();- let layer = doc.layer(&ink).unwrap();+ let skel = doc.layer(&rig).unwrap();assert!(- layer.ik.is_empty() && layer.bones.len() == 1,+ skel.ik.is_empty() && skel.bones.len() == 1,"removing a bone takes its children and their IK");- let solved = applied(&layer.bones, &layer.ik, &baked);+ let solved = applied(&skel.bones, &skel.ik, &baked);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();+ fn rigged() -> (Document, String, String) {+ let (doc, made) = apply_all(+ &base(),+ &ops(&[json!({"op":"add","layer":{"kind":"bones","name":"rig"}})]),+ )+ .unwrap();+ let (ink, rig) = (doc.find_layer("ink").unwrap().id.clone(), made.added[0].clone());+ let (doc, _) = apply_all(&doc, &ops(&[json!({"op":"attach","layer":ink,"skeleton":rig})])).unwrap();+ (doc, ink, rig)+ }++ fn leg_with(lines: &[Value]) -> (Document, String, String, Vec<usize>) {+ let (doc, ink, rig) = rigged();let mut all = vec![- json!({"op":"bone","layer":ink,"chain":["thigh","shin","foot"],"through":[[100,100],[100,200],[90,300],[140,300]]}),+ json!({"op":"bone","layer":rig,"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["layer"] = json!(rig);l}));let (doc, _) = apply_all(&doc, &ops(&all)).unwrap();let path = layer_path(&doc, &ink).unwrap();- (doc, ink, path)+ (doc, ink, rig, path)}fn posed(doc: &mut Document, path: &[usize], at: usize, pose: crate::rig::Pose) {@@ -3882,7 +3952,7 @@ mod tests {[("foot", 1.0), ("shin", 1.0), ("foot", 0.5), ("shin", 0.5)].into_iter().for_each(|(gone, mix)| {- let (mut doc, ink, path) =+ let (mut doc, ink, rig, path) =leg_with(&[json!({"op":"ik","add":"shin"}), json!({"op":"ik","add":"foot"})]);posed(&mut doc,@@ -3890,11 +3960,11 @@ mod tests {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());+ let (layer, skel) = (doc.layer(&ink).unwrap(), doc.layer(&rig).unwrap());+ let before = tips(&skel.bones, &skel.ik, layer.cels()[0].pose.as_ref().unwrap());+ let (doc, made) = apply_all(&doc, &ops(&[json!({"op":"ik","layer":rig,"rm":gone})])).unwrap();+ let (layer, skel) = (doc.layer(&ink).unwrap(), doc.layer(&rig).unwrap());+ let after = tips(&skel.bones, &skel.ik, layer.cels()[0].pose.as_ref().unwrap());assert!(before.iter()@@ -3912,7 +3982,7 @@ mod tests {#[test]fn baked_turns_stay_the_short_way_between_poses() {- let (mut doc, ink, path) = leg_with(&[json!({"op":"ik","add":"shin"})]);+ let (mut doc, ink, rig, path) = leg_with(&[json!({"op":"ik","add":"shin"})]);let at = |frame: u32, id: &str| crate::doc::Cel {id: id.into(),frame,@@ -3922,7 +3992,7 @@ mod tests {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 (doc, _) = apply_all(&doc, &ops(&[json!({"op":"ik","layer":rig,"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| {@@ -3937,7 +4007,7 @@ mod tests {#[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 doc, ink, rig, 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);@@ -3959,7 +4029,7 @@ mod tests {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 (doc, _) = apply_all(&doc, &ops(&[json!({"op":"bone","layer":rig,"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(),diff --git a/crates/core/src/patch.rs b/crates/core/src/patch.rsindex d60b495..4722e46 100644--- a/crates/core/src/patch.rs+++ b/crates/core/src/patch.rs@@ -111,6 +111,7 @@ fn layer_shell(layer: &Layer) -> Layer {LayerContent::Vector { .. } => LayerContent::Vector { cels: Vec::new() },LayerContent::Group { .. } => LayerContent::Group { children: Vec::new() },LayerContent::Adjust { adjust } => LayerContent::Adjust { adjust: adjust.clone() },+ LayerContent::Bones {} => LayerContent::Bones {},};Layer {id: layer.id.clone(),@@ -128,7 +129,7 @@ fn layer_shell(layer: &Layer) -> Layer {reference: layer.reference,bones: layer.bones.clone(),ik: layer.ik.clone(),- bone: layer.bone.clone(),+ rig: layer.rig.clone(),keys: layer.keys.clone(),}}@@ -188,7 +189,8 @@ fn layer(out: &mut Out, at: &str, a: &Layer, b: &Layer) -> Result<()> {LayerContent::Paint { cels: x } | LayerContent::Vector { cels: x },LayerContent::Paint { cels: y } | LayerContent::Vector { cels: y },) => list(out, &format!("{at}/cels"), x, y, same_cel, cel),- (LayerContent::Adjust { .. }, LayerContent::Adjust { .. }) => Ok(()),+ (LayerContent::Adjust { .. }, LayerContent::Adjust { .. })+ | (LayerContent::Bones {}, LayerContent::Bones {}) => Ok(()),_ => bail!("layer {} changed kind", a.id),}}@@ -240,7 +242,9 @@ fn step<'a>(target: Target<'a>, part: &str) -> Result<Target<'a>> {(Target::Layers(list), part) => Target::Layer(nth(list, part)?),(Target::Layer(layer), "cels") => match &mut layer.content {LayerContent::Paint { cels } | LayerContent::Vector { cels } => Target::Cels(cels),- LayerContent::Group { .. } | LayerContent::Adjust { .. } => bail!("layer {} has no cels", layer.id),+ LayerContent::Group { .. } | LayerContent::Adjust { .. } | LayerContent::Bones {} => {+ bail!("layer {} has no cels", layer.id)+ }},(Target::Layer(layer), "children") => match &mut layer.content {LayerContent::Group { children } => Target::Layers(children),@@ -309,7 +313,7 @@ fn lists(content: &mut LayerContent) -> (Option<&mut Vec<Cel>>, Option<&mut Vec<match content {LayerContent::Paint { cels } | LayerContent::Vector { cels } => (Some(cels), None),LayerContent::Group { children } => (None, Some(children)),- LayerContent::Adjust { .. } => (None, None),+ LayerContent::Adjust { .. } | LayerContent::Bones {} => (None, None),}}diff --git a/crates/core/src/rig.rs b/crates/core/src/rig.rsindex 0c48f26..0694211 100644--- a/crates/core/src/rig.rs+++ b/crates/core/src/rig.rs@@ -771,6 +771,14 @@ impl Weights {}}+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct Link {+ pub skeleton: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub bone: Option<String>,+}+pub struct Rig<'a> {pub bones: &'a [Bone],pub weights: &'a Weights,@@ -966,21 +974,33 @@ pub fn moved_weights(w: &Weights, back: crate::markedit::Affine) -> Weights {}}-pub fn skeleton_of<'a>(doc: &'a Document, path: &[usize]) -> Option<&'a Layer> {- (1..=path.len())- .rev()- .map(|n| doc.layer_at(&path[..n]))- .find(|l| !l.bones.is_empty())+pub fn skeletons(doc: &Document) -> Vec<&Layer> {+ doc.all_layers()+ .into_iter()+ .filter(|l| l.kind() == Kind::Bones)+ .collect()+}++pub fn painted<'a>(doc: &'a Document, skeleton: &str) -> Vec<&'a Layer> {+ doc.all_layers()+ .into_iter()+ .filter(|l| l.kind() == Kind::Paint && l.rig.as_ref().is_some_and(|r| r.skeleton == skeleton))+ .collect()}-pub fn family(layer: &Layer) -> Vec<&Layer> {- std::iter::once(layer)- .chain(layer.children().iter().flat_map(family))+pub fn painted_paths(doc: &Document, skeleton: &str) -> Vec<Vec<usize>> {+ painted(doc, skeleton)+ .iter()+ .filter_map(|l| match doc.locate(&l.id) {+ Some(crate::doc::Loc::Layer(path)) => Some(path),+ _ => None,+ }).collect()}-pub fn painted(owner: &Layer) -> Vec<&Layer> {- family(owner).into_iter().filter(|l| l.kind() == Kind::Paint).collect()+pub fn linked<'a>(doc: &'a Document, layer: &Layer) -> Option<&'a Layer> {+ let link = layer.rig.as_ref()?;+ doc.layer(&link.skeleton).filter(|s| s.kind() == Kind::Bones)}pub fn weights_for(@@ -1025,7 +1045,7 @@ pub fn weights_for(if let Some(part) = &spec.part {let b = bone()?;let mut cells = Vec::new();- painted(owner).iter().try_for_each(|layer| -> Result<()> {+ painted(doc, &owner.id).iter().try_for_each(|layer| -> Result<()> {let Some(cel) = layer.content_at(spec.frame) else {return Ok(());};diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rsindex 66a165b..6160407 100644--- a/crates/render/src/lib.rs+++ b/crates/render/src/lib.rs@@ -330,6 +330,7 @@ fn may_draw(layer: &Layer, ctx: Ctx, window: IRect) -> bool {|| match &layer.content {LayerContent::Group { children } => children.iter().any(|c| may_draw(c, ctx, window)),LayerContent::Adjust { .. } => true,+ LayerContent::Bones {} => false,LayerContent::Paint { .. } | LayerContent::Vector { .. } => {layer.content_at(ctx.frame).is_some_and(|cel| {let swapped = ctx.swap.filter(|s| s.cel == cel.id).is_some_and(|s| {@@ -770,6 +771,7 @@ fn draw_unmoved(canvas: &Canvas, layer: &Layer, ctx: Ctx) -> Result<()> {})}LayerContent::Group { children } => draw_layers(canvas, children, ctx.nested()),+ LayerContent::Bones {} => Ok(()),LayerContent::Adjust {adjust: Adjustment::Fill(fill),} => {diff --git a/crates/render/src/overlay.rs b/crates/render/src/overlay.rsindex 25e0a1b..93e26b3 100644--- a/crates/render/src/overlay.rs+++ b/crates/render/src/overlay.rs@@ -412,7 +412,7 @@ fn layer_marks(layer: &Layer, frame: u32, depth: usize, out: &mut Vec<Mark>) ->.children().iter().try_for_each(|c| layer_marks(c, frame, depth, out)),- Kind::Paint | Kind::Adjust => Ok(()),+ Kind::Paint | Kind::Adjust | Kind::Bones => Ok(()),}}@@ -548,7 +548,7 @@ fn layer_hits(layer: &Layer, frame: u32, point: (f32, f32), out: &mut Vec<(StrinOk(())})}- Kind::Paint | Kind::Adjust => Ok(()),+ Kind::Paint | Kind::Adjust | Kind::Bones => Ok(()),}}diff --git a/crates/render/src/shift.rs b/crates/render/src/shift.rsindex 964a74d..0cb45b7 100644--- a/crates/render/src/shift.rs+++ b/crates/render/src/shift.rs@@ -33,8 +33,14 @@ pub fn resolve(bundle: &Bundle, ops: &mut [Op]) -> Result<()> {})}+fn family(root: &Layer) -> Vec<&Layer> {+ let mut out = vec![root];+ klad_core::doc::walk_children(root, &mut out);+ out+}+pub fn moved_cels(root: &Layer, only: Option<u32>) -> Vec<(&Layer, &Cel)> {- rig::family(root)+ family(root).into_iter().filter(|l| matches!(l.kind(), Kind::Paint | Kind::Vector)).flat_map(|l| {@@ -80,9 +86,19 @@ pub fn targets(bundle: &Bundle, layer: &str, only: Option<u32>) -> Result<Targetif let Some(r) = vector::nodes_bounds(&nodes)? {boxes.push([r.left, r.top, r.right, r.bottom]);}+ if only.is_none() {+ family(root).iter().flat_map(|l| l.bones.iter()).for_each(|b| {+ boxes.push([+ b.head[0].min(b.tail[0]),+ b.head[1].min(b.tail[1]),+ b.head[0].max(b.tail[0]),+ b.head[1].max(b.tail[1]),+ ])+ });+ }let weights = match only {Some(_) => Vec::new(),- None => rig::family(root)+ None => family(root).into_iter().filter(|l| !l.bones.is_empty()).map(|l| bundle.read_weights(&l.id).map(|w| (l.id.clone(), w)))diff --git a/docs/DESIGN.md b/docs/DESIGN.mdindex 05e12b1..440879f 100644--- a/docs/DESIGN.md+++ b/docs/DESIGN.md@@ -101,11 +101,11 @@ art.klad/Committed: everything except `.cache/`. A fresh clone rebuilds the cache by replaying strokes and fills.-### doc.json (format `klad/3`)+### doc.json (format `klad/4`)```json{- "format": "klad/3",+ "format": "klad/4","rev": 42,"canvas": { "width": 2048, "height": 2048, "background": "#f4efe6" },"timeline": { "fps": 12, "frames": 24, "origin": [1024, 1800],@@ -154,7 +154,7 @@ Committed: everything except `.cache/`. A fresh clone rebuilds the cache by repl- **Masks.** `mask` is a paint layer kept under the layer it masks, with its own id, cels and stroke files (`strokes/<mask id>/<cel>.strokes`). Its alpha hides the layer: strokes and fills on the mask hide, the eraser shows the layer again, and an empty mask (or a frame without a mask cel) hides nothing. `visible: false` turns the mask off. A mask keeps opacity 1 and blend normal and has no mask or clip of its own. Paint, vector and group layers can have one. Internally a mask's layer path ends in `MASK`, so `locate`, `layer_at` and the history treat it as a layer.- **Clipping.** `clip: true` shows a layer only where its base, the nearest layer below it in the same list without `clip`, has alpha. The base and the clipped layers above it draw as one group: each clipped layer blends onto the base with its own blend and opacity (masked by the base's alpha), then the group composites onto what is below with the base's blend and opacity, as in Photoshop with "blend clipped layers as group". A hidden base hides its clipped layers; the lowest layer of a list draws unclipped.- **Lock alpha.** `lockAlpha: true` on a paint layer makes new strokes and fills land only where the layer already has alpha: they composite source-atop and leave alpha unchanged. The flag is recorded on each stroke and fill (stroke format 5), so turning it off later never changes what was drawn. An eraser stroke on a lock-alpha layer changes nothing (the editor refuses it).-- `rev` increments on every write. `klad/1` (2026-11-06) is the first `.klad` format and starts clean: drawings from before it (`.draw` folders, `draw-anything/0` to `/9`, stroke files marked `DAST`) are refused on open with the reason and not converted (`migrate.rs` keeps the place where later migrations go). From here on a format change bumps the number and migrates older `.klad` drawings on open; history snapshots go through the same migration when undone. `klad/2` (2026-11-07) added IK (`ik` on skeletons and in poses); a `klad/1` drawing opens as it is, renamed. `klad/3` (2026-11-08) added `bone` on paint layers, attaching a layer to one bone; older drawings open as they are. History patches never carry the change, because they are diffs of documents already migrated in memory.+- `rev` increments on every write. `klad/1` (2026-11-06) is the first `.klad` format and starts clean: drawings from before it (`.draw` folders, `draw-anything/0` to `/9`, stroke files marked `DAST`) are refused on open with the reason and not converted (`migrate.rs` keeps the place where later migrations go). From here on a format change bumps the number and migrates older `.klad` drawings on open; history snapshots go through the same migration when undone. `klad/2` (2026-11-07) added IK (`ik` on skeletons and in poses); a `klad/1` drawing opens as it is, renamed. `klad/3` (2026-11-08) added `bone` on paint layers, attaching a layer to one bone; older drawings open as they are. `klad/4` (2026-11-08) moved skeletons to bones layers that any paint layer joins through `rig` (follow a bone, or bend); drawings from before open with their rigs dropped (Kevin's call: rigs were new and untested), their drawings kept. History patches never carry the change, because they are diffs of documents already migrated in memory.### Editsdiff --git a/docs/cli.md b/docs/cli.mdindex 2f8c940..3c89b12 100644--- a/docs/cli.md+++ b/docs/cli.md@@ -45,7 +45,7 @@ This reference is licensed under the MIT License (`LICENSE-MIT`), unlike klad it- [`klad foliage`](#klad-foliage): Paint closed shapes as clumps of leaves, lit as forms- [`klad bone`](#klad-bone): Add, remove, rename, move or reparent a bone of a layer's or group's skeleton- [`klad ik`](#klad-ik): Add, change or remove an IK on a bone: a limb (the bone and its parent) or an aim reaches for a target set per pose-- [`klad attach`](#klad-attach): Attach a layer to a bone, so it moves with that bone alone when posed+- [`klad attach`](#klad-attach): Rig a layer: attach it to a bone, let it bend with a skeleton, or unrig it- [`klad solo`](#klad-solo): Show only one layer: hide every other layer (its groups stay shown, its own layers as they are)- [`klad bones`](#klad-bones): List the skeletons, their bones and weights, and the posed drawings- [`klad weights`](#klad-weights): Set how much each bone moves each part of the drawing: automatic, painted dabs, a whole part, smoothed@@ -848,7 +848,7 @@ Arguments:layer, cel, mask, rect, ellipse, path, group, rays, image, scatter, repeat, mirror or text[REST]...- For layers the kind first (paint, vector, group, image with src=photo.jpg, or adjust and its type: hsl, levels, curves, balance, gradient-map, fill), then key=value pairs+ For layers the kind first (paint, vector, group, bones, image with src=photo.jpg, or adjust and its type: hsl, levels, curves, balance, gradient-map, fill), then key=value pairsOptions:--in <INTO>@@ -2259,12 +2259,13 @@ Options:## klad attach```text-Attach a paint layer under a skeleton to one of its bones: posed, the whole layer moves rigidly with that bone, the way a cut-out arm follows its upper arm. Draw a character in pieces (upper arm, forearm, hand on their own layers), attach each to its bone and no weights are needed. A layer not attached bends by the weights instead (by distance to the bones, or as painted in the bone tool's weights mode): use that for a layer drawn in one piece across a joint. --off detaches a layer, so it bends again.+Bones live on bones layers (klad add <bundle> layer bones, or Layer > New bones layer); a bones layer draws nothing. Any paint layer in the drawing can be rigged to one: attached to a bone (--bone), it moves rigidly with that bone when posed, the way a cut-out arm follows its upper arm, so a character drawn in pieces (upper arm, forearm, hand on their own layers) needs no weights; set to bend (--bend), each of its points moves by the skeleton's weights, for a layer drawn in one piece across a joint. --off unrigs it: posing leaves it as it is. --skeleton names the bones layer when the drawing has more than one (with --bone, the one that has that bone is found).klad attach art.klad forearm --bone fore+ klad attach art.klad sleeve --bend --skeleton bonesklad attach art.klad forearm --off-Also an attach op: {"op":"attach","layer":"forearm","bone":"fore"}; without "bone" the layer bends by the weights. Renaming the bone keeps the layer on it; removing it leaves the layer bending.+Also an attach op: {"op":"attach","layer":"forearm","bone":"fore"}; {"op":"attach","layer":"sleeve","skeleton":"bones"} bends; without either it unrigs. Renaming a bone keeps its layers on it; removing it unrigs them.Usage: klad attach [OPTIONS] <BUNDLE> <LAYER>@@ -2279,8 +2280,14 @@ Options:--bone <BONE>+ --bend+ bend with the skeleton by its weights, instead of following one bone++ --skeleton <SKELETON>+ the bones layer, when there is more than one+--off- detach: the layer bends by the weights again+ unrig: posing leaves the layer as it is--renderRender a preview after the edit and print its pathdiff --git a/docs/format.md b/docs/format.mdindex 4d3f73a..c03c57d 100644--- a/docs/format.md+++ b/docs/format.md@@ -1,4 +1,4 @@-_Last updated: 2026-11-08 (format `klad/3`, stroke files `KLST` version 1, brushes `klad-brush/1`)_+_Last updated: 2026-11-08 (format `klad/4`, stroke files `KLST` version 1, brushes `klad-brush/1`)_# The klad drawing format@@ -16,7 +16,7 @@ klad is the reference: when this text and klad's renders disagree, klad is right| `brushes/images/<name>.png` | pictures that brushes use as tips or grain | when a brush names one klad does not have built in || `images/<file>` | pictures placed by `image` nodes (PNG) | for every `src` || `fonts/<file>` | fonts used by `text` nodes, with their licence files | for every `font` |-| `weights/<owner>.weights` | how much each bone of a skeleton moves each part of the drawing | for every layer or group with `bones` |+| `weights/<owner>.weights` | how much each bone of a skeleton moves each part of the drawing | for every bones layer with `bones` || `.gitignore` | `.cache/`, so a drawing can live in a git repository | no || `.cache/` | rebuildable pixels, the undo history, the editor's selection and pinned notes | no: never read it as data |@@ -30,13 +30,13 @@ Writers replace files atomically (write a temporary file, then rename), so a rea- **Colours** are `"#rrggbb"` or `"#rrggbbaa"`: sRGB, straight (not premultiplied) alpha.- **Ids** are unique across the whole document and use letters, digits, `-` and `_`. klad makes new ones from a prefix (`l` layer, `c` cel, `n` node) and `nextId`. Ids are case sensitive.- **JSON** is UTF-8, written pretty with a stable key order. Keys at their default value are left out; readers must take the defaults listed below for missing keys. Most objects reject keys they do not know, so writers must not add their own.-- **Versions.** `format` names the version of `doc.json` and everything it implies; this is `klad/3`. Each version opens the older `klad/` drawings and migrates them in memory (written back on the next change). A reader that meets a newer version than it knows should refuse to write the bundle. Drawings from before `klad/1` (`.draw` folders, formats `draw-anything/0` to `/9`) do not open.+- **Versions.** `format` names the version of `doc.json` and everything it implies; this is `klad/4`. Each version opens the older `klad/` drawings and migrates them in memory (written back on the next change). A reader that meets a newer version than it knows should refuse to write the bundle. Drawings from before `klad/1` (`.draw` folders, formats `draw-anything/0` to `/9`) do not open.## doc.json```json{- "format": "klad/3",+ "format": "klad/4","rev": 42,"canvas": { "width": 2048, "height": 2048, "background": "#f4efe6" },"timeline": { "fps": 12, "frames": 24, "origin": [1024, 1800],@@ -60,7 +60,7 @@ Writers replace files atomically (write a temporary file, then rename), so a rea| Key | Type | Default | Meaning ||---|---|---|---|-| `format` | string | | `"klad/3"` |+| `format` | string | | `"klad/4"` || `rev` | integer | | grows by one on every write || `canvas` | object | | `width`, `height` (px), `background` (a colour; none is transparent) || `timeline` | object | 12 fps, 1 frame | see below |@@ -88,7 +88,7 @@ A clip is `name` (unique), `from` and `to` (both included), `loop` (false) and `| Key | Type | Default | Meaning ||---|---|---|---|| `id`, `name` | string | | |-| `kind` | string | | `paint`, `vector`, `group` or `adjust` |+| `kind` | string | | `paint`, `vector`, `group`, `adjust` or `bones` || `cels` | array | `[]` | paint and vector layers: the drawings on the timeline || `children` | array | `[]` | groups: the layers inside, bottom first || `adjust` | object | | adjustment layers: one adjustment (below) |@@ -102,9 +102,9 @@ A clip is `name` (unique), `from` and `to` (both included), `loop` (false) and `| `effects` | array | `[]` | applied in order when the layer composes (below) || `depth` | number | none | on a top-level layer or group: how far the plane is (0 near); drives the atmosphere and parallax || `reference` | bool | false | shown in the editor, left out of renders and exports (pictures to trace) |-| `bones` | array | `[]` | a skeleton (paint layers and groups, below) |-| `ik` | array | `[]` | the skeleton's IK constraints (below) |-| `bone` | string | none | on a paint layer under a skeleton: the bone it is attached to (below) |+| `bones` | array | `[]` | bones layers: the skeleton (below) |+| `ik` | array | `[]` | bones layers: the skeleton's IK constraints (below) |+| `rig` | object | none | paint layers: the bones layer they move with, and the bone they follow (below) || `keys` | object | `{}` | animated properties (below) |Layers compose bottom to top. Groups compose their children into one image, then blend that with the group's opacity and blend. An **adjustment layer** changes what is under it inside its group (or, with `clip`, only its base).@@ -211,7 +211,7 @@ A key is `frame`, `value` and `ease` (`linear` when absent; `in`, `out`, `in-out### Skeletons-A paint layer or a group may have `bones`: each a `name` (unique in the skeleton), a `parent` (a bone listed before it; none for a root), a `head` and a `tail` (`[x, y]` in canvas px, at rest). A group's skeleton moves every paint layer in it together. A paint layer with `bone` (a bone of the nearest skeleton holding it: its own, or its nearest group's with bones) is attached to that bone: posed, it moves rigidly with that bone's frame alone, the way a cut-out limb follows its bone, and the weights do not touch it. A layer without `bone` bends by the weights. Each skeleton has a weights file (below). Posed drawings store their marks already bent (see `pose` above), so bones and weights are only needed to make new poses.+A skeleton lives on a **bones layer** (`kind` `bones`), which draws nothing and has no cels: its `bones` are each a `name` (unique in the skeleton), a `parent` (a bone listed before it; none for a root), a `head` and a `tail` (`[x, y]` in canvas px, at rest). A paint layer anywhere in the drawing moves with a bones layer through its `rig`: `{"skeleton": "<bones layer id>", "bone": "<name>"}` attaches it to that bone, so posed it moves rigidly with that bone's frame alone, the way a cut-out limb follows its bone, and the weights do not touch it; without `bone` it bends by the skeleton's weights. A paint layer without `rig` is not moved by any pose. Each skeleton has a weights file (below). Posed drawings store their marks already bent (see `pose` above), so bones and weights are only needed to make new poses.A pose turns each bone about its head by its angle, its children with it, and moves the root bones by `root`. A bone's world turn is its angle plus its parent's world turn; a child's head moves with its parent's frame.@@ -335,3 +335,4 @@ Drawing a stroke: walk the samples, interpolate between them, stamp the tip ever| `klad/1` | the first `.klad` format (2026-11). Drawings from before it, `.draw` folders in formats `draw-anything/0` to `/9` with stroke files marked `DAST`, do not open. || `klad/2` | skeletons get `ik` constraints and poses their `ik` targets (2026-11-07). `klad/1` drawings open unchanged. || `klad/3` | paint layers under a skeleton get `bone`, attaching them to one bone (2026-11-08). `klad/1` and `klad/2` drawings open unchanged. |+| `klad/4` | skeletons move to bones layers, and paint layers join one with `rig` (2026-11-08). Older drawings open without their bones, IK, weights links and the `pose` of their cels; the drawings themselves, posed ones too, stay. |diff --git a/docs/skill/SKILL.md b/docs/skill/SKILL.mdindex c0c4770..d1ebbf7 100644--- a/docs/skill/SKILL.md+++ b/docs/skill/SKILL.md@@ -219,14 +219,16 @@ klad prepare art.klad## Bones, poses and keys-Draw a character once and pose it, instead of redrawing every frame. Put its paint layers (lines, colour, shading) in a group and give the group bones: the skeleton poses every layer in it together. Name parts as you draw (`"part"` on strokes and fills): they are what weights and the rig export use.+Draw a character once and pose it, instead of redrawing every frame. Its skeleton goes on a bones layer of its own (it draws nothing), and its paint layers join it with `klad attach`: each follows one bone rigidly, or bends with the skeleton by the weights. Name parts as you draw (`"part"` on strokes and fills): they are what weights and the rig export use.```bash+klad add art.klad layer bones name=figure # the bones layer; the commands below name itklad bone art.klad figure --add body --head 400,590 --tail 400,360klad bone art.klad figure --add upper --parent body --head 452,392 --tail 560,360 # a child starts at its parent's end, or anywhereklad bone art.klad figure --chain thigh,shin,foot --through '390,590 395,700 385,810 425,815' --parent body # each the child of the one beforeklad ik art.klad figure --add shin # a limb: shin and thigh reach for a target, bending as drawnklad attach art.klad forearm --bone fore # a layer drawn as its own piece moves with one bone, no weights+klad attach art.klad lines --bend --skeleton figure # a layer drawn in one piece bends by the weightsklad weights art.klad figure --auto # blend from the bones, for layers that bendklad weights art.klad figure --bone head --part head # a part held rigidly by one boneklad weights art.klad figure --bone upper --set '470,380,20,1 500,370,16,0.8' # soft dabs: x,y,radius,weight@@ -241,7 +243,7 @@ klad export art.klad --godot-rig game/art --godot-scene game/art- Angles are degrees from the rest pose, positive turning clockwise on screen; a child follows its parent. Pose from the rest drawing (`--from` its frame); posing a frame again re-poses it.- Fix a skeleton in place: `--move upper --tail 570,350` moves an end (children that start at that tail come along), `--move upper --by 10,0` moves a bone with all its children, `--reparent hand --parent fore` changes a parent. The user does the same in the bone tool: the skeleton list picks a bone, its ends and middle drag, a drag on empty canvas draws a chain (each click adds the next bone; Esc ends it), alt drag from an end starts a chain from there.- IK poses a limb by where its end goes: `klad ik --add shin` makes the shin and its parent a limb (`--chain 1` an aim: the bone alone points at the target), `--bend clockwise|counterclockwise|flip` picks the side the joint bends to (by default as drawn), `--softness 8` keeps a knee from snapping straight. Each pose then sets targets (`--target shin=x,y`, canvas px): the limb turns so the shin's tail lands there, and the target ignores `--root`, so a planted foot stays planted while the body bobs; `--mix shin=0.5` blends between the bones' own turns and the target. In-betweens move targets in straight lines, so plant feet with the same target in both keys and swing free limbs with turns instead. `klad bones` lists the constraints, each pose's targets and its solved turns.-- Two ways to move a layer: attached (`klad attach <layer> --bone <bone>`) it moves rigidly with that bone, as a cut-out piece; not attached it bends by the weights. Draw limbs on their own layers and attach them when they should stay stiff; keep a layer drawn in one piece across a joint (a sleeve, a tail) unattached and paint its weights. `klad bones` says which layers follow which bone.+- A paint layer moves with the bones only once it is rigged: attached (`klad attach <layer> --bone <bone>`) it moves rigidly with that bone, as a cut-out piece; set to bend (`--bend --skeleton <bones layer>`) each point moves by the weights; not rigged, posing leaves it alone. Draw limbs on their own layers and attach them when they should stay stiff; let a layer drawn in one piece across a joint (a sleeve, a tail) bend and paint its weights. Rigged layers can sit anywhere in the layer tree. `klad bones` says which layers follow which bone.- Automatic weights bend joints over a short stretch; hold rigid things (head, hands, props) with `--part`, or a stiff limb with dabs at 1. Look at `--overlay weights:<bone>` before posing.- Keys move whole layers, groups and shapes (`x`, `y`, `rotate`, `sx`, `sy`, `scale`, `opacity`) between frames with an ease (`linear`, `in`, `out`, `in-out`, `step`, or a curve `x1,y1,x2,y2`); a segment follows its first key's ease. A lantern that floats, a glow that pulses, a far plane that drifts: no drawing per frame.- Godot: `--godot` exports frames (always works), `--godot-rig` a Skeleton2D with Polygon2D parts and an AnimationPlayer per clip (only frames that are poses of the rest drawing; the others are listed), `--godot-scene` one Parallax2D per top-level layer scrolling by its depth. `samples/rig` builds all of it.diff --git a/samples/rig/generate.py b/samples/rig/generate.pyindex 0e80249..c03e8bb 100644--- a/samples/rig/generate.py+++ b/samples/rig/generate.py@@ -35,6 +35,7 @@ def drawing():layer("figure", "group"),layer("colour", "paint", "figure"),layer("lines", "paint", "figure"),+ layer("bones", "bones", "figure"),layer("lantern", "vector"),fill("sky", [[0, 560], [800, 540], [800, 800], [0, 800]], "#6f7f6a", "hill"),fill("sky", ellipse(620, 160, 60, 60), "#f4e4b0", "moon"),@@ -57,7 +58,7 @@ def drawing():def rig():- bone = lambda name, parent, head, tail: {"op": "bone", "layer": "figure", "add": name, "head": head, "tail": tail,+ bone = lambda name, parent, head, tail: {"op": "bone", "layer": "bones", "add": name, "head": head, "tail": tail,**({"parent": parent} if parent else {})}return [bone("body", None, [400, 590], [400, 360]),@@ -65,22 +66,24 @@ def rig():bone("upper", "body", [452, 392], [560, 360]),bone("fore", "upper", [560, 360], [650, 330]),bone("hand", "fore", [650, 330], [694, 316]),+ {"op": "attach", "layer": "colour", "skeleton": "bones"},+ {"op": "attach", "layer": "lines", "skeleton": "bones"},]def weights():return [- {"op": "weights", "layer": "figure", "auto": True},- {"op": "weights", "layer": "figure", "bone": "head", "part": "head"},- {"op": "weights", "layer": "figure", "bone": "body", "part": "body"},- {"op": "weights", "layer": "figure", "bone": "hand", "part": "hand"},+ {"op": "weights", "layer": "bones", "auto": True},+ {"op": "weights", "layer": "bones", "bone": "head", "part": "head"},+ {"op": "weights", "layer": "bones", "bone": "body", "part": "body"},+ {"op": "weights", "layer": "bones", "bone": "hand", "part": "hand"},]def poses():wave = [(4, {"upper": -35, "fore": -55, "hand": -10}), (8, {"upper": -50, "fore": -20, "hand": 25}),(12, {"upper": -35, "fore": -55, "hand": -10}), (16, {"upper": -50, "fore": -20, "hand": 25})]- return [{"op": "pose", "layer": "figure", "from": 0, "to": f, "bones": b, "hold": 8 if f == 16 else 4} for f, b in wave]+ return [{"op": "pose", "layer": "bones", "from": 0, "to": f, "bones": b, "hold": 8 if f == 16 else 4} for f, b in wave]def keys():