diff --git a/crates/nodes/src/filters.rs b/crates/nodes/src/filters.rs index b433e8cf..726cf6e4 100644 --- a/crates/nodes/src/filters.rs +++ b/crates/nodes/src/filters.rs @@ -509,42 +509,22 @@ fn anisotropic_blur(ctx: &Ctx) -> CookResult { Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| transform_sample(&b, u, v, [0.0, 0.0], [1.0, 1.0], -a / TAU, false, true).unwrap_or([0.0; 4]))]) } -/// Most extra horizontal passes `blur_xy` runs: a cost bound, whatever sigma it is given. -const MAX_BLUR_PASSES: i64 = 64; -/// Widest horizontal kernel half-width `blur_xy` builds: a cost bound on the kernel allocation. -const MAX_KERNEL_RADIUS: i64 = 512; - fn blur_xy(img: &Image, sx: f32, sy: f32, tile: bool) -> Image { if !sx.is_finite() || !sy.is_finite() { return img.clone(); } // Separable: a horizontal-only Gaussian is a 2D one on an image stretched vertically, so - // blur fully with the smaller sigma and add the extra along x by repeated small passes. + // blur fully with the smaller sigma and add the extra along x. + let cap = img.w.max(img.h) as f32; + let (sx, sy) = (sx.min(cap), sy.min(cap)); let base = ops::gaussian(img, sy, tile); let extra = (sx * sx - sy * sy).max(0.0).sqrt(); if extra < 0.1 { return base; } - let n = ((extra / 2.0).ceil().max(1.0) as i64).min(MAX_BLUR_PASSES); - let step = extra / (n as f32).sqrt(); - let mut out = base; - for _ in 0..n { - let src = out.clone(); - let r = ((step * 2.0).ceil() as i64).clamp(1, MAX_KERNEL_RADIUS); - let k: Vec = (-r..=r).map(|i| (-(i * i) as f32 / (2.0 * step * step)).exp()).collect(); - let sum: f32 = k.iter().sum(); - out = Image::generate(src.w, src.h, src.kind, |x, y| { - let mut acc = [0.0; 4]; - for (j, kv) in k.iter().enumerate() { - let p = src.get(x as i64 + j as i64 - r, y as i64, tile); - for c in 0..4 { - acc[c] += p[c] * kv / sum; - } - } - acc - }); - } - out + // Independent Gaussians compose in quadrature, so one horizontal Gaussian of sigma `extra` + // finishes the job (box passes: O(1) per pixel, sigma clamped to the image size). + ops::gaussian_h(&base, extra, tile) } fn non_uniform_blur(ctx: &Ctx) -> CookResult { @@ -967,3 +947,7 @@ fn skew(ctx: &Ctx) -> CookResult { if vert { img.sample(u, v + (u - 0.5) * k, ctx.tile) } else { img.sample(u + (v - 0.5) * k, v, ctx.tile) } })]) } + +#[cfg(test)] +#[path = "filters.test.rs"] +mod tests; diff --git a/crates/nodes/src/filters.test.rs b/crates/nodes/src/filters.test.rs index f1d9e3d4..0d558105 100644 --- a/crates/nodes/src/filters.test.rs +++ b/crates/nodes/src/filters.test.rs @@ -22,3 +22,32 @@ mod normal_blend_tests { assert!(out[0].data.iter().all(|v| v.is_finite()), "NaN or Inf in the blended normal"); } } + +// Tests for the blur helpers. + +use materialcraft_image::{Image, Kind}; + +use super::blur_xy; + +fn noise(n: u32) -> Image { + Image::generate(n, n, Kind::Gray, |x, y| [((x * 7 + y * 13) % 17) as f32 / 16.0, 0.0, 0.0, 1.0]) +} + +#[test] +fn blur_xy_huge_sigma_is_bounded_and_finite() { + let t = std::time::Instant::now(); + let out = blur_xy(&noise(64), 1e14, 1.0, true); + assert!(out.data.iter().all(|v| v.is_finite())); + assert!(t.elapsed().as_secs() < 20, "took {:?}", t.elapsed()); +} + +#[test] +fn blur_xy_horizontal_blur_is_stronger_than_vertical() { + // Vertical stripes survive a vertical-only blur but are smoothed by a horizontal one. + let img = Image::generate(64, 64, Kind::Gray, |x, _| [(x % 2) as f32, 0.0, 0.0, 1.0]); + let out = blur_xy(&img, 6.0, 0.0, true); + let range = out.data.chunks(1).map(|v| v[0]).fold((f32::MAX, f32::MIN), |a, v| (a.0.min(v), a.1.max(v))); + assert!(range.1 - range.0 < 0.1, "stripes should be blurred away: {range:?}"); + let mean: f32 = out.data.iter().sum::() / out.data.len() as f32; + assert!((mean - 0.5).abs() < 0.02); +} diff --git a/crates/nodes/src/lib.rs b/crates/nodes/src/lib.rs index a30494ac..e0a0dfb7 100644 --- a/crates/nodes/src/lib.rs +++ b/crates/nodes/src/lib.rs @@ -190,4 +190,37 @@ mod tests { assert!((atomic::levels_fn(0.5, 0.0, 0.5, 1.0, 0.0, 1.0) - 0.5).abs() < 1e-5); assert_eq!(atomic::levels_fn(0.2, 0.4, 0.5, 0.8, 0.0, 1.0), 0.0); } + + /// Cook one node with a single overridden parameter on a `size`-square noise input. + fn cook_with(id: &str, key: &str, value: materialcraft_core::Value, size: u32) -> Image { + let def = find(id).unwrap(); + let mut over = BTreeMap::new(); + over.insert(key.to_string(), value); + let params = resolve_params(def, &over); + let no_res = |_: &str| None; + let vars = BTreeMap::new(); + let img = Image::generate(size, size, Kind::Gray, |x, y| [((x * 7 + y * 13) % 17) as f32 / 16.0, 0.0, 0.0, 1.0]); + let inputs = [Some(img)]; + let ctx = Ctx { w: size, h: size, seed: 7, tile: true, inputs: &inputs, params: ¶ms, resource: &no_res, vars: &vars }; + (def.cook)(&ctx).unwrap().remove(0) + } + + /// A hostile blur intensity must return promptly (it used to loop for ~i64::MAX passes). + #[test] + fn anisotropic_blur_hostile_intensity_is_bounded() { + let t = std::time::Instant::now(); + let out = cook_with("anisotropic_blur", "intensity", materialcraft_core::Value::Float(1e15), 64); + assert!(out.data.iter().all(|v| v.is_finite())); + assert!(t.elapsed().as_secs() < 20, "took {:?}", t.elapsed()); + } + + /// Large-but-legal intensity stays close to the Gaussian it approximates. + #[test] + fn anisotropic_blur_matches_horizontal_gaussian() { + let img = Image::generate(128, 128, Kind::Gray, |x, y| [((x * 7 + y * 13) % 17) as f32 / 16.0, 0.0, 0.0, 1.0]); + let out = cook_with("anisotropic_blur", "intensity", materialcraft_core::Value::Float(8.0), 128); + // Mean is preserved by a normalised blur on a tiling image. + let mean = |i: &Image| (0..128 * 128).map(|k| i.data[k]).sum::() / (128.0 * 128.0); + assert!((mean(&out) - mean(&img)).abs() < 0.02); + } } diff --git a/crates/nodes/src/ops.rs b/crates/nodes/src/ops.rs index cd3b0405..f120be8e 100644 --- a/crates/nodes/src/ops.rs +++ b/crates/nodes/src/ops.rs @@ -14,23 +14,51 @@ pub fn gaussian(img: &Image, sigma: f32, tile: bool) -> Image { } let sigma = sigma.min(img.w.max(img.h) as f32); if sigma < 3.0 { - let r = (sigma * 3.0).ceil() as i64; - let k: Vec = (-r..=r).map(|i| (-(i * i) as f32 / (2.0 * sigma * sigma)).exp()).collect(); - let s: f32 = k.iter().sum(); - let k: Vec = k.iter().map(|v| v / s).collect(); + let (k, r) = gauss_kernel(sigma); let pass = |src: &Image, horizontal: bool| convolve_1d(src, &k, r, horizontal, tile); return pass(&pass(img, true), false); } - // Box widths for three passes (Kovesi, "Fast almost-Gaussian filtering"). + let mut out = img.clone(); + for r in box_radii(sigma) { + out = box_1d(&box_1d(&out, r, true, tile), r, false, tile); + } + out +} + +/// Horizontal-only Gaussian (sigma in pixels, clamped to the image size), O(1) per pixel. +pub fn gaussian_h(img: &Image, sigma: f32, tile: bool) -> Image { + if sigma.is_nan() || sigma <= 0.05 || !sigma.is_finite() { + return img.clone(); + } + let sigma = sigma.min(img.w.max(img.h) as f32); + if sigma < 3.0 { + let (k, r) = gauss_kernel(sigma); + return convolve_1d(img, &k, r, true, tile); + } + let mut out = img.clone(); + for r in box_radii(sigma) { + out = box_1d(&out, r, true, tile); + } + out +} + +fn gauss_kernel(sigma: f32) -> (Vec, i64) { + let r = (sigma * 3.0).ceil() as i64; + let k: Vec = (-r..=r).map(|i| (-(i * i) as f32 / (2.0 * sigma * sigma)).exp()).collect(); + let s: f32 = k.iter().sum(); + (k.iter().map(|v| v / s).collect(), r) +} + +/// Box radii for three passes approximating a Gaussian (Kovesi, "Fast almost-Gaussian filtering"). +fn box_radii(sigma: f32) -> [i64; 3] { let n = 3.0f32; let wl = ((12.0 * sigma * sigma / n + 1.0).sqrt()).floor() as i64; let wl = if wl % 2 == 0 { wl - 1 } else { wl }; let wu = wl + 2; let m = ((12.0 * sigma * sigma - n * (wl * wl) as f32 - 4.0 * n * wl as f32 - 3.0 * n) / (-4.0 * wl as f32 - 4.0)).round() as i64; - let mut out = img.clone(); - for i in 0..3 { - let r = (if i < m { wl } else { wu } - 1) / 2; - out = box_1d(&box_1d(&out, r.max(0), true, tile), r.max(0), false, tile); + let mut out = [0; 3]; + for (i, o) in out.iter_mut().enumerate() { + *o = ((if (i as i64) < m { wl } else { wu } - 1) / 2).max(0); } out }