From 541ea0696f152a8dbb06bd712f4fb77861a39bf6 Mon Sep 17 00:00:00 2001 From: Jeremy Hooke Date: Sat, 31 Oct 2026 23:16:18 +1100 Subject: [PATCH 1/7] LR-EDIT-LIGHT-SHADOWS: no bright blocks beside lettering under Shadows From process V2 the Highlights/Shadows base was the edge-aware filter of a separable median of log luminance (radius 0.15 % of the long edge). Dark lettering on a bright panel (a bus number in a 7000 px raw: strokes and gaps about one radius wide) makes every row and column window close to half letter, half panel, so the median picked one tone or the other in rectangles: it filled the gaps between the digits, their counters and the corners where they nearly touch with the letters' tone, and parts of the strokes with the panel's. Shadows +75 then lifted those patches of panel by up to ~1.3 EV into bright yellow blocks, and lifted the strokes unevenly. The base now clamps each value to the quartiles of its window (`local::quartile_clamp_hv`, ranks r - r/2 and r + r/2 of 2r+1; at r = 1 the 3-tap median). A line thinner than about r/2 in an even surround is still a minority of every window and takes the surround's tone, as #632 wants; a window that mixes two tones leaves its pixels alone, and steps stay exact. The #632 twig/stalk tests keep their margins; twig meshes covering ~50 % of their area keep less contrast than under the median (0.69 of Exposure's at -100, as V1). GPU: the kernels count the centre's rank first and select only for pixels outside the band, from the nearer end; the planes stage of a 32 MP render with Shadows went from ~228 ms to ~165 ms. CPU cost unchanged. CPU and GPU match. Lands in place on V2 under the bug-fix rule of docs/process-versions.md (the blocks are output in neither the photo nor the edit), noted there. RENDER_CACHE_VERSION 72 -> 73 so cached thumbnails re-render. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/media/source.rs | 2 +- crates/gpu/src/ctx.rs | 2 +- crates/gpu/src/render.rs | 12 ++-- crates/gpu/src/wgsl/blur.wgsl | 68 ++++++++++++++----- crates/gpu/tests/it/equivalence.rs | 2 +- crates/pipeline/src/local.rs | 59 ++++++++++------- crates/pipeline/src/tests_tone.rs | 101 ++++++++++++++++++++++------- docs/parity-checklist.md | 4 +- docs/process-versions.md | 16 ++++- docs/whats-new.md | 9 +++ 10 files changed, 200 insertions(+), 75 deletions(-) diff --git a/crates/engine/src/media/source.rs b/crates/engine/src/media/source.rs index 3373e12b5c4..08ba806170e 100644 --- a/crates/engine/src/media/source.rs +++ b/crates/engine/src/media/source.rs @@ -1,7 +1,7 @@ use super::{Arc, Deserialize, DevelopSettings, MediaKind, Photo, Rgb32f, Rgba8, Serialize, SourceInfo}; /// Bump when the pipeline's output changes, to invalidate cached thumbnails. -pub const RENDER_CACHE_VERSION: u64 = 72; +pub const RENDER_CACHE_VERSION: u64 = 73; /// Thumbnails render at one of these long edges (so window/cell size changes reuse the cache). pub const THUMB_SIZES: [usize; 4] = [128, 256, 384, 512]; diff --git a/crates/gpu/src/ctx.rs b/crates/gpu/src/ctx.rs index d3e56f74914..e0f8d7ec19e 100644 --- a/crates/gpu/src/ctx.rs +++ b/crates/gpu/src/ctx.rs @@ -30,7 +30,7 @@ const MODULES: &[Module] = &[ Module { src: include_str!("wgsl/blur.wgsl"), bindings: &[("src", false, "f32"), ("dst", true, "f32")], - entries: &["box_h", "box_v", "median_h", "median_v"], + entries: &["box_h", "box_v", "quartile_h", "quartile_v"], }, Module { src: include_str!("wgsl/resize.wgsl"), diff --git a/crates/gpu/src/render.rs b/crates/gpu/src/render.rs index 9d6172d9c36..6a2beb65994 100644 --- a/crates/gpu/src/render.rs +++ b/crates/gpu/src/render.rs @@ -318,25 +318,25 @@ fn guided_coeffs(cx: &mut Cx<'_>, p: &Buf, w: usize, h: usize, sigma: f32, eps: gaussian(cx, &ab, w, h, 2, sigma) } -/// Separable median of a plane (`local::median_hv`). -fn median_hv(cx: &mut Cx<'_>, p: &Buf, w: usize, h: usize, r: usize) -> Buf { +/// Separable interquartile clamp of a plane (`local::quartile_clamp_hv`). +fn quartile_clamp_hv(cx: &mut Cx<'_>, p: &Buf, w: usize, h: usize, r: usize) -> Buf { if r == 0 || w * h == 0 { return cx.copy(p); } let pr = [w as u32, h as u32, 1, r.min(local::BASE_DETAIL_MAX) as u32]; let tmp = cx.gpu.buffer(w * h); - cx.run("median_h", &pr, &[Some(p), Some(&tmp)], groups2(w, h, [16, 16])); + cx.run("quartile_h", &pr, &[Some(p), Some(&tmp)], groups2(w, h, [16, 16])); let out = cx.gpu.buffer(w * h); - cx.run("median_v", &pr, &[Some(&tmp), Some(&out)], groups2(w, h, [16, 16])); + cx.run("quartile_v", &pr, &[Some(&tmp), Some(&out)], groups2(w, h, [16, 16])); out } -/// The highlights/shadows base (`local::tone_base`; `detail` 0: V1, no median). +/// The highlights/shadows base (`local::tone_base`; `detail` 0: V1, no interquartile clamp). fn tone_base(cx: &mut Cx<'_>, l: &Buf, w: usize, h: usize, sigma: f32, detail: usize) -> Buf { if detail == 0 { return guided_fast(cx, l, w, h, sigma, local::BASE_EPS); } - let m = median_hv(cx, l, w, h, detail); + let m = quartile_clamp_hv(cx, l, w, h, detail); guided_fast(cx, &m, w, h, sigma, local::BASE_EPS) } diff --git a/crates/gpu/src/wgsl/blur.wgsl b/crates/gpu/src/wgsl/blur.wgsl index 375fb6d5503..7826aae01e8 100644 --- a/crates/gpu/src/wgsl/blur.wgsl +++ b/crates/gpu/src/wgsl/blur.wgsl @@ -75,28 +75,60 @@ fn box_v(@builtin(global_invocation_id) g: vec3) { } } -// Separable median of a single-channel plane (`lightcraft_pipeline::local::median_hv`): 2r+1 -// taps (r ≤ 24, clamped edges) along a row (median_h) or a column (median_v), one thread per -// pixel. The median is a selection, so the result matches the CPU's bit for bit. +// Separable interquartile clamp of a single-channel plane +// (`lightcraft_pipeline::local::quartile_clamp_hv`): 2r+1 taps (r ≤ 24, clamped edges) along a row +// (quartile_h) or a column (quartile_v), one thread per pixel; the centre value is clamped to the +// window's ranks r - r/2 and r + r/2 (`local::quartile_ranks`). Ranks are selections, so the +// result matches the CPU's bit for bit (signed zeros and NaNs aside: the CPU orders them by +// `f32::total_cmp`). // P: w, h, nc (unused), r. -fn median_of(n: u32, r: u32, v: ptr>) -> f32 { - // partial selection sort up to the middle - for (var i = 0u; i <= r; i++) { - var m = i; - for (var j = i + 1u; j < n; j++) { - if ((*v)[j] < (*v)[m]) { - m = j; +fn quartile_clamp_of(n: u32, r: u32, v: ptr>) -> f32 { + let c = (*v)[r]; + let lo = r - r / 2u; + let hi = r + r / 2u; + // where the centre ranks among its window: most pixels lie inside the band and need no sort + var lt = 0u; + var le = 0u; + for (var j = 0u; j < n; j++) { + lt += select(0u, 1u, (*v)[j] < c); + le += select(0u, 1u, (*v)[j] <= c); + } + if (le <= lo) { + // below the lower rank: select it from the bottom (partial selection sort, ascending) + for (var i = 0u; i <= lo; i++) { + var m = i; + for (var j = i + 1u; j < n; j++) { + if ((*v)[j] < (*v)[m]) { + m = j; + } + } + let t = (*v)[i]; + (*v)[i] = (*v)[m]; + (*v)[m] = t; + } + return (*v)[lo]; + } + if (lt > hi) { + // above the upper rank: select it from the top (partial selection sort, descending) + let top = n - 1u - hi; + for (var i = 0u; i <= top; i++) { + var m = i; + for (var j = i + 1u; j < n; j++) { + if ((*v)[j] > (*v)[m]) { + m = j; + } } + let t = (*v)[i]; + (*v)[i] = (*v)[m]; + (*v)[m] = t; } - let t = (*v)[i]; - (*v)[i] = (*v)[m]; - (*v)[m] = t; + return (*v)[top]; } - return (*v)[r]; + return c; } @compute @workgroup_size(16, 16) -fn median_h(@builtin(global_invocation_id) g: vec3) { +fn quartile_h(@builtin(global_invocation_id) g: vec3) { let w = pu(0u); let h = pu(1u); let r = min(pu(3u), 24u); @@ -110,11 +142,11 @@ fn median_h(@builtin(global_invocation_id) g: vec3) { let x = clamp(i32(g.x + k) - i32(r), 0, i32(w) - 1); v[k] = src[row + u32(x)]; } - dst[row + g.x] = median_of(n, r, &v); + dst[row + g.x] = quartile_clamp_of(n, r, &v); } @compute @workgroup_size(16, 16) -fn median_v(@builtin(global_invocation_id) g: vec3) { +fn quartile_v(@builtin(global_invocation_id) g: vec3) { let w = pu(0u); let h = pu(1u); let r = min(pu(3u), 24u); @@ -127,5 +159,5 @@ fn median_v(@builtin(global_invocation_id) g: vec3) { let y = clamp(i32(g.y + k) - i32(r), 0, i32(h) - 1); v[k] = src[u32(y) * w + g.x]; } - dst[g.y * w + g.x] = median_of(n, r, &v); + dst[g.y * w + g.x] = quartile_clamp_of(n, r, &v); } diff --git a/crates/gpu/tests/it/equivalence.rs b/crates/gpu/tests/it/equivalence.rs index 7432ebb7c8a..8dd28ff8ac2 100644 --- a/crates/gpu/tests/it/equivalence.rs +++ b/crates/gpu/tests/it/equivalence.rs @@ -615,7 +615,7 @@ fn cached_renders_match_uncached() { } /// Issue #632: the Highlights / Shadows base of each process (V1: the edge-aware filter of log -/// luminance; V2: of its fine median, a radius that grows with the render) matches the CPU's, and +/// luminance; V2: of its fine interquartile clamp, a radius that grows with the render) matches the CPU's, and /// a warm cache never hands one process the other's base. #[test] fn highlights_shadows_base_matches_on_every_process() { diff --git a/crates/pipeline/src/local.rs b/crates/pipeline/src/local.rs index 6d09cf7557b..7cdad311f4b 100644 --- a/crates/pipeline/src/local.rs +++ b/crates/pipeline/src/local.rs @@ -283,23 +283,35 @@ pub fn guided_fast(p: &Plane, sigma: f32, eps: f32) -> Plane { guided_apply(p, &ma, &mb) } -/// Separable median (`2r+1` px along each row, then each column; clamped edges). It keeps the -/// steps between regions where they are and removes features thinner than about `r` px. -pub fn median_hv(p: &Plane, r: usize) -> Plane { +/// Separable interquartile clamp (`2r+1` px along each row, then each column; clamped edges): +/// each value is clamped to the ranks [`quartile_ranks`] of its window. A line or speck thinner +/// than about `r/2` px in an even surround is a minority of every window it is in, so it takes +/// the surround's value, as under a median; steps between regions stay where they are. Unlike a +/// median, a window that is a mix of two tones (text, grilles: strokes and gaps about `r` px wide) +/// leaves its pixels as they are instead of deciding for one tone or the other per row and +/// column, which turned the gaps between letters into blocks of the letters' tone (and the +/// strokes into blocks of the background's). At `r = 1` the two ranks meet: a 3-tap median. +pub fn quartile_clamp_hv(p: &Plane, r: usize) -> Plane { if r == 0 || p.data.is_empty() { return p.clone(); } let rows = |src: &Plane| { let mut out = Plane::new(src.width, src.height); - for_rows(&mut out.data, src.width, |y, row| median_row(src.row(y), row, r)); + for_rows(&mut out.data, src.width, |y, row| quartile_clamp_row(src.row(y), row, r)); out }; transpose(&rows(&transpose(&rows(p)))) } -/// Running median of `src` over `2r+1` taps (clamped edges) into `out`: a sorted window that -/// drops the leaving value and inserts the entering one. -fn median_row(src: &[f32], out: &mut [f32], r: usize) { +/// The ranks (0-based, in a sorted window of `2r+1`) a value is clamped to by [`quartile_clamp_hv`]: +/// `r - r/2` and `r + r/2`, about the window's quartiles. +pub fn quartile_ranks(r: usize) -> (usize, usize) { + (r - r / 2, r + r / 2) +} + +/// Running interquartile clamp of `src` over `2r+1` taps (clamped edges) into `out`: a sorted +/// window that drops the leaving value and inserts the entering one. +fn quartile_clamp_row(src: &[f32], out: &mut [f32], r: usize) { let n = src.len(); if n == 0 { return; @@ -308,8 +320,9 @@ fn median_row(src: &[f32], out: &mut [f32], r: usize) { let r_ = r as isize; let mut win: Vec = (-r_..=r_).map(at).collect(); win.sort_unstable(); + let (lo, hi) = quartile_ranks(r); for (x, o) in out.iter_mut().enumerate() { - *o = f32::from_bits(total_key_inv(win[r])); + *o = f32::from_bits(total_key_inv(at(x as isize).clamp(win[lo], win[hi]))); let (old, new) = (at(x as isize - r_), at(x as isize + r_ + 1)); if old != new { // Ranks by counting the smaller keys in one branch-free pass the compiler vectorizes. @@ -357,21 +370,21 @@ fn transpose(p: &Plane) -> Plane { } /// Detail scale of the highlights/shadows base from process V2, as a fraction of the long edge: -/// the base is the edge-aware filter of the [`median_hv`] of log luminance at this radius, so -/// twigs, lines and fine texture brighter or darker than their surroundings take their +/// the base is the edge-aware filter of the [`quartile_clamp_hv`] of log luminance at this radius, +/// so twigs, lines and fine texture brighter or darker than their surroundings take their /// surroundings' shift (and keep their contrast, as with Exposure) while region boundaries stay /// sharp (no halos). V1's base is the edge-aware filter of log luminance itself (issue #632). pub const BASE_DETAIL: f64 = 0.0015; /// Largest [`base_detail_radius`] (px). pub const BASE_DETAIL_MAX: usize = 24; -/// Median radius (px) of the highlights/shadows base at `px_per_long` (see [`BASE_DETAIL`]). +/// Detail radius (px) of the highlights/shadows base at `px_per_long` (see [`BASE_DETAIL`]). pub fn base_detail_radius(px_per_long: f64) -> usize { ((BASE_DETAIL * px_per_long).round().max(0.0) as usize).min(BASE_DETAIL_MAX) } -/// Median radius (px) of the highlights/shadows base of `s`'s rendering process at `px_per_long`: -/// 0 (no median) under V1, [`base_detail_radius`] from V2. +/// Detail radius (px) of the highlights/shadows base of `s`'s rendering process at `px_per_long`: +/// 0 (no clamp) under V1, [`base_detail_radius`] from V2. pub fn tone_base_detail(s: &DevelopSettings, px_per_long: f64) -> usize { match s.process.process() { Process::V1 => 0, @@ -380,12 +393,12 @@ pub fn tone_base_detail(s: &DevelopSettings, px_per_long: f64) -> usize { } /// The highlights/shadows base layer of log luminance `l`: the fast guided filter ([`BASE_EPS`]) -/// of its [`median_hv`] at `detail` px ([`tone_base_detail`]); at 0, of `l` itself (V1). +/// of its [`quartile_clamp_hv`] at `detail` px ([`tone_base_detail`]); at 0, of `l` itself (V1). pub fn tone_base(l: &Plane, sigma: f32, detail: usize) -> Plane { if detail == 0 { return guided_fast(l, sigma, BASE_EPS); } - guided_fast(&median_hv(l, detail), sigma, BASE_EPS) + guided_fast(&quartile_clamp_hv(l, detail), sigma, BASE_EPS) } /// Subsampling step of [`guided_fast`] for `sigma` (1 = no subsampling: the plain guided filter). @@ -517,7 +530,7 @@ pub(crate) struct Planes { /// The image's key without its noise reduction (`Plan::pre_nr_key`). pub pre_nr: u64, pub log_l: Option>, - /// Keyed by its radius, process and median radius ([`BaseKey`]). + /// Keyed by its radius, process and detail radius ([`BaseKey`]). pub base: Option<(BaseKey, Arc)>, pub clarity: Option<(u32, Arc)>, pub texture: Option<(u32, Arc)>, @@ -537,7 +550,7 @@ impl Planes { } /// What the highlights/shadows base plane was computed with: its radius (`f32` bits), the -/// rendering process and the median radius ([`tone_base_detail`]). The base differs between +/// rendering process and the detail radius ([`tone_base_detail`]). The base differs between /// processes, so a photo moved to another one (Update to Current Process, undo) recomputes it. pub type BaseKey = (u32, Process, usize); @@ -576,7 +589,7 @@ pub const CHROMA_SIGMA: f32 = 0.004; #[derive(Clone, Copy, Debug, Default, PartialEq)] pub struct PlaneSigmas { /// Edge-aware base for highlights/shadows ([`tone_base`]: fast guided filter, [`BASE_EPS`]; from - /// process V2 of the [`BASE_DETAIL`] median). + /// process V2 of the [`BASE_DETAIL`] interquartile clamp). pub base: Option, /// Median radius (px) of that base ([`tone_base_detail`]: 0 under V1). pub base_detail: usize, @@ -605,8 +618,8 @@ pub fn plane_sigmas(s: &DevelopSettings, px_per_long: f64, q: Quality) -> PlaneS || s.light.shadows != 0.0 || s.masks.iter().filter(live).any(|m| m.adjust.highlights != 0.0 || m.adjust.shadows != 0.0); // Edge-aware base at ~1.5% of the long edge (EV² epsilon: edges of > ~0.6 EV are preserved) - // From V2 it is taken of the median at 0.15%: lines and texture finer than that are detail, - // not tone (#632). + // From V2 it is taken of the interquartile clamp at 0.15%: lines and texture finer than about + // half that are detail, not tone (#632). let base = tone_active.then(|| { let sigma = (0.015 * ppl).max(1.0); if q == Quality::Draft { sigma.min(24.0) } else { sigma } @@ -949,12 +962,12 @@ mod fast_tests { } #[test] - fn sampled_tone_base_keeps_the_median_before_the_guided_filter() { + fn sampled_tone_base_keeps_the_quartile_clamp_before_the_guided_filter() { let p = Plane::from_fn(73, 51, |x, y| if x % 9 == 0 { 3.0 } else { -4.0 + ((x + y) % 7) as f32 * 0.03 }); for sigma in [6.0, 24.0, 120.0] { for detail in [0, 1, 3, BASE_DETAIL_MAX] { - let median = median_hv(&p, detail); - assert_eq!(tone_base(&p, sigma, detail).data, resized_reference(&median, sigma, BASE_EPS).data, "{sigma}, {detail}"); + let clamped = quartile_clamp_hv(&p, detail); + assert_eq!(tone_base(&p, sigma, detail).data, resized_reference(&clamped, sigma, BASE_EPS).data, "{sigma}, {detail}"); } } } diff --git a/crates/pipeline/src/tests_tone.rs b/crates/pipeline/src/tests_tone.rs index 87e1b659aca..5e9425dd7ab 100644 --- a/crates/pipeline/src/tests_tone.rs +++ b/crates/pipeline/src/tests_tone.rs @@ -157,38 +157,62 @@ fn zero_highlights_and_shadows_render_without_the_base() { } #[test] -fn median_keeps_steps_and_drops_thin_lines() { +fn quartile_clamp_keeps_steps_and_drops_thin_lines() { let p = Plane::from_fn(40, 30, |x, y| if x < 20 { -2.0 } else { 2.0 } + if y == 15 || x == 8 { -3.0 } else { 0.0 }); - let m = local::median_hv(&p, 2); + let m = local::quartile_clamp_hv(&p, 2); for y in 0..30 { for x in 0..40 { let want = if x < 20 { -2.0 } else { 2.0 }; assert_eq!(m.get(x, y), want, "({x}, {y})"); } } - assert_eq!(local::median_hv(&p, 0).data, p.data); + assert_eq!(local::quartile_clamp_hv(&p, 0).data, p.data); assert_eq!(local::base_detail_radius(5568.0), 8); assert_eq!(local::base_detail_radius(300.0), 0); assert_eq!(local::base_detail_radius(1e9), local::BASE_DETAIL_MAX); } +/// `v` clamped to the ranks [`local::quartile_ranks`] of the sorted window `win` of `2r+1` +/// values, in `f32::total_cmp` order (a plain per-pixel reference for the running window). +fn quartile_clamp(v: f32, win: &mut [f32], r: usize) -> f32 { + win.sort_by(f32::total_cmp); + let (lo, hi) = local::quartile_ranks(r); + if v.total_cmp(&win[lo]).is_lt() { + win[lo] + } else if v.total_cmp(&win[hi]).is_gt() { + win[hi] + } else { + v + } +} + +/// [`quartile_clamp`] of every pixel of `p` along rows, then along columns (clamped edges). +fn quartile_clamp_reference(p: &Plane, r: usize) -> Plane { + let (w, h) = (p.width, p.height); + let rows = Plane::from_fn(w, h, |x, y| { + quartile_clamp(p.get(x, y), &mut (0..=2 * r).map(|k| p.get((x + k).saturating_sub(r).min(w - 1), y)).collect::>(), r) + }); + Plane::from_fn(w, h, |x, y| { + quartile_clamp(rows.get(x, y), &mut (0..=2 * r).map(|k| rows.get(x, (y + k).saturating_sub(r).min(h - 1))).collect::>(), r) + }) +} + #[test] -fn median_matches_a_plain_per_pixel_median() { +fn quartile_clamp_matches_a_plain_per_pixel_clamp() { let p = Plane::from_fn(37, 23, |x, y| (((x * 31 + y * 17) * 2_654_435_761usize) % 1000) as f32 / 250.0 - 2.0 + if x % 5 == 0 { 0.5 } else { 0.0 }); - for r in [1, 2, 4, 9] { - let med = |v: &mut Vec| { - v.sort_by(f32::total_cmp); - v[r] - }; - let rows = Plane::from_fn(37, 23, |x, y| med(&mut (0..=2 * r).map(|k| p.get((x + k).saturating_sub(r).min(36), y)).collect())); - let want = Plane::from_fn(37, 23, |x, y| med(&mut (0..=2 * r).map(|k| rows.get(x, (y + k).saturating_sub(r).min(22))).collect())); - assert_eq!(local::median_hv(&p, r).data, want.data, "r {r}"); + for r in [1, 2, 3, 4, 9] { + assert_eq!(local::quartile_clamp_hv(&p, r).data, quartile_clamp_reference(&p, r).data, "r {r}"); } + // the band is the window's quartiles; at r = 1 it closes to the 3-tap median + assert_eq!(local::quartile_ranks(1), (1, 1)); + assert_eq!(local::quartile_ranks(2), (1, 3)); + assert_eq!(local::quartile_ranks(10), (5, 15)); + assert_eq!(local::quartile_ranks(local::BASE_DETAIL_MAX), (12, 36)); } #[test] -fn median_orders_special_values_and_ties_like_total_cmp() { +fn quartile_clamp_orders_special_values_and_ties_like_total_cmp() { // the running window keeps keys in `f32::total_cmp` order: NaNs of either sign, signed zeros, // infinities and long runs of equal values come out bit for bit as a sorted per-pixel window // does, also on planes narrower or shorter than the window @@ -197,20 +221,53 @@ fn median_orders_special_values_and_ties_like_total_cmp() { for (w, h) in [(1, 1), (2, 3), (5, 1), (19, 7), (61, 9)] { let p = Plane::from_fn(w, h, |x, y| special[(x * 7 + y * 3 + (x * y) % 5) % special.len()]); for r in [1, 2, 9, 24] { - let med = |v: &mut Vec| { - v.sort_by(f32::total_cmp); - v[r] - }; - let rows = Plane::from_fn(w, h, |x, y| med(&mut (0..=2 * r).map(|k| p.get((x + k).saturating_sub(r).min(w - 1), y)).collect())); - let want = Plane::from_fn(w, h, |x, y| med(&mut (0..=2 * r).map(|k| rows.get(x, (y + k).saturating_sub(r).min(h - 1))).collect())); - assert_eq!(bits(&local::median_hv(&p, r)), bits(&want), "{w}x{h} r {r}"); + assert_eq!(bits(&local::quartile_clamp_hv(&p, r)), bits(&quartile_clamp_reference(&p, r)), "{w}x{h} r {r}"); + } + } +} + +#[test] +fn gaps_between_letters_keep_their_own_tone_in_the_base() { + // A row of "8"s (two rings each, strokes 1.3 detail radii wide, neighbours 0.8 radii apart), + // dark lettering on a bright panel at the size of a bus number in a 7000 px photo. A separable + // median at this radius filled the gaps between the digits and around their waists with the + // letters' tone: 360 panel pixels sat over 1 EV (up to 2.3 EV) above their base, so Shadows + // lifted them by up to 1.3 EV into bright blocks. The interquartile clamp leaves the panel + // within 0.13 EV of itself. + let ppl = 6960.0; + let r = local::base_detail_radius(ppl); + let rf = r as f32; + let (w, h) = (900usize, 400usize); + let ring = |x: f32, y: f32, cx: f32, cy: f32, outer: f32| { + let d = ((x - cx).powi(2) + (y - cy).powi(2)).sqrt(); + d <= outer && d >= outer - 1.3 * rf + }; + let stroke = |x: usize, y: usize| { + let (x, y) = (x as f32, y as f32); + (0..5).any(|i| { + let cx = 150.0 + i as f32 * 7.4 * rf; + ring(x, y, cx, 200.0 - 2.8 * rf, 2.9 * rf) || ring(x, y, cx, 200.0 + 3.2 * rf, 3.3 * rf) + }) + }; + let l = Plane::from_fn(w, h, |x, y| if stroke(x, y) { -4.6 } else { -1.3 }); + let base = local::tone_base(&l, 0.015 * ppl as f32, r); + // panel pixels at least 3 px from a stroke (the guided filter's own edge softness aside) + let panel = |x: usize, y: usize| !(x.saturating_sub(2)..(x + 3).min(w)).any(|a| (y.saturating_sub(2)..(y + 3).min(h)).any(|b| stroke(a, b))); + let (mut worst, mut under) = (0.0f32, 0usize); + for y in 0..h { + for x in (0..w).filter(|&x| panel(x, y)) { + let d = l.get(x, y) - base.get(x, y); + worst = worst.max(d); + under += usize::from(d > 1.0); } } + assert_eq!(r, 10); + assert!(under == 0 && worst < 0.3, "{under} panel px over 1 EV above their base; worst {worst} EV"); } #[test] fn v1_keeps_the_base_it_always_had() { - // V1's base is the edge-aware filter of log luminance itself, as before process V2: no median + // V1's base is the edge-aware filter of log luminance itself, as before process V2: no clamp // radius, and `tone_base` at 0 is that filter bit for bit let v1 = with_on(Process::V1, "light.highlights", -100.0); assert_eq!(ProcessVersion::legacy().process(), Process::V1); @@ -227,7 +284,7 @@ fn v1_keeps_the_base_it_always_had() { for sg in [1.0f32, 4.5, 18.0] { assert_eq!(local::tone_base(&l, sg, 0).data, local::guided_fast(&l, sg, local::BASE_EPS).data, "sigma {sg}"); } - // V2 takes the median wherever the image is big enough for one + // V2 takes the interquartile clamp wherever the image is big enough for one let v2 = with("light.highlights", -100.0); assert_eq!(local::plane_sigmas(&v2, 5568.0, Quality::Full).base_detail, local::base_detail_radius(5568.0)); assert_eq!(local::plane_sigmas(&v2, 300.0, Quality::Full).base_detail, 0); diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index a9dd7252361..0fd30ea3639 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -180,8 +180,8 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-EDIT-HDR-MODE | HDR editing | P2 | ✅ | `cmd:develop.hdr`, `ctl:hdr.maxEv`, `crates/ui-egui/src/panels/edit.rs` (`hdr_row`) | HDR button next to B&W in the Edit panel header, as Lightroom (Visualize HDR and the headroom limit in the Light panel while it's on); see Q. HDR | | LR-EDIT-LIGHT-EXPOSURE | Exposure | P0 | ✅ | `ctl:light.exposure` | Alt/Option-drag shows highlight clipping (black, clipped channels in colour) | | LR-EDIT-LIGHT-CONTRAST | Contrast | P0 | ✅ | `ctl:light.contrast` | | -| LR-EDIT-LIGHT-HIGHLIGHTS | Highlights | P0 | ✅ | `ctl:light.highlights`, `crates/raw/src/highlight.rs` | sensor-clipped highlights stay neutral when Highlights (or Exposure, Whites) darkens them: fully clipped content is rebuilt to the neutral of the colour model applied after it, partly clipped content takes its colour from reliable unclipped content nearby (not from dark objects, lens fringes or another surface beside it) and white where there is none, and pale partly clipped content (a white sky) turns white on its way to clipping (#523); binned previews and thumbnails decide clipping per sample before averaging (`develop_binned_masked`, `highlight::reconstruct_masked`), so a block with one clipped specular sample keeps its mean instead of jumping to the clip level, which reconstruction turned into green speckles at 500 px (#548) From process V2 the Highlights/Shadows base is the edge-aware filter of the 0.15 %-of-long-edge median of log luminance: twigs and fine texture take their surroundings' shift, so bright areas keep their local contrast as with Exposure (V1's base kept ~0.6 of it at −100, #632); region edges stay sharp. Alt/Option-drag shows highlight clipping | -| LR-EDIT-LIGHT-SHADOWS | Shadows | P0 | ✅ | `ctl:light.shadows` | From process V2, the same base as Highlights: dark areas keep their local contrast when lifted (#632). Alt/Option-drag shows shadow clipping (white, clipped channels in colour) | +| LR-EDIT-LIGHT-HIGHLIGHTS | Highlights | P0 | ✅ | `ctl:light.highlights`, `crates/raw/src/highlight.rs` | sensor-clipped highlights stay neutral when Highlights (or Exposure, Whites) darkens them: fully clipped content is rebuilt to the neutral of the colour model applied after it, partly clipped content takes its colour from reliable unclipped content nearby (not from dark objects, lens fringes or another surface beside it) and white where there is none, and pale partly clipped content (a white sky) turns white on its way to clipping (#523); binned previews and thumbnails decide clipping per sample before averaging (`develop_binned_masked`, `highlight::reconstruct_masked`), so a block with one clipped specular sample keeps its mean instead of jumping to the clip level, which reconstruction turned into green speckles at 500 px (#548) From process V2 the Highlights/Shadows base is the edge-aware filter of the 0.15 %-of-long-edge interquartile clamp of log luminance: twigs and fine texture take their surroundings' shift, so bright areas keep their local contrast as with Exposure (V1's base kept ~0.6 of it at −100, #632); region edges stay sharp, and lettering keeps clean gaps (a median there turned them into blocks of the letters' tone). Alt/Option-drag shows highlight clipping | +| LR-EDIT-LIGHT-SHADOWS | Shadows | P0 | ✅ | `ctl:light.shadows` | From process V2, the same base as Highlights: dark areas keep their local contrast when lifted (#632), and the gaps in dark lettering on a bright panel are not lifted into bright blocks. Alt/Option-drag shows shadow clipping (white, clipped channels in colour) | | LR-EDIT-LIGHT-WHITES | Whites | P0 | ✅ | `ctl:light.whites`, `crates/pipeline/src/visualize.rs` | Alt/Option-drag shows highlight clipping (black, clipped channels in colour) | | LR-EDIT-LIGHT-BLACKS | Blacks | P0 | ✅ | `ctl:light.blacks`, `crates/pipeline/src/visualize.rs` | Alt/Option-drag shows shadow clipping (white, clipped channels in colour) | | LR-EDIT-LIGHT-CURVE-PARAM | Parametric curve | P0 | ✅ | `ctl:curve.highlights`, `ctl:curve.lights`, `ctl:curve.darks`, `ctl:curve.shadows`, `ctl:curve.split*`, `crates/pipeline/src/curve.rs` | the graph draws the renderer's own curve model; dragging the line moves the region under the pointer (one undo step) | diff --git a/docs/process-versions.md b/docs/process-versions.md index 7e6788f11e6..3f55658b452 100644 --- a/docs/process-versions.md +++ b/docs/process-versions.md @@ -8,7 +8,7 @@ stronger Light sliders, issue #196) without changing a single photo someone has | Process | What it changes | |---|---| | **V1** | LightCraft's rendering from before process versions existed. Frozen. | -| **V2** (the latest) | Highlights and Shadows keep fine detail (issue #632): their base layer (`local::tone_base`) is the edge-aware filter of a separable median of log luminance (radius 0.15 % of the long edge, at most 24 px, `local::BASE_DETAIL`) instead of log luminance itself, so twigs, lines and texture take their surroundings' shift and keep their contrast; region edges stay sharp. CPU (`local::prepare`) and GPU prepare branch on `local::tone_base_detail` (0 = no median under V1); the base plane is cached per process (`local::BaseKey`). Renders without Highlights or Shadows (global or local) are the same as V1's. Tone map unchanged. | +| **V2** (the latest) | Highlights and Shadows keep fine detail (issue #632): their base layer (`local::tone_base`) is the edge-aware filter of a separable interquartile clamp of log luminance (`local::quartile_clamp_hv`: each value clamped to the quartiles of its window, radius 0.15 % of the long edge, at most 24 px, `local::BASE_DETAIL`) instead of log luminance itself, so twigs, lines and texture take their surroundings' shift and keep their contrast; region edges stay sharp. CPU (`local::prepare`) and GPU prepare branch on `local::tone_base_detail` (0 = no clamp under V1); the base plane is cached per process (`local::BaseKey`). Renders without Highlights or Shadows (global or local) are the same as V1's. Tone map unchanged. | ## The rule @@ -34,6 +34,20 @@ exports. Existing AI masks become 1–2 px tighter at a subject's edges, on ever inside, their outside and edges without contrast in the photo are unchanged. It landed in place as a bug fix: the outline is output that isn't in the photo nor in the edit, not a look anyone chose. +**Lettering under Highlights and Shadows** (V2) no longer grows blocks of the wrong tone. V2's base +was first the edge-aware filter of a separable median. Dark lettering on a bright panel (a bus +number, a sign) has strokes and gaps about as wide as the median's radius, so each row and column +window was close to half letter and half panel, and the median picked one tone or the other in +rectangles: it filled the gaps between the letters and their counters with the letters' tone, and +parts of the strokes with the panel's. Shadows then lifted those patches of panel by over 1 EV, into +bright blocks beside the letters, and left the strokes lifted unevenly. The base now clamps each +value to the quartiles of its window instead (`local::quartile_clamp_hv`). Thin lines in an even +surround still take the surround's tone, as #632 wants; a window that mixes two tones leaves its +pixels alone. V2 renders with Highlights or Shadows change only on detail about as fine as the +radius (lettering, grilles, foliage against the sky); twig meshes that cover about half their +area keep somewhat less contrast than under the median. It landed in place as a bug fix: the blocks +are output that is neither in the photo nor in the edit. + ## Adding a process 1. Add a variant to `Process` (`V2`), append it to `Process::ALL` (oldest first), give it its number in diff --git a/docs/whats-new.md b/docs/whats-new.md index 2179a4a0f4f..902f59ec1a9 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -1,5 +1,14 @@ # What's new in LightCraft +## 2026-10-31 + +### Shadows no longer brightens blocks beside lettering +- Raising Shadows on a photo with dark lettering on a bright panel, such as the number on a bus, brightened rectangles + beside the letters: the gaps between them, their insides and the corners where they nearly touch, while the letters + themselves turned uneven. Highlights could do the same to light lettering on a darker panel. The gaps now keep the + panel's tone and the letters lift evenly. Photos on process 2 with Highlights or Shadows set change slightly in fine + detail such as lettering, grilles and foliage against the sky; nothing else changes. + ## 2026-10-30 ### A keyboard shortcut for Clear Color Label From 84f7819e0e5c5c86e58f5afcf05d20677ec6b257 Mon Sep 17 00:00:00 2001 From: Jeremy Hooke Date: Sat, 31 Oct 2026 23:43:26 +1100 Subject: [PATCH 2/7] LR-EDIT-LIGHT-SHADOWS: leave the lettering fix out of What's New Render-quality fixes landed in place are recorded in docs/process-versions.md (as #3272 was), not in the release notes. Co-Authored-By: Claude Opus 5.5 --- docs/whats-new.md | 9 --------- 1 file changed, 9 deletions(-) diff --git a/docs/whats-new.md b/docs/whats-new.md index 902f59ec1a9..2179a4a0f4f 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -1,14 +1,5 @@ # What's new in LightCraft -## 2026-10-31 - -### Shadows no longer brightens blocks beside lettering -- Raising Shadows on a photo with dark lettering on a bright panel, such as the number on a bus, brightened rectangles - beside the letters: the gaps between them, their insides and the corners where they nearly touch, while the letters - themselves turned uneven. Highlights could do the same to light lettering on a darker panel. The gaps now keep the - panel's tone and the letters lift evenly. Photos on process 2 with Highlights or Shadows set change slightly in fine - detail such as lettering, grilles and foliage against the sky; nothing else changes. - ## 2026-10-30 ### A keyboard shortcut for Clear Color Label From 73854d9a119f8c1a6a2fce48c8f7dad97e6b5791 Mon Sep 17 00:00:00 2001 From: Jeremy Hooke Date: Sun, 1 Nov 2026 01:05:33 +1100 Subject: [PATCH 3/7] LR-EDIT-LIGHT-SHADOWS: keep #632's thin detail; clamp between two medians The interquartile clamp fixed the lettering but stopped treating isolated lines between r/2 and r px wide as detail: on a corpus Sony A7 III (shadows +100) twigs of 3-6 px against a dark wall were lifted less than the wall, flattening them as V1 did. Light lines 6-10 px wide leaked 0.3-0.6 of the way into the base (the median: none). A fixed window can't tell an isolated line from the gap between two strokes; a wider neighbourhood can (a twig's is mostly wall, a gap's is mostly panel). `local::detail_free` therefore clamps each value between its separable median at r (main's `median_hv`) and the median of a 3x wider neighbourhood (the median at r of a box-downscaled copy, enlarged bilinearly). Both medians on the same side of the pixel (a twig, a speck): it takes the nearer one. They disagree (a gap between strokes): it keeps its own value. Steps stay exact (the fine median keeps them). - Lettering test: 0 panel px over 1 EV (median: 360; worst 0.8 EV). - New test: isolated lines of 1-9 px stay out of the base as under the median; the quartile clamp fails it (6 px line 0.31 into the base). - GPU: main's median kernels back, the coarse median through the existing box/bilinear resize, and a `clamp_between_k` map kernel. CPU and GPU match (max 1 level). - 32 MP render with Shadows: GPU planes ~231 -> ~254 ms, CPU base ~400 -> ~465 ms; the same +10 % / +14 % on an ISO 3200 file. - Corpus A/B (451 pinned raws x Shadows +100 / Highlights -100, old vs new, full size): no failures; RMSE median 0.18 % / 0.10 %, max 0.86 %; worst 8x8 block median 10 / 7 levels, max 61. The 22 largest local changes inspected show no new artefacts, and one more instance of the bug fixed (a bright block in the gap between two posts, Hasselblad coverage-6568). Co-Authored-By: Claude Opus 5.5 --- crates/gpu/src/ctx.rs | 3 +- crates/gpu/src/render.rs | 29 +++++-- crates/gpu/src/wgsl/blur.wgsl | 68 ++++----------- crates/gpu/src/wgsl/map.wgsl | 19 ++++ crates/gpu/tests/it/equivalence.rs | 2 +- crates/pipeline/src/local.rs | 101 ++++++++++++++-------- crates/pipeline/src/tests_tone.rs | 134 +++++++++++++++++------------ docs/parity-checklist.md | 2 +- docs/process-versions.md | 22 ++--- 9 files changed, 218 insertions(+), 162 deletions(-) diff --git a/crates/gpu/src/ctx.rs b/crates/gpu/src/ctx.rs index e0f8d7ec19e..a3255b2d787 100644 --- a/crates/gpu/src/ctx.rs +++ b/crates/gpu/src/ctx.rs @@ -30,7 +30,7 @@ const MODULES: &[Module] = &[ Module { src: include_str!("wgsl/blur.wgsl"), bindings: &[("src", false, "f32"), ("dst", true, "f32")], - entries: &["box_h", "box_v", "quartile_h", "quartile_v"], + entries: &["box_h", "box_v", "median_h", "median_v"], }, Module { src: include_str!("wgsl/resize.wgsl"), @@ -46,6 +46,7 @@ const MODULES: &[Module] = &[ "guided_pre", "guided_ab", "guided_apply", + "clamp_between_k", "wb_k", "nr_lum", "chroma_k", diff --git a/crates/gpu/src/render.rs b/crates/gpu/src/render.rs index 6a2beb65994..bb45a985729 100644 --- a/crates/gpu/src/render.rs +++ b/crates/gpu/src/render.rs @@ -318,28 +318,45 @@ fn guided_coeffs(cx: &mut Cx<'_>, p: &Buf, w: usize, h: usize, sigma: f32, eps: gaussian(cx, &ab, w, h, 2, sigma) } -/// Separable interquartile clamp of a plane (`local::quartile_clamp_hv`). -fn quartile_clamp_hv(cx: &mut Cx<'_>, p: &Buf, w: usize, h: usize, r: usize) -> Buf { +/// Separable median of a plane (`local::median_hv`). +fn median_hv(cx: &mut Cx<'_>, p: &Buf, w: usize, h: usize, r: usize) -> Buf { if r == 0 || w * h == 0 { return cx.copy(p); } let pr = [w as u32, h as u32, 1, r.min(local::BASE_DETAIL_MAX) as u32]; let tmp = cx.gpu.buffer(w * h); - cx.run("quartile_h", &pr, &[Some(p), Some(&tmp)], groups2(w, h, [16, 16])); + cx.run("median_h", &pr, &[Some(p), Some(&tmp)], groups2(w, h, [16, 16])); let out = cx.gpu.buffer(w * h); - cx.run("quartile_v", &pr, &[Some(&tmp), Some(&out)], groups2(w, h, [16, 16])); + cx.run("median_v", &pr, &[Some(&tmp), Some(&out)], groups2(w, h, [16, 16])); out } -/// The highlights/shadows base (`local::tone_base`; `detail` 0: V1, no interquartile clamp). +/// The highlights/shadows base (`local::tone_base`; `detail` 0: V1, no detail removal). fn tone_base(cx: &mut Cx<'_>, l: &Buf, w: usize, h: usize, sigma: f32, detail: usize) -> Buf { if detail == 0 { return guided_fast(cx, l, w, h, sigma, local::BASE_EPS); } - let m = quartile_clamp_hv(cx, l, w, h, detail); + let m = detail_free(cx, l, w, h, detail); guided_fast(cx, &m, w, h, sigma, local::BASE_EPS) } +/// Log luminance without detail finer than `r` px (`local::detail_free`): clamped between its +/// median at `r` and the median of a `local::BASE_COARSE_STEP`× downscaled copy, enlarged. +fn detail_free(cx: &mut Cx<'_>, l: &Buf, w: usize, h: usize, r: usize) -> Buf { + if r == 0 || w * h == 0 { + return cx.copy(l); + } + let fine = median_hv(cx, l, w, h, r); + let s = local::BASE_COARSE_STEP; + let (lw, lh) = (w.div_ceil(s).max(1), h.div_ceil(s).max(1)); + let lo = resize(cx, l, (w, h), (lw, lh), 1, Filter::Box); + let lo_median = median_hv(cx, &lo, lw, lh, r); + let coarse = resize(cx, &lo_median, (lw, lh), (w, h), 1, Filter::Bilinear); + let out = cx.gpu.buffer(w * h); + map(cx, "clamp_between_k", w * h, &[], [Some(l), Some(&fine), Some(&coarse)], &out); + out +} + /// Fast guided filter (`local::guided_fast`): coefficients on a subsampled grid. fn guided_fast(cx: &mut Cx<'_>, p: &Buf, w: usize, h: usize, sigma: f32, eps: f32) -> Buf { let s = local::guided_fast_step(sigma); diff --git a/crates/gpu/src/wgsl/blur.wgsl b/crates/gpu/src/wgsl/blur.wgsl index 7826aae01e8..375fb6d5503 100644 --- a/crates/gpu/src/wgsl/blur.wgsl +++ b/crates/gpu/src/wgsl/blur.wgsl @@ -75,60 +75,28 @@ fn box_v(@builtin(global_invocation_id) g: vec3) { } } -// Separable interquartile clamp of a single-channel plane -// (`lightcraft_pipeline::local::quartile_clamp_hv`): 2r+1 taps (r ≤ 24, clamped edges) along a row -// (quartile_h) or a column (quartile_v), one thread per pixel; the centre value is clamped to the -// window's ranks r - r/2 and r + r/2 (`local::quartile_ranks`). Ranks are selections, so the -// result matches the CPU's bit for bit (signed zeros and NaNs aside: the CPU orders them by -// `f32::total_cmp`). +// Separable median of a single-channel plane (`lightcraft_pipeline::local::median_hv`): 2r+1 +// taps (r ≤ 24, clamped edges) along a row (median_h) or a column (median_v), one thread per +// pixel. The median is a selection, so the result matches the CPU's bit for bit. // P: w, h, nc (unused), r. -fn quartile_clamp_of(n: u32, r: u32, v: ptr>) -> f32 { - let c = (*v)[r]; - let lo = r - r / 2u; - let hi = r + r / 2u; - // where the centre ranks among its window: most pixels lie inside the band and need no sort - var lt = 0u; - var le = 0u; - for (var j = 0u; j < n; j++) { - lt += select(0u, 1u, (*v)[j] < c); - le += select(0u, 1u, (*v)[j] <= c); - } - if (le <= lo) { - // below the lower rank: select it from the bottom (partial selection sort, ascending) - for (var i = 0u; i <= lo; i++) { - var m = i; - for (var j = i + 1u; j < n; j++) { - if ((*v)[j] < (*v)[m]) { - m = j; - } - } - let t = (*v)[i]; - (*v)[i] = (*v)[m]; - (*v)[m] = t; - } - return (*v)[lo]; - } - if (lt > hi) { - // above the upper rank: select it from the top (partial selection sort, descending) - let top = n - 1u - hi; - for (var i = 0u; i <= top; i++) { - var m = i; - for (var j = i + 1u; j < n; j++) { - if ((*v)[j] > (*v)[m]) { - m = j; - } +fn median_of(n: u32, r: u32, v: ptr>) -> f32 { + // partial selection sort up to the middle + for (var i = 0u; i <= r; i++) { + var m = i; + for (var j = i + 1u; j < n; j++) { + if ((*v)[j] < (*v)[m]) { + m = j; } - let t = (*v)[i]; - (*v)[i] = (*v)[m]; - (*v)[m] = t; } - return (*v)[top]; + let t = (*v)[i]; + (*v)[i] = (*v)[m]; + (*v)[m] = t; } - return c; + return (*v)[r]; } @compute @workgroup_size(16, 16) -fn quartile_h(@builtin(global_invocation_id) g: vec3) { +fn median_h(@builtin(global_invocation_id) g: vec3) { let w = pu(0u); let h = pu(1u); let r = min(pu(3u), 24u); @@ -142,11 +110,11 @@ fn quartile_h(@builtin(global_invocation_id) g: vec3) { let x = clamp(i32(g.x + k) - i32(r), 0, i32(w) - 1); v[k] = src[row + u32(x)]; } - dst[row + g.x] = quartile_clamp_of(n, r, &v); + dst[row + g.x] = median_of(n, r, &v); } @compute @workgroup_size(16, 16) -fn quartile_v(@builtin(global_invocation_id) g: vec3) { +fn median_v(@builtin(global_invocation_id) g: vec3) { let w = pu(0u); let h = pu(1u); let r = min(pu(3u), 24u); @@ -159,5 +127,5 @@ fn quartile_v(@builtin(global_invocation_id) g: vec3) { let y = clamp(i32(g.y + k) - i32(r), 0, i32(h) - 1); v[k] = src[u32(y) * w + g.x]; } - dst[g.y * w + g.x] = quartile_clamp_of(n, r, &v); + dst[g.y * w + g.x] = median_of(n, r, &v); } diff --git a/crates/gpu/src/wgsl/map.wgsl b/crates/gpu/src/wgsl/map.wgsl index fc8eebecfec..9b7ada411d0 100644 --- a/crates/gpu/src/wgsl/map.wgsl +++ b/crates/gpu/src/wgsl/map.wgsl @@ -70,6 +70,25 @@ fn guided_apply(@builtin(global_invocation_id) g: vec3, @builtin(num_workgr dst[i] = b[2u * i] * a[i] + b[2u * i + 1u]; } +// `clamp_between` (`local::detail_free`): a clamped between b and c, in either order. +@compute @workgroup_size(256) +fn clamp_between_k(@builtin(global_invocation_id) g: vec3, @builtin(num_workgroups) nw: vec3) { + let i = lin_index(g, nw); + if (i >= pu(0u)) { + return; + } + let lo = min(b[i], c[i]); + let hi = max(b[i], c[i]); + let v = a[i]; + if (v < lo) { + dst[i] = lo; + } else if (v > hi) { + dst[i] = hi; + } else { + dst[i] = v; + } +} + // Cross guided filter (`masks::guided_cross`), a: guide, b: input. P[1] = 0: (guide, input); // 1: (guide·input, guide²). @compute @workgroup_size(256) diff --git a/crates/gpu/tests/it/equivalence.rs b/crates/gpu/tests/it/equivalence.rs index 8dd28ff8ac2..f8192675ae8 100644 --- a/crates/gpu/tests/it/equivalence.rs +++ b/crates/gpu/tests/it/equivalence.rs @@ -615,7 +615,7 @@ fn cached_renders_match_uncached() { } /// Issue #632: the Highlights / Shadows base of each process (V1: the edge-aware filter of log -/// luminance; V2: of its fine interquartile clamp, a radius that grows with the render) matches the CPU's, and +/// luminance; V2: of its detail-free plane, a radius that grows with the render) matches the CPU's, and /// a warm cache never hands one process the other's base. #[test] fn highlights_shadows_base_matches_on_every_process() { diff --git a/crates/pipeline/src/local.rs b/crates/pipeline/src/local.rs index 7cdad311f4b..0467464eeb1 100644 --- a/crates/pipeline/src/local.rs +++ b/crates/pipeline/src/local.rs @@ -283,35 +283,23 @@ pub fn guided_fast(p: &Plane, sigma: f32, eps: f32) -> Plane { guided_apply(p, &ma, &mb) } -/// Separable interquartile clamp (`2r+1` px along each row, then each column; clamped edges): -/// each value is clamped to the ranks [`quartile_ranks`] of its window. A line or speck thinner -/// than about `r/2` px in an even surround is a minority of every window it is in, so it takes -/// the surround's value, as under a median; steps between regions stay where they are. Unlike a -/// median, a window that is a mix of two tones (text, grilles: strokes and gaps about `r` px wide) -/// leaves its pixels as they are instead of deciding for one tone or the other per row and -/// column, which turned the gaps between letters into blocks of the letters' tone (and the -/// strokes into blocks of the background's). At `r = 1` the two ranks meet: a 3-tap median. -pub fn quartile_clamp_hv(p: &Plane, r: usize) -> Plane { +/// Separable median (`2r+1` px along each row, then each column; clamped edges). It keeps the +/// steps between regions where they are and removes features thinner than about `r` px. +pub fn median_hv(p: &Plane, r: usize) -> Plane { if r == 0 || p.data.is_empty() { return p.clone(); } let rows = |src: &Plane| { let mut out = Plane::new(src.width, src.height); - for_rows(&mut out.data, src.width, |y, row| quartile_clamp_row(src.row(y), row, r)); + for_rows(&mut out.data, src.width, |y, row| median_row(src.row(y), row, r)); out }; transpose(&rows(&transpose(&rows(p)))) } -/// The ranks (0-based, in a sorted window of `2r+1`) a value is clamped to by [`quartile_clamp_hv`]: -/// `r - r/2` and `r + r/2`, about the window's quartiles. -pub fn quartile_ranks(r: usize) -> (usize, usize) { - (r - r / 2, r + r / 2) -} - -/// Running interquartile clamp of `src` over `2r+1` taps (clamped edges) into `out`: a sorted -/// window that drops the leaving value and inserts the entering one. -fn quartile_clamp_row(src: &[f32], out: &mut [f32], r: usize) { +/// Running median of `src` over `2r+1` taps (clamped edges) into `out`: a sorted window that +/// drops the leaving value and inserts the entering one. +fn median_row(src: &[f32], out: &mut [f32], r: usize) { let n = src.len(); if n == 0 { return; @@ -320,9 +308,8 @@ fn quartile_clamp_row(src: &[f32], out: &mut [f32], r: usize) { let r_ = r as isize; let mut win: Vec = (-r_..=r_).map(at).collect(); win.sort_unstable(); - let (lo, hi) = quartile_ranks(r); for (x, o) in out.iter_mut().enumerate() { - *o = f32::from_bits(total_key_inv(at(x as isize).clamp(win[lo], win[hi]))); + *o = f32::from_bits(total_key_inv(win[r])); let (old, new) = (at(x as isize - r_), at(x as isize + r_ + 1)); if old != new { // Ranks by counting the smaller keys in one branch-free pass the compiler vectorizes. @@ -370,21 +357,21 @@ fn transpose(p: &Plane) -> Plane { } /// Detail scale of the highlights/shadows base from process V2, as a fraction of the long edge: -/// the base is the edge-aware filter of the [`quartile_clamp_hv`] of log luminance at this radius, -/// so twigs, lines and fine texture brighter or darker than their surroundings take their +/// the base is the edge-aware filter of the [`detail_free`] log luminance at this radius, so +/// twigs, lines and fine texture brighter or darker than their surroundings take their /// surroundings' shift (and keep their contrast, as with Exposure) while region boundaries stay /// sharp (no halos). V1's base is the edge-aware filter of log luminance itself (issue #632). pub const BASE_DETAIL: f64 = 0.0015; /// Largest [`base_detail_radius`] (px). pub const BASE_DETAIL_MAX: usize = 24; -/// Detail radius (px) of the highlights/shadows base at `px_per_long` (see [`BASE_DETAIL`]). +/// Median radius (px) of the highlights/shadows base at `px_per_long` (see [`BASE_DETAIL`]). pub fn base_detail_radius(px_per_long: f64) -> usize { ((BASE_DETAIL * px_per_long).round().max(0.0) as usize).min(BASE_DETAIL_MAX) } -/// Detail radius (px) of the highlights/shadows base of `s`'s rendering process at `px_per_long`: -/// 0 (no clamp) under V1, [`base_detail_radius`] from V2. +/// Median radius (px) of the highlights/shadows base of `s`'s rendering process at `px_per_long`: +/// 0 (no median) under V1, [`base_detail_radius`] from V2. pub fn tone_base_detail(s: &DevelopSettings, px_per_long: f64) -> usize { match s.process.process() { Process::V1 => 0, @@ -393,12 +380,54 @@ pub fn tone_base_detail(s: &DevelopSettings, px_per_long: f64) -> usize { } /// The highlights/shadows base layer of log luminance `l`: the fast guided filter ([`BASE_EPS`]) -/// of its [`quartile_clamp_hv`] at `detail` px ([`tone_base_detail`]); at 0, of `l` itself (V1). +/// of its [`detail_free`] plane at `detail` px ([`tone_base_detail`]); at 0, of `l` itself (V1). pub fn tone_base(l: &Plane, sigma: f32, detail: usize) -> Plane { if detail == 0 { return guided_fast(l, sigma, BASE_EPS); } - guided_fast(&quartile_clamp_hv(l, detail), sigma, BASE_EPS) + guided_fast(&detail_free(l, detail), sigma, BASE_EPS) +} + +/// Downscale factor of the coarse median in [`detail_free`]: its radius at full size is this many +/// times the fine one's. +pub const BASE_COARSE_STEP: usize = 3; + +/// Log luminance `l` without detail finer than `r` px (process V2's highlights/shadows base takes +/// its edge-aware filter): each value moves toward its [`median_hv`] at `r` only as far as the +/// median of a [`BASE_COARSE_STEP`]× wider neighbourhood agrees (`l` clamped between the two). +/// A twig, line or speck in an even surround has both medians on the surround's side and takes +/// its tone, as #632 wants. The gap between two letter strokes, which a median at `r` fills with the +/// strokes' tone, sits in a wider neighbourhood mostly of the panel's tone: the two medians +/// disagree and the gap keeps its own. The coarse median is taken at `r` of a box-downscaled copy and +/// enlarged bilinearly, like [`guided_fast`]'s coefficients. +pub fn detail_free(l: &Plane, r: usize) -> Plane { + use lightcraft_raster::resample::{Filter, resize}; + if r == 0 || l.data.is_empty() { + return l.clone(); + } + let (w, h) = (l.width, l.height); + let fine = median_hv(l, r); + let (lw, lh) = (w.div_ceil(BASE_COARSE_STEP).max(1), h.div_ceil(BASE_COARSE_STEP).max(1)); + let coarse = resize(&median_hv(&resize(l, lw, lh, Filter::Box), r), w, h, Filter::Bilinear); + let mut out = Plane::new(w, h); + for_rows(&mut out.data, w, |y, row| { + for (((o, &v), &a), &b) in row.iter_mut().zip(l.row(y)).zip(fine.row(y)).zip(coarse.row(y)) { + *o = clamp_between(v, a, b); + } + }); + out +} + +/// `v` clamped between `a` and `b` (in either order); a NaN bound is ignored, not a panic. +fn clamp_between(v: f32, a: f32, b: f32) -> f32 { + let (lo, hi) = (a.min(b), a.max(b)); + if v < lo { + lo + } else if v > hi { + hi + } else { + v + } } /// Subsampling step of [`guided_fast`] for `sigma` (1 = no subsampling: the plain guided filter). @@ -530,7 +559,7 @@ pub(crate) struct Planes { /// The image's key without its noise reduction (`Plan::pre_nr_key`). pub pre_nr: u64, pub log_l: Option>, - /// Keyed by its radius, process and detail radius ([`BaseKey`]). + /// Keyed by its radius, process and median radius ([`BaseKey`]). pub base: Option<(BaseKey, Arc)>, pub clarity: Option<(u32, Arc)>, pub texture: Option<(u32, Arc)>, @@ -550,7 +579,7 @@ impl Planes { } /// What the highlights/shadows base plane was computed with: its radius (`f32` bits), the -/// rendering process and the detail radius ([`tone_base_detail`]). The base differs between +/// rendering process and the median radius ([`tone_base_detail`]). The base differs between /// processes, so a photo moved to another one (Update to Current Process, undo) recomputes it. pub type BaseKey = (u32, Process, usize); @@ -589,7 +618,7 @@ pub const CHROMA_SIGMA: f32 = 0.004; #[derive(Clone, Copy, Debug, Default, PartialEq)] pub struct PlaneSigmas { /// Edge-aware base for highlights/shadows ([`tone_base`]: fast guided filter, [`BASE_EPS`]; from - /// process V2 of the [`BASE_DETAIL`] interquartile clamp). + /// process V2 of its [`detail_free`] plane at [`BASE_DETAIL`]). pub base: Option, /// Median radius (px) of that base ([`tone_base_detail`]: 0 under V1). pub base_detail: usize, @@ -618,8 +647,8 @@ pub fn plane_sigmas(s: &DevelopSettings, px_per_long: f64, q: Quality) -> PlaneS || s.light.shadows != 0.0 || s.masks.iter().filter(live).any(|m| m.adjust.highlights != 0.0 || m.adjust.shadows != 0.0); // Edge-aware base at ~1.5% of the long edge (EV² epsilon: edges of > ~0.6 EV are preserved) - // From V2 it is taken of the interquartile clamp at 0.15%: lines and texture finer than about - // half that are detail, not tone (#632). + // From V2 it is taken of the median at 0.15%: lines and texture finer than that are detail, + // not tone (#632). let base = tone_active.then(|| { let sigma = (0.015 * ppl).max(1.0); if q == Quality::Draft { sigma.min(24.0) } else { sigma } @@ -962,12 +991,12 @@ mod fast_tests { } #[test] - fn sampled_tone_base_keeps_the_quartile_clamp_before_the_guided_filter() { + fn sampled_tone_base_keeps_the_detail_free_plane_before_the_guided_filter() { let p = Plane::from_fn(73, 51, |x, y| if x % 9 == 0 { 3.0 } else { -4.0 + ((x + y) % 7) as f32 * 0.03 }); for sigma in [6.0, 24.0, 120.0] { for detail in [0, 1, 3, BASE_DETAIL_MAX] { - let clamped = quartile_clamp_hv(&p, detail); - assert_eq!(tone_base(&p, sigma, detail).data, resized_reference(&clamped, sigma, BASE_EPS).data, "{sigma}, {detail}"); + let free = detail_free(&p, detail); + assert_eq!(tone_base(&p, sigma, detail).data, resized_reference(&free, sigma, BASE_EPS).data, "{sigma}, {detail}"); } } } diff --git a/crates/pipeline/src/tests_tone.rs b/crates/pipeline/src/tests_tone.rs index 5e9425dd7ab..6e709909ccd 100644 --- a/crates/pipeline/src/tests_tone.rs +++ b/crates/pipeline/src/tests_tone.rs @@ -157,62 +157,38 @@ fn zero_highlights_and_shadows_render_without_the_base() { } #[test] -fn quartile_clamp_keeps_steps_and_drops_thin_lines() { +fn median_keeps_steps_and_drops_thin_lines() { let p = Plane::from_fn(40, 30, |x, y| if x < 20 { -2.0 } else { 2.0 } + if y == 15 || x == 8 { -3.0 } else { 0.0 }); - let m = local::quartile_clamp_hv(&p, 2); + let m = local::median_hv(&p, 2); for y in 0..30 { for x in 0..40 { let want = if x < 20 { -2.0 } else { 2.0 }; assert_eq!(m.get(x, y), want, "({x}, {y})"); } } - assert_eq!(local::quartile_clamp_hv(&p, 0).data, p.data); + assert_eq!(local::median_hv(&p, 0).data, p.data); assert_eq!(local::base_detail_radius(5568.0), 8); assert_eq!(local::base_detail_radius(300.0), 0); assert_eq!(local::base_detail_radius(1e9), local::BASE_DETAIL_MAX); } -/// `v` clamped to the ranks [`local::quartile_ranks`] of the sorted window `win` of `2r+1` -/// values, in `f32::total_cmp` order (a plain per-pixel reference for the running window). -fn quartile_clamp(v: f32, win: &mut [f32], r: usize) -> f32 { - win.sort_by(f32::total_cmp); - let (lo, hi) = local::quartile_ranks(r); - if v.total_cmp(&win[lo]).is_lt() { - win[lo] - } else if v.total_cmp(&win[hi]).is_gt() { - win[hi] - } else { - v - } -} - -/// [`quartile_clamp`] of every pixel of `p` along rows, then along columns (clamped edges). -fn quartile_clamp_reference(p: &Plane, r: usize) -> Plane { - let (w, h) = (p.width, p.height); - let rows = Plane::from_fn(w, h, |x, y| { - quartile_clamp(p.get(x, y), &mut (0..=2 * r).map(|k| p.get((x + k).saturating_sub(r).min(w - 1), y)).collect::>(), r) - }); - Plane::from_fn(w, h, |x, y| { - quartile_clamp(rows.get(x, y), &mut (0..=2 * r).map(|k| rows.get(x, (y + k).saturating_sub(r).min(h - 1))).collect::>(), r) - }) -} - #[test] -fn quartile_clamp_matches_a_plain_per_pixel_clamp() { +fn median_matches_a_plain_per_pixel_median() { let p = Plane::from_fn(37, 23, |x, y| (((x * 31 + y * 17) * 2_654_435_761usize) % 1000) as f32 / 250.0 - 2.0 + if x % 5 == 0 { 0.5 } else { 0.0 }); - for r in [1, 2, 3, 4, 9] { - assert_eq!(local::quartile_clamp_hv(&p, r).data, quartile_clamp_reference(&p, r).data, "r {r}"); + for r in [1, 2, 4, 9] { + let med = |v: &mut Vec| { + v.sort_by(f32::total_cmp); + v[r] + }; + let rows = Plane::from_fn(37, 23, |x, y| med(&mut (0..=2 * r).map(|k| p.get((x + k).saturating_sub(r).min(36), y)).collect())); + let want = Plane::from_fn(37, 23, |x, y| med(&mut (0..=2 * r).map(|k| rows.get(x, (y + k).saturating_sub(r).min(22))).collect())); + assert_eq!(local::median_hv(&p, r).data, want.data, "r {r}"); } - // the band is the window's quartiles; at r = 1 it closes to the 3-tap median - assert_eq!(local::quartile_ranks(1), (1, 1)); - assert_eq!(local::quartile_ranks(2), (1, 3)); - assert_eq!(local::quartile_ranks(10), (5, 15)); - assert_eq!(local::quartile_ranks(local::BASE_DETAIL_MAX), (12, 36)); } #[test] -fn quartile_clamp_orders_special_values_and_ties_like_total_cmp() { +fn median_orders_special_values_and_ties_like_total_cmp() { // the running window keeps keys in `f32::total_cmp` order: NaNs of either sign, signed zeros, // infinities and long runs of equal values come out bit for bit as a sorted per-pixel window // does, also on planes narrower or shorter than the window @@ -221,35 +197,46 @@ fn quartile_clamp_orders_special_values_and_ties_like_total_cmp() { for (w, h) in [(1, 1), (2, 3), (5, 1), (19, 7), (61, 9)] { let p = Plane::from_fn(w, h, |x, y| special[(x * 7 + y * 3 + (x * y) % 5) % special.len()]); for r in [1, 2, 9, 24] { - assert_eq!(bits(&local::quartile_clamp_hv(&p, r)), bits(&quartile_clamp_reference(&p, r)), "{w}x{h} r {r}"); + let med = |v: &mut Vec| { + v.sort_by(f32::total_cmp); + v[r] + }; + let rows = Plane::from_fn(w, h, |x, y| med(&mut (0..=2 * r).map(|k| p.get((x + k).saturating_sub(r).min(w - 1), y)).collect())); + let want = Plane::from_fn(w, h, |x, y| med(&mut (0..=2 * r).map(|k| rows.get(x, (y + k).saturating_sub(r).min(h - 1))).collect())); + assert_eq!(bits(&local::median_hv(&p, r)), bits(&want), "{w}x{h} r {r}"); } } } -#[test] -fn gaps_between_letters_keep_their_own_tone_in_the_base() { - // A row of "8"s (two rings each, strokes 1.3 detail radii wide, neighbours 0.8 radii apart), - // dark lettering on a bright panel at the size of a bus number in a 7000 px photo. A separable - // median at this radius filled the gaps between the digits and around their waists with the - // letters' tone: 360 panel pixels sat over 1 EV (up to 2.3 EV) above their base, so Shadows - // lifted them by up to 1.3 EV into bright blocks. The interquartile clamp leaves the panel - // within 0.13 EV of itself. - let ppl = 6960.0; - let r = local::base_detail_radius(ppl); +/// A row of "8"s (two rings each, strokes 1.3 detail radii `r` wide, neighbours 0.8 radii apart): +/// dark lettering on a bright panel at the size of a bus number, as log luminance. +fn lettering(r: usize) -> (Plane, impl Fn(usize, usize) -> bool) { let rf = r as f32; - let (w, h) = (900usize, 400usize); - let ring = |x: f32, y: f32, cx: f32, cy: f32, outer: f32| { + let ring = move |x: f32, y: f32, cx: f32, cy: f32, outer: f32| { let d = ((x - cx).powi(2) + (y - cy).powi(2)).sqrt(); d <= outer && d >= outer - 1.3 * rf }; - let stroke = |x: usize, y: usize| { + let stroke = move |x: usize, y: usize| { let (x, y) = (x as f32, y as f32); (0..5).any(|i| { let cx = 150.0 + i as f32 * 7.4 * rf; ring(x, y, cx, 200.0 - 2.8 * rf, 2.9 * rf) || ring(x, y, cx, 200.0 + 3.2 * rf, 3.3 * rf) }) }; - let l = Plane::from_fn(w, h, |x, y| if stroke(x, y) { -4.6 } else { -1.3 }); + (Plane::from_fn(900, 400, |x, y| if stroke(x, y) { -4.6 } else { -1.3 }), stroke) +} + +#[test] +fn gaps_between_letters_keep_their_own_tone_in_the_base() { + // At the size of a bus number in a 7000 px photo, a median at the detail radius filled the + // gaps between the digits and around their waists with the letters' tone: 360 panel pixels + // sat over 1 EV (up to 2.3 EV) above their base, so Shadows lifted them by up to 1.3 EV into + // bright blocks. The wider median sees the panel there, so the gaps keep their own tone. + let ppl = 6960.0; + let r = local::base_detail_radius(ppl); + assert_eq!(r, 10); + let (l, stroke) = lettering(r); + let (w, h) = (l.width, l.height); let base = local::tone_base(&l, 0.015 * ppl as f32, r); // panel pixels at least 3 px from a stroke (the guided filter's own edge softness aside) let panel = |x: usize, y: usize| !(x.saturating_sub(2)..(x + 3).min(w)).any(|a| (y.saturating_sub(2)..(y + 3).min(h)).any(|b| stroke(a, b))); @@ -261,13 +248,48 @@ fn gaps_between_letters_keep_their_own_tone_in_the_base() { under += usize::from(d > 1.0); } } - assert_eq!(r, 10); - assert!(under == 0 && worst < 0.3, "{under} panel px over 1 EV above their base; worst {worst} EV"); + assert!(under == 0 && worst < 1.0, "{under} panel px over 1 EV above their base; worst {worst} EV"); +} + +#[test] +fn isolated_lines_up_to_the_detail_radius_stay_out_of_the_base() { + // Light lines 1 to 9 px wide on a dark ground (twigs against a dark wall, r = 10): the base + // keeps the ground's tone under each, as under the median (#632), so Shadows lifts them with + // the ground and they keep their contrast. Clamping to the window's quartiles instead let lines + // of 6 px and more a third to two thirds of the way into the base. + let ppl = 6960.0; + let r = local::base_detail_radius(ppl); + let widths = [1usize, 2, 3, 4, 5, 6, 7, 8, 9]; + let l = Plane::from_fn(1300, 200, |x, _| { + let (i, off) = (x / 130, x % 130); + if i < widths.len() && (60..60 + widths[i]).contains(&off) { -2.0 } else { -6.0 } + }); + let base = local::tone_base(&l, 0.015 * ppl as f32, r); + for (i, wd) in widths.iter().enumerate() { + let leak = (base.get(i * 130 + 60 + wd / 2, 100) + 6.0) / 4.0; + assert!(leak.abs() < 0.05, "a {wd} px line is {leak} of the way into the base"); + } +} + +#[test] +fn detail_free_keeps_steps_and_regions() { + // a step between two flat regions, and a flat field, come out as they went in + let step = Plane::from_fn(90, 60, |x, _| if x < 45 { -4.0 } else { 0.5 }); + assert_eq!(local::detail_free(&step, 6).data, step.data); + let flat = Plane::from_fn(31, 17, |_, _| -1.25); + assert_eq!(local::detail_free(&flat, 3).data, flat.data); + assert_eq!(local::detail_free(&step, 0).data, step.data); + // tiny and empty planes, and NaNs, are not a panic + for (w, h) in [(1, 1), (2, 3), (5, 1)] { + let p = Plane::from_fn(w, h, |x, y| if (x + y) % 2 == 0 { f32::NAN } else { 1.0 }); + assert_eq!(local::detail_free(&p, 4).data.len(), w * h); + } + assert!(local::detail_free(&Plane::new(0, 0), 4).data.is_empty()); } #[test] fn v1_keeps_the_base_it_always_had() { - // V1's base is the edge-aware filter of log luminance itself, as before process V2: no clamp + // V1's base is the edge-aware filter of log luminance itself, as before process V2: no median // radius, and `tone_base` at 0 is that filter bit for bit let v1 = with_on(Process::V1, "light.highlights", -100.0); assert_eq!(ProcessVersion::legacy().process(), Process::V1); @@ -284,7 +306,7 @@ fn v1_keeps_the_base_it_always_had() { for sg in [1.0f32, 4.5, 18.0] { assert_eq!(local::tone_base(&l, sg, 0).data, local::guided_fast(&l, sg, local::BASE_EPS).data, "sigma {sg}"); } - // V2 takes the interquartile clamp wherever the image is big enough for one + // V2 takes the median wherever the image is big enough for one let v2 = with("light.highlights", -100.0); assert_eq!(local::plane_sigmas(&v2, 5568.0, Quality::Full).base_detail, local::base_detail_radius(5568.0)); assert_eq!(local::plane_sigmas(&v2, 300.0, Quality::Full).base_detail, 0); diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 0fd30ea3639..619f33c5b32 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -180,7 +180,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-EDIT-HDR-MODE | HDR editing | P2 | ✅ | `cmd:develop.hdr`, `ctl:hdr.maxEv`, `crates/ui-egui/src/panels/edit.rs` (`hdr_row`) | HDR button next to B&W in the Edit panel header, as Lightroom (Visualize HDR and the headroom limit in the Light panel while it's on); see Q. HDR | | LR-EDIT-LIGHT-EXPOSURE | Exposure | P0 | ✅ | `ctl:light.exposure` | Alt/Option-drag shows highlight clipping (black, clipped channels in colour) | | LR-EDIT-LIGHT-CONTRAST | Contrast | P0 | ✅ | `ctl:light.contrast` | | -| LR-EDIT-LIGHT-HIGHLIGHTS | Highlights | P0 | ✅ | `ctl:light.highlights`, `crates/raw/src/highlight.rs` | sensor-clipped highlights stay neutral when Highlights (or Exposure, Whites) darkens them: fully clipped content is rebuilt to the neutral of the colour model applied after it, partly clipped content takes its colour from reliable unclipped content nearby (not from dark objects, lens fringes or another surface beside it) and white where there is none, and pale partly clipped content (a white sky) turns white on its way to clipping (#523); binned previews and thumbnails decide clipping per sample before averaging (`develop_binned_masked`, `highlight::reconstruct_masked`), so a block with one clipped specular sample keeps its mean instead of jumping to the clip level, which reconstruction turned into green speckles at 500 px (#548) From process V2 the Highlights/Shadows base is the edge-aware filter of the 0.15 %-of-long-edge interquartile clamp of log luminance: twigs and fine texture take their surroundings' shift, so bright areas keep their local contrast as with Exposure (V1's base kept ~0.6 of it at −100, #632); region edges stay sharp, and lettering keeps clean gaps (a median there turned them into blocks of the letters' tone). Alt/Option-drag shows highlight clipping | +| LR-EDIT-LIGHT-HIGHLIGHTS | Highlights | P0 | ✅ | `ctl:light.highlights`, `crates/raw/src/highlight.rs` | sensor-clipped highlights stay neutral when Highlights (or Exposure, Whites) darkens them: fully clipped content is rebuilt to the neutral of the colour model applied after it, partly clipped content takes its colour from reliable unclipped content nearby (not from dark objects, lens fringes or another surface beside it) and white where there is none, and pale partly clipped content (a white sky) turns white on its way to clipping (#523); binned previews and thumbnails decide clipping per sample before averaging (`develop_binned_masked`, `highlight::reconstruct_masked`), so a block with one clipped specular sample keeps its mean instead of jumping to the clip level, which reconstruction turned into green speckles at 500 px (#548) From process V2 the Highlights/Shadows base is the edge-aware filter of log luminance without detail finer than 0.15 % of the long edge (`local::detail_free`: clamped between the median at that radius and one 3× wider): twigs and fine texture take their surroundings' shift, so bright areas keep their local contrast as with Exposure (V1's base kept ~0.6 of it at −100, #632); region edges stay sharp, and lettering keeps clean gaps (the median alone turned them into blocks of the letters' tone). Alt/Option-drag shows highlight clipping | | LR-EDIT-LIGHT-SHADOWS | Shadows | P0 | ✅ | `ctl:light.shadows` | From process V2, the same base as Highlights: dark areas keep their local contrast when lifted (#632), and the gaps in dark lettering on a bright panel are not lifted into bright blocks. Alt/Option-drag shows shadow clipping (white, clipped channels in colour) | | LR-EDIT-LIGHT-WHITES | Whites | P0 | ✅ | `ctl:light.whites`, `crates/pipeline/src/visualize.rs` | Alt/Option-drag shows highlight clipping (black, clipped channels in colour) | | LR-EDIT-LIGHT-BLACKS | Blacks | P0 | ✅ | `ctl:light.blacks`, `crates/pipeline/src/visualize.rs` | Alt/Option-drag shows shadow clipping (white, clipped channels in colour) | diff --git a/docs/process-versions.md b/docs/process-versions.md index 3f55658b452..cc7abc1b8c8 100644 --- a/docs/process-versions.md +++ b/docs/process-versions.md @@ -8,7 +8,7 @@ stronger Light sliders, issue #196) without changing a single photo someone has | Process | What it changes | |---|---| | **V1** | LightCraft's rendering from before process versions existed. Frozen. | -| **V2** (the latest) | Highlights and Shadows keep fine detail (issue #632): their base layer (`local::tone_base`) is the edge-aware filter of a separable interquartile clamp of log luminance (`local::quartile_clamp_hv`: each value clamped to the quartiles of its window, radius 0.15 % of the long edge, at most 24 px, `local::BASE_DETAIL`) instead of log luminance itself, so twigs, lines and texture take their surroundings' shift and keep their contrast; region edges stay sharp. CPU (`local::prepare`) and GPU prepare branch on `local::tone_base_detail` (0 = no clamp under V1); the base plane is cached per process (`local::BaseKey`). Renders without Highlights or Shadows (global or local) are the same as V1's. Tone map unchanged. | +| **V2** (the latest) | Highlights and Shadows keep fine detail (issue #632): their base layer (`local::tone_base`) is the edge-aware filter of log luminance without its fine detail (`local::detail_free`: each value clamped between its separable median at 0.15 % of the long edge, at most 24 px, `local::BASE_DETAIL`, and the median of a 3× wider neighbourhood) instead of log luminance itself, so twigs, lines and texture take their surroundings' shift and keep their contrast; region edges stay sharp. CPU (`local::prepare`) and GPU prepare branch on `local::tone_base_detail` (0 = no detail removal under V1); the base plane is cached per process (`local::BaseKey`). Renders without Highlights or Shadows (global or local) are the same as V1's. Tone map unchanged. | ## The rule @@ -35,18 +35,18 @@ inside, their outside and edges without contrast in the photo are unchanged. It a bug fix: the outline is output that isn't in the photo nor in the edit, not a look anyone chose. **Lettering under Highlights and Shadows** (V2) no longer grows blocks of the wrong tone. V2's base -was first the edge-aware filter of a separable median. Dark lettering on a bright panel (a bus +was first the edge-aware filter of a separable median alone. Dark lettering on a bright panel (a bus number, a sign) has strokes and gaps about as wide as the median's radius, so each row and column window was close to half letter and half panel, and the median picked one tone or the other in -rectangles: it filled the gaps between the letters and their counters with the letters' tone, and -parts of the strokes with the panel's. Shadows then lifted those patches of panel by over 1 EV, into -bright blocks beside the letters, and left the strokes lifted unevenly. The base now clamps each -value to the quartiles of its window instead (`local::quartile_clamp_hv`). Thin lines in an even -surround still take the surround's tone, as #632 wants; a window that mixes two tones leaves its -pixels alone. V2 renders with Highlights or Shadows change only on detail about as fine as the -radius (lettering, grilles, foliage against the sky); twig meshes that cover about half their -area keep somewhat less contrast than under the median. It landed in place as a bug fix: the blocks -are output that is neither in the photo nor in the edit. +rectangles: it filled the gaps between the letters and their counters with the letters' tone. +Shadows then lifted those patches of panel by over 1 EV, into bright blocks beside the letters. Each +value now moves toward that median only as far as the median of a 3× wider neighbourhood agrees +(`local::detail_free`). A twig against a wall has both medians on the wall's side and takes its tone, +as before (#632); the gap between two strokes sits in a wider neighbourhood that is mostly panel, the +two medians disagree, and the gap keeps its own tone. The letters themselves count as fine dark detail +on the panel and keep their contrast, as twigs do. V2 renders with Highlights or Shadows change only +in detail about as fine as the radius, mostly where it is packed closely (lettering, grilles). It +landed in place as a bug fix: the blocks are output that is neither in the photo nor in the edit. ## Adding a process From fcac37bf48c5b3503da63bb5c8c5beece336d657 Mon Sep 17 00:00:00 2001 From: Jeremy Hooke Date: Sun, 1 Nov 2026 14:02:51 +1100 Subject: [PATCH 4/7] =?UTF-8?q?LR-EDIT-LIGHT-SHADOWS:=204=C3=97=20faster?= =?UTF-8?q?=20GPU=20median=20for=20the=20highlights/shadows=20base?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The base's separable median dominated the GPU planes stage: 191 ms of the 226 ms base on a 6960×4640 plane (r = 10, M2 Max). Each pixel ran a partial selection sort over a private 49-tap array, which drivers keep in scratch memory because it is indexed dynamically. median_h / median_v now load each 16×16 workgroup's taps into workgroup memory and select by rank, 4 neighbouring outputs per thread, which share all but their first and last 3 taps. Same selection, so the output is bit for bit the CPU's (new test median_matches_cpu_bit_for_bit, every r 1–24, edge tiles, ties). Median 191 → 47 ms; full-size GPU planes on the #3460 CR3 with Whites +54, Blacks +31, Shadows +75: main 231, before this commit 257, now 113 ms. Renders are byte-identical to before on GPU and CPU. CPU: detail_free enlarges the coarse median while it clamps, into the fine median in place, instead of storing two more full-size planes (same sums; detail_free_matches_its_reference checks it bit for bit). ~10 ms. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QQTJhXnxfpjcQxB77dvuYA --- crates/gpu/src/render.rs | 75 ++++++++++++++++++++- crates/gpu/src/wgsl/blur.wgsl | 119 +++++++++++++++++++++++++--------- crates/pipeline/src/local.rs | 69 ++++++++++++++++++-- 3 files changed, 225 insertions(+), 38 deletions(-) diff --git a/crates/gpu/src/render.rs b/crates/gpu/src/render.rs index bb45a985729..ebd3719608e 100644 --- a/crates/gpu/src/render.rs +++ b/crates/gpu/src/render.rs @@ -318,6 +318,9 @@ fn guided_coeffs(cx: &mut Cx<'_>, p: &Buf, w: usize, h: usize, sigma: f32, eps: gaussian(cx, &ab, w, h, 2, sigma) } +/// Pixels per thread along the pass of `median_h` / `median_v` (`MED_K` in `blur.wgsl`). +const MEDIAN_K: usize = 4; + /// Separable median of a plane (`local::median_hv`). fn median_hv(cx: &mut Cx<'_>, p: &Buf, w: usize, h: usize, r: usize) -> Buf { if r == 0 || w * h == 0 { @@ -325,9 +328,9 @@ fn median_hv(cx: &mut Cx<'_>, p: &Buf, w: usize, h: usize, r: usize) -> Buf { } let pr = [w as u32, h as u32, 1, r.min(local::BASE_DETAIL_MAX) as u32]; let tmp = cx.gpu.buffer(w * h); - cx.run("median_h", &pr, &[Some(p), Some(&tmp)], groups2(w, h, [16, 16])); + cx.run("median_h", &pr, &[Some(p), Some(&tmp)], groups2(w.div_ceil(MEDIAN_K), h, [16, 16])); let out = cx.gpu.buffer(w * h); - cx.run("median_v", &pr, &[Some(&tmp), Some(&out)], groups2(w, h, [16, 16])); + cx.run("median_v", &pr, &[Some(&tmp), Some(&out)], groups2(w, h.div_ceil(MEDIAN_K), [16, 16])); out } @@ -1283,6 +1286,74 @@ mod tests { time("guided sigma=1.75", &mut |cx| drop(guided(cx, &src, w, h, 1.75, 0.01))); } + /// The tiled median kernels select exactly what the CPU's sorted window does: edge tiles, + /// planes smaller than a tile or a window, every radius and many ties. + #[test] + fn median_matches_cpu_bit_for_bit() { + let Some(gpu) = crate::device() else { return lightcraft_testkit::skip!(Gpu, "no GPU adapter") }; + let _scope = crate::ctx::RenderScope::new(gpu); + let mut seed = 0x9e37_79b9_u32; + let mut next = move || { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + seed + }; + for (w, h) in [(1, 1), (2, 3), (5, 70), (70, 5), (63, 65), (130, 67), (200, 129)] { + // a coarse level set gives ties; a smooth ramp and fine noise give distinct values + let mut p = Plane::new(w, h); + for (i, o) in p.data.iter_mut().enumerate() { + let (x, y) = (i % w, i / w); + *o = match (next() % 3, next()) { + (0, v) => (v % 7) as f32 * 0.5 - 2.0, + (1, v) => (x + 2 * y) as f32 * 0.01 + (v % 100) as f32 * 1e-4, + (_, v) => (v % 10_000) as f32 * 1e-3 - 5.0, + }; + } + let src = gpu.upload(&p.data); + for r in 1..=local::BASE_DETAIL_MAX { + let mut cx = Cx::new(gpu); + let out = median_hv(&mut cx, &src, w, h, r); + let got: Vec = cx.read(&out, w * h); + let want = local::median_hv(&p, r); + let bad = got.iter().zip(&want.data).position(|(g, c)| g.to_bits() != c.to_bits()); + assert!(bad.is_none(), "{w}×{h} r={r}: pixel {bad:?}"); + } + } + } + + /// Highlights/shadows base timings on the #3460 frame size: + /// `cargo test --release -p lightcraft-gpu bench_tone_base -- --ignored --nocapture`. + #[test] + #[ignore] + fn bench_tone_base() { + let Some(gpu) = crate::device() else { return eprintln!("no gpu: {:?}", crate::unavailable_reason()) }; + let _scope = crate::ctx::RenderScope::new(gpu); + let (w, h) = (6960, 4640); + let r = local::base_detail_radius(w as f64); + eprintln!("{} ({:?}) r={r}", gpu.info.name, gpu.info.backend); + let l: Vec = (0..w * h).map(|i: usize| ((i.wrapping_mul(2_654_435_761)) % 1000) as f32 / 250.0 - 6.0).collect(); + let src = gpu.upload(&l); + let time = |name: &str, f: &mut dyn FnMut(&mut Cx<'_>)| { + let mut ts = Vec::new(); + for _ in 0..9 { + let mut cx = Cx::new(gpu); + cx.sync(); + let t = std::time::Instant::now(); + f(&mut cx); + cx.sync(); + ts.push(t.elapsed().as_secs_f64() * 1e3); + } + ts.sort_by(f64::total_cmp); + eprintln!("{name:<40} min {:.1} ms median {:.1} ms", ts[0], ts[4]); + }; + let sigma = 0.015 * w as f32; + time("median_hv", &mut |cx| drop(median_hv(cx, &src, w, h, r))); + time("detail_free", &mut |cx| drop(detail_free(cx, &src, w, h, r))); + time("guided_fast", &mut |cx| drop(guided_fast(cx, &src, w, h, sigma, local::BASE_EPS))); + time("tone_base", &mut |cx| drop(tone_base(cx, &src, w, h, sigma, r))); + } + #[test] fn orient_map_matches_image_oriented() { use Orientation::*; diff --git a/crates/gpu/src/wgsl/blur.wgsl b/crates/gpu/src/wgsl/blur.wgsl index 375fb6d5503..75b98167e33 100644 --- a/crates/gpu/src/wgsl/blur.wgsl +++ b/crates/gpu/src/wgsl/blur.wgsl @@ -76,56 +76,113 @@ fn box_v(@builtin(global_invocation_id) g: vec3) { } // Separable median of a single-channel plane (`lightcraft_pipeline::local::median_hv`): 2r+1 -// taps (r ≤ 24, clamped edges) along a row (median_h) or a column (median_v), one thread per -// pixel. The median is a selection, so the result matches the CPU's bit for bit. +// taps (1 ≤ r ≤ 24, clamped edges) along a row (median_h) or a column (median_v). The median is a +// selection, so the result matches the CPU's bit for bit. // P: w, h, nc (unused), r. -fn median_of(n: u32, r: u32, v: ptr>) -> f32 { - // partial selection sort up to the middle - for (var i = 0u; i <= r; i++) { - var m = i; - for (var j = i + 1u; j < n; j++) { - if ((*v)[j] < (*v)[m]) { - m = j; - } +// +// Each thread finds the medians of 4 neighbouring pixels along the pass by rank: a tap is the +// median of a window when fewer than r+1 of its taps are smaller and at least r+1 are smaller or +// equal. The 4 windows share all but their first and last 3 taps, so one count over the shared +// taps serves all four. A 16×16 workgroup (64 pixels along the pass, 16 lines across) first loads +// its taps into `med_tile`. On a 6960×4640 plane at r = 10 this takes 47 ms on an M2 Max, against +// 191 ms for a partial selection sort per pixel over a private array of taps, which drivers keep in +// scratch memory because it is indexed dynamically. +const MED_K: u32 = 4u; +const MED_LINE: u32 = 113u; // 16·MED_K + 2·24, odd +var med_tile: array; // 16 lines + +// The medians of the 2r+1-tap windows starting at `med_tile[base + k]`, k < 4 (r ≥ 1). Taps 3 to +// n-1 are in all four windows; the three at each end are in some. +fn median4(base: u32, r: u32) -> vec4 { + let n = 2u * r + 1u; + let e0 = vec3(med_tile[base], med_tile[base + 1u], med_tile[base + 2u]); + let e1 = vec3(med_tile[base + n], med_tile[base + n + 1u], med_tile[base + n + 2u]); + var out = vec4(0.0); + var found = vec4(false); + for (var i = 0u; i < n + 3u; i++) { + let c = med_tile[base + i]; + var less = 0u; + var le = 0u; + for (var j = 3u; j < n; j++) { + let v = med_tile[base + j]; + less += select(0u, 1u, v < c); + le += select(0u, 1u, v <= c); + } + let l0 = select(vec3(0u), vec3(1u), e0 < vec3(c)); + let l1 = select(vec3(0u), vec3(1u), e1 < vec3(c)); + let q0 = select(vec3(0u), vec3(1u), e0 <= vec3(c)); + let q1 = select(vec3(0u), vec3(1u), e1 <= vec3(c)); + // window k: taps k..k+n-1 = taps k..2 of the start, the middle, taps n..n+k-1 of the end + let lw = vec4(l0.x + l0.y + l0.z, l0.y + l0.z + l1.x, l0.z + l1.x + l1.y, l1.x + l1.y + l1.z) + vec4(less); + let qw = vec4(q0.x + q0.y + q0.z, q0.y + q0.z + q1.x, q0.z + q1.x + q1.y, q1.x + q1.y + q1.z) + vec4(le); + let has = vec4((i < n), (i >= 1u) && (i < n + 1u), (i >= 2u) && (i < n + 2u), (i >= 3u)); + let hit = has & !found & (lw <= vec4(r)) & (qw > vec4(r)); + out = select(out, vec4(c), hit); + found = found | hit; + if (all(found)) { + break; } - let t = (*v)[i]; - (*v)[i] = (*v)[m]; - (*v)[m] = t; } - return (*v)[r]; + return out; } +// Thread (l.x, l.y) of a workgroup takes line l.x and pixels 4·l.y to 4·l.y + 3 along it, so the +// threads of a SIMD group read 16 different lines at once; with an odd line length those fall in +// different banks of workgroup memory. @compute @workgroup_size(16, 16) -fn median_h(@builtin(global_invocation_id) g: vec3) { +fn median_h(@builtin(local_invocation_id) l: vec3, @builtin(workgroup_id) wg: vec3) { let w = pu(0u); let h = pu(1u); let r = min(pu(3u), 24u); - if (g.x >= w || g.y >= h) { + let span = 16u * MED_K + 2u * r; + let x0 = i32(wg.x * 16u * MED_K) - i32(r); + // load: consecutive threads read consecutive pixels of a row + for (var e = l.y * 16u + l.x; e < 16u * span; e += 256u) { + let line = e / span; + let k = e % span; + let y = min(wg.y * 16u + line, h - 1u); + let x = clamp(x0 + i32(k), 0, i32(w) - 1); + med_tile[line * MED_LINE + k] = src[y * w + u32(x)]; + } + workgroupBarrier(); + let y = wg.y * 16u + l.x; + let x = (wg.x * 16u + l.y) * MED_K; + if (x >= w || y >= h) { return; } - let n = 2u * r + 1u; - var v: array; - let row = g.y * w; - for (var k = 0u; k < n; k++) { - let x = clamp(i32(g.x + k) - i32(r), 0, i32(w) - 1); - v[k] = src[row + u32(x)]; + let m = median4(l.x * MED_LINE + l.y * MED_K, r); + for (var k = 0u; k < MED_K; k++) { + if (x + k < w) { + dst[y * w + x + k] = m[k]; + } } - dst[row + g.x] = median_of(n, r, &v); } @compute @workgroup_size(16, 16) -fn median_v(@builtin(global_invocation_id) g: vec3) { +fn median_v(@builtin(local_invocation_id) l: vec3, @builtin(workgroup_id) wg: vec3) { let w = pu(0u); let h = pu(1u); let r = min(pu(3u), 24u); - if (g.x >= w || g.y >= h) { + let span = 16u * MED_K + 2u * r; + let y0 = i32(wg.y * 16u * MED_K) - i32(r); + // load: consecutive threads read consecutive pixels of a row (16 columns) + for (var e = l.y * 16u + l.x; e < 16u * span; e += 256u) { + let line = e % 16u; + let k = e / 16u; + let x = min(wg.x * 16u + line, w - 1u); + let y = clamp(y0 + i32(k), 0, i32(h) - 1); + med_tile[line * MED_LINE + k] = src[u32(y) * w + x]; + } + workgroupBarrier(); + let x = wg.x * 16u + l.x; + let y = (wg.y * 16u + l.y) * MED_K; + if (x >= w || y >= h) { return; } - let n = 2u * r + 1u; - var v: array; - for (var k = 0u; k < n; k++) { - let y = clamp(i32(g.y + k) - i32(r), 0, i32(h) - 1); - v[k] = src[u32(y) * w + g.x]; + let m = median4(l.x * MED_LINE + l.y * MED_K, r); + for (var k = 0u; k < MED_K; k++) { + if (y + k < h) { + dst[(y + k) * w + x] = m[k]; + } } - dst[g.y * w + g.x] = median_of(n, r, &v); } diff --git a/crates/pipeline/src/local.rs b/crates/pipeline/src/local.rs index 0467464eeb1..72d11ca2f1e 100644 --- a/crates/pipeline/src/local.rs +++ b/crates/pipeline/src/local.rs @@ -406,13 +406,28 @@ pub fn detail_free(l: &Plane, r: usize) -> Plane { return l.clone(); } let (w, h) = (l.width, l.height); - let fine = median_hv(l, r); let (lw, lh) = (w.div_ceil(BASE_COARSE_STEP).max(1), h.div_ceil(BASE_COARSE_STEP).max(1)); - let coarse = resize(&median_hv(&resize(l, lw, lh, Filter::Box), r), w, h, Filter::Bilinear); - let mut out = Plane::new(w, h); + if (lw, lh) == (w, h) { + // nothing to downscale: both medians are the same + return median_hv(l, r); + } + let lo = median_hv(&resize(l, lw, lh, Filter::Box), r); + // The bilinear enlargement of `lo` (`resize`'s horizontal pass, then its vertical pass taken + // row by row with the same sums) is clamped into `out` as it is made, not stored. + let wide = resize(&lo, w, lh, Filter::Bilinear); + let wy = lightcraft_raster::resample::weights(lh, h, Filter::Bilinear); + let mut out = median_hv(l, r); for_rows(&mut out.data, w, |y, row| { - for (((o, &v), &a), &b) in row.iter_mut().zip(l.row(y)).zip(fine.row(y)).zip(coarse.row(y)) { - *o = clamp_between(v, a, b); + let Some((y0, ws)) = wy.get(y) else { return }; + let mut coarse = vec![0.0f32; w]; + for (k, &wt) in ws.iter().enumerate() { + let Some(t) = wide.data.get((y0 + k) * w..(y0 + k + 1) * w) else { continue }; + for (c, &v) in coarse.iter_mut().zip(t) { + *c += v * wt; + } + } + for ((o, &v), &c) in row.iter_mut().zip(l.row(y)).zip(&coarse) { + *o = clamp_between(v, *o, c); } }); out @@ -947,6 +962,50 @@ mod tests { mod fast_tests { use super::*; + /// [`detail_free`] enlarges the coarse median as it clamps; the result is the plain + /// composition of `resize` and [`median_hv`], bit for bit. + #[test] + fn detail_free_matches_its_reference() { + use lightcraft_raster::resample::{Filter, resize}; + for (w, h) in [(1, 1), (2, 1), (3, 3), (4, 7), (61, 47), (200, 31)] { + let p = Plane::from_fn(w, h, |x, y| ((x * 37 + y * 101) % 23) as f32 * 0.4 - 4.0 + if (x / 5 + y / 7) % 2 == 0 { 2.0 } else { 0.0 }); + for r in [1, 2, 5, 10] { + let fine = median_hv(&p, r); + let (lw, lh) = (w.div_ceil(BASE_COARSE_STEP), h.div_ceil(BASE_COARSE_STEP)); + let coarse = resize(&median_hv(&resize(&p, lw, lh, Filter::Box), r), w, h, Filter::Bilinear); + let want: Vec = (0..w * h).map(|i| clamp_between(p.data[i], fine.data[i], coarse.data[i]).to_bits()).collect(); + let got: Vec = detail_free(&p, r).data.iter().map(|v| v.to_bits()).collect(); + assert_eq!(got, want, "{w}×{h} r={r}"); + } + } + } + + /// CPU highlights/shadows base timings on the #3460 frame size: + /// `cargo test --release -p lightcraft-pipeline bench_tone_base_cpu -- --ignored --nocapture`. + #[test] + #[ignore] + fn bench_tone_base_cpu() { + let (w, h) = (6960, 4640); + let r = base_detail_radius(w as f64); + let p = Plane::from_fn(w, h, |x, y| ((x * 7 + y * 13) % 1000) as f32 / 250.0 - 6.0 + if (x / 40 + y / 40) % 2 == 0 { 1.0 } else { 0.0 }); + let sigma = 0.015 * w as f32; + let time = |name: &str, f: &dyn Fn() -> Plane| { + let mut ts: Vec = (0..5) + .map(|_| { + let t = std::time::Instant::now(); + std::hint::black_box(f()); + t.elapsed().as_secs_f64() * 1e3 + }) + .collect(); + ts.sort_by(f64::total_cmp); + eprintln!("{name:<20} min {:.1} ms median {:.1} ms", ts[0], ts[2]); + }; + time("median_hv", &|| median_hv(&p, r)); + time("detail_free", &|| detail_free(&p, r)); + time("guided_fast", &|| guided_fast(&p, sigma, BASE_EPS)); + time("tone_base", &|| tone_base(&p, sigma, r)); + } + /// The previous fast path, including its two materialized coefficient resizes. fn resized_reference(p: &Plane, sigma: f32, eps: f32) -> Plane { use lightcraft_raster::resample::{Filter, resize}; From 14e8783832a695904c65430e34f1df0114437bf8 Mon Sep 17 00:00:00 2001 From: Jeremy Hooke Date: Sun, 1 Nov 2026 19:19:03 +1100 Subject: [PATCH 5/7] LR-EDIT-LIGHT-SHADOWS: don't zero workgroup memory in the pipeline kernels wgpu zeroes `var` arrays by default; on DX12 that is one assignment per element of `med_tile`, and FXC took about 87 s over the median kernels at every start of a release build (GTX 1070, reported on #3462). `nn.rs` and `faces.rs` already turn it off. The median kernels are the only ones `build_jobs` builds that use workgroup memory, and their load loop writes every element `median4` reads before the barrier. Renders are byte-identical (the #3460 CR3, Whites +54, Blacks +31, Shadows +75, M2 Max). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QQTJhXBE6yZLw3xqWysb6P --- crates/gpu/src/ctx.rs | 6 +++++- crates/gpu/src/wgsl/blur.wgsl | 1 + 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/gpu/src/ctx.rs b/crates/gpu/src/ctx.rs index a3255b2d787..f2e3f13b127 100644 --- a/crates/gpu/src/ctx.rs +++ b/crates/gpu/src/ctx.rs @@ -163,7 +163,11 @@ fn build_jobs( layout: Some(&p.pipeline_layout), module: &p.module, entry_point: Some(entry), - compilation_options: Default::default(), + // Only the median kernels (`blur.wgsl`, `med_tile`) use workgroup memory, and they + // load every element they read before the barrier, so wgpu's default zeroing is not + // needed. On DX12 it is written out as one assignment per element, which made FXC take + // about 87 s over these kernels at every start of a release build. + compilation_options: wgpu::PipelineCompilationOptions { zero_initialize_workgroup_memory: false, ..Default::default() }, cache: None, }); let kernel = Kernel { pipeline, layout: p.layout.clone(), nbuf: p.nbuf }; diff --git a/crates/gpu/src/wgsl/blur.wgsl b/crates/gpu/src/wgsl/blur.wgsl index 75b98167e33..b350dc3fa33 100644 --- a/crates/gpu/src/wgsl/blur.wgsl +++ b/crates/gpu/src/wgsl/blur.wgsl @@ -89,6 +89,7 @@ fn box_v(@builtin(global_invocation_id) g: vec3) { // scratch memory because it is indexed dynamically. const MED_K: u32 = 4u; const MED_LINE: u32 = 113u; // 16·MED_K + 2·24, odd +// Not zero-initialised (`build_jobs` in ctx.rs turns that off): write every element read. var med_tile: array; // 16 lines // The medians of the 2r+1-tap windows starting at `med_tile[base + k]`, k < 4 (r ≥ 1). Taps 3 to From c47a2550401b82d9314e32433266a07311690971 Mon Sep 17 00:00:00 2001 From: Jeremy Hooke Date: Thu, 5 Nov 2026 21:20:02 +1100 Subject: [PATCH 6/7] LR-EDIT-LIGHT-SHADOWS: the lettering note follows the fix to process V3 Co-Authored-By: Claude Opus 5.5 --- docs/process-versions.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/docs/process-versions.md b/docs/process-versions.md index 96baca67ea3..d549815ef51 100644 --- a/docs/process-versions.md +++ b/docs/process-versions.md @@ -38,19 +38,19 @@ exports. Existing AI masks become 1–2 px tighter at a subject's edges, on ever inside, their outside and edges without contrast in the photo are unchanged. It landed in place as a bug fix: the outline is output that isn't in the photo nor in the edit, not a look anyone chose. -**Lettering under Highlights and Shadows** (V2) no longer grows blocks of the wrong tone. V2's base -was first the edge-aware filter of a separable median alone. Dark lettering on a bright panel (a bus +**Lettering under Highlights and Shadows** (V3) no longer grows blocks of the wrong tone. V2's base +is the edge-aware filter of a separable median alone. Dark lettering on a bright panel (a bus number, a sign) has strokes and gaps about as wide as the median's radius, so each row and column window was close to half letter and half panel, and the median picked one tone or the other in rectangles: it filled the gaps between the letters and their counters with the letters' tone. -Shadows then lifted those patches of panel by over 1 EV, into bright blocks beside the letters. Each -value now moves toward that median only as far as the median of a 3× wider neighbourhood agrees +Shadows then lifted those patches of panel by over 1 EV, into bright blocks beside the letters. From V3 each +value moves toward that median only as far as the median of a 3× wider neighbourhood agrees (`local::detail_free`). A twig against a wall has both medians on the wall's side and takes its tone, as before (#632); the gap between two strokes sits in a wider neighbourhood that is mostly panel, the two medians disagree, and the gap keeps its own tone. The letters themselves count as fine dark detail -on the panel and keep their contrast, as twigs do. V2 renders with Highlights or Shadows change only -in detail about as fine as the radius, mostly where it is packed closely (lettering, grilles). It -landed in place as a bug fix: the blocks are output that is neither in the photo nor in the edit. +on the panel and keep their contrast, as twigs do. V3 differs from V2 under Highlights or Shadows only in detail +about as fine as the radius, mostly where it is packed closely (lettering, grilles). V2 is frozen +and keeps the blocks (`tests_legacy`); Update to Current Process moves a photo past them. ## Adding a process From d4bdd065c4de98f1ac1c2e26b55dd1d6772c20f8 Mon Sep 17 00:00:00 2001 From: Jeremy Hooke Date: Mon, 9 Nov 2026 22:52:47 +1100 Subject: [PATCH 7/7] LR-EDIT-LIGHT-SHADOWS: name the process test after V8 Co-Authored-By: Claude Opus 5.5 --- crates/pipeline/src/tests_tone.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/pipeline/src/tests_tone.rs b/crates/pipeline/src/tests_tone.rs index a4d0c796c2c..f8926e780ca 100644 --- a/crates/pipeline/src/tests_tone.rs +++ b/crates/pipeline/src/tests_tone.rs @@ -272,7 +272,7 @@ fn isolated_lines_up_to_the_detail_radius_stay_out_of_the_base() { } #[test] -fn only_process_v7_on_takes_the_detail_free_base() { +fn only_process_v8_on_takes_the_detail_free_base() { // V2 to V7 keep the plain median (V1 has none): they are released and frozen (`tests_legacy`) for p in Process::ALL { let s = DevelopSettings { process: p.version(), ..Default::default() };