Skip to content
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
c813684
LR-EDIT-EFFECTS-GRAIN: film grain from crystal layers (process V3)
jeremyh Nov 2, 2026
0c6cd98
LR-EDIT-EFFECTS-GRAIN: crystal grain a row at a time on the CPU
jeremyh Nov 2, 2026
fe6e064
LR-EDIT-EFFECTS-GRAIN: crystal grain keeps slider drags in budget on …
jeremyh Nov 2, 2026
4ea6a81
LR-EDIT-EFFECTS-GRAIN: grain pattern and export timings re-measured o…
jeremyh Nov 2, 2026
50e6422
LR-EDIT-EFFECTS-GRAIN: grain drag benchmark; Ryzen numbers for main a…
jeremyh Nov 3, 2026
e909f7f
LR-EDIT-EFFECTS-GRAIN: grain drag benchmark on the M2 Max for main, #…
jeremyh Nov 3, 2026
1acedc8
LR-EDIT-EFFECTS-GRAIN: M2 Max export timings for main, #1060 and this…
jeremyh Nov 3, 2026
b908538
LR-EDIT-EFFECTS-GRAIN: review fixes (shared grain tables, own test ca…
jeremyh Nov 3, 2026
2038ebc
LR-EDIT-EFFECTS-GRAIN: review fixes (one draw per missed tile, table …
jeremyh Nov 3, 2026
7f637be
LR-EDIT-EFFECTS-GRAIN: review fix (renders that miss a tile together …
jeremyh Nov 3, 2026
6b59774
LR-EDIT-EFFECTS-GRAIN: review fix (a drawer hands its tile to the ren…
jeremyh Nov 3, 2026
21a235f
LR-EDIT-EFFECTS-GRAIN: review fixes (crystal tile waiter tests)
jeremyh Nov 3, 2026
3b23f25
Merge main into crystal-grain; the crystal grain moves to process V4
jeremyh Nov 5, 2026
a850d05
LR-EDIT-EFFECTS-GRAIN: review fixes (crystal grain unit tests)
jeremyh Nov 6, 2026
ed10d44
Merge main into crystal-grain; the crystal grain moves to process V7
jeremyh Nov 6, 2026
622c288
LR-EDIT-EFFECTS-GRAIN: review fix (a draft waits when nothing can sta…
jeremyh Nov 7, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions crates/develop/src/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,17 +84,21 @@ pub enum Process {
/// Highlights and Shadows keep the local contrast of the tones they move: their edge-aware base
/// is taken of a fine median of log luminance (issue #632).
V2,
/// Film grain from a stack of crystal layers (after Aurélien Pierre's model): resolution
/// independent, fading out at black and white; V1 and V2 keep their value noise.
V3,
}

impl Process {
/// Every process, oldest first.
pub const ALL: [Process; 2] = [Process::V1, Process::V2];
pub const LATEST: Process = Process::V2;
pub const ALL: [Process; 3] = [Process::V1, Process::V2, Process::V3];
pub const LATEST: Process = Process::V3;

pub const fn version(self) -> ProcessVersion {
match self {
Process::V1 => ProcessVersion(1),
Process::V2 => ProcessVersion(2),
Process::V3 => ProcessVersion(3),
}
}
}
Expand Down
56 changes: 56 additions & 0 deletions crates/gpu/examples/grain_drag_bench.rs
Original file line number Diff line number Diff line change
@@ -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);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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;
});
}
79 changes: 78 additions & 1 deletion crates/gpu/src/ctx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,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>)>>,
}

/// WGSL constants shared by every module (generated from the CPU pipeline's values).
Expand Down Expand Up @@ -367,6 +372,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
);
for (name, idx) in crate::params::finish_fields() {
s += &format!("const F_{name}: u32 = {idx}u;\n");
}
Expand Down Expand Up @@ -454,7 +464,7 @@ impl Gpu {
});
let max_buffer = limits.max_storage_buffer_binding_size.min(limits.max_buffer_size);
log::info!("gpu: {} ({:?}), {} kernels in {build_ms} ms, buffers ≤ {} MiB", info.name, info.backend, kernels.len(), max_buffer >> 20);
Ok(Gpu { device, queue, info, kernels, dummy, free: Default::default(), max_buffer })
Ok(Gpu { device, queue, info, kernels, dummy, free: Default::default(), max_buffer, grain: Default::default() })
}

/// A buffer of `len` 32-bit values with undefined contents (a recycled one when possible).
Expand Down Expand Up @@ -636,6 +646,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;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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 {
Expand Down Expand Up @@ -1017,6 +1065,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]
Expand Down
46 changes: 39 additions & 7 deletions crates/gpu/src/params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};

/// Entries per tone-curve table (`lightcraft_pipeline::finish` builds them at this size).
pub const CURVE_N: u32 = 1024;
Expand Down Expand Up @@ -60,6 +60,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, V2: GRAIN_AMT, GRAIN_SC, GRAIN_ROUGH), 1 = crystal layers (V3)
("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),
Expand Down Expand Up @@ -146,7 +152,8 @@ pub struct Present {
}

/// The `finish` kernel's parameter block and auxiliary table (tone LUT | chroma curve | sRGB LUT | curve LUTs |
/// mask terms) for `fp` with `masks` (their local adjustments' terms).
/// mask terms) 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).
pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Present) -> (Vec<u32>, Vec<f32>) {
let mut aux: Vec<f32> = fp.tone.lut().to_vec();
aux.extend_from_slice(fp.tone.chroma_lut());
Expand All @@ -163,6 +170,16 @@ pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Pr
for m in masks {
aux.extend_from_slice(m);
}
// 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("W", fp.w as u32);
Expand Down Expand Up @@ -248,12 +265,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);
Expand Down
29 changes: 26 additions & 3 deletions crates/gpu/src/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,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
Expand All @@ -142,7 +146,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`]).
Expand All @@ -156,11 +160,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
Expand All @@ -172,6 +192,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).
Expand All @@ -180,6 +201,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());
}

Expand Down Expand Up @@ -683,6 +705,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));
Expand All @@ -696,7 +719,7 @@ pub fn render(
chroma: masks.is_some() && prep.chroma.is_some(),
};
let (p, aux) = finish_block(&fp, &terms, &present);
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(n);
if fault == Some(crate::Fault::Validation) {
Expand Down
Loading