From eb2ef3527913297eec211b52780e10ce6f0562d7 Mon Sep 17 00:00:00 2001 From: skylar taylor-barrick Date: Mon, 19 Oct 2026 13:58:58 -0600 Subject: [PATCH 1/2] fix(retouch): preserve Smudge pickup through live stroke release --- crates/engine/src/retouch_cmds.rs | 64 ++++++- crates/engine/tests/pr7281_adversarial.rs | 216 ++++++++++++++++++++++ crates/paint/src/retouch.rs | 8 +- crates/ui-egui/src/stroke_timing_tests.rs | 56 ++++++ 4 files changed, 333 insertions(+), 11 deletions(-) create mode 100644 crates/engine/tests/pr7281_adversarial.rs diff --git a/crates/engine/src/retouch_cmds.rs b/crates/engine/src/retouch_cmds.rs index fdbee1cb21e..1a2530d3d3f 100644 --- a/crates/engine/src/retouch_cmds.rs +++ b/crates/engine/src/retouch_cmds.rs @@ -911,6 +911,37 @@ enum DabTool { /// One dab's edit of the working copy. pub(crate) type DabEffect = Box; +/// Pixels an effect reads beyond the dab it writes. Smudge's pickup is a fixed-size square, +/// independent of pressure, roundness and the dab's current angle. +#[derive(Clone, Copy)] +enum DabNeighborhood { + Halo(i32), + Smudge(i32), +} + +impl DabNeighborhood { + fn halo(self) -> i32 { + match self { + Self::Halo(radius) | Self::Smudge(radius) => radius, + } + } + + fn read_rect(self, rect: Rect, dab: &photocraft_paint::Dab) -> Rect { + match self { + Self::Halo(radius) => rect.inflate(radius), + Self::Smudge(radius) => { + let (x, y) = (dab.center.x.floor() as i32, dab.center.y.floor() as i32); + rect.union(&Rect::new( + x.saturating_sub(radius), + y.saturating_sub(radius), + x.saturating_add(radius).saturating_add(1), + y.saturating_add(radius).saturating_add(1), + )) + } + } + } +} + impl DabTool { /// The tool for `cmd` and its history label. fn parse(s: &Session, cmd: &str, p: &Value, stroke: &Stroke) -> Result<(Self, &'static str)> { @@ -952,10 +983,11 @@ impl DabTool { } /// How far around each dab the effect reads (Blur and Sharpen read a neighbourhood). - fn halo(&self) -> i32 { + fn neighborhood(&self) -> DabNeighborhood { match self { - Self::Focus { sigma, .. } => (sigma * 3.0).ceil() as i32 + 1, - _ => 0, + Self::Focus { sigma, .. } => DabNeighborhood::Halo((sigma * 3.0).ceil() as i32 + 1), + Self::Smudge { max_size, .. } => DabNeighborhood::Smudge(Smudge::sampling_radius(*max_size)), + _ => DabNeighborhood::Halo(0), } } @@ -1020,7 +1052,7 @@ fn dab_cmd(s: &mut Session, p: &Value, cmd: &str) -> Result { let fmt = surf.format(); let mut effect = tool.effect(fmt, stroke.brush.spacing); let mut sampler = all.then(|| AllLayers::new(pre, fmt)); - Ok(apply_dab_stroke(surf, &stroke, sel, lock, tool.halo(), |work, fp| match &mut sampler { + Ok(apply_dab_stroke(surf, &stroke, sel, lock, tool.neighborhood().halo(), |work, fp| match &mut sampler { Some(all) => all.dab(work, fp, |w, f| effect(w, f)), None => effect(work, fp), })) @@ -1120,7 +1152,7 @@ pub struct LiveDab { renderer: photocraft_paint::StrokeRenderer, done: usize, effect: DabEffect, - halo: i32, + neighborhood: DabNeighborhood, pre_surf: Surface, work: WorkTiles, id: Option, @@ -1155,9 +1187,9 @@ impl LiveDab { } let (stroke, id) = parse_brush(s, p, cmd)?; let (tool, _) = DabTool::parse(s, cmd, p, &stroke)?; - let (halo, spacing, brush) = (tool.halo(), stroke.brush.spacing, Box::new(stroke.brush.clone())); + let (neighborhood, spacing, brush) = (tool.neighborhood(), stroke.brush.spacing, Box::new(stroke.brush.clone())); let effect = tool.clone(); - let mut live = Self::with_effect(s, cmd, p, stroke, id, halo, |pre| effect.effect(pre.format(), spacing))?; + let mut live = Self::with_neighborhood(s, cmd, p, stroke, id, neighborhood, |pre| effect.effect(pre.format(), spacing))?; live.tool = Some((tool, brush)); Ok(live) } @@ -1172,6 +1204,18 @@ impl LiveDab { id: Option, halo: i32, effect: impl FnOnce(&Surface) -> DabEffect, + ) -> Result { + Self::with_neighborhood(s, cmd, p, stroke, id, DabNeighborhood::Halo(halo), effect) + } + + fn with_neighborhood( + s: &Session, + cmd: &str, + p: &Value, + stroke: Stroke, + id: Option, + neighborhood: DabNeighborhood, + effect: impl FnOnce(&Surface) -> DabEffect, ) -> Result { let st = s.active().ok_or(EngineError::NoDocument)?; let base = (st.doc.id, st.revision); @@ -1188,7 +1232,7 @@ impl LiveDab { renderer, done: 0, effect, - halo, + neighborhood, work: WorkTiles::new(pre_surf.channels()), pre_surf, id, @@ -1230,7 +1274,7 @@ impl LiveDab { if r.is_empty() { continue; } - let mut region = self.work.read(&self.pre_surf, r.inflate(self.halo)); + let mut region = self.work.read(&self.pre_surf, self.neighborhood.read_rect(r, d)); (self.effect)(&mut region, &ctx.footprint(d, self.done + k)); self.work.write(&self.pre_surf, ®ion.crop(r)); dmg = dmg.union(&r); @@ -1262,7 +1306,7 @@ impl LiveDab { let ds = self.renderer.tail_dabs(); let r = ds.iter().fold(Rect::EMPTY, |a, d| a.union(&ctx.dab_rect(d, false))); if !r.is_empty() { - let mut region = self.work.read(&self.pre_surf, r.inflate(self.halo)); + let mut region = self.work.read(&self.pre_surf, r.inflate(self.neighborhood.halo())); for (k, d) in ds.iter().enumerate() { (self.effect)(&mut region, &ctx.footprint(d, self.done + k)); } diff --git a/crates/engine/tests/pr7281_adversarial.rs b/crates/engine/tests/pr7281_adversarial.rs new file mode 100644 index 00000000000..aae7e32b53c --- /dev/null +++ b/crates/engine/tests/pr7281_adversarial.rs @@ -0,0 +1,216 @@ +use photocraft_engine::{Session, retouch_cmds::LiveDab}; +use photocraft_paint::StrokePoint; +use serde_json::json; + +fn setup(depth: u32, mode: &str) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width":200,"height":120,"depth":depth,"mode":mode})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.edit("texture", |doc, active| { + let bounds = doc.bounds(); + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + let fmt = surf.format(); + let mut px = Vec::new(); + for y in 0..120 { + for x in 0..200 { + px.extend(photocraft_raster::from_rgba( + &fmt, + [((x * 7 + y * 3) % 31) as f32 / 31.0, x as f32 / 200.0, y as f32 / 120.0, 0.4 + ((x + y) % 7) as f32 / 12.0], + )); + } + } + surf.write_region(bounds, &px); + Ok(()) + }) + .unwrap(); + s +} + +fn pixels(s: &Session) -> Vec { + let st = s.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().read_region(st.doc.bounds()) +} + +#[test] +fn pressure_shape_and_smoothing_match_replay() { + let mut failures = Vec::new(); + for cmd in ["paint.smudge", "paint.blur", "paint.sharpen", "paint.dodge", "paint.burn", "paint.sponge"] { + for case in ["pressure", "locked", "ellipse", "smoothing", "scattering"] { + for depth in [8, 16, 32] { + let mut s = setup(depth, "rgb"); + match case { + "locked" => { + s.edit("lock alpha", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().locks.transparency = true; + Ok(()) + }) + .unwrap(); + } + "ellipse" => { + s.tools.brush.roundness = 0.2; + s.tools.brush.angle = 37.0; + } + "smoothing" => { + s.tools.brush.smoothing.amount = 0.6; + } + "scattering" => { + s.tools.brush.scattering.enabled = true; + s.tools.brush.scattering.scatter.jitter = 1.0; + } + _ => {} + } + let points = [[40.0, 40.0, 0.1], [65.0, 50.0, 0.4], [100.0, 60.0, 1.0], [140.0, 70.0, 0.7], [60.0, 40.0, 0.2]]; + let params = json!({"points":points,"size":40,"hardness":70,"strength":80,"opacity":55,"spacing":25}); + s.execute(cmd, params.clone()).unwrap(); + let want = pixels(&s); + s.execute("edit.undo", json!({})).unwrap(); + let mut start = params.clone(); + start["points"] = json!([points[0]]); + let mut live = LiveDab::begin(&s, cmd, &start).unwrap(); + for q in &points[1..] { + live.push(&[StrokePoint::new(q[0], q[1], q[2] as f32)]).unwrap(); + } + s.offer_live_dab(live).unwrap(); + let result = s.execute(cmd, params).unwrap(); + assert_eq!(result["fromLive"], true); + let got = pixels(&s); + let count = got.iter().zip(&want).filter(|(a, b)| a != b).count(); + let max = got.iter().zip(&want).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); + if count > 0 { + failures.push(format!("{cmd} {case} depth={depth}: {count} channels differ, max={max}")); + } + } + } + } + assert!(failures.is_empty(), "{}", failures.join("\n")); +} + +#[test] +fn native_modes_selection_and_lock_match_replay() { + for mode in ["rgb", "gray", "cmyk", "lab"] { + for depth in [8, 16, 32] { + let mut s = setup(depth, mode); + s.edit("lock alpha", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().locks.transparency = true; + Ok(()) + }) + .unwrap(); + s.execute("select.rect", json!({"x":30,"y":20,"width":110,"height":60})).unwrap(); + let points = [[-10.0, 30.0], [80.0, 50.0], [160.0, 80.0], [60.0, 60.0]]; + for cmd in ["paint.blur", "paint.sharpen", "paint.dodge", "paint.burn", "paint.sponge", "paint.smudge"] { + let params = json!({"points":points,"size":30,"hardness":40,"strength":70,"opacity":37}); + let expected_damage = s.execute(cmd, params.clone()).unwrap()["damage"].clone(); + let want = pixels(&s); + s.execute("edit.undo", json!({})).unwrap(); + let mut start = params.clone(); + start["points"] = json!([points[0]]); + let mut live = LiveDab::begin(&s, cmd, &start).unwrap(); + for q in &points[1..] { + live.push(&[StrokePoint::new(q[0], q[1], 1.0)]).unwrap(); + } + s.offer_live_dab(live).unwrap(); + let result = s.execute(cmd, params).unwrap(); + assert_eq!(result["fromLive"], true); + assert_eq!(result["damage"], expected_damage); + assert_eq!(pixels(&s), want, "{mode} {depth} {cmd}"); + s.execute("edit.undo", json!({})).unwrap(); + } + } + } +} + +#[test] +fn changed_document_refuses_live_pixels() { + let mut s = setup(8, "rgb"); + let p = json!({"points":[[40,40],[80,60]],"size":30}); + let live = LiveDab::begin(&s, "paint.blur", &p).unwrap(); + s.execute("paint.stroke", json!({"points":[[40,40],[80,60]],"color":"#ffffff","size":20})).unwrap(); + let mut replay = Session::new(); + replay.add_document((*s.active().unwrap().doc).clone(), None); + replay.tools.brush = s.tools.brush.clone(); + s.offer_live_dab(live).unwrap(); + assert!(s.execute("paint.blur", p.clone()).unwrap().get("fromLive").is_none()); + replay.execute("paint.blur", p).unwrap(); + assert_eq!(pixels(&s), pixels(&replay)); +} + +/// An independent paint-level oracle gives Smudge a generously padded working region. Pixels +/// picked up by the initial small dab must not depend on the final stroke's bounding rectangle. +#[test] +fn smudge_pickup_matches_full_neighborhood_when_pressure_expands() { + use photocraft_paint::{ + Stroke, + retouch::{Smudge, apply_dab_stroke}, + }; + + let points = [[40.0, 40.0, 0.1], [65.0, 50.0, 0.4], [100.0, 60.0, 1.0], [140.0, 70.0, 0.7], [60.0, 40.0, 0.2]]; + for depth in [8, 16, 32] { + let mut s = setup(depth, "rgb"); + let params = json!({"points":points,"size":40,"hardness":70,"strength":80,"opacity":55,"spacing":25}); + let (mut expected, lock) = { + let st = s.active().unwrap(); + let id = st.active_layer.unwrap(); + (st.doc.layer(id).unwrap().surface().unwrap().clone(), st.doc.effective_locks(id).transparency) + }; + let stroke = Stroke { + brush: photocraft_engine::retouch_cmds::stroke_brush(&s.tools.brush, ¶ms), + points: points.iter().map(|q| StrokePoint::new(q[0], q[1], q[2] as f32)).collect(), + }; + let mut effect = Smudge::new(0.8, None, 40.0).with_alpha(Some(3)); + apply_dab_stroke(&mut expected, &stroke, None, lock, 40, |work, fp| effect.dab(work, fp)); + let bounds = s.active().unwrap().doc.bounds(); + let want = expected.read_region(bounds); + s.execute("paint.smudge", params.clone()).unwrap(); + assert!(pixels(&s) == want, "command must read the whole pickup square at depth {depth}"); + s.execute("edit.undo", json!({})).unwrap(); + let live = LiveDab::begin(&s, "paint.smudge", ¶ms).unwrap(); + s.offer_live_dab(live).unwrap(); + assert_eq!(s.execute("paint.smudge", params).unwrap()["fromLive"], true); + assert!(pixels(&s) == want, "a single batch uses the same pickup square at depth {depth}"); + } +} + +#[test] +fn pressure_sized_live_dabs_commit_only_the_requested_mask_or_channel() { + use photocraft_raster::Surface; + + let fill = |surface: &mut Surface| { + let values: Vec = (0..120).flat_map(|y| (0..200).map(move |x| ((x * 7 + y * 3) % 31) as f32 / 31.0)).collect(); + surface.write_region(photocraft_geom::Rect::new(0, 0, 200, 120), &values); + }; + for depth in [8, 16, 32] { + let mut s = setup(depth, "rgb"); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + s.execute("channel.new", json!({"fill":"white"})).unwrap(); + s.execute("select.editInQuickMaskMode", json!({"on":true})).unwrap(); + s.edit("mask texture", |doc, active| { + fill(&mut doc.layer_mut(active.unwrap()).unwrap().mask.as_mut().unwrap().surface); + fill(&mut doc.channels[0].surface); + fill(&mut doc.quick_mask.as_mut().unwrap().surface); + Ok(()) + }) + .unwrap(); + let before = s.active().unwrap().doc.clone(); + for target in [json!("mask"), json!({"channel":0}), json!("quickMask")] { + for cmd in ["paint.smudge", "paint.blur", "paint.sharpen", "paint.dodge", "paint.burn", "paint.sponge"] { + let points = [[40.0, 40.0, 0.1], [65.0, 50.0, 0.4], [100.0, 60.0, 1.0], [140.0, 70.0, 0.7], [60.0, 40.0, 0.2]]; + let params = json!({"target":target,"points":points,"size":40,"hardness":70,"strength":80,"opacity":55,"spacing":25}); + s.execute(cmd, params.clone()).unwrap(); + let want = s.active().unwrap().doc.clone(); + s.execute("edit.undo", json!({})).unwrap(); + let mut start = params.clone(); + start["points"] = json!([points[0]]); + let mut live = LiveDab::begin(&s, cmd, &start).unwrap(); + for q in &points[1..] { + live.push(&[StrokePoint::new(q[0], q[1], q[2] as f32)]).unwrap(); + } + s.offer_live_dab(live).unwrap(); + assert_eq!(s.execute(cmd, params).unwrap()["fromLive"], true); + assert_eq!(s.active().unwrap().doc, want, "depth={depth} {cmd} target={target}"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc, before); + } + } + } +} diff --git a/crates/paint/src/retouch.rs b/crates/paint/src/retouch.rs index 16d52e1d5b8..06b4537ad46 100644 --- a/crates/paint/src/retouch.rs +++ b/crates/paint/src/retouch.rs @@ -319,8 +319,14 @@ pub struct Smudge { } impl Smudge { + /// Radius of the carried-colour buffer, including pixels outside a pressure-sized dab. + /// Both the first pickup and every subsequent pickup need this entire neighbourhood. + pub fn sampling_radius(max_brush_size: f32) -> i32 { + ((max_brush_size / 2.0).ceil() as i32).saturating_add(2) + } + pub fn new(strength: f32, finger: Option>, max_brush_size: f32) -> Self { - Self { strength: strength.clamp(0.0, 1.0), finger, radius: (max_brush_size / 2.0).ceil() as i32 + 2, alpha: None, carry: None } + Self { strength: strength.clamp(0.0, 1.0), finger, radius: Self::sampling_radius(max_brush_size), alpha: None, carry: None } } /// Mix in premultiplied space using alpha channel `a` (the format's [`alpha_index`]). diff --git a/crates/ui-egui/src/stroke_timing_tests.rs b/crates/ui-egui/src/stroke_timing_tests.rs index 93dd4665612..9949b03d2d6 100644 --- a/crates/ui-egui/src/stroke_timing_tests.rs +++ b/crates/ui-egui/src/stroke_timing_tests.rs @@ -467,3 +467,59 @@ fn releasing_a_sequential_dab_stroke_commits_what_a_replay_paints() { assert!(a.px.iter().zip(&b.px).all(|(x, y)| x == y), "{cmd}: live commit and replay differ"); } } + +/// Pressure changes Smudge's painted footprint, but not the square of colour it carries. +/// Exercise the actual pen → live preview → release handoff → journal replay, then undo/redo. +#[test] +fn pressure_sized_smudge_release_matches_replay_and_undo_redo() { + use crate::stylus::PenSample; + + let setup = |run: &mut dyn FnMut(&str, Value)| { + run("tools.setBrush", json!({"brush": {"size":40,"hardness":0.7,"pressureSize":true,"smoothing":{"amount":0.4}}})); + run("paint.stroke", json!({"points":[[10,20],[190,80]],"size":30,"color":"#2060c0"})); + }; + let mut h = harness(); + h.state_mut().ui.tool = Tool::Smudge; + h.run_steps(1); + setup(&mut |id, p| { + h.state_mut().run(id, p).unwrap(); + }); + let before = h.state().session.active().unwrap().doc.clone(); + h.state_mut().ui.tool_options.strength = 80.0; + h.run_steps(1); + let pen = |pressure| Some(PenSample { pressure, ..Default::default() }); + h.state().stylus.feed.set(pen(0.1)); + move_to(&mut h, 40.0, 30.0); + button(&mut h, 40.0, 30.0, true); + for (x, y, pressure) in [(65.0, 40.0, 0.4), (100.0, 55.0, 1.0), (140.0, 70.0, 0.7), (60.0, 40.0, 0.2)] { + h.state().stylus.feed.set(pen(pressure)); + move_to(&mut h, x, y); + } + assert!(h.state().live_stroke.is_some()); + button(&mut h, 60.0, 40.0, false); + h.run_steps(2); + assert!(h.state().retouch_from_live, "release must actually reuse the live pixels"); + let (_, params) = h.state().session.journal.iter().rev().find(|(id, _)| id == "paint.smudge").cloned().unwrap(); + let points = params["points"].as_array().unwrap(); + assert!(points.iter().any(|p| p[2].as_f64().unwrap() < 0.2)); + assert!(points.iter().any(|p| p[2].as_f64().unwrap() > 0.9)); + + let mut fresh = photocraft_engine::Session::new(); + fresh.execute("file.new", json!({"width":200,"height":100,"background":"white"})).unwrap(); + setup(&mut |id, p| { + fresh.execute(id, p).unwrap(); + }); + assert_eq!(h.state().session.tools.brush, fresh.tools.brush, "replay uses the Smudge tool's actual brush"); + assert!( + photocraft_compose::render(&before, before.bounds()).px == photocraft_compose::render(&fresh.active().unwrap().doc, before.bounds()).px, + "the replay fixture starts with identical pixels" + ); + assert!(fresh.execute("paint.smudge", params).unwrap().get("fromLive").is_none()); + let committed = h.state().session.active().unwrap().doc.clone(); + let expected = photocraft_compose::render(&fresh.active().unwrap().doc, committed.bounds()); + assert!(photocraft_compose::render(&committed, committed.bounds()).px == expected.px, "live commit and replay must paint identical pixels"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(h.state().session.active().unwrap().doc, before); + h.state_mut().run("edit.redo", json!({})).unwrap(); + assert_eq!(h.state().session.active().unwrap().doc, committed); +} From 389a1d5bd67072d5581c27989080222a7065b585 Mon Sep 17 00:00:00 2001 From: skylar taylor-barrick Date: Mon, 19 Oct 2026 14:03:11 -0600 Subject: [PATCH 2/2] test(retouch): name live dab replay regressions by behavior --- .../tests/{pr7281_adversarial.rs => live_dab_matches_replay.rs} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename crates/engine/tests/{pr7281_adversarial.rs => live_dab_matches_replay.rs} (100%) diff --git a/crates/engine/tests/pr7281_adversarial.rs b/crates/engine/tests/live_dab_matches_replay.rs similarity index 100% rename from crates/engine/tests/pr7281_adversarial.rs rename to crates/engine/tests/live_dab_matches_replay.rs