From a60090fff58a7347e0db82bf8dfb1aae3fce2991 Mon Sep 17 00:00:00 2001 From: fjamesprice Date: Sat, 17 Oct 2026 05:14:09 -0400 Subject: [PATCH] perf(camera-raw): develop Shadows and Highlights on the GPU in the preview (#6916) Step 2 of #6916: the local Laplacian filter behind Shadows and Highlights (Paris, Hasinoff, Kautz 2011, sampled as in Aubry et al. 2014, as local_tone.rs does) as wgpu fragment passes, chained in front of step 1's per-pixel pass with no readback in between. - algo: local_tone exposes its constants and resolves the sliders into LocalTone / TonePass (the remapping is a method); the CPU filter runs those passes. PerPixel gains local_tone and measure_whites_blacks; whites_blacks_model() exposes the Whites and Blacks tables; quantile_rank() is the one rank rule. CPU output unchanged bit for bit (86 hashes, 8-bit and float, 171x113 to 2100x1300) and as fast. - gpu: camera_raw_tone.rs/.wgsl. Pyramid levels are R32Float textures; the remapped pyramids of up to 96 references sit in one Rgba32Float atlas per level, four per tile. The filter's quantiles, and Whites and Blacks' points after it, are exact order statistics on the GPU (16 thresholds per round, 8 rounds); a pass renders the Whites and Blacks rows into the table texture. Textures, passes and bind groups are planned once per frame size. Pipelines build with the rest on the existing thread. - ui-egui: the proxy worker sends Shadows and Highlights frames to the GPU; Dehaze, Texture, Clarity and Detail still use the CPU for the frame. GPU vs CPU at 8, 16 and 32 bits: at most 9.9e-6 (RTX 5060 Ti, Vulkan and DX12), 1.03e-5 (WARP); tests keep 1/4096. 858x572 proxy, release: Shadows +50 8.7 ms (Vulkan) / 10.6 ms (DX12) vs 147-300 ms on the CPU. Part of #6916. Co-Authored-By: Claude Opus 5.5 --- crates/algo/src/camera_raw.rs | 21 +- crates/algo/src/camera_raw/local_tone.rs | 162 ++-- crates/algo/src/camera_raw/per_pixel.rs | 49 +- crates/algo/src/camera_raw/whites_blacks.rs | 65 +- crates/gpu/examples/bench_camera_raw.rs | 82 +- crates/gpu/src/camera_raw.rs | 180 ++-- crates/gpu/src/camera_raw.wgsl | 83 +- crates/gpu/src/camera_raw_tone.rs | 852 +++++++++++++++++++ crates/gpu/src/camera_raw_tone.wgsl | 585 +++++++++++++ crates/gpu/src/lib.rs | 7 +- crates/gpu/tests/it/camera_raw.rs | 108 ++- crates/ui-egui/src/dialogs/camera_raw_gpu.rs | 42 +- crates/ui-egui/src/dialogs/camera_raw_ui.rs | 3 +- docs/hardware-parity.md | 5 +- 14 files changed, 2046 insertions(+), 198 deletions(-) create mode 100644 crates/gpu/src/camera_raw_tone.rs create mode 100644 crates/gpu/src/camera_raw_tone.wgsl diff --git a/crates/algo/src/camera_raw.rs b/crates/algo/src/camera_raw.rs index 5bd0c8ab067..b4e0d0f8d9d 100644 --- a/crates/algo/src/camera_raw.rs +++ b/crates/algo/src/camera_raw.rs @@ -55,11 +55,14 @@ pub fn validate_curve(points: &[[f32; 2]]) -> Result<(), String> { use crate::photo_util::{hash01, linear_to_srgb, par_rows, srgb_to_linear}; -mod local_tone; +pub mod local_tone; mod per_pixel; mod whites_blacks; -pub use per_pixel::{CURVE_LUT, Grade, Grain, PerPixel, Vignette, VignetteStyle, WB_STEPS, WhitesBlacks, per_pixel, white_black_points}; +pub use local_tone::{LocalTone, ToneKind, TonePass}; +pub use per_pixel::{ + CURVE_LUT, Grade, Grain, PerPixel, Vignette, VignetteStyle, WB_STEPS, WhitesBlacks, WhitesBlacksModel, per_pixel, white_black_points, whites_blacks_model, +}; /// How the pixels encode light: the sRGB curve (gamma 0) or a pure power law (ProPhoto's 1.8, /// Adobe RGB's 2.2). The tone controls work on light, so the document's own curve decodes it. @@ -885,11 +888,17 @@ fn balance(mut q: [f32; 4], g: [f32; 3]) -> [f32; 4] { q } +/// The index of the `q` quantile (0 … 1) among `len` sorted values, as every percentile in the +/// develop picks it. +pub fn quantile_rank(len: usize, q: f32) -> usize { + (len.saturating_sub(1) as f32 * q).round() as usize +} + /// The image's black and white points as sRGB-encoded grey levels: the 3rd percentile of the /// luminance and the 99.5th of the brightest channel, on a copy at most 256 pixels across (so a /// preview proxy and the full image agree). `map` is applied to each pixel first. fn luminance_points(px: &[[f32; 4]], w: usize, h: usize, enc: Encoding, map: impl Fn([f32; 4]) -> [f32; 4] + Sync) -> (f32, f32) { - let f = w.max(h).div_ceil(256).max(1); + let f = w.max(h).div_ceil(whites_blacks::POINTS_SIDE).max(1); let (sw, sh) = (w.div_ceil(f), h.div_ceil(f)); // Each band of `f` rows sums into its own row of cells, in the same order as one pass would. let bands = crate::photo_util::par_map(sh, |sy| { @@ -912,10 +921,10 @@ fn luminance_points(px: &[[f32; 4]], w: usize, h: usize, enc: Encoding, map: imp } let pct = |mut v: Vec, q: f32| { v.sort_by(f32::total_cmp); - v[((v.len() - 1) as f32 * q).round() as usize] + v[quantile_rank(v.len(), q)] }; - let bp = pct(cells.iter().map(|c| luma(*c)).collect(), 0.03); - let wp = pct(cells.iter().map(|c| c[0].max(c[1]).max(c[2])).collect(), 0.995); + let bp = pct(cells.iter().map(|c| luma(*c)).collect(), whites_blacks::POINT_QUANTILES[0]); + let wp = pct(cells.iter().map(|c| c[0].max(c[1]).max(c[2])).collect(), whites_blacks::POINT_QUANTILES[1]); (linear_to_srgb(bp), linear_to_srgb(wp)) } diff --git a/crates/algo/src/camera_raw/local_tone.rs b/crates/algo/src/camera_raw/local_tone.rs index 1dbf58421fa..2e28a2efc78 100644 --- a/crates/algo/src/camera_raw/local_tone.rs +++ b/crates/algo/src/camera_raw/local_tone.rs @@ -20,19 +20,31 @@ //! mean error against Photoshop is 2.8–9.4 levels (of 255) where the previous heuristic's was //! 3.7–14.3. -use super::{Encoding, luma}; +use super::{Encoding, luma, quantile_rank}; use crate::photo_util::par_rows; /// Spacing of the fast filter's reference values in stops. Its remapping changes within about /// half a stop, and coefficients interpolated across wider gaps show as contour lines on smooth /// gradients (12 references over a whole raw's range left visible steps; at an eighth of a stop a /// ramp's slope varies by under a third, as the remapping itself makes it). -const REF_STEP: f32 = 0.125; +pub const REF_STEP: f32 = 0.125; +/// Most reference values one filter uses. +pub const MAX_REFS: usize = 96; +/// The lowest reference sits at this quantile of the log luminance: the deepest 0.1 % (noise down +/// to the floor) share it instead of stretching the spacing. +pub const REF_LOW_QUANTILE: f32 = 0.001; +/// The filter works on `log2(luminance + LOG_FLOOR)`. +pub const LOG_FLOOR: f32 = 1.0 / 65536.0; /// The filter runs on a copy at most this many pixels across; the change it makes is brought back /// to full size by a guided upsampling, so a preview and the full image agree. -const WORK_SIDE: usize = 1600; +pub const WORK_SIDE: usize = 1600; +/// The image range the strengths are placed in: these quantiles of the log luminance averaged +/// over cells of a copy at most [`RANGE_SIDE`] pixels across. +pub const RANGE_QUANTILES: [f32; 2] = [0.01, 0.99]; +/// See [`RANGE_QUANTILES`]. +pub const RANGE_SIDE: usize = 256; /// Knots of the strength curves over the surroundings' place in the image range (0 … 1). -const KNOTS: usize = 5; +pub const KNOTS: usize = 5; /// Shadows: how far a pixel darker than its surroundings rises, in stops per unit slider, as /// a function of its own place in the image range (`own`) times a factor of its surroundings' @@ -59,6 +71,86 @@ struct Side { sigma: f32, } +/// Which remapping a [`TonePass`] uses. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ToneKind { + /// Pixels brighter than their surroundings move toward them (or away, for positive values) + /// by the part of the difference past `sigma`. + Highlights, + /// Pixels darker than their surroundings rise (or sink) by an amount set by their own and + /// their surroundings' place in the image range. + Shadows, +} + +/// One pass of the filter resolved for a slider value: everything its remapping reads. +#[derive(Clone, Debug, PartialEq)] +pub struct TonePass { + pub kind: ToneKind, + /// Highlights: the slider / 100. Shadows: its strength (the slider / 100, times `down` when + /// negative). + pub amount: f32, + /// Highlights: the strengths for the slider's direction, then an unused row. Shadows: the + /// curves over the pixel's own (`own`) and its surroundings' (`around`) place. + pub knots: [[f32; KNOTS]; 2], + /// The detail threshold in stops. + pub sigma: f32, + /// The quantile of the log luminance the pass puts back where it was. + pub keep: f32, +} + +/// Shadows and Highlights resolved: Highlights runs first, then Shadows on its result. +#[derive(Clone, Debug, PartialEq)] +pub struct LocalTone { + pub passes: Vec, +} + +impl LocalTone { + /// The passes for the sliders (−100 … 100); `None` when both are 0. + pub fn new(shadows: f32, highlights: f32) -> Option { + let mut passes = Vec::new(); + if highlights != 0.0 { + let amount = highlights.clamp(-100.0, 100.0) / 100.0; + let strengths = if amount < 0.0 { HIGHLIGHTS.pull } else { HIGHLIGHTS.push }; + // Then the darkest content is put back where it was. + passes.push(TonePass { kind: ToneKind::Highlights, amount, knots: [strengths, [0.0; KNOTS]], sigma: HIGHLIGHTS.sigma, keep: 0.01 }); + } + if shadows != 0.0 { + let amount = shadows.clamp(-100.0, 100.0) / 100.0; + let k = if amount > 0.0 { amount } else { amount * SHADOWS.down }; + // Keep the brightest content. + passes.push(TonePass { kind: ToneKind::Shadows, amount: k, knots: [SHADOWS.own, SHADOWS.around], sigma: SHADOWS.sigma, keep: 0.99 }); + } + (!passes.is_empty()).then_some(LocalTone { passes }) + } +} + +impl TonePass { + /// The remapping of log luminance `x` around the reference `g`, in an image range that + /// starts at `lo` and is `span` stops wide. + pub fn remap(&self, x: f32, g: f32, lo: f32, span: f32) -> f32 { + match self.kind { + ToneKind::Highlights => x + knot((g - lo) / span, &self.knots[0]) * self.amount * excess((x - g).max(0.0), self.sigma), + ToneKind::Shadows => { + let below = ((g - x) / self.sigma).clamp(0.0, 1.0); + if below == 0.0 { + return x; + } + let w = below * below * (3.0 - 2.0 * below); + x + self.amount * knot((x - lo) / span, &self.knots[0]) * knot((g - lo) / span, &self.knots[1]) * w + } + } + } + + /// The pass on the log luminance `u`: the filter, then the kept quantile put back. + fn run(&self, u: &Plane) -> Plane { + let (lo, hi) = range(u); + let span = (hi - lo).max(1.0); + let o = llf(u, |x, g| self.remap(x, g, lo, span)); + let shift = quantile(&u.v, self.keep) - quantile(&o.v, self.keep); + Plane { w: o.w, h: o.h, v: o.v.iter().map(|v| v + shift).collect() } + } +} + /// One channel, `w × h`. struct Plane { w: usize, @@ -77,7 +169,8 @@ fn mirror(i: isize, n: usize) -> usize { (if m >= n { p - m } else { m }) as usize } -const TAPS: [f32; 5] = [1.0 / 16.0, 4.0 / 16.0, 6.0 / 16.0, 4.0 / 16.0, 1.0 / 16.0]; +/// The pyramid's binomial kernel. +pub const TAPS: [f32; 5] = [1.0 / 16.0, 4.0 / 16.0, 6.0 / 16.0, 4.0 / 16.0, 1.0 / 16.0]; /// Planes smaller than this run their rows on one thread: the filter builds a whole pyramid per /// reference (up to 96), and splitting its small levels into one-row tasks cost more in rayon's @@ -230,14 +323,13 @@ fn gaussian(p: Plane, n: usize) -> Vec { fn llf(u: &Plane, remap: impl Fn(f32, f32) -> f32 + Sync) -> Plane { let n = depth(u.w, u.h); let g = gaussian(Plane { w: u.w, h: u.h, v: u.v.clone() }, n); - // References span the image's tones; the deepest 0.1 % (noise down to the floor) share the - // lowest reference instead of stretching the spacing. + // References span the image's tones (see `REF_LOW_QUANTILE`). let hi = u.v.iter().fold(f32::NEG_INFINITY, |a, &v| a.max(v)); - let lo = quantile(&u.v, 0.001).min(hi); + let lo = quantile(&u.v, REF_LOW_QUANTILE).min(hi); if hi - lo <= 1e-6 || (hi - lo).is_nan() { return Plane { w: u.w, h: u.h, v: u.v.clone() }; } - let refs = (((hi - lo) / REF_STEP).ceil() as usize + 1).clamp(2, 96); + let refs = (((hi - lo) / REF_STEP).ceil() as usize + 1).clamp(2, MAX_REFS); let step = (hi - lo) / (refs - 1) as f32; let mut lap: Vec> = g[..n - 1].iter().map(|p| vec![0.0; p.v.len()]).collect(); for k in 0..refs { @@ -279,13 +371,14 @@ fn quantile(v: &[f32], q: f32) -> f32 { let mut s = v.to_vec(); // Selecting the one element is linear, a full sort is not (5 sorts of the work copy were a // fifteenth of a render). `total_cmp` ties are bit-identical, so it is the sorted element. - let i = ((s.len() - 1) as f32 * q).round() as usize; + let i = quantile_rank(s.len(), q); *s.select_nth_unstable_by(i, f32::total_cmp).1 } -/// 1st and 99th percentiles of the log luminance on a copy at most 256 pixels across. +/// The image range: [`RANGE_QUANTILES`] of the log luminance on a copy at most [`RANGE_SIDE`] +/// pixels across. fn range(u: &Plane) -> (f32, f32) { - let f = u.w.max(u.h).div_ceil(256).max(1); + let f = u.w.max(u.h).div_ceil(RANGE_SIDE).max(1); let (sw, sh) = (u.w.div_ceil(f), u.h.div_ceil(f)); let mut sum = vec![(0.0f64, 0u32); sw * sh]; for y in 0..u.h { @@ -296,7 +389,7 @@ fn range(u: &Plane) -> (f32, f32) { } } let cells: Vec = sum.iter().filter(|c| c.1 > 0).map(|c| (c.0 / f64::from(c.1)) as f32).collect(); - (quantile(&cells, 0.01), quantile(&cells, 0.99)) + (quantile(&cells, RANGE_QUANTILES[0]), quantile(&cells, RANGE_QUANTILES[1])) } /// `d` past the detail threshold: about 0 below `sigma`, `d − sigma` well above it. @@ -310,52 +403,19 @@ fn knot(t: f32, k: &[f32; KNOTS]) -> f32 { k[i] + (k[i + 1] - k[i]) * (x - i as f32) } -/// The Highlights pass on the log luminance `u` (`amount` −1 … 1): pixels brighter than their -/// surroundings move toward them (or away, for positive values) by the part of the difference -/// past `sigma`, then the darkest content is put back where it was. -fn highlights_pass(u: &Plane, amount: f32, side: &Side) -> Plane { - let (lo, hi) = range(u); - let span = (hi - lo).max(1.0); - let strengths = if amount < 0.0 { &side.pull } else { &side.push }; - let o = llf(u, |x, g| x + knot((g - lo) / span, strengths) * amount * excess((x - g).max(0.0), side.sigma)); - let shift = quantile(&u.v, 0.01) - quantile(&o.v, 0.01); - Plane { w: o.w, h: o.h, v: o.v.iter().map(|v| v + shift).collect() } -} - -/// The Shadows pass on the log luminance `u` (`amount` −1 … 1). -fn shadows_pass(u: &Plane, amount: f32) -> Plane { - let (lo, hi) = range(u); - let span = (hi - lo).max(1.0); - let k = if amount > 0.0 { amount } else { amount * SHADOWS.down }; - let o = llf(u, |x, g| { - let below = ((g - x) / SHADOWS.sigma).clamp(0.0, 1.0); - if below == 0.0 { - return x; - } - let w = below * below * (3.0 - 2.0 * below); - x + k * knot((x - lo) / span, &SHADOWS.own) * knot((g - lo) / span, &SHADOWS.around) * w - }); - // Keep the brightest content. - let shift = quantile(&u.v, 0.99) - quantile(&o.v, 0.99); - Plane { w: o.w, h: o.h, v: o.v.iter().map(|v| v + shift).collect() } -} - /// Applies Shadows and Highlights (−100 … 100) to straight RGBA pixels encoded with `enc`. pub(crate) fn apply(px: &mut [[f32; 4]], w: usize, h: usize, shadows: f32, highlights: f32, enc: Encoding) { - if (shadows == 0.0 && highlights == 0.0) || w < 2 || h < 2 { + let Some(tone) = LocalTone::new(shadows, highlights) else { return }; + if w < 2 || h < 2 { return; } - const FLOOR: f32 = 1.0 / 65536.0; - let u = Plane { w, h, v: px.iter().map(|q| (luma([0, 1, 2].map(|c| enc.decode(q[c]))).max(0.0) + FLOOR).log2()).collect() }; + let u = Plane { w, h, v: px.iter().map(|q| (luma([0, 1, 2].map(|c| enc.decode(q[c]))).max(0.0) + LOG_FLOOR).log2()).collect() }; // The filter on a copy at most WORK_SIDE across (box-averaged in log). let f = w.max(h).div_ceil(WORK_SIDE).max(1); let small = if f == 1 { Plane { w, h, v: u.v.clone() } } else { shrink(&u, f) }; let mut o = Plane { w: small.w, h: small.h, v: small.v.clone() }; - if highlights != 0.0 { - o = highlights_pass(&o, highlights.clamp(-100.0, 100.0) / 100.0, &HIGHLIGHTS); - } - if shadows != 0.0 { - o = shadows_pass(&o, shadows.clamp(-100.0, 100.0) / 100.0); + for pass in &tone.passes { + o = pass.run(&o); } // The change in log luminance, at full size. let change: Vec = if f == 1 { diff --git a/crates/algo/src/camera_raw/per_pixel.rs b/crates/algo/src/camera_raw/per_pixel.rs index 6400db8a259..c10070ab02c 100644 --- a/crates/algo/src/camera_raw/per_pixel.rs +++ b/crates/algo/src/camera_raw/per_pixel.rs @@ -1,9 +1,13 @@ //! Develop's per-pixel stages resolved for one image: every constant and table they use, so //! another implementation of them (the GPU preview, `photocraft_gpu::CameraRawDevelop`) runs the //! same maths. [`develop`](super::develop) builds its own constants with the same functions. +//! Shadows and Highlights, the one spatial stage resolved here, come as a [`LocalTone`]. +use super::local_tone::{LocalTone, WORK_SIDE}; use super::{CameraRaw, Encoding, Wheel, curve_lut, hsv_to_rgb, is_linear, luma, parametric_lut, white_balance_gains, whites_blacks}; +pub use whites_blacks::Model as WhitesBlacksModel; + /// Entries of the tone curve tables (parametric and point curves). pub const CURVE_LUT: usize = 1024; /// Samples of a Whites or Blacks curve row: grey levels 0, 1/32, …, 1. @@ -24,6 +28,11 @@ fn contrast(p: &CameraRaw) -> Option { (p.contrast != 0.0).then_some(p.contrast / 100.0 * 0.6) } +/// Whites and Blacks' tables, for an implementation that measures the image's points itself. +pub fn whites_blacks_model() -> WhitesBlacksModel { + whites_blacks::model() +} + /// Whites and Blacks as two curve rows for the image's amounts. #[derive(Clone, Debug, PartialEq)] pub struct WhitesBlacks { @@ -149,10 +158,18 @@ impl Grain { pub struct PerPixel { /// 1. White balance and exposure gains in linear light (sRGB-decoded values). pub gains: Option<[f32; 3]>, + /// 3. Shadows and Highlights: a local Laplacian filter of the whole frame, then each pixel's + /// light scaled by the change of its log luminance. + pub local_tone: Option, /// 3. Contrast's strength (Contrast without Texture or Clarity is per pixel). pub contrast: Option, /// 3b. Whites and Blacks, in the document's encoding. pub whites_blacks: Option, + /// 3b. Whites and Blacks to measure the image's points for (the sliders, −100 … 100), when + /// `local_tone` is set: the points then depend on the filter's output, so whatever runs + /// it measures them and picks the curves from [`whites_blacks_model`]. `whites_blacks` is + /// then `None`. + pub measure_whites_blacks: Option<[f32; 2]>, /// The document's transfer curve: 0 for sRGB's, else a power-law gamma. pub encoding: f32, /// 4. Vibrance and Saturation (slider / 100). @@ -183,6 +200,15 @@ impl CameraRaw { || self.noise_luminance > 0.0 || self.noise_color > 0.0 } + + /// Whether developing needs a spatial stage other than Shadows and Highlights. + fn spatial_beyond_local_tone(&self) -> bool { + self.dehaze != 0.0 + || [self.texture, self.clarity].iter().any(|v| *v != 0.0) + || self.sharpen_amount > 0.0 + || self.noise_luminance > 0.0 + || self.noise_color > 0.0 + } } /// The image's black and white points that Whites and Blacks adapt to, for `px` (`w × h`, @@ -201,16 +227,25 @@ pub fn white_black_points(px: &[[f32; 4]], w: usize, h: usize, p: &CameraRaw) -> })) } -/// Develop's stages for settings without spatial stages, on a `w × h` image; `points` are the -/// image's [`white_black_points`]. `None` when `p` needs a spatial stage or Calibration (these -/// stages don't run it), or Whites or Blacks is set without `points`. The points themselves -/// leave Calibration out, so a caller may cache them across Calibration changes. +/// Develop's stages for settings whose only spatial stage is Shadows and Highlights, on a +/// `w × h` image; `points` are the image's [`white_black_points`]. `None` when `p` needs another +/// spatial stage or Calibration (these stages don't run it), Shadows or Highlights on a frame +/// wider than the filter's working copy (the develop then filters a reduced copy), or Whites or +/// Blacks without Shadows and Highlights and without `points`. The points themselves leave +/// Calibration out, so a caller may cache them across Calibration changes. pub fn per_pixel(p: &CameraRaw, w: usize, h: usize, float: bool, points: Option<(f32, f32)>) -> Option { - if p.spatial() || !p.calibration_neutral() { + if p.spatial_beyond_local_tone() || !p.calibration_neutral() { + return None; + } + // The develop leaves frames under 2 pixels on a side alone. + let local_tone = if w >= 2 && h >= 2 { LocalTone::new(p.shadows, p.highlights) } else { None }; + if local_tone.is_some() && w.max(h) > WORK_SIDE { return None; } let identity = p.is_identity(); - let whites_blacks = if p.whites != 0.0 || p.blacks != 0.0 { + let wb_on = p.whites != 0.0 || p.blacks != 0.0; + let measure_whites_blacks = (wb_on && local_tone.is_some()).then(|| [p.whites.clamp(-100.0, 100.0), p.blacks.clamp(-100.0, 100.0)]); + let whites_blacks = if wb_on && measure_whites_blacks.is_none() { let (bp, wp) = points?; let (xw, xb) = whites_blacks::amounts(p.whites.clamp(-100.0, 100.0), p.blacks.clamp(-100.0, 100.0), bp, wp); (xw != 0.0 || xb != 0.0).then(|| WhitesBlacks { @@ -225,8 +260,10 @@ pub fn per_pixel(p: &CameraRaw, w: usize, h: usize, float: bool, points: Option< let pts = |c: &Vec<[f32; 2]>| (!is_linear(c)).then(|| curve_lut(c, CURVE_LUT)); Some(PerPixel { gains: gains(p), + local_tone, contrast: contrast(p), whites_blacks, + measure_whites_blacks, encoding: Encoding::of(p.encoding_gamma).0, presence: (p.vibrance != 0.0 || p.saturation != 0.0).then_some([p.vibrance / 100.0, p.saturation / 100.0]), parametric: parametric_on.then(|| parametric_lut(p, CURVE_LUT)), diff --git a/crates/algo/src/camera_raw/whites_blacks.rs b/crates/algo/src/camera_raw/whites_blacks.rs index cfce5378b4c..2300a433629 100644 --- a/crates/algo/src/camera_raw/whites_blacks.rs +++ b/crates/algo/src/camera_raw/whites_blacks.rs @@ -25,9 +25,66 @@ use crate::photo_util::par_rows; /// Grey levels the curves are sampled at: 0, 1/32, …, 1 (sRGB-encoded). pub(crate) const STEPS: usize = 33; -/// The first row's internal amount; rows are 10 apart. +/// The first row's internal amount; rows are [`ROW_STEP`] apart. const WHITES_FROM: f32 = -100.0; const BLACKS_FROM: f32 = -100.0; +const ROW_STEP: f32 = 10.0; +/// The image's points are measured on cells of a copy at most this many pixels across. +pub(crate) const POINTS_SIDE: usize = 256; +/// The black point's quantile of the cells' luminance, the white point's of their brightest +/// channel. +pub(crate) const POINT_QUANTILES: [f32; 2] = [0.03, 0.995]; +/// Internal amounts the sliders reach: Whites, then Blacks. +const WHITES_RANGE: [f32; 2] = [-100.0, 270.0]; +const BLACKS_RANGE: [f32; 2] = [-100.0, 100.0]; + +/// Whites and Blacks' tables and how an image's points choose from them, for another +/// implementation (the GPU preview measures the points after Shadows and Highlights itself). +#[derive(Clone, Copy, Debug)] +pub struct Model { + /// Whites curves over grey levels 0, 1/32, …, 1, at internal amounts `whites_from`, + /// `whites_from + row_step`, …. + pub whites: &'static [[f32; STEPS]], + pub whites_from: f32, + /// Blacks curves, likewise. + pub blacks: &'static [[f32; STEPS]], + pub blacks_from: f32, + pub row_step: f32, + /// Black points and white points of the adaptation tables' rows and columns. + pub black_points: &'static [f32], + pub white_points: &'static [f32], + /// How much the clipping directions adapt (Whites up, Blacks down), by black and white point. + pub whites_adapt: &'static [[f32; 8]; 9], + pub blacks_adapt: &'static [[f32; 8]; 9], + /// The least Blacks adaptation on photographs. + pub photo_blacks: f32, + /// Internal amounts the Whites and Blacks sliders reach. + pub whites_range: [f32; 2], + pub blacks_range: [f32; 2], + /// See [`POINTS_SIDE`] and [`POINT_QUANTILES`]. + pub points_side: usize, + pub point_quantiles: [f32; 2], +} + +/// The tables [`amounts`], [`whites_row`] and [`blacks_row`] read. +pub(crate) fn model() -> Model { + Model { + whites: &WHITES, + whites_from: WHITES_FROM, + blacks: &BLACKS, + blacks_from: BLACKS_FROM, + row_step: ROW_STEP, + black_points: &BPS, + white_points: &WPS, + whites_adapt: &AW, + blacks_adapt: &AB, + photo_blacks: PHOTO_BLACKS, + whites_range: WHITES_RANGE, + blacks_range: BLACKS_RANGE, + points_side: POINTS_SIDE, + point_quantiles: POINT_QUANTILES, + } +} // Measured levels; some happen to lie near π/8 and π/4. /// Whites curves at internal amounts -100, -90, …, 270 (rows) over grey levels 0, 1/32, …, 1. #[allow(clippy::approx_constant)] @@ -303,7 +360,7 @@ fn curve(rows: &[[f32; STEPS]], from: f32, x: f32, v: f32) -> f32 { if v >= 1.0 { return 1.0; } - let r = ((x - from) / 10.0).clamp(0.0, (rows.len() - 1) as f32); + let r = ((x - from) / ROW_STEP).clamp(0.0, (rows.len() - 1) as f32); let i = (r as usize).min(rows.len() - 2); let t = r - i as f32; let at = |row: &[f32; STEPS]| { @@ -318,7 +375,7 @@ fn curve(rows: &[[f32; STEPS]], from: f32, x: f32, v: f32) -> f32 { /// The curve at a fractional internal amount `x` as one row: `curve(rows, from, x, v)` is this /// row interpolated at `v`, because both interpolations are linear. fn row_at(rows: &[[f32; STEPS]], from: f32, x: f32) -> [f32; STEPS] { - let r = ((x - from) / 10.0).clamp(0.0, (rows.len() - 1) as f32); + let r = ((x - from) / ROW_STEP).clamp(0.0, (rows.len() - 1) as f32); let i = (r as usize).min(rows.len() - 2); let t = r - i as f32; std::array::from_fn(|j| rows[i][j] * (1.0 - t) + rows[i + 1][j] * t) @@ -367,7 +424,7 @@ pub(crate) fn amounts(whites: f32, blacks: f32, bp: f32, wp: f32) -> (f32, f32) // On photographs Photoshop's Blacks is about 1.2 times the block images' amount even where // their black point is 0 (ten public-domain photos: 1.08–1.36). let b = if blacks < 0.0 { blacks * adapt(&AB, bp, wp).max(PHOTO_BLACKS) } else { blacks }; - (w.clamp(-100.0, 270.0), b.clamp(-100.0, 100.0)) + (w.clamp(WHITES_RANGE[0], WHITES_RANGE[1]), b.clamp(BLACKS_RANGE[0], BLACKS_RANGE[1])) } /// Applies Whites and Blacks (internal amounts `w`, `b`) to straight RGBA pixels (`width` per diff --git a/crates/gpu/examples/bench_camera_raw.rs b/crates/gpu/examples/bench_camera_raw.rs index be206fe382a..38f8f2709de 100644 --- a/crates/gpu/examples/bench_camera_raw.rs +++ b/crates/gpu/examples/bench_camera_raw.rs @@ -1,5 +1,6 @@ //! Camera Raw's preview develop on the 858×572 proxy of a 6000×4000 image: the CPU develop -//! against the GPU pass (upload, render, readback), for per-pixel settings. +//! against the GPU passes (upload, render, readback), for per-pixel settings and for Shadows and +//! Highlights with them. //! `cargo run --release -p photocraft-gpu --example bench_camera_raw [-- --quick]` use std::time::Instant; @@ -47,56 +48,62 @@ fn main() -> Result<(), Box> { let built = Instant::now(); let mut pass = CameraRawDevelop::new(&device)?; println!("pipeline build: {:.1} ms", built.elapsed().as_secs_f64() * 1e3); + // A photo-like proxy: gradients, noise and bright patches, so the filter has edges to keep. let src: Vec<[f32; 4]> = (0..w * h) .map(|i| { let (x, y) = ((i % w) as f32 / w as f32, (i / w) as f32 / h as f32); - [0.1 + 0.8 * x, 0.2 + 0.6 * y, 0.6 - 0.5 * x * y, 1.0] + let n = ((i as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) >> 40) as f32 / (1u64 << 24) as f32; + if (i / w) % 90 < 25 && (i % w) % 130 < 40 { + return [0.95, 0.92, 0.88, 1.0]; + } + let c = [0.02 + 0.8 * x * x, 0.05 + 0.6 * y, 0.6 - 0.5 * x * y].map(|v| (v + (n - 0.5) * 0.05).clamp(0.0, 1.0)); + [c[0], c[1], c[2], 1.0] }) .collect(); let scale = w as f32 / 6000.0; let mut hsl = [0.0; 8]; hsl[1] = 30.0; hsl[5] = -40.0; + let per_pixel_stages = CameraRaw { + temperature: 20.0, + tint: 5.0, + exposure: 0.4, + contrast: 25.0, + whites: 30.0, + blacks: -20.0, + vibrance: 30.0, + saturation: 10.0, + curve_lights: 20.0, + point_curve: vec![[0.0, 8.0], [128.0, 140.0], [255.0, 250.0]], + hsl_hue: hsl, + hsl_sat: hsl, + hsl_lum: hsl, + grade_shadows: Wheel { hue: 210.0, sat: 30.0, lum: 0.0 }, + grade_highlights: Wheel { hue: 40.0, sat: 20.0, lum: 5.0 }, + vignette_amount: -30.0, + grain_amount: 25.0, + pixel_scale: scale, + ..Default::default() + }; let sets = [ ( "Basic (WB, Exposure, Contrast, Whites, Blacks)", CameraRaw { temperature: 20.0, exposure: 0.4, contrast: 25.0, whites: 30.0, blacks: -20.0, pixel_scale: scale, ..Default::default() }, ), - ( - "every per-pixel stage", - CameraRaw { - temperature: 20.0, - tint: 5.0, - exposure: 0.4, - contrast: 25.0, - whites: 30.0, - blacks: -20.0, - vibrance: 30.0, - saturation: 10.0, - curve_lights: 20.0, - point_curve: vec![[0.0, 8.0], [128.0, 140.0], [255.0, 250.0]], - hsl_hue: hsl, - hsl_sat: hsl, - hsl_lum: hsl, - grade_shadows: Wheel { hue: 210.0, sat: 30.0, lum: 0.0 }, - grade_highlights: Wheel { hue: 40.0, sat: 20.0, lum: 5.0 }, - vignette_amount: -30.0, - grain_amount: 25.0, - pixel_scale: scale, - ..Default::default() - }, - ), + ("every per-pixel stage", per_pixel_stages.clone()), + ("Shadows +50", CameraRaw { shadows: 50.0, pixel_scale: scale, ..Default::default() }), + ("Highlights -50", CameraRaw { highlights: -50.0, pixel_scale: scale, ..Default::default() }), + ("Shadows +50, Highlights -50", CameraRaw { shadows: 50.0, highlights: -50.0, pixel_scale: scale, ..Default::default() }), + ("Shadows +50, Highlights -50, every per-pixel stage", CameraRaw { shadows: 50.0, highlights: -50.0, ..per_pixel_stages }), ]; for (name, p) in &sets { - let cpu = time(runs, || { + let toned = p.shadows != 0.0 || p.highlights != 0.0; + let cpu = time(if toned { runs.min(10) } else { runs }, || { let mut px = src.clone(); develop(&mut px, w, h, p, false); }); - let points_ms = time(runs, || { - std::hint::black_box(white_black_points(&src, w, h, p)); - }); let points = white_black_points(&src, w, h, p); - let stages = per_pixel(p, w, h, false, points).ok_or("not per pixel")?; + let stages = per_pixel(p, w, h, false, points).ok_or("not developed on the GPU")?; let size = [w as u32, h as u32]; let upload = try_time(runs, || pass.develop(&device, &queue, None, &src, None, size, &stages).map(drop))?; let cached = try_time(runs, || pass.develop(&device, &queue, None, &src, Some(1), size, &stages).map(drop))?; @@ -104,13 +111,12 @@ fn main() -> Result<(), Box> { println!(" CPU develop {cpu:7.2} ms"); println!(" GPU, source uploaded every time {upload:7.2} ms"); println!(" GPU, source cached (slider drag) {cached:7.2} ms"); - println!(" Whites/Blacks points on the CPU {points_ms:7.2} ms (cached per WB/Exposure/Contrast in the dialog)"); + if !toned && (p.whites != 0.0 || p.blacks != 0.0) { + let points_ms = time(runs, || { + std::hint::black_box(white_black_points(&src, w, h, p)); + }); + println!(" Whites/Blacks points on the CPU {points_ms:7.2} ms (cached per WB/Exposure/Contrast in the dialog)"); + } } - let shadows = CameraRaw { shadows: 50.0, pixel_scale: scale, ..Default::default() }; - let cpu = time(runs.min(10), || { - let mut px = src.clone(); - develop(&mut px, w, h, &shadows, false); - }); - println!("for reference, Shadows +50 (CPU only): {cpu:.2} ms"); Ok(()) } diff --git a/crates/gpu/src/camera_raw.rs b/crates/gpu/src/camera_raw.rs index 14f8a17e6c4..7ef82e39049 100644 --- a/crates/gpu/src/camera_raw.rs +++ b/crates/gpu/src/camera_raw.rs @@ -5,22 +5,27 @@ //! Saturation, the tone curves, the Color Mixer, Color Grading, the vignette and grain. Their //! constants and tables come from [`photocraft_algo::camera_raw::per_pixel`], which the CPU //! develop builds its own from, so both evaluate the same maths; the curves and the Whites and -//! Blacks rows are rows of one `R32Float` texture. Settings with a spatial stage (Dehaze, Shadows -//! and Highlights, Texture, Clarity, Detail) have no [`PerPixel`] and stay on the CPU. +//! Blacks rows are rows of one `R32Float` texture. Shadows and Highlights run before it as the +//! passes of `camera_raw_tone.rs`, which then also measure the image's points for Whites and +//! Blacks; this pass applies their change. Settings with another spatial stage (Dehaze, Texture, +//! Clarity, Detail) have no [`PerPixel`] and stay on the CPU. //! -//! The pipeline is built on demand ([`CameraRawDevelop::new`]), not with the compositor (#6419). -//! It renders into `Rgba32Float`; [`CameraRawDevelop::supported`] says whether the adapter can. +//! The pipelines are built on demand ([`CameraRawDevelop::new`]), not with the compositor +//! (#6419). They render into `Rgba32Float`, `R32Float` and `Rgba32Uint`; +//! [`CameraRawDevelop::supported`] says whether the adapter can. +use photocraft_algo::camera_raw::local_tone::LOG_FLOOR; use photocraft_algo::camera_raw::{CURVE_LUT, PerPixel, VignetteStyle, WB_STEPS}; use crate::Unsupported; +use crate::camera_raw_tone::{ToneFrame, TonePipelines, WB_ROW}; /// The pass's WGSL source. pub const CAMERA_RAW_SHADER: &str = include_str!("camera_raw.wgsl"); const FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba32Float; -/// `Params` in the shader: 19 rows of 16 bytes. -const PARAMS_SIZE: u64 = 19 * 16; +/// `Params` in the shader: 21 rows of 16 bytes. +const PARAMS_SIZE: u64 = 21 * 16; /// Rows of the table texture: parametric, master, red, green, blue curves; Whites, Blacks. const LUT_ROWS: u32 = 7; const LUT_WIDTH: u32 = CURVE_LUT as u32; @@ -53,6 +58,11 @@ impl Image { /// The Camera Raw preview pass and its textures (reused while the size stays). pub struct CameraRawDevelop { pipeline: wgpu::RenderPipeline, + /// `fs_log` and `fs_points`: Shadows and Highlights' input, Whites and Blacks' cells after it. + log: wgpu::RenderPipeline, + points: wgpu::RenderPipeline, + tone: TonePipelines, + tone_frame: Option, layout: wgpu::BindGroupLayout, params: wgpu::Buffer, luts: wgpu::Texture, @@ -64,9 +74,11 @@ pub struct CameraRawDevelop { } impl CameraRawDevelop { - /// Whether `adapter` can render the pass's `Rgba32Float` output. + /// Whether `adapter` can render the passes' `Rgba32Float`, `R32Float` and `Rgba32Uint` targets. pub fn supported(adapter: &wgpu::Adapter) -> bool { - adapter.get_texture_format_features(FORMAT).allowed_usages.contains(wgpu::TextureUsages::RENDER_ATTACHMENT) + [FORMAT, wgpu::TextureFormat::R32Float, wgpu::TextureFormat::Rgba32Uint] + .iter() + .all(|f| adapter.get_texture_format_features(*f).allowed_usages.contains(wgpu::TextureUsages::RENDER_ATTACHMENT)) } /// Builds the pipeline. A shader or pipeline the driver can't build is an `Err`, so the @@ -97,6 +109,9 @@ impl CameraRawDevelop { }, crate::tex_entry(1), crate::tex_entry(2), + crate::tex_entry(3), + crate::tex_entry(4), + crate::camera_raw_tone::uint_entry(5), ], }); let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { @@ -104,22 +119,27 @@ impl CameraRawDevelop { bind_group_layouts: &[Some(&layout)], immediate_size: 0, }); - let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: Some("pc_camera_raw"), - layout: Some(&pipeline_layout), - vertex: wgpu::VertexState { module: &module, entry_point: Some("vs"), buffers: &[], compilation_options: Default::default() }, - primitive: wgpu::PrimitiveState::default(), - depth_stencil: None, - multisample: wgpu::MultisampleState::default(), - fragment: Some(wgpu::FragmentState { - module: &module, - entry_point: Some("fs"), - targets: &[Some(wgpu::ColorTargetState { format: FORMAT, blend: None, write_mask: wgpu::ColorWrites::ALL })], - compilation_options: Default::default(), - }), - multiview_mask: None, - cache: None, - }); + let pipeline_for = |entry: &str, format: wgpu::TextureFormat| { + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(entry), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { module: &module, entry_point: Some("vs"), buffers: &[], compilation_options: Default::default() }, + primitive: wgpu::PrimitiveState::default(), + depth_stencil: None, + multisample: wgpu::MultisampleState::default(), + fragment: Some(wgpu::FragmentState { + module: &module, + entry_point: Some(entry), + targets: &[Some(wgpu::ColorTargetState { format, blend: None, write_mask: wgpu::ColorWrites::ALL })], + compilation_options: Default::default(), + }), + multiview_mask: None, + cache: None, + }) + }; + let pipeline = pipeline_for("fs", FORMAT); + let log = pipeline_for("fs_log", wgpu::TextureFormat::R32Float); + let points = pipeline_for("fs_points", FORMAT); let params = device.create_buffer(&wgpu::BufferDescriptor { label: Some("pc_camera_raw_params"), size: PARAMS_SIZE, @@ -133,12 +153,17 @@ impl CameraRawDevelop { sample_count: 1, dimension: wgpu::TextureDimension::D2, format: wgpu::TextureFormat::R32Float, - usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + // Whites and Blacks' rows are rendered in when Shadows and Highlights measure the points. + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::RENDER_ATTACHMENT, view_formats: &[], }); let luts_view = luts.create_view(&Default::default()); CameraRawDevelop { pipeline, + log, + points, + tone: TonePipelines::build(device), + tone_frame: None, layout, params, luts, @@ -181,7 +206,20 @@ impl CameraRawDevelop { ); src.key = key; } - queue.write_buffer(&self.params, 0, ¶ms(size, stages)); + let tone = match &stages.local_tone { + Some(t) => { + let frame = match self.tone_frame.take() { + Some(f) if f.size() == size => f, + _ => ToneFrame::new(device, size)?, + }; + let [slot_in, slot_out] = ToneFrame::last_slots(t); + let edge = self.tone_frame.insert(frame).points().2; + self.tone.write(queue, t, stages.measure_whites_blacks); + Some([slot_in, slot_out, edge, 0]) + } + None => None, + }; + queue.write_buffer(&self.params, 0, ¶ms(size, stages, tone)); queue.write_texture( wgpu::TexelCopyTextureInfo { texture: &self.luts, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, bytemuck::cast_slice(&tables(stages)), @@ -193,33 +231,34 @@ impl CameraRawDevelop { _ => Image::new(device, "pc_camera_raw_target", size, wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC), }; let target = self.target.insert(target); - let group = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("pc_camera_raw"), - layout: &self.layout, - entries: &[ - wgpu::BindGroupEntry { binding: 0, resource: self.params.as_entire_binding() }, - wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(&src.view) }, - wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(&self.luts_view) }, - ], - }); - { - let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + let (dummy, dummy_uint) = (self.tone.dummy(), self.tone.dummy_uint()); + let group = |log_in: &wgpu::TextureView, log_out: &wgpu::TextureView, stats: &wgpu::TextureView| { + device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("pc_camera_raw"), - color_attachments: &[Some(wgpu::RenderPassColorAttachment { - view: &target.view, - depth_slice: None, - resolve_target: None, - ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), store: wgpu::StoreOp::Store }, - })], - depth_stencil_attachment: None, - timestamp_writes: None, - occlusion_query_set: None, - multiview_mask: None, - }); - pass.set_pipeline(&self.pipeline); - pass.set_bind_group(0, &group, &[]); - pass.draw(0..3, 0..1); + layout: &self.layout, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: self.params.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(&src.view) }, + wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(&self.luts_view) }, + wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::TextureView(log_in) }, + wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(log_out) }, + wgpu::BindGroupEntry { binding: 5, resource: wgpu::BindingResource::TextureView(stats) }, + ], + }) + }; + let mut main = group(dummy, dummy, dummy_uint); + if let (Some(tone), Some(frame)) = (&stages.local_tone, self.tone_frame.as_mut()) { + // The input's log luminance, then the filter on it. + pass(encoder, &self.log, &main, frame.log_in()); + let measure = stages.measure_whites_blacks.is_some(); + frame.encode_tone(device, queue, &self.tone, encoder, tone, measure, &self.luts_view); + main = group(frame.log_in(), frame.log_out(), frame.stats()); + if measure { + pass(encoder, &self.points, &main, frame.points().0); + frame.encode_whites_blacks(&self.tone, encoder, tone); + } } + pass(encoder, &self.pipeline, &main, &target.view); Ok(&target.texture) } @@ -313,6 +352,26 @@ impl CameraRawDevelop { } } +/// One full-frame pass of `pipeline` into `target`. +fn pass(encoder: &mut wgpu::CommandEncoder, pipeline: &wgpu::RenderPipeline, group: &wgpu::BindGroup, target: &wgpu::TextureView) { + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("pc_camera_raw"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: target, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), store: wgpu::StoreOp::Store }, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + pass.set_pipeline(pipeline); + pass.set_bind_group(0, group, &[]); + pass.draw(0..3, 0..1); +} + fn check_size(device: &wgpu::Device, source: &[[f32; 4]], [w, h]: [u32; 2]) -> Result<(), Unsupported> { let max = device.limits().max_texture_dimension_2d; if w == 0 || h == 0 || w > max || h > max { @@ -327,12 +386,14 @@ fn check_size(device: &wgpu::Device, source: &[[f32; 4]], [w, h]: [u32; 2]) -> R /// Flags of `Params.flags`, in the shader's bit order. fn flags(s: &PerPixel) -> u32 { let wb = s.whites_blacks.as_ref(); + // Measured after Shadows and Highlights, the amounts keep the sliders' signs. + let measured = s.measure_whites_blacks; let on = [ s.gains.is_some(), s.contrast.is_some(), - wb.is_some_and(|w| w.whites.is_some()), - wb.is_some_and(|w| w.blacks.is_some()), - wb.is_some_and(|w| w.per_channel), + wb.is_some_and(|w| w.whites.is_some()) || measured.is_some_and(|[w, _]| w != 0.0), + wb.is_some_and(|w| w.blacks.is_some()) || measured.is_some_and(|[_, b]| b != 0.0), + wb.is_some_and(|w| w.per_channel) || measured.is_some_and(|[w, b]| w > 0.0 || b < 0.0), s.presence.is_some(), s.parametric.is_some(), s.point[0].is_some(), @@ -344,12 +405,13 @@ fn flags(s: &PerPixel) -> u32 { s.vignette.is_some(), s.grain.is_some(), s.clamp, + s.local_tone.is_some(), ]; on.iter().enumerate().fold(0, |f, (bit, on)| if *on { f | 1 << bit } else { f }) } -/// The shader's `Params` for a `size` image. -fn params(size: [u32; 2], s: &PerPixel) -> Vec { +/// The shader's `Params` for a `size` image; `tone` is `Params.tone` when Shadows and Highlights run. +fn params(size: [u32; 2], s: &PerPixel, tone: Option<[u32; 4]>) -> Vec { let g = s.gains.unwrap_or([1.0; 3]); let presence = s.presence.unwrap_or_default(); let hsl = s.hsl.unwrap_or_default(); @@ -382,6 +444,8 @@ fn params(size: [u32; 2], s: &PerPixel) -> Vec { let seed = grain.map_or(0, |gr| gr.seed); let fine = seed.wrapping_add(7); out.extend([seed as u32, (seed >> 32) as u32, fine as u32, (fine >> 32) as u32].iter().flat_map(|v| v.to_le_bytes())); + out.extend(tone.unwrap_or_default().iter().flat_map(|v| v.to_le_bytes())); + out.extend([LOG_FLOOR, 0.0, 0.0, 0.0].iter().flat_map(|v| v.to_le_bytes())); out } @@ -414,5 +478,5 @@ fn tables(s: &PerPixel) -> Vec { t } -// The Whites and Blacks rows fit a table row. -const _: () = assert!(WB_STEPS <= CURVE_LUT); +// The Whites and Blacks rows fit a table row, at the rows the tone passes render them into. +const _: () = assert!(WB_STEPS <= CURVE_LUT && WB_ROW == 5 && LUT_ROWS == WB_ROW + 2); diff --git a/crates/gpu/src/camera_raw.wgsl b/crates/gpu/src/camera_raw.wgsl index abad7cbbc14..da71aab38a8 100644 --- a/crates/gpu/src/camera_raw.wgsl +++ b/crates/gpu/src/camera_raw.wgsl @@ -1,6 +1,7 @@ // Camera Raw's per-pixel develop stages (`photocraft_algo::camera_raw::develop`, constants from // `camera_raw::per_pixel`), one fragment per pixel. Each function mirrors the CPU code it is -// named after, in the same order of operations; `camera_raw.rs` holds the bindings. +// named after, in the same order of operations; `camera_raw.rs` holds the bindings. Shadows and +// Highlights (`camera_raw_tone.wgsl`) start from `fs_log` and end here as a gain per pixel. struct Params { size: vec2, @@ -23,12 +24,21 @@ struct Params { grain: vec4, // The two octaves' seeds as (low, high) words. seeds: vec4, + // Shadows and Highlights: the last pass's statistics slots (input, output); the Whites and + // Blacks cells' edge. + tone: vec4, + // The log luminance's floor. + floor_: vec4, } @group(0) @binding(0) var P: Params; @group(0) @binding(1) var src: texture_2d; // R32Float rows of `LUT_WIDTH`: parametric, master, red, green, blue curves; Whites, Blacks rows. @group(0) @binding(2) var luts: texture_2d; +// Shadows and Highlights: the log luminance before and after, and the order statistics. +@group(0) @binding(3) var log_in: texture_2d; +@group(0) @binding(4) var log_out: texture_2d; +@group(0) @binding(5) var stats: texture_2d; const GAINS: u32 = 0u; const CONTRAST: u32 = 1u; @@ -44,6 +54,7 @@ const GRADE: u32 = 12u; const VIGNETTE: u32 = 13u; const GRAIN: u32 = 14u; const CLAMP: u32 = 15u; +const LOCAL_TONE: u32 = 16u; const CURVE_LUT: i32 = 1024; const WB_STEPS: i32 = 33; @@ -279,16 +290,34 @@ fn value_noise(x: f32, y: f32, seed: vec2) -> f32 { return top + (bot - top) * sy; } -@fragment -fn fs(@builtin(position) pos: vec4) -> @location(0) vec4 { - let p = vec2(floor(pos.xy)); - let q = textureLoad(src, p, 0); - var c = q.rgb; - // 1. White balance and exposure. +fn gained(v: f32, g: f32) -> f32 { + return linear_to_srgb(max(srgb_to_linear(v) * g, 0.0)); +} + +// 1. White balance and exposure. (Whole vectors: FXC unrolls any loop around a component written +// by index, and `fs_points` loops over this.) +fn balance(q: vec3) -> vec3 { if on(GAINS) { - for (var i = 0; i < 3; i++) { - c[i] = linear_to_srgb(max(srgb_to_linear(c[i]) * P.gains[i], 0.0)); - } + return vec3(gained(q.x, P.gains.x), gained(q.y, P.gains.y), gained(q.z, P.gains.z)); + } + return q; +} + +// `camera_raw_tone.wgsl`'s `unkey`. +fn unkey(k: u32) -> f32 { + return bitcast(select(~k, k ^ 0x80000000u, (k & 0x80000000u) != 0u)); +} + +// Stages 1 to 3 on the pixel at `p`: what Whites and Blacks measure and apply to. +fn tonal(p: vec2, q: vec3) -> vec3 { + var c = balance(q); + // 3. Shadows and Highlights: the light scaled by the change of the log luminance, the last + // pass's kept quantile put back. + if on(LOCAL_TONE) { + let shift = unkey(textureLoad(stats, vec2(i32(P.tone.x), 0), 0).y) - unkey(textureLoad(stats, vec2(i32(P.tone.y), 0), 0).x); + let change = (textureLoad(log_out, p, 0).r + shift) - textureLoad(log_in, p, 0).r; + let gain = exp2(change); + c = vec3(encode(decode(c.x) * gain), encode(decode(c.y) * gain), encode(decode(c.z) * gain)); } // 3. Contrast (without Texture and Clarity). if on(CONTRAST) { @@ -304,6 +333,40 @@ fn fs(@builtin(position) pos: vec4) -> @location(0) vec4 { c = c + vec3(lv - l0); } } + return c; +} + +// The log luminance Shadows and Highlights filter (`local_tone::apply`). +@fragment +fn fs_log(@builtin(position) pos: vec4) -> @location(0) vec4 { + let c = balance(textureLoad(src, vec2(floor(pos.xy)), 0).rgb); + let l = max(luma(vec3(decode(c.x), decode(c.y), decode(c.z))), 0.0); + return vec4(log2(l + P.floor_.x), 0.0, 0.0, 1.0); +} + +// `luminance_points`' cells after Shadows and Highlights: the luminance and the brightest +// channel of each `edge × edge` block's mean light (clipped to 0 … 1). +@fragment +fn fs_points(@builtin(position) pos: vec4) -> @location(0) vec4 { + let t = vec2(floor(pos.xy)); + let f = i32(P.tone.z); + let end = min((t + vec2(1)) * f, vec2(P.size)); + var sum = vec3(0.0); + for (var y = t.y * f; y < end.y; y++) { + for (var x = t.x * f; x < end.x; x++) { + let c = tonal(vec2(x, y), textureLoad(src, vec2(x, y), 0).rgb); + sum += clamp(vec3(decode(c.x), decode(c.y), decode(c.z)), vec3(0.0), vec3(1.0)); + } + } + let m = sum / f32((end.x - t.x * f) * (end.y - t.y * f)); + return vec4(luma(m), max(max(m.x, m.y), m.z), 0.0, 1.0); +} + +@fragment +fn fs(@builtin(position) pos: vec4) -> @location(0) vec4 { + let p = vec2(floor(pos.xy)); + let q = textureLoad(src, p, 0); + var c = tonal(p, q.rgb); // 3b. Whites and Blacks. if on(WHITES) || on(BLACKS) { c = whites_blacks(c); diff --git a/crates/gpu/src/camera_raw_tone.rs b/crates/gpu/src/camera_raw_tone.rs new file mode 100644 index 00000000000..55ef2786957 --- /dev/null +++ b/crates/gpu/src/camera_raw_tone.rs @@ -0,0 +1,852 @@ +//! Shadows and Highlights for Camera Raw's GPU preview (#6916): the local Laplacian filter of +//! `photocraft_algo::camera_raw::local_tone` as fragment passes (`camera_raw_tone.wgsl`), with no +//! compute shaders, so the same passes can run on WebGL2. +//! +//! Each [`TonePass`](photocraft_algo::camera_raw::TonePass) builds the Gaussian pyramid of its +//! input, the remapped pyramids of up to [`MAX_REFS`] references (four per `Rgba32Float` tile, all +//! tiles of a level in one atlas), and the output from coarse to fine, each coefficient +//! interpolated between the two references around the input there. The quantiles the filter and +//! Whites and Blacks read are exact order statistics, found on the GPU by narrowing an interval of +//! keys in [`ROUNDS`] rounds of [`SPLITS`] thresholds, so nothing is read back before the +//! per-pixel pass (`camera_raw.wgsl`) applies the change. +//! +//! The textures and the list of passes are built once per frame size and set of passes +//! ([`ToneFrame`]); a develop only writes the settings uniform and records the passes. + +use std::collections::HashMap; + +use photocraft_algo::camera_raw::local_tone::{KNOTS, MAX_REFS, RANGE_QUANTILES, RANGE_SIDE, REF_LOW_QUANTILE, REF_STEP, TAPS}; +use photocraft_algo::camera_raw::{LocalTone, ToneKind, WhitesBlacksModel, quantile_rank}; + +use crate::Unsupported; + +/// The passes' WGSL source. +pub const CAMERA_RAW_TONE_SHADER: &str = include_str!("camera_raw_tone.wgsl"); + +const PLANE: wgpu::TextureFormat = wgpu::TextureFormat::R32Float; +const RGBA: wgpu::TextureFormat = wgpu::TextureFormat::Rgba32Float; +const UINT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba32Uint; +/// `Step` in the shader: five rows of 16 bytes, one per uniform slot of [`SLOT`] bytes. +const STEP_SIZE: u64 = 5 * 16; +const SLOT: u64 = 256; +/// `Tone` in the shader. +const TONE_SIZE: u64 = 16 * 16; +/// Thresholds per round of a selection: each round splits the key interval into `SPLITS + 1`. +const SPLITS: u32 = 16; +/// Rounds until the interval of every key (2^32) is down to one key. +const ROUNDS: usize = rounds(); +/// Values per tile edge counted by one fragment; counts are summed in tiles of the same edge until +/// at most [`SUM_MAX`] tiles remain, which a round's update sums. +const COUNT_TILE: u32 = 16; +const SUM_MAX: u32 = 256; + +/// [`ROUNDS`]: the widest part `fs_update` can leave of an interval `span` keys wide (less one), +/// until it is 0. +const fn rounds() -> usize { + let mut span: u64 = u32::MAX as u64; + let mut n = 0; + while span > 0 { + let q = span / (SPLITS as u64 + 1) + 1; + let last = span.saturating_sub(SPLITS as u64 * q); + span = if q - 1 > last { q - 1 } else { last }; + n += 1; + } + n +} + +/// Reference groups (four per tile). +const GROUPS: u32 = MAX_REFS.div_ceil(4) as u32; +/// Statistics slots: pass `i`'s input and output are `2i` and `2i + 1`; Whites and Blacks' points. +const WB_SLOT: u32 = 4; +const SLOTS: u32 = 5; +/// Rows of `camera_raw.wgsl`'s table texture that hold the Whites and Blacks curves. +pub(crate) const WB_ROW: u32 = 5; + +// The shader's knot interpolation and taps are written for these sizes. +const _: () = assert!(KNOTS == 5 && TAPS.len() == 5); + +/// A texture and its view. +struct Tex { + texture: wgpu::Texture, + view: wgpu::TextureView, +} + +impl Tex { + fn new(device: &wgpu::Device, label: &str, [w, h]: [u32; 2], format: wgpu::TextureFormat, usage: wgpu::TextureUsages) -> Self { + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some(label), + size: wgpu::Extent3d { width: w.max(1), height: h.max(1), depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage, + view_formats: &[], + }); + let view = texture.create_view(&Default::default()); + Tex { texture, view } + } + + fn target(device: &wgpu::Device, label: &str, size: [u32; 2], format: wgpu::TextureFormat) -> Self { + Tex::new(device, label, size, format, wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING) + } +} + +fn tex_entry(binding: u32, sample_type: wgpu::TextureSampleType) -> wgpu::BindGroupLayoutEntry { + wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { multisampled: false, sample_type, view_dimension: wgpu::TextureViewDimension::D2 }, + count: None, + } +} + +/// A `u32` texture binding. +pub(crate) fn uint_entry(binding: u32) -> wgpu::BindGroupLayoutEntry { + tex_entry(binding, wgpu::TextureSampleType::Uint) +} + +/// The passes' entry points. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +enum Pipe { + Down, + DownRemap, + DownAtlas, + Lap, + Shift, + Cells, + Init, + Count, + Reduce, + Update, + WbRows, +} + +impl Pipe { + const ALL: [Pipe; 11] = + [Pipe::Down, Pipe::DownRemap, Pipe::DownAtlas, Pipe::Lap, Pipe::Shift, Pipe::Cells, Pipe::Init, Pipe::Count, Pipe::Reduce, Pipe::Update, Pipe::WbRows]; + + fn entry(self) -> &'static str { + match self { + Pipe::Down => "fs_down", + Pipe::DownRemap => "fs_down_remap", + Pipe::DownAtlas => "fs_down_atlas", + Pipe::Lap => "fs_lap", + Pipe::Shift => "fs_shift", + Pipe::Cells => "fs_cells", + Pipe::Init => "fs_init", + Pipe::Count => "fs_count", + Pipe::Reduce => "fs_reduce", + Pipe::Update => "fs_update", + Pipe::WbRows => "fs_wb_rows", + } + } + + fn targets(self) -> &'static [wgpu::TextureFormat] { + match self { + Pipe::DownRemap | Pipe::DownAtlas => &[RGBA], + Pipe::Init | Pipe::Update => &[UINT], + Pipe::Count | Pipe::Reduce => &[UINT, UINT], + _ => &[PLANE], + } + } +} + +/// The passes' pipelines, the settings uniform and the Whites and Blacks tables. +pub(crate) struct TonePipelines { + layout: wgpu::BindGroupLayout, + pipelines: HashMap, + settings: wgpu::Buffer, + model: Tex, + model_written: bool, + /// Bound where a pass reads nothing. + dummy: Tex, + dummy_uint: Tex, +} + +/// Rows of the Whites and Blacks model texture, in order: Whites curves, Blacks curves, the two +/// adaptation tables, the black points, the white points. +struct ModelRows { + whites: u32, + blacks: u32, + whites_adapt: u32, + blacks_adapt: u32, + black_points: u32, + white_points: u32, + rows: u32, + width: u32, +} + +fn model_rows(m: &WhitesBlacksModel) -> ModelRows { + let whites = 0; + let blacks = whites + m.whites.len() as u32; + let whites_adapt = blacks + m.blacks.len() as u32; + let blacks_adapt = whites_adapt + m.whites_adapt.len() as u32; + let black_points = blacks_adapt + m.blacks_adapt.len() as u32; + let white_points = black_points + 1; + let width = [m.whites.first().map_or(0, |r| r.len()), m.black_points.len(), m.white_points.len(), m.whites_adapt[0].len()].into_iter().max().unwrap_or(1); + ModelRows { whites, blacks, whites_adapt, blacks_adapt, black_points, white_points, rows: white_points + 1, width: width as u32 } +} + +impl TonePipelines { + pub(crate) fn build(device: &wgpu::Device) -> Self { + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("pc_camera_raw_tone"), + source: wgpu::ShaderSource::Wgsl(CAMERA_RAW_TONE_SHADER.into()), + }); + let float = wgpu::TextureSampleType::Float { filterable: false }; + let uniform = |binding, dynamic, size| wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: dynamic, min_binding_size: wgpu::BufferSize::new(size) }, + count: None, + }; + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("pc_camera_raw_tone"), + entries: &[ + uniform(0, true, STEP_SIZE), + uniform(1, false, TONE_SIZE), + tex_entry(2, float), + tex_entry(3, float), + tex_entry(4, float), + tex_entry(5, float), + uint_entry(6), + uint_entry(7), + uint_entry(8), + uint_entry(9), + tex_entry(10, float), + ], + }); + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("pc_camera_raw_tone"), + bind_group_layouts: &[Some(&layout)], + immediate_size: 0, + }); + let pipelines = Pipe::ALL + .iter() + .map(|&pipe| { + let targets: Vec> = + pipe.targets().iter().map(|&format| Some(wgpu::ColorTargetState { format, blend: None, write_mask: wgpu::ColorWrites::ALL })).collect(); + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(pipe.entry()), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { module: &module, entry_point: Some("vs"), buffers: &[], compilation_options: Default::default() }, + primitive: wgpu::PrimitiveState::default(), + depth_stencil: None, + multisample: wgpu::MultisampleState::default(), + fragment: Some(wgpu::FragmentState { + module: &module, + entry_point: Some(pipe.entry()), + targets: &targets, + compilation_options: Default::default(), + }), + multiview_mask: None, + cache: None, + }); + (pipe, pipeline) + }) + .collect(); + let settings = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("pc_camera_raw_tone_settings"), + size: TONE_SIZE, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let rows = model_rows(&photocraft_algo::camera_raw::whites_blacks_model()); + let model = + Tex::new(device, "pc_camera_raw_wb_model", [rows.width, rows.rows], PLANE, wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST); + let sampled = wgpu::TextureUsages::TEXTURE_BINDING; + TonePipelines { + layout, + pipelines, + settings, + model, + model_written: false, + dummy: Tex::new(device, "pc_camera_raw_tone_dummy", [1, 1], PLANE, sampled), + dummy_uint: Tex::new(device, "pc_camera_raw_tone_dummy_uint", [1, 1], UINT, sampled), + } + } + + /// A plane bound where a pass reads nothing (for `camera_raw.wgsl`'s bindings too). + pub(crate) fn dummy(&self) -> &wgpu::TextureView { + &self.dummy.view + } + + pub(crate) fn dummy_uint(&self) -> &wgpu::TextureView { + &self.dummy_uint.view + } + + /// Writes the settings uniform for `tone` and Whites and Blacks' sliders, and the model once. + pub(crate) fn write(&mut self, queue: &wgpu::Queue, tone: &LocalTone, whites_blacks: Option<[f32; 2]>) { + let m = photocraft_algo::camera_raw::whites_blacks_model(); + let rows = model_rows(&m); + if !self.model_written { + let width = rows.width as usize; + let mut data = vec![0.0f32; width * rows.rows as usize]; + let mut put = |row: u32, v: &[f32]| { + let start = row as usize * width; + for (d, s) in data.iter_mut().skip(start).take(width).zip(v) { + *d = *s; + } + }; + for (k, r) in m.whites.iter().enumerate() { + put(rows.whites + k as u32, r); + } + for (k, r) in m.blacks.iter().enumerate() { + put(rows.blacks + k as u32, r); + } + for (k, r) in m.whites_adapt.iter().enumerate() { + put(rows.whites_adapt + k as u32, r); + } + for (k, r) in m.blacks_adapt.iter().enumerate() { + put(rows.blacks_adapt + k as u32, r); + } + put(rows.black_points, m.black_points); + put(rows.white_points, m.white_points); + queue.write_texture( + wgpu::TexelCopyTextureInfo { texture: &self.model.texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, + bytemuck::cast_slice(&data), + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(rows.width * 4), rows_per_image: Some(rows.rows) }, + wgpu::Extent3d { width: rows.width, height: rows.rows, depth_or_array_layers: 1 }, + ); + self.model_written = true; + } + let mut f: Vec = Vec::with_capacity(TONE_SIZE as usize / 4); + for i in 0..2 { + f.extend(tone.passes.get(i).map_or([0.0; 4], |p| [if p.kind == ToneKind::Highlights { 0.0 } else { 1.0 }, p.amount, p.sigma, 0.0])); + } + let mut knots = [0.0f32; 20]; + for (i, p) in tone.passes.iter().take(2).enumerate() { + for (r, row) in p.knots.iter().enumerate() { + for (k, v) in row.iter().enumerate() { + if let Some(slot) = knots.get_mut(i * 10 + r * 5 + k) { + *slot = *v; + } + } + } + } + f.extend(knots); + f.extend([REF_STEP, MAX_REFS as f32, 0.0, 0.0]); + f.extend([TAPS[0], TAPS[1], TAPS[2], TAPS[3], TAPS[4], 0.0, 0.0, 0.0]); + let [whites, blacks] = whites_blacks.unwrap_or_default(); + f.extend([whites, blacks, m.row_step, m.photo_blacks]); + f.extend([m.whites_from, m.blacks_from, 0.0, 0.0]); + f.extend([m.whites_range[0], m.whites_range[1], m.blacks_range[0], m.blacks_range[1]]); + let mut bytes: Vec = bytemuck::cast_slice(&f).to_vec(); + let u = [ + rows.whites, + rows.blacks, + rows.whites_adapt, + rows.blacks_adapt, + rows.black_points, + rows.white_points, + m.black_points.len() as u32, + m.white_points.len() as u32, + m.whites.len() as u32, + m.blacks.len() as u32, + 0, + 0, + ]; + bytes.extend(u.iter().flat_map(|v| v.to_le_bytes())); + bytes.resize(TONE_SIZE as usize, 0); + queue.write_buffer(&self.settings, 0, &bytes); + } +} + +/// One pass's uniform slot (`Step` in the shader). +#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)] +struct Step { + sizes: [u32; 4], + sizes2: [u32; 4], + misc: [u32; 4], + ranks: [[u32; 4]; 2], +} + +impl Step { + fn sized(dst: [u32; 2], src: [u32; 2]) -> Self { + Step { sizes: [dst[0], dst[1], src[0], src[1]], ..Default::default() } + } + fn bytes(&self) -> impl Iterator + '_ { + [self.sizes, self.sizes2, self.misc, self.ranks[0], self.ranks[1]].into_iter().flatten().flat_map(u32::to_le_bytes) + } +} + +/// The textures one pass reads (unset ones are dummies). +#[derive(Clone, Default, PartialEq, Eq, Hash)] +struct Reads { + a: Option, + b: Option, + fine: Option, + coarse: Option, + ua: Option, + ub: Option, + uc: Option, +} + +/// A recorded pass, or the copy of a bisection's result (column 0 of its state) into a slot. +enum Op { + Draw { pipe: Pipe, group: wgpu::BindGroup, offset: u32, targets: Vec, viewport: Option<[f32; 4]> }, + Result { state: wgpu::Texture, slot: u32 }, +} + +/// A pass before its uniform slot and bind group exist (a list built once per plan). +#[allow(clippy::large_enum_variant)] +enum Pending { + Draw { pipe: Pipe, step: Step, reads: Reads, targets: Vec, viewport: Option<[f32; 4]> }, + Result { state: wgpu::Texture, slot: u32 }, +} + +/// Count textures for selections over a source of one size: per stage, both banks and the size. +struct Chain { + stages: Vec<([Tex; 2], [u32; 2])>, +} + +impl Chain { + fn new(device: &wgpu::Device, [w, h]: [u32; 2]) -> Self { + let mut stages = Vec::new(); + let mut size = [w.div_ceil(COUNT_TILE), h.div_ceil(COUNT_TILE)]; + loop { + // Each tile has a column per threshold. + let texels = [size[0] * SPLITS, size[1]]; + stages.push(([Tex::target(device, "pc_camera_raw_counts_a", texels, UINT), Tex::target(device, "pc_camera_raw_counts_b", texels, UINT)], size)); + if size[0] * size[1] <= SUM_MAX { + break; + } + size = [size[0].div_ceil(COUNT_TILE), size[1].div_ceil(COUNT_TILE)]; + } + Chain { stages } + } +} + +/// Collects a plan's passes. +#[derive(Default)] +struct Builder { + ops: Vec, +} + +impl Builder { + fn draw(&mut self, pipe: Pipe, step: Step, reads: Reads, targets: &[&wgpu::TextureView], viewport: Option<[f32; 4]>) { + self.ops.push(Pending::Draw { pipe, step, reads, targets: targets.iter().map(|v| (*v).clone()).collect(), viewport }); + } + + /// Order statistics by bisection, into statistics slot `slot`: bank 0 of `source` (`size` + /// texels; its red channel in all four, or with `channels` its four channels), bank 1 of the + /// red channel of `second`, at `ranks` (0-based, below the counts). + #[allow(clippy::too_many_arguments)] + fn select( + &mut self, + source: &wgpu::TextureView, + size: [u32; 2], + channels: bool, + second: Option<(&wgpu::TextureView, [u32; 2])>, + ranks: [[u32; 4]; 2], + slot: u32, + chain: &Chain, + state: &[Tex; 2], + ) { + let (Some(first), Some(last)) = (chain.stages.first(), chain.stages.last()) else { return }; + self.draw(Pipe::Init, Step::default(), Reads::default(), &[&state[0].view], None); + let (second, second_size) = second.map_or((None, [0, 0]), |(v, s)| (Some(v.clone()), s)); + let mut count = Step::sized(first.1, size); + count.sizes2 = [second_size[0], second_size[1], 0, COUNT_TILE]; + count.misc = [0, 0, u32::from(channels), SPLITS]; + let mut update = Step::sized([2, 2], last.1); + update.misc[3] = SPLITS; + update.ranks = ranks; + let mut cur = 0; + for _ in 0..ROUNDS { + let reads = Reads { a: Some(source.clone()), b: second.clone(), ua: Some(state[cur].view.clone()), ..Default::default() }; + self.draw(Pipe::Count, count, reads, &[&first.0[0].view, &first.0[1].view], None); + for w in chain.stages.windows(2) { + let (from, to) = (&w[0], &w[1]); + let mut step = Step::sized(to.1, from.1); + step.sizes2[3] = COUNT_TILE; + step.misc[3] = SPLITS; + let reads = Reads { ua: Some(from.0[0].view.clone()), ub: Some(from.0[1].view.clone()), ..Default::default() }; + self.draw(Pipe::Reduce, step, reads, &[&to.0[0].view, &to.0[1].view], None); + } + let reads = Reads { ua: Some(state[cur].view.clone()), ub: Some(last.0[0].view.clone()), uc: Some(last.0[1].view.clone()), ..Default::default() }; + self.draw(Pipe::Update, update, reads, &[&state[1 - cur].view], None); + cur = 1 - cur; + } + self.ops.push(Pending::Result { state: state[cur].texture.clone(), slot }); + } + + /// The passes with their uniform slots in `steps` (written here) and their bind groups. + fn finish(self, device: &wgpu::Device, queue: &wgpu::Queue, pipes: &TonePipelines, stats: &wgpu::TextureView) -> (wgpu::Buffer, Vec) { + let mut steps: Vec = Vec::new(); + let mut slots: HashMap = HashMap::new(); + for op in &self.ops { + if let Pending::Draw { step, .. } = op { + slots.entry(*step).or_insert_with(|| { + steps.push(*step); + steps.len() as u32 - 1 + }); + } + } + let buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("pc_camera_raw_tone_steps"), + size: steps.len().max(1) as u64 * SLOT, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let mut data = vec![0u8; steps.len() * SLOT as usize]; + for (chunk, step) in data.chunks_mut(SLOT as usize).zip(&steps) { + for (d, v) in chunk.iter_mut().zip(step.bytes()) { + *d = v; + } + } + queue.write_buffer(&buffer, 0, &data); + // wgpu resources hash and compare by identity, which never changes. + #[allow(clippy::mutable_key_type)] + let mut groups: HashMap = HashMap::new(); + let ops = self + .ops + .into_iter() + .map(|op| match op { + Pending::Draw { pipe, step, reads, targets, viewport } => { + let group = groups.entry(reads.clone()).or_insert_with(|| pipes.group(device, &buffer, &reads, stats)).clone(); + let offset = slots.get(&step).copied().unwrap_or(0) * SLOT as u32; + Op::Draw { pipe, group, offset, targets, viewport } + } + Pending::Result { state, slot } => Op::Result { state, slot }, + }) + .collect(); + (buffer, ops) + } +} + +impl TonePipelines { + fn group(&self, device: &wgpu::Device, steps: &wgpu::Buffer, r: &Reads, stats: &wgpu::TextureView) -> wgpu::BindGroup { + fn or<'a>(v: &'a Option, dummy: &'a wgpu::TextureView) -> wgpu::BindingResource<'a> { + wgpu::BindingResource::TextureView(v.as_ref().unwrap_or(dummy)) + } + let step = wgpu::BufferBinding { buffer: steps, offset: 0, size: wgpu::BufferSize::new(STEP_SIZE) }; + let entries = [ + wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::Buffer(step) }, + wgpu::BindGroupEntry { binding: 1, resource: self.settings.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 2, resource: or(&r.a, &self.dummy.view) }, + wgpu::BindGroupEntry { binding: 3, resource: or(&r.b, &self.dummy.view) }, + wgpu::BindGroupEntry { binding: 4, resource: or(&r.fine, &self.dummy.view) }, + wgpu::BindGroupEntry { binding: 5, resource: or(&r.coarse, &self.dummy.view) }, + wgpu::BindGroupEntry { binding: 6, resource: wgpu::BindingResource::TextureView(stats) }, + wgpu::BindGroupEntry { binding: 7, resource: or(&r.ua, &self.dummy_uint.view) }, + wgpu::BindGroupEntry { binding: 8, resource: or(&r.ub, &self.dummy_uint.view) }, + wgpu::BindGroupEntry { binding: 9, resource: or(&r.uc, &self.dummy_uint.view) }, + wgpu::BindGroupEntry { binding: 10, resource: wgpu::BindingResource::TextureView(&self.model.view) }, + ]; + device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("pc_camera_raw_tone"), layout: &self.layout, entries: &entries }) + } +} + +/// What a plan runs: the passes' kept quantiles (their bits), and whether Whites and Blacks +/// measure the points. +#[derive(Clone, PartialEq, Eq, Hash)] +struct PlanKey { + keeps: Vec, + whites_blacks: bool, +} + +impl PlanKey { + fn new(tone: &LocalTone, whites_blacks: bool) -> Self { + PlanKey { keeps: tone.passes.iter().map(|p| p.keep.to_bits()).collect(), whites_blacks } + } +} + +/// The recorded passes for one [`PlanKey`]. +struct Plan { + /// Holds the passes' uniform slots. + _steps: wgpu::Buffer, + /// Shadows and Highlights. + tone: Vec, + /// Whites and Blacks' points and curves, after `camera_raw.wgsl`'s `fs_points`. + whites_blacks: Vec, +} + +/// Pyramid level sizes down to about 2 pixels on the short side (`local_tone::depth`). +fn levels([w, h]: [u32; 2]) -> Vec<[u32; 2]> { + let mut out = vec![[w, h]]; + let (mut s, mut level) = (w.min(h), [w, h]); + while s > 2 { + s = s.div_ceil(2); + level = level.map(|v| v.div_ceil(2)); + out.push(level); + } + out +} + +/// The filter's textures for one frame size, and its plans. +pub(crate) struct ToneFrame { + size: [u32; 2], + /// Pyramid level sizes, finest first (at least two). + levels: Vec<[u32; 2]>, + /// Atlas columns. + cols: u32, + /// The first pass's input, which `fs_log` renders. + log_in: Tex, + /// The second pass's input. + input: Tex, + /// The input's Gaussian pyramid (index 0 unused: level 0 is the input). + gauss: Vec, + /// The remapped pyramids (index 0 unused). + atlas: Vec, + /// The output, level by level (0 … n − 2). + out: Vec, + /// The range's cells. + cells: Tex, + cells_size: [u32; 2], + /// Whites and Blacks' cells, which `fs_points` renders. + points: Tex, + points_size: [u32; 2], + points_edge: u32, + full: Chain, + small: Chain, + state: [Tex; 2], + stats: Tex, + plans: HashMap, +} + +impl ToneFrame { + /// The textures for a `size` frame, or `Unsupported` where they don't fit the device. + pub(crate) fn new(device: &wgpu::Device, size: [u32; 2]) -> Result { + let levels = levels(size); + let n = levels.len(); + let Some(&[w1, h1]) = levels.get(1) else { + return Err(Unsupported(format!("a {}×{} frame is too small for the Shadows and Highlights pyramid", size[0], size[1]))); + }; + let max = device.limits().max_texture_dimension_2d; + // The squarest atlas of the reference groups. + let cols = (1..=GROUPS).min_by_key(|c| (c * w1).max(GROUPS.div_ceil(*c) * h1)).unwrap_or(GROUPS); + let rows = GROUPS.div_ceil(cols); + if cols * w1 > max || rows * h1 > max { + return Err(Unsupported(format!("Shadows and Highlights' {}×{} atlas doesn't fit the GPU's {max} px textures", cols * w1, rows * h1))); + } + let cells_of = |side: usize| { + let f = size[0].max(size[1]).div_ceil(side as u32).max(1); + ([size[0].div_ceil(f), size[1].div_ceil(f)], f) + }; + let (cells_size, _) = cells_of(RANGE_SIDE); + let (points_size, points_edge) = cells_of(photocraft_algo::camera_raw::whites_blacks_model().points_side); + let plane = |label: &str, s: [u32; 2]| Tex::target(device, label, s, PLANE); + Ok(ToneFrame { + size, + cols, + log_in: plane("pc_camera_raw_log_in", size), + input: plane("pc_camera_raw_tone_input", size), + gauss: levels.iter().enumerate().map(|(l, &s)| plane("pc_camera_raw_gauss", if l == 0 { [1, 1] } else { s })).collect(), + atlas: levels + .iter() + .enumerate() + .map(|(l, &[lw, lh])| Tex::target(device, "pc_camera_raw_atlas", if l == 0 { [1, 1] } else { [cols * lw, rows * lh] }, RGBA)) + .collect(), + out: levels.iter().take(n - 1).map(|&s| plane("pc_camera_raw_tone_out", s)).collect(), + cells: plane("pc_camera_raw_tone_cells", cells_size), + cells_size, + points: Tex::target(device, "pc_camera_raw_wb_cells", points_size, RGBA), + points_size, + points_edge, + full: Chain::new(device, size), + small: Chain::new(device, points_size), + state: [0, 1].map(|_| { + let usage = wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_SRC; + Tex::new(device, "pc_camera_raw_select", [2, 2], UINT, usage) + }), + stats: Tex::new(device, "pc_camera_raw_stats", [SLOTS, 2], UINT, wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST), + levels, + plans: HashMap::new(), + }) + } + + pub(crate) fn size(&self) -> [u32; 2] { + self.size + } + + /// The log luminance the first pass filters (`camera_raw.wgsl`'s `fs_log` renders it). + pub(crate) fn log_in(&self) -> &wgpu::TextureView { + &self.log_in.view + } + + /// The last pass's output, before its kept quantile is put back. + pub(crate) fn log_out(&self) -> &wgpu::TextureView { + &self.out[0].view + } + + pub(crate) fn stats(&self) -> &wgpu::TextureView { + &self.stats.view + } + + /// Whites and Blacks' cells (rendered by `fs_points`), their size and edge in pixels. + pub(crate) fn points(&self) -> (&wgpu::TextureView, [u32; 2], u32) { + (&self.points.view, self.points_size, self.points_edge) + } + + /// The statistics slots of the last pass of `tone`: its input's and its output's. + pub(crate) fn last_slots(tone: &LocalTone) -> [u32; 2] { + let i = tone.passes.len().saturating_sub(1) as u32; + [2 * i, 2 * i + 1] + } + + /// Records Shadows and Highlights on `log_in`: then `log_out` and `stats` hold the result. + /// `luts` is `camera_raw.wgsl`'s table texture, where Whites and Blacks' curves go. + #[allow(clippy::too_many_arguments)] + pub(crate) fn encode_tone( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + pipes: &TonePipelines, + encoder: &mut wgpu::CommandEncoder, + tone: &LocalTone, + whites_blacks: bool, + luts: &wgpu::TextureView, + ) { + let key = PlanKey::new(tone, whites_blacks); + if !self.plans.contains_key(&key) { + let plan = self.plan(device, queue, pipes, &key, luts); + self.plans.insert(key.clone(), plan); + } + if let Some(plan) = self.plans.get(&key) { + record(encoder, &plan.tone, pipes, &self.stats.texture); + } + } + + /// Records Whites and Blacks' points and curves (rows [`WB_ROW`] and the next of `luts`), + /// after `fs_points` rendered the cells. + pub(crate) fn encode_whites_blacks(&self, pipes: &TonePipelines, encoder: &mut wgpu::CommandEncoder, tone: &LocalTone) { + if let Some(plan) = self.plans.get(&PlanKey::new(tone, true)) { + record(encoder, &plan.whites_blacks, pipes, &self.stats.texture); + } + } + + fn plan(&self, device: &wgpu::Device, queue: &wgpu::Queue, pipes: &TonePipelines, key: &PlanKey, luts: &wgpu::TextureView) -> Plan { + let mut b = Builder::default(); + let n = self.levels.len(); + let full = self.size; + let count = full[0] * full[1]; + let cells = self.cells_size[0] * self.cells_size[1]; + let rank = |len: u32, q: f32| (quantile_rank(len as usize, q) as u32).min(len.saturating_sub(1)); + let v = |t: &Tex| Some(t.view.clone()); + for (i, keep) in key.keeps.iter().enumerate() { + let keep = f32::from_bits(*keep); + let i = i as u32; + let (slot_in, slot_out) = (2 * i, 2 * i + 1); + let input = if i == 0 { &self.log_in } else { &self.input }; + let level = |l: usize| if l == 0 { input } else { &self.gauss[l] }; + // The input's Gaussian pyramid. + for l in 0..n - 1 { + b.draw( + Pipe::Down, + Step::sized(self.levels[l + 1], self.levels[l]), + Reads { a: v(level(l)), ..Default::default() }, + &[&self.gauss[l + 1].view], + None, + ); + } + // Its range, the lowest reference, the kept quantile and the highest reference. + let mut step = Step::sized(self.cells_size, full); + step.sizes2[3] = full[0].max(full[1]).div_ceil(RANGE_SIDE as u32).max(1); + b.draw(Pipe::Cells, step, Reads { a: v(input), ..Default::default() }, &[&self.cells.view], None); + let ranks = [ + [rank(count, REF_LOW_QUANTILE), rank(count, keep), count - 1, count - 1], + [rank(cells, RANGE_QUANTILES[0]), rank(cells, RANGE_QUANTILES[1]), 0, 0], + ]; + b.select(&input.view, full, false, Some((&self.cells.view, self.cells_size)), ranks, slot_in, &self.full, &self.state); + // The remapped pyramids. + let mut step = Step::sized(self.levels[1], full); + step.sizes2[2] = self.cols; + step.misc = [i, slot_in, 0, 0]; + b.draw(Pipe::DownRemap, step, Reads { a: v(input), ..Default::default() }, &[&self.atlas[1].view], None); + for l in 1..n - 1 { + let mut step = Step::sized(self.levels[l + 1], self.levels[l]); + step.sizes2[2] = self.cols; + step.misc = [i, slot_in, 0, 0]; + b.draw(Pipe::DownAtlas, step, Reads { fine: v(&self.atlas[l]), ..Default::default() }, &[&self.atlas[l + 1].view], None); + } + // The output, coarse to fine. + for l in (0..n - 1).rev() { + let mut step = Step::sized(self.levels[l], self.levels[l + 1]); + step.sizes2[2] = self.cols; + step.misc = [i, slot_in, u32::from(l == 0), 0]; + let coarse = if l == n - 2 { &self.gauss[n - 1] } else { &self.out[l + 1] }; + let reads = Reads { + a: v(level(l)), + b: v(coarse), + fine: if l > 0 { v(&self.atlas[l]) } else { None }, + coarse: v(&self.atlas[l + 1]), + ..Default::default() + }; + b.draw(Pipe::Lap, step, reads, &[&self.out[l].view], None); + } + b.select(&self.out[0].view, full, false, None, [[rank(count, keep), 0, 0, 0], [0; 4]], slot_out, &self.full, &self.state); + if (i as usize) + 1 < key.keeps.len() { + let mut step = Step::sized(full, full); + step.misc = [i, slot_in, 0, slot_out]; + b.draw(Pipe::Shift, step, Reads { a: v(&self.out[0]), ..Default::default() }, &[&self.input.view], None); + } + } + let split = b.ops.len(); + if key.whites_blacks { + let points = self.points_size[0] * self.points_size[1]; + let q = photocraft_algo::camera_raw::whites_blacks_model().point_quantiles; + b.select( + &self.points.view, + self.points_size, + true, + None, + [[rank(points, q[0]), rank(points, q[1]), 0, 0], [0; 4]], + WB_SLOT, + &self.small, + &self.state, + ); + let step = Step { misc: [0, WB_SLOT, WB_ROW, 0], ..Default::default() }; + let rows = Some([0.0, WB_ROW as f32, photocraft_algo::camera_raw::WB_STEPS as f32, 2.0]); + b.draw(Pipe::WbRows, step, Reads::default(), &[luts], rows); + } + let (steps, mut tone) = b.finish(device, queue, pipes, &self.stats.view); + let whites_blacks = tone.split_off(split.min(tone.len())); + Plan { _steps: steps, tone, whites_blacks } + } +} + +/// Records `ops`; results go into `stats`. +fn record(encoder: &mut wgpu::CommandEncoder, ops: &[Op], pipes: &TonePipelines, stats: &wgpu::Texture) { + for op in ops { + match op { + Op::Draw { pipe, group, offset, targets, viewport } => { + let Some(pipeline) = pipes.pipelines.get(pipe) else { continue }; + // Only Whites and Blacks' rows draw into part of a target, which keeps the rest. + let load = if viewport.is_some() { wgpu::LoadOp::Load } else { wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT) }; + let attachments: Vec> = targets + .iter() + .map(|view| { + Some(wgpu::RenderPassColorAttachment { + view, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { load, store: wgpu::StoreOp::Store }, + }) + }) + .collect(); + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some(pipe.entry()), + color_attachments: &attachments, + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + pass.set_pipeline(pipeline); + pass.set_bind_group(0, group, &[*offset]); + if let Some([x, y, w, h]) = *viewport { + pass.set_viewport(x, y, w, h, 0.0, 1.0); + pass.set_scissor_rect(x as u32, y as u32, w as u32, h as u32); + } + pass.draw(0..3, 0..1); + } + Op::Result { state, slot } => encoder.copy_texture_to_texture( + wgpu::TexelCopyTextureInfo { texture: state, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, + wgpu::TexelCopyTextureInfo { texture: stats, mip_level: 0, origin: wgpu::Origin3d { x: *slot, y: 0, z: 0 }, aspect: wgpu::TextureAspect::All }, + wgpu::Extent3d { width: 1, height: 2, depth_or_array_layers: 1 }, + ), + } + } +} diff --git a/crates/gpu/src/camera_raw_tone.wgsl b/crates/gpu/src/camera_raw_tone.wgsl new file mode 100644 index 00000000000..5c86d5ea896 --- /dev/null +++ b/crates/gpu/src/camera_raw_tone.wgsl @@ -0,0 +1,585 @@ +// Shadows and Highlights for Camera Raw's GPU preview: `photocraft_algo::camera_raw::local_tone` +// (the fast local Laplacian filter of Paris, Hasinoff and Kautz, SIGGRAPH 2011, in Aubry et al.'s +// form, ACM TOG 2014) as fragment passes, and the order statistics it and Whites and Blacks read. +// `camera_raw_tone.rs` holds the bindings and the order of the passes. +// +// - Pyramid levels are textures. The remapped pyramids of all references sit in one atlas per +// level: reference k is channel k % 4 of tile k / 4. +// - A quantile is found by splitting an interval of the values' order-preserving u32 keys: each +// round counts the values at or below each of `splits()` thresholds across the interval (per +// tile, then summed) and keeps the part that holds the rank, until one key is left: the exact +// order statistic. Two banks of four channels select eight at once. The results are texels of +// `stats`: column = slot, row = bank. + +struct Step { + // The output's size (or tile size, in an atlas), then the source's (or tile size). + sizes: vec4, + // A second source's size, the atlas's columns, a tile or cell edge. + sizes2: vec4, + // The tone pass (0 or 1), the statistics slot it reads (or selects into), a mode, a second slot. + misc: vec4, + // A selection's ranks per bank. + ranks: array, 2>, +} + +struct Tone { + // Per pass: kind (0 Highlights, 1 Shadows), amount, sigma, unused. + passes: array, 2>, + // Per pass, two rows of five knots: pass p, row r, knot i at p * 10 + r * 5 + i. + knots: array, 5>, + // REF_STEP, MAX_REFS. + refs: vec4, + // The pyramid's five taps. + taps: vec4, + taps2: vec4, + // Whites, Blacks (sliders), the model's row step and least Blacks adaptation on photographs. + wb: vec4, + // The internal amount of the first Whites row and of the first Blacks row. + wb2: vec4, + // The internal amounts Whites and Blacks reach: [lo, hi] each. + wb3: vec4, + // Model rows: Whites curves, Blacks curves, Whites adaptation, Blacks adaptation. + model: vec4, + // Model rows: black points, white points; their counts. + model2: vec4, + // Counts of the Whites and Blacks curves. + model3: vec4, +} + +@group(0) @binding(0) var S: Step; +@group(0) @binding(1) var T: Tone; +@group(0) @binding(2) var plane_a: texture_2d; +@group(0) @binding(3) var plane_b: texture_2d; +@group(0) @binding(4) var atlas_fine: texture_2d; +@group(0) @binding(5) var atlas_coarse: texture_2d; +@group(0) @binding(6) var stats: texture_2d; +@group(0) @binding(7) var uint_a: texture_2d; +@group(0) @binding(8) var uint_b: texture_2d; +@group(0) @binding(9) var uint_c: texture_2d; +@group(0) @binding(10) var model: texture_2d; + +struct VOut { + @builtin(position) pos: vec4, +} + +@vertex +fn vs(@builtin(vertex_index) vi: u32) -> VOut { + let uv = vec2(f32((vi << 1u) & 2u), f32(vi & 2u)); + return VOut(vec4(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, 0.0, 1.0)); +} + +fn pixel(pos: vec4) -> vec2 { + return vec2(floor(pos.xy)); +} + +fn dst_size() -> vec2 { + return vec2(S.sizes.xy); +} + +fn src_size() -> vec2 { + return vec2(S.sizes.zw); +} + +fn tap(k: i32) -> f32 { + if k < 4 { + return T.taps[k]; + } + return T.taps2.x; +} + +// `local_tone::mirror`: `i` mirrored into 0..n, the edge sample not repeated. +fn mirror(i: i32, n: i32) -> i32 { + if n == 1 { + return 0; + } + let p = 2 * (n - 1); + var m = i % p; + if m < 0 { + m += p; + } + return select(m, p - m, m >= n); +} + +// Order-preserving keys of f32 values (negative values below positive ones, -0 below +0). +fn key(v: f32) -> u32 { + let b = bitcast(v); + return select(b ^ 0x80000000u, ~b, (b & 0x80000000u) != 0u); +} + +fn key4(v: vec4) -> vec4 { + return vec4(key(v.x), key(v.y), key(v.z), key(v.w)); +} + +fn unkey(k: u32) -> f32 { + return bitcast(select(~k, k ^ 0x80000000u, (k & 0x80000000u) != 0u)); +} + +fn stat(slot: u32, bank: i32) -> vec4 { + return textureLoad(stats, vec2(i32(slot), bank), 0); +} + +// ---- The filter's parameters (`local_tone::llf` and `TonePass::run`) ---- + +struct Llf { + lo: f32, + hi: f32, + step: f32, + refs: i32, + // `hi - lo` is at most 1e-6 (or NaN): the filter leaves its input as it is. + flat: bool, + // The image range the strengths are placed in. + range_lo: f32, + span: f32, +} + +// From a pass's input selection: bank 0 holds the REF_LOW_QUANTILE quantile, the kept one and the +// maximum; bank 1 the RANGE_QUANTILES of the cells. +fn llf(slot: u32) -> Llf { + let a = stat(slot, 0); + let b = stat(slot, 1); + var l: Llf; + l.hi = unkey(a.z); + l.lo = min(unkey(a.x), l.hi); + let d = l.hi - l.lo; + l.flat = !(d > 1e-6); + l.refs = i32(clamp(ceil(d / T.refs.x) + 1.0, 2.0, T.refs.y)); + l.step = d / f32(l.refs - 1); + l.range_lo = unkey(b.x); + l.span = max(unkey(b.y) - l.range_lo, 1.0); + return l; +} + +fn knot_at(p: u32, row: u32, i: u32) -> f32 { + let k = p * 10u + row * 5u + i; + return T.knots[k / 4u][k % 4u]; +} + +// `local_tone::knot`. +fn knot(t: f32, p: u32, row: u32) -> f32 { + let x = clamp(t, 0.0, 1.0) * 4.0; + let i = min(u32(x), 3u); + let a = knot_at(p, row, i); + return a + (knot_at(p, row, i + 1u) - a) * (x - f32(i)); +} + +// tanh that stays finite for large arguments (excess() reaches |x| of several hundred). +fn tanh_(x: f32) -> f32 { + let e = exp(-2.0 * abs(x)); + return sign(x) * (1.0 - e) / (1.0 + e); +} + +fn excess(d: f32, sigma: f32) -> f32 { + return d - sigma * tanh_(d / sigma); +} + +// `TonePass::remap` of pass `p`. +fn remap(x: f32, g: f32, p: u32, l: Llf) -> f32 { + let pp = T.passes[p]; + if pp.x == 0.0 { + return x + knot((g - l.range_lo) / l.span, p, 0u) * pp.y * excess(max(x - g, 0.0), pp.z); + } + let below = clamp((g - x) / pp.z, 0.0, 1.0); + if below == 0.0 { + return x; + } + let w = below * below * (3.0 - 2.0 * below); + return x + pp.y * knot((x - l.range_lo) / l.span, p, 0u) * knot((g - l.range_lo) / l.span, p, 1u) * w; +} + +fn remap4(x: f32, r: vec4, p: u32, l: Llf) -> vec4 { + return vec4(remap(x, r.x, p, l), remap(x, r.y, p, l), remap(x, r.z, p, l), remap(x, r.w, p, l)); +} + +// ---- The pyramids (`local_tone::down`, `up`) ---- + +// The input's Gaussian pyramid: the next coarser level of `plane_a`. +@fragment +fn fs_down(@builtin(position) pos: vec4) -> @location(0) vec4 { + let p = pixel(pos); + let n = src_size(); + var acc = 0.0; + for (var kx = 0; kx < 5; kx++) { + let x = mirror(2 * p.x + kx - 2, n.x); + var col = 0.0; + for (var ky = 0; ky < 5; ky++) { + col += tap(ky) * textureLoad(plane_a, vec2(x, mirror(2 * p.y + ky - 2, n.y)), 0).r; + } + acc += tap(kx) * col; + } + return vec4(acc, 0.0, 0.0, 1.0); +} + +// The tile and its references of an atlas pixel: (group, local x, local y). +fn atlas_cell(p: vec2, tile: vec2) -> vec3 { + let t = p / tile; + return vec3(t.y * i32(S.sizes2.z) + t.x, p - t * tile); +} + +fn tile_origin(group: i32, tile: vec2) -> vec2 { + let cols = i32(S.sizes2.z); + return vec2(group % cols, group / cols) * tile; +} + +// Level 1 of the remapped pyramids: `plane_a` (the input) remapped at the tile's four +// references, then blurred and subsampled. +@fragment +fn fs_down_remap(@builtin(position) pos: vec4) -> @location(0) vec4 { + let tile = dst_size(); + let c = atlas_cell(pixel(pos), tile); + let l = llf(S.misc.y); + if l.flat || 4 * c.x >= l.refs { + return vec4(0.0); + } + let k = f32(4 * c.x); + let r = vec4(l.lo + l.step * k, l.lo + l.step * (k + 1.0), l.lo + l.step * (k + 2.0), l.lo + l.step * (k + 3.0)); + let n = src_size(); + var acc = vec4(0.0); + for (var kx = 0; kx < 5; kx++) { + let x = mirror(2 * c.y + kx - 2, n.x); + var col = vec4(0.0); + for (var ky = 0; ky < 5; ky++) { + let v = textureLoad(plane_a, vec2(x, mirror(2 * c.z + ky - 2, n.y)), 0).r; + col += tap(ky) * remap4(v, r, S.misc.x, l); + } + acc += tap(kx) * col; + } + return acc; +} + +// The next level of the remapped pyramids, tile by tile. +@fragment +fn fs_down_atlas(@builtin(position) pos: vec4) -> @location(0) vec4 { + let tile = dst_size(); + let c = atlas_cell(pixel(pos), tile); + let l = llf(S.misc.y); + if l.flat || 4 * c.x >= l.refs { + return vec4(0.0); + } + let n = src_size(); + let o = tile_origin(c.x, n); + var acc = vec4(0.0); + for (var kx = 0; kx < 5; kx++) { + let x = mirror(2 * c.y + kx - 2, n.x); + var col = vec4(0.0); + for (var ky = 0; ky < 5; ky++) { + col += tap(ky) * textureLoad(atlas_fine, o + vec2(x, mirror(2 * c.z + ky - 2, n.y)), 0); + } + acc += tap(kx) * col; + } + return acc; +} + +// `local_tone::up`'s source sample for index `i` of a zero-stuffed axis of length `n` holding +// `lim` samples, or -1 where the stuffed sample is zero. +fn up_src(i: i32, n: i32, lim: i32) -> i32 { + let m = mirror(i, n); + if m % 2 == 0 && m / 2 < lim { + return m / 2; + } + return -1; +} + +// `plane_b` (`coarse` texels) brought up to the output level, at `p`. +fn up_plane(p: vec2, fine: vec2, coarse: vec2) -> f32 { + let lim = min(coarse, (fine + vec2(1)) / 2); + var acc = 0.0; + for (var kx = 0; kx < 5; kx++) { + let jx = up_src(p.x + kx - 2, fine.x, lim.x); + if jx < 0 { + continue; + } + var col = 0.0; + for (var ky = 0; ky < 5; ky++) { + let jy = up_src(p.y + ky - 2, fine.y, lim.y); + if jy >= 0 { + col += tap(ky) * (textureLoad(plane_b, vec2(jx, jy), 0).r * 4.0); + } + } + acc += tap(kx) * col; + } + return acc; +} + +// Reference `k`'s coarse level (`atlas_coarse`, `coarse` per tile) brought up, at `p`. +fn up_ref(p: vec2, fine: vec2, coarse: vec2, k: i32) -> f32 { + let lim = min(coarse, (fine + vec2(1)) / 2); + let o = tile_origin(k / 4, coarse); + let c = k % 4; + var acc = 0.0; + for (var kx = 0; kx < 5; kx++) { + let jx = up_src(p.x + kx - 2, fine.x, lim.x); + if jx < 0 { + continue; + } + var col = 0.0; + for (var ky = 0; ky < 5; ky++) { + let jy = up_src(p.y + ky - 2, fine.y, lim.y); + if jy >= 0 { + col += tap(ky) * (textureLoad(atlas_coarse, o + vec2(jx, jy), 0)[c] * 4.0); + } + } + acc += tap(kx) * col; + } + return acc; +} + +// One level of the output, coarse to fine: the coarser output (`plane_b`) brought up plus this +// level's Laplacian coefficients, each interpolated between the two references around the +// input's level (`plane_a`) there. Mode 1 is level 0, whose remapped levels are the remapping +// itself; above it they are tiles of `atlas_fine`. +@fragment +fn fs_lap(@builtin(position) pos: vec4) -> @location(0) vec4 { + let p = pixel(pos); + let l = llf(S.misc.y); + let gl = textureLoad(plane_a, p, 0).r; + if l.flat { + return vec4(gl, 0.0, 0.0, 1.0); + } + let fine = dst_size(); + let coarse = src_size(); + let gc = clamp(gl, l.lo, l.hi); + let k0 = i32(floor((gc - l.lo) / l.step)); + var lap = 0.0; + for (var k = max(k0 - 1, 0); k <= min(k0 + 2, l.refs - 1); k++) { + let r = l.lo + l.step * f32(k); + let wgt = max(1.0 - abs(gc - r) / l.step, 0.0); + if wgt > 0.0 { + var f: f32; + if S.misc.z == 1u { + f = remap(gl, r, S.misc.x, l); + } else { + f = textureLoad(atlas_fine, tile_origin(k / 4, fine) + p, 0)[k % 4]; + } + lap += wgt * (f - up_ref(p, fine, coarse, k)); + } + } + return vec4(up_plane(p, fine, coarse) + lap, 0.0, 0.0, 1.0); +} + +// The second pass's input: the first one's output with its kept quantile put back. +@fragment +fn fs_shift(@builtin(position) pos: vec4) -> @location(0) vec4 { + let shift = unkey(stat(S.misc.y, 0).y) - unkey(stat(S.misc.w, 0).x); + return vec4(textureLoad(plane_a, pixel(pos), 0).r + shift, 0.0, 0.0, 1.0); +} + +// `local_tone::range`'s cells: `plane_a` averaged over `edge × edge` blocks. +@fragment +fn fs_cells(@builtin(position) pos: vec4) -> @location(0) vec4 { + let p = pixel(pos); + let f = i32(S.sizes2.w); + let n = src_size(); + let end = min((p + vec2(1)) * f, n); + var sum = 0.0; + for (var y = p.y * f; y < end.y; y++) { + for (var x = p.x * f; x < end.x; x++) { + sum += textureLoad(plane_a, vec2(x, y), 0).r; + } + } + let count = (end.x - p.x * f) * (end.y - p.y * f); + return vec4(sum / f32(count), 0.0, 0.0, 1.0); +} + +// ---- Order statistics ---- + +struct Banks { + @location(0) a: vec4, + @location(1) b: vec4, +} + +// Every key: the selection's starting interval. +@fragment +fn fs_init(@builtin(position) pos: vec4) -> @location(0) vec4 { + return select(vec4(0xffffffffu), vec4(0u), pixel(pos).x == 0); +} + +fn splits() -> u32 { + return S.misc.w; +} + +// Threshold `t` (0 … splits − 1) of the interval [lo, hi]: the last key of its part `t`, the parts +// as even as integers allow (later thresholds clamp to `hi` on a narrow interval). +fn threshold(lo: vec4, hi: vec4, t: u32) -> vec4 { + let d = hi - lo; + let q = d / (splits() + 1u) + vec4(1u); + return lo + min(q * (t + 1u) - vec4(1u), d); +} + +fn interval(bank: i32) -> array, 2> { + return array(textureLoad(uint_a, vec2(0, bank), 0), textureLoad(uint_a, vec2(1, bank), 0)); +} + +// Per `edge × edge` tile and threshold (a column per threshold): how many keys are at or below +// it. Bank 0 counts `plane_a` (its red channel in all four, or mode 1 its four channels), bank 1 +// `plane_b`'s red channel (`sizes2.xy` texels; none when 0). +@fragment +fn fs_count(@builtin(position) pos: vec4) -> Banks { + let g = pixel(pos); + let t = vec2(g.x / i32(splits()), g.y); + let split = u32(g.x) % splits(); + let f = i32(S.sizes2.w); + var out: Banks; + out.a = vec4(0u); + out.b = vec4(0u); + let i0 = interval(0); + let m0 = threshold(i0[0], i0[1], split); + let end = min((t + vec2(1)) * f, src_size()); + for (var y = t.y * f; y < end.y; y++) { + for (var x = t.x * f; x < end.x; x++) { + var v = textureLoad(plane_a, vec2(x, y), 0); + if S.misc.z == 0u { + v = vec4(v.r); + } + out.a += select(vec4(0u), vec4(1u), key4(v) <= m0); + } + } + let end2 = min((t + vec2(1)) * f, vec2(S.sizes2.xy)); + if end2.x > t.x * f && end2.y > t.y * f { + let i1 = interval(1); + let m1 = threshold(i1[0], i1[1], split); + for (var y = t.y * f; y < end2.y; y++) { + for (var x = t.x * f; x < end2.x; x++) { + out.b += select(vec4(0u), vec4(1u), vec4(key(textureLoad(plane_b, vec2(x, y), 0).r)) <= m1); + } + } + } + return out; +} + +// Counts of both banks (`uint_a`, `uint_b`) summed over `edge × edge` tiles, per threshold. +// Sizes are in tiles. +@fragment +fn fs_reduce(@builtin(position) pos: vec4) -> Banks { + let g = pixel(pos); + let n = i32(splits()); + let t = vec2(g.x / n, g.y); + let split = g.x % n; + let f = i32(S.sizes2.w); + let end = min((t + vec2(1)) * f, src_size()); + var out: Banks; + out.a = vec4(0u); + out.b = vec4(0u); + for (var y = t.y * f; y < end.y; y++) { + for (var x = t.x * f; x < end.x; x++) { + out.a += textureLoad(uint_a, vec2(x * n + split, y), 0); + out.b += textureLoad(uint_b, vec2(x * n + split, y), 0); + } + } + return out; +} + +// One round: texel (0, bank) is the interval's low end, (1, bank) its high end. `uint_a` is the +// interval, `uint_b` and `uint_c` the two banks' counts (all their tiles summed here). The new +// interval is the part ending at the first threshold with more than `rank` keys at or below it. +@fragment +fn fs_update(@builtin(position) pos: vec4) -> @location(0) vec4 { + let p = pixel(pos); + let n = src_size(); + let i = interval(p.y); + let rank = S.ranks[p.y]; + var lo = i[0]; + var hi = i[1]; + var found = vec4(false); + var prev = i[0]; + for (var s = 0u; s < splits(); s++) { + var count = vec4(0u); + for (var y = 0; y < n.y; y++) { + for (var x = 0; x < n.x; x++) { + let at = vec2(x * i32(splits()) + i32(s), y); + if p.y == 0 { + count += textureLoad(uint_b, at, 0); + } else { + count += textureLoad(uint_c, at, 0); + } + } + } + let thr = threshold(i[0], i[1], s); + let take = !found & (count > rank); + hi = select(hi, thr, take); + if s > 0u { + lo = select(lo, prev + vec4(1u), take); + } + found = found | take; + prev = thr; + } + // Past the last threshold (below `hi`, or it would have been taken). + lo = select(prev + vec4(1u), lo, found); + return select(hi, lo, p.x == 0); +} + +// ---- Whites and Blacks after Shadows and Highlights (`whites_blacks::amounts`, `row_at`) ---- + +fn linear_to_srgb(v: f32) -> f32 { + if v <= 0.0031308 { + return v * 12.92; + } + return 1.055 * pow(v, 1.0 / 2.4) - 0.055; +} + +fn model_at(x: i32, row: u32) -> f32 { + return textureLoad(model, vec2(x, i32(row)), 0).r; +} + +// `whites_blacks::adapt`'s index into a grid of `n` points on model row `row`: (index, fraction). +fn grid_index(row: u32, n: i32, v: f32) -> vec2 { + let w = clamp(v, model_at(0, row), model_at(n - 1, row)); + var i = n - 2; + for (var k = 0; k < n - 1; k++) { + if w <= model_at(k + 1, row) { + i = k; + break; + } + } + let g = model_at(i, row); + return vec2(f32(i), (w - g) / (model_at(i + 1, row) - g)); +} + +// `whites_blacks::adapt` of the table starting at model row `table`. +fn adapt(table: u32, bp: f32, wp: f32) -> f32 { + let bi = grid_index(T.model2.x, i32(T.model2.z), bp); + let wi = grid_index(T.model2.y, i32(T.model2.w), wp); + let i = u32(bi.x); + let j = i32(wi.x); + let t = wi.y; + let r0 = model_at(j, table + i) * (1.0 - t) + model_at(j + 1, table + i) * t; + let r1 = model_at(j, table + i + 1u) * (1.0 - t) + model_at(j + 1, table + i + 1u) * t; + return r0 * (1.0 - bi.y) + r1 * bi.y; +} + +// Rows 5 (Whites) and 6 (Blacks) of `camera_raw.wgsl`'s tables, at the internal amounts for the +// image's points (slot `misc.y`: the black point's luminance, the white point's channel, linear). +@fragment +fn fs_wb_rows(@builtin(position) pos: vec4) -> @location(0) vec4 { + let p = pixel(pos); + let pts = stat(S.misc.y, 0); + let bp = linear_to_srgb(unkey(pts.x)); + let wp = linear_to_srgb(unkey(pts.y)); + let whites = p.y == i32(S.misc.z); + var x: f32; + var table: u32; + var rows: u32; + var row0: f32; + if whites { + x = T.wb.x; + if x > 0.0 { + x = x * adapt(T.model.z, bp, wp); + } + x = clamp(x, T.wb3.x, T.wb3.y); + table = T.model.x; + rows = T.model3.x; + row0 = T.wb2.x; + } else { + x = T.wb.y; + if x < 0.0 { + x = x * max(adapt(T.model.w, bp, wp), T.wb.w); + } + x = clamp(x, T.wb3.z, T.wb3.w); + table = T.model.y; + rows = T.model3.y; + row0 = T.wb2.y; + } + let r = clamp((x - row0) / T.wb.z, 0.0, f32(rows - 1u)); + let i = min(u32(r), rows - 2u); + let s = r - f32(i); + return vec4(model_at(p.x, table + i) * (1.0 - s) + model_at(p.x, table + i + 1u) * s, 0.0, 0.0, 1.0); +} diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index e4f08908840..0aa423bf79d 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -35,13 +35,15 @@ //! coincident colour or opacity stops) returns [`Unsupported`]; //! callers fall back to the CPU compositor. //! -//! [`CameraRawDevelop`] (`camera_raw.rs`) is a separate pass, not part of the compositor: Camera -//! Raw's per-pixel develop stages for the dialog's preview, built the first time the dialog opens. +//! [`CameraRawDevelop`] (`camera_raw.rs`, `camera_raw_tone.rs`) is separate from the compositor: +//! Camera Raw's per-pixel develop stages and Shadows and Highlights for the dialog's preview, +//! built the first time the dialog opens. #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] pub mod bounds; mod camera_raw; +mod camera_raw_tone; mod fx; pub mod health; pub mod plan; @@ -59,6 +61,7 @@ use photocraft_geom::{Rect, TILE_SIZE, TileCoord}; use photocraft_raster::{Surface, Tile}; pub use camera_raw::{CAMERA_RAW_SHADER, CameraRawDevelop}; +pub use camera_raw_tone::CAMERA_RAW_TONE_SHADER; pub use health::{DeviceHealth, Fault}; pub use plan::{Kernel, Plan, Role, Unsupported, plan}; pub use timing::{GpuTimer, GpuTiming}; diff --git a/crates/gpu/tests/it/camera_raw.rs b/crates/gpu/tests/it/camera_raw.rs index ff841c825a9..ac19c0a01b5 100644 --- a/crates/gpu/tests/it/camera_raw.rs +++ b/crates/gpu/tests/it/camera_raw.rs @@ -113,9 +113,16 @@ fn image(w: usize, h: usize, depth: Depth) -> Vec<[f32; 4]> { /// Develops `p` both ways and returns the largest channel difference. fn compare(g: &mut Gpu, p: &CameraRaw, depth: Depth) -> f32 { - let (w, h) = (171, 113); + compare_at(g, p, depth, (171, 113)) +} + +fn compare_at(g: &mut Gpu, p: &CameraRaw, depth: Depth, (w, h): (usize, usize)) -> f32 { + compare_image(g, p, depth, &image(w, h, depth), (w, h)) +} + +fn compare_image(g: &mut Gpu, p: &CameraRaw, depth: Depth, src: &[[f32; 4]], (w, h): (usize, usize)) -> f32 { let float = matches!(depth, Depth::Float); - let src = image(w, h, depth); + let src = src.to_vec(); let mut cpu = src.clone(); develop(&mut cpu, w, h, p, float); let points = white_black_points(&src, w, h, p); @@ -324,8 +331,7 @@ fn identity_leaves_pixels_alone_and_spatial_settings_have_no_pass() { assert_eq!(out, src, "the CPU develop returns early, unclipped"); for spatial in [ CameraRaw { dehaze: 10.0, ..Default::default() }, - CameraRaw { shadows: 10.0, ..Default::default() }, - CameraRaw { highlights: -10.0, ..Default::default() }, + CameraRaw { shadows: 10.0, clarity: 5.0, ..Default::default() }, CameraRaw { texture: 10.0, ..Default::default() }, CameraRaw { clarity: 10.0, ..Default::default() }, CameraRaw { sharpen_amount: 10.0, ..Default::default() }, @@ -334,8 +340,12 @@ fn identity_leaves_pixels_alone_and_spatial_settings_have_no_pass() { ] { assert!(spatial.spatial() && per_pixel(&spatial, 64, 32, false, Some((0.0, 1.0))).is_none(), "{spatial:?}"); } - // Whites and Blacks need the image's points. + // Whites and Blacks need the image's points, unless Shadows and Highlights measure them. assert!(per_pixel(&CameraRaw { whites: 10.0, ..Default::default() }, 64, 32, false, None).is_none()); + let toned = per_pixel(&CameraRaw { whites: 10.0, shadows: 20.0, ..Default::default() }, 64, 32, false, None).unwrap(); + assert!(toned.local_tone.is_some() && toned.whites_blacks.is_none() && toned.measure_whites_blacks == Some([10.0, 0.0])); + // Wider than the filter's working copy, the develop filters a reduced copy: the CPU's. + assert!(per_pixel(&CameraRaw { shadows: 20.0, ..Default::default() }, 1601, 32, false, None).is_none()); } #[test] @@ -368,3 +378,91 @@ fn bad_sizes_and_faulted_devices_are_errors() { // And the pass still works afterwards. assert!(g.dev.develop(&g.device, &g.queue, Some(&DeviceHealth::new()), &px, None, [4, 4], &stages).is_ok()); } + +#[test] +fn shadows_and_highlights() { + let sets = [ + CameraRaw { shadows: 50.0, ..Default::default() }, + CameraRaw { shadows: -70.0, ..Default::default() }, + CameraRaw { highlights: -50.0, ..Default::default() }, + CameraRaw { highlights: 60.0, ..Default::default() }, + CameraRaw { shadows: 100.0, highlights: -100.0, ..Default::default() }, + CameraRaw { shadows: 35.0, highlights: -45.0, encoding_gamma: 1.8, ..Default::default() }, + ]; + // The test image gives the filter work: each setting moves some pixel by over 2 %. + for p in &sets { + let src = image(171, 113, Depth::Sixteen); + let mut out = src.clone(); + develop(&mut out, 171, 113, p, false); + let moved = out.iter().zip(&src).flat_map(|(a, b)| (0..3).map(move |c| (a[c] - b[c]).abs())).fold(0.0f32, f32::max); + assert!(moved > 0.02, "{p:?} moves pixels by at most {moved}"); + } + check("shadows/highlights", &sets); +} + +#[test] +fn shadows_and_highlights_on_tiny_odd_and_flat_frames() { + let Some(mut g) = gpu() else { return }; + let p = CameraRaw { shadows: 60.0, highlights: -40.0, whites: 20.0, ..Default::default() }; + // A frame 2 pixels on a side has a one-level pyramid: the passes refuse it (the CPU develops it). + for (w, h) in [(2, 2), (40, 2)] { + let stages = per_pixel(&p, w, h, false, None).unwrap(); + assert!(g.dev.develop(&g.device, &g.queue, None, &image(w, h, Depth::Eight), None, [w as u32, h as u32], &stages).is_err()); + } + for size in [(3, 3), (5, 3), (37, 23), (300, 7)] { + for depth in DEPTHS { + let d = compare_at(&mut g, &p, depth, size); + eprintln!("shadows/highlights {size:?} {depth:?}: max |GPU - CPU| = {d:.2e}"); + } + } + // A flat frame has no range to filter. + let flat = vec![[0.4, 0.35, 0.3, 1.0]; 64 * 48]; + for depth in DEPTHS { + compare_image(&mut g, &p, depth, &flat, (64, 48)); + } +} + +#[test] +fn shadows_and_highlights_with_per_pixel_stages() { + let mut hsl = [0.0; 8]; + hsl[1] = 35.0; + hsl[5] = -50.0; + let all = CameraRaw { + temperature: 25.0, + tint: 10.0, + exposure: 0.3, + contrast: 25.0, + shadows: 45.0, + highlights: -55.0, + whites: 20.0, + blacks: -15.0, + vibrance: 30.0, + saturation: 10.0, + curve_darks: 20.0, + point_curve: vec![[0.0, 8.0], [255.0, 250.0]], + hsl_hue: hsl, + hsl_sat: hsl, + hsl_lum: hsl, + grade_shadows: Wheel { hue: 210.0, sat: 25.0, lum: 0.0 }, + vignette_amount: -30.0, + grain_amount: 20.0, + pixel_scale: 0.2, + ..Default::default() + }; + check( + "shadows/highlights + per pixel", + &[ + all.clone(), + // Whites and Blacks measured after the filter, both directions. + CameraRaw { shadows: 60.0, whites: 70.0, blacks: -45.0, ..Default::default() }, + CameraRaw { highlights: -60.0, whites: -60.0, blacks: 50.0, exposure: -0.4, ..Default::default() }, + CameraRaw { shadows: 30.0, highlights: -30.0, whites: 40.0, blacks: -30.0, encoding_gamma: 1.8, ..Default::default() }, + ], + ); + // At the dialog's proxy size. + let Some(mut g) = gpu() else { return }; + for depth in DEPTHS { + let d = compare_at(&mut g, &all, depth, (858, 572)); + eprintln!("shadows/highlights + per pixel 858x572 {depth:?}: max |GPU - CPU| = {d:.2e}"); + } +} diff --git a/crates/ui-egui/src/dialogs/camera_raw_gpu.rs b/crates/ui-egui/src/dialogs/camera_raw_gpu.rs index f4545a5bb15..41cd176137d 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_gpu.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_gpu.rs @@ -1,8 +1,9 @@ -//! Camera Raw's preview develop on the GPU (#6916). When every stage the settings use reads -//! only its own pixel, the proxy develops in one wgpu pass (`photocraft_gpu::CameraRawDevelop`) -//! on the canvas's device and is read back for the histogram, scopes and display conversion. -//! Spatial stages, Rendering Mode CPU, `PHOTOCRAFT_CPU_CAMERA_RAW`, no GPU canvas, a software -//! adapter, a device fault or a failed develop all keep the CPU develop on the worker. +//! Camera Raw's preview develop on the GPU (#6916). When the settings use only stages that read +//! their own pixel, plus Shadows and Highlights, the proxy develops in wgpu passes +//! (`photocraft_gpu::CameraRawDevelop`) on the canvas's device and is read back once for the +//! histogram, scopes and display conversion. Other spatial stages (Dehaze, Texture, Clarity, +//! Detail), Rendering Mode CPU, `PHOTOCRAFT_CPU_CAMERA_RAW`, no GPU canvas, a software adapter, a +//! device fault or a failed develop all keep the CPU develop on the worker. //! //! The pipeline builds on a thread the first time a dialog opens (DX12's shader compiler takes //! about 0.35 s, #6419); frames develop on the CPU until it is ready. @@ -117,17 +118,18 @@ impl CameraRawGpu { CameraRawGpu { device, queue, health, pass, failed: Arc::default(), points: Arc::default() } } - /// Develops `px` (`w × h`) with `p`, or `None` when the CPU must: a spatial stage, the pass - /// still building, a fault, or a GPU error (logged; the dialog then stays on the CPU). `key` names the pixels when they - /// are the dialog's unchanged proxy ([`source_key`]), so they upload once. Neutral settings - /// are `None` too: the CPU develop returns them at once, a GPU round trip would only cost. + /// Develops `px` (`w × h`) with `p`, or `None` when the CPU must: a spatial stage other than + /// Shadows and Highlights, the pass still building, a fault, or a GPU error (logged; the + /// dialog then stays on the CPU). `key` names the pixels when they are the dialog's unchanged + /// proxy ([`source_key`]), so they upload once. Neutral settings are `None` too: the CPU + /// develop returns them at once, a GPU round trip would only cost. pub(crate) fn develop(&self, px: &[[f32; 4]], key: Option, w: usize, h: usize, p: &CameraRaw, float: bool) -> Option> { - if p.spatial() || p.is_identity() || self.failed.load(Ordering::Relaxed) || !self.health.is_ok() { + if p.is_identity() || self.failed.load(Ordering::Relaxed) || !self.health.is_ok() { return None; } #[cfg(target_arch = "wasm32")] { - let _ = (px, key, w, h, float); + let _ = (px, key, w, h, p, float); None } #[cfg(not(target_arch = "wasm32"))] @@ -148,9 +150,11 @@ impl CameraRawGpu { } } + /// The image's black and white points for Whites and Blacks, measured on the CPU. With + /// Shadows and Highlights the GPU measures them after the filter instead. #[cfg(not(target_arch = "wasm32"))] fn points(&self, px: &[[f32; 4]], key: Option, w: usize, h: usize, p: &CameraRaw) -> Option<(f32, f32)> { - if p.whites == 0.0 && p.blacks == 0.0 { + if (p.whites == 0.0 && p.blacks == 0.0) || p.spatial() { return None; } let Some(key) = key else { return photocraft_algo::camera_raw::white_black_points(px, w, h, p) }; @@ -255,9 +259,17 @@ mod tests { assert!(worst <= TOL, "{depth}-bit: off by {worst}"); let described = app.camera_raw.as_ref().map(|d| d.describe(&app.ui.camera_raw_scope, &app.ui.camera_raw_preview)).unwrap(); assert_eq!(described["developBackend"], "gpu"); - // A spatial stage develops the whole frame on the CPU. - let (backend, shown, cpu) = developed(&mut app, &ctx, CameraRaw { shadows: 40.0, ..per_pixel.clone() }); - assert_eq!((backend, shown == cpu), ("cpu", true), "{depth}-bit"); + // Shadows and Highlights develop on the GPU too, Whites and Blacks measured after them. + let toned = CameraRaw { shadows: 40.0, highlights: -35.0, ..per_pixel.clone() }; + let (backend, gpu, cpu) = developed(&mut app, &ctx, toned.clone()); + assert_eq!(backend, "gpu", "{depth}-bit, Shadows and Highlights"); + let worst = gpu.iter().zip(&cpu).flat_map(|(a, b)| (0..4).map(move |c| (a[c] - b[c]).abs())).fold(0.0f32, f32::max); + assert!(worst <= TOL, "{depth}-bit, Shadows and Highlights: off by {worst}"); + // Another spatial stage develops the whole frame on the CPU. + for spatial in [CameraRaw { clarity: 30.0, ..toned.clone() }, CameraRaw { dehaze: 20.0, ..per_pixel.clone() }] { + let (backend, shown, cpu) = developed(&mut app, &ctx, spatial); + assert_eq!((backend, shown == cpu), ("cpu", true), "{depth}-bit"); + } // A device fault: the CPU, from the next frame on. app.gpu.as_ref().unwrap().health().mark(photocraft_gpu::Fault::Lost("test".into())); let (backend, shown, cpu) = developed(&mut app, &ctx, per_pixel); diff --git a/crates/ui-egui/src/dialogs/camera_raw_ui.rs b/crates/ui-egui/src/dialogs/camera_raw_ui.rs index 3c2f576671c..5facab73a8b 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_ui.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_ui.rs @@ -5,7 +5,8 @@ //! (≤ 900 px, `pixel_scale` keeps pixel radii true to the full image), recomputed when a //! control changes: on a worker for the dialog's own controls, so a drag never waits for it, and //! on the UI thread for the control channel, so a reply describes its own settings. Settings -//! whose stages are all per pixel develop on the GPU instead where it can (`camera_raw_gpu`). +//! whose stages are per pixel, or Shadows and Highlights, develop on the GPU instead where it can +//! (`camera_raw_gpu`). //! OK runs `filter.cameraRaw` with the non-default settings, so the result is one history step //! (or a smart filter on a smart object) and exactly replayable. //! diff --git a/docs/hardware-parity.md b/docs/hardware-parity.md index 5d28b21dd84..96c26a74cf4 100644 --- a/docs/hardware-parity.md +++ b/docs/hardware-parity.md @@ -1,6 +1,6 @@ # Hardware parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Windows: flipping the pen to its eraser end selects the Eraser with Windows Ink on, #2285, not yet confirmed on a pen with an eraser end; optional WinTab backend on Windows: pressure and the eraser end; tilt on devices with orientation axes; rotation only with a pen and driver that report twist, with Windows Ink off) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Windows: flipping the pen to its eraser end selects the Eraser with Windows Ink on, #2285, not yet confirmed on a pen with an eraser end; optional WinTab backend on Windows: pressure and the eraser end; tilt on devices with orientation axes; rotation only with a pen and driver that report twist, with Windows Ink off; Camera Raw's preview develops Shadows and Highlights on the GPU) · **Target:** Adobe Photoshop 2026 Each hardware feature Photoshop 2026 (27.11.0) uses, per platform, against PhotoCraft. Photoshop side: its bundle (Metal and OpenCL paths, "Precise Color Management for HDR Display" and EDR @@ -22,7 +22,7 @@ HDR display to verify. | GPU canvas, zoom/pan, rotate view | Metal (macOS), DirectX/OpenCL (Windows) | wgpu 30: Metal, Vulkan, DX12, GL; backend selectable | done | | GPU compositing of layers, blend modes, effects | partial (Photoshop composites mostly on CPU) | wgpu compositor, ≤ 1/255 vs CPU oracle; Multichannel and > texture-limit regions fall back to CPU | done (ahead in places) | | GPU compositor startup | available | Pipeline preparation runs in the background on native hardware; the CPU composites until ready. Windows WARP probe: 0.329 ms p95, 6.860 ms maximum device-work stall during two FXC builds; hardware measurements remain pending (#9157, #9364, #6419) | partial | -| GPU filters (Blur Gallery, Liquify, Smart Sharpen, Camera Raw) | yes | CPU (rayon) for filters; GPU for compose and effects. Camera Raw's preview runs its per-pixel stages (white balance to grain) in one wgpu pass, about 2-3 ms vs 11-28 ms on the CPU for the 858×572 proxy, depending on the machine; spatial stages, Calibration and OK still develop on the CPU (#6916) | partial | +| GPU filters (Blur Gallery, Liquify, Smart Sharpen, Camera Raw) | yes | CPU (rayon) for filters; GPU for compose and effects. Camera Raw's preview runs its per-pixel stages (white balance to grain) in one wgpu pass, about 2-3 ms vs 11-28 ms on the CPU for the 858×572 proxy, depending on the machine, and Shadows and Highlights (the local Laplacian filter) as fragment passes in front of it, 8.7-10.6 ms vs 147-300 ms; Dehaze, Texture, Clarity, Detail, Calibration and OK still develop on the CPU (#6916) | partial | | Documents larger than the GPU texture limit | yes (tiled) | CPU fallback; tiling in progress (#49) | partial | | CPU-only fallback when no GPU | yes, reduced | `cpu` canvas preference; fails to start without an adapter on some Linux systems (#2519, #2412) | partial | | Choosing the GPU on a multi-GPU machine | Preferences › Performance › Use Graphics Processor | Linux only: Preferences › Performance › Advanced › GPU adapter and `PHOTOCRAFT_GPU_ADAPTER` (#1885); ignored on Windows and macOS | partial | @@ -76,4 +76,5 @@ rotation; its eraser end comes from the pointer hooks (#2285). | 2026-10-28 | minor | Build GPU compositor pipelines in the background; benchmark baseline pending (#9157) | | 2026-10-10 | major | First version | | 2026-10-17 | minor | GPU filters: Camera Raw's preview, per-pixel stages (#6916 step 1) | +| 2026-10-17 | minor | GPU filters: Camera Raw's preview, Shadows and Highlights (#6916 step 2) | | 2026-10-19 | minor | Graphics Adapter choice on Linux (#1885) |