A drawing app built for agent/human collaboration
Rust
Pixel test fixes: the eraser leaves no mark, fill and shapes always draw, the filled box stays
Indicode BV749a1861171a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2afb232..f9ec0ef 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -19,7 +19,7 @@ The first builds, and klad's licences.- 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`).-- The pixel pencil and eraser. On a pixel layer the brush tool (**B**) draws whole pixels in the current colour, which joins the palette, and the eraser (**E**, or the pen's eraser end) clears them; each drag is one mark. A one-pixel line is pixel perfect (no doubled corners), the size is a square of whole pixels (**[** and **]**), and shift click draws a straight line from the last pixel. From the command line, `klad pixel` takes `--path` (SVG path data as a line of pixels) and `--size`.+- The pixel pencil and eraser. On a pixel layer the brush tool (**B**) draws whole pixels in the current colour, which joins the palette, and the eraser (**E**, or the pen's eraser end) clears them; each drag of the pencil is one mark, and the eraser takes its pixels out of the marks under it and leaves none of its own, so pixels you move there later stay whole. A one-pixel line is pixel perfect (no doubled corners), the size is a square of whole pixels (**[** and **]**), and shift click draws a straight line from the last pixel. From the command line, `klad pixel` takes `--path` (SVG path data as a line of pixels) and `--size`.- The palette of a pixel drawing. Changing a palette colour changes every pixel painted with it: click the colour in the palette, change it, and press **update** (or `klad palette art.klad --recolour skin --to '#e8b796'`). **palettes** adds the colours of a palette that comes with klad (PICO-8, Resurrect 64, four greens, 1-bit; `klad palettes` lists them) or of a palette file, a list of hex colours or a GIMP palette (`klad palette art.klad --load pico-8`). **ramp** adds five steps of the current colour, from dark and cool to light and warm (`klad palette art.klad --ramp wood --base '#8b5a2b'`), and `--ramp skin --of skin-dark,skin,skin-light` groups colours the palette has.- A sharp view for pixel drawings. In the editor the zoom steps in whole pixels, so every pixel is the same size; a grid shows between the pixels once you are zoomed in (**View > Pixel grid**), the pixel under the pointer is outlined and its position shows in the status line, and the **Real size** panel shows the drawing as the player sees it, at 1x, 2x or 4x. `klad render` enlarges a pixel drawing to about 512 px, and `--overlay grid` numbers its pixels along the top and the left.- Pixel layers, the start of pixel art in klad. A pixel drawing (**Pixel art** in the start window, or `klad new sprite.klad --pixel 64x64`) is a small drawing of whole pixels with no soft edges; **Layer > New pixel layer** or `klad add art.klad layer pixel` adds a pixel layer to any drawing. `klad pixel sprite.klad l1 --color skin --cells '4-11,5-9'` puts pixels on it as one mark bound to a palette colour (a colour the palette lacks is added), and `--erase` clears them. Each mark stays editable: recolour it with `klad set`, move it with `klad transform`, remove it with `klad rm`; `klad strokes` lists them. Exports above full size keep the pixels square. Brush strokes and fills stay off pixel layers. The format is now `klad/7` (stroke files version 3); older drawings open unchanged.diff --git a/crates/app/src/editor.rs b/crates/app/src/editor.rsindex 11bef51..d67df39 100644--- a/crates/app/src/editor.rs+++ b/crates/app/src/editor.rs@@ -3459,9 +3459,22 @@ impl Editor {}}+ fn erases_nothing(&self, ops: &[Op]) -> bool {+ let (w, h) = self.scene.size();+ let grid = klad_core::pixel::grid_of(self.scene.active_marks(), w, h);+ let painted = |c: &klad_core::pixel::Cell| {+ c[0] >= 0 && c[1] >= 0 && c[0] < w as i64 && c[1] < h as i64 && grid.at(c[0] as u32, c[1] as u32).is_some()+ };+ ops.iter().all(|op| match op {+ Op::Pixel(spec) => spec.erase && !spec.cells.iter().any(painted),+ _ => false,+ })+ }+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) if self.erases_nothing(&ops) => {}Ok(ops) => {self.apply(ops)?;if drew {@@ -3510,8 +3523,7 @@ impl Editor {if at[0] < 0 || at[1] < 0 || at[0] >= w as i64 || at[1] >= h as i64 {return Ok(());}- let erase = self.brush == "eraser";- let Some(spec) = self.pixel_spec(erase) else {+ let Some(spec) = self.pixel_spec(false) else {return Ok(());};self.apply_pixels(klad_core::ops::PixelSpec {@@ -3539,7 +3551,7 @@ impl Editor {(b[0] - a[0]).abs() + 1,(b[1] - a[1]).abs() + 1,];- let spec = self.pixel_spec(self.brush == "eraser")?;+ let spec = self.pixel_spec(false)?;Some(match self.pixel_shape {PixelShape::Rect => klad_core::ops::PixelSpec {rect: Some(bounds),diff --git a/crates/app/src/editor/options.rs b/crates/app/src/editor/options.rsindex ed263bf..fb4fb77 100644--- a/crates/app/src/editor/options.rs+++ b/crates/app/src/editor/options.rs@@ -448,10 +448,10 @@ impl Editor {self.pixel_shape = *kind;}});- if self.pixel_shape != super::PixelShape::Line {- ui.checkbox(&mut self.pixel_filled, "filled")- .hint("every pixel inside, not only the outline");- }+ let closed = self.pixel_shape != super::PixelShape::Line;+ ui.add_enabled(closed, egui::Checkbox::new(&mut self.pixel_filled, "filled"))+ .hint("every pixel inside, not only the outline")+ .on_disabled_hover_text("a line has no inside: pick rectangle or ellipse to fill one");self.pixel_inks(ui);let label = ui.label("size");ui.add(diff --git a/crates/app/src/editor/ui_tests.rs b/crates/app/src/editor/ui_tests.rsindex ea6f9ff..8076789 100644--- a/crates/app/src/editor/ui_tests.rs+++ b/crates/app/src/editor/ui_tests.rs@@ -1956,19 +1956,53 @@ fn the_brush_tool_is_a_pixel_pencil_and_eraser_on_a_pixel_layer() {click_with(&mut h, dot, Modifiers::NONE);h.run_steps(3);ready(&mut h);- let marks = h.state().scene.active_marks().to_vec();- assert!(marks[before + 3].as_fill().unwrap().erases());+ assert_eq!(+ h.state().scene.active_marks().len(),+ before + 3,+ "the eraser leaves no mark of its own"+ );+ assert_eq!(+ cells_of(&h, before + 2).len(),+ 8,+ "it takes the pixel out of the mark under it"+ );let raster = h.state().scene.active_raster().unwrap();assert_eq!(raster.alpha_at(25.5, 5.5), 0.0, "the erased pixel is clear");assert_eq!(raster.alpha_at(24.5, 5.5), 1.0, "its neighbour is still there");- let palette = h.state().scene.bundle.doc.palette.len();- h.state_mut().invoke(Cmd::Undo).unwrap();+ let empty = on_screen(&h, 29.5, 20.5);+ click_with(&mut h, empty, Modifiers::NONE);h.run_steps(3);+ ready(&mut h);+ h.state_mut().tool = Tool::Strokes;+ h.state_mut().invoke(Cmd::SelectAll).unwrap();+ h.run_steps(2);+ let chosen: Vec<u32> = h.state().scene.active_marks().iter().map(|m| m.id()).collect();+ let cel = h.state().scene.active_cel().unwrap();+ let ids: Vec<String> = chosen.iter().map(|id| format!("\"{cel}:s{id}\"")).collect();+ let ops = klad_core::ops::parse_lines(&format!(+ r#"{{"op":"transform","ids":[{}],"x":4,"y":15}}"#,+ ids.join(",")+ ))+ .unwrap();+ h.state_mut().apply(ops).unwrap();+ h.run_steps(3);+ ready(&mut h);+ let raster = h.state().scene.active_raster().unwrap();assert_eq!(- h.state().scene.active_marks().len(),- before + 3,- "undo takes the eraser mark back"+ (+ raster.alpha_at(28.5, 20.5),+ raster.alpha_at(29.5, 20.5),+ raster.alpha_at(30.5, 20.5)+ ),+ (1.0, 0.0, 1.0),+ "pixels moved over a place the eraser went stay whole; their own hole moves with them");+ h.state_mut().invoke(Cmd::Undo).unwrap();+ h.run_steps(3);+ let palette = h.state().scene.bundle.doc.palette.len();+ h.state_mut().invoke(Cmd::Undo).unwrap();+ h.run_steps(3);+ assert_eq!(cells_of(&h, before + 2).len(), 9, "undo puts the erased pixel back");assert_eq!(h.state().scene.bundle.doc.palette.len(), palette);let _ = std::fs::remove_dir_all(&path);}@@ -2052,6 +2086,37 @@ fn the_fill_and_shape_tools_draw_whole_pixels_on_a_pixel_layer() {drag(&mut h, a, b);h.run_steps(3);assert_eq!(cells_of(&h, before + 3), (2..=9).map(|x| [x, 20]).collect::<Vec<_>>());+ h.run_steps(2);+ assert!(+ h.query_by_label("filled").is_some(),+ "the filled box stays in the bar when the line is picked"+ );+ h.state_mut().invoke(Cmd::Eraser).unwrap();+ h.state_mut().pixel_shape = super::PixelShape::Rect;+ h.state_mut().tool = Tool::Shape;+ h.run_steps(2);+ let (a, b) = (on_screen(&h, 2.5, 20.5), on_screen(&h, 4.5, 21.5));+ drag(&mut h, a, b);+ h.run_steps(3);+ ready(&mut h);+ h.state_mut().tool = Tool::Fill;+ h.run_steps(2);+ let inside = on_screen(&h, 23.5, 5.5);+ click_with(&mut h, inside, Modifiers::NONE);+ h.run_steps(3);+ ready(&mut h);+ let marks = h.state().scene.active_marks();+ let last: Vec<&klad_core::fill::Fill> = marks.iter().rev().take(2).filter_map(|m| m.as_fill()).collect();+ assert!(+ last.len() == 2+ && last+ .iter()+ .all(|f| !f.erases() && klad_core::color::to_hex(f.color()) == "#f2c14e"),+ "after E, the shape and the fill tools still draw in the colour"+ );+ let doc = &h.state().scene.bundle.doc;+ let grid = klad_core::pixel::grid_of(marks, doc.canvas.width, doc.canvas.height);+ assert!(grid.at(3, 20).is_some() && grid.at(23, 5).is_some());let _ = std::fs::remove_dir_all(&path);}diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rsindex 50d0c7e..07ce1b9 100644--- a/crates/cli/src/main.rs+++ b/crates/cli/src/main.rs@@ -1014,7 +1014,7 @@ 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\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]}."+ 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 takes those pixels out of the marks under them instead, and leaves no mark of its own.\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,diff --git a/crates/cli/tests/binary.rs b/crates/cli/tests/binary.rsindex fd36591..9360c02 100644--- a/crates/cli/tests/binary.rs+++ b/crates/cli/tests/binary.rs@@ -584,12 +584,12 @@ fn a_pixel_drawing_is_made_drawn_listed_and_edited_from_the_command_line() {draw(&["pixel", path, &layer, "--erase", "--cells", "7,5 8,5"]);let listed = json(&["strokes", path, &layer, "--json"]);let marks = listed["fills"].as_array().unwrap();- assert_eq!(marks.len(), 3);+ assert_eq!(marks.len(), 2, "the eraser leaves no mark of its own");assert_eq!(marks[0]["cells"].as_array().unwrap().len(), 32);- assert_eq!(marks[1]["cells"].as_array().unwrap().len(), 48);assert_eq!(- (marks[2]["erase"].as_bool(), marks[2]["cells"].as_array().unwrap().len()),- (Some(true), 2)+ marks[1]["cells"].as_array().unwrap().len(),+ 46,+ "it takes its two pixels out of the mark under it");let palette = json(&["palette", path, "--json"]);assert_eq!(palette.as_array().unwrap().len(), 2);@@ -600,7 +600,7 @@ fn a_pixel_drawing_is_made_drawn_listed_and_edited_from_the_command_line() {assert_eq!(marks[0]["entry"], palette[1]["id"]);let text = draw(&["strokes", path, &layer]);assert!(- text.contains("3 pixel marks, 82 cells") && text.contains("skin") && text.contains("erases"),+ text.contains("2 pixel marks, 78 cells") && text.contains("skin") && !text.contains("erases"),"{text}");let first = marks[0]["address"].as_str().unwrap().to_string();@@ -609,7 +609,7 @@ fn a_pixel_drawing_is_made_drawn_listed_and_edited_from_the_command_line() {let after = json(&["strokes", path, &layer, "--json"]);assert_eq!(after["fills"][0]["entry"], palette[0]["id"]);assert_eq!(after["fills"][0]["bounds"][0].as_f64(), Some(4.0));- assert!(draw(&["ls", path]).contains("3 pixel marks"));+ assert!(draw(&["ls", path]).contains("2 pixel marks"));let refused = run(&["stroke", path, &layer, "--path", "M1 1 L9 9"]);assert!(!refused.status.success());assert!(String::from_utf8_lossy(&refused.stderr).contains("pixel layer"));@@ -639,7 +639,6 @@ fn a_pixel_drawing_is_made_drawn_listed_and_edited_from_the_command_line() {"--path","M1.5 1.5 L5.5 1.5 L5.5 4.5",]);- draw(&["pixel", path, &lines_id, "--erase", "--size", "3", "--cells", "5,1"]);let lines = json(&["strokes", path, &lines_id, "--json"]);let cells = |at: usize| -> Vec<(i64, i64)> {lines["fills"][at]["cells"]@@ -660,7 +659,16 @@ fn a_pixel_drawing_is_made_drawn_listed_and_edited_from_the_command_line() {});assert!(!doubled, "a curve is one pixel thin with no corner doubled: {curve:?}");assert_eq!(cells(1).len(), 8, "a path's own corner is kept");- assert_eq!(cells(2).len(), 9, "a size is a square of whole pixels");+ draw(&["pixel", path, &lines_id, "--erase", "--size", "3", "--cells", "5,1"]);+ let erased = json(&["strokes", path, &lines_id, "--json"]);+ assert_eq!(+ (+ erased["fills"].as_array().unwrap().len(),+ erased["fills"][1]["cells"].as_array().unwrap().len()+ ),+ (2, 5),+ "a size is a square of whole pixels: the eraser takes three of the path's and leaves no mark"+ );draw(&["rm", path, &lines_id]);let wide = run(&["pixel", path, &layer, "--color", "skin", "--cells", "1,1", "--size", "99",diff --git a/crates/core/src/bundle.rs b/crates/core/src/bundle.rsindex 2526de2..2f99f6a 100644--- a/crates/core/src/bundle.rs+++ b/crates/core/src/bundle.rs@@ -663,6 +663,19 @@ impl Bundle {marks: &mut Vec<Mark>,change: &mut MarkChange,cel: &str,+ ) -> Result<()> {+ self.change_marks(doc, plan, marks, change, cel)?;+ crate::pixel::bake(marks);+ Ok(())+ }++ fn change_marks(+ &self,+ doc: &Document,+ plan: &[PendingMarks],+ marks: &mut Vec<Mark>,+ change: &mut MarkChange,+ cel: &str,) -> Result<()> {match change {MarkChange::Copy { layer, cel, upto } => {@@ -1712,7 +1725,12 @@ mod tests {[[3, 3], [4, 3], [5, 3]],"moves are whole pixels");- assert!(fills[2].erases() && fills[2].entry().is_none());+ assert_eq!(fills.len(), 2, "an eraser leaves no mark of its own");+ assert_eq!(+ fills[1].coverage.cells().collect::<Vec<_>>(),+ [[3, 3]],+ "it takes its pixels out of the marks under it"+ );assert_eq!(bundle.doc.palette.len(),2,@@ -2149,6 +2167,104 @@ mod tests {fs::remove_dir_all(&dir).unwrap();}+ #[test]+ fn an_eraser_on_a_pixel_layer_waits_for_nothing() {+ use crate::fill::{Coverage, Fill};+ use crate::ops::parse_lines;+ let dir = scratch("pixel-eraser");+ 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 cel = bundle.doc.layers[0].cels()[0].id.clone();+ let run = |bundle: &mut Bundle, lines: String| bundle.apply(&parse_lines(&lines).unwrap()).unwrap();+ let grid = |bundle: &Bundle| {+ let marks = bundle.read_marks(&layer, &cel).unwrap();+ crate::pixel::grid_of(&marks, 12, 8)+ };+ let count = |bundle: &Bundle| bundle.read_marks(&layer, &cel).unwrap().len();+ run(+ &mut bundle,+ format!(+ "{}\n{}",+ format_args!(r##"{{"op":"pixel","layer":"{layer}","color":"#aa3344","cells":[[1,1],[2,1],[3,1]]}}"##),+ format_args!(r##"{{"op":"pixel","layer":"{layer}","erase":true,"cells":[[7,1],[8,1],[2,1]]}}"##),+ ),+ );+ assert_eq!(count(&bundle), 1, "the eraser is not kept as a mark");+ assert_eq!(+ (+ grid(&bundle).at(1, 1).is_some(),+ grid(&bundle).at(2, 1),+ grid(&bundle).at(3, 1).is_some()+ ),+ (true, None, true),+ "it took its pixel out of the mark under it"+ );+ let first = crate::markedit::address(&cel, bundle.read_marks(&layer, &cel).unwrap()[0].id());+ run(+ &mut bundle,+ format!(r##"{{"op":"transform","ids":["{first}"],"x":6,"y":0}}"##),+ );+ assert_eq!(+ [7, 8, 9].map(|x| grid(&bundle).at(x, 1).is_some()),+ [true, false, true],+ "pixels moved to where an eraser once went stay whole, and their hole moves with them"+ );+ let mut marks = bundle.read_marks(&layer, &cel).unwrap();+ marks.push(+ Fill::cells(+ 900,+ [0.0, 0.0, 0.0, 1.0],+ "",+ true,+ Coverage::from_cells(&[[1, 5], [2, 5]]),+ )+ .into(),+ );+ bundle.write_marks(&layer, &cel, &marks).unwrap();+ run(+ &mut bundle,+ format!(+ "{}\n{}",+ format_args!(r##"{{"op":"pixel","layer":"{layer}","color":"#aa3344","cells":[[1,6]]}}"##),+ format_args!(r##"{{"op":"transform","ids":["{first}"],"x":-6,"y":4}}"##),+ ),+ );+ assert_eq!(+ count(&bundle),+ 2,+ "an eraser saved by an earlier build goes with the next edit"+ );+ assert!(+ grid(&bundle).at(1, 5).is_some(),+ "and erases nothing that comes by later"+ );+ run(+ &mut bundle,+ format!(+ "{}\n{}",+ format_args!(r##"{{"op":"set","id":"{layer}","lockAlpha":true}}"##),+ format_args!(r##"{{"op":"pixel","layer":"{layer}","color":"#223355","cells":[[1,5],[2,5],[5,5]]}}"##),+ ),+ );+ let marks = bundle.read_marks(&layer, &cel).unwrap();+ let last = marks.last().and_then(Mark::as_fill).unwrap();+ assert_eq!(+ (last.coverage.cells().collect::<Vec<_>>(), last.lock),+ (vec![[1, 5]], false),+ "with alpha locked a mark keeps only the pixels it landed on"+ );+ }+#[test]fn pixels_shade_along_their_ramp_dither_between_two_colours_and_take_an_outline() {use crate::ops::parse_lines;diff --git a/crates/core/src/ops.rs b/crates/core/src/ops.rsindex 3feb5c6..418f628 100644--- a/crates/core/src/ops.rs+++ b/crates/core/src/ops.rs@@ -4355,7 +4355,7 @@ fn put_pixels(doc: &mut Document, spec: &PixelSpec, out: &mut Applied) -> Resultfill.lock = !fill.erases() && locks_alpha(doc, &spec.layer);let cel = paint_cel_at(doc, &spec.layer, spec.frame, out)?;out.push(&spec.layer, &cel, MarkChange::Add(vec![Mark::Fill(fill)]));- if let Some(name) = &spec.part {+ if let Some(name) = spec.part.as_ref().filter(|_| !spec.erase) {out.push(&spec.layer,&cel,diff --git a/crates/core/src/pixel.rs b/crates/core/src/pixel.rsindex 173189c..6e095e2 100644--- a/crates/core/src/pixel.rs+++ b/crates/core/src/pixel.rs@@ -1,4 +1,5 @@use crate::doc::Document;+use crate::fill::{Coverage, Fill};use crate::path;use crate::stroke::Mark;use anyhow::{Result, bail};@@ -363,6 +364,57 @@ pub fn grid_of(marks: &[Mark], width: u32, height: u32) -> Grid {Grid { width, height, cells }}+fn shown(fill: &Fill) -> Vec<[u32; 2]> {+ fill.coverage+ .cells()+ .filter(|c| crate::cut::keeps(&fill.cuts, (c[0] as f32 + 0.5, c[1] as f32 + 0.5)))+ .collect()+}++fn keep(fill: &mut Fill, cells: &[[u32; 2]]) {+ fill.coverage = Coverage::from_cells(cells);+ fill.cuts.clear();+}++pub fn bake(marks: &mut Vec<Mark>) {+ let settles = |m: &Mark| matches!(m, Mark::Fill(f) if f.on_grid() && (f.erases() || f.lock));+ if !marks.iter().any(settles) {+ return;+ }+ let mut out: Vec<Mark> = Vec::with_capacity(marks.len());+ std::mem::take(marks).into_iter().for_each(|mark| match mark {+ Mark::Fill(eraser) if eraser.on_grid() && eraser.erases() => {+ let gone: BTreeSet<[u32; 2]> = shown(&eraser).into_iter().collect();+ out.iter_mut().for_each(|m| {+ if let Mark::Fill(under) = m+ && under.on_grid()+ {+ let all = shown(under);+ let kept: Vec<[u32; 2]> = all.iter().copied().filter(|c| !gone.contains(c)).collect();+ if kept.len() != all.len() {+ keep(under, &kept);+ }+ }+ });+ out.retain(|m| !matches!(m, Mark::Fill(f) if f.on_grid() && f.coverage.is_empty()));+ }+ Mark::Fill(mut locked) if locked.on_grid() && locked.lock => {+ let painted: BTreeSet<[u32; 2]> = crate::stroke::fills_of(&out)+ .filter(|f| f.on_grid())+ .flat_map(shown)+ .collect();+ let kept: Vec<[u32; 2]> = shown(&locked).into_iter().filter(|c| painted.contains(c)).collect();+ if !kept.is_empty() {+ keep(&mut locked, &kept);+ locked.lock = false;+ out.push(Mark::Fill(locked));+ }+ }+ other => out.push(other),+ });+ *marks = out;+}+#[derive(Clone, Debug, PartialEq, Eq)]pub struct Named {pub sign: char,diff --git a/docs/cli.md b/docs/cli.mdindex acd709c..fa53f8e 100644--- a/docs/cli.md+++ b/docs/cli.md@@ -1840,7 +1840,7 @@ Options:```textPut 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.---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.+--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 takes those pixels out of the marks under them instead, and leaves no mark of its own.--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.diff --git a/docs/format.md b/docs/format.mdindex ac7658d..bca6215 100644--- a/docs/format.md+++ b/docs/format.md@@ -1,4 +1,4 @@-_Last updated: 2026-11-12 19:30 (format `klad/7`, stroke files `KLST` version 3, brushes `klad-brush/1`)_+_Last updated: 2026-11-12 09:31 (format `klad/7`, stroke files `KLST` version 3, brushes `klad-brush/1`)_# The klad drawing format@@ -126,7 +126,7 @@ Layers compose bottom to top. Groups compose their children into one image, then- **Clipping.** A layer with `clip: true` shows only where its base, the nearest layer below it in the same list without `clip`, has alpha. The base and the clipped layers above it draw as one group: each clipped layer blends onto the base with its own blend and opacity, kept inside the base's alpha; the group then blends with the base's blend and opacity. A hidden base hides its clipped layers; the lowest layer of a list is never clipped.- **Masks.** `mask` is a paint layer of its own (own id, cels and stroke files, `strokes/<mask id>/...`) with opacity 1 and blend normal. Its alpha hides the layer: marks on the mask hide, eraser strokes on it show the layer again, and a frame without a mask cel hides nothing. `visible: false` on the mask turns it off.-- **Pixel layers.** A paint layer with `pixel: true` is a grid with no anti-aliasing where one pixel is one canvas pixel. Its drawings hold only pixel marks (a fill record whose source is cells, below): each is a set of whole pixels in the colour of one palette swatch, or a set of pixels to erase. klad refuses brush strokes and flood or lasso fills on it.+- **Pixel layers.** A paint layer with `pixel: true` is a grid with no anti-aliasing where one pixel is one canvas pixel. Its drawings hold only pixel marks (a fill record whose source is cells, below): each is a set of whole pixels in the colour of one palette swatch. klad refuses brush strokes and flood or lasso fills on it.- **Lock alpha** is recorded on each stroke and fill as it is made (a flag in the stroke file), so turning `lockAlpha` off later never changes what was drawn. A locked mark composites source-atop: it changes colour where the layer has paint and leaves alpha as it was.### Cels: drawings on the timeline@@ -307,7 +307,7 @@ A reader that ignores attachments draws every drawing as it was when its erasersA fill is drawn from its stored **coverage**, not recomputed, so it looks the same however the lines around it change (`klad refill` recomputes it on purpose). Coverage is a box and run-length coded alpha: varints `x`, `y`, `width`, `height`, a varint count of runs, then each run as a varint length and a `u8` alpha, row by row through the box.-A **pixel mark** is a fill whose source is cells. Its coverage holds only 0 and 255: the pixels it covers. It paints them in its colour, which is the colour of its swatch when it was made or last recoloured; a mark that erases clears the paint of the marks before it at those pixels and has no colour of its own. Moving one moves it by whole pixels, and scaling, flipping or turning it samples the nearest pixel, so it never gets a soft edge.+A **pixel mark** is a fill whose source is cells. Its coverage holds only 0 and 255: the pixels it covers. It paints them in its colour, which is the colour of its swatch when it was made or last recoloured; a mark that erases clears the paint of the marks before it at those pixels and has no colour of its own. klad does not keep erasing marks: its eraser takes the pixels out of the marks before it, and a mark made with alpha locked keeps only the pixels that had paint under them, so no mark waits to change pixels that arrive later. A reader should still honour an erasing or locked pixel mark it meets; klad folds one into the marks before it on the next change to that drawing. Moving one moves it by whole pixels, and scaling, flipping or turning it samples the nearest pixel, so it never gets a soft edge.### Cutsdiff --git a/docs/skill/SKILL.md b/docs/skill/SKILL.mdindex b700f05..85fb58d 100644--- a/docs/skill/SKILL.md+++ b/docs/skill/SKILL.md@@ -150,7 +150,7 @@ klad export sprite.klad --scale 8 -o [email protected] square pixels, to keep- Pictures to pixels. `klad pixelize sprite.klad --image ref.png --to l1` puts a PNG or JPEG on a pixel layer: every pixel takes the nearest colour of the drawing's palette (so it lands in the colours the sprite has; `--colors N` makes N colours from the picture and adds them instead), `--size 48` shrinks it to 48 px on its longest side first (each pixel the average of the area it covers; a picture enlarged by a whole number comes back exact; pixels less than half solid stay empty), `--at x,y` places its top left, `--frame` picks the drawing. `klad import ref.png [--size N] [--colors N]` makes a new pixel drawing from a picture, with the picture's own colours as its palette (reduced to 32 when it has more than 256). `klad pixelize hero.klad --size 64 [--layer body] [--colors 12] [-o out.klad]` makes a new pixel drawing (`hero-pixel.klad`) of a painted or vector layer or of the whole picture, every frame with one set of colours, frames that come out the same held, clips kept; the drawing itself is not changed. All three give marks bound to palette colours, one per colour, so the result is edited like anything else here. Treat it as a start, not a finish: shrinking blurs edges into in-between colours and breaks one-pixel outlines, so look at it at real size, then redraw the outline, cut stray colours with `klad recolour --from a --to b`, and run `klad check` on it.- Aseprite files: `klad import hero.aseprite` (or `.ase`; `-o` names the drawing) makes `hero.klad` next to the file: image layers as pixel layers with their name, visibility, opacity and blend mode, groups as groups, every cel as a drawing on its frame (linked cels stay links), the palette with its names, tags as clips. Frame times become whole frames at the slowest speed that fits (100 ms frames are 10 fps; a 300 ms frame holds for three). Indexed, grey and RGBA files all open, every pixel bound to its palette colour. It says what it leaves out: tilemap layers, tilesets, slices, tag directions other than forwards, blend modes klad lacks. `klad export hero.klad --aseprite` writes the pixel layers and groups back (RGBA; holds and links as linked cels, clips as tags, a pixel layer's keyed moves and opacity baked into its cels; `--variant` and `--variants` work); paint, vector and other layers are left out and named. Use it to hand work to someone who uses Aseprite, or to take over a sprite made there.- 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).+- Later marks cover earlier ones. `--erase` (or `erase` in a grid's legend) takes those pixels out of the marks under them and leaves no mark of its own, so nothing waits there to erase what you move or draw there later (`klad undo` brings the pixels 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"`), `"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`.