A drawing app built for agent/human collaboration
Rust
Bones, painted weights and poses, and in-betweens on bones
Indicode BV174b0d681756
diff --git a/crates/cli/src/agent.rs b/crates/cli/src/agent.rsindex 9a475ef..d494f9e 100644--- a/crates/cli/src/agent.rs+++ b/crates/cli/src/agent.rs@@ -208,6 +208,8 @@ pub struct Kinds {pub onion: bool,pub parts: bool,pub arcs: bool,+ pub bones: bool,+ pub weights: Option<String>,}pub fn overlay_flags(kinds: &str) -> Result<Kinds> {@@ -223,13 +225,21 @@ pub fn overlay_flags(kinds: &str) -> Result<Kinds> {"onion" => Kinds { onion: true, ..acc },"parts" => Kinds { parts: true, ..acc },"arcs" => Kinds { arcs: true, ..acc },+ "bones" => Kinds { bones: true, ..acc },+ w if w.starts_with("weights:") => Kinds {+ weights: Some(w.trim_start_matches("weights:").to_string()),+ bones: true,+ ..acc+ },"all" => Kinds {ids: true,bbox: true,grid: true,..acc},- other => bail!("unknown overlay {other:?}: use ids, bbox, grid, onion, parts, arcs or all"),+ other => bail!(+ "unknown overlay {other:?}: use ids, bbox, grid, onion, parts, arcs, bones, weights:<bone> or all"+ ),})})}@@ -383,7 +393,7 @@ pub fn render_look(let brushes = BrushSet::for_bundle(bundle)?;let loaded = layers::load(bundle, frame, &brushes, use_cache)?;let kinds = look.kinds()?;- let overlay = (kinds.ids || kinds.bbox || kinds.grid || kinds.parts || kinds.arcs)+ let overlay = (kinds.ids || kinds.bbox || kinds.grid || kinds.parts || kinds.arcs || kinds.bones).then(|| {let mut found = if kinds.ids || kinds.bbox {marks(bundle, frame, look.focus.as_deref(), look.depth)?@@ -401,6 +411,15 @@ pub fn render_look(arcs: arcs_of(bundle, look, frame, kinds.arcs)?,frame: Some(frame),numbers: true,+ bones: match kinds.bones {+ true => crate::rig::bones_at(bundle, frame)?,+ false => Vec::new(),+ },+ heat: kinds+ .weights+ .as_deref()+ .map(|b| crate::rig::heat(bundle, b))+ .transpose()?,})}).transpose()?;@@ -570,6 +589,9 @@ pub fn edit(path: &Path, ops: &[Op], out: &Output) -> Result<()> {true => println!("{n}"),false => eprintln!("{n}"),});+ crate::rig::resolve(&bundle, &mut ops)?+ .iter()+ .for_each(|n| println!("{n}"));let made = crate::inbetween::resolve(&bundle, &mut ops)?;made.iter().for_each(|n| println!("{n}"));if let Some(ms) = std::env::var("DRAW_TEST_WRITE_DELAY_MS")diff --git a/crates/cli/src/inbetween.rs b/crates/cli/src/inbetween.rsindex 72ce64f..2f8b7dc 100644--- a/crates/cli/src/inbetween.rs+++ b/crates/cli/src/inbetween.rs@@ -321,6 +321,7 @@ fn make(bundle: &Bundle, spec: &InbetweenSpec) -> Result<(Inbetweens, Vec<Stringlet mut made = Inbetweens::default();let mut notes = Vec::new();let mut jobs = Vec::new();+ let mut rigged: Vec<(usize, crate::rig::Posed, f32)> = Vec::new();paint_layers(doc, &spec.layers)?.into_iter().try_for_each(|layer| {let owner = doc.layer(&layer).ok_or_else(|| anyhow!("no layer {layer}"))?;let name = owner.name.clone();@@ -389,14 +390,18 @@ fn make(bundle: &Bundle, spec: &InbetweenSpec) -> Result<(Inbetweens, Vec<Stringfrom,(spec.matching, &spec.pairs, spec.unpaired),)?;+ let on_bones = crate::rig::posed_pair(bundle, &layer, &a, &b)?;frames.iter().zip(&ts).enumerate().for_each(|(i, (&frame, &t))| {let next = frames.get(i + 1).copied().unwrap_or(to);- jobs.push(Job {- key: keys.len(),- index: made.cels.len(),- frame,- t,- });+ match &on_bones {+ Some(rig) => rigged.push((made.cels.len(), rig.clone(), t)),+ None => jobs.push(Job {+ key: keys.len(),+ index: made.cels.len(),+ frame,+ t,+ }),+ }made.cels.push(TweenCel {layer: layer.clone(),cel: staged.alloc_id_in('c', &mut taken),@@ -406,6 +411,7 @@ fn make(bundle: &Bundle, spec: &InbetweenSpec) -> Result<(Inbetweens, Vec<Stringmarks: Vec::new(),fresh: true,parts: BTreeMap::new(),+ pose: None,});});keys.push(key);@@ -421,8 +427,24 @@ fn make(bundle: &Bundle, spec: &InbetweenSpec) -> Result<(Inbetweens, Vec<String..spec.clone()})],)?;- keys.iter().for_each(|k| pairing_notes(k, &mut notes));- compute(bundle, &staged, &keys, &jobs, &mut made.cels, &mut notes)?;+ keys.iter()+ .filter(|k| !rigged.iter().any(|(i, _, _)| made.cels[*i].layer == k.layer))+ .for_each(|k| pairing_notes(k, &mut notes));+ if !jobs.is_empty() {+ compute(bundle, &staged, &keys, &jobs, &mut made.cels, &mut notes)?;+ }+ rigged.iter().for_each(|(i, rig, t)| {+ let (marks, pose) = rig.at(*t, (doc.canvas.width, doc.canvas.height));+ made.cels[*i].marks = marks;+ made.cels[*i].pose = Some(pose);+ });+ let mut bent: Vec<&str> = rigged.iter().map(|(i, _, _)| made.cels[*i].layer.as_str()).collect();+ bent.dedup();+ bent.iter().for_each(|l| {+ notes.push(format!(+ "{l}: in-betweened on bones (both keys are poses of one rest drawing)"+ ))+ });keep_parts(doc, &mut made.cels);made.cels.iter().for_each(|c| {notes.push(format!(@@ -527,6 +549,7 @@ fn redo(bundle: &Bundle, spec: &InbetweenSpec) -> Result<(Inbetweens, Vec<Stringtween: tween.clone(),marks: Vec::new(),fresh: false,+ pose: None,parts: BTreeMap::new(),});Ok(())diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rsindex 5cd0f00..867bdb0 100644--- a/crates/cli/src/main.rs+++ b/crates/cli/src/main.rs@@ -18,12 +18,13 @@ mod looks;mod marks;mod paintover;mod paths;+mod rig;mod shapes;mod sheet;mod sprites;use agent::{Look, Output};-use anyhow::{Result, anyhow};+use anyhow::{Result, anyhow, bail};use clap::{Args, Parser, Subcommand};use klad_brush::BrushSet;use klad_core::bundle::{Blank, Bundle};@@ -32,8 +33,9 @@ use klad_core::fill::{EXPAND, FillSource, TOLERANCE};use klad_core::history::Stack;use klad_core::markedit::{LassoAction, MarkTransform};use klad_core::ops::{- ClipEdit, CopySpec, CopyTarget, FillSpec, FoliageSpec, GrassSpec, HatchSpec, InbetweenSpec, InkSpec, LassoSpec,- LightSpec, Op, PaintOverSpec, PaintSpec, PaletteEdit, Place, ScatterSpec, StrokeSpec,+ BoneSpec, ClipEdit, CopySpec, CopyTarget, FillSpec, FoliageSpec, GrassSpec, HatchSpec, InbetweenSpec, InkSpec,+ LassoSpec, LightSpec, Op, PaintOverSpec, PaintSpec, PaletteEdit, Place, PoseSpec, ScatterSpec, StrokeSpec,+ WeightsSpec,};use klad_core::retime::{Retime, RetimeSpec};use klad_core::stroke::{fills_of, strokes_of};@@ -1157,6 +1159,84 @@ enum Command {#[command(flatten)]flags: EditFlags,},+ #[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.\n\n klad bone art.draw body --add hip --head 400,500 --tail 400,420\n klad bone art.draw body --add thigh --parent hip --head 400,500 --tail 410,620\n klad bone art.draw body --rename thigh --as femur\n klad bone art.draw body --move femur --tail 420,630\n klad bone art.draw body --reparent femur --parent pelvis\n klad bone art.draw body --rm femur\n\nAlso a bone op: {\"op\":\"bone\",\"layer\":\"body\",\"add\":\"thigh\",\"parent\":\"hip\",\"head\":[400,500],\"tail\":[410,620]}."+ )]+ Bone {+ bundle: PathBuf,+ layer: String,+ #[arg(long)]+ add: Option<String>,+ #[arg(long)]+ rm: Option<String>,+ #[arg(long)]+ rename: Option<String>,+ #[arg(long = "as")]+ to_name: Option<String>,+ #[arg(long = "move")]+ moved: Option<String>,+ #[arg(long)]+ reparent: Option<String>,+ #[arg(long)]+ parent: Option<String>,+ #[arg(long, value_parser = parse_pair, allow_hyphen_values = true)]+ head: Option<[f32; 2]>,+ #[arg(long, value_parser = parse_pair, allow_hyphen_values = true)]+ tail: Option<[f32; 2]>,+ #[command(flatten)]+ flags: EditFlags,+ },+ #[command(about = "List the skeletons, their bones and weights, and the posed drawings")]+ Bones {+ bundle: PathBuf,+ #[arg(long)]+ json: bool,+ },+ #[command(+ about = "Set how much each bone moves each part of the drawing: automatic, painted dabs, a whole part, smoothed",+ long_about = "Every bone has a weight map over the rest drawing (a grid at a quarter of the canvas resolution); where weights blend, lines bend smoothly; a part held by one bone at weight 1 moves rigidly. --auto starts from the bones (by distance, blending across the joints). --set paints soft round dabs of a weight onto --bone: 'x,y,radius,weight ...'. --part makes a named part of the drawing (at --frame) fully that bone's (and no other's). --smooth blurs the maps a little. render --overlay weights:<bone> shows a bone's map.\n\n klad weights art.draw body --auto\n klad weights art.draw body --bone shin --set '400,600,30,1 410,640,20,0.8'\n klad weights art.draw body --bone head --part head\n\nAlso a weights op: {\"op\":\"weights\",\"layer\":\"body\",\"bone\":\"shin\",\"set\":[[400,600,30,1]]}."+ )]+ Weights {+ bundle: PathBuf,+ layer: String,+ #[arg(long)]+ auto: bool,+ #[arg(long)]+ bone: Option<String>,+ #[arg(long, allow_hyphen_values = true)]+ set: Option<String>,+ #[arg(long)]+ part: Option<String>,+ #[arg(long, default_value_t = 1.0)]+ value: f32,+ #[arg(long)]+ smooth: bool,+ #[arg(long, default_value_t = 0)]+ frame: u32,+ #[command(flatten)]+ flags: EditFlags,+ },+ #[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.draw 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]}."+ )]+ Pose {+ bundle: PathBuf,+ layer: String,+ #[arg(long, default_value_t = 0)]+ from: u32,+ #[arg(long)]+ to: u32,+ #[arg(long = "bone", help = "name=degrees; repeat for more", allow_hyphen_values = true)]+ bones: Vec<String>,+ #[arg(long, value_parser = parse_pair, allow_hyphen_values = true, default_value = "0,0")]+ root: [f32; 2],+ #[arg(long)]+ hold: Option<u32>,+ #[command(flatten)]+ flags: EditFlags,+ },#[command(about = "Measure a drawing against a reference picture: values, saturation, texture, edges, colour per region",long_about = "Render the drawing (or read a PNG or JPEG) at the reference's size and compare the two in OKLab: the value range (L at the 5th, 50th and 95th percentile), mean chroma, stroke texture (mean absolute Laplacian of L), edge sharpness (99th percentile of the gradient) and the mean colour difference, with what differs in words (lighter, bluer, busier, softer edges). --region adds a row per named rectangle; --heat writes a picture of where they differ most (black, red, yellow, white as the difference grows to 20).\n\n klad compare cafe.draw reference.png --region shade=40,300,200,120 --region cup=610,180,90,120 --heat diff.png"@@ -2656,6 +2736,106 @@ fn run() -> Result<()> {};agent::edit(&bundle, &[Op::Foliage(spec)], &output(&flags, frame))?;}+ Command::Bone {+ bundle,+ layer,+ add,+ rm,+ rename,+ to_name,+ moved,+ reparent,+ parent,+ head,+ tail,+ flags,+ } => {+ let spec = BoneSpec {+ layer: layer_id(&bundle, &layer)?,+ add,+ rm,+ rename,+ to_name,+ moved,+ reparent,+ parent,+ head,+ tail,+ };+ agent::edit(&bundle, &[Op::Bone(spec)], &output(&flags, 0))?;+ }+ Command::Bones { bundle, json } => rig::list(&Bundle::open(&bundle)?, json)?,+ Command::Weights {+ bundle,+ layer,+ auto,+ bone,+ set,+ part,+ value,+ smooth,+ frame,+ flags,+ } => {+ let set = set+ .as_deref()+ .map(|text| {+ text.split_whitespace()+ .map(|d| -> Result<[f32; 4]> {+ parse_numbers(d)?+ .try_into()+ .map_err(|_| anyhow!("dab {d:?} is not x,y,radius,weight"))+ })+ .collect::<Result<Vec<_>>>()+ })+ .transpose()?+ .unwrap_or_default();+ if !auto && set.is_empty() && part.is_none() && !smooth {+ bail!("say what to do: --auto, --set with --bone, --part with --bone, or --smooth");+ }+ let spec = WeightsSpec {+ layer: layer_id(&bundle, &layer)?,+ frame,+ auto,+ bone,+ set,+ part,+ value,+ smooth,+ resolved: None,+ };+ agent::edit(&bundle, &[Op::Weights(spec)], &output(&flags, frame))?;+ }+ Command::Pose {+ bundle,+ layer,+ from,+ to,+ bones,+ root,+ hold,+ flags,+ } => {+ let bones = bones+ .iter()+ .map(|b| -> Result<(String, f32)> {+ let (name, deg) = b+ .split_once('=')+ .ok_or_else(|| anyhow!("--bone {b:?} is not name=degrees"))?;+ Ok((name.trim().to_string(), deg.trim().parse()?))+ })+ .collect::<Result<_>>()?;+ let spec = PoseSpec {+ layer: layer_id(&bundle, &layer)?,+ from,+ to,+ bones,+ root,+ hold,+ resolved: None,+ };+ agent::edit(&bundle, &[Op::Pose(spec)], &output(&flags, to))?;+ }Command::Compare {drawing,reference,diff --git a/crates/cli/src/rig.rs b/crates/cli/src/rig.rsnew file mode 100644index 0000000..e9f3147--- /dev/null+++ b/crates/cli/src/rig.rs@@ -0,0 +1,512 @@+use anyhow::{Context, Result, anyhow, bail};+use klad_core::bundle::Bundle;+use klad_core::doc::{Document, Kind, Layer};+use klad_core::ops::{Applied, Op, PoseSpec, PosedCel, WeightsSpec, apply, rig_owner};+use klad_core::rig::{Bone, CELL, Pose, Rig, Weights, tips};+use klad_core::stroke::Mark;+use klad_render::overlay::Heat;+use serde_json::json;+use std::collections::BTreeMap;++fn family(layer: &Layer) -> Vec<&Layer> {+ std::iter::once(layer)+ .chain(layer.children().iter().flat_map(family))+ .collect()+}++pub fn painted(owner: &Layer) -> Vec<&Layer> {+ family(owner).into_iter().filter(|l| l.kind() == Kind::Paint).collect()+}++pub fn owners(doc: &Document) -> Vec<&Layer> {+ doc.all_layers().into_iter().filter(|l| !l.bones.is_empty()).collect()+}++fn pose_at(owner: &Layer, frame: u32) -> Pose {+ painted(owner)+ .iter()+ .find_map(|l| l.content_at(frame).and_then(|c| c.pose.clone()))+ .unwrap_or_default()+}++pub fn bones_at(bundle: &Bundle, frame: u32) -> Result<Vec<klad_render::overlay::Shown>> {+ Ok(owners(&bundle.doc)+ .into_iter()+ .flat_map(|owner| {+ let pose = pose_at(owner, frame);+ owner+ .bones+ .iter()+ .zip(tips(&owner.bones, &pose))+ .map(|(b, (h, t))| (b.name.clone(), h, t))+ .collect::<Vec<_>>()+ })+ .collect())+}++pub fn heat(bundle: &Bundle, bone: &str) -> Result<Heat> {+ let owner = owners(&bundle.doc)+ .into_iter()+ .find(|o| o.bones.iter().any(|b| b.name == bone))+ .ok_or_else(|| anyhow!("no bone {bone} in this drawing"))?;+ let weights = bundle.read_weights(&owner.id)?;+ let at: Vec<u8> = (0..weights.height)+ .flat_map(|y| (0..weights.width).map(move |x| (x, y)))+ .map(|(x, y)| {+ let p = [(x as f32 + 0.5) * CELL as f32, (y as f32 + 0.5) * CELL as f32];+ let i = owner.bones.iter().position(|b| b.name == bone).unwrap_or(0);+ (weights.at(&owner.bones, p)[i] * 255.0).round() as u8+ })+ .collect();+ Ok(Heat {+ cell: CELL as f32,+ width: weights.width,+ values: at,+ })+}++fn weights_for(+ bundle: &Bundle,+ doc: &Document,+ spec: &WeightsSpec,+ current: &BTreeMap<String, Weights>,+) -> Result<Weights> {+ let owner = rig_owner(doc, &spec.layer)?;+ let canvas = (doc.canvas.width, doc.canvas.height);+ if owner.bones.is_empty() {+ bail!("{} has no bones yet: add them with klad bone first", owner.name);+ }+ let mut w = match current.get(&owner.id) {+ Some(w) => w.clone(),+ None => bundle.read_weights(&owner.id)?,+ };+ if (w.width, w.height) != Weights::new(canvas).dims() {+ w = Weights::new(canvas);+ }+ if spec.auto {+ let fresh = Weights::auto(&owner.bones, canvas);+ match &spec.bone {+ Some(b) => {+ let map = fresh.maps.get(b).cloned().ok_or_else(|| anyhow!("no bone {b}"))?;+ w.maps.insert(b.clone(), map);+ }+ None => w = fresh,+ }+ }+ let bone = || -> Result<String> {+ let b = spec.bone.clone().context("say which bone: \"bone\"")?;+ if !owner.bones.iter().any(|o| o.name == b) {+ bail!("no bone {b} on {}", owner.name);+ }+ Ok(b)+ };+ if !spec.set.is_empty() {+ let b = bone()?;+ spec.set.iter().for_each(|d| w.dab(&b, [d[0], d[1]], d[2], d[3]));+ }+ if let Some(part) = &spec.part {+ let b = bone()?;+ let mut cells = Vec::new();+ painted(owner).iter().try_for_each(|layer| -> Result<()> {+ let Some(cel) = layer.content_at(spec.frame) else {+ return Ok(());+ };+ let Some(ids) = cel.parts.get(part) else {+ return Ok(());+ };+ let marks = bundle.read_marks(&layer.id, &cel.id)?;+ marks.iter().filter(|m| ids.contains(&m.id())).for_each(|m| match m {+ Mark::Stroke(s) => s.samples.iter().for_each(|q| {+ let (x, y) = q.pos();+ let r = (s.size * 0.5 / CELL as f32).ceil() as i64 + 1;+ let (cx, cy) = ((x / CELL as f32) as i64, (y / CELL as f32) as i64);+ (-r..=r)+ .flat_map(|dy| (-r..=r).map(move |dx| (cx + dx, cy + dy)))+ .for_each(|c| cells.push(c));+ }),+ Mark::Fill(f) => {+ let c = &f.coverage;+ (c.y..c.y + c.height).step_by(CELL as usize / 2).for_each(|y| {+ (c.x..c.x + c.width)+ .step_by(CELL as usize / 2)+ .filter(|&x| c.at(x, y) > 0)+ .for_each(|x| cells.push(((x / CELL) as i64, (y / CELL) as i64)));+ });+ }+ });+ Ok(())+ })?;+ let (gw, gh) = (w.width as i64, w.height as i64);+ let mut cells: Vec<(u32, u32)> = cells+ .into_iter()+ .filter(|(x, y)| *x >= 0 && *y >= 0 && *x < gw && *y < gh)+ .map(|(x, y)| (x as u32, y as u32))+ .collect();+ cells.sort_unstable();+ cells.dedup();+ if cells.is_empty() {+ bail!("no marks in the part {part} at frame {}", spec.frame);+ }+ w.fill(&b, &cells, spec.value);+ if spec.value >= 1.0 {+ let others: Vec<String> = w.maps.keys().filter(|k| **k != b).cloned().collect();+ others.iter().for_each(|o| w.fill(o, &cells, 0.0));+ }+ }+ if spec.smooth {+ w.smooth();+ }+ Ok(w)+}++fn rest_of(layer: &Layer, frame: u32) -> Option<String> {+ let cel = layer.content_at(frame)?;+ Some(cel.pose.as_ref().map_or_else(|| cel.id.clone(), |p| p.rest.clone()))+}++fn posed(bundle: &Bundle, doc: &mut Document, spec: &PoseSpec, weights: &Weights) -> Result<Vec<PosedCel>> {+ let owner = rig_owner(doc, &spec.layer)?.clone();+ if owner.bones.is_empty() {+ bail!("{} has no bones yet: add them with klad bone first", owner.name);+ }+ if let Some(b) = spec.bones.keys().find(|b| !owner.bones.iter().any(|o| &o.name == *b)) {+ bail!("no bone {b} on {}", owner.name);+ }+ let canvas = (doc.canvas.width, doc.canvas.height);+ let layers: Vec<Layer> = painted(&owner).into_iter().cloned().collect();+ layers+ .iter()+ .filter_map(|layer| rest_of(layer, spec.from).map(|rest| (layer, rest)))+ .map(|(layer, rest)| {+ let pose = Pose {+ rest: rest.clone(),+ angles: spec.bones.clone(),+ root: spec.root,+ };+ let marks = bundle.read_marks(&layer.id, &rest)?;+ let made = Rig::new(&owner.bones, 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),+ Some(c) if c.id == rest => bail!(+ "frame {} holds the rest drawing {rest} on {}: pose into another frame",+ spec.to,+ layer.name+ ),+ Some(c) => bail!(+ "frame {} already has the drawing {} on {}, not a pose of {rest}",+ spec.to,+ c.id,+ layer.name+ ),+ None => (doc.alloc_id('c'), true),+ };+ Ok(PosedCel {+ layer: layer.id.clone(),+ cel,+ frame: spec.to,+ hold: spec.hold,+ pose,+ marks: made,+ fresh,+ })+ })+ .collect()+}++pub fn resolve(bundle: &Bundle, ops: &mut [Op]) -> Result<Vec<String>> {+ if !ops.iter().any(|op| matches!(op, Op::Weights(_) | Op::Pose(_))) {+ return Ok(Vec::new());+ }+ let mut doc = bundle.doc.clone();+ let mut applied = Applied::default();+ let mut weights: BTreeMap<String, Weights> = BTreeMap::new();+ let mut notes = Vec::new();+ ops.iter_mut().enumerate().try_for_each(|(i, op)| {+ match op {+ Op::Weights(spec) => {+ let made = weights_for(bundle, &doc, spec, &weights).with_context(|| format!("op {}", i + 1))?;+ let owner = rig_owner(&doc, &spec.layer)?.id.clone();+ weights.insert(owner, made.clone());+ spec.resolved = Some(made);+ }+ Op::Pose(spec) => {+ let owner = rig_owner(&doc, &spec.layer)?.id.clone();+ let w = match weights.get(&owner) {+ Some(w) => w.clone(),+ None => bundle.read_weights(&owner)?,+ };+ let w = match w.maps.is_empty() {+ true => {+ let o = rig_owner(&doc, &spec.layer)?;+ Weights::auto(&o.bones, (doc.canvas.width, doc.canvas.height))+ }+ false => w,+ };+ let made = posed(bundle, &mut doc, spec, &w).with_context(|| format!("op {}", i + 1))?;+ notes.push(format!(+ "posed {} drawings at frame {}: {}",+ made.len(),+ spec.to,+ made.iter().map(|c| c.cel.as_str()).collect::<Vec<_>>().join(" ")+ ));+ spec.resolved = Some(made);+ }+ _ => {}+ }+ apply(&mut doc, op, &mut applied).with_context(|| format!("op {}", i + 1))+ })?;+ Ok(notes)+}++pub fn list(bundle: &Bundle, as_json: bool) -> Result<()> {+ let doc = &bundle.doc;+ let rigs: Vec<serde_json::Value> = owners(doc)+ .iter()+ .map(|o| {+ let weights = bundle.read_weights(&o.id).ok();+ json!({+ "layer": o.id,+ "name": o.name,+ "bones": o.bones.iter().map(|b| json!({+ "name": b.name,+ "parent": b.parent,+ "head": b.head,+ "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<_>>(),+ })+ })+ .collect();+ if as_json {+ println!("{}", serde_json::to_string_pretty(&rigs)?);+ return Ok(());+ }+ if rigs.is_empty() {+ println!("no bones yet: klad bone <bundle> <layer> --add hip --head x,y --tail x,y");+ }+ owners(doc).iter().for_each(|o| {+ println!("{} ({})", o.name, o.id);+ let weights = bundle.read_weights(&o.id).ok();+ o.bones.iter().for_each(|b: &Bone| {+ let painted = weights.as_ref().is_some_and(|w| w.maps.contains_key(&b.name));+ println!(+ " {:<14} {:<12} {:.0},{:.0} -> {:.0},{:.0}{}",+ b.name,+ b.parent.as_deref().unwrap_or("-"),+ b.head[0],+ b.head[1],+ b.tail[0],+ b.tail[1],+ if painted { "" } else { " no weights yet" }+ );+ });+ 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(" "));+ })+ });+ });+ Ok(())+}++#[derive(Clone)]+pub struct Posed {+ bones: Vec<Bone>,+ weights: Weights,+ a: Pose,+ b: Pose,+ rest: Vec<Mark>,+}++impl Posed {+ pub fn at(&self, t: f32, canvas: (u32, u32)) -> (Vec<Mark>, Pose) {+ let pose = self.a.mix(&self.b, t);+ (+ Rig::new(&self.bones, &self.weights, &pose).pose(&self.rest, canvas),+ pose,+ )+ }+}++pub fn posed_pair(bundle: &Bundle, layer: &str, a: &str, b: &str) -> Result<Option<Posed>> {+ let doc = &bundle.doc;+ let Some(paint) = doc.layer(layer) else {+ return Ok(None);+ };+ let pose = |id: &str| paint.cels().iter().find(|c| c.id == id).and_then(|c| c.pose.clone());+ let rest = |id: &str| Pose {+ rest: id.to_string(),+ ..Pose::default()+ };+ let (pa, pb) = match (pose(a), pose(b)) {+ (Some(x), Some(y)) => (x, y),+ (Some(x), None) if x.rest == b => (x, rest(b)),+ (None, Some(y)) if y.rest == a => (rest(a), y),+ _ => return Ok(None),+ };+ if pa.rest != pb.rest {+ return Ok(None);+ }+ let Some(owner) = owners(doc)+ .into_iter()+ .find(|o| family(o).iter().any(|l| l.id == layer))+ else {+ return Ok(None);+ };+ let weights = bundle.read_weights(&owner.id)?;+ let weights = match weights.maps.is_empty() {+ true => Weights::auto(&owner.bones, (doc.canvas.width, doc.canvas.height)),+ false => weights,+ };+ Ok(Some(Posed {+ bones: owner.bones.clone(),+ weights,+ a: pa.clone(),+ b: pb,+ rest: bundle.read_marks(layer, &pa.rest)?,+ }))+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::agent::Output;+ use klad_core::ops::parse_lines;++ fn quiet() -> Output {+ Output {+ json: false,+ render: false,+ scale: None,+ frame: 0,+ overlay: None,+ }+ }++ fn arm(name: &str) -> std::path::PathBuf {+ let dir = std::env::temp_dir().join(format!("klad-rig-{name}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ let mut doc = Document::new(600, 400);+ doc.layers = vec![Layer::paint("l1", "arm", "c1")];+ doc.timeline.frames = 9;+ doc.next_id = 10;+ Bundle::create(&dir, doc).unwrap();+ let ops = r##"{"op":"stroke","layer":"l1","brush":"ink","size":20,"color":"#c06a3a","path":"M100 200 L 300 200 L 480 200","part":"arm"}+{"op":"fill","layer":"l1","polygon":[[470,185],[520,188],[522,212],[470,215]],"color":"#e0b080","part":"hand"}"##;+ crate::agent::edit(&dir, &parse_lines(ops).unwrap(), &quiet()).unwrap();+ dir+ }++ fn edit(dir: &std::path::Path, ops: &str) -> Result<()> {+ crate::agent::edit(dir, &parse_lines(ops)?, &quiet())+ }++ fn end_of(bundle: &Bundle, frame: u32) -> (f32, f32) {+ let cel = bundle.doc.layer("l1").unwrap().content_at(frame).unwrap().id.clone();+ let marks = bundle.read_marks("l1", &cel).unwrap();+ let s = marks.iter().find_map(Mark::as_stroke).unwrap();+ s.samples[s.samples.len() - 1].pos()+ }++ #[test]+ fn bones_weights_and_poses_through_the_cli_and_undo() {+ let dir = arm("pose");+ edit(+ &dir,+ r#"{"op":"bone","layer":"l1","add":"upper","head":[100,200],"tail":[300,200]}+{"op":"bone","layer":"l1","add":"fore","parent":"upper","head":[300,200],"tail":[480,200]}+{"op":"bone","layer":"l1","add":"hand","parent":"fore","head":[480,200],"tail":[520,200]}"#,+ )+ .unwrap();+ assert!(+ edit(+ &dir,+ r#"{"op":"bone","layer":"l1","add":"fore","head":[0,0],"tail":[1,1]}"#+ )+ .is_err()+ );+ edit(+ &dir,+ r#"{"op":"weights","layer":"l1","auto":true}+{"op":"weights","layer":"l1","bone":"hand","part":"hand"}"#,+ )+ .unwrap();+ let bundle = Bundle::open(&dir).unwrap();+ let w = bundle.read_weights("l1").unwrap();+ assert_eq!(w.maps.len(), 3);+ let bones = &bundle.doc.layer("l1").unwrap().bones;+ assert!(+ w.at(bones, [500.0, 200.0])[2] > 0.99,+ "the hand part is the hand bone's alone"+ );+ edit(+ &dir,+ r#"{"op":"pose","layer":"l1","from":0,"to":4,"bones":{"fore":-90}}"#,+ )+ .unwrap();+ let bundle = Bundle::open(&dir).unwrap();+ let end = end_of(&bundle, 4);+ assert!(+ (end.0 - 300.0).abs() < 4.0 && (end.1 - 20.0).abs() < 4.0,+ "the forearm points up: {end:?}"+ );+ let posed = bundle.doc.layer("l1").unwrap().content_at(4).unwrap();+ assert_eq!(posed.pose.as_ref().unwrap().rest, "c1");+ edit(+ &dir,+ r#"{"op":"pose","layer":"l1","from":4,"to":4,"bones":{"fore":-45}}"#,+ )+ .unwrap();+ let bundle = Bundle::open(&dir).unwrap();+ assert_eq!(+ bundle.doc.layer("l1").unwrap().cels().len(),+ 2,+ "posing a pose again re-poses it"+ );+ edit(&dir, r#"{"op":"inbetween","layers":["l1"],"from":0,"to":4}"#).unwrap();+ let bundle = Bundle::open(&dir).unwrap();+ let mid = bundle.doc.layer("l1").unwrap().content_at(2).unwrap();+ let angle = mid.pose.as_ref().unwrap().angles["fore"];+ assert!(angle < -5.0 && angle > -40.0, "{angle}");+ let end = end_of(&bundle, 2);+ let reach = (end.0 - 300.0).hypot(end.1 - 200.0);+ assert!(+ (reach - 180.0).abs() < 4.0,+ "the forearm keeps its length on bones: {reach}"+ );+ edit(&dir, r#"{"op":"bone","layer":"l1","rename":"fore","as":"forearm"}"#).unwrap();+ let bundle = Bundle::open(&dir).unwrap();+ assert!(bundle.read_weights("l1").unwrap().maps.contains_key("forearm"));+ assert!(+ bundle+ .doc+ .layer("l1")+ .unwrap()+ .content_at(4)+ .unwrap()+ .pose+ .as_ref()+ .unwrap()+ .angles+ .contains_key("forearm")+ );+ let mut bundle = Bundle::open(&dir).unwrap();+ klad_core::history::step(&mut bundle, klad_core::history::Stack::Undo).unwrap();+ assert!(+ bundle.read_weights("l1").unwrap().maps.contains_key("fore"),+ "undo restores the weights file"+ );+ edit(&dir, r#"{"op":"bone","layer":"l1","rm":"upper"}"#).unwrap();+ assert!(+ Bundle::open(&dir).unwrap().doc.layer("l1").unwrap().bones.is_empty(),+ "removing a bone removes its children"+ );+ std::fs::remove_dir_all(&dir).unwrap();+ }+}diff --git a/crates/core/src/bundle.rs b/crates/core/src/bundle.rsindex 7b5540e..7430295 100644--- a/crates/core/src/bundle.rs+++ b/crates/core/src/bundle.rs@@ -313,6 +313,21 @@ impl Bundle {Ok(strokes_of(&self.read_marks(layer, cel)?).cloned().collect())}+ pub fn weights_path(&self, layer: &str) -> PathBuf {+ self.root.join("weights").join(format!("{layer}.weights"))+ }++ pub fn read_weights(&self, layer: &str) -> Result<crate::rig::Weights> {+ let path = self.weights_path(layer);+ let canvas = (self.doc.canvas.width, self.doc.canvas.height);+ match path.is_file() {+ true => {+ crate::rig::Weights::decode(&fs::read(&path)?).with_context(|| format!("reading {}", path.display()))+ }+ false => Ok(crate::rig::Weights::new(canvas)),+ }+ }+pub fn write_marks(&self, layer: &str, cel: &str, marks: &[Mark]) -> Result<u64> {self.embed_brushes_of(marks)?;let bytes = encode_cel(marks)?;@@ -346,16 +361,35 @@ impl Bundle {}).collect::<Result<Vec<_>>>()?;name_parts(&mut doc, &applied.marks);+ let mut weights = applied.weights.clone();+ applied+ .renamed_bones+ .iter()+ .try_for_each(|(layer, old, new)| -> Result<()> {+ if !weights.iter().any(|(l, _)| l == layer) {+ weights.push((layer.clone(), self.read_weights(layer)?));+ }+ if let Some((_, w)) = weights.iter_mut().find(|(l, _)| l == layer)+ && let Some(map) = w.maps.remove(old)+ {+ w.maps.insert(new.clone(), map);+ }+ Ok(())+ })?;let touched: Vec<PathBuf> = written.iter().map(|(layer, cel, _)| self.strokes_path(layer, cel)).chain(applied.dropped_cels.iter().map(|(l, c)| self.strokes_path(l, c)))+ .chain(weights.iter().map(|(l, _)| self.weights_path(l))).collect();checkpoint(self, &doc, author, &summarize(ops), &touched)?;self.doc = doc;written.iter().try_for_each(|(layer, cel, marks)| self.write_marks(layer, cel, marks).map(|_| ()))?;+ weights+ .iter()+ .try_for_each(|(layer, w)| write_atomic(&self.weights_path(layer), &w.encode()?))?;self.save()?;applied.dropped_cels.iter().for_each(|(layer, cel)| {let _ = fs::remove_file(self.strokes_path(layer, cel));@@ -529,6 +563,9 @@ pub fn summarize(ops: &[Op]) -> String {Op::Scatter(spec) => format!("scatter on {}", spec.layer),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::Weights(spec) => format!("weights on {}", spec.layer),+ Op::Pose(spec) => format!("pose on {} at frame {}", spec.layer, spec.to),Op::Grass(spec) => format!("grass on {}", spec.layer),Op::Inbetween(spec) if spec.redo => "redo in-betweens".to_string(),Op::Inbetween(spec) => format!(diff --git a/crates/core/src/doc.rs b/crates/core/src/doc.rsindex 5f30ccf..54960a4 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 = "draw-anything/8";+pub const FORMAT: &str = "draw-anything/9";pub const MAX_SIZE: u32 = 16384;pub const MASK: usize = usize::MAX;@@ -145,6 +145,8 @@ pub struct Layer {pub depth: Option<f32>,#[serde(default, skip_serializing_if = "is_false")]pub reference: bool,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub bones: Vec<crate::rig::Bone>,}#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]@@ -253,6 +255,8 @@ pub struct Cel {pub nodes: Vec<Node>,#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]pub parts: BTreeMap<String, Vec<u32>>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub pose: Option<crate::rig::Pose>,}#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]@@ -512,6 +516,7 @@ impl Layer {effects: Vec::new(),depth: None,reference: false,+ bones: Vec::new(),}}@@ -633,6 +638,7 @@ impl Cel {tween: None,nodes: Vec::new(),parts: BTreeMap::new(),+ pose: None,}}@@ -696,6 +702,13 @@ impl Node {}}+pub fn family_paths(doc: &Document, path: &[usize]) -> Vec<Vec<usize>> {+ let layer = doc.layer_at(path);+ std::iter::once(path.to_vec())+ .chain((0..layer.children().len()).flat_map(|i| family_paths(doc, &[path, &[i]].concat())))+ .collect()+}+fn walk_layers<'a>(layers: &'a [Layer], out: &mut Vec<&'a Layer>) {layers.iter().for_each(|l| {out.push(l);diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rsindex 76c8a84..ce5a004 100644--- a/crates/core/src/lib.rs+++ b/crates/core/src/lib.rs@@ -15,6 +15,7 @@ pub mod patch;pub mod path;pub mod pathedit;pub mod retime;+pub mod rig;pub mod rng;pub mod stroke;pub mod synth;diff --git a/crates/core/src/migrate.rs b/crates/core/src/migrate.rsindex eaec77b..49046d1 100644--- a/crates/core/src/migrate.rs+++ b/crates/core/src/migrate.rs@@ -12,6 +12,7 @@ const V4: &str = "draw-anything/4";const V5: &str = "draw-anything/5";const V6: &str = "draw-anything/6";const V7: &str = "draw-anything/7";+const V8: &str = "draw-anything/8";#[derive(Clone, Debug, PartialEq, Eq)]pub struct FileMove {@@ -44,7 +45,7 @@ pub fn migrate(value: Value) -> Result<Migrated> {moves: Vec::new(),embed_m1_brushes: false,}),- V2 | V3 | V4 | V5 | V6 | V7 => Ok(Migrated {+ V2 | V3 | V4 | V5 | V6 | V7 | V8 => Ok(Migrated {value: to_current(value),moves: Vec::new(),embed_m1_brushes: false,diff --git a/crates/core/src/ops.rs b/crates/core/src/ops.rsindex d97e59f..46281eb 100644--- a/crates/core/src/ops.rs+++ b/crates/core/src/ops.rs@@ -148,6 +148,9 @@ pub enum Op {Foliage(FoliageSpec),Grass(GrassSpec),PaintOver(PaintOverSpec),+ Bone(BoneSpec),+ Weights(WeightsSpec),+ Pose(PoseSpec),Clip(ClipEdit),Export {godot: Option<String>,@@ -207,6 +210,7 @@ pub struct TweenCel {pub marks: Vec<Mark>,pub fresh: bool,pub parts: BTreeMap<String, Vec<u32>>,+ pub pose: Option<crate::rig::Pose>,}#[derive(Clone, Debug, PartialEq)]@@ -617,6 +621,80 @@ pub struct GrassSpec {pub part: Option<String>,}+#[derive(Clone, Debug, PartialEq, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct BoneSpec {+ pub layer: String,+ #[serde(default)]+ pub add: Option<String>,+ #[serde(default)]+ pub rm: Option<String>,+ #[serde(default)]+ pub rename: Option<String>,+ #[serde(default, rename = "as")]+ pub to_name: Option<String>,+ #[serde(default, rename = "move")]+ pub moved: Option<String>,+ #[serde(default)]+ pub reparent: Option<String>,+ #[serde(default)]+ pub parent: Option<String>,+ #[serde(default)]+ pub head: Option<[f32; 2]>,+ #[serde(default)]+ pub tail: Option<[f32; 2]>,+}++#[derive(Clone, Debug, PartialEq, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct WeightsSpec {+ pub layer: String,+ #[serde(default)]+ pub frame: u32,+ #[serde(default)]+ pub auto: bool,+ #[serde(default)]+ pub bone: Option<String>,+ #[serde(default)]+ pub set: Vec<[f32; 4]>,+ #[serde(default)]+ pub part: Option<String>,+ #[serde(default = "full")]+ pub value: f32,+ #[serde(default)]+ pub smooth: bool,+ #[serde(skip)]+ pub resolved: Option<crate::rig::Weights>,+}++#[derive(Clone, Debug, PartialEq, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct PoseSpec {+ pub layer: String,+ #[serde(default)]+ pub from: u32,+ pub to: u32,+ #[serde(default)]+ pub bones: BTreeMap<String, f32>,+ #[serde(default)]+ pub root: [f32; 2],+ #[serde(default)]+ pub hold: Option<u32>,+ #[serde(skip)]+ pub resolved: Option<Vec<PosedCel>>,+}++#[derive(Clone, Debug, PartialEq)]+pub struct PosedCel {+ pub layer: String,+ pub cel: String,+ pub frame: u32,+ pub hold: Option<u32>,+ pub pose: crate::rig::Pose,+ pub marks: Vec<Mark>,+ pub fresh: bool,+}+#[derive(Clone, Debug, PartialEq, Deserialize)]#[serde(deny_unknown_fields)]pub struct PaintOverSpec {@@ -939,6 +1017,8 @@ pub struct Applied {pub dropped_cels: Vec<(String, String)>,pub marks: Vec<PendingMarks>,pub notes: Vec<String>,+ pub weights: Vec<(String, crate::rig::Weights)>,+ pub renamed_bones: Vec<(String, String, String)>,}impl Applied {@@ -1371,6 +1451,9 @@ impl Op {"scatter" => Op::Scatter(serde_json::from_value(Value::Object(std::mem::take(&mut map)))?),"foliage" => Op::Foliage(serde_json::from_value(Value::Object(std::mem::take(&mut map)))?),"paintover" => Op::PaintOver(serde_json::from_value(Value::Object(std::mem::take(&mut map)))?),+ "bone" => Op::Bone(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)))?),"clip" => Op::Clip(parse_clip(&mut map)?),"export" => Op::Export {@@ -1494,6 +1577,165 @@ fn parse_inbetween(map: &mut Map<String, Value>) -> Result<InbetweenSpec> {Ok(spec)}+pub fn rig_owner<'a>(doc: &'a Document, id: &str) -> Result<&'a Layer> {+ let layer = doc.find_layer(id)?;+ match layer.kind() {+ Kind::Paint | Kind::Group => Ok(layer),+ _ => bail!("bones go on a paint layer or a group; {} is neither", layer.name),+ }+}++fn bone(doc: &mut Document, spec: &BoneSpec, out: &mut Applied) -> Result<()> {+ let id = rig_owner(doc, &spec.layer)?.id.clone();+ let path = layer_path(doc, &id)?;+ let mut bones = doc.layer_at(&path).bones.clone();+ let find = |bones: &[crate::rig::Bone], name: &str| -> Result<usize> {+ bones.iter().position(|b| b.name == name).ok_or_else(|| {+ anyhow!(+ "no bone {name} on {}: {}",+ spec.layer,+ bones.iter().map(|b| b.name.as_str()).collect::<Vec<_>>().join(", ")+ )+ })+ };+ 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 {+ bail!("a new bone needs \"head\" and \"tail\": [x, y] each");+ };+ if bones.iter().any(|b| &b.name == name) {+ bail!("there is already a bone {name} on {}", spec.layer);+ }+ if let Some(p) = &spec.parent {+ find(&bones, p)?;+ }+ bones.push(crate::rig::Bone {+ name: name.clone(),+ parent: spec.parent.clone(),+ head,+ tail,+ });+ out.notes.push(format!("bone {name} on {}", spec.layer));+ }+ (None, Some(name), None, None, None) => {+ find(&bones, name)?;+ let mut gone = vec![name.clone()];+ while let Some(next) = bones+ .iter()+ .find(|b| b.parent.as_ref().is_some_and(|p| gone.contains(p)) && !gone.contains(&b.name))+ .map(|b| b.name.clone())+ {+ gone.push(next);+ }+ bones.retain(|b| !gone.contains(&b.name));+ out.notes.push(format!("removed {}", gone.join(", ")));+ }+ (None, None, Some(name), None, None) => {+ let Some(to) = &spec.to_name else {+ bail!("rename needs \"as\": the new name");+ };+ let at = find(&bones, name)?;+ if bones.iter().any(|b| &b.name == to) {+ bail!("there is already a bone {to}");+ }+ bones[at].name = to.clone();+ bones+ .iter_mut()+ .filter(|b| b.parent.as_ref() == Some(name))+ .for_each(|b| b.parent = Some(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() {+ cels.iter_mut().filter_map(|c| c.pose.as_mut()).for_each(|pose| {+ if let Some(v) = pose.angles.remove(name) {+ pose.angles.insert(to.clone(), v);+ }+ });+ }+ });+ out.renamed_bones.push((id.clone(), name.clone(), to.clone()));+ }+ (None, None, None, Some(name), None) => {+ let at = find(&bones, name)?;+ if let Some(h) = spec.head {+ bones[at].head = h;+ }+ if let Some(t) = spec.tail {+ bones[at].tail = t;+ }+ }+ (None, None, None, None, Some(name)) => {+ let at = find(&bones, name)?;+ if let Some(p) = &spec.parent {+ find(&bones, p)?;+ if p == name {+ bail!("a bone cannot be its own parent");+ }+ }+ bones[at].parent = spec.parent.clone();+ let mut sorted: Vec<crate::rig::Bone> = Vec::new();+ while sorted.len() < bones.len() {+ let before = sorted.len();+ bones.iter().for_each(|b| {+ let ready = b.parent.as_ref().is_none_or(|p| sorted.iter().any(|s| &s.name == p));+ if ready && !sorted.iter().any(|s| s.name == b.name) {+ sorted.push(b.clone());+ }+ });+ if sorted.len() == before {+ bail!("that parent would make a loop");+ }+ }+ bones = sorted;+ }+ _ => bail!("a bone op takes one of add, rm, rename, move or reparent"),+ }+ crate::rig::check(&bones)?;+ doc.layer_at_mut(&path).bones = bones;+ out.changed.push(id);+ Ok(())+}++fn posed(doc: &mut Document, made: &[PosedCel], out: &mut Applied) -> Result<()> {+ made.iter().try_for_each(|cel| {+ let path = layer_path(doc, &cel.layer)?;+ let cels = doc+ .layer_at_mut(&path)+ .cels_mut()+ .ok_or_else(|| anyhow!("layer {} has no cels", cel.layer))?;+ match cel.fresh {+ true => {+ if let Some(c) = cels.iter().find(|c| c.frame == cel.frame) {+ bail!("layer {} already has {} at frame {}", cel.layer, c.id, cel.frame);+ }+ let at = cels.iter().position(|c| c.frame > cel.frame).unwrap_or(cels.len());+ cels.insert(+ at,+ Cel {+ hold: cel.hold,+ pose: Some(cel.pose.clone()),+ ..Cel::at(&cel.cel, cel.frame)+ },+ );+ if let Some(n) = cel.cel.strip_prefix('c').and_then(|n| n.parse::<u64>().ok()) {+ doc.next_id = doc.next_id.max(n);+ }+ out.added.push(cel.cel.clone());+ }+ false => {+ let existing = cels+ .iter_mut()+ .find(|c| c.id == cel.cel)+ .ok_or_else(|| anyhow!("no cel {} on layer {}", cel.cel, cel.layer))?;+ existing.pose = Some(cel.pose.clone());+ out.changed.push(cel.cel.clone());+ }+ }+ out.push(&cel.layer, &cel.cel, MarkChange::Put(cel.marks.clone()));+ Ok(())+ })+}+fn inbetweens(doc: &mut Document, made: &Inbetweens, out: &mut Applied) -> Result<()> {made.removed.iter().try_for_each(|id| remove(doc, id, out))?;made.holds.iter().try_for_each(|(id, hold)| {@@ -1523,6 +1765,7 @@ fn inbetweens(doc: &mut Document, made: &Inbetweens, out: &mut Applied) -> Resulhold: cel.hold,tween: Some(cel.tween.clone()),parts: cel.parts.clone(),+ pose: cel.pose.clone(),..Cel::at(&cel.cel, cel.frame)},);@@ -1538,6 +1781,7 @@ fn inbetweens(doc: &mut Document, made: &Inbetweens, out: &mut Applied) -> Resul.ok_or_else(|| anyhow!("no cel {} on layer {}", cel.cel, cel.layer))?;existing.tween = Some(cel.tween.clone());existing.parts = cel.parts.clone();+ existing.pose = cel.pose.clone();out.changed.push(cel.cel.clone());}}@@ -2670,6 +2914,22 @@ pub fn apply(doc: &mut Document, op: &Op, out: &mut Applied) -> Result<()> {"ink, light, hatch, paint, scatter, foliage, grass and paintover are turned into strokes and fills by klad ink, klad light, klad hatch, klad paint, klad scatter, klad foliage, klad grass, klad paintover or klad apply first");}+ Op::Bone(spec) => bone(doc, spec, out)?,+ Op::Weights(spec) => {+ let Some(made) = &spec.resolved else {+ bail!("weights are computed by klad weights (or klad apply) first");+ };+ rig_owner(doc, &spec.layer)?;+ out.weights.retain(|(l, _)| l != &spec.layer);+ out.weights.push((spec.layer.clone(), made.clone()));+ out.changed.push(spec.layer.clone());+ }+ Op::Pose(spec) => {+ let Some(made) = &spec.resolved else {+ bail!("poses are computed by klad pose (or klad apply) first");+ };+ posed(doc, made, out)?;+ }Op::Inbetween(spec) => {let Some(made) = &spec.resolved else {bail!(diff --git a/crates/core/src/patch.rs b/crates/core/src/patch.rsindex 7932d13..27d9db2 100644--- a/crates/core/src/patch.rs+++ b/crates/core/src/patch.rs@@ -126,6 +126,7 @@ fn layer_shell(layer: &Layer) -> Layer {effects: layer.effects.clone(),depth: layer.depth,reference: layer.reference,+ bones: layer.bones.clone(),}}@@ -138,6 +139,7 @@ fn cel_shell(cel: &Cel) -> Cel {tween: cel.tween.clone(),nodes: Vec::new(),parts: cel.parts.clone(),+ pose: cel.pose.clone(),}}diff --git a/crates/core/src/rig.rs b/crates/core/src/rig.rsnew file mode 100644index 0000000..29cd846--- /dev/null+++ b/crates/core/src/rig.rs@@ -0,0 +1,573 @@+use crate::fill::{Coverage, FillSource};+use crate::stroke::{Mark, POS_SCALE};+use anyhow::{Context, Result, bail};+use serde::{Deserialize, Serialize};+use std::collections::BTreeMap;++pub const CELL: u32 = 4;++#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct Bone {+ pub name: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub parent: Option<String>,+ pub head: [f32; 2],+ pub tail: [f32; 2],+}++impl Bone {+ pub fn angle(&self) -> f32 {+ libm::atan2f(self.tail[1] - self.head[1], self.tail[0] - self.head[0])+ }++ pub fn length(&self) -> f32 {+ (self.tail[0] - self.head[0]).hypot(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])+ }+}++#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct Pose {+ pub rest: String,+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]+ pub angles: BTreeMap<String, f32>,+ #[serde(default, skip_serializing_if = "is_origin")]+ pub root: [f32; 2],+}++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 check(bones: &[Bone]) -> Result<()> {+ bones.iter().enumerate().try_for_each(|(i, b)| {+ if b.name.trim().is_empty() {+ bail!("a bone needs a name");+ }+ if bones[..i].iter().any(|o| o.name == b.name) {+ bail!("two bones are called {}", b.name);+ }+ if let Some(p) = &b.parent+ && !bones[..i].iter().any(|o| &o.name == p)+ {+ bail!("bone {}: its parent {p} must come before it", b.name);+ }+ if b.length() < 1e-3 {+ bail!("bone {}: its head and tail are the same point", b.name);+ }+ Ok(())+ })+}++type Mat = [f32; 6];++fn mul(a: Mat, b: Mat) -> Mat {+ [+ a[0] * b[0] + a[2] * b[1],+ a[1] * b[0] + a[3] * b[1],+ a[0] * b[2] + a[2] * b[3],+ a[1] * b[2] + a[3] * b[3],+ a[0] * b[4] + a[2] * b[5] + a[4],+ a[1] * b[4] + a[3] * b[5] + a[5],+ ]+}++fn invert(m: Mat) -> Mat {+ let det = m[0] * m[3] - m[1] * m[2];+ let d = if det.abs() < 1e-12 { 1.0 } else { 1.0 / det };+ let (a, b, c, e) = (m[3] * d, -m[1] * d, -m[2] * d, m[0] * d);+ [a, b, c, e, -(a * m[4] + c * m[5]), -(b * m[4] + e * m[5])]+}++fn placed(at: [f32; 2], angle: f32) -> Mat {+ let (s, c) = (libm::sinf(angle), libm::cosf(angle));+ [c, s, -s, c, at[0], at[1]]+}++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> {+ 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)) {+ 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)),+ };+ posed.push(world);+ });+ 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);+ bones+ .iter()+ .zip(&mats)+ .map(|(b, m)| (apply(*m, b.head), apply(*m, b.tail)))+ .collect()+}++#[derive(Clone, Debug, PartialEq)]+pub struct Weights {+ pub width: u32,+ pub height: u32,+ pub maps: BTreeMap<String, Vec<u8>>,+}++impl Weights {+ pub fn new(canvas: (u32, u32)) -> Self {+ Self {+ width: canvas.0.div_ceil(CELL),+ height: canvas.1.div_ceil(CELL),+ maps: BTreeMap::new(),+ }+ }++ pub fn dims(&self) -> (u32, u32) {+ (self.width, self.height)+ }++ pub fn encode(&self) -> Result<Vec<u8>> {+ let names: Vec<&String> = self.maps.keys().collect();+ let head = serde_json::json!({"width": self.width, "height": self.height, "bones": names});+ let mut raw = serde_json::to_vec(&head)?;+ raw.push(b'\n');+ self.maps.values().for_each(|m| raw.extend_from_slice(m));+ Ok(zstd::encode_all(&raw[..], 9)?)+ }++ pub fn decode(bytes: &[u8]) -> Result<Self> {+ let raw = zstd::decode_all(bytes)?;+ let split = raw+ .iter()+ .position(|&b| b == b'\n')+ .context("weights file without a header")?;+ let head: serde_json::Value = serde_json::from_slice(&raw[..split])?;+ let (width, height) = (+ head["width"].as_u64().unwrap_or(0) as u32,+ head["height"].as_u64().unwrap_or(0) as u32,+ );+ let n = (width * height) as usize;+ let names: Vec<String> = serde_json::from_value(head["bones"].clone())?;+ let body = &raw[split + 1..];+ if body.len() != n * names.len() {+ bail!("weights file is cut short");+ }+ Ok(Self {+ width,+ height,+ maps: names+ .into_iter()+ .enumerate()+ .map(|(i, name)| (name, body[i * n..(i + 1) * n].to_vec()))+ .collect(),+ })+ }++ fn map(&mut self, bone: &str) -> &mut Vec<u8> {+ let n = (self.width * self.height) as usize;+ self.maps.entry(bone.to_string()).or_insert_with(|| vec![0; n])+ }++ pub fn auto(bones: &[Bone], canvas: (u32, u32)) -> Self {+ let mut out = Self::new(canvas);+ let (w, h) = (out.width, out.height);+ let mut maps: Vec<Vec<u8>> = vec![vec![0; (w * h) as usize]; bones.len()];+ (0..h).for_each(|gy| {+ (0..w).for_each(|gx| {+ let p = [(gx as f32 + 0.5) * CELL as f32, (gy as f32 + 0.5) * CELL as f32];+ let raw: Vec<f32> = bones+ .iter()+ .map(|b| 1.0 / (b.distance(p) + b.length() * 0.15 + 1.0).powi(3))+ .collect();+ let sum: f32 = raw.iter().sum::<f32>().max(1e-12);+ raw.iter().enumerate().for_each(|(i, r)| {+ maps[i][(gy * w + gx) as usize] = (r / sum * 255.0).round() as u8;+ });+ })+ });+ out.maps = bones.iter().map(|b| b.name.clone()).zip(maps).collect();+ out+ }++ pub fn dab(&mut self, bone: &str, at: [f32; 2], radius: f32, value: f32) {+ let (w, h) = (self.width, self.height);+ let r = (radius / CELL as f32).max(0.5);+ let (cx, cy) = (at[0] / CELL as f32, at[1] / CELL as f32);+ let map = self.map(bone);+ let (x0, x1) = ((cx - r).floor().max(0.0) as u32, ((cx + r).ceil() as u32).min(w));+ let (y0, y1) = ((cy - r).floor().max(0.0) as u32, ((cy + r).ceil() as u32).min(h));+ (y0..y1).for_each(|y| {+ (x0..x1).for_each(|x| {+ let d = (x as f32 + 0.5 - cx).hypot(y as f32 + 0.5 - cy) / r;+ if d < 1.0 {+ let k = 1.0 - d * d * (3.0 - 2.0 * d);+ let v = &mut map[(y * w + x) as usize];+ let now = *v as f32 / 255.0;+ *v = ((now + (value.clamp(0.0, 1.0) - now) * k) * 255.0).round() as u8;+ }+ })+ });+ }++ pub fn fill(&mut self, bone: &str, cells: &[(u32, u32)], value: f32) {+ let w = self.width;+ let v = (value.clamp(0.0, 1.0) * 255.0).round() as u8;+ let map = self.map(bone);+ cells.iter().for_each(|&(x, y)| map[(y * w + x) as usize] = v);+ }++ pub fn smooth(&mut self) {+ let (w, h) = (self.width as i64, self.height as i64);+ self.maps.values_mut().for_each(|m| {+ let before = m.clone();+ (0..h).for_each(|y| {+ (0..w).for_each(|x| {+ let (sum, n) = (-1..=1)+ .flat_map(|dy| (-1..=1).map(move |dx| (dx, dy)))+ .map(|(dx, dy)| (x + dx, y + dy))+ .filter(|(x, y)| *x >= 0 && *y >= 0 && *x < w && *y < h)+ .fold((0u32, 0u32), |(s, n), (x, y)| {+ (s + before[(y * w + x) as usize] as u32, n + 1)+ });+ m[(y * w + x) as usize] = (sum / n.max(1)) as u8;+ })+ })+ });+ }++ pub fn at(&self, bones: &[Bone], p: [f32; 2]) -> Vec<f32> {+ let (gx, gy) = (p[0] / CELL as f32 - 0.5, p[1] / CELL as f32 - 0.5);+ let (x0, y0) = (gx.floor(), gy.floor());+ let (tx, ty) = (gx - x0, gy - y0);+ let (w, h) = (self.width as i64, self.height as i64);+ let get = |m: &Vec<u8>, x: i64, y: i64| m[(y.clamp(0, h - 1) * w + x.clamp(0, w - 1)) as usize] as f32 / 255.0;+ let raw: Vec<f32> = bones+ .iter()+ .map(|b| {+ self.maps.get(&b.name).map_or(0.0, |m| {+ let (x, y) = (x0 as i64, y0 as i64);+ let top = get(m, x, y) + (get(m, x + 1, y) - get(m, x, y)) * tx;+ let bottom = get(m, x, y + 1) + (get(m, x + 1, y + 1) - get(m, x, y + 1)) * tx;+ top + (bottom - top) * ty+ })+ })+ .collect();+ let sum: f32 = raw.iter().sum();+ match sum > 1e-4 {+ true => raw.iter().map(|r| r / sum).collect(),+ false => {+ let nearest = bones+ .iter()+ .enumerate()+ .min_by(|a, b| a.1.distance(p).total_cmp(&b.1.distance(p)))+ .map_or(0, |(i, _)| i);+ (0..bones.len()).map(|i| if i == nearest { 1.0 } else { 0.0 }).collect()+ }+ }+ }+}++pub struct Rig<'a> {+ pub bones: &'a [Bone],+ pub weights: &'a Weights,+ pub mats: Vec<Mat>,+}++impl<'a> Rig<'a> {+ pub fn new(bones: &'a [Bone], weights: &'a Weights, pose: &Pose) -> Self {+ Self {+ bones,+ weights,+ mats: skinning(bones, pose),+ }+ }++ pub fn moved(&self, p: [f32; 2]) -> [f32; 2] {+ let w = self.weights.at(self.bones, p);+ w.iter()+ .zip(&self.mats)+ .filter(|(k, _)| **k > 0.0)+ .fold([0.0, 0.0], |acc, (k, m)| {+ let q = apply(*m, p);+ [acc[0] + q[0] * k, acc[1] + q[1] * k]+ })+ }++ fn stretch(&self, p: [f32; 2]) -> f32 {+ let (o, x, y) = (+ self.moved(p),+ self.moved([p[0] + 1.0, p[1]]),+ self.moved([p[0], p[1] + 1.0]),+ );+ let det = (x[0] - o[0]) * (y[1] - o[1]) - (x[1] - o[1]) * (y[0] - o[0]);+ det.abs().sqrt().clamp(0.25, 4.0)+ }++ fn coverage(&self, c: &Coverage, canvas: (u32, u32)) -> Coverage {+ if c.is_empty() {+ return c.clone();+ }+ let step = 4u32;+ let (cols, rows) = (c.width.div_ceil(step) + 1, c.height.div_ceil(step) + 1);+ let rest = |i: u32, j: u32| {+ [+ (c.x + (i * step).min(c.width)) as f32,+ (c.y + (j * step).min(c.height)) as f32,+ ]+ };+ let posed: Vec<[f32; 2]> = (0..rows)+ .flat_map(|j| (0..cols).map(move |i| (i, j)))+ .map(|(i, j)| self.moved(rest(i, j)))+ .collect();+ let (w, h) = (canvas.0 as usize, canvas.1 as usize);+ let mut mask = vec![0u8; w * h];+ let sample = |p: [f32; 2]| -> u8 {+ let (x, y) = (p[0].floor(), p[1].floor());+ match x >= 0.0 && y >= 0.0 {+ true => c.at(x as u32, y as u32),+ false => 0,+ }+ };+ (0..rows - 1).for_each(|j| {+ (0..cols - 1).for_each(|i| {+ let corner = |di: u32, dj: u32| ((i + di, j + dj), posed[((j + dj) * cols + i + di) as usize]);+ [+ [corner(0, 0), corner(1, 0), corner(1, 1)],+ [corner(0, 0), corner(1, 1), corner(0, 1)],+ ]+ .iter()+ .for_each(|tri| {+ let [a, b, d] = [tri[0].1, tri[1].1, tri[2].1];+ let area = (b[0] - a[0]) * (d[1] - a[1]) - (b[1] - a[1]) * (d[0] - a[0]);+ if area.abs() < 1e-6 {+ return;+ }+ let lo = [+ a[0].min(b[0]).min(d[0]).floor().max(0.0),+ a[1].min(b[1]).min(d[1]).floor().max(0.0),+ ];+ let hi = [+ a[0].max(b[0]).max(d[0]).ceil().min(w as f32),+ a[1].max(b[1]).max(d[1]).ceil().min(h as f32),+ ];+ let rests = [+ rest(tri[0].0.0, tri[0].0.1),+ rest(tri[1].0.0, tri[1].0.1),+ rest(tri[2].0.0, tri[2].0.1),+ ];+ (lo[1] as usize..hi[1] as usize).for_each(|y| {+ (lo[0] as usize..hi[0] as usize).for_each(|x| {+ let p = [x as f32 + 0.5, y as f32 + 0.5];+ let u = ((b[0] - p[0]) * (d[1] - p[1]) - (b[1] - p[1]) * (d[0] - p[0])) / area;+ let v = ((d[0] - p[0]) * (a[1] - p[1]) - (d[1] - p[1]) * (a[0] - p[0])) / area;+ let k = 1.0 - u - v;+ if u < -1e-4 || v < -1e-4 || k < -1e-4 {+ return;+ }+ let q = [+ rests[0][0] * u + rests[1][0] * v + rests[2][0] * k,+ rests[0][1] * u + rests[1][1] * v + rests[2][1] * k,+ ];+ let m = &mut mask[y * w + x];+ *m = (*m).max(sample(q));+ })+ });+ });+ })+ });+ Coverage::from_mask(canvas.0, canvas.1, &mask)+ }++ pub fn pose(&self, marks: &[Mark], canvas: (u32, u32)) -> Vec<Mark> {+ if self.mats.iter().all(|m| {+ *m == [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]+ || m.iter()+ .zip([1.0, 0.0, 0.0, 1.0, 0.0, 0.0])+ .all(|(a, b)| (a - b).abs() < 1e-5)+ }) {+ return marks.to_vec();+ }+ marks+ .iter()+ .map(|mark| {+ let mut out = mark.clone();+ match &mut out {+ Mark::Stroke(s) => {+ let n = s.samples.len().max(1) as f32;+ let stretch = s.samples.iter().map(|q| self.stretch(q.pos().into())).sum::<f32>() / n;+ s.samples.iter_mut().for_each(|q| {+ let (x, y) = q.pos();+ let p = self.moved([x, y]);+ q.x = (p[0] * POS_SCALE).round() as i32;+ q.y = (p[1] * POS_SCALE).round() as i32;+ });+ s.size *= stretch;+ }+ Mark::Fill(f) => {+ if let FillSource::Polygon(points) = &mut f.source {+ points.iter_mut().for_each(|p| *p = self.moved(*p));+ }+ if let FillSource::Seed { seed, .. } = &mut f.source {+ let p = self.moved([seed.x, seed.y]);+ (seed.x, seed.y) = (p[0], p[1]);+ }+ f.coverage = self.coverage(&f.coverage, canvas);+ }+ }+ out+ })+ .collect()+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::stroke::Stroke;++ fn leg() -> Vec<Bone> {+ vec![+ Bone {+ name: "thigh".into(),+ parent: None,+ head: [100.0, 100.0],+ tail: [100.0, 200.0],+ },+ Bone {+ name: "shin".into(),+ parent: Some("thigh".into()),+ head: [100.0, 200.0],+ tail: [100.0, 300.0],+ },+ ]+ }++ #[test]+ fn automatic_weights_add_up_and_fall_off_across_the_joint() {+ let bones = leg();+ let w = Weights::auto(&bones, (200, 400));+ let at = |y: f32| w.at(&bones, [100.0, y]);+ assert!(+ at(130.0)[0] > 0.9 && at(270.0)[1] > 0.9,+ "{:?} {:?}",+ at(130.0),+ at(270.0)+ );+ let joint = at(200.0);+ assert!((joint[0] - 0.5).abs() < 0.15, "{joint:?}");+ assert!(((joint[0] + joint[1]) - 1.0).abs() < 1e-3);+ let back = Weights::decode(&w.encode().unwrap()).unwrap();+ assert_eq!(back, w);+ }++ #[test]+ fn a_painted_dab_changes_only_near_it() {+ let bones = leg();+ let mut w = Weights::auto(&bones, (200, 400));+ let before = w.clone();+ w.dab("thigh", [100.0, 260.0], 16.0, 1.0);+ assert!(w.at(&bones, [100.0, 260.0])[0] > before.at(&bones, [100.0, 260.0])[0] + 0.3);+ assert_eq!(w.at(&bones, [100.0, 120.0]), before.at(&bones, [100.0, 120.0]));+ let changed: Vec<usize> = (0..w.maps["thigh"].len())+ .filter(|&i| w.maps["thigh"][i] != before.maps["thigh"][i])+ .collect();+ assert!(!changed.is_empty());+ assert!(changed.iter().all(|&i| {+ let (x, y) = ((i as u32 % w.width) * CELL, (i as u32 / w.width) * CELL);+ (x as f32 - 100.0).hypot(y as f32 - 260.0) <= 16.0 + CELL as f32 * 1.5+ }));+ }++ #[test]+ fn a_bent_knee_bends_a_line_smoothly_and_the_rest_pose_changes_nothing() {+ let bones = leg();+ let weights = Weights::auto(&bones, (200, 400));+ let points: Vec<(f32, f32, f32)> = (0..=40).map(|i| (100.0, 100.0 + i as f32 * 5.0, 1.0)).collect();+ 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());+ 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 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];+ let expected = [+ 100.0 - 100.0 * 60f32.to_radians().sin(),+ 200.0 + 100.0 * 60f32.to_radians().cos(),+ ];+ assert!(+ (end.0 - expected[0]).abs() < 3.0 && (end.1 - expected[1]).abs() < 3.0,+ "{end:?} {expected:?}"+ );+ let turns: Vec<f32> = pts+ .windows(3)+ .map(|w| {+ let a = libm::atan2f(w[1].1 - w[0].1, w[1].0 - w[0].0);+ let b = libm::atan2f(w[2].1 - w[1].1, w[2].0 - w[1].0);+ (b - a).abs()+ })+ .collect();+ assert!(turns.iter().all(|t| *t < 20f32.to_radians()), "no kink: {turns:?}");+ assert!(+ turns.iter().filter(|t| **t > 2f32.to_radians()).count() >= 4,+ "the bend spreads: {turns:?}"+ );+ let mut rigid = Weights::new((200, 400));+ rigid.fill(+ "thigh",+ &(0..100).flat_map(|y| (0..50).map(move |x| (x, y))).collect::<Vec<_>>(),+ 1.0,+ );+ 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 s = moved[0].as_stroke().unwrap();+ let (a, b) = (s.samples[0].pos(), s.samples[s.samples.len() - 1].pos());+ assert!(+ ((b.0 - a.0).hypot(b.1 - a.1) - 200.0).abs() < 1.0,+ "a mark held by one bone moves rigidly"+ );+ }+}diff --git a/crates/render/src/overlay.rs b/crates/render/src/overlay.rsindex 5d3a9d5..fb44ba4 100644--- a/crates/render/src/overlay.rs+++ b/crates/render/src/overlay.rs@@ -119,6 +119,60 @@ pub struct Overlay {pub arcs: Vec<Arc>,pub frame: Option<u32>,pub numbers: bool,+ pub bones: Vec<Shown>,+ pub heat: Option<Heat>,+}++pub type Shown = (String, [f32; 2], [f32; 2]);++#[derive(Clone, Debug, Default)]+pub struct Heat {+ pub cell: f32,+ pub width: u32,+ pub values: Vec<u8>,+}++fn draw_heat(canvas: &Canvas, heat: &Heat, to_out: impl Fn([f32; 2]) -> (f32, f32)) {+ let w = heat.width.max(1) as usize;+ heat.values+ .iter()+ .enumerate()+ .filter(|(_, v)| **v > 0)+ .for_each(|(i, v)| {+ let (gx, gy) = ((i % w) as f32 * heat.cell, (i / w) as f32 * heat.cell);+ let (x0, y0) = to_out([gx, gy]);+ let (x1, y1) = to_out([gx + heat.cell, gy + heat.cell]);+ let t = *v as f32 / 255.0;+ canvas.draw_rect(+ Rect::from_ltrb(x0, y0, x1, y1),+ &color([0.95, 0.25 + 0.6 * t, 0.15], 0.15 + 0.45 * t),+ );+ });+}++fn draw_bones(+ canvas: &Canvas,+ bones: &[(String, [f32; 2], [f32; 2])],+ to_out: impl Fn([f32; 2]) -> (f32, f32),+ px: f32,+) {+ bones.iter().enumerate().for_each(|(i, (name, head, tail))| {+ let (a, b) = (to_out(*head), to_out(*tail));+ let hue = HUES[(i + 1) % HUES.len()];+ let mut back = color([0.0, 0.0, 0.0], 0.6);+ back.set_style(PaintStyle::Stroke);+ back.set_stroke_width(5.0 * px);+ back.set_stroke_cap(skia_safe::paint::Cap::Round);+ let mut front = color(hue, 1.0);+ front.set_style(PaintStyle::Stroke);+ front.set_stroke_width(2.5 * px);+ front.set_stroke_cap(skia_safe::paint::Cap::Round);+ canvas.draw_line(a, b, &back);+ canvas.draw_line(a, b, &front);+ canvas.draw_circle(a, 4.0 * px, &color([0.0, 0.0, 0.0], 0.7));+ canvas.draw_circle(a, 2.5 * px, &color(hue, 1.0));+ draw_label(canvas, name, (a.0 + b.0) / 2.0 + 4.0, (a.1 + b.1) / 2.0, px, hue);+ });}fn draw_arcs(canvas: &Canvas, overlay: &Overlay, to_out: impl Fn([f32; 2]) -> (f32, f32), px: f32) {@@ -279,7 +333,16 @@ pub fn apply(image: &skia_safe::Image, overlay: &Overlay, view: &View) -> Resultcanvas.draw_rect(rect, &front);});}+ if let Some(heat) = &overlay.heat {+ draw_heat(canvas, heat, |p| ((p[0] - origin.0) * s, (p[1] - origin.1) * s));+ }draw_arcs(canvas, overlay, |p| ((p[0] - origin.0) * s, (p[1] - origin.1) * s), px);+ draw_bones(+ canvas,+ &overlay.bones,+ |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)| {