A drawing app built for agent/human collaboration
Rust
A sharp view for pixel drawings: whole zoom, a pixel grid, the pointer's pixel and a real size panel
Indicode BVc9193d879dec
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 16c4795..b2cb924 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.+- A sharp view for pixel drawings. In the editor the zoom steps in whole pixels, so every pixel is the same size; a grid shows between the pixels once you are zoomed in (**View > Pixel grid**), the pixel under the pointer is outlined and its position shows in the status line, and the **Real size** panel shows the drawing as the player sees it, at 1x, 2x or 4x. `klad render` enlarges a pixel drawing to about 512 px, and `--overlay grid` numbers its pixels along the top and the left.- Pixel layers, the start of pixel art in klad. A pixel drawing (**Pixel art** in the start window, or `klad new sprite.klad --pixel 64x64`) is a small drawing of whole pixels with no soft edges; **Layer > New pixel layer** or `klad add art.klad layer pixel` adds a pixel layer to any drawing. `klad pixel sprite.klad l1 --color skin --cells '4-11,5-9'` puts pixels on it as one mark bound to a palette colour (a colour the palette lacks is added), and `--erase` clears them. Each mark stays editable: recolour it with `klad set`, move it with `klad transform`, remove it with `klad rm`; `klad strokes` lists them. Exports above full size keep the pixels square. Brush strokes and fills stay off pixel layers. The format is now `klad/7` (stroke files version 3); older drawings open unchanged.- Align and distribute shapes. With **V**, shift click adds a shape to the selection and a loop dragged on a vector layer takes the shapes inside; several shapes move, scale, turn, flip, duplicate and delete together. The bar under them lines up their left, right, top or bottom edges or their centres and spaces three or more evenly; one shape lines up on the canvas (**Edit > Align**). From the command line: `klad align art.klad n3 n4 n7 --y middle --spread x`, with `--to canvas` or `--to <shape>` and `--gap`.- Fixed exports of a clip moved by keys (a layer, group or shape keyed between frames, with no drawing per frame): `klad export --sheet`, `--frames` and `--godot` wrote the first pose for every frame, and `klad render --sheet` showed them as held. Each pose is now its own picture.diff --git a/crates/app/src/commands.rs b/crates/app/src/commands.rsindex 31a5697..bf6d806 100644--- a/crates/app/src/commands.rs+++ b/crates/app/src/commands.rs@@ -127,6 +127,8 @@ pub enum Cmd {InspectorPane,NotesPane,HistoryPane,+ PreviewPane,+ PixelGrid,Timeline,Numbers,Settings,@@ -507,7 +509,7 @@ use Repeat as R;use Trigger as T;impl Cmd {- pub const ALL: [Cmd; 180] = [+ pub const ALL: [Cmd; 182] = [Cmd::Brush,Cmd::Eraser,Cmd::Fill,@@ -631,6 +633,8 @@ impl Cmd {Cmd::InspectorPane,Cmd::NotesPane,Cmd::HistoryPane,+ Cmd::PreviewPane,+ Cmd::PixelGrid,Cmd::Timeline,Cmd::Numbers,Cmd::Settings,@@ -1871,6 +1875,24 @@ impl Cmd {R::No,"start the measurements again",),+ Cmd::PreviewPane => spec(+ "panel.real-size",+ "real size panel",+ icon::IMAGE,+ G::Panels,+ T::None,+ R::No,+ "show or hide the drawing at its real size in the dock: one pixel of the drawing on one pixel of the screen, or 2 or 4",+ ),+ Cmd::PixelGrid => spec(+ "view.pixel-grid",+ "pixel grid",+ icon::PIXELS,+ G::View,+ T::None,+ R::No,+ "lines between the pixels of a pixel drawing once it is zoomed in far enough to tell them apart",+ ),Cmd::FlipView => spec("view.flip","flip the view left-right",@@ -2434,6 +2456,8 @@ impl Cmd {Cmd::InspectorPane => "Layer settings",Cmd::NotesPane => "Notes",Cmd::HistoryPane => "History",+ Cmd::PreviewPane => "Real size",+ Cmd::PixelGrid => "Pixel grid",Cmd::Timeline => "Timeline",Cmd::Numbers => "Show numbers",Cmd::Settings => "Settings…",@@ -2774,6 +2798,7 @@ pub const MENUS: [Menu; 9] = [Run(Cmd::TurnLeft),Run(Cmd::ResetRotation),Run(Cmd::FlipView),+ Run(Cmd::PixelGrid),Line,Run(Cmd::CompareReference),],@@ -2790,6 +2815,7 @@ pub const MENUS: [Menu; 9] = [Run(Cmd::InspectorPane),Run(Cmd::NotesPane),Run(Cmd::HistoryPane),+ Run(Cmd::PreviewPane),Run(Cmd::Timeline),Line,Run(Cmd::MessageLog),diff --git a/crates/app/src/editor.rs b/crates/app/src/editor.rsindex 8326a56..b840cd7 100644--- a/crates/app/src/editor.rs+++ b/crates/app/src/editor.rs@@ -82,6 +82,10 @@ const FINISH_WAIT: Duration = Duration::from_secs(2);const DRAG_SLOP: f32 = 3.0;const KNOB: f32 = 30.0;const IDENTITY: [f32; 6] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];+const GRID_FROM: f32 = 8.0;+pub(crate) const REAL_MAX: u32 = 512;++type RealKey = (u64, u32, u64);fn raw_of(e: &PenEvent, c: Vec2, dt_ms: f32) -> Raw {Raw {@@ -700,6 +704,10 @@ pub(crate) struct Editor {preview: Option<PreviewState>,outbox: Arc<Mutex<Outbox>>,zoom_px: f32,+ zoom_wanted: Option<f32>,+ hover_cell: Option<[i32; 2]>,+ painted: u64,+ real: Option<(RealKey, egui::TextureHandle)>,picked: Option<Picked>,also: Vec<String>,direct: Option<Direct>,@@ -743,7 +751,14 @@ impl Editor {.ok_or_else(|| crate::report::bug("the ink brush is missing from the library"))?,);let settings_path = settings::default_path();- let settings = settings_path.as_deref().map(Settings::load).unwrap_or_default();+ let mut settings = settings_path.as_deref().map(Settings::load).unwrap_or_default();+ let offered = scene.bundle.doc.pixel_art() && !settings.real_size_shown;+ if offered {+ settings.real_size_shown = true;+ if !settings.layout.is_open(crate::layout::Pane::Preview) {+ settings.layout.toggle(crate::layout::Pane::Preview);+ }+ }let open = format!("{} layers, opened in {:.0} ms",scene.bundle.doc.all_layers().len(),@@ -786,7 +801,7 @@ impl Editor {flow: 1.0,settings,settings_path,- settings_dirty: false,+ settings_dirty: offered,update: None,update_feed: crate::updates::feed(),update_check: None,@@ -882,6 +897,10 @@ impl Editor {preview: None,outbox: Arc::default(),zoom_px: 1.0,+ zoom_wanted: None,+ hover_cell: None,+ painted: 0,+ real: None,picked: None,also: Vec::new(),direct: None,@@ -3358,7 +3377,14 @@ impl Editor {};let at = hover.filter(|p| rect.contains(*p)).map_or(area / 2.0, |p| p - rect.min);if response.hovered() || response.dragged() {- if zoom != 1.0 {+ if zoom != 1.0 && self.scene.bundle.doc.pixel_art() {+ let wanted = (self.zoom_wanted.unwrap_or(view.zoom) * zoom).clamp(0.02, 64.0);+ self.zoom_wanted = Some(wanted);+ let target = View::whole(wanted, ui.ctx().pixels_per_point());+ if target != view.zoom {+ view.zoom_at(target / view.zoom, at, area);+ }+ } else if zoom != 1.0 {view.zoom_at(zoom, at, area);}if scroll != Vec2::ZERO {@@ -3384,7 +3410,9 @@ impl Editor {self.canvas_rect = rect;let area = rect.size();let canvas = self.canvas_size();- self.view.get_or_insert_with(|| View::fit(canvas, area));+ if self.view.is_none() {+ self.view = Some(self.fitted(area));+ }self.navigate(ui, &response, rect);self.keep_typing_focus(ui, &response)?;self.typing_keys(ui)?;@@ -3415,7 +3443,7 @@ impl Editor {{self.select_pin(view.to_canvas(p - rect.min, rect.size()))?;}- let view = self.view.unwrap_or_else(|| View::fit(canvas, area));+ let view = self.view.unwrap_or_else(|| self.fitted(area));self.double_click_text(&response, view, rect)?;self.zoom_px = view.zoom * ctx.pixels_per_point();self.refresh_box();@@ -3474,6 +3502,9 @@ impl Editor {stats.tiles.push(uploads.len() as f32);}let uploads: Tiles = previewed.into_iter().chain(uploads).collect();+ if !uploads.is_empty() {+ self.painted += 1;+ }let (frame_uploads, frame_drops) = self.frames.take();lock(&self.outbox).send(uploads, frame_uploads, frame_drops);ui.painter().add(egui_wgpu::Callback::new_paint_callback(@@ -3490,11 +3521,16 @@ impl Editor {));self.parallax(ui, view, rect);self.prepare_typing(&ctx, view, rect);- self.decorate(ui, view, rect);let hover = ui.input(|i| i.pointer.hover_pos()).filter(|p| rect.contains(*p)).map(|p| view.to_canvas(p - rect.min, rect.size()));+ self.hover_cell = hover+ .filter(|_| self.scene.bundle.doc.pixel_art())+ .filter(|p| p.x >= 0.0 && p.y >= 0.0 && p.x < canvas.x && p.y < canvas.y)+ .map(|p| [p.x.floor() as i32, p.y.floor() as i32]);+ self.decorate_grid(ui, view, rect);+ self.decorate(ui, view, rect);let painter = ui.painter().with_clip_rect(rect);self.decorate_bones(&painter, |c| rect.min + view.to_screen(c, rect.size()), hover);if self.live.is_some()@@ -3513,6 +3549,59 @@ impl Editor {Ok(())}+ pub(super) fn fitted(&self, area: Vec2) -> View {+ match self.scene.bundle.doc.pixel_art() {+ true => View::fit_whole(self.canvas_size(), area, self.ctx.pixels_per_point()),+ false => View::fit(self.canvas_size(), area),+ }+ }++ pub(super) fn grid_shows(&self) -> bool {+ self.settings.pixel_grid && self.zoom_px >= GRID_FROM && self.scene.bundle.doc.pixel_art()+ }++ fn decorate_grid(&self, ui: &egui::Ui, view: View, rect: Rect) {+ let painter = ui.painter().with_clip_rect(rect);+ let canvas = self.canvas_size();+ if self.grid_shows() {+ let corners = [+ rect.left_top(),+ rect.right_top(),+ rect.right_bottom(),+ rect.left_bottom(),+ ]+ .map(|p| view.to_canvas(p - rect.min, rect.size()));+ let low = |f: fn(&Vec2) -> f32| corners.iter().map(f).fold(f32::MAX, f32::min);+ let high = |f: fn(&Vec2) -> f32| corners.iter().map(f).fold(f32::MIN, f32::max);+ let (x0, x1) = (low(|p| p.x).floor().max(0.0), high(|p| p.x).ceil().min(canvas.x));+ let (y0, y1) = (low(|p| p.y).floor().max(0.0), high(|p| p.y).ceil().min(canvas.y));+ let dark = egui::Stroke::new(1.0, Color32::from_black_alpha(70));+ let light = egui::Stroke::new(1.0, Color32::from_white_alpha(90));+ let to_screen = |x: f32, y: f32| self.screen(view, rect, vec2(x, y));+ let rule = |a: Pos2, b: Pos2| {+ painter.line_segment([a, b], dark);+ painter.extend(egui::Shape::dashed_line(&[a, b], light, 2.0, 2.0));+ };+ (x0 as i32..=x1 as i32)+ .map(|x| x as f32)+ .for_each(|x| rule(to_screen(x, y0), to_screen(x, y1)));+ (y0 as i32..=y1 as i32)+ .map(|y| y as f32)+ .for_each(|y| rule(to_screen(x0, y), to_screen(x1, y)));+ }+ if let Some([x, y]) = self.hover_cell.filter(|_| self.scene.on_grid() && self.zoom_px >= 3.0) {+ let (x, y) = (x as f32, y as f32);+ let cell = [(x, y), (x + 1.0, y), (x + 1.0, y + 1.0), (x, y + 1.0)]+ .map(|(x, y)| self.screen(view, rect, vec2(x, y)))+ .to_vec();+ painter.add(egui::Shape::closed_line(+ cell.clone(),+ egui::Stroke::new(3.0, Color32::from_black_alpha(150)),+ ));+ painter.add(egui::Shape::closed_line(cell, egui::Stroke::new(1.0, Color32::WHITE)));+ }+ }+fn decorate(&self, ui: &egui::Ui, view: View, rect: Rect) {let painter = ui.painter().with_clip_rect(rect);let accent = Color32::from_rgb(64, 196, 255);diff --git a/crates/app/src/editor/commands.rs b/crates/app/src/editor/commands.rsindex ee56a0b..722c1ea 100644--- a/crates/app/src/editor/commands.rs+++ b/crates/app/src/editor/commands.rs@@ -7,7 +7,6 @@ use crate::layout::Pane;use crate::messages::Tone;use crate::stats::{Stats, lock};use crate::theme::{self, Hint};-use crate::view::View;use anyhow::Result;use egui::RichText;use klad_core::doc::{Kind as LayerKind, MASK, Shape};@@ -163,6 +162,8 @@ impl Editor {.view.is_none().then(|| "the canvas is not shown yet: wait a moment".to_string()),+ 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.filter(|d| !d.points.is_empty()).is_none()@@ -382,6 +383,8 @@ impl Editor {Cmd::Brush => self.tool == Tool::Brush && !erasing,Cmd::Eraser => self.tool == Tool::Brush && erasing,Cmd::FlipView => self.view.is_some_and(|v| v.flip),+ Cmd::PixelGrid => self.settings.pixel_grid,+ Cmd::PreviewPane => layout.dock && layout.is_open(Pane::Preview),Cmd::Fill => self.tool == Tool::Fill,Cmd::Shapes => self.tool == Tool::Select,Cmd::Strokes => self.tool == Tool::Strokes,@@ -545,8 +548,12 @@ impl Editor {Cmd::Note => self.tool = Tool::Note,Cmd::Smaller => self.size = (self.size / 1.25).max(0.5),Cmd::Bigger => self.size = (self.size * 1.25).min(800.0),- Cmd::Fit => self.view = Some(View::fit(self.canvas_size(), area)),+ Cmd::Fit => {+ self.view = Some(self.fitted(area));+ self.zoom_wanted = None;+ }Cmd::ActualSize => {+ self.zoom_wanted = None;let ppp = self.ctx.pixels_per_point();if let Some(view) = self.view.as_mut() {view.zoom_at(1.0 / (view.zoom * ppp), area / 2.0, area);@@ -896,6 +903,11 @@ impl Editor {Cmd::InspectorPane => self.pane(Pane::Inspector),Cmd::NotesPane => self.pane(Pane::Notes),Cmd::HistoryPane => self.pane(Pane::History),+ Cmd::PreviewPane => self.pane(Pane::Preview),+ Cmd::PixelGrid => {+ self.settings.pixel_grid = !self.settings.pixel_grid;+ self.settings_dirty = true;+ }Cmd::Timeline => {self.settings.layout.timeline = !self.settings.layout.timeline;self.settings_dirty = true;diff --git a/crates/app/src/editor/panels.rs b/crates/app/src/editor/panels.rsindex 0ab446f..2b1bf99 100644--- a/crates/app/src/editor/panels.rs+++ b/crates/app/src/editor/panels.rs@@ -651,9 +651,82 @@ impl Editor {},Pane::Notes => self.notes_pane(ui),Pane::History => self.history_pane(ui),+ Pane::Preview => self.real_size_pane(ui),}}+ fn real_size_pane(&mut self, ui: &mut egui::Ui) -> Result<()> {+ let (w, h) = self.scene.size();+ if w > super::REAL_MAX || h > super::REAL_MAX {+ ui.label(+ RichText::new(format!(+ "this panel shows drawings up to {} px a side at their real size; this one is {w} x {h}",+ super::REAL_MAX+ ))+ .color(theme::WEAK),+ );+ return Ok(());+ }+ ui.horizontal(|ui| {+ [1u32, 2, 4].into_iter().for_each(|scale| {+ let chosen = self.settings.real_size_scale == scale;+ if ui+ .selectable_label(chosen, format!("{scale}x"))+ .hint(format!(+ "one pixel of the drawing on {} of the screen",+ match scale {+ 1 => "one pixel".to_string(),+ n => format!("{n} by {n} pixels"),+ }+ ))+ .clicked()+ && !chosen+ {+ self.settings.real_size_scale = scale;+ self.settings_dirty = true;+ }+ });+ ui.label(RichText::new(format!("{w} x {h}")).color(theme::WEAK));+ });+ let key = (self.scene.bundle.doc.rev, self.scene.frame, self.painted);+ if self.real.as_ref().is_none_or(|(held, _)| *held != key) {+ let tiles = self.scene.compose(&self.scene.all_tiles(), None)?;+ let image = real_image((w, h), self.scene.cols(), &tiles);+ let texture = ui.ctx().load_texture("real size", image, egui::TextureOptions::NEAREST);+ self.real = Some((key, texture));+ }+ let Some((_, texture)) = self.real.as_ref() else {+ return Ok(());+ };+ let scale = self.settings.real_size_scale.clamp(1, 4) as f32 / ui.ctx().pixels_per_point();+ let size = vec2(w as f32, h as f32) * scale;+ egui::ScrollArea::both().id_salt("real size").show(ui, |ui| {+ let (rect, _) = ui.allocate_exact_size(size, Sense::hover());+ let painter = ui.painter().with_clip_rect(rect);+ painter.rect_filled(rect, 0.0, Color32::from_gray(235));+ let cell = 8.0;+ let (cols, rows) = ((size.x / cell).ceil() as usize, (size.y / cell).ceil() as usize);+ (0..rows)+ .flat_map(|j| (0..cols).map(move |i| (i, j)))+ .filter(|(i, j)| (i + j) % 2 == 1)+ .for_each(|(i, j)| {+ let at = rect.min + vec2(i as f32 * cell, j as f32 * cell);+ painter.rect_filled(+ egui::Rect::from_min_size(at, vec2(cell, cell)),+ 0.0,+ Color32::from_gray(204),+ );+ });+ painter.image(+ texture.id(),+ rect,+ egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)),+ Color32::WHITE,+ );+ });+ Ok(())+ }+fn status_line(&mut self, ui: &mut egui::Ui) {let now = Instant::now();let mut cancel = None;@@ -704,6 +777,10 @@ impl Editor {{self.queued.push(Cmd::ResetRotation);}+ if let Some([x, y]) = self.hover_cell {+ ui.add(flat(format!("{x}, {y}")))+ .hint("the pixel under the pointer: across, then down, from the top left");+ }if view.flip&& ui.add(flat(format!("{} flipped", icon::FLIP_H)))@@ -1212,3 +1289,27 @@ impl Editor {}}}++pub(super) fn real_image((w, h): (u32, u32), cols: usize, tiles: &[(usize, Vec<half::f16>)]) -> egui::ColorImage {+ let side = klad_brush::TILE;+ let byte = |v: half::f16| (v.to_f32().clamp(0.0, 1.0) * 255.0).round() as u8;+ let pixels: Vec<Color32> = (0..h as usize)+ .flat_map(|y| (0..w as usize).map(move |x| (x, y)))+ .map(|(x, y)| {+ let index = (y / side) * cols + x / side;+ match tiles.iter().find(|(i, _)| *i == index) {+ Some((_, tile)) => {+ let at = ((y % side) * side + x % side) * 4;+ Color32::from_rgba_premultiplied(+ byte(tile[at]),+ byte(tile[at + 1]),+ byte(tile[at + 2]),+ byte(tile[at + 3]),+ )+ }+ None => Color32::TRANSPARENT,+ }+ })+ .collect();+ egui::ColorImage::new([w as usize, h as usize], pixels)+}diff --git a/crates/app/src/editor/ui_tests.rs b/crates/app/src/editor/ui_tests.rsindex e27ee9e..5ba9504 100644--- a/crates/app/src/editor/ui_tests.rs+++ b/crates/app/src/editor/ui_tests.rs@@ -1513,6 +1513,119 @@ fn a_pixel_layer_is_added_shows_its_marks_hard_and_keeps_brush_strokes_out() {let _ = std::fs::remove_dir_all(&path);}+fn pixel_sample(name: &str) -> PathBuf {+ let dir = std::env::temp_dir().join(format!("draw-ui-{name}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ let mut bundle = Bundle::blank(+ &dir,+ &klad_core::bundle::Blank {+ width: 32,+ height: 24,+ pixel: true,+ ..klad_core::bundle::Blank::default()+ },+ "cli",+ )+ .unwrap();+ let layer = bundle.doc.layers[0].id.clone();+ bundle+ .apply(+ &parse_lines(&format!(+ "{}\n{}",+ format_args!(+ r##"{{"op":"pixel","layer":"{layer}","color":"#2b2d42","cells":[[4,4],[5,4],[6,4],[4,5],[6,5],[4,6],[5,6],[6,6]]}}"##+ ),+ format_args!(r##"{{"op":"pixel","layer":"{layer}","color":"#ef233c","cells":[[5,5]]}}"##),+ ))+ .unwrap(),+ )+ .unwrap();+ dir+}++#[test]+fn a_pixel_drawing_zooms_in_whole_steps_and_shows_its_grid_the_pointers_pixel_and_its_real_size() {+ let path = pixel_sample("sharp");+ let mut h = harness(editor(&path), vec2(1440.0, 900.0));+ let ppp = h.ctx.pixels_per_point();+ let whole = |h: &Harness<'static, Editor>| {+ let px = h.state().view.unwrap().zoom * ppp;+ assert!(+ (px - px.round()).abs() < 1e-4,+ "{px} screen pixels per pixel is not a whole number"+ );+ px.round() as u32+ };+ assert!(whole(&h) >= 8, "a 32 pixel drawing opens enlarged");+ h.state_mut().invoke(Cmd::Fit).unwrap();+ h.run_steps(2);+ let fitted = whole(&h);+ let rect = h.state().canvas_rect;+ assert!(fitted >= 8, "and fits enlarged: {fitted}");+ assert!(+ 32.0 * fitted as f32 / ppp <= rect.width() && 24.0 * fitted as f32 / ppp <= rect.height(),+ "and whole on the canvas"+ );+ assert!(h.state().grid_shows(), "zoomed in this far the grid shows");+ h.hover_at(rect.center());+ h.run_steps(1);+ (0..6).for_each(|_| {+ h.event(egui::Event::Zoom(0.9));+ h.run_steps(1);+ whole(&h);+ });+ let smaller = whole(&h);+ assert!(smaller < fitted, "pinching zooms out: {smaller} from {fitted}");+ (0..40).for_each(|_| {+ h.event(egui::Event::Zoom(0.8));+ h.run_steps(1);+ });+ assert!(+ h.state().view.unwrap().zoom * ppp < 1.0,+ "below real size the zoom is free again"+ );+ assert!(!h.state().grid_shows(), "and the grid is gone");+ h.state_mut().invoke(Cmd::Fit).unwrap();+ h.run_steps(2);+ assert_eq!(whole(&h), fitted, "fit comes back to the largest whole zoom");+ let at = on_screen(&h, 5.5, 7.5);+ h.hover_at(at);+ h.run_steps(2);+ assert_eq!(h.state().hover_cell, Some([5, 7]));+ assert!(+ h.query_by_label("5, 7").is_some(),+ "the status line names the pixel under the pointer"+ );+ h.state_mut().invoke(Cmd::PixelGrid).unwrap();+ h.run_steps(1);+ assert!(!h.state().grid_shows() && h.state().is_on(Cmd::PixelGrid) == Some(false));+ h.state_mut().invoke(Cmd::PixelGrid).unwrap();+ assert!(!h.state().settings.layout.is_open(Pane::Preview));+ h.state_mut().invoke(Cmd::PreviewPane).unwrap();+ h.run_steps(3);+ assert!(h.query_by_label("Real size").is_some() && h.query_by_label("32 x 24").is_some());+ let (_, texture) = h.state().real.as_ref().expect("the drawing at its real size");+ assert_eq!(texture.size(), [32, 24]);+ h.get_by_label("2x").click();+ h.run_steps(2);+ assert_eq!(h.state().settings.real_size_scale, 2);+ let painting = sample("no-grid");+ let plain = harness(editor(&painting), vec2(1440.0, 900.0));+ assert!(+ plain+ .state()+ .can_run(Cmd::PixelGrid)+ .is_some_and(|why| why.contains("no pixel layer"))+ );+ let px = plain.state().view.unwrap().zoom * ppp;+ assert!(+ (px - px.round()).abs() > 1e-3,+ "a painting still fits at any zoom: {px}"+ );+ let _ = std::fs::remove_dir_all(&path);+ let _ = std::fs::remove_dir_all(&painting);+}+#[test]fn a_tap_that_wobbles_selects_and_a_drag_past_three_points_moves() {let path = sample("tap");diff --git a/crates/app/src/layout.rs b/crates/app/src/layout.rsindex 79050de..3f7612c 100644--- a/crates/app/src/layout.rs+++ b/crates/app/src/layout.rs@@ -20,6 +20,7 @@ pub enum Pane {Inspector,Notes,History,+ Preview,}impl Pane {@@ -31,6 +32,7 @@ impl Pane {Pane::Inspector => "Layer settings",Pane::Notes => "Notes for the agent",Pane::History => "History",+ Pane::Preview => "Real size",}}@@ -42,6 +44,7 @@ impl Pane {Pane::Inspector => 110.0,Pane::Notes => 60.0,Pane::History => 60.0,+ Pane::Preview => 110.0,}}@@ -53,6 +56,7 @@ impl Pane {Pane::Inspector => 220.0,Pane::Notes => 90.0,Pane::History => 80.0,+ Pane::Preview => 170.0,}}}@@ -91,17 +95,18 @@ impl Default for Layout {timeline_folded: false,numbers: false,panes: [- (Pane::Tool, false),- (Pane::Brush, false),- (Pane::Layers, false),- (Pane::Inspector, false),- (Pane::Notes, true),- (Pane::History, true),+ (Pane::Tool, true, false),+ (Pane::Preview, false, false),+ (Pane::Brush, true, false),+ (Pane::Layers, true, false),+ (Pane::Inspector, true, false),+ (Pane::Notes, true, true),+ (Pane::History, true, true),].into_iter()- .map(|(pane, collapsed)| PaneState {+ .map(|(pane, open, collapsed)| PaneState {pane,- open: true,+ open,collapsed,body: pane.default_body(),})@@ -335,7 +340,11 @@ mod tests {).unwrap().repaired();- assert_eq!(old.panes.len(), 6);+ assert_eq!(old.panes.len(), 7);+ assert!(+ !old.is_open(Pane::Preview),+ "a pane that is new to old settings keeps its default"+ );assert_eq!(old.panes[0].pane, Pane::Layers);assert_eq!(old.panes[0].body, Pane::Layers.min_body());}diff --git a/crates/app/src/settings.rs b/crates/app/src/settings.rsindex 6af219b..ee301f7 100644--- a/crates/app/src/settings.rs+++ b/crates/app/src/settings.rs@@ -91,6 +91,16 @@ pub struct Settings {pub developer: bool,#[serde(default, rename = "eraserFeather", skip_serializing_if = "Option::is_none")]pub eraser_feather: Option<f32>,+ #[serde(default = "yes", rename = "pixelGrid")]+ pub pixel_grid: bool,+ #[serde(default, rename = "realSizeShown", skip_serializing_if = "std::ops::Not::not")]+ pub real_size_shown: bool,+ #[serde(default = "one_u32", rename = "realSizeScale")]+ pub real_size_scale: u32,+}++fn one_u32() -> u32 {+ 1}fn yes() -> bool {@@ -116,12 +126,15 @@ impl Default for Settings {pick_all_layers: true,developer: false,eraser_feather: None,+ pixel_grid: true,+ real_size_shown: false,+ real_size_scale: 1,}}}fn migrate(mut value: serde_json::Value) -> serde_json::Value {- const PANES: [&str; 5] = ["tool", "layers", "inspector", "notes", "history"];+ const PANES: [&str; 7] = ["tool", "brush", "layers", "inspector", "notes", "history", "preview"];if let Some(panes) = value.pointer_mut("/layout/panes").and_then(|p| p.as_array_mut()) {panes.retain(|p| p["pane"].as_str().is_some_and(|name| PANES.contains(&name)));}@@ -250,15 +263,36 @@ mod tests {&path,r#"{"uiScale":1.25,"recentDocuments":["/w/a.klad"],"agent":{"model":"m","limit":2.0},"layout":{"dockWidth":400,"panes":[{"pane":"agent","open":true,"collapsed":false,"body":300},- {"pane":"layers","open":true,"collapsed":false,"body":200}]}}"#,+ {"pane":"layers","open":true,"collapsed":false,"body":200},+ {"pane":"brush","open":false,"collapsed":false,"body":150},+ {"pane":"preview","open":true,"collapsed":true,"body":150}]}}"#,).unwrap();let settings = Settings::load(&path);assert_eq!(settings.ui_scale, 1.25);assert_eq!(settings.documents, ["/w/a.klad"]);assert_eq!(settings.layout.dock_width, 400.0);- assert_eq!(settings.layout.panes.len(), 6);+ assert_eq!(settings.layout.panes.len(), 7);assert_eq!(settings.layout.panes[0].pane, crate::layout::Pane::Layers);+ let pane = |pane| settings.layout.pane(pane).map(|p| (p.open, p.collapsed));+ assert_eq!(+ pane(crate::layout::Pane::Brush),+ Some((false, false)),+ "a closed brush pane stays closed"+ );+ assert_eq!(+ pane(crate::layout::Pane::Preview),+ Some((true, true)),+ "the real size pane comes back as it was left"+ );+ assert_eq!(+ Settings::default()+ .layout+ .pane(crate::layout::Pane::Preview)+ .map(|p| p.open),+ Some(false),+ "and is closed until a pixel drawing opens it"+ );fs::remove_dir_all(&dir).unwrap();}diff --git a/crates/app/src/view.rs b/crates/app/src/view.rsindex d9c7432..78a893f 100644--- a/crates/app/src/view.rs+++ b/crates/app/src/view.rs@@ -30,6 +30,26 @@ impl View {}}+ pub fn whole(zoom: f32, pixels_per_point: f32) -> f32 {+ let px = zoom * pixels_per_point;+ match px >= 1.0 {+ true => px.round().clamp(1.0, 64.0) / pixels_per_point,+ false => zoom,+ }+ }++ pub fn fit_whole(canvas: Vec2, area: Vec2, pixels_per_point: f32) -> Self {+ let fit = Self::fit(canvas, area);+ let px = fit.zoom * pixels_per_point;+ Self {+ zoom: match px >= 1.0 {+ true => px.floor().clamp(1.0, 64.0) / pixels_per_point,+ false => fit.zoom,+ },+ ..fit+ }+ }+pub fn to_screen(self, canvas: Vec2, area: Vec2) -> Vec2 {rotate(mirror(canvas - self.center, self.flip), self.angle) * self.zoom + area / 2.0}@@ -108,6 +128,33 @@ mod tests {assert!(close(view.to_canvas(view.to_screen(p, area), area), p));}+ #[test]+ fn a_pixel_drawing_fits_and_zooms_at_whole_screen_pixels_per_pixel() {+ let area = Vec2::new(900.0, 700.0);+ let fit = View::fit_whole(Vec2::new(64.0, 64.0), area, 2.0);+ assert_eq!(+ fit.zoom * 2.0,+ 20.0,+ "the largest whole number under 700 * 0.92 * 2 / 64"+ );+ assert_eq!(fit.center, Vec2::new(32.0, 32.0));+ let large = View::fit_whole(Vec2::new(4096.0, 4096.0), area, 2.0);+ assert_eq!(+ large.zoom,+ View::fit(Vec2::new(4096.0, 4096.0), area).zoom,+ "under real size it fits freely"+ );+ assert_eq!(View::whole(3.4, 1.0), 3.0);+ assert_eq!(View::whole(3.6, 1.0), 4.0);+ assert_eq!(+ View::whole(1.3, 2.0),+ 1.5,+ "on a dense screen half steps are whole screen pixels"+ );+ assert_eq!(View::whole(0.4, 1.0), 0.4);+ assert_eq!(View::whole(200.0, 1.0), 64.0);+ }+#[test]fn zoom_and_rotate_keep_the_anchor() {let area = Vec2::new(1000.0, 700.0);diff --git a/crates/cli/src/agent.rs b/crates/cli/src/agent.rsindex 1ec6eef..b6d6278 100644--- a/crates/cli/src/agent.rs+++ b/crates/cli/src/agent.rs@@ -14,6 +14,7 @@ use std::io::Read;use std::path::{Path, PathBuf};pub const PREVIEW_SIDE: f32 = 1024.0;+pub const PIXEL_SIDE: f32 = 512.0;const STRING_KEYS: [&str; 5] = ["name", "d", "id", "link", "text"];pub struct Output {@@ -175,10 +176,14 @@ pub fn add_op(what: &str, rest: &[String], place: Place) -> Result<Op> {}}+pub fn pixel_scale(bundle: &Bundle, longest: f32) -> Option<f32> {+ (bundle.doc.pixel_art() && longest <= PIXEL_SIDE).then(|| (PIXEL_SIDE / longest.max(1.0)).floor().clamp(1.0, 64.0))+}+fn preview_scale(bundle: &Bundle, scale: Option<f32>) -> f32 {scale.unwrap_or_else(|| {let longest = bundle.doc.canvas.width.max(bundle.doc.canvas.height) as f32;- (PREVIEW_SIDE / longest).min(1.0)+ pixel_scale(bundle, longest).unwrap_or((PREVIEW_SIDE / longest).min(1.0))})}@@ -368,7 +373,7 @@ pub fn focus_view(bundle: &Bundle, id: &str, frame: u32, scale: Option<f32>) ->}let (rw, rh) = (x1 - x0, y1 - y0);Ok(View {- scale: scale.unwrap_or_else(|| PREVIEW_SIDE / rw.max(rh)),+ scale: scale.unwrap_or_else(|| pixel_scale(bundle, rw.max(rh)).unwrap_or(PREVIEW_SIDE / rw.max(rh))),region: Some([x0 as i32, y0 as i32, rw as i32, rh as i32]),references: false,})@@ -410,6 +415,7 @@ pub fn render_look(boxes: kinds.bbox || kinds.parts,ids: kinds.ids || kinds.parts,grid: kinds.grid,+ cells: bundle.doc.pixel_art(),arcs: arcs_of(bundle, look, frame, kinds.arcs)?,frame: Some(frame),numbers: true,diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rsindex ef6e2d9..d29a8b0 100644--- a/crates/cli/src/main.rs+++ b/crates/cli/src/main.rs@@ -707,7 +707,10 @@ enum Command {out: Option<PathBuf>,#[arg(long, default_value_t = 0)]frame: u32,- #[arg(long, help = "Scale (default 1, or longest side 1024 px with --focus)")]+ #[arg(+ long,+ help = "Scale (default 1, or longest side 1024 px with --focus; a pixel drawing is enlarged by a whole number to about 512 px)"+ )]scale: Option<f32>,#[arg(long, value_parser = parse_region, help = "Only this canvas region: x,y,w,h")]region: Option<[i32; 4]>,@@ -3874,11 +3877,16 @@ fn render(let bundle = Bundle::open(path)?;let view = match &look.focus {Some(id) => agent::focus_view(&bundle, id, frame, scale)?,- None => View {- scale: scale.unwrap_or(1.0),- region,- references: false,- },+ None => {+ let longest = region.map_or(bundle.doc.canvas.width.max(bundle.doc.canvas.height) as f32, |r| {+ r[2].max(r[3]) as f32+ });+ View {+ scale: scale.or_else(|| agent::pixel_scale(&bundle, longest)).unwrap_or(1.0),+ region,+ references: false,+ }+ }};let done = agent::render_look(&bundle, frame, view, look, out, use_cache)?;println!("{}", done.path.display());diff --git a/crates/cli/tests/binary.rs b/crates/cli/tests/binary.rsindex 3042efe..3a6fb4d 100644--- a/crates/cli/tests/binary.rs+++ b/crates/cli/tests/binary.rs@@ -575,6 +575,26 @@ fn a_pixel_drawing_is_made_drawn_listed_and_edited_from_the_command_line() {assert!(String::from_utf8_lossy(&refused.stderr).contains("pixel layer"));let bad = run(&["pixel", path, &layer, "--color", "skin", "--cells", "3;4"]);assert!(String::from_utf8_lossy(&bad.stderr).contains("is not x,y"));+ let shown = run(&["render", path]);+ assert!(+ String::from_utf8_lossy(&shown.stderr).contains("512x384"),+ "a pixel drawing renders enlarged by a whole number: {}",+ String::from_utf8_lossy(&shown.stderr)+ );+ let hash = |out: &std::process::Output| {+ String::from_utf8_lossy(&out.stderr)+ .split_whitespace()+ .skip_while(|word| *word != "hash")+ .nth(1)+ .map(String::from)+ };+ let gridded = run(&["render", path, "--overlay", "grid"]);+ assert!(+ gridded.status.success() && hash(&gridded) != hash(&shown),+ "the grid overlay draws its lines"+ );+ let real = run(&["render", path, "--scale", "1"]);+ assert!(String::from_utf8_lossy(&real.stderr).contains("16x12"));draw(&["add", path, "layer", "pixel", "name=shade"]);assert_eq!(json(&["ls", path, "--json"])["layers"][0]["kind"], "pixel");std::fs::remove_dir_all(&dir).unwrap();diff --git a/crates/core/src/doc.rs b/crates/core/src/doc.rsindex d72fba6..988899f 100644--- a/crates/core/src/doc.rs+++ b/crates/core/src/doc.rs@@ -1055,6 +1055,10 @@ impl Document {}}+ pub fn pixel_art(&self) -> bool {+ self.all_layers().iter().any(|l| l.pixel())+ }+pub fn all_layers(&self) -> Vec<&Layer> {let mut out = Vec::new();walk_layers(&self.layers, &mut out);diff --git a/crates/render/src/overlay.rs b/crates/render/src/overlay.rsindex 745b488..188fca8 100644--- a/crates/render/src/overlay.rs+++ b/crates/render/src/overlay.rs@@ -116,6 +116,7 @@ pub struct Overlay {pub boxes: bool,pub ids: bool,pub grid: bool,+ pub cells: bool,pub arcs: Vec<Arc>,pub frame: Option<u32>,pub numbers: bool,@@ -308,6 +309,64 @@ fn grid_step(scale: f32) -> f32 {.unwrap_or(4096.0)}+fn cell_steps(scale: f32) -> (f32, f32) {+ let step = |least: f32| {+ [1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0]+ .into_iter()+ .find(|s| s * scale >= least)+ .unwrap_or(128.0)+ };+ (step(6.0), step(26.0))+}++fn draw_cells(canvas: &Canvas, origin: (f32, f32), scale: f32, size: (f32, f32), px: f32) {+ let (step, labelled) = cell_steps(scale);+ let stroke = |rgb: [f32; 3], alpha: f32, dashed: bool| {+ let mut paint = color(rgb, alpha);+ paint.set_style(PaintStyle::Stroke);+ paint.set_stroke_width(1.0);+ if dashed {+ paint.set_path_effect(skia_safe::PathEffect::dash(&[2.0, 2.0], 0.0));+ }+ paint+ };+ let first = |o: f32| (o / step).ceil() * step;+ let named = |v: f32| (v / labelled).fract() == 0.0;+ let xs: Vec<f32> = std::iter::successors(Some(first(origin.0)), |v| Some(v + step))+ .take_while(|v| (v - origin.0) * scale < size.0)+ .collect();+ let ys: Vec<f32> = std::iter::successors(Some(first(origin.1)), |v| Some(v + step))+ .take_while(|v| (v - origin.1) * scale < size.1)+ .collect();+ let lines = |v: f32| match named(v) {+ true => [stroke([0.0, 0.0, 0.0], 0.55, false), stroke([1.0, 1.0, 1.0], 0.8, true)],+ false => [stroke([0.0, 0.0, 0.0], 0.3, false), stroke([1.0, 1.0, 1.0], 0.45, true)],+ };+ xs.iter().for_each(|v| {+ let x = ((v - origin.0) * scale).round() + 0.5;+ lines(*v).iter().for_each(|paint| {+ canvas.draw_line((x, 0.0), (x, size.1), paint);+ });+ });+ ys.iter().for_each(|v| {+ let y = ((v - origin.1) * scale).round() + 0.5;+ lines(*v).iter().for_each(|paint| {+ canvas.draw_line((0.0, y), (size.0, y), paint);+ });+ });+ let tag = |text: String, x: f32, y: f32| {+ let (w, h) = (text_width(&text, px) + 2.0 * px + 1.0, 9.0 * px);+ canvas.draw_rect(Rect::from_xywh(x, y, w, h), &color([0.05, 0.06, 0.08], 0.82));+ draw_text(canvas, &text, x + px, y + px, px, [1.0, 1.0, 1.0]);+ };+ xs.iter().filter(|v| named(**v)).for_each(|v| {+ tag(format!("{v:.0}"), ((v - origin.0) * scale).round() + 1.0, 0.0);+ });+ ys.iter().filter(|v| named(**v) && **v > origin.1).for_each(|v| {+ tag(format!("{v:.0}"), 0.0, ((v - origin.1) * scale).round() + 1.0);+ });+}+fn draw_grid(canvas: &Canvas, origin: (f32, f32), scale: f32, size: (f32, f32), px: f32) {let step = grid_step(scale);let mut line = color([1.0, 1.0, 1.0], 0.35);@@ -344,7 +403,9 @@ pub fn apply(image: &skia_safe::Image, overlay: &Overlay, view: &View) -> Resultlet origin = view.region.map_or((0.0, 0.0), |[x, y, _, _]| (x as f32, y as f32));let s = view.scale;let px = if w.max(h) >= 1400 { 2.0 } else { 1.0 };- if overlay.grid {+ if overlay.grid && overlay.cells {+ draw_cells(canvas, origin, s, (w as f32, h as f32), px);+ } else if overlay.grid {draw_grid(canvas, origin, s, (w as f32, h as f32), px);}let to_out = |r: [f32; 4]| [(r[0] - origin.0) * s, (r[1] - origin.1) * s, r[2] * s, r[3] * s];@@ -813,4 +874,35 @@ mod tests {assert_eq!(pair.width, 816);assert!(text_width("ab", 1.0) > 0.0);}++ #[test]+ fn a_pixel_grid_lines_every_pixel_once_enlarged_and_names_them_where_the_numbers_fit() {+ assert_eq!(cell_steps(21.0), (1.0, 2.0));+ assert_eq!(cell_steps(32.0), (1.0, 1.0));+ assert_eq!(cell_steps(8.0), (1.0, 4.0));+ assert_eq!(+ cell_steps(2.0),+ (4.0, 16.0),+ "too small to tell pixels apart: fewer lines"+ );+ let d = doc();+ let view = View::scaled(8.0);+ let plain = compose_view(&d, 0, &Rasters::new(), view, None, None).unwrap();+ let cells = Overlay {+ grid: true,+ cells: true,+ ..Overlay::default()+ };+ let marked = compose_view(&d, 0, &Rasters::new(), view, Some(&cells), None).unwrap();+ assert_ne!(+ marked.pixel(8 * 30, 8 * 20 + 3),+ plain.pixel(8 * 30, 8 * 20 + 3),+ "a line between pixels 29 and 30"+ );+ assert_eq!(+ marked.pixel(8 * 30 + 4, 8 * 20 + 4),+ plain.pixel(8 * 30 + 4, 8 * 20 + 4),+ "the pixel itself is untouched"+ );+ }}diff --git a/docs/DESIGN.md b/docs/DESIGN.mdindex b93a628..c1c7a6d 100644--- a/docs/DESIGN.md+++ b/docs/DESIGN.md@@ -1,4 +1,4 @@-_Last updated: 2026-11-11 13:40_+_Last updated: 2026-11-11 15:40_# klad: design@@ -232,7 +232,7 @@ Unknown keys are errors that list the valid ones, so a typo never passes silentlEvery layer has `blend`, `opacity`, `visible`, `locked`, optional `mask`, `clip` and (M5, format 8) `effects`. Effects are layer settings, not a layer kind: the planned `filter` kind became them.-- **Pixel layers (M9).** A pixel layer is a paint layer flagged `pixel`, so it shares cels, masks, clipping, lock alpha, effects, the timeline and every export with paint layers. One pixel is one canvas pixel: a 64x64 sprite is a 64x64 drawing shown enlarged, and a drawing never mixes pixel sizes. Its marks stay data, as strokes do: a pixel mark is a fill record whose source is cells (`FillSource::Cells`), a set of whole pixels (coverage 0 or 255) with the id of the palette swatch it was drawn with, or a set of pixels to erase. So the same addresses, `set`, `rm`, `transform`, lasso, copy and history work on them; scaling, flipping and turning sample the nearest pixel (`markedit::resampled` with `hard`), which also makes an export above full size hard-edged. Colours are palette entries: `Document::bind_swatch` finds or adds the swatch and gives it an `id` the first time a mark uses it, and `set color=` on a pixel mark binds it to the new entry. The `pixel` op (`klad pixel`) is the first way to make marks; brush strokes and flood or lasso fills are refused on a pixel layer (`ops::off_the_grid`). Palette-wide recolouring, the pencil, shapes, shading, sharp exports and Aseprite files follow in the milestone's later stories.+- **Pixel layers (M9).** A pixel layer is a paint layer flagged `pixel`, so it shares cels, masks, clipping, lock alpha, effects, the timeline and every export with paint layers. One pixel is one canvas pixel: a 64x64 sprite is a 64x64 drawing shown enlarged, and a drawing never mixes pixel sizes. Its marks stay data, as strokes do: a pixel mark is a fill record whose source is cells (`FillSource::Cells`), a set of whole pixels (coverage 0 or 255) with the id of the palette swatch it was drawn with, or a set of pixels to erase. So the same addresses, `set`, `rm`, `transform`, lasso, copy and history work on them; scaling, flipping and turning sample the nearest pixel (`markedit::resampled` with `hard`), which also makes an export above full size hard-edged. Colours are palette entries: `Document::bind_swatch` finds or adds the swatch and gives it an `id` the first time a mark uses it, and `set color=` on a pixel mark binds it to the new entry. The `pixel` op (`klad pixel`) is the first way to make marks; brush strokes and flood or lasso fills are refused on a pixel layer (`ops::off_the_grid`). A drawing with a pixel layer (`Document::pixel_art`) gets a sharp view on both sides. In the editor the zoom moves in whole screen pixels per pixel above real size (`View::whole`, `View::fit_whole`; free below it), a pixel grid shows from 8 screen pixels per pixel (a dark line with light dashes, so it reads on any colour; View > Pixel grid), the pixel under the pointer is outlined on a pixel layer and named in the status line, and the Real size pane (`Pane::Preview`, opened the first time a pixel drawing is opened) shows the composed frame at 1, 2 or 4 screen pixels per pixel for drawings up to 512 px. In the CLI, `klad render` and edit previews enlarge by a whole number to about 512 px (`agent::pixel_scale`), and `--overlay grid` draws the same lines with the pixel numbers along the top and left (`overlay::draw_cells`). Palette-wide recolouring, the pencil, shapes, shading, sharp exports and Aseprite files follow in the milestone's later stories.- **Blend modes.** `normal`, `multiply`, `screen`, `overlay`, `add`, and since M5 `color-dodge`, `soft-light`, `hard-light`, `lighten`, `darken`, `color`, `luminosity`, all as in the W3C compositing spec (Skia's modes; `look::blend_rgb` and `look::composite` hold the formulas the tests check them against).- **Effects (M5).** `"effects": [{"glow": {...}}, {"outline": {...}}]`, applied in order to the layer's content (after its mask; for a clip base, to the base and its clipped layers together) before its opacity and blend: `blur` (radius, a Gaussian sigma), `glow` (radius, strength, threshold: 0 glows from every pixel, higher only from the bright ones; color: a tint; blend: how the glow mixes with what is under the layer, screen by default, normal lays it like paint under the layer), `outline` (width, color, inside), `shadow` (x, y, radius, color, laid under the layer), `noise` (amount, size, seed, mono: a grain fixed to the canvas), `displace` (amount, size, seed, by: smooth waves, or a layer whose red pushes across and green down), `relief` (strength, light, highlight, shade, softness: lights the paint height of the layer's drawings, below). Each effect knows its reach (`look::reach`), so a tile is composed from its content within the tile plus that margin and tiles meet without seams (noise and haze read only their own pixel and add no margin, so they cost no neighbouring tiles); a tile skips a clip stack or group that puts no pixel in it (none of its rasters, live tiles or onion ghosts has a tile in the tile grown by its effects' margin; layers moved by keys, adjustment layers and vector layers drawn from their nodes always count), which leaves the tile the same since every blend leaves the pixels under a transparent layer as they are; the pixels are computed in Rust (`klad-render/effects.rs`) on f32 with absolute coordinates, so a tile equals the same pixels of the whole image byte for byte (tested). Blurs use a direct kernel, below a sigma of 2 at full size and above it on a grid of 2, 4, ... px blocks anchored to the canvas, then sampled back.- **Adjustment layers (M5).** An `adjust` layer changes what is under it in its list: the layers below it in its group, or, clipped, its base. A group holding an adjustment is composed apart, so the adjustment stays inside it. The colour math is on unpremultiplied sRGB values with alpha kept: `hsl` (hue in degrees, saturation and lightness -1..1), `levels` (black, white, gamma, low, high), `curves` (points, and red, green, blue applied before them; monotone cubic, no overshoot), `balance` (shadows, midtones, highlights: cyan to red, magenta to green, yellow to blue, keepLight), `gradient-map` (stops by brightness). The layer's opacity, blend and mask decide how much of the adjusted colour replaces the colour under it. `fill` (a solid or gradient paint) is drawn like a content layer instead, with the layer's blend.diff --git a/docs/cli.md b/docs/cli.mdindex 6bb821d..8f67264 100644--- a/docs/cli.md+++ b/docs/cli.md@@ -1421,7 +1421,7 @@ Options:[default: 0]--scale <SCALE>- Scale (default 1, or longest side 1024 px with --focus)+ Scale (default 1, or longest side 1024 px with --focus; a pixel drawing is enlarged by a whole number to about 512 px)--region <REGION>Only this canvas region: x,y,w,hdiff --git a/docs/skill/SKILL.md b/docs/skill/SKILL.mdindex c36da04..7c761e7 100644--- a/docs/skill/SKILL.md+++ b/docs/skill/SKILL.md@@ -107,7 +107,8 @@ klad add art.klad layer pixel name=sprite a pixel layer in any draklad pixel sprite.klad l1 --color '#2b2d42' --cells '3-12,2 3,3-8 12,3-8 3-12,9'klad pixel sprite.klad l1 --color skin --cells '4-11,3-8'klad pixel sprite.klad l1 --erase --cells '7,5 8,5'-klad export sprite.klad --scale 8 -o [email protected] square pixels, to look at+klad render sprite.klad --overlay grid enlarged, with numbered pixel lines+klad export sprite.klad --scale 8 -o [email protected] square pixels, to keep```- A pixel layer is a grid with no soft edges, and one pixel is one canvas pixel: a 32x32 sprite is a 32x32 drawing. Size the drawing in pixels of the art, not of the screen; `klad ls` shows the layer as `pixel`.@@ -115,7 +116,7 @@ klad export sprite.klad --scale 8 -o [email protected] square pixels, to look a- `--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.- Each call makes one mark, `<cel>:s<id>`, that stays editable: `klad set sprite.klad c2:s1 color=shadow` recolours it (and binds it to that entry), `klad transform ... --move 2,0` moves it by whole pixels, `--flip h` and `--rotate 90` keep it hard, `klad rm` removes it. `klad strokes sprite.klad l1` lists the marks with their entry and cell count; `--json` gives each one's `cells`.- Later marks cover earlier ones; `--erase` makes a mark that clears what was drawn before it at those pixels (remove that mark and the pixels come back).-- Look at a sprite enlarged: `klad export --scale 8` (whole numbers) keeps every pixel a square. At real size a 32 px picture is too small to judge.+- Looking: `klad render` and the `--render` preview of an edit enlarge a pixel drawing by a whole number to about 512 px, so every pixel is a square you can see (`--scale 1` gives the real size, which is how the player sees it: check there too). `--overlay grid` draws a line between pixels and numbers them along the top and the left, so a pixel's `x,y` can be read off the picture: the number is on the line where that column or row starts. `klad export --scale 8` (whole numbers) writes the enlarged PNG to keep.- In `apply`: `{"op":"pixel","layer":"l1","color":"skin","cells":[[4,5],[5,5]]}` or `"erase":true`. Brush strokes (`klad stroke`, `ink`, `paint`, ...) and `klad fill` are refused on a pixel layer.## Masks, clipping and lock alpha