Skip to content

armgit / klad

Public Imported from GitHub
0

A drawing app built for agent/human collaboration

Rust

Drags preview their area of effect in the background

Indicode BVfcf73839a834
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 12bf2ce..8d05588 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -28,6 +28,9 @@ The first builds, and klad's licences.
- `klad paintover` (and "paint over" in the layers panel): brushwork from any picture, strokes that follow its forms and stop at its colour edges, big to small, detail where the picture has it; `--like` and `--frames` carry it through an animation without boiling.
- `klad compare` (and "compare with the reference" in the editor): a drawing against a reference picture in numbers and words, with a heat map.
- Large stills render several times faster: strokes land only where they painted, and the CLI replays a drawing's tiles on every core (same pixels).
+- Dragging in a large drawing: shapes and strokes move under the pointer from the first move, wherever they are (in groups with effects, clipped, masked, under any blend), drawn in the background tile by tile; the layers above and the rest of the dragged layer stay in place (dragging a shape on the topmost layer no longer hid the shapes above it), and letting go redraws only the tiles the move touched.
+- Edits on vector layers redraw only the tiles their shapes covered before and after, not the whole layer.
+- Noise and haze no longer make every edit redraw the tiles around it.
## 0.1.0 (2026-11-04)
diff --git a/crates/app/src/composite.rs b/crates/app/src/composite.rs
index 8ee8b48..ddb6913 100644
--- a/crates/app/src/composite.rs
+++ b/crates/app/src/composite.rs
@@ -28,40 +28,7 @@ const CACHE_BYTES: usize = 1 << 30;
pub type Tiles = Vec<(usize, Vec<f16>)>;
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub enum Mix {
- Over,
- Multiply,
- Screen,
- Add,
-}
-
-impl Mix {
- fn of(blend: Blend) -> Option<Self> {
- match blend {
- Blend::Normal => Some(Mix::Over),
- Blend::Multiply => Some(Mix::Multiply),
- Blend::Screen => Some(Mix::Screen),
- Blend::Add => Some(Mix::Add),
- _ => None,
- }
- }
-}
-
-pub struct Planes {
- pub base: Tiles,
- pub runs: Vec<(Mix, Tiles)>,
- pub opacity: f32,
-}
-
-fn pure(doc: &Document, layer: &Layer) -> bool {
- layer.blend == Blend::Normal
- && doc.effects_of(layer).is_empty()
- && !layer.reads_under()
- && layer.children().iter().all(|c| pure(doc, c))
-}
-
-fn effect_reach(doc: &Document, layers: &[Layer]) -> i32 {
+pub(crate) fn effect_reach(doc: &Document, layers: &[Layer]) -> i32 {
layers
.iter()
.filter(|l| l.visible)
@@ -70,7 +37,7 @@ fn effect_reach(doc: &Document, layers: &[Layer]) -> i32 {
.unwrap_or(0)
}
-fn dilate(tiles: &[usize], reach: i32, cols: usize, rows: usize) -> Vec<usize> {
+pub(crate) fn dilate(tiles: &[usize], reach: i32, cols: usize, rows: usize) -> Vec<usize> {
let n = (reach.max(0) as usize).div_ceil(TILE) as i64;
if n == 0 {
return tiles.to_vec();
@@ -732,7 +699,7 @@ impl CanvasRequest {
}
#[allow(clippy::too_many_arguments)]
-fn compose_items(
+pub(crate) fn compose_items(
doc: &Document,
frame: u32,
rasters: &Rasters,
@@ -1190,11 +1157,6 @@ impl Scene {
self.rasters.get(&self.active_cel()?)
}
- pub fn active_replay(&self) -> Option<(&CelReplay, &Raster)> {
- let cel = self.active_cel()?;
- Some((&self.cels.get(&cel)?.replay, self.rasters.get(&cel)?))
- }
-
fn seen_at(&self, path: &[usize], at: (f32, f32)) -> Option<f32> {
let doc = &self.bundle.doc;
let alpha_of = |layer: &Layer| -> Option<f32> {
@@ -1397,10 +1359,6 @@ impl Scene {
(!self.onions.is_empty()).then_some(&self.onions)
}
- fn onion_tile(&self, layer: &str, index: usize) -> Option<&[f16]> {
- self.onions.get(layer).and_then(|r| r.at(index))
- }
-
pub fn rebuild_caches(&mut self, tiles: Option<&[usize]>) -> Result<()> {
if self.slimmed() {
self.stale = true;
@@ -2333,20 +2291,6 @@ impl Scene {
Ok(extra.into_iter().collect())
}
- pub fn node_slot(&self, node: &str) -> Option<(Vec<usize>, String, usize, Vec<Node>)> {
- match self.bundle.doc.locate(node)? {
- Loc::Node(path, c, nodes) if nodes.len() == 1 => {
- let layer = self.bundle.doc.layer_at(&path);
- if layer.kind() != Kind::Vector || layer.locked {
- return None;
- }
- let cel = &layer.cels()[c];
- Some((path, cel.id.clone(), nodes[0], cel.nodes.clone()))
- }
- _ => None,
- }
- }
-
fn compose_with(
&self,
items: &[TileItem],
@@ -2368,116 +2312,26 @@ impl Scene {
compose_tile(items, &job)
}
- pub fn lift_planes(&self, layer: &[usize], lower: &Raster, upper: &Raster) -> Result<Option<Planes>> {
- if self.slimmed() {
- return Ok(None);
- }
- let doc = &self.bundle.doc;
- let Some((below, above, through)) = split(doc, &doc.layers, layer) else {
- return Ok(None);
- };
- let owner = doc.layer_at(layer);
- if !through || owner.blend != Blend::Normal || !doc.effects_of(owner).is_empty() {
- return Ok(None);
- }
- let units = above.into_iter().fold(Vec::<Vec<&Layer>>::new(), |mut out, l| {
- match out.last_mut() {
- Some(unit) if l.clip => unit.push(l),
- _ => out.push(vec![l]),
- }
- out
- });
- let mut runs: Vec<(Mix, Vec<Vec<&Layer>>)> = Vec::new();
- for unit in units.into_iter().filter(|u| u[0].visible) {
- let Some(mix) = Mix::of(unit[0].blend) else {
- return Ok(None);
- };
- if !unit
- .iter()
- .all(|l| doc.effects_of(l).is_empty() && !l.reads_under() && l.children().iter().all(|c| pure(doc, c)))
- {
- return Ok(None);
- }
- match runs.last_mut() {
- Some((last, group)) if *last == mix => group.push(unit),
- _ => runs.push((mix, vec![unit])),
- }
- }
- fn own<'a>(raster: &'a Raster, index: usize, owner: &Layer) -> Option<TileItem<'a>> {
- raster.at(index).filter(|_| owner.visible).map(|tile| TileItem::Pixels {
- tile,
- opacity: owner.opacity,
- blend: Blend::Normal,
- })
+ pub fn preview_snapshot(&self, cels: &[String], brushes: &BrushSet) -> Option<crate::preview::Snapshot> {
+ if self.slimmed() || self.stale || (self.tint_mask && self.active_is_mask()) {
+ return None;
}
- let background = doc.canvas.background.as_deref();
- let tiles = self.all_tiles();
- let base = tiles
- .par_iter()
- .map(|&i| {
- let ghost = self.onion_tile(&owner.id, i).map(|tile| TileItem::Pixels {
- tile,
- opacity: 1.0,
- blend: Blend::Normal,
- });
- let items: Vec<TileItem> = below
- .iter()
- .filter(|l| l.visible)
- .map(|l| TileItem::Layer(l))
- .chain(ghost)
- .chain(own(lower, i, owner))
- .collect();
- Ok((i, self.compose_with(&items, i, background, true)?))
- })
- .collect::<Result<Vec<_>>>()?;
- let planes = runs
+ let replays = cels
.iter()
- .enumerate()
- .map(|(k, (mix, units))| {
- let tiles = tiles
- .par_iter()
- .map(|&i| {
- let tile = match mix {
- Mix::Multiply => {
- let mut factor = vec![f16::ONE; TILE_PX * 4];
- units.iter().try_for_each(|unit| {
- let items: Vec<TileItem> = unit.iter().map(|l| TileItem::Layer(l)).collect();
- let t = self.compose_with(&items, i, None, true)?;
- factor
- .as_chunks_mut::<4>()
- .0
- .iter_mut()
- .zip(t.as_chunks::<4>().0)
- .for_each(|(f, s)| {
- let a = s[3].to_f32();
- (0..3).for_each(|c| {
- f[c] = f16::from_f32(f[c].to_f32() * (1.0 - a + s[c].to_f32()));
- });
- });
- Ok::<_, anyhow::Error>(())
- })?;
- factor
- }
- _ => {
- let first = (k == 0).then(|| own(upper, i, owner)).flatten();
- let items: Vec<TileItem> = first
- .into_iter()
- .chain(units.iter().flatten().map(|l| TileItem::Layer(l)))
- .collect();
- self.compose_with(&items, i, None, true)?
- }
- };
- Ok((i, tile))
- })
- .collect::<Result<Vec<_>>>()?;
- Ok((*mix, tiles))
- })
- .collect::<Result<Vec<_>>>()?;
- Ok(Some(Planes {
- base,
- runs: planes,
- opacity: if owner.visible { owner.opacity } else { 0.0 },
- }))
+ .map(|c| self.cels.get(c).map(|d| (c.clone(), d.replay.clone())))
+ .collect::<Option<BTreeMap<_, _>>>()?;
+ Some(crate::preview::Snapshot {
+ rev: self.bundle.doc.rev,
+ bundle: Bundle {
+ root: self.bundle.root.clone(),
+ doc: self.bundle.doc.clone(),
+ },
+ frame: self.frame,
+ rasters: self.rasters.clone(),
+ cels: replays,
+ onions: self.onion_map().cloned(),
+ brushes: brushes.clone(),
+ })
}
fn vector_cels_since(&self, old: &Document) -> Vec<(String, u64)> {
@@ -3419,73 +3273,29 @@ mod tests {
.split(',')
.filter(|n| !n.is_empty())
{
- let Some((layer, _, index, nodes)) = scene.node_slot(node) else {
+ let Some(Loc::Node(layer, c, at)) = scene.bundle.doc.locate(node) else {
continue;
};
+ let nodes = scene.bundle.doc.layer_at(&layer).cels()[c].nodes.clone();
+ let index = at[0];
let (w, h) = scene.size();
- let start = std::time::Instant::now();
- klad_render::rasterize_region(
- &nodes[index..=index],
- klad_render::vector::node_box(&nodes[index]).unwrap().unwrap(),
- 4096,
- 0.5,
- )
- .unwrap();
- println!(
- "lift {node}: lifted at half scale {:.0} ms",
- start.elapsed().as_secs_f64() * 1000.0
- );
- let t = std::time::Instant::now();
- let lower = rasterize_nodes(&nodes[..index], w, h).unwrap();
- let lower_ms = t.elapsed().as_secs_f64() * 1000.0;
- let t = std::time::Instant::now();
- let upper = rasterize_nodes(&nodes[index + 1..], w, h).unwrap();
- println!(
- "lift {node}: index {index} of {}, lower {lower_ms:.0} ms, upper {:.0} ms",
- nodes.len(),
- t.elapsed().as_secs_f64() * 1000.0
- );
- let start = std::time::Instant::now();
- let [x, y, bw, bh] = klad_render::vector::node_box(&nodes[index]).unwrap().unwrap();
- let lifted = klad_render::rasterize_region(&nodes[index..=index], [x, y, bw, bh], 4096, 1.0).unwrap();
- let prepare = start.elapsed().as_secs_f64() * 1000.0;
- let start = std::time::Instant::now();
- let planes = scene.lift_planes(&layer, &lower, &upper).unwrap();
- let compose = start.elapsed().as_secs_f64() * 1000.0;
- if let Some(planes) = &planes {
- let worst = [(300usize, 900usize), (1000, 1100), (1700, 800), (600, 1250), (100, 300)]
- .iter()
- .map(|&(x, y)| {
- let px = rebuilt(&scene, planes, &lifted, x, y);
- let i = (y / 256) * scene.cols() + x / 256;
- let reference = &scene.compose(&[i], None).unwrap()[0].1;
- let o = ((y % 256) * 256 + x % 256) * 4;
- (0..3)
- .map(|c| (px[c] - reference[o + c].to_f32()).abs())
- .fold(0.0f32, f32::max)
- })
- .fold(0.0f32, f32::max);
- println!(
- "lift {node}: {} planes {:?}, worst channel error {worst:.4}",
- planes.runs.len(),
- planes.runs.iter().map(|(m, _)| *m).collect::<Vec<_>>()
- );
- }
- let mut moved = nodes.clone();
- moved[index].transform.x += 25.0;
- let raster = rasterize_nodes(&moved, w, h).unwrap();
- let hash = fnv(FNV_OFFSET, &serde_json::to_vec(&moved).unwrap());
- let cel = scene.node_slot(node).unwrap().1;
- let mut editing = Scene::open(Path::new(&path)).unwrap();
let op = klad_core::ops::parse_lines(&format!(
r#"{{"op":"set","id":"{node}","transform.x":{}}}"#,
- moved[index].transform.x
+ nodes[index].transform.x + 25.0
))
.unwrap();
+ let mut editing = Scene::open(Path::new(&path)).unwrap();
let start = std::time::Instant::now();
- let dirty = editing.apply_rendered(&op, (cel, hash, raster), &brushes).unwrap();
+ let done = previewed(&editing, op.clone(), &[], &brushes);
println!(
- "commit {node}: apply_rendered {:.0} ms, {} tiles",
+ "preview {node} ({layer:?}, {w}x{h}): {:.0} ms, {} tiles composed",
+ start.elapsed().as_secs_f64() * 1000.0,
+ done.tiles.len()
+ );
+ let start = std::time::Instant::now();
+ let dirty = editing.apply(&op, &brushes).unwrap();
+ println!(
+ "commit {node}: apply {:.0} ms, {} tiles",
start.elapsed().as_secs_f64() * 1000.0,
dirty.len()
);
@@ -3514,87 +3324,55 @@ mod tests {
"redo {node}: editor redo total {:.0} ms ({step:?} tiles)",
start.elapsed().as_secs_f64() * 1000.0
);
- println!(
- "lift {node}: background prepare {prepare:.0} ms ({}x{}), compose base and top {compose:.0} ms, live {}",
- lifted.width,
- lifted.height,
- planes.is_some()
- );
}
}
- fn rebuilt(scene: &Scene, planes: &Planes, lifted: &klad_render::Lifted, x: usize, y: usize) -> [f32; 4] {
- let i = (y / 256) * scene.cols() + x / 256;
- let o = ((y % 256) * 256 + x % 256) * 4;
- let pick = |tiles: &Tiles| -> [f32; 4] {
- let t = &tiles.iter().find(|(k, _)| *k == i).unwrap().1;
- [t[o].to_f32(), t[o + 1].to_f32(), t[o + 2].to_f32(), t[o + 3].to_f32()]
- };
- let [rx, ry, rw, rh] = lifted.rect;
- let lx = ((x as f32 + 0.5 - rx) / rw * lifted.width as f32) as usize;
- let ly = ((y as f32 + 0.5 - ry) / rh * lifted.height as f32) as usize;
- let l: [f32; 4] = if lx < lifted.width as usize && ly < lifted.height as usize {
- let at = (ly * lifted.width as usize + lx) * 4;
- [0, 1, 2, 3].map(|c| lifted.pixels[at + c].to_f32() * planes.opacity)
- } else {
- [0.0; 4]
- };
- let base = pick(&planes.base);
- let mut px: [f32; 4] = [0, 1, 2, 3].map(|c| l[c] + base[c] * (1.0 - l[3]));
- planes.runs.iter().for_each(|(mix, tiles)| {
- let t = pick(tiles);
- px = match mix {
- Mix::Over => [0, 1, 2, 3].map(|c| t[c] + px[c] * (1.0 - t[3])),
- Mix::Multiply => [px[0] * t[0], px[1] * t[1], px[2] * t[2], px[3]],
- Mix::Screen => [0, 1, 2, 3].map(|c| t[c] + px[c] * (1.0 - t[c])),
- Mix::Add => [0, 1, 2, 3].map(|c| t[c] + px[c]),
- };
+ fn previewed(scene: &Scene, ops: Vec<Op>, cels: &[String], brushes: &BrushSet) -> crate::preview::Done {
+ crate::preview::Job {
+ ops,
+ snap: std::sync::Arc::new(scene.preview_snapshot(cels, brushes).unwrap()),
+ shown: BTreeSet::new(),
+ visible: scene.all_tiles().into_iter().collect(),
+ }
+ .run()
+ .unwrap()
+ }
+
+ fn preview_agrees(scene: &mut Scene, ops: Vec<Op>, cels: &[String], brushes: &BrushSet) -> usize {
+ let done = previewed(scene, ops.clone(), cels, brushes);
+ let dirty = scene.apply(&ops, brushes).unwrap();
+ assert!(
+ dirty.iter().all(|i| done.changed.contains(i)),
+ "the commit changed {dirty:?}, the preview {:?}",
+ done.changed
+ );
+ let indices: Vec<usize> = done.tiles.iter().map(|(i, _)| *i).collect();
+ let committed = scene.compose(&indices, None).unwrap();
+ done.tiles.iter().zip(&committed).for_each(|((i, shown), (j, after))| {
+ assert_eq!(i, j);
+ let worst = shown
+ .iter()
+ .zip(after)
+ .map(|(a, b)| (a.to_f32() - b.to_f32()).abs())
+ .fold(0.0f32, f32::max);
+ assert!(worst <= 2.0 / 255.0, "tile {i} previewed {:.2}/255 off", worst * 255.0);
});
- px
+ done.tiles.len()
}
#[test]
- fn lifted_planes_rebuild_the_same_picture_under_blend_modes() {
- [Blend::Normal, Blend::Multiply, Blend::Screen]
+ fn previews_compose_what_the_edit_will_show_under_every_blend() {
+ let brushes = BrushSet::presets();
+ [Blend::Normal, Blend::Multiply, Blend::Screen, Blend::Overlay]
.iter()
.for_each(|&blend| {
- let dir = bundle(&format!("lift-{blend:?}"), blend);
- let scene = Scene::open(&dir).unwrap();
- let (path, _, index, nodes) = scene.node_slot("n1").unwrap();
- let (w, h) = scene.size();
- let lower = rasterize_nodes(&nodes[..index], w, h).unwrap();
- let upper = rasterize_nodes(&nodes[index + 1..], w, h).unwrap();
- let planes = scene.lift_planes(&path, &lower, &upper).unwrap().unwrap();
- let lifted =
- klad_render::rasterize_region(&nodes[index..=index], [48.0, 48.0, 404.0, 154.0], 4096, 1.0)
- .unwrap();
- let paint: Rasters = scene
- .rasters
- .iter()
- .filter(|(k, _)| scene.cels.contains_key(*k))
- .map(|(k, v)| (k.clone(), v.clone()))
- .collect();
- let full = compose(&scene.bundle.doc, scene.frame, &paint, View::scaled(1.0)).unwrap();
- [(100usize, 100usize), (300, 60), (520, 250), (60, 190)]
- .iter()
- .for_each(|&(x, y)| {
- let px = rebuilt(&scene, &planes, &lifted, x, y);
- let got = [0, 1, 2].map(|c| (px[c] / px[3].max(1e-6) * 255.0).round() as i32);
- let want = full.pixel(x as u32, y as u32);
- assert!(
- got.iter().zip(&want[..3]).all(|(a, b)| (a - *b as i32).abs() <= 3),
- "{blend:?} at ({x},{y}): {got:?} vs {want:?}"
- );
- });
- assert_eq!(planes.runs.len(), if blend == Blend::Normal { 1 } else { 2 });
+ let dir = bundle(&format!("preview-{blend:?}"), blend);
+ let mut scene = Scene::open(&dir).unwrap();
+ let moved = klad_core::ops::parse_lines(r#"{"op":"set","id":"n1","transform.x":120,"transform.y":40}"#)
+ .unwrap();
+ let tiles = preview_agrees(&mut scene, moved, &[], &brushes);
+ assert!(tiles > 0 && tiles < scene.all_tiles().len(), "{blend:?}: {tiles} tiles");
});
- let dir = bundle("lift-overlay", Blend::Overlay);
- let scene = Scene::open(&dir).unwrap();
- let (path, _, _, _) = scene.node_slot("n1").unwrap();
- let (w, h) = scene.size();
- let empty = Raster::new(w, h);
- assert!(scene.lift_planes(&path, &empty, &empty).unwrap().is_none());
- assert!(scene.node_slot("cv").is_none());
}
#[test]
@@ -3930,7 +3708,7 @@ mod tests {
}
#[test]
- fn clips_and_masks_compose_right_from_every_active_layer_and_lift_only_when_exact() {
+ fn clips_and_masks_compose_right_from_every_active_layer_and_preview_too() {
let brushes = BrushSet::presets();
let dir = bundle("clipmask", Blend::Normal);
let mut scene = Scene::open(&dir).unwrap();
@@ -3976,35 +3754,25 @@ mod tests {
scene.apply(&reclip, &brushes).unwrap();
assert!(!scene.fast);
agrees(&scene);
- let (w, h) = scene.size();
- let empty = Raster::new(w, h);
- [vec![2], vec![1, 0], vec![1]].iter().for_each(|path| {
- assert!(scene.lift_planes(path, &empty, &empty).unwrap().is_none(), "{path:?}");
- });
- let (path, _, index, nodes) = scene.node_slot("n1").unwrap();
- let lower = rasterize_nodes(&nodes[..index], w, h).unwrap();
- let upper = rasterize_nodes(&nodes[index + 1..], w, h).unwrap();
- let planes = scene.lift_planes(&path, &lower, &upper).unwrap().unwrap();
- let lifted =
- klad_render::rasterize_region(&nodes[index..=index], [48.0, 48.0, 404.0, 154.0], 4096, 1.0).unwrap();
- let paint: Rasters = scene
- .rasters
+ let moved =
+ klad_core::ops::parse_lines(r#"{"op":"set","id":"n1","transform.x":-60,"transform.y":70}"#).unwrap();
+ preview_agrees(&mut scene, moved, &[], &brushes);
+ let painted = scene.bundle.doc.layer("a").unwrap().cels()[0].id.clone();
+ let ids: Vec<String> = scene.cels[&painted]
+ .marks()
.iter()
- .filter(|(k, _)| scene.cels.contains_key(*k))
- .map(|(k, v)| (k.clone(), v.clone()))
+ .map(|m| format!("{painted}:s{}", m.id()))
.collect();
- let full = compose(&scene.bundle.doc, scene.frame, &paint, View::scaled(1.0)).unwrap();
- [(100usize, 100usize), (300, 60), (300, 150), (520, 250)]
- .iter()
- .for_each(|&(x, y)| {
- let px = rebuilt(&scene, &planes, &lifted, x, y);
- let got = [0, 1, 2].map(|c| (px[c] / px[3].max(1e-6) * 255.0).round() as i32);
- let want = full.pixel(x as u32, y as u32);
- assert!(
- got.iter().zip(&want[..3]).all(|(a, b)| (a - *b as i32).abs() <= 3),
- "({x},{y}): {got:?} vs {want:?}"
- );
- });
+ let shifted = vec![Op::Transform {
+ ids,
+ transform: klad_core::markedit::MarkTransform {
+ x: 40.0,
+ y: -25.0,
+ ..Default::default()
+ },
+ }];
+ scene.set_active(vec![1, 0]).unwrap();
+ preview_agrees(&mut scene, shifted, &[painted], &brushes);
}
#[test]
diff --git a/crates/app/src/editor.rs b/crates/app/src/editor.rs
index 2410d3f..93ec7f1 100644
--- a/crates/app/src/editor.rs
+++ b/crates/app/src/editor.rs
@@ -32,13 +32,14 @@ mod ui_tests;
use crate::color::{self, Hsva};
use crate::commands::Cmd;
-use crate::composite::{Planes, Preview, Scene};
+use crate::composite::{Preview, Scene, Tiles};
use crate::frames::FrameCache;
-use crate::gpu::{CanvasPaint, QuadDraw, quad_uniform};
+use crate::gpu::CanvasPaint;
use crate::jobs::Jobs;
-use crate::lift::{self, Prepared};
+use crate::lift;
use crate::messages::{Messages, Tone};
use crate::pen::{self, Pen, PenEvent, Phase, device_key};
+use crate::preview;
use crate::settings::{self, Settings};
use crate::stats::{Stats, lock};
use crate::sync::{Watch, watch};
@@ -67,12 +68,13 @@ use serde_json::{Map, Value, json};
use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::ops::RangeInclusive;
use std::path::{Path, PathBuf};
-use std::sync::mpsc::Receiver;
+use std::sync::mpsc::{Receiver, channel};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
const HANDLE: f32 = 12.0;
const REFILL_MS: f64 = 8.0;
+const FINISH_WAIT: Duration = Duration::from_secs(2);
const KNOB: f32 = 30.0;
const IDENTITY: [f32; 6] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];
@@ -422,19 +424,20 @@ impl Drag {
}
}
-struct Commit {
- job: Receiver<Result<(u64, Raster)>>,
+struct Finish {
ops: Vec<Op>,
- affine: [f32; 6],
+ rev: u64,
+ dirty: BTreeSet<usize>,
+ since: Instant,
}
-struct LiftState {
- key: String,
- rev: u64,
- job: Option<Receiver<Result<Prepared>>>,
- ready: Option<(Prepared, Planes)>,
- stage: usize,
- commit: Option<Commit>,
+struct PreviewState {
+ snap: Arc<preview::Snapshot>,
+ asked: Option<Vec<Op>>,
+ job: Option<Receiver<Result<preview::Done>>>,
+ shown: BTreeSet<usize>,
+ done: Option<(Vec<Op>, bool, BTreeSet<usize>)>,
+ finish: Option<Finish>,
}
struct Live {
@@ -583,7 +586,6 @@ pub(crate) struct Editor {
queued: Vec<Cmd>,
tabs: Vec<bool>,
themed: bool,
- lift_since: Instant,
key_shift: bool,
held: selection::Held,
sizing: Option<(f32, f32, Pos2)>,
@@ -644,7 +646,7 @@ pub(crate) struct Editor {
shared: (Option<String>, Vec<String>, u32),
ctx: egui::Context,
sel_box: Option<(String, u64, [Vec2; 4])>,
- lift: Option<LiftState>,
+ preview: Option<PreviewState>,
zoom_px: f32,
picked: Option<Picked>,
also: Vec<String>,
@@ -758,7 +760,6 @@ impl Editor {
queued: Vec::new(),
tabs: Vec::new(),
themed: false,
- lift_since: Instant::now(),
key_shift: false,
held: selection::Held::default(),
sizing: None,
@@ -819,7 +820,7 @@ impl Editor {
shared: (None, Vec::new(), 0),
ctx,
sel_box: None,
- lift: None,
+ preview: None,
zoom_px: 1.0,
picked: None,
also: Vec::new(),
@@ -944,7 +945,7 @@ impl Editor {
self.external.get_or_insert(first);
self.pins = notes::read(&self.scene.bundle);
}
- let committing = self.lift.as_ref().is_some_and(|l| l.commit.is_some()) || self.path_commit.is_some();
+ let committing = self.path_commit.is_some();
if self.live.is_some()
|| self.drag.is_some()
|| self.point_drag.is_some()
@@ -1044,10 +1045,16 @@ impl Editor {
}
fn apply(&mut self, ops: Vec<Op>) -> Result<()> {
+ let dirty = self.commit(ops)?;
+ self.dirty.extend(dirty);
+ Ok(())
+ }
+
+ fn commit(&mut self, ops: Vec<Op>) -> Result<Vec<usize>> {
self.checks.gaps = None;
self.checks.arcs = None;
if ops.is_empty() {
- return Ok(());
+ return Ok(Vec::new());
}
self.end_look_preview()?;
self.end_typing_preview()?;
@@ -1057,9 +1064,8 @@ impl Editor {
"edit",
format!("edit applied, {} tiles refreshed in {:.0} ms", dirty.len(), ms(start)),
);
- self.dirty.extend(dirty);
self.forget_missing_selection();
- Ok(())
+ Ok(dirty)
}
fn set(&mut self, id: &str, props: Vec<(String, Value)>) -> Result<()> {
@@ -1326,145 +1332,210 @@ impl Editor {
}
}
- fn lift_key(&self) -> Option<String> {
- match self.tool {
- Tool::Direct => None,
- _ if self.on_marks() => self.picked.as_ref().map(Picked::key),
- _ => self.selection.clone(),
+ fn node_ops(&self, drag: &Drag) -> Result<Option<Vec<Op>>> {
+ let node = match self.scene.bundle.doc.item(&drag.node) {
+ Some(Item::Node(_, _, node)) => node.clone(),
+ _ => return Ok(None),
+ };
+ let affine = drag.affine();
+ let t = match drag.stretch() {
+ Some((axis, _, k)) => lift::stretched(&node, affine, axis, k)?,
+ None => lift::committed(&node, affine, drag.scale(), drag.angle().to_degrees())?,
+ };
+ let props: Map<String, Value> = [
+ ("transform.x", json!(t.x)),
+ ("transform.y", json!(t.y)),
+ ("transform.rotate", json!(t.rotate)),
+ ("transform.sx", json!(t.sx)),
+ ("transform.sy", json!(t.sy)),
+ ]
+ .into_iter()
+ .map(|(k, v)| (k.to_string(), v))
+ .collect();
+ Ok(Some(vec![Op::Set {
+ id: drag.node.clone(),
+ props,
+ }]))
+ }
+
+ fn drag_ops(&self) -> Option<Vec<Op>> {
+ let drag = self.drag.as_ref().filter(|d| d.moved() && !d.copy)?;
+ match drag.strokes {
+ true => self
+ .picked_ops(LassoAction::Transform(drag.mark_transform()))
+ .map(|(ops, _)| ops),
+ false => self.node_ops(drag).ok().flatten(),
}
}
- fn lift_job(&self, key: String, rev: u64) -> Option<lift::Job> {
- let canvas = self.scene.size();
- let scale = self.zoom_px.clamp(0.25, 1.0);
- if self.on_marks() {
- let picked = self.picked.as_ref().filter(|p| p.more.is_empty())?;
- let (replay, raster) = self.scene.active_replay()?;
- let (marks, ids) = match &picked.cut {
- Some(_) => {
- let view = self.cut_view.as_ref().filter(|v| v.key == key)?;
- (Some(view.marks.clone()), view.chosen.clone())
- }
- None => (None, picked.ids.clone()),
- };
- let order = marks.as_deref().unwrap_or(replay.marks());
- let first = order.iter().position(|m| ids.contains(&m.id()))?;
- if order[first..].iter().any(Mark::locked) {
- return None;
+ fn preview_cels(&self) -> Vec<String> {
+ match self.drag.as_ref().is_some_and(|d| d.strokes) {
+ true => self
+ .picked
+ .iter()
+ .flat_map(|p| std::iter::once(p.cel.clone()).chain(p.more.iter().map(|m| m.cel.clone())))
+ .collect(),
+ false => Vec::new(),
+ }
+ }
+
+ fn drop_preview(&mut self) {
+ if let Some(state) = self.preview.take() {
+ self.dirty.extend(state.shown);
+ if let Some(finish) = state.finish {
+ self.dirty.extend(finish.dirty);
}
- return Some(lift::Job {
- key,
- rev,
- cel: picked.cel.clone(),
- layer: self.scene.active.clone(),
- source: lift::Source::Marks {
- ids,
- marks,
- replay: Box::new(replay.clone()),
- raster: raster.clone(),
- brushes: Box::new(self.brushes.clone()),
- },
- canvas,
- scale,
- });
}
- let (layer, cel, index, nodes) = self.scene.node_slot(&key)?;
- Some(lift::Job {
- key,
- rev,
- cel,
- layer,
- source: lift::Source::Node { index, nodes },
- canvas,
- scale,
- })
}
- fn drop_lift(&mut self) {
- self.lift = None;
+ fn finish_preview(&mut self, ops: Vec<Op>, dirty: Vec<usize>) {
+ let Some(mut state) = self.preview.take() else {
+ self.dirty.extend(dirty);
+ return;
+ };
+ match state.done.take() {
+ Some((done, exact, composed)) if state.job.is_none() && done == ops => {
+ let settled = |i: &usize| exact && composed.contains(i);
+ self.dirty.retain(|i| !settled(i));
+ self.dirty
+ .extend(dirty.into_iter().chain(state.shown).filter(|i| !settled(i)));
+ }
+ done => {
+ state.done = done;
+ state.finish = Some(Finish {
+ ops,
+ rev: self.scene.bundle.doc.rev,
+ dirty: dirty.into_iter().collect(),
+ since: Instant::now(),
+ });
+ self.preview = Some(state);
+ }
+ }
}
- fn tend_lift(&mut self) -> Result<()> {
+ fn tend_preview(&mut self, visible: BTreeSet<usize>) -> Result<Tiles> {
+ let mut uploads = Vec::new();
let rev = self.scene.bundle.doc.rev;
- let busy = self.drag.is_some() || self.lift.as_ref().is_some_and(|l| l.commit.is_some());
- let key = self.lift_key();
- let stale = self
- .lift
- .as_ref()
- .is_some_and(|l| Some(&l.key) != key.as_ref() || l.rev != rev);
- if stale && !busy {
- self.drop_lift();
- }
- if self.lift.is_none()
- && !busy
- && let Some(key) = key.clone()
- && let Some(job) = self.lift_job(key.clone(), rev)
- {
- self.lift_since = Instant::now();
- self.lift = Some(LiftState {
- key,
- rev,
- job: Some(lift::prepare(job, self.ctx.clone())),
- ready: None,
- stage: 0,
- commit: None,
- });
- }
- let prepared = self
- .lift
- .as_mut()
- .and_then(|l| l.job.as_ref().and_then(|rx| rx.try_recv().ok()));
- if let Some(result) = prepared {
- match result {
- Ok(p) if p.rev == rev && Some(&p.key) == key.as_ref() => {
- let planes = self.scene.lift_planes(&p.layer, &p.lower, &p.upper)?;
- if let Some(l) = self.lift.as_mut() {
- l.job = None;
- l.ready = planes.map(|planes| (p, planes));
+ if let Some(mut state) = self.preview.take() {
+ let mut keep = true;
+ match state.job.as_ref().and_then(|rx| rx.try_recv().ok()) {
+ Some(Ok(done)) => {
+ state.job = None;
+ let composed: BTreeSet<usize> = done.tiles.iter().map(|(i, _)| *i).collect();
+ let earlier = std::mem::replace(
+ &mut state.shown,
+ done.changed.intersection(&composed).copied().collect(),
+ );
+ let current = state.finish.as_ref().map_or(state.snap.rev, |f| f.rev) == rev;
+ let last = state.finish.as_ref().is_some_and(|f| f.ops == done.ops);
+ if current {
+ uploads = done.tiles;
}
- }
- Ok(_) => self.lift = None,
- Err(e) => {
- self.failed(e.context("the selection could not be prepared"));
- if let Some(l) = self.lift.as_mut() {
- l.job = None;
+ if last || !current {
+ keep = false;
+ let settled: BTreeSet<usize> = match current && done.exact {
+ true => composed,
+ false => BTreeSet::new(),
+ };
+ self.dirty.retain(|i| !settled.contains(i));
+ let finished = state.finish.take().map(|f| f.dirty).unwrap_or_default();
+ self.dirty.extend(
+ finished
+ .into_iter()
+ .chain(earlier)
+ .chain(state.shown.iter().copied())
+ .chain(done.hidden)
+ .filter(|i| !settled.contains(i)),
+ );
+ } else {
+ state.done = Some((done.ops, done.exact, composed));
}
}
+ Some(Err(e)) => {
+ keep = false;
+ self.dirty.extend(state.shown.iter().copied());
+ self.dirty
+ .extend(state.finish.iter().flat_map(|f| f.dirty.iter().copied()));
+ self.failed(e.context("the moved picture could not be drawn"));
+ }
+ None => {}
+ }
+ let abandoned = state.finish.is_none() && self.drag.is_none();
+ if keep && (abandoned || state.finish.as_ref().is_some_and(|f| f.since.elapsed() > FINISH_WAIT)) {
+ keep = false;
+ self.dirty.extend(state.shown.iter().copied());
+ self.dirty
+ .extend(state.finish.iter().flat_map(|f| f.dirty.iter().copied()));
+ }
+ if keep {
+ self.preview = Some(state);
}
}
- let finished = self
- .lift
- .as_mut()
- .and_then(|l| l.commit.as_ref().and_then(|c| c.job.try_recv().ok()));
- if let Some(result) = finished {
- let Some(mut state) = self.lift.take() else {
- return Ok(());
+ if self.preview.is_none()
+ && self.live.is_none()
+ && self.drag.as_ref().is_some_and(|d| d.moved() && !d.copy)
+ && self.canvas_current()
+ {
+ let cels = self.preview_cels();
+ self.preview = self
+ .scene
+ .preview_snapshot(&cels, &self.brushes)
+ .map(|snap| PreviewState {
+ snap: Arc::new(snap),
+ asked: None,
+ job: None,
+ shown: BTreeSet::new(),
+ done: None,
+ finish: None,
+ });
+ }
+ let wanted = match self.preview.as_ref().map(|p| p.finish.as_ref()) {
+ Some(Some(finish)) => Some(finish.ops.clone()),
+ Some(None) => self.drag_ops(),
+ None => None,
+ };
+ if let (Some(state), Some(ops)) = (self.preview.as_mut(), wanted)
+ && state.job.is_none()
+ && state.asked.as_ref() != Some(&ops)
+ {
+ let job = preview::Job {
+ ops: ops.clone(),
+ snap: state.snap.clone(),
+ shown: state.shown.clone(),
+ visible,
};
- let commit = state
- .commit
- .take()
- .ok_or_else(|| crate::report::bug("a shape edit lost what it was writing"))?;
- let start = Instant::now();
- match (result, state.ready.as_ref()) {
- (Ok((hash, raster)), Some((p, _))) => {
- self.scene
- .apply_rendered(&commit.ops, (p.cel.clone(), hash, raster), &self.brushes)?;
- }
- _ => {
- self.scene.apply(&commit.ops, &self.brushes)?;
- }
- }
- self.measure("transform", format!("transform written in {:.0} ms", ms(start)));
- self.dirty.extend(self.scene.all_tiles());
- self.forget_missing_selection();
+ state.asked = Some(ops);
+ let (tx, rx) = channel();
+ let ctx = self.ctx.clone();
+ crate::background().spawn(move || {
+ let _ = tx.send(job.run());
+ ctx.request_repaint();
+ });
+ state.job = Some(rx);
}
- Ok(())
+ Ok(uploads)
}
fn screen(&self, view: View, rect: Rect, c: Vec2) -> Pos2 {
rect.min + view.to_screen(c, rect.size())
}
+ fn visible_tiles(&self, view: View, rect: Rect) -> BTreeSet<usize> {
+ 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| {
+ let at = |v: f32| ((v / klad_brush::TILE as f32).floor() as i64).clamp(0, count as i64 - 1) as usize;
+ at(lo).saturating_sub(1)..=(at(hi) + 1).min(count - 1)
+ };
+ let (xs, ys) = (corners.map(|c| c.x), corners.map(|c| c.y));
+ let low = |v: [f32; 4]| v.into_iter().fold(f32::MAX, f32::min);
+ let high = |v: [f32; 4]| v.into_iter().fold(f32::MIN, f32::max);
+ let cols = self.scene.cols();
+ range(low(ys), high(ys), self.scene.rows())
+ .flat_map(|ty| range(low(xs), high(xs), cols).map(move |tx| ty * cols + tx))
+ .collect()
+ }
+
fn edges(&self) -> bool {
match self.tool {
_ if self.on_marks() => true,
@@ -1487,6 +1558,7 @@ impl Editor {
}
fn start_drag(&mut self, id: String, grab: Grab, corners: [Vec2; 4], at: Vec2, fresh: bool) {
+ self.drop_preview();
let strokes = self.on_marks();
if !strokes && !matches!(self.scene.bundle.doc.item(&id), Some(Item::Node(..))) {
return;
@@ -1561,43 +1633,13 @@ impl Editor {
}
return Ok(());
}
- let affine = drag.affine();
- let node = match self.scene.bundle.doc.item(&drag.node) {
- Some(Item::Node(_, _, node)) => node.clone(),
- _ => return Ok(()),
- };
- let t = match drag.stretch() {
- Some((axis, _, k)) => lift::stretched(&node, affine, axis, k)?,
- None => lift::committed(&node, affine, drag.scale(), drag.angle().to_degrees())?,
+ let Some(ops) = self.node_ops(&drag)? else {
+ self.drop_preview();
+ return Ok(());
};
- let props: Map<String, Value> = [
- ("transform.x", json!(t.x)),
- ("transform.y", json!(t.y)),
- ("transform.rotate", json!(t.rotate)),
- ("transform.sx", json!(t.sx)),
- ("transform.sy", json!(t.sy)),
- ]
- .into_iter()
- .map(|(k, v)| (k.to_string(), v))
- .collect();
- let ops = vec![Op::Set {
- id: drag.node.clone(),
- props,
- }];
- let canvas = self.scene.size();
- let staged = |l: &LiftState| l.ready.as_ref().is_some_and(|(_, p)| l.stage >= p.runs.len() + 2);
- match self.lift.as_mut().filter(|l| staged(l) && l.key == drag.node) {
- Some(state) => {
- let (p, _) = state
- .ready
- .as_ref()
- .ok_or_else(|| crate::report::bug("a drag started before its picture was ready"))?;
- let job = lift::finish(p.nodes.clone(), p.index, t, canvas, self.ctx.clone());
- state.commit = Some(Commit { job, ops, affine });
- Ok(())
- }
- None => self.apply(ops),
- }
+ let dirty = self.commit(ops.clone())?;
+ self.finish_preview(ops, dirty);
+ Ok(())
}
fn grab_under(&mut self, c: Vec2, pos: Pos2) -> Result<()> {
@@ -1682,7 +1724,7 @@ impl Editor {
};
drag.copy = false;
let strokes = drag.strokes;
- self.drop_lift();
+ self.drop_preview();
self.duplicate_in_place()?;
if !strokes && let (Some(drag), Some(id)) = (self.drag.as_mut(), self.selection.clone()) {
drag.node = id;
@@ -1706,7 +1748,15 @@ impl Editor {
return self.finish_pick();
}
let start = Instant::now();
- self.edit_picked(LassoAction::Transform(drag.mark_transform()))?;
+ match self.picked_ops(LassoAction::Transform(drag.mark_transform())) {
+ Some((ops, after)) => {
+ let dirty = self.commit(ops.clone())?;
+ self.picked = after;
+ self.forget_missing_selection();
+ self.finish_preview(ops, dirty);
+ }
+ None => self.drop_preview(),
+ }
let text = format!(
"{} strokes and fills {} and redrawn in {:.0} ms",
self.picked.as_ref().map_or(0, Picked::count),
@@ -2434,7 +2484,6 @@ impl Editor {
});
}
}
- (Tool::Strokes, Phase::Down) if self.lift.as_ref().is_some_and(|l| l.commit.is_some()) => {}
(Tool::Strokes, Phase::Down) => match self.grab_at(view, rect, e.pos) {
Some((id, grab, corners)) => self.start_drag(id, grab, corners, c, false),
None => {
@@ -2493,7 +2542,6 @@ impl Editor {
}
}
(Tool::Brush, Phase::Up) => self.finish()?,
- (Tool::Select, Phase::Down) if self.lift.as_ref().is_some_and(|l| l.commit.is_some()) => {}
(Tool::Select, Phase::Down) => match self.grab_at(view, rect, e.pos) {
Some((id, grab, corners)) => self.start_drag(id, grab, corners, c, false),
None => self.grab_under(c, e.pos)?,
@@ -2859,7 +2907,6 @@ impl Editor {
self.refresh_box();
self.refresh_cut();
self.refresh_shape();
- self.tend_lift()?;
self.tend_path()?;
let level = match self.zoom_px >= 1.0 {
true => 0,
@@ -2869,50 +2916,14 @@ impl Editor {
let show = self.tend_frames()?;
let view_uniform = view.uniform(area, ctx.pixels_per_point(), canvas);
let (w, h) = self.scene.size();
- let moving = self.drag.as_ref().filter(|d| d.moved()).map(Drag::affine);
- let mut base = Vec::new();
- let mut tops = Vec::new();
- let mut lifted = None;
- let mut lifting = false;
- if let Some(state) = self.lift.as_mut()
- && let Some((p, planes)) = state.ready.as_ref()
- {
- let stages = planes.runs.len() + 2;
- if state.stage == 0 {
- base = planes.base.clone();
- }
- tops = planes
- .runs
- .iter()
- .enumerate()
- .map(|(k, (mix, tiles))| {
- let draw = QuadDraw {
- uniform: quad_uniform(&view_uniform, IDENTITY, 1.0, [0.0, 0.0, w as f32, h as f32]),
- tiles: Mutex::new(if state.stage == k + 1 {
- tiles.clone()
- } else {
- Vec::new()
- }),
- image: Mutex::new(None),
- };
- (*mix, draw)
- })
- .collect();
- let affine = state.commit.as_ref().map_or(moving.unwrap_or(IDENTITY), |c| c.affine);
- lifted = Some(QuadDraw {
- uniform: quad_uniform(&view_uniform, affine, planes.opacity, p.lifted.rect),
- tiles: Mutex::new(Vec::new()),
- image: Mutex::new(
- (state.stage == stages - 1).then(|| (p.lifted.width, p.lifted.height, p.lifted.pixels.clone())),
- ),
- });
- if state.stage < stages {
- state.stage += 1;
- ctx.request_repaint();
- }
- lifting = state.stage >= stages && (moving.is_some() || state.commit.is_some());
- }
+ let visible = self.visible_tiles(view, rect);
+ let previewed = self.tend_preview(visible)?;
let mut tiles = std::mem::take(&mut self.dirty);
+ if let Some(state) = self.preview.as_ref() {
+ let held: BTreeSet<usize> = tiles.intersection(&state.shown).copied().collect();
+ tiles.retain(|i| !held.contains(i));
+ self.dirty.extend(held);
+ }
let mut stroke: Vec<usize> = self.buffer.take_dirty();
stroke.extend(self.mirror_buffer.take_dirty());
if !self.canvas_current() {
@@ -2934,7 +2945,7 @@ impl Editor {
opacity: l.stroke.opacity,
blend: stroke_blend(&l.brush, l.stroke.lock).unwrap_or(l.brush.blend),
});
- let uploads = if tiles.is_empty() && stroke.is_empty() {
+ let mut uploads = if tiles.is_empty() && stroke.is_empty() {
Vec::new()
} else {
self.scene.compose_painting(&stroke, &tiles, preview.as_ref())?
@@ -2948,11 +2959,12 @@ impl Editor {
stats.compose_ms.push(spent as f32);
stats.tiles.push(uploads.len() as f32);
}
+ uploads.extend(previewed);
let (frame_uploads, frame_drops) = self.frames.take();
ui.painter().add(egui_wgpu::Callback::new_paint_callback(
rect,
CanvasPaint {
- show: show.filter(|_| !lifting),
+ show: show.filter(|_| self.preview.is_none()),
frame_uploads: Mutex::new(frame_uploads),
frame_drops,
uniform: view_uniform,
@@ -2961,10 +2973,6 @@ impl Editor {
cols: self.scene.cols(),
pending: self.pending.take(),
stats: self.stats.clone(),
- base: Mutex::new(base),
- tops,
- lift: lifted,
- lifting,
},
));
self.parallax(ui, view, rect);
@@ -2982,9 +2990,9 @@ impl Editor {
|| self.point_drag.is_some()
|| self.path_commit.is_some()
|| self
- .lift
+ .preview
.as_ref()
- .is_some_and(|l| l.job.is_some() || l.commit.is_some())
+ .is_some_and(|p| p.job.is_some() || p.finish.is_some())
{
ctx.request_repaint();
}
@@ -3057,14 +3065,9 @@ impl Editor {
self.decorate_pen(&painter, path, hover, view, rect, accent, dark);
}
if let Some((_, corners)) = self.handles() {
- let committing = self.lift.as_ref().and_then(|l| l.commit.as_ref()).map(|c| c.affine);
- let corners = match (&self.drag, committing) {
- (Some(drag), _) => drag.preview(),
- (None, Some(a)) => corners.map(|c| {
- let (x, y) = lift::affine_apply(a, (c.x, c.y));
- vec2(x, y)
- }),
- _ => corners,
+ let corners = match &self.drag {
+ Some(drag) => drag.preview(),
+ None => corners,
};
let screen: Vec<Pos2> = corners.iter().map(|c| self.screen(view, rect, *c)).collect();
painter.add(egui::Shape::closed_line(screen.clone(), dark));
diff --git a/crates/app/src/editor/panels.rs b/crates/app/src/editor/panels.rs
index eb39efb..a1a6eb6 100644
--- a/crates/app/src/editor/panels.rs
+++ b/crates/app/src/editor/panels.rs
@@ -710,8 +710,13 @@ impl Editor {
fn internal_work(&self, now: Instant) -> Vec<String> {
let slow = Duration::from_millis(600);
let mut work = Vec::new();
- if self.lift.as_ref().is_some_and(|l| l.job.is_some()) && now.duration_since(self.lift_since) > slow {
- work.push("preparing the selection".to_string());
+ if self
+ .preview
+ .as_ref()
+ .and_then(|p| p.finish.as_ref())
+ .is_some_and(|f| now.duration_since(f.since) > slow)
+ {
+ work.push("drawing the move".to_string());
}
if self.path_commit.is_some() {
work.push("drawing the edited path".to_string());
diff --git a/crates/app/src/editor/selection.rs b/crates/app/src/editor/selection.rs
index 4a5fee1..3fe323f 100644
--- a/crates/app/src/editor/selection.rs
+++ b/crates/app/src/editor/selection.rs
@@ -72,7 +72,7 @@ impl Editor {
}
pub(super) fn writing(&self) -> bool {
- self.lift.as_ref().is_some_and(|l| l.commit.is_some()) || self.path_commit.is_some()
+ self.path_commit.is_some()
}
fn middle_of_picked(&self) -> Option<[f32; 2]> {
diff --git a/crates/app/src/editor/timeline.rs b/crates/app/src/editor/timeline.rs
index 25498c3..c4bde1f 100644
--- a/crates/app/src/editor/timeline.rs
+++ b/crates/app/src/editor/timeline.rs
@@ -291,11 +291,7 @@ fn exposed(layer: &Layer, frame: u32) -> Option<(Cel, u32)> {
impl Editor {
pub(super) fn busy(&self) -> bool {
- self.live.is_some()
- || self.drag.is_some()
- || self.point_drag.is_some()
- || self.path_commit.is_some()
- || self.lift.as_ref().is_some_and(|l| l.commit.is_some())
+ self.live.is_some() || self.drag.is_some() || self.point_drag.is_some() || self.path_commit.is_some()
}
pub(crate) fn canvas_current(&self) -> bool {
@@ -325,7 +321,7 @@ impl Editor {
self.direct = None;
self.cut_view = None;
self.lasso = None;
- self.drop_lift();
+ self.drop_preview();
Ok(())
}
diff --git a/crates/app/src/editor/ui_tests.rs b/crates/app/src/editor/ui_tests.rs
index eda658c..bef34ee 100644
--- a/crates/app/src/editor/ui_tests.rs
+++ b/crates/app/src/editor/ui_tests.rs
@@ -1062,7 +1062,7 @@ fn drag(h: &mut Harness<'static, Editor>, from: egui::Pos2, to: egui::Pos2) {
}
#[test]
-fn a_shape_drag_started_while_the_last_one_is_written_still_happens() {
+fn a_shape_previews_only_its_tiles_while_dragged_and_two_drags_in_a_row_both_land() {
let path = sample("held");
let mut h = harness(editor(&path), vec2(1440.0, 900.0));
activate(&mut h, "shapes");
@@ -1074,32 +1074,38 @@ fn a_shape_drag_started_while_the_last_one_is_written_still_happens() {
};
let before = h.state().node_transform(&id).unwrap();
h.state_mut().tool = Tool::Select;
- h.state_mut().selection = Some(id.clone());
- settle(&mut h, |ed| {
- ed.lift
- .as_ref()
- .is_some_and(|l| l.ready.as_ref().is_some_and(|(_, p)| l.stage >= p.runs.len() + 2))
- });
let view = h.state().view.unwrap();
let rect = h.state().canvas_rect;
- let middle = rect.min + view.to_screen(egui::Vec2::new(80.0, 60.0), rect.size());
- drag(&mut h, middle, middle + vec2(40.0, 0.0));
- let writing = h.state().writing();
+ let middle = rect.min + view.to_screen(egui::Vec2::new(120.0, 30.0), rect.size());
+ h.hover_at(middle);
+ h.run_steps(1);
+ h.drag_at(middle);
+ h.run_steps(1);
+ (1..=5).for_each(|i| {
+ h.hover_at(middle + vec2(8.0 * i as f32, 0.0));
+ h.run_steps(1);
+ });
+ settle(&mut h, |ed| ed.preview.as_ref().is_some_and(|p| p.done.is_some()));
+ let (shown, all) = {
+ let ed = h.state();
+ (ed.preview.as_ref().unwrap().shown.clone(), ed.scene.all_tiles().len())
+ };
assert!(
- writing,
- "the first move was already written; the test would not cover a press during a write"
+ !shown.is_empty() && shown.len() < all,
+ "a press-and-drag previews the tiles under the shape: {shown:?} of {all}"
);
+ h.drop_at(middle + vec2(40.0, 0.0));
+ h.run_steps(1);
drag(&mut h, middle + vec2(40.0, 0.0), middle + vec2(40.0, 50.0));
- settle(&mut h, |ed| !ed.writing() && ed.drag.is_none() && ed.held.len() == 0);
- h.run_steps(3);
- settle(&mut h, |ed| !ed.writing() && ed.drag.is_none());
+ settle(&mut h, |ed| {
+ ed.preview.is_none() && ed.drag.is_none() && ed.dirty.is_empty()
+ });
let after = h.state().node_transform(&id).unwrap();
let moved = (after.x - before.x, after.y - before.y);
let expect = (40.0 / view.zoom, 50.0 / view.zoom);
assert!(
(moved.0 - expect.0).abs() < 2.0 && (moved.1 - expect.1).abs() < 2.0,
- "moved {moved:?}, expected {expect:?} (the first drag was {}being written when the second began)",
- if writing { "" } else { "not " }
+ "moved {moved:?}, expected {expect:?}"
);
let _ = std::fs::remove_dir_all(&path);
}
diff --git a/crates/app/src/gpu.rs b/crates/app/src/gpu.rs
index 3d1ab8f..343f025 100644
--- a/crates/app/src/gpu.rs
+++ b/crates/app/src/gpu.rs
@@ -1,4 +1,4 @@
-use crate::composite::{FrameImage, Mix};
+use crate::composite::FrameImage;
use crate::stats::{Stats, lock};
use egui_wgpu::wgpu;
use half::f16;
@@ -45,16 +45,9 @@ pub fn mip_chain(tile: &[f16]) -> Vec<Vec<f16>> {
pub struct CanvasGpu {
canvas_pipeline: wgpu::RenderPipeline,
- over: wgpu::RenderPipeline,
- multiply: wgpu::RenderPipeline,
- screen: wgpu::RenderPipeline,
- add: wgpu::RenderPipeline,
layout: wgpu::BindGroupLayout,
sampler: wgpu::Sampler,
canvas: Plane,
- base: Plane,
- tops: Vec<Plane>,
- lift: Plane,
frames: BTreeMap<u64, Plane>,
}
@@ -222,32 +215,9 @@ impl CanvasGpu {
mipmap_filter: wgpu::MipmapFilterMode::Linear,
..Default::default()
});
- let part = |src_factor, dst_factor| wgpu::BlendComponent {
- src_factor,
- dst_factor,
- operation: wgpu::BlendOperation::Add,
- };
- use wgpu::BlendFactor as F;
- let over_alpha = part(F::One, F::OneMinusSrcAlpha);
- let quad = |color, alpha| {
- pipeline(
- device,
- &layout,
- format,
- include_str!("quad.wgsl"),
- Some(wgpu::BlendState { color, alpha }),
- )
- };
Self {
canvas_pipeline: pipeline(device, &layout, format, include_str!("canvas.wgsl"), None),
- over: quad(part(F::One, F::OneMinusSrcAlpha), over_alpha),
- multiply: quad(part(F::Zero, F::Src), part(F::Zero, F::One)),
- screen: quad(part(F::One, F::OneMinusSrc), over_alpha),
- add: quad(part(F::One, F::One), part(F::One, F::One)),
canvas: plane(device, &layout, &sampler, size, 48, levels_for(size)),
- base: plane(device, &layout, &sampler, size, 48, levels_for(size)),
- tops: Vec::new(),
- lift: plane(device, &layout, &sampler, (1, 1), 80, 1),
frames: BTreeMap::new(),
layout,
sampler,
@@ -299,51 +269,14 @@ impl CanvasGpu {
);
}
- fn resize(&mut self, device: &wgpu::Device, which: Which, size: (u32, u32)) {
- let target = match which {
- Which::Canvas => &mut self.canvas,
- Which::Base => &mut self.base,
- Which::Top(i) => &mut self.tops[i],
- Which::Lift => &mut self.lift,
- };
- let levels = match which {
- Which::Lift => 1,
- _ => levels_for(size),
- };
+ fn resize(&mut self, device: &wgpu::Device, size: (u32, u32)) {
+ let levels = levels_for(size);
+ let target = &mut self.canvas;
target.texture = texture(device, size, levels);
target.bind_group = bind(device, &self.layout, &target.uniform, &target.texture, &self.sampler);
target.size = size;
target.levels = levels;
}
-
- fn ensure_tops(&mut self, device: &wgpu::Device, count: usize, size: (u32, u32)) {
- while self.tops.len() < count {
- let plane = plane(device, &self.layout, &self.sampler, size, 80, levels_for(size));
- self.tops.push(plane);
- }
- (0..self.tops.len()).for_each(|i| {
- if self.tops[i].size != size {
- self.resize(device, Which::Top(i), size);
- }
- });
- }
-
- fn pipeline_for(&self, mix: Mix) -> &wgpu::RenderPipeline {
- match mix {
- Mix::Over => &self.over,
- Mix::Multiply => &self.multiply,
- Mix::Screen => &self.screen,
- Mix::Add => &self.add,
- }
- }
-}
-
-#[derive(Clone, Copy)]
-enum Which {
- Canvas,
- Base,
- Top(usize),
- Lift,
}
type Upload = (usize, Vec<f16>);
@@ -395,42 +328,6 @@ fn upload_tiles(queue: &wgpu::Queue, plane: &Plane, cols: usize, tiles: &[Upload
});
}
-fn upload_image(queue: &wgpu::Queue, plane: &Plane, (width, height): (u32, u32), pixels: &[f16]) {
- queue.write_texture(
- wgpu::TexelCopyTextureInfo {
- texture: &plane.texture,
- mip_level: 0,
- origin: wgpu::Origin3d::ZERO,
- aspect: wgpu::TextureAspect::All,
- },
- bytemuck::cast_slice(pixels),
- wgpu::TexelCopyBufferLayout {
- offset: 0,
- bytes_per_row: Some(width * 8),
- rows_per_image: None,
- },
- wgpu::Extent3d {
- width,
- height,
- depth_or_array_layers: 1,
- },
- );
-}
-
-pub struct QuadDraw {
- pub uniform: [f32; 20],
- pub tiles: Mutex<Vec<(usize, Vec<f16>)>>,
- pub image: Mutex<Option<(u32, u32, Vec<f16>)>>,
-}
-
-pub fn quad_uniform(view: &[f32; 12], affine: [f32; 6], opacity: f32, rect: [f32; 4]) -> [f32; 20] {
- let [a, b, c, d, e, f] = affine;
- [
- view[0], view[1], view[2], view[3], view[4], view[5], view[6], view[7], a, b, c, d, e, f, opacity, 0.0,
- rect[0], rect[1], rect[2], rect[3],
- ]
-}
-
pub struct CanvasPaint {
pub uniform: [f32; 12],
pub uploads: Mutex<Vec<(usize, Vec<f16>)>>,
@@ -438,10 +335,6 @@ pub struct CanvasPaint {
pub cols: usize,
pub pending: Option<Instant>,
pub stats: Arc<Mutex<Stats>>,
- pub base: Mutex<Vec<(usize, Vec<f16>)>>,
- pub tops: Vec<(Mix, QuadDraw)>,
- pub lift: Option<QuadDraw>,
- pub lifting: bool,
pub show: Option<u64>,
pub frame_uploads: Mutex<Vec<FrameImage>>,
pub frame_drops: Vec<u64>,
@@ -460,34 +353,12 @@ impl egui_wgpu::CallbackTrait for CanvasPaint {
return Vec::new();
};
if gpu.canvas.size != self.size {
- gpu.resize(device, Which::Canvas, self.size);
- }
- if gpu.base.size != self.size {
- gpu.resize(device, Which::Base, self.size);
- }
- queue.write_buffer(&gpu.base.uniform, 0, bytemuck::cast_slice(&self.uniform));
- upload_tiles(queue, &gpu.base, self.cols, &std::mem::take(&mut *lock(&self.base)));
- if !self.tops.is_empty() {
- gpu.ensure_tops(device, self.tops.len(), self.size);
+ gpu.resize(device, self.size);
}
queue.write_buffer(&gpu.canvas.uniform, 0, bytemuck::cast_slice(&self.uniform));
let uploads = std::mem::take(&mut *lock(&self.uploads));
let start = Instant::now();
upload_tiles(queue, &gpu.canvas, self.cols, &uploads);
- self.tops.iter().enumerate().for_each(|(k, (_, top))| {
- let plane = &gpu.tops[k];
- queue.write_buffer(&plane.uniform, 0, bytemuck::cast_slice(&top.uniform));
- upload_tiles(queue, plane, self.cols, &std::mem::take(&mut *lock(&top.tiles)));
- });
- if let Some(lift) = &self.lift {
- if let Some((w, h, pixels)) = lock(&lift.image).take() {
- if gpu.lift.size != (w, h) {
- gpu.resize(device, Which::Lift, (w, h));
- }
- upload_image(queue, &gpu.lift, (w, h), &pixels);
- }
- queue.write_buffer(&gpu.lift.uniform, 0, bytemuck::cast_slice(&lift.uniform));
- }
self.frame_drops.iter().for_each(|key| {
gpu.frames.remove(key);
});
@@ -520,29 +391,9 @@ impl egui_wgpu::CallbackTrait for CanvasPaint {
return;
};
pass.set_pipeline(&gpu.canvas_pipeline);
- let cached = self.show.filter(|_| !self.lifting).and_then(|key| gpu.frames.get(&key));
- let under = match (self.lifting, cached) {
- (true, _) => &gpu.base,
- (false, Some(plane)) => plane,
- (false, None) => &gpu.canvas,
- };
+ let under = self.show.and_then(|key| gpu.frames.get(&key)).unwrap_or(&gpu.canvas);
pass.set_bind_group(0, &under.bind_group, &[]);
pass.draw(0..6, 0..1);
- if !self.lifting {
- return;
- }
- if self.lift.is_some() {
- pass.set_pipeline(&gpu.over);
- pass.set_bind_group(0, &gpu.lift.bind_group, &[]);
- pass.draw(0..6, 0..1);
- }
- self.tops.iter().enumerate().for_each(|(k, (mix, _))| {
- if let Some(plane) = gpu.tops.get(k) {
- pass.set_pipeline(gpu.pipeline_for(*mix));
- pass.set_bind_group(0, &plane.bind_group, &[]);
- pass.draw(0..6, 0..1);
- }
- });
}
}
diff --git a/crates/app/src/lib.rs b/crates/app/src/lib.rs
index 8a3507c..a062cf6 100644
--- a/crates/app/src/lib.rs
+++ b/crates/app/src/lib.rs
@@ -15,6 +15,7 @@ mod pen;
mod picker;
mod places;
mod planes;
+mod preview;
pub mod report;
mod settings;
mod start;
diff --git a/crates/app/src/lift.rs b/crates/app/src/lift.rs
index 6fe657e..404a6cc 100644
--- a/crates/app/src/lift.rs
+++ b/crates/app/src/lift.rs
@@ -1,49 +1,10 @@
-use anyhow::{Result, anyhow};
-use half::f16;
-use klad_brush::{BrushSet, CelReplay, Raster, TILE};
+use anyhow::Result;
+use klad_brush::Raster;
use klad_core::doc::{Node, Transform};
-use klad_core::markedit::union;
use klad_core::rng::{FNV_OFFSET, fnv};
-use klad_core::stroke::Mark;
-use klad_render::{Lifted, rasterize_nodes, rasterize_region, vector};
+use klad_render::{rasterize_nodes, vector};
use std::sync::mpsc::{Receiver, channel};
-pub struct Prepared {
- pub key: String,
- pub rev: u64,
- pub cel: String,
- pub layer: Vec<usize>,
- pub index: usize,
- pub nodes: Vec<Node>,
- pub lifted: Lifted,
- pub lower: Raster,
- pub upper: Raster,
-}
-
-pub enum Source {
- Node {
- index: usize,
- nodes: Vec<Node>,
- },
- Marks {
- ids: Vec<u32>,
- marks: Option<Vec<Mark>>,
- replay: Box<CelReplay>,
- raster: Raster,
- brushes: Box<BrushSet>,
- },
-}
-
-pub struct Job {
- pub key: String,
- pub rev: u64,
- pub cel: String,
- pub layer: Vec<usize>,
- pub source: Source,
- pub canvas: (u32, u32),
- pub scale: f32,
-}
-
fn spawn<T: Send + 'static>(
ctx: egui::Context,
work: impl FnOnce() -> Result<T> + Send + 'static,
@@ -56,85 +17,6 @@ fn spawn<T: Send + 'static>(
rx
}
-pub fn crop(raster: &Raster, [x, y, w, h]: [f32; 4], max_side: u32) -> Lifted {
- let (x0, y0) = (x.floor().max(0.0) as u32, y.floor().max(0.0) as u32);
- let x1 = ((x + w).ceil().max(0.0) as u32).min(raster.width).max(x0 + 1);
- let y1 = ((y + h).ceil().max(0.0) as u32).min(raster.height).max(y0 + 1);
- let step = (x1 - x0).max(y1 - y0).div_ceil(max_side).max(1);
- let (width, height) = ((x1 - x0).div_ceil(step), (y1 - y0).div_ceil(step));
- let pixel = |px: u32, py: u32| -> [f16; 4] {
- if px >= raster.width || py >= raster.height {
- return [f16::ZERO; 4];
- }
- let (px, py) = (px as usize, py as usize);
- raster.get(px / TILE, py / TILE).map_or([f16::ZERO; 4], |tile| {
- let at = ((py % TILE) * TILE + px % TILE) * 4;
- [tile[at], tile[at + 1], tile[at + 2], tile[at + 3]]
- })
- };
- let pixels = (0..height)
- .flat_map(|j| (0..width).map(move |i| (i, j)))
- .flat_map(|(i, j)| pixel(x0 + i * step, y0 + j * step))
- .collect();
- Lifted {
- rect: [x0 as f32, y0 as f32, (width * step) as f32, (height * step) as f32],
- width,
- height,
- pixels,
- }
-}
-
-pub fn prepare(job: Job, ctx: egui::Context) -> Receiver<Result<Prepared>> {
- spawn(ctx, move || {
- let (cw, ch) = job.canvas;
- let (index, nodes, lifted, lower, upper) = match job.source {
- Source::Node { index, nodes } => {
- let target = nodes
- .get(index)
- .ok_or_else(|| crate::report::bug("a dragged shape is not in its layer"))?;
- let [x, y, w, h] =
- vector::node_box(target)?.ok_or_else(|| anyhow!("{} has nothing to draw", job.key))?;
- let lifted = rasterize_region(
- std::slice::from_ref(target),
- [x - 2.0, y - 2.0, w + 4.0, h + 4.0],
- 4096,
- job.scale,
- )?;
- let lower = rasterize_nodes(&nodes[..index], cw, ch)?;
- let upper = rasterize_nodes(&nodes[index + 1..], cw, ch)?;
- (index, nodes, lifted, lower, upper)
- }
- Source::Marks {
- ids,
- marks,
- mut replay,
- mut raster,
- brushes,
- } => {
- let all = marks.unwrap_or_else(|| replay.marks().to_vec());
- let (chosen, rest): (Vec<Mark>, Vec<Mark>) = all.into_iter().partition(|m| ids.contains(&m.id()));
- let [x0, y0, x1, y1] = union(&chosen.iter().collect::<Vec<_>>())
- .ok_or_else(|| anyhow!("the selected strokes have nothing to draw"))?;
- let (_, alone, _) = CelReplay::replay(cw, ch, chosen, &brushes)?;
- let lifted = crop(&alone, [x0 - 2.0, y0 - 2.0, x1 - x0 + 4.0, y1 - y0 + 4.0], 4096);
- replay.update(&mut raster, rest, &brushes)?;
- (0, Vec::new(), lifted, raster, Raster::new(cw, ch))
- }
- };
- Ok(Prepared {
- key: job.key,
- rev: job.rev,
- cel: job.cel,
- layer: job.layer,
- index,
- nodes,
- lifted,
- lower,
- upper,
- })
- })
-}
-
pub fn render(nodes: Vec<Node>, canvas: (u32, u32), ctx: egui::Context) -> Receiver<Result<(u64, Raster)>> {
spawn(ctx, move || {
let hash = fnv(FNV_OFFSET, &serde_json::to_vec(&nodes)?);
@@ -142,19 +24,6 @@ pub fn render(nodes: Vec<Node>, canvas: (u32, u32), ctx: egui::Context) -> Recei
})
}
-pub fn finish(
- mut nodes: Vec<Node>,
- index: usize,
- transform: Transform,
- canvas: (u32, u32),
- ctx: egui::Context,
-) -> Receiver<Result<(u64, Raster)>> {
- if let Some(node) = nodes.get_mut(index) {
- node.transform = transform;
- }
- render(nodes, canvas, ctx)
-}
-
pub fn affine_apply(a: [f32; 6], (x, y): (f32, f32)) -> (f32, f32) {
(a[0] * x + a[1] * y + a[4], a[2] * x + a[3] * y + a[5])
}
@@ -198,20 +67,6 @@ mod tests {
use super::*;
use klad_core::doc::Shape;
- #[test]
- fn crops_copy_pixels_across_tiles_and_shrink_big_regions() {
- let mut raster = Raster::new(600, 300);
- let i = raster.index(1, 0);
- raster.ensure(i)[((10 * TILE) + 3) * 4 + 3] = f16::ONE;
- let lifted = crop(&raster, [250.0, 5.0, 20.0, 10.0], 4096);
- assert_eq!((lifted.width, lifted.height), (20, 10));
- assert_eq!(lifted.rect, [250.0, 5.0, 20.0, 10.0]);
- assert_eq!(lifted.pixels[(5 * 20 + 9) * 4 + 3], f16::ONE);
- let small = crop(&raster, [0.0, 0.0, 600.0, 300.0], 100);
- assert_eq!((small.width, small.height), (100, 50));
- assert_eq!(small.rect, [0.0, 0.0, 600.0, 300.0]);
- }
-
#[test]
fn stretching_a_square_shape_scales_its_own_axis_and_keeps_the_far_edge() {
let mut node = Node::new(
diff --git a/crates/app/src/preview.rs b/crates/app/src/preview.rs
new file mode 100644
index 0000000..d60437e
--- /dev/null
+++ b/crates/app/src/preview.rs
@@ -0,0 +1,145 @@
+use crate::composite::{compose_items, dilate, effect_reach};
+use anyhow::{Result, anyhow};
+use half::f16;
+use klad_brush::tiles::TILE_PX;
+use klad_brush::{BrushSet, CelReplay, Raster};
+use klad_core::bundle::Bundle;
+use klad_core::doc::{Kind, Layer, Node};
+use klad_core::ops::{Op, apply_all};
+use klad_render::onion::Onions;
+use klad_render::{Rasters, changed_tiles, rasterize_nodes, rasterize_tiles};
+use rayon::prelude::*;
+use std::collections::{BTreeMap, BTreeSet};
+use std::sync::Arc;
+
+pub struct Snapshot {
+ pub rev: u64,
+ pub bundle: Bundle,
+ pub frame: u32,
+ pub rasters: Rasters,
+ pub cels: BTreeMap<String, CelReplay>,
+ pub onions: Option<Onions>,
+ pub brushes: BrushSet,
+}
+
+pub struct Job {
+ pub ops: Vec<Op>,
+ pub snap: Arc<Snapshot>,
+ pub shown: BTreeSet<usize>,
+ pub visible: BTreeSet<usize>,
+}
+
+pub struct Done {
+ pub ops: Vec<Op>,
+ pub tiles: Vec<(usize, Vec<f16>)>,
+ pub changed: BTreeSet<usize>,
+ pub hidden: BTreeSet<usize>,
+ pub exact: bool,
+}
+
+fn vector_nodes(doc: &klad_core::doc::Document, frame: u32) -> BTreeMap<String, Vec<Node>> {
+ doc.all_layers()
+ .into_iter()
+ .filter(|l| l.kind() == Kind::Vector)
+ .filter_map(|l| l.content_at(frame))
+ .map(|c| (c.id.clone(), c.nodes.clone()))
+ .collect()
+}
+
+impl Job {
+ pub fn run(self) -> Result<Done> {
+ let snap = &self.snap;
+ let (doc, mut applied) = apply_all(&snap.bundle.doc, &self.ops)?;
+ let (w, h) = (doc.canvas.width, doc.canvas.height);
+ let mut rasters = snap.rasters.clone();
+ let mut changed = BTreeSet::new();
+ let before = vector_nodes(&snap.bundle.doc, snap.frame);
+ let redrawn = vector_nodes(&doc, snap.frame)
+ .into_iter()
+ .filter(|(cel, nodes)| before.get(cel) != Some(nodes))
+ .collect::<Vec<_>>()
+ .into_par_iter()
+ .map(|(cel, nodes)| {
+ let old = before.get(&cel);
+ let drawn = rasters.get(&cel);
+ let tiles = match (old, drawn) {
+ (Some(old), Some(_)) => changed_tiles(old, &nodes, w, h)?,
+ _ => None,
+ };
+ let raster = match (tiles, drawn) {
+ (Some(tiles), Some(drawn)) => {
+ let mut patched = drawn.clone();
+ rasterize_tiles(&nodes, w, h, &tiles)?
+ .into_iter()
+ .for_each(|(i, tile)| match tile {
+ Some(tile) => patched.put(i, tile.into_boxed_slice()),
+ None => patched.clear(i),
+ });
+ patched
+ }
+ _ => rasterize_nodes(&nodes, w, h)?,
+ };
+ let differs = match drawn {
+ Some(drawn) => drawn.differs(&raster),
+ None => raster.occupied().map(|(i, _)| i).collect(),
+ };
+ Ok((cel, raster, differs))
+ })
+ .collect::<Result<Vec<_>>>()?;
+ redrawn.into_iter().for_each(|(cel, raster, differs)| {
+ changed.extend(differs);
+ rasters.insert(cel, raster);
+ });
+ let plan = applied.marks.clone();
+ let exact = applied.marks.is_empty();
+ applied.marks.iter_mut().try_for_each(|pending| {
+ let replay = snap
+ .cels
+ .get(&pending.cel)
+ .ok_or_else(|| anyhow!("cel {} is not in memory", pending.cel))?;
+ let mut replay = replay.clone();
+ let mut marks = replay.marks().to_vec();
+ pending
+ .changes
+ .iter_mut()
+ .try_for_each(|change| snap.bundle.apply_change(&plan, &mut marks, change, &pending.cel))?;
+ let mut raster = rasters.get(&pending.cel).cloned().unwrap_or_else(|| Raster::new(w, h));
+ changed.extend(replay.update(&mut raster, marks, &snap.brushes)?.tiles);
+ rasters.insert(pending.cel.clone(), raster);
+ Ok::<_, anyhow::Error>(())
+ })?;
+ let cols = (w as usize).div_ceil(klad_brush::TILE);
+ let rows = (h as usize).div_ceil(klad_brush::TILE);
+ let reach = effect_reach(&doc, &doc.layers);
+ let changed: BTreeSet<usize> = dilate(&changed.into_iter().collect::<Vec<_>>(), reach, cols, rows)
+ .into_iter()
+ .collect();
+ let wanted: Vec<usize> = changed.union(&self.shown).copied().collect();
+ let (now, hidden): (Vec<usize>, Vec<usize>) = wanted.into_iter().partition(|i| self.visible.contains(i));
+ let layers: Vec<&Layer> = doc.layers.iter().collect();
+ let background = doc.canvas.background.as_deref();
+ let tiles = now
+ .par_iter()
+ .map(|&i| {
+ let tile = compose_items(
+ &doc,
+ snap.frame,
+ &rasters,
+ snap.onions.as_ref(),
+ &layers,
+ i,
+ background,
+ None,
+ )?;
+ Ok((i, tile.unwrap_or_else(|| vec![f16::ZERO; TILE_PX * 4])))
+ })
+ .collect::<Result<Vec<_>>>()?;
+ Ok(Done {
+ ops: self.ops,
+ tiles,
+ changed,
+ hidden: hidden.into_iter().collect(),
+ exact,
+ })
+ }
+}
diff --git a/crates/app/src/quad.wgsl b/crates/app/src/quad.wgsl
deleted file mode 100644
index 3840968..0000000
--- a/crates/app/src/quad.wgsl
+++ /dev/null
@@ -1,43 +0,0 @@
-struct Quad {
- view_a: vec4<f32>,
- view_b: vec4<f32>,
- drag_a: vec4<f32>,
- drag_b: vec4<f32>,
- rect: vec4<f32>,
-};
-
-@group(0) @binding(0) var<uniform> q: Quad;
-@group(0) @binding(1) var tex: texture_2d<f32>;
-@group(0) @binding(2) var samp: sampler;
-
-struct Out {
- @builtin(position) pos: vec4<f32>,
- @location(0) uv: vec2<f32>,
-};
-
-@vertex
-fn vs_main(@builtin(vertex_index) index: u32) -> Out {
- var corners = array<vec2<f32>, 6>(
- 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 p = q.rect.xy + uv * q.rect.zw;
- let d = vec2<f32>(
- q.drag_a.x * p.x + q.drag_a.y * p.y + q.drag_b.x,
- q.drag_a.z * p.x + q.drag_a.w * p.y + q.drag_b.y,
- );
- let px = vec2<f32>(
- q.view_a.x * d.x + q.view_a.y * d.y + q.view_b.x,
- q.view_a.z * d.x + q.view_a.w * d.y + q.view_b.y,
- );
- var out: Out;
- out.pos = vec4<f32>(px.x / q.view_b.z * 2.0 - 1.0, 1.0 - px.y / q.view_b.w * 2.0, 0.0, 1.0);
- out.uv = uv;
- return out;
-}
-
-@fragment
-fn fs_main(in: Out) -> @location(0) vec4<f32> {
- return textureSample(tex, samp, in.uv) * q.drag_b.z;
-}
diff --git a/docs/DESIGN.md b/docs/DESIGN.md
index 6e19a65..0744235 100644
--- a/docs/DESIGN.md
+++ b/docs/DESIGN.md
@@ -1,4 +1,4 @@
-_Last updated: 2026-11-07 10:23_
+_Last updated: 2026-11-07 13:30_
# klad: design
@@ -235,7 +235,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.
- **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; 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.
+- **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); 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.
- **Rays (M5).** A vector node `{"type": "rays", "x", "y", "angle", "spread", "count", "length", "start", "falloff", "noise", "seed"}` draws soft beams from an origin (a gap `start` px wide), each a quad with a radial falloff and its own length and strength from the seed; the node's `fill` colours them and its `blur` softens them. Rays come from the agent (`klad add rays`); in the editor a selected rays node shows its settings in layer settings.
- **Depth and atmosphere (M5).** A layer at the top of the stack (a plane, usually a group) may have a `depth` (0 is near; validation refuses it deeper in the tree). The document's `atmosphere` (`color`, an optional `top` colour blended down over the canvas height, `density`, `blur`, `desaturate`) turns each plane's depth into two effects after its own (`Document::effects_of`): a `haze` towards the fog of `1 - e^(-density x depth)` with `desaturate x depth` of its colour taken out, and a blur of `blur x depth` px. `haze` is an ordinary effect too. The depths are kept for M6's Parallax2D export; in the editor a depth field sits in each plane's row and layer settings, layer settings hold the atmosphere, and holding D shows the planes (each flattened alone, in the background) sliding by `offset x 0.08 / (1 + depth)` with the pointer.
@@ -435,7 +435,7 @@ Scripts are any language that prints edit ops as JSON lines into `klad apply`. G
- Canvas: pan, zoom, rotate; pen pressure, tilt and eraser end; 120 Hz on Apple Silicon. The window around the canvas is a neutral grey (`theme::SURROUND`), so colours read true.
- Layout (M4 batch 1): a tool strip on the left (the tools with their key letter, undo and redo, and at its foot the document and panels menus, the command palette, numbers and settings; the strip only has the height between the menu bar and the timeline, so when both groups do not fit its buttons shrink from 36 to 28 pt, then the foot folds into one menu pinned at the bottom, and last the tools scroll, never overlapping; each size is measured as it is drawn, so the choice does not flicker); a dock on the right holding panes (colour and brush, layers, layer settings (`Pane::Inspector` in code), notes for the agent, history), each with a title row that folds it, closes it and, dragged at its top edge, resizes the pane above; the timeline along the bottom, resizable and foldable to its toolbar; a status line under everything. Panes share the dock's height: they keep the sizes the user gave them, the last open one takes what is left, and when they do not fit they shrink towards their minimums and scroll inside (`layout::Layout::bodies`). Tab hides every panel but the status line, shift Tab the dock. Which panels are open, the dock's width, the timeline's height and each pane's size are kept in the user's settings (`layout`) and restored, clamped to the window. Pen calibration lives in the settings modal (cmd ,); the performance numbers in a numbers window that can stay open over the canvas.
- Commands (M4 batch 1): every editor action is a `Cmd` in one list (`commands.rs`): an id (`tool.brush`, `drawing.new`, kept in settings), a name in plain words, a Phosphor icon, a group, its keys or the hold that triggers it, whether a held key repeats it, and a line on what it does. Keys, the strip, panel buttons, the timeline's buttons and context menu, and the palette all run commands through `Editor::invoke`, which first asks `can_run` (a reason when it cannot, shown as a refusal) and remembers the last twelve run. A key matches only with exactly its modifiers (shift K is not K); key repeats run commands that repeat (`=`, `[`, cmd Z) and frame steps only once the frame on screen caught up. cmd K opens the palette: type to filter (name start, then a key, a word, a substring, the letters in order, the group; hyphens ignored, so "inb" finds in-between), arrows and Return run, rows grey out with the reason, recent commands first; `?` opens it too. Every control has a hover hint after 0.35 s (from its command where there is one) and is at least 24 pt high; a test walks every control of every panel and window to keep it so.
-- Tool options and selections (M4 batch 2): a bar over the canvas holds the active tool's settings (brush: picker, size, opacity, flow, and a "more" menu for hardness, lightest size, curve, taper, stabiliser and smoothing; fill: reference, gap, tolerance, grow, opacity; strokes: cut at the lasso edge, select all; points: corner, smooth, simplify, make it a path). The strip shows the eraser while the eraser brush or the pen's eraser end is on, and two colours (the current one over the second; X or a click swaps them; picking a colour from a swatch, the hex field or the eyedropper makes the old one the second). cmd alt drag sideways on the canvas sizes the brush (doubling every 120 pt), the circle staying where the drag began. H flips the view left-right (the view's mappings and the GPU matrix mirror; the document does not change); the status line's zoom takes a click for 100% and a double-click to fit, its rotation a click to turn upright. A selection bar sits under (or over) the selection's box: for strokes flips, quarter turns, recolour, thinner, thicker, opacity, copy, paste, duplicate in place, delete, deselect; for a shape flips (sx or sy negated and its rotation mirrored), quarter turns, fill with the colour and outline in the colour (rectangles, ellipses, paths and text: `fill`, or `stroke.paint`, or a new `stroke` at the pen's width when it had none; Edit > Shape; `klad set <id> fill=...` is the CLI form), duplicate in place (an `add` of the node without ids, above it), delete, deselect; for points corner, smooth, nudges, delete. Arrows nudge strokes, a shape or points by 1 px, 10 px with shift. Strokes select across layers (M5 batch 2 round 1): cmd or shift click on rows in the layers panel adds paint layers to the active one (marked with a blue edge); S then lassos, clicks and selects all on all of them, and the selection (one part per layer) moves, turns, scales, flips, recolours, cuts at the lasso edge, copies and deletes as one edit, each layer's marks staying on their layer. A selection on several layers drags as its outline (no GPU lift) and lands on release; copies of several layers paste back into their own layers, a copy of one layer into the active one. The strip's panels button lists the five panels and the timeline with a tick each, so a closed panel always has a way back. U draws rectangles and ellipses on a vector layer (shift for a square or circle, alt from the centre, rounded corners for rectangles; fill, outline and width shared with the pen, the fill in the first colour and the outline in the second, as for the pen's paths) as `rect` and `ellipse` nodes. Mirror painting (the brush bar's "mirror" and its axis) paints every stroke's mirror image as it is drawn, in a second stroke buffer landed after the first, and commits both as plain marks in one history step. Handles are drawn at 12 pt and hit within 12 pt (`grab`); shapes whose rotation is a quarter turn get edge handles too (`lift::stretched` scales their own axis). Pen events that arrive while a shape move or point edit is being written are held and replayed in order after it. The colour and brush pane shows the palette (swatches drag to reorder; the x in a hovered swatch's corner, or a right-click, removes it), recent colours, size presets and the brushes as tiles, each with a sample stroke drawn by `klad-brush` once per brush definition.
+- Tool options and selections (M4 batch 2): a bar over the canvas holds the active tool's settings (brush: picker, size, opacity, flow, and a "more" menu for hardness, lightest size, curve, taper, stabiliser and smoothing; fill: reference, gap, tolerance, grow, opacity; strokes: cut at the lasso edge, select all; points: corner, smooth, simplify, make it a path). The strip shows the eraser while the eraser brush or the pen's eraser end is on, and two colours (the current one over the second; X or a click swaps them; picking a colour from a swatch, the hex field or the eyedropper makes the old one the second). cmd alt drag sideways on the canvas sizes the brush (doubling every 120 pt), the circle staying where the drag began. H flips the view left-right (the view's mappings and the GPU matrix mirror; the document does not change); the status line's zoom takes a click for 100% and a double-click to fit, its rotation a click to turn upright. A selection bar sits under (or over) the selection's box: for strokes flips, quarter turns, recolour, thinner, thicker, opacity, copy, paste, duplicate in place, delete, deselect; for a shape flips (sx or sy negated and its rotation mirrored), quarter turns, fill with the colour and outline in the colour (rectangles, ellipses, paths and text: `fill`, or `stroke.paint`, or a new `stroke` at the pen's width when it had none; Edit > Shape; `klad set <id> fill=...` is the CLI form), duplicate in place (an `add` of the node without ids, above it), delete, deselect; for points corner, smooth, nudges, delete. Arrows nudge strokes, a shape or points by 1 px, 10 px with shift. Strokes select across layers (M5 batch 2 round 1): cmd or shift click on rows in the layers panel adds paint layers to the active one (marked with a blue edge); S then lassos, clicks and selects all on all of them, and the selection (one part per layer) moves, turns, scales, flips, recolours, cuts at the lasso edge, copies and deletes as one edit, each layer's marks staying on their layer. A selection on several layers moves as one edit, each layer previewed while it is dragged; copies of several layers paste back into their own layers, a copy of one layer into the active one. The strip's panels button lists the five panels and the timeline with a tick each, so a closed panel always has a way back. U draws rectangles and ellipses on a vector layer (shift for a square or circle, alt from the centre, rounded corners for rectangles; fill, outline and width shared with the pen, the fill in the first colour and the outline in the second, as for the pen's paths) as `rect` and `ellipse` nodes. Mirror painting (the brush bar's "mirror" and its axis) paints every stroke's mirror image as it is drawn, in a second stroke buffer landed after the first, and commits both as plain marks in one history step. Handles are drawn at 12 pt and hit within 12 pt (`grab`); shapes whose rotation is a quarter turn get edge handles too (`lift::stretched` scales their own axis). Pen events that arrive while a point edit is being written are held and replayed in order after it. The colour and brush pane shows the palette (swatches drag to reorder; the x in a hovered swatch's corner, or a right-click, removes it), recent colours, size presets and the brushes as tiles, each with a sample stroke drawn by `klad-brush` once per brush definition.
- First start (S8.7, `start.rs`, `editor/first.rs`, `klad_core::samples`): until the settings say `welcomed` (set when any drawing opens, or by "Not now"), the start window opens with a welcome offering first steps. First steps make `first steps.klad` (1280 by 800 on paper, one paint layer) in the drawings folder and open it with a small window of three steps that tick as they happen: a brush stroke is saved, a fill is saved, the request for an agent is copied (a sentence with the drawing's path asking the agent to read `klad skill`, render the drawing and add a shadow; "install the klad command" sits next to it). Help > First steps opens and closes the window on any drawing. The checklist is the editor's alone: it teaches the hands on the canvas, and an agent's first steps are `klad skill`. Revisit the third step when klad is an MCP server (S8.10). Under the recent drawings the start window shows the samples: the drawings `samples/shipped.json` names (name, bundle, a line on what it shows), each a card with its thumbnail and that line; a click copies it into the drawings folder without its `.cache` (`samples::copy`, `<name>.klad` or `<name> 2.klad`) and opens the copy, so a sample is never changed. `klad samples` lists the same set and `--copy <name> [--into folder]` copies one (default the current folder). Samples are found like the fonts: `KLAD_SAMPLES`, then `samples/` next to the binary, `../Resources/samples`, `../share/klad/samples`, and a source checkout's `samples/` up to five folders above the binary (where they exist after `just samples`; a sample not built is left out). `packaging/samples.sh` puts them in every build: it builds any that are missing with that build's `klad` (through the sample's `build.sh`, `PYTHON` naming the interpreter), copies them without caches, and renders each one's `<name>.thumb.png` next to it at 336 px, so the start window never renders into the app (a thumbnail outside the bundle is used as it is; only recent drawings' `.cache/thumb.png` are remade when the drawing changes). `app.sh` puts them in `Resources/samples`, `archive.sh` in the archive's `samples/` and the AppImage's `usr/share/klad/samples`; the six weigh about 4 MB.
- Messages and problem reports (S8.8, `report.rs`): a message says what happened and what to do next ("nothing to fill there: click inside closed lines, or raise the gap so small openings close"); a refusal names the step that makes the command possible. Errors that mean klad itself went wrong (an invariant broken, a picture missing that should be there) are `report::Bug`s: the editor says "something went wrong inside klad (what), everything up to your last edit is saved; Help > Report a problem copies what an issue needs" instead of the bare detail; a job whose CLI crashed reads the same, and a job that failed says "<job> did not finish: <the CLI's reason>". Every error message, job failure and crash of the editor or the CLI is appended to `klad.log` next to the settings (`KLAD_LOG` overrides it; past 512 KB the older half goes), one dated line each. Help > Report a problem opens a window with the report as it will be copied: klad's version and where it ran, the system (macOS version, the Linux distribution, Windows' version, and the processor), a place for what happened, the drawing's size, the last 40 messages and the last 40 lines of the log, with the home folder written as `~` and the drawing's folder as `<the drawing's folder>`. "include the drawing" zips the drawing without its cache next to it (`<name> for a report.zip`, stored entries, written by klad itself) and the report names the file to attach; "copy the report" copies it and "open klad's issues" opens GitHub. Nothing is sent by klad. `klad report [--drawing <bundle>]` prints the same report from the command line (version, system, log, the drawing zipped).
- Menus (S8.6, `commands::MENUS`, `menus.rs`): one list of menus holds every command but the holds (pan, zoom, the eyedropper, flipping, rolling, the parallax preview and sizing on the canvas, which are gestures), so the menus, the palette and the keys stay one list; a test fails when a command is in no menu or in two. The menus, in order: File (new, open, recent, close; import; export; the path and the command line tool), Edit (undo; copy, paste, duplicate, delete; selecting; Transform, Strokes and Points submenus), Tools (the tools, the brush, the colours), Layer (new, duplicate, rename, group, delete; show, lock, clip, lock alpha; Mask and Shape generators submenus, paint over; refill and gaps), Frame (stepping, drawings, holds and moves, inserting and removing frames), Animation (playback, onion skin, exposure, Selected frames and Clip submenus, the checks across frames), View (zoom, rotation, flip, the reference), Window (the panels, the message log, numbers) and Help. Each command has a short menu label (`Cmd::menu`: "Show", "Clip to layer below", "Export…"), since the menu says what it acts on, while the palette and hints keep the longer names; "…" marks a command that opens a window. Items show one key each (Backspace for delete); toggles show a tick, except commands that open a window; a command that cannot run now is greyed out (its reason is the palette's). A test keeps labels unique in each menu and under 30 characters. On macOS the list becomes the system menu bar (`menus::install`, rebuilt when the keys or the recent drawings change): an app menu with About, Settings, Services, hide and Quit, then the list, whose Window menu also gets the system's Minimize, Zoom and Bring all to front (it is the app's windows menu). Items target one Objective-C object (`KladMenuTarget`, `define_class!`) whose `kladRun:` queues the command for the next frame (the editor runs it through `Editor::invoke` as any key would) and whose `validateMenuItem:` reads a snapshot of what is off and on that the app refreshes every 0.4 s. The item keys are shown but not claimed: the object is each menu's delegate and answers no to `menuHasKeyEquivalent:forEvent:target:action:`, so a key still reaches the editor's own dispatch (which knows holds, repeats and text fields) and nothing runs twice; only the app menu's own keys (cmd , cmd Q cmd H) and Window's cmd M are AppKit's. On Windows and Linux (and in tests) the same list is an egui menu bar over the window, hidden with the panels (Tab). File > Open recent lists the last ten drawings; File > Close the drawing (cmd W, refused while a job runs) goes back to the start window, where only new, open, recent and quit run. Settings and Quit sit in the app menu on macOS and in Edit and File elsewhere; About (with the licences) is in Help everywhere and also in the macOS app menu.
@@ -443,7 +443,8 @@ Scripts are any language that prints edit ops as JSON lines into `klad apply`. G
- Tools: brush, eraser, smudge, fill (inside lines, gap closing), lasso select and transform, move/rotate/scale handles, path point editing, eyedropper.
- Stroke select (S, M2): a click picks the mark you see under the pointer. With "all layers" (the S and V options and Edit > Pick from all layers, `pickAllLayers` in the settings, on by default) that is on the topmost visible, unlocked paint layer that shows paint there, which becomes active: a layer shows paint where its raster's alpha, times its own and its groups' opacity, outside its mask and inside its clip base, passes 5%, and a layer whose pixels are not loaded counts by its marks' shapes (`Scene::seen_at`, `Scene::marks_at`); with "this layer" it is the active layer. In that layer the mark is the topmost one covering the point (inside a stroke's painted width or a fill's coverage, never an eraser stroke), and only when none covers it does one within 5 pt of the point count, so a thin line is still easy to take (`markedit::pick`); when no layer shows paint there, the topmost mark within those 5 pt on any of the layers is taken. A shift click adds or removes on the active layer, a dragged loop picks every stroke whose samples are all inside it and every fill whose pixels are, shift adds or toggles. With "a lasso cuts strokes at its edge" (on by default) the loop also takes the parts of strokes and fills crossing it: the selection shows the dashed lasso and the parts that will move, and the first edit (move, recolour, delete, ...) writes one `lasso` op that splits them, after which the selection is the moved marks. The selection shows as thin lines and a box with corner handles (uniform scale), edge handles (stretch one axis; dragging past the other edge flips) and a rotate knob; dragging moves it on the GPU (the selected marks drawn alone, over the cel replayed without them) and release writes one `transform` or `lasso` op. Layer settings recolour (the current colour), makes thinner or thicker, sets opacity, flips left-right or up-down and deletes, each as one history step. The selection is shared with the agent as addresses.
- Layers (M2 batch 4): layer settings sets clip to the layer below and lock alpha, adds a mask (empty, or hiding all), turns it on and off, removes it, and "paint on the mask" makes the mask the active layer (it also has its own row under its layer). Painting on a mask hides the layer under the strokes; the eraser shows it again. While a mask is active, what it hides is tinted red ("show the mask in red", on by default), and the brush panel says whether the brush or the eraser is on. The brush and fill tools record lock alpha from the active layer.
-- Live previews and clipping: the editor composes the active layer between cached images of everything below and above it only when that is exact (the active layer and the groups around it are not clipped, masked or a clip base); otherwise each dirty tile composes the whole stack. The GPU lift of a dragged shape or of selected strokes falls back to the outline (the result appears on release) when the dragged layer is clipped, masked or a clip base, when a group around it is, when a layer above it uses overlay, or when a lock-alpha mark lies at or after the first selected mark in its cel. Clip groups above the dragged layer stay live: they compose as one plane with the base's blend.
+- Live previews and clipping: the editor composes the active layer between cached images of everything below and above it only when that is exact (the active layer and the groups around it are not clipped, masked or a clip base); otherwise each dirty tile composes the whole stack. A drag (a shape with V, strokes with S or V, any grab: move, scale, turn, stretch, an alt-drag copy) previews the edit it will commit: at its first move the editor takes a snapshot of the document and the pixels (tiles are shared, so this is cheap), and while the pointer moves a background job applies the drag's ops in memory, redraws only the tiles they change (vector nodes through the tile patching below, strokes through the cel's replay) and composes those tiles through the whole stack, so clips, masks, blends, group effects and everything above the dragged thing stay exactly right. One job runs at a time and the newest pointer position wins; only tiles on screen are composed while dragging. The composed tiles go straight to the canvas plane, which is shown while a preview is up. On release the edit is written at once (it costs only its tiles), a last job composes the final position, and its tiles are taken as they are when the edit only moved vector nodes; tiles the preview touched that the edit did not are composed again. In a lean scene, while a mask is tinted, or before the canvas has caught up, a drag shows only its outline and lands on release.
+- Vector edits redraw only their tiles: a changed vector cel whose node order is kept is patched where its changed nodes were and are (their bounds grown for strokes, miter joins, blur and generator instances; added, removed and hidden nodes count), drawn on one surface that holds every node touching those tiles so no node is cut at a tile edge and the tiles are bit-identical to a full rasterization; a new order, or a node without bounds, redraws the cel. A swapped vector raster (an edit, undo or redo from the remembered rasters) dirties only the tiles whose pixels differ.
- Direct select (A, M2): click a path, rect or ellipse (inside groups too) to show its points; clicking the selected shape again steps down to the next shape under the pointer, and layer settings list them all; click or shift click points, drag on empty canvas for a box; drag points or handles; alt click the outline adds a point, alt click a point toggles corner and smooth, alt drag a handle breaks it; delete removes points; layer settings have corner, smooth, delete points, simplify and "make it a path". While dragging, the edited outline is drawn live; on release the edit is one `path` op whose layer is rendered in the background, then swapped in.
- Select and move (V, M4 test): a press picks what you see under the pen and drags it at once: the mark S would pick and the topmost vector shape there are compared by their layers' places in the stack and the higher one wins (clicking a shape again steps to the one under it); its layer becomes the active layer. With "this layer" only the active layer's marks or shapes are picked. A stroke picked this way is the same selection as S makes (its bar, layer settings, nudges, delete, copy), so V is the one tool for "move this". A press on empty canvas lassoes strokes on the active layer. Alt drag drags a copy: the copy is made (duplicate in place, one step) when the drag first moves, and the drag moves the copy (two history steps). A, the point editor, says so when a click lands on a brush stroke: strokes are samples, not paths.
- Pen (P, M4 test): draws vector paths on a vector layer: a click places a corner, a drag pulls out symmetric handles, a click on the first point closes the path, Return finishes it open, Esc drops it, and another tool finishes it. The path is one `add` node op into the layer at the current frame, in the current colour: closed paths are filled (unless "fill" is off) and outlined (unless "outline" is off), open ones always outlined, at the width in the options bar. On other layers it refuses and says why; the brush says so on a vector layer.
@@ -459,7 +460,7 @@ Scripts are any language that prints edit ops as JSON lines into `klad apply`. G
- Caches on disk for heavy documents (M4 test, round 2): three layers of cache, all automatic and all thrown away safely (`.cache/` is never in git).
- Pixels per drawing (`klad_brush::cache`, `.cache/tiles`): the replayed raster (zstd) and its edit record (each mark's key and the tiles it touches), keyed by the stroke file, the brushes, the canvas size and the engine version, shared by the CLI and the editor. A hit rebuilds the drawing's replay without painting anything (`CelReplay::with_marks`); a drawing whose file changed replays only its changed marks from the record. The CLI writes it after every load, as it always did; the editor writes it after a replay of 30 ms or more, so small drawings never touch the disk. 2 GB per bundle, least recently used out first.
- Frame pictures (`.cache/frames`, one file per frame cache key, zstd of the 8-bit picture at its display level, mips rebuilt on load): written after a picture that took 30 ms or more to make, read instead of loading a frame's drawings. The canvas job writes the picture of the frame it prepares (in the background pool, from the rasters it already holds), so on a heavy document every frame you stop on is seen at once next time. Heavy documents ask for a picture of a frame, and prefetch, only when it is on disk. 1 GB per bundle.
- - Lean scenes: in a heavy document, once the canvas job has made the caches below and above the active layer, the other layers' pixels on the current frame are dropped (their strokes stay, so V still picks them). A drawing counts as loaded only with its pixels, so pictures and canvas jobs reload what they need from the disk cache. Edits on the active drawing never need the others (the caches below and above stand); an edit that would (a change on another layer, a vector or onion change, a structure change, a clip that makes the stack slow) marks the canvas stale and the canvas job redoes it. The eyedropper samples what is on screen, a fill that references other layers loads them from the disk cache first, the GPU lift falls back to the outline drag, and the canvas job hands over thumbnails before the pixels go.
+ - Lean scenes: in a heavy document, once the canvas job has made the caches below and above the active layer, the other layers' pixels on the current frame are dropped (their strokes stay, so V still picks them). A drawing counts as loaded only with its pixels, so pictures and canvas jobs reload what they need from the disk cache. Edits on the active drawing never need the others (the caches below and above stand); an edit that would (a change on another layer, a vector or onion change, a structure change, a clip that makes the stack slow) marks the canvas stale and the canvas job redoes it. The eyedropper samples what is on screen, a fill that references other layers loads them from the disk cache first, a drag shows only its outline, and the canvas job hands over thumbnails before the pixels go.
- Buffered frames and prepare (round 3, `editor/buffer.rs`): a strip along the top of the ruler shows, per frame, green when its picture is buffered (in the frame cache or on disk: it shows at once) and blue under it when its drawings are cached (every paint drawing of the frame holds its pixels in memory or a current pixel cache on disk: drawing there starts within seconds). A background survey works it out (stat of each picture file, the first 8 bytes of each drawing's cache file against the key of its stroke file, stroke files hashed again only when their size or time changed) whenever the revision, display level, onion, frame cache, held drawings or a disk write changes. "Prepare frames" (the lightning in the timeline header, or cmd K) buffers the loop range, else the clip under the playhead, else every frame, one frame at a time on a background thread (frames sharing a picture once): it loads each drawing through the pixel cache (writing it), makes the picture at the current display level and writes it, skips what is already there, keeps nothing in memory, shows its progress next to the button and in the status line, and stops after the current frame when pressed again. The skipped frames count; the summary says how many pictures and drawings were made.
- Container numbers on `klad stress --frames 12` at 4096 px (30 layers of 300 strokes): a frame never seen is ready to draw on after 8.5 to 10 s (the replay, now also writing the caches); after reopening, a frame seen before is on screen in 12 to 45 ms and ready to draw on in about 3 s (30 drawings from the disk cache, then the caches below and above); drawings in memory 450 to 680 MB, down from 3.3 to 6 GB; UI frames while loading median 3.4 ms, p95 8 ms, slowest 62 to 88 ms.
- Clips (M3 batch 3): a strip above the frame numbers shows each clip as a bar (teal when it loops, amber when it plays once, with its name and its own fps), overlapping clips in lanes. Drag along empty strip to make a clip (named `clip1`, `clip2`, ..., looping, at the document's fps); click a bar to pick it; drag a bar's end to move that end. The row under the playback controls edits the picked clip, or the one under the playhead: name, loops, own fps, delete. Each change is one `clip` op and one history step. Clip edits change no pixels, so the frame cache keeps every picture.