From 976919707a294f2a8d80f112988118d3485bf81a Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 22 Nov 2026 15:05:39 -0500 Subject: [PATCH] algo: delegate Camera Raw Filter to craft_develop::camera_raw (#587) (#16444) * algo: delegate Camera Raw Filter to craft_develop::camera_raw (#587) * algo/camera_raw: put spatial module re-exports in pub mod spatial * algo/camera_raw: put spatial module re-exports in pub mod spatial * algo/photo_util: gate hash01 and bilinear to cfg(test) --- Cargo.lock | 35 +- Cargo.toml | 4 +- crates/algo/src/camera_raw.rs | 1386 ++----------------- crates/algo/src/camera_raw/local_tone.rs | 658 --------- crates/algo/src/camera_raw/per_pixel.rs | 284 ---- crates/algo/src/camera_raw/spatial.rs | 191 --- crates/algo/src/camera_raw/whites_blacks.rs | 494 ------- crates/algo/src/photo_util.rs | 2 + 8 files changed, 171 insertions(+), 2883 deletions(-) delete mode 100644 crates/algo/src/camera_raw/local_tone.rs delete mode 100644 crates/algo/src/camera_raw/per_pixel.rs delete mode 100644 crates/algo/src/camera_raw/spatial.rs delete mode 100644 crates/algo/src/camera_raw/whites_blacks.rs diff --git a/Cargo.lock b/Cargo.lock index c85fe08a08..fcefc9508b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1504,7 +1504,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7631ed550ef6b1abcc90a095dd7338e1b2c67c26#7631ed550ef6b1abcc90a095dd7338e1b2c67c26" +source = "git+https://github.com/storytold/craft-libs?rev=22a80f2965469c633518f4779d7b414ac15dd5f3#22a80f2965469c633518f4779d7b414ac15dd5f3" dependencies = [ "md-5", "rayon", @@ -1527,7 +1527,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea20789 [[package]] name = "craft-color" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7631ed550ef6b1abcc90a095dd7338e1b2c67c26#7631ed550ef6b1abcc90a095dd7338e1b2c67c26" +source = "git+https://github.com/storytold/craft-libs?rev=22a80f2965469c633518f4779d7b414ac15dd5f3#22a80f2965469c633518f4779d7b414ac15dd5f3" dependencies = [ "serde", ] @@ -1535,9 +1535,9 @@ dependencies = [ [[package]] name = "craft-color-transform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7631ed550ef6b1abcc90a095dd7338e1b2c67c26#7631ed550ef6b1abcc90a095dd7338e1b2c67c26" +source = "git+https://github.com/storytold/craft-libs?rev=22a80f2965469c633518f4779d7b414ac15dd5f3#22a80f2965469c633518f4779d7b414ac15dd5f3" dependencies = [ - "craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7631ed550ef6b1abcc90a095dd7338e1b2c67c26)", + "craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=22a80f2965469c633518f4779d7b414ac15dd5f3)", "craft-color", "serde", ] @@ -1590,7 +1590,7 @@ dependencies = [ [[package]] name = "craft-crw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7631ed550ef6b1abcc90a095dd7338e1b2c67c26#7631ed550ef6b1abcc90a095dd7338e1b2c67c26" +source = "git+https://github.com/storytold/craft-libs?rev=22a80f2965469c633518f4779d7b414ac15dd5f3#22a80f2965469c633518f4779d7b414ac15dd5f3" dependencies = [ "thiserror 2.0.21", ] @@ -1614,24 +1614,25 @@ dependencies = [ [[package]] name = "craft-develop" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7631ed550ef6b1abcc90a095dd7338e1b2c67c26#7631ed550ef6b1abcc90a095dd7338e1b2c67c26" +source = "git+https://github.com/storytold/craft-libs?rev=22a80f2965469c633518f4779d7b414ac15dd5f3#22a80f2965469c633518f4779d7b414ac15dd5f3" dependencies = [ "craft-color", "craft-color-transform", "craft-develop-model", "craft-geom", - "craft-raw 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7631ed550ef6b1abcc90a095dd7338e1b2c67c26)", + "craft-raw 0.1.0 (git+https://github.com/storytold/craft-libs?rev=22a80f2965469c633518f4779d7b414ac15dd5f3)", "rayon", "serde", + "serde_json", ] [[package]] name = "craft-develop-model" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7631ed550ef6b1abcc90a095dd7338e1b2c67c26#7631ed550ef6b1abcc90a095dd7338e1b2c67c26" +source = "git+https://github.com/storytold/craft-libs?rev=22a80f2965469c633518f4779d7b414ac15dd5f3#22a80f2965469c633518f4779d7b414ac15dd5f3" dependencies = [ "craft-geom", - "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7631ed550ef6b1abcc90a095dd7338e1b2c67c26)", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=22a80f2965469c633518f4779d7b414ac15dd5f3)", "miniz_oxide 0.9.1", "serde", "serde_json", @@ -1785,7 +1786,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea20789 [[package]] name = "craft-geom" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7631ed550ef6b1abcc90a095dd7338e1b2c67c26#7631ed550ef6b1abcc90a095dd7338e1b2c67c26" +source = "git+https://github.com/storytold/craft-libs?rev=22a80f2965469c633518f4779d7b414ac15dd5f3#22a80f2965469c633518f4779d7b414ac15dd5f3" dependencies = [ "serde", ] @@ -1969,11 +1970,11 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7631ed550ef6b1abcc90a095dd7338e1b2c67c26#7631ed550ef6b1abcc90a095dd7338e1b2c67c26" +source = "git+https://github.com/storytold/craft-libs?rev=22a80f2965469c633518f4779d7b414ac15dd5f3#22a80f2965469c633518f4779d7b414ac15dd5f3" dependencies = [ "brotli-decompressor 6.3.2", "chrono", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7631ed550ef6b1abcc90a095dd7338e1b2c67c26)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=22a80f2965469c633518f4779d7b414ac15dd5f3)", "quick-xml 0.41.0", "serde", ] @@ -2149,12 +2150,12 @@ dependencies = [ [[package]] name = "craft-raw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7631ed550ef6b1abcc90a095dd7338e1b2c67c26#7631ed550ef6b1abcc90a095dd7338e1b2c67c26" +source = "git+https://github.com/storytold/craft-libs?rev=22a80f2965469c633518f4779d7b414ac15dd5f3#22a80f2965469c633518f4779d7b414ac15dd5f3" dependencies = [ "chrono", - "craft-crw 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7631ed550ef6b1abcc90a095dd7338e1b2c67c26)", - "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7631ed550ef6b1abcc90a095dd7338e1b2c67c26)", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7631ed550ef6b1abcc90a095dd7338e1b2c67c26)", + "craft-crw 0.1.0 (git+https://github.com/storytold/craft-libs?rev=22a80f2965469c633518f4779d7b414ac15dd5f3)", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=22a80f2965469c633518f4779d7b414ac15dd5f3)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=22a80f2965469c633518f4779d7b414ac15dd5f3)", "jxl-oxide", "miniz_oxide 0.9.1", "rayon", @@ -2317,7 +2318,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7631ed550ef6b1abcc90a095dd7338e1b2c67c26#7631ed550ef6b1abcc90a095dd7338e1b2c67c26" +source = "git+https://github.com/storytold/craft-libs?rev=22a80f2965469c633518f4779d7b414ac15dd5f3#22a80f2965469c633518f4779d7b414ac15dd5f3" dependencies = [ "serde", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index 06ecee7964..009a84e8c7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -67,8 +67,8 @@ craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a3 # Camera-field EXIF reader/writer, shared prerequisite craft-libs#1563. craft-metadata = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" } craft-crs = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" } -craft-develop = { git = "https://github.com/storytold/craft-libs", rev = "7631ed550ef6b1abcc90a095dd7338e1b2c67c26" } -craft-develop-model = { git = "https://github.com/storytold/craft-libs", rev = "7631ed550ef6b1abcc90a095dd7338e1b2c67c26" } +craft-develop = { git = "https://github.com/storytold/craft-libs", rev = "22a80f2965469c633518f4779d7b414ac15dd5f3" } +craft-develop-model = { git = "https://github.com/storytold/craft-libs", rev = "22a80f2965469c633518f4779d7b414ac15dd5f3" } # Interface translations: lookup, fallback, CLDR plurals and language names over the craft-i18n # catalogs that `crates/ui-egui/build.rs` embeds from `CRAFT_I18N_DIR` (storytold/craft-i18n, at # the commit in `craft-i18n.rev`). Already in the tree through craft. diff --git a/crates/algo/src/camera_raw.rs b/crates/algo/src/camera_raw.rs index f4fd95340a..eab20f9b7e 100644 --- a/crates/algo/src/camera_raw.rs +++ b/crates/algo/src/camera_raw.rs @@ -1,1266 +1,178 @@ -//! Filter › Camera Raw Filter: a float develop pipeline over RGB pixels. +//! Filter › Camera Raw Filter: thin delegation to [`craft_develop::camera_raw`]. //! -//! Stages, in order (each skipped when its controls are neutral, so defaults are an identity): -//! -//! 1. **White balance and exposure** in linear light (the document's values decoded with the sRGB -//! curve as a perceptual working encoding; encoding is undone exactly at the end). -//! 2. **Dehaze**: K. He, J. Sun, X. Tang, *Single Image Haze Removal Using Dark Channel Prior*, -//! CVPR 2009 (dark channel, atmospheric light from its brightest 0.1 %, transmission refined -//! with the guided filter); negative amounts add haze toward the atmospheric light. -//! 3. **Tone** on luminance with colour ratios kept: Highlights / Shadows as exposure changes -//! weighted by an edge-preserving base layer (guided filter: K. He, J. Sun, X. Tang, *Guided -//! Image Filtering*, ECCV 2010), so local contrast survives; Contrast is an S-curve about -//! middle grey; Clarity (large radius, midtone weighted) and Texture (small radius) add -//! band-pass local contrast. Whites / Blacks follow as Photoshop's Camera Raw applies them: -//! image-adaptive global curves measured on Photoshop 25.4 (see `whites_blacks`). -//! 4. **Presence**: Vibrance (weighted toward less saturated colours) and Saturation. -//! 5. **Tone Curve**: parametric regions (Highlights, Lights, Darks, Shadows with movable splits) -//! then point curves (master and per channel), monotone cubic interpolation (F. Fritsch, -//! R. Carlson, *Monotone Piecewise Cubic Interpolation*, SIAM J. Numer. Anal. 1980). -//! 6. **Color Mixer (HSL)**: eight hue bands (red, orange, yellow, green, aqua, blue, purple, -//! magenta) with hat-function weights on the hue circle. -//! 7. **Color Grading**: shadows / midtones / highlights / global wheels (hue, saturation, -//! luminance) with Blending and Balance. -//! 8. **Detail**: sharpening on luminance (unsharp mask with Detail as halo control and Masking as -//! an edge mask) and noise reduction (luminance by guided filter, colour by chroma blur). -//! 9. **Effects**: post-crop vignette (amount, midpoint, roundness, feather, highlights, -//! style) and grain (amount, size, roughness; position-hashed, deterministic). +//! PhotoCraft keeps its [`craft::imaging::raw::RawDevelopSettings`] (`CameraRaw`) type at the +//! public boundary for UI/command/GPU callers and converts to [`craft_develop::camera_raw::CameraRaw`] +//! before delegating all CPU math, tone mapping, spatial filters, and per-pixel parameter packing +//! to `craft_develop::camera_raw`. -#![allow(clippy::needless_range_loop)] // index loops mirror the maths (pixels × channels) - -// The settings are the framework's: one model, with its validation and identity rules. pub use craft::imaging::raw::{GradeWheel as Wheel, MAX_CURVE_POINTS, RawDevelopSettings as CameraRaw, VignetteStyle as StoredVignetteStyle, validate_curve}; - -// PLAN: `develop`, `per_pixel` and `white_black_points` now take `&DevelopInputs`; their callers outside this set's files need it: -// crates/gpu/tests/it/camera_raw.rs and examples/bench_camera_raw.rs (spatial(p) is a free function now), dialogs-w51's -// camera_raw_gpu.rs `CameraRawGpu::develop` (takes the inputs beside `p`), crates/io/src/camera_raw_xmp.rs (`vignette_style` is the -// framework's `VignetteStyle` enum, not a string). Owner: tools-w28 / dialogs-w51 / the io set. -/// What one develop reads besides the settings. PhotoCraft sets these per job (the proxy's scale, the document's -/// transfer curve), so they are not part of the settings the workspace edits and the commands store. -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct DevelopInputs { - /// Seeds the grain's noise. - pub seed: u32, - /// Pixel-size multiplier for previews on downsampled proxies (radii in px scale by it). - pub pixel_scale: f32, - /// The document's transfer curve: 0 for sRGB's, else the gamma of a power-law space (1.8 for ProPhoto). Whites and - /// Blacks act on light. - pub encoding_gamma: f32, -} - -impl Default for DevelopInputs { - fn default() -> Self { - DevelopInputs { seed: 0, pixel_scale: 1.0, encoding_gamma: 0.0 } - } -} - -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, spatial, white_black_points, +pub use craft_develop::camera_raw::{ + CURVE_LUT, Clarity, Dehaze, DevelopInputs, Grade, Grain, HSL_BANDS, LocalTone, PerPixel, Texture, ToneKind, TonePass, Vignette, VignetteStyle, WB_STEPS, + WhitesBlacks, WhitesBlacksModel, band_weights, calibration_weights, curve_lut, local_tone, migrate_to_develop_settings, quantile_rank, white_balance_gains, 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. -#[derive(Clone, Copy, Debug, PartialEq)] -pub(crate) struct Encoding(f32); +pub mod spatial { + pub use craft_develop::camera_raw::spatial::*; +} -impl Encoding { - pub(crate) fn of(gamma: f32) -> Self { - Encoding(if gamma.is_finite() && gamma > 0.0 { gamma.clamp(0.5, 4.0) } else { 0.0 }) - } - /// A value in this encoding as linear light. - pub(crate) fn decode(self, v: f32) -> f32 { - if self.0 > 0.0 { v.max(0.0).powf(self.0) } else { srgb_to_linear(v) } - } - /// Linear light back into this encoding, the inverse of [`Encoding::decode`]. - pub(crate) fn encode(self, v: f32) -> f32 { - if self.0 > 0.0 { v.max(0.0).powf(1.0 / self.0) } else { linear_to_srgb(v) } +fn to_shared_wheel(w: Wheel) -> craft_develop::camera_raw::Wheel { + craft_develop::camera_raw::Wheel { hue: w.hue, sat: w.sat, lum: w.lum } +} + +fn from_shared_wheel(w: craft_develop::camera_raw::Wheel) -> Wheel { + Wheel { hue: w.hue, sat: w.sat, lum: w.lum } +} + +fn to_shared_style(s: StoredVignetteStyle) -> craft_develop::camera_raw::StoredVignetteStyle { + match s { + StoredVignetteStyle::ColorPriority => craft_develop::camera_raw::StoredVignetteStyle::ColorPriority, + StoredVignetteStyle::PaintOverlay => craft_develop::camera_raw::StoredVignetteStyle::PaintOverlay, + StoredVignetteStyle::HighlightPriority => craft_develop::camera_raw::StoredVignetteStyle::HighlightPriority, } } -fn luma_linear(c: [f32; 3]) -> f32 { - luma(c) -} - -/// Hue band centres of the Color Mixer (degrees). -pub const HSL_BANDS: [f32; 8] = [0.0, 30.0, 60.0, 120.0, 180.0, 240.0, 270.0, 300.0]; - -/// How far a primary turns at Hue ±100 (degrees), as the Color Mixer's hue sliders do. -const CALIBRATION_TURN: f32 = 30.0; - -/// How much of each primary (red, green, blue) a hue is made of: triangular weights around -/// 0°, 120° and 240° that sum to one, so a colour between two primaries follows both. -pub fn calibration_weights(hue: f32) -> [f32; 3] { - let h = hue.rem_euclid(360.0); - let mut w = [0.0f32; 3]; - for (i, centre) in [0.0f32, 120.0, 240.0].iter().enumerate() { - let d = (h - centre).abs().min(360.0 - (h - centre).abs()); - w[i] = (1.0 - d / 120.0).max(0.0); +fn from_shared_style(s: craft_develop::camera_raw::StoredVignetteStyle) -> StoredVignetteStyle { + match s { + craft_develop::camera_raw::StoredVignetteStyle::ColorPriority => StoredVignetteStyle::ColorPriority, + craft_develop::camera_raw::StoredVignetteStyle::PaintOverlay => StoredVignetteStyle::PaintOverlay, + craft_develop::camera_raw::StoredVignetteStyle::HighlightPriority => StoredVignetteStyle::HighlightPriority, } - let sum: f32 = w.iter().sum(); - if sum > 1e-6 { w.map(|v| v / sum) } else { [1.0, 0.0, 0.0] } } -/// The Calibration panel's primaries on one linear-light pixel: its hue turns by the weighted -/// Hue of the primaries it is made of (±100 is ±30°, positive towards the next primary) and its -/// saturation scales by their weighted Saturation (−100 greys it); the luminance is kept, so -/// neutrals are untouched. -fn calibrate(c: [f32; 3], hue: [f32; 3], sat: [f32; 3]) -> [f32; 3] { - let [h, s, v] = rgb_to_hsv(c.map(|x| x.max(0.0))); - if s <= 1e-5 || v <= 1e-6 { - return c; - } - let w = calibration_weights(h); - let (mut dh, mut ds) = (0.0f32, 0.0f32); - for i in 0..3 { - dh += w[i] * hue[i].clamp(-100.0, 100.0); - ds += w[i] * sat[i].clamp(-100.0, 100.0); - } - let nh = h + dh / 100.0 * CALIBRATION_TURN; - let ns = (s * (1.0 + ds / 100.0)).clamp(0.0, 1.0); - let out = hsv_to_rgb(nh, ns, v); - let (l0, l1) = (luma(c), luma(out)); - if l1 > 1e-6 { out.map(|x| x * l0 / l1) } else { out } +fn to_shared(p: &CameraRaw) -> craft_develop::camera_raw::CameraRaw { + let mut s = craft_develop::camera_raw::CameraRaw::default(); + s.temperature = p.temperature; + s.tint = p.tint; + s.exposure = p.exposure; + s.contrast = p.contrast; + s.highlights = p.highlights; + s.shadows = p.shadows; + s.whites = p.whites; + s.blacks = p.blacks; + s.texture = p.texture; + s.clarity = p.clarity; + s.dehaze = p.dehaze; + s.vibrance = p.vibrance; + s.saturation = p.saturation; + s.curve_highlights = p.curve_highlights; + s.curve_lights = p.curve_lights; + s.curve_darks = p.curve_darks; + s.curve_shadows = p.curve_shadows; + s.curve_splits = p.curve_splits; + s.point_curve.clone_from(&p.point_curve); + s.point_curve_red.clone_from(&p.point_curve_red); + s.point_curve_green.clone_from(&p.point_curve_green); + s.point_curve_blue.clone_from(&p.point_curve_blue); + s.hsl_hue = p.hsl_hue; + s.hsl_sat = p.hsl_sat; + s.hsl_lum = p.hsl_lum; + s.grade_shadows = to_shared_wheel(p.grade_shadows); + s.grade_midtones = to_shared_wheel(p.grade_midtones); + s.grade_highlights = to_shared_wheel(p.grade_highlights); + s.grade_global = to_shared_wheel(p.grade_global); + s.grade_blending = p.grade_blending; + s.grade_balance = p.grade_balance; + s.sharpen_amount = p.sharpen_amount; + s.sharpen_radius = p.sharpen_radius; + s.sharpen_detail = p.sharpen_detail; + s.sharpen_masking = p.sharpen_masking; + s.noise_luminance = p.noise_luminance; + s.noise_luminance_detail = p.noise_luminance_detail; + s.noise_color = p.noise_color; + s.noise_color_detail = p.noise_color_detail; + s.grain_amount = p.grain_amount; + s.grain_size = p.grain_size; + s.grain_roughness = p.grain_roughness; + s.vignette_amount = p.vignette_amount; + s.vignette_midpoint = p.vignette_midpoint; + s.vignette_roundness = p.vignette_roundness; + s.vignette_feather = p.vignette_feather; + s.vignette_highlights = p.vignette_highlights; + s.vignette_style = to_shared_style(p.vignette_style); + s.shadow_tint = p.shadow_tint; + s.calibration_hue = p.calibration_hue; + s.calibration_sat = p.calibration_sat; + s } -/// Shadows › Tint on one linear-light pixel: `tint` −1 (green) … 1 (magenta), weighted by how -/// dark the pixel is; the luminance is kept. -fn shadow_tint(c: [f32; 3], tint: f32) -> [f32; 3] { - let l = luma(c).max(0.0); - // Linear 0.18 is middle grey: full strength below it, fading out towards white. - let weight = (1.0 - (l / 0.18).sqrt().min(1.0)).powi(2) * 0.5 + (1.0 - l.min(1.0)).powi(4) * 0.5; - let k = tint * 0.12 * weight * (l + 0.02); - let o = [c[0] + k, c[1] - k, c[2] + k].map(|v| v.max(0.0)); - let l2 = luma(o); - if l2 > 1e-6 { o.map(|v| v * l / l2) } else { o } +fn copy_from_shared(s: &craft_develop::camera_raw::CameraRaw, p: &mut CameraRaw) { + p.temperature = s.temperature; + p.tint = s.tint; + p.exposure = s.exposure; + p.contrast = s.contrast; + p.highlights = s.highlights; + p.shadows = s.shadows; + p.whites = s.whites; + p.blacks = s.blacks; + p.texture = s.texture; + p.clarity = s.clarity; + p.dehaze = s.dehaze; + p.vibrance = s.vibrance; + p.saturation = s.saturation; + p.curve_highlights = s.curve_highlights; + p.curve_lights = s.curve_lights; + p.curve_darks = s.curve_darks; + p.curve_shadows = s.curve_shadows; + p.curve_splits = s.curve_splits; + p.point_curve.clone_from(&s.point_curve); + p.point_curve_red.clone_from(&s.point_curve_red); + p.point_curve_green.clone_from(&s.point_curve_green); + p.point_curve_blue.clone_from(&s.point_curve_blue); + p.hsl_hue = s.hsl_hue; + p.hsl_sat = s.hsl_sat; + p.hsl_lum = s.hsl_lum; + p.grade_shadows = from_shared_wheel(s.grade_shadows); + p.grade_midtones = from_shared_wheel(s.grade_midtones); + p.grade_highlights = from_shared_wheel(s.grade_highlights); + p.grade_global = from_shared_wheel(s.grade_global); + p.grade_blending = s.grade_blending; + p.grade_balance = s.grade_balance; + p.sharpen_amount = s.sharpen_amount; + p.sharpen_radius = s.sharpen_radius; + p.sharpen_detail = s.sharpen_detail; + p.sharpen_masking = s.sharpen_masking; + p.noise_luminance = s.noise_luminance; + p.noise_luminance_detail = s.noise_luminance_detail; + p.noise_color = s.noise_color; + p.noise_color_detail = s.noise_color_detail; + p.grain_amount = s.grain_amount; + p.grain_size = s.grain_size; + p.grain_roughness = s.grain_roughness; + p.vignette_amount = s.vignette_amount; + p.vignette_midpoint = s.vignette_midpoint; + p.vignette_roundness = s.vignette_roundness; + p.vignette_feather = s.vignette_feather; + p.vignette_highlights = s.vignette_highlights; + p.vignette_style = from_shared_style(s.vignette_style); + p.shadow_tint = s.shadow_tint; + p.calibration_hue = s.calibration_hue; + p.calibration_sat = s.calibration_sat; } -/// Camera Raw's Auto for the Light panel: Exposure, Contrast, Highlights, Shadows, Whites and -/// Blacks from the image's luminance histogram (`px` in the document's encoding). A well -/// exposed image gets near-zero settings; a dark one more exposure and lifted shadows; one -/// with a crushed or blown end gets Blacks or Whites back from the edge. The other panels are -/// left alone, as Camera Raw's Auto leaves them. +/// Fills in an automatic tone adjustment from the image's percentiles (`px` in sRGB). pub fn auto_tone(px: &[[f32; 4]], p: &mut CameraRaw) { - if px.is_empty() { - return; - } - let mut lum: Vec = px.iter().map(|q| luma([q[0], q[1], q[2]]).clamp(0.0, 1.0)).collect(); - lum.sort_by(|a, b| a.total_cmp(b)); - let at = |f: f32| lum[((lum.len() - 1) as f32 * f).round() as usize]; - let (black, shadow, median, light, white) = (at(0.001), at(0.1), at(0.5), at(0.9), at(0.999)); - // Exposure: the median towards middle grey (sRGB 0.46), damped so flat scenes aren't - // forced to it. - let median_lin = srgb_to_linear(median).max(1e-4); - p.exposure = (0.6 * (0.18f32 / median_lin).log2()).clamp(-2.0, 2.0); - // Blacks and Whites bring the ends to the edges without clipping more than Camera Raw does. - p.blacks = ((0.04 - black) * 400.0).clamp(-40.0, 40.0); - p.whites = ((0.96 - white) * 300.0).clamp(-40.0, 40.0); - // Shadows up when the darker tenth is crushed, highlights down when the brighter tenth is - // near white. - p.shadows = ((0.25 - shadow) * 200.0).clamp(0.0, 50.0); - p.highlights = ((light - 0.85) * -300.0).clamp(-50.0, 0.0); - // A little contrast for a flat histogram. - let spread = (light - shadow).max(0.0); - p.contrast = ((0.6 - spread) * 60.0).clamp(0.0, 25.0); - // Shown as Camera Raw shows them: Exposure to a hundredth of a stop, the others whole. - p.exposure = (p.exposure * 100.0).round() / 100.0; - for v in [&mut p.blacks, &mut p.whites, &mut p.shadows, &mut p.highlights, &mut p.contrast] { - *v = v.round(); - } -} - -fn luma(c: [f32; 3]) -> f32 { - 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2] -} - -fn smoothstep(e0: f32, e1: f32, x: f32) -> f32 { - let t = ((x - e0) / (e1 - e0)).clamp(0.0, 1.0); - t * t * (3.0 - 2.0 * t) -} - -/// Box mean of a single-channel buffer (radius `r`, edge clamped): rows in parallel, then -/// columns in parallel bands with running column sums (cache-friendly, no transposes). -fn box_mean(v: &[f32], w: usize, h: usize, r: usize) -> Vec { - if r == 0 || w == 0 || h == 0 { - return v.to_vec(); - } - let n = (2 * r + 1) as f64; - let mut tmp = vec![0.0f32; w * h]; - par_rows(&mut tmp, w, 1, |y, row| { - let src = &v[y * w..(y + 1) * w]; - let at = |k: i64| src[k.clamp(0, w as i64 - 1) as usize] as f64; - let mut acc: f64 = (-(r as i64)..=r as i64).map(at).sum(); - for (x, o) in row.iter_mut().enumerate() { - *o = (acc / n) as f32; - acc += at(x as i64 + r as i64 + 1) - at(x as i64 - r as i64); - } - }); - const BAND: usize = 256; - let bands = crate::photo_util::par_map(w.div_ceil(BAND), |b| { - let (x0, x1) = (b * BAND, ((b + 1) * BAND).min(w)); - let bw = x1 - x0; - let row = |y: i64| &tmp[y.clamp(0, h as i64 - 1) as usize * w + x0..y.clamp(0, h as i64 - 1) as usize * w + x1]; - let mut acc = vec![0.0f64; bw]; - for y in -(r as i64)..=r as i64 { - for (a, v) in acc.iter_mut().zip(row(y)) { - *a += *v as f64; - } - } - let mut out = vec![0.0f32; bw * h]; - for y in 0..h { - for (o, a) in out[y * bw..(y + 1) * bw].iter_mut().zip(&acc) { - *o = (*a / n) as f32; - } - let (add, sub) = (row(y as i64 + r as i64 + 1), row(y as i64 - r as i64)); - for ((a, p), m) in acc.iter_mut().zip(add).zip(sub) { - *a += (*p - *m) as f64; - } - } - out - }); - let mut out = vec![0.0f32; w * h]; - for (b, band) in bands.iter().enumerate() { - let (x0, x1) = (b * BAND, ((b + 1) * BAND).min(w)); - let bw = x1 - x0; - for y in 0..h { - out[y * w + x0..y * w + x1].copy_from_slice(&band[y * bw..(y + 1) * bw]); - } - } - out -} - -/// Approximate Gaussian (three box passes). -fn gauss(v: &[f32], w: usize, h: usize, sigma: f32) -> 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 { - let mut out = v.to_vec(); - for &r in radii { - out = box_mean(&out, w, h, r); - } - out -} - -/// Fast guided filter (K. He, J. Sun, *Fast Guided Filter*, arXiv 2015): the linear -/// 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 { - let (s, rs) = spatial::fast_guided_steps(r); - if s == 1 { - return guided(i, p, w, h, r, eps); - } - let (sw, sh) = (w.div_ceil(s), h.div_ceil(s)); - let down = |v: &[f32]| -> Vec { - let mut o = vec![0.0f32; sw * sh]; - let mut c = vec![0.0f32; sw * sh]; - for y in 0..h { - for x in 0..w { - let k = (y / s) * sw + x / s; - o[k] += v[y * w + x]; - c[k] += 1.0; - } - } - o.iter().zip(&c).map(|(a, b)| a / b.max(1.0)).collect() - }; - let (si, sp) = (down(i), down(p)); - let mi = box_mean(&si, sw, sh, rs); - let mp = box_mean(&sp, sw, sh, rs); - let ip: Vec = si.iter().zip(&sp).map(|(a, b)| a * b).collect(); - let ii: Vec = si.iter().map(|a| a * a).collect(); - let mip = box_mean(&ip, sw, sh, rs); - let mii = box_mean(&ii, sw, sh, rs); - let a: Vec = (0..sw * sh).map(|k| (mip[k] - mi[k] * mp[k]) / (mii[k] - mi[k] * mi[k] + eps)).collect(); - let b: Vec = (0..sw * sh).map(|k| mp[k] - a[k] * mi[k]).collect(); - let (ma, mb) = (box_mean(&a, sw, sh, rs), box_mean(&b, sw, sh, rs)); - let mut out = vec![0.0f32; w * h]; - let sf = s as f32; - par_rows(&mut out, w, 1, |y, row| { - let fy = (y as f32 + 0.5) / sf - 0.5; - for (x, o) in row.iter_mut().enumerate() { - let fx = (x as f32 + 0.5) / sf - 0.5; - let av = crate::photo_util::bilinear(&ma, sw, sh, 1, 0, fx, fy); - let bv = crate::photo_util::bilinear(&mb, sw, sh, 1, 0, fx, fy); - *o = av * i[y * w + x] + bv; - } - }); - out -} - -/// Guided filter of `p` guided by `i` (He et al. 2010). -fn guided(i: &[f32], p: &[f32], w: usize, h: usize, r: usize, eps: f32) -> Vec { - let mi = box_mean(i, w, h, r); - let mp = box_mean(p, w, h, r); - let ip: Vec = i.iter().zip(p).map(|(a, b)| a * b).collect(); - let ii: Vec = i.iter().map(|a| a * a).collect(); - let mip = box_mean(&ip, w, h, r); - let mii = box_mean(&ii, w, h, r); - let a: Vec = (0..w * h).map(|k| (mip[k] - mi[k] * mp[k]) / (mii[k] - mi[k] * mi[k] + eps)).collect(); - let b: Vec = (0..w * h).map(|k| mp[k] - a[k] * mi[k]).collect(); - let ma = box_mean(&a, w, h, r); - let mb = box_mean(&b, w, h, r); - (0..w * h).map(|k| ma[k] * i[k] + mb[k]).collect() -} - -/// Monotone cubic (Fritsch–Carlson) through `pts` (x ascending, 0..=1), evaluated into a LUT via -/// [`craft_develop::color::spline::MonotoneCurve`]. -pub fn curve_lut(pts: &[[f32; 2]], n: usize) -> Vec { - // Keep the legacy f32 knot selection; normalizing in f64 can drop a saved knot. - let mut p: Vec<[f32; 2]> = pts.iter().map(|q| [q[0] / 255.0, q[1] / 255.0]).collect(); - p.sort_by(|a, b| a[0].total_cmp(&b[0])); - p.dedup_by(|a, b| (a[0] - b[0]).abs() < 1e-6); - if p.len() < 2 || n < 2 { - return (0..n).map(|k| if n <= 1 { 0.0 } else { k as f32 / (n - 1) as f32 }).collect(); - } - let p: Vec<_> = p.into_iter().map(|[x, y]| (f64::from(x), f64::from(y))).collect(); - craft_develop::color::spline::MonotoneCurve::new(&p).to_lut(n).v.into_iter().map(|v| v.clamp(0.0, 1.0)).collect() -} - -/// Migrate a PhotoCraft Camera Raw / `filter.cameraRaw` settings object to shared -/// [`craft_develop_model::DevelopSettings`], stripping PhotoCraft-only transport keys -/// (`layer`, `encodingGamma`, `__cameraRawPsd`) before delegating to -/// [`craft_develop_model::migration::migrate_camera_raw`]. -pub fn migrate_to_develop_settings( - base: &craft_develop_model::DevelopSettings, - fields: &serde_json::Value, -) -> Result { - let Some(obj) = fields.as_object() else { - return craft_develop_model::migration::migrate_camera_raw(base, fields); - }; - let cleaned: serde_json::Map = - obj.iter().filter(|(k, _)| !matches!(k.as_str(), "layer" | "encodingGamma" | "__cameraRawPsd")).map(|(k, v)| (k.clone(), v.clone())).collect(); - craft_develop_model::migration::migrate_camera_raw(base, &serde_json::Value::Object(cleaned)) -} - -fn lut_eval(lut: &[f32], v: f32) -> f32 { - if !(0.0..=1.0).contains(&v) { - // Extend linearly outside (float documents). - return if v < 0.0 { v + lut[0] } else { lut[lut.len() - 1] + (v - 1.0) }; - } - let x = v * (lut.len() - 1) as f32; - let i = (x as usize).min(lut.len() - 2); - let t = x - i as f32; - lut[i] + (lut[i + 1] - lut[i]) * t -} - -/// Parametric tone curve as a LUT (regions split at `splits`, each slider ±100 moves its region -/// by up to a quarter of the range, smoothly). -fn parametric_lut(p: &CameraRaw, n: usize) -> Vec { - let s = p.curve_splits.map(|v| v.clamp(5.0, 95.0) / 100.0); - let centres = [s[0] / 2.0, (s[0] + s[1]) / 2.0, (s[1] + s[2]) / 2.0, (s[2] + 1.0) / 2.0]; - let amounts = [p.curve_shadows, p.curve_darks, p.curve_lights, p.curve_highlights]; - let widths = [s[0].max(0.1), (s[1] - s[0]).max(0.1), (s[2] - s[1]).max(0.1), (1.0 - s[2]).max(0.1)]; - let mut lut: Vec = (0..n) - .map(|i| { - let x = i as f32 / (n - 1) as f32; - let mut y = x; - for k in 0..4 { - let d = (x - centres[k]) / (widths[k] * 1.2); - let bump = (-d * d * 2.0).exp() * x * (1.0 - x) * 4.0; - y += amounts[k] / 100.0 * 0.25 * bump; - } - y.clamp(0.0, 1.0) - }) - .collect(); - // Keep it monotone. - for i in 1..n { - lut[i] = lut[i].max(lut[i - 1]); - } - lut -} - -fn rgb_to_hsv(c: [f32; 3]) -> [f32; 3] { - let (mx, mn) = (c[0].max(c[1]).max(c[2]), c[0].min(c[1]).min(c[2])); - let d = mx - mn; - let h = if d <= 1e-9 { - 0.0 - } else if mx == c[0] { - 60.0 * (((c[1] - c[2]) / d).rem_euclid(6.0)) - } else if mx == c[1] { - 60.0 * ((c[2] - c[0]) / d + 2.0) - } else { - 60.0 * ((c[0] - c[1]) / d + 4.0) - }; - [h, if mx > 1e-9 { d / mx } else { 0.0 }, mx] -} - -fn hsv_to_rgb(h: f32, s: f32, v: f32) -> [f32; 3] { - let h = h.rem_euclid(360.0) / 60.0; - let c = v * s; - let x = c * (1.0 - ((h % 2.0) - 1.0).abs()); - let (r, g, b) = match h as u32 { - 0 => (c, x, 0.0), - 1 => (x, c, 0.0), - 2 => (0.0, c, x), - 3 => (0.0, x, c), - 4 => (x, 0.0, c), - _ => (c, 0.0, x), - }; - let m = v - c; - [r + m, g + m, b + m] -} - -/// Weights of the eight HSL bands at hue `h` (hat functions between neighbouring centres). -pub fn band_weights(h: f32) -> [f32; 8] { - let mut w = [0.0f32; 8]; - for k in 0..8 { - let (c, prev, next) = (HSL_BANDS[k], HSL_BANDS[(k + 7) % 8], HSL_BANDS[(k + 1) % 8]); - let diff = ((h - c + 540.0) % 360.0) - 180.0; - let span = if diff >= 0.0 { (next - c).rem_euclid(360.0) } else { (c - prev).rem_euclid(360.0) }; - w[k] = (1.0 - diff.abs() / span.max(1e-3)).max(0.0); - } - w -} - -/// Contrast, Highlights, Shadows, Texture and Clarity (the luminance stage) at rest. -fn local_tone_neutral(p: &CameraRaw) -> bool { - [p.contrast, p.highlights, p.shadows, p.texture, p.clarity].iter().all(|v| *v == 0.0) -} - -/// The Color Mixer at rest. -pub(crate) fn hsl_neutral(p: &CameraRaw) -> bool { - p.hsl_hue.iter().chain(&p.hsl_sat).chain(&p.hsl_lum).all(|v| *v == 0.0) -} - -/// Color Grading at rest. -pub(crate) fn grade_neutral(p: &CameraRaw) -> bool { - [&p.grade_shadows, &p.grade_midtones, &p.grade_highlights, &p.grade_global].iter().all(|w| w.sat == 0.0 && w.lum == 0.0) -} - -/// The Calibration panel at rest. -pub(crate) fn calibration_neutral(p: &CameraRaw) -> bool { - p.shadow_tint == 0.0 && p.calibration_hue.iter().chain(&p.calibration_sat).all(|v| *v == 0.0) -} - -/// The Tone Curve panel at rest. -fn curves_neutral(p: &CameraRaw) -> bool { - [p.curve_highlights, p.curve_lights, p.curve_darks, p.curve_shadows].iter().all(|v| *v == 0.0) - && [&p.point_curve, &p.point_curve_red, &p.point_curve_green, &p.point_curve_blue].iter().all(|c| is_linear(c)) -} - -fn is_linear(c: &[[f32; 2]]) -> bool { - c.len() < 2 || c.iter().all(|p| (p[0] - p[1]).abs() < 1e-3) -} - -/// Camera Raw's white-balance channel gains for Temperature / Tint (−100…100), relative to the -/// as-shot balance: warmer raises red and lowers blue (±35 % at the ends); a negative tint -/// raises green, a positive one lowers it toward magenta (±25 %). An observed approximation of -/// Adobe Camera Raw's sliders, not a colour-temperature model; shared by the filter (in linear -/// RGB) and the raw open (on the camera's white-balance multipliers) so both agree. -pub fn white_balance_gains(temperature: f32, tint: f32) -> [f32; 3] { - let t = temperature / 100.0; - let tn = tint / 100.0; - [1.0 + 0.35 * t, 1.0 - 0.25 * tn, 1.0 - 0.35 * t] + let mut s = to_shared(p); + craft_develop::camera_raw::auto_tone(px, &mut s); + copy_from_shared(&s, p); } /// Runs the Camera Raw pipeline on straight RGBA pixels (`w × h`, display-encoded RGB). -/// `float` keeps values above 1 (32-bit documents). `inputs` are the job's scale, grain seed and encoding. pub fn develop(px: &mut [[f32; 4]], w: usize, h: usize, p: &CameraRaw, inputs: &DevelopInputs, float: bool) { - if px.is_empty() || p.is_identity() { - return; - } - let ps = inputs.pixel_scale.clamp(0.01, 1.0); - // 1. White balance + exposure in linear light. - if let Some(g) = per_pixel::gains(p) { - par_rows(px, w, 1, |_, row| { - for q in row.iter_mut() { - *q = balance(*q, g); - } - }); - } - // 1b. Calibration: the primaries turned and purer or greyer, and the shadows tinted, in - // linear light (the camera's primaries are what Camera Raw's panel calibrates). - if !calibration_neutral(p) { - let primaries = p.calibration_hue.iter().chain(&p.calibration_sat).any(|v| *v != 0.0); - let tint = p.shadow_tint.clamp(-100.0, 100.0) / 100.0; - par_rows(px, w, 1, |_, row| { - for q in row.iter_mut() { - let c = [srgb_to_linear(q[0]), srgb_to_linear(q[1]), srgb_to_linear(q[2])]; - let mut o = if primaries { calibrate(c, p.calibration_hue, p.calibration_sat) } else { c }; - if tint != 0.0 { - o = shadow_tint(o, tint); - } - for k in 0..3 { - q[k] = linear_to_srgb(o[k].max(0.0)); - } - } - }); - } - // 2. Dehaze. - 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 { - local_tone::apply(px, w, h, p.shadows, p.highlights, Encoding::of(inputs.encoding_gamma)); - } - if !local_tone_neutral(p) && [p.contrast, p.texture, p.clarity].iter().any(|v| *v != 0.0) { - let l: Vec = px.iter().map(|q| luma([q[0], q[1], q[2]]).max(0.0)).collect(); - let lc: Vec = l.iter().map(|v| v.min(1.0)).collect(); - let clarity = Clarity::new(p, w, h); - let texture = Texture::new(p, inputs, 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), Some(k)) = (&clar, &clarity) { - let mw = 1.0 - (2.0 * lv.clamp(0.0, 1.0) - 1.0).powi(2); - lv += k.amount * (lc[i] - c[i]) * mw; - } - 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); - } - }); - } - // 3b. Whites and Blacks: global curves adapted to the image's black and white points. - if p.whites != 0.0 || p.blacks != 0.0 { - let enc = Encoding::of(inputs.encoding_gamma); - let (bp, wp) = luminance_points(px, w, h, enc, |q| q); - let (xw, xb) = whites_blacks::amounts(p.whites.clamp(-100.0, 100.0), p.blacks.clamp(-100.0, 100.0), bp, wp); - whites_blacks::apply(px, w, xw, xb, enc); - } - // 4–7: per-pixel colour stages. - let need_color = p.vibrance != 0.0 || p.saturation != 0.0 || !curves_neutral(p) || !hsl_neutral(p) || !grade_neutral(p); - if need_color { - let par = (!(p.curve_highlights == 0.0 && p.curve_lights == 0.0 && p.curve_darks == 0.0 && p.curve_shadows == 0.0)).then(|| parametric_lut(p, 1024)); - let pts = |c: &Vec<[f32; 2]>| (!is_linear(c)).then(|| curve_lut(c, 1024)); - let (master, cr, cg, cb) = (pts(&p.point_curve), pts(&p.point_curve_red), pts(&p.point_curve_green), pts(&p.point_curve_blue)); - let hsl = !hsl_neutral(p); - let grade = !grade_neutral(p); - let Grade { tints, lums, blend, balance: bal } = Grade::new(p); - par_rows(px, w, 1, |_, row| { - for q in row.iter_mut() { - let mut c = [q[0], q[1], q[2]]; - if p.vibrance != 0.0 || p.saturation != 0.0 { - let l = luma(c); - let (mx, mn) = (c[0].max(c[1]).max(c[2]), c[0].min(c[1]).min(c[2])); - let sat = if mx > 1e-6 { (mx - mn) / mx } else { 0.0 }; - // Vibrance protects skin-ish hues (oranges) a little, like ACR. - let hue = rgb_to_hsv(c)[0]; - let skin = (1.0 - ((hue - 25.0).abs() / 25.0)).clamp(0.0, 1.0) * 0.5; - let k = 1.0 + p.saturation / 100.0 + p.vibrance / 100.0 * (1.0 - sat) * (1.0 - skin); - c = c.map(|v| l + (v - l) * k.max(0.0)); - } - if let Some(lut) = &par { - c = c.map(|v| lut_eval(lut, v)); - } - if let Some(lut) = &master { - c = c.map(|v| lut_eval(lut, v)); - } - for (ch, lut) in [&cr, &cg, &cb].iter().enumerate() { - if let Some(lut) = lut { - c[ch] = lut_eval(lut, c[ch]); - } - } - if hsl { - let [hh, s, v] = rgb_to_hsv(c.map(|x| x.max(0.0))); - if s > 1e-4 { - let wts = band_weights(hh); - let (mut dh, mut ds, mut dl) = (0.0f32, 0.0f32, 0.0f32); - for k in 0..8 { - dh += wts[k] * p.hsl_hue[k]; - ds += wts[k] * p.hsl_sat[k]; - dl += wts[k] * p.hsl_lum[k]; - } - let nh = hh + dh / 100.0 * 30.0; - let ns = (s * (1.0 + ds / 100.0)).clamp(0.0, 1.0); - let mut out = hsv_to_rgb(nh, ns, v); - // Keep the luminance, then apply the luminance shift weighted by saturation. - let (l0, l1) = (luma(c), luma(out)); - if l1 > 1e-6 { - out = out.map(|x| x * l0 / l1); - } - let k = 2f32.powf(dl / 100.0 * 1.0 * s); - c = out.map(|x| x * k); - } - } - if grade { - let l = luma(c).clamp(0.0, 1.0); - let sh = 1.0 - smoothstep(0.0, 0.5 + bal + blend, l); - let hi = smoothstep(0.5 + bal - blend, 1.0, l); - let mid = (1.0 - sh - hi).max(0.0); - let masks = [sh, mid, hi, 1.0]; - for k in 0..4 { - for ch in 0..3 { - c[ch] += masks[k] * tints[k][ch]; - } - if lums[k] != 0.0 { - let f = 2f32.powf(masks[k] * lums[k] / 100.0 * 0.6); - c = c.map(|x| x * f); - } - } - } - q[0] = c[0]; - q[1] = c[1]; - q[2] = c[2]; - } - }); - } - // 8. Detail. - if p.noise_luminance > 0.0 || p.noise_color > 0.0 || p.sharpen_amount > 0.0 { - detail(px, w, h, p, ps); - } - // 9. Effects. - if p.vignette_amount != 0.0 { - vignette(px, w, h, p); - } - if p.grain_amount > 0.0 { - let Grain { cell, roughness: rough, amount: amt, seed, scale: pscale } = Grain::new(p, inputs); - par_rows(px, w, 1, |y, row| { - for (x, q) in row.iter_mut().enumerate() { - // Sample in full-resolution coordinates so previews match the result. - let (fx, fy) = (x as f32 * pscale / cell, y as f32 * pscale / cell); - let n = value_noise(fx, fy, seed) * (1.0 - rough) + (value_noise(fx * 2.3, fy * 2.3, seed + 7) - 0.0) * rough; - let l = luma([q[0], q[1], q[2]]).clamp(0.0, 1.0); - let g = (n - 0.5) * 2.0 * amt * (0.4 + 2.4 * l * (1.0 - l)); - for c in 0..3 { - q[c] += g; - } - } - }); - } - if !float { - for q in px.iter_mut() { - for c in 0..3 { - q[c] = q[c].clamp(0.0, 1.0); - } - } - } + craft_develop::camera_raw::develop(px, w, h, &to_shared(p), inputs, float); } -/// The end of stage 3 on one pixel: Contrast (strength `k_con`) on the luminance `lv` that -/// Clarity and Texture left, then the pixel rescaled to it. `l0` is its luminance, `lc` that -/// clipped to 1. -fn tone(mut q: [f32; 4], l0: f32, lc: f32, mut lv: f32, k_con: f32) -> [f32; 4] { - if k_con != 0.0 { - let tau = std::f32::consts::TAU; - let xx = lv.clamp(0.0, 1.0); - lv += -k_con * (tau * xx).sin() / tau; - } - let lv = lv.max(0.0) + (l0 - lc); - let ratio = if l0 > 1e-5 { lv / l0 } else { 1.0 }; - for c in 0..3 { - q[c] = if l0 > 1e-5 { q[c] * ratio } else { q[c] + (lv - l0) }; - } - q +/// Per-pixel stages packed for the GPU preview pass. +pub fn per_pixel(p: &CameraRaw, inputs: &DevelopInputs, w: usize, h: usize, float: bool, points: Option<(f32, f32)>) -> Option { + craft_develop::camera_raw::per_pixel(&to_shared(p), inputs, w, h, float, points) } -/// Stage 3 on one pixel when Contrast is its only control. -fn contrast(q: [f32; 4], k_con: f32) -> [f32; 4] { - let l0 = luma([q[0], q[1], q[2]]).max(0.0); - let lc = l0.min(1.0); - tone(q, l0, lc, lc, k_con) +/// Whether `p` needs a spatial pass on the GPU (`Dehaze`, `Shadows`/`Highlights`, `Clarity`, `Texture`). +pub fn spatial(p: &CameraRaw) -> bool { + craft_develop::camera_raw::spatial(&to_shared(p)) } -/// Stage 1 on one pixel: white balance and exposure `gains` in linear light. -fn balance(mut q: [f32; 4], g: [f32; 3]) -> [f32; 4] { - for c in 0..3 { - q[c] = linear_to_srgb((srgb_to_linear(q[c]) * g[c]).max(0.0)); - } - q -} - -/// The index of the `q` quantile (0 … 1) among `len` sorted values, as every percentile in the -/// develop picks it. -pub fn quantile_rank(len: usize, q: f32) -> usize { - (len.saturating_sub(1) as f32 * q).round() as usize -} - -/// The image's black and white points as sRGB-encoded grey levels: the 3rd percentile of the -/// luminance and the 99.5th of the brightest channel, on a copy at most 256 pixels across (so a -/// preview proxy and the full image agree). `map` is applied to each pixel first. -fn luminance_points(px: &[[f32; 4]], w: usize, h: usize, enc: Encoding, map: impl Fn([f32; 4]) -> [f32; 4] + Sync) -> (f32, f32) { - let f = w.max(h).div_ceil(whites_blacks::POINTS_SIDE).max(1); - let (sw, sh) = (w.div_ceil(f), h.div_ceil(f)); - // Each band of `f` rows sums into its own row of cells, in the same order as one pass would. - let bands = crate::photo_util::par_map(sh, |sy| { - let mut sum = vec![[0.0f64; 4]; sw]; - for y in sy * f..((sy + 1) * f).min(h) { - for x in 0..w { - let q = map(px[y * w + x]); - let s = &mut sum[x / f]; - for c in 0..3 { - s[c] += f64::from(enc.decode(q[c]).clamp(0.0, 1.0)); - } - s[3] += 1.0; - } - } - sum - }); - let cells: Vec<[f32; 3]> = bands.iter().flatten().filter(|s| s[3] > 0.0).map(|s| [0, 1, 2].map(|c| (s[c] / s[3]) as f32)).collect(); - if cells.is_empty() { - return (0.0, 1.0); - } - let pct = |mut v: Vec, q: f32| { - v.sort_by(f32::total_cmp); - v[quantile_rank(v.len(), q)] - }; - let bp = pct(cells.iter().map(|c| luma(*c)).collect(), whites_blacks::POINT_QUANTILES[0]); - let wp = pct(cells.iter().map(|c| c[0].max(c[1]).max(c[2])).collect(), whites_blacks::POINT_QUANTILES[1]); - (linear_to_srgb(bp), linear_to_srgb(wp)) -} - -fn value_noise(x: f32, y: f32, seed: u64) -> f32 { - let (xi, yi) = (x.floor(), y.floor()); - let (tx, ty) = (x - xi, y - yi); - let (sx, sy) = (tx * tx * (3.0 - 2.0 * tx), ty * ty * (3.0 - 2.0 * ty)); - let h = |dx: i64, dy: i64| hash01(xi as i64 + dx, yi as i64 + dy, seed); - let top = h(0, 0) + (h(1, 0) - h(0, 0)) * sx; - let bot = h(0, 1) + (h(1, 1) - h(0, 1)) * sx; - top + (bot - top) * sy -} - -/// 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; - } - } - small.iter().zip(&cnt).map(|(s, c)| s.map(|v| v / c.max(1.0))).collect::>() - }); - 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 { - let mut a = vec![0.0f32; sw * sh]; - for y in 0..sh { - for x in 0..sw { - let (x0, x1) = (x.saturating_sub(r), (x + r).min(sw - 1)); - a[y * sw + x] = (x0..=x1).map(|xx| v[y * sw + xx]).fold(start, pick); - } - } - let mut b = vec![0.0f32; sw * sh]; - for y in 0..sh { - for x in 0..sw { - let (y0, y1) = (y.saturating_sub(r), (y + r).min(sh - 1)); - b[y * sw + x] = (y0..=y1).map(|yy| a[yy * sw + x]).fold(start, pick); - } - } - b - }; - 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::>()); - // Atmospheric light: mean colour of the brightest 0.1 % of the dark channel (ties in the - // order of the cells). - let mut idx: Vec = (0..sw * sh).collect(); - idx.sort_by(|&a, &b| dark[b].total_cmp(&dark[a])); - 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(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::>()); - // 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 ω weight is scaled to keep the slider's overall strength. - let opened = rank_filter(&norm_dark, f32::MIN, f32::max); - // Summed in f64: an f32 running sum over the copy's few hundred thousand cells drifts by about - // 1e-5, which the low transmission beside haze multiplies up to a visible fraction of a level. - let mean = |v: &[f32]| (v.iter().map(|x| f64::from(*x)).sum::() / v.len().max(1) as f64) as f32; - let weight = spatial::DEHAZE_OMEGA * mean(&norm_dark) / mean(&opened).max(1e-6); - let t_raw: Vec = opened.iter().map(|d| 1.0 - weight * d).collect(); - let guide: Vec = small.iter().map(|c| luma(*c)).collect(); - 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(spatial::DEHAZE_T_FLOOR, 1.0); - for c in 0..3 { - let i = q[c]; - let j = (i - air[c]) / tv + air[c]; - q[c] = if amount >= 0.0 { i + (j - i) * amount } else { i + (air[c] - i) * (-amount) * 0.5 * (1.0 - tv * 0.5) }; - } - } - }); -} - -fn detail(px: &mut [[f32; 4]], w: usize, h: usize, p: &CameraRaw, ps: f32) { - // The controls' documented 0..=100 range: raw values drive the filter radii below. - let [nl, nld, nc, ncd] = [p.noise_luminance, p.noise_luminance_detail, p.noise_color, p.noise_color_detail].map(|v| v.clamp(0.0, 100.0)); - // Work in Y + chroma (BT.709 luma, B−Y, R−Y). - let mut y: Vec = px.iter().map(|q| luma([q[0], q[1], q[2]])).collect(); - let mut cb: Vec = px.iter().zip(&y).map(|(q, l)| q[2] - l).collect(); - let mut cr: Vec = px.iter().zip(&y).map(|(q, l)| q[0] - l).collect(); - if nl > 0.0 { - let n = nl / 100.0; - let r = ((1.0 + 3.0 * n) * ps).round().max(1.0) as usize; - let smooth = guided(&y, &y, w, h, r, (n * 0.06).powi(2) + 1e-6); - let keep = nld / 100.0 * 0.5; - for i in 0..w * h { - y[i] = smooth[i] + (y[i] - smooth[i]) * keep; - } - } - if nc > 0.0 { - let sigma = (nc / 100.0 * 6.0 * ps).max(0.3); - let (bcb, bcr) = (gauss(&cb, w, h, sigma), gauss(&cr, w, h, sigma)); - let keep = ncd / 100.0 * 0.3; - for i in 0..w * h { - cb[i] = bcb[i] + (cb[i] - bcb[i]) * keep; - cr[i] = bcr[i] + (cr[i] - bcr[i]) * keep; - } - } - if p.sharpen_amount > 0.0 { - let sigma = (p.sharpen_radius.clamp(0.5, 3.0) * ps).max(0.3); - let blur = gauss(&y, w, h, sigma); - // Masking: an edge mask from the gradient of a smoothed luminance. - let mask: Option> = (p.sharpen_masking > 0.0).then(|| { - let s = gauss(&y, w, h, 1.0 * ps.max(0.5)); - let t = p.sharpen_masking / 100.0 * 0.08; - crate::photo_util::par_map(w * h, |i| { - let (x, yy) = (i % w, i / w); - let gx = s[yy * w + (x + 1).min(w - 1)] - s[yy * w + x.saturating_sub(1)]; - let gy = s[(yy + 1).min(h - 1) * w + x] - s[yy.saturating_sub(1) * w + x]; - smoothstep(t * 0.5, t + 1e-4, gx.hypot(gy)) - }) - }); - let amt = p.sharpen_amount / 100.0 * 1.2; - let det = p.sharpen_detail / 100.0; - for i in 0..w * h { - let hp = y[i] - blur[i]; - // Low Detail damps large (halo-producing) differences. - let limit = 0.03 + det * 0.3; - let hp = hp.clamp(-limit, limit) * (0.5 + 0.5 * det); - let m = mask.as_ref().map_or(1.0, |m| m[i]); - y[i] += amt * hp * m; - } - } - for i in 0..w * h { - let (l, b, r) = (y[i], cb[i], cr[i]); - let (rr, bb) = (r + l, b + l); - let g = (l - 0.2126 * rr - 0.0722 * bb) / 0.7152; - px[i][0] = rr; - px[i][1] = g; - px[i][2] = bb; - } -} - -fn vignette(px: &mut [[f32; 4]], w: usize, h: usize, p: &CameraRaw) { - let Vignette { amount: amt, highlights: hl, style, centre: [cx, cy], axes: [ax, ay], power: pw, edges: [edge0, edge1] } = Vignette::new(w, h, p); - par_rows(px, w, 1, |y, row| { - for (x, q) in row.iter_mut().enumerate() { - let (dx, dy) = (((x as f32 + 0.5 - cx) / ax).abs(), ((y as f32 + 0.5 - cy) / ay).abs()); - let r = (dx.powf(pw) + dy.powf(pw)).powf(1.0 / pw); - let m = smoothstep(edge0, edge1, r); - if m <= 0.0 { - continue; - } - let l = luma([q[0], q[1], q[2]]).clamp(0.0, 1.0); - match style { - VignetteStyle::PaintOverlay => { - let target = if amt < 0.0 { 0.0 } else { 1.0 }; - let k = m * amt.abs(); - for c in 0..3 { - q[c] += (target - q[c]) * k; - } - } - _ => { - let mut k = 2f32.powf(amt * 2.0 * m); - if amt < 0.0 && hl > 0.0 { - // Highlights: let bright areas punch through a darkening vignette. - let protect = smoothstep(0.6, 1.0, l) * hl; - k += (1.0 - k) * protect; - } - if style == VignetteStyle::ColorPriority { - let nl = l * k; - for c in 0..3 { - q[c] += nl - l; - } - } else { - for c in 0..3 { - q[c] *= k; - } - } - } - } - } - }); -} - -#[cfg(test)] -mod tests { - use super::*; - - /// `CameraRaw` with the named fields set (the type is `#[non_exhaustive]`, so no struct expression), or a copy of a base with them set. - macro_rules! cr { - ($($f:ident : $v:expr),* $(,)?) => {{ - let mut s = CameraRaw::default(); - $(s.$f = $v;)* - s - }}; - ($base:expr => $($f:ident : $v:expr),* $(,)?) => {{ - let mut s: CameraRaw = $base; - $(s.$f = $v;)* - s - }}; - } - - /// [`super::develop`] with the default inputs (full scale, sRGB encoding, seed 0). - fn develop(px: &mut [[f32; 4]], w: usize, h: usize, p: &CameraRaw, float: bool) { - super::develop(px, w, h, p, &DevelopInputs::default(), float); - } - - /// [`super::per_pixel`] with the default inputs. - fn per_pixel(p: &CameraRaw, w: usize, h: usize, float: bool, points: Option<(f32, f32)>) -> Option { - super::per_pixel(p, &DevelopInputs::default(), w, h, float, points) - } - - /// #9273: Dehaze clears the haze evenly over a sky, right up to a dark building, instead of - /// leaving a bright halo of uncorrected haze around it. Synthetic scene: a clear sky and a - /// dark tower, hazed with `I = J·t + A·(1 − t)`. - #[test] - fn dehaze_leaves_no_halo_beside_dark_objects() { - let (w, h) = (600usize, 400usize); - let tower = |x: usize, y: usize| (250..350).contains(&x) && y >= 120; - let (t, air) = (0.55f32, [0.9f32, 0.9, 0.9]); - let mut px: Vec<[f32; 4]> = (0..w * h) - .map(|i| { - let (x, y) = (i % w, i / w); - let j = if tower(x, y) { [0.06, 0.06, 0.07] } else { [0.35 + 0.1 * y as f32 / h as f32, 0.5, 0.8] }; - let c: [f32; 3] = std::array::from_fn(|k| j[k] * t + air[k] * (1.0 - t)); - [c[0], c[1], c[2], 1.0] - }) - .collect(); - let d = Dehaze::new(&cr! { dehaze: 100.0}, w, h).unwrap(); - dehaze(&mut px, w, h, &d); - let sky = |xs: std::ops::Range| { - let v: Vec = - (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(); - v.iter().sum::() / v.len() as f32 - }; - // Sky 1–8 px from the tower against open sky: the haze left beside it, in 8-bit levels. - let halo = (sky(242..250) - sky(20..80)) * 255.0; - // 6.4 levels before the dark channel was opened, under 1 after. - assert!(halo < 3.0, "a {halo:.1}-level halo beside the tower"); - // The open sky is still cleared: darker than the hazy input. - let hazy = luma(std::array::from_fn(|k| [0.4, 0.5, 0.8][k] * t + air[k] * (1.0 - t))); - assert!(sky(20..80) < hazy - 0.02, "{} vs hazy {hazy}", sky(20..80)); - } - - #[test] - fn new_curves_are_validated_but_saved_curves_still_load_and_render() { - for field in ["pointCurve", "pointCurveRed", "pointCurveGreen", "pointCurveBlue"] { - for points in [ - serde_json::json!([[128, 128]]), - serde_json::json!([[255, 255], [0, 0]]), - serde_json::json!([[0, 0], [0, 255]]), - serde_json::json!([[0, -1], [255, 255]]), - serde_json::json!([[0, 0], [256, 255]]), - serde_json::json!([[0, 0], [1e30, 255]]), - serde_json::json!((0..17).map(|i| [i * 15, i * 15]).collect::>()), - ] { - let p: CameraRaw = serde_json::from_value(serde_json::json!({field: points})).unwrap(); - assert!(p.validate().is_err(), "{field}: {points}"); - } - for points in - [serde_json::json!([]), serde_json::json!([[0, 0], [255, 255]]), serde_json::json!((0..16).map(|i| [i * 17, i * 17]).collect::>())] - { - let p: CameraRaw = serde_json::from_value(serde_json::json!({field: points})).unwrap(); - assert!(p.validate().is_ok(), "{field}: {points}"); - } - } - assert_eq!(serde_json::from_str::("{}").unwrap(), CameraRaw::default()); - // An older editor could stack two points on one input and exceed 16 points; such a - // saved Smart Filter must still develop instead of silently disappearing. - let mut legacy: Vec<[f32; 2]> = (0..20).map(|i| [i as f32 * 12.0, i as f32 * 12.0]).collect(); - legacy.insert(5, [60.0, 200.0]); - let p: CameraRaw = serde_json::from_value(serde_json::json!({"pointCurve": legacy})).unwrap(); - assert!(p.validate().is_err()); - let edited = cr! { p.clone() => exposure: 1.0}; - assert!(edited.validate_changes(&p).is_ok(), "an unchanged stored curve stays editable"); - let broken = cr! { p.clone() => point_curve: vec![[10.0, 10.0]]}; - assert!(broken.validate_changes(&p).is_err(), "a changed curve is validated"); - let mut px = img(4, 4); - develop(&mut px, 4, 4, &p, false); - assert!(px.iter().flatten().all(|v| v.is_finite())); - } - - fn img(w: usize, h: usize) -> Vec<[f32; 4]> { - (0..w * h) - .map(|i| { - let (x, y) = ((i % w) as f32 / w as f32, (i / w) as f32 / h as f32); - [0.2 + 0.6 * x, 0.3 + 0.4 * y, 0.5 - 0.3 * x * y, 1.0] - }) - .collect() - } - - fn mean(px: &[[f32; 4]], c: usize) -> f32 { - px.iter().map(|q| q[c]).sum::() / px.len() as f32 - } - - #[test] - fn defaults_are_identity() { - let mut a = img(40, 30); - let b = a.clone(); - develop(&mut a, 40, 30, &CameraRaw::default(), false); - assert_eq!(a, b); - } - - #[test] - fn basic_panel_moves_the_right_way() { - let (w, h) = (64, 48); - let base = img(w, h); - let run = |p: CameraRaw| { - let mut a = base.clone(); - develop(&mut a, w, h, &p, false); - a - }; - let warm = run(cr! { temperature: 50.0}); - assert!(mean(&warm, 0) > mean(&base, 0) && mean(&warm, 2) < mean(&base, 2)); - let bright = run(cr! { exposure: 1.0}); - assert!(mean(&bright, 1) > mean(&base, 1) + 0.1); - let shadows = run(cr! { shadows: 100.0}); - let dark_px = |a: &[[f32; 4]]| a[0][1]; - assert!(dark_px(&shadows) > dark_px(&base)); - let hl = run(cr! { highlights: -100.0}); - assert!(hl[w * h - 1][0] < base[w * h - 1][0]); - let con = run(cr! { contrast: 100.0}); - // More contrast: darker darks, brighter brights. - assert!(con[0][1] < base[0][1] && con[w * h - 1][0] > base[w * h - 1][0]); - let desat = run(cr! { saturation: -100.0}); - assert!(desat.iter().all(|q| (q[0] - q[1]).abs() < 1e-4 && (q[1] - q[2]).abs() < 1e-4)); - let vib = run(cr! { vibrance: 100.0}); - let spread = |q: [f32; 4]| q[0].max(q[1]).max(q[2]) - q[0].min(q[1]).min(q[2]); - assert!(spread(vib[w * h / 2]) > spread(base[w * h / 2])); - for p in [cr! { clarity: 80.0}, cr! { texture: 80.0}, cr! { dehaze: 60.0}, cr! { dehaze: -60.0}, cr! { whites: 50.0, blacks: -50.0}] { - let out = run(p.clone()); - assert!(out.iter().all(|q| q[..3].iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v))), "{p:?}"); - assert_ne!(out, base); - } - } - - #[test] - fn camera_raw_curve_keeps_legacy_close_knots() { - // The middle knots survive the original f32 normalization and make a sharp step. - let x = 127.5_f32; - let close = f32::from_bits(x.to_bits() + 33); - let lut = curve_lut(&[[0.0, 0.0], [x, 0.0], [close, 255.0], [255.0, 255.0]], 1024); - assert!(lut[256] < 0.01 && lut[767] > 0.99, "expected the legacy step, got {} and {}", lut[256], lut[767]); - } - - #[test] - fn curves_hsl_grading_detail_effects() { - // Monotone cubic LUT through the points. - let lut = curve_lut(&[[0.0, 0.0], [64.0, 40.0], [192.0, 220.0], [255.0, 255.0]], 256); - assert!((lut[64] - 40.0 / 255.0).abs() < 0.01 && (lut[192] - 220.0 / 255.0).abs() < 0.01); - assert!(lut.windows(2).all(|p| p[1] >= p[0])); - // Band weights sum to one everywhere. - for hh in (0..360).step_by(7) { - let s: f32 = band_weights(hh as f32).iter().sum(); - assert!((s - 1.0).abs() < 1e-4, "{hh}: {s}"); - } - let (w, h) = (48, 32); - let reds: Vec<[f32; 4]> = vec![[0.8, 0.2, 0.2, 1.0]; w * h]; - let mut a = reds.clone(); - let mut hs = [0.0; 8]; - hs[0] = -100.0; - develop(&mut a, w, h, &cr! { hsl_sat: hs}, false); - assert!(a[0][0] - a[0][1] < 0.1, "reds desaturated: {:?}", a[0]); - let blues: Vec<[f32; 4]> = vec![[0.2, 0.2, 0.8, 1.0]; w * h]; - let mut b = blues.clone(); - develop(&mut b, w, h, &cr! { hsl_sat: hs}, false); - assert!((b[0][2] - 0.8).abs() < 1e-4, "blues untouched"); - // Grading: blue shadows tint dark pixels, leave bright ones nearly alone. - let mut g: Vec<[f32; 4]> = vec![[0.1, 0.1, 0.1, 1.0], [0.95, 0.95, 0.95, 1.0]]; - develop(&mut g, 2, 1, &cr! { grade_shadows: Wheel { hue: 220.0, sat: 80.0, lum: 0.0 }}, false); - assert!(g[0][2] > g[0][0] + 0.05 && (g[1][2] - g[1][0]).abs() < 0.02, "{g:?}"); - // Point curve + parametric. - let mut c = img(w, h); - develop(&mut c, w, h, &cr! { point_curve: vec![[0.0, 30.0], [255.0, 255.0]], curve_shadows: 50.0}, false); - assert!(c.iter().all(|q| q[1] >= 30.0 / 255.0 - 1e-4)); - // Noise reduction reduces variance; sharpening increases it; grain is deterministic. - let noisy: Vec<[f32; 4]> = (0..w * h) - .map(|i| { - let n = hash01(i as i64, 0, 3) * 0.2; - [0.4 + n, 0.4 + n, 0.4 + n, 1.0] - }) - .collect(); - let var = |a: &[[f32; 4]]| { - let m = mean(a, 1); - a.iter().map(|q| (q[1] - m).powi(2)).sum::() / a.len() as f32 - }; - let mut nr = noisy.clone(); - develop(&mut nr, w, h, &cr! { noise_luminance: 80.0}, false); - assert!(var(&nr) < var(&noisy) * 0.5); - // Out-of-range noise settings are held to their 0..=100 range, not turned into huge radii. - let mut wild = noisy.clone(); - let hostile = cr! { noise_luminance: 1.0e30, noise_color: 1.0e30, noise_luminance_detail: 1.0e30, noise_color_detail: 1.0e30}; - develop(&mut wild, w, h, &hostile, false); - assert!(wild.iter().all(|q| q[0].is_finite())); - let mut sh = noisy.clone(); - develop(&mut sh, w, h, &cr! { sharpen_amount: 100.0}, false); - assert!(var(&sh) > var(&noisy)); - let mut g1 = img(w, h); - let mut g2 = img(w, h); - let gp = cr! { grain_amount: 50.0}; - let seeded = DevelopInputs { seed: 4, ..Default::default() }; - super::develop(&mut g1, w, h, &gp, &seeded, false); - super::develop(&mut g2, w, h, &gp, &seeded, false); - assert_eq!(g1, g2); - assert_ne!(g1, img(w, h)); - // Post-crop vignette darkens corners, leaves the centre. - let flat = vec![[0.5f32, 0.5, 0.5, 1.0]; w * h]; - let mut v = flat.clone(); - develop(&mut v, w, h, &cr! { vignette_amount: -80.0}, false); - assert!(v[0][0] < 0.35 && (v[(h / 2) * w + w / 2][0] - 0.5).abs() < 0.01, "{:?}", v[0]); - } - - #[test] - fn calibration_keeps_the_develop_off_the_per_pixel_gpu_stages() { - // The per-pixel stages (the Camera Raw dialog's GPU preview) don't run Calibration, so - // settings with it must fall back to the CPU develop instead of previewing without it. - for p in [cr! { shadow_tint: 40.0}, cr! { calibration_hue: [0.0, 0.0, 30.0], whites: 20.0}, cr! { calibration_sat: [-50.0, 0.0, 0.0], exposure: 0.5}] { - assert!(!spatial(&p)); - assert!(per_pixel(&p, 2, 2, false, Some((0.0, 1.0))).is_none(), "{p:?}"); - } - assert!(per_pixel(&cr! { exposure: 0.5}, 2, 2, false, None).is_some()); - } - - #[test] - fn calibration_turns_primaries_keeps_neutrals_and_tints_shadows() { - let w = calibration_weights(0.0); - assert!((w[0] - 1.0).abs() < 1e-6, "pure red is all red primary: {w:?}"); - let w = calibration_weights(60.0); - assert!((w[0] - 0.5).abs() < 1e-6 && (w[1] - 0.5).abs() < 1e-6, "yellow is half red, half green: {w:?}"); - let w = calibration_weights(300.0); - assert!((w[2] - 0.5).abs() < 1e-6 && (w[0] - 0.5).abs() < 1e-6, "magenta wraps round: {w:?}"); - let (none, zero) = ([0.0f32; 3], [0.0f32; 3]); - let grey = calibrate([0.3, 0.3, 0.3], [100.0, -100.0, 50.0], [100.0, -100.0, 100.0]); - assert!(grey.iter().all(|v| (v - 0.3).abs() < 1e-5), "greys are untouched: {grey:?}"); - // Red turned towards green: it gains green, keeps its luminance. - let red = calibrate([0.5, 0.0, 0.0], [100.0, 0.0, 0.0], zero); - assert!(red[1] > 0.05 && (red[1] / red[0] - 0.5).abs() < 0.02 && red[2] < 1e-6, "red turns 30° towards green (orange): {red:?}"); - assert!((luma(red) - luma([0.5, 0.0, 0.0])).abs() < 1e-4, "luminance kept: {red:?}"); - // Blue at saturation −100 is grey; green at −50 is paler. - let blue = calibrate([0.0, 0.0, 0.8], none, [0.0, 0.0, -100.0]); - assert!((blue[0] - blue[1]).abs() < 1e-5 && (blue[1] - blue[2]).abs() < 1e-5, "blue at −100 saturation is grey: {blue:?}"); - let green = calibrate([0.2, 0.8, 0.2], none, [0.0, -50.0, 0.0]); - assert!(green[0] > 0.2 && green[1] < 0.8, "green at −50 is paler: {green:?}"); - // A primary's sliders leave the other primaries alone. - let unchanged = calibrate([0.0, 0.0, 0.8], [100.0, 100.0, 0.0], [100.0, 100.0, 0.0]); - assert!(unchanged.iter().zip([0.0, 0.0, 0.8]).all(|(a, b)| (a - b).abs() < 1e-5), "{unchanged:?}"); - // Shadows tint: magenta lifts red and blue over green in a dark pixel, keeps luminance, - // and leaves white alone. - let dark = shadow_tint([0.02, 0.02, 0.02], 1.0); - assert!(dark[0] > dark[1] && dark[2] > dark[1], "{dark:?}"); - assert!((luma(dark) - 0.02).abs() < 1e-4, "luminance kept: {dark:?}"); - let green = shadow_tint([0.02, 0.02, 0.02], -1.0); - assert!(green[1] > green[0], "{green:?}"); - let white = shadow_tint([1.0, 1.0, 1.0], 1.0); - assert!(white.iter().all(|v| (v - 1.0).abs() < 1e-3), "white is not tinted: {white:?}"); - // Through develop: neutral settings are an identity, a tint changes dark pixels only. - let mut p = CameraRaw::default(); - assert!(p.is_identity()); - p.shadow_tint = 100.0; - assert!(!p.is_identity()); - let mut px = vec![[0.1, 0.1, 0.1, 1.0], [0.95, 0.95, 0.95, 1.0]]; - develop(&mut px, 2, 1, &p, false); - assert!(px[0][0] > px[0][1], "dark grey turns magenta: {:?}", px[0]); - assert!((px[1][0] - px[1][1]).abs() < 0.01, "near-white stays neutral: {:?}", px[1]); - p = CameraRaw::default(); - p.calibration_hue[2] = 100.0; - let mut px = vec![[0.0, 0.0, 0.8, 1.0]]; - develop(&mut px, 1, 1, &p, false); - assert!(px[0][0] > 0.05, "blue turned towards red: {:?}", px[0]); - } - - #[test] - fn auto_tone_brightens_dark_and_darkens_bright_images() { - let mut p = CameraRaw::default(); - auto_tone(&[], &mut p); - assert_eq!(p, CameraRaw::default(), "no pixels: nothing changes"); - let dark: Vec<[f32; 4]> = (0..4096) - .map(|i| { - let v = 0.05 + (i % 64) as f32 / 64.0 * 0.15; - [v, v, v, 1.0] - }) - .collect(); - auto_tone(&dark, &mut p); - assert!(p.exposure > 0.5, "a dark image gets exposure: {}", p.exposure); - assert!(p.shadows > 0.0, "and lifted shadows: {}", p.shadows); - let mut p = CameraRaw::default(); - let bright: Vec<[f32; 4]> = (0..4096) - .map(|i| { - let v = 0.8 + (i % 64) as f32 / 64.0 * 0.19; - [v, v, v, 1.0] - }) - .collect(); - auto_tone(&bright, &mut p); - assert!(p.exposure < -0.5, "a bright image loses exposure: {}", p.exposure); - assert!(p.highlights < 0.0, "and its highlights come down: {}", p.highlights); - let mut p = CameraRaw::default(); - let good: Vec<[f32; 4]> = (0..4096) - .map(|i| { - let v = 0.04 + (i % 64) as f32 / 63.0 * 0.92; - [v, v, v, 1.0] - }) - .collect(); - auto_tone(&good, &mut p); - assert!(p.exposure.abs() < 0.3 && p.blacks.abs() < 10.0 && p.whites.abs() < 10.0, "a full-range image is left nearly alone: {p:?}"); - assert!(p.saturation == 0.0 && hsl_neutral(&p), "other panels untouched"); - } - - #[test] - fn float_documents_keep_overrange() { - let mut a = vec![[2.0f32, 1.5, 0.5, 1.0]; 16]; - develop(&mut a, 4, 4, &cr! { exposure: 0.5}, true); - assert!(a[0][0] > 2.0); - } - - /// A Gaussian narrower than 0.3 px has no box radii, so it returns its input unchanged, and - /// Texture on a proxy that small changes nothing. - #[test] - fn a_gaussian_below_0_3_px_leaves_the_image_alone() { - assert!(spatial::gauss_radii(0.29).is_empty()); - assert!(!spatial::gauss_radii(0.3).is_empty()); - let (w, h) = (64usize, 48usize); - let v: Vec = (0..w * h).map(|i| ((i * 37) % 101) as f32 / 100.0).collect(); - assert_eq!(gauss(&v, w, h, 0.29), v); - assert_eq!(box_means(&v, w, h, &[]), v); - assert_ne!(gauss(&v, w, h, 1.0), v); - let src: Vec<[f32; 4]> = v.iter().map(|&x| [x, 1.0 - x, 0.5 * x, 1.0]).collect(); - let base = cr! { contrast: 10.0}; - let scaled = DevelopInputs { pixel_scale: 0.1, ..Default::default() }; - let (mut plain, mut textured) = (src.clone(), src); - super::develop(&mut plain, w, h, &base, &scaled, false); - super::develop(&mut textured, w, h, &cr! { base => texture: 80.0}, &scaled, false); - assert_eq!(plain, textured); - } +/// Image black and white points for `Whites` and `Blacks`, measured on the CPU. +pub fn white_black_points(px: &[[f32; 4]], w: usize, h: usize, p: &CameraRaw, inputs: &DevelopInputs) -> Option<(f32, f32)> { + craft_develop::camera_raw::white_black_points(px, w, h, &to_shared(p), inputs) } diff --git a/crates/algo/src/camera_raw/local_tone.rs b/crates/algo/src/camera_raw/local_tone.rs deleted file mode 100644 index b5953e9060..0000000000 --- a/crates/algo/src/camera_raw/local_tone.rs +++ /dev/null @@ -1,658 +0,0 @@ -//! Shadows and Highlights as a local Laplacian filter. -//! -//! Adobe has said Camera Raw's process version 2012 rests on local Laplacian filters (S. Paris, -//! S. W. Hasinoff, J. Kautz, *Local Laplacian Filters: Edge-aware Image Processing with a -//! Laplacian Pyramid*, SIGGRAPH 2011). This follows that paper, in its fast form (M. Aubry et -//! al., *Fast Local Laplacian Filters*, ACM TOG 2014: the remapping sampled at a few reference -//! values, each pyramid coefficient interpolated between them), on the log2 luminance: -//! -//! - **Shadows** raises pixels darker than their surroundings, by an amount set by their own and -//! their surroundings' place in the image's range (1st to 99th percentile); **Highlights** -//! pulls pixels brighter than their surroundings toward them. Differences under a threshold -//! are left alone, so fine detail stays. -//! - Shadows then keeps the image's 99th percentile, Highlights its 1st (Photoshop keeps the -//! brightest content under Shadows and the darkest under Highlights). -//! - A uniform image is unchanged, edges keep no halo, and the result does not depend on the -//! image size. -//! -//! The strengths were fitted to Photoshop 25.4's Camera Raw Filter on ten public-domain photos -//! (black-box measurements, no Adobe code or data). It is an approximation: on those photos the -//! mean error against Photoshop is 2.8–9.4 levels (of 255) where the previous heuristic's was -//! 3.7–14.3. - -use super::{Encoding, luma, quantile_rank}; -use crate::photo_util::par_rows; - -/// Spacing of the fast filter's reference values in stops. Its remapping changes within about -/// half a stop, and coefficients interpolated across wider gaps show as contour lines on smooth -/// gradients (12 references over a whole raw's range left visible steps; at an eighth of a stop a -/// ramp's slope varies by under a third, as the remapping itself makes it). -pub const REF_STEP: f32 = 0.125; -/// Most reference values one filter uses. -pub const MAX_REFS: usize = 96; -/// The lowest reference sits at this quantile of the log luminance: the deepest 0.1 % (noise down -/// to the floor) share it instead of stretching the spacing. -pub const REF_LOW_QUANTILE: f32 = 0.001; -/// The filter works on `log2(luminance + LOG_FLOOR)`. -pub const LOG_FLOOR: f32 = 1.0 / 65536.0; -/// The filter runs on a copy at most this many pixels across; the change it makes is brought back -/// to full size by a guided upsampling, so a preview and the full image agree. -pub const WORK_SIDE: usize = 1600; -/// The image range the strengths are placed in: these quantiles of the log luminance averaged -/// over cells of a copy at most [`RANGE_SIDE`] pixels across. -pub const RANGE_QUANTILES: [f32; 2] = [0.01, 0.99]; -/// See [`RANGE_QUANTILES`]. -pub const RANGE_SIDE: usize = 256; -/// Knots of the strength curves over the surroundings' place in the image range (0 … 1). -pub const KNOTS: usize = 5; - -/// Shadows: how far a pixel darker than its surroundings rises, in stops per unit slider, as -/// a function of its own place in the image range (`own`) times a factor of its surroundings' -/// place (`around`); it rises fully once it is `sigma` stops below them. The lift depends on -/// the pixel's tone, not on the size of the difference, so it is the same at every pyramid -/// level and a big edge keeps no halo. Lowering (negative values) is `down` times as strong. -const SHADOWS: Lift = Lift { own: [-0.017, 0.466, 0.886, 1.221, -0.081], around: [4.566, 4.067, 1.088, 0.149, 0.878], sigma: 0.571, down: 0.808 }; -const HIGHLIGHTS: Side = Side { pull: [0.179, 0.141, 0.196, 0.629, 2.07], push: [0.156, 0.08, 0.175, 0.049, 1.261], sigma: 0.05 }; - -/// See [`SHADOWS`]. -struct Lift { - own: [f32; KNOTS], - around: [f32; KNOTS], - sigma: f32, - down: f32, -} - -/// Highlights: strengths per unit slider over the surroundings' place in the image range, for -/// lowering (`pull`, toward the surroundings) and raising (`push`), and the detail threshold in -/// stops. -struct Side { - pull: [f32; KNOTS], - push: [f32; KNOTS], - sigma: f32, -} - -/// Which remapping a [`TonePass`] uses. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum ToneKind { - /// Pixels brighter than their surroundings move toward them (or away, for positive values) - /// by the part of the difference past `sigma`. - Highlights, - /// Pixels darker than their surroundings rise (or sink) by an amount set by their own and - /// their surroundings' place in the image range. - Shadows, -} - -/// One pass of the filter resolved for a slider value: everything its remapping reads. -#[derive(Clone, Debug, PartialEq)] -pub struct TonePass { - pub kind: ToneKind, - /// Highlights: the slider / 100. Shadows: its strength (the slider / 100, times `down` when - /// negative). - pub amount: f32, - /// Highlights: the strengths for the slider's direction, then an unused row. Shadows: the - /// curves over the pixel's own (`own`) and its surroundings' (`around`) place. - pub knots: [[f32; KNOTS]; 2], - /// The detail threshold in stops. - pub sigma: f32, - /// The quantile of the log luminance the pass puts back where it was. - pub keep: f32, -} - -/// Shadows and Highlights resolved: Highlights runs first, then Shadows on its result. -#[derive(Clone, Debug, PartialEq)] -pub struct LocalTone { - pub passes: Vec, -} - -impl LocalTone { - /// The passes for the sliders (−100 … 100); `None` when both are 0. - pub fn new(shadows: f32, highlights: f32) -> Option { - let mut passes = Vec::new(); - if highlights != 0.0 { - let amount = highlights.clamp(-100.0, 100.0) / 100.0; - let strengths = if amount < 0.0 { HIGHLIGHTS.pull } else { HIGHLIGHTS.push }; - // Then the darkest content is put back where it was. - passes.push(TonePass { kind: ToneKind::Highlights, amount, knots: [strengths, [0.0; KNOTS]], sigma: HIGHLIGHTS.sigma, keep: 0.01 }); - } - if shadows != 0.0 { - let amount = shadows.clamp(-100.0, 100.0) / 100.0; - let k = if amount > 0.0 { amount } else { amount * SHADOWS.down }; - // Keep the brightest content. - passes.push(TonePass { kind: ToneKind::Shadows, amount: k, knots: [SHADOWS.own, SHADOWS.around], sigma: SHADOWS.sigma, keep: 0.99 }); - } - (!passes.is_empty()).then_some(LocalTone { passes }) - } -} - -impl TonePass { - /// The remapping of log luminance `x` around the reference `g`, in an image range that - /// starts at `lo` and is `span` stops wide. - pub fn remap(&self, x: f32, g: f32, lo: f32, span: f32) -> f32 { - match self.kind { - ToneKind::Highlights => x + knot((g - lo) / span, &self.knots[0]) * self.amount * excess((x - g).max(0.0), self.sigma), - ToneKind::Shadows => { - let below = ((g - x) / self.sigma).clamp(0.0, 1.0); - if below == 0.0 { - return x; - } - let w = below * below * (3.0 - 2.0 * below); - x + self.amount * knot((x - lo) / span, &self.knots[0]) * knot((g - lo) / span, &self.knots[1]) * w - } - } - } - - /// The pass on the log luminance `u`: the filter, then the kept quantile put back. - fn run(&self, u: &Plane) -> Plane { - let (lo, hi) = range(u); - let span = (hi - lo).max(1.0); - let o = llf(u, |x, g| self.remap(x, g, lo, span)); - let shift = quantile(&u.v, self.keep) - quantile(&o.v, self.keep); - Plane { w: o.w, h: o.h, v: o.v.iter().map(|v| v + shift).collect() } - } -} - -/// One channel, `w × h`. -struct Plane { - w: usize, - h: usize, - v: Vec, -} - -/// Mirrors `i` into `0..n` (the edge sample is not repeated). -fn mirror(i: isize, n: usize) -> usize { - let n = n as isize; - if n == 1 { - return 0; - } - let p = 2 * (n - 1); - let m = i.rem_euclid(p); - (if m >= n { p - m } else { m }) as usize -} - -/// The pyramid's binomial kernel. -pub const TAPS: [f32; 5] = [1.0 / 16.0, 4.0 / 16.0, 6.0 / 16.0, 4.0 / 16.0, 1.0 / 16.0]; - -/// Planes smaller than this run their rows on one thread: the filter builds a whole pyramid per -/// reference (up to 96), and splitting its small levels into one-row tasks cost more in rayon's -/// scheduling than the rows themselves (a fifth of a Shadows render on 36 MP, measured). -const PAR_MIN: usize = 1 << 15; - -/// [`par_rows`] for a plane, on one thread when it is small (see [`PAR_MIN`]). -fn rows(buf: &mut [f32], w: usize, f: impl Fn(usize, &mut [f32]) + Sync + Send) { - if buf.len() < PAR_MIN { - buf.chunks_mut(w.max(1)).enumerate().for_each(|(y, row)| f(y, row)); - } else { - par_rows(buf, w, 1, f); - } -} - -/// The binomial 5-tap blur, sampled every `step` pixels from 0 (1 = full resolution). -fn blur_step(p: &Plane, step: usize) -> Plane { - let (w2, h2) = (p.w.div_ceil(step), p.h.div_ceil(step)); - // Columns first at the kept rows, then rows at the kept columns. Each sum adds the same terms - // in the same order as a `mirror` per tap would, so the result is bit for bit the same; the - // source rows are found once per row and the columns mirrored only near the edges. - let mut tmp = vec![0.0f32; p.w * h2]; - rows(&mut tmp, p.w, |y2, row| { - let y = (y2 * step) as isize; - let src: [&[f32]; 5] = std::array::from_fn(|k| { - let r = mirror(y + k as isize - 2, p.h); - &p.v[r * p.w..(r + 1) * p.w] - }); - for (x, o) in row.iter_mut().enumerate() { - *o = (0..5).map(|k| TAPS[k] * src[k][x]).sum(); - } - }); - let mut out = vec![0.0f32; w2 * h2]; - rows(&mut out, w2, |y2, row| { - let src = &tmp[y2 * p.w..(y2 + 1) * p.w]; - for (x2, o) in row.iter_mut().enumerate() { - let x = x2 * step; - *o = if x >= 2 && x + 2 < p.w { - let s = &src[x - 2..x + 3]; - (0..5).map(|k| TAPS[k] * s[k]).sum() - } else { - (0..5).map(|k| TAPS[k] * src[mirror(x as isize + k as isize - 2, p.w)]).sum() - }; - } - }); - Plane { w: w2, h: h2, v: out } -} - -/// The next coarser level. -fn down(p: &Plane) -> Plane { - blur_step(p, 2) -} - -/// `p` brought up to `w × h`: zeros between samples, then the blur times four. -/// -/// Three samples in four are zero, so their taps are skipped instead of blurring a zero-filled -/// plane: the nonzero terms are added in the same order (skipping `+0.0` terms changes at most the -/// sign of a zero, and the filter only adds and exponentiates these values). -fn up(p: &Plane, w: usize, h: usize) -> Plane { - let (lh, lw) = (p.h.min(h.div_ceil(2)), p.w.min(w.div_ceil(2))); - // The source sample behind index `i` of a zero-stuffed axis of length `n` holding `lim` samples. - let src = |i: isize, n: usize, lim: usize| { - let m = mirror(i, n); - (m.is_multiple_of(2) && m / 2 < lim).then_some(m / 2) - }; - // Columns first, only at the even columns (the odd ones are all zero). - let mut tmp = vec![0.0f32; lw * h]; - if lw > 0 { - rows(&mut tmp, lw, |y, row| { - let taps: [Option<&[f32]>; 5] = std::array::from_fn(|k| src(y as isize + k as isize - 2, h, lh).map(|r| &p.v[r * p.w..r * p.w + lw])); - for (j, o) in row.iter_mut().enumerate() { - *o = (0..5).filter_map(|k| taps[k].map(|s| TAPS[k] * (s[j] * 4.0))).sum(); - } - }); - } - let mut out = vec![0.0f32; w * h]; - rows(&mut out, w, |y, row| { - let t = &tmp[y * lw..(y + 1) * lw]; - for (x, o) in row.iter_mut().enumerate() { - *o = if x >= 2 && x + 2 < w { - // Away from the edges no tap mirrors. - (0..5) - .filter_map(|k| { - let i = x + k - 2; - (i.is_multiple_of(2) && i / 2 < lw).then(|| TAPS[k] * t[i / 2]) - }) - .sum() - } else { - (0..5).filter_map(|k| src(x as isize + k as isize - 2, w, lw).map(|j| TAPS[k] * t[j])).sum() - }; - } - }); - Plane { w, h, v: out } -} - -/// The source rows of [`up`]`(p, w, h)` at output row `y`, one per tap (`None` where the -/// zero-stuffed row is all zeros). -fn up_rows(p: &Plane, h: usize, y: usize) -> [Option; 5] { - let lh = p.h.min(h.div_ceil(2)); - std::array::from_fn(|k| { - let m = mirror(y as isize + k as isize - 2, h); - (m.is_multiple_of(2) && m / 2 < lh).then_some(m / 2) - }) -} - -/// One sample of [`up`]`(p, w, h)`: column `x` of the output row whose [`up_rows`] are `rows`. -/// It adds the same terms in the same order as `up`, so it gives the same bits. -fn up_at(p: &Plane, w: usize, rows: &[Option; 5], x: usize) -> f32 { - let lw = p.w.min(w.div_ceil(2)); - let col = |j: usize| -> f32 { (0..5).filter_map(|k| rows[k].map(|r| TAPS[k] * (p.v[r * p.w + j] * 4.0))).sum() }; - if x >= 2 && x + 2 < w { - // Away from the edges no tap mirrors. - (0..5) - .filter_map(|k| { - let i = x + k - 2; - (i.is_multiple_of(2) && i / 2 < lw).then(|| TAPS[k] * col(i / 2)) - }) - .sum() - } else { - (0..5) - .filter_map(|k| { - let m = mirror(x as isize + k as isize - 2, w); - (m.is_multiple_of(2) && m / 2 < lw).then(|| TAPS[k] * col(m / 2)) - }) - .sum() - } -} - -/// Levels down to about 2 pixels on the short side. -fn depth(w: usize, h: usize) -> usize { - let mut s = w.min(h); - let mut n = 1; - while s > 2 { - s = s.div_ceil(2); - n += 1; - } - n -} - -fn gaussian(p: Plane, n: usize) -> Vec { - let mut g = vec![p]; - for _ in 1..n { - let next = down(&g[g.len() - 1]); - g.push(next); - } - g -} - -/// The local Laplacian filter of `u` with `remap(value, reference)`; the coarsest level is kept. -fn llf(u: &Plane, remap: impl Fn(f32, f32) -> f32 + Sync) -> Plane { - let n = depth(u.w, u.h); - let g = gaussian(Plane { w: u.w, h: u.h, v: u.v.clone() }, n); - // References span the image's tones (see `REF_LOW_QUANTILE`). - let hi = u.v.iter().fold(f32::NEG_INFINITY, |a, &v| a.max(v)); - let lo = quantile(&u.v, REF_LOW_QUANTILE).min(hi); - if hi - lo <= 1e-6 || (hi - lo).is_nan() { - return Plane { w: u.w, h: u.h, v: u.v.clone() }; - } - let refs = (((hi - lo) / REF_STEP).ceil() as usize + 1).clamp(2, MAX_REFS); - let step = (hi - lo) / (refs - 1) as f32; - let mut lap: Vec> = g[..n - 1].iter().map(|p| vec![0.0; p.v.len()]).collect(); - for k in 0..refs { - let r = lo + step * k as f32; - let mut m = Plane { w: u.w, h: u.h, v: u.v.clone() }; - rows(&mut m.v, u.w, |_, row| { - for v in row.iter_mut() { - *v = remap(*v, r); - } - }); - let gr = gaussian(m, n); - for l in 0..n - 1 { - let (gl, fine, lw, lh, coarse) = (&g[l].v, &gr[l].v, g[l].w, g[l].h, &gr[l + 1]); - rows(&mut lap[l], lw, |y, row| { - let taps = up_rows(coarse, lh, y); - for (x, o) in row.iter_mut().enumerate() { - let i = y * lw + x; - let wgt = (1.0 - (gl[i].clamp(lo, hi) - r).abs() / step).max(0.0); - if wgt > 0.0 { - *o += wgt * (fine[i] - up_at(coarse, lw, &taps, x)); - } - } - }); - } - } - let mut o = Plane { w: g[n - 1].w, h: g[n - 1].h, v: g[n - 1].v.clone() }; - for l in (0..n - 1).rev() { - let mut next = up(&o, g[l].w, g[l].h); - for (a, b) in next.v.iter_mut().zip(&lap[l]) { - *a += b; - } - o = next; - } - o -} - -/// The `q` quantile (0 … 1) of `v`. -fn quantile(v: &[f32], q: f32) -> f32 { - let mut s = v.to_vec(); - // Selecting the one element is linear, a full sort is not (5 sorts of the work copy were a - // fifteenth of a render). `total_cmp` ties are bit-identical, so it is the sorted element. - let i = quantile_rank(s.len(), q); - *s.select_nth_unstable_by(i, f32::total_cmp).1 -} - -/// The image range: [`RANGE_QUANTILES`] of the log luminance on a copy at most [`RANGE_SIDE`] -/// pixels across. -fn range(u: &Plane) -> (f32, f32) { - let f = u.w.max(u.h).div_ceil(RANGE_SIDE).max(1); - let (sw, sh) = (u.w.div_ceil(f), u.h.div_ceil(f)); - let mut sum = vec![(0.0f64, 0u32); sw * sh]; - for y in 0..u.h { - for x in 0..u.w { - let c = &mut sum[(y / f) * sw + x / f]; - c.0 += f64::from(u.v[y * u.w + x]); - c.1 += 1; - } - } - let cells: Vec = sum.iter().filter(|c| c.1 > 0).map(|c| (c.0 / f64::from(c.1)) as f32).collect(); - (quantile(&cells, RANGE_QUANTILES[0]), quantile(&cells, RANGE_QUANTILES[1])) -} - -/// `d` past the detail threshold: about 0 below `sigma`, `d − sigma` well above it. -fn excess(d: f32, sigma: f32) -> f32 { - d - sigma * (d / sigma).tanh() -} - -fn knot(t: f32, k: &[f32; KNOTS]) -> f32 { - let x = t.clamp(0.0, 1.0) * (KNOTS - 1) as f32; - let i = (x as usize).min(KNOTS - 2); - k[i] + (k[i + 1] - k[i]) * (x - i as f32) -} - -/// Applies Shadows and Highlights (−100 … 100) to straight RGBA pixels encoded with `enc` -/// (`Encoding::of(DevelopInputs::encoding_gamma)`). The filter is deterministic, so it reads no grain seed. -pub(crate) fn apply(px: &mut [[f32; 4]], w: usize, h: usize, shadows: f32, highlights: f32, enc: Encoding) { - let Some(tone) = LocalTone::new(shadows, highlights) else { return }; - if w < 2 || h < 2 { - return; - } - let u = Plane { w, h, v: px.iter().map(|q| (luma([0, 1, 2].map(|c| enc.decode(q[c]))).max(0.0) + LOG_FLOOR).log2()).collect() }; - // The filter on a copy at most WORK_SIDE across (box-averaged in log). - let f = w.max(h).div_ceil(WORK_SIDE).max(1); - let small = if f == 1 { Plane { w, h, v: u.v.clone() } } else { shrink(&u, f) }; - let mut o = Plane { w: small.w, h: small.h, v: small.v.clone() }; - for pass in &tone.passes { - o = pass.run(&o); - } - // The change in log luminance, at full size. - let change: Vec = if f == 1 { - o.v.iter().zip(&u.v).map(|(a, b)| a - b).collect() - } else { - let d: Vec = o.v.iter().zip(&small.v).map(|(a, b)| a - b).collect(); - guided_upsample(&small, &d, &u) - }; - par_rows(px, w, 1, |y, row| { - for (x, q) in row.iter_mut().enumerate() { - let gain = change[y * w + x].exp2(); - for c in 0..3 { - q[c] = enc.encode(enc.decode(q[c]) * gain); - } - } - }); -} - -/// `u` averaged over `f × f` blocks. -fn shrink(u: &Plane, f: usize) -> Plane { - let (sw, sh) = (u.w.div_ceil(f), u.h.div_ceil(f)); - let mut v = vec![0.0f32; sw * sh]; - par_rows(&mut v, sw, 1, |y, row| { - for (x, o) in row.iter_mut().enumerate() { - let (x0, y0) = (x * f, y * f); - let (x1, y1) = ((x0 + f).min(u.w), (y0 + f).min(u.h)); - let mut s = 0.0f64; - for yy in y0..y1 { - for xx in x0..x1 { - s += f64::from(u.v[yy * u.w + xx]); - } - } - *o = (s / ((x1 - x0) * (y1 - y0)) as f64) as f32; - } - }); - Plane { w: sw, h: sh, v } -} - -/// The change `d` computed on `small` brought to the size of `full`, following its edges: a local -/// linear model of the change against the log luminance (the guided filter of K. He, J. Sun, -/// *Fast Guided Filter*, 2015), fitted on the small copy and evaluated on the full one. -fn guided_upsample(small: &Plane, d: &[f32], full: &Plane) -> Vec { - let (sw, sh) = (small.w, small.h); - let r = 2; - let eps = 0.01; - let mean = |v: &[f32]| super::box_mean(v, sw, sh, r); - let ud: Vec = small.v.iter().zip(d).map(|(a, b)| a * b).collect(); - let uu: Vec = small.v.iter().map(|a| a * a).collect(); - let (mu, md, mud, muu) = (mean(&small.v), mean(d), mean(&ud), mean(&uu)); - let a: Vec = (0..sw * sh).map(|i| (mud[i] - mu[i] * md[i]) / (muu[i] - mu[i] * mu[i] + eps)).collect(); - let b: Vec = (0..sw * sh).map(|i| md[i] - a[i] * mu[i]).collect(); - let (ma, mb) = (mean(&a), mean(&b)); - let (fx, fy) = (sw as f32 / full.w as f32, sh as f32 / full.h as f32); - let mut out = vec![0.0f32; full.w * full.h]; - par_rows(&mut out, full.w, 1, |y, row| { - let sy = (y as f32 + 0.5) * fy - 0.5; - for (x, o) in row.iter_mut().enumerate() { - let sx = (x as f32 + 0.5) * fx - 0.5; - let av = crate::photo_util::bilinear(&ma, sw, sh, 1, 0, sx, sy); - let bv = crate::photo_util::bilinear(&mb, sw, sh, 1, 0, sx, sy); - *o = av * full.v[y * full.w + x] + bv; - } - }); - out -} - -#[cfg(test)] -mod tests { - use super::*; - - const SRGB: Encoding = Encoding(0.0); - - /// The plain blur: a `mirror` per tap over the whole plane, the reference for [`blur_step`]. - fn blur_step_reference(p: &Plane, step: usize) -> Plane { - let (w2, h2) = (p.w.div_ceil(step), p.h.div_ceil(step)); - let mut tmp = vec![0.0f32; p.w * h2]; - for y2 in 0..h2 { - for x in 0..p.w { - tmp[y2 * p.w + x] = (0..5).map(|k| TAPS[k] * p.v[mirror((y2 * step) as isize + k as isize - 2, p.h) * p.w + x]).sum(); - } - } - let mut out = vec![0.0f32; w2 * h2]; - for y2 in 0..h2 { - for x2 in 0..w2 { - out[y2 * w2 + x2] = (0..5).map(|k| TAPS[k] * tmp[y2 * p.w + mirror((x2 * step) as isize + k as isize - 2, p.w)]).sum(); - } - } - Plane { w: w2, h: h2, v: out } - } - - /// The plain upsampling: a zero-stuffed plane blurred whole, the reference for [`up`]. - fn up_reference(p: &Plane, w: usize, h: usize) -> Plane { - let mut z = Plane { w, h, v: vec![0.0; w * h] }; - for y in 0..p.h.min(h.div_ceil(2)) { - for x in 0..p.w.min(w.div_ceil(2)) { - z.v[2 * y * w + 2 * x] = p.v[y * p.w + x] * 4.0; - } - } - blur_step_reference(&z, 1) - } - - fn noise_plane(w: usize, h: usize, seed: u32) -> Plane { - let mut s = seed.wrapping_mul(2_654_435_761).max(1); - let v = (0..w * h) - .map(|_| { - s ^= s << 13; - s ^= s >> 17; - s ^= s << 5; - (s % 20_000) as f32 / 1000.0 - 16.0 - }) - .collect(); - Plane { w, h, v } - } - - #[test] - fn the_fast_pyramid_matches_the_plain_one_exactly() { - // Odd, even, tiny and large-enough-to-run-in-parallel sizes, as the pyramid's levels are. - for (i, (w, h)) in [(1, 1), (1, 7), (2, 2), (3, 5), (5, 3), (8, 6), (37, 23), (64, 64), (301, 211)].into_iter().enumerate() { - let p = noise_plane(w, h, i as u32 + 1); - for step in [1, 2] { - assert_eq!(blur_step(&p, step).v, blur_step_reference(&p, step).v, "blur {w}×{h} step {step}"); - } - for (uw, uh) in [(w * 2, h * 2), (w * 2 - 1, h * 2 - 1), (w * 2, h * 2 - 1), (w.max(2) * 2 - 3, h * 2)] { - let full = up(&p, uw, uh); - assert_eq!(full.v, up_reference(&p, uw, uh).v, "up {w}×{h} → {uw}×{uh}"); - // The filter samples `up` one pixel at a time; every sample has the same bits. - for y in 0..uh { - let taps = up_rows(&p, uh, y); - for x in 0..uw { - assert_eq!(up_at(&p, uw, &taps, x).to_bits(), full.v[y * uw + x].to_bits(), "up_at {w}×{h} → {uw}×{uh} at {x},{y}"); - } - } - } - } - } - - #[test] - fn quantile_is_the_sorted_element() { - let p = noise_plane(301, 211, 9); - let mut v = p.v.clone(); - // Ties and signed zeros, which `total_cmp` orders by their bits. - v.extend([0.0, -0.0, 0.0, -0.0, 3.5, 3.5, f32::MIN_POSITIVE]); - let mut sorted = v.clone(); - sorted.sort_by(f32::total_cmp); - for q in [0.0, 0.001, 0.01, 0.25, 0.5, 0.99, 1.0] { - let want = sorted[((sorted.len() - 1) as f32 * q).round() as usize]; - assert_eq!(quantile(&v, q).to_bits(), want.to_bits(), "q {q}"); - } - } - - fn grey(w: usize, h: usize, f: impl Fn(usize, usize) -> f32) -> Vec<[f32; 4]> { - (0..w * h).map(|i| f(i % w, i / w)).map(|v| [v, v, v, 1.0]).collect() - } - - #[test] - fn a_flat_image_is_unchanged() { - let mut px = grey(64, 48, |_, _| 0.4); - apply(&mut px, 64, 48, 100.0, -100.0, SRGB); - assert!(px.iter().all(|q| (q[0] - 0.4).abs() < 1e-5)); - } - - #[test] - fn shadows_raise_a_dark_area_without_a_halo() { - // A 0.1 | 0.6 step (the dark half is the image's black point, which Photoshop barely - // moves either): the bright half stays, and no halo forms on either side of the edge. - let (w, h) = (256, 128); - let mut px = grey(w, h, |x, _| if x < w / 2 { 0.1 } else { 0.6 }); - apply(&mut px, w, h, 100.0, 0.0, SRGB); - let row = &px[64 * w..65 * w]; - assert!((row[w / 2 + 1][0] - 0.6).abs() < 0.002 && (row[w - 5][0] - 0.6).abs() < 0.002); - let (far, near) = (row[10][0], row[w / 2 - 1][0]); - assert!((far - 0.1).abs() < 0.004 && (far - near).abs() < 0.004, "{far} {near}"); - } - - #[test] - fn grey_moves_as_in_photoshop() { - // Mid-grey with 1 % black (0.015) and white (0.97) corners, Photoshop 25.4: Shadows +100 - // takes the grey from 127.5 to 165.3, Highlights −100 to 89.6 (of 255). - let n = 256; - let image = |c: f32| { - grey(n, n, |x, y| { - if x >= n - 26 && y >= n - 26 { - 0.97 - } else if x >= n - 26 && y < 26 { - 0.015 - } else { - c - } - }) - }; - for (s, hl, want) in [(100.0, 0.0, 165.3), (0.0, -100.0, 89.6)] { - let mut px = image(0.5); - apply(&mut px, n, n, s, hl, SRGB); - let got = px[175 * n + 100][0] * 255.0; - assert!((got - want).abs() < 5.0, "{s} {hl}: {got} vs {want}"); - } - } - - #[test] - fn highlights_lower_a_bright_area_and_keep_the_darkest() { - let (w, h) = (192, 192); - let mut px = grey(w, h, |x, y| if (64..128).contains(&x) && (64..128).contains(&y) { 0.8 } else { 0.2 }); - apply(&mut px, w, h, 0.0, -100.0, SRGB); - assert!(px[96 * w + 96][0] < 0.75, "{}", px[96 * w + 96][0]); - assert!((px[5 * w + 5][0] - 0.2).abs() < 0.01, "{}", px[5 * w + 5][0]); - } - - #[test] - fn smooth_gradients_stay_smooth() { - // A soft ramp over eight stops, as in an out-of-focus background. Coefficients interpolated - // between references too far apart drew contour lines across such ramps (Shadows +100 on - // a D4 raw): the output must rise steadily, without ripples. - let (w, h) = (640, 48); - let mut px = grey(w, h, |x, _| crate::photo_util::linear_to_srgb((x as f32 / (w - 1) as f32 * 8.0 - 9.0).exp2())); - for (s, hl) in [(100.0, 0.0), (0.0, -100.0), (-100.0, 100.0)] { - let mut p = px.clone(); - apply(&mut p, w, h, s, hl, SRGB); - let row: Vec = (0..w).map(|x| crate::photo_util::srgb_to_linear(p[24 * w + x][0]).max(1e-6).log2()).collect(); - let steps: Vec = row.windows(2).map(|d| d[1] - d[0]).collect(); - assert!(steps.iter().all(|d| *d > 0.0), "{s} {hl}: the ramp reverses"); - let jumps: Vec = steps.windows(2).map(|d| (d[1] - d[0]).abs()).collect(); - let ripple = jumps[16..jumps.len() - 16].iter().fold(0.0f32, |a, b| a.max(*b)); - // The ramp rises 0.0125 stops per pixel; its slope may change by a third at most. - assert!(ripple < 0.004, "{s} {hl}: slope jumps by {ripple} stops per pixel"); - } - px.clear(); - } - - #[test] - fn the_result_does_not_depend_on_the_image_size() { - let at = |n: usize| { - let mut px = grey(n, n, |x, y| if x < n / 3 || y < n / 4 { 0.08 } else { 0.7 }); - apply(&mut px, n, n, 70.0, -60.0, SRGB); - [px[(n / 8) * n + n / 8][0], px[(3 * n / 4) * n + 3 * n / 4][0]] - }; - let (a, b) = (at(96), at(384)); - assert!((a[0] - b[0]).abs() < 0.02 && (a[1] - b[1]).abs() < 0.02, "{a:?} {b:?}"); - } -} diff --git a/crates/algo/src/camera_raw/per_pixel.rs b/crates/algo/src/camera_raw/per_pixel.rs deleted file mode 100644 index ec88b92474..0000000000 --- a/crates/algo/src/camera_raw/per_pixel.rs +++ /dev/null @@ -1,284 +0,0 @@ -//! 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. -//! 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, DevelopInputs, Encoding, Wheel, calibration_neutral, curve_lut, grade_neutral, hsl_neutral, hsv_to_rgb, is_linear, luma, parametric_lut, - white_balance_gains, whites_blacks, -}; -use craft::imaging::raw::VignetteStyle as StoredStyle; - -pub use whites_blacks::Model as WhitesBlacksModel; - -/// Entries of the tone curve tables (parametric and point curves). -pub const CURVE_LUT: usize = 1024; -/// Samples of a Whites or Blacks curve row: grey levels 0, 1/32, …, 1. -pub const WB_STEPS: usize = whites_blacks::STEPS; - -/// White balance and exposure: channel gains in linear light, when the stage is on. -pub(crate) fn gains(p: &CameraRaw) -> Option<[f32; 3]> { - if p.temperature == 0.0 && p.tint == 0.0 && p.exposure == 0.0 { - return None; - } - let g = white_balance_gains(p.temperature, p.tint); - let norm = luma(g); - Some(g.map(|v| v / norm * 2f32.powf(p.exposure))) -} - -/// Contrast's strength, when Contrast is set (with or without Texture and Clarity). -fn contrast(p: &CameraRaw) -> Option { - (p.contrast != 0.0).then_some(p.contrast / 100.0 * 0.6) -} - -/// Whites and Blacks' tables, for an implementation that measures the image's points itself. -pub fn whites_blacks_model() -> WhitesBlacksModel { - whites_blacks::model() -} - -/// Whites and Blacks as two curve rows for the image's amounts. -#[derive(Clone, Debug, PartialEq)] -pub struct WhitesBlacks { - /// The Whites curve over grey levels 0, 1/32, …, 1, when Whites is set. - pub whites: Option<[f32; WB_STEPS]>, - /// The Blacks curve, applied after Whites. - pub blacks: Option<[f32; WB_STEPS]>, - /// The clipping directions (Whites up, Blacks down) curve each channel; the others scale the - /// pixel by the change of its luminance. - pub per_channel: bool, -} - -/// Color Grading's wheels resolved. -#[derive(Clone, Debug, PartialEq)] -pub struct Grade { - /// Colour offsets of the shadows, midtones, highlights and global wheels. - pub tints: [[f32; 3]; 4], - /// Luminance of the same wheels (slider units). - pub lums: [f32; 4], - pub blend: f32, - pub balance: f32, -} - -impl Grade { - pub(crate) fn new(p: &CameraRaw) -> Self { - let tint = |wh: &Wheel| -> [f32; 3] { - let c = hsv_to_rgb(wh.hue, 1.0, 1.0); - let l = luma(c); - [c[0] - l, c[1] - l, c[2] - l].map(|v| v * wh.sat / 100.0 * 0.3) - }; - Grade { - tints: [tint(&p.grade_shadows), tint(&p.grade_midtones), tint(&p.grade_highlights), tint(&p.grade_global)], - lums: [p.grade_shadows.lum, p.grade_midtones.lum, p.grade_highlights.lum, p.grade_global.lum], - blend: 0.15 + p.grade_blending.clamp(0.0, 100.0) / 100.0 * 0.35, - balance: p.grade_balance.clamp(-100.0, 100.0) / 100.0 * 0.25, - } - } -} - -/// The vignette's `vignette_style`. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum VignetteStyle { - HighlightPriority, - ColorPriority, - PaintOverlay, -} - -/// The post-crop vignette's shape on a `w × h` frame. -#[derive(Clone, Debug, PartialEq)] -pub struct Vignette { - /// −1 … 1. - pub amount: f32, - /// 0 … 1. - pub highlights: f32, - pub style: VignetteStyle, - /// Frame centre (pixels). - pub centre: [f32; 2], - /// Half axes of the shape (pixels). - pub axes: [f32; 2], - /// Exponent of the superellipse. - pub power: f32, - /// The mask's smoothstep edges in normalised radius. - pub edges: [f32; 2], -} - -impl Vignette { - pub(crate) fn new(w: usize, h: usize, p: &CameraRaw) -> Self { - let mid = p.vignette_midpoint.clamp(0.0, 100.0) / 100.0; - let feather = p.vignette_feather.clamp(0.0, 100.0) / 100.0; - let round = p.vignette_roundness.clamp(-100.0, 100.0) / 100.0; - let (cx, cy) = (w as f32 / 2.0, h as f32 / 2.0); - // Roundness: 0 follows the frame's aspect, +1 a circle, −1 a rounded rectangle. - let (ax, ay) = if round >= 0.0 { - let r = cx.min(cy) + (cx.max(cy) - cx.min(cy)) * (1.0 - round); - (if cx >= cy { r } else { cx }, if cy > cx { r } else { cy }) - } else { - (cx, cy) - }; - let inner = 1.0 - mid * 0.8; - Vignette { - amount: p.vignette_amount / 100.0, - highlights: p.vignette_highlights.clamp(0.0, 100.0) / 100.0, - style: match p.vignette_style { - StoredStyle::PaintOverlay => VignetteStyle::PaintOverlay, - StoredStyle::ColorPriority => VignetteStyle::ColorPriority, - _ => VignetteStyle::HighlightPriority, - }, - centre: [cx, cy], - axes: [ax, ay], - power: 2.0 + (-round).max(0.0) * 6.0, - edges: [inner - feather * 0.5 * inner, inner + feather * 0.5 * (1.4 - inner) + 0.02], - } - } -} - -/// Grain: value noise sampled in full-resolution coordinates. -#[derive(Clone, Debug, PartialEq)] -pub struct Grain { - /// Noise cell size (full-resolution pixels). - pub cell: f32, - /// Weight of the finer octave. - pub roughness: f32, - pub amount: f32, - pub seed: u64, - /// Full-resolution pixels per pixel (`1 / pixel_scale`). - pub scale: f32, -} - -impl Grain { - pub(crate) fn new(p: &CameraRaw, inputs: &DevelopInputs) -> Self { - Grain { - cell: 1.0 + p.grain_size / 25.0, - roughness: p.grain_roughness / 100.0, - amount: p.grain_amount / 100.0 * 0.12, - seed: u64::from(inputs.seed), - scale: 1.0 / inputs.pixel_scale.clamp(0.01, 1.0), - } - } -} - -/// Develop's per-pixel stages for one image and settings, in order. `None` stages are off. -#[derive(Clone, Debug, PartialEq)] -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, - /// 3. Shadows and Highlights: a local Laplacian filter of the whole frame, then each pixel's - /// light scaled by the change of its log luminance. - pub local_tone: Option, - /// 3. Clarity and Texture on the luminance clipped to 1, before Contrast. - pub clarity: Option, - pub texture: Option, - /// 3. Contrast's strength. - pub contrast: Option, - /// 3b. Whites and Blacks, in the document's encoding. - pub whites_blacks: Option, - /// 3b. Whites and Blacks to measure the image's points for (the sliders, −100 … 100), when 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. - pub encoding: f32, - /// 4. Vibrance and Saturation (slider / 100). - pub presence: Option<[f32; 2]>, - /// 5. The parametric tone curve, [`CURVE_LUT`] entries over 0 … 1. - pub parametric: Option>, - /// 5. Point curves: master, red, green, blue. - pub point: [Option>; 4], - /// 6. Color Mixer hue, saturation and luminance per band. - pub hsl: Option<[[f32; 8]; 3]>, - /// 7. Color Grading. - pub grade: Option, - /// 9. Vignette. - pub vignette: Option, - /// 9. Grain. - pub grain: Option, - /// Clip RGB to 0 … 1 at the end (all but 32-bit documents). - pub clamp: bool, -} - -/// Whether developing needs a stage that reads neighbouring pixels: Dehaze, Shadows and -/// Highlights, Texture, Clarity, sharpening or noise reduction. -pub fn spatial(p: &CameraRaw) -> bool { - p.dehaze != 0.0 || [p.highlights, p.shadows, p.texture, p.clarity].iter().any(|v| *v != 0.0) || detail_on(p) -} - -/// Whether developing needs Detail: sharpening or noise reduction. -fn detail_on(p: &CameraRaw) -> bool { - p.sharpen_amount > 0.0 || p.noise_luminance > 0.0 || p.noise_color > 0.0 -} - -/// The image's black and white points that Whites and Blacks adapt to, for `px` (`w × h`, -/// display-encoded) developed per pixel with `p`: what [`develop`](super::develop) measures -/// after white balance and Contrast. `None` when Whites and Blacks are 0 or `p` needs a -/// spatial stage. -pub fn white_black_points(px: &[[f32; 4]], w: usize, h: usize, p: &CameraRaw, inputs: &DevelopInputs) -> Option<(f32, f32)> { - if (p.whites == 0.0 && p.blacks == 0.0) || spatial(p) || px.len() != w.saturating_mul(h) { - return None; - } - let enc = Encoding::of(inputs.encoding_gamma); - let (g, k_con) = (gains(p), contrast(p)); - Some(super::luminance_points(px, w, h, enc, |q| { - let q = g.map_or(q, |g| super::balance(q, g)); - k_con.map_or(q, |k| super::contrast(q, k)) - })) -} - -/// 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, inputs: &DevelopInputs, w: usize, h: usize, float: bool, points: Option<(f32, f32)>) -> Option { - if detail_on(p) || !calibration_neutral(p) { - return None; - } - // The develop leaves frames under 2 pixels on a side alone. - let local_tone = if w >= 2 && h >= 2 { LocalTone::new(p.shadows, p.highlights) } else { None }; - // At 2 pixels on the short side the GPU pass's pyramid has one level, so the CPU develops it. - 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, inputs, 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 && 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); - (xw != 0.0 || xb != 0.0).then(|| WhitesBlacks { - whites: (xw != 0.0).then(|| whites_blacks::whites_row(xw)), - blacks: (xb != 0.0).then(|| whites_blacks::blacks_row(xb)), - per_channel: xw > 0.0 || xb < 0.0, - }) - } else { - None - }; - let parametric_on = !(p.curve_highlights == 0.0 && p.curve_lights == 0.0 && p.curve_darks == 0.0 && p.curve_shadows == 0.0); - 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, - encoding: Encoding::of(inputs.encoding_gamma).0, - presence: (p.vibrance != 0.0 || p.saturation != 0.0).then_some([p.vibrance / 100.0, p.saturation / 100.0]), - parametric: parametric_on.then(|| parametric_lut(p, CURVE_LUT)), - point: [pts(&p.point_curve), pts(&p.point_curve_red), pts(&p.point_curve_green), pts(&p.point_curve_blue)], - hsl: (!hsl_neutral(p)).then_some([p.hsl_hue, p.hsl_sat, p.hsl_lum]), - grade: (!grade_neutral(p)).then(|| Grade::new(p)), - vignette: (p.vignette_amount != 0.0).then(|| Vignette::new(w, h, p)), - grain: (p.grain_amount > 0.0).then(|| Grain::new(p, inputs)), - clamp: !float && !identity, - }) -} diff --git a/crates/algo/src/camera_raw/spatial.rs b/crates/algo/src/camera_raw/spatial.rs deleted file mode 100644 index 871830eecc..0000000000 --- a/crates/algo/src/camera_raw/spatial.rs +++ /dev/null @@ -1,191 +0,0 @@ -//! 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, DevelopInputs}; - -/// 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 { - 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 { - 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, -} - -impl Texture { - /// Texture for `p` on a `w × h` frame; `None` when it is off. - pub fn new(p: &CameraRaw, inputs: &DevelopInputs, w: usize, h: usize) -> Option { - if p.texture == 0.0 { - return None; - } - let ps = inputs.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 { - if sigma < 0.3 { - return Vec::new(); - } - crate::fxutil::gauss_box_radii(sigma).to_vec() -} - -#[cfg(test)] -mod tests { - use super::*; - - /// `CameraRaw` with the named fields set (the type is `#[non_exhaustive]`, so no struct expression), or a copy of a base with them set. - macro_rules! cr { - ($($f:ident : $v:expr),* $(,)?) => {{ - let mut s = CameraRaw::default(); - $(s.$f = $v;)* - s - }}; - ($base:expr => $($f:ident : $v:expr),* $(,)?) => {{ - let mut s: CameraRaw = $base; - $(s.$f = $v;)* - s - }}; - } - - #[test] - fn stages_resolve_for_the_dialogs_proxy_and_are_off_at_zero() { - let p = cr! { dehaze: 40.0, clarity: -50.0, texture: 50.0}; - let scale = |pixel_scale| DevelopInputs { pixel_scale, ..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, &scale(0.143), 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(&cr! { texture: 10.0}, &scale(0.1), 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, &scale(1.0), 858, 572).is_none()); - } - - #[test] - fn dehaze_cells_average_blocks_after_white_balance_and_refuse_a_wrong_size() { - let d = Dehaze::new(&cr! { dehaze: 10.0}, 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()); - } -} diff --git a/crates/algo/src/camera_raw/whites_blacks.rs b/crates/algo/src/camera_raw/whites_blacks.rs deleted file mode 100644 index 2300a43362..0000000000 --- a/crates/algo/src/camera_raw/whites_blacks.rs +++ /dev/null @@ -1,494 +0,0 @@ -//! Whites and Blacks as Adobe Camera Raw (process version 2012) applies them. -//! -//! Measured as a black box on the Camera Raw Filter of Photoshop 25.4: grey blocks with chosen -//! histograms went through the filter by script and came back exactly; no Adobe code or data -//! was used. -//! -//! - Both are global curves of the grey level, applied after Shadows and Highlights, Whites -//! first. On an image whose darkest and lightest percent reach black and white the curve of a -//! slider value `x` is the measured row at `x` of [`WHITES`] or [`BLACKS`]. -//! - The direction that only compresses (Whites down, Blacks up) is that fixed curve on every -//! image. The direction that clips (Whites up, Blacks down) adapts: the row used is -//! `x · A(BP, WP)`. On the block images BP and WP are their darkest and lightest levels; on -//! photographs Photoshop's amounts follow best with BP the 3rd percentile of the luminance and -//! WP the 99.5th of the brightest channel, and Blacks at least 1.2 times. A low -//! white point makes Whites +100 stronger (up to 2.7 times), a raised black point Blacks -//! (up to 1.45 times at −40). Whites rows past +100 come from images where `A > 1`. -//! - Not reproduced: past −40 Photoshop's Blacks grows faster on images with a raised black -//! point (on one spanning 0.6–1 its −100 blacks out everything below 0.74, here below about -//! 0.15); its curves there are not rows of the full-range family. -//! - Colour: the clipping directions act on each channel, the compressing ones scale the pixel -//! by the curve's change of its luminance (closest to Photoshop on saturated colours). - -use super::Encoding; -use crate::photo_util::par_rows; - -/// Grey levels the curves are sampled at: 0, 1/32, …, 1 (sRGB-encoded). -pub(crate) const STEPS: usize = 33; -/// The first row's internal amount; rows are [`ROW_STEP`] apart. -const WHITES_FROM: f32 = -100.0; -const BLACKS_FROM: f32 = -100.0; -const ROW_STEP: f32 = 10.0; -/// The image's points are measured on cells of a copy at most this many pixels across. -pub(crate) const POINTS_SIDE: usize = 256; -/// The black point's quantile of the cells' luminance, the white point's of their brightest -/// channel. -pub(crate) const POINT_QUANTILES: [f32; 2] = [0.03, 0.995]; -/// Internal amounts the sliders reach: Whites, then Blacks. -const WHITES_RANGE: [f32; 2] = [-100.0, 270.0]; -const BLACKS_RANGE: [f32; 2] = [-100.0, 100.0]; - -/// Whites and Blacks' tables and how an image's points choose from them, for another -/// implementation (the GPU preview measures the points after Shadows and Highlights itself). -#[derive(Clone, Copy, Debug)] -pub struct Model { - /// Whites curves over grey levels 0, 1/32, …, 1, at internal amounts `whites_from`, - /// `whites_from + row_step`, …. - pub whites: &'static [[f32; STEPS]], - pub whites_from: f32, - /// Blacks curves, likewise. - pub blacks: &'static [[f32; STEPS]], - pub blacks_from: f32, - pub row_step: f32, - /// Black points and white points of the adaptation tables' rows and columns. - pub black_points: &'static [f32], - pub white_points: &'static [f32], - /// How much the clipping directions adapt (Whites up, Blacks down), by black and white point. - pub whites_adapt: &'static [[f32; 8]; 9], - pub blacks_adapt: &'static [[f32; 8]; 9], - /// The least Blacks adaptation on photographs. - pub photo_blacks: f32, - /// Internal amounts the Whites and Blacks sliders reach. - pub whites_range: [f32; 2], - pub blacks_range: [f32; 2], - /// See [`POINTS_SIDE`] and [`POINT_QUANTILES`]. - pub points_side: usize, - pub point_quantiles: [f32; 2], -} - -/// The tables [`amounts`], [`whites_row`] and [`blacks_row`] read. -pub(crate) fn model() -> Model { - Model { - whites: &WHITES, - whites_from: WHITES_FROM, - blacks: &BLACKS, - blacks_from: BLACKS_FROM, - row_step: ROW_STEP, - black_points: &BPS, - white_points: &WPS, - whites_adapt: &AW, - blacks_adapt: &AB, - photo_blacks: PHOTO_BLACKS, - whites_range: WHITES_RANGE, - blacks_range: BLACKS_RANGE, - points_side: POINTS_SIDE, - point_quantiles: POINT_QUANTILES, - } -} -// Measured levels; some happen to lie near π/8 and π/4. -/// Whites curves at internal amounts -100, -90, …, 270 (rows) over grey levels 0, 1/32, …, 1. -#[allow(clippy::approx_constant)] -static WHITES: [[f32; 33]; 38] = [ - [ - 0.0000, 0.0298, 0.0621, 0.0926, 0.1226, 0.1523, 0.1817, 0.2107, 0.2391, 0.2671, 0.2946, 0.3215, 0.3480, 0.3738, 0.3995, 0.4256, 0.4517, 0.4774, 0.5028, - 0.5278, 0.5524, 0.5768, 0.6008, 0.6245, 0.6482, 0.6717, 0.6957, 0.7207, 0.7483, 0.7814, 0.8263, 0.8949, 0.9999, - ], - [ - 0.0000, 0.0298, 0.0621, 0.0926, 0.1226, 0.1523, 0.1817, 0.2107, 0.2392, 0.2672, 0.2947, 0.3217, 0.3482, 0.3742, 0.4000, 0.4263, 0.4526, 0.4785, 0.5042, - 0.5296, 0.5548, 0.5797, 0.6044, 0.6291, 0.6539, 0.6789, 0.7046, 0.7317, 0.7617, 0.7969, 0.8425, 0.9074, 0.9999, - ], - [ - 0.0000, 0.0298, 0.0621, 0.0926, 0.1226, 0.1524, 0.1818, 0.2108, 0.2393, 0.2673, 0.2950, 0.3221, 0.3487, 0.3748, 0.4008, 0.4274, 0.4540, 0.4803, 0.5064, - 0.5323, 0.5580, 0.5837, 0.6093, 0.6350, 0.6610, 0.6875, 0.7149, 0.7438, 0.7756, 0.8122, 0.8576, 0.9184, 0.9999, - ], - [ - 0.0000, 0.0298, 0.0621, 0.0926, 0.1226, 0.1524, 0.1818, 0.2109, 0.2395, 0.2677, 0.2954, 0.3227, 0.3495, 0.3759, 0.4022, 0.4291, 0.4561, 0.4828, 0.5094, - 0.5360, 0.5624, 0.5888, 0.6154, 0.6423, 0.6695, 0.6973, 0.7261, 0.7566, 0.7897, 0.8271, 0.8716, 0.9280, 0.9999, - ], - [ - 0.0000, 0.0298, 0.0621, 0.0926, 0.1226, 0.1525, 0.1820, 0.2111, 0.2398, 0.2682, 0.2961, 0.3237, 0.3508, 0.3775, 0.4042, 0.4317, 0.4591, 0.4864, 0.5136, - 0.5408, 0.5680, 0.5953, 0.6229, 0.6508, 0.6791, 0.7082, 0.7382, 0.7698, 0.8037, 0.8412, 0.8843, 0.9365, 0.9999, - ], - [ - 0.0000, 0.0298, 0.0621, 0.0927, 0.1227, 0.1527, 0.1822, 0.2116, 0.2404, 0.2690, 0.2972, 0.3251, 0.3527, 0.3799, 0.4071, 0.4351, 0.4630, 0.4910, 0.5189, - 0.5469, 0.5749, 0.6031, 0.6316, 0.6605, 0.6899, 0.7199, 0.7509, 0.7832, 0.8174, 0.8544, 0.8958, 0.9439, 0.9999, - ], - [ - 0.0000, 0.0298, 0.0621, 0.0927, 0.1229, 0.1529, 0.1827, 0.2122, 0.2414, 0.2702, 0.2989, 0.3272, 0.3553, 0.3831, 0.4110, 0.4396, 0.4682, 0.4968, 0.5254, - 0.5542, 0.5830, 0.6121, 0.6414, 0.6712, 0.7014, 0.7322, 0.7637, 0.7964, 0.8305, 0.8668, 0.9062, 0.9503, 0.9999, - ], - [ - 0.0000, 0.0298, 0.0622, 0.0928, 0.1231, 0.1534, 0.1834, 0.2132, 0.2427, 0.2720, 0.3011, 0.3300, 0.3587, 0.3872, 0.4160, 0.4452, 0.4745, 0.5038, 0.5332, - 0.5627, 0.5923, 0.6221, 0.6522, 0.6826, 0.7134, 0.7447, 0.7765, 0.8092, 0.8429, 0.8781, 0.9155, 0.9559, 1.0000, - ], - [ - 0.0000, 0.0298, 0.0623, 0.0930, 0.1236, 0.1541, 0.1844, 0.2145, 0.2445, 0.2744, 0.3041, 0.3337, 0.3632, 0.3925, 0.4221, 0.4520, 0.4820, 0.5120, 0.5421, - 0.5723, 0.6026, 0.6330, 0.6636, 0.6946, 0.7257, 0.7572, 0.7890, 0.8214, 0.8545, 0.8885, 0.9237, 0.9608, 1.0000, - ], - [ - 0.0000, 0.0298, 0.0624, 0.0934, 0.1242, 0.1551, 0.1858, 0.2164, 0.2470, 0.2775, 0.3080, 0.3383, 0.3687, 0.3989, 0.4293, 0.4600, 0.4906, 0.5213, 0.5520, - 0.5827, 0.6136, 0.6445, 0.6755, 0.7067, 0.7380, 0.7694, 0.8011, 0.8330, 0.8652, 0.8978, 0.9310, 0.9651, 1.0000, - ], - [ - 0.0000, 0.0312, 0.0625, 0.0938, 0.1250, 0.1562, 0.1875, 0.2188, 0.2500, 0.2812, 0.3125, 0.3438, 0.3750, 0.4062, 0.4375, 0.4688, 0.5000, 0.5312, 0.5625, - 0.5938, 0.6250, 0.6562, 0.6875, 0.7188, 0.7500, 0.7812, 0.8125, 0.8438, 0.8750, 0.9062, 0.9375, 0.9688, 1.0000, - ], - [ - 0.0000, 0.0299, 0.0626, 0.0940, 0.1253, 0.1567, 0.1881, 0.2195, 0.2510, 0.2825, 0.3140, 0.3456, 0.3772, 0.4089, 0.4405, 0.4720, 0.5036, 0.5351, 0.5667, - 0.5983, 0.6298, 0.6613, 0.6929, 0.7244, 0.7559, 0.7874, 0.8189, 0.8503, 0.8816, 0.9128, 0.9438, 0.9742, 1.0000, - ], - [ - 0.0000, 0.0299, 0.0627, 0.0941, 0.1257, 0.1573, 0.1890, 0.2208, 0.2526, 0.2846, 0.3167, 0.3488, 0.3811, 0.4134, 0.4456, 0.4777, 0.5098, 0.5419, 0.5741, - 0.6062, 0.6383, 0.6704, 0.7025, 0.7345, 0.7664, 0.7983, 0.8301, 0.8617, 0.8931, 0.9241, 0.9543, 0.9829, 1.0000, - ], - [ - 0.0000, 0.0299, 0.0628, 0.0944, 0.1262, 0.1582, 0.1903, 0.2225, 0.2550, 0.2876, 0.3204, 0.3534, 0.3867, 0.4200, 0.4529, 0.4858, 0.5186, 0.5516, 0.5845, - 0.6174, 0.6502, 0.6830, 0.7157, 0.7482, 0.7807, 0.8131, 0.8451, 0.8769, 0.9082, 0.9385, 0.9673, 0.9928, 1.0000, - ], - [ - 0.0000, 0.0299, 0.0629, 0.0948, 0.1269, 0.1594, 0.1920, 0.2249, 0.2582, 0.2917, 0.3256, 0.3597, 0.3942, 0.4289, 0.4628, 0.4966, 0.5305, 0.5644, 0.5983, - 0.6321, 0.6658, 0.6994, 0.7327, 0.7660, 0.7989, 0.8316, 0.8639, 0.8956, 0.9263, 0.9553, 0.9815, 1.0000, 1.0000, - ], - [ - 0.0000, 0.0299, 0.0631, 0.0953, 0.1280, 0.1610, 0.1944, 0.2282, 0.2625, 0.2973, 0.3325, 0.3683, 0.4045, 0.4407, 0.4758, 0.5109, 0.5460, 0.5811, 0.6161, - 0.6510, 0.6857, 0.7201, 0.7541, 0.7879, 0.8213, 0.8543, 0.8864, 0.9175, 0.9468, 0.9733, 0.9950, 1.0000, 1.0000, - ], - [ - 0.0000, 0.0299, 0.0633, 0.0961, 0.1293, 0.1632, 0.1976, 0.2327, 0.2684, 0.3048, 0.3419, 0.3798, 0.4183, 0.4562, 0.4928, 0.5294, 0.5660, 0.6024, 0.6387, - 0.6748, 0.7104, 0.7456, 0.7803, 0.8145, 0.8480, 0.8807, 0.9121, 0.9417, 0.9684, 0.9907, 1.0000, 1.0000, 1.0000, - ], - [ - 0.0000, 0.0300, 0.0637, 0.0971, 0.1313, 0.1663, 0.2020, 0.2387, 0.2763, 0.3149, 0.3546, 0.3952, 0.4365, 0.4763, 0.5149, 0.5532, 0.5914, 0.6294, 0.6670, - 0.7041, 0.7406, 0.7763, 0.8113, 0.8456, 0.8788, 0.9104, 0.9401, 0.9667, 0.9888, 1.0000, 1.0000, 1.0000, 1.0000, - ], - [ - 0.0000, 0.0300, 0.0641, 0.0984, 0.1338, 0.1703, 0.2079, 0.2468, 0.2870, 0.3286, 0.3717, 0.4161, 0.4602, 0.5024, 0.5430, 0.5833, 0.6232, 0.6627, 0.7015, - 0.7394, 0.7764, 0.8123, 0.8472, 0.8808, 0.9126, 0.9420, 0.9681, 0.9896, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, - ], - [ - 0.0000, 0.0302, 0.0647, 0.1003, 0.1374, 0.1760, 0.2160, 0.2579, 0.3016, 0.3472, 0.3949, 0.4436, 0.4908, 0.5355, 0.5784, 0.6207, 0.6622, 0.7029, 0.7424, - 0.7806, 0.8176, 0.8530, 0.8868, 0.9185, 0.9474, 0.9726, 0.9926, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, - ], - [ - 0.0000, 0.0304, 0.0656, 0.1029, 0.1423, 0.1837, 0.2271, 0.2731, 0.3215, 0.3726, 0.4262, 0.4791, 0.5294, 0.5769, 0.6220, 0.6660, 0.7086, 0.7498, 0.7893, - 0.8272, 0.8631, 0.8969, 0.9281, 0.9560, 0.9795, 0.9967, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, - ], - [ - 0.0000, 0.0305, 0.0679, 0.1094, 0.1509, 0.1968, 0.2459, 0.2956, 0.3510, 0.4094, 0.4680, 0.5248, 0.5781, 0.6278, 0.6742, 0.7195, 0.7624, 0.8031, 0.8417, - 0.8779, 0.9113, 0.9414, 0.9675, 0.9886, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, - ], - [ - 0.0000, 0.0306, 0.0702, 0.1160, 0.1623, 0.2144, 0.2709, 0.3243, 0.3885, 0.4556, 0.5199, 0.5807, 0.6369, 0.6884, 0.7355, 0.7799, 0.8217, 0.8606, 0.8964, - 0.9288, 0.9570, 0.9803, 0.9958, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, - ], - [ - 0.0000, 0.0308, 0.0725, 0.1225, 0.1737, 0.2320, 0.2960, 0.3641, 0.4393, 0.5133, 0.5825, 0.6460, 0.7032, 0.7544, 0.8003, 0.8426, 0.8817, 0.9168, 0.9475, - 0.9733, 0.9924, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, - ], - [ - 0.0000, 0.0322, 0.0751, 0.1303, 0.1918, 0.2594, 0.3348, 0.4189, 0.5044, 0.5841, 0.6565, 0.7208, 0.7771, 0.8262, 0.8692, 0.9074, 0.9408, 0.9686, 0.9900, - 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, - ], - [ - 0.0000, 0.0331, 0.0818, 0.1482, 0.2171, 0.2977, 0.3892, 0.4865, 0.5779, 0.6602, 0.7322, 0.7943, 0.8470, 0.8915, 0.9286, 0.9600, 0.9844, 0.9996, 1.0000, - 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, - ], - [ - 0.0000, 0.0340, 0.0884, 0.1661, 0.2544, 0.3540, 0.4658, 0.5729, 0.6681, 0.7496, 0.8183, 0.8748, 0.9208, 0.9568, 0.9832, 1.0000, 1.0000, 1.0000, 1.0000, - 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, - ], - [ - 0.0000, 0.3356, 0.5799, 0.6166, 0.6166, 0.6166, 0.6166, 0.6624, 0.7556, 0.8321, 0.8935, 0.9411, 0.9755, 0.9970, 0.9998, 1.0000, 1.0000, 1.0000, 1.0000, - 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, - ], - [ - 0.0000, 0.5007, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, - 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, - ], - [ - 0.0000, 0.1655, 0.1655, 0.2972, 0.4728, 0.6327, 0.7616, 0.8598, 0.9317, 0.9790, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, - 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, - ], - [ - 0.0000, 0.0457, 0.1830, 0.3836, 0.5790, 0.7379, 0.8549, 0.9360, 0.9869, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, - 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, - ], - [ - 0.0000, 0.0520, 0.2329, 0.4864, 0.6989, 0.8449, 0.9403, 0.9884, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, - 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, - ], - [ - 0.0000, 0.0773, 0.3027, 0.6040, 0.8058, 0.9302, 0.9930, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, - 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, - ], - [ - 0.0000, 0.1454, 0.4738, 0.7615, 0.9074, 0.9908, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, - 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, - ], - [ - 0.0000, 0.0964, 0.5416, 0.8589, 0.9897, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, - 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, - ], - [ - 0.1538, 0.1538, 0.7080, 0.9596, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, - 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, - ], - [ - 0.8439, 0.8439, 0.8439, 0.9993, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, - 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, - ], - [ - 0.9228, 0.9228, 0.9228, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, - 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, - ], -]; -/// Blacks curves at internal amounts -100, …, 100 in steps of 10. -#[allow(clippy::approx_constant)] -static BLACKS: [[f32; 33]; 21] = [ - [ - 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0290, 0.0572, 0.0879, 0.1222, 0.1580, 0.1935, 0.2287, 0.2636, 0.2988, 0.3355, 0.3741, 0.4151, 0.4571, - 0.4990, 0.5406, 0.5818, 0.6226, 0.6631, 0.7031, 0.7424, 0.7811, 0.8192, 0.8568, 0.8937, 0.9300, 0.9655, 1.0000, - ], - [ - 0.0000, 0.0000, 0.0000, 0.0000, 0.0015, 0.0363, 0.0640, 0.0956, 0.1300, 0.1651, 0.2000, 0.2345, 0.2686, 0.3026, 0.3369, 0.3727, 0.4105, 0.4495, 0.4885, - 0.5272, 0.5657, 0.6039, 0.6419, 0.6796, 0.7169, 0.7538, 0.7903, 0.8264, 0.8621, 0.8974, 0.9322, 0.9664, 1.0000, - ], - [ - 0.0000, 0.0000, 0.0000, 0.0000, 0.0346, 0.0625, 0.0934, 0.1271, 0.1616, 0.1959, 0.2298, 0.2635, 0.2969, 0.3301, 0.3638, 0.3990, 0.4357, 0.4727, 0.5094, - 0.5460, 0.5824, 0.6187, 0.6547, 0.6906, 0.7262, 0.7615, 0.7965, 0.8313, 0.8657, 0.8998, 0.9336, 0.9671, 1.0000, - ], - [ - 0.0000, 0.0000, 0.0000, 0.0235, 0.0554, 0.0850, 0.1175, 0.1514, 0.1852, 0.2187, 0.2519, 0.2849, 0.3178, 0.3505, 0.3837, 0.4183, 0.4537, 0.4891, 0.5243, - 0.5594, 0.5944, 0.6292, 0.6639, 0.6985, 0.7329, 0.7671, 0.8010, 0.8347, 0.8683, 0.9016, 0.9347, 0.9676, 1.0000, - ], - [ - 0.0000, 0.0000, 0.0020, 0.0438, 0.0724, 0.1035, 0.1365, 0.1699, 0.2030, 0.2359, 0.2686, 0.3011, 0.3336, 0.3659, 0.3986, 0.4327, 0.4669, 0.5011, 0.5352, - 0.5692, 0.6031, 0.6369, 0.6706, 0.7043, 0.7378, 0.7711, 0.8043, 0.8373, 0.8702, 0.9029, 0.9355, 0.9679, 1.0000, - ], - [ - 0.0000, 0.0000, 0.0230, 0.0567, 0.0865, 0.1182, 0.1510, 0.1839, 0.2164, 0.2489, 0.2812, 0.3133, 0.3455, 0.3775, 0.4100, 0.4433, 0.4767, 0.5100, 0.5433, - 0.5765, 0.6096, 0.6426, 0.6756, 0.7086, 0.7414, 0.7741, 0.8067, 0.8392, 0.8716, 0.9039, 0.9361, 0.9682, 1.0000, - ], - [ - 0.0000, 0.0000, 0.0368, 0.0670, 0.0976, 0.1294, 0.1619, 0.1943, 0.2265, 0.2586, 0.2906, 0.3225, 0.3544, 0.3862, 0.4184, 0.4512, 0.4839, 0.5166, 0.5492, - 0.5818, 0.6144, 0.6469, 0.6793, 0.7117, 0.7441, 0.7763, 0.8085, 0.8406, 0.8727, 0.9046, 0.9365, 0.9683, 1.0000, - ], - [ - 0.0000, 0.0000, 0.0444, 0.0749, 0.1058, 0.1377, 0.1699, 0.2020, 0.2339, 0.2657, 0.2975, 0.3292, 0.3609, 0.3926, 0.4245, 0.4568, 0.4891, 0.5213, 0.5535, - 0.5857, 0.6179, 0.6499, 0.6820, 0.7140, 0.7460, 0.7779, 0.8098, 0.8416, 0.8734, 0.9052, 0.9368, 0.9685, 1.0000, - ], - [ - 0.0000, 0.0086, 0.0511, 0.0817, 0.1128, 0.1445, 0.1763, 0.2080, 0.2397, 0.2713, 0.3029, 0.3344, 0.3660, 0.3975, 0.4292, 0.4611, 0.4930, 0.5249, 0.5567, - 0.5886, 0.6204, 0.6522, 0.6839, 0.7157, 0.7475, 0.7791, 0.8108, 0.8424, 0.8740, 0.9056, 0.9371, 0.9686, 1.0000, - ], - [ - 0.0000, 0.0198, 0.0564, 0.0874, 0.1186, 0.1501, 0.1817, 0.2133, 0.2447, 0.2762, 0.3076, 0.3390, 0.3705, 0.4018, 0.4333, 0.4649, 0.4965, 0.5281, 0.5597, - 0.5912, 0.6227, 0.6543, 0.6858, 0.7173, 0.7488, 0.7802, 0.8117, 0.8431, 0.8745, 0.9059, 0.9373, 0.9686, 1.0000, - ], - [ - 0.0000, 0.0312, 0.0625, 0.0938, 0.1250, 0.1562, 0.1875, 0.2188, 0.2500, 0.2812, 0.3125, 0.3438, 0.3750, 0.4062, 0.4375, 0.4688, 0.5000, 0.5312, 0.5625, - 0.5938, 0.6250, 0.6562, 0.6875, 0.7188, 0.7500, 0.7812, 0.8125, 0.8438, 0.8750, 0.9062, 0.9375, 0.9688, 1.0000, - ], - [ - 0.0000, 0.0313, 0.0650, 0.0979, 0.1303, 0.1624, 0.1942, 0.2260, 0.2576, 0.2891, 0.3206, 0.3520, 0.3833, 0.4146, 0.4455, 0.4763, 0.5070, 0.5378, 0.5684, - 0.5991, 0.6298, 0.6605, 0.6912, 0.7219, 0.7526, 0.7833, 0.8141, 0.8450, 0.8758, 0.9067, 0.9377, 0.9688, 1.0000, - ], - [ - 0.0000, 0.0326, 0.0677, 0.1022, 0.1357, 0.1686, 0.2010, 0.2332, 0.2652, 0.2969, 0.3286, 0.3601, 0.3915, 0.4227, 0.4532, 0.4835, 0.5138, 0.5440, 0.5741, - 0.6042, 0.6344, 0.6645, 0.6946, 0.7248, 0.7550, 0.7853, 0.8156, 0.8461, 0.8766, 0.9072, 0.9380, 0.9689, 1.0000, - ], - [ - 0.0000, 0.0341, 0.0706, 0.1066, 0.1413, 0.1749, 0.2079, 0.2405, 0.2728, 0.3048, 0.3366, 0.3682, 0.3996, 0.4307, 0.4608, 0.4906, 0.5203, 0.5500, 0.5796, - 0.6092, 0.6387, 0.6683, 0.6979, 0.7276, 0.7573, 0.7871, 0.8170, 0.8472, 0.8773, 0.9077, 0.9382, 0.9690, 1.0000, - ], - [ - 0.0000, 0.0354, 0.0736, 0.1113, 0.1472, 0.1814, 0.2149, 0.2479, 0.2805, 0.3127, 0.3446, 0.3763, 0.4077, 0.4385, 0.4681, 0.4974, 0.5267, 0.5558, 0.5849, - 0.6139, 0.6429, 0.6720, 0.7011, 0.7303, 0.7595, 0.7889, 0.8184, 0.8481, 0.8780, 0.9081, 0.9384, 0.9690, 1.0000, - ], - [ - 0.0000, 0.0368, 0.0768, 0.1162, 0.1531, 0.1881, 0.2221, 0.2554, 0.2882, 0.3206, 0.3527, 0.3843, 0.4158, 0.4461, 0.4753, 0.5041, 0.5328, 0.5615, 0.5900, - 0.6185, 0.6470, 0.6755, 0.7041, 0.7328, 0.7616, 0.7906, 0.8197, 0.8491, 0.8787, 0.9085, 0.9386, 0.9691, 1.0000, - ], - [ - 0.0000, 0.0381, 0.0802, 0.1214, 0.1593, 0.1949, 0.2293, 0.2630, 0.2961, 0.3286, 0.3607, 0.3924, 0.4236, 0.4536, 0.4823, 0.5106, 0.5388, 0.5669, 0.5949, - 0.6229, 0.6509, 0.6789, 0.7070, 0.7352, 0.7636, 0.7922, 0.8209, 0.8500, 0.8793, 0.9089, 0.9388, 0.9691, 1.0000, - ], - [ - 0.0000, 0.0394, 0.0837, 0.1267, 0.1656, 0.2018, 0.2367, 0.2707, 0.3039, 0.3365, 0.3686, 0.4003, 0.4314, 0.4608, 0.4890, 0.5168, 0.5445, 0.5721, 0.5996, - 0.6271, 0.6546, 0.6822, 0.7098, 0.7375, 0.7655, 0.7937, 0.8221, 0.8509, 0.8799, 0.9092, 0.9390, 0.9692, 1.0000, - ], - [ - 0.0000, 0.0407, 0.0875, 0.1322, 0.1720, 0.2088, 0.2441, 0.2784, 0.3118, 0.3444, 0.3765, 0.4082, 0.4389, 0.4679, 0.4955, 0.5229, 0.5501, 0.5771, 0.6042, - 0.6312, 0.6582, 0.6853, 0.7124, 0.7398, 0.7673, 0.7952, 0.8233, 0.8517, 0.8804, 0.9096, 0.9391, 0.9692, 1.0000, - ], - [ - 0.0000, 0.0421, 0.0915, 0.1379, 0.1786, 0.2160, 0.2516, 0.2861, 0.3196, 0.3523, 0.3844, 0.4159, 0.4462, 0.4747, 0.5019, 0.5287, 0.5554, 0.5820, 0.6085, - 0.6351, 0.6616, 0.6882, 0.7149, 0.7419, 0.7690, 0.7965, 0.8243, 0.8524, 0.8810, 0.9099, 0.9393, 0.9693, 1.0000, - ], - [ - 0.0000, 0.0436, 0.0957, 0.1438, 0.1853, 0.2232, 0.2592, 0.2938, 0.3274, 0.3601, 0.3922, 0.4235, 0.4533, 0.4813, 0.5080, 0.5343, 0.5605, 0.5866, 0.6127, - 0.6387, 0.6648, 0.6910, 0.7173, 0.7439, 0.7707, 0.7978, 0.8253, 0.8532, 0.8815, 0.9102, 0.9394, 0.9693, 1.0000, - ], -]; -const BPS: [f32; 9] = [0.0000, 0.0200, 0.0500, 0.1000, 0.2000, 0.3000, 0.4500, 0.6000, 0.8000]; -const WPS: [f32; 8] = [0.1000, 0.2000, 0.3000, 0.4500, 0.6000, 0.8000, 0.9000, 1.0000]; -static AW: [[f32; 8]; 9] = [ - [1.7750, 2.3875, 2.4000, 2.1625, 1.9438, 1.6125, 1.3875, 1.0000], - [1.8125, 2.5250, 2.3937, 2.1688, 1.9375, 1.6062, 1.3938, 0.9875], - [2.7000, 2.4688, 2.2750, 2.0688, 1.8875, 1.6000, 1.3875, 0.9938], - [2.3250, 2.3250, 2.1875, 1.9750, 1.7937, 1.5188, 1.3250, 1.0437], - [2.0187, 2.0187, 2.0187, 1.8625, 1.7063, 1.4062, 1.2250, 0.9250], - [1.7500, 1.7500, 1.7500, 1.7500, 1.6438, 1.3562, 1.1687, 0.8625], - [1.4937, 1.4937, 1.4937, 1.4937, 1.4937, 1.2875, 1.1000, 0.7875], - [1.1687, 1.1687, 1.1687, 1.1687, 1.1687, 1.1687, 1.0375, 0.7562], - [0.8250, 0.8250, 0.8250, 0.8250, 0.8250, 0.8250, 0.8250, 0.7562], -]; -static AB: [[f32; 8]; 9] = [ - [0.9938, 0.9812, 1.0000, 1.0125, 0.9563, 0.9688, 1.0437, 1.0000], - [1.0437, 1.0250, 1.0125, 1.0000, 1.0000, 1.0375, 1.0000, 0.9938], - [1.2312, 1.2063, 1.1875, 1.1625, 1.1438, 1.1438, 1.1375, 1.1250], - [1.2500, 1.2500, 1.2312, 1.2125, 1.2125, 1.2375, 1.2375, 1.2375], - [1.1750, 1.1750, 1.1750, 1.1750, 1.2063, 1.2688, 1.3125, 1.3375], - [1.1812, 1.1812, 1.1812, 1.1812, 1.2125, 1.2812, 1.3313, 1.4125], - [1.2375, 1.2375, 1.2375, 1.2375, 1.2375, 1.3062, 1.3562, 1.4375], - [1.3250, 1.3250, 1.3250, 1.3250, 1.3250, 1.3250, 1.3687, 1.4500], - [1.3938, 1.3938, 1.3938, 1.3938, 1.3938, 1.3938, 1.3938, 1.4312], -]; - -/// A curve row at a fractional internal amount `x`, at grey level `v` (both interpolated). -fn curve(rows: &[[f32; STEPS]], from: f32, x: f32, v: f32) -> f32 { - if v >= 1.0 { - return 1.0; - } - let r = ((x - from) / ROW_STEP).clamp(0.0, (rows.len() - 1) as f32); - let i = (r as usize).min(rows.len() - 2); - let t = r - i as f32; - let at = |row: &[f32; STEPS]| { - let p = v.max(0.0) * (STEPS - 1) as f32; - let j = (p as usize).min(STEPS - 2); - let s = p - j as f32; - row[j] + (row[j + 1] - row[j]) * s - }; - at(&rows[i]) * (1.0 - t) + at(&rows[i + 1]) * t -} - -/// The curve at a fractional internal amount `x` as one row: `curve(rows, from, x, v)` is this -/// row interpolated at `v`, because both interpolations are linear. -fn row_at(rows: &[[f32; STEPS]], from: f32, x: f32) -> [f32; STEPS] { - let r = ((x - from) / ROW_STEP).clamp(0.0, (rows.len() - 1) as f32); - let i = (r as usize).min(rows.len() - 2); - let t = r - i as f32; - std::array::from_fn(|j| rows[i][j] * (1.0 - t) + rows[i + 1][j] * t) -} - -/// The Whites curve at internal amount `x` as a row over grey levels 0, 1/32, …, 1. -pub(crate) fn whites_row(x: f32) -> [f32; STEPS] { - row_at(&WHITES, WHITES_FROM, x) -} - -/// The Blacks curve at internal amount `x` as a row over grey levels 0, 1/32, …, 1. -pub(crate) fn blacks_row(x: f32) -> [f32; STEPS] { - row_at(&BLACKS, BLACKS_FROM, x) -} - -/// Whites at internal amount `x` (−100 … 270) of grey level `v`. -pub(crate) fn whites(v: f32, x: f32) -> f32 { - curve(&WHITES, WHITES_FROM, x, v) -} - -/// Blacks at internal amount `x` (−100 … 100) of grey level `v`. -pub(crate) fn blacks(v: f32, x: f32) -> f32 { - curve(&BLACKS, BLACKS_FROM, x, v) -} - -/// The least Blacks adaptation on photographs. -const PHOTO_BLACKS: f32 = 1.2; - -/// Bilinear lookup of an adaptation table at black point `bp` and white point `wp`. -fn adapt(table: &[[f32; 8]; 9], bp: f32, wp: f32) -> f32 { - let idx = |grid: &[f32], v: f32| { - let v = v.clamp(grid[0], grid[grid.len() - 1]); - let i = grid.windows(2).position(|w| v <= w[1]).unwrap_or(grid.len() - 2); - (i, (v - grid[i]) / (grid[i + 1] - grid[i])) - }; - let (i, s) = idx(&BPS, bp); - let (j, t) = idx(&WPS, wp); - let row = |i: usize| table[i][j] * (1.0 - t) + table[i][j + 1] * t; - row(i) * (1.0 - s) + row(i + 1) * s -} - -/// The internal amounts of the Whites and Blacks sliders (−100 … 100) for an image whose 1st -/// and 99th luminance percentiles are the grey levels `bp` and `wp` (sRGB-encoded). -pub(crate) fn amounts(whites: f32, blacks: f32, bp: f32, wp: f32) -> (f32, f32) { - let w = if whites > 0.0 { whites * adapt(&AW, bp, wp) } else { whites }; - // On photographs Photoshop's Blacks is about 1.2 times the block images' amount even where - // their black point is 0 (ten public-domain photos: 1.08–1.36). - let b = if blacks < 0.0 { blacks * adapt(&AB, bp, wp).max(PHOTO_BLACKS) } else { blacks }; - (w.clamp(WHITES_RANGE[0], WHITES_RANGE[1]), b.clamp(BLACKS_RANGE[0], BLACKS_RANGE[1])) -} - -/// Applies Whites and Blacks (internal amounts `w`, `b`) to straight RGBA pixels (`width` per -/// row) encoded with `enc`. Values above 1 (float documents) keep their excess. -pub(crate) fn apply(px: &mut [[f32; 4]], width: usize, w: f32, b: f32, enc: Encoding) { - if w == 0.0 && b == 0.0 { - return; - } - // A grey level's new level, both sRGB-encoded. - let grey = |v: f32| { - let v = if w != 0.0 { whites(v, w) } else { v }; - if b != 0.0 { blacks(v, b) } else { v } - }; - let per_channel = w > 0.0 || b < 0.0; - par_rows(px, width, 1, |_, row| { - for q in row.iter_mut() { - let lin = [0, 1, 2].map(|c| enc.decode(q[c])); - if per_channel { - for c in 0..3 { - let over = (lin[c] - 1.0).max(0.0); - q[c] = enc.encode(super::srgb_to_linear(grey(super::linear_to_srgb(lin[c].min(1.0)))) + over); - } - } else { - let y = super::luma_linear(lin).max(0.0); - if y <= 1e-7 { - continue; - } - let y2 = super::srgb_to_linear(grey(super::linear_to_srgb(y.min(1.0)))) + (y - 1.0).max(0.0); - let k = y2 / y; - for c in 0..3 { - q[c] = enc.encode(lin[c] * k); - } - } - } - }); -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn full_range_rows_match_photoshop() { - // Photoshop 25.4 on a 64-level block image spanning black to white (sRGB levels). - assert!((whites(97.1 / 255.0, 100.0) * 255.0 - 137.4).abs() < 0.6); - assert!((whites(194.3 / 255.0, -100.0) * 255.0 - 167.6).abs() < 0.6); - assert!((blacks(97.1 / 255.0, -100.0) * 255.0 - 60.0).abs() < 0.6); - assert!((blacks(48.6 / 255.0, 100.0) * 255.0 - 67.0).abs() < 0.6); - // The compressing directions keep black and white. - assert_eq!(whites(1.0, -100.0), 1.0); - assert_eq!(blacks(0.0, 100.0), 0.0); - } - - #[test] - fn the_clipping_directions_adapt_to_the_image() { - // A dark, low-contrast image needs more: Whites +50 acts like +94.5 on [0.05, 0.6]. - let (w, _) = amounts(50.0, 0.0, 0.05, 0.6); - assert!((w - 94.5).abs() < 2.0, "{w}"); - // A raised black point strengthens Blacks −40 to −58 on [0.6, 1]. - let (_, b) = amounts(0.0, -40.0, 0.6, 1.0); - assert!((b + 58.0).abs() < 1.0, "{b}"); - // Never below the photographs' 1.2. - assert!((amounts(0.0, -50.0, 0.0, 1.0).1 + 60.0).abs() < 1e-3); - // The compressing directions never adapt. - assert_eq!(amounts(-50.0, 50.0, 0.3, 0.6), (-50.0, 50.0)); - } -} diff --git a/crates/algo/src/photo_util.rs b/crates/algo/src/photo_util.rs index af707ca6d3..9c55d8cb08 100644 --- a/crates/algo/src/photo_util.rs +++ b/crates/algo/src/photo_util.rs @@ -326,6 +326,7 @@ impl Rng { } /// Integer hash → `0..1` (position-keyed noise, independent of tiling). +#[cfg(test)] pub(crate) fn hash01(x: i64, y: i64, seed: u64) -> f32 { let mut z = (x as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ (y as u64).wrapping_mul(0xC2B2_AE3D_27D4_EB4F) ^ seed.wrapping_mul(0x1656_67B1_9E37_79F9); z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); @@ -337,6 +338,7 @@ pub(crate) fn hash01(x: i64, y: i64, seed: u64) -> f32 { pub(crate) use photocraft_color::convert::{linear_to_srgb, srgb_to_linear}; /// Bilinear sample of channel `c` of a `w × h × ch` buffer, clamped to the edges. +#[cfg(test)] pub(crate) fn bilinear(buf: &[f32], w: usize, h: usize, ch: usize, c: usize, x: f32, y: f32) -> f32 { let x = x.clamp(0.0, (w - 1) as f32); let y = y.clamp(0.0, (h - 1) as f32);