A drawing app built for agent/human collaboration
Rust
Shading pixels: steps along a ramp, dither, replacing a colour and a one-pixel outline
Indicode BVf386f170e97a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 57d80f4..5b460a7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,7 @@The first builds, and klad's licences.- A new icon, painted in klad: a K in two brush strokes.+- Shading pixels. The pixel pencil, the shape tool and the fill tool have three inks: **colour**, **lighter** and **darker**; the last two step the pixels you go over along their colour's ramp. **dither** draws a share of the pixels in an even pattern, with the **second colour** for the rest. **Layer > Outline the pixels** adds a one-pixel outline in the current colour, and **Lighter** and **Darker** in the bar under selected marks step them along their ramp. From the command line: `klad pixel --shade`, `--dither` with `--second`, `--outline` (`--inside`), `klad recolour --step`, and `klad recolour --from skin --to skin-dark` to replace a colour.- Selecting and editing pixels. On a pixel layer the stroke tool (**S**) drags a box, or a loop, around pixels and takes them, cutting marks between whole pixels; drag them to move by whole pixels, scale by whole numbers or turn by quarters, and the bar under them flips, turns, recolours (exactly the current colour), copies and deletes. **Select same colour** takes every mark in the selected colours. From the command line: `klad lasso` takes `--box x,y,w,h`, `klad strokes --entry skin` lists one colour's marks, and `klad recolour` gives pixel marks the exact palette colour.- Shapes and fill on the grid. On a pixel layer the fill tool (**G**) fills every pixel joined to the one you click that has exactly its colour (**across corners**, **read all pixel layers**), and the shape tool (**U**) drags a rectangle, an ellipse or a line of whole pixels, outlined or **filled**. From the command line: `klad pixel` with `--line`, `--rect`, `--ellipse` (`--filled`) and `--fill x,y` (`--diagonal`, `--ref`).- Sprites as text, for agents. `klad pixel sprite.klad l1 --grid sprite.txt` draws a sprite from a legend (`i = ink`) and rows of characters, one per pixel, each character becoming one mark bound to its palette colour; `klad pixels sprite.klad l1` reads a pixel layer back the same way, with its legend and numbered rows and columns (`--plain` in the form `--grid` reads, `--json`).diff --git a/crates/app/src/commands.rs b/crates/app/src/commands.rsindex 56d6fb8..e21b71b 100644--- a/crates/app/src/commands.rs+++ b/crates/app/src/commands.rs@@ -43,6 +43,9 @@ pub enum Cmd {CutLasso,Recolour,Thinner,+ ShadeLighter,+ ShadeDarker,+ PixelOutline,Thicker,AttachedOnly,Detach,@@ -513,7 +516,7 @@ use Repeat as R;use Trigger as T;impl Cmd {- pub const ALL: [Cmd; 186] = [+ pub const ALL: [Cmd; 189] = [Cmd::Brush,Cmd::Eraser,Cmd::Fill,@@ -553,6 +556,9 @@ impl Cmd {Cmd::CutLasso,Cmd::Recolour,Cmd::Thinner,+ Cmd::ShadeLighter,+ Cmd::ShadeDarker,+ Cmd::PixelOutline,Cmd::Thicker,Cmd::AttachedOnly,Cmd::Detach,@@ -1046,6 +1052,33 @@ impl Cmd {R::No,"give the selected strokes and fills the current colour",),+ Cmd::ShadeLighter => spec(+ "edit.lighter",+ "one step lighter",+ icon::PLUS,+ G::Edit,+ T::None,+ R::No,+ "the selected pixel marks take the next lighter colour of their ramp",+ ),+ Cmd::ShadeDarker => spec(+ "edit.darker",+ "one step darker",+ icon::MINUS,+ G::Edit,+ T::None,+ R::No,+ "the selected pixel marks take the next darker colour of their ramp",+ ),+ Cmd::PixelOutline => spec(+ "layer.pixel-outline",+ "outline the pixels",+ icon::PIXELS,+ G::Layers,+ T::None,+ R::No,+ "a one-pixel outline in the current colour around what the pixel layer shows, as one mark",+ ),Cmd::Thinner => spec("edit.thinner","make the selected strokes thinner",@@ -2418,6 +2451,9 @@ impl Cmd {Cmd::CutLasso => "Lasso cuts strokes",Cmd::Recolour => "Recolour",Cmd::Thinner => "Thinner",+ Cmd::ShadeLighter => "Lighter",+ Cmd::ShadeDarker => "Darker",+ Cmd::PixelOutline => "Outline the pixels",Cmd::Thicker => "Thicker",Cmd::AttachedOnly => "Attached only",Cmd::Detach => "Detach",@@ -2666,6 +2702,8 @@ pub const MENUS: [Menu; 9] = ["Strokes",&[Run(Cmd::Recolour),+ Run(Cmd::ShadeLighter),+ Run(Cmd::ShadeDarker),Run(Cmd::Thinner),Run(Cmd::Thicker),Line,@@ -2719,6 +2757,7 @@ pub const MENUS: [Menu; 9] = [items: &[Run(Cmd::NewPaintLayer),Run(Cmd::NewPixelLayer),+ Run(Cmd::PixelOutline),Run(Cmd::NewVectorLayer),Run(Cmd::NewAdjustLayer),Run(Cmd::NewGroupLayer),diff --git a/crates/app/src/editor.rs b/crates/app/src/editor.rsindex 06b385a..02b7ec6 100644--- a/crates/app/src/editor.rs+++ b/crates/app/src/editor.rs@@ -508,6 +508,13 @@ impl PreviewState {}}+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) enum PixelMode {+ Draw,+ Lighter,+ Darker,+}+#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub(crate) enum PixelShape {Rect,@@ -749,6 +756,9 @@ pub(crate) struct Editor {pub(crate) pixel_diagonal: bool,pub(crate) pixel_fill_all: bool,pub(crate) pixel_box: bool,+ pub(crate) pixel_mode: PixelMode,+ pub(crate) pixel_dither: u32,+ pub(crate) pixel_two: bool,pixel_live: Option<PixelLive>,pixel_last: Option<klad_core::pixel::Cell>,hover_cell: Option<[i32; 2]>,@@ -947,6 +957,9 @@ impl Editor {pixel_diagonal: false,pixel_fill_all: false,pixel_box: true,+ pixel_mode: PixelMode::Draw,+ pixel_dither: 100,+ pixel_two: false,pixel_live: None,pixel_last: None,hover_cell: None,@@ -3403,17 +3416,72 @@ impl Editor {klad_core::pixel::stamp(&run, self.pixel_size)}- fn pixel_spec(&self, erase: bool) -> Option<klad_core::ops::PixelSpec> {+ pub(super) fn pixel_spec(&self, erase: bool) -> Option<klad_core::ops::PixelSpec> {+ let shade = match (erase, self.pixel_mode) {+ (false, PixelMode::Lighter) => Some(1),+ (false, PixelMode::Darker) => Some(-1),+ _ => None,+ };+ let dither = (!erase && shade.is_none() && self.pixel_dither < 100).then_some(self.pixel_dither);Some(klad_core::ops::PixelSpec {layer: self.scene.active_id()?,frame: self.scene.frame,- color: (!erase).then(|| color::hex(self.color)),+ color: (!erase && shade.is_none()).then(|| color::hex(self.color)),erase,+ shade,+ dither,+ second: dither.filter(|_| self.pixel_two).map(|_| color::hex(self.second)),by_hand: true,..klad_core::ops::PixelSpec::default()})}+ pub(super) fn apply_pixels(&mut self, spec: klad_core::ops::PixelSpec) -> Result<()> {+ let drew = spec.color.is_some();+ match self.scene.bundle.settle_pixels(&[Op::Pixel(spec)]) {+ Ok(ops) => {+ self.apply(ops)?;+ if drew {+ self.used_colour();+ }+ }+ Err(e) => {+ let why = e.chain().last().map_or_else(|| format!("{e:#}"), ToString::to_string);+ self.say(Tone::Refused, why);+ }+ }+ Ok(())+ }++ fn step_picked(&mut self, by: i32) -> Result<()> {+ let doc = &self.scene.bundle.doc;+ let sets: Vec<(String, u32, &'static str, Value)> = self.chosen_marks().map_or(Vec::new(), |(_, chosen)| {+ chosen+ .iter()+ .filter_map(|(cel, m)| {+ let fill = m.as_fill().filter(|f| f.on_grid() && !f.erases())?;+ let at = fill+ .entry()+ .and_then(|entry| doc.swatch(entry))+ .or_else(|| doc.swatch(&klad_core::color::to_hex(fill.color())))?;+ let to = doc.ramp_step(at, by)?;+ Some((cel.clone(), m.id(), "color", json!(to.to_string())))+ })+ .collect()+ });+ if sets.is_empty() {+ self.say(+ Tone::Refused,+ match by > 0 {+ true => "nothing to step lighter: these colours are in no ramp, or at its light end (the ramp button makes one)",+ false => "nothing to step darker: these colours are in no ramp, or at its dark end (the ramp button makes one)",+ },+ );+ return Ok(());+ }+ self.set_picked(sets)+ }+fn fill_pixels(&mut self, at: klad_core::pixel::Cell) -> Result<()> {let (w, h) = self.scene.size();if at[0] < 0 || at[1] < 0 || at[0] >= w as i64 || at[1] >= h as i64 {@@ -3423,17 +3491,12 @@ impl Editor {let Some(spec) = self.pixel_spec(erase) else {return Ok(());};- let spec = klad_core::ops::PixelSpec {+ self.apply_pixels(klad_core::ops::PixelSpec {fill: Some(at),diagonal: self.pixel_diagonal,reference: self.pixel_fill_all.then(|| "all".to_string()),..spec- };- self.apply(vec![Op::Pixel(spec)])?;- if !erase {- self.used_colour();- }- Ok(())+ })}pub(super) fn pixel_shape_spec(&self) -> Option<klad_core::ops::PixelSpec> {@@ -3479,9 +3542,6 @@ impl Editor {let Some(live) = self.pixel_live.take() else {return Ok(());};- let Some(layer) = self.scene.active_id() else {- return Ok(());- };self.pixel_last = live.run.last().copied();let (w, h) = self.scene.size();let cells: Vec<klad_core::pixel::Cell> = self@@ -3489,23 +3549,10 @@ impl Editor {.into_iter().filter(|c| c[0] >= 0 && c[1] >= 0 && c[0] < w as i64 && c[1] < h as i64).collect();- if cells.is_empty() {+ let Some(spec) = self.pixel_spec(live.erase).filter(|_| !cells.is_empty()) else {return Ok(());- }- let spec = klad_core::ops::PixelSpec {- layer,- frame: self.scene.frame,- color: (!live.erase).then(|| color::hex(self.color)),- erase: live.erase,- cells,- by_hand: true,- ..klad_core::ops::PixelSpec::default()};- self.apply(vec![Op::Pixel(spec)])?;- if !live.erase {- self.used_colour();- }- Ok(())+ self.apply_pixels(klad_core::ops::PixelSpec { cells, ..spec })}fn finish_fill(&mut self) -> Result<()> {@@ -3799,18 +3846,37 @@ impl Editor {let shaped = self.pixel_shape_spec().filter(|_| self.tool == Tool::Shape && self.scene.on_grid())- .and_then(|spec| spec.drawn().ok().map(|cells| (cells, spec.erase)));+ .and_then(|spec| {+ klad_core::ops::PixelSpec {+ shade: None,+ dither: None,+ ..spec.clone()+ }+ .drawn()+ .ok()+ .map(|cells| (cells, spec.erase))+ });let drawing = self.pixel_live.as_ref().map(|live| (self.pixel_cells(live), live.erase)).or(shaped);if let Some((cells, erase)) = drawing {- let fill = match erase {- true => Color32::from_rgba_unmultiplied(255, 255, 255, 120),- false => color::color32(self.color),- };+ let shading = !erase && self.pixel_mode != PixelMode::Draw;+ let dither = (!erase && !shading && self.pixel_dither < 100).then_some(self.pixel_dither);cells.iter().for_each(|c| {+ let fill = match (erase, self.pixel_mode, dither) {+ (true, _, _) => Color32::from_rgba_unmultiplied(255, 255, 255, 120),+ (false, PixelMode::Lighter, _) => Color32::from_white_alpha(90),+ (false, PixelMode::Darker, _) => Color32::from_black_alpha(90),+ (false, PixelMode::Draw, Some(percent)) if !klad_core::pixel::dithered(*c, percent) => {+ match self.pixel_two {+ true => color::color32(self.second),+ false => Color32::TRANSPARENT,+ }+ }+ (false, PixelMode::Draw, _) => color::color32(self.color),+ };let (x, y) = (c[0] as f32, c[1] as f32);let corners = [(x, y), (x + 1.0, y), (x + 1.0, y + 1.0), (x, y + 1.0)].map(|(x, y)| self.screen(view, rect, vec2(x, y)))diff --git a/crates/app/src/editor/commands.rs b/crates/app/src/editor/commands.rsindex e79b512..ad0520c 100644--- a/crates/app/src/editor/commands.rs+++ b/crates/app/src/editor/commands.rs@@ -118,6 +118,17 @@ impl Editor {Cmd::SelectAll => (!self.active_paint() || self.scene.active_marks().is_empty()).then(|| "the active layer has no strokes on this frame".to_string()),Cmd::Recolour | Cmd::Thinner | Cmd::Thicker => need_strokes().or(editing),+ Cmd::ShadeLighter | Cmd::ShadeDarker => match self.scene.on_grid() {+ true => need_strokes().or(editing),+ false => {+ Some("select pixel marks on a pixel layer first: they step along their colour's ramp".to_string())+ }+ },+ Cmd::PixelOutline => match (self.scene.on_grid(), self.scene.active_marks().is_empty()) {+ (false, _) => Some("make a pixel layer active first".to_string()),+ (true, true) => Some("this drawing has no pixels to outline yet".to_string()),+ (true, false) => editing,+ },Cmd::AttachedOnly => need_strokes().or_else(|| {(self.attached_count() == 0)@@ -684,6 +695,20 @@ impl Editor {self.settings.pick_all_layers = !self.settings.pick_all_layers;self.settings_dirty = true;}+ Cmd::ShadeLighter => self.step_picked(1)?,+ Cmd::ShadeDarker => self.step_picked(-1)?,+ Cmd::PixelOutline => {+ if let Some(spec) = self.pixel_spec(false) {+ self.apply_pixels(klad_core::ops::PixelSpec {+ outline: true,+ shade: None,+ dither: None,+ second: None,+ color: Some(crate::color::hex(self.color)),+ ..spec+ })?;+ }+ }Cmd::Thinner => self.size_picked(0.8)?,Cmd::Thicker => self.size_picked(1.25)?,Cmd::AttachedOnly => self.select_attached()?,diff --git a/crates/app/src/editor/make.rs b/crates/app/src/editor/make.rsindex 24a614c..d610054 100644--- a/crates/app/src/editor/make.rs+++ b/crates/app/src/editor/make.rs@@ -110,12 +110,7 @@ impl Editor {let Some(spec) = spec else {return Ok(());};- let erase = spec.erase;- self.apply(vec![Op::Pixel(spec)])?;- if !erase {- self.used_colour();- }- return Ok(());+ return self.apply_pixels(spec);}let made = self.shape_now();self.shapes.drag = None;diff --git a/crates/app/src/editor/options.rs b/crates/app/src/editor/options.rsindex b8588bb..31d3761 100644--- a/crates/app/src/editor/options.rs+++ b/crates/app/src/editor/options.rs@@ -327,6 +327,7 @@ impl Editor {.hint("the pencil is a square of this many pixels a side; [ and ] change it");ui.checkbox(&mut self.pixel_perfect, "pixel perfect").hint("a one-pixel line drops the corner pixels a hand leaves, so curves stay one pixel thin");+ self.pixel_inks(ui);ui.label(RichText::new("draws whole pixels in the palette colour; shift click: a straight line from the last pixel").color(theme::WEAK),@@ -372,6 +373,7 @@ impl Editor {.hint("the fill also spreads to pixels that only touch at a corner");ui.checkbox(&mut self.pixel_fill_all, "read all pixel layers").hint("the fill stops at the pixels of every visible pixel layer, not only this one's: colour on a layer under the lines");+ self.pixel_inks(ui);ui.label(RichText::new("click a pixel: every pixel joined to it with exactly its colour takes the current colour").color(theme::WEAK),@@ -450,6 +452,7 @@ impl Editor {ui.checkbox(&mut self.pixel_filled, "filled").hint("every pixel inside, not only the outline");}+ self.pixel_inks(ui);let label = ui.label("size");ui.add(egui::DragValue::new(&mut self.pixel_size)@@ -709,6 +712,60 @@ impl Editor {edit}+ fn pixel_inks(&mut self, ui: &mut egui::Ui) {+ ui.separator();+ [+ (super::PixelMode::Draw, "colour", "draw in the current colour"),+ (+ super::PixelMode::Lighter,+ "lighter",+ "the pixels you go over take the next lighter colour of their ramp",+ ),+ (+ super::PixelMode::Darker,+ "darker",+ "the pixels you go over take the next darker colour of their ramp",+ ),+ ]+ .iter()+ .for_each(|(mode, label, hint)| {+ if ui+ .selectable_label(self.pixel_mode == *mode, *label)+ .hint(*hint)+ .clicked()+ {+ self.pixel_mode = *mode;+ }+ });+ if self.pixel_mode == super::PixelMode::Draw {+ let shown = match self.pixel_dither {+ 100 => "solid".to_string(),+ percent => format!("dither {percent}%"),+ };+ egui::ComboBox::from_id_salt("pixel dither")+ .selected_text(shown)+ .width(96.0)+ .show_ui(ui, |ui| {+ [+ (100, "solid"),+ (75, "dither 75%"),+ (50, "dither 50%"),+ (25, "dither 25%"),+ ]+ .iter()+ .for_each(|(percent, label)| {+ ui.selectable_value(&mut self.pixel_dither, *percent, *label);+ });+ })+ .response+ .hint("draw only a share of the pixels in an even pattern: 50% is a checkerboard");+ if self.pixel_dither < 100 {+ ui.checkbox(&mut self.pixel_two, "second colour")+ .hint("the pixels the pattern leaves out take the second colour (X swaps the two)");+ }+ }+ }+pub(super) fn palettes_window(&mut self, ctx: &egui::Context) {if !self.windows.palettes {return;diff --git a/crates/app/src/editor/selection.rs b/crates/app/src/editor/selection.rsindex edcce02..2ab6c96 100644--- a/crates/app/src/editor/selection.rs+++ b/crates/app/src/editor/selection.rs@@ -350,6 +350,8 @@ impl Editor {Cmd::TurnLeft90,Cmd::TurnRight90,Cmd::Recolour,+ Cmd::ShadeLighter,+ Cmd::ShadeDarker,Cmd::SelectSameColour,Cmd::Copy,Cmd::Paste,diff --git a/crates/app/src/editor/ui_tests.rs b/crates/app/src/editor/ui_tests.rsindex 121bb29..f224e15 100644--- a/crates/app/src/editor/ui_tests.rs+++ b/crates/app/src/editor/ui_tests.rs@@ -2028,6 +2028,139 @@ fn pixels_are_selected_by_box_or_colour_and_move_flip_turn_and_recolour_on_the_glet _ = std::fs::remove_dir_all(&plain);}+#[test]+fn the_pencil_shades_and_dithers_and_a_selection_steps_along_its_ramp_and_takes_an_outline() {+ let path = pixel_sample("pixel-shade");+ {+ let mut bundle = Bundle::open(&path).unwrap();+ let layer = bundle.doc.layers[0].id.clone();+ let ramp = klad_core::palettes::ramp_swatches("green", "#4c9a54", 3).unwrap();+ let keys: Vec<String> = ramp.iter().map(|s| format!("\"{}\"", s.color)).collect();+ bundle+ .apply(+ &parse_lines(&format!(+ "{}\n{}\n{}",+ format_args!(+ r##"{{"op":"palette","load":{}}}"##,+ serde_json::to_string(&ramp).unwrap()+ ),+ format_args!(r##"{{"op":"palette","ramp":"green","of":[{}]}}"##, keys.join(",")),+ format_args!(+ r##"{{"op":"pixel","layer":"{layer}","color":"green-2","rect":[12,4,8,6],"filled":true}}"##+ ),+ ))+ .unwrap(),+ )+ .unwrap();+ }+ let mut h = harness(editor(&path), vec2(1440.0, 900.0));+ let grid = |h: &Harness<'static, Editor>| -> Vec<String> {+ let ed = h.state();+ let doc = &ed.scene.bundle.doc;+ let grid = klad_core::pixel::grid_of(ed.scene.active_marks(), doc.canvas.width, doc.canvas.height);+ klad_core::pixel::rows(&grid, &klad_core::pixel::legend(doc, &grid))+ };+ let green = |h: &Harness<'static, Editor>, name: &str| -> char {+ let ed = h.state();+ let doc = &ed.scene.bundle.doc;+ let grid = klad_core::pixel::grid_of(ed.scene.active_marks(), doc.canvas.width, doc.canvas.height);+ let at = doc.swatch(name).unwrap();+ klad_core::pixel::legend(doc, &grid)+ .iter()+ .find(|n| n.key == doc.palette[at].id || n.color == doc.palette[at].color)+ .map_or('?', |n| n.sign)+ };+ h.state_mut().tool = Tool::Brush;+ h.run_steps(2);+ assert!(h.query_by_label("lighter").is_some() && h.query_by_label("darker").is_some());+ h.state_mut().pixel_mode = super::PixelMode::Darker;+ let (a, b) = (on_screen(&h, 12.5, 8.5), on_screen(&h, 19.5, 8.5));+ drag(&mut h, a, b);+ h.run_steps(3);+ ready(&mut h);+ let mid = green(&h, "green-2");+ let dark = green(&h, "green-1");+ assert_eq!(+ &grid(&h)[8][12..20],+ dark.to_string().repeat(8),+ "the row the pencil went over is a step darker"+ );+ assert_eq!(&grid(&h)[7][12..20], mid.to_string().repeat(8));+ let empty = on_screen(&h, 28.5, 20.5);+ click_with(&mut h, empty, Modifiers::NONE);+ h.run_steps(3);+ let refused = h.state().messages.latest().map(|m| m.text.clone()).unwrap_or_default();+ assert!(refused.contains("in no ramp"), "{refused}");+ h.state_mut().pixel_mode = super::PixelMode::Draw;+ h.state_mut().pixel_dither = 50;+ h.state_mut().pixel_two = true;+ h.state_mut()+ .set_colour(klad_core::color::parse_hex("#22223b").unwrap());+ h.state_mut().second = klad_core::color::parse_hex("#ef233c").unwrap();+ h.state_mut().tool = Tool::Shape;+ h.state_mut().pixel_filled = true;+ let (a, b) = (on_screen(&h, 24.5, 12.5), on_screen(&h, 27.5, 13.5));+ drag(&mut h, a, b);+ h.run_steps(3);+ ready(&mut h);+ let rows = grid(&h);+ let (one, two) = (rows[12].as_bytes()[24], rows[12].as_bytes()[25]);+ assert!(+ one != two && one != b'.' && two != b'.',+ "two colours side by side: {}",+ &rows[12][24..28]+ );+ assert_eq!(+ (+ rows[12].as_bytes()[26],+ rows[13].as_bytes()[24],+ rows[13].as_bytes()[25]+ ),+ (one, two, one),+ "in a checkerboard"+ );+ h.state_mut().pixel_dither = 100;+ h.state_mut().tool = Tool::Strokes;+ let block = on_screen(&h, 15.5, 5.5);+ click_with(&mut h, block, Modifiers::NONE);+ h.run_steps(3);+ assert!(h.state().picked.is_some(), "the green block is selected");+ h.state_mut().invoke(Cmd::ShadeLighter).unwrap();+ h.run_steps(3);+ ready(&mut h);+ let light = green(&h, "green-3");+ assert_eq!(+ &grid(&h)[5][12..20],+ light.to_string().repeat(8),+ "the mark took the next lighter colour of its ramp"+ );+ h.state_mut().invoke(Cmd::ShadeLighter).unwrap();+ h.run_steps(2);+ let end = h.state().messages.latest().map(|m| m.text.clone()).unwrap_or_default();+ assert!(end.contains("light end"), "{end}");+ h.state_mut().invoke(Cmd::Deselect).unwrap();+ let before = h.state().scene.active_marks().len();+ h.state_mut()+ .set_colour(klad_core::color::parse_hex("#101018").unwrap());+ h.state_mut().invoke(Cmd::PixelOutline).unwrap();+ h.run_steps(3);+ ready(&mut h);+ assert_eq!(+ h.state().scene.active_marks().len(),+ before + 1,+ "the outline is one mark"+ );+ let outlined = grid(&h);+ assert_ne!(+ outlined[3].as_bytes()[13],+ b'.',+ "a pixel above the block is outlined: {}",+ outlined[3]+ );+ assert_eq!(outlined[3].as_bytes()[11], b'.', "its corner is left open");+ let _ = std::fs::remove_dir_all(&path);+}+#[test]fn a_tap_that_wobbles_selects_and_a_drag_past_three_points_moves() {let path = sample("tap");diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rsindex 31bdb94..d8f38fb 100644--- a/crates/cli/src/main.rs+++ b/crates/cli/src/main.rs@@ -526,13 +526,44 @@ enum Command {},#[command(about = "Recolour strokes and fills together: the group moves to the colour and each keeps its own lighter or darker shade",- long_about = "Recolour strokes and fills together. The group's average colour moves to --to and every mark keeps its own difference from that average (in OKLab: lighter, darker, warmer, cooler), so painted strokes stay painted. One mark takes the colour as it is. One history step.\n\n klad recolour art.klad c9:s12 c9:s13 c9:s40 --to '#e3962f'\n klad recolour art.klad c9:s12 c9:s13 --to skin"+ long_about = "Recolour strokes and fills together. The group's average colour moves to --to and every mark keeps its own difference from that average (in OKLab: lighter, darker, warmer, cooler), so painted strokes stay painted. One mark takes the colour as it is. One history step.\n\n klad recolour art.klad c9:s12 c9:s13 c9:s40 --to '#e3962f'\n klad recolour art.klad c9:s12 c9:s13 --to skin\n\nPixel marks take exactly the colour and its palette entry, with no shades kept. On pixel layers there are two more forms: --step moves each mark along its colour's ramp (1 one lighter, -1 one darker), and --from replaces a colour, taking every mark drawn in it (in one --layer or at one --frame, or everywhere).\n\n klad recolour sprite.klad c2:s4 c2:s9 --step -1\n klad recolour sprite.klad --from skin --to skin-dark --layer l1")]Recolour {bundle: PathBuf,ids: Vec<String>,- #[arg(long, help = "The colour: #rrggbb or a palette name")]- to: String,+ #[arg(+ long,+ required_unless_present = "step",+ help = "The colour: #rrggbb or a palette name"+ )]+ to: Option<String>,+ #[arg(+ long,+ value_name = "STEPS",+ allow_hyphen_values = true,+ conflicts_with_all = ["to", "from"],+ help = "Pixel marks: step each along its colour's ramp instead, 1 one lighter, -1 one darker"+ )]+ step: Option<i32>,+ #[arg(+ long,+ value_name = "COLOUR",+ requires = "to",+ help = "Pixel layers: in place of marks, every mark of this palette colour (a name, a colour, an index or an id)"+ )]+ from: Option<String>,+ #[arg(+ long,+ requires = "from",+ help = "With --from: only this pixel layer (default: every pixel layer)"+ )]+ layer: Option<String>,+ #[arg(+ long,+ requires = "from",+ help = "With --from: only the drawing at this frame (default: every drawing)"+ )]+ frame: Option<u32>,#[command(flatten)]flags: EditFlags,},@@ -878,14 +909,14 @@ enum Command {},#[command(about = "Put whole pixels of one palette colour on a pixel layer, or erase them",- long_about = "Put whole pixels of one palette colour on a pixel layer, or erase them. A pixel layer is a grid with no anti-aliasing where one pixel is one canvas pixel; make a pixel drawing with klad new --pixel 64x64, or add a layer with klad add <bundle> layer pixel.\n\n--cells lists them: x,y for one pixel, x0-x1,y for a run along a row, x,y0-y1 for a run down a column and x0-x1,y0-y1 for a block. --color is a palette name, a palette index or #rrggbb; a colour the palette does not have yet is added to it. The pixels become one mark bound to that palette entry, so it can be recoloured (klad set <cel>:s<id> color=...), moved (klad transform) or removed (klad rm) later, and klad strokes lists it. --erase clears the pixels under it instead.\n\n--path draws SVG path data as a line of pixels: a pixel is the square from x,y to x+1,y+1, so aim at pixel middles (3.5, not 3). Straight segments keep the corners they are given; curves are cleaned so no corner is doubled. --size makes the pencil a square of that many pixels, for --cells and --path alike.\n\n klad pixel sprite.klad l1 --color '#2b2d42' --cells '3-12,4 3,5-9 12,5-9 3-12,10'\n klad pixel sprite.klad l1 --color '#2b2d42' --path 'M3.5 20.5 C 10 4 22 4 28.5 20.5'\n klad pixel sprite.klad l1 --erase --size 3 --path 'M4.5 4.5 L12.5 12.5'\n klad pixel sprite.klad l1 --color skin --cells '4-11,5-9'\n klad pixel sprite.klad l1 --erase --cells '7,7 8,7'\n\nShapes on the grid, each one mark: --line x0,y0,x1,y1 is a straight line between two pixels, --rect x,y,w,h and --ellipse x,y,w,h the outline of a rectangle or of the ellipse that fits that box (--filled for all of it), with --size for a thicker outline. --fill x,y is a flood fill: every pixel joined to that one that has exactly its colour, or is empty like it (--diagonal also crosses corners; --ref all reads every visible pixel layer, --ref <layer> another one, so flat colour can go on a layer under the lines).\n\n klad pixel sprite.klad l1 --color ink --ellipse 4,4,16,12\n klad pixel sprite.klad l1 --color body --fill 12,10\n klad pixel sprite.klad colour --color body --fill 12,10 --ref lines\n\n--grid draws a whole sprite from text, the way klad pixels --plain prints one: legend lines (one character, =, a palette name, a colour, erase or empty), a blank line, then a row of characters per row of pixels. . is empty unless the legend says otherwise. Each character becomes one mark bound to its colour; --at x,y moves the grid's top left.\n\n klad pixel sprite.klad l1 --grid - <<'GRID'\n i = ink\n b = body\n\n ..iiii..\n .ibbbbi.\n .ibbbbi.\n ..iiii..\n GRID\n\nAlso a pixel op in klad apply: {\"op\":\"pixel\",\"layer\":\"l1\",\"color\":\"skin\",\"cells\":[[4,5],[5,5]]}, with \"path\":\"M3.5 3.5 L9.5 3.5\" in place of cells, \"size\":2, or \"erase\":true; \"line\":[x0,y0,x1,y1], \"rect\":[x,y,w,h] or \"ellipse\":[x,y,w,h] with \"filled\":true; \"fill\":[x,y] with \"diagonal\" and \"ref\"; and as a grid {\"op\":\"pixel\",\"layer\":\"l1\",\"rows\":[\"..ii..\",\".ibbi.\"],\"legend\":{\"i\":\"ink\",\"b\":\"body\"},\"at\":[0,0]}."+ long_about = "Put whole pixels of one palette colour on a pixel layer, or erase them. A pixel layer is a grid with no anti-aliasing where one pixel is one canvas pixel; make a pixel drawing with klad new --pixel 64x64, or add a layer with klad add <bundle> layer pixel.\n\n--cells lists them: x,y for one pixel, x0-x1,y for a run along a row, x,y0-y1 for a run down a column and x0-x1,y0-y1 for a block. --color is a palette name, a palette index or #rrggbb; a colour the palette does not have yet is added to it. The pixels become one mark bound to that palette entry, so it can be recoloured (klad set <cel>:s<id> color=...), moved (klad transform) or removed (klad rm) later, and klad strokes lists it. --erase clears the pixels under it instead.\n\n--path draws SVG path data as a line of pixels: a pixel is the square from x,y to x+1,y+1, so aim at pixel middles (3.5, not 3). Straight segments keep the corners they are given; curves are cleaned so no corner is doubled. --size makes the pencil a square of that many pixels, for --cells and --path alike.\n\n klad pixel sprite.klad l1 --color '#2b2d42' --cells '3-12,4 3,5-9 12,5-9 3-12,10'\n klad pixel sprite.klad l1 --color '#2b2d42' --path 'M3.5 20.5 C 10 4 22 4 28.5 20.5'\n klad pixel sprite.klad l1 --erase --size 3 --path 'M4.5 4.5 L12.5 12.5'\n klad pixel sprite.klad l1 --color skin --cells '4-11,5-9'\n klad pixel sprite.klad l1 --erase --cells '7,7 8,7'\n\nShapes on the grid, each one mark: --line x0,y0,x1,y1 is a straight line between two pixels, --rect x,y,w,h and --ellipse x,y,w,h the outline of a rectangle or of the ellipse that fits that box (--filled for all of it), with --size for a thicker outline. --fill x,y is a flood fill: every pixel joined to that one that has exactly its colour, or is empty like it (--diagonal also crosses corners; --ref all reads every visible pixel layer, --ref <layer> another one, so flat colour can go on a layer under the lines).\n\n klad pixel sprite.klad l1 --color ink --ellipse 4,4,16,12\n klad pixel sprite.klad l1 --color body --fill 12,10\n klad pixel sprite.klad colour --color body --fill 12,10 --ref lines\n\nShading: --shade 1 (or -1) draws no colour of its own: every pixel it covers takes the next lighter (or darker) colour of its own ramp, so one call shades a form made of several colours; pixels in no ramp, or at its end, stay. --dither 50 draws only that share of the pixels in an even pattern (50 a checkerboard, 25 one in four), and --second gives the others a second colour, for a blend between two ramp steps. --outline draws a one-pixel outline around what the layer shows (--inside on its own edge pixels, --diagonal with the corners, --ref another layer or all).\n\n klad pixel sprite.klad l1 --shade -1 --rect 4,12,16,4 --filled\n klad pixel sprite.klad l1 --color wood-2 --second wood-3 --dither 50 --rect 4,8,16,2 --filled\n klad pixel sprite.klad l1 --color ink --outline\n\n--grid draws a whole sprite from text, the way klad pixels --plain prints one: legend lines (one character, =, a palette name, a colour, erase or empty), a blank line, then a row of characters per row of pixels. . is empty unless the legend says otherwise. Each character becomes one mark bound to its colour; --at x,y moves the grid's top left.\n\n klad pixel sprite.klad l1 --grid - <<'GRID'\n i = ink\n b = body\n\n ..iiii..\n .ibbbbi.\n .ibbbbi.\n ..iiii..\n GRID\n\nAlso a pixel op in klad apply: {\"op\":\"pixel\",\"layer\":\"l1\",\"color\":\"skin\",\"cells\":[[4,5],[5,5]]}, with \"path\":\"M3.5 3.5 L9.5 3.5\" in place of cells, \"size\":2, or \"erase\":true; \"line\":[x0,y0,x1,y1], \"rect\":[x,y,w,h] or \"ellipse\":[x,y,w,h] with \"filled\":true; \"fill\":[x,y] with \"diagonal\" and \"ref\"; and as a grid {\"op\":\"pixel\",\"layer\":\"l1\",\"rows\":[\"..ii..\",\".ibbi.\"],\"legend\":{\"i\":\"ink\",\"b\":\"body\"},\"at\":[0,0]}.")]Pixel {bundle: PathBuf,layer: String,#[arg(long,- required_unless_present_any = ["path", "grid", "line", "rect", "ellipse", "fill"],+ required_unless_present_any = ["path", "grid", "line", "rect", "ellipse", "fill", "outline"],help = "The pixels: x,y, a row run x0-x1,y, a column run x,y0-y1 or a block x0-x1,y0-y1, separated by spaces")]cells: Option<String>,@@ -929,16 +960,47 @@ enum Command {fill: Option<[i64; 2]>,#[arg(long,- requires = "fill",- help = "A fill also spreads across corners (eight neighbours, not four)"+ help = "A fill also spreads across corners (eight neighbours, not four); an outline also takes the corner pixels")]diagonal: bool,#[arg(long = "ref",- requires = "fill",- help = "What a fill reads: this layer (default), all (every visible pixel layer) or a pixel layer's id or name"+ help = "What a fill or an outline reads: this layer (default), all (every visible pixel layer) or a pixel layer's id or name")]reference: Option<String>,+ #[arg(+ long,+ conflicts_with_all = ["cells", "path", "grid", "line", "rect", "ellipse", "fill", "size"],+ help = "A one-pixel outline: every empty pixel that touches a drawn one (--inside: every drawn pixel that touches an empty one)"+ )]+ outline: bool,+ #[arg(+ long,+ requires = "outline",+ help = "The outline goes on the drawing's own edge pixels, not around it"+ )]+ inside: bool,+ #[arg(+ long,+ value_name = "STEPS",+ allow_hyphen_values = true,+ conflicts_with_all = ["color", "erase", "grid", "dither"],+ help = "Step the colours that are there along their ramps instead of drawing a colour: 1 one lighter, -1 one darker"+ )]+ shade: Option<i32>,+ #[arg(+ long,+ value_name = "PERCENT",+ conflicts_with_all = ["erase", "grid"],+ help = "Draw only this share of the pixels, in an even pattern: 50 is a checkerboard, 25 one pixel in four"+ )]+ dither: Option<u32>,+ #[arg(+ long,+ requires = "dither",+ help = "With --dither: the colour of the pixels the pattern leaves out"+ )]+ second: Option<String>,#[arg(long,value_name = "FILE",@@ -2651,9 +2713,26 @@ fn run() -> Result<()> {};agent::edit(&bundle, &[op], &output(&flags, frame))?;}- Command::Recolour { bundle, ids, to, flags } => {- let ops = recolour_ops(&bundle, &ids, &to)?;- agent::edit(&bundle, &ops, &output(&flags, 0))?;+ Command::Recolour {+ bundle,+ ids,+ to,+ step,+ from,+ layer,+ frame,+ flags,+ } => {+ let ids = match &from {+ Some(colour) => marks_of_colour(&bundle, colour, layer.as_deref(), frame)?,+ None => ids,+ };+ let ops = match (step, to) {+ (Some(by), _) => step_ops(&bundle, &ids, by)?,+ (None, Some(to)) => recolour_ops(&bundle, &ids, &to)?,+ (None, None) => return Err(anyhow!("recolour needs --to <colour> or --step <steps>")),+ };+ agent::edit(&bundle, &ops, &output(&flags, frame.unwrap_or(0)))?;}Command::Detach { bundle, ids, flags } => {if ids.is_empty() {@@ -2970,6 +3049,11 @@ fn run() -> Result<()> {fill,diagonal,reference,+ outline,+ inside,+ shade,+ dither,+ second,size,color,erase,@@ -3009,6 +3093,11 @@ fn run() -> Result<()> {fill,diagonal,reference,+ outline,+ inside,+ shade,+ dither,+ second,size,part,by_hand: false,@@ -4212,6 +4301,104 @@ pub fn copy_tag(doc: &klad_core::doc::Document) -> String {}}+fn marks_of_colour(path: &Path, colour: &str, layer: Option<&str>, frame: Option<u32>) -> Result<Vec<String>> {+ let bundle = Bundle::open(path)?;+ let doc = &bundle.doc;+ let at = doc+ .swatch(colour)+ .ok_or_else(|| anyhow!("the palette has no {colour:?} (give a name, a colour, an index or an id)"))?;+ let entry = doc.palette[at].id.clone();+ let layers: Vec<&klad_core::doc::Layer> = match layer {+ Some(key) => vec![doc.find_layer(key)?],+ None => doc.all_layers().into_iter().filter(|l| l.pixel()).collect(),+ };+ if let Some(other) = layers.iter().find(|l| !l.pixel()) {+ bail!(+ "{} is a {} layer: --from picks pixel marks by their palette colour",+ other.id,+ other.kind_name()+ );+ }+ let found = layers+ .iter()+ .flat_map(|l| {+ l.cels()+ .iter()+ .filter(|c| c.link.is_none())+ .filter(|c| frame.is_none_or(|f| l.content_at(f).is_some_and(|shown| shown.id == c.id)))+ .map(move |c| (*l, c))+ })+ .map(|(l, c)| {+ Ok(bundle+ .read_marks(&l.id, &c.id)?+ .iter()+ .filter(|m| {+ m.as_fill()+ .is_some_and(|f| !entry.is_empty() && f.entry() == Some(entry.as_str()))+ })+ .map(|m| klad_core::markedit::address(&c.id, m.id()))+ .collect::<Vec<_>>())+ })+ .collect::<Result<Vec<_>>>()?+ .into_iter()+ .flatten()+ .collect::<Vec<_>>();+ if found.is_empty() {+ bail!("no pixel mark is drawn in {colour:?} there");+ }+ Ok(found)+}++fn step_ops(path: &Path, ids: &[String], by: i32) -> Result<Vec<Op>> {+ if ids.is_empty() || by == 0 {+ return Err(anyhow!(+ "give the pixel marks to step, as <cel>:s<id>, and a number of steps: 1 one lighter, -1 one darker"+ ));+ }+ let bundle = Bundle::open(path)?;+ let doc = &bundle.doc;+ let ops = ids+ .iter()+ .map(|id| {+ let (cel, mark) =+ klad_core::markedit::parse_address(id).ok_or_else(|| anyhow!("{id} is not a mark: use <cel>:s<id>"))?;+ let owner = doc+ .all_layers()+ .into_iter()+ .find(|l| l.cels().iter().any(|c| c.id == cel))+ .ok_or_else(|| anyhow!("no drawing {cel}"))?;+ let marks = bundle.read_marks(&owner.id, cel)?;+ let fill = marks+ .iter()+ .find(|m| m.id() == mark)+ .ok_or_else(|| anyhow!("{id} does not exist"))?+ .as_fill()+ .filter(|f| f.on_grid() && !f.erases())+ .ok_or_else(|| {+ anyhow!("{id} is not a pixel mark with a colour: --step moves pixel marks along their ramp")+ })?;+ let at = fill+ .entry()+ .and_then(|entry| doc.swatch(entry))+ .or_else(|| doc.swatch(&klad_core::color::to_hex(fill.color())));+ Ok(at.and_then(|at| doc.ramp_step(at, by)).map(|to| Op::Set {+ id: id.clone(),+ props: serde_json::Map::from_iter([("color".to_string(), serde_json::json!(to.to_string()))]),+ }))+ })+ .collect::<Result<Vec<_>>>()?+ .into_iter()+ .flatten()+ .collect::<Vec<_>>();+ if ops.is_empty() {+ bail!(+ "none of these marks can step {}: their colours are in no ramp, or already at its end (klad palette --ramp groups colours)",+ if by > 0 { "lighter" } else { "darker" }+ );+ }+ Ok(ops)+}+fn recolour_ops(path: &Path, ids: &[String], to: &str) -> Result<Vec<Op>> {if ids.is_empty() {return Err(anyhow!("give the strokes and fills to recolour, as <cel>:s<id>"));diff --git a/crates/cli/tests/binary.rs b/crates/cli/tests/binary.rsindex dbcc586..72f8d66 100644--- a/crates/cli/tests/binary.rs+++ b/crates/cli/tests/binary.rs@@ -931,6 +931,74 @@ fn pixel_marks_are_listed_by_colour_cut_by_a_box_and_recoloured_exactly() {std::fs::remove_dir_all(&dir).unwrap();}+#[test]+fn pixels_are_shaded_dithered_outlined_and_replaced_from_the_command_line() {+ let dir = std::env::temp_dir().join(format!("draw-binary-shade-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ let bundle = dir.join("sprite.klad");+ let path = bundle.to_str().unwrap();+ let run = |args: &[&str]| Command::new(env!("CARGO_BIN_EXE_klad")).args(args).output().unwrap();+ let draw = |args: &[&str]| {+ let out = run(args);+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));+ String::from_utf8_lossy(&out.stdout).to_string()+ };+ let rows = || -> Vec<String> {+ draw(&["pixels", path, "l1", "--plain"])+ .lines()+ .skip_while(|line| !line.is_empty())+ .skip(1)+ .map(String::from)+ .collect()+ };+ draw(&["new", path, "--pixel", "12x8"]);+ draw(&["palette", path, "--ramp", "green", "--base", "#4c9a54", "--steps", "3"]);+ draw(&["palette", path, "--add", "#22223b", "--name", "ink"]);+ draw(&[+ "pixel", path, "l1", "--color", "green-2", "--rect", "4,3,3,2", "--filled",+ ]);+ draw(&["pixel", path, "l1", "--color", "ink", "--outline"]);+ assert_eq!(+ rows()[2..6],+ ["....iii.....", "...iGGGi....", "...iGGGi....", "....iii....."],+ "a one-pixel outline around the block"+ );+ draw(&["pixel", path, "l1", "--shade", "-1", "--rect", "4,4,3,1"]);+ draw(&["pixel", path, "l1", "--shade", "1", "--cells", "4,3"]);+ assert_eq!(+ rows()[3..5],+ ["...iaGGi....", "...igggi...."],+ "a highlight and a darker foot"+ );+ let first = serde_json::from_str::<serde_json::Value>(&draw(&["strokes", path, "l1", "--json"])).unwrap()["fills"]+ [0]["address"]+ .as_str()+ .unwrap()+ .to_string();+ draw(&["recolour", path, &first, "--step", "1"]);+ assert_eq!(+ rows()[3],+ "...iaaai....",+ "the block itself stepped lighter along its ramp"+ );+ draw(&["recolour", path, "--from", "ink", "--to", "green-1"]);+ assert_eq!(rows()[2], "....ggg.....", "every ink mark is the dark green now");+ draw(&[+ "pixel", path, "l1", "--color", "ink", "--second", "green-3", "--dither", "50", "--rect", "8,0,4,2", "--filled",+ ]);+ assert_eq!(+ rows()[..2],+ ["........iaia", "........aiai"],+ "a checkerboard of two colours"+ );+ let none = run(&["recolour", path, &first, "--step", "5"]);+ assert!(String::from_utf8_lossy(&none.stderr).contains("already at its end"));+ let both = run(&["pixel", path, "l1", "--shade", "1", "--color", "ink", "--cells", "1,1"]);+ assert!(!both.status.success());+ std::fs::remove_dir_all(&dir).unwrap();+}+#[test]fn recolour_moves_strokes_together_and_keeps_their_shades() {let dir = std::env::temp_dir().join(format!("draw-binary-recolour-{}", std::process::id()));diff --git a/crates/core/src/bundle.rs b/crates/core/src/bundle.rsindex 8261bce..eb172f6 100644--- a/crates/core/src/bundle.rs+++ b/crates/core/src/bundle.rs@@ -407,20 +407,18 @@ impl Bundle {self.apply_as(ops, "cli")}- fn flooded(+ fn shown(&self,doc: &Document,plan: &[PendingMarks],spec: &crate::ops::PixelSpec,- ) -> Result<crate::ops::PixelSpec> {+ reference: Option<&str>,+ ) -> Result<crate::pixel::Grid> {use crate::pixel;- let Some(seed) = spec.fill else {- return Ok(spec.clone());- };let own = doc.layer(&spec.layer).ok_or_else(|| anyhow!("no layer {}", spec.layer))?;- let layers: Vec<&Layer> = match spec.reference.as_deref().map(str::trim) {+ let layers: Vec<&Layer> = match reference.map(str::trim) {None | Some("this") => vec![own],Some("all") => doc.all_layers()@@ -429,12 +427,12 @@ impl Bundle {.collect(),Some(key) => vec![doc.find_layer(key)- .map_err(|e| anyhow!("fill reference: {e}; or use this or all"))?,+ .map_err(|e| anyhow!("reference: {e}; or use this or all"))?,],};if let Some(other) = layers.iter().find(|l| !l.pixel()) {bail!(- "{} is a {} layer: a pixel fill reads pixel layers",+ "{} is a {} layer: a pixel fill, outline or shade reads pixel layers",other.id,other.kind_name());@@ -450,46 +448,146 @@ impl Bundle {Ok(pixel::grid_of(&marks, w, h))}).collect::<Result<Vec<_>>>()?;- let grid = pixel::merged(&grids).unwrap_or_else(|| pixel::grid_of(&[], w, h));- let cells = pixel::flood(&grid, seed, spec.diagonal);- if cells.is_empty() {- bail!(- "the fill starts at {},{}, which is off the {w}x{h} canvas",- seed[0],- seed[1]- );- }- Ok(crate::ops::PixelSpec {- cells,+ Ok(pixel::merged(&grids).unwrap_or_else(|| pixel::grid_of(&[], w, h)))+ }++ fn settled(+ &self,+ doc: &Document,+ plan: &[PendingMarks],+ spec: &crate::ops::PixelSpec,+ ) -> Result<Vec<crate::ops::PixelSpec>> {+ use crate::ops::PixelSpec;+ use crate::pixel;+ spec.check()?;+ let (w, h) = (doc.canvas.width, doc.canvas.height);+ let placed = match (spec.fill, spec.outline) {+ (Some(seed), _) => {+ let grid = self.shown(doc, plan, spec, spec.reference.as_deref())?;+ let cells = pixel::flood(&grid, seed, spec.diagonal);+ if cells.is_empty() {+ bail!(+ "the fill starts at {},{}, which is off the {w}x{h} canvas",+ seed[0],+ seed[1]+ );+ }+ cells+ }+ (None, true) => {+ let grid = self.shown(doc, plan, spec, spec.reference.as_deref())?;+ let cells = pixel::outline(&grid, spec.inside, spec.diagonal);+ if cells.is_empty() {+ bail!("there are no pixels to outline at frame {}", spec.frame);+ }+ cells+ }+ (None, false) => PixelSpec {+ shade: None,+ dither: None,+ ..spec.clone()+ }+ .drawn()?,+ };+ let plain = PixelSpec {+ cells: Vec::new(),+ path: None,+ line: None,+ rect: None,+ ellipse: None,+ filled: false,fill: None,+ diagonal: false,+ reference: None,+ outline: false,+ inside: false,+ shade: None,+ dither: None,+ second: None,+ size: 1,..spec.clone()- })+ };+ if let Some(by) = spec.shade {+ let grid = self.shown(doc, plan, spec, None)?;+ let mut stepped: BTreeMap<usize, Vec<pixel::Cell>> = BTreeMap::new();+ placed+ .iter()+ .filter(|c| c[0] >= 0 && c[1] >= 0 && c[0] < w as i64 && c[1] < h as i64)+ .for_each(|c| {+ let to = grid+ .at(c[0] as u32, c[1] as u32)+ .and_then(|key| doc.swatch(key))+ .and_then(|at| doc.ramp_step(at, by));+ if let Some(to) = to {+ stepped.entry(to).or_default().push(*c);+ }+ });+ if stepped.is_empty() {+ bail!(+ "none of these pixels can step {}: their colours are in no ramp, or already at its end (klad palette --ramp groups colours)",+ if by > 0 { "lighter" } else { "darker" }+ );+ }+ return Ok(stepped+ .into_iter()+ .map(|(to, cells)| PixelSpec {+ color: Some(to.to_string()),+ cells,+ ..plain.clone()+ })+ .collect());+ }+ let Some(percent) = spec.dither else {+ return Ok(vec![PixelSpec { cells: placed, ..plain }]);+ };+ let (on, off): (Vec<pixel::Cell>, Vec<pixel::Cell>) =+ placed.into_iter().partition(|c| pixel::dithered(*c, percent));+ let first = (!on.is_empty()).then(|| PixelSpec {+ cells: on,+ ..plain.clone()+ });+ let second = spec+ .second+ .as_ref()+ .filter(|_| !off.is_empty())+ .map(|colour| PixelSpec {+ color: Some(colour.clone()),+ cells: off,+ ..plain.clone()+ });+ let both: Vec<PixelSpec> = first.into_iter().chain(second).collect();+ if both.is_empty() {+ bail!("a dither of {percent}% with no second colour leaves no pixel to draw");+ }+ Ok(both)}pub fn settle_pixels(&self, ops: &[Op]) -> Result<Vec<Op>> {- if !ops- .iter()- .any(|op| matches!(op, Op::Pixel(spec) if spec.fill.is_some()))- {+ if !ops.iter().any(|op| matches!(op, Op::Pixel(spec) if !spec.settled())) {return Ok(ops.to_vec());}let mut doc = self.doc.clone();let mut applied = Applied::default();- ops.iter()- .enumerate()- .map(|(i, op)| {- let op = match op {- Op::Pixel(spec) if spec.fill.is_some() => Op::Pixel(- self.flooded(&doc, &applied.marks, spec)- .with_context(|| format!("op {}: pixel fill on {}", i + 1, spec.layer))?,- ),- other => other.clone(),- };- crate::ops::apply(&mut doc, &op, &mut applied).with_context(|| format!("op {}", i + 1))?;+ let mut out = Vec::with_capacity(ops.len());+ ops.iter().enumerate().try_for_each(|(i, op)| {+ let made = match op {+ Op::Pixel(spec) if !spec.settled() => self+ .settled(&doc, &applied.marks, spec)+ .with_context(|| format!("op {}: pixels on {}", i + 1, spec.layer))?+ .into_iter()+ .map(Op::Pixel)+ .collect(),+ other => vec![other.clone()],+ };+ made.iter().try_for_each(|op| {+ crate::ops::apply(&mut doc, op, &mut applied).with_context(|| format!("op {}", i + 1))?;crate::timing::grow(&mut doc);- Ok(op)- })- .collect()+ Ok::<_, anyhow::Error>(())+ })?;+ out.extend(made);+ Ok::<_, anyhow::Error>(())+ })?;+ Ok(out)}pub fn apply_as(&mut self, ops: &[Op], author: &str) -> Result<Applied> {@@ -1895,4 +1993,167 @@ mod tests {);fs::remove_dir_all(&dir).unwrap();}++ #[test]+ fn pixels_shade_along_their_ramp_dither_between_two_colours_and_take_an_outline() {+ use crate::ops::parse_lines;+ let dir = scratch("pixel-shade");+ let mut bundle = Bundle::blank(+ &dir,+ &Blank {+ width: 12,+ height: 8,+ pixel: true,+ ..Blank::default()+ },+ "cli",+ )+ .unwrap();+ let layer = bundle.doc.layers[0].id.clone();+ let ramp = crate::palettes::ramp_swatches("green", "#4c9a54", 3).unwrap();+ let keys: Vec<String> = ramp.iter().map(|s| format!("\"{}\"", s.color)).collect();+ let run = |bundle: &mut Bundle, lines: String| bundle.apply(&parse_lines(&lines).unwrap()).unwrap();+ run(+ &mut bundle,+ format!(+ "{}\n{}\n{}\n{}\n{}",+ format_args!(+ r##"{{"op":"palette","load":{}}}"##,+ serde_json::to_string(&ramp).unwrap()+ ),+ format_args!(r##"{{"op":"palette","ramp":"green","of":[{}]}}"##, keys.join(",")),+ r##"{"op":"palette","add":"#22223b","name":"ink"}"##,+ format_args!(+ r##"{{"op":"pixel","layer":"{layer}","color":"green-2","rect":[2,2,4,4],"filled":true}}"##+ ),+ format_args!(r##"{{"op":"pixel","layer":"{layer}","color":"ink","cells":[[9,2]]}}"##),+ ),+ );+ let rows = |bundle: &Bundle| -> Vec<String> {+ let cel = bundle.doc.layers[0].cels()[0].id.clone();+ let grid = crate::pixel::grid_of(&bundle.read_marks(&layer, &cel).unwrap(), 12, 8);+ let legend = crate::pixel::legend(&bundle.doc, &grid);+ crate::pixel::rows(&grid, &legend)+ };+ assert_eq!(+ rows(&bundle)[2],+ "..GGGG...i..",+ "green-1 is g, green-2 is G, green-3 is a"+ );+ run(+ &mut bundle,+ format!(+ "{}\n{}",+ format_args!(r##"{{"op":"pixel","layer":"{layer}","shade":-1,"rect":[2,4,10,2],"filled":true}}"##),+ format_args!(r##"{{"op":"pixel","layer":"{layer}","shade":1,"cells":[[2,2],[3,2],[9,2],[0,0]]}}"##),+ ),+ );+ assert_eq!(+ rows(&bundle)[..6],+ [+ "............",+ "............",+ "..aaGG...i..",+ "..GGGG......",+ "..gggg......",+ "..gggg......"+ ],+ "the lower half is a step darker and two pixels a step lighter; ink is in no ramp and the empty pixel stays empty"+ );+ let marks = |bundle: &Bundle| {+ let cel = bundle.doc.layers[0].cels()[0].id.clone();+ bundle.read_marks(&layer, &cel).unwrap().len()+ };+ assert_eq!(marks(&bundle), 4, "each shade is one mark per colour it makes");+ run(+ &mut bundle,+ format!(r##"{{"op":"pixel","layer":"{layer}","shade":1,"rect":[2,4,4,2],"filled":true}}"##),+ );+ assert_eq!(rows(&bundle)[4], "..GGGG......", "and a step back up");+ let stuck = bundle+ .settle_pixels(+ &parse_lines(&format!(+ r##"{{"op":"pixel","layer":"{layer}","shade":1,"cells":[[9,2]]}}"##+ ))+ .unwrap(),+ )+ .unwrap_err();+ assert!(format!("{stuck:#}").contains("in no ramp"), "{stuck:#}");+ run(+ &mut bundle,+ format!(+ "{}\n{}",+ format_args!(+ r##"{{"op":"pixel","layer":"{layer}","color":"ink","second":"green-3","dither":50,"rect":[7,4,4,4],"filled":true}}"##+ ),+ format_args!(+ r##"{{"op":"pixel","layer":"{layer}","color":"ink","dither":25,"rect":[0,6,4,2],"filled":true}}"##+ ),+ ),+ );+ let after = rows(&bundle);+ assert_eq!(&after[4][7..11], "aiai", "a checkerboard of the two colours: {after:?}");+ assert_eq!(&after[5][7..11], "iaia");+ assert_eq!(+ (&after[6][..4], &after[7][..4]),+ ("i.i.", "...."),+ "a quarter of the pixels, the rest left alone"+ );+ run(+ &mut bundle,+ format!(+ "{}\n{}",+ format_args!(r##"{{"op":"rm","ids":["{layer}"]}}"##),+ r##"{"op":"add","layer":{"kind":"pixel","name":"blob","id":"lb"}}"##,+ ),+ );+ run(+ &mut bundle,+ format!(+ "{}\n{}",+ r##"{"op":"pixel","layer":"lb","color":"green-2","rect":[4,3,3,2],"filled":true}"##,+ r##"{"op":"pixel","layer":"lb","color":"ink","outline":true}"##,+ ),+ );+ let blob = |bundle: &Bundle| -> Vec<String> {+ let cel = bundle.doc.layer("lb").unwrap().cels()[0].id.clone();+ let grid = crate::pixel::grid_of(&bundle.read_marks("lb", &cel).unwrap(), 12, 8);+ crate::pixel::rows(&grid, &crate::pixel::legend(&bundle.doc, &grid))+ };+ assert_eq!(+ blob(&bundle)[1..7],+ [+ "............",+ "....iii.....",+ "...iGGGi....",+ "...iGGGi....",+ "....iii.....",+ "............"+ ],+ "one pixel around the block, corners left open"+ );+ run(+ &mut bundle,+ r##"{"op":"pixel","layer":"lb","color":"green-3","outline":true,"inside":true,"diagonal":true}"##+ .to_string(),+ );+ assert_eq!(+ blob(&bundle)[2],+ "....aaa.....",+ "an inside outline recolours the edge pixels: here the ink ring's own edge"+ );+ let wrong = |line: &str| format!("{:#}", parse_lines(line).unwrap_err());+ assert!(+ wrong(r##"{"op":"pixel","layer":"lb","color":"ink","shade":1,"cells":[[1,1]]}"##)+ .contains("leave out color")+ );+ assert!(+ wrong(r##"{"op":"pixel","layer":"lb","color":"ink","second":"ink","cells":[[1,1]]}"##)+ .contains("give dither too")+ );+ assert!(+ wrong(r##"{"op":"pixel","layer":"lb","color":"ink","dither":140,"cells":[[1,1]]}"##).contains("0 to 100")+ );+ fs::remove_dir_all(&dir).unwrap();+ }}diff --git a/crates/core/src/doc.rs b/crates/core/src/doc.rsindex ac0445d..eeb97a4 100644--- a/crates/core/src/doc.rs+++ b/crates/core/src/doc.rs@@ -1244,6 +1244,19 @@ impl Document {.collect()}+ pub fn ramp_step(&self, at: usize, by: i32) -> Option<usize> {+ let ramp = &self.palette.get(at)?.ramp;+ if ramp.is_empty() {+ return None;+ }+ let members: Vec<usize> = (0..self.palette.len())+ .filter(|i| &self.palette[*i].ramp == ramp)+ .collect();+ let here = members.iter().position(|i| *i == at)? as i64;+ let there = (here + by as i64).clamp(0, members.len() as i64 - 1);+ (there != here).then(|| members[there as usize])+ }+pub fn entry(&self, id: &str) -> Option<&Swatch> {self.palette.iter().find(|s| !s.id.is_empty() && s.id == id)}diff --git a/crates/core/src/ops.rs b/crates/core/src/ops.rsindex a773a78..a06feb3 100644--- a/crates/core/src/ops.rs+++ b/crates/core/src/ops.rs@@ -307,6 +307,16 @@ pub struct PixelSpec {pub diagonal: bool,#[serde(default, rename = "ref")]pub reference: Option<String>,+ #[serde(default)]+ pub outline: bool,+ #[serde(default)]+ pub inside: bool,+ #[serde(default)]+ pub shade: Option<i32>,+ #[serde(default)]+ pub dither: Option<u32>,+ #[serde(default)]+ pub second: Option<String>,#[serde(default = "one_pixel")]pub size: u32,#[serde(default)]@@ -335,6 +345,11 @@ impl Default for PixelSpec {fill: None,diagonal: false,reference: None,+ outline: false,+ inside: false,+ shade: None,+ dither: None,+ second: None,size: 1,part: None,by_hand: false,@@ -394,11 +409,36 @@ impl GridSpec {impl PixelSpec {pub fn check(&self) -> Result<()> {- match (&self.color, self.erase) {- (Some(_), true) => bail!("pixel takes a color or erase, not both"),- (None, false) => bail!("pixel needs a color (a palette name or #rrggbb) or \"erase\":true"),+ match (&self.color, self.erase, self.shade) {+ (Some(_), true, _) => bail!("pixel takes a color or erase, not both"),+ (Some(_), _, Some(_)) | (_, true, Some(_)) => {+ bail!("shade steps the colours that are there along their ramps: leave out color and erase")+ }+ (None, false, None) => {+ bail!(+ "pixel needs a color (a palette name or #rrggbb), \"erase\":true or \"shade\" (steps along the ramp)"+ )+ }_ => {}}+ if self.shade == Some(0) {+ bail!("shade takes a number of steps along the ramp: 1 is one lighter, -1 one darker");+ }+ if self.dither.is_some_and(|d| d > 100) {+ bail!("dither is a share of the pixels in percent, 0 to 100");+ }+ if self.second.is_some() && self.dither.is_none() {+ bail!("second is the other colour of a dither: give dither too");+ }+ if self.dither.is_some() && (self.erase || self.shade.is_some()) {+ bail!("dither goes with a color (and a second one), not with erase or shade");+ }+ if self.inside && !self.outline {+ bail!("inside goes with outline");+ }+ if self.diagonal && !self.outline && self.fill.is_none() {+ bail!("diagonal goes with fill or outline");+ }let sources = [!self.cells.is_empty(),self.path.is_some(),@@ -406,16 +446,17 @@ impl PixelSpec {self.rect.is_some(),self.ellipse.is_some(),self.fill.is_some(),+ self.outline,].iter().filter(|given| **given).count();match sources {0 => bail!(- "pixel needs one of: cells (a list of [x, y]), path (SVG path data), line ([x0, y0, x1, y1]), rect or ellipse ([x, y, w, h]) or fill ([x, y], a flood fill)"+ "pixel needs one of: cells (a list of [x, y]), path (SVG path data), line ([x0, y0, x1, y1]), rect or ellipse ([x, y, w, h]), fill ([x, y], a flood fill) or outline"),1 => {}- _ => bail!("pixel takes one of cells, path, line, rect, ellipse and fill, not several"),+ _ => bail!("pixel takes one of cells, path, line, rect, ellipse, fill and outline, not several"),}if [self.rect, self.ellipse].iter()@@ -437,14 +478,18 @@ impl PixelSpec {Ok(())}+ pub fn settled(&self) -> bool {+ self.fill.is_none() && !self.outline && self.shade.is_none() && self.dither.is_none()+ }+pub fn drawn(&self) -> Result<Vec<[i64; 2]>> {use crate::pixel;if let Some(d) = &self.path {return Ok(pixel::drawn(&pixel::of_path(d)?, self.size));}- if self.fill.is_some() {+ if !self.settled() {bail!(- "a flood fill of pixels is worked out from the drawing by klad pixel --fill, klad apply or the editor"+ "a fill, an outline, a shade or a dither of pixels is worked out from the drawing by klad pixel, klad apply or the editor");}let cells = match (self.line, self.rect, self.ellipse) {diff --git a/crates/core/src/pixel.rs b/crates/core/src/pixel.rsindex b86903e..0ca4c1b 100644--- a/crates/core/src/pixel.rs+++ b/crates/core/src/pixel.rs@@ -249,6 +249,28 @@ pub fn flood(grid: &Grid, at: Cell, diagonal: bool) -> Vec<Cell> {out}+const BAYER: [[u32; 4]; 4] = [[0, 8, 2, 10], [12, 4, 14, 6], [3, 11, 1, 9], [15, 7, 13, 5]];++pub fn dithered(cell: Cell, percent: u32) -> bool {+ let level = (percent.min(100) * 16 + 50) / 100;+ BAYER[cell[1].rem_euclid(4) as usize][cell[0].rem_euclid(4) as usize] < level+}++pub fn outline(grid: &Grid, inside: bool, diagonal: bool) -> Vec<Cell> {+ let (w, h) = (grid.width as i64, grid.height as i64);+ let filled =+ |c: Cell| c[0] >= 0 && c[1] >= 0 && c[0] < w && c[1] < h && grid.at(c[0] as u32, c[1] as u32).is_some();+ let steps: &[(i64, i64)] = match diagonal {+ true => &[(1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (1, -1), (-1, 1), (-1, -1)],+ false => &[(1, 0), (-1, 0), (0, 1), (0, -1)],+ };+ (0..h)+ .flat_map(|y| (0..w).map(move |x| [x, y]))+ .filter(|c| filled(*c) == inside)+ .filter(|c| steps.iter().any(|(dx, dy)| filled([c[0] + dx, c[1] + dy]) != inside))+ .collect()+}+pub fn merged(grids: &[Grid]) -> Option<Grid> {let first = grids.first()?;let cells = (0..first.cells.len())@@ -321,21 +343,18 @@ const SIGNS: &str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456pub fn legend(doc: &Document, grid: &Grid) -> Vec<Named> {let used: BTreeSet<&str> = grid.keys().into_iter().collect();- let entries: Vec<(String, String, String)> = doc+ let entries = doc.palette.iter()- .filter(|s| !s.id.is_empty() && used.contains(s.id.as_str())).map(|s| (s.id.clone(), s.name.clone(), s.color.clone())).chain(grid.keys().into_iter().filter(|k| doc.entry(k).is_none()).map(|k| (k.to_string(), String::new(), k.to_string())),- )- .collect();+ );let mut taken: BTreeSet<char> = BTreeSet::new();entries- .into_iter().map(|(key, name, color)| {let wished = name.chars().find(|c| c.is_ascii_alphanumeric());let sign = wished@@ -347,6 +366,7 @@ pub fn legend(doc: &Document, grid: &Grid) -> Vec<Named> {taken.insert(sign);Named { sign, key, name, color }})+ .filter(|n| used.contains(n.key.as_str())).collect()}diff --git a/docs/DESIGN.md b/docs/DESIGN.mdindex 821159b..0375266 100644--- a/docs/DESIGN.md+++ b/docs/DESIGN.md@@ -1,4 +1,4 @@-_Last updated: 2026-11-12 00:40_+_Last updated: 2026-11-12 02:20_# klad: design@@ -232,7 +232,7 @@ Unknown keys are errors that list the valid ones, so a typo never passes silentlEvery layer has `blend`, `opacity`, `visible`, `locked`, optional `mask`, `clip` and (M5, format 8) `effects`. Effects are layer settings, not a layer kind: the planned `filter` kind became them.-- **Pixel layers (M9).** A pixel layer is a paint layer flagged `pixel`, so it shares cels, masks, clipping, lock alpha, effects, the timeline and every export with paint layers. One pixel is one canvas pixel: a 64x64 sprite is a 64x64 drawing shown enlarged, and a drawing never mixes pixel sizes. Its marks stay data, as strokes do: a pixel mark is a fill record whose source is cells (`FillSource::Cells`), a set of whole pixels (coverage 0 or 255) with the id of the palette swatch it was drawn with, or a set of pixels to erase. So the same addresses, `set`, `rm`, `transform`, lasso, copy and history work on them; scaling, flipping and turning sample the nearest pixel (`markedit::resampled` with `hard`), which also makes an export above full size hard-edged. Colours are palette entries: `Document::bind_swatch` finds or adds the swatch and gives it an `id` the first time a mark uses it, and `set color=` on a pixel mark binds it to the new entry. The `pixel` op (`klad pixel`) is the first way to make marks; brush strokes and flood or lasso fills are refused on a pixel layer (`ops::off_the_grid`). A drawing with a pixel layer (`Document::pixel_art`) gets a sharp view on both sides. In the editor the zoom moves in whole screen pixels per pixel above real size (`View::whole`, `View::fit_whole`; free below it), a pixel grid shows from 8 screen pixels per pixel (a dark line with light dashes, so it reads on any colour; View > Pixel grid), the pixel under the pointer is outlined on a pixel layer and named in the status line, and the Real size pane (`Pane::Preview`, opened the first time a pixel drawing is opened) shows the composed frame at 1, 2 or 4 screen pixels per pixel for drawings up to 512 px. In the CLI, `klad render` and edit previews enlarge by a whole number to about 512 px (`agent::pixel_scale`), and `--overlay grid` draws the same lines with the pixel numbers along the top and left (`overlay::draw_cells`). The palette is what a pixel drawing is bound to. A mark stores its swatch's id and its colour, so every reader of a stroke file draws it without the palette; when a palette edit changes a swatch's colour, `ops::follow_palette` adds a `MarkChange::Entry` for every pixel drawing, which rewrites the colour of the marks bound to that swatch in the same transaction (one undo step), and a removed swatch unbinds its marks. A palette rewritten without ids keeps them by name, then by colour (`carry_ids`). Swatches carry an optional `ramp` name: a ramp is the swatches sharing it, in palette order, dark to light (`palettes::ramp` makes one from a base colour with `color::value_step`, darker and cooler to lighter and warmer). Palettes that come with klad are colour lists in `core/src/palettes.rs` (`klad palettes`), and `palettes::parse` reads a list of hex colours or a GIMP palette. The pencil is grid geometry in `core/src/pixel.rs`, shared by both hands: `line` (Bresenham), `extend` (a run that follows the pen with no holes), `perfect` (drops the corner pixel of an L, so a hand-drawn line stays one pixel thin), `stamp` (a size is a square of whole pixels) and `of_path` (SVG path data flattened and traced; corners the path asks for are kept, the corners that flattening a curve leaves are not). The `pixel` op takes `cells` or a `path`, and a `size`. In the editor the brush tool on a pixel layer is the pencil (the eraser command and the pen's eraser end erase): the run is drawn over the canvas as it grows and committed on release as one `pixel` op marked as made by hand, so the palette binding, history and sync are the op's. Shift click draws a straight line from the last pixel; `[` and `]` change the size. An agent reads and writes a pixel layer as text, which is exact where a picture is not. `pixel::grid_of` works out what a drawing's marks show, pixel by pixel (later marks over earlier ones, erasing marks, lock alpha, cuts), as the palette entry or the colour of each pixel; `pixel::legend` gives each one a character (the first letter of its name where free) and `pixel::ruled` or `pixel::plain` print the rows (`klad pixels`). The other way, `pixel::parse_text` reads a legend and rows and the grid form of the `pixel` op (`rows`, `legend`, `at`) turns each character into one mark bound to its colour (`klad pixel --grid`), so what `klad pixels --plain` prints draws the same picture again. Text grids are the agent's side only: a person draws with the pencil. Shapes and fills are the same op with other sources: `line`, `rect` and `ellipse` (the ellipse that fits a box of pixels, by an integer midpoint walk, so even and odd sizes stay symmetric; `filled` takes the rows between its outline) are pure geometry in `core/src/pixel.rs`; `fill` is a flood over what the drawing shows (`pixel::flood` on the grid of `grid_of`: pixels joined to the seed with exactly its entry or colour, four neighbours or eight), reading this layer, another pixel layer or all of them merged. A flood needs the marks, which an op cannot read, so `Bundle::settle_pixels` turns every `fill` into its cells before the ops are applied, walking the batch so a fill sees the marks the ops before it made; `Bundle::apply_as` calls it, so the CLI, `klad apply` and the editor share it. In the editor the fill tool floods on a click and the shape tool drags a rectangle, an ellipse or a line of pixels on a pixel layer, previewed as the pixels it will make. Editing pixel marks reuses the selection and transform of strokes and fills, with three differences that keep the grid. A lasso that cuts would leave a supersampled cut on a mark (a soft edge), so `markedit::split` divides a pixel mark's coverage between whole pixels instead, by pixel middles, and the two halves carry no cut. A transform whose matrix is whole numbers (flips, quarter turns, whole scales) is rounded onto the grid in `transform_fill` (`on_the_grid`: matrix and offset rounded), so every pixel lands on a pixel whatever the pivot and marks transformed together still fit; other transforms sample the nearest pixel. Recolouring pixel marks gives each exactly the target colour and its palette entry, where paint marks keep their shades. In the editor the stroke tool on a pixel layer drags a box (or a loop) that snaps out to whole pixels and takes pixels, its box is the selected area, drags move by whole pixels, scale by whole numbers and turn by quarters (`Drag.whole`), and Select same colour takes every mark of the selected marks' palette entries. Shading, sharp exports and Aseprite files follow in the milestone's later stories.+- **Pixel layers (M9).** A pixel layer is a paint layer flagged `pixel`, so it shares cels, masks, clipping, lock alpha, effects, the timeline and every export with paint layers. One pixel is one canvas pixel: a 64x64 sprite is a 64x64 drawing shown enlarged, and a drawing never mixes pixel sizes. Its marks stay data, as strokes do: a pixel mark is a fill record whose source is cells (`FillSource::Cells`), a set of whole pixels (coverage 0 or 255) with the id of the palette swatch it was drawn with, or a set of pixels to erase. So the same addresses, `set`, `rm`, `transform`, lasso, copy and history work on them; scaling, flipping and turning sample the nearest pixel (`markedit::resampled` with `hard`), which also makes an export above full size hard-edged. Colours are palette entries: `Document::bind_swatch` finds or adds the swatch and gives it an `id` the first time a mark uses it, and `set color=` on a pixel mark binds it to the new entry. The `pixel` op (`klad pixel`) is the first way to make marks; brush strokes and flood or lasso fills are refused on a pixel layer (`ops::off_the_grid`). A drawing with a pixel layer (`Document::pixel_art`) gets a sharp view on both sides. In the editor the zoom moves in whole screen pixels per pixel above real size (`View::whole`, `View::fit_whole`; free below it), a pixel grid shows from 8 screen pixels per pixel (a dark line with light dashes, so it reads on any colour; View > Pixel grid), the pixel under the pointer is outlined on a pixel layer and named in the status line, and the Real size pane (`Pane::Preview`, opened the first time a pixel drawing is opened) shows the composed frame at 1, 2 or 4 screen pixels per pixel for drawings up to 512 px. In the CLI, `klad render` and edit previews enlarge by a whole number to about 512 px (`agent::pixel_scale`), and `--overlay grid` draws the same lines with the pixel numbers along the top and left (`overlay::draw_cells`). The palette is what a pixel drawing is bound to. A mark stores its swatch's id and its colour, so every reader of a stroke file draws it without the palette; when a palette edit changes a swatch's colour, `ops::follow_palette` adds a `MarkChange::Entry` for every pixel drawing, which rewrites the colour of the marks bound to that swatch in the same transaction (one undo step), and a removed swatch unbinds its marks. A palette rewritten without ids keeps them by name, then by colour (`carry_ids`). Swatches carry an optional `ramp` name: a ramp is the swatches sharing it, in palette order, dark to light (`palettes::ramp` makes one from a base colour with `color::value_step`, darker and cooler to lighter and warmer). Palettes that come with klad are colour lists in `core/src/palettes.rs` (`klad palettes`), and `palettes::parse` reads a list of hex colours or a GIMP palette. The pencil is grid geometry in `core/src/pixel.rs`, shared by both hands: `line` (Bresenham), `extend` (a run that follows the pen with no holes), `perfect` (drops the corner pixel of an L, so a hand-drawn line stays one pixel thin), `stamp` (a size is a square of whole pixels) and `of_path` (SVG path data flattened and traced; corners the path asks for are kept, the corners that flattening a curve leaves are not). The `pixel` op takes `cells` or a `path`, and a `size`. In the editor the brush tool on a pixel layer is the pencil (the eraser command and the pen's eraser end erase): the run is drawn over the canvas as it grows and committed on release as one `pixel` op marked as made by hand, so the palette binding, history and sync are the op's. Shift click draws a straight line from the last pixel; `[` and `]` change the size. An agent reads and writes a pixel layer as text, which is exact where a picture is not. `pixel::grid_of` works out what a drawing's marks show, pixel by pixel (later marks over earlier ones, erasing marks, lock alpha, cuts), as the palette entry or the colour of each pixel; `pixel::legend` gives each one a character (the first letter of its name where free) and `pixel::ruled` or `pixel::plain` print the rows (`klad pixels`). The other way, `pixel::parse_text` reads a legend and rows and the grid form of the `pixel` op (`rows`, `legend`, `at`) turns each character into one mark bound to its colour (`klad pixel --grid`), so what `klad pixels --plain` prints draws the same picture again. Text grids are the agent's side only: a person draws with the pencil. Shapes and fills are the same op with other sources: `line`, `rect` and `ellipse` (the ellipse that fits a box of pixels, by an integer midpoint walk, so even and odd sizes stay symmetric; `filled` takes the rows between its outline) are pure geometry in `core/src/pixel.rs`; `fill` is a flood over what the drawing shows (`pixel::flood` on the grid of `grid_of`: pixels joined to the seed with exactly its entry or colour, four neighbours or eight), reading this layer, another pixel layer or all of them merged. A flood needs the marks, which an op cannot read, so `Bundle::settle_pixels` turns every `fill` into its cells before the ops are applied, walking the batch so a fill sees the marks the ops before it made; `Bundle::apply_as` calls it, so the CLI, `klad apply` and the editor share it. In the editor the fill tool floods on a click and the shape tool drags a rectangle, an ellipse or a line of pixels on a pixel layer, previewed as the pixels it will make. Editing pixel marks reuses the selection and transform of strokes and fills, with three differences that keep the grid. A lasso that cuts would leave a supersampled cut on a mark (a soft edge), so `markedit::split` divides a pixel mark's coverage between whole pixels instead, by pixel middles, and the two halves carry no cut. A transform whose matrix is whole numbers (flips, quarter turns, whole scales) is rounded onto the grid in `transform_fill` (`on_the_grid`: matrix and offset rounded), so every pixel lands on a pixel whatever the pivot and marks transformed together still fit; other transforms sample the nearest pixel. Recolouring pixel marks gives each exactly the target colour and its palette entry, where paint marks keep their shades. In the editor the stroke tool on a pixel layer drags a box (or a loop) that snaps out to whole pixels and takes pixels, its box is the selected area, drags move by whole pixels, scale by whole numbers and turn by quarters (`Drag.whole`), and Select same colour takes every mark of the selected marks' palette entries. Shading builds on ramps. `shade` (a number of ramp steps) is a way to colour, not a source: for the pixels of any source, `Bundle::settled` reads what the layer shows and makes one mark per target colour, each pixel taking the swatch `Document::ramp_step` gives for its own (pixels in no ramp, or at its end, are left). `dither` keeps the pixels a 4x4 Bayer pattern fixed to the canvas turns on for that share (`pixel::dithered`), and `second` gives the rest another colour, as a second mark. `outline` is a source: the empty pixels that touch a drawn one (or, `inside`, the drawn ones that touch an empty one) on the grid of this layer, another or all (`pixel::outline`). All three need the drawing, so they are settled in the bundle with `fill`, and `settle_pixels` may return more ops than it was given. Mark by mark, `klad recolour --step` and the selection bar's Lighter and Darker move a mark to the next swatch of its ramp, and `klad recolour --from` rebinds every mark of one colour. A colour's character in the text view is fixed by its place in the palette, not by which colours are in use. Sharp exports and Aseprite files follow in the milestone's later stories.- **Blend modes.** `normal`, `multiply`, `screen`, `overlay`, `add`, and since M5 `color-dodge`, `soft-light`, `hard-light`, `lighten`, `darken`, `color`, `luminosity`, all as in the W3C compositing spec (Skia's modes; `look::blend_rgb` and `look::composite` hold the formulas the tests check them against).- **Effects (M5).** `"effects": [{"glow": {...}}, {"outline": {...}}]`, applied in order to the layer's content (after its mask; for a clip base, to the base and its clipped layers together) before its opacity and blend: `blur` (radius, a Gaussian sigma), `glow` (radius, strength, threshold: 0 glows from every pixel, higher only from the bright ones; color: a tint; blend: how the glow mixes with what is under the layer, screen by default, normal lays it like paint under the layer), `outline` (width, color, inside), `shadow` (x, y, radius, color, laid under the layer), `noise` (amount, size, seed, mono: a grain fixed to the canvas), `displace` (amount, size, seed, by: smooth waves, or a layer whose red pushes across and green down), `relief` (strength, light, highlight, shade, softness: lights the paint height of the layer's drawings, below). Each effect knows its reach (`look::reach`), so a tile is composed from its content within the tile plus that margin and tiles meet without seams (noise and haze read only their own pixel and add no margin, so they cost no neighbouring tiles); a tile skips a clip stack or group that puts no pixel in it (none of its rasters, live tiles or onion ghosts has a tile in the tile grown by its effects' margin; layers moved by keys, adjustment layers and vector layers drawn from their nodes always count), which leaves the tile the same since every blend leaves the pixels under a transparent layer as they are; the pixels are computed in Rust (`klad-render/effects.rs`) on f32 with absolute coordinates, so a tile equals the same pixels of the whole image byte for byte (tested). Blurs use a direct kernel, below a sigma of 2 at full size and above it on a grid of 2, 4, ... px blocks anchored to the canvas, then sampled back.- **Adjustment layers (M5).** An `adjust` layer changes what is under it in its list: the layers below it in its group, or, clipped, its base. A group holding an adjustment is composed apart, so the adjustment stays inside it. The colour math is on unpremultiplied sRGB values with alpha kept: `hsl` (hue in degrees, saturation and lightness -1..1), `levels` (black, white, gamma, low, high), `curves` (points, and red, green, blue applied before them; monotone cubic, no overshoot), `balance` (shadows, midtones, highlights: cyan to red, magenta to green, yellow to blue, keepLight), `gradient-map` (stops by brightness). The layer's opacity, blend and mask decide how much of the adjusted colour replaces the colour under it. `fill` (a solid or gradient paint) is drawn like a content layer instead, with the layer's blend.diff --git a/docs/cli.md b/docs/cli.mdindex d97b00b..a8ddee7 100644--- a/docs/cli.md+++ b/docs/cli.md@@ -946,7 +946,12 @@ Recolour strokes and fills together. The group's average colour moves to --to anklad recolour art.klad c9:s12 c9:s13 c9:s40 --to '#e3962f'klad recolour art.klad c9:s12 c9:s13 --to skin-Usage: klad recolour [OPTIONS] --to <TO> <BUNDLE> [IDS]...+Pixel marks take exactly the colour and its palette entry, with no shades kept. On pixel layers there are two more forms: --step moves each mark along its colour's ramp (1 one lighter, -1 one darker), and --from replaces a colour, taking every mark drawn in it (in one --layer or at one --frame, or everywhere).++ klad recolour sprite.klad c2:s4 c2:s9 --step -1+ klad recolour sprite.klad --from skin --to skin-dark --layer l1++Usage: klad recolour [OPTIONS] <BUNDLE> [IDS]...Arguments:<BUNDLE>@@ -959,6 +964,18 @@ Options:--to <TO>The colour: #rrggbb or a palette name+ --step <STEPS>+ Pixel marks: step each along its colour's ramp instead, 1 one lighter, -1 one darker++ --from <COLOUR>+ Pixel layers: in place of marks, every mark of this palette colour (a name, a colour, an index or an id)++ --layer <LAYER>+ With --from: only this pixel layer (default: every pixel layer)++ --frame <FRAME>+ With --from: only the drawing at this frame (default: every drawing)+--renderRender a preview after the edit and print its path@@ -1668,6 +1685,12 @@ Shapes on the grid, each one mark: --line x0,y0,x1,y1 is a straight line betweenklad pixel sprite.klad l1 --color body --fill 12,10klad pixel sprite.klad colour --color body --fill 12,10 --ref lines+Shading: --shade 1 (or -1) draws no colour of its own: every pixel it covers takes the next lighter (or darker) colour of its own ramp, so one call shades a form made of several colours; pixels in no ramp, or at its end, stay. --dither 50 draws only that share of the pixels in an even pattern (50 a checkerboard, 25 one in four), and --second gives the others a second colour, for a blend between two ramp steps. --outline draws a one-pixel outline around what the layer shows (--inside on its own edge pixels, --diagonal with the corners, --ref another layer or all).++ klad pixel sprite.klad l1 --shade -1 --rect 4,12,16,4 --filled+ klad pixel sprite.klad l1 --color wood-2 --second wood-3 --dither 50 --rect 4,8,16,2 --filled+ klad pixel sprite.klad l1 --color ink --outline+--grid draws a whole sprite from text, the way klad pixels --plain prints one: legend lines (one character, =, a palette name, a colour, erase or empty), a blank line, then a row of characters per row of pixels. . is empty unless the legend says otherwise. Each character becomes one mark bound to its colour; --at x,y moves the grid's top left.klad pixel sprite.klad l1 --grid - <<'GRID'@@ -1711,10 +1734,25 @@ Options:Flood fill from that pixel: every pixel joined to it that has exactly its colour (or is empty like it)--diagonal- A fill also spreads across corners (eight neighbours, not four)+ A fill also spreads across corners (eight neighbours, not four); an outline also takes the corner pixels--ref <REFERENCE>- What a fill reads: this layer (default), all (every visible pixel layer) or a pixel layer's id or name+ What a fill or an outline reads: this layer (default), all (every visible pixel layer) or a pixel layer's id or name++ --outline+ A one-pixel outline: every empty pixel that touches a drawn one (--inside: every drawn pixel that touches an empty one)++ --inside+ The outline goes on the drawing's own edge pixels, not around it++ --shade <STEPS>+ Step the colours that are there along their ramps instead of drawing a colour: 1 one lighter, -1 one darker++ --dither <PERCENT>+ Draw only this share of the pixels, in an even pattern: 50 is a checkerboard, 25 one pixel in four++ --second <SECOND>+ With --dither: the colour of the pixels the pattern leaves out--grid <FILE>Draw a grid of characters from a file (- reads stdin): a legend (i = ink), a blank line, then one row of characters per row of pixelsdiff --git a/docs/skill/SKILL.md b/docs/skill/SKILL.mdindex b30de89..57534c7 100644--- a/docs/skill/SKILL.md+++ b/docs/skill/SKILL.md@@ -126,19 +126,22 @@ klad export sprite.klad --scale 8 -o [email protected] square pixels, to keep- A pixel layer is a grid with no soft edges, and one pixel is one canvas pixel: a 32x32 sprite is a 32x32 drawing. Size the drawing in pixels of the art, not of the screen; `klad ls` shows the layer as `pixel`.- Draw a sprite as a grid of characters: `klad pixel <bundle> <layer> --grid <file>` (`-` reads stdin). Legend lines come first (one character, `=`, then a palette name, a colour, `erase` or `empty`), then a blank line, then one row of characters per row of pixels. `.` is empty (it leaves what is there) unless the legend says otherwise; a character the legend does not name is an error that says where. `--at x,y` puts the grid's top left pixel elsewhere, so a part (an eye, a hand) can be a small grid of its own. Each character becomes one mark bound to its colour, so a whole sprite is a handful of marks you can recolour or move.-- Read before you change: `klad pixels <bundle> <layer>` prints what the layer shows as the same kind of grid, with a legend (each colour's character, name, hex and id) and the pixel numbers along the top and the left. `--plain` prints only the legend and rows, in the form `--grid` reads, so a sprite can be read, edited as text and written to an empty layer or frame; `--json` gives `rows` and `legend`. Reading the text is exact; the picture is for judging how it looks.+- Read before you change: `klad pixels <bundle> <layer>` prints what the layer shows as the same kind of grid, with a legend (each colour's character, name, hex and id; a colour keeps its character as long as the palette's order stays) and the pixel numbers along the top and the left. `--plain` prints only the legend and rows, in the form `--grid` reads, so a sprite can be read, edited as text and written to an empty layer or frame; `--json` gives `rows` and `legend`. Reading the text is exact; the picture is for judging how it looks.- For a few pixels use `--cells`: `x,y` for one pixel, `x0-x1,y` for a run along a row, `x,y0-y1` for a run down a column and `x0-x1,y0-y1` for a block, separated by spaces. Pixels off the canvas are dropped.- `--path` draws SVG path data as a line of pixels, for outlines and curves that would be tedious as cells. A pixel is the square from `x,y` to `x+1,y+1`, so aim at pixel middles (`3.5`, not `3`). Straight segments keep the corners they are given; curves come out one pixel thin with no doubled corners. `--size 2` (1 to 64) makes the pencil a square of that many pixels, for `--cells` and `--path` alike. In `apply`: `"path":"M3.5 3.5 L9.5 3.5"` in place of `cells`, and `"size":2`.- Shapes, each one mark: `--line x0,y0,x1,y1` is a straight line between two pixels; `--rect x,y,w,h` and `--ellipse x,y,w,h` are the outline of a rectangle, or of the ellipse that fits that box of pixels (`x,y` its top left pixel, `w,h` its size in pixels), and `--filled` takes all of it; `--size` thickens a line or outline. An ellipse outline plus a fill is the quick way to a round body.- `--fill x,y` is a flood fill: every pixel joined to that one that has exactly its colour, or is empty like it, with no tolerance. It spreads to the four neighbours; `--diagonal` also crosses corners (a one-pixel diagonal line then no longer stops it). It reads this layer; `--ref all` reads every visible pixel layer and `--ref <layer>` another one, so flat colour can go on a layer under the outlines: `klad pixel sprite.klad colour --color body --fill 12,10 --ref lines`. Check the outline is closed first (`klad pixels`): through a gap the fill takes the whole background.+- Shading with ramps: `--shade 1` (or `-1`) draws no colour of its own; every pixel it covers takes the next lighter (or darker) colour of its own ramp, so one call shades a form made of several materials: `klad pixel sprite.klad l1 --shade -1 --rect 4,12,16,4 --filled` darkens the lower part of whatever is there, and pixels in no ramp or at its end stay. It works with any source (cells, a path, a shape, a fill). So: block the form in each ramp's middle colour, then shade down on the side away from the light and up where the light hits.+- `--dither 50` draws only that share of the pixels, in an even pattern fixed to the canvas (50 a checkerboard, 25 one pixel in four, 75 three in four), and `--second <colour>` gives the others a second colour: a band of dither between two ramp steps softens the step. Use it sparingly and only at sizes where the pattern reads as a tone.+- `--outline` draws a one-pixel outline around what the layer shows, in `--color`, as one mark: every empty pixel that touches a drawn one (`--diagonal` also takes the corners, for a heavier line; `--inside` recolours the drawing's own edge pixels instead; `--ref <layer>` outlines another layer's pixels, to keep the outline on a layer of its own).- `--color` is a palette name, a palette index or `#rrggbb`. Every pixel mark is bound to a palette entry: a colour the palette lacks is added to it, so name the colours first (`klad palette sprite.klad --add '#f0c8a0' --name skin`) and draw with the names. `klad palette` lists the entries with their ids.- The palette is the drawing's colours, and changing one changes the picture: `klad palette sprite.klad --recolour skin --to '#e8b796'` (a name, a colour, an index or an id) recolours every pixel mark drawn with it, on every frame. So fix a colour in the palette, not mark by mark. `klad palette sprite.klad --load pico-8` adds a palette that comes with klad (`klad palettes` lists them: pico-8, resurrect-64, four-greens, 1-bit) or a file (`.hex`, one colour per line, or a GIMP `.gpl`); colours the palette holds are not added twice. A ramp is a row of colours for one material, dark to light: `klad palette sprite.klad --ramp wood --base '#8b5a2b' --steps 5` makes `wood-1` (dark, cooler) to `wood-5` (light, warmer) around the base, and `--ramp skin --of skin-dark,skin,skin-light` groups colours it has. Shade a form with the steps of its ramp, not with new colours.- Editing an area: `klad lasso sprite.klad l1 --box x,y,w,h --cut --move 2,0` takes the pixels in that box (its top left pixel and size; `--polygon` for another outline) and moves them by whole pixels; `--flip h`, `--rotate 90`, `--scale 2` and `--rm` work the same way. With `--cut` the box takes pixels: marks it crosses are split between whole pixels and the inside halves become marks of their own. Without it only marks that lie whole inside are taken. Quarter turns, flips and whole-number scales keep every pixel; other angles and scales stay hard but look jagged.-- Editing by colour: `klad strokes sprite.klad l1 --entry skin` lists only the marks of one palette colour (with `--json`, their addresses), to move, remove or recolour them together. `klad recolour sprite.klad c2:s4 c2:s9 --to shadow` gives pixel marks exactly that palette colour (no shades are kept, unlike on paint layers).+- Editing by colour: `klad strokes sprite.klad l1 --entry skin` lists only the marks of one palette colour (with `--json`, their addresses), to move, remove or recolour them together. `klad recolour sprite.klad c2:s4 c2:s9 --to shadow` gives pixel marks exactly that palette colour (no shades are kept, unlike on paint layers); `--step 1` or `--step -1` moves each mark along its colour's ramp instead; `klad recolour sprite.klad --from skin --to skin-dark` replaces a colour, rebinding every mark drawn in it (`--layer`, `--frame` to limit it). To change what a colour looks like everywhere, change the swatch (`klad palette --recolour`); to move marks to another colour, replace.- Each mark, `<cel>:s<id>`, stays editable: `klad set sprite.klad c2:s1 color=shadow` recolours it (and binds it to that entry), `klad transform ... --move 2,0` moves it by whole pixels, `--flip h` and `--rotate 90` keep it hard, `klad rm` removes it. `klad strokes sprite.klad l1` lists the marks with their entry and cell count; `--json` gives each one's `cells`.- Later marks cover earlier ones; `--erase` (or `erase` in a grid's legend) makes a mark that clears what was drawn before it at those pixels (remove that mark and the pixels come back).- Looking: `klad render` and the `--render` preview of an edit enlarge a pixel drawing by a whole number to about 512 px, so every pixel is a square you can see (`--scale 1` gives the real size, which is how the player sees it: check there too). `--overlay grid` draws a line between pixels and numbers them along the top and the left, so a pixel's `x,y` can be read off the picture: the number is on the line where that column or row starts. `klad export --scale 8` (whole numbers) writes the enlarged PNG to keep.-- In `apply`: `{"op":"pixel","layer":"l1","color":"skin","cells":[[4,5],[5,5]]}`, with `"erase":true`, `"line":[x0,y0,x1,y1]`, `"rect":[x,y,w,h]` or `"ellipse":[x,y,w,h]` (and `"filled":true`), `"fill":[x,y]` (and `"diagonal"`, `"ref"`), or a grid: `{"op":"pixel","layer":"l1","rows":["..ii..",".ibbi."],"legend":{"i":"ink","b":"body"},"at":[0,0]}`. Brush strokes (`klad stroke`, `ink`, `paint`, ...) and `klad fill` are refused on a pixel layer: fill it with `klad pixel --fill`.+- In `apply`: `{"op":"pixel","layer":"l1","color":"skin","cells":[[4,5],[5,5]]}`, with `"erase":true`, `"line":[x0,y0,x1,y1]`, `"rect":[x,y,w,h]` or `"ellipse":[x,y,w,h]` (and `"filled":true`), `"fill":[x,y]` (and `"diagonal"`, `"ref"`), `"outline":true` (and `"inside"`), `"shade":-1` in place of a colour, `"dither":50` with `"second"`, or a grid: `{"op":"pixel","layer":"l1","rows":["..ii..",".ibbi."],"legend":{"i":"ink","b":"body"},"at":[0,0]}`. Brush strokes (`klad stroke`, `ink`, `paint`, ...) and `klad fill` are refused on a pixel layer: fill it with `klad pixel --fill`.## Masks, clipping and lock alpha