A drawing app built for agent/human collaboration
Rust
Paint over and compare
Indicode BV04adfe7c8643
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 821f0af..2182816 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,8 @@ The first downloadable builds.- `klad --version` and About show the commit a build was made from.- In-betweens blend colours evenly (in OKLab), so light can follow a turning limb when the second key is coloured for it.- `klad arcs` follows the part of a foot on the ground: a heel-to-toe roll is no longer reported as a slide.+- `klad paintover` (and "paint over" in the layers panel): brushwork from any picture, strokes that follow its forms and stop at its colour edges, big to small, detail where the picture has it; `--like` and `--frames` carry it through an animation without boiling.+- `klad compare` (and "compare with the reference" in the editor): a drawing against a reference picture in numbers and words, with a heat map.- Large stills render several times faster: strokes land only where they painted, and the CLI replays a drawing's tiles on every core (same pixels).## 0.1.0 (2026-11-04)diff --git a/README.md b/README.mdindex a7a6a76..75412dd 100644--- a/README.md+++ b/README.md@@ -61,7 +61,7 @@ Building takes about ten minutes the first time.1. Install Rust with [rustup](https://rustup.rs) and [`just`](https://github.com/casey/just) (`brew install just`, or `cargo install just`). On Linux also `pkg-config`, `libfreetype-dev`, `libfontconfig1-dev`, `libxkbcommon-dev` and `libwayland-dev`.2. `git clone https://github.com/klad-app/klad && cd klad`, then `just build` makes `klad` and `klad-editor` in `target/release/` (on Linux in `target/linux/release/`).3. `target/release/klad open` starts the editor on its start window: make a drawing and start painting.-4. `just samples` builds the sample drawings in `samples/` (a lantern, a walking creature, a running courier, an underground ruin, an inn sign, a tree, a meadow, painted solids, a bowl of lemons, a bouncing ball, ink examples); open one with `target/release/klad open samples/lantern/lantern.draw`.+4. `just samples` builds the sample drawings in `samples/` (a lantern, a walking creature, a running courier, an underground ruin, an inn sign, a tree, a meadow, painted solids, a bowl of lemons and the same painted over with brushwork, a bouncing ball, ink examples); open one with `target/release/klad open samples/lantern/lantern.draw`.5. `just app` makes `klad.app` and a disk image on a Mac; `just dist` makes the archive for the machine you are on (`just dist x86_64-pc-windows-msvc` for another target).## Drawing with an agentdiff --git a/crates/app/src/commands.rs b/crates/app/src/commands.rsindex 520134b..9a6c88a 100644--- a/crates/app/src/commands.rs+++ b/crates/app/src/commands.rs@@ -148,6 +148,8 @@ pub enum Cmd {OpenRecent,CopyPath,InstallCommand,+ PaintOver,+ CompareReference,About,Export,AddFont,@@ -470,7 +472,7 @@ use Repeat as R;use Trigger as T;impl Cmd {- pub const ALL: [Cmd; 152] = [+ pub const ALL: [Cmd; 154] = [Cmd::Brush,Cmd::Eraser,Cmd::Fill,@@ -620,9 +622,11 @@ impl Cmd {Cmd::AddFont,Cmd::Refill,Cmd::FillLike,+ Cmd::PaintOver,Cmd::ShowGaps,Cmd::ShowParts,Cmd::ShowArcs,+ Cmd::CompareReference,];pub fn spec(self) -> Spec {@@ -1968,6 +1972,24 @@ impl Cmd {R::No,"the version, the licence and every open source part it is built on",),+ Cmd::CompareReference => spec(+ "view.compare",+ "compare with the reference",+ icon::INFO,+ G::View,+ T::None,+ R::No,+ "measure this frame against the reference picture: values, saturation, texture, edges, and where they differ",+ ),+ Cmd::PaintOver => spec(+ "layer.paint-over",+ "paint over",+ icon::BRUSH,+ G::Layers,+ T::None,+ R::No,+ "repaint what is below this layer with brush strokes that follow its forms, and carry them through an animation",+ ),Cmd::InstallCommand => spec("file.install-command","install the klad command",diff --git a/crates/app/src/editor.rs b/crates/app/src/editor.rsindex 5fba39b..56c57e2 100644--- a/crates/app/src/editor.rs+++ b/crates/app/src/editor.rs@@ -5,6 +5,7 @@ mod cells;mod checks;mod clips;mod commands;+mod compare;mod copy;mod depth;mod export;@@ -13,6 +14,7 @@ mod layers;mod look;mod make;mod options;+mod paintover;mod panels;mod pins;mod prefs;@@ -507,6 +509,8 @@ struct Windows {about: bool,export: bool,font: bool,+ paintover: bool,+ compare: bool,}#[derive(Default)]@@ -603,6 +607,8 @@ pub(crate) struct Editor {between: between::Between,checks: checks::Checks,export: export::Form,+ paintover: paintover::Form,+ compare: Option<compare::Compared>,bindings: crate::commands::Bindings,capturing: Option<Cmd>,key_filter: String,@@ -760,6 +766,8 @@ impl Editor {between: between::Between::default(),checks: checks::Checks::default(),export: export::Form::default(),+ paintover: paintover::Form::default(),+ compare: None,bindings: crate::commands::Bindings::default(),capturing: None,key_filter: String::new(),diff --git a/crates/app/src/editor/checks.rs b/crates/app/src/editor/checks.rsindex 1bc62c4..b58e489 100644--- a/crates/app/src/editor/checks.rs+++ b/crates/app/src/editor/checks.rs@@ -401,6 +401,7 @@ impl Editor {let track = name.trim_start_matches("arcs of ");self.checks.arcs = arcs_from(output, track);}+ Tag::Compare => self.compared(output),_ => {}}}diff --git a/crates/app/src/editor/commands.rs b/crates/app/src/editor/commands.rsindex 6c690a6..4317f71 100644--- a/crates/app/src/editor/commands.rs+++ b/crates/app/src/editor/commands.rs@@ -273,6 +273,9 @@ impl Editor {.then(|| "the gaps are being looked for".to_string()),Cmd::ShowArcs if self.checks.arcs.is_some() => None,Cmd::ShowArcs => self.track().err().map(|e| e.to_string()),+ Cmd::CompareReference => super::compare::reference_image(&self.scene.bundle.root, &self.scene.bundle.doc)+ .is_none()+ .then(|| "add a reference picture first: a picture layer marked as a reference".to_string()),Cmd::ExportGodot => {if self.jobs.busy(crate::jobs::Tag::Export) {Some("an export is running".into())@@ -340,6 +343,8 @@ impl Editor {Cmd::About => self.windows.about,Cmd::Export => self.windows.export,Cmd::AddFont => self.windows.font,+ Cmd::PaintOver => self.windows.paintover,+ Cmd::CompareReference => self.windows.compare,Cmd::ShowGaps => self.checks.gaps.is_some(),Cmd::ShowParts => self.checks.parts,Cmd::ShowArcs => self.checks.arcs.is_some(),@@ -583,6 +588,8 @@ impl Editor {Cmd::About => self.windows.about = !self.windows.about,Cmd::Export => self.windows.export = !self.windows.export,Cmd::AddFont => self.windows.font = !self.windows.font,+ Cmd::PaintOver => self.windows.paintover = !self.windows.paintover,+ Cmd::CompareReference => self.compare_reference()?,Cmd::Refill => self.refill()?,Cmd::FillLike => self.fill_like()?,Cmd::ShowGaps => self.show_gaps()?,diff --git a/crates/app/src/editor/compare.rs b/crates/app/src/editor/compare.rsnew file mode 100644index 0000000..b17d1b5--- /dev/null+++ b/crates/app/src/editor/compare.rs@@ -0,0 +1,168 @@+use super::Editor;+use crate::jobs::{Spec, Tag};+use crate::messages::Tone;+use crate::theme::Hint;+use anyhow::{Context, Result};+use klad_core::doc::{Kind, Shape};+use serde_json::Value;+use std::path::{Path, PathBuf};++pub(super) struct Compared {+ pub report: Value,+ pub heat: Option<egui::TextureHandle>,+}++pub(super) fn reference_image(root: &Path, doc: &klad_core::doc::Document) -> Option<PathBuf> {+ doc.all_layers()+ .into_iter()+ .filter(|l| l.reference && l.kind() == Kind::Vector)+ .flat_map(|l| l.cels().iter())+ .flat_map(|c| c.nodes.iter())+ .find_map(|n| match &n.shape {+ Shape::Image(p) => Some(root.join(klad_render::assets::IMAGES).join(&p.src)),+ _ => None,+ })+}++pub(super) fn args(bundle: &Path, reference: &Path, frame: u32, heat: &Path) -> Vec<String> {+ vec![+ "compare".into(),+ bundle.to_string_lossy().to_string(),+ reference.to_string_lossy().to_string(),+ "--frame".into(),+ frame.to_string(),+ "--json".into(),+ "--heat".into(),+ heat.to_string_lossy().to_string(),+ ]+}++fn heat_texture(ctx: &egui::Context, path: &str) -> Option<egui::TextureHandle> {+ let bytes = std::fs::read(path).ok()?;+ let rgba = klad_render::assets::decode(&bytes).ok()?;+ let image = egui::ColorImage::from_rgba_unmultiplied([rgba.width as usize, rgba.height as usize], &rgba.pixels);+ Some(ctx.load_texture("compare heat", image, egui::TextureOptions::LINEAR))+}++impl Editor {+ pub(super) fn compare_reference(&mut self) -> Result<()> {+ let root = self.scene.bundle.root.clone();+ let reference = reference_image(&root, &self.scene.bundle.doc)+ .context("add a reference picture first: a picture layer marked as a reference")?;+ let heat = self.scene.bundle.cache_dir().join("compare-heat.png");+ self.start_job(Spec {+ tag: Tag::Compare,+ name: "compare with the reference".into(),+ exe: PathBuf::new(),+ args: args(&root, &reference, self.scene.frame, &heat),+ env: Vec::new(),+ reruns: 0,+ summary: |out, _| {+ serde_json::from_str::<Value>(out)+ .ok()+ .and_then(|v| {+ v["words"]+ .as_array()+ .map(|w| w.iter().filter_map(Value::as_str).collect::<Vec<_>>().join(", "))+ })+ .unwrap_or_default()+ },+ failure: |_, err| err.lines().last().unwrap_or_default().to_string(),+ });+ Ok(())+ }++ pub(super) fn compared(&mut self, output: &str) {+ match serde_json::from_str::<Value>(output) {+ Ok(report) => {+ let heat = report["heat"].as_str().and_then(|p| heat_texture(&self.ctx, p));+ self.compare = Some(Compared { report, heat });+ self.windows.compare = true;+ }+ Err(e) => self.say(Tone::Error, format!("the comparison could not be read: {e}")),+ }+ }++ pub(super) fn compare_window(&mut self, ui: &mut egui::Ui) -> Result<()> {+ let Some(compared) = &self.compare else {+ ui.label("Compare runs against the drawing's reference picture.");+ return Ok(());+ };+ let r = &compared.report;+ let number = |v: &Value| v.as_f64().map_or("-".to_string(), |n| format!("{n:.1}"));+ let range = |v: &Value| {+ v.as_array()+ .map(|a| a.iter().map(number).collect::<Vec<_>>().join(" / "))+ .unwrap_or_default()+ };+ egui::Grid::new("compare numbers").num_columns(3).show(ui, |ui| {+ ui.label("");+ ui.strong("yours");+ ui.strong("reference");+ ui.end_row();+ ui.label("value L")+ .hint("lightness at the 5th, 50th and 95th percentile, 0 to 100");+ ui.label(range(&r["yours"]["value"]));+ ui.label(range(&r["reference"]["value"]));+ ui.end_row();+ [+ ("chroma", "how saturated, on average"),+ ("texture", "how busy the strokes are"),+ ("sharpness", "how hard the hardest edges are"),+ ]+ .iter()+ .for_each(|(key, hint)| {+ ui.label(*key).hint(*hint);+ ui.label(number(&r["yours"][key]));+ ui.label(number(&r["reference"][key]));+ ui.end_row();+ });+ });+ let words: Vec<&str> = r["words"]+ .as_array()+ .map_or_else(Vec::new, |w| w.iter().filter_map(Value::as_str).collect());+ ui.label(format!("difference {}: {}", number(&r["difference"]), words.join(", ")));+ if let Some(heat) = &compared.heat {+ let size = heat.size_vec2();+ let scale = (320.0 / size.x.max(1.0)).min(1.0);+ ui.image((heat.id(), size * scale))+ .hint("where they differ most: black is the same, red, yellow and white differ more");+ }+ if ui.button("compare again").hint("after painting more").clicked() {+ self.compare_reference()?;+ }+ Ok(())+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn the_window_builds_the_cli_compare_and_finds_the_reference() {+ let joined = args(+ Path::new("/w/a.draw"),+ Path::new("/w/a.draw/images/f.png"),+ 2,+ Path::new("/w/h.png"),+ )+ .join(" ");+ assert_eq!(+ joined,+ "compare /w/a.draw /w/a.draw/images/f.png --frame 2 --json --heat /w/h.png"+ );+ let mut doc = klad_core::doc::Document::new(100, 100);+ assert!(reference_image(Path::new("/w/a.draw"), &doc).is_none());+ let node: klad_core::doc::Node =+ serde_json::from_value(serde_json::json!({"id": "n1", "type": "image", "src": "f.png", "w": 10, "h": 10}))+ .unwrap();+ let mut layer = klad_core::doc::Layer::vector("l1", "photo", "c1", vec![node]);+ layer.reference = true;+ doc.layers = vec![layer];+ assert_eq!(+ reference_image(Path::new("/w/a.draw"), &doc),+ Some(PathBuf::from("/w/a.draw/images/f.png"))+ );+ }+}diff --git a/crates/app/src/editor/layers.rs b/crates/app/src/editor/layers.rsindex 70df220..cc086e0 100644--- a/crates/app/src/editor/layers.rs+++ b/crates/app/src/editor/layers.rs@@ -559,6 +559,7 @@ impl Editor {(Cmd::DuplicateLayer, None),(Cmd::GroupLayer, None),(Cmd::DeleteLayer, None),+ (Cmd::PaintOver, Some("paint over")),].into_iter().for_each(|(cmd, label)| {diff --git a/crates/app/src/editor/paintover.rs b/crates/app/src/editor/paintover.rsnew file mode 100644index 0000000..077637d--- /dev/null+++ b/crates/app/src/editor/paintover.rs@@ -0,0 +1,229 @@+use super::Editor;+use crate::jobs::{Spec, Tag};+use crate::theme::Hint;+use anyhow::{Result, bail};+use std::path::{Path, PathBuf};++#[derive(Clone, Debug, PartialEq)]+pub(super) struct Form {+ pub sizes: String,+ pub threshold: f32,+ pub length: [f32; 2],+ pub curve: f32,+ pub brush: String,+ pub vary: f32,+ pub within: String,+ pub focus: String,+ pub seed: u32,+ pub until: String,+}++impl Default for Form {+ fn default() -> Self {+ Self {+ sizes: "32,16,8".into(),+ threshold: 6.0,+ length: [1.0, 8.0],+ curve: 0.5,+ brush: "oil".into(),+ vary: 0.025,+ within: String::new(),+ focus: String::new(),+ seed: 1,+ until: String::new(),+ }+ }+}++pub(super) fn args(bundle: &Path, layer: &str, frame: u32, form: &Form, like: Option<(&str, String)>) -> Vec<String> {+ let mut args = vec![+ "paintover".to_string(),+ bundle.to_string_lossy().to_string(),+ layer.to_string(),+ "--frame".into(),+ frame.to_string(),+ "--sizes".into(),+ form.sizes.trim().replace(' ', ""),+ "--threshold".into(),+ form.threshold.to_string(),+ "--length".into(),+ format!("{},{}", form.length[0], form.length[1]),+ "--curve".into(),+ form.curve.to_string(),+ "--brush".into(),+ form.brush.clone(),+ "--vary".into(),+ form.vary.to_string(),+ "--seed".into(),+ form.seed.to_string(),+ ];+ [("--in", &form.within), ("--focus", &form.focus)]+ .iter()+ .filter(|(_, v)| !v.trim().is_empty())+ .for_each(|(k, v)| args.extend([k.to_string(), v.trim().to_string()]));+ if let Some((cel, frames)) = like {+ args.extend(["--like".into(), cel.to_string(), "--frames".into(), frames]);+ }+ args+}++impl Editor {+ fn paint_over(&mut self, carry: bool) -> Result<()> {+ let Some(layer) = self+ .scene+ .active_layer()+ .filter(|l| l.kind() == klad_core::doc::Kind::Paint)+ else {+ bail!("pick the paint layer to paint on first; paint over paints what is below it");+ };+ let form = self.paintover.clone();+ if form+ .sizes+ .split(',')+ .any(|s| s.trim().parse::<f32>().map_or(true, |v| v <= 0.0))+ {+ bail!("brush sizes are numbers above 0, biggest first: 32,16,8");+ }+ let frame = self.scene.frame;+ let like = match carry {+ false => None,+ true => {+ let Some(cel) = layer.content_at(frame) else {+ bail!(+ "paint over this drawing first: there is no drawing on {} here to carry",+ layer.name+ );+ };+ let last = match form.until.trim().parse::<u32>() {+ Ok(f) => f,+ Err(_) => self+ .current_clip()+ .map_or(self.scene.bundle.doc.timeline.frames.saturating_sub(1), |c| c.to),+ };+ Some((cel.id.clone(), format!("{frame}-{last}")))+ }+ };+ let name = match &like {+ Some((_, frames)) => format!("carry the paint-over on {} over frames {frames}", layer.name),+ None => format!("paint over on {} at frame {frame}", layer.name),+ };+ let args = args(+ &self.scene.bundle.root,+ &layer.id,+ frame,+ &form,+ like.as_ref().map(|(c, f)| (c.as_str(), f.clone())),+ );+ self.start_job(Spec {+ tag: Tag::Edit,+ name,+ exe: PathBuf::new(),+ args,+ env: Vec::new(),+ reruns: 3,+ summary: |_, err| err.lines().last().unwrap_or_default().to_string(),+ failure: |_, err| super::tweens::failure(err),+ });+ Ok(())+ }++ pub(super) fn paintover_window(&mut self, ui: &mut egui::Ui) -> Result<()> {+ let mut run = None;+ let form = &mut self.paintover;+ ui.label(+ "Repaints what is below the active layer with brush strokes that follow its forms, big brushes first.",+ );+ ui.horizontal(|ui| {+ let label = ui.label("brush sizes");+ ui.add(egui::TextEdit::singleline(&mut form.sizes).desired_width(90.0))+ .labelled_by(label.id)+ .hint("px, biggest first; smaller ones only go where detail is left");+ let label = ui.label("brush");+ ui.add(egui::TextEdit::singleline(&mut form.brush).desired_width(90.0))+ .labelled_by(label.id)+ .hint("any brush id of this drawing or the library");+ });+ ui.add(egui::Slider::new(&mut form.threshold, 1.0..=25.0).text("how close"))+ .hint("lower paints more and smaller strokes, until the painting is this close to the source");+ ui.horizontal(|ui| {+ ui.add(+ egui::DragValue::new(&mut form.length[0])+ .range(0.0..=20.0)+ .speed(0.1)+ .prefix("length "),+ )+ .hint("the shortest stroke, in brush widths");+ ui.add(+ egui::DragValue::new(&mut form.length[1])+ .range(1.0..=40.0)+ .speed(0.1)+ .prefix("to "),+ )+ .hint("the longest stroke, in brush widths");+ });+ ui.add(egui::Slider::new(&mut form.curve, 0.0..=1.0).text("follow the forms"))+ .hint("0 straight strokes, 1 strokes that turn with every bend");+ ui.add(egui::Slider::new(&mut form.vary, 0.0..=0.1).text("break the colour"))+ .hint("each stroke a little warmer or cooler, lighter or darker");+ ui.horizontal(|ui| {+ let label = ui.label("only in");+ ui.add(+ egui::TextEdit::singleline(&mut form.within)+ .desired_width(110.0)+ .hint_text("all"),+ )+ .labelled_by(label.id)+ .hint("ids of closed shapes to paint inside, with commas");+ let label = ui.label("detail near");+ ui.add(+ egui::TextEdit::singleline(&mut form.focus)+ .desired_width(80.0)+ .hint_text("anywhere"),+ )+ .labelled_by(label.id)+ .hint("a closed shape: the smallest brush only works in and near it");+ });+ ui.add(egui::DragValue::new(&mut form.seed).prefix("seed "))+ .hint("another seed paints other strokes the same way");+ ui.horizontal(|ui| {+ if ui.button("paint over this drawing").hint("klad paintover, one undo step").clicked() {+ run = Some(false);+ }+ if ui+ .button("carry it to the next drawings")+ .hint("each later drawing up to the end of the clip takes this one's strokes, moved with the drawing under them, so animation does not boil")+ .clicked()+ {+ run = Some(true);+ }+ let label = ui.label("until frame");+ ui.add(egui::TextEdit::singleline(&mut form.until).desired_width(40.0).hint_text("clip end"))+ .labelled_by(label.id)+ .hint("the last frame to carry it to; empty: the end of the clip, or of the timeline");+ });+ if let Some(carry) = run {+ self.paint_over(carry)?;+ }+ Ok(())+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn the_window_builds_the_cli_paintover() {+ let bundle = Path::new("/w/art.draw");+ let form = Form {+ within: "rock".into(),+ ..Form::default()+ };+ assert_eq!(+ args(bundle, "l4", 3, &form, None).join(" "),+ "paintover /w/art.draw l4 --frame 3 --sizes 32,16,8 --threshold 6 --length 1,8 --curve 0.5 --brush oil --vary 0.025 --seed 1 --in rock"+ );+ let carried = args(bundle, "l4", 3, &Form::default(), Some(("c9", "3-12".into()))).join(" ");+ assert!(carried.ends_with("--like c9 --frames 3-12"), "{carried}");+ }+}diff --git a/crates/app/src/editor/panels.rs b/crates/app/src/editor/panels.rsindex 6e70683..5a7cff0 100644--- a/crates/app/src/editor/panels.rs+++ b/crates/app/src/editor/panels.rs@@ -723,6 +723,28 @@ impl Editor {);self.windows.export &= open;}+ if self.windows.paintover {+ let mut open = true;+ Self::window(+ ctx,+ "paintover",+ (format!("{} Paint over", icon::BRUSH), settings_at),+ &mut open,+ |ui| self.check(|e| e.paintover_window(ui)),+ );+ self.windows.paintover &= open;+ }+ if self.windows.compare {+ let mut open = true;+ Self::window(+ ctx,+ "compare",+ (format!("{} Compared with the reference", icon::INFO), settings_at),+ &mut open,+ |ui| self.check(|e| e.compare_window(ui)),+ );+ self.windows.compare &= open;+ }if self.windows.font {let mut open = true;Self::window(diff --git a/crates/app/src/editor/ui_tests.rs b/crates/app/src/editor/ui_tests.rsindex 3fc59e0..6bba9c6 100644--- a/crates/app/src/editor/ui_tests.rs+++ b/crates/app/src/editor/ui_tests.rs@@ -241,6 +241,36 @@ fn every_control_is_pen_sized_and_has_a_hover_hint() {h.run_steps(3);assert!(h.query_all(By::new().label("page size px")).count() > 0);checked += audit(&h, "the export and font windows");+ {+ let ed = h.state_mut();+ ed.windows.export = false;+ ed.windows.font = false;+ ed.windows.paintover = true;+ }+ h.run_steps(3);+ assert!(h.query_all(By::new().label("carry it to the next drawings")).count() > 0);+ checked += audit(&h, "the paint-over window");+ {+ let ed = h.state_mut();+ ed.windows.paintover = false;+ ed.compare = Some(super::compare::Compared {+ report: serde_json::json!({+ "yours": {"value": [40.0, 66.9, 93.4], "chroma": 30.3, "texture": 14.2, "sharpness": 60.4},+ "reference": {"value": [37.3, 68.4, 94.3], "chroma": 27.5, "texture": 10.6, "sharpness": 57.3},+ "difference": 5.2,+ "words": ["10% more saturated", "34% busier"],+ }),+ heat: None,+ });+ ed.windows.compare = true;+ }+ h.run_steps(3);+ assert!(+ h.query_all(By::new().label("difference 5.2: 10% more saturated, 34% busier"))+ .count()+ > 0+ );+ checked += audit(&h, "the compare window");assert!(checked > 150, "only {checked} controls checked");let _ = std::fs::remove_dir_all(&path);}diff --git a/crates/app/src/jobs.rs b/crates/app/src/jobs.rsindex c2fb32f..00d0ae8 100644--- a/crates/app/src/jobs.rs+++ b/crates/app/src/jobs.rs@@ -18,6 +18,7 @@ pub enum Tag {Arcs,Fonts,Install,+ Compare,}#[derive(Clone)]diff --git a/crates/brush/src/cache.rs b/crates/brush/src/cache.rsindex 48368b1..c8eff7f 100644--- a/crates/brush/src/cache.rs+++ b/crates/brush/src/cache.rs@@ -2,7 +2,7 @@ use crate::{BrushSet, CelReplay, ENGINE_VERSION, Raster};use anyhow::{Context, Result, bail};use klad_core::bundle::{Bundle, write_atomic};use klad_core::rng::{FNV_OFFSET, fnv};-use klad_core::stroke::{Mark, decode_cel};+use klad_core::stroke::{Mark, decode_cel, fingerprint};use std::fs;use std::path::{Path, PathBuf};use std::time::{Duration, Instant, SystemTime};@@ -146,6 +146,17 @@ impl CelCache {let stale = self.record(cel).and_then(|(k, (keys, footprints))| {Ok((CelReplay::from_cache(w, h, keys, footprints), self.raster(cel, k)?))});+ let stale = stale.and_then(|(replay, raster)| {+ let known: std::collections::BTreeSet<(u32, u64)> = replay.keys().iter().copied().collect();+ let kept = marks+ .iter()+ .filter(|m| known.contains(&(m.id(), fingerprint(m))))+ .count();+ match kept * 2 >= marks.len() {+ true => Ok((replay, raster)),+ false => Err(anyhow::anyhow!("most marks are new")),+ }+ });let (replay, raster, how, strokes, dabs) = match stale {Ok((mut replay, mut raster)) => {let done = replaydiff --git a/crates/cli/src/agent.rs b/crates/cli/src/agent.rsindex 22eb5bc..9a475ef 100644--- a/crates/cli/src/agent.rs+++ b/crates/cli/src/agent.rs@@ -556,7 +556,11 @@ pub fn preview(bundle: &Bundle, out: &Output) -> Result<Option<PathBuf>> {pub fn edit(path: &Path, ops: &[Op], out: &Output) -> Result<()> {let mut bundle = Bundle::open(path)?;- let ops = crate::shapes::expand(&bundle, ops.to_vec())?;+ let mut ops = ops.to_vec();+ crate::paintover::resolve(&bundle, &mut ops)?+ .iter()+ .for_each(|n| eprintln!("{n}"));+ let ops = crate::shapes::expand(&bundle, ops)?;let mut ops = vector::pinned(&bundle.doc, &ops)?;resolve_strokes(&bundle, &mut ops)?;crate::fonts::settle(&bundle, &mut ops)?;diff --git a/crates/cli/src/arcs.rs b/crates/cli/src/arcs.rsindex 4a4d61d..bb2a415 100644--- a/crates/cli/src/arcs.rs+++ b/crates/cli/src/arcs.rs@@ -304,7 +304,7 @@ pub fn ground(path: &Path, y: f32, travel: f32, slack: f32) -> Ground {let ((fa, a), (fb, b)) = (w[0], w[1]);let expected = -travel * (fb - fa) as f32;let end = |i: usize| (b.sole[i] - a.sole[i] - expected).abs();- let off = end(0).min(end(1));+ let off = end(0).min(end(1)).min((b.bottom[0] - a.bottom[0] - expected).abs());(touching(&a) && touching(&b) && off > slack).then_some((fa, fb, off))}).collect(),diff --git a/crates/cli/src/compare.rs b/crates/cli/src/compare.rsnew file mode 100644index 0000000..14f249b--- /dev/null+++ b/crates/cli/src/compare.rs@@ -0,0 +1,382 @@+use crate::agent::{Look, render_look};+use anyhow::{Context, Result, bail};+use klad_core::bundle::Bundle;+use klad_core::color;+use klad_render::View;+use serde_json::json;+use std::path::{Path, PathBuf};++type Lab = [f32; 3];++#[derive(Clone)]+pub struct Image {+ pub w: usize,+ pub h: usize,+ pub lab: Vec<Lab>,+}++impl Image {+ pub fn from_rgba(w: usize, h: usize, rgba: &[u8]) -> Self {+ let lab = rgba+ .chunks(4)+ .map(|p| {+ let a = p[3] as f32 / 255.0;+ let c = |v: u8| v as f32 / 255.0 * a + (1.0 - a);+ color::to_oklab([c(p[0]), c(p[1]), c(p[2]), 1.0])+ })+ .collect();+ Self { w, h, lab }+ }++ fn resized(&self, w: usize, h: usize) -> Self {+ if (w, h) == (self.w, self.h) {+ return self.clone();+ }+ let (sx, sy) = (self.w as f32 / w as f32, self.h as f32 / h as f32);+ let at = |x: usize, y: usize| self.lab[y.min(self.h - 1) * self.w + x.min(self.w - 1)];+ let lab = (0..h)+ .flat_map(|y| (0..w).map(move |x| (x, y)))+ .map(|(x, y)| {+ let (fx, fy) = (+ ((x as f32 + 0.5) * sx - 0.5).max(0.0),+ ((y as f32 + 0.5) * sy - 0.5).max(0.0),+ );+ let (x0, y0) = (fx.floor() as usize, fy.floor() as usize);+ let (tx, ty) = (fx - x0 as f32, fy - y0 as f32);+ let mix = |a: Lab, b: Lab, t: f32| -> Lab { std::array::from_fn(|i| a[i] + (b[i] - a[i]) * t) };+ mix(+ mix(at(x0, y0), at(x0 + 1, y0), tx),+ mix(at(x0, y0 + 1), at(x0 + 1, y0 + 1), tx),+ ty,+ )+ })+ .collect();+ Self { w, h, lab }+ }+}++#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Stats {+ pub value: [f32; 3],+ pub chroma: f32,+ pub texture: f32,+ pub sharpness: f32,+ pub mean: Lab,+}++fn percentile(sorted: &[f32], p: f32) -> f32 {+ match sorted.len() {+ 0 => 0.0,+ n => sorted[((n - 1) as f32 * p).round() as usize],+ }+}++pub fn stats(img: &Image, rect: [usize; 4]) -> Stats {+ let [x0, y0, w, h] = rect;+ let (x1, y1) = ((x0 + w).min(img.w), (y0 + h).min(img.h));+ let at = |x: usize, y: usize| img.lab[y * img.w + x];+ let cells: Vec<(usize, usize)> = (y0..y1).flat_map(|y| (x0..x1).map(move |x| (x, y))).collect();+ let n = cells.len().max(1) as f32;+ let mut values: Vec<f32> = cells.iter().map(|&(x, y)| at(x, y)[0] * 100.0).collect();+ values.sort_by(f32::total_cmp);+ let mean: Lab = cells.iter().fold([0.0; 3], |m, &(x, y)| {+ let v = at(x, y);+ std::array::from_fn(|i| m[i] + v[i] / n)+ });+ let chroma = cells+ .iter()+ .map(|&(x, y)| {+ let v = at(x, y);+ v[1].hypot(v[2]) * 100.0+ })+ .sum::<f32>()+ / n;+ let inner: Vec<(usize, usize)> = cells+ .iter()+ .copied()+ .filter(|&(x, y)| x > 0 && y > 0 && x + 1 < img.w && y + 1 < img.h)+ .collect();+ let l = |x: usize, y: usize| at(x, y)[0] * 100.0;+ let texture = inner+ .iter()+ .map(|&(x, y)| (4.0 * l(x, y) - l(x - 1, y) - l(x + 1, y) - l(x, y - 1) - l(x, y + 1)).abs())+ .sum::<f32>()+ / inner.len().max(1) as f32;+ let mut edges: Vec<f32> = inner+ .iter()+ .map(|&(x, y)| (l(x + 1, y) - l(x - 1, y)).hypot(l(x, y + 1) - l(x, y - 1)) * 0.5)+ .collect();+ edges.sort_by(f32::total_cmp);+ Stats {+ value: [+ percentile(&values, 0.05),+ percentile(&values, 0.5),+ percentile(&values, 0.95),+ ],+ chroma,+ texture,+ sharpness: percentile(&edges, 0.99),+ mean,+ }+}++fn ratio(a: f32, b: f32) -> f32 {+ a / b.max(1e-3)+}++pub fn words(yours: &Stats, reference: &Stats) -> Vec<String> {+ let mut out = Vec::new();+ let dl = (yours.mean[0] - reference.mean[0]) * 100.0;+ if dl.abs() > 2.0 {+ out.push(format!(+ "{} by {:.0} L",+ if dl > 0.0 { "lighter" } else { "darker" },+ dl.abs()+ ));+ }+ let (da, db) = (+ (yours.mean[1] - reference.mean[1]) * 100.0,+ (yours.mean[2] - reference.mean[2]) * 100.0,+ );+ if db.abs() > 1.5 {+ out.push(if db > 0.0 { "yellower" } else { "bluer" }.to_string());+ }+ if da.abs() > 1.5 {+ out.push(if da > 0.0 { "redder" } else { "greener" }.to_string());+ }+ let pct = |r: f32| ((r - 1.0).abs() * 100.0).round();+ let c = ratio(yours.chroma, reference.chroma);+ if (c - 1.0).abs() > 0.1 && (yours.chroma - reference.chroma).abs() > 1.0 {+ out.push(format!(+ "{:.0}% {} saturated",+ pct(c),+ if c > 1.0 { "more" } else { "less" }+ ));+ }+ let t = ratio(yours.texture, reference.texture);+ if (t - 1.0).abs() > 0.2 && (yours.texture - reference.texture).abs() > 0.5 {+ out.push(format!(+ "{:.0}% {}",+ pct(t),+ if t > 1.0 { "busier" } else { "smoother" }+ ));+ }+ let s = ratio(yours.sharpness, reference.sharpness);+ if (s - 1.0).abs() > 0.15 && (yours.sharpness - reference.sharpness).abs() > 1.0 {+ out.push(format!(+ "{:.0}% {} edges",+ pct(s),+ if s > 1.0 { "sharper" } else { "softer" }+ ));+ }+ if out.is_empty() {+ out.push("about the same".into());+ }+ out+}++fn difference(a: Lab, b: Lab) -> f32 {+ 100.0 * ((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2) + (a[2] - b[2]).powi(2)).sqrt()+}++pub fn mean_difference(a: &Image, b: &Image) -> f32 {+ a.lab.iter().zip(&b.lab).map(|(x, y)| difference(*x, *y)).sum::<f32>() / a.lab.len().max(1) as f32+}++fn heat(a: &Image, b: &Image) -> klad_render::assets::Rgba {+ let pixels = a+ .lab+ .iter()+ .zip(&b.lab)+ .flat_map(|(x, y)| {+ let t = (difference(*x, *y) / 20.0).clamp(0.0, 1.0);+ let ramp = [t * 3.0, t * 3.0 - 1.0, t * 3.0 - 2.0].map(|v| (v.clamp(0.0, 1.0) * 255.0) as u8);+ [ramp[0], ramp[1], ramp[2], 255]+ })+ .collect();+ klad_render::assets::Rgba {+ width: a.w as u32,+ height: a.h as u32,+ pixels,+ }+}++fn hex(lab: Lab) -> String {+ color::to_hex(color::from_oklab(lab, 1.0))+}++fn load(path: &Path, frame: u32, size: Option<(usize, usize)>) -> Result<Image> {+ if path.is_dir() {+ let bundle = Bundle::open(path)?;+ let scale = size.map_or(1.0, |(w, _)| w as f32 / bundle.doc.canvas.width.max(1) as f32);+ let out = std::env::temp_dir().join(format!("klad-compare-{}.png", std::process::id()));+ let rendered = render_look(+ &bundle,+ frame,+ View::scaled(scale),+ &Look::plain(None),+ Some(out.clone()),+ true,+ )?;+ let _ = std::fs::remove_file(&out);+ let f = rendered.frame;+ return Ok(Image::from_rgba(f.width as usize, f.height as usize, &f.rgba));+ }+ let bytes = std::fs::read(path).with_context(|| format!("reading {}", path.display()))?;+ let rgba = klad_render::assets::decode(&bytes)?;+ Ok(Image::from_rgba(+ rgba.width as usize,+ rgba.height as usize,+ &rgba.pixels,+ ))+}++pub fn parse_region(text: &str) -> Result<(String, [usize; 4])> {+ let (name, rect) = text.split_once('=').context("a region is name=x,y,w,h")?;+ let n: Vec<usize> = rect.split(',').map(|v| v.trim().parse()).collect::<Result<_, _>>()?;+ match n.as_slice() {+ [x, y, w, h] if *w > 0 && *h > 0 => Ok((name.trim().to_string(), [*x, *y, *w, *h])),+ _ => bail!("region {text:?} is not name=x,y,w,h"),+ }+}++pub fn compare(+ yours: &Path,+ reference: &Path,+ frame: u32,+ regions: &[(String, [usize; 4])],+ heat_to: Option<PathBuf>,+ as_json: bool,+) -> Result<()> {+ let theirs = load(reference, 0, None)?;+ let mine = load(yours, frame, Some((theirs.w, theirs.h)))?.resized(theirs.w, theirs.h);+ let whole = [0, 0, theirs.w, theirs.h];+ let (a, b) = (stats(&mine, whole), stats(&theirs, whole));+ let mean = mean_difference(&mine, &theirs);+ let rows: Vec<(String, Stats, Stats)> = regions+ .iter()+ .map(|(name, rect)| (name.clone(), stats(&mine, *rect), stats(&theirs, *rect)))+ .collect();+ if let Some(path) = &heat_to {+ klad_core::bundle::write_atomic(path, &klad_render::assets::encode_png(&heat(&mine, &theirs))?)?;+ }+ let side = |s: &Stats| json!({"value": s.value, "chroma": s.chroma, "texture": s.texture, "sharpness": s.sharpness, "mean": hex(s.mean)});+ if as_json {+ let regions: Vec<_> = rows+ .iter()+ .map(|(n, x, y)| {+ json!({"name": n, "yours": side(x), "reference": side(y), "difference": difference(x.mean, y.mean), "words": words(x, y)})+ })+ .collect();+ println!(+ "{}",+ serde_json::to_string_pretty(&json!({+ "size": [theirs.w, theirs.h],+ "yours": side(&a),+ "reference": side(&b),+ "difference": mean,+ "words": words(&a, &b),+ "regions": regions,+ "heat": heat_to.as_ref().map(|p| p.display().to_string()),+ }))?+ );+ return Ok(());+ }+ println!("{:<12} {:<22} {:<22}", "", "yours", "reference");+ println!(+ "{:<12} {:<22} {:<22}",+ "value L",+ format!("{:.1} / {:.1} / {:.1}", a.value[0], a.value[1], a.value[2]),+ format!("{:.1} / {:.1} / {:.1}", b.value[0], b.value[1], b.value[2])+ );+ [+ ("chroma", a.chroma, b.chroma),+ ("texture", a.texture, b.texture),+ ("sharpness", a.sharpness, b.sharpness),+ ]+ .iter()+ .for_each(|(n, x, y)| println!("{n:<12} {x:<22.1} {y:<22.1}"));+ println!("mean difference {mean:.1} (OKLab x100): {}", words(&a, &b).join(", "));+ if !rows.is_empty() {+ println!(+ "{:<14} {:<9} {:<10} {:>5} what differs",+ "region", "yours", "reference", "dE"+ );+ rows.iter().for_each(|(n, x, y)| {+ println!(+ "{n:<14} {:<9} {:<10} {:>5.1} {}",+ hex(x.mean),+ hex(y.mean),+ difference(x.mean, y.mean),+ words(x, y).join(", ")+ )+ });+ }+ if let Some(path) = heat_to {+ println!("{}", path.display());+ }+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;++ fn picture(w: usize, h: usize, f: impl Fn(usize, usize) -> [u8; 3]) -> Image {+ let rgba: Vec<u8> = (0..h)+ .flat_map(|y| (0..w).map(move |x| (x, y)))+ .flat_map(|(x, y)| {+ let c = f(x, y);+ [c[0], c[1], c[2], 255]+ })+ .collect();+ Image::from_rgba(w, h, &rgba)+ }++ fn painting(x: usize, y: usize) -> [u8; 3] {+ let n = ((x * 7 + y * 13) % 11) as u8 * 4;+ match x < 60 {+ true => [180 + n, 120 + n / 2, 60],+ false => [90, 110 + n, 160 + n],+ }+ }++ #[test]+ fn a_picture_against_itself_a_lighter_copy_a_blurred_copy_and_a_recoloured_region() {+ let base = picture(120, 80, painting);+ let whole = [0, 0, 120, 80];+ let s = stats(&base, whole);+ assert_eq!(words(&s, &s), ["about the same"]);+ assert_eq!(mean_difference(&base, &base), 0.0);+ let lighter = picture(120, 80, |x, y| painting(x, y).map(|v| v.saturating_add(30)));+ let said = words(&stats(&lighter, whole), &s);+ assert!(said[0].starts_with("lighter by"), "{said:?}");+ let blurred = picture(120, 80, |x, y| {+ let sum = (0..5)+ .flat_map(|dy| (0..5).map(move |dx| (dx, dy)))+ .fold([0u32; 3], |acc, (dx, dy)| {+ let c = painting((x + dx).saturating_sub(2).min(119), (y + dy).saturating_sub(2).min(79));+ std::array::from_fn(|i| acc[i] + c[i] as u32)+ });+ sum.map(|v| (v / 25) as u8)+ });+ let b = stats(&blurred, whole);+ assert!(b.texture < s.texture * 0.5 && b.sharpness < s.sharpness, "{b:?} {s:?}");+ let said = words(&b, &s).join(", ");+ assert!(said.contains("smoother") && said.contains("softer edges"), "{said}");+ let recoloured = picture(120, 80, |x, y| if x < 60 { [90, 110, 200] } else { painting(x, y) });+ let left = [0, 0, 60, 80];+ let said = words(&stats(&recoloured, left), &stats(&base, left)).join(", ");+ assert!(said.contains("bluer"), "{said}");+ let right = [60, 0, 60, 80];+ assert_eq!(+ words(&stats(&recoloured, right), &stats(&base, right)),+ ["about the same"]+ );+ assert_eq!(+ parse_region("shade=10,20,30,40").unwrap(),+ ("shade".to_string(), [10, 20, 30, 40])+ );+ assert!(parse_region("shade=10,20").is_err());+ }+}diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rsindex 35da391..5cd0f00 100644--- a/crates/cli/src/main.rs+++ b/crates/cli/src/main.rs@@ -3,6 +3,7 @@ mod arcs;mod bench;mod brushes;mod colour;+mod compare;mod demo;mod edit;mod export;@@ -15,6 +16,7 @@ mod install;mod layers;mod looks;mod marks;+mod paintover;mod paths;mod shapes;mod sheet;@@ -31,7 +33,7 @@ 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, PaintSpec, PaletteEdit, Place, ScatterSpec, StrokeSpec,+ LightSpec, Op, PaintOverSpec, PaintSpec, PaletteEdit, Place, ScatterSpec, StrokeSpec,};use klad_core::retime::{Retime, RetimeSpec};use klad_core::stroke::{fills_of, strokes_of};@@ -1155,6 +1157,82 @@ enum Command {#[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"+ )]+ Compare {+ drawing: PathBuf,+ reference: PathBuf,+ #[arg(long, default_value_t = 0)]+ frame: u32,+ #[arg(long = "region", help = "name=x,y,w,h in the reference's pixels; repeat for more")]+ regions: Vec<String>,+ #[arg(long)]+ heat: Option<PathBuf>,+ #[arg(long)]+ json: bool,+ },+ #[command(+ about = "Paint over a picture with brushwork: strokes that follow its forms and stop at its colour edges, big to small",+ long_about = "Repaint what is below a paint layer (or the layers in --from) with strokes on that layer: big brushes first, then smaller ones only where the painting still differs from the source by more than --threshold (a colour difference in OKLab, x100), so detail lands where the source has it. Each stroke takes the source's colour where it starts, broken a little warm and cool (--vary), and runs along the forms (across the colour gradient) until the colour under it changes, it reaches --length (in brush widths, min,max) or it would bend more than --curve allows (0 straight, 1 follows every turn). --in limits it to closed shapes; --focus lets the smallest brush work only in and near one shape. The strokes are ordinary strokes in the part \"paint over\" (--part), one history step, so they take body and relief and can be edited.\n\nFor animation, paint over one key, then carry it to the next with --like <cel>: every stroke moves with the marks under it, takes its colour from the new drawing, and strokes are only added (part \"paint over added\") where the new drawing needs them. The carried strokes keep their order, so klad inbetween pairs them part by part and nothing boils.\n\n klad paintover still.draw brushwork --sizes 32,16,8 --threshold 6\n klad paintover walk.draw brushwork --frame 4 --like c12\n\nAlso a paintover op, alone in its batch: {\"op\":\"paintover\",\"layer\":\"brushwork\",\"sizes\":[32,16,8],\"threshold\":6}."+ )]+ Paintover {+ bundle: PathBuf,+ layer: String,+ #[arg(+ long,+ value_delimiter = ',',+ help = "Layers to paint from (default: everything below the layer, with the background)"+ )]+ from: Vec<String>,+ #[arg(long = "in", value_delimiter = ',', help = "Closed vector shapes to paint inside")]+ within: Vec<String>,+ #[arg(long, value_delimiter = ',', default_values_t = [32.0, 16.0, 8.0], help = "Brush sizes in px, biggest first")]+ sizes: Vec<f32>,+ #[arg(+ long,+ default_value_t = 6.0,+ help = "How far the painting may differ from the source (OKLab difference x100)"+ )]+ threshold: f32,+ #[arg(long, default_value = "1,8", help = "Stroke length in brush widths: min,max")]+ length: String,+ #[arg(+ long,+ default_value_t = 0.5,+ help = "How closely strokes follow the forms' turns (0 to 1)"+ )]+ curve: f32,+ #[arg(long, default_value = "oil")]+ brush: String,+ #[arg(long, help = "A closed shape: the smallest brush only paints in and near it")]+ focus: Option<String>,+ #[arg(+ long,+ default_value_t = 0.025,+ help = "Warm and cool, light and dark break per stroke (OKLab)"+ )]+ vary: f32,+ #[arg(+ long,+ help = "Carry the paint-over of this drawing (a cel id on the same layer) to this frame"+ )]+ like: Option<String>,+ #[arg(+ long,+ help = "With --like: carry it from drawing to drawing over these frames (a-b), making a drawing on the layer wherever the source starts one"+ )]+ frames: Option<String>,+ #[arg(long, default_value = "paint over")]+ part: String,+ #[arg(long, default_value_t = 1)]+ seed: u32,+ #[arg(long, default_value_t = 0)]+ frame: u32,+ #[command(flatten)]+ flags: EditFlags,+ },#[command(about = "Grow grass in closed shapes: blades lit by the ground, smaller with distance, breaking the top edge",long_about = "Fill closed shapes with grass blades from the far (top) edge to the near (bottom) one: each blade rises from its root, leans with --wind (degrees) and bends, and is smaller and denser towards the top (--far is the far size against the near one). The ground under them rolls in soft patches about --patch px wide, lit by --light (or a --lamp x,y,height): each blade runs from a dark root to a lit tip in a few value families from --shade through --color to --lit. Along the top edge taller blades (--edge) break the outline against what is behind. Near blades are drawn last.\n\nWith a stroke brush (blade, the default, or any round or chalk tip) each blade is a tapered stroke whose colour runs from --color at the root to the lit colour at the tip when the brush blends to a second colour by pressure. With a picture brush (a tip made of pictures, like your own tufts) each blade is one stamp of the picture, turned to the blade. Build your own brush for your grass (klad brushes --picture, --set) and pass it with --brush: the op decides where the marks go and how they are lit, the brush decides what they look like.\n\n klad grass meadow.draw field --in field-shape --color '#6f8a3c' --light -0.9,-0.45 --blade 30 --far 0.22\n klad grass meadow.draw bank --in bank --brush my-tuft --blade 160 --density 0.1\n\nAlso a grass op: {\"op\":\"grass\",\"layer\":\"field\",\"in\":[\"field-shape\"],\"color\":\"#6f8a3c\",\"blade\":30,\"far\":0.22,\"wind\":12}."@@ -2578,6 +2656,69 @@ fn run() -> Result<()> {};agent::edit(&bundle, &[Op::Foliage(spec)], &output(&flags, frame))?;}+ Command::Compare {+ drawing,+ reference,+ frame,+ regions,+ heat,+ json,+ } => {+ let regions = regions+ .iter()+ .map(|r| compare::parse_region(r))+ .collect::<Result<Vec<_>>>()?;+ compare::compare(&drawing, &reference, frame, ®ions, heat, json)?;+ }+ Command::Paintover {+ bundle,+ layer,+ from,+ within,+ sizes,+ threshold,+ length,+ curve,+ brush,+ focus,+ vary,+ like,+ frames,+ part,+ seed,+ frame,+ flags,+ } => {+ let length: [f32; 2] = parse_numbers(&length)?+ .try_into()+ .map_err(|_| anyhow!("--length {length:?} is not min,max"))?;+ let spec = PaintOverSpec {+ layer: layer_id(&bundle, &layer)?,+ frame,+ from,+ within,+ sizes,+ threshold,+ length,+ curve,+ brush,+ focus,+ vary,+ like,+ part,+ seed,+ };+ match frames {+ Some(range) => {+ let (a, b) = range+ .split_once('-')+ .and_then(|(a, b)| Some((a.trim().parse().ok()?, b.trim().parse().ok()?)))+ .ok_or_else(|| anyhow!("--frames {range:?} is not first-last"))?;+ paintover::chain(&bundle, &spec, (a, b), &output(&flags, frame))?;+ }+ None => agent::edit(&bundle, &[Op::PaintOver(spec)], &output(&flags, frame))?,+ }+ }Command::Grass {bundle,layer,diff --git a/crates/cli/src/paintover.rs b/crates/cli/src/paintover.rsnew file mode 100644index 0000000..a7c1c60--- /dev/null+++ b/crates/cli/src/paintover.rs@@ -0,0 +1,1125 @@+use crate::layers::{self, Vectors};+use crate::shapes::areas;+use anyhow::{Context, Result, anyhow, bail};+use klad_brush::BrushSet;+use klad_core::bundle::Bundle;+use klad_core::color;+use klad_core::doc::{Document, Kind, Layer, Loc};+use klad_core::ops::{Op, PaintOverSpec, StrokeSpec};+use klad_core::rng::Rng;+use klad_core::stroke::{Mark, Stroke};+use klad_core::tween::{self, Lines, Match};+use klad_render::{Rasters, flatten};+use rayon::prelude::*;+use serde_json::json;++type Lab = [f32; 3];+type P = [f32; 2];++const EDGE: f32 = 0.12;++pub struct Picture {+ pub w: usize,+ pub h: usize,+ pub lab: Vec<Lab>,+ pub alpha: Vec<f32>,+}++impl Picture {+ fn index(&self, x: f32, y: f32) -> Option<usize> {+ let (xi, yi) = (x.floor(), y.floor());+ (xi >= 0.0 && yi >= 0.0 && (xi as usize) < self.w && (yi as usize) < self.h)+ .then(|| yi as usize * self.w + xi as usize)+ }+}++pub fn difference(a: Lab, b: Lab) -> f32 {+ 100.0 * ((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2) + (a[2] - b[2]).powi(2)).sqrt()+}++fn box_pass(data: &[[f32; 4]], w: usize, h: usize, r: usize, rows: bool) -> Vec<[f32; 4]> {+ let (lines, len) = if rows { (h, w) } else { (w, h) };+ let at = move |line: usize, i: usize| if rows { line * w + i } else { i * w + line };+ let mut out = vec![[0.0; 4]; w * h];+ let done: Vec<Vec<(usize, [f32; 4])>> = (0..lines)+ .into_par_iter()+ .map(|line| {+ let mut sum = [0.0f32; 4];+ let span = (2 * r + 1) as f32;+ let get = |i: isize| data[at(line, i.clamp(0, len as isize - 1) as usize)];+ (-(r as isize)..=r as isize).for_each(|i| {+ let v = get(i);+ (0..4).for_each(|c| sum[c] += v[c]);+ });+ (0..len)+ .map(|i| {+ let value = sum.map(|s| s / span);+ let (add, drop) = (get(i as isize + r as isize + 1), get(i as isize - r as isize));+ (0..4).for_each(|c| sum[c] += add[c] - drop[c]);+ (at(line, i), value)+ })+ .collect()+ })+ .collect();+ done.into_iter().flatten().for_each(|(i, v)| out[i] = v);+ out+}++pub fn blur(picture: &Picture, radius: f32) -> Picture {+ let r = (radius * 0.5).round() as usize;+ let mut data: Vec<[f32; 4]> = picture+ .lab+ .iter()+ .zip(&picture.alpha)+ .map(|(l, a)| [l[0], l[1], l[2], *a])+ .collect();+ if r > 0 {+ (0..3).for_each(|_| {+ data = box_pass(&data, picture.w, picture.h, r, true);+ data = box_pass(&data, picture.w, picture.h, r, false);+ });+ }+ Picture {+ w: picture.w,+ h: picture.h,+ lab: data.iter().map(|v| [v[0], v[1], v[2]]).collect(),+ alpha: data.iter().map(|v| v[3]).collect(),+ }+}++fn scanline(polygons: &[Vec<P>], w: usize, h: usize) -> Vec<bool> {+ let mut mask = vec![false; w * h];+ (0..h).for_each(|y| {+ let fy = y as f32 + 0.5;+ let mut xs: Vec<f32> = polygons+ .iter()+ .flat_map(|poly| {+ (0..poly.len()).filter_map(move |i| {+ let (a, b) = (poly[i], poly[(i + 1) % poly.len()]);+ ((a[1] > fy) != (b[1] > fy)).then(|| a[0] + (fy - a[1]) / (b[1] - a[1]) * (b[0] - a[0]))+ })+ })+ .collect();+ xs.sort_by(f32::total_cmp);+ xs.chunks(2).filter(|c| c.len() == 2).for_each(|c| {+ let (x0, x1) = (+ (c[0] - 0.5).ceil().max(0.0) as usize,+ ((c[1] - 0.5).floor() + 1.0).clamp(0.0, w as f32) as usize,+ );+ (x0..x1).for_each(|x| mask[y * w + x] = true);+ });+ });+ mask+}++fn grow(mask: &[bool], w: usize, h: usize, by: f32) -> Vec<bool> {+ let picture = Picture {+ w,+ h,+ lab: vec![[0.0; 3]; w * h],+ alpha: mask.iter().map(|&m| if m { 1.0 } else { 0.0 }).collect(),+ };+ blur(&picture, by * 2.0).alpha.iter().map(|&a| a > 0.001).collect()+}++fn family(layer: &Layer) -> Vec<&Layer> {+ std::iter::once(layer)+ .chain(layer.children().iter().flat_map(family))+ .collect()+}++fn layers_of<'a>(doc: &'a Document, spec: &PaintOverSpec) -> Result<Vec<&'a Layer>> {+ if !spec.from.is_empty() {+ return spec.from.iter().map(|key| doc.find_layer(key)).collect();+ }+ let target = doc.find_layer(&spec.layer)?;+ let top = doc+ .layers+ .iter()+ .position(|l| family(l).iter().any(|c| c.id == target.id))+ .ok_or_else(|| anyhow!("paint over: {} is not in the layer stack", spec.layer))?;+ Ok(doc.layers[..top].iter().filter(|l| l.visible && !l.reference).collect())+}++pub fn source(bundle: &Bundle, spec: &PaintOverSpec, frame: u32) -> Result<Picture> {+ let doc = &bundle.doc;+ let chosen = layers_of(doc, spec)?;+ if chosen.is_empty() {+ bail!("paint over: nothing below {} to paint from; give --from", spec.layer);+ }+ let brushes = BrushSet::for_bundle(bundle)?;+ let mut rasters = Rasters::new();+ doc.paint_content_at(frame)+ .iter()+ .try_for_each(|(layer, cel)| -> Result<()> {+ rasters.insert(cel.id.clone(), layers::load_one(bundle, &brushes, &layer.id, &cel.id)?);+ Ok(())+ })?;+ Vectors::default().add_to(doc, frame, &mut rasters)?;+ let background = spec+ .from+ .is_empty()+ .then_some(doc.canvas.background.as_deref())+ .flatten();+ let flat = flatten(doc, frame, &rasters, &chosen, background)?;+ let (w, h) = (doc.canvas.width as usize, doc.canvas.height as usize);+ let mut lab = vec![[0.0; 3]; w * h];+ let mut alpha = vec![0.0; w * h];+ flat.occupied().for_each(|(index, tile)| {+ let (ox, oy) = (+ (index % flat.cols) * klad_brush::TILE,+ (index / flat.cols) * klad_brush::TILE,+ );+ tile.chunks(4).enumerate().for_each(|(i, px)| {+ let (x, y) = (ox + i % klad_brush::TILE, oy + i / klad_brush::TILE);+ if x >= w || y >= h {+ return;+ }+ let a = px[3].to_f32();+ if a <= 1e-4 {+ return;+ }+ let rgb = [px[0].to_f32() / a, px[1].to_f32() / a, px[2].to_f32() / a, 1.0];+ lab[y * w + x] = color::to_oklab(rgb);+ alpha[y * w + x] = a;+ });+ });+ Ok(Picture { w, h, lab, alpha })+}++struct Canvas {+ lab: Vec<Lab>,+ painted: Vec<bool>,+}++impl Canvas {+ fn new(n: usize) -> Self {+ Self {+ lab: vec![[0.0; 3]; n],+ painted: vec![false; n],+ }+ }++ fn error(&self, reference: &Picture, i: usize) -> f32 {+ match self.painted[i] {+ true => difference(self.lab[i], reference.lab[i]),+ false => 100.0,+ }+ }++ fn paint(&mut self, w: usize, h: usize, points: &[P], radius: f32, lab: Lab) {+ let r = radius.max(0.5);+ let step = (r * 0.5).max(0.5);+ let dense: Vec<P> = points+ .windows(2)+ .flat_map(|s| {+ let (a, b) = (s[0], s[1]);+ let n = ((b[0] - a[0]).hypot(b[1] - a[1]) / step).ceil().max(1.0) as usize;+ (0..n).map(move |k| {+ let t = k as f32 / n as f32;+ [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]+ })+ })+ .chain(points.last().copied())+ .collect();+ dense.iter().for_each(|c| {+ let (x0, x1) = (+ (c[0] - r).floor().max(0.0) as usize,+ ((c[0] + r).ceil() as usize).min(w),+ );+ let (y0, y1) = (+ (c[1] - r).floor().max(0.0) as usize,+ ((c[1] + r).ceil() as usize).min(h),+ );+ (y0..y1).for_each(|y| {+ (x0..x1).for_each(|x| {+ if (x as f32 + 0.5 - c[0]).hypot(y as f32 + 0.5 - c[1]) <= r {+ self.lab[y * w + x] = lab;+ self.painted[y * w + x] = true;+ }+ })+ })+ });+ }+}++fn lightness(p: &Picture, x: isize, y: isize) -> f32 {+ let (x, y) = (+ x.clamp(0, p.w as isize - 1) as usize,+ y.clamp(0, p.h as isize - 1) as usize,+ );+ p.lab[y * p.w + x][0] * p.alpha[y * p.w + x].min(1.0)+}++fn gradient(p: &Picture, at: P) -> P {+ let (x, y) = (at[0].floor() as isize, at[1].floor() as isize);+ let l = |dx: isize, dy: isize| lightness(p, x + dx, y + dy);+ let gx = (l(1, -1) + 2.0 * l(1, 0) + l(1, 1)) - (l(-1, -1) + 2.0 * l(-1, 0) + l(-1, 1));+ let gy = (l(-1, 1) + 2.0 * l(0, 1) + l(1, 1)) - (l(-1, -1) + 2.0 * l(0, -1) + l(1, -1));+ [gx, gy]+}++fn drift(at: P, seed: u32) -> P {+ let cell = 220.0;+ let (x, y) = (at[0] / cell, at[1] / cell);+ let (ix, iy) = (x.floor(), y.floor());+ let (fx, fy) = (x - ix, y - iy);+ let (sx, sy) = (fx * fx * (3.0 - 2.0 * fx), fy * fy * (3.0 - 2.0 * fy));+ let h = |dx: f32, dy: f32| klad_core::rng::hash2_unit((ix + dx) as i32, (iy + dy) as i32, seed);+ let top = h(0.0, 0.0) + (h(1.0, 0.0) - h(0.0, 0.0)) * sx;+ let bottom = h(0.0, 1.0) + (h(1.0, 1.0) - h(0.0, 1.0)) * sx;+ let base = (klad_core::rng::hash2_unit(0, 0, seed ^ 0x5eed) - 0.5) * 0.6;+ let angle = base + (top + (bottom - top) * sy - 0.5) * 0.9;+ [angle.cos(), angle.sin()]+}++pub struct Painted {+ pub points: Vec<P>,+ pub size: f32,+ pub lab: Lab,+}++struct Rules<'a> {+ reference: &'a Picture,+ canvas: &'a Canvas,+ region: &'a [bool],+ radius: f32,+ steps: [usize; 2],+ curve: f32,+ threshold: f32,+ seed: u32,+}++fn walk(rules: &Rules, start: P) -> Option<Painted> {+ let r = rules.reference;+ let i0 = r.index(start[0], start[1])?;+ let colour = r.lab[i0];+ let mut points = vec![start];+ let mut last: Option<P> = None;+ for step in 1..=rules.steps[1] {+ let at = *points.last()?;+ let Some(i) = r.index(at[0], at[1]) else {+ break;+ };+ let here = r.lab[i];+ if step > rules.steps[0]+ && difference(here, rules.canvas.lab[i]) < difference(here, colour)+ && rules.canvas.painted[i]+ {+ break;+ }+ if difference(here, colour) > rules.threshold * 2.0 {+ break;+ }+ let g = gradient(r, at);+ let length = g[0].hypot(g[1]);+ let sure = (length / EDGE).clamp(0.0, 1.0);+ let along = match length > 1e-6 {+ true => [-g[1] / length, g[0] / length],+ false => drift(at, rules.seed),+ };+ let prior = last.unwrap_or_else(|| drift(at, rules.seed));+ let along = match along[0] * prior[0] + along[1] * prior[1] < 0.0 {+ true => [-along[0], -along[1]],+ false => along,+ };+ let k = match last {+ Some(_) => rules.curve * sure,+ None => sure,+ };+ let mut d = [k * along[0] + (1.0 - k) * prior[0], k * along[1] + (1.0 - k) * prior[1]];+ let n = d[0].hypot(d[1]).max(1e-6);+ d = [d[0] / n, d[1] / n];+ let next = [at[0] + rules.radius * d[0], at[1] + rules.radius * d[1]];+ match r.index(next[0], next[1]) {+ Some(j) if rules.region[j] && difference(r.lab[j], colour) <= rules.threshold * 2.0 => points.push(next),+ _ => break,+ }+ last = Some(d);+ }+ Some(Painted {+ points,+ size: rules.radius * 2.0,+ lab: colour,+ })+}++pub struct Plan<'a> {+ pub sizes: &'a [f32],+ pub threshold: f32,+ pub length: [f32; 2],+ pub curve: f32,+ pub seed: u32,+ pub region: &'a [bool],+ pub focus: Option<&'a [bool]>,+}++pub fn paint(picture: &Picture, plan: &Plan, canvas_from: &[Painted]) -> Vec<Painted> {+ let (w, h) = (picture.w, picture.h);+ let mut canvas = Canvas::new(w * h);+ canvas_from+ .iter()+ .for_each(|s| canvas.paint(w, h, &s.points, s.size * 0.5, s.lab));+ let mut rng = Rng::new(plan.seed as u64 ^ 0x9a17);+ let last = plan.sizes.len().saturating_sub(1);+ let mut out = Vec::new();+ plan.sizes.iter().enumerate().for_each(|(pass, &size)| {+ let radius = (size * 0.5).max(1.0);+ let reference = blur(picture, radius);+ let grid = radius.max(1.0) as usize;+ let mut starts: Vec<P> = (0..h.div_ceil(grid))+ .flat_map(|gy| (0..w.div_ceil(grid)).map(move |gx| (gx * grid, gy * grid)))+ .filter_map(|(x0, y0)| {+ let cells: Vec<usize> = (y0..(y0 + grid).min(h))+ .flat_map(|y| (x0..(x0 + grid).min(w)).map(move |x| y * w + x))+ .filter(|&i| plan.region[i] && (pass != last || plan.focus.is_none_or(|f| f[i])))+ .collect();+ if cells.is_empty() {+ return None;+ }+ let errors: Vec<f32> = cells.iter().map(|&i| canvas.error(&reference, i)).collect();+ let mean = errors.iter().sum::<f32>() / errors.len() as f32;+ (mean > plan.threshold).then(|| {+ let worst = errors+ .iter()+ .enumerate()+ .max_by(|a, b| a.1.total_cmp(b.1))+ .map_or(cells[0], |(k, _)| cells[k]);+ [(worst % w) as f32 + 0.5, (worst / w) as f32 + 0.5]+ })+ })+ .collect();+ (0..starts.len()).rev().for_each(|i| {+ let j = (rng.unit() * (i + 1) as f32) as usize;+ starts.swap(i, j.min(i));+ });+ let rules = Rules {+ reference: &reference,+ canvas: &canvas,+ region: plan.region,+ radius,+ steps: [+ (plan.length[0] * 2.0).round().max(0.0) as usize,+ (plan.length[1] * 2.0).round().max(1.0) as usize,+ ],+ curve: plan.curve,+ threshold: plan.threshold,+ seed: plan.seed.wrapping_add(pass as u32),+ };+ let made: Vec<Painted> = starts.par_iter().filter_map(|&s| walk(&rules, s)).collect();+ made.iter()+ .for_each(|s| canvas.paint(w, h, &s.points, s.size * 0.5, s.lab));+ out.extend(made);+ });+ out+}++fn pressure(n: usize, k: usize) -> f32 {+ let t = if n <= 1 { 0.5 } else { k as f32 / (n - 1) as f32 };+ let smooth = |a: f32, b: f32, x: f32| {+ let u = ((x - a) / (b - a)).clamp(0.0, 1.0);+ u * u * (3.0 - 2.0 * u)+ };+ (0.4 + 0.6 * smooth(0.0, 0.25, t)) * (1.0 - 0.75 * smooth(0.65, 1.0, t))+}++fn hex(lab: Lab, seed: u32, vary: f32) -> String {+ let jitter = |k: i32| klad_core::rng::hash2_unit(seed as i32, k, 0x7a11) * 2.0 - 1.0;+ let shifted = [+ lab[0] + vary * 0.6 * jitter(1),+ lab[1] + vary * 0.3 * jitter(2),+ lab[2] + vary * 0.6 * jitter(3),+ ];+ color::to_hex(color::from_oklab(shifted, 1.0))+}++fn stroke_op(+ spec: &PaintOverSpec,+ part: &str,+ points: &[P],+ size: f32,+ colour: String,+ opacity: f32,+ seed: u32,+) -> Result<Op> {+ let run: Vec<[f32; 3]> = match points.len() {+ 1 => vec![+ [points[0][0] - size * 0.15, points[0][1], 0.7],+ [points[0][0] + size * 0.15, points[0][1], 0.7],+ ],+ n => points+ .iter()+ .enumerate()+ .map(|(k, p)| [p[0], p[1], pressure(n, k)])+ .collect(),+ };+ let spec: StrokeSpec = serde_json::from_value(json!({+ "layer": spec.layer,+ "frame": spec.frame,+ "brush": spec.brush,+ "color": colour,+ "size": size,+ "opacity": opacity,+ "points": run,+ "seed": seed,+ "part": part,+ }))?;+ Ok(Op::Stroke(spec))+}++fn region(doc: &Document, spec: &PaintOverSpec, picture: &Picture) -> Result<Vec<bool>> {+ let alpha = picture.alpha.iter().map(|&a| a > 0.5);+ match spec.within.is_empty() {+ true => Ok(alpha.collect()),+ false => {+ let polygons = areas(doc, &spec.within, &None, "paint over")?;+ Ok(scanline(&polygons, picture.w, picture.h)+ .into_iter()+ .zip(alpha)+ .map(|(a, b)| a && b)+ .collect())+ }+ }+}++struct Like {+ strokes: Vec<(Stroke, Vec<P>, bool)>,+ remove: Vec<String>,+ from: u32,+}++#[derive(Clone, Copy, PartialEq)]+enum Rides {+ Line(usize),+ Nearest,+ Still,+ Gone,+}++#[derive(Default)]+struct Sources {+ from: Lines,+ to: Lines,+ marks: Vec<(Mark, Rides)>,+}++fn covers(mark: &Mark, at: P, reach: f32) -> bool {+ match mark {+ Mark::Stroke(s) => {+ let line = tween::line_of(s);+ let near = s.size * 0.5 + reach;+ match line.len() {+ 0 => false,+ 1 => (line[0].0 - at[0]).hypot(line[0].1 - at[1]) <= near,+ _ => line.windows(2).any(|w| {+ let (a, b) = ([w[0].0, w[0].1], [w[1].0, w[1].1]);+ let (dx, dy) = (b[0] - a[0], b[1] - a[1]);+ let t =+ (((at[0] - a[0]) * dx + (at[1] - a[1]) * dy) / (dx * dx + dy * dy).max(1e-6)).clamp(0.0, 1.0);+ (a[0] + dx * t - at[0]).hypot(a[1] + dy * t - at[1]) <= near+ }),+ }+ }+ Mark::Fill(f) => match &f.source {+ klad_core::fill::FillSource::Polygon(points) => crate::shapes::inside(std::slice::from_ref(points), at),+ klad_core::fill::FillSource::Seed { .. } => {+ at[0] >= 0.0 && at[1] >= 0.0 && f.coverage.at(at[0] as u32, at[1] as u32) > 0+ }+ },+ }+}++impl Sources {+ fn rides(&self, at: P) -> Rides {+ self.marks+ .iter()+ .rev()+ .find(|(m, _)| covers(m, at, 1.0))+ .map_or(Rides::Still, |(_, r)| *r)+ }+}++fn outline_of(mark: &Mark) -> Option<Vec<(f32, f32)>> {+ match mark {+ Mark::Stroke(s) => Some(tween::line_of(s)),+ Mark::Fill(f) => match &f.source {+ klad_core::fill::FillSource::Polygon(points) => {+ Some(points.iter().chain(points.first()).map(|p| (p[0], p[1])).collect())+ }+ klad_core::fill::FillSource::Seed { .. } => None,+ },+ }+}++fn sources(bundle: &Bundle, spec: &PaintOverSpec, from: u32) -> Result<Sources> {+ let doc = &bundle.doc;+ let mut out = Sources::default();+ layers_of(doc, spec)?+ .into_iter()+ .flat_map(family)+ .filter(|l| l.kind() == Kind::Paint)+ .try_for_each(|layer| -> Result<()> {+ let Some(a) = layer.content_at(from) else {+ return Ok(());+ };+ let ma = bundle.read_marks(&layer.id, &a.id)?;+ let b = layer.content_at(spec.frame);+ if b.is_some_and(|b| b.id == a.id) {+ out.marks.extend(ma.into_iter().map(|m| (m, Rides::Still)));+ return Ok(());+ }+ let Some(b) = b else {+ out.marks.extend(ma.into_iter().map(|m| (m, Rides::Gone)));+ return Ok(());+ };+ let mb = bundle.read_marks(&layer.id, &b.id)?;+ let groups: Vec<(Vec<u32>, Vec<u32>)> = a+ .parts+ .iter()+ .filter_map(|(name, ids)| b.parts.get(name).map(|other| (ids.clone(), other.clone())))+ .collect();+ let pairing = tween::pair_parts(&ma, &mb, Match::Id, &[], &groups);+ ma.into_iter().for_each(|m| {+ let pair = pairing.pairs.iter().find(|p| p.a == m.id());+ let rides = match pair {+ None => Rides::Gone,+ Some(p) => {+ let other = mb.iter().find(|n| n.id() == p.b);+ match (outline_of(&m), other.and_then(outline_of)) {+ (Some(la), Some(mut lb)) => {+ if p.reversed {+ lb.reverse();+ }+ out.from.push(la);+ out.to.push(lb);+ Rides::Line(out.from.len() - 1)+ }+ _ => Rides::Nearest,+ }+ }+ };+ out.marks.push((m, rides));+ });+ Ok(())+ })?;+ Ok(out)+}++fn like(bundle: &Bundle, spec: &PaintOverSpec, cel: &str) -> Result<Like> {+ let doc = &bundle.doc;+ let layer = doc.find_layer(&spec.layer)?;+ match doc.locate(cel) {+ Some(Loc::Cel(path, _)) if doc.layer_at(&path).id == layer.id => {}+ _ => bail!("paint over --like {cel}: not a drawing on {}", spec.layer),+ }+ let from = (0..doc.timeline.frames.max(1))+ .find(|&f| layer.content_at(f).is_some_and(|c| c.id == cel))+ .ok_or_else(|| anyhow!("paint over --like {cel}: that drawing is not shown on any frame"))?;+ if layer.content_at(spec.frame).is_some_and(|c| c.id == cel) {+ bail!(+ "paint over --like {cel}: frame {} shows that drawing itself; make a new drawing there first",+ spec.frame+ );+ }+ let marks = bundle.read_marks(&layer.id, cel)?;+ let owner = layer.cels().iter().find(|c| c.id == cel).context("no such drawing")?;+ let ids: Option<&Vec<u32>> = owner.parts.get(&spec.part);+ let found = sources(bundle, spec, from)?;+ let strokes = marks+ .iter()+ .filter_map(Mark::as_stroke)+ .filter(|s| ids.is_none_or(|ids| ids.contains(&s.id)))+ .map(|s| {+ let line = tween::line_of(s);+ let n = line.len().max(1) as f32;+ let centre = line.iter().fold([0.0, 0.0], |c, p| [c[0] + p.0 / n, c[1] + p.1 / n]);+ let mark = Mark::Stroke(s.clone());+ let rides = found.rides(centre);+ let moved = match rides {+ Rides::Line(i) => tween::carry(&mark, &found.from, &found.to, Some(&[i])),+ Rides::Nearest => tween::carry(&mark, &found.from, &found.to, None),+ Rides::Still | Rides::Gone => mark,+ };+ let points = moved.as_stroke().map_or_else(Vec::new, |m| {+ m.samples+ .iter()+ .map(|q| {+ let (x, y) = q.pos();+ [x, y]+ })+ .collect()+ });+ (s.clone(), points, rides != Rides::Gone)+ })+ .collect();+ let remove = layer+ .content_at(spec.frame)+ .map(|c| {+ let added = format!("{} added", spec.part);+ [&spec.part, &added]+ .iter()+ .filter_map(|p| c.parts.get(*p))+ .flatten()+ .map(|id| format!("{}:s{id}", c.id))+ .collect()+ })+ .unwrap_or_default();+ Ok(Like { strokes, remove, from })+}++pub fn expand(bundle: &Bundle, spec: &PaintOverSpec) -> Result<Vec<Op>> {+ let doc = &bundle.doc;+ let target = doc.find_layer(&spec.layer)?;+ if target.kind() != Kind::Paint {+ bail!("paint over draws on a paint layer; {} is not one", spec.layer);+ }+ if spec.sizes.is_empty() || spec.sizes.iter().any(|s| *s <= 0.0) {+ bail!("paint over needs brush sizes above 0, biggest first: --sizes 32,16,8");+ }+ let picture = source(bundle, spec, spec.frame)?;+ let region = region(doc, spec, &picture)?;+ if !region.iter().any(|r| *r) {+ bail!("paint over: the source has no paint where it would draw");+ }+ let focus = spec+ .focus+ .as_ref()+ .map(|id| -> Result<Vec<bool>> {+ let polygons = areas(doc, std::slice::from_ref(id), &None, "paint over --focus")?;+ let near = spec.sizes.last().copied().unwrap_or(8.0) * 3.0;+ Ok(grow(+ &scanline(&polygons, picture.w, picture.h),+ picture.w,+ picture.h,+ near,+ ))+ })+ .transpose()?;+ let plan = Plan {+ sizes: &spec.sizes,+ threshold: spec.threshold,+ length: spec.length,+ curve: spec.curve.clamp(0.0, 1.0),+ seed: spec.seed,+ region: ®ion,+ focus: focus.as_deref(),+ };+ let mut rng = Rng::new(spec.seed as u64 ^ 0xc0102);+ let mut ops = Vec::new();+ let mut kept = Vec::new();+ if let Some(cel) = &spec.like {+ let carried = like(bundle, spec, cel)?;+ if !carried.remove.is_empty() {+ ops.extend(klad_core::ops::parse_lines(+ &json!({"op": "rm", "ids": carried.remove}).to_string(),+ )?);+ }+ let mut blurred: std::collections::BTreeMap<u32, Picture> = std::collections::BTreeMap::new();+ carried+ .strokes+ .iter()+ .try_for_each(|(stroke, points, alive)| -> Result<()> {+ let key = (stroke.size * 0.5).round() as u32;+ let reference = blurred.entry(key).or_insert_with(|| blur(&picture, stroke.size * 0.5));+ let at = points.first().copied().unwrap_or([0.0, 0.0]);+ let found = reference.index(at[0], at[1]).filter(|&i| region[i] && *alive);+ let crosses = found.is_some_and(|i| {+ let step = (points.len() / 6).max(1);+ points.iter().step_by(step).any(|p| {+ reference.index(p[0], p[1]).is_none_or(|j| {+ !region[j] || difference(reference.lab[j], reference.lab[i]) > spec.threshold * 2.5+ })+ })+ });+ let found = found.filter(|_| !crosses);+ let (lab, opacity) = match found {+ Some(i) => (reference.lab[i], stroke.opacity),+ None => (color::to_oklab(color::from_u16(stroke.color)), 0.0),+ };+ ops.push(stroke_op(+ spec,+ &spec.part,+ points,+ stroke.size,+ hex(lab, stroke.seed, spec.vary),+ opacity,+ stroke.seed,+ )?);+ if opacity > 0.0 {+ kept.push(Painted {+ points: points.clone(),+ size: stroke.size,+ lab,+ });+ }+ Ok(())+ })?;+ }+ let part = match spec.like {+ Some(_) => format!("{} added", spec.part),+ None => spec.part.clone(),+ };+ let changed: Option<Vec<bool>> = match &spec.like {+ Some(cel) => {+ let from = like(bundle, spec, cel)?.from;+ let before = source(bundle, spec, from)?;+ let moved: Vec<bool> = before+ .lab+ .iter()+ .zip(&picture.lab)+ .zip(before.alpha.iter().zip(&picture.alpha))+ .map(|((a, b), (x, y))| (x - y).abs() > 0.25 || difference(*a, *b) > spec.threshold * 0.5)+ .collect();+ let near = spec.sizes.first().copied().unwrap_or(16.0);+ let mut covered = Canvas::new(picture.w * picture.h);+ kept.iter()+ .for_each(|k| covered.paint(picture.w, picture.h, &k.points, k.size * 0.5, k.lab));+ Some(+ grow(&moved, picture.w, picture.h, near)+ .iter()+ .zip(®ion)+ .zip(&covered.painted)+ .map(|((m, r), c)| *r && (*m || !*c))+ .collect(),+ )+ }+ None => None,+ };+ let plan = Plan {+ region: changed.as_deref().unwrap_or(®ion),+ ..plan+ };+ let made = paint(&picture, &plan, &kept);+ made.iter().enumerate().try_for_each(|(k, s)| -> Result<()> {+ let size = s.size * (0.9 + 0.2 * rng.unit());+ let seed = spec.seed.wrapping_mul(7919).wrapping_add(k as u32);+ ops.push(stroke_op(+ spec,+ &part,+ &s.points,+ size,+ hex(s.lab, seed, spec.vary),+ 1.0,+ seed,+ )?);+ Ok(())+ })?;+ if ops.is_empty() {+ bail!("paint over: nothing to paint; the layer already matches the source within --threshold");+ }+ Ok(ops)+}++pub fn resolve(bundle: &Bundle, ops: &mut Vec<Op>) -> Result<Vec<String>> {+ if !ops.iter().any(|op| matches!(op, Op::PaintOver(_))) {+ return Ok(Vec::new());+ }+ if ops.len() > 1 {+ bail!("paint over needs a batch of its own: it reads the drawing from the bundle as it is");+ }+ let Some(Op::PaintOver(spec)) = ops.first() else {+ unreachable!("checked above");+ };+ let spec = spec.clone();+ let made = expand(bundle, &spec)?;+ let strokes = made.iter().filter(|o| matches!(o, Op::Stroke(_))).count();+ *ops = made;+ Ok(vec![format!(+ "paint over on {}: {strokes} strokes{}",+ spec.layer,+ spec.like+ .as_ref()+ .map_or(String::new(), |c| format!(", carried from {c}"))+ )])+}++pub fn chain(+ path: &std::path::Path,+ spec: &PaintOverSpec,+ (first, last): (u32, u32),+ out: &crate::agent::Output,+) -> Result<()> {+ let mut previous = spec+ .like+ .clone()+ .context("--frames carries a paint-over from drawing to drawing: give the first with --like")?;+ let mut made: std::collections::BTreeMap<String, String> = std::collections::BTreeMap::new();+ let mut painted = 0;+ (first..=last).try_for_each(|frame| -> Result<()> {+ let bundle = Bundle::open(path)?;+ let doc = &bundle.doc;+ let target = doc.find_layer(&spec.layer)?;+ let starting: Vec<klad_core::doc::Cel> = layers_of(doc, spec)?+ .into_iter()+ .flat_map(family)+ .filter(|l| l.kind() == Kind::Paint)+ .filter_map(|l| l.cel_at(frame).filter(|c| c.frame == frame).cloned())+ .collect();+ if starting.is_empty() {+ return Ok(());+ }+ let hold = starting.iter().filter_map(|c| c.hold).min();+ if let Some(source) = starting.iter().find_map(|c| c.link.as_ref())+ && starting.iter().all(|c| c.link.is_some())+ {+ if let Some(mine) = made.get(source) {+ let mut op = json!({"op": "cel", "link": mine, "frame": frame});+ if let Some(h) = hold {+ op["hold"] = json!(h);+ }+ crate::agent::edit(path, &klad_core::ops::parse_lines(&op.to_string())?, out)?;+ }+ return Ok(());+ }+ let own = target+ .cel_at(frame)+ .filter(|c| c.frame == frame && c.link.is_none())+ .map(|c| c.id.clone());+ let cel = match own {+ Some(id) => id,+ None => {+ let mut op = json!({"op": "cel", "new": spec.layer, "frame": frame});+ if let Some(h) = hold {+ op["hold"] = json!(h);+ }+ crate::agent::edit(path, &klad_core::ops::parse_lines(&op.to_string())?, out)?;+ let bundle = Bundle::open(path)?;+ let target = bundle.doc.find_layer(&spec.layer)?;+ target+ .cel_at(frame)+ .map(|c| c.id.clone())+ .context("the new drawing did not land")?+ }+ };+ if cel == previous {+ starting.iter().for_each(|c| {+ made.insert(c.id.clone(), cel.clone());+ });+ return Ok(());+ }+ let step = PaintOverSpec {+ frame,+ like: Some(previous.clone()),+ ..spec.clone()+ };+ crate::agent::edit(path, &[Op::PaintOver(step)], out)?;+ starting.iter().for_each(|c| {+ made.insert(c.id.clone(), cel.clone());+ });+ previous = cel;+ painted += 1;+ Ok(())+ })?;+ eprintln!("paint over carried to {painted} drawings, frames {first} to {last}");+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;+ use klad_core::doc::Document;+ use klad_core::ops::parse_lines;++ fn bundle(name: &str, w: u32, h: u32, ops: &str) -> (std::path::PathBuf, Bundle) {+ let dir = std::env::temp_dir().join(format!("klad-paintover-{name}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ let mut doc = Document::new(w, h);+ doc.layers = vec![+ Layer::paint("src", "source", "c1"),+ Layer::paint("work", "brushwork", "c2"),+ ];+ doc.next_id = 10;+ let mut bundle = Bundle::create(&dir, doc).unwrap();+ let mut ops = parse_lines(ops).unwrap();+ crate::fills::resolve(&bundle, &mut ops).unwrap();+ bundle.apply(&ops).unwrap();+ (dir, bundle)+ }++ fn spec(sizes: &[f32]) -> PaintOverSpec {+ serde_json::from_value(json!({"layer": "work", "sizes": sizes, "seed": 3})).unwrap()+ }++ fn strokes(ops: &[Op]) -> Vec<&StrokeSpec> {+ ops.iter()+ .filter_map(|o| match o {+ Op::Stroke(s) => Some(s),+ _ => None,+ })+ .collect()+ }++ fn points(s: &StrokeSpec) -> Vec<[f32; 3]> {+ s.points.clone().unwrap()+ }++ fn rect(x: f32, w: f32, h: f32, colour: &str) -> String {+ format!(+ r#"{{"op":"fill","layer":"src","polygon":[[{x},0],[{},0],[{},{h}],[{x},{h}]],"color":"{colour}"}}"#,+ x + w,+ x + w+ )+ }++ #[test]+ fn strokes_stay_on_their_side_of_an_edge_and_repeat_with_a_seed() {+ let ops = [rect(0.0, 120.0, 160.0, "#c0402a"), rect(120.0, 120.0, 160.0, "#2f5fb0")].join("\n");+ let (dir, bundle) = bundle("edge", 240, 160, &ops);+ let made = expand(&bundle, &spec(&[16.0, 8.0])).unwrap();+ let found = strokes(&made);+ assert!(found.len() > 20, "{}", found.len());+ found.iter().for_each(|s| {+ let xs: Vec<f32> = points(s).iter().map(|p| p[0]).collect();+ let (lo, hi) = xs.iter().fold((f32::MAX, f32::MIN), |(a, b), x| (a.min(*x), b.max(*x)));+ assert!(+ hi <= 120.0 + 6.0 || lo >= 120.0 - 6.0,+ "a stroke crossed the edge: {lo}..{hi}"+ );+ assert_eq!(s.part.as_deref(), Some("paint over"));+ });+ assert_eq!(+ expand(&bundle, &spec(&[16.0, 8.0])).unwrap(),+ made,+ "the same seed paints the same strokes"+ );+ std::fs::remove_dir_all(&dir).unwrap();+ }++ #[test]+ fn strokes_run_along_bands_and_small_brushes_only_go_where_detail_is() {+ let bands: Vec<String> = (0..16)+ .map(|i| {+ let v = 40 + i * 12;+ format!(+ r##"{{"op":"fill","layer":"src","polygon":[[0,{}],[160,{}],[160,{}],[0,{}]],"color":"#{v:02x}{v:02x}{v:02x}"}}"##,+ i * 10,+ i * 10,+ i * 10 + 10,+ i * 10 + 10+ )+ })+ .collect();+ let checks: Vec<String> = (0..20)+ .flat_map(|i| (0..20).map(move |j| (i, j)))+ .filter(|(i, j)| (i + j) % 2 == 0)+ .map(|(i, j)| {+ let (x, y) = (160 + i * 8, j * 8);+ format!(+ r##"{{"op":"fill","layer":"src","polygon":[[{x},{y}],[{},{y}],[{},{}],[{x},{}]],"color":"#202020"}}"##,+ x + 8,+ x + 8,+ y + 8,+ y + 8+ )+ })+ .collect();+ let ops = [rect(160.0, 160.0, 160.0, "#e8e8e8")]+ .into_iter()+ .chain(bands)+ .chain(checks)+ .collect::<Vec<_>>()+ .join("\n");+ let (dir, bundle) = bundle("bands", 320, 160, &ops);+ let made = expand(&bundle, &spec(&[24.0, 6.0])).unwrap();+ let found = strokes(&made);+ let (mut along, mut across) = (0.0, 0.0);+ found+ .iter()+ .filter(|s| s.size > 12.0 && points(s).iter().all(|p| p[0] < 150.0))+ .for_each(|s| {+ let p = points(s);+ let (a, b) = (p[0], p[p.len() - 1]);+ along += (b[0] - a[0]).abs();+ across += (b[1] - a[1]).abs();+ });+ assert!(+ along > 3.0 * across,+ "strokes over horizontal bands run sideways: {along} against {across}"+ );+ let small: Vec<f32> = found+ .iter()+ .filter(|s| s.size < 12.0)+ .map(|s| points(s)[0][0])+ .collect();+ let right = small.iter().filter(|x| **x >= 160.0).count();+ assert!(+ right * 4 > small.len() * 3,+ "small strokes go where the detail is: {right} of {}",+ small.len()+ );+ std::fs::remove_dir_all(&dir).unwrap();+ }++ #[test]+ fn a_paint_over_carried_to_the_next_key_moves_with_the_marks_and_in_betweens_without_boiling() {+ let disc = |cx: f32| {+ let pts: Vec<String> = (0..24)+ .map(|k| {+ let a = std::f32::consts::TAU * k as f32 / 24.0;+ format!("[{:.1},{:.1}]", cx + 40.0 * a.cos(), 100.0 + 40.0 * a.sin())+ })+ .collect();+ format!(+ r##"{{"op":"fill","layer":"src","polygon":[{}],"color":"#d0a030","frame":FRAME}}"##,+ pts.join(",")+ )+ };+ let ops = [+ r#"{"op":"timeline","frames":8}"#.to_string(),+ rect(0.0, 320.0, 200.0, "#486080").replace(r#""color""#, r#""frame":0,"color""#),+ disc(110.0).replace("FRAME", "0"),+ r#"{"op":"cel","new":"src","frame":4,"id":"k4"}"#.to_string(),+ rect(0.0, 320.0, 200.0, "#486080").replace(r#""color""#, r#""frame":4,"color""#),+ disc(140.0).replace("FRAME", "4"),+ r#"{"op":"cel","new":"work","frame":4,"id":"w4"}"#.to_string(),+ ]+ .join("\n");+ let (dir, mut bundle) = bundle("like", 320, 200, &ops);+ let first = expand(&bundle, &spec(&[16.0, 8.0])).unwrap();+ bundle.apply(&first).unwrap();+ let mut carry = spec(&[16.0, 8.0]);+ carry.frame = 4;+ carry.like = Some("c2".into());+ let second = expand(&bundle, &carry).unwrap();+ let (a, b) = (strokes(&first), strokes(&second));+ let carried: Vec<&&StrokeSpec> = b.iter().filter(|s| s.part.as_deref() == Some("paint over")).collect();+ assert_eq!(carried.len(), a.len(), "every stroke is carried, in order");+ let (mut on_disc, mut still) = (0, 0);+ a.iter().zip(&carried).for_each(|(s, t)| {+ let (p, q) = (points(s)[0], points(t)[0]);+ let inside = (p[0] - 110.0).hypot(p[1] - 100.0) < 30.0;+ let away = (p[0] - 110.0).hypot(p[1] - 100.0) > 70.0 && (p[0] - 140.0).hypot(p[1] - 100.0) > 70.0;+ if inside {+ on_disc += 1;+ assert!(+ (q[0] - p[0] - 30.0).abs() < 2.0 && (q[1] - p[1]).abs() < 2.0,+ "{p:?} -> {q:?}"+ );+ }+ if away {+ still += 1;+ assert!(+ (p[0] - q[0]).abs() < 0.1 && (p[1] - q[1]).abs() < 0.1,+ "the background stays: {p:?} {q:?}"+ );+ assert_eq!(+ s.seed, t.seed,+ "a carried stroke keeps its seed, so its texture does not boil"+ );+ }+ });+ assert!(on_disc > 3 && still > 10, "{on_disc} on the disc, {still} still");+ bundle.apply(&second).unwrap();+ let mut tween = parse_lines(r#"{"op":"inbetween","layers":["work"],"from":0,"to":4}"#).unwrap();+ let notes = crate::inbetween::resolve(&bundle, &mut tween).unwrap();+ let Op::Inbetween(made) = &tween[0] else { panic!() };+ let resolved = made.resolved.as_ref().unwrap();+ assert_eq!(resolved.cels.len(), 3, "{notes:?}");+ let marks = |c: &klad_core::ops::TweenCel| c.marks.len();+ assert!(+ resolved.cels.iter().all(|c| marks(c) >= a.len()),+ "every carried stroke is paired: {notes:?}"+ );+ std::fs::remove_dir_all(&dir).unwrap();+ }+}diff --git a/crates/cli/src/shapes.rs b/crates/cli/src/shapes.rsindex c89b2fc..50f3530 100644--- a/crates/cli/src/shapes.rs+++ b/crates/cli/src/shapes.rs@@ -62,7 +62,12 @@ fn closed(outlines: &[Outline]) -> Vec<Vec<P>> {.collect()}-fn areas(doc: &Document, within: &[String], polygon: &Option<Vec<[f32; 2]>>, what: &str) -> Result<Vec<Vec<P>>> {+pub(crate) fn areas(+ doc: &Document,+ within: &[String],+ polygon: &Option<Vec<[f32; 2]>>,+ what: &str,+) -> Result<Vec<Vec<P>>> {let mut found = closed(&shapes::outlines(doc, within)?);found.extend(polygon.clone().filter(|p| p.len() >= 3));if found.is_empty() {@@ -326,7 +331,7 @@ fn scatter(doc: &Document, spec: &ScatterSpec) -> Result<Vec<Op>> {.collect()}-fn inside(polygons: &[Vec<P>], at: P) -> bool {+pub(crate) fn inside(polygons: &[Vec<P>], at: P) -> bool {polygons.iter().fold(false, |odd, poly| {let crossings = (0..poly.len()).filter(|&i| {diff --git a/crates/core/src/bundle.rs b/crates/core/src/bundle.rsindex 10e03c3..7b5540e 100644--- a/crates/core/src/bundle.rs+++ b/crates/core/src/bundle.rs@@ -528,6 +528,7 @@ pub fn summarize(ops: &[Op]) -> String {Op::Paint(spec) => format!("paint on {}", spec.layer),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::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/ops.rs b/crates/core/src/ops.rsindex dc965e1..d97e59f 100644--- a/crates/core/src/ops.rs+++ b/crates/core/src/ops.rs@@ -147,6 +147,7 @@ pub enum Op {Scatter(ScatterSpec),Foliage(FoliageSpec),Grass(GrassSpec),+ PaintOver(PaintOverSpec),Clip(ClipEdit),Export {godot: Option<String>,@@ -616,6 +617,66 @@ pub struct GrassSpec {pub part: Option<String>,}+#[derive(Clone, Debug, PartialEq, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct PaintOverSpec {+ pub layer: String,+ #[serde(default)]+ pub frame: u32,+ #[serde(default)]+ pub from: Vec<String>,+ #[serde(default, rename = "in")]+ pub within: Vec<String>,+ #[serde(default = "paintover_sizes")]+ pub sizes: Vec<f32>,+ #[serde(default = "paintover_threshold")]+ pub threshold: f32,+ #[serde(default = "paintover_length")]+ pub length: [f32; 2],+ #[serde(default = "paintover_curve")]+ pub curve: f32,+ #[serde(default = "paintover_brush")]+ pub brush: String,+ #[serde(default)]+ pub focus: Option<String>,+ #[serde(default = "paintover_vary")]+ pub vary: f32,+ #[serde(default)]+ pub like: Option<String>,+ #[serde(default = "paintover_part")]+ pub part: String,+ #[serde(default = "first_seed")]+ pub seed: u32,+}++fn paintover_sizes() -> Vec<f32> {+ vec![32.0, 16.0, 8.0]+}++fn paintover_threshold() -> f32 {+ 6.0+}++fn paintover_length() -> [f32; 2] {+ [1.0, 10.0]+}++fn paintover_curve() -> f32 {+ 0.5+}++fn paintover_brush() -> String {+ "oil".into()+}++fn paintover_vary() -> f32 {+ 0.025+}++fn paintover_part() -> String {+ "paint over".into()+}+#[derive(Clone, Debug, PartialEq, Deserialize)]#[serde(deny_unknown_fields)]pub struct GrassKind {@@ -1309,6 +1370,7 @@ impl Op {"paint" => Op::Paint(serde_json::from_value(Value::Object(std::mem::take(&mut map)))?),"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)))?),"grass" => Op::Grass(serde_json::from_value(Value::Object(std::mem::take(&mut map)))?),"clip" => Op::Clip(parse_clip(&mut map)?),"export" => Op::Export {@@ -2596,9 +2658,16 @@ pub fn apply(doc: &mut Document, op: &Op, out: &mut Applied) -> Result<()> {let id = duplicate_layer(doc, layer, out)?;out.added.push(id);}- Op::Ink(_) | Op::Light(_) | Op::Hatch(_) | Op::Paint(_) | Op::Scatter(_) | Op::Foliage(_) | Op::Grass(_) => {+ Op::Ink(_)+ | Op::Light(_)+ | Op::Hatch(_)+ | Op::Paint(_)+ | Op::Scatter(_)+ | Op::Foliage(_)+ | Op::Grass(_)+ | Op::PaintOver(_) => {bail!(- "ink, light, hatch, paint, scatter, foliage and grass are turned into strokes and fills by klad ink, klad light, klad hatch, klad paint, klad scatter, klad foliage, klad grass or klad apply first"+ "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::Inbetween(spec) => {diff --git a/docs/DESIGN.md b/docs/DESIGN.mdindex c4f0e33..042d491 100644--- a/docs/DESIGN.md+++ b/docs/DESIGN.md@@ -1,4 +1,4 @@-_Last updated: 2026-11-05 20:26_+_Last updated: 2026-11-05 21:14_# klad: design@@ -208,7 +208,7 @@ Unknown keys are errors that list the valid ones, so a typo never passes silentl**Fills like another drawing.** A `fill` with `like` carries every flood fill of one drawing to the layer's other drawings on `frames` (all, a range or a clip): for each target, the reference at the frame where it first shows is cut into regions as the fill would see them (its colour, tolerance and gap); each region near the old fill is compared with the old coverage shifted onto the region's centre (overlap over union, falling off with the distance moved), regions open to the canvas edge only when the old fill touched it; the seed goes to the best region's pixel nearest the shifted old seed and the fill is computed there. A target that already has a fill with that id has it replaced in place, otherwise the fill goes on top with that id (or the next free one). Fills that find no region, cover nothing or come out over 2.5 times (plus 256 px) the old one are listed. One history step for all targets.-**Parts, arcs and hand work in in-betweens (M4.5 batch 2).** Pairing for in-betweens goes forced pairs first (`--pair`), then part by part for every part name both keys have (within a part and a kind of mark, in drawing order when the counts match, by nearest shape when they do not), then the `match` rule for the rest, so keys drawn separately pair whatever their ids. `--loop` takes the loop's first drawing as the second key (the clip holding `--from`, else frame 0; `--to` defaults to the loop's end), so a cycle closes without a temporary link. Marks in one key only follow `unpaired`: left out (the default, listed), `pop` at the middle or at `t`, `fade` (opacity over the in-betweens), `draw-on` (drawn along their length; one-key marks of the first key draw off); they are carried with the lines around them (`tween::carry`: every point anchored along the nearest paired line and placed on that line in the in-between), and flood fills among them are still left out. `--redo --keep-drawn` splits an in-between's marks by author: it remakes the agent's from the keys and keeps the hand-drawn ones on top, carried from the old in-between's lines to the new ones (aligned by mark id; a hand mark in a part follows the lines of that part), with new ids and their parts; `made` stays the hash of the agent's marks, so a plain `--redo` still refuses it. Arcs (`cli/src/arcs.rs`) track a mark through the drawings that show its id, a part's centre in each drawing of a layer (the first paint layer that has the part, or `layer:part`), or a point carried by the stroke nearest to it at the first frame; each frame gives a centre, a lowest point (the middle of the samples within 1 px of the lowest y) and the sole (the span of the samples within 2 px of it, the part on the ground). `--ground` reports the lowest point under the line, and slides: consecutive changed positions both on the line (within `--slack`) where neither end of the sole moved by `-travel` per frame (a cycle drawn in place should move a planted foot back by the travel); the slide is the smaller of the two ends' moves, so a foot rolling from heel to toe, which keeps one end still, is not a slide, and a foot pushed along the ground, which moves both, is; with two tracks, frames where their left-right order flips are swaps. `--overlay arcs` draws each track as a line with a dot and a tick across the path per frame, numbered, the current frame ringed; `--overlay parts` boxes and names each part.+**Parts, arcs and hand work in in-betweens (M4.5 batch 2).** Pairing for in-betweens goes forced pairs first (`--pair`), then part by part for every part name both keys have (within a part and a kind of mark, in drawing order when the counts match, by nearest shape when they do not), then the `match` rule for the rest, so keys drawn separately pair whatever their ids. `--loop` takes the loop's first drawing as the second key (the clip holding `--from`, else frame 0; `--to` defaults to the loop's end), so a cycle closes without a temporary link. Marks in one key only follow `unpaired`: left out (the default, listed), `pop` at the middle or at `t`, `fade` (opacity over the in-betweens), `draw-on` (drawn along their length; one-key marks of the first key draw off); they are carried with the lines around them (`tween::carry`: every point anchored along the nearest paired line and placed on that line in the in-between), and flood fills among them are still left out. `--redo --keep-drawn` splits an in-between's marks by author: it remakes the agent's from the keys and keeps the hand-drawn ones on top, carried from the old in-between's lines to the new ones (aligned by mark id; a hand mark in a part follows the lines of that part), with new ids and their parts; `made` stays the hash of the agent's marks, so a plain `--redo` still refuses it. Arcs (`cli/src/arcs.rs`) track a mark through the drawings that show its id, a part's centre in each drawing of a layer (the first paint layer that has the part, or `layer:part`), or a point carried by the stroke nearest to it at the first frame; each frame gives a centre, a lowest point (the middle of the samples within 1 px of the lowest y) and the sole (the span of the samples within 2 px of it, the part on the ground). `--ground` reports the lowest point under the line, and slides: consecutive changed positions both on the line (within `--slack`) where neither end of the sole nor its lowest point moved by `-travel` per frame (a cycle drawn in place should move a planted foot back by the travel); the slide is the smallest of those three moves, so a foot rolling from heel to toe, which keeps one end still, or turning a little on its lowest point, is not a slide, and a foot pushed along the ground, which moves all three, is; with two tracks, frames where their left-right order flips are swaps. `--overlay arcs` draws each track as a line with a dot and a tick across the path per frame, numbered, the current frame ringed; `--overlay parts` boxes and names each part.**Drawing from shapes.** `ink`, `light`, `hatch`, `scatter` and `fill` with `shape` read the outlines of vector shapes (rects, ellipses, paths; a group means each shape in it), flattened every 2 px and taken to canvas coordinates through the node's transforms (`klad_render::shapes`), and are turned by the CLI into ordinary strokes and fills before the transaction (`cli/src/shapes.rs`), so they replay like any mark; shapes added earlier in the same batch are seen. Ink resamples each outline, splits it at corners sharper than `break` degrees (open paths at their ends too), and gives each sample a pressure from three rules multiplied together and smoothed: the outward normal against the light (0.55 facing it to 1 facing away), the silhouette (0.7 where the outline lies inside another closed outline of the call), the curvature (down to 0.65 on tight curves); a seeded two-sine wobble moves points along the normal. A closed outline without corners is one stroke that starts at its lightest point and overlaps its start by 12 px. `light` makes lasso fills of each closed outline with a cut that keeps the outside of the same outline moved towards the light by `depth` (in `soft` steps from 0.6 to 1.4 times the depth, each at a share of the opacity) for the shade, and moved away from the light by `rimWidth` for the rim. `hatch` cuts parallel lines (or inward offsets of the outline with `along`) into pieces of the given lengths, jittered and clipped to the area; `scatter` places a mark at jittered grid points or `count` random points inside the area and outside `avoid`, scaled and turned by seeded amounts. All of it is deterministic (libm, the seeded RNG). Lasso fills skip the CLI's catch-up of earlier marks (only flood fills need to see them), so 160 fills from one `light` of 40 shapes take about 260 ms.@@ -243,6 +243,8 @@ Every layer has `blend`, `opacity`, `visible`, `locked`, optional `mask`, `clip`- **Text (M5).** `{"type": "text", "text", "font", "x", "y", "size", "tracking", "leading", "align", "weight"}` with the node's fill and outline. The font is a file in the bundle's `fonts/` folder, so a drawing renders the same anywhere. Each line is shaped by `harfrust` (HarfBuzz's shaping in Rust: GPOS and `kern` kerning, ligatures, marks, scripts), `weight` sets a variable font's `wght` axis, and the outlines come from the file through `skrifa`, each glyph's contours merged with Skia's path ops so an outline never shows the overlaps variable fonts are built with; they are drawn as one path, never by the system's font engine, so the Mac and the container draw the same pixels. A missing font is refused with its name.- **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.+- **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.+- **Compare (M5, S5.30).** `compare` (`cli/src/compare.rs`) renders the drawing at the reference's width (or reads a PNG or JPEG), resamples it to the reference's size, composites both over white and compares in OKLab: L at the 5th, 50th and 95th percentile, mean chroma, texture as the mean absolute Laplacian of L, sharpness as the 99th percentile of the gradient, and the mean difference, each x100; per `--region` the mean colours and their difference; words when a difference passes a threshold (2 L, 1.5 in a or b, 10% chroma, 20% texture, 15% sharpness); `--heat` writes the per-pixel difference as black to red to yellow to white at 20. The editor's "compare with the reference" runs it as a job against the first picture on a reference layer and shows the numbers and the heat in a window.- **Grass (M5, S5.28).** `grass` is a shape op too: rows of blades from the far (top) edge of the shapes to the near one, scaled from `far` to 1 by depth, leaning by `wind` with a bend, each from a dark root (`color`) to a lit tip (`second`, the `blade` brush blends to it by pressure as the blade thins) over ground that rolls in a value noise foreshortened with depth, lit by the light or lamp in soft value families; taller blades root just inside the top edge and break it; lit blades get a thin glint on their lit side; strokes are sorted far to near. Each root picks a species (`kinds`, by default fine, broad, dry, seed heads and clover) weighted by its share and by a noise of its own, so species grow in patches; heads and low plants thin out with distance. Per blade the hue, chroma and taper vary. A picture brush gets one stamp per blade; a species with a `head` gets a picture stamped at its tip; `low` species are stamped near the root and drawn before the blades around them. Both ops take any brush: they place and light marks, the brush (often the agent's own pictures) gives them their look.- **Picture brushes start facing the stroke (engine version 6).** A brush whose angle follows the stroke places its first dab before it knows the stroke's direction, so that dab points right. For a picture tip that made one-dab marks (a leaf, a tuft) never turn; such a brush now holds its first dab until the second point gives the direction (a tap is drawn when the stroke ends, `StrokePainter::end`, called by the replay and by the editor at pen up), the same live and in replay. Round, chalk and bristle tips keep the old first dab, so M1 drawings and every painted sample render as before; only strokes with picture tips and a following angle (`leaves`) change.@@ -404,7 +406,10 @@ An error is one line on stderr (`error: reading a.draw/doc.json: No such file or| `klad export <bundle> --frames all\|<clip>\|0-11 [--scale s] [-o dir]` | numbered full-size PNGs, one per frame (`run-0000.png`, ...) || `klad export <bundle> --godot [dir] [--store] [--scale s]` | the sheet, a `SpriteFrames` `.tres` and an `AnimatedSprite2D` `.tscn` (see Exports) || `klad hash <bundle> [--frame n] [--all]` | pixel hash for the parity check; `--all` one line per frame |-| `klad open [bundle]` | the editor (macOS); without a bundle, the start window: New, Open (the macOS open panel or a pasted path), Recent with thumbnails |+| `klad open [bundle]` | the editor; without a bundle, the start window: New, Open (the platform's open panel or a pasted path), Recent with thumbnails |+| `klad paintover <bundle> <layer> [--from] [--in] [--sizes 32,16,8] [--threshold 6] [--length 1,8] [--curve 0.5] [--brush oil] [--focus] [--vary] [--like <cel> [--frames a-b]] [--part] [--seed]` | brushwork from what is below the layer (see Paint over) |+| `klad compare <drawing\|png> <reference> [--frame] [--region name=x,y,w,h]... [--heat out.png] [--json]` | values, saturation, texture, edges and colour against a reference, in numbers and words |+| `klad install [--dir]`, `klad skill` | put `klad` on the terminal's path; print the agent skill |Scripts are any language that prints edit ops as JSON lines into `klad apply`. Generators that should stay editable (scatter, repeat, symmetry) are built-in vector node kinds with parameters.diff --git a/docs/skill/SKILL.md b/docs/skill/SKILL.mdindex 8ff463e..bdd2d78 100644--- a/docs/skill/SKILL.md+++ b/docs/skill/SKILL.md@@ -213,6 +213,30 @@ klad prepare art.draw- Details that make a prop read as made rather than blocked in (an early version of the lantern read "kind of as good, but its details are not too great"): connect what hangs (hook, links, bead, cap: every piece touches the next; a link seen face-on is a closed ring through `--path`, one seen edge-on a small filled bar); give a round form a crisp core shadow with its own `light` pass (`--soft 1`, depth about a third of its width, `shadeOpacity` 1) instead of a soft gradient; build a stone or block from two planes (a top face and a darker side as its own shape) and keep texture to the side plane; plant grass as a few tufts where things meet the ground, leaning away from the object, not a fringe along an edge; ink a shape that enters another as an open path, so its cut edge is not drawn on top.- The ops are `ink`, `light`, `hatch`, `paint`, `scatter` and `fill` with `shape`; shapes added earlier in the same `apply` can be used by them. `samples/lantern/` builds the inked prop, and with `PAINTED=1` the painted one (`paint` by form in place of `light` and `hatch`).+## Painting over, and measuring against a reference++`paintover` turns a flat or smooth picture into a painted one: it renders what is below a paint layer (or `--from` layers) and lays brush strokes on that layer, big to small. Each stroke takes the source's colour where it starts and runs along the forms (across the colour gradient) until the colour under it changes; smaller brushes only go where the painting still differs from the source by more than `--threshold`, so detail lands where the source has it. Flat areas get broad, mostly level strokes. The strokes are ordinary strokes in the part `paint over`, so `body` and `relief` light them and the user can edit them.++```bash+klad add art.draw layer paint name=brushwork # on top of the drawing+klad paintover art.draw brushwork --sizes 32,16,8 --threshold 6 [--in rock] [--focus face] [--brush oil-load] [--curve 0.5] [--length 1,8]+klad paintover walk.draw brushwork --frame 0 --sizes 14,7+klad paintover walk.draw brushwork --like c37 --frames 0-27 # carry it drawing to drawing through an animation+```++- Block in and light the picture first (flats, `paint`, shadows), then paint over it: the paint-over keeps your values and edges and adds the hand. Keep the source layers under the brushwork; hide them or not.+- `--focus <shape>` keeps the smallest brush to the focal area, so detail falls off away from it. Bigger `--threshold` means fewer, bigger strokes.+- Animation: never paint over each drawing on its own (the strokes jump every frame). Paint over the first drawing, then `--like <its cel> --frames a-b`: each later drawing gets the previous one's strokes moved with the source marks under them, recoloured from the new drawing, and new strokes only where the source changed; the background stays still. The carried strokes keep their order and seeds, so in-betweens of the brushwork layer pair them part by part.+- `paintover` needs a batch of its own in `apply` (it reads the drawing as it is).++`compare` measures your drawing against a reference picture, so a critique is numbers as well as a look: the value range (L at the 5th, 50th and 95th percentile), saturation, stroke texture, edge sharpness and mean colour difference, with what differs in words, plus a row per `--region` and a heat map of where they differ most.++```bash+klad compare art.draw study.png --region shade=40,300,200,120 --region cup=610,180,90,120 --heat diff.png+```++Read the words ("lighter by 4 L", "bluer", "33% busier", "softer edges") and fix the biggest first. In the editor, "compare with the reference" (View) does the same against the drawing's reference picture layer.+## Building in 3D and painting stroke by strokeAnything with straight edges or round rims (boxes, buildings, cylinders, cups, rims of holes) is built in 3D and projected, never typed in as corners: typed corners give vanishing points at different heights and verticals of the same length near and far. `docs/skill/drawkit.py` (Python, no dependencies; `python3 docs/skill/drawkit.py --check` tests it) has a `Camera(eye, focal, centre, horizon)` with `project`, `box` (corners and faces with normals), `visible_faces`, `sphere_points`, `cylinder_points`, `extrusion_points`, `silhouette` (the hull of projected points), `shadow` and `shadow_shape` (points projected along the light onto the ground), and `stroke`, the same hand as the CLI's, for generators that place their own strokes. A level camera with the horizon on the canvas gives two-point perspective with upright verticals; moving the camera's centre on the canvas moves the subject without bending the perspective.diff --git a/justfile b/justfileindex d7f7cdf..23df3af 100644--- a/justfile+++ b/justfile@@ -19,7 +19,7 @@ lint:cargo clippy --workspace --all-targets -- -D warningssamples: build- for s in lantern ink-shapes bounce creature courier solids lemons ruin sign tree meadow; do FORCE=1 bash samples/$s/build.sh >/dev/null && echo "samples/$s/$s.draw"; done+ for s in lantern ink-shapes bounce creature courier solids lemons ruin sign tree meadow paintover; do FORCE=1 bash samples/$s/build.sh >/dev/null || { echo "samples/$s failed" >&2; exit 1; }; echo "samples/$s"; doneapp:bash packaging/macos/app.shdiff --git a/samples/README.md b/samples/README.mdindex fcb9d82..7208099 100644--- a/samples/README.md+++ b/samples/README.md@@ -14,6 +14,7 @@ Drawings made from scratch with the `klad` CLI, each from a generator that print| `sign` | Lettering in fonts that come with klad: a gilded inn sign on a painted board, the text clipped to the board with a shadow and grain over it || `tree` | Foliage that reads as leaves: clumps built from leaf marks with `klad foliage`, each lit as a form and turning with the whole crown, leaves breaking the outline, a bark trunk painted as a cylinder || `meadow` | Grass that reads as grass with `klad grass`: a field receding in soft light patches, a near bank whose blades break its crest, and tufts with seed heads from a brush the build script makes itself (pictures drawn in klad, added with `klad brushes --picture` and `--set`) |+| `paintover` | Brushwork from a picture: the lemons repainted with `klad paintover`, and the creature's walk painted over once and carried drawing to drawing with `--like` and `--frames`, so the strokes move with the creature and the background stays still || `solids` | Painting stroke by stroke: a sphere, a cube and a cylinder built in 3D with `docs/skill/drawkit.py`, lit, painted with natural strokes |The generated `.draw` bundles and pictures stay out of git.diff --git a/samples/creature/build.sh b/samples/creature/build.shindex 7fe9766..d114dd3 100755--- a/samples/creature/build.sh+++ b/samples/creature/build.sh@@ -37,9 +37,9 @@ for keys in "0 2" "3 5" "5 7" "7 9"; dodone"$klad" inbetween "$out" --layers "$layers" --from 9 --loop --spacing in-out | grep 'in-between.* in \|left out\|unpaired\|by part'echo "timing:"-"$klad" retime "$out" 0-2 --pingpong | head -1-"$klad" retime "$out" 0-3 --on 3 | head -1-"$klad" retime "$out" 12-19 --on 2 | head -1+"$klad" retime "$out" 0-2 --pingpong | sed -n 1p+"$klad" retime "$out" 0-3 --on 3 | sed -n 1p+"$klad" retime "$out" 12-19 --on 2 | sed -n 1p"$klad" timeline "$out" --origin 512,820 >/dev/null"$klad" clip "$out"echo "the walk's arcs, in-betweened:"diff --git a/samples/paintover/build.py b/samples/paintover/build.pynew file mode 100644index 0000000..8cae756--- /dev/null+++ b/samples/paintover/build.py@@ -0,0 +1,17 @@+import json+import subprocess+import sys++klad, walk = sys.argv[1], sys.argv[2]+++def run(*args):+ return subprocess.run([klad, *args], check=True, capture_output=True, text=True).stdout+++run("add", walk, "layer", "paint", "name=brushwork", "id=brushwork")+timeline = json.loads(run("frames", walk, "--json"))+first = next(l for l in timeline["layers"] if not l["cels"][0]["id"].startswith("lines"))["cels"][0]["id"]+run("paintover", walk, "brushwork", "--frame", "0", "--sizes", "14,7", "--seed", "4")+last = timeline["frames"] - 1+print(run("paintover", walk, "brushwork", "--like", first, "--frames", f"0-{last}", "--sizes", "14,7", "--seed", "4"))diff --git a/samples/paintover/build.sh b/samples/paintover/build.shnew file mode 100755index 0000000..3e6d40b--- /dev/null+++ b/samples/paintover/build.sh@@ -0,0 +1,27 @@+#!/usr/bin/env bash+set -euo pipefail+here="$(cd "$(dirname "$0")" && pwd)"+root="$(cd "$here/../.." && pwd)"+case "$(uname -s)" in+ Darwin) built=target ;;+ Linux) built=target/linux ;;+ *) built=target/windows ;;+esac+klad="${KLAD:-$root/${KLAD_TARGET_DIR:-$built}/release/klad}"+still="${1:-$here/still.draw}"+walk="${still%still.draw}walk.draw"+for out in "$still" "$walk"; do+ if [ -e "$out" ] && [ "${FORCE:-0}" != 1 ]; then+ echo "$out exists and may hold edits made in the editor; give another path, or FORCE=1 to rebuild it" >&2+ exit 1+ fi+done+KLAD="$klad" FORCE=1 bash "$root/samples/lemons/build.sh" "$still" >/dev/null+"$klad" add "$still" layer paint name=brushwork >/dev/null+"$klad" paintover "$still" brushwork --sizes 32,16,8 --seed 2 2>&1 >/dev/null+"$klad" render "$still" -o "${still%.draw}.png" | tail -1+"$klad" hash "$still" --no-cache | sed -n 1p+KLAD="$klad" FORCE=1 bash "$root/samples/creature/build.sh" "$walk" >/dev/null+python3 "$here/build.py" "$klad" "$walk"+"$klad" render "$walk" --sheet walk --drawings -o "${walk%.draw}-sheet.png" | tail -1+"$klad" hash "$walk" --all --no-cache | sed -n 1,3pdiff --git a/samples/ruin/build.sh b/samples/ruin/build.shindex 717faf3..ac9f061 100755--- a/samples/ruin/build.sh+++ b/samples/ruin/build.sh@@ -17,4 +17,4 @@ rm -rf "$out""$klad" new "$out" --width 1920 --height 1080 --layers 0 --background '#1c2232' >/dev/nullpython3 "$here/generate.py" | "$klad" apply "$out" >/dev/null"$klad" render "$out" -o "${out%.draw}.png"-"$klad" hash "$out" --no-cache | head -1+"$klad" hash "$out" --no-cache | sed -n 1p