Skip to content

armgit / klad

Public Imported from GitHub
0

A drawing app built for agent/human collaboration

Rust

Mirror and wrap for pixel art: twins across a line, and tiles that repeat at their edges

Indicode BVd793a3966c5c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5b460a7..cd41ff0 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.
+- 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.
- Selecting and editing pixels. On a pixel layer the stroke tool (**S**) drags a box, or a loop, around pixels and takes them, cutting marks between whole pixels; drag them to move by whole pixels, scale by whole numbers or turn by quarters, and the bar under them flips, turns, recolours (exactly the current colour), copies and deletes. **Select same colour** takes every mark in the selected colours. From the command line: `klad lasso` takes `--box x,y,w,h`, `klad strokes --entry skin` lists one colour's marks, and `klad recolour` gives pixel marks the exact palette colour.
- Shapes and fill on the grid. On a pixel layer the fill tool (**G**) fills every pixel joined to the one you click that has exactly its colour (**across corners**, **read all pixel layers**), and the shape tool (**U**) drags a rectangle, an ellipse or a line of whole pixels, outlined or **filled**. From the command line: `klad pixel` with `--line`, `--rect`, `--ellipse` (`--filled`) and `--fill x,y` (`--diagonal`, `--ref`).
diff --git a/crates/app/src/canvas.wgsl b/crates/app/src/canvas.wgsl
index 4deee32..752dcb2 100644
--- a/crates/app/src/canvas.wgsl
+++ b/crates/app/src/canvas.wgsl
@@ -19,7 +19,8 @@ fn vs_main(@builtin(vertex_index) index: u32) -> Out {
vec2<f32>(0.0, 0.0), vec2<f32>(1.0, 0.0), vec2<f32>(0.0, 1.0),
vec2<f32>(1.0, 0.0), vec2<f32>(1.0, 1.0), vec2<f32>(0.0, 1.0),
);
- let uv = corners[index];
+ let around = step(0.5, view.c.z);
+ let uv = corners[index] * (1.0 + 2.0 * around) - vec2<f32>(around);
let p = uv * view.c.xy;
let px = vec2<f32>(
view.a.x * p.x + view.a.y * p.y + view.b.x,
@@ -33,8 +34,10 @@ fn vs_main(@builtin(vertex_index) index: u32) -> Out {
@fragment
fn fs_main(in: Out) -> @location(0) vec4<f32> {
- let color = textureSample(canvas_tex, canvas_sampler, in.uv);
+ let color = textureSample(canvas_tex, canvas_sampler, fract(in.uv));
let cell = vec2<i32>(floor(in.pos.xy / view.c.w));
let checker = select(0.80, 0.92, ((cell.x + cell.y) & 1) == 0);
- return vec4<f32>(color.rgb + vec3<f32>(checker) * (1.0 - color.a), 1.0);
+ let own = all(in.uv >= vec2<f32>(0.0)) && all(in.uv <= vec2<f32>(1.0));
+ let dim = select(0.62, 1.0, own);
+ return vec4<f32>((color.rgb + vec3<f32>(checker) * (1.0 - color.a)) * dim, 1.0);
}
diff --git a/crates/app/src/commands.rs b/crates/app/src/commands.rs
index e21b71b..9136356 100644
--- a/crates/app/src/commands.rs
+++ b/crates/app/src/commands.rs
@@ -136,6 +136,7 @@ pub enum Cmd {
HistoryPane,
PreviewPane,
PixelGrid,
+ WrapCanvas,
Timeline,
Numbers,
Settings,
@@ -516,7 +517,7 @@ use Repeat as R;
use Trigger as T;
impl Cmd {
- pub const ALL: [Cmd; 189] = [
+ pub const ALL: [Cmd; 190] = [
Cmd::Brush,
Cmd::Eraser,
Cmd::Fill,
@@ -649,6 +650,7 @@ impl Cmd {
Cmd::HistoryPane,
Cmd::PreviewPane,
Cmd::PixelGrid,
+ Cmd::WrapCanvas,
Cmd::Timeline,
Cmd::Numbers,
Cmd::Settings,
@@ -1970,6 +1972,15 @@ impl Cmd {
R::No,
"lines between the pixels of a pixel drawing once it is zoomed in far enough to tell them apart",
),
+ Cmd::WrapCanvas => spec(
+ "view.wrap",
+ "tile: wrap at the edges",
+ icon::REPEAT,
+ G::View,
+ T::None,
+ R::No,
+ "the drawing is a tile: pixels drawn past an edge come back in on the other side, and the canvas shows its repeats around it",
+ ),
Cmd::FlipView => spec(
"view.flip",
"flip the view left-right",
@@ -2542,6 +2553,7 @@ impl Cmd {
Cmd::HistoryPane => "History",
Cmd::PreviewPane => "Real size",
Cmd::PixelGrid => "Pixel grid",
+ Cmd::WrapCanvas => "Tile: wrap at the edges",
Cmd::Timeline => "Timeline",
Cmd::Numbers => "Show numbers",
Cmd::Settings => "Settings…",
@@ -2890,6 +2902,7 @@ pub const MENUS: [Menu; 9] = [
Run(Cmd::ResetRotation),
Run(Cmd::FlipView),
Run(Cmd::PixelGrid),
+ Run(Cmd::WrapCanvas),
Line,
Run(Cmd::CompareReference),
],
diff --git a/crates/app/src/editor.rs b/crates/app/src/editor.rs
index 02b7ec6..6243825 100644
--- a/crates/app/src/editor.rs
+++ b/crates/app/src/editor.rs
@@ -1787,6 +1787,9 @@ impl Editor {
}
fn visible_tiles(&self, view: View, rect: Rect) -> BTreeSet<usize> {
+ if self.scene.bundle.doc.canvas.wrap {
+ return self.scene.all_tiles().into_iter().collect();
+ }
let size = rect.size();
let corners = [vec2(0.0, 0.0), vec2(size.x, 0.0), vec2(0.0, size.y), size].map(|p| view.to_canvas(p, size));
let range = |lo: f32, hi: f32, count: usize| {
@@ -3431,11 +3434,24 @@ impl Editor {
shade,
dither,
second: dither.filter(|_| self.pixel_two).map(|_| color::hex(self.second)),
+ mirror_x: self.mirror.map(|axis| (axis * 2.0).round() / 2.0),
by_hand: true,
..klad_core::ops::PixelSpec::default()
})
}
+ fn pixel_preview(&self, cells: Vec<klad_core::pixel::Cell>) -> Vec<klad_core::pixel::Cell> {
+ let twinned = match self.mirror {
+ Some(axis) => klad_core::pixel::mirrored(&cells, Some((axis * 2.0).round() / 2.0), None),
+ None => cells,
+ };
+ let canvas = &self.scene.bundle.doc.canvas;
+ match canvas.wrap {
+ true => klad_core::pixel::wrapped(&twinned, canvas.width, canvas.height),
+ false => twinned,
+ }
+ }
+
pub(super) fn apply_pixels(&mut self, spec: klad_core::ops::PixelSpec) -> Result<()> {
let drew = spec.color.is_some();
match self.scene.bundle.settle_pixels(&[Op::Pixel(spec)]) {
@@ -3543,12 +3559,7 @@ impl Editor {
return Ok(());
};
self.pixel_last = live.run.last().copied();
- let (w, h) = self.scene.size();
- let cells: Vec<klad_core::pixel::Cell> = self
- .pixel_cells(&live)
- .into_iter()
- .filter(|c| c[0] >= 0 && c[1] >= 0 && c[0] < w as i64 && c[1] < h as i64)
- .collect();
+ let cells = self.pixel_cells(&live);
let Some(spec) = self.pixel_spec(live.erase).filter(|_| !cells.is_empty()) else {
return Ok(());
};
@@ -3710,7 +3721,7 @@ impl Editor {
};
self.frames.set_level(level);
let show = self.tend_frames()?;
- let view_uniform = view.uniform(area, ctx.pixels_per_point(), canvas);
+ let view_uniform = view.uniform(area, ctx.pixels_per_point(), canvas, self.scene.bundle.doc.canvas.wrap);
let (w, h) = self.scene.size();
let visible = self.visible_tiles(view, rect);
let previewed = self.tend_preview(visible)?;
@@ -3854,12 +3865,12 @@ impl Editor {
}
.drawn()
.ok()
- .map(|cells| (cells, spec.erase))
+ .map(|cells| (self.pixel_preview(cells), spec.erase))
});
let drawing = self
.pixel_live
.as_ref()
- .map(|live| (self.pixel_cells(live), live.erase))
+ .map(|live| (self.pixel_preview(self.pixel_cells(live)), live.erase))
.or(shaped);
if let Some((cells, erase)) = drawing {
let shading = !erase && self.pixel_mode != PixelMode::Draw;
@@ -3949,7 +3960,9 @@ impl Editor {
}
self.decorate_shape(&painter, &|x, y| self.screen(view, rect, vec2(x, y)), accent);
self.decorate_typing(&painter, view, rect, accent);
- if let Some(axis) = self.mirror.filter(|_| self.tool == Tool::Brush) {
+ let mirrors =
+ self.tool == Tool::Brush || (self.scene.on_grid() && matches!(self.tool, Tool::Shape | Tool::Fill));
+ if let Some(axis) = self.mirror.filter(|_| mirrors) {
let h = self.scene.size().1 as f32;
painter.add(egui::Shape::dashed_line(
&[
diff --git a/crates/app/src/editor/commands.rs b/crates/app/src/editor/commands.rs
index ad0520c..9c7c93a 100644
--- a/crates/app/src/editor/commands.rs
+++ b/crates/app/src/editor/commands.rs
@@ -193,6 +193,7 @@ impl Editor {
Some(_) => editing,
}
}
+ Cmd::WrapCanvas => editing,
Cmd::PixelGrid => (!self.scene.bundle.doc.pixel_art())
.then(|| "this drawing has no pixel layer: Layer > New pixel layer adds one".to_string()),
Cmd::Corner | Cmd::Smooth => direct
@@ -415,6 +416,7 @@ impl Editor {
Cmd::Eraser => self.tool == Tool::Brush && erasing,
Cmd::FlipView => self.view.is_some_and(|v| v.flip),
Cmd::PixelGrid => self.settings.pixel_grid,
+ Cmd::WrapCanvas => self.scene.bundle.doc.canvas.wrap,
Cmd::PreviewPane => layout.dock && layout.is_open(Pane::Preview),
Cmd::Fill => self.tool == Tool::Fill,
Cmd::Shapes => self.tool == Tool::Select,
@@ -998,6 +1000,11 @@ impl Editor {
self.settings.pixel_grid = !self.settings.pixel_grid;
self.settings_dirty = true;
}
+ Cmd::WrapCanvas => {
+ let wrap = !self.scene.bundle.doc.canvas.wrap;
+ self.apply(vec![Op::Canvas { wrap: Some(wrap) }])?;
+ self.dirty.extend(self.scene.all_tiles());
+ }
Cmd::Timeline => {
self.settings.layout.timeline = !self.settings.layout.timeline;
self.settings_dirty = true;
diff --git a/crates/app/src/editor/options.rs b/crates/app/src/editor/options.rs
index 31d3761..ed263bf 100644
--- a/crates/app/src/editor/options.rs
+++ b/crates/app/src/editor/options.rs
@@ -713,6 +713,16 @@ impl Editor {
}
fn pixel_inks(&mut self, ui: &mut egui::Ui) {
+ self.command_check(ui, Cmd::Symmetry, "mirror");
+ if let Some(axis) = self.mirror.as_mut() {
+ ui.add(
+ egui::DragValue::new(axis)
+ .speed(0.5)
+ .prefix("at x ")
+ .custom_formatter(|v, _| format!("{:.1}", (v * 2.0).round() / 2.0)),
+ )
+ .hint("where the mirror line stands: a whole number is between two pixels, .5 runs through a column");
+ }
ui.separator();
[
(super::PixelMode::Draw, "colour", "draw in the current colour"),
diff --git a/crates/app/src/editor/ui_tests.rs b/crates/app/src/editor/ui_tests.rs
index f224e15..5e859ed 100644
--- a/crates/app/src/editor/ui_tests.rs
+++ b/crates/app/src/editor/ui_tests.rs
@@ -2161,6 +2161,60 @@ fn the_pencil_shades_and_dithers_and_a_selection_steps_along_its_ramp_and_takes_
let _ = std::fs::remove_dir_all(&path);
}
+#[test]
+fn the_pixel_pencil_mirrors_across_a_line_and_wraps_on_a_tile() {
+ let path = pixel_sample("pixel-mirror");
+ let mut h = harness(editor(&path), vec2(1440.0, 900.0));
+ h.state_mut().tool = Tool::Brush;
+ h.state_mut()
+ .set_colour(klad_core::color::parse_hex("#2a9d8f").unwrap());
+ h.run_steps(2);
+ let last = |h: &Harness<'static, Editor>| -> Vec<[u32; 2]> {
+ h.state()
+ .scene
+ .active_marks()
+ .last()
+ .and_then(|m| m.as_fill())
+ .map(|f| f.coverage.cells().collect())
+ .unwrap_or_default()
+ };
+ assert_eq!(h.state().is_on(Cmd::Symmetry), Some(false));
+ h.state_mut().invoke(Cmd::Symmetry).unwrap();
+ h.run_steps(2);
+ assert_eq!(
+ h.state().mirror,
+ Some(16.0),
+ "the mirror line starts in the middle of the 32 pixel canvas"
+ );
+ let at = on_screen(&h, 10.5, 12.5);
+ click_with(&mut h, at, Modifiers::NONE);
+ h.run_steps(3);
+ assert_eq!(
+ last(&h),
+ [[10, 12], [21, 12]],
+ "a pixel and its twin across the line between 15 and 16"
+ );
+ h.state_mut().invoke(Cmd::Symmetry).unwrap();
+ assert_eq!(h.state().is_on(Cmd::WrapCanvas), Some(false));
+ h.state_mut().invoke(Cmd::WrapCanvas).unwrap();
+ h.run_steps(3);
+ assert!(h.state().scene.bundle.doc.canvas.wrap && h.state().is_on(Cmd::WrapCanvas) == Some(true));
+ let (a, b) = (on_screen(&h, 29.5, 20.5), on_screen(&h, 33.5, 20.5));
+ drag(&mut h, a, b);
+ h.run_steps(3);
+ ready(&mut h);
+ assert_eq!(
+ last(&h),
+ [[0, 20], [1, 20], [29, 20], [30, 20], [31, 20]],
+ "a line drawn past the right edge comes back in on the left"
+ );
+ h.state_mut().invoke(Cmd::Undo).unwrap();
+ h.state_mut().invoke(Cmd::WrapCanvas).unwrap();
+ h.run_steps(3);
+ assert!(!h.state().scene.bundle.doc.canvas.wrap);
+ let _ = std::fs::remove_dir_all(&path);
+}
+
#[test]
fn a_tap_that_wobbles_selects_and_a_drag_past_three_points_moves() {
let path = sample("tap");
diff --git a/crates/app/src/view.rs b/crates/app/src/view.rs
index 78a893f..0487169 100644
--- a/crates/app/src/view.rs
+++ b/crates/app/src/view.rs
@@ -84,7 +84,7 @@ impl View {
self.keep(anchor, at, area);
}
- pub fn uniform(self, area: Vec2, pixels_per_point: f32, canvas: Vec2) -> [f32; 12] {
+ pub fn uniform(self, area: Vec2, pixels_per_point: f32, canvas: Vec2, repeat: bool) -> [f32; 12] {
let (s, c) = self.angle.sin_cos();
let k = pixels_per_point * self.zoom;
let f = if self.flip { -1.0 } else { 1.0 };
@@ -105,7 +105,7 @@ impl View {
area.y * pixels_per_point,
canvas.x,
canvas.y,
- pixels_per_point,
+ if repeat { 1.0 } else { 0.0 },
8.0 * pixels_per_point,
]
}
@@ -171,7 +171,7 @@ mod tests {
let area = Vec2::new(900.0, 600.0);
let mut view = View::fit(Vec2::new(1024.0, 1024.0), area);
view.angle = -0.3;
- let u = view.uniform(area, 2.0, Vec2::new(1024.0, 1024.0));
+ let u = view.uniform(area, 2.0, Vec2::new(1024.0, 1024.0), false);
let p = Vec2::new(100.0, 700.0);
let px = Vec2::new(u[0] * p.x + u[1] * p.y + u[4], u[2] * p.x + u[3] * p.y + u[5]);
assert!(close(px, view.to_screen(p, area) * 2.0));
@@ -192,7 +192,7 @@ mod tests {
view.zoom_at(1.7, Vec2::new(200.0, 100.0), area);
let p = Vec2::new(321.0, 654.0);
assert!(close(view.to_canvas(view.to_screen(p, area), area), p));
- let u = view.uniform(area, 2.0, Vec2::new(1000.0, 800.0));
+ let u = view.uniform(area, 2.0, Vec2::new(1000.0, 800.0), false);
let px = Vec2::new(u[0] * p.x + u[1] * p.y + u[4], u[2] * p.x + u[3] * p.y + u[5]);
assert!(close(px, view.to_screen(p, area) * 2.0));
let before = view.to_screen(p, area);
diff --git a/crates/cli/src/agent.rs b/crates/cli/src/agent.rs
index b6d6278..4125bfe 100644
--- a/crates/cli/src/agent.rs
+++ b/crates/cli/src/agent.rs
@@ -33,6 +33,7 @@ pub struct Look {
pub onion_layers: Option<Vec<String>>,
pub tracks: Vec<String>,
pub references: bool,
+ pub repeat: u32,
}
impl Look {
@@ -45,6 +46,7 @@ impl Look {
onion_layers: None,
tracks: Vec::new(),
references: false,
+ repeat: 1,
}
}
@@ -440,14 +442,22 @@ pub fn render_look(
.then(|| onions(bundle, frame, &onion_layers(bundle, look)?, look, &brushes))
.transpose()?;
let rasters: &Rasters = &loaded.rasters;
- let mut image = compose_view(&bundle.doc, frame, rasters, view, overlay.as_ref(), onions.as_ref())?;
+ let image = compose_view(&bundle.doc, frame, rasters, view, overlay.as_ref(), onions.as_ref())?;
let tag = match (overlay.is_some(), onions.is_some()) {
(true, true) => "-overlay-onion",
(true, false) => "-overlay",
(false, true) => "-onion",
(false, false) => "",
};
- let path = out.unwrap_or_else(|| render_path(bundle, frame, view, tag));
+ let tag = match look.repeat > 1 {
+ true => format!("{tag}-x{}", look.repeat),
+ false => tag.to_string(),
+ };
+ let mut image = match look.repeat > 1 {
+ true => image.tiled(look.repeat),
+ false => image,
+ };
+ let path = out.unwrap_or_else(|| render_path(bundle, frame, view, &tag));
write_atomic(&path, &image.png()?)?;
let note = match loaded.updated {
0 => format!(
diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs
index d8f38fb..702f8c1 100644
--- a/crates/cli/src/main.rs
+++ b/crates/cli/src/main.rs
@@ -152,6 +152,19 @@ enum Command {
help = "A pixel art drawing of that many pixels, for example 64x64: its layers are pixel layers"
)]
pixel: Option<String>,
+ #[arg(long, help = "A tile: what is drawn past an edge comes back in on the other side")]
+ wrap: bool,
+ },
+ #[command(
+ about = "The canvas: its size and background, and whether it wraps at its edges",
+ long_about = "The canvas: its size and background, and whether it wraps at its edges. On a canvas that wraps, a tile, pixels drawn past an edge come back in on the other side, and fills and outlines go round the edges, so the drawing repeats without a seam. klad render --repeat 3 shows it repeated.\n\n klad canvas tile.klad\n klad canvas tile.klad --wrap on\n\nAs an op: {\"op\":\"canvas\",\"wrap\":true}."
+ )]
+ Canvas {
+ bundle: PathBuf,
+ #[arg(long, value_parser = ["on", "off"], help = "Turn wrapping at the edges on or off")]
+ wrap: Option<String>,
+ #[command(flatten)]
+ flags: EditFlags,
},
#[command(
about = "Exposure sheet: a row per frame, a column per layer (top first)",
@@ -770,6 +783,12 @@ enum Command {
depth: usize,
#[arg(long, help = "Replay every stroke instead of using cached tiles")]
no_cache: bool,
+ #[arg(
+ long,
+ default_value_t = 1,
+ help = "Show the picture this many times across and down (up to 9), to check a tile's seams"
+ )]
+ repeat: u32,
#[arg(long, help = "Show reference layers (photos to trace over), which renders leave out")]
references: bool,
#[arg(long, value_name = "BEFORE,AFTER", value_parser = parse_onion_counts, help = "Onion skin: how many drawings (or frames) before and after (default 2,2)")]
@@ -1023,6 +1042,18 @@ enum Command {
help = "SVG path data drawn as a line of pixels, one pixel wide with no doubled corners on curves: 'M3.5 20.5 C 10 4 22 4 28.5 20.5'"
)]
path: Option<String>,
+ #[arg(
+ long,
+ value_name = "X",
+ help = "Also draw the mirror image across the upright line at this x: a whole number is the line between two pixels, .5 runs through a column"
+ )]
+ mirror_x: Option<f32>,
+ #[arg(
+ long,
+ value_name = "Y",
+ help = "Also draw the mirror image across the level line at this y"
+ )]
+ mirror_y: Option<f32>,
#[arg(
long,
default_value_t = 1,
@@ -2397,9 +2428,10 @@ fn run() -> Result<()> {
frames,
sketch,
pixel,
+ wrap,
} => {
let size = pixel.as_deref().map(pixel_size).transpose()?;
- edit::new(
+ let mut made = edit::new(
&bundle,
&Blank {
width: size.map_or(width, |s| s.0),
@@ -2412,8 +2444,37 @@ fn run() -> Result<()> {
pixel: size.is_some(),
},
)?;
+ if wrap {
+ made.apply(&[Op::Canvas { wrap: Some(true) }])?;
+ made.stamp("cli")?;
+ }
println!("{}", bundle.display());
}
+ Command::Canvas { bundle, wrap, flags } => match wrap {
+ Some(wrap) => agent::edit(
+ &bundle,
+ &[Op::Canvas {
+ wrap: Some(wrap == "on"),
+ }],
+ &output(&flags, 0),
+ )?,
+ None => {
+ let canvas = Bundle::open(&bundle)?.doc.canvas;
+ match flags.json {
+ true => println!("{}", serde_json::to_string(&canvas)?),
+ false => println!(
+ "{}x{} background {} {}",
+ canvas.width,
+ canvas.height,
+ canvas.background.as_deref().unwrap_or("none"),
+ match canvas.wrap {
+ true => "wraps at its edges",
+ false => "stops at its edges",
+ }
+ ),
+ }
+ }
+ },
Command::Frames { bundle, from, to, json } => frames::sheet(&bundle, from, to, json)?,
Command::Frame {
bundle,
@@ -2922,6 +2983,7 @@ fn run() -> Result<()> {
overlay,
depth,
no_cache,
+ repeat,
references,
onion,
onion_by,
@@ -2969,6 +3031,7 @@ fn run() -> Result<()> {
onion_layers,
tracks: track,
references,
+ repeat: repeat.clamp(1, 9),
};
match sheet {
Some(spec) => {
@@ -3054,6 +3117,8 @@ fn run() -> Result<()> {
shade,
dither,
second,
+ mirror_x,
+ mirror_y,
size,
color,
erase,
@@ -3098,6 +3163,8 @@ fn run() -> Result<()> {
shade,
dither,
second,
+ mirror_x,
+ mirror_y,
size,
part,
by_hand: false,
diff --git a/crates/cli/tests/binary.rs b/crates/cli/tests/binary.rs
index 72f8d66..e41de5c 100644
--- a/crates/cli/tests/binary.rs
+++ b/crates/cli/tests/binary.rs
@@ -999,6 +999,63 @@ fn pixels_are_shaded_dithered_outlined_and_replaced_from_the_command_line() {
std::fs::remove_dir_all(&dir).unwrap();
}
+#[test]
+fn a_tile_wraps_at_its_edges_mirrors_and_renders_repeated_from_the_command_line() {
+ let dir = std::env::temp_dir().join(format!("draw-binary-tile-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ let bundle = dir.join("tile.klad");
+ let path = bundle.to_str().unwrap();
+ let run = |args: &[&str]| Command::new(env!("CARGO_BIN_EXE_klad")).args(args).output().unwrap();
+ let draw = |args: &[&str]| {
+ let out = run(args);
+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
+ String::from_utf8_lossy(&out.stdout).to_string()
+ };
+ let rows = || -> Vec<String> {
+ draw(&["pixels", path, "l1", "--plain"])
+ .lines()
+ .skip_while(|line| !line.is_empty())
+ .skip(1)
+ .map(String::from)
+ .collect()
+ };
+ draw(&["new", path, "--pixel", "8x4", "--wrap"]);
+ assert!(draw(&["canvas", path]).contains("wraps at its edges"));
+ draw(&["palette", path, "--add", "#22223b", "--name", "ink"]);
+ draw(&["pixel", path, "l1", "--color", "ink", "--rect", "6,3,4,2", "--filled"]);
+ assert_eq!(
+ rows(),
+ ["ii....ii", "........", "........", "ii....ii"],
+ "a block over the corner shows in all four corners"
+ );
+ draw(&[
+ "pixel",
+ path,
+ "l1",
+ "--color",
+ "ink",
+ "--cells",
+ "1,1",
+ "--mirror-x",
+ "4",
+ "--mirror-y",
+ "2",
+ ]);
+ assert_eq!(rows()[1..3], [".i....i.", ".i....i."]);
+ let shown = run(&["render", path, "--repeat", "3", "--scale", "4"]);
+ assert!(
+ String::from_utf8_lossy(&shown.stderr).contains("96x48"),
+ "three tiles across and down at 4x: {}",
+ String::from_utf8_lossy(&shown.stderr)
+ );
+ draw(&["canvas", path, "--wrap", "off"]);
+ assert!(draw(&["canvas", path]).contains("stops at its edges"));
+ let json: serde_json::Value = serde_json::from_str(&draw(&["canvas", path, "--json"])).unwrap();
+ assert_eq!((json["width"].as_u64(), json.get("wrap")), (Some(8), None));
+ std::fs::remove_dir_all(&dir).unwrap();
+}
+
#[test]
fn recolour_moves_strokes_together_and_keeps_their_shades() {
let dir = std::env::temp_dir().join(format!("draw-binary-recolour-{}", std::process::id()));
diff --git a/crates/core/src/bundle.rs b/crates/core/src/bundle.rs
index eb172f6..96f1f77 100644
--- a/crates/core/src/bundle.rs
+++ b/crates/core/src/bundle.rs
@@ -464,7 +464,7 @@ impl Bundle {
let placed = match (spec.fill, spec.outline) {
(Some(seed), _) => {
let grid = self.shown(doc, plan, spec, spec.reference.as_deref())?;
- let cells = pixel::flood(&grid, seed, spec.diagonal);
+ let cells = spec.twinned(pixel::flood(&grid, seed, spec.diagonal, doc.canvas.wrap));
if cells.is_empty() {
bail!(
"the fill starts at {},{}, which is off the {w}x{h} canvas",
@@ -476,7 +476,7 @@ impl Bundle {
}
(None, true) => {
let grid = self.shown(doc, plan, spec, spec.reference.as_deref())?;
- let cells = pixel::outline(&grid, spec.inside, spec.diagonal);
+ let cells = pixel::outline(&grid, spec.inside, spec.diagonal, doc.canvas.wrap);
if cells.is_empty() {
bail!("there are no pixels to outline at frame {}", spec.frame);
}
@@ -504,9 +504,15 @@ impl Bundle {
shade: None,
dither: None,
second: None,
+ mirror_x: None,
+ mirror_y: None,
size: 1,
..spec.clone()
};
+ let placed = match doc.canvas.wrap {
+ true => pixel::wrapped(&placed, w, h),
+ false => placed,
+ };
if let Some(by) = spec.shade {
let grid = self.shown(doc, plan, spec, None)?;
let mut stepped: BTreeMap<usize, Vec<pixel::Cell>> = BTreeMap::new();
@@ -858,6 +864,8 @@ pub fn summarize(ops: &[Op]) -> String {
),
Op::Timeline { origin: Some(_), .. } => "timeline origin".to_string(),
Op::Timeline { .. } => "timeline".to_string(),
+ Op::Canvas { wrap: Some(true) } => "the canvas wraps".to_string(),
+ Op::Canvas { .. } => "the canvas stops at its edges".to_string(),
Op::Atmosphere(Some(_)) => "atmosphere".to_string(),
Op::Atmosphere(None) => "atmosphere off".to_string(),
Op::Clip(edit) => match edit {
@@ -2156,4 +2164,81 @@ mod tests {
);
fs::remove_dir_all(&dir).unwrap();
}
+
+ #[test]
+ fn a_wrapping_canvas_brings_pixels_fills_and_outlines_round_its_edges_and_a_mirror_twins_them() {
+ use crate::ops::parse_lines;
+ let dir = scratch("pixel-wrap");
+ let mut bundle = Bundle::blank(
+ &dir,
+ &Blank {
+ width: 8,
+ height: 6,
+ pixel: true,
+ ..Blank::default()
+ },
+ "cli",
+ )
+ .unwrap();
+ let layer = bundle.doc.layers[0].id.clone();
+ let rows = |bundle: &Bundle| -> Vec<String> {
+ let cel = bundle.doc.layers[0].cels()[0].id.clone();
+ let grid = crate::pixel::grid_of(&bundle.read_marks(&layer, &cel).unwrap(), 8, 6);
+ crate::pixel::rows(&grid, &crate::pixel::legend(&bundle.doc, &grid))
+ };
+ let run = |bundle: &mut Bundle, lines: String| bundle.apply(&parse_lines(&lines).unwrap()).unwrap();
+ run(
+ &mut bundle,
+ format!(
+ "{}\n{}",
+ r##"{"op":"palette","add":"#22223b","name":"ink"}"##,
+ format_args!(r##"{{"op":"pixel","layer":"{layer}","color":"ink","line":[6,1,9,1]}}"##),
+ ),
+ );
+ assert_eq!(
+ rows(&bundle)[1],
+ "......ii",
+ "without wrap the pixels past the edge are dropped"
+ );
+ run(
+ &mut bundle,
+ format!(
+ "{}\n{}\n{}\n{}",
+ r##"{"op":"canvas","wrap":true}"##,
+ format_args!(r##"{{"op":"pixel","layer":"{layer}","color":"ink","line":[6,3,9,3]}}"##),
+ format_args!(
+ r##"{{"op":"pixel","layer":"{layer}","color":"ink","cells":[[1,-1],[2,5]],"mirrorX":4}}"##
+ ),
+ format_args!(r##"{{"op":"pixel","layer":"{layer}","color":"ink","line":[0,4,7,4]}}"##),
+ ),
+ );
+ assert!(bundle.doc.canvas.wrap);
+ assert_eq!(
+ rows(&bundle),
+ ["........", "......ii", "........", "ii....ii", "iiiiiiii", ".ii..ii."],
+ "the line comes back in on the left; the pixel above the top lands on the bottom row; both have a twin across x 4"
+ );
+ run(
+ &mut bundle,
+ format!(
+ "{}\n{}",
+ r##"{"op":"palette","add":"#8ecae6","name":"sky"}"##,
+ format_args!(r##"{{"op":"pixel","layer":"{layer}","color":"sky","fill":[3,0]}}"##),
+ ),
+ );
+ assert_eq!(
+ rows(&bundle),
+ ["ssssssss", "ssssssii", "ssssssss", "iissssii", "iiiiiiii", "siissiis"],
+ "the fill goes over the top edge into the bottom row, and stops at the wall of row 4"
+ );
+ run(&mut bundle, r##"{"op":"canvas","wrap":false}"##.to_string());
+ assert!(!bundle.doc.canvas.wrap);
+ assert!(
+ !fs::read_to_string(dir.join("doc.json")).unwrap().contains("wrap"),
+ "wrap off is not written"
+ );
+ let wrong = format!("{:#}", parse_lines(r##"{"op":"canvas","wrap":"yes"}"##).unwrap_err());
+ assert!(wrong.contains("true or false"), "{wrong}");
+ fs::remove_dir_all(&dir).unwrap();
+ }
}
diff --git a/crates/core/src/doc.rs b/crates/core/src/doc.rs
index eeb97a4..f1fd290 100644
--- a/crates/core/src/doc.rs
+++ b/crates/core/src/doc.rs
@@ -69,6 +69,8 @@ pub struct Canvas {
pub height: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub background: Option<String>,
+ #[serde(default, skip_serializing_if = "is_false")]
+ pub wrap: bool,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
@@ -1046,6 +1048,7 @@ impl Document {
width,
height,
background: None,
+ wrap: false,
},
timeline: Timeline::default(),
palette: Vec::new(),
diff --git a/crates/core/src/ops.rs b/crates/core/src/ops.rs
index a06feb3..5457158 100644
--- a/crates/core/src/ops.rs
+++ b/crates/core/src/ops.rs
@@ -142,6 +142,9 @@ pub enum Op {
frames: Option<u32>,
origin: Option<Option<[f32; 2]>>,
},
+ Canvas {
+ wrap: Option<bool>,
+ },
Atmosphere(Option<crate::look::Atmosphere>),
Frames(FrameSpec),
Cel(CelSpec),
@@ -317,6 +320,10 @@ pub struct PixelSpec {
pub dither: Option<u32>,
#[serde(default)]
pub second: Option<String>,
+ #[serde(default, rename = "mirrorX")]
+ pub mirror_x: Option<f32>,
+ #[serde(default, rename = "mirrorY")]
+ pub mirror_y: Option<f32>,
#[serde(default = "one_pixel")]
pub size: u32,
#[serde(default)]
@@ -350,6 +357,8 @@ impl Default for PixelSpec {
shade: None,
dither: None,
second: None,
+ mirror_x: None,
+ mirror_y: None,
size: 1,
part: None,
by_hand: false,
@@ -485,7 +494,7 @@ impl PixelSpec {
pub fn drawn(&self) -> Result<Vec<[i64; 2]>> {
use crate::pixel;
if let Some(d) = &self.path {
- return Ok(pixel::drawn(&pixel::of_path(d)?, self.size));
+ return Ok(self.twinned(pixel::drawn(&pixel::of_path(d)?, self.size)));
}
if !self.settled() {
bail!(
@@ -498,12 +507,22 @@ impl PixelSpec {
(_, _, Some([x, y, w, h])) => pixel::ellipse([x, y], [w, h], self.filled),
_ => self.cells.clone(),
};
- Ok(pixel::stamp(&cells, self.size))
+ Ok(self.twinned(pixel::stamp(&cells, self.size)))
+ }
+
+ pub fn twinned(&self, cells: Vec<[i64; 2]>) -> Vec<[i64; 2]> {
+ match self.mirror_x.is_some() || self.mirror_y.is_some() {
+ true => crate::pixel::mirrored(&cells, self.mirror_x, self.mirror_y),
+ false => cells,
+ }
}
pub fn coverage(&self, doc: &Document) -> Result<Coverage> {
let (w, h) = (doc.canvas.width as i64, doc.canvas.height as i64);
- let drawn = self.drawn()?;
+ let drawn = match doc.canvas.wrap {
+ true => crate::pixel::wrapped(&self.drawn()?, doc.canvas.width, doc.canvas.height),
+ false => self.drawn()?,
+ };
let inside: Vec<[u32; 2]> = drawn
.iter()
.filter(|c| c[0] >= 0 && c[1] >= 0 && c[0] < w && c[1] < h)
@@ -1781,6 +1800,13 @@ impl Op {
Some(other) if other != Value::Bool(false) => bail!("atmosphere: off takes true or false"),
_ => Op::Atmosphere(Some(serde_json::from_value(Value::Object(std::mem::take(&mut map)))?)),
},
+ "canvas" => Op::Canvas {
+ wrap: match map.remove("wrap") {
+ None => None,
+ Some(Value::Bool(wrap)) => Some(wrap),
+ Some(other) => bail!("wrap takes true or false, not {other}"),
+ },
+ },
"timeline" => Op::Timeline {
fps: whole(&mut map, "fps")?,
frames: whole(&mut map, "frames")?,
@@ -1873,7 +1899,7 @@ impl Op {
},
other => {
bail!(
- "unknown op {other:?}: use add, set, rm, mv, stroke, fill, pixel, palette, transform, path, lasso, copy, timeline, frames, cel, clip, retime, inbetween, duplicate, ink, light, hatch, scatter, paint, foliage, grass, paintover, part, key, bone, ik, weights, pose or export"
+ "unknown op {other:?}: use add, set, rm, mv, stroke, fill, pixel, palette, canvas, transform, path, lasso, copy, timeline, frames, cel, clip, retime, inbetween, duplicate, ink, light, hatch, scatter, paint, foliage, grass, paintover, part, key, bone, ik, weights, pose or export"
)
}
};
@@ -4012,6 +4038,13 @@ pub fn apply(doc: &mut Document, op: &Op, out: &mut Applied) -> Result<()> {
doc.atmosphere = air.clone();
out.changed.push("atmosphere".into());
}
+ Op::Canvas { wrap } => {
+ let Some(wrap) = wrap else {
+ bail!("canvas needs \"wrap\": true or false (a tile that repeats at its edges)");
+ };
+ doc.canvas.wrap = *wrap;
+ out.changed.push("canvas".into());
+ }
Op::Timeline { fps, frames, origin } => {
timing::timeline(doc, *fps, *frames)?;
if let Some(origin) = origin {
diff --git a/crates/core/src/pixel.rs b/crates/core/src/pixel.rs
index 0ca4c1b..173189c 100644
--- a/crates/core/src/pixel.rs
+++ b/crates/core/src/pixel.rs
@@ -216,8 +216,49 @@ pub fn ellipse(at: Cell, size: [i64; 2], filled: bool) -> Vec<Cell> {
.collect()
}
-pub fn flood(grid: &Grid, at: Cell, diagonal: bool) -> Vec<Cell> {
+pub fn mirrored(cells: &[Cell], x: Option<f32>, y: Option<f32>) -> Vec<Cell> {
+ let across = |v: i64, axis: f32| (2.0 * axis).round() as i64 - 1 - v;
+ let mut seen = BTreeSet::new();
+ cells
+ .iter()
+ .flat_map(|c| {
+ let over = x.map(|axis| [across(c[0], axis), c[1]]);
+ let under = y.map(|axis| [c[0], across(c[1], axis)]);
+ let both = x.zip(y).map(|(ax, ay)| [across(c[0], ax), across(c[1], ay)]);
+ [Some(*c), over, under, both].into_iter().flatten()
+ })
+ .filter(|c| seen.insert(*c))
+ .collect()
+}
+
+pub fn wrapped(cells: &[Cell], width: u32, height: u32) -> Vec<Cell> {
+ let (w, h) = (width.max(1) as i64, height.max(1) as i64);
+ let mut seen = BTreeSet::new();
+ cells
+ .iter()
+ .map(|c| [c[0].rem_euclid(w), c[1].rem_euclid(h)])
+ .filter(|c| seen.insert(*c))
+ .collect()
+}
+
+fn neighbours(c: Cell, diagonal: bool, (w, h): (i64, i64), wrap: bool) -> impl Iterator<Item = Cell> {
+ const STEPS: [(i64, i64); 8] = [(1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (1, -1), (-1, 1), (-1, -1)];
+ STEPS
+ .into_iter()
+ .take(if diagonal { 8 } else { 4 })
+ .map(move |(dx, dy)| [c[0] + dx, c[1] + dy])
+ .filter_map(move |n| match wrap {
+ true => Some([n[0].rem_euclid(w), n[1].rem_euclid(h)]),
+ false => (n[0] >= 0 && n[1] >= 0 && n[0] < w && n[1] < h).then_some(n),
+ })
+}
+
+pub fn flood(grid: &Grid, at: Cell, diagonal: bool, wrap: bool) -> Vec<Cell> {
let (w, h) = (grid.width as i64, grid.height as i64);
+ let at = match wrap && w > 0 && h > 0 {
+ true => [at[0].rem_euclid(w), at[1].rem_euclid(h)],
+ false => at,
+ };
if at[0] < 0 || at[1] < 0 || at[0] >= w || at[1] >= h {
return Vec::new();
}
@@ -229,21 +270,13 @@ pub fn flood(grid: &Grid, at: Cell, diagonal: bool) -> Vec<Cell> {
let mut out = Vec::new();
while let Some(c) = queue.pop() {
out.push(c);
- let steps: &[(i64, i64)] = match diagonal {
- true => &[(1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (1, -1), (-1, 1), (-1, -1)],
- false => &[(1, 0), (-1, 0), (0, 1), (0, -1)],
- };
- steps
- .iter()
- .map(|(dx, dy)| [c[0] + dx, c[1] + dy])
- .filter(|n| n[0] >= 0 && n[1] >= 0 && n[0] < w && n[1] < h)
- .for_each(|n| {
- let i = (n[1] * w + n[0]) as usize;
- if !seen[i] && key(n) == wanted {
- seen[i] = true;
- queue.push(n);
- }
- });
+ neighbours(c, diagonal, (w, h), wrap).for_each(|n| {
+ let i = (n[1] * w + n[0]) as usize;
+ if !seen[i] && key(n) == wanted {
+ seen[i] = true;
+ queue.push(n);
+ }
+ });
}
out.sort_by_key(|c| (c[1], c[0]));
out
@@ -256,18 +289,17 @@ pub fn dithered(cell: Cell, percent: u32) -> bool {
BAYER[cell[1].rem_euclid(4) as usize][cell[0].rem_euclid(4) as usize] < level
}
-pub fn outline(grid: &Grid, inside: bool, diagonal: bool) -> Vec<Cell> {
+pub fn outline(grid: &Grid, inside: bool, diagonal: bool, wrap: bool) -> Vec<Cell> {
let (w, h) = (grid.width as i64, grid.height as i64);
- let filled =
- |c: Cell| c[0] >= 0 && c[1] >= 0 && c[0] < w && c[1] < h && grid.at(c[0] as u32, c[1] as u32).is_some();
- let steps: &[(i64, i64)] = match diagonal {
- true => &[(1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (1, -1), (-1, 1), (-1, -1)],
- false => &[(1, 0), (-1, 0), (0, 1), (0, -1)],
- };
+ let filled = |c: Cell| grid.at(c[0] as u32, c[1] as u32).is_some();
(0..h)
.flat_map(|y| (0..w).map(move |x| [x, y]))
.filter(|c| filled(*c) == inside)
- .filter(|c| steps.iter().any(|(dx, dy)| filled([c[0] + dx, c[1] + dy]) != inside))
+ .filter(|c| {
+ let around: Vec<Cell> = neighbours(*c, diagonal, (w, h), wrap).collect();
+ let edge = inside && !wrap && around.len() < if diagonal { 8 } else { 4 };
+ edge || around.iter().any(|n| filled(*n) != inside)
+ })
.collect()
}
@@ -757,27 +789,70 @@ mod tests {
};
let walls = grid(&["..a..", ".a.a.", "..a..", "....."]);
assert_eq!(
- flood(&walls, [2, 1], false),
+ flood(&walls, [2, 1], false, false),
[[2, 1]],
"four neighbours stop at a diamond"
);
assert_eq!(
- flood(&walls, [2, 1], true).len(),
+ flood(&walls, [2, 1], true, false).len(),
20 - 4,
"eight slip out between its corners"
);
assert_eq!(
- flood(&walls, [2, 0], false),
+ flood(&walls, [2, 0], false, false),
[[2, 0]],
"a fill takes pixels of exactly the seed's colour"
);
assert_eq!(
- flood(&walls, [2, 0], true).len(),
+ flood(&walls, [2, 0], true, false).len(),
4,
"and the diamond is joined across its corners"
);
- assert_eq!(flood(&walls, [0, 0], false).len(), 15);
- assert!(flood(&walls, [9, 9], false).is_empty());
+ assert_eq!(flood(&walls, [0, 0], false, false).len(), 15);
+ assert!(flood(&walls, [9, 9], false, false).is_empty());
+ let bar = grid(&["..a..", "..a..", "..a..", "..a.."]);
+ assert_eq!(
+ flood(&bar, [0, 0], false, false).len(),
+ 8,
+ "a wall across the canvas stops a fill"
+ );
+ assert_eq!(
+ flood(&bar, [0, 0], false, true).len(),
+ 16,
+ "unless the canvas wraps: the fill goes round the edge"
+ );
+ assert_eq!(
+ flood(&bar, [-5, 4], false, true).len(),
+ 16,
+ "and a seed off the canvas wraps onto it"
+ );
+ assert_eq!(outline(&bar, false, false, false).len(), 8);
+ let dot = grid(&["a....", ".....", "....."]);
+ assert_eq!(outline(&dot, false, false, false), [[1, 0], [0, 1]]);
+ assert_eq!(
+ outline(&dot, false, false, true),
+ [[1, 0], [4, 0], [0, 1], [0, 2]],
+ "on a wrapping canvas the outline comes back in on the other side"
+ );
+ assert_eq!(outline(&dot, true, false, false), [[0, 0]]);
+ assert_eq!(
+ mirrored(&[[2, 3], [5, 3]], Some(8.0), None),
+ [[2, 3], [13, 3], [5, 3], [10, 3]],
+ "across the line between pixels 7 and 8"
+ );
+ assert_eq!(
+ mirrored(&[[7, 0]], Some(7.5), None),
+ [[7, 0]],
+ "a pixel on the mirror line is its own twin"
+ );
+ assert_eq!(
+ mirrored(&[[1, 1]], Some(4.0), Some(4.0)),
+ [[1, 1], [6, 1], [1, 6], [6, 6]]
+ );
+ assert_eq!(
+ wrapped(&[[-1, 0], [8, 9], [3, 3], [11, 3]], 8, 8),
+ [[7, 0], [0, 1], [3, 3]]
+ );
let under = grid(&["bb...", ".....", ".....", "....."]);
let both = merged(&[under, walls.clone()]).unwrap();
assert_eq!(
diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs
index 1b57fad..f8d9d9d 100644
--- a/crates/render/src/lib.rs
+++ b/crates/render/src/lib.rs
@@ -46,6 +46,22 @@ impl Frame {
fnv(FNV_OFFSET, &self.rgba)
}
+ pub fn tiled(&self, times: u32) -> Frame {
+ let times = times.max(1) as usize;
+ let row = self.width as usize * 4;
+ let rgba = (0..self.height as usize * times)
+ .flat_map(|y| {
+ let line = &self.rgba[(y % self.height as usize) * row..][..row];
+ (0..times).flat_map(move |_| line.iter().copied())
+ })
+ .collect();
+ Frame {
+ width: self.width * times as u32,
+ height: self.height * times as u32,
+ rgba,
+ }
+ }
+
pub fn png(&mut self) -> Result<Vec<u8>> {
let info = rgba8_info(self.width, self.height);
let pixmap =
diff --git a/docs/DESIGN.md b/docs/DESIGN.md
index 0375266..6f78aa1 100644
--- a/docs/DESIGN.md
+++ b/docs/DESIGN.md
@@ -1,4 +1,4 @@
-_Last updated: 2026-11-12 02:20_
+_Last updated: 2026-11-12 04: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. Sharp exports and Aseprite files follow in the milestone's later stories.
+- **Pixel layers (M9).** A pixel layer is a paint layer flagged `pixel`, so it shares cels, masks, clipping, lock alpha, effects, the timeline and every export with paint layers. One pixel is one canvas pixel: a 64x64 sprite is a 64x64 drawing shown enlarged, and a drawing never mixes pixel sizes. Its marks stay data, as strokes do: a pixel mark is a fill record whose source is cells (`FillSource::Cells`), a set of whole pixels (coverage 0 or 255) with the id of the palette swatch it was drawn with, or a set of pixels to erase. So the same addresses, `set`, `rm`, `transform`, lasso, copy and history work on them; scaling, flipping and turning sample the nearest pixel (`markedit::resampled` with `hard`), which also makes an export above full size hard-edged. Colours are palette entries: `Document::bind_swatch` finds or adds the swatch and gives it an `id` the first time a mark uses it, and `set color=` on a pixel mark binds it to the new entry. The `pixel` op (`klad pixel`) is the first way to make marks; brush strokes and flood or lasso fills are refused on a pixel layer (`ops::off_the_grid`). A drawing with a pixel layer (`Document::pixel_art`) gets a sharp view on both sides. In the editor the zoom moves in whole screen pixels per pixel above real size (`View::whole`, `View::fit_whole`; free below it), a pixel grid shows from 8 screen pixels per pixel (a dark line with light dashes, so it reads on any colour; View > Pixel grid), the pixel under the pointer is outlined on a pixel layer and named in the status line, and the Real size pane (`Pane::Preview`, opened the first time a pixel drawing is opened) shows the composed frame at 1, 2 or 4 screen pixels per pixel for drawings up to 512 px. In the CLI, `klad render` and edit previews enlarge by a whole number to about 512 px (`agent::pixel_scale`), and `--overlay grid` draws the same lines with the pixel numbers along the top and left (`overlay::draw_cells`). The palette is what a pixel drawing is bound to. A mark stores its swatch's id and its colour, so every reader of a stroke file draws it without the palette; when a palette edit changes a swatch's colour, `ops::follow_palette` adds a `MarkChange::Entry` for every pixel drawing, which rewrites the colour of the marks bound to that swatch in the same transaction (one undo step), and a removed swatch unbinds its marks. A palette rewritten without ids keeps them by name, then by colour (`carry_ids`). Swatches carry an optional `ramp` name: a ramp is the swatches sharing it, in palette order, dark to light (`palettes::ramp` makes one from a base colour with `color::value_step`, darker and cooler to lighter and warmer). Palettes that come with klad are colour lists in `core/src/palettes.rs` (`klad palettes`), and `palettes::parse` reads a list of hex colours or a GIMP palette. The pencil 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. Sharp exports and Aseprite files follow in the milestone's later stories.
- **Blend modes.** `normal`, `multiply`, `screen`, `overlay`, `add`, and since M5 `color-dodge`, `soft-light`, `hard-light`, `lighten`, `darken`, `color`, `luminosity`, all as in the W3C compositing spec (Skia's modes; `look::blend_rgb` and `look::composite` hold the formulas the tests check them against).
- **Effects (M5).** `"effects": [{"glow": {...}}, {"outline": {...}}]`, applied in order to the layer's content (after its mask; for a clip base, to the base and its clipped layers together) before its opacity and blend: `blur` (radius, a Gaussian sigma), `glow` (radius, strength, threshold: 0 glows from every pixel, higher only from the bright ones; color: a tint; blend: how the glow mixes with what is under the layer, screen by default, normal lays it like paint under the layer), `outline` (width, color, inside), `shadow` (x, y, radius, color, laid under the layer), `noise` (amount, size, seed, mono: a grain fixed to the canvas), `displace` (amount, size, seed, by: smooth waves, or a layer whose red pushes across and green down), `relief` (strength, light, highlight, shade, softness: lights the paint height of the layer's drawings, below). Each effect knows its reach (`look::reach`), so a tile is composed from its content within the tile plus that margin and tiles meet without seams (noise and haze read only their own pixel and add no margin, so they cost no neighbouring tiles); a tile skips a clip stack or group that puts no pixel in it (none of its rasters, live tiles or onion ghosts has a tile in the tile grown by its effects' margin; layers moved by keys, adjustment layers and vector layers drawn from their nodes always count), which leaves the tile the same since every blend leaves the pixels under a transparent layer as they are; the pixels are computed in Rust (`klad-render/effects.rs`) on f32 with absolute coordinates, so a tile equals the same pixels of the whole image byte for byte (tested). Blurs use a direct kernel, below a sigma of 2 at full size and above it on a grid of 2, 4, ... px blocks anchored to the canvas, then sampled back.
- **Adjustment layers (M5).** An `adjust` layer changes what is under it in its list: the layers below it in its group, or, clipped, its base. A group holding an adjustment is composed apart, so the adjustment stays inside it. The colour math is on unpremultiplied sRGB values with alpha kept: `hsl` (hue in degrees, saturation and lightness -1..1), `levels` (black, white, gamma, low, high), `curves` (points, and red, green, blue applied before them; monotone cubic, no overshoot), `balance` (shadows, midtones, highlights: cyan to red, magenta to green, yellow to blue, keepLight), `gradient-map` (stops by brightness). The layer's opacity, blend and mask decide how much of the adjusted colour replaces the colour under it. `fill` (a solid or gradient paint) is drawn like a content layer instead, with the layer's blend.
diff --git a/docs/cli.md b/docs/cli.md
index a8ddee7..6609c88 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -9,6 +9,7 @@ This reference is licensed under the MIT License (`LICENSE-MIT`), unlike klad it
## Commands
- [`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)
- [`klad frame`](#klad-frame): Insert or remove frames in every layer or the listed ones
- [`klad arcs`](#klad-arcs): Track marks, parts or points across frames: positions, spacing, ground contacts, feet crossing
@@ -127,10 +128,51 @@ Options:
--pixel <WxH>
A pixel art drawing of that many pixels, for example 64x64: its layers are pixel layers
+ --wrap
+ A tile: what is drawn past an edge comes back in on the other side
+
-h, --help
Print help
```
+## klad canvas
+
+```text
+The canvas: its size and background, and whether it wraps at its edges. On a canvas that wraps, a tile, pixels drawn past an edge come back in on the other side, and fills and outlines go round the edges, so the drawing repeats without a seam. klad render --repeat 3 shows it repeated.
+
+ klad canvas tile.klad
+ klad canvas tile.klad --wrap on
+
+As an op: {"op":"canvas","wrap":true}.
+
+Usage: klad canvas [OPTIONS] <BUNDLE>
+
+Arguments:
+ <BUNDLE>
+
+
+Options:
+ --wrap <WRAP>
+ Turn wrapping at the edges on or off
+
+ [possible values: on, off]
+
+ --render
+ Render a preview after the edit and print its path
+
+ --scale <SCALE>
+ Preview scale (default: longest side 1024 px)
+
+ --json
+ Print the result as JSON
+
+ --overlay <OVERLAY>
+ Draw on the preview: ids, bbox, grid or all (comma separated)
+
+ -h, --help
+ Print help (see a summary with '-h')
+```
+
## klad frames
```text
@@ -1465,6 +1507,11 @@ Options:
--no-cache
Replay every stroke instead of using cached tiles
+ --repeat <REPEAT>
+ Show the picture this many times across and down (up to 9), to check a tile's seams
+
+ [default: 1]
+
--references
Show reference layers (photos to trace over), which renders leave out
@@ -1765,6 +1812,12 @@ Options:
--path <PATH>
SVG path data drawn as a line of pixels, one pixel wide with no doubled corners on curves: 'M3.5 20.5 C 10 4 22 4 28.5 20.5'
+ --mirror-x <X>
+ Also draw the mirror image across the upright line at this x: a whole number is the line between two pixels, .5 runs through a column
+
+ --mirror-y <Y>
+ Also draw the mirror image across the level line at this y
+
--size <SIZE>
The pencil's size: a square of this many pixels a side (1 to 64)
diff --git a/docs/format.md b/docs/format.md
index 5318204..d4feb7c 100644
--- a/docs/format.md
+++ b/docs/format.md
@@ -1,4 +1,4 @@
-_Last updated: 2026-11-11 17:20 (format `klad/7`, stroke files `KLST` version 3, brushes `klad-brush/1`)_
+_Last updated: 2026-11-12 04:00 (format `klad/7`, stroke files `KLST` version 3, brushes `klad-brush/1`)_
# The klad drawing format
@@ -61,7 +61,7 @@ Writers replace files atomically (write a temporary file, then rename), so a rea
| Key | Type | Default | Meaning |
|---|---|---|---|
| `format` | string | | `"klad/7"` |
-| `canvas` | object | | `width`, `height` (px), `background` (a colour; none is transparent) |
+| `canvas` | object | | `width`, `height` (px), `background` (a colour; none is transparent), `wrap` (bool, default false: the drawing is a tile, and klad brings pixel marks drawn past an edge back in on the other side; it changes nothing about how the drawing renders) |
| `timeline` | object | 12 fps, 1 frame | see below |
| `palette` | array | `[]` | swatches: `color`, optional `name` (unique, not starting with `#`), optional `id` (unique; set once a pixel mark uses the swatch), optional `ramp` (the name of the ramp it belongs to) |
| `layers` | array | | the layers, **bottom first** |
diff --git a/docs/skill/SKILL.md b/docs/skill/SKILL.md
index 57534c7..85095ea 100644
--- a/docs/skill/SKILL.md
+++ b/docs/skill/SKILL.md
@@ -134,6 +134,8 @@ klad export sprite.klad --scale 8 -o [email protected] square pixels, to keep
- Shading with ramps: `--shade 1` (or `-1`) draws no colour of its own; every pixel it covers takes the next lighter (or darker) colour of its own ramp, so one call shades a form made of several materials: `klad pixel sprite.klad l1 --shade -1 --rect 4,12,16,4 --filled` darkens the lower part of whatever is there, and pixels in no ramp or at its end stay. It works with any source (cells, a path, a shape, a fill). So: block the form in each ramp's middle colour, then shade down on the side away from the light and up where the light hits.
- `--dither 50` draws only that share of the pixels, in an even pattern fixed to the canvas (50 a checkerboard, 25 one pixel in four, 75 three in four), and `--second <colour>` gives the others a second colour: a band of dither between two ramp steps softens the step. Use it sparingly and only at sizes where the pattern reads as a tone.
- `--outline` draws a one-pixel outline around what the layer shows, in `--color`, as one mark: every empty pixel that touches a drawn one (`--diagonal` also takes the corners, for a heavier line; `--inside` recolours the drawing's own edge pixels instead; `--ref <layer>` outlines another layer's pixels, to keep the outline on a layer of its own).
+- Symmetry: `--mirror-x 16` also draws the mirror image across the upright line at x 16 (a whole number is the line between two pixels, so 16 mirrors a 32 px sprite about its middle; `15.5` runs through column 15, for sprites with a middle column); `--mirror-y` mirrors across a level line, and both together give four copies. It works with every source, so draw half a face or half a tree and get the whole. In `apply`: `"mirrorX":16`.
+- Tiles: on a canvas that wraps (`klad new tile.klad --pixel 16 --wrap`, or `klad canvas tile.klad --wrap on`), pixels drawn past an edge come back in on the other side, and fills and outlines go round the edges, so a shape drawn over a corner shows in all four. `klad render tile.klad --repeat 3` shows the tile three times across and down: look there for seams, lines that do not meet and a pattern that reads as a grid. Moving marks with `klad transform` or `klad lasso` does not wrap.
- `--color` is a palette name, a palette index or `#rrggbb`. Every pixel mark is bound to a palette entry: a colour the palette lacks is added to it, so name the colours first (`klad palette sprite.klad --add '#f0c8a0' --name skin`) and draw with the names. `klad palette` lists the entries with their ids.
- The palette is the drawing's colours, and changing one changes the picture: `klad palette sprite.klad --recolour skin --to '#e8b796'` (a name, a colour, an index or an id) recolours every pixel mark drawn with it, on every frame. So fix a colour in the palette, not mark by mark. `klad palette sprite.klad --load pico-8` adds a palette that comes with klad (`klad palettes` lists them: pico-8, resurrect-64, four-greens, 1-bit) or a file (`.hex`, one colour per line, or a GIMP `.gpl`); colours the palette holds are not added twice. A ramp is a row of colours for one material, dark to light: `klad palette sprite.klad --ramp wood --base '#8b5a2b' --steps 5` makes `wood-1` (dark, cooler) to `wood-5` (light, warmer) around the base, and `--ramp skin --of skin-dark,skin,skin-light` groups colours it has. Shade a form with the steps of its ramp, not with new colours.
- Editing an area: `klad lasso sprite.klad l1 --box x,y,w,h --cut --move 2,0` takes the pixels in that box (its top left pixel and size; `--polygon` for another outline) and moves them by whole pixels; `--flip h`, `--rotate 90`, `--scale 2` and `--rm` work the same way. With `--cut` the box takes pixels: marks it crosses are split between whole pixels and the inside halves become marks of their own. Without it only marks that lie whole inside are taken. Quarter turns, flips and whole-number scales keep every pixel; other angles and scales stay hard but look jagged.