authoravatarclover caruso<git@paperclover.net>2026-11-30 18:23:05-08:00
committeravatarclover caruso<git@paperclover.net>2026-11-30 19:14:04-08:00
loge047711ccb7667ce25327eb57a9afe1af8408665
tree43ab5347faadba0820acacdcc8ed4310868c9d2e
parent138aa6b97bbbf1feaf785a127ca34a5e1a487476
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

Add deterministic fuzzer v2, calibrate Paint, and implement PerspectivePositioner/DaySky/GridWarp/sGrid (#36)


8 files changed, 1580 insertions(+), 50 deletions(-)

compatibility.md+14-10
......@@ -9,10 +9,10 @@ Auto-generated from live engine sources (`crates/engine/src/eval.rs`, `crates/en
99
1010| Metric | Value |
1111| --- | --- |
12| **Supported Flow Tools** | **115** (90 2D/Fuse/utility in `eval.rs`, 23 3D scene nodes in `scene3d.rs`, 2 Flow annotations) |
12| **Supported Flow Tools** | **119** (94 2D/Fuse/utility in `eval.rs`, 23 3D scene nodes in `scene3d.rs`, 2 Flow annotations) |
1313| **Modifiers & Animation** | **8** systems (9 Fusion modifier classes + Lua expressions) |
1414| **Active Corpus (`trees/fusion`) Coverage** | **99.7%** (1,988 / 1,993 nodes across 16 `.comp` files) |
15| **Archive Corpus (`private/samples`) Coverage** | **99.6%** (54,734 / 54,955 nodes across 324 `.comp` files) |
15| **Archive Corpus (`private/samples`) Coverage** | **99.7%** (54,763 / 54,955 nodes across 324 `.comp` files) |
1616| **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. |
1717
1818## Generators
......@@ -24,6 +24,7 @@ Auto-generated from live engine sources (`crates/engine/src/eval.rs`, `crates/en
2424| `Plasma` | `tier1_c` | 0.1%–0.2% | 0 / 39 | 4-circle linear/sine interference pattern with phase/scale animation. |
2525| `TextPlus` | `text`, `noise_text` | 0.2%–0.9% | 53 / 2770 | CoreText rasterizer, alignment, tracking, Euclidean subpixel SDF outline, `BorderFill` (`ElementShape = 2`, `Level`, `ExtendHorizontal/Vertical`, `Round`, `Offset`), and `StyledTextCLS`. |
2626| `Loader` | All suites | 0.0% | 106 / 1274 | PNG/JPG/TIFF/EXR stills & sequences with direct unclamped 16/32-bit float HDR OpenEXR upload in `HiQ`; native macOS `AVFoundation`/`VideoToolbox` + `ffmpeg` video; `.wav`/`.mp3` audio. |
27| `DaySky` | Unit tests | 0.4%–1.1% | 0 / 16 | Equirectangular Preetham/Perez physical sky dome (`Latitude`, `Longitude`, `Month`, `Day`, `Time`, `Turbidity`, `Exposure`, Perez horizon/circumsolar/backscatter sliders, log-avg luminance normalization + Reinhard tone map). |
2728
2829## Compositing & Blending
2930
......@@ -31,9 +32,9 @@ Auto-generated from live engine sources (`crates/engine/src/eval.rs`, `crates/en
3132| --- | --- | --- | --- | --- |
3233| `Merge` | `merge` | 0.0%–0.3% | 293 / 6358 | All ApplyModes (`Normal`, `Screen`, `Multiply`, `Difference`, `DarkerColor`, `Overlay`, `Hard/Soft/Linear/VividLight`, `LinearDodge`, etc.), `Operator=Over/Under`, `Gain`, `BurnIn`, `SubtractiveAdditive`, `Blend`, effect mask. |
3334| `Dissolve` | `tier1_b` | 0.0%–0.1% | 0 / 4 | Mix (`Mix = 0..1`) between `Background` and `Foreground` with effect mask support. |
34| `Paint` | Unit tests | Visual* | 0 / 25 | Composites the `Paint` stroke chain (`PolylineStroke` / `Multistroke`) over `Input` with `Blend` and `EffectMask`. CPU-rasterized round `CircleBrush` / `SoftBrush` (`Size`, `Softness`), `PaintApplyColor` (`Red`/`Green`/`Blue`/`Opacity`) and `PaintApplyErase` (erases earlier strokes). *Brush size/softness falloff are not Fusion-calibrated; `Clone` and other apply modes are skipped. |
35| `PolylineStroke` | Unit tests | Visual* | 0 / 27 | Bezier/linear `Polyline` (static or animated) with `WriteOnStart`/`WriteOnEnd`; always visible. Rendered only through `Paint` / `PaintMask`. |
36| `Multistroke` | Unit tests | Visual* | 0 / 33 | Recorded freehand `Strokes`, visible from `Time` for `Duration` frames (default 1) with per-stroke `Params` overrides (`ApplyMode`, `Size`, `Softness`, color, `Duration`). Per-point `T` is ignored. Rendered only through `Paint` / `PaintMask`. |
35| `Paint` | Unit tests | 0.0%–1.2% | 0 / 25 | Composites the `Paint` stroke chain (`PolylineStroke` / `Multistroke`) over `Input` with `Blend` and `EffectMask`. Fusion-calibrated round `CircleBrush` / `SoftBrush` (`Size`, `Softness`, ~0.41*r spacing, sequential alpha buildup), `PaintApplyColor` (`Red`/`Green`/`Blue`/`Opacity`), and `PaintApplyErase`. |
36| `PolylineStroke` | Unit tests | 0.0%–0.3% | 0 / 27 | Bezier/linear `Polyline` (static or animated) with `WriteOnStart`/`WriteOnEnd`; always visible. Rendered only through `Paint` / `PaintMask`. |
37| `Multistroke` | Unit tests | 0.1%–1.2% | 0 / 33 | Recorded freehand `Strokes`, visible from `Time` for `Frames`/`Duration` frames (default 1) with per-stroke `Params` overrides (`ApplyMode`, `Size`, `Softness`, color, `Duration`). Rendered only through `Paint` / `PaintMask`. |
3738| `Shadow` | `tier1_b` | 0.1%–0.4% | 0 / 38 | Drop shadow offset, softness blur, tint color/alpha, and `ShadowOnly` output. |
3839
3940## Color & Depth
......@@ -83,6 +84,8 @@ Auto-generated from live engine sources (`crates/engine/src/eval.rs`, `crates/en
8384| `Transform` | `xf` | 0.0%–0.3% | 47 / 1211 | `Center`, `Pivot`, `Size`/`XSize`/`YSize`, `Aspect`, `Angle`, `FlipHoriz`/`FlipVert`, `FilterMethod` (`Nearest`/`Box`/`Linear`/`Catmull-Rom`), `Edges` (`Canvas`/`Wrap`/`Duplicate`/`Mirror`). |
8485| `CameraShake` | `tier1_c` | 0.1%–0.5% | 0 / 12 | Procedural X/Y/Rotation/Zoom camera shake with `OverallStrength`, `Speed`, `Edges`. |
8586| `CornerPositioner` | `tier1_b` | 0.1%–0.4% | 0 / 29 | 4-point projective homography warp (`TopLeft`/`TopRight`/`BottomLeft`/`BottomRight`). |
87| `PerspectivePositioner` | Unit tests | 0.3%–0.4% | 0 / 4 | Rectifies 4-corner quad (`BottomLeft`/`BottomRight`/`TopRight`/`TopLeft`) to unit square with `MappingType` bilinear `Linear` (0) or projective `Perspective` (1). |
88| `GridWarp` | Unit tests | 0.4%–1.2% | 0 / 5 | 2D control-point `Mesh` Bezier/Coons patch warp (`SrcGridChange` -> `DstGridChange`, static or keyframed splines, tangent handles, `Blend`, `EffectMask`). |
8689| `DVE` | `tier1_b` | 0.1%–0.4% | 4 / 22 | 2.5D ZYX Euler rotation + perspective homography (`Center`, `ZMove`, `Pivot`, `AlphaMode`). |
8790| `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). |
8891| `Vortex` | `vortex_cc` | 0.0%–0.4% | 1 / 1 | Isotropic radial swirl warp (`Center`, `Size`, `Angle`, `Power`, `Blend`, `EffectMask`). |
......@@ -104,7 +107,7 @@ Auto-generated from live engine sources (`crates/engine/src/eval.rs`, `crates/en
104107| `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`. |
105108| `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`. |
106109| `WandMask` | `archive_3d` | 0.0%–0.3% | 0 / 150 | Seeded BFS flood-fill wand mask (`Source`, `SelectionPoint`, `SelectionRange`, `ColorSpace`, `SoftEdge`, `Invert`, `Level`, `PaintMode`). |
107| `PaintMask` | Unit tests | Visual* | 0 / 14 | Alpha mask of the `Paint` stroke chain (stroke opacity, erase), `MaskWidth`/`MaskHeight`, `SoftEdge`, `Filter`, `ClippingMode`, `Invert`, `Level`, `PaintMode` chaining. *Brush falloff is not Fusion-calibrated. |
110| `PaintMask` | Unit tests | 0.1%–0.4% | 0 / 14 | Fusion-calibrated alpha mask of the `Paint` stroke chain (`Size`, `Softness`, opacity, erase), `MaskWidth`/`MaskHeight`, `SoftEdge`, `Filter`, `ClippingMode`, `Invert`, `Level`, `PaintMode` chaining. |
108111
109112## 2D Vector Shapes
110113
......@@ -114,6 +117,7 @@ Auto-generated from live engine sources (`crates/engine/src/eval.rs`, `crates/en
114117| `sNGon` | Unit tests | 0.0% | 0 / 9 | Regular N-sided polygon vector shape (`Sides`, `Width`, `Height`, `Translate.X/Y`, `Angle`, `Solid`, `BorderWidth`, `JoinStyle`, RGBA color). |
115118| `sRectangle` | Unit tests | 0.0% | 0 / 6 | Vector rectangle & rounded rectangle (`Width`, `Height`, `CornerRadius`, `Translate.X/Y`, `Angle`, `Solid`, `BorderWidth`, RGBA color). |
116119| `sEllipse` | Unit tests | 0.0% | 0 / 3 | Cubic Bezier vector ellipse (`Width`, `Height`, `Translate.X/Y`, `Angle`, `Solid`, `BorderWidth`, RGBA color). |
120| `sGrid` | Unit tests | 0.0% | 0 / 4 | Centered 2D vector shape grid generator (`CellsX`, `CellsY`, `XOffset`, `YOffset`) feeding `sRender`. |
117121| `sMerge` | Unit tests | 0.0% | 0 / 3 | Composites multiple upstream vector shape inputs (`Input1`..`InputN`) in painter's order. |
118122| `sTransform` | Unit tests | 0.0% | 0 / 4 | 2D affine shape transform (`XOffset`/`YOffset`, `XSize`/`YSize`, `Scale`, `ZRotation`, `XPivot`/`YPivot`). |
119123| `sBoolean` | Unit tests | 0.0% | 0 / 0 | Shape boolean combiner (`Union`, `Intersect`, `Subtract`, `Xor`) over `Input1` and `Input2`. |
......@@ -208,16 +212,12 @@ Unlike Blackmagic Fusion — which unlinks missing OFX or Resolve-only plugins w
208212| `AudioDisplay` | 0 / 21 | — | Preserved lossless on save; passes through main input in Flow. |
209213| `Fuse.AlphaWeightedNoise` | 0 / 21 | — | Preserved lossless on save; passes through main input in Flow. |
210214| `Fuse.Hexagon` | 0 / 17 | — | Preserved lossless on save; passes through main input in Flow. |
211| `DaySky` | 0 / 16 | — | Preserved lossless on save; passes through main input in Flow. |
212215| `SurfaceAlembicMesh` | 0 / 13 | — | Preserved lossless on save; passes through main input in Flow. |
213216| `PseudoColor` | 0 / 6 | — | Preserved lossless on save; passes through main input in Flow. |
214217| `Fuse.CheckerPieceGenerator` | 0 / 6 | — | Preserved lossless on save; passes through main input in Flow. |
215| `GridWarp` | 0 / 5 | — | Preserved lossless on save; passes through main input in Flow. |
216218| `Fog` | 0 / 5 | — | Preserved lossless on save; passes through main input in Flow. |
217219| `Highlight` | 0 / 4 | — | Preserved lossless on save; passes through main input in Flow. |
218220| `Fuse.Lightning` | 0 / 4 | — | Preserved lossless on save; passes through main input in Flow. |
219| `PerspectivePositioner` | 0 / 4 | — | Preserved lossless on save; passes through main input in Flow. |
220| `sGrid` | 0 / 4 | — | Preserved lossless on save; passes through main input in Flow. |
221221| `DepthBlur` | 0 / 4 | — | Preserved lossless on save; passes through main input in Flow. |
222222| `Replicate3D` | 0 / 4 | — | Preserved lossless on save; passes through main input in Flow. |
223223| `SphereMap` | 0 / 4 | — | Preserved lossless on save; passes through main input in Flow. |
......@@ -225,6 +225,10 @@ Unlike Blackmagic Fusion — which unlinks missing OFX or Resolve-only plugins w
225225| `RankFilter` | 0 / 3 | — | Preserved lossless on save; passes through main input in Flow. |
226226| `AcesTransform` | 0 / 3 | — | Preserved lossless on save; passes through main input in Flow. |
227227| `Bender3D` | 0 / 2 | — | Preserved lossless on save; passes through main input in Flow. |
228| `CleanPLate` | 0 / 2 | — | Preserved lossless on save; passes through main input in Flow. |
229| `Calculation` | 0 / 2 | — | Preserved lossless on save; passes through main input in Flow. |
230| `DeltaKeyer` | 0 / 2 | — | Preserved lossless on save; passes through main input in Flow. |
231| `LensDistort` | 0 / 2 | — | Preserved lossless on save; passes through main input in Flow. |
228232
229233---
230234
crates/engine/src/eval/mod.rs+16-3
......@@ -146,6 +146,9 @@ enum ShaderOp {
146146 KScope,
147147 Drip,
148148 Dent,
149 PerspectivePos,
150 DaySky,
151 GridWarp,
149152}
150153
151154impl ShaderOp {
......@@ -200,7 +203,9 @@ impl ShaderOp {
200203 | Self::UltraKeyer
201204 | Self::Plasma => ShaderDomain::KeyersGen,
202205
203 Self::Drip | Self::Dent => ShaderDomain::ArchiveFx,
206 Self::Drip | Self::Dent | Self::PerspectivePos | Self::DaySky | Self::GridWarp => {
207 ShaderDomain::ArchiveFx
208 }
204209 }
205210 }
206211
......@@ -251,6 +256,9 @@ impl ShaderOp {
251256 Self::KScope => "kscope_op",
252257 Self::Drip => "drip_op",
253258 Self::Dent => "dent_op",
259 Self::PerspectivePos => "perspective_pos_op",
260 Self::DaySky => "day_sky_op",
261 Self::GridWarp => "grid_warp_op",
254262 }
255263 }
256264}
......@@ -1100,6 +1108,7 @@ impl Engine {
11001108 "Transform" => self.eval_transform(comp, node, time, frame_i, enc, visiting, stats),
11011109 "CameraShake" => self.eval_camera_shake(comp, node, time, frame_i, enc, visiting, stats),
11021110 "CornerPositioner" => self.eval_corner_positioner(comp, node, time, frame_i, enc, visiting, stats),
1111 "PerspectivePositioner" => self.eval_perspective_positioner(comp, node, time, frame_i, enc, visiting, stats),
11031112 "DVE" => self.eval_dve(comp, node, time, frame_i, enc, visiting, stats),
11041113 "Shadow" => self.eval_shadow(comp, node, time, frame_i, enc, visiting, stats),
11051114 "Scale" | "BetterResize" => self.eval_scale(comp, node, time, frame_i, comp_dims, enc, visiting, stats),
......@@ -1126,17 +1135,20 @@ impl Engine {
11261135 "ErodeDilate" => self.eval_erode_dilate(comp, node, time, frame_i, enc, visiting, stats),
11271136 "FastNoise" => self.eval_fast_noise(comp, node, time, frame_i, comp_dims, enc, stats),
11281137 "Plasma" => self.eval_plasma(comp, node, time, frame_i, comp_dims, enc, visiting, stats),
1138 "DaySky" => self.eval_day_sky(comp, node, time, frame_i, comp_dims, enc, visiting, stats),
11291139 "FilmGrain" => self.eval_film_grain(comp, node, time, frame_i, enc, visiting, stats),
11301140 "Displace" => self.eval_displace(comp, node, time, frame_i, enc, visiting, stats),
11311141 "Vortex" => self.eval_vortex(comp, node, time, frame_i, enc, visiting, stats),
11321142 "Drip" => self.eval_drip(comp, node, time, frame_i, enc, visiting, stats),
11331143 "Dent" => self.eval_dent(comp, node, time, frame_i, enc, visiting, stats),
1144 "GridWarp" => self.eval_grid_warp(comp, node, time, frame_i, enc, visiting, stats),
11341145 "Fuse.Duplicate" => self.eval_duplicate(comp, node, time, frame_i, enc, visiting, stats),
11351146 "Fuse.KScope" => self.eval_kscope(comp, node, time, frame_i, enc, visiting, stats),
11361147 "sRender" => self.eval_s_render(comp, node, time, frame_i, comp_dims, enc, visiting, stats),
11371148 "sNGon"
11381149 | "sRectangle"
11391150 | "sEllipse"
1151 | "sGrid"
11401152 | "sMerge"
11411153 | "sTransform"
11421154 | "sBoolean"
......@@ -1400,6 +1412,7 @@ mod lazy_shader_verify {
14001412 ShaderOp::UltraKeyer, ShaderOp::Dissolve, ShaderOp::Homography, ShaderOp::ShadowComp,
14011413 ShaderOp::Plasma, ShaderOp::FilmGrain, ShaderOp::SetDomain, ShaderOp::ChangeDepth,
14021414 ShaderOp::Vortex, ShaderOp::KScope, ShaderOp::Drip, ShaderOp::Dent,
1415 ShaderOp::PerspectivePos, ShaderOp::DaySky, ShaderOp::GridWarp,
14031416 ];
14041417 // Verify starts completely empty (lazy!)
14051418 assert_eq!(eng.pipelines.borrow().modules.len(), 0);
......@@ -1409,9 +1422,9 @@ mod lazy_shader_verify {
14091422 eng.pipelines_for(BitDepth::Float16).borrow_mut().ensure_pipeline(&eng.device, op);
14101423 }
14111424 assert_eq!(eng.pipelines.borrow().modules.len(), 7);
1412 assert_eq!(eng.pipelines.borrow().pipelines.len(), 45);
1425 assert_eq!(eng.pipelines.borrow().pipelines.len(), 48);
14131426 assert_eq!(eng.pipelines_for(BitDepth::Float16).borrow().modules.len(), 7);
1414 assert_eq!(eng.pipelines_for(BitDepth::Float16).borrow().pipelines.len(), 45);
1427 assert_eq!(eng.pipelines_for(BitDepth::Float16).borrow().pipelines.len(), 48);
14151428 }
14161429
14171430 #[test]
crates/engine/src/eval/paint.rs+42-12
......@@ -84,7 +84,9 @@ fn collect_strokes(comp: &Comp, head: &Node, time: f64, expr: &ExprEngine) -> Ve
8484 let params = st.get_table("Params");
8585 let Some(mut s) = stroke_style(comp, node, time, expr, params) else { continue };
8686 let start = st.get_f64("Time").unwrap_or(0.0);
87 let duration = stroke_number(comp, node, time, expr, params, "Duration", 1.0);
87 let duration = st
88 .get_f64("Frames")
89 .unwrap_or_else(|| stroke_number(comp, node, time, expr, params, "Duration", 1.0));
8890 if time < start || time >= start + duration {
8991 continue;
9092 }
......@@ -131,6 +133,7 @@ fn stroke_style(
131133 let mode = params
132134 .and_then(|p| p.get_table("ApplyMode")?.get("Value"))
133135 .and_then(fuid)
136 .or_else(|| node.static_str("ApplyMode"))
134137 .or_else(|| node.raw.get_table("ApplyModes")?.get_index(1)?.as_str())
135138 .unwrap_or("PaintApplyColor");
136139 let erase = match mode {
......@@ -142,11 +145,25 @@ fn stroke_style(
142145 .static_str("BrushShape")
143146 .or_else(|| node.raw.get_table("Brushes")?.get_index(1)?.as_str())
144147 .unwrap_or("SoftBrush");
148 let size = stroke_number(
149 comp,
150 node,
151 time,
152 expr,
153 params,
154 &format!("{brush}.Size"),
155 stroke_number(comp, node, time, expr, params, "Size", 0.01),
156 ) as f32;
157 let softness = if brush == "SoftBrush" {
158 num("SoftBrush.Softness", 0.5).clamp(0.0, 1.0)
159 } else {
160 0.0
161 };
145162 Some(Stroke {
146163 path: Vec::new(),
147164 write_on: [0.0, 1.0],
148 size: num(&format!("{brush}.Size"), 0.01),
149 softness: if brush == "SoftBrush" { num("SoftBrush.Softness", 0.5).clamp(0.0, 1.0) } else { 0.0 },
165 size,
166 softness,
150167 color: [
151168 num("PaintApplyColor.Red", 1.0),
152169 num("PaintApplyColor.Green", 1.0),
......@@ -173,10 +190,15 @@ fn stamp_positions(path: &[[f32; 2]], write_on: [f32; 2], spacing: f32) -> Vec<[
173190 return vec![first];
174191 }
175192 let (d0, d1) = (start * total, end * total);
176 let n = ((d1 - d0) / spacing).ceil() as usize;
193 let span = d1 - d0;
194 if span <= 1e-4 {
195 return Vec::new();
196 }
197 let n = (span / spacing).round().max(1.0) as usize;
198 let step = span / n as f32;
177199 (0..=n)
178200 .map(|k| {
179 let d = (d0 + k as f32 * spacing).min(d1);
201 let d = (d0 + k as f32 * step).min(d1);
180202 let i = cum.partition_point(|&c| c < d).clamp(1, path.len() - 1);
181203 let t = (d - cum[i - 1]) / (cum[i] - cum[i - 1]).max(1e-6);
182204 [0, 1].map(|a| path[i - 1][a] + (path[i][a] - path[i - 1][a]) * t)
......@@ -184,13 +206,17 @@ fn stamp_positions(path: &[[f32; 2]], write_on: [f32; 2], spacing: f32) -> Vec<[
184206 .collect()
185207}
186208
187/// Coverage of a round brush of radius `r` at distance `d` from its center.
209/// Coverage of a round brush of radius `r` at distance `d` from its center (calibrated to Fusion 21.1 SoftBrush/CircleBrush).
188210fn brush_coverage(d: f32, r: f32, softness: f32) -> f32 {
189211 if softness <= 0.0 {
190212 return (r + 0.5 - d).clamp(0.0, 1.0);
191213 }
192 let t = ((r - d) / (r * softness).max(1e-3)).clamp(0.0, 1.0);
193 t * t * (3.0 - 2.0 * t)
214 let u = (d / r.max(1e-5)).clamp(0.0, 1.0);
215 if u >= 1.0 {
216 return 0.0;
217 }
218 let p = 1.75 / softness.max(1e-3);
219 (1.0 - u.powf(p)).max(0.0).powf(1.85)
194220}
195221
196222/// Rasterizes `strokes` in order into a premultiplied RGBA float layer, top row first.
......@@ -199,7 +225,8 @@ fn render_strokes(strokes: &[Stroke], [w, h]: [u32; 2]) -> Vec<[f32; 4]> {
199225 for s in strokes {
200226 let r = (s.size * w as f32 * 0.5).max(0.5);
201227 let px: Vec<[f32; 2]> = s.path.iter().map(|p| [(0.5 + p[0]) * w as f32, (0.5 - p[1]) * h as f32]).collect();
202 let stamps = stamp_positions(&px, s.write_on, (r * 0.2).max(0.5));
228 // Fusion default stamp spacing is ~0.205 * diameter (~0.41 * radius).
229 let stamps = stamp_positions(&px, s.write_on, (r * 0.41).max(0.5));
203230 let bounds = stamps.iter().fold([f32::MAX, f32::MAX, f32::MIN, f32::MIN], |b, p| {
204231 [b[0].min(p[0]), b[1].min(p[1]), b[2].max(p[0]), b[3].max(p[1])]
205232 });
......@@ -218,14 +245,17 @@ fn render_strokes(strokes: &[Stroke], [w, h]: [u32; 2]) -> Vec<[f32; 4]> {
218245 for y in sy0..sy1 {
219246 for x in sx0..sx1 {
220247 let d = (x as f32 + 0.5 - c[0]).hypot(y as f32 + 0.5 - c[1]);
221 let v = &mut cov[(y - y0) as usize * bw + (x - x0) as usize];
222 *v = v.max(brush_coverage(d, r, s.softness));
248 let a_stamp = brush_coverage(d, r, s.softness) * s.opacity;
249 if a_stamp > 0.0 {
250 let v = &mut cov[(y - y0) as usize * bw + (x - x0) as usize];
251 *v = a_stamp + *v * (1.0 - a_stamp);
252 }
223253 }
224254 }
225255 }
226256 for y in y0..y1 {
227257 for x in x0..x1 {
228 let a = cov[(y - y0) as usize * bw + (x - x0) as usize] * s.opacity;
258 let a = cov[(y - y0) as usize * bw + (x - x0) as usize];
229259 let px = &mut layer[(y * w + x) as usize];
230260 if s.erase {
231261 px.iter_mut().for_each(|c| *c *= 1.0 - a);
crates/engine/src/eval/shapes_warp.rs+680-3
......@@ -277,7 +277,10 @@ fn collect_shape_tree(
277277 })
278278 }
279279 "sTransform" => {
280 let src_id = node.connected_node("Input").and_then(|s| comp.find_node(s))?;
280 let src_id = node
281 .connected_node("Input")
282 .or_else(|| node.connected_node("Input1"))
283 .and_then(|s| comp.find_node(s))?;
281284 let ox = eval_first_num(comp, node, &["XOffset", "Translate.X"], time, 0.0, expr) as f32;
282285 let oy = eval_first_num(comp, node, &["YOffset", "Translate.Y"], time, 0.0, expr) as f32;
283286 let px = eval_first_num(comp, node, &["XPivot", "Pivot.X"], time, 0.0, expr) as f32;
......@@ -327,8 +330,45 @@ fn collect_shape_tree(
327330 Some(ShapeTree::Group(children))
328331 }
329332 }
333 "sGrid" => {
334 let src_id = node
335 .connected_node("Input")
336 .or_else(|| node.connected_node("Input1"))
337 .and_then(|s| comp.find_node(s))?;
338 let cells_x = comp.eval_number(node, "CellsX", time, 3.0, expr).round().clamp(1.0, 256.0) as usize;
339 let cells_y = comp.eval_number(node, "CellsY", time, 3.0, expr).round().clamp(1.0, 256.0) as usize;
340 let x_off = comp.eval_number(node, "XOffset", time, 0.2, expr) as f32;
341 let y_off = comp.eval_number(node, "YOffset", time, 0.2, expr) as f32;
342 let mut children = Vec::with_capacity(cells_x.saturating_mul(cells_y));
343 for iy in 0..cells_y {
344 let ty = (iy as f32 - (cells_y as f32 - 1.0) * 0.5) * y_off;
345 for ix in 0..cells_x {
346 let tx = (ix as f32 - (cells_x as f32 - 1.0) * 0.5) * x_off;
347 let cell_xf = parent_xform.mul(Affine2D::translate(tx, ty));
348 if let Some(tree) = collect_shape_tree(
349 comp,
350 src_id,
351 time,
352 expr,
353 cell_xf,
354 outline_override,
355 depth + 1,
356 ) {
357 children.push(tree);
358 }
359 }
360 }
361 if children.is_empty() {
362 None
363 } else {
364 Some(ShapeTree::Group(children))
365 }
366 }
330367 "sOutline" => {
331 let src_id = node.connected_node("Input").and_then(|s| comp.find_node(s))?;
368 let src_id = node
369 .connected_node("Input")
370 .or_else(|| node.connected_node("Input1"))
371 .and_then(|s| comp.find_node(s))?;
332372 let thickness = eval_first_num(comp, node, &["Thickness", "BorderWidth"], time, 0.01, expr).abs() as f32;
333373 let join = comp.eval_number(node, "JoinStyle", time, 2.0, expr).round().clamp(0.0, 2.0) as u8;
334374 let cap = comp.eval_number(node, "CapStyle", time, 0.0, expr).round().clamp(0.0, 2.0) as u8;
......@@ -373,7 +413,10 @@ fn collect_shape_tree(
373413 }
374414 }
375415 "PipeRouter" | "Fuse.Wireless" => {
376 let src_id = node.connected_node("Input").and_then(|s| comp.find_node(s))?;
416 let src_id = node
417 .connected_node("Input")
418 .or_else(|| node.connected_node("Input1"))
419 .and_then(|s| comp.find_node(s))?;
377420 collect_shape_tree(comp, src_id, time, expr, parent_xform, outline_override, depth + 1)
378421 }
379422 "MacroOperator" | "GroupOperator" => {
......@@ -844,6 +887,507 @@ impl Engine {
844887 self.cache.insert(key, out.clone(), node.id, frame_i);
845888 out
846889 }
890
891 #[allow(clippy::too_many_arguments)]
892 pub(super) fn eval_perspective_positioner(
893 &mut self,
894 comp: &Comp,
895 node: &Node,
896 time: f64,
897 frame_i: i64,
898 enc: &mut wgpu::CommandEncoder,
899 visiting: &mut HashSet<(NodeId, i64)>,
900 stats: &mut EvalStats,
901 ) -> CachedTexture {
902 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
903 return self.dummy.clone();
904 };
905 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
906 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
907 if blend <= 1e-6 {
908 return src;
909 }
910 let src = self.crop_to_canvas(enc, src);
911 let bl = comp.eval_point(node, "BottomLeft", time, [0.0, 0.0], &self.expr);
912 let br = comp.eval_point(node, "BottomRight", time, [1.0, 0.0], &self.expr);
913 let tr = comp.eval_point(node, "TopRight", time, [1.0, 1.0], &self.expr);
914 let tl = comp.eval_point(node, "TopLeft", time, [0.0, 1.0], &self.expr);
915 let mapping_type = comp.eval_number(node, "MappingType", time, 0.0, &self.expr).round() as i32;
916 let h_fwd = quad_forward_homography(bl, br, tr, tl);
917 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
918 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
919
920 let mut u = UniformParams::default();
921 u.p[0] = [bl[0] as f32, bl[1] as f32, br[0] as f32, br[1] as f32];
922 u.p[1] = [tr[0] as f32, tr[1] as f32, tl[0] as f32, tl[1] as f32];
923 u.p[2] = [h_fwd[0], h_fwd[1], h_fwd[2], h_fwd[3]];
924 u.p[3] = [h_fwd[4], h_fwd[5], h_fwd[6], h_fwd[7]];
925 u.p[4] = [
926 h_fwd[8],
927 if mapping_type == 1 { 1.0 } else { 0.0 },
928 blend,
929 if mask.is_some() { 1.0 } else { 0.0 },
930 ];
931 u.p[5] = [if mask_inv { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0];
932
933 let key = self.make_key(
934 node,
935 "PerspectivePositioner",
936 src.size,
937 &[src.content_hash, mask_hash],
938 bytemuck::cast_slice(&u.p[..6]),
939 );
940 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
941 stats.cache_hits += 1;
942 return hit;
943 }
944 stats.cache_misses += 1;
945 stats.nodes_evaluated += 1;
946 let dst = self.alloc_tex_like(&src, src.depth, key);
947 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
948 self.dispatch_op(enc, ShaderOp::PerspectivePos, &src.view, &self.dummy.view, mv, &dst, &u);
949 self.cache.insert(key, dst.clone(), node.id, frame_i);
950 dst
951 }
952
953 #[allow(clippy::too_many_arguments)]
954 pub(super) fn eval_day_sky(
955 &mut self,
956 comp: &Comp,
957 node: &Node,
958 time: f64,
959 frame_i: i64,
960 comp_dims: [u32; 2],
961 enc: &mut wgpu::CommandEncoder,
962 visiting: &mut HashSet<(NodeId, i64)>,
963 stats: &mut EvalStats,
964 ) -> CachedTexture {
965 let use_ff = comp.eval_number(node, "UseFrameFormatSettings", time, 0.0, &self.expr) > 0.5;
966 let w = if use_ff {
967 comp.width
968 } else {
969 comp.eval_number(node, "Width", time, comp.width as f64, &self.expr).round().max(1.0) as u32
970 };
971 let h = if use_ff {
972 comp.height
973 } else {
974 comp.eval_number(node, "Height", time, comp.height as f64, &self.expr).round().max(1.0) as u32
975 };
976 let size = if w == comp.width && h == comp.height { comp_dims } else { self.scaled_dims(w, h) };
977 let dst_depth = self.node_depth(comp, node, time, None);
978 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
979
980 let lat_deg = comp.eval_number(node, "Latitude", time, 43.65, &self.expr);
981 let lon_deg = comp.eval_number(node, "Longitude", time, -79.38, &self.expr);
982 let month = parse_month_index(node, comp, time, &self.expr);
983 let day = node
984 .static_str("Day")
985 .and_then(|s| s.parse::<f64>().ok())
986 .unwrap_or_else(|| comp.eval_number(node, "Day", time, 1.0, &self.expr));
987 let hour = comp.eval_number(node, "Time", time, 12.0, &self.expr);
988 let turbidity_in = comp.eval_number(node, "Turbidity", time, 0.0, &self.expr).max(0.0);
989 let exposure = comp.eval_number(node, "Exposure", time, 0.72, &self.expr).max(0.0);
990 let hb = comp.eval_number(node, "Horizon.Brightness", time, 1.0, &self.expr).max(0.0);
991 let hl = comp.eval_number(node, "Horizon.Luminance", time, 1.0, &self.expr).max(0.0);
992 let ci = comp.eval_number(node, "Circumsolar.Intensity", time, 1.0, &self.expr).max(0.0);
993 let cw = comp.eval_number(node, "Circumsolar.Width", time, 1.0, &self.expr).max(0.0);
994 let bs = comp.eval_number(node, "BackscatteredLight", time, 1.0, &self.expr).max(0.0);
995
996 let (sun_dir, ts) = solar_direction(lat_deg, lon_deg, month, day, hour);
997 // Calibrated to Fusion 21.1 DaySky: Turbidity in [0,1] maps to T = 1.9 + 4.0 * turb
998 let t_preetham = 1.9 + turbidity_in * 4.0;
999 let (xz, yz, _yz_lum) = preetham_zenith_xyy(t_preetham, ts);
1000 let c_y0 = [
1001 0.1787 * t_preetham - 1.4630,
1002 (-0.3554 * t_preetham + 0.4275) * 1.20,
1003 -0.0227 * t_preetham + 5.3251,
1004 0.1206 * t_preetham - 2.5771,
1005 -0.0670 * t_preetham + 0.3703,
1006 ];
1007 let c_x0 = [
1008 -0.0193 * t_preetham - 0.2592,
1009 -0.0665 * t_preetham + 0.0008,
1010 -0.0004 * t_preetham + 0.2125,
1011 -0.0641 * t_preetham - 0.8989,
1012 -0.0033 * t_preetham + 0.0452,
1013 ];
1014 let c_y_c0 = [
1015 -0.0167 * t_preetham - 0.2608,
1016 -0.0950 * t_preetham + 0.0092,
1017 -0.0079 * t_preetham + 0.2102,
1018 -0.0441 * t_preetham - 1.6537,
1019 -0.0109 * t_preetham + 0.0529,
1020 ];
1021
1022 let scale_perez = |base: [f64; 5]| -> [f64; 5] {
1023 let a = if hb <= 1e-4 || hl <= 1e-4 { 0.0 } else { base[0] * hb };
1024 let b = base[1] / hl.max(1e-3);
1025 let c = if cw <= 1e-4 { 0.0 } else { base[2] * ci };
1026 let d = base[3] * cw;
1027 let e = base[4] * bs;
1028 [a, b, c, d, e]
1029 };
1030 let c_y = scale_perez(c_y0);
1031 let c_x = scale_perez(c_x0);
1032 let c_yc = scale_perez(c_y_c0);
1033
1034 // Log-average Perez luminance normalization: geom_mean(Y_hdr) == Exposure
1035 const N_TH: usize = 32;
1036 const N_PH: usize = 32;
1037 let mut sum_log = 0.0_f64;
1038 for iy in 0..N_TH {
1039 let th = (iy as f64 + 0.5) / N_TH as f64 * std::f64::consts::FRAC_PI_2;
1040 let (st, ct) = th.sin_cos();
1041 for ix in 0..N_PH {
1042 let ph = (ix as f64 + 0.5) / N_PH as f64 * std::f64::consts::TAU;
1043 let (sp, cp) = ph.sin_cos();
1044 let cos_g = (st * cp * sun_dir[0] + st * sp * sun_dir[1] + ct * sun_dir[2]).clamp(-1.0, 1.0);
1045 let fy = eval_perez(th, cos_g.acos(), c_y).max(1e-5);
1046 sum_log += fy.ln();
1047 }
1048 }
1049 let geomean_fy = (sum_log / (N_TH * N_PH) as f64).exp().max(1e-5);
1050 let lum_gain = (exposure / geomean_fy) as f32;
1051 let f_y0 = 1.0_f64;
1052 let f_x0 = eval_perez(0.0, ts, c_x);
1053 let f_yc0 = eval_perez(0.0, ts, c_yc);
1054 let yz_scaled = lum_gain;
1055
1056 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(size), enc, visiting, stats);
1057 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
1058
1059 let mut u = UniformParams::default();
1060 u.p[0] = [sun_dir[0] as f32, sun_dir[1] as f32, sun_dir[2] as f32, yz_scaled];
1061 u.p[1] = [xz as f32, yz as f32, f_y0 as f32, f_x0 as f32];
1062 u.p[2] = [f_yc0 as f32, blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }];
1063 u.p[3] = [c_y[0] as f32, c_y[1] as f32, c_y[2] as f32, c_y[3] as f32];
1064 u.p[4] = [c_y[4] as f32, c_x[0] as f32, c_x[1] as f32, c_x[2] as f32];
1065 u.p[5] = [c_x[3] as f32, c_x[4] as f32, c_yc[0] as f32, c_yc[1] as f32];
1066 u.p[6] = [c_yc[2] as f32, c_yc[3] as f32, c_yc[4] as f32, 0.0];
1067
1068 let key = self.make_key(
1069 node,
1070 "DaySky",
1071 size,
1072 &[mask_hash, dst_depth as u64],
1073 bytemuck::cast_slice(&u.p[..7]),
1074 );
1075 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
1076 stats.cache_hits += 1;
1077 return hit;
1078 }
1079 stats.cache_misses += 1;
1080 stats.nodes_evaluated += 1;
1081 let dst = self.alloc_tex(size, dst_depth, key);
1082 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
1083 self.dispatch_op(enc, ShaderOp::DaySky, &self.dummy.view, &self.dummy.view, mv, &dst, &u);
1084 self.cache.insert(key, dst.clone(), node.id, frame_i);
1085 dst
1086 }
1087
1088 #[allow(clippy::too_many_arguments)]
1089 pub(super) fn eval_grid_warp(
1090 &mut self,
1091 comp: &Comp,
1092 node: &Node,
1093 time: f64,
1094 frame_i: i64,
1095 enc: &mut wgpu::CommandEncoder,
1096 visiting: &mut HashSet<(NodeId, i64)>,
1097 stats: &mut EvalStats,
1098 ) -> CachedTexture {
1099 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
1100 return self.dummy.clone();
1101 };
1102 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
1103 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
1104 if blend <= 1e-6 {
1105 return src;
1106 }
1107 let src_mesh = comp.eval_grid_mesh(node, "SrcGridChange", time);
1108 let dst_mesh = comp.eval_grid_mesh(node, "DstGridChange", time);
1109 let (Some(src_mesh), Some(dst_mesh)) = (src_mesh, dst_mesh) else {
1110 return src;
1111 };
1112 if src_mesh == dst_mesh {
1113 return src;
1114 }
1115 let src = self.crop_to_canvas(enc, src);
1116 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
1117 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
1118
1119 let mut u = UniformParams::default();
1120 u.p[0] = [blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }, 0.0];
1121
1122 let mut mesh_params: Vec<f32> = Vec::with_capacity(4 + (src_mesh.points.len() + dst_mesh.points.len()) * 10);
1123 mesh_params.extend_from_slice(&[blend, src_mesh.cols as f32, src_mesh.rows as f32, dst_mesh.cols as f32]);
1124 for m in [&src_mesh, &dst_mesh] {
1125 for p in &m.points {
1126 mesh_params.extend_from_slice(&[
1127 p.x as f32,
1128 p.y as f32,
1129 p.l_cx.unwrap_or(f32::NAN as f64) as f32,
1130 p.l_cy.unwrap_or(0.0) as f32,
1131 p.r_cx.unwrap_or(f32::NAN as f64) as f32,
1132 p.r_cy.unwrap_or(0.0) as f32,
1133 p.t_cx.unwrap_or(0.0) as f32,
1134 p.t_cy.unwrap_or(f32::NAN as f64) as f32,
1135 p.b_cx.unwrap_or(0.0) as f32,
1136 p.b_cy.unwrap_or(f32::NAN as f64) as f32,
1137 ]);
1138 }
1139 }
1140
1141 let key = self.make_key(node, "GridWarp", src.size, &[src.content_hash, mask_hash], &mesh_params);
1142 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
1143 stats.cache_hits += 1;
1144 return hit;
1145 }
1146 stats.cache_misses += 1;
1147 stats.nodes_evaluated += 1;
1148
1149 let uv_f16 = rasterize_grid_warp_uv_f16(&src_mesh, &dst_mesh, src.size);
1150 let uv_tex = create_texture_dod_fmt(
1151 &self.device,
1152 src.size,
1153 [0, 0],
1154 src.size,
1155 BitDepth::Float16,
1156 wgpu::TextureFormat::Rgba16Float,
1157 0,
1158 );
1159 self.queue.write_texture(
1160 uv_tex.texture.as_image_copy(),
1161 bytemuck::cast_slice(&uv_f16),
1162 wgpu::TexelCopyBufferLayout {
1163 offset: 0,
1164 bytes_per_row: Some(src.size[0] * 8),
1165 rows_per_image: Some(src.size[1]),
1166 },
1167 wgpu::Extent3d {
1168 width: src.size[0],
1169 height: src.size[1],
1170 depth_or_array_layers: 1,
1171 },
1172 );
1173
1174 let dst = self.alloc_tex_like(&src, src.depth, key);
1175 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
1176 self.dispatch_op(enc, ShaderOp::GridWarp, &src.view, &uv_tex.view, mv, &dst, &u);
1177 self.cache.insert(key, dst.clone(), node.id, frame_i);
1178 dst
1179 }
1180}
1181
1182fn quad_forward_homography(bl: [f64; 2], br: [f64; 2], tr: [f64; 2], tl: [f64; 2]) -> [f32; 9] {
1183 let dx1 = br[0] - tr[0];
1184 let dy1 = br[1] - tr[1];
1185 let dx2 = tl[0] - tr[0];
1186 let dy2 = tl[1] - tr[1];
1187 let sx = bl[0] - br[0] + tr[0] - tl[0];
1188 let sy = bl[1] - br[1] + tr[1] - tl[1];
1189 let denom = dx1 * dy2 - dx2 * dy1;
1190 if denom.abs() < 1e-10 {
1191 return [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
1192 }
1193 let g = (sx * dy2 - sy * dx2) / denom;
1194 let h = (dx1 * sy - dy1 * sx) / denom;
1195 let a = br[0] - bl[0] + g * br[0];
1196 let b = tl[0] - bl[0] + h * tl[0];
1197 let c = bl[0];
1198 let d = br[1] - bl[1] + g * br[1];
1199 let e = tl[1] - bl[1] + h * tl[1];
1200 let f = bl[1];
1201 [a as f32, b as f32, c as f32, d as f32, e as f32, f as f32, g as f32, h as f32, 1.0]
1202}
1203
1204fn parse_month_index(node: &Node, comp: &Comp, time: f64, expr: &ExprEngine) -> usize {
1205 if let Some(m) = node.static_str("Month") {
1206 let low = m.to_ascii_lowercase();
1207 let names = [
1208 "january", "february", "march", "april", "may", "june",
1209 "july", "august", "september", "october", "november", "december",
1210 ];
1211 if let Some(idx) = names.iter().position(|&n| low.starts_with(&n[..3])) {
1212 return idx + 1;
1213 }
1214 if let Ok(v) = m.parse::<usize>() {
1215 return v.clamp(1, 12);
1216 }
1217 }
1218 (comp.eval_number(node, "Month", time, 0.0, expr).round() as usize + 1).clamp(1, 12)
1219}
1220
1221fn solar_direction(lat_deg: f64, lon_deg: f64, month: usize, day: f64, hour: f64) -> ([f64; 3], f64) {
1222 const CUM_DAYS: [i32; 12] = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
1223 let doy = CUM_DAYS[month.saturating_sub(1).min(11)] as f64 + day;
1224 let b = 2.0 * std::f64::consts::PI * (doy - 81.0) / 365.0;
1225 let eot_min = 9.87 * (2.0 * b).sin() - 7.53 * b.cos() - 1.5 * b.sin();
1226 let decl = 23.44_f64.to_radians() * ((2.0 * std::f64::consts::PI / 365.0) * (doy - 81.0)).sin();
1227 let std_meridian = (lon_deg / 15.0).round() * 15.0;
1228 let solar_hour = hour + (lon_deg - std_meridian) / 15.0 + eot_min / 60.0;
1229 let hour_angle = ((solar_hour - 12.0) * 15.0).to_radians();
1230 let lat = lat_deg.to_radians();
1231 let sin_alt = (lat.sin() * decl.sin() + lat.cos() * decl.cos() * hour_angle.cos()).clamp(-1.0, 1.0);
1232 let ts = (std::f64::consts::FRAC_PI_2 - sin_alt.asin()).max(0.0);
1233 // Azimuth measured from South (0=South, pi/2=East morning, pi=North, 3*pi/2=West afternoon)
1234 let cos_az_south = (-(decl.sin() * lat.cos() - decl.cos() * lat.sin() * hour_angle.cos())
1235 / ts.sin().max(1e-5))
1236 .clamp(-1.0, 1.0);
1237 let mut phi_s = cos_az_south.acos();
1238 if hour_angle > 0.0 {
1239 phi_s = 2.0 * std::f64::consts::PI - phi_s;
1240 }
1241 let dir = [ts.sin() * phi_s.cos(), ts.sin() * phi_s.sin(), ts.cos()];
1242 (dir, ts)
1243}
1244
1245fn preetham_zenith_xyy(t: f64, ts: f64) -> (f64, f64, f64) {
1246 let t2 = t * t;
1247 let ts2 = ts * ts;
1248 let ts3 = ts2 * ts;
1249 let chi = (4.0 / 9.0 - t / 120.0) * (std::f64::consts::PI - 2.0 * ts);
1250 let yz_lum = ((4.0453 * t - 4.9710) * chi.tan() - 0.2155 * t + 2.4192).max(0.05);
1251 let xz = (0.00166 * ts3 - 0.00375 * ts2 + 0.00209 * ts) * t2
1252 + (-0.02903 * ts3 + 0.06377 * ts2 - 0.03202 * ts + 0.00394) * t
1253 + (0.11693 * ts3 - 0.21196 * ts2 + 0.06052 * ts + 0.25886);
1254 let yz = (0.00275 * ts3 - 0.00610 * ts2 + 0.00317 * ts) * t2
1255 + (-0.04214 * ts3 + 0.08970 * ts2 - 0.04153 * ts + 0.00516) * t
1256 + (0.15346 * ts3 - 0.26756 * ts2 + 0.06670 * ts + 0.26688);
1257 (xz, yz, yz_lum)
1258}
1259
1260fn eval_perez(theta: f64, gamma: f64, c: [f64; 5]) -> f64 {
1261 let ct = theta.cos().max(0.02);
1262 let cg = gamma.cos();
1263 (1.0 + c[0] * (c[1] / ct).exp()) * (1.0 + c[2] * (c[3] * gamma).exp() + c[4] * cg * cg)
1264}
1265
1266#[derive(Clone, Copy)]
1267struct CoonsPt {
1268 p: [f32; 2],
1269 l: [f32; 2],
1270 r: [f32; 2],
1271 t: [f32; 2],
1272 b: [f32; 2],
1273}
1274
1275fn mesh_coons_cells(mesh: &model::comp::GridMesh) -> Vec<[CoonsPt; 4]> {
1276 let cols = mesh.cols;
1277 let rows = mesh.rows;
1278 let dc = (mesh.delta_c as f32) / 3.0;
1279 let dr = (mesh.delta_r as f32) / 3.0;
1280 let pts: Vec<CoonsPt> = mesh
1281 .points
1282 .iter()
1283 .map(|mp| {
1284 let p = [mp.x as f32, mp.y as f32];
1285 let l = [p[0] + mp.l_cx.map_or(-dc, |v| v as f32), p[1] + mp.l_cy.unwrap_or(0.0) as f32];
1286 let r = [p[0] + mp.r_cx.map_or(dc, |v| v as f32), p[1] + mp.r_cy.unwrap_or(0.0) as f32];
1287 let t = [p[0] + mp.t_cx.unwrap_or(0.0) as f32, p[1] + mp.t_cy.map_or(-dr, |v| v as f32)];
1288 let b = [p[0] + mp.b_cx.unwrap_or(0.0) as f32, p[1] + mp.b_cy.map_or(dr, |v| v as f32)];
1289 CoonsPt { p, l, r, t, b }
1290 })
1291 .collect();
1292 let mut cells = Vec::with_capacity((cols - 1) * (rows - 1));
1293 for r in 0..(rows - 1) {
1294 for c in 0..(cols - 1) {
1295 cells.push([
1296 pts[r * cols + c],
1297 pts[r * cols + c + 1],
1298 pts[(r + 1) * cols + c],
1299 pts[(r + 1) * cols + c + 1],
1300 ]);
1301 }
1302 }
1303 cells
1304}
1305
1306fn bez3_2d(p0: [f32; 2], p1: [f32; 2], p2: [f32; 2], p3: [f32; 2], t: f32) -> [f32; 2] {
1307 let u = 1.0 - t;
1308 let (w0, w1, w2, w3) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t);
1309 [
1310 w0 * p0[0] + w1 * p1[0] + w2 * p2[0] + w3 * p3[0],
1311 w0 * p0[1] + w1 * p1[1] + w2 * p2[1] + w3 * p3[1],
1312 ]
1313}
1314
1315fn eval_coons_cell(cell: &[CoonsPt; 4], u: f32, v: f32) -> [f32; 2] {
1316 let [p00, p10, p01, p11] = *cell;
1317 let bot = bez3_2d(p00.p, p00.r, p10.l, p10.p, u);
1318 let top = bez3_2d(p01.p, p01.r, p11.l, p11.p, u);
1319 let lft = bez3_2d(p00.p, p00.b, p01.t, p01.p, v);
1320 let rgt = bez3_2d(p10.p, p10.b, p11.t, p11.p, v);
1321 let bi0 = (1.0 - u) * (1.0 - v) * p00.p[0] + u * (1.0 - v) * p10.p[0] + (1.0 - u) * v * p01.p[0] + u * v * p11.p[0];
1322 let bi1 = (1.0 - u) * (1.0 - v) * p00.p[1] + u * (1.0 - v) * p10.p[1] + (1.0 - u) * v * p01.p[1] + u * v * p11.p[1];
1323 [
1324 (1.0 - v) * bot[0] + v * top[0] + (1.0 - u) * lft[0] + u * rgt[0] - bi0,
1325 (1.0 - v) * bot[1] + v * top[1] + (1.0 - u) * lft[1] + u * rgt[1] - bi1,
1326 ]
1327}
1328
1329fn rasterize_grid_warp_uv_f16(
1330 src_mesh: &model::comp::GridMesh,
1331 dst_mesh: &model::comp::GridMesh,
1332 dims: [u32; 2],
1333) -> Vec<u16> {
1334 let [w, h] = dims;
1335 let (wf, hf) = (w as f32, h as f32);
1336 let mut uv_buf = vec![0u16; (w as usize) * (h as usize) * 4];
1337 let src_cells = mesh_coons_cells(src_mesh);
1338 let dst_cells = mesh_coons_cells(dst_mesh);
1339 let sub = 24usize;
1340 let one_f16 = crate::media::f32_to_f16_bits(1.0);
1341
1342 for (sc, dc) in src_cells.iter().zip(dst_cells.iter()) {
1343 for j in 0..sub {
1344 let (v0, v1) = (j as f32 / sub as f32, (j + 1) as f32 / sub as f32);
1345 for i in 0..sub {
1346 let (u0, u1) = (i as f32 / sub as f32, (i + 1) as f32 / sub as f32);
1347 let da = eval_coons_cell(dc, u0, v0);
1348 let db = eval_coons_cell(dc, u1, v0);
1349 let dc2 = eval_coons_cell(dc, u1, v1);
1350 let dd = eval_coons_cell(dc, u0, v1);
1351 let sa = eval_coons_cell(sc, u0, v0);
1352 let sb = eval_coons_cell(sc, u1, v0);
1353 let sc2 = eval_coons_cell(sc, u1, v1);
1354 let sd = eval_coons_cell(sc, u0, v1);
1355
1356 for ([pa, pb, pc], [qa, qb, qc]) in [([da, db, dc2], [sa, sb, sc2]), ([da, dc2, dd], [sa, sc2, sd])] {
1357 let (ax, ay) = ((pa[0] + 0.5) * wf, (0.5 - pa[1]) * hf);
1358 let (bx, by) = ((pb[0] + 0.5) * wf, (0.5 - pb[1]) * hf);
1359 let (cx, cy) = ((pc[0] + 0.5) * wf, (0.5 - pc[1]) * hf);
1360 let area = (bx - ax) * (cy - ay) - (by - ay) * (cx - ax);
1361 if area.abs() < 1e-6 {
1362 continue;
1363 }
1364 let inv_area = 1.0 / area;
1365 let x0 = ax.min(bx).min(cx).floor().max(0.0) as u32;
1366 let x1 = (ax.max(bx).max(cx).ceil() as u32).min(w.saturating_sub(1));
1367 let y0 = ay.min(by).min(cy).floor().max(0.0) as u32;
1368 let y1 = (ay.max(by).max(cy).ceil() as u32).min(h.saturating_sub(1));
1369 for py in y0..=y1 {
1370 let qy = py as f32 + 0.5;
1371 for px in x0..=x1 {
1372 let qx = px as f32 + 0.5;
1373 let w0 = ((bx - qx) * (cy - qy) - (by - qy) * (cx - qx)) * inv_area;
1374 let w1 = ((cx - qx) * (ay - qy) - (cy - qy) * (ax - qx)) * inv_area;
1375 let w2 = 1.0 - w0 - w1;
1376 if w0 >= -1e-4 && w1 >= -1e-4 && w2 >= -1e-4 {
1377 let su = w0 * qa[0] + w1 * qb[0] + w2 * qc[0] + 0.5;
1378 let sv = w0 * qa[1] + w1 * qb[1] + w2 * qc[1] + 0.5;
1379 let idx = (py as usize * w as usize + px as usize) * 4;
1380 uv_buf[idx] = crate::media::f32_to_f16_bits(su);
1381 uv_buf[idx + 1] = crate::media::f32_to_f16_bits(sv);
1382 uv_buf[idx + 2] = one_f16;
1383 }
1384 }
1385 }
1386 }
1387 }
1388 }
1389 }
1390 uv_buf
8471391}
8481392
8491393#[cfg(test)]
......@@ -1211,4 +1755,137 @@ mod tests {
12111755 let ngon_only = (64 * 128 + 54) * 4;
12121756 assert_eq!(&px_xor[ngon_only..ngon_only + 4], &[255, 255, 255, 255]);
12131757 }
1758
1759 #[test]
1760 fn test_perspective_positioner_and_s_grid() {
1761 let src = r#"{
1762 Tools = ordered() {
1763 Bg1 = Background {
1764 Inputs = {
1765 Width = Input { Value = 64, },
1766 Height = Input { Value = 64, },
1767 Type = Input { Value = FuID { "Horizontal" }, },
1768 TopLeftRed = Input { Value = 1, },
1769 TopRightRed = Input { Value = 0, },
1770 TopRightBlue = Input { Value = 1, },
1771 },
1772 },
1773 PP_Lin = PerspectivePositioner {
1774 Inputs = {
1775 TopLeft = Input { Value = { 0.25, 0.75 }, },
1776 TopRight = Input { Value = { 0.75, 0.75 }, },
1777 BottomLeft = Input { Value = { 0.25, 0.25 }, },
1778 BottomRight = Input { Value = { 0.75, 0.25 }, },
1779 Input = Input { SourceOp = "Bg1", Source = "Output", },
1780 },
1781 },
1782 El1 = sEllipse {
1783 Inputs = { Width = Input { Value = 0.1, }, Height = Input { Value = 0.1, }, },
1784 },
1785 Gr1 = sGrid {
1786 Inputs = {
1787 Input = Input { SourceOp = "El1", Source = "Output", },
1788 CellsX = Input { Value = 3, },
1789 CellsY = Input { Value = 3, },
1790 XOffset = Input { Value = 0.25, },
1791 YOffset = Input { Value = 0.25, },
1792 },
1793 },
1794 SR1 = sRender {
1795 Inputs = {
1796 Width = Input { Value = 64, },
1797 Height = Input { Value = 64, },
1798 Input = Input { SourceOp = "Gr1", Source = "Output", },
1799 },
1800 },
1801 },
1802 }"#;
1803 let comp = Comp::from_fusion_str(src).unwrap();
1804 let Ok(mut eng) = Engine::new_headless() else { return; };
1805 let (t_pp, _) = eng.evaluate(&comp, comp.find_node("PP_Lin").unwrap(), 0.0);
1806 let px_pp = eng.readback_rgba(&t_pp).unwrap();
1807 // Top-left output pixel samples around (0.25, 0.75) in Bg1 -> ~75% red, ~25% blue!
1808 let p0 = &px_pp[0..4];
1809 assert!(p0[0] > 165 && p0[2] > 40 && p0[2] < 90, "got {p0:?}");
1810
1811 let (t_sr, _) = eng.evaluate(&comp, comp.find_node("SR1").unwrap(), 0.0);
1812 let px_sr = eng.readback_rgba(&t_sr).unwrap();
1813 // Center cell (32, 32) and offset (+0.25*64 = 48, 32) should be lit white
1814 assert_eq!(&px_sr[(32 * 64 + 32) * 4..(32 * 64 + 32) * 4 + 4], &[255, 255, 255, 255]);
1815 assert_eq!(&px_sr[(32 * 64 + 48) * 4..(32 * 64 + 48) * 4 + 4], &[255, 255, 255, 255]);
1816 assert_eq!(&px_sr[0..4], &[0, 0, 0, 0]);
1817 }
1818
1819 #[test]
1820 fn test_day_sky_and_grid_warp() {
1821 let src = r#"{
1822 Tools = ordered() {
1823 DS1 = DaySky {
1824 Inputs = {
1825 Width = Input { Value = 64, },
1826 Height = Input { Value = 64, },
1827 Latitude = Input { Value = 37.0, },
1828 Longitude = Input { Value = 0.0, },
1829 Time = Input { Value = 12.0, },
1830 Exposure = Input { Value = 1.0, },
1831 },
1832 },
1833 BgW = Background {
1834 Inputs = {
1835 Width = Input { Value = 64, },
1836 Height = Input { Value = 64, },
1837 Type = Input { Value = FuID { "Horizontal" }, },
1838 TopLeftRed = Input { Value = 1, },
1839 TopRightGreen = Input { Value = 1, },
1840 },
1841 },
1842 GW1 = GridWarp {
1843 Inputs = {
1844 SrcGridChange = Input {
1845 Value = Mesh {
1846 Columns = 2, Rows = 2,
1847 DeltaC = 1, DeltaR = 1,
1848 Center = { 0, 0 },
1849 Corners = { -0.5, -0.5, 0.5, 0.5 },
1850 Points = {
1851 { X = -0.5, Y = -0.5 }, { X = 0.5, Y = -0.5 },
1852 { X = -0.5, Y = 0.5 }, { X = 0.5, Y = 0.5 },
1853 },
1854 },
1855 },
1856 DstGridChange = Input {
1857 Value = Mesh {
1858 Columns = 2, Rows = 2,
1859 DeltaC = 1, DeltaR = 1,
1860 Center = { 0, 0 },
1861 Corners = { -0.5, -0.5, 0.5, 0.5 },
1862 Points = {
1863 { X = -0.5, Y = -0.5 }, { X = 0.5, Y = -0.5 },
1864 { X = -0.5, Y = 0.5 }, { X = 0.5, Y = 0.5 },
1865 },
1866 },
1867 },
1868 Input = Input { SourceOp = "BgW", Source = "Output", },
1869 },
1870 },
1871 },
1872 }"#;
1873 let comp = Comp::from_fusion_str(src).unwrap();
1874 let Ok(mut eng) = Engine::new_headless() else { return; };
1875 let (t_ds, _) = eng.evaluate(&comp, comp.find_node("DS1").unwrap(), 0.0);
1876 let px_ds = eng.readback_rgba(&t_ds).unwrap();
1877 // Zenith row (y=0) is sky blue (B > R), horizon (y=63) is brighter haze
1878 let zen = &px_ds[(0 * 64 + 32) * 4..(0 * 64 + 32) * 4 + 4];
1879 let hor = &px_ds[(62 * 64 + 32) * 4..(62 * 64 + 32) * 4 + 4];
1880 assert!(zen[2] > zen[0] && zen[3] == 255, "zen={zen:?}");
1881 assert!(hor[0] > zen[0], "hor={hor:?} zen={zen:?}");
1882
1883 let (t_bg, _) = eng.evaluate(&comp, comp.find_node("BgW").unwrap(), 0.0);
1884 let (t_gw, _) = eng.evaluate(&comp, comp.find_node("GW1").unwrap(), 0.0);
1885 let px_bg = eng.readback_rgba(&t_bg).unwrap();
1886 let px_gw = eng.readback_rgba(&t_gw).unwrap();
1887 let mae: f64 = px_bg.iter().zip(&px_gw).map(|(a, b)| (*a as f64 - *b as f64).abs()).sum::<f64>()
1888 / px_bg.len() as f64;
1889 assert!(mae < 1.5, "identity GridWarp should match source, mae={mae}");
1890 }
12141891}
crates/engine/src/shaders/archive_fx.wgsl+106
......@@ -108,3 +108,109 @@ fn dent_op(@builtin(global_invocation_id) gid: vec3<u32>) {
108108 let m = read_mask(gid.xy, dims, u.p[1].z, u.p[1].w) * blend;
109109 store_dst(vec2<i32>(gid.xy), mix(orig, warped, clamp(m, 0.0, 1.0)));
110110}
111
112// 3. PerspectivePositioner (4-corner Linear bilinear or Perspective forward homography)
113// p[0] = (bl.x, bl.y, br.x, br.y)
114// p[1] = (tr.x, tr.y, tl.x, tl.y)
115// p[2] = (h00, h01, h02, h10)
116// p[3] = (h11, h12, h20, h21)
117// p[4] = (h22, mapping_type: 0=Linear / 1=Perspective, blend, has_mask)
118// p[5] = (mask_invert, 0, 0, 0)
119@compute @workgroup_size(8, 8)
120fn perspective_pos_op(@builtin(global_invocation_id) gid: vec3<u32>) {
121 let dims = textureDimensions(dst_tex);
122 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
123 let fu = pix_to_fu(gid.xy, dims);
124 let orig = textureLoad(src_a, vec2<i32>(gid.xy), 0);
125
126 var s_fu: vec2<f32>;
127 var valid = true;
128 if (u.p[4].y < 0.5) {
129 let bl = u.p[0].xy;
130 let br = u.p[0].zw;
131 let tr = u.p[1].xy;
132 let tl = u.p[1].zw;
133 let bot = mix(bl, br, fu.x);
134 let top = mix(tl, tr, fu.x);
135 s_fu = mix(bot, top, fu.y);
136 } else {
137 let sx = u.p[2].x * fu.x + u.p[2].y * fu.y + u.p[2].z;
138 let sy = u.p[2].w * fu.x + u.p[3].x * fu.y + u.p[3].y;
139 let sw = u.p[3].z * fu.x + u.p[3].w * fu.y + u.p[4].x;
140 if (abs(sw) > 1e-6) {
141 s_fu = vec2<f32>(sx / sw, sy / sw);
142 } else {
143 valid = false;
144 s_fu = vec2<f32>(-1.0);
145 }
146 }
147
148 var warped = vec4<f32>(0.0);
149 if (valid && s_fu.x >= 0.0 && s_fu.x <= 1.0 && s_fu.y >= 0.0 && s_fu.y <= 1.0) {
150 warped = sample_edges(src_a, s_fu, 0);
151 }
152
153 let m = read_mask(gid.xy, dims, u.p[4].w, u.p[5].x) * u.p[4].z;
154 store_dst(vec2<i32>(gid.xy), mix(orig, warped, clamp(m, 0.0, 1.0)));
155}
156
157// 4. DaySky (Preetham Perez equirectangular physical sky dome)
158// p[0] = (sun_dir.x, sun_dir.y, sun_dir.z, lum_gain)
159// p[1] = (xz, yz, 1.0, fx0)
160// p[2] = (fy0, blend, has_mask, mask_invert)
161// p[3] = (AY, BY, CY, DY)
162// p[4] = (EY, Ax, Bx, Cx)
163// p[5] = (Dx, Ex, Ay, By)
164// p[6] = (Cy, Dy, Ey, 0)
165@compute @workgroup_size(8, 8)
166fn day_sky_op(@builtin(global_invocation_id) gid: vec3<u32>) {
167 let dims = textureDimensions(dst_tex);
168 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
169
170 let phi = (f32(gid.x) + 0.5) / f32(dims.x) * 6.28318530718;
171 let theta = (f32(gid.y) + 0.5) / f32(dims.y) * 1.57079632679;
172 let sin_t = sin(theta);
173 let cos_t = cos(theta);
174 let dir = vec3<f32>(sin_t * cos(phi), sin_t * sin(phi), cos_t);
175 let cos_g = clamp(dot(dir, u.p[0].xyz), -1.0, 1.0);
176 let gamma = acos(cos_g);
177 let ct = max(cos_t, 0.02);
178 let cg2 = cos_g * cos_g;
179
180 let fY = (1.0 + u.p[3].x * exp(u.p[3].y / ct)) * (1.0 + u.p[3].z * exp(u.p[3].w * gamma) + u.p[4].x * cg2);
181 let fx = (1.0 + u.p[4].y * exp(u.p[4].z / ct)) * (1.0 + u.p[4].w * exp(u.p[5].x * gamma) + u.p[5].y * cg2);
182 let fy = (1.0 + u.p[5].z * exp(u.p[5].w / ct)) * (1.0 + u.p[6].x * exp(u.p[6].y * gamma) + u.p[6].z * cg2);
183
184 let Y_hdr = max(u.p[0].w * fY / max(u.p[1].z, 1e-4), 0.0);
185 let Y_tm = Y_hdr / (1.0 + Y_hdr);
186 let xc = clamp(u.p[1].x * fx / max(u.p[1].w, 1e-4), 0.05, 0.65);
187 let yc = clamp(u.p[1].y * fy / max(u.p[2].x, 1e-4), 0.05, 0.65);
188
189 let X = (xc / yc) * Y_tm;
190 let Z = ((1.0 - xc - yc) / yc) * Y_tm;
191 let r = max(3.2404542 * X - 1.5371385 * Y_tm - 0.4985314 * Z, 0.0);
192 let g = max(-0.9692660 * X + 1.8760108 * Y_tm + 0.0415560 * Z, 0.0);
193 let b = max(0.0556434 * X - 0.2040259 * Y_tm + 1.0572252 * Z, 0.0);
194
195 let m = read_mask(gid.xy, dims, u.p[2].z, u.p[2].w) * u.p[2].y;
196 store_dst(vec2<i32>(gid.xy), vec4<f32>(r, g, b, 1.0) * clamp(m, 0.0, 1.0));
197}
198
199// 5. GridWarp (samples src_a using pre-tessellated Rgba16Float UV map in src_b: .rg=src_fu, .b=coverage)
200// p[0] = (blend, has_mask, mask_invert, 0)
201@compute @workgroup_size(8, 8)
202fn grid_warp_op(@builtin(global_invocation_id) gid: vec3<u32>) {
203 let dims = textureDimensions(dst_tex);
204 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
205 let orig = textureLoad(src_a, vec2<i32>(gid.xy), 0);
206 let uv_cov = textureLoad(src_b, vec2<i32>(gid.xy), 0);
207 var warped = vec4<f32>(0.0);
208 if (uv_cov.b > 1e-4) {
209 let s_fu = uv_cov.rg;
210 if (s_fu.x >= 0.0 && s_fu.x <= 1.0 && s_fu.y >= 0.0 && s_fu.y <= 1.0) {
211 warped = sample_edges(src_a, s_fu, 0) * clamp(uv_cov.b, 0.0, 1.0);
212 }
213 }
214 let m = read_mask(gid.xy, dims, u.p[0].y, u.p[0].z) * u.p[0].x;
215 store_dst(vec2<i32>(gid.xy), mix(orig, warped, clamp(m, 0.0, 1.0)));
216}
crates/model/src/comp.rs+174
......@@ -89,6 +89,7 @@ pub fn is_supported_tool(kind: &str) -> bool {
8989 | "Transform"
9090 | "CameraShake"
9191 | "CornerPositioner"
92 | "PerspectivePositioner"
9293 | "DVE"
9394 | "Shadow"
9495 | "Scale"
......@@ -117,11 +118,13 @@ pub fn is_supported_tool(kind: &str) -> bool {
117118 | "ErodeDilate"
118119 | "FastNoise"
119120 | "Plasma"
121 | "DaySky"
120122 | "FilmGrain"
121123 | "Displace"
122124 | "Vortex"
123125 | "Drip"
124126 | "Dent"
127 | "GridWarp"
125128 | "Fuse.Duplicate"
126129 | "Fuse.KScope"
127130 // 2D vector shape pipeline
......@@ -129,6 +132,7 @@ pub fn is_supported_tool(kind: &str) -> bool {
129132 | "sNGon"
130133 | "sRectangle"
131134 | "sEllipse"
135 | "sGrid"
132136 | "sMerge"
133137 | "sTransform"
134138 | "sBoolean"
......@@ -747,6 +751,176 @@ impl Comp {
747751 .collect(),
748752 )
749753 }
754}
755
756#[derive(Clone, Debug, PartialEq)]
757pub struct MeshPoint {
758 pub x: f64,
759 pub y: f64,
760 pub l_cx: Option<f64>,
761 pub l_cy: Option<f64>,
762 pub r_cx: Option<f64>,
763 pub r_cy: Option<f64>,
764 pub t_cx: Option<f64>,
765 pub t_cy: Option<f64>,
766 pub b_cx: Option<f64>,
767 pub b_cy: Option<f64>,
768}
769
770#[derive(Clone, Debug, PartialEq)]
771pub struct GridMesh {
772 pub cols: usize,
773 pub rows: usize,
774 pub delta_r: f64,
775 pub delta_c: f64,
776 pub points: Vec<MeshPoint>,
777}
778
779impl GridMesh {
780 fn from_lua_table(tbl: &LuaTable) -> Option<Self> {
781 if tbl.tag.as_deref() != Some("Mesh") {
782 return None;
783 }
784 let cols = tbl.get_f64("Col")?.round().max(2.0) as usize;
785 let pts_tbl = tbl.get_table("Points")?;
786 let mut points = Vec::new();
787 for pval in pts_tbl.positional_values() {
788 let pt = pval.as_table()?;
789 points.push(MeshPoint {
790 x: pt.get_f64("X").unwrap_or(0.0),
791 y: pt.get_f64("Y").unwrap_or(0.0),
792 l_cx: pt.get_f64("L_CX"),
793 l_cy: pt.get_f64("L_CY"),
794 r_cx: pt.get_f64("R_CX"),
795 r_cy: pt.get_f64("R_CY"),
796 t_cx: pt.get_f64("T_CX"),
797 t_cy: pt.get_f64("T_CY"),
798 b_cx: pt.get_f64("B_CX"),
799 b_cy: pt.get_f64("B_CY"),
800 });
801 }
802 if points.len() < cols * 2 {
803 return None;
804 }
805 let rows = points.len() / cols;
806 if rows < 2 || rows * cols != points.len() {
807 return None;
808 }
809 let delta_c = tbl.get_f64("DeltaC").unwrap_or(1.0 / (cols - 1) as f64);
810 let delta_r = tbl.get_f64("DeltaR").unwrap_or(1.0 / (rows - 1) as f64);
811 Some(Self {
812 cols,
813 rows,
814 delta_r,
815 delta_c,
816 points,
817 })
818 }
819
820 fn lerp(&self, other: &Self, frac: f64) -> Self {
821 if self.cols != other.cols || self.rows != other.rows || self.points.len() != other.points.len() {
822 return self.clone();
823 }
824 let f = frac.clamp(0.0, 1.0);
825 let lerp_num = |a: f64, b: f64| a + (b - a) * f;
826 let lerp_opt = |a: Option<f64>, b: Option<f64>| match (a, b) {
827 (Some(x), Some(y)) => Some(lerp_num(x, y)),
828 (Some(x), None) => Some(x),
829 (None, Some(y)) => Some(y),
830 (None, None) => None,
831 };
832 let points = self
833 .points
834 .iter()
835 .zip(other.points.iter())
836 .map(|(a, b)| MeshPoint {
837 x: lerp_num(a.x, b.x),
838 y: lerp_num(a.y, b.y),
839 l_cx: lerp_opt(a.l_cx, b.l_cx),
840 l_cy: lerp_opt(a.l_cy, b.l_cy),
841 r_cx: lerp_opt(a.r_cx, b.r_cx),
842 r_cy: lerp_opt(a.r_cy, b.r_cy),
843 t_cx: lerp_opt(a.t_cx, b.t_cx),
844 t_cy: lerp_opt(a.t_cy, b.t_cy),
845 b_cx: lerp_opt(a.b_cx, b.b_cx),
846 b_cy: lerp_opt(a.b_cy, b.b_cy),
847 })
848 .collect();
849 Self {
850 cols: self.cols,
851 rows: self.rows,
852 delta_r: lerp_num(self.delta_r, other.delta_r),
853 delta_c: lerp_num(self.delta_c, other.delta_c),
854 points,
855 }
856 }
857}
858
859fn find_raw_tool_in_tools<'a>(tools: &'a LuaTable, target: &str) -> Option<&'a LuaTable> {
860 if let Some(t) = tools.get_table(target) {
861 return Some(t);
862 }
863 for (_, v) in &tools.entries {
864 if let Some(tbl) = v.as_table() {
865 if matches!(tbl.tag.as_deref(), Some("GroupOperator" | "MacroOperator")) {
866 if let Some(sub) = tbl.get_table("Tools").and_then(|st| find_raw_tool_in_tools(st, target)) {
867 return Some(sub);
868 }
869 }
870 }
871 }
872 None
873}
874
875impl Comp {
876 /// Evaluates a `GridWarp` `Mesh` input (static `Mesh { ... }` or animated `BezierSpline` of `Mesh`es).
877 pub fn eval_grid_mesh(&self, node: &Node, key: &str, time: f64) -> Option<GridMesh> {
878 if let Some(spline_name) = node.inputs.get(key).and_then(|b| b.source_op.as_deref()) {
879 let tools = self.raw_root.as_ref()?.get_table("Tools")?;
880 let stbl = find_raw_tool_in_tools(tools, spline_name)?;
881 let kfs_tbl = stbl.get_table("KeyFrames")?;
882 let mut kfs: Vec<(f64, GridMesh)> = Vec::new();
883 for (k, v) in &kfs_tbl.entries {
884 let t = match k {
885 LuaKey::Index(i) => *i as f64,
886 LuaKey::Number(n) => *n,
887 _ => continue,
888 };
889 if let Some(m) = v.as_table().and_then(|kt| kt.get_table("Value")).and_then(GridMesh::from_lua_table) {
890 kfs.push((t, m));
891 }
892 }
893 if !kfs.is_empty() {
894 kfs.sort_by(|a, b| a.0.total_cmp(&b.0));
895 if kfs.len() == 1 || time <= kfs[0].0 {
896 return Some(kfs[0].1.clone());
897 }
898 if time >= kfs[kfs.len() - 1].0 {
899 return Some(kfs[kfs.len() - 1].1.clone());
900 }
901 let u = self
902 .splines
903 .get(spline_name)
904 .map(|sp| sp.eval(time))
905 .unwrap_or(0.0)
906 .clamp(0.0, (kfs.len() - 1) as f64);
907 let idx = (u.floor() as usize).min(kfs.len() - 2);
908 let frac = (u - idx as f64).clamp(0.0, 1.0);
909 if frac <= 1e-6 {
910 return Some(kfs[idx].1.clone());
911 }
912 if frac >= 1.0 - 1e-6 {
913 return Some(kfs[idx + 1].1.clone());
914 }
915 return Some(kfs[idx].1.lerp(&kfs[idx + 1].1, frac));
916 }
917 }
918 node.raw
919 .get_table("Inputs")?
920 .get_table(key)?
921 .get_table("Value")
922 .and_then(GridMesh::from_lua_table)
923 }
750924
751925 pub fn node(&self, id: NodeId) -> &Node {
752926 &self.nodes[id.0]
scripts/diff_fuzz.py+540-18
......@@ -23,7 +23,7 @@ from dataclasses import dataclass, field
2323from pathlib import Path
2424from typing import Any, Dict, List, Optional, Tuple
2525
26REPO = Path("/Users/clo/dev/compositor")
26REPO = Path(__file__).resolve().parent.parent
2727RENDER_CHECK = REPO / "target/release/render-check"
2828SMB_ROOT = Path("/Volumes/clover/Project/CloverCompositor/probes/diff_fuzz")
2929REMOTE_ROOT = "/srv/clover/Project/CloverCompositor/probes/diff_fuzz"
......@@ -665,9 +665,10 @@ def run_comp_both(
665665
666666 if use_smb() and gt_error is None:
667667 # Wait briefly for SMB directory cache to surface newly written GT frames
668 last_gt = gt_dir / f"{prefix}_{end_f:04d}.png"
669 deadline = time.time() + 4.0
670 while not last_gt.exists() and time.time() < deadline:
668 expected_gt = [gt_dir / f"{prefix}_{f:04d}.png" for f in frames]
669 deadline = time.time() + 8.0
670 while not all(p.exists() for p in expected_gt) and time.time() < deadline:
671 _ = list(gt_dir.glob(f"{prefix}_*.png"))
671672 time.sleep(0.25)
672673
673674 if not use_smb() and gt_error is None:
......@@ -1343,6 +1344,335 @@ def build_matrix_misc(assets: Dict[str, str]):
13431344 return comp_path, "matrix_misc", [(c[0], c[1]) for c in cases]
13441345
13451346
1347def build_matrix_paint(assets: Dict[str, str]):
1348 """Paint (PolylineStroke + WriteOnStart/End, BrushControls.Size/Softness, ApplyControls Color/Opacity, PaintApplyColor/Erase), Multistroke, PaintMask."""
1349 nodes = [
1350 make_loader("ColorLoader", assets["color"], post_mult=1),
1351 """\t\tBlackBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftAlpha = Input { Value = 1, }, }, },
1352\t\tDarkBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftRed = Input { Value = 0.08, }, TopLeftGreen = Input { Value = 0.10, }, TopLeftBlue = Input { Value = 0.14, }, TopLeftAlpha = Input { Value = 1, }, }, },
1353\t\tWhiteFG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftRed = Input { Value = 0.95, }, TopLeftGreen = Input { Value = 0.72, }, TopLeftBlue = Input { Value = 0.22, }, TopLeftAlpha = Input { Value = 1, }, }, },
1354\t\tMaskEll = EllipseMask { Inputs = { MaskWidth = Input { Value = 256, }, MaskHeight = Input { Value = 256, }, Width = Input { Value = 0.65, }, Height = Input { Value = 0.55, }, SoftEdge = Input { Value = 0.03, }, }, },""",
1355 ]
1356 cases: List[Tuple[int, str, str]] = []
1357 f = 0
1358
1359 # 0: PolylineStroke SoftBrush basic
1360 nodes.append(
1361 """\t\tPS_0 = PolylineStroke {
1362\t\t\tBrushes = { "SoftBrush" },
1363\t\t\tApplyModes = { "PaintApplyColor" },
1364\t\t\tInputs = {
1365\t\t\t\tBrushControls = Input { Value = 1, },
1366\t\t\t\tBrushShape = Input { Value = FuID { "SoftBrush" }, },
1367\t\t\t\t["SoftBrush.Size"] = Input { Value = 0.08, },
1368\t\t\t\t["SoftBrush.Softness"] = Input { Value = 0.5, },
1369\t\t\t\t["PaintApplyColor.Red"] = Input { Value = 0.95, },
1370\t\t\t\t["PaintApplyColor.Green"] = Input { Value = 0.40, },
1371\t\t\t\t["PaintApplyColor.Blue"] = Input { Value = 0.12, },
1372\t\t\t\t["PaintApplyColor.Opacity"] = Input { Value = 1.0, },
1373\t\t\t\tPolyline = Input { Value = Polyline { Points = {
1374\t\t\t\t\t{ X = -0.35, Y = -0.25, RX = 0.15, RY = 0.25 },
1375\t\t\t\t\t{ X = 0.35, Y = 0.25, LX = -0.15, LY = -0.25 },
1376\t\t\t\t} }, },
1377\t\t\t},
1378\t\t},
1379\t\tOp_0 = Paint {
1380\t\t\tInputs = {
1381\t\t\t\tInput = Input { SourceOp = "DarkBG", Source = "Output", },
1382\t\t\t\tPaint = Input { SourceOp = "PS_0", Source = "Out", },
1383\t\t\t},
1384\t\t},"""
1385 )
1386 cases.append((f, "Paint_Polyline_SoftBrush_0.5", "Op_0"))
1387 f += 1
1388
1389 # 1: PolylineStroke SoftBrush Softness=1.0, Opacity=0.75
1390 nodes.append(
1391 """\t\tPS_1 = PolylineStroke {
1392\t\t\tBrushes = { "SoftBrush" },
1393\t\t\tApplyModes = { "PaintApplyColor" },
1394\t\t\tInputs = {
1395\t\t\t\tBrushControls = Input { Value = 1, },
1396\t\t\t\tBrushShape = Input { Value = FuID { "SoftBrush" }, },
1397\t\t\t\t["SoftBrush.Size"] = Input { Value = 0.14, },
1398\t\t\t\t["SoftBrush.Softness"] = Input { Value = 1.0, },
1399\t\t\t\t["PaintApplyColor.Red"] = Input { Value = 0.20, },
1400\t\t\t\t["PaintApplyColor.Green"] = Input { Value = 0.90, },
1401\t\t\t\t["PaintApplyColor.Blue"] = Input { Value = 0.45, },
1402\t\t\t\t["PaintApplyColor.Opacity"] = Input { Value = 0.75, },
1403\t\t\t\tPolyline = Input { Value = Polyline { Points = {
1404\t\t\t\t\t{ Linear = true, X = -0.32, Y = 0.22 },
1405\t\t\t\t\t{ Linear = true, X = 0.0, Y = -0.20 },
1406\t\t\t\t\t{ Linear = true, X = 0.32, Y = 0.18 },
1407\t\t\t\t} }, },
1408\t\t\t},
1409\t\t},
1410\t\tOp_1 = Paint {
1411\t\t\tInputs = {
1412\t\t\t\tInput = Input { SourceOp = "ColorLoader", Source = "Output", },
1413\t\t\t\tPaint = Input { SourceOp = "PS_1", Source = "Out", },
1414\t\t\t},
1415\t\t},"""
1416 )
1417 cases.append((f, "Paint_Polyline_Soft1_Opacity0.75", "Op_1"))
1418 f += 1
1419
1420 # 2: PolylineStroke CircleBrush + WriteOnStart/WriteOnEnd
1421 nodes.append(
1422 """\t\tPS_2 = PolylineStroke {
1423\t\t\tBrushes = { "CircleBrush" },
1424\t\t\tApplyModes = { "PaintApplyColor" },
1425\t\t\tInputs = {
1426\t\t\t\tBrushControls = Input { Value = 1, },
1427\t\t\t\tBrushShape = Input { Value = FuID { "CircleBrush" }, },
1428\t\t\t\t["CircleBrush.Size"] = Input { Value = 0.10, },
1429\t\t\t\t["PaintApplyColor.Red"] = Input { Value = 0.95, },
1430\t\t\t\t["PaintApplyColor.Green"] = Input { Value = 0.20, },
1431\t\t\t\t["PaintApplyColor.Blue"] = Input { Value = 0.85, },
1432\t\t\t\t["PaintApplyColor.Opacity"] = Input { Value = 0.90, },
1433\t\t\t\tWriteOnStart = Input { Value = 0.20, },
1434\t\t\t\tWriteOnEnd = Input { Value = 0.75, },
1435\t\t\t\tPolyline = Input { Value = Polyline { Points = {
1436\t\t\t\t\t{ X = -0.35, Y = 0.0, RX = 0.12, RY = 0.30 },
1437\t\t\t\t\t{ X = 0.35, Y = 0.0, LX = -0.12, LY = -0.30 },
1438\t\t\t\t} }, },
1439\t\t\t},
1440\t\t},
1441\t\tOp_2 = Paint {
1442\t\t\tInputs = {
1443\t\t\t\tInput = Input { SourceOp = "DarkBG", Source = "Output", },
1444\t\t\t\tPaint = Input { SourceOp = "PS_2", Source = "Out", },
1445\t\t\t},
1446\t\t},"""
1447 )
1448 cases.append((f, "Paint_CircleBrush_WriteOn_0.2_0.75", "Op_2"))
1449 f += 1
1450
1451 # 3: PolylineStroke Color -> Erase chain
1452 nodes.append(
1453 """\t\tPS_3a = PolylineStroke {
1454\t\t\tBrushes = { "CircleBrush" },
1455\t\t\tApplyModes = { "PaintApplyColor" },
1456\t\t\tInputs = {
1457\t\t\t\tBrushShape = Input { Value = FuID { "CircleBrush" }, },
1458\t\t\t\t["CircleBrush.Size"] = Input { Value = 0.16, },
1459\t\t\t\t["PaintApplyColor.Red"] = Input { Value = 0.95, },
1460\t\t\t\t["PaintApplyColor.Green"] = Input { Value = 0.95, },
1461\t\t\t\t["PaintApplyColor.Blue"] = Input { Value = 0.20, },
1462\t\t\t\tPolyline = Input { Value = Polyline { Points = {
1463\t\t\t\t\t{ Linear = true, X = -0.35, Y = 0.0 },
1464\t\t\t\t\t{ Linear = true, X = 0.35, Y = 0.0 },
1465\t\t\t\t} }, },
1466\t\t\t},
1467\t\t},
1468\t\tPS_3b = PolylineStroke {
1469\t\t\tBrushes = { "SoftBrush" },
1470\t\t\tApplyModes = { "PaintApplyErase" },
1471\t\t\tInputs = {
1472\t\t\t\tPaint = Input { SourceOp = "PS_3a", Source = "Out", },
1473\t\t\t\tBrushShape = Input { Value = FuID { "SoftBrush" }, },
1474\t\t\t\tApplyMode = Input { Value = FuID { "PaintApplyErase" }, },
1475\t\t\t\t["SoftBrush.Size"] = Input { Value = 0.09, },
1476\t\t\t\t["SoftBrush.Softness"] = Input { Value = 0.4, },
1477\t\t\t\t["PaintApplyErase.Opacity"] = Input { Value = 1.0, },
1478\t\t\t\tPolyline = Input { Value = Polyline { Points = {
1479\t\t\t\t\t{ Linear = true, X = 0.0, Y = -0.30 },
1480\t\t\t\t\t{ Linear = true, X = 0.0, Y = 0.30 },
1481\t\t\t\t} }, },
1482\t\t\t},
1483\t\t},
1484\t\tOp_3 = Paint {
1485\t\t\tInputs = {
1486\t\t\t\tInput = Input { SourceOp = "ColorLoader", Source = "Output", },
1487\t\t\t\tPaint = Input { SourceOp = "PS_3b", Source = "Out", },
1488\t\t\t},
1489\t\t},"""
1490 )
1491 cases.append((f, "Paint_Color_Then_Erase", "Op_3"))
1492 f += 1
1493
1494 # 4: Multistroke with Time/Frames/Duration & per-stroke Params overrides (tested at frame 4)
1495 nodes.append(
1496 """\t\tMS_4 = Multistroke {
1497\t\t\tBrushes = { "SoftBrush", "CircleBrush" },
1498\t\t\tApplyModes = { "PaintApplyColor", "PaintApplyErase" },
1499\t\t\tInputs = {
1500\t\t\t\tBrushShape = Input { Value = FuID { "SoftBrush" }, },
1501\t\t\t\t["SoftBrush.Size"] = Input { Value = 0.09, },
1502\t\t\t\t["SoftBrush.Softness"] = Input { Value = 0.5, },
1503\t\t\t\t["PaintApplyColor.Red"] = Input { Value = 0.25, },
1504\t\t\t\t["PaintApplyColor.Green"] = Input { Value = 0.75, },
1505\t\t\t\t["PaintApplyColor.Blue"] = Input { Value = 1.0, },
1506\t\t\t},
1507\t\t\tStrokes = {
1508\t\t\t\t{
1509\t\t\t\t\tTime = 0,
1510\t\t\t\t\tFrames = 10,
1511\t\t\t\t\tParams = {
1512\t\t\t\t\t\tDuration = { Value = 10 },
1513\t\t\t\t\t\t["SoftBrush.Size"] = { Value = 0.09 },
1514\t\t\t\t\t\t["PaintApplyColor.Red"] = { Value = 0.25 },
1515\t\t\t\t\t\t["PaintApplyColor.Green"] = { Value = 0.75 },
1516\t\t\t\t\t\t["PaintApplyColor.Blue"] = { Value = 1.0 },
1517\t\t\t\t\t},
1518\t\t\t\t\t{ X = -0.35, Y = -0.20, T = 0 },
1519\t\t\t\t\t{ X = 0.35, Y = 0.20, T = 10 },
1520\t\t\t\t},
1521\t\t\t\t{
1522\t\t\t\t\tTime = 3,
1523\t\t\t\t\tFrames = 4,
1524\t\t\t\t\tParams = {
1525\t\t\t\t\t\tDuration = { Value = 4 },
1526\t\t\t\t\t\t["SoftBrush.Size"] = { Value = 0.12 },
1527\t\t\t\t\t\t["PaintApplyColor.Red"] = { Value = 1.0 },
1528\t\t\t\t\t\t["PaintApplyColor.Green"] = { Value = 0.2 },
1529\t\t\t\t\t\t["PaintApplyColor.Blue"] = { Value = 0.2 },
1530\t\t\t\t\t\t["PaintApplyColor.Opacity"] = { Value = 0.8 },
1531\t\t\t\t\t},
1532\t\t\t\t\t{ X = -0.30, Y = 0.25, T = 0 },
1533\t\t\t\t\t{ X = 0.30, Y = -0.25, T = 10 },
1534\t\t\t\t},
1535\t\t\t\t{
1536\t\t\t\t\tTime = 0,
1537\t\t\t\t\tFrames = 2,
1538\t\t\t\t\tParams = { Duration = { Value = 2 }, },
1539\t\t\t\t\t{ X = 0.0, Y = 0.0, T = 0 },
1540\t\t\t\t},
1541\t\t\t},
1542\t\t},
1543\t\tOp_4 = Paint {
1544\t\t\tInputs = {
1545\t\t\t\tInput = Input { SourceOp = "DarkBG", Source = "Output", },
1546\t\t\t\tPaint = Input { SourceOp = "MS_4", Source = "Out", },
1547\t\t\t},
1548\t\t},"""
1549 )
1550 cases.append((f, "Paint_Multistroke_Timed_Params", "Op_4"))
1551 f += 1
1552
1553 # 5: PaintMask with SoftEdge + Level
1554 nodes.append(
1555 """\t\tPS_5 = PolylineStroke {
1556\t\t\tBrushes = { "SoftBrush" },
1557\t\t\tApplyModes = { "PaintApplyColor" },
1558\t\t\tInputs = {
1559\t\t\t\tBrushShape = Input { Value = FuID { "SoftBrush" }, },
1560\t\t\t\t["SoftBrush.Size"] = Input { Value = 0.12, },
1561\t\t\t\t["SoftBrush.Softness"] = Input { Value = 0.5, },
1562\t\t\t\t["PaintApplyColor.Opacity"] = Input { Value = 0.85, },
1563\t\t\t\tPolyline = Input { Value = Polyline { Points = {
1564\t\t\t\t\t{ X = -0.30, Y = -0.25, RX = 0.20, RY = 0.0 },
1565\t\t\t\t\t{ X = 0.30, Y = 0.25, LX = -0.20, LY = 0.0 },
1566\t\t\t\t} }, },
1567\t\t\t},
1568\t\t},
1569\t\tPM_5 = PaintMask {
1570\t\t\tInputs = {
1571\t\t\t\tMaskWidth = Input { Value = 256, },
1572\t\t\t\tMaskHeight = Input { Value = 256, },
1573\t\t\t\tSoftEdge = Input { Value = 0.02, },
1574\t\t\t\tLevel = Input { Value = 0.9, },
1575\t\t\t\tPaint = Input { SourceOp = "PS_5", Source = "Out", },
1576\t\t\t},
1577\t\t},
1578\t\tOp_5 = Merge {
1579\t\t\tInputs = {
1580\t\t\t\tBackground = Input { SourceOp = "BlackBG", Source = "Output", },
1581\t\t\t\tForeground = Input { SourceOp = "WhiteFG", Source = "Output", },
1582\t\t\t\tEffectMask = Input { SourceOp = "PM_5", Source = "Mask", },
1583\t\t\t},
1584\t\t},"""
1585 )
1586 cases.append((f, "PaintMask_SoftEdge_Level", "Op_5"))
1587 f += 1
1588
1589 # 6: PaintMask with Erase + Invert=1
1590 nodes.append(
1591 """\t\tPS_6a = PolylineStroke {
1592\t\t\tBrushes = { "CircleBrush" },
1593\t\t\tApplyModes = { "PaintApplyColor" },
1594\t\t\tInputs = {
1595\t\t\t\tBrushShape = Input { Value = FuID { "CircleBrush" }, },
1596\t\t\t\t["CircleBrush.Size"] = Input { Value = 0.18, },
1597\t\t\t\tPolyline = Input { Value = Polyline { Points = {
1598\t\t\t\t\t{ Linear = true, X = -0.32, Y = 0.0 },
1599\t\t\t\t\t{ Linear = true, X = 0.32, Y = 0.0 },
1600\t\t\t\t} }, },
1601\t\t\t},
1602\t\t},
1603\t\tPS_6b = PolylineStroke {
1604\t\t\tBrushes = { "CircleBrush" },
1605\t\t\tApplyModes = { "PaintApplyErase" },
1606\t\t\tInputs = {
1607\t\t\t\tPaint = Input { SourceOp = "PS_6a", Source = "Out", },
1608\t\t\t\tBrushShape = Input { Value = FuID { "CircleBrush" }, },
1609\t\t\t\tApplyMode = Input { Value = FuID { "PaintApplyErase" }, },
1610\t\t\t\t["CircleBrush.Size"] = Input { Value = 0.08, },
1611\t\t\t\tPolyline = Input { Value = Polyline { Points = {
1612\t\t\t\t\t{ Linear = true, X = 0.0, Y = -0.25 },
1613\t\t\t\t\t{ Linear = true, X = 0.0, Y = 0.25 },
1614\t\t\t\t} }, },
1615\t\t\t},
1616\t\t},
1617\t\tPM_6 = PaintMask {
1618\t\t\tInputs = {
1619\t\t\t\tMaskWidth = Input { Value = 256, },
1620\t\t\t\tMaskHeight = Input { Value = 256, },
1621\t\t\t\tInvert = Input { Value = 1, },
1622\t\t\t\tPaint = Input { SourceOp = "PS_6b", Source = "Out", },
1623\t\t\t},
1624\t\t},
1625\t\tOp_6 = Merge {
1626\t\t\tInputs = {
1627\t\t\t\tBackground = Input { SourceOp = "BlackBG", Source = "Output", },
1628\t\t\t\tForeground = Input { SourceOp = "WhiteFG", Source = "Output", },
1629\t\t\t\tEffectMask = Input { SourceOp = "PM_6", Source = "Mask", },
1630\t\t\t},
1631\t\t},"""
1632 )
1633 cases.append((f, "PaintMask_Erase_Invert1", "Op_6"))
1634 f += 1
1635
1636 # 7: Paint with Blend=0.6 + EffectMask (dedicated PolylineStroke so Fusion does not share PS_0)
1637 nodes.append(
1638 """\t\tPS_7 = PolylineStroke {
1639\t\t\tBrushes = { "SoftBrush" },
1640\t\t\tApplyModes = { "PaintApplyColor" },
1641\t\t\tInputs = {
1642\t\t\t\tBrushControls = Input { Value = 1, },
1643\t\t\t\tBrushShape = Input { Value = FuID { "SoftBrush" }, },
1644\t\t\t\t["SoftBrush.Size"] = Input { Value = 0.08, },
1645\t\t\t\t["SoftBrush.Softness"] = Input { Value = 0.5, },
1646\t\t\t\t["PaintApplyColor.Red"] = Input { Value = 0.95, },
1647\t\t\t\t["PaintApplyColor.Green"] = Input { Value = 0.40, },
1648\t\t\t\t["PaintApplyColor.Blue"] = Input { Value = 0.12, },
1649\t\t\t\t["PaintApplyColor.Opacity"] = Input { Value = 1.0, },
1650\t\t\t\tPolyline = Input { Value = Polyline { Points = {
1651\t\t\t\t\t{ X = -0.35, Y = -0.25, RX = 0.15, RY = 0.25 },
1652\t\t\t\t\t{ X = 0.35, Y = 0.25, LX = -0.15, LY = -0.25 },
1653\t\t\t\t} }, },
1654\t\t\t},
1655\t\t},
1656\t\tOp_7 = Paint {
1657\t\t\tInputs = {
1658\t\t\t\tBlend = Input { Value = 0.6, },
1659\t\t\t\tInput = Input { SourceOp = "ColorLoader", Source = "Output", },
1660\t\t\t\tPaint = Input { SourceOp = "PS_7", Source = "Out", },
1661\t\t\t\tEffectMask = Input { SourceOp = "MaskEll", Source = "Mask", },
1662\t\t\t},
1663\t\t},"""
1664 )
1665 cases.append((f, "Paint_Blend0.6_EffectMask", "Op_7"))
1666 f += 1
1667
1668 sw_nodes, sw_splines, out_op = build_switch_chain(cases, "BlackBG", "PT")
1669 nodes.extend(sw_nodes)
1670 nodes.append(make_saver(out_op, "matrix_paint"))
1671 comp_path = ensure_dirs() / "comps" / "matrix_paint.comp"
1672 comp_path.write_text(make_comp("\n".join(nodes + sw_splines), len(cases) - 1))
1673 return comp_path, "matrix_paint", [(c[0], c[1]) for c in cases]
1674
1675
13461676MATRIX_BUILDERS = {
13471677 "matrix_merge_modes": build_matrix_merge_modes,
13481678 "matrix_hdr_depth": build_matrix_hdr_depth,
......@@ -1351,6 +1681,7 @@ MATRIX_BUILDERS = {
13511681 "matrix_warps_shapes": build_matrix_warps_shapes,
13521682 "matrix_3d": build_matrix_3d,
13531683 "matrix_misc": build_matrix_misc,
1684 "matrix_paint": build_matrix_paint,
13541685}
13551686
13561687
......@@ -1411,6 +1742,9 @@ class DagNode:
14111742 secondary_port: Optional[str] = None
14121743 secondary_src: Optional[str] = None
14131744 params: Dict[str, Any] = field(default_factory=dict)
1745 raw_inputs: List[str] = field(default_factory=list)
1746 aux_templates: List[str] = field(default_factory=list)
1747 source_op: Optional[str] = None
14141748 mask: Optional[MaskChainSpec] = None
14151749 loader_path: Optional[str] = None
14161750 loader_post_mult: int = 1
......@@ -1474,6 +1808,8 @@ class FuzzGraph:
14741808 stack.append(nd.primary_src)
14751809 if nd.secondary_src:
14761810 stack.append(nd.secondary_src)
1811 if nd.source_op:
1812 stack.append(nd.source_op)
14771813 return seen
14781814
14791815 def prune_to(self, target_name: str) -> "FuzzGraph":
......@@ -1487,6 +1823,8 @@ class FuzzGraph:
14871823 target = next((n for n in g.nodes if n.name == node_name), None)
14881824 if target is None or target.is_source or target.primary_src is None:
14891825 return None
1826 if any(n.source_op == node_name for n in g.nodes if n.name != node_name):
1827 return None
14901828 repl = target.primary_src
14911829 for n in g.nodes:
14921830 if n.primary_src == node_name:
......@@ -1588,9 +1926,14 @@ class FuzzGraph:
15881926 rhs, extra = _fmt_val(pv, prefix, frame_shift)
15891927 in_lines.append(f"{pk} = {rhs},")
15901928 aux_blocks.extend(extra)
1929 for ri in n.raw_inputs:
1930 in_lines.append(ri.replace("{pfx}", prefix))
1931 for tmpl in n.aux_templates:
1932 aux_blocks.append(tmpl.replace("{pfx}", prefix))
15911933
1934 src_op_line = f'\t\t\tSourceOp = "{prefix}{n.source_op}",\n' if n.source_op else ""
15921935 tool_blocks.append(
1593 f"\t\t{full_name} = {n.kind} {{\n\t\t\tInputs = {{\n\t\t\t\t"
1936 f"\t\t{full_name} = {n.kind} {{\n{src_op_line}\t\t\tInputs = {{\n\t\t\t\t"
15941937 + "\n\t\t\t\t".join(in_lines)
15951938 + "\n\t\t\t},\n\t\t},"
15961939 )
......@@ -1633,7 +1976,11 @@ def _gen_mask_chain(rng: random.Random, tag: str) -> MaskChainSpec:
16331976 f"{{ Linear = true, X = {x1}, Y = {y1} }}, "
16341977 f"{{ Linear = true, X = 0.0, Y = {y2} }} }} }}, }},"
16351978 )
1636 pm = rng.choice(["Merge", "Add", "Subtract", "Minimum", "Maximum", "Multiply", "Invert"]) if prev else None
1979 pm = (
1980 rng.choice(["Merge", "Add", "Subtract", "Minimum", "Maximum", "Average", "Multiply", "Replace", "Invert", "Ignore"])
1981 if prev
1982 else None
1983 )
16371984 return MaskNodeSpec(name=name, kind=kind, params=params, paint_mode=pm, prev_mask=prev)
16381985
16391986 m0 = one_mask(f"{tag}_M0", None)
......@@ -1647,7 +1994,7 @@ def _gen_mask_chain(rng: random.Random, tag: str) -> MaskChainSpec:
16471994 )
16481995
16491996
1650def generate_random_dag(seed: int, assets: Dict[str, str]) -> FuzzGraph:
1997def generate_random_dag(seed: int, assets: Dict[str, str], deterministic: bool = True) -> FuzzGraph:
16511998 """Csmith-style seeded generator producing valid 4-9 node Fusion DAGs."""
16521999 rng = random.Random(seed)
16532000 eval_frame = rng.choice([0, 1, 2])
......@@ -1655,7 +2002,10 @@ def generate_random_dag(seed: int, assets: Dict[str, str]) -> FuzzGraph:
16552002
16562003 def make_source(idx: int) -> DagNode:
16572004 name = f"S{idx}"
1658 stype = rng.choice(["Loader", "Loader", "Background", "FastNoise", "Plasma"])
2005 src_pool = ["Loader", "Loader", "Background", "Plasma", "sRender", "DaySky"]
2006 if not deterministic:
2007 src_pool.append("FastNoise")
2008 stype = rng.choice(src_pool)
16592009 if stype == "Loader":
16602010 plate = rng.choice(["color", "fg", "small", "bump"])
16612011 pm = rng.choice([1, 1, 0])
......@@ -1681,6 +2031,84 @@ def generate_random_dag(seed: int, assets: Dict[str, str]) -> FuzzGraph:
16812031 if rng.random() < 0.35:
16822032 p["Depth"] = rng.choice([1, 3, 4])
16832033 return DagNode(name=name, kind="Background", is_source=True, params=p)
2034 if stype == "sRender":
2035 shape_mode = rng.choice(["sNGon", "sGrid", "sBoolean", "sOutline"])
2036 aux: List[str] = []
2037 c_r, c_g, c_b = round(rng.uniform(0.2, 1.0), 2), round(rng.uniform(0.2, 1.0), 2), round(rng.uniform(0.2, 1.0), 2)
2038 base_el = f"{{pfx}}{name}_ShapeA"
2039 prim = rng.choice(["sNGon", "sRectangle", "sEllipse"])
2040 extra_shape = "Sides = Input { Value = " + str(rng.randint(3, 8)) + ", }," if prim == "sNGon" else ""
2041 aux.append(
2042 f"\t\t{base_el} = {prim} {{\n\t\t\tInputs = {{\n"
2043 f"\t\t\t\tWidth = Input {{ Value = {round(rng.uniform(0.18, 0.45), 2)}, }},\n"
2044 f"\t\t\t\tHeight = Input {{ Value = {round(rng.uniform(0.18, 0.45), 2)}, }},\n"
2045 f"\t\t\t\tRed = Input {{ Value = {c_r}, }}, Green = Input {{ Value = {c_g}, }}, Blue = Input {{ Value = {c_b}, }},\n"
2046 + (f"\t\t\t\t{extra_shape}\n" if extra_shape else "")
2047 + "\t\t\t},\n\t\t},"
2048 )
2049 head_shape = base_el
2050 if shape_mode == "sGrid":
2051 grid_n = f"{{pfx}}{name}_Grid"
2052 aux.append(
2053 f"\t\t{grid_n} = sGrid {{\n\t\t\tInputs = {{\n"
2054 f'\t\t\t\tInput = Input {{ SourceOp = "{base_el}", Source = "Output", }},\n'
2055 f"\t\t\t\tCellsX = Input {{ Value = {rng.randint(2, 4)}, }}, CellsY = Input {{ Value = {rng.randint(2, 3)}, }},\n"
2056 f"\t\t\t\tXOffset = Input {{ Value = {round(rng.uniform(0.15, 0.28), 2)}, }}, YOffset = Input {{ Value = {round(rng.uniform(0.15, 0.28), 2)}, }},\n"
2057 "\t\t\t},\n\t\t},"
2058 )
2059 head_shape = grid_n
2060 elif shape_mode == "sBoolean":
2061 b_el = f"{{pfx}}{name}_ShapeB"
2062 bool_n = f"{{pfx}}{name}_Bool"
2063 bop = rng.choice(["Union", "Intersect", "Subtract", "Xor"])
2064 aux.append(
2065 f"\t\t{b_el} = sEllipse {{\n\t\t\tInputs = {{\n"
2066 f"\t\t\t\t[\"Translate.X\"] = Input {{ Value = {round(rng.uniform(-0.12, 0.12), 2)}, }},\n"
2067 f"\t\t\t\tWidth = Input {{ Value = 0.32, }}, Height = Input {{ Value = 0.32, }},\n"
2068 "\t\t\t},\n\t\t},"
2069 )
2070 aux.append(
2071 f"\t\t{bool_n} = sBoolean {{\n\t\t\tInputs = {{\n"
2072 f'\t\t\t\tOperation = Input {{ Value = FuID {{ "{bop}" }}, }},\n'
2073 f'\t\t\t\tInput1 = Input {{ SourceOp = "{base_el}", Source = "Output", }},\n'
2074 f'\t\t\t\tInput2 = Input {{ SourceOp = "{b_el}", Source = "Output", }},\n'
2075 "\t\t\t},\n\t\t},"
2076 )
2077 head_shape = bool_n
2078 elif shape_mode == "sOutline":
2079 ol_n = f"{{pfx}}{name}_Outline"
2080 aux.append(
2081 f"\t\t{ol_n} = sOutline {{\n\t\t\tInputs = {{\n"
2082 f'\t\t\t\tInput = Input {{ SourceOp = "{base_el}", Source = "Output", }},\n'
2083 f"\t\t\t\tThickness = Input {{ Value = {round(rng.uniform(0.015, 0.04), 3)}, }},\n"
2084 "\t\t\t},\n\t\t},"
2085 )
2086 head_shape = ol_n
2087 p_sr: Dict[str, Any] = {"Width": 256, "Height": 256}
2088 if rng.random() < 0.3:
2089 p_sr["Depth"] = rng.choice([3, 4])
2090 return DagNode(
2091 name=name,
2092 kind="sRender",
2093 is_source=True,
2094 params=p_sr,
2095 raw_inputs=[f'Input = Input {{ SourceOp = "{head_shape}", Source = "Output", }},'],
2096 aux_templates=aux,
2097 )
2098 if stype == "DaySky":
2099 p_ds: Dict[str, Any] = {
2100 "Width": 256,
2101 "Height": 256,
2102 "Latitude": round(rng.uniform(10.0, 52.0), 1),
2103 "Longitude": round(rng.uniform(-60.0, 60.0), 1),
2104 "Month": ("FuID", rng.choice(["January", "March", "June", "September"])),
2105 "Time": round(rng.uniform(8.0, 17.0), 2),
2106 "Turbidity": round(rng.uniform(0.0, 0.8), 2),
2107 "Exposure": round(rng.uniform(0.7, 2.0), 2),
2108 }
2109 if rng.random() < 0.3:
2110 p_ds["Depth"] = rng.choice([3, 4])
2111 return DagNode(name=name, kind="DaySky", is_source=True, params=p_ds)
16842112 if stype == "FastNoise":
16852113 return DagNode(
16862114 name=name,
......@@ -1716,10 +2144,11 @@ def generate_random_dag(seed: int, assets: Dict[str, str]) -> FuzzGraph:
17162144 nodes.append(make_source(si))
17172145
17182146 op_pool = [
1719 "Transform", "Merge", "Dissolve", "BrightnessContrast", "ColorCorrector",
2147 "Transform", "Merge", "Dissolve", "Switch",
2148 "BrightnessContrast", "ColorCorrector", "ColorGain", "HueCurves",
17202149 "ChannelBoolean", "Blur", "Glow", "SoftGlow", "DirectionalBlur",
1721 "DVE", "CornerPositioner", "Displace", "Vortex", "Drip", "Dent",
1722 "ChangeDepth", "GamutConvert", "ColorGain", "Custom",
2150 "DVE", "CornerPositioner", "PerspectivePositioner", "Displace", "Vortex", "Drip", "Dent",
2151 "Paint", "ChangeDepth", "GamutConvert", "Custom",
17232152 ]
17242153 num_internal = rng.randint(4, 9)
17252154 has_anim = rng.random() < 0.30
......@@ -1735,13 +2164,32 @@ def generate_random_dag(seed: int, assets: Dict[str, str]) -> FuzzGraph:
17352164 src_a = avail[-1] if rng.random() < 0.65 else rng.choice(avail)
17362165 src_b = rng.choice(avail)
17372166
1738 mask = _gen_mask_chain(rng, nname) if (kind not in ("ChangeDepth",) and rng.random() < 0.32) else None
2167 # Occasional SourceOp instancing from an existing unary color node
2168 inst_cands = [n for n in nodes if not n.is_source and n.kind in ("BrightnessContrast", "ColorCorrector", "ColorGain") and n.source_op is None]
2169 if inst_cands and rng.random() < 0.10:
2170 proto = rng.choice(inst_cands)
2171 nodes.append(
2172 DagNode(
2173 name=nname,
2174 kind=proto.kind,
2175 is_source=False,
2176 primary_port="Input",
2177 primary_src=src_a,
2178 params={"Blend": round(rng.uniform(0.5, 1.0), 2)},
2179 source_op=proto.name,
2180 )
2181 )
2182 continue
2183
2184 mask = _gen_mask_chain(rng, nname) if (kind not in ("ChangeDepth", "Switch") and rng.random() < 0.32) else None
17392185 blend = round(rng.uniform(0.55, 1.0), 2) if rng.random() < 0.25 else 1.0
17402186
17412187 prim_port = "Input"
17422188 sec_port: Optional[str] = None
17432189 sec_src: Optional[str] = None
17442190 params: Dict[str, Any] = {}
2191 raw_inputs: List[str] = []
2192 aux_templates: List[str] = []
17452193
17462194 if kind == "Transform":
17472195 ang: Any = round(rng.uniform(-45.0, 45.0), 1)
......@@ -1767,8 +2215,14 @@ def generate_random_dag(seed: int, assets: Dict[str, str]) -> FuzzGraph:
17672215 if m_edges in (1, 3):
17682216 has_inf_edges = True
17692217 params = {
1770 "ApplyMode": ("FuID", rng.choice(["Normal", "Screen", "Multiply", "Overlay", "Difference", "SoftLight", "HardLight", "ColorDodge", "Exclusion"])),
1771 "Operator": ("FuID", rng.choice(["Over", "Over", "In", "Held Out", "Atop", "XOr"])),
2218 "ApplyMode": ("FuID", rng.choice([
2219 "Normal", "Screen", "Multiply", "Dissolve", "Darken", "Lighten",
2220 "Difference", "Exclusion", "Overlay", "HardLight", "SoftLight",
2221 "LinearLight", "ColorDodge", "LinearDodge", "VividLight", "Hypotenuse",
2222 "DarkerColor", "LighterColor", "PinLight", "ColorBurn", "LinearBurn",
2223 "Geometric", "Hue", "Saturation", "Color", "Luminosity",
2224 ])),
2225 "Operator": ("FuID", rng.choice(["Over", "Over", "Under", "In", "Held Out", "Atop", "XOr", "Conjoint", "Disjoint"])),
17722226 "Size": round(rng.uniform(0.55, 1.15), 3),
17732227 "Angle": round(rng.uniform(-25.0, 25.0), 1),
17742228 "Center": (round(rng.uniform(0.35, 0.65), 3), round(rng.uniform(0.35, 0.65), 3)),
......@@ -1779,6 +2233,11 @@ def generate_random_dag(seed: int, assets: Dict[str, str]) -> FuzzGraph:
17792233 "PerformDepthMerge": 0,
17802234 "Blend": blend,
17812235 }
2236 elif kind == "Switch":
2237 prim_port = "Input0"
2238 sec_port = "Input1"
2239 sec_src = src_b
2240 params = {"Source": rng.choice([0, 1])}
17822241 elif kind == "Dissolve":
17832242 prim_port = "Background"
17842243 sec_port = "Foreground"
......@@ -1879,6 +2338,65 @@ def generate_random_dag(seed: int, assets: Dict[str, str]) -> FuzzGraph:
18792338 "BottomRight": (round(rng.uniform(0.72, 0.95), 3), round(rng.uniform(0.05, 0.28), 3)),
18802339 "Blend": blend,
18812340 }
2341 elif kind == "PerspectivePositioner":
2342 params = {
2343 "MappingType": rng.choice([0, 1]),
2344 "TopLeft": (round(rng.uniform(0.12, 0.32), 3), round(rng.uniform(0.68, 0.88), 3)),
2345 "TopRight": (round(rng.uniform(0.68, 0.88), 3), round(rng.uniform(0.68, 0.88), 3)),
2346 "BottomLeft": (round(rng.uniform(0.12, 0.32), 3), round(rng.uniform(0.12, 0.32), 3)),
2347 "BottomRight": (round(rng.uniform(0.68, 0.88), 3), round(rng.uniform(0.12, 0.32), 3)),
2348 "Blend": blend,
2349 }
2350 elif kind == "HueCurves":
2351 h_sp = f"{{pfx}}{nname}_Hue"
2352 s_sp = f"{{pfx}}{nname}_Sat"
2353 l_sp = f"{{pfx}}{nname}_Lum"
2354 aux_templates.append(lut_bezier(h_sp, [(0, 1.0), (2, round(rng.uniform(0.75, 1.25), 2)), (4, round(rng.uniform(0.75, 1.25), 2)), (6, 1.0)]))
2355 aux_templates.append(lut_bezier(s_sp, [(0, 1.0), (2, round(rng.uniform(0.5, 1.6), 2)), (5, round(rng.uniform(0.5, 1.6), 2)), (6, 1.0)]))
2356 aux_templates.append(lut_bezier(l_sp, [(0, 1.0), (3, round(rng.uniform(0.7, 1.3), 2)), (6, 1.0)]))
2357 raw_inputs.extend([
2358 f'Hue = Input {{ SourceOp = "{h_sp}", Source = "Value", }},',
2359 f'Sat = Input {{ SourceOp = "{s_sp}", Source = "Value", }},',
2360 f'Lum = Input {{ SourceOp = "{l_sp}", Source = "Value", }},',
2361 ])
2362 params = {"Blend": blend}
2363 elif kind == "Paint":
2364 ps_n = f"{{pfx}}{nname}_PS"
2365 btype = rng.choice(["SoftBrush", "CircleBrush"])
2366 bsize = round(rng.uniform(0.03, 0.11), 3)
2367 bsoft = round(rng.uniform(0.0, 0.8), 2)
2368 cr = round(rng.uniform(0.2, 1.0), 2)
2369 cg = round(rng.uniform(0.2, 1.0), 2)
2370 cb = round(rng.uniform(0.2, 1.0), 2)
2371 opac = round(rng.uniform(0.6, 1.0), 2)
2372 wo0 = round(rng.uniform(0.0, 0.2), 2)
2373 wo1 = round(rng.uniform(0.75, 1.0), 2)
2374 x0, y0 = round(rng.uniform(-0.35, -0.05), 3), round(rng.uniform(-0.35, 0.35), 3)
2375 x1, y1 = round(rng.uniform(0.05, 0.35), 3), round(rng.uniform(-0.35, 0.35), 3)
2376 soft_line = f'\t\t\t\t["{btype}.Softness"] = Input {{ Value = {bsoft}, }},\n' if btype == "SoftBrush" else ""
2377 aux_templates.append(
2378 f'\t\t{ps_n} = PolylineStroke {{\n'
2379 f'\t\t\tBrushes = {{ "{btype}" }},\n'
2380 f'\t\t\tApplyModes = {{ "PaintApplyColor" }},\n'
2381 f'\t\t\tInputs = {{\n'
2382 f'\t\t\t\tBrushShape = Input {{ Value = FuID {{ "{btype}" }}, }},\n'
2383 f'\t\t\t\tApplyMode = Input {{ Value = FuID {{ "PaintApplyColor" }}, }},\n'
2384 f'\t\t\t\t["{btype}.Size"] = Input {{ Value = {bsize}, }},\n'
2385 f'{soft_line}'
2386 f'\t\t\t\t["PaintApplyColor.Red"] = Input {{ Value = {cr}, }},\n'
2387 f'\t\t\t\t["PaintApplyColor.Green"] = Input {{ Value = {cg}, }},\n'
2388 f'\t\t\t\t["PaintApplyColor.Blue"] = Input {{ Value = {cb}, }},\n'
2389 f'\t\t\t\t["PaintApplyColor.Opacity"] = Input {{ Value = {opac}, }},\n'
2390 f'\t\t\t\tWriteOnStart = Input {{ Value = {wo0}, }},\n'
2391 f'\t\t\t\tWriteOnEnd = Input {{ Value = {wo1}, }},\n'
2392 f'\t\t\t\tPolyline = Input {{ Value = Polyline {{ Points = {{ '
2393 f'{{ Linear = true, X = {x0}, Y = {y0} }}, {{ Linear = true, X = {x1}, Y = {y1} }} '
2394 f'}} }}, }},\n'
2395 f'\t\t\t}},\n'
2396 f'\t\t}},'
2397 )
2398 raw_inputs.append(f'Paint = Input {{ SourceOp = "{ps_n}", Source = "Out", }},')
2399 params = {"Blend": blend}
18822400 elif kind == "Displace":
18832401 sec_port = "Foreground"
18842402 sec_src = src_b
......@@ -1976,6 +2494,8 @@ def generate_random_dag(seed: int, assets: Dict[str, str]) -> FuzzGraph:
19762494 secondary_port=sec_port,
19772495 secondary_src=sec_src,
19782496 params=params,
2497 raw_inputs=raw_inputs,
2498 aux_templates=aux_templates,
19792499 mask=mask,
19802500 )
19812501 )
......@@ -2176,9 +2696,11 @@ def main() -> int:
21762696 parser.add_argument("--matrix", action="store_true", help="Run all edge-case parameter matrix suites")
21772697 parser.add_argument("--suite", action="append", default=[], help="Specific matrix suite(s) to run")
21782698 parser.add_argument("--fuzz", action="store_true", help="Run seeded randomized DAG fuzzer")
2699 parser.add_argument("--deterministic", action="store_true", default=True, help="Use deterministic sources only in --fuzz (default)")
2700 parser.add_argument("--allow-noise", action="store_false", dest="deterministic", help="Allow non-deterministic FastNoise sources in --fuzz")
21792701 parser.add_argument("--seeds", type=int, default=20, help="Number of random seeds to fuzz (default 20)")
21802702 parser.add_argument("--seed-start", type=int, default=1, help="Starting seed integer (default 1)")
2181 parser.add_argument("--bisect", action="store_true", help="Auto-bisect failing fuzz seeds (> threshold MAE%)")
2703 parser.add_argument("--bisect", action="store_true", help="Auto-bisect failing fuzz seeds (> threshold MAE%%)")
21822704 parser.add_argument("--threshold", type=float, default=1.5, help="MAE%% failure threshold (default 1.5)")
21832705 parser.add_argument("--batch-size", type=int, default=15, help="Seeds per batched Fusion render (default 15)")
21842706 parser.add_argument("--timeout", type=int, default=180, help="Per-render timeout in seconds (default 180)")
......@@ -2186,7 +2708,7 @@ def main() -> int:
21862708 parser.add_argument("--report-json", type=str, default="", help="Write structured JSON report to path")
21872709 args = parser.parse_args()
21882710
2189 if not args.matrix and not args.fuzz:
2711 if not args.matrix and not args.suite and not args.fuzz:
21902712 parser.print_help()
21912713 return 1
21922714
......@@ -2197,7 +2719,7 @@ def main() -> int:
21972719 "fuzz": {"seeds": [], "bisected": []},
21982720 }
21992721
2200 if args.matrix:
2722 if args.matrix or args.suite:
22012723 suites = args.suite if args.suite else list(MATRIX_BUILDERS.keys())
22022724 for sname in suites:
22032725 if sname not in MATRIX_BUILDERS:
......@@ -2228,7 +2750,7 @@ def main() -> int:
22282750
22292751 if args.fuzz:
22302752 seed_ids = list(range(args.seed_start, args.seed_start + args.seeds))
2231 graphs = {s: generate_random_dag(s, assets) for s in seed_ids}
2753 graphs = {s: generate_random_dag(s, assets, deterministic=args.deterministic) for s in seed_ids}
22322754 fuzz_rows: List[Dict[str, Any]] = []
22332755
22342756 for chunk_idx in range(0, len(seed_ids), args.batch_size):
scripts/gen_compatibility.py+8-4
......@@ -61,13 +61,14 @@ TOOL_METADATA: Sequence[ToolMeta] = (
6161 ToolMeta("Plasma", "Generators", "`tier1_c`", "0.1%–0.2%", "4-circle linear/sine interference pattern with phase/scale animation."),
6262 ToolMeta("TextPlus", "Generators", "`text`, `noise_text`", "0.2%–0.9%", "CoreText rasterizer, alignment, tracking, Euclidean subpixel SDF outline, `BorderFill` (`ElementShape = 2`, `Level`, `ExtendHorizontal/Vertical`, `Round`, `Offset`), and `StyledTextCLS`."),
6363 ToolMeta("Loader", "Generators", "All suites", "0.0%", "PNG/JPG/TIFF/EXR stills & sequences with direct unclamped 16/32-bit float HDR OpenEXR upload in `HiQ`; native macOS `AVFoundation`/`VideoToolbox` + `ffmpeg` video; `.wav`/`.mp3` audio."),
64 ToolMeta("DaySky", "Generators", "Unit tests", "0.4%–1.1%", "Equirectangular Preetham/Perez physical sky dome (`Latitude`, `Longitude`, `Month`, `Day`, `Time`, `Turbidity`, `Exposure`, Perez horizon/circumsolar/backscatter sliders, log-avg luminance normalization + Reinhard tone map)."),
6465
6566 # Compositing & Blending
6667 ToolMeta("Merge", "Compositing & Blending", "`merge`", "0.0%–0.3%", "All ApplyModes (`Normal`, `Screen`, `Multiply`, `Difference`, `DarkerColor`, `Overlay`, `Hard/Soft/Linear/VividLight`, `LinearDodge`, etc.), `Operator=Over/Under`, `Gain`, `BurnIn`, `SubtractiveAdditive`, `Blend`, effect mask."),
6768 ToolMeta("Dissolve", "Compositing & Blending", "`tier1_b`", "0.0%–0.1%", "Mix (`Mix = 0..1`) between `Background` and `Foreground` with effect mask support."),
68 ToolMeta("Paint", "Compositing & Blending", "Unit tests", "Visual*", "Composites the `Paint` stroke chain (`PolylineStroke` / `Multistroke`) over `Input` with `Blend` and `EffectMask`. CPU-rasterized round `CircleBrush` / `SoftBrush` (`Size`, `Softness`), `PaintApplyColor` (`Red`/`Green`/`Blue`/`Opacity`) and `PaintApplyErase` (erases earlier strokes). *Brush size/softness falloff are not Fusion-calibrated; `Clone` and other apply modes are skipped."),
69 ToolMeta("PolylineStroke", "Compositing & Blending", "Unit tests", "Visual*", "Bezier/linear `Polyline` (static or animated) with `WriteOnStart`/`WriteOnEnd`; always visible. Rendered only through `Paint` / `PaintMask`."),
70 ToolMeta("Multistroke", "Compositing & Blending", "Unit tests", "Visual*", "Recorded freehand `Strokes`, visible from `Time` for `Duration` frames (default 1) with per-stroke `Params` overrides (`ApplyMode`, `Size`, `Softness`, color, `Duration`). Per-point `T` is ignored. Rendered only through `Paint` / `PaintMask`."),
69 ToolMeta("Paint", "Compositing & Blending", "Unit tests", "0.0%–1.2%", "Composites the `Paint` stroke chain (`PolylineStroke` / `Multistroke`) over `Input` with `Blend` and `EffectMask`. Fusion-calibrated round `CircleBrush` / `SoftBrush` (`Size`, `Softness`, ~0.41*r spacing, sequential alpha buildup), `PaintApplyColor` (`Red`/`Green`/`Blue`/`Opacity`), and `PaintApplyErase`."),
70 ToolMeta("PolylineStroke", "Compositing & Blending", "Unit tests", "0.0%–0.3%", "Bezier/linear `Polyline` (static or animated) with `WriteOnStart`/`WriteOnEnd`; always visible. Rendered only through `Paint` / `PaintMask`."),
71 ToolMeta("Multistroke", "Compositing & Blending", "Unit tests", "0.1%–1.2%", "Recorded freehand `Strokes`, visible from `Time` for `Frames`/`Duration` frames (default 1) with per-stroke `Params` overrides (`ApplyMode`, `Size`, `Softness`, color, `Duration`). Rendered only through `Paint` / `PaintMask`."),
7172 ToolMeta("Shadow", "Compositing & Blending", "`tier1_b`", "0.1%–0.4%", "Drop shadow offset, softness blur, tint color/alpha, and `ShadowOnly` output."),
7273
7374 # Color & Depth
......@@ -105,6 +106,8 @@ TOOL_METADATA: Sequence[ToolMeta] = (
105106 ToolMeta("Transform", "Transform, Warp & Framing", "`xf`", "0.0%–0.3%", "`Center`, `Pivot`, `Size`/`XSize`/`YSize`, `Aspect`, `Angle`, `FlipHoriz`/`FlipVert`, `FilterMethod` (`Nearest`/`Box`/`Linear`/`Catmull-Rom`), `Edges` (`Canvas`/`Wrap`/`Duplicate`/`Mirror`)."),
106107 ToolMeta("CameraShake", "Transform, Warp & Framing", "`tier1_c`", "0.1%–0.5%", "Procedural X/Y/Rotation/Zoom camera shake with `OverallStrength`, `Speed`, `Edges`."),
107108 ToolMeta("CornerPositioner", "Transform, Warp & Framing", "`tier1_b`", "0.1%–0.4%", "4-point projective homography warp (`TopLeft`/`TopRight`/`BottomLeft`/`BottomRight`)."),
109 ToolMeta("PerspectivePositioner", "Transform, Warp & Framing", "Unit tests", "0.3%–0.4%", "Rectifies 4-corner quad (`BottomLeft`/`BottomRight`/`TopRight`/`TopLeft`) to unit square with `MappingType` bilinear `Linear` (0) or projective `Perspective` (1)."),
110 ToolMeta("GridWarp", "Transform, Warp & Framing", "Unit tests", "0.4%–1.2%", "2D control-point `Mesh` Bezier/Coons patch warp (`SrcGridChange` -> `DstGridChange`, static or keyframed splines, tangent handles, `Blend`, `EffectMask`)."),
108111 ToolMeta("DVE", "Transform, Warp & Framing", "`tier1_b`", "0.1%–0.4%", "2.5D ZYX Euler rotation + perspective homography (`Center`, `ZMove`, `Pivot`, `AlphaMode`)."),
109112 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)."),
110113 ToolMeta("Vortex", "Transform, Warp & Framing", "`vortex_cc`", "0.0%–0.4%", "Isotropic radial swirl warp (`Center`, `Size`, `Angle`, `Power`, `Blend`, `EffectMask`)."),
......@@ -123,13 +126,14 @@ TOOL_METADATA: Sequence[ToolMeta] = (
123126 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`."),
124127 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`."),
125128 ToolMeta("WandMask", "Masks", "`archive_3d`", "0.0%–0.3%", "Seeded BFS flood-fill wand mask (`Source`, `SelectionPoint`, `SelectionRange`, `ColorSpace`, `SoftEdge`, `Invert`, `Level`, `PaintMode`)."),
126 ToolMeta("PaintMask", "Masks", "Unit tests", "Visual*", "Alpha mask of the `Paint` stroke chain (stroke opacity, erase), `MaskWidth`/`MaskHeight`, `SoftEdge`, `Filter`, `ClippingMode`, `Invert`, `Level`, `PaintMode` chaining. *Brush falloff is not Fusion-calibrated."),
129 ToolMeta("PaintMask", "Masks", "Unit tests", "0.1%–0.4%", "Fusion-calibrated alpha mask of the `Paint` stroke chain (`Size`, `Softness`, opacity, erase), `MaskWidth`/`MaskHeight`, `SoftEdge`, `Filter`, `ClippingMode`, `Invert`, `Level`, `PaintMode` chaining."),
127130
128131 # 2D Vector Shapes
129132 ToolMeta("sRender", "2D Vector Shapes", "Unit tests", "0.0%", "Antialiased `zeno` 2D vector shape tree rasterizer (`Width`, `Height`, `Blend`, `EffectMask`, cached RGBA upload & `HiQ` depth promotion)."),
130133 ToolMeta("sNGon", "2D Vector Shapes", "Unit tests", "0.0%", "Regular N-sided polygon vector shape (`Sides`, `Width`, `Height`, `Translate.X/Y`, `Angle`, `Solid`, `BorderWidth`, `JoinStyle`, RGBA color)."),
131134 ToolMeta("sRectangle", "2D Vector Shapes", "Unit tests", "0.0%", "Vector rectangle & rounded rectangle (`Width`, `Height`, `CornerRadius`, `Translate.X/Y`, `Angle`, `Solid`, `BorderWidth`, RGBA color)."),
132135 ToolMeta("sEllipse", "2D Vector Shapes", "Unit tests", "0.0%", "Cubic Bezier vector ellipse (`Width`, `Height`, `Translate.X/Y`, `Angle`, `Solid`, `BorderWidth`, RGBA color)."),
136 ToolMeta("sGrid", "2D Vector Shapes", "Unit tests", "0.0%", "Centered 2D vector shape grid generator (`CellsX`, `CellsY`, `XOffset`, `YOffset`) feeding `sRender`."),
133137 ToolMeta("sMerge", "2D Vector Shapes", "Unit tests", "0.0%", "Composites multiple upstream vector shape inputs (`Input1`..`InputN`) in painter's order."),
134138 ToolMeta("sTransform", "2D Vector Shapes", "Unit tests", "0.0%", "2D affine shape transform (`XOffset`/`YOffset`, `XSize`/`YSize`, `Scale`, `ZRotation`, `XPivot`/`YPivot`)."),
135139 ToolMeta("sBoolean", "2D Vector Shapes", "Unit tests", "0.0%", "Shape boolean combiner (`Union`, `Intersect`, `Subtract`, `Xor`) over `Input1` and `Input2`."),