From d1bf7129be3295cd7b12077f92e514fd10dfc37f Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:40:15 +0100 Subject: [PATCH 1/5] fix(algo): HDR Toning stretches an ordinary image to the full range (#14723) Local Adaptation compressed the blurred log luminance toward its mean and never stretched the result, so an 8-bit image came out darker (white at 166). It now compresses toward the brightest base, which becomes white, with 1 / (1 + 3 * strength) fitted to the reference samples, and the detail is compressed with the base so a darker tone never comes out brighter at a large radius or strength. The checked replay follows the same lines. The #710 Gamma test toned a flat grey document, which now turns white at every Gamma; it gets a white half so the grey stays a midtone. --- crates/algo/src/tone.rs | 23 ++- crates/algo/src/tone/checked_hdr.rs | 13 +- .../algo/src/tone/hdr_toning_range_tests.rs | 151 ++++++++++++++++++ crates/engine/tests/it/hdr_gamma_direction.rs | 7 +- 4 files changed, 177 insertions(+), 17 deletions(-) create mode 100644 crates/algo/src/tone/hdr_toning_range_tests.rs diff --git a/crates/algo/src/tone.rs b/crates/algo/src/tone.rs index 62697048b4..f36ccc9f75 100644 --- a/crates/algo/src/tone.rs +++ b/crates/algo/src/tone.rs @@ -251,9 +251,12 @@ fn curve_eval(pts: &[(f32, f32)], x: f32) -> f32 { } /// Local adaptation tone mapping (Durand–Dorsey style base/detail split in log luminance): the -/// blurred log luminance (radius) is the base layer, compressed toward its mean by `strength`; -/// detail is boosted; then exposure, gamma, shadow/highlight lift, the toning curve, and -/// vibrance/saturation. Like Photoshop the result is a flattened, low-dynamic-range image. +/// blurred log luminance (radius) is the base layer, compressed by `strength` toward its brightest +/// value, which becomes white, so an ordinary image is stretched to the full range and its dark +/// tones are lifted (#14723); the detail (log luminance less the base, boosted by `detail`) is +/// compressed with it, so a darker tone never comes out brighter on a smooth gradient; then +/// exposure, gamma, shadow/highlight lift, the toning curve, and vibrance/saturation. Like +/// Photoshop the result is a flattened, low-dynamic-range image. pub fn hdr_toning(px: &mut [[f32; 4]], w: usize, h: usize, p: &HdrToning) { if px.is_empty() { return; @@ -265,10 +268,11 @@ pub fn hdr_toning(px: &mut [[f32; 4]], w: usize, h: usize, p: &HdrToning) { }); let mut base = logl.clone(); gauss_blur_n(&mut base, w, h, 1, p.radius.max(1.0) / 2.0); - let n = px.iter().filter(|q| q[3] > 0.0).count().max(1) as f64; - // Match the checked path: narrow sums lose log-luminance samples on large scenes. - let mean = (base.iter().zip(px.iter()).filter(|(_, q)| q[3] > 0.0).map(|(b, _)| f64::from(*b)).sum::() / n) as f32; - let compress = 1.0 / (1.0 + p.strength.max(0.0)); + // The brightest base of the visible pixels (only visible pixels are toned). + let white = base.iter().zip(px.iter()).filter(|(_, q)| q[3] > 0.0).map(|(b, _)| *b).fold(f32::NEG_INFINITY, f32::max); + // Fitted to the reference application's samples (#14723): Strength 0.5296 compresses the + // base's log range to about 0.39 of its span. + let compress = 1.0 / (1.0 + 3.0 * p.strength.max(0.0)); let detail = 1.0 + p.detail / 100.0; let exposure = 2f32.powf(p.exposure); let gamma = p.gamma.clamp(0.1, 4.0); @@ -283,7 +287,7 @@ pub fn hdr_toning(px: &mut [[f32; 4]], w: usize, h: usize, p: &HdrToning) { } let c = [q[0], q[1], q[2]]; let l0 = luma(c).max(0.0) + EPS; - let new_log = mean + (base[i] - mean) * compress + (logl[i] - base[i]) * detail; + let new_log = ((base[i] - white) + (logl[i] - base[i]) * detail) * compress; // The contract is "lower = more contrast", i.e. gamma is the divisor of // the exponent, matching the crate's other gamma controls (hdr.rs, proof_sim.rs). let mut l1 = (new_log.exp() * exposure).max(0.0).powf(1.0 / gamma); @@ -383,3 +387,6 @@ mod tests { assert!(luma([px[2][0], px[2][1], px[2][2]]) > luma([px[38][0], px[38][1], px[38][2]])); } } + +#[cfg(test)] +mod hdr_toning_range_tests; diff --git a/crates/algo/src/tone/checked_hdr.rs b/crates/algo/src/tone/checked_hdr.rs index 22be7b4cf9..189017069f 100644 --- a/crates/algo/src/tone/checked_hdr.rs +++ b/crates/algo/src/tone/checked_hdr.rs @@ -166,19 +166,16 @@ pub fn process_with(px: &mut [[f32; 4]], w: usize, h: usize, p: &HdrToning, ctl: })?; let mut scratch = zeroes(w.max(h), 0f32, ctl)?; blur(&mut base, w, h, &mut scratch, p.radius / 2., ctl)?; - // F32 loses successive log-luminance additions on ordinary megapixel images. - let mut total = 0f64; - let mut visible = 0usize; + // The brightest base of the visible pixels becomes white (#14723). + let mut white = f32::NEG_INFINITY; for (qs, bs) in px.chunks(2048).zip(base.chunks(2048)) { check(ctl)?; for (q, b) in qs.iter().zip(bs) { if q[3] > 0. { - total += f64::from(*b); - visible += 1; + white = white.max(*b); } } } - let mean = (total / visible.max(1) as f64) as f32; let mut curve = zeroes(p.curve.len(), (0f32, 0f32), ctl)?; curve.copy_from_slice(&p.curve); // Stable bounded in-place insertion avoids slice::sort's infallible temporary allocation. @@ -190,7 +187,7 @@ pub fn process_with(px: &mut [[f32; 4]], w: usize, h: usize, p: &HdrToning, ctl: j -= 1; } } - let compress = 1. / (1. + p.strength); + let compress = 1. / (1. + 3. * p.strength); let detail = 1. + p.detail / 100.; let exposure = 2f32.powf(p.exposure); independent_chunks(px, |start, qs| { @@ -203,7 +200,7 @@ pub fn process_with(px: &mut [[f32; 4]], w: usize, h: usize, p: &HdrToning, ctl: } let c = [q[0], q[1], q[2]]; let l0 = luma(c).max(0.) + 1e-4; - let new_log = mean + (*b - mean) * compress + (*l - *b) * detail; + let new_log = ((*b - white) + (*l - *b) * detail) * compress; let mut l1 = (new_log.exp() * exposure).max(0.).powf(1. / p.gamma); l1 += p.shadow / 100. * (1. - l1).powi(3) * 0.5 - p.highlight / 100. * l1.powi(3) * 0.5; if !l1.is_finite() { diff --git a/crates/algo/src/tone/hdr_toning_range_tests.rs b/crates/algo/src/tone/hdr_toning_range_tests.rs new file mode 100644 index 0000000000..0607bd4b8f --- /dev/null +++ b/crates/algo/src/tone/hdr_toning_range_tests.rs @@ -0,0 +1,151 @@ +//! #14723: HDR Toning's Local Adaptation stretches an ordinary image to the full range (white +//! stays white, dark tones are lifted) instead of compressing it towards its mean, and keeps the +//! order of the tones for every Radius and Strength. + +use super::*; +use crate::hdr::{ToneMethod, tone_map}; + +/// The reference application's factory Radius and Strength, passed explicitly so the samples +/// don't depend on the defaults (#14720). +fn reference(radius: f32, strength: f32) -> HdrToning { + HdrToning { radius, strength, ..Default::default() } +} + +const RADIUS: f32 = 7.68; +const STRENGTH: f32 = 0.5296; + +/// A grey 8-bit level as a pixel. +fn grey(v: u32) -> [f32; 4] { + let v = v as f32 / 255.0; + [v, v, v, 1.0] +} + +/// The issue's 512 x 256 document: a ramp (rows 0-63, column x is level x/2), eight flat grey +/// patches (rows 64-127), a 40 | 200 step edge at x 256 (rows 128-191) and eight colour patches +/// (rows 192-255). +fn document() -> (Vec<[f32; 4]>, usize, usize) { + const COLOURS: [[u32; 3]; 8] = [[60, 20, 20], [20, 60, 20], [40, 40, 90], [120, 60, 30], [200, 60, 60], [60, 200, 60], [220, 200, 120], [230, 180, 200]]; + let (w, h) = (512, 256); + let px = (0..w * h) + .map(|i| { + let (x, y) = (i % w, i / w); + match y { + 0..64 => grey(x as u32 / 2), + 64..128 => grey(PATCHES[x / 64]), + 128..192 => grey(if x < 256 { 40 } else { 200 }), + _ => { + let c = COLOURS[x / 64].map(|v| v as f32 / 255.0); + [c[0], c[1], c[2], 1.0] + } + } + }) + .collect(); + (px, w, h) +} + +const PATCHES: [u32; 8] = [0, 16, 48, 80, 128, 176, 224, 255]; + +/// The issue's dark 256 x 64 document: a ramp 0..63 at 4 px per level (rows 0-31) and a 30 | 90 +/// step edge at x 128 (rows 32-63). +fn dark_document() -> (Vec<[f32; 4]>, usize, usize) { + let (w, h) = (256, 64); + let px = (0..w * h).map(|i| if i / w < 32 { grey((i % w) as u32 / 4) } else { grey(if i % w < 128 { 30 } else { 90 }) }).collect(); + (px, w, h) +} + +/// The grey level of pixel `(x, y)`. +fn level(px: &[[f32; 4]], w: usize, x: usize, y: usize) -> f32 { + let q = px[y * w + x]; + luma([q[0], q[1], q[2]]) * 255.0 +} + +fn toned((mut px, w, h): (Vec<[f32; 4]>, usize, usize), p: &HdrToning) -> (Vec<[f32; 4]>, usize) { + hdr_toning(&mut px, w, h, p); + (px, w) +} + +#[test] +fn an_ordinary_image_is_stretched_to_white_with_its_dark_tones_lifted() { + let (px, w) = toned(document(), &reference(RADIUS, STRENGTH)); + let patches = [0.0, 93.0, 131.0, 158.0, 191.0, 217.0, 240.0, 253.0]; + for (i, want) in patches.into_iter().enumerate() { + let got = level(&px, w, i * 64 + 32, 96); + assert!((got - want).abs() <= 12.0, "grey patch {}: {got:.1}, the reference gives {want}", PATCHES[i]); + } + for (v, want) in [(15, 91.0), (120, 186.0), (255, 254.0)] { + let got = level(&px, w, 2 * v + 1, 32); + assert!((got - want).abs() <= 12.0, "ramp {v}: {got:.1}, the reference gives {want}"); + } + assert!(level(&px, w, 511, 32) > 240.0 && level(&px, w, 255 * 2, 96) > 240.0, "white stays white"); +} + +#[test] +fn a_dark_image_is_stretched_to_fill_the_range() { + let (px, w) = toned(dark_document(), &reference(RADIUS, STRENGTH)); + for (v, want) in [(8, 105.0), (56, 203.0)] { + let got = level(&px, w, 4 * v + 2, 16); + assert!((got - want).abs() <= 15.0, "ramp {v}: {got:.1}, the reference gives {want}"); + } + for (x, v, want) in [(64, 30, 157.0), (192, 90, 253.0)] { + let got = level(&px, w, x, 48); + assert!((got - want).abs() <= 15.0, "edge {v}: {got:.1}, the reference gives {want}"); + } +} + +#[test] +fn a_darker_ramp_level_never_comes_out_brighter() { + // The ramp alone, sampled every 15 levels: the blur at a large radius sees nothing else. + // The issue's document at its three ramp samples: there the patches below the ramp fall + // inside a large blur. + let (w, h) = (512, 64); + let ramp = (0..w * h).map(|i| grey((i % w) as u32 / 2)).collect::>(); + for radius in [1.0, RADIUS, 100.0] { + for strength in [0.1, 0.53, 4.0] { + let (px, w) = toned((ramp.clone(), w, h), &reference(radius, strength)); + let samples: Vec = (1..=17).map(|k| level(&px, w, 2 * 15 * k + 1, 32)).collect(); + assert!(samples.windows(2).all(|p| p[0] <= p[1]), "ramp, radius {radius}, strength {strength}: levels 15, 30, .. 255 give {samples:?}"); + let (px, w) = toned(document(), &reference(radius, strength)); + let samples = [15, 120, 255].map(|v| level(&px, w, 2 * v + 1, 32)); + assert!(samples[0] <= samples[1] && samples[1] <= samples[2], "document, radius {radius}, strength {strength}: ramp 15/120/255 give {samples:?}"); + // The reference keeps the flat greys in order even at Radius 100 and Strength 4. + let patches: Vec = (0..8).map(|i| level(&px, w, i * 64 + 32, 96)).collect(); + assert!(patches.windows(2).all(|p| p[0] <= p[1]), "document, radius {radius}, strength {strength}: grey patches give {patches:?}"); + } + } +} + +#[test] +fn black_stays_black_and_results_stay_in_range_at_every_depth() { + // 8- and 16-bit documents arrive as 0..1; a 32-bit one can hold values far above 1. + let (doc, w, h) = document(); + let bright: Vec<[f32; 4]> = doc.iter().map(|q| [q[0] * 40.0, q[1] * 40.0, q[2] * 40.0, 1.0]).collect(); + for px in [doc, bright] { + let (px, w) = toned((px, w, h), &reference(RADIUS, STRENGTH)); + assert!(px.iter().all(|q| q[..3].iter().all(|v| (0.0..=1.0).contains(v))), "every channel in 0..1"); + assert_eq!(level(&px, w, 32, 96), 0.0, "black stays 0"); + } +} + +/// A 4 x 1 strip of flat 64 x 64 areas with the given linear values, as Merge to HDR Pro hands +/// its radiance to the tone map. +fn strip(values: [f32; 4]) -> Vec<[f32; 4]> { + (0..256 * 64) + .map(|i| { + let v = values[i % 256 / 64]; + [v, v, v, 1.0] + }) + .collect() +} + +#[test] +fn merge_to_hdr_local_adaptation_reaches_the_reference_from_the_reference_radiance() { + // The reference application's own 32-bit merge of #14023's scene (#14021): grey 128, ramp 26, + // ramp 246 and the white patch. Its 16-bit Local Adaptation result of that merge (#14023): + // 35725, 14858 and 63103. + let mut px = strip([0.0531, 0.00074, 1.130, 1.341]); + tone_map(&mut px, 256, 64, &ToneMethod::LocalAdaptation(reference(6.0, 0.53))); + for (i, name, want) in [(0, "grey 128", 35725.0), (1, "ramp 26", 14858.0), (2, "ramp 246", 63103.0)] { + let got = px[32 * 256 + i * 64 + 32][1] * 65535.0; + assert!((got - want).abs() <= 0.08 * 65535.0, "{name}: {got:.0}, the reference gives {want}"); + } +} diff --git a/crates/engine/tests/it/hdr_gamma_direction.rs b/crates/engine/tests/it/hdr_gamma_direction.rs index 932b3b4f19..a264bb06bf 100644 --- a/crates/engine/tests/it/hdr_gamma_direction.rs +++ b/crates/engine/tests/it/hdr_gamma_direction.rs @@ -8,7 +8,12 @@ use serde_json::json; fn midtone_luma(gamma: f64) -> f64 { let mut s = Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8, "background": "#808080"})).unwrap(); + // A white right half: HDR Toning makes the brightest tone white (#14723), so a flat grey + // document would come out white at every gamma. + s.execute("file.new", json!({"width": 64, "height": 8, "background": "#808080"})).unwrap(); + s.execute("select.rect", json!({"x": 32, "y": 0, "width": 32, "height": 8})).unwrap(); + s.execute("edit.fill", json!({"color": "#ffffff"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); s.execute("image.adjustments.hdrToning", json!({"gamma": gamma, "strength": 0.1, "detail": 0, "saturation": 0, "radius": 30})).unwrap(); let p: Vec = serde_json::from_value(s.execute("document.pixel", json!({"x": 4, "y": 4})).unwrap()).unwrap(); f64::from(0.299 * p[0] + 0.587 * p[1] + 0.114 * p[2]) From 79335e9df9fc4e31a788a058d297cd1917568162 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:39:07 +0100 Subject: [PATCH 2/5] fix(algo): HDR Toning stays finite when its tone overflows f32 (#14723) A bright pixel between dark ones with a large Detail and a low Gamma toned past f32 before the shadow/highlight cubic, which then gave 0 * inf = NaN. The brightest-base anchor made that easier to reach. The direct path now takes the checked replay's wide-range evaluation, shared as wide_range_tone, so both paths give the same finite colour. --- crates/algo/src/tone.rs | 16 ++++++++++++++++ crates/algo/src/tone/checked_hdr.rs | 10 ++-------- crates/algo/src/tone/hdr_toning_range_tests.rs | 14 ++++++++++++++ 3 files changed, 32 insertions(+), 8 deletions(-) diff --git a/crates/algo/src/tone.rs b/crates/algo/src/tone.rs index f36ccc9f75..be2c22838c 100644 --- a/crates/algo/src/tone.rs +++ b/crates/algo/src/tone.rs @@ -250,6 +250,19 @@ fn curve_eval(pts: &[(f32, f32)], x: f32) -> f32 { pts[pts.len() - 1].1 } +/// The tone of a sample whose f32 exposure, gamma and shadow/highlight arithmetic overflowed (a +/// low Gamma or a strong local contrast): the same curve evaluated in f64. A cap beyond every +/// control's polynomial crossover keeps cubing finite; those values saturate at the display +/// clamp. Both HDR Toning paths use it, so they stay equal. +pub(crate) fn wide_range_tone(new_log: f32, exposure: f32, gamma: f32, shadow: f32, highlight: f32) -> f32 { + let log_value = (f64::from(new_log) + f64::from(exposure) * std::f64::consts::LN_2) / f64::from(gamma); + let value = log_value.exp().min(1e100); + let shadow = f64::from(shadow) / 200.; + let highlight = f64::from(highlight) / 200.; + let mapped = ((-(shadow + highlight) * value + 3. * shadow) * value + (1. - 3. * shadow)) * value + shadow; + mapped.clamp(0., 1.) as f32 +} + /// Local adaptation tone mapping (Durand–Dorsey style base/detail split in log luminance): the /// blurred log luminance (radius) is the base layer, compressed by `strength` toward its brightest /// value, which becomes white, so an ordinary image is stretched to the full range and its dark @@ -292,6 +305,9 @@ pub fn hdr_toning(px: &mut [[f32; 4]], w: usize, h: usize, p: &HdrToning) { // the exponent, matching the crate's other gamma controls (hdr.rs, proof_sim.rs). let mut l1 = (new_log.exp() * exposure).max(0.0).powf(1.0 / gamma); l1 += p.shadow / 100.0 * (1.0 - l1).powi(3) * 0.5 - p.highlight / 100.0 * l1.powi(3) * 0.5; + if !l1.is_finite() { + l1 = wide_range_tone(new_log, p.exposure, gamma, p.shadow, p.highlight); + } l1 = curve_eval(&sorted, l1.clamp(0.0, 1.0)); let ratio = l1 / l0; let mut out = c.map(|v| v * ratio); diff --git a/crates/algo/src/tone/checked_hdr.rs b/crates/algo/src/tone/checked_hdr.rs index 189017069f..d4462b06f4 100644 --- a/crates/algo/src/tone/checked_hdr.rs +++ b/crates/algo/src/tone/checked_hdr.rs @@ -205,14 +205,8 @@ pub fn process_with(px: &mut [[f32; 4]], w: usize, h: usize, p: &HdrToning, ctl: l1 += p.shadow / 100. * (1. - l1).powi(3) * 0.5 - p.highlight / 100. * l1.powi(3) * 0.5; if !l1.is_finite() { // Preserve ordinary native arithmetic, but evaluate extreme valid HDR in a - // wider domain. A cap beyond every f32 control's polynomial crossover keeps - // cubing finite; those values already saturate at the final display clamp. - let log_value = (f64::from(new_log) + f64::from(p.exposure) * std::f64::consts::LN_2) / f64::from(p.gamma); - let value = log_value.exp().min(1e100); - let shadow = f64::from(p.shadow) / 200.; - let highlight = f64::from(p.highlight) / 200.; - let mapped = ((-(shadow + highlight) * value + 3. * shadow) * value + (1. - 3. * shadow)) * value + shadow; - l1 = mapped.clamp(0., 1.) as f32; + // wider domain. + l1 = super::wide_range_tone(new_log, p.exposure, p.gamma, p.shadow, p.highlight); if !l1.is_finite() { return Err(Error::NonFiniteSample); } diff --git a/crates/algo/src/tone/hdr_toning_range_tests.rs b/crates/algo/src/tone/hdr_toning_range_tests.rs index 0607bd4b8f..d29256b815 100644 --- a/crates/algo/src/tone/hdr_toning_range_tests.rs +++ b/crates/algo/src/tone/hdr_toning_range_tests.rs @@ -149,3 +149,17 @@ fn merge_to_hdr_local_adaptation_reaches_the_reference_from_the_reference_radian assert!((got - want).abs() <= 0.08 * 65535.0, "{name}: {got:.0}, the reference gives {want}"); } } + +#[test] +fn a_strong_local_contrast_at_a_low_gamma_stays_finite() { + // A bright pixel between dark ones with Detail 300 and Gamma 0.1 tones far past f32 before the + // shadow and highlight curve; the result is still a colour, and the checked replay agrees. + let p = HdrToning { radius: 100.0, strength: 0.1, gamma: 0.1, detail: 300.0, saturation: 0.0, ..Default::default() }; + let input = vec![[0.01, 0.01, 0.01, 1.0], [0.9, 0.9, 0.9, 1.0], [0.01, 0.01, 0.01, 1.0]]; + let mut px = input.clone(); + hdr_toning(&mut px, 3, 1, &p); + assert!(px.iter().all(|q| q.iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v))), "{px:?}"); + let mut checked = input; + checked_hdr::process_with(&mut checked, 3, 1, &p, &photocraft_raster::Interrupt::NONE).unwrap(); + assert!(px.iter().flatten().zip(checked.iter().flatten()).all(|(a, b)| (a - b).abs() < 1e-6), "{px:?} vs {checked:?}"); +} From 0344c55a3bf6e1aca6d0e16bf6038bc3a98ec590 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:22:10 +0100 Subject: [PATCH 3/5] test(algo): set every HDR Toning control in the overflow test (#14723) --- crates/algo/src/tone/hdr_toning_range_tests.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/crates/algo/src/tone/hdr_toning_range_tests.rs b/crates/algo/src/tone/hdr_toning_range_tests.rs index d29256b815..b308d231a2 100644 --- a/crates/algo/src/tone/hdr_toning_range_tests.rs +++ b/crates/algo/src/tone/hdr_toning_range_tests.rs @@ -154,7 +154,18 @@ fn merge_to_hdr_local_adaptation_reaches_the_reference_from_the_reference_radian fn a_strong_local_contrast_at_a_low_gamma_stays_finite() { // A bright pixel between dark ones with Detail 300 and Gamma 0.1 tones far past f32 before the // shadow and highlight curve; the result is still a colour, and the checked replay agrees. - let p = HdrToning { radius: 100.0, strength: 0.1, gamma: 0.1, detail: 300.0, saturation: 0.0, ..Default::default() }; + let p = HdrToning { + radius: 100.0, + strength: 0.1, + gamma: 0.1, + exposure: 0.0, + detail: 300.0, + shadow: 0.0, + highlight: 0.0, + vibrance: 0.0, + saturation: 0.0, + curve: Vec::new(), + }; let input = vec![[0.01, 0.01, 0.01, 1.0], [0.9, 0.9, 0.9, 1.0], [0.01, 0.01, 0.01, 1.0]]; let mut px = input.clone(); hdr_toning(&mut px, 3, 1, &p); From 79aaba8a6c1c2840a72e419201452a890870c318 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:57:39 +0100 Subject: [PATCH 4/5] fix(algo): Merge to HDR Pro keeps the mean-anchored tone map (#14723) The issue owner chose to keep Merge to HDR Pro's Local Adaptation on today's tone map until #14023 moves the merge to the reference's radiance: on today's merge radiance the white-anchored map is worse (17001 levels off on #14023's scene, against 11530). `hdr::tone_map` now calls `tone::hdr_toning_mean_anchored`, the earlier mapping, sharing the rest of `hdr_toning`'s code; HDR Toning itself is unchanged. The test on the reference's radiance now runs `hdr_toning` directly, and a new test merges #14023's scene and pins the worst sample within 11530. --- crates/algo/src/hdr.rs | 3 +- crates/algo/src/tone.rs | 43 ++++++++++-- .../algo/src/tone/hdr_toning_range_tests.rs | 65 +++++++++++++++++-- 3 files changed, 100 insertions(+), 11 deletions(-) diff --git a/crates/algo/src/hdr.rs b/crates/algo/src/hdr.rs index 08119ad7a2..9770b16497 100644 --- a/crates/algo/src/hdr.rs +++ b/crates/algo/src/hdr.rs @@ -385,7 +385,8 @@ pub fn tone_map(px: &mut [[f32; 4]], w: usize, h: usize, method: &ToneMethod) { q[c] *= k; } } - crate::tone::hdr_toning(px, w, h, p); + // Today's merge radiance keeps the mean-anchored map until #14023 moves it (#14723). + crate::tone::hdr_toning_mean_anchored(px, w, h, p); for q in px.iter_mut() { for c in 0..3 { q[c] = linear_to_srgb(q[c].clamp(0.0, 1.0)); diff --git a/crates/algo/src/tone.rs b/crates/algo/src/tone.rs index be2c22838c..e4cd820485 100644 --- a/crates/algo/src/tone.rs +++ b/crates/algo/src/tone.rs @@ -271,6 +271,27 @@ pub(crate) fn wide_range_tone(new_log: f32, exposure: f32, gamma: f32, shadow: f /// exposure, gamma, shadow/highlight lift, the toning curve, and vibrance/saturation. Like /// Photoshop the result is a flattened, low-dynamic-range image. pub fn hdr_toning(px: &mut [[f32; 4]], w: usize, h: usize, p: &HdrToning) { + local_adaptation(px, w, h, p, Anchor::White); +} + +/// Merge to HDR Pro's Local Adaptation until the merge moves to the reference's radiance and +/// [`hdr_toning`] (#14023, #14021): the base is compressed toward its mean, which stays put, and +/// the detail is not compressed. On today's merge radiance this is closer to the reference than +/// the white-anchored map (#14723). +pub(crate) fn hdr_toning_mean_anchored(px: &mut [[f32; 4]], w: usize, h: usize, p: &HdrToning) { + local_adaptation(px, w, h, p, Anchor::Mean); +} + +/// The log luminance a Local Adaptation base is compressed toward. +#[derive(Clone, Copy)] +enum Anchor { + /// The brightest visible base, which becomes white. + White, + /// The mean visible base, which stays put. + Mean, +} + +fn local_adaptation(px: &mut [[f32; 4]], w: usize, h: usize, p: &HdrToning, anchor: Anchor) { if px.is_empty() { return; } @@ -281,11 +302,18 @@ pub fn hdr_toning(px: &mut [[f32; 4]], w: usize, h: usize, p: &HdrToning) { }); let mut base = logl.clone(); gauss_blur_n(&mut base, w, h, 1, p.radius.max(1.0) / 2.0); - // The brightest base of the visible pixels (only visible pixels are toned). - let white = base.iter().zip(px.iter()).filter(|(_, q)| q[3] > 0.0).map(|(b, _)| *b).fold(f32::NEG_INFINITY, f32::max); - // Fitted to the reference application's samples (#14723): Strength 0.5296 compresses the - // base's log range to about 0.39 of its span. - let compress = 1.0 / (1.0 + 3.0 * p.strength.max(0.0)); + // Only visible pixels are toned, so only they set the anchor. + let visible = || base.iter().zip(px.iter()).filter(|(_, q)| q[3] > 0.0).map(|(b, _)| *b); + let (anchor_log, compress) = match anchor { + // Fitted to the reference application's samples (#14723): Strength 0.5296 compresses the + // base's log range to about 0.39 of its span. + Anchor::White => (visible().fold(f32::NEG_INFINITY, f32::max), 1.0 / (1.0 + 3.0 * p.strength.max(0.0))), + Anchor::Mean => { + let n = visible().count().max(1) as f64; + // Match the checked path: narrow sums lose log-luminance samples on large scenes. + ((visible().map(f64::from).sum::() / n) as f32, 1.0 / (1.0 + p.strength.max(0.0))) + } + }; let detail = 1.0 + p.detail / 100.0; let exposure = 2f32.powf(p.exposure); let gamma = p.gamma.clamp(0.1, 4.0); @@ -300,7 +328,10 @@ pub fn hdr_toning(px: &mut [[f32; 4]], w: usize, h: usize, p: &HdrToning) { } let c = [q[0], q[1], q[2]]; let l0 = luma(c).max(0.0) + EPS; - let new_log = ((base[i] - white) + (logl[i] - base[i]) * detail) * compress; + let new_log = match anchor { + Anchor::White => ((base[i] - anchor_log) + (logl[i] - base[i]) * detail) * compress, + Anchor::Mean => anchor_log + (base[i] - anchor_log) * compress + (logl[i] - base[i]) * detail, + }; // The contract is "lower = more contrast", i.e. gamma is the divisor of // the exponent, matching the crate's other gamma controls (hdr.rs, proof_sim.rs). let mut l1 = (new_log.exp() * exposure).max(0.0).powf(1.0 / gamma); diff --git a/crates/algo/src/tone/hdr_toning_range_tests.rs b/crates/algo/src/tone/hdr_toning_range_tests.rs index b308d231a2..ac87ccf8e9 100644 --- a/crates/algo/src/tone/hdr_toning_range_tests.rs +++ b/crates/algo/src/tone/hdr_toning_range_tests.rs @@ -3,7 +3,8 @@ //! order of the tones for every Radius and Strength. use super::*; -use crate::hdr::{ToneMethod, tone_map}; +use crate::hdr::{MergeOptions, ToneMethod, merge, tone_map}; +use crate::photo_util::{linear_to_srgb, srgb_to_linear}; /// The reference application's factory Radius and Strength, passed explicitly so the samples /// don't depend on the defaults (#14720). @@ -138,12 +139,20 @@ fn strip(values: [f32; 4]) -> Vec<[f32; 4]> { } #[test] -fn merge_to_hdr_local_adaptation_reaches_the_reference_from_the_reference_radiance() { +fn this_tone_map_reaches_the_reference_merge_from_the_reference_radiance() { // The reference application's own 32-bit merge of #14023's scene (#14021): grey 128, ramp 26, // ramp 246 and the white patch. Its 16-bit Local Adaptation result of that merge (#14023): - // 35725, 14858 and 63103. + // 35725, 14858 and 63103. Merge to HDR Pro keys the scene to middle grey, tones it and encodes + // it (`hdr::tone_map`); here with this tone map, which #14023 will move the merge to. let mut px = strip([0.0531, 0.00074, 1.130, 1.341]); - tone_map(&mut px, 256, 64, &ToneMethod::LocalAdaptation(reference(6.0, 0.53))); + let log_mean = (px.iter().map(|q| f64::from(luma([q[0], q[1], q[2]]).max(1e-6)).ln()).sum::() / px.len() as f64).exp() as f32; + for q in &mut px { + q[..3].iter_mut().for_each(|v| *v *= 0.18 / log_mean); + } + hdr_toning(&mut px, 256, 64, &reference(6.0, 0.53)); + for q in &mut px { + q[..3].iter_mut().for_each(|v| *v = linear_to_srgb(v.clamp(0.0, 1.0))); + } for (i, name, want) in [(0, "grey 128", 35725.0), (1, "ramp 26", 14858.0), (2, "ramp 246", 63103.0)] { let got = px[32 * 256 + i * 64 + 32][1] * 65535.0; assert!((got - want).abs() <= 0.08 * 65535.0, "{name}: {got:.0}, the reference gives {want}"); @@ -174,3 +183,51 @@ fn a_strong_local_contrast_at_a_low_gamma_stays_finite() { checked_hdr::process_with(&mut checked, 3, 1, &p, &photocraft_raster::Interrupt::NONE).unwrap(); assert!(px.iter().flatten().zip(checked.iter().flatten()).all(|(a, b)| (a - b).abs() < 1e-6), "{px:?} vs {checked:?}"); } + +/// #14023's scene: 300 x 200, a grey ramp in 10 px steps (rows 0-99, level round(x0 / 290 * 255)), +/// a grey 128 band (rows 100-119) and red, green, blue, white and black 60 px patches (rows +/// 120-179), shot at `ev` stops in 8 bits. +fn hdr_scene_shot(ev: f32) -> Vec<[f32; 4]> { + let (w, h) = (300, 200); + (0..w * h) + .map(|i| { + let (x, y) = (i % w, i / w); + let level = |v: f32| v / 255.0; + let c = match y { + 0..100 => [level((((x / 10 * 10) as f32) / 290.0 * 255.0).round()); 3], + 100..120 => [level(128.0); 3], + 120..180 => [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], [1.0, 1.0, 1.0], [0.0, 0.0, 0.0]][x / 60], + _ => [0.0; 3], + }; + let shot = c.map(|v| (linear_to_srgb((srgb_to_linear(v) * 2f32.powf(ev)).clamp(0.0, 1.0)) * 255.0).round() / 255.0); + [shot[0], shot[1], shot[2], 1.0] + }) + .collect() +} + +#[test] +fn merge_to_hdr_local_adaptation_gets_no_worse_on_todays_merge() { + // Merge to HDR Pro keeps the mean-anchored tone map until #14023 moves it to the reference's + // radiance (#14723): on today's merge of #14023's scene its worst sample stays within main's + // 11530 levels of the reference at 16 bits (11435 here); the white-anchored map's is 17001. + let (w, h) = (300, 200); + let shots: Vec> = [-2.0, 0.0, 2.0].map(hdr_scene_shot).into(); + let refs: Vec<&[[f32; 4]]> = shots.iter().map(Vec::as_slice).collect(); + let options = MergeOptions { exposures: vec![0.25, 1.0, 4.0], remove_ghosts: false, ghost_base: None, response: None }; + let mut px = merge(w, h, &refs, &options).px; + let p = HdrToning { radius: 6.0, strength: 0.53, ..Default::default() }; + tone_map(&mut px, w, h, &ToneMethod::LocalAdaptation(p)); + // (x, y, the reference's 16-bit green) for ramp 0, 26, 62, 123, 185, 246, grey 128 and black. + let samples = [ + (5, 50, 1538.0), + (35, 50, 14858.0), + (75, 50, 21840.0), + (145, 50, 33663.0), + (215, 50, 48003.0), + (285, 50, 63103.0), + (150, 110, 35725.0), + (270, 150, 1538.0), + ]; + let worst = samples.iter().map(|&(x, y, want)| (px[y * w + x][1] * 65535.0 - want).abs()).fold(0.0, f32::max); + assert!(worst <= 11530.0, "the worst sample is {worst:.0} levels off the reference"); +} From 063f21b0b5dc7aaa37dae64176415435d724c78f Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:08:31 +0100 Subject: [PATCH 5/5] test(algo): the merge test refuses a sample that is not a colour (#14723) f32::max skips NaN, so a NaN sample would have passed the worst-sample bound. --- crates/algo/src/tone/hdr_toning_range_tests.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/algo/src/tone/hdr_toning_range_tests.rs b/crates/algo/src/tone/hdr_toning_range_tests.rs index ac87ccf8e9..93dae0a46e 100644 --- a/crates/algo/src/tone/hdr_toning_range_tests.rs +++ b/crates/algo/src/tone/hdr_toning_range_tests.rs @@ -228,6 +228,11 @@ fn merge_to_hdr_local_adaptation_gets_no_worse_on_todays_merge() { (150, 110, 35725.0), (270, 150, 1538.0), ]; - let worst = samples.iter().map(|&(x, y, want)| (px[y * w + x][1] * 65535.0 - want).abs()).fold(0.0, f32::max); + let error = |&(x, y, want): &(usize, usize, f32)| { + let error = (px[y * w + x][1] * 65535.0 - want).abs(); + assert!(error.is_finite(), "({x}, {y}) is not a colour: {:?}", px[y * w + x]); + error + }; + let worst = samples.iter().map(error).fold(0.0, f32::max); assert!(worst <= 11530.0, "the worst sample is {worst:.0} levels off the reference"); }