Skip to content

armgit / klad

Public Imported from GitHub
0

A drawing app built for agent/human collaboration

Rust

Pixel layers: whole pixels bound to the palette, as marks that stay data

Indicode BV46f2dea92789
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 05f4bf7..16c4795 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.
+- 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.
- Align and distribute shapes. With **V**, shift click adds a shape to the selection and a loop dragged on a vector layer takes the shapes inside; several shapes move, scale, turn, flip, duplicate and delete together. The bar under them lines up their left, right, top or bottom edges or their centres and spaces three or more evenly; one shape lines up on the canvas (**Edit > Align**). From the command line: `klad align art.klad n3 n4 n7 --y middle --spread x`, with `--to canvas` or `--to <shape>` and `--gap`.
- Fixed exports of a clip moved by keys (a layer, group or shape keyed between frames, with no drawing per frame): `klad export --sheet`, `--frames` and `--godot` wrote the first pose for every frame, and `klad render --sheet` showed them as held. Each pose is now its own picture.
- A second agent skill, `klad skill drawing`: the craft of drawing and painting (planning a picture, light on form, values, edges, colour, materials, line, a painting method and a critique checklist), under the MIT licence like the first.
diff --git a/crates/app/src/commands.rs b/crates/app/src/commands.rs
index 2d8807f..31a5697 100644
--- a/crates/app/src/commands.rs
+++ b/crates/app/src/commands.rs
@@ -61,6 +61,7 @@ pub enum Cmd {
MakePath,
AddSwatch,
NewPaintLayer,
+ NewPixelLayer,
NewVectorLayer,
ToggleVisible,
ToggleLocked,
@@ -506,7 +507,7 @@ use Repeat as R;
use Trigger as T;
impl Cmd {
- pub const ALL: [Cmd; 179] = [
+ pub const ALL: [Cmd; 180] = [
Cmd::Brush,
Cmd::Eraser,
Cmd::Fill,
@@ -564,6 +565,7 @@ impl Cmd {
Cmd::MakePath,
Cmd::AddSwatch,
Cmd::NewPaintLayer,
+ Cmd::NewPixelLayer,
Cmd::NewVectorLayer,
Cmd::ToggleVisible,
Cmd::ToggleLocked,
@@ -1203,6 +1205,15 @@ impl Cmd {
R::No,
"a paint layer above the active one, with a drawing at this frame",
),
+ Cmd::NewPixelLayer => spec(
+ "layer.new-pixel",
+ "new pixel layer",
+ icon::PIXELS,
+ G::Layers,
+ T::None,
+ R::No,
+ "a pixel layer above the active one: whole pixels with no soft edges, each bound to a palette colour",
+ ),
Cmd::NewAdjustLayer => spec(
"layer.new-adjust",
"new adjustment layer",
@@ -2359,6 +2370,7 @@ impl Cmd {
Cmd::MakePath => "Make path",
Cmd::AddSwatch => "Add colour to palette",
Cmd::NewPaintLayer => "New paint layer",
+ Cmd::NewPixelLayer => "New pixel layer",
Cmd::NewVectorLayer => "New vector layer",
Cmd::ToggleVisible => "Show",
Cmd::ToggleLocked => "Lock",
@@ -2630,6 +2642,7 @@ pub const MENUS: [Menu; 9] = [
title: "Layer",
items: &[
Run(Cmd::NewPaintLayer),
+ Run(Cmd::NewPixelLayer),
Run(Cmd::NewVectorLayer),
Run(Cmd::NewAdjustLayer),
Run(Cmd::NewGroupLayer),
diff --git a/crates/app/src/composite.rs b/crates/app/src/composite.rs
index c8cd377..6df4579 100644
--- a/crates/app/src/composite.rs
+++ b/crates/app/src/composite.rs
@@ -1152,6 +1152,10 @@ impl Scene {
.is_some_and(|l| l.kind() == Kind::Paint && !l.locked)
}
+ pub fn on_grid(&self) -> bool {
+ self.active_layer().is_some_and(Layer::pixel)
+ }
+
pub fn active_cel(&self) -> Option<String> {
self.active_layer()
.filter(|l| l.kind() == Kind::Paint)
diff --git a/crates/app/src/editor.rs b/crates/app/src/editor.rs
index ca8d34d..8326a56 100644
--- a/crates/app/src/editor.rs
+++ b/crates/app/src/editor.rs
@@ -2933,6 +2933,10 @@ 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 | Tool::Brush, Phase::Down) if self.scene.on_grid() => self.say(
+ Tone::Refused,
+ "this is a pixel layer: it takes whole pixels, not brush strokes or fills",
+ ),
(Tool::Fill, Phase::Down) => {
if self.scene.can_paint() {
self.lasso = Some(Lasso {
@@ -4656,7 +4660,7 @@ impl Editor {
return Ok(());
};
let id = layer.id.clone();
- ui.label(format!("{} layer", layer.kind().name()));
+ ui.label(format!("{} layer", layer.kind_name()));
let mut props: Vec<(String, Value)> = Vec::new();
ui.horizontal(|ui| {
if let Some(name) = self.text(
diff --git a/crates/app/src/editor/commands.rs b/crates/app/src/editor/commands.rs
index 704ee1f..ee56a0b 100644
--- a/crates/app/src/editor/commands.rs
+++ b/crates/app/src/editor/commands.rs
@@ -255,6 +255,7 @@ impl Editor {
}
}),
Cmd::NewPaintLayer
+ | Cmd::NewPixelLayer
| Cmd::NewVectorLayer
| Cmd::NewGroupLayer
| Cmd::NewBonesLayer
@@ -671,6 +672,7 @@ impl Editor {
self.apply(vec![Op::Palette(edit)])?;
}
Cmd::NewPaintLayer => self.add_layer("paint")?,
+ Cmd::NewPixelLayer => self.add_layer("pixel")?,
Cmd::NewGroupLayer => self.new_group(false)?,
Cmd::NewBonesLayer => {
self.new_skeleton()?;
diff --git a/crates/app/src/editor/layers.rs b/crates/app/src/editor/layers.rs
index fda9570..b7a625a 100644
--- a/crates/app/src/editor/layers.rs
+++ b/crates/app/src/editor/layers.rs
@@ -26,6 +26,7 @@ pub(super) struct LayerRow {
pub id: String,
pub name: String,
pub kind: Kind,
+ pub pixel: bool,
pub depth: usize,
pub visible: bool,
pub locked: bool,
@@ -146,6 +147,7 @@ impl Editor {
id: layer.id.clone(),
name: layer.name.clone(),
kind: layer.kind(),
+ pixel: layer.pixel(),
depth,
visible: layer.visible,
locked: layer.locked,
@@ -316,6 +318,7 @@ impl Editor {
(_, Kind::Bones) => icon::BONE,
(_, Kind::Adjust) => icon::ADJUST,
(_, Kind::Vector) => icon::POINTS,
+ _ if row.pixel => icon::PIXELS,
_ => icon::BRUSH,
};
child.label(RichText::new(kind).color(theme::WEAK));
@@ -636,6 +639,7 @@ impl Editor {
ui.horizontal_wrapped(|ui| {
[
(Cmd::NewPaintLayer, Some("paint")),
+ (Cmd::NewPixelLayer, Some("pixel")),
(Cmd::NewVectorLayer, Some("vector")),
(Cmd::NewGroupLayer, Some("group")),
(Cmd::NewBonesLayer, Some("bones")),
@@ -754,6 +758,7 @@ mod tests {
id: id.into(),
name: id.into(),
kind,
+ pixel: false,
depth: 0,
visible: true,
locked: false,
diff --git a/crates/app/src/editor/options.rs b/crates/app/src/editor/options.rs
index 1070a75..71aed3c 100644
--- a/crates/app/src/editor/options.rs
+++ b/crates/app/src/editor/options.rs
@@ -338,6 +338,11 @@ impl Editor {
theme::REFUSED,
"this is a vector layer: P draws paths on it; brushes paint on paint layers",
);
+ } else if self.scene.on_grid() {
+ ui.colored_label(
+ theme::REFUSED,
+ "this is a pixel layer: it takes whole pixels, not brush strokes",
+ );
} else if !self.scene.can_paint() {
ui.colored_label(theme::REFUSED, "pick a paint layer to draw on");
}
diff --git a/crates/app/src/editor/ui_tests.rs b/crates/app/src/editor/ui_tests.rs
index 98570a3..e27ee9e 100644
--- a/crates/app/src/editor/ui_tests.rs
+++ b/crates/app/src/editor/ui_tests.rs
@@ -1451,6 +1451,68 @@ fn several_shapes_select_with_shift_or_a_lasso_move_together_align_and_distribut
let _ = std::fs::remove_dir_all(&path);
}
+#[test]
+fn a_pixel_layer_is_added_shows_its_marks_hard_and_keeps_brush_strokes_out() {
+ let path = sample("pixel-layer");
+ let mut h = harness(editor(&path), vec2(1440.0, 900.0));
+ activate(&mut h, "notes");
+ assert!(h.state().can_run(Cmd::NewPixelLayer).is_none());
+ h.state_mut().invoke(Cmd::NewPixelLayer).unwrap();
+ h.run_steps(3);
+ ready(&mut h);
+ let layer = h.state().scene.active_layer().unwrap().clone();
+ assert!(
+ layer.pixel() && h.state().scene.on_grid(),
+ "the new layer is a pixel layer and active"
+ );
+ assert!(
+ h.query_by_label("pixel layer").is_some(),
+ "layer settings say what kind of layer it is"
+ );
+ h.state_mut().tool = Tool::Brush;
+ 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 brush stroke 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()
+ .apply(
+ parse_lines(&format!(
+ r##"{{"op":"pixel","layer":"{}","color":"#3a86ff","cells":[[10,10],[11,10],[10,11]]}}"##,
+ layer.id
+ ))
+ .unwrap(),
+ )
+ .unwrap();
+ h.run_steps(3);
+ ready(&mut h);
+ let ed = h.state();
+ let raster = ed.scene.active_raster().expect("the pixel layer's drawing");
+ let tile = raster.at(0).expect("the first tile is painted");
+ let at = |x: usize, y: usize| -> [f32; 4] {
+ let i = (y * klad_brush::TILE + x) * 4;
+ [tile[i], tile[i + 1], tile[i + 2], tile[i + 3]].map(|v| v.to_f32())
+ };
+ let blue = klad_core::color::parse_hex("#3a86ff").unwrap();
+ [(10, 10), (11, 10), (10, 11)].iter().for_each(|&(x, y)| {
+ let got = at(x, y);
+ assert!(
+ got.iter().zip(blue).all(|(a, b)| (a - b).abs() < 1e-3),
+ "{x},{y} is {got:?}, not {blue:?}"
+ );
+ });
+ assert_eq!(at(11, 11), [0.0; 4], "no soft edge beside the pixels");
+ assert_eq!(at(9, 10), [0.0; 4]);
+ assert_eq!(ed.scene.bundle.doc.palette.len(), 1, "its colour joined the palette");
+ assert!(ed.scene.active_marks()[0].as_fill().is_some_and(|f| f.on_grid()));
+ 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/app/src/home.rs b/crates/app/src/home.rs
index 6f7a35a..3b23878 100644
--- a/crates/app/src/home.rs
+++ b/crates/app/src/home.rs
@@ -490,6 +490,43 @@ mod tests {
std::fs::remove_dir_all(&dir).unwrap();
}
+ #[test]
+ fn the_start_window_makes_a_pixel_drawing_like_draw_new_with_pixel() {
+ let dir = folder("new-pixel");
+ let mut first = home(&dir, &[]);
+ first.begin(&egui::Context::default(), None);
+ let mut h = harness(first);
+ h.state_mut().start.as_mut().unwrap().name.clear();
+ h.get_by_role_and_label(Role::TextInput, "Name").type_text("slime");
+ h.run_steps(2);
+ assert!(h.query_by_label("A sketch layer for blocking in shapes").is_some());
+ h.get_by_label("Pixel art").click();
+ h.run_steps(2);
+ assert!(
+ h.query_by_label("A sketch layer for blocking in shapes").is_none(),
+ "a pixel drawing has no sketch layer to offer"
+ );
+ h.get_by_label("Create").click();
+ h.run_steps(3);
+ let made = dir.join("slime.klad");
+ assert_eq!(opened(&h), made);
+ let cli = Bundle::blank(
+ dir.join("cli.klad"),
+ &Blank {
+ width: 64,
+ height: 64,
+ pixel: true,
+ ..Blank::default()
+ },
+ "cli",
+ )
+ .unwrap();
+ let doc = Bundle::open(&made).unwrap().doc;
+ assert_eq!(doc, cli.doc);
+ assert!(doc.layers[0].pixel() && doc.layers[0].name == "pixel 1");
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
+
#[test]
fn a_drawing_the_system_asks_to_open_opens_from_the_start_window() {
let dir = folder("finder");
diff --git a/crates/app/src/start.rs b/crates/app/src/start.rs
index 8210368..e910112 100644
--- a/crates/app/src/start.rs
+++ b/crates/app/src/start.rs
@@ -1,6 +1,6 @@
use crate::picker;
use crate::settings::Settings;
-use crate::theme::{self, icon};
+use crate::theme::{self, Hint, icon};
use anyhow::{Result, anyhow, bail};
use egui::{RichText, TextureHandle, vec2};
use klad_core::bundle::{Blank, Bundle};
@@ -19,6 +19,14 @@ pub const PRESETS: [(&str, u32, u32); 5] = [
("large", 4096, 4096),
];
+pub const PIXEL_PRESETS: [(&str, u32, u32); 5] = [
+ ("icon", 16, 16),
+ ("small sprite", 32, 32),
+ ("sprite", 64, 64),
+ ("large sprite", 128, 128),
+ ("screen", 320, 180),
+];
+
const THUMB: f32 = 168.0;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -50,6 +58,10 @@ pub struct Start {
pub colour: [u8; 3],
pub fps: u32,
pub sketch: bool,
+ pub pixel: bool,
+ pub pixel_preset: Option<usize>,
+ pub pixel_width: u32,
+ pub pixel_height: u32,
pub path: String,
pub error: Option<String>,
pub repair: Option<PathBuf>,
@@ -85,6 +97,10 @@ impl Start {
colour: [244, 239, 230],
fps: blank.fps,
sketch: true,
+ pixel: false,
+ pixel_preset: Some(2),
+ pixel_width: 64,
+ pixel_height: 64,
path: String::new(),
error: None,
repair: None,
@@ -103,6 +119,19 @@ impl Start {
.preset
.map_or((self.width, self.height), |i| (PRESETS[i].1, PRESETS[i].2));
let [r, g, b] = self.colour;
+ if self.pixel {
+ let (width, height) = self.pixel_preset.map_or((self.pixel_width, self.pixel_height), |i| {
+ (PIXEL_PRESETS[i].1, PIXEL_PRESETS[i].2)
+ });
+ return Blank {
+ width,
+ height,
+ background: self.paper.then(|| format!("#{r:02x}{g:02x}{b:02x}")),
+ fps: self.fps,
+ pixel: true,
+ ..Blank::default()
+ };
+ }
Blank {
width,
height,
@@ -278,11 +307,22 @@ impl Start {
}
fn new_section(&mut self, ui: &mut egui::Ui, settings: &mut Settings) -> Option<PathBuf> {
- ui.label(
- RichText::new(format!("{} New drawing", icon::FILE_PLUS))
- .strong()
- .size(16.0),
- );
+ ui.horizontal(|ui| {
+ ui.label(
+ RichText::new(format!("{} New drawing", icon::FILE_PLUS))
+ .strong()
+ .size(16.0),
+ );
+ ui.add_space(12.0);
+ let was = self.pixel;
+ ui.selectable_value(&mut self.pixel, false, "Painting")
+ .hint("brushes, shapes and text at any size");
+ ui.selectable_value(&mut self.pixel, true, "Pixel art")
+ .hint("a small drawing of whole pixels, bound to a palette, shown enlarged");
+ if self.pixel && !was {
+ self.paper = false;
+ }
+ });
ui.add_space(6.0);
let mut entered = false;
egui::Grid::new("start new")
@@ -311,20 +351,48 @@ impl Start {
});
ui.end_row();
let label = ui.label("Size");
- let shown = self.preset.map_or("custom".to_string(), preset_name);
+ let shown = match self.pixel {
+ true => self.pixel_preset.map_or("custom".to_string(), pixel_preset_name),
+ false => self.preset.map_or("custom".to_string(), preset_name),
+ };
egui::ComboBox::from_id_salt("start size")
.selected_text(shown)
.width(260.0)
- .show_ui(ui, |ui| {
- (0..PRESETS.len()).for_each(|i| {
- ui.selectable_value(&mut self.preset, Some(i), preset_name(i));
- });
- ui.selectable_value(&mut self.preset, None, "custom");
+ .show_ui(ui, |ui| match self.pixel {
+ true => {
+ (0..PIXEL_PRESETS.len()).for_each(|i| {
+ ui.selectable_value(&mut self.pixel_preset, Some(i), pixel_preset_name(i));
+ });
+ ui.selectable_value(&mut self.pixel_preset, None, "custom");
+ }
+ false => {
+ (0..PRESETS.len()).for_each(|i| {
+ ui.selectable_value(&mut self.preset, Some(i), preset_name(i));
+ });
+ ui.selectable_value(&mut self.preset, None, "custom");
+ }
})
.response
.labelled_by(label.id);
ui.end_row();
- if self.preset.is_none() {
+ if self.pixel && self.pixel_preset.is_none() {
+ ui.label("Width and height");
+ ui.horizontal(|ui| {
+ ui.add(
+ egui::DragValue::new(&mut self.pixel_width)
+ .range(1..=4096)
+ .suffix(" px"),
+ );
+ ui.label("by");
+ ui.add(
+ egui::DragValue::new(&mut self.pixel_height)
+ .range(1..=4096)
+ .suffix(" px"),
+ );
+ });
+ ui.end_row();
+ }
+ if !self.pixel && self.preset.is_none() {
ui.label("Width and height");
ui.horizontal(|ui| {
ui.add(egui::DragValue::new(&mut self.width).range(1..=16384).suffix(" px"));
@@ -351,7 +419,9 @@ impl Start {
.labelled_by(label.id);
ui.end_row();
});
- ui.checkbox(&mut self.sketch, "A sketch layer for blocking in shapes");
+ if !self.pixel {
+ ui.checkbox(&mut self.sketch, "A sketch layer for blocking in shapes");
+ }
ui.add_space(6.0);
if !(ui.add(egui::Button::new("Create").min_size(vec2(96.0, 28.0))).clicked() || entered) {
return None;
@@ -548,6 +618,11 @@ fn preset_name(i: usize) -> String {
format!("{w} x {h} {name}")
}
+fn pixel_preset_name(i: usize) -> String {
+ let (name, w, h) = PIXEL_PRESETS[i];
+ format!("{w} x {h} {name}")
+}
+
fn fit(size: egui::Vec2) -> egui::Vec2 {
size * (THUMB / size.x.max(size.y).max(1.0))
}
@@ -716,6 +791,18 @@ mod tests {
(start.blank().width, start.blank().height, start.blank().background),
(640, 360, Some("#f4efe6".to_string()))
);
+ start.pixel = true;
+ let pixel = start.blank();
+ assert_eq!(
+ (pixel.width, pixel.height, pixel.pixel, pixel.sketch),
+ (64, 64, true, false),
+ "pixel art starts as a 64 pixel sprite with pixel layers and no sketch layer"
+ );
+ start.pixel_preset = None;
+ (start.pixel_width, start.pixel_height) = (48, 24);
+ assert_eq!((start.blank().width, start.blank().height), (48, 24));
+ start.pixel = false;
+ assert_eq!((start.blank().width, start.blank().pixel), (640, false));
start.name = "a/b".into();
assert!(format!("{:#}", start.create(&mut Settings::default()).unwrap_err()).contains("cannot hold a /"));
assert!(format!("{:#}", openable(Path::new("/nowhere")).unwrap_err()).contains("is not a folder"));
diff --git a/crates/app/src/theme.rs b/crates/app/src/theme.rs
index 86ea9eb..80d653e 100644
--- a/crates/app/src/theme.rs
+++ b/crates/app/src/theme.rs
@@ -70,6 +70,7 @@ pub mod icon {
pub const DISTRIBUTE_DOWN: &str = "\u{E536}";
pub const FLIP_V: &str = "\u{ED6C}";
pub const LAYERS: &str = "\u{E466}";
+ pub const PIXELS: &str = "\u{E296}";
pub const EYE: &str = "\u{E220}";
pub const EYE_OFF: &str = "\u{E224}";
pub const LOCK: &str = "\u{E2FA}";
diff --git a/crates/brush/src/fill.rs b/crates/brush/src/fill.rs
index 7df2c4c..3f78091 100644
--- a/crates/brush/src/fill.rs
+++ b/crates/brush/src/fill.rs
@@ -461,14 +461,14 @@ pub fn paint_fill_where(raster: &mut Raster, fill: &Fill, allowed: impl Fn(usize
return false;
};
if paint {
- let target = match fill.lock {
+ let target = match fill.lock || fill.erases() {
true => raster.at_mut(index),
false => Some(raster.ensure(index)),
};
- let blend = if fill.lock {
- StrokeBlend::Atop
- } else {
- StrokeBlend::Normal
+ let blend = match (fill.erases(), fill.lock) {
+ (true, _) => StrokeBlend::Erase,
+ (false, true) => StrokeBlend::Atop,
+ (false, false) => StrokeBlend::Normal,
};
if let Some(target) = target {
blend_coverage(target, &buffer, color, fill.opacity, blend);
@@ -995,6 +995,40 @@ mod tests {
assert_eq!(pixel(&before.raster, 60, 5)[3].to_f32(), 1.0);
}
+ #[test]
+ fn pixel_marks_replay_hard_and_an_erasing_mark_clears_what_is_under_it() {
+ let brushes = BrushSet::presets();
+ let block: Vec<[u32; 2]> = (2..6).flat_map(|y| (3..9).map(move |x| [x, y])).collect();
+ let red = Fill::cells(1, [1.0, 0.0, 0.0, 1.0], "p1", false, Coverage::from_cells(&block));
+ let hole = Fill::cells(
+ 2,
+ [0.0, 0.0, 0.0, 1.0],
+ "",
+ true,
+ Coverage::from_cells(&[[4, 3], [5, 3], [20, 20]]),
+ );
+ let dot = Fill::cells(3, [0.0, 0.0, 1.0, 1.0], "p2", false, Coverage::from_cells(&[[5, 3]]));
+ let done = replay(
+ 32,
+ 32,
+ &[Mark::Fill(red.clone()), Mark::Fill(hole.clone()), Mark::Fill(dot)],
+ &brushes,
+ )
+ .unwrap();
+ let at = |x: usize, y: usize| pixel(&done.raster, x, y).map(|v| v.to_f32());
+ assert_eq!(at(3, 2), [1.0, 0.0, 0.0, 1.0]);
+ assert_eq!(at(4, 3), [0.0, 0.0, 0.0, 0.0], "erased");
+ assert_eq!(at(5, 3), [0.0, 0.0, 1.0, 1.0], "a later mark paints into the hole");
+ assert_eq!(at(2, 2), [0.0, 0.0, 0.0, 0.0], "nothing bleeds past the cells");
+ assert_eq!(at(20, 20), [0.0, 0.0, 0.0, 0.0], "erasing empty canvas leaves it empty");
+ let first = replay(32, 32, &[Mark::Fill(hole), Mark::Fill(red)], &brushes).unwrap();
+ assert_eq!(
+ pixel(&first.raster, 4, 3)[3].to_f32(),
+ 1.0,
+ "it only clears what came before it"
+ );
+ }
+
#[test]
#[ignore = "timing: cargo test --release -p klad-brush fill_timing -- --ignored --nocapture"]
fn fill_timing() {
diff --git a/crates/cli/src/agent.rs b/crates/cli/src/agent.rs
index 0e3ca41..1ec6eef 100644
--- a/crates/cli/src/agent.rs
+++ b/crates/cli/src/agent.rs
@@ -126,7 +126,9 @@ pub fn add_op(what: &str, rest: &[String], place: Place) -> Result<Op> {
"layer" => {
let (kind, props) = match rest.split_first() {
Some((kind, props)) if !kind.contains('=') => (kind.clone(), props),
- _ => bail!("say which kind: klad add <bundle> layer paint|vector|group|adjust|image [key=value ...]"),
+ _ => bail!(
+ "say which kind: klad add <bundle> layer paint|pixel|vector|group|adjust|image [key=value ...]"
+ ),
};
let layer = match kind.as_str() {
"adjust" => crate::looks::adjust_layer(props)?,
@@ -528,14 +530,21 @@ fn report(bundle: &Bundle, applied: &Applied, render: Option<PathBuf>, out: &Out
.filter(|p| p.added().next().is_some())
.for_each(|p| {
let (fills, strokes): (Vec<&PaintMark>, Vec<&PaintMark>) = p.added().partition(|m| m.as_fill().is_some());
+ let (pixels, fills): (Vec<&PaintMark>, Vec<&PaintMark>) = fills
+ .into_iter()
+ .partition(|m| m.as_fill().is_some_and(|f| f.on_grid()));
let list = |marks: &[&PaintMark], what: &str| {
let ids: Vec<String> = marks.iter().map(|m| m.id().to_string()).collect();
(!ids.is_empty()).then(|| format!("{what} {}", ids.join(" ")))
};
- let parts: Vec<String> = [list(&strokes, "strokes"), list(&fills, "fills")]
- .into_iter()
- .flatten()
- .collect();
+ let parts: Vec<String> = [
+ list(&strokes, "strokes"),
+ list(&fills, "fills"),
+ list(&pixels, "pixel marks"),
+ ]
+ .into_iter()
+ .flatten()
+ .collect();
println!("painted on {} cel {}: {}", p.layer, p.cel, parts.join(", "));
});
applied
@@ -678,7 +687,7 @@ fn layer_summary(bundle: &Bundle, layer: &Layer, frame: u32) -> Result<Value> {
let content = layer.content_at(frame);
let mut value = json!({
"id": layer.id,
- "kind": layer.kind().name(),
+ "kind": layer.kind_name(),
"name": layer.name,
"visible": layer.visible,
"opacity": layer.opacity,
@@ -822,6 +831,7 @@ fn print_layer(v: &Value, depth: usize, frames: u32) {
Some(fills) => format!("{} strokes, {fills} fills", v["strokes"].as_u64().unwrap_or(0)),
None => format!("{} strokes", v["strokes"].as_u64().unwrap_or(0)),
},
+ Some("pixel") => format!("{} pixel marks", v["fills"].as_u64().unwrap_or(0)),
Some("vector") => format!("{} nodes", v["nodes"].as_array().map_or(0, Vec::len)),
Some("adjust") => v["adjust"]
.as_object()
diff --git a/crates/cli/src/arcs.rs b/crates/cli/src/arcs.rs
index bb2a415..e65856f 100644
--- a/crates/cli/src/arcs.rs
+++ b/crates/cli/src/arcs.rs
@@ -93,7 +93,7 @@ fn points(mark: &Mark) -> Vec<[f32; 2]> {
Mark::Stroke(s) => s.samples.iter().map(Sample::pos).map(|(x, y)| [x, y]).collect(),
Mark::Fill(f) => match &f.source {
FillSource::Polygon(p) => p.clone(),
- FillSource::Seed { .. } => f
+ FillSource::Seed { .. } | FillSource::Cells { .. } => f
.bounds()
.map(|[x0, y0, x1, y1]| vec![[x0, y0], [x1, y1]])
.unwrap_or_default(),
diff --git a/crates/cli/src/export.rs b/crates/cli/src/export.rs
index ec17fb5..f77d20c 100644
--- a/crates/cli/src/export.rs
+++ b/crates/cli/src/export.rs
@@ -171,4 +171,67 @@ mod tests {
assert_eq!(detail_for(0.5), 1.0);
std::fs::remove_dir_all(&dir).unwrap();
}
+
+ #[test]
+ fn a_pixel_drawing_exports_its_palette_colours_exactly_and_stays_hard_when_larger() {
+ use klad_core::bundle::Blank;
+ let dir = std::env::temp_dir().join(format!("draw-export-pixel-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ let mut bundle = Bundle::blank(
+ dir.join("art.klad"),
+ &Blank {
+ width: 16,
+ height: 17,
+ pixel: true,
+ ..Blank::default()
+ },
+ "cli",
+ )
+ .unwrap();
+ let layer = bundle.doc.layers[0].id.clone();
+ let colour = |i: u32| [i as u8, (255 - i) as u8, ((i * 7) % 256) as u8];
+ let lines: Vec<String> = (0..256u32)
+ .map(|i| {
+ let [r, g, b] = colour(i);
+ format!(
+ r##"{{"op":"pixel","layer":"{layer}","color":"#{r:02x}{g:02x}{b:02x}","cells":[[{},{}]]}}"##,
+ i % 16,
+ i / 16
+ )
+ })
+ .collect();
+ bundle
+ .apply(&klad_core::ops::parse_lines(&lines.join("\n")).unwrap())
+ .unwrap();
+ assert_eq!(bundle.doc.palette.len(), 256);
+ let brushes = BrushSet::for_bundle(&bundle).unwrap();
+ let pixels = |scale: f32| {
+ let detail = detail_for(scale);
+ let rasters = layers::load_at(&bundle, 0, &brushes, detail).unwrap();
+ let options = Options {
+ scale,
+ background: false,
+ references: false,
+ detail,
+ };
+ let image = render(&bundle.doc, 0, &rasters, &Target::Frame, options).unwrap();
+ (image.width() as usize, klad_render::export::dither8(&image).unwrap())
+ };
+ let (w, flat) = pixels(1.0);
+ (0..256usize).for_each(|i| {
+ let at = ((i / 16) * w + i % 16) * 4;
+ let [r, g, b] = colour(i as u32);
+ assert_eq!(flat[at..at + 4], [r, g, b, 255], "colour {i} at real size");
+ });
+ assert!(flat[16 * w * 4..].iter().all(|v| *v == 0), "the empty row stays empty");
+ let (w, big) = pixels(3.0);
+ (0..256usize).for_each(|i| {
+ let [r, g, b] = colour(i as u32);
+ (0..9).for_each(|k| {
+ let at = (((i / 16) * 3 + k / 3) * w + (i % 16) * 3 + k % 3) * 4;
+ assert_eq!(big[at..at + 4], [r, g, b, 255], "colour {i} at 3x, block pixel {k}");
+ });
+ });
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
}
diff --git a/crates/cli/src/fills.rs b/crates/cli/src/fills.rs
index 07afb2b..31d502e 100644
--- a/crates/cli/src/fills.rs
+++ b/crates/cli/src/fills.rs
@@ -46,6 +46,7 @@ pub fn compute(doc: &Document, frame: u32, rasters: &Rasters, cel: &str, source:
reference_ms: 0.0,
fill_ms: ms(start),
}),
+ FillSource::Cells { .. } => bail!("a pixel mark keeps its own cells: there is nothing to compute"),
}
}
@@ -200,7 +201,7 @@ pub fn refill(path: &Path, layer: &str, frame: u32, only: Option<u32>, out: &Out
let redo = match mark {
Mark::Fill(fill) if only.is_none_or(|id| id == fill.id) => match &fill.source {
FillSource::Seed { reference, .. } => Some(reference.clone()),
- FillSource::Polygon(_) => None,
+ FillSource::Polygon(_) | FillSource::Cells { .. } => None,
},
_ => None,
};
diff --git a/crates/cli/src/frames.rs b/crates/cli/src/frames.rs
index d833547..c71b9db 100644
--- a/crates/cli/src/frames.rs
+++ b/crates/cli/src/frames.rs
@@ -84,7 +84,7 @@ pub fn sheet_json(doc: &Document, from: u32, to: u32) -> Value {
json!({
"id": layer.id,
"name": layer.name,
- "kind": layer.kind().name(),
+ "kind": layer.kind_name(),
"maskOf": mask_of,
"cels": cels,
"cells": all[from as usize..].to_vec(),
diff --git a/crates/cli/src/history.rs b/crates/cli/src/history.rs
index 1e33875..bb7c51c 100644
--- a/crates/cli/src/history.rs
+++ b/crates/cli/src/history.rs
@@ -166,7 +166,7 @@ pub fn selection(path: &Path, as_json: bool) -> Result<()> {
let layer = sel.layer.as_deref().and_then(|id| bundle.doc.layer(id));
if as_json {
let value = json!({
- "layer": layer.map(|l| json!({ "id": l.id, "name": l.name, "kind": l.kind().name() })),
+ "layer": layer.map(|l| json!({ "id": l.id, "name": l.name, "kind": l.kind_name() })),
"nodes": nodes,
"frame": sel.frame,
"atMs": sel.at_ms,
@@ -181,7 +181,7 @@ pub fn selection(path: &Path, as_json: bool) -> Result<()> {
};
println!("selected {}{at}", ago(sel.at_ms));
if let Some(l) = layer {
- println!("layer {} {} ({})", l.id, l.name, l.kind().name());
+ println!("layer {} {} ({})", l.id, l.name, l.kind_name());
}
nodes.iter().for_each(|n| {
let b = n["bounds"].as_array().map_or("".into(), |b| {
diff --git a/crates/cli/src/inbetween.rs b/crates/cli/src/inbetween.rs
index 9907910..b4d3b23 100644
--- a/crates/cli/src/inbetween.rs
+++ b/crates/cli/src/inbetween.rs
@@ -778,6 +778,7 @@ fn frame_job(
let id = fill.id;
let what = |why: String| format!("{} at frame {frame}: {why}", address(&key.a, id));
match fill.source.clone() {
+ FillSource::Cells { .. } => {}
FillSource::Polygon(points) => fill.coverage = polygon(&points, w, h),
FillSource::Seed { mut seed, reference } => {
let Some((a, b)) = floods.iter().find(|(a, _)| a.id == id) else {
diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs
index cc40c5c..ef6e2d9 100644
--- a/crates/cli/src/main.rs
+++ b/crates/cli/src/main.rs
@@ -36,8 +36,8 @@ use klad_core::history::Stack;
use klad_core::markedit::{LassoAction, MarkTransform};
use klad_core::ops::{
BoneSpec, ClipEdit, CopySpec, CopyTarget, FillSpec, FoliageSpec, GrassSpec, HatchSpec, IkSpec, InbetweenSpec,
- InkSpec, LassoSpec, LightSpec, Op, PaintOverSpec, PaintSpec, PaletteEdit, Place, PoseSpec, ScatterSpec, ShiftSpec,
- StrokeSpec, WeightsSpec,
+ InkSpec, LassoSpec, LightSpec, Op, PaintOverSpec, PaintSpec, PaletteEdit, PixelSpec, Place, PoseSpec, ScatterSpec,
+ ShiftSpec, StrokeSpec, WeightsSpec,
};
use klad_core::retime::{Retime, RetimeSpec};
use klad_core::stroke::{fills_of, strokes_of};
@@ -146,6 +146,12 @@ enum Command {
frames: u32,
#[arg(long, help = "Add a vector layer named sketch on top, for blocking in shapes")]
sketch: bool,
+ #[arg(
+ long,
+ value_name = "WxH",
+ help = "A pixel art drawing of that many pixels, for example 64x64: its layers are pixel layers"
+ )]
+ pixel: Option<String>,
},
#[command(
about = "Exposure sheet: a row per frame, a column per layer (top first)",
@@ -497,7 +503,7 @@ enum Command {
#[arg(help = "layer, cel, mask, rect, ellipse, path, group, rays, image, scatter, repeat, mirror or text")]
what: String,
#[arg(
- help = "For layers the kind first (paint, vector, group, bones, image with src=photo.jpg, or adjust and its type: hsl, levels, curves, balance, gradient-map, fill), then key=value pairs"
+ help = "For layers the kind first (paint, pixel, vector, group, bones, image with src=photo.jpg, or adjust and its type: hsl, levels, curves, balance, gradient-map, fill), then key=value pairs"
)]
rest: Vec<String>,
#[command(flatten)]
@@ -858,6 +864,29 @@ enum Command {
#[command(flatten)]
flags: EditFlags,
},
+ #[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 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 skin --cells '4-11,5-9'\n klad pixel sprite.klad l1 --erase --cells '7,7 8,7'\n\nAlso a pixel op in klad apply: {\"op\":\"pixel\",\"layer\":\"l1\",\"color\":\"skin\",\"cells\":[[4,5],[5,5]]} or with \"erase\":true."
+ )]
+ Pixel {
+ bundle: PathBuf,
+ layer: String,
+ #[arg(
+ long,
+ 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: String,
+ #[arg(long, conflicts_with = "erase", help = "A palette name, a palette index or #rrggbb")]
+ color: Option<String>,
+ #[arg(long, help = "Clear these pixels instead of colouring them")]
+ erase: bool,
+ #[arg(long, default_value_t = 0)]
+ frame: u32,
+ #[arg(long, help = "Put the mark in this named part")]
+ part: Option<String>,
+ #[command(flatten)]
+ flags: EditFlags,
+ },
#[command(
about = "Ink the outlines of vector shapes as tapered strokes, the way an inker would",
long_about = "Ink the outlines of vector shapes (rects, ellipses, paths, groups of them; often on a hidden sketch layer) as strokes on a paint layer. An outline is split into separate strokes at corners sharper than --break degrees, each stroke tapers in and out, and its weight follows rules instead of pressure written by hand: heavier on the side facing away from the light, heavier on the silhouette (the outer edge of the shapes inked together) than on inner lines, thinner along tight curves, with a small seeded wobble.\n\n klad ink art.klad lines --from body,eye,leg --weight 6 --light -1,-1\n klad ink art.klad lines --from rock --weight 9 --break 45 --gap 3 --wobble 1\n klad ink art.klad lines --path \"M10 10 C 80 0 120 60 200 40\" --weight 4\n\nThe strokes are ordinary agent strokes: klad set, klad transform and the editor edit them. Also an ink op: {\"op\":\"ink\",\"layer\":\"l3\",\"from\":[\"n5\"],\"weight\":6,\"light\":[-1,-1],\"break\":60,\"gap\":0,\"wobble\":0.6}."
@@ -1985,6 +2014,39 @@ fn parse_pair(text: &str) -> Result<[f32; 2]> {
.map_err(|_| anyhow!("{text:?} is not x,y"))
}
+fn parse_cells(text: &str) -> Result<Vec<[i64; 2]>> {
+ let span = |part: &str| -> Option<(i64, i64)> {
+ let part = part.trim();
+ let split = part.char_indices().skip(1).find(|(_, c)| *c == '-').map(|(i, _)| i);
+ match split {
+ Some(i) => {
+ let (a, b) = (part[..i].parse::<i64>().ok()?, part[i + 1..].parse::<i64>().ok()?);
+ Some((a.min(b), a.max(b)))
+ }
+ None => part.parse::<i64>().ok().map(|v| (v, v)),
+ }
+ };
+ let cells = text
+ .split_whitespace()
+ .map(|item| {
+ let bad = || anyhow!("{item:?} is not x,y, a row run x0-x1,y, a column run x,y0-y1 or a block x0-x1,y0-y1");
+ let (x, y) = item.split_once(',').ok_or_else(bad)?;
+ let ((x0, x1), (y0, y1)) = (span(x).ok_or_else(bad)?, span(y).ok_or_else(bad)?);
+ if (x1 - x0).max(y1 - y0) > klad_core::doc::MAX_SIZE as i64 {
+ bail!("{item:?} runs further than any canvas");
+ }
+ Ok((y0..=y1).flat_map(move |y| (x0..=x1).map(move |x| [x, y])))
+ })
+ .collect::<Result<Vec<_>>>()?
+ .into_iter()
+ .flatten()
+ .collect::<Vec<_>>();
+ if cells.is_empty() {
+ bail!("--cells is empty: give pixels like '3,4 4,4' or runs like '3-9,4'");
+ }
+ Ok(cells)
+}
+
fn parse_origin(text: &str) -> Result<Option<[f32; 2]>> {
match text {
"centre" | "center" => Ok(None),
@@ -2066,6 +2128,16 @@ fn bug(info: &std::panic::PanicHookInfo) -> String {
)
}
+fn pixel_size(text: &str) -> Result<(u32, u32)> {
+ let side = |part: &str| part.trim().parse::<u32>().ok().filter(|n| *n > 0);
+ let sides: Vec<Option<u32>> = text.split(['x', 'X']).map(side).collect();
+ match sides.as_slice() {
+ [Some(w)] => Ok((*w, *w)),
+ [Some(w), Some(h)] => Ok((*w, *h)),
+ _ => bail!("--pixel takes a size in pixels like 64x64 or 32, not {text:?}"),
+ }
+}
+
fn run() -> Result<()> {
match Cli::parse().command {
Command::New {
@@ -2077,17 +2149,20 @@ fn run() -> Result<()> {
fps,
frames,
sketch,
+ pixel,
} => {
+ let size = pixel.as_deref().map(pixel_size).transpose()?;
edit::new(
&bundle,
&Blank {
- width,
- height,
+ width: size.map_or(width, |s| s.0),
+ height: size.map_or(height, |s| s.1),
layers,
background,
fps,
frames,
sketch,
+ pixel: size.is_some(),
},
)?;
println!("{}", bundle.display());
@@ -2687,6 +2762,26 @@ fn run() -> Result<()> {
};
agent::edit(&bundle, &[Op::Stroke(spec)], &output(&flags, frame))?;
}
+ Command::Pixel {
+ bundle,
+ layer,
+ cells,
+ color,
+ erase,
+ frame,
+ part,
+ flags,
+ } => {
+ let spec = PixelSpec {
+ layer,
+ frame,
+ color,
+ erase,
+ cells: parse_cells(&cells)?,
+ part,
+ };
+ agent::edit(&bundle, &[Op::Pixel(spec)], &output(&flags, frame))?;
+ }
Command::Fill {
bundle,
layer,
@@ -3983,6 +4078,47 @@ fn strokes(path: &Path, layer: &str, frame: u32, after: u32, as_json: bool) -> R
);
return Ok(());
}
+ if owner.pixel() {
+ println!(
+ "cel {}: address a pixel mark as {}:s<id>, for example {}",
+ cel.id,
+ cel.id,
+ klad_core::markedit::address(&cel.id, marks.first().map_or(1, |m| m.id()))
+ );
+ if !fills.is_empty() {
+ println!("id author colour entry cells bounds");
+ }
+ fills.iter().for_each(|f| {
+ let part = cel.part_of(f.id).map_or(String::new(), |p| format!(" part {p}"));
+ let (colour, entry) = match (f.erases(), f.entry()) {
+ (true, _) => ("erases ".to_string(), String::new()),
+ (false, Some(id)) => (
+ hex8(f.color()),
+ match bundle.doc.entry(id) {
+ Some(swatch) => format!("{id} {}", swatch.name).trim().to_string(),
+ None => format!("{id} (gone)"),
+ },
+ ),
+ (false, None) => (hex8(f.color()), "none".to_string()),
+ };
+ let [x0, y0, x1, y1] = f.bounds().unwrap_or_default();
+ println!(
+ "{:<6} {:<6} {colour} {entry:<14} {:>7} {x0:.0},{y0:.0} {:.0}x{:.0}{}{part}",
+ klad_core::doc::mark_name(f.id),
+ f.author.name(),
+ f.coverage.pixels(),
+ x1 - x0,
+ y1 - y0,
+ marks::flags(f.lock, &f.cuts)
+ );
+ });
+ println!(
+ "{} pixel marks, {} cells",
+ fills.len(),
+ fills.iter().map(|f| f.coverage.pixels()).sum::<usize>()
+ );
+ return Ok(());
+ }
println!(
"cel {}: address a stroke or fill as {}:s<id>, for example {}",
cel.id,
@@ -4052,6 +4188,7 @@ fn strokes(path: &Path, layer: &str, frame: u32, after: u32, as_json: bool) -> R
seed.tolerance
),
FillSource::Polygon(points) => format!("polygon of {} points", points.len()),
+ FillSource::Cells { .. } => "cells".to_string(),
};
let [x0, y0, x1, y1] = f.bounds().unwrap_or_default();
println!(
@@ -4086,10 +4223,12 @@ fn palette(path: &Path, as_json: bool) -> Result<()> {
if palette.is_empty() {
println!("the palette is empty: klad palette <bundle> --add '#rrggbb' --name <name>");
}
- palette
- .iter()
- .enumerate()
- .for_each(|(i, s)| println!("{i:<3} {:<10} {}", s.color, s.name));
+ palette.iter().enumerate().for_each(|(i, s)| {
+ println!(
+ "{}",
+ format!("{i:<3} {:<10} {:<8} {}", s.color, s.id, s.name).trim_end()
+ )
+ });
Ok(())
}
diff --git a/crates/cli/src/marks.rs b/crates/cli/src/marks.rs
index 700eac2..77359f3 100644
--- a/crates/cli/src/marks.rs
+++ b/crates/cli/src/marks.rs
@@ -36,6 +36,22 @@ pub fn fill_json(cel: &str, f: &Fill) -> Value {
value["expand"] = json!(round4(seed.expand));
}
FillSource::Polygon(points) => value["polygon"] = json!(points),
+ FillSource::Cells { entry, erase } => {
+ value["cells"] = json!(f.coverage.cells().collect::<Vec<_>>());
+ match erase {
+ true => {
+ value["erase"] = json!(true);
+ if let Some(map) = value.as_object_mut() {
+ map.remove("color");
+ map.remove("opacity");
+ }
+ }
+ false => value["entry"] = json!(entry),
+ }
+ if let Some(map) = value.as_object_mut() {
+ map.remove("pixels");
+ }
+ }
}
flags_json(&mut value, f.lock, &f.cuts);
value
diff --git a/crates/cli/src/paintover.rs b/crates/cli/src/paintover.rs
index 3589c6e..bf9383c 100644
--- a/crates/cli/src/paintover.rs
+++ b/crates/cli/src/paintover.rs
@@ -522,7 +522,7 @@ fn covers(mark: &Mark, at: P, reach: f32) -> bool {
}
Mark::Fill(f) => match &f.source {
klad_core::fill::FillSource::Polygon(points) => crate::shapes::inside(std::slice::from_ref(points), at),
- klad_core::fill::FillSource::Seed { .. } => {
+ klad_core::fill::FillSource::Seed { .. } | klad_core::fill::FillSource::Cells { .. } => {
at[0] >= 0.0 && at[1] >= 0.0 && f.coverage.at(at[0] as u32, at[1] as u32) > 0
}
},
@@ -546,7 +546,7 @@ fn outline_of(mark: &Mark) -> Option<Vec<(f32, f32)>> {
klad_core::fill::FillSource::Polygon(points) => {
Some(points.iter().chain(points.first()).map(|p| (p[0], p[1])).collect())
}
- klad_core::fill::FillSource::Seed { .. } => None,
+ klad_core::fill::FillSource::Seed { .. } | klad_core::fill::FillSource::Cells { .. } => None,
},
}
}
diff --git a/crates/cli/tests/binary.rs b/crates/cli/tests/binary.rs
index 53ae071..3042efe 100644
--- a/crates/cli/tests/binary.rs
+++ b/crates/cli/tests/binary.rs
@@ -504,6 +504,82 @@ fn shapes_align_spread_and_centre_on_the_canvas_from_the_command_line() {
std::fs::remove_dir_all(&dir).unwrap();
}
+#[test]
+fn a_pixel_drawing_is_made_drawn_listed_and_edited_from_the_command_line() {
+ let dir = std::env::temp_dir().join(format!("draw-binary-pixel-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ let bundle = dir.join("sprite.klad");
+ let path = bundle.to_str().unwrap();
+ let run = |args: &[&str]| Command::new(env!("CARGO_BIN_EXE_klad")).args(args).output().unwrap();
+ let draw = |args: &[&str]| {
+ let out = run(args);
+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
+ String::from_utf8_lossy(&out.stdout).to_string()
+ };
+ let json = |args: &[&str]| -> serde_json::Value { serde_json::from_str(&draw(args)).unwrap() };
+ draw(&["new", path, "--pixel", "16x12"]);
+ let tree = json(&["ls", path, "--json"]);
+ assert_eq!(
+ (tree["canvas"]["width"].as_u64(), tree["canvas"]["height"].as_u64()),
+ (Some(16), Some(12))
+ );
+ let layer = tree["layers"][0]["id"].as_str().unwrap().to_string();
+ assert_eq!(tree["layers"][0]["kind"], "pixel");
+ draw(&["palette", path, "--add", "#f0c8a0", "--name", "skin"]);
+ let made = draw(&[
+ "pixel",
+ path,
+ &layer,
+ "--color",
+ "#2b2d42",
+ "--cells",
+ "3-12,2 3,3-8 12,3-8 3-12,9",
+ ]);
+ assert!(
+ made.contains("pixel marks") && made.contains("changed palette"),
+ "{made}"
+ );
+ draw(&["pixel", path, &layer, "--color", "skin", "--cells", "4-11,3-8"]);
+ 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[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)
+ );
+ let palette = json(&["palette", path, "--json"]);
+ assert_eq!(palette.as_array().unwrap().len(), 2);
+ assert_eq!(
+ marks[1]["entry"], palette[0]["id"],
+ "the mark is bound to the skin entry"
+ );
+ 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}"
+ );
+ let first = marks[0]["address"].as_str().unwrap().to_string();
+ draw(&["set", path, &first, "color=skin"]);
+ draw(&["transform", path, &first, "--move", "1,0"]);
+ 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"));
+ 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"));
+ let bad = run(&["pixel", path, &layer, "--color", "skin", "--cells", "3;4"]);
+ assert!(String::from_utf8_lossy(&bad.stderr).contains("is not x,y"));
+ draw(&["add", path, "layer", "pixel", "name=shade"]);
+ assert_eq!(json(&["ls", path, "--json"])["layers"][0]["kind"], "pixel");
+ 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 9aa50ed..b46f1ca 100644
--- a/crates/core/src/bundle.rs
+++ b/crates/core/src/bundle.rs
@@ -33,6 +33,7 @@ pub struct Blank {
pub fps: u32,
pub frames: u32,
pub sketch: bool,
+ pub pixel: bool,
}
impl Default for Blank {
@@ -45,6 +46,7 @@ impl Default for Blank {
fps: 12,
frames: 1,
sketch: false,
+ pixel: false,
}
}
}
@@ -327,7 +329,10 @@ impl Bundle {
doc.layers = (1..=blank.layers)
.map(|i| {
let (layer, cel) = (doc.alloc_id('l'), doc.alloc_id('c'));
- Layer::paint(&layer, &format!("paint {i}"), &cel)
+ match blank.pixel {
+ true => Layer::pixels(&layer, &format!("pixel {i}"), &cel),
+ false => Layer::paint(&layer, &format!("paint {i}"), &cel),
+ }
})
.collect();
if blank.sketch {
@@ -650,6 +655,8 @@ pub fn summarize(ops: &[Op]) -> String {
like: Some(cel), layer, ..
}) => format!("fills on {layer} like {cel}"),
Op::Fill(spec) => format!("fill on {}", spec.layer),
+ Op::Pixel(spec) if spec.erase => format!("erase {} pixels on {}", spec.cells.len(), spec.layer),
+ Op::Pixel(spec) => format!("{} pixels on {}", spec.cells.len(), spec.layer),
Op::Palette(_) => "palette".to_string(),
Op::Transform { ids, .. } => format!("transform {}", ids.join(" ")),
Op::Detach { ids } => format!("detach {}", ids.join(" ")),
@@ -772,6 +779,8 @@ pub fn write_atomic(path: &Path, bytes: &[u8]) -> Result<()> {
#[cfg(test)]
mod tests {
use super::*;
+ use crate::doc::Kind;
+ use crate::fill::Fill;
use crate::synth::Synth;
fn scratch(name: &str) -> PathBuf {
@@ -1423,4 +1432,153 @@ mod tests {
assert_eq!(Bundle::open(&dir).unwrap().doc.rev, 2);
fs::remove_dir_all(&dir).unwrap();
}
+
+ #[test]
+ fn a_pixel_layer_takes_whole_pixels_bound_to_the_palette() {
+ use crate::ops::parse_lines;
+ let dir = scratch("pixels");
+ let mut bundle = Bundle::blank(
+ &dir,
+ &Blank {
+ width: 16,
+ height: 12,
+ pixel: true,
+ ..Blank::default()
+ },
+ "cli",
+ )
+ .unwrap();
+ let layer = bundle.doc.layers[0].clone();
+ assert!(layer.pixel() && layer.kind() == Kind::Paint && layer.kind_name() == "pixel");
+ let cel = layer.cels()[0].id.clone();
+ bundle
+ .apply(
+ &parse_lines(&format!(
+ "{}\n{}\n{}",
+ r##"{"op":"palette","add":"#f0c8a0","name":"skin"}"##,
+ format_args!(
+ r##"{{"op":"pixel","layer":"{}","color":"skin","cells":[[2,3],[3,3],[4,3],[-1,3],[99,3]]}}"##,
+ layer.id
+ ),
+ format_args!(
+ r##"{{"op":"pixel","layer":"{}","color":"#2b2d42","cells":[[3,3],[3,4]]}}"##,
+ layer.id
+ ),
+ ))
+ .unwrap(),
+ )
+ .unwrap();
+ let skin = bundle.doc.palette[0].clone();
+ let ink = bundle.doc.palette[1].clone();
+ assert!(!skin.id.is_empty() && !ink.id.is_empty() && skin.id != ink.id);
+ assert_eq!(
+ (ink.color.as_str(), ink.name.as_str()),
+ ("#2b2d42", ""),
+ "a new colour joins the palette"
+ );
+ let marks = bundle.read_marks(&layer.id, &cel).unwrap();
+ let fills: Vec<&Fill> = crate::stroke::fills_of(&marks).collect();
+ assert_eq!(fills.len(), 2);
+ assert_eq!(fills[0].entry(), Some(skin.id.as_str()));
+ assert_eq!(
+ fills[0].coverage.cells().collect::<Vec<_>>(),
+ [[2, 3], [3, 3], [4, 3]],
+ "cells off the canvas are dropped"
+ );
+ assert!(fills[0].coverage.alpha.iter().all(|a| *a == 0 || *a == 255));
+ assert_eq!(fills[1].color(), crate::color::parse_hex("#2b2d42").unwrap());
+ let address = crate::markedit::address(&cel, fills[0].id);
+ bundle
+ .apply(
+ &parse_lines(&format!(
+ "{}\n{}\n{}",
+ format_args!(r##"{{"op":"set","id":"{address}","color":"#2b2d42"}}"##),
+ format_args!(r##"{{"op":"transform","ids":["{address}"],"x":1.4,"y":0}}"##),
+ format_args!(
+ r##"{{"op":"pixel","layer":"{}","erase":true,"cells":[[3,4]]}}"##,
+ layer.id
+ ),
+ ))
+ .unwrap(),
+ )
+ .unwrap();
+ let marks = bundle.read_marks(&layer.id, &cel).unwrap();
+ let fills: Vec<&Fill> = crate::stroke::fills_of(&marks).collect();
+ assert_eq!(
+ fills[0].entry(),
+ Some(ink.id.as_str()),
+ "a recoloured mark is bound to the new entry"
+ );
+ assert_eq!(
+ fills[0].coverage.cells().collect::<Vec<_>>(),
+ [[3, 3], [4, 3], [5, 3]],
+ "moves are whole pixels"
+ );
+ assert!(fills[2].erases() && fills[2].entry().is_none());
+ assert_eq!(
+ bundle.doc.palette.len(),
+ 2,
+ "a colour the palette has is not added again"
+ );
+ fn refuse(doc: &Document, line: String) -> String {
+ format!(
+ "{:#}",
+ crate::ops::apply_all(doc, &parse_lines(&line).unwrap()).unwrap_err()
+ )
+ }
+ assert!(
+ refuse(
+ &bundle.doc,
+ format!(r##"{{"op":"stroke","layer":"{}","path":"M1 1 L9 9"}}"##, layer.id)
+ )
+ .contains("pixel layer"),
+ "brush strokes stay off the grid"
+ );
+ assert!(
+ refuse(
+ &bundle.doc,
+ format!(
+ r##"{{"op":"fill","layer":"{}","polygon":[[1,1],[9,1],[9,9]]}}"##,
+ layer.id
+ )
+ )
+ .contains("pixel layer")
+ );
+ assert!(
+ refuse(
+ &bundle.doc,
+ format!(
+ r##"{{"op":"pixel","layer":"{}","color":"teal","cells":[[1,1]]}}"##,
+ layer.id
+ )
+ )
+ .contains("teal")
+ );
+ assert!(
+ refuse(
+ &bundle.doc,
+ format!(
+ r##"{{"op":"pixel","layer":"{}","color":"skin","cells":[[40,40]]}}"##,
+ layer.id
+ )
+ )
+ .contains("none of the 1 cells")
+ );
+ let paint = bundle
+ .apply(&parse_lines(r##"{"op":"add","layer":{"kind":"paint","name":"paint"}}"##).unwrap())
+ .unwrap()
+ .added[0]
+ .clone();
+ let wrong = refuse(
+ &bundle.doc,
+ format!(r##"{{"op":"pixel","layer":"{paint}","color":"skin","cells":[[1,1]]}}"##),
+ );
+ assert!(wrong.contains("pixels go into pixel layers"), "{wrong}");
+ bundle
+ .apply(&parse_lines(r##"{"op":"add","layer":{"kind":"pixel","name":"more"}}"##).unwrap())
+ .unwrap();
+ assert!(bundle.doc.find_layer("more").unwrap().pixel());
+ assert!(Bundle::open(&dir).unwrap().doc.find_layer("more").unwrap().pixel());
+ fs::remove_dir_all(&dir).unwrap();
+ }
}
diff --git a/crates/core/src/doc.rs b/crates/core/src/doc.rs
index e66f34e..d72fba6 100644
--- a/crates/core/src/doc.rs
+++ b/crates/core/src/doc.rs
@@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize};
use std::borrow::Cow;
use std::collections::{BTreeMap, BTreeSet};
-pub const FORMAT: &str = "klad/6";
+pub const FORMAT: &str = "klad/7";
pub const MAX_SIZE: u32 = 16384;
pub const MASK: usize = usize::MAX;
@@ -76,6 +76,8 @@ pub struct Swatch {
pub color: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub name: String,
+ #[serde(default, skip_serializing_if = "String::is_empty")]
+ pub id: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -182,6 +184,8 @@ pub enum LayerContent {
Paint {
#[serde(default)]
cels: Vec<Cel>,
+ #[serde(default, skip_serializing_if = "is_false")]
+ pixel: bool,
},
Vector {
#[serde(default)]
@@ -561,10 +565,33 @@ impl Layer {
name,
LayerContent::Paint {
cels: vec![Cel::at(cel, 0)],
+ pixel: false,
+ },
+ )
+ }
+
+ pub fn pixels(id: &str, name: &str, cel: &str) -> Self {
+ Self::with(
+ id,
+ name,
+ LayerContent::Paint {
+ cels: vec![Cel::at(cel, 0)],
+ pixel: true,
},
)
}
+ pub fn pixel(&self) -> bool {
+ matches!(self.content, LayerContent::Paint { pixel: true, .. })
+ }
+
+ pub fn kind_name(&self) -> &'static str {
+ match self.pixel() {
+ true => "pixel",
+ false => self.kind().name(),
+ }
+ }
+
pub fn vector(id: &str, name: &str, cel: &str, nodes: Vec<Node>) -> Self {
let mut first = Cel::at(cel, 0);
first.nodes = nodes;
@@ -610,14 +637,14 @@ impl Layer {
pub fn cels(&self) -> &[Cel] {
match &self.content {
- LayerContent::Paint { cels } | LayerContent::Vector { cels } => cels,
+ LayerContent::Paint { cels, .. } | LayerContent::Vector { cels } => cels,
LayerContent::Group { .. } | LayerContent::Adjust { .. } | LayerContent::Bones {} => &[],
}
}
pub fn cels_mut(&mut self) -> Option<&mut Vec<Cel>> {
match &mut self.content {
- LayerContent::Paint { cels } | LayerContent::Vector { cels } => Some(cels),
+ LayerContent::Paint { cels, .. } | LayerContent::Vector { cels } => Some(cels),
LayerContent::Group { .. } | LayerContent::Adjust { .. } | LayerContent::Bones {} => None,
}
}
@@ -1203,6 +1230,35 @@ impl Document {
.or_else(|| key.parse::<usize>().ok().filter(|i| *i < self.palette.len()))
}
+ pub fn entry(&self, id: &str) -> Option<&Swatch> {
+ self.palette.iter().find(|s| !s.id.is_empty() && s.id == id)
+ }
+
+ pub fn bind_swatch(&mut self, key: &str) -> Result<(String, String)> {
+ let key = key.trim();
+ let at = match self.swatch(key) {
+ Some(at) => at,
+ None if key.starts_with('#') => {
+ parse_hex(key)?;
+ self.palette.push(Swatch {
+ color: key.to_string(),
+ name: String::new(),
+ id: String::new(),
+ });
+ self.palette.len() - 1
+ }
+ None => {
+ self.resolve_color(key)?;
+ bail!("the palette has no {key:?}");
+ }
+ };
+ if self.palette[at].id.is_empty() {
+ let mut taken: BTreeSet<String> = self.palette.iter().map(|s| s.id.clone()).collect();
+ self.palette[at].id = self.alloc_id_in('p', &mut taken);
+ }
+ Ok((self.palette[at].id.clone(), self.palette[at].color.clone()))
+ }
+
pub fn effects_of<'a>(&self, layer: &'a Layer) -> Cow<'a, [Effect]> {
match (layer.depth, &self.atmosphere) {
(Some(depth), Some(air)) if depth > 0.0 => Cow::Owned(
@@ -1258,8 +1314,12 @@ impl Document {
check_color(bg).context("canvas background")?;
}
let mut swatch_names = BTreeSet::new();
+ let mut swatch_ids = BTreeSet::new();
self.palette.iter().try_for_each(|swatch| {
parse_hex(&swatch.color).with_context(|| format!("palette colour {}", swatch.color))?;
+ if !swatch.id.is_empty() && !swatch_ids.insert(&swatch.id) {
+ bail!("palette id {} is used twice", swatch.id);
+ }
if swatch.name.starts_with('#') {
bail!("palette name {} cannot start with #", swatch.name);
}
@@ -1500,10 +1560,12 @@ mod tests {
Swatch {
color: "#1b1b1b".into(),
name: "ink".into(),
+ id: String::new(),
},
Swatch {
color: "#F4EFE6".into(),
name: String::new(),
+ id: String::new(),
},
];
doc.next_id = 10;
diff --git a/crates/core/src/fill.rs b/crates/core/src/fill.rs
index ce24392..241805f 100644
--- a/crates/core/src/fill.rs
+++ b/crates/core/src/fill.rs
@@ -39,6 +39,7 @@ pub struct Seed {
pub enum FillSource {
Seed { seed: Seed, reference: FillRef },
Polygon(Vec<[f32; 2]>),
+ Cells { entry: String, erase: bool },
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
@@ -77,6 +78,35 @@ impl Coverage {
}
}
+ pub fn from_cells(cells: &[[u32; 2]]) -> Self {
+ let (Some(x0), Some(y0)) = (cells.iter().map(|c| c[0]).min(), cells.iter().map(|c| c[1]).min()) else {
+ return Self::default();
+ };
+ let x1 = cells.iter().map(|c| c[0]).max().unwrap_or(x0);
+ let y1 = cells.iter().map(|c| c[1]).max().unwrap_or(y0);
+ let (width, height) = (x1 - x0 + 1, y1 - y0 + 1);
+ let mut alpha = vec![0u8; width as usize * height as usize];
+ cells
+ .iter()
+ .for_each(|c| alpha[((c[1] - y0) * width + (c[0] - x0)) as usize] = 255);
+ Self {
+ x: x0,
+ y: y0,
+ width,
+ height,
+ alpha,
+ }
+ }
+
+ pub fn cells(&self) -> impl Iterator<Item = [u32; 2]> + '_ {
+ let width = self.width.max(1);
+ self.alpha
+ .iter()
+ .enumerate()
+ .filter(|(_, a)| **a > 0)
+ .map(move |(i, _)| [self.x + i as u32 % width, self.y + i as u32 / width])
+ }
+
pub fn is_empty(&self) -> bool {
self.width == 0 || self.height == 0
}
@@ -188,9 +218,40 @@ impl Fill {
pub fn reference(&self) -> Option<&FillRef> {
match &self.source {
FillSource::Seed { reference, .. } => Some(reference),
- FillSource::Polygon(_) => None,
+ FillSource::Polygon(_) | FillSource::Cells { .. } => None,
}
}
+
+ pub fn cells(id: u32, color: Rgba, entry: &str, erase: bool, coverage: Coverage) -> Self {
+ Self::new(
+ id,
+ color,
+ FillSource::Cells {
+ entry: entry.to_string(),
+ erase,
+ },
+ coverage,
+ )
+ }
+
+ pub fn centre(&self) -> Option<(f32, f32)> {
+ self.bounds().map(|[x0, y0, x1, y1]| ((x0 + x1) / 2.0, (y0 + y1) / 2.0))
+ }
+
+ pub fn entry(&self) -> Option<&str> {
+ match &self.source {
+ FillSource::Cells { entry, .. } if !entry.is_empty() => Some(entry),
+ _ => None,
+ }
+ }
+
+ pub fn on_grid(&self) -> bool {
+ matches!(self.source, FillSource::Cells { .. })
+ }
+
+ pub fn erases(&self) -> bool {
+ matches!(self.source, FillSource::Cells { erase: true, .. })
+ }
}
fn put_f32(out: &mut Vec<u8>, v: f32) {
@@ -229,6 +290,12 @@ pub(crate) fn encode(out: &mut Vec<u8>, fill: &Fill) {
varint::put(out, points.len() as u64);
points.iter().flatten().for_each(|v| put_f32(out, *v));
}
+ FillSource::Cells { entry, erase } => {
+ out.push(2 | flags);
+ varint::put(out, entry.len() as u64);
+ out.extend_from_slice(entry.as_bytes());
+ out.push(u8::from(*erase));
+ }
}
fill.coverage.encode(out);
if !fill.cuts.is_empty() {
@@ -279,6 +346,14 @@ pub(crate) fn decode(reader: &mut Reader) -> Result<Fill> {
.collect::<Result<_>>()?,
)
}
+ 2 => {
+ let len = reader.varint()? as usize;
+ let entry = String::from_utf8(reader.take(len)?.to_vec())?;
+ FillSource::Cells {
+ entry,
+ erase: reader.u8()? == 1,
+ }
+ }
other => bail!("unknown fill source {other}"),
};
let coverage = Coverage::decode(reader)?;
@@ -364,7 +439,20 @@ mod tests {
keep: cut::Keep::Inside,
polygon: vec![[0.0, 0.0], [20.0, 0.0], [0.0, 20.0]],
}];
- fills.iter().chain([&locked]).for_each(|fill| {
+ let cells = Coverage::from_cells(&[[4, 9], [5, 9], [7, 11]]);
+ assert_eq!((cells.x, cells.y, cells.width, cells.height), (4, 9, 4, 3));
+ assert_eq!(cells.cells().collect::<Vec<_>>(), [[4, 9], [5, 9], [7, 11]]);
+ assert!(Coverage::from_cells(&[]).is_empty());
+ let mut pixels = Fill::cells(6, [0.5, 0.25, 0.125, 1.0], "p3qa", false, cells.clone());
+ pixels.lock = true;
+ let eraser = Fill::cells(7, [0.0, 0.0, 0.0, 1.0], "", true, cells);
+ assert_eq!(
+ (pixels.entry(), pixels.erases(), pixels.on_grid()),
+ (Some("p3qa"), false, true)
+ );
+ assert_eq!((eraser.entry(), eraser.erases()), (None, true));
+ assert!(!locked.on_grid() && locked.entry().is_none());
+ fills.iter().chain([&locked, &pixels, &eraser]).for_each(|fill| {
let mut bytes = Vec::new();
encode(&mut bytes, fill);
let mut reader = Reader::new(&bytes);
diff --git a/crates/core/src/markedit.rs b/crates/core/src/markedit.rs
index 8eec20a..c703b76 100644
--- a/crates/core/src/markedit.rs
+++ b/crates/core/src/markedit.rs
@@ -13,6 +13,7 @@ pub type Affine = [f32; 6];
pub const IDENTITY: Affine = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];
const STROKE_KEYS: &[&str] = &["color", "size", "opacity", "flow", "brush", "taper", "path"];
const FILL_KEYS: &[&str] = &["color", "opacity"];
+const CELL_KEYS: &[&str] = &["color", "opacity", "entry"];
pub const TRANSFORM_KEYS: &[&str] = &["x", "y", "rotate", "sx", "sy", "pivot"];
pub fn parse_address(text: &str) -> Option<(&str, u32)> {
@@ -333,7 +334,18 @@ pub fn reshape(stroke: &mut Stroke, d: &str) -> Result<()> {
}
fn set_fill(fill: &mut Fill, props: &Map<String, Value>) -> Result<()> {
- check_keys(props, FILL_KEYS, "fill")?;
+ match &mut fill.source {
+ FillSource::Cells { erase: true, .. } => {
+ bail!("an erasing mark has no colour or opacity to set; remove it instead")
+ }
+ FillSource::Cells { entry, .. } => {
+ check_keys(props, CELL_KEYS, "pixel mark")?;
+ if let Some(bound) = props.get("entry").and_then(Value::as_str) {
+ *entry = bound.to_string();
+ }
+ }
+ _ => check_keys(props, FILL_KEYS, "fill")?,
+ }
if let Some(c) = color(props)? {
fill.color = c;
}
@@ -395,7 +407,7 @@ fn shifted(c: &Coverage, dx: i64, dy: i64) -> Coverage {
}
}
-fn resampled(c: &Coverage, a: Affine) -> Coverage {
+fn resampled(c: &Coverage, a: Affine, hard: bool) -> Coverage {
let Some(inverse) = invert(a) else {
return Coverage::default();
};
@@ -419,6 +431,12 @@ fn resampled(c: &Coverage, a: Affine) -> Coverage {
.flat_map(|j| (0..w).map(move |i| (i, j)))
.map(|(i, j)| {
let (sx, sy) = apply_affine(inverse, ((bx0 + i) as f32 + 0.5, (by0 + j) as f32 + 0.5));
+ if hard {
+ return match at(sx.floor() as i64, sy.floor() as i64) > 0.0 {
+ true => 255,
+ false => 0,
+ };
+ }
let (fx, fy) = (sx - 0.5, sy - 0.5);
let (ix, iy) = (fx.floor() as i64, fy.floor() as i64);
let (tx, ty) = (fx - ix as f32, fy - iy as f32);
@@ -440,13 +458,14 @@ pub fn transform_fill(fill: &mut Fill, a: Affine) {
match &mut fill.source {
FillSource::Seed { seed, .. } => [seed.x, seed.y] = map([seed.x, seed.y]),
FillSource::Polygon(points) => points.iter_mut().for_each(|p| *p = map(*p)),
+ FillSource::Cells { .. } => {}
}
let (coverage, region) = match translation(a) {
Some((dx, dy)) => (
shifted(&fill.coverage, dx, dy),
[1.0, 0.0, 0.0, 1.0, dx as f32, dy as f32],
),
- None => (resampled(&fill.coverage, a), a),
+ None => (resampled(&fill.coverage, a, fill.on_grid()), a),
};
fill.coverage = coverage;
fill.cuts.iter_mut().for_each(|c| c.map(|p| mapped(region, p)));
@@ -973,6 +992,57 @@ mod tests {
assert!(matches!(f.source, FillSource::Seed { seed, .. } if seed.x == 30.0));
}
+ #[test]
+ fn pixel_marks_stay_hard_when_scaled_flipped_or_turned() {
+ let corner = || -> Mark {
+ Fill::cells(
+ 1,
+ [1.0, 0.0, 0.0, 1.0],
+ "p1",
+ false,
+ Coverage::from_cells(&[[4, 4], [5, 4], [6, 4], [4, 5]]),
+ )
+ .into()
+ };
+ let changed = |transform: MarkTransform| -> Coverage {
+ let mut marks = vec![corner()];
+ let mut change = MarkChange::Transform {
+ ids: vec![1],
+ transform,
+ };
+ apply(&mut marks, &mut change, "c1", MarkIds::default()).unwrap();
+ let fill = marks[0].as_fill().unwrap();
+ assert_eq!(fill.entry(), Some("p1"));
+ assert!(fill.coverage.alpha.iter().all(|a| *a == 0 || *a == 255));
+ fill.coverage.clone()
+ };
+ let big = changed(MarkTransform {
+ sx: 3.0,
+ sy: 3.0,
+ pivot: Some([0.0, 0.0]),
+ ..Default::default()
+ });
+ assert_eq!((big.x, big.y, big.width, big.height), (12, 12, 9, 6));
+ assert_eq!(big.pixels(), 4 * 9, "every pixel becomes a 3x3 block");
+ assert_eq!(
+ (big.at(12, 12), big.at(20, 14), big.at(15, 15), big.at(14, 17)),
+ (255, 255, 0, 255)
+ );
+ let flipped = changed(MarkTransform {
+ sx: -1.0,
+ pivot: Some([5.5, 5.0]),
+ ..Default::default()
+ });
+ assert_eq!(flipped.cells().collect::<Vec<_>>(), [[4, 4], [5, 4], [6, 4], [6, 5]]);
+ let turned = changed(MarkTransform {
+ rotate: 90.0,
+ pivot: Some([5.0, 5.0]),
+ ..Default::default()
+ });
+ assert_eq!(turned.cells().collect::<Vec<_>>(), [[4, 4], [5, 4], [5, 5], [5, 6]]);
+ assert_eq!(turned.pixels(), 4, "a quarter turn keeps every pixel");
+ }
+
#[test]
fn clicks_pick_the_topmost_mark_and_lassos_take_whole_marks() {
let mut marks = vec![square(1), line(2)];
diff --git a/crates/core/src/migrate.rs b/crates/core/src/migrate.rs
index 963f71d..1e7382d 100644
--- a/crates/core/src/migrate.rs
+++ b/crates/core/src/migrate.rs
@@ -10,7 +10,7 @@ pub fn migrate(value: Value) -> Result<Value> {
.to_string();
match format.as_str() {
FORMAT => Ok(value),
- "klad/4" | "klad/5" => Ok(uncount(value)),
+ "klad/4" | "klad/5" | "klad/6" => Ok(uncount(value)),
"klad/1" | "klad/2" | "klad/3" => {
let mut value = value;
if let Some(layers) = value.get_mut("layers").and_then(Value::as_array_mut) {
@@ -98,8 +98,13 @@ mod tests {
]}]}),
"rigs from before bones layers are dropped; the drawings, posed ones too, stay"
);
+ assert_eq!(
+ migrate(json!({"format": "klad/6", "layers": []})).unwrap(),
+ json!({"format": FORMAT, "layers": []}),
+ "klad/7 adds pixel layers and palette ids; a klad/6 drawing opens unchanged"
+ );
assert!(
- migrate(json!({"format": "klad/7"}))
+ migrate(json!({"format": "klad/8"}))
.unwrap_err()
.to_string()
.contains("newer klad")
diff --git a/crates/core/src/ops.rs b/crates/core/src/ops.rs
index 96a8164..aa8bb96 100644
--- a/crates/core/src/ops.rs
+++ b/crates/core/src/ops.rs
@@ -27,6 +27,7 @@ const LAYER_KEYS: &[&str] = &[
"mask",
"cels",
"children",
+ "pixel",
"effects",
"adjust",
"depth",
@@ -53,7 +54,7 @@ const NODE_KEYS: &[&str] = &[
const TRANSFORM_KEYS: &[&str] = &["x", "y", "rotate", "sx", "sy", "pivot"];
const STROKE_KEYS: &[&str] = &["paint", "width", "cap", "join", "dash"];
const STRUCTURE: &[&str] = &[
- "id", "kind", "type", "cels", "children", "nodes", "mask", "bones", "ik", "rig", "keys", "pose", "parts",
+ "id", "kind", "pixel", "type", "cels", "children", "nodes", "mask", "bones", "ik", "rig", "keys", "pose", "parts",
];
fn shape_keys(kind: &str) -> Result<&'static [&'static str]> {
@@ -119,6 +120,7 @@ pub enum Op {
},
Stroke(StrokeSpec),
Fill(FillSpec),
+ Pixel(PixelSpec),
Palette(PaletteEdit),
Transform {
ids: Vec<String>,
@@ -265,6 +267,49 @@ pub enum PaletteEdit {
},
}
+#[derive(Clone, Debug, PartialEq, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct PixelSpec {
+ pub layer: String,
+ #[serde(default)]
+ pub frame: u32,
+ #[serde(default)]
+ pub color: Option<String>,
+ #[serde(default)]
+ pub erase: bool,
+ pub cells: Vec<[i64; 2]>,
+ #[serde(default)]
+ pub part: Option<String>,
+}
+
+impl PixelSpec {
+ pub fn check(&self) -> Result<()> {
+ match (&self.color, self.erase) {
+ (Some(_), true) => bail!("pixel takes a color or erase, not both"),
+ (None, false) => bail!("pixel needs a color (a palette name or #rrggbb) or \"erase\":true"),
+ _ => {}
+ }
+ if self.cells.is_empty() {
+ bail!("pixel needs cells: a list of [x, y] in canvas pixels");
+ }
+ Ok(())
+ }
+
+ pub fn coverage(&self, doc: &Document) -> Result<Coverage> {
+ let (w, h) = (doc.canvas.width as i64, doc.canvas.height as i64);
+ let inside: Vec<[u32; 2]> = self
+ .cells
+ .iter()
+ .filter(|c| c[0] >= 0 && c[1] >= 0 && c[0] < w && c[1] < h)
+ .map(|c| [c[0] as u32, c[1] as u32])
+ .collect();
+ if inside.is_empty() {
+ bail!("none of the {} cells is on the {w}x{h} canvas", self.cells.len());
+ }
+ Ok(Coverage::from_cells(&inside))
+ }
+}
+
#[derive(Clone, Debug, PartialEq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct FillSpec {
@@ -1470,6 +1515,11 @@ impl Op {
spec.check()?;
Op::Fill(spec)
}
+ "pixel" => {
+ let spec: PixelSpec = serde_json::from_value(Value::Object(std::mem::take(&mut map)))?;
+ spec.check()?;
+ Op::Pixel(spec)
+ }
"palette" => Op::Palette(parse_palette(&mut map)?),
"transform" if map.contains_key("layer") => {
let layer = take_str(&mut map, "layer")?.unwrap_or_default();
@@ -1612,7 +1662,7 @@ impl Op {
},
other => {
bail!(
- "unknown op {other:?}: use add, set, rm, mv, stroke, fill, palette, transform, path, lasso, copy, timeline, frames, cel, clip, retime, inbetween, duplicate, ink, light, hatch, scatter, paint, foliage, grass, paintover, part, key, bone, ik, weights, pose or export"
+ "unknown op {other:?}: use add, set, rm, mv, stroke, fill, pixel, palette, transform, path, lasso, copy, timeline, frames, cel, clip, retime, inbetween, duplicate, ink, light, hatch, scatter, paint, foliage, grass, paintover, part, key, bone, ik, weights, pose or export"
)
}
};
@@ -2727,6 +2777,7 @@ fn edit_palette(doc: &mut Document, edit: &PaletteEdit) -> Result<()> {
Swatch {
color: color.clone(),
name: name.clone(),
+ id: String::new(),
},
);
}
@@ -2802,8 +2853,17 @@ fn assign_layer_ids(doc: &mut Document, taken: &mut BTreeSet<String>, value: &mu
let kind = value
.get("kind")
.and_then(Value::as_str)
- .ok_or_else(|| anyhow!("a layer needs a kind: paint, vector, group or adjust"))?
+ .ok_or_else(|| anyhow!("a layer needs a kind: paint, pixel, vector, group or adjust"))?
.to_string();
+ let pixel = kind == "pixel" || value.get("pixel").and_then(Value::as_bool) == Some(true);
+ if kind == "pixel" {
+ value["kind"] = Value::from("paint");
+ value["pixel"] = Value::from(true);
+ }
+ let kind = match pixel {
+ true => "pixel".to_string(),
+ false => kind,
+ };
let id = ensure_id(doc, taken, value, 'l')?;
if value.get("name").is_none() {
let names: BTreeSet<String> = doc.all_layers().iter().map(|l| l.name.clone()).collect();
@@ -2814,7 +2874,7 @@ fn assign_layer_ids(doc: &mut Document, taken: &mut BTreeSet<String>, value: &mu
value["name"] = Value::String(name);
}
match kind.as_str() {
- "paint" | "vector" => {
+ "paint" | "pixel" | "vector" => {
if value.get("cels").is_none_or(|c| c.as_array().is_none_or(Vec::is_empty)) {
value["cels"] = serde_json::json!([{ "frame": 0 }]);
}
@@ -3300,7 +3360,7 @@ pub fn apply(doc: &mut Document, op: &Op, out: &mut Applied) -> Result<()> {
let path = layer_path(doc, layer)?;
let target = doc.layer_at_mut(&path);
let cels = match &mut target.content {
- LayerContent::Paint { cels } | LayerContent::Vector { cels } => cels,
+ LayerContent::Paint { cels, .. } | LayerContent::Vector { cels } => cels,
LayerContent::Group { .. } => bail!("{layer} is a group; cels go into paint or vector layers"),
LayerContent::Adjust { .. } => bail!("{layer} is an adjustment; cels go into paint or vector layers"),
LayerContent::Bones {} => bail!("{layer} is a bones layer; cels go into paint or vector layers"),
@@ -3356,8 +3416,20 @@ pub fn apply(doc: &mut Document, op: &Op, out: &mut Applied) -> Result<()> {
Some((cel, mark)) => {
let layer = mark_owner(doc, cel)?;
let mut props = props.clone();
- if let Some(color) = props.get("color").and_then(Value::as_str) {
- let hex = doc.resolve_color(color).with_context(|| format!("set {id}"))?;
+ let on_grid = doc.layer(&layer).is_some_and(Layer::pixel);
+ if let Some(color) = props.get("color").and_then(Value::as_str).map(String::from) {
+ let hex = match on_grid {
+ true => {
+ let before = doc.palette.clone();
+ let (entry, hex) = doc.bind_swatch(&color).with_context(|| format!("set {id}"))?;
+ if doc.palette != before && !out.changed.iter().any(|c| c == "palette") {
+ out.changed.push("palette".into());
+ }
+ props.insert("entry".into(), Value::String(entry));
+ hex
+ }
+ false => doc.resolve_color(&color).with_context(|| format!("set {id}"))?,
+ };
props.insert("color".into(), Value::String(hex));
}
out.push(&layer, cel, MarkChange::Set { id: mark, props });
@@ -3438,6 +3510,7 @@ pub fn apply(doc: &mut Document, op: &Op, out: &mut Applied) -> Result<()> {
out.changed.push(id.clone());
}
Op::Stroke(spec) => {
+ off_the_grid(doc, &spec.layer, "brush strokes")?;
let resolved = StrokeSpec {
color: doc.resolve_color(&spec.color)?,
second: spec.second.as_deref().map(|c| doc.resolve_color(c)).transpose()?,
@@ -3482,7 +3555,49 @@ pub fn apply(doc: &mut Document, op: &Op, out: &mut Applied) -> Result<()> {
Ok::<_, anyhow::Error>(())
})?;
}
+ Op::Pixel(spec) => {
+ spec.check().with_context(|| format!("pixel on {}", spec.layer))?;
+ let path = layer_path(doc, &spec.layer)?;
+ let target = doc.layer_at(&path);
+ if !target.pixel() {
+ bail!(
+ "{} is a {} layer; pixels go into pixel layers (klad add <bundle> layer pixel)",
+ spec.layer,
+ target.kind().name()
+ );
+ }
+ let coverage = spec.coverage(doc).with_context(|| format!("pixel on {}", spec.layer))?;
+ let mut fill = match &spec.color {
+ Some(color) => {
+ let before = doc.palette.clone();
+ let (entry, hex) = doc
+ .bind_swatch(color)
+ .with_context(|| format!("pixel on {}", spec.layer))?;
+ if doc.palette != before && !out.changed.iter().any(|c| c == "palette") {
+ out.changed.push("palette".into());
+ }
+ Fill::cells(0, parse_hex(&hex)?, &entry, false, coverage)
+ }
+ None => Fill::cells(0, [0.0, 0.0, 0.0, 1.0], "", true, coverage),
+ }
+ .by(Author::Agent);
+ fill.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 {
+ out.push(
+ &spec.layer,
+ &cel,
+ MarkChange::Part {
+ name: name.clone(),
+ count: 1,
+ ids: Vec::new(),
+ },
+ );
+ }
+ }
Op::Fill(spec) => {
+ off_the_grid(doc, &spec.layer, "flood and lasso fills")?;
let mut fill = spec.build(doc).with_context(|| format!("fill on {}", spec.layer))?;
fill.lock = locks_alpha(doc, &spec.layer);
let cel = paint_cel_at(doc, &spec.layer, spec.frame, out)?;
@@ -3629,6 +3744,13 @@ fn edit_path(doc: &mut Document, id: &str, edit: &PathEdit) -> Result<()> {
Ok(())
}
+fn off_the_grid(doc: &Document, layer: &str, what: &str) -> Result<()> {
+ if doc.layer(layer).is_some_and(Layer::pixel) {
+ bail!("{layer} is a pixel layer: it takes whole pixels (klad pixel), not {what}");
+ }
+ Ok(())
+}
+
fn locks_alpha(doc: &Document, layer: &str) -> bool {
doc.layer(layer).is_some_and(|l| l.lock_alpha)
}
diff --git a/crates/core/src/patch.rs b/crates/core/src/patch.rs
index a496f42..1954242 100644
--- a/crates/core/src/patch.rs
+++ b/crates/core/src/patch.rs
@@ -108,7 +108,10 @@ fn doc_shell(doc: &Document) -> Document {
fn layer_shell(layer: &Layer) -> Layer {
let content = match &layer.content {
- LayerContent::Paint { .. } => LayerContent::Paint { cels: Vec::new() },
+ LayerContent::Paint { pixel, .. } => LayerContent::Paint {
+ cels: Vec::new(),
+ pixel: *pixel,
+ },
LayerContent::Vector { .. } => LayerContent::Vector { cels: Vec::new() },
LayerContent::Group { .. } => LayerContent::Group { children: Vec::new() },
LayerContent::Adjust { adjust } => LayerContent::Adjust { adjust: adjust.clone() },
@@ -187,8 +190,8 @@ fn layer(out: &mut Out, at: &str, a: &Layer, b: &Layer) -> Result<()> {
list(out, &format!("{at}/children"), x, y, same_layer, layer)
}
(
- LayerContent::Paint { cels: x } | LayerContent::Vector { cels: x },
- LayerContent::Paint { cels: y } | LayerContent::Vector { cels: y },
+ LayerContent::Paint { cels: x, .. } | LayerContent::Vector { cels: x },
+ LayerContent::Paint { cels: y, .. } | LayerContent::Vector { cels: y },
) => list(out, &format!("{at}/cels"), x, y, same_cel, cel),
(LayerContent::Adjust { .. }, LayerContent::Adjust { .. })
| (LayerContent::Bones {}, LayerContent::Bones {}) => Ok(()),
@@ -242,7 +245,7 @@ fn step<'a>(target: Target<'a>, part: &str) -> Result<Target<'a>> {
(Target::Doc(doc), "layers") => Target::Layers(&mut doc.layers),
(Target::Layers(list), part) => Target::Layer(nth(list, part)?),
(Target::Layer(layer), "cels") => match &mut layer.content {
- LayerContent::Paint { cels } | LayerContent::Vector { cels } => Target::Cels(cels),
+ LayerContent::Paint { cels, .. } | LayerContent::Vector { cels } => Target::Cels(cels),
LayerContent::Group { .. } | LayerContent::Adjust { .. } | LayerContent::Bones {} => {
bail!("layer {} has no cels", layer.id)
}
@@ -312,7 +315,7 @@ fn merge<T: Serialize + DeserializeOwned>(item: &T, old: &Value, new: &Value) ->
fn lists(content: &mut LayerContent) -> (Option<&mut Vec<Cel>>, Option<&mut Vec<Layer>>) {
match content {
- LayerContent::Paint { cels } | LayerContent::Vector { cels } => (Some(cels), None),
+ LayerContent::Paint { cels, .. } | LayerContent::Vector { cels } => (Some(cels), None),
LayerContent::Group { children } => (None, Some(children)),
LayerContent::Adjust { .. } | LayerContent::Bones {} => (None, None),
}
diff --git a/crates/core/src/retime.rs b/crates/core/src/retime.rs
index b749d2f..aa72cf9 100644
--- a/crates/core/src/retime.rs
+++ b/crates/core/src/retime.rs
@@ -171,7 +171,7 @@ fn rebuild(doc: &mut Document, path: &[usize], runs: Vec<Run>, out: &mut Applied
}
})
.collect();
- if let LayerContent::Paint { cels: list } | LayerContent::Vector { cels: list } =
+ if let LayerContent::Paint { cels: list, .. } | LayerContent::Vector { cels: list } =
&mut doc.layer_at_mut(path).content
{
*list = cels;
diff --git a/crates/core/src/stroke.rs b/crates/core/src/stroke.rs
index e79a0c0..a1fb5be 100644
--- a/crates/core/src/stroke.rs
+++ b/crates/core/src/stroke.rs
@@ -10,8 +10,8 @@ pub const TILT_STEPS: f32 = 127.0;
pub const ZSTD_LEVEL: i32 = 3;
const MAGIC: &[u8; 4] = b"KLST";
const OLD_MAGIC: &[u8; 4] = b"DAST";
-const VERSION: u8 = 2;
-const READS: [u8; 2] = [1, 2];
+const VERSION: u8 = 3;
+const READS: [u8; 3] = [1, 2, 3];
const MARK_STROKE: u8 = 0;
const MARK_FILL: u8 = 1;
const HAS_TILT: u8 = 1;
@@ -542,7 +542,12 @@ mod tests {
vec![Mark::Stroke(line), Mark::Stroke(free)],
"a version 1 file reads as strokes with nothing attached"
);
- old[4] = 3;
+ old[4] = 2;
+ assert!(
+ decode_raw(&old).is_ok(),
+ "a version 2 file, from before pixel marks, reads as it is"
+ );
+ old[4] = 4;
assert!(decode_raw(&old).unwrap_err().to_string().contains("newer klad"));
}
diff --git a/crates/core/src/tween.rs b/crates/core/src/tween.rs
index 7bacd65..73281c9 100644
--- a/crates/core/src/tween.rs
+++ b/crates/core/src/tween.rs
@@ -455,6 +455,7 @@ fn points_of_mark(mark: &Mark) -> Vec<(f32, f32)> {
Mark::Fill(f) => match &f.source {
FillSource::Polygon(points) => points.iter().map(|p| (p[0], p[1])).collect(),
FillSource::Seed { seed, .. } => vec![(seed.x, seed.y)],
+ FillSource::Cells { .. } => f.centre().into_iter().collect(),
},
}
}
@@ -503,6 +504,7 @@ pub fn carry(mark: &Mark, from: &Lines, to: &Lines, within: Option<&[usize]>) ->
FillSource::Seed { seed, .. } => {
(seed.x, seed.y) = mv((seed.x, seed.y));
}
+ FillSource::Cells { .. } => {}
},
}
out
@@ -583,7 +585,7 @@ fn sort_of(mark: &Mark) -> Sort {
Mark::Stroke(_) => Sort::Stroke,
Mark::Fill(f) => match f.source {
FillSource::Polygon(_) => Sort::Polygon,
- FillSource::Seed { .. } => Sort::Flood,
+ FillSource::Seed { .. } | FillSource::Cells { .. } => Sort::Flood,
},
}
}
@@ -606,6 +608,15 @@ fn outline(mark: &Mark) -> Vec<P> {
y: seed.y as f64,
..P::default()
}],
+ FillSource::Cells { .. } => f
+ .centre()
+ .map(|(x, y)| P {
+ x: x as f64,
+ y: y as f64,
+ ..P::default()
+ })
+ .into_iter()
+ .collect(),
},
}
}
diff --git a/docs/DESIGN.md b/docs/DESIGN.md
index 6b3bf7b..b93a628 100644
--- a/docs/DESIGN.md
+++ b/docs/DESIGN.md
@@ -1,4 +1,4 @@
-_Last updated: 2026-11-10 20:10_
+_Last updated: 2026-11-11 13:40_
# klad: design
@@ -101,7 +101,7 @@ art.klad/
Committed: everything except `.cache/`. A fresh clone rebuilds the cache by replaying strokes and fills.
-### doc.json (format `klad/6`)
+### doc.json (format `klad/7`)
```json
{
@@ -226,12 +226,13 @@ Unknown keys are errors that list the valid ones, so a typo never passes silentl
|---|---|---|
| `paint` | strokes, replayed to f16 tiles | human pen, agent scripted strokes |
| `vector` | shapes, paths, text, generators | agent |
-| `pixel` | palette-indexed grid, no anti-aliasing | agent and human |
+| `pixel` | whole pixels bound to palette entries, no anti-aliasing (a `paint` layer with `pixel: true`, M9) | agent and human |
| `adjust` | one adjustment: `hsl`, `levels`, `curves`, `balance`, `gradient-map`, `fill` (M5) | either |
| `group` | children, blend mode, opacity, mask, clipping | either |
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`). Palette-wide recolouring, the pencil, shapes, 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.
@@ -528,7 +529,8 @@ The agent may run in a Linux container while the editor runs on the macOS host,
| M4 | The editor, usable: docked panels, a look, tool strip, layers panel, timeline toolbar, status and progress, command palette, pen-sized targets |
| M4.5 | The agent's hand: ink, flats, shade, rim and texture from vector shapes; arcs and spacing checks, parts, in-betweens that keep hand work |
| M5 | Painting and the look: textured and wet brushes, adjustments, filters, light, depth fog, generators, text, image layers |
-| M6 | Rigs and scenes: cut-out parts, bones, re-posing drawings, keyframes, parallax scenes, pixel layers |
+| M6 | Rigs and scenes: cut-out parts, bones, re-posing drawings, keyframes, parallax scenes |
+| M9 | Pixel art: pixel layers of marks bound to the palette, a sharp view, pencil and shapes on the grid, text grids for agents, palette swaps, sharp exports, Aseprite files, checks and a pixel art skill |
## Risks M0 retires
diff --git a/docs/cli.md b/docs/cli.md
index c5249ab..6bb821d 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -39,6 +39,7 @@ This reference is licensed under the MIT License (`LICENSE-MIT`), unlike klad it
- [`klad render`](#klad-render): Render a frame to PNG and print the path
- [`klad stroke`](#klad-stroke): Paint a stroke with a brush along an SVG path or explicit points
- [`klad fill`](#klad-fill): Fill a region of a paint layer, inside the lines (flood) or inside a polygon (lasso)
+- [`klad pixel`](#klad-pixel): Put whole pixels of one palette colour on a pixel layer, or erase them
- [`klad ink`](#klad-ink): Ink the outlines of vector shapes as tapered strokes, the way an inker would
- [`klad light`](#klad-light): Shade and rim light vector shapes from one light direction
- [`klad hatch`](#klad-hatch): Fill a shape's area with short tapered strokes: hatching, bark, fur, stone grain
@@ -121,6 +122,9 @@ Options:
--sketch
Add a vector layer named sketch on top, for blocking in shapes
+ --pixel <WxH>
+ A pixel art drawing of that many pixels, for example 64x64: its layers are pixel layers
+
-h, --help
Print help
```
@@ -852,7 +856,7 @@ Arguments:
layer, cel, mask, rect, ellipse, path, group, rays, image, scatter, repeat, mirror or text
[REST]...
- For layers the kind first (paint, vector, group, bones, image with src=photo.jpg, or adjust and its type: hsl, levels, curves, balance, gradient-map, fill), then key=value pairs
+ For layers the kind first (paint, pixel, vector, group, bones, image with src=photo.jpg, or adjust and its type: hsl, levels, curves, balance, gradient-map, fill), then key=value pairs
Options:
--in <INTO>
@@ -1638,6 +1642,60 @@ Options:
Print help (see a summary with '-h')
```
+## klad pixel
+
+```text
+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.
+
+--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.
+
+ klad pixel sprite.klad l1 --color '#2b2d42' --cells '3-12,4 3,5-9 12,5-9 3-12,10'
+ klad pixel sprite.klad l1 --color skin --cells '4-11,5-9'
+ klad pixel sprite.klad l1 --erase --cells '7,7 8,7'
+
+Also a pixel op in klad apply: {"op":"pixel","layer":"l1","color":"skin","cells":[[4,5],[5,5]]} or with "erase":true.
+
+Usage: klad pixel [OPTIONS] --cells <CELLS> <BUNDLE> <LAYER>
+
+Arguments:
+ <BUNDLE>
+
+
+ <LAYER>
+
+
+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
+
+ --color <COLOR>
+ A palette name, a palette index or #rrggbb
+
+ --erase
+ Clear these pixels instead of colouring them
+
+ --frame <FRAME>
+ [default: 0]
+
+ --part <PART>
+ Put the mark in this named part
+
+ --render
+ Render a preview after the edit and print its path
+
+ --scale <SCALE>
+ Preview scale (default: longest side 1024 px)
+
+ --json
+ Print the result as JSON
+
+ --overlay <OVERLAY>
+ Draw on the preview: ids, bbox, grid or all (comma separated)
+
+ -h, --help
+ Print help (see a summary with '-h')
+```
+
## klad ink
```text
diff --git a/docs/format.md b/docs/format.md
index 2f9e7b2..793f897 100644
--- a/docs/format.md
+++ b/docs/format.md
@@ -1,4 +1,4 @@
-_Last updated: 2026-11-09 21:30 (format `klad/6`, stroke files `KLST` version 2, brushes `klad-brush/1`)_
+_Last updated: 2026-11-11 13:30 (format `klad/7`, stroke files `KLST` version 3, brushes `klad-brush/1`)_
# The klad drawing format
@@ -32,13 +32,13 @@ Writers replace files atomically (write a temporary file, then rename), so a rea
- **Colours** are `"#rrggbb"` or `"#rrggbbaa"`: sRGB, straight (not premultiplied) alpha.
- **Ids** are unique across the whole document and use letters, digits, `-` and `_`. Ids are case sensitive. klad makes new ones from a prefix (`l` layer, `c` cel, `n` node), a number, and the tag of the copy that made them: `l48qa`. Each copy of a drawing (a clone, a git worktree: any folder without `.cache/copy.json`) picks a two-letter tag the first time klad opens it and keeps it in `.cache/copy.json`, with counters that only go up, so two copies edited apart never make the same id; the copy a drawing was made in has no tag (`l48`). A folder copied by hand with its `.cache/` keeps the tag: delete `.cache/` in the copy to give it its own. Ids already in a drawing never change. Writers that make their own ids should do the same or use a long random part. A drawing with an id used twice does not open; `klad repair` gives every later one a new id.
- **JSON** is UTF-8, written pretty with a stable key order. Keys at their default value are left out; readers must take the defaults listed below for missing keys. Most objects reject keys they do not know, so writers must not add their own.
-- **Versions.** `format` names the version of `doc.json` and everything it implies; this is `klad/6`. Each version opens the older `klad/` drawings and migrates them in memory (written back on the next change). A reader that meets a newer version than it knows should refuse to write the bundle. Drawings from before `klad/1` (`.draw` folders, formats `draw-anything/0` to `/9`) do not open.
+- **Versions.** `format` names the version of `doc.json` and everything it implies; this is `klad/7`. Each version opens the older `klad/` drawings and migrates them in memory (written back on the next change). A reader that meets a newer version than it knows should refuse to write the bundle. Drawings from before `klad/1` (`.draw` folders, formats `draw-anything/0` to `/9`) do not open.
## doc.json
```json
{
- "format": "klad/6",
+ "format": "klad/7",
"canvas": { "width": 2048, "height": 2048, "background": "#f4efe6" },
"timeline": { "fps": 12, "frames": 24, "origin": [1024, 1800],
"clips": [{ "name": "run", "from": 0, "to": 11, "loop": true, "fps": 24 }] },
@@ -60,15 +60,15 @@ Writers replace files atomically (write a temporary file, then rename), so a rea
| Key | Type | Default | Meaning |
|---|---|---|---|
-| `format` | string | | `"klad/6"` |
+| `format` | string | | `"klad/7"` |
| `canvas` | object | | `width`, `height` (px), `background` (a colour; none is transparent) |
| `timeline` | object | 12 fps, 1 frame | see below |
-| `palette` | array | `[]` | swatches: `color`, optional `name` (unique, not starting with `#`) |
+| `palette` | array | `[]` | swatches: `color`, optional `name` (unique, not starting with `#`), optional `id` (unique; set once a pixel mark uses the swatch) |
| `layers` | array | | the layers, **bottom first** |
| `export` | object | `{}` | `godot`: the folder Godot exports go to, relative to the folder holding the bundle |
| `atmosphere` | object | none | fog by depth: `color` (`#9aa8b8`), `top` (a colour higher up), `density` (0.5), `blur` (1), `desaturate` (0.15) |
-Strokes and fills store their colour, so the palette is a list of names for colours, never a reference: renaming or recolouring a swatch changes nothing drawn.
+Strokes and fills store their colour, so for them the palette is a list of names for colours, never a reference: renaming or recolouring a swatch changes nothing drawn. Pixel marks (below) also name the swatch they were drawn with, by its `id`.
### The timeline
@@ -88,6 +88,7 @@ A clip is `name` (unique), `from` and `to` (both included), `loop` (false) and `
| `id`, `name` | string | | |
| `kind` | string | | `paint`, `vector`, `group`, `adjust` or `bones` |
| `cels` | array | `[]` | paint and vector layers: the drawings on the timeline |
+| `pixel` | bool | false | paint layers: a pixel layer, whose marks are whole pixels (below) |
| `children` | array | `[]` | groups: the layers inside, bottom first |
| `adjust` | object | | adjustment layers: one adjustment (below) |
| `opacity` | number | 1 | |
@@ -109,6 +110,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.
- **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
@@ -224,14 +226,14 @@ Constraints are solved parent first, by the position of the limb's top bone (A f
## Stroke files
-`strokes/<layer>/<cel>.strokes` holds the marks of one paint drawing, in the order they are drawn: brush strokes and fills. Every mark has an id, unique within its drawing, shared by strokes and fills. A mark's address is `<cel>:s<id>`. An id is a `u32`: its top 10 bits name the copy that made it (0 for none, else 1 + 26 × first letter + second letter, with `a` as 0) and its low 22 bits are a number counted per copy, so `s349qa` is 349 made by the copy tagged `qa`, stored as `(1 + 16 × 26 + 0) << 22 | 349`. Ids from before `klad/5`, and those of the copy a drawing was made in, are plain numbers: `s348`. Addresses accept the number in either form.
+`strokes/<layer>/<cel>.strokes` holds the marks of one paint drawing, in the order they are drawn: brush strokes and fills (on a pixel layer, pixel marks). Every mark has an id, unique within its drawing, shared by strokes and fills. A mark's address is `<cel>:s<id>`. An id is a `u32`: its top 10 bits name the copy that made it (0 for none, else 1 + 26 × first letter + second letter, with `a` as 0) and its low 22 bits are a number counted per copy, so `s349qa` is 349 made by the copy tagged `qa`, stored as `(1 + 16 × 26 + 0) << 22 | 349`. Ids from before `klad/5`, and those of the copy a drawing was made in, are plain numbers: `s348`. Addresses accept the number in either form.
The file is one zstd frame (any level; klad uses 3). Inside:
| Bytes | What |
|---|---|
| 4 | `KLST` |
-| 1 | the version: 2 (version 1 files read as strokes with nothing attached) |
+| 1 | the version: 3 (version 1 files read as strokes with nothing attached; version 2 has no pixel marks) |
| varint | the number of marks |
| ... | each mark: a kind byte (0 stroke, 1 fill), then its record |
@@ -280,14 +282,17 @@ A reader that ignores attachments draws every drawing as it was when its erasers
| colour | colour | |
| opacity | f32 | |
| author | u8 | 0 a person, 1 an agent |
-| source | u8 | low bits: 0 a flood fill, 1 a polygon; bit `0x80` lock alpha, bit `0x40` cuts |
+| source | u8 | low bits: 0 a flood fill, 1 a polygon, 2 cells (a pixel mark); bit `0x80` lock alpha, bit `0x40` cuts |
| flood fill | f32 x, f32 y, u8 reference, 3 f32 | the seed point; what it filled from: 0 this layer, 1 everything visible, 2 a layer (then a string, its id); `tolerance`, `gap`, `expand` |
| polygon | varint n, n pairs of f32 | the polygon's points |
+| cells | string, u8 | the `id` of the palette swatch the mark is bound to (empty: none), then 1 if the mark erases, else 0 |
| coverage | see below | the pixels the fill covered when it was made |
| cuts | cuts | if bit `0x40` |
A 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.
+
### Cuts
When a lasso cuts across a mark, the mark is not split into new geometry: each part keeps the whole mark plus a cut that shows only its side. Cuts are a varint count, then for each a `u8` (0 keep inside, 1 keep outside) and a polygon (a varint n and n pairs of f32). A mark shows only where every one of its cuts keeps it.
@@ -347,3 +352,4 @@ Drawing a stroke: walk the samples, interpolate between them, stamp the tip ever
| `klad/4` | skeletons move to bones layers, and paint layers join one with `rig` (2026-11-08). Older drawings open without their bones, IK, weights links and the `pose` of their cels; the drawings themselves, posed ones too, stay. |
| `klad/5` | `rev` and `nextId` leave `doc.json`, and new ids carry the tag of the copy that made them, so drawings diff and merge in git (2026-11-09). Older drawings open with their ids unchanged; their counters move to `.cache/copy.json`. |
| `klad/6` | stroke files version 2: eraser, smudge and blender strokes record the marks they are attached to, and attached erasers erase only those (2026-11-09). Older drawings open unchanged, with nothing attached. |
+| `klad/7` | pixel layers: paint layers with `pixel`, pixel marks in stroke files (version 3), and palette swatches with an `id` (2026-11-11). Older drawings open unchanged. |
diff --git a/docs/skill/SKILL.md b/docs/skill/SKILL.md
index 5de0043..c36da04 100644
--- a/docs/skill/SKILL.md
+++ b/docs/skill/SKILL.md
@@ -99,6 +99,25 @@ klad lasso art.klad l4 --polygon '...' --cut --rm
- `klad transform` takes `--flip h` or `--flip v` too. In `transform` and `lasso`, `--scale` scales the marks; their previews use the default size.
- In `apply`: `{"op":"lasso","layer":"l4","polygon":[[600,600],[1400,560],[1450,1300]],"cut":true,"x":40,"y":-25}` (also `rotate`, `sx`, `sy`, `scale`, `pivot`, or `"rm":true`).
+## Pixel art
+
+```
+klad new sprite.klad --pixel 32x32 a pixel drawing: one pixel layer, l1
+klad add art.klad layer pixel name=sprite a pixel layer in any drawing
+klad pixel sprite.klad l1 --color '#2b2d42' --cells '3-12,2 3,3-8 12,3-8 3-12,9'
+klad pixel sprite.klad l1 --color skin --cells '4-11,3-8'
+klad pixel sprite.klad l1 --erase --cells '7,5 8,5'
+klad export sprite.klad --scale 8 -o [email protected] square pixels, to look at
+```
+
+- A pixel layer is a grid with no soft edges, and one pixel is one canvas pixel: a 32x32 sprite is a 32x32 drawing. Size the drawing in pixels of the art, not of the screen; `klad ls` shows the layer as `pixel`.
+- `--cells` takes `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.
+- `--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.
+- Each call makes one mark, `<cel>:s<id>`, that 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` makes a mark that clears what was drawn before it at those pixels (remove that mark and the pixels come back).
+- Look at a sprite enlarged: `klad export --scale 8` (whole numbers) keeps every pixel a square. At real size a 32 px picture is too small to judge.
+- In `apply`: `{"op":"pixel","layer":"l1","color":"skin","cells":[[4,5],[5,5]]}` or `"erase":true`. Brush strokes (`klad stroke`, `ink`, `paint`, ...) and `klad fill` are refused on a pixel layer.
+
## Masks, clipping and lock alpha
```