perf(camera-raw): develop Dehaze, Clarity and Texture on the GPU in the preview (#6916)

Step 3 of #6916. Dehaze, Clarity and Texture run as fragment passes
(box, minimum and guided filters) around step 2's Shadows and
Highlights, so every setting but Detail develops on the GPU with one
readback.

- algo: camera_raw::spatial resolves Dehaze, Clarity and Texture per
  frame; develop builds them the same way (130 output hashes unchanged,
  same speed). PerPixel gains the three stages, per_pixel() refuses only
  Detail, and Whites/Blacks are measured after any spatial stage.
- gpu: camera_raw_filters.wgsl; the tone frame's pyramid is made on
  demand; plans record four segments around the main shader's passes.
  Dehaze's light uses two exact selections (cutoff value, then cutoff
  index among its ties). Its <=768 px copy comes from the CPU
  (Dehaze::cells, develop's own code), cached per source and white
  balance: on WARP the GPU's copy split CPU ties at the cutoff and moved
  the light by 5.7e-3.
- GPU vs CPU at most 7.6e-5 (Vulkan, DX12, WARP), tolerance 1/4096.
  858x572: Dehaze +40 6.0 ms vs 29 ms, Clarity +50 3.5 vs 16 ms,
  Texture +50 3.4 vs 10 ms, everything 19 ms vs 650-690 ms (Vulkan).

Part of #6916.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
fjamespriceandClaude Opus 5.5 committed 2026-11-01 03:38:55 -05:00
1 parent 320ddcffb4
commit 7d1a7d6922
12 files changed
+1284 -319

No files matched your search

+54 -40
View File
@@ -57,12 +57,14 @@ use crate::photo_util::{hash01, linear_to_srgb, par_rows, srgb_to_linear};
pub mod local_tone;
mod per_pixel;
pub mod spatial;
mod whites_blacks;
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,
};
pub use spatial::{Clarity, Dehaze, Texture};
/// 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.
@@ -391,11 +393,13 @@ fn box_mean(v: &[f32], w: usize, h: usize, r: usize) -> Vec<f32> {
/// Approximate Gaussian (three box passes).
fn gauss(v: &[f32], w: usize, h: usize, sigma: f32) -> Vec<f32> {
if sigma < 0.3 {
return v.to_vec();
}
box_means(v, w, h, &spatial::gauss_radii(sigma))
}
/// Box means of radii `radii` in turn.
fn box_means(v: &[f32], w: usize, h: usize, radii: &[usize]) -> Vec<f32> {
let mut out = v.to_vec();
for r in crate::fxutil::gauss_box_radii(sigma) {
for &r in radii {
out = box_mean(&out, w, h, r);
}
out
@@ -405,7 +409,7 @@ fn gauss(v: &[f32], w: usize, h: usize, sigma: f32) -> Vec<f32> {
/// coefficients are computed on a `s×` subsampled copy and upsampled bilinearly, which is
/// visually equivalent for the large radii used by tone controls at a fraction of the cost.
fn guided_fast(i: &[f32], p: &[f32], w: usize, h: usize, r: usize, eps: f32) -> Vec<f32> {
let s = (r / 8).clamp(1, 8);
let (s, rs) = spatial::fast_guided_steps(r);
if s == 1 {
return guided(i, p, w, h, r, eps);
}
@@ -423,7 +427,6 @@ fn guided_fast(i: &[f32], p: &[f32], w: usize, h: usize, r: usize, eps: f32) ->
o.iter().zip(&c).map(|(a, b)| a / b.max(1.0)).collect()
};
let (si, sp) = (down(i), down(p));
let rs = (r / s).max(1);
let mi = box_mean(&si, sw, sh, rs);
let mp = box_mean(&sp, sw, sh, rs);
let ip: Vec<f32> = si.iter().zip(&sp).map(|(a, b)| a * b).collect();
@@ -683,7 +686,6 @@ pub fn develop(px: &mut [[f32; 4]], w: usize, h: usize, p: &CameraRaw, float: bo
return;
}
let ps = p.pixel_scale.clamp(0.01, 1.0);
let long = w.max(h) as f32;
// 1. White balance + exposure in linear light.
if let Some(g) = per_pixel::gains(p) {
par_rows(px, w, 1, |_, row| {
@@ -711,8 +713,8 @@ pub fn develop(px: &mut [[f32; 4]], w: usize, h: usize, p: &CameraRaw, float: bo
});
}
// 2. Dehaze.
if p.dehaze != 0.0 {
dehaze(px, w, h, p.dehaze / 100.0);
if let Some(d) = Dehaze::new(p, w, h) {
dehaze(px, w, h, &d);
}
// 3. Tone. Highlights and Shadows: a local Laplacian filter (see `local_tone`).
if p.highlights != 0.0 || p.shadows != 0.0 {
@@ -721,20 +723,22 @@ pub fn develop(px: &mut [[f32; 4]], w: usize, h: usize, p: &CameraRaw, float: bo
if !p.local_tone_neutral() && [p.contrast, p.texture, p.clarity].iter().any(|v| *v != 0.0) {
let l: Vec<f32> = px.iter().map(|q| luma([q[0], q[1], q[2]]).max(0.0)).collect();
let lc: Vec<f32> = l.iter().map(|v| v.min(1.0)).collect();
let clar = (p.clarity != 0.0).then(|| guided_fast(&lc, &lc, w, h, ((long * 0.02) as usize).max(3), 0.005));
let tex = (p.texture != 0.0).then(|| gauss(&lc, w, h, (long * 0.002).max(1.5 * ps)));
let clarity = Clarity::new(p, w, h);
let texture = Texture::new(p, w, h);
let clar = clarity.as_ref().map(|c| guided_fast(&lc, &lc, w, h, c.radius, spatial::CLARITY_EPS));
let tex = texture.as_ref().map(|t| box_means(&lc, w, h, &t.radii));
let k_con = p.contrast / 100.0 * 0.6;
par_rows(px, w, 1, |y, row| {
for (x, q) in row.iter_mut().enumerate() {
let i = y * w + x;
let l0 = l[i];
let mut lv = lc[i];
if let Some(c) = &clar {
if let (Some(c), Some(k)) = (&clar, &clarity) {
let mw = 1.0 - (2.0 * lv.clamp(0.0, 1.0) - 1.0).powi(2);
lv += p.clarity / 100.0 * 0.8 * (lc[i] - c[i]) * mw;
lv += k.amount * (lc[i] - c[i]) * mw;
}
if let Some(t) = &tex {
lv += p.texture / 100.0 * 0.9 * (lc[i] - t[i]).clamp(-0.1, 0.1);
if let (Some(t), Some(k)) = (&tex, &texture) {
lv += k.amount * (lc[i] - t[i]).clamp(-spatial::TEXTURE_LIMIT, spatial::TEXTURE_LIMIT);
}
*q = tone(*q, l0, lc[i], lv, k_con);
}
@@ -938,25 +942,32 @@ fn value_noise(x: f32, y: f32, seed: u64) -> f32 {
top + (bot - top) * sy
}
fn dehaze(px: &mut [[f32; 4]], w: usize, h: usize, amount: f32) {
// Transmission on a ≤ 768 px proxy, upsampled.
let k = w.max(h).div_ceil(768).max(1);
let (sw, sh) = (w.div_ceil(k), h.div_ceil(k));
let mut small = vec![[0.0f32; 3]; sw * sh];
let mut cnt = vec![0f32; sw * sh];
for y in 0..h {
for x in 0..w {
let i = (y / k) * sw + x / k;
for c in 0..3 {
small[i][c] += px[y * w + x][c].clamp(0.0, 1.0);
/// Dehaze's copy of `px` (`w × h`): each pixel mapped by `map`, clipped to 0 … 1 and averaged over
/// `d.factor × d.factor` blocks, each block summed in raster order.
fn haze_cells(px: &[[f32; 4]], w: usize, h: usize, d: &Dehaze, map: impl Fn([f32; 4]) -> [f32; 4] + Sync) -> Vec<[f32; 3]> {
let (k, [sw, sh]) = (d.factor, d.size);
let bands = crate::photo_util::par_map(sh, |sy| {
let mut small = vec![[0.0f32; 3]; sw];
let mut cnt = vec![0f32; sw];
for y in sy * k..((sy + 1) * k).min(h) {
for x in 0..w {
let q = map(px[y * w + x]);
let i = x / k;
for c in 0..3 {
small[i][c] += q[c].clamp(0.0, 1.0);
}
cnt[i] += 1.0;
}
cnt[i] += 1.0;
}
}
for (s, c) in small.iter_mut().zip(&cnt) {
*s = s.map(|v| v / c.max(1.0));
}
let r = (sw.max(sh) / 60).max(2);
small.iter().zip(&cnt).map(|(s, c)| s.map(|v| v / c.max(1.0))).collect::<Vec<_>>()
});
bands.into_iter().flatten().collect()
}
fn dehaze(px: &mut [[f32; 4]], w: usize, h: usize, d: &Dehaze) {
// Transmission on a ≤ DEHAZE_SIDE px proxy, upsampled.
let (k, [sw, sh], r, amount) = (d.factor, d.size, d.radius, d.amount);
let small = haze_cells(px, w, h, d, |q| q);
// The minimum (or, with `f32::max`, maximum) over each (2r + 1)² window.
let rank_filter = |v: &[f32], start: f32, pick: fn(f32, f32) -> f32| -> Vec<f32> {
let mut a = vec![0.0f32; sw * sh];
@@ -977,33 +988,35 @@ fn dehaze(px: &mut [[f32; 4]], w: usize, h: usize, amount: f32) {
};
let min_filter = |v: &[f32]| rank_filter(v, f32::MAX, f32::min);
let dark = min_filter(&small.iter().map(|c| c[0].min(c[1]).min(c[2])).collect::<Vec<_>>());
// Atmospheric light: mean colour of the brightest 0.1 % of the dark channel.
// Atmospheric light: mean colour of the brightest 0.1 % of the dark channel (ties in the
// order of the cells).
let mut idx: Vec<usize> = (0..sw * sh).collect();
idx.sort_by(|&a, &b| dark[b].total_cmp(&dark[a]));
let top = (sw * sh / 1000).max(1);
let top = d.top;
let mut air = [0.0f32; 3];
for &i in &idx[..top] {
for c in 0..3 {
air[c] += small[i][c] / top as f32;
}
}
let air = air.map(|v| v.max(0.2));
let air = air.map(|v| v.max(spatial::DEHAZE_AIR_FLOOR));
let norm_dark = min_filter(&small.iter().map(|c| (c[0] / air[0]).min(c[1] / air[1]).min(c[2] / air[2])).collect::<Vec<_>>());
// Opened (a maximum filter of the same radius after the minimum): the minimum grows every
// dark object by `r`, so sky beside a dark building took its dark channel, counted as
// haze-free and kept a bright halo (#9273). Opening shrinks dark regions back to their
// outline and is still a lower bound of the dark channel over the window. It raises the dark
// channel on average, so the 0.95 weight is scaled to keep the slider's overall strength.
// channel on average, so the ω weight is scaled to keep the slider's overall strength.
let opened = rank_filter(&norm_dark, f32::MIN, f32::max);
let mean = |v: &[f32]| v.iter().sum::<f32>() / v.len().max(1) as f32;
let weight = 0.95 * mean(&norm_dark) / mean(&opened).max(1e-6);
let weight = spatial::DEHAZE_OMEGA * mean(&norm_dark) / mean(&opened).max(1e-6);
let t_raw: Vec<f32> = opened.iter().map(|d| 1.0 - weight * d).collect();
let guide: Vec<f32> = small.iter().map(|c| luma(*c)).collect();
let t = guided(&guide, &t_raw, sw, sh, r * 2, 1e-3);
let t = guided(&guide, &t_raw, sw, sh, d.guide_radius, spatial::DEHAZE_EPS);
let ks = k as f32;
par_rows(px, w, 1, |y, row| {
for (x, q) in row.iter_mut().enumerate() {
let tv = crate::photo_util::bilinear(&t, sw, sh, 1, 0, (x as f32 + 0.5) / ks - 0.5, (y as f32 + 0.5) / ks - 0.5).clamp(0.1, 1.0);
let tv =
crate::photo_util::bilinear(&t, sw, sh, 1, 0, (x as f32 + 0.5) / ks - 0.5, (y as f32 + 0.5) / ks - 0.5).clamp(spatial::DEHAZE_T_FLOOR, 1.0);
for c in 0..3 {
let i = q[c];
let j = (i - air[c]) / tv + air[c];
@@ -1133,7 +1146,8 @@ mod tests {
[c[0], c[1], c[2], 1.0]
})
.collect();
dehaze(&mut px, w, h, 1.0);
let d = Dehaze::new(&CameraRaw { dehaze: 100.0, ..Default::default() }, w, h).unwrap();
dehaze(&mut px, w, h, &d);
let sky = |xs: std::ops::Range<usize>| {
let v: Vec<f32> =
(150..390).flat_map(|y| xs.clone().map(move |x| (x, y))).map(|(x, y)| luma([px[y * w + x][0], px[y * w + x][1], px[y * w + x][2]])).collect();
+30 -23
View File
@@ -1,9 +1,11 @@
//! Develop's per-pixel stages resolved for one image: every constant and table they use, so
//! Develop's stages resolved for one image: every constant and table the per-pixel ones 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`].
//! The spatial stages other than Detail come as their parameters: Dehaze, Clarity and Texture
//! (see [`spatial`](super::spatial)), Shadows and Highlights as a [`LocalTone`].
use super::local_tone::{LocalTone, WORK_SIDE};
use super::spatial::{Clarity, Dehaze, Texture};
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;
@@ -23,7 +25,7 @@ pub(crate) fn gains(p: &CameraRaw) -> Option<[f32; 3]> {
Some(g.map(|v| v / norm * 2f32.powf(p.exposure)))
}
/// Contrast's strength, when Contrast is set.
/// Contrast's strength, when Contrast is set (with or without Texture and Clarity).
fn contrast(p: &CameraRaw) -> Option<f32> {
(p.contrast != 0.0).then_some(p.contrast / 100.0 * 0.6)
}
@@ -158,16 +160,21 @@ impl Grain {
pub struct PerPixel {
/// 1. White balance and exposure gains in linear light (sRGB-decoded values).
pub gains: Option<[f32; 3]>,
/// 2. Dehaze.
pub dehaze: Option<Dehaze>,
/// 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<LocalTone>,
/// 3. Contrast's strength (Contrast without Texture or Clarity is per pixel).
/// 3. Clarity and Texture on the luminance clipped to 1, before Contrast.
pub clarity: Option<Clarity>,
pub texture: Option<Texture>,
/// 3. Contrast's strength.
pub contrast: Option<f32>,
/// 3b. Whites and Blacks, in the document's encoding.
pub whites_blacks: Option<WhitesBlacks>,
/// 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
/// 3b. Whites and Blacks to measure the image's points for (the sliders, −100 … 100), when a
/// spatial stage is set: the points then depend on its 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.
@@ -201,13 +208,9 @@ impl CameraRaw {
|| 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
/// Whether developing needs Detail: sharpening or noise reduction.
fn detail_on(&self) -> bool {
self.sharpen_amount > 0.0 || self.noise_luminance > 0.0 || self.noise_color > 0.0
}
}
@@ -227,15 +230,14 @@ pub fn white_black_points(px: &[[f32; 4]], w: usize, h: usize, p: &CameraRaw) ->
}))
}
/// 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 only 2
/// pixels on its short side, 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.
/// Develop's stages for settings without Detail or Calibration, on a `w × h` image; `points` are
/// the image's [`white_black_points`]. `None` when `p` needs Detail or Calibration (these stages
/// run neither), Shadows or Highlights on a frame wider than the filter's working copy (the
/// develop then filters a reduced copy) or only 2 pixels on its short side, or Whites or Blacks
/// without a spatial stage 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<PerPixel> {
if p.spatial_beyond_local_tone() || !p.calibration_neutral() {
if p.detail_on() || !p.calibration_neutral() {
return None;
}
// The develop leaves frames under 2 pixels on a side alone.
@@ -244,9 +246,11 @@ pub fn per_pixel(p: &CameraRaw, w: usize, h: usize, float: bool, points: Option<
if local_tone.is_some() && (w.max(h) > WORK_SIDE || w.min(h) <= 2) {
return None;
}
let (dehaze, clarity, texture) = (Dehaze::new(p, w, h), Clarity::new(p, w, h), Texture::new(p, w, h));
let spatial = local_tone.is_some() || dehaze.is_some() || clarity.is_some() || texture.is_some();
let identity = p.is_identity();
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 measure_whites_blacks = (wb_on && spatial).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);
@@ -262,7 +266,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),
dehaze,
local_tone,
clarity,
texture,
contrast: contrast(p),
whites_blacks,
measure_whites_blacks,
+176
View File
@@ -0,0 +1,176 @@
//! Dehaze, Clarity and Texture resolved for one frame: the sizes, radii and constants their
//! filters use, so another implementation of them (the GPU preview,
//! `photocraft_gpu::CameraRawDevelop`) runs the same filters. [`develop`](super::develop) builds
//! its own from the same constructors.
//!
//! - **Dehaze** follows the dark channel prior (K. He, J. Sun, X. Tang, *Single Image Haze Removal
//! Using Dark Channel Prior*, CVPR 2009) on a box-averaged copy at most [`DEHAZE_SIDE`] pixels
//! across, with the transmission refined by a guided filter (K. He, J. Sun, X. Tang, *Guided
//! Image Filtering*, ECCV 2010) and brought back to full size bilinearly.
//! - **Clarity** raises the luminance's difference from a fast guided filter of itself (K. He,
//! J. Sun, *Fast Guided Filter*, arXiv 2015), weighted toward the midtones.
//! - **Texture** raises its difference from a Gaussian blur (three box passes), limited to
//! ±[`TEXTURE_LIMIT`].
use super::CameraRaw;
/// Dehaze measures the haze on a copy at most this many pixels across.
pub const DEHAZE_SIDE: usize = 768;
/// The dark channel's minimum filter has a radius of the copy's long side over this, at least
/// [`DEHAZE_MIN_RADIUS`].
pub const DEHAZE_RADIUS_DIVISOR: usize = 60;
/// See [`DEHAZE_RADIUS_DIVISOR`].
pub const DEHAZE_MIN_RADIUS: usize = 2;
/// The atmospheric light is the mean colour of the brightest 1 / this of the dark channel (at
/// least one cell).
pub const DEHAZE_AIR_FRACTION: usize = 1000;
/// Each channel of the atmospheric light is at least this.
pub const DEHAZE_AIR_FLOOR: f32 = 0.2;
/// The share of the haze the raw transmission removes (the paper's ω).
pub const DEHAZE_OMEGA: f32 = 0.95;
/// The guided filter's regularisation for the transmission.
pub const DEHAZE_EPS: f32 = 1e-3;
/// The transmission is at least this.
pub const DEHAZE_T_FLOOR: f32 = 0.1;
/// Clarity's guided filter regularisation.
pub const CLARITY_EPS: f32 = 0.005;
/// Texture moves the luminance by at most this.
pub const TEXTURE_LIMIT: f32 = 0.1;
/// Dehaze on a `w × h` frame.
#[derive(Clone, Debug, PartialEq)]
pub struct Dehaze {
/// The slider / 100 (−1 … 1).
pub amount: f32,
/// The copy averages `factor × factor` blocks.
pub factor: usize,
/// The copy's size.
pub size: [usize; 2],
/// The minimum filter's radius.
pub radius: usize,
/// The guided filter's radius.
pub guide_radius: usize,
/// How many of the copy's cells the atmospheric light averages.
pub top: usize,
}
impl Dehaze {
/// Dehaze for `p` on a `w × h` frame; `None` when it is off.
pub fn new(p: &CameraRaw, w: usize, h: usize) -> Option<Self> {
if p.dehaze == 0.0 {
return None;
}
let factor = w.max(h).div_ceil(DEHAZE_SIDE).max(1);
let size = [w.div_ceil(factor), h.div_ceil(factor)];
let radius = (size[0].max(size[1]) / DEHAZE_RADIUS_DIVISOR).max(DEHAZE_MIN_RADIUS);
Some(Dehaze { amount: p.dehaze / 100.0, factor, size, radius, guide_radius: radius * 2, top: (size[0] * size[1] / DEHAZE_AIR_FRACTION).max(1) })
}
/// The copy the haze is measured on, for `px` (`w × h`, display-encoded) before white balance
/// and exposure (`gains`, as in [`PerPixel`](super::PerPixel)): `size` cells in rows, each the
/// mean light of its block, clipped to 0 … 1. These are exactly the cells
/// [`develop`](super::develop) uses: the brightest of them set the atmospheric light, and a
/// tie between them decides which, so another implementation that computes stage 1 to a few
/// ulps should start from these. Empty when `px` isn't `w × h`.
pub fn cells(&self, px: &[[f32; 4]], w: usize, h: usize, gains: Option<[f32; 3]>) -> Vec<[f32; 3]> {
if px.len() != w.saturating_mul(h) || w.div_ceil(self.factor) != self.size[0] || h.div_ceil(self.factor) != self.size[1] {
return Vec::new();
}
super::haze_cells(px, w, h, self, |q| gains.map_or(q, |g| super::balance(q, g)))
}
}
/// Clarity on a `w × h` frame.
#[derive(Clone, Debug, PartialEq)]
pub struct Clarity {
/// The strength: the slider / 100 × 0.8.
pub amount: f32,
/// The guided filter's radius at full size.
pub radius: usize,
/// The fast guided filter works on `subsample × subsample` block means…
pub subsample: usize,
/// …with this radius…
pub sub_radius: usize,
/// …at this size.
pub sub_size: [usize; 2],
}
impl Clarity {
/// Clarity for `p` on a `w × h` frame; `None` when it is off.
pub fn new(p: &CameraRaw, w: usize, h: usize) -> Option<Self> {
if p.clarity == 0.0 {
return None;
}
let radius = ((w.max(h) as f32 * 0.02) as usize).max(3);
let (subsample, sub_radius) = fast_guided_steps(radius);
Some(Clarity { amount: p.clarity / 100.0 * 0.8, radius, subsample, sub_radius, sub_size: [w.div_ceil(subsample), h.div_ceil(subsample)] })
}
}
/// The fast guided filter's subsampling and its radius there, for radius `r` at full size. A
/// subsampling of 1 is the plain guided filter at radius `r`.
pub fn fast_guided_steps(r: usize) -> (usize, usize) {
let s = (r / 8).clamp(1, 8);
(s, if s == 1 { r } else { (r / s).max(1) })
}
/// Texture on a `w × h` frame.
#[derive(Clone, Debug, PartialEq)]
pub struct Texture {
/// The strength: the slider / 100 × 0.9.
pub amount: f32,
/// The blur's box radii, in order; empty when the blur is too small to change anything.
pub radii: Vec<usize>,
}
impl Texture {
/// Texture for `p` on a `w × h` frame; `None` when it is off.
pub fn new(p: &CameraRaw, w: usize, h: usize) -> Option<Self> {
if p.texture == 0.0 {
return None;
}
let ps = p.pixel_scale.clamp(0.01, 1.0);
let sigma = (w.max(h) as f32 * 0.002).max(1.5 * ps);
Some(Texture { amount: p.texture / 100.0 * 0.9, radii: gauss_radii(sigma) })
}
}
/// The box radii of develop's Gaussian of `sigma`: none below 0.3.
pub(crate) fn gauss_radii(sigma: f32) -> Vec<usize> {
if sigma < 0.3 {
return Vec::new();
}
crate::fxutil::gauss_box_radii(sigma).to_vec()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn stages_resolve_for_the_dialogs_proxy_and_are_off_at_zero() {
let p = CameraRaw { dehaze: 40.0, clarity: -50.0, texture: 50.0, pixel_scale: 0.143, ..Default::default() };
let d = Dehaze::new(&p, 858, 572).unwrap();
assert_eq!((d.factor, d.size, d.radius, d.guide_radius, d.top), (2, [429, 286], 7, 14, 122));
let c = Clarity::new(&p, 858, 572).unwrap();
assert_eq!((c.radius, c.subsample, c.sub_radius, c.sub_size), (17, 2, 8, [429, 286]));
assert!((c.amount + 0.4).abs() < 1e-6);
assert_eq!(Texture::new(&p, 858, 572).unwrap().radii, [1, 1, 2]);
// Small frames: the plain guided filter, a blur too narrow to change anything.
assert_eq!(fast_guided_steps(3), (1, 3));
assert!(Texture::new(&CameraRaw { texture: 10.0, pixel_scale: 0.1, ..Default::default() }, 64, 48).unwrap().radii.is_empty());
let off = CameraRaw::default();
assert!(Dehaze::new(&off, 858, 572).is_none() && Clarity::new(&off, 858, 572).is_none() && Texture::new(&off, 858, 572).is_none());
}
#[test]
fn dehaze_cells_average_blocks_after_white_balance_and_refuse_a_wrong_size() {
let d = Dehaze::new(&CameraRaw { dehaze: 10.0, ..Default::default() }, 3, 1).unwrap();
let px = [[0.2, 0.4, 1.5, 1.0], [0.4, 0.0, 0.5, 1.0], [0.9, 0.9, 0.9, 1.0]];
assert_eq!(d.cells(&px, 3, 1, None), vec![[0.2, 0.4, 1.0], [0.4, 0.0, 0.5], [0.9, 0.9, 0.9]]);
let brighter = d.cells(&px, 3, 1, Some([2.0, 2.0, 2.0]));
assert!(brighter[0][0] > 0.2 && brighter[2] == [1.0; 3]);
assert!(d.cells(&px[..2], 3, 1, None).is_empty());
assert!(d.cells(&px, 1, 3, None).is_empty());
}
}
+13 -4
View File
@@ -1,6 +1,7 @@
//! Camera Raw's preview develop on the 858×572 proxy of a 6000×4000 image: the CPU develop
//! against the GPU passes (upload, render, readback), for per-pixel settings and for Shadows and
//! Highlights with them.
//! against the GPU passes (upload, render, readback), for per-pixel settings and for the spatial
//! stages (Dehaze, Shadows and Highlights, Clarity, Texture) with them. "Source uploaded every
//! time" also makes Dehaze's copy on the CPU every time, as a white balance drag does.
//! `cargo run --release -p photocraft-gpu --example bench_camera_raw [-- --quick]`
use std::time::Instant;
@@ -94,10 +95,18 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
("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 }),
("Shadows +50, Highlights -50, every per-pixel stage", CameraRaw { shadows: 50.0, highlights: -50.0, ..per_pixel_stages.clone() }),
("Clarity +50", CameraRaw { clarity: 50.0, pixel_scale: scale, ..Default::default() }),
("Texture +50", CameraRaw { texture: 50.0, pixel_scale: scale, ..Default::default() }),
("Dehaze +40", CameraRaw { dehaze: 40.0, pixel_scale: scale, ..Default::default() }),
("Clarity +50, Texture +50, Dehaze +40, every per-pixel stage", CameraRaw { clarity: 50.0, texture: 50.0, dehaze: 40.0, ..per_pixel_stages.clone() }),
(
"Clarity, Texture, Dehaze, Shadows, Highlights, every per-pixel stage",
CameraRaw { clarity: 50.0, texture: 50.0, dehaze: 40.0, shadows: 50.0, highlights: -50.0, ..per_pixel_stages },
),
];
for (name, p) in &sets {
let toned = p.shadows != 0.0 || p.highlights != 0.0;
let toned = p.spatial();
let cpu = time(if toned { runs.min(10) } else { runs }, || {
let mut px = src.clone();
develop(&mut px, w, h, p, false);
+143 -49
View File
@@ -7,25 +7,28 @@
//! 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. 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.
//! Blacks; this pass applies their change. Dehaze runs before them (its filters on the copy of
//! [`Dehaze::cells`], then `fs_dehaze`, which the later passes read instead of the source),
//! Clarity and Texture after them (`fs_luma`, then their filters, applied in `tonal`). Settings with Detail have no
//! [`PerPixel`] and stay on the CPU.
//!
//! 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 photocraft_algo::camera_raw::spatial::{DEHAZE_T_FLOOR, TEXTURE_LIMIT};
use photocraft_algo::camera_raw::{CURVE_LUT, Dehaze, PerPixel, VignetteStyle, WB_STEPS};
use crate::Unsupported;
use crate::camera_raw_tone::{ToneFrame, TonePipelines, WB_ROW};
use crate::camera_raw_tone::{Segment, 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: 21 rows of 16 bytes.
const PARAMS_SIZE: u64 = 21 * 16;
/// `Params` in the shader: 23 rows of 16 bytes.
const PARAMS_SIZE: u64 = 23 * 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;
@@ -61,6 +64,9 @@ pub struct CameraRawDevelop {
/// `fs_log` and `fs_points`: Shadows and Highlights' input, Whites and Blacks' cells after it.
log: wgpu::RenderPipeline,
points: wgpu::RenderPipeline,
/// `fs_dehaze` and `fs_luma`: Dehaze's result, Clarity and Texture's input.
dehaze: wgpu::RenderPipeline,
luma: wgpu::RenderPipeline,
tone: TonePipelines,
tone_frame: Option<ToneFrame>,
layout: wgpu::BindGroupLayout,
@@ -112,6 +118,11 @@ impl CameraRawDevelop {
crate::tex_entry(3),
crate::tex_entry(4),
crate::camera_raw_tone::uint_entry(5),
crate::tex_entry(6),
crate::tex_entry(7),
crate::tex_entry(8),
crate::tex_entry(9),
crate::tex_entry(10),
],
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
@@ -140,6 +151,8 @@ impl CameraRawDevelop {
let pipeline = pipeline_for("fs", FORMAT);
let log = pipeline_for("fs_log", wgpu::TextureFormat::R32Float);
let points = pipeline_for("fs_points", FORMAT);
let dehaze = pipeline_for("fs_dehaze", FORMAT);
let luma = pipeline_for("fs_luma", wgpu::TextureFormat::R32Float);
let params = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("pc_camera_raw_params"),
size: PARAMS_SIZE,
@@ -162,6 +175,8 @@ impl CameraRawDevelop {
pipeline,
log,
points,
dehaze,
luma,
tone: TonePipelines::build(device),
tone_frame: None,
layout,
@@ -206,20 +221,30 @@ impl CameraRawDevelop {
);
src.key = key;
}
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])
let clarity = stages.clarity.is_some();
let texture = stages.texture.as_ref().is_some_and(|t| t.radii.iter().any(|r| *r > 0));
let filtered = stages.local_tone.is_some() || stages.dehaze.is_some() || clarity || texture || stages.measure_whites_blacks.is_some();
let frame = if filtered {
let frame = match self.tone_frame.take() {
Some(f) if f.size() == size => f,
_ => ToneFrame::new(device, size),
};
let frame = self.tone_frame.insert(frame);
frame.prepare(device, queue, &self.tone, stages, &self.luts_view)?;
if let Some(d) = &stages.dehaze {
// The copy comes from the CPU's own code: which of its brightest cells tie decides
// the atmospheric light, and stage 1 on the GPU differs by a few ulps.
let gains = stages.gains.map(|g| g.map(f32::to_bits));
frame.upload_cells(queue, key.map(|k| (k, gains)), || Dehaze::cells(d, source, w as usize, h as usize, stages.gains))?;
}
None => None,
self.tone.write(queue, stages.local_tone.as_ref(), stages.measure_whites_blacks);
Some(&*frame)
} else {
None
};
queue.write_buffer(&self.params, 0, &params(size, stages, tone));
let slots = stages.local_tone.as_ref().map_or([0, 0], ToneFrame::last_slots);
let tone = [slots[0], slots[1], frame.map_or(1, |f| f.points().2), 0];
queue.write_buffer(&self.params, 0, &params(size, stages, tone, texture));
queue.write_texture(
wgpu::TexelCopyTextureInfo { texture: &self.luts, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
bytemuck::cast_slice(&tables(stages)),
@@ -232,30 +257,59 @@ impl CameraRawDevelop {
};
let target = self.target.insert(target);
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"),
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 all = Bound { log_in: dummy, log_out: dummy, stats: dummy_uint, base: dummy, haze: dummy, air: dummy, clarity: dummy, texture: dummy };
if let Some(f) = frame {
all.stats = f.stats();
if let Some((log_in, log_out)) = f.log() {
(all.log_in, all.log_out) = (log_in, log_out);
}
if let Some([t, air, dehazed]) = f.haze() {
(all.haze, all.air, all.base) = (t, air, dehazed);
}
if let Some((_, c, t)) = f.detail() {
all.clarity = c.unwrap_or(dummy);
all.texture = t.unwrap_or(dummy);
}
}
let group = |b: &Bound| {
let 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(b.log_in) },
wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(b.log_out) },
wgpu::BindGroupEntry { binding: 5, resource: wgpu::BindingResource::TextureView(b.stats) },
wgpu::BindGroupEntry { binding: 6, resource: wgpu::BindingResource::TextureView(b.base) },
wgpu::BindGroupEntry { binding: 7, resource: wgpu::BindingResource::TextureView(b.haze) },
wgpu::BindGroupEntry { binding: 8, resource: wgpu::BindingResource::TextureView(b.air) },
wgpu::BindGroupEntry { binding: 9, resource: wgpu::BindingResource::TextureView(b.clarity) },
wgpu::BindGroupEntry { binding: 10, resource: wgpu::BindingResource::TextureView(b.texture) },
];
device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("pc_camera_raw"), layout: &self.layout, entries: &entries })
};
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);
// A pass never binds the texture it renders: those are dummies in its group.
let main = group(&all);
if let Some(f) = frame {
let missing = || Unsupported("a Camera Raw stage's textures are missing".into());
if stages.dehaze.is_some() {
let [_, _, dehazed] = f.haze().ok_or_else(missing)?;
f.record(encoder, &self.tone, Segment::Haze);
pass(encoder, &self.dehaze, &group(&Bound { base: dummy, log_in: dummy, log_out: dummy, ..all }), dehazed);
}
if stages.local_tone.is_some() {
// The input's log luminance, then the filter on it.
let (log_in, _) = f.log().ok_or_else(missing)?;
pass(encoder, &self.log, &group(&Bound { log_in: dummy, log_out: dummy, ..all }), log_in);
f.record(encoder, &self.tone, Segment::Tone);
}
if clarity || texture {
let (lc, _, _) = f.detail().ok_or_else(missing)?;
pass(encoder, &self.luma, &main, lc);
f.record(encoder, &self.tone, Segment::Detail);
}
if stages.measure_whites_blacks.is_some() {
pass(encoder, &self.points, &main, f.points().0);
f.record(encoder, &self.tone, Segment::WhitesBlacks);
}
}
pass(encoder, &self.pipeline, &main, &target.view);
@@ -285,6 +339,9 @@ impl CameraRawDevelop {
Some(e) => {
// A half-done upload must not be taken for the cached source next time.
self.source = None;
if let Some(f) = &mut self.tone_frame {
f.forget_cells();
}
Err(Unsupported(format!("GPU Camera Raw develop failed: {e}")))
}
None => result,
@@ -352,6 +409,23 @@ impl CameraRawDevelop {
}
}
/// The textures a pass of `camera_raw.wgsl` reads besides the source and tables (dummies where
/// unused).
#[derive(Clone, Copy)]
struct Bound<'a> {
log_in: &'a wgpu::TextureView,
log_out: &'a wgpu::TextureView,
stats: &'a wgpu::TextureView,
/// Stages 1 and 2 when Dehaze runs.
base: &'a wgpu::TextureView,
/// Dehaze's transmission and atmospheric light.
haze: &'a wgpu::TextureView,
air: &'a wgpu::TextureView,
/// Clarity's coefficients and Texture's blur.
clarity: &'a wgpu::TextureView,
texture: &'a wgpu::TextureView,
}
/// 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 {
@@ -383,14 +457,15 @@ fn check_size(device: &wgpu::Device, source: &[[f32; 4]], [w, h]: [u32; 2]) -> R
Ok(())
}
/// Flags of `Params.flags`, in the shader's bit order.
fn flags(s: &PerPixel) -> u32 {
/// Flags of `Params.flags`, in the shader's bit order; `texture` is whether Texture's blur ran.
fn flags(s: &PerPixel, texture: bool) -> 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(),
// The luminance stage: Contrast, Clarity, Texture.
s.contrast.is_some() || s.clarity.is_some() || s.texture.is_some(),
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),
@@ -406,12 +481,16 @@ fn flags(s: &PerPixel) -> u32 {
s.grain.is_some(),
s.clamp,
s.local_tone.is_some(),
s.dehaze.is_some(),
s.clarity.is_some(),
texture,
];
on.iter().enumerate().fold(0, |f, (bit, on)| if *on { f | 1 << bit } else { f })
}
/// 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<u8> {
/// The shader's `Params` for a `size` image; `tone` is `Params.tone`, `texture` whether Texture's
/// blur ran.
fn params(size: [u32; 2], s: &PerPixel, tone: [u32; 4], texture: bool) -> Vec<u8> {
let g = s.gains.unwrap_or([1.0; 3]);
let presence = s.presence.unwrap_or_default();
let hsl = s.hsl.unwrap_or_default();
@@ -419,7 +498,7 @@ fn params(size: [u32; 2], s: &PerPixel, tone: Option<[u32; 4]>) -> Vec<u8> {
let vig = s.vignette.as_ref();
let grain = s.grain.as_ref();
let mut out: Vec<u8> = Vec::with_capacity(PARAMS_SIZE as usize);
out.extend([size[0], size[1], flags(s)].iter().flat_map(|v| v.to_le_bytes()).chain(s.encoding.to_le_bytes()));
out.extend([size[0], size[1], flags(s, texture)].iter().flat_map(|v| v.to_le_bytes()).chain(s.encoding.to_le_bytes()));
let mut f = |v: [f32; 4]| out.extend(v.iter().flat_map(|x| x.to_le_bytes()));
f([g[0], g[1], g[2], s.contrast.unwrap_or(0.0)]);
f([presence[0], presence[1], 0.0, 0.0]);
@@ -444,8 +523,23 @@ fn params(size: [u32; 2], s: &PerPixel, tone: Option<[u32; 4]>) -> Vec<u8> {
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.extend(tone.iter().flat_map(|v| v.to_le_bytes()));
let amount = |v: Option<f32>| v.unwrap_or(0.0);
let rows = [
LOG_FLOOR,
0.0,
0.0,
0.0,
amount(s.dehaze.as_ref().map(|d| d.amount)),
amount(s.clarity.as_ref().map(|c| c.amount)),
amount(s.texture.as_ref().map(|t| t.amount)),
TEXTURE_LIMIT,
s.dehaze.as_ref().map_or(1.0, |d| d.factor as f32),
s.clarity.as_ref().map_or(1.0, |c| c.subsample as f32),
DEHAZE_T_FLOOR,
0.0,
];
out.extend(rows.iter().flat_map(|v| v.to_le_bytes()));
out
}
+108 -13
View File
@@ -1,7 +1,9 @@
// 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. Shadows and
// Highlights (`camera_raw_tone.wgsl`) start from `fs_log` and end here as a gain per pixel.
// named after, in the same order of operations; `camera_raw.rs` holds the bindings. The spatial
// stages' filters (`camera_raw_tone.wgsl`, `camera_raw_filters.wgsl`) start from passes here
// (`fs_log`, `fs_luma`, `fs_points`; Dehaze from a copy the CPU makes) and end here: Dehaze in `fs_dehaze`, Shadows
// and Highlights as a gain per pixel, Clarity and Texture in `tonal`.
struct Params {
size: vec2<u32>,
@@ -29,6 +31,10 @@ struct Params {
tone: vec4<u32>,
// The log luminance's floor.
floor_: vec4<f32>,
// Dehaze, Clarity and Texture's strengths, Texture's limit.
spatial: vec4<f32>,
// Dehaze's and Clarity's subsampling, the transmission's floor.
spatial2: vec4<f32>,
}
@group(0) @binding(0) var<uniform> P: Params;
@@ -39,9 +45,18 @@ struct Params {
@group(0) @binding(3) var log_in: texture_2d<f32>;
@group(0) @binding(4) var log_out: texture_2d<f32>;
@group(0) @binding(5) var stats: texture_2d<u32>;
// Dehaze: stages 1 and 2 (read instead of `src` once rendered), the transmission (red) on the
// copy, the atmospheric light (one texel).
@group(0) @binding(6) var base: texture_2d<f32>;
@group(0) @binding(7) var haze: texture_2d<f32>;
@group(0) @binding(8) var air: texture_2d<f32>;
// Clarity's coefficients (a, b) on its copy; Texture's blur (red).
@group(0) @binding(9) var clarity: texture_2d<f32>;
@group(0) @binding(10) var blur: texture_2d<f32>;
const GAINS: u32 = 0u;
const CONTRAST: u32 = 1u;
// The luminance stage: Contrast, Clarity or Texture.
const LUMINANCE: u32 = 1u;
const WHITES: u32 = 2u;
const BLACKS: u32 = 3u;
const PER_CHANNEL: u32 = 4u;
@@ -55,6 +70,9 @@ const VIGNETTE: u32 = 13u;
const GRAIN: u32 = 14u;
const CLAMP: u32 = 15u;
const LOCAL_TONE: u32 = 16u;
const DEHAZE: u32 = 17u;
const CLARITY: u32 = 18u;
const TEXTURE: u32 = 19u;
const CURVE_LUT: i32 = 1024;
const WB_STEPS: i32 = 33;
@@ -308,9 +326,42 @@ fn unkey(k: u32) -> f32 {
return bitcast<f32>(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<i32>, q: vec3<f32>) -> vec3<f32> {
var c = balance(q);
// `photo_util::bilinear` of texture `t` at (x, y), edges clamped.
fn bilinear(t: texture_2d<f32>, x_: f32, y_: f32) -> vec4<f32> {
let n = vec2<i32>(textureDimensions(t));
let x = clamp(x_, 0.0, f32(n.x - 1));
let y = clamp(y_, 0.0, f32(n.y - 1));
let x0 = i32(floor(x));
let y0 = i32(floor(y));
let x1 = min(x0 + 1, n.x - 1);
let y1 = min(y0 + 1, n.y - 1);
let tx = x - f32(x0);
let ty = y - f32(y0);
let p00 = textureLoad(t, vec2(x0, y0), 0);
let p10 = textureLoad(t, vec2(x1, y0), 0);
let p01 = textureLoad(t, vec2(x0, y1), 0);
let p11 = textureLoad(t, vec2(x1, y1), 0);
let top = p00 + (p10 - p00) * tx;
let bot = p01 + (p11 - p01) * tx;
return top + (bot - top) * ty;
}
// Where pixel `p` of a copy subsampled `s` times sits: develop's `(x + 0.5) / s - 0.5`.
fn subsampled(p: vec2<i32>, s: f32) -> vec2<f32> {
return (vec2<f32>(p) + vec2(0.5)) / s - vec2(0.5);
}
// Stages 1 and 2 at `p`: the dehazed frame once `fs_dehaze` rendered it.
fn source(p: vec2<i32>) -> vec3<f32> {
if on(DEHAZE) {
return textureLoad(base, p, 0).rgb;
}
return balance(textureLoad(src, p, 0).rgb);
}
// Stages 1 to 3 up to Shadows and Highlights at `p`.
fn lit(p: vec2<i32>) -> vec3<f32> {
var c = source(p);
// 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) {
@@ -319,13 +370,32 @@ fn tonal(p: vec2<i32>, q: vec3<f32>) -> vec3<f32> {
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) {
return c;
}
// Stages 1 to 3 on the pixel at `p`: what Whites and Blacks measure and apply to.
fn tonal(p: vec2<i32>) -> vec3<f32> {
var c = lit(p);
// 3. Clarity, Texture and Contrast on the luminance (develop's `tone`).
if on(LUMINANCE) {
let l0 = max(luma(c), 0.0);
let lc = min(l0, 1.0);
var lv = lc;
let xx = clamp(lv, 0.0, 1.0);
lv += -P.gains.w * sin(TAU * xx) / TAU;
if on(CLARITY) {
let at = subsampled(p, P.spatial2.y);
let ab = bilinear(clarity, at.x, at.y);
let base_ = ab.x * lc + ab.y;
let d = 2.0 * clamp(lv, 0.0, 1.0) - 1.0;
let mw = 1.0 - d * d;
lv += P.spatial.y * (lc - base_) * mw;
}
if on(TEXTURE) {
lv += P.spatial.z * clamp(lc - textureLoad(blur, p, 0).r, -P.spatial.w, P.spatial.w);
}
if P.gains.w != 0.0 {
let xx = clamp(lv, 0.0, 1.0);
lv += -P.gains.w * sin(TAU * xx) / TAU;
}
lv = max(lv, 0.0) + (l0 - lc);
if l0 > 1e-5 {
c = c * (lv / l0);
@@ -336,14 +406,39 @@ fn tonal(p: vec2<i32>, q: vec3<f32>) -> vec3<f32> {
return c;
}
// 2. Dehaze: each pixel moved away from the atmospheric light by the transmission (brought up
// from the copy), or toward it for negative amounts.
@fragment
fn fs_dehaze(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
let p = vec2<i32>(floor(pos.xy));
let q = textureLoad(src, p, 0);
let i = balance(q.rgb);
let at = subsampled(p, P.spatial2.x);
let tv = clamp(bilinear(haze, at.x, at.y).r, P.spatial2.z, 1.0);
let a = textureLoad(air, vec2(0, 0), 0).rgb;
let amount = P.spatial.x;
if amount >= 0.0 {
let j = (i - a) / tv + a;
return vec4(i + (j - i) * amount, q.a);
}
return vec4(i + (a - i) * (-amount) * 0.5 * (1.0 - tv * 0.5), q.a);
}
// The log luminance Shadows and Highlights filter (`local_tone::apply`).
@fragment
fn fs_log(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
let c = balance(textureLoad(src, vec2<i32>(floor(pos.xy)), 0).rgb);
let c = source(vec2<i32>(floor(pos.xy)));
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);
}
// Clarity and Texture's input: the luminance after Shadows and Highlights, clipped to 0 … 1.
@fragment
fn fs_luma(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
let c = lit(vec2<i32>(floor(pos.xy)));
return vec4(min(max(luma(c), 0.0), 1.0), 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
@@ -354,7 +449,7 @@ fn fs_points(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
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);
let c = tonal(vec2(x, y));
sum += clamp(vec3(decode(c.x), decode(c.y), decode(c.z)), vec3(0.0), vec3(1.0));
}
}
@@ -366,7 +461,7 @@ fn fs_points(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
fn fs(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
let p = vec2<i32>(floor(pos.xy));
let q = textureLoad(src, p, 0);
var c = tonal(p, q.rgb);
var c = tonal(p);
// 3b. Whites and Blacks.
if on(WHITES) || on(BLACKS) {
c = whites_blacks(c);
+142
View File
@@ -0,0 +1,142 @@
// Dehaze, Clarity and Texture for Camera Raw's GPU preview: develop's `box_mean`, `guided`,
// `guided_fast` and `dehaze` (constants from `photocraft_algo::camera_raw::spatial`) as fragment
// passes. Appended to `camera_raw_tone.wgsl`, whose bindings and helpers it uses;
// `camera_raw_tone.rs` orders the passes and `camera_raw.wgsl` applies their results.
fn luma(c: vec3<f32>) -> f32 {
return 0.2126 * c.x + 0.7152 * c.y + 0.0722 * c.z;
}
// `box_mean` along one axis (misc.x: 0 rows, 1 columns) at radius misc.y, edges clamped. Mode
// misc.z: 0 the means; 1 then the guided filter's coefficients (a, b) from the means of
// (I, p, I·p, I·I), regularised by misc.w's bits; 2 then the guided filter's output a·I + b, I
// the red channel of `plane_b`.
@fragment
fn fs_box(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
let p = pixel(pos);
let n = src_size();
let r = i32(S.misc.y);
var acc = vec4(0.0);
if S.misc.x == 0u {
for (var k = -r; k <= r; k++) {
acc += textureLoad(plane_a, vec2(clamp(p.x + k, 0, n.x - 1), p.y), 0);
}
} else {
for (var k = -r; k <= r; k++) {
acc += textureLoad(plane_a, vec2(p.x, clamp(p.y + k, 0, n.y - 1)), 0);
}
}
let m = acc / f32(2 * r + 1);
if S.misc.z == 1u {
let a = (m.z - m.x * m.y) / (m.w - m.x * m.x + bitcast<f32>(S.misc.w));
return vec4(a, m.y - a * m.x, 0.0, 1.0);
}
if S.misc.z == 2u {
return vec4(m.x * textureLoad(plane_b, p, 0).r + m.y, 0.0, 0.0, 1.0);
}
return m;
}
// `guided_fast`'s subsampled copy of `plane_a`'s red channel (`edge × edge` block means), as the
// guided filter's (I, p, I·p, I·I) with I = p.
@fragment
fn fs_block(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
let t = pixel(pos);
let f = i32(S.sizes2.w);
let end = min((t + vec2(1)) * f, src_size());
var sum = 0.0;
for (var y = t.y * f; y < end.y; y++) {
for (var x = t.x * f; x < end.x; x++) {
sum += textureLoad(plane_a, vec2(x, y), 0).r;
}
}
let m = sum / f32((end.x - t.x * f) * (end.y - t.y * f));
return vec4(m, m, m * m, m * m);
}
// Dehaze's minimum filter along one axis (misc.x) at radius misc.y, the window cut at the edges.
// Mode misc.z: 0 the red channel; 1 the darkest channel of `plane_a`; 2 the darkest channel over
// the atmospheric light (`plane_b`'s one texel); 3 the red channel, then the guided filter's
// (I, p, I·p, I·I) for the transmission: I the luminance of the cells (`plane_b`), p = 1 − ω·min
// with ω misc.w's bits.
@fragment
fn fs_min(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
let p = pixel(pos);
let n = src_size();
let r = i32(S.misc.y);
let mode = S.misc.z;
let air = textureLoad(plane_b, vec2(0, 0), 0).rgb;
var axis = vec2(1, 0);
var at = p.x;
var len = n.x;
if S.misc.x == 1u {
axis = vec2(0, 1);
at = p.y;
len = n.y;
}
// The window is never empty, so this never shows.
var m = 3.0e38;
for (var k = max(at - r, 0); k <= min(at + r, len - 1); k++) {
let v = textureLoad(plane_a, p + axis * (k - at), 0);
var d = v.r;
if mode == 1u {
d = min(min(v.r, v.g), v.b);
} else if mode == 2u {
d = min(min(v.r / air.r, v.g / air.g), v.b / air.b);
}
m = min(m, d);
}
if mode == 3u {
let i = luma(textureLoad(plane_b, p, 0).rgb);
let t = 1.0 - bitcast<f32>(S.misc.w) * m;
return vec4(i, t, i * t, i * i);
}
return vec4(m, 0.0, 0.0, 1.0);
}
// The cells in the order `dehaze` sorts them, for selecting the atmospheric light's: -1 where the
// dark channel (`plane_a`) is above the selected value (slot misc.y), the cell's index where it
// is that value (ties go in index order), and above every index elsewhere.
@fragment
fn fs_haze_rank(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
let p = pixel(pos);
let k = key(textureLoad(plane_a, p, 0).r);
let v = stat(S.misc.y, 0).x;
var out = 3.0e38;
if k > v {
out = -1.0;
} else if k == v {
out = f32(p.y * src_size().x + p.x);
}
return vec4(out, 0.0, 0.0, 1.0);
}
// The atmospheric light. Mode misc.x 0: per `edge × edge` tile, the cells (`plane_b`) whose order
// (`plane_a`) is at or below the selected one (slot misc.y), each divided by their count misc.w,
// summed. Mode 1: every tile (`plane_a`) summed, each channel at least misc.w's bits.
@fragment
fn fs_air(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
let n = src_size();
var sum = vec3(0.0);
if S.misc.x == 1u {
for (var y = 0; y < n.y; y++) {
for (var x = 0; x < n.x; x++) {
sum += textureLoad(plane_a, vec2(x, y), 0).rgb;
}
}
return vec4(max(sum, vec3(bitcast<f32>(S.misc.w))), 1.0);
}
let t = pixel(pos);
let f = i32(S.sizes2.w);
let end = min((t + vec2(1)) * f, n);
let cut = stat(S.misc.y, 0).x;
let top = f32(S.misc.w);
for (var y = t.y * f; y < end.y; y++) {
for (var x = t.x * f; x < end.x; x++) {
if key(textureLoad(plane_a, vec2(x, y), 0).r) <= cut {
sum += textureLoad(plane_b, vec2(x, y), 0).rgb / top;
}
}
}
return vec4(sum, 1.0);
}
+449 -152
View File
@@ -1,14 +1,21 @@
//! 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.
//! The spatial stages of Camera Raw's GPU preview (#6916) as fragment passes, with no compute
//! shaders, so the same passes can run on WebGL2: Dehaze, Shadows and Highlights, Clarity and
//! Texture, and the measurement of Whites and Blacks' points after them.
//!
//! 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.
//! Shadows and Highlights are the local Laplacian filter of
//! `photocraft_algo::camera_raw::local_tone` (`camera_raw_tone.wgsl`). 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.
//!
//! Dehaze, Clarity and Texture (`camera_raw_filters.wgsl`, constants from
//! `photocraft_algo::camera_raw::spatial`) are separable box and minimum filters and guided
//! filters on small copies; `camera_raw.wgsl` applies their results per pixel.
//!
//! The quantiles the filters and Whites and Blacks read (including Dehaze's brightest cells) 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.
//!
//! 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.
@@ -16,12 +23,15 @@
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 photocraft_algo::camera_raw::spatial::{CLARITY_EPS, DEHAZE_AIR_FLOOR, DEHAZE_EPS, DEHAZE_OMEGA};
use photocraft_algo::camera_raw::{LocalTone, PerPixel, ToneKind, WhitesBlacksModel, quantile_rank};
use crate::Unsupported;
/// The passes' WGSL source.
/// The Shadows and Highlights passes' WGSL source.
pub const CAMERA_RAW_TONE_SHADER: &str = include_str!("camera_raw_tone.wgsl");
/// Dehaze, Clarity and Texture's passes, compiled after [`CAMERA_RAW_TONE_SHADER`] in one module.
pub const CAMERA_RAW_FILTERS_SHADER: &str = include_str!("camera_raw_filters.wgsl");
const PLANE: wgpu::TextureFormat = wgpu::TextureFormat::R32Float;
const RGBA: wgpu::TextureFormat = wgpu::TextureFormat::Rgba32Float;
@@ -56,9 +66,12 @@ const fn rounds() -> usize {
/// 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.
/// Statistics slots: pass `i`'s input and output are `2i` and `2i + 1`; Whites and Blacks' points;
/// Dehaze's darkest value among the brightest cells, then the last of those cells in its order.
const WB_SLOT: u32 = 4;
const SLOTS: u32 = 5;
const HAZE_SLOT: u32 = 5;
const TIE_SLOT: u32 = 6;
const SLOTS: u32 = 7;
/// Rows of `camera_raw.wgsl`'s table texture that hold the Whites and Blacks curves.
pub(crate) const WB_ROW: u32 = 5;
@@ -120,11 +133,38 @@ enum Pipe {
Reduce,
Update,
WbRows,
/// `fs_box` into an `Rgba32Float` target (guided filters) or an `R32Float` one (Texture).
Box,
BoxPlane,
Block,
/// `fs_min` into an `R32Float` target, or (its packing mode) an `Rgba32Float` one.
Min,
MinPack,
HazeRank,
Air,
}
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];
const ALL: [Pipe; 18] = [
Pipe::Down,
Pipe::DownRemap,
Pipe::DownAtlas,
Pipe::Lap,
Pipe::Shift,
Pipe::Cells,
Pipe::Init,
Pipe::Count,
Pipe::Reduce,
Pipe::Update,
Pipe::WbRows,
Pipe::Box,
Pipe::BoxPlane,
Pipe::Block,
Pipe::Min,
Pipe::MinPack,
Pipe::HazeRank,
Pipe::Air,
];
fn entry(self) -> &'static str {
match self {
@@ -139,12 +179,17 @@ impl Pipe {
Pipe::Reduce => "fs_reduce",
Pipe::Update => "fs_update",
Pipe::WbRows => "fs_wb_rows",
Pipe::Box | Pipe::BoxPlane => "fs_box",
Pipe::Block => "fs_block",
Pipe::Min | Pipe::MinPack => "fs_min",
Pipe::HazeRank => "fs_haze_rank",
Pipe::Air => "fs_air",
}
}
fn targets(self) -> &'static [wgpu::TextureFormat] {
match self {
Pipe::DownRemap | Pipe::DownAtlas => &[RGBA],
Pipe::DownRemap | Pipe::DownAtlas | Pipe::Box | Pipe::Block | Pipe::MinPack | Pipe::Air => &[RGBA],
Pipe::Init | Pipe::Update => &[UINT],
Pipe::Count | Pipe::Reduce => &[UINT, UINT],
_ => &[PLANE],
@@ -192,7 +237,7 @@ 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()),
source: wgpu::ShaderSource::Wgsl(format!("{CAMERA_RAW_TONE_SHADER}\n{CAMERA_RAW_FILTERS_SHADER}").into()),
});
let float = wgpu::TextureSampleType::Float { filterable: false };
let uniform = |binding, dynamic, size| wgpu::BindGroupLayoutEntry {
@@ -277,7 +322,9 @@ impl TonePipelines {
}
/// 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]>) {
pub(crate) fn write(&mut self, queue: &wgpu::Queue, tone: Option<&LocalTone>, whites_blacks: Option<[f32; 2]>) {
let none = LocalTone { passes: Vec::new() };
let tone = tone.unwrap_or(&none);
let m = photocraft_algo::camera_raw::whites_blacks_model();
let rows = model_rows(&m);
if !self.model_written {
@@ -429,6 +476,28 @@ impl Builder {
self.ops.push(Pending::Draw { pipe, step, reads, targets: targets.iter().map(|v| (*v).clone()).collect(), viewport });
}
/// A pass of `pipe` into `target` (`size` texels) reading `a` (`src` texels) and `b`.
#[allow(clippy::too_many_arguments)]
fn filter(&mut self, pipe: Pipe, size: [u32; 2], src: [u32; 2], misc: [u32; 4], a: &Tex, b: Option<&Tex>, target: &Tex) {
let mut step = Step::sized(size, src);
step.misc = misc;
self.draw(pipe, step, Reads { a: Some(a.view.clone()), b: b.map(|t| t.view.clone()), ..Default::default() }, &[&target.view], None);
}
/// Develop's `guided` (radius `r`, regularised by `eps`) on the (I, p, I·p, I·I) in `t[0]`
/// (`size` texels): the box means of its coefficients (a, b) in `t[0]`, or with `output`
/// a·I + b in `t[2]`.
fn guided(&mut self, size: [u32; 2], r: u32, eps: f32, t: &[Tex; 3], output: bool) {
self.filter(Pipe::Box, size, size, [0, r, 0, 0], &t[0], None, &t[1]);
self.filter(Pipe::Box, size, size, [1, r, 1, eps.to_bits()], &t[1], None, &t[2]);
self.filter(Pipe::Box, size, size, [0, r, 0, 0], &t[2], None, &t[1]);
if output {
self.filter(Pipe::Box, size, size, [1, r, 2, 0], &t[1], Some(&t[0]), &t[2]);
} else {
self.filter(Pipe::Box, size, size, [1, r, 0, 0], &t[1], None, &t[0]);
}
}
/// 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).
@@ -539,28 +608,52 @@ impl TonePipelines {
}
}
/// What a plan runs: the passes' kept quantiles (their bits), and whether Whites and Blacks
/// measure the points.
/// What a plan runs.
#[derive(Clone, PartialEq, Eq, Hash)]
struct PlanKey {
/// Dehaze: the minimum filter's and the guided filter's radii, the cells the light averages.
dehaze: Option<[u32; 3]>,
/// Shadows and Highlights: the passes' kept quantiles (their bits).
keeps: Vec<u32>,
/// Clarity: the subsampling and the radius there.
clarity: Option<[u32; 2]>,
/// Texture: the blur's box radii (those of 0 left out).
texture: Vec<u32>,
/// Whether Whites and Blacks measure the points.
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 }
fn new(s: &PerPixel) -> Self {
let n = |v: usize| u32::try_from(v).unwrap_or(u32::MAX);
PlanKey {
dehaze: s.dehaze.as_ref().map(|d| [n(d.radius), n(d.guide_radius), n(d.top)]),
keeps: s.local_tone.as_ref().map_or(Vec::new(), |t| t.passes.iter().map(|p| p.keep.to_bits()).collect()),
clarity: s.clarity.as_ref().map(|c| [n(c.subsample), n(c.sub_radius)]),
texture: s.texture.as_ref().map_or(Vec::new(), |t| t.radii.iter().filter(|r| **r > 0).map(|r| n(*r)).collect()),
whites_blacks: s.measure_whites_blacks.is_some(),
}
}
}
/// The recorded passes for one [`PlanKey`].
/// Where a plan's passes run among `camera_raw.wgsl`'s.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Segment {
/// First: Dehaze's atmospheric light and transmission (before `fs_dehaze`).
Haze,
/// After `fs_log`: Shadows and Highlights.
Tone,
/// After `fs_luma`: Clarity's coefficients and Texture's blur.
Detail,
/// After `fs_points`: Whites and Blacks' points and curves.
WhitesBlacks,
}
/// The recorded passes for one [`PlanKey`], by [`Segment`].
struct Plan {
/// Holds the passes' uniform slots.
_steps: wgpu::Buffer,
/// Shadows and Highlights.
tone: Vec<Op>,
/// Whites and Blacks' points and curves, after `camera_raw.wgsl`'s `fs_points`.
whites_blacks: Vec<Op>,
segments: [Vec<Op>; 4],
}
/// Pyramid level sizes down to about 2 pixels on the short side (`local_tone::depth`).
@@ -575,10 +668,9 @@ fn levels([w, h]: [u32; 2]) -> Vec<[u32; 2]> {
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).
/// Shadows and Highlights' textures.
struct Pyramid {
/// Level sizes, finest first (at least two).
levels: Vec<[u32; 2]>,
/// Atlas columns.
cols: u32,
@@ -595,20 +687,13 @@ pub(crate) struct ToneFrame {
/// 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,
/// Selections over the whole frame.
full: Chain,
small: Chain,
state: [Tex; 2],
stats: Tex,
plans: HashMap<PlanKey, Plan>,
}
impl ToneFrame {
impl Pyramid {
/// 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<Self, Unsupported> {
fn new(device: &wgpu::Device, size: [u32; 2]) -> Result<Self, Unsupported> {
let levels = levels(size);
let n = levels.len();
let Some(&[w1, h1]) = levels.get(1) else {
@@ -621,15 +706,9 @@ impl ToneFrame {
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 (cells_size, _) = cells_of(size, RANGE_SIDE);
let plane = |label: &str, s: [u32; 2]| Tex::target(device, label, s, PLANE);
Ok(ToneFrame {
size,
Ok(Pyramid {
cols,
log_in: plane("pc_camera_raw_log_in", size),
input: plane("pc_camera_raw_tone_input", size),
@@ -642,33 +721,191 @@ impl ToneFrame {
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,
full: Chain::new(device, size),
levels,
})
}
}
/// What Dehaze's copy was made from: the source's key and the white balance gains' bits.
pub(crate) type CellsKey = (u64, Option<[u32; 3]>);
/// Dehaze's textures: the copy's cells, the filters on them and the dehazed frame.
struct Haze {
/// The copy's size.
size: [u32; 2],
/// The copy ([`Dehaze::cells`](photocraft_algo::camera_raw::Dehaze::cells), uploaded) and
/// what it was made from.
cells: Tex,
cells_key: Option<CellsKey>,
/// A minimum filter's rows.
min: Tex,
/// The dark channel.
dark: Tex,
/// The cells' order for the atmospheric light (`fs_haze_rank`).
order: Tex,
/// The light's sums per tile, and the light.
tiles: Tex,
tiles_size: [u32; 2],
air: Tex,
/// The transmission's guided filter: its input, then working textures; the transmission ends
/// in the last.
guide: [Tex; 3],
/// Selections over the copy.
chain: Chain,
/// Stages 1 and 2 at full size, which `fs_dehaze` renders.
dehazed: Tex,
}
impl Haze {
fn new(device: &wgpu::Device, size: [u32; 2], full: [u32; 2]) -> Self {
let tiles_size = [size[0].div_ceil(COUNT_TILE), size[1].div_ceil(COUNT_TILE)];
let rgba = |label: &str, s: [u32; 2]| Tex::target(device, label, s, RGBA);
let plane = |label: &str| Tex::target(device, label, size, PLANE);
Haze {
size,
cells: Tex::new(device, "pc_camera_raw_haze_cells", size, RGBA, wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST),
cells_key: None,
min: plane("pc_camera_raw_haze_min"),
dark: plane("pc_camera_raw_haze_dark"),
order: plane("pc_camera_raw_haze_order"),
tiles: rgba("pc_camera_raw_haze_tiles", tiles_size),
tiles_size,
air: rgba("pc_camera_raw_haze_air", [1, 1]),
guide: [0, 1, 2].map(|_| rgba("pc_camera_raw_haze_guide", size)),
chain: Chain::new(device, size),
dehazed: rgba("pc_camera_raw_dehazed", full),
}
}
}
/// Clarity and Texture's textures.
struct Detail {
/// The luminance clipped to 1, which `camera_raw.wgsl`'s `fs_luma` renders.
lc: Tex,
/// Texture's blur, back and forth; it ends in the second.
blur: Option<[Tex; 2]>,
/// Clarity's subsampled copy and guided filter (its size; the coefficients end in the first).
sub: Option<([u32; 2], [Tex; 3])>,
}
/// The cells of a `size` frame at most `side` across: their size and edge in pixels.
fn cells_of(size: [u32; 2], side: usize) -> ([u32; 2], u32) {
let f = size[0].max(size[1]).div_ceil(u32::try_from(side).unwrap_or(u32::MAX)).max(1);
([size[0].div_ceil(f), size[1].div_ceil(f)], f)
}
/// The spatial stages' textures for one frame size (made when a stage first needs them), and
/// their plans.
pub(crate) struct ToneFrame {
size: [u32; 2],
pyramid: Option<Pyramid>,
haze: Option<Haze>,
detail: Option<Detail>,
/// Whites and Blacks' cells, which `fs_points` renders.
points: Tex,
points_size: [u32; 2],
points_edge: u32,
small: Chain,
state: [Tex; 2],
stats: Tex,
plans: HashMap<PlanKey, Plan>,
/// The plan [`prepare`](Self::prepare) picked.
current: Option<PlanKey>,
}
impl ToneFrame {
/// The textures every plan of a `size` frame uses.
pub(crate) fn new(device: &wgpu::Device, size: [u32; 2]) -> Self {
let (points_size, points_edge) = cells_of(size, photocraft_algo::camera_raw::whites_blacks_model().points_side);
ToneFrame {
size,
pyramid: None,
haze: None,
detail: None,
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(),
})
current: None,
}
}
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
/// Makes the textures and the plan for `stages`, which [`record`](Self::record) then records.
/// `luts` is `camera_raw.wgsl`'s table texture, where Whites and Blacks' curves go. A frame too
/// small or too large for a stage's textures is `Unsupported`.
pub(crate) fn prepare(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
pipes: &TonePipelines,
stages: &PerPixel,
luts: &wgpu::TextureView,
) -> Result<(), Unsupported> {
let dim = |v: [usize; 2]| [u32::try_from(v[0]).unwrap_or(u32::MAX), u32::try_from(v[1]).unwrap_or(u32::MAX)];
let max = device.limits().max_texture_dimension_2d;
if stages.local_tone.is_some() && self.pyramid.is_none() {
self.pyramid = Some(Pyramid::new(device, self.size)?);
}
if let Some(d) = &stages.dehaze {
let size = dim(d.size);
if size[0] == 0 || size[1] == 0 || size[0] > max || size[1] > max {
return Err(Unsupported(format!("Dehaze's {}×{} copy doesn't fit the GPU's {max} px textures", size[0], size[1])));
}
if self.haze.as_ref().is_none_or(|h| h.size != size) {
self.haze = Some(Haze::new(device, size, self.size));
self.plans.clear();
}
}
if stages.clarity.is_some() || stages.texture.is_some() {
let full = self.size;
let detail = self.detail.get_or_insert_with(|| Detail { lc: Tex::target(device, "pc_camera_raw_luma", full, PLANE), blur: None, sub: None });
if stages.texture.is_some() && detail.blur.is_none() {
detail.blur = Some([0, 1].map(|_| Tex::target(device, "pc_camera_raw_texture", full, PLANE)));
}
if let Some(c) = &stages.clarity {
let size = dim(c.sub_size);
if size[0] == 0 || size[1] == 0 || size[0] > max || size[1] > max {
return Err(Unsupported(format!("Clarity's {}×{} copy doesn't fit the GPU's {max} px textures", size[0], size[1])));
}
if detail.sub.as_ref().is_none_or(|(s, _)| *s != size) {
detail.sub = Some((size, [0, 1, 2].map(|_| Tex::target(device, "pc_camera_raw_clarity", size, RGBA))));
self.plans.clear();
}
}
}
let key = PlanKey::new(stages);
if !self.plans.contains_key(&key) {
let plan = self.plan(device, queue, pipes, &key, luts);
self.plans.insert(key.clone(), plan);
}
self.current = Some(key);
Ok(())
}
/// The last pass's output, before its kept quantile is put back.
pub(crate) fn log_out(&self) -> &wgpu::TextureView {
&self.out[0].view
/// Records segment `seg` of the plan [`prepare`](Self::prepare) picked; results go into `stats`.
pub(crate) fn record(&self, encoder: &mut wgpu::CommandEncoder, pipes: &TonePipelines, seg: Segment) {
let ops = self.current.as_ref().and_then(|k| self.plans.get(k)).and_then(|p| p.segments.get(seg as usize));
if let Some(ops) = ops {
record(encoder, ops, pipes, &self.stats.texture);
}
}
/// Shadows and Highlights' input (which `camera_raw.wgsl`'s `fs_log` renders) and the last
/// pass's output, before its kept quantile is put back.
pub(crate) fn log(&self) -> Option<(&wgpu::TextureView, &wgpu::TextureView)> {
let p = self.pyramid.as_ref()?;
Some((&p.log_in.view, &p.out.first()?.view))
}
pub(crate) fn stats(&self) -> &wgpu::TextureView {
@@ -680,110 +917,168 @@ impl ToneFrame {
(&self.points.view, self.points_size, self.points_edge)
}
/// Dehaze's transmission and atmospheric light, and the dehazed frame (which `fs_dehaze`
/// renders).
pub(crate) fn haze(&self) -> Option<[&wgpu::TextureView; 3]> {
let h = self.haze.as_ref()?;
Some([&h.guide[2].view, &h.air.view, &h.dehazed.view])
}
/// Uploads Dehaze's copy from `cells` unless the one there has the same `key` (`None` always
/// uploads).
pub(crate) fn upload_cells(&mut self, queue: &wgpu::Queue, key: Option<CellsKey>, cells: impl FnOnce() -> Vec<[f32; 3]>) -> Result<(), Unsupported> {
let Some(h) = self.haze.as_mut() else { return Err(Unsupported("no Dehaze textures".into())) };
if key.is_some() && h.cells_key == key {
return Ok(());
}
let cells = cells();
let [w, hh] = h.size;
if cells.len() as u64 != u64::from(w) * u64::from(hh) {
return Err(Unsupported(format!("{} Dehaze cells for {w}×{hh}", cells.len())));
}
let data: Vec<[f32; 4]> = cells.iter().map(|c| [c[0], c[1], c[2], 1.0]).collect();
queue.write_texture(
wgpu::TexelCopyTextureInfo { texture: &h.cells.texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
bytemuck::cast_slice(&data),
wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(w * 16), rows_per_image: Some(hh) },
wgpu::Extent3d { width: w, height: hh, depth_or_array_layers: 1 },
);
h.cells_key = key;
Ok(())
}
/// Forgets which copy Dehaze's texture holds (after a failed develop).
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn forget_cells(&mut self) {
if let Some(h) = self.haze.as_mut() {
h.cells_key = None;
}
}
/// The clipped luminance (which `fs_luma` renders), Clarity's coefficients and Texture's blur.
pub(crate) fn detail(&self) -> Option<(&wgpu::TextureView, Option<&wgpu::TextureView>, Option<&wgpu::TextureView>)> {
let d = self.detail.as_ref()?;
Some((&d.lc.view, d.sub.as_ref().map(|(_, t)| &t[0].view), d.blur.as_ref().map(|t| &t[1].view)))
}
/// 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 mut bounds = [0usize; 3];
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;
// Dehaze's atmospheric light and transmission, from the uploaded copy.
if let (Some([r, gr, top]), Some(hz)) = (key.dehaze, &self.haze) {
let s = hz.size;
let n = s[0] * s[1];
// The dark channel: each cell's darkest channel, minimum filtered.
b.filter(Pipe::Min, s, s, [0, r, 1, 0], &hz.cells, None, &hz.min);
b.filter(Pipe::Min, s, s, [1, r, 0, 0], &hz.min, None, &hz.dark);
// The light: the cells of its `top` largest values, ties in the cells' order, which a
// second selection over that order finds.
b.select(&hz.dark.view, s, false, None, [[n.saturating_sub(top), 0, 0, 0], [0; 4]], HAZE_SLOT, &hz.chain, &self.state);
b.filter(Pipe::HazeRank, s, s, [0, HAZE_SLOT, 0, 0], &hz.dark, None, &hz.order);
b.select(&hz.order.view, s, false, None, [[top.saturating_sub(1), 0, 0, 0], [0; 4]], TIE_SLOT, &hz.chain, &self.state);
let mut tiles = Step::sized(hz.tiles_size, s);
tiles.sizes2[3] = COUNT_TILE;
tiles.misc = [0, TIE_SLOT, 0, top];
b.draw(Pipe::Air, tiles, Reads { a: v(&hz.order), b: v(&hz.cells), ..Default::default() }, &[&hz.tiles.view], None);
b.filter(Pipe::Air, [1, 1], hz.tiles_size, [1, 0, 0, DEHAZE_AIR_FLOOR.to_bits()], &hz.tiles, None, &hz.air);
// The transmission: the dark channel of the cells over the light, minimum filtered,
// then guided by their luminance.
b.filter(Pipe::Min, s, s, [0, r, 2, 0], &hz.cells, Some(&hz.air), &hz.min);
b.filter(Pipe::MinPack, s, s, [1, r, 3, DEHAZE_OMEGA.to_bits()], &hz.min, Some(&hz.cells), &hz.guide[0]);
b.guided(s, gr, DEHAZE_EPS, &hz.guide, true);
}
bounds[0] = b.ops.len();
if let Some(py) = &self.pyramid {
let n = py.levels.len();
let count = full[0] * full[1];
let cells = py.cells_size[0] * py.cells_size[1];
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 { &py.log_in } else { &py.input };
let level = |l: usize| if l == 0 { input } else { &py.gauss[l] };
// The input's Gaussian pyramid.
for l in 0..n - 1 {
b.draw(
Pipe::Down,
Step::sized(py.levels[l + 1], py.levels[l]),
Reads { a: v(level(l)), ..Default::default() },
&[&py.gauss[l + 1].view],
None,
);
}
// Its range, the lowest reference, the kept quantile and the highest reference.
let mut step = Step::sized(py.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() }, &[&py.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((&py.cells.view, py.cells_size)), ranks, slot_in, &py.full, &self.state);
// The remapped pyramids.
let mut step = Step::sized(py.levels[1], full);
step.sizes2[2] = py.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);
b.draw(Pipe::DownRemap, step, Reads { a: v(input), ..Default::default() }, &[&py.atlas[1].view], None);
for l in 1..n - 1 {
let mut step = Step::sized(py.levels[l + 1], py.levels[l]);
step.sizes2[2] = py.cols;
step.misc = [i, slot_in, 0, 0];
b.draw(Pipe::DownAtlas, step, Reads { fine: v(&py.atlas[l]), ..Default::default() }, &[&py.atlas[l + 1].view], None);
}
// The output, coarse to fine.
for l in (0..n - 1).rev() {
let mut step = Step::sized(py.levels[l], py.levels[l + 1]);
step.sizes2[2] = py.cols;
step.misc = [i, slot_in, u32::from(l == 0), 0];
let coarse = if l == n - 2 { &py.gauss[n - 1] } else { &py.out[l + 1] };
let reads = Reads {
a: v(level(l)),
b: v(coarse),
fine: if l > 0 { v(&py.atlas[l]) } else { None },
coarse: v(&py.atlas[l + 1]),
..Default::default()
};
b.draw(Pipe::Lap, step, reads, &[&py.out[l].view], None);
}
b.select(&py.out[0].view, full, false, None, [[rank(count, keep), 0, 0, 0], [0; 4]], slot_out, &py.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(&py.out[0]), ..Default::default() }, &[&py.input.view], None);
}
}
}
let split = b.ops.len();
bounds[1] = b.ops.len();
// Clarity's coefficients and Texture's blur, from the luminance of `fs_luma`.
if let Some(d) = &self.detail {
if let (Some([s, rs]), Some((size, sub))) = (key.clarity, &d.sub) {
let mut step = Step::sized(*size, full);
step.sizes2[3] = s;
b.draw(Pipe::Block, step, Reads { a: v(&d.lc), ..Default::default() }, &[&sub[0].view], None);
b.guided(*size, rs, CLARITY_EPS, sub, false);
}
if let Some(blur) = &d.blur {
let mut from = &d.lc;
for &r in &key.texture {
b.filter(Pipe::BoxPlane, full, full, [0, r, 0, 0], from, None, &blur[0]);
b.filter(Pipe::BoxPlane, full, full, [1, r, 0, 0], &blur[0], None, &blur[1]);
from = &blur[1];
}
}
}
bounds[2] = 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;
@@ -801,9 +1096,11 @@ impl ToneFrame {
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 }
let (steps, mut ops) = b.finish(device, queue, pipes, &self.stats.view);
let whites_blacks = ops.split_off(bounds[2].min(ops.len()));
let detail = ops.split_off(bounds[1].min(ops.len()));
let tone = ops.split_off(bounds[0].min(ops.len()));
Plan { _steps: steps, segments: [ops, tone, detail, whites_blacks] }
}
}
+3 -3
View File
@@ -36,8 +36,8 @@
//! callers fall back to the CPU compositor.
//!
//! [`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.
//! Camera Raw's develop for the dialog's preview (every stage but Detail), 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)]
@@ -61,7 +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 camera_raw_tone::{CAMERA_RAW_FILTERS_SHADER, CAMERA_RAW_TONE_SHADER};
pub use health::{DeviceHealth, Fault};
pub use plan::{Kernel, Plan, Role, Unsupported, plan};
pub use timing::{GpuTimer, GpuTiming};
+135 -16
View File
@@ -323,7 +323,7 @@ fn every_per_pixel_stage_at_once() {
}
#[test]
fn identity_leaves_pixels_alone_and_spatial_settings_have_no_pass() {
fn identity_leaves_pixels_alone_and_detail_has_no_pass() {
let Some(mut g) = gpu() else { return };
let p = CameraRaw::default();
let src = image(64, 32, Depth::Float);
@@ -331,20 +331,24 @@ fn identity_leaves_pixels_alone_and_spatial_settings_have_no_pass() {
let out = g.dev.develop(&g.device, &g.queue, None, &src, Some(1), [64, 32], &stages).unwrap();
assert_eq!(out, src, "the CPU develop returns early, unclipped");
for spatial in [
CameraRaw { dehaze: 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() },
CameraRaw { noise_luminance: 10.0, ..Default::default() },
CameraRaw { noise_color: 10.0, ..Default::default() },
CameraRaw { noise_luminance: 10.0, clarity: 20.0, ..Default::default() },
CameraRaw { noise_color: 10.0, dehaze: 20.0, ..Default::default() },
] {
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, unless Shadows and Highlights measure them.
// Whites and Blacks need the image's points, unless a spatial stage's passes 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]));
for p in [
CameraRaw { blacks: -10.0, dehaze: 20.0, ..Default::default() },
CameraRaw { blacks: -10.0, clarity: 20.0, ..Default::default() },
CameraRaw { blacks: -10.0, texture: 20.0, ..Default::default() },
] {
let s = per_pixel(&p, 64, 32, false, None).unwrap();
assert!(s.whites_blacks.is_none() && s.measure_whites_blacks == Some([0.0, -10.0]), "{p:?}");
}
// 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());
// At 2 pixels on the short side the pass's pyramid has one level: the CPU's too.
@@ -394,14 +398,7 @@ fn shadows_and_highlights() {
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}");
}
assert_moves(&sets);
check("shadows/highlights", &sets);
}
@@ -473,3 +470,125 @@ fn shadows_and_highlights_with_per_pixel_stages() {
eprintln!("shadows/highlights + per pixel 858x572 {depth:?}: max |GPU - CPU| = {d:.2e}");
}
}
/// Asserts that each of `sets` moves some pixel of the test image by over 2 %, so a comparison
/// with the CPU can't pass trivially.
fn assert_moves(sets: &[CameraRaw]) {
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}");
}
}
#[test]
fn clarity_texture_and_dehaze() {
let sets = [
CameraRaw { clarity: 50.0, ..Default::default() },
CameraRaw { clarity: -80.0, ..Default::default() },
CameraRaw { texture: 50.0, ..Default::default() },
CameraRaw { texture: -70.0, pixel_scale: 0.143, ..Default::default() },
CameraRaw { dehaze: 40.0, ..Default::default() },
CameraRaw { dehaze: 100.0, ..Default::default() },
CameraRaw { dehaze: -60.0, ..Default::default() },
// With Contrast, which then runs after them on the same luminance.
CameraRaw { clarity: 40.0, texture: 30.0, contrast: -35.0, ..Default::default() },
CameraRaw { dehaze: 30.0, clarity: 45.0, texture: -40.0, contrast: 20.0, ..Default::default() },
CameraRaw { dehaze: -30.0, clarity: -25.0, texture: 60.0, encoding_gamma: 1.8, ..Default::default() },
];
assert_moves(&sets);
check("clarity/texture/dehaze", &sets);
}
#[test]
fn clarity_texture_and_dehaze_with_shadows_highlights_and_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,
dehaze: 35.0,
shadows: 45.0,
highlights: -55.0,
clarity: 40.0,
texture: 30.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()
};
let sets = [
all.clone(),
CameraRaw { dehaze: 50.0, shadows: 60.0, highlights: -40.0, ..Default::default() },
CameraRaw { clarity: 60.0, texture: 50.0, shadows: 40.0, ..Default::default() },
// Whites and Blacks measured after them, without Shadows and Highlights, both directions.
CameraRaw { dehaze: 40.0, whites: 60.0, blacks: -40.0, ..Default::default() },
CameraRaw { clarity: 50.0, whites: -50.0, blacks: 45.0, exposure: -0.3, ..Default::default() },
CameraRaw { texture: -60.0, whites: 30.0, blacks: -60.0, ..Default::default() },
];
check("clarity/texture/dehaze + shadows/highlights + per pixel", &sets);
let Some(mut g) = gpu() else { return };
// At the dialog's proxy size (Dehaze and Clarity on a copy subsampled twice), and wider (three
// times).
for size in [(858, 572), (1600, 900)] {
for depth in DEPTHS {
let d = compare_at(&mut g, &all, depth, size);
eprintln!("everything {size:?} {depth:?}: max |GPU - CPU| = {d:.2e}");
}
}
}
#[test]
fn clarity_texture_and_dehaze_on_tiny_and_odd_frames() {
let Some(mut g) = gpu() else { return };
let p = CameraRaw { dehaze: 45.0, clarity: 50.0, texture: 60.0, whites: 20.0, blacks: -20.0, ..Default::default() };
// Without Shadows and Highlights even 1 and 2 pixel frames develop on the GPU.
for size in [(1, 1), (2, 2), (40, 2), (3, 3), (5, 3), (37, 23), (300, 7)] {
for depth in DEPTHS {
let d = compare_at(&mut g, &p, depth, size);
eprintln!("clarity/texture/dehaze {size:?} {depth:?}: max |GPU - CPU| = {d:.2e}");
}
}
// Texture's blur on a small proxy is too narrow to change anything; the stage still runs.
let narrow = CameraRaw { texture: 80.0, contrast: 10.0, pixel_scale: 0.1, ..Default::default() };
assert!(per_pixel(&narrow, 64, 48, true, None).and_then(|s| s.texture).is_some_and(|t| t.radii.is_empty()));
for depth in DEPTHS {
compare_at(&mut g, &narrow, depth, (64, 48));
}
// A flat frame: no haze to find, no detail to raise.
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 dehaze_remakes_its_copy_when_the_white_balance_changes() {
let Some(mut g) = gpu() else { return };
let src = image(858, 572, Depth::Eight);
// Same source key throughout: the copy is cached by it and by the white balance.
for temperature in [25.0, -40.0, -40.0, 0.0] {
let p = CameraRaw { dehaze: 50.0, temperature, ..Default::default() };
let mut cpu = src.clone();
develop(&mut cpu, 858, 572, &p, false);
let stages = per_pixel(&p, 858, 572, false, None).unwrap();
let out = g.dev.develop(&g.device, &g.queue, None, &src, Some(3), [858, 572], &stages).unwrap();
let d = out.iter().zip(&cpu).flat_map(|(a, b)| (0..3).map(move |c| (a[c] - b[c]).abs())).fold(0.0f32, f32::max);
assert!(d <= TOL, "temperature {temperature}: off by {d}");
}
}
+28 -17
View File
@@ -1,12 +1,12 @@
//! 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
//! Camera Raw's preview develop on the GPU (#6916). When the settings don't use Detail
//! (sharpening, noise reduction), 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.
//! histogram, scopes and display conversion. 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.
//! The pipelines build on a thread the first time a dialog opens (DX12's shader compiler takes
//! about a second, #6419); frames develop on the CPU until they are ready.
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
@@ -118,11 +118,11 @@ 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 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.
/// Develops `px` (`w × h`) with `p`, or `None` when the CPU must: Detail or Calibration, 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<u64>, w: usize, h: usize, p: &CameraRaw, float: bool) -> Option<Vec<[f32; 4]>> {
if p.is_identity() || self.failed.load(Ordering::Relaxed) || !self.health.is_ok() {
return None;
@@ -150,8 +150,8 @@ 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.
/// The image's black and white points for Whites and Blacks, measured on the CPU. With a
/// spatial stage the GPU measures them after it instead.
#[cfg(not(target_arch = "wasm32"))]
fn points(&self, px: &[[f32; 4]], key: Option<u64>, w: usize, h: usize, p: &CameraRaw) -> Option<(f32, f32)> {
if (p.whites == 0.0 && p.blacks == 0.0) || p.spatial() {
@@ -265,9 +265,20 @@ mod tests {
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);
// So do Dehaze, Clarity and Texture, with Whites and Blacks measured after them.
for spatial in [
CameraRaw { clarity: 30.0, texture: 25.0, dehaze: 20.0, ..toned.clone() },
CameraRaw { dehaze: -25.0, ..per_pixel.clone() },
CameraRaw { clarity: -40.0, texture: 35.0, ..per_pixel.clone() },
] {
let (backend, gpu, cpu) = developed(&mut app, &ctx, spatial.clone());
assert_eq!(backend, "gpu", "{depth}-bit, {spatial:?}");
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, {spatial:?}: off by {worst}");
}
// Detail develops the whole frame on the CPU.
for detail in [CameraRaw { sharpen_amount: 40.0, ..toned.clone() }, CameraRaw { noise_luminance: 30.0, dehaze: 20.0, ..per_pixel.clone() }] {
let (backend, shown, cpu) = developed(&mut app, &ctx, detail);
assert_eq!((backend, shown == cpu), ("cpu", true), "{depth}-bit");
}
// A device fault: the CPU, from the next frame on.
+3 -2
View File
@@ -1,6 +1,6 @@
# Hardware parity
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-17 · **Change:** minor (Camera Raw's preview develops Shadows and Highlights on the GPU) · **Target:** Adobe Photoshop 2026
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-17 · **Change:** minor (Camera Raw's preview develops Dehaze, Clarity and Texture 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
@@ -19,7 +19,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 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 |
| 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, Shadows and Highlights (the local Laplacian filter) as fragment passes in front of it, 8.7-10.6 ms vs 147-300 ms, and Dehaze, Clarity and Texture (box, minimum and guided filters) as fragment passes too, 3.5-7.2 ms vs 10-30 ms each; with all of them and every per-pixel stage 19-24 ms vs 630-690 ms. 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 |
@@ -65,4 +65,5 @@ HDR display to verify.
| 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-17 | minor | GPU filters: Camera Raw's preview, Dehaze, Clarity and Texture (#6916 step 3) |
| 2026-10-19 | minor | Graphics Adapter choice on Linux (#1885) |