Skip to content

armgit / klad

Public Imported from GitHub
0

A drawing app built for agent/human collaboration

Rust

The palette of a pixel drawing: a changed colour recolours its pixels, ramps, and palettes to load

Indicode BV83e97a6e8e88
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b2cb924..fe2ab13 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.
+- The palette of a pixel drawing. Changing a palette colour changes every pixel painted with it: click the colour in the palette, change it, and press **update** (or `klad palette art.klad --recolour skin --to '#e8b796'`). **palettes** adds the colours of a palette that comes with klad (PICO-8, Sweetie 16, DawnBringer 16 and 32, Endesga 32, Resurrect 64, AAP-64, Game Boy, 1-bit; `klad palettes` lists them) or of a palette file, a list of hex colours or a GIMP palette (`klad palette art.klad --load pico-8`). **ramp** adds five steps of the current colour, from dark and cool to light and warm (`klad palette art.klad --ramp wood --base '#8b5a2b'`), and `--ramp skin --of skin-dark,skin,skin-light` groups colours the palette has.
- A sharp view for pixel drawings. In the editor the zoom steps in whole pixels, so every pixel is the same size; a grid shows between the pixels once you are zoomed in (**View > Pixel grid**), the pixel under the pointer is outlined and its position shows in the status line, and the **Real size** panel shows the drawing as the player sees it, at 1x, 2x or 4x. `klad render` enlarges a pixel drawing to about 512 px, and `--overlay grid` numbers its pixels along the top and the left.
- Pixel layers, the start of pixel art in klad. A pixel drawing (**Pixel art** in the start window, or `klad new sprite.klad --pixel 64x64`) is a small drawing of whole pixels with no soft edges; **Layer > New pixel layer** or `klad add art.klad layer pixel` adds a pixel layer to any drawing. `klad pixel sprite.klad l1 --color skin --cells '4-11,5-9'` puts pixels on it as one mark bound to a palette colour (a colour the palette lacks is added), and `--erase` clears them. Each mark stays editable: recolour it with `klad set`, move it with `klad transform`, remove it with `klad rm`; `klad strokes` lists them. Exports above full size keep the pixels square. Brush strokes and fills stay off pixel layers. The format is now `klad/7` (stroke files version 3); older drawings open unchanged.
- 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`.
diff --git a/crates/app/src/commands.rs b/crates/app/src/commands.rs
index bf6d806..8d0c0a8 100644
--- a/crates/app/src/commands.rs
+++ b/crates/app/src/commands.rs
@@ -60,6 +60,9 @@ pub enum Cmd {
Simplify,
MakePath,
AddSwatch,
+ UpdateSwatch,
+ AddRamp,
+ LoadPalette,
NewPaintLayer,
NewPixelLayer,
NewVectorLayer,
@@ -509,7 +512,7 @@ use Repeat as R;
use Trigger as T;
impl Cmd {
- pub const ALL: [Cmd; 182] = [
+ pub const ALL: [Cmd; 185] = [
Cmd::Brush,
Cmd::Eraser,
Cmd::Fill,
@@ -566,6 +569,9 @@ impl Cmd {
Cmd::Simplify,
Cmd::MakePath,
Cmd::AddSwatch,
+ Cmd::UpdateSwatch,
+ Cmd::AddRamp,
+ Cmd::LoadPalette,
Cmd::NewPaintLayer,
Cmd::NewPixelLayer,
Cmd::NewVectorLayer,
@@ -1200,6 +1206,33 @@ impl Cmd {
R::No,
"the current colour, with the name typed next to it",
),
+ Cmd::UpdateSwatch => spec(
+ "colour.update",
+ "change the palette colour to this colour",
+ icon::PALETTE,
+ G::Colour,
+ T::None,
+ R::No,
+ "the palette colour you clicked last takes the current colour, and every pixel painted with it changes too",
+ ),
+ Cmd::AddRamp => spec(
+ "colour.ramp",
+ "add a ramp of the colour",
+ icon::PALETTE,
+ G::Colour,
+ T::None,
+ R::No,
+ "five steps of the current colour in the palette, from dark and cool to light and warm, named after the name typed next to it",
+ ),
+ Cmd::LoadPalette => spec(
+ "colour.palettes",
+ "load a palette",
+ icon::PALETTE,
+ G::Colour,
+ T::None,
+ R::No,
+ "add the colours of a palette that comes with klad, or of a palette file (a list of hex colours or a GIMP palette)",
+ ),
Cmd::NewPaintLayer => spec(
"layer.new-paint",
"new paint layer",
@@ -2391,6 +2424,9 @@ impl Cmd {
Cmd::Simplify => "Simplify",
Cmd::MakePath => "Make path",
Cmd::AddSwatch => "Add colour to palette",
+ Cmd::UpdateSwatch => "Change palette colour to this",
+ Cmd::AddRamp => "Add a ramp of the colour",
+ Cmd::LoadPalette => "Load a palette…",
Cmd::NewPaintLayer => "New paint layer",
Cmd::NewPixelLayer => "New pixel layer",
Cmd::NewVectorLayer => "New vector layer",
@@ -2660,6 +2696,9 @@ pub const MENUS: [Menu; 9] = [
Line,
Run(Cmd::SwapColours),
Run(Cmd::AddSwatch),
+ Run(Cmd::UpdateSwatch),
+ Run(Cmd::AddRamp),
+ Run(Cmd::LoadPalette),
],
},
Menu {
diff --git a/crates/app/src/editor.rs b/crates/app/src/editor.rs
index b840cd7..d5dbf55 100644
--- a/crates/app/src/editor.rs
+++ b/crates/app/src/editor.rs
@@ -562,6 +562,7 @@ struct Windows {
clip: bool,
between: bool,
import: bool,
+ palettes: bool,
about: bool,
export: bool,
report: bool,
@@ -659,6 +660,8 @@ pub(crate) struct Editor {
mirror_buffer: StrokeBuffer,
typing: BTreeMap<String, String>,
import_path: String,
+ palette_path: String,
+ swatch_picked: Option<usize>,
depth: depth::Parallax,
batch: usize,
pen_path: Option<PenPath>,
@@ -852,6 +855,8 @@ impl Editor {
mirror_buffer: StrokeBuffer::new(size.0, size.1),
typing: BTreeMap::new(),
import_path: String::new(),
+ palette_path: String::new(),
+ swatch_picked: None,
depth: depth::Parallax::default(),
batch: timeline::FILL,
pen_path: None,
@@ -4860,6 +4865,11 @@ impl Editor {
.labelled_by(label.id)
.hint("a name for the colour; agents can use it in place of the hex");
self.command_button(ui, Cmd::AddSwatch, Some("add colour"));
+ if self.can_run(Cmd::UpdateSwatch).is_none() {
+ self.command_button(ui, Cmd::UpdateSwatch, Some("update"));
+ }
+ self.command_button(ui, Cmd::AddRamp, Some("ramp"));
+ self.command_button(ui, Cmd::LoadPalette, Some("palettes"));
});
if !self.settings.recent.is_empty() {
ui.label("recent");
diff --git a/crates/app/src/editor/commands.rs b/crates/app/src/editor/commands.rs
index 722c1ea..809af94 100644
--- a/crates/app/src/editor/commands.rs
+++ b/crates/app/src/editor/commands.rs
@@ -162,6 +162,16 @@ impl Editor {
.view
.is_none()
.then(|| "the canvas is not shown yet: wait a moment".to_string()),
+ Cmd::UpdateSwatch => {
+ let picked = self.swatch_picked.and_then(|at| self.scene.bundle.doc.palette.get(at));
+ match picked {
+ None => Some("click a colour in the palette first, then change the colour".to_string()),
+ Some(swatch) if swatch.color.eq_ignore_ascii_case(&crate::color::hex(self.color)) => {
+ Some("the palette colour already is this colour: change the colour first".to_string())
+ }
+ Some(_) => editing,
+ }
+ }
Cmd::PixelGrid => (!self.scene.bundle.doc.pixel_art())
.then(|| "this drawing has no pixel layer: Layer > New pixel layer adds one".to_string()),
Cmd::Corner | Cmd::Smooth => direct
@@ -544,6 +554,43 @@ impl Editor {
Cmd::MakeMirror => self.wrap("mirror")?,
Cmd::Unwrap => self.unwrap()?,
Cmd::ImportPicture => self.windows.import = !self.windows.import,
+ Cmd::LoadPalette => self.windows.palettes = !self.windows.palettes,
+ Cmd::UpdateSwatch => {
+ if let Some(at) = self.swatch_picked {
+ let edit = PaletteEdit::Recolour {
+ key: at.to_string(),
+ color: crate::color::hex(self.color),
+ };
+ self.apply(vec![Op::Palette(edit)])?;
+ }
+ }
+ Cmd::AddRamp => {
+ let typed = self.swatch_name.trim().to_string();
+ let doc = &self.scene.bundle.doc;
+ let taken = |name: &str| {
+ doc.palette
+ .iter()
+ .any(|s| s.ramp == name || s.name.starts_with(&format!("{name}-")))
+ };
+ let name = match typed.is_empty() || taken(&typed) {
+ false => typed,
+ true => {
+ let stem = if typed.is_empty() { "ramp".to_string() } else { typed };
+ (2..)
+ .map(|n| format!("{stem} {n}"))
+ .chain(std::iter::once(stem.clone()))
+ .find(|n| !taken(n))
+ .unwrap_or(stem)
+ }
+ };
+ let swatches = klad_core::palettes::ramp_swatches(&name, &crate::color::hex(self.color), 5)?;
+ let keys = swatches.iter().map(|s| s.color.clone()).collect();
+ self.swatch_name.clear();
+ self.apply(vec![
+ Op::Palette(PaletteEdit::Load { swatches }),
+ Op::Palette(PaletteEdit::Ramp { name, keys }),
+ ])?;
+ }
Cmd::Parallax => {}
Cmd::Note => self.tool = Tool::Note,
Cmd::Smaller => self.size = (self.size / 1.25).max(0.5),
diff --git a/crates/app/src/editor/options.rs b/crates/app/src/editor/options.rs
index 71aed3c..637b1e4 100644
--- a/crates/app/src/editor/options.rs
+++ b/crates/app/src/editor/options.rs
@@ -1,6 +1,7 @@
use super::{Editor, Tool};
use crate::color;
use crate::commands::Cmd;
+use crate::messages::Tone;
use crate::theme::{self, Hint, icon};
use anyhow::{Result, anyhow};
use egui::{Color32, ColorImage, RichText, Sense, TextureHandle, TextureOptions, vec2};
@@ -547,6 +548,14 @@ impl Editor {
true => swatch.color.clone(),
false => format!("{} {}", swatch.name, swatch.color),
};
+ let name = match swatch.ramp.is_empty() {
+ true => name,
+ false => format!("{name} (ramp {})", swatch.ramp),
+ };
+ let edge = i > 0 && palette[i - 1].ramp != swatch.ramp;
+ if edge {
+ ui.add_space(6.0);
+ }
let response = color::swatch_with(
ui,
rgba,
@@ -580,7 +589,10 @@ impl Editor {
rest.remove(i);
edit = Some(PaletteEdit::Set { swatches: rest });
}
- false => picked = Some(rgba),
+ false => {
+ picked = Some(rgba);
+ self.swatch_picked = Some(i);
+ }
}
}
if response.secondary_clicked() {
@@ -606,8 +618,96 @@ impl Editor {
if let Some(rgba) = picked {
self.pick_new_colour(rgba);
}
+ if edit.is_some() {
+ self.swatch_picked = None;
+ }
edit
}
+
+ pub(super) fn palettes_window(&mut self, ctx: &egui::Context) {
+ if !self.windows.palettes {
+ return;
+ }
+ let mut open = true;
+ let mut load: Option<Vec<klad_core::doc::Swatch>> = None;
+ egui::Window::new("palettes")
+ .open(&mut open)
+ .resizable(false)
+ .show(ctx, |ui| {
+ ui.label("Add the colours of a palette to this drawing's palette:");
+ klad_core::palettes::SHIPPED.iter().for_each(|shipped| {
+ ui.horizontal(|ui| {
+ let by = match shipped.by.is_empty() {
+ true => String::new(),
+ false => format!(", by {}", shipped.by),
+ };
+ if ui
+ .add(egui::Button::new(shipped.title).min_size(vec2(130.0, theme::TARGET)))
+ .hint(format!("{} colours{by}", shipped.count()))
+ .clicked()
+ {
+ load = Some(shipped.swatches());
+ }
+ let swatches = shipped.swatches();
+ let side = (300.0 / swatches.len() as f32).clamp(4.0, 14.0);
+ let (rect, _) =
+ ui.allocate_exact_size(vec2(side * swatches.len() as f32, 14.0), Sense::hover());
+ swatches.iter().enumerate().for_each(|(i, swatch)| {
+ let [r, g, b, _] = color::rgba_of(&swatch.color).unwrap_or([0.0; 4]);
+ ui.painter().rect_filled(
+ egui::Rect::from_min_size(rect.min + vec2(i as f32 * side, 0.0), vec2(side, 14.0)),
+ 0.0,
+ Color32::from_rgb((r * 255.0) as u8, (g * 255.0) as u8, (b * 255.0) as u8),
+ );
+ });
+ });
+ });
+ ui.separator();
+ let label = ui.label("or a palette file");
+ ui.horizontal(|ui| {
+ ui.add(egui::TextEdit::singleline(&mut self.palette_path).desired_width(240.0))
+ .labelled_by(label.id)
+ .hint("a list of hex colours, one per line (.hex), or a GIMP palette (.gpl)");
+ if crate::picker::NATIVE
+ && ui.button("Choose").hint("pick the palette file").clicked()
+ && let Some(file) = crate::picker::choose_file(None, "Choose")
+ {
+ self.palette_path = file.display().to_string();
+ }
+ if ui
+ .button("load")
+ .hint("add the file's colours to the palette")
+ .clicked()
+ {
+ let path = self.palette_path.trim().to_string();
+ let read = std::fs::read_to_string(&path)
+ .map_err(|e| format!("could not read {path}: {}", crate::report::io_words(&e)))
+ .and_then(|text| klad_core::palettes::parse(&text).map_err(|e| format!("{path}: {e:#}")));
+ match read {
+ Ok(swatches) => load = Some(swatches),
+ Err(why) => self.say(Tone::Refused, why),
+ }
+ }
+ });
+ });
+ if let Some(swatches) = load {
+ let before = self.scene.bundle.doc.palette.len();
+ self.check(|e| e.apply(vec![Op::Palette(PaletteEdit::Load { swatches })]));
+ let added = self.scene.bundle.doc.palette.len() - before;
+ self.say(
+ Tone::Done,
+ match added {
+ 0 => "the palette already has all of these colours".to_string(),
+ 1 => "1 colour added to the palette".to_string(),
+ n => format!("{n} colours added to the palette"),
+ },
+ );
+ self.windows.palettes = false;
+ }
+ if !open {
+ self.windows.palettes = false;
+ }
+ }
}
#[cfg(test)]
diff --git a/crates/app/src/editor/panels.rs b/crates/app/src/editor/panels.rs
index 2b1bf99..53d88c5 100644
--- a/crates/app/src/editor/panels.rs
+++ b/crates/app/src/editor/panels.rs
@@ -144,6 +144,7 @@ impl Editor {
self.windows(&ctx);
self.first_steps_window(&ctx);
self.import_window(&ctx);
+ self.palettes_window(&ctx);
self.dropped_pictures(&ctx);
self.tend_thumbs(&ctx);
if let Some(path) = self.queued_activate.take() {
diff --git a/crates/app/src/editor/ui_tests.rs b/crates/app/src/editor/ui_tests.rs
index 5ba9504..7cb3f19 100644
--- a/crates/app/src/editor/ui_tests.rs
+++ b/crates/app/src/editor/ui_tests.rs
@@ -1626,6 +1626,101 @@ fn a_pixel_drawing_zooms_in_whole_steps_and_shows_its_grid_the_pointers_pixel_an
let _ = std::fs::remove_dir_all(&painting);
}
+#[test]
+fn a_clicked_palette_colour_is_updated_with_its_pixels_and_ramps_and_palettes_join_the_palette() {
+ let path = pixel_sample("palette-edit");
+ let mut h = harness(editor(&path), vec2(1440.0, 1060.0));
+ let hexes = |h: &Harness<'static, Editor>| -> Vec<String> {
+ h.state()
+ .scene
+ .bundle
+ .doc
+ .palette
+ .iter()
+ .map(|s| s.color.clone())
+ .collect()
+ };
+ assert_eq!(hexes(&h), ["#2b2d42", "#ef233c"]);
+ assert!(
+ h.state()
+ .can_run(Cmd::UpdateSwatch)
+ .is_some_and(|why| why.contains("click a colour in the palette first"))
+ );
+ let red = h.get_by_role_and_label(Role::Button, "#ef233c").rect();
+ h.hover_at(red.center());
+ h.run_steps(1);
+ h.drag_at(red.center());
+ h.run_steps(1);
+ h.drop_at(red.center());
+ h.run_steps(2);
+ assert_eq!(h.state().swatch_picked, Some(1));
+ assert!(
+ h.state()
+ .can_run(Cmd::UpdateSwatch)
+ .is_some_and(|why| why.contains("already is this colour"))
+ );
+ assert!(h.query_by_label_contains("update").is_none(), "nothing to update yet");
+ let teal = klad_core::color::parse_hex("#2a9d8f").unwrap();
+ h.state_mut().set_colour(teal);
+ h.run_steps(2);
+ h.state_mut().invoke(Cmd::UpdateSwatch).unwrap();
+ h.run_steps(3);
+ ready(&mut h);
+ assert_eq!(hexes(&h), ["#2b2d42", "#2a9d8f"]);
+ let marks = h.state().scene.active_marks().to_vec();
+ let centre = marks[1].as_fill().unwrap();
+ assert_eq!(
+ klad_core::color::to_hex(centre.color()),
+ "#2a9d8f",
+ "the pixel painted with it changed"
+ );
+ assert_eq!(klad_core::color::to_hex(marks[0].as_fill().unwrap().color()), "#2b2d42");
+ let raster = h.state().scene.active_raster().unwrap();
+ let tile = raster.at(0).unwrap();
+ let at = (5 * klad_brush::TILE + 5) * 4;
+ assert!(
+ (0..3).all(|i| (tile[at + i].to_f32() - teal[i]).abs() < 1e-3),
+ "and the canvas shows it"
+ );
+ h.state_mut().swatch_name = "sea".into();
+ h.state_mut().invoke(Cmd::AddRamp).unwrap();
+ h.run_steps(2);
+ let doc = h.state().scene.bundle.doc.clone();
+ let ramp: Vec<&str> = doc.ramp("sea").iter().map(|s| s.color.as_str()).collect();
+ assert_eq!(ramp.len(), 5);
+ assert_eq!(ramp[2], "#2a9d8f", "the colour itself is the middle of its ramp");
+ assert_eq!(
+ doc.palette.len(),
+ 6,
+ "the palette colour joined the ramp instead of being added twice"
+ );
+ h.state_mut().invoke(Cmd::LoadPalette).unwrap();
+ h.run_steps(2);
+ h.get_by_label("PICO-8").click();
+ h.run_steps(3);
+ assert_eq!(h.state().scene.bundle.doc.palette.len(), 22);
+ assert!(
+ !h.state().windows.palettes,
+ "the window closes once a palette is loaded"
+ );
+ let said = h.state().messages.latest().map(|m| m.text.clone()).unwrap_or_default();
+ assert!(said.contains("16 colours added"), "{said}");
+ let file = path.with_extension("hex");
+ std::fs::write(&file, "ff00ff\n00ffff\n000000\n").unwrap();
+ h.state_mut().invoke(Cmd::LoadPalette).unwrap();
+ h.state_mut().palette_path = file.display().to_string();
+ h.run_steps(2);
+ h.get_by_label("load").click();
+ h.run_steps(3);
+ assert_eq!(
+ h.state().scene.bundle.doc.palette.len(),
+ 24,
+ "two new colours: black is in the palette already"
+ );
+ let _ = std::fs::remove_file(&file);
+ let _ = std::fs::remove_dir_all(&path);
+}
+
#[test]
fn a_tap_that_wobbles_selects_and_a_drag_past_three_points_moves() {
let path = sample("tap");
diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs
index d29a8b0..6b84658 100644
--- a/crates/cli/src/main.rs
+++ b/crates/cli/src/main.rs
@@ -1616,8 +1616,8 @@ enum Command {
flags: EditFlags,
},
#[command(
- about = "The document palette: list, --add a colour (with --name), --rm a name, colour or index",
- long_about = "The document palette, kept in doc.json. Named colours can be used wherever a colour goes (--color skin).\n\n klad palette art.klad\n klad palette art.klad --add '#f0c8a0' --name skin\n klad palette art.klad --add '#d0a080' --name skin (changes skin)\n klad palette art.klad --rm skin\n\nAs ops: {\"op\":\"palette\",\"add\":\"#f0c8a0\",\"name\":\"skin\"}, {\"op\":\"palette\",\"rm\":\"skin\"}, {\"op\":\"palette\",\"set\":[{\"color\":\"#1b1b1b\",\"name\":\"ink\"}]}"
+ about = "The document palette: list it, --add or --rm a colour, --recolour one, --load a palette, or group colours in a --ramp",
+ long_about = "The document palette, kept in doc.json. Named colours can be used wherever a colour goes (--color skin). On pixel layers every mark is bound to the palette colour it was drawn with, so changing that colour here changes the marks.\n\n klad palette art.klad\n klad palette art.klad --add '#f0c8a0' --name skin\n klad palette art.klad --add '#d0a080' --name skin (changes skin)\n klad palette art.klad --recolour skin --to '#e8b796' (by name, colour, index or id)\n klad palette art.klad --rm skin\n klad palette art.klad --load pico-8 (a palette that comes with klad: klad palettes lists them)\n klad palette art.klad --load my.hex (a list of hex colours, one per line, or a GIMP .gpl palette)\n klad palette art.klad --ramp wood --base '#8b5a2b' --steps 5 (wood-1 to wood-5, dark and cool to light and warm)\n klad palette art.klad --ramp skin --of skin-dark,skin,skin-light (group colours it has, dark to light)\n\nA loaded colour the palette already holds is not added again. A ramp is a row of colours from dark to light, used to shade one material.\n\nAs ops: {\"op\":\"palette\",\"add\":\"#f0c8a0\",\"name\":\"skin\"}, {\"op\":\"palette\",\"rm\":\"skin\"}, {\"op\":\"palette\",\"recolour\":\"skin\",\"to\":\"#e8b796\"}, {\"op\":\"palette\",\"load\":\"pico-8\"}, {\"op\":\"palette\",\"ramp\":\"skin\",\"of\":[\"skin-dark\",\"skin\"]}, {\"op\":\"palette\",\"set\":[{\"color\":\"#1b1b1b\",\"name\":\"ink\"}]}"
)]
Palette {
bundle: PathBuf,
@@ -1627,9 +1627,57 @@ enum Command {
name: Option<String>,
#[arg(long, conflicts_with = "add")]
rm: Option<String>,
+ #[arg(
+ long,
+ alias = "recolor",
+ requires = "to",
+ conflicts_with_all = ["add", "rm"],
+ help = "Change one colour (a name, a colour, an index or an id) to --to; pixel marks drawn with it change too"
+ )]
+ recolour: Option<String>,
+ #[arg(long, requires = "recolour", help = "The new colour for --recolour")]
+ to: Option<String>,
+ #[arg(
+ long,
+ conflicts_with_all = ["add", "rm", "recolour"],
+ help = "Add the colours of a palette that comes with klad (klad palettes), or of a .hex or .gpl file"
+ )]
+ load: Option<String>,
+ #[arg(
+ long,
+ conflicts_with_all = ["add", "rm", "recolour", "load"],
+ help = "A ramp of that name: made from --base in --steps, or the palette's own colours listed in --of"
+ )]
+ ramp: Option<String>,
+ #[arg(
+ long,
+ requires = "ramp",
+ conflicts_with = "of",
+ help = "The middle colour of a new ramp"
+ )]
+ base: Option<String>,
+ #[arg(
+ long,
+ requires = "base",
+ default_value_t = 5,
+ help = "How many colours a new ramp has (2 to 16)"
+ )]
+ steps: usize,
+ #[arg(
+ long,
+ requires = "ramp",
+ value_delimiter = ',',
+ help = "The colours of the ramp, dark to light: names, colours, indexes or ids (empty: the ramp is dropped)"
+ )]
+ of: Option<Vec<String>>,
#[command(flatten)]
flags: EditFlags,
},
+ #[command(about = "The palettes that come with klad, to load with klad palette <bundle> --load <name>")]
+ Palettes {
+ #[arg(long)]
+ json: bool,
+ },
#[command(
about = "Export PNGs, sprite sheets, numbered frames or a Godot SpriteFrames and scene",
long_about = "Export a transparent PNG of the whole image or one layer or group, at a frame, at any scale from 1/16 to 8 (vectors stay sharp; paint layers are resampled). 8-bit PNGs are dithered from the 16-bit float pixels so gradients do not band; --depth 16 writes 16-bit PNGs. --background keeps the canvas background colour.\n\n klad export art.klad\n klad export art.klad --scale 2\n klad export art.klad --layer lines --scale 4 --depth 16 -o lines.png\n\nAnimations (each clip, or the whole timeline when there are no clips):\n\n klad export art.klad --sheet all [--scale 0.5] [--padding 2] [--max 4096]\n a PNG holding each distinct picture once, trimmed to its pixels (more pages, art-sheet-2.png ..., when it does not fit --max), plus art-sheet.json in Aseprite's array layout: one entry per exposure with its duration in ms, frameTags for clips\n klad export art.klad --sheet run one clip; --sheet 0-11 a range\n klad export art.klad --frames run numbered full-size PNGs, one per frame (run-0000.png ...) in art-run/\n klad export art.klad --godot ../game/art the sheet, art.tres (SpriteFrames: one animation per clip with its fps, loop and per-frame durations) and art.tscn (an AnimatedSprite2D placed so the timeline's origin sits on the node's position). The first folder given is kept in the document (export.godot); later exports and the editor's button write there, and Godot uids are kept so scenes using them keep working. --store replaces a kept folder."
@@ -3536,22 +3584,63 @@ fn run() -> Result<()> {
add,
name,
rm,
+ recolour,
+ to,
+ load,
+ ramp,
+ base,
+ steps,
+ of,
flags,
} => {
- let edit = match (add, rm) {
- (Some(color), _) => Some(PaletteEdit::Add {
+ let edit = match (add, rm, recolour, load, ramp) {
+ (Some(color), ..) => Some(PaletteEdit::Add {
color,
name: name.unwrap_or_default(),
index: None,
}),
- (_, Some(key)) => Some(PaletteEdit::Remove { key }),
+ (_, Some(key), ..) => Some(PaletteEdit::Remove { key }),
+ (_, _, Some(key), ..) => Some(PaletteEdit::Recolour {
+ key,
+ color: to.unwrap_or_default(),
+ }),
+ (_, _, _, Some(source), _) => Some(PaletteEdit::Load {
+ swatches: palette_source(&source)?,
+ }),
+ (_, _, _, _, Some(name)) => Some(match (base, of) {
+ (Some(base), _) => PaletteEdit::Load {
+ swatches: klad_core::palettes::ramp_swatches(&name, &base, steps)?,
+ },
+ (None, Some(keys)) => PaletteEdit::Ramp {
+ name,
+ keys: keys.into_iter().filter(|k| !k.trim().is_empty()).collect(),
+ },
+ (None, None) => {
+ return Err(anyhow!(
+ "--ramp needs --base '#rrggbb' to make its colours, or --of with the palette colours it groups"
+ ));
+ }
+ }),
+ _ => None,
+ };
+ let ramped = match &edit {
+ Some(PaletteEdit::Load { swatches }) => swatches.first().filter(|s| !s.ramp.is_empty()).map(|first| {
+ Op::Palette(PaletteEdit::Ramp {
+ name: first.ramp.clone(),
+ keys: swatches.iter().map(|s| s.color.clone()).collect(),
+ })
+ }),
_ => None,
};
match edit {
- Some(edit) => agent::edit(&bundle, &[Op::Palette(edit)], &output(&flags, 0))?,
+ Some(edit) => {
+ let ops: Vec<Op> = std::iter::once(Op::Palette(edit)).chain(ramped).collect();
+ agent::edit(&bundle, &ops, &output(&flags, 0))?
+ }
None => palette(&bundle, flags.json)?,
}
}
+ Command::Palettes { json } => palettes(json),
Command::Export {
bundle,
png: _,
@@ -4232,14 +4321,60 @@ fn palette(path: &Path, as_json: bool) -> Result<()> {
println!("the palette is empty: klad palette <bundle> --add '#rrggbb' --name <name>");
}
palette.iter().enumerate().for_each(|(i, s)| {
+ let ramp = match s.ramp.is_empty() {
+ true => String::new(),
+ false => format!(" ramp {}", s.ramp),
+ };
println!(
"{}",
- format!("{i:<3} {:<10} {:<8} {}", s.color, s.id, s.name).trim_end()
- )
+ format!("{i:<3} {:<10} {:<8} {}{ramp}", s.color, s.id, s.name).trim_end()
+ );
});
Ok(())
}
+fn palette_source(source: &str) -> Result<Vec<klad_core::doc::Swatch>> {
+ if let Some(shipped) = klad_core::palettes::shipped(source) {
+ return Ok(shipped.swatches());
+ }
+ let path = Path::new(source);
+ if !path.is_file() {
+ bail!(
+ "{source:?} is not a palette that comes with klad ({}) or a palette file (.hex or .gpl)",
+ klad_core::palettes::names()
+ );
+ }
+ let text = std::fs::read_to_string(path).with_context(|| format!("reading {source}"))?;
+ klad_core::palettes::parse(&text).with_context(|| format!("reading {source}"))
+}
+
+fn palettes(as_json: bool) {
+ use klad_core::palettes::SHIPPED;
+ if as_json {
+ let list: Vec<serde_json::Value> = SHIPPED
+ .iter()
+ .map(|p| {
+ serde_json::json!({
+ "name": p.id,
+ "title": p.title,
+ "by": p.by,
+ "colors": p.swatches().iter().map(|s| s.color.clone()).collect::<Vec<_>>(),
+ })
+ })
+ .collect();
+ println!("{}", serde_json::Value::Array(list));
+ return;
+ }
+ SHIPPED.iter().for_each(|p| {
+ let by = match p.by.is_empty() {
+ true => String::new(),
+ false => format!(", by {}", p.by),
+ };
+ println!("{:<16} {:>2} colours {}{by}", p.id, p.count(), p.title);
+ });
+ println!("load one with: klad palette <bundle> --load <name>");
+}
+
const REFERENCE_HEAD: &str = "_Last updated: with the commands it lists. `just reference` writes it from `klad reference`; `cargo test -p klad-cli` fails when it is out of date._
# klad command reference
diff --git a/crates/cli/tests/binary.rs b/crates/cli/tests/binary.rs
index 3a6fb4d..3b470a4 100644
--- a/crates/cli/tests/binary.rs
+++ b/crates/cli/tests/binary.rs
@@ -600,6 +600,62 @@ fn a_pixel_drawing_is_made_drawn_listed_and_edited_from_the_command_line() {
std::fs::remove_dir_all(&dir).unwrap();
}
+#[test]
+fn the_palette_recolours_its_pixels_loads_palettes_and_groups_ramps_from_the_command_line() {
+ let dir = std::env::temp_dir().join(format!("draw-binary-palette-{}", 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", "8"]);
+ draw(&["palette", path, "--add", "#f0c8a0", "--name", "skin"]);
+ draw(&["pixel", path, "l1", "--color", "skin", "--cells", "1-3,1-3"]);
+ draw(&["palette", path, "--recolour", "skin", "--to", "#e8b796"]);
+ let marks = json(&["strokes", path, "l1", "--json"]);
+ assert_eq!(
+ marks["fills"][0]["color"], "#e8b796ff",
+ "the pixels follow their palette colour"
+ );
+ draw(&["palette", path, "--ramp", "skin", "--base", "#e8b796", "--steps", "3"]);
+ let palette = json(&["palette", path, "--json"]);
+ let ramp: Vec<(&str, &str)> = palette
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|s| (s["name"].as_str().unwrap_or(""), s["ramp"].as_str().unwrap_or("")))
+ .collect();
+ assert_eq!(
+ ramp,
+ [("skin-1", "skin"), ("skin", "skin"), ("skin-3", "skin")],
+ "the colour the palette has takes its place in the middle of its ramp"
+ );
+ assert!(draw(&["palettes"]).contains("pico-8"));
+ assert_eq!(json(&["palettes", "--json"])[2]["colors"].as_array().unwrap().len(), 16);
+ draw(&["palette", path, "--load", "gameboy"]);
+ let file = dir.join("mine.hex");
+ std::fs::write(&file, "081820\nabcdef\n").unwrap();
+ draw(&["palette", path, "--load", file.to_str().unwrap()]);
+ assert_eq!(
+ json(&["palette", path, "--json"]).as_array().unwrap().len(),
+ 8,
+ "three of the ramp, four of the game boy, one new from the file"
+ );
+ draw(&["palette", path, "--ramp", "greens", "--of", "#081820,#346856,#88c070"]);
+ assert!(draw(&["palette", path]).contains("ramp greens"));
+ let refused = run(&["palette", path, "--load", "nope"]);
+ assert!(String::from_utf8_lossy(&refused.stderr).contains("comes with klad"));
+ let lonely = run(&["palette", path, "--ramp", "x"]);
+ assert!(String::from_utf8_lossy(&lonely.stderr).contains("--base"));
+ 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 b46f1ca..695d53f 100644
--- a/crates/core/src/bundle.rs
+++ b/crates/core/src/bundle.rs
@@ -1581,4 +1581,150 @@ mod tests {
assert!(Bundle::open(&dir).unwrap().doc.find_layer("more").unwrap().pixel());
fs::remove_dir_all(&dir).unwrap();
}
+
+ #[test]
+ fn a_swatch_change_recolours_the_marks_bound_to_it_and_ramps_and_loads_shape_the_palette() {
+ use crate::ops::parse_lines;
+ let dir = scratch("palette");
+ let mut bundle = Bundle::blank(
+ &dir,
+ &Blank {
+ width: 16,
+ height: 16,
+ pixel: true,
+ frames: 2,
+ ..Blank::default()
+ },
+ "cli",
+ )
+ .unwrap();
+ let layer = bundle.doc.layers[0].id.clone();
+ let first = bundle.doc.layers[0].cels()[0].id.clone();
+ let run = |bundle: &mut Bundle, lines: &str| bundle.apply(&parse_lines(lines).unwrap()).unwrap();
+ run(
+ &mut bundle,
+ &format!(
+ "{}\n{}\n{}\n{}\n{}",
+ r##"{"op":"palette","add":"#f0c8a0","name":"skin"}"##,
+ r##"{"op":"palette","add":"#2b2d42","name":"ink"}"##,
+ format_args!(r##"{{"op":"pixel","layer":"{layer}","color":"skin","cells":[[1,1],[2,1]]}}"##),
+ format_args!(r##"{{"op":"pixel","layer":"{layer}","color":"ink","cells":[[3,3]]}}"##),
+ format_args!(r##"{{"op":"add","cel":{{"frame":1}},"in":"{layer}"}}"##),
+ ),
+ );
+ run(
+ &mut bundle,
+ &format!(r##"{{"op":"pixel","layer":"{layer}","frame":1,"color":"skin","cells":[[5,5]]}}"##),
+ );
+ let second = bundle.doc.layers[0].cels()[1].id.clone();
+ let colours = |bundle: &Bundle, cel: &str| -> Vec<(String, Option<String>)> {
+ crate::stroke::fills_of(&bundle.read_marks(&layer, cel).unwrap())
+ .map(|f| (crate::color::to_hex(f.color()), f.entry().map(String::from)))
+ .collect()
+ };
+ let skin = bundle.doc.palette[0].id.clone();
+ let ink = bundle.doc.palette[1].id.clone();
+ run(&mut bundle, r##"{"op":"palette","recolour":"skin","to":"#e8b796"}"##);
+ assert_eq!(
+ colours(&bundle, &first),
+ [
+ ("#e8b796".to_string(), Some(skin.clone())),
+ ("#2b2d42".to_string(), Some(ink.clone()))
+ ],
+ "the marks of the changed swatch follow it, the others stay"
+ );
+ assert_eq!(
+ colours(&bundle, &second),
+ [("#e8b796".to_string(), Some(skin.clone()))],
+ "on every drawing"
+ );
+ crate::history::step(&mut bundle, crate::history::Stack::Undo).unwrap();
+ assert_eq!(
+ colours(&bundle, &second),
+ [("#f0c8a0".to_string(), Some(skin.clone()))],
+ "and undo brings it back"
+ );
+ assert_eq!(bundle.doc.palette[0].color, "#f0c8a0");
+ run(&mut bundle, r##"{"op":"palette","add":"#ffd9b3","name":"skin"}"##);
+ assert_eq!(
+ colours(&bundle, &first)[0].0,
+ "#ffd9b3",
+ "adding a name again changes its colour, and its marks"
+ );
+ run(
+ &mut bundle,
+ r##"{"op":"palette","set":[{"color":"#101020","name":"ink"},{"color":"#ffd9b3","name":"skin"}]}"##,
+ );
+ let ids: Vec<&str> = bundle.doc.palette.iter().map(|s| s.id.as_str()).collect();
+ assert_eq!(
+ ids,
+ [ink.as_str(), skin.as_str()],
+ "a rewritten palette keeps the ids by name"
+ );
+ assert_eq!(colours(&bundle, &first)[1], ("#101020".to_string(), Some(ink.clone())));
+ run(&mut bundle, r##"{"op":"palette","rm":"ink"}"##);
+ assert_eq!(
+ colours(&bundle, &first)[1],
+ ("#101020".to_string(), None),
+ "a mark whose swatch is removed keeps its colour and is bound to nothing"
+ );
+ run(&mut bundle, r##"{"op":"palette","load":"pico-8"}"##);
+ assert_eq!(bundle.doc.palette.len(), 17);
+ run(&mut bundle, r##"{"op":"palette","load":"pico-8"}"##);
+ assert_eq!(
+ bundle.doc.palette.len(),
+ 17,
+ "colours the palette holds are not loaded twice"
+ );
+ run(
+ &mut bundle,
+ r##"{"op":"palette","load":[{"color":"#123456","name":"skin"},{"color":"#abcdef","name":"sky","ramp":"blues"}]}"##,
+ );
+ let last: Vec<(&str, &str, &str)> = bundle.doc.palette[17..]
+ .iter()
+ .map(|s| (s.color.as_str(), s.name.as_str(), s.ramp.as_str()))
+ .collect();
+ assert_eq!(
+ last,
+ [("#123456", "", ""), ("#abcdef", "sky", "blues")],
+ "a name already taken is dropped"
+ );
+ run(
+ &mut bundle,
+ r##"{"op":"palette","ramp":"reds","of":["#ff004d","#7e2553","#ab5236"]}"##,
+ );
+ let reds: Vec<&str> = bundle.doc.ramp("reds").iter().map(|s| s.color.as_str()).collect();
+ assert_eq!(
+ reds,
+ ["#ff004d", "#7e2553", "#ab5236"],
+ "a ramp keeps the order it is given"
+ );
+ let at = bundle.doc.swatch("#ff004d").unwrap();
+ assert_eq!(
+ bundle.doc.palette[at..at + 3]
+ .iter()
+ .map(|s| s.ramp.as_str())
+ .collect::<Vec<_>>(),
+ ["reds", "reds", "reds"],
+ "and its colours sit side by side"
+ );
+ run(&mut bundle, r##"{"op":"palette","ramp":"reds","of":[]}"##);
+ assert!(bundle.doc.ramp("reds").is_empty());
+ let refuse = |line: &str| {
+ format!(
+ "{:#}",
+ crate::ops::apply_all(&bundle.doc, &parse_lines(line).unwrap()).unwrap_err()
+ )
+ };
+ assert!(format!("{:#}", parse_lines(r##"{"op":"palette","load":"nes"}"##).unwrap_err()).contains("comes with"));
+ assert!(refuse(r##"{"op":"palette","recolour":"teal","to":"#000000"}"##).contains("teal"));
+ assert!(
+ format!(
+ "{:#}",
+ parse_lines(r##"{"op":"palette","recolour":"skin"}"##).unwrap_err()
+ )
+ .contains("\"to\"")
+ );
+ fs::remove_dir_all(&dir).unwrap();
+ }
}
diff --git a/crates/core/src/doc.rs b/crates/core/src/doc.rs
index 988899f..ac0445d 100644
--- a/crates/core/src/doc.rs
+++ b/crates/core/src/doc.rs
@@ -78,6 +78,8 @@ pub struct Swatch {
pub name: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub id: String,
+ #[serde(default, skip_serializing_if = "String::is_empty")]
+ pub ramp: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -1232,6 +1234,14 @@ impl Document {
.position(|s| key.starts_with('#') && s.color.eq_ignore_ascii_case(key))
})
.or_else(|| key.parse::<usize>().ok().filter(|i| *i < self.palette.len()))
+ .or_else(|| self.palette.iter().position(|s| !s.id.is_empty() && s.id == key))
+ }
+
+ pub fn ramp(&self, name: &str) -> Vec<&Swatch> {
+ self.palette
+ .iter()
+ .filter(|s| !s.ramp.is_empty() && s.ramp == name)
+ .collect()
}
pub fn entry(&self, id: &str) -> Option<&Swatch> {
@@ -1248,6 +1258,7 @@ impl Document {
color: key.to_string(),
name: String::new(),
id: String::new(),
+ ramp: String::new(),
});
self.palette.len() - 1
}
@@ -1327,6 +1338,9 @@ impl Document {
if swatch.name.starts_with('#') {
bail!("palette name {} cannot start with #", swatch.name);
}
+ if swatch.ramp.starts_with('#') {
+ bail!("ramp name {} cannot start with #", swatch.ramp);
+ }
if !swatch.name.is_empty() && !swatch_names.insert(&swatch.name) {
bail!("palette name {} is used twice", swatch.name);
}
@@ -1565,11 +1579,13 @@ mod tests {
color: "#1b1b1b".into(),
name: "ink".into(),
id: String::new(),
+ ramp: String::new(),
},
Swatch {
color: "#F4EFE6".into(),
name: String::new(),
id: String::new(),
+ ramp: String::new(),
},
];
doc.next_id = 10;
diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs
index e2eac2b..1681c5c 100644
--- a/crates/core/src/lib.rs
+++ b/crates/core/src/lib.rs
@@ -15,6 +15,7 @@ pub mod markedit;
pub mod migrate;
pub mod notes;
pub mod ops;
+pub mod palettes;
pub mod patch;
pub mod path;
pub mod pathedit;
diff --git a/crates/core/src/markedit.rs b/crates/core/src/markedit.rs
index c703b76..19833a1 100644
--- a/crates/core/src/markedit.rs
+++ b/crates/core/src/markedit.rs
@@ -149,6 +149,11 @@ pub enum MarkChange {
Detach {
ids: Vec<u32>,
},
+ Entry {
+ entry: String,
+ color: Option<[u16; 4]>,
+ changed: Vec<u32>,
+ },
}
#[derive(Clone, Debug, PartialEq)]
@@ -176,6 +181,7 @@ impl MarkChange {
MarkChange::Paste { made, .. } => made.iter().map(|c| c.to).collect(),
MarkChange::Put(marks) => marks.iter().map(Mark::id).collect(),
MarkChange::Detach { ids } => ids.clone(),
+ MarkChange::Entry { changed, .. } => changed.clone(),
MarkChange::Copy { .. } | MarkChange::Part { .. } => Vec::new(),
}
}
@@ -747,6 +753,26 @@ pub fn apply_following(marks: &mut Vec<Mark>, change: &mut MarkChange, cel: &str
ids.iter().try_for_each(|id| position(marks, cel, *id).map(|_| ()))?;
attach::detach(marks, ids);
}
+ MarkChange::Entry { entry, color, changed } => {
+ *changed = marks
+ .iter_mut()
+ .filter_map(|m| match m {
+ Mark::Fill(f) if f.entry() == Some(entry.as_str()) => Some(f),
+ _ => None,
+ })
+ .map(|f| {
+ match color {
+ Some(c) => f.color = *c,
+ None => {
+ if let FillSource::Cells { entry, .. } = &mut f.source {
+ entry.clear();
+ }
+ }
+ }
+ f.id
+ })
+ .collect();
+ }
}
Ok(alone)
}
diff --git a/crates/core/src/ops.rs b/crates/core/src/ops.rs
index aa8bb96..f990279 100644
--- a/crates/core/src/ops.rs
+++ b/crates/core/src/ops.rs
@@ -265,6 +265,17 @@ pub enum PaletteEdit {
Set {
swatches: Vec<Swatch>,
},
+ Recolour {
+ key: String,
+ color: String,
+ },
+ Load {
+ swatches: Vec<Swatch>,
+ },
+ Ramp {
+ name: String,
+ keys: Vec<String>,
+ },
}
#[derive(Clone, Debug, PartialEq, Deserialize)]
@@ -2749,7 +2760,50 @@ fn parse_palette(map: &mut Map<String, Value>) -> Result<PaletteEdit> {
.context("palette set takes a list like [{\"color\":\"#1b1b1b\",\"name\":\"ink\"}]")?;
return Ok(PaletteEdit::Set { swatches });
}
- bail!("palette needs \"add\" (with \"name\"), \"rm\" or \"set\"")
+ if let Some(key) = map.remove("recolour").or_else(|| map.remove("recolor")) {
+ let key = match key {
+ Value::String(s) => s,
+ Value::Number(n) => n.to_string(),
+ other => bail!("palette recolour takes a name, a colour, an index or an id, not {other}"),
+ };
+ let color = take_str(map, "to")?
+ .ok_or_else(|| anyhow!("palette recolour needs \"to\": the new colour, #rrggbb or #rrggbbaa"))?;
+ return Ok(PaletteEdit::Recolour { key, color });
+ }
+ if let Some(load) = map.remove("load") {
+ let swatches = match load {
+ Value::String(name) => crate::palettes::shipped(&name)
+ .ok_or_else(|| {
+ anyhow!(
+ "klad has no palette {name:?}: it comes with {}",
+ crate::palettes::names()
+ )
+ })?
+ .swatches(),
+ list => serde_json::from_value(list).context(
+ "palette load takes the name of a palette that comes with klad, or a list like [{\"color\":\"#1b1b1b\"}]",
+ )?,
+ };
+ return Ok(PaletteEdit::Load { swatches });
+ }
+ if let Some(name) = take_str(map, "ramp")? {
+ let keys = match map.remove("of") {
+ None | Some(Value::Null) => Vec::new(),
+ Some(Value::Array(items)) => items
+ .into_iter()
+ .map(|v| match v {
+ Value::String(s) => Ok(s),
+ Value::Number(n) => Ok(n.to_string()),
+ other => bail!("a ramp lists palette names, colours, indexes or ids, not {other}"),
+ })
+ .collect::<Result<_>>()?,
+ Some(other) => bail!("\"of\" is the list of the ramp's colours, dark to light, not {other}"),
+ };
+ return Ok(PaletteEdit::Ramp { name, keys });
+ }
+ bail!(
+ "palette needs \"add\" (with \"name\"), \"rm\", \"set\", \"recolour\" (with \"to\"), \"load\" or \"ramp\" (with \"of\")"
+ )
}
fn edit_palette(doc: &mut Document, edit: &PaletteEdit) -> Result<()> {
@@ -2778,6 +2832,7 @@ fn edit_palette(doc: &mut Document, edit: &PaletteEdit) -> Result<()> {
color: color.clone(),
name: name.clone(),
id: String::new(),
+ ramp: String::new(),
},
);
}
@@ -2787,8 +2842,138 @@ fn edit_palette(doc: &mut Document, edit: &PaletteEdit) -> Result<()> {
.ok_or_else(|| anyhow!("the palette has no {key:?} (give a name, a colour or an index)"))?;
doc.palette.remove(at);
}
- PaletteEdit::Set { swatches } => doc.palette = swatches.clone(),
+ PaletteEdit::Set { swatches } => doc.palette = carry_ids(&doc.palette, swatches),
+ PaletteEdit::Recolour { key, color } => {
+ parse_hex(color)?;
+ let at = doc
+ .swatch(key)
+ .ok_or_else(|| anyhow!("the palette has no {key:?} (give a name, a colour, an index or an id)"))?;
+ doc.palette[at].color = color.clone();
+ }
+ PaletteEdit::Load { swatches } => {
+ swatches.iter().try_for_each(|swatch| {
+ parse_hex(&swatch.color)?;
+ let held = doc.palette.iter().any(|s| s.color.eq_ignore_ascii_case(&swatch.color));
+ let named = !swatch.name.is_empty() && doc.palette.iter().any(|s| s.name == swatch.name);
+ if !held {
+ doc.palette.push(Swatch {
+ color: swatch.color.clone(),
+ name: match named {
+ true => String::new(),
+ false => swatch.name.clone(),
+ },
+ id: String::new(),
+ ramp: swatch.ramp.clone(),
+ });
+ }
+ Ok::<_, anyhow::Error>(())
+ })?;
+ }
+ PaletteEdit::Ramp { name, keys } => {
+ let name = name.trim();
+ if name.is_empty() || name.starts_with('#') {
+ bail!("a ramp needs a name that does not start with #");
+ }
+ let places = keys
+ .iter()
+ .map(|key| {
+ doc.swatch(key)
+ .ok_or_else(|| anyhow!("the palette has no {key:?} (give a name, a colour, an index or an id)"))
+ })
+ .collect::<Result<Vec<usize>>>()?;
+ doc.palette
+ .iter_mut()
+ .filter(|s| s.ramp == name)
+ .for_each(|s| s.ramp.clear());
+ let Some(&first) = places.iter().min() else {
+ return Ok(());
+ };
+ let chosen: Vec<Swatch> = places
+ .iter()
+ .map(|&at| Swatch {
+ ramp: name.to_string(),
+ ..doc.palette[at].clone()
+ })
+ .collect();
+ let before = places.iter().filter(|&&at| at < first).count();
+ let mut rest: Vec<Swatch> = doc
+ .palette
+ .iter()
+ .enumerate()
+ .filter(|(at, _)| !places.contains(at))
+ .map(|(_, s)| s.clone())
+ .collect();
+ let at = (first - before).min(rest.len());
+ rest.splice(at..at, chosen);
+ doc.palette = rest;
+ }
+ }
+ Ok(())
+}
+
+fn carry_ids(old: &[Swatch], new: &[Swatch]) -> Vec<Swatch> {
+ let mut free: Vec<&Swatch> = old.iter().filter(|s| !s.id.is_empty()).collect();
+ free.retain(|s| !new.iter().any(|n| n.id == s.id));
+ new.iter()
+ .map(|swatch| {
+ if !swatch.id.is_empty() {
+ return swatch.clone();
+ }
+ let found = free
+ .iter()
+ .position(|s| !swatch.name.is_empty() && s.name == swatch.name)
+ .or_else(|| {
+ free.iter().position(|s| {
+ s.name.is_empty() == swatch.name.is_empty() && s.color.eq_ignore_ascii_case(&swatch.color)
+ })
+ });
+ match found {
+ Some(at) => Swatch {
+ id: free.remove(at).id.clone(),
+ ..swatch.clone()
+ },
+ None => swatch.clone(),
+ }
+ })
+ .collect()
+}
+
+fn follow_palette(doc: &Document, before: &[Swatch], out: &mut Applied) -> Result<()> {
+ let changes: Vec<MarkChange> = before
+ .iter()
+ .filter(|old| !old.id.is_empty())
+ .filter_map(|old| match doc.entry(&old.id) {
+ Some(now) if now.color.eq_ignore_ascii_case(&old.color) => None,
+ Some(now) => Some(parse_hex(&now.color).map(|c| MarkChange::Entry {
+ entry: old.id.clone(),
+ color: Some(crate::color::to_u16(c)),
+ changed: Vec::new(),
+ })),
+ None => Some(Ok(MarkChange::Entry {
+ entry: old.id.clone(),
+ color: None,
+ changed: Vec::new(),
+ })),
+ })
+ .collect::<Result<_>>()?;
+ if changes.is_empty() {
+ return Ok(());
}
+ doc.all_layers()
+ .into_iter()
+ .filter(|layer| layer.pixel())
+ .flat_map(|layer| {
+ layer
+ .cels()
+ .iter()
+ .filter(|c| c.link.is_none())
+ .map(move |c| (layer, c))
+ })
+ .for_each(|(layer, cel)| {
+ changes
+ .iter()
+ .for_each(|change| out.push(&layer.id, &cel.id, change.clone()));
+ });
Ok(())
}
@@ -3648,7 +3833,9 @@ pub fn apply(doc: &mut Document, op: &Op, out: &mut Applied) -> Result<()> {
out.changed.push(id.clone());
}
Op::Palette(edit) => {
+ let before = doc.palette.clone();
edit_palette(doc, edit)?;
+ follow_palette(doc, &before, out)?;
if !out.changed.iter().any(|c| c == "palette") {
out.changed.push("palette".into());
}
diff --git a/crates/core/src/palettes.rs b/crates/core/src/palettes.rs
new file mode 100644
index 0000000..7fd8379
--- /dev/null
+++ b/crates/core/src/palettes.rs
@@ -0,0 +1,279 @@
+use crate::color::{Rgba, parse_hex, to_hex, value_step};
+use crate::doc::Swatch;
+use anyhow::{Result, anyhow, bail};
+
+pub struct Shipped {
+ pub id: &'static str,
+ pub title: &'static str,
+ pub by: &'static str,
+ pub colors: &'static str,
+}
+
+pub const SHIPPED: [Shipped; 9] = [
+ Shipped {
+ id: "1-bit",
+ title: "1-bit",
+ by: "",
+ colors: "000000 ffffff",
+ },
+ Shipped {
+ id: "gameboy",
+ title: "Game Boy (bgb)",
+ by: "",
+ colors: "081820 346856 88c070 e0f8d0",
+ },
+ Shipped {
+ id: "pico-8",
+ title: "PICO-8",
+ by: "Lexaloffle Games",
+ colors: "000000 1d2b53 7e2553 008751 ab5236 5f574f c2c3c7 fff1e8 ff004d ffa300 ffec27 00e436 29adff 83769c ff77a8 ffccaa",
+ },
+ Shipped {
+ id: "sweetie-16",
+ title: "Sweetie 16",
+ by: "GrafxKid",
+ colors: "1a1c2c 5d275d b13e53 ef7d57 ffcd75 a7f070 38b764 257179 29366f 3b5dc9 41a6f6 73eff7 f4f4f4 94b0c2 566c86 333c57",
+ },
+ Shipped {
+ id: "dawnbringer-16",
+ title: "DawnBringer 16",
+ by: "DawnBringer",
+ colors: "140c1c 442434 30346d 4e4a4e 854c30 346524 d04648 757161 597dce d27d2c 8595a1 6daa2c d2aa99 6dc2ca dad45e deeed6",
+ },
+ Shipped {
+ id: "dawnbringer-32",
+ title: "DawnBringer 32",
+ by: "DawnBringer",
+ colors: "000000 222034 45283c 663931 8f563b df7126 d9a066 eec39a fbf236 99e550 6abe30 37946e 4b692f 524b24 323c39 3f3f74 306082 5b6ee1 639bff 5fcde4 cbdbfc ffffff 9badb7 847e87 696a6a 595652 76428a ac3232 d95763 d77bba 8f974a 8a6f30",
+ },
+ Shipped {
+ id: "endesga-32",
+ title: "Endesga 32",
+ by: "ENDESGA",
+ colors: "be4a2f d77643 ead4aa e4a672 b86f50 733e39 3e2731 a22633 e43b44 f77622 feae34 fee761 63c74d 3e8948 265c42 193c3e 124e89 0099db 2ce8f5 ffffff c0cbdc 8b9bb4 5a6988 3a4466 262b44 181425 ff0044 68386c b55088 f6757a e8b796 c28569",
+ },
+ Shipped {
+ id: "resurrect-64",
+ title: "Resurrect 64",
+ by: "Kerrie Lake",
+ colors: "2e222f 3e3546 625565 966c6c ab947a 694f62 7f708a 9babb2 c7dcd0 ffffff 6e2727 b33831 ea4f36 f57d4a ae2334 e83b3b fb6b1d f79617 f9c22b 7a3045 9e4539 cd683d e6904e fbb954 4c3e24 676633 a2a947 d5e04b fbff86 165a4c 239063 1ebc73 91db69 cddf6c 313638 374e4a 547e64 92a984 b2ba90 0b5e65 0b8a8f 0eaf9b 30e1b9 8ff8e2 323353 484a77 4d65b4 4d9be6 8fd3ff 45293f 6b3e75 905ea9 a884f3 eaaded 753c54 a24b6f cf657f ed8099 831c5d c32454 f04f78 f68181 fca790 fdcbb0",
+ },
+ Shipped {
+ id: "aap-64",
+ title: "AAP-64",
+ by: "Adigun A. Polack",
+ colors: "060608 141013 3b1725 73172d b4202a df3e23 fa6a0a f9a31b ffd541 fffc40 d6f264 9cdb43 59c135 14a02e 1a7a3e 24523b 122020 143464 285cc4 249fde 20d6c7 a6fcdb ffffff fef3c0 fad6b8 f5a097 e86a73 bc4a9b 793a80 403353 242234 221c1a 322b28 71413b bb7547 dba463 f4d29c dae0ea b3b9d1 8b93af 6d758d 4a5462 333941 422433 5b3138 8e5252 ba756a e9b5a3 e3e6ff b9bffb 849be4 588dbe 477d85 23674e 328464 5daf8d 92dcba cdf7e2 e4d2aa c7b08b a08662 796755 5a4e44 423934",
+ },
+];
+
+fn plain(color: String, name: String) -> Swatch {
+ Swatch {
+ color,
+ name,
+ id: String::new(),
+ ramp: String::new(),
+ }
+}
+
+impl Shipped {
+ pub fn swatches(&self) -> Vec<Swatch> {
+ self.colors
+ .split_whitespace()
+ .map(|hex| plain(format!("#{hex}"), String::new()))
+ .collect()
+ }
+
+ pub fn count(&self) -> usize {
+ self.colors.split_whitespace().count()
+ }
+}
+
+pub fn shipped(id: &str) -> Option<&'static Shipped> {
+ let wanted = id.trim().to_ascii_lowercase();
+ SHIPPED.iter().find(|p| p.id == wanted)
+}
+
+pub fn names() -> String {
+ SHIPPED.iter().map(|p| p.id).collect::<Vec<_>>().join(", ")
+}
+
+fn hex_line(line: &str) -> Option<String> {
+ let digits = line.trim().trim_start_matches('#');
+ let valid = matches!(digits.len(), 6 | 8) && digits.chars().all(|c| c.is_ascii_hexdigit());
+ valid.then(|| format!("#{}", digits.to_ascii_lowercase()))
+}
+
+fn gimp(text: &str) -> Result<Vec<Swatch>> {
+ text.lines()
+ .skip(1)
+ .map(str::trim)
+ .filter(|line| !line.is_empty() && !line.starts_with('#'))
+ .filter(|line| !line.contains(':') || line.chars().next().is_some_and(|c| c.is_ascii_digit()))
+ .map(|line| {
+ let mut parts = line.split_whitespace();
+ let mut channel = || -> Option<u8> { parts.next()?.parse::<u8>().ok() };
+ let (Some(r), Some(g), Some(b)) = (channel(), channel(), channel()) else {
+ bail!(
+ "{line:?} is not a line of a GIMP palette: it should start with red, green and blue from 0 to 255"
+ );
+ };
+ let name = parts.collect::<Vec<_>>().join(" ");
+ let name = match name.as_str() {
+ "Untitled" | "untitled" => String::new(),
+ other => other.trim_start_matches('#').to_string(),
+ };
+ Ok(plain(format!("#{r:02x}{g:02x}{b:02x}"), name))
+ })
+ .collect()
+}
+
+pub fn parse(text: &str) -> Result<Vec<Swatch>> {
+ let first = text
+ .lines()
+ .map(str::trim)
+ .find(|line| !line.is_empty())
+ .unwrap_or_default();
+ let swatches = match first.starts_with("GIMP Palette") {
+ true => gimp(text)?,
+ false => text
+ .lines()
+ .map(str::trim)
+ .filter(|line| !line.is_empty() && !line.starts_with(';') && !line.starts_with("//"))
+ .map(|line| {
+ hex_line(line).map(|hex| plain(hex, String::new())).ok_or_else(|| {
+ anyhow!(
+ "{line:?} is not a colour: a palette file is a list of hex colours, one per line (.hex), or a GIMP palette (.gpl)"
+ )
+ })
+ })
+ .collect::<Result<Vec<_>>>()?,
+ };
+ if swatches.is_empty() {
+ bail!("the palette file holds no colours");
+ }
+ Ok(unnamed_twice(swatches))
+}
+
+fn unnamed_twice(swatches: Vec<Swatch>) -> Vec<Swatch> {
+ let mut seen = std::collections::BTreeSet::new();
+ swatches
+ .into_iter()
+ .map(|s| match s.name.is_empty() || seen.insert(s.name.clone()) {
+ true => s,
+ false => Swatch {
+ name: String::new(),
+ ..s
+ },
+ })
+ .collect()
+}
+
+pub const RAMP_STEP: f32 = 0.09;
+
+pub fn ramp(base: Rgba, steps: usize) -> Vec<Rgba> {
+ let steps = steps.clamp(2, 16);
+ let middle = (steps - 1) as f32 / 2.0;
+ (0..steps)
+ .map(|i| value_step(base, (i as f32 - middle) * RAMP_STEP).map(|v| v.clamp(0.0, 1.0)))
+ .map(|c| [c[0], c[1], c[2], base[3]])
+ .collect()
+}
+
+pub fn ramp_swatches(name: &str, base: &str, steps: usize) -> Result<Vec<Swatch>> {
+ let name = name.trim();
+ if name.is_empty() || name.starts_with('#') {
+ bail!("a ramp needs a name that does not start with #");
+ }
+ let colours = ramp(parse_hex(base)?, steps);
+ Ok(colours
+ .iter()
+ .enumerate()
+ .map(|(i, c)| Swatch {
+ color: to_hex(*c),
+ name: format!("{name}-{}", i + 1),
+ id: String::new(),
+ ramp: name.to_string(),
+ })
+ .collect())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::color::to_oklab;
+
+ #[test]
+ fn shipped_palettes_hold_valid_colours_and_are_found_by_name() {
+ let counts: Vec<(&str, usize)> = SHIPPED.iter().map(|p| (p.id, p.count())).collect();
+ assert_eq!(
+ counts,
+ [
+ ("1-bit", 2),
+ ("gameboy", 4),
+ ("pico-8", 16),
+ ("sweetie-16", 16),
+ ("dawnbringer-16", 16),
+ ("dawnbringer-32", 32),
+ ("endesga-32", 32),
+ ("resurrect-64", 64),
+ ("aap-64", 64),
+ ]
+ );
+ SHIPPED.iter().for_each(|p| {
+ let swatches = p.swatches();
+ swatches.iter().for_each(|s| {
+ parse_hex(&s.color).unwrap_or_else(|e| panic!("{} holds {}: {e}", p.id, s.color));
+ });
+ let distinct: std::collections::BTreeSet<&str> = swatches.iter().map(|s| s.color.as_str()).collect();
+ assert_eq!(distinct.len(), swatches.len(), "{} repeats a colour", p.id);
+ });
+ assert_eq!(shipped(" PICO-8 ").map(|p| p.title), Some("PICO-8"));
+ assert!(shipped("nes").is_none());
+ assert!(names().contains("endesga-32"));
+ }
+
+ #[test]
+ fn hex_lists_and_gimp_palettes_are_read() {
+ let hex = parse("1a1c2c\n#5D275D\n\n; a comment\nb13e53ff\n").unwrap();
+ let colours: Vec<&str> = hex.iter().map(|s| s.color.as_str()).collect();
+ assert_eq!(colours, ["#1a1c2c", "#5d275d", "#b13e53ff"]);
+ let gpl = parse(
+ "GIMP Palette\nName: Sprite\nColumns: 4\n#\n 26 28 44\tnight\n93 39 93 Untitled\n177 62 83\tnight\n255\t205\t117\n",
+ )
+ .unwrap();
+ let read: Vec<(&str, &str)> = gpl.iter().map(|s| (s.color.as_str(), s.name.as_str())).collect();
+ assert_eq!(
+ read,
+ [("#1a1c2c", "night"), ("#5d275d", ""), ("#b13e53", ""), ("#ffcd75", "")],
+ "a name used twice is kept once, so the palette stays valid"
+ );
+ assert!(parse("not a colour").unwrap_err().to_string().contains("one per line"));
+ assert!(
+ parse("GIMP Palette\n300 0 0\n")
+ .unwrap_err()
+ .to_string()
+ .contains("0 to 255")
+ );
+ assert!(parse("\n\n").is_err());
+ }
+
+ #[test]
+ fn a_ramp_runs_from_dark_and_cool_to_light_and_warm_through_its_base() {
+ let made = ramp_swatches("wood", "#8b5a2b", 5).unwrap();
+ let names: Vec<&str> = made.iter().map(|s| s.name.as_str()).collect();
+ assert_eq!(names, ["wood-1", "wood-2", "wood-3", "wood-4", "wood-5"]);
+ assert!(made.iter().all(|s| s.ramp == "wood"));
+ assert_eq!(made[2].color, "#8b5a2b", "the middle step is the base colour");
+ let labs: Vec<[f32; 3]> = made.iter().map(|s| to_oklab(parse_hex(&s.color).unwrap())).collect();
+ assert!(
+ labs.windows(2).all(|w| w[1][0] > w[0][0]),
+ "each step is lighter: {labs:?}"
+ );
+ assert!(
+ labs[4][2] > labs[0][2],
+ "and the light end is yellower than the dark end"
+ );
+ assert_eq!(ramp(parse_hex("#336699").unwrap(), 1).len(), 2);
+ assert!(ramp_swatches("#bad", "#336699", 3).is_err());
+ }
+}
diff --git a/docs/DESIGN.md b/docs/DESIGN.md
index c1c7a6d..b602aae 100644
--- a/docs/DESIGN.md
+++ b/docs/DESIGN.md
@@ -1,4 +1,4 @@
-_Last updated: 2026-11-11 15:40_
+_Last updated: 2026-11-11 17:20_
# klad: design
@@ -232,7 +232,7 @@ Unknown keys are errors that list the valid ones, so a typo never passes silentl
Every layer has `blend`, `opacity`, `visible`, `locked`, optional `mask`, `clip` and (M5, format 8) `effects`. Effects are layer settings, not a layer kind: the planned `filter` kind became them.
-- **Pixel layers (M9).** A pixel layer is a paint layer flagged `pixel`, so it shares cels, masks, clipping, lock alpha, effects, the timeline and every export with paint layers. One pixel is one canvas pixel: a 64x64 sprite is a 64x64 drawing shown enlarged, and a drawing never mixes pixel sizes. Its marks stay data, as strokes do: a pixel mark is a fill record whose source is cells (`FillSource::Cells`), a set of whole pixels (coverage 0 or 255) with the id of the palette swatch it was drawn with, or a set of pixels to erase. So the same addresses, `set`, `rm`, `transform`, lasso, copy and history work on them; scaling, flipping and turning sample the nearest pixel (`markedit::resampled` with `hard`), which also makes an export above full size hard-edged. Colours are palette entries: `Document::bind_swatch` finds or adds the swatch and gives it an `id` the first time a mark uses it, and `set color=` on a pixel mark binds it to the new entry. The `pixel` op (`klad pixel`) is the first way to make marks; brush strokes and flood or lasso fills are refused on a pixel layer (`ops::off_the_grid`). A drawing with a pixel layer (`Document::pixel_art`) gets a sharp view on both sides. In the editor the zoom moves in whole screen pixels per pixel above real size (`View::whole`, `View::fit_whole`; free below it), a pixel grid shows from 8 screen pixels per pixel (a dark line with light dashes, so it reads on any colour; View > Pixel grid), the pixel under the pointer is outlined on a pixel layer and named in the status line, and the Real size pane (`Pane::Preview`, opened the first time a pixel drawing is opened) shows the composed frame at 1, 2 or 4 screen pixels per pixel for drawings up to 512 px. In the CLI, `klad render` and edit previews enlarge by a whole number to about 512 px (`agent::pixel_scale`), and `--overlay grid` draws the same lines with the pixel numbers along the top and left (`overlay::draw_cells`). Palette-wide recolouring, the pencil, shapes, shading, sharp exports and Aseprite files follow in the milestone's later stories.
+- **Pixel layers (M9).** A pixel layer is a paint layer flagged `pixel`, so it shares cels, masks, clipping, lock alpha, effects, the timeline and every export with paint layers. One pixel is one canvas pixel: a 64x64 sprite is a 64x64 drawing shown enlarged, and a drawing never mixes pixel sizes. Its marks stay data, as strokes do: a pixel mark is a fill record whose source is cells (`FillSource::Cells`), a set of whole pixels (coverage 0 or 255) with the id of the palette swatch it was drawn with, or a set of pixels to erase. So the same addresses, `set`, `rm`, `transform`, lasso, copy and history work on them; scaling, flipping and turning sample the nearest pixel (`markedit::resampled` with `hard`), which also makes an export above full size hard-edged. Colours are palette entries: `Document::bind_swatch` finds or adds the swatch and gives it an `id` the first time a mark uses it, and `set color=` on a pixel mark binds it to the new entry. The `pixel` op (`klad pixel`) is the first way to make marks; brush strokes and flood or lasso fills are refused on a pixel layer (`ops::off_the_grid`). A drawing with a pixel layer (`Document::pixel_art`) gets a sharp view on both sides. In the editor the zoom moves in whole screen pixels per pixel above real size (`View::whole`, `View::fit_whole`; free below it), a pixel grid shows from 8 screen pixels per pixel (a dark line with light dashes, so it reads on any colour; View > Pixel grid), the pixel under the pointer is outlined on a pixel layer and named in the status line, and the Real size pane (`Pane::Preview`, opened the first time a pixel drawing is opened) shows the composed frame at 1, 2 or 4 screen pixels per pixel for drawings up to 512 px. In the CLI, `klad render` and edit previews enlarge by a whole number to about 512 px (`agent::pixel_scale`), and `--overlay grid` draws the same lines with the pixel numbers along the top and left (`overlay::draw_cells`). The palette is what a pixel drawing is bound to. A mark stores its swatch's id and its colour, so every reader of a stroke file draws it without the palette; when a palette edit changes a swatch's colour, `ops::follow_palette` adds a `MarkChange::Entry` for every pixel drawing, which rewrites the colour of the marks bound to that swatch in the same transaction (one undo step), and a removed swatch unbinds its marks. A palette rewritten without ids keeps them by name, then by colour (`carry_ids`). Swatches carry an optional `ramp` name: a ramp is the swatches sharing it, in palette order, dark to light (`palettes::ramp` makes one from a base colour with `color::value_step`, darker and cooler to lighter and warmer). Palettes that come with klad are colour lists in `core/src/palettes.rs` (`klad palettes`), and `palettes::parse` reads a list of hex colours or a GIMP palette. The pencil, 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.
diff --git a/docs/cli.md b/docs/cli.md
index 8f67264..0f08dc0 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -61,7 +61,8 @@ This reference is licensed under the MIT License (`LICENSE-MIT`), unlike klad it
- [`klad grass`](#klad-grass): Grow grass in closed shapes: blades lit by the ground, smaller with distance, breaking the top edge
- [`klad gaps`](#klad-gaps): List closed regions of the lines that no fill on the layer covers
- [`klad refill`](#klad-refill): Recompute the flood fills of a paint cel after the lines they were made from changed
-- [`klad palette`](#klad-palette): The document palette: list, --add a colour (with --name), --rm a name, colour or index
+- [`klad palette`](#klad-palette): The document palette: list it, --add or --rm a colour, --recolour one, --load a palette, or group colours in a --ramp
+- [`klad palettes`](#klad-palettes): The palettes that come with klad, to load with klad palette <bundle> --load <name>
- [`klad export`](#klad-export): Export PNGs, sprite sheets, numbered frames or a Godot SpriteFrames and scene
- [`klad brushes`](#klad-brushes): List brushes: the library, and with a bundle the ones it embeds
- [`klad effect`](#klad-effect): List, add or remove a layer's effects: klad effect art.klad l3 glow radius=24 color=#ffd080
@@ -3062,14 +3063,21 @@ Options:
## klad palette
```text
-The document palette, kept in doc.json. Named colours can be used wherever a colour goes (--color skin).
+The document palette, kept in doc.json. Named colours can be used wherever a colour goes (--color skin). On pixel layers every mark is bound to the palette colour it was drawn with, so changing that colour here changes the marks.
klad palette art.klad
klad palette art.klad --add '#f0c8a0' --name skin
klad palette art.klad --add '#d0a080' --name skin (changes skin)
+ klad palette art.klad --recolour skin --to '#e8b796' (by name, colour, index or id)
klad palette art.klad --rm skin
+ klad palette art.klad --load pico-8 (a palette that comes with klad: klad palettes lists them)
+ klad palette art.klad --load my.hex (a list of hex colours, one per line, or a GIMP .gpl palette)
+ klad palette art.klad --ramp wood --base '#8b5a2b' --steps 5 (wood-1 to wood-5, dark and cool to light and warm)
+ klad palette art.klad --ramp skin --of skin-dark,skin,skin-light (group colours it has, dark to light)
-As ops: {"op":"palette","add":"#f0c8a0","name":"skin"}, {"op":"palette","rm":"skin"}, {"op":"palette","set":[{"color":"#1b1b1b","name":"ink"}]}
+A loaded colour the palette already holds is not added again. A ramp is a row of colours from dark to light, used to shade one material.
+
+As ops: {"op":"palette","add":"#f0c8a0","name":"skin"}, {"op":"palette","rm":"skin"}, {"op":"palette","recolour":"skin","to":"#e8b796"}, {"op":"palette","load":"pico-8"}, {"op":"palette","ramp":"skin","of":["skin-dark","skin"]}, {"op":"palette","set":[{"color":"#1b1b1b","name":"ink"}]}
Usage: klad palette [OPTIONS] <BUNDLE>
@@ -3087,6 +3095,29 @@ Options:
--rm <RM>
+ --recolour <RECOLOUR>
+ Change one colour (a name, a colour, an index or an id) to --to; pixel marks drawn with it change too
+
+ --to <TO>
+ The new colour for --recolour
+
+ --load <LOAD>
+ Add the colours of a palette that comes with klad (klad palettes), or of a .hex or .gpl file
+
+ --ramp <RAMP>
+ A ramp of that name: made from --base in --steps, or the palette's own colours listed in --of
+
+ --base <BASE>
+ The middle colour of a new ramp
+
+ --steps <STEPS>
+ How many colours a new ramp has (2 to 16)
+
+ [default: 5]
+
+ --of <OF>
+ The colours of the ramp, dark to light: names, colours, indexes or ids (empty: the ramp is dropped)
+
--render
Render a preview after the edit and print its path
@@ -3103,6 +3134,21 @@ Options:
Print help (see a summary with '-h')
```
+## klad palettes
+
+```text
+The palettes that come with klad, to load with klad palette <bundle> --load <name>
+
+Usage: klad palettes [OPTIONS]
+
+Options:
+ --json
+
+
+ -h, --help
+ Print help
+```
+
## klad export
```text
diff --git a/docs/format.md b/docs/format.md
index 793f897..5318204 100644
--- a/docs/format.md
+++ b/docs/format.md
@@ -1,4 +1,4 @@
-_Last updated: 2026-11-11 13:30 (format `klad/7`, stroke files `KLST` version 3, brushes `klad-brush/1`)_
+_Last updated: 2026-11-11 17:20 (format `klad/7`, stroke files `KLST` version 3, brushes `klad-brush/1`)_
# The klad drawing format
@@ -63,12 +63,12 @@ Writers replace files atomically (write a temporary file, then rename), so a rea
| `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 `#`), optional `id` (unique; set once a pixel mark uses the swatch) |
+| `palette` | array | `[]` | swatches: `color`, optional `name` (unique, not starting with `#`), optional `id` (unique; set once a pixel mark uses the swatch), optional `ramp` (the name of the ramp it belongs to) |
| `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 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`.
+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`: when klad changes that swatch's colour it rewrites the colour of every pixel mark bound to it, and when the swatch is removed it clears the marks' binding and leaves their colour. A reader draws a pixel mark in the colour the mark stores. A **ramp** is the swatches that share a `ramp` name, in palette order, dark to light.
### The timeline
diff --git a/docs/skill/SKILL.md b/docs/skill/SKILL.md
index 7c761e7..3fe7333 100644
--- a/docs/skill/SKILL.md
+++ b/docs/skill/SKILL.md
@@ -114,6 +114,7 @@ klad export sprite.klad --scale 8 -o [email protected] square pixels, to keep
- A pixel layer is a grid with no soft edges, and one pixel is one canvas pixel: a 32x32 sprite is a 32x32 drawing. Size the drawing in pixels of the art, not of the screen; `klad ls` shows the layer as `pixel`.
- `--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.
+- The palette is the drawing's colours, and changing one changes the picture: `klad palette sprite.klad --recolour skin --to '#e8b796'` (a name, a colour, an index or an id) recolours every pixel mark drawn with it, on every frame. So fix a colour in the palette, not mark by mark. `klad palette sprite.klad --load pico-8` adds a palette that comes with klad (`klad palettes` lists them: pico-8, sweetie-16, dawnbringer-16, dawnbringer-32, endesga-32, resurrect-64, aap-64, gameboy, 1-bit) or a file (`.hex`, one colour per line, or a GIMP `.gpl`); colours the palette holds are not added twice. A ramp is a row of colours for one material, dark to light: `klad palette sprite.klad --ramp wood --base '#8b5a2b' --steps 5` makes `wood-1` (dark, cooler) to `wood-5` (light, warmer) around the base, and `--ramp skin --of skin-dark,skin,skin-light` groups colours it has. Shade a form with the steps of its ramp, not with new colours.
- Each 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).
- Looking: `klad render` and the `--render` preview of an edit enlarge a pixel drawing by a whole number to about 512 px, so every pixel is a square you can see (`--scale 1` gives the real size, which is how the player sees it: check there too). `--overlay grid` draws a line between pixels and numbers them along the top and the left, so a pixel's `x,y` can be read off the picture: the number is on the line where that column or row starts. `klad export --scale 8` (whole numbers) writes the enlarged PNG to keep.