diff --git a/crates/engine/src/shaders/keyers_gen.wgsl b/crates/engine/src/shaders/keyers_gen.wgsl index 9fed1f0a441bd3dd35a804c60ca1004faf565dd6..8d27c5c534a466f3313f471b41b6603b6739c4ae 100644 --- a/crates/engine/src/shaders/keyers_gen.wgsl +++ b/crates/engine/src/shaders/keyers_gen.wgsl @@ -24,10 +24,11 @@ fn luma_key_op(@builtin(global_invocation_id) gid: vec3) { store_dst(vec2(gid.xy), out_col); } // ============================================================================ -// 8. FastNoise (3D Perlin Gradient FBM with Seethe, Angle, Discontinuous & LUT) +// 8. FastNoise (3D Perlin FBM with Seethe, Angle, Discontinuous & gradient LUT) // p[0] = (x_scale, y_scale, detail, contrast) // p[1] = (brightness, seethe, discontinuous, center_x) -// p[2] = (center_y, angle_rad, inverted, use_lut) +// p[2] = (center_y, angle_rad, inverted, type) with type 2 = Gradient, else Two Color +// src_b = 256x1 straight-alpha color LUT indexed by the noise value // ============================================================================ fn grad3_dot(i: vec3, f: vec3) -> f32 { // Deterministic 3D gradient hash -> 12 Perlin cube-edge directions (smooth isotropic blobs!) @@ -63,6 +64,13 @@ fn noise3d(p: vec3) -> f32 { return mix(nxy0, nxy1, u_f.z); } +// Measured against Fusion 21.1 (same-lattice parameter sweeps): one octave spans +// 0.5 +/- 0.26 (std 0.106), later octaves are 2x frequency at half amplitude and +// are summed unnormalized, Discontinuous sums 2|n| per octave, Contrast pivots +// on 0.5 (on 0 when Discontinuous), Inverted runs before Brightness, Brightness +// adds half its value, and Gradient + Discontinuous shifts the lookup by 0.25. +const NOISE_GAIN: f32 = 0.40; + @compute @workgroup_size(8, 8) fn fast_noise_op(@builtin(global_invocation_id) gid: vec3) { let dims = textureDimensions(dst_tex); @@ -77,8 +85,9 @@ fn fast_noise_op(@builtin(global_invocation_id) gid: vec3) { let seethe = u.p[1].y; let disc = u.p[1].z > 0.5; let angle = u.p[2].y; + let gradient = u.p[2].w > 1.5; - // Fusion FastNoise uses frame-width isotropic units `(fu - center) * vec2(1, 1/aspect)` + // Frame-width isotropic units var rel = (fu - center) * vec2(1.0, 1.0 / aspect); if (abs(angle) > 1e-5) { let ca = cos(angle); @@ -87,49 +96,26 @@ fn fast_noise_op(@builtin(global_invocation_id) gid: vec3) { } let p = rel * scale; - var val = 0.5 + brightness; - if (detail > 1e-4) { - let octaves = i32(ceil(detail)); - var sum = 0.0; - var norm = 0.0; - var amp = 1.0; - var freq = 1.0; - for (var i = 0; i < 10; i = i + 1) { - if (i >= octaves) { break; } - let weight = select(amp, amp * fract(detail), i == octaves - 1 && fract(detail) > 1e-4); - let n = noise3d(vec3(p * freq, seethe + f32(i) * 1.73)); - sum = sum + select(n, abs(n), disc) * weight; - norm = norm + weight; - freq = freq * 2.0; - amp = amp * 0.5; - } - let n_avg = sum / max(norm, 1.0); - // Perlin3D normalized fBm: at Detail=1 (norm=1), *0.41 matches Fusion std=0.106 [0.24, 0.76]; - // at Detail=10 (norm=2), std naturally narrows to ~0.060 matching Fusion's pinpoint starfield threshold! - // Discontinuous mode takes |n| turbulence (~1.60x -> mean 0.34, std 0.14 in Type=0 TwoColor), - // pivoting Contrast around 0.5 when Contrast != 1 (verified via probe_moon_3d f02 & displace_wave f05/f07/f08). - if (disc) { - let grad_bias = select(0.0, 0.25, u.p[2].w > 1.5); - let base = n_avg * 1.60 + grad_bias; - val = (base - 0.5) * contrast + 0.5 + brightness; - } else { - val = n_avg * 0.41 * contrast + 0.5 + brightness; - } + let octaves = i32(ceil(detail)); + var sum = 0.0; + var amp = 1.0; + var freq = 1.0; + for (var i = 0; i < octaves; i = i + 1) { + let weight = select(amp, amp * fract(detail), i == octaves - 1 && fract(detail) > 1e-4); + let n = noise3d(vec3(p * freq, seethe + f32(i) * 1.73)) * NOISE_GAIN; + sum = sum + weight * select(n, 2.0 * abs(n), disc); + freq = freq * 2.0; + amp = amp * 0.5; } - val = clamp(val, 0.0, 1.0); + + var val = select(0.5 + sum, sum, disc); + val = select((val - 0.5) * contrast + 0.5, val * contrast, disc); + if (gradient && disc) { val = val + 0.25; } if (u.p[2].z > 0.5) { val = 1.0 - val; } - var col: vec4; - if (u.p[2].w > 0.5) { - // High-precision 256x1 gradient LUT in src_b (supports razor-sharp thresholds like starfields!) - col = textureSampleLevel(src_b, samp_lin, vec2(val, 0.5), 0.0); - } else { - let lut_pos = val * 12.0; - let i0 = u32(clamp(floor(lut_pos), 0.0, 11.0)); - let f = lut_pos - f32(i0); - col = mix(u.p[3u + i0], u.p[4u + i0], f); - } - let out_col = vec4(col.rgb * col.a, col.a); - store_dst(vec2(gid.xy), out_col); + val = clamp(val + 0.5 * brightness, 0.0, 1.0); + + // Fusion leaves the ramp color unpremultiplied; downstream Merge treats it as premultiplied + store_dst(vec2(gid.xy), textureSampleLevel(src_b, samp_lin, vec2(val, 0.5), 0.0)); } // ============================================================================ // 12. Fuse.Outline (Clover's exact 2020 Outline.fuse passes!) diff --git a/crates/engine/tests/fast_noise.rs b/crates/engine/tests/fast_noise.rs new file mode 100644 index 0000000000000000000000000000000000000000..066c829b341ac8aebee388a6f12e205827d22e8d --- /dev/null +++ b/crates/engine/tests/fast_noise.rs @@ -0,0 +1,139 @@ +//! FastNoise parameter transfer curves, checked pixel-for-pixel against a same-lattice baseline. +//! The curves were measured from Fusion 21.1 sweeps where only one input changes. + +use engine::{Engine, ExportOptions, export_saver_png_sequence}; +use model::Comp; + +const SIZE: u32 = 96; +const LINEAR_GRADIENT: &str = "Gradient { Colors = { [0] = { 0, 0, 0, 1 }, [1] = { 1, 1, 1, 1 } } }"; + +fn render(tag: &str, overrides: &[(&str, &str)]) -> Vec<[f32; 4]> { + let mut inputs: Vec<(&str, &str)> = vec![ + ("Detail", "1"), + ("XScale", "4"), + ("Color1Alpha", "1"), + ]; + for (key, value) in overrides { + inputs.retain(|(k, _)| k != key); + inputs.push((key, value)); + } + let inputs: String = inputs.iter().map(|(k, v)| format!("\t\t\t\t{k} = Input {{ Value = {v}, }},\n")).collect(); + + let dir = std::env::temp_dir().join(format!("fission-fast-noise-{}-{tag}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let path = dir.join("out_0000.png"); + let path = path.to_string_lossy().replace('\\', "\\\\"); + let src = format!( + r#"Composition {{ + RenderRange = {{ 0, 0 }}, + Tools = ordered() {{ + Noise = FastNoise {{ + Inputs = {{ + Width = Input {{ Value = {SIZE}, }}, + Height = Input {{ Value = {SIZE}, }}, +{inputs} }}, + }}, + Black = Background {{ + Inputs = {{ + Width = Input {{ Value = {SIZE}, }}, + Height = Input {{ Value = {SIZE}, }}, + TopLeftAlpha = Input {{ Value = 1, }}, + }}, + }}, + Over = Merge {{ + Inputs = {{ + Background = Input {{ SourceOp = "Black", Source = "Output", }}, + Foreground = Input {{ SourceOp = "Noise", Source = "Output", }}, + }}, + }}, + Saver1 = Saver {{ + Inputs = {{ + Clip = Input {{ Value = Clip {{ Filename = "{path}", FormatID = "PNGFormat", Saving = true, }}, }}, + Input = Input {{ SourceOp = "Over", Source = "Output", }}, + }}, + }}, + }}, + Prefs = {{ Comp = {{ FrameFormat = {{ Width = {SIZE}, Height = {SIZE}, Rate = 24, }}, }}, }}, +}}"# + ); + let comp = Comp::from_fusion_str(&src).expect("parse FastNoise comp"); + let mut engine = Engine::new_headless().expect("gpu"); + export_saver_png_sequence(&mut engine, &comp, &ExportOptions::default(), |_| {}).expect("export"); + let img = image::open(dir.join("out_0000.png")).expect("decode").to_rgba8(); + let _ = std::fs::remove_dir_all(&dir); + img.pixels().map(|p| p.0.map(|c| c as f32 / 255.0)).collect() +} + +/// Asserts `out == expected(base)` per pixel on pixels where `valid(base)` holds, and that enough pixels qualify. +fn assert_transfer(base: &[[f32; 4]], out: &[[f32; 4]], valid: impl Fn(f32) -> bool, expected: impl Fn(f32) -> f32) { + let mut checked = 0; + for (b, o) in base.iter().zip(out) { + if !valid(b[0]) { + continue; + } + checked += 1; + let want = expected(b[0]); + assert!((o[0] - want).abs() <= 4.0 / 255.0, "base {:.3}: got {:.3}, want {want:.3}", b[0], o[0]); + } + assert!(checked > base.len() / 4, "only {checked} of {} pixels exercised", base.len()); +} + +fn std_dev(px: &[[f32; 4]]) -> f32 { + let mean = px.iter().map(|p| p[0]).sum::() / px.len() as f32; + (px.iter().map(|p| (p[0] - mean).powi(2)).sum::() / px.len() as f32).sqrt() +} + +#[test] +fn brightness_adds_half_its_value() { + let base = render("b0", &[]); + let bright = render("b1", &[("Brightness", "0.2")]); + assert_transfer(&base, &bright, |a| a < 0.85, |a| a + 0.1); +} + +#[test] +fn contrast_pivots_on_half() { + let base = render("c0", &[]); + let contrast = render("c1", &[("Contrast", "2")]); + assert_transfer(&base, &contrast, |a| (0.3..0.7).contains(&a), |a| (a - 0.5) * 2.0 + 0.5); +} + +#[test] +fn discontinuous_folds_noise_and_scales_contrast_from_zero() { + let base = render("d0", &[]); + let disc = render("d1", &[("Discontinuous", "1")]); + assert_transfer(&base, &disc, |_| true, |a| 2.0 * (a - 0.5).abs()); + let disc_contrast = render("d2", &[("Discontinuous", "1"), ("Contrast", "0.5")]); + assert_transfer(&base, &disc_contrast, |_| true, |a| (a - 0.5).abs()); +} + +#[test] +fn inverted_runs_before_brightness() { + let base = render("i0", &[]); + let inverted = render("i1", &[("Inverted", "1"), ("Brightness", "0.2")]); + assert_transfer(&base, &inverted, |a| a > 0.1, |a| 1.0 - a + 0.1); +} + +#[test] +fn gradient_with_discontinuous_shifts_lookup_by_quarter() { + let base = render("g0", &[]); + let plain = render("g1", &[("Type", "1"), ("Gradient", LINEAR_GRADIENT)]); + assert_transfer(&base, &plain, |_| true, |a| a); + let disc = render("g2", &[("Type", "1"), ("Gradient", LINEAR_GRADIENT), ("Discontinuous", "1")]); + assert_transfer(&base, &disc, |_| true, |a| (2.0 * (a - 0.5).abs() + 0.25).min(1.0)); +} + +#[test] +fn detail_octaves_sum_unnormalized() { + let one = std_dev(&render("o1", &[("XScale", "8")])); + let three = std_dev(&render("o3", &[("XScale", "8"), ("Detail", "3")])); + // sqrt(1 + 1/4 + 1/16) = 1.146 for independent octaves at amplitudes 1, 1/2, 1/4 + assert!((1.05..1.25).contains(&(three / one)), "std ratio {}", three / one); +} + +#[test] +fn colors_are_not_premultiplied_by_alpha() { + let px = render("a0", &[("Color1Alpha", "0.5"), ("Color1Red", "1"), ("Color2Alpha", "0.5")]); + // red is 1 at both ends of the ramp, so a premultiplied output would land near 0.5 + assert!(px.iter().all(|p| p[0] > 0.99), "min red {}", px.iter().map(|p| p[0]).fold(1.0, f32::min)); + assert!(std_dev(&px.iter().map(|p| [p[1], 0.0, 0.0, 0.0]).collect::>()) > 0.05); +}