From a11204c6773ccf02abfc00b08c4b6e3fdf2381a5 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 7 Nov 2026 21:04:55 +0100 Subject: [PATCH 1/2] Background Eraser: Protect Foreground Color fades with the distance (#11903) Protect Foreground Color skipped every pixel within the whole Tolerance of the foreground colour, the sampled colour included, so with a foreground near the sample nothing was erased at all. It now narrows the Tolerance to the distance between the sampled colour and the foreground colour: the sample is still erased, the protection fades towards the sample, and the foreground colour and colours beyond it are kept, as the reference application does. Co-Authored-By: Claude Opus 5.5 --- crates/paint/src/bg_erase.rs | 32 +++- .../src/bg_erase_protect_foreground_tests.rs | 174 ++++++++++++++++++ 2 files changed, 201 insertions(+), 5 deletions(-) create mode 100644 crates/paint/src/bg_erase_protect_foreground_tests.rs diff --git a/crates/paint/src/bg_erase.rs b/crates/paint/src/bg_erase.rs index 323a90036aa..8220eff783a 100644 --- a/crates/paint/src/bg_erase.rs +++ b/crates/paint/src/bg_erase.rs @@ -19,7 +19,8 @@ pub struct BgEraseSettings { pub limits: Limits, /// 0..1: largest per-channel difference from the sampled colour that is erased. pub tolerance: f32, - /// Keep pixels that match the foreground colour. + /// Keep the foreground colour: the erase narrows to the colours between the sampled colour and + /// the foreground colour (see [`protected_distance`]). pub protect_foreground: bool, /// Straight RGBA foreground colour (for Protect Foreground Color). pub foreground: [f32; 4], @@ -45,6 +46,22 @@ fn dist(a: &[f32], b: &[f32]) -> f32 { a.iter().zip(b).fold(0.0f32, |m, (x, y)| m.max((x - y).abs())) } +/// The distance `d` from the sampled colour as Protect Foreground Color weighs it: the Tolerance +/// narrows to `limit`, the distance from the sampled colour to the foreground colour, so the +/// protection fades with the distance from the foreground and the sampled colour itself is still +/// erased (#11903). Colours at least as far from the sample as the foreground (the foreground +/// itself included) are never erased; a foreground equal to the sample protects everything. +fn protected_distance(d: f32, tol: f32, limit: f32) -> f32 { + if limit.is_nan() || d.is_nan() || limit <= 0.0 || d >= limit { + return f32::INFINITY; + } + if limit >= tol || d <= 0.0 { + return d; + } + // Stretch the distance so the Tolerance ends at the foreground colour. + d * (tol / limit) +} + /// Erase along `stroke`. The brush opacity is ignored (Photoshop's Background Eraser has none); /// the selection limits the effect. Returns the damaged rectangle; empty when the surface has no /// alpha channel. @@ -116,6 +133,7 @@ pub fn background_eraser_effect(pre: &Surface, bs: &BgEraseSettings) -> Option Some(swatch.clone()), }; let Some(sampled) = sampled else { return }; + let protect_limit = protect_foreground.then(|| dist(&sampled, &fg)); let (w, h) = (r.width() as usize, r.height() as usize); // Per-pixel match weight from the pre-stroke colours: the contiguous fill passes through // pixels this stroke already erased. @@ -129,11 +147,11 @@ pub fn background_eraser_effect(pre: &Surface, bs: &BgEraseSettings) -> Option [f32; 4] { + [200.0 / 255.0, (40.0 + 20.0 * i as f32) / 255.0, 40.0 / 255.0, 1.0] +} + +/// Eight 100 px blocks side by side, 900 x 300 (the reference's layout, shifted up). +fn blocks(fmt: PixelFormat) -> Surface { + let mut s = Surface::new(fmt); + for i in 0..8 { + let x = 100 * i as i32; + s.fill_rect(Rect::new(x, 0, x + 100, 300), &from_rgba(&fmt, block(i))); + } + s +} + +fn stroke(points: &[(f64, f64)]) -> Stroke { + Stroke { + brush: BrushSettings { size: 40.0, hardness: 1.0, spacing: 0.25, pressure_size: false, ..Default::default() }, + points: points.iter().map(|&(x, y)| StrokePoint::new(x, y, 1.0)).collect(), + } +} + +fn settings(protect: Option) -> BgEraseSettings { + BgEraseSettings { + sampling: Sampling::Once, + limits: Limits::Discontiguous, + tolerance: 0.5, + protect_foreground: protect.is_some(), + foreground: block(protect.unwrap_or(0)), + ..Default::default() + } +} + +/// The reference's drag from block 0's centre through all eight; alpha (0-255) at each centre. +fn drag(fmt: PixelFormat, protect: Option) -> [i32; 8] { + let mut s = blocks(fmt); + apply_background_eraser(&mut s, &stroke(&[(50.0, 150.0), (750.0, 150.0)]), &settings(protect), None); + std::array::from_fn(|i| (s.rgba(100 * i as i32 + 50, 150)[3] * 255.0).round() as i32) +} + +/// The measured rows: Sampling Once, Discontiguous, Tolerance 50, 40 px hard tip. Without +/// protection the reference gives `0 30 75 114 156 198 238 255` (the graded erase of #11901). +const REFERENCE: [(usize, [i32; 8]); 3] = + [(1, [0, 255, 255, 255, 255, 255, 255, 255]), (3, [0, 76, 166, 255, 255, 255, 255, 255]), (5, [0, 40, 94, 148, 201, 255, 255, 255])]; + +#[test] +fn the_sampled_colour_is_erased_and_colours_from_the_foreground_on_are_kept() { + for (fg, want) in REFERENCE { + let got = drag(PixelFormat::RGBA8, Some(fg)); + let off = drag(PixelFormat::RGBA8, None); + for i in 0..8 { + match want[i] { + // Fully kept in the reference: kept here too. + 255 => assert_eq!(got[i], 255, "fg block {fg}: block {i} kept, got {got:?}"), + // The sample itself: erased. + 0 => assert_eq!(got[i], 0, "fg block {fg}: block {i} (the sample) erased, got {got:?}"), + // Partly erased in the reference: erased here too, never more than without protection. + _ => assert!(got[i] < 255 && got[i] >= off[i], "fg block {fg}: block {i} partly erased, got {got:?}, off {off:?}"), + } + } + } +} + +#[test] +fn protection_narrows_the_tolerance_to_the_foreground_in_one_dab() { + // One click (Background Swatch = block 0, so the click's own pixel does not matter) on each + // block: with the foreground at block `fg`, the protected click erases what an unprotected + // click at Tolerance = the sample-to-foreground distance erases, and keeps block fg and beyond. + let fmt = PixelFormat::RGBA8; + let click = |protect: Option, tolerance: f32| -> Vec { + (0..8) + .map(|i| { + let mut s = blocks(fmt); + let bs = BgEraseSettings { sampling: Sampling::BackgroundSwatch, background: block(0), tolerance, ..settings(protect) }; + let x = 100.0 * i as f64 + 50.0; + apply_background_eraser(&mut s, &stroke(&[(x, 150.0)]), &bs, None); + s.rgba(x as i32, 150)[3] + }) + .collect() + }; + for fg in [1, 3, 5] { + let protected = click(Some(fg), 0.5); + let narrowed = click(None, 20.0 * fg as f32 / 255.0); + for i in 0..8 { + if i < fg { + assert!((protected[i] - narrowed[i]).abs() <= 1.0 / 255.0, "fg block {fg}: block {i} {protected:?} vs {narrowed:?}"); + } else { + assert_eq!(protected[i], 1.0, "fg block {fg}: block {i} kept, {protected:?}"); + } + } + } +} + +#[test] +fn a_foreground_equal_to_the_sample_erases_nothing() { + for limits in [Limits::Contiguous, Limits::Discontiguous, Limits::FindEdges] { + for tolerance in [0.0, 0.1, 0.5, 1.0] { + let s = blocks(PixelFormat::RGBA8); + let mut t = s.clone(); + let bs = BgEraseSettings { limits, tolerance, ..settings(Some(0)) }; + apply_background_eraser(&mut t, &stroke(&[(50.0, 150.0), (750.0, 150.0)]), &bs, None); + assert_eq!(t, s, "{limits:?} tolerance {tolerance}"); + } + } +} + +#[test] +fn find_edges_keeps_the_foreground_colour_itself() { + // Find Edges erases fully inside the Tolerance; a pixel exactly at the foreground stays. + let fmt = PixelFormat::RGBA8; + let mut s = blocks(fmt); + let bs = BgEraseSettings { limits: Limits::FindEdges, ..settings(Some(1)) }; + apply_background_eraser(&mut s, &stroke(&[(80.0, 150.0), (120.0, 150.0)]), &bs, None); + assert_eq!(s.rgba(75, 150)[3], 0.0, "the sample erased"); + assert_eq!(s.rgba(110, 150)[3], 1.0, "the foreground colour kept"); +} + +#[test] +fn protect_off_is_unchanged() { + // The drag without protection, as main gives it before the graded erase of #11901: today's + // pre-stroke matching over overlapping dabs. Pinned so the protection change cannot leak in. + let off = drag(PixelFormat::RGBA8, None); + assert_eq!(off[0], 0); + assert_eq!(off[7], 255); + let mut s = blocks(PixelFormat::RGBA8); + let mut t = s.clone(); + let on_far = BgEraseSettings { foreground: [0.0, 0.0, 1.0, 1.0], protect_foreground: true, ..settings(None) }; + apply_background_eraser(&mut s, &stroke(&[(50.0, 150.0), (750.0, 150.0)]), &settings(None), None); + apply_background_eraser(&mut t, &stroke(&[(50.0, 150.0), (750.0, 150.0)]), &on_far, None); + assert_eq!(s, t, "a foreground beyond the Tolerance protects nothing"); +} + +#[test] +fn protection_works_in_the_documents_own_channels() { + // 16-bit RGB: the same rows as 8-bit. + let rgb16 = PixelFormat::new(ColorMode::Rgb, SampleType::U16, true); + for (fg, want) in REFERENCE { + let got = drag(rgb16, Some(fg)); + for i in 0..8 { + if want[i] == 255 || want[i] == 0 { + assert_eq!(got[i], want[i], "16-bit fg block {fg}: block {i}, got {got:?}"); + } + } + } + // Gray: blocks stepping by 20 in gray; foreground at block 3 keeps blocks 3 and beyond and + // still erases block 0. + let gray = PixelFormat::new(ColorMode::Grayscale, SampleType::U8, true); + let mut s = Surface::new(gray); + let level = |i: usize| (40.0 + 20.0 * i as f32) / 255.0; + for i in 0..8 { + let x = 100 * i as i32; + s.fill_rect(Rect::new(x, 0, x + 100, 300), &[level(i), 1.0]); + } + let fg = [level(3), level(3), level(3), 1.0]; + let bs = BgEraseSettings { foreground: fg, ..settings(Some(3)) }; + apply_background_eraser(&mut s, &stroke(&[(50.0, 150.0), (750.0, 150.0)]), &bs, None); + let a: Vec = (0..8).map(|i| s.rgba(100 * i + 50, 150)[3]).collect(); + assert_eq!(a[0], 0.0, "gray: the sample erased, {a:?}"); + for (i, v) in a.iter().enumerate().skip(3) { + assert_eq!(*v, 1.0, "gray: block {i} kept, {a:?}"); + } +} From 6bd3773e0743d21bb28d76ca7026298462f967ea Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 8 Nov 2026 01:40:59 +0100 Subject: [PATCH 2/2] Address CodeRabbit review: match the foreground at the document's precision, pin the protect-off row The sampled colour is read from stored pixels, but the foreground was compared unrounded, so in 8- and 16-bit documents a foreground between two levels missed its own stored colour: Find Edges erased it, and a foreground stored as the sample no longer protected anything. The foreground is now rounded to the document's sample type first (32-bit float unchanged). protect_off_is_unchanged now pins the whole alpha row, not only the first and last block. Co-Authored-By: Claude Opus 5.5 --- crates/paint/src/bg_erase.rs | 12 +++++- .../src/bg_erase_protect_foreground_tests.rs | 41 +++++++++++++++++-- 2 files changed, 48 insertions(+), 5 deletions(-) diff --git a/crates/paint/src/bg_erase.rs b/crates/paint/src/bg_erase.rs index 8220eff783a..314bf5ab78f 100644 --- a/crates/paint/src/bg_erase.rs +++ b/crates/paint/src/bg_erase.rs @@ -4,6 +4,7 @@ //! Colours are compared in the surface's own colour channels (RGB, CMYK, Gray, Lab… at any depth), //! so nothing is converted through RGB; only alpha changes. +use photocraft_color::{SampleType, read_sample, write_sample}; use photocraft_geom::Rect; use photocraft_raster::{Surface, from_rgba}; use serde::{Deserialize, Serialize}; @@ -62,6 +63,15 @@ fn protected_distance(d: f32, tol: f32, limit: f32) -> f32 { d * (tol / limit) } +/// `v` as the document stores it: rounded to the 8- or 16-bit levels, unchanged in 32-bit float. +/// The sampled colour is read from stored pixels, so the foreground is compared at the same +/// precision; otherwise a foreground between two levels misses its own stored colour (#11903). +fn at_sample_precision(sample: SampleType, v: f32) -> f32 { + let mut bytes = [0u8; 4]; + write_sample(&mut bytes, sample, 0, v); + read_sample(&bytes, sample, 0) +} + /// Erase along `stroke`. The brush opacity is ignored (Photoshop's Background Eraser has none); /// the selection limits the effect. Returns the damaged rectangle; empty when the surface has no /// alpha channel. @@ -90,7 +100,7 @@ pub fn background_eraser_effect(pre: &Surface, bs: &BgEraseSettings) -> Option Vec { from_rgba(&fmt, [c[0], c[1], c[2], 1.0])[..nc].to_vec() }; let swatch = native(bs.background); - let fg = native(bs.foreground); + let fg: Vec = native(bs.foreground).into_iter().map(|v| at_sample_precision(fmt.sample, v)).collect(); let (sampling, limits, protect_foreground) = (bs.sampling, bs.limits, bs.protect_foreground); let mut once: Option>> = None; let match_w = move |d: f32| -> f32 { diff --git a/crates/paint/src/bg_erase_protect_foreground_tests.rs b/crates/paint/src/bg_erase_protect_foreground_tests.rs index 42e3a18c5af..c94604072fb 100644 --- a/crates/paint/src/bg_erase_protect_foreground_tests.rs +++ b/crates/paint/src/bg_erase_protect_foreground_tests.rs @@ -130,10 +130,9 @@ fn find_edges_keeps_the_foreground_colour_itself() { #[test] fn protect_off_is_unchanged() { // The drag without protection, as main gives it before the graded erase of #11901: today's - // pre-stroke matching over overlapping dabs. Pinned so the protection change cannot leak in. - let off = drag(PixelFormat::RGBA8, None); - assert_eq!(off[0], 0); - assert_eq!(off[7], 255); + // pre-stroke matching over overlapping dabs. The whole row is pinned so the protection change + // cannot leak in (#11901 will change it to the reference's 0 30 75 114 156 198 238 255). + assert_eq!(drag(PixelFormat::RGBA8, None), [0, 0, 0, 0, 0, 0, 92, 255]); let mut s = blocks(PixelFormat::RGBA8); let mut t = s.clone(); let on_far = BgEraseSettings { foreground: [0.0, 0.0, 1.0, 1.0], protect_foreground: true, ..settings(None) }; @@ -172,3 +171,37 @@ fn protection_works_in_the_documents_own_channels() { assert_eq!(*v, 1.0, "gray: block {i} kept, {a:?}"); } } + +#[test] +fn the_foreground_is_matched_at_the_documents_precision() { + // Mid grey 0.5 lies between two 8-bit (and 16-bit) levels and is stored one level up, nearer + // white. The stored foreground colour must still count as the foreground, and a foreground + // that is stored as the sampled colour must still protect everything. + let grey = [0.5, 0.5, 0.5, 1.0]; + for mode in [ColorMode::Rgb, ColorMode::Grayscale] { + for sample in [SampleType::U8, SampleType::U16, SampleType::F32] { + let fmt = PixelFormat::new(mode, sample, true); + let bs = BgEraseSettings { + sampling: Sampling::Once, + limits: Limits::FindEdges, + tolerance: 1.0, + protect_foreground: true, + foreground: grey, + ..Default::default() + }; + // White (the sample) next to the foreground grey. + let mut s = Surface::new(fmt); + s.fill_rect(Rect::new(0, 0, 100, 100), &from_rgba(&fmt, [1.0; 4])); + s.fill_rect(Rect::new(100, 0, 200, 100), &from_rgba(&fmt, grey)); + apply_background_eraser(&mut s, &stroke(&[(50.0, 50.0), (150.0, 50.0)]), &bs, None); + assert_eq!(s.rgba(50, 50)[3], 0.0, "{fmt:?}: the sample erased"); + assert_eq!(s.rgba(150, 50)[3], 1.0, "{fmt:?}: the stored foreground colour kept"); + // The foreground grey is also the sample. + let mut s = Surface::new(fmt); + s.fill_rect(Rect::new(0, 0, 200, 100), &from_rgba(&fmt, grey)); + let t = s.clone(); + apply_background_eraser(&mut s, &stroke(&[(50.0, 50.0), (150.0, 50.0)]), &bs, None); + assert_eq!(s, t, "{fmt:?}: a foreground stored as the sample erases nothing"); + } + } +}