Skip to content

armgit / klad

Public Imported from GitHub
0

A drawing app built for agent/human collaboration

Rust

Attach a layer to a bone; pose mode shows the pose live

Indicode BVae58299cdee0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0478e55..5c76ce5 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/2` (drawings from the first builds, `klad/1`, 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/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.
- 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.
@@ -19,6 +19,7 @@ The first builds, and klad's licences.
- 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`).
- 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 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/editor.rs b/crates/app/src/editor.rs
index dbcf604..a556fae 100644
--- a/crates/app/src/editor.rs
+++ b/crates/app/src/editor.rs
@@ -453,6 +453,7 @@ struct PreviewState {
shown: BTreeSet<usize>,
done: Option<(Vec<Op>, bool, BTreeSet<usize>)>,
finish: Option<Finish>,
+ posed: Option<(u64, u32, String, klad_core::rig::Pose)>,
}
impl PreviewState {
@@ -1469,6 +1470,7 @@ impl Editor {
}
let mut uploads = Vec::new();
let rev = self.scene.bundle.doc.rev;
+ let posing = self.live_pose();
if let Some(mut state) = self.preview.take() {
let mut keep = true;
match state.job.as_ref().and_then(|rx| rx.try_recv().ok()) {
@@ -1510,8 +1512,11 @@ impl Editor {
None => {}
}
if keep {
- let stale =
- state.finish.is_none() && (self.drag.is_none() || state.snap.rev != rev || !self.canvas_current());
+ let gone = match &state.posed {
+ Some(_) => posing.is_none(),
+ None => self.drag.is_none(),
+ };
+ let stale = state.finish.is_none() && (gone || state.snap.rev != rev || !self.canvas_current());
let late = state.finish.as_ref().is_some_and(|f| f.since.elapsed() > FINISH_WAIT);
match stale || late {
true => {
@@ -1524,11 +1529,14 @@ impl Editor {
}
if self.preview.is_none()
&& self.live.is_none()
- && self.drag.as_ref().is_some_and(|d| d.moved() && !d.copy)
+ && (posing.is_some() || self.drag.as_ref().is_some_and(|d| d.moved() && !d.copy))
&& self.canvas_current()
&& self.dirty.len() <= timeline::FILL
{
- let cels = self.preview_cels();
+ let cels = match &posing {
+ Some(p) => p.cels.to_vec(),
+ None => self.preview_cels(),
+ };
self.preview = self
.scene
.preview_snapshot(&cels, &self.brushes)
@@ -1542,6 +1550,7 @@ impl Editor {
shown: BTreeSet::new(),
done: None,
finish: None,
+ posed: None,
});
}
let position = self.drag.as_ref().map(|d| d.now);
@@ -1550,11 +1559,16 @@ impl Editor {
.as_ref()
.filter(|p| p.job.is_none())
.map(|p| p.finish.as_ref().map(|f| f.ops.clone()).ok_or(p.asked_at != position));
- let wanted = match ready {
- Some(Ok(finish)) => Some(finish),
- Some(Err(true)) => self.drag_ops(),
+ let wanted = match (ready, &posing) {
+ (Some(Ok(finish)), _) => Some(finish),
+ (Some(Err(_)), Some(p)) => match self.preview.as_ref().is_some_and(|s| s.posed.as_ref() == Some(&p.key)) {
+ true => None,
+ false => Some(p.ops.to_vec()),
+ },
+ (Some(Err(true)), None) => self.drag_ops(),
_ => None,
};
+
if let (Some(state), Some(ops)) = (self.preview.as_mut(), wanted) {
state.asked_at = position;
if state.asked.as_ref() != Some(&ops) {
@@ -1566,6 +1580,7 @@ impl Editor {
cancel: state.cancel.clone(),
};
state.asked = Some(ops);
+ state.posed = posing.as_ref().map(|p| p.key.clone());
let (tx, rx) = channel();
let ctx = self.ctx.clone();
crate::background().spawn(move || {
diff --git a/crates/app/src/editor/bones.rs b/crates/app/src/editor/bones.rs
index 38c0af8..9578d9e 100644
--- a/crates/app/src/editor/bones.rs
+++ b/crates/app/src/editor/bones.rs
@@ -5,7 +5,7 @@ use crate::theme::{self, Hint};
use anyhow::{Context, Result, bail};
use egui::{Color32, Key, Modifiers, Pos2, RichText, Vec2};
use klad_core::doc::Kind;
-use klad_core::ops::{BendSpec, BoneSpec, IkSpec, Op, WeightsSpec};
+use klad_core::ops::{BendSpec, BoneSpec, IkSpec, Op, PoseSpec, PosedCel, WeightsSpec};
use klad_core::rig::{
Bend, Bone, CELL, Ik, Pose, Reach, Weights, applied, bent_against, limb_of, moved, near_degrees, painted, subtree,
target_for_end, tips, weights_for,
@@ -60,6 +60,15 @@ pub(super) enum Posing {
Root(Vec2),
}
+#[derive(Clone)]
+pub(super) struct Live {
+ pub key: (u64, u32, String, Pose),
+ pub ops: std::sync::Arc<Vec<Op>>,
+ pub cels: std::sync::Arc<Vec<String>>,
+}
+
+type Rests = (u64, String, Weights, BTreeMap<String, Vec<klad_core::stroke::Mark>>);
+
pub(super) struct BoneTool {
pub mode: Mode,
pub selected: Option<String>,
@@ -72,6 +81,8 @@ pub(super) struct BoneTool {
pub root: [f32; 2],
pub reach: BTreeMap<String, Reach>,
pub loaded: Option<(u32, String, Option<Pose>)>,
+ pub live: Option<Live>,
+ rests: Option<Rests>,
pub sent: bool,
pub posing: Option<Posing>,
pub name: String,
@@ -92,6 +103,8 @@ impl Default for BoneTool {
root: [0.0, 0.0],
reach: BTreeMap::new(),
loaded: None,
+ live: None,
+ rests: None,
sent: false,
posing: None,
name: String::new(),
@@ -187,6 +200,127 @@ impl Editor {
}
}
+ pub(super) fn live_pose(&mut self) -> Option<Live> {
+ if self.tool != Tool::Bone || self.bones.mode != Mode::Pose {
+ self.bones.live = None;
+ return None;
+ }
+ let owner = self.rig_owner()?;
+ let shown = self.shown_pose();
+ let stored = self.stored_pose(&owner).unwrap_or_default();
+ let same = |a: &BTreeMap<String, f32>, b: &BTreeMap<String, f32>| {
+ a.keys()
+ .chain(b.keys())
+ .all(|k| (a.get(k).copied().unwrap_or(0.0) - b.get(k).copied().unwrap_or(0.0)).abs() < 1e-3)
+ };
+ if same(&shown.angles, &stored.angles) && shown.root == stored.root && shown.ik == stored.ik {
+ self.bones.live = None;
+ return None;
+ }
+ let doc = &self.scene.bundle.doc;
+ let key = (doc.rev, self.scene.frame, owner.clone(), shown.clone());
+ if let Some(live) = self.bones.live.as_ref().filter(|l| l.key == key) {
+ return Some(live.clone());
+ }
+ let skeleton = doc.layer(&owner)?.clone();
+ let canvas = (doc.canvas.width, doc.canvas.height);
+ if self
+ .bones
+ .rests
+ .as_ref()
+ .is_none_or(|(r, o, _, _)| (*r, o) != (doc.rev, &owner))
+ {
+ let weights = self
+ .scene
+ .bundle
+ .read_weights(&owner)
+ .ok()
+ .filter(|w| !w.maps.is_empty())
+ .unwrap_or_else(|| Weights::auto(&skeleton.bones, canvas));
+ self.bones.rests = Some((doc.rev, owner.clone(), weights, BTreeMap::new()));
+ }
+ let frame = self.scene.frame;
+ let wanted: Vec<(String, String)> = painted(&skeleton)
+ .iter()
+ .filter_map(|layer| {
+ let cel = layer.content_at(frame)?;
+ Some((
+ layer.id.clone(),
+ cel.pose.as_ref().map_or_else(|| cel.id.clone(), |p| p.rest.clone()),
+ ))
+ })
+ .collect();
+ let (scene, rests) = (&self.scene, &mut self.bones.rests);
+ let (_, _, weights, marks) = rests.as_mut()?;
+ wanted.iter().for_each(|(layer, rest)| {
+ if !marks.contains_key(rest) {
+ let read = match scene.marks_of(rest) {
+ [] => scene.bundle.read_marks(layer, rest).unwrap_or_default(),
+ loaded => loaded.to_vec(),
+ };
+ marks.insert(rest.clone(), read);
+ }
+ });
+ let (weights, rests) = (&*weights, &*marks);
+ let made: Vec<PosedCel> = painted(&skeleton)
+ .into_iter()
+ .filter_map(|layer| {
+ let cel = layer.content_at(frame)?;
+ let rest = cel.pose.as_ref().map_or_else(|| cel.id.clone(), |p| p.rest.clone());
+ let marks = rests.get(&rest)?;
+ let pose = Pose {
+ rest: rest.clone(),
+ ..shown.clone()
+ };
+ let marks = klad_core::rig::Rig::new(&skeleton.bones, &skeleton.ik, weights, &pose)
+ .following(layer.bone.as_deref())
+ .pose(marks, canvas);
+ Some(PosedCel {
+ layer: layer.id.clone(),
+ cel: cel.id.clone(),
+ frame: cel.frame,
+ hold: cel.hold,
+ pose,
+ marks,
+ fresh: false,
+ })
+ })
+ .collect();
+ if made.is_empty() {
+ return None;
+ }
+ let cels = made.iter().map(|c| c.cel.clone()).collect();
+ let ops = vec![Op::Pose(PoseSpec {
+ layer: owner,
+ from: frame,
+ to: frame,
+ bones: shown.angles.clone(),
+ root: shown.root,
+ ik: shown.ik.clone(),
+ hold: None,
+ resolved: Some(made),
+ })];
+ let live = Live {
+ key,
+ ops: std::sync::Arc::new(ops),
+ cels: std::sync::Arc::new(cels),
+ };
+ self.bones.live = Some(live.clone());
+ Some(live)
+ }
+
+ 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)
+ }
+
fn stored_pose(&self, owner: &str) -> Option<Pose> {
let layer = self.scene.bundle.doc.layer(owner)?;
painted(layer)
@@ -1029,7 +1163,13 @@ impl Editor {
run = Some(later);
} else if let Some(later) = self.ik_menu(ui, &picked) {
run = Some(later);
- } else if ui.button("remove").hint("the picked bone and its children").clicked() {
+ } else if let Some(later) = self.attach_menu(ui, &picked) {
+ run = Some(later);
+ } else if ui
+ .button(theme::icon::TRASH)
+ .hint("remove the picked bone and its children")
+ .clicked()
+ {
run = Some(Box::new(move |e| {
e.end_chain();
e.bone_edit(|s| s.rm = Some(picked))?;
@@ -1046,13 +1186,17 @@ impl Editor {
(None, Some(_)) => None,
(None, None) => Some((
"drag to draw a chain of bones",
- "a drag draws a bone and the chain carries on from its end: each click adds the next; click a bone to pick it",
+ "a drag draws a bone and the chain carries on from its end: each click adds the next; click a bone to pick it, then its layers menu attaches the layers that move with it",
)),
};
if let Some((hint, more)) = said {
ui.label(RichText::new(hint).color(theme::WEAK)).hint(more);
}
}
+ Mode::Weights if !self.bends() => {
+ ui.label(RichText::new("every layer follows a bone: nothing bends by weights").color(theme::WEAK))
+ .hint("weights are for a layer drawn in one piece across a joint; detach one (draw mode, the picked bone's layers menu, or the bone in its layers row) to paint its weights");
+ }
Mode::Weights => {
ui.add(
egui::Slider::new(&mut self.bones.radius, 4.0..=200.0)
@@ -1169,6 +1313,36 @@ impl Editor {
Ok(())
}
+ 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)
+ .iter()
+ .map(|l| (l.id.clone(), l.name.clone(), l.bone.clone()))
+ .collect();
+ let on = layers.iter().filter(|l| l.2.as_deref() == Some(picked)).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(),
+ };
+ if ui.checkbox(&mut checked, label).changed() {
+ chosen = Some((id.clone(), checked.then(|| picked.to_string())));
+ }
+ });
+ })
+ .response
+ .hint(format!(
+ "the layers that move with {picked} alone when posed; a layer attached to no bone bends by the weights"
+ ));
+ chosen.map(|(layer, bone)| -> Later {
+ Box::new(move |e| e.apply(vec![Op::Attach(klad_core::ops::AttachSpec { layer, bone })]))
+ })
+ }
+
fn skeleton_list(&mut self, ui: &mut egui::Ui) -> Option<Later> {
let bones = self.rig_bones();
let doc = &self.scene.bundle.doc;
@@ -1266,6 +1440,7 @@ impl Editor {
let mut chosen: Option<Option<String>> = None;
let label = ui.label("parent");
egui::ComboBox::from_id_salt("bones.parent")
+ .width(90.0)
.selected_text(current.as_deref().unwrap_or("none"))
.show_ui(ui, |ui| {
std::iter::once(None)
diff --git a/crates/app/src/editor/layers.rs b/crates/app/src/editor/layers.rs
index 4b8b583..8483082 100644
--- a/crates/app/src/editor/layers.rs
+++ b/crates/app/src/editor/layers.rs
@@ -35,6 +35,8 @@ pub(super) struct LayerRow {
pub mask: bool,
pub folded: bool,
pub cel: Option<String>,
+ pub skeleton: Vec<String>,
+ pub bone: Option<String>,
}
#[derive(Clone, Debug, PartialEq)]
@@ -153,6 +155,13 @@ 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(),
+ _ => Vec::new(),
+ },
+ bone: layer.bone.clone(),
}
}
@@ -407,6 +416,36 @@ 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 {
+ 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()));
+ }
+ });
+ 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()
.filter(|(on, _, _)| *on)
@@ -690,6 +729,8 @@ mod tests {
mask,
folded: false,
cel: None,
+ skeleton: Vec::new(),
+ bone: None,
}
}
diff --git a/crates/app/src/editor/ui_tests.rs b/crates/app/src/editor/ui_tests.rs
index 1e9ca64..0ec037d 100644
--- a/crates/app/src/editor/ui_tests.rs
+++ b/crates/app/src/editor/ui_tests.rs
@@ -3663,6 +3663,82 @@ fn the_bone_options_stay_one_row_whatever_is_picked() {
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");
+ Bundle::open(&path)
+ .unwrap()
+ .apply(
+ &parse_lines(
+ r#"{"op":"bone","layer":"l6","chain":["thigh","shin"],"through":[[100,60],[100,160],[110,260]]}"#,
+ )
+ .unwrap(),
+ )
+ .unwrap();
+ let mut h = harness(editor(&path), vec2(1440.0, 1000.0));
+ activate(&mut h, "lines");
+ h.key_press(Key::J);
+ h.run_steps(2);
+ h.state_mut().pick_bone(Some("shin".into()));
+ 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.run_steps(3);
+ assert_eq!(
+ h.state().scene.bundle.doc.layer("l6").unwrap().bone.as_deref(),
+ Some("shin"),
+ "the picked bone's layers menu attaches a layer"
+ );
+ assert!(h.query_by_label("layers: 1").is_some(), "and counts it");
+ h.get_by_label("weights").click();
+ h.run_steps(2);
+ assert!(
+ h.query_by_label_contains("nothing bends by weights").is_some(),
+ "with every layer attached, weights mode says there is nothing to bend"
+ );
+ h.get_by_label("pose").click();
+ h.run_steps(2);
+ let rev = h.state().scene.bundle.doc.rev;
+ h.state_mut().bones.pose.insert("shin".into(), 90.0);
+ let start = std::time::Instant::now();
+ while !h
+ .state()
+ .preview
+ .as_ref()
+ .is_some_and(|p| p.posed.is_some() && p.job.is_none() && p.done.is_some())
+ && start.elapsed() < std::time::Duration::from_secs(20)
+ {
+ h.run_steps(1);
+ std::thread::sleep(std::time::Duration::from_millis(2));
+ }
+ let preview = h.state().preview.as_ref().expect("posing shows the drawing live");
+ assert!(preview.done.is_some(), "the posed drawing was drawn");
+ let live = h.state().bones.live.clone().expect("the live pose");
+ let klad_core::ops::Op::Pose(spec) = &live.ops[0] else {
+ panic!("a pose op");
+ };
+ let made = &spec.resolved.as_ref().unwrap()[0];
+ let line = made.marks.iter().find_map(|m| m.as_stroke()).unwrap();
+ let first = line.samples[0].pos();
+ assert!(
+ (first.0 - 220.0).abs() < 0.5 && (first.1 - 100.0).abs() < 0.5,
+ "the whole layer turns a quarter round the shin's head: {first:?}"
+ );
+ assert_eq!(
+ h.state().scene.bundle.doc.rev,
+ rev,
+ "showing a pose changes nothing in the drawing"
+ );
+ h.get_by_label("draw").click();
+ h.run_steps(3);
+ assert!(
+ h.state().preview.is_none(),
+ "leaving pose mode shows the drawing as it is"
+ );
+ let _ = std::fs::remove_dir_all(&path);
+}
+
#[test]
fn a_leg_gets_its_ik_in_the_options_and_its_foot_is_dragged_and_planted_in_pose_mode() {
let path = sample("leg-ik");
diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs
index d292a60..234c365 100644
--- a/crates/cli/src/main.rs
+++ b/crates/cli/src/main.rs
@@ -1235,6 +1235,20 @@ enum Command {
#[command(flatten)]
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."
+ )]
+ Attach {
+ bundle: PathBuf,
+ layer: String,
+ #[arg(long, conflicts_with = "off", required_unless_present = "off")]
+ bone: Option<String>,
+ #[arg(long, help = "detach: the layer bends by the weights again")]
+ off: bool,
+ #[command(flatten)]
+ flags: EditFlags,
+ },
#[command(
about = "Show only one layer: hide every other layer (its groups stay shown, its own layers as they are)",
long_about = "Show only one layer: every other layer is hidden, the groups it is in stay shown and the layers inside it keep their own visibility, in one step that klad undo takes back. The editor's alt click on a layer's eye does the same.\n\n klad solo art.klad lines"
@@ -1277,7 +1291,7 @@ enum Command {
},
#[command(
about = "Pose a drawing with its bones: a new drawing at --to, bent from the rest drawing at --from",
- long_about = "A pose is a turn per bone (degrees from its rest angle, children follow their parent), a move of the whole (--root), and a target per IK (--target, canvas px; see klad ik): the IK's limb turns so its end reaches the target, and the target stays put when the root moves. --mix blends an IK's limb from its turns (0) to reaching the target (1, the default). Every paint layer under the skeleton gets a new drawing at --to: each stroke point and fill moves by its bones' weighted blend, the same way Godot's Skeleton2D bends a Polygon2D. The pose is kept on the drawing; posing that frame again re-poses it from the same rest drawing, and posing from a posed drawing starts from its rest drawing. klad inbetween between two poses of one rest drawing turns the bones instead of matching strokes, and moves the targets in straight lines, so a foot planted in both keys stays planted.\n\n klad pose art.klad body --from 0 --to 4 --bone thigh=25 --bone shin=-40 --root 0,6\n klad pose art.klad body --from 0 --to 8 --target shin=410,740 --root 20,6\n klad pose art.klad body --from 0 --to 12 --target shin=430,700 --mix shin=0.5 --bone shin=-20\n\nAlso a pose op: {\"op\":\"pose\",\"layer\":\"body\",\"from\":0,\"to\":4,\"bones\":{\"thigh\":25,\"shin\":-40},\"root\":[0,6],\"ik\":{\"shin\":{\"target\":[410,740],\"mix\":1}}}."
+ long_about = "A pose is a turn per bone (degrees from its rest angle, children follow their parent), a move of the whole (--root), and a target per IK (--target, canvas px; see klad ik): the IK's limb turns so its end reaches the target, and the target stays put when the root moves. --mix blends an IK's limb from its turns (0) to reaching the target (1, the default). Every paint layer under the skeleton gets a new drawing at --to: a layer attached to a bone (klad attach) moves with that bone alone; in the others each stroke point and fill moves by its bones' weighted blend, the same way Godot's Skeleton2D bends a Polygon2D. The pose is kept on the drawing; posing that frame again re-poses it from the same rest drawing, and posing from a posed drawing starts from its rest drawing. klad inbetween between two poses of one rest drawing turns the bones instead of matching strokes, and moves the targets in straight lines, so a foot planted in both keys stays planted.\n\n klad pose art.klad body --from 0 --to 4 --bone thigh=25 --bone shin=-40 --root 0,6\n klad pose art.klad body --from 0 --to 8 --target shin=410,740 --root 20,6\n klad pose art.klad body --from 0 --to 12 --target shin=430,700 --mix shin=0.5 --bone shin=-20\n\nAlso a pose op: {\"op\":\"pose\",\"layer\":\"body\",\"from\":0,\"to\":4,\"bones\":{\"thigh\":25,\"shin\":-40},\"root\":[0,6],\"ik\":{\"shin\":{\"target\":[410,740],\"mix\":1}}}."
)]
Pose {
bundle: PathBuf,
@@ -2974,6 +2988,19 @@ fn run() -> Result<()> {
};
agent::edit(&bundle, &[Op::Ik(spec)], &output(&flags, 0))?;
}
+ Command::Attach {
+ bundle,
+ layer,
+ bone,
+ off: _,
+ flags,
+ } => {
+ let spec = klad_core::ops::AttachSpec {
+ layer: layer_id(&bundle, &layer)?,
+ bone,
+ };
+ agent::edit(&bundle, &[Op::Attach(spec)], &output(&flags, 0))?;
+ }
Command::Bones { bundle, json } => rig::list(&Bundle::open(&bundle)?, json)?,
Command::Solo { bundle, layer, flags } => {
let opened = Bundle::open(&bundle)?;
diff --git a/crates/cli/src/rig.rs b/crates/cli/src/rig.rs
index 51ee102..c0a7c18 100644
--- a/crates/cli/src/rig.rs
+++ b/crates/cli/src/rig.rs
@@ -115,7 +115,9 @@ fn posed(bundle: &Bundle, doc: &mut Document, spec: &PoseSpec, weights: &Weights
ik: spec.ik.clone(),
};
let marks = bundle.read_marks(&layer.id, &rest)?;
- let made = Rig::new(&owner.bones, &owner.ik, weights, &pose).pose(&marks, canvas);
+ let made = Rig::new(&owner.bones, &owner.ik, weights, &pose)
+ .following(layer.bone.as_deref())
+ .pose(&marks, canvas);
let here = layer.cels().iter().find(|c| c.frame == spec.to);
let (cel, fresh) = match here {
Some(c) if c.pose.as_ref().is_some_and(|p| p.rest == rest) => (c.id.clone(), false),
@@ -212,6 +214,7 @@ 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| {
let mut entry = json!({"cel": c.id, "frame": c.frame, "rest": p.rest, "angles": p.angles, "root": p.root});
if !p.ik.is_empty() {
@@ -233,8 +236,9 @@ 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());
o.bones.iter().for_each(|b: &Bone| {
- let painted = weights.as_ref().is_some_and(|w| w.maps.contains_key(&b.name));
+ let painted = !bending || weights.as_ref().is_some_and(|w| w.maps.contains_key(&b.name));
println!(
" {:<14} {:<12} {:.0},{:.0} -> {:.0},{:.0}{}",
b.name,
@@ -264,6 +268,10 @@ pub fn list(bundle: &Bundle, as_json: bool) -> Result<()> {
_ => println!(" ik {}: an aim", c.bone),
}
});
+ painted(o).iter().for_each(|l| match &l.bone {
+ Some(b) => println!(" layer {} follows {b}", l.name),
+ None => println!(" layer {} bends by the weights", l.name),
+ });
painted(o).iter().for_each(|l| {
l.cels()
.iter()
@@ -298,6 +306,7 @@ pub struct Posed {
bones: Vec<Bone>,
ik: Vec<Ik>,
weights: Weights,
+ bone: Option<String>,
a: Pose,
b: Pose,
rest: Vec<Mark>,
@@ -306,7 +315,9 @@ pub struct Posed {
impl Posed {
pub fn at(&self, t: f32, canvas: (u32, u32)) -> (Vec<Mark>, Pose) {
let pose = between(&self.bones, &self.ik, &self.a, &self.b, t);
- let mut marks = Rig::new(&self.bones, &self.ik, &self.weights, &pose).pose(&self.rest, canvas);
+ let mut marks = Rig::new(&self.bones, &self.ik, &self.weights, &pose)
+ .following(self.bone.as_deref())
+ .pose(&self.rest, canvas);
marks
.iter_mut()
.for_each(|m| m.set_author(klad_core::stroke::Author::Agent));
@@ -348,6 +359,7 @@ pub fn posed_pair(bundle: &Bundle, layer: &str, a: &str, b: &str) -> Result<Opti
bones: owner.bones.clone(),
ik: owner.ik.clone(),
weights,
+ bone: paint.bone.clone(),
a: pa.clone(),
b: pb,
rest: bundle.read_marks(layer, &pa.rest)?,
@@ -395,6 +407,84 @@ mod tests {
s.samples[s.samples.len() - 1].pos()
}
+ #[test]
+ fn an_attached_layer_moves_rigidly_with_its_bone_and_keeps_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.timeline.frames = 9;
+ doc.next_id = 10;
+ Bundle::create(&dir, doc).unwrap();
+ 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]]}"##,
+ )
+ .unwrap();
+ assert!(
+ edit(&dir, r#"{"op":"attach","layer":"l2","bone":"wing"}"#).is_err(),
+ "only a bone the skeleton 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}}"#,
+ )
+ .unwrap();
+ let bundle = Bundle::open(&dir).unwrap();
+ 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();
+ let s = marks.iter().find_map(Mark::as_stroke).unwrap().clone();
+ (s.samples[0].pos(), s.samples[s.samples.len() - 1].pos())
+ };
+ let (a, b) = (line("l1", 0), line("l1", 4));
+ assert!(
+ (a.0.0 - b.0.0).abs() < 0.01 && (a.1.0 - b.1.0).abs() < 0.01 && (a.1.1 - b.1.1).abs() < 0.01,
+ "the upper arm does not move when only the forearm turns, not even its end by the elbow: {a:?} {b:?}"
+ );
+ let (start, end) = line("l2", 4);
+ assert!(
+ (start.0 - 300.0).abs() < 0.5 && (start.1 - 160.0).abs() < 0.5,
+ "the forearm's start, 40 px before the elbow, turns with it: {start:?}"
+ );
+ assert!(
+ (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();
+ 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();
+ 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"
+ );
+ 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"}"#,
+ )
+ .unwrap();
+ assert!(
+ Bundle::open(&dir).unwrap().doc.layer("l2").unwrap().bone.is_none(),
+ "no bone detaches"
+ );
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
+
#[test]
fn an_ik_limb_reaches_its_target_and_stays_planted_through_the_in_betweens() {
let dir = arm("ik");
diff --git a/crates/cli/src/scene.rs b/crates/cli/src/scene.rs
index 01ee590..fcc5692 100644
--- a/crates/cli/src/scene.rs
+++ b/crates/cli/src/scene.rs
@@ -148,6 +148,7 @@ struct Part {
origin: [f32; 2],
vertices: Vec<[f32; 2]>,
triangles: Vec<[usize; 3]>,
+ bone: Option<usize>,
}
const GRID: u32 = 16;
@@ -334,6 +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)),
});
Ok(())
})
@@ -487,7 +489,14 @@ pub fn rig(path: &Path, dir: Option<PathBuf>) -> Result<Vec<PathBuf>> {
.iter()
.map(|t| format!("PackedInt32Array({}, {}, {})", t[0], t[1], t[2]))
.collect();
- let per_vertex: Vec<Vec<f32>> = p.vertices.iter().map(|v| weights.at(bones, *v)).collect();
+ let per_vertex: Vec<Vec<f32>> = p
+ .vertices
+ .iter()
+ .map(|v| match p.bone {
+ Some(on) => (0..bones.len()).map(|i| if i == on { 1.0 } else { 0.0 }).collect(),
+ None => weights.at(bones, *v),
+ })
+ .collect();
let bone_list: Vec<String> = paths
.iter()
.enumerate()
@@ -635,6 +644,23 @@ func _process(_delta):
text.contains("\"values\": [0.0, -1.222]"),
"angles in radians, as floats"
);
+ let weights_of = |text: &str, bone: &str| -> Vec<f32> {
+ let from = format!("NodePath(\"{bone}\"), ");
+ let rest = &text[text.find(&from).unwrap() + from.len()..];
+ let inner = &rest[rest.find('(').unwrap() + 1..rest.find(')').unwrap()];
+ inner.split(',').map(|v| v.trim().parse().unwrap()).collect()
+ };
+ assert!(
+ weights_of(&text, "upper").iter().any(|w| *w > 0.0 && *w < 1.0),
+ "a layer that bends blends its bones"
+ );
+ edit(r#"{"op":"attach","layer":"arm","bone":"fore"}"#);
+ let attached = fs::read_to_string(rig(&path, Some(project.join("art"))).unwrap().last().unwrap()).unwrap();
+ assert!(
+ weights_of(&attached, "upper").iter().all(|w| *w == 0.0)
+ && weights_of(&attached, "upper/fore").iter().all(|w| *w == 1.0),
+ "a layer attached to a bone is all that bone's"
+ );
let planes = parallax(&path, Some(project.join("art")), 0).unwrap();
let scene = fs::read_to_string(planes.last().unwrap()).unwrap();
assert!(scene.contains("scroll_scale = Vector2(0.25, 0.25)") && scene.contains("scroll_scale = Vector2(1, 1)"));
diff --git a/crates/core/src/bundle.rs b/crates/core/src/bundle.rs
index ead859e..b7f4885 100644
--- a/crates/core/src/bundle.rs
+++ b/crates/core/src/bundle.rs
@@ -526,6 +526,7 @@ pub fn summarize(ops: &[Op]) -> String {
Op::PaintOver(spec) => format!("paint over on {}", spec.layer),
Op::Bone(spec) => format!("bones on {}", spec.layer),
Op::Ik(spec) => format!("IK on {}", spec.layer),
+ Op::Attach(spec) => format!("{} attached", spec.layer),
Op::Key(spec) => format!("keys on {} at frame {}", spec.id, spec.frame),
Op::Weights(spec) => format!("weights on {}", spec.layer),
Op::Pose(spec) => format!("pose on {} at frame {}", spec.layer, spec.to),
diff --git a/crates/core/src/doc.rs b/crates/core/src/doc.rs
index 770b9be..7e27a83 100644
--- a/crates/core/src/doc.rs
+++ b/crates/core/src/doc.rs
@@ -1,12 +1,12 @@
use crate::color::parse_hex;
use crate::generators::{Mirror, Picture, Repeat, Scatter, Text};
use crate::look::{Adjustment, Atmosphere, Effect, Rays};
-use anyhow::{Context, Result, bail};
+use anyhow::{Context, Result, anyhow, bail};
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
use std::collections::{BTreeMap, BTreeSet};
-pub const FORMAT: &str = "klad/2";
+pub const FORMAT: &str = "klad/3";
pub const MAX_SIZE: u32 = 16384;
pub const MASK: usize = usize::MAX;
@@ -149,6 +149,8 @@ pub struct Layer {
pub bones: Vec<crate::rig::Bone>,
#[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>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub keys: crate::keys::Keys,
}
@@ -524,6 +526,7 @@ impl Layer {
reference: false,
bones: Vec::new(),
ik: Vec::new(),
+ bone: None,
keys: BTreeMap::new(),
}
}
@@ -1235,6 +1238,23 @@ 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 layer.kind() != Kind::Paint {
+ bail!("layer {}: only paint layers follow a bone", 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) {
+ bail!(
+ "layer {}: follows bone {bone}, which {} does not have",
+ layer.id,
+ owner.name
+ );
+ }
+ }
if !layer.bones.is_empty() || !layer.ik.is_empty() {
if !matches!(layer.kind(), Kind::Paint | Kind::Group) {
bail!("layer {}: bones go on a paint layer or a group", layer.id);
diff --git a/crates/core/src/migrate.rs b/crates/core/src/migrate.rs
index af265db..34ad969 100644
--- a/crates/core/src/migrate.rs
+++ b/crates/core/src/migrate.rs
@@ -10,7 +10,7 @@ pub fn migrate(value: Value) -> Result<Value> {
.to_string();
match format.as_str() {
FORMAT => Ok(value),
- "klad/1" => {
+ "klad/1" | "klad/2" => {
let mut value = value;
value["format"] = Value::from(FORMAT);
Ok(value)
diff --git a/crates/core/src/ops.rs b/crates/core/src/ops.rs
index 1ddbf05..0f8f42b 100644
--- a/crates/core/src/ops.rs
+++ b/crates/core/src/ops.rs
@@ -157,6 +157,7 @@ pub enum Op {
PaintOver(PaintOverSpec),
Bone(BoneSpec),
Ik(IkSpec),
+ Attach(AttachSpec),
Weights(WeightsSpec),
Pose(PoseSpec),
Key(KeySpec),
@@ -675,6 +676,14 @@ pub struct Shifted {
pub weights: Vec<(String, crate::rig::Weights)>,
}
+#[derive(Clone, Debug, Default, PartialEq, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct AttachSpec {
+ pub layer: String,
+ #[serde(default)]
+ pub bone: Option<String>,
+}
+
#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum BendSpec {
@@ -1572,6 +1581,7 @@ impl Op {
}
"bone" => Op::Bone(serde_json::from_value(Value::Object(std::mem::take(&mut map)))?),
"ik" => Op::Ik(serde_json::from_value(Value::Object(std::mem::take(&mut map)))?),
+ "attach" => Op::Attach(serde_json::from_value(Value::Object(std::mem::take(&mut map)))?),
"weights" => Op::Weights(serde_json::from_value(Value::Object(std::mem::take(&mut map)))?),
"pose" => Op::Pose(serde_json::from_value(Value::Object(std::mem::take(&mut map)))?),
"grass" => Op::Grass(serde_json::from_value(Value::Object(std::mem::take(&mut map)))?),
@@ -1827,6 +1837,23 @@ fn bone(doc: &mut Document, spec: &BoneSpec, out: &mut Applied) -> Result<()> {
let also = bake(doc, &path, &bones, &ik, &held, &gone);
ik.retain(|c| !held.contains(&c.bone));
bones.retain(|b| !gone.contains(&b.name));
+ let loose: Vec<String> = followers(doc, &path)
+ .iter()
+ .filter_map(|p| {
+ let layer = doc.layer_at_mut(p);
+ layer.bone.take_if(|b| gone.contains(b)).map(|_| layer.name.clone())
+ })
+ .collect();
+ if !loose.is_empty() {
+ out.notes.push(format!(
+ "{} followed a removed bone, so {} by the weights again",
+ loose.join(", "),
+ match loose.len() {
+ 1 => "it bends",
+ _ => "they bend",
+ }
+ ));
+ }
crate::doc::family_paths(doc, &path).iter().for_each(|p| {
if let Some(cels) = doc.layer_at_mut(p).cels_mut() {
cels.iter_mut().filter_map(|c| c.pose.as_mut()).for_each(|pose| {
@@ -1874,6 +1901,12 @@ 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());
+ }
+ });
out.renamed_bones.push((id.clone(), name.clone(), to.clone()));
}
(None, None, None, Some(name), None) => {
@@ -1934,6 +1967,52 @@ fn bone(doc: &mut Document, spec: &BoneSpec, out: &mut Applied) -> Result<()> {
Ok(())
}
+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()
+}
+
+fn attach(doc: &mut Document, spec: &AttachSpec, out: &mut Applied) -> Result<()> {
+ let Some(Loc::Layer(path)) = doc.locate(&spec.layer) else {
+ bail!("no layer {}", spec.layer);
+ };
+ 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);
+ }
+ 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
+ );
+ };
+ if let Some(b) = &spec.bone
+ && !owner.bones.iter().any(|o| &o.name == b)
+ {
+ bail!(
+ "no bone {b} on {} (its bones: {})",
+ owner.name,
+ owner
+ .bones
+ .iter()
+ .map(|o| o.name.as_str())
+ .collect::<Vec<_>>()
+ .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"),
+ });
+ out.changed.push(id);
+ Ok(())
+}
+
fn bake(
doc: &mut Document,
path: &[usize],
@@ -3398,6 +3477,7 @@ pub fn apply(doc: &mut Document, op: &Op, out: &mut Applied) -> Result<()> {
}
Op::Bone(spec) => bone(doc, spec, out)?,
Op::Ik(spec) => ik(doc, spec, out)?,
+ Op::Attach(spec) => attach(doc, spec, out)?,
Op::Key(spec) => key(doc, spec, out)?,
Op::Weights(spec) => {
let Some(made) = &spec.resolved else {
diff --git a/crates/core/src/patch.rs b/crates/core/src/patch.rs
index ee62691..d60b495 100644
--- a/crates/core/src/patch.rs
+++ b/crates/core/src/patch.rs
@@ -128,6 +128,7 @@ fn layer_shell(layer: &Layer) -> Layer {
reference: layer.reference,
bones: layer.bones.clone(),
ik: layer.ik.clone(),
+ bone: layer.bone.clone(),
keys: layer.keys.clone(),
}
}
diff --git a/crates/core/src/rig.rs b/crates/core/src/rig.rs
index f396cab..0c48f26 100644
--- a/crates/core/src/rig.rs
+++ b/crates/core/src/rig.rs
@@ -775,6 +775,7 @@ pub struct Rig<'a> {
pub bones: &'a [Bone],
pub weights: &'a Weights,
pub mats: Vec<Mat>,
+ pub on: Option<usize>,
}
impl<'a> Rig<'a> {
@@ -783,10 +784,19 @@ impl<'a> Rig<'a> {
bones,
weights,
mats: skinning(bones, ik, pose),
+ on: None,
}
}
+ pub fn following(self, bone: Option<&str>) -> Self {
+ let on = bone.and_then(|b| self.bones.iter().position(|o| o.name == b));
+ Self { on, ..self }
+ }
+
pub fn moved(&self, p: [f32; 2]) -> [f32; 2] {
+ if let Some(m) = self.on.and_then(|i| self.mats.get(i)) {
+ return apply(*m, p);
+ }
let w = self.weights.at(self.bones, p);
w.iter()
.zip(&self.mats)
@@ -883,8 +893,12 @@ impl<'a> Rig<'a> {
}
pub fn pose(&self, marks: &[Mark], canvas: (u32, u32)) -> Vec<Mark> {
- if self.mats.iter().all(|m| {
- *m == [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
+ let mats: Vec<&Mat> = match self.on {
+ Some(i) => self.mats.get(i).into_iter().collect(),
+ None => self.mats.iter().collect(),
+ };
+ if mats.iter().all(|m| {
+ **m == [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
|| m.iter()
.zip([1.0, 0.0, 0.0, 1.0, 0.0, 0.0])
.all(|(a, b)| (a - b).abs() < 1e-5)
@@ -952,6 +966,13 @@ 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 family(layer: &Layer) -> Vec<&Layer> {
std::iter::once(layer)
.chain(layer.children().iter().flat_map(family))
diff --git a/docs/DESIGN.md b/docs/DESIGN.md
index e894f9b..6d97536 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/2`)
+### doc.json (format `klad/3`)
```json
{
- "format": "klad/2",
+ "format": "klad/3",
"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. 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. History patches never carry the change, because they are diffs of documents already migrated in memory.
### Edits
diff --git a/docs/cli.md b/docs/cli.md
index 5407783..2f8c940 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -45,6 +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 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
@@ -2255,6 +2256,48 @@ Options:
Print help (see a summary with '-h')
```
+## 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.
+
+ klad attach art.klad forearm --bone fore
+ klad 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.
+
+Usage: klad attach [OPTIONS] <BUNDLE> <LAYER>
+
+Arguments:
+ <BUNDLE>
+
+
+ <LAYER>
+
+
+Options:
+ --bone <BONE>
+
+
+ --off
+ detach: the layer bends by the weights again
+
+ --render
+ Render a preview after the edit and print its path
+
+ --scale <SCALE>
+ Preview scale (default: longest side 1024 px)
+
+ --json
+ Print the result as JSON
+
+ --overlay <OVERLAY>
+ Draw on the preview: ids, bbox, grid or all (comma separated)
+
+ -h, --help
+ Print help (see a summary with '-h')
+```
+
## klad solo
```text
@@ -2368,7 +2411,7 @@ Options:
## klad pose
```text
-A pose is a turn per bone (degrees from its rest angle, children follow their parent), a move of the whole (--root), and a target per IK (--target, canvas px; see klad ik): the IK's limb turns so its end reaches the target, and the target stays put when the root moves. --mix blends an IK's limb from its turns (0) to reaching the target (1, the default). Every paint layer under the skeleton gets a new drawing at --to: each stroke point and fill moves by its bones' weighted blend, the same way Godot's Skeleton2D bends a Polygon2D. The pose is kept on the drawing; posing that frame again re-poses it from the same rest drawing, and posing from a posed drawing starts from its rest drawing. klad inbetween between two poses of one rest drawing turns the bones instead of matching strokes, and moves the targets in straight lines, so a foot planted in both keys stays planted.
+A pose is a turn per bone (degrees from its rest angle, children follow their parent), a move of the whole (--root), and a target per IK (--target, canvas px; see klad ik): the IK's limb turns so its end reaches the target, and the target stays put when the root moves. --mix blends an IK's limb from its turns (0) to reaching the target (1, the default). Every paint layer under the skeleton gets a new drawing at --to: a layer attached to a bone (klad attach) moves with that bone alone; in the others each stroke point and fill moves by its bones' weighted blend, the same way Godot's Skeleton2D bends a Polygon2D. The pose is kept on the drawing; posing that frame again re-poses it from the same rest drawing, and posing from a posed drawing starts from its rest drawing. klad inbetween between two poses of one rest drawing turns the bones instead of matching strokes, and moves the targets in straight lines, so a foot planted in both keys stays planted.
klad pose art.klad body --from 0 --to 4 --bone thigh=25 --bone shin=-40 --root 0,6
klad pose art.klad body --from 0 --to 8 --target shin=410,740 --root 20,6
diff --git a/docs/format.md b/docs/format.md
index 67a95c0..4d3f73a 100644
--- a/docs/format.md
+++ b/docs/format.md
@@ -1,4 +1,4 @@
-_Last updated: 2026-11-07 (format `klad/2`, stroke files `KLST` version 1, brushes `klad-brush/1`)_
+_Last updated: 2026-11-08 (format `klad/3`, stroke files `KLST` version 1, brushes `klad-brush/1`)_
# The klad drawing format
@@ -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/2`. 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/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.
## doc.json
```json
{
- "format": "klad/2",
+ "format": "klad/3",
"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/2"` |
+| `format` | string | | `"klad/3"` |
| `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 |
@@ -104,6 +104,7 @@ A clip is `name` (unique), `from` and `to` (both included), `loop` (false) and `
| `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) |
| `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).
@@ -210,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. 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 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 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.
@@ -333,3 +334,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. |
diff --git a/docs/skill/SKILL.md b/docs/skill/SKILL.md
index de0a022..c0c4770 100644
--- a/docs/skill/SKILL.md
+++ b/docs/skill/SKILL.md
@@ -226,7 +226,8 @@ klad bone art.klad figure --add body --head 400,590 --tail 400,360
klad bone art.klad figure --add upper --parent body --head 452,392 --tail 560,360 # a child starts at its parent's end, or anywhere
klad 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 before
klad ik art.klad figure --add shin # a limb: shin and thigh reach for a target, bending as drawn
-klad weights art.klad figure --auto # blend from the bones
+klad attach art.klad forearm --bone fore # a layer drawn as its own piece moves with one bone, no weights
+klad weights art.klad figure --auto # blend from the bones, for layers that bend
klad weights art.klad figure --bone head --part head # a part held rigidly by one bone
klad weights art.klad figure --bone upper --set '470,380,20,1 500,370,16,0.8' # soft dabs: x,y,radius,weight
klad pose art.klad figure --from 0 --to 4 --bone upper=-35 --bone fore=-55 --hold 4
@@ -240,6 +241,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.
- 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.