Skip to content

armgit / klad

Public Imported from GitHub
0

A drawing app built for agent/human collaboration

Rust

Aseprite files in and out

Indicode BV44ccc0cb0d93
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5d6e8f1..337ee83 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.
+- 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`.
- Exports that stay sharp, and GIFs. A pixel drawing exports at whole-number sizes only, up to 64 times (`klad export sprite.klad --scale 8`), enlarged pixel for pixel; the export window shows **times real size** and the size in pixels. Sheets, numbered frames and Godot exports follow the same rule, and the Godot scenes of a pixel drawing turn texture filtering off. New for every drawing: `klad export art.klad --gif` and **GIF** in the export window write an animated GIF for each clip, or one of the whole timeline, with each frame's own duration. A GIF holds 255 colours: `--dither` (the **dither** box) mixes them in a fine pattern so the soft gradients of a painting do not band.
- Animating pixel layers. Frames, holds, links, clips and onion skins work on pixel layers as on paint layers. A keyed pixel layer moves by whole pixels and stays sharp. In-betweens, poses, weights and bones refuse pixel layers and say why: they move points and bend strokes, so draw the frames or key the layer's position.
diff --git a/crates/app/src/editor/export.rs b/crates/app/src/editor/export.rs
index 18e6f9c..f46bc0b 100644
--- a/crates/app/src/editor/export.rs
+++ b/crates/app/src/editor/export.rs
@@ -12,6 +12,7 @@ pub(super) enum What {
Frames,
Sheet,
Gif,
+ Aseprite,
}
#[derive(Clone, Debug, PartialEq)]
@@ -60,11 +61,16 @@ pub(super) fn args(bundle: &Path, home: &Path, frame: u32, form: &Form) -> Vec<S
What::Frames => push("--frames", Some(form.range.trim().to_string())),
What::Sheet => push("--sheet", Some(form.range.trim().to_string())),
What::Gif => push("--gif", Some(form.range.trim().to_string())),
+ What::Aseprite => push("--aseprite", None),
}
- if let Some(layer) = form.layer.as_ref().filter(|_| form.what != What::Frames) {
+ if let Some(layer) = form
+ .layer
+ .as_ref()
+ .filter(|_| !matches!(form.what, What::Frames | What::Aseprite))
+ {
push("--layer", Some(layer.clone()));
}
- if form.scale != 1.0 {
+ if form.scale != 1.0 && form.what != What::Aseprite {
push("--scale", Some(form.scale.to_string()));
}
if form.deep && matches!(form.what, What::Image | What::Sheet) {
@@ -95,7 +101,14 @@ fn written(out: &str, err: &str) -> String {
out.lines()
.chain(err.lines())
.map(str::trim)
- .filter(|l| l.ends_with(".png") || l.ends_with(".json") || l.ends_with(".gif") || l.contains(" in all"))
+ .filter(|l| {
+ l.ends_with(".png")
+ || l.ends_with(".json")
+ || l.ends_with(".gif")
+ || l.ends_with(".aseprite")
+ || l.starts_with("note: ")
+ || l.contains(" in all")
+ })
.take(3)
.collect::<Vec<_>>()
.join("; ")
@@ -104,7 +117,7 @@ fn written(out: &str, err: &str) -> String {
impl Editor {
pub(super) fn export(&mut self) -> Result<()> {
let form = self.export.clone();
- if form.what != What::Image && form.range.trim().is_empty() {
+ if !matches!(form.what, What::Image | What::Aseprite) && form.range.trim().is_empty() {
bail!("say which frames: all, a clip's name or a range like 0-11");
}
let args = args(&self.scene.bundle.root, &self.bundle_home(), self.scene.frame, &form);
@@ -113,6 +126,7 @@ impl Editor {
What::Frames => format!("export frames {}", form.range.trim()),
What::Sheet => format!("export the sheet of {}", form.range.trim()),
What::Gif => format!("export a GIF of {}", form.range.trim()),
+ What::Aseprite => "export an Aseprite file".to_string(),
};
self.start_job(Spec {
tag: Tag::Export,
@@ -163,8 +177,15 @@ impl Editor {
.hint("sheet pages and Aseprite JSON");
ui.selectable_value(&mut form.what, What::Gif, "GIF")
.hint("an animated GIF: one for each clip, or one of the whole timeline");
+ if pixel || form.what == What::Aseprite {
+ ui.selectable_value(&mut form.what, What::Aseprite, "Aseprite")
+ .hint("an .aseprite file of the pixel layers: groups, every frame's drawing, the palette, and clips as tags");
+ }
});
- if form.what != What::Frames {
+ if form.what == What::Aseprite {
+ ui.weak("pixel layers and groups only; frames that show the same drawings become one frame");
+ }
+ if !matches!(form.what, What::Frames | What::Aseprite) {
let shown = form
.layer
.as_ref()
@@ -181,7 +202,7 @@ impl Editor {
.response
.hint("export the whole image or one layer or group");
}
- if form.what != What::Image {
+ if !matches!(form.what, What::Image | What::Aseprite) {
ui.horizontal(|ui| {
let label = ui.label("frames");
ui.add(
@@ -199,6 +220,7 @@ impl Editor {
});
}
match pixel {
+ _ if form.what == What::Aseprite => {}
true => {
form.scale = form.scale.round().clamp(1.0, most);
ui.add(
@@ -358,6 +380,25 @@ mod tests {
args(bundle, home, 0, &gif).join(" "),
"export /w/art.klad --gif hop --scale 8 --background --dither"
);
+ let file = Form {
+ what: What::Aseprite,
+ scale: 4.0,
+ layer: Some("l2".into()),
+ range: String::new(),
+ variant: "blue".into(),
+ ..Form::default()
+ };
+ assert_eq!(
+ args(bundle, home, 0, &file).join(" "),
+ "export /w/art.klad --aseprite --variant blue"
+ );
+ assert_eq!(
+ written(
+ "/w/art.aseprite\n",
+ "16x12, 1 layers, 2 frames\nnote: left out, since an Aseprite file holds only pixel layers: notes\n"
+ ),
+ "/w/art.aseprite; note: left out, since an Aseprite file holds only pixel layers: notes"
+ );
let every = Form {
what: What::Sheet,
variant: EVERY.into(),
diff --git a/crates/app/src/home.rs b/crates/app/src/home.rs
index 0cd9067..fb0a2a5 100644
--- a/crates/app/src/home.rs
+++ b/crates/app/src/home.rs
@@ -118,6 +118,8 @@ impl Home {
}
pub(crate) fn open(&mut self, ctx: &egui::Context, path: &Path) -> Result<()> {
+ let (made, told) = start::brought_in(path)?;
+ let path = made.as_path();
let mut settings = self
.editor
.as_ref()
@@ -126,6 +128,9 @@ impl Home {
if let Some(words) = self.start.as_mut().and_then(|s| s.repaired.take()) {
editor.say(Tone::Done, words);
}
+ if let Some(words) = told {
+ editor.say(Tone::Done, words);
+ }
settings.opened(path);
settings.offer_real_size(editor.scene.bundle.doc.pixel_art());
editor.settings = settings.clone();
@@ -551,6 +556,81 @@ mod tests {
std::fs::remove_dir_all(&dir).unwrap();
}
+ #[test]
+ fn an_aseprite_file_opens_as_a_drawing_made_next_to_it() {
+ use klad_render::aseprite::{Cel, Layer, Picture, Sprite, Tag};
+ let dir = folder("aseprite");
+ let file = dir.join("hero.aseprite");
+ let sprite = Sprite {
+ width: 8,
+ height: 8,
+ layers: vec![Layer::image("body", 0)],
+ durations: vec![100, 100],
+ cels: vec![Cel {
+ layer: 0,
+ frame: 0,
+ x: 1,
+ y: 1,
+ opacity: 255,
+ picture: Picture::Pixels {
+ width: 2,
+ height: 1,
+ rgba: vec![255, 0, 0, 255, 0, 0, 255, 255],
+ },
+ }],
+ tags: vec![Tag {
+ name: "idle".into(),
+ from: 0,
+ to: 1,
+ direction: 2,
+ repeat: 0,
+ }],
+ ..Sprite::default()
+ };
+ std::fs::write(&file, klad_render::aseprite::write(&sprite).unwrap()).unwrap();
+ let mut first = home(&dir, &[]);
+ first.begin(&egui::Context::default(), None);
+ let mut h = harness(first);
+ let ctx = h.ctx.clone();
+ h.state_mut().open(&ctx, &file).unwrap();
+ h.run_steps(3);
+ assert_eq!(opened(&h), dir.join("hero.klad"));
+ {
+ let doc = &h.state().editor.as_ref().unwrap().scene.bundle.doc;
+ assert!(doc.pixel_art());
+ assert_eq!((doc.timeline.frames, doc.timeline.fps), (2, 10));
+ assert_eq!(doc.layers[0].name, "body");
+ assert_eq!(doc.timeline.clips[0].name, "idle");
+ assert_eq!(doc.palette.len(), 2, "the two colours it uses are its palette");
+ }
+ assert!(
+ h.query_all_by_label_contains("made hero.klad from hero.aseprite")
+ .count()
+ > 0,
+ "the editor says what it made"
+ );
+ assert!(
+ h.query_all_by_label_contains("plays forwards").count() > 0,
+ "and what did not come over"
+ );
+ h.state_mut().open(&ctx, &file).unwrap();
+ h.run_steps(2);
+ assert_eq!(opened(&h), dir.join("hero.klad"));
+ assert!(
+ h.query_all_by_label_contains("made from hero.aseprite before").count() > 0,
+ "a second time it opens the drawing it made"
+ );
+ let broken = dir.join("broken.ase");
+ std::fs::write(&broken, b"not a sprite").unwrap();
+ let error = format!("{:#}", h.state_mut().open(&ctx, &broken).unwrap_err());
+ assert!(error.contains("not an Aseprite file"), "{error}");
+ assert!(!dir.join("broken.klad").exists());
+ assert!(
+ start::foreign(&file) && !start::foreign(&dir.join("hero.klad")) && !start::foreign(&dir.join("gone.ase"))
+ );
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
+
#[test]
fn a_drawing_the_system_asks_to_open_opens_from_the_start_window() {
let dir = folder("finder");
diff --git a/crates/app/src/start.rs b/crates/app/src/start.rs
index e910112..35f7399 100644
--- a/crates/app/src/start.rs
+++ b/crates/app/src/start.rs
@@ -453,6 +453,14 @@ impl Start {
{
picked = picker::choose_folder(Some(&settings.drawings_folder()), "Open");
}
+ if picker::NATIVE
+ && ui
+ .add(egui::Button::new("Choose an Aseprite file...").min_size(vec2(200.0, 28.0)))
+ .on_hover_text("an .aseprite or .ase file opens as a new klad drawing next to it")
+ .clicked()
+ {
+ picked = picker::choose_file(Some(&settings.drawings_folder()), "Open");
+ }
ui.add_space(6.0);
let label = ui.label(RichText::new("Or paste its path").color(theme::WEAK));
ui.horizontal(|ui| {
@@ -467,7 +475,11 @@ impl Start {
picked = Some(expand(self.path.trim()));
}
});
+ ui.label(RichText::new("The path of an Aseprite file (.aseprite, .ase) works too.").color(theme::WEAK));
let path = picked?;
+ if foreign(&path) {
+ return Some(path);
+ }
match openable(&path) {
Ok(()) => Some(path),
Err(e) => {
@@ -634,6 +646,52 @@ pub fn expand(text: &str) -> PathBuf {
}
}
+pub fn foreign(path: &Path) -> bool {
+ path.is_file()
+ && path
+ .extension()
+ .and_then(|e| e.to_str())
+ .is_some_and(|e| e.eq_ignore_ascii_case("aseprite") || e.eq_ignore_ascii_case("ase"))
+}
+
+pub fn brought_in(path: &Path) -> Result<(PathBuf, Option<String>)> {
+ if !foreign(path) {
+ return Ok((path.to_path_buf(), None));
+ }
+ let name = |p: &Path| p.file_name().map_or(String::new(), |n| n.to_string_lossy().to_string());
+ let target = path.with_extension("klad");
+ if target.join("doc.json").is_file() {
+ let told = format!(
+ "opened {}, the drawing made from {} before; rename or remove it to bring the file in again",
+ name(&target),
+ name(path)
+ );
+ return Ok((target, Some(told)));
+ }
+ let Some(exe) = draw_binary() else {
+ bail!(
+ "the klad command line tool is missing next to the editor, so an Aseprite file cannot be opened: install klad again (it ships both)"
+ );
+ };
+ let out = std::process::Command::new(exe).arg("import").arg(path).output()?;
+ let said = String::from_utf8_lossy(&out.stderr).to_string();
+ if !out.status.success() {
+ bail!("{}", said.trim().trim_start_matches("error: "));
+ }
+ let made = String::from_utf8_lossy(&out.stdout)
+ .lines()
+ .last()
+ .map(|line| PathBuf::from(line.trim()))
+ .filter(|p| p.join("doc.json").is_file())
+ .ok_or_else(|| anyhow::anyhow!("klad import did not say which drawing it made"))?;
+ let notes: Vec<&str> = said.lines().filter_map(|line| line.strip_prefix("note: ")).collect();
+ let told = match notes.is_empty() {
+ true => format!("made {} from {}", name(&made), name(path)),
+ false => format!("made {} from {}; {}", name(&made), name(path), notes.join("; ")),
+ };
+ Ok((made, Some(told)))
+}
+
pub fn openable(path: &Path) -> Result<()> {
if path.as_os_str().is_empty() {
bail!("paste the path of a .klad folder");
diff --git a/crates/cli/src/aseprite.rs b/crates/cli/src/aseprite.rs
new file mode 100644
index 0000000..ba63815
--- /dev/null
+++ b/crates/cli/src/aseprite.rs
@@ -0,0 +1,703 @@
+use crate::layers::{dress_of, variant_tag};
+use crate::sprites::{bundle_dir, bundle_stem};
+use anyhow::{Context, Result, bail};
+use klad_core::bundle::{Blank, Bundle, write_atomic};
+use klad_core::color::parse_hex;
+use klad_core::doc::{Blend, Clip, Document, Layer, Swatch};
+use klad_core::ops::{ClipEdit, Op, PaletteEdit, PixelSpec};
+use klad_render::aseprite::{Cel, Colour, Picture, Sprite, Tag};
+use serde_json::{Value, json};
+use std::collections::{BTreeMap, BTreeSet};
+use std::fs;
+use std::path::{Path, PathBuf};
+
+const MOST_COLOURS: usize = 1024;
+const MOST_FPS: u32 = 120;
+
+const BLENDS: [(u16, Blend); 12] = [
+ (0, Blend::Normal),
+ (1, Blend::Multiply),
+ (2, Blend::Screen),
+ (3, Blend::Overlay),
+ (4, Blend::Darken),
+ (5, Blend::Lighten),
+ (6, Blend::ColorDodge),
+ (8, Blend::HardLight),
+ (9, Blend::SoftLight),
+ (14, Blend::Color),
+ (15, Blend::Luminosity),
+ (16, Blend::Add),
+];
+
+pub fn is_file(path: &Path) -> bool {
+ path.extension()
+ .and_then(|e| e.to_str())
+ .is_some_and(|e| e.eq_ignore_ascii_case("aseprite") || e.eq_ignore_ascii_case("ase"))
+}
+
+pub struct Timing {
+ pub fps: u32,
+ pub spans: Vec<u32>,
+ pub exact: bool,
+}
+
+pub fn timing(durations: &[u16]) -> Timing {
+ let spans_at = |fps: u32| -> Vec<u32> {
+ durations
+ .iter()
+ .map(|d| ((*d as f64 * fps as f64 / 1000.0).round() as u32).max(1))
+ .collect()
+ };
+ let off = |fps: u32| -> f64 {
+ spans_at(fps)
+ .iter()
+ .zip(durations)
+ .map(|(span, d)| (*span as f64 * 1000.0 / fps as f64 - *d as f64).abs())
+ .sum()
+ };
+ let fps = (1..=MOST_FPS)
+ .min_by(|a, b| off(*a).total_cmp(&off(*b)).then(a.cmp(b)))
+ .unwrap_or(12);
+ Timing {
+ fps,
+ spans: spans_at(fps),
+ exact: off(fps) < 0.5,
+ }
+}
+
+fn hex_of(rgba: [u8; 4]) -> String {
+ match rgba[3] {
+ 255 => format!("#{:02x}{:02x}{:02x}", rgba[0], rgba[1], rgba[2]),
+ a => format!("#{:02x}{:02x}{:02x}{a:02x}", rgba[0], rgba[1], rgba[2]),
+ }
+}
+
+fn swatches(palette: &[Colour]) -> Vec<Swatch> {
+ let mut names = BTreeSet::new();
+ palette
+ .iter()
+ .map(|colour| {
+ let name = colour.name.trim().trim_start_matches('#').to_string();
+ Swatch {
+ color: hex_of(colour.rgba),
+ name: match name.is_empty() || !names.insert(name.clone()) {
+ true => String::new(),
+ false => name,
+ },
+ id: String::new(),
+ ramp: String::new(),
+ }
+ })
+ .collect()
+}
+
+struct Placed {
+ id: String,
+ cels: BTreeMap<u16, String>,
+}
+
+fn real_cel(sprite: &Sprite, layer: u16, frame: u16) -> Option<&Cel> {
+ let mut at = frame;
+ (0..sprite.durations.len()).find_map(|_| {
+ let cel = sprite.cels.iter().find(|c| c.layer == layer && c.frame == at)?;
+ match &cel.picture {
+ Picture::Link(to) if *to != at => {
+ at = *to;
+ None
+ }
+ Picture::Link(_) => None,
+ Picture::Pixels { .. } => Some(cel),
+ }
+ })
+}
+
+fn layer_json(
+ sprite: &Sprite,
+ at: usize,
+ starts: &[u32],
+ spans: &[u32],
+ ids: &mut impl FnMut(char) -> String,
+ placed: &mut BTreeMap<u16, Placed>,
+ notes: &mut BTreeSet<String>,
+) -> (Value, usize) {
+ let layer = &sprite.layers[at];
+ let id = ids('l');
+ let blend = BLENDS.iter().find(|(n, _)| *n == layer.blend).map(|(_, b)| *b);
+ if blend.is_none() {
+ notes.insert(format!(
+ "layer {} has a blend mode klad does not have: it blends as normal",
+ layer.name
+ ));
+ }
+ let mut value = json!({
+ "id": id,
+ "name": layer.name,
+ "visible": layer.visible,
+ "opacity": layer.opacity as f32 / 255.0,
+ "blend": blend.unwrap_or_default(),
+ });
+ if layer.reference {
+ value["reference"] = Value::from(true);
+ }
+ let mut next = at + 1;
+ if layer.group {
+ let mut children = Vec::new();
+ while next < sprite.layers.len() && sprite.layers[next].level > layer.level {
+ let (child, after) = layer_json(sprite, next, starts, spans, ids, placed, notes);
+ if !sprite.layers[next].tilemap {
+ children.push(child);
+ }
+ next = after;
+ }
+ value["kind"] = Value::from("group");
+ value["children"] = Value::Array(children);
+ return (value, next);
+ }
+ let index = at as u16;
+ let frames: Vec<u16> = (0..sprite.durations.len() as u16)
+ .filter(|f| sprite.cels.iter().any(|c| c.layer == index && c.frame == *f))
+ .collect();
+ let mut made: BTreeMap<u16, String> = BTreeMap::new();
+ let cels: Vec<Value> = frames
+ .iter()
+ .map(|&frame| {
+ let cel_id = ids('c');
+ let own = sprite
+ .cels
+ .iter()
+ .find(|c| c.layer == index && c.frame == frame)
+ .is_some_and(|c| matches!(c.picture, Picture::Pixels { .. }));
+ let source = real_cel(sprite, index, frame).map(|c| c.frame);
+ let mut cel = json!({ "id": cel_id, "frame": starts[frame as usize] });
+ match (own, source.and_then(|s| made.get(&s))) {
+ (false, Some(link)) => cel["link"] = Value::from(link.clone()),
+ _ => {
+ made.insert(frame, cel_id.clone());
+ }
+ }
+ if !frames.contains(&(frame + 1)) && (frame as usize + 1) < sprite.durations.len() {
+ cel["hold"] = Value::from(spans[frame as usize]);
+ }
+ cel
+ })
+ .collect();
+ value["kind"] = Value::from("pixel");
+ if !cels.is_empty() {
+ value["cels"] = Value::Array(cels);
+ }
+ placed.insert(index, Placed { id, cels: made });
+ (value, next)
+}
+
+fn clip_names(tags: &[Tag]) -> Vec<String> {
+ let mut taken = BTreeSet::new();
+ tags.iter()
+ .enumerate()
+ .map(|(i, tag)| {
+ let wanted = match tag.name.trim() {
+ "" => format!("tag {}", i + 1),
+ name => name.to_string(),
+ };
+ let name = std::iter::once(wanted.clone())
+ .chain((2..).map(|n| format!("{wanted} {n}")))
+ .find(|n| !taken.contains(n))
+ .unwrap_or(wanted);
+ taken.insert(name.clone());
+ name
+ })
+ .collect()
+}
+
+pub fn import(file: &Path, out: Option<PathBuf>) -> Result<PathBuf> {
+ let bytes = fs::read(file).with_context(|| format!("reading {}", file.display()))?;
+ let sprite = klad_render::aseprite::read(&bytes).with_context(|| file.display().to_string())?;
+ let target = out.unwrap_or_else(|| file.with_extension("klad"));
+ if target.exists() {
+ bail!(
+ "{} is there already: give the drawing another name with -o",
+ target.display()
+ );
+ }
+ if sprite.durations.is_empty() {
+ bail!("{} holds no frames", file.display());
+ }
+ let mut notes: BTreeSet<String> = sprite
+ .notes
+ .iter()
+ .map(|n| format!("{n} are not carried over"))
+ .collect();
+ let timed = timing(&sprite.durations);
+ if !timed.exact {
+ notes.insert(format!(
+ "frame times were rounded to whole frames at {} a second",
+ timed.fps
+ ));
+ }
+ let starts: Vec<u32> = timed
+ .spans
+ .iter()
+ .scan(0u32, |at, span| {
+ let start = *at;
+ *at += span;
+ Some(start)
+ })
+ .collect();
+ let total: u32 = timed.spans.iter().sum();
+ let (width, height) = (sprite.width as u32, sprite.height as u32);
+ let mut bundle = Bundle::blank(
+ &target,
+ &Blank {
+ width,
+ height,
+ layers: 0,
+ fps: timed.fps,
+ frames: total,
+ pixel: true,
+ ..Blank::default()
+ },
+ "cli",
+ )?;
+ let tag = bundle.doc.here.tag.clone();
+ let mut counter = bundle.doc.next_id;
+ let mut ids = |prefix: char| {
+ counter += 1;
+ format!("{prefix}{counter}{tag}")
+ };
+ let mut placed: BTreeMap<u16, Placed> = BTreeMap::new();
+ let mut tree = Vec::new();
+ let mut at = 0;
+ while at < sprite.layers.len() {
+ let (value, next) = layer_json(&sprite, at, &starts, &timed.spans, &mut ids, &mut placed, &mut notes);
+ if !sprite.layers[at].tilemap {
+ tree.push(value);
+ }
+ at = next;
+ }
+ if placed.is_empty() {
+ bail!("{} holds no image layers to bring in", file.display());
+ }
+ let palette = swatches(&sprite.palette);
+ let known: BTreeMap<[u8; 4], usize> = sprite
+ .palette
+ .iter()
+ .enumerate()
+ .rev()
+ .map(|(i, c)| (c.rgba, i))
+ .collect();
+ let mut strangers: BTreeSet<[u8; 4]> = BTreeSet::new();
+ let pixels: Vec<Op> = sprite
+ .cels
+ .iter()
+ .filter_map(|cel| match &cel.picture {
+ Picture::Pixels { width, rgba, .. } => Some((cel, (*width as i64).max(1), rgba)),
+ Picture::Link(_) => None,
+ })
+ .filter_map(|(cel, w, rgba)| {
+ let owner = placed.get(&cel.layer)?;
+ let frame = starts[cel.frame as usize];
+ owner.cels.get(&cel.frame)?;
+ let mut by_colour: BTreeMap<[u8; 4], Vec<[i64; 2]>> = BTreeMap::new();
+ rgba.as_chunks::<4>().0.iter().enumerate().for_each(|(i, px)| {
+ let alpha = (px[3] as u32 * cel.opacity as u32 + 127) / 255;
+ let (x, y) = (cel.x as i64 + i as i64 % w, cel.y as i64 + i as i64 / w);
+ let inside = x >= 0 && y >= 0 && x < width as i64 && y < height as i64;
+ if alpha > 0 && inside {
+ by_colour
+ .entry([px[0], px[1], px[2], alpha as u8])
+ .or_default()
+ .push([x, y]);
+ }
+ });
+ Some(
+ by_colour
+ .into_iter()
+ .map(|(colour, cells)| {
+ let key = match known.get(&colour) {
+ Some(index) => index.to_string(),
+ None => {
+ strangers.insert(colour);
+ hex_of(colour)
+ }
+ };
+ Op::Pixel(PixelSpec {
+ layer: owner.id.clone(),
+ frame,
+ color: Some(key),
+ cells,
+ ..PixelSpec::default()
+ })
+ })
+ .collect::<Vec<_>>(),
+ )
+ })
+ .flatten()
+ .collect();
+ if strangers.len() > MOST_COLOURS {
+ let _ = fs::remove_dir_all(&target);
+ bail!(
+ "{} uses {} colours that are not in its palette: klad draws pixel art with palette colours, at most {MOST_COLOURS} new ones are added. Reduce its colours first (in Aseprite: Sprite > Color Mode > Indexed)",
+ file.display(),
+ strangers.len()
+ );
+ }
+ if !strangers.is_empty() {
+ notes.insert(format!(
+ "{} colours that were not in the file's palette were added to it",
+ strangers.len()
+ ));
+ }
+ let names = clip_names(&sprite.tags);
+ let last = sprite.durations.len() - 1;
+ let clips = sprite.tags.iter().zip(&names).map(|(tag, name)| {
+ let (from, to) = ((tag.from as usize).min(last), (tag.to as usize).min(last));
+ if tag.direction != 0 {
+ notes.insert(format!(
+ "tag {name} plays backwards or back and forth in the file: the clip plays forwards"
+ ));
+ }
+ Op::Clip(ClipEdit::Add(Clip::new(
+ name,
+ starts[from.min(to)],
+ starts[to.max(from)] + timed.spans[to.max(from)] - 1,
+ tag.repeat == 0,
+ )))
+ });
+ let ops: Vec<Op> = (!palette.is_empty())
+ .then_some(Op::Palette(PaletteEdit::Set { swatches: palette }))
+ .into_iter()
+ .map(Ok)
+ .chain(
+ tree.into_iter()
+ .map(|layer| Op::parse(json!({ "op": "add", "layer": layer }))),
+ )
+ .chain(pixels.into_iter().map(Ok))
+ .chain(clips.collect::<Vec<_>>().into_iter().map(Ok))
+ .collect::<Result<_>>()?;
+ let applied = bundle.apply(&ops).and_then(|_| bundle.stamp("cli"));
+ if let Err(error) = applied {
+ let _ = fs::remove_dir_all(&target);
+ return Err(error.context(format!("bringing in {}", file.display())));
+ }
+ let doc = &bundle.doc;
+ eprintln!(
+ "{}x{}, {} layers, {} frames at {} fps, {} palette colours, {} clips",
+ doc.canvas.width,
+ doc.canvas.height,
+ doc.all_layers().len(),
+ doc.timeline.frames,
+ doc.timeline.fps,
+ doc.palette.len(),
+ doc.timeline.clips.len()
+ );
+ notes.iter().for_each(|note| eprintln!("note: {note}"));
+ Ok(target)
+}
+
+fn rgba8(color: [f32; 4]) -> [u8; 4] {
+ color.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8)
+}
+
+fn listed<'a>(layers: &'a [Layer], level: u16, out: &mut Vec<(&'a Layer, u16)>, skipped: &mut Vec<String>) {
+ layers.iter().for_each(|layer| match layer.children().is_empty() {
+ true if layer.pixel() => out.push((layer, level)),
+ true => skipped.push(layer.name.clone()),
+ false => {
+ let before = out.len();
+ out.push((layer, level));
+ listed(layer.children(), level + 1, out, skipped);
+ if out.len() == before + 1 {
+ out.pop();
+ }
+ }
+ });
+}
+
+fn ms(frame: u32, fps: u32) -> u32 {
+ ((frame as u64 * 1000 + fps as u64 / 2) / fps as u64) as u32
+}
+
+pub fn sprite_of(bundle: &Bundle, variant: Option<&str>) -> Result<(Sprite, Vec<String>)> {
+ let doc: &Document = &bundle.doc;
+ let (width, height) = (doc.canvas.width, doc.canvas.height);
+ if width > u16::MAX as u32 || height > u16::MAX as u32 {
+ bail!("an Aseprite file is at most 65535 px a side");
+ }
+ let dress = dress_of(doc, variant)?;
+ let colour_of = |key: &str| -> Result<[u8; 4]> {
+ match (dress.get(key), doc.entry(key)) {
+ (Some(c), _) => Ok(c.map(|v| ((v as u32 * 255 + 32767) / 65535) as u8)),
+ (None, Some(swatch)) => Ok(rgba8(parse_hex(&swatch.color)?)),
+ (None, None) => Ok(rgba8(parse_hex(key)?)),
+ }
+ };
+ let mut notes: Vec<String> = Vec::new();
+ let mut skipped = Vec::new();
+ let mut kept: Vec<(&Layer, u16)> = Vec::new();
+ listed(&doc.layers, 0, &mut kept, &mut skipped);
+ if !kept.iter().any(|(l, _)| l.pixel()) {
+ bail!(
+ "this drawing has no pixel layers: an Aseprite file holds pixel art. Export a painting as a sheet (--sheet) or as numbered frames (--frames)"
+ );
+ }
+ if !skipped.is_empty() {
+ notes.push(format!(
+ "left out, since an Aseprite file holds only pixel layers: {}",
+ skipped.join(", ")
+ ));
+ }
+ let frames = doc.timeline.frames;
+ let fps = doc.timeline.fps;
+ let keyed = kept.iter().any(|(l, _)| !l.keys.is_empty());
+ let cuts: BTreeSet<u32> = match keyed {
+ true => (0..frames).collect(),
+ false => std::iter::once(0)
+ .chain(
+ kept.iter()
+ .flat_map(|(l, _)| {
+ l.cels()
+ .iter()
+ .flat_map(|c| [Some(c.frame), c.hold.map(|h| c.frame + h)])
+ })
+ .flatten(),
+ )
+ .chain(doc.timeline.clips.iter().flat_map(|c| [c.from, c.to + 1]))
+ .filter(|f| *f < frames)
+ .collect(),
+ };
+ let starts: Vec<u32> = cuts.into_iter().collect();
+ if starts.len() > u16::MAX as usize {
+ bail!("an Aseprite file holds at most 65535 frames");
+ }
+ let ends: Vec<u32> = starts.iter().skip(1).copied().chain([frames]).collect();
+ let durations: Vec<u16> = starts
+ .iter()
+ .zip(&ends)
+ .map(|(from, to)| (ms(*to, fps) - ms(*from, fps)).clamp(1, u16::MAX as u32) as u16)
+ .collect();
+ let segment_of = |frame: u32| starts.iter().rposition(|s| *s <= frame).unwrap_or(0) as u16;
+ if kept.iter().any(|(l, _)| {
+ ["rotate", "sx", "sy"].iter().any(|p| l.keys.contains_key(*p)) || (!l.pixel() && !l.keys.is_empty())
+ }) {
+ notes.push(
+ "keyed turns and scales, and keys on groups, are not carried: only a pixel layer's own moves and opacity"
+ .into(),
+ );
+ }
+ if kept
+ .iter()
+ .any(|(l, _)| l.mask.is_some() || !l.effects.is_empty() || l.clip)
+ {
+ notes.push("masks, effects and clipping are not carried".into());
+ }
+ if doc.timeline.clips.iter().any(|c| c.fps.is_some()) {
+ notes.push("clips with a speed of their own play at the drawing's speed in the file".into());
+ }
+ let mut cels: Vec<Cel> = Vec::new();
+ kept.iter()
+ .enumerate()
+ .filter(|(_, (l, _))| l.pixel())
+ .try_for_each(|(index, (layer, _))| {
+ let mut seen: BTreeMap<(String, i32, i32, u8), u16> = BTreeMap::new();
+ starts.iter().enumerate().try_for_each(|(segment, &frame)| {
+ let Some(content) = layer.content_at(frame) else {
+ return Ok(());
+ };
+ let (opacity, moved) = layer.keyed(frame);
+ let (dx, dy) = moved.map_or((0, 0), |m| (m.x.round() as i32, m.y.round() as i32));
+ let own = match layer.opacity > 0.0 {
+ true => ((opacity / layer.opacity).clamp(0.0, 1.0) * 255.0).round() as u8,
+ false => 255,
+ };
+ let key = (content.id.clone(), dx, dy, own);
+ if let Some(first) = seen.get(&key) {
+ cels.push(Cel {
+ layer: index as u16,
+ frame: segment as u16,
+ x: 0,
+ y: 0,
+ opacity: own,
+ picture: Picture::Link(*first),
+ });
+ return Ok(());
+ }
+ let marks = bundle.read_marks(&layer.id, &content.id)?;
+ let grid = klad_core::pixel::grid_of(&marks, width, height);
+ let filled: Vec<(u32, u32, &str)> = (0..height)
+ .flat_map(|y| (0..width).map(move |x| (x, y)))
+ .filter_map(|(x, y)| grid.at(x, y).map(|key| (x, y, key)))
+ .collect();
+ let (Some(left), Some(right), Some(top), Some(bottom)) = (
+ filled.iter().map(|c| c.0).min(),
+ filled.iter().map(|c| c.0).max(),
+ filled.iter().map(|c| c.1).min(),
+ filled.iter().map(|c| c.1).max(),
+ ) else {
+ return Ok(());
+ };
+ let (w, h) = (right - left + 1, bottom - top + 1);
+ let mut rgba = vec![0u8; (w * h * 4) as usize];
+ let mut colours: BTreeMap<&str, [u8; 4]> = BTreeMap::new();
+ filled.iter().try_for_each(|(x, y, key)| {
+ let colour = match colours.get(key) {
+ Some(c) => *c,
+ None => {
+ let c = colour_of(key)?;
+ colours.insert(key, c);
+ c
+ }
+ };
+ let at = (((y - top) * w + (x - left)) * 4) as usize;
+ rgba[at..at + 4].copy_from_slice(&colour);
+ Ok::<_, anyhow::Error>(())
+ })?;
+ seen.insert(key, segment as u16);
+ cels.push(Cel {
+ layer: index as u16,
+ frame: segment as u16,
+ x: (left as i32 + dx).clamp(i16::MIN as i32, i16::MAX as i32) as i16,
+ y: (top as i32 + dy).clamp(i16::MIN as i32, i16::MAX as i32) as i16,
+ opacity: own,
+ picture: Picture::Pixels {
+ width: w as u16,
+ height: h as u16,
+ rgba,
+ },
+ });
+ Ok::<_, anyhow::Error>(())
+ })
+ })?;
+ cels.sort_by_key(|c| (c.frame, c.layer));
+ let palette = doc
+ .palette
+ .iter()
+ .map(|swatch| {
+ let key = match swatch.id.is_empty() {
+ true => swatch.color.as_str(),
+ false => swatch.id.as_str(),
+ };
+ Ok(Colour {
+ rgba: colour_of(key)?,
+ name: swatch.name.clone(),
+ })
+ })
+ .collect::<Result<Vec<_>>>()?;
+ let layers = kept
+ .iter()
+ .map(|(layer, level)| klad_render::aseprite::Layer {
+ name: layer.name.clone(),
+ visible: layer.visible,
+ group: !layer.pixel(),
+ tilemap: false,
+ level: *level,
+ blend: BLENDS.iter().find(|(_, b)| *b == layer.blend).map_or(0, |(n, _)| *n),
+ opacity: (layer.opacity.clamp(0.0, 1.0) * 255.0).round() as u8,
+ reference: layer.reference,
+ background: false,
+ })
+ .collect();
+ let tags = doc
+ .timeline
+ .clips
+ .iter()
+ .map(|clip| Tag {
+ name: clip.name.clone(),
+ from: segment_of(clip.from),
+ to: segment_of(clip.to),
+ direction: 0,
+ repeat: match clip.looping {
+ true => 0,
+ false => 1,
+ },
+ })
+ .collect();
+ Ok((
+ Sprite {
+ width: width as u16,
+ height: height as u16,
+ palette,
+ layers,
+ durations,
+ cels,
+ tags,
+ notes: Vec::new(),
+ },
+ notes,
+ ))
+}
+
+pub fn export(path: &Path, out: Option<PathBuf>, variant: Option<&str>) -> Result<()> {
+ let bundle = Bundle::open(path)?;
+ let (sprite, notes) = sprite_of(&bundle, variant)?;
+ let bytes = klad_render::aseprite::write(&sprite)?;
+ let file = out.unwrap_or_else(|| {
+ bundle_dir(&bundle).join(format!("{}{}.aseprite", bundle_stem(&bundle), variant_tag(variant)))
+ });
+ write_atomic(&file, &bytes)?;
+ println!("{}", file.display());
+ eprintln!(
+ "{}x{}, {} layers, {} frames, {} cels, {} palette colours, {} tags, {:.1} KB",
+ sprite.width,
+ sprite.height,
+ sprite.layers.len(),
+ sprite.durations.len(),
+ sprite.cels.len(),
+ sprite.palette.len(),
+ sprite.tags.len(),
+ bytes.len() as f64 / 1024.0
+ );
+ notes.iter().for_each(|note| eprintln!("note: {note}"));
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn frame_times_become_whole_frames_at_the_slowest_speed_that_fits() {
+ let even = timing(&[100, 100, 100]);
+ assert_eq!((even.fps, even.spans.clone(), even.exact), (10, vec![1, 1, 1], true));
+ let held = timing(&[100, 300, 150]);
+ assert_eq!((held.fps, held.spans.clone(), held.exact), (20, vec![2, 6, 3], true));
+ let slow = timing(&[250, 250]);
+ assert_eq!((slow.fps, slow.spans.clone()), (4, vec![1, 1]));
+ let twelve = timing(&[83, 83, 84]);
+ assert_eq!(
+ (twelve.fps, twelve.spans.clone(), twelve.exact),
+ (12, vec![1, 1, 1], false)
+ );
+ let one = timing(&[1000]);
+ assert_eq!((one.fps, one.spans.clone(), one.exact), (1, vec![1], true));
+ assert_eq!(ms(3, 12) - ms(0, 12), 250);
+ assert_eq!((ms(1, 12), ms(2, 12) - ms(1, 12), ms(3, 12) - ms(2, 12)), (83, 84, 83));
+ }
+
+ #[test]
+ fn names_are_made_fit_for_klad() {
+ let tag = |name: &str| Tag {
+ name: name.into(),
+ from: 0,
+ to: 0,
+ direction: 0,
+ repeat: 0,
+ };
+ assert_eq!(
+ clip_names(&[tag("run"), tag(""), tag("run"), tag("run")]),
+ ["run", "tag 2", "run 2", "run 3"]
+ );
+ let colour = |name: &str, rgba: [u8; 4]| Colour {
+ rgba,
+ name: name.into(),
+ };
+ let made = swatches(&[
+ colour("skin", [240, 200, 160, 255]),
+ colour("skin", [1, 2, 3, 128]),
+ colour("#odd", [0, 0, 0, 255]),
+ ]);
+ let read: Vec<(&str, &str)> = made.iter().map(|s| (s.color.as_str(), s.name.as_str())).collect();
+ assert_eq!(read, [("#f0c8a0", "skin"), ("#01020380", ""), ("#000000", "odd")]);
+ assert!(
+ is_file(Path::new("a/b.ASE")) && is_file(Path::new("hero.aseprite")) && !is_file(Path::new("hero.png"))
+ );
+ }
+}
diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs
index 28b573a..c0f41d0 100644
--- a/crates/cli/src/main.rs
+++ b/crates/cli/src/main.rs
@@ -1,5 +1,6 @@
mod agent;
mod arcs;
+mod aseprite;
mod bench;
mod brushes;
mod colour;
@@ -129,6 +130,19 @@ impl Where {
#[derive(Subcommand)]
enum Command {
+ #[command(
+ about = "Open an Aseprite file as a klad drawing",
+ long_about = "Make a klad drawing from an Aseprite file (.aseprite or .ase): its layers and groups, the drawing of every frame, its palette and its tags. The drawing is written next to the file (hero.aseprite makes hero.klad) unless -o names it, and its path is printed.\n\n klad import hero.aseprite\n klad import hero.ase -o sprites/hero.klad\n\nWhat comes over: 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 linked), the palette with its names, and tags as clips. Frame times become whole frames: a file of 100 ms frames is 10 frames a second, and a frame shown for 300 ms holds for three. Indexed, grey and RGBA files all open; every pixel is bound to its palette colour, and colours a file uses outside its palette are added to it.\n\nWhat does not: tilemap layers, tilesets and slices are left out, a tag that plays backwards or back and forth becomes a clip that plays forwards, and blend modes klad does not have blend as normal. Each of these is said when it happens.\n\nklad export art.klad --aseprite writes a drawing's pixel layers back to an Aseprite file."
+ )]
+ Import {
+ file: PathBuf,
+ #[arg(
+ short,
+ long,
+ help = "The drawing to make (default: the file's name with .klad, next to it)"
+ )]
+ out: Option<PathBuf>,
+ },
#[command(about = "Create an empty bundle with paint layers")]
New {
bundle: PathBuf,
@@ -1904,7 +1918,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 --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 --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,
@@ -1948,6 +1962,12 @@ enum Command {
help = "With --gif: where a picture has more than 255 colours, mix the nearest ones in a fine even pattern so gradients do not band"
)]
dither: bool,
+ #[arg(
+ long,
+ conflicts_with_all = ["sheet", "frames", "gif", "godot", "godot_scene", "godot_rig"],
+ 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,
@@ -2469,6 +2489,15 @@ fn pixel_size(text: &str) -> Result<(u32, u32)> {
fn run() -> Result<()> {
match Cli::parse().command {
+ Command::Import { file, out } => {
+ if !aseprite::is_file(&file) {
+ return Err(anyhow!(
+ "klad import opens Aseprite files (.aseprite or .ase): {} is something else. A picture goes on a layer with klad add <bundle> layer image src=<file>",
+ file.display()
+ ));
+ }
+ println!("{}", aseprite::import(&file, out)?.display());
+ }
Command::New {
bundle,
width,
@@ -4074,6 +4103,7 @@ fn run() -> Result<()> {
frames,
gif,
dither,
+ aseprite,
godot,
store,
godot_scene,
@@ -4120,6 +4150,7 @@ fn run() -> Result<()> {
variant: variant.clone(),
};
match (&sheet, &frames, &godot) {
+ _ if aseprite => aseprite::export(&bundle, out, variant.as_deref()),
_ 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),
diff --git a/crates/cli/tests/binary.rs b/crates/cli/tests/binary.rs
index af18845..053bd9a 100644
--- a/crates/cli/tests/binary.rs
+++ b/crates/cli/tests/binary.rs
@@ -1407,6 +1407,163 @@ fn palette_variants_are_made_shown_and_exported_one_by_one() {
std::fs::remove_dir_all(&dir).unwrap();
}
+#[test]
+fn a_pixel_drawing_goes_out_to_an_aseprite_file_and_comes_back_the_same() {
+ let dir = std::env::temp_dir().join(format!("draw-binary-aseprite-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ let bundle = dir.join("hero.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()
+ };
+ draw(&["new", path, "--pixel", "12x8", "--frames", "6", "--fps", "10"]);
+ draw(&["palette", path, "--add", "#22223b", "--name", "ink"]);
+ draw(&["palette", path, "--add", "#ef233c", "--name", "red"]);
+ draw(&["palette", path, "--add", "#f0c8a080", "--name", "glow"]);
+ draw(&["set", path, "l1", "name=body"]);
+ draw(&["pixel", path, "body", "--color", "ink", "--rect", "1,4,3,3", "--filled"]);
+ draw(&["add", path, "cel", "--in", "l1", "frame=2"]);
+ draw(&[
+ "pixel", path, "body", "--frame", "2", "--color", "ink", "--rect", "1,1,3,3", "--filled",
+ ]);
+ draw(&[
+ "pixel", path, "body", "--frame", "2", "--color", "red", "--cells", "2,2",
+ ]);
+ draw(&["add", path, "cel", "--in", "l1", "frame=5", "link=c2"]);
+ let ops = dir.join("fx.jsonl");
+ std::fs::write(
+ &ops,
+ r##"{"op":"add","layer":{"kind":"group","name":"fx","opacity":0.5,"children":[{"kind":"pixel","name":"spark","blend":"screen","visible":false,"cels":[{"frame":1,"hold":2}]}]}}"##,
+ )
+ .unwrap();
+ draw(&["apply", path, "--file", ops.to_str().unwrap()]);
+ draw(&[
+ "pixel",
+ path,
+ "spark",
+ "--frame",
+ "1",
+ "--color",
+ "glow",
+ "--cells",
+ "8,1 9,1 9,2",
+ ]);
+ draw(&["add", path, "layer", "paint", "name=notes"]);
+ draw(&["clip", path, "--add", "hop", "--from", "0", "--to", "4", "--loop"]);
+ draw(&["clip", path, "--add", "land", "--from", "5", "--to", "5"]);
+
+ let (named, said) = both(&["export", path, "--aseprite"]);
+ let file = std::path::PathBuf::from(named.trim());
+ assert_eq!(file.file_name().unwrap(), "hero.aseprite");
+ assert!(said.contains("left out") && said.contains("notes"), "{said}");
+ assert!(said.contains("3 layers") && said.contains("2 tags"), "{said}");
+ let bytes = std::fs::read(&file).unwrap();
+ assert_eq!(u16::from_le_bytes([bytes[4], bytes[5]]), 0xA5E0);
+ assert_eq!(
+ u16::from_le_bytes([bytes[6], bytes[7]]),
+ 5,
+ "frames 0-1, 1 (the spark), 2, 3-4 and 5: a frame for each change, not for each klad frame"
+ );
+
+ let back = dir.join("back.klad");
+ let (_, told) = both(&["import", file.to_str().unwrap(), "-o", back.to_str().unwrap()]);
+ assert!(told.contains("6 frames at 10 fps"), "{told}");
+ let again = back.to_str().unwrap();
+ let grid = |drawing: &str, layer: &str, frame: u32| -> Vec<String> {
+ draw(&["pixels", drawing, layer, "--frame", &frame.to_string(), "--plain"])
+ .lines()
+ .skip_while(|line| !line.is_empty())
+ .skip(1)
+ .map(String::from)
+ .collect()
+ };
+ (0..6).for_each(|frame| {
+ assert_eq!(
+ grid(again, "body", frame),
+ grid(path, "body", frame),
+ "body, frame {frame}"
+ );
+ assert_eq!(
+ grid(again, "spark", frame),
+ grid(path, "spark", frame),
+ "spark, frame {frame}"
+ );
+ });
+ let listed = draw(&["ls", again]);
+ assert!(
+ listed.contains("group") && listed.contains("fx") && listed.contains("hidden"),
+ "{listed}"
+ );
+ assert!(!listed.contains("notes"));
+ let doc: serde_json::Value =
+ serde_json::from_str(&std::fs::read_to_string(back.join("doc.json")).unwrap()).unwrap();
+ let fx = doc["layers"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .find(|l| l["name"] == "fx")
+ .unwrap();
+ assert!(
+ (fx["opacity"].as_f64().unwrap() - 0.5).abs() < 0.003,
+ "the group keeps its opacity, to the nearest of 255 steps: {fx}"
+ );
+ assert_eq!(
+ fx["children"][0]["blend"], "screen",
+ "and the layer its blend mode: {fx}"
+ );
+ let colours = draw(&["palette", again]);
+ assert!(
+ colours.contains("#f0c8a080") && colours.contains("glow") && colours.contains("ink"),
+ "{colours}"
+ );
+ let timeline = draw(&["frames", again]);
+ assert!(
+ timeline.contains("clip hop frames 0 to 4") && timeline.contains("loops"),
+ "{timeline}"
+ );
+ assert!(timeline.contains("clip land frames 5 to 5"), "{timeline}");
+ assert!(timeline.contains("->"), "the linked drawing stays a link: {timeline}");
+ assert_eq!(
+ draw(&["hash", again, "--all"])
+ .lines()
+ .map(|l| l.split_whitespace().last().unwrap().to_string())
+ .collect::<Vec<_>>(),
+ draw(&["hash", path, "--all"])
+ .lines()
+ .map(|l| l.split_whitespace().last().unwrap().to_string())
+ .collect::<Vec<_>>(),
+ "every frame renders the same"
+ );
+
+ assert!(refused(&["import", file.to_str().unwrap(), "-o", again]).contains("is there already"));
+ assert!(refused(&["import", path]).contains("Aseprite files"));
+ let fake = dir.join("fake.ase");
+ std::fs::write(&fake, b"not a sprite at all").unwrap();
+ assert!(refused(&["import", fake.to_str().unwrap()]).contains("not an Aseprite file"));
+ assert!(!dir.join("fake.klad").exists());
+ let painting = dir.join("painting.klad");
+ draw(&["new", painting.to_str().unwrap(), "--width", "64", "--height", "64"]);
+ assert!(refused(&["export", painting.to_str().unwrap(), "--aseprite"]).contains("no pixel layers"));
+ 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/render/src/aseprite.rs b/crates/render/src/aseprite.rs
new file mode 100644
index 0000000..01661b6
--- /dev/null
+++ b/crates/render/src/aseprite.rs
@@ -0,0 +1,859 @@
+use anyhow::{Context, Result, anyhow, bail};
+use flate2::Compression;
+use flate2::read::ZlibDecoder;
+use flate2::write::ZlibEncoder;
+use std::io::{Read, Write};
+
+const MAGIC: u16 = 0xA5E0;
+const FRAME_MAGIC: u16 = 0xF1FA;
+const HEADER: usize = 128;
+const OLD_PALETTE: u16 = 0x0004;
+const LAYER: u16 = 0x2004;
+const CEL: u16 = 0x2005;
+const PROFILE: u16 = 0x2007;
+const TAGS: u16 = 0x2018;
+const PALETTE: u16 = 0x2019;
+const SLICE: u16 = 0x2022;
+const TILESET: u16 = 0x2023;
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Colour {
+ pub rgba: [u8; 4],
+ pub name: String,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Layer {
+ pub name: String,
+ pub visible: bool,
+ pub group: bool,
+ pub tilemap: bool,
+ pub level: u16,
+ pub blend: u16,
+ pub opacity: u8,
+ pub reference: bool,
+ pub background: bool,
+}
+
+impl Layer {
+ pub fn image(name: &str, level: u16) -> Self {
+ Self {
+ name: name.to_string(),
+ visible: true,
+ group: false,
+ tilemap: false,
+ level,
+ blend: 0,
+ opacity: 255,
+ reference: false,
+ background: false,
+ }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum Picture {
+ Pixels { width: u16, height: u16, rgba: Vec<u8> },
+ Link(u16),
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Cel {
+ pub layer: u16,
+ pub frame: u16,
+ pub x: i16,
+ pub y: i16,
+ pub opacity: u8,
+ pub picture: Picture,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Tag {
+ pub name: String,
+ pub from: u16,
+ pub to: u16,
+ pub direction: u8,
+ pub repeat: u16,
+}
+
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct Sprite {
+ pub width: u16,
+ pub height: u16,
+ pub palette: Vec<Colour>,
+ pub layers: Vec<Layer>,
+ pub durations: Vec<u16>,
+ pub cels: Vec<Cel>,
+ pub tags: Vec<Tag>,
+ pub notes: Vec<String>,
+}
+
+struct Reader<'a> {
+ bytes: &'a [u8],
+ at: usize,
+}
+
+impl<'a> Reader<'a> {
+ fn take(&mut self, count: usize) -> Result<&'a [u8]> {
+ let end = self
+ .at
+ .checked_add(count)
+ .filter(|end| *end <= self.bytes.len())
+ .ok_or_else(|| anyhow!("the file ends early, at byte {}", self.bytes.len()))?;
+ let part = &self.bytes[self.at..end];
+ self.at = end;
+ Ok(part)
+ }
+
+ fn byte(&mut self) -> Result<u8> {
+ Ok(self.take(1)?[0])
+ }
+
+ fn word(&mut self) -> Result<u16> {
+ let b = self.take(2)?;
+ Ok(u16::from_le_bytes([b[0], b[1]]))
+ }
+
+ fn short(&mut self) -> Result<i16> {
+ Ok(self.word()? as i16)
+ }
+
+ fn dword(&mut self) -> Result<u32> {
+ let b = self.take(4)?;
+ Ok(u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
+ }
+
+ fn string(&mut self) -> Result<String> {
+ let length = self.word()? as usize;
+ Ok(String::from_utf8_lossy(self.take(length)?).to_string())
+ }
+
+ fn rest(&mut self) -> &'a [u8] {
+ let part = &self.bytes[self.at..];
+ self.at = self.bytes.len();
+ part
+ }
+}
+
+struct RawCel {
+ layer: u16,
+ frame: u16,
+ x: i16,
+ y: i16,
+ opacity: u8,
+ width: u16,
+ height: u16,
+ data: Option<Vec<u8>>,
+ link: u16,
+}
+
+fn inflate(data: &[u8], wanted: usize) -> Result<Vec<u8>> {
+ let mut out = Vec::with_capacity(wanted);
+ ZlibDecoder::new(data)
+ .take(wanted as u64 + 1)
+ .read_to_end(&mut out)
+ .context("a cel's compressed pixels do not unpack")?;
+ if out.len() != wanted {
+ bail!("a cel unpacks to {} bytes, not the {wanted} its size needs", out.len());
+ }
+ Ok(out)
+}
+
+fn deflate(data: &[u8]) -> Result<Vec<u8>> {
+ let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
+ encoder.write_all(data)?;
+ Ok(encoder.finish()?)
+}
+
+fn layer_chunk(data: &[u8], flags: u32) -> Result<Layer> {
+ let mut r = Reader { bytes: data, at: 0 };
+ let bits = r.word()?;
+ let kind = r.word()?;
+ let level = r.word()?;
+ r.take(4)?;
+ let blend = r.word()?;
+ let opacity = r.byte()?;
+ r.take(3)?;
+ let name = r.string()?;
+ let own_look = kind != 1 || flags & 2 != 0;
+ Ok(Layer {
+ name,
+ visible: bits & 1 != 0,
+ group: kind == 1,
+ tilemap: kind == 2,
+ level,
+ blend: match own_look {
+ true => blend,
+ false => 0,
+ },
+ opacity: match own_look && (flags & 1 != 0 || kind == 1) {
+ true => opacity,
+ false => 255,
+ },
+ reference: bits & 64 != 0,
+ background: bits & 8 != 0,
+ })
+}
+
+fn cel_chunk(data: &[u8], frame: u16, bytes_per_pixel: usize) -> Result<Option<RawCel>> {
+ let mut r = Reader { bytes: data, at: 0 };
+ let layer = r.word()?;
+ let (x, y) = (r.short()?, r.short()?);
+ let opacity = r.byte()?;
+ let kind = r.word()?;
+ r.take(7)?;
+ let plain = |width, height, data, link| RawCel {
+ layer,
+ frame,
+ x,
+ y,
+ opacity,
+ width,
+ height,
+ data,
+ link,
+ };
+ match kind {
+ 0 => {
+ let (width, height) = (r.word()?, r.word()?);
+ let pixels = r.take(width as usize * height as usize * bytes_per_pixel)?;
+ Ok(Some(plain(width, height, Some(pixels.to_vec()), 0)))
+ }
+ 1 => Ok(Some(plain(0, 0, None, r.word()?))),
+ 2 => {
+ let (width, height) = (r.word()?, r.word()?);
+ let pixels = inflate(r.rest(), width as usize * height as usize * bytes_per_pixel)?;
+ Ok(Some(plain(width, height, Some(pixels), 0)))
+ }
+ _ => Ok(None),
+ }
+}
+
+fn palette_chunk(data: &[u8], palette: &mut Vec<Colour>) -> Result<()> {
+ let mut r = Reader { bytes: data, at: 0 };
+ let size = r.dword()? as usize;
+ let (first, last) = (r.dword()? as usize, r.dword()? as usize);
+ r.take(8)?;
+ if size > 1 << 16 || last >= 1 << 16 {
+ bail!("the palette says it holds {size} colours");
+ }
+ palette.resize(
+ size.max(last + 1),
+ Colour {
+ rgba: [0, 0, 0, 255],
+ name: String::new(),
+ },
+ );
+ (first..=last).try_for_each(|at| {
+ let named = r.word()? & 1 != 0;
+ let c = r.take(4)?;
+ palette[at] = Colour {
+ rgba: [c[0], c[1], c[2], c[3]],
+ name: match named {
+ true => r.string()?,
+ false => String::new(),
+ },
+ };
+ Ok::<_, anyhow::Error>(())
+ })?;
+ palette.truncate(size);
+ Ok(())
+}
+
+fn old_palette_chunk(data: &[u8], palette: &mut Vec<Colour>) -> Result<()> {
+ let mut r = Reader { bytes: data, at: 0 };
+ let packets = r.word()?;
+ let mut at = 0usize;
+ (0..packets).try_for_each(|_| {
+ at += r.byte()? as usize;
+ let count = match r.byte()? {
+ 0 => 256,
+ n => n as usize,
+ };
+ (0..count).try_for_each(|_| {
+ let c = r.take(3)?;
+ if palette.len() <= at {
+ palette.resize(
+ at + 1,
+ Colour {
+ rgba: [0, 0, 0, 255],
+ name: String::new(),
+ },
+ );
+ }
+ palette[at].rgba = [c[0], c[1], c[2], 255];
+ at += 1;
+ Ok::<_, anyhow::Error>(())
+ })
+ })
+}
+
+fn tags_chunk(data: &[u8]) -> Result<Vec<Tag>> {
+ let mut r = Reader { bytes: data, at: 0 };
+ let count = r.word()?;
+ r.take(8)?;
+ (0..count)
+ .map(|_| {
+ let (from, to) = (r.word()?, r.word()?);
+ let direction = r.byte()?;
+ let repeat = r.word()?;
+ r.take(10)?;
+ Ok(Tag {
+ name: r.string()?,
+ from,
+ to,
+ direction,
+ repeat,
+ })
+ })
+ .collect()
+}
+
+fn to_rgba(raw: &[u8], depth: u16, palette: &[Colour], clear: Option<u8>) -> Vec<u8> {
+ match depth {
+ 32 => raw.to_vec(),
+ 16 => raw
+ .as_chunks::<2>()
+ .0
+ .iter()
+ .flat_map(|p| [p[0], p[0], p[0], p[1]])
+ .collect(),
+ _ => raw
+ .iter()
+ .flat_map(|index| match (Some(*index) == clear, palette.get(*index as usize)) {
+ (false, Some(colour)) => colour.rgba,
+ _ => [0, 0, 0, 0],
+ })
+ .collect(),
+ }
+}
+
+pub fn is_aseprite(bytes: &[u8]) -> bool {
+ bytes.len() >= HEADER && u16::from_le_bytes([bytes[4], bytes[5]]) == MAGIC
+}
+
+pub fn read(bytes: &[u8]) -> Result<Sprite> {
+ if !is_aseprite(bytes) {
+ bail!("this is not an Aseprite file (.aseprite or .ase)");
+ }
+ let mut r = Reader { bytes, at: 6 };
+ let frames = r.word()?;
+ let (width, height) = (r.word()?, r.word()?);
+ let depth = r.word()?;
+ if ![8, 16, 32].contains(&depth) {
+ bail!("the file has {depth} bits per pixel: Aseprite files have 8, 16 or 32");
+ }
+ let flags = r.dword()?;
+ let speed = r.word()?;
+ r.take(8)?;
+ let transparent = r.byte()?;
+ r.at = HEADER;
+ let bytes_per_pixel = depth as usize / 8;
+ let mut sprite = Sprite {
+ width,
+ height,
+ ..Sprite::default()
+ };
+ let mut raw: Vec<RawCel> = Vec::new();
+ let mut old_palette: Vec<Colour> = Vec::new();
+ let mut dropped: Vec<&str> = Vec::new();
+ (0..frames).try_for_each(|frame| {
+ let start = r.at;
+ let size = r.dword()? as usize;
+ if r.word()? != FRAME_MAGIC {
+ bail!("frame {frame} does not start where the file says it does");
+ }
+ let old_count = r.word()? as u32;
+ let duration = r.word()?;
+ r.take(2)?;
+ let new_count = r.dword()?;
+ let chunks = match new_count {
+ 0 => old_count,
+ n => n,
+ };
+ sprite.durations.push(match duration {
+ 0 => speed.max(1),
+ d => d,
+ });
+ (0..chunks).try_for_each(|_| {
+ let chunk_start = r.at;
+ let chunk_size = r.dword()? as usize;
+ let kind = r.word()?;
+ if chunk_size < 6 {
+ bail!("a chunk in frame {frame} has no size");
+ }
+ let data = r.take(chunk_size - 6)?;
+ match kind {
+ LAYER => sprite.layers.push(layer_chunk(data, flags)?),
+ CEL => match cel_chunk(data, frame, bytes_per_pixel)? {
+ Some(cel) => raw.push(cel),
+ None => dropped.push("tilemap cels"),
+ },
+ PALETTE if frame == 0 || sprite.palette.is_empty() => palette_chunk(data, &mut sprite.palette)?,
+ PALETTE => dropped.push("palette changes after the first frame"),
+ OLD_PALETTE if frame == 0 => old_palette_chunk(data, &mut old_palette)?,
+ TAGS => sprite.tags.extend(tags_chunk(data)?),
+ SLICE => dropped.push("slices"),
+ TILESET => dropped.push("tilesets"),
+ _ => {}
+ }
+ r.at = chunk_start + chunk_size;
+ Ok(())
+ })?;
+ if size >= 16 {
+ r.at = start + size;
+ }
+ Ok(())
+ })?;
+ if sprite.palette.is_empty() {
+ sprite.palette = old_palette;
+ }
+ sprite.cels = raw
+ .into_iter()
+ .filter(|cel| (cel.layer as usize) < sprite.layers.len())
+ .map(|cel| {
+ let background = sprite.layers[cel.layer as usize].background;
+ let clear = (depth == 8 && !background).then_some(transparent);
+ Cel {
+ layer: cel.layer,
+ frame: cel.frame,
+ x: cel.x,
+ y: cel.y,
+ opacity: cel.opacity,
+ picture: match &cel.data {
+ Some(data) => Picture::Pixels {
+ width: cel.width,
+ height: cel.height,
+ rgba: to_rgba(data, depth, &sprite.palette, clear),
+ },
+ None => Picture::Link(cel.link),
+ },
+ }
+ })
+ .collect();
+ if sprite.layers.iter().any(|l| l.tilemap) {
+ dropped.push("tilemap layers");
+ }
+ dropped.sort_unstable();
+ dropped.dedup();
+ sprite.notes = dropped.into_iter().map(String::from).collect();
+ Ok(sprite)
+}
+
+fn put_string(out: &mut Vec<u8>, text: &str) {
+ let bytes = &text.as_bytes()[..text.len().min(u16::MAX as usize)];
+ out.extend_from_slice(&(bytes.len() as u16).to_le_bytes());
+ out.extend_from_slice(bytes);
+}
+
+fn chunk(kind: u16, data: &[u8]) -> Vec<u8> {
+ let mut out = Vec::with_capacity(data.len() + 6);
+ out.extend_from_slice(&(data.len() as u32 + 6).to_le_bytes());
+ out.extend_from_slice(&kind.to_le_bytes());
+ out.extend_from_slice(data);
+ out
+}
+
+fn profile_out() -> Vec<u8> {
+ let mut data = Vec::new();
+ data.extend_from_slice(&1u16.to_le_bytes());
+ data.extend_from_slice(&[0; 14]);
+ chunk(PROFILE, &data)
+}
+
+fn palette_out(palette: &[Colour]) -> Vec<u8> {
+ let mut data = Vec::new();
+ data.extend_from_slice(&(palette.len() as u32).to_le_bytes());
+ data.extend_from_slice(&0u32.to_le_bytes());
+ data.extend_from_slice(&(palette.len() as u32 - 1).to_le_bytes());
+ data.extend_from_slice(&[0; 8]);
+ palette.iter().for_each(|colour| {
+ data.extend_from_slice(&(!colour.name.is_empty() as u16).to_le_bytes());
+ data.extend_from_slice(&colour.rgba);
+ if !colour.name.is_empty() {
+ put_string(&mut data, &colour.name);
+ }
+ });
+ chunk(PALETTE, &data)
+}
+
+fn layer_out(layer: &Layer) -> Vec<u8> {
+ let bits = (layer.visible as u16) | 2 | ((layer.background as u16) << 3) | ((layer.reference as u16) << 6);
+ let mut data = Vec::new();
+ data.extend_from_slice(&bits.to_le_bytes());
+ data.extend_from_slice(&(layer.group as u16).to_le_bytes());
+ data.extend_from_slice(&layer.level.to_le_bytes());
+ data.extend_from_slice(&[0; 4]);
+ data.extend_from_slice(&layer.blend.to_le_bytes());
+ data.push(layer.opacity);
+ data.extend_from_slice(&[0; 3]);
+ put_string(&mut data, &layer.name);
+ chunk(LAYER, &data)
+}
+
+fn tags_out(tags: &[Tag]) -> Vec<u8> {
+ let mut data = Vec::new();
+ data.extend_from_slice(&(tags.len() as u16).to_le_bytes());
+ data.extend_from_slice(&[0; 8]);
+ tags.iter().for_each(|tag| {
+ data.extend_from_slice(&tag.from.to_le_bytes());
+ data.extend_from_slice(&tag.to.to_le_bytes());
+ data.push(tag.direction);
+ data.extend_from_slice(&tag.repeat.to_le_bytes());
+ data.extend_from_slice(&[0; 10]);
+ put_string(&mut data, &tag.name);
+ });
+ chunk(TAGS, &data)
+}
+
+fn cel_out(cel: &Cel) -> Result<Vec<u8>> {
+ let mut data = Vec::new();
+ data.extend_from_slice(&cel.layer.to_le_bytes());
+ data.extend_from_slice(&cel.x.to_le_bytes());
+ data.extend_from_slice(&cel.y.to_le_bytes());
+ data.push(cel.opacity);
+ match &cel.picture {
+ Picture::Link(frame) => {
+ data.extend_from_slice(&1u16.to_le_bytes());
+ data.extend_from_slice(&[0; 7]);
+ data.extend_from_slice(&frame.to_le_bytes());
+ }
+ Picture::Pixels { width, height, rgba } => {
+ if rgba.len() != *width as usize * *height as usize * 4 {
+ bail!("a cel of {width}x{height} holds {} bytes", rgba.len());
+ }
+ data.extend_from_slice(&2u16.to_le_bytes());
+ data.extend_from_slice(&[0; 7]);
+ data.extend_from_slice(&width.to_le_bytes());
+ data.extend_from_slice(&height.to_le_bytes());
+ data.extend_from_slice(&deflate(rgba)?);
+ }
+ }
+ Ok(chunk(CEL, &data))
+}
+
+pub fn write(sprite: &Sprite) -> Result<Vec<u8>> {
+ if sprite.durations.is_empty() || sprite.durations.len() > u16::MAX as usize {
+ bail!(
+ "an Aseprite file holds 1 to 65535 frames, not {}",
+ sprite.durations.len()
+ );
+ }
+ if sprite.width == 0 || sprite.height == 0 {
+ bail!("an Aseprite file needs a size");
+ }
+ if sprite.layers.len() > u16::MAX as usize || sprite.palette.len() > 1 << 16 {
+ bail!("too many layers or colours for an Aseprite file");
+ }
+ let frames = sprite
+ .durations
+ .iter()
+ .enumerate()
+ .map(|(frame, duration)| {
+ let first: Vec<Vec<u8>> = match frame {
+ 0 => std::iter::once(profile_out())
+ .chain((!sprite.palette.is_empty()).then(|| palette_out(&sprite.palette)))
+ .chain(sprite.layers.iter().map(layer_out))
+ .chain((!sprite.tags.is_empty()).then(|| tags_out(&sprite.tags)))
+ .collect(),
+ _ => Vec::new(),
+ };
+ let cels = sprite
+ .cels
+ .iter()
+ .filter(|cel| cel.frame as usize == frame)
+ .map(cel_out)
+ .collect::<Result<Vec<_>>>()?;
+ let chunks: Vec<Vec<u8>> = first.into_iter().chain(cels).collect();
+ let size = 16 + chunks.iter().map(Vec::len).sum::<usize>();
+ let mut out = Vec::with_capacity(size);
+ out.extend_from_slice(&(size as u32).to_le_bytes());
+ out.extend_from_slice(&FRAME_MAGIC.to_le_bytes());
+ out.extend_from_slice(&(chunks.len().min(0xFFFF) as u16).to_le_bytes());
+ out.extend_from_slice(&duration.to_le_bytes());
+ out.extend_from_slice(&[0; 2]);
+ out.extend_from_slice(&(chunks.len() as u32).to_le_bytes());
+ chunks.iter().for_each(|c| out.extend_from_slice(c));
+ Ok(out)
+ })
+ .collect::<Result<Vec<_>>>()?;
+ let size = HEADER + frames.iter().map(Vec::len).sum::<usize>();
+ let mut out = Vec::with_capacity(size);
+ out.extend_from_slice(&(size as u32).to_le_bytes());
+ out.extend_from_slice(&MAGIC.to_le_bytes());
+ out.extend_from_slice(&(sprite.durations.len() as u16).to_le_bytes());
+ out.extend_from_slice(&sprite.width.to_le_bytes());
+ out.extend_from_slice(&sprite.height.to_le_bytes());
+ out.extend_from_slice(&32u16.to_le_bytes());
+ out.extend_from_slice(&3u32.to_le_bytes());
+ out.extend_from_slice(&sprite.durations[0].to_le_bytes());
+ out.extend_from_slice(&[0; 8]);
+ out.extend_from_slice(&[0; 4]);
+ out.extend_from_slice(&(sprite.palette.len().min(u16::MAX as usize) as u16).to_le_bytes());
+ out.extend_from_slice(&[1, 1]);
+ out.extend_from_slice(&0i16.to_le_bytes());
+ out.extend_from_slice(&0i16.to_le_bytes());
+ out.extend_from_slice(&16u16.to_le_bytes());
+ out.extend_from_slice(&16u16.to_le_bytes());
+ out.resize(HEADER, 0);
+ frames.iter().for_each(|f| out.extend_from_slice(f));
+ Ok(out)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn sample() -> Sprite {
+ let red = [0xef, 0x23, 0x3c, 255];
+ let ink = [0x22, 0x22, 0x3b, 255];
+ let square = |colour: [u8; 4]| -> Vec<u8> {
+ (0..6)
+ .flat_map(|i| if i == 5 { [0, 0, 0, 0] } else { colour })
+ .collect()
+ };
+ Sprite {
+ width: 16,
+ height: 12,
+ palette: vec![
+ Colour {
+ rgba: ink,
+ name: "ink".into(),
+ },
+ Colour {
+ rgba: red,
+ name: String::new(),
+ },
+ ],
+ layers: vec![
+ Layer::image("ground", 0),
+ Layer {
+ group: true,
+ opacity: 200,
+ ..Layer::image("hero", 0)
+ },
+ Layer {
+ blend: 1,
+ opacity: 128,
+ visible: false,
+ ..Layer::image("shade ✦", 1)
+ },
+ ],
+ durations: vec![100, 150, 100],
+ cels: vec![
+ Cel {
+ layer: 0,
+ frame: 0,
+ x: 2,
+ y: -1,
+ opacity: 255,
+ picture: Picture::Pixels {
+ width: 3,
+ height: 2,
+ rgba: square(ink),
+ },
+ },
+ Cel {
+ layer: 2,
+ frame: 0,
+ x: 4,
+ y: 5,
+ opacity: 90,
+ picture: Picture::Pixels {
+ width: 2,
+ height: 3,
+ rgba: square(red),
+ },
+ },
+ Cel {
+ layer: 0,
+ frame: 1,
+ x: 2,
+ y: -1,
+ opacity: 255,
+ picture: Picture::Link(0),
+ },
+ Cel {
+ layer: 2,
+ frame: 2,
+ x: 0,
+ y: 0,
+ opacity: 255,
+ picture: Picture::Pixels {
+ width: 1,
+ height: 1,
+ rgba: red.to_vec(),
+ },
+ },
+ ],
+ tags: vec![
+ Tag {
+ name: "idle".into(),
+ from: 0,
+ to: 1,
+ direction: 0,
+ repeat: 0,
+ },
+ Tag {
+ name: "blink".into(),
+ from: 2,
+ to: 2,
+ direction: 2,
+ repeat: 3,
+ },
+ ],
+ notes: Vec::new(),
+ }
+ }
+
+ #[test]
+ fn a_sprite_written_and_read_back_is_the_same_sprite() {
+ let sprite = sample();
+ let bytes = write(&sprite).unwrap();
+ assert!(is_aseprite(&bytes));
+ assert_eq!(
+ u32::from_le_bytes(bytes[0..4].try_into().unwrap()) as usize,
+ bytes.len()
+ );
+ assert_eq!(u16::from_le_bytes([bytes[6], bytes[7]]), 3);
+ assert_eq!(u16::from_le_bytes([bytes[12], bytes[13]]), 32);
+ assert_eq!(read(&bytes).unwrap(), sprite);
+ assert!(
+ read(&bytes[..bytes.len() - 9])
+ .unwrap_err()
+ .to_string()
+ .contains("ends early")
+ );
+ assert!(
+ read(b"GIF89a")
+ .unwrap_err()
+ .to_string()
+ .contains("not an Aseprite file")
+ );
+ assert!(
+ write(&Sprite {
+ durations: Vec::new(),
+ ..sample()
+ })
+ .is_err()
+ );
+ }
+
+ fn by_hand(depth: u16, flags: u32, transparent: u8, chunks: &[Vec<u8>]) -> Vec<u8> {
+ let size = 16 + chunks.iter().map(Vec::len).sum::<usize>();
+ let mut out = Vec::new();
+ out.extend_from_slice(&((HEADER + size) as u32).to_le_bytes());
+ out.extend_from_slice(&MAGIC.to_le_bytes());
+ out.extend_from_slice(&1u16.to_le_bytes());
+ out.extend_from_slice(&4u16.to_le_bytes());
+ out.extend_from_slice(&2u16.to_le_bytes());
+ out.extend_from_slice(&depth.to_le_bytes());
+ out.extend_from_slice(&flags.to_le_bytes());
+ out.extend_from_slice(&125u16.to_le_bytes());
+ out.extend_from_slice(&[0; 8]);
+ out.push(transparent);
+ out.resize(HEADER, 0);
+ out.extend_from_slice(&(size as u32).to_le_bytes());
+ out.extend_from_slice(&FRAME_MAGIC.to_le_bytes());
+ out.extend_from_slice(&(chunks.len() as u16).to_le_bytes());
+ out.extend_from_slice(&[0; 8]);
+ chunks.iter().for_each(|c| out.extend_from_slice(c));
+ out
+ }
+
+ fn raw_cel(layer: u16, pixels: &[u8], width: u16, height: u16) -> Vec<u8> {
+ let mut data = Vec::new();
+ data.extend_from_slice(&layer.to_le_bytes());
+ data.extend_from_slice(&[0; 4]);
+ data.push(255);
+ data.extend_from_slice(&0u16.to_le_bytes());
+ data.extend_from_slice(&[0; 7]);
+ data.extend_from_slice(&width.to_le_bytes());
+ data.extend_from_slice(&height.to_le_bytes());
+ data.extend_from_slice(pixels);
+ chunk(CEL, &data)
+ }
+
+ #[test]
+ fn indexed_and_grey_files_with_old_chunk_counts_and_raw_cels_are_read() {
+ let palette = [
+ Colour {
+ rgba: [255, 0, 255, 255],
+ name: String::new(),
+ },
+ Colour {
+ rgba: [10, 20, 30, 255],
+ name: "night".into(),
+ },
+ Colour {
+ rgba: [200, 210, 220, 128],
+ name: String::new(),
+ },
+ ];
+ let back = Layer {
+ background: true,
+ ..Layer::image("back", 0)
+ };
+ let indexed = by_hand(
+ 8,
+ 1,
+ 0,
+ &[
+ palette_out(&palette),
+ layer_out(&back),
+ layer_out(&Layer::image("top", 0)),
+ raw_cel(0, &[0, 1, 2, 9], 4, 1),
+ raw_cel(1, &[0, 1, 2, 9], 4, 1),
+ ],
+ );
+ let sprite = read(&indexed).unwrap();
+ assert_eq!(
+ sprite.durations,
+ [125],
+ "a frame without a duration takes the file's speed"
+ );
+ assert_eq!(sprite.palette, palette);
+ let pixels = |at: usize| match &sprite.cels[at].picture {
+ Picture::Pixels { rgba, .. } => rgba.clone(),
+ Picture::Link(_) => panic!("a link"),
+ };
+ assert_eq!(
+ pixels(0),
+ [255, 0, 255, 255, 10, 20, 30, 255, 200, 210, 220, 128, 0, 0, 0, 0],
+ "on the background layer index 0 is a colour; an index past the palette is clear"
+ );
+ assert_eq!(pixels(1)[..4], [0, 0, 0, 0], "elsewhere the transparent index is clear");
+ let grey = by_hand(
+ 16,
+ 0,
+ 0,
+ &[
+ layer_out(&Layer {
+ opacity: 40,
+ ..Layer::image("g", 0)
+ }),
+ raw_cel(0, &[7, 255, 90, 128], 2, 1),
+ ],
+ );
+ let sprite = read(&grey).unwrap();
+ assert_eq!(
+ sprite.layers[0].opacity, 255,
+ "without the flag a layer's opacity is not valid"
+ );
+ assert_eq!(
+ sprite.cels[0].picture,
+ Picture::Pixels {
+ width: 2,
+ height: 1,
+ rgba: vec![7, 7, 7, 255, 90, 90, 90, 128]
+ }
+ );
+ let mut old = Vec::new();
+ old.extend_from_slice(&1u16.to_le_bytes());
+ old.extend_from_slice(&[0, 2, 1, 2, 3, 4, 5, 6]);
+ let sprite = read(&by_hand(32, 1, 0, &[chunk(OLD_PALETTE, &old), chunk(SLICE, &[0; 4])])).unwrap();
+ let colours: Vec<[u8; 4]> = sprite.palette.iter().map(|c| c.rgba).collect();
+ assert_eq!(colours, [[1, 2, 3, 255], [4, 5, 6, 255]]);
+ assert_eq!(sprite.notes, ["slices"]);
+ }
+}
diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs
index 72ed20f..fb57351 100644
--- a/crates/render/src/lib.rs
+++ b/crates/render/src/lib.rs
@@ -1,4 +1,5 @@
pub mod align;
+pub mod aseprite;
pub mod assets;
pub mod effects;
pub mod export;
diff --git a/docs/DESIGN.md b/docs/DESIGN.md
index 4405549..8169a8a 100644
--- a/docs/DESIGN.md
+++ b/docs/DESIGN.md
@@ -1,4 +1,4 @@
-_Last updated: 2026-11-12 11:00_
+_Last updated: 2026-11-12 14:00_
# klad: design
@@ -232,7 +232,7 @@ Unknown keys are errors that list the valid ones, so a typo never passes silentl
Every layer has `blend`, `opacity`, `visible`, `locked`, optional `mask`, `clip` and (M5, format 8) `effects`. Effects are layer settings, not a layer kind: the planned `filter` kind became them.
-- **Pixel layers (M9).** A pixel layer is a paint layer flagged `pixel`, so it shares cels, masks, clipping, lock alpha, effects, the timeline and every export with paint layers. One pixel is one canvas pixel: a 64x64 sprite is a 64x64 drawing shown enlarged, and a drawing never mixes pixel sizes. Its marks stay data, as strokes do: a pixel mark is a fill record whose source is cells (`FillSource::Cells`), a set of whole pixels (coverage 0 or 255) with the id of the palette swatch it was drawn with, or a set of pixels to erase. So the same addresses, `set`, `rm`, `transform`, lasso, copy and history work on them; scaling, flipping and turning sample the nearest pixel (`markedit::resampled` with `hard`), which also makes an export above full size hard-edged. Colours are palette entries: `Document::bind_swatch` finds or adds the swatch and gives it an `id` the first time a mark uses it, and `set color=` on a pixel mark binds it to the new entry. The `pixel` op (`klad pixel`) is the first way to make marks; brush strokes and flood or lasso fills are refused on a pixel layer (`ops::off_the_grid`). A drawing with a pixel layer (`Document::pixel_art`) gets a sharp view on both sides. In the editor the zoom moves in whole screen pixels per pixel above real size (`View::whole`, `View::fit_whole`; free below it), a pixel grid shows from 8 screen pixels per pixel (a dark line with light dashes, so it reads on any colour; View > Pixel grid), the pixel under the pointer is outlined on a pixel layer and named in the status line, and the Real size pane (`Pane::Preview`, opened the first time a pixel drawing is opened) shows the composed frame at 1, 2 or 4 screen pixels per pixel for drawings up to 512 px. In the CLI, `klad render` and edit previews enlarge by a whole number to about 512 px (`agent::pixel_scale`), and `--overlay grid` draws the same lines with the pixel numbers along the top and left (`overlay::draw_cells`). The palette is what a pixel drawing is bound to. A mark stores its swatch's id and its colour, so every reader of a stroke file draws it without the palette; when a palette edit changes a swatch's colour, `ops::follow_palette` adds a `MarkChange::Entry` for every pixel drawing, which rewrites the colour of the marks bound to that swatch in the same transaction (one undo step), and a removed swatch unbinds its marks. A palette rewritten without ids keeps them by name, then by colour (`carry_ids`). Swatches carry an optional `ramp` name: a ramp is the swatches sharing it, in palette order, dark to light (`palettes::ramp` makes one from a base colour with `color::value_step`, darker and cooler to lighter and warmer). Palettes that come with klad are colour lists in `core/src/palettes.rs` (`klad palettes`), and `palettes::parse` reads a list of hex colours or a GIMP palette. The pencil is grid geometry in `core/src/pixel.rs`, shared by both hands: `line` (Bresenham), `extend` (a run that follows the pen with no holes), `perfect` (drops the corner pixel of an L, so a hand-drawn line stays one pixel thin), `stamp` (a size is a square of whole pixels) and `of_path` (SVG path data flattened and traced; corners the path asks for are kept, the corners that flattening a curve leaves are not). The `pixel` op takes `cells` or a `path`, and a `size`. In the editor the brush tool on a pixel layer is the pencil (the eraser command and the pen's eraser end erase): the run is drawn over the canvas as it grows and committed on release as one `pixel` op marked as made by hand, so the palette binding, history and sync are the op's. Shift click draws a straight line from the last pixel; `[` and `]` change the size. An agent reads and writes a pixel layer as text, which is exact where a picture is not. `pixel::grid_of` works out what a drawing's marks show, pixel by pixel (later marks over earlier ones, erasing marks, lock alpha, cuts), as the palette entry or the colour of each pixel; `pixel::legend` gives each one a character (the first letter of its name where free) and `pixel::ruled` or `pixel::plain` print the rows (`klad pixels`). The other way, `pixel::parse_text` reads a legend and rows and the grid form of the `pixel` op (`rows`, `legend`, `at`) turns each character into one mark bound to its colour (`klad pixel --grid`), so what `klad pixels --plain` prints draws the same picture again. Text grids are the agent's side only: a person draws with the pencil. Shapes 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 follow in the milestone's later stories.
+- **Pixel layers (M9).** A pixel layer is a paint layer flagged `pixel`, so it shares cels, masks, clipping, lock alpha, effects, the timeline and every export with paint layers. One pixel is one canvas pixel: a 64x64 sprite is a 64x64 drawing shown enlarged, and a drawing never mixes pixel sizes. Its marks stay data, as strokes do: a pixel mark is a fill record whose source is cells (`FillSource::Cells`), a set of whole pixels (coverage 0 or 255) with the id of the palette swatch it was drawn with, or a set of pixels to erase. So the same addresses, `set`, `rm`, `transform`, lasso, copy and history work on them; scaling, flipping and turning sample the nearest pixel (`markedit::resampled` with `hard`), which also makes an export above full size hard-edged. Colours are palette entries: `Document::bind_swatch` finds or adds the swatch and gives it an `id` the first time a mark uses it, and `set color=` on a pixel mark binds it to the new entry. The `pixel` op (`klad pixel`) is the first way to make marks; brush strokes and flood or lasso fills are refused on a pixel layer (`ops::off_the_grid`). A drawing with a pixel layer (`Document::pixel_art`) gets a sharp view on both sides. In the editor the zoom moves in whole screen pixels per pixel above real size (`View::whole`, `View::fit_whole`; free below it), a pixel grid shows from 8 screen pixels per pixel (a dark line with light dashes, so it reads on any colour; View > Pixel grid), the pixel under the pointer is outlined on a pixel layer and named in the status line, and the Real size pane (`Pane::Preview`, opened the first time a pixel drawing is opened) shows the composed frame at 1, 2 or 4 screen pixels per pixel for drawings up to 512 px. In the CLI, `klad render` and edit previews enlarge by a whole number to about 512 px (`agent::pixel_scale`), and `--overlay grid` draws the same lines with the pixel numbers along the top and left (`overlay::draw_cells`). The palette is what a pixel drawing is bound to. A mark stores its swatch's id and its colour, so every reader of a stroke file draws it without the palette; when a palette edit changes a swatch's colour, `ops::follow_palette` adds a `MarkChange::Entry` for every pixel drawing, which rewrites the colour of the marks bound to that swatch in the same transaction (one undo step), and a removed swatch unbinds its marks. A palette rewritten without ids keeps them by name, then by colour (`carry_ids`). Swatches carry an optional `ramp` name: a ramp is the swatches sharing it, in palette order, dark to light (`palettes::ramp` makes one from a base colour with `color::value_step`, darker and cooler to lighter and warmer). Palettes that come with klad are colour lists in `core/src/palettes.rs` (`klad palettes`), and `palettes::parse` reads a list of hex colours or a GIMP palette. The pencil is grid geometry in `core/src/pixel.rs`, shared by both hands: `line` (Bresenham), `extend` (a run that follows the pen with no holes), `perfect` (drops the corner pixel of an L, so a hand-drawn line stays one pixel thin), `stamp` (a size is a square of whole pixels) and `of_path` (SVG path data flattened and traced; corners the path asks for are kept, the corners that flattening a curve leaves are not). The `pixel` op takes `cells` or a `path`, and a `size`. In the editor the brush tool on a pixel layer is the pencil (the eraser command and the pen's eraser end erase): the run is drawn over the canvas as it grows and committed on release as one `pixel` op marked as made by hand, so the palette binding, history and sync are the op's. Shift click draws a straight line from the last pixel; `[` and `]` change the size. An agent reads and writes a pixel layer as text, which is exact where a picture is not. `pixel::grid_of` works out what a drawing's marks show, pixel by pixel (later marks over earlier ones, erasing marks, lock alpha, cuts), as the palette entry or the colour of each pixel; `pixel::legend` gives each one a character (the first letter of its name where free) and `pixel::ruled` or `pixel::plain` print the rows (`klad pixels`). The other way, `pixel::parse_text` reads a legend and rows and the grid form of the `pixel` op (`rows`, `legend`, `at`) turns each character into one mark bound to its colour (`klad pixel --grid`), so what `klad pixels --plain` prints draws the same picture again. Text grids are the agent's side only: a person draws with the pencil. Shapes and fills are the same op with other sources: `line`, `rect` and `ellipse` (the ellipse that fits a box of pixels, by an integer midpoint walk, so even and odd sizes stay symmetric; `filled` takes the rows between its outline) are pure geometry in `core/src/pixel.rs`; `fill` is a flood over what the drawing shows (`pixel::flood` on the grid of `grid_of`: pixels joined to the seed with exactly its entry or colour, four neighbours or eight), reading this layer, another pixel layer or all of them merged. A flood needs the marks, which an op cannot read, so `Bundle::settle_pixels` turns every `fill` into its cells before the ops are applied, walking the batch so a fill sees the marks the ops before it made; `Bundle::apply_as` calls it, so the CLI, `klad apply` and the editor share it. In the editor the fill tool floods on a click and the shape tool drags a rectangle, an ellipse or a line of pixels on a pixel layer, previewed as the pixels it will make. 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.
- **Blend modes.** `normal`, `multiply`, `screen`, `overlay`, `add`, and since M5 `color-dodge`, `soft-light`, `hard-light`, `lighten`, `darken`, `color`, `luminosity`, all as in the W3C compositing spec (Skia's modes; `look::blend_rgb` and `look::composite` hold the formulas the tests check them against).
- **Effects (M5).** `"effects": [{"glow": {...}}, {"outline": {...}}]`, applied in order to the layer's content (after its mask; for a clip base, to the base and its clipped layers together) before its opacity and blend: `blur` (radius, a Gaussian sigma), `glow` (radius, strength, threshold: 0 glows from every pixel, higher only from the bright ones; color: a tint; blend: how the glow mixes with what is under the layer, screen by default, normal lays it like paint under the layer), `outline` (width, color, inside), `shadow` (x, y, radius, color, laid under the layer), `noise` (amount, size, seed, mono: a grain fixed to the canvas), `displace` (amount, size, seed, by: smooth waves, or a layer whose red pushes across and green down), `relief` (strength, light, highlight, shade, softness: lights the paint height of the layer's drawings, below). Each effect knows its reach (`look::reach`), so a tile is composed from its content within the tile plus that margin and tiles meet without seams (noise and haze read only their own pixel and add no margin, so they cost no neighbouring tiles); a tile skips a clip stack or group that puts no pixel in it (none of its rasters, live tiles or onion ghosts has a tile in the tile grown by its effects' margin; layers moved by keys, adjustment layers and vector layers drawn from their nodes always count), which leaves the tile the same since every blend leaves the pixels under a transparent layer as they are; the pixels are computed in Rust (`klad-render/effects.rs`) on f32 with absolute coordinates, so a tile equals the same pixels of the whole image byte for byte (tested). Blurs use a direct kernel, below a sigma of 2 at full size and above it on a grid of 2, 4, ... px blocks anchored to the canvas, then sampled back.
- **Adjustment layers (M5).** An `adjust` layer changes what is under it in its list: the layers below it in its group, or, clipped, its base. A group holding an adjustment is composed apart, so the adjustment stays inside it. The colour math is on unpremultiplied sRGB values with alpha kept: `hsl` (hue in degrees, saturation and lightness -1..1), `levels` (black, white, gamma, low, high), `curves` (points, and red, green, blue applied before them; monotone cubic, no overshoot), `balance` (shadows, midtones, highlights: cyan to red, magenta to green, yellow to blue, keepLight), `gradient-map` (stops by brightness). The layer's opacity, blend and mask decide how much of the adjusted colour replaces the colour under it. `fill` (a solid or gradient paint) is drawn like a content layer instead, with the layer's blend.
diff --git a/docs/cli.md b/docs/cli.md
index 8c8ea25..e4548c5 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -8,6 +8,7 @@ This reference is licensed under the MIT License (`LICENSE-MIT`), unlike klad it
## Commands
+- [`klad import`](#klad-import): Open an Aseprite file as a klad drawing
- [`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 frames`](#klad-frames): Exposure sheet: a row per frame, a column per layer (top first)
@@ -92,6 +93,34 @@ This reference is licensed under the MIT License (`LICENSE-MIT`), unlike klad it
- [`klad bench`](#klad-bench): Measure stroke storage, brush speed, replay, cache and compositing
- [`klad open`](#klad-open): Open the editor, on a bundle or on the start window (new, open, recent)
+## klad import
+
+```text
+Make a klad drawing from an Aseprite file (.aseprite or .ase): its layers and groups, the drawing of every frame, its palette and its tags. The drawing is written next to the file (hero.aseprite makes hero.klad) unless -o names it, and its path is printed.
+
+ klad import hero.aseprite
+ klad import hero.ase -o sprites/hero.klad
+
+What comes over: 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 linked), the palette with its names, and tags as clips. Frame times become whole frames: a file of 100 ms frames is 10 frames a second, and a frame shown for 300 ms holds for three. Indexed, grey and RGBA files all open; every pixel is bound to its palette colour, and colours a file uses outside its palette are added to it.
+
+What does not: tilemap layers, tilesets and slices are left out, a tag that plays backwards or back and forth becomes a clip that plays forwards, and blend modes klad does not have blend as normal. Each of these is said when it happens.
+
+klad export art.klad --aseprite writes a drawing's pixel layers back to an Aseprite file.
+
+Usage: klad import [OPTIONS] <FILE>
+
+Arguments:
+ <FILE>
+
+
+Options:
+ -o, --out <OUT>
+ The drawing to make (default: the file's name with .klad, next to it)
+
+ -h, --help
+ Print help (see a summary with '-h')
+```
+
## klad new
```text
@@ -3375,6 +3404,7 @@ Animations (each clip, or the whole timeline when there are no clips):
klad export art.klad --sheet run one clip; --sheet 0-11 a range
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 --background
+ 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
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.
Usage: klad export [OPTIONS] <BUNDLE>
@@ -3419,6 +3449,9 @@ Options:
--dither
With --gif: where a picture has more than 255 colours, mix the nearest ones in a fine even pattern so gradients do not band
+ --aseprite
+ An Aseprite file of the drawing's pixel layers: groups, the drawing of every frame, the palette and clips as tags
+
--godot [<GODOT>]
Godot SpriteFrames and AnimatedSprite2D scene into this folder (default: the document's export.godot)
diff --git a/docs/skill/SKILL.md b/docs/skill/SKILL.md
index 5301200..966e96b 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.
+- Aseprite files: `klad import hero.aseprite` (or `.ase`; `-o` names the drawing) makes `hero.klad` next to the file: image layers as pixel layers with their name, visibility, opacity and blend mode, groups as groups, every cel as a drawing on its frame (linked cels stay links), the palette with its names, tags as clips. Frame times become whole frames at the slowest speed that fits (100 ms frames are 10 fps; a 300 ms frame holds for three). Indexed, grey and RGBA files all open, every pixel bound to its palette colour. It says what it leaves out: tilemap layers, tilesets, slices, tag directions other than forwards, blend modes klad lacks. `klad export hero.klad --aseprite` writes the pixel layers and groups back (RGBA; holds and links as linked cels, clips as tags, a pixel layer's keyed moves and opacity baked into its cels; `--variant` and `--variants` work); paint, vector and other layers are left out and named. Use it to hand work to someone who uses Aseprite, or to take over a sprite made there.
- Each mark, `<cel>:s<id>`, stays editable: `klad set sprite.klad c2:s1 color=shadow` recolours it (and binds it to that entry), `klad transform ... --move 2,0` moves it by whole pixels, `--flip h` and `--rotate 90` keep it hard, `klad rm` removes it. `klad strokes sprite.klad l1` lists the marks with their entry and cell count; `--json` gives each one's `cells`.
- Later marks cover earlier ones; `--erase` (or `erase` in a grid's legend) makes a mark that clears what was drawn before it at those pixels (remove that mark and the pixels come back).
- Looking: `klad render` and the `--render` preview of an edit enlarge a pixel drawing by a whole number to about 512 px, so every pixel is a square you can see (`--scale 1` gives the real size, which is how the player sees it: check there too). `--overlay grid` draws a line between pixels and numbers them along the top and the left, so a pixel's `x,y` can be read off the picture: the number is on the line where that column or row starts. `klad export --scale 8` (whole numbers) writes the enlarged PNG to keep.