Skip to content

armgit / klad

Public Imported from GitHub
0

A drawing app built for agent/human collaboration

Rust

Bones: chains and IK

Indicode BV70bd3df47c24
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d775905..ff5d8b8 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/1`. Drawings from before (`.draw` folders) do not open and are not converted.
+- 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.
- 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.
@@ -18,6 +18,8 @@ The first builds, and klad's licences.
- 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 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).
- Picking strokes takes what you see: the topmost layer that shows paint under the pen and the mark covering the point, on all layers or this layer only (the S and V options).
- A selected shape takes the colour as its fill or its outline (the shape's bar, Edit > Shape).
diff --git a/crates/app/src/editor.rs b/crates/app/src/editor.rs
index ef2c122..970ca1e 100644
--- a/crates/app/src/editor.rs
+++ b/crates/app/src/editor.rs
@@ -2932,6 +2932,7 @@ impl Editor {
self.keep_typing_focus(ui, &response)?;
self.typing_keys(ui)?;
self.pen_keys(ui)?;
+ self.bone_keys(ui);
self.command_keys(ui)?;
let ctx = ui.ctx().clone();
let was_focused = self.focused;
@@ -2947,6 +2948,9 @@ impl Editor {
.admit(holding, events)
.into_iter()
.try_for_each(|e| self.on_pen(&ctx, e, rect, was_focused))?;
+ if self.tool == Tool::Bone && response.secondary_clicked() {
+ self.end_chain();
+ }
if self.tool == Tool::Note
&& response.secondary_clicked()
&& let (Some(p), Some(view)) = (response.interact_pointer_pos(), self.view)
diff --git a/crates/app/src/editor/bones.rs b/crates/app/src/editor/bones.rs
index 6e7cf3e..95dc8a8 100644
--- a/crates/app/src/editor/bones.rs
+++ b/crates/app/src/editor/bones.rs
@@ -1,11 +1,12 @@
-use super::Editor;
+use super::{Editor, Tool};
use crate::jobs::{Spec, Tag};
+use crate::messages::Tone;
use crate::theme::{self, Hint};
use anyhow::{Context, Result, bail};
-use egui::{Color32, Pos2, RichText, Vec2};
+use egui::{Color32, Key, Modifiers, Pos2, RichText, Vec2};
use klad_core::doc::Kind;
-use klad_core::ops::{BoneSpec, Op, WeightsSpec};
-use klad_core::rig::{Bone, CELL, Pose, Weights, moved, subtree, tips, weights_for};
+use klad_core::ops::{BendSpec, BoneSpec, IkSpec, Op, WeightsSpec};
+use klad_core::rig::{Bend, Bone, CELL, Ik, Pose, Reach, Weights, applied, moved, painted, subtree, tips, weights_for};
use std::collections::BTreeMap;
use std::path::PathBuf;
@@ -37,15 +38,37 @@ pub(super) struct Drag {
pub what: Dragging,
}
+#[derive(Clone, Debug, PartialEq)]
+pub(super) struct Chain {
+ pub owner: String,
+ pub parent: Option<String>,
+ pub head: [f32; 2],
+ pub joined: bool,
+ pub drawn: Vec<String>,
+ pub to: Vec2,
+ pub pressed: bool,
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub(super) enum Posing {
+ Turn(String),
+ Reach(String, Vec2),
+ Root(Vec2),
+}
+
pub(super) struct BoneTool {
pub mode: Mode,
pub selected: Option<String>,
pub drag: Option<Drag>,
+ pub chain: Option<Chain>,
pub dabs: Vec<[f32; 4]>,
pub radius: f32,
pub strength: f32,
pub pose: BTreeMap<String, f32>,
- pub turning: Option<String>,
+ pub root: [f32; 2],
+ pub reach: BTreeMap<String, Reach>,
+ pub loaded: Option<(u32, String, Option<Pose>)>,
+ pub posing: Option<Posing>,
pub name: String,
pub heat: Option<(String, u64, egui::TextureHandle)>,
}
@@ -56,11 +79,15 @@ impl Default for BoneTool {
mode: Mode::Draw,
selected: None,
drag: None,
+ chain: None,
dabs: Vec::new(),
radius: 24.0,
strength: 1.0,
pose: BTreeMap::new(),
- turning: None,
+ root: [0.0, 0.0],
+ reach: BTreeMap::new(),
+ loaded: None,
+ posing: None,
name: String::new(),
heat: None,
}
@@ -70,6 +97,7 @@ impl Default for BoneTool {
const NEAR: f32 = 10.0;
const CLICK: f32 = 5.0;
const JOINED: f32 = 0.5;
+const TARGET: Color32 = Color32::from_rgb(255, 120, 50);
type Later = Box<dyn FnOnce(&mut Editor) -> Result<()>>;
@@ -80,12 +108,20 @@ fn near_segment(p: Vec2, a: [f32; 2], b: [f32; 2]) -> f32 {
(a + d * t - p).length()
}
-pub(super) fn pose_args(
- bundle: &std::path::Path,
- owner: &str,
- frame: u32,
- pose: &BTreeMap<String, f32>,
-) -> Vec<String> {
+fn at(p: [f32; 2]) -> Vec2 {
+ Vec2::new(p[0], p[1])
+}
+
+fn limb(bones: &[Bone], k: &Ik) -> Vec<String> {
+ let parent = bones
+ .iter()
+ .find(|b| b.name == k.bone)
+ .and_then(|b| b.parent.clone())
+ .filter(|_| k.chain == 2);
+ std::iter::once(k.bone.clone()).chain(parent).collect()
+}
+
+pub(super) fn pose_args(bundle: &std::path::Path, owner: &str, frame: u32, pose: &Pose) -> Vec<String> {
let mut args = vec![
"pose".to_string(),
bundle.to_string_lossy().to_string(),
@@ -95,9 +131,22 @@ pub(super) fn pose_args(
"--to".into(),
frame.to_string(),
];
- pose.iter()
+ pose.angles
+ .iter()
.filter(|(_, v)| v.abs() > 1e-3)
.for_each(|(k, v)| args.extend(["--bone".to_string(), format!("{k}={v:.2}")]));
+ if pose.root != [0.0, 0.0] {
+ args.extend(["--root".to_string(), format!("{:.2},{:.2}", pose.root[0], pose.root[1])]);
+ }
+ pose.ik.iter().for_each(|(k, r)| {
+ args.extend([
+ "--target".to_string(),
+ format!("{k}={:.2},{:.2}", r.target[0], r.target[1]),
+ ]);
+ if r.mix != 1.0 {
+ args.extend(["--mix".to_string(), format!("{k}={:.3}", r.mix)]);
+ }
+ });
args
}
@@ -123,14 +172,208 @@ impl Editor {
.unwrap_or_default()
}
+ fn rig_ik(&self) -> Vec<Ik> {
+ self.rig_owner()
+ .and_then(|id| self.scene.bundle.doc.layer(&id).map(|l| l.ik.clone()))
+ .unwrap_or_default()
+ }
+
fn shown_pose(&self) -> Pose {
match self.bones.mode {
- Mode::Draw => Pose::default(),
- _ => Pose {
+ Mode::Pose => Pose {
+ rest: String::new(),
angles: self.bones.pose.clone(),
- ..Pose::default()
+ root: self.bones.root,
+ ik: self.bones.reach.clone(),
+ },
+ _ => Pose::default(),
+ }
+ }
+
+ fn stored_pose(&self, owner: &str) -> Option<Pose> {
+ let layer = self.scene.bundle.doc.layer(owner)?;
+ painted(layer)
+ .iter()
+ .find_map(|l| l.content_at(self.scene.frame).and_then(|c| c.pose.clone()))
+ }
+
+ pub(super) fn bone_keys(&mut self, ui: &mut egui::Ui) {
+ self.tend_chain();
+ self.tend_pose();
+ if self.bones.chain.is_none() {
+ return;
+ }
+ let (enter, escape) = ui.input_mut(|i| {
+ (
+ i.consume_key(Modifiers::NONE, Key::Enter),
+ i.consume_key(Modifiers::NONE, Key::Escape),
+ )
+ });
+ if enter || escape {
+ self.end_chain();
+ }
+ }
+
+ pub(super) fn end_chain(&mut self) {
+ if self.bones.chain.take().is_some() {
+ self.say(Tone::Info, "chain ended");
+ }
+ }
+
+ fn tend_chain(&mut self) {
+ let Some(mut chain) = self.bones.chain.take() else {
+ return;
+ };
+ if self.tool != Tool::Bone || self.bones.mode != Mode::Draw || self.rig_owner().as_deref() != Some(&chain.owner)
+ {
+ return;
+ }
+ let bones = self.rig_bones();
+ let exists = |n: &str| bones.iter().any(|b| b.name == n);
+ if chain.parent.as_deref().is_some_and(|p| !exists(p)) {
+ while chain.drawn.last().is_some_and(|n| !exists(n)) {
+ chain.drawn.pop();
+ }
+ let Some(last) = chain.drawn.last() else {
+ return;
+ };
+ chain.parent = Some(last.clone());
+ chain.joined = true;
+ }
+ if chain.joined
+ && let Some(p) = chain.parent.as_ref().and_then(|p| bones.iter().find(|b| &b.name == p))
+ {
+ chain.head = p.tail;
+ }
+ self.bones.chain = Some(chain);
+ }
+
+ fn tend_pose(&mut self) {
+ if self.bones.mode != Mode::Pose {
+ self.bones.loaded = None;
+ return;
+ }
+ let Some(owner) = self.rig_owner() else {
+ return;
+ };
+ let stored = self.stored_pose(&owner);
+ let key = (self.scene.frame, owner, stored.clone());
+ if self.bones.loaded.as_ref() == Some(&key) {
+ return;
+ }
+ let pose = stored.unwrap_or_default();
+ self.bones.pose = pose.angles;
+ self.bones.root = pose.root;
+ self.bones.reach = pose.ik;
+ self.bones.posing = None;
+ self.bones.loaded = Some(key);
+ }
+
+ 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 taken = self.rig_bones();
+ let name = (1..)
+ .map(|n| format!("bone {n}"))
+ .find(|n| !taken.iter().any(|b| &b.name == n))
+ .unwrap_or_default();
+ self.apply(vec![Op::Bone(BoneSpec {
+ layer: owner,
+ add: Some(name.clone()),
+ parent: parent.clone(),
+ head: Some(head),
+ tail: Some(tail),
+ ..BoneSpec::default()
+ })])?;
+ self.pick_bone(Some(name.clone()));
+ Ok(Bone {
+ name,
+ parent,
+ head,
+ tail,
+ })
+ }
+
+ fn chain_on(&mut self, drawn: Vec<String>, made: &Bone) {
+ let Some(owner) = self.rig_owner() else {
+ return;
+ };
+ let bones = self.rig_bones();
+ let sibling = self.modifiers.shift;
+ let joined = |b: &Bone| {
+ b.parent
+ .as_ref()
+ .and_then(|p| bones.iter().find(|o| &o.name == p))
+ .is_some_and(|p| (at(p.tail) - at(b.head)).length() <= JOINED)
+ };
+ self.bones.chain = Some(Chain {
+ owner,
+ parent: match sibling {
+ true => made.parent.clone(),
+ false => Some(made.name.clone()),
},
+ head: if sibling { made.head } else { made.tail },
+ joined: !sibling || joined(made),
+ drawn,
+ to: at(made.tail),
+ pressed: false,
+ });
+ }
+
+ fn chain_up(&mut self) -> Result<()> {
+ self.tend_chain();
+ let Some(chain) = self.bones.chain.clone() else {
+ return Ok(());
+ };
+ if !chain.pressed {
+ return Ok(());
+ }
+ if let Some(c) = self.bones.chain.as_mut() {
+ c.pressed = false;
+ }
+ if (chain.to - at(chain.head)).length() * self.zoom() < CLICK {
+ self.end_chain();
+ return Ok(());
}
+ let made = self.add_bone(chain.parent.clone(), chain.head, [chain.to.x, chain.to.y])?;
+ let mut drawn = chain.drawn;
+ drawn.push(made.name.clone());
+ self.chain_on(drawn, &made);
+ Ok(())
+ }
+
+ fn limb_of(&self, name: &str) -> Option<String> {
+ let bones = self.rig_bones();
+ self.rig_ik()
+ .into_iter()
+ .filter(|k| self.bones.reach.get(&k.bone).is_some_and(|r| r.mix > 0.0))
+ .find(|k| limb(&bones, k).iter().any(|b| b == name))
+ .map(|k| k.bone)
+ }
+
+ fn ik_on(&mut self, end: &str) {
+ let bones = self.rig_bones();
+ let Some(i) = bones.iter().position(|b| b.name == end) else {
+ return;
+ };
+ let tip = tips(&bones, &self.rig_ik(), &self.shown_pose())[i].1;
+ self.bones
+ .reach
+ .insert(end.to_string(), Reach { target: tip, mix: 1.0 });
+ }
+
+ fn ik_off(&mut self, end: &str) {
+ let (bones, ik) = (self.rig_bones(), self.rig_ik());
+ let solved = applied(&bones, &ik, &self.shown_pose());
+ if let Some(k) = ik.iter().find(|k| k.bone == end) {
+ limb(&bones, k).into_iter().for_each(|b| {
+ if let Some(v) = solved.get(&b) {
+ self.bones.pose.insert(b, *v);
+ }
+ });
+ }
+ self.bones.reach.remove(end);
}
fn zoom(&self) -> f32 {
@@ -205,7 +448,7 @@ impl Editor {
fn bone_at(&self, c: Vec2) -> Option<String> {
let bones = self.rig_bones();
let zoom = self.zoom();
- let shown = tips(&bones, &self.shown_pose());
+ let shown = tips(&bones, &self.rig_ik(), &self.shown_pose());
bones
.iter()
.zip(shown)
@@ -217,13 +460,19 @@ impl Editor {
pub(super) fn bone_down(&mut self, c: Vec2) {
match self.bones.mode {
+ Mode::Draw if self.bones.chain.is_some() => {
+ if let Some(chain) = self.bones.chain.as_mut() {
+ chain.pressed = true;
+ chain.to = c;
+ }
+ }
Mode::Draw if self.modifiers.alt => {
let bones = self.rig_bones();
let reach = NEAR / self.zoom();
let from_tail = bones
.iter()
- .find(|b| (Vec2::new(b.tail[0], b.tail[1]) - c).length() <= reach)
- .map(|b| (b.name.clone(), Vec2::new(b.tail[0], b.tail[1])));
+ .find(|b| (at(b.tail) - c).length() <= reach)
+ .map(|b| (b.name.clone(), at(b.tail)));
let (parent, from) = match from_tail {
Some((name, tail)) => (Some(name), tail),
None => (self.bone_at(c), c),
@@ -256,13 +505,66 @@ impl Editor {
self.bones.dabs.clear();
self.bone_dab(c);
}
- Mode::Pose => {
- self.bones.turning = self.bone_at(c);
- if let Some(b) = self.bones.turning.clone() {
- self.pick_bone(Some(b));
- }
- }
+ Mode::Pose => self.pose_down(c),
+ }
+ }
+
+ fn pose_down(&mut self, c: Vec2) {
+ let (bones, ik) = (self.rig_bones(), self.rig_ik());
+ let shown = tips(&bones, &ik, &self.shown_pose());
+ let reach = NEAR / self.zoom();
+ let alt = self.modifiers.alt;
+ let handle = ik
+ .iter()
+ .filter_map(|k| {
+ let i = bones.iter().position(|b| b.name == k.bone)?;
+ let tip = shown[i].1;
+ let target = self.bones.reach.get(&k.bone).map(|r| r.target);
+ let d = (at(tip) - c)
+ .length()
+ .min(target.map_or(f32::MAX, |t| (at(t) - c).length()));
+ (d <= reach).then(|| (d, k.bone.clone(), target.unwrap_or(tip)))
+ })
+ .min_by(|a, b| a.0.total_cmp(&b.0));
+ if !alt && let Some((_, end, target)) = handle {
+ let target = self
+ .bones
+ .reach
+ .entry(end.clone())
+ .or_insert(Reach { target, mix: 1.0 })
+ .target;
+ self.bones.posing = Some(Posing::Reach(end.clone(), at(target) - c));
+ self.pick_bone(Some(end));
+ return;
+ }
+ let root = bones
+ .iter()
+ .zip(&shown)
+ .filter(|(b, _)| b.parent.is_none())
+ .map(|(b, (h, _))| ((at(*h) - c).length(), b.name.clone()))
+ .filter(|(d, _)| *d <= reach)
+ .min_by(|a, b| a.0.total_cmp(&b.0));
+ if !alt && let Some((_, name)) = root {
+ self.bones.posing = Some(Posing::Root(c));
+ self.pick_bone(Some(name));
+ return;
}
+ let Some(name) = self.bone_at(c) else {
+ self.bones.posing = None;
+ return;
+ };
+ self.pick_bone(Some(name.clone()));
+ self.bones.posing = match self.limb_of(&name) {
+ Some(end) if !alt => {
+ let target = self.bones.reach[&end].target;
+ Some(Posing::Reach(end, at(target) - c))
+ }
+ Some(end) => {
+ self.ik_off(&end);
+ Some(Posing::Turn(name))
+ }
+ None => Some(Posing::Turn(name)),
+ };
}
fn bone_dab(&mut self, c: Vec2) {
@@ -280,6 +582,9 @@ impl Editor {
pub(super) fn bone_move(&mut self, c: Vec2) {
match self.bones.mode {
Mode::Draw => {
+ if let Some(chain) = self.bones.chain.as_mut() {
+ chain.to = c;
+ }
if let Some(drag) = self.bones.drag.as_mut() {
drag.to = c;
}
@@ -289,27 +594,37 @@ impl Editor {
self.bone_dab(c);
}
}
- Mode::Pose => {
- let Some(name) = self.bones.turning.clone() else {
- return;
- };
- let bones = self.rig_bones();
- let Some(i) = bones.iter().position(|b| b.name == name) else {
- return;
- };
- let shown = tips(&bones, &self.shown_pose());
- let (head, tail) = shown[i];
- let now = (tail[1] - head[1]).atan2(tail[0] - head[0]);
- let want = (c.y - head[1]).atan2(c.x - head[0]);
- let mut turn = (want - now).to_degrees();
- turn = (turn + 540.0).rem_euclid(360.0) - 180.0;
- *self.bones.pose.entry(name).or_insert(0.0) += turn;
- }
+ Mode::Pose => match self.bones.posing.clone() {
+ Some(Posing::Turn(name)) => {
+ let bones = self.rig_bones();
+ let Some(i) = bones.iter().position(|b| b.name == name) else {
+ return;
+ };
+ let shown = tips(&bones, &self.rig_ik(), &self.shown_pose());
+ let (head, tail) = shown[i];
+ let now = (tail[1] - head[1]).atan2(tail[0] - head[0]);
+ let want = (c.y - head[1]).atan2(c.x - head[0]);
+ let mut turn = (want - now).to_degrees();
+ turn = (turn + 540.0).rem_euclid(360.0) - 180.0;
+ *self.bones.pose.entry(name).or_insert(0.0) += turn;
+ }
+ Some(Posing::Reach(end, offset)) => {
+ if let Some(r) = self.bones.reach.get_mut(&end) {
+ r.target = [c.x + offset.x, c.y + offset.y];
+ }
+ }
+ Some(Posing::Root(last)) => {
+ self.bones.root = [self.bones.root[0] + c.x - last.x, self.bones.root[1] + c.y - last.y];
+ self.bones.posing = Some(Posing::Root(c));
+ }
+ None => {}
+ },
}
}
pub(super) fn bone_up(&mut self) -> Result<()> {
match self.bones.mode {
+ Mode::Draw if self.bones.chain.is_some() => self.chain_up()?,
Mode::Draw => {
let Some(drag) = self.bones.drag.take() else {
return Ok(());
@@ -327,24 +642,8 @@ impl Editor {
}
(Dragging::New(parent), false) => parent.clone(),
};
- let (a, b) = (drag.from, drag.to);
- let owner = self
- .rig_owner()
- .context("pick the layer or group the bones go on first")?;
- let taken = self.rig_bones();
- let name = (1..)
- .map(|n| format!("bone {n}"))
- .find(|n| !taken.iter().any(|b| &b.name == n))
- .unwrap_or_default();
- self.apply(vec![Op::Bone(BoneSpec {
- layer: owner,
- add: Some(name.clone()),
- parent,
- head: Some([a.x, a.y]),
- tail: Some([b.x, b.y]),
- ..BoneSpec::default()
- })])?;
- self.pick_bone(Some(name));
+ let made = self.add_bone(parent, [drag.from.x, drag.from.y], [drag.to.x, drag.to.y])?;
+ self.chain_on(vec![made.name.clone()], &made);
}
Mode::Weights => {
let dabs = std::mem::take(&mut self.bones.dabs);
@@ -368,7 +667,7 @@ impl Editor {
resolved: None,
})?;
}
- Mode::Pose => self.bones.turning = None,
+ Mode::Pose => self.bones.posing = None,
}
Ok(())
}
@@ -393,7 +692,8 @@ impl Editor {
fn pose_drawing(&mut self) -> Result<()> {
let owner = self.rig_owner().context("no skeleton here")?;
- if self.bones.pose.values().all(|v| v.abs() < 1e-3) {
+ let pose = self.shown_pose();
+ if pose.angles.values().all(|v| v.abs() < 1e-3) && pose.root == [0.0, 0.0] && pose.ik.is_empty() {
bail!("turn a bone first: drag a bone's end in pose mode");
}
let frame = self.scene.frame;
@@ -401,7 +701,7 @@ impl Editor {
tag: Tag::Edit,
name: format!("pose at frame {frame}"),
exe: PathBuf::new(),
- args: pose_args(&self.scene.bundle.root, &owner, frame, &self.bones.pose),
+ args: pose_args(&self.scene.bundle.root, &owner, frame, &pose),
env: Vec::new(),
reruns: 3,
summary: |out, _| {
@@ -412,24 +712,148 @@ impl Editor {
},
failure: |_, err| super::tweens::failure(err),
});
- self.bones.pose.clear();
Ok(())
}
+ fn ik_spec(&self, edit: impl FnOnce(&mut IkSpec)) -> Option<IkSpec> {
+ let mut spec = IkSpec {
+ layer: self.rig_owner()?,
+ ..IkSpec::default()
+ };
+ edit(&mut spec);
+ Some(spec)
+ }
+
+ fn ik_menu(&mut self, ui: &mut egui::Ui, picked: &str) -> Option<Later> {
+ let (bones, ik) = (self.rig_bones(), self.rig_ik());
+ let parent = bones.iter().find(|b| b.name == picked)?.parent.clone();
+ let mut chosen: Option<IkSpec> = None;
+ let name = picked.to_string();
+ match ik.iter().find(|k| k.bone == picked) {
+ Some(k) => {
+ let label = match (k.chain, &parent) {
+ (2, Some(p)) => format!("IK: limb with {p}"),
+ _ => "IK: aim".to_string(),
+ };
+ ui.menu_button(label, |ui| {
+ if k.chain == 2 {
+ [
+ (Bend::Clockwise, BendSpec::Clockwise, "bends clockwise"),
+ (
+ Bend::Counterclockwise,
+ BendSpec::Counterclockwise,
+ "bends counterclockwise",
+ ),
+ ]
+ .into_iter()
+ .for_each(|(bend, spec, word)| {
+ if ui
+ .selectable_label(k.bend == bend, word)
+ .hint("which way the joint between the two bones bends on screen")
+ .clicked()
+ && k.bend != bend
+ {
+ chosen = self.ik_spec(|s| {
+ s.set = Some(name.clone());
+ s.bend = Some(spec);
+ });
+ ui.close();
+ }
+ });
+ let mut soft = k.softness;
+ let r = ui
+ .add(egui::Slider::new(&mut soft, 0.0..=100.0).text("softness"))
+ .hint("px: the limb slows this far before full reach, so it does not snap straight");
+ if (r.drag_stopped() || (r.changed() && !r.dragged())) && soft != k.softness {
+ chosen = self.ik_spec(|s| {
+ s.set = Some(name.clone());
+ s.softness = Some(soft);
+ });
+ }
+ if ui
+ .button("make it an aim")
+ .hint("turn this bone alone to point at the target")
+ .clicked()
+ {
+ chosen = self.ik_spec(|s| {
+ s.set = Some(name.clone());
+ s.chain = Some(1);
+ });
+ ui.close();
+ }
+ } else if let Some(p) = &parent
+ && ui
+ .button(format!("make it a limb with {p}"))
+ .hint("turn this bone and its parent so its end reaches the target")
+ .clicked()
+ {
+ chosen = self.ik_spec(|s| {
+ s.set = Some(name.clone());
+ s.chain = Some(2);
+ });
+ ui.close();
+ }
+ if ui.button("remove IK").hint("poses keep their look, as turns").clicked() {
+ chosen = self.ik_spec(|s| s.rm = Some(name.clone()));
+ ui.close();
+ }
+ })
+ .response
+ .hint("this bone's IK: in pose mode, drag its end and the limb follows");
+ }
+ None => {
+ ui.menu_button("add IK", |ui| {
+ if let Some(p) = &parent
+ && ui
+ .button(format!("limb: {picked} and {p}"))
+ .hint(
+ "in pose mode, drag this bone's end and both bones turn to reach it, bending as drawn",
+ )
+ .clicked()
+ {
+ chosen = self.ik_spec(|s| {
+ s.add = Some(name.clone());
+ s.chain = Some(2);
+ });
+ ui.close();
+ }
+ if ui
+ .button(format!("aim: {picked}"))
+ .hint("in pose mode, drag this bone's end and it turns to point there")
+ .clicked()
+ {
+ chosen = self.ik_spec(|s| {
+ s.add = Some(name.clone());
+ s.chain = Some(1);
+ });
+ ui.close();
+ }
+ })
+ .response
+ .hint("IK: pose this bone by where its end goes instead of by turning it");
+ }
+ }
+ chosen.map(|spec| -> Later { Box::new(move |e| e.apply(vec![Op::Ik(spec)])) })
+ }
+
pub(super) fn bone_options(&mut self, ui: &mut egui::Ui) -> Result<()> {
let mut run: Option<Later> = None;
[
(
Mode::Draw,
"draw",
- "drag on empty canvas to draw a bone; drag a bone's end or middle to move it; alt drag from a bone's end for a child",
+ "drag on empty canvas to draw a chain of bones; drag a bone's end or middle to move it; alt drag from a bone's end for a child",
),
(
Mode::Weights,
"weights",
"paint the picked bone's weight; alt removes it; cmd click a bone to pick it",
),
- (Mode::Pose, "pose", "drag a bone's end to turn it, its children follow"),
+ (
+ Mode::Pose,
+ "pose",
+ "drag a bone's end to turn it, its children follow; drag an IK limb's end and the limb reaches for it",
+ ),
]
.iter()
.for_each(|(mode, label, hint)| {
@@ -439,18 +863,8 @@ impl Editor {
.clicked()
{
self.bones.mode = *mode;
- if *mode == Mode::Pose {
- self.bones.pose = self
- .rig_owner()
- .and_then(|o| self.scene.bundle.doc.layer(&o).cloned())
- .and_then(|o| {
- klad_core::rig::painted(&o)
- .iter()
- .find_map(|l| l.content_at(self.scene.frame).and_then(|c| c.pose.clone()))
- })
- .map(|p| p.angles)
- .unwrap_or_default();
- }
+ self.bones.loaded = None;
+ self.bones.posing = None;
}
});
ui.separator();
@@ -478,17 +892,32 @@ impl Editor {
}));
} else if let Some(later) = self.parent_menu(ui, &picked) {
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() {
run = Some(Box::new(move |e| {
+ e.end_chain();
e.bone_edit(|s| s.rm = Some(picked))?;
e.pick_bone(None);
Ok(())
}));
}
- ui.label(RichText::new("drag its ends or middle; alt drag: a child").color(theme::WEAK));
- } else {
- ui.label(RichText::new("drag to draw a bone; click one to pick it").color(theme::WEAK));
}
+ let (hint, more) = match (&self.bones.chain, &self.bones.selected) {
+ (Some(_), _) => (
+ "click: the next bone; Esc: done",
+ "each click places the next bone of the chain; shift as you let go starts the next one from the same joint; Esc, Enter, a right click or a click on the chain's open end ends it",
+ ),
+ (None, Some(_)) => (
+ "drag its ends or middle; alt drag: a child",
+ "drag an end or the middle to move it; alt drag from its end starts a chain from there; a drag on empty canvas starts a new chain",
+ ),
+ (None, None) => (
+ "drag to draw a chain of bones",
+ "a drag draws a bone and the chain carries on from its end: each click adds the next; click a bone to pick it",
+ ),
+ };
+ ui.label(RichText::new(hint).color(theme::WEAK)).hint(more);
}
Mode::Weights => {
ui.add(
@@ -553,8 +982,48 @@ impl Editor {
{
run = Some(Box::new(|e| e.pose_drawing()));
}
- if ui.button("back to rest").hint("forget the turns").clicked() {
+ if ui
+ .button("back to rest")
+ .hint("forget the turns, the move and the targets")
+ .clicked()
+ {
self.bones.pose.clear();
+ self.bones.root = [0.0, 0.0];
+ self.bones.reach.clear();
+ }
+ let (bones, ik) = (self.rig_bones(), self.rig_ik());
+ let held = self
+ .bones
+ .selected
+ .as_ref()
+ .and_then(|p| ik.iter().find(|k| limb(&bones, k).contains(p)))
+ .map(|k| k.bone.clone());
+ let how = "drag a bone's end to turn it; drag the end of an IK limb and the limb reaches for it; drag a root bone's head to move the whole while IK ends stay; alt drag turns a bone by hand, taking its limb off IK";
+ match held {
+ Some(end) => {
+ let mut on = self.bones.reach.contains_key(&end);
+ if ui
+ .checkbox(&mut on, "IK")
+ .hint(format!(
+ "on: {end}'s limb reaches for its target; off: turn it by hand, as it is now. {how}"
+ ))
+ .changed()
+ {
+ match on {
+ true => self.ik_on(&end),
+ false => self.ik_off(&end),
+ }
+ }
+ if let Some(r) = self.bones.reach.get_mut(&end) {
+ ui.spacing_mut().slider_width = 70.0;
+ ui.add(egui::Slider::new(&mut r.mix, 0.0..=1.0).text("mix"))
+ .hint("0: the limb's own turns; 1: it reaches the target");
+ }
+ }
+ None => {
+ ui.label(RichText::new("drag an end; alt: turn by hand").color(theme::WEAK))
+ .hint(how);
+ }
}
}
}
@@ -647,6 +1116,7 @@ impl Editor {
.hint(format!("the skeleton of {owner}, each bone under its parent: pick one"));
chosen.map(|name| -> Later {
Box::new(move |e| {
+ e.end_chain();
e.pick_bone(Some(name));
Ok(())
})
@@ -745,10 +1215,17 @@ impl Editor {
);
}
let bones = self.drawn_bones();
- let shown = tips(&bones, &self.shown_pose());
+ let ik = self.rig_ik();
+ let pose = self.shown_pose();
+ let shown = tips(&bones, &ik, &pose);
let editing = self.bones.mode == Mode::Draw;
- bones.iter().zip(shown).for_each(|(b, (h, t))| {
- let (a, z) = (place(Vec2::new(h[0], h[1])), place(Vec2::new(t[0], t[1])));
+ let held: Vec<String> = ik
+ .iter()
+ .filter(|k| pose.ik.get(&k.bone).is_some_and(|r| r.mix > 0.0))
+ .flat_map(|k| limb(&bones, k))
+ .collect();
+ bones.iter().zip(&shown).for_each(|(b, (h, t))| {
+ let (a, z) = (place(at(*h)), place(at(*t)));
let picked = self.bones.selected.as_ref() == Some(&b.name);
let colour = if picked {
theme::ACCENT
@@ -757,8 +1234,19 @@ impl Editor {
};
painter.line_segment([a, z], egui::Stroke::new(6.0, Color32::from_black_alpha(150)));
painter.line_segment([a, z], egui::Stroke::new(3.0, colour));
+ if held.contains(&b.name) {
+ painter.line_segment([a, z], egui::Stroke::new(1.2, Color32::from_black_alpha(200)));
+ }
painter.circle_filled(a, 4.5, colour);
painter.circle_stroke(z, 4.0, egui::Stroke::new(1.5, colour));
+ if ik.iter().any(|k| k.bone == b.name) {
+ painter.rect_stroke(
+ egui::Rect::from_center_size(z, egui::vec2(11.0, 11.0)),
+ 1.0,
+ egui::Stroke::new(1.5, TARGET),
+ egui::StrokeKind::Middle,
+ );
+ }
if picked && editing {
[a, z].into_iter().for_each(|p| {
painter.circle_filled(p, 6.5, Color32::WHITE);
@@ -781,6 +1269,37 @@ impl Editor {
{
painter.line_segment([place(*from), place(*to)], egui::Stroke::new(2.0, theme::ACCENT));
}
+ if editing && let Some(chain) = &self.bones.chain {
+ let (a, z) = (place(at(chain.head)), place(chain.to));
+ painter.extend(egui::Shape::dashed_line(
+ &[a, z],
+ egui::Stroke::new(2.0, theme::ACCENT),
+ 6.0,
+ 4.0,
+ ));
+ painter.circle_stroke(a, 6.5, egui::Stroke::new(1.5, theme::ACCENT));
+ }
+ if self.bones.mode == Mode::Pose {
+ ik.iter().for_each(|k| {
+ let (Some(r), Some(i)) = (pose.ik.get(&k.bone), bones.iter().position(|b| b.name == k.bone)) else {
+ return;
+ };
+ let (end, target) = (place(at(shown[i].1)), place(at(r.target)));
+ if (end - target).length() > 2.0 {
+ painter.extend(egui::Shape::dashed_line(
+ &[end, target],
+ egui::Stroke::new(1.5, TARGET),
+ 4.0,
+ 3.0,
+ ));
+ }
+ let stroke = egui::Stroke::new(2.0, TARGET);
+ painter.circle_stroke(target, 7.0, egui::Stroke::new(4.0, Color32::from_black_alpha(150)));
+ painter.circle_stroke(target, 7.0, stroke);
+ painter.line_segment([target - egui::vec2(11.0, 0.0), target + egui::vec2(11.0, 0.0)], stroke);
+ painter.line_segment([target - egui::vec2(0.0, 11.0), target + egui::vec2(0.0, 11.0)], stroke);
+ });
+ }
if editing
&& self.bones.drag.is_none()
&& let Some(p) = hover
@@ -810,10 +1329,32 @@ mod tests {
#[test]
fn a_pose_from_the_editor_is_the_cli_pose() {
- let pose = BTreeMap::from([("fore".to_string(), -45.0), ("upper".to_string(), 0.0)]);
+ let mut pose = Pose {
+ angles: BTreeMap::from([("fore".to_string(), -45.0), ("upper".to_string(), 0.0)]),
+ ..Pose::default()
+ };
assert_eq!(
pose_args(std::path::Path::new("/w/a.klad"), "l1", 4, &pose).join(" "),
"pose /w/a.klad l1 --from 4 --to 4 --bone fore=-45.00"
);
+ pose.root = [-3.0, 6.5];
+ pose.ik.insert(
+ "shin".into(),
+ Reach {
+ target: [410.0, 742.25],
+ mix: 1.0,
+ },
+ );
+ pose.ik.insert(
+ "hand".into(),
+ Reach {
+ target: [-5.0, 20.0],
+ mix: 0.25,
+ },
+ );
+ assert_eq!(
+ pose_args(std::path::Path::new("/w/a.klad"), "l1", 4, &pose).join(" "),
+ "pose /w/a.klad l1 --from 4 --to 4 --bone fore=-45.00 --root -3.00,6.50 --target hand=-5.00,20.00 --mix hand=0.250 --target shin=410.00,742.25"
+ );
}
}
diff --git a/crates/app/src/editor/ui_tests.rs b/crates/app/src/editor/ui_tests.rs
index 0a656a5..8b21098 100644
--- a/crates/app/src/editor/ui_tests.rs
+++ b/crates/app/src/editor/ui_tests.rs
@@ -3339,6 +3339,201 @@ fn bones_are_drawn_weighted_and_posed_on_the_canvas() {
let _ = std::fs::remove_dir_all(&path);
}
+#[test]
+fn bones_are_drawn_as_a_chain_that_fans_ends_and_takes_back_its_last_bone() {
+ let path = sample("chain");
+ let mut h = harness(editor(&path), vec2(1440.0, 1000.0));
+ activate(&mut h, "lines");
+ h.key_press(Key::J);
+ h.run_steps(2);
+ let bones = |h: &Harness<'static, Editor>| h.state().scene.bundle.doc.layer("l6").unwrap().bones.clone();
+ let 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]);
+ h.run_steps(2);
+ assert!(h.state().bones.chain.is_some(), "letting go starts the next bone");
+ click_with(&mut h, screen[2], Modifiers::NONE);
+ click_with(&mut h, screen[3], Modifiers::NONE);
+ let drawn = bones(&h);
+ assert_eq!(drawn.len(), 3, "{drawn:?}");
+ assert_eq!(drawn[1].parent.as_deref(), Some("bone 1"));
+ assert_eq!(drawn[2].parent.as_deref(), Some("bone 2"));
+ assert!(
+ drawn.windows(2).all(|w| w[1].head == w[0].tail),
+ "each bone starts on the last one's end"
+ );
+ assert_eq!(
+ h.state().bones.selected.as_deref(),
+ Some("bone 3"),
+ "the new bone is picked"
+ );
+ h.key_press_modifiers(Modifiers::COMMAND, Key::Z);
+ h.run_steps(3);
+ assert_eq!(bones(&h).len(), 2, "cmd Z takes back the last bone");
+ let again = canvas_at(&h, 230.0, 40.0);
+ click_with(&mut h, again, Modifiers::NONE);
+ let redrawn = bones(&h);
+ assert_eq!(redrawn.len(), 3);
+ assert_eq!(
+ redrawn[2].parent.as_deref(),
+ Some("bone 2"),
+ "and the chain carries on from the one before"
+ );
+ assert_eq!(redrawn[2].head, redrawn[1].tail);
+ let joint = canvas_at(&h, redrawn[2].tail[0], redrawn[2].tail[1]);
+ click_with(&mut h, joint, Modifiers::NONE);
+ assert!(
+ h.state().bones.chain.is_none(),
+ "a click on the open end ends the chain"
+ );
+ assert_eq!(bones(&h).len(), 3);
+ let (root, hand) = (canvas_at(&h, 400.0, 300.0), canvas_at(&h, 400.0, 220.0));
+ drag(&mut h, root, hand);
+ h.run_steps(2);
+ let fingers = [[360.0, 160.0], [400.0, 150.0], [440.0, 160.0]];
+ fingers.iter().for_each(|f| {
+ let at = canvas_at(&h, f[0], f[1]);
+ click_with(&mut h, at, Modifiers::SHIFT);
+ });
+ let fanned = bones(&h);
+ let palm = fanned
+ .iter()
+ .find(|b| b.head == fanned[3].head && b.parent.is_none())
+ .unwrap()
+ .name
+ .clone();
+ let spread: Vec<_> = fanned
+ .iter()
+ .filter(|b| b.parent.as_deref() == Some(palm.as_str()))
+ .collect();
+ assert_eq!(spread.len(), 3, "shift fans siblings from one joint: {fanned:?}");
+ assert!(spread.iter().all(|b| b.head == fanned[3].tail));
+ h.key_press(Key::Escape);
+ h.run_steps(2);
+ assert!(h.state().bones.chain.is_none(), "Esc ends the chain");
+ let count = bones(&h).len();
+ let empty = canvas_at(&h, 500.0, 60.0);
+ click_with(&mut h, empty, Modifiers::NONE);
+ assert_eq!(bones(&h).len(), count, "a click with no chain adds nothing");
+ let cli = sample("chain-cli");
+ Bundle::open(&cli)
+ .unwrap()
+ .apply(
+ &parse_lines(&format!(
+ r#"{{"op":"bone","layer":"l6","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();
+ 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);
+ let _ = std::fs::remove_dir_all(&cli);
+}
+
+#[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");
+ 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_label("add IK").click();
+ 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();
+ assert_eq!(ik.len(), 1, "{ik:?}");
+ assert_eq!((ik[0].bone.as_str(), ik[0].chain), ("shin", 2));
+ assert!(
+ h.query_by_label_contains("IK: limb with thigh").is_some(),
+ "the options show the bone's IK"
+ );
+ h.get_by_label("pose").click();
+ h.run_steps(2);
+ let shown = |h: &Harness<'static, Editor>| {
+ let ed = h.state();
+ let layer = ed.scene.bundle.doc.layer("l6").unwrap();
+ let pose = klad_core::rig::Pose {
+ angles: ed.bones.pose.clone(),
+ root: ed.bones.root,
+ ik: ed.bones.reach.clone(),
+ ..Default::default()
+ };
+ klad_core::rig::tips(&layer.bones, &layer.ik, &pose)
+ };
+ let canvas = h.state().canvas_rect;
+ let (foot, there) = (canvas_at(&h, 110.0, 260.0), canvas_at(&h, 170.0, 220.0));
+ drag(&mut h, foot, there);
+ h.run_steps(2);
+ assert_eq!(
+ h.state().canvas_rect,
+ canvas,
+ "picking a limb keeps the canvas where it is"
+ );
+ let target = h.state().bones.reach.get("shin").map(|r| r.target).unwrap();
+ assert!(
+ (target[0] - 170.0).abs() < 1.5 && (target[1] - 220.0).abs() < 1.5,
+ "{target:?}"
+ );
+ let end = shown(&h)[1].1;
+ assert!(
+ (end[0] - target[0]).abs() < 0.01 && (end[1] - target[1]).abs() < 0.01,
+ "the foot reaches: {end:?}"
+ );
+ let (hip, moved) = (canvas_at(&h, 100.0, 60.0), canvas_at(&h, 130.0, 70.0));
+ drag(&mut h, hip, moved);
+ h.run_steps(2);
+ let root = h.state().bones.root;
+ assert!(
+ (root[0] - 30.0).abs() < 1.5 && (root[1] - 10.0).abs() < 1.5,
+ "the root's head moves it all: {root:?}"
+ );
+ let planted = shown(&h)[1].1;
+ assert!(
+ (planted[0] - target[0]).abs() < 0.01 && (planted[1] - target[1]).abs() < 0.01,
+ "the foot stays planted: {planted:?}"
+ );
+ let knee = shown(&h)[0].1;
+ let (thigh, swung) = (
+ canvas_at(&h, (130.0 + knee[0]) / 2.0, (70.0 + knee[1]) / 2.0),
+ canvas_at(&h, 60.0, 140.0),
+ );
+ h.event(egui::Event::ModifiersChanged(Modifiers::ALT));
+ drag(&mut h, thigh, swung);
+ h.event(egui::Event::ModifiersChanged(Modifiers::NONE));
+ h.run_steps(2);
+ assert!(
+ h.state().bones.reach.is_empty(),
+ "alt drag takes the limb off IK and turns it by hand"
+ );
+ let args = super::bones::pose_args(
+ &h.state().scene.bundle.root,
+ "l6",
+ 0,
+ &klad_core::rig::Pose {
+ angles: h.state().bones.pose.clone(),
+ root: h.state().bones.root,
+ ..Default::default()
+ },
+ );
+ assert!(args.iter().any(|a| a == "--root"), "{args:?}");
+ let _ = std::fs::remove_dir_all(&path);
+}
+
#[test]
fn bones_are_picked_from_the_list_and_the_canvas_and_edited_in_place() {
let path = sample("bone-edit");
diff --git a/crates/cli/src/agent.rs b/crates/cli/src/agent.rs
index d494f9e..30ae6e0 100644
--- a/crates/cli/src/agent.rs
+++ b/crates/cli/src/agent.rs
@@ -415,6 +415,10 @@ pub fn render_look(
true => crate::rig::bones_at(bundle, frame)?,
false => Vec::new(),
},
+ targets: match kinds.bones {
+ true => crate::rig::targets_at(bundle, frame),
+ false => Vec::new(),
+ },
heat: kinds
.weights
.as_deref()
diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs
index 072ae7e..51c2890 100644
--- a/crates/cli/src/main.rs
+++ b/crates/cli/src/main.rs
@@ -26,7 +26,7 @@ mod sheet;
mod sprites;
use agent::{Look, Output};
-use anyhow::{Result, anyhow, bail};
+use anyhow::{Context, Result, anyhow, bail};
use clap::{Args, Parser, Subcommand};
use klad_brush::BrushSet;
use klad_core::bundle::{Blank, Bundle};
@@ -35,8 +35,8 @@ use klad_core::fill::{EXPAND, FillSource, TOLERANCE};
use klad_core::history::Stack;
use klad_core::markedit::{LassoAction, MarkTransform};
use klad_core::ops::{
- BoneSpec, ClipEdit, CopySpec, CopyTarget, FillSpec, FoliageSpec, GrassSpec, HatchSpec, InbetweenSpec, InkSpec,
- LassoSpec, LightSpec, Op, PaintOverSpec, PaintSpec, PaletteEdit, Place, PoseSpec, ScatterSpec, StrokeSpec,
+ BoneSpec, ClipEdit, CopySpec, CopyTarget, FillSpec, FoliageSpec, GrassSpec, HatchSpec, IkSpec, InbetweenSpec,
+ InkSpec, LassoSpec, LightSpec, Op, PaintOverSpec, PaintSpec, PaletteEdit, Place, PoseSpec, ScatterSpec, StrokeSpec,
WeightsSpec,
};
use klad_core::retime::{Retime, RetimeSpec};
@@ -45,6 +45,7 @@ use klad_core::timing::{CelAction, CelSpec, FrameSpec};
use klad_core::tween::{Match, Spacing, Unpaired};
use klad_render::{View, compose};
use marks::{fill_json, hex8, stroke_json};
+use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::time::Instant;
@@ -1163,7 +1164,7 @@ enum Command {
},
#[command(
about = "Add, remove, rename, move or reparent a bone of a layer's or group's skeleton",
- long_about = "Bones go on a paint layer or a group (a group's skeleton poses every paint layer in it together). A bone has a name, an optional parent, a head and a tail in canvas px; a child usually starts where its parent ends. Removing a bone removes its children. Moving a tail takes the heads of the children that start there along; --by moves a bone with all its children.\n\n klad bone art.klad body --add hip --head 400,500 --tail 400,420\n klad bone art.klad body --add thigh --parent hip --head 400,500 --tail 410,620\n klad bone art.klad body --rename thigh --as femur\n klad bone art.klad body --move femur --tail 420,630\n klad bone art.klad body --move femur --by 12,-4\n klad bone art.klad body --reparent femur --parent pelvis\n klad bone art.klad body --rm femur\n\nAlso a bone op: {\"op\":\"bone\",\"layer\":\"body\",\"add\":\"thigh\",\"parent\":\"hip\",\"head\":[400,500],\"tail\":[410,620]}."
+ long_about = "Bones go on a paint layer or a group (a group's skeleton poses every paint layer in it together). A bone has a name, an optional parent, a head and a tail in canvas px; a child usually starts where its parent ends. --chain adds several bones at once, each the child of the one before and starting where it ends, through one more point than bones (the editor's bone tool draws chains the same way). Removing a bone removes its children (and the IK on them, its poses keeping their look). Moving a tail takes the heads of the children that start there along; --by moves a bone with all its children.\n\n klad bone art.klad body --add hip --head 400,500 --tail 400,420\n klad bone art.klad body --add thigh --parent hip --head 400,500 --tail 410,620\n klad bone art.klad body --chain thigh,shin,foot --through '400,500 410,620 405,740 440,745' --parent hip\n klad bone art.klad body --rename thigh --as femur\n klad bone art.klad body --move femur --tail 420,630\n klad bone art.klad body --move femur --by 12,-4\n klad bone art.klad body --reparent femur --parent pelvis\n klad bone art.klad body --rm femur\n\nAlso a bone op: {\"op\":\"bone\",\"layer\":\"body\",\"add\":\"thigh\",\"parent\":\"hip\",\"head\":[400,500],\"tail\":[410,620]}, or {\"op\":\"bone\",\"layer\":\"body\",\"chain\":[\"thigh\",\"shin\"],\"through\":[[400,500],[410,620],[405,740]],\"parent\":\"hip\"}."
)]
Bone {
bundle: PathBuf,
@@ -1188,6 +1189,42 @@ enum Command {
tail: Option<[f32; 2]>,
#[arg(long, value_parser = parse_pair, allow_hyphen_values = true, help = "dx,dy in px: with --move, the bone and its children")]
by: Option<[f32; 2]>,
+ #[arg(
+ long,
+ help = "names of a chain of new bones, comma separated: each the child of the one before"
+ )]
+ chain: Option<String>,
+ #[arg(
+ long,
+ allow_hyphen_values = true,
+ help = "the chain's points, 'x,y x,y ...': one more than its bones"
+ )]
+ through: Option<String>,
+ #[command(flatten)]
+ flags: EditFlags,
+ },
+ #[command(
+ about = "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",
+ long_about = "An IK turns bones so the end of a limb reaches a target, instead of turning each bone by hand. A limb (--chain 2, when the bone has a parent) turns the bone and its parent so the bone's tail lands on the target, the joint between them bending --bend clockwise or counterclockwise on screen (by default the way it bends in the rest drawing; flip turns it over); out of reach it points straight at the target. An aim (--chain 1) turns the bone to point at the target. --softness (px) eases the limb into full stretch so a knee does not snap straight: it starts slowing that far before full reach and is straight that far past it. Targets are set per pose (klad pose --target), in canvas px, and stay put when the root moves, so a foot stays planted while the body moves; a pose without a target for an IK leaves that limb to its turns. IKs are solved parent first: a foot's aim after its leg's limb.\n\n klad ik art.klad body --add shin\n klad ik art.klad body --add shin --chain 2 --bend counterclockwise --softness 8\n klad ik art.klad body --add foot --chain 1\n klad ik art.klad body --set shin --bend flip\n klad ik art.klad body --rm shin\n\nAlso an ik op: {\"op\":\"ik\",\"layer\":\"body\",\"add\":\"shin\",\"chain\":2,\"bend\":\"clockwise\",\"softness\":8}. Removing an IK (or its bone) keeps every pose as it looks, as turns."
+ )]
+ Ik {
+ bundle: PathBuf,
+ layer: String,
+ #[arg(long)]
+ add: Option<String>,
+ #[arg(long)]
+ set: Option<String>,
+ #[arg(long)]
+ rm: Option<String>,
+ #[arg(long, help = "2: a limb, the bone and its parent; 1: an aim, the bone alone")]
+ chain: Option<u8>,
+ #[arg(long, value_parser = ["clockwise", "counterclockwise", "flip"], help = "which way the limb's joint bends on screen")]
+ bend: Option<String>,
+ #[arg(
+ long,
+ help = "px: how far before full reach the limb starts to slow, so it does not snap straight"
+ )]
+ softness: Option<f32>,
#[command(flatten)]
flags: EditFlags,
},
@@ -1233,7 +1270,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) and a move of the whole (--root). 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.\n\n klad pose art.klad body --from 0 --to 4 --bone thigh=25 --bone shin=-40 --root 0,6\n\nAlso a pose op: {\"op\":\"pose\",\"layer\":\"body\",\"from\":0,\"to\":4,\"bones\":{\"thigh\":25,\"shin\":-40},\"root\":[0,6]}."
+ 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}}}."
)]
Pose {
bundle: PathBuf,
@@ -1246,6 +1283,18 @@ enum Command {
bones: Vec<String>,
#[arg(long, value_parser = parse_pair, allow_hyphen_values = true, default_value = "0,0")]
root: [f32; 2],
+ #[arg(
+ long = "target",
+ help = "bone=x,y: where the end of that bone's IK reaches, in canvas px; repeat for more",
+ allow_hyphen_values = true
+ )]
+ targets: Vec<String>,
+ #[arg(
+ long = "mix",
+ help = "bone=0..1: how far that IK pulls its limb from the turns to the target (default 1)",
+ allow_hyphen_values = true
+ )]
+ mixes: Vec<String>,
#[arg(long)]
hold: Option<u32>,
#[command(flatten)]
@@ -2843,8 +2892,22 @@ fn run() -> Result<()> {
head,
tail,
by,
+ chain,
+ through,
flags,
} => {
+ let through = through
+ .map(|t| {
+ t.split_whitespace()
+ .map(parse_pair)
+ .collect::<Result<Vec<_>>>()
+ .context("--through takes points 'x,y x,y ...'")
+ })
+ .transpose()?;
+ let chain = chain.map(|c| c.split(',').map(|n| n.trim().to_string()).collect::<Vec<_>>());
+ if chain.is_some() != through.is_some() {
+ bail!("--chain names the bones and --through gives their points: give both");
+ }
let spec = BoneSpec {
layer: layer_id(&bundle, &layer)?,
add,
@@ -2857,9 +2920,35 @@ fn run() -> Result<()> {
head,
tail,
by,
+ chain,
+ through,
};
agent::edit(&bundle, &[Op::Bone(spec)], &output(&flags, 0))?;
}
+ Command::Ik {
+ bundle,
+ layer,
+ add,
+ set,
+ rm,
+ chain,
+ bend,
+ softness,
+ flags,
+ } => {
+ let spec = IkSpec {
+ layer: layer_id(&bundle, &layer)?,
+ add,
+ set,
+ rm,
+ chain,
+ bend: bend
+ .map(|b| serde_json::from_value(serde_json::Value::String(b)))
+ .transpose()?,
+ softness,
+ };
+ agent::edit(&bundle, &[Op::Ik(spec)], &output(&flags, 0))?;
+ }
Command::Bones { bundle, json } => rig::list(&Bundle::open(&bundle)?, json)?,
Command::Solo { bundle, layer, flags } => {
let opened = Bundle::open(&bundle)?;
@@ -2945,6 +3034,8 @@ fn run() -> Result<()> {
to,
bones,
root,
+ targets,
+ mixes,
hold,
flags,
} => {
@@ -2957,12 +3048,42 @@ fn run() -> Result<()> {
Ok((name.trim().to_string(), deg.trim().parse()?))
})
.collect::<Result<_>>()?;
+ let mut ik: BTreeMap<String, klad_core::rig::Reach> = targets
+ .iter()
+ .map(|t| -> Result<(String, klad_core::rig::Reach)> {
+ let (name, at) = t
+ .split_once('=')
+ .ok_or_else(|| anyhow!("--target {t:?} is not bone=x,y"))?;
+ Ok((
+ name.trim().to_string(),
+ klad_core::rig::Reach {
+ target: parse_pair(at.trim())?,
+ mix: 1.0,
+ },
+ ))
+ })
+ .collect::<Result<_>>()?;
+ mixes.iter().try_for_each(|m| -> Result<()> {
+ let (name, value) = m
+ .split_once('=')
+ .ok_or_else(|| anyhow!("--mix {m:?} is not bone=0..1"))?;
+ let value: f32 = value.trim().parse()?;
+ if !(0.0..=1.0).contains(&value) {
+ bail!("--mix {m:?}: the mix goes from 0 (its turns) to 1 (the target)");
+ }
+ match ik.get_mut(name.trim()) {
+ Some(r) => r.mix = value,
+ None => bail!("--mix {}: give its --target {}=x,y too", name.trim(), name.trim()),
+ }
+ Ok(())
+ })?;
let spec = PoseSpec {
layer: layer_id(&bundle, &layer)?,
from,
to,
bones,
root,
+ ik,
hold,
resolved: None,
};
diff --git a/crates/cli/src/rig.rs b/crates/cli/src/rig.rs
index 1093605..0938a20 100644
--- a/crates/cli/src/rig.rs
+++ b/crates/cli/src/rig.rs
@@ -2,7 +2,7 @@ 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, Pose, Rig, Weights, family, painted, tips, weights_for};
+use klad_core::rig::{Bone, CELL, Ik, Pose, Rig, Weights, applied, between, family, painted, tips, weights_for};
use klad_core::stroke::Mark;
use klad_render::overlay::Heat;
use serde_json::json;
@@ -27,13 +27,34 @@ pub fn bones_at(bundle: &Bundle, frame: u32) -> Result<Vec<klad_render::overlay:
owner
.bones
.iter()
- .zip(tips(&owner.bones, &pose))
+ .zip(tips(&owner.bones, &owner.ik, &pose))
.map(|(b, (h, t))| (b.name.clone(), h, t))
.collect::<Vec<_>>()
})
.collect())
}
+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 shown = tips(&owner.bones, &owner.ik, &pose);
+ pose.ik
+ .iter()
+ .filter_map(|(bone, reach)| {
+ let i = owner.bones.iter().position(|b| &b.name == bone)?;
+ owner
+ .ik
+ .iter()
+ .any(|c| &c.bone == bone)
+ .then_some((shown[i].1, reach.target))
+ })
+ .collect::<Vec<_>>()
+ })
+ .collect()
+}
+
pub fn heat(bundle: &Bundle, bone: &str) -> Result<Heat> {
let owner = owners(&bundle.doc)
.into_iter()
@@ -68,6 +89,19 @@ fn posed(bundle: &Bundle, doc: &mut Document, spec: &PoseSpec, weights: &Weights
if let Some(b) = spec.bones.keys().find(|b| !owner.bones.iter().any(|o| &o.name == *b)) {
bail!("no bone {b} on {}", owner.name);
}
+ if let Some(b) = spec.ik.keys().find(|b| !owner.ik.iter().any(|c| &c.bone == *b)) {
+ bail!(
+ "no IK on {b} on {}: add one first with klad ik --add {b}{}",
+ owner.name,
+ match owner.ik.is_empty() {
+ true => String::new(),
+ false => format!(
+ " (the IKs end on {})",
+ owner.ik.iter().map(|c| c.bone.as_str()).collect::<Vec<_>>().join(", ")
+ ),
+ }
+ );
+ }
let canvas = (doc.canvas.width, doc.canvas.height);
let layers: Vec<Layer> = painted(&owner).into_iter().cloned().collect();
layers
@@ -78,9 +112,10 @@ fn posed(bundle: &Bundle, doc: &mut Document, spec: &PoseSpec, weights: &Weights
rest: rest.clone(),
angles: spec.bones.clone(),
root: spec.root,
+ ik: spec.ik.clone(),
};
let marks = bundle.read_marks(&layer.id, &rest)?;
- let made = Rig::new(&owner.bones, weights, &pose).pose(&marks, canvas);
+ let made = Rig::new(&owner.bones, &owner.ik, weights, &pose).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),
@@ -171,7 +206,20 @@ pub fn list(bundle: &Bundle, as_json: bool) -> Result<()> {
"tail": b.tail,
"weights": weights.as_ref().is_some_and(|w| w.maps.contains_key(&b.name)),
})).collect::<Vec<_>>(),
- "poses": painted(o).iter().flat_map(|l| l.cels().iter().filter_map(|c| c.pose.as_ref().map(|p| json!({"cel": c.id, "frame": c.frame, "rest": p.rest, "angles": p.angles, "root": p.root})))).collect::<Vec<_>>(),
+ "ik": o.ik.iter().map(|c| json!({
+ "bone": c.bone,
+ "chain": c.chain,
+ "bend": c.bend,
+ "softness": c.softness,
+ })).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() {
+ entry["ik"] = json!(p.ik);
+ entry["solved"] = json!(applied(&o.bones, &o.ik, p));
+ }
+ entry
+ }))).collect::<Vec<_>>(),
})
})
.collect();
@@ -198,13 +246,49 @@ pub fn list(bundle: &Bundle, as_json: bool) -> Result<()> {
if painted { "" } else { " no weights yet" }
);
});
+ o.ik.iter().for_each(|c: &Ik| {
+ let parent = o.bones.iter().find(|b| b.name == c.bone).and_then(|b| b.parent.clone());
+ match (c.chain, parent) {
+ (2, Some(p)) => println!(
+ " ik {}: a limb with {p}, bending {}{}",
+ c.bone,
+ serde_json::to_value(c.bend)
+ .ok()
+ .and_then(|v| v.as_str().map(str::to_string))
+ .unwrap_or_default(),
+ match c.softness > 0.0 {
+ true => format!(", softness {} px", c.softness),
+ false => String::new(),
+ }
+ ),
+ _ => println!(" ik {}: an aim", c.bone),
+ }
+ });
painted(o).iter().for_each(|l| {
l.cels()
.iter()
.filter_map(|c| c.pose.as_ref().map(|p| (c, p)))
.for_each(|(c, p)| {
let angles: Vec<String> = p.angles.iter().map(|(k, v)| format!("{k}={v}")).collect();
- println!(" pose {} at {} from {}: {}", c.id, c.frame, p.rest, angles.join(" "));
+ let root = match p.root == [0.0, 0.0] {
+ true => String::new(),
+ false => format!(" root {},{}", p.root[0], p.root[1]),
+ };
+ let targets: Vec<String> =
+ p.ik.iter()
+ .map(|(k, r)| match r.mix == 1.0 {
+ true => format!(" target {k}={},{}", r.target[0], r.target[1]),
+ false => format!(" target {k}={},{} mix {}", r.target[0], r.target[1], r.mix),
+ })
+ .collect();
+ println!(
+ " pose {} at {} from {}: {}{root}{}",
+ c.id,
+ c.frame,
+ p.rest,
+ angles.join(" "),
+ targets.concat()
+ );
})
});
});
@@ -214,6 +298,7 @@ pub fn list(bundle: &Bundle, as_json: bool) -> Result<()> {
#[derive(Clone)]
pub struct Posed {
bones: Vec<Bone>,
+ ik: Vec<Ik>,
weights: Weights,
a: Pose,
b: Pose,
@@ -222,9 +307,9 @@ pub struct Posed {
impl Posed {
pub fn at(&self, t: f32, canvas: (u32, u32)) -> (Vec<Mark>, Pose) {
- let pose = self.a.mix(&self.b, t);
+ let pose = between(&self.bones, &self.ik, &self.a, &self.b, t);
(
- Rig::new(&self.bones, &self.weights, &pose).pose(&self.rest, canvas),
+ Rig::new(&self.bones, &self.ik, &self.weights, &pose).pose(&self.rest, canvas),
pose,
)
}
@@ -262,6 +347,7 @@ pub fn posed_pair(bundle: &Bundle, layer: &str, a: &str, b: &str) -> Result<Opti
};
Ok(Some(Posed {
bones: owner.bones.clone(),
+ ik: owner.ik.clone(),
weights,
a: pa.clone(),
b: pb,
@@ -310,6 +396,114 @@ mod tests {
s.samples[s.samples.len() - 1].pos()
}
+ #[test]
+ fn an_ik_limb_reaches_its_target_and_stays_planted_through_the_in_betweens() {
+ 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}"#,
+ )
+ .unwrap();
+ let bundle = Bundle::open(&dir).unwrap();
+ let owner = bundle.doc.layer("l1").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]}}}"#
+ )
+ .is_err(),
+ "a target needs an IK on that bone"
+ );
+ 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]}}}"#,
+ )
+ .unwrap();
+ edit(&dir, r#"{"op":"inbetween","layers":["l1"],"from":4,"to":8}"#).unwrap();
+ let bundle = Bundle::open(&dir).unwrap();
+ (4..=8).for_each(|f| {
+ let end = end_of(&bundle, f);
+ assert!(
+ (end.0 - target[0]).hypot(end.1 - target[1]) < 4.0,
+ "frame {f}: the forearm's end stays on its target while the shoulder moves: {end:?}"
+ );
+ });
+ let mid = bundle
+ .doc
+ .layer("l1")
+ .unwrap()
+ .content_at(6)
+ .unwrap()
+ .pose
+ .clone()
+ .unwrap();
+ assert_eq!(mid.ik["fore"].target, target, "the in-between keeps the target");
+ assert!((mid.root[0] - 20.0).abs() < 1e-3 && (mid.root[1] + 15.0).abs() < 1e-3);
+ let shown = targets_at(&bundle, 6);
+ assert_eq!(shown.len(), 1);
+ assert!((shown[0].0[0] - target[0]).hypot(shown[0].0[1] - target[1]) < 0.01 && shown[0].1 == target);
+ let solved = applied(
+ &owner.bones,
+ &owner.ik,
+ bundle
+ .doc
+ .layer("l1")
+ .unwrap()
+ .content_at(4)
+ .unwrap()
+ .pose
+ .as_ref()
+ .unwrap(),
+ );
+ let out = dir.join("godot");
+ crate::scene::rig(&dir, Some(out.clone())).unwrap();
+ let scene = std::fs::read_dir(&out)
+ .unwrap()
+ .filter_map(|e| e.ok().map(|e| e.path()))
+ .find(|p| p.extension().is_some_and(|x| x == "tscn"))
+ .unwrap();
+ let text = std::fs::read_to_string(scene).unwrap();
+ let track = text
+ .split("tracks/")
+ .find(|t| t.contains("Skeleton2D/upper:rotation\""))
+ .unwrap();
+ let block = text[text.find(track).unwrap()..].to_string();
+ let values: Vec<f32> = block
+ .split("\"values\": [")
+ .nth(1)
+ .unwrap()
+ .split(']')
+ .next()
+ .unwrap()
+ .split(',')
+ .map(|v| v.trim().parse().unwrap())
+ .collect();
+ let wanted = solved["upper"] * (std::f32::consts::PI / 180.0);
+ assert!(
+ values.iter().any(|v| (v - wanted).abs() < 1e-3),
+ "the rig exports the solved turn {wanted}: {values:?}"
+ );
+ edit(&dir, r#"{"op":"ik","layer":"l1","rm":"fore"}"#).unwrap();
+ let bundle = Bundle::open(&dir).unwrap();
+ let kept = bundle
+ .doc
+ .layer("l1")
+ .unwrap()
+ .content_at(4)
+ .unwrap()
+ .pose
+ .clone()
+ .unwrap();
+ assert!(kept.ik.is_empty() && (kept.angles["upper"] - solved["upper"]).abs() < 1e-4);
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
+
#[test]
fn bones_weights_and_poses_through_the_cli_and_undo() {
let dir = arm("pose");
diff --git a/crates/cli/src/scene.rs b/crates/cli/src/scene.rs
index ac9a3f9..c6342a6 100644
--- a/crates/cli/src/scene.rs
+++ b/crates/cli/src/scene.rs
@@ -392,7 +392,10 @@ pub fn rig(path: &Path, dir: Option<PathBuf>) -> Result<Vec<PathBuf>> {
let (rest, _) = local(bones, i);
let values: Vec<f32> = poses
.iter()
- .map(|(_, p)| rest + p.angles.get(&b.name).copied().unwrap_or(0.0).to_radians())
+ .map(|(_, p)| {
+ let turned = klad_core::rig::applied(bones, &owner.ik, p);
+ rest + turned.get(&b.name).copied().unwrap_or(0.0) * (std::f32::consts::PI / 180.0)
+ })
.collect();
format!(
"tracks/{i}/type = \"value\"\ntracks/{i}/imported = false\ntracks/{i}/enabled = true\ntracks/{i}/path = NodePath(\"Skeleton2D/{}:rotation\")\ntracks/{i}/interp = 0\ntracks/{i}/loop_wrap = true\ntracks/{i}/keys = {{\n\"times\": {},\n\"transitions\": {},\n\"update\": 0,\n\"values\": [{}]\n}}\n",
diff --git a/crates/cli/tests/binary.rs b/crates/cli/tests/binary.rs
index 03a01a7..5082c9e 100644
--- a/crates/cli/tests/binary.rs
+++ b/crates/cli/tests/binary.rs
@@ -253,3 +253,64 @@ fn solo_shows_one_layer_and_undo_brings_the_rest_back() {
assert_eq!(shown(), [true, true, true]);
std::fs::remove_dir_all(&dir).unwrap();
}
+
+#[test]
+fn a_chain_and_its_ik_are_set_up_and_posed_from_the_command_line() {
+ let dir = std::env::temp_dir().join(format!("klad-binary-ik-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ let bundle = dir.join("a.klad");
+ let klad = |args: &[&str]| {
+ let out = Command::new(env!("CARGO_BIN_EXE_klad")).args(args).output().unwrap();
+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
+ String::from_utf8_lossy(&out.stdout).to_string()
+ };
+ let path = bundle.to_str().unwrap();
+ klad(&["new", path, "--width", "400", "--height", "400", "--frames", "6"]);
+ klad(&[
+ "stroke",
+ path,
+ "l1",
+ "--path",
+ "M100 100 L100 200 L100 300",
+ "--size",
+ "6",
+ ]);
+ let made = klad(&[
+ "bone",
+ path,
+ "l1",
+ "--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"]);
+ assert!(ik.contains("a limb with thigh") && ik.contains("softness 4"), "{ik}");
+ klad(&["ik", path, "l1", "--set", "shin", "--bend", "flip"]);
+ klad(&[
+ "pose",
+ path,
+ "l1",
+ "--from",
+ "0",
+ "--to",
+ "3",
+ "--target",
+ "shin=180,240",
+ "--mix",
+ "shin=0.5",
+ "--root",
+ "-10,0",
+ ]);
+ let listed = klad(&["bones", path]);
+ assert!(
+ listed.contains("ik shin: a limb with thigh, bending counterclockwise, softness 4 px"),
+ "{listed}"
+ );
+ assert!(listed.contains("root -10,0 target shin=180,240 mix 0.5"), "{listed}");
+ let json: serde_json::Value = serde_json::from_str(&klad(&["bones", path, "--json"])).unwrap();
+ assert_eq!(json[0]["ik"][0]["bone"], "shin");
+ assert!(json[0]["poses"][0]["solved"]["thigh"].is_number());
+ std::fs::remove_dir_all(&dir).unwrap();
+}
diff --git a/crates/core/src/bundle.rs b/crates/core/src/bundle.rs
index d16aad5..92f601b 100644
--- a/crates/core/src/bundle.rs
+++ b/crates/core/src/bundle.rs
@@ -524,6 +524,7 @@ pub fn summarize(ops: &[Op]) -> String {
Op::Foliage(spec) => format!("foliage on {}", spec.layer),
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::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 bfb21dd..edd70bd 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/1";
+pub const FORMAT: &str = "klad/2";
pub const MAX_SIZE: u32 = 16384;
pub const MASK: usize = usize::MAX;
@@ -147,6 +147,8 @@ pub struct Layer {
pub reference: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
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 = "BTreeMap::is_empty")]
pub keys: crate::keys::Keys,
}
@@ -521,6 +523,7 @@ impl Layer {
depth: None,
reference: false,
bones: Vec::new(),
+ ik: Vec::new(),
keys: BTreeMap::new(),
}
}
@@ -1225,6 +1228,13 @@ impl Document {
{
bail!("layer {}: depth {depth} must be 0 or more", layer.id);
}
+ if !layer.bones.is_empty() || !layer.ik.is_empty() {
+ if !matches!(layer.kind(), Kind::Paint | Kind::Group) {
+ bail!("layer {}: bones go on a paint layer or a group", layer.id);
+ }
+ 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))?;
+ }
check_cels(layer)
})
}
diff --git a/crates/core/src/migrate.rs b/crates/core/src/migrate.rs
index 6296e09..af265db 100644
--- a/crates/core/src/migrate.rs
+++ b/crates/core/src/migrate.rs
@@ -10,6 +10,11 @@ pub fn migrate(value: Value) -> Result<Value> {
.to_string();
match format.as_str() {
FORMAT => Ok(value),
+ "klad/1" => {
+ let mut value = value;
+ value["format"] = Value::from(FORMAT);
+ Ok(value)
+ }
old if old.starts_with("draw-anything/") => bail!(
"a drawing in the old .draw format ({old}); this klad opens {FORMAT} drawings (.klad) only and does not convert old ones"
),
@@ -28,7 +33,15 @@ mod tests {
let current = json!({"format": FORMAT, "rev": 1});
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("klad/1"), "{old}");
+ 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 mut moved = first.clone();
+ moved["format"] = json!(FORMAT);
+ assert_eq!(
+ migrate(first).unwrap(),
+ moved,
+ "a klad/1 drawing opens as it was, in the new format"
+ );
assert!(
migrate(json!({"format": "klad/7"}))
.unwrap_err()
diff --git a/crates/core/src/ops.rs b/crates/core/src/ops.rs
index 56d1b46..b073a06 100644
--- a/crates/core/src/ops.rs
+++ b/crates/core/src/ops.rs
@@ -149,6 +149,7 @@ pub enum Op {
Grass(GrassSpec),
PaintOver(PaintOverSpec),
Bone(BoneSpec),
+ Ik(IkSpec),
Weights(WeightsSpec),
Pose(PoseSpec),
Key(KeySpec),
@@ -646,6 +647,36 @@ pub struct BoneSpec {
pub tail: Option<[f32; 2]>,
#[serde(default)]
pub by: Option<[f32; 2]>,
+ #[serde(default)]
+ pub chain: Option<Vec<String>>,
+ #[serde(default)]
+ pub through: Option<Vec<[f32; 2]>>,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum BendSpec {
+ Clockwise,
+ Counterclockwise,
+ Flip,
+}
+
+#[derive(Clone, Debug, Default, PartialEq, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct IkSpec {
+ pub layer: String,
+ #[serde(default)]
+ pub add: Option<String>,
+ #[serde(default)]
+ pub set: Option<String>,
+ #[serde(default)]
+ pub rm: Option<String>,
+ #[serde(default)]
+ pub chain: Option<u8>,
+ #[serde(default)]
+ pub bend: Option<BendSpec>,
+ #[serde(default)]
+ pub softness: Option<f32>,
}
#[derive(Clone, Debug, PartialEq, Deserialize)]
@@ -682,6 +713,8 @@ pub struct PoseSpec {
#[serde(default)]
pub root: [f32; 2],
#[serde(default)]
+ pub ik: BTreeMap<String, crate::rig::Reach>,
+ #[serde(default)]
pub hold: Option<u32>,
#[serde(skip)]
pub resolved: Option<Vec<PosedCel>>,
@@ -1503,6 +1536,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)))?),
"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)))?),
@@ -1516,7 +1550,7 @@ impl Op {
},
other => {
bail!(
- "unknown op {other:?}: use add, set, rm, mv, stroke, fill, palette, transform, path, lasso, copy, timeline, frames, cel, clip, retime, inbetween, duplicate, ink, light, hatch, scatter or export"
+ "unknown op {other:?}: use add, set, rm, mv, stroke, fill, palette, transform, path, lasso, copy, timeline, frames, cel, clip, retime, inbetween, duplicate, ink, light, hatch, scatter, paint, foliage, grass, paintover, part, key, bone, ik, weights, pose or export"
)
}
};
@@ -1675,6 +1709,52 @@ fn bone(doc: &mut Document, spec: &BoneSpec, out: &mut Applied) -> Result<()> {
)
})
};
+ let before = bones.clone();
+ let mut ik = doc.layer_at(&path).ik.clone();
+ if let Some(names) = &spec.chain {
+ if spec.add.is_some()
+ || spec.rm.is_some()
+ || spec.rename.is_some()
+ || spec.moved.is_some()
+ || spec.reparent.is_some()
+ {
+ bail!("a bone op takes one of add, chain, rm, rename, move or reparent");
+ }
+ let Some(through) = &spec.through else {
+ bail!("a chain needs \"through\": its points, one more than its bones");
+ };
+ if names.is_empty() || through.len() != names.len() + 1 {
+ bail!(
+ "a chain of {} bones goes through {} points, not {}",
+ names.len(),
+ names.len() + 1,
+ through.len()
+ );
+ }
+ if let Some(p) = &spec.parent {
+ find(&bones, p)?;
+ }
+ names.iter().enumerate().try_for_each(|(i, name)| {
+ if bones.iter().any(|b| &b.name == name) {
+ bail!("there is already a bone {name} on {}", spec.layer);
+ }
+ bones.push(crate::rig::Bone {
+ name: name.clone(),
+ parent: match i {
+ 0 => spec.parent.clone(),
+ _ => Some(names[i - 1].clone()),
+ },
+ head: through[i],
+ tail: through[i + 1],
+ });
+ Ok(())
+ })?;
+ out.notes.push(format!("chain {} on {}", names.join(", "), spec.layer));
+ crate::rig::check(&bones)?;
+ doc.layer_at_mut(&path).bones = bones;
+ out.changed.push(id);
+ return Ok(());
+ }
match (&spec.add, &spec.rm, &spec.rename, &spec.moved, &spec.reparent) {
(Some(name), None, None, None, None) => {
let (Some(head), Some(tail)) = (spec.head, spec.tail) else {
@@ -1704,8 +1784,18 @@ fn bone(doc: &mut Document, spec: &BoneSpec, out: &mut Applied) -> Result<()> {
{
gone.push(next);
}
+ let held: Vec<String> = ik
+ .iter()
+ .filter(|c| gone.contains(&c.bone))
+ .map(|c| c.bone.clone())
+ .collect();
+ bake(doc, &path, &bones, &ik, &held);
+ ik.retain(|c| !held.contains(&c.bone));
bones.retain(|b| !gone.contains(&b.name));
- out.notes.push(format!("removed {}", gone.join(", ")));
+ out.notes.push(match held.is_empty() {
+ true => format!("removed {}", gone.join(", ")),
+ false => format!("removed {} and the IK on {}", gone.join(", "), held.join(", ")),
+ });
}
(None, None, Some(name), None, None) => {
let Some(to) = &spec.to_name else {
@@ -1720,6 +1810,9 @@ fn bone(doc: &mut Document, spec: &BoneSpec, out: &mut Applied) -> Result<()> {
.iter_mut()
.filter(|b| b.parent.as_ref() == Some(name))
.for_each(|b| b.parent = Some(to.clone()));
+ 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);
rigged.iter().for_each(|p| {
if let Some(cels) = doc.layer_at_mut(p).cels_mut() {
@@ -1727,6 +1820,9 @@ fn bone(doc: &mut Document, spec: &BoneSpec, out: &mut Applied) -> Result<()> {
if let Some(v) = pose.angles.remove(name) {
pose.angles.insert(to.clone(), v);
}
+ if let Some(r) = pose.ik.remove(name) {
+ pose.ik.insert(to.clone(), r);
+ }
});
}
});
@@ -1760,10 +1856,166 @@ fn bone(doc: &mut Document, spec: &BoneSpec, out: &mut Applied) -> Result<()> {
}
bones = sorted;
}
- _ => bail!("a bone op takes one of add, rm, rename, move or reparent"),
+ _ => bail!("a bone op takes one of add, chain, rm, rename, move or reparent"),
}
crate::rig::check(&bones)?;
- doc.layer_at_mut(&path).bones = bones;
+ let broken: Vec<String> = ik
+ .iter()
+ .filter(|c| crate::rig::check_ik(&bones, std::slice::from_ref(c)).is_err())
+ .map(|c| c.bone.clone())
+ .collect();
+ if !broken.is_empty() {
+ bake(doc, &path, &before, &ik, &broken);
+ ik.retain(|c| !broken.contains(&c.bone));
+ out.notes.push(format!(
+ "removed the IK on {}: its limb no longer has a parent to turn (its poses keep their look as turns)",
+ broken.join(", ")
+ ));
+ }
+ crate::rig::check_ik(&bones, &ik)?;
+ let layer = doc.layer_at_mut(&path);
+ layer.bones = bones;
+ layer.ik = ik;
+ out.changed.push(id);
+ Ok(())
+}
+
+fn bake(doc: &mut Document, path: &[usize], bones: &[crate::rig::Bone], ik: &[crate::rig::Ik], held: &[String]) {
+ if held.is_empty() {
+ return;
+ }
+ let driven: Vec<String> = ik
+ .iter()
+ .filter(|c| held.contains(&c.bone))
+ .flat_map(|c| {
+ let parent = bones
+ .iter()
+ .find(|b| b.name == c.bone)
+ .and_then(|b| b.parent.clone())
+ .filter(|_| c.chain == 2);
+ std::iter::once(c.bone.clone()).chain(parent)
+ })
+ .collect();
+ crate::doc::family_paths(doc, path).iter().for_each(|p| {
+ if let Some(cels) = doc.layer_at_mut(p).cels_mut() {
+ cels.iter_mut()
+ .filter_map(|c| c.pose.as_mut())
+ .filter(|pose| held.iter().any(|h| pose.ik.contains_key(h)))
+ .for_each(|pose| {
+ let solved = crate::rig::applied(bones, ik, pose);
+ driven.iter().for_each(|b| {
+ if let Some(v) = solved.get(b) {
+ pose.angles.insert(b.clone(), *v);
+ }
+ });
+ held.iter().for_each(|h| {
+ pose.ik.remove(h);
+ });
+ });
+ }
+ });
+}
+
+fn ik(doc: &mut Document, spec: &IkSpec, out: &mut Applied) -> Result<()> {
+ use crate::rig::{Bend, Ik};
+ let id = rig_owner(doc, &spec.layer)?.id.clone();
+ let path = layer_path(doc, &id)?;
+ let bones = doc.layer_at(&path).bones.clone();
+ let mut ik = doc.layer_at(&path).ik.clone();
+ let has = |name: &str| -> Result<()> {
+ match bones.iter().any(|b| b.name == name) {
+ true => Ok(()),
+ false => bail!(
+ "no bone {name} on {}: {}",
+ spec.layer,
+ bones.iter().map(|b| b.name.as_str()).collect::<Vec<_>>().join(", ")
+ ),
+ }
+ };
+ let find = |ik: &[Ik], name: &str| -> Result<usize> {
+ ik.iter().position(|c| c.bone == name).ok_or_else(|| {
+ anyhow!(
+ "no IK on {name}: {}",
+ match ik.is_empty() {
+ true => "add one with klad ik --add".to_string(),
+ false => format!(
+ "the IKs end on {}",
+ ik.iter().map(|c| c.bone.as_str()).collect::<Vec<_>>().join(", ")
+ ),
+ }
+ )
+ })
+ };
+ let bend = |was: Bend, rest: Bend| match spec.bend {
+ None => was,
+ Some(BendSpec::Clockwise) => Bend::Clockwise,
+ Some(BendSpec::Counterclockwise) => Bend::Counterclockwise,
+ Some(BendSpec::Flip) => match spec.add.is_some() {
+ true => rest.flipped(),
+ false => was.flipped(),
+ },
+ };
+ let said = |c: &Ik| {
+ let parent = bones.iter().find(|b| b.name == c.bone).and_then(|b| b.parent.clone());
+ match (c.chain, parent) {
+ (2, Some(p)) => format!(
+ "IK on {}: a limb with {p}, bending {}{}",
+ c.bone,
+ match c.bend {
+ Bend::Clockwise => "clockwise",
+ Bend::Counterclockwise => "counterclockwise",
+ },
+ match c.softness > 0.0 {
+ true => format!(", softness {} px", c.softness),
+ false => String::new(),
+ }
+ ),
+ _ => format!("IK on {}: an aim", c.bone),
+ }
+ };
+ match (&spec.add, &spec.set, &spec.rm) {
+ (Some(name), None, None) => {
+ has(name)?;
+ if ik.iter().any(|c| &c.bone == name) {
+ bail!("{name} has an IK already: change it with set");
+ }
+ let parent = bones.iter().find(|b| &b.name == name).and_then(|b| b.parent.clone());
+ let rest = crate::rig::rest_bend(&bones, name);
+ let made = Ik {
+ bone: name.clone(),
+ chain: spec.chain.unwrap_or(if parent.is_some() { 2 } else { 1 }),
+ bend: bend(rest, rest),
+ softness: spec.softness.unwrap_or(0.0),
+ };
+ out.notes.push(said(&made));
+ ik.push(made);
+ }
+ (None, Some(name), None) => {
+ let at = find(&ik, name)?;
+ if spec.chain.is_none() && spec.bend.is_none() && spec.softness.is_none() {
+ bail!("say what to set: chain, bend or softness");
+ }
+ let rest = crate::rig::rest_bend(&bones, name);
+ let c = &mut ik[at];
+ c.chain = spec.chain.unwrap_or(c.chain);
+ c.bend = bend(c.bend, rest);
+ c.softness = spec.softness.unwrap_or(c.softness);
+ out.notes.push(said(c));
+ }
+ (None, None, Some(name)) => {
+ find(&ik, name)?;
+ if spec.chain.is_some() || spec.bend.is_some() || spec.softness.is_some() {
+ bail!("rm takes no chain, bend or softness");
+ }
+ bake(doc, &path, &bones, &ik, std::slice::from_ref(name));
+ ik.retain(|c| &c.bone != name);
+ out.notes
+ .push(format!("removed the IK on {name}; its poses keep their look as turns"));
+ }
+ _ => bail!("an ik op takes one of add, set or rm"),
+ }
+ crate::rig::check_ik(&bones, &ik)?;
+ doc.layer_at_mut(&path).ik = ik;
out.changed.push(id);
Ok(())
}
@@ -3020,6 +3272,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::Key(spec) => key(doc, spec, out)?,
Op::Weights(spec) => {
let Some(made) = &spec.resolved else {
@@ -3194,6 +3447,129 @@ mod tests {
doc
}
+ #[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, applied_ops) = apply_all(
+ &doc,
+ &ops(&[json!({"op":"bone","layer":ink,"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();
+ assert_eq!(
+ bones.iter().map(|b| b.name.as_str()).collect::<Vec<_>>(),
+ ["thigh", "shin", "foot"]
+ );
+ assert_eq!(bones[0].parent, None);
+ assert_eq!(bones[1].parent.as_deref(), Some("thigh"));
+ assert_eq!(bones[2].parent.as_deref(), Some("shin"));
+ assert!(
+ bones.windows(2).all(|w| w[1].head == w[0].tail),
+ "each starts where the one before ends"
+ );
+ let short = apply_all(
+ &doc,
+ &ops(&[json!({"op":"bone","layer":ink,"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();
+ assert_eq!(
+ doc.layer(&ink).unwrap().ik,
+ [Ik {
+ bone: "shin".into(),
+ chain: 2,
+ bend: Bend::Clockwise,
+ softness: 0.0
+ }],
+ "a limb by default, bending as drawn: the shin turns clockwise off the thigh"
+ );
+ assert!(
+ made.notes.iter().any(|n| n.contains("a limb with thigh")),
+ "{:?}",
+ made.notes
+ );
+ let (doc, _) = apply_all(
+ &doc,
+ &ops(&[json!({"op":"ik","layer":ink,"set":"shin","bend":"flip","softness":6})]),
+ )
+ .unwrap();
+ let ik = doc.layer(&ink).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"})]));
+ assert!(format!("{:#}", again.map(|_| ()).unwrap_err()).contains("has an IK already"));
+ let mut doc = doc;
+ let path = layer_path(&doc, &ink).unwrap();
+ let pose = Pose {
+ rest: "c0".into(),
+ angles: BTreeMap::from([("thigh".to_string(), 10.0)]),
+ ik: BTreeMap::from([(
+ "shin".to_string(),
+ Reach {
+ target: [160.0, 250.0],
+ mix: 1.0,
+ },
+ )]),
+ ..Pose::default()
+ };
+ doc.layer_at_mut(&path).cels_mut().unwrap()[0].pose = Some(pose.clone());
+ let looked = tips(&bones, &ik, &pose);
+ let (doc, _) = apply_all(
+ &doc,
+ &ops(&[json!({"op":"bone","layer":ink,"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 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();
+ assert!(gone.notes.iter().any(|n| n.contains("keep their look")));
+ let layer = doc.layer(&ink).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!(
+ now.iter()
+ .zip(&looked)
+ .all(|(a, b)| (a.1[0] - b.1[0]).abs() < 1e-3 && (a.1[1] - b.1[1]).abs() < 1e-3),
+ "the pose looks as it did, now as turns: {now:?} {looked:?}"
+ );
+ let (doc, _) = apply_all(
+ &doc,
+ &ops(&[
+ json!({"op":"ik","layer":ink,"add":"foot","chain":2}),
+ json!({"op":"bone","layer":ink,"reparent":"foot"}),
+ ]),
+ )
+ .unwrap();
+ assert!(
+ doc.layer(&ink).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"}),
+ ]),
+ )
+ .unwrap();
+ let layer = doc.layer(&ink).unwrap();
+ assert!(
+ layer.ik.is_empty() && layer.bones.len() == 1,
+ "removing a bone takes its children and their IK"
+ );
+ let solved = applied(&layer.bones, &layer.ik, &baked);
+ assert_eq!(solved["thigh"], baked.angles["thigh"]);
+ }
+
#[test]
fn layers_and_nodes_get_ids_and_land_where_asked() {
let doc = base();
diff --git a/crates/core/src/patch.rs b/crates/core/src/patch.rs
index a03af05..ee62691 100644
--- a/crates/core/src/patch.rs
+++ b/crates/core/src/patch.rs
@@ -127,6 +127,7 @@ fn layer_shell(layer: &Layer) -> Layer {
depth: layer.depth,
reference: layer.reference,
bones: layer.bones.clone(),
+ ik: layer.ik.clone(),
keys: layer.keys.clone(),
}
}
diff --git a/crates/core/src/rig.rs b/crates/core/src/rig.rs
index 3f8e130..b6e4f55 100644
--- a/crates/core/src/rig.rs
+++ b/crates/core/src/rig.rs
@@ -25,17 +25,85 @@ impl Bone {
}
pub fn length(&self) -> f32 {
- (self.tail[0] - self.head[0]).hypot(self.tail[1] - self.head[1])
+ libm::hypotf(self.tail[0] - self.head[0], self.tail[1] - self.head[1])
}
fn distance(&self, p: [f32; 2]) -> f32 {
let (a, b) = (self.head, self.tail);
let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
let t = (((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / (dx * dx + dy * dy).max(1e-6)).clamp(0.0, 1.0);
- (a[0] + dx * t - p[0]).hypot(a[1] + dy * t - p[1])
+ libm::hypotf(a[0] + dx * t - p[0], a[1] + dy * t - p[1])
}
}
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum Bend {
+ #[default]
+ Clockwise,
+ Counterclockwise,
+}
+
+impl Bend {
+ pub fn flipped(self) -> Bend {
+ match self {
+ Bend::Clockwise => Bend::Counterclockwise,
+ Bend::Counterclockwise => Bend::Clockwise,
+ }
+ }
+
+ fn sign(self) -> f64 {
+ match self {
+ Bend::Clockwise => 1.0,
+ Bend::Counterclockwise => -1.0,
+ }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct Ik {
+ pub bone: String,
+ #[serde(default = "limb", skip_serializing_if = "is_limb")]
+ pub chain: u8,
+ #[serde(default, skip_serializing_if = "is_clockwise")]
+ pub bend: Bend,
+ #[serde(default, skip_serializing_if = "is_zero")]
+ pub softness: f32,
+}
+
+fn limb() -> u8 {
+ 2
+}
+
+fn is_limb(n: &u8) -> bool {
+ *n == 2
+}
+
+fn is_clockwise(b: &Bend) -> bool {
+ *b == Bend::Clockwise
+}
+
+fn is_zero(v: &f32) -> bool {
+ *v == 0.0
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct Reach {
+ pub target: [f32; 2],
+ #[serde(default = "full", skip_serializing_if = "is_full")]
+ pub mix: f32,
+}
+
+fn full() -> f32 {
+ 1.0
+}
+
+fn is_full(v: &f32) -> bool {
+ *v == 1.0
+}
+
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Pose {
@@ -44,32 +112,64 @@ pub struct Pose {
pub angles: BTreeMap<String, f32>,
#[serde(default, skip_serializing_if = "is_origin")]
pub root: [f32; 2],
+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
+ pub ik: BTreeMap<String, Reach>,
}
fn is_origin(p: &[f32; 2]) -> bool {
p[0] == 0.0 && p[1] == 0.0
}
-impl Pose {
- pub fn mix(&self, other: &Pose, t: f32) -> Pose {
- let names: std::collections::BTreeSet<&String> = self.angles.keys().chain(other.angles.keys()).collect();
- Pose {
- rest: self.rest.clone(),
- angles: names
- .into_iter()
- .map(|n| {
- let (a, b) = (
- self.angles.get(n).copied().unwrap_or(0.0),
- other.angles.get(n).copied().unwrap_or(0.0),
- );
- (n.clone(), a + (b - a) * t)
- })
- .collect(),
- root: [
- self.root[0] + (other.root[0] - self.root[0]) * t,
- self.root[1] + (other.root[1] - self.root[1]) * t,
- ],
- }
+pub fn between(bones: &[Bone], ik: &[Ik], a: &Pose, b: &Pose, t: f32) -> Pose {
+ let lerp = |x: f32, y: f32| x + (y - x) * t;
+ let names: std::collections::BTreeSet<&String> = a.angles.keys().chain(b.angles.keys()).collect();
+ let end = |pose: &Pose, bone: &str| {
+ bones
+ .iter()
+ .position(|o| o.name == bone)
+ .map_or([0.0, 0.0], |i| tips(bones, ik, pose)[i].1)
+ };
+ let reaches = ik
+ .iter()
+ .filter_map(|c| {
+ let (x, y) = match (a.ik.get(&c.bone), b.ik.get(&c.bone)) {
+ (None, None) => return None,
+ (Some(x), Some(y)) => (x.clone(), y.clone()),
+ (Some(x), None) => (
+ x.clone(),
+ Reach {
+ target: end(b, &c.bone),
+ mix: 0.0,
+ },
+ ),
+ (None, Some(y)) => (
+ Reach {
+ target: end(a, &c.bone),
+ mix: 0.0,
+ },
+ y.clone(),
+ ),
+ };
+ Some((
+ c.bone.clone(),
+ Reach {
+ target: [lerp(x.target[0], y.target[0]), lerp(x.target[1], y.target[1])],
+ mix: lerp(x.mix, y.mix),
+ },
+ ))
+ })
+ .collect();
+ Pose {
+ rest: a.rest.clone(),
+ angles: names
+ .into_iter()
+ .map(|n| {
+ let at = |p: &Pose| p.angles.get(n).copied().unwrap_or(0.0);
+ (n.clone(), lerp(at(a), at(b)))
+ })
+ .collect(),
+ root: [lerp(a.root[0], b.root[0]), lerp(a.root[1], b.root[1])],
+ ik: reaches,
}
}
@@ -93,6 +193,58 @@ pub fn check(bones: &[Bone]) -> Result<()> {
})
}
+pub fn check_ik(bones: &[Bone], ik: &[Ik]) -> Result<()> {
+ ik.iter().enumerate().try_for_each(|(i, c)| {
+ let Some(at) = bones.iter().position(|b| b.name == c.bone) else {
+ bail!("IK on {}: there is no bone {}", c.bone, c.bone);
+ };
+ if ik[..i].iter().any(|o| o.bone == c.bone) {
+ bail!("two IKs end on {}", c.bone);
+ }
+ match c.chain {
+ 1 => {}
+ 2 => {
+ let Some(p) = parent_of(bones, at) else {
+ bail!(
+ "IK on {}: a limb (chain 2) turns the bone and its parent, and {} has none: make it an aim (chain 1)",
+ c.bone,
+ c.bone
+ );
+ };
+ let (h, q) = (bones[at].head, bones[p].head);
+ if libm::hypotf(h[0] - q[0], h[1] - q[1]) < 1e-3 {
+ bail!(
+ "IK on {}: it starts where its parent {} starts, so turning {} cannot carry it to a target: make it an aim (chain 1)",
+ c.bone,
+ bones[p].name,
+ bones[p].name
+ );
+ }
+ }
+ n => bail!("IK on {}: chain is 1 (an aim) or 2 (a limb), not {n}", c.bone),
+ }
+ if !(c.softness.is_finite() && c.softness >= 0.0) {
+ bail!("IK on {}: softness is a distance in px, 0 or more", c.bone);
+ }
+ Ok(())
+ })
+}
+
+pub fn rest_bend(bones: &[Bone], bone: &str) -> Bend {
+ let Some(at) = bones.iter().position(|b| b.name == bone) else {
+ return Bend::Clockwise;
+ };
+ let Some(p) = parent_of(bones, at) else {
+ return Bend::Clockwise;
+ };
+ let (b, a) = (&bones[at], &bones[p]);
+ let along = libm::atan2((b.head[1] - a.head[1]) as f64, (b.head[0] - a.head[0]) as f64);
+ match wrap(rest_angle(b) - along) < -RAD {
+ true => Bend::Counterclockwise,
+ false => Bend::Clockwise,
+ }
+}
+
pub fn subtree(bones: &[Bone], name: &str) -> Vec<String> {
let mut found = vec![name.to_string()];
bones.iter().for_each(|b| {
@@ -174,15 +326,181 @@ fn apply(m: Mat, p: [f32; 2]) -> [f32; 2] {
[m[0] * p[0] + m[2] * p[1] + m[4], m[1] * p[0] + m[3] * p[1] + m[5]]
}
-pub fn skinning(bones: &[Bone], pose: &Pose) -> Vec<Mat> {
+fn parent_of(bones: &[Bone], i: usize) -> Option<usize> {
+ let p = bones[i].parent.as_ref()?;
+ bones[..i].iter().position(|o| &o.name == p)
+}
+
+const RAD: f64 = std::f64::consts::PI / 180.0;
+const NEAR: f64 = 1e-4;
+
+fn rest_angle(b: &Bone) -> f64 {
+ libm::atan2((b.tail[1] - b.head[1]) as f64, (b.tail[0] - b.head[0]) as f64)
+}
+
+fn wrap(a: f64) -> f64 {
+ (a + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI
+}
+
+struct Frame {
+ head: [f64; 2],
+ turn: f64,
+}
+
+fn frames(bones: &[Bone], turns: &[f64], root: [f32; 2]) -> Vec<Frame> {
+ let mut out: Vec<Frame> = Vec::with_capacity(bones.len());
+ bones.iter().enumerate().for_each(|(i, b)| {
+ let frame = match parent_of(bones, i) {
+ Some(p) => {
+ let (dx, dy) = (
+ (b.head[0] - bones[p].head[0]) as f64,
+ (b.head[1] - bones[p].head[1]) as f64,
+ );
+ let (s, c) = (libm::sin(out[p].turn), libm::cos(out[p].turn));
+ Frame {
+ head: [out[p].head[0] + c * dx - s * dy, out[p].head[1] + s * dx + c * dy],
+ turn: out[p].turn + turns[i],
+ }
+ }
+ None => Frame {
+ head: [(b.head[0] + root[0]) as f64, (b.head[1] + root[1]) as f64],
+ turn: turns[i],
+ },
+ };
+ out.push(frame);
+ });
+ out
+}
+
+fn soft(d: f64, reach: f64, softness: f64) -> f64 {
+ match softness > 0.0 {
+ false => d,
+ true if d <= reach - softness => d,
+ true if d >= reach + softness => reach,
+ true => {
+ let over = d - reach + softness;
+ d - over * over / (4.0 * softness)
+ }
+ }
+}
+
+fn aim(bones: &[Bone], end: usize, world: &[Frame], target: [f64; 2]) -> Vec<(usize, f64)> {
+ let head = world[end].head;
+ let (vx, vy) = (target[0] - head[0], target[1] - head[1]);
+ if libm::hypot(vx, vy) < NEAR {
+ return Vec::new();
+ }
+ let above = parent_of(bones, end).map_or(0.0, |p| world[p].turn);
+ vec![(end, libm::atan2(vy, vx) - rest_angle(&bones[end]) - above)]
+}
+
+fn solve(bones: &[Bone], c: &Ik, end: usize, world: &[Frame], target: [f64; 2]) -> Vec<(usize, f64)> {
+ let Some(a) = parent_of(bones, end).filter(|_| c.chain == 2) else {
+ return aim(bones, end, world, target);
+ };
+ let (upper, lower) = (&bones[a], &bones[end]);
+ let (jx, jy) = (
+ (lower.head[0] - upper.head[0]) as f64,
+ (lower.head[1] - upper.head[1]) as f64,
+ );
+ let l1 = libm::hypot(jx, jy);
+ if l1 < NEAR {
+ return aim(bones, end, world, target);
+ }
+ let along = libm::atan2(jy, jx);
+ let l2 = libm::hypot(
+ (lower.tail[0] - lower.head[0]) as f64,
+ (lower.tail[1] - lower.head[1]) as f64,
+ );
+ let s = world[a].head;
+ let (dx, dy) = (target[0] - s[0], target[1] - s[1]);
+ let d = libm::hypot(dx, dy);
+ let u = match d < NEAR {
+ true => {
+ let fk = along + world[a].turn;
+ [libm::cos(fk), libm::sin(fk)]
+ }
+ false => [dx / d, dy / d],
+ };
+ let n = [-u[1], u[0]];
+ let reach = l1 + l2;
+ let r = soft(d, reach, c.softness as f64).clamp((l1 - l2).abs().max(NEAR), reach);
+ let a_len = (r * r + l1 * l1 - l2 * l2) / (2.0 * r);
+ let h = (l1 * l1 - a_len * a_len).max(0.0).sqrt();
+ let sign = c.bend.sign();
+ let elbow = [
+ s[0] + a_len * u[0] - sign * h * n[0],
+ s[1] + a_len * u[1] - sign * h * n[1],
+ ];
+ let tip = [s[0] + r * u[0], s[1] + r * u[1]];
+ let first = libm::atan2(elbow[1] - s[1], elbow[0] - s[0]);
+ let second = libm::atan2(tip[1] - elbow[1], tip[0] - elbow[0]);
+ let above = parent_of(bones, a).map_or(0.0, |p| world[p].turn);
+ vec![
+ (a, first - along - above),
+ (end, second - first - (rest_angle(lower) - along)),
+ ]
+}
+
+fn order<'a>(bones: &[Bone], ik: &'a [Ik]) -> Vec<(usize, &'a Ik)> {
+ let mut found: Vec<(usize, usize, &Ik)> = ik
+ .iter()
+ .filter_map(|c| {
+ let end = bones.iter().position(|b| b.name == c.bone)?;
+ let top = match c.chain {
+ 2 => parent_of(bones, end).unwrap_or(end),
+ _ => end,
+ };
+ Some((top, end, c))
+ })
+ .collect();
+ found.sort_by_key(|(top, end, _)| (*top, *end));
+ found.into_iter().map(|(_, end, c)| (end, c)).collect()
+}
+
+pub fn applied(bones: &[Bone], ik: &[Ik], pose: &Pose) -> BTreeMap<String, f32> {
+ let mut angles = pose.angles.clone();
+ if pose.ik.is_empty() || ik.is_empty() {
+ return angles;
+ }
+ let mut turns: Vec<f64> = bones
+ .iter()
+ .map(|b| angles.get(&b.name).map_or(0.0, |a| *a as f64 * RAD))
+ .collect();
+ let mut touched = std::collections::BTreeSet::new();
+ order(bones, ik).into_iter().for_each(|(end, c)| {
+ let Some(reach) = pose.ik.get(&c.bone) else {
+ return;
+ };
+ let mix = if reach.mix.is_finite() {
+ reach.mix.clamp(0.0, 1.0) as f64
+ } else {
+ 0.0
+ };
+ let target = [reach.target[0] as f64, reach.target[1] as f64];
+ if mix <= 0.0 || !target.iter().all(|v| v.is_finite()) {
+ return;
+ }
+ let world = frames(bones, &turns, pose.root);
+ solve(bones, c, end, &world, target).into_iter().for_each(|(i, turn)| {
+ turns[i] += mix * wrap(turn - turns[i]);
+ touched.insert(i);
+ });
+ });
+ touched.into_iter().for_each(|i| {
+ angles.insert(bones[i].name.clone(), (turns[i] / RAD) as f32);
+ });
+ angles
+}
+
+pub fn skinning(bones: &[Bone], ik: &[Ik], pose: &Pose) -> Vec<Mat> {
+ let angles = applied(bones, ik, pose);
let rest: Vec<Mat> = bones.iter().map(|b| placed(b.head, b.angle())).collect();
let mut posed: Vec<Mat> = Vec::with_capacity(bones.len());
bones.iter().enumerate().for_each(|(i, b)| {
- let turn = placed(
- [0.0, 0.0],
- pose.angles.get(&b.name).copied().unwrap_or(0.0).to_radians(),
- );
- let world = match b.parent.as_ref().and_then(|p| bones.iter().position(|o| &o.name == p)) {
+ let degrees = angles.get(&b.name).copied().unwrap_or(0.0);
+ let turn = placed([0.0, 0.0], degrees * (std::f32::consts::PI / 180.0));
+ let world = match parent_of(bones, i) {
Some(p) => mul(posed[p], mul(mul(invert(rest[p]), rest[i]), turn)),
None => mul([1.0, 0.0, 0.0, 1.0, pose.root[0], pose.root[1]], mul(rest[i], turn)),
};
@@ -191,8 +509,8 @@ pub fn skinning(bones: &[Bone], pose: &Pose) -> Vec<Mat> {
posed.iter().zip(&rest).map(|(p, r)| mul(*p, invert(*r))).collect()
}
-pub fn tips(bones: &[Bone], pose: &Pose) -> Vec<([f32; 2], [f32; 2])> {
- let mats = skinning(bones, pose);
+pub fn tips(bones: &[Bone], ik: &[Ik], pose: &Pose) -> Vec<([f32; 2], [f32; 2])> {
+ let mats = skinning(bones, ik, pose);
bones
.iter()
.zip(&mats)
@@ -368,11 +686,11 @@ pub struct Rig<'a> {
}
impl<'a> Rig<'a> {
- pub fn new(bones: &'a [Bone], weights: &'a Weights, pose: &Pose) -> Self {
+ pub fn new(bones: &'a [Bone], ik: &[Ik], weights: &'a Weights, pose: &Pose) -> Self {
Self {
bones,
weights,
- mats: skinning(bones, pose),
+ mats: skinning(bones, ik, pose),
}
}
@@ -623,6 +941,8 @@ mod tests {
use super::*;
use crate::stroke::Stroke;
+ const GOLDEN: [u32; 3] = [1101004800, 3257723871, 1097306278];
+
fn leg() -> Vec<Bone> {
vec![
Bone {
@@ -640,6 +960,332 @@ mod tests {
]
}
+ fn bone(name: &str, parent: Option<&str>, head: [f32; 2], tail: [f32; 2]) -> Bone {
+ Bone {
+ name: name.into(),
+ parent: parent.map(str::to_string),
+ head,
+ tail,
+ }
+ }
+
+ fn limb_on(bone: &str, bend: Bend, softness: f32) -> Ik {
+ Ik {
+ bone: bone.into(),
+ chain: 2,
+ bend,
+ softness,
+ }
+ }
+
+ fn reaching(targets: &[(&str, [f32; 2], f32)]) -> Pose {
+ Pose {
+ ik: targets
+ .iter()
+ .map(|(b, t, m)| (b.to_string(), Reach { target: *t, mix: *m }))
+ .collect(),
+ ..Pose::default()
+ }
+ }
+
+ fn end_of(bones: &[Bone], ik: &[Ik], pose: &Pose, name: &str) -> [f32; 2] {
+ let i = bones.iter().position(|b| b.name == name).unwrap();
+ tips(bones, ik, pose)[i].1
+ }
+
+ fn apart(a: [f32; 2], b: [f32; 2]) -> f32 {
+ (a[0] - b[0]).hypot(a[1] - b[1])
+ }
+
+ fn cross(o: [f32; 2], a: [f32; 2], b: [f32; 2]) -> f32 {
+ (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
+ }
+
+ #[test]
+ fn a_limb_reaches_its_target_with_an_offset_joint_a_turned_parent_and_a_root_move() {
+ let bones = vec![
+ bone("pelvis", None, [200.0, 100.0], [200.0, 150.0]),
+ bone("thigh", Some("pelvis"), [215.0, 155.0], [220.0, 255.0]),
+ bone("shin", Some("thigh"), [222.0, 258.0], [230.0, 360.0]),
+ ];
+ let target = [300.0, 330.0];
+ [Bend::Clockwise, Bend::Counterclockwise].into_iter().for_each(|bend| {
+ let ik = vec![limb_on("shin", bend, 0.0)];
+ let mut pose = reaching(&[("shin", target, 1.0)]);
+ pose.angles.insert("pelvis".into(), 20.0);
+ pose.root = [15.0, -10.0];
+ let shown = tips(&bones, &ik, &pose);
+ assert!(apart(shown[2].1, target) < 0.01, "{bend:?}: {:?}", shown[2].1);
+ let side = cross(shown[1].0, target, shown[2].0);
+ match bend {
+ Bend::Clockwise => assert!(side < 0.0, "a clockwise knee sits on its side: {side}"),
+ Bend::Counterclockwise => assert!(side > 0.0, "a counterclockwise knee sits on the other: {side}"),
+ }
+ let fk = tips(&bones, &[], &pose);
+ assert_eq!(shown[0], fk[0], "the pelvis is not part of the limb");
+ });
+ }
+
+ #[test]
+ fn out_of_reach_the_limb_points_straight_at_the_target_and_too_close_it_folds() {
+ let bones = vec![
+ bone("thigh", None, [100.0, 100.0], [100.0, 200.0]),
+ bone("shin", Some("thigh"), [100.0, 200.0], [100.0, 260.0]),
+ ];
+ let ik = vec![limb_on("shin", Bend::Clockwise, 0.0)];
+ let far = end_of(&bones, &ik, &reaching(&[("shin", [500.0, 100.0], 1.0)]), "shin");
+ assert!(apart(far, [260.0, 100.0]) < 0.01, "straight at full reach: {far:?}");
+ let near = end_of(&bones, &ik, &reaching(&[("shin", [110.0, 100.0], 1.0)]), "shin");
+ assert!(apart(near, [140.0, 100.0]) < 0.01, "folded as far as it goes: {near:?}");
+ let on = tips(&bones, &ik, &reaching(&[("shin", [100.0, 100.0], 1.0)]));
+ assert!(on.iter().all(|(h, t)| h.iter().chain(t).all(|v| v.is_finite())));
+ let aim = vec![Ik {
+ bone: "shin".into(),
+ chain: 1,
+ bend: Bend::Clockwise,
+ softness: 0.0,
+ }];
+ let pointed = end_of(&bones, &aim, &reaching(&[("shin", [400.0, 200.0], 1.0)]), "shin");
+ assert!(
+ apart(pointed, [160.0, 200.0]) < 0.01,
+ "an aim turns the bone alone: {pointed:?}"
+ );
+ let still = tips(&bones, &aim, &reaching(&[("shin", [100.0, 200.0], 1.0)]));
+ assert_eq!(
+ still,
+ tips(&bones, &[], &Pose::default()),
+ "a target on its head keeps the turn"
+ );
+ }
+
+ #[test]
+ fn softness_eases_the_limb_into_full_reach() {
+ let bones = vec![
+ bone("thigh", None, [0.0, 0.0], [0.0, 100.0]),
+ bone("shin", Some("thigh"), [0.0, 100.0], [0.0, 200.0]),
+ ];
+ let sweep = |softness: f32| -> (Vec<f32>, Vec<f32>) {
+ let ik = vec![limb_on("shin", Bend::Clockwise, softness)];
+ (0..=240)
+ .map(|i| {
+ let d = 140.0 + i as f32 * 0.5;
+ let pose = reaching(&[("shin", [0.0, d], 1.0)]);
+ let reach = end_of(&bones, &ik, &pose, "shin")[1];
+ (reach, applied(&bones, &ik, &pose)["thigh"])
+ })
+ .unzip()
+ };
+ let (hard, hard_turn) = sweep(0.0);
+ let (soft, soft_turn) = sweep(20.0);
+ assert!(soft.windows(2).all(|w| w[1] >= w[0] - 1e-3), "it never pulls back");
+ assert!(
+ (soft[0] - 140.0).abs() < 0.01,
+ "reaches the target well inside full reach"
+ );
+ assert!(
+ (soft[240] - 200.0).abs() < 0.01,
+ "straight once the target is softness past full reach"
+ );
+ assert!(
+ (soft[120] - 195.0).abs() < 0.01 && hard[120] == 200.0,
+ "at full reach a soft limb is still a quarter of its softness short: {}",
+ soft[120]
+ );
+ let step = |turns: &[f32]| turns.windows(2).map(|w| (w[1] - w[0]).abs()).fold(0.0, f32::max);
+ assert!(
+ step(&hard_turn) > 2.0,
+ "without softness the knee snaps: {}",
+ step(&hard_turn)
+ );
+ assert!(step(&soft_turn) < 0.6, "with softness it eases: {}", step(&soft_turn));
+ }
+
+ #[test]
+ fn mix_blends_from_the_turns_to_the_target_the_short_way() {
+ let bones = vec![
+ bone("upper", None, [0.0, 0.0], [100.0, 0.0]),
+ bone("fore", Some("upper"), [100.0, 0.0], [200.0, 0.0]),
+ ];
+ let ik = vec![Ik {
+ bone: "fore".into(),
+ chain: 1,
+ bend: Bend::Clockwise,
+ softness: 0.0,
+ }];
+ let at = |mix: f32| {
+ let mut pose = reaching(&[("fore", [100.0, 100.0], mix)]);
+ pose.angles.insert("fore".into(), -170.0);
+ applied(&bones, &ik, &pose)["fore"]
+ };
+ let same = |a: f32, b: f32| ((a - b + 540.0).rem_euclid(360.0) - 180.0).abs() < 1e-3;
+ assert_eq!(at(0.0), -170.0, "mix 0 is the turns");
+ assert!(same(at(1.0), 90.0), "{}", at(1.0));
+ assert!(
+ same(at(0.5), 140.0) && (at(0.5) + 170.0).abs() < 90.0,
+ "half way the short way round, through 180: {}",
+ at(0.5)
+ );
+ }
+
+ #[test]
+ fn constraints_are_solved_parent_first_whatever_their_order() {
+ let bones = vec![
+ bone("thigh", None, [0.0, 0.0], [0.0, 100.0]),
+ bone("shin", Some("thigh"), [0.0, 100.0], [0.0, 200.0]),
+ bone("foot", Some("shin"), [0.0, 200.0], [30.0, 200.0]),
+ ];
+ let ik = vec![
+ Ik {
+ bone: "foot".into(),
+ chain: 1,
+ bend: Bend::Clockwise,
+ softness: 0.0,
+ },
+ limb_on("shin", Bend::Clockwise, 0.0),
+ ];
+ let pose = reaching(&[("shin", [60.0, 150.0], 1.0), ("foot", [200.0, 150.0], 1.0)]);
+ let shown = tips(&bones, &ik, &pose);
+ assert!(
+ apart(shown[1].1, [60.0, 150.0]) < 0.01,
+ "the leg reaches: {:?}",
+ shown[1].1
+ );
+ let (h, t) = shown[2];
+ let pointing = libm::atan2f(t[1] - h[1], t[0] - h[0]);
+ let wanted = libm::atan2f(150.0 - h[1], 200.0 - h[0]);
+ assert!(
+ (pointing - wanted).abs() < 1e-4,
+ "the foot aims from where the leg put it"
+ );
+ }
+
+ #[test]
+ fn in_betweens_mix_the_targets_so_a_planted_foot_stays_planted() {
+ let bones = vec![
+ bone("thigh", None, [0.0, 0.0], [0.0, 100.0]),
+ bone("shin", Some("thigh"), [0.0, 100.0], [0.0, 200.0]),
+ ];
+ let ik = vec![limb_on("shin", Bend::Clockwise, 0.0)];
+ let key = |x: f32| Pose {
+ root: [x, 0.0],
+ ..reaching(&[("shin", [0.0, 180.0], 1.0)])
+ };
+ let (a, b) = (key(-60.0), key(60.0));
+ (0..=10).map(|i| i as f32 / 10.0).for_each(|t| {
+ let foot = end_of(&bones, &ik, &between(&bones, &ik, &a, &b, t), "shin");
+ assert!(apart(foot, [0.0, 180.0]) < 1e-3, "t {t}: {foot:?}");
+ });
+ let turned = |p: &Pose| Pose {
+ angles: applied(&bones, &ik, p),
+ root: p.root,
+ ..Pose::default()
+ };
+ let slid = end_of(
+ &bones,
+ &[],
+ &between(&bones, &[], &turned(&a), &turned(&b), 0.5),
+ "shin",
+ );
+ assert!(
+ (slid[1] - 189.74).abs() < 0.05,
+ "mixing the solved turns instead pushes the foot through the floor: {slid:?}"
+ );
+ }
+
+ #[test]
+ fn a_limb_on_ik_in_one_key_only_hands_over_without_a_jump() {
+ let bones = vec![
+ bone("upper", None, [0.0, 0.0], [100.0, 0.0]),
+ bone("fore", Some("upper"), [100.0, 0.0], [200.0, 0.0]),
+ ];
+ let ik = vec![limb_on("fore", Bend::Clockwise, 0.0)];
+ let a = reaching(&[("fore", [120.0, 80.0], 1.0)]);
+ let mut b = Pose::default();
+ b.angles.insert("upper".into(), 60.0);
+ let at = |t: f32| end_of(&bones, &ik, &between(&bones, &ik, &a, &b, t), "fore");
+ assert!(apart(at(0.0), [120.0, 80.0]) < 0.01);
+ assert!(apart(at(1.0), end_of(&bones, &[], &b, "fore")) < 0.01);
+ let path: Vec<[f32; 2]> = (0..=20).map(|i| at(i as f32 / 20.0)).collect();
+ assert!(
+ path.windows(2).all(|w| apart(w[0], w[1]) < 25.0),
+ "no jump on the way: {path:?}"
+ );
+ }
+
+ #[test]
+ fn bad_constraints_are_refused_and_the_rest_bend_is_read_from_the_drawing() {
+ let bones = vec![
+ bone("thigh", None, [0.0, 0.0], [0.0, 100.0]),
+ bone("shin", Some("thigh"), [0.0, 100.0], [-30.0, 190.0]),
+ bone("spur", Some("thigh"), [0.0, 0.0], [20.0, 10.0]),
+ ];
+ let refused = |ik: Vec<Ik>| check_ik(&bones, &ik).unwrap_err().to_string();
+ assert!(refused(vec![limb_on("calf", Bend::Clockwise, 0.0)]).contains("no bone calf"));
+ assert!(refused(vec![limb_on("thigh", Bend::Clockwise, 0.0)]).contains("has none"));
+ assert!(refused(vec![limb_on("spur", Bend::Clockwise, 0.0)]).contains("starts where its parent"));
+ assert!(
+ refused(vec![Ik {
+ chain: 3,
+ ..limb_on("shin", Bend::Clockwise, 0.0)
+ }])
+ .contains("not 3")
+ );
+ assert!(refused(vec![limb_on("shin", Bend::Clockwise, -1.0)]).contains("softness"));
+ assert!(
+ refused(vec![
+ limb_on("shin", Bend::Clockwise, 0.0),
+ limb_on("shin", Bend::Counterclockwise, 0.0)
+ ])
+ .contains("two IKs")
+ );
+ assert!(check_ik(&bones, &[limb_on("shin", Bend::Clockwise, 4.0)]).is_ok());
+ assert_eq!(
+ rest_bend(&bones, "shin"),
+ Bend::Clockwise,
+ "the shin turns clockwise off the thigh"
+ );
+ let mirrored = vec![
+ bones[0].clone(),
+ bone("shin", Some("thigh"), [0.0, 100.0], [30.0, 190.0]),
+ ];
+ assert_eq!(rest_bend(&mirrored, "shin"), Bend::Counterclockwise);
+ let straight = vec![
+ bones[0].clone(),
+ bone("shin", Some("thigh"), [0.0, 100.0], [0.0, 200.0]),
+ ];
+ assert_eq!(rest_bend(&straight, "shin"), Bend::Clockwise);
+ let ik = vec![limb_on("shin", rest_bend(&bones, "shin"), 0.0)];
+ let rest_tip = end_of(&bones, &[], &Pose::default(), "shin");
+ let at_rest = tips(&bones, &ik, &reaching(&[("shin", rest_tip, 1.0)]));
+ assert!(
+ at_rest
+ .iter()
+ .zip(tips(&bones, &[], &Pose::default()))
+ .all(|(a, b)| apart(a.0, b.0) < 1e-3 && apart(a.1, b.1) < 1e-3),
+ "a target on the limb's end at rest moves nothing"
+ );
+ }
+
+ #[test]
+ fn the_solver_gives_the_same_numbers_everywhere() {
+ let bones = vec![
+ bone("pelvis", None, [200.0, 100.0], [200.0, 150.0]),
+ bone("thigh", Some("pelvis"), [215.0, 155.0], [220.0, 255.0]),
+ bone("shin", Some("thigh"), [222.0, 258.0], [230.0, 360.0]),
+ ];
+ let ik = vec![limb_on("shin", Bend::Clockwise, 6.0)];
+ let mut pose = reaching(&[("shin", [300.0, 330.0], 0.8)]);
+ pose.angles.insert("pelvis".into(), 20.0);
+ pose.angles.insert("thigh".into(), -12.5);
+ pose.root = [15.0, -10.0];
+ let solved = applied(&bones, &ik, &pose);
+ let bits: Vec<u32> = ["pelvis", "thigh", "shin"]
+ .iter()
+ .map(|b| solved[*b].to_bits())
+ .collect();
+ assert_eq!(bits, GOLDEN, "{solved:?}");
+ }
+
#[test]
fn a_moved_tail_takes_the_joined_children_along_and_by_moves_the_family() {
let mut bones = leg();
@@ -709,11 +1355,11 @@ mod tests {
let line: Mark = Stroke::new(1, "ink", [0.0, 0.0, 0.0, 1.0], 6.0, 1)
.with_points(&points, 8.0)
.into();
- let rest = Rig::new(&bones, &weights, &Pose::default());
+ let rest = Rig::new(&bones, &[], &weights, &Pose::default());
assert_eq!(rest.pose(std::slice::from_ref(&line), (200, 400)), vec![line.clone()]);
let mut bent = Pose::default();
bent.angles.insert("shin".into(), 60.0);
- let posed = Rig::new(&bones, &weights, &bent).pose(std::slice::from_ref(&line), (200, 400));
+ let posed = Rig::new(&bones, &[], &weights, &bent).pose(std::slice::from_ref(&line), (200, 400));
let pts: Vec<(f32, f32)> = posed[0].as_stroke().unwrap().samples.iter().map(|q| q.pos()).collect();
assert!((pts[0].0 - 100.0).abs() < 0.5 && (pts[0].1 - 100.0).abs() < 0.5);
let end = pts[pts.len() - 1];
@@ -746,7 +1392,7 @@ mod tests {
);
let mut swing = Pose::default();
swing.angles.insert("thigh".into(), 90.0);
- let moved = Rig::new(&bones, &rigid, &swing).pose(std::slice::from_ref(&line), (200, 400));
+ let moved = Rig::new(&bones, &[], &rigid, &swing).pose(std::slice::from_ref(&line), (200, 400));
let s = moved[0].as_stroke().unwrap();
let (a, b) = (s.samples[0].pos(), s.samples[s.samples.len() - 1].pos());
assert!(
diff --git a/crates/render/src/overlay.rs b/crates/render/src/overlay.rs
index fb44ba4..25e0a1b 100644
--- a/crates/render/src/overlay.rs
+++ b/crates/render/src/overlay.rs
@@ -120,6 +120,7 @@ pub struct Overlay {
pub frame: Option<u32>,
pub numbers: bool,
pub bones: Vec<Shown>,
+ pub targets: Vec<([f32; 2], [f32; 2])>,
pub heat: Option<Heat>,
}
@@ -175,6 +176,34 @@ fn draw_bones(
});
}
+fn draw_targets(canvas: &Canvas, targets: &[([f32; 2], [f32; 2])], to_out: impl Fn([f32; 2]) -> (f32, f32), px: f32) {
+ let pen = |rgb: [f32; 3], a: f32, width: f32| {
+ let mut paint = color(rgb, a);
+ paint.set_anti_alias(true);
+ paint.set_style(PaintStyle::Stroke);
+ paint.set_stroke_width(width);
+ paint
+ };
+ let hue = [1.0, 0.45, 0.2];
+ targets.iter().for_each(|(end, target)| {
+ let (e, t) = (to_out(*end), to_out(*target));
+ if (e.0 - t.0).hypot(e.1 - t.1) > 2.0 * px {
+ canvas.draw_line(e, t, &pen([0.0, 0.0, 0.0], 0.6, 3.0 * px));
+ canvas.draw_line(e, t, &pen(hue, 1.0, 1.2 * px));
+ }
+ [
+ (pen([0.0, 0.0, 0.0], 0.6, 3.5 * px), 7.0),
+ (pen(hue, 1.0, 1.5 * px), 7.0),
+ ]
+ .iter()
+ .for_each(|(paint, r)| {
+ canvas.draw_circle(t, r * px, paint);
+ canvas.draw_line((t.0 - r * 1.6 * px, t.1), (t.0 + r * 1.6 * px, t.1), paint);
+ canvas.draw_line((t.0, t.1 - r * 1.6 * px), (t.0, t.1 + r * 1.6 * px), paint);
+ });
+ });
+}
+
fn draw_arcs(canvas: &Canvas, overlay: &Overlay, to_out: impl Fn([f32; 2]) -> (f32, f32), px: f32) {
let mut placed: Vec<Rect> = Vec::new();
overlay.arcs.iter().enumerate().for_each(|(i, arc)| {
@@ -343,6 +372,12 @@ pub fn apply(image: &skia_safe::Image, overlay: &Overlay, view: &View) -> Result
|p| ((p[0] - origin.0) * s, (p[1] - origin.1) * s),
px,
);
+ draw_targets(
+ canvas,
+ &overlay.targets,
+ |p| ((p[0] - origin.0) * s, (p[1] - origin.1) * s),
+ px,
+ );
if overlay.ids {
let mut placed: Vec<Rect> = Vec::new();
overlay.marks.iter().enumerate().for_each(|(i, m)| {
diff --git a/docs/DESIGN.md b/docs/DESIGN.md
index f7c6b06..f799bff 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/1`)
+### doc.json (format `klad/2`)
```json
{
- "format": "klad/1",
+ "format": "klad/2",
"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.
+- `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.
### Edits
@@ -246,7 +246,8 @@ Every layer has `blend`, `opacity`, `visible`, `locked`, optional `mask`, `clip`
- **Fonts (M5, S5.26).** klad ships about fifty open families for game art in `fonts/` (sans, serif, mono, display, handwriting, pixel; OFL-1.1 or Apache-2.0, unchanged from the Google Fonts repository at a pinned commit, listed with their licences in the notices; `fonts/update.py` fetches them again). `klad_render::fonts` finds that folder next to the binary (also `../Resources/fonts` in a Mac app and the repository's `fonts/` for development builds; `KLAD_FONTS` overrides), and keeps families downloaded on request in a per-user folder (`~/Library/Application Support/klad/fonts`, `$XDG_DATA_HOME/klad/fonts`, `%APPDATA%\klad\fonts`). `fonts/catalogue.json` lists every open family on Google Fonts (about 1,900) with its group and folder at the same commit, so `klad fonts --search` works offline and a download (`klad fonts --get`, or naming a family anywhere a font is taken) fetches exactly that commit's files with `curl`. Choosing a font anywhere (the CLI's `font=`, `klad font`, the editor's picker) copies the file and its licence into the bundle; the node keeps the file name. This replaces M5 choice 3 (no fonts with the app). The editor's frame and plane caches fold `klad_render::RENDER_VERSION` into their keys, so pictures cached before a renderer change are not shown again. A light layer is no kind of its own: a paint layer set to `add` with a soft glow (a shortcut button for it only confused the layers pane).
- **Foliage (M5, S5.27).** `foliage` is a shape op (CLI only, principle 7): each closed shape becomes a clump built from leaf strokes on a jittered grid, each coloured from the clump lit as a round form (a normal from its bounding ellipse, mixed with the normal of an optional `mass` shape so clumps turn with the whole crown, a key light or a lamp, the underside darker) and stepped into three value families between `shade`, `color` and `lit` (OKLab; by default darker and cooler, lighter and warmer), with more variety in the light; then leaves along the outline, kept more where the outline faces the light or the sky, a few in `glow` on the shadow edge. Strokes are sorted dark to light so lit leaves land on top. It puts how foliage is painted (light families on the clump, the big mass before the texture, a broken silhouette) into one op, so an agent does not scatter leaves like confetti.
- **No agent inside the editor (M8).** A first version ran a model in an Agent pane with the user's Claude API key; it was removed on 2026-11-06 in favour of an MCP server that any agent client can use (planned). Agents work on a drawing through the `klad` CLI, and the person reaches them through notes, the selection and the shared history.
-- **Rigs (M6).** A paint layer or a group gets `bones` (format 9): each a name, an optional parent that comes before it, a head and a tail in canvas px. A group's skeleton poses every paint layer in it together, so a character's lines, colour and shading layers stay in step. Each bone has a weight map in `weights/<owner>.weights` (zstd: a JSON header with the grid size and bone names, then one byte per cell per bone, cells of 4 px), written by `Bundle::apply` with the edit and kept in its history step; weights are normalised across bones when read (bilinear between cells), and a place no bone weighs follows the nearest bone. Automatic weights are 1/(d + 0.15 L + 1)^3 by distance to each bone segment (L its length), so joints blend over a short stretch; `set` paints soft dabs (smoothstep falloff towards a value), `part` gives a named part's cells to one bone at 1 and the others 0, `smooth` blurs every map once. A pose (`pose` on a cel: its rest drawing's id, an angle per bone in degrees from rest, a root move) is linear blend skinning: each bone's rest matrix (head, angle) and posed matrix (its parent's posed matrix times the rest offset times its turn) give a skin matrix, and every stroke sample moves by the weighted sum; stroke sizes scale by the mean local stretch (the Jacobian's determinant, square-rooted); polygon fills move their points; flood fills are warped through a 4 px triangle mesh over their coverage (each posed triangle rasterised, sampling the rest coverage by barycentric position). The rest pose returns the marks untouched. `pose` (computed by the CLI, `cli/src/rig.rs`) makes or re-poses a drawing at `to` on every paint layer under the skeleton from the rest drawing shown at `from` (a posed drawing's own rest when `from` shows one). In-betweens of two poses of one rest drawing (or a pose and its rest) mix the angles and root by t instead of matching strokes (`rig::posed_pair`), and keep the mixed pose. A bone `move` with a `tail` takes along the heads of the children that start at the old tail (within half a pixel), and `by` moves a bone with all its children (`rig::moved`, which the editor also draws while dragging). The editor's bone tool (J) has three modes (draw, weights, pose) and in every mode a skeleton list in its options (each bone under its parent; picking one highlights it on the canvas); with no skeleton on the active layer the options name the layers and groups that have one, each a button that makes it active. Picking on the canvas is a click in draw and pose mode and cmd click (ctrl outside macOS) in weights mode. In draw mode a drag on empty canvas draws a root bone, a press on a bone picks it and drags what is under the pointer (the picked bone shows handles at both ends): an end moves that end, the middle moves the bone and its children, and the head of a child that starts at its parent's tail is that joint, so dragging it moves the parent's tail; alt drag from a tail draws a child (from a bone's middle, a child starting there); the options rename, reparent (a parent menu without the bone's own children) and remove. Draw mode shows the skeleton at rest. Weights are painted in the editor's own process (`klad_core::rig::weights_for`) over a tint of the picked bone's map, and pose mode turns bones, committing the pose through `klad pose` as a job; the drawing is not deformed live while turning, only the skeleton.
+- **Rigs (M6).** A paint layer or a group gets `bones` (format 9): each a name, an optional parent that comes before it, a head and a tail in canvas px. A group's skeleton poses every paint layer in it together, so a character's lines, colour and shading layers stay in step. Each bone has a weight map in `weights/<owner>.weights` (zstd: a JSON header with the grid size and bone names, then one byte per cell per bone, cells of 4 px), written by `Bundle::apply` with the edit and kept in its history step; weights are normalised across bones when read (bilinear between cells), and a place no bone weighs follows the nearest bone. Automatic weights are 1/(d + 0.15 L + 1)^3 by distance to each bone segment (L its length), so joints blend over a short stretch; `set` paints soft dabs (smoothstep falloff towards a value), `part` gives a named part's cells to one bone at 1 and the others 0, `smooth` blurs every map once. A pose (`pose` on a cel: its rest drawing's id, an angle per bone in degrees from rest, a root move) is linear blend skinning: each bone's rest matrix (head, angle) and posed matrix (its parent's posed matrix times the rest offset times its turn) give a skin matrix, and every stroke sample moves by the weighted sum; stroke sizes scale by the mean local stretch (the Jacobian's determinant, square-rooted); polygon fills move their points; flood fills are warped through a 4 px triangle mesh over their coverage (each posed triangle rasterised, sampling the rest coverage by barycentric position). The rest pose returns the marks untouched. `pose` (computed by the CLI, `cli/src/rig.rs`) makes or re-poses a drawing at `to` on every paint layer under the skeleton from the rest drawing shown at `from` (a posed drawing's own rest when `from` shows one). In-betweens of two poses of one rest drawing (or a pose and its rest) mix the angles and root by t instead of matching strokes (`rig::posed_pair`), and keep the mixed pose. A bone `move` with a `tail` takes along the heads of the children that start at the old tail (within half a pixel), and `by` moves a bone with all its children (`rig::moved`, which the editor also draws while dragging). The editor's bone tool (J) has three modes (draw, weights, pose) and in every mode a skeleton list in its options (each bone under its parent; picking one highlights it on the canvas); with no skeleton on the active layer the options name the layers and groups that have one, each a button that makes it active. Picking on the canvas is a click in draw and pose mode and cmd click (ctrl outside macOS) in weights mode. In draw mode a drag on empty canvas draws a root bone and starts a chain (S6.9, as Spine's create tool makes the new bone the next one's parent, but welded: Spine has no snapping and its users have asked for it): the next bone runs from the last tail to the pointer and each release (a click or a drag) adds it, its head exactly on that tail, so `rig::moved` and the joint grips treat it as a joint; shift as you let go keeps the joint and parent for the next bone (a fan); Esc, Enter, a right click, a click on the open end, or a change of mode, tool or skeleton owner ends it; a chain only commits on a release whose press reached the canvas, and each bone is its own undo step, so after cmd Z the chain (checked every frame against the bones) carries on from the last bone still there. With no chain, a press on a bone picks it and drags what is under the pointer (the picked bone shows handles at both ends): an end moves that end, the middle moves the bone and its children, and the head of a child that starts at its parent's tail is that joint, so dragging it moves the parent's tail; alt drag from a tail starts a chain from it (from a bone's middle, a child starting there); the options rename, reparent (a parent menu without the bone's own children), add or change the picked bone's IK, and remove. Draw and weights modes show the skeleton at rest. Weights are painted in the editor's own process (`klad_core::rig::weights_for`) over a tint of the picked bone's map, and pose mode turns bones, committing the pose (angles, root and targets) through `klad pose` as a job; it loads the pose of the frame shown again whenever the frame, the owner or that pose changes; the drawing is not deformed live while posing, only the skeleton.
+- **IK (M6, S6.10).** Taken from Spine (constraints on one or two bones, a bend side, softness, a mix, solved parent first, posing a limb by its end) with two changes: a target is a point kept in each pose (`pose.ik`), not a bone, because klad bones carry weight maps and go to Godot as `Bone2D`s, and constraints are ordered by the skeleton itself (the limb's top bone, then its bone), so there is no order to keep by hand. Constraints (`layer.ik`: bone, chain 1 or 2, bend, softness) live on the skeleton; a pose without a target for one leaves that limb to its angles, so adding a constraint changes no pose, and removing one (or a bone it holds, or a reparent that leaves a limb without its parent, which drops it as Spine does) first writes its solved turns into the angles of every pose that used it (`ops::bake`), so those poses keep their look. `rig::applied` solves (f64, libm): FK frames from the angles and root, then per constraint an aim (atan2 to the target) or a limb by two circles meeting (the upper segment runs from the parent's head to the bone's head, so a child that starts off its parent's tail is exact), with Spine-like softness as a quadratic ease into full reach (r = d - (d - L + s)^2 / 4s between L - s and L + s, smooth at both ends, straight at L + s), and the mix along the short way round from the angle. `skinning`, `tips` and `Rig::new` take the constraints, so every place a pose bends a drawing or draws a skeleton (the CLI's poses, in-betweens, the bones overlay, the Godot export's rotation tracks, the editor) uses the solved turns. In-betweens mix the targets, not the solved angles: a 100 + 100 px leg whose hip moves 120 px over a planted foot keeps the foot exactly with mixed targets and pushes it 9.7 px through the floor with mixed angles (`rig::tests`). Joint limits, stretch and chains of three or more bones (Spine refuses them: the result would depend on earlier frames) are not built. The editor's pose mode: a press near an IK limb's end or its target drags the target (making one at the end, so nothing jumps, when the pose had none); near a root bone's head moves the root, the targets staying where they are; on a bone an IK holds moves its target with the pointer; anywhere else it turns the bone, and alt turns a bone by hand after writing its limb's solved turns into the angles (IK off). The options show an IK switch and a mix for the picked bone's limb.
- **Keys (M6, S6.5).** Layers, groups and vector nodes keep `keys`: per property (`x`, `y`, `rotate`, `sx`, `sy`, `opacity`) a sorted list of frame, value and ease (linear, in, out, in-out, step, or a cubic curve x1,y1,x2,y2 solved by bisection). A segment follows its first key's ease; values hold before the first key and after the last. Layers and groups composite with their keyed opacity and, when moved, with their keyed transform about the canvas centre (drawn whole, not tile by tile, while moved); nodes take keyed transforms and opacity when rasterised (`nodes_at`). The editor's frame and plane caches hash the keyed values; its vector raster cache does not follow node keys yet, so keyed shapes move in `klad render` and the exports, not in the editor.
- **Godot scenes (M6, S6.6, S6.7).** `export --godot-scene` flattens each visible top-level layer (with its fog; the background with the first) into a texture on a `Parallax2D` with `scroll_scale` 1/(1 + depth), the factor the editor's depth preview (hold D) uses. `export --godot-rig` writes per skeleton: each part of the rest drawing (named parts of each paint layer's rest drawing, the loose marks as one) replayed alone, trimmed, on a `Polygon2D` with a 16 px triangle mesh over its pixels (one cell of margin), UVs, and per-vertex weights sampled from the maps; a `Skeleton2D` with a `Bone2D` per bone at rest (local position and angle against the parent, `rest`, `length`); and an `AnimationPlayer` with one animation per clip (or one for the timeline) whose value tracks hold each bone's rest angle plus its pose at the frame each posed drawing starts (stepped, so drawings hold as in klad); frames that are not poses of the rest drawing are listed for the frames export. Re-exports keep their uids. `samples/rig` builds a figure with all of it.
- **Paint over (M5, S5.29).** `paintover` (`cli/src/paintover.rs`, resolved before the shape ops, alone in its batch) flattens the source (the `from` layers, or every visible layer below the target's top-level layer with the background) into OKLab, then follows Hertzmann's painterly method: for each brush size, biggest first, the source is blurred to that size, a grid at half the size finds cells whose mean difference from the painting so far (an estimate made by stamping discs of each stroke's colour) exceeds `threshold`, and a stroke starts at each such cell's worst pixel in a seeded random order. A stroke walks in steps of half its size across the luminance gradient (Sobel), turning towards it by `curve` times how sure the gradient is (weak gradients keep the stroke's direction; with none, a smooth seeded field of mostly level angles), and stops past its minimum length when the source there is closer to the painting than to the stroke's colour, at a colour change over twice the threshold, at the edge of the region or at its maximum length. `focus` keeps the last size to a shape grown by three of those sizes. Each stroke becomes a stroke op with a press-in and lift-off pressure, its size a little varied, its colour broken by `vary` from a hash of its seed, in the part `part`. `like <cel>` carries a paint-over to another drawing: every source paint layer's two drawings are paired as in-betweens pair them; each stroke rides the topmost source mark under its centre (a stroke within half its size, a polygon fill, a flood fill's coverage) with `tween::carry` along that mark's line (still marks: it stays; marks gone: it fades to opacity 0); it keeps its seed and is recoloured from the new source at its start, faded when it would now cross an edge; new strokes, in `<part> added`, only go where the source changed (its colour or alpha, grown by the biggest size) or where carried strokes left a gap. `--frames a-b` repeats that drawing to drawing, making a drawing on the target wherever a source layer starts one (a link where they link). `samples/paintover` paints over the lemons and carries a paint-over through the creature's walk; frame to frame its background changes by 0.03 of 255 on average.
diff --git a/docs/cli.md b/docs/cli.md
index cb462d6..f46d4b9 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -44,6 +44,7 @@ This reference is licensed under the MIT License (`LICENSE-MIT`), unlike klad it
- [`klad scatter`](#klad-scatter): Scatter copies of a small mark over a shape: grass, cracks, dots
- [`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 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
@@ -2110,17 +2111,18 @@ Options:
## klad bone
```text
-Bones go on a paint layer or a group (a group's skeleton poses every paint layer in it together). A bone has a name, an optional parent, a head and a tail in canvas px; a child usually starts where its parent ends. Removing a bone removes its children. Moving a tail takes the heads of the children that start there along; --by moves a bone with all its children.
+Bones go on a paint layer or a group (a group's skeleton poses every paint layer in it together). A bone has a name, an optional parent, a head and a tail in canvas px; a child usually starts where its parent ends. --chain adds several bones at once, each the child of the one before and starting where it ends, through one more point than bones (the editor's bone tool draws chains the same way). Removing a bone removes its children (and the IK on them, its poses keeping their look). Moving a tail takes the heads of the children that start there along; --by moves a bone with all its children.
klad bone art.klad body --add hip --head 400,500 --tail 400,420
klad bone art.klad body --add thigh --parent hip --head 400,500 --tail 410,620
+ klad bone art.klad body --chain thigh,shin,foot --through '400,500 410,620 405,740 440,745' --parent hip
klad bone art.klad body --rename thigh --as femur
klad bone art.klad body --move femur --tail 420,630
klad bone art.klad body --move femur --by 12,-4
klad bone art.klad body --reparent femur --parent pelvis
klad bone art.klad body --rm femur
-Also a bone op: {"op":"bone","layer":"body","add":"thigh","parent":"hip","head":[400,500],"tail":[410,620]}.
+Also a bone op: {"op":"bone","layer":"body","add":"thigh","parent":"hip","head":[400,500],"tail":[410,620]}, or {"op":"bone","layer":"body","chain":["thigh","shin"],"through":[[400,500],[410,620],[405,740]],"parent":"hip"}.
Usage: klad bone [OPTIONS] <BUNDLE> <LAYER>
@@ -2162,6 +2164,71 @@ Options:
--by <BY>
dx,dy in px: with --move, the bone and its children
+ --chain <CHAIN>
+ names of a chain of new bones, comma separated: each the child of the one before
+
+ --through <THROUGH>
+ the chain's points, 'x,y x,y ...': one more than its bones
+
+ --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 ik
+
+```text
+An IK turns bones so the end of a limb reaches a target, instead of turning each bone by hand. A limb (--chain 2, when the bone has a parent) turns the bone and its parent so the bone's tail lands on the target, the joint between them bending --bend clockwise or counterclockwise on screen (by default the way it bends in the rest drawing; flip turns it over); out of reach it points straight at the target. An aim (--chain 1) turns the bone to point at the target. --softness (px) eases the limb into full stretch so a knee does not snap straight: it starts slowing that far before full reach and is straight that far past it. Targets are set per pose (klad pose --target), in canvas px, and stay put when the root moves, so a foot stays planted while the body moves; a pose without a target for an IK leaves that limb to its turns. IKs are solved parent first: a foot's aim after its leg's limb.
+
+ klad ik art.klad body --add shin
+ klad ik art.klad body --add shin --chain 2 --bend counterclockwise --softness 8
+ klad ik art.klad body --add foot --chain 1
+ klad ik art.klad body --set shin --bend flip
+ klad ik art.klad body --rm shin
+
+Also an ik op: {"op":"ik","layer":"body","add":"shin","chain":2,"bend":"clockwise","softness":8}. Removing an IK (or its bone) keeps every pose as it looks, as turns.
+
+Usage: klad ik [OPTIONS] <BUNDLE> <LAYER>
+
+Arguments:
+ <BUNDLE>
+
+
+ <LAYER>
+
+
+Options:
+ --add <ADD>
+
+
+ --set <SET>
+
+
+ --rm <RM>
+
+
+ --chain <CHAIN>
+ 2: a limb, the bone and its parent; 1: an aim, the bone alone
+
+ --bend <BEND>
+ which way the limb's joint bends on screen
+
+ [possible values: clockwise, counterclockwise, flip]
+
+ --softness <SOFTNESS>
+ px: how far before full reach the limb starts to slow, so it does not snap straight
+
--render
Render a preview after the edit and print its path
@@ -2291,11 +2358,13 @@ Options:
## klad pose
```text
-A pose is a turn per bone (degrees from its rest angle, children follow their parent) and a move of the whole (--root). 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.
+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.
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
+ klad pose art.klad body --from 0 --to 12 --target shin=430,700 --mix shin=0.5 --bone shin=-20
-Also a pose op: {"op":"pose","layer":"body","from":0,"to":4,"bones":{"thigh":25,"shin":-40},"root":[0,6]}.
+Also 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}}}.
Usage: klad pose [OPTIONS] --to <TO> <BUNDLE> <LAYER>
@@ -2319,6 +2388,12 @@ Options:
--root <ROOT>
[default: 0,0]
+ --target <TARGETS>
+ bone=x,y: where the end of that bone's IK reaches, in canvas px; repeat for more
+
+ --mix <MIXES>
+ bone=0..1: how far that IK pulls its limb from the turns to the target (default 1)
+
--hold <HOLD>
diff --git a/docs/format.md b/docs/format.md
index b84ca56..2574b4b 100644
--- a/docs/format.md
+++ b/docs/format.md
@@ -1,4 +1,4 @@
-_Last updated: 2026-11-06 (format `klad/1`, stroke files `KLST` version 1, brushes `klad-brush/1`)_
+_Last updated: 2026-11-07 (format `klad/2`, 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/1`, the first. Later versions will open older `klad/` drawings and migrate 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/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.
## doc.json
```json
{
- "format": "klad/1",
+ "format": "klad/2",
"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/1"` |
+| `format` | string | | `"klad/2"` |
| `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 |
@@ -103,6 +103,7 @@ A clip is `name` (unique), `from` and `to` (both included), `loop` (false) and `
| `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) |
| `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).
@@ -130,7 +131,7 @@ A cel that is not a link is a **drawing**; frames no cel covers are blank. Drawi
`tween` records an in-between made from two keys: `from` and `to` (the keys' drawing ids), `t` (0 to 1, after spacing), `match` (`order` or `near` when marks were not paired by id), `pairs` (forced pairs, `[first key mark, second key mark]`), `made` (a hash of the marks as made, so klad can tell whether someone drew on it since) and `unpaired` (`pop`, `pop 0.3`, `fade` or `draw-on`: how marks found in one key only were shown). The marks themselves are stored like any drawing's; the record only says how to remake them.
-`pose` records a drawing bent from a rest drawing by its layer's skeleton: `rest` (the rest drawing's id), `angles` (degrees from rest per bone name) and `root` (`[dx, dy]`, default `[0, 0]`). Its marks are stored bent, so a reader can draw it without knowing about bones.
+`pose` records a drawing bent from a rest drawing by its layer's skeleton: `rest` (the rest drawing's id), `angles` (degrees from rest per bone name), `root` (`[dx, dy]`, default `[0, 0]`) and `ik` (per IK constraint, named by its bone: `target`, `[x, y]` in canvas px, and `mix`, 0 to 1, default 1; see Skeletons). The bones' turns are `angles` with the IK solved on top of them. Its marks are stored bent, so a reader can draw it without knowing about bones.
### Vector nodes
@@ -211,6 +212,17 @@ A key is `frame`, `value` and `ease` (`linear` when absent; `in`, `out`, `in-out
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 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.
+
+`ik` lists the skeleton's IK constraints, one per bone at most: `bone` (the end of the limb), `chain` (`2`, the default: the bone and its parent, a limb; `1`: the bone alone, an aim), `bend` (`clockwise`, the default, or `counterclockwise`: the way the limb's joint bends on screen, as the bone turns relative to its parent) and `softness` (px, default 0). A pose with an `ik` entry for a constraint solves it after the pose's angles and root, on top of them:
+
+- **Aim** (`chain` 1): the bone turns so its tail points at the target; a target on its head leaves it as it is.
+- **Limb** (`chain` 2, parent A, bone B): with s the posed head of A, l1 the rest distance from A's head to B's head (B need not start at A's tail), l2 B's length and d the distance from s to the target, the reach r is d eased by the softness (below) and clamped to between |l1 - l2| and l1 + l2. The joint (B's posed head) is the meeting point of the circle of radius l1 about s and the circle of radius l2 about the point r along the line from s to the target, on the `bend` side: B turns clockwise relative to the line from A's head to B's head for `clockwise`. A then turns so its head-to-B line points at the joint, and B so its tail is at the target (or, out of reach, straight towards it at full reach).
+- **Softness** s eases the reach: r = d up to l1 + l2 - s; r = d - (d - l1 - l2 + s)^2 / (4 s) up to l1 + l2 + s; then r = l1 + l2. So the limb slows before full reach and is straight only once the target is s past it.
+- **Mix** m blends each turned bone from the pose's angle a to the solved angle b the short way round: a + m wrap(b - a), wrap taking an angle to -180 to 180 degrees.
+
+Constraints are solved parent first, by the position of the limb's top bone (A for a limb, the bone for an aim) in `bones`, then of its bone; each sees the bones as the ones before it left them. The solve is in 64-bit floats with deterministic maths, so it gives the same turns everywhere. A pose without an entry for a constraint leaves that limb to its angles. In-betweens of two poses of one rest drawing mix the angles, the root, each target and each mix by t (a constraint in one key only counts, in the other, as mix 0 with its target at that key's limb end), then solve.
+
## Stroke files
`strokes/<layer>/<cel>.strokes` holds the marks of one paint drawing, in the order they are drawn: brush strokes and fills. Every mark has an id, unique within its drawing, from one counter shared by strokes and fills. A mark's address is `<cel>:s<id>`.
@@ -320,3 +332,4 @@ Drawing a stroke: walk the samples, interpolate between them, stamp the tip ever
| Format | Change |
|---|---|
| `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. |
diff --git a/docs/skill/SKILL.md b/docs/skill/SKILL.md
index 2327e50..4153217 100644
--- a/docs/skill/SKILL.md
+++ b/docs/skill/SKILL.md
@@ -223,10 +223,13 @@ Draw a character once and pose it, instead of redrawing every frame. Put its pai
```bash
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 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
+klad pose art.klad figure --from 0 --to 8 --target shin=405,800 --root 30,-6 # the foot stays on 405,800 while the body moves
klad inbetween art.klad --layers colour,lines --from 0 --to 4 # poses of one rest drawing in-between on the bones
klad render art.klad --frame 4 --overlay bones # or --overlay weights:upper
klad key art.klad lantern --frame 0 y=0 --ease in-out; klad key art.klad lantern --frame 12 y=-18
@@ -234,7 +237,8 @@ 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, alt drag from an end draws a child.
+- 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.
- 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.