diff --git a/crates/engine-paint/src/cmd/retouch_cmds/dab.rs b/crates/engine-paint/src/cmd/retouch_cmds/dab.rs index 11dc337871..06c88a220a 100644 --- a/crates/engine-paint/src/cmd/retouch_cmds/dab.rs +++ b/crates/engine-paint/src/cmd/retouch_cmds/dab.rs @@ -4,7 +4,7 @@ use super::{ Region, Result, Session, Smudge, Stroke, StrokePoint, Surface, ToneRange, Value, alpha_index, apply_dab_stroke, bad, damage_json, dodge_burn, flag, from_rgba_into, has_pixel_layer, json, local_blur, local_sharpen, num, parse_blend, parse_brush, run_stroke, sponge, string, to_rgba, }; -use photocraft_algo::retouch::sponge_rgb; +use photocraft_algo::retouch::{luma, sponge_rgb, tone_curve}; use photocraft_color::{ColorMode, SampleType}; // --------------------------------------------------------------------------------------------- @@ -185,6 +185,46 @@ fn tone_stroke(fmt: PixelFormat, toned: impl Fn([f32; 3]) -> [f32; 3] + Send + ' }) } +/// Strength of [`linear_midtones`] per unit of Exposure. +const LINEAR_MIDTONES_STRENGTH: f32 = 1.34; + +/// The Midtones Dodge (`burn = false`) or Burn curve for one linear value of a 32-bit document at +/// exposure `e` (0..1): `v ± 1.34·e·v²·(1 − v)^1.5`, each channel on its own. It is fitted to the +/// reference's 32-bit results (#12687), which tone the stored linear values: much gentler on the +/// mid tones than the 8-bit curve on gamma-encoded values, and the shadows are left alone. Black +/// and white stay put, values outside 0..1 (light above white) are kept as they are, and tones +/// stay in order at every exposure. +#[inline] +fn linear_midtones(v: f32, e: f32, burn: bool) -> f32 { + if !(v > 0.0 && v < 1.0) { + return v; + } + let d = LINEAR_MIDTONES_STRENGTH * e.clamp(0.0, 1.0) * v * v * (1.0 - v).powf(1.5); + if burn { v - d } else { v + d } +} + +/// The 32-bit reference was measured at Exposure 50 % only (#12687); other exposures keep the +/// gamma curve. +const MEASURED_LINEAR_EXPOSURE: f32 = 0.5; + +/// Dodge or Burn of a 32-bit colour with the curve the other bit depths use, except that light above +/// white isn't clipped: Protect Tones scales such a colour to its new luma without gamut +/// compression, which would pull it back to 1.0 (#12687). Such a colour whose luma isn't positive +/// (a negative channel outweighs it) can't be scaled by luma, so it takes the per-channel curve, as +/// with Protect Tones off, which keeps light above white too. Other colours get today's result. +#[inline] +fn dodge_burn_float(c: [f32; 3], e: f32, range: ToneRange, burn: bool, protect: bool) -> [f32; 3] { + if protect && c.iter().any(|&v| v > 1.0) { + let l = luma(c); + if l > 1e-6 { + let nl = tone_curve(l, e, range, burn); + return c.map(|v| v * nl / l); + } + return dodge_burn(c, e, range, burn, false); + } + dodge_burn(c, e, range, burn, protect) +} + fn tone_range(p: &Value, cmd: &str) -> Result { match string(p, "range", "midtones") { "shadows" => Ok(ToneRange::Shadows), @@ -305,6 +345,18 @@ impl DabTool { pub(super) fn effect(&self, fmt: PixelFormat, spacing: f32) -> DabEffect { let sp = spacing; match self.clone() { + // A 32-bit RGB document holds linear values, which the reference's default Dodge tones + // with its own curve. Grayscale, the other ranges, Protect Tones off and the other + // exposures weren't measured there and keep the gamma curve, without clipping light + // above white. + Self::Tone { burn: false, range: ToneRange::Midtones, exposure, protect: true } + if fmt.sample == SampleType::F32 && fmt.mode == ColorMode::Rgb && (exposure - MEASURED_LINEAR_EXPOSURE).abs() < 1e-4 => + { + tone_stroke(fmt, move |c| c.map(|v| linear_midtones(v, exposure, false))) + } + Self::Tone { burn, range, exposure, protect } if fmt.sample == SampleType::F32 => { + tone_stroke(fmt, move |c| dodge_burn_float(c, exposure, range, burn, protect)) + } Self::Tone { burn, range, exposure, protect } => tone_stroke(fmt, move |c| dodge_burn(c, exposure, range, burn, protect)), // Flow is already in the dab's coverage. The reference RGB response applies to integer // RGB surfaces, including 16-bit. Float RGB and the other models use the legacy curve. @@ -828,3 +880,7 @@ mod smudge_refuses_indexed_tests; #[cfg(test)] #[path = "smudge_mode_tests.rs"] mod smudge_mode_tests; + +#[cfg(test)] +#[path = "dodge_32bit_linear_tests.rs"] +mod dodge_32bit_linear_tests; diff --git a/crates/engine-paint/src/cmd/retouch_cmds/dodge_32bit_linear_tests.rs b/crates/engine-paint/src/cmd/retouch_cmds/dodge_32bit_linear_tests.rs new file mode 100644 index 0000000000..dd8535b397 --- /dev/null +++ b/crates/engine-paint/src/cmd/retouch_cmds/dodge_32bit_linear_tests.rs @@ -0,0 +1,187 @@ +//! Dodge in a 32-bit document tones the linear values it holds, with the reference's curve +//! (#12687); 8- and 16-bit documents keep their results. + +use crate::Session; +use photocraft_algo::retouch::{ToneRange, dodge_burn}; +use photocraft_color::convert::linear_to_srgb; +use serde_json::{Value, json}; + +/// The reference's test colours (8-bit RGB): grey 32, 128 and 224, red, skin and pastel. +const PATCHES: [[u8; 3]; 6] = [[32, 32, 32], [128, 128, 128], [224, 224, 224], [200, 40, 40], [220, 170, 140], [180, 200, 230]]; +const SIDE: i32 = 60; + +/// An 8-bit RGB document of `PATCHES` side by side, converted to `depth` bits. +fn patches(depth: u32) -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": SIDE * PATCHES.len() as i32, "height": SIDE, "depth": 8, "mode": "rgb"})).unwrap(); + s.edit("patches", |doc, active| { + let b = doc.bounds(); + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + let fmt = surf.format(); + let mut data = Vec::new(); + for _ in b.y0..b.y1 { + for x in b.x0..b.x1 { + let c = PATCHES[(x / SIDE) as usize].map(|v| f32::from(v) / 255.0); + data.extend(photocraft_raster::from_rgba(&fmt, [c[0], c[1], c[2], 1.0])); + } + } + surf.write_region(b, &data); + Ok(()) + }) + .unwrap(); + if depth != 8 { + s.execute(&format!("image.mode.bits{depth}"), json!({})).unwrap(); + } + s +} + +fn rgb(s: &Session, x: i32, y: i32) -> [f32; 3] { + let d = s.active().unwrap(); + let p = d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y); + [p[0], p[1], p[2]] +} + +/// One default Dodge click (Midtones, Protect Tones, 50 %) with a hard 40 px tip on each patch's +/// centre; the stored values there. +fn dodge_each(s: &mut Session, extra: Value) -> Vec<[f32; 3]> { + (0..PATCHES.len() as i32) + .map(|i| { + let (x, y) = (i * SIDE + SIDE / 2, SIDE / 2); + let mut p = json!({"points": [[x, y]], "size": 40, "hardness": 100}); + if let (Some(p), Some(e)) = (p.as_object_mut(), extra.as_object()) { + p.extend(e.clone()); + } + s.execute("paint.dodge", p).unwrap(); + rgb(s, x, y) + }) + .collect() +} + +/// A 32-bit document's linear values as 8-bit RGB, as the reference reads them. +fn as_8bit(c: [f32; 3]) -> [i32; 3] { + c.map(|v| (linear_to_srgb(v).clamp(0.0, 1.0) * 255.0).round() as i32) +} + +#[test] +fn dodge_tones_linear_values_in_32_bit() { + // Measured in the reference: one default click in a 32-bit RGB document, read as 8-bit. + let expected = [[32, 32, 32], [134, 134, 134], [230, 230, 230], [210, 40, 40], [227, 177, 147], [191, 209, 235]]; + let mut s = patches(32); + let got: Vec<_> = dodge_each(&mut s, json!({})).into_iter().map(as_8bit).collect(); + for ((g, e), p) in got.iter().zip(expected).zip(PATCHES) { + assert!(g.iter().zip(e).all(|(g, e)| (g - e).abs() <= 2), "32-bit Dodge of {p:?}: got {g:?}, expected {e:?} (+-2); all: {got:?}"); + } +} + +#[test] +fn dodge_keeps_8_and_16_bit_results() { + // Pinned from main 406ac677e1: this change only adds the 32-bit path. + let mut s = patches(8); + let got: Vec<_> = dodge_each(&mut s, json!({})).into_iter().map(|c| c.map(|v| (v * 255.0).round() as u16)).collect(); + assert_eq!(got, [[46, 46, 46], [161, 161, 161], [228, 228, 228], [255, 65, 65], [242, 187, 154], [191, 212, 244]]); + let mut s = patches(16); + let got: Vec<_> = dodge_each(&mut s, json!({})).into_iter().map(|c| c.map(|v| (v * 65535.0).round() as u16)).collect(); + assert_eq!(got, [[11825, 11825, 11825], [41392, 41392, 41392], [58654, 58654, 58654], [65535, 16658, 16658], [62104, 47989, 39521], [49139, 54599, 62789]]); +} + +/// Fill the first patch with light above white (4.0, 1.5, 0.2, linear). +fn above_white(s: &mut Session) { + s.edit("bright", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + let r = photocraft_geom::Rect::new(0, 0, SIDE, SIDE); + let px = photocraft_raster::from_rgba(&surf.format(), [4.0, 1.5, 0.2, 1.0]); + surf.write_region(r, &px.repeat((SIDE * SIDE) as usize)); + Ok(()) + }) + .unwrap(); +} + +#[test] +fn dodge_keeps_light_above_white_in_32_bit() { + let mut s = patches(32); + above_white(&mut s); + let c = dodge_each(&mut s, json!({}))[0]; + assert_eq!([c[0], c[1]], [4.0, 1.5], "light above white must stay as it was: {c:?}"); + assert!(c[2] > 0.2, "the in-range channel is still dodged: {c:?}"); +} + +#[test] +fn dodge_keeps_todays_curve_at_unmeasured_exposures_in_32_bit() { + // Only 50 % was measured in 32-bit; other exposures keep the gamma curve with Protect Tones' + // luma scaling, run on the stored values. + for exposure in [25, 100] { + let mut s = patches(32); + let before: Vec<_> = (0..PATCHES.len() as i32).map(|i| rgb(&s, i * SIDE + SIDE / 2, SIDE / 2)).collect(); + let got = dodge_each(&mut s, json!({"exposure": exposure})); + for (g, o) in got.iter().zip(before) { + let e = dodge_burn(o, exposure as f32 / 100.0, ToneRange::Midtones, false, true); + assert!(g.iter().zip(e).all(|(g, e)| (g - e).abs() < 1e-5), "{exposure} % Dodge of {o:?}: got {g:?}, today's curve gives {e:?}"); + } + } +} + +#[test] +fn dodge_keeps_light_above_white_with_unmeasured_settings_in_32_bit() { + // The settings that keep today's curve must not clip light above white either. + for extra in [json!({"exposure": 100}), json!({"range": "shadows"}), json!({"range": "highlights"}), json!({"protectTones": false})] { + let mut s = patches(32); + above_white(&mut s); + let c = dodge_each(&mut s, extra.clone())[0]; + assert!(c[0] >= 4.0 && c[1] >= 1.5, "Dodge with {extra} clipped light above white: {c:?}"); + } + let mut s = crate::session(); + s.execute("file.new", json!({"width": SIDE, "height": SIDE, "depth": 32, "mode": "gray"})).unwrap(); + s.edit("bright", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + let px = photocraft_raster::from_rgba(&surf.format(), [2.0, 2.0, 2.0, 1.0]); + surf.write_region(photocraft_geom::Rect::new(0, 0, SIDE, SIDE), &px.repeat((SIDE * SIDE) as usize)); + Ok(()) + }) + .unwrap(); + let before = rgb(&s, SIDE / 2, SIDE / 2)[0]; + assert!(before > 1.0, "{before}"); + s.execute("paint.dodge", json!({"points": [[SIDE / 2, SIDE / 2]], "size": 40, "hardness": 100})).unwrap(); + let after = rgb(&s, SIDE / 2, SIDE / 2)[0]; + assert!(after >= before, "32-bit Grayscale Dodge clipped {before} to {after}"); +} + +#[test] +fn dodge_keeps_light_above_white_when_luma_is_not_positive_in_32_bit() { + // A channel above white next to a negative one: luma <= 0, so Protect Tones can't scale the + // colour by luma. It takes the per-channel curve instead and keeps the light above white. + for exposure in [25, 100] { + for o in [[1.2f32, -0.7, 0.2], [1.01, -0.52, 0.02]] { + let mut s = patches(32); + s.edit("bright", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + let px = photocraft_raster::from_rgba(&surf.format(), [o[0], o[1], o[2], 1.0]); + surf.write_region(photocraft_geom::Rect::new(0, 0, SIDE, SIDE), &px.repeat((SIDE * SIDE) as usize)); + Ok(()) + }) + .unwrap(); + assert_eq!(rgb(&s, SIDE / 2, SIDE / 2), o); + let c = dodge_each(&mut s, json!({"exposure": exposure}))[0]; + assert!(c[0] >= o[0], "{exposure} % Dodge of {o:?} clipped light above white: {c:?}"); + let e = dodge_burn(o, exposure as f32 / 100.0, ToneRange::Midtones, false, false); + assert!(c.iter().zip(e).all(|(c, e)| (c - e).abs() < 1e-5), "{exposure} % Dodge of {o:?}: got {c:?}, the per-channel curve gives {e:?}"); + } + } +} + +#[test] +fn dodge_keeps_tones_in_order_in_32_bit() { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 256, "height": 8, "depth": 32, "mode": "rgb"})).unwrap(); + s.edit("ramp", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + let fmt = surf.format(); + let data: Vec = (0..8).flat_map(|_| (0..256).flat_map(|x| photocraft_raster::from_rgba(&fmt, [x as f32 / 255.0; 4]))).collect(); + surf.write_region(photocraft_geom::Rect::new(0, 0, 256, 8), &data); + Ok(()) + }) + .unwrap(); + s.execute("paint.dodge", json!({"points": [[-20, 4], [276, 4]], "size": 40, "hardness": 100})).unwrap(); + let row: Vec = (0..256).map(|x| rgb(&s, x, 4)[0]).collect(); + assert!(row.windows(2).all(|w| w[1] >= w[0]), "{row:?}"); + assert!(row.iter().all(|v| (0.0..=1.0).contains(v)) && row[0] == 0.0 && row[255] == 1.0, "{row:?}"); +}