PhotoCraft: An open-source, photo editor written by scratch in pure Rust
fix(curves): 32-bit Curves continue past 0..1 like Photoshop (#8782)
FinnNk89d127d25981
diff --git a/crates/compose/src/adjust.rs b/crates/compose/src/adjust.rsindex d03c7a507..386ab5319 100644--- a/crates/compose/src/adjust.rs+++ b/crates/compose/src/adjust.rs@@ -77,6 +77,12 @@ pub fn apply_with(adj: &Adjustment, buf: &mut Buffer, transfer: Transfer) {/// unrounded). Integer depths work on whole levels like Photoshop's (see [`levels_q`] and/// `adjustment_quantum`), 32-bit documents get its float Levels (see [`levels_float`]).pub fn apply_depth(adj: &Adjustment, buf: &mut Buffer, transfer: Transfer, depth: Option<SampleType>) {+ apply_depth_mode(adj, buf, transfer, depth, ColorMode::Rgb);+}++/// [`apply_depth`] in a document of colour `mode` (which decides whether float curves extend,+/// see [`float_tone_extrapolates`]).+fn apply_depth_mode(adj: &Adjustment, buf: &mut Buffer, transfer: Transfer, depth: Option<SampleType>, mode: ColorMode) {match adj {Adjustment::Invert => map_rgb(buf, |c| [1.0 - c[0], 1.0 - c[1], 1.0 - c[2]]),Adjustment::Threshold { level } => map_rgb(buf, |c| [if threshold_white(c, *level, depth) { 1.0 } else { 0.0 }; 3]),@@ -143,7 +149,7 @@ pub fn apply_depth(adj: &Adjustment, buf: &mut Buffer, transfer: Transfer, depthreturn;}let luts = tone_luts_depth(adj, depth);- apply_tone(buf, *space, &luts, identity);+ apply_tone(buf, *space, &luts, identity, float_tone_extrapolates(adj, depth, mode));}Adjustment::HueSaturation { hue, saturation, lightness, colorize, ranges } => {let table = (!*colorize && ranges.iter().any(|r| !r.is_neutral())).then(|| hue_range_tables(ranges));@@ -338,7 +344,7 @@ pub fn apply_in(adj: &Adjustment, buf: &mut Buffer, transfer: Transfer, depth: O});}} else {- apply_depth(adj, buf, transfer, depth);+ apply_depth_mode(adj, buf, transfer, depth, mode);}}@@ -566,8 +572,8 @@ fn apply_lab(adj: &Adjustment, buf: &mut Buffer, depth: Option<SampleType>) {}}-/// Float RGB curve channels with no edit must preserve samples outside the LUT domain.-/// Edited curves retain the existing spline/LUT behaviour until HDR extrapolation has an oracle.+/// Float RGB curve channels with no edit must preserve samples outside the LUT domain; edited+/// ones extend past it (see [`float_tone_extrapolates`]).pub fn float_tone_identity(adj: &Adjustment, depth: Option<SampleType>) -> [bool; 3] {match adj {Adjustment::Curves { master, per_channel, space: ToneSpace::Rgb, .. } if depth == Some(SampleType::F32) => {@@ -577,9 +583,18 @@ pub fn float_tone_identity(adj: &Adjustment, depth: Option<SampleType>) -> [bool}}-pub(crate) fn apply_tone(buf: &mut Buffer, space: ToneSpace, luts: &[Vec<f32>; 4], identity: [bool; 3]) {+/// Whether an edited Curves adjustment continues past 0..1 instead of clipping: in a 32-bit RGB+/// document Photoshop extends each curve beyond its end points along the slope of its end+/// segments (#7157: `[[0,0],[255,128]]` maps -0.5 to -0.250980407 and 2 to 1.003921628). Only+/// in RGB documents: the curve's space is not the document's, and other modes keep the table.+pub fn float_tone_extrapolates(adj: &Adjustment, depth: Option<SampleType>, mode: ColorMode) -> bool {+ matches!(adj, Adjustment::Curves { space: ToneSpace::Rgb, .. }) && depth == Some(SampleType::F32) && mode == ColorMode::Rgb+}++pub(crate) fn apply_tone(buf: &mut Buffer, space: ToneSpace, luts: &[Vec<f32>; 4], identity: [bool; 3], extrapolate: bool) {+ let sample = if extrapolate { lut_extended } else { lut };match space {- ToneSpace::Rgb => map_rgb(buf, |c| std::array::from_fn(|i| if identity[i] { c[i] } else { lut(&luts[i], c[i]) })),+ ToneSpace::Rgb => map_rgb(buf, |c| std::array::from_fn(|i| if identity[i] { c[i] } else { sample(&luts[i], c[i]) })),ToneSpace::Cmyk | ToneSpace::Lab => map_rgb(buf, |c| tone_in_space(space, luts, c)),}}@@ -996,6 +1011,24 @@ fn lut(table: &[f32], v: f32) -> f32 {table[i] * (1.0 - f) + table[j] * f}+/// Table steps the end slopes of [`lut_extended`] are measured over: one step's difference near+/// 0.5 carries f32 rounding (2e-4 of the slope), while 16 steps are still only 0.4 % of the domain.+pub const TONE_SLOPE_SPAN: usize = 16;++/// [`lut`] continued past 0..1 along the slope of the table's end segments, as Photoshop applies+/// a curve to float samples ([`float_tone_extrapolates`]). Inside the domain it is [`lut`];+/// non-finite samples stay with it too, so an infinite one can't become NaN on a flat end.+#[inline]+fn lut_extended(table: &[f32], v: f32) -> f32 {+ let n = table.len();+ if !v.is_finite() || (0.0..=1.0).contains(&v) || n < 2 {+ return lut(table, v);+ }+ let k = TONE_SLOPE_SPAN.min(n - 1);+ let per_unit = (n - 1) as f32 / k as f32;+ if v < 0.0 { table[0] + v * (table[k] - table[0]) * per_unit } else { table[n - 1] + (v - 1.0) * (table[n - 1] - table[n - 1 - k]) * per_unit }+}+/// Photo Filter's linear-light RGB matrix. Photoshop multiplies the pixel's D50 XYZ, relative to/// white, by the filter colour's (mixed in by `density`): a fixed linear map, so it is folded into/// one matrix. With `normalize_y` the map keeps luminance Y (32-bit Preserve Luminosity; 8/16-bitdiff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rsindex 6cb6707e0..9c6da0a5b 100644--- a/crates/compose/src/lib.rs+++ b/crates/compose/src/lib.rs@@ -890,7 +890,8 @@ impl<'a> Ctx<'a> {if identity == [true; 3] {return;}- adjust::apply_tone(buf, *space, luts.get_or_init(|| adjust::tone_luts_depth(adj, Some(self.depth))), identity);+ let extrapolate = adjust::float_tone_extrapolates(adj, Some(self.depth), self.mode);+ adjust::apply_tone(buf, *space, luts.get_or_init(|| adjust::tone_luts_depth(adj, Some(self.depth))), identity, extrapolate);} else {adjust::apply_in(adj, buf, self.transfer, Some(self.depth), self.mode);}diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rsindex 11da5a62f..2ede50e9f 100644--- a/crates/compose/src/tests.rs+++ b/crates/compose/src/tests.rs@@ -94,7 +94,7 @@ fn identity_float_curves_match_previous_mapping_bits() {px: vec![[2.0, -0.0, -0.2, 1.0], [f32::from_bits(0x7fc01234), f32::INFINITY, f32::NEG_INFINITY, 0.6], [0.7, -0.0, 1.5, 0.0], [0.1; 4]],};let mut previous = input.clone();- adjust::apply_tone(&mut previous, ToneSpace::Rgb, &adjust::tone_luts_depth(&adj, Some(SampleType::F32)), [true; 3]);+ adjust::apply_tone(&mut previous, ToneSpace::Rgb, &adjust::tone_luts_depth(&adj, Some(SampleType::F32)), [true; 3], false);let mut actual = input.clone();adjust::apply_depth(&adj, &mut actual, adjust::Transfer::Gamma(1.0), Some(SampleType::F32));assert_buffer_bits(&actual, &previous);@@ -2798,6 +2798,53 @@ fn exposure_scales_32_bit_samples_as_stored() {}}+/// #7157, measured on Photoshop 27.11: an edited Curves in a 32-bit RGB document continues past+/// 0..1 along its end segments instead of clipping. The straight curve `[[0,0],[255,128]]` maps+/// -0.5, 0.5 and 2 to -0.250980407, 0.250980407 and 1.003921628, through Image › Adjustments and+/// through an adjustment layer alike. 8/16-bit documents still clip to the table.+#[test]+fn float_curves_extend_past_the_unit_range_like_photoshop() {+ use photocraft_doc::adjust::CurvePoint;+ let line = vec![CurvePoint { input: 0.0, output: 0.0 }, CurvePoint { input: 1.0, output: 128.0 / 255.0 }];+ let ident = vec![CurvePoint { input: 0.0, output: 0.0 }, CurvePoint { input: 1.0, output: 1.0 }];+ let adj = Adjustment::Curves { master: line, per_channel: std::array::from_fn(|_| ident.clone()), space: ToneSpace::Rgb, black: Vec::new(), pencil: false };+ let input = Buffer { rect: Rect::new(0, 0, 3, 1), px: vec![[-0.5, -0.5, -0.5, 1.0], [0.5, 0.5, 0.5, 1.0], [2.0, 2.0, 2.0, 1.0]] };+ // Photoshop's samples, compared in f64 so the reference keeps its printed digits.+ let want = [-0.250980407f64, 0.250980407, 1.003921628];+ let check = |got: &Buffer, what: &str| {+ for (p, w) in got.px.iter().zip(want) {+ assert!(p[..3].iter().all(|v| (f64::from(*v) - w).abs() < 2e-5), "{what}: {p:?} vs {w}");+ assert_eq!(p[3], 1.0);+ }+ };+ let mut destructive = input.clone();+ adjust::apply_depth(&adj, &mut destructive, adjust::Transfer::Gamma(1.0), Some(SampleType::F32));+ check(&destructive, "Image › Adjustments");+ let doc = Document::new("hdr", Size::new(3, 1), ColorMode::Rgb, SampleType::F32);+ let patterns = pattern::PreparedPatterns::new(&[], pattern::PREPARED_PATTERN_BYTES);+ let cx = Ctx::for_doc(&doc, &patterns);+ let mut layer = input.clone();+ cx.apply_adjustment(&adj, &mut layer);+ check(&layer, "adjustment layer");+ // Not at 8 or 16 bits: those samples never leave 0..1, and the table's ends hold.+ for depth in [SampleType::U8, SampleType::U16] {+ let mut clipped = input.clone();+ adjust::apply_depth(&adj, &mut clipped, adjust::Transfer::for_document(ColorMode::Rgb, depth), Some(depth));+ assert!(clipped.px[2][..3].iter().all(|v| *v <= 128.0 / 255.0 + 1e-4), "{depth:?}: {:?}", clipped.px[2]);+ }+ // Only in RGB documents: a 32-bit grayscale document keeps the table's end.+ let mut gray = input.clone();+ adjust::apply_in(&adj, &mut gray, adjust::Transfer::Gamma(1.0), Some(SampleType::F32), ColorMode::Grayscale);+ assert!(gray.px[2][..3].iter().all(|v| *v <= 128.0 / 255.0 + 1e-4), "grayscale: {:?}", gray.px[2]);+ let mut rgb = input.clone();+ adjust::apply_in(&adj, &mut rgb, adjust::Transfer::Gamma(1.0), Some(SampleType::F32), ColorMode::Rgb);+ check(&rgb, "apply_in in RGB");+ // Infinite samples don't become NaN on the way out.+ let mut odd = Buffer { rect: Rect::new(0, 0, 1, 1), px: vec![[f32::INFINITY, f32::NEG_INFINITY, 0.5, 1.0]] };+ adjust::apply_depth(&adj, &mut odd, adjust::Transfer::Gamma(1.0), Some(SampleType::F32));+ assert!(odd.px[0].iter().all(|v| !v.is_nan()), "{:?}", odd.px[0]);+}+#[test]fn float_adjustments_preserve_hdr_range() {let identity = vec![photocraft_doc::adjust::CurvePoint { input: 0.0, output: 0.0 }, photocraft_doc::adjust::CurvePoint { input: 1.0, output: 1.0 }];diff --git a/crates/gpu/src/compose.wgsl b/crates/gpu/src/compose.wgslindex a06996a21..3eb1cfe17 100644--- a/crates/gpu/src/compose.wgsl+++ b/crates/gpu/src/compose.wgsl@@ -616,8 +616,22 @@ fn levels_float(record: i32, v: f32) -> f32 {return lut_at(base + 3) + mapped * (lut_at(base + 4) - lut_at(base + 3));}-fn tone_channel(row: i32, v: f32, identity: f32) -> f32 {+fn tone_channel(row: i32, v: f32, identity: f32, extrapolate: f32) -> f32 {if (identity > 0.5) { return v; }+ // Mirrors compose::adjust::lut_extended: past 0..1 along the end segments' slopes, measured+ // over TONE_SLOPE_SPAN (16) table steps.+ if (extrapolate > 0.5 && abs(v) <= 3.0e38) {+ if (v < 0.0) {+ let a = textureLoad(lut_tex, vec2(0, row), 0).r;+ let b = textureLoad(lut_tex, vec2(16, row), 0).r;+ return a + v * (b - a) * (4095.0 / 16.0);+ }+ if (v > 1.0) {+ let a = textureLoad(lut_tex, vec2(4079, row), 0).r;+ let b = textureLoad(lut_tex, vec2(4095, row), 0).r;+ return b + (v - 1.0) * (b - a) * (4095.0 / 16.0);+ }+ }return lut(row, v);}@@ -651,7 +665,7 @@ fn adjust(c: vec3<f32>) -> vec3<f32> {return clamp(v, vec3(0.0), vec3(1.0));}case 6: { return vec3(exposure(c.r, p0), exposure(c.g, p0), exposure(c.b, p0)); } // Exposure- case 7: { return vec3(tone_channel(0, c.r, p0.x), tone_channel(1, c.g, p0.y), tone_channel(2, c.b, p0.z)); } // Levels / Curves / modern Brightness/Contrast (compose::adjust::modern_lut)+ case 7: { return vec3(tone_channel(0, c.r, p0.x, p0.w), tone_channel(1, c.g, p0.y, p0.w), tone_channel(2, c.b, p0.z, p0.w)); } // Levels / Curves / modern Brightness/Contrast (compose::adjust::modern_lut)case 17: { return vec3(levels_float(0, levels_float(1, c.r)), levels_float(0, levels_float(2, c.g)), levels_float(0, levels_float(3, c.b))); }case 8: { // Hue/Saturationlet hsl = rgb_to_hsl(c);diff --git a/crates/gpu/src/plan.rs b/crates/gpu/src/plan.rsindex 69e4b6485..38cc879b0 100644--- a/crates/gpu/src/plan.rs+++ b/crates/gpu/src/plan.rs@@ -1027,7 +1027,7 @@ impl<'a> Planner<'a> {}let mut p = Pass::new(Kernel::Adjust, 0);p.a = Some(src);- let (kind, params, lut) = adjustment_program(adj, self.cx.transfer, self.cx.depth);+ let (kind, params, lut) = adjustment_program(adj, self.cx.transfer, self.cx.depth, self.cx.mode);p.adjust_kind = kind;p.params = params;p.lut = lut;@@ -1656,7 +1656,7 @@ fn transfer_exponent(t: Transfer) -> f32 {}/// Adjustment → (kernel kind, parameters, LUT rows). Kinds are the `switch` in `adjust()`.-pub fn adjustment_program(adj: &Adjustment, transfer: Transfer, depth: photocraft_color::SampleType) -> Program {+pub fn adjustment_program(adj: &Adjustment, transfer: Transfer, depth: photocraft_color::SampleType, mode: photocraft_color::ColorMode) -> Program {let mut p = [[0.0f32; 4]; 4];match adj {Adjustment::Invert => (1, p, None),@@ -1711,6 +1711,8 @@ pub fn adjustment_program(adj: &Adjustment, transfer: Transfer, depth: photocraffor (v, identity) in p[0].iter_mut().zip(adjust::float_tone_identity(adj, Some(depth))) {*v = if identity { 1.0 } else { 0.0 };}+ // p0.w: continue the curve past 0..1 (32-bit RGB Curves, #7157).+ p[0][3] = if adjust::float_tone_extrapolates(adj, Some(depth), mode) { 1.0 } else { 0.0 };(7, p, Some(adjust::tone_luts_depth(adj, Some(depth)).iter().take(3).map(|t| to_row(t)).collect()))}Adjustment::HueSaturation { hue, saturation, lightness, colorize, ranges } => {@@ -1996,7 +1998,7 @@ mod tests {fn color_lookup_with_an_overflowing_stored_size_uploads_no_table() {for size in [1 << 22, u32::MAX] {let a = Adjustment::ColorLookup { name: "x".into(), lut: Some(std::sync::Arc::new(vec![0.5; 24])), size, tetrahedral: false, dither: false };- let (kind, _, rows) = adjustment_program(&a, Transfer::Srgb, SampleType::U8);+ let (kind, _, rows) = adjustment_program(&a, Transfer::Srgb, SampleType::U8, photocraft_color::ColorMode::Rgb);assert_eq!((kind, rows.is_none()), (0, true), "size {size}");}}diff --git a/crates/gpu/tests/it/parity.rs b/crates/gpu/tests/it/parity.rsindex c07b43833..3305083f4 100644--- a/crates/gpu/tests/it/parity.rs+++ b/crates/gpu/tests/it/parity.rs@@ -57,6 +57,14 @@ fn hdr_adjustments_preserve_range_and_cpu_parity() {black: Vec::new(),pencil: false,},+ // #7157: an edited curve continues past 0..1 along its end segments (Photoshop's `[[0,0],[255,128]]`).+ Adjustment::Curves {+ master: vec![CurvePoint { input: 0.0, output: 0.0 }, CurvePoint { input: 1.0, output: 128.0 / 255.0 }],+ per_channel: std::array::from_fn(|_| identity.clone()),+ space: Default::default(),+ black: Vec::new(),+ pencil: false,+ },// 32-bit Photoshop rules: unclipped, legacy pivot 127, the mixer's 1/1024 steps and halved constant.Adjustment::BrightnessContrast { brightness: 25.0, contrast: 30.0, legacy: true },Adjustment::BrightnessContrast { brightness: -20.0, contrast: -30.0, legacy: true },