A drawing app built for agent/human collaboration
Rust
Tilesets: a drawing cut into tiles, and a Godot TileSet
Indicode BV231e701d4f82
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c0ae3f1..73f2b75 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.+- Tilesets. **View > Tileset: cut into tiles…** cuts a drawing into tiles of one size; the canvas shows the tile lines, and **as a tile set** in the export window writes a Godot TileSet with a tile for every cell that is not empty. From the command line: `klad new ground.klad --pixel 64x48 --tile 16`, `klad canvas --tile 16`, `klad pixels --tile 2,0` and `klad pixel --grid --tile 2,0` to read and draw one tile at a time, and `klad export --tileset <folder>`.- Pictures to pixels. **File > Pixels of a picture…** turns a PNG or JPEG into pixels on the pixel layer you are on, in the palette's colours, or makes a pixel drawing of the layer you are on or of the whole picture at a size you choose. From the command line: `klad pixelize sprite.klad --image ref.png --to l1`, `klad pixelize hero.klad --size 64`, and `klad import ref.png` for a new pixel drawing from a picture. Each pixel becomes part of a mark bound to a palette colour, so the result is edited like any pixel drawing.- Aseprite files in and out. `klad import hero.aseprite` opens an Aseprite file as a klad drawing: its layers and groups, every frame's drawing, linked cels, the palette and its tags as clips. In the editor, **Choose an Aseprite file...** in the start window (or its path pasted there) does the same and opens the drawing it made. `klad export hero.klad --aseprite`, or **Aseprite** in the export window, writes a drawing's pixel layers back to an Aseprite file. klad says what it leaves out each way.- Palette variants. A drawing can hold other colours for the same sprite, like a blue team beside a red one. In the Colour panel **new variant** makes one and shows it; colours you change while it is shown are its own, and the palette itself keeps its colours. Pick **base** or a variant under the palette to show it. The export window exports what is shown, one variant, or **every variant** in one go. From the command line: `klad palette --new-variant blue`, `--variant base`, `--rename-variant`, `--rm-variant`, and `klad export --variant blue` or `--variants`.diff --git a/crates/app/src/commands.rs b/crates/app/src/commands.rsindex 75d9ee4..b24a79e 100644--- a/crates/app/src/commands.rs+++ b/crates/app/src/commands.rs@@ -142,6 +142,7 @@ pub enum Cmd {PreviewPane,PixelGrid,WrapCanvas,+ TileSize,Timeline,Numbers,Settings,@@ -522,7 +523,7 @@ use Repeat as R;use Trigger as T;impl Cmd {- pub const ALL: [Cmd; 195] = [+ pub const ALL: [Cmd; 196] = [Cmd::Brush,Cmd::Eraser,Cmd::Fill,@@ -661,6 +662,7 @@ impl Cmd {Cmd::PreviewPane,Cmd::PixelGrid,Cmd::WrapCanvas,+ Cmd::TileSize,Cmd::Timeline,Cmd::Numbers,Cmd::Settings,@@ -2036,6 +2038,15 @@ impl Cmd {R::No,"the drawing is a tile: pixels drawn past an edge come back in on the other side, and the canvas shows its repeats around it",),+ Cmd::TileSize => spec(+ "view.tiles",+ "cut into tiles",+ icon::PIXELS,+ G::View,+ T::None,+ R::No,+ "cut the drawing into tiles of one size, a tileset: the canvas shows the tile lines, and it exports as a Godot TileSet",+ ),Cmd::FlipView => spec("view.flip","flip the view left-right",@@ -2614,6 +2625,7 @@ impl Cmd {Cmd::PreviewPane => "Real size",Cmd::PixelGrid => "Pixel grid",Cmd::WrapCanvas => "Tile: wrap at the edges",+ Cmd::TileSize => "Tileset: cut into tiles…",Cmd::Timeline => "Timeline",Cmd::Numbers => "Show numbers",Cmd::Settings => "Settings…",@@ -2969,6 +2981,7 @@ pub const MENUS: [Menu; 9] = [Run(Cmd::FlipView),Run(Cmd::PixelGrid),Run(Cmd::WrapCanvas),+ Run(Cmd::TileSize),Line,Run(Cmd::CompareReference),],diff --git a/crates/app/src/editor.rs b/crates/app/src/editor.rsindex 145936d..11bef51 100644--- a/crates/app/src/editor.rs+++ b/crates/app/src/editor.rs@@ -608,6 +608,7 @@ struct Windows {about: bool,export: bool,pixels: bool,+ tiles: bool,report: bool,font: bool,paintover: bool,@@ -716,6 +717,7 @@ pub(crate) struct Editor {checks: checks::Checks,export: export::Form,pixels: pixels::Form,+ tile_size: [u32; 2],paintover: paintover::Form,compare: Option<compare::Compared>,bones: bones::BoneTool,@@ -918,6 +920,7 @@ impl Editor {checks: checks::Checks::default(),export: export::Form::default(),pixels: pixels::Form::default(),+ tile_size: [16, 16],paintover: paintover::Form::default(),compare: None,bones: bones::BoneTool::default(),@@ -3858,6 +3861,21 @@ impl Editor {.map(|y| y as f32).for_each(|y| rule(to_screen(x0, y), to_screen(x1, y)));}+ if let Some([tile_width, tile_height]) = self.scene.bundle.doc.canvas.tile {+ let edge = egui::Stroke::new(1.5, Color32::from_black_alpha(150));+ let glow = egui::Stroke::new(1.0, Color32::from_white_alpha(140));+ let to_screen = |x: f32, y: f32| self.screen(view, rect, vec2(x, y));+ let rule = |a: Pos2, b: Pos2| {+ painter.line_segment([a, b], edge);+ painter.extend(egui::Shape::dashed_line(&[a, b], glow, 4.0, 4.0));+ };+ (0..=(canvas.x as u32 / tile_width.max(1)))+ .map(|column| (column * tile_width) as f32)+ .for_each(|x| rule(to_screen(x, 0.0), to_screen(x, canvas.y)));+ (0..=(canvas.y as u32 / tile_height.max(1)))+ .map(|row| (row * tile_height) as f32)+ .for_each(|y| rule(to_screen(0.0, y), to_screen(canvas.x, y)));+ }let shaped = self.pixel_shape_spec().filter(|_| self.tool == Tool::Shape && self.scene.on_grid())diff --git a/crates/app/src/editor/clips.rs b/crates/app/src/editor/clips.rsindex 64cbb57..cc5d558 100644--- a/crates/app/src/editor/clips.rs+++ b/crates/app/src/editor/clips.rs@@ -341,7 +341,11 @@ impl Editor {tag: Tag::Export,name: format!("export a Godot {} ({typed})",- if how == "--godot-rig" { "rig" } else { "parallax scene" }+ match how {+ "--godot-rig" => "rig",+ "--tileset" => "tile set",+ _ => "parallax scene",+ }),exe: PathBuf::new(),args,diff --git a/crates/app/src/editor/commands.rs b/crates/app/src/editor/commands.rsindex 9001dc6..6adb142 100644--- a/crates/app/src/editor/commands.rs+++ b/crates/app/src/editor/commands.rs@@ -494,6 +494,7 @@ impl Editor {Cmd::ReportProblem => self.windows.report,Cmd::Export => self.windows.export,Cmd::Pixelize => self.windows.pixels,+ Cmd::TileSize => self.windows.tiles,Cmd::AddFont => self.windows.font,Cmd::PaintOver => self.windows.paintover,Cmd::CompareReference => self.windows.compare,@@ -605,6 +606,12 @@ impl Editor {Cmd::Unwrap => self.unwrap()?,Cmd::ImportPicture => self.windows.import = !self.windows.import,Cmd::Pixelize => self.windows.pixels = !self.windows.pixels,+ Cmd::TileSize => {+ self.windows.tiles = !self.windows.tiles;+ if let Some(tile) = self.scene.bundle.doc.canvas.tile {+ self.tile_size = tile;+ }+ }Cmd::LoadPalette => self.windows.palettes = !self.windows.palettes,Cmd::NewVariant => {let typed = self.swatch_name.trim().to_string();@@ -1064,7 +1071,10 @@ impl Editor {}Cmd::WrapCanvas => {let wrap = !self.scene.bundle.doc.canvas.wrap;- self.apply(vec![Op::Canvas { wrap: Some(wrap) }])?;+ self.apply(vec![Op::Canvas {+ wrap: Some(wrap),+ tile: None,+ }])?;self.dirty.extend(self.scene.all_tiles());}Cmd::Timeline => {diff --git a/crates/app/src/editor/export.rs b/crates/app/src/editor/export.rsindex f46bc0b..7563ace 100644--- a/crates/app/src/editor/export.rs+++ b/crates/app/src/editor/export.rs@@ -317,6 +317,14 @@ impl Editor {{self.export_godot_as("--godot-rig");}+ let tiled = self.scene.bundle.doc.canvas.tile.is_some();+ if ui+ .add_enabled(tiled, egui::Button::new("as a tile set"))+ .hint("a Godot TileSet with a tile for every cell that is not empty; needs the drawing cut into tiles (View > Tileset: cut into tiles…)")+ .clicked()+ {+ self.export_godot_as("--tileset");+ }});if run {self.export()?;diff --git a/crates/app/src/editor/panels.rs b/crates/app/src/editor/panels.rsindex ff8b56a..c6d51a9 100644--- a/crates/app/src/editor/panels.rs+++ b/crates/app/src/editor/panels.rs@@ -1031,6 +1031,17 @@ impl Editor {);self.windows.pixels &= open;}+ if self.windows.tiles {+ let mut open = true;+ Self::window(+ ctx,+ "tiles",+ (format!("{} Tileset", icon::PIXELS), near_timeline),+ &mut open,+ |ui| self.check(|e| e.tiles_window(ui)),+ );+ self.windows.tiles &= open;+ }if self.windows.paintover {let mut open = true;Self::window(diff --git a/crates/app/src/editor/pixels.rs b/crates/app/src/editor/pixels.rsindex 7d45a9e..9f38ffd 100644--- a/crates/app/src/editor/pixels.rs+++ b/crates/app/src/editor/pixels.rs@@ -106,6 +106,57 @@ impl Editor {Ok(())}+ pub(super) fn tiles_window(&mut self, ui: &mut egui::Ui) -> Result<()> {+ let canvas = self.scene.bundle.doc.canvas.clone();+ ui.label(match (canvas.tile, canvas.tiles()) {+ (Some([w, h]), Some((columns, rows))) => {+ format!("cut into tiles of {w} x {h} px: {columns} across, {rows} down")+ }+ _ => format!(+ "not cut into tiles; the canvas is {} x {} px",+ canvas.width, canvas.height+ ),+ });+ ui.horizontal(|ui| {+ let label = ui.label("tile");+ ui.add(egui::DragValue::new(&mut self.tile_size[0]).range(1..=canvas.width))+ .labelled_by(label.id)+ .hint("the width of a tile in pixels");+ ui.label("x");+ ui.add(egui::DragValue::new(&mut self.tile_size[1]).range(1..=canvas.height))+ .hint("the height of a tile in pixels");+ ui.label("px");+ });+ let fits = canvas.cut(self.tile_size);+ if let Err(why) = &fits {+ ui.weak(format!("{why:#}"));+ }+ let (mut cut, mut clear) = (false, false);+ ui.horizontal(|ui| {+ cut = ui+ .add_enabled(fits.is_ok(), egui::Button::new("cut into tiles"))+ .hint("the canvas shows the tile lines, and the drawing exports as a Godot TileSet (as klad canvas --tile does)")+ .clicked();+ clear = ui+ .add_enabled(canvas.tile.is_some(), egui::Button::new("no tiles"))+ .hint("the drawing is one picture again")+ .clicked();+ });+ if cut {+ self.apply(vec![klad_core::ops::Op::Canvas {+ wrap: None,+ tile: Some(Some(self.tile_size)),+ }])?;+ }+ if clear {+ self.apply(vec![klad_core::ops::Op::Canvas {+ wrap: None,+ tile: Some(None),+ }])?;+ }+ Ok(())+ }+pub(super) fn pixels_window(&mut self, ui: &mut egui::Ui) -> Result<()> {let on_pixels = self.scene.active_layer().is_some_and(|l| l.pixel());let form = &mut self.pixels;diff --git a/crates/app/src/editor/ui_tests.rs b/crates/app/src/editor/ui_tests.rsindex 8a5aa45..862d1f4 100644--- a/crates/app/src/editor/ui_tests.rs+++ b/crates/app/src/editor/ui_tests.rs@@ -2279,6 +2279,36 @@ fn the_pixel_pencil_mirrors_across_a_line_and_wraps_on_a_tile() {"a GIF has no 16-bit form");h.state_mut().windows.export = false;+ h.state_mut().invoke(Cmd::TileSize).unwrap();+ h.run_steps(3);+ assert!(+ h.query_all(By::new().label_contains("not cut into tiles")).count() > 0,+ "the window says what the drawing is"+ );+ let (width, height) = {+ let canvas = &h.state().scene.bundle.doc.canvas;+ (canvas.width, canvas.height)+ };+ h.state_mut().tile_size = [width / 2, height / 2];+ h.run_steps(2);+ h.get_by_label("cut into tiles").click();+ h.run_steps(3);+ assert_eq!(+ h.state().scene.bundle.doc.canvas.tile,+ Some([width / 2, height / 2]),+ "the drawing is four tiles"+ );+ assert!(h.query_all(By::new().label_contains("2 across, 2 down")).count() > 0);+ h.state_mut().tile_size = [width / 2 + 1, height / 2];+ h.run_steps(2);+ assert!(+ h.query_all(By::new().label_contains("does not cut into tiles")).count() > 0,+ "a size that does not fit says why"+ );+ h.get_by_label("no tiles").click();+ h.run_steps(3);+ assert_eq!(h.state().scene.bundle.doc.canvas.tile, None);+ h.state_mut().invoke(Cmd::TileSize).unwrap();h.state_mut().invoke(Cmd::Pixelize).unwrap();h.run_steps(3);assert_eq!(h.state().is_on(Cmd::Pixelize), Some(true));diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rsindex f404b18..2e8dfee 100644--- a/crates/cli/src/main.rs+++ b/crates/cli/src/main.rs@@ -227,15 +227,27 @@ enum Command {pixel: Option<String>,#[arg(long, help = "A tile: what is drawn past an edge comes back in on the other side")]wrap: bool,+ #[arg(+ long,+ value_name = "SIZE",+ help = "Cut the drawing into tiles of this size, 16 or 16x24: a tileset (the canvas has to be a whole number of tiles each way)"+ )]+ tile: Option<String>,},#[command(- about = "The canvas: its size and background, and whether it wraps at its edges",- long_about = "The canvas: its size and background, and whether it wraps at its edges. On a canvas that wraps, a tile, pixels drawn past an edge come back in on the other side, and fills and outlines go round the edges, so the drawing repeats without a seam. klad render --repeat 3 shows it repeated.\n\n klad canvas tile.klad\n klad canvas tile.klad --wrap on\n\nAs an op: {\"op\":\"canvas\",\"wrap\":true}."+ about = "The canvas: its size and background, whether it wraps at its edges, and the size of its tiles",+ long_about = "The canvas: its size and background, and whether it wraps at its edges. On a canvas that wraps, a tile, pixels drawn past an edge come back in on the other side, and fills and outlines go round the edges, so the drawing repeats without a seam. klad render --repeat 3 shows it repeated.\n\n klad canvas tile.klad\n klad canvas tile.klad --wrap on\n\nA drawing can also be cut into tiles of one size, a tileset: --tile 16 (or 16x24) sets the size, which the canvas has to be a whole number of each way, and --tile off takes it away. klad pixels and klad pixel --grid then take --tile column,row to read and draw one tile at a time, the editor shows the tile lines, and klad export --tileset writes a Godot TileSet.\n\n klad canvas tiles.klad --tile 16\n klad pixels tiles.klad l1 --tile 2,0 --plain\n klad export tiles.klad --tileset ../game/art\n\nAs an op: {\"op\":\"canvas\",\"wrap\":true}, {\"op\":\"canvas\",\"tile\":16}, {\"op\":\"canvas\",\"tile\":[16,24]}, {\"op\":\"canvas\",\"tile\":null}.")]Canvas {bundle: PathBuf,#[arg(long, value_parser = ["on", "off"], help = "Turn wrapping at the edges on or off")]wrap: Option<String>,+ #[arg(+ long,+ value_name = "SIZE",+ help = "Cut the drawing into tiles of this size, 16 or 16x24 (off: no tiles); the canvas has to be a whole number of tiles each way"+ )]+ tile: Option<String>,#[command(flatten)]flags: EditFlags,},@@ -1109,6 +1121,14 @@ enum Command {help = "Where the grid's top left pixel goes: x,y")]at: [i64; 2],+ #[arg(+ long,+ requires = "grid",+ value_parser = parse_cell,+ value_name = "COLUMN,ROW",+ help = "With --grid, in a drawing cut into tiles: put the grid's top left on that tile's (0,0 is the first tile)"+ )]+ tile: Option<[i64; 2]>,#[arg(long,conflicts_with = "cells",@@ -1969,6 +1989,13 @@ enum Command {plain: bool,#[arg(long)]json: bool,+ #[arg(+ long,+ value_parser = parse_cell,+ value_name = "COLUMN,ROW",+ help = "In a drawing cut into tiles: only that tile (0,0 is the first), with pixels counted from its own top left"+ )]+ tile: Option<[i64; 2]>,},#[command(about = "The palettes that come with klad, to load with klad palette <bundle> --load <name>")]Palettes {@@ -1977,7 +2004,7 @@ enum Command {},#[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). A pixel drawing exports at whole-number scales only, up to 64 (or 16384 px a side), enlarged pixel for pixel so it stays sharp: --scale 8 turns a 32 px sprite into 256 px. 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 --gif [run] [--scale 8] an animated GIF with each frame's own duration: one per clip (art-run.gif; clips that loop, loop), or art.gif of the whole timeline; up to 255 colours kept exactly, more are reduced to the nearest of 255, in flat areas of one colour or, with --dither, mixed in a fine even pattern that keeps gradients smooth; transparent unless --background\n klad export art.klad --aseprite art.aseprite: the pixel layers and groups, the drawing of every frame (holds and links as linked cels), the palette and clips as tags, in RGBA; frames that show the same drawings are one frame with their time added up. Paint and vector layers are left out and named. klad import opens such a file\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). For a pixel drawing the scenes set texture_filter to nearest, so the sprite stays sharp in the game. 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."+ 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). A pixel drawing exports at whole-number scales only, up to 64 (or 16384 px a side), enlarged pixel for pixel so it stays sharp: --scale 8 turns a 32 px sprite into 256 px. 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 --gif [run] [--scale 8] an animated GIF with each frame's own duration: one per clip (art-run.gif; clips that loop, loop), or art.gif of the whole timeline; up to 255 colours kept exactly, more are reduced to the nearest of 255, in flat areas of one colour or, with --dither, mixed in a fine even pattern that keeps gradients smooth; transparent unless --background\n klad export art.klad --aseprite art.aseprite: the pixel layers and groups, the drawing of every frame (holds and links as linked cels), the palette and clips as tags, in RGBA; frames that show the same drawings are one frame with their time added up. Paint and vector layers are left out and named. klad import opens such a file\n klad export art.klad --tileset ../game/art a drawing cut into tiles (klad canvas --tile 16) as a Godot TileSet: art-tiles.png and art-tiles.tres with one atlas source and a tile for every cell that is not empty; --frame, --scale and --variant choose what is shown\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). For a pixel drawing the scenes set texture_filter to nearest, so the sprite stays sharp in the game. 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.")]Export {bundle: PathBuf,@@ -2027,6 +2054,13 @@ enum Command {help = "An Aseprite file of the drawing's pixel layers: groups, the drawing of every frame, the palette and clips as tags")]aseprite: bool,+ #[arg(+ long,+ num_args = 0..=1,+ conflicts_with_all = ["sheet", "frames", "gif", "godot", "godot_scene", "godot_rig", "aseprite"],+ help = "A Godot TileSet of a drawing cut into tiles (klad canvas --tile): the picture and a .tres with a tile for every cell that is not empty, into this folder (default: the document's export.godot)"+ )]+ tileset: Option<Option<PathBuf>>,#[arg(long,num_args = 0..=1,@@ -2444,6 +2478,34 @@ fn parse_box(text: &str) -> Result<[i64; 4]> {.map_err(|_| anyhow!("{text:?} is not four whole numbers like 2,3,10,8"))}+fn tile_size(text: &str) -> Result<Option<[u32; 2]>> {+ let text = text.trim();+ if ["off", "none", "0"].contains(&text) {+ return Ok(None);+ }+ let sides: Vec<u32> = text+ .split(['x', 'X', ','])+ .map(|part| part.trim().parse::<u32>())+ .collect::<std::result::Result<_, _>>()+ .map_err(|_| anyhow!("a tile size is a number of pixels, 16 or 16x24, or off: not {text:?}"))?;+ match sides.as_slice() {+ [side] => Ok(Some([*side, *side])),+ [width, height] => Ok(Some([*width, *height])),+ _ => Err(anyhow!(+ "a tile size is a number of pixels, 16 or 16x24, or off: not {text:?}"+ )),+ }+}++fn tile_of(canvas: &klad_core::doc::Canvas, at: [i64; 2]) -> Result<[u32; 4]> {+ match (u32::try_from(at[0]), u32::try_from(at[1])) {+ (Ok(column), Ok(row)) => canvas.tile_at(column, row),+ _ => Err(anyhow!(+ "a tile is its column and row, counted from 0,0 at the top left"+ )),+ }+}+fn parse_cell(text: &str) -> Result<[i64; 2]> {let parts: Vec<i64> = text.split(',')@@ -2621,6 +2683,7 @@ fn run() -> Result<()> {sketch,pixel,wrap,+ tile,} => {let size = pixel.as_deref().map(pixel_size).transpose()?;let mut made = edit::new(@@ -2636,36 +2699,56 @@ fn run() -> Result<()> {pixel: size.is_some(),},)?;- if wrap {- made.apply(&[Op::Canvas { wrap: Some(true) }])?;+ let cut = tile.as_deref().map(tile_size).transpose()?;+ if wrap || cut.is_some() {+ let applied = made.apply(&[Op::Canvas {+ wrap: wrap.then_some(true),+ tile: cut,+ }]);+ if let Err(error) = applied {+ let _ = std::fs::remove_dir_all(&bundle);+ return Err(error);+ }made.stamp("cli")?;}println!("{}", bundle.display());}- Command::Canvas { bundle, wrap, flags } => match wrap {- Some(wrap) => agent::edit(- &bundle,- &[Op::Canvas {- wrap: Some(wrap == "on"),- }],- &output(&flags, 0),- )?,- None => {+ Command::Canvas {+ bundle,+ wrap,+ tile,+ flags,+ } => match (wrap, tile) {+ (None, None) => {let canvas = Bundle::open(&bundle)?.doc.canvas;match flags.json {true => println!("{}", serde_json::to_string(&canvas)?),false => println!(- "{}x{} background {} {}",+ "{}x{} background {} {}{}",canvas.width,canvas.height,canvas.background.as_deref().unwrap_or("none"),match canvas.wrap {true => "wraps at its edges",false => "stops at its edges",+ },+ match (canvas.tile, canvas.tiles()) {+ (Some([w, h]), Some((columns, rows))) => {+ format!(" tiles of {w}x{h}, {columns} across and {rows} down")+ }+ _ => String::new(),}),}}+ (wrap, tile) => agent::edit(+ &bundle,+ &[Op::Canvas {+ wrap: wrap.map(|w| w == "on"),+ tile: tile.as_deref().map(tile_size).transpose()?,+ }],+ &output(&flags, 0),+ )?,},Command::Frames { bundle, from, to, json } => frames::sheet(&bundle, from, to, json)?,Command::Frame {@@ -3296,6 +3379,7 @@ fn run() -> Result<()> {cells,grid,at,+ tile,path,line,rect,@@ -3325,6 +3409,13 @@ fn run() -> Result<()> {file => std::fs::read_to_string(file).with_context(|| format!("reading {file}"))?,};let (legend, rows) = klad_core::pixel::parse_text(&text)?;+ let at = match tile {+ Some(tile) => {+ let [x, y, ..] = tile_of(&Bundle::open(&bundle)?.doc.canvas, tile)?;+ [x as i64 + at[0], y as i64 + at[1]]+ }+ None => at,+ };let spec = klad_core::ops::GridSpec {layer,frame,@@ -4201,7 +4292,8 @@ fn run() -> Result<()> {frame,plain,json,- } => pixels(&bundle, &layer, frame, plain, json)?,+ tile,+ } => pixels(&bundle, &layer, frame, plain, json, tile)?,Command::Export {bundle,png: _,@@ -4216,6 +4308,7 @@ fn run() -> Result<()> {gif,dither,aseprite,+ tileset,godot,store,godot_scene,@@ -4263,6 +4356,9 @@ fn run() -> Result<()> {};match (&sheet, &frames, &godot) {_ if aseprite => aseprite::export(&bundle, out, variant.as_deref()),+ _ if tileset.is_some() => {+ sprites::tileset(&bundle, tileset.clone().flatten().or(out), store, &look, frame)+ }_ if gif.is_some() => sprites::gif(&bundle, gif.as_deref().unwrap_or("all"), &look, dither, out),(Some(spec), _, _) => sprites::sheet(&bundle, spec, &look, &packing, out),(_, Some(spec), _) => sprites::frames(&bundle, spec, &look, out),@@ -5069,7 +5165,7 @@ fn palette(path: &Path, as_json: bool) -> Result<()> {Ok(())}-fn pixels(path: &Path, layer: &str, frame: u32, plain: bool, as_json: bool) -> Result<()> {+fn pixels(path: &Path, layer: &str, frame: u32, plain: bool, as_json: bool, tile: Option<[i64; 2]>) -> Result<()> {let bundle = Bundle::open(path)?;let doc = &bundle.doc;let owner = doc.find_layer(layer)?;@@ -5084,7 +5180,19 @@ fn pixels(path: &Path, layer: &str, frame: u32, plain: bool, as_json: bool) -> RSome(cel) => bundle.read_marks(&owner.id, &cel.id)?,None => Vec::new(),};- let grid = klad_core::pixel::grid_of(&marks, doc.canvas.width, doc.canvas.height);+ let whole = klad_core::pixel::grid_of(&marks, doc.canvas.width, doc.canvas.height);+ let region = tile.map(|tile| tile_of(&doc.canvas, tile)).transpose()?;+ let grid = match region {+ None => whole,+ Some([x, y, w, h]) => klad_core::pixel::Grid {+ width: w,+ height: h,+ cells: (y..y + h)+ .flat_map(|row| (x..x + w).map(move |column| (column, row)))+ .map(|(column, row)| whole.at(column, row).map(String::from))+ .collect(),+ },+ };let legend = klad_core::pixel::legend(doc, &grid);if as_json {let named: serde_json::Map<String, serde_json::Value> = legend@@ -5120,8 +5228,16 @@ fn pixels(path: &Path, layer: &str, frame: u32, plain: bool, as_json: bool) -> Rreturn Ok(());}println!(- "{}x{} layer {} \"{}\" frame {frame}",- grid.width, grid.height, owner.id, owner.name+ "{}x{} layer {} \"{}\" frame {frame}{}",+ grid.width,+ grid.height,+ owner.id,+ owner.name,+ match (tile, region) {+ (Some([column, row]), Some([x, y, ..])) =>+ format!(" tile {column},{row} (its top left is canvas pixel {x},{y})"),+ _ => String::new(),+ });println!("{}", klad_core::pixel::ruled(&grid, &legend));Ok(())diff --git a/crates/cli/src/sprites.rs b/crates/cli/src/sprites.rsindex 0f5576f..05b4cde 100644--- a/crates/cli/src/sprites.rs+++ b/crates/cli/src/sprites.rs@@ -498,13 +498,10 @@ pub(crate) fn read(path: &Path) -> Option<String> {fs::read_to_string(path).ok()}-pub fn godot(path: &Path, dir: Option<PathBuf>, store: bool, look: &Look, packing: &Packing) -> Result<()> {- let start = Instant::now();- check_look(look)?;- let mut bundle = Bundle::open(path)?;- let home = bundle_dir(&bundle);+fn godot_folder(bundle: &mut Bundle, dir: &Option<PathBuf>, store: bool) -> Result<PathBuf> {+ let home = bundle_dir(bundle);let stored = bundle.doc.export.godot.clone();- let target = match (&dir, &stored) {+ let target = match (dir, &stored) {(Some(d), _) => d.clone(),(None, Some(s)) => home.join(s),(None, None) => bail!(@@ -514,7 +511,7 @@ pub fn godot(path: &Path, dir: Option<PathBuf>, store: bool, look: &Look, packinfs::create_dir_all(&target).with_context(|| format!("making {}", target.display()))?;let target = target.canonicalize()?;let rel = kept_folder(&home.canonicalize()?, &target);- let keep = match (&dir, &stored) {+ let keep = match (dir, &stored) {(Some(_), None) => true,(Some(_), Some(s)) => store && *s != rel,_ => false,@@ -525,11 +522,119 @@ pub fn godot(path: &Path, dir: Option<PathBuf>, store: bool, look: &Look, packin}])?;bundle.stamp("cli")?;eprintln!("kept {rel} as this document's Godot folder (export.godot)");- } else if let (Some(_), Some(s)) = (&dir, &stored)+ } else if let (Some(_), Some(s)) = (dir, &stored)&& *s != rel{eprintln!("exported to {rel}; the document's Godot folder stays {s} (add --store to replace it)");}+ Ok(target)+}++pub fn tileset(path: &Path, dir: Option<PathBuf>, store: bool, look: &Look, frame: u32) -> Result<()> {+ check_look(look)?;+ let mut bundle = Bundle::open(path)?;+ let Some([tile_width, tile_height]) = bundle.doc.canvas.tile else {+ bail!(+ "this drawing is not cut into tiles: klad canvas <bundle> --tile 16 sets the tile size (the canvas has to be a whole number of tiles each way)"+ );+ };+ if frame >= bundle.doc.timeline.frames {+ bail!(+ "frame {frame} is past the last frame {}",+ bundle.doc.timeline.frames - 1+ );+ }+ let target = godot_folder(&mut bundle, &dir, store)?;+ let doc = &bundle.doc;+ klad_render::export::check_scale(doc, look.scale)?;+ let size = |side: u32| (side as f32 * look.scale).round() as u32;+ if size(tile_width) as f32 != tile_width as f32 * look.scale+ || size(tile_height) as f32 != tile_height as f32 * look.scale+ {+ bail!(+ "at scale {} a tile of {tile_width}x{tile_height} is not a whole number of pixels",+ look.scale+ );+ }+ let layer = look.layer.as_deref().map(|k| doc.find_layer(k)).transpose()?;+ let detail = detail_of(doc, look.scale);+ let brushes = BrushSet::for_bundle(&bundle)?;+ let dress = crate::layers::dress_of(doc, look.variant.as_deref())?;+ let rasters = crate::layers::dressed(+ &bundle,+ &brushes,+ crate::layers::load_at(&bundle, frame, &brushes, detail)?,+ &dress,+ )?;+ let options = Options {+ scale: look.scale,+ background: look.background,+ references: false,+ detail,+ };+ let image = render(+ doc,+ frame,+ &rasters,+ &layer.map_or(Target::Frame, Target::Layer),+ options,+ )?;+ let shown = klad_render::export::dither8(&image)?;+ let (cell_width, cell_height) = (size(tile_width), size(tile_height));+ let (columns, rows) = (image.width() as u32 / cell_width, image.height() as u32 / cell_height);+ let across = image.width() as usize;+ let tiles: Vec<(u32, u32)> = (0..rows)+ .flat_map(|row| (0..columns).map(move |column| (column, row)))+ .filter(|(column, row)| {+ (0..cell_height).any(|y| {+ (0..cell_width).any(|x| {+ let at = ((row * cell_height + y) as usize * across + (column * cell_width + x) as usize) * 4;+ shown[at + 3] > 0+ })+ })+ })+ .collect();+ if tiles.is_empty() {+ bail!("frame {frame} shows nothing: there are no tiles to export");+ }+ let stem = format!("{}-tiles", file_safe(&stem_for(&bundle, look)));+ let (png, tres) = (target.join(format!("{stem}.png")), target.join(format!("{stem}.tres")));+ let bytes = match look.depth {+ 16 => klad_render::export::png16(&image)?,+ _ => klad_render::export::png8(&image)?,+ };+ let uid = read(&tres)+ .and_then(|t| sprites::header_uid(&t))+ .unwrap_or_else(|| sprites::uid_for(&tres.to_string_lossy()));+ let text = sprites::tile_set(&sprites::TileSet {+ uid: &uid,+ texture: &Texture {+ path: file_name(&png),+ uid: read(&png.with_extension("png.import")).and_then(|t| sprites::import_uid(&t)),+ },+ tile: [cell_width, cell_height],+ tiles: &tiles,+ });+ write_atomic(&png, &bytes)?;+ write_atomic(&tres, text.as_bytes())?;+ println!("{}", png.display());+ println!("{}", tres.display());+ eprintln!(+ "{} tiles of {cell_width}x{cell_height} ({columns} across, {rows} down, {} empty left out)",+ tiles.len(),+ (columns * rows) as usize - tiles.len()+ );+ if doc.pixel_art() {+ eprintln!("note: in Godot, set the TileMapLayer's texture filter to Nearest so the tiles stay sharp");+ }+ Ok(())+}++pub fn godot(path: &Path, dir: Option<PathBuf>, store: bool, look: &Look, packing: &Packing) -> Result<()> {+ let start = Instant::now();+ check_look(look)?;+ let mut bundle = Bundle::open(path)?;+ let target = godot_folder(&mut bundle, &dir, store)?;let doc = &bundle.doc;let animations = sprites::animations(doc, "all")?;let stem = file_safe(&stem_for(&bundle, look));@@ -722,6 +827,113 @@ func _init():const PACKING: Packing = Packing { padding: 2, max: 4096 };+ const TILES: &str = r#"extends SceneTree++func _init():+ var out = {}+ var tiles = load("res://art/ground-tiles.tres")+ out["class"] = tiles.get_class()+ out["tile_size"] = [tiles.tile_size.x, tiles.tile_size.y]+ out["sources"] = tiles.get_source_count()+ var source = tiles.get_source(tiles.get_source_id(0))+ out["source"] = source.get_class()+ out["region"] = [source.texture_region_size.x, source.texture_region_size.y]+ out["count"] = source.get_tiles_count()+ out["has"] = [source.has_tile(Vector2i(0, 0)), source.has_tile(Vector2i(1, 0)), source.has_tile(Vector2i(2, 1))]+ out["texture"] = [source.texture.get_width(), source.texture.get_height()]+ out["path"] = tiles.resource_path+ print("RESULT ", JSON.stringify(out))+ quit()+"#;++ #[test]+ fn godot_loads_the_tile_set_with_a_tile_for_every_cell_that_is_drawn() {+ let dir = std::env::temp_dir().join(format!("draw-godot-tiles-{}", std::process::id()));+ let _ = fs::remove_dir_all(&dir);+ let project = dir.join("game");+ fs::create_dir_all(project.join("art")).unwrap();+ let path = dir.join("ground.klad");+ let mut bundle = Bundle::blank(+ &path,+ &klad_core::bundle::Blank {+ width: 48,+ height: 32,+ pixel: true,+ ..klad_core::bundle::Blank::default()+ },+ "cli",+ )+ .unwrap();+ let layer = bundle.doc.layers[0].id.clone();+ assert!(+ tileset(&path, Some(project.join("art")), false, &look(1.0), 0)+ .unwrap_err()+ .to_string()+ .contains("not cut into tiles")+ );+ bundle+ .apply(+ &klad_core::ops::parse_lines(&format!(+ "{}\n{}\n{}",+ r##"{"op":"canvas","tile":16}"##,+ format_args!(+ r##"{{"op":"pixel","layer":"{layer}","color":"#3a5a40","rect":[0,0,16,16],"filled":true}}"##+ ),+ format_args!(r##"{{"op":"pixel","layer":"{layer}","color":"#8b5a2b","cells":[[40,20]]}}"##),+ ))+ .unwrap(),+ )+ .unwrap();+ tileset(&path, Some(project.join("art")), false, &look(2.0), 0).unwrap();+ let tres = fs::read_to_string(project.join("art/ground-tiles.tres")).unwrap();+ assert!(tres.starts_with("[gd_resource type=\"TileSet\" load_steps=3 format=3 uid=\"uid://"));+ assert!(tres.contains("texture_region_size = Vector2i(32, 32)\n0:0/0 = 0\n2:1/0 = 0\n\n[resource]"));+ assert!(tres.contains("path=\"ground-tiles.png\""));+ assert!(!tres.contains("1:0/0"), "an empty cell is no tile");+ assert_eq!(+ Bundle::open(&path).unwrap().doc.export.godot.as_deref(),+ Some("game/art"),+ "the folder is kept, as for the other Godot exports"+ );+ let uid = sprites::header_uid(&tres).unwrap();+ tileset(&path, None, false, &look(2.0), 0).unwrap();+ assert_eq!(+ sprites::header_uid(&fs::read_to_string(project.join("art/ground-tiles.tres")).unwrap()).unwrap(),+ uid,+ "a second export keeps the uid"+ );+ assert!(tileset(&path, None, false, &look(1.5), 0).is_err());+ let Some(binary) = godot_binary() else {+ eprintln!("no godot on PATH (or $GODOT): skipping the import check");+ fs::remove_dir_all(&dir).unwrap();+ return;+ };+ fs::write(+ project.join("project.godot"),+ "config_version=5\n\n[application]\n\nconfig/name=\"klad tiles\"\n",+ )+ .unwrap();+ fs::write(project.join("tiles.gd"), TILES).unwrap();+ godot_run(&binary, &project, &["--import"]);+ let text = godot_run(&binary, &project, &["--script", "res://tiles.gd"]);+ let line = text+ .lines()+ .find_map(|l| l.strip_prefix("RESULT "))+ .unwrap_or_else(|| panic!("no result from godot:\n{text}"));+ let got: Value = serde_json::from_str(line).unwrap();+ assert_eq!(got["class"], "TileSet", "{got}");+ assert_eq!(got["tile_size"], serde_json::json!([32, 32]));+ assert_eq!(+ (got["sources"].as_u64(), got["source"].as_str()),+ (Some(1), Some("TileSetAtlasSource"))+ );+ assert_eq!(got["region"], serde_json::json!([32, 32]));+ assert_eq!(got["count"].as_u64(), Some(2));+ assert_eq!(got["has"], serde_json::json!([true, false, true]));+ assert_eq!(got["texture"], serde_json::json!([96, 64]));+ fs::remove_dir_all(&dir).unwrap();+ }+#[test]fn godot_imports_the_export_with_its_clips_timing_origin_and_uids() {let Some(binary) = godot_binary() else {diff --git a/crates/cli/tests/binary.rs b/crates/cli/tests/binary.rsindex 04308aa..9676ea9 100644--- a/crates/cli/tests/binary.rs+++ b/crates/cli/tests/binary.rs@@ -1808,6 +1808,102 @@ fn pictures_and_painted_layers_become_pixels_on_the_palette() {std::fs::remove_dir_all(&dir).unwrap();}+#[test]+fn a_drawing_cut_into_tiles_is_read_drawn_and_exported_tile_by_tile() {+ let dir = std::env::temp_dir().join(format!("draw-binary-tiles-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(dir.join("game")).unwrap();+ let bundle = dir.join("ground.klad");+ let path = bundle.to_str().unwrap();+ let run = |args: &[&str]| Command::new(env!("CARGO_BIN_EXE_klad")).args(args).output().unwrap();+ let both = |args: &[&str]| {+ let out = run(args);+ assert!(+ out.status.success(),+ "{args:?}: {}",+ String::from_utf8_lossy(&out.stderr)+ );+ (+ String::from_utf8_lossy(&out.stdout).to_string(),+ String::from_utf8_lossy(&out.stderr).to_string(),+ )+ };+ let draw = |args: &[&str]| both(args).0;+ let refused = |args: &[&str]| {+ let out = run(args);+ assert!(!out.status.success(), "{args:?} went through");+ String::from_utf8_lossy(&out.stderr).to_string()+ };+ let odd = dir.join("odd.klad");+ assert!(+ refused(&["new", odd.to_str().unwrap(), "--pixel", "50x32", "--tile", "16"])+ .contains("does not cut into tiles")+ );+ assert!(!odd.exists(), "a drawing that cannot be cut is not left behind");+ draw(&["new", path, "--pixel", "48x32", "--tile", "16"]);+ assert!(draw(&["canvas", path]).contains("tiles of 16x16, 3 across and 2 down"));+ draw(&["palette", path, "--add", "#3a5a40", "--name", "grass"]);+ draw(&["palette", path, "--add", "#8b5a2b", "--name", "dirt"]);+ draw(&[+ "pixel",+ path,+ "l1",+ "--color",+ "grass",+ "--rect",+ "0,0,16,16",+ "--filled",+ ]);+ let grid = dir.join("tile.txt");+ std::fs::write(&grid, "d = dirt\n\ndddd\nd..d\ndddd\n").unwrap();+ draw(&["pixel", path, "l1", "--grid", grid.to_str().unwrap(), "--tile", "2,1"]);+ let whole = draw(&["pixels", path, "l1", "--plain"]);+ let rows: Vec<&str> = whole.lines().skip_while(|l| !l.is_empty()).skip(1).collect();+ assert_eq!(+ &rows[16][32..36],+ "dddd",+ "the grid went to the tile's own corner, canvas pixel 32,16"+ );+ assert_eq!(&rows[17][32..36], "d..d");+ let tile = draw(&["pixels", path, "l1", "--tile", "2,1", "--plain"]);+ let cut: Vec<&str> = tile.lines().skip_while(|l| !l.is_empty()).skip(1).collect();+ assert_eq!(cut.len(), 16, "one tile is 16 rows");+ assert_eq!(+ (cut[0], cut[1], cut[3]),+ ("dddd............", "d..d............", "................")+ );+ assert!(draw(&["pixels", path, "l1", "--tile", "2,1"]).contains("tile 2,1 (its top left is canvas pixel 32,16)"));+ assert!(refused(&["pixels", path, "l1", "--tile", "3,0"]).contains("3 by 2 tiles"));++ let art = dir.join("game").join("art");+ let (named, told) = both(&["export", path, "--tileset", art.to_str().unwrap()]);+ assert!(+ named.contains("ground-tiles.png") && named.contains("ground-tiles.tres"),+ "{named}"+ );+ assert!(+ told.contains("2 tiles of 16x16 (3 across, 2 down, 4 empty left out)"),+ "{told}"+ );+ assert!(told.contains("texture filter to Nearest"), "{told}");+ let tres = std::fs::read_to_string(art.join("ground-tiles.tres")).unwrap();+ assert!(+ tres.contains("tile_size = Vector2i(16, 16)") && tres.contains("0:0/0 = 0") && tres.contains("2:1/0 = 0"),+ "{tres}"+ );+ let png = std::fs::read(art.join("ground-tiles.png")).unwrap();+ assert_eq!(u32::from_be_bytes(png[16..20].try_into().unwrap()), 48);+ draw(&["export", path, "--tileset"]);++ draw(&["canvas", path, "--tile", "off"]);+ assert!(!draw(&["canvas", path]).contains("tiles of"));+ assert!(refused(&["export", path, "--tileset"]).contains("not cut into tiles"));+ assert!(refused(&["pixels", path, "l1", "--tile", "0,0"]).contains("not cut into tiles"));+ draw(&["canvas", path, "--tile", "24x16", "--wrap", "on"]);+ assert!(draw(&["canvas", path]).contains("wraps at its edges tiles of 24x16, 2 across and 2 down"));+ std::fs::remove_dir_all(&dir).unwrap();+}+#[test]fn recolour_moves_strokes_together_and_keeps_their_shades() {let dir = std::env::temp_dir().join(format!("draw-binary-recolour-{}", std::process::id()));diff --git a/crates/core/src/bundle.rs b/crates/core/src/bundle.rsindex b8ac1d8..2526de2 100644--- a/crates/core/src/bundle.rs+++ b/crates/core/src/bundle.rs@@ -864,7 +864,12 @@ pub fn summarize(ops: &[Op]) -> String {),Op::Timeline { origin: Some(_), .. } => "timeline origin".to_string(),Op::Timeline { .. } => "timeline".to_string(),- Op::Canvas { wrap: Some(true) } => "the canvas wraps".to_string(),+ Op::Canvas {+ tile: Some(Some([w, h])),+ ..+ } => format!("tiles of {w}x{h}"),+ Op::Canvas { tile: Some(None), .. } => "no tiles".to_string(),+ Op::Canvas { wrap: Some(true), .. } => "the canvas wraps".to_string(),Op::Canvas { .. } => "the canvas stops at its edges".to_string(),Op::Atmosphere(Some(_)) => "atmosphere".to_string(),Op::Atmosphere(None) => "atmosphere off".to_string(),diff --git a/crates/core/src/doc.rs b/crates/core/src/doc.rsindex 9542271..f54520e 100644--- a/crates/core/src/doc.rs+++ b/crates/core/src/doc.rs@@ -74,6 +74,40 @@ pub struct Canvas {pub background: Option<String>,#[serde(default, skip_serializing_if = "is_false")]pub wrap: bool,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub tile: Option<[u32; 2]>,+}++impl Canvas {+ pub fn cut(&self, tile: [u32; 2]) -> Result<()> {+ let [tw, th] = tile;+ if tw == 0 || th == 0 || tw > self.width || th > self.height {+ bail!("tiles of {tw}x{th} do not fit a {}x{} canvas", self.width, self.height);+ }+ if !self.width.is_multiple_of(tw) || !self.height.is_multiple_of(th) {+ bail!(+ "a {}x{} canvas does not cut into tiles of {tw}x{th}: each side has to be a whole number of tiles",+ self.width,+ self.height+ );+ }+ Ok(())+ }++ pub fn tiles(&self) -> Option<(u32, u32)> {+ self.tile+ .map(|[tw, th]| (self.width / tw.max(1), self.height / th.max(1)))+ }++ pub fn tile_at(&self, column: u32, row: u32) -> Result<[u32; 4]> {+ let (Some([tw, th]), Some((columns, rows))) = (self.tile, self.tiles()) else {+ bail!("this drawing is not cut into tiles: klad canvas <bundle> --tile 16 sets the tile size");+ };+ if column >= columns || row >= rows {+ bail!("tile {column},{row} is past the drawing's {columns} by {rows} tiles (the first is 0,0)");+ }+ Ok([column * tw, row * th, tw, th])+ }}#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]@@ -1099,6 +1133,7 @@ impl Document {height,background: None,wrap: false,+ tile: None,},timeline: Timeline::default(),palette: Vec::new(),@@ -1460,6 +1495,9 @@ impl Document {if let Some(bg) = &self.canvas.background {check_color(bg).context("canvas background")?;}+ if let Some(tile) = self.canvas.tile {+ self.canvas.cut(tile)?;+ }let mut swatch_names = BTreeSet::new();let mut swatch_ids = BTreeSet::new();self.palette.iter().try_for_each(|swatch| {diff --git a/crates/core/src/ops.rs b/crates/core/src/ops.rsindex 1f192e6..3feb5c6 100644--- a/crates/core/src/ops.rs+++ b/crates/core/src/ops.rs@@ -144,6 +144,7 @@ pub enum Op {},Canvas {wrap: Option<bool>,+ tile: Option<Option<[u32; 2]>>,},Atmosphere(Option<crate::look::Atmosphere>),Frames(FrameSpec),@@ -1828,6 +1829,22 @@ impl Op {Some(Value::Bool(wrap)) => Some(wrap),Some(other) => bail!("wrap takes true or false, not {other}"),},+ tile: match map.remove("tile") {+ None => None,+ Some(Value::Null) | Some(Value::Bool(false)) => Some(None),+ Some(Value::Number(side)) => {+ let side = side+ .as_u64()+ .ok_or_else(|| anyhow!("tile takes a whole number of pixels, [width, height] or null"))?+ as u32;+ Some(Some([side, side]))+ }+ Some(other) => {+ Some(Some(serde_json::from_value(other).map_err(|_| {+ anyhow!("tile takes a whole number of pixels, [width, height] or null")+ })?))+ }+ },},"timeline" => Op::Timeline {fps: whole(&mut map, "fps")?,@@ -4205,11 +4222,21 @@ pub fn apply(doc: &mut Document, op: &Op, out: &mut Applied) -> Result<()> {doc.atmosphere = air.clone();out.changed.push("atmosphere".into());}- Op::Canvas { wrap } => {- let Some(wrap) = wrap else {- bail!("canvas needs \"wrap\": true or false (a tile that repeats at its edges)");- };- doc.canvas.wrap = *wrap;+ Op::Canvas { wrap, tile } => {+ if wrap.is_none() && tile.is_none() {+ bail!(+ "canvas needs \"wrap\": true or false (a drawing that repeats at its edges), or \"tile\": the size of its tiles as 16 or [16, 16], null for none"+ );+ }+ if let Some(wrap) = wrap {+ doc.canvas.wrap = *wrap;+ }+ if let Some(tile) = tile {+ if let Some(size) = tile {+ doc.canvas.cut(*size)?;+ }+ doc.canvas.tile = *tile;+ }out.changed.push("canvas".into());}Op::Timeline { fps, frames, origin } => {@@ -5052,6 +5079,51 @@ mod tests {);}+ #[test]+ fn a_canvas_is_cut_into_tiles_that_fit_it_whole() {+ let mut doc = Document::new(48, 32);+ let run = |doc: &mut Document, value: Value| apply(doc, &Op::parse(value).unwrap(), &mut Applied::default());+ run(&mut doc, json!({"op":"canvas","tile":16})).unwrap();+ assert_eq!((doc.canvas.tile, doc.canvas.tiles()), (Some([16, 16]), Some((3, 2))));+ assert_eq!(doc.canvas.tile_at(2, 1).unwrap(), [32, 16, 16, 16]);+ assert!(+ doc.canvas+ .tile_at(3, 0)+ .unwrap_err()+ .to_string()+ .contains("3 by 2 tiles")+ );+ run(&mut doc, json!({"op":"canvas","tile":[24, 8],"wrap":true})).unwrap();+ assert_eq!((doc.canvas.tile, doc.canvas.wrap), (Some([24, 8]), true));+ let odd = format!("{:#}", run(&mut doc, json!({"op":"canvas","tile":10})).unwrap_err());+ assert!(odd.contains("does not cut into tiles of 10x10"), "{odd}");+ assert!(run(&mut doc, json!({"op":"canvas","tile":[64, 8]})).is_err());+ assert_eq!(+ doc.canvas.tile,+ Some([24, 8]),+ "a size that does not fit changes nothing"+ );+ run(&mut doc, json!({"op":"canvas","tile":null})).unwrap();+ assert_eq!(+ (doc.canvas.tile, doc.canvas.wrap),+ (None, true),+ "taking the tiles away leaves the rest"+ );+ assert!(+ doc.canvas+ .tile_at(0, 0)+ .unwrap_err()+ .to_string()+ .contains("not cut into tiles")+ );+ assert!(run(&mut doc, json!({"op":"canvas"})).is_err());+ doc.canvas.tile = Some([7, 7]);+ assert!(+ doc.validate().is_err(),+ "a drawing whose tiles do not fit is not opened"+ );+ }+#[test]fn in_betweens_poses_weights_and_bones_say_why_they_do_not_take_pixel_layers() {let (doc, _) = apply_all(diff --git a/crates/render/src/sprites.rs b/crates/render/src/sprites.rsindex 83f3398..e066443 100644--- a/crates/render/src/sprites.rs+++ b/crates/render/src/sprites.rs@@ -431,6 +431,28 @@ pub fn sprite_frames(res: &SpriteFrames) -> String {out}+pub struct TileSet<'a> {+ pub uid: &'a str,+ pub texture: &'a Texture,+ pub tile: [u32; 2],+ pub tiles: &'a [(u32, u32)],+}++pub fn tile_set(set: &TileSet) -> String {+ let uid = set+ .texture+ .uid+ .as_deref()+ .map_or(String::new(), |u| format!(" uid={}", quoted(u)));+ let [w, h] = set.tile;+ let tiles: String = set.tiles.iter().map(|(x, y)| format!("{x}:{y}/0 = 0\n")).collect();+ format!(+ "[gd_resource type=\"TileSet\" load_steps=3 format=3 uid={}]\n\n[ext_resource type=\"Texture2D\"{uid} path={} id=\"1_tiles\"]\n\n[sub_resource type=\"TileSetAtlasSource\" id=\"TileSetAtlasSource_1\"]\ntexture = ExtResource(\"1_tiles\")\ntexture_region_size = Vector2i({w}, {h})\n{tiles}\n[resource]\ntile_size = Vector2i({w}, {h})\nsources/0 = SubResource(\"TileSetAtlasSource_1\")\n",+ quoted(set.uid),+ quoted(&set.texture.path),+ )+}+pub struct Scene<'a> {pub uid: &'a str,pub node: &'a str,diff --git a/docs/DESIGN.md b/docs/DESIGN.mdindex bd1fe35..a45dc2c 100644--- a/docs/DESIGN.md+++ b/docs/DESIGN.md@@ -1,4 +1,4 @@-_Last updated: 2026-11-12 17:00_+_Last updated: 2026-11-12 19:30_# klad: design@@ -232,7 +232,7 @@ Unknown keys are errors that list the valid ones, so a typo never passes silentlEvery layer has `blend`, `opacity`, `visible`, `locked`, optional `mask`, `clip` and (M5, format 8) `effects`. Effects are layer settings, not a layer kind: the planned `filter` kind became them.-- **Pixel layers (M9).** A pixel layer is a paint layer flagged `pixel`, so it shares cels, masks, clipping, lock alpha, effects, the timeline and every export with paint layers. One pixel is one canvas pixel: a 64x64 sprite is a 64x64 drawing shown enlarged, and a drawing never mixes pixel sizes. Its marks stay data, as strokes do: a pixel mark is a fill record whose source is cells (`FillSource::Cells`), a set of whole pixels (coverage 0 or 255) with the id of the palette swatch it was drawn with, or a set of pixels to erase. So the same addresses, `set`, `rm`, `transform`, lasso, copy and history work on them; scaling, flipping and turning sample the nearest pixel (`markedit::resampled` with `hard`), which also makes an export above full size hard-edged. Colours are palette entries: `Document::bind_swatch` finds or adds the swatch and gives it an `id` the first time a mark uses it, and `set color=` on a pixel mark binds it to the new entry. The `pixel` op (`klad pixel`) is the first way to make marks; brush strokes and flood or lasso fills are refused on a pixel layer (`ops::off_the_grid`). A drawing with a pixel layer (`Document::pixel_art`) gets a sharp view on both sides. In the editor the zoom moves in whole screen pixels per pixel above real size (`View::whole`, `View::fit_whole`; free below it), a pixel grid shows from 8 screen pixels per pixel (a dark line with light dashes, so it reads on any colour; View > Pixel grid), the pixel under the pointer is outlined on a pixel layer and named in the status line, and the Real size pane (`Pane::Preview`, opened the first time a pixel drawing is opened) shows the composed frame at 1, 2 or 4 screen pixels per pixel for drawings up to 512 px. In the CLI, `klad render` and edit previews enlarge by a whole number to about 512 px (`agent::pixel_scale`), and `--overlay grid` draws the same lines with the pixel numbers along the top and left (`overlay::draw_cells`). The palette is what a pixel drawing is bound to. A mark stores its swatch's id and its colour, so every reader of a stroke file draws it without the palette; when a palette edit changes a swatch's colour, `ops::follow_palette` adds a `MarkChange::Entry` for every pixel drawing, which rewrites the colour of the marks bound to that swatch in the same transaction (one undo step), and a removed swatch unbinds its marks. A palette rewritten without ids keeps them by name, then by colour (`carry_ids`). Swatches carry an optional `ramp` name: a ramp is the swatches sharing it, in palette order, dark to light (`palettes::ramp` makes one from a base colour with `color::value_step`, darker and cooler to lighter and warmer). Palettes that come with klad are colour lists in `core/src/palettes.rs` (`klad palettes`), and `palettes::parse` reads a list of hex colours or a GIMP palette. The pencil is grid geometry in `core/src/pixel.rs`, shared by both hands: `line` (Bresenham), `extend` (a run that follows the pen with no holes), `perfect` (drops the corner pixel of an L, so a hand-drawn line stays one pixel thin), `stamp` (a size is a square of whole pixels) and `of_path` (SVG path data flattened and traced; corners the path asks for are kept, the corners that flattening a curve leaves are not). The `pixel` op takes `cells` or a `path`, and a `size`. In the editor the brush tool on a pixel layer is the pencil (the eraser command and the pen's eraser end erase): the run is drawn over the canvas as it grows and committed on release as one `pixel` op marked as made by hand, so the palette binding, history and sync are the op's. Shift click draws a straight line from the last pixel; `[` and `]` change the size. An agent reads and writes a pixel layer as text, which is exact where a picture is not. `pixel::grid_of` works out what a drawing's marks show, pixel by pixel (later marks over earlier ones, erasing marks, lock alpha, cuts), as the palette entry or the colour of each pixel; `pixel::legend` gives each one a character (the first letter of its name where free) and `pixel::ruled` or `pixel::plain` print the rows (`klad pixels`). The other way, `pixel::parse_text` reads a legend and rows and the grid form of the `pixel` op (`rows`, `legend`, `at`) turns each character into one mark bound to its colour (`klad pixel --grid`), so what `klad pixels --plain` prints draws the same picture again. Text grids are the agent's side only: a person draws with the pencil. Shapes and fills are the same op with other sources: `line`, `rect` and `ellipse` (the ellipse that fits a box of pixels, by an integer midpoint walk, so even and odd sizes stay symmetric; `filled` takes the rows between its outline) are pure geometry in `core/src/pixel.rs`; `fill` is a flood over what the drawing shows (`pixel::flood` on the grid of `grid_of`: pixels joined to the seed with exactly its entry or colour, four neighbours or eight), reading this layer, another pixel layer or all of them merged. A flood needs the marks, which an op cannot read, so `Bundle::settle_pixels` turns every `fill` into its cells before the ops are applied, walking the batch so a fill sees the marks the ops before it made; `Bundle::apply_as` calls it, so the CLI, `klad apply` and the editor share it. In the editor the fill tool floods on a click and the shape tool drags a rectangle, an ellipse or a line of pixels on a pixel layer, previewed as the pixels it will make. Editing pixel marks reuses the selection and transform of strokes and fills, with three differences that keep the grid. A lasso that cuts would leave a supersampled cut on a mark (a soft edge), so `markedit::split` divides a pixel mark's coverage between whole pixels instead, by pixel middles, and the two halves carry no cut. A transform whose matrix is whole numbers (flips, quarter turns, whole scales) is rounded onto the grid in `transform_fill` (`on_the_grid`: matrix and offset rounded), so every pixel lands on a pixel whatever the pivot and marks transformed together still fit; other transforms sample the nearest pixel. Recolouring pixel marks gives each exactly the target colour and its palette entry, where paint marks keep their shades. In the editor the stroke tool on a pixel layer drags a box (or a loop) that snaps out to whole pixels and takes pixels, its box is the selected area, drags move by whole pixels, scale by whole numbers and turn by quarters (`Drag.whole`), and Select same colour takes every mark of the selected marks' palette entries. Shading builds on ramps. `shade` (a number of ramp steps) is a way to colour, not a source: for the pixels of any source, `Bundle::settled` reads what the layer shows and makes one mark per target colour, each pixel taking the swatch `Document::ramp_step` gives for its own (pixels in no ramp, or at its end, are left). `dither` keeps the pixels a 4x4 Bayer pattern fixed to the canvas turns on for that share (`pixel::dithered`), and `second` gives the rest another colour, as a second mark. `outline` is a source: the empty pixels that touch a drawn one (or, `inside`, the drawn ones that touch an empty one) on the grid of this layer, another or all (`pixel::outline`). All three need the drawing, so they are settled in the bundle with `fill`, and `settle_pixels` may return more ops than it was given. Mark by mark, `klad recolour --step` and the selection bar's Lighter and Darker move a mark to the next swatch of its ramp, and `klad recolour --from` rebinds every mark of one colour. A colour's character in the text view is fixed by its place in the palette, not by which colours are in use. Two things multiply what is drawn. A mirror (`mirrorX`, `mirrorY` on the `pixel` op; the editor's mirror line) adds each pixel's twin across a line that stands between two pixels or through a column (`pixel::mirrored`); it is part of the op, so the mark holds both halves. Wrap is a property of the canvas (`canvas.wrap`, set by the `canvas` op): the drawing is a tile, so `PixelSpec::coverage` brings pixels past an edge back in on the other side (`pixel::wrapped`) instead of dropping them, and floods and outlines take their neighbours round the edges. It changes what is drawn, never how the drawing renders; to see the repeat, the editor draws the canvas quad three times across and down with the copies dimmed (the shader repeats the texture when the view's uniform says so) and `klad render --repeat N` tiles the finished picture. Transforms of marks do not wrap. Animation on pixel layers is the timeline as it is: drawings on frames, holds, links, clips and onion skins need nothing new, since a pixel layer is a paint layer. Two things differ. A keyed layer or group that holds only pixel layers (`Layer::grid_only`) is drawn at its key's position rounded to whole pixels and sampled nearest (`render::draw_content`), so a keyed move never softens a sprite. And the ops that move points refuse pixel layers with the reason and what to do instead (`ops::grid_refusal`, checked in `ops::apply` and before the CLI resolves anything): `inbetween`, `pose`, `weights` and attaching to bones. Exports of a pixel drawing take whole-number scales only (`export::check_scale`: 1 to `PIXEL_MAX_SCALE` 64, no side past 16384 px, checked before anything is drawn): the frame is drawn at its real size and enlarged with nearest sampling (`export::render`, the same `resample` the preview uses), so the detail of the rasters stays 1 (`export::detail_of`) and every export path (a frame, sheets, numbered frames, GIF, Godot) is sharp by the same code. Fractional scales are refused, not rounded, because a rounded scale would silently change the size asked for. The Godot scenes of a pixel drawing set `texture_filter = 1` (nearest) on the sprite, or on the root of a parallax scene, so nothing depends on the project's default filter. `render/src/gif.rs` writes animated GIFs (`klad export --gif`, the export window's GIF choice) with no new dependency: one global table of up to 255 colours plus a clear index, exact when the frames hold 255 colours or fewer (always, for palette art), median cut otherwise, each pixel then taking the nearest entry, or with `--dither` (the export window's dither box) the nearest entry of the colour moved by an 8x8 ordered pattern, offset per channel, as far as the table's entries lie apart on average (`gif::Pattern`, `spacing`); ordered and not error diffusion, so the pattern holds still from frame to frame; it is an option and off by default because flat art is cleaner without it, and it does nothing when nothing was reduced; LZW with a table reset at 4096 codes; each run of equal pictures is one frame whose delay is its duration in hundredths with the rounding error carried to the next, so the total stays right; frames replace each other (disposal 2) since they are whole pictures with clear pixels. A test reads the result back with Skia's decoder. Palette variants (`doc.variants`, S9.12) are named sets of colour overrides by swatch id. The drawing always is in one variant: the palette and the marks hold the shown variant's colours, `variants.base` keeps the base colours that variant overrides, and showing another one is an ordinary palette edit (`PaletteEdit::Variant`, through `follow_palette`), so the editor, the previews, undo and every reader of the file need nothing new and a variant can never be seen half applied. A view-only variant was the alternative; it would have needed a second set of rasters in the editor's compositor and would have left the question of which variant an edit belongs to. Here the rule is simple: a colour changed while a variant is shown is that variant's (`ops::keep_variant` records it, and drops it again when it is set back to the base colour); a variant follows the base wherever it has no colour of its own. Exports of a variant that is not shown do not touch the drawing: `Document::dress(name)` gives the colours that differ from what is shown, and `layers::dressed` replays the pixel drawings that use them with those colours (`klad export --variant`, `--variants`; file names take the variant after the drawing's name). Both paths rest on `Document::variant_colours`. Aseprite files (S9.13): `render/src/aseprite.rs` reads and writes the published binary format into a plain `Sprite` (layers with their nesting level, cels with a picture or a link, per-frame durations, tags, palette); reading turns indexed and grey pixels into RGBA (the transparent index is clear except on a background layer) and lists what it drops, writing is always RGBA with zlib cels. It was checked against files made by Aseprite itself (its public test sprites, not in the repository) and, for the writer, against an independent dump of the chunks. `cli/src/aseprite.rs` maps a sprite to a drawing and back. In: one `add layer` op per top-level layer with its children and cels (explicit cel ids, so linked cels become klad links and a cel followed by an empty frame gets a `hold`), then one pixel op per colour per cel, bound to the palette entry with that colour (file palette first, other colours added, at most 1024), tags as clips; frame times become whole frames at the lowest fps from 1 to 120 with the least error (`timing`), said when it is not exact. Out: pixel layers and groups only (others are named in a note), one file frame per stretch of timeline in which no layer starts or ends a drawing and no clip starts or ends, so holds do not multiply frames and a file that came in goes out with the frames it had; a drawing shown again is a linked cel; a pixel layer's own keyed x, y and opacity go into the cel's position and opacity (every frame is then its own). `klad import` makes the drawing, `klad export --aseprite` the file; the editor opens an Aseprite file by running `klad import` (`start::brought_in`, used by `Home::open`, so the start window, a path given at launch and the system's open all work) and has an Aseprite choice in the export window. Indexed output and tag directions are not kept on the way out. Pictures to pixels (S9.14): `render/src/pixelise.rs` decodes a picture with Skia, shrinks it by area average on premultiplied colour (`shrunk`; exact for whole-number reductions of enlarged pixel art), picks colours (`colours`: the picture's own, most used first, when few enough, else the GIF encoder's median cut, dark to light) and maps every pixel at least half solid to the nearest colour in Oklab (`mapped`). `cli/src/pixelise.rs` turns that into ordinary pixel ops, one mark per colour, so nothing new is stored: a picture file onto a pixel layer in the drawing's palette (`klad pixelize --image --to`), a picture as a new pixel drawing (`klad import x.png`), and a painted or vector layer, or the whole picture, as a new pixel drawing with every frame rendered through the export path, shrunk, and held when it equals the frame before (`klad pixelize --size`). The palette rule is the same everywhere: `--colors N` makes colours from the picture, else an existing palette of two or more solid colours is used as it is, else the picture's own colours (32 when it has more than 256, 16 for a painting). No dithering and no outline repair: the result is a start to clean up. The editor has one window for it (File > Pixels of a picture…, `editor/pixels.rs`) that runs the same command.+- **Pixel layers (M9).** A pixel layer is a paint layer flagged `pixel`, so it shares cels, masks, clipping, lock alpha, effects, the timeline and every export with paint layers. One pixel is one canvas pixel: a 64x64 sprite is a 64x64 drawing shown enlarged, and a drawing never mixes pixel sizes. Its marks stay data, as strokes do: a pixel mark is a fill record whose source is cells (`FillSource::Cells`), a set of whole pixels (coverage 0 or 255) with the id of the palette swatch it was drawn with, or a set of pixels to erase. So the same addresses, `set`, `rm`, `transform`, lasso, copy and history work on them; scaling, flipping and turning sample the nearest pixel (`markedit::resampled` with `hard`), which also makes an export above full size hard-edged. Colours are palette entries: `Document::bind_swatch` finds or adds the swatch and gives it an `id` the first time a mark uses it, and `set color=` on a pixel mark binds it to the new entry. The `pixel` op (`klad pixel`) is the first way to make marks; brush strokes and flood or lasso fills are refused on a pixel layer (`ops::off_the_grid`). A drawing with a pixel layer (`Document::pixel_art`) gets a sharp view on both sides. In the editor the zoom moves in whole screen pixels per pixel above real size (`View::whole`, `View::fit_whole`; free below it), a pixel grid shows from 8 screen pixels per pixel (a dark line with light dashes, so it reads on any colour; View > Pixel grid), the pixel under the pointer is outlined on a pixel layer and named in the status line, and the Real size pane (`Pane::Preview`, opened the first time a pixel drawing is opened) shows the composed frame at 1, 2 or 4 screen pixels per pixel for drawings up to 512 px. In the CLI, `klad render` and edit previews enlarge by a whole number to about 512 px (`agent::pixel_scale`), and `--overlay grid` draws the same lines with the pixel numbers along the top and left (`overlay::draw_cells`). The palette is what a pixel drawing is bound to. A mark stores its swatch's id and its colour, so every reader of a stroke file draws it without the palette; when a palette edit changes a swatch's colour, `ops::follow_palette` adds a `MarkChange::Entry` for every pixel drawing, which rewrites the colour of the marks bound to that swatch in the same transaction (one undo step), and a removed swatch unbinds its marks. A palette rewritten without ids keeps them by name, then by colour (`carry_ids`). Swatches carry an optional `ramp` name: a ramp is the swatches sharing it, in palette order, dark to light (`palettes::ramp` makes one from a base colour with `color::value_step`, darker and cooler to lighter and warmer). Palettes that come with klad are colour lists in `core/src/palettes.rs` (`klad palettes`), and `palettes::parse` reads a list of hex colours or a GIMP palette. The pencil is grid geometry in `core/src/pixel.rs`, shared by both hands: `line` (Bresenham), `extend` (a run that follows the pen with no holes), `perfect` (drops the corner pixel of an L, so a hand-drawn line stays one pixel thin), `stamp` (a size is a square of whole pixels) and `of_path` (SVG path data flattened and traced; corners the path asks for are kept, the corners that flattening a curve leaves are not). The `pixel` op takes `cells` or a `path`, and a `size`. In the editor the brush tool on a pixel layer is the pencil (the eraser command and the pen's eraser end erase): the run is drawn over the canvas as it grows and committed on release as one `pixel` op marked as made by hand, so the palette binding, history and sync are the op's. Shift click draws a straight line from the last pixel; `[` and `]` change the size. An agent reads and writes a pixel layer as text, which is exact where a picture is not. `pixel::grid_of` works out what a drawing's marks show, pixel by pixel (later marks over earlier ones, erasing marks, lock alpha, cuts), as the palette entry or the colour of each pixel; `pixel::legend` gives each one a character (the first letter of its name where free) and `pixel::ruled` or `pixel::plain` print the rows (`klad pixels`). The other way, `pixel::parse_text` reads a legend and rows and the grid form of the `pixel` op (`rows`, `legend`, `at`) turns each character into one mark bound to its colour (`klad pixel --grid`), so what `klad pixels --plain` prints draws the same picture again. Text grids are the agent's side only: a person draws with the pencil. Shapes and fills are the same op with other sources: `line`, `rect` and `ellipse` (the ellipse that fits a box of pixels, by an integer midpoint walk, so even and odd sizes stay symmetric; `filled` takes the rows between its outline) are pure geometry in `core/src/pixel.rs`; `fill` is a flood over what the drawing shows (`pixel::flood` on the grid of `grid_of`: pixels joined to the seed with exactly its entry or colour, four neighbours or eight), reading this layer, another pixel layer or all of them merged. A flood needs the marks, which an op cannot read, so `Bundle::settle_pixels` turns every `fill` into its cells before the ops are applied, walking the batch so a fill sees the marks the ops before it made; `Bundle::apply_as` calls it, so the CLI, `klad apply` and the editor share it. In the editor the fill tool floods on a click and the shape tool drags a rectangle, an ellipse or a line of pixels on a pixel layer, previewed as the pixels it will make. Editing pixel marks reuses the selection and transform of strokes and fills, with three differences that keep the grid. A lasso that cuts would leave a supersampled cut on a mark (a soft edge), so `markedit::split` divides a pixel mark's coverage between whole pixels instead, by pixel middles, and the two halves carry no cut. A transform whose matrix is whole numbers (flips, quarter turns, whole scales) is rounded onto the grid in `transform_fill` (`on_the_grid`: matrix and offset rounded), so every pixel lands on a pixel whatever the pivot and marks transformed together still fit; other transforms sample the nearest pixel. Recolouring pixel marks gives each exactly the target colour and its palette entry, where paint marks keep their shades. In the editor the stroke tool on a pixel layer drags a box (or a loop) that snaps out to whole pixels and takes pixels, its box is the selected area, drags move by whole pixels, scale by whole numbers and turn by quarters (`Drag.whole`), and Select same colour takes every mark of the selected marks' palette entries. Shading builds on ramps. `shade` (a number of ramp steps) is a way to colour, not a source: for the pixels of any source, `Bundle::settled` reads what the layer shows and makes one mark per target colour, each pixel taking the swatch `Document::ramp_step` gives for its own (pixels in no ramp, or at its end, are left). `dither` keeps the pixels a 4x4 Bayer pattern fixed to the canvas turns on for that share (`pixel::dithered`), and `second` gives the rest another colour, as a second mark. `outline` is a source: the empty pixels that touch a drawn one (or, `inside`, the drawn ones that touch an empty one) on the grid of this layer, another or all (`pixel::outline`). All three need the drawing, so they are settled in the bundle with `fill`, and `settle_pixels` may return more ops than it was given. Mark by mark, `klad recolour --step` and the selection bar's Lighter and Darker move a mark to the next swatch of its ramp, and `klad recolour --from` rebinds every mark of one colour. A colour's character in the text view is fixed by its place in the palette, not by which colours are in use. Two things multiply what is drawn. A mirror (`mirrorX`, `mirrorY` on the `pixel` op; the editor's mirror line) adds each pixel's twin across a line that stands between two pixels or through a column (`pixel::mirrored`); it is part of the op, so the mark holds both halves. Wrap is a property of the canvas (`canvas.wrap`, set by the `canvas` op): the drawing is a tile, so `PixelSpec::coverage` brings pixels past an edge back in on the other side (`pixel::wrapped`) instead of dropping them, and floods and outlines take their neighbours round the edges. It changes what is drawn, never how the drawing renders; to see the repeat, the editor draws the canvas quad three times across and down with the copies dimmed (the shader repeats the texture when the view's uniform says so) and `klad render --repeat N` tiles the finished picture. Transforms of marks do not wrap. Animation on pixel layers is the timeline as it is: drawings on frames, holds, links, clips and onion skins need nothing new, since a pixel layer is a paint layer. Two things differ. A keyed layer or group that holds only pixel layers (`Layer::grid_only`) is drawn at its key's position rounded to whole pixels and sampled nearest (`render::draw_content`), so a keyed move never softens a sprite. And the ops that move points refuse pixel layers with the reason and what to do instead (`ops::grid_refusal`, checked in `ops::apply` and before the CLI resolves anything): `inbetween`, `pose`, `weights` and attaching to bones. Exports of a pixel drawing take whole-number scales only (`export::check_scale`: 1 to `PIXEL_MAX_SCALE` 64, no side past 16384 px, checked before anything is drawn): the frame is drawn at its real size and enlarged with nearest sampling (`export::render`, the same `resample` the preview uses), so the detail of the rasters stays 1 (`export::detail_of`) and every export path (a frame, sheets, numbered frames, GIF, Godot) is sharp by the same code. Fractional scales are refused, not rounded, because a rounded scale would silently change the size asked for. The Godot scenes of a pixel drawing set `texture_filter = 1` (nearest) on the sprite, or on the root of a parallax scene, so nothing depends on the project's default filter. `render/src/gif.rs` writes animated GIFs (`klad export --gif`, the export window's GIF choice) with no new dependency: one global table of up to 255 colours plus a clear index, exact when the frames hold 255 colours or fewer (always, for palette art), median cut otherwise, each pixel then taking the nearest entry, or with `--dither` (the export window's dither box) the nearest entry of the colour moved by an 8x8 ordered pattern, offset per channel, as far as the table's entries lie apart on average (`gif::Pattern`, `spacing`); ordered and not error diffusion, so the pattern holds still from frame to frame; it is an option and off by default because flat art is cleaner without it, and it does nothing when nothing was reduced; LZW with a table reset at 4096 codes; each run of equal pictures is one frame whose delay is its duration in hundredths with the rounding error carried to the next, so the total stays right; frames replace each other (disposal 2) since they are whole pictures with clear pixels. A test reads the result back with Skia's decoder. Palette variants (`doc.variants`, S9.12) are named sets of colour overrides by swatch id. The drawing always is in one variant: the palette and the marks hold the shown variant's colours, `variants.base` keeps the base colours that variant overrides, and showing another one is an ordinary palette edit (`PaletteEdit::Variant`, through `follow_palette`), so the editor, the previews, undo and every reader of the file need nothing new and a variant can never be seen half applied. A view-only variant was the alternative; it would have needed a second set of rasters in the editor's compositor and would have left the question of which variant an edit belongs to. Here the rule is simple: a colour changed while a variant is shown is that variant's (`ops::keep_variant` records it, and drops it again when it is set back to the base colour); a variant follows the base wherever it has no colour of its own. Exports of a variant that is not shown do not touch the drawing: `Document::dress(name)` gives the colours that differ from what is shown, and `layers::dressed` replays the pixel drawings that use them with those colours (`klad export --variant`, `--variants`; file names take the variant after the drawing's name). Both paths rest on `Document::variant_colours`. Aseprite files (S9.13): `render/src/aseprite.rs` reads and writes the published binary format into a plain `Sprite` (layers with their nesting level, cels with a picture or a link, per-frame durations, tags, palette); reading turns indexed and grey pixels into RGBA (the transparent index is clear except on a background layer) and lists what it drops, writing is always RGBA with zlib cels. It was checked against files made by Aseprite itself (its public test sprites, not in the repository) and, for the writer, against an independent dump of the chunks. `cli/src/aseprite.rs` maps a sprite to a drawing and back. In: one `add layer` op per top-level layer with its children and cels (explicit cel ids, so linked cels become klad links and a cel followed by an empty frame gets a `hold`), then one pixel op per colour per cel, bound to the palette entry with that colour (file palette first, other colours added, at most 1024), tags as clips; frame times become whole frames at the lowest fps from 1 to 120 with the least error (`timing`), said when it is not exact. Out: pixel layers and groups only (others are named in a note), one file frame per stretch of timeline in which no layer starts or ends a drawing and no clip starts or ends, so holds do not multiply frames and a file that came in goes out with the frames it had; a drawing shown again is a linked cel; a pixel layer's own keyed x, y and opacity go into the cel's position and opacity (every frame is then its own). `klad import` makes the drawing, `klad export --aseprite` the file; the editor opens an Aseprite file by running `klad import` (`start::brought_in`, used by `Home::open`, so the start window, a path given at launch and the system's open all work) and has an Aseprite choice in the export window. Indexed output and tag directions are not kept on the way out. Pictures to pixels (S9.14): `render/src/pixelise.rs` decodes a picture with Skia, shrinks it by area average on premultiplied colour (`shrunk`; exact for whole-number reductions of enlarged pixel art), picks colours (`colours`: the picture's own, most used first, when few enough, else the GIF encoder's median cut, dark to light) and maps every pixel at least half solid to the nearest colour in Oklab (`mapped`). `cli/src/pixelise.rs` turns that into ordinary pixel ops, one mark per colour, so nothing new is stored: a picture file onto a pixel layer in the drawing's palette (`klad pixelize --image --to`), a picture as a new pixel drawing (`klad import x.png`), and a painted or vector layer, or the whole picture, as a new pixel drawing with every frame rendered through the export path, shrunk, and held when it equals the frame before (`klad pixelize --size`). The palette rule is the same everywhere: `--colors N` makes colours from the picture, else an existing palette of two or more solid colours is used as it is, else the picture's own colours (32 when it has more than 256, 16 for a painting). No dithering and no outline repair: the result is a start to clean up. The editor has one window for it (File > Pixels of a picture…, `editor/pixels.rs`) that runs the same command. Tilesets (S9.15): `canvas.tile` is the size of the tiles a drawing is cut into, and nothing else is stored: a tile is a region of the one canvas (`Canvas::tile_at(column, row)`), so every tool, layer, frame and palette works on a tileset as on any drawing, and the cut can be changed or taken away without touching a mark. The canvas has to be a whole number of tiles each way (`Canvas::cut`, checked by the op and when a drawing is opened), which keeps tile addresses and the export exact. The CLI reads and draws one tile at a time (`klad pixels --tile`, `klad pixel --grid --tile`), the editor draws the tile lines over the canvas at any zoom and sets the size in View > Tileset: cut into tiles…, and `klad export --tileset` (the export window's tile set button) renders the frame and writes a Godot `TileSet` with one `TileSetAtlasSource` and a tile for every cell with anything in it (`sprites::tile_set`), into the drawing's Godot folder with a kept uid; a test loads it in Godot. Not there: animated tiles, per-tile wrapping, collision or terrain data, margins between tiles.- **Blend modes.** `normal`, `multiply`, `screen`, `overlay`, `add`, and since M5 `color-dodge`, `soft-light`, `hard-light`, `lighten`, `darken`, `color`, `luminosity`, all as in the W3C compositing spec (Skia's modes; `look::blend_rgb` and `look::composite` hold the formulas the tests check them against).- **Effects (M5).** `"effects": [{"glow": {...}}, {"outline": {...}}]`, applied in order to the layer's content (after its mask; for a clip base, to the base and its clipped layers together) before its opacity and blend: `blur` (radius, a Gaussian sigma), `glow` (radius, strength, threshold: 0 glows from every pixel, higher only from the bright ones; color: a tint; blend: how the glow mixes with what is under the layer, screen by default, normal lays it like paint under the layer), `outline` (width, color, inside), `shadow` (x, y, radius, color, laid under the layer), `noise` (amount, size, seed, mono: a grain fixed to the canvas), `displace` (amount, size, seed, by: smooth waves, or a layer whose red pushes across and green down), `relief` (strength, light, highlight, shade, softness: lights the paint height of the layer's drawings, below). Each effect knows its reach (`look::reach`), so a tile is composed from its content within the tile plus that margin and tiles meet without seams (noise and haze read only their own pixel and add no margin, so they cost no neighbouring tiles); a tile skips a clip stack or group that puts no pixel in it (none of its rasters, live tiles or onion ghosts has a tile in the tile grown by its effects' margin; layers moved by keys, adjustment layers and vector layers drawn from their nodes always count), which leaves the tile the same since every blend leaves the pixels under a transparent layer as they are; the pixels are computed in Rust (`klad-render/effects.rs`) on f32 with absolute coordinates, so a tile equals the same pixels of the whole image byte for byte (tested). Blurs use a direct kernel, below a sigma of 2 at full size and above it on a grid of 2, 4, ... px blocks anchored to the canvas, then sampled back.- **Adjustment layers (M5).** An `adjust` layer changes what is under it in its list: the layers below it in its group, or, clipped, its base. A group holding an adjustment is composed apart, so the adjustment stays inside it. The colour math is on unpremultiplied sRGB values with alpha kept: `hsl` (hue in degrees, saturation and lightness -1..1), `levels` (black, white, gamma, low, high), `curves` (points, and red, green, blue applied before them; monotone cubic, no overshoot), `balance` (shadows, midtones, highlights: cyan to red, magenta to green, yellow to blue, keepLight), `gradient-map` (stops by brightness). The layer's opacity, blend and mask decide how much of the adjusted colour replaces the colour under it. `fill` (a solid or gradient paint) is drawn like a content layer instead, with the layer's blend.diff --git a/docs/cli.md b/docs/cli.mdindex 362fc94..d6a0db5 100644--- a/docs/cli.md+++ b/docs/cli.md@@ -11,7 +11,7 @@ This reference is licensed under the MIT License (`LICENSE-MIT`), unlike klad it- [`klad import`](#klad-import): Open an Aseprite file or a picture as a klad pixel drawing- [`klad pixelize`](#klad-pixelize): Make pixels of a picture or of a painted or vector layer- [`klad new`](#klad-new): Create an empty bundle with paint layers-- [`klad canvas`](#klad-canvas): The canvas: its size and background, and whether it wraps at its edges+- [`klad canvas`](#klad-canvas): The canvas: its size and background, whether it wraps at its edges, and the size of its tiles- [`klad frames`](#klad-frames): Exposure sheet: a row per frame, a column per layer (top first)- [`klad frame`](#klad-frame): Insert or remove frames in every layer or the listed ones- [`klad arcs`](#klad-arcs): Track marks, parts or points across frames: positions, spacing, ground contacts, feet crossing@@ -242,6 +242,9 @@ Options:--wrapA tile: what is drawn past an edge comes back in on the other side+ --tile <SIZE>+ Cut the drawing into tiles of this size, 16 or 16x24: a tileset (the canvas has to be a whole number of tiles each way)+-h, --helpPrint help```@@ -254,7 +257,13 @@ The canvas: its size and background, and whether it wraps at its edges. On a canklad canvas tile.kladklad canvas tile.klad --wrap on-As an op: {"op":"canvas","wrap":true}.+A drawing can also be cut into tiles of one size, a tileset: --tile 16 (or 16x24) sets the size, which the canvas has to be a whole number of each way, and --tile off takes it away. klad pixels and klad pixel --grid then take --tile column,row to read and draw one tile at a time, the editor shows the tile lines, and klad export --tileset writes a Godot TileSet.++ klad canvas tiles.klad --tile 16+ klad pixels tiles.klad l1 --tile 2,0 --plain+ klad export tiles.klad --tileset ../game/art++As an op: {"op":"canvas","wrap":true}, {"op":"canvas","tile":16}, {"op":"canvas","tile":[16,24]}, {"op":"canvas","tile":null}.Usage: klad canvas [OPTIONS] <BUNDLE>@@ -268,6 +277,9 @@ Options:[possible values: on, off]+ --tile <SIZE>+ Cut the drawing into tiles of this size, 16 or 16x24 (off: no tiles); the canvas has to be a whole number of tiles each way+--renderRender a preview after the edit and print its path@@ -1920,6 +1932,9 @@ Options:[default: 0,0]+ --tile <COLUMN,ROW>+ With --grid, in a drawing cut into tiles: put the grid's top left on that tile's (0,0 is the first tile)+--path <PATH>SVG path data drawn as a line of pixels, one pixel wide with no doubled corners on curves: 'M3.5 20.5 C 10 4 22 4 28.5 20.5'@@ -3451,6 +3466,9 @@ Options:--json+ --tile <COLUMN,ROW>+ In a drawing cut into tiles: only that tile (0,0 is the first), with pixels counted from its own top left+-h, --helpPrint help (see a summary with '-h')```@@ -3487,6 +3505,7 @@ Animations (each clip, or the whole timeline when there are no clips):klad export art.klad --frames run numbered full-size PNGs, one per frame (run-0000.png ...) in art-run/klad export art.klad --gif [run] [--scale 8] an animated GIF with each frame's own duration: one per clip (art-run.gif; clips that loop, loop), or art.gif of the whole timeline; up to 255 colours kept exactly, more are reduced to the nearest of 255, in flat areas of one colour or, with --dither, mixed in a fine even pattern that keeps gradients smooth; transparent unless --backgroundklad export art.klad --aseprite art.aseprite: the pixel layers and groups, the drawing of every frame (holds and links as linked cels), the palette and clips as tags, in RGBA; frames that show the same drawings are one frame with their time added up. Paint and vector layers are left out and named. klad import opens such a file+ klad export art.klad --tileset ../game/art a drawing cut into tiles (klad canvas --tile 16) as a Godot TileSet: art-tiles.png and art-tiles.tres with one atlas source and a tile for every cell that is not empty; --frame, --scale and --variant choose what is shownklad 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). For a pixel drawing the scenes set texture_filter to nearest, so the sprite stays sharp in the game. 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.Usage: klad export [OPTIONS] <BUNDLE>@@ -3534,6 +3553,9 @@ Options:--asepriteAn Aseprite file of the drawing's pixel layers: groups, the drawing of every frame, the palette and clips as tags+ --tileset [<TILESET>]+ A Godot TileSet of a drawing cut into tiles (klad canvas --tile): the picture and a .tres with a tile for every cell that is not empty, into this folder (default: the document's export.godot)+--godot [<GODOT>]Godot SpriteFrames and AnimatedSprite2D scene into this folder (default: the document's export.godot)diff --git a/docs/format.md b/docs/format.mdindex 2573041..ac7658d 100644--- a/docs/format.md+++ b/docs/format.md@@ -1,4 +1,4 @@-_Last updated: 2026-11-12 11:00 (format `klad/7`, stroke files `KLST` version 3, brushes `klad-brush/1`)_+_Last updated: 2026-11-12 19:30 (format `klad/7`, stroke files `KLST` version 3, brushes `klad-brush/1`)_# The klad drawing format@@ -61,7 +61,7 @@ Writers replace files atomically (write a temporary file, then rename), so a rea| Key | Type | Default | Meaning ||---|---|---|---|| `format` | string | | `"klad/7"` |-| `canvas` | object | | `width`, `height` (px), `background` (a colour; none is transparent), `wrap` (bool, default false: the drawing is a tile, and klad brings pixel marks drawn past an edge back in on the other side; it changes nothing about how the drawing renders) |+| `canvas` | object | | `width`, `height` (px), `background` (a colour; none is transparent), `wrap` (bool, default false: the drawing is a tile, and klad brings pixel marks drawn past an edge back in on the other side; it changes nothing about how the drawing renders); `tile` ([width, height] in px, left out when there is none: the drawing is cut into tiles of that size, a tileset, and each side of the canvas is a whole number of them) || `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), optional `ramp` (the name of the ramp it belongs to) || `variants` | object | none | palette variants (below): `sets`, `shown` and `base`; left out when the drawing has none |@@ -368,4 +368,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), palette swatches with an `id` (2026-11-11), and palette `variants` (2026-11-12). Older drawings open unchanged. |+| `klad/7` | pixel layers: paint layers with `pixel`, pixel marks in stroke files (version 3), palette swatches with an `id` (2026-11-11), palette `variants` and `canvas.tile` (2026-11-12). Older drawings open unchanged. |diff --git a/docs/skill/SKILL.md b/docs/skill/SKILL.mdindex e9affbd..2aed2ec 100644--- a/docs/skill/SKILL.md+++ b/docs/skill/SKILL.md@@ -143,6 +143,7 @@ klad export sprite.klad --scale 8 -o [email protected] square pixels, to keep- Animation is frame by frame: a pixel layer holds a drawing per frame like a paint layer (`klad add sprite.klad cel --in l1 frame=2`, then `klad pixel ... --frame 2`; `klad duplicate`, links, holds, clips and `--overlay onion` all work). To make the next frame, read the last one (`klad pixels sprite.klad l1 --frame 0 --plain`), change the text and write it to the new frame. Keying a pixel layer (`klad key sprite.klad l1 --frame 4 x=6`) moves it by whole pixels: positions in between are rounded, so a slow move steps a pixel at a time. `klad inbetween`, `klad pose`, `klad weights` and `klad attach` refuse pixel layers and say why: they move points and bend strokes, which would take pixels off the grid.- Palette variants are other colours for the same sprite (teams, seasons, a hurt flash, day and night): `klad palette sprite.klad --new-variant blue` makes one and shows it, and every colour you change while it is shown (`--recolour team --to '#2a6fdb'`, `--add` with an existing name) is blue's own; the base palette keeps its colours, and a variant follows the base for every colour it has not changed. `--variant base` (or `--variant blue`) shows another one: the pixels stay the same marks, only their colours change, as one undo step. `klad palette sprite.klad` lists what is shown and each variant's own colours; `--rename-variant blue --to navy` and `--rm-variant navy` do what they say. Draw in the base palette and bind the parts that will change to their own palette colours (a `team` colour and its shades, not the same red that is also used for the mouth), or a variant changes more than you meant. Export without switching: `klad export sprite.klad --variant blue` renders that variant whatever is shown (file names get `-blue` after the drawing's name), and `--variants` exports the base and every variant in one go; both work with `--sheet`, `--frames`, `--gif` and `--godot`. Variants recolour pixel marks only: strokes on paint layers and vector shapes store their own colours.- Exports stay sharp: a pixel drawing exports at whole-number scales only (`--scale 1` to 64, at most 16384 px a side), enlarged pixel for pixel, never smoothed; `--scale 2.5` is refused with the reason. That holds for `klad export` of a frame, `--sheet`, `--frames`, `--gif` and `--godot` (sheet cells and the Godot offset are scaled with it; the Godot scenes set `texture_filter` to nearest so the sprite stays sharp in the game). To show a sprite to someone, `klad export sprite.klad --gif --scale 8`; in a game, export at `--scale 1` and let the engine enlarge it.+- Tilesets. A drawing can be cut into tiles of one size: `klad new ground.klad --pixel 64x48 --tile 16` (or `klad canvas ground.klad --tile 16`, `16x24` for other shapes, `--tile off` to undo); each side of the canvas has to be a whole number of tiles, and `klad canvas ground.klad` says how many there are. Work one tile at a time: `klad pixels ground.klad l1 --tile 2,0 --plain` reads the tile in column 2 of row 0 with its pixels counted from its own corner, and `klad pixel ground.klad l1 --grid - --tile 2,0` draws a grid there (`--at` then moves it inside the tile); every other command still uses canvas pixels, and a tile's corner is column times width, row times height. Keep each tile inside its own cell, and check seams by reading two neighbours: a tile's last column has to meet the next tile's first. `klad export ground.klad --tileset ../game/art` writes a Godot TileSet (`ground-tiles.png` and `ground-tiles.tres`, one atlas source, a tile for every cell that is not empty; `--scale`, `--frame` and `--variant` as for other exports; the folder is the drawing's Godot folder once given). In Godot the TileMapLayer's texture filter has to be Nearest for pixel tiles. `--wrap` is a different thing: it makes the whole canvas one repeating tile.- Pictures to pixels. `klad pixelize sprite.klad --image ref.png --to l1` puts a PNG or JPEG on a pixel layer: every pixel takes the nearest colour of the drawing's palette (so it lands in the colours the sprite has; `--colors N` makes N colours from the picture and adds them instead), `--size 48` shrinks it to 48 px on its longest side first (each pixel the average of the area it covers; a picture enlarged by a whole number comes back exact; pixels less than half solid stay empty), `--at x,y` places its top left, `--frame` picks the drawing. `klad import ref.png [--size N] [--colors N]` makes a new pixel drawing from a picture, with the picture's own colours as its palette (reduced to 32 when it has more than 256). `klad pixelize hero.klad --size 64 [--layer body] [--colors 12] [-o out.klad]` makes a new pixel drawing (`hero-pixel.klad`) of a painted or vector layer or of the whole picture, every frame with one set of colours, frames that come out the same held, clips kept; the drawing itself is not changed. All three give marks bound to palette colours, one per colour, so the result is edited like anything else here. Treat it as a start, not a finish: shrinking blurs edges into in-between colours and breaks one-pixel outlines, so look at it at real size, then redraw the outline, and cut stray colours with `klad recolour --from a --to b`.- Aseprite files: `klad import hero.aseprite` (or `.ase`; `-o` names the drawing) makes `hero.klad` next to the file: image layers as pixel layers with their name, visibility, opacity and blend mode, groups as groups, every cel as a drawing on its frame (linked cels stay links), the palette with its names, tags as clips. Frame times become whole frames at the slowest speed that fits (100 ms frames are 10 fps; a 300 ms frame holds for three). Indexed, grey and RGBA files all open, every pixel bound to its palette colour. It says what it leaves out: tilemap layers, tilesets, slices, tag directions other than forwards, blend modes klad lacks. `klad export hero.klad --aseprite` writes the pixel layers and groups back (RGBA; holds and links as linked cels, clips as tags, a pixel layer's keyed moves and opacity baked into its cels; `--variant` and `--variants` work); paint, vector and other layers are left out and named. Use it to hand work to someone who uses Aseprite, or to take over a sprite made there.- Each mark, `<cel>:s<id>`, stays editable: `klad set sprite.klad c2:s1 color=shadow` recolours it (and binds it to that entry), `klad transform ... --move 2,0` moves it by whole pixels, `--flip h` and `--rotate 90` keep it hard, `klad rm` removes it. `klad strokes sprite.klad l1` lists the marks with their entry and cell count; `--json` gives each one's `cells`.