Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

fix(ui): brush and eraser show the real stroke while drawing (#64)

sommerper4f8da9365ab8
diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs
index b23658828..13457c363 100644
--- a/crates/compose/src/lib.rs
+++ b/crates/compose/src/lib.rs
@@ -290,25 +290,53 @@ pub fn thumbnail_buffer(doc: &Document, max_side: u32) -> Buffer {
/// The document's composite area-averaged (premultiplied) down to `w`×`h` (clamped to the
/// document size), rendered in bands so no full-size composite is held.
pub fn render_reduced(doc: &Document, w: u32, h: u32) -> Buffer {
- render_reduced_in_bands(doc, w, h, 0)
+ render_reduced_in_bands(doc, w, h, None, 0)
}
-/// [`render_reduced`] with an explicit band height (see [`render_bands`]).
-fn render_reduced_in_bands(doc: &Document, w: u32, h: u32, band_rows: i32) -> Buffer {
+/// The part of [`render_reduced`]`(doc, w, h)` that a change to `damage` (document pixels) can
+/// affect: the output pixels whose source areas meet it, rendered from just those areas, with the
+/// same values the whole reduction gives them. The buffer's rect is in output pixels (empty when
+/// `damage` misses the document), so a reduced canvas texture can update only what a stroke touched.
+pub fn render_reduced_damage(doc: &Document, w: u32, h: u32, damage: Rect) -> Buffer {
+ render_reduced_in_bands(doc, w, h, Some(damage), 0)
+}
+
+/// [`render_reduced`] (or, with `damage`, [`render_reduced_damage`]) with an explicit band height
+/// (see [`render_bands`]).
+fn render_reduced_in_bands(doc: &Document, w: u32, h: u32, damage: Option<Rect>, band_rows: i32) -> Buffer {
let b = doc.bounds();
let (fw, fh) = (b.width() as usize, b.height() as usize);
let (w, h) = (w.clamp(1, b.width().max(1)) as usize, h.clamp(1, b.height().max(1)) as usize);
- let rect = Rect::from_xywh(0, 0, w as u32, h as u32);
+ let full = Rect::from_xywh(0, 0, w as u32, h as u32);
if fw == 0 || fh == 0 {
- return Buffer::transparent(rect);
- }
- if (w, h) == (fw, fh) {
- let mut out = render(doc, b);
- out.rect = rect;
- return out;
+ return Buffer::transparent(if damage.is_some() { Rect::EMPTY } else { full });
}
// Output column / row of each document column / row: output pixel t covers [t·f/n, (t+1)·f/n).
let span = |t: usize, f: usize, n: usize| (t * f / n, ((t + 1) * f / n).max(t * f / n + 1).min(f));
+ // The output pixel whose span holds document column / row `x` (spans are contiguous: n <= f).
+ let cell = |x: usize, f: usize, n: usize| ((x + 1) * n).saturating_sub(1) / f;
+ // Output pixels to produce and the document area they cover.
+ let out = match damage {
+ None => full,
+ Some(d) => {
+ let d = d.intersect(&b);
+ if d.is_empty() {
+ return Buffer::transparent(Rect::EMPTY);
+ }
+ let (x0, x1) = ((d.x0 - b.x0) as usize, (d.x1 - b.x0) as usize);
+ let (y0, y1) = ((d.y0 - b.y0) as usize, (d.y1 - b.y0) as usize);
+ Rect::new(cell(x0, fw, w) as i32, cell(y0, fh, h) as i32, cell(x1 - 1, fw, w) as i32 + 1, cell(y1 - 1, fh, h) as i32 + 1)
+ }
+ };
+ let (ox0, oy0, ow, oh) = (out.x0 as usize, out.y0 as usize, out.width() as usize, out.height() as usize);
+ let (sx0, sx1) = (span(ox0, fw, w).0, span(ox0 + ow - 1, fw, w).1);
+ let (sy0, sy1) = (span(oy0, fh, h).0, span(oy0 + oh - 1, fh, h).1);
+ let src = Rect::new(b.x0 + sx0 as i32, b.y0 + sy0 as i32, b.x0 + sx1 as i32, b.y0 + sy1 as i32);
+ if (w, h) == (fw, fh) {
+ let mut px = render(doc, src);
+ px.rect = out;
+ return px;
+ }
let map = |f: usize, n: usize| {
let mut m = vec![0u32; f];
for t in 0..n {
@@ -318,17 +346,19 @@ fn render_reduced_in_bands(doc: &Document, w: u32, h: u32, band_rows: i32) -> Bu
m
};
let (cols, rows) = (map(fw, w), map(fh, h));
- let mut acc = vec![[0.0f32; 4]; w * h];
- let ok: Result<(), ()> = render_bands(doc, b, band_rows, |band| {
+ let cols = &cols[sx0..sx1];
+ let mut acc = vec![[0.0f32; 4]; ow * oh];
+ let ok: Result<(), ()> = render_bands(doc, src, band_rows, |band| {
let (by0, by1) = ((band.rect.y0 - b.y0) as usize, (band.rect.y1 - b.y0) as usize);
let (t0, t1) = (rows[by0] as usize, rows[by1 - 1] as usize + 1);
+ let sw = sx1 - sx0;
// Each output row sums its source rows in this band (in order, top to bottom).
let sum_row = |t: usize, out: &mut [[f32; 4]]| {
let (a, z) = span(t, fh, h);
for y in a.max(by0)..z.min(by1) {
- let src = &band.px[(y - by0) * fw..(y - by0 + 1) * fw];
- for (p, &c) in src.iter().zip(&cols) {
- let o = &mut out[c as usize];
+ let src = &band.px[(y - by0) * sw..(y - by0 + 1) * sw];
+ for (p, &c) in src.iter().zip(cols) {
+ let o = &mut out[c as usize - ox0];
for i in 0..3 {
o[i] += p[i] * p[3];
}
@@ -336,26 +366,26 @@ fn render_reduced_in_bands(doc: &Document, w: u32, h: u32, band_rows: i32) -> Bu
}
}
};
- let part = &mut acc[t0 * w..t1 * w];
+ let part = &mut acc[(t0 - oy0) * ow..(t1 - oy0) * ow];
#[cfg(not(target_arch = "wasm32"))]
{
use rayon::prelude::*;
- part.par_chunks_mut(w).enumerate().for_each(|(i, out)| sum_row(t0 + i, out));
+ part.par_chunks_mut(ow).enumerate().for_each(|(i, out)| sum_row(t0 + i, out));
}
#[cfg(target_arch = "wasm32")]
- for (i, out) in part.chunks_mut(w).enumerate() {
+ for (i, out) in part.chunks_mut(ow).enumerate() {
sum_row(t0 + i, out);
}
Ok(())
});
debug_assert!(ok.is_ok());
for (i, p) in acc.iter_mut().enumerate() {
- let ((x0, x1), (y0, y1)) = (span(i % w, fw, w), span(i / w, fh, h));
+ let ((x0, x1), (y0, y1)) = (span(ox0 + i % ow, fw, w), span(oy0 + i / ow, fh, h));
let n = ((y1 - y0) * (x1 - x0)).max(1) as f32;
let a = p[3];
*p = if a > 0.0 { [p[0] / a, p[1] / a, p[2] / a, a / n] } else { [0.0; 4] };
}
- Buffer { rect, px: acc }
+ Buffer { rect: out, px: acc }
}
/// Composite a sibling list (bottom→top) onto `backdrop`.
diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs
index 9aca7f013..e003e21ee 100644
--- a/crates/compose/src/tests.rs
+++ b/crates/compose/src/tests.rs
@@ -1096,7 +1096,7 @@ fn reference_reduce(doc: &Document, w: usize, h: usize) -> Vec<[f32; 4]> {
fn reduced_render_matches_the_full_composite_averaged() {
let d = tall_doc(53, 1000);
for (w, h, band) in [(10, 190, 0), (7, 33, 256), (53, 999, 512), (1, 1, 256)] {
- let got = render_reduced_in_bands(&d, w, h, band);
+ let got = render_reduced_in_bands(&d, w, h, None, band);
assert_eq!((got.rect.width(), got.rect.height()), (w, h));
assert_eq!(got.px, reference_reduce(&d, w as usize, h as usize), "{w}x{h} band {band}");
}
@@ -1106,6 +1106,37 @@ fn reduced_render_matches_the_full_composite_averaged() {
assert_eq!(render_reduced(&empty, 4, 4).px, vec![[0.0; 4]]);
}
+#[test]
+fn reduced_damage_matches_the_whole_reduction() {
+ // A reduced canvas texture updates only what a stroke touched: those pixels must equal the
+ // whole reduction's, for uneven factors, damage on span edges and bands smaller than the area.
+ let d = tall_doc(53, 1000);
+ for (w, h, band) in [(10, 190, 0), (7, 33, 256), (53, 999, 64), (53, 1000, 0), (1, 1, 256)] {
+ let all = render_reduced_in_bands(&d, w, h, None, band);
+ for dmg in [Rect::new(0, 0, 1, 1), Rect::new(5, 17, 6, 18), Rect::new(12, 300, 40, 701), Rect::new(-9, 990, 80, 2000), Rect::new(0, 0, 53, 1000)] {
+ let part = render_reduced_in_bands(&d, w, h, Some(dmg), band);
+ let r = part.rect;
+ assert!(!r.is_empty() && r.x0 >= 0 && r.y0 >= 0 && r.x1 as u32 <= w && r.y1 as u32 <= h, "{w}x{h} {dmg:?} -> {r:?}");
+ for y in r.y0..r.y1 {
+ for x in r.x0..r.x1 {
+ assert_eq!(part.get(x, y), all.get(x, y), "{w}x{h} band {band} {dmg:?} at {x},{y}");
+ }
+ }
+ // Exactly the output pixels whose source area meets the damage.
+ let span = |t: u32, f: u32, n: u32| (t * f / n, ((t + 1) * f / n).max(t * f / n + 1).min(f));
+ let d = dmg.intersect(&Rect::new(0, 0, 53, 1000));
+ for y in 0..h {
+ for x in 0..w {
+ let ((x0, x1), (y0, y1)) = (span(x, 53, w), span(y, 1000, h));
+ let meets = !Rect::new(x0 as i32, y0 as i32, x1 as i32, y1 as i32).intersect(&d).is_empty();
+ assert_eq!(r.contains(x as i32, y as i32), meets, "{w}x{h} {dmg:?} at {x},{y}");
+ }
+ }
+ }
+ assert!(render_reduced_in_bands(&d, w, h, Some(Rect::new(60, 0, 70, 10)), band).rect.is_empty());
+ }
+}
+
#[test]
fn large_documents_thumbnail_from_a_proxy() {
// 4200 × 4200 (17.6 MP) is above PROXY_THUMBNAIL_PIXELS: the proxy path must still give a
diff --git a/crates/engine/src/brush_cmds.rs b/crates/engine/src/brush_cmds.rs
index 11d387255..39629f1d7 100644
--- a/crates/engine/src/brush_cmds.rs
+++ b/crates/engine/src/brush_cmds.rs
@@ -10,7 +10,7 @@ use photocraft_doc::LayerContent;
use photocraft_geom::Rect;
use photocraft_paint::mixer::{MixerSettings, apply_mixer_stroke};
use photocraft_paint::replace::{Limits, ReplaceMode, ReplaceSettings, Sampling, apply_color_replacement};
-use photocraft_paint::{BrushPreset, BrushSettings, GrayTile, Stroke, StrokePoint, TipShape, render_stroke};
+use photocraft_paint::{BrushPreset, BrushSettings, GrayTile, Stroke, StrokePoint, StrokeRenderer, TipShape, render_stroke};
use photocraft_raster::Surface;
use serde_json::{Value, json};
@@ -154,25 +154,34 @@ fn damage_json(s: &mut Session, dmg: Rect) -> Value {
json!({ "damage": [dmg.x0, dmg.y0, dmg.width(), dmg.height()] })
}
-/// Stroke with a resolved brush onto the target layer (pixels or mask).
-fn stroke_with(s: &mut Session, p: &Value, label: &str, brush: BrushSettings, pts: Vec<StrokePoint>, auto_erase: bool) -> Result<Value> {
+/// The target layer (`None` for a channel), brush and zoom of a stroke. On a mask or channel the
+/// eraser paints the background colour (Photoshop).
+fn stroke_target(s: &Session, p: &Value, brush: BrushSettings) -> Result<(Option<photocraft_doc::LayerId>, BrushSettings, f32)> {
let gray = is_mask_target(p) || crate::channel_cmds::is_channel_target(p);
let id = if crate::channel_cmds::is_channel_target(p) { None } else { Some(layer_id(s, p)?) };
- let zoom = num(p, "zoom").unwrap_or(1.0);
+ let brush = if gray && brush.erase { BrushSettings { erase: false, color: s.tools.background, ..brush } } else { brush };
+ Ok((id, brush, num(p, "zoom").unwrap_or(1.0)))
+}
+
+/// Erasing a layer with locked transparency (e.g. the Background) can't remove opacity, so it
+/// paints the background colour instead (Photoshop).
+fn erase_locked(brush: &mut BrushSettings, lock: bool, bg: [f32; 4]) {
+ if brush.erase && lock {
+ brush.erase = false;
+ brush.color = bg;
+ }
+}
+
+/// Stroke with a resolved brush onto the target layer (pixels or mask).
+fn stroke_with(s: &mut Session, p: &Value, label: &str, brush: BrushSettings, pts: Vec<StrokePoint>, auto_erase: bool) -> Result<Value> {
let bg = s.tools.background;
let fg = brush.color;
- // On a mask or channel the eraser paints the background colour (Photoshop).
- let brush = if gray && brush.erase { BrushSettings { erase: false, color: bg, ..brush } } else { brush };
+ let (id, brush, zoom) = stroke_target(s, p, brush)?;
let dmg = s.edit(label, |doc, _| {
let sel = doc.selection.clone();
let (surf, lock) = crate::channel_cmds::target_surface(doc, id, p)?;
let mut brush = brush;
- // Erasing a layer with locked transparency (e.g. the Background) can't remove opacity, so
- // it paints the background colour instead (Photoshop). `gray` targets are handled above.
- if brush.erase && lock {
- brush.erase = false;
- brush.color = bg;
- }
+ erase_locked(&mut brush, lock, bg);
if auto_erase {
// Pencil Auto Erase: starting on foreground-coloured pixels paints the background colour.
let c = surf.rgba(pts[0].x.floor() as i32, pts[0].y.floor() as i32);
@@ -204,6 +213,54 @@ pub fn paint_stroke(s: &mut Session, p: &Value) -> Result<Value> {
stroke_with(s, p, label, brush, pts, false)
}
+/// A `paint.stroke` rendered while it is drawn, onto a copy of the active document, so the canvas
+/// shows the real dabs before the stroke commits. Committing the same params and points with
+/// `"seed": live.seed` gives the same pixels.
+pub struct LiveStroke {
+ /// The active document with the stroke so far.
+ pub doc: std::sync::Arc<photocraft_doc::Document>,
+ /// Jitter seed to pass to `paint.stroke`.
+ pub seed: u64,
+ renderer: StrokeRenderer,
+ pre: Surface,
+ sel: Option<Surface>,
+ lock: bool,
+ layer: Option<photocraft_doc::LayerId>,
+ params: Value,
+}
+
+impl LiveStroke {
+ /// Start from `paint.stroke` params; their `points` are rendered.
+ pub fn begin(s: &Session, p: &Value) -> Result<Self> {
+ has_paintable(s).map_err(EngineError::Other)?;
+ let pts = parse_points(p, "paint.stroke")?;
+ let brush = with_blend_mode(resolve_brush(s, p, "paint.stroke")?, p);
+ let seed = brush.seed;
+ let (layer, mut brush, zoom) = stroke_target(s, p, brush)?;
+ let mut doc = (*s.active().ok_or(EngineError::NoDocument)?.doc).clone();
+ let sel = doc.selection.clone();
+ let (surf, lock) = crate::channel_cmds::target_surface(&mut doc, layer, p)?;
+ erase_locked(&mut brush, lock, s.tools.background);
+ let renderer = StrokeRenderer::new(&brush, Some(surf.format()), zoom);
+ let pre = surf.clone();
+ let mut live = Self { doc: std::sync::Arc::new(doc), seed, renderer, pre, sel, lock, layer, params: p.clone() };
+ live.push(&pts)?;
+ Ok(live)
+ }
+
+ /// Everything the stroke has touched so far.
+ pub fn bounds(&self) -> Rect {
+ self.renderer.bounds()
+ }
+
+ /// Render more points; returns the rectangle that changed.
+ pub fn push(&mut self, pts: &[StrokePoint]) -> Result<Rect> {
+ self.renderer.push(pts);
+ let (surf, _) = crate::channel_cmds::target_surface(std::sync::Arc::make_mut(&mut self.doc), self.layer, &self.params)?;
+ Ok(self.renderer.composite(&self.pre, surf, self.sel.as_ref(), self.lock, false))
+ }
+}
+
fn pencil(s: &mut Session, p: &Value) -> Result<Value> {
let pts = parse_points(p, "paint.pencil")?;
let mut brush = with_blend_mode(resolve_brush(s, p, "paint.pencil")?, p);
diff --git a/crates/engine/src/brush_cmds/tests.rs b/crates/engine/src/brush_cmds/tests.rs
index d5e839db9..89c69cc8a 100644
--- a/crates/engine/src/brush_cmds/tests.rs
+++ b/crates/engine/src/brush_cmds/tests.rs
@@ -247,3 +247,28 @@ fn eraser_on_background_layer_paints_the_background_colour() {
let w = st.doc.layers[0].surface().unwrap().rgba(10, 2);
assert!(w[0] > 0.9 && w[1] > 0.9 && w[2] > 0.9, "untouched stays white: {w:?}");
}
+
+#[test]
+fn live_stroke_matches_the_committed_stroke() {
+ // The canvas previews strokes with `LiveStroke`; it must show what `paint.stroke` commits
+ // (soft edge, scatter seed), not a stand-in.
+ let mut s = session(200, 100);
+ let pts = [[10.0, 50.0, 1.0], [60.0, 30.0, 0.7], [120.0, 60.0, 0.9], [180.0, 40.0, 1.0]];
+ let p = json!({"points": [pts[0]], "preset": "Spatter", "brush": {"hardness": 0.0}, "smoothing": 0.0, "target": "pixels"});
+ let mut live = LiveStroke::begin(&s, &p).unwrap();
+ for c in pts[1..].chunks(2) {
+ let sp: Vec<StrokePoint> = c.iter().map(|q| StrokePoint::new(q[0], q[1], q[2] as f32)).collect();
+ assert!(!live.push(&sp).unwrap().is_empty());
+ }
+ let mut commit = p.clone();
+ commit["points"] = json!(pts);
+ commit["seed"] = json!(live.seed);
+ s.execute("paint.stroke", commit).unwrap();
+ let shown = live.doc.layer(s.active().unwrap().active_layer.unwrap()).unwrap().surface().unwrap().clone();
+ assert!(same_pixels(&shown, &surface(&s), Rect::new(0, 0, 200, 100)));
+ assert!((0..100).any(|y| (0..200).any(|x| (0.05..0.95).contains(&shown.rgba(x, y)[3]))), "soft edge previewed");
+ // Bad input is an error, not a panic.
+ assert!(LiveStroke::begin(&s, &json!({"points": []})).is_err());
+ assert!(LiveStroke::begin(&s, &json!({"points": [[1, 1]], "target": {"channel": 9}})).is_err());
+ assert!(LiveStroke::begin(&Session::new(), &json!({"points": [[1, 1]]})).is_err());
+}
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index 1c5b472fe..d0a150fd5 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -39,6 +39,77 @@ pub struct Drag {
pub modifiers: egui::Modifiers,
}
+/// A Brush/Eraser stroke shown while it is drawn: the engine renders the real dabs onto a copy of
+/// the document, and the canvas redraws only what each step changed.
+pub(crate) struct LiveStroke {
+ stroke: photocraft_engine::brush_cmds::LiveStroke,
+ doc: photocraft_doc::DocId,
+ revision: u64,
+ /// Preview key of the stroke; step `n` displays as `key + n`.
+ key: u64,
+ /// Damage of each step (step 0 = the document before the stroke).
+ damage: Vec<DRect>,
+ /// Drag points rendered so far.
+ fed: usize,
+}
+
+impl LiveStroke {
+ fn display_key(&self) -> u64 {
+ self.key + self.damage.len() as u64
+ }
+
+ /// What changed since the canvas showed preview `key` (0 = the document before the stroke).
+ fn since(&self, key: u64) -> Option<DRect> {
+ let seen = if key == 0 { 0 } else { usize::try_from(key.checked_sub(self.key)?).ok()? };
+ Some(self.damage.get(seen..)?.iter().fold(DRect::EMPTY, |a, r| a.union(r)))
+ }
+}
+
+/// The live stroke on document `idx`, while it is current.
+fn live_stroke(app: &PhotocraftApp, idx: usize) -> Option<&LiveStroke> {
+ let st = app.session.documents().get(idx)?;
+ app.live_stroke.as_ref().filter(|l| app.drag.is_some() && l.doc == st.doc.id && l.revision == st.revision)
+}
+
+/// `paint.stroke` params for a Brush/Eraser drag (shared by the live preview and the commit).
+fn stroke_params(app: &PhotocraftApp, tool: Tool, points: &[Vec<f64>]) -> serde_json::Value {
+ json!({ "points": points, "erase": tool == Tool::Eraser, "smoothing": 0.3, "target": paint_target(app) })
+}
+
+fn begin_live_stroke(app: &PhotocraftApp, tool: Tool) -> Option<LiveStroke> {
+ static STROKES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
+ let st = app.session.active()?;
+ let d = app.drag.as_ref()?;
+ let stroke = photocraft_engine::brush_cmds::LiveStroke::begin(&app.session, &stroke_params(app, tool, &app.stylus.stroke_points(&d.points))).ok()?;
+ let n = STROKES.fetch_add(1, std::sync::atomic::Ordering::Relaxed) & 0xff_ffff;
+ let damage = vec![stroke.bounds()];
+ Some(LiveStroke { stroke, doc: st.doc.id, revision: st.revision, key: (1 << 44) | (n << 20), damage, fed: d.points.len() })
+}
+
+/// Render the drag points the live stroke hasn't seen yet, with the pen pressure, tilt and
+/// rotation the commit's `paint.stroke` gets for them.
+fn feed_live_stroke(app: &mut PhotocraftApp) {
+ let (Some(l), Some(d)) = (app.live_stroke.as_mut(), app.drag.as_ref()) else { return };
+ let pose = &app.stylus.stroke;
+ let pts: Vec<_> = (l.fed..d.points.len())
+ .filter_map(|i| {
+ let p = d.points.get(i)?;
+ let t = pose.get(i).or(pose.last()).copied().unwrap_or_default();
+ let mut sp = photocraft_engine::paint::StrokePoint::new(p[0], p[1], p[2] as f32);
+ (sp.tilt_x, sp.tilt_y, sp.rotation) = (t[0], t[1], t[2]);
+ Some(sp)
+ })
+ .collect();
+ if pts.is_empty() {
+ return;
+ }
+ l.fed = d.points.len();
+ match l.stroke.push(&pts) {
+ Ok(r) => l.damage.push(r),
+ Err(_) => app.live_stroke = None,
+ }
+}
+
/// Abstract tool event, produced by the mouse or by automation (`ui.pointer`).
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ToolEvent {
@@ -145,6 +216,9 @@ fn display_doc(app: &mut PhotocraftApp, idx: usize) -> (std::sync::Arc<Document>
if let Some(shown) = crate::distort_ui::display_doc(app, idx) {
return shown;
}
+ if let Some(l) = live_stroke(app, idx) {
+ return (l.stroke.doc.clone(), l.display_key());
+ }
if let (Some(t), Some(pv)) = (&app.ui.transform, &app.transform_preview)
&& app.session.active_index() == Some(idx)
&& st.doc.layer(photocraft_doc::LayerId(t.layer)).is_some()
@@ -231,6 +305,8 @@ pub fn ensure_texture(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize)
};
let (doc, preview_key) = display_doc(app, idx);
let (display, display_key) = canvas_display(app, &doc);
+ let seen = app.canvases.get(&id).map(|c| (c.tex_revision, c.tex_preview_key));
+ let damage = seen.and_then(|seen| damage_since(app, idx, seen, (revision, preview_key), display_key, last_damage));
let preview_key = preview_key ^ display_key;
let cache = app.canvases.entry(id).or_insert(CanvasCache {
revision: 0,
@@ -242,27 +318,24 @@ pub fn ensure_texture(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize)
tex_preview_key: 0,
});
if cache.tex_revision != revision || cache.texture.is_none() || cache.tex_preview_key != preview_key {
- let partial = cache.texture.is_some()
- && cache.tex_preview_key == preview_key
- && cache.tex_revision + 1 == revision
- && cache.scale == 1.0
- && last_damage.is_some();
let t0 = crate::gpu_canvas::now_ms();
- if partial {
- let r = last_damage.unwrap_or(DRect::EMPTY).intersect(&doc.bounds());
+ let longest = doc.size.width.max(doc.size.height);
+ let factor = longest.div_ceil(MAX_TEXTURE).max(1);
+ let (w, h) = ((doc.size.width / factor).max(1), (doc.size.height / factor).max(1));
+ let current = cache.texture.as_mut().filter(|t| t.size() == [w as usize, h as usize]);
+ if let (Some(d), Some(t)) = (damage, current) {
+ // Only what the edit or stroke touched: the reduced texture's pixels over it, with the
+ // values the whole reduction gives them (factor 1 is the plain composite of `d`).
+ let buf = photocraft_compose::render_reduced_damage(&doc, w, h, d);
+ let r = buf.rect;
if !r.is_empty() {
- let buf = photocraft_compose::render(&doc, r);
let t1 = crate::gpu_canvas::now_ms();
- if let Some(t) = cache.texture.as_mut() {
- t.set_partial([r.x0 as usize, r.y0 as usize], display_image(display.as_deref(), &buf), TextureOptions::LINEAR);
- }
- app.perf.record("rect", r.width() as u64 * r.height() as u64, t1 - t0, crate::gpu_canvas::now_ms() - t1);
+ t.set_partial([r.x0 as usize, r.y0 as usize], display_image(display.as_deref(), &buf), TextureOptions::LINEAR);
+ let px = (r.width() as u64 * r.height() as u64).saturating_mul(u64::from(factor).pow(2));
+ app.perf.record("rect", px, t1 - t0, crate::gpu_canvas::now_ms() - t1);
}
} else {
- let longest = doc.size.width.max(doc.size.height);
- let factor = longest.div_ceil(MAX_TEXTURE).max(1);
// Reduced in bands straight from the compositor: no full-size composite in memory.
- let (w, h) = ((doc.size.width / factor).max(1), (doc.size.height / factor).max(1));
let full = photocraft_compose::render_reduced(&doc, w, h);
let t1 = crate::gpu_canvas::now_ms();
let (img, scale) = (display_image(display.as_deref(), &full), 1.0 / factor as f32);
@@ -279,6 +352,18 @@ pub fn ensure_texture(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize)
Some((cache.texture.as_ref()?.id(), cache.scale))
}
+/// What changed since a canvas cache showed (`revision`, `preview key`) `seen`, when only a
+/// rectangle did: the last edit's damage, or the live stroke's dabs since then. Cached keys have
+/// the colour display's key folded in (`^ display_key`); `now`'s is still raw.
+fn damage_since(app: &PhotocraftApp, idx: usize, seen: (u64, u64), now: (u64, u64), display_key: u64, last_damage: Option<DRect>) -> Option<DRect> {
+ if seen.1 == now.1 ^ display_key && seen.0 + 1 == now.0 {
+ return last_damage;
+ }
+ let l = live_stroke(app, idx).filter(|l| seen.0 == now.0 && l.display_key() == now.1)?;
+ let r = l.since(seen.1 ^ display_key)?;
+ Some(if r.is_empty() { r } else { r.inflate(effect_reach(&l.stroke.doc.layers)) })
+}
+
/// How far beyond an edit's damage rect the composite can change: layer effects (shadows, glows,
/// strokes, …) on the edited layer and on the groups around it reach that far.
fn effect_reach(layers: &[photocraft_doc::Layer]) -> i32 {
@@ -312,6 +397,8 @@ fn ensure_gpu(app: &mut PhotocraftApp, idx: usize) -> bool {
};
let (doc, preview_key) = display_doc(app, idx);
let (display, display_key) = canvas_display(app, &doc);
+ let seen = app.canvases.get(&id).map(|c| (c.revision, c.preview_key));
+ let damage = seen.and_then(|seen| damage_since(app, idx, seen, (revision, preview_key), display_key, last_damage));
let preview_key = preview_key ^ display_key;
let size = [doc.size.width, doc.size.height];
let cache = app.canvases.entry(id).or_insert(CanvasCache {
@@ -327,8 +414,8 @@ fn ensure_gpu(app: &mut PhotocraftApp, idx: usize) -> bool {
if present && cache.revision == revision && cache.preview_key == preview_key {
return true;
}
- let partial = present && cache.preview_key == preview_key && cache.revision + 1 == revision && last_damage.is_some();
- let r = gpu.refresh(id.0, &doc, if partial { last_damage } else { None }, display.as_deref());
+ let partial = present && damage.is_some();
+ let r = gpu.refresh(id.0, &doc, if partial { damage } else { None }, display.as_deref());
if let Some(e) = &r.fallback
&& app.perf.gpu_fallback.as_deref() != Some(e.as_str())
{
@@ -1235,17 +1322,8 @@ fn draw_drag_preview(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXfor
last = crop_end(app, d.start, last);
}
match d.tool {
- Tool::Brush | Tool::Eraser => {
- let c = if d.tool == Tool::Eraser { [1.0, 1.0, 1.0, 0.6] } else { app.session.tools.foreground };
- let color = Color32::from_rgba_unmultiplied((c[0] * 255.0) as u8, (c[1] * 255.0) as u8, (c[2] * 255.0) as u8, (c[3] * 255.0) as u8);
- let pts: Vec<Pos2> = d.points.iter().map(|p| xf.to_screen(p[0] as f32, p[1] as f32)).collect();
- let w = (app.session.tools.brush.size * xf.zoom).max(1.0);
- if pts.len() == 1 {
- painter.circle_filled(pts[0], w / 2.0, color);
- } else {
- painter.add(egui::Shape::line(pts, Stroke::new(w, color)));
- }
- }
+ // The canvas shows the live stroke itself (`LiveStroke`).
+ Tool::Brush | Tool::Eraser => {}
t if t.is_brushlike() || t == Tool::QuickSelection => {
// Retouching strokes preview as a translucent trail of the brush footprint.
let pts: Vec<Pos2> = d.points.iter().map(|p| xf.to_screen(p[0] as f32, p[1] as f32)).collect();
@@ -1416,6 +1494,7 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers)
}
app.drag = Some(Drag { tool, start: [x, y], points: vec![[x, y, pressure as f64]], modifiers: mods });
app.stylus.begin_stroke();
+ app.live_stroke = if matches!(tool, Tool::Brush | Tool::Eraser) { begin_live_stroke(app, tool) } else { None };
}
ToolEvent::Move { x, y, pressure } => {
if tool == Tool::Type && app.drag.is_none() {
@@ -1430,6 +1509,7 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers)
d.points.push([x, y, pressure as f64]);
app.stylus.record_point();
}
+ feed_live_stroke(app);
}
ToolEvent::Up { x, y } => {
if tool == Tool::Type
@@ -1461,8 +1541,27 @@ fn finish_gesture(app: &mut PhotocraftApp, d: Drag) {
Tool::PathSelection => crate::vector_ui::path_selection_finish(app, d.start, [end[0], end[1]]),
Tool::Type => crate::type_tool::pointer_up(app, d.start, [end[0], end[1]]),
Tool::Brush | Tool::Eraser => {
- let pts = app.stylus.stroke_points(&d.points);
- let _ = app.run("paint.stroke", json!({ "points": pts, "erase": d.tool == Tool::Eraser, "smoothing": 0.3, "target": paint_target(app) }));
+ let live = app.live_stroke.take();
+ let mut p = stroke_params(app, d.tool, &app.stylus.stroke_points(&d.points));
+ if let Some(l) = &live {
+ p["seed"] = json!(l.stroke.seed);
+ }
+ // The canvas already shows the stroke: let the commit's damage rect refresh it rather
+ // than recompositing the whole document.
+ if app.run("paint.stroke", p).is_ok()
+ && let Some(l) = live
+ {
+ let display_key = app.session.active().map_or(0, |st| canvas_display(app, &st.doc).1);
+ if let Some(c) = app.canvases.get_mut(&l.doc) {
+ // Raw preview key 0 = the document itself (its colour display folded in).
+ if l.since(c.preview_key ^ display_key).is_some() {
+ c.preview_key = display_key;
+ }
+ if l.since(c.tex_preview_key ^ display_key).is_some() {
+ c.tex_preview_key = display_key;
+ }
+ }
+ }
}
Tool::RectMarquee | Tool::EllipseMarquee => {
let o = &app.ui.tool_options;
@@ -1640,6 +1739,67 @@ mod tests {
}
}
+ #[test]
+ fn brush_drag_shows_the_real_stroke_and_commits_it() {
+ // The drag used to draw a hard, flat stand-in and only showed the soft brush on release.
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
+ app.run("file.new", json!({"width": 120, "height": 60, "background": "transparent"})).unwrap();
+ app.run("tools.setBrush", json!({"brush": {"size": 20, "hardness": 0.0}})).unwrap();
+ app.ui.tool = Tool::Brush;
+ let m = egui::Modifiers::NONE;
+ let alpha = |d: &Document, x, y| d.layers[0].surface().unwrap().rgba(x, y)[3];
+ let rev = app.session.documents()[0].revision;
+ tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 30.0, pressure: 1.0 }, m);
+ for x in [40.0, 70.0, 100.0] {
+ tool_event(&mut app, ToolEvent::Move { x, y: 30.0, pressure: 1.0 }, m);
+ }
+ let (shown, key) = display_doc(&mut app, 0);
+ assert_ne!(key, 0);
+ assert!(alpha(&shown, 40, 30) > 0.5 && (0.01..0.5).contains(&alpha(&shown, 40, 38)), "soft stroke while drawing");
+ assert_eq!(alpha(&app.session.documents()[0].doc, 40, 30), 0.0, "not committed yet");
+ // The canvas redraws only what the stroke touched.
+ let dk = canvas_display(&app, &app.session.documents()[0].doc).1;
+ let d = damage_since(&app, 0, (rev, dk), (rev, key), dk, None).unwrap();
+ assert!(d.contains(40, 30) && !d.contains(40, 2) && d.width() < 120, "{d:?}");
+ tool_event(&mut app, ToolEvent::Up { x: 100.0, y: 30.0 }, m);
+ let doc = app.session.documents()[0].doc.clone();
+ assert!(app.live_stroke.is_none() && display_doc(&mut app, 0).1 == 0);
+ assert_eq!((alpha(&doc, 40, 30), alpha(&doc, 40, 38)), (alpha(&shown, 40, 30), alpha(&shown, 40, 38)), "commit matches the preview");
+ }
+
+ #[test]
+ fn live_stroke_uses_pen_tilt_and_updates_a_reduced_texture_partially() {
+ // Pen tilt drives the size; the preview must use the tilt the commit gets. The document
+ // is wider than MAX_TEXTURE, so the CPU texture is reduced (factor 2) and each step
+ // must update only the reduced pixels it touched.
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
+ let ctx = egui::Context::default();
+ app.run("file.new", json!({"width": 4097, "height": 90, "background": "transparent"})).unwrap();
+ let tilt = json!({"size": 30, "hardness": 1.0, "spacing": 0.05, "shapeDynamics": {"enabled": true, "size": {"control": "penTilt"}}});
+ app.run("tools.setBrush", json!({ "brush": tilt })).unwrap();
+ app.ui.tool = Tool::Brush;
+ assert_eq!(ensure_texture(&mut app, &ctx, 0).map(|t| t.1), Some(0.5));
+ let m = egui::Modifiers::NONE;
+ app.stylus.feed.set(Some(crate::stylus::PenSample { pressure: 1.0, tilt_x: 60.0, tilt_y: 0.0, rotation: 0.0 }));
+ tool_event(&mut app, ToolEvent::Down { x: 100.0, y: 45.0, pressure: 1.0 }, m);
+ for x in [300.0, 600.0, 900.0] {
+ tool_event(&mut app, ToolEvent::Move { x, y: 45.0, pressure: 1.0 }, m);
+ ensure_texture(&mut app, &ctx, 0);
+ assert_eq!(app.perf.last_refresh, "rect");
+ assert!(app.perf.last_refresh_px < 4097 * 90 / 4, "{}", app.perf.last_refresh_px);
+ }
+ let shown = display_doc(&mut app, 0).0;
+ tool_event(&mut app, ToolEvent::Up { x: 900.0, y: 45.0 }, m);
+ ensure_texture(&mut app, &ctx, 0);
+ assert_eq!(app.perf.last_refresh, "rect", "the commit refreshes only the stroke");
+ let doc = app.session.documents()[0].doc.clone();
+ let (a, b) = (doc.layers[0].surface().unwrap(), shown.layers[0].surface().unwrap());
+ // 60° tilt shrinks the dab well below 30 px: the preview shows that size, as committed.
+ assert!(a.rgba(500, 45)[3] > 0.5 && a.rgba(500, 45 + 12)[3] == 0.0);
+ // (The smoothed tail catches up to the end point only when the stroke finishes.)
+ assert!((0..90).all(|y| (0..700).all(|x| a.rgba(x, y) == b.rgba(x, y))), "commit matches the preview");
+ }
+
#[test]
fn layer_style_dialog_previews_live_and_cancel_restores() {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 3b7e21670..ad2c0f9fe 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -182,6 +182,8 @@ pub struct PhotocraftApp {
canvases: HashMap<DocId, canvas::CanvasCache>,
checker: Option<egui::TextureHandle>,
drag: Option<canvas::Drag>,
+ /// Brush/Eraser stroke being drawn, rendered by the engine (see `canvas::LiveStroke`).
+ live_stroke: Option<canvas::LiveStroke>,
control_rx: Option<Receiver<ControlRequest>>,
pending_screenshots: Vec<(u64, Option<String>, Sender<ControlResponse>)>,
/// Screenshots not yet requested from the viewport: (token, earliest time in ms, frames seen).
@@ -272,6 +274,7 @@ impl PhotocraftApp {
canvases: HashMap::new(),
checker: None,
drag: None,
+ live_stroke: None,
control_rx: None,
pending_screenshots: Vec::new(),
queued_screenshots: Vec::new(),