Skip to content
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
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
6 changes: 5 additions & 1 deletion apps/lightcraft-web/src/wire.rs
Original file line number Diff line number Diff line change
Expand Up @@ -451,7 +451,11 @@ mod tests {
let mut core = WorkerCore::default();
assert_eq!(core.needs_original(&wire), None, "demo scenes are generated");
let a = core.render(&wire, None).unwrap();
let b = job.run().rendered.unwrap();
// Worker serialization is compared exactly with the engine's CPU path. A native
// thumbnail job can select the GPU once ready, whose documented rounding may differ.
let decoded = job.source.load_source().unwrap();
let info = decoded.info_or(job.info.clone());
let b = lightcraft_engine::media::develop(&decoded.image, &info, &job.settings, &job.request, job.stages.as_deref(), false);
assert_eq!((a.image.width, a.image.height), (b.image.width, b.image.height));
assert_eq!(a.image.data, b.image.data);
assert_eq!(a.histogram, b.histogram);
Expand Down
3 changes: 3 additions & 0 deletions contributors/people.toml
Original file line number Diff line number Diff line change
Expand Up @@ -82,3 +82,6 @@ sync_github_name = true
[people.Peaperfish]
real_name = "Yule Wang"
display_name = "Brian Wang"

[people.nkovanen]
sync_github_name = true
7 changes: 6 additions & 1 deletion crates/gpu/src/params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,10 @@ const FIELDS: &[(&str, usize)] = &[
("VIG_POWER", 1),
("VIG_HL", 1),
("VIG_STYLE", 1),
// the window's offset in the whole output and the whole output's size (pixels)
// the vignette's frame (`FinishParams::vig_aff`): render pixel → frame pixel, and the frame's size
("VIG_AFF", 6),
("VIG_SIZE", 2),
// The full-output window origin used by dithering, never the vignette crop affine.
("VIG_VIEW", 4),
("GRAIN", 1),
("GRAIN_AMT", 1),
Expand Down Expand Up @@ -267,6 +270,8 @@ pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Pr
p.f("VIG_ASPECT_MIX", v.aspect_mix);
p.f("VIG_POWER", v.power);
p.f("VIG_HL", v.highlights);
p.fs("VIG_AFF", &fp.vig_aff);
p.fs("VIG_SIZE", &fp.vig_size);
p.u(
"VIG_STYLE",
match v.style {
Expand Down
12 changes: 7 additions & 5 deletions crates/gpu/src/wgsl/finish.wgsl
Original file line number Diff line number Diff line change
Expand Up @@ -586,15 +586,17 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {

// --- vignette (display linear, post-crop)
if (pu(F_VIG) != 0u) {
// the vignette belongs to the whole output frame, not to the window being drawn
let fw = pf(F_VIG_VIEW + 2u);
let fh = pf(F_VIG_VIEW + 3u);
// the vignette belongs to its frame (the whole output, or the crop), not to the pixels drawn
let fw = pf(F_VIG_SIZE);
let fh = pf(F_VIG_SIZE + 1u);
let aspect = fw / fh;
let amount = pf(F_VIG_AMOUNT);
let mixa = pf(F_VIG_ASPECT_MIX);
let power = pf(F_VIG_POWER);
let u = (pf(F_VIG_VIEW) + f32(x) + 0.5) / fw * 2.0 - 1.0;
let vv = (pf(F_VIG_VIEW + 1u) + f32(y) + 0.5) / fh * 2.0 - 1.0;
let px = f32(x) + 0.5;
let py = f32(y) + 0.5;
let u = (pf(F_VIG_AFF) * px + pf(F_VIG_AFF + 2u) * py + pf(F_VIG_AFF + 4u)) / fw * 2.0 - 1.0;
let vv = (pf(F_VIG_AFF + 1u) * px + pf(F_VIG_AFF + 3u) * py + pf(F_VIG_AFF + 5u)) / fh * 2.0 - 1.0;
let sx = 1.0 + (aspect - 1.0) * mixa;
let sy = 1.0 + (1.0 / aspect - 1.0) * mixa;
let ax = abs(u * max(sx, 1.0) / max(sx, sy));
Expand Down
105 changes: 102 additions & 3 deletions crates/gpu/tests/it/equivalence.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,22 @@ fn check_v3_luminance_cutoff(chroma: f32, pixel: [f32; 3], expected: [u8; 4]) {
let cpu = render(&src, &info, &s, &req).image;
let gpu = lightcraft_gpu::try_render(&src, &info, &s, &req, None).expect("GPU render without CPU fallback").image;
for image in [&cpu, &gpu] {
assert!(image.data.iter().all(|p| *p == image.data[0]));
for (actual, expected) in image.data[0].into_iter().zip(expected) {
assert!(actual.abs_diff(expected) <= 1, "chroma {chroma}: {:?}, expected {expected}", image.data[0]);
// A flat fractional color repeats the 8×8 Bayer tile, within adjacent byte values.
for pixel in &image.data {
assert_eq!(pixel[3], 255);
for (actual, expected) in pixel.iter().copied().zip(expected) {
assert!(actual.abs_diff(expected) <= 1, "chroma {chroma}: {pixel:?}, expected {expected}");
}
}
for channel in 0..3 {
let lo = image.data.iter().map(|p| p[channel]).min().unwrap();
let hi = image.data.iter().map(|p| p[channel]).max().unwrap();
assert!(hi - lo <= 1, "chroma {chroma}: channel {channel} spans {lo}..{hi}");
}
for y in 0..image.height {
for x in 0..image.width {
assert_eq!(image.get(x, y), image.get(x % 8, y % 8), "chroma {chroma}: Bayer tile at {x},{y}");
}
}
}
let (_, max, _) = diff(&cpu, &gpu);
Expand Down Expand Up @@ -1249,6 +1262,71 @@ fn soft_proofs_match() {
assert!(lightcraft_gpu::render(&src, &raw, &DevelopSettings::default(), &req, None).is_none(), "declined: the CPU renders it");
}

/// Issue #3484: the crop tool's uncropped view frames the post-crop vignette by the crop, on the
/// GPU as on the CPU, whole and as a zoomed window, with flips.
#[test]
fn crop_tool_vignette_matches() {
if !gpu() {
return;
}
let src = scene(2, 480, 320);
let mut s = DevelopSettings::default();
s.vignette.amount = -80.0;
s.vignette.midpoint = 20.0;
s.crop.geometry.rect = Rect { x0: 0.12, y0: 0.15, x1: 0.6, y1: 0.75 };
s.crop.geometry.angle = 5.0;
let info = SourceInfo::default();
let req = RenderRequest { apply_crop: false, ..RenderRequest::fit(480, 480) };
check("crop tool vignette", &src, &info, &s, &req);
let window = lightcraft_pipeline::PixelWindow { x: 100, y: 60, w: 240, h: 180 };
check("crop tool vignette, window", &src, &info, &s, &RenderRequest { window: Some(window), ..req });
s.crop.flip_h = true;
s.vignette.roundness = -40.0;
check("crop tool vignette, flip H", &src, &info, &s, &req);

// a crop below a pixel (0.25 × 0.75 px, around the centre of pixel (192, 128) of this 1:1 view):
// framed like the export, as a square, on both renderers; the vignette is there and on the crop:
// that pixel is darkened less than the far corner
s.crop.flip_h = false;
s.vignette.roundness = 0.0;
s.crop.geometry =
lightcraft_geom::CropGeometry { rect: Rect { x0: 192.4 / 480.0, y0: 128.2 / 320.0, x1: 192.65 / 480.0, y1: 128.95 / 320.0 }, angle: 0.0 };
s.vignette.feather = 100.0;
check("crop tool vignette, 0.25 x 0.75 px", &src, &info, &s, &req);
// (on a flat grey photo every difference is the vignette's)
let flat = Arc::new(Rgb32f { width: 480, height: 320, data: vec![[0.18; 3]; 480 * 320] });
check("crop tool vignette, 0.25 x 0.75 px, flat", &flat, &info, &s, &req);
let gpu_img = lightcraft_gpu::render(&flat, &info, &s, &req, None).expect("gpu render").image;
assert_eq!((gpu_img.width, gpu_img.height), (480, 320));
let unvignetted = render(&flat, &info, &DevelopSettings::default(), &req).image;
let darkened = |x: usize, y: usize| (0..3).map(|c| unvignetted.get(x, y)[c] as i64 - gpu_img.get(x, y)[c] as i64).sum::<i64>();
assert!(
darkened(192, 128) + 30 < darkened(477, 317),
"the 0.25 x 0.75 px crop's vignette isn't on the crop: {} vs {}",
darkened(192, 128),
darkened(477, 317)
);

// crops f32 can't frame (a size that rounds to 0, an edge that overflows, a power that
// overflows): both renderers show the whole-photo vignette, the one of a crop with nothing in it
s.vignette.feather = 50.0;
let mut empty = s.clone();
empty.crop.geometry = lightcraft_geom::CropGeometry { rect: Rect { x0: 0.3, y0: 0.3, x1: 0.3, y1: 0.3 }, angle: 0.0 };
for (name, side, roundness) in [("1e-50", 1e-50, 0.0), ("1e-39", 1e-39, 0.0), ("1e-22", 1e-22, 0.0), ("1e-6 at power 8", 1e-6, -100.0)] {
s.crop.geometry = lightcraft_geom::CropGeometry { rect: Rect { x0: 0.0, y0: 0.0, x1: side, y1: side }, angle: 0.0 };
s.vignette.roundness = roundness;
empty.vignette.roundness = roundness;
check(&format!("crop tool vignette, {name}"), &flat, &info, &s, &req);
let shown = lightcraft_gpu::render(&flat, &info, &s, &req, None).expect("gpu render").image;
let fallback = lightcraft_gpu::render(&flat, &info, &empty, &req, None).expect("gpu render").image;
let (mean, max, _) = diff(&shown, &fallback);
assert!(mean < MEAN_LSB && max <= MAX_LSB, "{name}: the GPU doesn't show the whole-photo vignette: mean {mean:.4}, max {max}");
let cpu_fallback = render(&flat, &info, &empty, &req).image;
let (mid, corner) = (cpu_fallback.get(cpu_fallback.width / 2, cpu_fallback.height / 2)[1], cpu_fallback.get(2, 2)[1]);
assert!(mid as i32 - corner as i32 > 20, "{name}: no whole-photo vignette to fall back to");
}
}

/// Spot removal on the device: Clone, Heal and Remove (automatic source, scored on the device),
/// brushed strokes, overlapping spots (each reads what the earlier ones left), feather 0 and
/// spots cut by the image edge.
Expand Down Expand Up @@ -1341,3 +1419,24 @@ fn device_histogram_is_exact() {
assert_eq!((r.image.width, r.image.height), (500, 400));
assert_eq!(r.histogram, lightcraft_raster::Histogram::of_srgb8(&r.image), "window");
}

#[test]
fn dithering_window_keeps_the_full_output_phase_without_a_vignette() {
if !gpu() {
return;
}
let src = Arc::new(Rgb32f::filled(480, 320, [0.123456; 3]));
let info = SourceInfo::default();
let s = DevelopSettings::default();
let req = RenderRequest { apply_crop: false, ..RenderRequest::fit(480, 480) };
let at = lightcraft_pipeline::PixelWindow { x: 7, y: 12, w: 120, h: 80 };
let full = lightcraft_gpu::render(&src, &info, &s, &req, None).expect("gpu render").image;
let part = lightcraft_gpu::render(&src, &info, &s, &RenderRequest { window: Some(at), ..req }, None).expect("gpu render").image;
assert!(full.data.iter().any(|p| p[0] != full.data[0][0]), "the flat image must exercise Bayer quantization");
assert_eq!((part.width, part.height), (at.w, at.h));
for y in 0..at.h {
for x in 0..at.w {
assert_eq!(part.get(x, y), full.get(at.x + x, at.y + y), "GPU Bayer phase at {x},{y}");
}
}
}
9 changes: 7 additions & 2 deletions crates/gpu/tests/mask_geometry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,11 @@ fn luma(img: &Rgba8, i: usize) -> f64 {
(p[0] as f64 + p[1] as f64 + p[2] as f64) / 3.0
}

/// Match the CPU geometry test: exclude the one-level quantization difference from centroid weights.
fn above_dither(d: f64) -> f64 {
(d - 1.5).max(0.0)
}

fn centroid(w: usize, weights: impl Iterator<Item = f64>) -> (f64, f64) {
let (mut sx, mut sy, mut n) = (0.0, 0.0, 0.0);
for (i, v) in weights.enumerate() {
Expand Down Expand Up @@ -140,9 +145,9 @@ fn masks_stay_on_the_content_under_every_geometry_change_on_the_gpu() {
let plain = on_gpu(&src, &unmasked, None);
// (where the marked photo differs from an unmarked one: a warp leaves light blank canvas)
let bare = on_gpu(&Arc::new(marked(false)), &unmasked, None);
let mark = centroid(plain.width, (0..plain.data.len()).map(|i| (luma(&plain, i) - luma(&bare, i)).max(0.0)));
let mark = centroid(plain.width, (0..plain.data.len()).map(|i| above_dither(luma(&plain, i) - luma(&bare, i))));
for (how, m) in [("fresh", on_gpu(&src, &s, None)), ("cached", on_gpu(&src, &s, Some(&cache)))] {
let at = centroid(m.width, (0..m.data.len()).map(|i| (luma(&m, i) - luma(&plain, i)).max(0.0)));
let at = centroid(m.width, (0..m.data.len()).map(|i| above_dither(luma(&m, i) - luma(&plain, i))));
let d = ((at.0 - mark.0).powi(2) + (at.1 - mark.1).powi(2)).sqrt();
assert!(d < 2.0, "{name} after {what} ({how}): the mask's effect is at {at:?}, the mark at {mark:?}");
}
Expand Down
59 changes: 53 additions & 6 deletions crates/pipeline/src/finish.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,42 @@ fn vignette(s: &DevelopSettings) -> Option<Vig> {
})
}

/// The vignette's frame ([`Frame::vignette_frame`]) as the kernels read it, in f32, for a `w × h`
/// render: the whole output's without a vignette (nothing reads it), or where the f32 kernels
/// can't evaluate the crop's, as for a crop far below a pixel (#3621 review).
fn vig_frame(frame: &Frame, s: &DevelopSettings, (w, h): (usize, usize), vig: Option<&Vig>) -> ([f32; 6], [f32; 2]) {
let f32s = |(a, (vw, vh)): (lightcraft_geom::Affine, (f64, f64))| (a.0.map(|v| v as f32), [vw as f32, vh as f32]);
let whole = f32s(frame.output_vignette_frame(w, h));
let Some(v) = vig else { return whole };
let (aff, size) = f32s(frame.vignette_frame(s, w, h));
if vig_frame_fits_f32(aff, size, (w, h), v.power) { (aff, size) } else { whole }
}

/// Whether the vignette kernels (CPU and GPU, in f32) stay finite over a `w × h` render with this
/// frame and power. A coefficient that fits f32 can still overflow at the far edge, and a position
/// that fits can overflow when raised to the power (up to 8): WGSL leaves what overflow gives
/// undefined. So this bounds every value the kernels compute, in f64, from the f32 parameters:
/// - the affine's products and sums are at most `S = |a|·X + |c|·Y + |e|` over the pixel centres
/// (X, Y: the last ones), whatever their order or cancellation, so `|u| ≤ U = S / vw · 2 + 1`,
/// and `V` alike;
/// - one of `sx`, `sy` is at least 1 and neither exceeds `k = max(aspect, 1 / aspect)`: so the
/// scaled `u · max(sx, 1) ≤ U · k`, the axis `|u| · max(sx, 1) / max(sx, sy) ≤ U`, and the
/// powered sum `≤ U^p + V^p`.
///
/// Each bound must stay 16× below `f32::MAX`, which covers the kernels' rounding, fused
/// multiply-adds and the GPU's approximate `pow`.
pub(crate) fn vig_frame_fits_f32(aff: [f32; 6], size: [f32; 2], (w, h): (usize, usize), power: f32) -> bool {
const LIMIT: f64 = f32::MAX as f64 / 16.0;
let [a, b, c, d, e, f] = aff.map(f64::from);
let [vw, vh, p] = [size[0], size[1], power].map(f64::from);
let (x, y) = (w.saturating_sub(1) as f64 + 0.5, h.saturating_sub(1) as f64 + 0.5);
let (su, sv) = (a.abs() * x + c.abs() * y + e.abs(), b.abs() * x + d.abs() * y + f.abs());
let (u, v) = (su / vw * 2.0 + 1.0, sv / vh * 2.0 + 1.0);
let k = (vw / vh).max(vh / vw);
// (every comparison is false for NaN)
vw > 0.0 && vh > 0.0 && [su, sv, u * k, v * k, u.powf(p) + v.powf(p)].iter().all(|&m| m <= LIMIT)
}

/// Hash constants of [`grain_noise`] (shared with the GPU kernel).
pub const GRAIN_HASH: [u32; 4] = [0x8da6_b343, 0xd816_3841, 0xcb1a_b31f, 0x5bd1_e995];

Expand Down Expand Up @@ -226,7 +262,11 @@ pub struct FinishParams {
pub w: usize,
pub h: usize,
pub px_per_long: f64,
/// The window's offset and the whole output's size (pixels): `(0, 0, w, h)` unless windowed.
/// The post-crop vignette's frame ([`Frame::vignette_frame`]): an affine from this render's
/// pixels (centres at +0.5) to that frame's pixels, and the frame's size in them.
pub vig_aff: [f32; 6],
pub vig_size: [f32; 2],
/// The window offset and whole-output size for pixel-aligned dithering, independent of the crop vignette.
pub view: [f32; 4],
/// Peak linear output relative to SDR white: 1 for SDR renders; `2^max_ev` for an HDR render
/// ([`OutputDepth::F32Hdr`] with HDR on), which keeps values above 1 instead of clipping them.
Expand Down Expand Up @@ -269,6 +309,8 @@ impl FinishParams {
});
let calibration = s.section_enabled("calibration");
let peak = s.hdr.peak();
let vig = if effects { vignette(s) } else { None };
let (vig_aff, vig_size) = vig_frame(frame, s, (w, h), vig.as_ref());
FinishParams {
peak,
calib: if calibration { crate::colorops::calibration_matrix(&s.calibration) } else { None },
Expand All @@ -279,7 +321,7 @@ impl FinishParams {
ops: ColorOps::new(s),
curves: curve_luts(&s.curve),
refine_sat: (s.curve.refine_saturation / 100.0).clamp(0.0, 1.0) as f32,
vig: if effects { vignette(s) } else { None },
vig,
to_out: space.from_working(),
out_luma: space.luma(),
out_trc: space.trc(),
Expand Down Expand Up @@ -309,6 +351,8 @@ impl FinishParams {
w,
h,
px_per_long,
vig_aff,
vig_size,
view: frame.view.map_or([0.0, 0.0, w as f32, h as f32], |v| [v.x as f32, v.y as f32, v.full_w as f32, v.full_h as f32]),
}
}
Expand Down Expand Up @@ -435,9 +479,11 @@ pub(crate) fn finish_with<T: Copy + Default + Send>(
let terms: Vec<[f32; MASK_TERMS]> = p.masks.iter().map(|m| mask_terms(&m.adjust)).collect();
let out_to_norm = fp.out_to_norm;
let long = fp.ow.max(fp.oh);
let [vx, vy, vw, vh] = fp.view;
// Pixel-aligned dithering keeps the output origin; only the vignette follows the crop.
let [vx, vy, _, _] = fp.view;
let (vx_u, vy_u) = (vx.round() as usize, vy.round() as usize);
// the vignette belongs to the whole output frame, not to the window being drawn
let [va, vb, vc, vd, ve, vf] = fp.vig_aff;
let [vw, vh] = fp.vig_size;
let aspect = vw / vh;

let srgb = srgb_lut();
Expand Down Expand Up @@ -496,8 +542,9 @@ pub(crate) fn finish_with<T: Copy + Default + Send>(

// --- vignette (display linear, post-crop)
if let Some(v) = vig {
let u = (vx + x as f32 + 0.5) / vw * 2.0 - 1.0;
let vv = (vy + y as f32 + 0.5) / vh * 2.0 - 1.0;
let (px, py) = (x as f32 + 0.5, y as f32 + 0.5);
let u = (va * px + vc * py + ve) / vw * 2.0 - 1.0;
let vv = (vb * px + vd * py + vf) / vh * 2.0 - 1.0;
let sx = 1.0 + (aspect - 1.0) * v.aspect_mix;
let sy = 1.0 + (1.0 / aspect - 1.0) * v.aspect_mix;
let (ax, ay) = ((u * sx.max(1.0) / sx.max(sy)).abs(), (vv * sy.max(1.0) / sx.max(sy)).abs());
Expand Down
Loading