Skip to content

armgit / klad

Public Imported from GitHub
0

A drawing app built for agent/human collaboration

Rust

GIF export: dithering as an option

Indicode BV48132f271273
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5f96b67..2e40d0b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,7 +5,7 @@
The first builds, and klad's licences.
- A new icon, painted in klad: a K in two brush strokes.
-- 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.
+- 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.
- Mirror and tiles for pixel art. The pixel pencil, shape and fill tools draw each pixel's twin across the **mirror** line. **View > Tile: wrap at the edges** makes the drawing a tile: what you draw past an edge comes back in on the other side, fills go round the edges, and the canvas shows its repeats around it. From the command line: `klad pixel --mirror-x 16` (and `--mirror-y`), `klad new tile.klad --pixel 16 --wrap`, `klad canvas tile.klad --wrap on`, and `klad render --repeat 3` to see a tile repeated.
- Shading pixels. The pixel pencil, the shape tool and the fill tool have three inks: **colour**, **lighter** and **darker**; the last two step the pixels you go over along their colour's ramp. **dither** draws a share of the pixels in an even pattern, with the **second colour** for the rest. **Layer > Outline the pixels** adds a one-pixel outline in the current colour, and **Lighter** and **Darker** in the bar under selected marks step them along their ramp. From the command line: `klad pixel --shade`, `--dither` with `--second`, `--outline` (`--inside`), `klad recolour --step`, and `klad recolour --from skin --to skin-dark` to replace a colour.
diff --git a/crates/app/src/editor/export.rs b/crates/app/src/editor/export.rs
index 95ab7af..fd26888 100644
--- a/crates/app/src/editor/export.rs
+++ b/crates/app/src/editor/export.rs
@@ -21,6 +21,7 @@ pub(super) struct Form {
pub scale: f32,
pub background: bool,
pub deep: bool,
+ pub dither: bool,
pub range: String,
pub padding: u32,
pub max: u32,
@@ -35,6 +36,7 @@ impl Default for Form {
scale: 1.0,
background: false,
deep: false,
+ dither: false,
range: "all".into(),
padding: 2,
max: 4096,
@@ -67,6 +69,9 @@ pub(super) fn args(bundle: &Path, home: &Path, frame: u32, form: &Form) -> Vec<S
if form.background && matches!(form.what, What::Image | What::Gif) {
push("--background", None);
}
+ if form.dither && form.what == What::Gif {
+ push("--dither", None);
+ }
if form.what == What::Sheet {
push("--padding", Some(form.padding.to_string()));
push("--max", Some(form.max.to_string()));
@@ -213,6 +218,10 @@ impl Editor {
ui.checkbox(&mut form.background, "keep the background colour")
.hint("off: a transparent picture");
}
+ if form.what == What::Gif && !pixel {
+ ui.checkbox(&mut form.dither, "dither")
+ .hint("a GIF holds 255 colours: mix them in a fine pattern so soft gradients do not band; off keeps flat areas of one colour");
+ }
if form.what == What::Sheet {
ui.add(egui::Slider::new(&mut form.padding, 0..=16).text("padding px"))
.hint("space between the cells of the sheet");
@@ -311,12 +320,18 @@ mod tests {
scale: 8.0,
deep: true,
background: true,
+ dither: true,
..Form::default()
};
assert_eq!(
args(bundle, home, 0, &gif).join(" "),
- "export /w/art.klad --gif hop --scale 8 --background"
+ "export /w/art.klad --gif hop --scale 8 --background --dither"
);
+ let image = Form {
+ dither: true,
+ ..Form::default()
+ };
+ assert!(!args(bundle, home, 0, &image).contains(&"--dither".to_string()));
assert_eq!(
written(
diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs
index dbea0b4..590969d 100644
--- a/crates/cli/src/main.rs
+++ b/crates/cli/src/main.rs
@@ -1879,7 +1879,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; 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 --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,
@@ -1917,6 +1917,12 @@ enum Command {
help = "An animated GIF: all (a GIF for each clip, or one of the whole timeline), a clip or a range like 0-11"
)]
gif: Option<String>,
+ #[arg(
+ long,
+ requires = "gif",
+ 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,
num_args = 0..=1,
@@ -4007,6 +4013,7 @@ fn run() -> Result<()> {
sheet,
frames,
gif,
+ dither,
godot,
store,
godot_scene,
@@ -4034,7 +4041,7 @@ fn run() -> Result<()> {
};
let packing = sprites::Packing { padding, max };
match (sheet, frames, godot) {
- _ if gif.is_some() => sprites::gif(&bundle, gif.as_deref().unwrap_or("all"), &look, out)?,
+ _ 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)?,
(_, _, Some(dir)) => sprites::godot(&bundle, dir.or(out), store, &look, &packing)?,
diff --git a/crates/cli/src/sprites.rs b/crates/cli/src/sprites.rs
index 5f85fef..1dc874e 100644
--- a/crates/cli/src/sprites.rs
+++ b/crates/cli/src/sprites.rs
@@ -377,7 +377,7 @@ pub fn frames(path: &Path, spec: &str, look: &Look, out: Option<PathBuf>) -> Res
Ok(())
}
-pub fn gif(path: &Path, spec: &str, look: &Look, out: Option<PathBuf>) -> Result<()> {
+pub fn gif(path: &Path, spec: &str, look: &Look, dither: bool, out: Option<PathBuf>) -> Result<()> {
let start = Instant::now();
let bundle = Bundle::open(path)?;
let animations = sprites::animations(&bundle.doc, spec)?;
@@ -419,7 +419,7 @@ pub fn gif(path: &Path, spec: &str, look: &Look, out: Option<PathBuf>) -> Result
ms: r.ms,
})
.collect();
- let bytes = klad_render::gif::encode(sw, sh, &shots, animation.looping)?;
+ let bytes = klad_render::gif::encode(sw, sh, &shots, animation.looping, dither)?;
let name = match animation.clip {
true => format!("{stem}-{}{}.gif", file_safe(&animation.name), scale_tag(look.scale)),
false => format!("{stem}{}.gif", scale_tag(look.scale)),
diff --git a/crates/cli/tests/binary.rs b/crates/cli/tests/binary.rs
index f9a6a39..5440069 100644
--- a/crates/cli/tests/binary.rs
+++ b/crates/cli/tests/binary.rs
@@ -1211,6 +1211,24 @@ fn a_pixel_drawing_exports_sharp_at_whole_number_scales_as_png_gif_sheet_and_god
gif.windows(11).any(|w| w == b"NETSCAPE2.0"),
"the clip loops, so the GIF does"
);
+ let mixed = dir.join("mixed.gif");
+ draw(&[
+ "export",
+ path,
+ "--gif",
+ "hop",
+ "--scale",
+ "8",
+ "--dither",
+ "-o",
+ mixed.to_str().unwrap(),
+ ]);
+ assert_eq!(
+ std::fs::read(&mixed).unwrap(),
+ gif,
+ "a drawing of a few colours is exact, so dithering changes nothing"
+ );
+ assert!(refused(&["export", path, "--dither"]).contains("--gif"));
let range = dir.join("first.gif");
draw(&["export", path, "--gif", "0-1", "-o", range.to_str().unwrap()]);
assert_eq!(u16::from_le_bytes([std::fs::read(&range).unwrap()[6], 0]), 16);
diff --git a/crates/render/src/export.rs b/crates/render/src/export.rs
index ae11bb6..ba6fe83 100644
--- a/crates/render/src/export.rs
+++ b/crates/render/src/export.rs
@@ -12,7 +12,7 @@ pub const MAX_SCALE: f32 = 8.0;
pub const PIXEL_MAX_SCALE: f32 = 64.0;
pub const PIXEL_MAX_SIDE: f32 = 16384.0;
-const BAYER: [u8; 64] = [
+pub(crate) const BAYER: [u8; 64] = [
0, 32, 8, 40, 2, 34, 10, 42, 48, 16, 56, 24, 50, 18, 58, 26, 12, 44, 4, 36, 14, 46, 6, 38, 60, 28, 52, 20, 62, 30,
54, 22, 3, 35, 11, 43, 1, 33, 9, 41, 51, 19, 59, 27, 49, 17, 57, 25, 15, 47, 7, 39, 13, 45, 5, 37, 63, 31, 55, 23,
61, 29, 53, 21,
diff --git a/crates/render/src/gif.rs b/crates/render/src/gif.rs
index e41ea7e..1485b5e 100644
--- a/crates/render/src/gif.rs
+++ b/crates/render/src/gif.rs
@@ -73,6 +73,62 @@ fn nearest(table: &[[u8; 3]], colour: [u8; 3]) -> usize {
.map_or(0, |(i, _)| i)
}
+fn spacing(table: &[[u8; 3]]) -> f32 {
+ let gaps: Vec<f32> = table
+ .iter()
+ .enumerate()
+ .filter_map(|(i, a)| {
+ table
+ .iter()
+ .enumerate()
+ .filter(|(j, _)| *j != i)
+ .map(|(_, b)| (0..3).map(|ch| (a[ch] as f32 - b[ch] as f32).powi(2)).sum::<f32>())
+ .min_by(f32::total_cmp)
+ })
+ .map(f32::sqrt)
+ .collect();
+ match gaps.is_empty() {
+ true => 0.0,
+ false => (gaps.iter().sum::<f32>() / gaps.len() as f32).clamp(2.0, 48.0),
+ }
+}
+
+const UNSET: u8 = u8::MAX;
+
+struct Pattern<'a> {
+ table: &'a [[u8; 3]],
+ spread: f32,
+ found: Vec<u8>,
+}
+
+impl<'a> Pattern<'a> {
+ fn new(table: &'a [[u8; 3]], dither: bool) -> Self {
+ Self {
+ table,
+ spread: match dither {
+ true => spacing(table),
+ false => 0.0,
+ },
+ found: vec![UNSET; 1 << 24],
+ }
+ }
+
+ fn pick(&mut self, colour: [u8; 3], x: usize, y: usize) -> usize {
+ let bayer = |x: usize, y: usize| (crate::export::BAYER[(y % 8) * 8 + x % 8] as f32 + 0.5) / 64.0 - 0.5;
+ let thresholds = [bayer(x, y), bayer(y + 3, x + 5), bayer(x + 5, y + 2)];
+ let moved: [u8; 3] = std::array::from_fn(|ch| {
+ (colour[ch] as f32 + thresholds[ch] * self.spread)
+ .round()
+ .clamp(0.0, 255.0) as u8
+ });
+ let key = ((moved[0] as usize) << 16) | ((moved[1] as usize) << 8) | moved[2] as usize;
+ if self.found[key] == UNSET {
+ self.found[key] = nearest(self.table, moved) as u8;
+ }
+ self.found[key] as usize
+ }
+}
+
struct Bits {
out: Vec<u8>,
hold: u32,
@@ -165,7 +221,7 @@ pub fn delays(durations: &[u32]) -> Vec<u16> {
.collect()
}
-pub fn encode(width: u32, height: u32, shots: &[Shot], looping: bool) -> Result<Vec<u8>> {
+pub fn encode(width: u32, height: u32, shots: &[Shot], looping: bool, dither: bool) -> Result<Vec<u8>> {
if shots.is_empty() {
bail!("a GIF needs at least one frame");
}
@@ -196,7 +252,7 @@ pub fn encode(width: u32, height: u32, shots: &[Shot], looping: bool) -> Result<
out.extend_from_slice(b"NETSCAPE2.0");
out.extend_from_slice(&[3, 1, 0, 0, 0]);
}
- let mut cache: BTreeMap<[u8; 3], usize> = BTreeMap::new();
+ let mut reduced = (counts.len() > 255).then(|| Pattern::new(&table, dither));
let ticks = delays(&shots.iter().map(|s| s.ms).collect::<Vec<_>>());
shots.iter().zip(&ticks).for_each(|(shot, delay)| {
let indices: Vec<u8> = shot
@@ -204,14 +260,15 @@ pub fn encode(width: u32, height: u32, shots: &[Shot], looping: bool) -> Result<
.as_chunks::<4>()
.0
.iter()
- .map(|px| match px[3] >= CLEAR_AT as u8 {
+ .enumerate()
+ .map(|(i, px)| match px[3] >= CLEAR_AT as u8 {
false => clear as u8,
true => {
let colour = [px[0], px[1], px[2]];
- let at = exact
- .get(&colour)
- .copied()
- .unwrap_or_else(|| *cache.entry(colour).or_insert_with(|| nearest(&table, colour)));
+ let at = match reduced.as_mut() {
+ Some(pattern) => pattern.pick(colour, i % width as usize, i / width as usize),
+ None => exact.get(&colour).copied().unwrap_or(0),
+ };
at as u8
}
})
@@ -329,7 +386,7 @@ mod tests {
ms: 84,
},
];
- let gif = encode(4, 2, &shots, true).unwrap();
+ let gif = encode(4, 2, &shots, true, true).unwrap();
assert_eq!(&gif[..6], b"GIF89a");
assert_eq!((gif[6], gif[8]), (4, 2));
assert_eq!(gif[10] & 0x87, 0x81, "a global table of four slots");
@@ -351,13 +408,13 @@ mod tests {
[(8, 2), (9, 2), (8, 2)],
"250 ms over three frames, in hundredths, with index 2 as the clear pixel"
);
- assert!(!String::from_utf8_lossy(&encode(4, 2, &shots, false).unwrap()).contains("NETSCAPE"));
+ assert!(!String::from_utf8_lossy(&encode(4, 2, &shots, false, false).unwrap()).contains("NETSCAPE"));
assert_eq!(
delays(&[83, 83, 84, 83, 83, 84]).iter().map(|d| *d as u32).sum::<u32>(),
50
);
assert_eq!(delays(&[1]), [1], "no frame is shorter than a hundredth");
- assert!(encode(4, 2, &[], true).is_err());
+ assert!(encode(4, 2, &[], true, false).is_err());
}
#[test]
@@ -379,6 +436,7 @@ mod tests {
ms: 100,
}],
false,
+ false,
)
.unwrap();
let image = Image::from_encoded(Data::new_copy(&gif)).expect("Skia reads the GIF");
@@ -397,6 +455,73 @@ mod tests {
});
}
+ fn read_back(gif: &[u8], w: usize, h: usize) -> Vec<u8> {
+ use skia_safe::{AlphaType, ColorType, Data, Image, ImageInfo, image::CachingHint};
+ let image = Image::from_encoded(Data::new_copy(gif)).expect("Skia reads the GIF");
+ let info = ImageInfo::new((w as i32, h as i32), ColorType::RGBA8888, AlphaType::Unpremul, None);
+ let mut read = vec![0u8; w * h * 4];
+ assert!(image.read_pixels(&info, &mut read, w * 4, (0, 0), CachingHint::Allow));
+ read
+ }
+
+ #[test]
+ fn dithering_keeps_a_gradient_smooth_on_average_and_leaves_few_colours_exact() {
+ let (w, h) = (256usize, 64usize);
+ let rgba = frame(w, h, |x, y| {
+ [
+ (x as f32 * 0.9) as u8,
+ (40.0 + y as f32 * 3.2) as u8,
+ (230.0 - (x + y * 2) as f32 * 0.55) as u8,
+ 255,
+ ]
+ });
+ assert!(
+ colours(&[Shot {
+ rgba: rgba.clone(),
+ ms: 1
+ }])
+ .len()
+ > 4000
+ );
+ let shot = |rgba: &[u8]| {
+ [Shot {
+ rgba: rgba.to_vec(),
+ ms: 100,
+ }]
+ };
+ let plain = read_back(&encode(w as u32, h as u32, &shot(&rgba), false, false).unwrap(), w, h);
+ let dithered = read_back(&encode(w as u32, h as u32, &shot(&rgba), false, true).unwrap(), w, h);
+ let off = |read: &[u8]| -> f32 {
+ let blocks: Vec<f32> = (0..8)
+ .flat_map(|by| (0..32).map(move |bx| (bx, by)))
+ .map(|(bx, by)| {
+ let sum = |pixels: &[u8], ch: usize| -> f32 {
+ (0..8)
+ .flat_map(|y| (0..8).map(move |x| (x, y)))
+ .map(|(x, y)| pixels[((by * 8 + y) * w + bx * 8 + x) * 4 + ch] as f32)
+ .sum::<f32>()
+ / 64.0
+ };
+ (0..3).map(|ch| (sum(read, ch) - sum(&rgba, ch)).abs()).sum::<f32>()
+ })
+ .collect();
+ blocks.iter().sum::<f32>() / blocks.len() as f32
+ };
+ let (flat, fine) = (off(&plain), off(&dithered));
+ assert!(
+ fine < flat * 0.5,
+ "8x8 blocks are {fine} levels off with dithering and {flat} without"
+ );
+ assert_ne!(plain, dithered);
+ let few = frame(8, 8, |x, y| [(x * 30) as u8, (y * 30) as u8, 90, 255]);
+ assert_eq!(
+ encode(8, 8, &shot(&few), false, true).unwrap(),
+ encode(8, 8, &shot(&few), false, false).unwrap(),
+ "with 255 colours or fewer nothing is reduced, so nothing is dithered"
+ );
+ assert_eq!(read_back(&encode(8, 8, &shot(&few), false, true).unwrap(), 8, 8), few);
+ }
+
#[test]
fn more_than_255_colours_are_cut_down_to_a_palette_that_stays_close() {
let rgba = frame(64, 64, |x, y| [(x * 4) as u8, (y * 4) as u8, ((x + y) * 2) as u8, 255]);
@@ -419,6 +544,6 @@ mod tests {
.max()
.unwrap_or(0);
assert!(worst <= 40, "the furthest colour is {worst} levels from its entry");
- assert!(encode(64, 64, &[Shot { rgba, ms: 100 }], false).is_ok());
+ assert!(encode(64, 64, &[Shot { rgba, ms: 100 }], false, false).is_ok());
}
}
diff --git a/docs/DESIGN.md b/docs/DESIGN.md
index 8adf4a2..fdd5c3d 100644
--- a/docs/DESIGN.md
+++ b/docs/DESIGN.md
@@ -1,4 +1,4 @@
-_Last updated: 2026-11-12 06:30_
+_Last updated: 2026-11-12 08:30_
# 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 and nearest entry otherwise, no dithering; 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. 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. Aseprite files follow in the milestone's later stories.
- **Blend modes.** `normal`, `multiply`, `screen`, `overlay`, `add`, and since M5 `color-dodge`, `soft-light`, `hard-light`, `lighten`, `darken`, `color`, `luminosity`, all as in the W3C compositing spec (Skia's modes; `look::blend_rgb` and `look::composite` hold the formulas the tests check them against).
- **Effects (M5).** `"effects": [{"glow": {...}}, {"outline": {...}}]`, applied in order to the layer's content (after its mask; for a clip base, to the base and its clipped layers together) before its opacity and blend: `blur` (radius, a Gaussian sigma), `glow` (radius, strength, threshold: 0 glows from every pixel, higher only from the bright ones; color: a tint; blend: how the glow mixes with what is under the layer, screen by default, normal lays it like paint under the layer), `outline` (width, color, inside), `shadow` (x, y, radius, color, laid under the layer), `noise` (amount, size, seed, mono: a grain fixed to the canvas), `displace` (amount, size, seed, by: smooth waves, or a layer whose red pushes across and green down), `relief` (strength, light, highlight, shade, softness: lights the paint height of the layer's drawings, below). Each effect knows its reach (`look::reach`), so a tile is composed from its content within the tile plus that margin and tiles meet without seams (noise and haze read only their own pixel and add no margin, so they cost no neighbouring tiles); a tile skips a clip stack or group that puts no pixel in it (none of its rasters, live tiles or onion ghosts has a tile in the tile grown by its effects' margin; layers moved by keys, adjustment layers and vector layers drawn from their nodes always count), which leaves the tile the same since every blend leaves the pixels under a transparent layer as they are; the pixels are computed in Rust (`klad-render/effects.rs`) on f32 with absolute coordinates, so a tile equals the same pixels of the whole image byte for byte (tested). Blurs use a direct kernel, below a sigma of 2 at full size and above it on a grid of 2, 4, ... px blocks anchored to the canvas, then sampled back.
- **Adjustment layers (M5).** An `adjust` layer changes what is under it in its list: the layers below it in its group, or, clipped, its base. A group holding an adjustment is composed apart, so the adjustment stays inside it. The colour math is on unpremultiplied sRGB values with alpha kept: `hsl` (hue in degrees, saturation and lightness -1..1), `levels` (black, white, gamma, low, high), `curves` (points, and red, green, blue applied before them; monotone cubic, no overshoot), `balance` (shadows, midtones, highlights: cyan to red, magenta to green, yellow to blue, keepLight), `gradient-map` (stops by brightness). The layer's opacity, blend and mask decide how much of the adjusted colour replaces the colour under it. `fill` (a solid or gradient paint) is drawn like a content layer instead, with the layer's blend.
diff --git a/docs/cli.md b/docs/cli.md
index 056a3b5..2747f3b 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -3352,7 +3352,7 @@ Animations (each clip, or the whole timeline when there are no clips):
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
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; transparent unless --background
+ 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 --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>
@@ -3394,6 +3394,9 @@ Options:
--gif [<GIF>]
An animated GIF: all (a GIF for each clip, or one of the whole timeline), a clip or a range like 0-11
+ --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
+
--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 d84a90c..635dabb 100644
--- a/docs/skill/SKILL.md
+++ b/docs/skill/SKILL.md
@@ -433,13 +433,13 @@ In `apply`: `{"op":"clip","add":"run","from":0,"to":11,"loop":true,"fps":24}`, `
klad export art.klad --sheet all [--scale 0.5] [--padding 2] [--max 4096] [--depth 16]
klad export art.klad --sheet run -o out/run.png
klad export art.klad --frames run # run-0000.png ... full size, one per frame, in art-run/
-klad export art.klad --gif [run] [--scale 2] [--background] # art-run.gif per clip, or art.gif of the whole timeline
+klad export art.klad --gif [run] [--scale 2] [--background] [--dither] # art-run.gif per clip, or art.gif of the whole timeline
klad export art.klad --godot ../game/art/hero # first time: the folder is kept in the document
klad export art.klad --godot # later: the kept folder (the editor's button does the same)
```
- `--sheet all` exports every clip (or the whole timeline as `default` when there are none), `--sheet <clip>` one, `--sheet 0-11` a range. The PNG holds each distinct picture once (holds, links and frames that render the same share one), trimmed to its pixels, in order of first appearance; beyond `--max` it goes to more pages (`art-sheet-2.png`, ...). The JSON is Aseprite's array layout: one entry per exposure with `duration` in ms at the clip's fps (a clip's durations add up to its length), `frame` (rect in the page), `spriteSourceSize` (the trim) and `sourceSize`, plus `frameTags` per clip (`repeat: "1"` when it plays once). Entries on later pages carry `image`.
-- `--gif` writes an animated GIF for each clip (`art-<clip>.gif`; a clip that loops makes a GIF that loops), or one of the whole timeline when there are no clips; `--gif <clip>` or `--gif 0-11` writes one, and `-o` names the file (or the folder, for several). Each picture is shown for as long as its frames last, in hundredths of a second with the rounding carried over, so the GIF runs as long as the clip. A GIF holds 255 colours and one clear one: pixel art and flat colour come out exact, a painting with more colours is reduced to the nearest of 255 without dithering (gradients band; use `--frames` and a video tool for those), and half-clear pixels become clear or solid. Transparent unless `--background`.
+- `--gif` writes an animated GIF for each clip (`art-<clip>.gif`; a clip that loops makes a GIF that loops), or one of the whole timeline when there are no clips; `--gif <clip>` or `--gif 0-11` writes one, and `-o` names the file (or the folder, for several). Each picture is shown for as long as its frames last, in hundredths of a second with the rounding carried over, so the GIF runs as long as the clip. A GIF holds 255 colours and one clear one: pixel art and flat colour come out exact, a painting with more colours is reduced to 255: by default each pixel takes the nearest one, which keeps flat areas clean but bands soft gradients (a glow turns into rings); `--dither` mixes the nearest colours in a fine even pattern instead, which keeps gradients smooth at the cost of a visible grain and a file about a third larger. Use `--dither` for painted, lit or hazy pieces, leave it off for flat colour and line art; it changes nothing when the frames hold 255 colours or fewer. Half-clear pixels become clear or solid. Transparent unless `--background`.
- `--godot <folder>` writes `art.png` (and pages), `art.tres` (a `SpriteFrames`: an `AtlasTexture` per picture with its trim as margin, one animation per clip with its name, speed, loop and per-frame durations in frames) and `art.tscn` (an `AnimatedSprite2D`, autoplaying the first clip, offset so the origin sits on the node's position). Re-exports keep the uids of the `.tres`, `.tscn` and the imported PNG, so scenes using them keep working. `--store` replaces a kept folder; the kept path (`export.godot`) is relative to the folder holding the bundle.
- Exports print a pixel hash per page and of the JSON on stderr. The bounce (`samples/bounce/build.sh`) exports in about 0.25 s; 40 distinct 1024 frames to Godot in about 1.4 s warm, 2.3 s cold.