diff --git a/crates/algo/src/retouch.rs b/crates/algo/src/retouch.rs index 78b588f787..08a2e63769 100644 --- a/crates/algo/src/retouch.rs +++ b/crates/algo/src/retouch.rs @@ -194,10 +194,22 @@ pub fn local_blur(data: &[f32], w: usize, h: usize, ch: usize, alpha: Option 0 && x + 1 < w && y > 0 && y + 1 < h { - let w_ch = w * ch; - [i - w_ch - ch, i - w_ch, i - w_ch + ch, i - ch, i + ch, i + w_ch - ch, i + w_ch, i + w_ch + ch] - } else { - let get_n_idx = |dx: i32, dy: i32| -> usize { - let nx = (x as i32 + dx).clamp(0, w as i32 - 1) as usize; - let ny = (y as i32 + dy).clamp(0, h as i32 - 1) as usize; - (ny * w + nx) * ch - }; - [ - get_n_idx(-1, -1), - get_n_idx(0, -1), - get_n_idx(1, -1), - get_n_idx(-1, 0), - get_n_idx(1, 0), - get_n_idx(-1, 1), - get_n_idx(0, 1), - get_n_idx(1, 1), - ] - } - } else { - [0; 8] - }; - + let i = (y * w + x0 + ox) * ch; for c in 0..ch { let v = data[i + c]; if Some(c) == alpha { dst[o + c] = v; continue; } - let mut s = v + amount * (v - blur_row[o + c]); - if protect_detail { - let (mut lo, mut hi) = (v, v); - for &n_idx in &offsets { - let nv = data[n_idx + c]; - lo = lo.min(nv); - hi = hi.max(nv); - } - s = s.clamp(lo, hi); - } - dst[o + c] = s; + let d = v - blur_row[o + c]; + // `PROTECT_DETAIL_LIMIT + |d|` is never zero, so this can't divide by zero. + let d = if protect_detail { d * PROTECT_DETAIL_LIMIT / (PROTECT_DETAIL_LIMIT + d.abs()) } else { d }; + dst[o + c] = v + amount * d; } } }; @@ -287,6 +264,10 @@ pub fn local_sharpen( out } +#[cfg(test)] +#[path = "retouch_sharpen_protect_detail_tests.rs"] +mod sharpen_protect_detail_tests; + #[cfg(test)] mod tests { use super::*; @@ -353,10 +334,10 @@ mod tests { let s = local_sharpen(&smooth, w, h, ch, None, win, 1.0, false); let so: Vec = (4..12).flat_map(|y| (4..12).map(move |x| (x, y))).map(|(x, y)| smooth[y * w + x]).collect(); assert!(var(&s) > var(&so)); - // Protect detail never exceeds the local range. + // Protect Detail sharpens too, but moves no pixel by more than its limit per unit of amount. let sp = local_sharpen(&smooth, w, h, ch, None, win, 4.0, true); - let hi = smooth.iter().cloned().fold(0.0, f32::max); - assert!(sp.iter().all(|v| *v <= hi + 1e-6)); + assert!(var(&sp) > var(&so)); + assert!(sp.iter().zip(&so).all(|(a, b)| (a - b).abs() < 4.0 * PROTECT_DETAIL_LIMIT)); } #[test] diff --git a/crates/algo/src/retouch_sharpen_protect_detail_tests.rs b/crates/algo/src/retouch_sharpen_protect_detail_tests.rs new file mode 100644 index 0000000000..efb9871c95 --- /dev/null +++ b/crates/algo/src/retouch_sharpen_protect_detail_tests.rs @@ -0,0 +1,125 @@ +//! Protect Detail in [`local_sharpen`] sharpens gently instead of changing nothing (#12938). +//! +//! The issue's test document, in RGBA like the Sharpen tool's dabs: a grey 96 | grey 160 step and +//! a lone grey-160 pixel in grey 96. A hard 40 px tip covers each test image, so one click is one +//! pass that moves every pixel by `strength · (sharpened − original)`, rounded to 8 bits. The +//! expected values are the reference application's, with the issue's tolerances. + +use super::*; + +const W: usize = 60; +const H: usize = 21; +/// x of the first grey-160 column of the step: x 400 in the issue's document. +const EDGE: usize = 30; + +fn grey(levels: impl Fn(usize, usize) -> f32, w: usize, h: usize) -> Vec { + (0..w * h) + .flat_map(|i| { + let g = levels(i % w, i / w) / 255.0; + [g, g, g, 1.0] + }) + .collect() +} + +fn step() -> Vec { + grey(|x, _| if x < EDGE { 96.0 } else { 160.0 }, W, H) +} + +/// One pass of the tool at `strength` (0–1) over the whole image. +fn pass(data: &[f32], w: usize, h: usize, strength: f32, protect: bool) -> Vec { + let out = local_sharpen(data, w, h, 4, Some(3), (0, 0, w, h), 1.0, protect); + data.iter().zip(&out).map(|(v, s)| v + (s - v) * strength).collect() +} + +/// Red channel of each pixel in 8-bit levels. +fn levels(data: &[f32]) -> Vec { + data.as_chunks::<4>().0.iter().map(|p| (p[0].clamp(0.0, 1.0) * 255.0).round() as i32).collect() +} + +/// Row `y` of the step, as x 400 + `x - EDGE` in the issue's document. +fn at(row: &[i32], x_doc: usize) -> i32 { + row[x_doc + EDGE - 400] +} + +#[test] +fn one_click_on_the_step_gives_a_low_halo_that_follows_strength() { + let row = |strength: f32| levels(&pass(&step(), W, H, strength, true))[H / 2 * W..(H / 2 + 1) * W].to_vec(); + let full = row(1.0); + for (x, want) in [(396, 94), (397, 92), (398, 91), (399, 90), (400, 164), (401, 163), (402, 161)] { + assert!((at(&full, x) - want).abs() <= 3, "100 %: x {x} is {}, want {want} ± 3 ({full:?})", at(&full, x)); + } + let half = row(0.5); + assert!((at(&half, 399) - 93).abs() <= 2 && (at(&half, 400) - 162).abs() <= 2, "50 %: x 399/400 = {}/{}", at(&half, 399), at(&half, 400)); + let quarter = row(0.25); + assert!(at(&quarter, 399) < 96 && at(&quarter, 400) > 160, "25 % still sharpens: {}/{}", at(&quarter, 399), at(&quarter, 400)); + assert_eq!(row(0.01), levels(&step())[..W].to_vec(), "1 % changes nothing"); +} + +#[test] +fn one_click_on_a_lone_pixel_lifts_it_gently() { + let (w, h, c) = (41, 41, 20); + let data = grey(|x, y| if (x, y) == (c, c) { 160.0 } else { 96.0 }, w, h); + let on = levels(&pass(&data, w, h, 1.0, true)); + let off = levels(&pass(&data, w, h, 1.0, false)); + let centre = on[c * w + c]; + assert!((centre - 168).abs() <= 4, "centre {centre}, want 168 ± 4"); + for (dx, dy) in [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)] { + let n = on[(c as i32 + dy) as usize * w + (c as i32 + dx) as usize]; + assert!((93..=95).contains(&n), "neighbour ({dx}, {dy}) is {n}, want 93–95"); + } + let (lift_on, lift_off) = (centre - 160, off[c * w + c] - 160); + assert!(lift_on > 0 && 2 * lift_on < lift_off, "Protect Detail lifts {lift_on}, off lifts {lift_off}"); +} + +#[test] +fn uniform_areas_and_alpha_stay_exactly_as_they_were() { + for g in [0.0, 96.0 / 255.0, 0.5, 1.0, 2.5] { + let data: Vec = (0..12 * 9).flat_map(|i| [g, g * 0.5, 0.25, [0.0, 0.3, 1.0][i % 3]]).collect(); + let out = local_sharpen(&data, 12, 9, 4, Some(3), (0, 0, 12, 9), 1.0, true); + for (o, d) in out.as_chunks::<4>().0.iter().zip(data.as_chunks::<4>().0) { + assert_eq!(o[3].to_bits(), d[3].to_bits(), "alpha unchanged"); + } + let opaque: Vec = (0..12 * 9).flat_map(|_| [g, g * 0.5, 0.25, 1.0]).collect(); + let out = local_sharpen(&opaque, 12, 9, 4, Some(3), (2, 2, 10, 7), 1.0, true); + // Exact up to the Gaussian weights' rounding, far below one 16-bit level. + let same = |a: f32, b: f32| (a - b).abs() < 1e-6; + assert!(out.as_chunks::<4>().0.iter().all(|p| same(p[0], g) && same(p[1], g * 0.5) && same(p[2], 0.25)), "grey {g} unchanged: {out:?}"); + } +} + +#[test] +fn three_drags_widen_the_halo_without_ringing_between_black_and_white() { + // A drag of a 40 px tip at 25 % spacing passes about four dabs over each point; each drag is a + // stroke of its own, rounded to 8 bits when it ends. + let (w, h, edge) = (80, 5, 40); + let mut data = grey(|x, _| if x < edge { 96.0 } else { 160.0 }, w, h); + let mut halos = Vec::new(); + for _ in 0..3 { + for _ in 0..4 { + data = pass(&data, w, h, 1.0, true); + } + data = data.iter().map(|v| (v.clamp(0.0, 1.0) * 255.0).round() / 255.0).collect(); + let row = levels(&data)[h / 2 * w..(h / 2 + 1) * w].to_vec(); + halos.push(row.iter().enumerate().filter(|&(x, &v)| (v - if x < edge { 96 } else { 160 }).abs() >= 2).count()); + // Darker towards the edge on the dark side, lighter towards it on the light side. + for x in edge - 5..edge - 1 { + assert!(row[x] >= row[x + 1], "dark side rises at x {x}: {row:?}"); + } + for x in edge..edge + 4 { + assert!(row[x] >= row[x + 1], "light side rises at x {x}: {row:?}"); + } + assert!(row[..edge].iter().all(|&v| v < 255) && row[edge..].iter().all(|&v| v > 0), "no black–white ringing: {row:?}"); + } + assert!(halos[0] < halos[2], "the halo widens with every drag: {halos:?}"); +} + +#[test] +fn protect_detail_off_keeps_the_sigma_1_unsharp_mask() { + let data = step(); + let blur = local_blur(&data, W, H, 4, Some(3), (0, 0, W, H), 1.0); + let out = local_sharpen(&data, W, H, 4, Some(3), (0, 0, W, H), 1.0, false); + for (i, ((v, b), o)) in data.iter().zip(&blur).zip(&out).enumerate() { + let want = if i % 4 == 3 { *v } else { v + (v - b) }; + assert_eq!(o.to_bits(), want.to_bits(), "sample {i}"); + } +} diff --git a/crates/algo/tests/it/retouch_sharpen_exact.rs b/crates/algo/tests/it/retouch_sharpen_exact.rs index 9e75a261ab..499b60d6ac 100644 --- a/crates/algo/tests/it/retouch_sharpen_exact.rs +++ b/crates/algo/tests/it/retouch_sharpen_exact.rs @@ -1,5 +1,6 @@ -//! Frozen scalar sharpen from main, used as an exact-output oracle. -use photocraft_algo::retouch::{local_blur, local_sharpen}; +//! Frozen scalar sharpen from main, used as an exact-output oracle. Its Protect Detail branch +//! follows #12938: a wider unsharp mask whose differences are soft-limited to 6 levels. +use photocraft_algo::retouch::{PROTECT_DETAIL_SIGMA, local_blur, local_sharpen}; #[test] fn matches_scalar_sharpen_bit_for_bit_across_layouts_edges_and_hdr() { @@ -51,8 +52,9 @@ fn scalar_local_sharpen( if ow == 0 || oh == 0 || ch == 0 { return Vec::new(); } - let blur = local_blur(data, w, h, ch, alpha, win, 1.0); + let blur = local_blur(data, w, h, ch, alpha, win, if protect_detail { PROTECT_DETAIL_SIGMA } else { 1.0 }); let mut out = vec![0.0f32; blur.len()]; + let limit = 6.0f32 / 255.0; for y in y0..y1 { for x in x0..x1 { let o = ((y - y0) * ow + (x - x0)) * ch; @@ -63,18 +65,9 @@ fn scalar_local_sharpen( out[o + c] = v; continue; } - let mut s = v + amount * (v - blur[o + c]); - if protect_detail { - let (mut lo, mut hi) = (v, v); - for (dx, dy) in [(-1i32, -1i32), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)] { - let (nx, ny) = ((x as i32 + dx).clamp(0, w as i32 - 1) as usize, (y as i32 + dy).clamp(0, h as i32 - 1) as usize); - let nv = data[(ny * w + nx) * ch + c]; - lo = lo.min(nv); - hi = hi.max(nv); - } - s = s.clamp(lo, hi); - } - out[o + c] = s; + let d = v - blur[o + c]; + let d = if protect_detail { d * limit / (limit + d.abs()) } else { d }; + out[o + c] = v + amount * d; } } } diff --git a/crates/engine/src/cmd/retouch_cmds/dab.rs b/crates/engine/src/cmd/retouch_cmds/dab.rs index 49b0531cc4..765057062a 100644 --- a/crates/engine/src/cmd/retouch_cmds/dab.rs +++ b/crates/engine/src/cmd/retouch_cmds/dab.rs @@ -209,6 +209,8 @@ impl DabTool { /// How far around each dab the effect reads (Blur and Sharpen read a neighbourhood). fn neighborhood(&self) -> DabNeighborhood { match self { + // Protect Detail sharpens against its own, wider Gaussian (#12938). + Self::Focus { sharpen: true, protect: true, .. } => DabNeighborhood::Halo((photocraft_algo::retouch::PROTECT_DETAIL_SIGMA * 3.0).ceil() as i32 + 1), 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), @@ -241,7 +243,10 @@ impl DabTool { return; } for x in r.x0..r.x1 { - let k = per_dab(fp.at(x, y) * strength, sp); + // Protect Detail applies Strength once per dab, so one click at 50 % + // does half of what 100 % does (#12938). Spread over the overlapping + // dabs (`per_dab`), it did 7 % of it at the default 10 % spacing. + let k = if sharpen && protect { fp.at(x, y) * strength } else { per_dab(fp.at(x, y) * strength, sp) }; if k <= 0.0 { continue; } diff --git a/crates/engine/src/cmd/retouch_cmds/tests.rs b/crates/engine/src/cmd/retouch_cmds/tests.rs index 60cabeeda2..b07de9d765 100644 --- a/crates/engine/src/cmd/retouch_cmds/tests.rs +++ b/crates/engine/src/cmd/retouch_cmds/tests.rs @@ -470,16 +470,31 @@ fn blur_reduces_local_variance_and_sharpen_increases_it() { s.execute("paint.blur", json!({"points": [[5, 15], [25, 15]], "size": 20, "hardness": 100, "strength": 100})).unwrap(); assert!(var(&s, 10) < v0 * 0.5, "depth {depth}: {v0} → {}", var(&s, 10)); assert!((var(&s, 45) - v0).abs() < 1e-3, "outside untouched"); - // Sharpen a low-contrast checkerboard: contrast grows; Protect Detail caps it at the local range. + // Sharpen a low-contrast checkerboard: contrast grows, with Protect Detail too (#12938). let mut s = session(60, 30, depth, "rgb"); paint_layer(&mut s, |x, y| if (x + y) % 2 == 0 { [0.45, 0.45, 0.45, 1.0] } else { [0.55, 0.55, 0.55, 1.0] }); let v0 = var(&s, 10); s.execute("paint.sharpen", json!({"points": [[5, 15], [25, 15]], "size": 20, "hardness": 100, "strength": 100, "protectDetail": false})).unwrap(); assert!(var(&s, 10) > v0 * 1.5, "depth {depth}: {v0} → {}", var(&s, 10)); - // Pinned at 25%: Protect Detail clamps per dab, so denser dabs creep past the range. + // Protect Detail moves a pixel by less than 6 levels per dab; at 25 % spacing four dabs + // pass over each point. s.execute("paint.sharpen", json!({"points": [[35, 15], [55, 15]], "size": 20, "hardness": 100, "strength": 100, "spacing": 25})).unwrap(); let hi = (10..20).flat_map(|y| (40..50).map(move |x| (x, y))).map(|(x, y)| rgba(&s, x, y)[0]).fold(0.0, f32::max); - assert!(hi <= 0.55 + tol(depth), "protect detail: {hi}"); + assert!(hi > 0.55 + tol(depth) && hi <= 0.55 + 4.0 * 6.0 / 255.0 + tol(depth), "protect detail: {hi}"); + } +} + +#[test] +fn protect_detail_click_on_a_step_follows_strength() { + // #12938: one 40 px hard click on a grey 96 | 160 step, Protect Detail on (the default). The + // reference gives x 399/400 = 90/164 at 100 % and 93/162 at 50 %; Strength applies once per dab. + let level = |s: &Session, x| (rgba(s, x, 20)[0] * 255.0).round() as i32; + for (strength, dark, light, tol) in [(100, 90, 164, 3), (50, 93, 162, 2), (1, 96, 160, 0)] { + let mut s = session(80, 40, 8, "rgb"); + paint_layer(&mut s, |x, _| if x < 40 { [96.0 / 255.0, 96.0 / 255.0, 96.0 / 255.0, 1.0] } else { [160.0 / 255.0, 160.0 / 255.0, 160.0 / 255.0, 1.0] }); + s.execute("paint.sharpen", json!({"points": [[40, 20]], "size": 40, "hardness": 100, "strength": strength})).unwrap(); + let (d, l) = (level(&s, 39), level(&s, 40)); + assert!((d - dark).abs() <= tol && (l - light).abs() <= tol, "{strength} %: x 399/400 = {d}/{l}, want {dark}/{light} ± {tol}"); } }