A drawing app built for agent/human collaboration
Rust
Exports above full size draw the strokes again at that size
Indicode BV0ab4424400ec
diff --git a/crates/brush/src/brush.rs b/crates/brush/src/brush.rsindex b89316d..3db64a9 100644--- a/crates/brush/src/brush.rs+++ b/crates/brush/src/brush.rs@@ -52,6 +52,7 @@ pub struct Brush {pub grain: Option<Texture>,pub dual: Option<Dual>,pub blend: StrokeBlend,+ pub scale: f32,}#[derive(Clone, Debug)]@@ -223,6 +224,7 @@ impl Brush {BrushBlend::Normal => StrokeBlend::Normal,BrushBlend::Erase => StrokeBlend::Erase,},+ scale: 1.0,})}@@ -258,6 +260,7 @@ impl Entry {pub struct BrushSet {entries: BTreeMap<String, Entry>,pictures: Arc<Pictures>,+ scale: f32,}impl BrushSet {@@ -268,6 +271,26 @@ impl BrushSet {.filter_map(|id| brushes::library(id).map(|def| (id.to_string(), Entry::new(def)))).collect(),pictures: Arc::new(Pictures::new()),+ scale: 1.0,+ }+ }++ pub fn at_scale(&self, scale: f32) -> Self {+ let entries = self+ .entries+ .iter()+ .map(|(id, e)| {+ let mut def = e.def.clone();+ if let Some(grain) = def.grain.as_mut() {+ grain.scale *= scale;+ }+ (id.clone(), Entry::new(def))+ })+ .collect();+ Self {+ entries,+ pictures: self.pictures.clone(),+ scale: self.scale * scale,}}@@ -331,7 +354,14 @@ impl BrushSet {})?;entry.built- .get_or_init(|| Brush::with_pictures(&entry.def, &self.pictures).map_err(|e| format!("brush {id}: {e:#}")))+ .get_or_init(|| {+ Brush::with_pictures(&entry.def, &self.pictures)+ .map(|brush| Brush {+ scale: self.scale,+ ..brush+ })+ .map_err(|e| format!("brush {id}: {e:#}"))+ }).as_ref().map_err(|e| anyhow!("{e}"))}diff --git a/crates/brush/src/engine.rs b/crates/brush/src/engine.rsindex 33f0d13..c455af0 100644--- a/crates/brush/src/engine.rs+++ b/crates/brush/src/engine.rs@@ -133,7 +133,8 @@ impl StrokePainter {reservoir: None,reservoir_height: None,previous: None,- bristles: (brush.def.body > 0.0).then(|| Box::new(Bristles::new(stroke.seed ^ 0x5bd1_e995, stroke.size))),+ bristles: (brush.def.body > 0.0)+ .then(|| Box::new(Bristles::new(stroke.seed ^ 0x5bd1_e995, stroke.size, brush.scale))),}}@@ -175,7 +176,7 @@ impl StrokePainter {return;}if sample.dt_ms > 0 {- let now = length / sample.dt_ms as f32;+ let now = length / sample.dt_ms as f32 / self.brush.scale;self.speed += (now - self.speed) * SPEED_EASE;}self.heading = libm::atan2f(next.y - prev.y, next.x - prev.x);@@ -456,8 +457,8 @@ struct Bristles {}impl Bristles {- fn new(seed: u32, size: f32) -> Self {- let count = (size / 3.5).clamp(3.0, 48.0);+ fn new(seed: u32, size: f32, scale: f32) -> Self {+ let count = (size / scale / 3.5).clamp(3.0, 48.0);let wave = |x: f32, row: i32| {let i = libm::floorf(x);let f = x - i;diff --git a/crates/cli/src/export.rs b/crates/cli/src/export.rsindex c4530f0..edfe14a 100644--- a/crates/cli/src/export.rs+++ b/crates/cli/src/export.rs@@ -2,7 +2,7 @@ use crate::layers;use anyhow::{Result, bail};use klad_brush::BrushSet;use klad_core::bundle::{Bundle, write_atomic};-use klad_render::export::{Options, Target, png8, png16, render};+use klad_render::export::{Options, Target, detail_for, png8, png16, render};use std::path::{Path, PathBuf};use std::time::Instant;@@ -52,7 +52,8 @@ pub fn run(path: &Path, opts: Export) -> Result<()> {);}let layer = opts.layer.as_deref().map(|key| doc.find_layer(key)).transpose()?;- let rasters = layers::load(&bundle, opts.frame, &BrushSet::for_bundle(&bundle)?, true)?.rasters;+ let detail = detail_for(opts.scale);+ let rasters = layers::load_at(&bundle, opts.frame, &BrushSet::for_bundle(&bundle)?, detail)?;let target = match layer {Some(l) => Target::Layer(l),None => Target::Frame,@@ -61,6 +62,7 @@ pub fn run(path: &Path, opts: Export) -> Result<()> {scale: opts.scale,background: opts.background,references: opts.references,+ detail,};let image = render(doc, opts.frame, &rasters, &target, options)?;let rendered = start.elapsed().as_secs_f64() * 1000.0;@@ -129,4 +131,44 @@ mod tests {);std::fs::remove_dir_all(&dir).unwrap();}++ #[test]+ fn an_export_above_full_size_draws_the_strokes_again_at_that_size() {+ let dir = std::env::temp_dir().join(format!("draw-export-sharp-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ let mut doc = Document::new(120, 60);+ doc.layers.push(Layer::paint("l1", "ink", "c1"));+ let mut bundle = Bundle::create(dir.join("art.draw/"), doc).unwrap();+ bundle+ .apply(+ &klad_core::ops::parse_lines(+ r##"{"op":"stroke","layer":"l1","brush":"ink","size":6,"color":"#101010","path":"M10 20 L110 26","taper":[0,0]}"##,+ )+ .unwrap(),+ )+ .unwrap();+ let brushes = BrushSet::for_bundle(&bundle).unwrap();+ let edge = |detail: f32| {+ let rasters = layers::load_at(&bundle, 0, &brushes, detail).unwrap();+ let options = Options {+ scale: 4.0,+ background: false,+ references: false,+ detail,+ };+ let image = render(&bundle.doc, 0, &rasters, &Target::Frame, options).unwrap();+ let frame = klad_render::read_rgba8(&image).unwrap();+ (40..140)+ .filter(|&y| (12..243).contains(&frame.pixel(240, y)[3]))+ .count()+ };+ let (stretched, drawn) = (edge(1.0), edge(4.0));+ assert!(+ drawn <= 4 && stretched >= drawn + 3,+ "soft pixels across the line: stretched {stretched}, drawn {drawn}"+ );+ assert_eq!(detail_for(4.0), 4.0);+ assert_eq!(detail_for(0.5), 1.0);+ std::fs::remove_dir_all(&dir).unwrap();+ }}diff --git a/crates/cli/src/layers.rs b/crates/cli/src/layers.rsindex 5493d26..7658648 100644--- a/crates/cli/src/layers.rs+++ b/crates/cli/src/layers.rs@@ -5,7 +5,7 @@ use klad_core::bundle::Bundle;use klad_core::doc::{Document, Kind, Node};use klad_core::rng::{FNV_OFFSET, fnv};use klad_core::stroke::decode_cel;-use klad_render::{Rasters, rasterize_nodes};+use klad_render::{Rasters, rasterize_nodes, rasterize_nodes_at};use rayon::prelude::*;use std::collections::BTreeMap;use std::fs;@@ -78,18 +78,62 @@ pub fn load_one(bundle: &Bundle, brushes: &BrushSet, layer: &str, cel: &str) ->}pub fn load_cels(bundle: &Bundle, brushes: &BrushSet, cels: &[(String, String, Kind)]) -> Result<Rasters> {+ load_cels_at(bundle, brushes, cels, 1.0)+}++pub fn load_cels_at(+ bundle: &Bundle,+ brushes: &BrushSet,+ cels: &[(String, String, Kind)],+ detail: f32,+) -> Result<Rasters> {let (w, h) = (bundle.doc.canvas.width, bundle.doc.canvas.height);+ let scaled = (detail != 1.0).then(|| brushes.at_scale(detail));cels.par_iter().map(|(layer, cel, kind)| {- let raster = match kind {- Kind::Vector => rasterize_nodes(&nodes_of(&bundle.doc, cel), w, h)?,- _ => load_cel(bundle, brushes, layer, cel, true)?.raster,+ let raster = match (kind, &scaled) {+ (Kind::Vector, None) => rasterize_nodes(&nodes_of(&bundle.doc, cel), w, h)?,+ (Kind::Vector, Some(_)) => rasterize_nodes_at(&nodes_of(&bundle.doc, cel), w, h, detail)?,+ (_, None) => load_cel(bundle, brushes, layer, cel, true)?.raster,+ (_, Some(scaled)) => replay_at(bundle, scaled, layer, cel, detail)?,};Ok((cel.clone(), raster))}).collect()}+pub fn load_at(bundle: &Bundle, frame: u32, brushes: &BrushSet, detail: f32) -> Result<Rasters> {+ if detail == 1.0 {+ return Ok(load(bundle, frame, brushes, true)?.rasters);+ }+ let cels: Vec<(String, String, Kind)> = bundle+ .doc+ .paint_content_at(frame)+ .iter()+ .map(|(layer, cel)| (layer.id.clone(), cel.id.clone(), Kind::Paint))+ .collect();+ load_cels_at(bundle, brushes, &cels, detail)+}++fn replay_at(bundle: &Bundle, brushes: &BrushSet, layer: &str, cel: &str, detail: f32) -> Result<Raster> {+ let path = bundle.strokes_path(layer, cel);+ let bytes = if path.exists() { fs::read(&path)? } else { Vec::new() };+ let mut marks = match bytes.is_empty() {+ true => Vec::new(),+ false => decode_cel(&bytes).with_context(|| format!("cel {cel}"))?,+ };+ marks+ .iter_mut()+ .for_each(|m| klad_core::markedit::transform_mark(m, [detail, 0.0, 0.0, detail, 0.0, 0.0]));+ let (w, h) = (+ (bundle.doc.canvas.width as f32 * detail).ceil() as u32,+ (bundle.doc.canvas.height as f32 * detail).ceil() as u32,+ );+ Ok(klad_brush::replay(w, h, &marks, brushes)+ .with_context(|| format!("cel {cel} at {detail}x"))?+ .raster)+}+fn nodes_of(doc: &Document, cel: &str) -> Vec<Node> {match doc.item(cel) {Some(klad_core::doc::Item::Cel(_, c)) => c.nodes.clone(),diff --git a/crates/cli/src/sprites.rs b/crates/cli/src/sprites.rsindex 711a565..c40a5c3 100644--- a/crates/cli/src/sprites.rs+++ b/crates/cli/src/sprites.rs@@ -1,11 +1,11 @@use crate::export::scale_tag;-use crate::layers::load_cels;+use crate::layers::load_cels_at;use crate::sheet::{batches, frame_cels, shown};use anyhow::{Context, Result, anyhow, bail};use klad_brush::BrushSet;use klad_core::bundle::{Bundle, write_atomic};use klad_core::ops::Op;-use klad_render::export::{Options, Target, render};+use klad_render::export::{Options, Target, detail_for, render};use klad_render::sprites::{self, Animation, Pixels, Placed, Rect, Run, Scene, Sheet, SpriteFrames, Texture};use rayon::prelude::*;use std::collections::{BTreeMap, BTreeSet};@@ -86,6 +86,7 @@ pub fn pictures(bundle: &Bundle, animations: Vec<Animation>, look: &Look) -> Resscale: look.scale,background: look.background,references: false,+ detail: detail_for(look.scale),};let frames: BTreeSet<u32> = animations.iter().flat_map(|a| a.from..=a.to).collect();let mut firsts: BTreeMap<Vec<String>, u32> = BTreeMap::new();@@ -107,7 +108,7 @@ pub fn pictures(bundle: &Bundle, animations: Vec<Animation>, look: &Look) -> Res.collect::<BTreeSet<_>>().into_iter().collect();- let rasters = load_cels(bundle, &brushes, &needed)?;+ let rasters = load_cels_at(bundle, &brushes, &needed, options.detail)?;let done = batch.par_iter().map(|(frame, _)| {diff --git a/crates/render/src/export.rs b/crates/render/src/export.rsindex d6e4b03..3993592 100644--- a/crates/render/src/export.rs+++ b/crates/render/src/export.rs@@ -26,6 +26,14 @@ pub struct Options {pub scale: f32,pub background: bool,pub references: bool,+ pub detail: f32,+}++pub fn detail_for(scale: f32) -> f32 {+ match scale > 1.0 {+ true => scale,+ false => 1.0,+ }}pub fn render(doc: &Document, frame: u32, rasters: &Rasters, target: &Target, options: Options) -> Result<Image> {@@ -57,6 +65,7 @@ pub fn render(doc: &Document, frame: u32, rasters: &Rasters, target: &Target, opsampling,doc: Some(doc),references: options.references,+ detail: options.detail,..Ctx::full(frame, rasters)};match target {@@ -199,6 +208,7 @@ mod tests {scale: 1.0,background: false,references: false,+ detail: 1.0,};let image = render(&doc, 0, &Rasters::new(), &Target::Frame, options).unwrap();let dithered = dither8(&image).unwrap();@@ -240,6 +250,7 @@ mod tests {scale: 1.0,background: false,references: false,+ detail: 1.0,};let image = render(&doc, 0, &Rasters::new(), &Target::Frame, options).unwrap();let rgba = dither8(&image).unwrap();@@ -287,6 +298,7 @@ mod tests {scale: 2.0,background: false,references: false,+ detail: 1.0,},).unwrap();@@ -308,6 +320,7 @@ mod tests {scale: 20.0,background: false,references: false,+ detail: 1.0,}).is_err()diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rsindex ffaa01e..0c23d42 100644--- a/crates/render/src/lib.rs+++ b/crates/render/src/lib.rs@@ -156,6 +156,21 @@ pub fn raster_image(raster: &Raster) -> Result<Image> {}fn draw_raster(canvas: &Canvas, raster: &Raster, ctx: Ctx) -> Result<()> {+ if ctx.detail != 1.0 {+ canvas.save();+ canvas.scale((1.0 / ctx.detail, 1.0 / ctx.detail));+ let drawn = draw_raster(+ canvas,+ raster,+ Ctx {+ detail: 1.0,+ sampling: None,+ ..ctx+ },+ );+ canvas.restore();+ return drawn;+ }match (ctx.area, ctx.sampling) {(Some(area), _) => tiles_in(raster.cols, raster.rows, area).into_iter()@@ -200,6 +215,7 @@ pub struct Ctx<'a> {pub flat: bool,pub doc: Option<&'a Document>,pub references: bool,+ pub detail: f32,}impl<'a> Ctx<'a> {@@ -214,6 +230,7 @@ impl<'a> Ctx<'a> {flat: true,doc: None,references: false,+ detail: 1.0,}}@@ -499,8 +516,8 @@ fn height_img(window: IRect, space: Space, layer: &Layer, ctx: Ctx) -> Option<Imreturn None;}let (w, h) = (window.width().max(0) as usize, window.height().max(0) as usize);- let taps = ((1.0 / space.scale).ceil() as usize).clamp(1, 4);- let step = 1.0 / (space.scale * taps as f32);+ let taps = ((ctx.detail / space.scale).ceil() as usize).clamp(1, 4);+ let step = ctx.detail / (space.scale * taps as f32);let px = (0..h).into_par_iter().flat_map_iter(|row| {@@ -508,8 +525,8 @@ fn height_img(window: IRect, space: Space, layer: &Layer, ctx: Ctx) -> Option<Im(0..w).map(move |col| {let (gx, gy) = (window.left + col as i32, window.top + row as i32);let (cx, cy) = (- (gx as f32 - space.tx) / space.scale,- (gy as f32 - space.ty) / space.scale,+ (gx as f32 - space.tx) / space.scale * ctx.detail,+ (gy as f32 - space.ty) / space.scale * ctx.detail,);let sum: f32 = (0..taps * taps).map(|k| {@@ -714,8 +731,17 @@ pub fn rasterize_region(nodes: &[klad_core::doc::Node], rect: [f32; 4], max_side}pub fn rasterize_nodes(nodes: &[klad_core::doc::Node], width: u32, height: u32) -> Result<Raster> {+ rasterize_nodes_at(nodes, width, height, 1.0)+}++pub fn rasterize_nodes_at(nodes: &[klad_core::doc::Node], width: u32, height: u32, detail: f32) -> Result<Raster> {+ let (width, height) = (+ (width as f32 * detail).ceil() as u32,+ (height as f32 * detail).ceil() as u32,+ );let info = f16_info(width, height);let mut surface = surfaces::raster(&info, None, None).ok_or_else(|| anyhow!("cannot allocate {width}x{height}"))?;+ surface.canvas().scale((detail, detail));vector::draw_nodes(surface.canvas(), nodes)?;let (w, h) = (width as usize, height as usize);let mut pixels = vec![half::f16::ZERO; w * h * 4];@@ -995,6 +1021,7 @@ pub fn compose_tile(items: &[TileItem], job: &TileJob) -> Result<Vec<half::f16>>flat: true,doc: Some(job.doc),references: job.references,+ detail: 1.0,};units(items).into_iter().try_for_each(|unit| match unit {Unit::Pixels { tile, opacity, blend } => {diff --git a/docs/DESIGN.md b/docs/DESIGN.mdindex 7f4d142..055fc35 100644--- a/docs/DESIGN.md+++ b/docs/DESIGN.md@@ -339,7 +339,7 @@ A brush is JSON. The library is built in (`crates/core/brushes/library/`: `ink`- Frame keys read a stroke file only when its size, time or inode changed (writes are atomic renames, so a rewrite always gets a new inode); an edit no longer clears them.- **Onion skin** (M3) is computed in `klad-render` (`onion`), one piece of code for the CLI, the editor's canvas and its frame cache. For a layer at a frame it lists the drawings before and after the current one: counted in drawings (the exposures before and after, each drawing once at its nearest distance, the current drawing and links to it skipped) or in frames (the drawings shown 1, 2, ... frames away). Opacity is `opacity x falloff^(distance - 1)` (defaults 0.5 and 0.6, 2 before and 2 after); those before are tinted red and those after green (`rgb x 0.25 + tint x alpha x 0.75`) unless the tint is off. In a looping range the count wraps around inside the range, so the last drawing of a cycle shows the first. The ghosts of a layer are composed (furthest first, f32 per pixel, on tiles in parallel, deterministic) into one raster, which the compositor draws right under that layer, outside its opacity, blend and mask; the ghosts of a clip group's layers go under the whole group. Hidden layers show none.- **Sheets** (M3): `klad render --sheet` lays frames out in a grid (columns about square, `--columns`), each cell the frame at `--cell` px on its longest side with its frame number, a `hold` mark when it looks exactly like the frame before, and per layer (top first, listed in the heading) the cel it shows: `c5` starts a drawing, `|c5` holds it, `c9>c1` a link, `.` blank. `--drawings` merges frames that look the same into one cell titled with their range. A clip's sheet is headed with the clip's name and its fps. Frames that look the same are composed once; drawings load in batches under 768 MB, so long sheets of big canvases stay in memory.-- Export (`klad export`) renders the image, or one layer or group alone, at a frame, at a scale from 1/16 to 8, on transparency unless `--background`. Vector nodes are drawn at the export scale; paint rasters are resampled as whole images (Mitchell cubic up, mipmapped down). 8-bit PNGs are ordered-dithered (8x8 Bayer) from the f16 pixels, colour and alpha, so gradients do not band; values within an eighth of a level of an 8-bit value are written as that value, so flat colours stay flat. `--depth 16` writes 16-bit PNG. Working renders (`klad render`, `klad hash`) stay undithered so their hashes hold.+- Export (`klad export`) renders the image, or one layer or group alone, at a frame, at a scale from 1/16 to 8, on transparency unless `--background`. Vector nodes are drawn at the export scale. Above full size the paint is drawn again at the export size: each drawing's marks are scaled (`markedit::transform_mark`: samples, sizes, tapers and cuts; fill coverage resampled bilinearly) and replayed with the brushes at that scale (`BrushSet::at_scale`: grain scaled with it, speed and bristle spacing measured in canvas px), the rasters drawn one to one (`Ctx::detail`), so lines stay crisp and textures keep their size; sprite sheets and frames do the same with their vector cels rasterized at that size. That replays without the cache (the lemons at 2x: 5.5 s instead of 0.7 s). Below full size the cached rasters are mipmapped down. 8-bit PNGs are ordered-dithered (8x8 Bayer) from the f16 pixels, colour and alpha, so gradients do not band; values within an eighth of a level of an 8-bit value are written as that value, so flat colours stay flat. `--depth 16` writes 16-bit PNG. Working renders (`klad render`, `klad hash`) stay undithered so their hashes hold.## The agent interface: `klad` CLIdiff --git a/docs/skill/SKILL.md b/docs/skill/SKILL.mdindex 42208fc..0a5aa0e 100644--- a/docs/skill/SKILL.md+++ b/docs/skill/SKILL.md@@ -230,9 +230,9 @@ klad export art.draw --scale 2klad export art.draw --layer hero --scale 4 --depth 16 -o hero.png```-Transparent PNG of the image or one layer or group, next to the bundle unless `-o`. 8-bit exports are dithered so gradients do not band; `--depth 16` keeps 16 bits; `--background` keeps the canvas colour. Vectors stay sharp at any scale; paint layers are resampled. Sprite sheets, numbered frames and Godot exports are under Time, Animation exports.+Transparent PNG of the image or one layer or group, next to the bundle unless `-o`. 8-bit exports are dithered so gradients do not band; `--depth 16` keeps 16 bits; `--background` keeps the canvas colour. Vectors stay sharp at any scale, and above full size `klad export` draws the strokes again at that size, so lines stay crisp and textures keep their size (it replays every mark, so it takes a few seconds on a dense painting). Sprite sheets, numbered frames and Godot exports are under Time, Animation exports.-Size the canvas for the largest size the art is ever seen at, not for the size it is used at. Paint layers are pixels at the canvas size: `--scale` above 1, a zoomed render, the editor's zoom, a sprite scaled up or a game camera that zooms in all magnify them, and every pixel shows as a block. Work out the largest size on screen (the camera's closest zoom times the sprite's scale, times 2 on a high density display), make the canvas about twice that, and show it scaled down (in Godot with mipmaps on). At that size give inked lines 4 to 8 px and noise or grain effects a `size` of 2 or more: lines of 2 to 3 px and 1 px noise read as pixels the moment anything enlarges them. Check at the size the player sees and at the closest zoom, not only at 1:1 on the canvas.+Size the canvas for the largest size the art is ever seen at, not for the size it is used at. Paint layers are pixels at the canvas size: `klad render --scale` above 1, the editor's zoom, a sprite scaled up or a game camera that zooms in all magnify them, and every pixel shows as a block (only `klad export --scale` draws them again). Work out the largest size on screen (the camera's closest zoom times the sprite's scale, times 2 on a high density display), make the canvas about twice that, and show it scaled down (in Godot with mipmaps on). At that size give inked lines 4 to 8 px and noise or grain effects a `size` of 2 or more: lines of 2 to 3 px and 1 px noise read as pixels the moment anything enlarges them. Check at the size the player sees and at the closest zoom, not only at 1:1 on the canvas.## Scripts