diff --git a/compatibility.md b/compatibility.md index a757910a9efb9d8035cc381dffe5b190059662c3..076176870c00ba671a7d2e408f81a6a708c650d5 100644 --- a/compatibility.md +++ b/compatibility.md @@ -9,10 +9,10 @@ Auto-generated from live engine sources (`crates/engine/src/eval.rs`, `crates/en | Metric | Value | | --- | --- | -| **Supported Flow Tools** | **79** (70 2D/Fuse/utility in `eval.rs`, 7 3D scene nodes in `scene3d.rs`, 2 Flow annotations) | +| **Supported Flow Tools** | **80** (71 2D/Fuse/utility in `eval.rs`, 7 3D scene nodes in `scene3d.rs`, 2 Flow annotations) | | **Modifiers & Animation** | **7** systems (8 Fusion modifier classes + Lua expressions) | -| **Active Corpus (`trees/fusion`) Coverage** | **99.3%** (1,980 / 1,993 nodes across 16 `.comp` files) | -| **Archive Corpus (`private/samples`) Coverage** | **96.1%** (52,825 / 54,955 nodes across 324 `.comp` files) | +| **Active Corpus (`trees/fusion`) Coverage** | **99.4%** (1,981 / 1,993 nodes across 16 `.comp` files) | +| **Archive Corpus (`private/samples`) Coverage** | **96.1%** (52,826 / 54,955 nodes across 324 `.comp` files) | | **HiQ vs Fast Mode** | **`HiQ`**: honors `DepthFull` / generator `Depth` / `ChangeDepth` (`Rgba8Unorm`, clamped `Rgba16Float`, unclamped HDR `Rgba16Float`/`Rgba32Float`), full-res blurs & `XGlow`. **`Fast`**: collapses working targets to `Rgba8Unorm`, downsamples blurs, caps `XGlow` octaves for interactive scrubbing. | ## Generators @@ -38,7 +38,7 @@ Auto-generated from live engine sources (`crates/engine/src/eval.rs`, `crates/en | Tool | Probe Suite | Verified MAE | Usage (Active / Archive) | Notes & Fallbacks | | --- | --- | --- | --- | --- | | `BrightnessContrast` | `color_ops`, `tier1_d` | 0.0%–0.1% | 29 / 231 | Gain, Lift, Gamma, Contrast, Brightness, Saturation, channel toggles, `PreDividePostMultiply`, `ClipBlack`/`ClipWhite`. | -| `ColorCorrector` | Suite comps | 0.1%–0.5% | 86 / 1357 | Master/Shadow/Midtone/Highlight wheel tint, Lift/Gamma/Gain/Brightness/Contrast/Saturation, `PreDividePostMultiply`. | +| `ColorCorrector` | `vortex_cc`, Suite comps | 0.0%–0.4% | 86 / 1357 | Master/Shadow/Midtone/Highlight wheels, exact Fusion 21.1 `TintMode` (`0`/`1`/`2`), Lift/Gamma/Gain/Brightness/Contrast/Saturation, `PreDividePostMultiply`. | | `ColorGain` | `color_ops`, `noise_text` | 0.0%–0.1% | 2 / 4 | Per-channel Gain, Lift, Gamma, Hue, Saturation, `PreDividePostMultiply`. | | `ColorCurves` | Suite comps | 0.1%–0.4% | 5 / 109 | Per-channel RGBA `LUTBezier` spline lookup tables with `PreDividePostMultiply`. | | `HueCurves` | `tier1_a` | 0.1%–0.5% | 6 / 28 | 9 nested `LUTBezier` splines (Hue/Sat/Lum vs Hue, Suppression, etc.) baked to GPU LUT. | @@ -53,7 +53,7 @@ Auto-generated from live engine sources (`crates/engine/src/eval.rs`, `crates/en | Tool | Probe Suite | Verified MAE | Usage (Active / Archive) | Notes & Fallbacks | | --- | --- | --- | --- | --- | | `LumaKeyer` | Suite comps | 0.1%–0.4% | 4 / 95 | Luminance/channel threshold keying with low/high feathering and matte inversion. | -| `UltraKeyer` | `tier1_a` | 0.1%–0.6% | 16 / 66 | Chroma keying with background color pick, matte threshold/gamma, spill suppression, and post-multiply. | +| `UltraKeyer` | `ultrakey`, `tier1_a` | 0.0%–0.1% | 16 / 66 | Exact Fusion 21.1 Ultimatte color-difference matte + background subtraction (`BackgroundRed/Green/Blue`, `LowMatteThreshold`/`High`, `MatteSeparation`, `SpillSuppression`, `PostMultiplyImage`). | | `Fuse.Cryptomatte` | Unit tests | 0.0% | 0 / 37 | Cryptomatte 1.2 multi-channel EXR matte extraction (manifest JSON + MurmurHash3-32 ID/coverage rank accumulation, wildcards, `MatteOnly`). | ## Blur, Sharpen & Glow @@ -81,7 +81,8 @@ Auto-generated from live engine sources (`crates/engine/src/eval.rs`, `crates/en | `CameraShake` | `tier1_c` | 0.1%–0.5% | 0 / 12 | Procedural X/Y/Rotation/Zoom camera shake with `OverallStrength`, `Speed`, `Edges`. | | `CornerPositioner` | `tier1_b` | 0.1%–0.4% | 0 / 29 | 4-point projective homography warp (`TopLeft`/`TopRight`/`BottomLeft`/`BottomRight`). | | `DVE` | `tier1_b` | 0.1%–0.4% | 4 / 22 | 2.5D ZYX Euler rotation + perspective homography (`Center`, `ZMove`, `Pivot`, `AlphaMode`). | -| `Displace` | `displace` | 0.0%–0.1% | 11 / 109 | `XY` refraction (channels, offsets, refraction strength) and `Radial`/`Bump` (`LightPower`, `LightAngle`, `LightChannel` additive directional slope lighting). | +| `Displace` | `displace`, `displace_wave` | 0.0%–0.1% | 11 / 109 | `XY` refraction (channels, offsets, refraction strength) and `Radial`/`Bump` (`LightPower`, `LightAngle`, `LightChannel` additive directional slope lighting). | +| `Vortex` | `vortex_cc` | 0.0%–0.4% | 1 / 1 | Isotropic radial swirl warp (`Center`, `Size`, `Angle`, `Power`, `Blend`, `EffectMask`). | | `Scale` | Suite comps | 0.0%–0.2% | 12 / 98 | Proportional/non-proportional image scaling with resampling filter. | | `BetterResize` | Suite comps | 0.0%–0.2% | 0 / 93 | Target pixel-dimension resize (`Width`, `Height`, `KeepAspect`). | | `Crop` | Suite comps | 0.0%–0.1% | 3 / 168 | Region crop & canvas repositioning (`XOffset`, `YOffset`, `XSize`, `YSize`, `KeepCentered`). | @@ -91,10 +92,10 @@ Auto-generated from live engine sources (`crates/engine/src/eval.rs`, `crates/en | Tool | Probe Suite | Verified MAE | Usage (Active / Archive) | Notes & Fallbacks | | --- | --- | --- | --- | --- | -| `EllipseMask` | `mask` | 0.0%–0.2% | 33 / 109 | Center, Width, Height, Angle, `SoftEdge`, `BorderWidth`, `Solid`, `Invert`, `PaintMode` chaining. | -| `RectangleMask` | `mask` | 0.0%–0.2% | 53 / 885 | Center, Width, Height, `CornerRadius`, Angle, `SoftEdge`, `BorderWidth`, `Solid`, `Invert`, `PaintMode` chaining. | -| `PolylineMask` | Suite comps | 0.1%–0.5% | 16 / 505 | CPU `zeno` Bezier/linear polygon rasterizer with animated keyframed `Polyline` splines, `SoftEdge`, `Invert`, `PaintMode`. | -| `BitmapMask` | Suite comps | 0.0%–0.2% | 3 / 121 | Image-to-mask extraction (`Alpha`/`Luminance`/`Red`/`Green`/`Blue`), `Low`/`High` clip, `SoftEdge`, `Invert`. | +| `EllipseMask` | `mask`, `mask_softedge` | 0.0%–0.2% | 33 / 109 | Center, Width, Height, Angle, progressive-pyramid `SoftEdge`, `BorderWidth`, `Solid`, `Filter` (`Fast Gaussian`/`Box`), `ClippingMode`, `Invert`, `PaintMode` chaining. | +| `RectangleMask` | `mask`, `mask_softedge` | 0.0%–0.2% | 53 / 885 | Center, Width, Height, `CornerRadius`, Angle, progressive-pyramid `SoftEdge`, `BorderWidth`, `Solid`, `Filter`, `ClippingMode`, `Invert`, `PaintMode` chaining. | +| `PolylineMask` | `mask_softedge`, Suite comps | 0.1%–0.4% | 16 / 505 | CPU `zeno` Bezier/linear polygon rasterizer with animated keyframed `Polyline` splines, progressive-pyramid `SoftEdge`, `ClippingMode`, `Invert`, `PaintMode`. | +| `BitmapMask` | `mask_softedge` | 0.0%–0.2% | 3 / 121 | GPU image-to-mask extraction (`Alpha`/`Luminance`/`Red`/`Green`/`Blue`/`Saturation`/`Lightness`/`Hue`), `Low`/`High` clip, centered 1:1 alignment, `SoftEdge`, `Invert`, `Level`, `PaintMode`. | ## Particles diff --git a/crates/engine/src/cache.rs b/crates/engine/src/cache.rs index fcb5de98d42c8bd537ed548ef846cdda5ac88817..c0280c18927944910a3fc3f0d0d0b8c7f3220729 100644 --- a/crates/engine/src/cache.rs +++ b/crates/engine/src/cache.rs @@ -27,6 +27,8 @@ pub struct CachedTexture { pub depth: BitDepth, /// Underlying GPU texture format (`Rgba8Unorm`, `Rgba16Float`, or `Rgba32Float`). pub format: wgpu::TextureFormat, + /// Scale ratio `physical_px / logical_px` when an oversized generator (>8K) is capped to GPU limits (1.0 normally). + pub tex_scale: f32, pub content_hash: u64, pub bytes: u64, } @@ -76,6 +78,7 @@ impl CachedTexture { canvas_size, depth, format, + tex_scale: 1.0, content_hash, bytes, } diff --git a/crates/engine/src/eval.rs b/crates/engine/src/eval.rs index d62b59170a7a537ccf7353db67e3be0f6c8509e4..1d30fac89eac9002568f5ee933002f01369e8ad7 100644 --- a/crates/engine/src/eval.rs +++ b/crates/engine/src/eval.rs @@ -64,6 +64,7 @@ enum ShaderOp { MaskShape, MaskCombine, MaskApply, + BitmapMask, Colorize, ColorCurves, XfChroma, @@ -90,6 +91,7 @@ enum ShaderOp { FilmGrain, SetDomain, ChangeDepth, + Vortex, } struct Pipelines { @@ -109,6 +111,7 @@ struct Pipelines { mask_shape: wgpu::ComputePipeline, mask_combine: wgpu::ComputePipeline, mask_apply: wgpu::ComputePipeline, + bitmap_mask: wgpu::ComputePipeline, colorize: wgpu::ComputePipeline, color_curves: wgpu::ComputePipeline, xf_chroma: wgpu::ComputePipeline, @@ -135,6 +138,7 @@ struct Pipelines { film_grain: wgpu::ComputePipeline, set_domain: wgpu::ComputePipeline, change_depth: wgpu::ComputePipeline, + vortex: wgpu::ComputePipeline, } impl Pipelines { @@ -248,6 +252,7 @@ impl Pipelines { mask_shape: make("mask_shape_op"), mask_combine: make("mask_combine_op"), mask_apply: make("mask_apply_op"), + bitmap_mask: make("bitmap_mask_op"), colorize: make("colorize_op"), color_curves: make("color_curves_op"), xf_chroma: make("xf_chroma_op"), @@ -274,6 +279,7 @@ impl Pipelines { film_grain: make("film_grain_op"), set_domain: make("set_domain_op"), change_depth: make("change_depth_op"), + vortex: make("vortex_op"), } } @@ -293,6 +299,7 @@ impl Pipelines { ShaderOp::MaskShape => &self.mask_shape, ShaderOp::MaskCombine => &self.mask_combine, ShaderOp::MaskApply => &self.mask_apply, + ShaderOp::BitmapMask => &self.bitmap_mask, ShaderOp::Colorize => &self.colorize, ShaderOp::ColorCurves => &self.color_curves, ShaderOp::XfChroma => &self.xf_chroma, @@ -319,6 +326,7 @@ impl Pipelines { ShaderOp::FilmGrain => &self.film_grain, ShaderOp::SetDomain => &self.set_domain, ShaderOp::ChangeDepth => &self.change_depth, + ShaderOp::Vortex => &self.vortex, } } } @@ -441,6 +449,30 @@ impl Engine { self.alloc_tex_dod(size, [0, 0], size, depth, content_hash) } + fn alloc_tex_like(&self, src: &CachedTexture, depth: BitDepth, content_hash: u64) -> CachedTexture { + let mut t = self.alloc_tex_dod(src.size, src.origin, src.canvas_size, depth, content_hash); + t.tex_scale = src.tex_scale; + t + } + + fn crop_to_canvas(&self, enc: &mut wgpu::CommandEncoder, tex: CachedTexture) -> CachedTexture { + if !tex.has_dod() { + return tex; + } + let mut cropped = self.alloc_tex(tex.canvas_size, tex.depth, tex.content_hash ^ 0xD0D0); + cropped.tex_scale = tex.tex_scale; + let mut params = UniformParams::default(); + params.p[0] = [1.0, 1.0, 0.0, 0.0]; + params.p[4] = [ + tex.origin[0] as f32, + tex.origin[1] as f32, + tex.canvas_size[0] as f32, + tex.canvas_size[1] as f32, + ]; + self.dispatch_op(enc, ShaderOp::DisplayBlit, &tex.view, &self.dummy.view, &self.dummy.view, &cropped, ¶ms); + cropped + } + fn alloc_tex_dod( &self, size: [u32; 2], @@ -864,10 +896,11 @@ impl Engine { "Plasma" => self.eval_plasma(comp, node, time, frame_i, comp_dims, enc, visiting, stats), "FilmGrain" => self.eval_film_grain(comp, node, time, frame_i, enc, visiting, stats), "Displace" => self.eval_displace(comp, node, time, frame_i, enc, visiting, stats), + "Vortex" => self.eval_vortex(comp, node, time, frame_i, enc, visiting, stats), "EllipseMask" => self.eval_mask_shape(comp, node, time, frame_i, comp_dims, 0, enc, visiting, stats), "RectangleMask" => self.eval_mask_shape(comp, node, time, frame_i, comp_dims, 1, enc, visiting, stats), "PolylineMask" => self.eval_polyline_mask(comp, node, time, frame_i, comp_dims, enc, visiting, stats), - "BitmapMask" => self.eval_bitmap_mask(comp, node, time, enc, visiting, stats), + "BitmapMask" => self.eval_bitmap_mask(comp, node, time, frame_i, comp_dims, enc, visiting, stats), "TextPlus" => self.eval_text_plus(comp, node, time, frame_i, comp_dims, enc, stats), "Fuse.Colorize" => self.eval_colorize(comp, node, time, frame_i, enc, visiting, stats), "Fuse.Outline" => self.eval_outline(comp, node, time, frame_i, enc, visiting, stats), @@ -1230,13 +1263,13 @@ impl Engine { }; let out = if matte_only { - let dst = self.alloc_tex(src.size, dst_depth, key); + let dst = self.alloc_tex_like(&src, dst_depth, key); let mut u = UniformParams::default(); u.p[0] = [1.0, 1.0, 0.0, 0.0]; self.dispatch_op(enc, ShaderOp::DisplayBlit, &matte_tex.view, &self.dummy.view, &self.dummy.view, &dst, &u); dst } else { - let dst = self.alloc_tex(src.size, dst_depth, key); + let dst = self.alloc_tex_like(&src, dst_depth, key); let mut u = UniformParams::default(); u.p[0] = [0.0, 0.0, 0.0, 0.0]; self.dispatch_op(enc, ShaderOp::MaskApply, &src.view, &self.dummy.view, &matte_tex.view, &dst, &u); @@ -1518,11 +1551,87 @@ impl Engine { _ => 0.0, // Over }; - let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(bg.size), enc, visiting, stats); + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(bg.canvas_size), enc, visiting, stats); let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + let eff_size = size_s * (bg.tex_scale / fg.tex_scale.max(1e-4)); + + // Fusion Merge preserves/expands Domain of Definition (DoD) when FG extends outside BG + // (e.g. a grid of tiles placed partly above y=1.0 before a downstream Transform zooms out). + let bg_x0 = bg.origin[0]; + let bg_y0 = bg.origin[1]; + let bg_x1 = bg.origin[0] + bg.size[0] as i32; + let bg_y1 = bg.origin[1] + bg.size[1] as i32; + let mut dst_origin = bg.origin; + let mut dst_size = bg.size; + + if edges < 0.5 + && mask.is_none() + && mode_id == 0.0 + && (op_id == 0.0 || op_id == 1.0 || op_id == 5.0) + && bg.tex_scale >= 0.99 + && eff_size > 1e-4 + { + let bg_cw = bg.canvas_size[0].max(1) as f32; + let bg_ch = bg.canvas_size[1].max(1) as f32; + let fg_cw = fg.canvas_size[0].max(1) as f32; + let fg_ch = fg.canvas_size[1].max(1) as f32; + let u0 = fg.origin[0] as f32 / fg_cw; + let u1 = (fg.origin[0] + fg.size[0] as i32) as f32 / fg_cw; + let v0 = 1.0 - (fg.origin[1] + fg.size[1] as i32) as f32 / fg_ch; + let v1 = 1.0 - fg.origin[1] as f32 / fg_ch; + let ang = angle_deg.to_radians(); + let (ca, sa) = (ang.cos(), ang.sin()); + let mut fg_x0 = f32::INFINITY; + let mut fg_x1 = f32::NEG_INFINITY; + let mut fg_y0 = f32::INFINITY; + let mut fg_y1 = f32::NEG_INFINITY; + for &(fu, fv) in &[(u0, v0), (u1, v0), (u0, v1), (u1, v1)] { + let fu = if flip_h > 0.5 { 1.0 - fu } else { fu }; + let fv = if flip_v > 0.5 { 1.0 - fv } else { fv }; + let rx = (fu - 0.5) * fg_cw * eff_size; + let ry = (fv - 0.5) * fg_ch * eff_size; + let dx = rx * ca - ry * sa; + let dy = rx * sa + ry * ca; + let px = center[0] as f32 * bg_cw + dx; + let py = (1.0 - center[1] as f32) * bg_ch - dy; + fg_x0 = fg_x0.min(px); + fg_x1 = fg_x1.max(px); + fg_y0 = fg_y0.min(py); + fg_y1 = fg_y1.max(py); + } + let max_pad = 512_i32; + let ux0 = if fg_x0 < bg_x0 as f32 - 0.5 { + bg_x0.min((fg_x0.floor() as i32 - 2).max(-max_pad)) + } else { + bg_x0 + }; + let uy0 = if fg_y0 < bg_y0 as f32 - 0.5 { + bg_y0.min((fg_y0.floor() as i32 - 2).max(-max_pad)) + } else { + bg_y0 + }; + let ux1 = if fg_x1 > bg_x1 as f32 + 0.5 { + bg_x1.max((fg_x1.ceil() as i32 + 2).min(bg.canvas_size[0] as i32 + max_pad)) + } else { + bg_x1 + }; + let uy1 = if fg_y1 > bg_y1 as f32 + 0.5 { + bg_y1.max((fg_y1.ceil() as i32 + 2).min(bg.canvas_size[1] as i32 + max_pad)) + } else { + bg_y1 + }; + let uw = (ux1 - ux0).max(1) as u32; + let uh = (uy1 - uy0).max(1) as u32; + if uw <= 4096 && uh <= 4096 && (ux0 != bg_x0 || uy0 != bg_y0 || uw != bg.size[0] || uh != bg.size[1]) { + dst_origin = [ux0, uy0]; + dst_size = [uw, uh]; + } + } + let dst_has_dod = dst_origin != [0, 0] || dst_size != bg.canvas_size; + let mut u = UniformParams::default(); - u.p[0] = [center[0] as f32, center[1] as f32, size_s, angle_deg.to_radians()]; + u.p[0] = [center[0] as f32, center[1] as f32, eff_size, angle_deg.to_radians()]; u.p[1] = [blend, gain, mode_id, edges]; u.p[2] = [flip_h, flip_v, nearest, op_id]; u.p[3] = [ @@ -1539,20 +1648,25 @@ impl Engine { fg.canvas_size[1] as f32, ]; } - if bg.has_dod() { + if dst_has_dod { u.p[5] = [ - bg.origin[0] as f32, - bg.origin[1] as f32, + dst_origin[0] as f32, + dst_origin[1] as f32, bg.canvas_size[0] as f32, bg.canvas_size[1] as f32, ]; } - u.p[6] = [burn_in, sub_add, 0.0, 0.0]; + u.p[6] = [ + burn_in, + sub_add, + (bg.origin[0] - dst_origin[0]) as f32, + (bg.origin[1] - dst_origin[1]) as f32, + ]; let key = self.make_key( node, "Merge", - bg.size, + dst_size, &[bg.content_hash, fg.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..7]), ); @@ -1563,7 +1677,8 @@ impl Engine { stats.cache_misses += 1; stats.nodes_evaluated += 1; - let dst = self.alloc_tex_dod(bg.size, bg.origin, bg.canvas_size, bg.depth.max(fg.depth), key); + let mut dst = self.alloc_tex_dod(dst_size, dst_origin, bg.canvas_size, bg.depth.max(fg.depth), key); + dst.tex_scale = bg.tex_scale; let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); self.dispatch_op(enc, ShaderOp::Merge, &bg.view, &fg.view, mv, &dst, &u); self.cache.insert(key, dst.clone(), node.id, frame_i); @@ -1740,6 +1855,7 @@ impl Engine { if blend <= 1e-6 { return src; } + let src = self.crop_to_canvas(enc, src); let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); @@ -1776,7 +1892,7 @@ impl Engine { } stats.cache_misses += 1; stats.nodes_evaluated += 1; - let dst = self.alloc_tex(src.size, src.depth, key); + let dst = self.alloc_tex_like(&src, src.depth, key); let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); self.dispatch_op(enc, ShaderOp::Bc, &src.view, &self.dummy.view, mv, &dst, &u); self.cache.insert(key, dst.clone(), node.id, frame_i); @@ -1801,6 +1917,7 @@ impl Engine { if blend <= 1e-6 { return src; } + let src = self.crop_to_canvas(enc, src); let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); @@ -1823,16 +1940,80 @@ impl Engine { blend, if mask.is_some() { 1.0 } else { 0.0 }, ]; - u.p[3] = [if mask_inv { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0]; + // Fusion ColorCorrector TintMode: 0 = RGB cube tilt matrix, 1 = additive+luma tint, 2 (default when omitted) = luma-weighted tint. + let tint_mode = comp.eval_number(node, "TintMode", time, 2.0, &self.expr) as f32; - let key = self.make_key(node, "CC", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..4])); + // Shadows (2), Midtones (3), Highlights (4) wheels & LGG + u.p[4] = [ + comp.eval_number(node, "WheelHue2", time, 0.0, &self.expr) as f32, + comp.eval_number(node, "WheelSaturation2", time, 1.0, &self.expr) as f32, + comp.eval_number(node, "WheelTintAngle2", time, 0.0, &self.expr) as f32, + comp.eval_number(node, "WheelTintLength2", time, 0.0, &self.expr) as f32, + ]; + u.p[5] = [ + comp.eval_number(node, "ShadowsRGBGain", time, 1.0, &self.expr) as f32, + comp.eval_number(node, "ShadowsRGBLift", time, 0.0, &self.expr) as f32, + comp.eval_number(node, "ShadowsRGBGamma", time, 1.0, &self.expr) as f32, + comp.eval_number(node, "ShadowsRGBContrast", time, 1.0, &self.expr) as f32, + ]; + u.p[6] = [ + comp.eval_number(node, "WheelHue3", time, 0.0, &self.expr) as f32, + comp.eval_number(node, "WheelSaturation3", time, 1.0, &self.expr) as f32, + comp.eval_number(node, "WheelTintAngle3", time, 0.0, &self.expr) as f32, + comp.eval_number(node, "WheelTintLength3", time, 0.0, &self.expr) as f32, + ]; + u.p[7] = [ + comp.eval_number(node, "MidtonesRGBGain", time, 1.0, &self.expr) as f32, + comp.eval_number(node, "MidtonesRGBLift", time, 0.0, &self.expr) as f32, + comp.eval_number(node, "MidtonesRGBGamma", time, 1.0, &self.expr) as f32, + comp.eval_number(node, "MidtonesRGBContrast", time, 1.0, &self.expr) as f32, + ]; + u.p[8] = [ + comp.eval_number(node, "WheelHue4", time, 0.0, &self.expr) as f32, + comp.eval_number(node, "WheelSaturation4", time, 1.0, &self.expr) as f32, + comp.eval_number(node, "WheelTintAngle4", time, 0.0, &self.expr) as f32, + comp.eval_number(node, "WheelTintLength4", time, 0.0, &self.expr) as f32, + ]; + u.p[9] = [ + comp.eval_number(node, "HighlightsRGBGain", time, 1.0, &self.expr) as f32, + comp.eval_number(node, "HighlightsRGBLift", time, 0.0, &self.expr) as f32, + comp.eval_number(node, "HighlightsRGBGamma", time, 1.0, &self.expr) as f32, + comp.eval_number(node, "HighlightsRGBContrast", time, 1.0, &self.expr) as f32, + ]; + u.p[10] = [ + comp.eval_number(node, "ShadowsRGBBrightness", time, 0.0, &self.expr) as f32, + comp.eval_number(node, "MidtonesRGBBrightness", time, 0.0, &self.expr) as f32, + comp.eval_number(node, "HighlightsRGBBrightness", time, 0.0, &self.expr) as f32, + 0.0, + ]; + let wheel_is_active = |w: [f32; 4], lgg: [f32; 4], b: f32| -> bool { + w[0].abs() > 1e-5 + || (w[1] - 1.0).abs() > 1e-5 + || w[3].abs() > 1e-5 + || (lgg[0] - 1.0).abs() > 1e-5 + || lgg[1].abs() > 1e-5 + || (lgg[2] - 1.0).abs() > 1e-5 + || (lgg[3] - 1.0).abs() > 1e-5 + || b.abs() > 1e-5 + }; + let has_smh = wheel_is_active(u.p[4], u.p[5], u.p[10][0]) + || wheel_is_active(u.p[6], u.p[7], u.p[10][1]) + || wheel_is_active(u.p[8], u.p[9], u.p[10][2]); + u.p[3] = [ + if mask_inv { 1.0 } else { 0.0 }, + tint_mode, + if has_smh { 1.0 } else { 0.0 }, + 0.0, + ]; + + let key = self.make_key(node, "CC", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..11])); 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 dst = self.alloc_tex(src.size, src.depth, key); + let dst = self.alloc_tex_like(&src, src.depth, key); let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); self.dispatch_op(enc, ShaderOp::Cc, &src.view, &self.dummy.view, mv, &dst, &u); self.cache.insert(key, dst.clone(), node.id, frame_i); @@ -1872,7 +2053,7 @@ impl Engine { } stats.cache_misses += 1; stats.nodes_evaluated += 1; - let dst = self.alloc_tex(src.size, src.depth, key); + let dst = self.alloc_tex_like(&src, src.depth, key); let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); self.dispatch_op(enc, ShaderOp::LumaKey, &src.view, &self.dummy.view, mv, &dst, &u); self.cache.insert(key, dst.clone(), node.id, frame_i); @@ -1903,7 +2084,7 @@ impl Engine { let y_raw = if lock_xy { x_raw } else { - comp.eval_number(node, "YBlurSize", time, x_raw as f64, &self.expr) as f32 + comp.eval_number(node, "YBlurSize", time, 1.0, &self.expr) as f32 }; let rx = x_raw * scale_ref * gauss_k; let ry = y_raw * scale_ref * gauss_k; @@ -1925,7 +2106,33 @@ impl Engine { stats.cache_misses += 1; stats.nodes_evaluated += 1; - let dst = self.alloc_tex_dod(src.size, src.origin, src.canvas_size, src.depth, key); + // When ClippingMode = "None" on an unmasked full-blend Blur, Fusion expands the DoD so the + // outer half of the Gaussian/Box falloff survives beyond the frame border for downstream Merges! + let expand_dod = clamp_edges < 0.5 && mask.is_none() && blend >= 0.999; + let (work_src, out_origin) = if expand_dod { + let pad_x = if rx >= 0.25 { (rx * 1.5).ceil().min(384.0) as u32 } else { 0 }; + let pad_y = if ry >= 0.25 { (ry * 1.5).ceil().min(384.0) as u32 } else { 0 }; + if pad_x > 0 || pad_y > 0 { + let exp_w = (src.size[0] + pad_x * 2).min(8192); + let exp_h = (src.size[1] + pad_y * 2).min(8192); + let actual_px = (exp_w.saturating_sub(src.size[0])) / 2; + let actual_py = (exp_h.saturating_sub(src.size[1])) / 2; + let exp_origin = [src.origin[0] - actual_px as i32, src.origin[1] - actual_py as i32]; + let padded = self.alloc_tex_dod([exp_w, exp_h], exp_origin, src.canvas_size, src.depth, 0); + let mut u_pad = UniformParams::default(); + u_pad.p[0] = [-100.0, -100.0, 100.0, 100.0]; + u_pad.p[1] = [exp_origin[0] as f32, exp_origin[1] as f32, src.canvas_size[0].max(1) as f32, src.canvas_size[1].max(1) as f32]; + u_pad.p[2] = [src.origin[0] as f32, src.origin[1] as f32, src.size[0] as f32, src.size[1] as f32]; + self.dispatch_op(enc, ShaderOp::SetDomain, &src.view, &self.dummy.view, &self.dummy.view, &padded, &u_pad); + (padded, exp_origin) + } else { + (src.clone(), src.origin) + } + } else { + (src.clone(), src.origin) + }; + + let dst = self.alloc_tex_dod(work_src.size, out_origin, src.canvas_size, src.depth, key); // Fast mode (`!self.hiq`): downsample large blurs to 1/2 or 1/4 pyramid level for 4-16x speedup! let down = if self.hiq { 1u32 @@ -1938,14 +2145,14 @@ impl Engine { }; if down > 1 { - let work_size = [(src.size[0] / down).max(1), (src.size[1] / down).max(1)]; + let work_size = [(work_src.size[0] / down).max(1), (work_src.size[1] / down).max(1)]; let small = self.alloc_tex(work_size, src.depth, 0); let tmp = self.alloc_tex(work_size, src.depth, 0); let small_blur = self.alloc_tex(work_size, src.depth, 0); let mut u_blit = UniformParams::default(); u_blit.p[0] = [1.0, 1.0, 0.0, 0.0]; - self.dispatch_op(enc, ShaderOp::DisplayBlit, &src.view, &self.dummy.view, &self.dummy.view, &small, &u_blit); + self.dispatch_op(enc, ShaderOp::DisplayBlit, &work_src.view, &self.dummy.view, &self.dummy.view, &small, &u_blit); let mut uh = UniformParams::default(); uh.p[0] = [1.0, 0.0, rx / down as f32, mode]; @@ -1963,23 +2170,23 @@ impl Engine { let mut um = UniformParams::default(); um.p[0] = [0.5, 0.5, 1.0, 0.0]; um.p[1] = [blend, 1.0, 0.0, 0.0]; - um.p[3] = [if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }, src.size[0] as f32, src.size[1] as f32]; + um.p[3] = [if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }, work_src.size[0] as f32, work_src.size[1] as f32]; let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); - self.dispatch_op(enc, ShaderOp::Merge, &src.view, &small_blur.view, mv, &dst, &um); + self.dispatch_op(enc, ShaderOp::Merge, &work_src.view, &small_blur.view, mv, &dst, &um); } } else { - let tmp = self.alloc_tex(src.size, src.depth, 0); + let tmp = self.alloc_tex(work_src.size, src.depth, 0); let mut uh = UniformParams::default(); uh.p[0] = [1.0, 0.0, rx, mode]; uh.p[1] = [1.0, 0.0, 0.0, clamp_edges]; - self.dispatch_op(enc, ShaderOp::Blur, &src.view, &self.dummy.view, &self.dummy.view, &tmp, &uh); + self.dispatch_op(enc, ShaderOp::Blur, &work_src.view, &self.dummy.view, &self.dummy.view, &tmp, &uh); let mut uv = UniformParams::default(); uv.p[0] = [0.0, 1.0, ry, mode]; uv.p[1] = [blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }, clamp_edges]; uv.p[2] = [1.0, 0.0, 0.0, 0.0]; // blend against original unblurred src in src_b! let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); - self.dispatch_op(enc, ShaderOp::Blur, &tmp.view, &src.view, mv, &dst, &uv); + self.dispatch_op(enc, ShaderOp::Blur, &tmp.view, &work_src.view, mv, &dst, &uv); } self.cache.insert(key, dst.clone(), node.id, frame_i); @@ -2004,6 +2211,7 @@ impl Engine { if blend <= 1e-6 { return src; } + let src = self.crop_to_canvas(enc, src); let kind = comp.eval_number(node, "Type", time, 0.0, &self.expr) as f32; let len = comp.eval_number(node, "Length", time, 0.02, &self.expr) as f32; let ang = (comp.eval_number(node, "Angle", time, 0.0, &self.expr) as f32).to_radians(); @@ -2028,7 +2236,7 @@ impl Engine { } stats.cache_misses += 1; stats.nodes_evaluated += 1; - let dst = self.alloc_tex(src.size, src.depth, key); + let dst = self.alloc_tex_like(&src, src.depth, key); let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); self.dispatch_op(enc, ShaderOp::DirBlur, &src.view, &self.dummy.view, mv, &dst, &u); self.cache.insert(key, dst.clone(), node.id, frame_i); @@ -2053,6 +2261,7 @@ impl Engine { if blend <= 1e-6 { return src; } + let src = self.crop_to_canvas(enc, src); let is_soft_glow = node.kind == "SoftGlow"; // Fusion SoftGlow/Glow sizes are in 720px-reference pixels; Glow's Gaussian kernel is // slightly tighter (~0.86x) than SoftGlow's (~1.00x). @@ -2179,6 +2388,7 @@ impl Engine { if blend <= 1e-6 { return src; } + let src = self.crop_to_canvas(enc, src); let prev_sz = self.mask_target_size; self.mask_target_size = Some(src.size); let glow_mask = node @@ -2355,7 +2565,8 @@ impl Engine { stats.cache_misses += 1; stats.nodes_evaluated += 1; let tmp = self.alloc_tex(src.size, src.depth, 0); - let dst = self.alloc_tex_dod(src.size, src.origin, src.canvas_size, src.depth, key); + let mut dst = self.alloc_tex_dod(src.size, src.origin, src.canvas_size, src.depth, key); + dst.tex_scale = src.tex_scale; let mut uh = UniformParams::default(); uh.p[0] = [1.0, 0.0, radius, mode]; uh.p[1] = [1.0, 0.0, 0.0, 0.0]; @@ -2386,8 +2597,10 @@ impl Engine { // Cap giant procedural sky-dome FastNoise textures (e.g. 11520x4000) to 8192 in HiQ / 4096 in Fast let cap = if self.hiq { 8192 } else { 4096 }; let max_dim = size[0].max(size[1]); + let mut tex_scale = 1.0_f32; if max_dim > cap { let scale = cap as f32 / max_dim as f32; + tex_scale = scale; size = [((size[0] as f32 * scale).round() as u32).max(1), ((size[1] as f32 * scale).round() as u32).max(1)]; } @@ -2420,7 +2633,8 @@ impl Engine { comp.eval_number(node, "Color2Blue", time, 1.0, &self.expr) as f32, comp.eval_number(node, "Color2Alpha", time, 1.0, &self.expr) as f32, ]; - let grad = comp.eval_gradient(node, "Gradient", time); + let noise_type = comp.eval_number(node, "Type", time, 0.0, &self.expr).round() as i32; + let grad = if noise_type == 1 { comp.eval_gradient(node, "Gradient", time) } else { None }; // Bake high-precision 256x1 RGBA gradient LUT so sharp thresholds (e.g. 0.95..0.96 stars) are exact! let mut grad_bytes = [0u8; 256 * 4]; @@ -2449,7 +2663,7 @@ impl Engine { let mut u = UniformParams::default(); u.p[0] = [x_scale, y_scale, detail, contrast]; u.p[1] = [brightness, seethe, disc, center[0] as f32]; - u.p[2] = [center[1] as f32, angle, inverted, 1.0]; + u.p[2] = [center[1] as f32, angle, inverted, if noise_type == 1 { 2.0 } else { 1.0 }]; let key = self.make_key(node, "FastNoise", size, &[grad_hash], bytemuck::cast_slice(&u.p[..3])); if let Some(hit) = self.cache.get(key, node.id, frame_i) { @@ -2465,7 +2679,8 @@ impl Engine { wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(256 * 4), rows_per_image: Some(1) }, wgpu::Extent3d { width: 256, height: 1, depth_or_array_layers: 1 }, ); - let dst = self.alloc_tex(size, self.node_depth(comp, node, time, None), key); + let mut dst = self.alloc_tex(size, self.node_depth(comp, node, time, None), key); + dst.tex_scale = tex_scale; self.dispatch_op(enc, ShaderOp::FastNoise, &self.dummy.view, &lut_tex.view, &self.dummy.view, &dst, &u); self.cache.insert(key, dst.clone(), node.id, frame_i); dst @@ -2488,7 +2703,9 @@ impl Engine { let Some(fg_id) = node.connected_node("Foreground").and_then(|s| comp.find_node(s)) else { return src; }; + let src = self.crop_to_canvas(enc, src); let fg = self.eval_node(comp, fg_id, time, enc, visiting, stats); + let fg = self.crop_to_canvas(enc, fg); let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); @@ -2522,13 +2739,57 @@ impl Engine { } stats.cache_misses += 1; stats.nodes_evaluated += 1; - let dst = self.alloc_tex(src.size, src.depth, key); + let dst = self.alloc_tex_like(&src, src.depth, key); let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); self.dispatch_op(enc, ShaderOp::Displace, &src.view, &fg.view, mv, &dst, &u); self.cache.insert(key, dst.clone(), node.id, frame_i); dst } + #[allow(clippy::too_many_arguments)] + fn eval_vortex( + &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) = node.connected_node("Input").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 angle_deg = comp.eval_number(node, "Angle", time, 0.0, &self.expr) as f32; + if blend <= 1e-6 || angle_deg.abs() <= 1e-5 { + return src; + } + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); + let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr); + let size = comp.eval_number(node, "Size", time, 0.5, &self.expr).max(1e-4) as f32; + let power = comp.eval_number(node, "Power", time, 5.0, &self.expr).max(0.0) as f32; + + let mut u = UniformParams::default(); + u.p[0] = [center[0] as f32, center[1] as f32, size * 0.5, angle_deg.to_radians()]; + u.p[1] = [power, blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }]; + + let key = self.make_key(node, "Vortex", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..2])); + 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 dst = self.alloc_tex_dod(src.size, src.origin, src.canvas_size, src.depth, key); + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.dispatch_op(enc, ShaderOp::Vortex, &src.view, &self.dummy.view, mv, &dst, &u); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + fn paint_mode_id(node: &Node) -> f32 { match node.static_str("PaintMode").unwrap_or("Merge") { "Add" => 1.0, @@ -2542,6 +2803,77 @@ impl Engine { } } + /// Runs Fusion-calibrated separable mask `SoftEdge` blur with progressive 2x downsampling so + /// large `SoftEdge` values (up to 0.5+ / ~960px at 1080p) neither alias nor hit the 64-tap cap. + fn blur_mask_texture( + &self, + enc: &mut wgpu::CommandEncoder, + raw: &CachedTexture, + soft_px: f32, + is_box: bool, + clamp_edges: f32, + ) -> CachedTexture { + let size = raw.size; + let mode = if is_box { 1.0 } else { 0.0 }; + // Fusion mask Box filter has half-width ~0.707 * soft_px (1/sqrt(2)) vs Gaussian radius = soft_px. + let eff_r = if is_box { soft_px * 0.707 } else { soft_px }; + // Keep per-level radius <= 48px (16px in Fast mode) via progressive 2x pyramid steps so thin shapes don't alias. + let max_level_r = if self.hiq { 48.0 } else { 16.0 }; + let mut levels = 0u32; + let mut r_s = eff_r; + let mut ws = size; + while r_s > max_level_r && ws[0] >= 16 && ws[1] >= 16 && levels < 5 { + levels += 1; + r_s *= 0.5; + ws = [(ws[0] / 2).max(1), (ws[1] / 2).max(1)]; + } + + let mut u_blit = UniformParams::default(); + u_blit.p[0] = [1.0, 1.0, 0.0, 0.0]; + let mut cur = raw.clone(); + if levels > 0 { + let mut cur_sz = size; + for _ in 0..levels { + cur_sz = [(cur_sz[0] / 2).max(1), (cur_sz[1] / 2).max(1)]; + let next = create_texture(&self.device, cur_sz, 0); + self.dispatch_op(enc, ShaderOp::DisplayBlit, &cur.view, &self.dummy.view, &self.dummy.view, &next, &u_blit); + cur = next; + } + } + + let tmp1 = create_texture(&self.device, cur.size, 0); + let tmp2 = create_texture(&self.device, cur.size, 0); + let mut uh = UniformParams::default(); + uh.p[0] = [1.0, 0.0, r_s, mode]; + uh.p[1] = [1.0, 0.0, 0.0, clamp_edges]; + self.dispatch_op(enc, ShaderOp::Blur, &cur.view, &self.dummy.view, &self.dummy.view, &tmp1, &uh); + let mut uv = UniformParams::default(); + uv.p[0] = [0.0, 1.0, r_s, mode]; + uv.p[1] = [1.0, 0.0, 0.0, clamp_edges]; + self.dispatch_op(enc, ShaderOp::Blur, &tmp1.view, &self.dummy.view, &self.dummy.view, &tmp2, &uv); + + if levels > 0 { + let up = create_texture(&self.device, size, 0); + self.dispatch_op(enc, ShaderOp::DisplayBlit, &tmp2.view, &self.dummy.view, &self.dummy.view, &up, &u_blit); + up + } else { + tmp2 + } + } + + fn mask_filter_is_box(node: &Node) -> bool { + node.static_str("Filter").unwrap_or("Fast Gaussian").eq_ignore_ascii_case("Box") + } + + fn mask_clamp_edges(node: &Node) -> f32 { + // Fusion masks default to ClippingMode = "Frame" (clamp to border); "None" pads with 0 outside frame. + if node.static_str("ClippingMode").unwrap_or("Frame").eq_ignore_ascii_case("None") { + 0.0 + } else { + 1.0 + } + } + #[allow(clippy::too_many_arguments)] fn eval_mask_shape( &mut self, @@ -2573,10 +2905,14 @@ impl Engine { let mw = comp.eval_number(node, "Width", time, 0.5, &self.expr) as f32; let mh = comp.eval_number(node, "Height", time, 0.5, &self.expr) as f32; let angle = (comp.eval_number(node, "Angle", time, 0.0, &self.expr) as f32).to_radians(); - let soft = comp.eval_number(node, "SoftEdge", time, 0.0, &self.expr) as f32; + let soft = comp.eval_number(node, "SoftEdge", time, 0.0, &self.expr).max(0.0) as f32; let corner = comp.eval_number(node, "CornerRadius", time, 0.0, &self.expr) as f32; let invert = comp.eval_number(node, "Invert", time, 0.0, &self.expr) as f32; let level = comp.eval_number(node, "Level", time, 1.0, &self.expr) as f32; + let border_w = comp.eval_number(node, "BorderWidth", time, 0.0, &self.expr) as f32; + let solid = if comp.eval_number(node, "Solid", time, 1.0, &self.expr) > 0.5 { 1.0 } else { 0.0 }; + let is_box = Self::mask_filter_is_box(node); + let clamp_edges = Self::mask_clamp_edges(node); let (prev_mask, _) = self.eval_mask_input_sized(comp, node, time, Some(size), enc, visiting, stats); let prev_hash = prev_mask.as_ref().map_or(0, |m| m.content_hash); let paint_mode = Self::paint_mode_id(node); @@ -2585,8 +2921,9 @@ impl Engine { u.p[0] = [center[0] as f32, center[1] as f32, mw, mh]; u.p[1] = [angle, soft, corner, invert]; u.p[2] = [shape as f32, level, if prev_mask.is_some() { 1.0 } else { 0.0 }, paint_mode]; + u.p[3] = [border_w, solid, if is_box { 1.0 } else { 0.0 }, clamp_edges]; - let key = self.make_key(node, "MaskShape", size, &[prev_hash], bytemuck::cast_slice(&u.p[..3])); + let key = self.make_key(node, "MaskShape", size, &[prev_hash], bytemuck::cast_slice(&u.p[..4])); if let Some(hit) = self.cache.get(key, node.id, frame_i) { stats.cache_hits += 1; return hit; @@ -2595,58 +2932,14 @@ impl Engine { stats.nodes_evaluated += 1; let mv = prev_mask.as_ref().map_or(&self.dummy.view, |m| &m.view); let soft_px = soft * size[0] as f32; - let dst = if soft_px >= 0.75 { - // Fusion Mask SoftEdge runs a true 2D Gaussian blur (sigma ~ 0.45 * SoftEdge * width) - // over the sharp shape before Invert/Level/PaintMode combine! + let dst = if soft_px >= 0.5 { let raw = create_texture(&self.device, size, 0); let mut u_raw = u; u_raw.p[1] = [angle, 0.0, corner, 0.0]; u_raw.p[2] = [shape as f32, 1.0, 0.0, 0.0]; self.dispatch_op(enc, ShaderOp::MaskShape, &self.dummy.view, &self.dummy.view, &self.dummy.view, &raw, &u_raw); - // Downsample for large SoftEdge radii (>24px or Fast mode) so 2048x2048 soft masks stay <0.5ms! - let down = if !self.hiq && soft_px >= 12.0 { - 4u32 - } else if soft_px >= 48.0 { - 4u32 - } else if soft_px >= 20.0 { - 2u32 - } else { - 1u32 - }; - let blurred = if down > 1 { - let ws = [(size[0] / down).max(1), (size[1] / down).max(1)]; - let small = create_texture(&self.device, ws, 0); - let tmp1 = create_texture(&self.device, ws, 0); - let tmp2 = create_texture(&self.device, ws, 0); - let up = create_texture(&self.device, size, 0); - let mut ub = UniformParams::default(); - ub.p[0] = [1.0, 1.0, 0.0, 0.0]; - self.dispatch_op(enc, ShaderOp::DisplayBlit, &raw.view, &self.dummy.view, &self.dummy.view, &small, &ub); - let r_s = soft_px / down as f32; - let mut uh = UniformParams::default(); - uh.p[0] = [1.0, 0.0, r_s, 0.0]; - uh.p[1] = [1.0, 0.0, 0.0, 0.0]; - self.dispatch_op(enc, ShaderOp::Blur, &small.view, &self.dummy.view, &self.dummy.view, &tmp1, &uh); - let mut uv = UniformParams::default(); - uv.p[0] = [0.0, 1.0, r_s, 0.0]; - uv.p[1] = [1.0, 0.0, 0.0, 0.0]; - self.dispatch_op(enc, ShaderOp::Blur, &tmp1.view, &self.dummy.view, &self.dummy.view, &tmp2, &uv); - self.dispatch_op(enc, ShaderOp::DisplayBlit, &tmp2.view, &self.dummy.view, &self.dummy.view, &up, &ub); - up - } else { - let tmp1 = create_texture(&self.device, size, 0); - let tmp2 = create_texture(&self.device, size, 0); - let mut uh = UniformParams::default(); - uh.p[0] = [1.0, 0.0, soft_px, 0.0]; - uh.p[1] = [1.0, 0.0, 0.0, 0.0]; - self.dispatch_op(enc, ShaderOp::Blur, &raw.view, &self.dummy.view, &self.dummy.view, &tmp1, &uh); - let mut uv = UniformParams::default(); - uv.p[0] = [0.0, 1.0, soft_px, 0.0]; - uv.p[1] = [1.0, 0.0, 0.0, 0.0]; - self.dispatch_op(enc, ShaderOp::Blur, &tmp1.view, &self.dummy.view, &self.dummy.view, &tmp2, &uv); - tmp2 - }; + let blurred = self.blur_mask_texture(enc, &raw, soft_px, is_box, clamp_edges); let out_tex = create_texture(&self.device, size, key); let mut uc = UniformParams::default(); @@ -2687,6 +2980,8 @@ impl Engine { let soft = comp.eval_number(node, "SoftEdge", time, 0.0, &self.expr).max(0.0) as f32; let invert = comp.eval_number(node, "Invert", time, 0.0, &self.expr) > 0.5; let level = comp.eval_number(node, "Level", time, 1.0, &self.expr) as f32; + let is_box = Self::mask_filter_is_box(node); + let clamp_edges = Self::mask_clamp_edges(node); let (prev_mask, _) = self.eval_mask_input_sized(comp, node, time, Some(size), enc, visiting, stats); let prev_hash = prev_mask.as_ref().map_or(0, |m| m.content_hash); let paint_mode = Self::paint_mode_id(node); @@ -2713,7 +3008,7 @@ impl Engine { &[] }; - let mut hash_floats = Vec::with_capacity(6 + points.len() * 6); + let mut hash_floats = Vec::with_capacity(8 + points.len() * 6); hash_floats.extend_from_slice(&[ center[0] as f32, center[1] as f32, @@ -2721,6 +3016,8 @@ impl Engine { if invert { 1.0 } else { 0.0 }, level, paint_mode, + if is_box { 1.0 } else { 0.0 }, + clamp_edges, ]); for p in points { hash_floats.extend_from_slice(&[p.x as f32, p.y as f32, p.lx as f32, p.ly as f32, p.rx as f32, p.ry as f32]); @@ -2733,8 +3030,8 @@ impl Engine { stats.cache_misses += 1; stats.nodes_evaluated += 1; - let soft_px = soft * size[0] as f32 * 1.14; - let need_post = soft_px >= 0.35 || prev_mask.is_some(); + let soft_px = soft * size[0] as f32; + let need_post = soft_px >= 0.5 || prev_mask.is_some(); let pixels = rasterize_polyline_mask( size, points, @@ -2750,18 +3047,8 @@ impl Engine { wgpu::Extent3d { width: size[0], height: size[1], depth_or_array_layers: 1 }, ); let tex = if need_post { - let blurred = if soft_px >= 0.35 { - let tmp1 = create_texture(&self.device, size, 0); - let tmp2 = create_texture(&self.device, size, 0); - let mut uh = UniformParams::default(); - uh.p[0] = [1.0, 0.0, soft_px, 0.0]; - uh.p[1] = [1.0, 0.0, 0.0, 0.0]; - self.dispatch_op(enc, ShaderOp::Blur, &raw_tex.view, &self.dummy.view, &self.dummy.view, &tmp1, &uh); - let mut uv = UniformParams::default(); - uv.p[0] = [0.0, 1.0, soft_px, 0.0]; - uv.p[1] = [1.0, 0.0, 0.0, 0.0]; - self.dispatch_op(enc, ShaderOp::Blur, &tmp1.view, &self.dummy.view, &self.dummy.view, &tmp2, &uv); - tmp2 + let blurred = if soft_px >= 0.5 { + self.blur_mask_texture(enc, &raw_tex, soft_px, is_box, clamp_edges) } else { raw_tex }; @@ -2783,20 +3070,107 @@ impl Engine { tex } + #[allow(clippy::too_many_arguments)] fn eval_bitmap_mask( &mut self, comp: &Comp, node: &Node, time: f64, + frame_i: i64, + comp_dims: [u32; 2], enc: &mut wgpu::CommandEncoder, visiting: &mut HashSet<(NodeId, i64)>, stats: &mut EvalStats, ) -> CachedTexture { - if let Some(src_id) = node.connected_node("Image").and_then(|s| comp.find_node(s)) { - self.eval_node(comp, src_id, time, enc, visiting, stats) + let Some(src_id) = node.connected_node("Image").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 output_size_mode = node.static_str("OutputSize").unwrap_or("Default"); + let size = if output_size_mode == "Custom" { + let w = comp.eval_number(node, "MaskWidth", time, comp.width as f64, &self.expr) as u32; + let h = comp.eval_number(node, "MaskHeight", time, comp.height as f64, &self.expr) as u32; + if w >= 16 && h >= 16 { self.scaled_dims(w, h) } else { comp_dims } + } else if let Some(ts) = self.mask_target_size { + ts + } else if node.inputs.contains_key("MaskWidth") || node.inputs.contains_key("MaskHeight") { + let w = comp.eval_number(node, "MaskWidth", time, comp.width as f64, &self.expr) as u32; + let h = comp.eval_number(node, "MaskHeight", time, comp.height as f64, &self.expr) as u32; + if w >= 16 && h >= 16 { self.scaled_dims(w, h) } else { src.canvas_size } } else { - self.dummy.clone() + src.canvas_size + }; + + let ch_id: f32 = match node.static_str("Channel").unwrap_or("Alpha") { + "Luminance" => 1.0, + "Red" => 2.0, + "Green" => 3.0, + "Blue" => 4.0, + "Saturation" => 5.0, + "Lightness" => 6.0, + "Hue" => 7.0, + _ => 0.0, // Alpha (Fusion default) + }; + let low = comp.eval_number(node, "Low", time, 0.0, &self.expr) as f32; + let high = comp.eval_number(node, "High", time, 1.0, &self.expr) as f32; + let soft = comp.eval_number(node, "SoftEdge", time, 0.0, &self.expr).max(0.0) as f32; + let invert = if comp.eval_number(node, "Invert", time, 0.0, &self.expr) > 0.5 { 1.0 } else { 0.0 }; + let level = comp.eval_number(node, "Level", time, 1.0, &self.expr) as f32; + let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr); + let fit_stretch = if comp.eval_number(node, "FitInput", time, 0.0, &self.expr) > 0.5 { 1.0 } else { 0.0 }; + let is_box = Self::mask_filter_is_box(node); + let clamp_edges = Self::mask_clamp_edges(node); + let (prev_mask, _) = self.eval_mask_input_sized(comp, node, time, Some(size), enc, visiting, stats); + let prev_hash = prev_mask.as_ref().map_or(0, |m| m.content_hash); + let paint_mode = Self::paint_mode_id(node); + + let key = self.make_key( + node, + "BitmapMask", + size, + &[src.content_hash, prev_hash], + &[ + ch_id, low, high, soft, invert, level, + center[0] as f32, center[1] as f32, fit_stretch, + if is_box { 1.0 } else { 0.0 }, clamp_edges, paint_mode, + ], + ); + 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 soft_px = soft * size[0] as f32; + let need_post = soft_px >= 0.5 || invert > 0.5 || (level - 1.0).abs() > 1e-4 || prev_mask.is_some(); + + let raw_tex = create_texture(&self.device, size, if need_post { 0 } else { key }); + let mut u = UniformParams::default(); + u.p[0] = [ch_id, low, high, fit_stretch]; + u.p[1] = [center[0] as f32, center[1] as f32, src.origin[0] as f32, src.origin[1] as f32]; + u.p[2] = [src.canvas_size[0] as f32, src.canvas_size[1] as f32, 0.0, 0.0]; + self.dispatch_op(enc, ShaderOp::BitmapMask, &src.view, &self.dummy.view, &self.dummy.view, &raw_tex, &u); + + let out_tex = if need_post { + let blurred = if soft_px >= 0.5 { + self.blur_mask_texture(enc, &raw_tex, soft_px, is_box, clamp_edges) + } else { + raw_tex + }; + let combined = create_texture(&self.device, size, key); + let mut uc = UniformParams::default(); + uc.p[0] = [paint_mode, invert, level, if prev_mask.is_some() { 1.0 } else { 0.0 }]; + let mv = prev_mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.dispatch_op(enc, ShaderOp::MaskCombine, &blurred.view, &self.dummy.view, mv, &combined, &uc); + combined + } else { + raw_tex + }; + + self.cache.insert(key, out_tex.clone(), node.id, frame_i); + out_tex } fn eval_text_plus( @@ -3248,7 +3622,7 @@ impl Engine { let dil_h = self.alloc_tex(src.size, src.depth, 0); let dil_v = self.alloc_tex(src.size, src.depth, 0); let tinted = self.alloc_tex(src.size, src.depth, 0); - let dst = self.alloc_tex(src.size, src.depth, key); + let dst = self.alloc_tex_like(&src, src.depth, key); let u0 = UniformParams::default(); let mut dh = UniformParams::default(); @@ -3372,6 +3746,7 @@ impl Engine { if blend <= 1e-6 { return src; } + let src = self.crop_to_canvas(enc, src); let proc_r = comp.eval_number(node, "ProcessRed", time, 1.0, &self.expr) as f32; let proc_g = comp.eval_number(node, "ProcessGreen", time, 1.0, &self.expr) as f32; let proc_b = comp.eval_number(node, "ProcessBlue", time, 1.0, &self.expr) as f32; @@ -3414,6 +3789,7 @@ impl Engine { if blend <= 1e-6 { return src; } + let src = self.crop_to_canvas(enc, src); let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); @@ -3473,6 +3849,7 @@ impl Engine { if blend <= 1e-6 { return src; } + let src = self.crop_to_canvas(enc, src); let prediv = comp.eval_number(node, "PreDividePostMultiply", time, 0.0, &self.expr) as f32; let ignore_trans = comp.eval_number(node, "IgnoreTransparent", time, 0.0, &self.expr) as f32; let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); @@ -3554,6 +3931,7 @@ impl Engine { if blend <= 1e-6 { return src; } + let src = self.crop_to_canvas(enc, src); let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); @@ -3679,7 +4057,7 @@ impl Engine { } else { bg.clone() }; - let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(bg.size), enc, visiting, stats); + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(bg.canvas_size), enc, visiting, stats); let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); let mut u = UniformParams::default(); u.p[0] = [op as f32, to_r as f32, to_g as f32, to_b as f32]; @@ -3692,14 +4070,17 @@ impl Engine { if fg.has_dod() { u.p[2] = [fg.origin[0] as f32, fg.origin[1] as f32, fg.canvas_size[0] as f32, fg.canvas_size[1] as f32]; } - let key = self.make_key(node, "ChannelBoolean", bg.size, &[bg.content_hash, fg.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..3])); + if bg.has_dod() { + u.p[3] = [bg.origin[0] as f32, bg.origin[1] as f32, bg.canvas_size[0] as f32, bg.canvas_size[1] as f32]; + } + let key = self.make_key(node, "ChannelBoolean", bg.size, &[bg.content_hash, fg.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..4])); 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 dst = self.alloc_tex(bg.size, bg.depth.max(fg.depth), key); + let dst = self.alloc_tex_like(&bg, bg.depth.max(fg.depth), key); let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); self.dispatch_op(enc, ShaderOp::ChannelBoolean, &bg.view, &fg.view, mv, &dst, &u); self.cache.insert(key, dst.clone(), node.id, frame_i); @@ -3724,6 +4105,7 @@ impl Engine { if blend <= 1e-6 { return src; } + let src = self.crop_to_canvas(enc, src); let map_space = |s: Option<&str>| -> f32 { match s.unwrap_or("NoChange") { "sRGB" => 1.0, @@ -3777,6 +4159,7 @@ impl Engine { if blend <= 1e-6 { return src; } + let src = self.crop_to_canvas(enc, src); let rx = (comp.eval_number(node, "XBlurSize", time, 1.0, &self.expr) as f32) * 2.0 / self.proxy_scale.max(1) as f32; let ry = (comp.eval_number(node, "YBlurSize", time, (rx * self.proxy_scale.max(1) as f32 / 2.0) as f64, &self.expr) as f32) * 2.0 / self.proxy_scale.max(1) as f32; let bmap = node @@ -4005,6 +4388,7 @@ impl Engine { if blend <= 1e-6 { return src; } + let src = self.crop_to_canvas(enc, src); let ftype = comp.eval_number(node, "FilterType", time, 0.0, &self.expr).round() as f32; let power = comp.eval_number(node, "Power", time, 1.0, &self.expr) as f32; let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); @@ -4100,6 +4484,7 @@ impl Engine { if blend <= 1e-6 { return src; } + let src = self.crop_to_canvas(enc, src); let prediv = comp.eval_number(node, "PreDividePostMultiply", time, 0.0, &self.expr) as f32; let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); @@ -4180,6 +4565,7 @@ impl Engine { if blend <= 1e-6 { return src; } + let src = self.crop_to_canvas(enc, src); let bg_r = comp.eval_number(node, "BackgroundRed", time, 0.0, &self.expr) as f32; let bg_g = comp.eval_number(node, "BackgroundGreen", time, 1.0, &self.expr) as f32; let bg_b = comp.eval_number(node, "BackgroundBlue", time, 0.0, &self.expr) as f32; @@ -4243,7 +4629,7 @@ impl Engine { if blend <= 1e-6 || mix_v <= 1e-6 { return bg; } - let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(bg.size), enc, visiting, stats); + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(bg.canvas_size), enc, visiting, stats); let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); let mut u = UniformParams::default(); u.p[0] = [mix_v, blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }]; @@ -4254,7 +4640,8 @@ impl Engine { } stats.cache_misses += 1; stats.nodes_evaluated += 1; - let dst = self.alloc_tex_dod(bg.size, bg.origin, bg.canvas_size, bg.depth.max(fg.depth), key); + let mut dst = self.alloc_tex_dod(bg.size, bg.origin, bg.canvas_size, bg.depth.max(fg.depth), key); + dst.tex_scale = bg.tex_scale; let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); self.dispatch_op(enc, ShaderOp::Dissolve, &bg.view, &fg.view, mv, &dst, &u); self.cache.insert(key, dst.clone(), node.id, frame_i); @@ -4279,6 +4666,7 @@ impl Engine { if blend <= 1e-6 { return src; } + let src = self.crop_to_canvas(enc, src); let offset = comp.eval_point(node, "ShadowOffset", time, [0.5, 0.5], &self.expr); let soft = comp.eval_number(node, "Softness", time, 0.0, &self.expr).max(0.0) as f32; let sh_r = comp.eval_number(node, "Red", time, 0.0, &self.expr) as f32; @@ -4398,6 +4786,7 @@ impl Engine { if blend <= 1e-6 { return src; } + let src = self.crop_to_canvas(enc, src); let bl = comp.eval_point(node, "BottomLeft", time, [0.0, 0.0], &self.expr); let br = comp.eval_point(node, "BottomRight", time, [1.0, 0.0], &self.expr); let tr = comp.eval_point(node, "TopRight", time, [1.0, 1.0], &self.expr); diff --git a/crates/engine/src/scene3d.rs b/crates/engine/src/scene3d.rs index b4c9bed427bd5166cb32c2264ae9f9301facec0f..d3a7101a011001f937aa0deb188f1eef5f2ec26f 100644 --- a/crates/engine/src/scene3d.rs +++ b/crates/engine/src/scene3d.rs @@ -628,7 +628,8 @@ pub fn collect_scene( } else { 24.302 }; - let gate_fit = node.static_str("ResolutionGateFit").unwrap_or("Inside"); + // Fusion Camera3D defaults ResolutionGateFit to "Height" (vertical AoV is preserved on square/tall renders) + let gate_fit = node.static_str("ResolutionGateFit").unwrap_or("Height"); let gate_aspect = (ap_w / ap_h.max(1e-4)).max(1e-4); let half_aov = (aov_deg.to_radians() * 0.5).tan(); @@ -684,7 +685,8 @@ pub fn collect_scene( let shape_name = node.static_str("Shape").unwrap_or("SurfacePlaneInputs"); let shape = match shape_name { "SurfaceSphereInputs" => ShapeKind::Sphere { - radius: comp.eval_number(node, "SurfaceSphereInputs.Radius", time, 0.5, expr) as f32, + // Fusion 21.1 Shape3D Sphere default Radius is 1.0 (verified via probe_moon_3d f00) + radius: comp.eval_number(node, "SurfaceSphereInputs.Radius", time, 1.0, expr) as f32, sub_base: comp.eval_number(node, "SurfaceSphereInputs.SubdivisionLevelBase", time, 32.0, expr).round() as u32, sub_height: comp.eval_number(node, "SurfaceSphereInputs.SubdivisionLevelHeight", time, 24.0, expr).round() as u32, }, @@ -712,7 +714,15 @@ pub fn collect_scene( let mat_node = node .connected_node("MaterialInput") .and_then(|s| comp.find_node(s)); - let (tex_node, diffuse_col, roughness) = resolve_material(comp, mat_node, time, expr); + let (tex_node, mut diffuse_col, roughness) = resolve_material(comp, mat_node, time, expr); + if mat_node.is_none() { + diffuse_col = [ + comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Red", time, 1.0, expr) as f32, + comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Green", time, 1.0, expr) as f32, + comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Blue", time, 1.0, expr) as f32, + comp.eval_number(node, "MtlStdInputs.Diffuse.Opacity", time, 1.0, expr) as f32, + ]; + } meshes.push(MeshInstance { world, shape, diff --git a/crates/engine/src/shaders.wgsl b/crates/engine/src/shaders.wgsl index f1102c139fe3a446ef786d3e05956e75776c8033..4326971277fcbb8922c3c26cc0e80e3241b50102 100644 --- a/crates/engine/src/shaders.wgsl +++ b/crates/engine/src/shaders.wgsl @@ -83,15 +83,21 @@ fn sample_edges(tex: texture_2d, fu: vec2, edges: i32) -> vec4 { return sample_dod_edges(tex, fu, edges, vec4(0.0)); } -fn read_mask(gid: vec2, dims: vec2, has_mask: f32, invert: f32) -> f32 { +fn read_mask_uv(uv: vec2, has_mask: f32, invert: f32) -> f32 { if (has_mask < 0.5) { return 1.0; } - let uv = (vec2(gid) + 0.5) / vec2(dims); - let m = textureSampleLevel(mask_tex, samp_lin, uv, 0.0).a; + var m = 0.0; + if (uv.x >= 0.0 && uv.x <= 1.0 && uv.y >= 0.0 && uv.y <= 1.0) { + m = textureSampleLevel(mask_tex, samp_lin, uv, 0.0).a; + } return select(m, 1.0 - m, invert > 0.5); } +fn read_mask(gid: vec2, dims: vec2, has_mask: f32, invert: f32) -> f32 { + return read_mask_uv((vec2(gid) + 0.5) / vec2(dims), has_mask, invert); +} + // ============================================================================ // 1. Background (Solid + Gradients) // p[0] = top_left rgba, p[1] = top_right rgba, p[2] = bottom_left rgba, p[3] = bottom_right rgba @@ -285,7 +291,13 @@ fn merge_op(@builtin(global_invocation_id) gid: vec3) { let bg_dims = select(vec2(dims), bg_dod.zw, has_bg_dod); let fg_dims = max(u.p[3].zw, vec2(1.0)); - let bg = textureLoad(src_a, vec2(gid.xy), 0); + let bg_off = vec2(i32(round(u.p[6].z)), i32(round(u.p[6].w))); + let bg_coord = vec2(gid.xy) - bg_off; + let bg_tex_dims = vec2(textureDimensions(src_a)); + var bg = vec4(0.0); + if (bg_coord.x >= 0 && bg_coord.y >= 0 && bg_coord.x < bg_tex_dims.x && bg_coord.y < bg_tex_dims.y) { + bg = textureLoad(src_a, bg_coord, 0); + } // If BG has expanded DoD, map output texel into logical BG canvas Fusion UV! let canvas_px = select( vec2(gid.xy) + vec2(0.5), @@ -314,7 +326,7 @@ fn merge_op(@builtin(global_invocation_id) gid: vec3) { if (u.p[2].y > 0.5) { fg_fu.y = 1.0 - fg_fu.y; } let fg = sample_dod_edges_mode(src_b, fg_fu, edges, u.p[4], nearest); - let mask = read_mask(gid.xy, dims, u.p[3].x, u.p[3].y); + let mask = read_mask_uv(canvas_px / bg_dims, u.p[3].x, u.p[3].y); let eff_blend = clamp(blend * mask, 0.0, 1.0); let op = i32(u.p[2].w + 0.5); // 0=Over, 1=Under, 2=In, 3=HeldOut, 4=Atop, 5=XOr @@ -482,11 +494,18 @@ fn bc_op(@builtin(global_invocation_id) gid: vec3) { // ============================================================================ -// 5. ColorCorrector (Lightness-preserving hue rotation + saturation + tint + LGG + contrast) -// p[0] = (hue_turns, sat, tint_angle_rad, tint_len) -// p[1] = (gain, lift, gamma, contrast) -// p[2] = (brightness, prediv, blend, has_mask) -// p[3] = (mask_invert, 0, 0, 0) +// 5. ColorCorrector (Master + Shadows/Midtones/Highlights wheels, TintMode 0 & 1, LGG) +// p[0] = (hue1, sat1, tint_angle1, tint_len1) +// p[1] = (gain1, lift1, gamma1, contrast1) +// p[2] = (brightness1, prediv, blend, has_mask) +// p[3] = (mask_invert, tint_mode, has_smh, 0) +// p[4] = (hue2, sat2, tint_angle2, tint_len2) // Shadows +// p[5] = (gain2, lift2, gamma2, contrast2) +// p[6] = (hue3, sat3, tint_angle3, tint_len3) // Midtones +// p[7] = (gain3, lift3, gamma3, contrast3) +// p[8] = (hue4, sat4, tint_angle4, tint_len4) // Highlights +// p[9] = (gain4, lift4, gamma4, contrast4) +// p[10] = (bright2, bright3, bright4, 0) // ============================================================================ fn rotate_hue_preserve_luma(c: vec3, angle: f32) -> vec3 { // Paul Haeberli luminance-preserving shear-rotate-unshear around (1,1,1) with Rec.601 weights. @@ -512,54 +531,120 @@ fn hsv_pure_hue(h_turns: f32) -> vec3 { return vec3(r, g, b); } -@compute @workgroup_size(8, 8) -fn cc_op(@builtin(global_invocation_id) gid: vec3) { - let dims = textureDimensions(dst_tex); - if (gid.x >= dims.x || gid.y >= dims.y) { return; } - let src = textureLoad(src_a, vec2(gid.xy), 0); - let hue_turns = u.p[0].x; - let sat = u.p[0].y; - let tint_turns = u.p[0].z; - let tint_len = u.p[0].w; - let gain = u.p[1].x; - let lift = u.p[1].y; - let gamma = max(u.p[1].z, 1e-4); - let contrast = u.p[1].w; - let brightness = u.p[2].x; - let prediv = u.p[2].y > 0.5; +fn apply_cc_wheel_and_lgg( + rgb_in: vec3, + hue_turns: f32, + sat: f32, + tint_turns: f32, + tint_len: f32, + tint_mode: f32, + gain: f32, + lift: f32, + gamma_in: f32, + contrast: f32, + brightness: f32, +) -> vec3 { let k_luma = vec3(0.299, 0.587, 0.114); + let gamma = max(gamma_in, 1e-4); + var rgb = rgb_in; - var rgb = src.rgb; - if (prediv && src.a > 1e-5) { - rgb = rgb / src.a; - } - - // 1. Hue rotation (verified 0.00/255 vs Fusion 21.1: +turns rotates Red -> Yellow -> Green -> Cyan -> Blue -> Magenta) + // 1. Hue rotation (verified 0.00/255 vs Fusion 21.1) if (abs(hue_turns) > 1e-5) { rgb = rotate_hue_preserve_luma(rgb, -hue_turns * 6.28318530718); } - // 2. Fusion Color Wheel Tint (verified 0.00/255 vs Fusion 21.1: lerp toward pure HSV chroma * 2*min(Y, 1-Y)) + // 2. Fusion Color Wheel Tint if (tint_len > 1e-5) { - let y_t = dot(rgb, k_luma); - let pure = hsv_pure_hue(tint_turns); - let pure_y = dot(pure, k_luma); - let tc = pure - vec3(pure_y); - let y_clamped = clamp(y_t, 0.0, 1.0); - let amp = 2.0 * min(y_clamped, 1.0 - y_clamped); - let tint_rgb = vec3(y_t) + tc * amp; - rgb = mix(rgb, tint_rgb, clamp(tint_len, 0.0, 1.0)); + let l = clamp(tint_len, 0.0, 1.0); + if (tint_mode < 0.5) { + // TintMode = 0 (RGB cube tilt + perpendicular chroma squeeze, verified 0.00/255 at len=1.0!) + let s3 = 0.5773502691896258; + let e1 = vec3(s3, s3, s3); + let a = tint_turns * 6.28318530718; + let u_ch = normalize(vec3(cos(a), cos(a - 2.09439510239), cos(a + 2.09439510239))); + let u_pp = normalize(cross(e1, u_ch)); + let t = l * l; + let th = 0.471238898038 * t; // 27.0 deg * len^2 + let c_th = cos(th); + let s_th = sin(th); + let x1 = dot(rgb, e1); + let x2 = dot(rgb, u_ch); + let x3 = dot(rgb, u_pp); + let y1 = c_th * x1 - s_th * x2; + let y2 = s_th * x1 + c_th * x2; + let y3 = (1.0 - t) * x3; + rgb = y1 * e1 + y2 * u_ch + y3 * u_pp; + } else if (tint_mode < 1.5) { + // TintMode = 1: luma-preserving chroma blend + amp = l*((1-l) + l*2*min(y,1-y)), verified 0.00/255! + let y_t = dot(rgb, k_luma); + let pure = hsv_pure_hue(tint_turns); + let pure_y = dot(pure, k_luma); + let tc = pure - vec3(pure_y); + let yc = clamp(y_t, 0.0, 1.0); + let amp = l * ((1.0 - l) + l * 2.0 * min(yc, 1.0 - yc)); + rgb = vec3(y_t) + (rgb - vec3(y_t)) * (1.0 - l) + tc * amp; + } else { + // TintMode = 2 (Fusion 21.1 default when omitted): lerp toward pure HSV chroma * 2*min(y,1-y) + let y_t = dot(rgb, k_luma); + let pure = hsv_pure_hue(tint_turns); + let pure_y = dot(pure, k_luma); + let tc = pure - vec3(pure_y); + let yc = clamp(y_t, 0.0, 1.0); + let amp = 2.0 * min(yc, 1.0 - yc); + let tint_rgb = vec3(y_t) + tc * amp; + rgb = mix(rgb, tint_rgb, l); + } } - // 3. Saturation (Rec.601 luma, no gamut crushing — verified 0.00/255 at sat=0, 1.6, 3.0, 6.0!) - let luma = dot(rgb, k_luma); - rgb = mix(vec3(luma), rgb, sat); + // 3. Saturation (Rec.601 luma, no gamut crushing) + if (abs(sat - 1.0) > 1e-5) { + let luma = dot(rgb, k_luma); + rgb = mix(vec3(luma), rgb, sat); + } + + // 4. Contrast -> Lift/Gain -> Brightness -> Gamma + if (abs(contrast - 1.0) > 1e-5) { + rgb = (rgb - 0.5) * contrast + 0.5; + } + if (abs(gain - 1.0) > 1e-5 || abs(lift) > 1e-5) { + rgb = rgb * (gain - lift) + lift; + } + if (abs(brightness) > 1e-5) { + rgb = rgb + brightness; + } + if (abs(gamma - 1.0) > 1e-5) { + rgb = pow(max(rgb, vec3(0.0)), vec3(1.0 / gamma)); + } + return rgb; +} + +@compute @workgroup_size(8, 8) +fn cc_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { return; } + let src = textureLoad(src_a, vec2(gid.xy), 0); + let prediv = u.p[2].y > 0.5; + let tint_mode = u.p[3].y; + let has_smh = u.p[3].z > 0.5; + let k_luma = vec3(0.299, 0.587, 0.114); + + var rgb = src.rgb; + if (prediv && src.a > 1e-5) { + rgb = rgb / src.a; + } + + if (has_smh) { + let y0 = clamp(dot(rgb, k_luma), 0.0, 1.0); + let w_s = clamp(1.0 - 2.0 * y0, 0.0, 1.0); + let w_h = clamp(2.0 * y0 - 1.0, 0.0, 1.0); + let w_m = max(1.0 - w_s - w_h, 0.0); + let rgb_s = apply_cc_wheel_and_lgg(rgb, u.p[4].x, u.p[4].y, u.p[4].z, u.p[4].w, tint_mode, u.p[5].x, u.p[5].y, u.p[5].z, u.p[5].w, u.p[10].x); + let rgb_m = apply_cc_wheel_and_lgg(rgb, u.p[6].x, u.p[6].y, u.p[6].z, u.p[6].w, tint_mode, u.p[7].x, u.p[7].y, u.p[7].z, u.p[7].w, u.p[10].y); + let rgb_h = apply_cc_wheel_and_lgg(rgb, u.p[8].x, u.p[8].y, u.p[8].z, u.p[8].w, tint_mode, u.p[9].x, u.p[9].y, u.p[9].z, u.p[9].w, u.p[10].z); + rgb = rgb_s * w_s + rgb_m * w_m + rgb_h * w_h; + } - // 4. Contrast -> Lift/Gain -> Brightness -> Gamma (verified 0.00/255 vs Fusion 21.1!) - rgb = (rgb - 0.5) * contrast + 0.5; - rgb = rgb * (gain - lift) + lift; - rgb = rgb + brightness; - rgb = pow(max(rgb, vec3(0.0)), vec3(1.0 / gamma)); + rgb = apply_cc_wheel_and_lgg(rgb, u.p[0].x, u.p[0].y, u.p[0].z, u.p[0].w, tint_mode, u.p[1].x, u.p[1].y, u.p[1].z, u.p[1].w, u.p[2].x); if (prediv) { rgb = rgb * src.a; @@ -754,11 +839,15 @@ fn fast_noise_op(@builtin(global_invocation_id) gid: vec3) { freq = freq * 2.0; amp = amp * 0.5; } - let n_avg = sum / max(norm, 1e-4); + 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) { - val = n_avg * 0.82 * contrast + brightness; + 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; } @@ -868,10 +957,11 @@ fn displace_op(@builtin(global_invocation_id) gid: vec3) { // ============================================================================ -// 10. Mask Shapes (EllipseMask & RectangleMask) + Mask Combine / Apply +// 10. Mask Shapes (EllipseMask & RectangleMask) + Mask Combine / Apply / BitmapMask // p[0] = (center.x, center.y, width, height) // p[1] = (angle_rad, soft_edge, corner_radius, invert) // p[2] = (shape: 0=Ellipse, 1=Rect, level, has_prev_mask, paint_mode) +// p[3] = (border_width, solid: 1=filled/0=outline, 0, 0) // paint_mode: 0=Merge, 1=Add, 2=Subtract, 3=Multiply, 4=Min, 5=Max, 6=Invert, 7=Replace // ============================================================================ fn combine_mask_val(prev: f32, cur: f32, mode: i32) -> f32 { @@ -895,13 +985,15 @@ fn mask_shape_op(@builtin(global_invocation_id) gid: vec3) { let center = u.p[0].xy; let half_sz = max(u.p[0].zw * 0.5, vec2(1e-5)); let angle = u.p[1].x; - let soft = max(u.p[1].y, 1.0 / max(f32(dims.x), 1.0)); + let soft = max(u.p[1].y, 0.5 / max(f32(dims.x), 1.0)); let radius = u.p[1].z; let invert = u.p[1].w > 0.5; let shape = i32(u.p[2].x + 0.5); let level = u.p[2].y; let has_prev = u.p[2].z > 0.5; let paint_mode = i32(u.p[2].w + 0.5); + let border_w = u.p[3].x; + let solid = u.p[3].y > 0.5; // Work in isotropic frame-width units (1.0 = canvas width) so rotations & circles are exact! let rel_w = (fu - center) * vec2(1.0, 1.0 / aspect); @@ -924,6 +1016,12 @@ fn mask_shape_op(@builtin(global_invocation_id) gid: vec3) { dist = length(max(q, vec2(0.0))) + min(max(q.x, q.y), 0.0) - r_w; } + if (solid) { + dist = dist - border_w * 0.5; + } else { + dist = abs(dist) - abs(border_w) * 0.5; + } + var a = 1.0 - smoothstep(-soft, soft, dist); if (invert) { a = 1.0 - a; } a = clamp(a * level, 0.0, 1.0); @@ -964,6 +1062,80 @@ fn mask_apply_op(@builtin(global_invocation_id) gid: vec3) { textureStore(dst_tex, vec2(gid.xy), src * m); } +// 10b. BitmapMask channel extraction + Low/High clip + centered 1:1 pixel alignment +// p[0] = (channel: 0=A,1=Luma,2=R,3=G,4=B,5=Sat,6=Lightness,7=Hue, low, high, fit_stretch) +// p[1] = (center.x, center.y, src_origin.x, src_origin.y) +// p[2] = (src_canvas.x, src_canvas.y, 0, 0) +@compute @workgroup_size(8, 8) +fn bitmap_mask_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { return; } + let fdims = vec2(dims); + let sdims = vec2(textureDimensions(src_a)); + let ch = i32(u.p[0].x + 0.5); + let lo = u.p[0].y; + let hi = u.p[0].z; + let fit_stretch = u.p[0].w > 0.5; + let center = u.p[1].xy; + let src_origin = u.p[1].zw; + let src_canvas = max(u.p[2].xy, vec2(1.0)); + + var col = vec4(0.0); + if (fit_stretch) { + let uv = (vec2(gid.xy) + 0.5) / fdims; + col = textureSampleLevel(src_a, samp_lin, uv, 0.0); + } else { + // Fusion BitmapMask places Image centered at 1:1 pixel scale inside the mask canvas + let shift_px = vec2((center.x - 0.5) * fdims.x, -(center.y - 0.5) * fdims.y); + let canvas_px = (vec2(gid.xy) + 0.5) - 0.5 * fdims - shift_px + 0.5 * src_canvas; + let tex_px = canvas_px - src_origin; + if (tex_px.x >= 0.0 && tex_px.x <= sdims.x && tex_px.y >= 0.0 && tex_px.y <= sdims.y) { + col = textureSampleLevel(src_a, samp_lin, tex_px / sdims, 0.0); + } + } + + var v = col.a; + if (ch == 1) { + // Fusion 21.1 BitmapMask Luminance channel (verified via probe_mask_softedge f08: BGR-order weights 0.114*R + 0.587*G + 0.299*B!) + v = dot(col.rgb, vec3(0.114, 0.587, 0.299)); + } else if (ch == 2) { + v = col.r; + } else if (ch == 3) { + v = col.g; + } else if (ch == 4) { + v = col.b; + } else if (ch == 5) { + let cmax = max(col.r, max(col.g, col.b)); + let cmin = min(col.r, min(col.g, col.b)); + v = select(0.0, (cmax - cmin) / cmax, cmax > 1e-5); + } else if (ch == 6) { + let cmax = max(col.r, max(col.g, col.b)); + let cmin = min(col.r, min(col.g, col.b)); + v = 0.5 * (cmax + cmin); + } else if (ch == 7) { + let cmax = max(col.r, max(col.g, col.b)); + let cmin = min(col.r, min(col.g, col.b)); + let d = cmax - cmin; + if (d > 1e-5) { + var h = 0.0; + if (cmax == col.r) { h = (col.g - col.b) / d + select(0.0, 6.0, col.g < col.b); } + else if (cmax == col.g) { h = (col.b - col.r) / d + 2.0; } + else { h = (col.r - col.g) / d + 4.0; } + v = h / 6.0; + } else { + v = 0.0; + } + } + + let span = hi - lo; + if (abs(span) < 1e-6) { + v = select(0.0, 1.0, v >= lo); + } else { + v = clamp((v - lo) / span, 0.0, 1.0); + } + textureStore(dst_tex, vec2(gid.xy), vec4(v, v, v, v)); +} + // ============================================================================ // 11. Fuse.Colorize (Clover's exact 2020 Colorize.fuse formula!) // p[0] = (r1, g1, b1, a1), p[1] = (r2, g2, b2, a2), p[2] = (blend, has_mask, mask_invert, 0) @@ -1361,7 +1533,15 @@ fn channel_boolean_op(@builtin(global_invocation_id) gid: vec3) { let dims = textureDimensions(dst_tex); if (gid.x >= dims.x || gid.y >= dims.y) { return; } let bg = textureLoad(src_a, vec2(gid.xy), 0); - let fu = pix_to_fu(gid.xy, dims); + let bg_dod = u.p[3]; + let has_bg_dod = bg_dod.z > 0.5 && bg_dod.w > 0.5; + let bg_dims = select(vec2(dims), bg_dod.zw, has_bg_dod); + let canvas_px = select( + vec2(gid.xy) + vec2(0.5), + vec2(gid.xy) + vec2(0.5) + bg_dod.xy, + has_bg_dod, + ); + let fu = vec2(canvas_px.x / bg_dims.x, 1.0 - canvas_px.y / bg_dims.y); let fg = sample_dod_edges_mode(src_b, fu, 0, u.p[2], false); let op = i32(u.p[0].x + 0.5); @@ -1376,7 +1556,7 @@ fn channel_boolean_op(@builtin(global_invocation_id) gid: vec3) { let va = select(cb_apply_op(op, bg.a, cb_pick(to_a, bg, fg, bg.a)), bg.a, to_a == 4); let res = clamp(vec4(vr, vg, vb, va), vec4(0.0), vec4(1.0)); - let m = read_mask(gid.xy, dims, u.p[1].z, u.p[1].w) * u.p[1].y; + let m = read_mask_uv(canvas_px / bg_dims, u.p[1].z, u.p[1].w) * u.p[1].y; let out_col = mix(bg, res, clamp(m, 0.0, 1.0)); store_dst(vec2(gid.xy), out_col); } @@ -1928,52 +2108,35 @@ fn ultra_keyer_op(@builtin(global_invocation_id) gid: vec3) { let blend = u.p[2].x; let inv_matte = u.p[2].w > 0.5; - // Chroma-vector projection against key background color (prevents bright Yellow from disappearing on green key!) - let bg_m = (bg.r + bg.g + bg.b) / 3.0; - let bg_c = bg - vec3(bg_m); - let bg_len = max(length(bg_c), 0.04); - let px_m = (src.r + src.g + src.b) / 3.0; - let px_c = src.rgb - vec3(px_m); - let px_len = length(px_c); - let denom_len = mix(bg_len, max(px_len, bg_len), 0.75); - let k_proj = max(dot(px_c, bg_c), 0.0) / (denom_len * bg_len); - - // Spill factor along dominant chroma channel for background subtraction - var k_spill = 0.0; + // Fusion 21.1 UltraKeyer exact color-difference matte + background subtraction + // Verified to 0.02%-0.15% MAE on Snow Globe probe_ultrakey (f00-f06)! + var k = 0.0; if (bg.g >= bg.r && bg.g >= bg.b) { - let bg_ex = max(bg.g - 0.5 * (bg.r + bg.b), 0.04); - k_spill = max((src.g - 0.5 * (src.r + src.b)) / bg_ex, 0.0); + let bg_ex = max(bg.g - 0.5 * (bg.r + bg.b), 1e-4); + k = max((src.g - 0.5 * (src.r + src.b)) / bg_ex, 0.0); } else if (bg.b >= bg.r && bg.b >= bg.g) { - let bg_ex = max(bg.b - 0.5 * (bg.r + bg.g), 0.04); - k_spill = max((src.b - 0.5 * (src.r + src.g)) / bg_ex, 0.0); + let bg_ex = max(bg.b - 0.5 * (bg.r + bg.g), 1e-4); + k = max((src.b - 0.5 * (src.r + src.g)) / bg_ex, 0.0); } else { - let bg_ex = max(bg.r - 0.5 * (bg.g + bg.b), 0.04); - k_spill = max((src.r - 0.5 * (src.g + src.b)) / bg_ex, 0.0); + let bg_ex = max(bg.r - 0.5 * (bg.g + bg.b), 1e-4); + k = max((src.r - 0.5 * (src.g + src.b)) / bg_ex, 0.0); } - let k_amt = k_spill; - // Higher MatteSeparation increases key sensitivity aggressively (default 0.0) - let k_sens = clamp(k_proj, 0.0, 1.0); - let raw_a = clamp(pow(1.0 - k_sens, 0.58 + sep * 14.0), 0.0, 1.0); + // Background subtraction (unclamped k cleanly zeroes green-screen background even when PostMultiplyImage=0) + var rgb = max(src.rgb - bg * k, vec3(0.0)); + var raw_a = clamp(max(1.0 - k, max(rgb.r, max(rgb.g, rgb.b))), 0.0, 1.0); + if (u.p[0].w > 1e-4) { + // MatteSeparation pushes partial matte values toward 0 + raw_a = clamp(pow(raw_a, 1.0 + u.p[0].w * 4.0), 0.0, 1.0); + } var alpha = clamp((raw_a - lo_th) / (hi_th - lo_th), 0.0, 1.0); - // Optional per-channel & luminance matte range gates (when non-default [0,1]) - let r_gate = (src.r >= u.p[3].x && src.r <= u.p[3].y); - let g_gate = (src.g >= u.p[3].z && src.g <= u.p[3].w); - let b_gate = (src.b >= u.p[4].x && src.b <= u.p[4].y); - let luma = dot(src.rgb, vec3(0.299, 0.587, 0.114)); - let l_gate = (luma >= u.p[4].z && luma <= u.p[4].w); - let has_gates = u.p[3].x > 1e-4 || u.p[3].y < 0.9999 || u.p[3].z > 1e-4 || u.p[3].w < 0.9999 - || u.p[4].x > 1e-4 || u.p[4].y < 0.9999 || u.p[4].z > 1e-4 || u.p[4].w < 0.9999; - if (has_gates && r_gate && g_gate && b_gate && l_gate) { - alpha = 0.0; - } - if (inv_matte) { alpha = 1.0 - alpha; } alpha = alpha * src.a; + if (alpha <= 1e-5) { + rgb = vec3(0.0); + } - // Background color subtraction (spill removal) proportional to key amount - var rgb = max(src.rgb - bg * clamp(k_amt, 0.0, 1.0), vec3(0.0)); if (spill_sup > 1e-4) { if (bg.g >= bg.r && bg.g >= bg.b) { let lim = max(rgb.r, rgb.b); @@ -1981,6 +2144,9 @@ fn ultra_keyer_op(@builtin(global_invocation_id) gid: vec3) { } else if (bg.b >= bg.r && bg.b >= bg.g) { let lim = max(rgb.r, rgb.g); if (rgb.b > lim) { rgb.b = mix(rgb.b, lim, spill_sup); } + } else { + let lim = max(rgb.g, rgb.b); + if (rgb.r > lim) { rgb.r = mix(rgb.r, lim, spill_sup); } } } if (post_mult) { @@ -2237,3 +2403,41 @@ fn change_depth_op(@builtin(global_invocation_id) gid: vec3) { } store_dst(p, col); } + + +// ============================================================================ +// 34. Vortex (radial twist warp: th = -angle * (1 - r / (0.5*Size))^Power) +// p[0] = (center.x, center.y, radius_norm, angle_rad) +// p[1] = (power, blend, has_mask, mask_invert) +// ============================================================================ +@compute @workgroup_size(8, 8) +fn vortex_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { return; } + let aspect = f32(dims.x) / max(f32(dims.y), 1.0); + let fu = pix_to_fu(gid.xy, dims); + let center = u.p[0].xy; + let radius = max(u.p[0].z, 1e-5); + let angle = u.p[0].w; + let power = max(u.p[1].x, 0.0); + let blend = u.p[1].y; + + let orig = textureLoad(src_a, vec2(gid.xy), 0); + // Isotropic frame-width delta so swirls stay circular on 16:9 canvases + let rel_w = (fu - center) * vec2(1.0, 1.0 / aspect); + let r = length(rel_w); + + var warped = orig; + if (r < radius && abs(angle) > 1e-6) { + let t = pow(max(1.0 - r / radius, 0.0), power); + let th = -angle * t; + let c = cos(th); + let s = sin(th); + let rot_w = vec2(rel_w.x * c - rel_w.y * s, rel_w.x * s + rel_w.y * c); + let src_fu = center + rot_w * vec2(1.0, aspect); + warped = sample_edges(src_a, src_fu, 0); + } + + let m = read_mask(gid.xy, dims, u.p[1].z, u.p[1].w) * blend; + store_dst(vec2(gid.xy), mix(orig, warped, clamp(m, 0.0, 1.0))); +} diff --git a/crates/model/src/comp.rs b/crates/model/src/comp.rs index 46c4fc936017e9fdc65dfea2faaa58652716209e..a017f421889ff556382da1ee7e3832ab28da319b 100644 --- a/crates/model/src/comp.rs +++ b/crates/model/src/comp.rs @@ -119,6 +119,7 @@ pub fn is_supported_tool(kind: &str) -> bool { | "Plasma" | "FilmGrain" | "Displace" + | "Vortex" | "EllipseMask" | "RectangleMask" | "PolylineMask" @@ -1051,50 +1052,20 @@ impl Comp { expr_engine.eval_point(expr, time, &sp, &spts, &en) } - /// Connects `src` node's output to `dst` node's `port` input. + /// Connects `src` node's `"Output"` to `dst` node's `port` input (ignores self-loops and cycles). pub fn connect(&mut self, src: NodeId, dst: NodeId, port: &str) { - if src == dst { - return; - } - let src_name = self.nodes[src.0].name.clone(); - let entry = self.nodes[dst.0] - .inputs - .entry(port.to_owned()) - .or_insert(InputBinding { - value: None, - source_op: None, - source_output: None, - expression: None, - }); - entry.source_op = Some(src_name); - entry.source_output = Some("Output".to_owned()); - self.revision += 1; - } - - /// Disconnects `dst` node's `port` input. - pub fn disconnect(&mut self, dst: NodeId, port: &str) { - if let Some(entry) = self.nodes[dst.0].inputs.get_mut(port) { - entry.source_op = None; - entry.source_output = None; - self.revision += 1; - } + let _ = self.connect_output(src, "Output", dst, port); } /// Inserts `mid` node cleanly onto the wire `src -> dst.dst_port`! /// Wires `src -> mid.(default_input)` and `mid -> dst.dst_port`. pub fn insert_on_wire(&mut self, mid: NodeId, src: NodeId, dst: NodeId, dst_port: &str) { - if mid == src || mid == dst { - return; - } - let mid_port = default_main_input_port(&self.nodes[mid.0].kind); - self.connect(src, mid, mid_port); - self.connect(mid, dst, dst_port); + let _ = self.splice_node_into_pipe(mid, src, dst, dst_port); } /// Toggles bypass (`PassThrough`) on a node. pub fn toggle_bypass(&mut self, id: NodeId) { - self.nodes[id.0].bypassed = !self.nodes[id.0].bypassed; - self.revision += 1; + let _ = self.toggle_passthrough(id); } /// Extracts metadata for every top-level (non-internal) `Saver` node in this comp. @@ -1390,7 +1361,7 @@ impl Comp { } } -fn vec2_lua(x: f64, y: f64) -> LuaValue { +pub(crate) fn vec2_lua(x: f64, y: f64) -> LuaValue { LuaValue::Table(LuaTable { tag: None, entries: vec![ @@ -1400,7 +1371,7 @@ fn vec2_lua(x: f64, y: f64) -> LuaValue { }) } -fn ensure_table_mut<'a>(parent: &'a mut LuaTable, key: &str, tag: Option<&str>) -> &'a mut LuaTable { +pub(crate) fn ensure_table_mut<'a>(parent: &'a mut LuaTable, key: &str, tag: Option<&str>) -> &'a mut LuaTable { if parent.get_table(key).is_none() { parent.set( LuaKey::Str(key.to_owned()), @@ -1413,7 +1384,7 @@ fn ensure_table_mut<'a>(parent: &'a mut LuaTable, key: &str, tag: Option<&str>) parent.get_table_mut(key).expect("table just inserted") } -fn param_value_to_lua(v: &ParamValue) -> LuaValue { +pub(crate) fn param_value_to_lua(v: &ParamValue) -> LuaValue { match v { ParamValue::Number(n) => LuaValue::Number(*n), ParamValue::Point([x, y]) => vec2_lua(*x, *y), @@ -1530,6 +1501,14 @@ fn sync_node_inputs( } } } + if it.entries.is_empty() + && binding.value.is_none() + && binding.source_op.is_none() + && binding.source_output.is_none() + && binding.expression.is_none() + { + in_tbl.remove(&LuaKey::Str(port.clone())); + } } } else { // Port did not exist in raw `Inputs`. diff --git a/crates/model/src/edit.rs b/crates/model/src/edit.rs new file mode 100644 index 0000000000000000000000000000000000000000..d20a0d13fc8a512f8eb8ec6fc7626e1fd81e84ff --- /dev/null +++ b/crates/model/src/edit.rs @@ -0,0 +1,1826 @@ +//! Lossless graph & parameter mutation API for `Comp`, plus `CompHistory` undo/redo stack. + +use crate::comp::{ + Comp, InputBinding, Node, NodeId, ParamValue, default_main_input_port, ensure_table_mut, + param_value_to_lua, vec2_lua, +}; +use crate::lua_value::{LuaKey, LuaTable, LuaValue, is_valid_lua_ident}; +use crate::spline::{BezierSpline, Keyframe, PolyPath}; +use std::collections::{HashMap, HashSet, VecDeque}; + +/// Default maximum number of undo steps retained by [`CompHistory`]. +pub const DEFAULT_MAX_HISTORY: usize = 128; + +impl Comp { + /// Checks whether a tool or modifier name is already in use anywhere in this composition. + fn name_exists(&self, name: &str) -> bool { + if self.node_by_name.contains_key(name) + || self.splines.contains_key(name) + || self.poly_paths.contains_key(name) + || self.gradient_modifiers.contains_key(name) + || self.text_modifiers.contains_key(name) + || self.text_splines.contains_key(name) + || self.polyline_splines.contains_key(name) + || self.text_cls.contains_key(name) + || self.shakes.contains_key(name) + { + return true; + } + if let Some(tools) = self.raw_root.as_ref().and_then(|r| r.get_table("Tools")) { + if tools.get(name).is_some() { + return true; + } + } + false + } + + /// Generates a unique Fusion-style name for a node or modifier. + /// - With `Some(hint)`: sanitizes `hint`; uses `hint` if free, else `hint_1`, `hint_2`, ... + /// - With `None`: derives a clean base from `kind` and tries `Base1`, `Base2`, ... + fn generate_unique_name(&self, kind: &str, name_hint: Option<&str>) -> String { + if let Some(hint) = name_hint.map(str::trim).filter(|s| !s.is_empty()) { + let base = sanitize_lua_ident(hint); + if !self.name_exists(&base) { + return base; + } + let mut idx = 1usize; + loop { + let candidate = format!("{base}_{idx}"); + if !self.name_exists(&candidate) { + return candidate; + } + idx += 1; + } + } + + let raw_base = kind.rsplit('.').next().unwrap_or(kind); + let base = sanitize_lua_ident(raw_base); + let mut idx = 1usize; + loop { + let candidate = format!("{base}{idx}"); + if !self.name_exists(&candidate) { + return candidate; + } + idx += 1; + } + } + + /// Adds a new node of Fusion class `kind` at flow position `pos` with sensible Fusion 21.1 defaults. + pub fn add_node(&mut self, kind: &str, name_hint: Option<&str>, pos: [f32; 2]) -> NodeId { + let name = self.generate_unique_name(kind, name_hint); + let id = NodeId(self.nodes.len()); + + let defaults = default_inputs_for_kind(kind, self.width, self.height); + let mut inputs = HashMap::new(); + let mut raw_inputs = LuaTable::default(); + for (port, val) in defaults { + let mut it = LuaTable { + tag: Some("Input".to_owned()), + entries: Vec::new(), + }; + it.set(LuaKey::Str("Value".to_owned()), param_value_to_lua(&val)); + raw_inputs.set(LuaKey::Str(port.clone()), LuaValue::Table(it)); + inputs.insert( + port, + InputBinding { + value: Some(val), + source_op: None, + source_output: None, + expression: None, + }, + ); + } + + let mut raw = LuaTable { + tag: Some(kind.to_owned()), + entries: Vec::new(), + }; + if kind == "Loader" { + raw.set( + LuaKey::Str("Clips".to_owned()), + LuaValue::Table(LuaTable::default()), + ); + } + if !raw_inputs.entries.is_empty() { + raw.set(LuaKey::Str("Inputs".to_owned()), LuaValue::Table(raw_inputs)); + } + raw.set( + LuaKey::Str("ViewInfo".to_owned()), + LuaValue::Table(default_view_info_for_kind(kind, pos)), + ); + + let node = Node { + id, + name: name.clone(), + kind: kind.to_owned(), + pos, + bypassed: false, + internal: false, + macro_output: None, + inputs, + clips: Vec::new(), + raw: raw.clone(), + }; + + self.nodes.push(node); + self.node_by_name.insert(name.clone(), id); + + if let Some(root) = self.raw_root.as_mut() { + let tools = ensure_table_mut(root, "Tools", Some("ordered")); + tools.set(LuaKey::Str(name), LuaValue::Table(raw)); + } + + self.revision += 1; + id + } + + /// Deletes the specified nodes, unwires downstream references, compacts `NodeId` indexing, + /// and prunes modifiers that were owned solely by the deleted nodes. + /// Returns the names of the deleted nodes. + pub fn delete_nodes(&mut self, ids: &[NodeId]) -> Vec { + let mut to_delete: HashSet = HashSet::new(); + let mut deleted_names: Vec = Vec::new(); + for &id in ids { + if id.0 < self.nodes.len() && to_delete.insert(id.0) { + deleted_names.push(self.nodes[id.0].name.clone()); + } + } + if to_delete.is_empty() { + return deleted_names; + } + + let deleted_name_set: HashSet = deleted_names.iter().cloned().collect(); + + // Collect modifier names referenced by the nodes being deleted (candidates for pruning). + let mut candidate_modifiers: HashSet = HashSet::new(); + for &idx in &to_delete { + collect_node_source_ops(&self.nodes[idx], &mut candidate_modifiers); + } + + // Compact `self.nodes` while building an old_idx -> Option remap. + let old_len = self.nodes.len(); + let mut remap: Vec> = vec![None; old_len]; + let old_nodes = std::mem::take(&mut self.nodes); + let mut new_nodes = Vec::with_capacity(old_len - to_delete.len()); + for (old_idx, mut node) in old_nodes.into_iter().enumerate() { + if to_delete.contains(&old_idx) { + continue; + } + let new_id = NodeId(new_nodes.len()); + remap[old_idx] = Some(new_id); + node.id = new_id; + new_nodes.push(node); + } + + // Fix `macro_output` and unwire any inputs pointing to deleted nodes. + for node in &mut new_nodes { + if let Some(old_mo) = node.macro_output { + node.macro_output = remap.get(old_mo.0).copied().flatten(); + } + let mut unwired_ports = Vec::new(); + for (port, binding) in &mut node.inputs { + if binding + .source_op + .as_ref() + .is_some_and(|s| deleted_name_set.contains(s)) + { + binding.source_op = None; + binding.source_output = None; + unwired_ports.push(port.clone()); + } + } + if !unwired_ports.is_empty() { + if let Some(in_tbl) = node.raw.get_table_mut("Inputs") { + for port in &unwired_ports { + if let Some(it) = in_tbl.get_table_mut(port) { + it.remove(&LuaKey::Str("SourceOp".to_owned())); + it.remove(&LuaKey::Str("Source".to_owned())); + } + } + } + } + } + + // Rebuild `node_by_name`. + self.node_by_name.clear(); + for node in &new_nodes { + if !node.internal || !self.node_by_name.contains_key(&node.name) { + self.node_by_name.insert(node.name.clone(), node.id); + } + } + self.nodes = new_nodes; + + // Collect all modifier references still live on surviving nodes (transitively through PolyPaths/Shakes). + let mut live_refs: HashSet = HashSet::new(); + for node in &self.nodes { + collect_node_source_ops(node, &mut live_refs); + } + // Propagate transitive references (e.g. surviving node -> PolyPath -> Displacement spline, + // or surviving node -> Shake -> BezierSpline). + let mut queue: VecDeque = live_refs.iter().cloned().collect(); + while let Some(mod_name) = queue.pop_front() { + if let Some(pp) = self.poly_paths.get(&mod_name) { + if let Some(disp) = &pp.displacement_op { + if live_refs.insert(disp.clone()) { + queue.push_back(disp.clone()); + } + } + } + if let Some(sh) = self.shakes.get(&mod_name) { + for binding in sh.inputs.values() { + if let Some(src) = &binding.source_op { + if live_refs.insert(src.clone()) { + queue.push_back(src.clone()); + } + } + } + } + } + + // Expand candidate_modifiers transitively (e.g. deleted node -> PolyPath -> Displacement spline). + let mut cand_queue: VecDeque = candidate_modifiers.iter().cloned().collect(); + while let Some(mod_name) = cand_queue.pop_front() { + if let Some(pp) = self.poly_paths.get(&mod_name) { + if let Some(disp) = &pp.displacement_op { + if candidate_modifiers.insert(disp.clone()) { + cand_queue.push_back(disp.clone()); + } + } + } + if let Some(sh) = self.shakes.get(&mod_name) { + for binding in sh.inputs.values() { + if let Some(src) = &binding.source_op { + if candidate_modifiers.insert(src.clone()) { + cand_queue.push_back(src.clone()); + } + } + } + } + } + + // Prune orphaned modifiers that belonged to deleted nodes and are no longer referenced. + let mut pruned_modifiers: HashSet = HashSet::new(); + for cand in candidate_modifiers { + if live_refs.contains(&cand) || self.node_by_name.contains_key(&cand) { + continue; + } + let mut removed = false; + removed |= self.splines.remove(&cand).is_some(); + removed |= self.poly_paths.remove(&cand).is_some(); + removed |= self.gradient_modifiers.remove(&cand).is_some(); + removed |= self.text_modifiers.remove(&cand).is_some(); + removed |= self.text_splines.remove(&cand).is_some(); + removed |= self.polyline_splines.remove(&cand).is_some(); + removed |= self.text_cls.remove(&cand).is_some(); + removed |= self.shakes.remove(&cand).is_some(); + if removed { + pruned_modifiers.insert(cand); + } + } + + // Update `raw_root.Tools`: remove deleted nodes & pruned modifiers, and clear stale SourceOp. + if let Some(root) = self.raw_root.as_mut() { + if let Some(tools) = root.get_table_mut("Tools") { + tools.entries.retain(|(k, _)| match k { + LuaKey::Str(name) => { + !deleted_name_set.contains(name) && !pruned_modifiers.contains(name) + } + _ => true, + }); + } + } + + self.revision += 1; + deleted_names + } + + /// Duplicates the selected nodes at `pos + offset` with unique names. + /// Preserves internal wires between duplicated nodes, keeps external wires intact, + /// and clones owned `BezierSpline` / `PolyPath` modifiers with fresh unique names. + pub fn duplicate_nodes(&mut self, ids: &[NodeId], offset: [f32; 2]) -> Vec { + let mut unique_ids = Vec::new(); + let mut seen = HashSet::new(); + for &id in ids { + if id.0 < self.nodes.len() && seen.insert(id.0) { + unique_ids.push(id); + } + } + if unique_ids.is_empty() { + return Vec::new(); + } + + // Reserve names for all duplicated nodes first so internal wires can be remapped cleanly. + let mut reserved: HashSet = HashSet::new(); + let mut node_name_map: HashMap = HashMap::new(); + let mut dup_specs: Vec<(NodeId, String)> = Vec::with_capacity(unique_ids.len()); + + for &id in &unique_ids { + let orig_name = self.nodes[id.0].name.clone(); + let new_name = self.generate_unique_name_excluding(&orig_name, &reserved); + reserved.insert(new_name.clone()); + node_name_map.insert(orig_name, new_name.clone()); + dup_specs.push((id, new_name)); + } + + // Clone `BezierSpline` and `PolyPath` modifiers referenced by the duplicated nodes. + let mut mod_name_map: HashMap = HashMap::new(); + let mut cloned_splines: Vec<(String, BezierSpline, Option)> = Vec::new(); + let mut cloned_paths: Vec<(String, PolyPath, Option)> = Vec::new(); + + for &(id, _) in &dup_specs { + let mut input_ports: Vec = self.nodes[id.0].inputs.keys().cloned().collect(); + input_ports.sort(); + for port in input_ports { + let Some(src_op) = self.nodes[id.0] + .inputs + .get(&port) + .and_then(|b| b.source_op.clone()) + else { + continue; + }; + if mod_name_map.contains_key(&src_op) || node_name_map.contains_key(&src_op) { + continue; + } + if let Some(orig_spline) = self.splines.get(&src_op).cloned() { + let new_mod = self.generate_unique_name_excluding(&src_op, &reserved); + reserved.insert(new_mod.clone()); + let mut sp = orig_spline; + sp.name = new_mod.clone(); + let raw_tbl = self + .raw_root + .as_ref() + .and_then(|r| r.get_table("Tools")) + .and_then(|t| t.get_table(&src_op)) + .cloned(); + mod_name_map.insert(src_op, new_mod.clone()); + cloned_splines.push((new_mod, sp, raw_tbl)); + } else if let Some(orig_path) = self.poly_paths.get(&src_op).cloned() { + let new_mod = self.generate_unique_name_excluding(&src_op, &reserved); + reserved.insert(new_mod.clone()); + let mut pp = orig_path; + pp.name = new_mod.clone(); + + let mut raw_tbl = self + .raw_root + .as_ref() + .and_then(|r| r.get_table("Tools")) + .and_then(|t| t.get_table(&src_op)) + .cloned(); + + // Also clone PolyPath's displacement spline if present. + if let Some(orig_disp) = pp.displacement_op.clone() { + let new_disp = if let Some(existing) = mod_name_map.get(&orig_disp) { + existing.clone() + } else if let Some(disp_sp) = self.splines.get(&orig_disp).cloned() { + let fresh = self.generate_unique_name_excluding(&orig_disp, &reserved); + reserved.insert(fresh.clone()); + let mut sp = disp_sp; + sp.name = fresh.clone(); + let disp_raw = self + .raw_root + .as_ref() + .and_then(|r| r.get_table("Tools")) + .and_then(|t| t.get_table(&orig_disp)) + .cloned(); + mod_name_map.insert(orig_disp.clone(), fresh.clone()); + cloned_splines.push((fresh.clone(), sp, disp_raw)); + fresh + } else { + orig_disp.clone() + }; + if new_disp != orig_disp { + pp.displacement_op = Some(new_disp.clone()); + if let Some(ref mut tbl) = raw_tbl { + rewrite_source_op_in_table(tbl, &orig_disp, &new_disp); + } + } + } + + mod_name_map.insert(src_op, new_mod.clone()); + cloned_paths.push((new_mod, pp, raw_tbl)); + } + } + } + + // Insert cloned modifiers into `Comp` and `raw_root.Tools`. + for (name, sp, raw_tbl) in cloned_splines { + self.splines.insert(name.clone(), sp); + if let (Some(root), Some(tbl)) = (self.raw_root.as_mut(), raw_tbl) { + let tools = ensure_table_mut(root, "Tools", Some("ordered")); + tools.set(LuaKey::Str(name), LuaValue::Table(tbl)); + } + } + for (name, pp, raw_tbl) in cloned_paths { + self.poly_paths.insert(name.clone(), pp); + if let (Some(root), Some(tbl)) = (self.raw_root.as_mut(), raw_tbl) { + let tools = ensure_table_mut(root, "Tools", Some("ordered")); + tools.set(LuaKey::Str(name), LuaValue::Table(tbl)); + } + } + + // Build and insert the duplicated nodes. + let mut created_ids = Vec::with_capacity(dup_specs.len()); + for (orig_id, new_name) in dup_specs { + let mut cloned = self.nodes[orig_id.0].clone(); + let new_id = NodeId(self.nodes.len()); + cloned.id = new_id; + cloned.name = new_name.clone(); + cloned.pos = [cloned.pos[0] + offset[0], cloned.pos[1] + offset[1]]; + + for binding in cloned.inputs.values_mut() { + if let Some(src) = binding.source_op.as_mut() { + if let Some(mapped) = node_name_map.get(src).or_else(|| mod_name_map.get(src)) { + *src = mapped.clone(); + } + } + } + + // Update `cloned.raw` ViewInfo.Pos and SourceOp references. + set_view_info_pos(&mut cloned.raw, cloned.pos); + for (old_s, new_s) in node_name_map.iter().chain(mod_name_map.iter()) { + rewrite_source_op_in_table(&mut cloned.raw, old_s, new_s); + } + + let raw_copy = cloned.raw.clone(); + self.nodes.push(cloned); + self.node_by_name.insert(new_name.clone(), new_id); + if let Some(root) = self.raw_root.as_mut() { + let tools = ensure_table_mut(root, "Tools", Some("ordered")); + tools.set(LuaKey::Str(new_name), LuaValue::Table(raw_copy)); + } + created_ids.push(new_id); + } + + self.revision += 1; + created_ids + } + + fn generate_unique_name_excluding(&self, hint: &str, reserved: &HashSet) -> String { + let base = sanitize_lua_ident(hint); + if !self.name_exists(&base) && !reserved.contains(&base) { + return base; + } + let mut idx = 1usize; + loop { + let candidate = format!("{base}_{idx}"); + if !self.name_exists(&candidate) && !reserved.contains(&candidate) { + return candidate; + } + idx += 1; + } + } + + /// Renames `id` to `new_name`, updating `node_by_name`, `raw_root.Tools`, and all `SourceOp` + /// references across every node's `inputs`, `raw` AST tables, and `raw_root`. + pub fn rename_node(&mut self, id: NodeId, new_name: &str) -> Result { + if id.0 >= self.nodes.len() { + return Err(format!("invalid node id {}", id.0)); + } + let trimmed = new_name.trim(); + if trimmed.is_empty() { + return Err("node name cannot be empty".to_owned()); + } + if !is_valid_lua_ident(trimmed) { + return Err(format!("'{trimmed}' is not a valid Fusion/Lua identifier")); + } + + let old_name = self.nodes[id.0].name.clone(); + if trimmed == old_name { + return Ok(old_name); + } + if self.name_exists(trimmed) { + return Err(format!("a node or modifier named '{trimmed}' already exists")); + } + + self.nodes[id.0].name = trimmed.to_owned(); + if self.node_by_name.get(&old_name) == Some(&id) { + self.node_by_name.remove(&old_name); + } + self.node_by_name.insert(trimmed.to_owned(), id); + + // Rewrite all `SourceOp` references across all nodes' typed `inputs` and `raw` tables. + for node in &mut self.nodes { + for binding in node.inputs.values_mut() { + if binding.source_op.as_deref() == Some(old_name.as_str()) { + binding.source_op = Some(trimmed.to_owned()); + } + } + rewrite_source_op_in_table(&mut node.raw, &old_name, trimmed); + } + + // Rewrite `SourceOp` inside `shakes` modifiers. + for shake in self.shakes.values_mut() { + for binding in shake.inputs.values_mut() { + if binding.source_op.as_deref() == Some(old_name.as_str()) { + binding.source_op = Some(trimmed.to_owned()); + } + } + } + + // Rename key in `raw_root.Tools` in place (preserving order) and rewrite all SourceOp refs. + if let Some(root) = self.raw_root.as_mut() { + if let Some(tools) = root.get_table_mut("Tools") { + for (k, _) in &mut tools.entries { + if let LuaKey::Str(s) = k { + if s == &old_name { + *s = trimmed.to_owned(); + break; + } + } + } + } + rewrite_source_op_in_table(root, &old_name, trimmed); + if root.get_str("ActiveTool") == Some(old_name.as_str()) { + root.set( + LuaKey::Str("ActiveTool".to_owned()), + LuaValue::String(trimmed.to_owned()), + ); + } + } + + self.revision += 1; + Ok(trimmed.to_owned()) + } + + /// Returns `true` if wiring `from_node -> to_node` would create a cycle (including self-loops). + pub fn would_create_cycle(&self, from_node: NodeId, to_node: NodeId) -> bool { + if from_node.0 >= self.nodes.len() || to_node.0 >= self.nodes.len() { + return false; + } + if from_node == to_node { + return true; + } + let mut visited: HashSet = HashSet::new(); + let mut stack: Vec = vec![from_node]; + while let Some(curr) = stack.pop() { + if !visited.insert(curr) { + continue; + } + for binding in self.nodes[curr.0].inputs.values() { + if let Some(src_name) = &binding.source_op { + if let Some(src_id) = self.find_node(src_name) { + if src_id == to_node { + return true; + } + if !visited.contains(&src_id) { + stack.push(src_id); + } + } + } + } + } + false + } + + /// Connects `from_node`'s `from_output` (typically `"Output"` or `"Mask"`) to `to_node`'s + /// `to_input` port, rejecting self-loops and cycles. + pub fn connect_output( + &mut self, + from_node: NodeId, + from_output: &str, + to_node: NodeId, + to_input: &str, + ) -> Result<(), String> { + if from_node.0 >= self.nodes.len() { + return Err(format!("invalid source node id {}", from_node.0)); + } + if to_node.0 >= self.nodes.len() { + return Err(format!("invalid target node id {}", to_node.0)); + } + if from_node == to_node { + return Err("cannot connect a node to itself".to_owned()); + } + if self.would_create_cycle(from_node, to_node) { + return Err(format!( + "connecting '{}' -> '{}' would create a cycle", + self.nodes[from_node.0].name, self.nodes[to_node.0].name + )); + } + + let src_name = self.nodes[from_node.0].name.clone(); + let out_name = if from_output.is_empty() { + "Output" + } else { + from_output + }; + + let dst = &mut self.nodes[to_node.0]; + let entry = dst + .inputs + .entry(to_input.to_owned()) + .or_insert(InputBinding { + value: None, + source_op: None, + source_output: None, + expression: None, + }); + entry.source_op = Some(src_name.clone()); + entry.source_output = Some(out_name.to_owned()); + + let in_tbl = ensure_table_mut(&mut dst.raw, "Inputs", None); + let port_tbl = ensure_table_mut(in_tbl, to_input, Some("Input")); + port_tbl.set(LuaKey::Str("SourceOp".to_owned()), LuaValue::String(src_name)); + port_tbl.set( + LuaKey::Str("Source".to_owned()), + LuaValue::String(out_name.to_owned()), + ); + + self.revision += 1; + Ok(()) + } + + /// Disconnects `to_node`'s `to_input` port. Returns `true` if a connection was removed. + pub fn disconnect(&mut self, to_node: NodeId, to_input: &str) -> bool { + if to_node.0 >= self.nodes.len() { + return false; + } + let dst = &mut self.nodes[to_node.0]; + let Some(entry) = dst.inputs.get_mut(to_input) else { + return false; + }; + if entry.source_op.is_none() && entry.source_output.is_none() { + return false; + } + entry.source_op = None; + entry.source_output = None; + + if let Some(in_tbl) = dst.raw.get_table_mut("Inputs") { + if let Some(port_tbl) = in_tbl.get_table_mut(to_input) { + port_tbl.remove(&LuaKey::Str("SourceOp".to_owned())); + port_tbl.remove(&LuaKey::Str("Source".to_owned())); + } + } + + self.revision += 1; + true + } + + /// Splices `new_node` into the pipe `upstream -> downstream.downstream_input`: + /// connects `upstream -> new_node.(default_main_input_port)` and + /// `new_node -> downstream.downstream_input`. + pub fn splice_node_into_pipe( + &mut self, + new_node: NodeId, + upstream: NodeId, + downstream: NodeId, + downstream_input: &str, + ) -> Result<(), String> { + if new_node.0 >= self.nodes.len() + || upstream.0 >= self.nodes.len() + || downstream.0 >= self.nodes.len() + { + return Err("invalid node id for splice_node_into_pipe".to_owned()); + } + if new_node == upstream || new_node == downstream || upstream == downstream { + return Err("splice_node_into_pipe requires three distinct nodes".to_owned()); + } + if self.would_create_cycle(upstream, new_node) + || self.would_create_cycle(new_node, downstream) + { + return Err("splicing node into pipe would create a cycle".to_owned()); + } + + let upstream_name = self.nodes[upstream.0].name.as_str(); + let upstream_output = self.nodes[downstream.0] + .inputs + .get(downstream_input) + .filter(|b| b.source_op.as_deref() == Some(upstream_name)) + .and_then(|b| b.source_output.clone()) + .unwrap_or_else(|| "Output".to_owned()); + + let mid_port = default_main_input_port(&self.nodes[new_node.0].kind); + self.connect_output(upstream, &upstream_output, new_node, mid_port)?; + self.connect_output(new_node, "Output", downstream, downstream_input)?; + Ok(()) + } + + /// Sets a static parameter value on `node`'s `input` port. + pub fn set_input_value(&mut self, node: NodeId, input: &str, value: ParamValue) -> bool { + if node.0 >= self.nodes.len() { + return false; + } + let n = &mut self.nodes[node.0]; + let entry = n.inputs.entry(input.to_owned()).or_insert(InputBinding { + value: None, + source_op: None, + source_output: None, + expression: None, + }); + entry.value = Some(value.clone()); + + let in_tbl = ensure_table_mut(&mut n.raw, "Inputs", None); + let port_tbl = ensure_table_mut(in_tbl, input, Some("Input")); + port_tbl.set(LuaKey::Str("Value".to_owned()), param_value_to_lua(&value)); + + self.revision += 1; + true + } + + /// Sets or clears a Fusion Lua expression on `node`'s `input` port. + pub fn set_input_expression( + &mut self, + node: NodeId, + input: &str, + expr: Option, + ) -> bool { + if node.0 >= self.nodes.len() { + return false; + } + let normalized = expr.and_then(|s| { + let trimmed = s.trim(); + if trimmed.is_empty() { + None + } else { + Some(s) + } + }); + + let n = &mut self.nodes[node.0]; + let entry = n.inputs.entry(input.to_owned()).or_insert(InputBinding { + value: None, + source_op: None, + source_output: None, + expression: None, + }); + entry.expression = normalized.clone(); + + if let Some(expr_str) = normalized { + let in_tbl = ensure_table_mut(&mut n.raw, "Inputs", None); + let port_tbl = ensure_table_mut(in_tbl, input, Some("Input")); + port_tbl.set( + LuaKey::Str("Expression".to_owned()), + LuaValue::String(expr_str), + ); + } else if let Some(in_tbl) = n.raw.get_table_mut("Inputs") { + if let Some(port_tbl) = in_tbl.get_table_mut(input) { + port_tbl.remove(&LuaKey::Str("Expression".to_owned())); + } + } + + self.revision += 1; + true + } + + /// Toggles `PassThrough` (bypass) on `node` and returns the new passthrough state. + pub fn toggle_passthrough(&mut self, node: NodeId) -> bool { + if node.0 >= self.nodes.len() { + return false; + } + let n = &mut self.nodes[node.0]; + n.bypassed = !n.bypassed; + if n.bypassed { + n.raw + .set(LuaKey::Str("PassThrough".to_owned()), LuaValue::Bool(true)); + } else { + n.raw.remove(&LuaKey::Str("PassThrough".to_owned())); + } + self.revision += 1; + n.bypassed + } + + /// Moves `node` to flow position `pos` and updates `ViewInfo.Pos` in `node.raw`. + pub fn set_node_pos(&mut self, node: NodeId, pos: [f32; 2]) { + if node.0 >= self.nodes.len() { + return; + } + let n = &mut self.nodes[node.0]; + n.pos = pos; + set_view_info_pos(&mut n.raw, pos); + self.revision += 1; + } + + /// Inserts or updates a scalar keyframe at `(frame, value)` on `node`'s `input`. + /// - If `input` is already connected to a `BezierSpline`, updates/inserts the keyframe there. + /// - Otherwise creates a new `BezierSpline` named `` (deduplicated), + /// wires `input` to it (`SourceOp = spline_name, Source = "Value"`), and inserts the keyframe. + /// Returns the spline's name. + pub fn set_keyframe( + &mut self, + node: NodeId, + input: &str, + frame: f64, + value: f64, + ) -> Result { + if node.0 >= self.nodes.len() { + return Err(format!("invalid node id {}", node.0)); + } + if !frame.is_finite() || !value.is_finite() { + return Err("keyframe frame and value must be finite numbers".to_owned()); + } + + let existing_spline = self.nodes[node.0] + .inputs + .get(input) + .and_then(|b| b.source_op.clone()) + .filter(|op| self.splines.contains_key(op)); + + let spline_name = if let Some(sp_name) = existing_spline { + let sp = self.splines.get_mut(&sp_name).expect("spline exists"); + upsert_keyframe(sp, frame, value); + sp_name + } else { + let hint = format!("{}{}", self.nodes[node.0].name, input); + let sp_name = self.generate_unique_name("BezierSpline", Some(&hint)); + let color = default_spline_color(&sp_name); + let spline = BezierSpline { + name: sp_name.clone(), + color, + keyframes: vec![Keyframe::new(frame, value)], + }; + self.splines.insert(sp_name.clone(), spline); + + let n = &mut self.nodes[node.0]; + let entry = n.inputs.entry(input.to_owned()).or_insert(InputBinding { + value: None, + source_op: None, + source_output: None, + expression: None, + }); + entry.source_op = Some(sp_name.clone()); + entry.source_output = Some("Value".to_owned()); + + let in_tbl = ensure_table_mut(&mut n.raw, "Inputs", None); + let port_tbl = ensure_table_mut(in_tbl, input, Some("Input")); + port_tbl.set( + LuaKey::Str("SourceOp".to_owned()), + LuaValue::String(sp_name.clone()), + ); + port_tbl.set( + LuaKey::Str("Source".to_owned()), + LuaValue::String("Value".to_owned()), + ); + + sp_name + }; + + self.revision += 1; + Ok(spline_name) + } + + /// Removes the keyframe at `frame` from `spline_name`. Returns `true` if a keyframe was deleted. + pub fn delete_keyframe(&mut self, spline_name: &str, frame: f64) -> bool { + let Some(sp) = self.splines.get_mut(spline_name) else { + return false; + }; + let Some(pos) = sp + .keyframes + .iter() + .position(|kf| (kf.time - frame).abs() < 1e-6) + else { + return false; + }; + sp.keyframes.remove(pos); + self.revision += 1; + true + } +} + +#[derive(Clone, Debug)] +struct HistoryEntry { + label: String, + snapshot: Comp, + coalesce_key: Option, +} + +/// Snapshot-based undo/redo history stack for [`Comp`] with transaction groups and drag coalescing. +#[derive(Clone, Debug)] +pub struct CompHistory { + undo_stack: VecDeque, + redo_stack: Vec, + max_depth: usize, + active_group: Option<(String, Comp)>, + group_depth: usize, + /// Position in `undo_stack` corresponding to the last saved state (`Some(0)` means clean at + /// depth 0; `None` means the saved state is no longer reachable via undo/redo). + saved_undo_depth: Option, + saved_revision: Option, +} + +impl Default for CompHistory { + fn default() -> Self { + Self::new() + } +} + +impl CompHistory { + pub fn new() -> Self { + Self::with_max_depth(DEFAULT_MAX_HISTORY) + } + + pub fn with_max_depth(max_depth: usize) -> Self { + Self { + undo_stack: VecDeque::new(), + redo_stack: Vec::new(), + max_depth: max_depth.max(1), + active_group: None, + group_depth: 0, + saved_undo_depth: None, + saved_revision: None, + } + } + + pub fn max_depth(&self) -> usize { + self.max_depth + } + + pub fn can_undo(&self) -> bool { + !self.undo_stack.is_empty() + } + + pub fn can_redo(&self) -> bool { + !self.redo_stack.is_empty() + } + + pub fn undo_len(&self) -> usize { + self.undo_stack.len() + } + + pub fn redo_len(&self) -> usize { + self.redo_stack.len() + } + + pub fn undo_label(&self) -> Option<&str> { + self.undo_stack.back().map(|e| e.label.as_str()) + } + + pub fn redo_label(&self) -> Option<&str> { + self.redo_stack.last().map(|e| e.label.as_str()) + } + + pub fn in_group(&self) -> bool { + self.group_depth > 0 + } + + /// Clears all undo/redo entries and any active transaction group. + pub fn clear(&mut self) { + self.undo_stack.clear(); + self.redo_stack.clear(); + self.active_group = None; + self.group_depth = 0; + self.saved_undo_depth = None; + self.saved_revision = None; + } + + /// Records the current state of `comp` as the clean saved point. + pub fn mark_saved(&mut self, comp: &Comp) { + self.saved_undo_depth = Some(self.undo_stack.len()); + self.saved_revision = Some(comp.revision); + } + + pub fn saved_revision(&self) -> Option { + self.saved_revision + } + + /// Returns `true` if `comp` has unsaved modifications relative to the last [`Self::mark_saved`]. + pub fn is_dirty(&self, comp: &Comp) -> bool { + match self.saved_undo_depth { + Some(depth) if depth == self.undo_stack.len() => { + // If an edit was pushed via coalescing or outside history after mark_saved, + // check whether we're still at the saved depth without an active modified group. + if let Some((_, ref snap)) = self.active_group { + comp.revision != snap.revision + } else { + false + } + } + _ => self.saved_revision != Some(comp.revision), + } + } + + /// Pushes a snapshot of `comp` BEFORE applying a discrete mutation. + /// No-op if currently inside a [`Self::begin_group`] transaction. + pub fn push_snapshot(&mut self, comp: &Comp, label: impl Into) { + if self.group_depth > 0 { + return; + } + self.push_entry(HistoryEntry { + label: label.into(), + snapshot: comp.clone(), + coalesce_key: None, + }); + } + + /// Pushes a snapshot of `comp` BEFORE applying a continuous mutation (such as dragging a node + /// or scrubbing a parameter slider). Consecutive calls with the same `key` coalesce into a + /// single undo step preserving the initial pre-drag snapshot. + /// No-op if currently inside a [`Self::begin_group`] transaction. + pub fn push_coalesced( + &mut self, + comp: &Comp, + label: impl Into, + key: impl Into, + ) { + if self.group_depth > 0 { + return; + } + let key_str = key.into(); + let label_str = label.into(); + if self.redo_stack.is_empty() { + if let Some(top) = self.undo_stack.back_mut() { + if top.coalesce_key.as_deref() == Some(key_str.as_str()) { + top.label = label_str; + return; + } + } + } + self.push_entry(HistoryEntry { + label: label_str, + snapshot: comp.clone(), + coalesce_key: Some(key_str), + }); + } + + /// Breaks coalescing on the top undo entry so subsequent edits with the same key start a new + /// undo step (e.g. on pointer release). + pub fn break_coalescing(&mut self) { + if let Some(top) = self.undo_stack.back_mut() { + top.coalesce_key = None; + } + } + + /// Begins a transaction group. All mutations until the matching [`Self::commit_group`] collapse + /// into a single undo step. Supports nesting. + pub fn begin_group(&mut self, comp: &Comp, label: impl Into) { + if self.group_depth == 0 { + self.active_group = Some((label.into(), comp.clone())); + } + self.group_depth += 1; + } + + /// Commits the current transaction group. When the outermost group closes, pushes one undo + /// entry if `comp.revision` changed since `begin_group`. Returns `true` if an entry was added. + pub fn commit_group(&mut self, comp: &Comp) -> bool { + if self.group_depth == 0 { + return false; + } + self.group_depth -= 1; + if self.group_depth > 0 { + return false; + } + let Some((label, snapshot)) = self.active_group.take() else { + return false; + }; + if comp.revision == snapshot.revision { + return false; + } + self.push_entry(HistoryEntry { + label, + snapshot, + coalesce_key: None, + }); + true + } + + /// Cancels the active transaction group and restores `comp` to its pre-group state. + pub fn cancel_group(&mut self, comp: &mut Comp) -> bool { + if self.group_depth == 0 { + return false; + } + self.group_depth = 0; + let Some((_, snapshot)) = self.active_group.take() else { + return false; + }; + let prev_rev = comp.revision; + *comp = snapshot; + if comp.revision != prev_rev { + comp.revision = prev_rev.max(comp.revision) + 1; + } + true + } + + /// Undoes the most recent edit, restoring `comp` to the saved snapshot. + /// Always advances `comp.revision` monotonically so downstream caches invalidate cleanly. + pub fn undo(&mut self, comp: &mut Comp) -> bool { + if self.group_depth > 0 { + self.group_depth = 1; + self.commit_group(comp); + } + let Some(entry) = self.undo_stack.pop_back() else { + return false; + }; + let prev_rev = comp.revision; + let redo_entry = HistoryEntry { + label: entry.label, + snapshot: comp.clone(), + coalesce_key: None, + }; + self.redo_stack.push(redo_entry); + *comp = entry.snapshot; + comp.revision = prev_rev.max(comp.revision) + 1; + true + } + + /// Redoes the most recently undone edit. + /// Always advances `comp.revision` monotonically so downstream caches invalidate cleanly. + pub fn redo(&mut self, comp: &mut Comp) -> bool { + let Some(entry) = self.redo_stack.pop() else { + return false; + }; + let prev_rev = comp.revision; + let undo_entry = HistoryEntry { + label: entry.label, + snapshot: comp.clone(), + coalesce_key: None, + }; + self.undo_stack.push_back(undo_entry); + *comp = entry.snapshot; + comp.revision = prev_rev.max(comp.revision) + 1; + true + } + + fn push_entry(&mut self, entry: HistoryEntry) { + // Any saved state that lived in the redo branch is now unreachable. + if let Some(saved_depth) = self.saved_undo_depth { + if saved_depth > self.undo_stack.len() { + self.saved_undo_depth = None; + } + } + self.redo_stack.clear(); + self.undo_stack.push_back(entry); + while self.undo_stack.len() > self.max_depth { + self.undo_stack.pop_front(); + self.saved_undo_depth = self.saved_undo_depth.and_then(|d| d.checked_sub(1)); + } + } +} + +fn sanitize_lua_ident(raw: &str) -> String { + let mut out = String::with_capacity(raw.len()); + for ch in raw.chars() { + if ch.is_ascii_alphanumeric() || ch == '_' { + out.push(ch); + } else { + out.push('_'); + } + } + if out.is_empty() || out.as_bytes()[0].is_ascii_digit() { + out.insert(0, '_'); + } + if !is_valid_lua_ident(&out) { + out.push('_'); + } + out +} + +fn collect_node_source_ops(node: &Node, out: &mut HashSet) { + for binding in node.inputs.values() { + if let Some(src) = &binding.source_op { + out.insert(src.clone()); + } + } + collect_source_ops_in_table(&node.raw, out); +} + +fn collect_source_ops_in_table(tbl: &LuaTable, out: &mut HashSet) { + for (k, v) in &tbl.entries { + if let LuaKey::Str(key) = k { + if key == "SourceOp" { + if let Some(s) = v.as_str() { + out.insert(s.to_owned()); + } + } + } + if let Some(sub) = v.as_table() { + collect_source_ops_in_table(sub, out); + } + } +} + +fn rewrite_source_op_in_table(tbl: &mut LuaTable, old_name: &str, new_name: &str) { + for (k, v) in &mut tbl.entries { + if let LuaKey::Str(key) = k { + if key == "SourceOp" { + if let LuaValue::String(s) = v { + if s == old_name { + *s = new_name.to_owned(); + } + } + } + } + if let Some(sub) = v.as_table_mut() { + rewrite_source_op_in_table(sub, old_name, new_name); + } + } +} + +fn set_view_info_pos(raw: &mut LuaTable, pos: [f32; 2]) { + let vi = ensure_table_mut(raw, "ViewInfo", Some("OperatorInfo")); + vi.set( + LuaKey::Str("Pos".to_owned()), + vec2_lua(pos[0] as f64, pos[1] as f64), + ); +} + +fn upsert_keyframe(spline: &mut BezierSpline, frame: f64, value: f64) { + if let Some(existing) = spline + .keyframes + .iter_mut() + .find(|kf| (kf.time - frame).abs() < 1e-6) + { + existing.value = value; + } else { + spline.keyframes.push(Keyframe::new(frame, value)); + spline.sort(); + } +} + +fn default_spline_color(name: &str) -> [u8; 3] { + // Deterministic vivid Fusion-like spline palette based on name hash. + const PALETTE: &[[u8; 3]] = &[ + [255, 128, 0], + [102, 204, 255], + [170, 238, 102], + [255, 102, 170], + [204, 153, 255], + [255, 221, 85], + ]; + let hash = name + .bytes() + .fold(0usize, |acc, b| acc.wrapping_mul(31).wrapping_add(b as usize)); + PALETTE[hash % PALETTE.len()] +} + +fn default_view_info_for_kind(kind: &str, pos: [f32; 2]) -> LuaTable { + let tag = match kind { + "PipeRouter" => "PipeRouterInfo", + "Underlay" => "UnderlayInfo", + "Note" | "StickyNote" => "StickyNoteInfo", + _ => "OperatorInfo", + }; + let mut vi = LuaTable { + tag: Some(tag.to_owned()), + entries: Vec::new(), + }; + vi.set( + LuaKey::Str("Pos".to_owned()), + vec2_lua(pos[0] as f64, pos[1] as f64), + ); + match kind { + "Underlay" => { + vi.set(LuaKey::Str("Size".to_owned()), vec2_lua(172.0, 166.364)); + } + "Note" | "StickyNote" => { + let mut flags = LuaTable::default(); + flags.set(LuaKey::Str("Expanded".to_owned()), LuaValue::Bool(true)); + vi.set(LuaKey::Str("Flags".to_owned()), LuaValue::Table(flags)); + vi.set(LuaKey::Str("Size".to_owned()), vec2_lua(196.0, 179.364)); + } + _ => {} + } + vi +} + +/// Returns sensible Fusion 21.1 default inputs for common tool classes so Fusion Studio opens +/// newly created nodes cleanly without errors. +fn default_inputs_for_kind(kind: &str, width: u32, height: u32) -> Vec<(String, ParamValue)> { + let w = width as f64; + let h = height as f64; + let num = |k: &str, v: f64| (k.to_owned(), ParamValue::Number(v)); + let pt = |k: &str, x: f64, y: f64| (k.to_owned(), ParamValue::Point([x, y])); + let txt = |k: &str, s: &str| (k.to_owned(), ParamValue::Text(s.to_owned())); + let fuid = |k: &str, s: &str| (k.to_owned(), ParamValue::FuId(s.to_owned())); + + match kind { + "Background" => vec![ + num("Width", w), + num("Height", h), + num("UseFrameFormatSettings", 1.0), + num("TopLeftRed", 0.0), + num("TopLeftGreen", 0.0), + num("TopLeftBlue", 0.0), + num("TopLeftAlpha", 1.0), + ], + "Merge" => vec![ + num("PerformDepthMerge", 0.0), + pt("Center", 0.5, 0.5), + num("Size", 1.0), + num("Angle", 0.0), + num("Blend", 1.0), + ], + "Transform" => vec![ + pt("Center", 0.5, 0.5), + pt("Pivot", 0.5, 0.5), + num("Size", 1.0), + num("Angle", 0.0), + ], + "Blur" => vec![fuid("Filter", "Fast Gaussian"), num("XBlurSize", 1.0)], + "Glow" => vec![num("XGlowSize", 10.0), num("Glow", 0.8)], + "SoftGlow" => vec![ + fuid("Filter", "Fast Gaussian"), + num("Gain", 2.0), + num("XGlowSize", 10.0), + ], + "BrightnessContrast" => vec![ + num("Gain", 1.0), + num("Lift", 0.0), + num("Gamma", 1.0), + num("Contrast", 0.0), + num("Brightness", 0.0), + num("Saturation", 1.0), + ], + "ColorCorrector" => vec![ + num("WheelSaturation1", 1.0), + num("MasterRGBGain", 1.0), + num("MasterRGBGamma", 1.0), + ], + "ColorGain" => vec![ + num("GainRed", 1.0), + num("GainGreen", 1.0), + num("GainBlue", 1.0), + num("GainAlpha", 1.0), + num("GammaRed", 1.0), + num("GammaGreen", 1.0), + num("GammaBlue", 1.0), + ], + "RectangleMask" => vec![ + num("MaskWidth", w), + num("MaskHeight", h), + pt("PixelAspect", 1.0, 1.0), + pt("Center", 0.5, 0.5), + num("Width", 0.5), + num("Height", 0.5), + num("CornerRadius", 0.0), + num("SoftEdge", 0.0), + ], + "EllipseMask" => vec![ + num("MaskWidth", w), + num("MaskHeight", h), + pt("PixelAspect", 1.0, 1.0), + pt("Center", 0.5, 0.5), + num("Width", 0.5), + num("Height", 0.5), + num("SoftEdge", 0.0), + ], + "PolylineMask" => vec![ + num("MaskWidth", w), + num("MaskHeight", h), + pt("PixelAspect", 1.0, 1.0), + num("SoftEdge", 0.0), + ], + "BitmapMask" => vec![ + num("MaskWidth", w), + num("MaskHeight", h), + pt("PixelAspect", 1.0, 1.0), + fuid("Channel", "Alpha"), + ], + "TextPlus" => vec![ + num("Width", w), + num("Height", h), + num("UseFrameFormatSettings", 1.0), + txt("StyledText", ""), + txt("Font", "Open Sans"), + txt("Style", "Bold"), + num("Size", 0.08), + pt("Center", 0.5, 0.5), + ], + "Loader" => vec![], + "Saver" => vec![num("ProcessWhenBlendIs00", 0.0), num("CreateDir", 1.0)], + "Displace" => vec![ + num("Type", 0.0), + num("XRefraction", 0.0), + num("YRefraction", 0.0), + num("RefractionStrength", 0.0), + ], + "FastNoise" => vec![ + num("Width", w), + num("Height", h), + num("UseFrameFormatSettings", 1.0), + num("Detail", 2.0), + num("Contrast", 1.0), + num("XScale", 2.0), + num("Seethe", 0.0), + ], + "PipeRouter" | "Underlay" => vec![], + "Switch" | "Fuse.Switch" => vec![num("Source", 0.0)], + "TimeStretcher" => vec![num("SourceTime", 0.0), num("InterpolateBetweenFrames", 0.0)], + "TimeSpeed" => vec![num("Speed", 1.0), num("Delay", 0.0)], + "Renderer3D" => vec![ + num("Width", w), + num("Height", h), + num("UseFrameFormatSettings", 1.0), + fuid("RendererType", "RendererOpenGL"), + ], + "Camera3D" => vec![num("FLength", 24.0), num("PlaneOfFocus", 5.0)], + "Merge3D" => vec![num("PassThroughLights", 1.0)], + "Transform3D" => vec![num("Transform3DOp.Scale.X", 1.0)], + "ImagePlane3D" => vec![ + num("SurfacePlaneInputs.Width", 1.0), + num("SurfacePlaneInputs.Height", 1.0), + ], + "Shape3D" => vec![fuid("Shape", "SurfacePlaneInputs")], + "Note" | "StickyNote" => vec![txt("Comments", "")], + _ => vec![], + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::expr::ExprEngine; + use std::path::Path; + + fn sample_comp() -> Comp { + let src = r#"Composition { + CurrentTime = 10, + RenderRange = { 0, 100 }, + GlobalRange = { 0, 100 }, + Prefs = { + Comp = { + FrameFormat = { + Width = 1920, + Height = 1080, + Rate = 24, + DepthFull = 3, + }, + }, + }, + Tools = ordered() { + BG1 = Background { + Inputs = { + Width = Input { Value = 1920, }, + Height = Input { Value = 1080, }, + TopLeftRed = Input { Value = 0.25, }, + }, + ViewInfo = OperatorInfo { Pos = { 100, 50 } }, + }, + BC1 = BrightnessContrast { + Inputs = { + Input = Input { + SourceOp = "BG1", + Source = "Output", + }, + Gain = Input { + SourceOp = "BC1Gain", + Source = "Value", + }, + }, + ViewInfo = OperatorInfo { Pos = { 300, 50 } }, + }, + BC1Gain = BezierSpline { + SplineColor = { Red = 255, Green = 128, Blue = 0 }, + KeyFrames = { + [0] = { 1, Flags = { Linear = true } }, + [30] = { 2, Flags = { Linear = true } }, + }, + }, + SurfaceTracker1 = SurfaceTracker { + Inputs = { + Source = Input { + SourceOp = "BC1", + Source = "Output", + }, + MeshBlob = Input { + Value = TrackingMesh { + Vertices = { 1, 2, 3 }, + }, + }, + }, + ViewInfo = OperatorInfo { Pos = { 500, 50 } }, + }, + }, +}"#; + Comp::from_fusion_str(src).expect("parse sample comp") + } + + #[test] + fn add_node_naming_and_tool_defaults() { + let mut comp = sample_comp(); + let rev0 = comp.revision; + + let t1 = comp.add_node("Transform", None, [120.0, 200.0]); + let t2 = comp.add_node("Transform", None, [240.0, 200.0]); + assert_eq!(comp.node(t1).name, "Transform1"); + assert_eq!(comp.node(t2).name, "Transform2"); + assert_eq!(comp.node(t1).pos, [120.0, 200.0]); + assert!(comp.revision >= rev0 + 2); + + let h0 = comp.add_node("Background", Some("HeroBG"), [0.0, 0.0]); + let h1 = comp.add_node("Background", Some("HeroBG"), [50.0, 0.0]); + let h2 = comp.add_node("Background", Some("HeroBG"), [100.0, 0.0]); + assert_eq!(comp.node(h0).name, "HeroBG"); + assert_eq!(comp.node(h1).name, "HeroBG_1"); + assert_eq!(comp.node(h2).name, "HeroBG_2"); + + // Cover all common Fusion 21.1 tool categories + generic fallback + let kinds = [ + "Background", + "Merge", + "Transform", + "Blur", + "Glow", + "SoftGlow", + "BrightnessContrast", + "ColorCorrector", + "ColorGain", + "RectangleMask", + "EllipseMask", + "PolylineMask", + "BitmapMask", + "TextPlus", + "Loader", + "Saver", + "Displace", + "FastNoise", + "PipeRouter", + "Switch", + "TimeStretcher", + "TimeSpeed", + "Renderer3D", + "Camera3D", + "Merge3D", + "Transform3D", + "ImagePlane3D", + "Shape3D", + "Note", + "Underlay", + "MyCustomThirdPartyTool", + ]; + for (i, kind) in kinds.iter().enumerate() { + let id = comp.add_node(kind, None, [i as f32 * 50.0, 400.0]); + assert_eq!(comp.node(id).kind, *kind); + assert!(comp.node(id).raw.get_table("ViewInfo").is_some()); + } + + // Roundtrip all newly created nodes cleanly + let s = comp.to_fusion_string(); + let reloaded = Comp::from_fusion_str(&s).expect("roundtrip added nodes"); + assert_eq!(reloaded.nodes.len(), comp.nodes.len()); + assert_eq!( + reloaded.node(reloaded.find_node("HeroBG").unwrap()).static_number("Width"), + Some(1920.0) + ); + } + + #[test] + fn connect_cycle_detection_disconnect_and_splice() { + let mut comp = sample_comp(); + let bg = comp.find_node("BG1").unwrap(); + let bc = comp.find_node("BC1").unwrap(); + let st = comp.find_node("SurfaceTracker1").unwrap(); + + // Self-loop rejected + assert!(comp.connect_output(bg, "Output", bg, "EffectMask").is_err()); + // Direct cycle BG1 -> BC1 -> BG1 rejected + assert!(comp.connect_output(bc, "Output", bg, "EffectMask").is_err()); + // Transitive cycle BG1 -> BC1 -> SurfaceTracker1 -> BG1 rejected + assert!(comp.connect_output(st, "Output", bg, "EffectMask").is_err()); + + // Splice a Blur into BG1 -> BC1.Input + let blur = comp.add_node("Blur", None, [200.0, 50.0]); + comp.splice_node_into_pipe(blur, bg, bc, "Input") + .expect("splice blur"); + assert_eq!(comp.node(blur).connected_node("Input"), Some("BG1")); + assert_eq!(comp.node(bc).connected_node("Input"), Some("Blur1")); + + // Disconnect returns true once, then false + assert!(comp.disconnect(bc, "Input")); + assert!(!comp.disconnect(bc, "Input")); + assert_eq!(comp.node(bc).connected_node("Input"), None); + + // Reconnect and verify roundtrip + comp.connect_output(blur, "Output", bc, "Input") + .expect("reconnect"); + let reloaded = Comp::from_fusion_str(&comp.to_fusion_string()).expect("roundtrip"); + assert_eq!( + reloaded.node(reloaded.find_node("BC1").unwrap()).connected_node("Input"), + Some("Blur1") + ); + } + + #[test] + fn params_expressions_passthrough_pos_and_keyframes() { + let mut comp = sample_comp(); + let bc = comp.find_node("BC1").unwrap(); + + assert!(comp.set_input_value(bc, "Gamma", ParamValue::Number(1.45))); + assert!(comp.set_input_expression(bc, "Brightness", Some("time * 0.01".to_owned()))); + assert!(comp.toggle_passthrough(bc)); + comp.set_node_pos(bc, [333.0, 77.0]); + + // Set keyframe on static input -> creates new BezierSpline and wires it + let sp_name = comp.set_keyframe(bc, "Contrast", 0.0, 0.2).expect("kf 0"); + assert_eq!(sp_name, "BC1Contrast"); + let sp_name2 = comp.set_keyframe(bc, "Contrast", 20.0, 0.8).expect("kf 20"); + assert_eq!(sp_name2, sp_name); + // Update existing keyframe at frame 20 + comp.set_keyframe(bc, "Contrast", 20.0, 0.9).expect("update kf 20"); + assert_eq!(comp.splines[&sp_name].keyframes.len(), 2); + + // Evaluate via Comp::eval_number + let expr = ExprEngine::new(); + let val_mid = comp.eval_number(comp.node(bc), "Contrast", 10.0, 0.0, &expr); + assert!((val_mid - 0.55).abs() < 1e-5, "got {val_mid}"); + + // Delete keyframe + assert!(comp.delete_keyframe(&sp_name, 20.0)); + assert!(!comp.delete_keyframe(&sp_name, 20.0)); + assert_eq!(comp.splines[&sp_name].keyframes.len(), 1); + + // Roundtrip + let reloaded = Comp::from_fusion_str(&comp.to_fusion_string()).expect("roundtrip"); + let r_bc = reloaded.node(reloaded.find_node("BC1").unwrap()); + assert!(r_bc.bypassed); + assert_eq!(r_bc.pos, [333.0, 77.0]); + assert_eq!(r_bc.static_number("Gamma"), Some(1.45)); + assert_eq!( + r_bc.inputs.get("Brightness").and_then(|b| b.expression.as_deref()), + Some("time * 0.01") + ); + assert_eq!(r_bc.connected_node("Contrast"), Some("BC1Contrast")); + assert_eq!(reloaded.splines["BC1Contrast"].keyframes.len(), 1); + + // Clear expression and un-bypass + assert!(comp.set_input_expression(bc, "Brightness", None)); + assert!(!comp.toggle_passthrough(bc)); + let reloaded2 = Comp::from_fusion_str(&comp.to_fusion_string()).expect("roundtrip 2"); + let r_bc2 = reloaded2.node(reloaded2.find_node("BC1").unwrap()); + assert!(!r_bc2.bypassed); + assert_eq!( + r_bc2.inputs.get("Brightness").and_then(|b| b.expression.as_deref()), + None + ); + } + + #[test] + fn rename_duplicate_and_delete_nodes_roundtrip() { + let mut comp = sample_comp(); + let bg = comp.find_node("BG1").unwrap(); + let bc = comp.find_node("BC1").unwrap(); + + // Rename validation + assert!(comp.rename_node(bg, "").is_err()); + assert!(comp.rename_node(bg, "123Bad").is_err()); + assert!(comp.rename_node(bg, "function").is_err()); + assert!(comp.rename_node(bg, "BC1").is_err()); + + // Rename BG1 -> PlateBG and verify BC1.Input SourceOp is rewritten + let new_name = comp.rename_node(bg, "PlateBG").expect("rename BG1"); + assert_eq!(new_name, "PlateBG"); + assert!(comp.find_node("BG1").is_none()); + assert_eq!(comp.find_node("PlateBG"), Some(bg)); + assert_eq!(comp.node(bc).connected_node("Input"), Some("PlateBG")); + + // Duplicate [PlateBG, BC1] together -> internal wire preserved, BC1Gain spline cloned + let dups = comp.duplicate_nodes(&[bg, bc], [0.0, 150.0]); + assert_eq!(dups.len(), 2); + let dup_bg = dups[0]; + let dup_bc = dups[1]; + assert_eq!(comp.node(dup_bg).name, "PlateBG_1"); + assert_eq!(comp.node(dup_bc).name, "BC1_1"); + assert_eq!(comp.node(dup_bg).pos, [100.0, 200.0]); + assert_eq!(comp.node(dup_bc).connected_node("Input"), Some("PlateBG_1")); + let dup_gain_spline = comp.node(dup_bc).connected_node("Gain").unwrap().to_owned(); + assert_ne!(dup_gain_spline, "BC1Gain"); + assert!(comp.splines.contains_key(&dup_gain_spline)); + + // Share BC1Gain with dup_bg (artificial) vs exclusive spline on dup_bc: + // Deleting dup_bc should prune `dup_gain_spline` while leaving `BC1Gain` intact. + let deleted = comp.delete_nodes(&[dup_bc]); + assert_eq!(deleted, vec!["BC1_1".to_owned()]); + assert!(!comp.splines.contains_key(&dup_gain_spline)); + assert!(comp.splines.contains_key("BC1Gain")); + + // Delete BC1 -> SurfaceTracker1.Source unwired, BC1Gain pruned, NodeId indices compact + let bc_now = comp.find_node("BC1").unwrap(); + let del2 = comp.delete_nodes(&[bc_now]); + assert_eq!(del2, vec!["BC1".to_owned()]); + assert!(!comp.splines.contains_key("BC1Gain")); + for (idx, n) in comp.nodes.iter().enumerate() { + assert_eq!(n.id, NodeId(idx)); + assert_eq!(comp.find_node(&n.name), Some(NodeId(idx))); + } + let st_now = comp.find_node("SurfaceTracker1").unwrap(); + assert_eq!(comp.node(st_now).connected_node("Source"), None); + + // Full roundtrip preserves unknown SurfaceTracker1 verbatim + all structural mutations + let reloaded = Comp::from_fusion_str(&comp.to_fusion_string()).expect("roundtrip"); + assert!(reloaded.find_node("PlateBG").is_some()); + assert!(reloaded.find_node("PlateBG_1").is_some()); + assert!(reloaded.find_node("BC1").is_none()); + assert!(reloaded.find_node("SurfaceTracker1").is_some()); + assert!(!reloaded.splines.contains_key("BC1Gain")); + let r_st = reloaded.node(reloaded.find_node("SurfaceTracker1").unwrap()); + assert_eq!(r_st.connected_node("Source"), None); + assert!( + r_st.raw + .get_table("Inputs") + .and_then(|i| i.get_table("MeshBlob")) + .is_some() + ); + } + + #[test] + fn roundtrip_mutations_on_real_20_falling_comp() { + let path = Path::new("/Volumes/Project/trees/fusion/20_falling.comp"); + if !path.exists() { + return; + } + let mut comp = Comp::from_fusion_file(path).expect("load 20_falling.comp"); + let orig_count = comp.nodes.len(); + + let blur = comp.add_node("Blur", Some("TestGlowBlur"), [1000.0, -500.0]); + let merge19 = comp.find_node("Merge19").expect("Merge19"); + comp.set_input_value(blur, "XBlurSize", ParamValue::Number(4.5)); + comp.set_input_expression(blur, "YBlurSize", Some("XBlurSize * 2".to_owned())); + comp.toggle_passthrough(blur); + let sp = comp + .set_keyframe(blur, "Blend", 2200.0, 0.5) + .expect("keyframe blend"); + comp.set_keyframe(blur, "Blend", 2250.0, 1.0) + .expect("keyframe blend 2"); + comp.connect_output(merge19, "Output", blur, "Input") + .expect("connect Merge19 -> blur"); + comp.rename_node(blur, "TestGlowBlurRenamed") + .expect("rename blur"); + + let serialized = comp.to_fusion_string(); + let reloaded = Comp::from_fusion_str(&serialized).expect("re-parse mutated 20_falling"); + assert_eq!(reloaded.nodes.len(), orig_count + 1); + let r_blur_id = reloaded + .find_node("TestGlowBlurRenamed") + .expect("TestGlowBlurRenamed"); + let r_blur = reloaded.node(r_blur_id); + assert!(r_blur.bypassed); + assert_eq!(r_blur.connected_node("Input"), Some("Merge19")); + assert_eq!(r_blur.static_number("XBlurSize"), Some(4.5)); + assert_eq!( + r_blur.inputs.get("YBlurSize").and_then(|b| b.expression.as_deref()), + Some("XBlurSize * 2") + ); + assert_eq!(reloaded.splines[&sp].keyframes.len(), 2); + } + + #[test] + fn comp_history_undo_redo_coalescing_groups_and_bounds() { + let mut comp = sample_comp(); + let mut history = CompHistory::with_max_depth(3); + history.mark_saved(&comp); + assert!(!history.is_dirty(&comp)); + assert!(!history.can_undo()); + assert!(!history.can_redo()); + + let bg = comp.find_node("BG1").unwrap(); + + // 1. Coalesced drag: 120 frames produce ONE undo step + for i in 1..=120 { + history.push_coalesced(&comp, "Move BG1", format!("drag_node:{}", bg.0)); + comp.set_node_pos(bg, [100.0 + i as f32, 50.0 + i as f32 * 0.5]); + } + history.break_coalescing(); + assert_eq!(history.undo_len(), 1); + assert_eq!(history.undo_label(), Some("Move BG1")); + assert!(history.is_dirty(&comp)); + assert_eq!(comp.node(bg).pos, [220.0, 110.0]); + + // Undo restores original pre-drag position and clears dirty flag + assert!(history.undo(&mut comp)); + assert_eq!(comp.node(bg).pos, [100.0, 50.0]); + assert!(!history.is_dirty(&comp)); + assert!(history.can_redo()); + assert_eq!(history.redo_label(), Some("Move BG1")); + + // Redo restores final dragged position + assert!(history.redo(&mut comp)); + assert_eq!(comp.node(bg).pos, [220.0, 110.0]); + assert!(history.is_dirty(&comp)); + + // 2. Redo invalidation on new edit after undo + assert!(history.undo(&mut comp)); + assert!(history.can_redo()); + history.push_snapshot(&comp, "Add Blur"); + let blur = comp.add_node("Blur", None, [200.0, 100.0]); + assert!(!history.can_redo()); + assert_eq!(history.undo_len(), 1); + + // 3. Transaction group collapses multiple mutations into one undo step + history.begin_group(&comp, "Style Blur"); + comp.set_input_value(blur, "XBlurSize", ParamValue::Number(5.0)); + history.push_snapshot(&comp, "Ignored inside group"); + comp.toggle_passthrough(blur); + assert!(history.commit_group(&comp)); + assert_eq!(history.undo_len(), 2); + assert_eq!(history.undo_label(), Some("Style Blur")); + + // No-op group doesn't push + history.begin_group(&comp, "No-op"); + assert!(!history.commit_group(&comp)); + assert_eq!(history.undo_len(), 2); + + // Cancel group restores pre-group state + history.begin_group(&comp, "Canceled"); + comp.set_node_pos(blur, [999.0, 999.0]); + assert!(history.cancel_group(&mut comp)); + assert_eq!(comp.node(blur).pos, [200.0, 100.0]); + + // 4. Bounded history depth (max_depth = 3) + history.push_snapshot(&comp, "Edit 3"); + comp.set_node_pos(blur, [210.0, 100.0]); + history.push_snapshot(&comp, "Edit 4"); + comp.set_node_pos(blur, [220.0, 100.0]); + assert_eq!(history.undo_len(), 3); + + history.clear(); + assert!(!history.can_undo()); + assert!(!history.can_redo()); + } +} diff --git a/crates/model/src/lib.rs b/crates/model/src/lib.rs index cb6d5b9f5e06073f3ea2d031c2d662c4c45f78ef..cc96e1fe68744bdaed729dc05f0494eaea31224a 100644 --- a/crates/model/src/lib.rs +++ b/crates/model/src/lib.rs @@ -1,4 +1,5 @@ pub mod comp; +pub mod edit; pub mod expr; pub mod lua_value; pub mod spline; @@ -7,6 +8,7 @@ pub use comp::{ BitDepth, ClipSpec, ClsEntry, Comp, InputBinding, Node, NodeId, ParamValue, PortRole, SaverSpec, default_main_input_port, is_supported_tool, }; +pub use edit::{CompHistory, DEFAULT_MAX_HISTORY}; pub use expr::ExprEngine; pub use lua_value::{LuaKey, LuaTable, LuaValue, ParseError, parse_lua}; pub use spline::{BezierSpline, Gradient, GradientStop, HandleMode, KeyFlags, Keyframe, PolyPath, PolyPoint}; diff --git a/crates/model/src/lua_value.rs b/crates/model/src/lua_value.rs index 2f5e45fd6de7d56b63aa645425ef6f71a083f418..27ddf7b44ec6ef9bc7aa48220aabc89d73f88e12 100644 --- a/crates/model/src/lua_value.rs +++ b/crates/model/src/lua_value.rs @@ -649,7 +649,7 @@ fn is_ident_cont(b: u8) -> bool { b.is_ascii_alphanumeric() || b == b'_' } -fn is_valid_lua_ident(s: &str) -> bool { +pub(crate) fn is_valid_lua_ident(s: &str) -> bool { let bytes = s.as_bytes(); if bytes.is_empty() || !is_ident_start(bytes[0]) || !bytes[1..].iter().all(|&b| is_ident_cont(b)) { return false; diff --git a/scripts/fusion_probes.py b/scripts/fusion_probes.py index 9492c3cbea159d8c8d0dee24d42b000cc7d9b7b6..4a8e68b987ed6b344e794124150b6a40b821d729 100644 --- a/scripts/fusion_probes.py +++ b/scripts/fusion_probes.py @@ -1317,6 +1317,604 @@ def build_probe_tier1_d(): return comp_path, "tier1_d", cases +def build_probe_mask_softedge(): + """Shale #8 probe: Mask SoftEdge (small..huge), BorderWidth, Solid=0, Filter, ClippingMode, BitmapMask, PolylineMask, and Blur ClippingMode=None + Merge shift.""" + grid = generate_grid_chart() + cases = [ + (0, "ellipse_soft0.01"), + (1, "ellipse_soft0.05_small"), + (2, "ellipse_soft0.18_large"), + (3, "rect_soft0.06_clip_none_edge"), + (4, "rect_soft0.06_clip_frame_edge"), + (5, "rect_soft0.06_box"), + (6, "rect_border0.04_solid0"), + (7, "ellipse_border0.03_soft0.02"), + (8, "bitmap_luma_low_high_soft0.04"), + (9, "bitmap_alpha_soft0.25_inv"), + (10, "poly_soft0.08"), + (11, "blur_clip_none_merge_shift"), + ] + nodes = [ + make_loader("GridLoader", grid, post_mult=1), + """\t\tBlackBG = Background { +\t\t\tInputs = { Width = Input { Value = 640, }, Height = Input { Value = 360, }, TopLeftAlpha = Input { Value = 1, }, }, +\t\t}, +\t\tWhiteFG = Background { +\t\t\tInputs = { Width = Input { Value = 640, }, Height = Input { Value = 360, }, TopLeftRed = Input { Value = 1, }, TopLeftGreen = Input { Value = 1, }, TopLeftBlue = Input { Value = 1, }, TopLeftAlpha = Input { Value = 1, }, }, +\t\t}, +\t\t-- f00: Ellipse SoftEdge=0.01 +\t\tMask_0 = EllipseMask { Inputs = { MaskWidth = Input { Value = 640, }, MaskHeight = Input { Value = 360, }, Width = Input { Value = 0.4, }, Height = Input { Value = 0.4, }, SoftEdge = Input { Value = 0.01, }, }, }, +\t\tOp_0 = Merge { Inputs = { Background = Input { SourceOp = "BlackBG", Source = "Output", }, Foreground = Input { SourceOp = "WhiteFG", Source = "Output", }, EffectMask = Input { SourceOp = "Mask_0", Source = "Mask", }, }, }, + +\t\t-- f01: Small Ellipse SoftEdge=0.05 (like 20_falling Ellipse1) +\t\tMask_1 = EllipseMask { Inputs = { MaskWidth = Input { Value = 640, }, MaskHeight = Input { Value = 360, }, Center = Input { Value = { 0.35, 0.45 }, }, Width = Input { Value = 0.12, }, Height = Input { Value = 0.12, }, SoftEdge = Input { Value = 0.05, }, Filter = Input { Value = FuID { "Fast Gaussian" }, }, ClippingMode = Input { Value = FuID { "None" }, }, }, }, +\t\tOp_1 = Merge { Inputs = { Background = Input { SourceOp = "BlackBG", Source = "Output", }, Foreground = Input { SourceOp = "WhiteFG", Source = "Output", }, EffectMask = Input { SourceOp = "Mask_1", Source = "Mask", }, }, }, + +\t\t-- f02: Large Ellipse SoftEdge=0.18 +\t\tMask_2 = EllipseMask { Inputs = { MaskWidth = Input { Value = 640, }, MaskHeight = Input { Value = 360, }, Width = Input { Value = 0.35, }, Height = Input { Value = 0.35, }, SoftEdge = Input { Value = 0.18, }, Filter = Input { Value = FuID { "Fast Gaussian" }, }, }, }, +\t\tOp_2 = Merge { Inputs = { Background = Input { SourceOp = "BlackBG", Source = "Output", }, Foreground = Input { SourceOp = "WhiteFG", Source = "Output", }, EffectMask = Input { SourceOp = "Mask_2", Source = "Mask", }, }, }, + +\t\t-- f03: Rect SoftEdge=0.06 near bottom edge, ClippingMode=None +\t\tMask_3 = RectangleMask { Inputs = { MaskWidth = Input { Value = 640, }, MaskHeight = Input { Value = 360, }, Center = Input { Value = { 0.5, 0.25 }, }, Width = Input { Value = 0.9, }, Height = Input { Value = 0.5, }, SoftEdge = Input { Value = 0.06, }, ClippingMode = Input { Value = FuID { "None" }, }, }, }, +\t\tOp_3 = Merge { Inputs = { Background = Input { SourceOp = "BlackBG", Source = "Output", }, Foreground = Input { SourceOp = "WhiteFG", Source = "Output", }, EffectMask = Input { SourceOp = "Mask_3", Source = "Mask", }, }, }, + +\t\t-- f04: Rect SoftEdge=0.06 near bottom edge, ClippingMode=Frame +\t\tMask_4 = RectangleMask { Inputs = { MaskWidth = Input { Value = 640, }, MaskHeight = Input { Value = 360, }, Center = Input { Value = { 0.5, 0.25 }, }, Width = Input { Value = 0.9, }, Height = Input { Value = 0.5, }, SoftEdge = Input { Value = 0.06, }, ClippingMode = Input { Value = FuID { "Frame" }, }, }, }, +\t\tOp_4 = Merge { Inputs = { Background = Input { SourceOp = "BlackBG", Source = "Output", }, Foreground = Input { SourceOp = "WhiteFG", Source = "Output", }, EffectMask = Input { SourceOp = "Mask_4", Source = "Mask", }, }, }, + +\t\t-- f05: Rect SoftEdge=0.06 Filter=Box +\t\tMask_5 = RectangleMask { Inputs = { MaskWidth = Input { Value = 640, }, MaskHeight = Input { Value = 360, }, Width = Input { Value = 0.45, }, Height = Input { Value = 0.45, }, SoftEdge = Input { Value = 0.06, }, Filter = Input { Value = FuID { "Box" }, }, }, }, +\t\tOp_5 = Merge { Inputs = { Background = Input { SourceOp = "BlackBG", Source = "Output", }, Foreground = Input { SourceOp = "WhiteFG", Source = "Output", }, EffectMask = Input { SourceOp = "Mask_5", Source = "Mask", }, }, }, + +\t\t-- f06: Rect BorderWidth=0.04 Solid=0 (outline) +\t\tMask_6 = RectangleMask { Inputs = { MaskWidth = Input { Value = 640, }, MaskHeight = Input { Value = 360, }, Width = Input { Value = 0.45, }, Height = Input { Value = 0.45, }, Solid = Input { Value = 0, }, BorderWidth = Input { Value = 0.04, }, }, }, +\t\tOp_6 = Merge { Inputs = { Background = Input { SourceOp = "BlackBG", Source = "Output", }, Foreground = Input { SourceOp = "WhiteFG", Source = "Output", }, EffectMask = Input { SourceOp = "Mask_6", Source = "Mask", }, }, }, + +\t\t-- f07: Ellipse BorderWidth=0.03 Solid=1 SoftEdge=0.02 +\t\tMask_7 = EllipseMask { Inputs = { MaskWidth = Input { Value = 640, }, MaskHeight = Input { Value = 360, }, Width = Input { Value = 0.30, }, Height = Input { Value = 0.30, }, Solid = Input { Value = 1, }, BorderWidth = Input { Value = 0.03, }, SoftEdge = Input { Value = 0.02, }, }, }, +\t\tOp_7 = Merge { Inputs = { Background = Input { SourceOp = "BlackBG", Source = "Output", }, Foreground = Input { SourceOp = "WhiteFG", Source = "Output", }, EffectMask = Input { SourceOp = "Mask_7", Source = "Mask", }, }, }, + +\t\t-- f08: BitmapMask Luminance + Low/High + SoftEdge=0.04 +\t\tMask_8 = BitmapMask { Inputs = { Image = Input { SourceOp = "GridLoader", Source = "Output", }, Channel = Input { Value = FuID { "Luminance" }, }, Low = Input { Value = 0.2, }, High = Input { Value = 0.8, }, SoftEdge = Input { Value = 0.04, }, }, }, +\t\tOp_8 = Merge { Inputs = { Background = Input { SourceOp = "BlackBG", Source = "Output", }, Foreground = Input { SourceOp = "WhiteFG", Source = "Output", }, EffectMask = Input { SourceOp = "Mask_8", Source = "Mask", }, }, }, + +\t\t-- f09: BitmapMask Alpha + huge SoftEdge=0.25 + Invert=1 +\t\tBmSrc_9 = RectangleMask { Inputs = { MaskWidth = Input { Value = 640, }, MaskHeight = Input { Value = 360, }, Width = Input { Value = 0.35, }, Height = Input { Value = 0.35, }, }, }, +\t\tBmImg_9 = Merge { Inputs = { Background = Input { SourceOp = "BlackBG", Source = "Output", }, Foreground = Input { SourceOp = "WhiteFG", Source = "Output", }, EffectMask = Input { SourceOp = "BmSrc_9", Source = "Mask", }, }, }, +\t\tMask_9 = BitmapMask { Inputs = { Image = Input { SourceOp = "BmImg_9", Source = "Output", }, Channel = Input { Value = FuID { "Luminance" }, }, SoftEdge = Input { Value = 0.25, }, Invert = Input { Value = 1, }, }, }, +\t\tOp_9 = Merge { Inputs = { Background = Input { SourceOp = "BlackBG", Source = "Output", }, Foreground = Input { SourceOp = "WhiteFG", Source = "Output", }, EffectMask = Input { SourceOp = "Mask_9", Source = "Mask", }, }, }, + +\t\t-- f10: PolylineMask SoftEdge=0.08 +\t\tMask_10 = PolylineMask { +\t\t\tInputs = { +\t\t\t\tMaskWidth = Input { Value = 640, }, +\t\t\t\tMaskHeight = Input { Value = 360, }, +\t\t\t\tSoftEdge = Input { Value = 0.08, }, +\t\t\t\tPolyline = Input { +\t\t\t\t\tValue = Polyline { +\t\t\t\t\t\tClosed = true, +\t\t\t\t\t\tPoints = { +\t\t\t\t\t\t\t{ Linear = true, X = -0.25, Y = -0.20, RX = 0.16, RY = 0 }, +\t\t\t\t\t\t\t{ Linear = true, X = 0.25, Y = -0.20, LX = -0.16, LY = 0, RX = -0.08, RY = 0.14 }, +\t\t\t\t\t\t\t{ Linear = true, X = 0.0, Y = 0.25, LX = 0.08, LY = -0.14 }, +\t\t\t\t\t\t}, +\t\t\t\t\t}, +\t\t\t\t}, +\t\t\t}, +\t\t}, +\t\tOp_10 = Merge { Inputs = { Background = Input { SourceOp = "BlackBG", Source = "Output", }, Foreground = Input { SourceOp = "WhiteFG", Source = "Output", }, EffectMask = Input { SourceOp = "Mask_10", Source = "Mask", }, }, }, + +\t\t-- f11: Blur ClippingMode=None on solid WhiteFG shifted down by Merge (20_falling Blur2->Merge7!) +\t\tBl_11 = Blur { Inputs = { Input = Input { SourceOp = "WhiteFG", Source = "Output", }, Filter = Input { Value = FuID { "Fast Gaussian" }, }, XBlurSize = Input { Value = 25.0, }, ClippingMode = Input { Value = FuID { "None" }, }, }, }, +\t\tOp_11 = Merge { Inputs = { Background = Input { SourceOp = "BlackBG", Source = "Output", }, Foreground = Input { SourceOp = "Bl_11", Source = "Output", }, Center = Input { Value = { 0.5, 0.20 }, }, Size = Input { Value = 1.1, }, }, },""", + ] + splines = [] + prev = "BlackBG" + for f, _label in cases: + bl = {c[0]: (1.0 if c[0] == f else 0.0) for c in cases} + sname = f"Mse_{f}_Blend" + splines.append(step_spline(sname, bl)) + nodes.append(f"""\t\tSw_{f} = Merge {{ +\t\t\tInputs = {{ +\t\t\t\tBlend = Input {{ SourceOp = "{sname}", Source = "Value", }}, +\t\t\t\tBackground = Input {{ SourceOp = "{prev}", Source = "Output", }}, +\t\t\t\tForeground = Input {{ SourceOp = "Op_{f}", Source = "Output", }}, +\t\t\t}}, +\t\t}},""") + prev = f"Sw_{f}" + nodes.append(make_saver(prev, "mask_softedge")) + comp_path = local_root() / "comps" / "probe_mask_softedge.comp" + comp_path.write_text(make_comp("\n".join(nodes + splines), len(cases) - 1, w=640, h=360)) + return comp_path, "mask_softedge", cases + + +def build_probe_displace_wave(): + """Shale #9 probe: Displace XY default channels/offset/scale, CustomTool sine wave + Lua expr, FastNoise Discontinuous/Type=1/high-Seethe.""" + grid = generate_grid_chart() + cases = [ + (0, "disp_xy_defaults_grid"), + (1, "disp_xy_grad_off0"), + (2, "disp_xy_grad_off-0.5"), + (3, "disp_xy_ch1_ch0_off-0.5"), + (4, "disp_custom_wave_expr"), + (5, "fastnoise_disc_detail10_grad"), + (6, "fastnoise_disc_high_seethe"), + (7, "fastnoise_type1_2d_disc"), + (8, "fastnoise_type0_xscale0_disc"), + ] + nodes = [ + make_loader("GridLoader", grid, post_mult=1), + """\t\tBlackBG = Background { Inputs = { Width = Input { Value = 512, }, Height = Input { Value = 512, }, TopLeftAlpha = Input { Value = 1, }, }, }, +\t\tGradH = Background { +\t\t\tInputs = { +\t\t\t\tWidth = Input { Value = 512, }, Height = Input { Value = 512, }, +\t\t\t\tType = Input { Value = FuID { "Horizontal" }, }, +\t\t\t\tTopLeftRed = Input { Value = 0, }, TopLeftGreen = Input { Value = 0, }, TopLeftBlue = Input { Value = 0, }, TopLeftAlpha = Input { Value = 1, }, +\t\t\t\tTopRightRed = Input { Value = 1, }, TopRightGreen = Input { Value = 0.25, }, TopRightBlue = Input { Value = 0.75, }, TopRightAlpha = Input { Value = 1, }, +\t\t\t}, +\t\t}, +\t\t-- f00: Displace Type=1 default XChannel/YChannel/XOffset/YOffset +\t\tOp_0 = Displace { +\t\t\tInputs = { +\t\t\t\tType = Input { Value = 1, }, +\t\t\t\tXRefraction = Input { Value = 0.05, }, +\t\t\t\tYRefraction = Input { Value = 0.05, }, +\t\t\t\tInput = Input { SourceOp = "GridLoader", Source = "Output", }, +\t\t\t\tForeground = Input { SourceOp = "GradH", Source = "Output", }, +\t\t\t}, +\t\t}, +\t\t-- f01: Displace Type=1 XOffset=0 XRefraction=0.08 +\t\tOp_1 = Displace { +\t\t\tInputs = { +\t\t\t\tType = Input { Value = 1, }, +\t\t\t\tXOffset = Input { Value = 0.0, }, +\t\t\t\tXRefraction = Input { Value = 0.08, }, +\t\t\t\tInput = Input { SourceOp = "GridLoader", Source = "Output", }, +\t\t\t\tForeground = Input { SourceOp = "GradH", Source = "Output", }, +\t\t\t}, +\t\t}, +\t\t-- f02: Displace Type=1 XOffset=-0.5 XRefraction=0.08 +\t\tOp_2 = Displace { +\t\t\tInputs = { +\t\t\t\tType = Input { Value = 1, }, +\t\t\t\tXOffset = Input { Value = -0.5, }, +\t\t\t\tXRefraction = Input { Value = 0.08, }, +\t\t\t\tInput = Input { SourceOp = "GridLoader", Source = "Output", }, +\t\t\t\tForeground = Input { SourceOp = "GradH", Source = "Output", }, +\t\t\t}, +\t\t}, +\t\t-- f03: Displace Type=1 XChannel=1 YChannel=0 XOffset=-0.5 YOffset=-0.5 +\t\tOp_3 = Displace { +\t\t\tInputs = { +\t\t\t\tType = Input { Value = 1, }, +\t\t\t\tXChannel = Input { Value = 1, }, +\t\t\t\tYChannel = Input { Value = 0, }, +\t\t\t\tXOffset = Input { Value = -0.5, }, +\t\t\t\tYOffset = Input { Value = -0.5, }, +\t\t\t\tXRefraction = Input { Value = 0.05, }, +\t\t\t\tYRefraction = Input { Value = 0.05, }, +\t\t\t\tInput = Input { SourceOp = "GridLoader", Source = "Output", }, +\t\t\t\tForeground = Input { SourceOp = "GradH", Source = "Output", }, +\t\t\t}, +\t\t}, +\t\t-- f04: CustomTool sine wave + Displace Lua expression +\t\tCustomWave1 = Custom { +\t\t\tInputs = { +\t\t\t\tRedExpression = Input { Value = "sin(x*w*n1 + n2*n1*w)*0.5+0.5", }, +\t\t\t\tGreenExpression = Input { Value = "sin(y*w*n1 + n2*n1*w)*0.5+0.5", }, +\t\t\t\tBlueExpression = Input { Value = "0", }, +\t\t\t\tAlphaExpression = Input { Value = "1", }, +\t\t\t\tImage1 = Input { SourceOp = "GridLoader", Source = "Output", }, +\t\t\t\tNumberIn1 = Input { Value = 0.7413, }, +\t\t\t\tNumberIn2 = Input { Value = 1.5, }, +\t\t\t\tWaveDirection = Input { Value = 0, }, +\t\t\t\tWaveAmp = Input { Value = 0.04, }, +\t\t\t}, +\t\t\tUserControls = ordered() { +\t\t\t\tWaveDirection = { INP_Default = 0, INPID_InputControl = "ComboControl", LINKID_DataType = "Number", }, +\t\t\t\tWaveAmp = { INP_Default = 0.04, INPID_InputControl = "SliderControl", LINKID_DataType = "Number", }, +\t\t\t}, +\t\t}, +\t\tOp_4 = Displace { +\t\t\tInputs = { +\t\t\t\tType = Input { Value = 1, }, +\t\t\t\tXChannel = Input { Value = 1, }, +\t\t\t\tYChannel = Input { Value = 0, }, +\t\t\t\tXOffset = Input { Value = -0.5, }, +\t\t\t\tYOffset = Input { Value = -0.5, }, +\t\t\t\tXRefraction = Input { Expression = "(CustomWave1.WaveDirection == 0) and (CustomWave1.WaveAmp) or 0", }, +\t\t\t\tYRefraction = Input { Expression = "(CustomWave1.WaveDirection == 1) and (CustomWave1.WaveAmp) or 0", }, +\t\t\t\tInput = Input { SourceOp = "GridLoader", Source = "Output", }, +\t\t\t\tForeground = Input { SourceOp = "CustomWave1", Source = "Output", }, +\t\t\t}, +\t\t}, +\t\t-- f05: FastNoise Discontinuous=1 Detail=10 XScale=0 YScale=80 Type=1 Gradient +\t\tOp_5 = FastNoise { +\t\t\tInputs = { +\t\t\t\tWidth = Input { Value = 512, }, Height = Input { Value = 512, }, +\t\t\t\tDetail = Input { Value = 10, }, +\t\t\t\tLockXY = Input { Value = 0, }, +\t\t\t\tXScale = Input { Value = 0, }, +\t\t\t\tYScale = Input { Value = 80, }, +\t\t\t\tSeethe = Input { Value = 8.377, }, +\t\t\t\tDiscontinuous = Input { Value = 1, }, +\t\t\t\tType = Input { Value = 1, }, +\t\t\t\tColor1Alpha = Input { Value = 1, }, +\t\t\t\tGradient = Input { +\t\t\t\t\tValue = Gradient { +\t\t\t\t\t\tColors = { +\t\t\t\t\t\t\t[0] = { 0, 0, 0, 1 }, +\t\t\t\t\t\t\t[0.428] = { 0.5, 0, 0, 1 }, +\t\t\t\t\t\t\t[0.552] = { 0.5, 0, 0, 1 }, +\t\t\t\t\t\t\t[1] = { 1, 1, 1, 1 }, +\t\t\t\t\t\t}, +\t\t\t\t\t}, +\t\t\t\t}, +\t\t\t}, +\t\t}, +\t\t-- f06: FastNoise Discontinuous=1 Detail=10 XScale=10 YScale=10 Seethe=29820 +\t\tOp_6 = FastNoise { +\t\t\tInputs = { +\t\t\t\tWidth = Input { Value = 512, }, Height = Input { Value = 512, }, +\t\t\t\tDetail = Input { Value = 10, }, +\t\t\t\tXScale = Input { Value = 10, }, +\t\t\t\tYScale = Input { Value = 10, }, +\t\t\t\tSeethe = Input { Value = 29820, }, +\t\t\t\tDiscontinuous = Input { Value = 1, }, +\t\t\t\tColor1Alpha = Input { Value = 1, }, +\t\t\t}, +\t\t}, +\t\t-- f07: FastNoise Type=1 linear 0..1 gradient, 2D (XScale=10, YScale=10), Discontinuous=1 +\t\tOp_7 = FastNoise { +\t\t\tInputs = { +\t\t\t\tWidth = Input { Value = 512, }, Height = Input { Value = 512, }, +\t\t\t\tDetail = Input { Value = 10, }, +\t\t\t\tXScale = Input { Value = 10, }, +\t\t\t\tYScale = Input { Value = 10, }, +\t\t\t\tSeethe = Input { Value = 8.377, }, +\t\t\t\tDiscontinuous = Input { Value = 1, }, +\t\t\t\tType = Input { Value = 1, }, +\t\t\t\tGradient = Input { Value = Gradient { Colors = { [0] = { 0, 0, 0, 1 }, [1] = { 1, 1, 1, 1 } }, }, }, +\t\t\t}, +\t\t}, +\t\t-- f08: FastNoise Type=0 TwoColor, XScale=0 YScale=80, Discontinuous=1 +\t\tOp_8 = FastNoise { +\t\t\tInputs = { +\t\t\t\tWidth = Input { Value = 512, }, Height = Input { Value = 512, }, +\t\t\t\tDetail = Input { Value = 10, }, +\t\t\t\tLockXY = Input { Value = 0, }, +\t\t\t\tXScale = Input { Value = 0, }, +\t\t\t\tYScale = Input { Value = 80, }, +\t\t\t\tSeethe = Input { Value = 8.377, }, +\t\t\t\tDiscontinuous = Input { Value = 1, }, +\t\t\t\tColor1Alpha = Input { Value = 1, }, +\t\t\t}, +\t\t},""", + ] + splines = [] + prev = "BlackBG" + for f, _label in cases: + bl = {c[0]: (1.0 if c[0] == f else 0.0) for c in cases} + sname = f"Dw_{f}_Blend" + splines.append(step_spline(sname, bl)) + nodes.append(f"""\t\tSw_{f} = Merge {{ +\t\t\tInputs = {{ +\t\t\t\tBlend = Input {{ SourceOp = "{sname}", Source = "Value", }}, +\t\t\t\tBackground = Input {{ SourceOp = "{prev}", Source = "Output", }}, +\t\t\t\tForeground = Input {{ SourceOp = "Op_{f}", Source = "Output", }}, +\t\t\t}}, +\t\t}},""") + prev = f"Sw_{f}" + nodes.append(make_saver(prev, "displace_wave")) + comp_path = local_root() / "comps" / "probe_displace_wave.comp" + comp_path.write_text(make_comp("\n".join(nodes + splines), len(cases) - 1)) + return comp_path, "displace_wave", cases + + +def build_probe_vortex_cc(): + """Shale #10 probe: Vortex warp + ColorCorrector TintMode & Shadows/Midtones/Highlights wheels.""" + grid = generate_grid_chart() + chart = generate_color_chart() + cases = [ + (0, "vortex_default"), + (1, "vortex_s0.6_a2.5_p2"), + (2, "vortex_s3.82_a2.1_p3.3"), + (3, "vortex_offcenter_neg"), + (4, "cc_tintmode0_len1_sat1.52"), + (5, "cc_tintmode1_len1_sat1.52"), + (6, "cc_tintmode0_len0.5"), + (7, "cc_tintmode1_len0.5"), + (8, "cc_smh_wheels"), + (9, "cc_smh_lgg"), + ] + nodes = [ + make_loader("GridLoader", grid, post_mult=1), + make_loader("ChartLoader", chart, post_mult=1), + """\t\tBlackBG = Background { Inputs = { Width = Input { Value = 512, }, Height = Input { Value = 512, }, TopLeftAlpha = Input { Value = 1, }, }, }, +\t\tOp_0 = Vortex { Inputs = { Input = Input { SourceOp = "GridLoader", Source = "Output", }, Size = Input { Value = 0.5, }, Angle = Input { Value = 1.0, }, Power = Input { Value = 1.0, }, }, }, +\t\tOp_1 = Vortex { Inputs = { Input = Input { SourceOp = "GridLoader", Source = "Output", }, Size = Input { Value = 0.6, }, Angle = Input { Value = 2.5, }, Power = Input { Value = 2.0, }, }, }, +\t\tOp_2 = Vortex { Inputs = { Input = Input { SourceOp = "GridLoader", Source = "Output", }, Size = Input { Value = 3.82, }, Angle = Input { Value = 2.1, }, Power = Input { Value = 3.3, }, }, }, +\t\tOp_3 = Vortex { Inputs = { Input = Input { SourceOp = "GridLoader", Source = "Output", }, Center = Input { Value = { 0.3, 0.7 }, }, Size = Input { Value = 0.5, }, Angle = Input { Value = -2.0, }, Power = Input { Value = 1.5, }, }, }, +\t\tOp_4 = ColorCorrector { Inputs = { Input = Input { SourceOp = "ChartLoader", Source = "Output", }, WheelTintAngle1 = Input { Value = -0.24, }, WheelTintLength1 = Input { Value = 1.0, }, WheelSaturation1 = Input { Value = 1.52, }, TintMode = Input { Value = 0, }, }, }, +\t\tOp_5 = ColorCorrector { Inputs = { Input = Input { SourceOp = "ChartLoader", Source = "Output", }, WheelTintAngle1 = Input { Value = -0.24, }, WheelTintLength1 = Input { Value = 1.0, }, WheelSaturation1 = Input { Value = 1.52, }, TintMode = Input { Value = 1, }, }, }, +\t\tOp_6 = ColorCorrector { Inputs = { Input = Input { SourceOp = "ChartLoader", Source = "Output", }, WheelTintAngle1 = Input { Value = -0.24, }, WheelTintLength1 = Input { Value = 0.5, }, TintMode = Input { Value = 0, }, }, }, +\t\tOp_7 = ColorCorrector { Inputs = { Input = Input { SourceOp = "ChartLoader", Source = "Output", }, WheelTintAngle1 = Input { Value = -0.24, }, WheelTintLength1 = Input { Value = 0.5, }, TintMode = Input { Value = 1, }, }, }, +\t\tOp_8 = ColorCorrector { Inputs = { Input = Input { SourceOp = "ChartLoader", Source = "Output", }, WheelTintAngle2 = Input { Value = 0.1, }, WheelTintLength2 = Input { Value = 0.6, }, WheelHue3 = Input { Value = 0.2, }, WheelSaturation4 = Input { Value = 1.5, }, }, }, +\t\tOp_9 = ColorCorrector { Inputs = { Input = Input { SourceOp = "ChartLoader", Source = "Output", }, ShadowsRGBGain = Input { Value = 0.7, }, MidtonesRGBGamma = Input { Value = 1.4, }, HighlightsRGBGain = Input { Value = 1.25, }, }, },""", + ] + splines = [] + prev = "BlackBG" + for f, _label in cases: + bl = {c[0]: (1.0 if c[0] == f else 0.0) for c in cases} + sname = f"Vcc_{f}_Blend" + splines.append(step_spline(sname, bl)) + nodes.append(f"""\t\tSw_{f} = Merge {{ +\t\t\tInputs = {{ +\t\t\t\tBlend = Input {{ SourceOp = "{sname}", Source = "Value", }}, +\t\t\t\tBackground = Input {{ SourceOp = "{prev}", Source = "Output", }}, +\t\t\t\tForeground = Input {{ SourceOp = "Op_{f}", Source = "Output", }}, +\t\t\t}}, +\t\t}},""") + prev = f"Sw_{f}" + nodes.append(make_saver(prev, "vortex_cc")) + comp_path = local_root() / "comps" / "probe_vortex_cc.comp" + comp_path.write_text(make_comp("\n".join(nodes + splines), len(cases) - 1)) + return comp_path, "vortex_cc", cases + + +def build_probe_moon_3d(): + """Shale #10 probe: Shape3D Sphere default radius + 1:1 Camera3D w/ 16:9 Aperture + mismatched BG/FG Merge Size + FastNoise Contrast/Brightness.""" + grid = generate_grid_chart() + cases = [ + (0, "sphere_cam_1x1_ap16x9"), + (1, "merge_bg1024x512_fg256_s0.6"), + (2, "fastnoise_low_contrast_neg_bright"), + ] + nodes = [ + make_loader("GridLoader", grid, post_mult=1), + """\t\tBlackBG = Background { Inputs = { Width = Input { Value = 512, }, Height = Input { Value = 512, }, TopLeftAlpha = Input { Value = 1, }, }, }, +\t\tWhite256 = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftRed = Input { Value = 1, }, TopLeftGreen = Input { Value = 0.8, }, TopLeftBlue = Input { Value = 0.2, }, TopLeftAlpha = Input { Value = 1, }, }, }, +\t\tDark1024 = Background { Inputs = { Width = Input { Value = 1024, }, Height = Input { Value = 512, }, TopLeftRed = Input { Value = 0.1, }, TopLeftGreen = Input { Value = 0.1, }, TopLeftBlue = Input { Value = 0.2, }, TopLeftAlpha = Input { Value = 1, }, }, }, +\t\t-- f00: Exact 60_moon_guide_u Shape3D1 + Camera3D1 + Renderer3D1 (512x512 1:1 with 16:9 Aperture) +\t\tSph0 = Shape3D { +\t\t\tInputs = { +\t\t\t\tShape = Input { Value = FuID { "SurfaceSphereInputs" }, }, +\t\t\t\t["MtlStdInputs.Diffuse.Color.Red"] = Input { Value = 0.8, }, +\t\t\t\t["MtlStdInputs.Diffuse.Color.Green"] = Input { Value = 0.8, }, +\t\t\t\t["MtlStdInputs.Diffuse.Color.Blue"] = Input { Value = 0.8, }, +\t\t\t}, +\t\t}, +\t\tCam0 = Camera3D { +\t\t\tInputs = { +\t\t\t\t["Transform3DOp.Translate.Z"] = Input { Value = 6.17286473705227, }, +\t\t\t\tAoV = Input { Value = 19.2642683071402, }, +\t\t\t\tFilmGate = Input { Value = FuID { "BMD_URSA_4K_16x9" }, }, +\t\t\t\tApertureW = Input { Value = 0.831496062992126, }, +\t\t\t\tApertureH = Input { Value = 0.467716535433071, }, +\t\t\t}, +\t\t}, +\t\tM3D0 = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "Sph0", Source = "Output", }, SceneInput2 = Input { SourceOp = "Cam0", Source = "Output", }, }, }, +\t\tOp_0 = Renderer3D { Inputs = { Width = Input { Value = 512, }, Height = Input { Value = 512, }, SceneInput = Input { SourceOp = "M3D0", Source = "Output", }, }, }, + +\t\t-- f01: Merge 256x256 FG onto 1024x512 BG at Size=0.6, then scaled to 512x512 +\t\tM_1 = Merge { Inputs = { Background = Input { SourceOp = "Dark1024", Source = "Output", }, Foreground = Input { SourceOp = "White256", Source = "Output", }, Size = Input { Value = 0.6, }, }, }, +\t\tOp_1 = BetterResize { Inputs = { Input = Input { SourceOp = "M_1", Source = "Output", }, Width = Input { Value = 512, }, Height = Input { Value = 512, }, }, }, + +\t\t-- f02: Exact Noise_1 from 60_moon_guide_u (Detail=0.39, Contrast=0.23, Brightness=-0.4, Discontinuous=1, Type=1) +\t\tOp_2 = FastNoise { +\t\t\tInputs = { +\t\t\t\tWidth = Input { Value = 512, }, Height = Input { Value = 512, }, +\t\t\t\tDetail = Input { Value = 0.39, }, +\t\t\t\tContrast = Input { Value = 0.23, }, +\t\t\t\tBrightness = Input { Value = -0.4, }, +\t\t\t\tXScale = Input { Value = 28.1, }, +\t\t\t\tYScale = Input { Value = 10, }, +\t\t\t\tAngle = Input { Value = 114.8, }, +\t\t\t\tDiscontinuous = Input { Value = 1, }, +\t\t\t\tType = Input { Value = 1, }, +\t\t\t\tColor1Alpha = Input { Value = 1, }, +\t\t\t}, +\t\t},""", + ] + splines = [] + prev = "BlackBG" + for f, _label in cases: + bl = {c[0]: (1.0 if c[0] == f else 0.0) for c in cases} + sname = f"M3_{f}_Blend" + splines.append(step_spline(sname, bl)) + nodes.append(f"""\t\tSw_{f} = Merge {{ +\t\t\tInputs = {{ +\t\t\t\tBlend = Input {{ SourceOp = "{sname}", Source = "Value", }}, +\t\t\t\tBackground = Input {{ SourceOp = "{prev}", Source = "Output", }}, +\t\t\t\tForeground = Input {{ SourceOp = "Op_{f}", Source = "Output", }}, +\t\t\t}}, +\t\t}},""") + prev = f"Sw_{f}" + nodes.append(make_saver(prev, "moon_3d")) + comp_path = local_root() / "comps" / "probe_moon_3d.comp" + comp_path.write_text(make_comp("\n".join(nodes + splines), len(cases) - 1)) + return comp_path, "moon_3d", cases + + +def generate_greenscreen_chart(w=512, h=512) -> str: + """512x512 RGB ramp spanning typical green-screen shades, skin tones, grays, and primaries.""" + p = local_root() / "assets" / "greenscreen_chart.png" + buf = bytearray(w * h * 4) + for y in range(h): + v = y / (h - 1) + for x in range(w): + u = x / (w - 1) + if y < h // 2: + # Top half: varied green-screen shades around (0.38, 0.58, 0.53) and (0.16, 0.72, 0.23) + # u varies luminance/exposure, v varies greenness/saturation + t = v * 2.0 + r = max(0.0, min(1.0, (0.05 + 0.55 * u) * (1.0 - 0.5 * (1.0 - t)))) + g = max(0.0, min(1.0, 0.25 + 0.65 * u + 0.15 * (1.0 - t))) + b = max(0.0, min(1.0, (0.05 + 0.55 * u) * (0.3 + 0.7 * t))) + else: + # Bottom half: hue wheel + skin/neutral stripes + t = (v - 0.5) * 2.0 + if t < 0.5: + # Hue sweep at high sat + h6 = u * 6.0 + c = 0.75 + x_c = c * (1.0 - abs((h6 % 2.0) - 1.0)) + m = 0.15 + if h6 < 1: r, g, b = c+m, x_c+m, m + elif h6 < 2: r, g, b = x_c+m, c+m, m + elif h6 < 3: r, g, b = m, c+m, x_c+m + elif h6 < 4: r, g, b = m, x_c+m, c+m + elif h6 < 5: r, g, b = x_c+m, m, c+m + else: r, g, b = c+m, m, x_c+m + else: + # Skin tone to gray to teal gradient + s = (t - 0.5) * 2.0 + r = 0.85 * (1.0 - u) + 0.25 * u + g = 0.65 * (1.0 - u) + 0.58 * u + b = 0.55 * (1.0 - u) + 0.53 * u + r = r * (1.0 - 0.4 * s) + 0.4 * s + g = g * (1.0 - 0.4 * s) + 0.4 * s + b = b * (1.0 - 0.4 * s) + 0.4 * s + idx = (y * w + x) * 4 + buf[idx] = int(round(max(0.0, min(1.0, r)) * 255)) + buf[idx + 1] = int(round(max(0.0, min(1.0, g)) * 255)) + buf[idx + 2] = int(round(max(0.0, min(1.0, b)) * 255)) + buf[idx + 3] = 255 + write_png_rgba(p, w, h, bytes(buf)) + return f"{CONTAINER_ROOT}/assets/greenscreen_chart.png" + + +def build_probe_ultrakey(): + """Shale #10 probe: UltraKeyer exact matte/threshold/range/PostMultiply/MatteBlur parity.""" + gs = generate_greenscreen_chart() + cases = [ + (0, "uk_bg_only_pm1"), + (1, "uk_bg_only_pm0_over_red"), + (2, "uk_crazy_uk1_exact_over_red"), + (3, "uk_crazy_uk2_exact_over_red"), + (4, "uk_sep_0.2_spill_0.5"), + (5, "uk_alpha_only_uk1"), + (6, "uk_alpha_only_uk2"), + ] + nodes = [ + make_loader("GSLoader", gs, post_mult=1), + """\t\tBlackBG = Background { Inputs = { Width = Input { Value = 512, }, Height = Input { Value = 512, }, TopLeftAlpha = Input { Value = 1, }, }, }, +\t\tRedBG = Background { Inputs = { Width = Input { Value = 512, }, Height = Input { Value = 512, }, TopLeftRed = Input { Value = 0.9, }, TopLeftGreen = Input { Value = 0.1, }, TopLeftBlue = Input { Value = 0.1, }, TopLeftAlpha = Input { Value = 1, }, }, }, +\t\t-- f00: basic green key, PostMultiply=1 (default) +\t\tOp_0 = UltraKeyer { +\t\t\tInputs = { +\t\t\t\tBackgroundRed = Input { Value = 0.383215, }, +\t\t\t\tBackgroundGreen = Input { Value = 0.583642, }, +\t\t\t\tBackgroundBlue = Input { Value = 0.530770, }, +\t\t\t\tInput = Input { SourceOp = "GSLoader", Source = "Output", }, +\t\t\t}, +\t\t}, +\t\t-- f01: basic green key, PostMultiply=0 merged over RedBG +\t\tUK_1 = UltraKeyer { +\t\t\tInputs = { +\t\t\t\tBackgroundRed = Input { Value = 0.383215, }, +\t\t\t\tBackgroundGreen = Input { Value = 0.583642, }, +\t\t\t\tBackgroundBlue = Input { Value = 0.530770, }, +\t\t\t\tPostMultiplyImage = Input { Value = 0, }, +\t\t\t\tInput = Input { SourceOp = "GSLoader", Source = "Output", }, +\t\t\t}, +\t\t}, +\t\tOp_1 = Merge { Inputs = { Background = Input { SourceOp = "RedBG", Source = "Output", }, Foreground = Input { SourceOp = "UK_1", Source = "Output", }, }, }, +\t\t-- f02: exact UltraKeyer1 from 30_ground_is_crazy001 merged over RedBG +\t\tUK_2 = UltraKeyer { +\t\t\tInputs = { +\t\t\t\tBackgroundRed = Input { Value = 0.383215069770813, }, +\t\t\t\tBackgroundGreen = Input { Value = 0.583642303943634, }, +\t\t\t\tBackgroundBlue = Input { Value = 0.530769824981689, }, +\t\t\t\tRedLow = Input { Value = 0.400122076272964, }, +\t\t\t\tRedHigh = Input { Value = 0.424994289875031, }, +\t\t\t\tGreenLow = Input { Value = 0.534645617008209, }, +\t\t\t\tGreenHigh = Input { Value = 0.552941203117371, }, +\t\t\t\tBlueLow = Input { Value = 0.496787965297699, }, +\t\t\t\tBlueHigh = Input { Value = 0.557503640651703, }, +\t\t\t\tLuminanceLow = Input { Value = 0.338475614786148, }, +\t\t\t\tLuminanceHigh = Input { Value = 0.566201269626617, }, +\t\t\t\tPostMultiplyImage = Input { Value = 0, }, +\t\t\t\tInput = Input { SourceOp = "GSLoader", Source = "Output", }, +\t\t\t}, +\t\t}, +\t\tOp_2 = Merge { Inputs = { Background = Input { SourceOp = "RedBG", Source = "Output", }, Foreground = Input { SourceOp = "UK_2", Source = "Output", }, }, }, +\t\t-- f03: exact UltraKeyer2 from 30_ground_is_crazy001 merged over RedBG +\t\tUK_3 = UltraKeyer { +\t\t\tInputs = { +\t\t\t\tBackgroundRed = Input { Value = 0.162176, }, +\t\t\t\tBackgroundGreen = Input { Value = 0.724, }, +\t\t\t\tBackgroundBlue = Input { Value = 0.225100288, }, +\t\t\t\tRedLow = Input { Value = 0.414969086647034, }, +\t\t\t\tRedHigh = Input { Value = 0.419638365507126, }, +\t\t\t\tGreenLow = Input { Value = 0.546013593673706, }, +\t\t\t\tGreenHigh = Input { Value = 0.547783613204956, }, +\t\t\t\tBlueLow = Input { Value = 0.515922784805298, }, +\t\t\t\tBlueHigh = Input { Value = 0.519722282886505, }, +\t\t\t\tLuminanceLow = Input { Value = 0.439078360795975, }, +\t\t\t\tLuminanceHigh = Input { Value = 0.440360099077225, }, +\t\t\t\tFringeGamma = Input { Value = 0.861, }, +\t\t\t\tFringeShape = Input { Value = 0.906, }, +\t\t\t\tMatteBlur = Input { Value = 0.24, }, +\t\t\t\tLowMatteThreshold = Input { Value = 0.706, }, +\t\t\t\tHigh = Input { Value = 0.783, }, +\t\t\t\tPostMultiplyImage = Input { Value = 0, }, +\t\t\t\tInput = Input { SourceOp = "GSLoader", Source = "Output", }, +\t\t\t}, +\t\t}, +\t\tOp_3 = Merge { Inputs = { Background = Input { SourceOp = "RedBG", Source = "Output", }, Foreground = Input { SourceOp = "UK_3", Source = "Output", }, }, }, +\t\t-- f04: MatteSeparation + SpillSuppression +\t\tOp_4 = UltraKeyer { +\t\t\tInputs = { +\t\t\t\tBackgroundRed = Input { Value = 0.16, }, +\t\t\t\tBackgroundGreen = Input { Value = 0.72, }, +\t\t\t\tBackgroundBlue = Input { Value = 0.22, }, +\t\t\t\tMatteSeparation = Input { Value = 0.2, }, +\t\t\t\tSpillSuppression = Input { Value = 0.5, }, +\t\t\t\tInput = Input { SourceOp = "GSLoader", Source = "Output", }, +\t\t\t}, +\t\t}, +\t\t-- f05: Visualize alpha of UK_2 directly as grayscale RGB +\t\tOp_5 = ChannelBoolean { +\t\t\tInputs = { +\t\t\t\tToRed = Input { Value = 3, }, +\t\t\t\tToGreen = Input { Value = 3, }, +\t\t\t\tToBlue = Input { Value = 3, }, +\t\t\t\tToAlpha = Input { Value = 16, }, +\t\t\t\tBackground = Input { SourceOp = "UK_2", Source = "Output", }, +\t\t\t}, +\t\t}, +\t\t-- f06: Visualize alpha of UK_3 directly as grayscale RGB +\t\tOp_6 = ChannelBoolean { +\t\t\tInputs = { +\t\t\t\tToRed = Input { Value = 3, }, +\t\t\t\tToGreen = Input { Value = 3, }, +\t\t\t\tToBlue = Input { Value = 3, }, +\t\t\t\tToAlpha = Input { Value = 16, }, +\t\t\t\tBackground = Input { SourceOp = "UK_3", Source = "Output", }, +\t\t\t}, +\t\t},""", + ] + splines = [] + prev = "BlackBG" + for f, _label in cases: + bl = {c[0]: (1.0 if c[0] == f else 0.0) for c in cases} + sname = f"UK_{f}_Blend" + splines.append(step_spline(sname, bl)) + nodes.append(f"""\t\tSw_{f} = Merge {{ +\t\t\tInputs = {{ +\t\t\t\tBlend = Input {{ SourceOp = "{sname}", Source = "Value", }}, +\t\t\t\tBackground = Input {{ SourceOp = "{prev}", Source = "Output", }}, +\t\t\t\tForeground = Input {{ SourceOp = "Op_{f}", Source = "Output", }}, +\t\t\t}}, +\t\t}},""") + prev = f"Sw_{f}" + nodes.append(make_saver(prev, "ultrakey")) + comp_path = local_root() / "comps" / "probe_ultrakey.comp" + comp_path.write_text(make_comp("\n".join(nodes + splines), len(cases) - 1)) + return comp_path, "ultrakey", cases + + def main(): ensure_dirs() which = [a for a in sys.argv[1:] if not a.startswith("--")] or ["merge"] @@ -1326,10 +1924,15 @@ def main(): "cam3d": build_probe_cam3d, "cam3d_fov": build_probe_cam3d_fov, "mask": build_probe_mask, + "mask_softedge": build_probe_mask_softedge, "xf": build_probe_transform, "blur": build_probe_blur, "color_ops": build_probe_color_ops, "displace": build_probe_displace, + "displace_wave": build_probe_displace_wave, + "vortex_cc": build_probe_vortex_cc, + "moon_3d": build_probe_moon_3d, + "ultrakey": build_probe_ultrakey, "glow": build_probe_glow, "text": build_probe_text, "noise_text": build_probe_noise_text, diff --git a/scripts/gen_compatibility.py b/scripts/gen_compatibility.py index c5ca85b02611b40509705ac8b2aa925cda551918..b1989b687e57b019325f272905bfa6fe1be00267 100755 --- a/scripts/gen_compatibility.py +++ b/scripts/gen_compatibility.py @@ -68,7 +68,7 @@ TOOL_METADATA: Sequence[ToolMeta] = ( # Color & Depth ToolMeta("BrightnessContrast", "Color & Depth", "`color_ops`, `tier1_d`", "0.0%–0.1%", "Gain, Lift, Gamma, Contrast, Brightness, Saturation, channel toggles, `PreDividePostMultiply`, `ClipBlack`/`ClipWhite`."), - ToolMeta("ColorCorrector", "Color & Depth", "Suite comps", "0.1%–0.5%", "Master/Shadow/Midtone/Highlight wheel tint, Lift/Gamma/Gain/Brightness/Contrast/Saturation, `PreDividePostMultiply`."), + ToolMeta("ColorCorrector", "Color & Depth", "`vortex_cc`, Suite comps", "0.0%–0.4%", "Master/Shadow/Midtone/Highlight wheels, exact Fusion 21.1 `TintMode` (`0`/`1`/`2`), Lift/Gamma/Gain/Brightness/Contrast/Saturation, `PreDividePostMultiply`."), ToolMeta("ColorGain", "Color & Depth", "`color_ops`, `noise_text`", "0.0%–0.1%", "Per-channel Gain, Lift, Gamma, Hue, Saturation, `PreDividePostMultiply`."), ToolMeta("ColorCurves", "Color & Depth", "Suite comps", "0.1%–0.4%", "Per-channel RGBA `LUTBezier` spline lookup tables with `PreDividePostMultiply`."), ToolMeta("HueCurves", "Color & Depth", "`tier1_a`", "0.1%–0.5%", "9 nested `LUTBezier` splines (Hue/Sat/Lum vs Hue, Suppression, etc.) baked to GPU LUT."), @@ -80,7 +80,7 @@ TOOL_METADATA: Sequence[ToolMeta] = ( # Keying ToolMeta("LumaKeyer", "Keying", "Suite comps", "0.1%–0.4%", "Luminance/channel threshold keying with low/high feathering and matte inversion."), - ToolMeta("UltraKeyer", "Keying", "`tier1_a`", "0.1%–0.6%", "Chroma keying with background color pick, matte threshold/gamma, spill suppression, and post-multiply."), + ToolMeta("UltraKeyer", "Keying", "`ultrakey`, `tier1_a`", "0.0%–0.1%", "Exact Fusion 21.1 Ultimatte color-difference matte + background subtraction (`BackgroundRed/Green/Blue`, `LowMatteThreshold`/`High`, `MatteSeparation`, `SpillSuppression`, `PostMultiplyImage`)."), ToolMeta("Fuse.Cryptomatte", "Keying", "Unit tests", "0.0%", "Cryptomatte 1.2 multi-channel EXR matte extraction (manifest JSON + MurmurHash3-32 ID/coverage rank accumulation, wildcards, `MatteOnly`).", aliases=("Cryptomatte",)), # Blur, Sharpen & Glow @@ -102,17 +102,18 @@ TOOL_METADATA: Sequence[ToolMeta] = ( ToolMeta("CameraShake", "Transform, Warp & Framing", "`tier1_c`", "0.1%–0.5%", "Procedural X/Y/Rotation/Zoom camera shake with `OverallStrength`, `Speed`, `Edges`."), ToolMeta("CornerPositioner", "Transform, Warp & Framing", "`tier1_b`", "0.1%–0.4%", "4-point projective homography warp (`TopLeft`/`TopRight`/`BottomLeft`/`BottomRight`)."), ToolMeta("DVE", "Transform, Warp & Framing", "`tier1_b`", "0.1%–0.4%", "2.5D ZYX Euler rotation + perspective homography (`Center`, `ZMove`, `Pivot`, `AlphaMode`)."), - ToolMeta("Displace", "Transform, Warp & Framing", "`displace`", "0.0%–0.1%", "`XY` refraction (channels, offsets, refraction strength) and `Radial`/`Bump` (`LightPower`, `LightAngle`, `LightChannel` additive directional slope lighting)."), + ToolMeta("Displace", "Transform, Warp & Framing", "`displace`, `displace_wave`", "0.0%–0.1%", "`XY` refraction (channels, offsets, refraction strength) and `Radial`/`Bump` (`LightPower`, `LightAngle`, `LightChannel` additive directional slope lighting)."), + ToolMeta("Vortex", "Transform, Warp & Framing", "`vortex_cc`", "0.0%–0.4%", "Isotropic radial swirl warp (`Center`, `Size`, `Angle`, `Power`, `Blend`, `EffectMask`)."), ToolMeta("Scale", "Transform, Warp & Framing", "Suite comps", "0.0%–0.2%", "Proportional/non-proportional image scaling with resampling filter."), ToolMeta("BetterResize", "Transform, Warp & Framing", "Suite comps", "0.0%–0.2%", "Target pixel-dimension resize (`Width`, `Height`, `KeepAspect`)."), ToolMeta("Crop", "Transform, Warp & Framing", "Suite comps", "0.0%–0.1%", "Region crop & canvas repositioning (`XOffset`, `YOffset`, `XSize`, `YSize`, `KeepCentered`)."), ToolMeta("SetDomain", "Transform, Warp & Framing", "`tier1_d`", "0.0%–0.1%", "Domain-of-Definition (`Adjust` shrink/expand and `Set` modes)."), # Masks - ToolMeta("EllipseMask", "Masks", "`mask`", "0.0%–0.2%", "Center, Width, Height, Angle, `SoftEdge`, `BorderWidth`, `Solid`, `Invert`, `PaintMode` chaining."), - ToolMeta("RectangleMask", "Masks", "`mask`", "0.0%–0.2%", "Center, Width, Height, `CornerRadius`, Angle, `SoftEdge`, `BorderWidth`, `Solid`, `Invert`, `PaintMode` chaining."), - ToolMeta("PolylineMask", "Masks", "Suite comps", "0.1%–0.5%", "CPU `zeno` Bezier/linear polygon rasterizer with animated keyframed `Polyline` splines, `SoftEdge`, `Invert`, `PaintMode`."), - ToolMeta("BitmapMask", "Masks", "Suite comps", "0.0%–0.2%", "Image-to-mask extraction (`Alpha`/`Luminance`/`Red`/`Green`/`Blue`), `Low`/`High` clip, `SoftEdge`, `Invert`."), + ToolMeta("EllipseMask", "Masks", "`mask`, `mask_softedge`", "0.0%–0.2%", "Center, Width, Height, Angle, progressive-pyramid `SoftEdge`, `BorderWidth`, `Solid`, `Filter` (`Fast Gaussian`/`Box`), `ClippingMode`, `Invert`, `PaintMode` chaining."), + ToolMeta("RectangleMask", "Masks", "`mask`, `mask_softedge`", "0.0%–0.2%", "Center, Width, Height, `CornerRadius`, Angle, progressive-pyramid `SoftEdge`, `BorderWidth`, `Solid`, `Filter`, `ClippingMode`, `Invert`, `PaintMode` chaining."), + ToolMeta("PolylineMask", "Masks", "`mask_softedge`, Suite comps", "0.1%–0.4%", "CPU `zeno` Bezier/linear polygon rasterizer with animated keyframed `Polyline` splines, progressive-pyramid `SoftEdge`, `ClippingMode`, `Invert`, `PaintMode`."), + ToolMeta("BitmapMask", "Masks", "`mask_softedge`", "0.0%–0.2%", "GPU image-to-mask extraction (`Alpha`/`Luminance`/`Red`/`Green`/`Blue`/`Saturation`/`Lightness`/`Hue`), `Low`/`High` clip, centered 1:1 alignment, `SoftEdge`, `Invert`, `Level`, `PaintMode`."), # Particles ToolMeta("pRender", "Particles", "Unit tests", "Visual*", "2D deterministic particle rasterizer (`ParticleStyleBitmap` rotated bilinear sprites, `ParticleStylePoint`/`Blob`, cached frame stepping). *Stochastic seed."),