Merge pull request #3630 from jeremyh/crystal-grain

LR-EDIT-EFFECTS-GRAIN: film grain from crystal layers (process V4), resolution independent, no GPU cost
This commit is contained in:
FredApps
2026-11-09 11:39:02 +01:00
committed by GitHub
20 changed files with 2462 additions and 82 deletions
+6 -2
View File
@@ -96,12 +96,15 @@ pub enum Process {
/// V5, with colour noise reduction on the linear colour differences R−Y and B−Y, leaving Y alone, with
/// edge-aware weights from a denoised guide and a brake for isolated colour specks (issue #815).
V6,
/// V6, with film grain from a stack of crystal layers (after Aurélien Pierre's model): resolution
/// independent, fading out at black and white; V1 to V6 keep their value noise.
V7,
}
impl Process {
/// Every process, oldest first.
pub const ALL: [Process; 6] = [Process::V1, Process::V2, Process::V3, Process::V4, Process::V5, Process::V6];
pub const LATEST: Process = Process::V6;
pub const ALL: [Process; 7] = [Process::V1, Process::V2, Process::V3, Process::V4, Process::V5, Process::V6, Process::V7];
pub const LATEST: Process = Process::V7;
pub const fn version(self) -> ProcessVersion {
match self {
@@ -111,6 +114,7 @@ impl Process {
Process::V4 => ProcessVersion(4),
Process::V5 => ProcessVersion(5),
Process::V6 => ProcessVersion(6),
Process::V7 => ProcessVersion(7),
}
}
}
+5 -4
View File
@@ -89,13 +89,14 @@ fn v1_is_left_out_when_saving_and_other_processes_are_kept() {
#[test]
fn unknown_process_numbers_load_and_render_with_the_newest_known() {
// written by a newer LightCraft: kept as it is, rendered with the latest process this build has
let s = DevelopSettings::from_json(&json!({"process": 7, "light": {"exposure": 0.5}})).unwrap();
assert_eq!(s.process, ProcessVersion(7));
let newer = Process::LATEST.version().0 + 1;
let s = DevelopSettings::from_json(&json!({"process": newer, "light": {"exposure": 0.5}})).unwrap();
assert_eq!(s.process, ProcessVersion(newer));
assert_eq!(s.process.process(), Process::LATEST);
assert!(!s.process.is_known());
assert!(!s.process.is_outdated(), "never downgraded by Update to Current Process");
assert_eq!(s.to_json()["process"], json!(7));
assert_eq!(s.merged(&json!({"light": {"exposure": 1.0}})).unwrap().process, ProcessVersion(7));
assert_eq!(s.to_json()["process"], json!(newer));
assert_eq!(s.merged(&json!({"light": {"exposure": 1.0}})).unwrap().process, ProcessVersion(newer));
// below V1 (no LightCraft writes it): rendered as V1, and updatable
let zero = DevelopSettings::from_json(&json!({"process": 0})).unwrap().process;
assert_eq!((zero.process(), zero.is_known(), zero.is_outdated()), (Process::V1, false, true));
+56
View File
@@ -0,0 +1,56 @@
//! Grain slider drags on the GPU: the time per frame of the draft renders the loupe makes while
//! Amount or Size is dragged, on a ~2.5 MP preview (1936 × 1290, the procedural demo photo).
//! `cargo run --release -p lightcraft-gpu --example grain_drag_bench` (`FRAMES=n`, default 40).
//!
//! The same source, settings and request on every build, so it can be copied unchanged into
//! another branch to compare grain models (see `docs/grain.md` → Performance). Each drag first
//! renders four frames that aren't counted (stage cache, GPU pipelines), then moves the slider one
//! step a frame; prints the median, fastest and slowest frame.
#![allow(clippy::unwrap_used, clippy::expect_used)]
use std::sync::Arc;
use std::time::Instant;
use lightcraft_develop::DevelopSettings;
use lightcraft_pipeline::{Quality, RenderRequest, SourceInfo, StageCache};
fn main() {
let frames: usize = std::env::var("FRAMES").ok().and_then(|v| v.parse().ok()).unwrap_or(40).max(1);
let (w, h) = (1936, 1290);
let src = Arc::new(lightcraft_scenes::demo_library()[3].render(w, h));
let info = SourceInfo { raw: true, ..Default::default() };
let draft = RenderRequest { quality: Quality::Draft, ..RenderRequest::fit(w, h) };
let Some(adapter) = lightcraft_gpu::adapter_name() else {
eprintln!("no GPU adapter: nothing to measure");
return;
};
println!("gpu: {adapter}; {w}×{h} draft renders, {frames} frames per drag");
let mut s = DevelopSettings::default();
s.light.exposure = 0.3;
let mut drag = |label: &str, step: &dyn Fn(&mut DevelopSettings, usize)| {
let cache = StageCache::default();
let mut ms = Vec::with_capacity(frames);
for i in 0..frames + 4 {
step(&mut s, i);
let t = Instant::now();
assert!(lightcraft_gpu::render(&src, &info, &s, &draft, Some(&cache)).is_some(), "GPU render failed");
if i >= 4 {
ms.push(t.elapsed().as_secs_f64() * 1e3);
}
}
ms.sort_by(f64::total_cmp);
println!("{label:<30} median {:5.1} ms min {:5.1} max {:5.1}", ms[ms.len() / 2], ms[0], ms[ms.len() - 1]);
};
drag("exposure drag, no grain", &|s, i| {
s.grain.amount = 0.0;
s.light.exposure = 0.3 + i as f64 * 0.01;
});
drag("Amount drag (20 → 100)", &|s, i| {
s.grain.size = 25.0;
s.grain.amount = 20.0 + (i * 2 % 80) as f64;
});
drag("Size drag (amount 50, 0 → 100)", &|s, i| {
s.grain.amount = 50.0;
s.grain.size = (i * 2 % 100) as f64;
});
}
+78 -1
View File
@@ -382,6 +382,11 @@ pub struct Gpu {
free: std::sync::Mutex<Vec<Tracked>>,
/// Largest storage buffer the device accepts (bytes).
pub max_buffer: u64,
/// The crystal grain tables of the last grain pattern, resident: a render (each Amount step
/// of a drag) copies them on the GPU instead of uploading their 12 MB again ([`Gpu::grain_tables`]).
/// Shared with each render that recorded a copy from them until it submits: replacing them
/// while another thread's copy is unsubmitted must not hand the buffer back to the pool.
grain: std::sync::Mutex<Option<(std::sync::Arc<lightcraft_pipeline::crystal::CrystalTile>, std::sync::Arc<Buf>)>>,
/// The device is the window's (eframe's): renders can hand it textures to draw directly.
pub window: bool,
}
@@ -430,6 +435,11 @@ fn constants() -> String {
for (i, h) in GRAIN_HASH.iter().enumerate() {
s += &format!("const GRAIN_H{i}: u32 = {h}u;\n");
}
use lightcraft_pipeline::crystal::{TILE_PER_LONG, TORI};
s += &format!(
"const CRYSTAL_T0: u32 = {}u;\nconst CRYSTAL_T1: u32 = {}u;\nconst CRYSTAL_TPL: f32 = {:?};\n",
TORI[0], TORI[1], TILE_PER_LONG as f32
);
s += &format!("const DEEP_WRITTEN: u32 = {}u;\n", crate::params::DEEP_WRITTEN);
for (name, idx) in crate::params::finish_fields() {
s += &format!("const F_{name}: u32 = {idx}u;\n");
@@ -543,7 +553,7 @@ impl Gpu {
max_buffer >> 20,
if window { ", the window's device" } else { "" }
);
Ok(Gpu { device, queue, info, kernels, dummy, free: Default::default(), max_buffer, window })
Ok(Gpu { device, queue, info, kernels, dummy, free: Default::default(), max_buffer, window, grain: Default::default() })
}
/// A buffer of `len` 32-bit values with undefined contents (a recycled one when possible).
@@ -718,6 +728,44 @@ impl Gpu {
);
}
/// Record into `enc` a copy of `tile`'s summed-area tables (both tori, back to back) into
/// `dst` at value offset `at`, uploading them first unless they are the resident ones.
/// Returns the buffer copied from, which the caller keeps until it has submitted `enc` (another
/// render may replace the resident tables meanwhile). None when `dst` can't hold them (an
/// over-limit placeholder: the render has failed already).
pub fn grain_tables(
&self,
enc: &mut wgpu::CommandEncoder,
tile: &std::sync::Arc<lightcraft_pipeline::crystal::CrystalTile>,
dst: &Buf,
at: usize,
) -> Option<std::sync::Arc<Buf>> {
let len: usize = tile.sats.iter().map(Vec::len).sum();
let (start, bytes) = ((at as u64) * 4, (len as u64) * 4);
if len == 0 || dst.raw().size() < start.saturating_add(bytes) {
return None;
}
let mut resident = self.grain.lock().unwrap_or_else(|e| e.into_inner());
if !resident.as_ref().is_some_and(|(t, b)| std::sync::Arc::ptr_eq(t, tile) && b.raw().size() >= bytes) {
// the old tables go back to the pool first (once no unsubmitted copy holds them): one
// pattern's tables are resident at a time
*resident = None;
let buf = self.buffer(len);
if buf.raw().size() < bytes {
return None;
}
let mut off = 0u64;
for sat in &tile.sats {
self.queue.write_buffer(buf.raw(), off, bytemuck::cast_slice(sat));
off += (sat.len() as u64) * 4;
}
*resident = Some((tile.clone(), std::sync::Arc::new(buf)));
}
let (_, src) = resident.as_ref()?;
enc.copy_buffer_to_buffer(src.raw(), 0, dst.raw(), start, bytes);
Some(src.clone())
}
/// Stands in for a buffer that could not be created (the render has failed already).
fn placeholder(&self) -> wgpu::Buffer {
self.device.create_buffer(&wgpu::BufferDescriptor {
@@ -1321,6 +1369,35 @@ mod tests {
}
}
/// Resident grain tables replaced by another pattern stay out of the pool while a render
/// that recorded a copy from them hasn't submitted it: reusing them then would hand that
/// render another tile's tables.
#[test]
fn replaced_grain_tables_stay_alive_until_their_copy_is_submitted() {
use lightcraft_pipeline::crystal::{CrystalLook, CrystalTile};
let Some(g) = crate::device() else {
lightcraft_testkit::skip!(Gpu, "no GPU device");
return;
};
let look = CrystalLook::new(25.0, 50.0);
let (Some(a), Some(b)) = (CrystalTile::new(look, 0x7ab1_0001), CrystalTile::new(look, 0x7ab1_0002)) else { panic!("tiles") };
let (a, b) = (std::sync::Arc::new(a), std::sync::Arc::new(b));
let len: usize = a.sats.iter().map(Vec::len).sum();
let (dst_a, dst_b) = (g.buffer(len), g.buffer(len));
let mut first = g.encoder();
let held = g.grain_tables(&mut first, &a, &dst_a, 0).expect("tables copied");
// another render replaces the resident tables before `first` is submitted
let mut second = g.encoder();
assert!(g.grain_tables(&mut second, &b, &dst_b, 0).is_some());
let next = g.buffer(len);
assert!(next.raw() != held.raw(), "the replaced tables went back to the pool before their copy was submitted");
g.submit([first.finish()]);
// each render read its own tile's tables
let tables = |t: &lightcraft_pipeline::crystal::CrystalTile| t.sats.concat();
assert!(g.finish_and_read::<f32>(second, &dst_a, len) == tables(&a), "the first render copied other tables");
assert!(g.finish_and_read::<f32>(g.encoder(), &dst_b, len) == tables(&b), "the second render copied other tables");
}
/// A GPU retired by another failure (a validation error) keeps a live device: its buffers are
/// still released, which takes a poll.
#[test]
+39 -7
View File
@@ -3,7 +3,7 @@
use lightcraft_develop::VignetteStyle;
use lightcraft_pipeline::colorops::POINT_WORDS;
use lightcraft_pipeline::finish::{FinishParams, MASK_TERMS, srgb_lut};
use lightcraft_pipeline::finish::{FinishParams, GrainModel, MASK_TERMS, srgb_lut};
use crate::ctx::{FailKind, fail};
@@ -71,6 +71,12 @@ const FIELDS: &[(&str, usize)] = &[
// the window's offset in the whole output and the whole output's size (pixels)
("VIG_VIEW", 4),
("GRAIN", 1),
// 0 = value noise (processes V1 to V6: GRAIN_AMT, GRAIN_SC, GRAIN_ROUGH), 1 = crystal layers (V7)
("GRAIN_MODEL", 1),
// crystal grain: amplitude, footprint (tile px per output px), the tori's tables in `aux`
("GRAIN_K", 1),
("GRAIN_FOOT", 1),
("GRAIN_SAT", 2),
("GRAIN_AMT", 1),
("GRAIN_SC", 1),
("GRAIN_ROUGH", 1),
@@ -178,7 +184,8 @@ pub struct Present {
}
/// The `finish` kernel's parameter block and auxiliary table (tone LUT | chroma curve | sRGB LUT | curve LUTs |
/// mask terms | light operator tables) for `fp` with `masks` (their local adjustments' terms).
/// mask terms | light operator tables) for `fp` with `masks` (their local adjustments' terms). The crystal
/// grain's tables go after `aux` in the kernel's buffer ([`crate::render`] copies them there).
///
/// `deep`: the kernel writes float samples, as the pipeline's `finish_deep` does.
///
@@ -220,6 +227,16 @@ pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Pr
if let Some((l, _)) = &fp.lut {
aux.extend(l.data.iter().flatten());
}
// the crystal grain's tables follow `aux` on the GPU without being part of it: they stay
// resident between renders ([`crate::Gpu::grain_tables`]) and the render copies them in
let mut sat_off = [0u32; 2];
if let Some(GrainModel::Crystal(g)) = &fp.grain {
let mut off = aux.len();
for (slot, sat) in sat_off.iter_mut().zip(&g.tile.sats) {
*slot = off as u32;
off += sat.len();
}
}
let mut p = Block::new();
p.u("LIGHT_OPS", light.len() as u32);
@@ -330,12 +347,27 @@ pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Pr
p.b("PROOF_DEST_WARN", pp.dest_warning);
p.b("PROOF_DISP_WARN", pp.display_warning);
}
if let Some((amt, cell, rough, seed)) = fp.grain {
if let Some(model) = &fp.grain {
p.b("GRAIN", true);
p.f("GRAIN_AMT", amt);
p.f("GRAIN_SC", fp.px_per_long as f32 / cell);
p.f("GRAIN_ROUGH", rough);
p.u("GRAIN_SEED", seed);
match model {
GrainModel::Value(g) => {
p.u("GRAIN_MODEL", 0);
p.f("GRAIN_AMT", g.amt);
p.f("GRAIN_SC", fp.px_per_long as f32 / g.cell);
p.f("GRAIN_ROUGH", g.rough);
p.u("GRAIN_SEED", g.seed);
}
GrainModel::Crystal(g) => {
p.u("GRAIN_MODEL", 1);
p.f("GRAIN_K", g.k);
p.f("GRAIN_FOOT", g.foot);
if let Some(i) = index("GRAIN_SAT") {
for (slot, off) in p.0.iter_mut().skip(i).zip(sat_off) {
*slot = off;
}
}
}
}
let long = fp.ow.max(fp.oh);
let [a, b, c, d, e, f] = fp.out_to_norm.0;
let (kx, ky) = (fp.ow / long, fp.oh / long);
+26 -3
View File
@@ -136,6 +136,10 @@ pub(crate) struct Cx<'a> {
enc: Option<wgpu::CommandEncoder>,
/// Kernel invocations recorded since the last submit.
pending: u64,
/// Buffers shared with other renders that recorded commands read from (the resident grain
/// tables): kept until those commands are submitted. Declared after `enc`, so an unsubmitted
/// encoder is dropped before them.
held: Vec<std::sync::Arc<Buf>>,
}
/// Kernel invocations recorded before a render submits them (under one full-size pass over a
@@ -147,7 +151,7 @@ const BAND_PIXELS: usize = 4 << 20;
impl<'a> Cx<'a> {
pub fn new(gpu: &'a Gpu) -> Cx<'a> {
Cx { gpu, enc: Some(gpu.encoder()), pending: 0 }
Cx { gpu, enc: Some(gpu.encoder()), pending: 0, held: Vec::new() }
}
/// Record kernel `name` (see [`Gpu::run`]).
@@ -161,11 +165,27 @@ impl<'a> Cx<'a> {
}
}
/// The finish kernel's `aux` buffer: `aux`, then the crystal grain's tables when it has them
/// (copied on the GPU from the resident ones, see [`Gpu::grain_tables`]).
pub fn finish_aux(&mut self, aux: &[f32], grain: Option<&lightcraft_pipeline::finish::GrainModel>) -> Buf {
let Some(lightcraft_pipeline::finish::GrainModel::Crystal(g)) = grain else { return self.gpu.upload(aux) };
let tables: usize = g.tile.sats.iter().map(Vec::len).sum();
let out = self.gpu.buffer(aux.len().saturating_add(tables));
if !aux.is_empty() && out.raw().size() >= (aux.len() as u64) * 4 {
self.gpu.queue.write_buffer(out.raw(), 0, bytemuck::cast_slice(aux));
}
let enc = self.enc.get_or_insert_with(|| self.gpu.encoder());
self.held.extend(self.gpu.grain_tables(enc, &g.tile, &out, aux.len()));
out
}
/// Submit what is recorded and read back `len` values of `b`.
pub fn read<T: bytemuck::Pod>(&mut self, b: &Buf, len: usize) -> Vec<T> {
self.pending = 0;
let enc = self.enc.take().unwrap_or_else(|| self.gpu.encoder());
self.gpu.finish_and_read(enc, b, len)
let out = self.gpu.finish_and_read(enc, b, len);
self.held.clear();
out
}
/// Submit what is recorded so far without waiting. Renders submit stage by stage and every
@@ -177,6 +197,7 @@ impl<'a> Cx<'a> {
if let Some(enc) = self.enc.take() {
self.gpu.submit([enc.finish()]);
}
self.held.clear();
}
/// Submit what is recorded and wait for it (profiling only: stage timings).
@@ -185,6 +206,7 @@ impl<'a> Cx<'a> {
if let Some(enc) = self.enc.take() {
self.gpu.submit([enc.finish()]);
}
self.held.clear();
let _ = self.gpu.poll(wgpu::PollType::wait_indefinitely());
}
@@ -749,6 +771,7 @@ pub fn render(
px_per_long: plan.px_per_long,
air_pre: prep.air,
space: req.space,
draft: req.quality == lightcraft_pipeline::Quality::Draft,
});
// soft proofing as the CPU's `finish` sets it up (an output-device table never gets here: see `render`)
fp.proof = req.proof.map(|pr| pr.params(req.space));
@@ -780,7 +803,7 @@ pub fn render(
if crate::ctx::failed() {
return None; // a malformed parameter block failed the render: the CPU fallback redoes it
}
let aux = gpu.upload(&aux);
let aux = cx.finish_aux(&aux, fp.grain.as_ref());
// cleared, so that work which never ran cannot pass for an image (see the check below)
let out = cx.zeroed(if deep { 3 * n } else { n });
if fault == Some(crate::Fault::Validation) {
+73 -10
View File
@@ -291,6 +291,65 @@ fn ghash(i: i32, j: i32, seed: u32) -> f32 {
return f32(v & 0xffffu) / 32768.0 - 1.0;
}
// Crystal grain (process V4): `lightcraft_pipeline::crystal` (keep in step with it). The tori's
// summed-area tables follow the other tables in `aux` (offsets F_GRAIN_SAT).
fn cg_bilinear(o: u32, t: u32, x: f32, y: f32) -> f32 {
let s = t + 1u;
let i = min(u32(max(x, 0.0)), t - 1u);
let j = min(u32(max(y, 0.0)), t - 1u);
let fx = x - f32(i);
let fy = y - f32(j);
let b = o + j * s + i;
let a = aux[b] + (aux[b + 1u] - aux[b]) * fx;
let c = aux[b + s] + (aux[b + s + 1u] - aux[b + s]) * fx;
return a + (c - a) * fy;
}
fn cg_integral(o: u32, t: u32, x: f32, y: f32) -> f32 {
let tf = f32(t);
let wx = x >= tf;
let wy = y >= tf;
let rx = select(x, x - tf, wx);
let ry = select(y, y - tf, wy);
var v = cg_bilinear(o, t, rx, ry);
if (wx) {
v += cg_bilinear(o, t, tf, ry);
}
if (wy) {
v += cg_bilinear(o, t, rx, tf);
}
if (wx && wy) {
v += cg_bilinear(o, t, tf, tf);
}
return v;
}
fn cg_box(o: u32, t: u32, x0_: f32, y0_: f32, w: f32) -> f32 {
let tf = f32(t);
let x0 = x0_ - floor(x0_ / tf) * tf;
let y0 = y0_ - floor(y0_ / tf) * tf;
return cg_integral(o, t, x0 + w, y0 + w) - cg_integral(o, t, x0, y0 + w) - cg_integral(o, t, x0 + w, y0) + cg_integral(o, t, x0, y0);
}
fn cg_lift(v: f32) -> f32 {
let c = clamp(v, 0.0, 1.0);
return select((c + 0.055) / 2.4, c, c <= 0.04045);
}
fn cg_srgb_to_linear(v: f32) -> f32 {
return select(pow((v + 0.055) / 1.055, 2.4), v / 12.92, v <= 0.04045);
}
fn crystal_grain(e: vec3<f32>, gx: f32, gy: f32) -> vec3<f32> {
let w = pf(F_GRAIN_FOOT);
let x0 = gx * CRYSTAL_TPL - 0.5 * w;
let y0 = gy * CRYSTAL_TPL - 0.5 * w;
let g = (cg_box(pu(F_GRAIN_SAT), CRYSTAL_T0, x0, y0, w) + cg_box(pu(F_GRAIN_SAT + 1u), CRYSTAL_T1, x0, y0, w)) / (w * w);
let lum = clamp(0.2126 * e.x + 0.7152 * e.y + 0.0722 * e.z, 0.0, 1.0);
let k = pf(F_GRAIN_K) * g * (1.0 - cg_srgb_to_linear(lum));
return e + k * vec3<f32>(cg_lift(e.x), cg_lift(e.y), cg_lift(e.z));
}
fn grain_noise(x: f32, y: f32, seed: u32) -> f32 {
let x0 = floor(x);
let y0 = floor(y);
@@ -694,17 +753,21 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
let py = f32(y) + 0.5;
let gx = pf(F_GRAIN_AFF) * px + pf(F_GRAIN_AFF + 2u) * py + pf(F_GRAIN_AFF + 4u);
let gy = pf(F_GRAIN_AFF + 1u) * px + pf(F_GRAIN_AFF + 3u) * py + pf(F_GRAIN_AFF + 5u);
let sc = pf(F_GRAIN_SC);
let rough = pf(F_GRAIN_ROUGH);
let seed = pu(F_GRAIN_SEED);
var g = grain_noise(gx * sc, gy * sc, seed);
g = g * (1.0 - rough * 0.5) + grain_noise(gx * sc * 2.3, gy * sc * 2.3, seed ^ 0x55u) * rough * 0.7;
var lum = 0.2126 * e.x + 0.7152 * e.y + 0.0722 * e.z;
if (hdr) {
lum = clamp(lum, 0.0, 1.0);
if (pu(F_GRAIN_MODEL) == 1u) {
e = crystal_grain(e, gx, gy);
} else {
let sc = pf(F_GRAIN_SC);
let rough = pf(F_GRAIN_ROUGH);
let seed = pu(F_GRAIN_SEED);
var g = grain_noise(gx * sc, gy * sc, seed);
g = g * (1.0 - rough * 0.5) + grain_noise(gx * sc * 2.3, gy * sc * 2.3, seed ^ 0x55u) * rough * 0.7;
var lum = 0.2126 * e.x + 0.7152 * e.y + 0.0722 * e.z;
if (hdr) {
lum = clamp(lum, 0.0, 1.0);
}
let k = pf(F_GRAIN_AMT) * g * (0.35 + 2.6 * lum * (1.0 - lum));
e = e + k;
}
let k = pf(F_GRAIN_AMT) * g * (0.35 + 2.6 * lum * (1.0 - lum));
e = e + k;
}
if (pu(F_LUT) != 0u) {
let lc = clamp(e, vec3<f32>(0.0), vec3<f32>(1.0));
+46
View File
@@ -210,6 +210,33 @@ fn banded_full_size_render_matches() {
check("banded 3000×2000", &src, &SourceInfo { raw: true, ..Default::default() }, &s, &RenderRequest::fit(w, h));
}
/// The crystal grain's tables stay on the GPU between renders: an Amount change reuses them,
/// another pattern (Size, Roughness, seed) replaces them, and going back draws the first again.
#[test]
fn grain_patterns_in_turn_match() {
if !gpu() {
return;
}
let src = scene(1, 480, 320);
let info = SourceInfo { raw: true, ..Default::default() };
let steps: [(&str, f64, f64, f64, u32); 6] = [
("grain 50/25/50", 50.0, 25.0, 50.0, 1),
("grain 90/25/50 (same pattern)", 90.0, 25.0, 50.0, 1),
("grain 50/70/50 (new size)", 50.0, 70.0, 50.0, 1),
("grain 50/70/0 (new roughness)", 50.0, 70.0, 0.0, 1),
("grain 50/70/0 seed 7", 50.0, 70.0, 0.0, 7),
("grain 50/25/50 again", 50.0, 25.0, 50.0, 1),
];
for (name, amount, size, roughness, seed) in steps {
let mut s = DevelopSettings::default();
s.grain.amount = amount;
s.grain.size = size;
s.grain.roughness = roughness;
s.grain.seed = seed;
check(name, &src, &info, &s, &RenderRequest::fit(480, 320));
}
}
fn cases() -> Vec<(&'static str, Edit)> {
vec![
("default", |_| {}),
@@ -287,6 +314,25 @@ fn cases() -> Vec<(&'static str, Edit)> {
s.grain.size = 40.0;
s.grain.roughness = 60.0;
}),
// the frozen value-noise grain of the earlier processes (the default is V7's crystals)
("grain, process V6", |s| {
s.process = Process::V6.version();
s.grain.amount = 50.0;
s.grain.size = 40.0;
s.grain.roughness = 60.0;
}),
("grain, process V1", |s| {
s.process = Process::V1.version();
s.grain.amount = 50.0;
s.grain.size = 40.0;
s.grain.roughness = 60.0;
}),
("grain, process V2", |s| {
s.process = Process::V2.version();
s.grain.amount = 50.0;
s.grain.size = 40.0;
s.grain.roughness = 60.0;
}),
("dehaze -", |s| s.effects.dehaze = -50.0),
("dehaze +", |s| s.effects.dehaze = 60.0),
("clarity/texture -", |s| {
File diff suppressed because it is too large Load Diff
+118 -43
View File
@@ -110,6 +110,50 @@ fn vignette(s: &DevelopSettings) -> Option<Vig> {
/// Hash constants of [`grain_noise`] (shared with the GPU kernel).
pub const GRAIN_HASH: [u32; 4] = [0x8da6_b343, 0xd816_3841, 0xcb1a_b31f, 0x5bd1_e995];
/// The grain of processes V1 to V3: two octaves of value noise. Frozen: photos on those
/// processes keep rendering with it (`docs/process-versions.md`).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ValueGrain {
/// Amplitude (display-encoded).
pub amt: f32,
/// Noise cell size (output pixels).
pub cell: f32,
/// Roughness 0..1: weight of the finer octave.
pub rough: f32,
pub seed: u32,
}
/// A render's film grain. The model follows the photo's process: changing it would change how
/// existing photos look, so the crystal grain came with process V4.
#[derive(Clone, Debug)]
pub enum GrainModel {
/// V1 to V3: value noise.
Value(ValueGrain),
/// V4 and later: crystal layers ([`crate::crystal`]).
Crystal(crate::crystal::CrystalGrain),
}
impl GrainModel {
/// The grain `s` renders with at `px_per_long` output pixels per long edge (`None`: none);
/// `draft`: for a drag ([`crate::crystal::CrystalGrain::draft`]).
pub fn new(s: &DevelopSettings, px_per_long: f64, draft: bool) -> Option<GrainModel> {
let g = &s.grain;
match s.process.process() {
Process::V1 | Process::V2 | Process::V3 | Process::V4 | Process::V5 | Process::V6 => (g.amount > 0.0).then(|| {
let cell = (0.0006 + (g.size / 100.0) as f32 * 0.0024) * px_per_long as f32;
GrainModel::Value(ValueGrain {
amt: (g.amount / 100.0) as f32 * 0.13,
cell: cell.max(0.6),
rough: (g.roughness / 100.0) as f32,
seed: g.seed,
})
}),
Process::V7 if draft => crate::crystal::CrystalGrain::draft(g, px_per_long).map(GrainModel::Crystal),
Process::V7 => crate::crystal::CrystalGrain::new(g, px_per_long).map(GrainModel::Crystal),
}
}
}
#[inline]
fn grain_noise(x: f32, y: f32, seed: u32) -> f32 {
// A degenerate frame (zero-width crop) maps pixels to NaN/inf coordinates: no grain there.
@@ -132,6 +176,21 @@ fn grain_noise(x: f32, y: f32, seed: u32) -> f32 {
a + (b - a) * v
}
/// The crystal grain of output row `y` (`w` pixels) when its pixels are axis-aligned; empty
/// otherwise (and without crystal grain): the pixels then take it one by one.
fn crystal_row(fp: &FinishParams, y: usize, w: usize) -> Vec<f32> {
let Some(GrainModel::Crystal(g)) = &fp.grain else { return Vec::new() };
let long = fp.ow.max(fp.oh);
let (a, b) = (fp.out_to_norm.apply(Point::new(0.5, y as f64 + 0.5)), fp.out_to_norm.apply(Point::new(1.5, y as f64 + 0.5)));
let (gx, gy) = (a.x * fp.ow / long, a.y * fp.oh / long);
let (dx, dy) = ((b.x - a.x) * fp.ow / long, (b.y - a.y) * fp.oh / long);
let mut out = vec![0.0; w];
if !g.row(gx, gy, dx, dy, &mut out) {
out.clear();
}
out
}
/// Number of per-mask terms in [`mask_terms`].
pub const MASK_TERMS: usize = 21;
@@ -217,8 +276,8 @@ pub struct FinishParams {
pub air_pre: f32,
pub gain: f32,
pub ev: f32,
/// Grain: amount, cell size (px), roughness, seed.
pub grain: Option<(f32, f32, f32, u32)>,
/// Film grain: the model of the photo's process ([`GrainModel`]).
pub grain: Option<GrainModel>,
/// Output px → normalized oriented coordinates.
pub out_to_norm: lightcraft_geom::Affine,
pub ow: f64,
@@ -241,12 +300,14 @@ pub struct FinishParamsInput<'a> {
pub px_per_long: f64,
pub air_pre: f32,
pub space: OutputSpace,
/// A draft render (a drag, [`crate::Quality::Draft`]): see [`GrainModel::new`].
pub draft: bool,
}
impl FinishParams {
/// Parameters for a `w × h` render into `space`; `ev`/`air_pre` as in [`crate::Prepared`].
pub fn new(input: FinishParamsInput<'_>) -> FinishParams {
let FinishParamsInput { settings: s, frame, info, image_size: (w, h), px_per_long, air_pre, space } = input;
let FinishParamsInput { settings: s, frame, info, image_size: (w, h), px_per_long, air_pre, space, draft } = input;
let effects = s.section_enabled("effects");
let (clar, tex, dehaze) = if effects {
((s.effects.clarity / 100.0) as f32, (s.effects.texture / 100.0) as f32, (s.effects.dehaze / 100.0) as f32)
@@ -263,10 +324,7 @@ impl FinishParams {
&& frame.oh.is_finite()
&& frame.ow.max(frame.oh) > 0.0
&& out_to_norm.0.iter().all(|v| v.is_finite());
let grain = (s.grain.amount > 0.0 && effects && finite_frame).then(|| {
let cell = (0.0006 + (s.grain.size / 100.0) as f32 * 0.0024) * px_per_long as f32;
((s.grain.amount / 100.0) as f32 * 0.13, cell.max(0.6), (s.grain.roughness / 100.0) as f32, s.grain.seed)
});
let grain = if effects && finite_frame { GrainModel::new(s, px_per_long, draft) } else { None };
let calibration = s.section_enabled("calibration");
let peak = s.hdr.peak();
FinishParams {
@@ -349,7 +407,7 @@ pub fn base_tone(s: &DevelopSettings, info: &SourceInfo, peak: f32) -> ToneMap {
},
// V4, with a raw's tone curve rolling off into white in stops: a camera curve past its last
// knot, the generic curve from half a stop below its white point instead of clipping (issue #1632)
Process::V5 | Process::V6 => match info.camera_tone.as_ref().filter(|_| info.raw) {
Process::V5 | Process::V6 | Process::V7 => match info.camera_tone.as_ref().filter(|_| info.raw) {
Some(curve) => ToneMap::camera_rolloff_hdr(curve, 0.0, l.whites, 0.0, peak),
None if info.raw => ToneMap::rolloff_hdr(l.contrast, l.whites, l.blacks, peak),
None => ToneMap::display_hdr(l.contrast, l.whites, l.blacks, peak),
@@ -358,18 +416,20 @@ pub fn base_tone(s: &DevelopSettings, info: &SourceInfo, peak: f32) -> ToneMap {
}
/// Finish the prepared pipeline stages into an 8-bit RGBA image in `space` (or `display`).
pub(crate) fn finish(
p: &Prepared,
s: &DevelopSettings,
frame: &Frame,
info: &SourceInfo,
space: OutputSpace,
display: Option<&crate::DisplaySpace>,
proof: Option<crate::Proof>,
) -> Rgba8 {
pub(crate) fn finish(p: &Prepared, s: &DevelopSettings, frame: &Frame, info: &SourceInfo, req: &crate::RenderRequest) -> Rgba8 {
let (space, display, proof) = (req.space, req.display.as_ref(), req.proof);
let (w, h) = (p.img.width, p.img.height);
let mut fp =
FinishParams::new(FinishParamsInput { settings: s, frame, info, image_size: (w, h), px_per_long: p.px_per_long, air_pre: p.air, space });
let draft = req.quality == crate::Quality::Draft;
let mut fp = FinishParams::new(FinishParamsInput {
settings: s,
frame,
info,
image_size: (w, h),
px_per_long: p.px_per_long,
air_pre: p.air,
space,
draft,
});
fp.proof = proof.map(|pr| pr.params(space));
if let Some(d) = display {
fp.for_display(d, proof);
@@ -389,19 +449,21 @@ pub(crate) fn finish(
}
/// [`finish`] into 16-bit display-encoded or 32-bit float linear samples (output primaries).
pub(crate) fn finish_deep(
p: &Prepared,
s: &DevelopSettings,
frame: &Frame,
info: &SourceInfo,
space: OutputSpace,
depth: OutputDepth,
proof: Option<crate::Proof>,
) -> DeepImage {
pub(crate) fn finish_deep(p: &Prepared, s: &DevelopSettings, frame: &Frame, info: &SourceInfo, req: &crate::RenderRequest) -> DeepImage {
use lightcraft_color::transfer::srgb_to_linear;
let (space, depth, proof) = (req.space, req.depth, req.proof);
let (w, h) = (p.img.width, p.img.height);
let mut fp =
FinishParams::new(FinishParamsInput { settings: s, frame, info, image_size: (w, h), px_per_long: p.px_per_long, air_pre: p.air, space });
let draft = req.quality == crate::Quality::Draft;
let mut fp = FinishParams::new(FinishParamsInput {
settings: s,
frame,
info,
image_size: (w, h),
px_per_long: p.px_per_long,
air_pre: p.air,
space,
draft,
});
fp.proof = proof.map(|pr| pr.params(space));
let trc = fp.out_trc;
let samples = match depth {
@@ -453,6 +515,8 @@ pub(crate) fn finish_with<T: Copy + Default + Send>(
let hdr = peak > 1.0;
let mut out = vec![T::default(); w * h];
for_rows(&mut out, w, |y, row| {
// the crystal grain of the whole row at once when its pixels are axis-aligned
let crystal_row = crystal_row(fp, y, row.len());
for (x, px) in row.iter_mut().enumerate() {
let i = y * w + x;
let raw = p.img.data[i];
@@ -587,20 +651,31 @@ pub(crate) fn finish_with<T: Copy + Default + Send>(
e = refine_saturation(e0, e, fp.refine_sat);
}
}
if let Some((amt, cell, rough, seed)) = *grain {
let n = out_to_norm.apply(Point::new(x as f64 + 0.5, y as f64 + 0.5));
let (gx, gy) = ((n.x * fp.ow) as f32 / long as f32, (n.y * fp.oh) as f32 / long as f32);
let sc = fp.px_per_long as f32 / cell;
let mut g = grain_noise(gx * sc, gy * sc, seed);
g = g * (1.0 - rough * 0.5) + grain_noise(gx * sc * 2.3, gy * sc * 2.3, seed ^ 0x55) * rough * 0.7;
let mut lum = 0.2126 * e[0] + 0.7152 * e[1] + 0.0722 * e[2];
if hdr {
lum = lum.clamp(0.0, 1.0);
}
let k = amt * g * (0.35 + 2.6 * lum * (1.0 - lum));
if k.is_finite() {
e = e.map(|v| v + k);
match grain {
Some(GrainModel::Value(g)) => {
// V1/V2 (frozen): exactly the arithmetic those processes always had
let n = out_to_norm.apply(Point::new(x as f64 + 0.5, y as f64 + 0.5));
let (gx, gy) = ((n.x * fp.ow) as f32 / long as f32, (n.y * fp.oh) as f32 / long as f32);
let sc = fp.px_per_long as f32 / g.cell;
let mut v = grain_noise(gx * sc, gy * sc, g.seed);
v = v * (1.0 - g.rough * 0.5) + grain_noise(gx * sc * 2.3, gy * sc * 2.3, g.seed ^ 0x55) * g.rough * 0.7;
let mut lum = 0.2126 * e[0] + 0.7152 * e[1] + 0.0722 * e[2];
if hdr {
lum = lum.clamp(0.0, 1.0);
}
let k = g.amt * v * (0.35 + 2.6 * lum * (1.0 - lum));
if k.is_finite() {
e = e.map(|v| v + k);
}
}
Some(GrainModel::Crystal(g)) => match crystal_row.get(x) {
Some(&f) => e = g.apply_field(e, f),
None => {
let n = out_to_norm.apply(Point::new(x as f64 + 0.5, y as f64 + 0.5));
e = g.apply(e, (n.x * fp.ow / long) as f32, (n.y * fp.oh / long) as f32);
}
},
None => {}
}
let e = match &p_lut {
Some((l, k)) if hdr => {
+5 -2
View File
@@ -26,6 +26,7 @@
pub mod auto;
pub mod blemish;
pub mod colorops;
pub mod crystal;
pub mod cull;
pub mod curve;
pub mod dust;
@@ -743,7 +744,7 @@ fn render_impl(src: Src<'_>, info: &SourceInfo, s: &DevelopSettings, req: &Rende
c.put(CacheEntry { src: a.clone(), geo, sampled, lin: Some((lin_key, lin)), colour_noise, planes });
}
if req.depth != OutputDepth::U8 {
let deep = finish::finish_deep(&prep, s, frame, info, req.space, req.depth, req.proof);
let deep = finish::finish_deep(&prep, s, frame, info, req);
let deep = match plan.keep {
Some(k) => deep.crop(k.x, k.y, k.w, k.h),
None => deep,
@@ -753,7 +754,7 @@ fn render_impl(src: Src<'_>, info: &SourceInfo, s: &DevelopSettings, req: &Rende
lap("finish (deep)", &mut t);
return Rendered { image, histogram, deep: Some(deep) };
}
let image = finish::finish(&prep, s, frame, info, req.space, req.display.as_ref(), req.proof);
let image = finish::finish(&prep, s, frame, info, req);
lap("finish", &mut t);
let cut = |i: &Rgba8| match plan.keep {
Some(k) => i.crop(k.x, k.y, k.w, k.h),
@@ -905,6 +906,8 @@ mod tests;
#[cfg(test)]
mod tests_geometry;
#[cfg(test)]
mod tests_grain;
#[cfg(test)]
mod tests_hdr;
#[cfg(test)]
mod tests_legacy;
+1 -1
View File
@@ -284,7 +284,7 @@ pub fn applies(s: &DevelopSettings, info: &SourceInfo) -> bool {
let camera_look = info.raw && info.camera_tone.is_some();
match s.process.process() {
Process::V1 | Process::V2 | Process::V3 => false,
Process::V4 | Process::V5 | Process::V6 => camera_look,
Process::V4 | Process::V5 | Process::V6 | Process::V7 => camera_look,
}
}
+1 -1
View File
@@ -375,7 +375,7 @@ pub fn base_detail_radius(px_per_long: f64) -> usize {
pub fn tone_base_detail(s: &DevelopSettings, px_per_long: f64) -> usize {
match s.process.process() {
Process::V1 => 0,
Process::V2 | Process::V3 | Process::V4 | Process::V5 | Process::V6 => base_detail_radius(px_per_long),
Process::V2 | Process::V3 | Process::V4 | Process::V5 | Process::V6 | Process::V7 => base_detail_radius(px_per_long),
}
}
+661
View File
@@ -0,0 +1,661 @@
use super::*;
/// The draws [`hold_for_waiters`] holds, by cache: how many renders wait for each, and how many
/// draws are left to hold.
static HOLDS: Mutex<Vec<(usize, usize, usize)>> = Mutex::new(Vec::new());
/// Holds the draw of `d` until the renders [`HOLDS`] names for its cache are waiting for it (each
/// holds a clone of its slot, as do the drawing and its in-flight entry), so a test can make
/// renders miss a tile together.
pub(super) fn hold_for_waiters(d: &Drawing) {
let waiters = {
let mut holds = HOLDS.lock().unwrap_or_else(PoisonError::into_inner);
let Some(h) = holds.iter_mut().find(|h| h.0 == d.id.0 && h.2 > 0) else { return };
h.2 -= 1;
h.1
};
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
while Arc::strong_count(&d.done) < 2 + waiters {
assert!(std::time::Instant::now() < deadline, "the renders never waited");
std::thread::sleep(std::time::Duration::from_millis(1));
}
}
/// The caches [`evict_before_waking`] empties.
static EVICTS: Mutex<Vec<usize>> = Mutex::new(Vec::new());
/// Empties `cache` if [`EVICTS`] names it, after its drawer `d` has cached its tile and before it
/// wakes the renders waiting for it, as other renders' tiles can push it out in that gap.
pub(super) fn evict_before_waking(cache: &Cache, d: &Drawing) {
if EVICTS.lock().unwrap_or_else(PoisonError::into_inner).contains(&d.id.0) {
cache.lock().unwrap_or_else(PoisonError::into_inner).clear();
}
}
/// Waits until `n` renders wait for the draw of `d`.
fn until_waiting(d: &Drawing, n: usize) {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
while Arc::strong_count(&d.done) < 2 + n {
assert!(std::time::Instant::now() < deadline, "the renders never waited");
std::thread::sleep(std::time::Duration::from_millis(1));
}
}
/// The field rendered at `long` px per long edge on an `n × n` patch starting at pixel `origin`.
fn patch(tile: &CrystalTile, long: f64, n: usize, origin: usize) -> Vec<f32> {
let w = (TILE_PER_LONG / long) as f32;
(0..n * n).map(|k| tile.field(((origin + k % n) as f32 + 0.5) * w, ((origin + k / n) as f32 + 0.5) * w, w)).collect()
}
fn std(v: &[f32]) -> f64 {
let m = v.iter().map(|&x| x as f64).sum::<f64>() / v.len() as f64;
(v.iter().map(|&x| (x as f64 - m).powi(2)).sum::<f64>() / v.len() as f64).sqrt()
}
/// Lag (px) at which the autocorrelation (mean of horizontal and vertical) falls to ½.
fn half_width(v: &[f32], n: usize) -> f64 {
let m = v.iter().map(|&x| x as f64).sum::<f64>() / v.len() as f64;
let d: Vec<f64> = v.iter().map(|&x| x as f64 - m).collect();
let var = d.iter().map(|x| x * x).sum::<f64>() / d.len() as f64;
let corr = |k: usize, horizontal: bool| {
let mut s = 0.0;
let mut c = 0usize;
for y in 0..n - if horizontal { 0 } else { k } {
for x in 0..n - if horizontal { k } else { 0 } {
let b = if horizontal { y * n + x + k } else { (y + k) * n + x };
s += d[y * n + x] * d[b];
c += 1;
}
}
s / c as f64 / var
};
let mut out = 0.0;
for horizontal in [true, false] {
let mut prev = 1.0;
let mut w = 16.0;
for k in 1..16 {
let c = corr(k, horizontal);
if c <= 0.5 {
w = k as f64 - 1.0 + (prev - 0.5) / (prev - c).max(1e-9);
break;
}
prev = c;
}
out += w / 2.0;
}
out
}
fn tile_of(size: f64, roughness: f64) -> Arc<CrystalTile> {
tile(CrystalLook::new(size, roughness), 7, true).expect("a tile")
}
#[test]
fn reference_render_has_unit_variance_and_no_mean() {
let t = tile_of(25.0, 50.0);
let v = patch(&t, REF_LONG, 600, 37);
let m = v.iter().map(|&x| x as f64).sum::<f64>() / v.len() as f64;
assert!((std(&v) - 1.0).abs() < 0.05, "std {}", std(&v));
assert!(m.abs() < 0.03, "mean {m}");
}
#[test]
fn small_render_is_the_downscaled_reference() {
for (size, rough) in [(0.0, 50.0), (25.0, 50.0), (100.0, 50.0), (25.0, 0.0), (25.0, 100.0)] {
let t = tile_of(size, rough);
for k in [2usize, 4, 8] {
let full = patch(&t, REF_LONG, 120 * k, 0);
let n = 120;
let down: Vec<f32> = (0..n * n)
.map(|q| {
let (x, y) = (q % n, q / n);
let mut s = 0.0;
for dy in 0..k {
for dx in 0..k {
s += full[(y * k + dy) * n * k + x * k + dx];
}
}
s / (k * k) as f32
})
.collect();
let small = patch(&t, REF_LONG / k as f64, n, 0);
let worst = down.iter().zip(&small).map(|(a, b)| (a - b).abs()).fold(0.0, f32::max);
assert!(worst < 2e-3, "size {size} roughness {rough} 1/{k}: differs by {worst}");
}
}
}
#[test]
fn strength_matches_the_target_at_mid_grey() {
for (a, s, r) in [(50.0, 25.0, 50.0), (25.0, 25.0, 50.0), (50.0, 0.0, 50.0), (50.0, 100.0, 50.0), (50.0, 25.0, 0.0)] {
let g = CrystalGrain::new(&Grain { amount: a, size: s, roughness: r, seed: 3 }, REF_LONG).expect("grain");
let n = 500;
let lum: Vec<f32> = (0..n * n)
.map(|k| {
let (x, y) = ((k % n) as f32 + 0.5, (k / n) as f32 + 0.5);
let e = g.apply([MID_GREY; 3], x / REF_LONG as f32, y / REF_LONG as f32);
(0.2126 * e[0] + 0.7152 * e[1] + 0.0722 * e[2]) * 255.0
})
.collect();
let want = strength_levels(a, s, r);
assert!((std(&lum) / want - 1.0).abs() < 0.06, "{a}/{s}/{r}: {} levels, want {want}", std(&lum));
}
}
#[test]
fn tones_keep_their_mean() {
// the strongest settings in the shadows; near white, strong grain clips at 255 like any grain
let cases = [
(100.0, 0.0, &[5.0f32, 20.0, 40.0, 60.0, 128.0, 255.0][..]),
(50.0, 0.0, &[200.0, 245.0][..]),
(50.0, 25.0, &[20.0, 128.0, 245.0, 255.0][..]),
];
for (amount, size, levels) in cases {
let g = CrystalGrain::new(&Grain { amount, size, roughness: 50.0, seed: 3 }, REF_LONG).expect("grain");
for &level in levels {
let n = 400;
let mut sum = 0.0f64;
for k in 0..n * n {
let (x, y) = ((k % n) as f32 + 0.5, (k / n) as f32 + 0.5);
let e = g.apply([level / 255.0; 3], x / REF_LONG as f32, y / REF_LONG as f32);
sum += (e[1].clamp(0.0, 1.0) * 255.0) as f64;
}
let shift = sum / (n * n) as f64 - level as f64;
assert!(shift.abs() < 0.5, "{amount}/{size}: level {level} moved {shift:+.2}");
}
}
}
#[test]
fn hostile_settings_render_finite_or_no_grain() {
let bad = [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -1e9, 1e9, 0.0];
for &a in &bad {
for &s in &bad {
for &ppl in &[f64::NAN, 0.0, -5.0, 1.0, 24.0, 1e12, 6000.0] {
let g = Grain { amount: if a == 0.0 { 50.0 } else { a }, size: s, roughness: s, seed: u32::MAX };
if let Some(c) = CrystalGrain::new(&g, ppl) {
for (x, y) in [(0.0, 0.0), (-3.5, 1e7), (f32::NAN, 0.2), (0.5, f32::INFINITY), (1.0, 0.6667)] {
let e = c.apply([0.5, 0.2, 0.9], x, y);
assert!(e.iter().all(|v| v.is_finite()), "{g:?} at {ppl}: {e:?}");
}
}
}
}
}
}
#[test]
fn seed_picks_the_pattern() {
let look = CrystalLook::new(25.0, 50.0);
let (Some(a), Some(c)) = (tile(look, 1, true), tile(look, 2, true)) else { panic!("tiles") };
assert_ne!(patch(&a, REF_LONG, 64, 0), patch(&c, REF_LONG, 64, 0));
}
/// A tile drawn again (its cache entry evicted, another process, an export after a preview) is the
/// same to the bit, however many threads draw it. These draw directly: through [`tile`], the second
/// would be the first one out of the cache.
#[test]
fn a_tile_draws_the_same_every_time() {
let look = CrystalLook::new(25.0, 50.0);
let one_thread = rayon::ThreadPoolBuilder::new().num_threads(1).build().expect("a pool");
let (Some(a), Some(b)) = (CrystalTile::new(look, 1), one_thread.install(|| CrystalTile::new(look, 1))) else { panic!("tiles") };
assert!(a.sats == b.sats, "the same seed drew different tiles");
}
/// Every seed has the same mix of crystal sizes, dealt to the layers in its own order.
#[test]
fn seeds_share_the_mix_of_crystal_sizes() {
let look = CrystalLook::new(50.0, 80.0);
let radii = |seed| emulsion(seed, &look).iter().map(|l| l.r).collect::<Vec<f64>>();
let sorted = |mut v: Vec<f64>| {
v.sort_by(f64::total_cmp);
v
};
let (a, b) = (radii(1), radii(2));
assert_eq!(a.len(), look.layers);
assert_eq!(a, radii(1), "the same seed deals the same order");
assert_ne!(a, b, "another seed deals another order");
assert_eq!(sorted(a), sorted(b));
assert_eq!(emulsion(1, &CrystalLook { layers: 0, ..look }).len(), 1, "an emulsion has a layer");
}
#[test]
fn sliders_clamp_and_fall_back() {
let look = CrystalLook::new;
assert_eq!(look(f64::NAN, f64::NAN), look(25.0, 50.0), "NaN is the default");
assert_eq!(look(-1e9, f64::NEG_INFINITY), look(0.0, 0.0));
assert_eq!(look(1e9, f64::INFINITY), look(100.0, 100.0));
// the ends of the tables
assert_eq!((look(0.0, 50.0).width, look(0.0, 50.0).layers), (0.55, 16));
assert_eq!((look(100.0, 50.0).width, look(100.0, 50.0).layers), (12.38, 70));
assert_eq!(look(100.0, 0.0).width, 12.38 * 0.734);
assert_eq!(look(100.0, 100.0).width, 12.38 * 1.422);
assert!(look(25.0, 100.0).spread > look(25.0, 0.0).spread);
let default = strength_levels(50.0, 25.0, 50.0);
assert_eq!(strength_levels(f64::NAN, 25.0, 50.0), 0.0, "a NaN Amount is no grain");
assert_eq!(strength_levels(-5.0, 25.0, 50.0), 0.0);
assert_eq!(strength_levels(50.0, f64::NAN, f64::NAN), default);
assert_eq!(strength_levels(1e9, 25.0, 50.0), 2.0 * default);
assert_eq!(strength_levels(50.0, -1e9, 50.0), strength_levels(50.0, 0.0, 50.0));
assert_eq!(strength_levels(50.0, 25.0, f64::INFINITY), strength_levels(50.0, 25.0, 100.0));
// Lightroom Classic's at the ends of each slider (`docs/grain.md`)
for (want, (a, s, r)) in [(23.08, (50.0, 0.0, 50.0)), (5.83, (50.0, 100.0, 50.0)), (12.42, (50.0, 25.0, 0.0)), (11.68, (50.0, 25.0, 100.0))] {
let got = strength_levels(a, s, r);
assert!((got / want - 1.0).abs() < 0.01, "{a}/{s}/{r}: {got}, want {want}");
}
}
#[test]
fn interp_is_linear_between_knots_and_constant_outside() {
let knots = [(0.0, 1.0), (10.0, 3.0), (20.0, 2.0)];
for (x, want) in [(-5.0, 1.0), (0.0, 1.0), (5.0, 2.0), (10.0, 3.0), (15.0, 2.5), (20.0, 2.0), (99.0, 2.0)] {
assert_eq!(interp(&knots, x), want, "at {x}");
}
assert_eq!(interp(&[], 5.0), 0.0);
assert_eq!(interp(&[(3.0, 7.0)], 5.0), 7.0);
}
#[test]
fn normal_quantile_matches_the_table() {
for (p, z) in [(0.5, 0.0), (0.975, 1.959_963_985), (0.841_344_746, 1.0), (0.001, -3.090_232_306), (1e-6, -4.753_424_309)] {
assert!((normal_quantile(p) - z).abs() < 1e-7, "at {p}: {}, want {z}", normal_quantile(p));
assert!((normal_quantile(1.0 - p) + z).abs() < 1e-7, "at 1 - {p}");
}
// increasing across the approximation's joins (0.02425 and its mirror), finite at the ends
let sweep: Vec<f64> = (0..=1000).map(|k| normal_quantile(k as f64 / 1000.0)).collect();
assert!(sweep.iter().all(|z| z.is_finite()));
assert!(sweep.windows(2).all(|w| w[0] < w[1]));
}
#[test]
fn poisson_counts_have_the_mean_and_variance_of_mu() {
let n = 40_000u32;
for mu in [0.5, 4.0, 40.0, 150.0] {
let cdf = poisson_cdf(mu);
assert!(cdf.windows(2).all(|w| w[0] <= w[1]), "mu {mu}: the distribution must not fall");
assert!(cdf.last().is_some_and(|&c| c >= 1.0 - 1e-12), "mu {mu}: the distribution must reach 1");
let draws: Vec<f64> = (0..n).map(|i| poisson(&cdf, mix(i)) as f64).collect();
let mean = draws.iter().sum::<f64>() / n as f64;
let var = draws.iter().map(|d| (d - mean).powi(2)).sum::<f64>() / n as f64;
assert!((mean - mu).abs() < 4.0 * (mu / n as f64).sqrt(), "mu {mu}: mean {mean}");
assert!((var / mu - 1.0).abs() < 0.05, "mu {mu}: variance {var}");
}
}
#[test]
fn poisson_stays_in_range_at_the_ends() {
for h in [0, u32::MAX] {
assert_eq!(poisson(&poisson_cdf(0.0), h), 0, "mean 0 is never a crystal");
// past what the model uses, e^-mu underflows: a capped count, not a panic
assert!(poisson(&poisson_cdf(1e6), h) <= 512);
assert_eq!(poisson(&[], h), 0);
}
}
#[test]
fn summed_area_matches_brute_force() {
let t = 7;
let count: Vec<u8> = (0..t * t).map(|i| (mix(i as u32) % 71) as u8).collect();
let sat = summed_area(&count, t);
assert_eq!(sat.len(), (t + 1) * (t + 1));
for y in 0..=t {
for x in 0..=t {
let want: u32 = (0..y).flat_map(|j| (0..x).map(move |i| (i, j))).map(|(i, j)| count[j * t + i] as u32).sum();
assert_eq!(sat[y * (t + 1) + x], want, "[0, {x}) × [0, {y})");
}
}
}
/// Boxes against the emulsion's own pixels (each table's counts, less their mean, scaled to unit
/// variance as [`CrystalTile::new`] does), integrated by hand. Whole and fractional boxes, across
/// the torus's seams, at negative coordinates and periods away.
#[test]
fn box_sum_is_the_integral_of_the_emulsion() {
let (look, seed) = (CrystalLook::new(25.0, 50.0), 7);
let tile = CrystalTile::new(look, seed).expect("a tile");
let counts = [0, 1].map(|which| draw_torus(which, TORI[which], seed, &look));
let means: [f64; 2] = [0, 1].map(|w| counts[w].iter().map(|&c| c as f64).sum::<f64>() / (TORI[w] * TORI[w]) as f64);
let var: f64 = [0, 1]
.map(|w| {
let (sq, n) = reference_square_sum(&counts[w], TORI[w], means[w]);
sq / n as f64
})
.iter()
.sum();
let k = 1.0 / var.sqrt();
// The overlap of the cell at `i` with `[a, a + w]`.
let overlap = |i: i64, a: f64, w: f64| ((i + 1) as f64).min(a + w) - (i as f64).max(a);
let integral_by_hand = |which: usize, x0: f32, y0: f32, w: f32| {
let (x0, y0, w, t) = (x0 as f64, y0 as f64, w as f64, TORI[which] as i64);
let mut sum = 0.0;
for j in y0.floor() as i64..(y0 + w).ceil() as i64 {
for i in x0.floor() as i64..(x0 + w).ceil() as i64 {
let c = counts[which][(j.rem_euclid(t) * t + i.rem_euclid(t)) as usize] as f64;
sum += (c - means[which]) * k * overlap(i, x0, w) * overlap(j, y0, w);
}
}
sum
};
for which in [0, 1] {
let t = TORI[which] as f32;
for (x0, y0, w) in [
(0.0, 0.0, 2.0),
(100.0, 200.0, 37.0),
(3.25, 7.5, 2.0),
(10.6, 11.3, 0.7),
(50.5, 60.25, 400.0),
(t - 1.5, 20.0, 4.0),
(20.0, t - 1.5, 4.0),
(t - 0.5, t - 0.25, 31.0),
(-1.5, -2.25, 8.0),
(3.0 * t + 12.5, -2.0 * t + 40.5, 8.0),
] {
let (got, want) = (tile.box_sum(which, x0, y0, w) as f64, integral_by_hand(which, x0, y0, w));
let area = (w * w) as f64;
assert!((got - want).abs() / area < 2e-3, "torus {which}, ({x0}, {y0}) side {w}: {got} vs {want}");
}
}
// the field is the two tori's mean, centred on its position
let (x, y, w) = (640.25, 1133.5, 3.0);
let want = (integral_by_hand(0, x - 0.5 * w, y - 0.5 * w, w) + integral_by_hand(1, x - 0.5 * w, y - 0.5 * w, w)) / (w * w) as f64;
assert!((tile.field(x, y, w) as f64 - want).abs() < 2e-3, "field {} vs {want}", tile.field(x, y, w));
}
/// A render under the footprint limit gets grain, one at or past it none, whatever else it asks.
#[test]
fn only_a_render_past_the_footprint_limit_loses_its_grain() {
let g = Grain { amount: 50.0, size: 25.0, roughness: 50.0, seed: 3 };
let limit = TILE_PER_LONG / MAX_FOOTPRINT as f64;
assert_eq!(limit, 24.0);
for none in [limit, limit - 1.0, 1.0, 0.0, -5.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
assert!(CrystalGrain::new(&g, none).is_none(), "{none} px per long edge");
}
assert_eq!(CrystalGrain::new(&g, limit + 1.0).expect("grain").foot, 480.0);
assert_eq!(CrystalGrain::new(&g, REF_LONG).expect("grain").foot, 2.0);
assert!(CrystalGrain::new(&Grain { amount: 0.0, ..g }, REF_LONG).is_none(), "no grain at Amount 0");
}
/// A draft (a Size or Roughness drag) doesn't wait for a new tile: the last tile of the seed stands
/// in while the new one is drawn in the background, and then the drag gets it. A render that
/// waits always gets the exact tile, as does a draft for a seed with no tile yet.
#[test]
fn a_drag_takes_the_last_tile_while_the_next_is_drawn() {
// a cache of its own: other tests' tiles (through any V7 render) would evict from the shared one
static OWN: Cache = Mutex::new(Vec::new());
let tile = |look, seed, wait| tile_in(&OWN, look, seed, wait);
let (seed, fresh) = (0x0d4a_0001, 0x0d4a_0002);
let (a, b) = (CrystalLook::new(30.0, 50.0), CrystalLook::new(31.0, 50.0));
let exact = |look: CrystalLook, seed: u32| patch(&CrystalTile::new(look, seed).expect("tile"), REF_LONG, 32, 0);
let first = tile(a, seed, true).expect("tile");
assert_eq!(first.look, a);
let stand_in = tile(b, seed, false).expect("tile");
assert_eq!(stand_in.look, a, "the draft waited for its tile");
// the drag's next renders get the new tile once it is drawn
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
let drawn = loop {
let t = tile(b, seed, false).expect("tile");
if t.look == b {
break t;
}
assert!(std::time::Instant::now() < deadline, "the background tile never arrived");
std::thread::sleep(std::time::Duration::from_millis(5));
};
assert_eq!(patch(&drawn, REF_LONG, 32, 0), exact(b, seed));
assert_eq!(patch(&tile(b, seed, true).expect("tile"), REF_LONG, 32, 0), exact(b, seed));
// nothing drawn for this seed: nothing to stand in, the draft draws it
assert_eq!(patch(&tile(a, fresh, false).expect("tile"), REF_LONG, 32, 0), exact(a, fresh));
}
/// A render that misses a tile another thread is drawing waits for that tile rather than drawing
/// it a second time.
#[test]
fn a_render_waits_for_a_tile_being_drawn() {
static OWN: Cache = Mutex::new(Vec::new());
let (look, seed) = (CrystalLook::new(40.0, 50.0), 0x0d4a_0003);
let key = key_of(look, seed);
let marker = start_drawing((std::ptr::from_ref(&OWN) as usize, key)).expect("not drawn yet");
let render = std::thread::spawn(move || tile_in(&OWN, look, seed, true));
until_waiting(&marker, 1);
let drawn = Arc::new(CrystalTile::new(look, seed).expect("tile"));
keep(&OWN, key, drawn.clone());
drop(marker);
let got = render.join().expect("render thread").expect("tile");
assert!(Arc::ptr_eq(&got, &drawn), "the render drew the tile again");
}
/// A render waiting for a tile gets it from its drawer even when the cache evicted it before the
/// render woke.
#[test]
fn a_waiting_render_gets_the_tile_the_cache_evicted() {
static OWN: Cache = Mutex::new(Vec::new());
let (look, seed) = (CrystalLook::new(40.0, 50.0), 0x0d4a_0004);
let key = key_of(look, seed);
let marker = start_drawing((std::ptr::from_ref(&OWN) as usize, key)).expect("not drawn yet");
let render = std::thread::spawn(move || tile_in(&OWN, look, seed, true));
until_waiting(&marker, 1);
let drawn = Arc::new(CrystalTile::new(look, seed).expect("tile"));
marker.finish(&drawn);
keep(&OWN, key, drawn.clone());
// other renders' tiles push it out of the cache before the waiter wakes
// (each its own tile: a waiter that took another key's would fail the check below)
for other in 1..=CACHE as u32 {
keep(&OWN, key_of(look, seed + other), Arc::new(CrystalTile::new(look, seed + other).expect("tile")));
}
assert!(cached(&OWN, key).is_none(), "the tile is still cached");
drop(marker);
let got = render.join().expect("render thread").expect("tile");
assert!(Arc::ptr_eq(&got, &drawn), "the render drew the tile again");
}
/// A render waiting for a tile another render is drawing gets the drawer's tile even when the
/// cache drops it before the waiter wakes.
#[test]
fn a_render_drawing_a_tile_hands_it_to_its_waiter() {
static OWN: Cache = Mutex::new(Vec::new());
let id = std::ptr::from_ref(&OWN) as usize;
// the first render's draw (only: a second would be the waiter drawing it again) waits for the
// second render to wait for it, and the cache empties before the second wakes
HOLDS.lock().unwrap_or_else(PoisonError::into_inner).push((id, 1, 1));
EVICTS.lock().unwrap_or_else(PoisonError::into_inner).push(id);
let (look, seed) = (CrystalLook::new(0.0, 50.0), 0x0d4a_0005);
let renders: Vec<_> = (0..2).map(|_| std::thread::spawn(move || tile_in(&OWN, look, seed, true))).collect();
let got: Vec<_> = renders.into_iter().map(|r| r.join().expect("render thread").expect("tile")).collect();
assert!(cached(&OWN, key_of(look, seed)).is_none(), "the cache kept the tile");
assert!(Arc::ptr_eq(&got[0], &got[1]), "the waiter drew the tile again");
}
/// Renders that miss the same tile together draw it once: the first registers the draw and the
/// others wait for it, as no gap lets a second render find it neither cached nor being drawn.
/// The first draw is held until the other renders all wait for it, so the misses overlap.
#[test]
fn renders_that_miss_a_tile_together_draw_it_once() {
static OWN: Cache = Mutex::new(Vec::new());
const N: usize = 8;
// the first render's draw waits for the other seven to miss the tile too
const SEEDS: u32 = 40;
HOLDS.lock().unwrap_or_else(PoisonError::into_inner).push((std::ptr::from_ref(&OWN) as usize, N - 1, SEEDS as usize));
let look = CrystalLook::new(0.0, 50.0);
for seed in 0x0d4a_1000..0x0d4a_1000 + SEEDS {
let start = Arc::new(std::sync::Barrier::new(N));
let renders: Vec<_> = (0..N)
.map(|_| {
let start = start.clone();
std::thread::spawn(move || {
start.wait();
tile_in(&OWN, look, seed, true)
})
})
.collect();
let got: Vec<_> = renders.into_iter().map(|r| r.join().expect("render thread").expect("tile")).collect();
assert!(got.iter().all(|t| Arc::ptr_eq(t, &got[0])), "seed {seed:#x}: a render drew the tile again");
}
}
/// Grain width (autocorrelation half-width at mid grey, 6000 px) at Lightroom Classic's
/// measured settings (open PR #1060's table); Size 0 is as fine as uncorrelated pixels get (0.5).
#[test]
fn width_matches_lightroom_classic() {
let lrc = [(0.0, 50.0, 0.5), (25.0, 50.0, 1.13), (100.0, 50.0, 3.38), (25.0, 0.0, 0.86), (25.0, 100.0, 1.54)];
for (s, r, want) in lrc {
let got = half_width(&patch(&tile_of(s, r), REF_LONG, 360, 0), 360);
assert!((got / want - 1.0).abs() < 0.1, "size {s} roughness {r}: width {got:.3}, want {want}");
}
}
/// Prints how long drawing a tile takes per setting (`--ignored --nocapture`, alone).
#[test]
#[ignore]
fn tile_timing_report() {
for (s, r) in [(0.0, 50.0), (10.0, 50.0), (25.0, 50.0), (50.0, 50.0), (100.0, 50.0), (25.0, 0.0), (25.0, 100.0), (100.0, 100.0)] {
let look = CrystalLook::new(s, r);
let mut best = f64::INFINITY;
for seed in 0..5 {
let start = std::time::Instant::now();
let t = CrystalTile::new(look, 100 + seed);
best = best.min(start.elapsed().as_secs_f64() * 1e3);
assert!(t.is_some());
}
eprintln!("size {s:>5} roughness {r:>5}: {best:.1} ms ({:?})", look);
}
}
/// Fits the median crystal width per Size (Roughness 50) and the Roughness factors at Size 25 to
/// Lightroom Classic's grain widths (`--ignored --nocapture`; paste into the look tables).
#[test]
#[ignore]
fn fit_widths() {
let width_of = |look: CrystalLook| {
let mut w = 0.0;
for seed in [11, 12] {
let t = CrystalTile::new(look, seed).expect("tile");
w += half_width(&patch(&t, REF_LONG, 360, 0), 360) / 2.0;
}
w
};
let fit = |s: f64, r: f64, want: f64| {
let base = CrystalLook::new(s, r);
let (mut lo, mut hi) = (0.05f64, 40.0f64);
for _ in 0..18 {
let mid = (lo * hi).sqrt();
if width_of(CrystalLook { width: mid, ..base }) < want { lo = mid } else { hi = mid }
}
let d = (lo * hi).sqrt();
(d, width_of(CrystalLook { width: d, ..base }))
};
for (s, want) in [(0.0, 0.43), (10.0, 0.71), (25.0, 1.13), (50.0, 1.70), (75.0, 2.54), (100.0, 3.38)] {
let (d, got) = fit(s, 50.0, want);
eprintln!("size {s}: width {d:.3} gives {got:.3} (want {want})");
}
let (d50, _) = fit(25.0, 50.0, 1.13);
for (r, want) in [(0.0, 0.86), (100.0, 1.54)] {
let (d, got) = fit(25.0, r, want);
eprintln!("roughness {r}: factor {:.3} gives {got:.3} (want {want})", d / d50);
}
}
/// Autocorrelation at lags 1–4 and the strength kept by box downscales of 2–16 (relative), of
/// candidate looks (`--ignored --nocapture`): compares a look's texture with a reference's.
#[test]
#[ignore]
fn texture_report() {
let profile = |look: CrystalLook| {
let n = 512;
let (mut acf, mut down) = ([0.0; 4], [0.0; 4]);
for seed in [21, 22] {
let t = CrystalTile::new(look, seed).expect("tile");
let v = patch(&t, REF_LONG, n, 0);
let s0 = std(&v);
for (k, a) in acf.iter_mut().enumerate() {
let lag = k + 1;
let mut s = 0.0f64;
for y in 0..n {
for x in 0..n - lag {
s += (v[y * n + x] * v[y * n + x + lag] + v[x * n + y] * v[(x + lag) * n + y]) as f64;
}
}
*a += s / (2 * n * (n - lag)) as f64 / (s0 * s0) / 2.0;
}
for (k, d) in down.iter_mut().enumerate() {
let f = 2usize << k;
let m = n / f;
let b: Vec<f32> = (0..m * m)
.map(|q| {
let (x, y) = (q % m * f, q / m * f);
(0..f * f).map(|i| v[(y + i / f) * n + x + i % f]).sum::<f32>() / (f * f) as f32
})
.collect();
*d += std(&b) / s0 / 2.0;
}
}
(acf, down)
};
for (s, r) in [(25.0, 50.0), (50.0, 50.0), (100.0, 50.0), (25.0, 0.0), (25.0, 100.0)] {
let (a, d) = profile(CrystalLook::new(s, r));
eprintln!(
"size {s} roughness {r}: acf {:.2} {:.2} {:.2} {:.2} down {:.2} {:.2} {:.2} {:.3}",
a[0], a[1], a[2], a[3], d[0], d[1], d[2], d[3]
);
}
}
/// A row computed with shared box edges equals the per-pixel boxes: any size, mirrored rows, rows
/// across the tori's seams and far from the origin.
#[test]
fn row_field_matches_per_pixel_field() {
let t = tile_of(25.0, 50.0);
for (w, sign, x, y) in [
(2.0f32, 1.0f32, 3.3f32, 7.9f32),
(2.0, -1.0, 9000.2, 1275.0),
(8.0, 1.0, 11990.0, 2260.5),
(0.7, 1.0, 1279.6, 0.1),
(31.0, -1.0, 400.0, 1133.9),
] {
for along_x in [true, false] {
let mut row = vec![0.0f32; 700];
t.row_field(x, y, w, sign * w, along_x, &mut row);
for (k, &v) in row.iter().enumerate() {
let d = sign * w * k as f32;
let want = if along_x { t.field(x + d, y, w) } else { t.field(x, y + d, w) };
assert!((v - want).abs() < 2e-3, "w {w} sign {sign} x {along_x} from ({x}, {y}), pixel {k}: {v} vs {want}");
}
}
}
}
/// Per-pixel cost of the grain on one thread (`--ignored --nocapture`).
#[test]
#[ignore]
fn pixel_cost_report() {
let g = CrystalGrain::new(&Grain { amount: 50.0, size: 25.0, roughness: 50.0, seed: 1 }, REF_LONG).expect("grain");
let (w, h) = (4000usize, 600usize);
let mut sink = 0.0f32;
let t0 = std::time::Instant::now();
for y in 0..h {
for x in 0..w {
sink += g.tile.field((x as f32 + 0.5) * 2.0, (y as f32 + 0.5) * 2.0, 2.0);
}
}
let per_pixel = t0.elapsed().as_secs_f64() / (w * h) as f64 * 1e9;
let mut row = vec![0.0; w];
let t1 = std::time::Instant::now();
for y in 0..h {
g.tile.row_field(1.0, (y as f32 + 0.5) * 2.0, 2.0, 2.0, true, &mut row);
sink += row[7];
}
let per_row = t1.elapsed().as_secs_f64() / (w * h) as f64 * 1e9;
let t3 = std::time::Instant::now();
for y in 0..h {
g.tile.row_field((y as f32 + 0.5) * 2.0, 1.0, 2.0, 2.0, false, &mut row);
sink += row[7];
}
eprintln!("column {:.1} ns/px", t3.elapsed().as_secs_f64() / (w * h) as f64 * 1e9);
let t2 = std::time::Instant::now();
for y in 0..h {
for x in 0..w {
sink += g.apply_field([0.4, 0.5, 0.6], (x + y) as f32 * 1e-4)[1];
}
}
let tone = t2.elapsed().as_secs_f64() / (w * h) as f64 * 1e9;
eprintln!("field {per_pixel:.1} ns/px, row {per_row:.1} ns/px, tone {tone:.1} ns/px ({sink})");
}
+99
View File
@@ -0,0 +1,99 @@
//! Film grain through the whole pipeline: which model each process renders with, and the crystal
//! grain's resolution independence (`crate::crystal`).
use lightcraft_develop::{DevelopSettings, Process};
use lightcraft_raster::Rgb32f;
use crate::finish::GrainModel;
use crate::{OutputDepth, RenderRequest, SourceInfo, render};
fn on(process: Process, amount: f64) -> DevelopSettings {
let mut s = DevelopSettings { process: process.version(), ..Default::default() };
s.grain.amount = amount;
s
}
/// Display-encoded luminance (0..255, 16-bit precision) of a render of `src` at `w × h`.
fn luma(src: &Rgb32f, s: &DevelopSettings, w: usize, h: usize) -> Vec<f64> {
let mut req = RenderRequest::fit(w, h);
req.depth = OutputDepth::U16;
let r = render(src, &SourceInfo::default(), s, &req);
let Some(crate::DeepSamples::U16(v)) = r.deep.map(|d| d.samples) else { panic!("no 16-bit render") };
v.chunks(3).map(|p| (0.2126 * p[0] as f64 + 0.7152 * p[1] as f64 + 0.0722 * p[2] as f64) / 257.0).collect()
}
fn std(v: &[f64]) -> f64 {
let m = v.iter().sum::<f64>() / v.len() as f64;
(v.iter().map(|x| (x - m).powi(2)).sum::<f64>() / v.len() as f64).sqrt()
}
#[test]
fn processes_before_v7_keep_the_value_noise() {
for p in Process::ALL {
let model = GrainModel::new(&on(p, 40.0), 2000.0, false);
match p {
Process::V1 | Process::V2 | Process::V3 | Process::V4 | Process::V5 | Process::V6 => {
assert!(matches!(model, Some(GrainModel::Value(_))), "{p:?}")
}
Process::V7 => assert!(matches!(model, Some(GrainModel::Crystal(_))), "{p:?}"),
}
assert!(GrainModel::new(&on(p, 0.0), 2000.0, false).is_none(), "{p:?}: no grain at Amount 0");
}
let src = Rgb32f::filled(160, 120, [0.18; 3]);
let (v6, v7) = (luma(&src, &on(Process::V6, 50.0), 160, 120), luma(&src, &on(Process::V7, 50.0), 160, 120));
assert_ne!(v6, v7, "V7 renders the crystal grain");
}
/// Grain is all that V7 changes: without it, a photo renders as under V6.
#[test]
fn without_grain_v7_renders_as_v6() {
let src = Rgb32f::filled(160, 120, [0.18, 0.4, 0.7]);
assert_eq!(luma(&src, &on(Process::V6, 0.0), 160, 120), luma(&src, &on(Process::V7, 0.0), 160, 120));
}
/// A preview shows what the export shows, box-downscaled to its size (whole pipeline).
#[test]
fn small_render_matches_the_downscaled_large_render() {
let src = Rgb32f::filled(300, 200, [0.18; 3]);
let (w, h, k) = (1200, 800, 4);
for size in [0.0, 25.0, 100.0] {
let mut s = on(Process::V7, 60.0);
s.grain.size = size;
let base = luma(&src, &on(Process::V7, 0.0), w, h);
let big: Vec<f64> = luma(&src, &s, w, h).iter().zip(&base).map(|(a, b)| a - b).collect();
let down: Vec<f64> = (0..(w / k) * (h / k))
.map(|q| {
let (x, y) = (q % (w / k) * k, q / (w / k) * k);
(0..k * k).map(|i| big[(y + i / k) * w + x + i % k]).sum::<f64>() / (k * k) as f64
})
.collect();
let small = luma(&src, &s, w / k, h / k);
let ratio = std(&small) / std(&down);
assert!((0.95..1.05).contains(&ratio), "size {size}: preview / export grain {ratio:.3}");
// and the same grain pixel by pixel, not just as strong: the preview's grain (less its
// no-grain render) against the downscaled export's
let small_base = luma(&src, &on(Process::V7, 0.0), w / k, h / k);
let delta: Vec<f64> = small.iter().zip(&small_base).map(|(a, b)| a - b).collect();
// (measured: at most 0.003 of 255 levels apart, the 16-bit output's rounding; the grain's
// standard deviation is 1.4–2.9 levels, so a shifted or reseeded pattern is far outside)
let worst = delta.iter().zip(&down).map(|(a, b)| (a - b).abs()).fold(0.0, f64::max);
assert!(worst < 0.01, "size {size}: preview grain {worst:.4} levels from the downscaled export's");
}
}
/// Degenerate and hostile grain settings render finite pixels under V7.
#[test]
fn hostile_grain_settings_render() {
let src = Rgb32f::filled(40, 30, [0.5, 0.2, 0.05]);
for (amount, size, rough) in
[(f64::NAN, 25.0, 50.0), (1e9, -1e9, f64::INFINITY), (50.0, f64::NAN, f64::NAN), (100.0, 100.0, 100.0), (-5.0, 0.0, 0.0)]
{
let mut s = on(Process::V7, amount);
s.grain.size = size;
s.grain.roughness = rough;
s.grain.seed = u32::MAX;
for (w, h) in [(40, 30), (1, 1), (3, 400)] {
assert!(luma(&src, &s, w, h).iter().all(|v| v.is_finite()), "{amount}/{size}/{rough} at {w}×{h}");
}
}
}
+1 -1
View File
@@ -310,7 +310,7 @@ real failure still stops the whole process. Such a test asserts on its own rende
`crates/gpu/tests/it/equivalence.rs` renders the same settings on both and compares 8-bit sRGB:
bounds **mean |Δ| < 0.5 LSB and max |Δ| ≤ 3 LSB** per channel. Measured (Apple M4 Pro, Metal):
**max 1 LSB, mean ≤ 0.0003 LSB** for every case — 26 settings cases (all tone/colour/effects tools,
3 vignette styles, grain, curves, grading, B&W, WB, NR, crop/straighten/flip, lens + perspective,
3 vignette styles, grain (value noise and crystal layers), curves, grading, B&W, WB, NR, crop/straighten/flip, lens + perspective,
three mask sets incl. CPU-evaluated shapes, spots + defringe), all 8 orientations ± crop, embedded
DNG lens data, display-referred sources, draft quality, full-size renders; the 24 MP export in
`render_bench` also differs by max 1 LSB. Cached (slider-drag) GPU renders are bit-identical to
+147
View File
@@ -0,0 +1,147 @@
# Film grain
The Effects panel's Grain (`ctl:grain.amount`, `ctl:grain.size`, `ctl:grain.roughness`; XMP
`crs:GrainAmount`, `crs:GrainSize`, `crs:GrainFrequency`) draws grain from a simulated emulsion of
crystal layers: `crates/pipeline/src/crystal.rs` on the CPU, the same tables read by the GPU
kernel (`crates/gpu/src/wgsl/finish.wgsl`).
This is the grain of **process V7** and later ([process-versions.md](process-versions.md)). Photos on
V1 to V6 keep the two-octave value noise they were edited with (`finish::ValueGrain`), so opening an
older catalog never changes a photo's grain; Update to Current Process moves a photo to the crystal
grain. The sliders, their ranges and their XMP names are unchanged.
## Model
After Aurélien Pierre, [*Stochastic photographic grain synthesis from crystallographic structure
simulation*](https://eng.aurelienpierre.com/2023/07/stochastic-photographic-grain-synthesis-from-crystallographic-structure-simulation/)
(2023). Implemented from the article's description of the method; no code was taken from it or from
any other implementation.
- **Emulsion.** A stack of layers. Each layer has one crystal shape: a regular polygon of
`round(4.5 + z)` vertices (3–8), a random rotation, and a width (circumscribed diameter) drawn from a
log-normal distribution. The layers' widths are the quantiles of that distribution, dealt out in an
order the seed shuffles, so every seed has the same mix of sizes (the same grain strength and
width) in a different arrangement.
- **Crystals.** Each layer is a Boolean model: Poisson seeds grown into crystals, at the density
`λ = −ln(1 − F)/A` (crystal area `A`) that leaves a fraction `F = ½` of the layer covered.
- **Capture.** A point's grain is the number of layers covering it less the mean: many independent
layers of different crystal sizes add up to dense, soft, cloudy grain with no hard particle edges.
- **Print.** The light a crystal captures is proportional to the light falling on it, and a print
shows less grain towards paper white: the grain is `Y·(1 − Y)·g` in linear light (`Y` the pixel's
luminance), zero at black and at white. It is applied in the display-encoded domain, to first
order: each channel `v` moves by `k·lift(v)·(1 − Y)·g`, where `lift(v) = Y·dv/dY` of the sRGB curve.
In that domain the grain is symmetric, so it neither darkens shadows (the article's model in
linear light does, through the concave encoding) nor greys blown highlights, and it keeps hue.
- **Colour:** monochrome, as in Lightroom Classic.
## Resolution independence
The emulsion is drawn in frame coordinates at twice the resolution of a 6000 px export (a tile pixel
is half a reference pixel), on two periodic tiles (tori) of 640 and 567 reference pixels; layers
alternate between them. The tiles are stored as summed-area tables, so each output pixel takes the
**exact mean of the emulsion under its footprint** (16 table reads): a fit-to-window preview shows
the export's grain box-downscaled to its size, and an export larger than 6000 px (a 45 MP camera)
still shows crystals rather than enlarged pixels. The tori share no small factor: the two patterns
only line up again after 362,880 reference pixels, so the grain has no visible period.
In a rotated frame (a straightened or rotated crop) the footprint is approximated: each pixel takes
the mean over an axis-aligned square of its size centred on it, not over the rotated pixel (summed
area tables only give axis-aligned boxes). The grain strength is the same; the exact match with a
box-downscaled export holds for unrotated frames in any orientation.
Measured on the comparison renders (four photos, six regions each, 1500 px preview against the
6000 px export box-downscaled to 1500 px): preview / export grain strength **1.00–1.04** at the
default, finest and coarsest settings. `crystal::tests::small_render_is_the_downscaled_reference`
checks it exactly at 1/2, 1/4 and 1/8 size; `tests_grain::small_render_matches_the_downscaled_large_render`
through the whole pipeline.
## Mapping and calibration
Amount, Size and Roughness keep Lightroom Classic's meaning: strength and width at mid grey match its
exports (the measurements of open PR #1060, `docs/grain.md` on that branch).
| Quantity | Value |
|---|---|
| strength (levels of 255 at mid grey, 6000 px) | `Amount/100 · exp(2.447 + 1.386·exp(−Size/19.88)) · (1 − 0.084d + 1.6384d²)`, `d = Roughness/100 − ½`: 8.55 at 50 / 25 / 50 |
| median crystal width (reference px) | by Size: 0.55, 1.39, 2.95, 5.17, 8.78, 12.38 at 0, 10, 25, 50, 75, 100; × 0.734 / 1 / 1.422 at Roughness 0 / 50 / 100 (`fit_widths`) |
| width spread (log std) | `hypot(0.1 + 0.6·Roughness/100, 0.45)` |
| layers | by Size: 16, 31, 54, 70 at 0, 25, 50, 100 |
- **Amount only scales the strength**: the amplitude is measured from the drawn emulsion itself (its
variance at the reference resolution), so every setting and seed has exactly its target strength,
and dragging Amount draws nothing new. In the article the layer count sets the strength; here it
sets only how dense the texture is (coarser grain averages more layers, so it stays a soft clump
texture).
- **Texture.** The width spread was chosen so the anti-aliased crystals have the texture of the
first, whole-pixel prototype at every scale, not just its width: autocorrelation at 1–5 px and the
strength kept by box downscales of 2–16 match it within a few hundredths
(`texture_report`).
- **Size 0** is as fine as the model gets: crystals narrower than a pixel, uncorrelated pixels
(width 0.51 px; Lightroom Classic's 0.43 needs anti-correlated grain).
Measured (chart, 6000 px, 8-bit, against the same build without grain):
| Amount / Size / Roughness | Strength at grey 20 · 128 · 245 | Width | Lightroom Classic at 128 |
|---|---|---|---|
| 25 / 25 / 50 | 1.66 · 4.29 · 1.67 | 1.11 | 4.29, 1.13 |
| 50 / 25 / 50 | 3.27 · 8.57 · 3.30 | 1.12 | 8.55, 1.13 |
| 100 / 25 / 50 | 6.53 · 17.14 · 6.36 | 1.12 | 17.01, 1.14 |
| 50 / 0 / 50 | 8.80 · 23.10 · 8.55 | 0.53 | 23.08, 0.43 |
| 50 / 50 / 50 | 2.46 · 6.42 · 2.43 | 1.70 | — |
| 50 / 100 / 50 | 2.24 · 5.83 · 2.19 | 3.39 | 5.83, 3.38 |
| 50 / 25 / 0 | 4.73 · 12.44 · 4.67 | 0.85 | 12.42, 0.86 |
| 50 / 25 / 100 | 4.46 · 11.75 · 4.37 | 1.53 | 11.68, 1.54 |
Unlike Lightroom Classic's, the grain fades towards black and white (the print model). Mean
brightness change on 24 photo regions: within ±0.1 level on every dark and mid-tone region at every
setting (#1060: up to +3.8 on dark fabric at 50 / 0 / 50); up to −0.55 on sunlit skin at the
strongest settings, where grain clips at white; blown highlights stay clean (−0.01 on a blown
curtain; #1060: −9.3). Fine detail under the grain is kept (detail gain
0.96–1.00).
## Performance
- **Drawing the emulsion** (per Size, Roughness and seed; cached, so Amount drags and re-renders
draw nothing): every crystal is stamped from a per-layer table of its rasterisation at 16 × 16
sub-pixel phases, as one 64-bit mask per row (a fixed number of rows per layer, those outside a
band landing in scratch rows around it, so a crystal costs no branch per row), layers are counted
in bit-sliced counters, and the tiles are drawn in parallel bands. 7–15 ms on an M2 Max (12
threads), 15–33 ms on a Ryzen 5 7545U (6 cores, 12 threads; 10–20 % less than before the row
masks) at any setting (`tile_timing_report`).
- **Drags.** A draft render (a slider drag) doesn't wait for a tile it hasn't got if one for the
photo's seed is cached: the last one drawn stands in while the new one is drawn in the background,
on a pool of half the cores so the drag's renders don't queue behind it, and the next render takes
it. With none cached for the seed there is nothing to stand in, so the draft waits for a draw
already running or draws the tile itself. The full-quality render when the drag ends waits for the
exact tile. A Size drag on the Ryzen with its
Radeon 740M (GPU, 2.5 MP preview): 13–14 ms a frame instead of 62–66 ms. (On wasm, without
threads, drafts wait.)
- **Drag benchmark** (`FRAMES=100 cargo run --release -p lightcraft-gpu --example grain_drag_bench`: GPU
draft renders of the 1936 × 1290 demo photo, median ms per frame of 100; the example has no
dependency on this model, so it can be copied unchanged into another branch). Ryzen 5 7545U /
Radeon 740M:
| Build | No grain (Exposure drag) | Amount drag | Size drag |
|---|---|---|---|
| main (value noise) | 8–12 | 10–13 | 10–13 |
| #1060 (particles) | 8 | 11–14 | 151–179 (17–312) |
| this model | 8–11 | 14–15 | 13 |
M2 Max (Metal), same benchmark, the medians of three runs:
| Build | No grain (Exposure drag) | Amount drag | Size drag |
|---|---|---|---|
| main (value noise) | 3.2–3.4 | 2.9–3.0 | 2.9 |
| #1060 (particles) | 3.3 | 3.0–3.1 | 35.6–36.0 |
| this model | 3.2–3.3 | 3.4–3.5 | 5.9–6.0 |
- **Per pixel:** two box sums, on the CPU and on the GPU. The tables (12 MB) stay on the GPU
between renders, for the last tile used (`Gpu::grain_tables`), and are copied after the finish
kernel's other tables in its `aux` buffer on the GPU: an Amount drag uploads nothing. On the
Radeon 740M an Amount drag frame (2.5 MP) went from 16.9 to 11–15 ms (no grain: 8 ms).
- **24 MP NEF → PNG** (`lightcraft-cli render`, M2 Max, median of three): no grain 1.06 s, grain
50 / 25 / 50 1.05 s on the GPU; 1.28 s and 1.43 s CPU-only (the finish stage 0.26 → 0.42 s).
Grain costs main ≈ 0 on the GPU and +0.08 s CPU-only, #1060 +0.29 s and +1.71 s.
- **24 MP NEF → PNG on the Ryzen 5 7545U / Radeon 740M** (median of three): no grain 2.07 s, grain
50 / 25 / 50 2.10 s on the GPU; 2.72 s and 2.88 s CPU-only. Grain costs main +0.03 s on the GPU
and +0.10 s CPU-only, #1060 +1.81 s and +3.54 s.
+7 -6
View File
@@ -31,7 +31,7 @@ cited here still exists. Formerly docs/parity.md.
| C. Views & navigation (VIEW) | 16 | 1 | 1 | 0 | 9/9 (100%) | 4/4 (100%) |
| D. Search & filter (FILT) | 11 | 1 | 1 | 0 | 4/4 (100%) | 4/4 (100%) |
| E. Metadata (META) | 5 | 1 | 0 | 0 | 2/2 (100%) | 2/2 (100%) |
| F. Edit panel — global adjustments (EDIT) | 41 | 5 | 3 | 1 | 25/28 (89%) | 13/14 (93%) |
| F. Edit panel — global adjustments (EDIT) | 42 | 5 | 3 | 1 | 25/28 (89%) | 14/15 (93%) |
| G. Profiles (PROF) | 7 | 1 | 3 | 0 | 3/4 (75%) | 3/3 (100%) |
| H. Crop & rotate (CROP) | 10 | 1 | 0 | 1 | 8/8 (100%) | 2/3 (67%) |
| I. Remove / healing (REM) | 8 | 1 | 2 | 2 | 4/4 (100%) | 2/3 (67%) |
@@ -51,11 +51,11 @@ cited here still exists. Formerly docs/parity.md.
| W. Cloud & AI infrastructure (CLOUD / AI) | 1 | 0 | 1 | 2 | — | — |
| X. Cross-cutting behaviours (BEHAV) | 23 | 6 | 1 | 1 | 8/8 (100%) | 7/10 (70%) |
| Y. Menus | 85 | 0 | 4 | 8 | 47/47 (100%) | 23/23 (100%) |
| Z. Keyboard shortcuts (desktop) | 78 | 4 | 2 | 1 | 49/52 (94%) | 24/26 (92%) |
| Z. Keyboard shortcuts (desktop) | 77 | 5 | 2 | 1 | 49/52 (94%) | 24/26 (92%) |
| Lightroom Classic extras | 41 | 26 | 21 | 8 | — | 24/27 (89%) |
| **Total** | 417 | 70 | 57 | 35 | 192/203 (95%) | 146/162 (90%) |
| **Total** | 419 | 70 | 57 | 35 | 193/203 (95%) | 147/163 (90%) |
Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **83.1%** of 544 in-scope rows — P0 97.3% of 203 · P1 94.1% of 162 · P2 56.7% of 178.
Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **83.2%** of 546 in-scope rows — P0 97.5% of 203 · P1 94.2% of 163 · P2 56.7% of 179.
<!-- /parity:summary -->
## Top gaps and shortcut notes
@@ -204,7 +204,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts).
| LR-EDIT-EFFECTS-CLARITY | Clarity | P0 | ✅ | `ctl:effects.clarity` | |
| LR-EDIT-EFFECTS-DEHAZE | Dehaze | P0 | ✅ | `ctl:effects.dehaze` | |
| LR-EDIT-EFFECTS-VIGNETTE | Post-crop vignette | P0 | ✅ | `ctl:vignette.*`, `crates/pipeline/src/finish.rs`, `crates/ui-egui/src/panels/edit.rs` | style picker (Highlight / Color / Paint) in the Effects section |
| LR-EDIT-EFFECTS-GRAIN | Grain | P1 | ✅ | `ctl:grain.*` | |
| LR-EDIT-EFFECTS-GRAIN | Grain | P1 | ✅ | `ctl:grain.*`, `crates/pipeline/src/crystal.rs` | Process V7: crystal-layer grain ([grain.md](grain.md)), Lightroom Classic's strength and width at mid grey, fades out at black and white, preview = export box-downscaled; CPU + GPU. V1 to V6 keep value noise |
| LR-EDIT-DETAIL-SHARPEN | Sharpening | P0 | ✅ | `ctl:detail.sharpenAmount`, `ctl:detail.sharpenRadius`, `ctl:detail.sharpenDetail`, `ctl:detail.sharpenMasking`, `crates/pipeline/src/visualize.rs` | Process V3: pixel-scale sharpening, working Radius and Detail, original-photo scale in previews and exports; V1/V2 preserve the previous rendering (`crates/pipeline/src/tests_sharpen.rs`). Alt/Option-drag previews: Amount greyscale, Radius / Detail the detail band sharpening amplifies, Masking the mask (white = sharpened) |
| LR-EDIT-DETAIL-NR | Luminance noise reduction | P0 | ✅ | `ctl:detail.nrLuminance`, `ctl:detail.nrDetail`, `ctl:detail.nrContrast` | radii in the original's pixels, so grid, loupe and smaller exports look like the full-size render scaled down (`local::nr_params`, `Plan::detail_scale`, #960). Alt/Option-drag on Luminance, Detail and Contrast shows the photo in greyscale |
| LR-EDIT-DETAIL-CNR | Colour noise reduction | P0 | ✅ | `ctl:detail.nrColor`, `ctl:detail.nrColorDetail`, `ctl:detail.nrColorSmoothness` | preview-size independent like luminance NR (#960). From process V6 the joint method (#815, `docs/nr-color-joint.md`): linear R−Y / B−Y, edge-aware weights from a denoised guide, a speck brake; acts clearly at the default 25 and keeps colour edges at 100. CPU and GPU within 1/255 |
@@ -732,7 +732,7 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06-
| LRC-DEV-CALIB | Calibration panel | P1 | ✅ | `ctl:calibration.*` | |
| LRC-DEV-TAT | Targeted adjustment tools | P1 | ✅ | `cmd:develop.targeted` (`target`: curve / hue / sat / lum) | |
| LRC-DEV-DEFAULTS | Per-camera raw defaults | P1 | ✅ | `cmd:library.preferences` (`camera`, `import.perCamera`), `crates/ui-egui/src/dialogs/settings.rs` | Settings → Import: raw default and per-camera presets |
| LRC-DEV-PROCESS | Process versions, Update to Current Process | P1 | ✅ | `cmd:develop.updateProcess`, `cmd:develop.reset`, `cmd:develop.get`, `crates/develop/src/settings.rs`, `crates/pipeline/src/finish.rs`, `docs/process-versions.md` | Each photo keeps its saved rendering process. V1 is legacy, V2 preserves Highlights/Shadows detail, V3 is pixel-scale sharpening, V4 calibrates camera-look Contrast and Blacks, V5 rolls raw tone curves off into white in stops (#1632). New photos and Reset use the latest; Update is one undoable step and never downgrades a future number. Copy/paste/sync preserve the receiving process. Persistent render keys include the resolved process from V3 on; V1/V2 keys remain unchanged. |
| LRC-DEV-PROCESS | Process versions, Update to Current Process | P1 | ✅ | `cmd:develop.updateProcess`, `cmd:develop.reset`, `cmd:develop.get`, `crates/develop/src/settings.rs`, `crates/pipeline/src/finish.rs`, `docs/process-versions.md` | Each photo keeps its saved rendering process. V1 is legacy, V2 preserves Highlights/Shadows detail, V3 is pixel-scale sharpening, V4 calibrates camera-look Contrast and Blacks, V5 rolls raw tone curves off into white in stops (#1632), V6 takes colour noise reduction to the joint method (#815), V7 draws film grain from crystal layers. New photos and Reset use the latest; Update is one undoable step and never downgrades a future number. Copy/paste/sync preserve the receiving process. Persistent render keys include the resolved process from V3 on; V1/V2 keys remain unchanged. |
| LRC-DEV-VIEWOPTIONS | Develop view options | P2 | 🟡 | `cmd:view.viewOptions`, `crates/ui-egui/src/dialogs/settings.rs` (`view_options`) | View ▸ View Options… (⌘J), the Loupe View part: Show Info Overlay with Info 1 / Info 2, and the three lines of each (none, file name, capture date, dimensions, exposure, camera, lens, camera + lens) with Use Defaults; Show Briefly When Photo Changes under each Info (one at most): with the overlay off, that Info shows for 3 s each time the loupe changes photo; General's Show message when loading or rendering photos (on by default; off, the loupe does not say "Rendering…"); applied as they change, saved with the app settings; `view.viewOptions {info1, info2, briefly, loupeMessages}` sets them for agents. Not yet: the Grid View tab, more fields (ratings, metadata, copy name), the video-frame option |
| LRC-DEV-LOUPEOVERLAY | Loupe overlay: layout image | P2 | 🟡 | `cmd:view.chooseLayoutImage`, `cmd:view.layoutImage`, `cmd:view.layoutImageOpacity`, `cmd:view.layoutImageMatte`, `crates/ui-egui/src/panels/layout_overlay.rs` | View ▸ Loupe Overlay: a PNG with transparency (a cover layout, a banner's safe areas) fitted and centred over the loupe photo, following zoom and pan; opacity and matte (the photo darkened outside the graphic's box) in steps; ⌥⌘O shows / hides it; read off the UI thread; saved with the UI state. Not yet: the Grid and Guides overlays, moving and resizing the layout with ⌘ held, free opacity / matte sliders |
| LRC-DEV-VIDEO | Video frame capture | P2 | ⬜ | | |
@@ -805,6 +805,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove
| 2026-11-07 | correction | Compressed ORF sensor support withdrawn pending provenance review; embedded preview fallback remains. Coverage regenerated without the removed decoder: 557 verified, 665 unverified, 187 preview-only, 37 unsupported; 94% use-weighted coverage. |
| 2026-11-04 | minor | Compressed ORF support was introduced in #3775; subsequently withdrawn pending provenance review. Earlier clean-room and verification claims are withdrawn; compressed files use embedded previews when available. See [ORF status](orf-compression.md). |
| 2026-10-28 | minor | KEY-HIDEPINS ✅ → 🟡: in the Masking panel an unmodified H toggles the mask pins (`view.maskPins`, the View ▸ Show Mask Pins switch) instead of opening Remove; the toggle yields only to an explicit assignment of H itself, a Remove key reassigned to anything else still opens Remove there, and outside Masking — and the full-screen preview, where no panel shows — H keeps its own binding (Remove, by default). Remove's spot pins keep ⇧H as their only hide toggle (`tests/keymap` `h_toggles_the_mask_pins_while_masking`, `a_remapped_remove_key_still_opens_remove_while_masking`, `h_still_toggles_the_pins_when_remove_moves_to_another_key`) |
| 2026-11-07 | minor | LR-EDIT-EFFECTS-GRAIN, LRC-DEV-PROCESS: process V7 takes film grain to crystal layers ([grain.md](grain.md)); V1 to V6 keep value noise |
| 2026-11-06 | minor | LR-EDIT-DETAIL-CNR, LRC-DEV-PROCESS: process V6 takes colour noise reduction to the joint method on linear R−Y / B−Y (issue #815); status unchanged |
| 2026-11-05 | minor | LR-BEHAV-RENDER-FIDELITY, LRC-DEV-PROCESS: process V5 rolls a raw's tone curve off into white in stops, past a camera curve's last knot and from half a stop below the generic curve's white point, so raising Exposure no longer turns recorded highlights white (#1632); statuses and counts unchanged |
| 2026-11-05 | minor | LR-LIB-PEOPLE: face boxes another app drew on the photo as stored land on the upright photo (#2674) |
+3 -1
View File
@@ -14,7 +14,8 @@ stronger Light sliders, issue #196) without changing a single photo someone has
| **V3** | Pixel-scale sharpening (issue #757): Radius uses the original photo’s pixels, Detail controls halo damping, and downsized sources retain a response-matched sharpening band. V1 and V2 keep texture-band sharpening exactly. The sharpen plane is keyed by radius and process and invalidated after noise-reduction changes. The Highlights/Shadows base and tone map are unchanged from V2. |
| **V4** | V3 plus calibrated global Contrast (per channel) and Blacks (per-channel/luminance mix) on raws with a camera tone curve. Whites behaves exactly as V2, both signs; its calibration is a planned follow-up. Other sources and local adjustments retain V2 operators. See [calibrated Light operators](light-v3.md). |
| **V5** | V4 plus: a raw's tone curve rolls off into white in stops instead of reaching it within about a stop of the sensor's white, so raising Exposure keeps the highlights the sensor recorded (issue #1632). **Camera curve** (the look fitted to the embedded JPEG, or a DNG's `ProfileToneCurve`; `CameraTone`): past its last knot `CameraTone::apply_rolloff` closes the gap to white by `gap / (1 + c·(2^t − 1))` at `t` stops past the knot, with `c` matching the curve's slope there and the gap halving every stop in the end (`tone::ROLLOFF_STOPS`); `ToneMap::camera_rolloff_hdr` builds the table from it. Under V1 to V4 the curve past its last knot (fitted only to camera JPEG tones below 0.85, so 1 to 3 stops below the sensor's white on most photos) closes on white exponentially in linear light: the sensor's white renders at 8-bit 246 to 254 at Exposure 0 and 254 to 255 from Exposure +1. On the 11 CC0 corpus files with a fitted look (8 Sony, 2 Nikon, 1 Fujifilm) it now renders at 239 to 250 at Exposure 0 and 247 to 253 at +1. A DNG curve that reaches white at the sensor's white renders as before. **Generic curve** (raws without a camera curve, `ToneMap::rolloff_hdr`): from half a stop below its white point (`tone::GENERIC_KNEE_STOPS`) the same shoulder takes over, with the extended Reinhard curve's value and slope at the join, where V1 to V4 clip at the white point (scene 1.18 at default settings, ¼ stop above the sensor's white). The sensor's white renders at about 235, 248 and 252 at Exposure 0, +1 and +2 (V1 to V4: 239, 255, 255; the CC0 Canon R8 file and 6 CC0 DNGs without a camera curve). Content past the old clip point, such as a clipped sky, now renders up to 15 codes below white at Exposure 0 and reaches 255 about 5 stops past the sensor's white. Below the last knot or the join, JPEGs and other display-referred sources, and the camera fit itself are unchanged; CPU and GPU share the tone LUT. |
| **V6** (the latest) | V5 plus: colour noise reduction filters the linear colour differences R−Y and B−Y with the joint method (issue #815, `docs/nr-color-joint.md`): edge-aware weights from a denoised guide shared by both differences, anisotropic diffusion over scales, a brake for isolated colour specks; Y is kept exactly. V1 to V5 keep the blurred chromaticity (`local::denoise`). CPU (`local::denoise`) and GPU (`render::denoise`) branch on `local::joint_colour_nr`. Renders with Color 0 are the same as V2's. |
| **V6** | V5 plus: colour noise reduction filters the linear colour differences R−Y and B−Y with the joint method (issue #815, `docs/nr-color-joint.md`): edge-aware weights from a denoised guide shared by both differences, anisotropic diffusion over scales, a brake for isolated colour specks; Y is kept exactly. V1 to V5 keep the blurred chromaticity (`local::denoise`). CPU (`local::denoise`) and GPU (`render::denoise`) branch on `local::joint_colour_nr`. Renders with Color 0 are the same as V2's. |
| **V7** (the latest) | V6 plus: film grain from crystal layers ([grain.md](grain.md), `crates/pipeline/src/crystal.rs`), after Aurélien Pierre's model: resolution independent (a preview is the export's grain box-downscaled), fading out at black and white, calibrated to Lightroom Classic's strength and width at mid grey. V1 to V6 keep their two-octave value noise exactly (`finish::ValueGrain`; on the GPU `F_GRAIN_MODEL` 0); `finish::GrainModel::new` picks the model per process. Renders without grain don't depend on this. |
## The rule
@@ -110,5 +111,6 @@ extra field and retain their existing cached renders. No cache-version bump is n
| Date | Change | Summary |
|---|---|---|
| 2026-11-07 | minor | V7: film grain from crystal layers ([grain.md](grain.md)); V1 to V6 keep their value noise |
| 2026-11-05 | minor | V5: a raw's tone curve rolls off into white in stops, so raising Exposure keeps recorded highlights (#1632) |
| 2026-10-12 | minor | Calibrated Contrast and Blacks, V2 Whites, resolved-process cache keys and number coordination |
+8
View File
@@ -2,6 +2,14 @@
## Unreleased
### Film grain that looks like film (process V7)
- Grain now comes from a simulated emulsion of crystal layers (after Aurélien Pierre's model): dense, soft and cloudy
rather than dots on top of the photo. It fades out towards black and white as on a print, so shadows keep their depth
and blown highlights stay clean, and the fit-to-window preview shows the grain you will export. Amount, Size and
Roughness keep their meaning and Lightroom Classic's strength and grain size. This is rendering process 7: new photos
(and Reset) get it, photos you already edited keep their grain until you choose Photo ▸ Update to Current Process.
See [film grain](grain.md).
### Colour noise reduction (process V6)
- Colour noise reduction removes colour noise at the raw default 25, where it used to leave most of it, and keeps
colour edges at high values instead of bleeding them into fringes (issue #815). It filters the colour differences