Merge pull request #9348 from VoiceLessQ/pattern-preview-wrap-tools

paint: 12 more painting tools wrap across the canvas edges in Pattern Preview (#8883)
This commit is contained in:
David Mann authored and GitHub committed 2026-11-08 19:22:34 +01:00
commit fa41efebc5
7 files changed
+305 -34

No files matched your search

+1 -1
View File
@@ -260,7 +260,7 @@ pub fn specs() -> Vec<CommandSpec> {
menu: &[],
shortcut: None,
params: brush_params!(
r#","source":[sx,sy] | "offset":[dx,dy],"aligned":bool=true,"sampleLayer":"current|currentAndBelow|all"="current","mode":"normal|…"="normal" → {"damage","offset","aligned","nextSource"}"#
r#","source":[sx,sy] | "offset":[dx,dy],"aligned":bool=true,"sampleLayer":"current|currentAndBelow|all"="current","mode":"normal|…"="normal","wrap":bool=false (View › Pattern Preview: the stroke goes on across the canvas edges) → {"damage","offset","aligned","nextSource"}"#
),
enabled: has_pixel_layer,
run: healing_brush,
+26 -27
View File
@@ -130,26 +130,19 @@ pub(super) fn clone_stamp(s: &mut Session, p: &Value) -> Result<Value> {
let from_live = live.is_some();
let map = clone_mapping(s, p, &stroke, CMD)?;
let off = map.offset();
let dmg =
run_stroke(s, "Clone Stamp", id, p, |pre, surf, sel, lock| {
if let Some(l) = live {
*surf = l.surface;
return Ok(l.bounds);
}
if flag(p, "wrap", false) {
let mut renderer = photocraft_paint::StrokeRenderer::new(&stroke.brush, None, 1.0);
renderer.push(&stroke.points);
renderer.finish();
let before = surf.clone();
let bounds = renderer.bounds();
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) = 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))
})?;
let dmg = run_stroke(s, "Clone Stamp", id, p, |pre, surf, sel, lock| {
if let Some(l) = live {
*surf = l.surface;
return Ok(l.bounds);
}
if flag(p, "wrap", false) {
return periodic::stroke(pre, surf, &stroke, sel, lock, mode, CMD, |before, r| clone_sample(pre, id, before, which, r, &map, true, CMD));
}
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))
})?;
let mut r = clone_result(dmg, off, aligned, p, &stroke);
if from_live {
r["fromLive"] = json!(true);
@@ -272,11 +265,14 @@ impl LiveRetouch {
/// Everything the stroke has touched so far.
pub fn bounds(&self) -> Rect {
let bounds = self.renderer.bounds().union(&self.tail);
if self.cmd == "paint.cloneStamp" && flag(&self.params, "wrap", false) {
periodic::project(bounds, self.pre.bounds()).into_iter().fold(Rect::EMPTY, |a, b| a.union(&b))
} else {
bounds
}
if self.wraps() { periodic::project(bounds, self.pre.bounds()).into_iter().fold(Rect::EMPTY, |a, b| a.union(&b)) } else { bounds }
}
/// Whether the stroke repeats across the canvas edges (View › Pattern Preview). Only the Clone
/// Stamp and the Healing Brush do: the reference application's other retouching tools stop
/// at the edge.
fn wraps(&self) -> bool {
matches!(self.cmd.as_str(), "paint.cloneStamp" | "paint.healingBrush") && flag(&self.params, "wrap", false)
}
/// Every point rendered so far, in order.
@@ -328,7 +324,7 @@ impl LiveRetouch {
let pts: Vec<_> = pts.iter().map(|q| StrokePoint::new(q.x, q.y, q.pressure)).collect();
self.points.extend_from_slice(&pts);
self.renderer.push(&pts);
if self.cmd == "paint.cloneStamp" && flag(&self.params, "wrap", false) {
if self.wraps() {
return self.push_periodic();
}
let old = std::mem::replace(&mut self.tail, Rect::EMPTY);
@@ -360,6 +356,8 @@ impl LiveRetouch {
let LivePaint::Clone { which, map, cmd } = &self.paint else {
return Err(bad(&self.cmd, "periodic painting requires a clone source"));
};
let (pre, id, pre_surf, live_cmd) = (&self.pre, self.id, &self.pre_surf, self.cmd.as_str());
let paint = |r| clone_sample(pre, id, pre_surf, *which, r, map, true, cmd);
let (surf, _) = crate::channel_cmds::target_surface(std::sync::Arc::make_mut(&mut self.doc), self.id, &self.params)?;
periodic::Composite {
target: surf,
@@ -369,8 +367,9 @@ impl LiveRetouch {
selection: self.sel.as_ref(),
lock: self.lock,
mode: self.mode,
cmd: live_cmd,
}
.draw(dirty, &self.brush, &self.points, |r| clone_sample(&self.pre, self.id, &self.pre_surf, *which, r, map, true, cmd))
.draw(dirty, &self.brush, &self.points, paint)
}
/// Redraw `r` from the pre-stroke pixels with the clone source through coverage `cov`.
+18 -2
View File
@@ -1,4 +1,5 @@
use super::clone::{blend_param, clamp_samples, clone_mapping, clone_result, clone_sample};
use super::periodic;
use super::sampling::{SampleLayers, composite_region, sample_all_layers, sample_layers};
use super::{
BlendMode, CompleteParams, Document, EngineError, LayerId, PixelFormat, Rect, Region, Result, Session, Stroke, Surface, Value, apply_coverage, bad,
@@ -53,15 +54,30 @@ pub(super) 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| {
// Pattern Preview: source and destination repeat across the canvas edges, so a stroke over
// a seam heals as one patch and goes on wherever it repeats.
let wrap = flag(p, "wrap", false);
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)?;
let src = clone_sample(pre, id, surf, which, g, &map, wrap, CMD)?;
// The destination the texture is fitted to: the layer itself, or what the user sees when
// sampling several layers (so healing onto an empty layer matches the composite).
let dst = if which == SampleLayers::Current { Region::read(surf, g) } else { composite_region(pre, id, which, g, fmt) };
let dst = if wrap {
periodic::sample(pre, id, surf, which, g, CMD)?
} else if which == SampleLayers::Current {
Region::read(surf, g)
} else {
composite_region(pre, id, which, g, fmt)
};
let mask: Vec<bool> = cov.iter().map(|c| *c > 0.0).collect();
let healed = heal_region(&fmt, &src, &dst, &mask);
if wrap {
return periodic::stroke(pre, surf, &stroke, sel, lock, mode, CMD, |_, r| {
let part = healed.crop(r);
if part.rect == r { Ok(part) } else { Err(bad(CMD, "the healed patch does not cover the stroke")) }
});
}
Ok(apply_coverage(surf, g, &cov, stroke.brush.opacity, sel, lock, &healed, mode))
})?;
Ok(clone_result(dmg, off, aligned, p, &stroke))
+31 -2
View File
@@ -1,6 +1,6 @@
//! Bounded reads from the repeating document tile used by Pattern Preview.
use super::{BlendMode, BrushSettings, Document, LayerId, Rect, Region, Result, SampleLayers, StrokePoint, Surface, alpha_index, apply_coverage, bad};
use super::{BlendMode, BrushSettings, Document, LayerId, Rect, Region, Result, SampleLayers, Stroke, StrokePoint, Surface, alpha_index, apply_coverage, bad};
/// At most four disjoint rectangles in the document tile. Projecting the dirty area separately
/// from the stroke bounds avoids scanning the whole document when a small dab crosses a seam.
@@ -23,6 +23,33 @@ pub(super) fn project(rect: Rect, tile: Rect) -> Vec<Rect> {
ys.into_iter().flat_map(|(y0, y1)| xs.iter().map(move |&(x0, x1)| Rect::new(x0, y0, x1, y1))).collect()
}
/// A composite tool's stroke wrapped around the document: `paint` gives the pixels for a
/// rectangle in the stroke's own coordinates, from the target as it was before the stroke, and
/// they go on through the stroke's coverage wherever it repeats on the document.
#[allow(clippy::too_many_arguments)]
pub(super) fn stroke(
pre: &Document,
target: &mut Surface,
stroke: &Stroke,
selection: Option<&Surface>,
lock: bool,
mode: BlendMode,
cmd: &str,
mut paint: impl FnMut(&Surface, Rect) -> Result<Region>,
) -> Result<Rect> {
let mut renderer = photocraft_paint::StrokeRenderer::new(&stroke.brush, None, 1.0);
renderer.push(&stroke.points);
renderer.finish();
let before = target.clone();
let bounds = renderer.bounds();
Composite { target, before: &before, tile: pre.bounds(), opacity: stroke.brush.opacity, selection, lock, mode, cmd }.draw(
bounds,
&stroke.brush,
&stroke.points,
|r| paint(&before, r),
)
}
/// Composite periodic copies of one stroke, restoring each dirty patch from pre-stroke pixels.
/// Each dab wraps once, then builds flow towards its opacity ceiling. Stroke opacity and
/// selection are applied once after all dabs, including repeated visits through other tiles.
@@ -34,6 +61,8 @@ pub(super) struct Composite<'a> {
pub selection: Option<&'a Surface>,
pub lock: bool,
pub mode: BlendMode,
/// The command an over-budget stroke's error names.
pub cmd: &'a str,
}
impl Composite<'_> {
@@ -138,7 +167,7 @@ impl Composite<'_> {
);
*work = work.saturating_add(r.width() as u64 * r.height() as u64);
if *work > 64 * 1024 * 1024 {
return Err(bad("paint.cloneStamp", "wrapped stroke exceeds its coverage budget"));
return Err(bad(self.cmd, "wrapped stroke exceeds its coverage budget"));
}
ctx.rasterize_into(dab, dual, r, &mut values, wet.then_some(&mut depths));
let mut sampled = None;
+189
View File
@@ -2532,3 +2532,192 @@ fn periodic_clone_interior_matches_ordinary_brush_masks_and_transparency() {
}
}
}
// ---------------------------------------------------------------------------------------------
// View › Pattern Preview: Clone Stamp and Healing Brush wrap across the canvas edges (#8883)
// ---------------------------------------------------------------------------------------------
/// The canvas the Pattern Preview tests wrap around.
const WRAP: (u32, u32) = (48, 36);
/// `texture` repeated every canvas, so each copy of a pixel holds the same colour.
fn tiled_texture(x: i32, y: i32) -> [f32; 4] {
texture(x.rem_euclid(WRAP.0 as i32), y.rem_euclid(WRAP.1 as i32))
}
/// A stroke from just inside the corner where the middle copy of a three-by-three tiling meets
/// the next copies, out across both of its edges.
fn corner_stroke(extra: &Value) -> Value {
let mut p = json!({"points": [[84, 64], [106, 79]], "size": 12, "hardness": 100});
for (k, v) in extra.as_object().unwrap() {
p[k] = v.clone();
}
p
}
/// The stroke tools that wrap, with their options. Both composite a paint image through the
/// stroke's coverage (`periodic::Composite`), which matches the ordinary composite only within
/// rounding.
fn wrap_cases() -> [(&'static str, Value); 2] {
[("paint.healingBrush", json!({"offset": [-20, -14]})), ("paint.cloneStamp", json!({"offset": [-20, -14]}))]
}
/// The native-channel difference `periodic::Composite` may leave against the ordinary composite.
fn composite_tolerance(depth: u64) -> f32 {
match depth {
8 => 1.1 / 255.0,
16 => 1.1 / 65535.0,
_ => 0.00001,
}
}
#[test]
fn every_wrapping_stroke_paints_the_canvas_as_on_the_canvas_tiled_three_by_three() {
// A stroke with `"wrap": true` gives each pixel of the canvas what the same stroke gives the
// copy of that pixel it goes over, on a document holding the canvas tiled three by three.
let (w, h) = (WRAP.0 as usize, WRAP.1 as usize);
for depth in DEPTHS {
for (cmd, extra) in wrap_cases() {
let mut canvas = session(WRAP.0, WRAP.1, depth, "rgb");
paint_layer(&mut canvas, tiled_texture);
let mut tiled = session(3 * WRAP.0, 3 * WRAP.1, depth, "rgb");
paint_layer(&mut tiled, tiled_texture);
let (mut wrapped, plain) = (corner_stroke(&extra), corner_stroke(&extra));
wrapped["wrap"] = json!(true);
canvas.execute(cmd, wrapped).unwrap_or_else(|e| panic!("{cmd} at {depth}: {e}"));
let before = layer_pixels(&tiled);
tiled.execute(cmd, plain).unwrap();
let (got, want) = (layer_pixels(&canvas), layer_pixels(&tiled));
let n = got.len() / (w * h);
let at = |x: usize, y: usize| (y * 3 * w + x) * n..(y * 3 * w + x + 1) * n;
let tolerance = composite_tolerance(depth);
let (mut moved, mut edges) = (0, [false; 4]);
for y in 0..h {
for x in 0..w {
let copies = (0..3).flat_map(|j| (0..3).map(move |i| (x + i * w, y + j * h)));
let changed: Vec<_> = copies.filter(|&(u, v)| want[at(u, v)] != before[at(u, v)]).collect();
let (pixel, expected) = match changed.as_slice() {
[] => (&got[(y * w + x) * n..][..n], &before[at(x, y)]),
[(u, v)] => (&got[(y * w + x) * n..][..n], &want[at(*u, *v)]),
_ => panic!("{cmd}: ({x}, {y}) has two copies under the stroke"),
};
let error = pixel.iter().zip(expected).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max);
assert!(error <= tolerance, "{cmd} {extra} at {depth}-bit: ({x}, {y}) is off by {error}");
if !changed.is_empty() {
moved += 1;
edges[0] |= x < 8;
edges[1] |= x >= w - 8;
edges[2] |= y < 8;
edges[3] |= y >= h - 8;
}
}
}
assert!(moved > 150 && edges.iter().all(|&e| e), "{cmd} {extra} at {depth}-bit: the stroke crossed both edges ({moved} px, {edges:?})");
}
}
}
#[test]
fn a_wrapped_stroke_inside_the_canvas_paints_as_an_ordinary_one() {
let p = json!({"points": [[130, 110], [150, 118], [168, 112]], "size": 14, "hardness": 60});
for depth in [8, 32] {
for (cmd, extra) in wrap_cases() {
let run = |wrap: bool| {
let mut s = session(300, 230, depth, "rgb");
paint_layer(&mut s, tiled_texture);
let mut q = p.clone();
for (k, v) in extra.as_object().unwrap() {
q[k] = v.clone();
}
q["wrap"] = json!(wrap);
s.execute(cmd, q).unwrap();
layer_pixels(&s)
};
let (plain, wrapped) = (run(false), run(true));
let error = plain.iter().zip(&wrapped).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max);
assert!(error <= composite_tolerance(depth), "{cmd} {extra} at {depth}-bit: off by {error}");
}
}
}
#[test]
fn a_wrapped_dab_bigger_than_the_canvas_stays_on_it() {
for (cmd, extra) in wrap_cases() {
let mut s = session(16, 12, 8, "rgb");
paint_layer(&mut s, tiled_texture);
let before = layer_pixels(&s);
let mut p = json!({"points": [[8, 6], [30, 20]], "size": 60, "hardness": 0, "wrap": true});
for (k, v) in extra.as_object().unwrap() {
p[k] = v.clone();
}
let r = s.execute(cmd, p).unwrap_or_else(|e| panic!("{cmd}: {e}"));
let d = r["damage"].as_array().map(|d| d.iter().filter_map(Value::as_i64).collect::<Vec<_>>()).unwrap_or_default();
assert!(matches!(d.as_slice(), [x, y, w, h] if *x >= 0 && *y >= 0 && x + w <= 16 && y + h <= 12), "{cmd}: damage {d:?} is on the canvas");
let st = s.active().unwrap();
let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap();
assert!([(-1, 5), (16, 5), (5, -1), (5, 12), (40, 30)].iter().all(|&(x, y)| surf.rgba(x, y)[3] == 0.0), "{cmd}: nothing lands off the canvas");
assert!(layer_pixels(&s) != before, "{cmd} {extra}: the stroke changed the canvas");
}
}
#[test]
fn the_tools_the_reference_application_does_not_wrap_stop_at_the_canvas_edge() {
// Measured in the reference application: in Pattern Preview the Clone Stamp and Healing
// Brush carry a stroke on across the canvas edges, but Blur … Sponge, Color Replacement,
// Background Eraser, Pattern Stamp and History Brush warn that they don't wrap, and Spot
// Healing stops at the edge too. Their `wrap` stroke over the corner paints as the same
// stroke without it.
let points = [[36.0, 24.0], [58.0, 39.0]];
let cases = [
("paint.blur", json!({"strength": 80})),
("paint.sharpen", json!({"strength": 60})),
("paint.smudge", json!({"strength": 70})),
("paint.dodge", json!({"exposure": 60})),
("paint.burn", json!({"exposure": 40})),
("paint.sponge", json!({"mode": "saturate"})),
("paint.colorReplacement", json!({"color": "#ff8000", "tolerance": 60})),
("paint.backgroundEraser", json!({"tolerance": 40})),
("paint.patternStamp", json!({"pattern": "Checkerboard"})),
("paint.patternStamp", json!({"pattern": "Bricks", "impressionist": true, "seed": 7})),
("paint.historyBrush", json!({"state": 1})),
("paint.spotHealing", json!({"type": "contentAware"})),
];
for (cmd, extra) in cases {
let run = |wrap: bool| {
let mut s = session(WRAP.0, WRAP.1, 8, "rgb");
paint_layer(&mut s, tiled_texture);
// Painted over since history state 1, so the History Brush has something to bring back.
paint_layer(&mut s, |x, y| tiled_texture(x + 7, y + 5));
let mut p = dab_opts(&points, 100, &extra);
p["size"] = json!(12);
p["wrap"] = json!(wrap);
let before = layer_pixels(&s);
s.execute(cmd, p).unwrap_or_else(|e| panic!("{cmd}: {e}"));
(before, layer_pixels(&s))
};
let ((before, plain), (_, wrapped)) = (run(false), run(true));
assert!(plain != before, "{cmd} {extra}: the stroke paints inside the canvas");
assert!(wrapped == plain, "{cmd} {extra}: nothing comes back at the opposite edges");
}
}
#[test]
fn live_history_and_pattern_strokes_stop_at_the_canvas_edge() {
// The History Brush and aligned Pattern Stamp previews stop at the edge as their commits do.
let points = [[36.0, 24.0], [58.0, 39.0]];
let pts: Vec<_> = points.iter().map(|q| StrokePoint::new(q[0], q[1], 1.0)).collect();
for (cmd, extra) in [("paint.historyBrush", json!({"state": 1})), ("paint.patternStamp", json!({"pattern": "Checkerboard"}))] {
let bounds = |wrap: bool| {
let mut s = session(WRAP.0, WRAP.1, 8, "rgb");
paint_layer(&mut s, tiled_texture);
paint_layer(&mut s, |_, _| [0.15, 0.2, 0.7, 1.0]);
let mut p = dab_opts(&points[..1], 100, &extra);
p["size"] = json!(12);
p["wrap"] = json!(wrap);
let mut live = LiveRetouch::begin(&s, cmd, &p).unwrap();
live.push(&pts[1..]).unwrap();
live.bounds()
};
assert_eq!(bounds(true), bounds(false), "{cmd}: the live stroke stays where it was drawn");
}
}
+2 -2
View File
@@ -29,9 +29,9 @@ pub(crate) fn clone_params(app: &PhotocraftApp) -> Option<Value> {
let o = &app.ui.tool_options;
// The options bar's Mode is the tool's own brush's.
let mode = crate::blend_keys::brush_tool_mode(app.ui.tool, app.session.tools.brush.mode);
let mut p = json!({"aligned": o.clone_aligned, "sampleLayer": o.clone_sample, "mode": mode.label()});
// View › Pattern Preview: both tools carry a stroke on across the canvas edges (#8883).
let mut p = json!({"aligned": o.clone_aligned, "sampleLayer": o.clone_sample, "mode": mode.label(), "wrap": app.ui.view.pattern_preview});
if app.ui.tool == Tool::CloneStamp {
p["wrap"] = json!(app.ui.view.pattern_preview);
p["opacity"] = json!(app.session.tools.brush.opacity * 100.0);
p["flow"] = json!(app.session.tools.brush.flow * 100.0);
}
@@ -28,6 +28,44 @@ fn stripes(app: &mut PhotocraftApp, step: usize, target: &str) {
}
}
#[test]
fn only_clone_stamp_and_healing_brush_wrap_in_pattern_preview() {
// View › Pattern Preview (#8883): a Clone Stamp or Healing Brush stroke across the right edge
// asks its command to go on at the opposite one, and only then. The reference application's
// other retouching tools stop at the edge.
let tools = [
(Tool::CloneStamp, "paint.cloneStamp", true),
(Tool::Healing, "paint.healingBrush", true),
(Tool::Blur, "paint.blur", false),
(Tool::Sharpen, "paint.sharpen", false),
(Tool::Smudge, "paint.smudge", false),
(Tool::Dodge, "paint.dodge", false),
(Tool::Burn, "paint.burn", false),
(Tool::Sponge, "paint.sponge", false),
(Tool::ColorReplacement, "paint.colorReplacement", false),
(Tool::PatternStamp, "paint.patternStamp", false),
(Tool::HistoryBrush, "paint.historyBrush", false),
(Tool::SpotHealing, "paint.spotHealing", false),
(Tool::BackgroundEraser, "paint.backgroundEraser", false),
];
for (tool, cmd, wraps) in tools {
for pattern_preview in [false, true] {
let mut app = app();
stripes(&mut app, 8, "pixels");
app.ui.view.pattern_preview = pattern_preview;
app.ui.clone_source = Some([20.0, 30.0]);
app.ui.tool = tool;
let m = egui::Modifiers::NONE;
tool_event(&mut app, ToolEvent::Down { x: 86.0, y: 30.0, pressure: 1.0 }, m);
tool_event(&mut app, ToolEvent::Move { x: 112.0, y: 30.0, pressure: 1.0 }, m);
tool_event(&mut app, ToolEvent::Up { x: 112.0, y: 30.0 }, m);
assert!(!app.ui.status_error, "{tool:?}: {}", app.ui.status);
let (_, p) = app.session.journal.iter().rev().find(|(id, _)| id == cmd).cloned().unwrap_or_else(|| panic!("{tool:?}: no {cmd}"));
assert_eq!(p.get("wrap").and_then(Value::as_bool).unwrap_or(false), wraps && pattern_preview, "{tool:?}: {p}");
}
}
}
#[test]
fn clone_stamp_in_pattern_preview_wraps_a_dab_across_the_right_edge() {
for pattern_preview in [false, true] {