From 902a25b57d4aea1e07151c56306ba0d97db5a278 Mon Sep 17 00:00:00 2001 From: clover caruso Date: Wed, 2 Dec 2026 15:31:44 -0800 Subject: [PATCH] feat(engine): implement Photron.Primatte4 & utility built-ins, calibrate Shader/VectorTransform/Texture Assisted-by: claude-sonnet-5.5 --- .../engine/src/eval/deep_flow/deep_pixel.rs | 94 ++---- crates/engine/src/eval/deep_flow/flow.rs | 59 ++-- crates/engine/src/eval/deep_flow/tests.rs | 136 +++++---- .../engine/src/eval/deep_flow/tests/flow.rs | 64 ++-- crates/engine/src/eval/mod.rs | 14 +- crates/engine/src/eval/primatte_misc.rs | 285 ++++++++++++++++++ crates/engine/src/eval/primatte_misc/tests.rs | 276 +++++++++++++++++ crates/engine/src/shaders/deep_flow.wgsl | 146 ++++----- crates/engine/src/shaders/primatte_misc.wgsl | 236 +++++++++++++++ 9 files changed, 1029 insertions(+), 281 deletions(-) create mode 100644 crates/engine/src/eval/primatte_misc.rs create mode 100644 crates/engine/src/eval/primatte_misc/tests.rs create mode 100644 crates/engine/src/shaders/primatte_misc.wgsl diff --git a/crates/engine/src/eval/deep_flow/deep_pixel.rs b/crates/engine/src/eval/deep_flow/deep_pixel.rs index 1335ca7ba531d1a5b46405d80331a0a11231f531..f46246306cf177fb8925efc5007bff20f58853c5 100644 --- a/crates/engine/src/eval/deep_flow/deep_pixel.rs +++ b/crates/engine/src/eval/deep_flow/deep_pixel.rs @@ -2,8 +2,6 @@ use super::*; -const LIGHT_TYPES: [&str; 3] = ["Directional", "Point", "Spot"]; - impl Engine { /// `SSAO`: hemisphere multi-tap ambient occlusion from `aux.z` and `aux.normal` (normals are /// derived from depth when absent). `Mode = Composite` darkens the image, `AO Only` outputs the occlusion term. @@ -59,8 +57,10 @@ impl Engine { self.df_run(node, frame_i, pass, &fin, &u, aux, enc, stats) } - /// `Shader`: deep-pixel relighting from `aux.normal` (or normals derived from `aux.z` / luminance) - /// with Directional / Point / Spot lights, Blinn-Phong specular and an optional equirectangular reflection map. + /// `Shader`: relights from `aux.normal` with a directional light (`EquatorAngle` / `PolarHeight`): + /// `Ambient` + `Diffuse` Lambert, `Specular` highlight tinted by `SpecularRed/Green/Blue`, and + /// `Reflection` of `EnvironmentReflectionMap` (`ReflectionType` = Screen / Spherical / Refraction). + /// Without normals only `Ambient` remains. #[allow(clippy::too_many_arguments)] pub(in crate::eval) fn eval_deep_shader( &mut self, @@ -79,69 +79,23 @@ impl Engine { if blend.0 <= 1e-6 && !blend.1 { return src; } - let map = self.df_input( - comp, - node, - &["EquirectangularMap", "ReflImage", "ReflectionImage"], - time, - enc, - visiting, - stats, - ); + let map = self.df_input(comp, node, &["EnvironmentReflectionMap"], time, enc, visiting, stats); let aux = src.aux.clone(); - let z = aux.as_ref().and_then(|a| a.z.as_ref()).map(|z| z.view.clone()); let normal = aux.as_ref().and_then(|a| a.normal.as_ref()).map(|n| n.view.clone()); let fin = self.df_fin(comp, node, time, blend, src.size, enc, visiting, stats); - let n = |keys: &[&str], d: f64| num_any(comp, node, keys, time, d, &self.expr) as f32; - let (w, h) = (src.size[0] as f32, src.size[1] as f32); - let light_type = enum_idx(comp, node, "LightType", &LIGHT_TYPES, time, 0, &self.expr); - // Light placement in y-up pixel space, +Z toward the viewer. - let pt = |key: &str| comp.eval_point(node, key, time, [0.5, 0.5], &self.expr); - let pos = { - let p = pt("LightPosition"); - [p[0] as f32 * w, p[1] as f32 * h, n(&["LightHeight"], 0.5) * w] - }; - let to_light = if light_type == 0 { - let (az, el) = (n(&["Angle"], 0.0).to_radians(), n(&["Elevation"], 90.0).to_radians()); - [el.cos() * az.cos(), el.cos() * az.sin(), el.sin()] - } else { - pos - }; - let axis = { - let t = pt("SpotTarget"); - let d = [t[0] as f32 * w - pos[0], t[1] as f32 * h - pos[1], -pos[2]]; - let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt().max(1e-6); - [d[0] / len, d[1] / len, d[2] / len] - }; - + let n = |key: &str, d: f64| num_any(comp, node, &[key], time, d, &self.expr) as f32; + let (equator, polar) = (n("EquatorAngle", 45.0).to_radians(), n("PolarHeight", 45.0).to_radians()); let mut u = UniformParams::default(); - u.p[0] = [ - light_type as f32, - n(&["Ambient"], 0.2).max(0.0), - n(&["Diffuse"], 0.8).max(0.0), - n(&["Specular"], 0.0).max(0.0), - ]; - u.p[1] = [ - n(&["SpecularExponent"], 32.0).max(1.0), - n(&["Reflectivity"], 1.0).max(0.0), - b2f(map.is_some()), - b2f(normal.is_some()), - ]; - u.p[2] = [to_light[0], to_light[1], to_light[2], 0.0]; - u.p[3] = [axis[0], axis[1], axis[2], n(&["ConeAngle"], 30.0).clamp(1.0, 179.0).to_radians().cos()]; - u.p[4] = [ - n(&["LightColorRed"], 1.0), - n(&["LightColorGreen"], 1.0), - n(&["LightColorBlue"], 1.0), - n(&["SpotSoftness"], 0.1).max(0.0), - ]; - u.p[5] = [n(&["ZScale"], 1.0), n(&["BumpHeight"], 10.0), b2f(z.is_some()), 0.0]; + u.p[0] = [n("Ambient", 0.25), n("Diffuse", 1.0), n("Specular", 1.0), n("Reflection", 1.0)]; + u.p[1] = [b2f(map.is_some()), b2f(normal.is_some()), n("ReflectionType", 0.0).round(), 0.0]; + u.p[2] = [polar.cos() * equator.cos(), polar.cos() * equator.sin(), polar.sin(), 0.0]; + u.p[3] = [n("SpecularRed", 1.0), n("SpecularGreen", 1.0), n("SpecularBlue", 1.0), 0.0]; let pass = DfPass { tag: "Shader", op: DeepFlowOp::Relight, - srcs: [Some(&src.view), z.as_deref(), normal.as_deref(), map.as_ref().map(|m| &*m.view)], + srcs: [Some(&src.view), None, normal.as_deref(), map.as_ref().map(|m| &*m.view)], hashes: &[src.content_hash, map.as_ref().map_or(0, |m| m.content_hash)], size: src.size, depth: self.node_depth(comp, node, time, Some(src.depth)), @@ -149,8 +103,9 @@ impl Engine { self.df_run(node, frame_i, pass, &fin, &u, aux, enc, stats) } - /// `Texture`: samples a `Texture` / `TextureImage` through the UV channels (RG) of `Input`, - /// with `UScale` / `VScale` / `UOffset` / `VOffset`; `Input` alpha is the coverage. + /// `Texture`: samples `Texture` through the UV channels (RG) of `Input`: swap, `UScale` / `VScale` / + /// `UOffset` / `VOffset`, `Rotate90`, then flips; `Input` alpha is the coverage. Without a `Texture` input + /// the image passes through (Blend, EffectMask and Process* still apply). #[allow(clippy::too_many_arguments)] pub(in crate::eval) fn eval_texture_tool( &mut self, @@ -166,26 +121,27 @@ impl Engine { return self.dummy.clone(); }; let blend = self.df_blend(comp, node, time); - let Some(tex) = self.df_input(comp, node, &["Texture", "TextureImage"], time, enc, visiting, stats) else { - return src; - }; if blend.0 <= 1e-6 && !blend.1 { return src; } + let tex = self.df_input(comp, node, &["Texture", "TextureImage"], time, enc, visiting, stats); let fin = self.df_fin(comp, node, time, blend, src.size, enc, visiting, stats); - let n = |keys: &[&str], d: f64| num_any(comp, node, keys, time, d, &self.expr) as f32; + let n = |key: &str, d: f64| num_any(comp, node, &[key], time, d, &self.expr) as f32; + let flag = |key: &str| b2f(n(key, 0.0) > 0.5); let mut u = UniformParams::default(); - u.p[0] = [n(&["UScale"], 1.0), n(&["VScale"], 1.0), n(&["UOffset"], 0.0), n(&["VOffset"], 0.0)]; - u.p[1][0] = enum_idx(comp, node, "Edges", &EDGES, time, 2, &self.expr) as f32; + u.p[0] = [n("UScale", 1.0), n("VScale", 1.0), n("UOffset", 0.0), n("VOffset", 0.0)]; + let edges = enum_idx(comp, node, "Edges", &EDGES, time, 2, &self.expr) as f32; + u.p[1] = [edges, b2f(tex.is_some()), flag("SwapUV0"), flag("Rotate90")]; + u.p[2] = [flag("FlipHoriz"), flag("FlipVert"), 0.0, 0.0]; let pass = DfPass { tag: "Texture", op: DeepFlowOp::Texture, - srcs: [Some(&src.view), Some(&tex.view), None, None], - hashes: &[src.content_hash, tex.content_hash], + srcs: [Some(&src.view), tex.as_ref().map(|t| &*t.view), None, None], + hashes: &[src.content_hash, tex.as_ref().map_or(0, |t| t.content_hash)], size: src.size, - depth: self.node_depth(comp, node, time, Some(src.depth.max(tex.depth))), + depth: self.node_depth(comp, node, time, Some(tex.as_ref().map_or(src.depth, |t| src.depth.max(t.depth)))), }; self.df_run(node, frame_i, pass, &fin, &u, src.aux.clone(), enc, stats) } diff --git a/crates/engine/src/eval/deep_flow/flow.rs b/crates/engine/src/eval/deep_flow/flow.rs index 43771e9ff6a8cc4710753b72750419984e6f940c..6a2af4b34bdfa0d4b181a3c24ad8d4302ecbb38e 100644 --- a/crates/engine/src/eval/deep_flow/flow.rs +++ b/crates/engine/src/eval/deep_flow/flow.rs @@ -310,9 +310,9 @@ impl Engine { self.df_with_aux(node, frame_i, key, src, aux) } - /// `VectorTransform`: flips, inverts, normalizes, scales (`XScale`/`YScale`), rotates (`Angle`) and offsets - /// (`XOffset`/`YOffset`) motion vectors. `Channel` = `Vector` / `BackVector` / `Color` (RG) selects one - /// source; the default (`Auto`) transforms every present aux vector, falling back to RG of the image. + /// `VectorTransform`: scales (`XSize` / `YSize`, or `Size` and `Aspect` with `UseSizeAndAspect`), rotates + /// (`Angle`) and `SmoothVector`-blurs the `aux.vector` / `aux.back_vector` motion vectors, mixed in by + /// `AttenuateVect`. Colour and alpha are untouched; an image without vectors passes through. #[allow(clippy::too_many_arguments)] pub(in crate::eval) fn eval_vector_transform( &mut self, @@ -327,56 +327,35 @@ impl Engine { let Some(src) = self.df_input(comp, node, &INPUT_PORTS, time, enc, visiting, stats) else { return self.dummy.clone(); }; - let blend = self.df_blend(comp, node, time); - if blend.0 <= 1e-6 && !blend.1 { - return src; - } - let channel = enum_idx(comp, node, "Channel", &["Auto", "Vector", "BackVector", "Color"], time, 0, &self.expr); - let aux = src.aux.clone(); - let vector = aux.as_ref().and_then(|a| a.vector.clone()).filter(|_| matches!(channel, 0 | 1)); - let back = aux.as_ref().and_then(|a| a.back_vector.clone()).filter(|_| matches!(channel, 0 | 2)); - let use_color = channel == 3 || (channel == 0 && vector.is_none() && back.is_none()); - if vector.is_none() && back.is_none() && !use_color { + if !src.aux.as_ref().is_some_and(|a| a.vector.is_some() || a.back_vector.is_some()) { return src; } - let n = |keys: &[&str], d: f64| num_any(comp, node, keys, time, d, &self.expr) as f32; - let flag = |key: &str| b2f(num_any(comp, node, &[key], time, 0.0, &self.expr) > 0.5); - let angle = n(&["Angle"], 0.0).to_radians(); + let n = |key: &str, d: f64| num_any(comp, node, &[key], time, d, &self.expr) as f32; + let (x_size, y_size) = if n("UseSizeAndAspect", 0.0) > 0.5 { + (n("Size", 1.0), n("Size", 1.0) * n("Aspect", 1.0)) + } else { + (n("XSize", 1.0), n("YSize", 1.0)) + }; + let angle = n("Angle", 0.0).to_radians(); let mut u = UniformParams::default(); - u.p[0] = [n(&["XScale"], 1.0), n(&["YScale"], 1.0), angle.cos(), angle.sin()]; - u.p[1] = [n(&["XOffset"], 0.0), n(&["YOffset"], 0.0), flag("FlipX"), flag("FlipY")]; - u.p[2] = [flag("Invert"), flag("Normalize"), 0.0, 0.0]; - let fin = self.df_fin(comp, node, time, blend, src.size, enc, visiting, stats); + u.p[0] = [x_size, y_size, angle.cos(), angle.sin()]; + u.p[1] = [n("AttenuateVect", 1.0).clamp(0.0, 1.0), n("SmoothVector", 0.0).max(0.0), 0.0, 0.0]; - if use_color { - let pass = DfPass { - tag: "VectorTransform", - op: DeepFlowOp::VectorTransform, - srcs: [Some(&src.view), None, None, None], - hashes: &[src.content_hash], - size: src.size, - depth: self.node_depth(comp, node, time, Some(src.depth)), - }; - return self.df_run(node, frame_i, pass, &fin, &u, aux, enc, stats); - } - let mut upstream = vec![src.content_hash, fin.mask_hash()]; - upstream.push(channel as u64); - let mut packed = u; - fin.pack(&mut packed); - let key = self.make_key(node, "VectorTransformAux", src.size, &upstream, bytemuck::cast_slice(&packed.p)); + let fin = Fin { blend: 1.0, mbm: false, mask: None, invert: false, skip: [0.0; 4] }; + let key = self.make_key(node, "VectorTransform", src.size, &[src.content_hash], bytemuck::cast_slice(&u.p)); if let Some(hit) = self.df_hit(key, node, frame_i, stats) { return hit; } let mut out_aux = src.aux_cloned(); - let mut run = |me: &Self, field: &mut Option, tex: Option| { - if let Some(t) = tex { + let mut run = |me: &Self, field: &mut Option| { + if let Some(t) = field.take() { let srcs = [Some(&*t.view), None, None, None]; *field = Some(me.df_aux_pass(enc, DeepFlowOp::VectorTransform, srcs, &fin, &u, t.size, wgpu::TextureFormat::Rgba16Float)); } }; - run(self, &mut out_aux.vector, vector); - run(self, &mut out_aux.back_vector, back); + run(self, &mut out_aux.vector); + run(self, &mut out_aux.back_vector); self.df_with_aux(node, frame_i, key, src, out_aux) } diff --git a/crates/engine/src/eval/deep_flow/tests.rs b/crates/engine/src/eval/deep_flow/tests.rs index d89d9c3289bdacb83f52bfdafdbd7ce4929c3ed9..184058e40fa224e2c7e919c5586f2e72117eac78 100644 --- a/crates/engine/src/eval/deep_flow/tests.rs +++ b/crates/engine/src/eval/deep_flow/tests.rs @@ -412,8 +412,17 @@ fn ssao_modes_strength_blend_and_normal_aux() { assert_eq!(px(&no_z, 32, 4, 4), [0.0, 0.0, 1.0, 1.0], "no aux.z passes through"); } +/// `base` colour carrying a constant `aux.normal` `n` (Rgba16Float `NX NY NZ`). +fn normal_scene(name: &str, rgba: [f32; 4], n: [f32; 3]) -> String { + format!( + "{}{}", + solid(&format!("{name}Col"), 32, 32, rgba), + aux_chain(name, &format!("{name}Col"), &[("Normal", &format!("{name}N"))]), + ) + &solid(&format!("{name}N"), 32, 32, [n[0], n[1], n[2], 1.0]) +} + #[test] -fn deep_shader_light_types_specular_reflection_and_depth_normals() { +fn deep_shader_ambient_diffuse_specular_reflection_and_blend() { let Some(mut eng) = engine() else { return }; let shader = |input: &str, extra: &[String]| { let mut v = vec![inp("Input", input)]; @@ -421,87 +430,91 @@ fn deep_shader_light_types_specular_reflection_and_depth_normals() { v }; let tools = [ - solid("Flat", 32, 32, [0.5, 0.5, 0.5, 1.0]), - grad("Ramp", 32, 32, [0.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0], false), - z_scene("Slope", 32, 32, [0.5, 0.5, 0.5, 1.0], -10.0, -5.0), + solid("Flat", 32, 32, [0.5, 0.5, 0.5, 0.5]), + // Facing the viewer, and tilted away from the default (45, 45) light. + normal_scene("Facing", [0.5, 0.5, 0.5, 1.0], [0.0, 0.0, 1.0]), + normal_scene("Away", [0.5, 0.5, 0.5, 1.0], [-0.7, -0.7, 0.14]), solid("Env", 16, 8, [1.0, 0.0, 0.0, 1.0]), - node("Head", "Shader", &shader("Flat", &[])), - node("Grazing", "Shader", &shader("Flat", &[val("Elevation", 0.0)])), - node("Spec", "Shader", &shader("Flat", &[val("Specular", 1.0), val("SpecularExponent", 64.0)])), - node("Refl", "Shader", &shader("Flat", &[inp("EquirectangularMap", "Env")])), - node("Point", "Shader", &shader("Flat", &["LightType = Input { Value = FuID { \"Point\" }, },".into(), val("LightHeight", 0.25)])), - node( - "SpotNode", - "Shader", - &shader("Flat", &["LightType = Input { Value = 2, },".into(), val("LightHeight", 1.0), val("ConeAngle", 10.0), val("SpotSoftness", 0.01)]), - ), - node("RampRight", "Shader", &shader("Ramp", &[val("Angle", 0.0), val("Elevation", 30.0), val("BumpHeight", 32.0)])), - node("RampLeft", "Shader", &shader("Ramp", &[val("Angle", 180.0), val("Elevation", 30.0), val("BumpHeight", 32.0)])), - node("SlopeRight", "Shader", &shader("Slope", &[val("Angle", 0.0), val("Elevation", 30.0), val("ZScale", 10.0)])), - node("SlopeLeft", "Shader", &shader("Slope", &[val("Angle", 180.0), val("Elevation", 30.0), val("ZScale", 10.0)])), - node("Off", "Shader", &shader("Flat", &[val("Elevation", 0.0), val("Blend", 0.0)])), + node("NoNormal", "Shader", &shader("Flat", &[])), + node("Ambient", "Shader", &shader("Flat", &[val("Ambient", 0.5), val("Diffuse", 0.0)])), + node("Skip", "Shader", &shader("Flat", &[val("ProcessGreen", 0.0)])), + node("Half", "Shader", &shader("Flat", &[val("Blend", 0.5)])), + node("Lit", "Shader", &shader("Facing", &[val("Specular", 0.0)])), + node("LitAway", "Shader", &shader("Away", &[val("Specular", 0.0)])), + node("Spec", "Shader", &shader("Facing", &[val("Diffuse", 0.0), val("Ambient", 0.0), val("EquatorAngle", 0.0), val("PolarHeight", 90.0)])), + node("SpecBlue", "Shader", &shader("Facing", &[val("Diffuse", 0.0), val("Ambient", 0.0), val("PolarHeight", 90.0), val("SpecularRed", 0.0), val("SpecularGreen", 0.0)])), + node("Refl", "Shader", &shader("Facing", &[inp("EnvironmentReflectionMap", "Env"), val("Specular", 0.0), val("Diffuse", 0.0), val("Ambient", 0.0)])), + node("Off", "Shader", &shader("Flat", &[val("Blend", 0.0)])), ] .concat(); let comp = mk_comp(&tools); - let at = |p: &[f32], x: u32, y: u32| px(p, 32, x, y); + let at = |p: &[f32]| px(p, 32, 16, 16); + let run = |eng: &mut Engine, name: &str| at(&eval(eng, &comp, name, 0.0).1); - let (_, head) = eval(&mut eng, &comp, "Head", 0.0); - assert!((at(&head, 16, 16)[0] - 0.5).abs() < 0.01, "head-on light on a flat surface is identity"); - let (_, graze) = eval(&mut eng, &comp, "Grazing", 0.0); - assert!((at(&graze, 16, 16)[0] - 0.1).abs() < 0.01, "grazing light leaves only Ambient * albedo"); - let (_, spec) = eval(&mut eng, &comp, "Spec", 0.0); - assert!(at(&spec, 16, 16)[0] > 0.99, "Specular adds a highlight, got {:?}", at(&spec, 16, 16)); + let flat = run(&mut eng, "NoNormal"); + assert!((flat[0] - 0.5 * 0.25).abs() < 0.01 && (flat[3] - 0.5).abs() < 1e-4, "no normals: only Ambient (0.25) remains, got {flat:?}"); + let ambient = run(&mut eng, "Ambient"); + assert!((ambient[0] - 0.25).abs() < 0.01, "Ambient scales the image: {ambient:?}"); + let skip = run(&mut eng, "Skip"); + assert!((skip[0] - 0.125).abs() < 0.01 && (skip[1] - 0.5).abs() < 0.01, "ProcessGreen=0 keeps the source green: {skip:?}"); + let half = run(&mut eng, "Half"); + assert!((half[0] - 0.5 * (1.0 + 0.25) / 2.0).abs() < 0.01, "Blend mixes with the source: {half:?}"); + assert!((run(&mut eng, "Off")[0] - 0.5).abs() < 1e-4, "Blend=0 keeps the input"); - let (_, refl) = eval(&mut eng, &comp, "Refl", 0.0); - let r = at(&refl, 16, 16); - assert!(r[0] > 1.2 && (r[1] - 0.5).abs() < 0.01, "reflection map adds red: {r:?}"); + let lit = run(&mut eng, "Lit"); + let away = run(&mut eng, "LitAway"); + let ndl = 0.5f32.sqrt(); + assert!((lit[0] - 0.5 * (0.25 + ndl)).abs() < 0.02, "Ambient + Diffuse * N.L for the (45, 45) light: {lit:?}"); + assert!(away[0] < lit[0] - 0.1 && away[0] >= 0.5 * 0.25 - 0.01, "a surface turned from the light keeps only Ambient: {away:?} vs {lit:?}"); - let (_, point) = eval(&mut eng, &comp, "Point", 0.0); - assert!(at(&point, 16, 16)[0] > at(&point, 1, 1)[0] + 0.05, "point light falls off toward the corner"); - let (_, spot) = eval(&mut eng, &comp, "SpotNode", 0.0); - assert!(at(&spot, 16, 16)[0] > 0.45, "spot centre is lit"); - assert!((at(&spot, 1, 1)[0] - 0.1).abs() < 0.01, "outside the cone only ambient remains: {:?}", at(&spot, 1, 1)); + let spec = run(&mut eng, "Spec"); + assert!(spec[0] > 0.9 && spec[1] > 0.9 && spec[2] > 0.9, "overhead light on a facing normal adds a white highlight: {spec:?}"); + let spec_blue = run(&mut eng, "SpecBlue"); + assert!(spec_blue[0] < 0.01 && spec_blue[2] > 0.9, "SpecularRed/Green tint the highlight: {spec_blue:?}"); + let refl = run(&mut eng, "Refl"); + assert!(refl[0] > 0.9 && refl[1] < 0.01, "Screen reflection of the red map: {refl:?}"); - let lit = |p: &[f32], albedo: f32| at(p, 16, 16)[0] / albedo; - let (_, rr) = eval(&mut eng, &comp, "RampRight", 0.0); - let (_, rl) = eval(&mut eng, &comp, "RampLeft", 0.0); - let albedo = at(&eval(&mut eng, &comp, "Ramp", 0.0).1, 16, 16)[0]; - assert!(lit(&rl, albedo) > lit(&rr, albedo) + 0.4, "luminance-derived normals tilt toward -X: {} vs {}", lit(&rl, albedo), lit(&rr, albedo)); - let (_, sr) = eval(&mut eng, &comp, "SlopeRight", 0.0); - let (_, sl) = eval(&mut eng, &comp, "SlopeLeft", 0.0); - assert!(at(&sl, 16, 16)[0] != at(&sr, 16, 16)[0], "aux.z derived normals respond to the light direction"); - let (tex, _) = eval(&mut eng, &comp, "SlopeLeft", 0.0); - assert!(tex.aux.as_ref().and_then(|a| a.z.as_ref()).is_some(), "aux preserved"); - - let (_, off) = eval(&mut eng, &comp, "Off", 0.0); - assert!((at(&off, 16, 16)[0] - 0.5).abs() < 1e-4, "Blend=0 keeps the input"); + let (tex, _) = eval(&mut eng, &comp, "Lit", 0.0); + assert!(tex.aux.as_ref().and_then(|a| a.normal.as_ref()).is_some(), "aux preserved"); } #[test] -fn texture_uv_remap_scale_offset_edges_and_coverage() { +fn texture_uv_remap_scale_offset_flips_and_coverage() { let Some(mut eng) = engine() else { return }; let tex_node = |extra: &[String]| { let mut v = vec![inp("Input", "UV"), inp("Texture", "Tex")]; v.extend_from_slice(extra); v }; + let edges = |e: &str| format!("Edges = Input {{ Value = FuID {{ \"{e}\" }}, }},"); let tools = [ grad("UV", 32, 32, [0.0, 0.5, 0.0, 1.0], [1.0, 0.5, 0.0, 1.0], false), + // A 2D UV image: u across, v up. + bg("Corner", 32, 32, "Type = Input { Value = FuID { \"Corner\" }, }, TopLeftGreen = Input { Value = 1, }, TopLeftAlpha = Input { Value = 1, }, TopRightRed = Input { Value = 1, }, TopRightGreen = Input { Value = 1, }, TopRightAlpha = Input { Value = 1, }, BottomLeftAlpha = Input { Value = 1, }, BottomRightRed = Input { Value = 1, }, BottomRightAlpha = Input { Value = 1, },"), grad("Tex", 64, 64, [0.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0], false), solid("Hole", 32, 32, [0.5, 0.5, 0.0, 0.0]), node("Def", "Texture", &tex_node(&[])), node("Scaled", "Texture", &tex_node(&[val("UScale", 2.0)])), node("Offset", "Texture", &tex_node(&[val("UOffset", 0.25)])), - node("Black", "Texture", &tex_node(&[val("UScale", 2.0), "Edges = Input { Value = FuID { \"Black\" }, },".into()])), - node("Dup", "Texture", &tex_node(&[val("UScale", 2.0), "Edges = Input { Value = FuID { \"Duplicate\" }, },".into()])), - node("Mirror", "Texture", &tex_node(&[val("UScale", 2.0), "Edges = Input { Value = FuID { \"Mirror\" }, },".into()])), + node("Black", "Texture", &tex_node(&[val("UScale", 2.0), edges("Black")])), + node("Dup", "Texture", &tex_node(&[val("UScale", 2.0), edges("Duplicate")])), + node("Mirror", "Texture", &tex_node(&[val("UScale", 2.0), edges("Mirror")])), node("Cover", "Texture", &[inp("Input", "Hole"), inp("Texture", "Tex")]), node("NoTex", "Texture", &[inp("Input", "UV")]), node("Half", "Texture", &tex_node(&[val("Blend", 0.5)])), + node("FlipH", "Texture", &[inp("Input", "UV"), inp("Texture", "Corner"), val("FlipHoriz", 1.0)]), + node("FlipV", "Texture", &[inp("Input", "Corner"), inp("Texture", "Corner"), val("FlipVert", 1.0)]), + node("Swap", "Texture", &[inp("Input", "Corner"), inp("Texture", "Corner"), val("SwapUV0", 1.0)]), + node("Rot", "Texture", &[inp("Input", "Corner"), inp("Texture", "Corner"), val("Rotate90", 1.0)]), + node("RotOff", "Texture", &[inp("Input", "Corner"), inp("Texture", "Corner"), val("Rotate90", 1.0), val("UOffset", 0.1), val("UScale", 0.5)]), + solid("Wide", 32, 32, [0.0, 0.5, 0.0, 1.0]), + rect_mask("LeftHalf", [0.25, 0.5], [0.5, 1.0]), + node("NoTexMasked", "Texture", &[inp("Input", "UV"), format!("MultiplyByMask = Input {{ Value = 1, }}, ProcessRed = Input {{ Value = 0, }}, EffectMask = Input {{ SourceOp = \"LeftHalf\", Source = \"Mask\", }},")]), ] .concat(); let comp = mk_comp(&tools); let at = |p: &[f32], x: u32| px(p, 32, x, 16); + let at_y = |p: &[f32], x: u32, y: u32| px(p, 32, x, y); let (_, def) = eval(&mut eng, &comp, "Def", 0.0); assert!((at(&def, 16)[0] - 0.5).abs() < 0.06 && (at(&def, 8)[0] - 0.25).abs() < 0.06, "identity UV samples the texture ramp"); @@ -509,7 +522,7 @@ fn texture_uv_remap_scale_offset_edges_and_coverage() { let (_, scaled) = eval(&mut eng, &comp, "Scaled", 0.0); assert!(at(&scaled, 16)[0] < 0.15, "UScale=2 wraps u=1.0 back near 0, got {:?}", at(&scaled, 16)); let (_, off) = eval(&mut eng, &comp, "Offset", 0.0); - assert!((at(&off, 16)[0] - 0.75).abs() < 0.06, "UOffset shifts the lookup"); + assert!((at(&off, 16)[0] - 0.25).abs() < 0.06, "UOffset subtracts from the lookup, got {:?}", at(&off, 16)); let (_, black) = eval(&mut eng, &comp, "Black", 0.0); assert!(at(&black, 24)[3] < 0.01, "Edges=Black is transparent out of range"); let (_, dup) = eval(&mut eng, &comp, "Dup", 0.0); @@ -522,6 +535,25 @@ fn texture_uv_remap_scale_offset_edges_and_coverage() { assert!((at(&no_tex, 16)[0] - 0.5).abs() < 0.03, "no texture input passes Input through"); let (_, half) = eval(&mut eng, &comp, "Half", 0.0); assert!((at(&half, 16)[0] - 0.5).abs() < 0.06, "Blend mixes with the UV image (0.5 either way here)"); + + let (_, fh) = eval(&mut eng, &comp, "FlipH", 0.0); + assert!((at(&fh, 8)[0] - 0.75).abs() < 0.04 && (at(&fh, 8)[0] - at(&fh, 24)[0]).abs() > 0.4, "FlipHoriz mirrors u: {:?}", at(&fh, 8)); + let rg = |p: &[f32], x: u32, y: u32| (at_y(p, x, y)[0], at_y(p, x, y)[1]); + let near = |a: (f32, f32), b: (f32, f32)| (a.0 - b.0).abs() < 0.05 && (a.1 - b.1).abs() < 0.05; + // pixel (8, 8) has (u, v) = (0.25, 0.75). + let (_, fv) = eval(&mut eng, &comp, "FlipV", 0.0); + assert!(near(rg(&fv, 8, 8), (0.25, 0.25)), "FlipVert mirrors v: {:?}", rg(&fv, 8, 8)); + let (_, sw) = eval(&mut eng, &comp, "Swap", 0.0); + assert!(near(rg(&sw, 8, 8), (0.75, 0.25)), "SwapUV0 exchanges u and v: {:?}", rg(&sw, 8, 8)); + let (_, rot) = eval(&mut eng, &comp, "Rot", 0.0); + assert!(near(rg(&rot, 8, 8), (0.75, 0.75)), "Rotate90 maps (u, v) to (v, 1 - u): {:?}", rg(&rot, 8, 8)); + let (_, rot_off) = eval(&mut eng, &comp, "RotOff", 0.0); + assert!(near(rg(&rot_off, 8, 8), (0.75, 0.975)), "scale and offset apply before the rotation: {:?}", rg(&rot_off, 8, 8)); + + let (_, masked) = eval(&mut eng, &comp, "NoTexMasked", 0.0); + assert_eq!(at(&masked, 4)[0], 0.0, "MultiplyByMask zeroes an unprocessed channel even without a texture"); + assert!((at(&masked, 4)[1] - 0.5).abs() < 0.03, "processed channels keep the image inside the mask"); + assert_eq!(at(&masked, 28)[1], 0.0, "outside the mask is multiplied away"); } mod flow; diff --git a/crates/engine/src/eval/deep_flow/tests/flow.rs b/crates/engine/src/eval/deep_flow/tests/flow.rs index 5f812ceaf47b32e4d264bd5ad85a311090e01480..173152c6a7bd8b22b29e5d65433a5d2a6708460f 100644 --- a/crates/engine/src/eval/deep_flow/tests/flow.rs +++ b/crates/engine/src/eval/deep_flow/tests/flow.rs @@ -8,7 +8,7 @@ fn vec_scene(name: &str, base: &str, v: [f32; 2], chan: &str) -> String { } #[test] -fn vector_transform_aux_color_and_mask() { +fn vector_transform_scales_rotates_smooths_and_attenuates_aux_vectors() { let Some(mut eng) = engine() else { return }; let vt = |extra: &[String]| { let mut v = vec![inp("Input", "Scene")]; @@ -20,63 +20,47 @@ fn vector_transform_aux_color_and_mask() { solid("FV", 32, 32, [4.0, -2.0, 0.0, 1.0]), solid("BV", 32, 32, [1.0, 1.0, 0.0, 1.0]), aux_chain("Scene", "Base", &[("Vector", "FV"), ("BackVector", "BV")]), - rect_mask("RightHalf", [0.75, 0.5], [0.5, 1.0]), + grad("StepFV", 32, 32, [0.0, 0.0, 0.0, 1.0], [32.0, 0.0, 0.0, 1.0], false), + aux_chain("Step", "Base", &[("Vector", "StepFV")]), node("Ident", "VectorTransform", &vt(&[])), - node("Scale", "VectorTransform", &vt(&[val("XScale", 2.0), val("YScale", 3.0)])), + node("Size", "VectorTransform", &vt(&[val("XSize", 2.0), val("YSize", 3.0)])), + node("SizeAspect", "VectorTransform", &vt(&[val("UseSizeAndAspect", 1.0), val("Size", 2.0), val("Aspect", 1.5), val("XSize", 9.0)])), node("Rot", "VectorTransform", &vt(&[val("Angle", 90.0)])), - node("Inv", "VectorTransform", &vt(&[val("Invert", 1.0)])), - node("FlipX", "VectorTransform", &vt(&[val("FlipX", 1.0)])), - node("FlipY", "VectorTransform", &vt(&[val("FlipY", 1.0)])), - node("Norm", "VectorTransform", &vt(&[val("Normalize", 1.0)])), - node("Off", "VectorTransform", &vt(&[val("XOffset", 1.0), val("YOffset", -1.0)])), - node("OnlyFwd", "VectorTransform", &vt(&[val("XScale", 2.0), "Channel = Input { Value = FuID { \"Vector\" }, },".into()])), - node("Half", "VectorTransform", &vt(&[val("XScale", 3.0), val("Blend", 0.5)])), - node("Masked", "VectorTransform", &vt(&[val("Invert", 1.0), inp("EffectMask", "RightHalf").replace("Output", "Mask")])), - solid("ColVec", 32, 32, [0.25, -0.5, 0.75, 1.0]), - node("Color", "VectorTransform", &[inp("Input", "ColVec"), val("Invert", 1.0)]), - node("ColorOnly", "VectorTransform", &vt(&[val("XScale", 0.0), "Channel = Input { Value = FuID { \"Color\" }, },".into()])), - node("NoVec", "VectorTransform", &[inp("Input", "Base"), "Channel = Input { Value = 1, },".into()]), + node("Half", "VectorTransform", &vt(&[val("Angle", 90.0), val("AttenuateVect", 0.5)])), + node("None", "VectorTransform", &vt(&[val("Angle", 90.0), val("AttenuateVect", 0.0)])), + node("Smooth", "VectorTransform", &[inp("Input", "Step"), val("SmoothVector", 4.0)]), + node("NoVec", "VectorTransform", &[inp("Input", "Base"), val("Angle", 90.0), val("XSize", 3.0)]), ] .concat(); let comp = mk_comp(&tools); - let check = |eng: &mut Engine, name: &str, f: [f32; 2], b: [f32; 2]| { + let vectors = |eng: &mut Engine, name: &str| { let (tex, _) = eval(eng, &comp, name, 0.0); let aux = tex.aux.as_ref().unwrap_or_else(|| panic!("{name}: aux missing")); - let fv = aux_at(&aux_px(eng, aux.vector.as_ref().unwrap()), 32, 16, 16); - let bv = aux_at(&aux_px(eng, aux.back_vector.as_ref().unwrap()), 32, 16, 16); + (aux_px(eng, aux.vector.as_ref().unwrap()), aux.back_vector.as_ref().map(|b| aux_px(eng, b))) + }; + let check = |eng: &mut Engine, name: &str, f: [f32; 2], b: [f32; 2]| { + let (fv, bv) = vectors(eng, name); + let (fv, bv) = (aux_at(&fv, 32, 16, 16), aux_at(&bv.unwrap(), 32, 16, 16)); assert!((fv[0] - f[0]).abs() < 0.02 && (fv[1] - f[1]).abs() < 0.02, "{name}: forward {fv:?} != {f:?}"); assert!((bv[0] - b[0]).abs() < 0.02 && (bv[1] - b[1]).abs() < 0.02, "{name}: back {bv:?} != {b:?}"); }; check(&mut eng, "Ident", [4.0, -2.0], [1.0, 1.0]); - check(&mut eng, "Scale", [8.0, -6.0], [2.0, 3.0]); + check(&mut eng, "Size", [8.0, -6.0], [2.0, 3.0]); + check(&mut eng, "SizeAspect", [8.0, -6.0], [2.0, 3.0]); check(&mut eng, "Rot", [2.0, 4.0], [-1.0, 1.0]); - check(&mut eng, "Inv", [-4.0, 2.0], [-1.0, -1.0]); - check(&mut eng, "FlipX", [-4.0, -2.0], [-1.0, 1.0]); - check(&mut eng, "FlipY", [4.0, 2.0], [1.0, -1.0]); - check(&mut eng, "Norm", [0.894, -0.447], [0.707, 0.707]); - check(&mut eng, "Off", [5.0, -3.0], [2.0, 0.0]); - check(&mut eng, "OnlyFwd", [8.0, -2.0], [1.0, 1.0]); - check(&mut eng, "Half", [8.0, -2.0], [2.0, 1.0]); + check(&mut eng, "Half", [3.0, 1.0], [0.0, 1.0]); + check(&mut eng, "None", [4.0, -2.0], [1.0, 1.0]); - // RGBA is untouched on the aux path. - let (tex, p) = eval(&mut eng, &comp, "Scale", 0.0); + let (tex, p) = eval(&mut eng, &comp, "Size", 0.0); assert_eq!(px(&p, 32, 16, 16), [0.1, 0.2, 0.3, 1.0], "colour passes through"); assert!(tex.aux.is_some()); - // EffectMask: left half keeps the original vector, right half is inverted. - let (tex, _) = eval(&mut eng, &comp, "Masked", 0.0); - let fwd = aux_px(&eng, tex.aux.as_ref().unwrap().vector.as_ref().unwrap()); - assert!((aux_at(&fwd, 32, 4, 16)[0] - 4.0).abs() < 0.02, "outside the mask is unchanged"); - assert!((aux_at(&fwd, 32, 28, 16)[0] + 4.0).abs() < 0.02, "inside the mask is transformed"); + let (ramp, _) = vectors(&mut eng, "Smooth"); + assert!((aux_at(&ramp, 32, 16, 16)[0] - 16.5).abs() < 0.2, "a linear ramp is its own 3-tap average"); + assert!((aux_at(&ramp, 32, 1, 16)[0] - 2.5).abs() < 0.2, "taps at x-4, x, x+4 clamp to the border: {:?}", aux_at(&ramp, 32, 1, 16)); - // Colour RG fallback when no aux vectors exist. - let (_, col) = eval(&mut eng, &comp, "Color", 0.0); - let c = px(&col, 32, 16, 16); - assert!((c[0] + 0.25).abs() < 1e-4 && (c[1] - 0.5).abs() < 1e-4 && (c[2] - 0.75).abs() < 1e-4, "RG inverted, B/A kept: {c:?}"); - let (_, col_only) = eval(&mut eng, &comp, "ColorOnly", 0.0); - assert!(px(&col_only, 32, 16, 16)[0].abs() < 1e-4, "Channel=Color forces the RG path even when aux exists"); let (_, no_vec) = eval(&mut eng, &comp, "NoVec", 0.0); - assert_eq!(px(&no_vec, 32, 16, 16), [0.1, 0.2, 0.3, 1.0], "nothing to transform"); + assert_eq!(px(&no_vec, 32, 16, 16), [0.1, 0.2, 0.3, 1.0], "without vectors the image is untouched, RG is never rotated"); } #[test] diff --git a/crates/engine/src/eval/mod.rs b/crates/engine/src/eval/mod.rs index d2bbb33927d1b6f715b413cc08996fa506692e4a..a695868f24ab73a731e0bafd2648750e9fa896e5 100644 --- a/crates/engine/src/eval/mod.rs +++ b/crates/engine/src/eval/mod.rs @@ -34,6 +34,7 @@ mod fx_fuses; mod archive_fx2; mod surface_fx; mod layer_ocio; +mod primatte_misc; mod deep_flow; mod text_3d; mod registry; @@ -90,6 +91,7 @@ pub struct Engine { archive_fx2_pipelines: OnceCell>, pub(crate) surface_fx: OnceCell>, pub(crate) layer_ocio: OnceCell>, + pub(crate) primatte_misc: OnceCell>, pub(crate) deep_flow: OnceCell>, auto_matte_pipelines: OnceCell>, pub auto_matte_cache: crate::auto_matte::AutoMatteCache, @@ -209,6 +211,7 @@ impl Engine { archive_fx2_pipelines: OnceCell::new(), surface_fx: OnceCell::new(), layer_ocio: OnceCell::new(), + primatte_misc: OnceCell::new(), deep_flow: OnceCell::new(), auto_matte_pipelines: OnceCell::new(), auto_matte_cache: crate::auto_matte::AutoMatteCache::new(), @@ -382,6 +385,9 @@ impl Engine { if let Some(lo) = self.layer_ocio.get() { lo.borrow_mut().reset_uniform_cursor(); } + if let Some(pm) = self.primatte_misc.get() { + pm.borrow_mut().reset_uniform_cursor(); + } if let Some(df) = self.deep_flow.get() { df.borrow_mut().reset_uniform_cursor(); } @@ -426,6 +432,9 @@ impl Engine { if let Some(lo) = self.layer_ocio.get() { lo.borrow_mut().trim_uniform_chunks(2); } + if let Some(pm) = self.primatte_misc.get() { + pm.borrow_mut().trim_uniform_chunks(2); + } if let Some(df) = self.deep_flow.get() { df.borrow_mut().trim_uniform_chunks(2); } @@ -1088,7 +1097,10 @@ impl Engine { "LayerRegex" => self.eval_layer_filter(comp, node, time, false, enc, visiting, stats), "LayerRemover" => self.eval_layer_filter(comp, node, time, true, enc, visiting, stats), "Swizzler" => self.eval_swizzler(comp, node, time, frame_i, enc, visiting, stats), - "Dummy" | "Fuse.FLS_CopyMetadata" | "Fuse.SetMetaDataTC" => self.eval_passthrough(comp, node, time, enc, visiting, stats), + "Dummy" | "Fuse.FLS_CopyMetadata" | "Fuse.SetMetaDataTC" | "Profiler" | "RunCommand" | "Fuse.ExternalMatteSaver" => { + self.eval_passthrough(comp, node, time, enc, visiting, stats) + } + "Photron.Primatte4" | "Primatte4" => self.eval_primatte4(comp, node, time, frame_i, enc, visiting, stats), "MultiText" => self.eval_multi_text(comp, node, time, frame_i, comp_dims, enc, stats), "Fields" => self.eval_fields(comp, node, time, frame_i, enc, visiting, stats), "KeyStretcher" => self.eval_key_stretcher(comp, node, time, frame_i, enc, visiting, stats), diff --git a/crates/engine/src/eval/primatte_misc.rs b/crates/engine/src/eval/primatte_misc.rs new file mode 100644 index 0000000000000000000000000000000000000000..deb33b0a5e6adca2e3533e586553bb00377dc898 --- /dev/null +++ b/crates/engine/src/eval/primatte_misc.rs @@ -0,0 +1,285 @@ +//! `Photron.Primatte4` (alias `Primatte4`): polyhedral chroma-space keyer on the GPU +//! (`primatte_misc.wgsl`: `filterable: false` + `textureLoad`, WriteOnly storage output patched per +//! format, no `read_write` storage textures). +//! +//! `Profiler`, `RunCommand` and `Fuse.ExternalMatteSaver` are lossless passthroughs (`eval_passthrough`); +//! `RunCommand` never executes anything, so an untrusted `.comp` cannot run a shell command. + +#[cfg(test)] +mod tests; + +use super::*; +use std::num::NonZeroU64; + +const PRIMATTE_WGSL: &str = include_str!("../shaders/primatte_misc.wgsl"); +const UNIFORM_SLOTS_PER_CHUNK: u32 = 512; +const OUTPUT_MODES: [&str; 3] = ["composite", "alpha", "spillsuppressed"]; +const KEY_COLOR_DEFAULT: [f64; 3] = [0.0, 1.0, 0.0]; + +struct FormatPipeline { + bgl: wgpu::BindGroupLayout, + pipeline: wgpu::ComputePipeline, +} + +pub(crate) struct PrimatteMiscPipelines { + uniform_stride: u32, + uniform_chunks: Vec, + uniform_cursor: u32, + by_format: HashMap<(wgpu::TextureFormat, bool), FormatPipeline>, +} + +fn unfilterable_tex_entry(binding: u32) -> wgpu::BindGroupLayoutEntry { + wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: false }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + } +} + +fn patch_storage_format(format: wgpu::TextureFormat, hdr_float: bool) -> String { + let storage_fmt = match format { + wgpu::TextureFormat::Rgba16Float => "rgba16float", + wgpu::TextureFormat::Rgba32Float => "rgba32float", + _ => "rgba8unorm", + }; + let mut src = PRIMATTE_WGSL.replace( + "texture_storage_2d", + &format!("texture_storage_2d<{storage_fmt}, write>"), + ); + if hdr_float { + src = src.replace("const HDR_FLOAT: bool = false;", "const HDR_FLOAT: bool = true;"); + } + src +} + +impl PrimatteMiscPipelines { + pub(super) fn new(device: &wgpu::Device) -> Self { + let uniform_size = std::mem::size_of::() as u32; + let min_align = device.limits().min_uniform_buffer_offset_alignment.max(1); + Self { + uniform_stride: uniform_size.div_ceil(min_align) * min_align, + uniform_chunks: Vec::new(), + uniform_cursor: 0, + by_format: HashMap::new(), + } + } + + pub(super) fn reset_uniform_cursor(&mut self) { + self.uniform_cursor = 0; + } + + pub(super) fn trim_uniform_chunks(&mut self, max_chunks: usize) { + self.uniform_cursor = 0; + self.uniform_chunks.truncate(max_chunks); + } + + fn alloc_uniform_slot(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, params: &UniformParams) -> (usize, u32) { + let slot = self.uniform_cursor; + let chunk_idx = (slot / UNIFORM_SLOTS_PER_CHUNK) as usize; + while chunk_idx >= self.uniform_chunks.len() { + self.uniform_chunks.push(device.create_buffer(&wgpu::BufferDescriptor { + label: Some("primatte-params-ring"), + size: u64::from(UNIFORM_SLOTS_PER_CHUNK) * u64::from(self.uniform_stride), + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + })); + } + let offset = (slot % UNIFORM_SLOTS_PER_CHUNK) * self.uniform_stride; + queue.write_buffer(&self.uniform_chunks[chunk_idx], u64::from(offset), bytemuck::bytes_of(params)); + self.uniform_cursor = slot + 1; + (chunk_idx, offset) + } + + fn ensure_format(&mut self, device: &wgpu::Device, format: wgpu::TextureFormat, hdr_float: bool) { + if self.by_format.contains_key(&(format, hdr_float)) { + return; + } + let u_size = std::mem::size_of::() as u64; + let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("primatte-bgl"), + entries: &[ + unfilterable_tex_entry(0), + unfilterable_tex_entry(1), + unfilterable_tex_entry(2), + unfilterable_tex_entry(3), + unfilterable_tex_entry(4), + wgpu::BindGroupLayoutEntry { + binding: 5, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::StorageTexture { + access: wgpu::StorageTextureAccess::WriteOnly, + format, + view_dimension: wgpu::TextureViewDimension::D2, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 6, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: true, + min_binding_size: NonZeroU64::new(u_size), + }, + count: None, + }, + ], + }); + let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("primatte-pl"), + bind_group_layouts: &[Some(&bgl)], + immediate_size: 0, + }); + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("primatte-wgsl"), + source: wgpu::ShaderSource::Wgsl(patch_storage_format(format, hdr_float).into()), + }); + let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("primatte_op"), + layout: Some(&layout), + module: &module, + entry_point: Some("primatte_op"), + compilation_options: Default::default(), + cache: None, + }); + self.by_format.insert((format, hdr_float), FormatPipeline { bgl, pipeline }); + } + + fn dispatch( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + enc: &mut wgpu::CommandEncoder, + views: [&wgpu::TextureView; 5], + dst: &CachedTexture, + params: &UniformParams, + ) { + let hdr_float = dst.depth.is_float(); + self.ensure_format(device, dst.format, hdr_float); + let (chunk_idx, offset) = self.alloc_uniform_slot(device, queue, params); + let fp = &self.by_format[&(dst.format, hdr_float)]; + let mut entries: Vec = views + .iter() + .enumerate() + .map(|(i, v)| wgpu::BindGroupEntry { binding: i as u32, resource: wgpu::BindingResource::TextureView(v) }) + .collect(); + entries.push(wgpu::BindGroupEntry { binding: 5, resource: wgpu::BindingResource::TextureView(&dst.view) }); + entries.push(wgpu::BindGroupEntry { + binding: 6, + resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { + buffer: &self.uniform_chunks[chunk_idx], + offset: 0, + size: NonZeroU64::new(std::mem::size_of::() as u64), + }), + }); + let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("primatte-bg"), layout: &fp.bgl, entries: &entries }); + let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("primatte-pass"), timestamp_writes: None }); + pass.set_pipeline(&fp.pipeline); + pass.set_bind_group(0, &bg, &[offset]); + pass.dispatch_workgroups(dst.size[0].div_ceil(8), dst.size[1].div_ceil(8), 1); + } +} + +fn b2f(v: bool) -> f32 { + if v { 1.0 } else { 0.0 } +} + +impl Engine { + fn primatte_pipelines(&self) -> &RefCell { + self.primatte_misc.get_or_init(|| RefCell::new(PrimatteMiscPipelines::new(&self.device))) + } + + /// `Photron.Primatte4`: a key polyhedron around the screen colour in chroma space (`BackgroundColor`, else + /// `KeyColor`, else green; `AutoCompute` samples it from the image) maps distance to matte. `CleanBackground` + /// and `CleanForeground` move the transparent and opaque boundaries, `MatteSponge` / `MatteRestore` / + /// `DetailMinus` / `DetailPlus` reshape partial alpha, `SpillSuppression` and `SpillSponge` de-contaminate + /// colour, `Deartifacting`, `MatteBlur` (px) and `MatteContractExpand` (px, negative contracts) refine the + /// matte, `GarbageMatte` removes and `SolidMatte` forces opacity (their alpha), and `OutputMode` picks + /// Composite (over `Background`), Alpha or SpillSuppressed. `Blend`, `EffectMask` and `Process*` apply last. + #[allow(clippy::too_many_arguments)] + pub(in crate::eval) fn eval_primatte4( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = ["Input", "Foreground", "Image"].iter().find_map(|p| node.connected_node(p).and_then(|s| comp.find_node(s))) else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + let mbm = self.multiplies_by_mask(comp, node, time); + if blend <= 1e-6 && !mbm { + return src; + } + let src = if Self::resolve_effect_mask_id(comp, node).is_some() { self.crop_to_canvas(enc, src) } else { src }; + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); + let skip = self.process_skip(comp, node, time); + + let mut optional = |ports: &[&str]| { + let id = ports.iter().find_map(|p| node.connected_node(p).and_then(|s| comp.find_node(s)))?; + Some(self.eval_node(comp, id, time, enc, visiting, stats)) + }; + let background = optional(&["Background"]); + let garbage = optional(&["GarbageMatte"]); + let solid = optional(&["SolidMatte"]); + + let n = |key: &str, d: f64| comp.eval_number(node, key, time, d, &self.expr) as f32; + let color = |name: &str| { + let has = ["Red", "Green", "Blue"].iter().any(|c| node.inputs.contains_key(&format!("{name}{c}"))); + has.then(|| ["Red", "Green", "Blue"].map(|c| comp.eval_number(node, &format!("{name}{c}"), time, 0.0, &self.expr) as f32)) + }; + let key = color("BackgroundColor").or_else(|| color("KeyColor")).unwrap_or(KEY_COLOR_DEFAULT.map(|v| v as f32)); + let mode = match node.static_str("OutputMode") { + Some(s) => { + let s = s.chars().filter(char::is_ascii_alphanumeric).collect::().to_ascii_lowercase(); + OUTPUT_MODES.iter().position(|m| *m == s).unwrap_or(0) + } + None => (n("OutputMode", 0.0).round().max(0.0) as usize).min(OUTPUT_MODES.len() - 1), + }; + + let mut u = UniformParams::default(); + u.p[0] = [key[0], key[1], key[2], b2f(n("AutoCompute", 0.0) > 0.5)]; + let unit = |name: &str, d: f64| n(name, d).clamp(0.0, 1.0); + u.p[1] = [unit("CleanBackground", 0.0), unit("CleanForeground", 0.0), unit("MatteSponge", 0.0), unit("MatteRestore", 0.0)]; + u.p[2] = [unit("SpillSponge", 0.0), unit("DetailMinus", 0.0), unit("DetailPlus", 0.0), unit("SpillSuppression", 0.5)]; + u.p[3] = [unit("Deartifacting", 0.0), n("MatteBlur", 0.0).clamp(0.0, 64.0), n("MatteContractExpand", 0.0).clamp(-64.0, 64.0), mode as f32]; + u.p[4] = [b2f(background.is_some()), b2f(garbage.is_some()), b2f(solid.is_some()), 0.0]; + u.p[14] = [blend, b2f(mask.is_some()), b2f(mask_inv), b2f(mbm)]; + u.p[15] = skip; + + let hash = |t: &Option| t.as_ref().map_or(0, |t| t.content_hash); + let depth = self.node_depth(comp, node, time, Some(src.depth)); + let upstream = [src.content_hash, hash(&background), hash(&garbage), hash(&solid), hash(&mask), depth as u64]; + let key = self.make_key(node, "Primatte4", src.size, &upstream, bytemuck::cast_slice(&u.p)); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + let mut dst = self.alloc_tex_like(&src, depth, key); + let view = |t: &Option| t.as_ref().map_or_else(|| self.dummy.view.clone(), |t| t.view.clone()); + let views = [src.view.clone(), view(&background), view(&garbage), view(&solid), view(&mask)]; + self.primatte_pipelines().borrow_mut().dispatch( + &self.device, + &self.queue, + enc, + [&views[0], &views[1], &views[2], &views[3], &views[4]], + &dst, + &u, + ); + dst.set_aux(src.aux.clone()); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } +} diff --git a/crates/engine/src/eval/primatte_misc/tests.rs b/crates/engine/src/eval/primatte_misc/tests.rs new file mode 100644 index 0000000000000000000000000000000000000000..66a459954bad0b508ebd61df14f519b3ab9bcd3a --- /dev/null +++ b/crates/engine/src/eval/primatte_misc/tests.rs @@ -0,0 +1,276 @@ +//! GPU unit tests for `Photron.Primatte4` and the passthrough utilities. + +use super::*; + +fn comp(tools: &str) -> Comp { + let src = format!( + "Composition {{ CurrentTime = 0, RenderRange = {{ 0, 10 }}, GlobalRange = {{ 0, 10 }}, Tools = ordered() {{ {tools} }} }}" + ); + Comp::from_fusion_str(&src).expect("parse comp") +} + +/// Float32 solid-colour `Background` named `name`. +fn solid(name: &str, w: u32, h: u32, [r, g, b, a]: [f32; 4]) -> String { + format!( + "{name} = Background {{ Inputs = {{ Width = Input {{ Value = {w}, }}, Height = Input {{ Value = {h}, }}, Depth = Input {{ Value = 4, }}, \ + TopLeftRed = Input {{ Value = {r}, }}, TopLeftGreen = Input {{ Value = {g}, }}, TopLeftBlue = Input {{ Value = {b}, }}, TopLeftAlpha = Input {{ Value = {a}, }}, }}, }}," + ) +} + +fn tool(name: &str, kind: &str, src: &str, extra: &str) -> String { + format!("{name} = {kind} {{ Inputs = {{ Input = Input {{ SourceOp = \"{src}\", Source = \"Output\", }}, {extra} }}, }},") +} + +fn link(port: &str, op: &str) -> String { + format!("{port} = Input {{ SourceOp = \"{op}\", Source = \"Output\", }},") +} + +fn with_z(name: &str, src: &str) -> String { + tool(name, "Dimension.CopyAux", src, "Channel = Input { Value = FuID { \"Z\" }, }, Mode = Input { Value = 1, },") +} + +fn render(c: &Comp, name: &str) -> Option<(CachedTexture, Vec)> { + let mut eng = Engine::new_headless().ok()?; + let (tex, stats) = eng.evaluate(c, c.find_node(name).expect("find node"), 0.0); + assert!(stats.unsupported_nodes.is_empty(), "unsupported: {:?}", stats.unsupported_nodes); + let px = eng.readback_rgba_f32(&tex).unwrap(); + Some((tex, px)) +} + +fn px(buf: &[f32], w: u32, x: u32, y: u32) -> [f32; 4] { + let i = ((y * w + x) * 4) as usize; + buf[i..i + 4].try_into().unwrap() +} + +fn near(got: f32, want: f32, tol: f32, what: &str) { + assert!((got - want).abs() <= tol, "{what}: got {got}, want {want} (±{tol})"); +} + +const ALPHA: &str = "OutputMode = Input { Value = FuID { \"Alpha\" }, },"; +const GREEN: [f32; 4] = [0.1, 0.8, 0.15, 1.0]; +const RED: [f32; 4] = [0.9, 0.1, 0.1, 1.0]; +const SEMI: [f32; 4] = [0.45, 0.62, 0.4, 1.0]; + +/// Red left half over a green right half (32x16), via a masked Merge. +fn split_scene() -> String { + [ + solid("SplitG", 32, 16, GREEN), + solid("SplitR", 32, 16, RED), + "SplitMask = RectangleMask { Inputs = { MaskWidth = Input { Value = 32, }, MaskHeight = Input { Value = 16, }, \ + Center = Input { Value = { 0.25, 0.5 }, }, Width = Input { Value = 0.5, }, Height = Input { Value = 1.0, }, }, }," + .to_owned(), + "Split = Merge { Inputs = { Background = Input { SourceOp = \"SplitG\", Source = \"Output\", }, \ + Foreground = Input { SourceOp = \"SplitR\", Source = \"Output\", }, \ + EffectMask = Input { SourceOp = \"SplitMask\", Source = \"Mask\", }, }, }," + .to_owned(), + ] + .concat() +} + +fn alpha_of(c: &Comp, name: &str, x: u32, y: u32) -> f32 { + let (tex, p) = render(c, name).unwrap(); + px(&p, tex.size[0], x, y)[3] +} + +#[test] +fn primatte4_keys_screen_colour_and_keeps_foreground() { + let c = comp(&[ + solid("Green", 8, 8, GREEN), + solid("Red", 8, 8, RED), + solid("Skin", 8, 8, [0.8, 0.6, 0.5, 1.0]), + solid("Black", 8, 8, [0.0, 0.0, 0.0, 1.0]), + solid("Shadow", 8, 8, [0.02, 0.1, 0.03, 1.0]), + tool("KeyGreen", "Photron.Primatte4", "Green", ALPHA), + tool("KeyRed", "Primatte4", "Red", ALPHA), + tool("KeySkin", "Photron.Primatte4", "Skin", ALPHA), + tool("KeyBlack", "Photron.Primatte4", "Black", ALPHA), + tool("KeyShadow", "Photron.Primatte4", "Shadow", ALPHA), + tool("RedAsKey", "Photron.Primatte4", "Red", &format!("{ALPHA} BackgroundColorRed = Input {{ Value = 0.9, }}, BackgroundColorGreen = Input {{ Value = 0.1, }}, BackgroundColorBlue = Input {{ Value = 0.1, }},")), + tool("KeyColorRed", "Photron.Primatte4", "Red", &format!("{ALPHA} KeyColorRed = Input {{ Value = 0.9, }}, KeyColorGreen = Input {{ Value = 0.1, }}, KeyColorBlue = Input {{ Value = 0.1, }},")), + ].concat()); + let Some((tex, p)) = render(&c, "KeyGreen") else { return }; + assert_eq!(px(&p, tex.size[0], 3, 3), [0.0, 0.0, 0.0, 0.0], "the default green screen keys fully transparent"); + near(alpha_of(&c, "KeyRed", 3, 3), 1.0, 1e-3, "red foreground"); + near(alpha_of(&c, "KeySkin", 3, 3), 1.0, 1e-3, "skin foreground"); + near(alpha_of(&c, "KeyBlack", 3, 3), 1.0, 1e-3, "black foreground stays opaque"); + near(alpha_of(&c, "KeyShadow", 3, 3), 0.0, 1e-3, "a dark screen shadow follows the chroma cone"); + near(alpha_of(&c, "RedAsKey", 3, 3), 0.0, 1e-3, "BackgroundColor picks the screen colour"); + near(alpha_of(&c, "KeyColorRed", 3, 3), 0.0, 1e-3, "KeyColor picks the screen colour too"); +} + +#[test] +fn primatte4_fine_tuning_moves_matte_and_spill() { + let c = comp(&[ + solid("Semi", 8, 8, SEMI), + solid("Spill", 8, 8, [0.7, 0.78, 0.5, 1.0]), + tool("Base", "Photron.Primatte4", "Semi", ALPHA), + tool("CleanBg", "Photron.Primatte4", "Semi", &format!("{ALPHA} CleanBackground = Input {{ Value = 1, }},")), + tool("CleanFg", "Photron.Primatte4", "Semi", &format!("{ALPHA} CleanForeground = Input {{ Value = 1, }},")), + tool("Sponge", "Photron.Primatte4", "Semi", &format!("{ALPHA} MatteSponge = Input {{ Value = 1, }},")), + tool("Restore", "Photron.Primatte4", "Semi", &format!("{ALPHA} MatteRestore = Input {{ Value = 1, }},")), + tool("Minus", "Photron.Primatte4", "Semi", &format!("{ALPHA} DetailMinus = Input {{ Value = 1, }},")), + tool("Plus", "Photron.Primatte4", "Semi", &format!("{ALPHA} DetailPlus = Input {{ Value = 1, }},")), + tool("NoSpill", "Photron.Primatte4", "Spill", "OutputMode = Input { Value = FuID { \"SpillSuppressed\" }, }, SpillSuppression = Input { Value = 0, },"), + tool("Spilled", "Photron.Primatte4", "Spill", "OutputMode = Input { Value = FuID { \"SpillSuppressed\" }, }, SpillSuppression = Input { Value = 1, },"), + tool("Sponged", "Photron.Primatte4", "Spill", "OutputMode = Input { Value = FuID { \"SpillSuppressed\" }, }, SpillSuppression = Input { Value = 1, }, SpillSponge = Input { Value = 1, },"), + ].concat()); + let Some(base) = render(&c, "Base").map(|(t, p)| px(&p, t.size[0], 3, 3)[3]) else { return }; + assert!(base > 0.2 && base < 0.9, "a mid-way pixel is partially transparent: {base}"); + assert!(alpha_of(&c, "CleanBg", 3, 3) < base - 0.1, "CleanBackground widens the transparent core"); + assert!(alpha_of(&c, "CleanFg", 3, 3) > base + 0.1, "CleanForeground widens the opaque shell"); + assert!(alpha_of(&c, "Sponge", 3, 3) < base - 0.1, "MatteSponge pushes low alpha to transparent"); + assert!(alpha_of(&c, "Restore", 3, 3) > base + 0.1, "MatteRestore recovers opacity"); + assert!(alpha_of(&c, "Minus", 3, 3) < base - 0.05, "DetailMinus lowers partial alpha"); + assert!(alpha_of(&c, "Plus", 3, 3) > base + 0.05, "DetailPlus raises partial alpha"); + + let pixel = |name: &str| { + let (t, p) = render(&c, name).unwrap(); + px(&p, t.size[0], 3, 3) + }; + assert_eq!(pixel("NoSpill"), [0.7, 0.78, 0.5, 1.0], "SpillSuppression=0 leaves the colour alone"); + let spilled = pixel("Spilled"); + assert!(spilled[1] < 0.78 && spilled[0] > 0.7 && spilled[2] > 0.5, "green lean removed, red and blue lifted: {spilled:?}"); + near(0.2126 * spilled[0] + 0.7152 * spilled[1] + 0.0722 * spilled[2], 0.2126 * 0.7 + 0.7152 * 0.78 + 0.0722 * 0.5, 0.01, "luminance preserved"); + near(spilled[3], 1.0, 1e-4, "SpillSuppressed keeps the source alpha"); + assert!(pixel("Sponged")[1] <= spilled[1] + 1e-4, "SpillSponge widens the suppression"); +} + +#[test] +fn primatte4_output_modes_composite_over_background() { + let c = comp(&[ + solid("Green", 8, 8, GREEN), + solid("Red", 8, 8, RED), + solid("Plate", 8, 8, [0.0, 0.0, 1.0, 1.0]), + tool("OverGreen", "Photron.Primatte4", "Green", &link("Background", "Plate")), + tool("OverRed", "Photron.Primatte4", "Red", &link("Background", "Plate")), + tool("NoPlate", "Photron.Primatte4", "Red", ""), + tool("Alpha", "Photron.Primatte4", "Red", ALPHA), + tool("AlphaNum", "Photron.Primatte4", "Red", "OutputMode = Input { Value = 1, },"), + ].concat()); + let Some((tex, p)) = render(&c, "OverGreen") else { return }; + let w = tex.size[0]; + assert_eq!(px(&p, w, 3, 3), [0.0, 0.0, 1.0, 1.0], "the keyed screen shows the Background"); + let (_, p) = render(&c, "OverRed").unwrap(); + assert_eq!(px(&p, w, 3, 3), [0.9, 0.1, 0.1, 1.0], "an opaque foreground covers the Background"); + let (_, p) = render(&c, "NoPlate").unwrap(); + assert_eq!(px(&p, w, 3, 3), [0.9, 0.1, 0.1, 1.0], "Composite without a Background is the premultiplied keyed foreground"); + let (_, p) = render(&c, "Alpha").unwrap(); + assert_eq!(px(&p, w, 3, 3), [1.0; 4], "Alpha mode outputs the matte as grey + alpha"); + let (_, p) = render(&c, "AlphaNum").unwrap(); + assert_eq!(px(&p, w, 3, 3), [1.0; 4], "OutputMode also takes the combo index"); +} + +#[test] +fn primatte4_auto_compute_finds_the_screen() { + let c = comp(&[ + solid("BlueScreen", 16, 16, [0.1, 0.2, 0.9, 1.0]), + tool("Manual", "Photron.Primatte4", "BlueScreen", ALPHA), + tool("Auto", "Photron.Primatte4", "BlueScreen", &format!("{ALPHA} AutoCompute = Input {{ Value = 1, }},")), + ].concat()); + let Some(manual) = render(&c, "Manual").map(|(t, p)| px(&p, t.size[0], 8, 8)[3]) else { return }; + near(manual, 1.0, 1e-3, "a blue screen survives the default green key"); + near(alpha_of(&c, "Auto", 8, 8), 0.0, 1e-3, "AutoCompute keys the dominant screen colour"); +} + +#[test] +fn primatte4_garbage_and_solid_mattes() { + let c = comp(&[ + solid("Green", 8, 8, GREEN), + solid("Red", 8, 8, RED), + solid("Opaque", 8, 8, [1.0, 1.0, 1.0, 1.0]), + solid("Clear", 8, 8, [0.0, 0.0, 0.0, 0.0]), + tool("Garbage", "Photron.Primatte4", "Red", &format!("{ALPHA}{}", link("GarbageMatte", "Opaque"))), + tool("GarbageClear", "Photron.Primatte4", "Red", &format!("{ALPHA}{}", link("GarbageMatte", "Clear"))), + tool("Solid", "Photron.Primatte4", "Green", &format!("{ALPHA}{}", link("SolidMatte", "Opaque"))), + tool("SolidClear", "Photron.Primatte4", "Green", &format!("{ALPHA}{}", link("SolidMatte", "Clear"))), + ].concat()); + let Some(garbage) = render(&c, "Garbage").map(|(t, p)| px(&p, t.size[0], 3, 3)[3]) else { return }; + near(garbage, 0.0, 1e-3, "a white garbage matte removes the foreground"); + near(alpha_of(&c, "GarbageClear", 3, 3), 1.0, 1e-3, "an empty garbage matte changes nothing"); + near(alpha_of(&c, "Solid", 3, 3), 1.0, 1e-3, "a solid matte forces opacity over the screen"); + near(alpha_of(&c, "SolidClear", 3, 3), 0.0, 1e-3, "an empty solid matte changes nothing"); +} + +#[test] +fn primatte4_matte_blur_contract_expand_and_deartifacting() { + let c = comp(&[ + split_scene(), + tool("Edge", "Photron.Primatte4", "Split", ALPHA), + tool("Blur", "Photron.Primatte4", "Split", &format!("{ALPHA} MatteBlur = Input {{ Value = 4, }},")), + tool("Contract", "Photron.Primatte4", "Split", &format!("{ALPHA} MatteContractExpand = Input {{ Value = -4, }},")), + tool("Expand", "Photron.Primatte4", "Split", &format!("{ALPHA} MatteContractExpand = Input {{ Value = 4, }},")), + tool("Clean", "Photron.Primatte4", "Split", &format!("{ALPHA} Deartifacting = Input {{ Value = 1, }},")), + ].concat()); + let at = |name: &str, x: u32| alpha_of(&c, name, x, 8); + let Some(edge_in) = render(&c, "Edge").map(|(t, p)| px(&p, t.size[0], 14, 8)[3]) else { return }; + near(edge_in, 1.0, 1e-3, "hard edge: opaque left"); + near(at("Edge", 17), 0.0, 1e-3, "hard edge: transparent right"); + let (blur_in, blur_out) = (at("Blur", 14), at("Blur", 17)); + assert!(blur_in < 0.95 && blur_out > 0.05, "MatteBlur softens both sides of the edge: {blur_in} {blur_out}"); + assert!(at("Contract", 14) < 0.5 && at("Contract", 2) > 0.99, "negative MatteContractExpand erodes the foreground"); + assert!(at("Expand", 17) > 0.5 && at("Expand", 28) < 0.01, "positive MatteContractExpand grows the foreground"); + near(at("Clean", 2), 1.0, 1e-3, "Deartifacting leaves solid regions alone"); + near(at("Clean", 28), 0.0, 1e-3, "Deartifacting leaves solid regions alone"); +} + +#[test] +fn primatte4_blend_mask_process_and_missing_input() { + let c = comp(&[ + split_scene(), + solid("Red", 32, 16, RED), + "Free = Photron.Primatte4 { },".to_owned(), + tool("Off", "Photron.Primatte4", "Red", "Blend = Input { Value = 0, },"), + tool("Half", "Photron.Primatte4", "Red", "Blend = Input { Value = 0.5, }, OutputMode = Input { Value = FuID { \"Alpha\" }, },"), + tool("SkipAlpha", "Photron.Primatte4", "SplitG", &format!("{ALPHA} ProcessAlpha = Input {{ Value = 0, }},")), + tool("Masked", "Photron.Primatte4", "SplitG", &format!("{ALPHA} {}", link("EffectMask", "SplitMask").replace("\"Output\"", "\"Mask\""))), + tool("Mult", "Photron.Primatte4", "SplitR", &format!("{ALPHA} MultiplyByMask = Input {{ Value = 1, }}, {}", link("EffectMask", "SplitMask").replace("\"Output\"", "\"Mask\""))), + ].concat()); + let Some((tex, p)) = render(&c, "Off") else { return }; + assert_eq!(px(&p, tex.size[0], 3, 3), RED, "Blend=0 returns the input"); + let (_, p) = render(&c, "Half").unwrap(); + near(px(&p, 32, 3, 3)[0], (0.9 + 1.0) / 2.0, 1e-3, "Blend=0.5 mixes the source with the keyed result"); + assert_eq!(render(&c, "Free").unwrap().0.size, [1, 1], "no input renders the placeholder"); + let (_, p) = render(&c, "SkipAlpha").unwrap(); + near(px(&p, 32, 3, 3)[3], 1.0, 1e-3, "ProcessAlpha=0 keeps the source alpha over the keyed screen"); + let (_, p) = render(&c, "Masked").unwrap(); + near(px(&p, 32, 4, 8)[0], 0.0, 1e-3, "inside the EffectMask the key applies"); + near(px(&p, 32, 28, 8)[0], GREEN[0], 1e-3, "outside the EffectMask the source stays"); + let (_, p) = render(&c, "Mult").unwrap(); + assert_eq!(px(&p, 32, 28, 8), [0.0; 4], "MultiplyByMask zeroes outside the mask"); + assert_eq!(px(&p, 32, 4, 8), [1.0; 4], "inside the mask the opaque foreground matte remains"); +} + +#[test] +fn profiler_run_command_and_external_matte_saver_are_lossless_passthroughs() { + let c = comp(&[ + solid("Src", 16, 16, [0.2, 0.4, 0.6, 1.0]), + solid("Hdr", 16, 16, [3.5, -0.25, 0.75, 0.5]), + with_z("Deep", "Src"), + tool("Prof", "Profiler", "Deep", ""), + tool("Run", "RunCommand", "Deep", "Command = Input { Value = \"touch /tmp/fission_run_command_must_not_exist\", }, Mode = Input { Value = 1, },"), + tool("Matte", "Fuse.ExternalMatteSaver", "Deep", "Filename = Input { Value = \"/tmp/fission_matte_saver_must_not_exist.exr\", },"), + tool("RunHdr", "RunCommand", "Hdr", ""), + tool("ProfHdr", "Profiler", "Hdr", ""), + tool("MatteHdr", "Fuse.ExternalMatteSaver", "Hdr", ""), + "Free = Profiler { }, FreeRun = RunCommand { }, FreeMatte = Fuse.ExternalMatteSaver { },".to_owned(), + ].concat()); + let Some((deep, deep_px)) = render(&c, "Deep") else { return }; + for name in ["Prof", "Run", "Matte"] { + let (t, p) = render(&c, name).unwrap(); + assert_eq!(p, deep_px, "{name} pixels"); + assert_eq!((t.origin, t.canvas_size, t.depth), (deep.origin, deep.canvas_size, deep.depth), "{name} DoD/depth"); + assert!(t.aux.as_ref().is_some_and(|a| a.z.is_some()), "{name} keeps aux.z"); + } + let (_, hdr_px) = render(&c, "Hdr").unwrap(); + for name in ["ProfHdr", "RunHdr", "MatteHdr"] { + let (t, p) = render(&c, name).unwrap(); + assert_eq!(p, hdr_px, "{name} keeps out-of-range float values"); + assert!(t.depth.is_float(), "{name} stays float"); + } + assert_eq!(px(&hdr_px, 16, 4, 4), [3.5, -0.25, 0.75, 0.5]); + for name in ["Free", "FreeRun", "FreeMatte"] { + assert_eq!(render(&c, name).unwrap().0.size, [1, 1], "{name} disconnected"); + } + assert!(!std::path::Path::new("/tmp/fission_run_command_must_not_exist").exists(), "RunCommand never executes its command"); + assert!(!std::path::Path::new("/tmp/fission_matte_saver_must_not_exist.exr").exists(), "ExternalMatteSaver never writes files"); +} diff --git a/crates/engine/src/shaders/deep_flow.wgsl b/crates/engine/src/shaders/deep_flow.wgsl index 315d689059ad50c42be12c22e81980fc7598c725..c886c67151ec1ceaa45b9c0bb7ecd581c37dc251 100644 --- a/crates/engine/src/shaders/deep_flow.wgsl +++ b/crates/engine/src/shaders/deep_flow.wgsl @@ -108,15 +108,12 @@ fn apply_channel_blend( skip: vec4, ) -> vec4 { var out_c = mix(orig, effect, eff); + var kept = orig; if (mbm > 0.5) { out_c = out_c * mask_v; + kept = vec4(0.0); } - return vec4( - select(out_c.r, orig.r, skip.x > 0.5), - select(out_c.g, orig.g, skip.y > 0.5), - select(out_c.b, orig.b, skip.z > 0.5), - select(out_c.a, orig.a, skip.w > 0.5), - ); + return select(out_c, kept, skip > vec4(0.5)); } // Shared Blend / EffectMask / MultiplyByMask / Process{R,G,B,A} tail of every kernel. @@ -379,79 +376,56 @@ fn ssao_op(@builtin(global_invocation_id) gid: vec3) { } // ---------------------------------------------------------------------------- -// Shader (deep-pixel relighting). src_a = albedo, src_b = aux.z, src_c = aux.normal, src_d = equirect map -// Lighting runs in y-up pixel space with +Z toward the viewer. -// p[0] = (light_type 0 dir / 1 point / 2 spot, ambient, diffuse, specular) -// p[1] = (spec_exponent, reflectivity, has_map, has_normal) -// p[2].xyz = light direction-to-light (directional) or light position (point/spot) -// p[3] = (spot axis xyz pointing away from the light, cos_cone), p[4] = (light rgb, spot_softness) -// p[5] = (z_scale, bump_height, has_z, 0) +// Shader. src_a = premultiplied image, src_c = aux.normal, src_d = EnvironmentReflectionMap. +// p[0] = (ambient, diffuse, specular, reflection), p[1] = (has_map, has_normal, reflection_type, 0) +// p[2].xyz = direction to the light, p[3].xyz = specular colour +// Without normals nothing faces the light: only the ambient term remains. // ---------------------------------------------------------------------------- -fn relight_height(p_in: vec2, dims: vec2) -> f32 { - let c = clamp(p_in, vec2(0), dims - vec2(1)); - if (u.p[5].z > 0.5) { - let z = textureLoad(src_b, c, 0).r; - return select(0.0, clamp(z, -1.0e6, 1.0e6) * u.p[5].x, z_valid(z)); - } - return dot(textureLoad(src_a, c, 0).rgb, LUMA_W) * u.p[5].y; -} +const SPEC_EXPONENT: f32 = 32.0; @compute @workgroup_size(8, 8, 1) fn relight_op(@builtin(global_invocation_id) gid: vec3) { let dims = textureDimensions(dst_tex); if (gid.x >= dims.x || gid.y >= dims.y) { return; } let p = vec2(gid.xy); - let idims = vec2(dims); let src = textureLoad(src_a, p, 0); - - let h = relight_height(p, idims); - var n = vec3(0.0, 0.0, 1.0); - var have_n = false; - if (u.p[1].w > 0.5) { - let nr = textureLoad(src_c, p, 0).xyz; - if (dot(nr, nr) > 1.0e-6) { - n = normalize(nr); - have_n = true; + var lit = src.rgb * u.p[0].x; + if (u.p[1].y > 0.5) { + var n = textureLoad(src_c, p, 0).xyz; + if (dot(n, n) > 1.0e-6) { + n = normalize(n); + if (n.z < 0.0) { n = -n; } + let l = normalize(u.p[2].xyz); + let v = vec3(0.0, 0.0, 1.0); + let ndl = max(dot(n, l), 0.0); + let spec = pow(max(dot(n, normalize(l + v)), 0.0), SPEC_EXPONENT) * select(0.0, 1.0, ndl > 0.0); + lit = src.rgb * (u.p[0].x + u.p[0].y * ndl) + u.p[3].xyz * (u.p[0].z * spec * src.a); + if (u.p[1].x > 0.5) { + var uv = vec2(n.x * 0.5 + 0.5, 0.5 - n.y * 0.5); + if (u.p[1].z > 1.5) { + let t = refract(-v, n, 1.0 / 1.5); + uv = vec2(t.x * 0.5 + 0.5, 0.5 - t.y * 0.5); + } else if (u.p[1].z > 0.5) { + let r = 2.0 * n.z * n - v; + uv = vec2(fract(atan2(r.x, r.z) / TAU + 0.5), acos(clamp(r.y, -1.0, 1.0)) / PI); + } + lit = lit + sample_bilinear_clamped(src_d, uv).rgb * (u.p[0].w * src.a); + } } } - if (!have_n) { - let dhdx = (relight_height(p + vec2(1, 0), idims) - relight_height(p + vec2(-1, 0), idims)) * 0.5; - let dhdy_up = (relight_height(p + vec2(0, -1), idims) - relight_height(p + vec2(0, 1), idims)) * 0.5; - n = normalize(vec3(-dhdx, -dhdy_up, 1.0)); + let mask_v = read_mask(gid.xy, dims, u.p[15].y, u.p[15].z); + var out_c = apply_channel_blend(src, vec4(lit, src.a), u.p[15].x * mask_v, mask_v, u.p[15].w, u.p[14]); + if (!HDR_FLOAT) { + // Fusion's 8-bit lighting truncates instead of rounding. + out_c = floor(out_c * 255.0 + 1.0e-3) / 255.0; } - if (n.z < 0.0) { n = -n; } - - let light_type = i32(u.p[0].x + 0.5); - var l = u.p[2].xyz; - var atten = 1.0; - if (light_type > 0) { - let pos = vec3(f32(p.x) + 0.5, f32(idims.y) - (f32(p.y) + 0.5), h); - let to_light = u.p[2].xyz - pos; - l = normalize(to_light); - if (light_type == 2) { - let cos_a = dot(-l, normalize(u.p[3].xyz)); - atten = smoothstep(u.p[3].w, u.p[3].w + max(u.p[4].w, 1.0e-4), cos_a); - } - } - let v = vec3(0.0, 0.0, 1.0); - let ndl = max(dot(n, l), 0.0) * atten; - let hv = normalize(l + v); - let spec = pow(max(dot(n, hv), 0.0), max(u.p[1].x, 1.0)) * atten * select(0.0, 1.0, ndl > 0.0); - let light_rgb = u.p[4].xyz; - - var lit = src.rgb * (u.p[0].y + u.p[0].z * ndl * light_rgb) + vec3(u.p[0].w * spec) * light_rgb; - if (u.p[1].z > 0.5) { - let r = 2.0 * dot(n, v) * n - v; - let uv = vec2(atan2(r.x, r.z) / TAU + 0.5, acos(clamp(r.y, -1.0, 1.0)) / PI); - let env = sample_bilinear_clamped(src_d, vec2(fract(uv.x), uv.y)).rgb; - lit = lit + env * u.p[1].y; - } - finish(gid.xy, dims, src, vec4(lit, src.a)); + store_dst(p, out_c); } // ---------------------------------------------------------------------------- -// Texture (UV remap). src_a = image whose RG channels carry UV (A = coverage), src_b = texture -// p[0] = (u_scale, v_scale, u_offset, v_offset), p[1].x = edge mode +// Texture (UV remap). src_a = image whose RG channels carry UV (A = coverage), src_b = texture. +// uv = swap -> scale & offset (u * scale - offset) -> rotate 90 -> flip. +// p[0] = (u_scale, v_scale, u_offset, v_offset), p[1] = (edge mode, has_texture, swap_uv, rotate_90), p[2] = (flip_h, flip_v, 0, 0) // ---------------------------------------------------------------------------- @compute @workgroup_size(8, 8, 1) fn texture_op(@builtin(global_invocation_id) gid: vec3) { @@ -459,7 +433,16 @@ fn texture_op(@builtin(global_invocation_id) gid: vec3) { if (gid.x >= dims.x || gid.y >= dims.y) { return; } let p = vec2(gid.xy); let src = textureLoad(src_a, p, 0); - let uv = vec2(src.r * u.p[0].x + u.p[0].z, src.g * u.p[0].y + u.p[0].w); + if (u.p[1].y < 0.5) { + finish(gid.xy, dims, src, src); + return; + } + var uv = src.rg; + if (u.p[1].z > 0.5) { uv = uv.yx; } + uv = uv * u.p[0].xy - u.p[0].zw; + if (u.p[1].w > 0.5) { uv = vec2(uv.y, 1.0 - uv.x); } + if (u.p[2].x > 0.5) { uv.x = 1.0 - uv.x; } + if (u.p[2].y > 0.5) { uv.y = 1.0 - uv.y; } let tdims = vec2(textureDimensions(src_b)); // UV v = 0 is the bottom row of the texture. let pos = vec2(uv.x * tdims.x, (1.0 - uv.y) * tdims.y); @@ -494,8 +477,9 @@ fn vector_warp_op(@builtin(global_invocation_id) gid: vec3) { } // ---------------------------------------------------------------------------- -// VectorTransform. src_a = vector texel (aux vector or colour RG); only .xy is transformed. -// p[0] = (x_scale, y_scale, cos, sin), p[1] = (x_offset, y_offset, flip_x, flip_y), p[2] = (invert, normalize, 0, 0) +// VectorTransform. src_a = aux vector texel; only .xy is transformed: smooth, then scale and rotate, +// mixed in by the attenuation. +// p[0] = (x_size, y_size, cos, sin), p[1] = (attenuate, smooth_radius_px, 0, 0) // ---------------------------------------------------------------------------- @compute @workgroup_size(8, 8, 1) fn vector_transform_op(@builtin(global_invocation_id) gid: vec3) { @@ -503,18 +487,22 @@ fn vector_transform_op(@builtin(global_invocation_id) gid: vec3) { if (gid.x >= dims.x || gid.y >= dims.y) { return; } let p = vec2(gid.xy); let src = textureLoad(src_a, p, 0); - var v = vec2(clean(src.x, 65504.0), clean(src.y, 65504.0)); - if (u.p[1].z > 0.5) { v.x = -v.x; } - if (u.p[1].w > 0.5) { v.y = -v.y; } - if (u.p[2].x > 0.5) { v = -v; } - if (u.p[2].y > 0.5) { - let len = length(v); - v = select(vec2(0.0), v / len, len > 1.0e-6); + let idims = vec2(dims); + let r = i32(round(u.p[1].y)); + var v = vec2(0.0); + var weight = 0.0; + for (var dy = -1; dy <= 1; dy = dy + 1) { + for (var dx = -1; dx <= 1; dx = dx + 1) { + let q = clamp(p + vec2(dx, dy) * r, vec2(0), idims - vec2(1)); + let t = textureLoad(src_a, q, 0); + v = v + vec2(clean(t.x, 65504.0), clean(t.y, 65504.0)); + weight = weight + 1.0; + } } - v = v * u.p[0].xy; - v = vec2(u.p[0].z * v.x - u.p[0].w * v.y, u.p[0].w * v.x + u.p[0].z * v.y); - v = v + u.p[1].xy; - finish(gid.xy, dims, src, vec4(v, src.z, src.w)); + v = select(vec2(clean(src.x, 65504.0), clean(src.y, 65504.0)), v / weight, r > 0); + let scaled = v * u.p[0].xy; + let rotated = vec2(u.p[0].z * scaled.x - u.p[0].w * scaled.y, u.p[0].w * scaled.x + u.p[0].z * scaled.y); + finish(gid.xy, dims, src, vec4(mix(v, rotated, u.p[1].x), src.z, src.w)); } // ---------------------------------------------------------------------------- diff --git a/crates/engine/src/shaders/primatte_misc.wgsl b/crates/engine/src/shaders/primatte_misc.wgsl new file mode 100644 index 0000000000000000000000000000000000000000..3eb9539b0877d71a940c539f61646591fb0e1a3c --- /dev/null +++ b/crates/engine/src/shaders/primatte_misc.wgsl @@ -0,0 +1,236 @@ +// Photron.Primatte4 compute shader: polyhedral chroma-space keyer. +// +// WebGPU-safe (`wasm32` compatible): every texture input is `filterable: false` and read via +// `textureLoad`; the output is a WriteOnly storage texture (format patched at pipeline build); +// no `read_write` storage textures. +// +// Bindings: tex_a = foreground, tex_b = Background, tex_c = GarbageMatte, tex_d = SolidMatte, mask_tex = EffectMask. +// +// p[0] = (key rgb, auto_compute) +// p[1] = (clean_background, clean_foreground, matte_sponge, matte_restore) +// p[2] = (spill_sponge, detail_minus, detail_plus, spill_suppression) +// p[3] = (deartifacting, matte_blur_px, contract_expand_px, output_mode: 0 composite / 1 alpha / 2 spill suppressed) +// p[4] = (has_background, has_garbage, has_solid, 0) +// p[14] = (blend, has_mask, mask_invert, multiply_by_mask), p[15] = per-channel skip (1 = keep source) + +@group(0) @binding(0) var tex_a: texture_2d; +@group(0) @binding(1) var tex_b: texture_2d; +@group(0) @binding(2) var tex_c: texture_2d; +@group(0) @binding(3) var tex_d: texture_2d; +@group(0) @binding(4) var mask_tex: texture_2d; +@group(0) @binding(5) var dst_tex: texture_storage_2d; + +struct Params { + p: array, 16>, +}; +@group(0) @binding(6) var u: Params; + +const HDR_FLOAT: bool = false; +const LUMA_709: vec3 = vec3(0.2126, 0.7152, 0.0722); +const TAU: f32 = 6.283185307179586; +// Orthonormal basis of the chroma plane (perpendicular to the grey axis). +const CHROMA_E1: vec3 = vec3(0.8164966, -0.4082483, -0.4082483); +const CHROMA_E2: vec3 = vec3(0.0, 0.7071068, -0.7071068); +// Polyhedron radii (in key-chroma units) at zero `Clean*` adjustment. +const BASE_INNER: f32 = 0.35; +const BASE_OUTER: f32 = 0.85; +const AUTO_GRID: i32 = 5; + +fn store_dst(p: vec2, col: vec4) { + if (HDR_FLOAT) { + textureStore(dst_tex, p, col); + } else { + textureStore(dst_tex, p, clamp(col, vec4(0.0), vec4(1.0))); + } +} + +fn load_clamped(tex: texture_2d, p: vec2) -> vec4 { + let dims = vec2(textureDimensions(tex)); + return textureLoad(tex, clamp(p, vec2(0), max(dims - vec2(1), vec2(0))), 0); +} + +fn sample_bilinear(tex: texture_2d, uv: vec2) -> vec4 { + let dims = vec2(textureDimensions(tex)); + let max_c = max(dims - vec2(1), vec2(0)); + let f = clamp(uv, vec2(0.0), vec2(1.0)) * vec2(dims) - vec2(0.5); + let i0 = clamp(vec2(floor(f)), vec2(0), max_c); + let i1 = clamp(i0 + vec2(1), vec2(0), max_c); + let t = clamp(f - floor(f), vec2(0.0), vec2(1.0)); + let c00 = textureLoad(tex, i0, 0); + let c10 = textureLoad(tex, vec2(i1.x, i0.y), 0); + let c01 = textureLoad(tex, vec2(i0.x, i1.y), 0); + let c11 = textureLoad(tex, i1, 0); + return mix(mix(c00, c10, t.x), mix(c01, c11, t.x), t.y); +} + +fn read_mask(gid: vec2, dims: vec2) -> f32 { + if (u.p[14].y < 0.5) { + return 1.0; + } + let m = sample_bilinear(mask_tex, (vec2(gid) + vec2(0.5)) / vec2(dims)).a; + return select(m, 1.0 - m, u.p[14].z > 0.5); +} + +/// Blend `res` over `src` by `Blend * EffectMask`; `MultiplyByMask` zeroes outside the mask. +fn finish(src: vec4, res: vec4, gid: vec2, dims: vec2) -> vec4 { + let m = clamp(read_mask(gid, dims) * u.p[14].x, 0.0, 1.0); + let use_mbm = u.p[14].y > 0.5 && u.p[14].w > 0.5; + let out_col = select(mix(src, res, m), res * m, use_mbm); + let unproc = select(src, vec4(0.0), use_mbm); + return select(out_col, unproc, u.p[15] > vec4(0.5)); +} + +fn chroma_plane(c: vec3) -> vec2 { + return vec2(dot(c, CHROMA_E1), dot(c, CHROMA_E2)); +} + +/// Chroma scaled by the brightest channel: a key-coloured shadow keeps the key's coordinates (the chroma cone). +fn cone_chroma(c: vec3) -> vec2 { + return chroma_plane(c) / max(max(c.r, max(c.g, c.b)), 1.0e-3); +} + +/// Regular-hexagon norm, vertices on the x axis: the cross-section of the polyhedron around the key axis. +fn hex_norm(v: vec2) -> f32 { + let a = abs(v); + return max(0.8660254 * a.x + 0.5 * a.y, a.y); +} + +struct Key { + rgb: vec3, + cone: vec2, + axis: vec2, + inv_mag: f32, +} + +fn make_key(rgb: vec3) -> Key { + let cone = cone_chroma(rgb); + let mag = max(length(cone), 1.0e-3); + return Key(rgb, cone, cone / mag, 1.0 / mag); +} + +/// Distance of `c` from the key in key-chroma units: 0 on the key colour, ~1 for a neutral grey. +fn key_distance(c: vec3, k: Key) -> f32 { + let d = cone_chroma(c) - k.cone; + return hex_norm(vec2(dot(d, k.axis), dot(d, vec2(-k.axis.y, k.axis.x)))) * k.inv_mag; +} + +/// Auto-detected key: the average of the grid samples near the most key-like (saturated) one. +fn auto_key(dims: vec2) -> vec3 { + var best = vec3(0.0, 1.0, 0.0); + var best_sat = -1.0; + for (var j = 0; j < AUTO_GRID; j = j + 1) { + for (var i = 0; i < AUTO_GRID; i = i + 1) { + let c = load_clamped(tex_a, (vec2(i, j) * 2 + vec2(1)) * dims / (2 * AUTO_GRID)).rgb; + let sat = length(chroma_plane(c)); + if (sat > best_sat) { + best_sat = sat; + best = c; + } + } + } + let seed = make_key(best); + var sum = vec3(0.0); + var count = 0.0; + for (var j = 0; j < AUTO_GRID; j = j + 1) { + for (var i = 0; i < AUTO_GRID; i = i + 1) { + let c = load_clamped(tex_a, (vec2(i, j) * 2 + vec2(1)) * dims / (2 * AUTO_GRID)).rgb; + if (key_distance(c, seed) < BASE_INNER) { + sum = sum + c; + count = count + 1.0; + } + } + } + return sum / max(count, 1.0); +} + +/// Matte of one pixel from the key polyhedra, then the sponge / restore / detail adjustments. +fn matte_at(p: vec2, k: Key) -> f32 { + let c = load_clamped(tex_a, p).rgb; + let inner = BASE_INNER + 0.5 * u.p[1].x; + let outer = max(BASE_OUTER - 0.5 * u.p[1].y, inner + 0.05); + var a = smoothstep(inner, outer, key_distance(c, k)); + a = clamp((a - 0.5 * u.p[1].z) / (1.0 - 0.5 * u.p[1].z), 0.0, 1.0); + a = 1.0 - pow(1.0 - a, 1.0 + 2.0 * u.p[1].w); + a = mix(a, a * a, u.p[2].y); + return mix(a, sqrt(a), u.p[2].z); +} + +/// Golden-angle disc tap `i` of `n`, scaled to `radius` pixels. +fn disc_tap(i: i32, n: i32, radius: f32) -> vec2 { + let r = radius * sqrt((f32(i) + 0.5) / f32(n)); + let t = f32(i) * 2.3999632; + return vec2(round(vec2(cos(t), sin(t)) * r)); +} + +@compute @workgroup_size(8, 8) +fn primatte_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { return; } + let p = vec2(gid.xy); + let src = textureLoad(tex_a, p, 0); + var key_rgb = u.p[0].xyz; + if (u.p[0].w > 0.5) { + key_rgb = auto_key(vec2(dims)); + } + let k = make_key(key_rgb); + let uv = (vec2(gid.xy) + vec2(0.5)) / vec2(dims); + + var a = matte_at(p, k); + let deartifact = u.p[3].x; + if (deartifact > 0.0) { + var ring = 0.0; + for (var i = 0; i < 8; i = i + 1) { + ring = ring + matte_at(p + disc_tap(i, 8, 1.5), k); + } + ring = ring / 8.0; + a = mix(a, ring, deartifact * smoothstep(0.25, 0.75, abs(a - ring))); + } + let blur = u.p[3].y; + if (blur > 0.0) { + var sum = a; + for (var i = 0; i < 16; i = i + 1) { + sum = sum + matte_at(p + disc_tap(i, 16, blur), k); + } + a = sum / 17.0; + } + let grow = u.p[3].z; + if (abs(grow) > 0.0) { + var ext = a; + for (var i = 0; i < 16; i = i + 1) { + let t = matte_at(p + disc_tap(i, 16, abs(grow)), k); + ext = select(min(ext, t), max(ext, t), grow > 0.0); + } + a = ext; + } + if (u.p[4].y > 0.5) { + a = a * (1.0 - sample_bilinear(tex_c, uv).a); + } + if (u.p[4].z > 0.5) { + a = max(a, sample_bilinear(tex_d, uv).a); + } + + // Colour: remove the key's share of the partially transparent edge, then its chroma lean, keeping luminance. + let d = key_distance(src.rgb, k); + let dec = clamp((src.rgb - (1.0 - a) * k.rgb) / max(a, 1.0e-3), vec3(0.0), vec3(1.0)); + var fg = mix(src.rgb, dec, u.p[2].w * smoothstep(0.0, 0.1, a) * select(0.0, 1.0, a < 0.999)); + let reach = max(BASE_OUTER - 0.5 * u.p[1].y, BASE_INNER) * (1.4 + 1.6 * u.p[2].x); + let weight = 1.0 - smoothstep(0.6 * BASE_OUTER, reach, d); + let lean = max(dot(chroma_plane(fg), k.axis), 0.0); + let axis_rgb = CHROMA_E1 * k.axis.x + CHROMA_E2 * k.axis.y; + let despilled = fg - axis_rgb * lean * weight * u.p[2].w; + fg = max(despilled + (dot(fg, LUMA_709) - dot(despilled, LUMA_709)), vec3(0.0)); + + var res: vec4; + let mode = i32(u.p[3].w + 0.5); + if (mode == 1) { + res = vec4(a, a, a, a); + } else if (mode == 2) { + res = vec4(fg, src.a); + } else if (u.p[4].x > 0.5) { + let bg = sample_bilinear(tex_b, uv); + res = vec4(fg * a + bg.rgb * (1.0 - a), a + bg.a * (1.0 - a)); + } else { + res = vec4(fg * a, a); + } + store_dst(p, finish(src, res, gid.xy, dims)); +} -- 2.54.1