Skip to content

armgit / klad

Public Imported from GitHub
0

A drawing app built for agent/human collaboration

Rust

Lines, rectangles, ellipses and flood fill on the pixel grid

Indicode BV3b11ef3b4653
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f462993..bd31d78 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.
+- 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 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.
diff --git a/crates/app/src/editor.rs b/crates/app/src/editor.rs
index 73e0d6b..0bb956e 100644
--- a/crates/app/src/editor.rs
+++ b/crates/app/src/editor.rs
@@ -486,6 +486,13 @@ impl PreviewState {
}
}
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum PixelShape {
+ Rect,
+ Ellipse,
+ Line,
+}
+
struct PixelLive {
run: Vec<klad_core::pixel::Cell>,
erase: bool,
@@ -715,6 +722,10 @@ pub(crate) struct Editor {
zoom_wanted: Option<f32>,
pub(crate) pixel_size: u32,
pub(crate) pixel_perfect: bool,
+ pub(crate) pixel_shape: PixelShape,
+ pub(crate) pixel_filled: bool,
+ pub(crate) pixel_diagonal: bool,
+ pub(crate) pixel_fill_all: bool,
pixel_live: Option<PixelLive>,
pixel_last: Option<klad_core::pixel::Cell>,
hover_cell: Option<[i32; 2]>,
@@ -908,6 +919,10 @@ impl Editor {
zoom_wanted: None,
pixel_size: 1,
pixel_perfect: true,
+ pixel_shape: PixelShape::Rect,
+ pixel_filled: false,
+ pixel_diagonal: false,
+ pixel_fill_all: false,
pixel_live: None,
pixel_last: None,
hover_cell: None,
@@ -2964,10 +2979,12 @@ impl Editor {
match (self.tool, e.phase) {
(_, Phase::Down) if !was_focused || !on_canvas || self.navigating => {}
(_, Phase::Down) if picking => self.pick_colour(c, self.modifiers.shift)?,
- (Tool::Fill, Phase::Down) if self.scene.on_grid() => self.say(
- Tone::Refused,
- "this is a pixel layer: it takes whole pixels (the pencil, B), not flood or lasso fills",
- ),
+ (Tool::Fill, Phase::Down) if self.scene.on_grid() => {
+ if self.scene.can_paint() {
+ self.fill_pixels(klad_core::pixel::cell_at(c.x, c.y))?;
+ }
+ }
+ (Tool::Fill, Phase::Move | Phase::Up) if self.scene.on_grid() => {}
(Tool::Brush, Phase::Down) if self.scene.on_grid() => {
if self.pixel_live.is_none() && self.scene.can_paint() {
let at = klad_core::pixel::cell_at(c.x, c.y);
@@ -3338,6 +3355,78 @@ impl Editor {
klad_core::pixel::stamp(&run, self.pixel_size)
}
+ fn pixel_spec(&self, erase: bool) -> Option<klad_core::ops::PixelSpec> {
+ Some(klad_core::ops::PixelSpec {
+ layer: self.scene.active_id()?,
+ frame: self.scene.frame,
+ color: (!erase).then(|| color::hex(self.color)),
+ erase,
+ by_hand: true,
+ ..klad_core::ops::PixelSpec::default()
+ })
+ }
+
+ 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 {
+ return Ok(());
+ }
+ let erase = self.brush == "eraser";
+ let Some(spec) = self.pixel_spec(erase) else {
+ return Ok(());
+ };
+ let spec = 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> {
+ let (a, b) = self.shapes.drag?;
+ let (a, b) = (klad_core::pixel::cell_at(a.x, a.y), klad_core::pixel::cell_at(b.x, b.y));
+ let b = match (self.modifiers.shift, self.pixel_shape) {
+ (true, PixelShape::Rect | PixelShape::Ellipse) => {
+ let side = (b[0] - a[0]).abs().max((b[1] - a[1]).abs());
+ let sign = |v: i64| if v < 0 { -1 } else { 1 };
+ [a[0] + side * sign(b[0] - a[0]), a[1] + side * sign(b[1] - a[1])]
+ }
+ _ => b,
+ };
+ let bounds = [
+ a[0].min(b[0]),
+ a[1].min(b[1]),
+ (b[0] - a[0]).abs() + 1,
+ (b[1] - a[1]).abs() + 1,
+ ];
+ let spec = self.pixel_spec(self.brush == "eraser")?;
+ Some(match self.pixel_shape {
+ PixelShape::Rect => klad_core::ops::PixelSpec {
+ rect: Some(bounds),
+ filled: self.pixel_filled,
+ size: self.pixel_size,
+ ..spec
+ },
+ PixelShape::Ellipse => klad_core::ops::PixelSpec {
+ ellipse: Some(bounds),
+ filled: self.pixel_filled,
+ size: self.pixel_size,
+ ..spec
+ },
+ PixelShape::Line => klad_core::ops::PixelSpec {
+ line: Some([a[0], a[1], b[0], b[1]]),
+ size: self.pixel_size,
+ ..spec
+ },
+ })
+ }
+
fn finish_pixels(&mut self) -> Result<()> {
let Some(live) = self.pixel_live.take() else {
return Ok(());
@@ -3361,10 +3450,8 @@ impl Editor {
color: (!live.erase).then(|| color::hex(self.color)),
erase: live.erase,
cells,
- path: None,
- size: 1,
- part: None,
by_hand: true,
+ ..klad_core::ops::PixelSpec::default()
};
self.apply(vec![Op::Pixel(spec)])?;
if !live.erase {
@@ -3661,12 +3748,21 @@ impl Editor {
.map(|y| y as f32)
.for_each(|y| rule(to_screen(x0, y), to_screen(x1, y)));
}
- if let Some(live) = self.pixel_live.as_ref() {
- let fill = match live.erase {
+ 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)));
+ 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),
};
- self.pixel_cells(live).iter().for_each(|c| {
+ cells.iter().for_each(|c| {
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/make.rs b/crates/app/src/editor/make.rs
index 6379be9..24a614c 100644
--- a/crates/app/src/editor/make.rs
+++ b/crates/app/src/editor/make.rs
@@ -81,6 +81,12 @@ impl Editor {
}
pub(super) fn shape_down(&mut self, c: Vec2) {
+ if self.scene.on_grid() {
+ if self.scene.can_paint() {
+ self.shapes.drag = Some((c, c));
+ }
+ return;
+ }
if on_vector(self).is_none() {
self.say(
Tone::Refused,
@@ -98,6 +104,19 @@ impl Editor {
}
pub(super) fn shape_up(&mut self) -> Result<()> {
+ if self.scene.on_grid() {
+ let spec = self.pixel_shape_spec();
+ self.shapes.drag = None;
+ let Some(spec) = spec else {
+ return Ok(());
+ };
+ let erase = spec.erase;
+ self.apply(vec![Op::Pixel(spec)])?;
+ if !erase {
+ self.used_colour();
+ }
+ return Ok(());
+ }
let made = self.shape_now();
self.shapes.drag = None;
let (Some([x, y, w, h]), Some(layer)) = (made, on_vector(self)) else {
@@ -144,6 +163,9 @@ impl Editor {
to_screen: &dyn Fn(f32, f32) -> Pos2,
accent: Color32,
) {
+ if self.scene.on_grid() {
+ return;
+ }
let Some([x, y, w, h]) = self.shape_now() else {
return;
};
diff --git a/crates/app/src/editor/options.rs b/crates/app/src/editor/options.rs
index e99a257..5a85d9f 100644
--- a/crates/app/src/editor/options.rs
+++ b/crates/app/src/editor/options.rs
@@ -367,6 +367,19 @@ impl Editor {
ui.colored_label(theme::REFUSED, "pick a paint layer to draw on");
}
}
+ Tool::Fill if self.scene.on_grid() => {
+ ui.checkbox(&mut self.pixel_diagonal, "across corners")
+ .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");
+ ui.label(
+ RichText::new("click a pixel: every pixel joined to it with exactly its colour takes the current colour")
+ .color(theme::WEAK),
+ );
+ if !self.scene.can_paint() {
+ ui.colored_label(theme::REFUSED, "this layer is locked: unlock it to fill on it");
+ }
+ }
Tool::Fill => self.fill_panel(ui),
Tool::Strokes => {
self.pick_scope(ui);
@@ -396,6 +409,38 @@ impl Editor {
self.command_button(ui, Cmd::Simplify, Some("simplify"));
self.command_button(ui, Cmd::MakePath, Some("make it a path"));
}
+ Tool::Shape if self.scene.on_grid() => {
+ [
+ (super::PixelShape::Rect, "rectangle"),
+ (super::PixelShape::Ellipse, "ellipse"),
+ (super::PixelShape::Line, "line"),
+ ]
+ .iter()
+ .for_each(|(kind, label)| {
+ if ui
+ .selectable_label(self.pixel_shape == *kind, *label)
+ .hint(format!("draw {label}s of whole pixels"))
+ .clicked()
+ {
+ 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 label = ui.label("size");
+ ui.add(
+ egui::DragValue::new(&mut self.pixel_size)
+ .range(1..=klad_core::pixel::MAX_SIZE)
+ .suffix(" px"),
+ )
+ .labelled_by(label.id)
+ .hint("how thick the line or outline is, in whole pixels");
+ ui.label(
+ RichText::new("drag on the pixel layer; shift for a square or circle").color(theme::WEAK),
+ );
+ }
Tool::Shape => {
[(super::make::ShapeKind::Rect, "rectangle"), (super::make::ShapeKind::Ellipse, "ellipse")]
.iter()
diff --git a/crates/app/src/editor/ui_tests.rs b/crates/app/src/editor/ui_tests.rs
index 8afb903..3663656 100644
--- a/crates/app/src/editor/ui_tests.rs
+++ b/crates/app/src/editor/ui_tests.rs
@@ -1469,17 +1469,8 @@ fn a_pixel_layer_is_added_shows_its_marks_hard_and_keeps_brush_strokes_out() {
h.query_by_label("pixel layer").is_some(),
"layer settings say what kind of layer it is"
);
- h.state_mut().tool = Tool::Fill;
let rect = h.state().canvas_rect;
let (a, b) = (rect.center() + vec2(-60.0, -20.0), rect.center() + vec2(40.0, 30.0));
- drag(&mut h, a, b);
- h.run_steps(2);
- assert!(
- h.state().scene.active_marks().is_empty(),
- "no fill lands on a pixel layer"
- );
- let refused = h.state().messages.latest().map(|m| m.text.clone()).unwrap_or_default();
- assert!(refused.contains("pixel layer"), "{refused}");
h.state_mut().tool = Tool::Brush;
drag(&mut h, a, b);
h.run_steps(3);
@@ -1835,6 +1826,88 @@ fn the_brush_tool_is_a_pixel_pencil_and_eraser_on_a_pixel_layer() {
let _ = std::fs::remove_dir_all(&path);
}
+#[test]
+fn the_fill_and_shape_tools_draw_whole_pixels_on_a_pixel_layer() {
+ let path = pixel_sample("fill-shape");
+ let mut h = harness(editor(&path), vec2(1440.0, 900.0));
+ h.state_mut()
+ .set_colour(klad_core::color::parse_hex("#f2c14e").unwrap());
+ let cells_of = |h: &Harness<'static, Editor>, at: usize| -> Vec<[u32; 2]> {
+ h.state().scene.active_marks()[at]
+ .as_fill()
+ .unwrap()
+ .coverage
+ .cells()
+ .collect()
+ };
+ let before = h.state().scene.active_marks().len();
+ h.state_mut().tool = Tool::Fill;
+ h.run_steps(2);
+ assert!(
+ h.query_by_label("across corners").is_some(),
+ "the fill tool shows its pixel options"
+ );
+ let centre = on_screen(&h, 5.5, 5.5);
+ click_with(&mut h, centre, Modifiers::NONE);
+ h.run_steps(3);
+ ready(&mut h);
+ assert_eq!(
+ cells_of(&h, before),
+ [[5, 5]],
+ "the fill takes the one red pixel inside the ring"
+ );
+ let mark = h.state().scene.active_marks()[before].as_fill().unwrap().clone();
+ assert!(mark.on_grid() && mark.author == klad_core::stroke::Author::Human);
+ assert_eq!(klad_core::color::to_hex(mark.color()), "#f2c14e");
+ let outside = on_screen(&h, 20.5, 20.5);
+ click_with(&mut h, outside, Modifiers::NONE);
+ h.run_steps(3);
+ ready(&mut h);
+ assert_eq!(
+ cells_of(&h, before + 1).len(),
+ 32 * 24 - 9,
+ "outside the ring the fill takes every empty pixel and stops at the ring"
+ );
+ h.state_mut().invoke(Cmd::Undo).unwrap();
+ h.run_steps(3);
+ ready(&mut h);
+ h.state_mut().tool = Tool::Shape;
+ h.run_steps(2);
+ assert!(
+ h.query_by_label("filled").is_some(),
+ "the shape tool shows its pixel options"
+ );
+ let (a, b) = (on_screen(&h, 10.5, 10.5), on_screen(&h, 17.5, 15.5));
+ drag(&mut h, a, b);
+ h.run_steps(3);
+ ready(&mut h);
+ let outline = cells_of(&h, before + 1);
+ assert_eq!(
+ outline.len(),
+ 2 * 8 + 2 * 4,
+ "an 8 by 6 rectangle's outline: {outline:?}"
+ );
+ assert!(outline.contains(&[10, 10]) && outline.contains(&[17, 15]) && !outline.contains(&[12, 12]));
+ h.state_mut().pixel_shape = super::PixelShape::Ellipse;
+ h.state_mut().pixel_filled = true;
+ let (a, b) = (on_screen(&h, 20.5, 2.5), on_screen(&h, 26.5, 8.5));
+ drag(&mut h, a, b);
+ h.run_steps(3);
+ ready(&mut h);
+ let disc = cells_of(&h, before + 2);
+ assert!(
+ disc.contains(&[23, 5]) && !disc.contains(&[20, 2]),
+ "a filled circle, without its box's corners"
+ );
+ assert!(disc.len() > 25 && disc.len() < 49, "{}", disc.len());
+ h.state_mut().pixel_shape = super::PixelShape::Line;
+ let (a, b) = (on_screen(&h, 2.5, 20.5), on_screen(&h, 9.5, 20.5));
+ drag(&mut h, a, b);
+ h.run_steps(3);
+ assert_eq!(cells_of(&h, before + 3), (2..=9).map(|x| [x, 20]).collect::<Vec<_>>());
+ 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.rs
index a4fa318..254d47b 100644
--- a/crates/cli/src/main.rs
+++ b/crates/cli/src/main.rs
@@ -869,17 +869,67 @@ 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\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; 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\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"],
+ required_unless_present_any = ["path", "grid", "line", "rect", "ellipse", "fill"],
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>,
+ #[arg(
+ long,
+ value_name = "X0,Y0,X1,Y1",
+ value_parser = parse_box,
+ allow_hyphen_values = true,
+ conflicts_with_all = ["cells", "path", "grid"],
+ help = "A straight line of pixels from one pixel to another"
+ )]
+ line: Option<[i64; 4]>,
+ #[arg(
+ long,
+ value_name = "X,Y,W,H",
+ value_parser = parse_box,
+ allow_hyphen_values = true,
+ conflicts_with_all = ["cells", "path", "grid", "line"],
+ help = "The outline of a rectangle, its top left pixel and its size in pixels (--filled: all of it)"
+ )]
+ rect: Option<[i64; 4]>,
+ #[arg(
+ long,
+ value_name = "X,Y,W,H",
+ value_parser = parse_box,
+ allow_hyphen_values = true,
+ conflicts_with_all = ["cells", "path", "grid", "line", "rect"],
+ help = "The outline of the ellipse that fits that box of pixels (--filled: all of it)"
+ )]
+ ellipse: Option<[i64; 4]>,
+ #[arg(long, help = "With --rect or --ellipse: every pixel inside, not only the outline")]
+ filled: bool,
+ #[arg(
+ long,
+ value_name = "X,Y",
+ value_parser = parse_cell,
+ allow_hyphen_values = true,
+ conflicts_with_all = ["cells", "path", "grid", "line", "rect", "ellipse", "size"],
+ help = "Flood fill from that pixel: every pixel joined to it that has exactly its colour (or is empty like it)"
+ )]
+ fill: Option<[i64; 2]>,
+ #[arg(
+ long,
+ requires = "fill",
+ help = "A fill also spreads across corners (eight neighbours, not four)"
+ )]
+ 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"
+ )]
+ reference: Option<String>,
#[arg(
long,
value_name = "FILE",
@@ -2145,6 +2195,17 @@ fn parse_cells(text: &str) -> Result<Vec<[i64; 2]>> {
Ok(cells)
}
+fn parse_box(text: &str) -> Result<[i64; 4]> {
+ let parts: Vec<i64> = text
+ .split(',')
+ .map(|part| part.trim().parse::<i64>())
+ .collect::<std::result::Result<_, _>>()
+ .map_err(|_| anyhow!("{text:?} is not four whole numbers like 2,3,10,8"))?;
+ parts
+ .try_into()
+ .map_err(|_| anyhow!("{text:?} is not four whole numbers like 2,3,10,8"))
+}
+
fn parse_cell(text: &str) -> Result<[i64; 2]> {
let parts: Vec<i64> = text
.split(',')
@@ -2878,6 +2939,13 @@ fn run() -> Result<()> {
grid,
at,
path,
+ line,
+ rect,
+ ellipse,
+ filled,
+ fill,
+ diagonal,
+ reference,
size,
color,
erase,
@@ -2910,10 +2978,18 @@ fn run() -> Result<()> {
erase,
cells: cells.as_deref().map(parse_cells).transpose()?.unwrap_or_default(),
path,
+ line,
+ rect,
+ ellipse,
+ filled,
+ fill,
+ diagonal,
+ reference,
size,
part,
by_hand: false,
};
+ spec.check()?;
agent::edit(&bundle, &[Op::Pixel(spec)], &output(&flags, frame))?;
}
Command::Fill {
diff --git a/crates/cli/tests/binary.rs b/crates/cli/tests/binary.rs
index fb851ef..cc3fe98 100644
--- a/crates/cli/tests/binary.rs
+++ b/crates/cli/tests/binary.rs
@@ -774,6 +774,71 @@ fn a_sprite_is_written_as_a_grid_of_characters_and_read_back_the_same() {
std::fs::remove_dir_all(&dir).unwrap();
}
+#[test]
+fn lines_rectangles_ellipses_and_fills_go_on_the_grid_from_the_command_line() {
+ let dir = std::env::temp_dir().join(format!("draw-binary-shapes-{}", 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()
+ };
+ draw(&["new", path, "--pixel", "16x12"]);
+ draw(&["palette", path, "--add", "#22223b", "--name", "ink"]);
+ draw(&["palette", path, "--add", "#f2c14e", "--name", "body"]);
+ draw(&["pixel", path, "l1", "--color", "ink", "--ellipse", "1,1,9,7"]);
+ draw(&["pixel", path, "l1", "--color", "body", "--fill", "5,4"]);
+ draw(&["pixel", path, "l1", "--color", "ink", "--rect", "11,1,4,4"]);
+ draw(&["pixel", path, "l1", "--color", "body", "--rect", "11,6,4,3", "--filled"]);
+ draw(&["pixel", path, "l1", "--color", "ink", "--line", "0,11,15,9"]);
+ let rows: Vec<String> = draw(&["pixels", path, "l1", "--plain"])
+ .lines()
+ .skip_while(|line| !line.is_empty())
+ .skip(1)
+ .map(String::from)
+ .collect();
+ assert_eq!(
+ rows,
+ [
+ "................",
+ "...iiiii...iiii.",
+ "..ibbbbbi..i..i.",
+ ".ibbbbbbbi.i..i.",
+ ".ibbbbbbbi.iiii.",
+ ".ibbbbbbbi......",
+ "..ibbbbbi..bbbb.",
+ "...iiiii...bbbb.",
+ "...........bbbb.",
+ "............iiii",
+ "....iiiiiiii....",
+ "iiii............",
+ ]
+ );
+ draw(&["add", path, "layer", "pixel", "name=under", "--below", "l1"]);
+ draw(&[
+ "pixel", path, "under", "--color", "#8ecae6", "--fill", "12,2", "--ref", "l1",
+ ]);
+ let under: serde_json::Value = serde_json::from_str(&draw(&["pixels", path, "under", "--json"])).unwrap();
+ assert_eq!(
+ under["rows"][2], "............aa..",
+ "a fill on another layer stops at the lines it reads"
+ );
+ assert_eq!(under["rows"][5], "................");
+ let both = run(&[
+ "pixel", path, "l1", "--color", "ink", "--rect", "0,0,2,2", "--line", "0,0,3,3",
+ ]);
+ assert!(!both.status.success());
+ let flat = run(&["pixel", path, "l1", "--color", "ink", "--rect", "0,0,0,2"]);
+ assert!(String::from_utf8_lossy(&flat.stderr).contains("at least 1 pixel"));
+ let off = run(&["pixel", path, "l1", "--color", "ink", "--fill", "40,40"]);
+ assert!(String::from_utf8_lossy(&off.stderr).contains("off the 16x12 canvas"));
+ 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.rs
index faad919..8261bce 100644
--- a/crates/core/src/bundle.rs
+++ b/crates/core/src/bundle.rs
@@ -9,7 +9,7 @@ use crate::ops::{Applied, ClipEdit, FillSpec, Op, PendingMarks, apply_all};
use crate::repair;
use crate::stroke::{Mark, Stroke, decode_cel, encode_cel, strokes_of};
use crate::timing::{CelAction, FrameSpec};
-use anyhow::{Context, Result, bail};
+use anyhow::{Context, Result, anyhow, bail};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use std::fs;
@@ -407,7 +407,93 @@ impl Bundle {
self.apply_as(ops, "cli")
}
+ fn flooded(
+ &self,
+ doc: &Document,
+ plan: &[PendingMarks],
+ spec: &crate::ops::PixelSpec,
+ ) -> Result<crate::ops::PixelSpec> {
+ 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) {
+ None | Some("this") => vec![own],
+ Some("all") => doc
+ .all_layers()
+ .into_iter()
+ .filter(|l| l.pixel() && l.visible)
+ .collect(),
+ Some(key) => vec![
+ doc.find_layer(key)
+ .map_err(|e| anyhow!("fill 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",
+ other.id,
+ other.kind_name()
+ );
+ }
+ let (w, h) = (doc.canvas.width, doc.canvas.height);
+ let grids = layers
+ .iter()
+ .map(|layer| {
+ let marks = match layer.content_at(spec.frame) {
+ Some(cel) => self.marks_after(doc, plan, &layer.id, &cel.id, usize::MAX)?,
+ None => Vec::new(),
+ };
+ 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,
+ fill: None,
+ ..spec.clone()
+ })
+ }
+
+ 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()))
+ {
+ 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))?;
+ crate::timing::grow(&mut doc);
+ Ok(op)
+ })
+ .collect()
+ }
+
pub fn apply_as(&mut self, ops: &[Op], author: &str) -> Result<Applied> {
+ let ops = &self.settle_pixels(ops)?[..];
let (mut doc, mut applied) = apply_all(&self.doc, ops)?;
self.embed_library(
applied
@@ -1728,4 +1814,85 @@ mod tests {
);
fs::remove_dir_all(&dir).unwrap();
}
+
+ #[test]
+ fn a_pixel_fill_reads_the_drawing_as_the_batch_leaves_it() {
+ use crate::ops::parse_lines;
+ let dir = scratch("pixel-fill");
+ let mut bundle = Bundle::blank(
+ &dir,
+ &Blank {
+ width: 12,
+ height: 10,
+ pixel: true,
+ layers: 2,
+ ..Blank::default()
+ },
+ "cli",
+ )
+ .unwrap();
+ let (colour, lines) = (bundle.doc.layers[0].id.clone(), bundle.doc.layers[1].id.clone());
+ let cel = |bundle: &Bundle, layer: &str| bundle.doc.layer(layer).unwrap().cels()[0].id.clone();
+ bundle
+ .apply(
+ &parse_lines(&format!(
+ "{}\n{}\n{}\n{}",
+ format_args!(r##"{{"op":"pixel","layer":"{lines}","color":"#22223b","rect":[2,2,6,5]}}"##),
+ format_args!(r##"{{"op":"pixel","layer":"{lines}","color":"#f2c14e","fill":[4,4]}}"##),
+ format_args!(
+ r##"{{"op":"pixel","layer":"{colour}","color":"#ef233c","fill":[4,4],"ref":"{lines}"}}"##
+ ),
+ format_args!(r##"{{"op":"pixel","layer":"{colour}","color":"#8ecae6","fill":[0,0],"ref":"all"}}"##),
+ ))
+ .unwrap(),
+ )
+ .unwrap();
+ let cells = |bundle: &Bundle, layer: &str, at: usize| -> Vec<[u32; 2]> {
+ crate::stroke::fills_of(&bundle.read_marks(layer, &cel(bundle, layer)).unwrap())
+ .nth(at)
+ .unwrap()
+ .coverage
+ .cells()
+ .collect()
+ };
+ assert_eq!(cells(&bundle, &lines, 0).len(), 18, "the outline of a 6 by 5 rectangle");
+ assert_eq!(
+ cells(&bundle, &lines, 1).len(),
+ 12,
+ "a fill in the same batch sees the rectangle drawn just before it"
+ );
+ assert_eq!(
+ cells(&bundle, &colour, 0).len(),
+ 12,
+ "a fill on another layer reads the layer it is pointed at: the inside again, now one colour"
+ );
+ assert_eq!(
+ cells(&bundle, &colour, 1).len(),
+ 120 - 30,
+ "reading every layer, the outside stops at the rectangle"
+ );
+ let fill = crate::stroke::fills_of(&bundle.read_marks(&lines, &cel(&bundle, &lines)).unwrap())
+ .nth(1)
+ .unwrap()
+ .clone();
+ assert!(fill.on_grid() && fill.entry().is_some());
+ let refuse = |line: String| format!("{:#}", bundle.settle_pixels(&parse_lines(&line).unwrap()).unwrap_err());
+ assert!(
+ refuse(format!(
+ r##"{{"op":"pixel","layer":"{lines}","color":"#000000","fill":[40,4]}}"##
+ ))
+ .contains("off the 12x10 canvas")
+ );
+ assert!(
+ format!(
+ "{:#}",
+ parse_lines(&format!(
+ r##"{{"op":"pixel","layer":"{lines}","color":"#000000","fill":[4,4],"rect":[0,0,2,2]}}"##
+ ))
+ .unwrap_err()
+ )
+ .contains("not several")
+ );
+ fs::remove_dir_all(&dir).unwrap();
+ }
}
diff --git a/crates/core/src/ops.rs b/crates/core/src/ops.rs
index 33d6b1d..a773a78 100644
--- a/crates/core/src/ops.rs
+++ b/crates/core/src/ops.rs
@@ -293,6 +293,20 @@ pub struct PixelSpec {
pub cells: Vec<[i64; 2]>,
#[serde(default)]
pub path: Option<String>,
+ #[serde(default)]
+ pub line: Option<[i64; 4]>,
+ #[serde(default)]
+ pub rect: Option<[i64; 4]>,
+ #[serde(default)]
+ pub ellipse: Option<[i64; 4]>,
+ #[serde(default)]
+ pub filled: bool,
+ #[serde(default)]
+ pub fill: Option<[i64; 2]>,
+ #[serde(default)]
+ pub diagonal: bool,
+ #[serde(default, rename = "ref")]
+ pub reference: Option<String>,
#[serde(default = "one_pixel")]
pub size: u32,
#[serde(default)]
@@ -305,6 +319,29 @@ fn one_pixel() -> u32 {
1
}
+impl Default for PixelSpec {
+ fn default() -> Self {
+ Self {
+ layer: String::new(),
+ frame: 0,
+ color: None,
+ erase: false,
+ cells: Vec::new(),
+ path: None,
+ line: None,
+ rect: None,
+ ellipse: None,
+ filled: false,
+ fill: None,
+ diagonal: false,
+ reference: None,
+ size: 1,
+ part: None,
+ by_hand: false,
+ }
+ }
+}
+
#[derive(Clone, Debug, PartialEq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct GridSpec {
@@ -348,10 +385,8 @@ impl GridSpec {
},
erase: matches!(meaning, crate::pixel::Sign::Erase),
cells,
- path: None,
- size: 1,
part: self.part.clone(),
- by_hand: false,
+ ..PixelSpec::default()
})
.collect())
}
@@ -364,12 +399,33 @@ impl PixelSpec {
(None, false) => bail!("pixel needs a color (a palette name or #rrggbb) or \"erase\":true"),
_ => {}
}
- match (self.cells.is_empty(), &self.path) {
- (true, None) => bail!(
- "pixel needs cells (a list of [x, y] in canvas pixels) or a path (SVG path data, drawn as a line of pixels)"
+ let sources = [
+ !self.cells.is_empty(),
+ self.path.is_some(),
+ self.line.is_some(),
+ self.rect.is_some(),
+ self.ellipse.is_some(),
+ self.fill.is_some(),
+ ]
+ .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)"
),
- (false, Some(_)) => bail!("pixel takes cells or a path, not both"),
- _ => {}
+ 1 => {}
+ _ => bail!("pixel takes one of cells, path, line, rect, ellipse and fill, not several"),
+ }
+ if [self.rect, self.ellipse]
+ .iter()
+ .flatten()
+ .any(|b| b[2] <= 0 || b[3] <= 0)
+ {
+ bail!("a rect or ellipse is [x, y, w, h] with a width and height of at least 1 pixel");
+ }
+ if self.filled && self.rect.is_none() && self.ellipse.is_none() {
+ bail!("filled goes with rect or ellipse");
}
if !(1..=crate::pixel::MAX_SIZE).contains(&self.size) {
bail!(
@@ -382,10 +438,22 @@ impl PixelSpec {
}
pub fn drawn(&self) -> Result<Vec<[i64; 2]>> {
- match &self.path {
- Some(d) => Ok(crate::pixel::drawn(&crate::pixel::of_path(d)?, self.size)),
- None => Ok(crate::pixel::stamp(&self.cells, self.size)),
+ use crate::pixel;
+ if let Some(d) = &self.path {
+ return Ok(pixel::drawn(&pixel::of_path(d)?, self.size));
+ }
+ if self.fill.is_some() {
+ bail!(
+ "a flood fill of pixels is worked out from the drawing by klad pixel --fill, klad apply or the editor"
+ );
}
+ let cells = match (self.line, self.rect, self.ellipse) {
+ (Some([x0, y0, x1, y1]), _, _) => pixel::line([x0, y0], [x1, y1]),
+ (_, Some([x, y, w, h]), _) => pixel::rect([x, y], [w, h], self.filled),
+ (_, _, Some([x, y, w, h])) => pixel::ellipse([x, y], [w, h], self.filled),
+ _ => self.cells.clone(),
+ };
+ Ok(pixel::stamp(&cells, self.size))
}
pub fn coverage(&self, doc: &Document) -> Result<Coverage> {
diff --git a/crates/core/src/pixel.rs b/crates/core/src/pixel.rs
index 0f45313..b86903e 100644
--- a/crates/core/src/pixel.rs
+++ b/crates/core/src/pixel.rs
@@ -144,6 +144,123 @@ pub fn drawn(runs: &[Run], size: u32) -> Vec<Cell> {
.collect()
}
+pub fn rect(at: Cell, size: [i64; 2], filled: bool) -> Vec<Cell> {
+ let (w, h) = (size[0].max(0), size[1].max(0));
+ (0..h)
+ .flat_map(|j| (0..w).map(move |i| (i, j)))
+ .filter(|&(i, j)| filled || i == 0 || j == 0 || i == w - 1 || j == h - 1)
+ .map(|(i, j)| [at[0] + i, at[1] + j])
+ .collect()
+}
+
+fn ellipse_outline(at: Cell, size: [i64; 2]) -> Vec<Cell> {
+ let (mut x0, mut y0, mut x1, mut y1) = (at[0], at[1], at[0] + size[0] - 1, at[1] + size[1] - 1);
+ let (mut a, b) = ((x1 - x0).abs(), (y1 - y0).abs());
+ let mut b1 = b & 1;
+ let (mut dx, mut dy) = (4 * (1 - a) * b * b, 4 * (b1 + 1) * a * a);
+ let mut err = dx + dy + b1 * a * a;
+ if x0 > x1 {
+ x0 = x1;
+ x1 += a;
+ }
+ if y0 > y1 {
+ y0 = y1;
+ }
+ y0 += (b + 1) / 2;
+ y1 = y0 - b1;
+ a = 8 * a * a;
+ b1 = 8 * b * b;
+ let mut out = Vec::new();
+ loop {
+ out.extend([[x1, y0], [x0, y0], [x0, y1], [x1, y1]]);
+ let e2 = 2 * err;
+ if e2 <= dy {
+ y0 += 1;
+ y1 -= 1;
+ dy += a;
+ err += dy;
+ }
+ if e2 >= dx || 2 * err > dy {
+ x0 += 1;
+ x1 -= 1;
+ dx += b1;
+ err += dx;
+ }
+ if x0 > x1 {
+ break;
+ }
+ }
+ while y0 - y1 <= b {
+ out.extend([[x0 - 1, y0], [x1 + 1, y0], [x0 - 1, y1], [x1 + 1, y1]]);
+ y0 += 1;
+ y1 -= 1;
+ }
+ out
+}
+
+pub fn ellipse(at: Cell, size: [i64; 2], filled: bool) -> Vec<Cell> {
+ if size[0] <= 0 || size[1] <= 0 {
+ return Vec::new();
+ }
+ let outline: BTreeSet<Cell> = ellipse_outline(at, size).into_iter().collect();
+ if !filled {
+ return outline.into_iter().collect();
+ }
+ let mut rows: BTreeMap<i64, (i64, i64)> = BTreeMap::new();
+ outline.iter().for_each(|c| {
+ let span = rows.entry(c[1]).or_insert((c[0], c[0]));
+ *span = (span.0.min(c[0]), span.1.max(c[0]));
+ });
+ rows.into_iter()
+ .flat_map(|(y, (x0, x1))| (x0..=x1).map(move |x| [x, y]))
+ .collect()
+}
+
+pub fn flood(grid: &Grid, at: Cell, diagonal: bool) -> Vec<Cell> {
+ let (w, h) = (grid.width as i64, grid.height as i64);
+ if at[0] < 0 || at[1] < 0 || at[0] >= w || at[1] >= h {
+ return Vec::new();
+ }
+ let key = |c: Cell| grid.at(c[0] as u32, c[1] as u32);
+ let wanted = key(at);
+ let mut seen = vec![false; (w * h) as usize];
+ let mut queue = vec![at];
+ seen[(at[1] * w + at[0]) as usize] = true;
+ let mut out = Vec::new();
+ while let Some(c) = queue.pop() {
+ out.push(c);
+ 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)],
+ };
+ steps
+ .iter()
+ .map(|(dx, dy)| [c[0] + dx, c[1] + dy])
+ .filter(|n| n[0] >= 0 && n[1] >= 0 && n[0] < w && n[1] < h)
+ .for_each(|n| {
+ let i = (n[1] * w + n[0]) as usize;
+ if !seen[i] && key(n) == wanted {
+ seen[i] = true;
+ queue.push(n);
+ }
+ });
+ }
+ out.sort_by_key(|c| (c[1], c[0]));
+ out
+}
+
+pub fn merged(grids: &[Grid]) -> Option<Grid> {
+ let first = grids.first()?;
+ let cells = (0..first.cells.len())
+ .map(|i| grids.iter().rev().find_map(|g| g.cells.get(i).cloned().flatten()))
+ .collect();
+ Some(Grid {
+ width: first.width,
+ height: first.height,
+ cells,
+ })
+}
+
pub const EMPTY: char = '.';
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -576,4 +693,77 @@ mod tests {
);
assert!(parse_text("i = ink\n\n\n").unwrap_err().to_string().contains("no rows"));
}
+
+ #[test]
+ fn rectangles_ellipses_and_floods_are_whole_pixels() {
+ assert_eq!(rect([2, 3], [4, 3], false).len(), 10);
+ assert_eq!(rect([2, 3], [4, 3], true).len(), 12);
+ assert_eq!(rect([0, 0], [1, 1], false), [[0, 0]]);
+ assert!(rect([0, 0], [0, 5], true).is_empty());
+ let ring = ellipse([0, 0], [7, 7], false);
+ let has = |cells: &[Cell], x: i64, y: i64| cells.contains(&[x, y]);
+ assert!(has(&ring, 3, 0) && has(&ring, 0, 3) && has(&ring, 6, 3) && has(&ring, 3, 6));
+ assert!(
+ !has(&ring, 0, 0) && !has(&ring, 3, 3),
+ "no corners of the box, nothing inside"
+ );
+ assert!(
+ ring.iter()
+ .all(|c| ring.contains(&[6 - c[0], c[1]]) && ring.contains(&[c[0], 6 - c[1]]))
+ );
+ let even = ellipse([10, 20], [8, 4], false);
+ assert!(
+ even.iter()
+ .all(|c| (10..18).contains(&c[0]) && (20..24).contains(&c[1])),
+ "{even:?}"
+ );
+ assert!(
+ even.iter()
+ .all(|c| even.contains(&[27 - c[0], c[1]]) && even.contains(&[c[0], 43 - c[1]]))
+ );
+ let disc = ellipse([0, 0], [7, 7], true);
+ assert!(has(&disc, 3, 3) && disc.len() > ring.len());
+ assert!(ring.iter().all(|c| disc.contains(c)));
+ assert_eq!(ellipse([5, 5], [1, 1], true), [[5, 5]]);
+ assert_eq!(ellipse([5, 5], [3, 1], false).len(), 3);
+ let grid = |rows: &[&str]| Grid {
+ width: rows[0].len() as u32,
+ height: rows.len() as u32,
+ cells: rows
+ .iter()
+ .flat_map(|row| row.chars())
+ .map(|c| (c != '.').then(|| c.to_string()))
+ .collect(),
+ };
+ let walls = grid(&["..a..", ".a.a.", "..a..", "....."]);
+ assert_eq!(
+ flood(&walls, [2, 1], false),
+ [[2, 1]],
+ "four neighbours stop at a diamond"
+ );
+ assert_eq!(
+ flood(&walls, [2, 1], true).len(),
+ 20 - 4,
+ "eight slip out between its corners"
+ );
+ assert_eq!(
+ flood(&walls, [2, 0], false),
+ [[2, 0]],
+ "a fill takes pixels of exactly the seed's colour"
+ );
+ assert_eq!(
+ flood(&walls, [2, 0], true).len(),
+ 4,
+ "and the diamond is joined across its corners"
+ );
+ assert_eq!(flood(&walls, [0, 0], false).len(), 15);
+ assert!(flood(&walls, [9, 9], false).is_empty());
+ let under = grid(&["bb...", ".....", ".....", "....."]);
+ let both = merged(&[under, walls.clone()]).unwrap();
+ assert_eq!(
+ (both.at(0, 0), both.at(2, 0), both.at(4, 3)),
+ (Some("b"), Some("a"), None)
+ );
+ assert!(merged(&[]).is_none());
+ }
}
diff --git a/docs/DESIGN.md b/docs/DESIGN.md
index eecb48b..37cf232 100644
--- a/docs/DESIGN.md
+++ b/docs/DESIGN.md
@@ -1,4 +1,4 @@
-_Last updated: 2026-11-11 19:40_
+_Last updated: 2026-11-11 23:10_
# klad: design
@@ -232,7 +232,7 @@ Unknown keys are errors that list the valid ones, so a typo never passes silentl
Every 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, 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. Shading, 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.md
index 329ae9a..bef6fdf 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -1659,6 +1659,12 @@ Put whole pixels of one palette colour on a pixel layer, or erase them. A pixel
klad pixel sprite.klad l1 --color skin --cells '4-11,5-9'
klad pixel sprite.klad l1 --erase --cells '7,7 8,7'
+Shapes 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).
+
+ klad pixel sprite.klad l1 --color ink --ellipse 4,4,16,12
+ klad pixel sprite.klad l1 --color body --fill 12,10
+ klad pixel sprite.klad colour --color body --fill 12,10 --ref lines
+
--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'
@@ -1671,7 +1677,7 @@ Put whole pixels of one palette colour on a pixel layer, or erase them. A pixel
..iiii..
GRID
-Also 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; and as a grid {"op":"pixel","layer":"l1","rows":["..ii..",".ibbi."],"legend":{"i":"ink","b":"body"},"at":[0,0]}.
+Also 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]}.
Usage: klad pixel [OPTIONS] <BUNDLE> <LAYER>
@@ -1686,6 +1692,27 @@ Options:
--cells <CELLS>
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
+ --line <X0,Y0,X1,Y1>
+ A straight line of pixels from one pixel to another
+
+ --rect <X,Y,W,H>
+ The outline of a rectangle, its top left pixel and its size in pixels (--filled: all of it)
+
+ --ellipse <X,Y,W,H>
+ The outline of the ellipse that fits that box of pixels (--filled: all of it)
+
+ --filled
+ With --rect or --ellipse: every pixel inside, not only the outline
+
+ --fill <X,Y>
+ 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)
+
+ --ref <REFERENCE>
+ What a fill reads: this layer (default), all (every visible pixel layer) or a pixel layer's id or name
+
--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 pixels
diff --git a/docs/skill/SKILL.md b/docs/skill/SKILL.md
index f4e850b..ef29348 100644
--- a/docs/skill/SKILL.md
+++ b/docs/skill/SKILL.md
@@ -118,6 +118,8 @@ klad pixels sprite.klad l1 read the layer back as t
klad render sprite.klad --overlay grid enlarged, with numbered pixel lines
klad pixel sprite.klad l1 --color ink --cells '3-12,2 3,3-8' single pixels, runs and blocks
klad pixel sprite.klad l1 --color ink --path 'M3.5 20.5 C 10 4 22 4 28.5 20.5' a curve, one pixel thin
+klad pixel sprite.klad l1 --color ink --ellipse 4,4,16,12 shapes: --line, --rect, --ellipse (--filled)
+klad pixel sprite.klad l1 --color body --fill 12,10 flood fill from a pixel
klad pixel sprite.klad l1 --erase --cells '7,5 8,5'
klad export sprite.klad --scale 8 -o [email protected] square pixels, to keep
```
@@ -127,12 +129,14 @@ klad export sprite.klad --scale 8 -o [email protected] square pixels, to keep
- 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.
- 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.
- `--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.
- 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`, 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.
+- 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`.
## Masks, clipping and lock alpha