diff --git a/README.md b/README.md index 42b164d6c64..6f872a67823 100644 --- a/README.md +++ b/README.md @@ -97,9 +97,9 @@ OkLCh, a modern perceptual colour space. ### ✨ Effects -**Texture** for fine detail, **Clarity** for mid-tone punch, **Dehaze** (dark-channel prior with guided refinement; -push it negative to add atmosphere), post-crop **Vignette** with highlight priority, roundness and feather, and -resolution-independent film **Grain** with size and roughness. +**Texture** for fine detail, **Clarity** for mid-tone punch, **Dehaze** (a guided dark-channel haze estimate of the +whole frame that clears haze without darkening the photo or crushing its shadows, #1237; push it negative for a soft veil), post-crop **Vignette** with +highlight priority, roundness and feather, and resolution-independent film **Grain** with size and roughness. ### πŸ“ˆ Tone Curve Parametric region curve with movable splits **plus** point curves for RGB, Red, Green and Blue. Curves are monotone by diff --git a/crates/develop/src/settings.rs b/crates/develop/src/settings.rs index a40f094c25f..4af2d9a06f1 100644 --- a/crates/develop/src/settings.rs +++ b/crates/develop/src/settings.rs @@ -84,17 +84,26 @@ pub enum Process { /// Highlights and Shadows keep the local contrast of the tones they move: their edge-aware base /// is taken of a fine median of log luminance (issue #632). V2, + /// Dehaze estimates haze from a patch-minimum dark channel, eases in, and never pushes a + /// pixel below a tenth of its darkest channel (issue #1237). + V3, + /// Dehaze estimates haze with a dark-channel prior on a fixed proxy of the whole frame (patch + /// minimum, guided refinement, colour airlight) and recovers it gently, so +25..+50 no longer + /// darkens the photo and crushes shadows (issue #1237). Without Dehaze it renders like V3. + V4, } impl Process { /// Every process, oldest first. - pub const ALL: [Process; 2] = [Process::V1, Process::V2]; - pub const LATEST: Process = Process::V2; + pub const ALL: [Process; 4] = [Process::V1, Process::V2, Process::V3, Process::V4]; + pub const LATEST: Process = Process::V4; pub const fn version(self) -> ProcessVersion { match self { Process::V1 => ProcessVersion(1), Process::V2 => ProcessVersion(2), + Process::V3 => ProcessVersion(3), + Process::V4 => ProcessVersion(4), } } } diff --git a/crates/develop/src/tests_process.rs b/crates/develop/src/tests_process.rs index f89ebfa1154..0d83942dd73 100644 --- a/crates/develop/src/tests_process.rs +++ b/crates/develop/src/tests_process.rs @@ -160,3 +160,25 @@ fn the_process_is_not_an_edit_nor_part_of_copied_settings() { /// A process other than the latest: a newer LightCraft's number (no older one than V1 exists). const LATEST_PLUS_ONE: u32 = ProcessVersion::LATEST.0 + 1; + +/// Issue #1237: V4 is the latest; settings saved on V2 stay V2 (outdated, not upgraded on load) and +/// round-trip as 2, V3 settings as 3, V4 settings as 4. +#[test] +fn v4_is_the_latest_and_v2_settings_stay_v2() { + assert_eq!(Process::LATEST, Process::V4); + assert_eq!(Process::ALL, [Process::V1, Process::V2, Process::V3, Process::V4]); + assert_eq!(Process::V3.version(), ProcessVersion(3)); + assert_eq!(Process::V4.version(), ProcessVersion(4)); + let v2 = DevelopSettings::from_json(&json!({"process": 2, "effects": {"dehaze": 30.0}})).unwrap(); + assert_eq!((v2.process, v2.process.process()), (ProcessVersion(2), Process::V2)); + assert!(v2.process.is_known() && v2.process.is_outdated()); + assert_eq!(v2.to_json()["process"], json!(2)); + let v3 = DevelopSettings { process: Process::V3.version(), ..v2.clone() }; + assert!(v3.process.is_known() && v3.process.is_outdated()); + assert_eq!(DevelopSettings::from_json(&v3.to_json()).unwrap().process.process(), Process::V3); + let v4 = DevelopSettings { process: Process::V4.version(), ..v2.clone() }; + assert!(v4.process.is_known() && !v4.process.is_outdated()); + assert_eq!(DevelopSettings::from_json(&v4.to_json()).unwrap().process.process(), Process::V4); + assert_ne!(v4.hash64(), v2.hash64(), "another process is another preview"); + assert_ne!(v4.hash64(), v3.hash64(), "another process is another preview"); +} diff --git a/crates/engine/src/tests_process.rs b/crates/engine/src/tests_process.rs index d101073ecfd..7ccf062b2ed 100644 --- a/crates/engine/src/tests_process.rs +++ b/crates/engine/src/tests_process.rs @@ -6,7 +6,7 @@ use std::sync::Arc; use lightcraft_catalog::{Photo, PhotoId, Source}; -use lightcraft_develop::{DevelopSettings, ProcessVersion}; +use lightcraft_develop::{DevelopSettings, Process, ProcessVersion}; use serde_json::json; use crate::{EngineError, Session}; @@ -262,3 +262,22 @@ fn update_to_current_process_checks_named_photos_not_the_selection() { // `ids: null` names nothing: the selection decides (and there is none) assert!(matches!(s.execute("develop.updateProcess", &json!({"ids": null})), Err(EngineError::Disabled(..)))); } + +/// Issue #1237: V4 (the new Dehaze) is the latest; photos edited on V1 and V2 move to it only with +/// Update to Current Process, keep their sliders, and undo puts each back on its own process. +#[test] +fn v1_and_v2_photos_update_to_v4() { + assert_eq!(ProcessVersion::LATEST, Process::V4.version()); + let mut s = Session::with_demo(); + let ids: Vec = s.visible_cloned().into_iter().take(3).collect(); + let (v1, v2) = (Process::V1.version(), Process::V2.version()); + put(&mut s, ids[0], v1, 0.5); + put(&mut s, ids[1], v2, -0.5); + select(&mut s, &ids); + let r = s.execute("develop.updateProcess", &json!({})).unwrap(); + assert_eq!(r, json!({"changed": 2, "process": 4})); + assert_eq!(ids.iter().map(|id| process(&s, *id)).collect::>(), [Process::V4.version(); 3]); + assert_eq!([s.develop_of(ids[0]).unwrap().light.exposure, s.develop_of(ids[1]).unwrap().light.exposure], [0.5, -0.5]); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!([process(&s, ids[0]), process(&s, ids[1]), process(&s, ids[2])], [v1, v2, Process::V4.version()]); +} diff --git a/crates/gpu/src/ctx.rs b/crates/gpu/src/ctx.rs index fb000c031e9..badab5f4626 100644 --- a/crates/gpu/src/ctx.rs +++ b/crates/gpu/src/ctx.rs @@ -22,6 +22,7 @@ const MODULES: &[Module] = &[ ("base_p", false, "f32"), ("clar", false, "f32"), ("tex", false, "f32"), + // V1 / V2: the dehaze dark plane; V4: the haze map's a / b coefficients (`HAS_HAZE`) ("dark", false, "f32"), ("masks", false, "f32"), ("aux", false, "f32"), @@ -32,7 +33,7 @@ const MODULES: &[Module] = &[ Module { src: include_str!("wgsl/blur.wgsl"), bindings: &[("src", false, "f32"), ("dst", true, "f32")], - entries: &["box_h", "box_v", "median_h", "median_v"], + entries: &["box_h", "box_v", "median_h", "median_v", "min_h", "min_v"], }, Module { src: include_str!("wgsl/resize.wgsl"), @@ -259,6 +260,24 @@ fn constants() -> String { use lightcraft_pipeline::masks::{AUTO_TOL_CHROMA, AUTO_TOL_EV}; s += &format!("const AUTO_TOL_EV: f32 = {AUTO_TOL_EV:?};\nconst AUTO_TOL_CHROMA: f32 = {AUTO_TOL_CHROMA:?};\n"); s += &format!("const SHADOW_TINT_K: f32 = {:?};\n", lightcraft_pipeline::colorops::SHADOW_TINT); + { + use lightcraft_pipeline::haze as hz; + for (name, v) in [ + ("HZ_AIR_FLOOR", hz::AIR_FLOOR), + ("HZ_G_MAX", hz::G_MAX), + ("HZ_OMEGA", hz::OMEGA), + ("HZ_OMEGA_POWER", hz::OMEGA_POWER), + ("HZ_T_FLOOR", hz::T_FLOOR), + ("HZ_SKY_K", hz::SKY_K), + ("HZ_CHROMA_KEEP", hz::CHROMA_KEEP), + ("HZ_VEIL", hz::VEIL), + ("HZ_VEIL_BASE", hz::VEIL_BASE), + ("HZ_VEIL_TOP", hz::VEIL_TOP), + ] { + s += &format!("const {name}: f32 = {v:?};\n"); + } + s += &format!("const HZ_COMP_N: u32 = {}u;\n", hz::COMP_N); + } for (i, h) in GRAIN_HASH.iter().enumerate() { s += &format!("const GRAIN_H{i}: u32 = {h}u;\n"); } diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index 7efae6a5763..37384761ac9 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -443,6 +443,20 @@ pub fn stage_bytes(stages: &StageCache) -> usize { } } +/// Process V4 haze maps a view's GPU stages (kept with its [`StageCache`]) uploaded so far: one +/// per map, not one per render (a diagnostic); 0 when it has none. +pub fn haze_uploads(stages: &StageCache) -> u64 { + #[cfg(not(target_arch = "wasm32"))] + { + stages.peek_extension::().map(|g| g.haze_uploads()).unwrap_or(0) + } + #[cfg(target_arch = "wasm32")] + { + let _ = stages; + 0 + } +} + /// Render `src` with `s` on the GPU, reusing the device-resident stages kept with `stages` (the /// view's CPU stage cache). `None`: render on the CPU instead. [`try_render`] also says why. pub fn render(src: &Arc, info: &SourceInfo, s: &DevelopSettings, req: &RenderRequest, stages: Option<&StageCache>) -> Option { diff --git a/crates/gpu/src/params.rs b/crates/gpu/src/params.rs index 7f9405492c4..266f284aea5 100644 --- a/crates/gpu/src/params.rs +++ b/crates/gpu/src/params.rs @@ -4,6 +4,7 @@ use lightcraft_develop::VignetteStyle; use lightcraft_pipeline::colorops::POINT_WORDS; use lightcraft_pipeline::finish::{FinishParams, MASK_TERMS, srgb_lut}; +use lightcraft_pipeline::haze::{COMP_N, HazeMap}; /// Entries per tone-curve table (`lightcraft_pipeline::finish` builds them at this size). pub const CURVE_N: u32 = 1024; @@ -26,12 +27,20 @@ const FIELDS: &[(&str, usize)] = &[ ("CLAR", 1), ("TEX", 1), ("DEHAZE", 1), + ("DEHAZE_V3", 1), ("SHARPEN", 1), ("SHARPEN_MASK", 1), ("HAS_CLAR", 1), ("HAS_TEX", 1), ("HAS_DARK", 1), ("HAS_CHROMA", 1), + // process V4's haze map (`lightcraft_pipeline::haze`): its a / b proxy (interleaved) is bound + // in place of the V1 / V2 dark plane, which V4 doesn't compute + ("HAS_HAZE", 1), + ("HAZE_W", 1), + ("HAZE_H", 1), + ("HAZE_AIR", 3), + ("HAZE_COMP", COMP_N), ("OPS_IDENTITY", 1), ("VIBRANCE", 1), ("SATURATION", 1), @@ -57,7 +66,8 @@ const FIELDS: &[(&str, usize)] = &[ ("VIG_POWER", 1), ("VIG_HL", 1), ("VIG_STYLE", 1), - // the window's offset in the whole output and the whole output's size (pixels) + // the window's offset in the whole output and the whole output's size (pixels; the vignette + // and V4's haze map read it) ("VIG_VIEW", 4), ("GRAIN", 1), ("GRAIN_AMT", 1), @@ -139,8 +149,9 @@ pub struct Present { } /// The `finish` kernel's parameter block and auxiliary table (tone LUT | chroma curve | sRGB LUT | curve LUTs | -/// mask terms) for `fp` with `masks` (their local adjustments' terms). -pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Present) -> (Vec, Vec) { +/// mask terms) for `fp` with `masks` (their local adjustments' terms) and, for process V4's Dehaze, +/// `haze`, the map whose coefficients ([`haze_coeffs`]) are bound in the `dark` slot. +pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Present, haze: Option<&HazeMap>) -> (Vec, Vec) { let mut aux: Vec = fp.tone.lut().to_vec(); aux.extend_from_slice(fp.tone.chroma_lut()); let srgb_off = aux.len(); @@ -175,12 +186,22 @@ pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Pr p.f("CLAR", fp.clar); p.f("TEX", fp.tex); p.f("DEHAZE", fp.dehaze); + p.b("DEHAZE_V3", fp.dehaze_v3); p.f("SHARPEN", fp.sharpen); p.f("SHARPEN_MASK", fp.sharpen_mask); p.b("HAS_CLAR", present.clarity); p.b("HAS_TEX", present.texture); p.b("HAS_DARK", present.dark); p.b("HAS_CHROMA", present.chroma); + p.fs("VIG_VIEW", &fp.view); + if let Some(m) = haze { + let (w, h) = m.size(); + p.b("HAS_HAZE", true); + p.u("HAZE_W", w as u32); + p.u("HAZE_H", h as u32); + p.fs("HAZE_AIR", &m.air); + p.fs("HAZE_COMP", &m.comp); + } let ops = &fp.ops; p.b("OPS_IDENTITY", ops.is_identity()); @@ -213,7 +234,6 @@ pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Pr p.f("VIG_ASPECT_MIX", v.aspect_mix); p.f("VIG_POWER", v.power); p.f("VIG_HL", v.highlights); - p.fs("VIG_VIEW", &fp.view); p.u( "VIG_STYLE", match v.style { @@ -246,3 +266,9 @@ pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Pr } (p.0, aux) } + +/// The haze map's guided-filter coefficients, interleaved `a, b` per proxy pixel (row-major), as +/// the `finish` kernel samples them. +pub fn haze_coeffs(m: &HazeMap) -> Vec { + m.a.data.iter().zip(&m.b.data).flat_map(|(a, b)| [*a, *b]).collect() +} diff --git a/crates/gpu/src/render.rs b/crates/gpu/src/render.rs index b747e0d327f..6a2bb691ea4 100644 --- a/crates/gpu/src/render.rs +++ b/crates/gpu/src/render.rs @@ -8,6 +8,7 @@ use lightcraft_develop::DevelopSettings; use lightcraft_geom::Orientation; use lightcraft_pipeline::finish::{FinishParams, MASK_TERMS, mask_terms}; use lightcraft_pipeline::geometry::SampleMode; +use lightcraft_pipeline::haze::HazeMap; use lightcraft_pipeline::local::plane_at; use lightcraft_pipeline::{Plan, RenderRequest, Rendered, SourceInfo, local}; use lightcraft_raster::resample::Filter; @@ -23,10 +24,31 @@ pub struct GpuStages { entries: Mutex>, /// The uploaded source (a view renders one photo at several sizes). source: Mutex, Arc)>>, + /// The uploaded coefficients of process V4's haze map (the map is cached per photo on the + /// CPU; a tone drag must not upload them again on every tick). + haze: Mutex, Arc)>>, + /// Haze maps uploaded so far (diagnostics and tests). + haze_uploads: std::sync::atomic::AtomicU64, } const CAPACITY: usize = 2; +/// The device copy of `of` kept in `slot`: the one there when it was uploaded from this very `of`, +/// else a fresh upload (the previous buffer freed first) that replaces it. Also returns whether +/// it uploaded. +fn upload_once(slot: &Mutex, Arc)>>, of: &Arc, upload: impl FnOnce() -> Buf) -> (Arc, bool) { + let mut g = slot.lock().unwrap_or_else(|e| e.into_inner()); + if let Some((k, b)) = &*g + && Arc::ptr_eq(k, of) + { + return (b.clone(), false); + } + *g = None; // free the previous buffer first + let b = Arc::new(upload()); + *g = Some((of.clone(), b.clone())); + (b, true) +} + #[derive(Clone)] struct Entry { src: Arc, @@ -44,7 +66,7 @@ struct Planes { base: Option<(local::BaseKey, Arc)>, clarity: Option<(u32, Arc)>, texture: Option<(u32, Arc)>, - dark: Option<(u32, Arc, f32)>, + dark: Option<(u64, Arc, f32)>, chroma: Option<(u32, Arc)>, } @@ -63,16 +85,21 @@ impl GpuStages { } fn source(&self, src: &Arc, upload: impl FnOnce() -> Buf) -> Arc { - let mut g = self.source.lock().unwrap_or_else(|e| e.into_inner()); - match &*g { - Some((s, b)) if Arc::ptr_eq(s, src) => b.clone(), - _ => { - *g = None; // free the previous photo's buffer first - let b = Arc::new(upload()); - *g = Some((src.clone(), b.clone())); - b - } + upload_once(&self.source, src, upload).0 + } + + /// The device copy of `map`'s coefficients, uploaded only when the map changes. + fn haze(&self, map: &Arc, upload: impl FnOnce() -> Buf) -> Arc { + let (b, uploaded) = upload_once(&self.haze, map, upload); + if uploaded { + self.haze_uploads.fetch_add(1, std::sync::atomic::Ordering::Relaxed); } + b + } + + /// Haze maps these stages uploaded so far. + pub fn haze_uploads(&self) -> u64 { + self.haze_uploads.load(std::sync::atomic::Ordering::Relaxed) } fn lock(&self) -> std::sync::MutexGuard<'_, Vec> { @@ -110,6 +137,9 @@ impl GpuStages { if let Some((_, b)) = &*self.source.lock().unwrap_or_else(|e| e.into_inner()) { add(b); } + if let Some((_, b)) = &*self.haze.lock().unwrap_or_else(|e| e.into_inner()) { + add(b); + } total } @@ -117,6 +147,7 @@ impl GpuStages { pub fn clear(&self) { self.lock().clear(); *self.source.lock().unwrap_or_else(|e| e.into_inner()) = None; + *self.haze.lock().unwrap_or_else(|e| e.into_inner()) = None; } pub fn is_empty(&self) -> bool { @@ -331,6 +362,19 @@ fn median_hv(cx: &mut Cx<'_>, p: &Buf, w: usize, h: usize, r: usize) -> Buf { out } +/// Separable minimum of a plane (`local::min_hv`). +fn min_hv(cx: &mut Cx<'_>, p: Buf, w: usize, h: usize, r: usize) -> Buf { + if r == 0 || w * h == 0 { + return p; + } + let pr = [w as u32, h as u32, 1, r.min(local::DEHAZE_PATCH_MAX) as u32]; + let tmp = cx.gpu.buffer(w * h); + cx.run("min_h", &pr, &[Some(&p), Some(&tmp)], groups2(w, h, [16, 16])); + let out = cx.gpu.buffer(w * h); + cx.run("min_v", &pr, &[Some(&tmp), Some(&out)], groups2(w, h, [16, 16])); + out +} + /// The highlights/shadows base (`local::tone_base`; `detail` 0: V1, no median). fn tone_base(cx: &mut Cx<'_>, l: &Buf, w: usize, h: usize, sigma: f32, detail: usize) -> Buf { if detail == 0 { @@ -678,8 +722,20 @@ pub fn render( dark: prep.dark.is_some(), chroma: masks.is_some() && prep.chroma.is_some(), }; - let (p, aux) = finish_block(&fp, &terms, &present); + // process V4's Dehaze: the whole frame's haze map (built on the CPU with the plan, so no + // airlight readback), its coefficients bound where V1 / V2 bind the dark plane + let haze_map = plan.haze.as_ref().filter(|_| prep.dark.is_none()); + let haze = haze_map.map(|m| &**m); + let (p, aux) = finish_block(&fp, &terms, &present, haze); let aux = gpu.upload(&aux); + // (kept with the view's stages: uploaded once per map, not on every tick) + let haze_buf = haze_map.map(|m| { + let upload = || gpu.upload(&crate::params::haze_coeffs(m)); + match stages { + Some(c) => c.haze(m, upload), + None => Arc::new(upload()), + } + }); // cleared, so that work which never ran cannot pass for an image (see the check below) let out = cx.zeroed(n); if fault == Some(crate::Fault::Validation) { @@ -701,7 +757,7 @@ pub fn render( Some(&prep.base), prep.clarity.as_deref(), prep.texture.as_deref(), - prep.dark.as_deref(), + prep.dark.as_deref().or(haze_buf.as_deref()), masks.as_ref(), Some(&aux), Some(&out), @@ -882,10 +938,11 @@ fn prepare(cx: &mut Cx<'_>, lin: &Buf, plan: &Plan<'_>, req: &RenderRequest, pla let (dark, air) = match sig.dark { None => (None, 1.0), Some(sg) => match &planes.dark { - Some((k, d, air)) if *k == sg.to_bits() => (Some(d.clone()), *air), + Some((k, d, air)) if *k == local::dark_key(sg, sig.dark_patch) => (Some(d.clone()), *air), _ => { let d0 = cx.gpu.buffer(n); map(cx, "dark_k", n, &[], [Some(lin), None, None], &d0); + let d0 = min_hv(cx, d0, w, h, sig.dark_patch); let d = gaussian(cx, &d0, w, h, 1, sg); // airlight: a percentile of every 7th value, as on the CPU let m = n.div_ceil(local::AIRLIGHT_STEP); @@ -894,7 +951,7 @@ fn prepare(cx: &mut Cx<'_>, lin: &Buf, plan: &Plan<'_>, req: &RenderRequest, pla let air = local::airlight_of(cx.read(&sub, m)); cx.flush(); let b = Arc::new(d); - planes.dark = Some((sg.to_bits(), b.clone(), air)); + planes.dark = Some((local::dark_key(sg, sig.dark_patch), b.clone(), air)); (Some(b), air) } }, diff --git a/crates/gpu/src/wgsl/blur.wgsl b/crates/gpu/src/wgsl/blur.wgsl index 375fb6d5503..0f803d7f382 100644 --- a/crates/gpu/src/wgsl/blur.wgsl +++ b/crates/gpu/src/wgsl/blur.wgsl @@ -129,3 +129,40 @@ fn median_v(@builtin(global_invocation_id) g: vec3) { } dst[g.y * w + g.x] = median_of(n, r, &v); } + +// Separable minimum of a single-channel plane (`lightcraft_pipeline::local::min_hv`): 2r+1 taps +// (clamped to the image) along a row (min_h) or a column (min_v). P: w, h, nc (unused), r. +@compute @workgroup_size(16, 16) +fn min_h(@builtin(global_invocation_id) g: vec3) { + let w = pu(0u); + let h = pu(1u); + let r = pu(3u); + if (g.x >= w || g.y >= h) { + return; + } + let row = g.y * w; + let a = select(0u, g.x - r, g.x >= r); + let b = min(g.x + r, w - 1u); + var m = src[row + a]; + for (var x = a + 1u; x <= b; x++) { + m = min(m, src[row + x]); + } + dst[row + g.x] = m; +} + +@compute @workgroup_size(16, 16) +fn min_v(@builtin(global_invocation_id) g: vec3) { + let w = pu(0u); + let h = pu(1u); + let r = pu(3u); + if (g.x >= w || g.y >= h) { + return; + } + let a = select(0u, g.y - r, g.y >= r); + let b = min(g.y + r, h - 1u); + var m = src[a * w + g.x]; + for (var y = a + 1u; y <= b; y++) { + m = min(m, src[y * w + g.x]); + } + dst[g.y * w + g.x] = m; +} diff --git a/crates/gpu/src/wgsl/finish.wgsl b/crates/gpu/src/wgsl/finish.wgsl index d51308ee0e0..8a9098c1248 100644 --- a/crates/gpu/src/wgsl/finish.wgsl +++ b/crates/gpu/src/wgsl/finish.wgsl @@ -1,5 +1,6 @@ // The per-pixel stage: a straight port of `lightcraft_pipeline::finish` (keep in step with it). -// Bindings: img (rgb, pre-exposure), log_l, base, clar, tex, dark, masks (NMASK planes, then the +// Bindings: img (rgb, pre-exposure), log_l, base, clar, tex, dark (V1 / V2: the dehaze dark plane; +// V4: the haze map's interleaved a / b coefficients), masks (NMASK planes, then the // blurred chromaticity when HAS_CHROMA), aux // (tone LUT | chroma curve | sRGB LUT | curve LUTs | mask terms), out (packed RGBA8). @@ -252,6 +253,171 @@ fn out_encode(v: f32) -> f32 { return 1.099 * pow(l, 0.45) - 0.099; } +// --- process V4's Dehaze: `lightcraft_pipeline::haze::dehaze_at` with the whole frame's haze map +// (its a / b coefficients interleaved in `dark`, airlight and compensation LUT in `P`). + +fn hz_finite(v: f32) -> bool { + return abs(v) <= 3.40282347e38; +} + +// `haze::encode` / `haze::decode` (the square-root encoding: square root and square) +fn hz_encode(v: f32) -> f32 { + if (hz_finite(v) && v > 0.0) { + return sqrt(v); + } + return 0.0; +} + +fn hz_decode(v: f32) -> f32 { + if (hz_finite(v) && v > 0.0) { + return v * v; + } + return 0.0; +} + +fn hz_air() -> vec3 { + return vec3(pf(F_HAZE_AIR), pf(F_HAZE_AIR + 1u), pf(F_HAZE_AIR + 2u)); +} + +// `HazeMap::air_lin` (the airlight is finite and at least HZ_AIR_FLOOR: `decode` is its square) +fn hz_air_lin() -> vec3 { + let a = hz_air(); + return a * a; +} + +fn hz_pos(v: f32) -> f32 { + if (hz_finite(v) && v > 0.0) { + return v; + } + return 0.0; +} + +// `haze::norm_dark_lin` (`inv`: `haze::inv_air_lin`) +fn hz_norm_dark_lin(lin: vec3, inv: vec3) -> f32 { + let r = min(min(hz_pos(lin.x) * inv.x, hz_pos(lin.y) * inv.y), hz_pos(lin.z) * inv.z); + let g = hz_encode(r); + if (hz_finite(g)) { + return clamp(g, 0.0, HZ_G_MAX); + } + return 0.0; +} + +// `haze::Axis::new`: (i0, i1, f) of frame-normalised `n` over `len` (β‰₯ 1) proxy pixels. +fn hz_axis(n0: f32, len: u32) -> vec3 { + var n = n0; + if (!hz_finite(n)) { + n = 0.5; + } + let p = clamp(n * f32(len) - 0.5, 0.0, f32(len - 1u)); + let i0 = floor(p); + return vec3(i0, min(i0 + 1.0, f32(len - 1u)), p - i0); +} + +fn hz_at(x: u32, y: u32, w: u32) -> vec2 { + let j = 2u * (y * w + x); + return vec2(dark[j], dark[j + 1u]); +} + +// `HazeMap::coeffs`: (a, b) bilinear over the proxy's pixel centres, the two rows blended first, +// then the two columns (HAS_HAZE is only set with a map, and a map is at least 1Γ—1). +fn hz_coeffs(nx: f32, ny: f32) -> vec2 { + let w = pu(F_HAZE_W); + let h = pu(F_HAZE_H); + let ax = hz_axis(nx, w); + let ay = hz_axis(ny, h); + let x0 = u32(ax.x); + let x1 = u32(ax.y); + let y0 = u32(ay.x); + let y1 = u32(ay.y); + let left = hz_at(x0, y0, w) + (hz_at(x0, y1, w) - hz_at(x0, y0, w)) * ay.z; + let right = hz_at(x1, y0, w) + (hz_at(x1, y1, w) - hz_at(x1, y0, w)) * ay.z; + return left + (right - left) * ax.z; +} + +// `HazeMap::comp`: the exposure compensation at amount `k`. +fn hz_comp_at(j: u32) -> f32 { + if (j == 0u) { + return 1.0; + } + return pf(F_HAZE_COMP + j - 1u); +} + +fn hz_comp(k: f32) -> f32 { + if (!(k > 0.0)) { + return 1.0; + } + let f = clamp(min(k, 1.0) * f32(HZ_COMP_N), 0.0, f32(HZ_COMP_N)); + let i = u32(floor(f)); + let lo = hz_comp_at(i); + let hi = hz_comp_at(min(i + 1u, HZ_COMP_N)); + return lo + (hi - lo) * (f - f32(i)); +} + +// `haze::dehaze_at` (with `haze::Ctx` and `haze::Amount` computed per pixel): `c` is the exposed +// colour, `gain` (> 0) the exposure gain; returns the dehazed colour. +fn hz_dehaze(nx: f32, ny: f32, c: vec3, gain: f32, k0: f32) -> vec3 { + var k = 0.0; + if (hz_finite(k0)) { + k = clamp(k0, -1.0, 1.0); + } + if (k == 0.0) { + return c; + } + let lin = c * (1.0 / gain); + let air = hz_air(); + let air_lin = hz_air_lin(); + let ab = hz_coeffs(nx, ny); + var d = ab.x * hz_norm_dark_lin(lin, 1.0 / max(air_lin, vec3(HZ_AIR_FLOOR * HZ_AIR_FLOOR))) + ab.y; + if (hz_finite(d)) { + d = clamp(d, 0.0, 1.0); + } else { + d = 0.0; + } + // `haze::recover_with` + let air_g = air_lin * gain; + var j = c; + if (k > 0.0) { + let omega = HZ_OMEGA * pow(k, HZ_OMEGA_POWER); + let tmin = 1.0 + (HZ_T_FLOOR - 1.0) * k; + var t = max(1.0 - omega * hz_decode(d), tmin); + // sky weight (`haze::Ctx::sky_distance`, `haze::sky_weight_at`) + let top = max(max(max(HZ_AIR_FLOOR, air.x), air.y), air.z); + let e = vec3(hz_encode(lin.x), hz_encode(lin.y), hz_encode(lin.z)); + let de = abs(e - air); + let m = max(max(max(0.0, de.x), de.y), de.z) * (1.0 / top); + var w = 1.0; + if (hz_finite(m)) { + w = sstep(0.0, HZ_SKY_K, m); + } + t = clamp(t / max(t + (1.0 - t) * w, 1e-6), HZ_T_FLOOR, 1.0); + j = max(air_g + (c - air_g) * (1.0 / t), vec3(0.0)); + // `haze::finish_recovery`: exposure compensation (weighted by the sky weight), some of + // the input's chroma back + j = j * (1.0 + (hz_comp(k) - 1.0) * w); + let yj = lum2020(j); + let yc = lum2020(c); + if (yj > 1e-9 && yc > 1e-9) { + let s = yj / yc; + j = j + (c * s - j) * HZ_CHROMA_KEEP; + } + } else { + // veil toward the airlight, mixed in a square-root encoding + let t = 1.0 - HZ_VEIL * -k * (HZ_VEIL_BASE + (1.0 - HZ_VEIL_BASE) * d); + // toward the airlight scaled to at most HZ_VEIL_TOP (`haze::veil_air`) + let top = max(max(air_lin.x, air_lin.y), air_lin.z); + var vs = 1.0; + if (top > HZ_VEIL_TOP) { + vs = HZ_VEIL_TOP / top; + } + let r = sqrt(max(c, vec3(0.0))) * t + sqrt(max(air_lin * vs * gain, vec3(0.0))) * (1.0 - t); + j = r * r; + } + if (hz_finite(j.x) && hz_finite(j.y) && hz_finite(j.z)) { + return j; + } + return c; +} + @compute @workgroup_size(16, 16) fn main(@builtin(global_invocation_id) gid: vec3) { let w = pu(F_W); @@ -323,10 +489,25 @@ fn main(@builtin(global_invocation_id) gid: vec3) { // --- dehaze (scene linear) let dz = pf(F_DEHAZE) + lt[10]; - if (dz != 0.0 && pu(F_HAS_DARK) != 0u) { + if (dz != 0.0 && pu(F_HAS_HAZE) != 0u) { + // V4: the whole frame's haze map, sampled where this pixel sits in the whole output frame + // (a window dehazes like the whole render) + let nx = (pf(F_VIG_VIEW) + f32(x) + 0.5) / pf(F_VIG_VIEW + 2u); + let ny = (pf(F_VIG_VIEW + 1u) + f32(y) + 0.5) / pf(F_VIG_VIEW + 3u); + if (gain > 0.0 && hz_finite(gain)) { + c = hz_dehaze(nx, ny, c, gain, dz); + } + } else if (dz != 0.0 && pu(F_HAS_DARK) != 0u) { let d = clamp(dark[i] / pf(F_AIR_PRE), 0.0, 1.0); let air = pf(F_AIR); - if (dz > 0.0) { + if (dz > 0.0 && pu(F_DEHAZE_V3) != 0u) { + // process V3 (`finish::dehaze_v3_pixel`) + let k0 = clamp(dz, 0.0, 1.0); + let k = k0 * (0.4 + 0.6 * k0); + let t = max(1.0 - 0.95 * k * d, 0.3); + let veil = min(air * (1.0 - t), 0.9 * max(min(c.x, min(c.y, c.z)), 0.0)); + c = max((c - veil) / t, vec3(0.0)); + } else if (dz > 0.0) { let t = max(1.0 - 0.95 * min(dz, 1.0) * d, 0.12); c = max((c - air * (1.0 - t)) / t, vec3(0.0)); } else { diff --git a/crates/gpu/tests/equivalence.rs b/crates/gpu/tests/equivalence.rs index c877e3d9d81..921644a67a7 100644 --- a/crates/gpu/tests/equivalence.rs +++ b/crates/gpu/tests/equivalence.rs @@ -216,8 +216,36 @@ fn cases() -> Vec<(&'static str, Edit)> { s.grain.size = 40.0; s.grain.roughness = 60.0; }), + // (the default process is V4; V1 / V2 / V3 keep their dark-plane Dehaze and airlight readback) ("dehaze -", |s| s.effects.dehaze = -50.0), ("dehaze +", |s| s.effects.dehaze = 60.0), + ("dehaze - (V2)", |s| { + s.process = Process::V2.version(); + s.effects.dehaze = -50.0; + }), + ("dehaze + (V2)", |s| { + s.process = Process::V2.version(); + s.effects.dehaze = 60.0; + }), + ("typical (V1)", |s| { + s.process = Process::V1.version(); + typical(s); + }), + ("dehaze -100", |s| s.effects.dehaze = -100.0), + ("dehaze +100", |s| s.effects.dehaze = 100.0), + ("dehaze in a mask, past +100", |s| { + s.effects.dehaze = 50.0; + s.masks = vec![Mask { + components: vec![MaskComponent { + name: None, + op: MaskOp::Add, + invert: false, + shape: MaskShape::Radial { center: Point::new(0.5, 0.4), rx: 0.35, ry: 0.25, angle: 0.0, feather: 50.0, invert: false }, + }], + adjust: lightcraft_develop::LocalAdjustments { dehaze: 80.0, ..Default::default() }, + ..Default::default() + }]; + }), ("clarity/texture -", |s| { s.effects.clarity = -60.0; s.effects.texture = -40.0; @@ -605,7 +633,7 @@ fn highlights_shadows_base_matches_on_every_process() { }]; check(&format!("{p:?} local highlights {w}"), &src, &raw, &s, &req); } - for p in [Process::V1, Process::V2, Process::V1, Process::V2] { + for p in [Process::V1, Process::V2, Process::V3, Process::V4, Process::V1, Process::V4, Process::V3, Process::V2] { let mut s = DevelopSettings { process: p.version(), ..DevelopSettings::default() }; s.light.highlights = -100.0; let warm = lightcraft_gpu::render(&src, &raw, &s, &req, Some(&cache)).expect("gpu"); @@ -779,6 +807,112 @@ fn tint_directions_match_cpu_for_raw_and_rendered_sources() { } } +/// Issue #1237: process V4's Dehaze (the whole frame's haze map, sampled by frame-normalised +/// position) on the hazy valley, at every amount, through masks (added to the slider and clamped to +/// Β±100), exposed, and in windows of a zoomed frame; V1 / V2's Dehaze still matches too. +#[test] +fn v4_dehaze_matches() { + if !gpu() { + return; + } + use lightcraft_pipeline::PixelWindow; + let src = Arc::new(lightcraft_scenes::hazy_valley(1200, 800)); + let rendered = SourceInfo::default(); + let raw = SourceInfo { raw: true, ..Default::default() }; + let whole = RenderRequest::fit(900, 900); + let mask = |dehaze: f64, invert: bool| Mask { + components: vec![MaskComponent { + name: None, + op: MaskOp::Add, + invert, + shape: MaskShape::Linear { start: Point::new(0.5, 0.2), end: Point::new(0.5, 0.7) }, + }], + adjust: lightcraft_develop::LocalAdjustments { dehaze, ..Default::default() }, + ..Default::default() + }; + let mut worst = (0.0f64, 0u8); + let mut run = |name: String, s: &DevelopSettings, info: &SourceInfo, req: &RenderRequest| { + let (m, x) = check(&name, &src, info, s, req); + worst = (worst.0.max(m), worst.1.max(x)); + }; + for amount in [-100.0, -50.0, -25.0, 25.0, 50.0, 100.0] { + let mut s = DevelopSettings { process: Process::V4.version(), ..DevelopSettings::default() }; + s.effects.dehaze = amount; + run(format!("V4 dehaze {amount}"), &s, &rendered, &whole); + run(format!("V4 dehaze {amount} raw"), &s, &raw, &whole); + s.light.exposure = 0.7; + run(format!("V4 dehaze {amount} exposed"), &s, &rendered, &whole); + typical(&mut s); + s.effects.dehaze = amount; + run(format!("V4 dehaze {amount} typical"), &s, &raw, &whole); + } + // masks: alone, added to the slider, and past Β±100 (clamped) + for (global, local, invert) in [(0.0, 60.0, false), (40.0, 40.0, true), (70.0, 90.0, false), (-60.0, -80.0, false), (50.0, -50.0, true)] { + let mut s = DevelopSettings { process: Process::V4.version(), ..DevelopSettings::default() }; + s.effects.dehaze = global; + s.masks = vec![mask(local, invert)]; + run(format!("V4 dehaze {global} + mask {local}"), &s, &rendered, &whole); + } + // the Effects section off: only the masks' Dehaze + let mut s = DevelopSettings { process: Process::V4.version(), ..DevelopSettings::default() }; + s.effects.dehaze = 80.0; + s.masks = vec![mask(50.0, false)]; + s.disabled_sections.push("effects".into()); + run("V4 dehaze, effects off, mask 50".into(), &s, &rendered, &whole); + // windows of a zoomed frame sample the whole frame's map + let windows = [ + PixelWindow { x: 0, y: 0, w: 640, h: 480 }, + PixelWindow { x: 1100, y: 700, w: 640, h: 480 }, + PixelWindow { x: 2360, y: 1520, w: 640, h: 480 }, + ]; + for win in windows { + let req = RenderRequest { window: Some(win), ..RenderRequest::fit(3000, 2000) }; + for amount in [-60.0, 35.0, 100.0] { + let mut s = DevelopSettings { process: Process::V4.version(), ..DevelopSettings::default() }; + s.effects.dehaze = amount; + run(format!("V4 dehaze {amount} window {},{}", win.x, win.y), &s, &rendered, &req); + s.masks = vec![mask(40.0, false)]; + run(format!("V4 dehaze {amount} + mask window {},{}", win.x, win.y), &s, &rendered, &req); + } + } + // V1 / V2 keep their own Dehaze on the GPU + for p in [Process::V1, Process::V2] { + for amount in [-60.0, 60.0] { + let mut s = DevelopSettings { process: p.version(), ..DevelopSettings::default() }; + s.effects.dehaze = amount; + run(format!("{p:?} dehaze {amount}"), &s, &rendered, &whole); + s.masks = vec![mask(40.0, false)]; + let req = RenderRequest { window: Some(windows[1]), ..RenderRequest::fit(3000, 2000) }; + run(format!("{p:?} dehaze {amount} + mask window"), &s, &rendered, &req); + } + } + eprintln!("worst: mean {:.4} LSB, max {} LSB", worst.0, worst.1); +} + +/// A tone drag on a V4-dehazed photo uploads the haze map's coefficients once, not on every tick; +/// a change the map depends on (white balance) uploads the new one. +#[test] +fn v3_haze_map_is_uploaded_once_per_map() { + if !gpu() { + return; + } + let src = Arc::new(lightcraft_scenes::hazy_valley(1210, 790)); + let info = SourceInfo::default(); + let req = RenderRequest::fit(900, 900); + let stages = StageCache::default(); + let mut s = DevelopSettings { process: Process::V4.version(), ..DevelopSettings::default() }; + s.effects.dehaze = 50.0; + for ev in [0.0, 0.2, 0.4, 0.6] { + s.light.exposure = ev; + lightcraft_gpu::render(&src, &info, &s, &req, Some(&stages)).expect("gpu render"); + } + assert_eq!(lightcraft_gpu::haze_uploads(&stages), 1, "one upload for four exposure ticks"); + s.wb.mode = WbMode::Custom; + s.wb.temp = 4000.0; + lightcraft_gpu::render(&src, &info, &s, &req, Some(&stages)).expect("gpu render"); + assert_eq!(lightcraft_gpu::haze_uploads(&stages), 2, "another map, another upload"); +} + /// Issue #323: windows of a zoomed frame. The GPU renders the window like the CPU does: the /// vignette and airlight belong to the whole frame, spots grow the window they work on. #[test] diff --git a/crates/pipeline/examples/dehaze_report.rs b/crates/pipeline/examples/dehaze_report.rs new file mode 100644 index 00000000000..bd3b9e853e5 --- /dev/null +++ b/crates/pipeline/examples/dehaze_report.rs @@ -0,0 +1,143 @@ +//! Measure Dehaze (issue #1237): for every process this build knows and Dehaze βˆ’100, βˆ’50, 0, +25, +//! +50, +100, print the median luminance shift, how many pixels clip to black, the width of the +//! dark halo at a bright/dark edge, the hue of a neutral grey patch and what a flat grey image does. +//! +//! `cargo run --release -p lightcraft-pipeline --example dehaze_report -- [--size 1200] [--out DIR] [image…]` +//! +//! `--out DIR` also writes each input's renders as PNGs (`-v-.png`) and a +//! 3Γ—2 contact sheet per process (`-v-sheet.png`: βˆ’100, βˆ’50, 0 / +25, +50, +100). +//! +//! Inputs: the procedural hazy valley (`lightcraft_scenes::hazy_valley`, which also has the edge +//! and grey patch), two misty demo scenes, and any sRGB PNG/JPEG paths given (e.g. CC0 corpus +//! photos); edge, grey and flat-grey figures need the valley's known layout, so they are only +//! printed for it. +use lightcraft_color::{REC2020, SRGB}; +use lightcraft_develop::{DevelopSettings, Process}; +use lightcraft_pipeline::{RenderRequest, SourceInfo, render}; +use lightcraft_raster::{Rgb32f, Rgba8}; +use lightcraft_scenes::haze::{black_pct, grey_lch, halo_widths, hue_diff, median_luma}; +use lightcraft_scenes::{Kind, demo_library, hazy_valley}; + +const AMOUNTS: [f64; 6] = [-100.0, -50.0, 0.0, 25.0, 50.0, 100.0]; + +fn main() { + let mut size = 1200usize; + let mut paths = Vec::new(); + let mut out: Option = None; + let mut args = std::env::args().skip(1); + while let Some(a) = args.next() { + if a == "--out" { + out = args.next().map(Into::into); + } else if a == "--size" { + size = args.next().and_then(|v| v.parse().ok()).unwrap_or(size).max(64); + } else { + paths.push(a); + } + } + + let (w, h) = (size, size * 2 / 3); + let mut inputs: Vec<(String, Rgb32f, bool)> = vec![("hazy valley".into(), hazy_valley(w, h), true)]; + for s in demo_library().into_iter().filter(|s| s.kind == Kind::MistyForest) { + inputs.push((format!("demo: {}", s.name), s.render_fit(size), false)); + } + for p in &paths { + match load_srgb(p, size) { + Ok(img) => inputs.push((p.clone(), img, false)), + Err(e) => eprintln!("skipping {p}: {e}"), + } + } + + for (name, src, layout) in &inputs { + println!("\n== {name} ({}Γ—{}) ==", src.width, src.height); + for process in Process::ALL { + println!("-- process V{} --", process.version().0); + println!( + "{:>7} {:>9} {:>8} {:>9} {:>10} {:>9} {:>9} {:>7} {:>6} {:>7} {:>9}", + "amount", "med luma", "EV", "black %", "Ξ”black %", "halo dk", "halo br", "grey L", "C*", "hΒ°", "Ξ”h vs+25" + ); + let renders: Vec<(f64, Rgba8)> = AMOUNTS.iter().map(|&a| (a, develop(src, process, a))).collect(); + if let Some(dir) = &out { + save(dir, name, process, &renders); + } + let Some((_, base)) = renders.iter().find(|(a, _)| *a == 0.0) else { continue }; + let base_med = median_luma(base); + let base_black = black_pct(base); + let hue25 = renders.iter().find(|(a, _)| *a == 25.0).map(|(_, r)| grey_lch(r)[2]); + for (amount, r) in &renders { + let med = median_luma(r); + let ev = (med.max(1e-4) / base_med.max(1e-4)).log2(); + let black = black_pct(r); + let mut line = format!("{:>+7.0} {:>9.1} {:>+8.2} {:>9.1} {:>+10.1}", amount, encode(med) * 255.0, ev, black, black - base_black); + if *layout { + let (dk, br) = halo_widths(r); + let [l, c, hue] = grey_lch(r); + let dh = hue25.map_or(f32::NAN, |h25| hue_diff(hue, h25)); + line += &format!(" {dk:>9.1} {br:>9.1} {l:>7.1} {c:>6.2} {hue:>7.1} {dh:>+9.1}"); + } + println!("{line}"); + } + } + } + + println!("\n== flat grey (0.18), max |Ξ”| vs Dehaze 0, 8-bit =="); + let flat = Rgb32f::filled(300, 200, [0.18; 3]); + for process in Process::ALL { + let base = develop(&flat, process, 0.0); + let diffs: Vec = AMOUNTS + .iter() + .map(|&a| { + let r = develop(&flat, process, a); + let d = r.data.iter().zip(&base.data).map(|(p, q)| (0..3).map(|i| p[i].abs_diff(q[i])).max().unwrap_or(0)).max().unwrap_or(0); + format!("{a:+.0}: {d}") + }) + .collect(); + println!("V{} {}", process.version().0, diffs.join(" ")); + } +} + +/// Writes every render and a 3Γ—2 sheet of them (half size) into `dir`. +fn save(dir: &std::path::Path, name: &str, process: Process, renders: &[(f64, Rgba8)]) { + let stem: String = name.chars().map(|c| if c.is_ascii_alphanumeric() { c.to_ascii_lowercase() } else { '-' }).collect(); + let stem = format!("{}-v{}", stem.trim_matches('-'), process.version().0); + let to_image = |r: &Rgba8| image::RgbaImage::from_fn(r.width as u32, r.height as u32, |x, y| image::Rgba(r.get(x as usize, y as usize))); + let Some((_, first)) = renders.first() else { return }; + let (tw, th) = ((first.width / 2) as u32, (first.height / 2) as u32); + let mut sheet = image::RgbaImage::from_pixel(tw * 3, th * 2, image::Rgba([0, 0, 0, 255])); + for (i, (amount, r)) in renders.iter().enumerate() { + let img = to_image(r); + if let Err(e) = img.save(dir.join(format!("{stem}-{amount:+.0}.png"))) { + eprintln!("cannot save: {e}"); + } + let small = image::imageops::resize(&img, tw, th, image::imageops::FilterType::Triangle); + image::imageops::replace(&mut sheet, &small, i64::from((i as u32 % 3) * tw), i64::from((i as u32 / 3) * th)); + } + if let Err(e) = sheet.save(dir.join(format!("{stem}-sheet.png"))) { + eprintln!("cannot save the sheet: {e}"); + } +} + +fn develop(src: &Rgb32f, process: Process, amount: f64) -> Rgba8 { + let mut s = DevelopSettings { process: process.version(), ..DevelopSettings::default() }; + s.effects.dehaze = amount; + render(src, &SourceInfo::default(), &s, &RenderRequest::fit(src.width, src.height)).image +} + +fn encode(v: f32) -> f32 { + lightcraft_color::transfer::linear_to_srgb(v.clamp(0.0, 1.0)) +} + +/// An sRGB PNG/JPEG as linear Rec.2020, fitted within `size` on the long edge. +fn load_srgb(path: &str, size: usize) -> Result { + let img = image::open(path)?; + let img = img.resize(size as u32, size as u32, image::imageops::FilterType::Triangle).to_rgb32f(); + let to2020 = SRGB.to_space(&REC2020); + let (w, h) = (img.width() as usize, img.height() as usize); + let data = img + .pixels() + .map(|p| { + let c = p.0.map(lightcraft_color::transfer::srgb_to_linear); + to2020.apply_f32(c).map(|v| v.max(0.0)) + }) + .collect(); + Ok(Rgb32f { width: w, height: h, data }) +} diff --git a/crates/pipeline/src/finish.rs b/crates/pipeline/src/finish.rs index eb65d51a2b9..7aa246b5b5b 100644 --- a/crates/pipeline/src/finish.rs +++ b/crates/pipeline/src/finish.rs @@ -111,6 +111,23 @@ pub const MASK_TERMS: usize = 21; /// Number of alpha-weighted terms at the start of [`mask_terms`]. pub const MASK_SUMS: usize = 17; +/// Positive dehaze from process V3 (#1237) of scene-linear `c`: `dz` the strength (0..1, with a +/// local adjustment's added), `d` the dark channel over the airlight (0..1), `air` the airlight. +/// The strength eases in (`dzΒ·(0.4 + 0.6Β·dz)`: +10 acts at about half V1's), the transmission is +/// floored at 0.3 (channel differences grow at most ~3x, so +100 adds no colour casts), and the +/// veil removed never exceeds 90 % of the pixel's darkest channel, so no +/// pixel is pushed to black (V1 clipped shadows next to bright sky from +10). The GPU mirrors it in +/// `finish.wgsl`. Sources: He, Sun, Tang, "Single Image Haze Removal Using Dark Channel Prior" +/// (CVPR 2009), with own easing and veil limit. +#[inline] +pub fn dehaze_v3_pixel(c: [f32; 3], dz: f32, d: f32, air: f32) -> [f32; 3] { + let k = dz.clamp(0.0, 1.0); + let k = k * (0.4 + 0.6 * k); + let t = (1.0 - 0.95 * k * d).max(0.3); + let veil = (air * (1.0 - t)).min(0.9 * c[0].min(c[1]).min(c[2]).max(0.0)); + c.map(|v| ((v - veil) / t).max(0.0)) +} + /// A mask's local adjustments as the per-pixel stage uses them (alpha-weighted sums), in order: /// exposure, temp, tint, contrast, highlights, shadows, whites, blacks, texture, clarity, dehaze, /// saturation, hue, sharpness, noise, moirΓ©, defringe, then the colour overlay: on (0/1), cos and @@ -174,6 +191,8 @@ pub struct FinishParams { pub clar: f32, pub tex: f32, pub dehaze: f32, + /// Dehaze's process-V3 response ([`dehaze_v3_pixel`]) instead of V1's. + pub dehaze_v3: bool, pub sharpen: f32, pub sharpen_mask: f32, /// Airlight after and before exposure, exposure gain and EV (see [`crate::Prepared`]). @@ -243,6 +262,7 @@ impl FinishParams { clar, tex, dehaze, + dehaze_v3: matches!(s.process.process(), Process::V3), sharpen: (s.detail.sharpen_amount / 150.0) as f32, sharpen_mask: (s.detail.sharpen_masking / 100.0) as f32, air: air_pre * gain, @@ -280,8 +300,8 @@ impl FinishParams { pub fn base_tone(s: &DevelopSettings, info: &SourceInfo, peak: f32) -> ToneMap { let l = &s.light; match s.process.process() { - // V2 changes the Highlights/Shadows base (`local::tone_base`), not the tone map - Process::V1 | Process::V2 => match info.camera_tone.as_ref().filter(|_| info.raw) { + // V2 changes the Highlights/Shadows base (`local::tone_base`) and V3 and V4 Dehaze, not the tone map + Process::V1 | Process::V2 | Process::V3 | Process::V4 => match info.camera_tone.as_ref().filter(|_| info.raw) { Some(curve) => ToneMap::camera_hdr(curve, l.contrast, l.whites, l.blacks, peak), None if info.raw => ToneMap::hdr(l.contrast, l.whites, l.blacks, peak), None => ToneMap::display_hdr(l.contrast, l.whites, l.blacks, peak), @@ -377,6 +397,7 @@ pub(crate) fn finish_with( clar, tex, dehaze, + dehaze_v3, sharpen, sharpen_mask, air, @@ -386,6 +407,7 @@ pub(crate) fn finish_with( grain, .. } = fp; + let dehaze_v3 = *dehaze_v3; let (hl, sh, clar, tex, dehaze, sharpen, sharpen_mask, air, air_pre, gain, ev) = (*hl, *sh, *clar, *tex, *dehaze, *sharpen, *sharpen_mask, *air, *air_pre, *gain, *ev); let terms: Vec<[f32; MASK_TERMS]> = p.masks.iter().map(|m| mask_terms(&m.adjust)).collect(); @@ -398,8 +420,37 @@ pub(crate) fn finish_with( let srgb = srgb_lut(); let peak = fp.peak; let hdr = peak > 1.0; + // V4 Dehaze's per-render values: the map's context at this exposure, the global amount's + // (pixels with mask Dehaze compute their own) and where each output column samples the map + let haze = p.haze.as_ref().and_then(|m| Some((crate::haze::Ctx::new(m, gain)?, crate::haze::Amount::new(m, dehaze)))); + let haze_cols: Vec = match (&p.haze, &haze) { + (Some(m), Some(_)) => (0..w).map(|x| m.column((vx + x as f32 + 0.5) / vw)).collect(), + _ => Vec::new(), + }; let mut out = vec![T::default(); w * h]; for_rows(&mut out, w, |y, row| { + // the map's two proxy rows around this output row, blended once (on the first pixel that + // dehazes) + let mut haze_row: Option = None; + // V4 Dehaze at the global amount of each pixel of the row as the main loop would see it + // without masks (`raw Β· gain`), in a tight pass of its own: its square roots and divisions + // then overlap from pixel to pixel, which they can't inside the long loop below (about + // twice as fast). Pixels whose colour or amount masks change dehaze in the loop. + let haze_pre: Vec<[f32; 3]> = match (&p.haze, &haze) { + (Some(map), Some((ctx, global))) if dehaze != 0.0 => { + let hr = haze_row.insert(map.row((vy + y as f32 + 0.5) / vh)); + let src = p.img.data.get(y * w..(y + 1) * w).unwrap_or(&[]); + src.iter() + .zip(&haze_cols) + .map(|(raw, col)| { + let c = if gain == 1.0 { *raw } else { raw.map(|v| v * gain) }; + let (a, b) = hr.coeffs(col); + crate::haze::dehaze_at(ctx, global, a, b, c) + }) + .collect() + } + _ => Vec::new(), + }; for (x, px) in row.iter_mut().enumerate() { let i = y * w + x; let raw = p.img.data[i]; @@ -425,6 +476,8 @@ pub(crate) fn finish_with( let [l_exp, l_temp, l_tint, l_con, l_hl, l_sh, l_wh, l_bl, l_tex, l_clar, l_dehaze, l_sat, l_hue, l_sharp, l_noise, l_moire, l_defringe] = l; + // (whether a mask changed the colour before Dehaze: `haze_pre` doesn't hold it then) + let mut recoloured = false; // --- local MoirΓ© (and the colour part of Noise): chromaticity towards its blur let mt = (l_moire + 0.5 * l_noise.max(0.0)).clamp(-1.0, 1.0); if mt != 0.0 @@ -432,6 +485,7 @@ pub(crate) fn finish_with( { let (y, ch0, cb) = (luminance_2020(c), crate::masks::chromaticity(raw), cb.data[i]); c = std::array::from_fn(|k| ((ch0[k] + (cb[k] - ch0[k]) * mt) * y).max(0.0)); + recoloured = true; } // --- local Defringe: desaturate purple / green fringes along edges let df = l_defringe.clamp(0.0, 1.0); @@ -442,16 +496,35 @@ pub(crate) fn finish_with( if k > 0.0 { let y = luminance_2020(c); c = c.map(|v| v + (y - v) * k); + recoloured = true; } } // --- dehaze (scene linear) let dz = dehaze + l_dehaze; if dz != 0.0 + && let Some(map) = &p.haze + { + // V4: the whole frame's haze map, sampled where this pixel sits in the whole + // output frame (a window dehazes like the whole render) + if l_dehaze == 0.0 + && !recoloured + && let Some(pre) = haze_pre.get(x) + { + c = *pre; + } else if let Some((ctx, global)) = &haze { + let hr = haze_row.get_or_insert_with(|| map.row((vy + y as f32 + 0.5) / vh)); + let (a, b) = haze_cols.get(x).map_or((0.0, 0.0), |col| hr.coeffs(col)); + let am = if l_dehaze == 0.0 { *global } else { crate::haze::Amount::new(map, dz) }; + c = crate::haze::dehaze_at(ctx, &am, a, b, c); + } + } else if dz != 0.0 && let Some(dark) = &p.dark { let d = (dark.data[i] / air_pre).clamp(0.0, 1.0); - if dz > 0.0 { + if dz > 0.0 && dehaze_v3 { + c = dehaze_v3_pixel(c, dz, d, air); + } else if dz > 0.0 { let t = (1.0 - 0.95 * dz.min(1.0) * d).max(0.12); c = c.map(|v| ((v - air * (1.0 - t)) / t).max(0.0)); } else { diff --git a/crates/pipeline/src/haze.rs b/crates/pipeline/src/haze.rs new file mode 100644 index 00000000000..0c63145c9ed --- /dev/null +++ b/crates/pipeline/src/haze.rs @@ -0,0 +1,931 @@ +//! The haze map of process V4's Dehaze (issue #1237): a dark-channel-prior estimate of how much of +//! each pixel is haze, computed once per image on a fixed-size proxy of the whole frame. +//! +//! Every render of the photo (any preview size, a zoomed window, the export, the GPU) samples the +//! same map by frame-normalised coordinates, so they all dehaze alike and none needs a margin or a +//! mid-render airlight readback. +//! +//! Built on a proxy of the whole output frame, long edge `P = min(`[`PROXY_EDGE`]`, native)`, after +//! white balance (before exposure), in the gamma encoding `e = √lin` (scale-invariant: the map +//! doesn't change with Exposure): +//! 1. airlight `A`: the per-channel median of the top [`AIR_TOP`] of the patch dark channel, +//! leaving out the brightest [`AIR_SKIP_BRIGHT`] of the frame (the sun, clipped highlights), +//! pulled [`AIR_NEUTRAL`] of the way toward neutral and floored at [`AIR_FLOOR`] (`A'`); +//! 2. normalised dark `g = min_c(e_c / A'_c)` (0..[`G_MAX`]), also the guide; +//! 3. patch dark channel `d = minfilter(g, `[`PATCH`]`Β·P)` ([`lightcraft_raster::morph`]); +//! 4. guided refinement of `d` by `g` ([`GUIDE_RADIUS`]`Β·P`, [`GUIDE_EPS`]), keeping the +//! coefficients `a`, `b` at proxy resolution: a full-resolution pixel's haze is +//! `dΜƒ = clamp(aΒ·g_px + b, 0, 1)` with its own `g_px`, so edges stay sharp at any size; +//! 5. an exposure-compensation LUT ([`COMP_N`] amounts): how much the recovery darkens the median +//! at each amount, so Dehaze clears haze without making the photo darker. +//! +//! [`dehaze_at`] is the per-pixel V4 Dehaze the CPU renderer applies with it (the GPU's `finish` +//! kernel mirrors it). + +use std::sync::{Arc, Mutex}; + +use lightcraft_color::luminance_2020; +use lightcraft_develop::{DevelopSettings, Process}; +use lightcraft_raster::{Plane, Rgb32f}; + +use crate::SourceInfo; +use crate::geometry::Frame; + +/// Long edge (px) of the proxy the map is built on (smaller frames use their own size). +pub const PROXY_EDGE: usize = 768; +/// Share of the patch dark channel (its brightest end) the airlight is picked from. +pub const AIR_TOP: f32 = 0.001; +/// Share of the brightest pixels (the sun, its glare, clipped highlights) left out of the airlight. +pub const AIR_SKIP_BRIGHT: f32 = 0.01; +/// How far the airlight is pulled toward a neutral of its own luminance (0 = as picked). +pub const AIR_NEUTRAL: f32 = 0.7; +/// Lowest airlight channel (encoded): no division by zero, no runaway gain on dark photos. +pub const AIR_FLOOR: f32 = 0.05; +/// Upper clamp of the normalised dark `g`. +pub const G_MAX: f32 = 1.5; +/// Patch (min filter) radius as a fraction of the proxy's long edge. +pub const PATCH: f32 = 0.012; +/// Guided refinement radius as a fraction of the proxy's long edge (Gaussian windows with the +/// spread of a box of this radius: `Οƒ = r/√3`). +pub const GUIDE_RADIUS: f32 = 0.05; +/// Guided refinement epsilon (in units of `gΒ²`). +pub const GUIDE_EPS: f32 = 1e-3; +/// Entries of the exposure-compensation LUT: amounts `0.05, 0.10, …, 1.0`. +pub const COMP_N: usize = 20; +/// Largest exposure compensation before the [`COMP_POWER`] (EV). +pub const COMP_MAX_EV: f32 = 1.4; +/// Share (as a power) of the measured median darkening the compensation gives back. +pub const COMP_POWER: f32 = 0.55; +/// The compensation LUT measures every `COMP_STEP`-th proxy pixel. +pub const COMP_STEP: usize = 7; + +/// Haze strength at +100: `Ο‰ = OMEGAΒ·k^OMEGA_POWER`. +pub const OMEGA: f32 = 0.95; +pub const OMEGA_POWER: f32 = 0.6; +/// Lowest transmission at +100 (`t β‰₯ lerp(1, T_FLOOR, k)`): bounds the gain at `1/T_FLOOR`. +pub const T_FLOOR: f32 = 0.35; +/// Sky tolerance: pixels within this of the airlight (encoded, per channel, relative to its brightest +/// channel) are recovered less. +pub const SKY_K: f32 = 0.3; +/// Share of the input's chromaticity blended back after recovery (keeps colours from swinging). +pub const CHROMA_KEEP: f32 = 0.5; +/// Negative Dehaze: veil strength at βˆ’100 and the share of it that doesn't depend on the haze. +pub const VEIL: f32 = 0.45; +pub const VEIL_BASE: f32 = 0.4; +/// Brightest channel (linear, pre-exposure) of the colour the veil mixes toward: the airlight, +/// scaled down when brighter, so a veil over a bright sky or sun doesn't clip it to white. +pub const VEIL_TOP: f32 = 1.0; + +/// The haze map of one photo (see the module docs). Frame-normalised: [`Self::coeffs`] takes +/// coordinates in 0..1 over the whole output frame. +#[derive(Clone, Debug, PartialEq)] +pub struct HazeMap { + /// Guided-filter coefficients at proxy resolution: `dΜƒ = clamp(aΒ·g + b, 0, 1)`. + pub a: Plane, + pub b: Plane, + /// Airlight `A'` in the square-root encoding ([`encode`]), every channel β‰₯ [`AIR_FLOOR`]. + pub air: [f32; 3], + /// Exposure compensation (a gain β‰₯ 1) at amounts `0.05Β·(i+1)`. + pub comp: [f32; COMP_N], +} + +/// The square-root encoding the map works in (`√lin`; cheap per pixel on the CPU and the GPU); +/// non-finite and negative values encode as 0. +#[inline] +pub fn encode(v: f32) -> f32 { + if v.is_finite() && v > 0.0 { v.sqrt() } else { 0.0 } +} + +/// Inverse of [`encode`] (`vΒ²`). +#[inline] +pub fn decode(v: f32) -> f32 { + if v.is_finite() && v > 0.0 { v * v } else { 0.0 } +} + +fn encode3(c: [f32; 3]) -> [f32; 3] { + c.map(encode) +} + +/// `1 / max(A_lin, AIR_FLOORΒ²)` of the encoded airlight `air`: what [`norm_dark_lin`] multiplies by. +fn inv_air_lin(air: [f32; 3]) -> [f32; 3] { + air.map(|a| 1.0 / decode(a).max(AIR_FLOOR * AIR_FLOOR)) +} + +/// Normalised dark `min_c(e_c / A_c)` of a linear pixel, clamped to 0..[`G_MAX`] (0 for NaN), with +/// `inv` = [`inv_air_lin`]. It encodes once instead of three times: the encoding is monotonic, so +/// `min_c(e_c / A_c) = √min_c(lin_c / A_lin_c)`. +#[inline] +fn norm_dark_lin(lin: [f32; 3], inv: [f32; 3]) -> f32 { + // (written without short-circuits so the per-pixel path has no branches: a NaN or infinite + // channel reads as 0, and `r β‰₯ 0` is never NaN; it overflows to +∞ only for a huge pixel, + // which `encode` reads as 0) + let pos = |v: f32| if v > 0.0 && v < f32::INFINITY { v } else { 0.0 }; + let r = (pos(lin[0]) * inv[0]).min(pos(lin[1]) * inv[1]).min(pos(lin[2]) * inv[2]); + if r < f32::INFINITY { r.sqrt().min(G_MAX) } else { 0.0 } +} + +/// One axis of the bilinear sampling: `(i0, i1, f)` of frame-normalised `n` (outside 0..1, the +/// edge's; NaN, the middle) over `len` proxy pixel centres. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Axis { + i0: usize, + i1: usize, + f: f32, +} + +impl Axis { + pub fn new(n: f32, len: usize) -> Axis { + let last = len.saturating_sub(1); + let n = if n.is_finite() { n } else { 0.5 }; + let p = (n * len as f32 - 0.5).clamp(0.0, last as f32); + let i0 = p.floor() as usize; + Axis { i0, i1: (i0 + 1).min(last), f: p - i0 as f32 } + } + + /// `v0` to `v1` by `f`. + #[inline] + fn mix(&self, v0: f32, v1: f32) -> f32 { + v0 + (v1 - v0) * self.f + } + + /// `v[i0]` to `v[i1]` by `f` (0 outside `v`). + #[inline] + fn lerp(&self, v: &[f32]) -> f32 { + let at = |i: usize| v.get(i).copied().unwrap_or(0.0); + self.mix(at(self.i0), at(self.i1)) + } +} + +/// The map's coefficients `a`, `b` blended between two proxy rows ([`HazeMap::row`]): one output +/// row's vertical half of the bilinear sampling, done once per row instead of once per pixel. +#[derive(Clone, Debug, Default)] +pub struct HazeRow { + a: Vec, + b: Vec, +} + +impl HazeRow { + /// The coefficients `(a, b)` at the column `x` ([`Axis::new`] of the pixel's `nx` over the + /// proxy width): [`HazeMap::coeffs`] with this row's `ny`. + #[inline] + pub fn coeffs(&self, x: &Axis) -> (f32, f32) { + (x.lerp(&self.a), x.lerp(&self.b)) + } +} + +impl HazeMap { + /// The map of `img`: the white-balanced (linear, pre-exposure) proxy of the whole frame. + pub fn build(img: &Rgb32f) -> HazeMap { + let (w, h) = (img.width, img.height); + if w == 0 || h == 0 || img.data.len() != w.saturating_mul(h) { + return HazeMap::empty(); + } + let long = w.max(h) as f32; + let r = ((PATCH * long).round() as usize).max(1); + let e = img.map(encode3); + // 1. airlight + let dark = crate::timed("haze dark", || lightcraft_raster::morph::min_filter(&e.map(crate::local::dark_of), r)); + let picked = crate::timed("haze air", || haze_colour(&e, &dark)).unwrap_or([1.0; 3]); + let y = luminance_2020(picked); + let air = picked.map(|c| { + let v = c + (y - c) * AIR_NEUTRAL; + if v.is_finite() { v.max(AIR_FLOOR) } else { 1.0 } + }); + // 2.-4. normalised dark, patch minimum, guided refinement + let inv = inv_air_lin(air); + let g = img.map(|p| norm_dark_lin(p, inv)); + let d = lightcraft_raster::morph::min_filter(&g, r); + let sigma = (GUIDE_RADIUS * long / 3f32.sqrt()).max(1.0); + let (a, b) = crate::timed("haze guided", || crate::masks::guided_cross_coeffs(&g, &d, sigma, GUIDE_EPS)); + let sane = |p: Plane| p.map(|v| if v.is_finite() { v } else { 0.0 }); + let mut map = HazeMap { a: sane(a), b: sane(b), air, comp: [1.0; COMP_N] }; + // 5. exposure compensation + map.comp = crate::timed("haze comp", || map.measure_comp(img, &e, &g)); + map + } + + /// A map that finds no haze anywhere (for an empty image). + fn empty() -> HazeMap { + HazeMap { a: Plane::new(1, 1), b: Plane::new(1, 1), air: [1.0; 3], comp: [1.0; COMP_N] } + } + + /// Bytes the map holds (its coefficient planes and itself). + pub fn bytes(&self) -> usize { + (self.a.data.len() + self.b.data.len()) * std::mem::size_of::() + std::mem::size_of::() + } + + /// Proxy size (px). + pub fn size(&self) -> (usize, usize) { + (self.a.width, self.a.height) + } + + /// [`Self::air`] in linear light (pre-exposure). + pub fn air_lin(&self) -> [f32; 3] { + self.air.map(decode) + } + + /// The column [`Axis`] of frame-normalised `nx` (0..1 over the whole output frame). + pub fn column(&self, nx: f32) -> Axis { + Axis::new(nx, self.a.width) + } + + /// The coefficients blended between the two proxy rows around frame-normalised `ny` (0..1 over + /// the whole output frame): [`HazeRow::coeffs`] then samples any column of it. + pub fn row(&self, ny: f32) -> HazeRow { + let (w, h) = self.size(); + let y = Axis::new(ny, h); + let rows = |p: &Plane| -> Vec { + let row = |i: usize| p.data.get(i.saturating_mul(w)..i.saturating_add(1).saturating_mul(w)).unwrap_or(&[]); + row(y.i0).iter().zip(row(y.i1)).map(|(v0, v1)| y.mix(*v0, *v1)).collect() + }; + HazeRow { a: rows(&self.a), b: rows(&self.b) } + } + + /// The coefficients `(a, b)` at frame-normalised point `(nx, ny)` (0..1 over the whole output + /// frame; outside, the edge's), bilinear over proxy pixel centres: the two rows blended first, + /// then the two columns, exactly like [`Self::row`] + [`HazeRow::coeffs`] and the GPU. + pub fn coeffs(&self, nx: f32, ny: f32) -> (f32, f32) { + let (w, h) = self.size(); + let (x, y) = (Axis::new(nx, w), Axis::new(ny, h)); + let at = |p: &Plane, xi: usize, yi: usize| p.data.get(yi.saturating_mul(w).saturating_add(xi)).copied().unwrap_or(0.0); + let bil = |p: &Plane| { + let col = |xi: usize| y.mix(at(p, xi, y.i0), at(p, xi, y.i1)); + x.mix(col(x.i0), col(x.i1)) + }; + (bil(&self.a), bil(&self.b)) + } + + /// Exposure compensation (gain β‰₯ 1) at amount `k` (linear between the LUT's entries; 1 at 0 and + /// for negative amounts). + pub fn comp(&self, k: f32) -> f32 { + if k.is_nan() || k <= 0.0 { + return 1.0; + } + let f = (k.min(1.0) * COMP_N as f32).clamp(0.0, COMP_N as f32); + let i = f.floor() as usize; + let at = |j: usize| if j == 0 { 1.0 } else { self.comp.get(j - 1).copied().unwrap_or(1.0) }; + let (lo, hi) = (at(i), at((i + 1).min(COMP_N))); + lo + (hi - lo) * (f - i as f32) + } + + /// The compensation LUT: for each amount, the ratio of the median luminance before and after + /// the recovery (every [`COMP_STEP`]-th proxy pixel), clamped to `1..2^COMP_MAX_EV` and raised + /// to [`COMP_POWER`]. + fn measure_comp(&self, img: &Rgb32f, e: &Rgb32f, g: &Plane) -> [f32; COMP_N] { + let Some(ctx) = Ctx::new(self, 1.0) else { + return [1.0; COMP_N]; + }; + let samples: Vec<([f32; 3], f32, f32)> = img + .data + .iter() + .zip(&e.data) + .zip(g.data.iter().zip(self.a.data.iter().zip(&self.b.data))) + .step_by(COMP_STEP) + .map(|((c, ev), (gv, (a, b)))| { + (c.map(|v| if v.is_finite() { v.max(0.0) } else { 0.0 }), (a * gv + b).clamp(0.0, 1.0), ctx.sky_distance(*ev)) + }) + .collect(); + let before = median(samples.iter().map(|(c, ..)| luminance_2020(*c)).collect()); + let max = 2f32.powf(COMP_MAX_EV); + let mut lut = [1.0f32; COMP_N]; + // (one amount per task: each is a pass over the samples and a median) + lightcraft_raster::par_rows(&mut lut, 1, |i, out| { + let k = (i + 1) as f32 / COMP_N as f32; + let am = Amount::new(self, k); + let after = median(samples.iter().map(|(c, d, m)| luminance_2020(recover_with(&ctx, &am, *c, *d, || sky_weight_at(*m)).0)).collect()); + let ratio = before / after; + let ratio = if ratio.is_finite() { + ratio + } else if before > 0.0 { + max + } else { + 1.0 + }; + for o in out.iter_mut() { + *o = ratio.clamp(1.0, max).powf(COMP_POWER); + } + }); + lut + } +} + +/// The airlight colour: the per-channel median of the pixels whose patch dark channel is in its +/// top [`AIR_TOP`], among the pixels that aren't in the brightest [`AIR_SKIP_BRIGHT`] (by +/// luminance of `e`). Skipping those keeps the sun, its glare and clipped highlights (often +/// magenta after white balance, and far above scene white in an HDR merge) out of the airlight; +/// the median keeps one odd pixel from setting its colour. `None` for an empty image. +fn haze_colour(e: &Rgb32f, dark: &Plane) -> Option<[f32; 3]> { + let finite = |v: f32| if v.is_finite() { v } else { 0.0 }; + let ys: Vec = e.data.iter().map(|p| finite(luminance_2020(*p))).collect(); + let ymax = nth_from_top(ys.clone(), AIR_SKIP_BRIGHT)?; + let kept = || e.data.iter().zip(&dark.data).zip(&ys).filter(move |(_, y)| **y <= ymax).map(|((p, d), _)| (*p, finite(*d))); + let thr = nth_from_top(kept().map(|(_, d)| d).collect(), AIR_TOP)?; + let cand: Vec<[f32; 3]> = kept().filter(|(_, d)| *d >= thr).map(|(p, _)| p).collect(); + if cand.is_empty() { + return None; + } + Some(std::array::from_fn(|c| median(cand.iter().map(|p| p[c]).collect()))) +} + +/// The value with a `share` (0..1) of `v` at or above it (`None` when empty). +fn nth_from_top(mut v: Vec, share: f32) -> Option { + let last = v.len().checked_sub(1)?; + let k = (((v.len() as f32) * (1.0 - share)) as usize).min(last); + Some(*v.select_nth_unstable_by(k, f32::total_cmp).1) +} + +/// Median of `v` (0 when empty). +fn median(mut v: Vec) -> f32 { + v.retain(|x| x.is_finite()); + if v.is_empty() { + return 0.0; + } + let k = v.len() / 2; + *v.select_nth_unstable_by(k, f32::total_cmp).1 +} + +/// What the per-pixel recovery needs of one render (one map, one exposure gain), computed once +/// instead of per pixel. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Ctx { + /// `1 / gain`: back from the exposed colour to the pre-exposure one the map judges. + inv_gain: f32, + /// The airlight, encoded ([`HazeMap::air`]). + air: [f32; 3], + /// [`inv_air_lin`] of it. + inv_air_lin: [f32; 3], + /// `1 /` the airlight's brightest channel (encoded, at least [`AIR_FLOOR`]). + inv_top: f32, + /// The airlight, linear and exposed. + air_g: [f32; 3], + /// The square root of the colour negative amounts veil toward ([`veil_air`]), exposed: the veil + /// mixes in that encoding. + veil_g_sqrt: [f32; 3], + /// Linear (pre-exposure) bounds of the pixels that can be within [`SKY_K`] of the airlight: + /// a pixel with any channel outside them gets the full recovery without encoding it. + sky_lo: [f32; 3], + sky_hi: [f32; 3], +} + +impl Ctx { + /// The values of `map` at exposure `gain` (`None` unless the gain is positive and finite). + pub fn new(map: &HazeMap, gain: f32) -> Option { + if !(gain > 0.0 && gain.is_finite()) { + return None; + } + let top = air_top(map); + let reach = SKY_K * top; + Some(Ctx { + inv_gain: 1.0 / gain, + air: map.air, + inv_air_lin: inv_air_lin(map.air), + inv_top: 1.0 / top, + air_g: map.air_lin().map(|v| v * gain), + veil_g_sqrt: veil_air(map).map(|v| (v * gain).max(0.0).sqrt()), + sky_lo: map.air.map(|a| decode(a - reach)), + sky_hi: map.air.map(|a| decode(a + reach)), + }) + } + + /// Haze `dΜƒ` (0..1) of a pixel with linear (pre-exposure) colour `lin` and the map's + /// coefficients `(a, b)` where it sits ([`HazeMap::coeffs`]). + #[inline] + pub fn dark_with(&self, a: f32, b: f32, lin: [f32; 3]) -> f32 { + let d = a * norm_dark_lin(lin, self.inv_air_lin) + b; + if d.is_finite() { d.clamp(0.0, 1.0) } else { 0.0 } + } + + /// How far an encoded pixel `e` is from the airlight: its largest channel difference, relative + /// to the airlight's brightest channel (so the same photo exposed brighter or darker is judged + /// alike). + #[inline] + fn sky_distance(&self, e: [f32; 3]) -> f32 { + (0..3).map(|i| (e[i] - self.air[i]).abs()).fold(0.0f32, f32::max) * self.inv_top + } + + /// [`sky_weight_at`] of a linear (pre-exposure) pixel; encodes it only when it can be near the + /// airlight. + #[inline] + fn sky_weight(&self, lin: [f32; 3]) -> f32 { + let within = |i: usize| (lin[i] >= self.sky_lo[i]) & (lin[i] <= self.sky_hi[i]); + if within(0) & within(1) & within(2) { sky_weight_at(self.sky_distance(encode3(lin))) } else { 1.0 } + } +} + +/// What the per-pixel recovery needs of one amount, computed once per amount instead of per pixel +/// (a render without mask Dehaze has one amount). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Amount { + /// The amount, βˆ’1..1. + pub k: f32, + /// Haze strength `OMEGAΒ·k^OMEGA_POWER` (positive amounts). + omega: f32, + /// Lowest transmission `lerp(1, T_FLOOR, k)` (positive amounts). + tmin: f32, + /// Exposure compensation ([`HazeMap::comp`]). + comp: f32, +} + +impl Amount { + /// The values of amount `k` (global plus masks; clamped to βˆ’1..1, 0 when not finite). + pub fn new(map: &HazeMap, k: f32) -> Amount { + let k = if k.is_finite() { k.clamp(-1.0, 1.0) } else { 0.0 }; + let kp = k.max(0.0); + Amount { k, omega: OMEGA * kp.powf(OMEGA_POWER), tmin: 1.0 + (T_FLOOR - 1.0) * kp, comp: map.comp(k) } + } +} + +/// The V4 Dehaze of one pixel: `c` is its white-balanced, exposed colour, `(a, b)` the map's +/// coefficients where it sits in the whole output frame ([`HazeMap::coeffs`], [`HazeRow::coeffs`]: +/// a window dehazes exactly like the whole render), `ctx` the render's values and `am` the amount. +/// Returns the dehazed colour; a non-finite result falls back to `c`. +#[inline] +pub fn dehaze_at(ctx: &Ctx, am: &Amount, a: f32, b: f32, c: [f32; 3]) -> [f32; 3] { + if am.k == 0.0 { + return c; + } + let lin = c.map(|v| v * ctx.inv_gain); + let d = ctx.dark_with(a, b, lin); + let (j, w) = recover_with(ctx, am, c, d, || ctx.sky_weight(lin)); + finish_recovery(am, c, j, w) +} + +/// The exposure compensation and chroma blend (positive amounts) of the recovered `j` of the +/// exposed colour `c`, and the fallback to `c` when anything is not finite. `w` is the pixel's sky +/// weight ([`sky_weight_at`]): the compensation makes up for the recovery's darkening, so a pixel +/// the sky tolerance left alone isn't brightened (no light band at the horizon). +fn finish_recovery(am: &Amount, c: [f32; 3], mut j: [f32; 3], w: f32) -> [f32; 3] { + if am.k > 0.0 { + let comp = 1.0 + (am.comp - 1.0) * w; + j = j.map(|v| v * comp); + // keep J's luminance, blend some of the input's chromaticity back + let (yj, yc) = (luminance_2020(j), luminance_2020(c)); + if yj > 1e-9 && yc > 1e-9 { + let s = yj / yc; + j = std::array::from_fn(|i| j[i] + (c[i] * s - j[i]) * CHROMA_KEEP); + } + } + if j[0].is_finite() & j[1].is_finite() & j[2].is_finite() { j } else { c } +} + +/// The colour negative amounts veil toward (linear, pre-exposure): the airlight, scaled so its +/// brightest channel is at most [`VEIL_TOP`]. +pub fn veil_air(map: &HazeMap) -> [f32; 3] { + let air_lin = map.air_lin(); + let top = air_lin.iter().fold(0.0f32, |m, v| m.max(*v)); + let s = if top > VEIL_TOP { VEIL_TOP / top } else { 1.0 }; + air_lin.map(|v| v * s) +} + +/// The airlight's brightest channel (encoded, at least [`AIR_FLOOR`]). +fn air_top(map: &HazeMap) -> f32 { + map.air.iter().fold(AIR_FLOOR, |m, v| m.max(*v)) +} + +/// The sky tolerance of a pixel at [`Ctx::sky_distance`] `m`: 0 at the airlight, rising smoothly +/// to 1 at [`SKY_K`] (1 for NaN). +fn sky_weight_at(m: f32) -> f32 { + if m.is_nan() { 1.0 } else { crate::optics::smoothstep(0.0, SKY_K, m) } +} + +/// The recovery of the exposed colour `c` with haze `d` before its exposure compensation and +/// chroma blend (what the compensation LUT measures), with the pixel's sky weight given (computed +/// only when needed). Returns the recovered colour and that weight (1 when the amount isn't +/// positive). +fn recover_with(ctx: &Ctx, am: &Amount, c: [f32; 3], d: f32, sky: impl FnOnce() -> f32) -> ([f32; 3], f32) { + let d = if d.is_finite() { d.clamp(0.0, 1.0) } else { 0.0 }; + if am.k > 0.0 { + let air = ctx.air_g; + // the map measures haze in the encoding; the recovery is linear, so is its haze share + // (`min(e/A)` of an encoded pixel is `√min(c/A)` of the linear one) + let t = (1.0 - am.omega * d * d).max(am.tmin); + // sky tolerance: pixels close to the airlight colour are left nearly alone; the gain + // above 1 fades in smoothly over 0..SKY_K, so the horizon gets no band. The gain is + // `1 / clamp(t / (t + (1 βˆ’ t)Β·s), T_FLOOR, 1)`, one division (`t β‰₯ tmin > 0`) + let s = sky(); + let inv_t = ((t + (1.0 - t) * s).max(1e-6) / t).clamp(1.0, 1.0 / T_FLOOR); + (std::array::from_fn(|i| (air[i] + (c[i] - air[i]) * inv_t).max(0.0)), s) + } else if am.k < 0.0 { + // a veil toward the airlight, mixed in a square-root encoding (lifts the shadows more + // than the median) + let t = 1.0 - VEIL * -am.k * (VEIL_BASE + (1.0 - VEIL_BASE) * d); + let mix = |v: f32, a_sqrt: f32| { + let r = v.max(0.0).sqrt() * t + a_sqrt * (1.0 - t); + r * r + }; + (std::array::from_fn(|i| mix(c[i], ctx.veil_g_sqrt[i])), 1.0) + } else { + (c, 1.0) + } +} + +/// Whether `s` renders under process V4, whose Dehaze uses a [`HazeMap`]. +pub fn is_v4(s: &DevelopSettings) -> bool { + match s.process.process() { + Process::V1 | Process::V2 | Process::V3 => false, + Process::V4 => true, + } +} + +/// Whether `s` dehazes with a [`HazeMap`]: process V4 with Dehaze (the Effects slider, its section +/// on, or a mask's that the render evaluates: visible, with components) not zero. +pub fn wanted(s: &DevelopSettings) -> bool { + let masks = s.masks.iter().any(|m| m.visible && !m.components.is_empty() && m.adjust.dehaze != 0.0); + is_v4(s) && ((s.section_enabled("effects") && s.effects.dehaze != 0.0) || masks) +} + +/// Proxy size (px) of the map of `frame` (the whole output frame). +pub fn proxy_size(frame: &Frame) -> (usize, usize) { + let (nw, nh) = frame.native_size(); + let native = nw.max(nh); + let edge = if native.is_finite() && native >= 1.0 { (native.round() as usize).min(PROXY_EDGE) } else { PROXY_EDGE }; + frame.fit(edge.max(1), edge.max(1)) +} + +/// How many maps [`for_frame`] keeps (the least recently used goes first). A 768-px proxy's map +/// is about 3.1 MB. +pub const CACHE_KEEP: usize = 6; + +/// One cached map: its full key, and what a draft may reuse it for (the same source content, +/// process and proxy size). +struct Cached { + key: u64, + src: u64, + shape: (Process, usize, usize), + map: Arc, +} + +/// The maps [`for_frame`] keeps: at most [`CACHE_KEEP`], the least recently used first out. +struct MapCache(Vec); + +impl MapCache { + const fn new() -> MapCache { + MapCache(Vec::new()) + } + + /// The map keyed `key`, or (`reuse`) the most recently used one of that source and shape. A + /// hit becomes the most recently used. + fn get(&mut self, key: u64, reuse: Option<(u64, (Process, usize, usize))>) -> Option> { + let c = &mut self.0; + let i = c + .iter() + .rposition(|e| e.key == key) + .or_else(|| reuse.and_then(|(src, shape)| c.iter().rposition(|e| e.src == src && e.shape == shape)))?; + let e = c.remove(i); + let map = e.map.clone(); + c.push(e); + Some(map) + } + + fn bytes(&self) -> usize { + self.0.iter().map(|e| e.map.bytes()).sum() + } + + fn put(&mut self, e: Cached) { + let c = &mut self.0; + c.retain(|o| o.key != e.key); + c.push(e); + while c.len() > CACHE_KEEP { + c.remove(0); + } + } +} + +static CACHE: Mutex = Mutex::new(MapCache::new()); + +fn cache() -> std::sync::MutexGuard<'static, MapCache> { + CACHE.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} + +/// Bytes the maps [`for_frame`] keeps hold. +pub fn cache_bytes() -> usize { + cache().bytes() +} + +/// Drop every map [`for_frame`] keeps (the next render of a dehazed V4 photo builds its map again). +pub fn clear_cache() { + cache().0.clear(); + CLEARS.with(|n| n.set(n.get().wrapping_add(1))); +} + +std::thread_local! { + static CLEARS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How many times this thread called [`clear_cache`]: lets a caller's tests check when it drops +/// the maps although other tests share the cache (and clear it) in parallel. +pub fn clears_on_this_thread() -> u64 { + CLEARS.with(std::cell::Cell::get) +} + +/// The haze map of `src` developed with `s` through `frame` (the whole output frame, before any +/// window), from a cache of the last [`CACHE_KEEP`] maps used (keyed by the source's content +/// fingerprint, the frame, the white balance, the camera local tone mapping, the process and the +/// proxy size). +/// +/// A `draft` (an interactive drag) that misses reuses the most recently used map of the same +/// source, process and proxy size instead of building one: a White Balance, crop or lens drag +/// would otherwise rebuild it on every tick. The map is smooth, so the stand-in is close; the +/// final-quality render after the drag builds the exact one. +pub fn for_frame(src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings, frame: &Frame, draft: bool) -> Arc { + // (an empty source has nothing to sample: no haze) + if src.width == 0 || src.height == 0 || src.data.is_empty() { + return Arc::new(HazeMap::empty()); + } + let (pw, ph) = proxy_size(frame); + let wb = crate::local::wb_matrix_for(info, s).map(|m| m.map(|r| r.map(f32::to_bits))); + let fp = crate::optics::fingerprint(src); + let shape = (s.process.process(), pw, ph); + let local_tone = crate::local_tone::enabled(info, s); + let key = crate::hash_of((fp, format!("{frame:?}"), wb, local_tone, shape)); + if let Some(map) = cache().get(key, draft.then_some((fp, shape))) { + return map; + } + let map = Arc::new(crate::timed("haze map", || { + let mut img = crate::timed("haze proxy", || frame.sample(src, pw, ph)); + // (the pixels the map is applied to went through the camera's local tone mapping) + crate::local_tone::apply_frame(&mut img, info, s, frame); + crate::local::white_balance(&mut img, info, s); + HazeMap::build(&img) + })); + cache().put(Cached { key, src: fp, shape, map: map.clone() }); + map +} + +#[cfg(test)] +mod tests { + use super::*; + + fn lin_of_encoded(e: [f32; 3]) -> [f32; 3] { + e.map(decode) + } + + /// The V4 Dehaze of one pixel of linear (pre-exposure) colour `lin` with haze `d` at amount + /// `k`, exposed by `gain`: [`dehaze_at`] with the haze given. + fn recover(map: &HazeMap, lin: [f32; 3], gain: f32, d: f32, k: f32) -> [f32; 3] { + let ctx = Ctx::new(map, gain).expect("a positive gain"); + let am = Amount::new(map, k); + let c = lin.map(|v| v * gain); + let (j, w) = recover_with(&ctx, &am, c, d, || ctx.sky_weight(lin)); + finish_recovery(&am, c, j, w) + } + + /// Haze `dΜƒ` of a pixel of linear colour `lin` at frame-normalised `(nx, ny)`. + fn dark(map: &HazeMap, nx: f32, ny: f32, lin: [f32; 3]) -> f32 { + let (a, b) = map.coeffs(nx, ny); + Ctx::new(map, 1.0).expect("gain 1").dark_with(a, b, lin) + } + + /// A hazy scene: a dark, contrasty foreground (bottom) under a bright bluish-grey veil (top), + /// with a small white object in the foreground. + fn hazy(w: usize, h: usize) -> Rgb32f { + Rgb32f::from_fn(w, h, |x, y| { + let fy = y as f32 / h as f32; + if (w / 2..w / 2 + 3).contains(&x) && (h * 3 / 4..h * 3 / 4 + 3).contains(&y) { + return [1.0, 1.0, 1.0]; + } + if fy < 0.4 { + lin_of_encoded([0.70, 0.74, 0.80]) + } else { + let t = ((x / 6 + y / 6) % 2) as f32; + lin_of_encoded([0.10 + 0.25 * t, 0.12 + 0.2 * t, 0.08 + 0.1 * t]) + } + }) + } + + #[test] + fn airlight_is_the_haze_not_a_small_white_object() { + let m = HazeMap::build(&hazy(200, 150)); + // the veil [0.70, 0.74, 0.80] pulled halfway to neutral, not the white object's 1.0 + let y = luminance_2020([0.70, 0.74, 0.80]); + for (i, c) in [0.70, 0.74, 0.80].into_iter().enumerate() { + let want = c + (y - c) * AIR_NEUTRAL; + assert!((m.air[i] - want).abs() < 1e-3, "air {:?} want ch{i} {want}", m.air); + } + // haze is high in the veil, low in the foreground + let (top, bottom) = (dark(&m, 0.5, 0.1, lin_of_encoded([0.70, 0.74, 0.80])), dark(&m, 0.3, 0.8, lin_of_encoded([0.10, 0.12, 0.08]))); + assert!(top > 0.8 && bottom < 0.3, "top {top} bottom {bottom}"); + } + + #[test] + fn a_bright_magenta_sun_is_not_the_airlight() { + // an HDR merge's sun: clipped, magenta after white balance, 15x scene white (~0.5 % of + // the frame); as the airlight it turned skies cyan + let mut img = hazy(200, 150); + for y in 10..18 { + for x in 20..40 { + if let Some(p) = img.data.get_mut(y * 200 + x) { + *p = [15.5, 5.0, 14.0]; + } + } + } + let m = HazeMap::build(&img); + let y = luminance_2020([0.70, 0.74, 0.80]); + for (i, c) in [0.70, 0.74, 0.80].into_iter().enumerate() { + let want = c + (y - c) * AIR_NEUTRAL; + assert!((m.air[i] - want).abs() < 1e-3, "air {:?} want ch{i} {want}", m.air); + } + } + + #[test] + fn a_flat_grey_has_constant_haze_and_is_left_alone() { + for v in [0.02f32, 0.18, 0.5, 1.0] { + let img = Rgb32f::filled(64, 48, [v; 3]); + let m = HazeMap::build(&img); + assert!(m.air.iter().all(|a| a.is_finite() && *a >= AIR_FLOOR), "{:?}", m.air); + let d0 = dark(&m, 0.0, 0.0, [v; 3]); + for (nx, ny) in [(0.5, 0.5), (1.0, 1.0), (0.2, 0.9)] { + assert!((dark(&m, nx, ny, [v; 3]) - d0).abs() < 1e-4); + } + assert!(m.comp.iter().all(|c| (*c - 1.0).abs() < 1e-3), "{:?}", m.comp); + for k in [-1.0, -0.5, 0.25, 0.5, 1.0] { + let out = recover(&m, [v; 3], 1.0, d0, k); + for c in out { + assert!((c - v).abs() <= v * 2e-3 + 1e-6, "v {v} k {k} -> {out:?}"); + } + } + } + } + + #[test] + fn black_white_and_nan_images_never_give_nan() { + let imgs = [ + Rgb32f::filled(32, 32, [0.0; 3]), + Rgb32f::filled(32, 32, [1.0; 3]), + Rgb32f::filled(32, 32, [f32::NAN; 3]), + Rgb32f::filled(32, 32, [f32::INFINITY, -1.0, f32::NAN]), + Rgb32f::from_fn(32, 32, |x, _| if x % 3 == 0 { [f32::NAN, 0.5, 0.2] } else { [0.3, 0.2, 0.1] }), + Rgb32f::new(0, 0), + Rgb32f::new(5, 0), + Rgb32f { width: 4, height: 4, data: vec![[0.5; 3]; 3] }, + ]; + for img in &imgs { + let m = HazeMap::build(img); + assert!(m.air.iter().all(|a| a.is_finite() && *a >= AIR_FLOOR), "{:?}", m.air); + assert!(m.air_lin().iter().all(|a| a.is_finite())); + assert!(m.a.data.iter().chain(&m.b.data).all(|v| v.is_finite())); + assert!(m.comp.iter().all(|c| c.is_finite() && *c >= 1.0)); + for px in [[0.0; 3], [1.0; 3], [f32::NAN; 3], [f32::INFINITY; 3], [-1.0; 3]] { + for (nx, ny) in [(0.5, 0.5), (f32::NAN, 2.0), (-3.0, f32::INFINITY)] { + let d = dark(&m, nx, ny, px); + assert!((0.0..=1.0).contains(&d), "{d}"); + for k in [-1.0, -0.3, 0.0, 0.4, 1.0, f32::NAN, 7.0] { + let out = recover(&m, px, 1.0, d, k); + let fallback = px.map(|v| v * 1.0); + assert!( + out.iter().all(|v| v.is_finite()) || out.iter().zip(fallback).all(|(a, b)| a.to_bits() == b.to_bits()), + "{px:?} k {k} -> {out:?}" + ); + } + } + } + } + } + + #[test] + fn deterministic() { + let img = hazy(160, 120); + assert_eq!(HazeMap::build(&img), HazeMap::build(&img)); + } + + #[test] + fn coefficients_are_frame_normalised() { + let m = HazeMap::build(&hazy(100, 80)); + // corners land on the corner proxy pixels, and outside is the edge's + let (w, h) = m.size(); + let at = |p: &Plane, x: usize, y: usize| p.data[y * w + x]; + assert_eq!(m.coeffs(0.0, 0.0), (at(&m.a, 0, 0), at(&m.b, 0, 0))); + assert_eq!(m.coeffs(1.0, 1.0), (at(&m.a, w - 1, h - 1), at(&m.b, w - 1, h - 1))); + assert_eq!(m.coeffs(-5.0, 9.0), m.coeffs(0.0, 1.0)); + } + + #[test] + fn row_sampling_is_bilinear_sampling() { + // the renderer blends two proxy rows once per output row, then two columns per pixel: the + // same arithmetic, in the same order, as `coeffs` (and the GPU) + let m = HazeMap::build(&hazy(100, 80)); + for ny in [-1.0, 0.0, 0.013, 0.37, 0.5, 0.999, 1.0, 3.0, f32::NAN] { + let row = m.row(ny); + for nx in [-1.0, 0.0, 0.021, 0.44, 0.5, 0.97, 1.0, 2.0, f32::NAN] { + let (a, b) = row.coeffs(&m.column(nx)); + let (ca, cb) = m.coeffs(nx, ny); + assert_eq!((a.to_bits(), b.to_bits()), (ca.to_bits(), cb.to_bits()), "({nx}, {ny})"); + } + } + // a malformed map samples zeros, never panics + let bad = HazeMap { a: Plane { width: 4, height: 4, data: vec![1.0; 3] }, ..HazeMap::empty() }; + assert_eq!(bad.row(0.9).coeffs(&bad.column(0.9)).0, 0.0); + assert_eq!(bad.coeffs(0.9, 0.9).0, 0.0); + } + + #[test] + fn compensation_brightens_more_with_the_amount_and_is_bounded() { + let m = HazeMap::build(&hazy(200, 150)); + assert_eq!(m.comp(0.0), 1.0); + assert_eq!(m.comp(-0.5), 1.0); + let max = 2f32.powf(COMP_MAX_EV).powf(COMP_POWER); + let mut last = 1.0; + for i in 0..=40 { + let c = m.comp(i as f32 / 40.0); + assert!(c >= last - 1e-6 && c <= max + 1e-6, "{i}: {c} after {last}"); + last = c; + } + assert!(m.comp(1.0) > 1.0, "{:?}", m.comp); + assert_eq!(m.comp(1.0), m.comp[COMP_N - 1]); + assert_eq!(m.comp(5.0), m.comp(1.0)); + } + + #[test] + fn dehaze_adds_contrast_and_negative_adds_a_veil() { + let m = HazeMap::build(&hazy(200, 150)); + let (p1, p2) = (lin_of_encoded([0.55, 0.57, 0.60]), lin_of_encoded([0.45, 0.47, 0.50])); + let y = |c: [f32; 3]| luminance_2020(c); + let before = y(p1) - y(p2); + let after = y(recover(&m, p1, 1.0, 0.5, 0.5)) - y(recover(&m, p2, 1.0, 0.5, 0.5)); + assert!(after > before * 1.1, "contrast {before} -> {after}"); + // without the exposure compensation the hazy tones darken + let ctx = Ctx::new(&m, 1.0).expect("gain 1"); + assert!(y(recover_with(&ctx, &Amount::new(&m, 0.5), p1, 0.5, || ctx.sky_weight(p1)).0) < y(p1)); + let veiled = recover(&m, [0.01; 3], 1.0, 0.5, -1.0); + assert!(y(veiled) > 0.02, "a veil lifts black: {veiled:?}"); + let less = y(recover(&m, p1, 1.0, 0.5, -1.0)) - y(recover(&m, p2, 1.0, 0.5, -1.0)); + assert!(less < before * 0.9, "negative lowers contrast: {before} -> {less}"); + } + + #[test] + fn proxy_is_capped_at_the_proxy_edge() { + let s = DevelopSettings::default(); + let big = Frame::new(4000, 3000, &s, true); + assert_eq!(proxy_size(&big), (768, 576)); + let small = Frame::new(300, 200, &s, true); + assert_eq!(proxy_size(&small), (300, 200)); + } + + #[test] + fn the_cache_evicts_the_least_recently_used_and_stays_bounded() { + let shape = (Process::V4, 10, 10); + let entry = |key: u64, src: u64| Cached { key, src, shape, map: Arc::new(HazeMap::empty()) }; + let mut c = MapCache::new(); + for k in 0..CACHE_KEEP as u64 { + c.put(entry(k, 100 + k)); + } + let first = c.get(0, None).expect("cached"); + // more maps than it keeps: the one used on every tick stays, the oldest unused goes + for k in 0..3u64 { + c.put(entry(1000 + k, 1000 + k)); + assert!(c.get(0, None).is_some_and(|m| Arc::ptr_eq(&m, &first)), "evicted the map in use"); + } + assert_eq!(c.0.len(), CACHE_KEEP); + assert!(c.get(1, None).is_none() && c.get(2, None).is_none(), "the least recently used went"); + // a draft that misses reuses the latest of the same source and shape; a final render doesn't + assert!(c.get(77, None).is_none()); + assert!(c.get(77, Some((100, shape))).is_some_and(|m| Arc::ptr_eq(&m, &first))); + assert!(c.get(77, Some((100, (Process::V4, 11, 10)))).is_none(), "another proxy size"); + assert!(c.get(77, Some((5, shape))).is_none(), "another source"); + } + + #[test] + fn the_cache_counts_its_bytes() { + let map = Arc::new(HazeMap::build(&hazy(120, 90))); + assert!(map.bytes() >= 2 * 120 * 90 * 4, "{}", map.bytes()); + let mut c = MapCache::new(); + assert_eq!(c.bytes(), 0); + c.put(Cached { key: 1, src: 1, shape: (Process::V4, 120, 90), map: map.clone() }); + c.put(Cached { key: 2, src: 2, shape: (Process::V4, 1, 1), map: Arc::new(HazeMap::empty()) }); + assert_eq!(c.bytes(), map.bytes() + HazeMap::empty().bytes()); + // (the shared cache: other tests use it, so only that it answers) + let _ = cache_bytes(); + } + + #[test] + fn wanted_ignores_masks_the_render_skips() { + use lightcraft_develop::{LocalAdjustments, Mask, MaskComponent, MaskOp, MaskShape}; + let comp = MaskComponent { + name: None, + op: MaskOp::Add, + invert: false, + shape: MaskShape::Linear { start: lightcraft_geom::Point::new(0.5, 0.0), end: lightcraft_geom::Point::new(0.5, 1.0) }, + }; + let mask = Mask { components: vec![comp], adjust: LocalAdjustments { dehaze: 40.0, ..Default::default() }, ..Default::default() }; + let mut s = DevelopSettings { process: Process::V4.version(), masks: vec![mask.clone()], ..DevelopSettings::default() }; + assert!(wanted(&s)); + s.masks = vec![Mask { visible: false, ..mask.clone() }]; + assert!(!wanted(&s), "a hidden mask"); + s.masks = vec![Mask { components: vec![], ..mask }]; + assert!(!wanted(&s), "a mask without components"); + } + + #[test] + fn wanted_only_for_v4_with_dehaze() { + use lightcraft_develop::ProcessVersion; + let mut s = DevelopSettings { process: Process::V4.version(), ..DevelopSettings::default() }; + assert!(!wanted(&s)); + s.effects.dehaze = 30.0; + assert!(wanted(&s)); + s.disabled_sections.push("effects".into()); + assert!(!wanted(&s)); + s.process = ProcessVersion(2); + s.disabled_sections.clear(); + assert!(!wanted(&s)); + } +} diff --git a/crates/pipeline/src/lib.rs b/crates/pipeline/src/lib.rs index 455cec02217..9d7b2029f1b 100644 --- a/crates/pipeline/src/lib.rs +++ b/crates/pipeline/src/lib.rs @@ -30,6 +30,7 @@ pub mod cull; pub mod dust; pub mod finish; pub mod geometry; +pub mod haze; pub mod local; pub mod local_tone; pub mod lut; @@ -209,6 +210,9 @@ pub(crate) struct Prepared { pub clarity_blur: Option>, pub texture_blur: Option>, pub dark: Option>, + /// Process V4's haze map of the whole frame ([`Plan::haze`]); V4 dehazes with it instead of + /// `dark` / `air`. + pub haze: Option>, /// Blurred chromaticity (`rgb / Y`) for local MoirΓ© / Noise. pub chroma_blur: Option>, /// Airlight of `dark` (before exposure). @@ -372,6 +376,8 @@ pub struct Plan<'a> { /// Key of the resampled source (together with the source buffer's identity). pub geo: u64, /// Key of the white-balanced, retouched, denoised image (and of the planes computed from it). + /// It doesn't depend on the rendering process: a plane that does is keyed by it on its own + /// ([`local::BaseKey`]), and V4's haze map has its own cache ([`haze::for_frame`]). pub lin_key: u64, /// [`Self::lin_key`] without the noise-reduction settings: draft renders reuse the smooth /// planes of an image that differs from this one only in its noise reduction. @@ -380,6 +386,10 @@ pub struct Plan<'a> { pub eyes: Vec, /// The whole frame's dehaze airlight, for a windowed render (which can't see the whole frame). pub fixed_air: Option, + /// Process V4's dehaze haze map of the whole frame ([`haze::HazeMap`], cached per image): every + /// render of the photo (any size, any window, CPU or GPU) samples the same one. `None` unless + /// the settings dehaze under V4 ([`haze::wanted`]). + pub haze: Option>, /// A windowed render works on a larger window when spots reach into it (see /// [`spots::window_for_reads`]); this is the requested window inside the rendered one, which /// the result is cut to. @@ -393,6 +403,12 @@ const AIRLIGHT_PROXY_EDGE: usize = 384; /// Resolve `s` against `src` for `req` (see [`Plan`]). pub fn plan<'a>(src: &Rgb32f, info: &SourceInfo, s: &'a DevelopSettings, req: &RenderRequest) -> Plan<'a> { + plan_with(src, info, s, req, true) +} + +/// [`plan`]; without the haze map (`Plan::haze` stays `None`) unless `haze`, for callers that +/// never dehaze (they only need the scene-linear stage). +fn plan_with<'a>(src: &Rgb32f, info: &SourceInfo, s: &'a DevelopSettings, req: &RenderRequest, haze: bool) -> Plan<'a> { let mut settings: Cow<'a, DevelopSettings> = match profiles::effective(s) { Cow::Borrowed(b) => upright::resolve(src, info, b), Cow::Owned(o) => Cow::Owned(upright::resolve(src, info, &o).into_owned()), @@ -412,12 +428,15 @@ pub fn plan<'a>(src: &Rgb32f, info: &SourceInfo, s: &'a DevelopSettings, req: &R let (full_w, full_h) = frame.fit(req.max_w, req.max_h); // sizes and scale are those of the whole output; a window only narrows what is drawn let px_per_long = frame.px_per_long(full_w); + // (of the whole frame, before any window narrows it) + let haze = (haze && haze::wanted(s)).then(|| haze::for_frame(src, info, s, &frame, req.quality == Quality::Draft)); let mut fixed_air = None; let mut keep = None; let (frame, w, h) = match req.window { Some(win) => { let win = win.clamped(full_w, full_h); - if s.section_enabled("effects") && (s.effects.dehaze != 0.0 || s.masks.iter().any(|m| m.adjust.dehaze != 0.0)) { + // (V4 dehazes with the haze map, which is already the whole frame's) + if !haze::is_v4(s) && s.section_enabled("effects") && (s.effects.dehaze != 0.0 || s.masks.iter().any(|m| m.adjust.dehaze != 0.0)) { let k = (AIRLIGHT_PROXY_EDGE as f64 / full_w.max(full_h) as f64).min(1.0); let (pw, ph) = (((full_w as f64 * k).round() as usize).max(1), ((full_h as f64 * k).round() as usize).max(1)); fixed_air = Some(local::frame_airlight(src, info, s, &frame, pw, ph)); @@ -455,7 +474,23 @@ pub fn plan<'a>(src: &Rgb32f, info: &SourceInfo, s: &'a DevelopSettings, req: &R [d.nr_luminance, d.nr_detail, d.nr_color, d.nr_color_detail, d.nr_color_smoothness].map(f64::to_bits), detail_scale.to_bits(), )); - Plan { settings, frame, w, h, px_per_long, src_long, detail_scale, geo, lin_key, pre_nr_key, eyes, fixed_air, keep, mattes: info.mattes.clone() } + Plan { + settings, + frame, + w, + h, + px_per_long, + src_long, + detail_scale, + geo, + lin_key, + pre_nr_key, + eyes, + fixed_air, + haze, + keep, + mattes: info.mattes.clone(), + } } /// Whether the scene-linear stage needs work only the CPU does (defringe, spot removal). @@ -592,6 +627,7 @@ fn render_impl(src: Src<'_>, info: &SourceInfo, s: &DevelopSettings, req: &Rende if let Some(a) = plan.fixed_air { prep.air = a; } + prep.haze = plan.haze.clone(); lap("prepare", &mut t); if let Some((a, c)) = shared { c.put(CacheEntry { src: a.clone(), geo, sampled, lin: Some((lin_key, lin)), planes }); @@ -638,7 +674,8 @@ pub fn color_range_sample(src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings, // SDR preview of an HDR edit includes the SDR rendition's exposure offset. let effective = s.effective(); let rendition = settings_for(&effective, req); - let plan = plan(src, info, &rendition, req); + // (the scene-linear colours only: no haze map) + let plan = plan_with(src, info, &rendition, req, false); let mut img = plan.frame.sample(src, plan.w, plan.h); lin_cpu(&mut img, info, &plan); let o = plan.frame.norm_to_out(plan.w, plan.h).apply(p); @@ -727,6 +764,10 @@ pub(crate) fn for_rows(data: &mut [T], w: usize, f: impl Fn(usize, &mut #[cfg(test)] mod tests; #[cfg(test)] +mod tests_dehaze; +#[cfg(test)] +mod tests_dehaze_v4; +#[cfg(test)] mod tests_geometry; #[cfg(test)] mod tests_hdr; diff --git a/crates/pipeline/src/local.rs b/crates/pipeline/src/local.rs index 679acabfe7a..591ffccf2d3 100644 --- a/crates/pipeline/src/local.rs +++ b/crates/pipeline/src/local.rs @@ -217,7 +217,7 @@ pub fn median_hv(p: &Plane, r: usize) -> Plane { for_rows(&mut out.data, src.width, |y, row| median_row(src.row(y), row, r)); out }; - transpose(&rows(&transpose(&rows(p)))) + rows(&rows(p).transpose()).transpose() } /// Running median of `src` over `2r+1` taps (clamped edges) into `out`: a sorted window that @@ -243,15 +243,67 @@ fn median_row(src: &[f32], out: &mut [f32], r: usize) { } } -fn transpose(p: &Plane) -> Plane { - let (w, h) = (p.width, p.height); - let mut t = Plane::new(h, w); - for_rows(&mut t.data, h, |x, row| { - for (y, v) in row.iter_mut().enumerate() { - *v = p.data[y * w + x]; - } - }); - t +/// Separable minimum (`2r+1` px along each row, then each column; clamped edges): a square +/// erosion. Dehaze's patch dark channel from process V3 (#1237). +pub fn min_hv(p: &Plane, r: usize) -> Plane { + if r == 0 || p.data.is_empty() { + return p.clone(); + } + let rows = |src: &Plane| { + let mut out = Plane::new(src.width, src.height); + for_rows(&mut out.data, src.width, |y, row| min_row(src.row(y), row, r)); + out + }; + rows(&rows(p).transpose()).transpose() +} + +/// Minimum of `src` over `2r+1` taps (clamped to the row) into `out`, in O(1) per pixel (van Herk / +/// Gil–Werman: block-wise running minima from both ends). +fn min_row(src: &[f32], out: &mut [f32], r: usize) { + let n = src.len(); + let k = 2 * r + 1; + // padded with +inf: r before, enough after to complete the last block + let len = (n + 2 * r).div_ceil(k) * k; + let at = |i: usize| if i >= r { src.get(i - r).copied().unwrap_or(f32::INFINITY) } else { f32::INFINITY }; + let mut fwd = vec![f32::INFINITY; len]; + let mut bwd = vec![f32::INFINITY; len]; + for i in 0..len { + let v = at(i); + fwd[i] = if i % k == 0 { v } else { v.min(fwd[i - 1]) }; + } + for i in (0..len).rev() { + let v = at(i); + bwd[i] = if i % k == k - 1 || i + 1 == len { v } else { v.min(bwd[i + 1]) }; + } + for (x, o) in out.iter_mut().enumerate().take(n) { + // window [x, x + 2r] in padded coordinates + *o = bwd.get(x).copied().unwrap_or(f32::INFINITY).min(fwd.get(x + 2 * r).copied().unwrap_or(f32::INFINITY)); + } +} + +/// Patch radius of dehaze's dark channel from process V3, as a fraction of the long edge. +pub const DEHAZE_PATCH: f64 = 0.005; +/// Largest [`dehaze_patch_radius`] (px). +pub const DEHAZE_PATCH_MAX: usize = 64; + +/// Patch (minimum) radius of the dehaze dark channel of `s`'s process at `px_per_long`: 0 (the +/// per-pixel minimum) before V3. +pub fn dehaze_patch_radius(s: &DevelopSettings, px_per_long: f64) -> usize { + match s.process.process() { + Process::V1 | Process::V2 => 0, + Process::V3 | Process::V4 => ((DEHAZE_PATCH * px_per_long).round().max(1.0) as usize).min(DEHAZE_PATCH_MAX), + } +} + +/// Cache key of the dark-channel plane: its blur radius and patch radius. +pub fn dark_key(sigma: f32, patch: usize) -> u64 { + u64::from(sigma.to_bits()) | ((patch as u64) << 32) +} + +/// The dehaze dark channel: the Gaussian (`sigma`) of the `patch`-px minimum of each pixel's +/// darkest channel. +pub fn dark_plane(img: &Rgb32f, sigma: f32, patch: usize) -> Plane { + gaussian(&min_hv(&img.map(dark_of), patch), sigma) } /// Detail scale of the highlights/shadows base from process V2, as a fraction of the long edge: @@ -273,7 +325,7 @@ pub fn base_detail_radius(px_per_long: f64) -> usize { pub fn tone_base_detail(s: &DevelopSettings, px_per_long: f64) -> usize { match s.process.process() { Process::V1 => 0, - Process::V2 => base_detail_radius(px_per_long), + Process::V2 | Process::V3 | Process::V4 => base_detail_radius(px_per_long), } } @@ -420,7 +472,7 @@ pub(crate) struct Planes { pub clarity: Option<(u32, Arc)>, pub texture: Option<(u32, Arc)>, /// Dark channel and its airlight. - pub dark: Option<(u32, Arc, f32)>, + pub dark: Option<(u64, Arc, f32)>, /// Blurred chromaticity (local MoirΓ© / Noise). pub chroma: Option<(u32, Arc)>, } @@ -484,6 +536,8 @@ pub struct PlaneSigmas { pub texture: Option, /// Dehaze dark channel (Gaussian). pub dark: Option, + /// Patch radius (px) of that dark channel ([`dehaze_patch_radius`]: 0 before V3). + pub dark_patch: usize, /// Chromaticity blur for local MoirΓ© / colour noise (Gaussian). pub chroma: Option, } @@ -509,10 +563,12 @@ pub fn plane_sigmas(s: &DevelopSettings, px_per_long: f64, q: Quality) -> PlaneS || local_any(|a| a.noise) || s.masks.iter().any(|m| m.adjust.defringe > 0.0)) .then(|| (0.0018 * ppl).max(0.6)); - let dark = (s.effects.dehaze != 0.0 || local_any(|a| a.dehaze)).then(|| (0.02 * ppl).max(1.0)); + // (from V4 Dehaze samples the whole frame's haze map instead: `crate::haze`) + let dark = (!crate::haze::is_v4(s) && (s.effects.dehaze != 0.0 || local_any(|a| a.dehaze))).then(|| (0.02 * ppl).max(1.0)); let chroma = (local_any(|a| a.moire) || s.masks.iter().any(|m| m.adjust.noise > 0.0)).then(|| (CHROMA_SIGMA * ppl).max(1.0)); let base_detail = if base.is_some() { tone_base_detail(s, px_per_long) } else { 0 }; - PlaneSigmas { base, base_detail, clarity, texture, dark, chroma } + let dark_patch = if dark.is_some() { dehaze_patch_radius(s, px_per_long) } else { 0 }; + PlaneSigmas { base, base_detail, clarity, texture, dark, dark_patch, chroma } } /// The spatial planes the per-pixel stage needs for `img` (white-balanced, before exposure), @@ -529,8 +585,15 @@ pub(crate) fn prepare( mattes: Option<&masks::Mattes>, ) -> Prepared { let log_l = planes.log_l.get_or_insert_with(|| Arc::new(timed("log_l", || img.map(log_lum)))).clone(); - let PlaneSigmas { base: base_sigma, base_detail, clarity: clarity_sigma, texture: texture_sigma, dark: dark_sigma, chroma: chroma_sigma } = - plane_sigmas(s, px_per_long, q); + let PlaneSigmas { + base: base_sigma, + base_detail, + clarity: clarity_sigma, + texture: texture_sigma, + dark: dark_sigma, + dark_patch, + chroma: chroma_sigma, + } = plane_sigmas(s, px_per_long, q); let Planes { base: sb, clarity: sc, texture: st, dark: sd, chroma: sch, .. } = planes; let chroma_blur = chroma_sigma.map(|sg| match sch { @@ -552,11 +615,11 @@ pub(crate) fn prepare( || texture_sigma.map(|sg| plane_at(st, sg.to_bits(), || timed("texture", || gaussian(l, sg)))), || { dark_sigma.map(|sg| match sd { - Some((k, d, air)) if *k == sg.to_bits() => (d.clone(), *air), + Some((k, d, air)) if *k == dark_key(sg, dark_patch) => (d.clone(), *air), _ => { - let d = timed("dehaze", || Arc::new(gaussian(&img.map(dark_of), sg))); + let d = timed("dehaze", || Arc::new(dark_plane(&img, sg, dark_patch))); let air = airlight(&d); - *sd = Some((sg.to_bits(), d.clone(), air)); + *sd = Some((dark_key(sg, dark_patch), d.clone(), air)); (d, air) } }) @@ -573,7 +636,7 @@ pub(crate) fn prepare( }; let ev = s.light.exposure as f32; let masks = timed("masks", || masks::evaluate(&s.masks, frame, img.width, img.height, &img, &log_l, ev, mattes)); - Prepared { img, log_l, base, clarity_blur, texture_blur, dark, chroma_blur, air, masks, px_per_long } + Prepared { img, log_l, base, clarity_blur, texture_blur, dark, haze: None, chroma_blur, air, masks, px_per_long } } /// The airlight of the whole output frame, estimated on a small render of it (`proxy_w` px wide): @@ -581,8 +644,9 @@ pub(crate) fn prepare( pub(crate) fn frame_airlight(src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings, frame: &Frame, proxy_w: usize, proxy_h: usize) -> f32 { let mut img = Rgb32f::clone(&frame_proxy(src, frame, proxy_w, proxy_h)); white_balance(&mut img, info, s); - let sigma = (0.02 * frame.px_per_long(proxy_w)).max(1.0) as f32; - airlight(&gaussian(&img.map(dark_of), sigma)) + let ppl = frame.px_per_long(proxy_w); + let sigma = (0.02 * ppl).max(1.0) as f32; + airlight(&dark_plane(&img, sigma, dehaze_patch_radius(s, ppl))) } /// How many airlight proxies [`frame_proxy`] keeps (one per photo and frame being zoomed into; each ≀ 1.8 MB). @@ -672,7 +736,8 @@ mod tests { let fresh = |src: &Rgb32f, frame: &Frame| { let mut img = frame.sample(src, 48, 32); white_balance(&mut img, &info, &s); - airlight(&gaussian(&img.map(dark_of), (0.02 * frame.px_per_long(48)).max(1.0) as f32)) + let ppl = frame.px_per_long(48); + airlight(&dark_plane(&img, (0.02 * ppl).max(1.0) as f32, dehaze_patch_radius(&s, ppl))) }; let frame = crate::frame_for(&hazy, &info, &s, true); let kept = frame_proxy(&hazy, &frame, 48, 32); diff --git a/crates/pipeline/src/local_tone.rs b/crates/pipeline/src/local_tone.rs index c38a25c9c45..1c51c621537 100644 --- a/crates/pipeline/src/local_tone.rs +++ b/crates/pipeline/src/local_tone.rs @@ -15,6 +15,7 @@ use lightcraft_geom::Point; use lightcraft_raster::Rgb32f; use lightcraft_raw::gaintable::{GainTableMap, SourcePlacement}; +use crate::geometry::Frame; use crate::{Plan, SourceInfo}; use lightcraft_develop::DevelopSettings; @@ -33,10 +34,14 @@ pub fn enabled(info: &SourceInfo, s: &DevelopSettings) -> bool { /// Multiply the resampled, not yet white-balanced source `img` (the output frame of `p`) by the /// local tone gain at each pixel. Blank canvas (outside a lens / perspective warp) is left alone. pub fn apply(img: &mut Rgb32f, info: &SourceInfo, p: &Plan<'_>) { - let Some(lt) = info.local_tone.as_deref().filter(|_| enabled(info, &p.settings)) else { return }; + apply_frame(img, info, &p.settings, &p.frame); +} + +/// [`apply`] for `img`, a resampling of the whole of `frame` (at any size) developed with `s`. +pub fn apply_frame(img: &mut Rgb32f, info: &SourceInfo, s: &DevelopSettings, frame: &Frame) { + let Some(lt) = info.local_tone.as_deref().filter(|_| enabled(info, s)) else { return }; let Some(eval) = lt.map.evaluator() else { return }; let (w, h) = (img.width, img.height); - let frame = &p.frame; let (ow, oh) = (frame.ow.max(1e-9), frame.oh.max(1e-9)); let o2t = frame.out_to_oriented(w, h); let user = frame.orient.inverse(); diff --git a/crates/pipeline/src/masks.rs b/crates/pipeline/src/masks.rs index c9a7dada9b7..6e3c4a05585 100644 --- a/crates/pipeline/src/masks.rs +++ b/crates/pipeline/src/masks.rs @@ -635,6 +635,18 @@ pub fn auto_refine(r: f64) -> (f32, f32) { /// Guided filter of `p` steered by `guide` (He et al.), clamped to 0..1: `p`'s edges snap to the /// guide's. pub fn guided_cross(guide: &Plane, p: &Plane, sigma: f32, eps: f32) -> Plane { + let (ma, mb) = guided_cross_coeffs(guide, p, sigma, eps); + let mut q = Plane::new(p.width, p.height); + for i in 0..q.data.len() { + q.data[i] = (ma.data[i] * guide.data[i] + mb.data[i]).clamp(0.0, 1.0); + } + q +} + +/// The blurred linear coefficients `(mean a, mean b)` of [`guided_cross`]: its output is +/// `mean_a Β· guide + mean_b` (clamped). Kept apart so they can be applied to another guide, e.g. at +/// another resolution (the dehaze haze map, [`crate::haze`]). `guide` and `p` have the same size. +pub fn guided_cross_coeffs(guide: &Plane, p: &Plane, sigma: f32, eps: f32) -> (Plane, Plane) { use lightcraft_raster::blur::gaussian; let mi = gaussian(guide, sigma); let mp = gaussian(p, sigma); @@ -648,12 +660,7 @@ pub fn guided_cross(guide: &Plane, p: &Plane, sigma: f32, eps: f32) -> Plane { a.data[i] = k; b.data[i] = mp.data[i] - k * mi.data[i]; } - let (ma, mb) = (gaussian(&a, sigma), gaussian(&b, sigma)); - let mut q = Plane::new(p.width, p.height); - for i in 0..q.data.len() { - q.data[i] = (ma.data[i] * guide.data[i] + mb.data[i]).clamp(0.0, 1.0); - } - q + (gaussian(&a, sigma), gaussian(&b, sigma)) } /// Stamp brush strokes into `out` (max-combine; erase strokes subtract). Auto Mask strokes weight diff --git a/crates/pipeline/src/optics.rs b/crates/pipeline/src/optics.rs index 31e8d1351bc..7a88c66779b 100644 --- a/crates/pipeline/src/optics.rs +++ b/crates/pipeline/src/optics.rs @@ -550,7 +550,7 @@ fn estimate_lateral_ca_uncached(img: &Rgb32f) -> [f64; 2] { const PURPLE_HUES: (f32, f32) = (240.0, 360.0); const GREEN_HUES: (f32, f32) = (90.0, 210.0); -fn smoothstep(e0: f32, e1: f32, x: f32) -> f32 { +pub(crate) fn smoothstep(e0: f32, e1: f32, x: f32) -> f32 { let t = ((x - e0) / (e1 - e0)).clamp(0.0, 1.0); t * t * (3.0 - 2.0 * t) } @@ -589,7 +589,7 @@ pub fn defringe(img: &mut Rgb32f, s: &DevelopSettings, scale: f64) { // perceptual lightness and its local range (dilated contrast) let lab: Vec<[f32; 3]> = img.data.iter().map(|p| oklab_from_2020([p[0].max(0.0), p[1].max(0.0), p[2].max(0.0)])).collect(); let l = Plane { width: w, height: h, data: lab.iter().map(|p| p[0]).collect() }; - let (lo, hi) = (min_filter(&l, radius, false), min_filter(&l, radius, true)); + let (lo, hi) = (lightcraft_raster::morph::min_filter(&l, radius), lightcraft_raster::morph::max_filter(&l, radius)); let range = |lo: f64, hi: f64, span: (f32, f32)| { let a = span.0 + (span.1 - span.0) * (lo / 100.0) as f32; let b = span.0 + (span.1 - span.0) * (hi / 100.0) as f32; @@ -623,32 +623,6 @@ pub fn defringe(img: &mut Rgb32f, s: &DevelopSettings, scale: f64) { }); } -/// Separable square min (or max) filter of radius `r`. -fn min_filter(p: &Plane, r: usize, max: bool) -> Plane { - let (w, h) = (p.width, p.height); - let pick = |a: f32, b: f32| if max { a.max(b) } else { a.min(b) }; - let mut tmp = Plane::new(w, h); - for_rows(&mut tmp.data, w, |y, row| { - let src = &p.data[y * w..(y + 1) * w]; - for (x, v) in row.iter_mut().enumerate() { - let (a, b) = (x.saturating_sub(r), (x + r).min(w - 1)); - *v = src[a..=b].iter().copied().fold(src[x], pick); - } - }); - let mut out = Plane::new(w, h); - for_rows(&mut out.data, w, |y, row| { - let (a, b) = (y.saturating_sub(r), (y + r).min(h - 1)); - for (x, v) in row.iter_mut().enumerate() { - let mut m = tmp.data[y * w + x]; - for yy in a..=b { - m = pick(m, tmp.data[yy * w + x]); - } - *v = m; - } - }); - out -} - #[cfg(test)] mod tests { use super::*; diff --git a/crates/pipeline/src/tests_dehaze.rs b/crates/pipeline/src/tests_dehaze.rs new file mode 100644 index 00000000000..b5d09ccb350 --- /dev/null +++ b/crates/pipeline/src/tests_dehaze.rs @@ -0,0 +1,132 @@ +//! Dehaze from process V3 (issue #1237): haze is estimated from a patch-minimum dark channel, the +//! response eases in, and no pixel is pushed to black; V1 and V2 keep their rendering. + +use lightcraft_develop::{DevelopSettings, Process, controls}; +use lightcraft_raster::{Rgb32f, Rgba8}; + +use crate::{RenderRequest, SourceInfo, finish::dehaze_v3_pixel, local, render}; + +const W: usize = 600; +const H: usize = 300; + +/// Left: bright sky (0.8); right: a textured ground (a 0.03 / 0.30 chequer of 6 px cells) whose +/// patches all hold dark pixels: no haze there. +fn scene() -> Rgb32f { + Rgb32f::from_fn(W, H, |x, y| { + let v = if x < W / 2 { + 0.8 + } else if (x / 6 + y / 6).is_multiple_of(2) { + 0.03 + } else { + 0.30 + }; + [v; 3] + }) +} + +fn shot(p: Process, dehaze: f64) -> Rgba8 { + let mut s = DevelopSettings { process: p.version(), ..DevelopSettings::default() }; + controls::set(&mut s, "effects.dehaze", dehaze); + render(&scene(), &SourceInfo::default(), &s, &RenderRequest::fit(W, H)).image +} + +fn luma(p: [u8; 4]) -> f32 { + 0.2126 * p[0] as f32 + 0.7152 * p[1] as f32 + 0.0722 * p[2] as f32 +} + +/// Mean luma and the share of black (< 2) pixels of the ground, columns `x0..x1`. +fn ground(img: &Rgba8, x0: usize, x1: usize) -> (f32, f32) { + let (mut sum, mut black, mut n) = (0.0, 0.0, 0.0); + for y in 20..H - 20 { + for x in x0..x1 { + let v = luma(img.data[y * W + x]); + sum += v; + black += f32::from(u8::from(v < 2.0)); + n += 1.0; + } + } + (sum / n, black / n) +} + +#[test] +fn v3_leaves_haze_free_texture_and_shadows_by_the_sky_alone() { + let ev = |a: f32, b: f32| (b / a).log2(); + for p in [Process::V1, Process::V3] { + let (m0, _) = ground(&shot(p, 0.0), W / 2 + 20, W); + let (m50, _) = ground(&shot(p, 50.0), W / 2 + 20, W); + let (_, black10) = ground(&shot(p, 10.0), W / 2, W / 2 + 12); + let (_, black50) = ground(&shot(p, 50.0), W / 2, W / 2 + 12); + eprintln!("{p:?}: ground {m0:.1} -> {m50:.1} at +50 ({:.2} EV); black by the sky {black10:.2} (+10) {black50:.2} (+50)", ev(m0, m50)); + if p == Process::V3 { + assert!(ev(m0, m50) > -0.25, "V3 darkens a haze-free ground by {:.2} EV at +50", ev(m0, m50)); + assert!(black10 < 0.01 && black50 < 0.01, "V3 clips shadows by the sky: {black10} {black50}"); + } else { + // V1 is frozen with the faults the issue measured + assert!(ev(m0, m50) < -0.4, "V1 changed: {:.2} EV", ev(m0, m50)); + } + } +} + +#[test] +fn v3_dehaze_still_clears_a_uniform_veil() { + // a hazy scene: a chequer lifted by a veil + let hazy = Rgb32f::from_fn(W, H, |x, y| [if (x / 6 + y / 6).is_multiple_of(2) { 0.42 } else { 0.6 }; 3]); + let contrast = |d: f64| { + let mut s = DevelopSettings { process: Process::V3.version(), ..DevelopSettings::default() }; + controls::set(&mut s, "effects.dehaze", d); + let img = render(&hazy, &SourceInfo::default(), &s, &RenderRequest::fit(W, H)).image; + let (a, b) = (luma(img.data[100 * W + 100]), luma(img.data[100 * W + 106])); + (a - b).abs() + }; + let (c0, c50, c100) = (contrast(0.0), contrast(50.0), contrast(100.0)); + assert!(c50 > c0 * 1.3 && c100 > c50, "{c0} {c50} {c100}"); +} + +#[test] +fn v3_pixel_never_goes_black_and_eases_in() { + // a shadow (0.05) whose blurred dark channel is the sky's: V1 clipped it to 0 at +10 + let air = 0.8; + for dz in [0.1, 0.25, 0.5, 1.0] { + let c = dehaze_v3_pixel([0.05, 0.06, 0.07], dz, 0.9, air); + assert!(c.iter().all(|v| *v > 0.0), "{dz}: {c:?}"); + } + let small = dehaze_v3_pixel([0.4; 3], 0.1, 0.5, air)[0]; + let v1_t = 1.0 - 0.95 * 0.1 * 0.5; + let v1 = (0.4 - air * (1.0 - v1_t)) / v1_t; + assert!((0.4 - small) < 0.6 * (0.4 - v1), "eases in: {small} vs V1 {v1}"); + assert_eq!(dehaze_v3_pixel([0.3, 0.2, 0.1], 0.0, 0.7, air), [0.3, 0.2, 0.1]); +} + +#[test] +fn patch_radius_only_from_v3_and_min_filter_erodes() { + let s = |p: Process| DevelopSettings { process: p.version(), ..DevelopSettings::default() }; + assert_eq!(local::dehaze_patch_radius(&s(Process::V1), 3000.0), 0); + assert_eq!(local::dehaze_patch_radius(&s(Process::V2), 3000.0), 0); + assert_eq!(local::dehaze_patch_radius(&s(Process::V3), 3000.0), 15); + assert_eq!(local::dehaze_patch_radius(&s(Process::V3), 1e9), local::DEHAZE_PATCH_MAX); + let p = lightcraft_raster::Plane::from_fn(9, 5, |x, y| if (x, y) == (4, 2) { 0.0 } else { 1.0 }); + let m = local::min_hv(&p, 1); + assert_eq!(m.get(3, 1), 0.0); + assert_eq!(m.get(5, 3), 0.0); + assert_eq!(m.get(6, 2), 1.0); + assert_eq!(m.get(0, 0), 1.0); +} + +#[test] +fn min_filter_matches_brute_force() { + for (w, h, r) in [(1, 1, 3), (7, 3, 1), (13, 11, 2), (40, 9, 5), (5, 30, 9)] { + let p = lightcraft_raster::Plane::from_fn(w, h, |x, y| ((x * 37 + y * 61) % 23) as f32); + let m = local::min_hv(&p, r); + for y in 0..h { + for x in 0..w { + let mut want = f32::INFINITY; + for yy in y.saturating_sub(r)..(y + r + 1).min(h) { + for xx in x.saturating_sub(r)..(x + r + 1).min(w) { + want = want.min(p.get(xx, yy)); + } + } + assert_eq!(m.get(x, y), want, "{w}x{h} r {r} at ({x}, {y})"); + } + } + } +} diff --git a/crates/pipeline/src/tests_dehaze_v4.rs b/crates/pipeline/src/tests_dehaze_v4.rs new file mode 100644 index 00000000000..13dffb1b3bc --- /dev/null +++ b/crates/pipeline/src/tests_dehaze_v4.rs @@ -0,0 +1,479 @@ +//! Dehaze and the rendering process (issue #1237): V4 gets its own dehaze; V1, V2 and V3 keep theirs, +//! and no stage cache ever hands one process another's work. + +use std::sync::Arc; + +use lightcraft_develop::{DevelopSettings, LocalAdjustments, Mask, MaskComponent, MaskOp, MaskShape, Process}; +use lightcraft_geom::Point; +use lightcraft_raster::{Rgb32f, Rgba8}; +use lightcraft_scenes::haze::{black_pct, grey_lch, halo_widths, hue_diff, lumas, median_luma, percentile}; +use lightcraft_scenes::hazy_valley; + +use crate::{OutputDepth, PixelWindow, RenderRequest, SourceInfo, StageCache, plan, render, render_cached}; + +const W: usize = 360; +const H: usize = 240; + +fn scene() -> Rgb32f { + hazy_valley(W, H) +} + +/// Settings on `process` with Dehaze `amount`, and with `local` also a gradient mask adding Dehaze. +fn dehazed(process: Process, amount: f64, local: bool) -> DevelopSettings { + let mut s = DevelopSettings { process: process.version(), ..DevelopSettings::default() }; + s.effects.dehaze = amount; + s.light.highlights = -40.0; + if local { + s.masks = vec![gradient_mask(0.0, 0.9, 40.0)]; + } + s +} + +/// A mask of one linear gradient from `(0.5, start)` to `(0.5, end)` with Dehaze `dehaze`. +fn gradient_mask(start: f64, end: f64, dehaze: f64) -> Mask { + Mask { + components: vec![MaskComponent { + name: None, + op: MaskOp::Add, + invert: false, + shape: MaskShape::Linear { start: Point::new(0.5, start), end: Point::new(0.5, end) }, + }], + adjust: LocalAdjustments { dehaze, ..Default::default() }, + ..Default::default() + } +} + +/// The scene-linear image doesn't depend on the process, so every process shares it (its keys are +/// the same); what does depend on it carries the process in its own key (the tone base) or has its +/// own cache (V4's haze map). Rendering through warm caches after a process switch is checked by +/// [`warm_caches_across_processes_match_fresh_renders`]. +#[test] +fn stage_caches_share_the_linear_image_across_processes() { + let src = scene(); + let info = SourceInfo::default(); + let req = RenderRequest::fit(W, H); + let keys = |p: Process| { + let s = dehazed(p, 30.0, false); + let pl = plan(&src, &info, &s, &req); + (pl.lin_key, pl.pre_nr_key, pl.geo, crate::local::base_key(&s, 4.0, 0)) + }; + let ks = Process::ALL.map(keys); + for (i, a) in ks.iter().enumerate() { + let Some(rest) = ks.get(i + 1..) else { continue }; + for b in rest { + assert_eq!((a.0, a.1, a.2), (b.0, b.1, b.2), "the linear image and its source are the same on every process"); + assert_ne!(a.3, b.3, "the tone base is the process's own"); + } + } +} + +/// V1 and V2 keep the Dehaze they always had (V1 and V2 differ only in the Highlights / Shadows +/// base, so without those they render alike), and V4 has its own: the same pixels as V2 and V3 +/// without Dehaze, others with it (globally, in a mask, in a window and at 16 bits). +#[test] +fn v1_and_v2_keep_their_dehaze_and_v4_has_its_own() { + let src = scene(); + let info = SourceInfo::default(); + let reqs = [ + RenderRequest::fit(W, H), + RenderRequest { depth: OutputDepth::U16, ..RenderRequest::fit(W, H) }, + RenderRequest { window: Some(PixelWindow { x: 60, y: 90, w: 200, h: 120 }), ..RenderRequest::fit(2 * W, 2 * H) }, + ]; + let plain = |p: Process, amount: f64, local: bool| DevelopSettings { light: Default::default(), ..dehazed(p, amount, local) }; + for amount in [-100.0, -35.0, 0.0, 25.0, 100.0] { + for local in [false, true] { + for req in &reqs { + let r1 = render(&src, &info, &plain(Process::V1, amount, local), req); + let r2 = render(&src, &info, &plain(Process::V2, amount, local), req); + let r3 = render(&src, &info, &plain(Process::V3, amount, local), req); + let r4 = render(&src, &info, &plain(Process::V4, amount, local), req); + assert!(r1.image == r2.image && r1.deep == r2.deep, "V1 vs V2: dehaze {amount}, mask {local}, {:?}", req.window); + let same = r2.image == r4.image && r2.deep == r4.deep; + assert_eq!(same, amount == 0.0 && !local, "V2 vs V4: dehaze {amount}, mask {local}, {:?}", req.window); + let same = r3.image == r4.image && r3.deep == r4.deep; + assert_eq!(same, amount == 0.0 && !local, "V3 vs V4: dehaze {amount}, mask {local}, {:?}", req.window); + } + } + } +} + +// ---- V4's Dehaze (issue #1237) ----------------------------------------------------------------- + +fn v4(src: &Rgb32f, amount: f64, req: &RenderRequest) -> Rgba8 { + let mut s = DevelopSettings { process: Process::V4.version(), ..DevelopSettings::default() }; + s.effects.dehaze = amount; + render(src, &SourceInfo::default(), &s, req).image +} + +/// (max, mean) of the per-channel 8-bit differences. +fn diff(a: &Rgba8, b: &Rgba8) -> (u8, f64) { + assert_eq!((a.width, a.height), (b.width, b.height)); + let (mut max, mut sum) = (0u8, 0u64); + for (p, q) in a.data.iter().zip(&b.data) { + for i in 0..3 { + let d = p[i].abs_diff(q[i]); + max = max.max(d); + sum += u64::from(d); + } + } + (max, sum as f64 / (3 * a.data.len().max(1)) as f64) +} + +/// The acceptance bands of #1237 on the hazy valley and the misty demo scenes: Dehaze clears haze +/// without making the photo much darker or crushing it to black. +#[test] +fn v4_dehaze_meets_the_acceptance_bands() { + // amount, median EV shift (low, high), most extra black (% of pixels) + let bands = [(25.0, -0.2, 0.0, 1.0), (50.0, -0.5, -0.2, 3.0), (100.0, -0.9, -0.4, 8.0)]; + let mut inputs = vec![("hazy valley".to_string(), scene())]; + for s in lightcraft_scenes::demo_library().into_iter().filter(|s| s.kind == lightcraft_scenes::Kind::MistyForest) { + inputs.push((s.name.clone(), s.render_fit(W))); + } + for (name, src) in &inputs { + let req = RenderRequest::fit(src.width, src.height); + let base = v4(src, 0.0, &req); + let (m0, b0) = (median_luma(&base), black_pct(&base)); + let mut last = 0.0f32; + for (amount, lo, hi, black) in bands { + let r = v4(src, amount, &req); + let ev = (median_luma(&r).max(1e-4) / m0.max(1e-4)).log2(); + let extra = black_pct(&r) - b0; + assert!((lo..=hi).contains(&ev), "{name} +{amount}: median {ev:+.2} EV, want {lo}..{hi}"); + assert!(extra <= black, "{name} +{amount}: {extra:.1} % more black, want ≀ {black}"); + assert!(ev <= last + 1e-3, "{name} +{amount}: darker with the amount ({last:+.2} β†’ {ev:+.2})"); + last = ev; + } + // and it does clear haze: more contrast (the 10th–90th percentile spread of the luminance, + // relative to the median) with the amount. (Only on the valley: in the demo fog a big sun + // dominates the spread, and Dehaze leaves the sky near the airlight alone.) + if name != "hazy valley" { + continue; + } + let spread = |i: &Rgba8| (percentile(lumas(i), 90) - percentile(lumas(i), 10)) / median_luma(i).max(1e-4); + let (s0, s50, s100) = (spread(&base), spread(&v4(src, 50.0, &req)), spread(&v4(src, 100.0, &req))); + assert!(s50 > s0 * 1.05 && s100 > s50 * 1.05, "{name}: contrast {s0:.3} β†’ +50 {s50:.3} β†’ +100 {s100:.3}"); + } +} + +/// Negative Dehaze is a gentle, near-neutral veil: at βˆ’100 the misty demo scenes' median rises +/// +0.4..+1.2 EV (V1 / V2: up to +1.5), βˆ’50 rises less, the shadows lift and no more pixels clip +/// to white. +#[test] +fn v4_negative_dehaze_is_a_gentle_veil() { + let mut inputs = vec![("hazy valley".to_string(), scene(), 0.0f32)]; + for s in lightcraft_scenes::demo_library().into_iter().filter(|s| s.kind == lightcraft_scenes::Kind::MistyForest) { + inputs.push((s.name.clone(), s.render_fit(W), 0.4)); + } + let pct = |img: &Rgba8, q: usize| percentile(lumas(img), q); + let white = |img: &Rgba8| img.data.iter().filter(|p| p[..3].iter().any(|&c| c >= 254)).count() as f32 / img.data.len().max(1) as f32 * 100.0; + for (name, src, lo) in &inputs { + let req = RenderRequest::fit(src.width, src.height); + let base = v4(src, 0.0, &req); + let m0 = median_luma(&base).max(1e-4); + let (half, full) = (v4(src, -50.0, &req), v4(src, -100.0, &req)); + let (ev50, ev100) = ((median_luma(&half) / m0).log2(), (median_luma(&full) / m0).log2()); + assert!((*lo..=1.2).contains(&ev100), "{name} βˆ’100: median {ev100:+.2} EV, want {lo}..1.2"); + assert!(ev50 > 0.0 && ev50 < ev100, "{name}: βˆ’50 {ev50:+.2} EV, βˆ’100 {ev100:+.2} EV"); + assert!(pct(&full, 5) > pct(&base, 5), "{name}: the shadows lift"); + assert!(white(&full) <= white(&base) + 0.5, "{name}: {:.1} % β†’ {:.1} % clipped white", white(&base), white(&full)); + } +} + +/// The hue of the valley's neutral grey patch drifts less than 2Β° between +25 and +100. +#[test] +fn v4_dehaze_keeps_the_hue_of_neutral_greys() { + let src = hazy_valley(900, 600); + let req = RenderRequest::fit(900, 600); + let hue = |img: &Rgba8| grey_lch(img)[2]; + let (h25, h100) = (hue(&v4(&src, 25.0, &req)), hue(&v4(&src, 100.0, &req))); + let drift = hue_diff(h100, h25); + assert!(drift.abs() < 2.0, "grey hue {h25:.1}Β° β†’ {h100:.1}Β° ({drift:+.1}Β°)"); +} + +/// No dark halo next to a bright edge, even at +100 (V1 makes one ~20 px wide at this size). +#[test] +fn v4_dehaze_makes_no_halos() { + let src = hazy_valley(900, 600); + let req = RenderRequest::fit(900, 600); + for amount in [50.0, 100.0] { + let (dark, bright) = halo_widths(&v4(&src, amount, &req)); + assert!(dark <= 2.0 && bright <= 2.0, "+{amount}: halo {dark:.1} px (dark side), {bright:.1} px (bright side)"); + } + // (the probe does see V1's) + let mut s = DevelopSettings { process: Process::V1.version(), ..DevelopSettings::default() }; + s.effects.dehaze = 100.0; + let (dark, _) = halo_widths(&render(&src, &SourceInfo::default(), &s, &req).image); + assert!(dark > 2.0, "V1's halo: {dark:.1} px"); +} + +/// A flat grey image has no haze to remove: every amount leaves it alone (within 1 LSB). +#[test] +fn v4_leaves_a_flat_grey_alone() { + for v in [0.03f32, 0.18, 0.6] { + let src = Rgb32f::filled(120, 80, [v; 3]); + let req = RenderRequest::fit(120, 80); + let base = v4(&src, 0.0, &req); + for amount in [-100.0, -50.0, 25.0, 50.0, 100.0] { + let (max, _) = diff(&base, &v4(&src, amount, &req)); + assert!(max <= 1, "grey {v}, dehaze {amount}: {max} LSB"); + } + } +} + +/// NaN, infinite, negative and black pixels never panic and never turn finite pixels into NaN. +#[test] +fn v4_dehaze_survives_hostile_pixels() { + let src = Rgb32f::from_fn(96, 64, |x, y| match (x + 3 * y) % 7 { + 0 => [f32::NAN, 0.2, 0.1], + 1 => [f32::INFINITY, 0.5, 0.5], + 2 => [-1.0, 0.0, 0.0], + 3 => [0.0; 3], + _ => [0.3, 0.32, 0.36], + }); + let req = RenderRequest { depth: OutputDepth::F32Linear, ..RenderRequest::fit(96, 64) }; + let deep = |amount: f64, local: bool| { + let s = DevelopSettings { light: Default::default(), ..dehazed(Process::V4, amount, local) }; + let r = render(&src, &SourceInfo::default(), &s, &req); + let Some(crate::DeepImage { samples: crate::DeepSamples::F32(v), .. }) = r.deep else { panic!("no float render") }; + v + }; + let base = deep(0.0, false); + for amount in [-100.0, -40.0, 30.0, 100.0] { + for local in [false, true] { + let r = deep(amount, local); + for (i, (a, b)) in base.iter().zip(&r).enumerate() { + assert!(!a.is_finite() || b.is_finite(), "dehaze {amount}, mask {local}: sample {i} {a} β†’ {b}"); + } + } + } + // a black frame + let black = Rgb32f::filled(40, 30, [0.0; 3]); + for amount in [-100.0, 100.0] { + assert!(v4(&black, amount, &RenderRequest::fit(40, 30)).data.iter().all(|p| p[..3] == [0, 0, 0] || amount < 0.0)); + } + // an empty source has no haze map to sample (and doesn't panic building one) + let s = DevelopSettings { process: Process::V4.version(), ..DevelopSettings::default() }; + let empty = Rgb32f::new(0, 0); + let frame = crate::geometry::Frame::new(0, 0, &s, true); + let map = crate::haze::for_frame(&empty, &SourceInfo::default(), &s, &frame, false); + assert_eq!(crate::haze::for_frame(&empty, &SourceInfo::default(), &s, &frame, true).size(), (1, 1)); + assert_eq!(map.size(), (1, 1)); +} + +/// A zoomed window samples the whole frame's haze map: it matches the same pixels of the whole +/// render (within 1/255 mean, 3/255 max), at every amount, with a mask too. +#[test] +fn v4_window_matches_the_whole_render() { + let src = scene(); + let info = SourceInfo::default(); + let full = RenderRequest::fit(4 * W, 4 * H); + let win = PixelWindow { x: 700, y: 500, w: 320, h: 240 }; + for amount in [-100.0, 40.0, 100.0] { + for local in [false, true] { + let s = DevelopSettings { light: Default::default(), ..dehazed(Process::V4, amount, local) }; + let whole = render(&src, &info, &s, &full).image.crop(win.x, win.y, win.w, win.h); + let part = render(&src, &info, &s, &RenderRequest { window: Some(win), ..full }).image; + let (max, mean) = diff(&whole, &part); + assert!(max <= 3 && mean <= 1.0, "dehaze {amount}, mask {local}: max {max}, mean {mean:.3}"); + } + } +} + +/// Preview and export dehaze alike: a small render matches the large one scaled down about as +/// well as without Dehaze (the haze map is the same for both). +#[test] +fn v4_preview_matches_the_export() { + let src = hazy_valley(1440, 960); + let (small, big) = (RenderRequest::fit(360, 240), RenderRequest::fit(1440, 960)); + let shrink = |i: &Rgba8| { + Rgba8::from_fn(i.width / 4, i.height / 4, |x, y| { + let mut acc = [0.0f32; 3]; + for dy in 0..4 { + for dx in 0..4 { + let p = i.get(4 * x + dx, 4 * y + dy); + for k in 0..3 { + acc[k] += lightcraft_color::transfer::decode_srgb8(p[k]); + } + } + } + let e = acc.map(|v| (lightcraft_color::transfer::linear_to_srgb(v / 16.0) * 255.0).round() as u8); + [e[0], e[1], e[2], 255] + }) + }; + let gap = |amount: f64| diff(&v4(&src, amount, &small), &shrink(&v4(&src, amount, &big))).1; + let g0 = gap(0.0); + for amount in [-100.0, 50.0, 100.0] { + let g = gap(amount); + assert!(g <= g0 + 1.0, "dehaze {amount}: preview vs export mean {g:.3} LSB (without Dehaze {g0:.3})"); + } +} + +/// A mask's Dehaze goes through the same path: a mask over the whole frame dehazes like the +/// slider, mask and slider add up (to Β±100 at most), and outside a mask nothing changes. +#[test] +fn v4_mask_dehaze_adds_to_the_slider() { + let src = scene(); + let info = SourceInfo::default(); + let req = RenderRequest::fit(W, H); + let with = |global: f64, local: f64, start: f64, end: f64| { + let mut s = DevelopSettings { process: Process::V4.version(), ..DevelopSettings::default() }; + s.effects.dehaze = global; + s.masks = vec![gradient_mask(start, end, local)]; + render(&src, &info, &s, &req).image + }; + let everywhere = |g, l| with(g, l, 3.0, 4.0); + let slider = |a| v4(&src, a, &req); + assert!(diff(&everywhere(0.0, 60.0), &slider(60.0)).0 <= 1, "a whole-frame mask is the slider"); + assert!(diff(&everywhere(-30.0, 80.0), &slider(50.0)).0 <= 1, "mask and slider add"); + assert!(diff(&everywhere(80.0, 60.0), &slider(100.0)).0 <= 1, "clamped to +100"); + assert!(diff(&everywhere(-80.0, -60.0), &slider(-100.0)).0 <= 1, "clamped to βˆ’100"); + // a mask over the top half: the bottom rows are the undehazed photo's + let half = with(0.0, 100.0, 0.0, 0.5); + let base = slider(0.0); + let rows = |i: &Rgba8, y0: usize| i.crop(0, y0, W, H - y0); + assert_eq!(rows(&half, H * 6 / 10), rows(&base, H * 6 / 10), "outside the mask"); + assert!(diff(&rows(&half, 0).crop(0, 0, W, H / 4), &base.crop(0, 0, W, H / 4)).0 > 5, "inside the mask"); +} + +/// Moving a dehazed photo between processes (Update to Current Process, then undo) with warm +/// caches renders what a fresh render does. +#[test] +fn warm_caches_across_processes_match_fresh_renders() { + let src = Arc::new(scene()); + let info = SourceInfo { raw: true, ..Default::default() }; + let cache = StageCache::default(); + for req in + [RenderRequest::fit(W, H), RenderRequest { window: Some(PixelWindow { x: 40, y: 30, w: 180, h: 150 }), ..RenderRequest::fit(2 * W, 2 * H) }] + { + for p in [Process::V1, Process::V4, Process::V2, Process::V3, Process::V4, Process::V1, Process::V3, Process::V2] { + let s = dehazed(p, 45.0, true); + let warm = render_cached(&src, &info, &s, &req, &cache).image; + assert!(warm == render(&src, &info, &s, &req).image, "{p:?}, window {:?}", req.window); + } + } +} + +/// The V4 haze map is built only when V4 dehazes (globally or in a mask), and every render of the +/// photo gets the same one: preview and export sizes, a zoomed window, any exposure. +#[test] +fn v4_plans_carry_one_haze_map_per_photo() { + let src = scene(); + let info = SourceInfo::default(); + let req = RenderRequest::fit(W, H); + assert!(plan(&src, &info, &dehazed(Process::V4, 0.0, false), &req).haze.is_none()); + assert!(plan(&src, &info, &dehazed(Process::V2, 50.0, true), &req).haze.is_none()); + assert!(plan(&src, &info, &dehazed(Process::V1, 50.0, false), &req).haze.is_none()); + let local_only = plan(&src, &info, &dehazed(Process::V4, 0.0, true), &req).haze; + let Some(map) = plan(&src, &info, &dehazed(Process::V4, 50.0, false), &req).haze else { panic!("no haze map for V4 Dehaze") }; + assert!(local_only.is_some_and(|m| *m == *map), "a mask's dehaze uses the same map"); + let reqs = [ + RenderRequest::fit(W / 3, H / 3), + RenderRequest::fit(4 * W, 4 * H), + RenderRequest { window: Some(PixelWindow { x: 300, y: 200, w: 150, h: 90 }), ..RenderRequest::fit(3 * W, 3 * H) }, + RenderRequest { depth: OutputDepth::U16, ..req }, + ]; + for (i, r) in reqs.iter().enumerate() { + for amount in [-60.0, 50.0, 100.0] { + let mut s = dehazed(Process::V4, amount, false); + s.light.exposure = 1.5; + let Some(m) = plan(&src, &info, &s, r).haze else { panic!("request {i}: no haze map") }; + assert!(*m == *map, "request {i}, dehaze {amount}: another haze map"); + } + } + // (the scene is smaller than the proxy edge: the proxy is the frame at its own size) + assert_eq!(map.size(), (W, H)); +} + +/// A large photo's map is built on the fixed-size proxy, once: the next plan reuses it. +#[test] +fn v4_haze_map_is_built_once() { + let src = hazy_valley(3000, 2000); + let info = SourceInfo::default(); + let s = dehazed(Process::V4, 50.0, false); + let a = plan(&src, &info, &s, &RenderRequest::fit(1500, 1000)).haze; + let b = plan(&src, &info, &s, &RenderRequest::fit(600, 400)).haze; + let (Some(a), Some(b)) = (a, b) else { panic!("no haze map") }; + // (by value: other tests share the process-wide cache and may evict it in between) + assert!(*a == *b, "the second plan gets the same map"); + assert_eq!(a.size(), (768, 512)); +} + +/// The cached map follows everything it depends on: the white balance, the crop, the orientation, +/// the source's content and the camera's local tone mapping give another map; Exposure doesn't. +/// A draft (a drag) that misses reuses the latest map of the photo instead of building one. +#[test] +fn v4_haze_map_follows_what_it_depends_on() { + use lightcraft_develop::WbMode; + // (sizes no other test uses: its own cache entries) + let (w, h) = (W + 7, H + 5); + let src = hazy_valley(w, h); + let info = SourceInfo { raw: true, ..Default::default() }; + let req = RenderRequest::fit(w, h); + let base = dehazed(Process::V4, 50.0, false); + let map = |src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings, req: &RenderRequest| { + let Some(m) = plan(src, info, s, req).haze else { panic!("no haze map") }; + m + }; + let m0 = map(&src, &info, &base, &req); + let mut exposed = base.clone(); + exposed.light.exposure = 1.0; + assert!(*map(&src, &info, &exposed, &req) == *m0, "exposure keeps the map"); + let mut warm = base.clone(); + (warm.wb.mode, warm.wb.temp) = (WbMode::Custom, 3500.0); + let mut cropped = base.clone(); + cropped.crop.geometry = lightcraft_geom::crop_fit_angle(w as f64, h as f64, 8.0, Some(1.0)); + let mut turned = base.clone(); + turned.orientation = lightcraft_geom::Orientation::Rotate90; + for (what, s) in [("white balance", &warm), ("crop", &cropped), ("orientation", &turned)] { + assert!(*map(&src, &info, s, &req) != *m0, "{what} gives another map"); + } + let brighter = Rgb32f { data: src.data.iter().map(|p| [p[0] * 1.3, p[1], p[2] * 0.8]).collect(), ..src.clone() }; + assert!(*map(&brighter, &info, &base, &req) != *m0, "other pixels give another map"); + // a drag: the white balance's draft reuses the map, the final render builds its own + let draft = RenderRequest { quality: crate::Quality::Draft, ..req }; + let drag = |temp: f64| { + let mut s = base.clone(); + (s.wb.mode, s.wb.temp) = (WbMode::Custom, temp); + s + }; + let dragged = drag(6100.0); + // (by value, and again with another tick if it missed: other tests share the process-wide + // cache and may evict the photo's map between the two plans; a miss caches that tick's own + // map; a draft that never reuses the photo's misses every time) + let reused = [6100.0, 6200.0, 6300.0].into_iter().any(|temp| { + let m1 = map(&src, &info, &base, &req); + *map(&src, &info, &drag(temp), &draft) == *m1 + }); + assert!(reused, "a draft reuses the photo's latest map"); + assert!(*map(&src, &info, &dragged, &req) != *m0, "the final render builds the exact map"); +} + +/// The map is measured on the pixels it is applied to: with the camera's local tone mapping (a +/// ProRAW gain table) on, it sees the gain, and toggling it gives another map. +#[test] +fn v4_haze_map_sees_the_camera_local_tone_mapping() { + use lightcraft_raw::gaintable::{GainTableMap, SourcePlacement}; + let (w, h) = (W + 11, H + 3); + let src = hazy_valley(w, h); + // gain 1 on the left edge, 4 on the right, whatever the colour + let map = GainTableMap { + points_v: 1, + points_h: 2, + points_n: 2, + spacing_v: 1.0, + spacing_h: 1.0, + origin_v: 0.0, + origin_h: 0.0, + weights: [0.0, 0.0, 0.0, 0.0, 1.0], + gamma: 1.0, + gains: vec![1.0, 1.0, 4.0, 4.0], + }; + let placement = SourcePlacement { rect: [0.0, 0.0, 1.0, 1.0], orientation: lightcraft_geom::Orientation::Normal }; + let info = SourceInfo { raw: true, local_tone: Some(Arc::new(crate::local_tone::LocalTone { map, placement })), ..Default::default() }; + let req = RenderRequest::fit(w, h); + let off = dehazed(Process::V4, 50.0, false); + let mut on = off.clone(); + on.profile.camera_local_tone = true; + let (Some(a), Some(b)) = (plan(&src, &info, &off, &req).haze, plan(&src, &info, &on, &req).haze) else { panic!("no haze map") }; + assert!(*a != *b, "the local tone mapping changes the haze map"); +} diff --git a/crates/scenes/src/haze.rs b/crates/scenes/src/haze.rs new file mode 100644 index 00000000000..560508363a7 --- /dev/null +++ b/crates/scenes/src/haze.rs @@ -0,0 +1,261 @@ +//! A hazy valley for measuring Dehaze (issue #1237): ridges that fade with distance into a bright +//! bluish-grey airlight, a sky, a sharp bright/dark edge and a neutral grey patch in the foreground. +//! +//! Every pixel follows the haze model `I = JΒ·t + AΒ·(1 βˆ’ t)` with a known airlight `A` +//! (`AIRLIGHT`) and a transmission per depth layer, so a dehaze can be judged against the +//! scene it should recover. Not part of the demo library: a test and measurement scene. + +use lightcraft_color::transfer::{decode_srgb8, linear_to_srgb}; +use lightcraft_color::{REC2020, SRGB}; +use lightcraft_raster::{Rgb32f, Rgba8}; +use rayon::prelude::*; + +use crate::noise::fbm; + +/// The airlight every layer blends towards, linear sRGB (a bright bluish grey). +const AIRLIGHT: [f32; 3] = [0.62, 0.68, 0.78]; + +/// Where the measurement features sit, in normalised image coordinates (`0..1` across and down). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct HazeLayout { + /// The bright block spans `bright_x0..edge_x`, the dark block `edge_x..dark_x1`, both + /// `block_y0..block_y1`: a sharp vertical bright/dark edge at `edge_x`. + pub bright_x0: f32, + pub edge_x: f32, + pub dark_x1: f32, + pub block_y0: f32, + pub block_y1: f32, + /// The neutral grey patch (albedo 0.18, under the foreground's haze): `[x0, y0, x1, y1]`. + pub grey: [f32; 4], + /// Transmission of the foreground layer the blocks and the patch sit in. + pub foreground_t: f32, +} + +/// The layout of [`hazy_valley`]. +pub const HAZE_LAYOUT: HazeLayout = + HazeLayout { bright_x0: 0.58, edge_x: 0.71, dark_x1: 0.86, block_y0: 0.74, block_y1: 0.93, grey: [0.12, 0.76, 0.26, 0.92], foreground_t: 0.87 }; + +/// Ridges from far to near: (crest base `v`, crest amplitude, frequency, transmission, albedo). +const RIDGES: [(f32, f32, f32, f32, [f32; 3]); 4] = [ + (0.34, 0.07, 3.0, 0.22, [0.10, 0.12, 0.09]), + (0.44, 0.07, 4.0, 0.45, [0.08, 0.11, 0.05]), + (0.55, 0.06, 5.0, 0.68, [0.12, 0.10, 0.05]), + (0.66, 0.05, 6.0, 0.87, [0.09, 0.13, 0.04]), +]; + +const SEED: u32 = 1237; + +/// Render the hazy valley at `w Γ— h` (meant for 3:2; any size works), linear Rec.2020. +pub fn hazy_valley(w: usize, h: usize) -> Rgb32f { + let mut img = Rgb32f::new(w, h); + if w == 0 || h == 0 { + return img; + } + let to2020 = SRGB.to_space(&REC2020).to_f32(); + img.data.par_chunks_mut(w).enumerate().for_each(|(y, row)| { + for (x, px) in row.iter_mut().enumerate() { + let u = (x as f32 + 0.5) / w as f32; + let v = (y as f32 + 0.5) / h as f32; + let c = shade(u, v); + let m = &to2020; + *px = [ + (m[0][0] * c[0] + m[0][1] * c[1] + m[0][2] * c[2]).max(0.0), + (m[1][0] * c[0] + m[1][1] * c[1] + m[1][2] * c[2]).max(0.0), + (m[2][0] * c[0] + m[2][1] * c[1] + m[2][2] * c[2]).max(0.0), + ]; + } + }); + img +} + +fn hazed(j: [f32; 3], t: f32) -> [f32; 3] { + let a = AIRLIGHT; + [j[0] * t + a[0] * (1.0 - t), j[1] * t + a[1] * (1.0 - t), j[2] * t + a[2] * (1.0 - t)] +} + +fn shade(u: f32, v: f32) -> [f32; 3] { + let l = HAZE_LAYOUT; + // The measurement features sit in the nearest layer. + let in_blocks = (l.block_y0..l.block_y1).contains(&v); + if in_blocks && (l.bright_x0..l.edge_x).contains(&u) { + return hazed([0.85, 0.85, 0.82], l.foreground_t); + } + if in_blocks && (l.edge_x..l.dark_x1).contains(&u) { + return hazed([0.015, 0.015, 0.02], l.foreground_t); + } + let [gx0, gy0, gx1, gy1] = l.grey; + if (gx0..gx1).contains(&u) && (gy0..gy1).contains(&v) { + return hazed([0.18, 0.18, 0.18], l.foreground_t); + } + // Nearest ridge whose crest is above this point. + for (k, &(base, amp, freq, t, albedo)) in RIDGES.iter().enumerate().rev() { + let seed = SEED.wrapping_add(k as u32 * 17); + let crest = base + amp * (fbm(u * freq, 0.5, seed, 4) * 0.5 + 0.5); + if v >= crest { + // Contrasty texture: lit faces and dark gullies. + let tex = fbm(u * 24.0, v * 24.0, seed ^ 0x7e, 4) * 0.5 + 0.5; + let light = 0.25 + 2.2 * tex * tex; + return hazed([albedo[0] * light, albedo[1] * light, albedo[2] * light], t); + } + } + // Sky: the airlight at the horizon, bluer and a little darker towards the zenith. + let elev = (1.0 - v / RIDGES[0].0).clamp(0.0, 1.0); + let zenith = [0.30, 0.45, 0.80]; + let a = AIRLIGHT; + let s = elev.powf(0.8); + let wisp = 1.0 + 0.04 * fbm(u * 3.0, v * 9.0, SEED ^ 0x5c, 3); + [(a[0] + (zenith[0] - a[0]) * s) * wisp, (a[1] + (zenith[1] - a[1]) * s) * wisp, (a[2] + (zenith[2] - a[2]) * s) * wisp] +} + +// ---- measuring a render of the valley (shared by the Dehaze tests and `examples/dehaze_report.rs`) + +/// A pixel is clipped to black when every channel is at most this (8-bit, display encoded). +pub const CLIP_BLACK: u8 = 2; +/// A halo pixel is darker than the interior of its block by more than this (8-bit luma). +pub const HALO_STEP: f32 = 10.0; + +/// Linear sRGB of an 8-bit sRGB pixel. +pub fn linear8(p: [u8; 4]) -> [f32; 3] { + [decode_srgb8(p[0]), decode_srgb8(p[1]), decode_srgb8(p[2])] +} + +/// Relative luminance (Rec.709 weights) of a linear sRGB colour. +pub fn luminance709(c: [f32; 3]) -> f32 { + 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2] +} + +/// Relative luminance (linear) of an 8-bit sRGB pixel. +pub fn luminance8(p: [u8; 4]) -> f32 { + luminance709(linear8(p)) +} + +/// Display-encoded luminance of an 8-bit sRGB pixel, 0..255. +pub fn luma8(p: [u8; 4]) -> f32 { + linear_to_srgb(luminance8(p).clamp(0.0, 1.0)) * 255.0 +} + +/// The value `pct` % of the way up the sorted `v` (index `lenΒ·pct/100`, clamped; 0 when empty). +pub fn percentile(mut v: Vec, pct: usize) -> f32 { + v.sort_by(f32::total_cmp); + let i = (v.len().saturating_mul(pct) / 100).min(v.len().saturating_sub(1)); + v.get(i).copied().unwrap_or(0.0) +} + +/// Luminance (linear) of every pixel of `img`. +pub fn lumas(img: &Rgba8) -> Vec { + img.data.iter().map(|&p| luminance8(p)).collect() +} + +/// Median linear luminance of `img`. +pub fn median_luma(img: &Rgba8) -> f32 { + percentile(lumas(img), 50) +} + +/// Share (%) of the pixels of `img` clipped to black ([`CLIP_BLACK`]). +pub fn black_pct(img: &Rgba8) -> f32 { + let n = img.data.iter().filter(|p| p[0] <= CLIP_BLACK && p[1] <= CLIP_BLACK && p[2] <= CLIP_BLACK).count(); + 100.0 * n as f32 / img.data.len().max(1) as f32 +} + +/// Width in pixels (mean over the middle rows of the blocks) of the band next to the valley's +/// bright/dark edge ([`HAZE_LAYOUT`]) that is darker than the interior of its block by more than +/// [`HALO_STEP`]: on the dark side and on the bright side. +pub fn halo_widths(img: &Rgba8) -> (f32, f32) { + let l = HAZE_LAYOUT; + let (w, h) = (img.width as f32, img.height as f32); + let px = |u: f32| ((u * w) as usize).min(img.width.saturating_sub(1)); + let (edge, bright0, dark1) = (px(l.edge_x), px(l.bright_x0), px(l.dark_x1)); + let span = l.block_y1 - l.block_y0; + let (y0, y1) = (((l.block_y0 + span * 0.25) * h) as usize, ((l.block_y1 - span * 0.25) * h) as usize); + let (mut dark_sum, mut bright_sum, mut rows) = (0.0f32, 0.0f32, 0.0f32); + for y in y0..y1.min(img.height) { + let luma = |x: usize| luma8(img.get(x, y)); + // Interiors: the outer half of each block, away from the edge. + let dark_ref = percentile((dark1 - (dark1 - edge) / 2..dark1.saturating_sub(2)).map(luma).collect(), 50); + let bright_ref = percentile((bright0 + 2..bright0 + (edge - bright0) / 2).map(luma).collect(), 50); + dark_sum += (edge..dark1).take_while(|&x| luma(x) < dark_ref - HALO_STEP).count() as f32; + bright_sum += (bright0..edge).rev().take_while(|&x| luma(x) < bright_ref - HALO_STEP).count() as f32; + rows += 1.0; + } + (dark_sum / rows.max(1.0), bright_sum / rows.max(1.0)) +} + +/// CIE L*C*hΒ° (D65) of the mean colour of the inner part of the valley's grey patch. +pub fn grey_lch(img: &Rgba8) -> [f32; 3] { + let [x0, y0, x1, y1] = HAZE_LAYOUT.grey; + let (w, h) = (img.width as f32, img.height as f32); + let (mx, my) = ((x1 - x0) * 0.2, (y1 - y0) * 0.2); + let (xa, xb) = (((x0 + mx) * w) as usize, ((x1 - mx) * w) as usize); + let (ya, yb) = (((y0 + my) * h) as usize, ((y1 - my) * h) as usize); + let (mut sum, mut n) = ([0.0f32; 3], 0.0f32); + for y in ya..yb.min(img.height) { + for x in xa..xb.min(img.width) { + let c = linear8(img.get(x, y)); + sum = [sum[0] + c[0], sum[1] + c[1], sum[2] + c[2]]; + n += 1.0; + } + } + let c = sum.map(|v| v / n.max(1.0)); + let [l, a, b] = lab(c); + [l, a.hypot(b), b.atan2(a).to_degrees().rem_euclid(360.0)] +} + +/// CIE L*a*b* (D65) of a linear sRGB colour. +fn lab(c: [f32; 3]) -> [f32; 3] { + let x = 0.4124 * c[0] + 0.3576 * c[1] + 0.1805 * c[2]; + let y = luminance709(c); + let z = 0.0193 * c[0] + 0.1192 * c[1] + 0.9505 * c[2]; + let f = |t: f32| if t > 0.008_856 { t.cbrt() } else { 7.787 * t + 16.0 / 116.0 }; + let (fx, fy, fz) = (f(x / 0.950_47), f(y), f(z / 1.088_83)); + [116.0 * fy - 16.0, 500.0 * (fx - fy), 200.0 * (fy - fz)] +} + +/// Signed difference `a βˆ’ b` of two hues (degrees), in βˆ’180..180. +pub fn hue_diff(a: f32, b: f32) -> f32 { + (a - b + 180.0).rem_euclid(360.0) - 180.0 +} + +#[cfg(test)] +mod tests { + use super::*; + + fn at(img: &Rgb32f, u: f32, v: f32) -> [f32; 3] { + img.get(((u * img.width as f32) as usize).min(img.width - 1), ((v * img.height as f32) as usize).min(img.height - 1)) + } + + #[test] + fn the_valley_is_deterministic_finite_and_hazy() { + let a = hazy_valley(150, 100); + assert_eq!(a, hazy_valley(150, 100)); + assert!(a.data.iter().all(|p| p.iter().all(|v| v.is_finite() && *v >= 0.0))); + assert!(hazy_valley(0, 4).data.is_empty()); + // Far ridges are brighter (hazier) than near ones on average. + let row_mean = |v: f32| (0..150).map(|x| at(&a, x as f32 / 150.0, v)[1]).sum::() / 150.0; + assert!(row_mean(0.43) > row_mean(0.70), "{} vs {}", row_mean(0.43), row_mean(0.70)); + } + + #[test] + fn the_measurements_are_sane_and_never_panic() { + assert_eq!(percentile(vec![], 50), 0.0); + assert_eq!(percentile(vec![3.0, 1.0, 2.0, 4.0], 50), 3.0); + assert_eq!(percentile(vec![3.0, 1.0, 2.0], 100), 3.0); + let empty = Rgba8::new(0, 0); + assert_eq!((median_luma(&empty), black_pct(&empty), halo_widths(&empty)), (0.0, 0.0, (0.0, 0.0))); + let black = Rgba8::from_fn(30, 20, |_, _| [0, 0, 0, 255]); + assert_eq!(black_pct(&black), 100.0); + assert!((hue_diff(350.0, 10.0) + 20.0).abs() < 1e-4); + } + + #[test] + fn the_features_are_where_the_layout_says() { + let img = hazy_valley(600, 400); + let l = HAZE_LAYOUT; + let mid = (l.block_y0 + l.block_y1) / 2.0; + let bright = at(&img, l.edge_x - 0.02, mid); + let dark = at(&img, l.edge_x + 0.02, mid); + assert!(bright[1] > 0.6 && dark[1] < 0.15, "{bright:?} {dark:?}"); + let [x0, y0, x1, y1] = l.grey; + let g = at(&img, (x0 + x1) / 2.0, (y0 + y1) / 2.0); + assert!(g[1] > 0.2 && g[1] < 0.3, "{g:?}"); + } +} diff --git a/crates/scenes/src/lib.rs b/crates/scenes/src/lib.rs index 11fd8685d9e..78bf3525059 100644 --- a/crates/scenes/src/lib.rs +++ b/crates/scenes/src/lib.rs @@ -7,12 +7,14 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod haze; mod noise; mod paint; use lightcraft_raster::Rgb32f; use serde::Serialize; +pub use haze::{HAZE_LAYOUT, HazeLayout, hazy_valley}; pub use paint::render_srgb_linear; /// Kinds of scene the generator knows. diff --git a/crates/ui-egui/src/render.rs b/crates/ui-egui/src/render.rs index 64ab067b7d7..6ead2fd879b 100644 --- a/crates/ui-egui/src/render.rs +++ b/crates/ui-egui/src/render.rs @@ -562,6 +562,7 @@ impl Renderer { self.thumb_inputs.clear(); self.textures.clear(); self.stages.clear(); + lightcraft_pipeline::haze::clear_cache(); self.quick_tried.clear(); self.failed.clear(); self.prefetched.clear(); @@ -933,6 +934,8 @@ impl Renderer { self.stages_trimmed += 1; } } + // (V4's haze maps stay: their cache is bounded on its own, `haze::CACHE_KEEP` maps of a few + // MB, and holds the open photo's, which its next render would otherwise rebuild) } /// What the renderer holds: per-view stage caches (CPU images and GPU buffers) and textures. @@ -942,7 +945,7 @@ impl Renderer { let tex: usize = self.textures.values().map(|t| t.size[0] * t.size[1] * 4).sum(); let copies: usize = self.textures.values().filter_map(|t| t.pixels.as_ref()).map(|p| p.pixels.len() * 4).sum(); serde_json::json!({ - "stageCaches": {"count": self.stages.len(), "cpuBytes": cpu, "gpuBytes": gpu, "budgetBytes": self.stage_budget(), "trimmed": self.stages_trimmed, "sharedSourceBytes": lightcraft_engine::gpu::shared_source_bytes()}, + "stageCaches": {"count": self.stages.len(), "cpuBytes": cpu, "gpuBytes": gpu, "budgetBytes": self.stage_budget(), "trimmed": self.stages_trimmed, "sharedSourceBytes": lightcraft_engine::gpu::shared_source_bytes(), "hazeMapBytes": lightcraft_pipeline::haze::cache_bytes()}, "textures": {"count": self.textures.len(), "bytes": tex, "cpuCopyBytes": copies}, }) } @@ -1612,6 +1615,28 @@ mod stage_budget_tests { assert_eq!(r.stages_trimmed, 1, "and nothing is trimmed again"); } + // Trimming the views' stage caches keeps V4's haze maps (bounded on their own, and the open + // photo's would be rebuilt on its next render); forgetting everything drops them + #[test] + fn trimming_stage_caches_keeps_the_haze_maps() { + use lightcraft_engine::pipeline::{RenderRequest, SourceInfo, render_cached}; + use lightcraft_pipeline::haze::clears_on_this_thread; + let src = std::sync::Arc::new(lightcraft_raster::Rgb32f::from_fn(320, 240, |x, y| [x as f32 / 320.0, y as f32 / 240.0, 0.3])); + let mut r = Renderer::default(); + let cache: Arc = Default::default(); + let mut s = lightcraft_engine::develop::DevelopSettings::default(); + s.effects.clarity = 50.0; + render_cached(&src, &SourceInfo::default(), &s, &RenderRequest::fit(320, 240), &cache); + r.stages.insert(Slot::Hover, cache); + r.stage_budget_override = Some(0); + let before = clears_on_this_thread(); + r.trim_stages(); + assert_eq!(r.stages_trimmed, 1, "the hover render's cache went"); + assert_eq!(clears_on_this_thread(), before, "the haze maps stayed"); + r.forget_all(); + assert_eq!(clears_on_this_thread(), before + 1, "forgetting everything drops them"); + } + // The renderer counts and trims what it holds, and says so #[test] fn the_renderer_reports_its_stage_budget() { @@ -1620,6 +1645,7 @@ mod stage_budget_tests { assert!(m["stageCaches"]["budgetBytes"].as_u64().unwrap() > 0, "{m}"); assert_eq!(m["stageCaches"]["trimmed"], 0); assert!(m["stageCaches"]["sharedSourceBytes"].is_u64(), "the one device copy of a big original is reported: {m}"); + assert!(m["stageCaches"]["hazeMapBytes"].is_u64(), "and the V4 Dehaze haze maps: {m}"); } } diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 31ecbf8c2c4..7ba920d5176 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -65,7 +65,7 @@ filmstrip is visible. | `engine.commands` | β€” | Engine + UI commands: id, label, menu, shortcut, params doc, enabled | | `ui.menu.list` | β€” | Menu entries (flat: id, label, menu path, shortcut, enabled) | | `ui.menu.tree` | β€” | The menu bar as shown (File … Help): items `{id, params?, label, shortcut?, enabled, checked?}`, separators, submenus β€” the model behind the native macOS menu bar and the in-window menus | -| `ui.inspect` | β€” | UI state, window, `loupe` (`source`, `pending`, `failed` = why its render failed, else `null`, and `region: {full, window, pending}` when a zoomed view also renders the window on screen at no more than 100 % β€” `full` is the frame it is cut from, `window` its `[x, y, w, h]` β€” and `regionBefore` for the Before side of a Before/After view), canvas/image rects, `scroll: {grid, filmstrip}` (scroll offsets in points, `null` until drawn), active photo, selection, perf (`frameMs` = layout, `logicMs` = per-frame logic before it, `updateMs` = both, `maxUpdateMs`, `fps`, render queue …, `gpu` = adapter in use, `gpuReason` = why renders don't use the GPU, `gpuFallback` = latest render redone on the CPU and why β€” see `docs/gpu-pipeline.md`), status, memory (bytes per cache, see `library.memory`; plus stage caches β€” `budgetBytes`, `trimmed`, `sharedSourceBytes` (the one device copy of a big original) β€” and textures), `export: {running: {total, done, current} \| null, last}`, `notices` (warnings waiting to be shown, e.g. a damaged settings file; OK = `button:noticeOk`), `quitPrompt` (why quitting was stopped: tasks that would be cut short are running β€” `button:quitAnyway` cancels them and quits, `button:quitCancel` keeps working β€” or unsaved changes: `button:quitRetry` / `button:quitAnyway` / `button:quitCancel`), `import: {done, total, imported, cancelled} \| null` (an import runs on a worker thread), `tasks` (other background work: `Find Missing Photos`, `Auto Import`), `activity` (every long-running task in flight as the activity stack in the top-left corner shows it, same shape as `activity.list`; a row appears once its task is 0.5 s old, ids `activity:row:`, βœ• = `activity:cancel:`, `activity:more` expands past 3 rows), `fileDialogs` (commands waiting on a native file dialog, which runs off the UI thread; they run again with the answer when it closes), `copied` (the text the UI last put on the clipboard, `null` until something is copied) | +| `ui.inspect` | β€” | UI state, window, `loupe` (`source`, `pending`, `failed` = why its render failed, else `null`, and `region: {full, window, pending}` when a zoomed view also renders the window on screen at no more than 100 % β€” `full` is the frame it is cut from, `window` its `[x, y, w, h]` β€” and `regionBefore` for the Before side of a Before/After view), canvas/image rects, `scroll: {grid, filmstrip}` (scroll offsets in points, `null` until drawn), active photo, selection, perf (`frameMs` = layout, `logicMs` = per-frame logic before it, `updateMs` = both, `maxUpdateMs`, `fps`, render queue …, `gpu` = adapter in use, `gpuReason` = why renders don't use the GPU, `gpuFallback` = latest render redone on the CPU and why β€” see `docs/gpu-pipeline.md`), status, memory (bytes per cache, see `library.memory`; plus stage caches β€” `budgetBytes`, `trimmed`, `sharedSourceBytes` (the one device copy of a big original), `hazeMapBytes` (the cached haze maps of V4 Dehaze) β€” and textures), `export: {running: {total, done, current} \| null, last}`, `notices` (warnings waiting to be shown, e.g. a damaged settings file; OK = `button:noticeOk`), `quitPrompt` (why quitting was stopped: tasks that would be cut short are running β€” `button:quitAnyway` cancels them and quits, `button:quitCancel` keeps working β€” or unsaved changes: `button:quitRetry` / `button:quitAnyway` / `button:quitCancel`), `import: {done, total, imported, cancelled} \| null` (an import runs on a worker thread), `tasks` (other background work: `Find Missing Photos`, `Auto Import`), `activity` (every long-running task in flight as the activity stack in the top-left corner shows it, same shape as `activity.list`; a row appears once its task is 0.5 s old, ids `activity:row:`, βœ• = `activity:cancel:`, `activity:more` expands past 3 rows), `fileDialogs` (commands waiting on a native file dialog, which runs off the UI thread; they run again with the answer when it closes), `copied` (the text the UI last put on the clipboard, `null` until something is copied) | | `ui.widgets` | `{filter?}` | On-screen widgets `{id, rect: [x, y, w, h]}` (screen points) | | `ui.clickWidget` / `ui.dragWidget` / `ui.hoverWidget` | `{id, count?, button?, fx?, fy?}` (`button: "right"` right-clicks) / `{id, toX?, toY?, dx?, dy?, steps?}` / `{id, fx?, fy?}` | Real egui input on a widget (hover: the pointer rests on it, e.g. for preset/profile previews) | | `ui.move` / `ui.click` / `ui.drag` | `{x, y, count?, button?}` / `{x, y, toX, toY, steps?}` | Raw pointer input, screen points | diff --git a/docs/gaps.md b/docs/gaps.md index f6686e2b414..a91f6bc42e4 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps: where LightCraft falls short of Lightroom -> **Last reviewed:** 2026-10-11 Β· **Last updated:** 2026-10-15 Β· **Change:** minor (gap 15: Print Page Options β€” page numbers, page info, crop marks) +> **Last reviewed:** 2026-10-11 Β· **Last updated:** 2026-10-18 Β· **Change:** minor (gap 30: Dehaze on older edits, process V4's haze-map Dehaze on top of V3's (#1237); gap 15: Print Page Options β€” page numbers, page info, crop marks) Every known shortfall, one entry each, ranked by user impact (how many Lightroom users hit it, and how hard it blocks them), then by effort. **Agents pick work from the top** (the first entry nobody is @@ -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, 5 bundled profiles or 52 spectral matrices (plus same-sensor bodies, e.g. the X-T30 through the X-T3); 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); 0 chart-calibrated models 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 unmeasured** (LR-BEHAV-RENDER-FIDELITY): tone, highlights, texture / clarity / dehaze, NR and sharpening are tuned by eye | no side-by-side suite; a retune needs a new process version (only V1 exists) | edits imported from Lightroom look different; the look "isn't Lightroom's" | 30–60 | [raw-parity](raw-parity.md), [process-versions](process-versions.md) | +| 3 B | **Render fidelity unmeasured** (LR-BEHAV-RENDER-FIDELITY): tone, highlights, texture / clarity / dehaze, NR and sharpening are tuned by eye | no side-by-side suite; a retune needs a new process version (V1, V2, V3 and V4 exist; see [process-versions](process-versions.md)) | edits imported from Lightroom look different; the look "isn't Lightroom's" | 30–60 | [raw-parity](raw-parity.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 B | **Compressed ORF** (every Olympus / OM body since ~2008) | measured: 66 of 78 Olympus / OM models preview-only; `orf.rs` refuses; OM bucket 3% of photographers, 3% of them fully work | +2.6 points; best gain per hour of any raw gap (~0.2) | 8–15 | [raw-parity](raw-parity.md#compressed-orf-a-clean-room-starting-point) (the two Olympus patents that describe the method) | @@ -44,6 +44,7 @@ Hours are Opus 5.5 agent wall-clock hours (see [target-app-parity.md](target-app | 27 | **Windows / Linux runtime coverage**: Windows installer UI unverified on Windows (#79); GPU path proven on Apple and on one AMD GPU on Linux (Radeon 8060S, Vulkan); NVIDIA, Intel and DX12 unverified; the Linux riscv64 tarball (new in 0.6.0, #844) is cross-compiled and never run beyond a QEMU smoke test | ROADMAP, issues, `release.yml` | non-Mac users find bugs first | 13–27 | [hardware-parity](hardware-parity.md) | | 29 | **HDR merge leftovers** (LR-MERGE-HDR): AI Denoise doesn't run on merged (linear) DNGs; JPEG brackets are treated as linear (no camera response curve); every frame is held as 32-bit float, ~0.86 GB per 67 MP frame (half-float frames would halve it) | tested on Sony A7R VI brackets 2026-10-14 ([merge.md](merge.md)); Lightroom's Denoise supports HDR DNGs | HDR shooters who denoise their merges, merge JPEGs, or merge 7+ frames of high-resolution raws on 16 GB machines | 10–20 (+ denoise linear-RGB contract, gap 11) | [merge](merge.md) | | 28 | **Small Classic shortcuts and keys**: rating `[` `]`, flag cycling, filter-bar keys, F1 help, panel keys (Tab, F5, F8; F6 and F7 toggle the filmstrip and the left panel) | [ui-parity](ui-parity.md#shortcuts) | Classic muscle memory | 4–8 | [ui-parity](ui-parity.md) | +| 30 | **Dehaze on older edits and against Lightroom** (LR-EDIT-EFFECTS-DEHAZE, #1237): process V4's Dehaze (guided dark-channel haze map of the whole frame, gentle recovery, soft veil when negative) is in and meets every #1237 acceptance band; photos edited under V1 / V2 keep the old one (V3 has #1283's patch-minimum dark channel) (+20–30 darkens the whole photo, crushes shadows, dark halos from +10) until Update to Current Process; V4 is not yet compared with Lightroom renders, and its CPU tick (~3 ms at 2.5 MP) is over the 2 ms budget | measured: V4 +50 βˆ’0.24..βˆ’0.26 EV median, +100 βˆ’0.53..βˆ’0.73, no extra black, no halo, grey hue drift 1.1Β°, βˆ’100 +0.66..+0.85 EV on fog (V1 +100: βˆ’2.03 EV, 6.5 % black, 55 px halo); checklist row 🟑 | photos edited with Dehaze before V4, and anyone matching Lightroom's look | 2–4 | [process-versions](process-versions.md) | Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform work they need around them, **~340–600 h** to beta (incl. 40–80 h for the ~92 open core-path user issues) (see [target-app-parity.md](target-app-parity.md#stage)). @@ -55,7 +56,7 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w - **File format:** 2, 6, 7, 10, 13, 20, 25 (raw ones in [raw-parity.md](raw-parity.md)) - **Hardware:** 14, 17, 22, 27 - **Localization:** 21 -- **Quality / fidelity:** 1, 3 +- **Quality / fidelity:** 1, 3, 30 - **Stability and platforms:** 9, 26, 27 ## Closed recently (kept for calibration) @@ -77,6 +78,7 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w | Date | Change | Summary | |---|---|---| +| 2026-10-18 | minor | Gap 30 (was 29 on its branch; 29 is now the HDR merge): process V4 carries the haze-map Dehaze on top of V3's patch-minimum one (#1283); V1 / V2 / V3 edits keep theirs; gap 3 lists V1–V4 | | 2026-10-18 | patch | Gap 1: six X-Trans CMOS 4 Fujifilm bodies (X-T30 …) take the X-T3's spectral matrices instead of the neutral matrix | | 2026-10-15 | minor | Gap 15 shrinks: the Page panel's Page Options (Page Numbers, Page Info, Crop Marks) print on Single Image and Contact Sheet pages; identity plate, watermark, photo info, Cut Guides, direct printing and JPEG output remain | | 2026-10-14 | minor | Gap 26: at 100k photos stack and album lookups are indexed, so an "In a Stack" or "Album" smart album counts in ~14 ms (was 0.6–2.7 s); open time unchanged | @@ -91,6 +93,10 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w | 2026-10-12 | minor | Gap 20 shrinks: Mamiya MEF decodes (`vendor/mef.rs`) and is imported; gap 10 count 240 β†’ 241 | | 2026-10-12 | minor | Gap 20 shrinks: Epson ERF decodes (`vendor/erf.rs`), 3 bodies verified; gap 10 count 237 β†’ 240 | | 2026-10-13 | minor | Gap 28: F6 (filmstrip) and F7 (left panel) are bound, so the entry no longer lists them as missing; hours unchanged | +| 2026-10-12 | minor | Gap 29: V3 Dehaze tuned and measured (every #1237 band met, gentler negatives, no horizon band); stays open for the Lightroom comparison, V1 / V2 edits and the CPU tick; 3–6 h β†’ 2–4 h | +| 2026-10-12 | minor | Gap 29: process V3's Dehaze landed (CPU and GPU); retitled to what remains: V1 / V2 edits keep the old Dehaze, no Lightroom comparison yet; 8–15 h β†’ 3–6 h | +| 2026-10-12 | minor | Gap 29: process V3 added (the latest) to carry the new Dehaze; it renders like V2 until that lands. Gap 3 lists V1–V3 | +| 2026-10-12 | minor | Gap 29 added: Dehaze far stronger than Lightroom's, no guided refinement (#1237; V3 dehaze in progress); gap 3's stale "only V1 exists" fixed (V1 and V2 exist) | | 2026-10-11 | minor | Gap 10 shrinks: Leica Q3 verified by a recorded check of 38 private DNGs (236 models verified; Leica 14); gap not closed | | 2026-10-12 | minor | Camera-look deep shadows follow the JPEG toe (#1307); camera calibration remains partial | | 2026-10-12 | minor | Gap 23 (accessibility): crop handles, spots, gradient handles and mask pins by keyboard; 4–8 h β†’ 2–4 h; gap not closed | diff --git a/docs/gpu-pipeline.md b/docs/gpu-pipeline.md index 5bd0119f952..3161dfdfd7e 100644 --- a/docs/gpu-pipeline.md +++ b/docs/gpu-pipeline.md @@ -161,8 +161,13 @@ walks the drive. - Stage cache: `GpuStages` mirrors `StageCache` (same keys: source identity + `geo`, `lin_key`, per-plane radii) and lives in it as an extension, so the UI needs no change. The uploaded source is kept per view. A tone / colour / exposure drag re-runs one dispatch of `finish` plus the readback. -- One command encoder per render; the only mid-render readback is the airlight samples (dehaze, when - the dark channel is recomputed). Dropped buffers are recycled (exact size, ≀ 2 GB pool) once the +- One command encoder per render; the only mid-render readback is the airlight samples (process V1 / V2 / V3 + dehaze, when the dark channel is recomputed). Process V4's Dehaze (issue #1237) needs none: its haze + map is built on the CPU with the plan (a fixed proxy of the whole frame, cached per image) and the + `finish` kernel samples its a / b coefficients (uploaded in the `dark` slot once per map and kept + with the view's `GpuStages`, so a tone drag uploads nothing new) bilinearly at each + pixel's frame-normalised position, with the airlight and compensation LUT in the parameter block, + so windows and whole renders dehaze alike. Dropped buffers are recycled (exact size, ≀ 2 GB pool) once the thread that dropped them has submitted β€” allocating and zero-filling fresh 100–300 MB buffers per pass cost as much as the passes. - `LIGHTCRAFT_PROFILE=1` prints GPU stage timings (each stage is then submitted and waited for). @@ -241,7 +246,10 @@ fresh ones. `windows_match` runs the settings cases again as a window of a 3000 (`RenderRequest::window`, the zoomed loupe, issue #323) plus a vignette in a corner and a spot reading from outside the window: the vignette geometry arrives as the `VIG_VIEW` parameter, the airlight and noise-reduction size come from the whole frame, and a window that spots or Auto Mask strokes grew is -cut back after the readback. The tests skip (pass with a note) when no adapter exists. +cut back after the readback. `v4_dehaze_matches` covers process V4's Dehaze on the hazy valley +(βˆ’100..+100, rendered and raw sources, exposed, with the typical edit, masks added to the slider and +clamped, Effects off, three windows of a 3000 Γ— 2000 frame) and V1 / V2's: max 1 LSB. The tests skip +(pass with a note) when no adapter exists. **AMD Radeon 8060S (RADV STRIX_HALO, Vulkan 1.4, Mesa 26.2.4, Linux 7.2), 2026-10-12**, the first non-Apple GPU verified: all 16 tests pass, 135 compared cases. 124 differ by max 1 LSB, 10 are diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 02f5bf08fdf..f1310bc22f3 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,6 +1,6 @@ # Lightroom parity checklist -> **Last reviewed:** 2026-10-10 Β· **Last updated:** 2026-10-20 Β· **Change:** minor (LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict) Β· **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 Β· **Last updated:** 2026-10-20 Β· **Change:** minor (LR-EDIT-EFFECTS-DEHAZE, LRC-DEV-PROCESS: process V4's haze-map Dehaze on top of V3's, #1237; LRC-PRINT-PAGE: Print Page Options) Β· **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 The measured, row-by-row checklist: one row per Lightroom feature, menu item and shortcut, what we have and what is missing. It answers *does the feature exist?* (feature breadth). Whether it is good @@ -31,7 +31,7 @@ cited here still exists. Formerly docs/parity.md. | C. Views & navigation (VIEW) | 16 | 1 | 1 | 0 | 9/9 (100%) | 4/4 (100%) | | D. Search & filter (FILT) | 11 | 1 | 1 | 0 | 4/4 (100%) | 4/4 (100%) | | E. Metadata (META) | 5 | 1 | 0 | 0 | 2/2 (100%) | 2/2 (100%) | -| F. Edit panel β€” global adjustments (EDIT) | 44 | 2 | 3 | 1 | 28/28 (100%) | 13/14 (93%) | +| F. Edit panel β€” global adjustments (EDIT) | 43 | 3 | 3 | 1 | 27/28 (96%) | 13/14 (93%) | | G. Profiles (PROF) | 7 | 1 | 3 | 0 | 3/4 (75%) | 3/3 (100%) | | H. Crop & rotate (CROP) | 9 | 0 | 0 | 1 | 6/6 (100%) | 3/3 (100%) | | I. Remove / healing (REM) | 8 | 1 | 2 | 2 | 4/4 (100%) | 2/3 (67%) | @@ -53,9 +53,9 @@ cited here still exists. Formerly docs/parity.md. | Y. Menus | 84 | 0 | 4 | 8 | 47/47 (100%) | 23/23 (100%) | | Z. Keyboard shortcuts (desktop) | 78 | 4 | 2 | 1 | 49/52 (94%) | 24/26 (92%) | | Lightroom Classic extras | 40 | 23 | 23 | 8 | β€” | 24/26 (92%) | -| **Total** | 419 | 61 | 59 | 35 | 194/201 (97%) | 148/161 (92%) | +| **Total** | 418 | 62 | 59 | 35 | 193/201 (96%) | 148/161 (92%) | -Weighted completion (βœ… = 1, 🟑 = Β½, 🚫 left out): **83.4%** of 539 in-scope rows β€” P0 98.3% of 201 Β· P1 95.0% of 161 Β· P2 55.7% of 176. +Weighted completion (βœ… = 1, 🟑 = Β½, 🚫 left out): **83.3%** of 539 in-scope rows β€” P0 98.0% of 201 Β· P1 95.0% of 161 Β· P2 55.7% of 176. ## Top gaps and shortcut notes @@ -203,7 +203,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-EDIT-COLOR-GRADING | Colour grading wheels | P0 | βœ… | `ctl:grading.*`, `crates/ui-egui/src/panels/edit.rs` (`grading`) | 3-Way / Shadows / Midtones / Highlights tabs; a range tab shows one large wheel with Hue, Saturation and Luminance sliders; Blending and Balance in every tab; 3-Way shows the hovered wheel's hue and saturation; every wheel marks its neutral centre; wheel modifiers as in Lightroom: Shift-drag keeps the puck's hue and changes saturation only (the spoke is the guide; a puck at the centre has no hue, so it takes the angle where the pointer pressed), Cmd/Ctrl-drag keeps the saturation and changes hue only (the circle is the guide), Alt/Option-drag fine-adjusts at 0.1x and combines with either lock, and a hover tooltip lists them (issues #559, #1160; tests `shift_dragging_across_the_tangent_keeps_the_hue_and_moves_saturation`, `shift_drag_keeps_the_pucks_hue_wherever_the_pointer_grabs`, `cmd_drag_keeps_the_saturation_and_changes_only_the_hue`, `alt_drag_fine_adjusts_to_a_tenth_of_the_pointers_travel`, `alt_works_with_shift_and_cmd_constraints` in `crates/ui-egui/src/tests_grading.rs`); the large wheel adds 25/50/75 % saturation rings (issue #559); each wheel's eye hides its effect for viewing only (`RenderJob::with_hidden_grading`, not saved, export unaffected) (issue #737). No Global wheel tab yet | | LR-EDIT-EFFECTS-TEXTURE | Texture | P0 | βœ… | `ctl:effects.texture` | | | LR-EDIT-EFFECTS-CLARITY | Clarity | P0 | βœ… | `ctl:effects.clarity` | | -| LR-EDIT-EFFECTS-DEHAZE | Dehaze | P0 | βœ… | `ctl:effects.dehaze` | | +| LR-EDIT-EFFECTS-DEHAZE | Dehaze | P0 | 🟑 | `ctl:effects.dehaze`, `crates/pipeline/src/haze.rs`, `crates/pipeline/src/finish.rs`, `crates/pipeline/src/local.rs`, `crates/pipeline/src/tests_dehaze.rs`, `crates/pipeline/src/tests_dehaze_v4.rs` | globally and in masks. Process V4 (#1237, on top of V3's patch-minimum dark channel, eased response and veil limit): a dark-channel haze map of the whole frame (patch minimum, guided refinement, colour airlight) built once per image on a 768 px proxy (~12 ms), a gentle recovery with a smooth sky tolerance and exposure compensation; negative amounts add a soft veil. Every #1237 acceptance band passes on the hazy valley and the misty demo scenes (`tests_dehaze_v4`): median +25 βˆ’0.14..βˆ’0.16 EV, +50 βˆ’0.24..βˆ’0.26, +100 βˆ’0.53..βˆ’0.73, no extra black, no halo, neutral-grey hue drift 1.1Β° (+25 β†’ +100), flat grey 0 LSB, βˆ’100 +0.66..+0.85 EV on the fog scenes with no extra clipping (V1: +100 βˆ’2.03 EV, 6.5 % black, 55 px halo; βˆ’100 +1.52 EV); preview, windows, export, CPU and GPU match. Still 🟑: not yet compared with Lightroom renders, and the CPU per-pixel cost (~18 ns/px, β‰ˆ3 ms a tick at 2.5 MP on 16 threads) is over the 2 ms budget (the GPU renders it interactively); V1 / V2 edits keep the old, too-strong Dehaze (Gaussian-blurred min(R,G,B), scalar airlight) and V3 edits the patch-minimum one, until Update to Current Process | | LR-EDIT-EFFECTS-VIGNETTE | Post-crop vignette | P0 | βœ… | `ctl:vignette.*`, `crates/pipeline/src/finish.rs`, `crates/ui-egui/src/panels/edit.rs` | style picker (Highlight / Color / Paint) in the Effects section | | LR-EDIT-EFFECTS-GRAIN | Grain | P1 | βœ… | `ctl:grain.*` | | | LR-EDIT-DETAIL-SHARPEN | Sharpening | P0 | βœ… | `ctl:detail.sharpenAmount`, `ctl:detail.sharpenRadius`, `ctl:detail.sharpenDetail`, `ctl:detail.sharpenMasking` | no Alt-drag mask preview | @@ -728,7 +728,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/panels/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 records the rendering process its settings are interpreted by: settings saved before this existed load as V1, new photos and Reset get the latest, virtual copies inherit, copy / paste / sync / presets keep each photo's own; Photo β–Έ Update to Current Process (one undo step, enabled while a selected photo is on an older process); a number from a newer LightCraft is kept and renders with the newest known process. Only V1 exists so far: this is what lets a retuned default tone (#146) or stronger Light sliders (#196) ship without changing existing edits | +| 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 records the rendering process its settings are interpreted by: settings saved before this existed load as V1, new photos and Reset get the latest, virtual copies inherit, copy / paste / sync / presets keep each photo's own; Photo β–Έ Update to Current Process (one undo step, enabled while a selected photo is on an older process); a number from a newer LightCraft is kept and renders with the newest known process. V1, V2 (Highlights / Shadows keep detail, #632) V3 (Dehaze from a patch-minimum dark channel, #1237; renders like V2 without Dehaze) and V4 (the haze-map Dehaze, #1237; renders like V3 without Dehaze) exist; the stage-cache keys include the process. This is what lets a retuned default tone (#146) or stronger Light sliders (#196) ship without changing existing edits | | LRC-DEV-VIEWOPTIONS | Develop view options | P2 | ⬜ | | | | 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 | ⬜ | | | @@ -799,6 +799,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove |---|---|---| | 2026-10-20 | patch | LR-VIEW-ZOOM: the 20 ms rule clears a slow-drag verdict only on a drag timed at full size; a drag that drafts small leaves it unchanged, as the code does; status unchanged | | 2026-10-19 | patch | LR-VIEW-ZOOM: the slow slider-drag verdict is described as per photo and control, as the code keys it; status unchanged | +| 2026-10-18 | minor | LR-EDIT-EFFECTS-DEHAZE, LRC-DEV-PROCESS: the haze-map Dehaze moves to process V4, on top of V3's patch-minimum dark channel (#1283); V1 / V2 / V3 edits keep their Dehaze; statuses unchanged (🟑 / βœ…) | | 2026-10-15 | minor | LR-VIEW-ZOOM: a slow slider-drag verdict needs two drags over 20 ms and expires after 30 s (doubling to 240 s); hidden-window frame times are ignored; the slow set forgets its oldest entry, not all (issue #330); status unchanged | | 2026-10-15 | minor | LR-BEHAV-BG-TASKS: Reload from Disk reads its files on a worker thread with a cancellable activity row instead of freezing the window on a selection of raws; its result is committed through the command wrapper (XMP sidecars auto-written as before) and an older reload finishing late no longer overwrites a newer one; status unchanged (βœ…) | | 2026-10-14 | patch | LR-EXP-TYPE: opaque 8-bit PNG/TIFF/WebP use RGB; transparent exports retain alpha (#1670). Statuses and feature counts unchanged. | @@ -836,6 +837,10 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-13 | minor | LR-IMP-DEVICE: Settings β†’ Import β†’ Cameras and Cards can open the import review when a camera or card is connected; status unchanged (βœ…) | | 2026-10-13 | minor | KEY-SLIDER-SCRUB: drag a slider's value sideways to scrub it, as in Lightroom (new row) | | 2026-10-13 | minor | KEY-SLIDER-RESET: hovering a slider's name or thumb says a double-click resets it; a double-click on the thumb is one undo step, not two; a disabled slider's name doesn't reset it (issue #1436); status unchanged (βœ…) | +| 2026-10-12 | minor | LR-EDIT-EFFECTS-DEHAZE: V3 Dehaze tuned (gentler veil, smooth sky tolerance, no light band at the horizon, 768 px map); every #1237 acceptance band passes and is tested; stays 🟑 (no Lightroom comparison yet, CPU tick over the 2 ms budget) | +| 2026-10-12 | minor | LR-EDIT-EFFECTS-DEHAZE and LRC-DEV-PROCESS: process V3's Dehaze landed (haze map, CPU and GPU, #1237); the row stays 🟑 until it is compared with Lightroom, and V1 / V2 keep the old Dehaze | +| 2026-10-12 | minor | LRC-DEV-PROCESS: process V3 added and made the latest, for the new Dehaze (#1237); the row no longer says only V1 exists | +| 2026-10-12 | minor | LR-EDIT-EFFECTS-DEHAZE βœ… β†’ 🟑: far stronger than Lightroom's and no guided refinement (#1237); a V3 dehaze is in progress | | 2026-10-11 | minor | LR-MERGE-HDR: HDR and panorama merges of raws without colour matrices (CR2, NEF, ARW…) write the colour they open with as DNG tags (issue #965); status unchanged | | 2026-10-12 | minor | LR-META-XMP: Read Metadata from File no longer auto-writes the sidecar it has just read, which added `lc:settings` and hid another app's later `crs:` edits (#934); status unchanged (βœ…) | | 2026-10-12 | patch | LR-IMP-CAMERA-COVERAGE: CR2 white level from the active area, not the saturated masked rows above it (issue #1272); status unchanged (🟑) | diff --git a/docs/process-versions.md b/docs/process-versions.md index ea31d395072..c6a7b3fb162 100644 --- a/docs/process-versions.md +++ b/docs/process-versions.md @@ -8,7 +8,9 @@ stronger Light sliders, issue #196) without changing a single photo someone has | Process | What it changes | |---|---| | **V1** | LightCraft's rendering from before process versions existed. Frozen. | -| **V2** (the latest) | Highlights and Shadows keep fine detail (issue #632): their base layer (`local::tone_base`) is the edge-aware filter of a separable median of log luminance (radius 0.15 % of the long edge, at most 24 px, `local::BASE_DETAIL`) instead of log luminance itself, so twigs, lines and texture take their surroundings' shift and keep their contrast; region edges stay sharp. CPU (`local::prepare`) and GPU prepare branch on `local::tone_base_detail` (0 = no median under V1); the base plane is cached per process (`local::BaseKey`). Renders without Highlights or Shadows (global or local) are the same as V1's. Tone map unchanged. | +| **V2** | Highlights and Shadows keep fine detail (issue #632): their base layer (`local::tone_base`) is the edge-aware filter of a separable median of log luminance (radius 0.15 % of the long edge, at most 24 px, `local::BASE_DETAIL`) instead of log luminance itself, so twigs, lines and texture take their surroundings' shift and keep their contrast; region edges stay sharp. CPU (`local::prepare`) and GPU prepare branch on `local::tone_base_detail` (0 = no median under V1); the base plane is cached per process (`local::BaseKey`). Renders without Highlights or Shadows (global or local) are the same as V1's. Tone map unchanged. | +| **V3** | Dehaze (issue #1237): the haze plane is the Gaussian of a patch minimum (`local::min_hv`, radius 0.5 % of the long edge, at most 64 px, `local::dehaze_patch_radius`) of each pixel's darkest channel instead of the Gaussian of that channel itself, so textured, haze-free regions are no longer read as haze; positive amounts ease in (`kΒ·(0.4 + 0.6Β·k)`), the transmission floor is 0.3, and the veil removed never exceeds 90 % of the pixel's darkest channel (`finish::dehaze_v3_pixel`), so shadows next to bright sky no longer clip to black. Negative dehaze is V1's. The dark plane's cache key carries the patch radius (`local::dark_key`). Renders without Dehaze are the same as V2's. | +| **V4** (the latest) | Dehaze (issue #1237): a dark-channel haze estimate built once per image on a fixed proxy of the whole frame (patch minimum, guided refinement, colour airlight) and a gentler recovery (a sky tolerance that fades in smoothly, exposure compensation that leaves the sky near the airlight alone, 50 % of the input's chroma kept), so +25..+50 no longer darkens the photo and crushes its shadows (+50 moves the median about βˆ’0.25 EV, +100 about βˆ’0.6 EV, no halo) and βˆ’100 adds a soft veil (about +0.7..+0.85 EV on fog) instead of washing the photo out (`crates/pipeline/src/haze.rs`: `HazeMap`, `dehaze_at`; CPU `finish.rs` and the GPU `finish` kernel). The map is cached per image (source content, frame, white balance, camera local tone mapping, proxy size), so every preview size, zoomed window, export and Exposure change shares it; a draft during a drag reuses the photo's latest map. Without Dehaze (global or in a mask) V4 renders exactly like V3. The stage caches (`Plan::lin_key`, `Plan::pre_nr_key`) include the process, so a photo moved between processes never reuses another's planes. V1, V2 and V3 renders are unchanged; V3 (the patch dark channel) keeps its own Dehaze. | ## The rule diff --git a/docs/whats-new.md b/docs/whats-new.md index cfeed33edb9..d158d4c50bb 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -496,6 +496,16 @@ - The kept original no longer pushes everything else out of the cache: on a 64 MP raw it filled the cache share alone, so the photo's preview and thumbnail sources and its neighbours' were decoded from the raw again on every edit at 1:1, every zoom out and every step to the next photo. +## 2026-10-12 + +### Rendering process 4 (Dehaze) +- New photos (and Reset) get rendering process 4 with a new, gentler Dehaze (issue #1237): it measures haze with + a dark-channel estimate of the whole frame and clears it without darkening the photo or crushing its shadows + (the old one did from about +25), with no dark halos, the same in the preview, a zoomed view and the export, on + the CPU and the GPU. Skies near the haze colour are left alone without a light band at the horizon, and negative + Dehaze adds a soft, near-neutral veil (about +0.7 to +0.85 EV at βˆ’100 on a foggy photo, where the old one added + +1.5) instead of washing the photo out. Process 4 differs from process 3 only in Dehaze. Photos you already edited keep their look, + Dehaze included, until you choose Photo β–Έ Update to Current Process. See [process versions](process-versions.md). ## 2026-10-11