diff --git a/crates/develop/src/settings.rs b/crates/develop/src/settings.rs index 9f8f6f872ae..cdcbafb4147 100644 --- a/crates/develop/src/settings.rs +++ b/crates/develop/src/settings.rs @@ -127,12 +127,17 @@ pub enum Process { /// V16, with Apple ProRAW's tone sliders running in Lightroom's fitted tone chain /// (`lightcraft_pipeline::proraw`). V17, + /// V17, with Whites and the parametric curve from a fitted model, and the tone curves applied + /// hue-preserving: Whites, the parametric and point curve in linear ProPhoto RGB, then the red, green and + /// blue curves per channel, before the colour stage (`lightcraft_pipeline::curve_stage`, + /// `docs/curve-stage.md`). + V18, } impl Process { /// Every process, oldest first (`ProcessVersion(9)` names none and renders as V8; 11 and 12 name none and /// render as V10). - pub const ALL: [Process; 14] = [ + pub const ALL: [Process; 15] = [ Process::V1, Process::V2, Process::V3, @@ -147,8 +152,9 @@ impl Process { Process::V15, Process::V16, Process::V17, + Process::V18, ]; - pub const LATEST: Process = Process::V17; + pub const LATEST: Process = Process::V18; pub const fn version(self) -> ProcessVersion { match self { @@ -166,6 +172,7 @@ impl Process { Process::V15 => ProcessVersion(15), Process::V16 => ProcessVersion(16), Process::V17 => ProcessVersion(17), + Process::V18 => ProcessVersion(18), } } } diff --git a/crates/gpu/src/params.rs b/crates/gpu/src/params.rs index e760bda9aa6..2b9db6179b4 100644 --- a/crates/gpu/src/params.rs +++ b/crates/gpu/src/params.rs @@ -23,6 +23,10 @@ const FIELDS: &[(&str, usize)] = &[ ("SRGB_OFF", 1), ("CURVE_OFF", 1), ("CURVES", 1), + ("STAGE", 1), + ("STAGE_OFF", 1), + ("STAGE_REFINE", 1), + ("STAGE_WHITES", 1), ("GAIN", 1), ("EV", 1), ("AIR", 1), @@ -296,21 +300,23 @@ pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Pr let srgb_off = aux.len(); aux.extend_from_slice(&srgb_lut()[..]); let curve_off = aux.len(); - if let Some(c) = &fp.curves { - for l in c { - if l.v.len() != CURVE_N as usize { - // a wrong-length curve would shift every later aux offset (CURVE_OFF, MASK_OFF and - // the mask terms that follow) and make the kernel read the wrong data. `fail()` - // records the failure on this thread so the render falls back to the CPU; the - // partial `(p, aux)` returned here is never bound to a pipeline. - fail(FailKind::Fatal, format!("curve table has {} entries, expected {}", l.v.len(), CURVE_N)); - // `p` is only assembled below the curve loop, so an empty block is as good as any: - // the caller (render.rs) gates on `failed()` right after this returns and bails to - // the CPU fallback before indexing `p` or uploading `aux`. - return (Vec::new(), aux); - } - aux.extend_from_slice(&l.v); + let stage_off = curve_off + fp.curves.as_ref().map_or(0, |c| c.len() * CURVE_N as usize); + // process V18's stage (red, green, blue, then the base table) or the earlier processes' curves + // (and Whites alone after the base table, when Refine Saturation needs it) + let tables = fp.curves.iter().flatten().chain(fp.curve_stage.iter().flat_map(|c| c.chan.iter().chain([&c.base]).chain(c.whites.iter()))); + for l in tables { + if l.v.len() != CURVE_N as usize { + // a wrong-length curve would shift every later aux offset (CURVE_OFF, MASK_OFF and + // the mask terms that follow) and make the kernel read the wrong data. `fail()` + // records the failure on this thread so the render falls back to the CPU; the + // partial `(p, aux)` returned here is never bound to a pipeline. + fail(FailKind::Fatal, format!("curve table has {} entries, expected {}", l.v.len(), CURVE_N)); + // `p` is only assembled below the curve loop, so an empty block is as good as any: + // the caller (render.rs) gates on `failed()` right after this returns and bails to + // the CPU fallback before indexing `p` or uploading `aux`. + return (Vec::new(), aux); } + aux.extend_from_slice(&l.v); } let mask_off = aux.len(); for m in masks { @@ -358,6 +364,10 @@ pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Pr p.u("SRGB_OFF", srgb_off as u32); p.u("CURVE_OFF", curve_off as u32); p.b("CURVES", fp.curves.is_some()); + p.b("STAGE", fp.curve_stage.is_some()); + p.u("STAGE_OFF", stage_off as u32); + p.f("STAGE_REFINE", fp.curve_stage.as_ref().map_or(1.0, |c| c.refine)); + p.b("STAGE_WHITES", fp.curve_stage.as_ref().is_some_and(|c| c.whites.is_some())); p.f("REFINE_SAT", fp.refine_sat); p.f("GAIN", fp.gain); p.f("EV", fp.ev); diff --git a/crates/gpu/src/wgsl/finish.wgsl b/crates/gpu/src/wgsl/finish.wgsl index 265e84b1faa..1798b11d355 100644 --- a/crates/gpu/src/wgsl/finish.wgsl +++ b/crates/gpu/src/wgsl/finish.wgsl @@ -127,6 +127,86 @@ fn light_ops(d: vec3) -> vec3 { return mul3(PRO_TO_2020, p); } +// A table of process V18's curve stage (`Lut1::eval`) at offset `o` in `aux`. +fn stage_lut(o: u32, x: f32) -> f32 { + let f = clamp(x, 0.0, 1.0) * f32(CURVE_N - 1u); + let i = min(u32(f), CURVE_N - 2u); + let t = f - f32(i); + return aux[o + i] + (aux[o + i + 1u] - aux[o + i]) * t; +} + +// `CurveStage::apply`: the base table on the largest and smallest channel of sRGB-encoded linear ProPhoto, the +// middle one keeping its place between them in linear light, then the red, green and blue curves per channel. +// `curve_stage::hue_preserving`: the table at `o` on the largest and smallest channel of `e`, the middle one keeping +// its place between them in linear light (`pc`). Linear, in [0, 1]. +fn stage_hue_preserving(o: u32, e: vec3, pc: vec3, hi: u32, lo: u32) -> vec3 { + let la = srgb_linear(stage_lut(o, e[hi])); + let lb = srgb_linear(stage_lut(o, e[lo])); + let pa = pc[hi]; + let pb = pc[lo]; + var out = vec3(0.0); + for (var k = 0u; k < 3u; k++) { + var t = 1.0; + if (pa > pb) { + t = (pc[k] - pb) / (pa - pb); + } + out[k] = clamp(lb + (la - lb) * t, 0.0, 1.0); + } + return out; +} + +fn curve_stage(d: vec3) -> vec3 { + let p = mul3(PRO_FROM_2020, d); + var pc = clamp(p, vec3(0.0), vec3(1.0)); + var e = vec3(srgb_exact(pc.x), srgb_exact(pc.y), srgb_exact(pc.z)); + var hi = 0u; + var lo = 0u; + for (var k = 1u; k < 3u; k++) { + if (e[k] > e[hi]) { + hi = k; + } + if (e[k] < e[lo]) { + lo = k; + } + } + let off = pu(F_STAGE_OFF); + let base = stage_hue_preserving(off + 3u * CURVE_N, e, pc, hi, lo); + var curved = vec3(0.0); + for (var k = 0u; k < 3u; k++) { + curved[k] = stage_lut(off + k * CURVE_N, srgb_exact(base[k])); + } + var q = vec3(0.0); + for (var k = 0u; k < 3u; k++) { + q[k] = srgb_linear(clamp(curved[k], 0.0, 1.0)); + } + let rs = pf(F_STAGE_REFINE); + if (rs < 1.0) { + // the saturation back towards the input's after Whites, at the curves' luminance + var reference = e; + if (pu(F_STAGE_WHITES) != 0u) { + let w = stage_hue_preserving(off + 4u * CURVE_N, e, pc, hi, lo); + reference = vec3(srgb_exact(w.x), srgb_exact(w.y), srgb_exact(w.z)); + } + let rr = refine_saturation(reference, curved, rs); + var r = vec3(0.0); + for (var k = 0u; k < 3u; k++) { + r[k] = srgb_linear(clamp(rr[k], 0.0, 1.0)); + } + let yq = dot(q, PRO_Y); + let yr = dot(r, PRO_Y); + q = r; + if (yr > 1e-6) { + q = r * (yq / yr); + } + } + for (var k = 0u; k < 3u; k++) { + if (p[k] > 1.0) { + q[k] += p[k] - 1.0; + } + } + return mul3(PRO_TO_2020, q); +} + // `proraw::tone_rgb`: the table at `o` on linear ProPhoto `p`, hue-preserving (the largest and // smallest channel go through it, the middle one keeps its relative position between them). fn tone_rgb_at(o: u32, p: vec3) -> vec3 { @@ -811,6 +891,11 @@ fn main(@builtin(global_invocation_id) gid: vec3) { d = light_ops(d); } + // --- process V18: Whites and the tone curves + if (pu(F_STAGE) != 0u) { + d = curve_stage(d); + } + // --- colour d = color_ops(d, lt[11], lt[12]); if (tint_on) { diff --git a/crates/gpu/tests/it/equivalence.rs b/crates/gpu/tests/it/equivalence.rs index 67fa3a445c8..2aade0e3e05 100644 --- a/crates/gpu/tests/it/equivalence.rs +++ b/crates/gpu/tests/it/equivalence.rs @@ -233,7 +233,9 @@ fn curve_input_matches_the_gpu_prefix_and_keeps_later_operations_out() { let v = 0.01 + x as f32 / 500.0; [v, v * (0.25 + y as f32 / 100.0), v * 0.4] })); - let mut s = DevelopSettings::default(); + // up to V17 the curves act on the encoded output, so a curve's input is the output of its predecessors; V18 samples + // where its curve stage reads (`lightcraft_pipeline` `v18_samples_where_the_curve_stage_reads_not_after_the_colour_tools`) + let mut s = DevelopSettings { process: Process::V17.version(), ..DevelopSettings::default() }; s.light.exposure = 0.5; s.curve.shadows = 45.0; s.curve.master = vec![Point::new(0.0, 0.04), Point::new(0.25, 0.65), Point::new(1.0, 0.95)]; @@ -988,6 +990,50 @@ fn light_v3_operators_match() { } } +/// Process V18's curve stage: Whites, the parametric curve, the point curves and Refine Saturation, on a camera curve +/// and without one, in SDR and HDR. +#[test] +fn curve_stage_matches() { + if !gpu() { + return; + } + use lightcraft_geom::Point; + let src = scene(0, 960, 640); + let curve = lightcraft_pipeline::tone::CameraTone::new(std::array::from_fn(|i| { + let x = 0.004 * 1.18f32.powi(i as i32); + [x, 1.0 - (-2.0 * x).exp()] + })) + .unwrap(); + let raw = SourceInfo { raw: true, camera_tone: Some(curve), ..Default::default() }; + let req = RenderRequest::fit(720, 720); + let v18 = || DevelopSettings { process: Process::V18.version(), ..Default::default() }; + for v in [-100.0, -30.0, 40.0, 100.0] { + let mut s = v18(); + s.light.whites = v; + check(&format!("V18 Whites {v}"), &src, &raw, &s, &req); + } + let mut s = v18(); + s.curve.highlights = -40.0; + s.curve.lights = 25.0; + s.curve.darks = -15.0; + s.curve.shadows = 30.0; + check("V18 parametric", &src, &raw, &s, &req); + s.curve.master = vec![Point { x: 0.0, y: 0.05 }, Point { x: 0.5, y: 0.55 }, Point { x: 1.0, y: 0.95 }]; + s.curve.red = vec![Point { x: 0.0, y: 0.0 }, Point { x: 0.4, y: 0.5 }, Point { x: 1.0, y: 1.0 }]; + s.curve.blue = vec![Point { x: 0.0, y: 0.1 }, Point { x: 1.0, y: 0.9 }]; + s.light.whites = -25.0; + check("V18 curves", &src, &raw, &s, &req); + s.curve.refine_saturation = 30.0; + check("V18 Refine Saturation", &src, &raw, &s, &req); + check("V18 curves, no camera curve", &src, &SourceInfo::default(), &s, &req); + s.curve.split_mid = 40.0; + check("V18 other splits", &src, &raw, &s, &req); + s.curve.split_mid = 50.0; + s.hdr.enabled = true; + s.hdr.max_ev = 2.0; + check("V18 HDR preview", &src, &raw, &s, &req); +} + /// Issue #632: the Highlights / Shadows base of each process (V1: the edge-aware filter of log /// luminance; V2 to V7: of its fine median, V8 on: 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. diff --git a/crates/pipeline/src/curve.rs b/crates/pipeline/src/curve.rs index 16b3df808e6..79e110650e8 100644 --- a/crates/pipeline/src/curve.rs +++ b/crates/pipeline/src/curve.rs @@ -9,6 +9,9 @@ use lightcraft_develop::ToneCurve; pub use craft_develop::curve::{PARAM_AMOUNTS, PARAM_LUT}; /// The parametric (region) curve of a [`ToneCurve`], backed by `craft_develop::curve::ParametricCurve`. +/// +/// Processes V1 to V17 render it, and V18 renders it when the splits are moved. The curve editor draws it +/// through [`crate::curve_stage::ParametricGraph`], which picks the measured regions where V18 renders those. #[derive(Clone, Debug)] pub struct ParametricCurve(craft_develop::curve::ParametricCurve); diff --git a/crates/pipeline/src/curve_input.rs b/crates/pipeline/src/curve_input.rs index 9e1269fcbf5..134184a7c46 100644 --- a/crates/pipeline/src/curve_input.rs +++ b/crates/pipeline/src/curve_input.rs @@ -3,7 +3,7 @@ //! The normal renderer is unchanged. A small, separate render shares its spatial stages and //! per-pixel code, stopping before the selected curve and everything that follows it. -use lightcraft_develop::{DevelopSettings, ToneCurve}; +use lightcraft_develop::{DevelopSettings, Process, ToneCurve}; use lightcraft_raster::{Histogram, Rgb32f, Rgba8}; use serde::{Deserialize, Serialize}; use std::sync::Arc; @@ -107,7 +107,12 @@ pub(crate) fn finish( if let Some(display) = &request.display { fp.for_display(display, request.proof); } - fp.curves = crate::finish::curve_luts(&input.predecessors(&settings.curve)); + // only the predecessors, wherever the process applies its curves (encoded output, or V18's curve stage) + let predecessors = DevelopSettings { curve: input.predecessors(&settings.curve), ..settings.clone() }; + fp.curves = if settings.process.process() < Process::V18 { crate::finish::curve_luts(&predecessors.curve) } else { None }; + fp.curve_stage = crate::finish::curve_stage_for(&predecessors, fp.proraw.is_some()); + // V18's curves read sRGB-encoded linear ProPhoto after the tone map: sample there, not after the colour tools + fp.sample_at_curve_stage = settings.process.process() >= Process::V18; fp.refine_sat = 1.0; // the samples, and the 8-bit pixels as `finish` dithers them at the same place in the output let samples = crate::finish::finish_with(p, &fp, false, true, |x, y, e| { @@ -115,7 +120,8 @@ pub(crate) fn finish( (e, [crate::finish::enc(e[0], d), crate::finish::enc(e[1], d), crate::finish::enc(e[2], d), 255]) }); let (samples, data): (Vec<[f32; 3]>, Vec<[u8; 4]>) = samples.into_iter().unzip(); - let histogram = of_encoded(&samples, fp.out_luma); + let weights = if fp.sample_at_curve_stage { crate::light_v3::PRO_Y } else { fp.out_luma }; + let histogram = of_encoded(&samples, weights); let image = Rgba8 { width: w, height: h, data }; Rendered { image, histogram, deep: None } } diff --git a/crates/pipeline/src/curve_input_tests.rs b/crates/pipeline/src/curve_input_tests.rs index 5426374ccf1..f0c1caba7a0 100644 --- a/crates/pipeline/src/curve_input_tests.rs +++ b/crates/pipeline/src/curve_input_tests.rs @@ -55,9 +55,11 @@ fn input_follows_exposure_but_not_its_own_curve_or_later_curves() { assert_ne!(a.image, b.image); } +/// Up to V17 the curves act on the encoded output, so a curve's input is the output of its predecessors. (V18: +/// `v18_samples_where_the_curve_stage_reads_not_after_the_colour_tools`.) #[test] fn each_curve_sees_exactly_its_predecessors_including_profile_contributions() { - let mut s = DevelopSettings::default(); + let mut s = DevelopSettings { process: lightcraft_develop::Process::V17.version(), ..DevelopSettings::default() }; s.profile.id = "lc.film.golden-hour".into(); s.curve.shadows = 45.0; s.curve.master = bent(); @@ -171,7 +173,8 @@ fn diagnostic_and_normal_renders_share_spatial_cache_without_changing_pixels() { fn input_uses_the_display_primaries_and_effective_edit() { let src = source(); let info = SourceInfo::default(); - let mut s = DevelopSettings::default(); + // up to V17 the curves act on the encoded output, in the display's primaries (V18's read ProPhoto) + let mut s = DevelopSettings { process: lightcraft_develop::Process::V17.version(), ..DevelopSettings::default() }; s.light.exposure = 1.0; s.curve.lights = 55.0; s.curve.master = bent(); @@ -181,7 +184,7 @@ fn input_uses_the_display_primaries_and_effective_edit() { let mut effective = s.effective().into_owned(); effective.curve = CurveInput::Red.predecessors(&effective.curve); assert_eq!(disabled.image, crate::render(&src, &info, &effective, &req).image); - let mut previous = DevelopSettings::default(); + let mut previous = DevelopSettings { process: lightcraft_develop::Process::V17.version(), ..DevelopSettings::default() }; previous.curve.lights = 45.0; let srgb = render(&src, &info, &previous, &req, None, CurveInput::Red).unwrap(); for space in [OutputSpace::DisplayP3, OutputSpace::Rec2020] { @@ -220,3 +223,36 @@ fn an_over_budget_brush_mask_fails_the_sample_instead_of_dropping_strokes() { s.masks.push(brush(vec![stroke(0.2, 0.6)])); assert!(render(&source(), &SourceInfo::default(), &s, &full_size, None, CurveInput::Master).is_ok()); } + +/// Under V18 the curves read the colour where the curve stage runs, after the tone map and before the colour tools: +/// Saturation, which comes after them, leaves every curve's input alone; on V17 it is part of it (review on #4076). +#[test] +fn v18_samples_where_the_curve_stage_reads_not_after_the_colour_tools() { + use lightcraft_develop::Process; + for ch in [CurveInput::Parametric, CurveInput::Master, CurveInput::Red] { + let on = |p: Process, saturation: f64| { + let mut s = DevelopSettings { process: p.version(), ..DevelopSettings::default() }; + s.color.saturation = saturation; + sample(&s, ch).histogram + }; + assert_eq!(on(Process::V18, -100.0), on(Process::V18, 0.0), "V18 {ch:?}: Saturation is after the curves"); + assert_ne!(on(Process::V17, -100.0), on(Process::V17, 0.0), "V17 {ch:?}: the curves read the encoded output"); + } +} + +/// On Apple ProRAW the chain applies Whites, so the curve stage the sample is built with leaves it out, as the render's +/// does: Whites alone gives no stage, a curve a stage of its own (review on #4076). +#[test] +fn proraw_curve_input_applies_whites_once() { + use lightcraft_develop::Process; + let mut s = DevelopSettings { process: Process::V18.version(), ..DevelopSettings::default() }; + s.light.whites = 40.0; + assert!(crate::finish::curve_stage_for(&s, false).is_some(), "elsewhere the stage applies Whites"); + assert!(crate::finish::curve_stage_for(&s, true).is_none(), "on ProRAW the chain does"); + s.curve.master = bent(); + let with_curve = crate::finish::curve_stage_for(&s, true).expect("the curve"); + let mut alone = s.clone(); + alone.light.whites = 0.0; + let curve_only = crate::finish::curve_stage_for(&alone, false).expect("the curve"); + assert_eq!(with_curve.base.v, curve_only.base.v, "the ProRAW stage is the curve without Whites"); +} diff --git a/crates/pipeline/src/curve_stage.rs b/crates/pipeline/src/curve_stage.rs new file mode 100644 index 00000000000..44d983e3eb2 --- /dev/null +++ b/crates/pipeline/src/curve_stage.rs @@ -0,0 +1,584 @@ +//! Process V18's tone-curve stage ([`lightcraft_develop::Process::V18`]): Whites, the parametric curve and the point +//! curves. `docs/curve-stage.md` records how the model was measured and fitted. +//! +//! - Whites, the parametric curve, the master point curve, Contrast and Blacks act hue-preserving on linear ProPhoto +//! RGB: the curve maps the largest and the smallest channel (on sRGB-encoded values), and the middle channel keeps +//! its relative position between them in linear light. +//! - The red, green and blue curves act per channel on sRGB-encoded linear ProPhoto RGB, after the master curve. +//! - Whites reaches into the midtones, and each parametric region is broad and overlapping; the regions add. +//! - Whites and the four regions come from a fitted model (`curve_stage_model`, written by `tools/lr_tone_charts.py +//! fit`): per slider direction, two smooth bumps whose gain, position and width change with the amount +//! ([`response`]). +//! +//! The stage runs after the tone map and Process V4's calibrated Contrast and Blacks, before the colour stage. It +//! replaces the curves of V17 and earlier on encoded output values; the tone map leaves Whites to it. + +use lightcraft_color::spline::{Lut1, MonotoneCurve}; +use lightcraft_color::transfer::{linear_to_srgb, srgb_to_linear}; +use lightcraft_develop::{DevelopSettings, Process, ToneCurve}; +use lightcraft_geom::Point; + +use crate::curve::ParametricCurve; +use crate::curve_stage_model as m; +use crate::light_v3::PRO_Y; + +/// Entries per table (as the shipping curve tables). +pub const N: usize = 1024; + +/// The least a region must be able to move the drawn parametric curve for a drag to move its slider: half an 8-bit level. +const REACH_MIN: f64 = 0.5 / 255.0; + +/// The default parametric splits (25, 50, 75): the fitted regions hold for them only. +const DEFAULT_SPLITS: [f64; 3] = [25.0, 50.0, 75.0]; + +/// The stage's tables: `base` (Whites, then the parametric curve, then the master point curve) acts hue-preserving, +/// `chan` (red, green, blue point curves) per channel. All on sRGB-encoded linear ProPhoto values. +#[derive(Clone, Debug)] +pub struct CurveStage { + pub chan: [Lut1; 3], + pub base: Lut1, + /// Refine Saturation, 0..1, on what the curves did (1 when only Whites is set). + pub refine: f32, + /// Whites alone, when Refine Saturation is below 1: the saturation it restores is the colour's after Whites, as + /// Lightroom's Refine Saturation belongs to the tone curve and Whites comes before it. + pub whites: Option, +} + +/// A bump of peak 1 at `p / (p + q)`, 0 at black and white and outside them. +fn bump(x: f64, p: f64, q: f64) -> f64 { + if x <= 0.0 || x >= 1.0 { + return 0.0; + } + let peak = p / (p + q); + (p * (x / peak).ln() + q * ((1.0 - x) / (1.0 - peak)).ln()).exp() +} + +/// The fitted response of a slider at `amount` (−100 to 100, clamped) for input `x`: output minus input on +/// sRGB-encoded values. Per direction, two bumps with gain `a1 t + a2 t² + a3 t³` (t = |amount| / 100) and shape +/// exponents `e^(p0 + p1 t)`, `e^(q0 + q1 t)`. +fn response(fit: &[m::Response; 2], amount: f32, x: f32) -> f32 { + if amount == 0.0 || !amount.is_finite() { + return 0.0; + } + let [negative, positive] = fit; + let side = if amount < 0.0 { negative } else { positive }; + let (t, x) = ((f64::from(amount) / 100.0).abs().min(1.0), f64::from(x)); + let r: f64 = side + .iter() + .map(|[a1, a2, a3, p0, p1, q0, q1]| (a1 * t + a2 * t * t + a3 * t * t * t) * bump(x, (p0 + p1 * t).exp(), (q0 + q1 * t).exp())) + .sum(); + r as f32 +} + +/// Whether `c` holds the default splits, the ones the regions are fitted for. +fn default_splits(c: &ToneCurve) -> bool { + [c.split_shadows, c.split_mid, c.split_highlights].iter().zip(DEFAULT_SPLITS).all(|(s, d)| (s - d).abs() <= 1e-6) +} + +/// The fitted regions at `x`, before the curve is kept monotone: the four responses added to the diagonal. +fn regions_at(amounts: [f32; 4], x: f32) -> f32 { + (x + regions_delta(amounts, x)).clamp(0.0, 1.0) +} + +/// The sum of the four fitted region responses at `x`. +fn regions_delta(amounts: [f32; 4], x: f32) -> f32 { + amounts.iter().zip(m::REGIONS.iter()).map(|(a, r)| response(r, *a, x)).sum() +} + +/// The fitted parametric curve at the default splits. +fn fitted_parametric(amounts: [f32; 4]) -> Lut1 { + let mut lut = Lut1::from_fn(N, |x| regions_at(amounts, x)); + monotone(&mut lut); + lut +} + +/// The parametric curve: the fitted regions at the default splits, else the analytic model of earlier processes. +fn parametric(c: &ToneCurve) -> Lut1 { + if !default_splits(c) { + return ParametricCurve::new(c).to_lut(); + } + fitted_parametric([c.shadows, c.darks, c.lights, c.highlights].map(|v| v as f32)) +} + +/// The parametric curve as `s`'s process renders it, for the Edit panel's graph and its drag: the fitted regions +/// under V18 at the default splits, else the analytic [`ParametricCurve`] (earlier processes, and V18 with moved +/// splits). Whites is left out of the graph. +#[derive(Clone, Debug)] +pub struct ParametricGraph { + model: ParametricCurve, + /// The fitted curve, when it is the one rendered. + fitted: Option, +} + +impl ParametricGraph { + /// The graph for `s`: the fitted curve when `s`'s process is V18 or later and the splits are the defaults. + pub fn new(s: &DevelopSettings) -> ParametricGraph { + let model = ParametricCurve::new(&s.curve); + let fitted = (s.process.process() >= Process::V18 && default_splits(&s.curve)).then(|| fitted_parametric(model.amounts.map(|a| a as f32))); + ParametricGraph { model, fitted } + } + + /// Whether the graph is the fitted curve (else the analytic one). + pub fn is_fitted(&self) -> bool { + self.fitted.is_some() + } + + /// The curve at `x` (0 = black, 1 = white). + pub fn at(&self, x: f64) -> f64 { + match &self.fitted { + Some(lut) => lut.eval(if x.is_nan() { 0.0 } else { x as f32 }) as f64, + None => self.model.at(x), + } + } + + /// The region that owns graph position `x` (the splits tile the graph: [`ParametricCurve::region_at`]). + pub fn region_at(&self, x: f64) -> usize { + self.model.region_at(x) + } + + /// Region `region`'s slider amount. + pub fn amount(&self, region: usize) -> f64 { + self.model.amounts.get(region).copied().unwrap_or(0.0) + } + + /// The amount for region `region` after a drag that grabbed the curve at `x`, with the region at `from`, and moved + /// it `delta` in output level (a fraction of the graph's height; up is positive). The other regions stay as they + /// are, and the level is the drawn curve's (kept monotone). A level the region cannot reach saturates at ±100; no + /// motion, or a region that cannot visibly move the line in that direction, keeps `from`. + pub fn dragged_amount(&self, region: usize, x: f64, from: f64, delta: f64) -> f64 { + if delta == 0.0 || !delta.is_finite() { + return from; + } + if self.fitted.is_none() { + let per_unit = self.model.level_per_unit(region, x); + return if per_unit.abs() > f64::EPSILON { (from + delta / per_unit).clamp(-100.0, 100.0).round() } else { from }; + } + // The fitted regions are not linear in the amount: search the amount that puts the drawn curve at the target, + // on the side of `from` the drag goes to (so a flat stretch never makes the slider jump back). The drawn curve + // is kept monotone, a running maximum, so its level at `x` reads the curve's entries up to `x`; the other + // regions' share of them is the same for every amount tried. + let Some(fit) = m::REGIONS.get(region) else { return from }; + let pos = x.clamp(0.0, 1.0) as f32 * (N - 1) as f32; + let j = (pos as usize).min(N - 2); + let f = pos - j as f32; + let mut others = self.model.amounts.map(|v| v as f32); + if let Some(v) = others.get_mut(region) { + *v = 0.0; + } + let entries: Vec<(f32, f32)> = (0..=j + 1) + .map(|i| { + let g = i as f32 / (N - 1) as f32; + (g, regions_delta(others, g)) + }) + .collect(); + let level = |a: f64| { + let (mut m, mut at) = (f32::NEG_INFINITY, [0.0f32; 2]); + for (i, (g, rest)) in entries.iter().enumerate() { + m = m.max((g + rest + response(fit, a as f32, *g)).clamp(0.0, 1.0)); + if let Some(v) = i.checked_sub(j).and_then(|k| at.get_mut(k)) { + *v = m; + } + } + (at[0] + (at[1] - at[0]) * f) as f64 + }; + let (start, end) = (level(from), if delta > 0.0 { 100.0 } else { -100.0 }); + let (target, reach) = (start + delta, level(end)); + // where the drawn line is held by a peak to its left, the region may hardly move it: then the slider stays + if (reach - start).abs() < REACH_MIN { + return from; + } + if (delta > 0.0 && reach < target) || (delta < 0.0 && reach > target) { + return end; + } + let (mut lo, mut hi) = if delta > 0.0 { (from, 100.0) } else { (-100.0, from) }; + // 20 halvings of the 200-wide range are well inside the rounding to whole amounts + for _ in 0..20 { + let mid = (lo + hi) / 2.0; + if level(mid) < target { + lo = mid; + } else { + hi = mid; + } + } + let a = if delta > 0.0 { hi } else { lo }; + a.clamp(-100.0, 100.0).round() + } +} + +/// The fitted Whites curve at `amount`, or `None` at 0. +fn whites(amount: f64) -> Option { + if amount == 0.0 { + return None; + } + let mut lut = Lut1::from_fn(N, |x| (x + response(&m::WHITES, amount as f32, x)).clamp(0.0, 1.0)); + monotone(&mut lut); + Some(lut) +} + +/// Keeps a table non-decreasing (tone order never reverses). +fn monotone(lut: &mut Lut1) { + let mut m = f32::NEG_INFINITY; + for v in &mut lut.v { + m = m.max(*v); + *v = m; + } +} + +impl CurveStage { + /// The stage for `s`: `None` before V18, or when Whites, the parametric curve and every point curve are neutral. + pub fn new(s: &DevelopSettings) -> Option { + if s.process.process() < Process::V18 { + return None; + } + let c = &s.curve; + let parametric_on = c.highlights != 0.0 || c.lights != 0.0 || c.darks != 0.0 || c.shadows != 0.0; + let master = !ToneCurve::point_curve_is_identity(&c.master); + let chans = [&c.red, &c.green, &c.blue].map(|p| !ToneCurve::point_curve_is_identity(p)); + let w = whites(s.light.whites); + if w.is_none() && !parametric_on && !master && !chans.iter().any(|b| *b) { + return None; + } + let to_pts = |p: &[Point]| p.iter().map(|q| (q.x, q.y)).collect::>(); + let mut base = if parametric_on { parametric(c) } else { Lut1::identity(N) }; + if let Some(w) = &w { + base = base.compose_len(w, N); + } + if master { + base = MonotoneCurve::new(&to_pts(&c.master)).to_lut(N).compose_len(&base, N); + } + let per = [&c.red, &c.green, &c.blue]; + let chan = std::array::from_fn(|i| match per.get(i) { + Some(p) if chans.get(i).copied().unwrap_or(false) => MonotoneCurve::new(&to_pts(p)).to_lut(N), + _ => Lut1::identity(N), + }); + let curves_on = parametric_on || master || chans.iter().any(|b| *b); + let refine = if curves_on { (c.refine_saturation / 100.0).clamp(0.0, 1.0) as f32 } else { 1.0 }; + let whites = w.filter(|_| refine < 1.0); + Some(CurveStage { chan, base, refine, whites }) + } + + /// Linear Rec.2020 in and out (display referred, after the tone map). + /// + /// The curves are looked up on the colour clamped to [0, 1] in linear ProPhoto; whatever a channel had + /// above white is added back after them, so HDR input keeps slope 1 above white and is not clipped by an + /// active curve (`hdr_values_keep_slope_one_above_white`). + pub fn apply(&self, d: [f32; 3]) -> [f32; 3] { + let (to, from) = matrices(); + let p = mul3(to, d); + let pc = p.map(|v| v.clamp(0.0, 1.0)); + let e = pc.map(linear_to_srgb); + let (mut hi, mut lo) = (0usize, 0usize); + for k in 1..3 { + if e[k] > e[hi] { + hi = k; + } + if e[k] < e[lo] { + lo = k; + } + } + let base = hue_preserving(&self.base, e, pc, hi, lo); + let curved: [f32; 3] = std::array::from_fn(|k| self.chan[k].eval(linear_to_srgb(base[k]))); + let lin = |v: [f32; 3]| v.map(|x| srgb_to_linear(x.clamp(0.0, 1.0))); + let mut q = lin(curved); + if self.refine < 1.0 { + // the saturation back towards the input's after Whites, at the curves' luminance + let reference = match &self.whites { + Some(w) => hue_preserving(w, e, pc, hi, lo).map(linear_to_srgb), + None => e, + }; + let r = lin(crate::finish::refine_saturation(reference, curved, self.refine)); + let y = |v: [f32; 3]| PRO_Y[0] * v[0] + PRO_Y[1] * v[1] + PRO_Y[2] * v[2]; + let (yq, yr) = (y(q), y(r)); + q = if yr > 1e-6 { r.map(|v| v * yq / yr) } else { r }; + } + for (k, v) in q.iter_mut().enumerate() { + if let Some(over) = p.get(k).filter(|x| **x > 1.0) { + *v += over - 1.0; + } + } + mul3(from, q) + } +} + +/// `table` on the largest and smallest channel of the encoded colour `e` (`pc` in linear light, `hi` and `lo` its +/// largest and smallest channel); the middle one keeps its place between them in linear light. Linear, in [0, 1]. +fn hue_preserving(table: &Lut1, e: [f32; 3], pc: [f32; 3], hi: usize, lo: usize) -> [f32; 3] { + let (la, lb) = (srgb_to_linear(table.eval(e[hi])), srgb_to_linear(table.eval(e[lo]))); + let (pa, pb) = (pc[hi], pc[lo]); + std::array::from_fn(|k| { + let t = if pa > pb { (pc[k] - pb) / (pa - pb) } else { 1.0 }; + (lb + (la - lb) * t).clamp(0.0, 1.0) + }) +} + +/// Linear Rec.2020 to linear ProPhoto and back, built once. +fn matrices() -> &'static ([[f32; 3]; 3], [[f32; 3]; 3]) { + static M: std::sync::OnceLock<([[f32; 3]; 3], [[f32; 3]; 3])> = std::sync::OnceLock::new(); + M.get_or_init(crate::light_v3::prophoto_matrices) +} + +/// Multiplies a colour by a 3 × 3 matrix. +fn mul3(m: &[[f32; 3]; 3], d: [f32; 3]) -> [f32; 3] { + std::array::from_fn(|r| m[r][0] * d[0] + m[r][1] * d[1] + m[r][2] * d[2]) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Default settings on process V18. + fn v18() -> DevelopSettings { + DevelopSettings { process: Process::V18.version(), ..Default::default() } + } + + /// V18 settings with only Whites at `v`. + fn with_whites(v: f64) -> DevelopSettings { + let mut s = v18(); + s.light.whites = v; + s + } + + /// Display-linear grey whose sRGB encoding is `e`, through the stage, back to encoded. + fn grey(stage: &CurveStage, e: f32) -> f32 { + linear_to_srgb(stage.apply([srgb_to_linear(e); 3])[1]) + } + + #[test] + fn earlier_processes_and_neutral_settings_have_no_stage() { + assert!(CurveStage::new(&v18()).is_none(), "neutral settings are the identity"); + for p in Process::ALL.iter().filter(|p| **p < Process::V18) { + let s = DevelopSettings { process: p.version(), ..with_whites(-50.0) }; + assert!(CurveStage::new(&s).is_none(), "{p:?}"); + } + } + + #[test] + fn whites_reaches_into_the_midtones_as_measured() { + let stage = CurveStage::new(&with_whites(-50.0)).expect("Whites set"); + let drop = (0.6 - grey(&stage, 0.6)) * 255.0; + assert!((7.0..13.0).contains(&drop), "encoded 0.6 fell by {drop}/255"); + let dark = (0.05 - grey(&stage, 0.05)).abs() * 255.0; + assert!(dark < 2.0, "the shadows hardly move: {dark}/255"); + let up = CurveStage::new(&with_whites(50.0)).expect("Whites set"); + assert!(grey(&up, 0.6) > 0.6); + } + + #[test] + fn regions_add_and_act_in_their_own_range() { + let curve = |f: fn(&mut ToneCurve)| { + let mut s = v18(); + f(&mut s.curve); + CurveStage::new(&s).expect("a region set") + }; + let shadows = curve(|c| c.shadows = 50.0); + let highlights = curve(|c| c.highlights = 50.0); + let both = curve(|c| { + c.shadows = 50.0; + c.highlights = 50.0; + }); + assert!(grey(&shadows, 0.15) - 0.15 > 3.0 * (grey(&shadows, 0.85) - 0.85).abs(), "Shadows lifts the dark end"); + assert!(grey(&highlights, 0.85) - 0.85 > 3.0 * (grey(&highlights, 0.15) - 0.15).abs(), "Highlights lifts the bright end"); + for e in [0.15f32, 0.4, 0.6, 0.85] { + let sum = e + (grey(&shadows, e) - e) + (grey(&highlights, e) - e); + assert!((grey(&both, e) - sum).abs() < 1.5 / 255.0, "{e}"); + } + } + + #[test] + fn other_splits_fall_back_to_the_analytic_curve() { + let mut s = v18(); + s.curve.highlights = 50.0; + s.curve.split_mid = 40.0; + let stage = CurveStage::new(&s).expect("a region set"); + assert_eq!(stage.base.v, crate::curve::ParametricCurve::new(&s.curve).to_lut().v); + } + + /// Every fitted response grows with its slider in the slider's direction, never acts against it, and is 0 at black, + /// at white and at amount 0; amounts beyond ±100 act as ±100. + #[test] + fn fitted_responses_grow_with_the_slider_and_stay_inside_black_and_white() { + let fits = std::iter::once(&m::WHITES).chain(m::REGIONS.iter()); + for (i, fit) in fits.enumerate() { + for sign in [-1.0f32, 1.0] { + for k in 0..=64 { + let x = k as f32 / 64.0; + let mut prev = 0.0f32; + for a in (0..=20).map(|j| sign * 5.0 * j as f32) { + let r = sign * response(fit, a, x); + // steadily: never back by more than a twentieth of an 8-bit level + assert!(r >= -1e-6 && r + 0.05 / 255.0 >= prev, "fit {i} at {x}, amount {a}: {r} after {prev}"); + prev = r; + } + assert_eq!(response(fit, sign * 150.0, x), response(fit, sign * 100.0, x)); + } + assert_eq!(response(fit, sign * 60.0, 0.0), 0.0); + assert_eq!(response(fit, sign * 60.0, 1.0), 0.0); + } + assert_eq!(response(fit, 0.0, 0.5), 0.0); + assert_eq!(response(fit, f32::NAN, 0.5), 0.0); + } + } + + /// The four regions peak in tone order: Shadows lowest, then Darks, Lights, Highlights, each one's strongest lift + /// above the one before's. + #[test] + fn the_regions_peak_in_tone_order() { + let peak = |fit: &[m::Response; 2]| { + (0..=256) + .map(|k| k as f32 / 256.0) + .fold((0.0f32, 0.0f32), |b, x| if response(fit, 50.0, x) > b.1 { (x, response(fit, 50.0, x)) } else { b }) + .0 + }; + let peaks = m::REGIONS.each_ref().map(peak); + assert!(peaks.windows(2).all(|w| w[0] < w[1]), "{peaks:?}"); + } + + /// What the graph draws is the stage's base curve, and the analytic one where the stage uses that. + #[test] + fn the_graph_is_the_curve_the_stage_renders() { + let mut s = v18(); + (s.curve.shadows, s.curve.darks, s.curve.lights, s.curve.highlights) = (40.0, -30.0, 25.0, -60.0); + let graph = ParametricGraph::new(&s); + assert!(graph.is_fitted()); + let stage = CurveStage::new(&s).expect("regions set"); + for i in 0..=64 { + let x = i as f32 / 64.0; + assert!((graph.at(x as f64) as f32 - stage.base.eval(x)).abs() < 1e-6, "{x}"); + } + // moved splits and earlier processes draw the analytic curve, as they render it + s.curve.split_mid = 40.0; + let moved = ParametricGraph::new(&s); + assert!(!moved.is_fitted()); + assert_eq!(moved.at(0.6), ParametricCurve::new(&s.curve).at(0.6)); + s.curve.split_mid = 50.0; + let v17 = DevelopSettings { process: Process::V17.version(), ..s }; + assert!(!ParametricGraph::new(&v17).is_fitted()); + } + + /// Refine Saturation restores the colour after Whites, not before it: at 0, a curve on top of Whites leaves the + /// saturation Whites gives a colour, as Whites alone does (review on #4099). + #[test] + fn refine_saturation_keeps_what_whites_did() { + let sat = |d: [f32; 3]| { + let p = mul3(&matrices().0, d); + let (hi, lo) = (p[0].max(p[1]).max(p[2]), p[0].min(p[1]).min(p[2])); + (hi - lo) / hi + }; + let colour = mul3(&matrices().1, [0.9, 0.6, 0.3]); + let mut s = v18(); + s.light.whites = 80.0; + let alone = CurveStage::new(&s).expect("Whites").apply(colour); + s.curve.master = vec![Point { x: 0.0, y: 0.0 }, Point { x: 0.5, y: 0.56 }, Point { x: 1.0, y: 1.0 }]; + s.curve.refine_saturation = 0.0; + let refined = CurveStage::new(&s).expect("Whites and a curve").apply(colour); + let whites_did = (sat(alone) - sat(colour)).abs(); + assert!(whites_did > 0.05, "Whites changes the saturation: {} vs {}", sat(alone), sat(colour)); + // close to Whites alone, not pulled back towards the colour before Whites + assert!((sat(refined) - sat(alone)).abs() < 0.3 * whites_did, "refined {} vs Whites alone {}", sat(refined), sat(alone)); + } + + /// In every region, the amount a drag picks moves the drawn curve by the drag's motion. + #[test] + fn a_graph_drag_puts_the_fitted_curve_where_the_hand_is() { + let mut s = v18(); + s.curve.darks = 30.0; + let graph = ParametricGraph::new(&s); + for (region, x) in [(0usize, 0.15f64), (1, 0.375), (2, 0.625), (3, 0.85)] { + for delta in [-0.04, 0.03] { + let from = graph.amount(region); + let a = graph.dragged_amount(region, x, from, delta); + let mut after = s.clone(); + let c = &mut after.curve; + *[&mut c.shadows, &mut c.darks, &mut c.lights, &mut c.highlights][region] = a; + let got = ParametricGraph::new(&after).at(x) - graph.at(x); + assert!((got - delta).abs() < 0.004, "region {region} at {x}: moved {got}, wanted {delta} (amount {from} → {a})"); + } + assert_eq!(graph.dragged_amount(region, x, graph.amount(region), 0.0), graph.amount(region), "no motion, no change"); + assert_eq!(graph.dragged_amount(region, x, 0.0, 1.0), 100.0, "out of reach saturates high"); + assert_eq!(graph.dragged_amount(region, x, 0.0, -1.0), -100.0, "and low"); + } + } + + /// Where opposite regions fold the fitted curve back, the drag follows the curve as drawn (held flat by the peak + /// to its left): Lights +80 and Highlights −100 fold it above 0.75. A region that reaches the peak moves the held + /// line with the hand; one that cannot reach it keeps its value instead of running to the end. + #[test] + fn a_graph_drag_follows_the_drawn_curve_where_it_is_flattened() { + let mut s = v18(); + (s.curve.shadows, s.curve.darks, s.curve.lights, s.curve.highlights) = (-50.0, 100.0, 80.0, -100.0); + let graph = ParametricGraph::new(&s); + let x = 0.86; + let raw = regions_at(graph.model.amounts.map(|v| v as f32), x as f32) as f64; + assert!(graph.at(x) - raw > 0.05, "the stretch is flattened, or this proves nothing: {} vs {raw}", graph.at(x)); + let drawn = |region: usize, a: f64| { + let mut after = s.clone(); + let c = &mut after.curve; + *[&mut c.shadows, &mut c.darks, &mut c.lights, &mut c.highlights][region] = a; + ParametricGraph::new(&after).at(x) + }; + for (region, delta) in [(2usize, -0.03), (3, 0.03)] { + let from = graph.amount(region); + let a = graph.dragged_amount(region, x, from, delta); + let moved = drawn(region, a) - graph.at(x); + assert!((moved - delta).abs() < 0.004, "region {region}: {from} → {a} moved the line {moved}"); + } + // Shadows does not reach the peak that holds the line, so its slider stays + assert!((drawn(0, 100.0) - graph.at(x)).abs() < REACH_MIN, "Shadows cannot move the held line"); + assert_eq!(graph.dragged_amount(0, x, -50.0, 0.03), -50.0); + } + + #[test] + fn tone_order_never_reverses_and_every_table_fits_the_gpu() { + for w in [-100.0, -50.0, 37.0, 100.0] { + let mut s = with_whites(w); + s.curve.shadows = -100.0; + s.curve.lights = 100.0; + let stage = CurveStage::new(&s).expect("set"); + assert!(stage.base.v.windows(2).all(|p| p[0] <= p[1]), "{w}"); + assert!(stage.chan.iter().chain([&stage.base]).all(|l| l.v.len() == N), "{w}"); + } + } + + #[test] + fn the_middle_channel_keeps_its_place_in_linear_prophoto() { + let stage = CurveStage::new(&with_whites(-100.0)).expect("Whites set"); + let (to, from) = matrices(); + let input = [0.55f32, 0.27, 0.08]; + let out = mul3(to, stage.apply(mul3(from, input))); + let at = |p: [f32; 3]| (p[1] - p[2]) / (p[0] - p[2]); + assert!((at(out) - at(input)).abs() < 1e-3, "{out:?}"); + } + + #[test] + fn colour_curves_act_per_channel_after_the_master() { + let mut s = v18(); + s.curve.red = vec![Point { x: 0.0, y: 0.0 }, Point { x: 0.5, y: 0.7 }, Point { x: 1.0, y: 1.0 }]; + let stage = CurveStage::new(&s).expect("a red curve"); + let (to, from) = matrices(); + let out = mul3(to, stage.apply(mul3(from, [srgb_to_linear(0.5); 3]))); + assert!((linear_to_srgb(out[0]) - 0.7).abs() < 2e-3, "{out:?}"); + assert!((linear_to_srgb(out[1]) - 0.5).abs() < 2e-3, "{out:?}"); + } + + #[test] + fn hdr_values_keep_slope_one_above_white() { + let stage = CurveStage::new(&with_whites(-50.0)).expect("Whites set"); + let (a, b) = (stage.apply([2.0; 3]), stage.apply([3.0; 3])); + assert!((b[0] - a[0] - 1.0).abs() < 1e-3, "{a:?} {b:?}"); + } + + #[test] + fn refine_saturation_at_zero_undoes_what_the_curves_added() { + let mut s = v18(); + s.curve.master = vec![Point { x: 0.0, y: 0.0 }, Point { x: 0.25, y: 0.15 }, Point { x: 0.75, y: 0.85 }, Point { x: 1.0, y: 1.0 }]; + let sat = |stage: &CurveStage| { + let (to, from) = matrices(); + let p = mul3(to, stage.apply(mul3(from, [0.5, 0.25, 0.12]))).map(linear_to_srgb); + (p[0] - p[2]) / (0.2126 * p[0] + 0.7152 * p[1] + 0.0722 * p[2]) + }; + let full = sat(&CurveStage::new(&s).expect("a curve")); + s.curve.refine_saturation = 0.0; + let none = sat(&CurveStage::new(&s).expect("a curve")); + assert!(none < full, "{none} {full}"); + } +} diff --git a/crates/pipeline/src/curve_stage_model.rs b/crates/pipeline/src/curve_stage_model.rs new file mode 100644 index 00000000000..aae839e7df8 --- /dev/null +++ b/crates/pipeline/src/curve_stage_model.rs @@ -0,0 +1,19 @@ +// Written by `tools/lr_tone_charts.py fit`: LightCraft's model of Whites and the parametric regions, fitted to the +// tool's grey-step charts (provenance in docs/curve-stage.md). Constants of the model only. + +/// One bump of a response: `[a1, a2, a3, p0, p1, q0, q1]`, gain `a1 t + a2 t² + a3 t³` (t = |amount| / 100), shape +/// exponents `e^(p0 + p1 t)` and `e^(q0 + q1 t)` ([`crate::curve_stage`]). +pub type Bump = [f64; 7]; +/// A slider direction's response: two bumps, added. +pub type Response = [Bump; 2]; + +/// Whites: negative, positive. +pub const WHITES: [Response; 2] = [[[-8.677986e-02, 2.059910e-02, -1.475161e-03, 1.084063e+00, -7.146165e-02, 7.463740e-01, -1.101123e+00], [-6.097932e-02, 2.162057e-02, -1.096353e-02, 1.843174e+00, 7.765309e-01, -1.820367e-01, 2.624658e-01]], [[4.491106e-02, 2.338704e-01, -4.586305e-02, 9.656835e-01, -4.030916e-01, -1.003725e+00, 5.542276e-01], [1.938421e-02, -8.766121e-02, 1.285831e-01, 4.062532e+00, -2.298370e+00, 3.928699e+00, -2.151902e+00]]]; + +/// Shadows, Darks, Lights, Highlights at the default splits (25, 50, 75): negative, positive. +pub const REGIONS: [[Response; 2]; 4] = [ + [[[-2.304904e-01, 5.397332e-01, -6.521258e-01, 5.201966e-01, -2.332761e+00, 2.029401e+00, 3.919508e-01], [2.322669e-02, -2.558633e-01, 1.479527e-01, 1.186677e+00, 5.075634e-01, 2.511894e+00, 3.430482e-01]], [[6.250307e-02, -3.253250e-03, 1.768197e-03, -5.212752e-01, -7.111264e-02, 2.313180e+00, -1.136211e-01], [6.286758e-02, 2.093856e-02, 8.466331e-03, 1.302920e+00, 1.043781e-01, 2.604516e+00, 8.384981e-02]]], + [[[2.129550e-01, -1.408218e+00, 2.309347e+00, 4.947582e-01, -1.714892e+00, 1.699307e+00, -6.420795e-01], [-5.249287e-01, 1.634143e+00, -2.399744e+00, 7.555377e-02, -1.304895e+00, 6.002093e-01, 2.401095e-01]], [[1.031476e-01, 3.281627e-02, 1.671911e-02, 5.258136e-01, 3.590506e-01, 9.760341e-01, 2.054602e-01], [6.812073e-02, 1.988377e-03, 5.246361e-03, -1.268885e+00, 1.303334e-01, 3.041567e-01, -9.264136e-02]]], + [[[-1.891098e-01, -2.287609e-02, 4.896024e-03, 1.011762e+00, -7.761107e-02, 4.262329e-02, -9.366133e-02], [-1.171421e-02, -1.146297e-02, -1.531020e-02, 1.645838e+00, 5.732118e-02, 1.456855e+00, 1.833067e-01]], [[-1.125586e-01, 1.431238e+00, -2.702337e+00, 1.792564e+00, -2.246400e-01, 4.144821e-01, -6.849247e-01], [5.280858e-01, -1.775048e+00, 2.776570e+00, 9.675963e-01, 3.076062e-01, 5.110037e-01, -9.632875e-01]]], + [[[-1.081283e-01, -3.328262e-02, -1.114034e-03, 1.725021e+00, -4.534782e-02, 8.818974e-02, -8.042736e-03], [2.358962e-02, 9.943229e-03, 1.375851e-03, 2.617848e+00, -4.358847e-02, 2.360366e+00, -4.425145e-02]], [[-6.006532e-02, 4.574089e-01, -2.733591e-01, 2.232173e+00, 5.657972e-01, 7.143387e-01, 9.022714e-01], [2.802296e-01, -7.070198e-01, 5.853124e-01, 2.094691e+00, 5.061273e-01, 7.808968e-01, -1.635143e+00]]], +]; diff --git a/crates/pipeline/src/finish.rs b/crates/pipeline/src/finish.rs index 29486f269a7..dca1fdf0d2c 100644 --- a/crates/pipeline/src/finish.rs +++ b/crates/pipeline/src/finish.rs @@ -148,10 +148,12 @@ impl GrainModel { seed: g.seed, }) }), - Process::V7 | Process::V8 | Process::V10 | Process::V13 | Process::V14 | Process::V15 | Process::V16 | Process::V17 if draft => { + Process::V7 | Process::V8 | Process::V10 | Process::V13 | Process::V14 | Process::V15 | Process::V16 | Process::V17 | Process::V18 + if draft => + { crate::crystal::CrystalGrain::draft(g, px_per_long).map(GrainModel::Crystal) } - Process::V7 | Process::V8 | Process::V10 | Process::V13 | Process::V14 | Process::V15 | Process::V16 | Process::V17 => { + Process::V7 | Process::V8 | Process::V10 | Process::V13 | Process::V14 | Process::V15 | Process::V16 | Process::V17 | Process::V18 => { crate::crystal::CrystalGrain::new(g, px_per_long).map(GrainModel::Crystal) } } @@ -271,6 +273,11 @@ pub struct FinishParams { pub shadow_tint: f32, /// Tone curves (parametric ∘ point, per channel) on encoded values, 1024 entries each. pub curves: Option<[Lut1; 3]>, + /// Process V18's Whites and tone curves (they replace `curves`, which stays `None` from V18 on). + pub curve_stage: Option, + /// A curve-input sample ([`crate::curve_input`]) under V18 is taken where the curve stage reads: right after it, as + /// sRGB-encoded linear ProPhoto, before the colour tools and the output. + pub sample_at_curve_stage: bool, /// Refine Saturation as 0..1 (1 = the curves' own saturation). pub refine_sat: f32, pub vig: Option, @@ -362,7 +369,9 @@ impl FinishParams { light: crate::light_v3::LightOps::new(s, info), lut: crate::lut::get(&s.profile.id).map(|l| (l, (s.profile.amount / 100.0).clamp(0.0, 2.0) as f32)), ops: ColorOps::new(s), - curves: curve_luts(&s.curve), + curves: if s.process.process() < Process::V18 { curve_luts(&s.curve) } else { None }, + sample_at_curve_stage: false, + curve_stage: curve_stage_for(s, proraw.is_some()), refine_sat: (s.curve.refine_saturation / 100.0).clamp(0.0, 1.0) as f32, vig: if effects { vignette(s) } else { None }, to_out: space.from_working(), @@ -489,6 +498,25 @@ pub fn base_tone(s: &DevelopSettings, info: &SourceInfo, peak: f32) -> ToneMap { None if info.raw => ToneMap::rolloff_hdr(l.contrast, l.whites, l.blacks, peak), None => ToneMap::display_hdr(l.contrast, l.whites, l.blacks, peak), }, + // V17, with Whites moved out of the tone map: the curve stage applies Whites (`crate::curve_stage`) + Process::V18 => match info.camera_tone.as_ref().filter(|_| info.raw) { + Some(curve) => ToneMap::camera_rolloff_hdr(curve, 0.0, 0.0, 0.0, peak), + None if info.raw => ToneMap::rolloff_hdr(l.contrast, 0.0, l.blacks, peak), + None => ToneMap::display_hdr(l.contrast, 0.0, l.blacks, peak), + }, + } +} + +/// The curve stage of `s` ([`crate::curve_stage`]). Apple ProRAW's chain applies Whites itself (`crate::proraw`), so +/// on ProRAW (`proraw`) the stage keeps only the curves. The render and the curve editor's input sample +/// ([`crate::curve_input`]) both build it here, so Whites applies once in each. +pub(crate) fn curve_stage_for(s: &DevelopSettings, proraw: bool) -> Option { + if proraw && s.light.whites != 0.0 { + let mut no_whites = s.clone(); + no_whites.light.whites = 0.0; + crate::curve_stage::CurveStage::new(&no_whites) + } else { + crate::curve_stage::CurveStage::new(s) } } @@ -589,6 +617,7 @@ pub(crate) fn finish_with( let preview_light = if exact { None } else { light.as_ref().and_then(|lo| crate::light_v3::PreviewOps::new(lo, &|v| encode_srgb(srgb, v))) }; let peak = fp.peak; let hdr = peak > 1.0; + let to_pro = crate::light_v3::prophoto_matrices().0; let mut out = vec![T::default(); w * h]; // the vignette splits into a column term and a row term, so each is computed once let vig_fall = vig.as_ref().map(|v| VigFalloff::new(v, aspect)); @@ -632,6 +661,15 @@ pub(crate) fn finish_with( // --- process V4: calibrated Contrast, Blacks (ProPhoto with the sRGB transfer) d = apply_light(d, light.as_ref(), preview_light.as_ref(), exact, srgb); + // --- process V18: Whites and the tone curves, hue-preserving + d = fp.curve_stage.as_ref().map_or(d, |stage| stage.apply(d)); + if stop_after_curves && fp.sample_at_curve_stage { + let pro = mul3(&to_pro, d); + // (above SDR white stays above 1, beyond the curve's axes, as on the output path) + *px = store(vx_u + x, vy_u + y, pro.map(|v| linear_to_srgb(v.max(0.0)))); + continue; + } + // --- colour d = fp.ops.apply(d, l_sat, l_hue); if let Some((dir, amt)) = local.tint { diff --git a/crates/pipeline/src/lib.rs b/crates/pipeline/src/lib.rs index 82c8b1dbcce..3146a62790a 100644 --- a/crates/pipeline/src/lib.rs +++ b/crates/pipeline/src/lib.rs @@ -12,6 +12,7 @@ //! 3. tone map — contrast / whites / blacks filmic curve on luminance, highlight desaturation //! 4. colour — vibrance, saturation, colour mixer, colour grading, B&W (OkLCh) //! 5. display — gamut map to the output space (sRGB unless [`RenderRequest::space`] says otherwise), encode, tone curves (parametric + point), vignette, grain +//! (from process V18 the tone curves and Whites run between 3 and 4 instead: [`curve_stage`]) //! //! Spatial parameters are specified relative to the image's long edge, so a 400 px preview and a //! 60 MP export look alike. @@ -31,6 +32,9 @@ pub mod crystal; pub mod cull; pub mod curve; pub mod curve_input; +pub mod curve_stage; +#[rustfmt::skip] +mod curve_stage_model; pub mod dust; pub mod finish; pub mod geometry; @@ -58,6 +62,7 @@ pub mod upright; pub mod visualize; pub use curve::{PARAM_AMOUNTS, PARAM_LUT, ParametricCurve}; +pub use curve_stage::ParametricGraph; pub use output::{DeepImage, DeepSamples, DisplaySpace, OutputDepth, OutputSpace, OutputTrc, Proof, ProofLut, proof_profile, register_proof_profile}; pub use visualize::{MaskView, Overlay}; diff --git a/crates/pipeline/src/proraw.rs b/crates/pipeline/src/proraw.rs index ae7c2e848e5..07e34015565 100644 --- a/crates/pipeline/src/proraw.rs +++ b/crates/pipeline/src/proraw.rs @@ -919,7 +919,9 @@ mod tests { let tone = std::sync::Arc::new(curve(PRORAW_TONE_KNOTS, |x| x.powf(0.6))); let info = SourceInfo { raw: true, proraw: Some(tone), ..Default::default() }; let mut s = DevelopSettings::default(); - assert_eq!(s.process.process(), Process::V17); + assert!(s.process.process() >= Process::V17); + assert!(active(&s, &info).is_some(), "the latest process activates ProRAW"); + s.process = Process::V17.version(); assert!(active(&s, &info).is_some(), "V17 activates ProRAW"); s.process = Process::V16.version(); assert!(active(&s, &info).is_none(), "V16 keeps the camera-curve path"); diff --git a/crates/pipeline/src/tests.rs b/crates/pipeline/src/tests.rs index ed85e83c193..6af4ddbace1 100644 --- a/crates/pipeline/src/tests.rs +++ b/crates/pipeline/src/tests.rs @@ -1,4 +1,4 @@ -use lightcraft_develop::{DevelopSettings, controls}; +use lightcraft_develop::{DevelopSettings, Process, controls}; use lightcraft_raster::Rgb32f; use crate::{RenderRequest, SourceInfo, render}; @@ -474,13 +474,23 @@ fn refine_saturation_tames_a_contrast_curve() { lightcraft_geom::Point::new(0.7, 0.85), lightcraft_geom::Point::new(1.0, 1.0), ]; - let full = render(&src, &info, &s, &req).image.data[0]; + let curved = s.clone(); s.curve.refine_saturation = 0.0; - let refined = render(&src, &info, &s, &req).image.data[0]; - assert!(sat(full) > sat(refined), "{flat:?} {full:?} {refined:?}"); - // the curve's tone change stays - let y = |p: [u8; 4]| 0.2126 * p[0] as f32 + 0.7152 * p[1] as f32 + 0.0722 * p[2] as f32; - assert!((y(full) - y(refined)).abs() < 2.0); + let y = |p: [u8; 4], lin: bool| { + let c = |v: u8| if lin { lightcraft_color::transfer::srgb_to_linear(v as f32 / 255.0) } else { v as f32 }; + 0.2126 * c(p[0]) + 0.7152 * c(p[1]) + 0.0722 * c(p[2]) + }; + for process in [Process::V7, Process::V18] { + let on = |s: &DevelopSettings| render(&src, &info, &DevelopSettings { process: process.version(), ..s.clone() }, &req).image.data[0]; + let (full, refined) = (on(&curved), on(&s)); + assert!(sat(full) > sat(refined), "{process:?}: {flat:?} {full:?} {refined:?}"); + // the curve's tone change stays: up to V17 the encoded luma, from V18 the luminance + if process < Process::V18 { + assert!((y(full, false) - y(refined, false)).abs() < 2.0, "{process:?}: {full:?} {refined:?}"); + } else { + assert!((y(full, true) / y(refined, true) - 1.0).abs() < 0.03, "{process:?}: {full:?} {refined:?}"); + } + } } #[test] diff --git a/crates/pipeline/src/tests_grain.rs b/crates/pipeline/src/tests_grain.rs index 971cf155776..eace63da12d 100644 --- a/crates/pipeline/src/tests_grain.rs +++ b/crates/pipeline/src/tests_grain.rs @@ -35,7 +35,7 @@ fn processes_before_v7_keep_the_value_noise() { Process::V1 | Process::V2 | Process::V3 | Process::V4 | Process::V5 | Process::V6 => { assert!(matches!(model, Some(GrainModel::Value(_))), "{p:?}") } - Process::V7 | Process::V8 | Process::V10 | Process::V13 | Process::V14 | Process::V15 | Process::V16 | Process::V17 => { + Process::V7 | Process::V8 | Process::V10 | Process::V13 | Process::V14 | Process::V15 | Process::V16 | Process::V17 | Process::V18 => { assert!(matches!(model, Some(GrainModel::Crystal(_))), "{p:?}") } } diff --git a/crates/pipeline/src/tests_proraw.rs b/crates/pipeline/src/tests_proraw.rs index 31a57ad7c45..410d4fd543e 100644 --- a/crates/pipeline/src/tests_proraw.rs +++ b/crates/pipeline/src/tests_proraw.rs @@ -75,6 +75,18 @@ fn v17_renders_everything_else_as_v16() { } } +/// V18's curve stage leaves Whites to the ProRAW chain, which applies it itself: Whites alone renders a ProRAW +/// photo as on V17, where a second Whites would brighten it again. +#[test] +fn v18_leaves_proraw_whites_to_the_chain() { + let info = proraw_info(); + let mut s = DevelopSettings::for_raw(5200.0, 4.0); + controls::set(&mut s, "light.whites", 40.0); + let at = |p: Process| deep(&info, &DevelopSettings { process: p.version(), ..s.clone() }); + assert!(at(Process::V18) == at(Process::V17), "Whites applies once"); + assert!(at(Process::V17) != deep(&info, &DevelopSettings { process: Process::V17.version(), ..DevelopSettings::for_raw(5200.0, 4.0) })); +} + #[test] fn v17_keeps_checked_white_balance_and_v9_fallback() { let info = SourceInfo { as_shot_temp: 5500.0, as_shot_tint: 0.0, proraw: None, ..proraw_info() }; diff --git a/crates/ui-egui/src/panels/edit.rs b/crates/ui-egui/src/panels/edit.rs index 370ede41c4d..075472b0690 100644 --- a/crates/ui-egui/src/panels/edit.rs +++ b/crates/ui-egui/src/panels/edit.rs @@ -8,7 +8,7 @@ use egui::{Align2, Color32, Pos2, Rect, RichText, Sense, Stroke, pos2, vec2}; use lightcraft_catalog::PhotoId; use lightcraft_develop::{ControlSpec, DevelopSettings, Section, Track, WbMode, controls}; use lightcraft_geom::Point; -use lightcraft_pipeline::{PARAM_AMOUNTS, ParametricCurve}; +use lightcraft_pipeline::{PARAM_AMOUNTS, ParametricGraph}; use lightcraft_raster::Histogram; use serde_json::{Value, json}; diff --git a/crates/ui-egui/src/panels/edit/curve.rs b/crates/ui-egui/src/panels/edit/curve.rs index 9f27031701e..ee02baecbe8 100644 --- a/crates/ui-egui/src/panels/edit/curve.rs +++ b/crates/ui-egui/src/panels/edit/curve.rs @@ -1,6 +1,6 @@ use super::sliders::control; use super::{ - Align2, Color32, DevelopSettings, Icon, LightcraftApp, Mesh, PARAM_AMOUNTS, ParametricCurve, PhotoId, Point, Pos2, Rect, RichText, Sense, Stroke, + Align2, Color32, DevelopSettings, Icon, LightcraftApp, Mesh, PARAM_AMOUNTS, ParametricGraph, PhotoId, Point, Pos2, Rect, RichText, Sense, Stroke, Tokens, Vertex, controls, hex, json, paint, pos2, text_button, vec2, }; use super::{Histogram, Slot}; @@ -80,12 +80,11 @@ const PARAM_GRAB: f32 = 14.0; /// The whole gesture runs inside one `develop` interaction, so it is one undo step (Ctrl+Z takes the /// gesture back, not the last frame of it), and every write goes through `develop.set`, so the /// slider, the curve and what is drawn are the same state rather than three things kept in step. -fn param_drag(app: &mut LightcraftApp, ui: &mut egui::Ui, r: Rect, resp: &egui::Response, d: &DevelopSettings) { +fn param_drag(app: &mut LightcraftApp, ui: &mut egui::Ui, r: Rect, resp: &egui::Response, d: &DevelopSettings, model: &ParametricGraph) { if r.width() <= 1.0 || r.height() <= 1.0 { return; } let t = Tokens::get(ui.ctx()); - let model = ParametricCurve::new(&d.curve); let to_screen = |x: f64, y: f64| pos2(r.left() + x as f32 * r.width(), r.bottom() - y as f32 * r.height()); let from_screen_x = |q: Pos2| ((q.x - r.left()) / r.width()).clamp(0.0, 1.0) as f64; // the graph x of a point, and how far it is from the drawn curve (in screen points) @@ -110,7 +109,7 @@ fn param_drag(app: &mut LightcraftApp, ui: &mut egui::Ui, r: Rect, resp: &egui:: let x = from_screen_x(q); let _ = app.run("develop.beginInteraction", json!({"label": "Parametric Curve"})); let region = model.region_at(x); - let initial_amount = model.amounts.get(region).copied().unwrap_or(0.0); + let initial_amount = model.amount(region); let start_pos = to_screen(x, model.at(x)); dragged = Some((region, x, initial_amount, start_pos.y)); ui.data_mut(|dd| dd.insert_temp(cursor_id, start_pos)); @@ -127,9 +126,7 @@ fn param_drag(app: &mut LightcraftApp, ui: &mut egui::Ui, r: Rect, resp: &egui:: ui.data_mut(|d| d.insert_temp(cursor_id, cursor)); let delta_y = start_y - cursor.y; let delta_level = (delta_y / r.height()) as f64; - let per_unit = model.level_per_unit(region, x); - let new_amount = - if per_unit.abs() > f64::EPSILON { (initial_amount + delta_level / per_unit).clamp(-100.0, 100.0).round() } else { initial_amount }; + let new_amount = model.dragged_amount(region, x, initial_amount, delta_level); if let Some(&id) = PARAM_AMOUNTS.get(region) { set = Some((id, new_amount)); } @@ -306,15 +303,15 @@ pub(super) fn curve_editor(app: &mut LightcraftApp, ui: &mut egui::Ui, id: Photo let to_screen = |x: f64, y: f64| pos2(r.left() + x as f32 * r.width(), r.bottom() - y as f32 * r.height()); let from_screen = |q: Pos2| (((q.x - r.left()) / r.width()).clamp(0.0, 1.0) as f64, ((r.bottom() - q.y) / r.height()).clamp(0.0, 1.0) as f64); if ch == "parametric" { - // The Effective curve: the model the renderer builds from the four region sliders, sampled - // here and rebuilt every frame. The graph holds no state of its own, so a slider moved by - // hand, a Reset or an Undo redraws it from the settings in the same frame it changes. - let c = &d.curve; - let model = ParametricCurve::new(c); + // The Effective curve: the one the renderer builds from the four region sliders for this + // process (the fitted regions under V18 at the default splits), sampled here and rebuilt every + // frame. The graph holds no state of its own, so a slider moved by hand, a Reset or an Undo + // redraws it from the settings in the same frame it changes. + let model = ParametricGraph::new(d); let pts: Vec = (0..=CURVE_SAMPLES).map(|i| to_screen(i as f64 / CURVE_SAMPLES as f64, model.at(i as f64 / CURVE_SAMPLES as f64))).collect(); p.add(egui::Shape::line(pts, Stroke::new(2.0, Color32::from_gray(220)))); - param_drag(app, ui, r, &resp, d); + param_drag(app, ui, r, &resp, d, &model); curve_footer(app, ui, d); for &c in PARAM_AMOUNTS.iter().rev() { control(app, ui, d, c, true); diff --git a/crates/ui-egui/src/tests/curve.rs b/crates/ui-egui/src/tests/curve.rs index e64d2cbb561..a9819e99819 100644 --- a/crates/ui-egui/src/tests/curve.rs +++ b/crates/ui-egui/src/tests/curve.rs @@ -6,7 +6,7 @@ use serde_json::json; use crate::headless::Headless; use crate::{LightcraftApp, Services}; -use lightcraft_pipeline::ParametricCurve; +use lightcraft_pipeline::{ParametricCurve, ParametricGraph}; const T: Duration = Duration::from_secs(20); @@ -40,6 +40,11 @@ fn exec(h: &mut Headless, command: &str, params: serde_json::Value) -> serde_jso r["result"].clone() } +/// The parametric graph the panel draws for the selected photo's settings (its process decides fitted or analytic). +fn graph(h: &Headless) -> ParametricGraph { + ParametricGraph::new(&develop(h)) +} + fn develop(h: &Headless) -> lightcraft_develop::DevelopSettings { let id = h.app.session.active().expect("active photo"); (*h.app.session.develop_of(id).unwrap_or_default()).clone() @@ -276,9 +281,10 @@ fn the_parametric_graph_paints_the_model_the_renderer_uses() { h.step(); let settings = develop(&h).curve; assert_eq!(settings, c, "the sliders hold the folded shape"); - let graph = curve_graph_rect(&mut h); - let painted = painted_param_curve(&h, graph); - let model = ParametricCurve::new(&c); + let model = graph(&h); + let rect = curve_graph_rect(&mut h); + let painted = painted_param_curve(&h, rect); + assert!(model.is_fitted(), "the demo photo is on the latest process, which renders the fitted regions"); let mut checked = 0; for i in 0..=24 { let x = i as f64 / 24.0; @@ -401,8 +407,8 @@ fn one_graph_drag_that_moves_several_regions_is_one_undo_step() { } /// The screen point where a drag should grab the curve: graph fraction `fx`, on the line itself. -fn on_curve(r: [f32; 4], c: &lightcraft_develop::ToneCurve, fx: f32) -> [f32; 2] { - let y = ParametricCurve::new(c).at(fx as f64); +fn on_curve(r: [f32; 4], g: &ParametricGraph, fx: f32) -> [f32; 2] { + let y = g.at(fx as f64); [r[0] + fx * r[2], r[1] + (1.0 - y as f32) * r[3]] } @@ -415,9 +421,10 @@ fn dragging_the_curve_moves_the_region_slider() { h.step(); let r = curve_graph_rect(&mut h); let c = develop(&h).curve; + let g = graph(&h); let undo_before = h.app.session.undo.len(); // grab the line inside the Lights window (x = 0.625) and pull it down - let [x, y] = on_curve(r, &c, 0.625); + let [x, y] = on_curve(r, &g, 0.625); let d = h.request("ui.drag", json!({"x": x, "y": y, "toX": x, "toY": y + 0.08 * r[3], "steps": 8}), T); assert_eq!(d["ok"], true, "{d}"); h.step(); @@ -430,8 +437,13 @@ fn dragging_the_curve_moves_the_region_slider() { // the graph really is redrawn below where the line was let graph = curve_graph_rect(&mut h); let painted = painted_param_curve(&h, graph)(0.625); - let before_level = ParametricCurve::new(&c).at(0.625); + let before_level = g.at(0.625); assert!(painted < before_level - 0.02, "the painted line followed the drag down: {painted} vs before {before_level}"); + // and lands where the hand is: at most 0.08 lower, and at least that less the drag threshold (6 points), which + // swallows the hand's first steps (how many depends on how the framework starts a drag) + let moved = before_level - painted; + let threshold = 6.0 / r[3] as f64; + assert!(moved < 0.08 + 0.006 && moved > 0.08 - threshold - 0.006, "the line moved {moved} for a hand motion of 0.08"); // and Undo takes the whole gesture back to where it started exec(&mut h, "edit.undo", json!({})); assert_eq!(develop(&h).curve, c, "undo restores the value the drag started from"); @@ -449,7 +461,7 @@ fn a_horizontal_drag_with_zero_vertical_motion_changes_nothing() { assert_eq!(before.darks, 60.0); assert_eq!(before.lights, 0.0); let r = curve_graph_rect(&mut h); - let [x, y] = on_curve(r, &before, 0.51); + let [x, y] = on_curve(r, &graph(&h), 0.51); // Drag purely horizontally from x=0.51: dx = 20 px, dy = 0 let d = h.request("ui.drag", json!({"x": x, "y": y, "toX": x + 20.0, "toY": y, "steps": 6}), T); assert_eq!(d["ok"], true, "{d}"); @@ -465,16 +477,16 @@ fn a_horizontal_drag_with_zero_vertical_motion_changes_nothing() { fn dragging_the_curve_up_raises_the_region_slider() { let mut h = curve_open("parametric"); let r = curve_graph_rect(&mut h); - let c = develop(&h).curve; + let g = graph(&h); // x = 0.375 is inside the Darks window - let [x, y] = on_curve(r, &c, 0.375); + let [x, y] = on_curve(r, &g, 0.375); let d = h.request("ui.drag", json!({"x": x, "y": y, "toX": x, "toY": y - 0.08 * r[3], "steps": 8}), T); assert_eq!(d["ok"], true, "{d}"); h.step(); let after = develop(&h).curve; assert!(after.darks > 0.0, "the Darks slider follows the line up: {}", after.darks); assert_eq!((after.shadows, after.lights, after.highlights), (0.0, 0.0, 0.0), "the other regions stay put: {after:?}"); - assert!(ParametricCurve::new(&after).at(0.375) > ParametricCurve::new(&c).at(0.375), "the curve is drawn bent up at the Darks region"); + assert!(graph(&h).at(0.375) > g.at(0.375), "the curve is drawn bent up at the Darks region"); } /// Which region a drag moves is decided by where on the line it is grabbed: the same drag gesture @@ -486,9 +498,9 @@ fn the_region_dragged_is_the_one_under_the_pointer() { { let mut h = curve_open("parametric"); let r = curve_graph_rect(&mut h); - let c = develop(&h).curve; - assert_eq!(ParametricCurve::new(&c).region_at(fx as f64), region, "x = {fx} belongs to {control}"); - let [x, y] = on_curve(r, &c, fx); + let g = graph(&h); + assert_eq!(g.region_at(fx as f64), region, "x = {fx} belongs to {control}"); + let [x, y] = on_curve(r, &g, fx); let d = h.request("ui.drag", json!({"x": x, "y": y, "toX": x, "toY": y - 0.06 * r[3], "steps": 6}), T); assert_eq!(d["ok"], true, "{d}"); h.step(); @@ -535,7 +547,7 @@ fn hovering_the_line_names_the_region_it_would_move() { exec(&mut h, "develop.set", json!({"control": "curve.lights", "value": 60})); h.step(); let r = curve_graph_rect(&mut h); - let [x, y] = on_curve(r, &develop(&h).curve, 0.625); + let [x, y] = on_curve(r, &graph(&h), 0.625); let q = h.request("ui.move", json!({"x": x, "y": y}), T); assert_eq!(q["ok"], true, "{q}"); h.step(); diff --git a/docs/curve-stage.md b/docs/curve-stage.md new file mode 100644 index 00000000000..4f679b508c9 --- /dev/null +++ b/docs/curve-stage.md @@ -0,0 +1,117 @@ +# Whites and the tone curves, measured (process V18) + +> **Changes:** [revision history](#revision-history) + +Process V18 renders Whites, the parametric curve and the point curves the way Lightroom does, with LightCraft's own +model fitted to measurements of Camera Raw's output. V1 to V17 are unchanged (`docs/process-versions.md`). The code is +`crates/pipeline/src/curve_stage.rs`, the model's fitted constants `crates/pipeline/src/curve_stage_model.rs`, and the +GPU kernel's `curve_stage` in `crates/gpu/src/wgsl/finish.wgsl`. + +## What was wrong + +Up to V17 Whites is part of the tone map, which acts on luminance, and the curves act on each channel of the +display-encoded output. Measured against Camera Raw, this goes wrong in three ways: + +- **Whites reaches too little.** Lightroom's Whites moves the upper midtones too: at Whites −50 an sRGB-encoded 0.6 + drops by about 10/255. V17's Whites barely touches them. +- **The parametric regions are too narrow.** Lightroom's Highlights, Lights, Darks and Shadows regions are broad and + overlap, and they add: the sum of the single regions reproduces three at once within 1/255. +- **Per-channel curves shift hues.** A contrast curve applied to R, G and B separately pushes orange towards red and + saturates. Lightroom's master curve keeps the hue. It maps the largest and the smallest channel through the curve, + and the middle channel keeps its relative position between them in linear light. + +## What V18 does + +After the tone map and V4's calibrated Contrast and Blacks, before the colour stage: + +1. Convert linear Rec.2020 to linear ProPhoto RGB (D50, Bradford) and encode with the sRGB curve, as the V4 + operators do (`light_v3::prophoto_matrices`). +2. Build the base table: Whites, then the parametric curve, then the master point curve. Whites and each of the four + regions add a fitted response to the diagonal (below). The regions are fitted for Lightroom's default splits + (25, 50, 75). With other splits the parametric curve is the analytic model of the earlier processes. The table is + kept non-decreasing. +3. Apply the base table to the largest and smallest channel. The middle channel keeps its relative position between + them in linear light. +4. Apply the red, green and blue point curves to each channel. +5. Refine Saturation (below 100) moves saturation back towards the colour after Whites, and then rescales to the + curves' linear luminance, so the tone change stays. In Lightroom it belongs to the tone curve, and Whites comes + before it, so Whites keeps its saturation change whether a curve is set or not (V17 and earlier refine on encoded + output, where there is no Whites). +6. Values above SDR white (an HDR render) continue with slope 1. + +The tone map no longer applies Whites under V18 (`finish::base_tone`), and the V17 output-curve tables are not built +(`FinishParams::curves` is `None`). With Whites, the parametric curve and the point curves all neutral, the curve +stage does not run. + +## The model + +Each slider direction (negative and positive) of Whites and of each region has its own response, output minus input +on sRGB-encoded values: the sum of two smooth bumps. With `t` = |amount| / 100, + + response(x) = Σ (a1 t + a2 t² + a3 t³) · bump(x, e^(p0 + p1 t), e^(q0 + q1 t)) + bump(x, p, q) = (x / m)^p · ((1 − x) / (1 − m))^q, m = p / (p + q) + +A bump is 0 at black and white and 1 at its peak `m`. The gain grows faster than linearly with the amount, and the +bump's position and width move with the amount, as Lightroom's regions widen and move when pushed harder. That is 7 +constants per bump, 14 per slider direction and 140 in all. The fit keeps every response growing with the amount at +every input and never acting against the slider, so dragging the graph moves the slider steadily. + +## The Edit panel's graph + +The parametric graph draws the curve the photo renders, from `curve_stage::ParametricGraph`: the fitted regions +under V18 at the default splits, else the analytic model. Dragging the line moves the region under the pointer by +the amount that puts the drawn curve where the pointer is. The fitted regions are not linear in the amount, so the +amount is searched for, on the side of the starting value the drag moves to, on the curve as drawn (kept monotone, so +where opposite regions fold it back the line is held flat by the peak to its left). A level out of the region's reach +saturates at ±100. A region that cannot move the line by half an 8-bit level in that direction keeps its value. +Whites is not part of the graph, as in Lightroom. + +## How it was measured + +`tools/lr_tone_charts.py charts OUT_DIR` writes linear DNG charts: 48 grey steps from 0.002 to 1 and OkLCh colour +patches, with the settings in the DNG's XMP. It writes one neutral chart, Whites at each measured amount, and each +parametric region at each measured amount. The charts are original test data. Every chart was rendered through +Camera Raw to a 16-bit Adobe RGB (1998) TIFF. Only that output is measured, and nothing of Adobe's is copied or +shipped, and no measurement is committed. `tools/lr_tone_charts.py fit RENDER_DIR OUT_RS [CHART_DIR]` takes the charts' `curve__manifest.json` from CHART_DIR +(RENDER_DIR when the renders sit beside the charts), reads the grey steps of +each render as sRGB-encoded linear ProPhoto values, fits the model to them and writes only its constants, +`curve_stage_model.rs`. It needs numpy, scipy and tifffile (`tools/requirements-lr-tone-charts.txt`). Running the +tool again reproduces the committed charts byte for byte, and the constants with the pinned packages. + +How close the model is to the measured response, as the stage renders it (both clamped to 0..1), over 257 inputs and +every measured amount, in 8-bit levels of the sRGB-encoded output: + +| Setting | negative: RMS | max | positive: RMS | max | +|---|---|---|---|---| +| Whites | 0.15 | 0.88 | 0.27 | 1.62 | +| Shadows | 0.39 | 2.18 | 0.34 | 1.37 | +| Darks | 0.33 | 1.73 | 0.19 | 1.32 | +| Lights | 0.05 | 0.17 | 0.37 | 1.04 | +| Highlights | 0.15 | 0.64 | 0.52 | 2.29 | + +Every largest error but one (Darks +50, at black) is at ±75 or ±100. + +The grey steps leave out how colour is treated. To check that, the colour patches of the same renders were +predicted from the grey-step curves under the hue-preserving rule in step 3. The prediction is within 0.03 to 0.16 +(OkLab × 100) of Camera Raw's patches, against 0.3 to 3.4 for V17's per-channel curves. + +## Limits + +- The regions are fitted with Lightroom's default splits. Moved splits use the earlier analytic model. +- The point curves' shape between the points is LightCraft's spline, not measured. What is measured for them is how + they apply: hue preserving, then the red, green and blue curves per channel. +- Local (mask) Whites keeps the earlier processes' operator. +- Apple ProRAW keeps V17's Lightroom tone chain (`crate::proraw`), which applies Whites itself. On those photos the + stage applies only the curves. +- The measurements use Camera Raw's process version 2012 controls (`crs:ProcessVersion` 11.0). + +## Revision history + +| Date | Change | Summary | +|---|---|---| +| 2026-11-10 | minor | Process V18: measured Whites and parametric curve, hue-preserving master curve | +| 2026-11-11 | minor | The Edit panel's parametric graph draws and drags the measured regions under V18 | +| 2026-12-02 | patch | Renumbered from V9 to V17, on top of V16: main retired 9 | +| 2026-11-24 | minor | Whites and the regions are a fitted model instead of measured tables | +| 2026-12-03 | patch | Renumbered from V17 to V18, on top of V17: main took 17 for Apple ProRAW (#4196) | +| 2026-12-03 | patch | Refine Saturation restores the colour after Whites, so Whites alone and Whites with a curve agree (review on #4099) | diff --git a/docs/gaps.md b/docs/gaps.md index b859d9c18b3..d16d5c7fb9a 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -17,7 +17,7 @@ Hours are Opus 5.5 agent wall-clock hours (see [target-app-parity.md](target-app |---:|---|---|---|---:|---| | 1 B | **Camera colour is estimated, not measured** (LR-PROF-CAMERACOLOR). Raws start from a per-file fit to the camera JPEG, 10 bundled profiles, 52 spectral matrices (plus same-sensor bodies, e.g. the X-T30 through the X-T3) or chart-measured matrices (the EOS D60); others use a neutral matrix (a black-and-white camera JPEG gives its tone curve only, #577; dark JPEG tones also guide the toe, #1307) | ΔE vs camera JPEG 2.9–10 after fitting (raw-parity.md); 1 chart-calibrated model (EOS D60: its Kelvin scale and fallback colour, the look stays the JPEG fit) vs 1,500 Adobe Standard profiles | every raw shooter sees colour that is close but not Lightroom's; some get neutral-matrix colour | 50–90 | [raw-parity](raw-parity.md#colour) | | 2 B | **CR3 variants no public file uses** (LR-IMP-FORMATS): `crx.rs` refuses vertical-tile C-RAW, partial-subband and other plane coding, multi-tile 0x200 and adaptive low-frequency gains, and those files fall back to the preview. All 110 CC0 CR3s on raw.pixls.us (31 folders) decode from sensor data, so none of these variants has a public sample; 26 CR3 bodies are verified (M50 / R100 / R8 exact, R5 Mark II pinned, 22 more pinned on one CC0 file each and checked against the camera JPEG, [cr3.md](cr3.md#further-bodies-one-cc0-file-each)). HEIF stills are `.HIF` files, not CR3; no CR3 sRAW / mRAW sample exists | measured: Canon's share whose camera fully works 73% → 94% (raw-parity.md); 18 of 22 popular Canon bodies write CR3, all 18 now verified | +0.3 points of photographers; the variants surface only as user files that open as a preview | 10–25 | [raw-parity](raw-parity.md#remaining-work-ranked-by-photographers-unlocked-per-hour) | -| 3 B | **Render fidelity partial** (LR-BEHAV-RENDER-FIDELITY): calibrated camera-look Contrast and Blacks; other operators need measurement; from process V5 raw tone curves roll off into white in stops, so Exposure keeps recorded highlights (#1632); from process V17 Apple ProRAW takes Lightroom's fitted tone chain | process V3 reduces held-out response error from 0.136 to 0.038 stops for Contrast and 0.424 to 0.077 for Blacks on one Sony camera; Whites remains V2 pending a follow-up | imported Lightroom edits still differ, especially on uncalibrated operators and cameras | 30–60 | [calibrated Light operators](light-v3.md), [process versions](process-versions.md) | +| 3 B | **Render fidelity partial** (LR-BEHAV-RENDER-FIDELITY): calibrated camera-look Contrast and Blacks; other operators need measurement; from process V5 raw tone curves roll off into white in stops, so Exposure keeps recorded highlights (#1632); from process V17 Apple ProRAW takes Lightroom's fitted tone chain; from V18 Whites and the parametric curve at its default splits are measured against Camera Raw, and the point curves (still LightCraft's spline) apply hue preserving as Lightroom's do ([curve-stage.md](curve-stage.md)) | process V3 reduces held-out response error from 0.136 to 0.038 stops for Contrast and 0.424 to 0.077 for Blacks on one Sony camera; V4 to V16, and V17 except Apple ProRAW (fitted Whites in its own chain), keep V2 Whites; for other photos V18's Whites is fitted to Camera Raw's grey-step charts, not yet checked on photos per camera | imported Lightroom edits still differ, especially on uncalibrated operators and cameras | 30–60 | [calibrated Light operators](light-v3.md), [process versions](process-versions.md) | | 4 | ~~Original-pixel detail at 100%~~ (LR-VIEW-ZOOM): closed 2026-10-12, see Closed recently | checklist row ✅ | — | 0 | [ui-parity](ui-parity.md) | | 5 B | **AI masks: Subject, Sky, People, Background, Landscape** are heuristics; Object / Describe run SAM 3 but its download has no mirror configured | `crates/segment`; ai-masks.md; MASK rows 67% | masking is how most Lightroom users edit today | 40–70 + model decision | [target-app-parity](target-app-parity.md#ai) | | 6 | **Compressed ORF** (support withdrawn) | #3775 decoder removed pending provenance review; uncompressed support remains | compressed files use embedded JPEG previews when available, not sensor data | pending review | [orf-compression](orf-compression.md) | @@ -96,6 +96,7 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w | Date | Change | Summary | |---|---|---| +| 2026-12-02 | minor | Gap 3: from V18 Whites and the parametric curve at its default splits are measured against Camera Raw, and the point curves (still LightCraft's spline) apply hue preserving as Lightroom's do ([curve-stage.md](curve-stage.md)); gap not closed | | 2026-11-26 | minor | Gap 31 added: sidebar multi-selection — the batch album, keyword and library-folder commands (#2757) have no sidebar caller yet | | 2026-11-01 | minor | Gap 13: Lightroom catalog backup zips import directly, and a backup of an imported catalog adds no collection twice (#2592); the gap stays open | | 2026-11-07 | correction | Compressed ORF sensor support withdrawn pending provenance review; embedded preview fallback remains. Coverage regenerated without the removed decoder: 557 verified, 665 unverified, 187 preview-only, 37 unsupported; 94% use-weighted coverage. | diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 455157e4acc..476f810c3b2 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -188,10 +188,10 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-EDIT-LIGHT-CONTRAST | Contrast | P0 | 🟡 | `ctl:light.contrast` | From process V4, global Contrast on the camera-look path is fitted per channel in ProPhoto with the sRGB transfer. Check response error 0.136 to 0.038 stops on six held-out Sony photos. Other sources and local adjustments retain V2; broader parity remains unverified (`docs/light-v3.md`). | | 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; from process V8 (`local::detail_free`: clamped between the median at that radius and one 3× wider) 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); from process V8, 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). From process V13 the global amount eases off as it grows: the operator's strength is `a / (1 + 1.33·abs(a))` for `a` = slider / 100 (0.43 at +100, against 1 up to V10), fitted to Lightroom exports (#523). | -| LR-EDIT-LIGHT-WHITES | Whites | P0 | 🟡 | `ctl:light.whites`, `crates/pipeline/src/visualize.rs` | V4 preserves V2 Whites for both signs. Calibration is a planned follow-up; measured V2 check response error is 0.075 stops on the Sony test photos (`docs/light-v3.md`). Alt/Option-drag shows highlight clipping (black, clipped channels in colour) | +| LR-EDIT-LIGHT-WHITES | Whites | P0 | 🟡 | `ctl:light.whites`, `crates/pipeline/src/visualize.rs` | From process V18 Whites is measured against Camera Raw renders of synthetic grey steps and reaches into the midtones as Lightroom's does ([curve-stage.md](curve-stage.md)); not yet compared on photos per camera. V4 to V16, and V17 except Apple ProRAW, preserve V2 Whites for both signs; ProRAW uses its chain's fitted Whites from V17, under V18 too; measured V2 check response error is 0.075 stops on the Sony test photos (`docs/light-v3.md`). 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` | From process V4, global Blacks on the camera-look path uses a fitted per-channel/luminance mix. Check response error 0.424 to 0.077 stops on six held-out Sony photos; deepest tones still differ. Other sources and local adjustments retain V2 (`docs/light-v3.md`). 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); sampled selected-curve input backdrop (#987); [stage and sampling limits](tone-curve-input.md) | -| LR-EDIT-LIGHT-CURVE-POINT | Point curve | P0 | ✅ | `cmd:develop.curve`, `cmd:curve.reset`, `cmd:curve.presets`, `cmd:curve.applyPreset`, `cmd:curve.savePreset`, `cmd:curve.deletePreset`, `cmd:curve.importPresets`, `cmd:curve.exportPresets`, `cmd:file.importCurvePresets`, `cmd:file.exportCurvePresets`, `crates/engine/src/cmd/curves.rs`, `crates/ui-egui/src/panels/edit.rs` | click to add a point; drag a point in both axes (between its neighbours, input / output readout, one undo step per drag; ⌥-drag moves it a tenth as far for fine adjustment, issue #1363); drag empty space to add and drag; double-click removes; reset: double-click a channel selector (that channel), the Reset button under the graph (every curve incl. parametric) or right-click the graph (channel / all); Point Curve preset dropdown: own Linear / Medium Contrast / Strong Contrast, user presets (save the current point curves, delete by right-click; saved with the library), import / export as `.lccurve` JSON; sampled input after Parametric, independent of this curve (#987); [stage and sampling limits](tone-curve-input.md) | +| 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` | from process V18 the regions are LightCraft's model fitted to Camera Raw's measured response at the default splits, broad and additive ([curve-stage.md](curve-stage.md)); the graph draws the curve the photo renders (`ParametricGraph`: the fitted regions under V18 at the default splits, else the analytic model); dragging the line moves the region under the pointer (one undo step); sampled selected-curve input backdrop (#987); [stage and sampling limits](tone-curve-input.md) | +| LR-EDIT-LIGHT-CURVE-POINT | Point curve | P0 | ✅ | `cmd:develop.curve`, `cmd:curve.reset`, `cmd:curve.presets`, `cmd:curve.applyPreset`, `cmd:curve.savePreset`, `cmd:curve.deletePreset`, `cmd:curve.importPresets`, `cmd:curve.exportPresets`, `cmd:file.importCurvePresets`, `cmd:file.exportCurvePresets`, `crates/engine/src/cmd/curves.rs`, `crates/ui-egui/src/panels/edit.rs` | click to add a point; drag a point in both axes (between its neighbours, input / output readout, one undo step per drag; ⌥-drag moves it a tenth as far for fine adjustment, issue #1363); drag empty space to add and drag; double-click removes; reset: double-click a channel selector (that channel), the Reset button under the graph (every curve incl. parametric) or right-click the graph (channel / all); Point Curve preset dropdown: own Linear / Medium Contrast / Strong Contrast, user presets (save the current point curves, delete by right-click; saved with the library), import / export as `.lccurve` JSON; from process V18 the master curve keeps hue as Lightroom's does (largest and smallest channel through the curve, the middle one in proportion), and the red, green and blue curves follow it per channel ([curve-stage.md](curve-stage.md)); sampled input after Parametric, independent of this curve (#987); [stage and sampling limits](tone-curve-input.md) | | LR-EDIT-LIGHT-CURVE-RGB | Per-channel curves | P0 | ✅ | `cmd:develop.curve` (`channel`) | sampled selected-curve input backdrop (#987); [stage and sampling limits](tone-curve-input.md) | | LR-EDIT-LIGHT-CURVE-REFINESAT | Curve saturation compensation | P1 | ✅ | `ctl:curve.refineSaturation` | | | LR-EDIT-LIGHT-CURVE-TAT | Drag-on-image curve adjust | P1 | ✅ | `cmd:develop.targeted` (`target: curve`) | | @@ -472,7 +472,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-BEHAV-OFFLINE | Offline editing | P1 | ✅ | | local-first: everything works offline | | LR-BEHAV-WEB-SAFETY | Library safety in the browser build | P1 | 🟡 | `cmd:file.backupLibrary`, `cmd:file.restoreLibrary`, `apps/lightcraft-web/src/safety.rs`, `apps/lightcraft-web/src/backup.rs`, `apps/lightcraft-web/src/files.rs` | web only (experimental): Back Up Library (zip of the catalog and every stored original) and a non-destructive Restore; failed saves show as unsaved and are retried; a photo that can't be stored isn't added; one tab per library (Web Locks); notices for storage that isn't persistent and for a library that can't open; `?reset` asks first; a panic shows a message. Missing: `?safe` start, deleting originals of removed photos, zip64 (backups > 4 GB) | | LR-BEHAV-GPU | GPU acceleration | P0 | ✅ | `crates/gpu/src/render.rs`, `cmd:app.gpu`, `docs/gpu-pipeline.md`, `crates/ui-egui/src/panels/notices.rs` | CPU fallback per render on device limits, out of memory, device errors / loss, incomplete or black results (`perf.gpuReason`, `perf.gpuFallback`; each render reports its own reason — `lightcraft_gpu::try_render`, `gpuFallback` per exported file — issue #675); short submissions for slow iGPUs; backend choice (DX12 only on Windows, `LIGHTCRAFT_GPU_BACKEND` / `WGPU_BACKEND`), device created after the window opens, crash sentinel (issue #136); a GPU lost while LightCraft runs (driver reset) stops it with that message and turns GPU rendering off for the next start, which says why (issue #1337; the window's renderer can't survive the lost device); quitting waits (up to 2 s) for renders in flight and starts no new GPU work, so none is inside the driver when the process exits (`crates/gpu/src/exit.rs`, issue #620; seen crashing only on Linux + NVIDIA, other drivers unverified); with GPU rendering on and no adapter found at all (e.g. no Vulkan loader on NixOS outside `nix develop`), the desktop app says once per session that it renders on the CPU and points to Help ▸ System Info (`gpu_notice`; not when the GPU is turned off or only a software adapter exists); no tiling beyond the buffer limit (CPU) | -| LR-BEHAV-RENDER-FIDELITY | Rendering matches Lightroom | P1 | 🟡 | `crates/pipeline/src/lib.rs`, `crates/pipeline/src/tone.rs`, `crates/pipeline/src/proraw.rs` | Process V4 calibrates global camera-look Contrast and Blacks against black-box Lightroom exports of Sony ILCE-7CR photos. Held-out response errors are 0.038 and 0.077 stops; V1/V2 keep their rendering. Whites retains V2 and awaits a follow-up. Exposure, Highlights/Shadows, other operators and broader camera coverage remain open (`docs/light-v3.md`). From process V5 a raw's tone curve rolls off into white in stops (past a camera curve's last fitted knot, or from half a stop below the generic curve's white point instead of clipping), so Exposure +1 and +2 keep the highlights the sensor recorded: on 12 CC0 corpus raws and 6 CC0 DNGs on the generic curve, unclipped pixels whose luminance renders at 254 or more fall from up to 22.5 % to 0 at +1 EV and from up to 35 % to at most 0.03 % at +2 EV, apart from one sky that is mostly at the clip (#1632). Not compared with Lightroom's output. From process V13 global Shadows eases off at large amounts (`finish::tone_slider`, +100 at 0.43 of V6), fitted to 56 Lightroom exports of real Canon portrait edits at Shadows +40 to +100; with negative Texture and the Global wheel, mean ΔE on those exports 9.5 → 9.0. Global Highlights stays linear: on those edits V6 renders the brightest tones about 5 L* too dark, but single-slider exports show Lightroom's Highlights response close to linear and dependent on the frame's content (#3923), so that coverage-dependent strength, and smaller Shadows amounts, remain open. From process V17 Apple ProRAW (Make Apple and a `ProfileToneCurve`) takes Lightroom Classic's tone chain: base operator, Highlights / Shadows on a neighbourhood of the photo, Whites, Blacks, the profile curve per channel, Contrast adapting to the image; closed-form operators fitted on one CC0 iPhone 12 Pro file against Lightroom Classic 15.6 exports, mean CIEDE2000 unedited 2.93 → 1.05 and the 12 single tone-slider renders 3.73 → 1.22 (#613). Other cameras keep the operators above | +| LR-BEHAV-RENDER-FIDELITY | Rendering matches Lightroom | P1 | 🟡 | `crates/pipeline/src/lib.rs`, `crates/pipeline/src/tone.rs`, `crates/pipeline/src/proraw.rs` | Process V4 calibrates global camera-look Contrast and Blacks against black-box Lightroom exports of Sony ILCE-7CR photos. Held-out response errors are 0.038 and 0.077 stops; V1/V2 keep their rendering. V4 to V16, and V17 except Apple ProRAW, keep V2 Whites; ProRAW uses its chain's fitted Whites from V17, and V18 measures Whites for other photos (below). Exposure, Highlights/Shadows, other operators and broader camera coverage remain open (`docs/light-v3.md`). From process V18 Whites, the parametric curve (at the default splits; moved splits keep the analytic model) and the point curves follow Camera Raw's measured response on synthetic grey steps, the master curve hue-preserving ([curve-stage.md](curve-stage.md)). From process V5 a raw's tone curve rolls off into white in stops (past a camera curve's last fitted knot, or from half a stop below the generic curve's white point instead of clipping), so Exposure +1 and +2 keep the highlights the sensor recorded: on 12 CC0 corpus raws and 6 CC0 DNGs on the generic curve, unclipped pixels whose luminance renders at 254 or more fall from up to 22.5 % to 0 at +1 EV and from up to 35 % to at most 0.03 % at +2 EV, apart from one sky that is mostly at the clip (#1632). Not compared with Lightroom's output. From process V13 global Shadows eases off at large amounts (`finish::tone_slider`, +100 at 0.43 of V6), fitted to 56 Lightroom exports of real Canon portrait edits at Shadows +40 to +100; with negative Texture and the Global wheel, mean ΔE on those exports 9.5 → 9.0. Global Highlights stays linear: on those edits V6 renders the brightest tones about 5 L* too dark, but single-slider exports show Lightroom's Highlights response close to linear and dependent on the frame's content (#3923), so that coverage-dependent strength, and smaller Shadows amounts, remain open. From process V17 Apple ProRAW (Make Apple and a `ProfileToneCurve`) takes Lightroom Classic's tone chain: base operator, Highlights / Shadows on a neighbourhood of the photo, Whites, Blacks, the profile curve per channel, Contrast adapting to the image; closed-form operators fitted on one CC0 iPhone 12 Pro file against Lightroom Classic 15.6 exports, mean CIEDE2000 unedited 2.93 → 1.05 and the 12 single tone-slider renders 3.73 → 1.22 (#613). Other cameras keep the operators above | | LR-BEHAV-DRAGDROP | Drag and drop | P1 | ✅ | `crates/ui-egui/src/lib.rs`, `crates/ui-egui/src/panels/grid.rs` (`drag_feedback`), `crates/ui-egui/src/panels/left.rs` (`drop_target`, `album_drag_over`, `top_level_drop_target`, `drag_auto_scroll`), `crates/ui-egui/src/tests/drag_contract.rs`, `crates/ui-egui/src/destination.rs`, `crates/ui-egui/src/widgets.rs` (`context_menu`), `crates/ui-egui/src/widgets/text_field.rs`, `crates/ui-egui/src/tests/carried_right_click.rs`, `crates/ui-egui/src/tests/carried_text_field_menu.rs` | a right-click while photos are carried opens no context menu (every menu opened through `widgets::context_menu`: sidebar rows, grid cells, lists; a text field's own Cut / Copy / Paste menu too); files → app (a drop-target card while they hover, then the import review); grid photos → an album row (the dragged label says how many photos it adds, or that they are all there already, and a drop then does nothing, with no undo step; a drop that finds some there says so in its toast); a smart album, an album folder and the sidebar's Keywords rows refuse photos with the not-allowed cursor and a reason, on the label and in the toast; Esc gives up any drag (photos, albums, sidebar sections, keywords) and does nothing else; sidebar album / folder rows → a folder (moves it; its name follows the pointer); a drag of albums or grid photos near the top or bottom edge of the sidebar scrolls it (faster nearer the edge, only while the pointer is over the sidebar); when another folder has the same name, the dragged label, the Move question and the toast name the folder it is in (`home (/a)`); an album drop's toast does the same for an album of that name in another album folder (two in the same place have nothing to tell them apart and keep the plain name); only the primary button drags photos and drops them: a right-button drag over a grid cell neither picks photos up nor changes the selection, and a right-button release while photos are dragged neither drops them nor ends the drag | | LR-BEHAV-TOAST | Toast notifications | P1 | ✅ | `crates/ui-egui/src/panels.rs` | | | LR-BEHAV-DIALOGS | Dialogs fit the window | P1 | ✅ | `crates/ui-egui/src/dialogs.rs` (`dialog_body`, `list_height`), `crates/ui-egui/src/tests/dialog_fit.rs`, `crates/ui-egui/src/tests/dialog_copy.rs`, `crates/ui-egui/src/tests/dialogs.rs` (`a_click_outside_closes_the_dialog_when_settings_allow_it`) | a dialog taller than the window (Export on a 1366×768 screen, issue #781) never runs off it: its options scroll while the title bar and the Cancel / confirm row stay on screen (the confirm button names its action: Create, Rename, Create Stacks, Export 3 Photos…, with "OK" kept only for a one-field prompt opened with a command that has no verb, `crates/ui-egui/src/tests/dialog_copy.rs`); lists that scroll on their own (What's New, All Metadata, shortcuts, smart-album rules, credits) get shorter first; dialogs that fit look as before; Import keeps its own resizable, scrolling window; Settings → Dialogs → Close a dialog by clicking outside it (off by default, so a stray click never throws away a dialog's choices): a click pressed and released on the dimmed backdrop closes the dialog like Esc and doesn't reach the panels below, while a drag that ends outside (a slider pulled past the edge) or a click that closes a dropdown keeps it; the import review never closes this way (`clicked_backdrop`); a one-line prompt (Rename Folder, New Folder on Disk, the preset and version names, New Library when its name can't be used, Auto-Tag from Tracklog) the engine refuses stays open with its text and shows the reason in a toast, so the name can be corrected, where it used to close without a word; a New Folder on Disk that works says so (“Created folder “Selects” in “2026/Shoot””, naming the parent by its last two folders as dialogs do) | @@ -738,7 +738,7 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06- | LRC-DEV-CALIB | Calibration panel | P1 | ✅ | `ctl:calibration.*` | | | LRC-DEV-TAT | Targeted adjustment tools | P1 | ✅ | `cmd:develop.targeted` (`target`: curve / hue / sat / lum) | | | LRC-DEV-DEFAULTS | Per-camera raw defaults | P1 | ✅ | `cmd:library.preferences` (`camera`, `import.perCamera`), `crates/ui-egui/src/dialogs/settings.rs` | Settings → Import: raw default and per-camera presets | -| LRC-DEV-PROCESS | Process versions, Update to Current Process | P1 | ✅ | `cmd:develop.updateProcess`, `cmd:develop.reset`, `cmd:develop.get`, `crates/develop/src/settings.rs`, `crates/pipeline/src/finish.rs`, `docs/process-versions.md` | Each photo keeps its saved rendering process. V1 is legacy, V2 preserves Highlights/Shadows detail, V3 is pixel-scale sharpening, V4 calibrates camera-look Contrast and Blacks, V5 rolls raw tone curves off into white in stops (#1632), V6 takes colour noise reduction to the joint method (#815), V7 draws film grain from crystal layers, V8 keeps the gaps in dark lettering under Highlights and Shadows (#3460), V10 checks the Bradford white-balance fallback (craft-libs#587), V13 eases global Shadows off at large amounts and has negative Texture and the Global grading wheel act less, as measured against Lightroom exports (#523), V14 pins Heal and Remove spots to the photo on the spot's edge. New photos and Reset use the latest; Update is one undoable step and never downgrades a future number. Copy/paste/sync preserve the receiving process. Persistent render keys include the resolved process from V3 on; V1/V2 keys remain unchanged. | +| LRC-DEV-PROCESS | Process versions, Update to Current Process | P1 | ✅ | `cmd:develop.updateProcess`, `cmd:develop.reset`, `cmd:develop.get`, `crates/develop/src/settings.rs`, `crates/pipeline/src/finish.rs`, `docs/process-versions.md` | Each photo keeps its saved rendering process. V1 is legacy, V2 preserves Highlights/Shadows detail, V3 is pixel-scale sharpening, V4 calibrates camera-look Contrast and Blacks, V5 rolls raw tone curves off into white in stops (#1632), V6 takes colour noise reduction to the joint method (#815), V7 draws film grain from crystal layers, V8 keeps the gaps in dark lettering under Highlights and Shadows (#3460), V10 checks the Bradford white-balance fallback (craft-libs#587), V13 eases global Shadows off at large amounts and has negative Texture and the Global grading wheel act less, as measured against Lightroom exports (#523), V14 pins Heal and Remove spots to the photo on the spot's edge, V17 renders Apple ProRAW in Lightroom's fitted tone chain, V18 measures Whites and the tone curves against Lightroom and keeps hue through the master curve. New photos and Reset use the latest; Update is one undoable step and never downgrades a future number. Copy/paste/sync preserve the receiving process. Persistent render keys include the resolved process from V3 on; V1/V2 keys remain unchanged. | | LRC-DEV-VIEWOPTIONS | Develop view options | P2 | 🟡 | `cmd:view.viewOptions`, `crates/ui-egui/src/dialogs/settings.rs` (`view_options`) | View ▸ Loupe Overlay ▸ View Options… (⌘J), the Loupe View part: Show Info Overlay with Info 1 / Info 2, and the three lines of each (none, file name, capture date, dimensions, exposure, camera, lens, camera + lens) with Use Defaults; Show Briefly When Photo Changes under each Info (one at most): with the overlay off, that Info shows for 3 s each time the loupe changes photo; General's Show message when loading or rendering photos (on by default; off, the loupe does not say "Rendering…"); applied as they change, saved with the app settings; `view.viewOptions {info1, info2, briefly, loupeMessages}` sets them for agents. Not yet: the Grid View tab, more fields (ratings, metadata, copy name), the video-frame option | | LRC-DEV-LOUPEOVERLAY | Loupe overlay: layout image | P2 | 🟡 | `cmd:view.chooseLayoutImage`, `cmd:view.layoutImage`, `cmd:view.layoutImageOpacity`, `cmd:view.layoutImageMatte`, `crates/ui-egui/src/panels/layout_overlay.rs` | View ▸ Loupe Overlay: a PNG with transparency (a cover layout, a banner's safe areas) fitted and centred over the loupe photo, following zoom and pan; opacity and matte (the photo darkened outside the graphic's box) in steps; ⌥⌘O shows / hides it; read off the UI thread; saved with the UI state. Not yet: the Grid and Guides overlays, moving and resizing the layout with ⌘ held, free opacity / matte sliders | | LRC-DEV-VIDEO | Video frame capture | P2 | ⬜ | | | @@ -1117,6 +1117,8 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-17 | minor | LR-BEHAV-DRAGDROP: Esc gives up a photo drag (and only the drag); album rows say how many photos a drop adds or that they are there already (a no-op drop changes nothing); smart albums, album folders and the sidebar's Keywords rows refuse photos with the not-allowed cursor and a reason; the Keyword List says how many photos get a keyword and refuses a keyword dropped inside itself; LR-LIB-ALBUM and LRC-LIB-KEYWORDS text updated; status unchanged (✅) | | 2026-10-27 | patch | MENU-HELP-FEEDBACK: on macOS the Help menu no longer shows the system's `Send Feedback` row beside Send Feedback… | | 2026-10-17 | minor | LR-LIB-SMARTALBUM, LR-LIB-PEOPLE, LR-VIEW-FOCUSPOINT, LR-VIEW-BEFOREAFTER, LR-VIEW-SLIDESHOW, LR-BEHAV-SIDEBAR-HIDE, MENU-VIEW-PHOTOCOUNT, MENU-VIEW-SIDEBARSECTIONS, KEY-MASKCOLOR, LRC-LIB-METADATA, LRC-MAP-TRACKLOG, LRC-SS-PLAYBACK, LRC-SS-EXPORT, LRC-DEV-VIEWOPTIONS: menu bar reorganised; the rows now cite the new paths (View ▸ Loupe Overlay, Before/After, Mask Overlay, Slideshow, Sort; Window for panel toggles; Photo ▸ Metadata); no command changed and no status changed | +| 2026-11-10 | minor | LR-EDIT-LIGHT-WHITES, LR-EDIT-LIGHT-CURVE-PARAM, LR-EDIT-LIGHT-CURVE-POINT, LR-BEHAV-RENDER-FIDELITY, LRC-DEV-PROCESS: process V18 measures Whites and the parametric curve against Camera Raw and applies the master curve hue-preserving ([curve-stage.md](curve-stage.md)); statuses unchanged | +| 2026-11-11 | patch | LR-EDIT-LIGHT-CURVE-PARAM: the graph draws and drags the curve the photo renders, the measured regions under V18 at the default splits; status unchanged (✅) | ## External-profile correspondence geometry diff --git a/docs/process-versions.md b/docs/process-versions.md index 12c23e24e9f..89165f78e0a 100644 --- a/docs/process-versions.md +++ b/docs/process-versions.md @@ -24,7 +24,8 @@ stronger Light sliders, issue #196) without changing a single photo someone has | **V14** | V13 plus: Heal spots, and Remove spots with their automatic source, are pinned to the photo on the spot's edge (`spots::pinned`, [heal-pinned.md](heal-pinned.md)). The patch is the source times `e^P`, `P` the membrane fill (`lightcraft_inpaint::membrane_fill`) of the log ratio of photo to source, known only on the ring of pixels touching the spot and blurred there over the outside only (1.5 px), so the patch meets its surroundings at the edge, takes nothing from features that don't touch it, and carries the source's texture at its contrast relative to the new light. The source's fine detail (log luminance minus a 1.5 px blur) is scaled to the detail around the spot, by the ratio of medians around the spot (1.05 to 2 radii) and inside the source (0.9 radii), within 0.5 to 2×. Every spot, Clone included, reads its source at whole pixels (read between pixels, bilinear sampling halved the grain). V1 to V13 keep the source plus a Gaussian-weighted average of the difference around the spot (σ 0.6 radii) in linear light. A Heal or Remove spot whose working box holds more than `MAX_SPOT_SPAN² / 2` pixels (about 33.5 million; 8.4 million on the web) is too big for the pinned heal's working memory and gets the V13 averaged correction instead, still reading its source at whole pixels. Fill is unchanged. CPU and GPU branch on `spots::HealMethod`; the GPU renderer reads the image back for the spot stage on V14 photos with spots and keeps the rest of the render on the device. Renders without Heal, Remove or Clone spots are the same as V13's. | | **V15** | V14 plus: brush Flow is the coverage a stroke adds per brush radius it travels, as in Lightroom Classic (#4045): each dab adds `1 − (1 − flow)^(d / r)` for a dab `d` past the previous one (the first dab counts one radius, so a click paints its flow), `masks::travel_flow`. A point a stroke passes over for a length `L` is then covered by `1 − (1 − flow)^(L / r)` however densely the dabs lie: a straight stroke's centre by 44 % at Flow 25 and 75 % at Flow 50, where Lightroom Classic measures 41 % and 76 % on a grey card. V1 to V14 add the full flow per dab (r/4 apart on a fast drag, closer on a slow one): 90 % at Flow 25 on a fast stroke, more on a slow one. CPU (`masks::brush_dabs_within`), GPU (a flow per dab in the `shape` kernel's brush data) and the live stroke (`brush_live`, the masking and Lens Blur brushes) all branch on `masks::flow_per_radius`. Renders without brush strokes, or with Flow 100 only, are the same as V14's. | | **V16** | V15 plus: a brush stroke's edge is feathered as one dab's is. Each stroke keeps its Flow build-up (every dab that reaches a pixel adds its flow, `masks::feather_dab`) apart from its edge (the highest falloff of those dabs), and covers their product up to Density (`masks::stroke_coverage`). V1 to V15 accumulate each dab's falloff times its flow, so the soft edges of dabs r/4 apart piled up: at Feather 100 and Flow 100 a straight stroke covered 0.90 halfway out from its centre line, where one dab covers 0.50; V16 covers 0.50. Below Flow 100 the centre now builds up by Flow per radius travelled whatever the Feather (a straight stroke's 44 % at Flow 25), where V15 also weakened a soft brush's centre (25 %). CPU (`masks::rasterize_brush`), GPU (a stroke-record word in the `shape` kernel's brush data) and the live stroke (`brush_live`, the masking and Lens Blur brushes) branch on `masks::stroke_feather`. Auto Mask strokes keep V15's accumulation (their edge follows the photo's edges, not the feather). Renders without brush strokes, or with Feather 0 or Auto Mask brushes only, are the same as V15's; a saved V1 to V15 photo keeps its strokes until Update to Current Process. | -| **V17** (the latest) | V16 plus: Apple ProRAW (Make `Apple` and a DNG `ProfileToneCurve`) renders its Light sliders through Lightroom Classic's fitted tone chain (`crates/pipeline/src/proraw.rs`, #613): base operator (BaselineExposure + Exposure), Highlights / Shadows on a Gaussian neighbourhood at 6.4 % of the long edge, Whites, Blacks, the 128-knot profile tone curve per channel (hue-preserving in linear ProPhoto), then Contrast adapting to the image's key. HDR keeps the chain through the midtones and lifts highlights past white (`camera_hdr_lift`). V1 to V16 keep the 32-knot camera curve on luminance; non-ProRAW photos and older offline smart previews without the curve render identically to V16. CPU and GPU share the stage tables and Highlights / Shadows curves. | +| **V17** | V16 plus: Apple ProRAW (Make `Apple` and a DNG `ProfileToneCurve`) renders its Light sliders through Lightroom Classic's fitted tone chain (`crates/pipeline/src/proraw.rs`, #613): base operator (BaselineExposure + Exposure), Highlights / Shadows on a Gaussian neighbourhood at 6.4 % of the long edge, Whites, Blacks, the 128-knot profile tone curve per channel (hue-preserving in linear ProPhoto), then Contrast adapting to the image's key. HDR keeps the chain through the midtones and lifts highlights past white (`camera_hdr_lift`). V1 to V16 keep the 32-knot camera curve on luminance; non-ProRAW photos and older offline smart previews without the curve render identically to V16. CPU and GPU share the stage tables and Highlights / Shadows curves. | +| **V18** (the latest) | V17 plus: Whites, the parametric curve and the point curves as Lightroom applies them ([curve-stage.md](curve-stage.md), `crates/pipeline/src/curve_stage.rs`), measured on Camera Raw renders of synthetic grey steps. Whites leaves the tone map (Apple ProRAW keeps Whites in V17's chain, and the stage then applies only the curves) and, with the parametric curve at Lightroom's default splits, comes from LightCraft's model fitted to those measurements (Whites reaches into the midtones; the regions are broad and add; moved splits keep the analytic model of V1 to V17); the master curve acts hue-preserving on sRGB-encoded linear ProPhoto RGB (largest and smallest channel through the curve, the middle one in proportion in linear light), then the red, green and blue curves per channel, between the calibrated Contrast and Blacks and the colour stage. V1 to V17 keep Whites in the tone map (Apple ProRAW from V17: in its own chain) and their per-channel curves on the output. CPU (`finish::finish_with`) and GPU (`finish.wgsl::curve_stage`) share the curve tables built from the model. With Whites, the parametric curve and the point curves neutral the curve stage does not run. | ## The rule @@ -134,6 +135,7 @@ extra field and retain their existing cached renders. No cache-version bump is n | Date | Change | Summary | |---|---|---| +| 2026-12-03 | minor | V18: Whites and the tone curves measured against Lightroom ([curve-stage.md](curve-stage.md)); V1 to V17 keep theirs | | 2026-12-03 | minor | V17: fitted Apple ProRAW tone chain (#613, #4196); V1 to V16 and non-ProRAW photos remain unchanged | | 2026-12-02 | minor | V16: a brush stroke's edge is feathered as one dab's is; V1 to V15 keep the accumulated soft edges | | 2026-11-24 | minor | V15: brush Flow per brush radius travelled, as in Lightroom Classic; V1 to V14 keep the flow per dab. 12 is no longer claimed | diff --git a/docs/whats-new.md b/docs/whats-new.md index 39d5cc7e927..5320c0bdedc 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -2,6 +2,13 @@ ## Unreleased +### Broader Whites and parametric curve, hue-preserving tone curves (process 18) +- Whites now reaches into the upper midtones, and the Highlights, Lights, Darks and Shadows regions of the + parametric curve are broader, overlap and add up when several are set. A contrast curve no longer turns orange + towards red: the point curve keeps colours' hue, and the red, green and blue curves act on their channel after it. + This is rendering process 18: new photos (and Reset) get it, photos you already edited keep their look until you + choose Photo ▸ Update to Current Process. See [Whites and the tone curves](curve-stage.md). + ### Apple ProRAW tone chain fitted to Lightroom (process 17) - On Apple ProRAW files with a profile tone curve, the Light sliders now run through a tone chain fitted to Lightroom Classic exports of an iPhone 12 Pro ProRAW, applying the profile curve to colour as well as brightness diff --git a/tools/lr_tone_charts.py b/tools/lr_tone_charts.py new file mode 100644 index 00000000000..4526334ba1e --- /dev/null +++ b/tools/lr_tone_charts.py @@ -0,0 +1,296 @@ +#!/usr/bin/env python3 +"""Measure Lightroom's Whites and parametric curve on synthetic grey steps (process V18, docs/curve-stage.md). + + python3 tools/lr_tone_charts.py charts OUT_DIR + Writes linear DNG charts (48 grey steps plus colour patches) with the settings embedded as XMP: + one neutral chart, Whites at +-25/50/100 and each parametric region at +-25/50/75/100 (default splits). + (render every DNG through Camera Raw to a 16-bit Adobe RGB (1998) TIFF with the same file name) + python3 tools/lr_tone_charts.py fit RENDER_DIR OUT_RS [CHART_DIR] + Reads the renders (and the charts' `curve__manifest.json` from CHART_DIR, by default RENDER_DIR), fits LightCraft's model of each setting to them and writes the model's constants + (`lightcraft_pipeline::curve_stage_model`). The measurements themselves are not written out. + +The charts are original test data generated here; nothing in them comes from Adobe. Only Camera Raw's output is +measured. Requires numpy, scipy and tifffile (tools/requirements-lr-tone-charts.txt). +""" +import json +import os +import struct +import sys + +import numpy as np + +W, H = 2400, 1600 +CELL = 60 +# linear sRGB -> XYZ (D65) inverse, stored as the DNG's ColorMatrix1 so the chart decodes as scene-linear sRGB +XYZ_TO_SRGB = [[3.2404542, -1.5371385, -0.4985314], [-0.969266, 1.8760108, 0.041556], [0.0556434, -0.2040259, 1.0572252]] +WHITES = (-100, -50, -25, 25, 50, 100) +REGIONS = ("Shadows", "Darks", "Lights", "Highlights") +REGION_AMOUNTS = (-100, -75, -50, -25, 25, 50, 75, 100) + + +def xmp(**settings): + """Camera Raw settings with everything else neutral (no sharpening, noise reduction, lens or vignette correction).""" + d = dict(CameraProfile="Embedded", WhiteBalance="As Shot", Exposure2012="0.00", Contrast2012="0", Highlights2012="0", + Shadows2012="0", Whites2012="0", Blacks2012="0", ToneCurveName2012="Linear", Sharpness="0", LuminanceSmoothing="0", + ColorNoiseReduction="0", LensProfileEnable="0", PostCropVignetteAmount="0", VignetteAmount="0", Texture="0", + Clarity2012="0", Dehaze="0", Vibrance="0", Saturation="0") + d.update({k: str(v) for k, v in settings.items()}) + attrs = " ".join(f'crs:{k}="{v}"' for k, v in d.items()) + return ('' + '').encode("utf8") + + +def write_dng(path, img, xm): + """A minimal linear (LinearRaw) DNG: `img` is scene-linear RGB 0..1, height x width x 3.""" + h, w = img.shape[:2] + px = (np.clip(img, 0, 1) * 65535 + 0.5).astype(" linear sRGB as the exact inverse of the sRGB primaries' matrix (the patches' colours) + x2s = np.linalg.inv(np.array([[0.4124564, 0.3575761, 0.1804375], [0.2126729, 0.7151522, 0.0721750], [0.0193339, 0.1191920, 0.9503041]])) + img = np.full((H, W, 3), 0.18) + patches = [] + + def put(c, **k): + """Place patch colour `c` in the next cell; a colour outside 0..1 is listed but left black.""" + i = len(patches) + x, y = (i % (W // CELL)) * CELL, (i // (W // CELL)) * CELL + ok = bool(np.all(c >= 0) and np.all(c <= 1)) + if ok: + img[y + 6:y + CELL - 6, x + 6:x + CELL - 6] = c + patches.append(dict(y=y + 6, x=x + 6, w=CELL - 12, h=CELL - 12, ok=ok, **k)) + + for g in np.geomspace(0.002, 1, 48): + put(np.array([g, g, g]), kind="grey", v=float(g)) + for lightness in (0.25, 0.4, 0.55, 0.7, 0.82, 0.92): + for chroma in (0.04, 0.08, 0.12): + for hue in range(0, 360, 15): + lab = np.array([lightness, chroma * np.cos(np.radians(hue)), chroma * np.sin(np.radians(hue))]) + put(x2s @ (m1i @ ((m2i @ lab) ** 3)), kind="colour", L=lightness, C=chroma, hue=hue) + return img, patches + + +def variants(): + """Name and XMP settings of every chart: neutral, each Whites amount, each region amount.""" + v = {"neutral": {}} + for a in WHITES: + v[f"whites{a:+d}"] = {"Whites2012": a} + for r in REGIONS: + for a in REGION_AMOUNTS: + v[f"par_{r.lower()}{a:+d}"] = {"Parametric" + r: a} + return v + + +# ---- measuring ---------------------------------------------------------------------------------------------- + +ADOBE_TO_XYZ = np.array([[0.5767309, 0.1855540, 0.1881852], [0.2973769, 0.6273491, 0.0752741], [0.0270343, 0.0706872, 0.9911085]]) +# XYZ (D65) -> linear ProPhoto RGB (D50, Bradford), as `RgbSpace::to_space` +XYZ_TO_PROPHOTO = (np.array([[1.3459433, -0.2556075, -0.0511118], [-0.5445989, 1.5081673, 0.0205351], [0.0, 0.0, 1.2118128]]) + @ np.array([[1.0478112, 0.0228866, -0.0501270], [0.0295424, 0.9904844, -0.0170491], + [-0.0092345, 0.0150436, 0.7521316]])) + + +def srgb_encode(v): + """Linear to sRGB-encoded values.""" + v = np.clip(v, 0, None) + return np.where(v <= 0.0031308, v * 12.92, 1.055 * v ** (1 / 2.4) - 0.055) + + +ADOBE_RGB_NAME = "Adobe RGB (1998)" + + +def read_render(path): + """A Camera Raw render as RGB 0..1, after checking it is the 16-bit Adobe RGB (1998) TIFF the fit assumes. + + Another export setting would still give plausible numbers, but wrong ones, so it is refused. + """ + import tifffile + with tifffile.TiffFile(path) as t: + page = t.pages[0] + icc = page.tags.get(34675) # InterColorProfile + profile = bytes(icc.value) if icc is not None else b"" + a = page.asarray() + if a.dtype != np.uint16 or a.ndim != 3 or a.shape[2] != 3: + raise SystemExit(f"{path}: expected a 16-bit RGB TIFF, got {a.dtype} {a.shape}") + # the profile's description: ASCII in ICC v2, UTF-16 in v4 + if not any(n in profile for n in (ADOBE_RGB_NAME.encode(), ADOBE_RGB_NAME.encode("utf-16-be"))): + raise SystemExit(f"{path}: expected an embedded {ADOBE_RGB_NAME} profile (export from Camera Raw in that colour space)") + return a.astype(np.float64) / 65535.0 + + +def grey_levels(path, patches): + """The grey steps of a Camera Raw render as sRGB-encoded linear ProPhoto values (the curve stage's domain).""" + a = read_render(path) + out = [] + for q in patches: + if q["kind"] != "grey" or not q["ok"]: + continue + rgb = a[q["y"] + 8:q["y"] + q["h"] - 8, q["x"] + 8:q["x"] + q["w"] - 8].reshape(-1, 3).mean(0) + xyz = ADOBE_TO_XYZ @ (np.clip(rgb, 0, 1) ** (563 / 256)) + out.append(srgb_encode((XYZ_TO_PROPHOTO @ xyz)[1])) + return np.array(out) + + +def delta_table(neutral, edited): + """Output minus input over 257 evenly spaced inputs, from matched grey steps; zero at both ends.""" + o = np.argsort(neutral) + x, y = neutral[o], np.maximum.accumulate(edited[o]) + grid = np.linspace(0, 1, 257) + d = np.interp(grid, x, y - x) + lo, hi = grid < x[0], grid > x[-1] + d[lo] = np.interp(grid[lo], [0, x[0]], [0, d[~lo][0]]) + d[hi] = np.interp(grid[hi], [x[-1], 1], [d[~hi][-1], 0]) + return d + + +# ---- fit ---------------------------------------------------------------------------------------------------- +# +# LightCraft's own model of each setting, fitted to the measured grey steps. Nothing measured is written out: only +# the model's constants. Per slider direction (negative, positive) the response (output minus input) is the sum of +# two bumps, each with a gain over the amount and a shape whose position and width change with the amount: +# +# t = |amount| / 100 +# response(x) = sum over the two bumps of (a1 t + a2 t^2 + a3 t^3) * bump(x, e^(p0 + p1 t), e^(q0 + q1 t)) +# bump(x, p, q) = (x / m)^p ((1 - x) / (1 - m))^q with m = p / (p + q): 0 at black and white, 1 at its peak m +# +# The fit keeps every response growing with the amount at every input, and never acting against the slider. + +FIT_SEED = 7 +FIT_STARTS = 16 +FIT_AMOUNTS = np.linspace(0, 1, 21) +GRID = np.linspace(0, 1, 257) + + +def bump(x, p, q): + """A bump of peak 1 at p / (p + q), 0 at black and white.""" + m = p / (p + q) + return np.exp(p * np.log(np.clip(x, 1e-12, 1) / m) + q * np.log(np.clip(1 - x, 1e-12, 1) / (1 - m))) + + +def response(params, t, x=GRID): + """The model's response of one slider direction at amount `t` (0..1) for inputs `x`.""" + out = 0.0 + for a1, a2, a3, p0, p1, q0, q1 in np.reshape(params, (2, 7)): + out = out + (a1 * t + a2 * t * t + a3 * t ** 3) * bump(x, np.exp(p0 + p1 * t), np.exp(q0 + q1 * t)) + return out + + +def fit_direction(amounts, deltas, sign): + """Fit one slider direction to its measured deltas (257 inputs each); returns the constants and the error.""" + from scipy.optimize import least_squares + rows = [(abs(a) / 100, d) for a, d in zip(amounts, deltas) if np.sign(a) == sign] + + def err(params): + """Error of the rendered curve in 8-bit levels, both sides clamped to 0..1 as the stage clamps.""" + return np.concatenate([(np.clip(GRID + response(params, t), 0, 1) - np.clip(GRID + d, 0, 1)) * 255 for t, d in rows]) + + def residual(params): + grow = np.array([sign * response(params, t) for t in FIT_AMOUNTS]) + return np.concatenate([err(params), 30 * 255 * np.minimum(np.diff(grow, axis=0), 0).ravel(), + 30 * 255 * np.minimum(grow, 0).ravel()]) + + rng = np.random.default_rng(FIT_SEED) + starts = [np.ravel([[sign * rng.uniform(0, 0.3), 0, 0, rng.uniform(-1.5, 2.5), 0, rng.uniform(-1.5, 2.5), 0] + for _ in range(2)]) for _ in range(FIT_STARTS)] + best = min((least_squares(residual, s, max_nfev=3000) for s in starts), key=lambda r: r.cost) + e = err(best.x) + return best.x, float(np.sqrt((e ** 2).mean())), float(np.abs(e).max()) + + +def fit(render_dir, out_rs, chart_dir=None): + """Fit the model to the Camera Raw renders in `render_dir` and write its constants to `out_rs`.""" + # the manifest carries the tool's prefix, as its charts do, so another chart tool's in the same folder is left alone + patches = json.load(open(os.path.join(chart_dir or render_dir, "curve__manifest.json")))["patches"] + tif = lambda n: os.path.join(render_dir, f"curve__{n}.tif") + n0 = grey_levels(tif("neutral"), patches) + rows = lambda names: [delta_table(n0, grey_levels(tif(n), patches)) for n in names] + sets = [("Whites", WHITES, rows([f"whites{a:+d}" for a in WHITES]))] + sets += [(r, REGION_AMOUNTS, rows([f"par_{r.lower()}{a:+d}" for a in REGION_AMOUNTS])) for r in REGIONS] + from concurrent.futures import ProcessPoolExecutor + jobs = [(name, sign, amounts, deltas) for name, amounts, deltas in sets for sign in (-1, 1)] + with ProcessPoolExecutor() as pool: + done = list(pool.map(fit_direction, *zip(*[(a, d, s) for _, s, a, d in jobs]))) + fitted = {} + for (name, sign, _, _), (params, rms, worst) in zip(jobs, done): + fitted[name, sign] = params + print(f"{name:10s} {'+' if sign > 0 else '-'} rms {rms:.2f} max {worst:.2f} (8-bit levels)") + num = lambda v: f"{v:.6e}" + resp = lambda name, sign: "[" + ", ".join("[" + ", ".join(num(v) for v in b) + "]" for b in np.reshape(fitted[name, sign], (2, 7))) + "]" + pair = lambda name: f"[{resp(name, -1)}, {resp(name, 1)}]" + s = ["// Written by `tools/lr_tone_charts.py fit`: LightCraft's model of Whites and the parametric regions, fitted to the", + "// tool's grey-step charts (provenance in docs/curve-stage.md). Constants of the model only.", + "", + "/// One bump of a response: `[a1, a2, a3, p0, p1, q0, q1]`, gain `a1 t + a2 t² + a3 t³` (t = |amount| / 100), shape", + "/// exponents `e^(p0 + p1 t)` and `e^(q0 + q1 t)` ([`crate::curve_stage`]).", + "pub type Bump = [f64; 7];", + "/// A slider direction's response: two bumps, added.", + "pub type Response = [Bump; 2];", + "", + "/// Whites: negative, positive.", + f"pub const WHITES: [Response; 2] = {pair('Whites')};", + "", + "/// Shadows, Darks, Lights, Highlights at the default splits (25, 50, 75): negative, positive.", + "pub const REGIONS: [[Response; 2]; 4] = [", + *[f" {pair(r)}," for r in REGIONS], + "];", + ""] + with open(out_rs, "w") as f: + f.write("\n".join(s)) + + +def main(): + """Command line: `charts OUT_DIR` or `fit RENDER_DIR OUT_RS [CHART_DIR]`.""" + if len(sys.argv) == 3 and sys.argv[1] == "charts": + out = sys.argv[2] + os.makedirs(out, exist_ok=True) + img, patches = chart() + json.dump(dict(patches=patches), open(os.path.join(out, "curve__manifest.json"), "w")) + for name, settings in variants().items(): + write_dng(os.path.join(out, f"curve__{name}.dng"), img, xmp(**settings)) + elif len(sys.argv) in (4, 5) and sys.argv[1] == "fit": + fit(*sys.argv[2:]) + else: + sys.exit(__doc__) + + +if __name__ == "__main__": + main() diff --git a/tools/requirements-lr-tone-charts.txt b/tools/requirements-lr-tone-charts.txt new file mode 100644 index 00000000000..8391b1cd899 --- /dev/null +++ b/tools/requirements-lr-tone-charts.txt @@ -0,0 +1,6 @@ +# Python packages for tools/lr_tone_charts.py (crates/pipeline/src/curve_stage_model.rs, docs/curve-stage.md). +# Needs Python 3.12 or newer (numpy 2.5); use a matching interpreter, e.g. python3.12 -m venv. +# python3.12 -m venv .venv-lr-tone && .venv-lr-tone/bin/pip install -r tools/requirements-lr-tone-charts.txt +numpy==2.5.4 +scipy==1.18.1 +tifffile==2026.11.8