Skip to content

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

Retouch: admit the rendered stroke extent, not an estimate (#4961, #6110)

Muhammad Saada4cdc63d88ee
diff --git a/crates/engine/src/retouch_cmds.rs b/crates/engine/src/retouch_cmds.rs
index b462d3751..8ef8722c1 100644
--- a/crates/engine/src/retouch_cmds.rs
+++ b/crates/engine/src/retouch_cmds.rs
@@ -15,7 +15,7 @@ use photocraft_algo::retouch::{ToneRange, dodge_burn, local_blur, local_sharpen,
use photocraft_color::{BlendMode, PixelFormat, SampleType};
use photocraft_doc::{Document, LayerContent, LayerId};
use photocraft_geom::Rect;
-use photocraft_paint::retouch::{Footprint, Region, Smudge, alpha_index, apply_coverage, apply_dab_stroke, stroke_coverage};
+use photocraft_paint::retouch::{Footprint, Region, Smudge, alpha_index, apply_coverage, apply_dab_stroke};
use photocraft_paint::{BrushSettings, Stroke, StrokePoint};
use photocraft_raster::{Surface, from_rgba_into, to_rgba};
use serde_json::{Value, json};
@@ -43,7 +43,16 @@ const MAX_STROKE_PIXELS: u64 = 67_108_864;
/// Refuse a stroke whose footprint would not fit the coverage budget, from the points and brush
/// size alone, before the renderer allocates anything for it.
fn reject_huge_stroke(cmd: &str, stroke: &Stroke) -> Result<()> {
- let pad = f64::from(stroke.brush.size.max(1.0)).mul_add(0.5, 4.0);
+ // Dynamics place dabs beyond the input points, so half the tip is not the whole reach:
+ // Scattering offsets a centre by up to its amount times the tip size, and a Dual Brush dab
+ // reaches its own radius further. Pad by what those can add so this estimate does not fall
+ // short of what the renderer will cover. It is only the cheap early-out; the rendered extent
+ // is admitted for real in `coverage` below.
+ let b = &stroke.brush;
+ let size = f64::from(b.size.max(1.0));
+ let scatter = if b.scattering.enabled { size * f64::from(b.scattering.scatter.jitter.max(0.0)) } else { 0.0 };
+ let dual = if b.dual_brush.enabled { f64::from(b.dual_brush.size.max(0.0)) * 0.5 } else { 0.0 };
+ let pad = size.mul_add(0.5, 4.0) + scatter + dual;
let mut min_x = f64::INFINITY;
let mut min_y = f64::INFINITY;
let mut max_x = f64::NEG_INFINITY;
@@ -69,16 +78,19 @@ fn reject_huge_stroke(cmd: &str, stroke: &Stroke) -> Result<()> {
Ok(())
}
-fn reject_bounds(cmd: &str, bounds: Rect) -> Result<()> {
- if bounds.is_empty() {
- return Ok(());
- }
- let (w, h) = (u64::from(bounds.width()), u64::from(bounds.height()));
- let area = w.saturating_mul(h);
- if area > MAX_STROKE_PIXELS {
- return Err(bad(cmd, format!("stroke too large ({w}×{h} px, at most {MAX_STROKE_PIXELS})")));
- }
- Ok(())
+/// The stroke's coverage, with the **rendered** extent admitted before the dense buffer exists.
+///
+/// `reject_huge_stroke` estimates from the input points; this is the real bound. Rendering is
+/// tiled, so it holds only the tiles the dabs touch; the extent is read from those tiles once
+/// every dab is placed (tips, dynamics and scattering included) and checked against `max`, and
+/// only a stroke that fits is made dense. `max` is a parameter so tests can inject a small budget.
+fn coverage_within(cmd: &str, stroke: &Stroke, max: u64) -> Result<(Rect, Vec<f32>)> {
+ photocraft_paint::retouch::stroke_coverage_within(stroke, max).ok_or_else(|| bad(cmd, format!("stroke too large (at most {max} px)")))
+}
+
+/// [`coverage_within`] at the shared allowance.
+fn coverage(cmd: &str, stroke: &Stroke) -> Result<(Rect, Vec<f32>)> {
+ coverage_within(cmd, stroke, MAX_STROKE_PIXELS)
}
/// A pixel layer, a layer with a mask, or a targeted alpha channel / Quick Mask (as the Brush).
@@ -383,8 +395,7 @@ fn clone_stamp(s: &mut Session, p: &Value) -> Result<Value> {
return periodic::Composite { target: surf, before: &before, tile: pre.bounds(), opacity: stroke.brush.opacity, selection: sel, lock, mode }
.draw(bounds, &stroke.brush, &stroke.points, |r| clone_sample(pre, id, &before, which, r, &map, true, CMD));
}
- let (bounds, cov) = stroke_coverage(&stroke);
- reject_bounds(CMD, bounds)?;
+ let (bounds, cov) = coverage(CMD, &stroke)?;
// Samples come from the pre-stroke state, so pixels painted earlier in the stroke are never re-cloned.
let paint = clone_sample(pre, id, surf, which, bounds, &map, flag(p, "wrap", false), CMD)?;
Ok(apply_coverage(surf, bounds, &cov, stroke.brush.opacity, sel, lock, &paint, mode))
@@ -647,8 +658,7 @@ fn healing_brush(s: &mut Session, p: &Value) -> Result<Value> {
let map = clone_mapping(s, p, &stroke, CMD)?;
let off = map.offset();
let dmg = run_stroke(s, "Healing Brush", id, p, |pre, surf, sel, lock| {
- let (bounds, cov) = stroke_coverage(&stroke);
- reject_bounds(CMD, bounds)?;
+ let (bounds, cov) = coverage(CMD, &stroke)?;
let (g, cov) = pad_coverage(bounds, &cov, 2);
let fmt = surf.format();
let src = clone_sample(pre, id, surf, which, g, &map, false, CMD)?;
@@ -695,8 +705,7 @@ fn history_brush(s: &mut Session, p: &Value) -> Result<Value> {
}
let fmt = surf.format();
let src = if src_surface.format() == fmt { src_surface } else { src_surface.convert(fmt) };
- let (bounds, cov) = stroke_coverage(&stroke);
- reject_bounds(CMD, bounds)?;
+ let (bounds, cov) = coverage(CMD, &stroke)?;
let paint = Region::read(&src, bounds);
Ok(apply_coverage(surf, bounds, &cov, stroke.brush.opacity, sel, lock, &paint, mode))
})?;
@@ -773,12 +782,12 @@ enum SpotType {
/// Photoshop 25.4 (measured): a dab changes exactly the brush's footprint, and Content-Aware takes
/// its texture from around it, as Edit › Fill does from its window
/// ([`crate::fill_cmds::sampling_window`] of the stroke's bounds), which is what this samples.
-fn spot_heal_surface(surf: &mut Surface, pre: &Document, stroke: &Stroke, kind: SpotType, all: bool, sel: Option<&Surface>, lock: bool) -> Rect {
- let (bounds, cov) = stroke_coverage(stroke);
+fn spot_heal_surface(surf: &mut Surface, pre: &Document, stroke: &Stroke, kind: SpotType, all: bool, sel: Option<&Surface>, lock: bool) -> Result<Rect> {
+ let (bounds, cov) = coverage("paint.spotHealing", stroke)?;
let size = stroke.brush.size;
let region_rect = crate::fill_cmds::sampling_window(bounds, pre.bounds());
if region_rect.is_empty() {
- return Rect::EMPTY;
+ return Ok(Rect::EMPTY);
}
// Proximity Match looks for its source anywhere in that window.
let margin = (region_rect.width().max(region_rect.height()) / 2) as i32;
@@ -795,7 +804,7 @@ fn spot_heal_surface(surf: &mut Surface, pre: &Document, stroke: &Stroke, kind:
}
let hole: Vec<bool> = stroke_cov.iter().map(|c| *c > 0.0).collect();
if !hole.iter().any(|h| *h) {
- return Rect::EMPTY;
+ return Ok(Rect::EMPTY);
}
// Synthesise over a slightly larger domain than the Poisson region, so the solve's boundary pixels
// carry synthesised values that differ from the untouched surroundings: that mismatch is what the
@@ -819,7 +828,7 @@ fn spot_heal_surface(surf: &mut Surface, pre: &Document, stroke: &Stroke, kind:
let healed = heal_region(&fmt, &src, &img, &heal_mask);
let dmg = bounds.intersect(&region_rect);
let dmg_cov: Vec<f32> = (dmg.y0..dmg.y1).flat_map(|y| (dmg.x0..dmg.x1).map(move |x| (x, y))).map(|(x, y)| stroke_cov[img.index(x, y)]).collect();
- apply_coverage(surf, dmg, &dmg_cov, stroke.brush.opacity, sel, lock, &healed, BlendMode::Normal)
+ Ok(apply_coverage(surf, dmg, &dmg_cov, stroke.brush.opacity, sel, lock, &healed, BlendMode::Normal))
}
fn spot_healing(s: &mut Session, p: &Value) -> Result<Value> {
@@ -833,7 +842,7 @@ fn spot_healing(s: &mut Session, p: &Value) -> Result<Value> {
o => return Err(bad(CMD, format!("unknown type `{o}` (contentAware|createTexture|proximityMatch)"))),
};
let all = sample_all_layers(p);
- let dmg = run_stroke(s, "Spot Healing Brush", id, p, |pre, surf, sel, lock| Ok(spot_heal_surface(surf, pre, &stroke, kind, all, sel, lock)))?;
+ let dmg = run_stroke(s, "Spot Healing Brush", id, p, |pre, surf, sel, lock| spot_heal_surface(surf, pre, &stroke, kind, all, sel, lock))?;
Ok(json!({ "damage": damage_json(dmg) }))
}
diff --git a/crates/engine/src/retouch_cmds/pattern_stamp.rs b/crates/engine/src/retouch_cmds/pattern_stamp.rs
index 3c90c6d2a..b4b71745a 100644
--- a/crates/engine/src/retouch_cmds/pattern_stamp.rs
+++ b/crates/engine/src/retouch_cmds/pattern_stamp.rs
@@ -8,12 +8,12 @@ use photocraft_color::{BlendMode, PixelFormat};
use photocraft_compose::pattern::{Placement, Tile, render};
use photocraft_doc::Pattern;
use photocraft_geom::Rect;
-use photocraft_paint::retouch::{Footprint, Region, apply_coverage, apply_dab_stroke, over_native, stroke_coverage};
+use photocraft_paint::retouch::{Footprint, Region, apply_coverage, apply_dab_stroke, over_native};
use photocraft_paint::{Stroke, StrokePoint};
use photocraft_raster::{Surface, from_rgba_into, to_rgba};
use serde_json::{Value, json};
-use super::{bad, blend_param, damage_json, flag, has_pixel_layer, parse_brush, reject_bounds, reject_huge_stroke};
+use super::{bad, blend_param, damage_json, flag, has_pixel_layer, parse_brush, reject_huge_stroke};
use crate::{Result, Session};
const STREAM_PHASE_X: u64 = 101;
@@ -150,8 +150,7 @@ fn paint_aligned(
mode: BlendMode,
cmd: &str,
) -> Result<Rect> {
- let (bounds, cov) = stroke_coverage(stroke);
- reject_bounds(cmd, bounds)?;
+ let (bounds, cov) = super::coverage(cmd, stroke)?;
if bounds.is_empty() {
return Ok(Rect::EMPTY);
}
@@ -259,9 +258,9 @@ mod tests {
#[test]
fn a_diagonal_across_a_24_mp_canvas_is_not_too_large() {
- assert!(reject_huge_stroke("t", &stroke(&[(0.0, 0.0), (6015.0, 3999.0)], 100.0)).is_ok());
- assert!(reject_bounds("t", Rect::from_xywh(-60, -60, 6136, 4120)).is_ok());
+ let across = stroke(&[(0.0, 0.0), (6015.0, 3999.0)], 100.0);
+ assert!(reject_huge_stroke("t", &across).is_ok());
+ assert!(super::super::coverage("t", &across).is_ok(), "the rendered extent fits too");
assert!(reject_huge_stroke("t", &stroke(&[(0.0, 0.0), (9000.0, 9000.0)], 100.0)).is_err());
- assert!(reject_bounds("t", Rect::from_xywh(0, 0, 9000, 9000)).is_err());
}
}
diff --git a/crates/engine/src/retouch_cmds/remove.rs b/crates/engine/src/retouch_cmds/remove.rs
index 55c53d3af..d298e8f02 100644
--- a/crates/engine/src/retouch_cmds/remove.rs
+++ b/crates/engine/src/retouch_cmds/remove.rs
@@ -117,12 +117,12 @@ fn plan(s: &Session, p: &Value) -> Result<Plan> {
/// The hole over the plan's window: the strokes' footprints, their enclosed areas and a margin,
/// limited to the selection. Empty when nothing would change.
-fn hole(plan: &Plan, sel: Option<&Surface>) -> Vec<bool> {
+fn hole(plan: &Plan, sel: Option<&Surface>) -> Result<Vec<bool>> {
let win = plan.window;
let (w, h) = (win.width() as usize, win.height() as usize);
let mut m = vec![false; w * h];
for stroke in &plan.strokes {
- let (bounds, cov) = stroke_coverage(stroke);
+ let (bounds, cov) = super::coverage(CMD, stroke)?;
let bw = bounds.width() as usize;
for (i, c) in cov.iter().enumerate() {
let (x, y) = (bounds.x0 + (i % bw.max(1)) as i32, bounds.y0 + (i / bw.max(1)) as i32);
@@ -143,13 +143,13 @@ fn hole(plan: &Plan, sel: Option<&Surface>) -> Vec<bool> {
*v &= c > 0.0;
}
}
- m
+ Ok(m)
}
/// The filled window and the hole it fills, computed on `doc` (a snapshot). `None` when the
/// layer's own window is fully transparent: nothing to remove and nothing to fill from.
fn run_remove(doc: &mut Document, plan: &Plan, p: &Value, ctx: &crate::jobs::JobCtx, label: &str) -> Result<Option<(Region, Vec<bool>)>> {
- let hole = hole(plan, doc.selection.as_ref());
+ let hole = hole(plan, doc.selection.as_ref())?;
if !hole.iter().any(|m| *m) {
return Err(bad(CMD, "the stroke doesn't cover anything that can change (check the selection)"));
}
diff --git a/crates/engine/src/retouch_cmds/tests.rs b/crates/engine/src/retouch_cmds/tests.rs
index 35f6e81ef..edbf33c31 100644
--- a/crates/engine/src/retouch_cmds/tests.rs
+++ b/crates/engine/src/retouch_cmds/tests.rs
@@ -566,23 +566,24 @@ fn history_brush_refuses_a_stroke_too_large_to_render() {
}
/// #6110: Pattern Stamp already refused a stroke it could not render; every other retouch stroke
-/// reached the same dense conversion unguarded. Each command refuses the oversized stroke and
-/// leaves the pixels alone, and a stroke across the whole canvas still works.
+/// reached the same dense conversion unguarded. Each command refuses the oversized stroke without
+/// touching the pixels or the history, and an ordinary stroke still succeeds.
#[test]
fn every_retouch_stroke_refuses_a_box_it_cannot_render() {
let huge = json!([[0, 0], [900_000, 900_000]]);
- let ok = json!([[0, 0], [40, 20]]);
- let cases: [(&str, Value); 5] = [
+ let ok = json!([[2, 2], [30, 16]]);
+ // Fixtures that are valid for a plain RGB document with one pixel layer.
+ let cases: [(&str, Value); 4] = [
("paint.cloneStamp", json!({"offset": [4, 0], "size": 8, "hardness": 100})),
("paint.healingBrush", json!({"offset": [4, 0], "size": 8, "hardness": 100})),
("paint.spotHealing", json!({"size": 8, "hardness": 100})),
("paint.historyBrush", json!({"size": 8, "hardness": 100})),
- ("paint.patternStamp", json!({"size": 8, "hardness": 100})),
];
for (cmd, base) in cases {
let mut s = session(40, 20, 8, "rgb");
s.execute("paint.stroke", json!({"points": [[0, 10], [40, 10]], "size": 12, "hardness": 1.0, "color": "#ff0000"})).unwrap();
let before = rgba(&s, 20, 10);
+ let steps = s.active().unwrap().history.past_len();
let with = |points: &Value| {
let mut v = base.clone();
if let Some(o) = v.as_object_mut() {
@@ -593,9 +594,11 @@ fn every_retouch_stroke_refuses_a_box_it_cannot_render() {
let err = s.execute(cmd, with(&huge)).unwrap_err().to_string();
assert!(err.contains("stroke too large"), "{cmd}: {err}");
assert_eq!(rgba(&s, 20, 10), before, "{cmd}: a refused stroke leaves the pixels alone");
- // The allowance still covers a stroke across the whole canvas.
- let across = s.execute(cmd, with(&ok));
- assert!(across.is_ok() || !format!("{across:?}").contains("stroke too large"), "{cmd}: {across:?}");
+ assert_eq!(s.active().unwrap().history.past_len(), steps, "{cmd}: and records no history step");
+
+ // The allowance still covers ordinary work: this must succeed, not merely avoid the error.
+ s.execute(cmd, with(&ok)).unwrap_or_else(|e| panic!("{cmd}: an ordinary stroke must work: {e}"));
+ assert_eq!(s.active().unwrap().history.past_len(), steps + 1, "{cmd}: and records one step");
}
// Remove takes a list of strokes; each one is charged as it is parsed.
@@ -604,6 +607,33 @@ fn every_retouch_stroke_refuses_a_box_it_cannot_render() {
assert!(err.contains("stroke too large"), "paint.remove: {err}");
}
+/// The review on #6110: the estimate from the input points is not the bound. Brush dynamics place
+/// dabs beyond those points, so the budget is applied to the extent the renderer actually produced,
+/// before the dense buffer is allocated. An injected budget makes that observable without asking
+/// for a stroke big enough to exhaust anything.
+#[test]
+fn the_budget_is_applied_to_the_rendered_extent_not_the_input_points() {
+ use photocraft_paint::{BrushSettings, Stroke, StrokePoint};
+ let mut brush = BrushSettings { size: 24.0, hardness: 1.0, ..Default::default() };
+ brush.scattering.enabled = true;
+ brush.scattering.scatter.jitter = 6.0;
+ let stroke = Stroke { brush, points: vec![StrokePoint::new(10.0, 10.0, 1.0), StrokePoint::new(40.0, 10.0, 1.0)] };
+
+ // What the renderer really covered, once scattering has placed every dab.
+ let (bounds, cov) = super::coverage_within("t", &stroke, u64::MAX).unwrap();
+ let rendered = u64::from(bounds.width()) * u64::from(bounds.height());
+ assert_eq!(cov.len() as u64, rendered, "the dense buffer is exactly the rendered extent");
+
+ // Scattering reaches past the points plus half the tip, which is what the estimate alone sees.
+ let points_only = (40.0 - 10.0 + 24.0 + 8.0) * (24.0 + 8.0);
+ assert!(rendered as f64 > points_only, "scattering expanded the stroke: {rendered} vs {points_only}");
+
+ // A budget one pixel under what it rendered refuses it; exactly the rendered extent fits.
+ let err = super::coverage_within("t", &stroke, rendered - 1).unwrap_err().to_string();
+ assert!(err.contains("stroke too large"), "{err}");
+ assert!(super::coverage_within("t", &stroke, rendered).is_ok(), "the rendered extent itself fits");
+}
+
#[test]
fn history_brush_reads_a_source_when_its_pixels_were_locked() {
// Given a white layer locked in history state 1, then unlocked and filled red.
diff --git a/crates/paint/src/retouch.rs b/crates/paint/src/retouch.rs
index 9ef837c0c..023e04b5e 100644
--- a/crates/paint/src/retouch.rs
+++ b/crates/paint/src/retouch.rs
@@ -130,6 +130,24 @@ pub fn stroke_coverage(stroke: &Stroke) -> (Rect, Vec<f32>) {
r.dense_coverage()
}
+/// [`stroke_coverage`] that admits the **rendered** extent before it is made dense: `None` when the
+/// stroke covers more than `max_pixels`.
+///
+/// Rendering itself is tiled, so it holds only the tiles the dabs touch. The bounds are read from
+/// those tiles, after tips, dynamics and scattering have placed every dab, so this is the stroke's
+/// real extent rather than an estimate from the input points. Only then is the `width × height`
+/// buffer allocated, which is what callers need bounded.
+pub fn stroke_coverage_within(stroke: &Stroke, max_pixels: u64) -> Option<(Rect, Vec<f32>)> {
+ let mut r = crate::StrokeRenderer::new(&stroke.brush, None, 1.0);
+ r.push(&stroke.points);
+ r.finish();
+ let b = r.bounds();
+ if u64::from(b.width()).saturating_mul(u64::from(b.height())) > max_pixels {
+ return None;
+ }
+ Some(r.dense_coverage())
+}
+
/// Index of the alpha channel, if the format has one.
#[inline]
pub fn alpha_index(fmt: &PixelFormat) -> Option<usize> {