authoravatarclover caruso<git@paperclover.net>2026-11-30 19:59:36-08:00
committeravatarclover caruso<git@paperclover.net>2026-11-30 20:12:25-08:00
log2810ca0adc68286adada4ae16bea07aa16dd2e4f
tree17b31ab64f7c83db817889c50ac0c456718e7dca
parent993d5986f0810126bd183704c7983593ba0d8ce8
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

Modularize diff_fuzz.py into scripts/diff_fuzz package and fix FuID typos

Fix Background Type FourCorner -> Corner, sBoolean Operation Intersect -> Intersection, and spaced Merge ApplyMode names (Soft Light, Hard Light, Color Dodge, Color Burn) that the engine matches verbatim. Assisted-by: claude-sonnet-5.5

6 files changed, 2721 insertions(+), 2678 deletions(-)

scripts/diff_fuzz.py+12-2678
......@@ -9,2686 +9,20 @@ DAG fuzzer (--fuzz) with automatic node-by-node graph bisection (--bisect).
99
1010import argparse
1111import json
12import math
13import os
14import random
15import re
16import shutil
17import struct
18import subprocess
1912import sys
20import time
21import zlib
22from dataclasses import dataclass, field
2313from pathlib import Path
24from typing import Any, Dict, List, Optional, Tuple
25
26REPO = Path(__file__).resolve().parent.parent
27RENDER_CHECK = REPO / "target/release/render-check"
28SMB_ROOT = Path("/Volumes/clover/Project/CloverCompositor/probes/diff_fuzz")
29REMOTE_ROOT = "/srv/clover/Project/CloverCompositor/probes/diff_fuzz"
30CONTAINER_ROOT = "/Volumes/clover/Project/CloverCompositor/probes/diff_fuzz"
31LOCAL_FALLBACK = Path("/tmp/fission_diff_fuzz")
32
33# ---------------------------------------------------------------------------
34# Storage / SG Transport Helpers
35# ---------------------------------------------------------------------------
36
37
38def use_smb() -> bool:
39 return Path("/Volumes/clover/Project/CloverCompositor").exists()
40
41
42def local_root() -> Path:
43 return SMB_ROOT if use_smb() else LOCAL_FALLBACK
44
45
46def ensure_dirs() -> Path:
47 root = local_root()
48 for sub in ("assets", "comps", "gt", "ours"):
49 (root / sub).mkdir(parents=True, exist_ok=True)
50 return root
51
52
53def sync_asset_to_remote(local_path: Path) -> None:
54 if not use_smb():
55 subprocess.run(
56 ["sg", "upload", str(local_path), f"{REMOTE_ROOT}/assets/{local_path.name}"],
57 check=True,
58 timeout=60,
59 )
60
61
62def ensure_render_check() -> Path:
63 if RENDER_CHECK.exists():
64 return RENDER_CHECK
65 print(f"[build] {RENDER_CHECK} missing; building render-check --release...", file=sys.stderr)
66 subprocess.run(
67 ["cargo", "build", "--release", "-p", "engine", "--bin", "render-check"],
68 cwd=str(REPO),
69 check=True,
70 timeout=600,
71 )
72 return RENDER_CHECK
73
74
75# ---------------------------------------------------------------------------
76# Pure Python Stdlib PNG Encoder / Decoder & Diff Metrics
77# ---------------------------------------------------------------------------
78
79
80def write_png_rgba(path: Path, w: int, h: int, rgba_bytes: bytes) -> None:
81 def chunk(tag: bytes, data: bytes) -> bytes:
82 return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
83
84 raw = bytearray()
85 stride = w * 4
86 for y in range(h):
87 raw.append(0)
88 raw.extend(rgba_bytes[y * stride : (y + 1) * stride])
89
90 ihdr = struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0)
91 png = (
92 b"\x89PNG\r\n\x1a\n"
93 + chunk(b"IHDR", ihdr)
94 + chunk(b"IDAT", zlib.compress(bytes(raw), level=6))
95 + chunk(b"IEND", b"")
96 )
97 path.parent.mkdir(parents=True, exist_ok=True)
98 path.write_bytes(png)
99
100
101def _paeth(a: int, b: int, c: int) -> int:
102 p = a + b - c
103 pa = abs(p - a)
104 pb = abs(p - b)
105 pc = abs(p - c)
106 if pa <= pb and pa <= pc:
107 return a
108 if pb <= pc:
109 return b
110 return c
111
112
113def read_png_rgba(path: Path) -> Tuple[int, int, bytes]:
114 data = path.read_bytes()
115 if data[:8] != b"\x89PNG\r\n\x1a\n":
116 raise ValueError(f"Not a PNG file: {path}")
117 pos = 8
118 w = h = bit_depth = color_type = interlace = 0
119 idat = bytearray()
120 while pos + 8 <= len(data):
121 length = struct.unpack(">I", data[pos : pos + 4])[0]
122 tag = data[pos + 4 : pos + 8]
123 chunk_data = data[pos + 8 : pos + 8 + length]
124 pos += 12 + length
125 if tag == b"IHDR":
126 w, h, bit_depth, color_type, _comp, _filt, interlace = struct.unpack(">IIBBBBB", chunk_data)
127 elif tag == b"IDAT":
128 idat.extend(chunk_data)
129 elif tag == b"IEND":
130 break
131
132 if interlace != 0:
133 raise ValueError(f"Interlaced PNG unsupported in pure-stdlib reader: {path}")
134 channels_map = {0: 1, 2: 3, 4: 2, 6: 4}
135 if color_type not in channels_map or bit_depth not in (8, 16):
136 raise ValueError(f"Unsupported PNG format (color={color_type}, depth={bit_depth}): {path}")
137
138 ch = channels_map[color_type]
139 bypp = ch * (bit_depth // 8)
140 row_bytes = w * bypp
141 raw = zlib.decompress(bytes(idat))
142 if len(raw) < h * (row_bytes + 1):
143 raise ValueError(f"Truncated PNG IDAT in {path}")
144
145 prev = bytearray(row_bytes)
146 out = bytearray(w * h * 4)
147 idx_in = 0
148 for y in range(h):
149 ftype = raw[idx_in]
150 idx_in += 1
151 scan = bytearray(raw[idx_in : idx_in + row_bytes])
152 idx_in += row_bytes
153 if ftype == 1:
154 for i in range(bypp, row_bytes):
155 scan[i] = (scan[i] + scan[i - bypp]) & 0xFF
156 elif ftype == 2:
157 for i in range(row_bytes):
158 scan[i] = (scan[i] + prev[i]) & 0xFF
159 elif ftype == 3:
160 for i in range(row_bytes):
161 a = scan[i - bypp] if i >= bypp else 0
162 scan[i] = (scan[i] + ((a + prev[i]) >> 1)) & 0xFF
163 elif ftype == 4:
164 for i in range(row_bytes):
165 a = scan[i - bypp] if i >= bypp else 0
166 b = prev[i]
167 c = prev[i - bypp] if i >= bypp else 0
168 scan[i] = (scan[i] + _paeth(a, b, c)) & 0xFF
169 elif ftype != 0:
170 raise ValueError(f"Unknown PNG filter {ftype} in {path}")
171 prev = scan
172
173 out_row = y * w * 4
174 if bit_depth == 8:
175 if ch == 4:
176 out[out_row : out_row + w * 4] = scan
177 elif ch == 3:
178 for x in range(w):
179 si = x * 3
180 di = out_row + x * 4
181 out[di] = scan[si]
182 out[di + 1] = scan[si + 1]
183 out[di + 2] = scan[si + 2]
184 out[di + 3] = 255
185 elif ch == 2:
186 for x in range(w):
187 si = x * 2
188 di = out_row + x * 4
189 v = scan[si]
190 out[di] = v
191 out[di + 1] = v
192 out[di + 2] = v
193 out[di + 3] = scan[si + 1]
194 else:
195 for x in range(w):
196 di = out_row + x * 4
197 v = scan[x]
198 out[di] = v
199 out[di + 1] = v
200 out[di + 2] = v
201 out[di + 3] = 255
202 else:
203 # 16-bit big endian -> 8-bit
204 for x in range(w):
205 si = x * bypp
206 di = out_row + x * 4
207 vals = [((scan[si + k * 2] << 8) | scan[si + k * 2 + 1]) >> 8 for k in range(ch)]
208 if ch == 4:
209 out[di : di + 4] = bytes(vals)
210 elif ch == 3:
211 out[di : di + 4] = bytes((vals[0], vals[1], vals[2], 255))
212 elif ch == 2:
213 out[di : di + 4] = bytes((vals[0], vals[0], vals[0], vals[1]))
214 else:
215 out[di : di + 4] = bytes((vals[0], vals[0], vals[0], 255))
216 return w, h, bytes(out)
217
218
219def compute_diff_metrics(ours_path: Path, gt_path: Path) -> Dict[str, Any]:
220 if not ours_path.exists():
221 return {"error": f"missing ours: {ours_path}", "mae_pct": 100.0, "mae_255": 255.0, "rmse_255": 255.0}
222 if not gt_path.exists():
223 return {"error": f"missing gt: {gt_path}", "mae_pct": 100.0, "mae_255": 255.0, "rmse_255": 255.0}
224
225 ow, oh, ob = read_png_rgba(ours_path)
226 gw, gh, gb = read_png_rgba(gt_path)
227 size_mismatch = (ow != gw) or (oh != gh)
228
229 # Compare over overlapping or resized if mismatched, matching render-check's RGB metric
230 cw = min(ow, gw)
231 ch = min(oh, gh)
232 if size_mismatch:
233 # Bilinear sample gt onto ow x oh just like render-check, but still flag size_mismatch!
234 sum_abs = 0
235 sum_sq = 0
236 max_diff = 0
237 for y in range(oh):
238 gy = min(gh - 1, int((y + 0.5) * gh / oh))
239 for x in range(ow):
240 gx = min(gw - 1, int((x + 0.5) * gw / ow))
241 oi = (y * ow + x) * 4
242 gi = (gy * gw + gx) * 4
243 for c in range(3):
244 d = abs(ob[oi + c] - gb[gi + c])
245 sum_abs += d
246 sum_sq += d * d
247 if d > max_diff:
248 max_diff = d
249 n = ow * oh * 3
250 else:
251 sum_abs = 0
252 sum_sq = 0
253 max_diff = 0
254 n = ow * oh * 3
255 for i in range(0, ow * oh * 4, 4):
256 d0 = abs(ob[i] - gb[i])
257 d1 = abs(ob[i + 1] - gb[i + 1])
258 d2 = abs(ob[i + 2] - gb[i + 2])
259 sum_abs += d0 + d1 + d2
260 sum_sq += d0 * d0 + d1 * d1 + d2 * d2
261 m = max(d0, d1, d2)
262 if m > max_diff:
263 max_diff = m
264
265 mae_255 = sum_abs / max(1, n)
266 rmse_255 = math.sqrt(sum_sq / max(1, n))
267 mae_pct = mae_255 / 2.55
268 return {
269 "mae_255": round(mae_255, 4),
270 "mae_pct": round(mae_pct, 4),
271 "rmse_255": round(rmse_255, 4),
272 "max_diff": max_diff,
273 "dims_ours": [ow, oh],
274 "dims_gt": [gw, gh],
275 "size_mismatch": size_mismatch,
276 }
277
278
279# ---------------------------------------------------------------------------
280# Synthetic Test Plate & Geometry Generators
281# ---------------------------------------------------------------------------
282
283
284def _hsv_to_rgb(h: float, s: float, v: float) -> Tuple[float, float, float]:
285 h = (h % 1.0) * 6.0
286 i = int(h)
287 f = h - i
288 p = v * (1.0 - s)
289 q = v * (1.0 - s * f)
290 t = v * (1.0 - s * (1.0 - f))
291 return [(v, t, p), (q, v, p), (p, v, t), (p, q, v), (t, p, v), (v, p, q)][i % 6]
292
293
294def _clamp8(v: float) -> int:
295 return max(0, min(255, int(round(v * 255.0))))
296
297
298def generate_assets() -> Dict[str, str]:
299 """Generates all synthetic test plates & cube.obj under probes/diff_fuzz/assets/."""
300 root = ensure_dirs()
301 assets_dir = root / "assets"
302
303 # 1. plate_color.png (256x256): HSV + gray/primary ramps + geometric edges + alpha gradient
304 p_color = assets_dir / "plate_color.png"
305 w, h = 256, 256
306 buf = bytearray(w * h * 4)
307 for y in range(h):
308 ny = y / (h - 1)
309 for x in range(w):
310 nx = x / (w - 1)
311 r, g, b, a = 0.0, 0.0, 0.0, 1.0
312 if ny < 0.40:
313 r, g, b = _hsv_to_rgb(nx, ny / 0.40, 0.90)
314 elif ny < 0.60:
315 if nx < 0.5:
316 g0 = nx * 2.0
317 r, g, b = g0, g0, g0
318 else:
319 bar = int((nx - 0.5) * 12.0) % 6
320 r, g, b = [
321 (0.95, 0.15, 0.15),
322 (0.15, 0.90, 0.20),
323 (0.15, 0.30, 0.95),
324 (0.95, 0.90, 0.15),
325 (0.15, 0.90, 0.95),
326 (0.95, 0.15, 0.90),
327 ][bar]
328 elif ny < 0.82:
329 # Sharp geometric edges (rotated diamond + circle + stripes)
330 r, g, b = 0.12, 0.14, 0.18
331 dx, dy = abs(nx - 0.30), abs(ny - 0.71)
332 if dx + dy < 0.11:
333 r, g, b = 0.96, 0.52, 0.12
334 if math.hypot(nx - 0.72, ny - 0.71) < 0.09:
335 r, g, b = 0.20, 0.85, 0.95
336 if ((x + y) // 6) % 2 == 0 and 0.45 < nx < 0.58:
337 r, g, b = 0.92, 0.92, 0.92
338 else:
339 r, g, b = _hsv_to_rgb(nx, 0.85, 0.92)
340 a = max(0.0, min(1.0, 1.0 - (ny - 0.82) / 0.18))
341 idx = (y * w + x) * 4
342 buf[idx] = _clamp8(r)
343 buf[idx + 1] = _clamp8(g)
344 buf[idx + 2] = _clamp8(b)
345 buf[idx + 3] = _clamp8(a)
346 write_png_rgba(p_color, w, h, bytes(buf))
347 sync_asset_to_remote(p_color)
348
349 # 2. plate_fg.png (256x256): semi-transparent shapes, fine diagonal stripes, soft radial falloff
350 p_fg = assets_dir / "plate_fg.png"
351 buf = bytearray(w * h * 4)
352 for y in range(h):
353 ny = y / (h - 1)
354 for x in range(w):
355 nx = x / (w - 1)
356 r, g, b, a = 0.0, 0.0, 0.0, 0.0
357 # Soft radial falloff orb (top-left)
358 d_orb = math.hypot(nx - 0.28, ny - 0.28)
359 if d_orb < 0.22:
360 t = 1.0 - d_orb / 0.22
361 r, g, b = 0.95 * t + 0.2 * (1.0 - t), 0.35 + 0.55 * math.sin(d_orb * 40.0) ** 2, 0.90 * (1.0 - 0.4 * t)
362 a = t * t * (3.0 - 2.0 * t)
363 # Fine diagonal stripes block (top-right)
364 if 0.54 <= nx <= 0.90 and 0.10 <= ny <= 0.44:
365 stripe = ((x - y) // 2) % 2 == 0
366 r, g, b = (0.95, 0.85, 0.15) if stripe else (0.15, 0.22, 0.55)
367 a = 0.85 if stripe else 0.55
368 # Overlapping semi-transparent discs (bottom-left)
369 d1 = math.hypot(nx - 0.24, ny - 0.72) < 0.14
370 d2 = math.hypot(nx - 0.36, ny - 0.72) < 0.14
371 if d1 and d2:
372 r, g, b, a = 0.85, 0.55, 0.95, 0.75
373 elif d1:
374 r, g, b, a = 0.10, 0.85, 0.90, 0.55
375 elif d2:
376 r, g, b, a = 0.95, 0.20, 0.65, 0.55
377 # Asymmetric crisp L-marker (bottom-right)
378 if (0.62 <= nx <= 0.68 and 0.58 <= ny <= 0.86) or (0.62 <= nx <= 0.86 and 0.80 <= ny <= 0.86):
379 r, g, b, a = 0.98, 0.98, 0.98, 1.0
380 idx = (y * w + x) * 4
381 buf[idx] = _clamp8(r)
382 buf[idx + 1] = _clamp8(g)
383 buf[idx + 2] = _clamp8(b)
384 buf[idx + 3] = _clamp8(a)
385 write_png_rgba(p_fg, w, h, bytes(buf))
386 sync_asset_to_remote(p_fg)
387
388 # 3. plate_small.png (160x120): mismatched resolution test plate
389 p_small = assets_dir / "plate_small.png"
390 sw, sh = 160, 120
391 sbuf = bytearray(sw * sh * 4)
392 for y in range(sh):
393 ny = y / (sh - 1)
394 for x in range(sw):
395 nx = x / (sw - 1)
396 r, g, b, a = 0.18, 0.22, 0.30, 0.95
397 if x < 5 or x >= sw - 5 or y < 5 or y >= sh - 5:
398 if y < 5:
399 r, g, b, a = 0.95, 0.20, 0.20, 1.0
400 elif y >= sh - 5:
401 r, g, b, a = 0.20, 0.90, 0.25, 1.0
402 elif x < 5:
403 r, g, b, a = 0.20, 0.40, 0.95, 1.0
404 else:
405 r, g, b, a = 0.95, 0.85, 0.15, 1.0
406 else:
407 if ((x // 10) + (y // 10)) % 2 == 0:
408 r, g, b = 0.72, 0.76, 0.82
409 if abs(nx - ny) < 0.04 or abs(nx - (1.0 - ny)) < 0.04:
410 r, g, b = 0.95, 0.35, 0.10
411 d_c = math.hypot(nx - 0.5, ny - 0.5)
412 if d_c < 0.22:
413 a = max(0.2, 1.0 - (0.22 - d_c) / 0.22 * 0.7)
414 idx = (y * sw + x) * 4
415 sbuf[idx] = _clamp8(r)
416 sbuf[idx + 1] = _clamp8(g)
417 sbuf[idx + 2] = _clamp8(b)
418 sbuf[idx + 3] = _clamp8(a)
419 write_png_rgba(p_small, sw, sh, bytes(sbuf))
420 sync_asset_to_remote(p_small)
421
422 # 4. plate_bump.png (256x256): grayscale heightmap / bump test texture
423 p_bump = assets_dir / "plate_bump.png"
424 bbuf = bytearray(w * h * 4)
425 for y in range(h):
426 ny = y / (h - 1)
427 for x in range(w):
428 nx = x / (w - 1)
429 d = math.hypot(nx - 0.5, ny - 0.5)
430 dome = max(0.0, 1.0 - (d / 0.38) ** 2) ** 0.5 if d < 0.38 else 0.0
431 ripple = 0.5 + 0.5 * math.sin(d * 48.0)
432 step = 0.25 * math.floor(nx * 5.0) / 4.0
433 val = max(0.0, min(1.0, 0.50 * dome + 0.30 * ripple + 0.20 * step))
434 v8 = _clamp8(val)
435 idx = (y * w + x) * 4
436 bbuf[idx] = v8
437 bbuf[idx + 1] = v8
438 bbuf[idx + 2] = v8
439 bbuf[idx + 3] = 255
440 write_png_rgba(p_bump, w, h, bytes(bbuf))
441 sync_asset_to_remote(p_bump)
442
443 # 5. cube.obj: small valid triangulated OBJ mesh
444 p_obj = assets_dir / "cube.obj"
445 obj_text = """# Synthetic unit cube for SurfaceFBXMesh differential testing
446o UnitCube
447v -0.5 -0.5 0.5
448v 0.5 -0.5 0.5
449v 0.5 0.5 0.5
450v -0.5 0.5 0.5
451v -0.5 -0.5 -0.5
452v 0.5 -0.5 -0.5
453v 0.5 0.5 -0.5
454v -0.5 0.5 -0.5
455vt 0.0 0.0
456vt 1.0 0.0
457vt 1.0 1.0
458vt 0.0 1.0
459vn 0.0 0.0 1.0
460vn 0.0 0.0 -1.0
461vn 1.0 0.0 0.0
462vn -1.0 0.0 0.0
463vn 0.0 1.0 0.0
464vn 0.0 -1.0 0.0
465f 1/1/1 2/2/1 3/3/1
466f 1/1/1 3/3/1 4/4/1
467f 6/1/2 5/2/2 8/3/2
468f 6/1/2 8/3/2 7/4/2
469f 2/1/3 6/2/3 7/3/3
470f 2/1/3 7/3/3 3/4/3
471f 5/1/4 1/2/4 4/3/4
472f 5/1/4 4/3/4 8/4/4
473f 4/1/5 3/2/5 7/3/5
474f 4/1/5 7/3/5 8/4/5
475f 5/1/6 6/2/6 2/3/6
476f 5/1/6 2/3/6 1/4/6
477"""
478 p_obj.write_text(obj_text)
479 sync_asset_to_remote(p_obj)
480
481 return {
482 "color": f"{CONTAINER_ROOT}/assets/plate_color.png",
483 "fg": f"{CONTAINER_ROOT}/assets/plate_fg.png",
484 "small": f"{CONTAINER_ROOT}/assets/plate_small.png",
485 "bump": f"{CONTAINER_ROOT}/assets/plate_bump.png",
486 "cube_obj": f"{CONTAINER_ROOT}/assets/cube.obj",
487 }
488
489
490# ---------------------------------------------------------------------------
491# Fusion .comp Serialization Primitives
492# ---------------------------------------------------------------------------
493
494
495def step_spline(name: str, frame_values: Dict[int, float]) -> str:
496 kfs = [f"\t\t\t\t[{f}] = {{ {v!r}, Flags = {{ StepIn = true }} }}," for f, v in sorted(frame_values.items())]
497 return f"\t\t{name} = BezierSpline {{\n\t\t\tKeyFrames = {{\n" + "\n".join(kfs) + "\n\t\t\t},\n\t\t},"
498
499
500def linear_spline(name: str, frame_values: Dict[int, float]) -> str:
501 kfs = [f"\t\t\t\t[{f}] = {{ {v!r}, Flags = {{ Linear = true }} }}," for f, v in sorted(frame_values.items())]
502 return f"\t\t{name} = BezierSpline {{\n\t\t\tKeyFrames = {{\n" + "\n".join(kfs) + "\n\t\t\t},\n\t\t},"
503
504
505def lut_bezier(name: str, pts: List[Tuple[float, float]]) -> str:
506 kfs = "\n".join(f"\t\t\t\t\t[{x}] = {{ {y} }}," for x, y in pts)
507 return (
508 f"\t\t{name} = LUTBezier {{\n"
509 f"\t\t\tSmoothEndsTransition = true,\n"
510 f"\t\t\tKeyColorSplines = {{\n"
511 f"\t\t\t\t[0] = {{\n{kfs}\n\t\t\t\t}}\n"
512 f"\t\t\t}},\n\t\t}},"
513 )
514
515
516def make_loader(name: str, container_path: str, post_mult: int = 1, depth: Optional[int] = None) -> str:
517 extra = f"\n\t\t\t\tDepth = Input {{ Value = {depth}, }}," if depth is not None else ""
518 return f"""\t\t{name} = Loader {{
519\t\t\tClips = {{
520\t\t\t\tClip {{
521\t\t\t\t\tID = "Clip1",
522\t\t\t\t\tFilename = "{container_path}",
523\t\t\t\t\tFormatID = "PNGFormat",
524\t\t\t\t\tLength = 1,
525\t\t\t\t\tLengthSetManually = true,
526\t\t\t\t\tTrimIn = 0,
527\t\t\t\t\tTrimOut = 0,
528\t\t\t\t\tExtendFirst = 0,
529\t\t\t\t\tExtendLast = 0,
530\t\t\t\t\tLoop = 1,
531\t\t\t\t\tStartFrame = -1,
532\t\t\t\t\tGlobalStart = 0,
533\t\t\t\t\tGlobalEnd = 1000,
534\t\t\t\t}},
535\t\t\t}},
536\t\t\tInputs = {{
537\t\t\t\t["Clip1.PNGFormat.PostMultiply"] = Input {{ Value = {post_mult}, }},{extra}
538\t\t\t}},
539\t\t}},"""
540
541
542def make_saver(src_op: str, prefix: str) -> str:
543 return f"""\t\tSaver1 = Saver {{
544\t\t\tInputs = {{
545\t\t\t\tClip = Input {{
546\t\t\t\t\tValue = Clip {{
547\t\t\t\t\t\tFilename = "{CONTAINER_ROOT}/gt/{prefix}_0000.png",
548\t\t\t\t\t\tFormatID = "PNGFormat",
549\t\t\t\t\t\tLength = 0,
550\t\t\t\t\t\tSaving = true,
551\t\t\t\t\t\tTrimIn = 0,
552\t\t\t\t\t\tExtendFirst = 0,
553\t\t\t\t\t\tExtendLast = 0,
554\t\t\t\t\t\tLoop = 1,
555\t\t\t\t\t\tAspectMode = 0,
556\t\t\t\t\t\tDepth = 0,
557\t\t\t\t\t\tGlobalStart = -2000000000,
558\t\t\t\t\t\tGlobalEnd = 0,
559\t\t\t\t\t}},
560\t\t\t\t}},
561\t\t\t\tOutputFormat = Input {{ Value = FuID {{ "PNGFormat" }}, }},
562\t\t\t\tInput = Input {{ SourceOp = "{src_op}", Source = "Output", }},
563\t\t\t}},
564\t\t}},"""
565
566
567def make_comp(tools_body: str, end_frame: int, w: int = 256, h: int = 256, start_frame: int = 0) -> str:
568 return f"""Composition {{
569\tCurrentTime = {start_frame},
570\tRenderRange = {{ {start_frame}, {end_frame} }},
571\tGlobalRange = {{ {start_frame}, {end_frame} }},
572\tCurrentID = 500,
573\tHiQ = true,
574\tPlaybackUpdateMode = 0,
575\tVersion = "Fusion Studio 21.1 build 23",
576\tTools = ordered() {{
577{tools_body}
578\t}},
579\tPrefs = {{
580\t\tComp = {{
581\t\t\tFrameFormat = {{
582\t\t\t\tWidth = {w},
583\t\t\t\tHeight = {h},
584\t\t\t\tRate = 24,
585\t\t\t}},
586\t\t}},
587\t}},
588}}
589"""
590
591
592def build_switch_chain(
593 cases: List[Tuple[int, str, str]],
594 bg_name: str,
595 prefix_tag: str,
596) -> Tuple[List[str], List[str], str]:
597 """Chains Merge switches so frame f outputs op_name for case (f, label, op_name)."""
598 nodes: List[str] = []
599 splines: List[str] = []
600 prev = bg_name
601 frames = [c[0] for c in cases]
602 for f, _label, op_name in cases:
603 bl = {fr: (1.0 if fr == f else 0.0) for fr in frames}
604 sname = f"{prefix_tag}_{f}_Blend"
605 splines.append(step_spline(sname, bl))
606 sw_name = f"{prefix_tag}_Sw_{f}"
607 nodes.append(
608 f"""\t\t{sw_name} = Merge {{
609\t\t\tInputs = {{
610\t\t\t\tBlend = Input {{ SourceOp = "{sname}", Source = "Value", }},
611\t\t\t\tBackground = Input {{ SourceOp = "{prev}", Source = "Output", }},
612\t\t\t\tForeground = Input {{ SourceOp = "{op_name}", Source = "Output", }},
613\t\t\t}},
614\t\t}},"""
615 )
616 prev = sw_name
617 return nodes, splines, prev
618
619
620# ---------------------------------------------------------------------------
621# Execution & Comparison Runner (sg render + render-check)
622# ---------------------------------------------------------------------------
623
624
625def run_comp_both(
626 comp_path: Path,
627 prefix: str,
628 frames: List[int],
629 labels: Dict[int, str],
630 render_gt: bool = True,
631 timeout_sec: int = 180,
632) -> Dict[int, Dict[str, Any]]:
633 """Renders comp via sg render (if render_gt) and render-check --render, returning per-frame metrics."""
634 root = ensure_dirs()
635 rc_bin = ensure_render_check()
636 start_f, end_f = min(frames), max(frames)
637
638 gt_error: Optional[str] = None
639 if render_gt:
640 if use_smb():
641 target_comp = str(comp_path)
642 else:
643 remote_comp = f"{REMOTE_ROOT}/comps/{comp_path.name}"
644 subprocess.run(["sg", "upload", str(comp_path), remote_comp], check=True, timeout=60)
645 target_comp = remote_comp
646
647 # Clear stale GT frames for this prefix
648 gt_dir = root / "gt"
649 for f in frames:
650 p = gt_dir / f"{prefix}_{f:04d}.png"
651 if p.exists():
652 p.unlink()
653
654 try:
655 cmd = ["sg", "render", target_comp, "--start", str(start_f), "--end", str(end_f)]
656 proc = subprocess.run(cmd, check=True, capture_output=True, text=True, timeout=timeout_sec)
657 combined_out = (proc.stdout or "") + "\n" + (proc.stderr or "")
658 if "ERROR: Render failed" in combined_out:
659 err_lines = [ln.strip() for ln in combined_out.splitlines() if "fail" in ln.lower() or "error" in ln.lower()]
660 gt_error = "sg render error: " + " | ".join(err_lines[:4])
661 except subprocess.TimeoutExpired:
662 gt_error = f"sg render timed out after {timeout_sec}s"
663 except subprocess.CalledProcessError as e:
664 gt_error = f"sg render failed (rc={e.returncode}): {(e.stderr or e.stdout or '').strip()[:300]}"
665
666 if use_smb() and gt_error is None:
667 # Wait briefly for SMB directory cache to surface newly written GT frames
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"))
672 time.sleep(0.25)
673
674 if not use_smb() and gt_error is None:
675 for f in frames:
676 fname = f"{prefix}_{f:04d}.png"
677 try:
678 subprocess.run(
679 ["sg", "download", f"{REMOTE_ROOT}/gt/{fname}", str(gt_dir / fname)],
680 check=True,
681 capture_output=True,
682 timeout=60,
683 )
684 except subprocess.CalledProcessError as e:
685 gt_error = f"sg download failed for {fname}: {e}"
686 break
687
688 eval_comp = comp_path
689 if not use_smb():
690 txt = comp_path.read_text().replace(CONTAINER_ROOT, str(root))
691 eval_comp = comp_path.with_suffix(".local.comp")
692 eval_comp.write_text(txt)
693
694 ours_sub = root / "ours" / prefix
695 if ours_sub.exists():
696 shutil.rmtree(ours_sub, ignore_errors=True)
697 ours_sub.mkdir(parents=True, exist_ok=True)
698
699 rc_error: Optional[str] = None
700 try:
701 subprocess.run(
702 [str(rc_bin), str(eval_comp), "--render", f"{start_f}..{end_f}", "--out-dir", str(ours_sub)],
703 check=True,
704 capture_output=True,
705 text=True,
706 timeout=timeout_sec,
707 )
708 except subprocess.TimeoutExpired:
709 rc_error = f"render-check timed out after {timeout_sec}s"
710 except subprocess.CalledProcessError as e:
711 rc_error = f"render-check failed (rc={e.returncode}): {(e.stderr or e.stdout or '').strip()[:300]}"
712
713 results: Dict[int, Dict[str, Any]] = {}
714 for f in frames:
715 label = labels.get(f, f"f{f}")
716 if gt_error is not None:
717 results[f] = {"frame": f, "label": label, "error": gt_error, "mae_pct": 100.0, "mae_255": 255.0, "rmse_255": 255.0}
718 continue
719 if rc_error is not None:
720 results[f] = {"frame": f, "label": label, "error": rc_error, "mae_pct": 100.0, "mae_255": 255.0, "rmse_255": 255.0}
721 continue
722 gt_p = root / "gt" / f"{prefix}_{f:04d}.png"
723 ours_p = ours_sub / f"{f:04d}.png"
724 m = compute_diff_metrics(ours_p, gt_p)
725 m["frame"] = f
726 m["label"] = label
727 results[f] = m
728 return results
729
730
731# ---------------------------------------------------------------------------
732# Matrix Suites (7 Exhaustive Edge-Case Suites)
733# ---------------------------------------------------------------------------
734
735
736def build_matrix_merge_modes(assets: Dict[str, str]):
737 """Sweeps all Merge ApplyModes, Operators, SubtractiveAdditive, AlphaGain/Gain, BurnIn, Edges, mismatched res, EffectMask."""
738 nodes = [
739 make_loader("ColorLoader", assets["color"], post_mult=1),
740 make_loader("FGLoader", assets["fg"], post_mult=1),
741 make_loader("SmallLoader", assets["small"], post_mult=1),
742 """\t\tBlackBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftAlpha = Input { Value = 1, }, }, },
743\t\tBlueBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftRed = Input { Value = 0.15, }, TopLeftGreen = Input { Value = 0.25, }, TopLeftBlue = Input { Value = 0.55, }, TopLeftAlpha = Input { Value = 1, }, }, },
744\t\tMaskEll = EllipseMask { Inputs = { MaskWidth = Input { Value = 256, }, MaskHeight = Input { Value = 256, }, Width = Input { Value = 0.55, }, Height = Input { Value = 0.45, }, SoftEdge = Input { Value = 0.04, }, }, },""",
745 ]
746 cases: List[Tuple[int, str, str]] = []
747 f = 0
748
749 def add_case(label: str, fg: str, bg: str, extra: str, over_blue: bool = False) -> None:
750 nonlocal f
751 mname = f"M_{f}"
752 nodes.append(
753 f"""\t\t{mname} = Merge {{
754\t\t\tInputs = {{
755\t\t\t\tBackground = Input {{ SourceOp = "{bg}", Source = "Output", }},
756\t\t\t\tForeground = Input {{ SourceOp = "{fg}", Source = "Output", }},
757\t\t\t\tPerformDepthMerge = Input {{ Value = 0, }},
758\t\t\t\t{extra}
759\t\t\t}},
760\t\t}},"""
761 )
762 out_name = mname
763 if over_blue:
764 oname = f"Vis_{f}"
765 nodes.append(
766 f"""\t\t{oname} = Merge {{
767\t\t\tInputs = {{
768\t\t\t\tBackground = Input {{ SourceOp = "BlueBG", Source = "Output", }},
769\t\t\t\tForeground = Input {{ SourceOp = "{mname}", Source = "Output", }},
770\t\t\t}},
771\t\t}},"""
772 )
773 out_name = oname
774 cases.append((f, label, out_name))
775 f += 1
776
777 apply_modes = [
778 "Normal", "Screen", "Multiply", "Dissolve", "SoftLight", "HardLight",
779 "Darken", "Lighten", "ColorDodge", "ColorBurn", "Difference", "Exclusion",
780 "Overlay", "Sub",
781 ]
782 for am in apply_modes:
783 add_case(f"ApplyMode={am}", "FGLoader", "ColorLoader", f'Size = Input {{ Value = 0.85, }}, ApplyMode = Input {{ Value = FuID {{ "{am}" }}, }},')
784
785 operators = ["Over", "In", "Held Out", "Atop", "XOr", "Conjoint", "Disjoint"]
786 for op in operators:
787 add_case(f"Operator={op}", "FGLoader", "ColorLoader", f'Operator = Input {{ Value = FuID {{ "{op}" }}, }},', over_blue=True)
788
789 for sa in (0.0, 0.5, 1.0):
790 add_case(f"SubAdd={sa}", "FGLoader", "ColorLoader", f"SubtractiveAdditive = Input {{ Value = {sa}, }},")
791
792 for ag in (0.0, 0.5, 1.5):
793 add_case(f"Gain={ag}", "FGLoader", "ColorLoader", f"Gain = Input {{ Value = {ag}, }},")
794 add_case("AlphaGain=0.5", "FGLoader", "ColorLoader", "AlphaGain = Input { Value = 0.5, },")
795
796 add_case("BurnIn=0.6", "FGLoader", "ColorLoader", "BurnIn = Input { Value = 0.6, },")
797
798 for ed in (0, 1, 2, 3):
799 add_case(
800 f"Edges={ed}",
801 "SmallLoader",
802 "ColorLoader",
803 f"Center = Input {{ Value = {{ 0.78, 0.72 }}, }}, Size = Input {{ Value = 0.55, }}, Angle = Input {{ Value = 22, }}, Edges = Input {{ Value = {ed}, }},",
804 )
805
806 add_case("Mismatch_SmallOverColor", "SmallLoader", "ColorLoader", "Size = Input { Value = 0.8, }, Angle = Input { Value = 20, },")
807 add_case("Mismatch_ColorOverSmall", "ColorLoader", "SmallLoader", "Size = Input { Value = 0.5, }, Angle = Input { Value = -15, },", over_blue=True)
808
809 for inv in (0, 1):
810 for mbm in (0, 1):
811 add_case(
812 f"Mask_inv{inv}_mbm{mbm}",
813 "FGLoader",
814 "ColorLoader",
815 f'EffectMask = Input {{ SourceOp = "MaskEll", Source = "Mask", }}, ApplyMaskInverted = Input {{ Value = {inv}, }}, MultiplyByMask = Input {{ Value = {mbm}, }},',
816 )
817
818 sw_nodes, sw_splines, out_op = build_switch_chain(cases, "BlackBG", "MM")
819 nodes.extend(sw_nodes)
820 nodes.append(make_saver(out_op, "matrix_merge_modes"))
821 comp_path = ensure_dirs() / "comps" / "matrix_merge_modes.comp"
822 comp_path.write_text(make_comp("\n".join(nodes + sw_splines), len(cases) - 1))
823 return comp_path, "matrix_merge_modes", [(c[0], c[1]) for c in cases]
824
825
826def build_matrix_hdr_depth(assets: Dict[str, str]):
827 """Tests BitDepth (int8/int16/float16/float32), HDR > 1.0, negative values, PreDividePostMultiply=0/1."""
828 nodes = [
829 make_loader("ColorLoader", assets["color"], post_mult=1),
830 make_loader("FGLoader", assets["fg"], post_mult=1),
831 """\t\tBlackBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftAlpha = Input { Value = 1, }, }, },
832\t\tDarkBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftRed = Input { Value = 0.1, }, TopLeftGreen = Input { Value = 0.12, }, TopLeftBlue = Input { Value = 0.16, }, TopLeftAlpha = Input { Value = 1, }, }, },""",
833 ]
834 cases: List[Tuple[int, str, str]] = []
835 f = 0
836
837 for d_code, d_name in ((1, "int8"), (2, "int16"), (3, "float16"), (4, "float32")):
838 cd = f"CD_{f}"
839 up = f"Up_{f}"
840 bl = f"Bl_{f}"
841 dn = f"Dn_{f}"
842 nodes.append(f'\t\t{cd} = ChangeDepth {{ Inputs = {{ Input = Input {{ SourceOp = "ColorLoader", Source = "Output", }}, Depth = Input {{ Value = {d_code}, }}, }}, }},')
843 nodes.append(f'\t\t{up} = BrightnessContrast {{ Inputs = {{ Input = Input {{ SourceOp = "{cd}", Source = "Output", }}, Gain = Input {{ Value = 2.5, }}, }}, }},')
844 nodes.append(f'\t\t{bl} = Blur {{ Inputs = {{ Input = Input {{ SourceOp = "{up}", Source = "Output", }}, XBlurSize = Input {{ Value = 8.0, }}, }}, }},')
845 nodes.append(f'\t\t{dn} = BrightnessContrast {{ Inputs = {{ Input = Input {{ SourceOp = "{bl}", Source = "Output", }}, Gain = Input {{ Value = 0.4, }}, }}, }},')
846 cases.append((f, f"HDR_Depth={d_name}_Gain2.5_Blur_Gain0.4", dn))
847 f += 1
848
849 # Negative value roundtrip across depths
850 for d_code, d_name in ((1, "int8"), (3, "float16"), (4, "float32")):
851 cd = f"CDN_{f}"
852 sub = f"Sub_{f}"
853 bl = f"BlN_{f}"
854 add = f"Add_{f}"
855 nodes.append(f'\t\t{cd} = ChangeDepth {{ Inputs = {{ Input = Input {{ SourceOp = "ColorLoader", Source = "Output", }}, Depth = Input {{ Value = {d_code}, }}, }}, }},')
856 nodes.append(f'\t\t{sub} = BrightnessContrast {{ Inputs = {{ Input = Input {{ SourceOp = "{cd}", Source = "Output", }}, Brightness = Input {{ Value = -0.4, }}, }}, }},')
857 nodes.append(f'\t\t{bl} = Blur {{ Inputs = {{ Input = Input {{ SourceOp = "{sub}", Source = "Output", }}, XBlurSize = Input {{ Value = 5.0, }}, }}, }},')
858 nodes.append(f'\t\t{add} = BrightnessContrast {{ Inputs = {{ Input = Input {{ SourceOp = "{bl}", Source = "Output", }}, Brightness = Input {{ Value = 0.4, }}, }}, }},')
859 cases.append((f, f"NegValues_Depth={d_name}", add))
860 f += 1
861
862 # Background native Depth=3/4 HDR
863 for d_code, d_name in ((3, "float16"), (4, "float32")):
864 bg = f"BG_{f}"
865 up = f"BUp_{f}"
866 dn = f"BDn_{f}"
867 nodes.append(f'\t\t{bg} = Background {{ Inputs = {{ Width = Input {{ Value = 256, }}, Height = Input {{ Value = 256, }}, Depth = Input {{ Value = {d_code}, }}, Type = Input {{ Value = FuID {{ "Horizontal" }}, }}, TopLeftRed = Input {{ Value = 0.8, }}, TopLeftGreen = Input {{ Value = 0.2, }}, TopLeftBlue = Input {{ Value = 0.1, }}, TopLeftAlpha = Input {{ Value = 1, }}, TopRightRed = Input {{ Value = 0.1, }}, TopRightGreen = Input {{ Value = 0.7, }}, TopRightBlue = Input {{ Value = 0.9, }}, }}, }},')
868 nodes.append(f'\t\t{up} = BrightnessContrast {{ Inputs = {{ Input = Input {{ SourceOp = "{bg}", Source = "Output", }}, Gain = Input {{ Value = 3.0, }}, }}, }},')
869 nodes.append(f'\t\t{dn} = BrightnessContrast {{ Inputs = {{ Input = Input {{ SourceOp = "{up}", Source = "Output", }}, Gain = Input {{ Value = 0.333333, }}, }}, }},')
870 cases.append((f, f"BG_Depth={d_name}_HDR", dn))
871 f += 1
872
873 # PreDividePostMultiply = 0 / 1 on semi-transparent FGLoader merged over DarkBG
874 for pd in (0, 1):
875 bc = f"BCPD_{f}"
876 m = f"MPD_{f}"
877 nodes.append(f'\t\t{bc} = BrightnessContrast {{ Inputs = {{ Input = Input {{ SourceOp = "FGLoader", Source = "Output", }}, Gain = Input {{ Value = 1.6, }}, Gamma = Input {{ Value = 0.7, }}, Brightness = Input {{ Value = 0.15, }}, PreDividePostMultiply = Input {{ Value = {pd}, }}, }}, }},')
878 nodes.append(f'\t\t{m} = Merge {{ Inputs = {{ Background = Input {{ SourceOp = "DarkBG", Source = "Output", }}, Foreground = Input {{ SourceOp = "{bc}", Source = "Output", }}, }}, }},')
879 cases.append((f, f"BC_PreDiv={pd}", m))
880 f += 1
881
882 sw_nodes, sw_splines, out_op = build_switch_chain(cases, "BlackBG", "HD")
883 nodes.extend(sw_nodes)
884 nodes.append(make_saver(out_op, "matrix_hdr_depth"))
885 comp_path = ensure_dirs() / "comps" / "matrix_hdr_depth.comp"
886 comp_path.write_text(make_comp("\n".join(nodes + sw_splines), len(cases) - 1))
887 return comp_path, "matrix_hdr_depth", [(c[0], c[1]) for c in cases]
888
889
890def build_matrix_masks(assets: Dict[str, str]):
891 """Chained multi-mask graphs (EllipseMask -> RectangleMask -> PolylineMask) testing all PaintModes, SoftEdge, BorderWidth, Invert, Level."""
892 nodes = [
893 """\t\tBlackBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftAlpha = Input { Value = 1, }, }, },
894\t\tWhiteFG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftRed = Input { Value = 0.95, }, TopLeftGreen = Input { Value = 0.75, }, TopLeftBlue = Input { Value = 0.25, }, TopLeftAlpha = Input { Value = 1, }, }, },""",
895 ]
896 cases: List[Tuple[int, str, str]] = []
897 f = 0
898
899 paint_modes = ["Merge", "Add", "Subtract", "Minimum", "Maximum", "Average", "Multiply", "Replace", "Invert"]
900 for pm in paint_modes:
901 e = f"Ell_{f}"
902 r = f"Rect_{f}"
903 p = f"Poly_{f}"
904 m = f"Op_{f}"
905 nodes.append(f'\t\t{e} = EllipseMask {{ Inputs = {{ MaskWidth = Input {{ Value = 256, }}, MaskHeight = Input {{ Value = 256, }}, Center = Input {{ Value = {{ 0.42, 0.50 }}, }}, Width = Input {{ Value = 0.50, }}, Height = Input {{ Value = 0.45, }}, SoftEdge = Input {{ Value = 0.03, }}, }}, }},')
906 nodes.append(f'\t\t{r} = RectangleMask {{ Inputs = {{ EffectMask = Input {{ SourceOp = "{e}", Source = "Mask", }}, PaintMode = Input {{ Value = FuID {{ "{pm}" }}, }}, MaskWidth = Input {{ Value = 256, }}, MaskHeight = Input {{ Value = 256, }}, Center = Input {{ Value = {{ 0.58, 0.55 }}, }}, Width = Input {{ Value = 0.42, }}, Height = Input {{ Value = 0.42, }}, SoftEdge = Input {{ Value = 0.02, }}, Level = Input {{ Value = 0.8, }}, }}, }},')
907 nodes.append(
908 f"""\t\t{p} = PolylineMask {{
909\t\t\tInputs = {{
910\t\t\t\tEffectMask = Input {{ SourceOp = "{r}", Source = "Mask", }},
911\t\t\t\tPaintMode = Input {{ Value = FuID {{ "{pm}" }}, }},
912\t\t\t\tMaskWidth = Input {{ Value = 256, }},
913\t\t\t\tMaskHeight = Input {{ Value = 256, }},
914\t\t\t\tSoftEdge = Input {{ Value = 0.02, }},
915\t\t\t\tPolyline = Input {{
916\t\t\t\t\tValue = Polyline {{
917\t\t\t\t\t\tClosed = true,
918\t\t\t\t\t\tPoints = {{
919\t\t\t\t\t\t\t{{ Linear = true, X = -0.25, Y = -0.25, RX = 0.16, RY = 0 }},
920\t\t\t\t\t\t\t{{ Linear = true, X = 0.25, Y = -0.15, LX = -0.16, LY = 0, RX = -0.08, RY = 0.14 }},
921\t\t\t\t\t\t\t{{ Linear = true, X = 0.0, Y = 0.28, LX = 0.08, LY = -0.14 }},
922\t\t\t\t\t\t}},
923\t\t\t\t\t}},
924\t\t\t\t}},
925\t\t\t}},
926\t\t}},"""
927 )
928 nodes.append(f'\t\t{m} = Merge {{ Inputs = {{ Background = Input {{ SourceOp = "BlackBG", Source = "Output", }}, Foreground = Input {{ SourceOp = "WhiteFG", Source = "Output", }}, EffectMask = Input {{ SourceOp = "{p}", Source = "Mask", }}, }}, }},')
929 cases.append((f, f"MaskChain_PaintMode={pm}", m))
930 f += 1
931
932 # BorderWidth, Solid=0/1, SoftEdge, Invert, Level edge cases
933 extra_masks = [
934 ("Rect_Border0.05_Solid0", 'RectangleMask { Inputs = { MaskWidth = Input { Value = 256, }, MaskHeight = Input { Value = 256, }, Width = Input { Value = 0.5, }, Height = Input { Value = 0.5, }, Solid = Input { Value = 0, }, BorderWidth = Input { Value = 0.05, }, }, }'),
935 ("Ell_Border0.04_Soft0.03_Inv1", 'EllipseMask { Inputs = { MaskWidth = Input { Value = 256, }, MaskHeight = Input { Value = 256, }, Width = Input { Value = 0.45, }, Height = Input { Value = 0.35, }, Angle = Input { Value = 25, }, Solid = Input { Value = 1, }, BorderWidth = Input { Value = 0.04, }, SoftEdge = Input { Value = 0.03, }, Invert = Input { Value = 1, }, Level = Input { Value = 0.65, }, }, }'),
936 ("Rect_Corner0.35_Soft0.08_Box", 'RectangleMask { Inputs = { MaskWidth = Input { Value = 256, }, MaskHeight = Input { Value = 256, }, Width = Input { Value = 0.6, }, Height = Input { Value = 0.45, }, CornerRadius = Input { Value = 0.35, }, SoftEdge = Input { Value = 0.08, }, Filter = Input { Value = FuID { "Box" }, }, }, }'),
937 ("Poly_Invert1_Level0.6_Soft0.05", 'PolylineMask { Inputs = { MaskWidth = Input { Value = 256, }, MaskHeight = Input { Value = 256, }, SoftEdge = Input { Value = 0.05, }, Invert = Input { Value = 1, }, Level = Input { Value = 0.6, }, Polyline = Input { Value = Polyline { Closed = true, Points = { { Linear = true, X = -0.3, Y = -0.2 }, { Linear = true, X = 0.3, Y = -0.2 }, { Linear = true, X = 0.0, Y = 0.3 } } }, }, }, }'),
938 ]
939 for label, mdef in extra_masks:
940 mk = f"Mk_{f}"
941 m = f"Op_{f}"
942 nodes.append(f"\t\t{mk} = {mdef},")
943 nodes.append(f'\t\t{m} = Merge {{ Inputs = {{ Background = Input {{ SourceOp = "BlackBG", Source = "Output", }}, Foreground = Input {{ SourceOp = "WhiteFG", Source = "Output", }}, EffectMask = Input {{ SourceOp = "{mk}", Source = "Mask", }}, }}, }},')
944 cases.append((f, label, m))
945 f += 1
946
947 sw_nodes, sw_splines, out_op = build_switch_chain(cases, "BlackBG", "MK")
948 nodes.extend(sw_nodes)
949 nodes.append(make_saver(out_op, "matrix_masks"))
950 comp_path = ensure_dirs() / "comps" / "matrix_masks.comp"
951 comp_path.write_text(make_comp("\n".join(nodes + sw_splines), len(cases) - 1))
952 return comp_path, "matrix_masks", [(c[0], c[1]) for c in cases]
953
954
955def build_matrix_color_blur(assets: Dict[str, str]):
956 """ColorCorrector, ColorCurves, HueCurves, GamutConvert, ChannelBoolean, Blur, Glow, SoftGlow, DirectionalBlur."""
957 nodes = [
958 make_loader("ColorLoader", assets["color"], post_mult=1),
959 make_loader("FGLoader", assets["fg"], post_mult=1),
960 """\t\tBlackBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftAlpha = Input { Value = 1, }, }, },
961\t\tDarkBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftRed = Input { Value = 0.12, }, TopLeftGreen = Input { Value = 0.12, }, TopLeftBlue = Input { Value = 0.18, }, TopLeftAlpha = Input { Value = 1, }, }, },""",
962 lut_bezier("CC_Red", [(0.0, 0.0), (0.3, 0.55), (0.7, 0.45), (1.0, 0.95)]),
963 lut_bezier("CC_Green", [(0.0, 0.08), (0.5, 0.42), (1.0, 1.0)]),
964 lut_bezier("CC_Blue", [(0.0, 0.0), (0.5, 0.72), (1.0, 0.85)]),
965 lut_bezier("CC_Alpha", [(0.0, 0.0), (0.5, 0.85), (1.0, 1.0)]),
966 lut_bezier("HC_Hue", [(0, 1.25), (2, 0.85), (4, 1.15), (6, 1.25)]),
967 lut_bezier("HC_Sat", [(0, 1.0), (1, 0.3), (3, 1.7), (5, 0.6), (6, 1.0)]),
968 lut_bezier("HC_Lum", [(0, 1.0), (2, 0.6), (4, 1.4), (6, 1.0)]),
969 lut_bezier("HC_RSup", [(0, 0.5), (2, 1.0), (6, 0.5)]),
970 ]
971 cases: List[Tuple[int, str, str]] = []
972 f = 0
973
974 def add_op(label: str, kind: str, in_port: str, src: str, extra: str, over_dark: bool = False) -> None:
975 nonlocal f
976 opn = f"Op_{f}"
977 nodes.append(
978 f"""\t\t{opn} = {kind} {{
979\t\t\tInputs = {{
980\t\t\t\t{in_port} = Input {{ SourceOp = "{src}", Source = "Output", }},
981\t\t\t\t{extra}
982\t\t\t}},
983\t\t}},"""
984 )
985 out_n = opn
986 if over_dark:
987 vn = f"Vis_{f}"
988 nodes.append(f'\t\t{vn} = Merge {{ Inputs = {{ Background = Input {{ SourceOp = "DarkBG", Source = "Output", }}, Foreground = Input {{ SourceOp = "{opn}", Source = "Output", }}, }}, }},')
989 out_n = vn
990 cases.append((f, label, out_n))
991 f += 1
992
993 # ColorCorrector: SMH + Wheel Hue/Sat/Tint + PreDividePostMultiply
994 add_op("CC_SMH_Wheel_PreDiv1", "ColorCorrector", "Input", "FGLoader", "WheelHue1 = Input { Value = 0.18, }, WheelSaturation1 = Input { Value = 1.35, }, WheelTintAngle1 = Input { Value = -0.35, }, WheelTintLength1 = Input { Value = 0.65, }, ShadowsRGBGain = Input { Value = 0.7, }, MidtonesRGBGamma = Input { Value = 1.35, }, HighlightsRGBGain = Input { Value = 1.3, }, PreDividePostMultiply = Input { Value = 1, },", over_dark=True)
995 add_op("CC_SMH_TintMode0", "ColorCorrector", "Input", "ColorLoader", "WheelTintAngle2 = Input { Value = 0.25, }, WheelTintLength2 = Input { Value = 0.7, }, WheelHue3 = Input { Value = -0.2, }, WheelSaturation4 = Input { Value = 1.6, }, TintMode = Input { Value = 0, },")
996 add_op("CC_SMH_TintMode1", "ColorCorrector", "Input", "ColorLoader", "WheelTintAngle1 = Input { Value = -0.25, }, WheelTintLength1 = Input { Value = 0.8, }, WheelSaturation1 = Input { Value = 1.4, }, TintMode = Input { Value = 1, },")
997
998 # ColorCurves & HueCurves
999 add_op("ColorCurves_RGBA_PreDiv1", "ColorCurves", "Input", "ColorLoader", 'Red = Input { SourceOp = "CC_Red", Source = "Value", }, Green = Input { SourceOp = "CC_Green", Source = "Value", }, Blue = Input { SourceOp = "CC_Blue", Source = "Value", }, Alpha = Input { SourceOp = "CC_Alpha", Source = "Value", }, PreDividePostMultiply = Input { Value = 1, },', over_dark=True)
1000 add_op("HueCurves_Multi", "HueCurves", "Input", "ColorLoader", 'Hue = Input { SourceOp = "HC_Hue", Source = "Value", }, Sat = Input { SourceOp = "HC_Sat", Source = "Value", }, Lum = Input { SourceOp = "HC_Lum", Source = "Value", }, RedSuppress = Input { SourceOp = "HC_RSup", Source = "Value", },')
1001
1002 # GamutConvert
1003 add_op("Gamut_sRGB_to_Linear", "GamutConvert", "Input", "ColorLoader", 'SourceSpace = Input { Value = FuID { "sRGB" }, }, OutputSpace = Input { Value = FuID { "NoChange" }, }, RemoveGamma = Input { Value = 1, }, AddGamma = Input { Value = 0, },')
1004 add_op("Gamut_Linear_to_sRGB", "GamutConvert", "Input", "ColorLoader", 'SourceSpace = Input { Value = FuID { "NoChange" }, }, OutputSpace = Input { Value = FuID { "sRGB" }, }, RemoveGamma = Input { Value = 0, }, AddGamma = Input { Value = 1, },')
1005 add_op("Gamut_Rec709_to_sRGB", "GamutConvert", "Input", "ColorLoader", 'SourceSpace = Input { Value = FuID { "Rec709" }, }, OutputSpace = Input { Value = FuID { "sRGB" }, }, RemoveGamma = Input { Value = 1, }, AddGamma = Input { Value = 1, },')
1006
1007 # ChannelBoolean: Add/Sub/Mul/Div/Copy/Min/Max/Negative/Solid
1008 cb_ops = [
1009 ("CB_Copy_BGR", 0, 'ToRed = Input { Value = 2, }, ToGreen = Input { Value = 1, }, ToBlue = Input { Value = 0, },'),
1010 ("CB_Add", 1, 'Foreground = Input { SourceOp = "FGLoader", Source = "Output", },'),
1011 ("CB_Sub", 2, 'Foreground = Input { SourceOp = "FGLoader", Source = "Output", },'),
1012 ("CB_Mul", 6, 'Foreground = Input { SourceOp = "FGLoader", Source = "Output", },'),
1013 ("CB_Div", 7, 'Foreground = Input { SourceOp = "FGLoader", Source = "Output", },'),
1014 ("CB_Max", 8, 'Foreground = Input { SourceOp = "FGLoader", Source = "Output", },'),
1015 ("CB_Min", 9, 'Foreground = Input { SourceOp = "FGLoader", Source = "Output", },'),
1016 ("CB_Negative", 10, 'Foreground = Input { SourceOp = "FGLoader", Source = "Output", },'),
1017 ("CB_Solid", 11, ''),
1018 ]
1019 for label, op_code, extra in cb_ops:
1020 add_op(label, "ChannelBoolean", "Background", "ColorLoader", f"Operation = Input {{ Value = {op_code}, }}, {extra}")
1021
1022 # Blur (Gaussian, Box, FastGaussian + unlocked X/Y)
1023 add_op("Blur_Gaussian_XY", "Blur", "Input", "ColorLoader", 'Filter = Input { Value = FuID { "Gaussian" }, }, LockBlurXY = Input { Value = 0, }, XBlurSize = Input { Value = 16.0, }, YBlurSize = Input { Value = 3.0, },')
1024 add_op("Blur_Box_12", "Blur", "Input", "ColorLoader", 'Filter = Input { Value = FuID { "Box" }, }, XBlurSize = Input { Value = 12.0, },')
1025 add_op("Blur_FastGauss_XY", "Blur", "Input", "ColorLoader", 'Filter = Input { Value = FuID { "Fast Gaussian" }, }, LockBlurXY = Input { Value = 0, }, XBlurSize = Input { Value = 4.0, }, YBlurSize = Input { Value = 20.0, },')
1026
1027 # Glow, SoftGlow, DirectionalBlur
1028 add_op("Glow_UnlockedXY", "Glow", "Input", "FGLoader", "LockGlowSize = Input { Value = 0, }, XGlowSize = Input { Value = 18.0, }, YGlowSize = Input { Value = 3.0, }, Glow = Input { Value = 0.78, },", over_dark=True)
1029 add_op("SoftGlow_UnlockedXY_Thresh", "SoftGlow", "Input", "ColorLoader", "LockGlowSize = Input { Value = 0, }, XGlowSize = Input { Value = 16.0, }, YGlowSize = Input { Value = 4.0, }, Gain = Input { Value = 2.2, }, Threshold = Input { Value = 0.45, },")
1030 add_op("DirBlur_Centered_Glow", "DirectionalBlur", "Input", "ColorLoader", "Type = Input { Value = 2, }, Length = Input { Value = 0.08, }, Angle = Input { Value = 35.0, }, Glow = Input { Value = 0.35, }, Center = Input { Value = { 0.4, 0.6 }, },")
1031
1032 sw_nodes, sw_splines, out_op = build_switch_chain(cases, "BlackBG", "CB")
1033 nodes.extend(sw_nodes)
1034 nodes.append(make_saver(out_op, "matrix_color_blur"))
1035 comp_path = ensure_dirs() / "comps" / "matrix_color_blur.comp"
1036 comp_path.write_text(make_comp("\n".join(nodes + sw_splines), len(cases) - 1))
1037 return comp_path, "matrix_color_blur", [(c[0], c[1]) for c in cases]
1038
1039
1040def build_matrix_warps_shapes(assets: Dict[str, str]):
1041 """Transform (Edges=0/1/2/3, Pivot, Angle, Aspect), DVE, CornerPositioner, Displace, Drip, Dent, Vortex, sRender+s*."""
1042 nodes = [
1043 make_loader("ColorLoader", assets["color"], post_mult=1),
1044 make_loader("BumpLoader", assets["bump"], post_mult=1),
1045 """\t\tBlackBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftAlpha = Input { Value = 1, }, }, },""",
1046 ]
1047 cases: List[Tuple[int, str, str]] = []
1048 f = 0
1049
1050 for ed in (0, 1, 2, 3):
1051 opn = f"Op_{f}"
1052 nodes.append(f'\t\t{opn} = Transform {{ Inputs = {{ Input = Input {{ SourceOp = "ColorLoader", Source = "Output", }}, Center = Input {{ Value = {{ 0.72, 0.65 }}, }}, Pivot = Input {{ Value = {{ 0.25, 0.35 }}, }}, Size = Input {{ Value = 0.80, }}, Aspect = Input {{ Value = 1.35, }}, Angle = Input {{ Value = 28.0, }}, Edges = Input {{ Value = {ed}, }}, }}, }},')
1053 cases.append((f, f"Transform_Edges={ed}_Pivot_Aspect", opn))
1054 f += 1
1055
1056 warps = [
1057 ("DVE_3D_Pivot", "DVE", 'Input = Input { SourceOp = "ColorLoader", Source = "Output", }, XRotation = Input { Value = 32, }, YRotation = Input { Value = -35, }, ZRotation = Input { Value = 18, }, ZMove = Input { Value = 1.35, }, Pivot = Input { Value = { 0.3, 0.6 }, }, Center = Input { Value = { 0.45, 0.55 }, },'),
1058 ("CornerPositioner_Quad", "CornerPositioner", 'Input = Input { SourceOp = "ColorLoader", Source = "Output", }, TopLeft = Input { Value = { 0.15, 0.88 }, }, TopRight = Input { Value = { 0.92, 0.78 }, }, BottomLeft = Input { Value = { 0.08, 0.12 }, }, BottomRight = Input { Value = { 0.82, 0.22 }, },'),
1059 ("Displace_Radial_Light", "Displace", 'Input = Input { SourceOp = "ColorLoader", Source = "Output", }, Foreground = Input { SourceOp = "BumpLoader", Source = "Output", }, Type = Input { Value = 0, }, RefractionStrength = Input { Value = 0.12, }, Spread = Input { Value = 0.25, }, LightPower = Input { Value = 0.6, },'),
1060 ("Displace_XY_Offset", "Displace", 'Input = Input { SourceOp = "ColorLoader", Source = "Output", }, Foreground = Input { SourceOp = "BumpLoader", Source = "Output", }, Type = Input { Value = 1, }, XOffset = Input { Value = -0.5, }, YOffset = Input { Value = -0.5, }, XRefraction = Input { Value = 0.10, }, YRefraction = Input { Value = 0.08, },'),
1061 ("Drip_Concentric", "Drip", 'Input = Input { SourceOp = "ColorLoader", Source = "Output", }, Center = Input { Value = { 0.45, 0.55 }, }, Strength = Input { Value = 1.0, }, Amplitude = Input { Value = 0.10, }, Frequency = Input { Value = 5.0, }, Phase = Input { Value = 0.4, }, Shape = Input { Value = 0, },'),
1062 ("Dent_Bulge", "Dent", 'Input = Input { SourceOp = "ColorLoader", Source = "Output", }, Center = Input { Value = { 0.5, 0.5 }, }, Size = Input { Value = 0.65, }, Strength = Input { Value = 0.75, }, Type = Input { Value = 0, },'),
1063 ("Dent_Pinch", "Dent", 'Input = Input { SourceOp = "ColorLoader", Source = "Output", }, Center = Input { Value = { 0.45, 0.55 }, }, Size = Input { Value = 0.60, }, Strength = Input { Value = 0.70, }, Type = Input { Value = 2, },'),
1064 ("Vortex_Swirl", "Vortex", 'Input = Input { SourceOp = "ColorLoader", Source = "Output", }, Center = Input { Value = { 0.4, 0.6 }, }, Size = Input { Value = 0.65, }, Angle = Input { Value = 2.4, }, Power = Input { Value = 2.2, },'),
1065 ]
1066 for label, kind, inputs in warps:
1067 opn = f"Op_{f}"
1068 nodes.append(f"\t\t{opn} = {kind} {{ Inputs = {{ {inputs} }}, }},")
1069 cases.append((f, label, opn))
1070 f += 1
1071
1072 # sRender + sNGon / sRectangle / sEllipse / sTransform / sMerge / sBoolean / sOutline
1073 nodes.append(
1074 """\t\tS_NGon = sNGon { Inputs = { Sides = Input { Value = 5, }, Width = Input { Value = 0.45, }, Height = Input { Value = 0.45, }, Red = Input { Value = 0.95, }, Green = Input { Value = 0.3, }, Blue = Input { Value = 0.2, }, }, },
1075\t\tS_Rect = sRectangle { Inputs = { Width = Input { Value = 0.35, }, Height = Input { Value = 0.35, }, CornerRadius = Input { Value = 0.08, }, ["Translate.X"] = Input { Value = 0.18, }, Red = Input { Value = 0.2, }, Green = Input { Value = 0.85, }, Blue = Input { Value = 0.4, }, }, },
1076\t\tS_Ell = sEllipse { Inputs = { Width = Input { Value = 0.32, }, Height = Input { Value = 0.24, }, ["Translate.X"] = Input { Value = -0.15, }, ["Translate.Y"] = Input { Value = 0.15, }, Red = Input { Value = 0.25, }, Green = Input { Value = 0.55, }, Blue = Input { Value = 0.98, }, }, },
1077\t\tS_XF = sTransform { Inputs = { Input = Input { SourceOp = "S_NGon", Source = "Output", }, XOffset = Input { Value = -0.15, }, YOffset = Input { Value = -0.10, }, ZRotation = Input { Value = 25.0, }, XSize = Input { Value = 0.85, }, YSize = Input { Value = 0.85, }, }, },
1078\t\tS_Merge = sMerge { Inputs = { Input1 = Input { SourceOp = "S_XF", Source = "Output", }, Input2 = Input { SourceOp = "S_Rect", Source = "Output", }, }, },
1079\t\tS_BoolSub = sBoolean { Inputs = { Operation = Input { Value = FuID { "Subtract" }, }, Input1 = Input { SourceOp = "S_Rect", Source = "Output", }, Input2 = Input { SourceOp = "S_Ell", Source = "Output", }, }, },
1080\t\tS_BoolXor = sBoolean { Inputs = { Operation = Input { Value = FuID { "Xor" }, }, Input1 = Input { SourceOp = "S_NGon", Source = "Output", }, Input2 = Input { SourceOp = "S_Rect", Source = "Output", }, }, },
1081\t\tS_Outl = sOutline { Inputs = { Input = Input { SourceOp = "S_Ell", Source = "Output", }, Thickness = Input { Value = 0.03, }, }, },"""
1082 )
1083 for label, s_src in [
1084 ("sRender_NGon_XF_Merge", "S_Merge"),
1085 ("sRender_sBoolean_Sub", "S_BoolSub"),
1086 ("sRender_sBoolean_Xor", "S_BoolXor"),
1087 ("sRender_sOutline_Ell", "S_Outl"),
1088 ]:
1089 opn = f"Op_{f}"
1090 nodes.append(f'\t\t{opn} = sRender {{ Inputs = {{ Width = Input {{ Value = 256, }}, Height = Input {{ Value = 256, }}, Input = Input {{ SourceOp = "{s_src}", Source = "Output", }}, }}, }},')
1091 cases.append((f, label, opn))
1092 f += 1
1093
1094 sw_nodes, sw_splines, out_op = build_switch_chain(cases, "BlackBG", "WS")
1095 nodes.extend(sw_nodes)
1096 nodes.append(make_saver(out_op, "matrix_warps_shapes"))
1097 comp_path = ensure_dirs() / "comps" / "matrix_warps_shapes.comp"
1098 comp_path.write_text(make_comp("\n".join(nodes + sw_splines), len(cases) - 1))
1099 return comp_path, "matrix_warps_shapes", [(c[0], c[1]) for c in cases]
1100
1101
1102def build_matrix_3d(assets: Dict[str, str]):
1103 """Cube3D, SurfaceFBXMesh, TextureTransformOperator, BumpMap, LightPoint (Linear/Quad), LightSpot, Duplicate3D, Displace3D, Override3D, ReplaceMaterial3D."""
1104 nodes = [
1105 make_loader("ColorLoader", assets["color"], post_mult=1),
1106 make_loader("BumpLoader", assets["bump"], post_mult=1),
1107 """\t\tBlackBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftAlpha = Input { Value = 1, }, }, },
1108\t\tCamBase = Camera3D { Inputs = { ["Transform3DOp.Translate.Z"] = Input { Value = 4.2, }, AoV = Input { Value = 35.0, }, FilmGate = Input { Value = FuID { "User" }, }, ApertureW = Input { Value = 1.0, }, ApertureH = Input { Value = 1.0, }, }, },
1109\t\tAmbLow = LightAmbient { Inputs = { Intensity = Input { Value = 0.20, }, }, },""",
1110 ]
1111 cases: List[Tuple[int, str, str]] = []
1112 f = 0
1113
1114 def add_3d(label: str, scene_nodes: List[str], merge_inputs: str, lighting: int = 1) -> None:
1115 nonlocal f
1116 nodes.extend(scene_nodes)
1117 m3d = f"M3D_{f}"
1118 rnd = f"Op_{f}"
1119 nodes.append(f"\t\t{m3d} = Merge3D {{ Inputs = {{ {merge_inputs} SceneInput9 = Input {{ SourceOp = \"CamBase\", Source = \"Output\", }}, }}, }},")
1120 nodes.append(f'\t\t{rnd} = Renderer3D {{ Inputs = {{ Width = Input {{ Value = 256, }}, Height = Input {{ Value = 256, }}, ["RendererSoftware.LightingEnabled"] = Input {{ Value = {lighting}, }}, SceneInput = Input {{ SourceOp = "{m3d}", Source = "Output", }}, }}, }},')
1121 cases.append((f, label, rnd))
1122 f += 1
1123
1124 # 0: Cube3D textured
1125 add_3d(
1126 "Cube3D_Textured",
1127 [
1128 '\t\tTex0 = Texture2DOperator { Inputs = { Input = Input { SourceOp = "ColorLoader", Source = "Output", }, }, },',
1129 '\t\tCube0 = Cube3D { Inputs = { ["SurfaceCubeInputs.Size"] = Input { Value = 1.4, }, ["Transform3DOp.Rotate.X"] = Input { Value = 25, }, ["Transform3DOp.Rotate.Y"] = Input { Value = 35, }, MaterialInput = Input { SourceOp = "Tex0", Source = "MaterialOutput", }, }, },',
1130 ],
1131 'SceneInput1 = Input { SourceOp = "Cube0", Source = "Output", },',
1132 lighting=0,
1133 )
1134
1135 # 1: SurfaceFBXMesh (cube.obj)
1136 add_3d(
1137 "SurfaceFBXMesh_OBJ",
1138 [
1139 '\t\tTex1 = Texture2DOperator { Inputs = { Input = Input { SourceOp = "ColorLoader", Source = "Output", }, }, },',
1140 f'\t\tFbx1 = SurfaceFBXMesh {{ Inputs = {{ ImportFile = Input {{ Value = "{assets["cube_obj"]}", }}, ["Transform3DOp.Scale.X"] = Input {{ Value = 1.5, }}, ["Transform3DOp.Scale.Y"] = Input {{ Value = 1.5, }}, ["Transform3DOp.Scale.Z"] = Input {{ Value = 1.5, }}, ["Transform3DOp.Rotate.X"] = Input {{ Value = 25, }}, ["Transform3DOp.Rotate.Y"] = Input {{ Value = -35, }}, MaterialInput = Input {{ SourceOp = "Tex1", Source = "MaterialOutput", }}, }}, }},',
1141 ],
1142 'SceneInput1 = Input { SourceOp = "Fbx1", Source = "Output", },',
1143 lighting=0,
1144 )
1145
1146 # 2: TextureTransformOperator
1147 add_3d(
1148 "TextureTransformOperator",
1149 [
1150 '\t\tTex2 = Texture2DOperator { Inputs = { Input = Input { SourceOp = "ColorLoader", Source = "Output", }, }, },',
1151 '\t\tTexXf2 = TextureTransformOperator { Inputs = { MaterialInput = Input { SourceOp = "Tex2", Source = "MaterialOutput", }, ["TranslationOffset.X"] = Input { Value = 0.25, }, ["TranslationOffset.Y"] = Input { Value = -0.15, }, ["Scale.X"] = Input { Value = 2.0, }, ["Scale.Y"] = Input { Value = 2.0, }, ["Rotation.Z"] = Input { Value = 30.0, }, WrapMode = Input { Value = FuID { "Wrap" }, }, }, },',
1152 '\t\tPl2 = Shape3D { Inputs = { Shape = Input { Value = FuID { "SurfacePlaneInputs" }, }, ["SurfacePlaneInputs.Width"] = Input { Value = 2.2, }, ["SurfacePlaneInputs.Height"] = Input { Value = 2.2, }, MaterialInput = Input { SourceOp = "TexXf2", Source = "MaterialOutput", }, }, },',
1153 ],
1154 'SceneInput1 = Input { SourceOp = "Pl2", Source = "Output", },',
1155 lighting=0,
1156 )
1157
1158 # 3: BumpMap + MtlBlinn + LightPoint
1159 add_3d(
1160 "BumpMap_MtlBlinn",
1161 [
1162 '\t\tBm3 = BumpMap { Inputs = { Input = Input { SourceOp = "BumpLoader", Source = "Output", }, HeightScale = Input { Value = 4.0, }, }, },',
1163 '\t\tMtl3 = MtlBlinn { Inputs = { ["Diffuse.Color.Red"] = Input { Value = 0.3, }, ["Diffuse.Color.Green"] = Input { Value = 0.7, }, ["Diffuse.Color.Blue"] = Input { Value = 0.95, }, ["Specular.Intensity"] = Input { Value = 1.0, }, ["Specular.Exponent"] = Input { Value = 28.0, }, ["Bumpmap.Material"] = Input { SourceOp = "Bm3", Source = "MaterialOutput", }, }, },',
1164 '\t\tSph3 = Shape3D { Inputs = { Shape = Input { Value = FuID { "SurfaceSphereInputs" }, }, ["SurfaceSphereInputs.Radius"] = Input { Value = 1.0, }, MaterialInput = Input { SourceOp = "Mtl3", Source = "MaterialOutput", }, }, },',
1165 '\t\tPt3 = LightPoint { Inputs = { ["Transform3DOp.Translate.X"] = Input { Value = 2.2, }, ["Transform3DOp.Translate.Y"] = Input { Value = 1.8, }, ["Transform3DOp.Translate.Z"] = Input { Value = 2.8, }, Intensity = Input { Value = 1.4, }, }, },',
1166 ],
1167 'SceneInput1 = Input { SourceOp = "Sph3", Source = "Output", }, SceneInput2 = Input { SourceOp = "Pt3", Source = "Output", }, SceneInput3 = Input { SourceOp = "AmbLow", Source = "Output", },',
1168 lighting=1,
1169 )
1170
1171 # 4 & 5: LightPoint Linear (DecayType=1) and Quadratic (DecayType=2)
1172 for decay_t, d_name in ((1, "Linear"), (2, "Quadratic")):
1173 add_3d(
1174 f"LightPoint_Decay={d_name}",
1175 [
1176 f'\t\tMtl_{f} = MtlBlinn {{ Inputs = {{ ["Diffuse.Color.Red"] = Input {{ Value = 0.9, }}, ["Diffuse.Color.Green"] = Input {{ Value = 0.85, }}, ["Diffuse.Color.Blue"] = Input {{ Value = 0.75, }}, }}, }},',
1177 f'\t\tPl_{f} = Shape3D {{ Inputs = {{ Shape = Input {{ Value = FuID {{ "SurfacePlaneInputs" }}, }}, ["SurfacePlaneInputs.Width"] = Input {{ Value = 2.8, }}, ["SurfacePlaneInputs.Height"] = Input {{ Value = 2.8, }}, MaterialInput = Input {{ SourceOp = "Mtl_{f}", Source = "MaterialOutput", }}, }}, }},',
1178 f'\t\tPt_{f} = LightPoint {{ Inputs = {{ ["Transform3DOp.Translate.X"] = Input {{ Value = 0.8, }}, ["Transform3DOp.Translate.Y"] = Input {{ Value = 0.5, }}, ["Transform3DOp.Translate.Z"] = Input {{ Value = 1.6, }}, Intensity = Input {{ Value = 3.5, }}, DecayType = Input {{ Value = {decay_t}, }}, }}, }},',
1179 ],
1180 f'SceneInput1 = Input {{ SourceOp = "Pl_{f}", Source = "Output", }}, SceneInput2 = Input {{ SourceOp = "Pt_{f}", Source = "Output", }}, SceneInput3 = Input {{ SourceOp = "AmbLow", Source = "Output", }},',
1181 lighting=1,
1182 )
1183
1184 # 6: LightSpot
1185 add_3d(
1186 "LightSpot_ConePenumbra",
1187 [
1188 '\t\tMtl6 = MtlCookTorrance { Inputs = { ["Diffuse.Color.Red"] = Input { Value = 0.95, }, ["Diffuse.Color.Green"] = Input { Value = 0.75, }, ["Diffuse.Color.Blue"] = Input { Value = 0.45, }, ["Specular.Roughness"] = Input { Value = 0.3, }, }, },',
1189 '\t\tPl6 = Shape3D { Inputs = { Shape = Input { Value = FuID { "SurfacePlaneInputs" }, }, ["SurfacePlaneInputs.Width"] = Input { Value = 3.0, }, ["SurfacePlaneInputs.Height"] = Input { Value = 3.0, }, MaterialInput = Input { SourceOp = "Mtl6", Source = "MaterialOutput", }, }, },',
1190 '\t\tSp6 = LightSpot { Inputs = { ["Transform3DOp.Translate.X"] = Input { Value = -0.5, }, ["Transform3DOp.Translate.Z"] = Input { Value = 2.5, }, ["Transform3DOp.Rotate.Y"] = Input { Value = -10, }, ConeAngle = Input { Value = 35.0, }, PenumbraAngle = Input { Value = 12.0, }, Intensity = Input { Value = 1.8, }, DecayType = Input { Value = 1, }, }, },',
1191 ],
1192 'SceneInput1 = Input { SourceOp = "Pl6", Source = "Output", }, SceneInput2 = Input { SourceOp = "Sp6", Source = "Output", }, SceneInput3 = Input { SourceOp = "AmbLow", Source = "Output", },',
1193 lighting=1,
1194 )
1195
1196 # 7: Duplicate3D
1197 add_3d(
1198 "Duplicate3D_5x",
1199 [
1200 '\t\tBox7 = Shape3D { Inputs = { Shape = Input { Value = FuID { "SurfaceCubeInputs" }, }, ["SurfaceCubeInputs.Size"] = Input { Value = 0.35, }, ["Transform3DOp.Translate.X"] = Input { Value = -1.1, }, ["MtlStdInputs.Diffuse.Color.Red"] = Input { Value = 0.95, }, ["MtlStdInputs.Diffuse.Color.Green"] = Input { Value = 0.45, }, ["MtlStdInputs.Diffuse.Color.Blue"] = Input { Value = 0.15, }, }, },',
1201 '\t\tDup7 = Duplicate3D { Inputs = { SceneInput = Input { SourceOp = "Box7", Source = "Output", }, FirstCopy = Input { Value = 0, }, LastCopy = Input { Value = 4, }, ["Translate.X"] = Input { Value = 0.55, }, ["Rotate.Z"] = Input { Value = 18.0, }, }, },',
1202 ],
1203 'SceneInput1 = Input { SourceOp = "Dup7", Source = "Output", },',
1204 lighting=0,
1205 )
1206
1207 # 8: Displace3D
1208 add_3d(
1209 "Displace3D_Bump",
1210 [
1211 '\t\tPl8 = Shape3D { Inputs = { Shape = Input { Value = FuID { "SurfacePlaneInputs" }, }, ["SurfacePlaneInputs.Width"] = Input { Value = 2.0, }, ["SurfacePlaneInputs.Height"] = Input { Value = 2.0, }, ["SurfacePlaneInputs.SubdivisionWidth"] = Input { Value = 32, }, ["SurfacePlaneInputs.SubdivisionHeight"] = Input { Value = 32, }, ["Transform3DOp.Rotate.X"] = Input { Value = -38.0, }, MaterialInput = Input { SourceOp = "ColorLoader", Source = "Output", }, }, },',
1212 '\t\tDisp8 = Displace3D { Inputs = { SceneInput = Input { SourceOp = "Pl8", Source = "Output", }, Input = Input { SourceOp = "BumpLoader", Source = "Output", }, Scale = Input { Value = 0.6, }, }, },',
1213 ],
1214 'SceneInput1 = Input { SourceOp = "Disp8", Source = "Output", },',
1215 lighting=0,
1216 )
1217
1218 # 9: Override3D (hide + material override)
1219 add_3d(
1220 "Override3D_Hide_MatOvr",
1221 [
1222 '\t\tSph9L = Shape3D { Inputs = { Shape = Input { Value = FuID { "SurfaceSphereInputs" }, }, ["SurfaceSphereInputs.Radius"] = Input { Value = 0.55, }, ["Transform3DOp.Translate.X"] = Input { Value = -0.7, }, ["MtlStdInputs.Diffuse.Color.Red"] = Input { Value = 0.9, }, ["MtlStdInputs.Diffuse.Color.Green"] = Input { Value = 0.2, }, ["MtlStdInputs.Diffuse.Color.Blue"] = Input { Value = 0.2, }, }, },',
1223 '\t\tOvr9Hide = Override3D { Inputs = { SceneInput = Input { SourceOp = "Sph9L", Source = "Output", }, ["Visibility.DoVisible"] = Input { Value = 1, }, ["Visibility.IsVisible"] = Input { Value = 0, }, }, },',
1224 '\t\tSph9R = Shape3D { Inputs = { Shape = Input { Value = FuID { "SurfaceSphereInputs" }, }, ["SurfaceSphereInputs.Radius"] = Input { Value = 0.55, }, ["Transform3DOp.Translate.X"] = Input { Value = 0.7, }, }, },',
1225 '\t\tTex9 = Texture2DOperator { Inputs = { Input = Input { SourceOp = "ColorLoader", Source = "Output", }, }, },',
1226 '\t\tOvr9Mat = Override3D { Inputs = { SceneInput = Input { SourceOp = "Sph9R", Source = "Output", }, ["Material.DoMaterial"] = Input { Value = 1, }, MaterialInput = Input { SourceOp = "Tex9", Source = "MaterialOutput", }, }, },',
1227 ],
1228 'SceneInput1 = Input { SourceOp = "Ovr9Hide", Source = "Output", }, SceneInput2 = Input { SourceOp = "Ovr9Mat", Source = "Output", },',
1229 lighting=0,
1230 )
1231
1232 # 10: ReplaceMaterial3D
1233 add_3d(
1234 "ReplaceMaterial3D_Cook",
1235 [
1236 '\t\tTex10 = Texture2DOperator { Inputs = { Input = Input { SourceOp = "ColorLoader", Source = "Output", }, }, },',
1237 '\t\tMtl10 = MtlCookTorrance { Inputs = { ["Diffuse.Color.Material"] = Input { SourceOp = "Tex10", Source = "MaterialOutput", }, ["Specular.Roughness"] = Input { Value = 0.25, }, }, },',
1238 '\t\tSph10 = Shape3D { Inputs = { Shape = Input { Value = FuID { "SurfaceSphereInputs" }, }, ["SurfaceSphereInputs.Radius"] = Input { Value = 1.0, }, }, },',
1239 '\t\tRep10 = ReplaceMaterial3D { Inputs = { SceneInput = Input { SourceOp = "Sph10", Source = "Output", }, MaterialInput = Input { SourceOp = "Mtl10", Source = "MaterialOutput", }, }, },',
1240 '\t\tPt10 = LightPoint { Inputs = { ["Transform3DOp.Translate.X"] = Input { Value = 2.0, }, ["Transform3DOp.Translate.Y"] = Input { Value = 1.5, }, ["Transform3DOp.Translate.Z"] = Input { Value = 3.0, }, Intensity = Input { Value = 1.2, }, }, },',
1241 ],
1242 'SceneInput1 = Input { SourceOp = "Rep10", Source = "Output", }, SceneInput2 = Input { SourceOp = "Pt10", Source = "Output", }, SceneInput3 = Input { SourceOp = "AmbLow", Source = "Output", },',
1243 lighting=1,
1244 )
1245
1246 sw_nodes, sw_splines, out_op = build_switch_chain(cases, "BlackBG", "D3D")
1247 nodes.extend(sw_nodes)
1248 nodes.append(make_saver(out_op, "matrix_3d"))
1249 comp_path = ensure_dirs() / "comps" / "matrix_3d.comp"
1250 comp_path.write_text(make_comp("\n".join(nodes + sw_splines), len(cases) - 1))
1251 return comp_path, "matrix_3d", [(c[0], c[1]) for c in cases]
1252
1253
1254def build_matrix_misc(assets: Dict[str, str]):
1255 """CustomTool (multi-input, getr1b, Setup1, Intermediate1, if), TimeSpeed, Switch, tool-level SourceOp instancing."""
1256 nodes = [
1257 make_loader("ColorLoader", assets["color"], post_mult=1),
1258 make_loader("FGLoader", assets["fg"], post_mult=1),
1259 """\t\tBlackBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftAlpha = Input { Value = 1, }, }, },
1260\t\t-- CustomTool 0: Setup1, Intermediate1, if, getr1b, Image2
1261\t\tOp_0 = Custom {
1262\t\t\tInputs = {
1263\t\t\t\tImage1 = Input { SourceOp = "ColorLoader", Source = "Output", },
1264\t\t\t\tImage2 = Input { SourceOp = "FGLoader", Source = "Output", },
1265\t\t\t\tNumberIn1 = Input { Value = 0.65, },
1266\t\t\t\tPointIn1 = Input { Value = { 0.45, 0.55 }, },
1267\t\t\t\tSetup1 = Input { Value = "1 - n1", },
1268\t\t\t\tIntermediate1 = Input { Value = "max(0, 1 - dist(x, y, p1x, p1y) * 2)", },
1269\t\t\t\tRedExpression = Input { Value = "if(x > p1x, getr1b(x - 0.1, y + 0.05), r2 * i1 + s1 * 0.2)", },
1270\t\t\t\tGreenExpression = Input { Value = "if(y > p1y, g1 * i1, g2 + n1 * 0.1)", },
1271\t\t\t\tBlueExpression = Input { Value = "b1 * (1 - i1) + b2 * i1", },
1272\t\t\t\tAlphaExpression = Input { Value = "1", },
1273\t\t\t},
1274\t\t},
1275\t\t-- TimeSpeed (frames 1 & 2 evaluate animated Transform at Speed=2.0, Delay=0.5)
1276\t\tXfAnim = Transform {
1277\t\t\tInputs = {
1278\t\t\t\tInput = Input { SourceOp = "ColorLoader", Source = "Output", },
1279\t\t\t\tAngle = Input { SourceOp = "TS_Angle", Source = "Value", },
1280\t\t\t\tSize = Input { Value = 0.8, },
1281\t\t\t},
1282\t\t},
1283\t\tOp_1 = TimeSpeed {
1284\t\t\tInputs = {
1285\t\t\t\tInput = Input { SourceOp = "XfAnim", Source = "Output", },
1286\t\t\t\tSpeed = Input { Value = 2.0, },
1287\t\t\t\tDelay = Input { Value = 0.5, },
1288\t\t\t},
1289\t\t},
1290\t\t-- Switch (Fusion 21 native Source=0/1 with Input0/Input1)
1291\t\tOp_2 = Switch {
1292\t\t\tInputs = {
1293\t\t\t\tSource = Input { Value = 0, },
1294\t\t\t\tInput0 = Input { SourceOp = "ColorLoader", Source = "Output", },
1295\t\t\t\tInput1 = Input { SourceOp = "FGLoader", Source = "Output", },
1296\t\t\t},
1297\t\t},
1298\t\tOp_3 = Switch {
1299\t\t\tInputs = {
1300\t\t\t\tSource = Input { Value = 1, },
1301\t\t\t\tInput0 = Input { SourceOp = "ColorLoader", Source = "Output", },
1302\t\t\t\tInput1 = Input { SourceOp = "FGLoader", Source = "Output", },
1303\t\t\t},
1304\t\t},
1305\t\t-- Tool-level SourceOp instancing
1306\t\tMasterCC = ColorCorrector {
1307\t\t\tInputs = {
1308\t\t\t\tInput = Input { SourceOp = "ColorLoader", Source = "Output", },
1309\t\t\t\tWheelHue1 = Input { Value = 0.25, },
1310\t\t\t\tWheelSaturation1 = Input { Value = 1.45, },
1311\t\t\t\tMasterRGBGain = Input { Value = 1.35, },
1312\t\t\t\tMasterRGBGamma = Input { Value = 0.85, },
1313\t\t\t},
1314\t\t},
1315\t\tOp_4 = ColorCorrector {
1316\t\t\tSourceOp = "MasterCC",
1317\t\t\tInputs = {
1318\t\t\t\tInput = Input { SourceOp = "FGLoader", Source = "Output", },
1319\t\t\t\tWheelHue1 = Input {},
1320\t\t\t\tMasterRGBGain = Input { Value = 0.8, },
1321\t\t\t},
1322\t\t},
1323\t\tOp_5 = Merge {
1324\t\t\tInputs = {
1325\t\t\t\tBackground = Input { SourceOp = "BlackBG", Source = "Output", },
1326\t\t\t\tForeground = Input { SourceOp = "Op_4", Source = "Output", },
1327\t\t\t},
1328\t\t},""",
1329 linear_spline("TS_Angle", {0: 0.0, 4: 180.0}),
1330 ]
1331 cases = [
1332 (0, "CustomTool_multi_getr1b_Setup_Inter_if", "Op_0"),
1333 (1, "TimeSpeed_f1_Speed2_Delay0.5", "Op_1"),
1334 (2, "TimeSpeed_f2_Speed2_Delay0.5", "Op_1"),
1335 (3, "Switch_Source0_Input0", "Op_2"),
1336 (4, "Switch_Source1_Input1", "Op_3"),
1337 (5, "SourceOp_Instance_ColorCorrector", "Op_5"),
1338 ]
1339 sw_nodes, sw_splines, out_op = build_switch_chain(cases, "BlackBG", "MS")
1340 nodes.extend(sw_nodes)
1341 nodes.append(make_saver(out_op, "matrix_misc"))
1342 comp_path = ensure_dirs() / "comps" / "matrix_misc.comp"
1343 comp_path.write_text(make_comp("\n".join(nodes + sw_splines), len(cases) - 1))
1344 return comp_path, "matrix_misc", [(c[0], c[1]) for c in cases]
1345
1346
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
1676MATRIX_BUILDERS = {
1677 "matrix_merge_modes": build_matrix_merge_modes,
1678 "matrix_hdr_depth": build_matrix_hdr_depth,
1679 "matrix_masks": build_matrix_masks,
1680 "matrix_color_blur": build_matrix_color_blur,
1681 "matrix_warps_shapes": build_matrix_warps_shapes,
1682 "matrix_3d": build_matrix_3d,
1683 "matrix_misc": build_matrix_misc,
1684 "matrix_paint": build_matrix_paint,
1685}
1686
1687
1688# ---------------------------------------------------------------------------
1689# Randomized DAG Fuzzer + Auto-Bisector
1690# ---------------------------------------------------------------------------
1691
1692
1693@dataclass
1694class MaskNodeSpec:
1695 name: str
1696 kind: str # EllipseMask | RectangleMask | PolylineMask
1697 params: Dict[str, Any]
1698 paint_mode: Optional[str] = None
1699 prev_mask: Optional[str] = None
1700
1701
1702@dataclass
1703class MaskChainSpec:
1704 nodes: List[MaskNodeSpec]
1705 apply_inverted: int = 0
1706 multiply_by_mask: int = 0
1707
1708 def output_name(self) -> str:
1709 return self.nodes[-1].name
1710
1711
1712@dataclass
1713class SplineParam:
1714 spline_name: str
1715 kind: str # step | linear | expr_num | expr_pt
1716 keyframes: Optional[Dict[int, float]] = None
1717 expr_inputs: Optional[Dict[str, Any]] = None
1718
1719 def eval_at(self, frame: int) -> Any:
1720 if self.kind in ("step", "linear") and self.keyframes:
1721 pts = sorted(self.keyframes.items())
1722 if frame <= pts[0][0]:
1723 return pts[0][1]
1724 if frame >= pts[-1][0]:
1725 return pts[-1][1]
1726 for (f0, v0), (f1, v1) in zip(pts, pts[1:]):
1727 if f0 <= frame <= f1:
1728 if self.kind == "step" or f1 == f0:
1729 return v0
1730 t = (frame - f0) / (f1 - f0)
1731 return round(v0 + (v1 - v0) * t, 5)
1732 return 0.5
1733
1734
1735@dataclass
1736class DagNode:
1737 name: str
1738 kind: str
1739 is_source: bool
1740 primary_port: Optional[str] = None
1741 primary_src: Optional[str] = None
1742 secondary_port: Optional[str] = None
1743 secondary_src: Optional[str] = None
1744 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
1748 mask: Optional[MaskChainSpec] = None
1749 loader_path: Optional[str] = None
1750 loader_post_mult: int = 1
1751
1752
1753def _fmt_val(v: Any, prefix: str, frame_shift: int) -> Tuple[str, List[str]]:
1754 """Formats a Fusion Input value and returns (lua_rhs, extra_aux_defs)."""
1755 if isinstance(v, SplineParam):
1756 sname = f"{prefix}{v.spline_name}"
1757 if v.kind == "step" and v.keyframes is not None:
1758 shifted = {k + frame_shift: val for k, val in v.keyframes.items()}
1759 return f'Input {{ SourceOp = "{sname}", Source = "Value", }}', [step_spline(sname, shifted)]
1760 if v.kind == "linear" and v.keyframes is not None:
1761 shifted = {k + frame_shift: val for k, val in v.keyframes.items()}
1762 return f'Input {{ SourceOp = "{sname}", Source = "Value", }}', [linear_spline(sname, shifted)]
1763 if v.kind in ("expr_num", "expr_pt") and v.expr_inputs is not None:
1764 src_port = "NumberResult" if v.kind == "expr_num" else "PointResult"
1765 lines = []
1766 for ek, ev in v.expr_inputs.items():
1767 if isinstance(ev, str):
1768 lines.append(f'{ek} = Input {{ Value = "{ev}", }},')
1769 elif isinstance(ev, tuple):
1770 lines.append(f"{ek} = Input {{ Value = {{ {ev[0]}, {ev[1]} }}, }},")
1771 else:
1772 lines.append(f"{ek} = Input {{ Value = {ev}, }},")
1773 expr_def = f"\t\t{sname} = Expression {{\n\t\t\tInputs = {{\n\t\t\t\t" + "\n\t\t\t\t".join(lines) + "\n\t\t\t},\n\t\t},"
1774 return f'Input {{ SourceOp = "{sname}", Source = "{src_port}", }}', [expr_def]
1775 if isinstance(v, tuple) and len(v) == 2 and v[0] == "FuID":
1776 return f'Input {{ Value = FuID {{ "{v[1]}" }}, }}', []
1777 if isinstance(v, tuple) and len(v) == 2:
1778 return f"Input {{ Value = {{ {v[0]}, {v[1]} }}, }}", []
1779 if isinstance(v, str):
1780 return f'Input {{ Value = "{v}", }}', []
1781 return f"Input {{ Value = {v}, }}", []
1782
1783
1784@dataclass
1785class FuzzGraph:
1786 seed: int
1787 eval_frame: int
1788 nodes: List[DagNode]
1789
1790 def clone(self) -> "FuzzGraph":
1791 import copy
1792 return copy.deepcopy(self)
1793
1794 def output_node(self) -> str:
1795 return self.nodes[-1].name
1796
1797 def active_cone_set(self, target_name: str) -> set:
1798 by_name = {n.name: n for n in self.nodes}
1799 seen = set()
1800 stack = [target_name]
1801 while stack:
1802 cur = stack.pop()
1803 if cur in seen or cur not in by_name:
1804 continue
1805 seen.add(cur)
1806 nd = by_name[cur]
1807 if nd.primary_src:
1808 stack.append(nd.primary_src)
1809 if nd.secondary_src:
1810 stack.append(nd.secondary_src)
1811 if nd.source_op:
1812 stack.append(nd.source_op)
1813 return seen
1814
1815 def prune_to(self, target_name: str) -> "FuzzGraph":
1816 g = self.clone()
1817 cone = g.active_cone_set(target_name)
1818 g.nodes = [n for n in g.nodes if n.name in cone]
1819 return g
1820
1821 def bypass_node(self, node_name: str) -> Optional["FuzzGraph"]:
1822 g = self.clone()
1823 target = next((n for n in g.nodes if n.name == node_name), None)
1824 if target is None or target.is_source or target.primary_src is None:
1825 return None
1826 if any(n.source_op == node_name for n in g.nodes if n.name != node_name):
1827 return None
1828 repl = target.primary_src
1829 for n in g.nodes:
1830 if n.primary_src == node_name:
1831 n.primary_src = repl
1832 if n.secondary_src == node_name:
1833 n.secondary_src = repl
1834 g.nodes = [n for n in g.nodes if n.name != node_name]
1835 if not g.nodes:
1836 return None
1837 return g.prune_to(g.nodes[-1].name)
1838
1839 def strip_mask(self, node_name: str) -> Optional["FuzzGraph"]:
1840 g = self.clone()
1841 for n in g.nodes:
1842 if n.name == node_name and n.mask is not None:
1843 n.mask = None
1844 return g
1845 return None
1846
1847 def flatten_splines(self) -> Optional["FuzzGraph"]:
1848 g = self.clone()
1849 changed = False
1850 for n in g.nodes:
1851 for k, v in list(n.params.items()):
1852 if isinstance(v, SplineParam):
1853 changed = True
1854 if v.kind in ("step", "linear"):
1855 n.params[k] = v.eval_at(g.eval_frame)
1856 elif v.kind == "expr_num":
1857 n.params[k] = 0.75
1858 else:
1859 n.params[k] = (0.45, 0.55)
1860 return g if changed else None
1861
1862 def summary_tools(self) -> List[Dict[str, Any]]:
1863 out = []
1864 for n in self.nodes:
1865 p_short = {}
1866 for k, v in n.params.items():
1867 if isinstance(v, SplineParam):
1868 p_short[k] = f"<{v.kind}>"
1869 elif isinstance(v, tuple) and len(v) == 2 and v[0] == "FuID":
1870 p_short[k] = v[1]
1871 else:
1872 p_short[k] = v
1873 entry: Dict[str, Any] = {"name": n.name, "kind": n.kind, "params": p_short}
1874 if n.mask is not None:
1875 entry["mask"] = [m.kind for m in n.mask.nodes]
1876 out.append(entry)
1877 return out
1878
1879 def to_lua_defs(self, prefix: str = "", frame_shift: int = 0) -> Tuple[List[str], List[str], str]:
1880 """Emits (tool_blocks, aux_splines_or_exprs, final_output_name)."""
1881 tool_blocks: List[str] = []
1882 aux_blocks: List[str] = []
1883
1884 for n in self.nodes:
1885 full_name = f"{prefix}{n.name}"
1886 if n.kind == "Loader":
1887 assert n.loader_path is not None
1888 tool_blocks.append(make_loader(full_name, n.loader_path, post_mult=n.loader_post_mult))
1889 continue
1890
1891 # Emit mask chain if present
1892 if n.mask is not None:
1893 for mi, mn in enumerate(n.mask.nodes):
1894 mname = f"{prefix}{mn.name}"
1895 in_lines = []
1896 if mn.prev_mask:
1897 in_lines.append(f'EffectMask = Input {{ SourceOp = "{prefix}{mn.prev_mask}", Source = "Mask", }},')
1898 if mn.paint_mode:
1899 in_lines.append(f'PaintMode = Input {{ Value = FuID {{ "{mn.paint_mode}" }}, }},')
1900 for pk, pv in mn.params.items():
1901 if pk == "Polyline":
1902 in_lines.append(pv)
1903 else:
1904 rhs, extra = _fmt_val(pv, prefix, frame_shift)
1905 in_lines.append(f"{pk} = {rhs},")
1906 aux_blocks.extend(extra)
1907 tool_blocks.append(
1908 f"\t\t{mname} = {mn.kind} {{\n\t\t\tInputs = {{\n\t\t\t\t"
1909 + "\n\t\t\t\t".join(in_lines)
1910 + "\n\t\t\t},\n\t\t},"
1911 )
1912
1913 in_lines = []
1914 if n.primary_port and n.primary_src:
1915 in_lines.append(f'{n.primary_port} = Input {{ SourceOp = "{prefix}{n.primary_src}", Source = "Output", }},')
1916 if n.secondary_port and n.secondary_src:
1917 in_lines.append(f'{n.secondary_port} = Input {{ SourceOp = "{prefix}{n.secondary_src}", Source = "Output", }},')
1918 if n.mask is not None:
1919 in_lines.append(f'EffectMask = Input {{ SourceOp = "{prefix}{n.mask.output_name()}", Source = "Mask", }},')
1920 if n.mask.apply_inverted:
1921 in_lines.append("ApplyMaskInverted = Input { Value = 1, },")
1922 if n.mask.multiply_by_mask:
1923 in_lines.append("MultiplyByMask = Input { Value = 1, },")
1924
1925 for pk, pv in n.params.items():
1926 rhs, extra = _fmt_val(pv, prefix, frame_shift)
1927 in_lines.append(f"{pk} = {rhs},")
1928 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))
1933
1934 src_op_line = f'\t\t\tSourceOp = "{prefix}{n.source_op}",\n' if n.source_op else ""
1935 tool_blocks.append(
1936 f"\t\t{full_name} = {n.kind} {{\n{src_op_line}\t\t\tInputs = {{\n\t\t\t\t"
1937 + "\n\t\t\t\t".join(in_lines)
1938 + "\n\t\t\t},\n\t\t},"
1939 )
1940
1941 return tool_blocks, aux_blocks, f"{prefix}{self.nodes[-1].name}"
1942
1943
1944def _gen_mask_chain(rng: random.Random, tag: str) -> MaskChainSpec:
1945 def one_mask(name: str, prev: Optional[str]) -> MaskNodeSpec:
1946 kind = rng.choice(["EllipseMask", "RectangleMask", "PolylineMask"])
1947 soft = rng.choice([0.0, 0.015, 0.04, 0.09])
1948 inv = rng.choice([0, 0, 1])
1949 lvl = round(rng.uniform(0.55, 1.0), 3)
1950 params: Dict[str, Any] = {
1951 "MaskWidth": 256,
1952 "MaskHeight": 256,
1953 "SoftEdge": soft,
1954 "Invert": inv,
1955 "Level": lvl,
1956 }
1957 if kind in ("EllipseMask", "RectangleMask"):
1958 params["Center"] = (round(rng.uniform(0.3, 0.7), 3), round(rng.uniform(0.3, 0.7), 3))
1959 params["Width"] = round(rng.uniform(0.25, 0.65), 3)
1960 params["Height"] = round(rng.uniform(0.25, 0.65), 3)
1961 params["Angle"] = round(rng.uniform(-45.0, 45.0), 1)
1962 if kind == "RectangleMask" and rng.random() < 0.4:
1963 params["CornerRadius"] = round(rng.uniform(0.1, 0.4), 2)
1964 if rng.random() < 0.25:
1965 params["Solid"] = 0
1966 params["BorderWidth"] = round(rng.uniform(0.02, 0.06), 3)
1967 else:
1968 x0 = round(rng.uniform(-0.35, -0.1), 3)
1969 y0 = round(rng.uniform(-0.35, -0.1), 3)
1970 x1 = round(rng.uniform(0.1, 0.35), 3)
1971 y1 = round(rng.uniform(-0.3, 0.05), 3)
1972 y2 = round(rng.uniform(0.15, 0.38), 3)
1973 params["Polyline"] = (
1974 f"Polyline = Input {{ Value = Polyline {{ Closed = true, Points = {{ "
1975 f"{{ Linear = true, X = {x0}, Y = {y0} }}, "
1976 f"{{ Linear = true, X = {x1}, Y = {y1} }}, "
1977 f"{{ Linear = true, X = 0.0, Y = {y2} }} }} }}, }},"
1978 )
1979 pm = (
1980 rng.choice(["Merge", "Add", "Subtract", "Minimum", "Maximum", "Average", "Multiply", "Replace", "Invert", "Ignore"])
1981 if prev
1982 else None
1983 )
1984 return MaskNodeSpec(name=name, kind=kind, params=params, paint_mode=pm, prev_mask=prev)
1985
1986 m0 = one_mask(f"{tag}_M0", None)
1987 chain = [m0]
1988 if rng.random() < 0.45:
1989 chain.append(one_mask(f"{tag}_M1", m0.name))
1990 return MaskChainSpec(
1991 nodes=chain,
1992 apply_inverted=1 if rng.random() < 0.3 else 0,
1993 multiply_by_mask=1 if rng.random() < 0.25 else 0,
1994 )
1995
1996
1997def generate_random_dag(seed: int, assets: Dict[str, str], deterministic: bool = True) -> FuzzGraph:
1998 """Csmith-style seeded generator producing valid 4-9 node Fusion DAGs."""
1999 rng = random.Random(seed)
2000 eval_frame = rng.choice([0, 1, 2])
2001 nodes: List[DagNode] = []
2002
2003 def make_source(idx: int) -> DagNode:
2004 name = f"S{idx}"
2005 src_pool = ["Loader", "Loader", "Background", "Plasma", "sRender", "DaySky"]
2006 if not deterministic:
2007 src_pool.append("FastNoise")
2008 stype = rng.choice(src_pool)
2009 if stype == "Loader":
2010 plate = rng.choice(["color", "fg", "small", "bump"])
2011 pm = rng.choice([1, 1, 0])
2012 return DagNode(name=name, kind="Loader", is_source=True, loader_path=assets[plate], loader_post_mult=pm)
2013 if stype == "Background":
2014 btype = rng.choice(["Solid", "Horizontal", "Vertical", "FourCorner"])
2015 p: Dict[str, Any] = {
2016 "Width": 256,
2017 "Height": 256,
2018 "Type": ("FuID", btype),
2019 "TopLeftRed": round(rng.uniform(0.05, 0.95), 3),
2020 "TopLeftGreen": round(rng.uniform(0.05, 0.95), 3),
2021 "TopLeftBlue": round(rng.uniform(0.05, 0.95), 3),
2022 "TopLeftAlpha": round(rng.uniform(0.4, 1.0), 3),
2023 }
2024 if btype != "Solid":
2025 p["TopRightRed"] = round(rng.uniform(0.05, 0.95), 3)
2026 p["TopRightGreen"] = round(rng.uniform(0.05, 0.95), 3)
2027 p["TopRightBlue"] = round(rng.uniform(0.05, 0.95), 3)
2028 p["BottomLeftRed"] = round(rng.uniform(0.05, 0.95), 3)
2029 p["BottomLeftGreen"] = round(rng.uniform(0.05, 0.95), 3)
2030 p["BottomLeftBlue"] = round(rng.uniform(0.05, 0.95), 3)
2031 if rng.random() < 0.35:
2032 p["Depth"] = rng.choice([1, 3, 4])
2033 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)
2112 if stype == "FastNoise":
2113 return DagNode(
2114 name=name,
2115 kind="FastNoise",
2116 is_source=True,
2117 params={
2118 "Width": 256,
2119 "Height": 256,
2120 "Detail": round(rng.uniform(0.5, 6.0), 2),
2121 "Contrast": round(rng.uniform(0.4, 2.2), 2),
2122 "Brightness": round(rng.uniform(-0.3, 0.3), 2),
2123 "XScale": round(rng.uniform(2.0, 18.0), 2),
2124 "YScale": round(rng.uniform(2.0, 18.0), 2),
2125 "Seethe": round(rng.uniform(0.0, 50.0), 2),
2126 "Discontinuous": rng.choice([0, 1]),
2127 "Color1Alpha": 1,
2128 },
2129 )
2130 return DagNode(
2131 name=name,
2132 kind="Plasma",
2133 is_source=True,
2134 params={
2135 "Width": 256,
2136 "Height": 256,
2137 "Phase": round(rng.uniform(0.0, 1.0), 3),
2138 "Scale": round(rng.uniform(0.6, 2.5), 2),
2139 },
2140 )
2141
2142 num_sources = rng.choice([1, 2, 2])
2143 for si in range(num_sources):
2144 nodes.append(make_source(si))
2145
2146 op_pool = [
2147 "Transform", "Merge", "Dissolve", "Switch",
2148 "BrightnessContrast", "ColorCorrector", "ColorGain", "HueCurves",
2149 "ChannelBoolean", "Blur", "Glow", "SoftGlow", "DirectionalBlur",
2150 "DVE", "CornerPositioner", "PerspectivePositioner", "Displace", "Vortex", "Drip", "Dent",
2151 "Paint", "ChangeDepth", "GamutConvert", "Custom",
2152 ]
2153 num_internal = rng.randint(4, 9)
2154 has_anim = rng.random() < 0.30
2155 has_inf_edges = False
2156
2157 for ni in range(num_internal):
2158 nname = f"N{ni}"
2159 kind = rng.choice(op_pool)
2160 if kind == "Drip" and has_inf_edges:
2161 kind = "Dent"
2162 # Prefer chaining mostly from recent nodes while allowing DAG forks from earlier nodes
2163 avail = [n.name for n in nodes]
2164 src_a = avail[-1] if rng.random() < 0.65 else rng.choice(avail)
2165 src_b = rng.choice(avail)
2166
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
2185 blend = round(rng.uniform(0.55, 1.0), 2) if rng.random() < 0.25 else 1.0
2186
2187 prim_port = "Input"
2188 sec_port: Optional[str] = None
2189 sec_src: Optional[str] = None
2190 params: Dict[str, Any] = {}
2191 raw_inputs: List[str] = []
2192 aux_templates: List[str] = []
2193
2194 if kind == "Transform":
2195 ang: Any = round(rng.uniform(-45.0, 45.0), 1)
2196 if has_anim and ni == 0:
2197 ang = SplineParam(f"{nname}_Ang", "linear", keyframes={0: -15.0, 2: 35.0})
2198 ed_val = rng.choice([0, 1, 2, 3])
2199 if ed_val in (1, 3):
2200 has_inf_edges = True
2201 params = {
2202 "Center": (round(rng.uniform(0.32, 0.68), 3), round(rng.uniform(0.32, 0.68), 3)),
2203 "Pivot": (round(rng.uniform(0.25, 0.75), 3), round(rng.uniform(0.25, 0.75), 3)),
2204 "Size": round(rng.uniform(0.65, 1.35), 3),
2205 "Aspect": round(rng.uniform(0.75, 1.35), 3),
2206 "Angle": ang,
2207 "Edges": ed_val,
2208 "Blend": blend,
2209 }
2210 elif kind == "Merge":
2211 prim_port = "Background"
2212 sec_port = "Foreground"
2213 sec_src = src_b
2214 m_edges = rng.choice([0, 1, 2, 3]) if rng.random() < 0.3 else 0
2215 if m_edges in (1, 3):
2216 has_inf_edges = True
2217 params = {
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"])),
2226 "Size": round(rng.uniform(0.55, 1.15), 3),
2227 "Angle": round(rng.uniform(-25.0, 25.0), 1),
2228 "Center": (round(rng.uniform(0.35, 0.65), 3), round(rng.uniform(0.35, 0.65), 3)),
2229 "Gain": round(rng.uniform(0.35, 1.25), 2),
2230 "SubtractiveAdditive": rng.choice([0.0, 0.5, 1.0]),
2231 "BurnIn": round(rng.uniform(0.0, 0.4), 2) if rng.random() < 0.35 else 0.0,
2232 "Edges": m_edges,
2233 "PerformDepthMerge": 0,
2234 "Blend": blend,
2235 }
2236 elif kind == "Switch":
2237 prim_port = "Input0"
2238 sec_port = "Input1"
2239 sec_src = src_b
2240 params = {"Source": rng.choice([0, 1])}
2241 elif kind == "Dissolve":
2242 prim_port = "Background"
2243 sec_port = "Foreground"
2244 sec_src = src_b
2245 params = {"Mix": round(rng.uniform(0.2, 0.85), 2), "Blend": blend}
2246 elif kind == "BrightnessContrast":
2247 g_val: Any = round(rng.uniform(0.5, 2.2), 2)
2248 if has_anim and ni == 1:
2249 g_val = SplineParam(
2250 f"{nname}_ExprG",
2251 "expr_num",
2252 expr_inputs={"n1": round(rng.uniform(0.6, 1.6), 2), "NumberExpression": "n1 * 0.8 + 0.35"},
2253 )
2254 params = {
2255 "Gain": g_val,
2256 "Lift": round(rng.uniform(-0.15, 0.2), 2),
2257 "Gamma": round(rng.uniform(0.6, 1.6), 2),
2258 "Contrast": round(rng.uniform(-0.25, 0.45), 2),
2259 "Brightness": round(rng.uniform(-0.2, 0.2), 2),
2260 "Saturation": round(rng.uniform(0.3, 1.6), 2),
2261 "PreDividePostMultiply": rng.choice([0, 1]),
2262 "Blend": blend,
2263 }
2264 elif kind == "ColorCorrector":
2265 params = {
2266 "WheelHue1": round(rng.uniform(-0.35, 0.35), 3),
2267 "WheelSaturation1": round(rng.uniform(0.5, 1.6), 2),
2268 "WheelTintAngle1": round(rng.uniform(-0.5, 0.5), 3),
2269 "WheelTintLength1": round(rng.uniform(0.0, 0.7), 2),
2270 "TintMode": rng.choice([0, 1, 2]),
2271 "MasterRGBGain": round(rng.uniform(0.65, 1.45), 2),
2272 "ShadowsRGBGain": round(rng.uniform(0.65, 1.35), 2),
2273 "HighlightsRGBGain": round(rng.uniform(0.65, 1.35), 2),
2274 "PreDividePostMultiply": rng.choice([0, 1]),
2275 "Blend": blend,
2276 }
2277 elif kind == "ChannelBoolean":
2278 prim_port = "Background"
2279 sec_port = "Foreground"
2280 sec_src = src_b
2281 params = {
2282 "Operation": rng.choice([0, 1, 2, 6, 8, 9, 10, 13]),
2283 "ToRed": rng.choice([0, 1, 2, 5, 10]),
2284 "ToGreen": rng.choice([0, 1, 2, 6, 10]),
2285 "ToBlue": rng.choice([0, 1, 2, 7, 10]),
2286 "ToAlpha": rng.choice([3, 8, 16]),
2287 "Blend": blend,
2288 }
2289 elif kind == "Blur":
2290 params = {
2291 "Filter": ("FuID", rng.choice(["Gaussian", "Box", "Fast Gaussian"])),
2292 "LockBlurXY": 0,
2293 "XBlurSize": round(rng.uniform(2.0, 18.0), 1),
2294 "YBlurSize": round(rng.uniform(2.0, 18.0), 1),
2295 "ClippingMode": ("FuID", rng.choice(["Frame", "None"])),
2296 "Blend": blend,
2297 }
2298 elif kind == "Glow":
2299 params = {
2300 "LockGlowSize": 0,
2301 "XGlowSize": round(rng.uniform(4.0, 20.0), 1),
2302 "YGlowSize": round(rng.uniform(2.0, 14.0), 1),
2303 "Glow": round(rng.uniform(0.4, 0.88), 2),
2304 "Blend": blend,
2305 }
2306 elif kind == "SoftGlow":
2307 params = {
2308 "LockGlowSize": 0,
2309 "XGlowSize": round(rng.uniform(4.0, 20.0), 1),
2310 "YGlowSize": round(rng.uniform(2.0, 16.0), 1),
2311 "Gain": round(rng.uniform(0.8, 2.5), 2),
2312 "Threshold": round(rng.uniform(0.1, 0.65), 2),
2313 "Blend": blend,
2314 }
2315 elif kind == "DirectionalBlur":
2316 params = {
2317 "Type": rng.choice([0, 1, 2]),
2318 "Length": round(rng.uniform(0.02, 0.12), 3),
2319 "Angle": round(rng.uniform(-90.0, 90.0), 1),
2320 "Glow": round(rng.uniform(0.0, 0.4), 2),
2321 "Blend": blend,
2322 }
2323 elif kind == "DVE":
2324 params = {
2325 "XRotation": round(rng.uniform(-35.0, 35.0), 1),
2326 "YRotation": round(rng.uniform(-35.0, 35.0), 1),
2327 "ZRotation": round(rng.uniform(-25.0, 25.0), 1),
2328 "ZMove": round(rng.uniform(0.95, 1.6), 2),
2329 "Pivot": (round(rng.uniform(0.3, 0.7), 2), round(rng.uniform(0.3, 0.7), 2)),
2330 "Center": (round(rng.uniform(0.4, 0.6), 2), round(rng.uniform(0.4, 0.6), 2)),
2331 "Blend": blend,
2332 }
2333 elif kind == "CornerPositioner":
2334 params = {
2335 "TopLeft": (round(rng.uniform(0.05, 0.28), 3), round(rng.uniform(0.72, 0.95), 3)),
2336 "TopRight": (round(rng.uniform(0.72, 0.95), 3), round(rng.uniform(0.72, 0.95), 3)),
2337 "BottomLeft": (round(rng.uniform(0.05, 0.28), 3), round(rng.uniform(0.05, 0.28), 3)),
2338 "BottomRight": (round(rng.uniform(0.72, 0.95), 3), round(rng.uniform(0.05, 0.28), 3)),
2339 "Blend": blend,
2340 }
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}
2400 elif kind == "Displace":
2401 sec_port = "Foreground"
2402 sec_src = src_b
2403 dtype = rng.choice([0, 1])
2404 if dtype == 0:
2405 params = {
2406 "Type": 0,
2407 "RefractionStrength": round(rng.uniform(0.04, 0.16), 3),
2408 "Spread": round(rng.uniform(0.0, 0.35), 2),
2409 "LightPower": round(rng.uniform(0.0, 0.6), 2),
2410 "Blend": blend,
2411 }
2412 else:
2413 params = {
2414 "Type": 1,
2415 "XChannel": rng.choice([0, 1, 2]),
2416 "YChannel": rng.choice([0, 1, 2]),
2417 "XOffset": -0.5,
2418 "YOffset": -0.5,
2419 "XRefraction": round(rng.uniform(-0.12, 0.12), 3),
2420 "YRefraction": round(rng.uniform(-0.12, 0.12), 3),
2421 "Blend": blend,
2422 }
2423 elif kind == "Vortex":
2424 params = {
2425 "Center": (round(rng.uniform(0.35, 0.65), 2), round(rng.uniform(0.35, 0.65), 2)),
2426 "Size": round(rng.uniform(0.35, 1.2), 2),
2427 "Angle": round(rng.uniform(-2.5, 2.5), 2),
2428 "Power": round(rng.uniform(0.8, 3.0), 2),
2429 "Blend": blend,
2430 }
2431 elif kind == "Drip":
2432 params = {
2433 "Center": (round(rng.uniform(0.35, 0.65), 2), round(rng.uniform(0.35, 0.65), 2)),
2434 "Strength": round(rng.uniform(0.4, 1.0), 2),
2435 "Amplitude": round(rng.uniform(0.04, 0.14), 3),
2436 "Frequency": round(rng.uniform(2.0, 7.0), 1),
2437 "Phase": round(rng.uniform(0.0, 1.0), 2),
2438 "Shape": rng.choice([0, 1]),
2439 "Blend": blend,
2440 }
2441 elif kind == "Dent":
2442 params = {
2443 "Center": (round(rng.uniform(0.35, 0.65), 2), round(rng.uniform(0.35, 0.65), 2)),
2444 "Size": round(rng.uniform(0.35, 0.85), 2),
2445 "Strength": round(rng.uniform(0.3, 0.9), 2),
2446 "Type": rng.choice([0, 1, 2, 3]),
2447 "Blend": blend,
2448 }
2449 elif kind == "ChangeDepth":
2450 params = {"Depth": rng.choice([1, 2, 3, 4])}
2451 elif kind == "GamutConvert":
2452 params = {
2453 "SourceSpace": ("FuID", rng.choice(["NoChange", "sRGB", "Rec709"])),
2454 "OutputSpace": ("FuID", rng.choice(["NoChange", "sRGB", "Rec709"])),
2455 "RemoveGamma": rng.choice([0, 1]),
2456 "AddGamma": rng.choice([0, 1]),
2457 "PreDividePostMultiply": rng.choice([0, 1]),
2458 "Blend": blend,
2459 }
2460 elif kind == "ColorGain":
2461 params = {
2462 "GainRed": round(rng.uniform(0.6, 1.5), 2),
2463 "GainGreen": round(rng.uniform(0.6, 1.5), 2),
2464 "GainBlue": round(rng.uniform(0.6, 1.5), 2),
2465 "LiftGreen": round(rng.uniform(-0.1, 0.15), 2),
2466 "GammaBlue": round(rng.uniform(0.7, 1.4), 2),
2467 "MidHue": round(rng.uniform(0.1, 0.9), 2),
2468 "PreDividePostMultiply": rng.choice([0, 1]),
2469 "Blend": blend,
2470 }
2471 elif kind == "Custom":
2472 prim_port = "Image1"
2473 sec_port = "Image2"
2474 sec_src = src_b
2475 params = {
2476 "NumberIn1": round(rng.uniform(0.3, 0.8), 2),
2477 "PointIn1": (round(rng.uniform(0.3, 0.7), 2), round(rng.uniform(0.3, 0.7), 2)),
2478 "Setup1": "1 - n1",
2479 "Intermediate1": "max(0, 1 - dist(x, y, p1x, p1y) * 1.8)",
2480 "RedExpression": "if(x > p1x, getr1b(x - 0.08, y) * i1 + r2 * s1, r1)",
2481 "GreenExpression": "g1 * (1 - i1) + g2 * i1",
2482 "BlueExpression": "b1 * n1 + b2 * (1 - n1)",
2483 "AlphaExpression": "a1",
2484 "Blend": blend,
2485 }
2486
2487 nodes.append(
2488 DagNode(
2489 name=nname,
2490 kind=kind,
2491 is_source=False,
2492 primary_port=prim_port,
2493 primary_src=src_a,
2494 secondary_port=sec_port,
2495 secondary_src=sec_src,
2496 params=params,
2497 raw_inputs=raw_inputs,
2498 aux_templates=aux_templates,
2499 mask=mask,
2500 )
2501 )
2502
2503 return FuzzGraph(seed=seed, eval_frame=eval_frame, nodes=nodes)
2504
2505
2506def write_standalone_graph_comp(graph: FuzzGraph, prefix: str) -> Path:
2507 root = ensure_dirs()
2508 tool_blocks, aux_blocks, out_op = graph.to_lua_defs(prefix="", frame_shift=0)
2509 # Normalize over BlackBG so Saver compares RGB over opaque black consistently
2510 tool_blocks.append('\t\t_BlackBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftAlpha = Input { Value = 1, }, }, },')
2511 tool_blocks.append(f'\t\t_NormOut = Merge {{ Inputs = {{ Background = Input {{ SourceOp = "_BlackBG", Source = "Output", }}, Foreground = Input {{ SourceOp = "{out_op}", Source = "Output", }}, }}, }},')
2512 tool_blocks.append(make_saver("_NormOut", prefix))
2513 comp_path = root / "comps" / f"{prefix}.comp"
2514 comp_path.write_text(make_comp("\n".join(tool_blocks + aux_blocks), graph.eval_frame, start_frame=graph.eval_frame))
2515 return comp_path
2516
2517
2518def run_multi_graph_batch(
2519 items: List[Tuple[str, FuzzGraph]],
2520 batch_prefix: str,
2521 render_gt: bool = True,
2522 timeout_sec: int = 180,
2523) -> Dict[int, Dict[str, Any]]:
2524 """Packs multiple FuzzGraphs into one multi-frame .comp using a Merge switch chain."""
2525 root = ensure_dirs()
2526 all_tools = [
2527 '\t\t_BlackBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftAlpha = Input { Value = 1, }, }, },'
2528 ]
2529 all_aux: List[str] = []
2530 cases: List[Tuple[int, str, str]] = []
2531 labels: Dict[int, str] = {}
2532
2533 for f_idx, (label, g) in enumerate(items):
2534 pfx = f"G{f_idx}_"
2535 frame_shift = f_idx - g.eval_frame
2536 tb, ab, out_op = g.to_lua_defs(prefix=pfx, frame_shift=frame_shift)
2537 all_tools.extend(tb)
2538 all_aux.extend(ab)
2539 cases.append((f_idx, label, out_op))
2540 labels[f_idx] = label
2541
2542 sw_nodes, sw_splines, final_op = build_switch_chain(cases, "_BlackBG", "FB")
2543 all_tools.extend(sw_nodes)
2544 all_aux.extend(sw_splines)
2545 all_tools.append(make_saver(final_op, batch_prefix))
2546
2547 comp_path = root / "comps" / f"{batch_prefix}.comp"
2548 comp_path.write_text(make_comp("\n".join(all_tools + all_aux), len(cases) - 1, start_frame=0))
2549 return run_comp_both(
2550 comp_path,
2551 batch_prefix,
2552 list(range(len(cases))),
2553 labels,
2554 render_gt=render_gt,
2555 timeout_sec=timeout_sec,
2556 )
2557
2558
2559def bisect_failing_graph(
2560 graph: FuzzGraph,
2561 threshold_pct: float,
2562 render_gt: bool = True,
2563 timeout_sec: int = 180,
2564) -> Dict[str, Any]:
2565 """Node-by-node graph bisection that trims downstream & upstream nodes while preserving MAE > threshold."""
2566 seed = graph.seed
2567 print(f" [bisect] seed={seed} ({len(graph.nodes)} nodes) ...", flush=True)
2568
2569 # Step 0: Verify standalone reproduction
2570 st_prefix = f"bisect_s{seed}_orig"
2571 st_comp = write_standalone_graph_comp(graph, st_prefix)
2572 st_res = run_comp_both(
2573 st_comp, st_prefix, [graph.eval_frame], {graph.eval_frame: f"seed_{seed}"}, render_gt=render_gt, timeout_sec=timeout_sec
2574 )[graph.eval_frame]
2575 orig_mae = st_res["mae_pct"]
2576 if orig_mae <= threshold_pct:
2577 return {
2578 "seed": seed,
2579 "reproduced_standalone": False,
2580 "orig_mae_pct": orig_mae,
2581 "min_mae_pct": orig_mae,
2582 "min_rmse_255": st_res["rmse_255"],
2583 "note": "batch failure did not reproduce standalone",
2584 "tools": graph.summary_tools(),
2585 }
2586
2587 # Step 1: Prefix trim (find earliest failing sink node in topological order)
2588 non_src = [n for n in graph.nodes if not n.is_source]
2589 cur = graph.clone()
2590 if len(non_src) > 1:
2591 prefix_items = [(f"prefix_{nd.name}", graph.prune_to(nd.name)) for nd in non_src]
2592 pref_res = run_multi_graph_batch(
2593 prefix_items, f"bisect_s{seed}_prefixes", render_gt=render_gt, timeout_sec=timeout_sec
2594 )
2595 for idx, nd in enumerate(non_src):
2596 if pref_res[idx]["mae_pct"] > threshold_pct:
2597 cur = graph.prune_to(nd.name)
2598 print(f" [prefix] trimmed sink to {nd.name} ({len(cur.nodes)} nodes, MAE={pref_res[idx]['mae_pct']:.2f}%)", flush=True)
2599 break
2600
2601 # Step 2: Iterative upstream node & mask removal + spline flattening
2602 for rnd in range(6):
2603 candidates: List[Tuple[str, str, FuzzGraph]] = [] # (desc, action, candidate_graph)
2604 # Try flattening splines first
2605 flat = cur.flatten_splines()
2606 if flat is not None:
2607 candidates.append(("flatten_splines", "flatten", flat))
2608 # Try stripping masks
2609 for nd in cur.nodes:
2610 if nd.mask is not None:
2611 sm = cur.strip_mask(nd.name)
2612 if sm is not None:
2613 candidates.append((f"strip_mask:{nd.name}", "mask", sm))
2614 # Try bypassing each upstream non-source node
2615 for nd in cur.nodes:
2616 if not nd.is_source and nd.name != cur.output_node():
2617 bp = cur.bypass_node(nd.name)
2618 if bp is not None:
2619 candidates.append((f"bypass:{nd.name}", "bypass", bp))
2620
2621 if not candidates:
2622 break
2623
2624 batch_items = [(desc, cg) for desc, _act, cg in candidates]
2625 cand_res = run_multi_graph_batch(
2626 batch_items, f"bisect_s{seed}_r{rnd}", render_gt=render_gt, timeout_sec=timeout_sec
2627 )
2628
2629 # Pick best failing candidate: fewest nodes, fewest masks, no splines
2630 failing: List[Tuple[Tuple[int, int, int], str, FuzzGraph, float]] = []
2631 for idx, (desc, _act, cg) in enumerate(candidates):
2632 m = cand_res[idx]
2633 if m["mae_pct"] > threshold_pct:
2634 mask_cnt = sum(1 for x in cg.nodes if x.mask is not None)
2635 spline_cnt = sum(
2636 1 for x in cg.nodes for v in x.params.values() if isinstance(v, SplineParam)
2637 )
2638 score = (len(cg.nodes), mask_cnt, spline_cnt)
2639 failing.append((score, desc, cg, m["mae_pct"]))
2640
2641 if not failing:
2642 break
2643 failing.sort(key=lambda t: t[0])
2644 _score, best_desc, best_cg, best_mae = failing[0]
2645 cur = best_cg
2646 print(f" [round {rnd}] {best_desc} -> {len(cur.nodes)} nodes (MAE={best_mae:.2f}%)", flush=True)
2647
2648 # Step 3: Standalone verification of minimal reproducer
2649 repro_prefix = f"repro_seed_{seed}"
2650 repro_comp = write_standalone_graph_comp(cur, repro_prefix)
2651 final_res = run_comp_both(
2652 repro_comp, repro_prefix, [cur.eval_frame], {cur.eval_frame: repro_prefix}, render_gt=render_gt, timeout_sec=timeout_sec
2653 )[cur.eval_frame]
2654
2655 return {
2656 "seed": seed,
2657 "reproduced_standalone": True,
2658 "orig_node_count": len(graph.nodes),
2659 "min_node_count": len(cur.nodes),
2660 "orig_mae_pct": orig_mae,
2661 "min_mae_pct": final_res["mae_pct"],
2662 "min_rmse_255": final_res["rmse_255"],
2663 "comp_path": str(repro_comp),
2664 "eval_frame": cur.eval_frame,
2665 "tools": cur.summary_tools(),
2666 }
2667
2668
2669# ---------------------------------------------------------------------------
2670# CLI & Main Entrypoint
2671# ---------------------------------------------------------------------------
2672
2673
2674def print_table(title: str, rows: List[Dict[str, Any]], threshold_pct: float) -> None:
2675 print(f"\n=== {title} ===")
2676 print(f" {'Case':<44s} | {'MAE%':>7s} | {'MAE':>6s} | {'RMSE':>6s} | {'Status'}")
2677 print(f" {'-'*44}-+-{'-'*7}-+-{'-'*6}-+-{'-'*6}-+-{'-'*18}")
2678 for r in rows:
2679 label = str(r.get("label", ""))[:44]
2680 mae_pct = r.get("mae_pct", 100.0)
2681 mae = r.get("mae_255", 255.0)
2682 rmse = r.get("rmse_255", 255.0)
2683 if r.get("error"):
2684 status = f"ERR: {str(r['error'])[:28]}"
2685 elif r.get("size_mismatch"):
2686 status = f"SIZE {r.get('dims_ours')}!={r.get('dims_gt')}"
2687 elif mae_pct > threshold_pct:
2688 status = "FAIL"
2689 else:
2690 status = "PASS"
2691 print(f" {label:<44s} | {mae_pct:6.2f}% | {mae:6.2f} | {rmse:6.2f} | {status}")
14from typing import Any, Dict, List
15
16from diff_fuzz.assets import generate_assets
17from diff_fuzz.fuzzer import generate_random_dag
18from diff_fuzz.matrix import MATRIX_BUILDERS
19from diff_fuzz.runner import (
20 bisect_failing_graph,
21 print_table,
22 run_comp_both,
23 run_multi_graph_batch,
24 write_standalone_graph_comp,
25)
269226
269327
269428def main() -> int:
scripts/diff_fuzz/__init__.py created+1
......@@ -0,0 +1 @@
1"""Fusion 21.1 vs Fission differential matrix and DAG fuzzer."""
scripts/diff_fuzz/assets.py created+604
......@@ -0,0 +1,604 @@
1"""Storage transport, PNG codec, diff metrics, synthetic plates, and Fusion .comp primitives."""
2
3import math
4import struct
5import subprocess
6import sys
7import zlib
8from pathlib import Path
9from typing import Any, Dict, List, Optional, Tuple
10
11REPO = Path(__file__).resolve().parents[2]
12RENDER_CHECK = REPO / "target/release/render-check"
13SMB_ROOT = Path("/Volumes/clover/Project/CloverCompositor/probes/diff_fuzz")
14REMOTE_ROOT = "/srv/clover/Project/CloverCompositor/probes/diff_fuzz"
15CONTAINER_ROOT = "/Volumes/clover/Project/CloverCompositor/probes/diff_fuzz"
16LOCAL_FALLBACK = Path("/tmp/fission_diff_fuzz")
17
18# ---------------------------------------------------------------------------
19# Storage / SG Transport Helpers
20# ---------------------------------------------------------------------------
21
22
23def use_smb() -> bool:
24 return Path("/Volumes/clover/Project/CloverCompositor").exists()
25
26
27def local_root() -> Path:
28 return SMB_ROOT if use_smb() else LOCAL_FALLBACK
29
30
31def ensure_dirs() -> Path:
32 root = local_root()
33 for sub in ("assets", "comps", "gt", "ours"):
34 (root / sub).mkdir(parents=True, exist_ok=True)
35 return root
36
37
38def sync_asset_to_remote(local_path: Path) -> None:
39 if not use_smb():
40 subprocess.run(
41 ["sg", "upload", str(local_path), f"{REMOTE_ROOT}/assets/{local_path.name}"],
42 check=True,
43 timeout=60,
44 )
45
46
47def ensure_render_check() -> Path:
48 if RENDER_CHECK.exists():
49 return RENDER_CHECK
50 print(f"[build] {RENDER_CHECK} missing; building render-check --release...", file=sys.stderr)
51 subprocess.run(
52 ["cargo", "build", "--release", "-p", "engine", "--bin", "render-check"],
53 cwd=str(REPO),
54 check=True,
55 timeout=600,
56 )
57 return RENDER_CHECK
58
59
60# ---------------------------------------------------------------------------
61# Pure Python Stdlib PNG Encoder / Decoder & Diff Metrics
62# ---------------------------------------------------------------------------
63
64
65def write_png_rgba(path: Path, w: int, h: int, rgba_bytes: bytes) -> None:
66 def chunk(tag: bytes, data: bytes) -> bytes:
67 return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
68
69 raw = bytearray()
70 stride = w * 4
71 for y in range(h):
72 raw.append(0)
73 raw.extend(rgba_bytes[y * stride : (y + 1) * stride])
74
75 ihdr = struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0)
76 png = (
77 b"\x89PNG\r\n\x1a\n"
78 + chunk(b"IHDR", ihdr)
79 + chunk(b"IDAT", zlib.compress(bytes(raw), level=6))
80 + chunk(b"IEND", b"")
81 )
82 path.parent.mkdir(parents=True, exist_ok=True)
83 path.write_bytes(png)
84
85
86def _paeth(a: int, b: int, c: int) -> int:
87 p = a + b - c
88 pa = abs(p - a)
89 pb = abs(p - b)
90 pc = abs(p - c)
91 if pa <= pb and pa <= pc:
92 return a
93 if pb <= pc:
94 return b
95 return c
96
97
98def read_png_rgba(path: Path) -> Tuple[int, int, bytes]:
99 data = path.read_bytes()
100 if data[:8] != b"\x89PNG\r\n\x1a\n":
101 raise ValueError(f"Not a PNG file: {path}")
102 pos = 8
103 w = h = bit_depth = color_type = interlace = 0
104 idat = bytearray()
105 while pos + 8 <= len(data):
106 length = struct.unpack(">I", data[pos : pos + 4])[0]
107 tag = data[pos + 4 : pos + 8]
108 chunk_data = data[pos + 8 : pos + 8 + length]
109 pos += 12 + length
110 if tag == b"IHDR":
111 w, h, bit_depth, color_type, _comp, _filt, interlace = struct.unpack(">IIBBBBB", chunk_data)
112 elif tag == b"IDAT":
113 idat.extend(chunk_data)
114 elif tag == b"IEND":
115 break
116
117 if interlace != 0:
118 raise ValueError(f"Interlaced PNG unsupported in pure-stdlib reader: {path}")
119 channels_map = {0: 1, 2: 3, 4: 2, 6: 4}
120 if color_type not in channels_map or bit_depth not in (8, 16):
121 raise ValueError(f"Unsupported PNG format (color={color_type}, depth={bit_depth}): {path}")
122
123 ch = channels_map[color_type]
124 bypp = ch * (bit_depth // 8)
125 row_bytes = w * bypp
126 raw = zlib.decompress(bytes(idat))
127 if len(raw) < h * (row_bytes + 1):
128 raise ValueError(f"Truncated PNG IDAT in {path}")
129
130 prev = bytearray(row_bytes)
131 out = bytearray(w * h * 4)
132 idx_in = 0
133 for y in range(h):
134 ftype = raw[idx_in]
135 idx_in += 1
136 scan = bytearray(raw[idx_in : idx_in + row_bytes])
137 idx_in += row_bytes
138 if ftype == 1:
139 for i in range(bypp, row_bytes):
140 scan[i] = (scan[i] + scan[i - bypp]) & 0xFF
141 elif ftype == 2:
142 for i in range(row_bytes):
143 scan[i] = (scan[i] + prev[i]) & 0xFF
144 elif ftype == 3:
145 for i in range(row_bytes):
146 a = scan[i - bypp] if i >= bypp else 0
147 scan[i] = (scan[i] + ((a + prev[i]) >> 1)) & 0xFF
148 elif ftype == 4:
149 for i in range(row_bytes):
150 a = scan[i - bypp] if i >= bypp else 0
151 b = prev[i]
152 c = prev[i - bypp] if i >= bypp else 0
153 scan[i] = (scan[i] + _paeth(a, b, c)) & 0xFF
154 elif ftype != 0:
155 raise ValueError(f"Unknown PNG filter {ftype} in {path}")
156 prev = scan
157
158 out_row = y * w * 4
159 if bit_depth == 8:
160 if ch == 4:
161 out[out_row : out_row + w * 4] = scan
162 elif ch == 3:
163 for x in range(w):
164 si = x * 3
165 di = out_row + x * 4
166 out[di] = scan[si]
167 out[di + 1] = scan[si + 1]
168 out[di + 2] = scan[si + 2]
169 out[di + 3] = 255
170 elif ch == 2:
171 for x in range(w):
172 si = x * 2
173 di = out_row + x * 4
174 v = scan[si]
175 out[di] = v
176 out[di + 1] = v
177 out[di + 2] = v
178 out[di + 3] = scan[si + 1]
179 else:
180 for x in range(w):
181 di = out_row + x * 4
182 v = scan[x]
183 out[di] = v
184 out[di + 1] = v
185 out[di + 2] = v
186 out[di + 3] = 255
187 else:
188 # 16-bit big endian -> 8-bit
189 for x in range(w):
190 si = x * bypp
191 di = out_row + x * 4
192 vals = [((scan[si + k * 2] << 8) | scan[si + k * 2 + 1]) >> 8 for k in range(ch)]
193 if ch == 4:
194 out[di : di + 4] = bytes(vals)
195 elif ch == 3:
196 out[di : di + 4] = bytes((vals[0], vals[1], vals[2], 255))
197 elif ch == 2:
198 out[di : di + 4] = bytes((vals[0], vals[0], vals[0], vals[1]))
199 else:
200 out[di : di + 4] = bytes((vals[0], vals[0], vals[0], 255))
201 return w, h, bytes(out)
202
203
204def compute_diff_metrics(ours_path: Path, gt_path: Path) -> Dict[str, Any]:
205 if not ours_path.exists():
206 return {"error": f"missing ours: {ours_path}", "mae_pct": 100.0, "mae_255": 255.0, "rmse_255": 255.0}
207 if not gt_path.exists():
208 return {"error": f"missing gt: {gt_path}", "mae_pct": 100.0, "mae_255": 255.0, "rmse_255": 255.0}
209
210 ow, oh, ob = read_png_rgba(ours_path)
211 gw, gh, gb = read_png_rgba(gt_path)
212 size_mismatch = (ow != gw) or (oh != gh)
213
214 # Compare over overlapping or resized if mismatched, matching render-check's RGB metric
215 cw = min(ow, gw)
216 ch = min(oh, gh)
217 if size_mismatch:
218 # Bilinear sample gt onto ow x oh just like render-check, but still flag size_mismatch!
219 sum_abs = 0
220 sum_sq = 0
221 max_diff = 0
222 for y in range(oh):
223 gy = min(gh - 1, int((y + 0.5) * gh / oh))
224 for x in range(ow):
225 gx = min(gw - 1, int((x + 0.5) * gw / ow))
226 oi = (y * ow + x) * 4
227 gi = (gy * gw + gx) * 4
228 for c in range(3):
229 d = abs(ob[oi + c] - gb[gi + c])
230 sum_abs += d
231 sum_sq += d * d
232 if d > max_diff:
233 max_diff = d
234 n = ow * oh * 3
235 else:
236 sum_abs = 0
237 sum_sq = 0
238 max_diff = 0
239 n = ow * oh * 3
240 for i in range(0, ow * oh * 4, 4):
241 d0 = abs(ob[i] - gb[i])
242 d1 = abs(ob[i + 1] - gb[i + 1])
243 d2 = abs(ob[i + 2] - gb[i + 2])
244 sum_abs += d0 + d1 + d2
245 sum_sq += d0 * d0 + d1 * d1 + d2 * d2
246 m = max(d0, d1, d2)
247 if m > max_diff:
248 max_diff = m
249
250 mae_255 = sum_abs / max(1, n)
251 rmse_255 = math.sqrt(sum_sq / max(1, n))
252 mae_pct = mae_255 / 2.55
253 return {
254 "mae_255": round(mae_255, 4),
255 "mae_pct": round(mae_pct, 4),
256 "rmse_255": round(rmse_255, 4),
257 "max_diff": max_diff,
258 "dims_ours": [ow, oh],
259 "dims_gt": [gw, gh],
260 "size_mismatch": size_mismatch,
261 }
262
263
264# ---------------------------------------------------------------------------
265# Synthetic Test Plate & Geometry Generators
266# ---------------------------------------------------------------------------
267
268
269def _hsv_to_rgb(h: float, s: float, v: float) -> Tuple[float, float, float]:
270 h = (h % 1.0) * 6.0
271 i = int(h)
272 f = h - i
273 p = v * (1.0 - s)
274 q = v * (1.0 - s * f)
275 t = v * (1.0 - s * (1.0 - f))
276 return [(v, t, p), (q, v, p), (p, v, t), (p, q, v), (t, p, v), (v, p, q)][i % 6]
277
278
279def _clamp8(v: float) -> int:
280 return max(0, min(255, int(round(v * 255.0))))
281
282
283def generate_assets() -> Dict[str, str]:
284 """Generates all synthetic test plates & cube.obj under probes/diff_fuzz/assets/."""
285 root = ensure_dirs()
286 assets_dir = root / "assets"
287
288 # 1. plate_color.png (256x256): HSV + gray/primary ramps + geometric edges + alpha gradient
289 p_color = assets_dir / "plate_color.png"
290 w, h = 256, 256
291 buf = bytearray(w * h * 4)
292 for y in range(h):
293 ny = y / (h - 1)
294 for x in range(w):
295 nx = x / (w - 1)
296 r, g, b, a = 0.0, 0.0, 0.0, 1.0
297 if ny < 0.40:
298 r, g, b = _hsv_to_rgb(nx, ny / 0.40, 0.90)
299 elif ny < 0.60:
300 if nx < 0.5:
301 g0 = nx * 2.0
302 r, g, b = g0, g0, g0
303 else:
304 bar = int((nx - 0.5) * 12.0) % 6
305 r, g, b = [
306 (0.95, 0.15, 0.15),
307 (0.15, 0.90, 0.20),
308 (0.15, 0.30, 0.95),
309 (0.95, 0.90, 0.15),
310 (0.15, 0.90, 0.95),
311 (0.95, 0.15, 0.90),
312 ][bar]
313 elif ny < 0.82:
314 # Sharp geometric edges (rotated diamond + circle + stripes)
315 r, g, b = 0.12, 0.14, 0.18
316 dx, dy = abs(nx - 0.30), abs(ny - 0.71)
317 if dx + dy < 0.11:
318 r, g, b = 0.96, 0.52, 0.12
319 if math.hypot(nx - 0.72, ny - 0.71) < 0.09:
320 r, g, b = 0.20, 0.85, 0.95
321 if ((x + y) // 6) % 2 == 0 and 0.45 < nx < 0.58:
322 r, g, b = 0.92, 0.92, 0.92
323 else:
324 r, g, b = _hsv_to_rgb(nx, 0.85, 0.92)
325 a = max(0.0, min(1.0, 1.0 - (ny - 0.82) / 0.18))
326 idx = (y * w + x) * 4
327 buf[idx] = _clamp8(r)
328 buf[idx + 1] = _clamp8(g)
329 buf[idx + 2] = _clamp8(b)
330 buf[idx + 3] = _clamp8(a)
331 write_png_rgba(p_color, w, h, bytes(buf))
332 sync_asset_to_remote(p_color)
333
334 # 2. plate_fg.png (256x256): semi-transparent shapes, fine diagonal stripes, soft radial falloff
335 p_fg = assets_dir / "plate_fg.png"
336 buf = bytearray(w * h * 4)
337 for y in range(h):
338 ny = y / (h - 1)
339 for x in range(w):
340 nx = x / (w - 1)
341 r, g, b, a = 0.0, 0.0, 0.0, 0.0
342 # Soft radial falloff orb (top-left)
343 d_orb = math.hypot(nx - 0.28, ny - 0.28)
344 if d_orb < 0.22:
345 t = 1.0 - d_orb / 0.22
346 r, g, b = 0.95 * t + 0.2 * (1.0 - t), 0.35 + 0.55 * math.sin(d_orb * 40.0) ** 2, 0.90 * (1.0 - 0.4 * t)
347 a = t * t * (3.0 - 2.0 * t)
348 # Fine diagonal stripes block (top-right)
349 if 0.54 <= nx <= 0.90 and 0.10 <= ny <= 0.44:
350 stripe = ((x - y) // 2) % 2 == 0
351 r, g, b = (0.95, 0.85, 0.15) if stripe else (0.15, 0.22, 0.55)
352 a = 0.85 if stripe else 0.55
353 # Overlapping semi-transparent discs (bottom-left)
354 d1 = math.hypot(nx - 0.24, ny - 0.72) < 0.14
355 d2 = math.hypot(nx - 0.36, ny - 0.72) < 0.14
356 if d1 and d2:
357 r, g, b, a = 0.85, 0.55, 0.95, 0.75
358 elif d1:
359 r, g, b, a = 0.10, 0.85, 0.90, 0.55
360 elif d2:
361 r, g, b, a = 0.95, 0.20, 0.65, 0.55
362 # Asymmetric crisp L-marker (bottom-right)
363 if (0.62 <= nx <= 0.68 and 0.58 <= ny <= 0.86) or (0.62 <= nx <= 0.86 and 0.80 <= ny <= 0.86):
364 r, g, b, a = 0.98, 0.98, 0.98, 1.0
365 idx = (y * w + x) * 4
366 buf[idx] = _clamp8(r)
367 buf[idx + 1] = _clamp8(g)
368 buf[idx + 2] = _clamp8(b)
369 buf[idx + 3] = _clamp8(a)
370 write_png_rgba(p_fg, w, h, bytes(buf))
371 sync_asset_to_remote(p_fg)
372
373 # 3. plate_small.png (160x120): mismatched resolution test plate
374 p_small = assets_dir / "plate_small.png"
375 sw, sh = 160, 120
376 sbuf = bytearray(sw * sh * 4)
377 for y in range(sh):
378 ny = y / (sh - 1)
379 for x in range(sw):
380 nx = x / (sw - 1)
381 r, g, b, a = 0.18, 0.22, 0.30, 0.95
382 if x < 5 or x >= sw - 5 or y < 5 or y >= sh - 5:
383 if y < 5:
384 r, g, b, a = 0.95, 0.20, 0.20, 1.0
385 elif y >= sh - 5:
386 r, g, b, a = 0.20, 0.90, 0.25, 1.0
387 elif x < 5:
388 r, g, b, a = 0.20, 0.40, 0.95, 1.0
389 else:
390 r, g, b, a = 0.95, 0.85, 0.15, 1.0
391 else:
392 if ((x // 10) + (y // 10)) % 2 == 0:
393 r, g, b = 0.72, 0.76, 0.82
394 if abs(nx - ny) < 0.04 or abs(nx - (1.0 - ny)) < 0.04:
395 r, g, b = 0.95, 0.35, 0.10
396 d_c = math.hypot(nx - 0.5, ny - 0.5)
397 if d_c < 0.22:
398 a = max(0.2, 1.0 - (0.22 - d_c) / 0.22 * 0.7)
399 idx = (y * sw + x) * 4
400 sbuf[idx] = _clamp8(r)
401 sbuf[idx + 1] = _clamp8(g)
402 sbuf[idx + 2] = _clamp8(b)
403 sbuf[idx + 3] = _clamp8(a)
404 write_png_rgba(p_small, sw, sh, bytes(sbuf))
405 sync_asset_to_remote(p_small)
406
407 # 4. plate_bump.png (256x256): grayscale heightmap / bump test texture
408 p_bump = assets_dir / "plate_bump.png"
409 bbuf = bytearray(w * h * 4)
410 for y in range(h):
411 ny = y / (h - 1)
412 for x in range(w):
413 nx = x / (w - 1)
414 d = math.hypot(nx - 0.5, ny - 0.5)
415 dome = max(0.0, 1.0 - (d / 0.38) ** 2) ** 0.5 if d < 0.38 else 0.0
416 ripple = 0.5 + 0.5 * math.sin(d * 48.0)
417 step = 0.25 * math.floor(nx * 5.0) / 4.0
418 val = max(0.0, min(1.0, 0.50 * dome + 0.30 * ripple + 0.20 * step))
419 v8 = _clamp8(val)
420 idx = (y * w + x) * 4
421 bbuf[idx] = v8
422 bbuf[idx + 1] = v8
423 bbuf[idx + 2] = v8
424 bbuf[idx + 3] = 255
425 write_png_rgba(p_bump, w, h, bytes(bbuf))
426 sync_asset_to_remote(p_bump)
427
428 # 5. cube.obj: small valid triangulated OBJ mesh
429 p_obj = assets_dir / "cube.obj"
430 obj_text = """# Synthetic unit cube for SurfaceFBXMesh differential testing
431o UnitCube
432v -0.5 -0.5 0.5
433v 0.5 -0.5 0.5
434v 0.5 0.5 0.5
435v -0.5 0.5 0.5
436v -0.5 -0.5 -0.5
437v 0.5 -0.5 -0.5
438v 0.5 0.5 -0.5
439v -0.5 0.5 -0.5
440vt 0.0 0.0
441vt 1.0 0.0
442vt 1.0 1.0
443vt 0.0 1.0
444vn 0.0 0.0 1.0
445vn 0.0 0.0 -1.0
446vn 1.0 0.0 0.0
447vn -1.0 0.0 0.0
448vn 0.0 1.0 0.0
449vn 0.0 -1.0 0.0
450f 1/1/1 2/2/1 3/3/1
451f 1/1/1 3/3/1 4/4/1
452f 6/1/2 5/2/2 8/3/2
453f 6/1/2 8/3/2 7/4/2
454f 2/1/3 6/2/3 7/3/3
455f 2/1/3 7/3/3 3/4/3
456f 5/1/4 1/2/4 4/3/4
457f 5/1/4 4/3/4 8/4/4
458f 4/1/5 3/2/5 7/3/5
459f 4/1/5 7/3/5 8/4/5
460f 5/1/6 6/2/6 2/3/6
461f 5/1/6 2/3/6 1/4/6
462"""
463 p_obj.write_text(obj_text)
464 sync_asset_to_remote(p_obj)
465
466 return {
467 "color": f"{CONTAINER_ROOT}/assets/plate_color.png",
468 "fg": f"{CONTAINER_ROOT}/assets/plate_fg.png",
469 "small": f"{CONTAINER_ROOT}/assets/plate_small.png",
470 "bump": f"{CONTAINER_ROOT}/assets/plate_bump.png",
471 "cube_obj": f"{CONTAINER_ROOT}/assets/cube.obj",
472 }
473
474
475# ---------------------------------------------------------------------------
476# Fusion .comp Serialization Primitives
477# ---------------------------------------------------------------------------
478
479
480def step_spline(name: str, frame_values: Dict[int, float]) -> str:
481 kfs = [f"\t\t\t\t[{f}] = {{ {v!r}, Flags = {{ StepIn = true }} }}," for f, v in sorted(frame_values.items())]
482 return f"\t\t{name} = BezierSpline {{\n\t\t\tKeyFrames = {{\n" + "\n".join(kfs) + "\n\t\t\t},\n\t\t},"
483
484
485def linear_spline(name: str, frame_values: Dict[int, float]) -> str:
486 kfs = [f"\t\t\t\t[{f}] = {{ {v!r}, Flags = {{ Linear = true }} }}," for f, v in sorted(frame_values.items())]
487 return f"\t\t{name} = BezierSpline {{\n\t\t\tKeyFrames = {{\n" + "\n".join(kfs) + "\n\t\t\t},\n\t\t},"
488
489
490def lut_bezier(name: str, pts: List[Tuple[float, float]]) -> str:
491 kfs = "\n".join(f"\t\t\t\t\t[{x}] = {{ {y} }}," for x, y in pts)
492 return (
493 f"\t\t{name} = LUTBezier {{\n"
494 f"\t\t\tSmoothEndsTransition = true,\n"
495 f"\t\t\tKeyColorSplines = {{\n"
496 f"\t\t\t\t[0] = {{\n{kfs}\n\t\t\t\t}}\n"
497 f"\t\t\t}},\n\t\t}},"
498 )
499
500
501def make_loader(name: str, container_path: str, post_mult: int = 1, depth: Optional[int] = None) -> str:
502 extra = f"\n\t\t\t\tDepth = Input {{ Value = {depth}, }}," if depth is not None else ""
503 return f"""\t\t{name} = Loader {{
504\t\t\tClips = {{
505\t\t\t\tClip {{
506\t\t\t\t\tID = "Clip1",
507\t\t\t\t\tFilename = "{container_path}",
508\t\t\t\t\tFormatID = "PNGFormat",
509\t\t\t\t\tLength = 1,
510\t\t\t\t\tLengthSetManually = true,
511\t\t\t\t\tTrimIn = 0,
512\t\t\t\t\tTrimOut = 0,
513\t\t\t\t\tExtendFirst = 0,
514\t\t\t\t\tExtendLast = 0,
515\t\t\t\t\tLoop = 1,
516\t\t\t\t\tStartFrame = -1,
517\t\t\t\t\tGlobalStart = 0,
518\t\t\t\t\tGlobalEnd = 1000,
519\t\t\t\t}},
520\t\t\t}},
521\t\t\tInputs = {{
522\t\t\t\t["Clip1.PNGFormat.PostMultiply"] = Input {{ Value = {post_mult}, }},{extra}
523\t\t\t}},
524\t\t}},"""
525
526
527def make_saver(src_op: str, prefix: str) -> str:
528 return f"""\t\tSaver1 = Saver {{
529\t\t\tInputs = {{
530\t\t\t\tClip = Input {{
531\t\t\t\t\tValue = Clip {{
532\t\t\t\t\t\tFilename = "{CONTAINER_ROOT}/gt/{prefix}_0000.png",
533\t\t\t\t\t\tFormatID = "PNGFormat",
534\t\t\t\t\t\tLength = 0,
535\t\t\t\t\t\tSaving = true,
536\t\t\t\t\t\tTrimIn = 0,
537\t\t\t\t\t\tExtendFirst = 0,
538\t\t\t\t\t\tExtendLast = 0,
539\t\t\t\t\t\tLoop = 1,
540\t\t\t\t\t\tAspectMode = 0,
541\t\t\t\t\t\tDepth = 0,
542\t\t\t\t\t\tGlobalStart = -2000000000,
543\t\t\t\t\t\tGlobalEnd = 0,
544\t\t\t\t\t}},
545\t\t\t\t}},
546\t\t\t\tOutputFormat = Input {{ Value = FuID {{ "PNGFormat" }}, }},
547\t\t\t\tInput = Input {{ SourceOp = "{src_op}", Source = "Output", }},
548\t\t\t}},
549\t\t}},"""
550
551
552def make_comp(tools_body: str, end_frame: int, w: int = 256, h: int = 256, start_frame: int = 0) -> str:
553 return f"""Composition {{
554\tCurrentTime = {start_frame},
555\tRenderRange = {{ {start_frame}, {end_frame} }},
556\tGlobalRange = {{ {start_frame}, {end_frame} }},
557\tCurrentID = 500,
558\tHiQ = true,
559\tPlaybackUpdateMode = 0,
560\tVersion = "Fusion Studio 21.1 build 23",
561\tTools = ordered() {{
562{tools_body}
563\t}},
564\tPrefs = {{
565\t\tComp = {{
566\t\t\tFrameFormat = {{
567\t\t\t\tWidth = {w},
568\t\t\t\tHeight = {h},
569\t\t\t\tRate = 24,
570\t\t\t}},
571\t\t}},
572\t}},
573}}
574"""
575
576
577def build_switch_chain(
578 cases: List[Tuple[int, str, str]],
579 bg_name: str,
580 prefix_tag: str,
581) -> Tuple[List[str], List[str], str]:
582 """Chains Merge switches so frame f outputs op_name for case (f, label, op_name)."""
583 nodes: List[str] = []
584 splines: List[str] = []
585 prev = bg_name
586 frames = [c[0] for c in cases]
587 for f, _label, op_name in cases:
588 bl = {fr: (1.0 if fr == f else 0.0) for fr in frames}
589 sname = f"{prefix_tag}_{f}_Blend"
590 splines.append(step_spline(sname, bl))
591 sw_name = f"{prefix_tag}_Sw_{f}"
592 nodes.append(
593 f"""\t\t{sw_name} = Merge {{
594\t\t\tInputs = {{
595\t\t\t\tBlend = Input {{ SourceOp = "{sname}", Source = "Value", }},
596\t\t\t\tBackground = Input {{ SourceOp = "{prev}", Source = "Output", }},
597\t\t\t\tForeground = Input {{ SourceOp = "{op_name}", Source = "Output", }},
598\t\t\t}},
599\t\t}},"""
600 )
601 prev = sw_name
602 return nodes, splines, prev
603
604
scripts/diff_fuzz/fuzzer.py created+821
......@@ -0,0 +1,821 @@
1"""Seeded randomized DAG fuzzer: graph model, Lua emission, and random graph generation."""
2
3import random
4from dataclasses import dataclass, field
5from typing import Any, Dict, List, Optional, Tuple
6
7from .assets import linear_spline, lut_bezier, make_loader, step_spline
8
9@dataclass
10class MaskNodeSpec:
11 name: str
12 kind: str # EllipseMask | RectangleMask | PolylineMask
13 params: Dict[str, Any]
14 paint_mode: Optional[str] = None
15 prev_mask: Optional[str] = None
16
17
18@dataclass
19class MaskChainSpec:
20 nodes: List[MaskNodeSpec]
21 apply_inverted: int = 0
22 multiply_by_mask: int = 0
23
24 def output_name(self) -> str:
25 return self.nodes[-1].name
26
27
28@dataclass
29class SplineParam:
30 spline_name: str
31 kind: str # step | linear | expr_num | expr_pt
32 keyframes: Optional[Dict[int, float]] = None
33 expr_inputs: Optional[Dict[str, Any]] = None
34
35 def eval_at(self, frame: int) -> Any:
36 if self.kind in ("step", "linear") and self.keyframes:
37 pts = sorted(self.keyframes.items())
38 if frame <= pts[0][0]:
39 return pts[0][1]
40 if frame >= pts[-1][0]:
41 return pts[-1][1]
42 for (f0, v0), (f1, v1) in zip(pts, pts[1:]):
43 if f0 <= frame <= f1:
44 if self.kind == "step" or f1 == f0:
45 return v0
46 t = (frame - f0) / (f1 - f0)
47 return round(v0 + (v1 - v0) * t, 5)
48 return 0.5
49
50
51@dataclass
52class DagNode:
53 name: str
54 kind: str
55 is_source: bool
56 primary_port: Optional[str] = None
57 primary_src: Optional[str] = None
58 secondary_port: Optional[str] = None
59 secondary_src: Optional[str] = None
60 params: Dict[str, Any] = field(default_factory=dict)
61 raw_inputs: List[str] = field(default_factory=list)
62 aux_templates: List[str] = field(default_factory=list)
63 source_op: Optional[str] = None
64 mask: Optional[MaskChainSpec] = None
65 loader_path: Optional[str] = None
66 loader_post_mult: int = 1
67
68
69def _fmt_val(v: Any, prefix: str, frame_shift: int) -> Tuple[str, List[str]]:
70 """Formats a Fusion Input value and returns (lua_rhs, extra_aux_defs)."""
71 if isinstance(v, SplineParam):
72 sname = f"{prefix}{v.spline_name}"
73 if v.kind == "step" and v.keyframes is not None:
74 shifted = {k + frame_shift: val for k, val in v.keyframes.items()}
75 return f'Input {{ SourceOp = "{sname}", Source = "Value", }}', [step_spline(sname, shifted)]
76 if v.kind == "linear" and v.keyframes is not None:
77 shifted = {k + frame_shift: val for k, val in v.keyframes.items()}
78 return f'Input {{ SourceOp = "{sname}", Source = "Value", }}', [linear_spline(sname, shifted)]
79 if v.kind in ("expr_num", "expr_pt") and v.expr_inputs is not None:
80 src_port = "NumberResult" if v.kind == "expr_num" else "PointResult"
81 lines = []
82 for ek, ev in v.expr_inputs.items():
83 if isinstance(ev, str):
84 lines.append(f'{ek} = Input {{ Value = "{ev}", }},')
85 elif isinstance(ev, tuple):
86 lines.append(f"{ek} = Input {{ Value = {{ {ev[0]}, {ev[1]} }}, }},")
87 else:
88 lines.append(f"{ek} = Input {{ Value = {ev}, }},")
89 expr_def = f"\t\t{sname} = Expression {{\n\t\t\tInputs = {{\n\t\t\t\t" + "\n\t\t\t\t".join(lines) + "\n\t\t\t},\n\t\t},"
90 return f'Input {{ SourceOp = "{sname}", Source = "{src_port}", }}', [expr_def]
91 if isinstance(v, tuple) and len(v) == 2 and v[0] == "FuID":
92 return f'Input {{ Value = FuID {{ "{v[1]}" }}, }}', []
93 if isinstance(v, tuple) and len(v) == 2:
94 return f"Input {{ Value = {{ {v[0]}, {v[1]} }}, }}", []
95 if isinstance(v, str):
96 return f'Input {{ Value = "{v}", }}', []
97 return f"Input {{ Value = {v}, }}", []
98
99
100@dataclass
101class FuzzGraph:
102 seed: int
103 eval_frame: int
104 nodes: List[DagNode]
105
106 def clone(self) -> "FuzzGraph":
107 import copy
108 return copy.deepcopy(self)
109
110 def output_node(self) -> str:
111 return self.nodes[-1].name
112
113 def active_cone_set(self, target_name: str) -> set:
114 by_name = {n.name: n for n in self.nodes}
115 seen = set()
116 stack = [target_name]
117 while stack:
118 cur = stack.pop()
119 if cur in seen or cur not in by_name:
120 continue
121 seen.add(cur)
122 nd = by_name[cur]
123 if nd.primary_src:
124 stack.append(nd.primary_src)
125 if nd.secondary_src:
126 stack.append(nd.secondary_src)
127 if nd.source_op:
128 stack.append(nd.source_op)
129 return seen
130
131 def prune_to(self, target_name: str) -> "FuzzGraph":
132 g = self.clone()
133 cone = g.active_cone_set(target_name)
134 g.nodes = [n for n in g.nodes if n.name in cone]
135 return g
136
137 def bypass_node(self, node_name: str) -> Optional["FuzzGraph"]:
138 g = self.clone()
139 target = next((n for n in g.nodes if n.name == node_name), None)
140 if target is None or target.is_source or target.primary_src is None:
141 return None
142 if any(n.source_op == node_name for n in g.nodes if n.name != node_name):
143 return None
144 repl = target.primary_src
145 for n in g.nodes:
146 if n.primary_src == node_name:
147 n.primary_src = repl
148 if n.secondary_src == node_name:
149 n.secondary_src = repl
150 g.nodes = [n for n in g.nodes if n.name != node_name]
151 if not g.nodes:
152 return None
153 return g.prune_to(g.nodes[-1].name)
154
155 def strip_mask(self, node_name: str) -> Optional["FuzzGraph"]:
156 g = self.clone()
157 for n in g.nodes:
158 if n.name == node_name and n.mask is not None:
159 n.mask = None
160 return g
161 return None
162
163 def flatten_splines(self) -> Optional["FuzzGraph"]:
164 g = self.clone()
165 changed = False
166 for n in g.nodes:
167 for k, v in list(n.params.items()):
168 if isinstance(v, SplineParam):
169 changed = True
170 if v.kind in ("step", "linear"):
171 n.params[k] = v.eval_at(g.eval_frame)
172 elif v.kind == "expr_num":
173 n.params[k] = 0.75
174 else:
175 n.params[k] = (0.45, 0.55)
176 return g if changed else None
177
178 def summary_tools(self) -> List[Dict[str, Any]]:
179 out = []
180 for n in self.nodes:
181 p_short = {}
182 for k, v in n.params.items():
183 if isinstance(v, SplineParam):
184 p_short[k] = f"<{v.kind}>"
185 elif isinstance(v, tuple) and len(v) == 2 and v[0] == "FuID":
186 p_short[k] = v[1]
187 else:
188 p_short[k] = v
189 entry: Dict[str, Any] = {"name": n.name, "kind": n.kind, "params": p_short}
190 if n.mask is not None:
191 entry["mask"] = [m.kind for m in n.mask.nodes]
192 out.append(entry)
193 return out
194
195 def to_lua_defs(self, prefix: str = "", frame_shift: int = 0) -> Tuple[List[str], List[str], str]:
196 """Emits (tool_blocks, aux_splines_or_exprs, final_output_name)."""
197 tool_blocks: List[str] = []
198 aux_blocks: List[str] = []
199
200 for n in self.nodes:
201 full_name = f"{prefix}{n.name}"
202 if n.kind == "Loader":
203 assert n.loader_path is not None
204 tool_blocks.append(make_loader(full_name, n.loader_path, post_mult=n.loader_post_mult))
205 continue
206
207 # Emit mask chain if present
208 if n.mask is not None:
209 for mi, mn in enumerate(n.mask.nodes):
210 mname = f"{prefix}{mn.name}"
211 in_lines = []
212 if mn.prev_mask:
213 in_lines.append(f'EffectMask = Input {{ SourceOp = "{prefix}{mn.prev_mask}", Source = "Mask", }},')
214 if mn.paint_mode:
215 in_lines.append(f'PaintMode = Input {{ Value = FuID {{ "{mn.paint_mode}" }}, }},')
216 for pk, pv in mn.params.items():
217 if pk == "Polyline":
218 in_lines.append(pv)
219 else:
220 rhs, extra = _fmt_val(pv, prefix, frame_shift)
221 in_lines.append(f"{pk} = {rhs},")
222 aux_blocks.extend(extra)
223 tool_blocks.append(
224 f"\t\t{mname} = {mn.kind} {{\n\t\t\tInputs = {{\n\t\t\t\t"
225 + "\n\t\t\t\t".join(in_lines)
226 + "\n\t\t\t},\n\t\t},"
227 )
228
229 in_lines = []
230 if n.primary_port and n.primary_src:
231 in_lines.append(f'{n.primary_port} = Input {{ SourceOp = "{prefix}{n.primary_src}", Source = "Output", }},')
232 if n.secondary_port and n.secondary_src:
233 in_lines.append(f'{n.secondary_port} = Input {{ SourceOp = "{prefix}{n.secondary_src}", Source = "Output", }},')
234 if n.mask is not None:
235 in_lines.append(f'EffectMask = Input {{ SourceOp = "{prefix}{n.mask.output_name()}", Source = "Mask", }},')
236 if n.mask.apply_inverted:
237 in_lines.append("ApplyMaskInverted = Input { Value = 1, },")
238 if n.mask.multiply_by_mask:
239 in_lines.append("MultiplyByMask = Input { Value = 1, },")
240
241 for pk, pv in n.params.items():
242 rhs, extra = _fmt_val(pv, prefix, frame_shift)
243 in_lines.append(f"{pk} = {rhs},")
244 aux_blocks.extend(extra)
245 for ri in n.raw_inputs:
246 in_lines.append(ri.replace("{pfx}", prefix))
247 for tmpl in n.aux_templates:
248 aux_blocks.append(tmpl.replace("{pfx}", prefix))
249
250 src_op_line = f'\t\t\tSourceOp = "{prefix}{n.source_op}",\n' if n.source_op else ""
251 tool_blocks.append(
252 f"\t\t{full_name} = {n.kind} {{\n{src_op_line}\t\t\tInputs = {{\n\t\t\t\t"
253 + "\n\t\t\t\t".join(in_lines)
254 + "\n\t\t\t},\n\t\t},"
255 )
256
257 return tool_blocks, aux_blocks, f"{prefix}{self.nodes[-1].name}"
258
259
260def _gen_mask_chain(rng: random.Random, tag: str) -> MaskChainSpec:
261 def one_mask(name: str, prev: Optional[str]) -> MaskNodeSpec:
262 kind = rng.choice(["EllipseMask", "RectangleMask", "PolylineMask"])
263 soft = rng.choice([0.0, 0.015, 0.04, 0.09])
264 inv = rng.choice([0, 0, 1])
265 lvl = round(rng.uniform(0.55, 1.0), 3)
266 params: Dict[str, Any] = {
267 "MaskWidth": 256,
268 "MaskHeight": 256,
269 "SoftEdge": soft,
270 "Invert": inv,
271 "Level": lvl,
272 }
273 if kind in ("EllipseMask", "RectangleMask"):
274 params["Center"] = (round(rng.uniform(0.3, 0.7), 3), round(rng.uniform(0.3, 0.7), 3))
275 params["Width"] = round(rng.uniform(0.25, 0.65), 3)
276 params["Height"] = round(rng.uniform(0.25, 0.65), 3)
277 params["Angle"] = round(rng.uniform(-45.0, 45.0), 1)
278 if kind == "RectangleMask" and rng.random() < 0.4:
279 params["CornerRadius"] = round(rng.uniform(0.1, 0.4), 2)
280 if rng.random() < 0.25:
281 params["Solid"] = 0
282 params["BorderWidth"] = round(rng.uniform(0.02, 0.06), 3)
283 else:
284 x0 = round(rng.uniform(-0.35, -0.1), 3)
285 y0 = round(rng.uniform(-0.35, -0.1), 3)
286 x1 = round(rng.uniform(0.1, 0.35), 3)
287 y1 = round(rng.uniform(-0.3, 0.05), 3)
288 y2 = round(rng.uniform(0.15, 0.38), 3)
289 params["Polyline"] = (
290 f"Polyline = Input {{ Value = Polyline {{ Closed = true, Points = {{ "
291 f"{{ Linear = true, X = {x0}, Y = {y0} }}, "
292 f"{{ Linear = true, X = {x1}, Y = {y1} }}, "
293 f"{{ Linear = true, X = 0.0, Y = {y2} }} }} }}, }},"
294 )
295 pm = (
296 rng.choice(["Merge", "Add", "Subtract", "Minimum", "Maximum", "Average", "Multiply", "Replace", "Invert", "Ignore"])
297 if prev
298 else None
299 )
300 return MaskNodeSpec(name=name, kind=kind, params=params, paint_mode=pm, prev_mask=prev)
301
302 m0 = one_mask(f"{tag}_M0", None)
303 chain = [m0]
304 if rng.random() < 0.45:
305 chain.append(one_mask(f"{tag}_M1", m0.name))
306 return MaskChainSpec(
307 nodes=chain,
308 apply_inverted=1 if rng.random() < 0.3 else 0,
309 multiply_by_mask=1 if rng.random() < 0.25 else 0,
310 )
311
312
313def generate_random_dag(seed: int, assets: Dict[str, str], deterministic: bool = True) -> FuzzGraph:
314 """Csmith-style seeded generator producing valid 4-9 node Fusion DAGs."""
315 rng = random.Random(seed)
316 eval_frame = rng.choice([0, 1, 2])
317 nodes: List[DagNode] = []
318
319 def make_source(idx: int) -> DagNode:
320 name = f"S{idx}"
321 src_pool = ["Loader", "Loader", "Background", "Plasma", "sRender", "DaySky"]
322 if not deterministic:
323 src_pool.append("FastNoise")
324 stype = rng.choice(src_pool)
325 if stype == "Loader":
326 plate = rng.choice(["color", "fg", "small", "bump"])
327 pm = rng.choice([1, 1, 0])
328 return DagNode(name=name, kind="Loader", is_source=True, loader_path=assets[plate], loader_post_mult=pm)
329 if stype == "Background":
330 btype = rng.choice(["Solid", "Horizontal", "Vertical", "Corner"])
331 p: Dict[str, Any] = {
332 "Width": 256,
333 "Height": 256,
334 "Type": ("FuID", btype),
335 "TopLeftRed": round(rng.uniform(0.05, 0.95), 3),
336 "TopLeftGreen": round(rng.uniform(0.05, 0.95), 3),
337 "TopLeftBlue": round(rng.uniform(0.05, 0.95), 3),
338 "TopLeftAlpha": round(rng.uniform(0.4, 1.0), 3),
339 }
340 if btype != "Solid":
341 p["TopRightRed"] = round(rng.uniform(0.05, 0.95), 3)
342 p["TopRightGreen"] = round(rng.uniform(0.05, 0.95), 3)
343 p["TopRightBlue"] = round(rng.uniform(0.05, 0.95), 3)
344 p["BottomLeftRed"] = round(rng.uniform(0.05, 0.95), 3)
345 p["BottomLeftGreen"] = round(rng.uniform(0.05, 0.95), 3)
346 p["BottomLeftBlue"] = round(rng.uniform(0.05, 0.95), 3)
347 if rng.random() < 0.35:
348 p["Depth"] = rng.choice([1, 3, 4])
349 return DagNode(name=name, kind="Background", is_source=True, params=p)
350 if stype == "sRender":
351 shape_mode = rng.choice(["sNGon", "sGrid", "sBoolean", "sOutline"])
352 aux: List[str] = []
353 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)
354 base_el = f"{{pfx}}{name}_ShapeA"
355 prim = rng.choice(["sNGon", "sRectangle", "sEllipse"])
356 extra_shape = "Sides = Input { Value = " + str(rng.randint(3, 8)) + ", }," if prim == "sNGon" else ""
357 aux.append(
358 f"\t\t{base_el} = {prim} {{\n\t\t\tInputs = {{\n"
359 f"\t\t\t\tWidth = Input {{ Value = {round(rng.uniform(0.18, 0.45), 2)}, }},\n"
360 f"\t\t\t\tHeight = Input {{ Value = {round(rng.uniform(0.18, 0.45), 2)}, }},\n"
361 f"\t\t\t\tRed = Input {{ Value = {c_r}, }}, Green = Input {{ Value = {c_g}, }}, Blue = Input {{ Value = {c_b}, }},\n"
362 + (f"\t\t\t\t{extra_shape}\n" if extra_shape else "")
363 + "\t\t\t},\n\t\t},"
364 )
365 head_shape = base_el
366 if shape_mode == "sGrid":
367 grid_n = f"{{pfx}}{name}_Grid"
368 aux.append(
369 f"\t\t{grid_n} = sGrid {{\n\t\t\tInputs = {{\n"
370 f'\t\t\t\tInput = Input {{ SourceOp = "{base_el}", Source = "Output", }},\n'
371 f"\t\t\t\tCellsX = Input {{ Value = {rng.randint(2, 4)}, }}, CellsY = Input {{ Value = {rng.randint(2, 3)}, }},\n"
372 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"
373 "\t\t\t},\n\t\t},"
374 )
375 head_shape = grid_n
376 elif shape_mode == "sBoolean":
377 b_el = f"{{pfx}}{name}_ShapeB"
378 bool_n = f"{{pfx}}{name}_Bool"
379 bop = rng.choice(["Union", "Intersection", "Subtract", "Xor"])
380 aux.append(
381 f"\t\t{b_el} = sEllipse {{\n\t\t\tInputs = {{\n"
382 f"\t\t\t\t[\"Translate.X\"] = Input {{ Value = {round(rng.uniform(-0.12, 0.12), 2)}, }},\n"
383 f"\t\t\t\tWidth = Input {{ Value = 0.32, }}, Height = Input {{ Value = 0.32, }},\n"
384 "\t\t\t},\n\t\t},"
385 )
386 aux.append(
387 f"\t\t{bool_n} = sBoolean {{\n\t\t\tInputs = {{\n"
388 f'\t\t\t\tOperation = Input {{ Value = FuID {{ "{bop}" }}, }},\n'
389 f'\t\t\t\tInput1 = Input {{ SourceOp = "{base_el}", Source = "Output", }},\n'
390 f'\t\t\t\tInput2 = Input {{ SourceOp = "{b_el}", Source = "Output", }},\n'
391 "\t\t\t},\n\t\t},"
392 )
393 head_shape = bool_n
394 elif shape_mode == "sOutline":
395 ol_n = f"{{pfx}}{name}_Outline"
396 aux.append(
397 f"\t\t{ol_n} = sOutline {{\n\t\t\tInputs = {{\n"
398 f'\t\t\t\tInput = Input {{ SourceOp = "{base_el}", Source = "Output", }},\n'
399 f"\t\t\t\tThickness = Input {{ Value = {round(rng.uniform(0.015, 0.04), 3)}, }},\n"
400 "\t\t\t},\n\t\t},"
401 )
402 head_shape = ol_n
403 p_sr: Dict[str, Any] = {"Width": 256, "Height": 256}
404 if rng.random() < 0.3:
405 p_sr["Depth"] = rng.choice([3, 4])
406 return DagNode(
407 name=name,
408 kind="sRender",
409 is_source=True,
410 params=p_sr,
411 raw_inputs=[f'Input = Input {{ SourceOp = "{head_shape}", Source = "Output", }},'],
412 aux_templates=aux,
413 )
414 if stype == "DaySky":
415 p_ds: Dict[str, Any] = {
416 "Width": 256,
417 "Height": 256,
418 "Latitude": round(rng.uniform(10.0, 52.0), 1),
419 "Longitude": round(rng.uniform(-60.0, 60.0), 1),
420 "Month": ("FuID", rng.choice(["January", "March", "June", "September"])),
421 "Time": round(rng.uniform(8.0, 17.0), 2),
422 "Turbidity": round(rng.uniform(0.0, 0.8), 2),
423 "Exposure": round(rng.uniform(0.7, 2.0), 2),
424 }
425 if rng.random() < 0.3:
426 p_ds["Depth"] = rng.choice([3, 4])
427 return DagNode(name=name, kind="DaySky", is_source=True, params=p_ds)
428 if stype == "FastNoise":
429 return DagNode(
430 name=name,
431 kind="FastNoise",
432 is_source=True,
433 params={
434 "Width": 256,
435 "Height": 256,
436 "Detail": round(rng.uniform(0.5, 6.0), 2),
437 "Contrast": round(rng.uniform(0.4, 2.2), 2),
438 "Brightness": round(rng.uniform(-0.3, 0.3), 2),
439 "XScale": round(rng.uniform(2.0, 18.0), 2),
440 "YScale": round(rng.uniform(2.0, 18.0), 2),
441 "Seethe": round(rng.uniform(0.0, 50.0), 2),
442 "Discontinuous": rng.choice([0, 1]),
443 "Color1Alpha": 1,
444 },
445 )
446 return DagNode(
447 name=name,
448 kind="Plasma",
449 is_source=True,
450 params={
451 "Width": 256,
452 "Height": 256,
453 "Phase": round(rng.uniform(0.0, 1.0), 3),
454 "Scale": round(rng.uniform(0.6, 2.5), 2),
455 },
456 )
457
458 num_sources = rng.choice([1, 2, 2])
459 for si in range(num_sources):
460 nodes.append(make_source(si))
461
462 op_pool = [
463 "Transform", "Merge", "Dissolve", "Switch",
464 "BrightnessContrast", "ColorCorrector", "ColorGain", "HueCurves",
465 "ChannelBoolean", "Blur", "Glow", "SoftGlow", "DirectionalBlur",
466 "DVE", "CornerPositioner", "PerspectivePositioner", "Displace", "Vortex", "Drip", "Dent",
467 "Paint", "ChangeDepth", "GamutConvert", "Custom",
468 ]
469 num_internal = rng.randint(4, 9)
470 has_anim = rng.random() < 0.30
471 has_inf_edges = False
472
473 for ni in range(num_internal):
474 nname = f"N{ni}"
475 kind = rng.choice(op_pool)
476 if kind == "Drip" and has_inf_edges:
477 kind = "Dent"
478 # Prefer chaining mostly from recent nodes while allowing DAG forks from earlier nodes
479 avail = [n.name for n in nodes]
480 src_a = avail[-1] if rng.random() < 0.65 else rng.choice(avail)
481 src_b = rng.choice(avail)
482
483 # Occasional SourceOp instancing from an existing unary color node
484 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]
485 if inst_cands and rng.random() < 0.10:
486 proto = rng.choice(inst_cands)
487 nodes.append(
488 DagNode(
489 name=nname,
490 kind=proto.kind,
491 is_source=False,
492 primary_port="Input",
493 primary_src=src_a,
494 params={"Blend": round(rng.uniform(0.5, 1.0), 2)},
495 source_op=proto.name,
496 )
497 )
498 continue
499
500 mask = _gen_mask_chain(rng, nname) if (kind not in ("ChangeDepth", "Switch") and rng.random() < 0.32) else None
501 blend = round(rng.uniform(0.55, 1.0), 2) if rng.random() < 0.25 else 1.0
502
503 prim_port = "Input"
504 sec_port: Optional[str] = None
505 sec_src: Optional[str] = None
506 params: Dict[str, Any] = {}
507 raw_inputs: List[str] = []
508 aux_templates: List[str] = []
509
510 if kind == "Transform":
511 ang: Any = round(rng.uniform(-45.0, 45.0), 1)
512 if has_anim and ni == 0:
513 ang = SplineParam(f"{nname}_Ang", "linear", keyframes={0: -15.0, 2: 35.0})
514 ed_val = rng.choice([0, 1, 2, 3])
515 if ed_val in (1, 3):
516 has_inf_edges = True
517 params = {
518 "Center": (round(rng.uniform(0.32, 0.68), 3), round(rng.uniform(0.32, 0.68), 3)),
519 "Pivot": (round(rng.uniform(0.25, 0.75), 3), round(rng.uniform(0.25, 0.75), 3)),
520 "Size": round(rng.uniform(0.65, 1.35), 3),
521 "Aspect": round(rng.uniform(0.75, 1.35), 3),
522 "Angle": ang,
523 "Edges": ed_val,
524 "Blend": blend,
525 }
526 elif kind == "Merge":
527 prim_port = "Background"
528 sec_port = "Foreground"
529 sec_src = src_b
530 m_edges = rng.choice([0, 1, 2, 3]) if rng.random() < 0.3 else 0
531 if m_edges in (1, 3):
532 has_inf_edges = True
533 params = {
534 "ApplyMode": ("FuID", rng.choice([
535 "Normal", "Screen", "Multiply", "Dissolve", "Darken", "Lighten",
536 "Difference", "Exclusion", "Overlay", "Hard Light", "Soft Light",
537 "LinearLight", "Color Dodge", "LinearDodge", "VividLight", "Hypotenuse",
538 "DarkerColor", "LighterColor", "PinLight", "Color Burn", "LinearBurn",
539 "Geometric", "Hue", "Saturation", "Color", "Luminosity",
540 ])),
541 "Operator": ("FuID", rng.choice(["Over", "Over", "Under", "In", "Held Out", "Atop", "XOr", "Conjoint", "Disjoint"])),
542 "Size": round(rng.uniform(0.55, 1.15), 3),
543 "Angle": round(rng.uniform(-25.0, 25.0), 1),
544 "Center": (round(rng.uniform(0.35, 0.65), 3), round(rng.uniform(0.35, 0.65), 3)),
545 "Gain": round(rng.uniform(0.35, 1.25), 2),
546 "SubtractiveAdditive": rng.choice([0.0, 0.5, 1.0]),
547 "BurnIn": round(rng.uniform(0.0, 0.4), 2) if rng.random() < 0.35 else 0.0,
548 "Edges": m_edges,
549 "PerformDepthMerge": 0,
550 "Blend": blend,
551 }
552 elif kind == "Switch":
553 prim_port = "Input0"
554 sec_port = "Input1"
555 sec_src = src_b
556 params = {"Source": rng.choice([0, 1])}
557 elif kind == "Dissolve":
558 prim_port = "Background"
559 sec_port = "Foreground"
560 sec_src = src_b
561 params = {"Mix": round(rng.uniform(0.2, 0.85), 2), "Blend": blend}
562 elif kind == "BrightnessContrast":
563 g_val: Any = round(rng.uniform(0.5, 2.2), 2)
564 if has_anim and ni == 1:
565 g_val = SplineParam(
566 f"{nname}_ExprG",
567 "expr_num",
568 expr_inputs={"n1": round(rng.uniform(0.6, 1.6), 2), "NumberExpression": "n1 * 0.8 + 0.35"},
569 )
570 params = {
571 "Gain": g_val,
572 "Lift": round(rng.uniform(-0.15, 0.2), 2),
573 "Gamma": round(rng.uniform(0.6, 1.6), 2),
574 "Contrast": round(rng.uniform(-0.25, 0.45), 2),
575 "Brightness": round(rng.uniform(-0.2, 0.2), 2),
576 "Saturation": round(rng.uniform(0.3, 1.6), 2),
577 "PreDividePostMultiply": rng.choice([0, 1]),
578 "Blend": blend,
579 }
580 elif kind == "ColorCorrector":
581 params = {
582 "WheelHue1": round(rng.uniform(-0.35, 0.35), 3),
583 "WheelSaturation1": round(rng.uniform(0.5, 1.6), 2),
584 "WheelTintAngle1": round(rng.uniform(-0.5, 0.5), 3),
585 "WheelTintLength1": round(rng.uniform(0.0, 0.7), 2),
586 "TintMode": rng.choice([0, 1, 2]),
587 "MasterRGBGain": round(rng.uniform(0.65, 1.45), 2),
588 "ShadowsRGBGain": round(rng.uniform(0.65, 1.35), 2),
589 "HighlightsRGBGain": round(rng.uniform(0.65, 1.35), 2),
590 "PreDividePostMultiply": rng.choice([0, 1]),
591 "Blend": blend,
592 }
593 elif kind == "ChannelBoolean":
594 prim_port = "Background"
595 sec_port = "Foreground"
596 sec_src = src_b
597 params = {
598 "Operation": rng.choice([0, 1, 2, 6, 8, 9, 10, 13]),
599 "ToRed": rng.choice([0, 1, 2, 5, 10]),
600 "ToGreen": rng.choice([0, 1, 2, 6, 10]),
601 "ToBlue": rng.choice([0, 1, 2, 7, 10]),
602 "ToAlpha": rng.choice([3, 8, 16]),
603 "Blend": blend,
604 }
605 elif kind == "Blur":
606 params = {
607 "Filter": ("FuID", rng.choice(["Gaussian", "Box", "Fast Gaussian"])),
608 "LockBlurXY": 0,
609 "XBlurSize": round(rng.uniform(2.0, 18.0), 1),
610 "YBlurSize": round(rng.uniform(2.0, 18.0), 1),
611 "ClippingMode": ("FuID", rng.choice(["Frame", "None"])),
612 "Blend": blend,
613 }
614 elif kind == "Glow":
615 params = {
616 "LockGlowSize": 0,
617 "XGlowSize": round(rng.uniform(4.0, 20.0), 1),
618 "YGlowSize": round(rng.uniform(2.0, 14.0), 1),
619 "Glow": round(rng.uniform(0.4, 0.88), 2),
620 "Blend": blend,
621 }
622 elif kind == "SoftGlow":
623 params = {
624 "LockGlowSize": 0,
625 "XGlowSize": round(rng.uniform(4.0, 20.0), 1),
626 "YGlowSize": round(rng.uniform(2.0, 16.0), 1),
627 "Gain": round(rng.uniform(0.8, 2.5), 2),
628 "Threshold": round(rng.uniform(0.1, 0.65), 2),
629 "Blend": blend,
630 }
631 elif kind == "DirectionalBlur":
632 params = {
633 "Type": rng.choice([0, 1, 2]),
634 "Length": round(rng.uniform(0.02, 0.12), 3),
635 "Angle": round(rng.uniform(-90.0, 90.0), 1),
636 "Glow": round(rng.uniform(0.0, 0.4), 2),
637 "Blend": blend,
638 }
639 elif kind == "DVE":
640 params = {
641 "XRotation": round(rng.uniform(-35.0, 35.0), 1),
642 "YRotation": round(rng.uniform(-35.0, 35.0), 1),
643 "ZRotation": round(rng.uniform(-25.0, 25.0), 1),
644 "ZMove": round(rng.uniform(0.95, 1.6), 2),
645 "Pivot": (round(rng.uniform(0.3, 0.7), 2), round(rng.uniform(0.3, 0.7), 2)),
646 "Center": (round(rng.uniform(0.4, 0.6), 2), round(rng.uniform(0.4, 0.6), 2)),
647 "Blend": blend,
648 }
649 elif kind == "CornerPositioner":
650 params = {
651 "TopLeft": (round(rng.uniform(0.05, 0.28), 3), round(rng.uniform(0.72, 0.95), 3)),
652 "TopRight": (round(rng.uniform(0.72, 0.95), 3), round(rng.uniform(0.72, 0.95), 3)),
653 "BottomLeft": (round(rng.uniform(0.05, 0.28), 3), round(rng.uniform(0.05, 0.28), 3)),
654 "BottomRight": (round(rng.uniform(0.72, 0.95), 3), round(rng.uniform(0.05, 0.28), 3)),
655 "Blend": blend,
656 }
657 elif kind == "PerspectivePositioner":
658 params = {
659 "MappingType": rng.choice([0, 1]),
660 "TopLeft": (round(rng.uniform(0.12, 0.32), 3), round(rng.uniform(0.68, 0.88), 3)),
661 "TopRight": (round(rng.uniform(0.68, 0.88), 3), round(rng.uniform(0.68, 0.88), 3)),
662 "BottomLeft": (round(rng.uniform(0.12, 0.32), 3), round(rng.uniform(0.12, 0.32), 3)),
663 "BottomRight": (round(rng.uniform(0.68, 0.88), 3), round(rng.uniform(0.12, 0.32), 3)),
664 "Blend": blend,
665 }
666 elif kind == "HueCurves":
667 h_sp = f"{{pfx}}{nname}_Hue"
668 s_sp = f"{{pfx}}{nname}_Sat"
669 l_sp = f"{{pfx}}{nname}_Lum"
670 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)]))
671 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)]))
672 aux_templates.append(lut_bezier(l_sp, [(0, 1.0), (3, round(rng.uniform(0.7, 1.3), 2)), (6, 1.0)]))
673 raw_inputs.extend([
674 f'Hue = Input {{ SourceOp = "{h_sp}", Source = "Value", }},',
675 f'Sat = Input {{ SourceOp = "{s_sp}", Source = "Value", }},',
676 f'Lum = Input {{ SourceOp = "{l_sp}", Source = "Value", }},',
677 ])
678 params = {"Blend": blend}
679 elif kind == "Paint":
680 ps_n = f"{{pfx}}{nname}_PS"
681 btype = rng.choice(["SoftBrush", "CircleBrush"])
682 bsize = round(rng.uniform(0.03, 0.11), 3)
683 bsoft = round(rng.uniform(0.0, 0.8), 2)
684 cr = round(rng.uniform(0.2, 1.0), 2)
685 cg = round(rng.uniform(0.2, 1.0), 2)
686 cb = round(rng.uniform(0.2, 1.0), 2)
687 opac = round(rng.uniform(0.6, 1.0), 2)
688 wo0 = round(rng.uniform(0.0, 0.2), 2)
689 wo1 = round(rng.uniform(0.75, 1.0), 2)
690 x0, y0 = round(rng.uniform(-0.35, -0.05), 3), round(rng.uniform(-0.35, 0.35), 3)
691 x1, y1 = round(rng.uniform(0.05, 0.35), 3), round(rng.uniform(-0.35, 0.35), 3)
692 soft_line = f'\t\t\t\t["{btype}.Softness"] = Input {{ Value = {bsoft}, }},\n' if btype == "SoftBrush" else ""
693 aux_templates.append(
694 f'\t\t{ps_n} = PolylineStroke {{\n'
695 f'\t\t\tBrushes = {{ "{btype}" }},\n'
696 f'\t\t\tApplyModes = {{ "PaintApplyColor" }},\n'
697 f'\t\t\tInputs = {{\n'
698 f'\t\t\t\tBrushShape = Input {{ Value = FuID {{ "{btype}" }}, }},\n'
699 f'\t\t\t\tApplyMode = Input {{ Value = FuID {{ "PaintApplyColor" }}, }},\n'
700 f'\t\t\t\t["{btype}.Size"] = Input {{ Value = {bsize}, }},\n'
701 f'{soft_line}'
702 f'\t\t\t\t["PaintApplyColor.Red"] = Input {{ Value = {cr}, }},\n'
703 f'\t\t\t\t["PaintApplyColor.Green"] = Input {{ Value = {cg}, }},\n'
704 f'\t\t\t\t["PaintApplyColor.Blue"] = Input {{ Value = {cb}, }},\n'
705 f'\t\t\t\t["PaintApplyColor.Opacity"] = Input {{ Value = {opac}, }},\n'
706 f'\t\t\t\tWriteOnStart = Input {{ Value = {wo0}, }},\n'
707 f'\t\t\t\tWriteOnEnd = Input {{ Value = {wo1}, }},\n'
708 f'\t\t\t\tPolyline = Input {{ Value = Polyline {{ Points = {{ '
709 f'{{ Linear = true, X = {x0}, Y = {y0} }}, {{ Linear = true, X = {x1}, Y = {y1} }} '
710 f'}} }}, }},\n'
711 f'\t\t\t}},\n'
712 f'\t\t}},'
713 )
714 raw_inputs.append(f'Paint = Input {{ SourceOp = "{ps_n}", Source = "Out", }},')
715 params = {"Blend": blend}
716 elif kind == "Displace":
717 sec_port = "Foreground"
718 sec_src = src_b
719 dtype = rng.choice([0, 1])
720 if dtype == 0:
721 params = {
722 "Type": 0,
723 "RefractionStrength": round(rng.uniform(0.04, 0.16), 3),
724 "Spread": round(rng.uniform(0.0, 0.35), 2),
725 "LightPower": round(rng.uniform(0.0, 0.6), 2),
726 "Blend": blend,
727 }
728 else:
729 params = {
730 "Type": 1,
731 "XChannel": rng.choice([0, 1, 2]),
732 "YChannel": rng.choice([0, 1, 2]),
733 "XOffset": -0.5,
734 "YOffset": -0.5,
735 "XRefraction": round(rng.uniform(-0.12, 0.12), 3),
736 "YRefraction": round(rng.uniform(-0.12, 0.12), 3),
737 "Blend": blend,
738 }
739 elif kind == "Vortex":
740 params = {
741 "Center": (round(rng.uniform(0.35, 0.65), 2), round(rng.uniform(0.35, 0.65), 2)),
742 "Size": round(rng.uniform(0.35, 1.2), 2),
743 "Angle": round(rng.uniform(-2.5, 2.5), 2),
744 "Power": round(rng.uniform(0.8, 3.0), 2),
745 "Blend": blend,
746 }
747 elif kind == "Drip":
748 params = {
749 "Center": (round(rng.uniform(0.35, 0.65), 2), round(rng.uniform(0.35, 0.65), 2)),
750 "Strength": round(rng.uniform(0.4, 1.0), 2),
751 "Amplitude": round(rng.uniform(0.04, 0.14), 3),
752 "Frequency": round(rng.uniform(2.0, 7.0), 1),
753 "Phase": round(rng.uniform(0.0, 1.0), 2),
754 "Shape": rng.choice([0, 1]),
755 "Blend": blend,
756 }
757 elif kind == "Dent":
758 params = {
759 "Center": (round(rng.uniform(0.35, 0.65), 2), round(rng.uniform(0.35, 0.65), 2)),
760 "Size": round(rng.uniform(0.35, 0.85), 2),
761 "Strength": round(rng.uniform(0.3, 0.9), 2),
762 "Type": rng.choice([0, 1, 2, 3]),
763 "Blend": blend,
764 }
765 elif kind == "ChangeDepth":
766 params = {"Depth": rng.choice([1, 2, 3, 4])}
767 elif kind == "GamutConvert":
768 params = {
769 "SourceSpace": ("FuID", rng.choice(["NoChange", "sRGB", "Rec709"])),
770 "OutputSpace": ("FuID", rng.choice(["NoChange", "sRGB", "Rec709"])),
771 "RemoveGamma": rng.choice([0, 1]),
772 "AddGamma": rng.choice([0, 1]),
773 "PreDividePostMultiply": rng.choice([0, 1]),
774 "Blend": blend,
775 }
776 elif kind == "ColorGain":
777 params = {
778 "GainRed": round(rng.uniform(0.6, 1.5), 2),
779 "GainGreen": round(rng.uniform(0.6, 1.5), 2),
780 "GainBlue": round(rng.uniform(0.6, 1.5), 2),
781 "LiftGreen": round(rng.uniform(-0.1, 0.15), 2),
782 "GammaBlue": round(rng.uniform(0.7, 1.4), 2),
783 "MidHue": round(rng.uniform(0.1, 0.9), 2),
784 "PreDividePostMultiply": rng.choice([0, 1]),
785 "Blend": blend,
786 }
787 elif kind == "Custom":
788 prim_port = "Image1"
789 sec_port = "Image2"
790 sec_src = src_b
791 params = {
792 "NumberIn1": round(rng.uniform(0.3, 0.8), 2),
793 "PointIn1": (round(rng.uniform(0.3, 0.7), 2), round(rng.uniform(0.3, 0.7), 2)),
794 "Setup1": "1 - n1",
795 "Intermediate1": "max(0, 1 - dist(x, y, p1x, p1y) * 1.8)",
796 "RedExpression": "if(x > p1x, getr1b(x - 0.08, y) * i1 + r2 * s1, r1)",
797 "GreenExpression": "g1 * (1 - i1) + g2 * i1",
798 "BlueExpression": "b1 * n1 + b2 * (1 - n1)",
799 "AlphaExpression": "a1",
800 "Blend": blend,
801 }
802
803 nodes.append(
804 DagNode(
805 name=nname,
806 kind=kind,
807 is_source=False,
808 primary_port=prim_port,
809 primary_src=src_a,
810 secondary_port=sec_port,
811 secondary_src=sec_src,
812 params=params,
813 raw_inputs=raw_inputs,
814 aux_templates=aux_templates,
815 mask=mask,
816 )
817 )
818
819 return FuzzGraph(seed=seed, eval_frame=eval_frame, nodes=nodes)
820
821
scripts/diff_fuzz/matrix.py created+969
......@@ -0,0 +1,969 @@
1"""Exhaustive edge-case parameter matrix suites (Merge, HDR, masks, color/blur, warps, 3D, misc, paint)."""
2
3from typing import Dict, List, Tuple
4
5from .assets import (
6 build_switch_chain,
7 linear_spline,
8 lut_bezier,
9 make_comp,
10 make_loader,
11 make_saver,
12 ensure_dirs,
13)
14
15
16
17
18def build_matrix_merge_modes(assets: Dict[str, str]):
19 """Sweeps all Merge ApplyModes, Operators, SubtractiveAdditive, AlphaGain/Gain, BurnIn, Edges, mismatched res, EffectMask."""
20 nodes = [
21 make_loader("ColorLoader", assets["color"], post_mult=1),
22 make_loader("FGLoader", assets["fg"], post_mult=1),
23 make_loader("SmallLoader", assets["small"], post_mult=1),
24 """\t\tBlackBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftAlpha = Input { Value = 1, }, }, },
25\t\tBlueBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftRed = Input { Value = 0.15, }, TopLeftGreen = Input { Value = 0.25, }, TopLeftBlue = Input { Value = 0.55, }, TopLeftAlpha = Input { Value = 1, }, }, },
26\t\tMaskEll = EllipseMask { Inputs = { MaskWidth = Input { Value = 256, }, MaskHeight = Input { Value = 256, }, Width = Input { Value = 0.55, }, Height = Input { Value = 0.45, }, SoftEdge = Input { Value = 0.04, }, }, },""",
27 ]
28 cases: List[Tuple[int, str, str]] = []
29 f = 0
30
31 def add_case(label: str, fg: str, bg: str, extra: str, over_blue: bool = False) -> None:
32 nonlocal f
33 mname = f"M_{f}"
34 nodes.append(
35 f"""\t\t{mname} = Merge {{
36\t\t\tInputs = {{
37\t\t\t\tBackground = Input {{ SourceOp = "{bg}", Source = "Output", }},
38\t\t\t\tForeground = Input {{ SourceOp = "{fg}", Source = "Output", }},
39\t\t\t\tPerformDepthMerge = Input {{ Value = 0, }},
40\t\t\t\t{extra}
41\t\t\t}},
42\t\t}},"""
43 )
44 out_name = mname
45 if over_blue:
46 oname = f"Vis_{f}"
47 nodes.append(
48 f"""\t\t{oname} = Merge {{
49\t\t\tInputs = {{
50\t\t\t\tBackground = Input {{ SourceOp = "BlueBG", Source = "Output", }},
51\t\t\t\tForeground = Input {{ SourceOp = "{mname}", Source = "Output", }},
52\t\t\t}},
53\t\t}},"""
54 )
55 out_name = oname
56 cases.append((f, label, out_name))
57 f += 1
58
59 apply_modes = [
60 "Normal", "Screen", "Multiply", "Dissolve", "Soft Light", "Hard Light",
61 "Darken", "Lighten", "Color Dodge", "Color Burn", "Difference", "Exclusion",
62 "Overlay", "Sub",
63 ]
64 for am in apply_modes:
65 add_case(f"ApplyMode={am}", "FGLoader", "ColorLoader", f'Size = Input {{ Value = 0.85, }}, ApplyMode = Input {{ Value = FuID {{ "{am}" }}, }},')
66
67 operators = ["Over", "In", "Held Out", "Atop", "XOr", "Conjoint", "Disjoint"]
68 for op in operators:
69 add_case(f"Operator={op}", "FGLoader", "ColorLoader", f'Operator = Input {{ Value = FuID {{ "{op}" }}, }},', over_blue=True)
70
71 for sa in (0.0, 0.5, 1.0):
72 add_case(f"SubAdd={sa}", "FGLoader", "ColorLoader", f"SubtractiveAdditive = Input {{ Value = {sa}, }},")
73
74 for ag in (0.0, 0.5, 1.5):
75 add_case(f"Gain={ag}", "FGLoader", "ColorLoader", f"Gain = Input {{ Value = {ag}, }},")
76 add_case("AlphaGain=0.5", "FGLoader", "ColorLoader", "AlphaGain = Input { Value = 0.5, },")
77
78 add_case("BurnIn=0.6", "FGLoader", "ColorLoader", "BurnIn = Input { Value = 0.6, },")
79
80 for ed in (0, 1, 2, 3):
81 add_case(
82 f"Edges={ed}",
83 "SmallLoader",
84 "ColorLoader",
85 f"Center = Input {{ Value = {{ 0.78, 0.72 }}, }}, Size = Input {{ Value = 0.55, }}, Angle = Input {{ Value = 22, }}, Edges = Input {{ Value = {ed}, }},",
86 )
87
88 add_case("Mismatch_SmallOverColor", "SmallLoader", "ColorLoader", "Size = Input { Value = 0.8, }, Angle = Input { Value = 20, },")
89 add_case("Mismatch_ColorOverSmall", "ColorLoader", "SmallLoader", "Size = Input { Value = 0.5, }, Angle = Input { Value = -15, },", over_blue=True)
90
91 for inv in (0, 1):
92 for mbm in (0, 1):
93 add_case(
94 f"Mask_inv{inv}_mbm{mbm}",
95 "FGLoader",
96 "ColorLoader",
97 f'EffectMask = Input {{ SourceOp = "MaskEll", Source = "Mask", }}, ApplyMaskInverted = Input {{ Value = {inv}, }}, MultiplyByMask = Input {{ Value = {mbm}, }},',
98 )
99
100 sw_nodes, sw_splines, out_op = build_switch_chain(cases, "BlackBG", "MM")
101 nodes.extend(sw_nodes)
102 nodes.append(make_saver(out_op, "matrix_merge_modes"))
103 comp_path = ensure_dirs() / "comps" / "matrix_merge_modes.comp"
104 comp_path.write_text(make_comp("\n".join(nodes + sw_splines), len(cases) - 1))
105 return comp_path, "matrix_merge_modes", [(c[0], c[1]) for c in cases]
106
107
108def build_matrix_hdr_depth(assets: Dict[str, str]):
109 """Tests BitDepth (int8/int16/float16/float32), HDR > 1.0, negative values, PreDividePostMultiply=0/1."""
110 nodes = [
111 make_loader("ColorLoader", assets["color"], post_mult=1),
112 make_loader("FGLoader", assets["fg"], post_mult=1),
113 """\t\tBlackBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftAlpha = Input { Value = 1, }, }, },
114\t\tDarkBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftRed = Input { Value = 0.1, }, TopLeftGreen = Input { Value = 0.12, }, TopLeftBlue = Input { Value = 0.16, }, TopLeftAlpha = Input { Value = 1, }, }, },""",
115 ]
116 cases: List[Tuple[int, str, str]] = []
117 f = 0
118
119 for d_code, d_name in ((1, "int8"), (2, "int16"), (3, "float16"), (4, "float32")):
120 cd = f"CD_{f}"
121 up = f"Up_{f}"
122 bl = f"Bl_{f}"
123 dn = f"Dn_{f}"
124 nodes.append(f'\t\t{cd} = ChangeDepth {{ Inputs = {{ Input = Input {{ SourceOp = "ColorLoader", Source = "Output", }}, Depth = Input {{ Value = {d_code}, }}, }}, }},')
125 nodes.append(f'\t\t{up} = BrightnessContrast {{ Inputs = {{ Input = Input {{ SourceOp = "{cd}", Source = "Output", }}, Gain = Input {{ Value = 2.5, }}, }}, }},')
126 nodes.append(f'\t\t{bl} = Blur {{ Inputs = {{ Input = Input {{ SourceOp = "{up}", Source = "Output", }}, XBlurSize = Input {{ Value = 8.0, }}, }}, }},')
127 nodes.append(f'\t\t{dn} = BrightnessContrast {{ Inputs = {{ Input = Input {{ SourceOp = "{bl}", Source = "Output", }}, Gain = Input {{ Value = 0.4, }}, }}, }},')
128 cases.append((f, f"HDR_Depth={d_name}_Gain2.5_Blur_Gain0.4", dn))
129 f += 1
130
131 # Negative value roundtrip across depths
132 for d_code, d_name in ((1, "int8"), (3, "float16"), (4, "float32")):
133 cd = f"CDN_{f}"
134 sub = f"Sub_{f}"
135 bl = f"BlN_{f}"
136 add = f"Add_{f}"
137 nodes.append(f'\t\t{cd} = ChangeDepth {{ Inputs = {{ Input = Input {{ SourceOp = "ColorLoader", Source = "Output", }}, Depth = Input {{ Value = {d_code}, }}, }}, }},')
138 nodes.append(f'\t\t{sub} = BrightnessContrast {{ Inputs = {{ Input = Input {{ SourceOp = "{cd}", Source = "Output", }}, Brightness = Input {{ Value = -0.4, }}, }}, }},')
139 nodes.append(f'\t\t{bl} = Blur {{ Inputs = {{ Input = Input {{ SourceOp = "{sub}", Source = "Output", }}, XBlurSize = Input {{ Value = 5.0, }}, }}, }},')
140 nodes.append(f'\t\t{add} = BrightnessContrast {{ Inputs = {{ Input = Input {{ SourceOp = "{bl}", Source = "Output", }}, Brightness = Input {{ Value = 0.4, }}, }}, }},')
141 cases.append((f, f"NegValues_Depth={d_name}", add))
142 f += 1
143
144 # Background native Depth=3/4 HDR
145 for d_code, d_name in ((3, "float16"), (4, "float32")):
146 bg = f"BG_{f}"
147 up = f"BUp_{f}"
148 dn = f"BDn_{f}"
149 nodes.append(f'\t\t{bg} = Background {{ Inputs = {{ Width = Input {{ Value = 256, }}, Height = Input {{ Value = 256, }}, Depth = Input {{ Value = {d_code}, }}, Type = Input {{ Value = FuID {{ "Horizontal" }}, }}, TopLeftRed = Input {{ Value = 0.8, }}, TopLeftGreen = Input {{ Value = 0.2, }}, TopLeftBlue = Input {{ Value = 0.1, }}, TopLeftAlpha = Input {{ Value = 1, }}, TopRightRed = Input {{ Value = 0.1, }}, TopRightGreen = Input {{ Value = 0.7, }}, TopRightBlue = Input {{ Value = 0.9, }}, }}, }},')
150 nodes.append(f'\t\t{up} = BrightnessContrast {{ Inputs = {{ Input = Input {{ SourceOp = "{bg}", Source = "Output", }}, Gain = Input {{ Value = 3.0, }}, }}, }},')
151 nodes.append(f'\t\t{dn} = BrightnessContrast {{ Inputs = {{ Input = Input {{ SourceOp = "{up}", Source = "Output", }}, Gain = Input {{ Value = 0.333333, }}, }}, }},')
152 cases.append((f, f"BG_Depth={d_name}_HDR", dn))
153 f += 1
154
155 # PreDividePostMultiply = 0 / 1 on semi-transparent FGLoader merged over DarkBG
156 for pd in (0, 1):
157 bc = f"BCPD_{f}"
158 m = f"MPD_{f}"
159 nodes.append(f'\t\t{bc} = BrightnessContrast {{ Inputs = {{ Input = Input {{ SourceOp = "FGLoader", Source = "Output", }}, Gain = Input {{ Value = 1.6, }}, Gamma = Input {{ Value = 0.7, }}, Brightness = Input {{ Value = 0.15, }}, PreDividePostMultiply = Input {{ Value = {pd}, }}, }}, }},')
160 nodes.append(f'\t\t{m} = Merge {{ Inputs = {{ Background = Input {{ SourceOp = "DarkBG", Source = "Output", }}, Foreground = Input {{ SourceOp = "{bc}", Source = "Output", }}, }}, }},')
161 cases.append((f, f"BC_PreDiv={pd}", m))
162 f += 1
163
164 sw_nodes, sw_splines, out_op = build_switch_chain(cases, "BlackBG", "HD")
165 nodes.extend(sw_nodes)
166 nodes.append(make_saver(out_op, "matrix_hdr_depth"))
167 comp_path = ensure_dirs() / "comps" / "matrix_hdr_depth.comp"
168 comp_path.write_text(make_comp("\n".join(nodes + sw_splines), len(cases) - 1))
169 return comp_path, "matrix_hdr_depth", [(c[0], c[1]) for c in cases]
170
171
172def build_matrix_masks(assets: Dict[str, str]):
173 """Chained multi-mask graphs (EllipseMask -> RectangleMask -> PolylineMask) testing all PaintModes, SoftEdge, BorderWidth, Invert, Level."""
174 nodes = [
175 """\t\tBlackBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftAlpha = Input { Value = 1, }, }, },
176\t\tWhiteFG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftRed = Input { Value = 0.95, }, TopLeftGreen = Input { Value = 0.75, }, TopLeftBlue = Input { Value = 0.25, }, TopLeftAlpha = Input { Value = 1, }, }, },""",
177 ]
178 cases: List[Tuple[int, str, str]] = []
179 f = 0
180
181 paint_modes = ["Merge", "Add", "Subtract", "Minimum", "Maximum", "Average", "Multiply", "Replace", "Invert"]
182 for pm in paint_modes:
183 e = f"Ell_{f}"
184 r = f"Rect_{f}"
185 p = f"Poly_{f}"
186 m = f"Op_{f}"
187 nodes.append(f'\t\t{e} = EllipseMask {{ Inputs = {{ MaskWidth = Input {{ Value = 256, }}, MaskHeight = Input {{ Value = 256, }}, Center = Input {{ Value = {{ 0.42, 0.50 }}, }}, Width = Input {{ Value = 0.50, }}, Height = Input {{ Value = 0.45, }}, SoftEdge = Input {{ Value = 0.03, }}, }}, }},')
188 nodes.append(f'\t\t{r} = RectangleMask {{ Inputs = {{ EffectMask = Input {{ SourceOp = "{e}", Source = "Mask", }}, PaintMode = Input {{ Value = FuID {{ "{pm}" }}, }}, MaskWidth = Input {{ Value = 256, }}, MaskHeight = Input {{ Value = 256, }}, Center = Input {{ Value = {{ 0.58, 0.55 }}, }}, Width = Input {{ Value = 0.42, }}, Height = Input {{ Value = 0.42, }}, SoftEdge = Input {{ Value = 0.02, }}, Level = Input {{ Value = 0.8, }}, }}, }},')
189 nodes.append(
190 f"""\t\t{p} = PolylineMask {{
191\t\t\tInputs = {{
192\t\t\t\tEffectMask = Input {{ SourceOp = "{r}", Source = "Mask", }},
193\t\t\t\tPaintMode = Input {{ Value = FuID {{ "{pm}" }}, }},
194\t\t\t\tMaskWidth = Input {{ Value = 256, }},
195\t\t\t\tMaskHeight = Input {{ Value = 256, }},
196\t\t\t\tSoftEdge = Input {{ Value = 0.02, }},
197\t\t\t\tPolyline = Input {{
198\t\t\t\t\tValue = Polyline {{
199\t\t\t\t\t\tClosed = true,
200\t\t\t\t\t\tPoints = {{
201\t\t\t\t\t\t\t{{ Linear = true, X = -0.25, Y = -0.25, RX = 0.16, RY = 0 }},
202\t\t\t\t\t\t\t{{ Linear = true, X = 0.25, Y = -0.15, LX = -0.16, LY = 0, RX = -0.08, RY = 0.14 }},
203\t\t\t\t\t\t\t{{ Linear = true, X = 0.0, Y = 0.28, LX = 0.08, LY = -0.14 }},
204\t\t\t\t\t\t}},
205\t\t\t\t\t}},
206\t\t\t\t}},
207\t\t\t}},
208\t\t}},"""
209 )
210 nodes.append(f'\t\t{m} = Merge {{ Inputs = {{ Background = Input {{ SourceOp = "BlackBG", Source = "Output", }}, Foreground = Input {{ SourceOp = "WhiteFG", Source = "Output", }}, EffectMask = Input {{ SourceOp = "{p}", Source = "Mask", }}, }}, }},')
211 cases.append((f, f"MaskChain_PaintMode={pm}", m))
212 f += 1
213
214 # BorderWidth, Solid=0/1, SoftEdge, Invert, Level edge cases
215 extra_masks = [
216 ("Rect_Border0.05_Solid0", 'RectangleMask { Inputs = { MaskWidth = Input { Value = 256, }, MaskHeight = Input { Value = 256, }, Width = Input { Value = 0.5, }, Height = Input { Value = 0.5, }, Solid = Input { Value = 0, }, BorderWidth = Input { Value = 0.05, }, }, }'),
217 ("Ell_Border0.04_Soft0.03_Inv1", 'EllipseMask { Inputs = { MaskWidth = Input { Value = 256, }, MaskHeight = Input { Value = 256, }, Width = Input { Value = 0.45, }, Height = Input { Value = 0.35, }, Angle = Input { Value = 25, }, Solid = Input { Value = 1, }, BorderWidth = Input { Value = 0.04, }, SoftEdge = Input { Value = 0.03, }, Invert = Input { Value = 1, }, Level = Input { Value = 0.65, }, }, }'),
218 ("Rect_Corner0.35_Soft0.08_Box", 'RectangleMask { Inputs = { MaskWidth = Input { Value = 256, }, MaskHeight = Input { Value = 256, }, Width = Input { Value = 0.6, }, Height = Input { Value = 0.45, }, CornerRadius = Input { Value = 0.35, }, SoftEdge = Input { Value = 0.08, }, Filter = Input { Value = FuID { "Box" }, }, }, }'),
219 ("Poly_Invert1_Level0.6_Soft0.05", 'PolylineMask { Inputs = { MaskWidth = Input { Value = 256, }, MaskHeight = Input { Value = 256, }, SoftEdge = Input { Value = 0.05, }, Invert = Input { Value = 1, }, Level = Input { Value = 0.6, }, Polyline = Input { Value = Polyline { Closed = true, Points = { { Linear = true, X = -0.3, Y = -0.2 }, { Linear = true, X = 0.3, Y = -0.2 }, { Linear = true, X = 0.0, Y = 0.3 } } }, }, }, }'),
220 ]
221 for label, mdef in extra_masks:
222 mk = f"Mk_{f}"
223 m = f"Op_{f}"
224 nodes.append(f"\t\t{mk} = {mdef},")
225 nodes.append(f'\t\t{m} = Merge {{ Inputs = {{ Background = Input {{ SourceOp = "BlackBG", Source = "Output", }}, Foreground = Input {{ SourceOp = "WhiteFG", Source = "Output", }}, EffectMask = Input {{ SourceOp = "{mk}", Source = "Mask", }}, }}, }},')
226 cases.append((f, label, m))
227 f += 1
228
229 sw_nodes, sw_splines, out_op = build_switch_chain(cases, "BlackBG", "MK")
230 nodes.extend(sw_nodes)
231 nodes.append(make_saver(out_op, "matrix_masks"))
232 comp_path = ensure_dirs() / "comps" / "matrix_masks.comp"
233 comp_path.write_text(make_comp("\n".join(nodes + sw_splines), len(cases) - 1))
234 return comp_path, "matrix_masks", [(c[0], c[1]) for c in cases]
235
236
237def build_matrix_color_blur(assets: Dict[str, str]):
238 """ColorCorrector, ColorCurves, HueCurves, GamutConvert, ChannelBoolean, Blur, Glow, SoftGlow, DirectionalBlur."""
239 nodes = [
240 make_loader("ColorLoader", assets["color"], post_mult=1),
241 make_loader("FGLoader", assets["fg"], post_mult=1),
242 """\t\tBlackBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftAlpha = Input { Value = 1, }, }, },
243\t\tDarkBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftRed = Input { Value = 0.12, }, TopLeftGreen = Input { Value = 0.12, }, TopLeftBlue = Input { Value = 0.18, }, TopLeftAlpha = Input { Value = 1, }, }, },""",
244 lut_bezier("CC_Red", [(0.0, 0.0), (0.3, 0.55), (0.7, 0.45), (1.0, 0.95)]),
245 lut_bezier("CC_Green", [(0.0, 0.08), (0.5, 0.42), (1.0, 1.0)]),
246 lut_bezier("CC_Blue", [(0.0, 0.0), (0.5, 0.72), (1.0, 0.85)]),
247 lut_bezier("CC_Alpha", [(0.0, 0.0), (0.5, 0.85), (1.0, 1.0)]),
248 lut_bezier("HC_Hue", [(0, 1.25), (2, 0.85), (4, 1.15), (6, 1.25)]),
249 lut_bezier("HC_Sat", [(0, 1.0), (1, 0.3), (3, 1.7), (5, 0.6), (6, 1.0)]),
250 lut_bezier("HC_Lum", [(0, 1.0), (2, 0.6), (4, 1.4), (6, 1.0)]),
251 lut_bezier("HC_RSup", [(0, 0.5), (2, 1.0), (6, 0.5)]),
252 ]
253 cases: List[Tuple[int, str, str]] = []
254 f = 0
255
256 def add_op(label: str, kind: str, in_port: str, src: str, extra: str, over_dark: bool = False) -> None:
257 nonlocal f
258 opn = f"Op_{f}"
259 nodes.append(
260 f"""\t\t{opn} = {kind} {{
261\t\t\tInputs = {{
262\t\t\t\t{in_port} = Input {{ SourceOp = "{src}", Source = "Output", }},
263\t\t\t\t{extra}
264\t\t\t}},
265\t\t}},"""
266 )
267 out_n = opn
268 if over_dark:
269 vn = f"Vis_{f}"
270 nodes.append(f'\t\t{vn} = Merge {{ Inputs = {{ Background = Input {{ SourceOp = "DarkBG", Source = "Output", }}, Foreground = Input {{ SourceOp = "{opn}", Source = "Output", }}, }}, }},')
271 out_n = vn
272 cases.append((f, label, out_n))
273 f += 1
274
275 # ColorCorrector: SMH + Wheel Hue/Sat/Tint + PreDividePostMultiply
276 add_op("CC_SMH_Wheel_PreDiv1", "ColorCorrector", "Input", "FGLoader", "WheelHue1 = Input { Value = 0.18, }, WheelSaturation1 = Input { Value = 1.35, }, WheelTintAngle1 = Input { Value = -0.35, }, WheelTintLength1 = Input { Value = 0.65, }, ShadowsRGBGain = Input { Value = 0.7, }, MidtonesRGBGamma = Input { Value = 1.35, }, HighlightsRGBGain = Input { Value = 1.3, }, PreDividePostMultiply = Input { Value = 1, },", over_dark=True)
277 add_op("CC_SMH_TintMode0", "ColorCorrector", "Input", "ColorLoader", "WheelTintAngle2 = Input { Value = 0.25, }, WheelTintLength2 = Input { Value = 0.7, }, WheelHue3 = Input { Value = -0.2, }, WheelSaturation4 = Input { Value = 1.6, }, TintMode = Input { Value = 0, },")
278 add_op("CC_SMH_TintMode1", "ColorCorrector", "Input", "ColorLoader", "WheelTintAngle1 = Input { Value = -0.25, }, WheelTintLength1 = Input { Value = 0.8, }, WheelSaturation1 = Input { Value = 1.4, }, TintMode = Input { Value = 1, },")
279
280 # ColorCurves & HueCurves
281 add_op("ColorCurves_RGBA_PreDiv1", "ColorCurves", "Input", "ColorLoader", 'Red = Input { SourceOp = "CC_Red", Source = "Value", }, Green = Input { SourceOp = "CC_Green", Source = "Value", }, Blue = Input { SourceOp = "CC_Blue", Source = "Value", }, Alpha = Input { SourceOp = "CC_Alpha", Source = "Value", }, PreDividePostMultiply = Input { Value = 1, },', over_dark=True)
282 add_op("HueCurves_Multi", "HueCurves", "Input", "ColorLoader", 'Hue = Input { SourceOp = "HC_Hue", Source = "Value", }, Sat = Input { SourceOp = "HC_Sat", Source = "Value", }, Lum = Input { SourceOp = "HC_Lum", Source = "Value", }, RedSuppress = Input { SourceOp = "HC_RSup", Source = "Value", },')
283
284 # GamutConvert
285 add_op("Gamut_sRGB_to_Linear", "GamutConvert", "Input", "ColorLoader", 'SourceSpace = Input { Value = FuID { "sRGB" }, }, OutputSpace = Input { Value = FuID { "NoChange" }, }, RemoveGamma = Input { Value = 1, }, AddGamma = Input { Value = 0, },')
286 add_op("Gamut_Linear_to_sRGB", "GamutConvert", "Input", "ColorLoader", 'SourceSpace = Input { Value = FuID { "NoChange" }, }, OutputSpace = Input { Value = FuID { "sRGB" }, }, RemoveGamma = Input { Value = 0, }, AddGamma = Input { Value = 1, },')
287 add_op("Gamut_Rec709_to_sRGB", "GamutConvert", "Input", "ColorLoader", 'SourceSpace = Input { Value = FuID { "Rec709" }, }, OutputSpace = Input { Value = FuID { "sRGB" }, }, RemoveGamma = Input { Value = 1, }, AddGamma = Input { Value = 1, },')
288
289 # ChannelBoolean: Add/Sub/Mul/Div/Copy/Min/Max/Negative/Solid
290 cb_ops = [
291 ("CB_Copy_BGR", 0, 'ToRed = Input { Value = 2, }, ToGreen = Input { Value = 1, }, ToBlue = Input { Value = 0, },'),
292 ("CB_Add", 1, 'Foreground = Input { SourceOp = "FGLoader", Source = "Output", },'),
293 ("CB_Sub", 2, 'Foreground = Input { SourceOp = "FGLoader", Source = "Output", },'),
294 ("CB_Mul", 6, 'Foreground = Input { SourceOp = "FGLoader", Source = "Output", },'),
295 ("CB_Div", 7, 'Foreground = Input { SourceOp = "FGLoader", Source = "Output", },'),
296 ("CB_Max", 8, 'Foreground = Input { SourceOp = "FGLoader", Source = "Output", },'),
297 ("CB_Min", 9, 'Foreground = Input { SourceOp = "FGLoader", Source = "Output", },'),
298 ("CB_Negative", 10, 'Foreground = Input { SourceOp = "FGLoader", Source = "Output", },'),
299 ("CB_Solid", 11, ''),
300 ]
301 for label, op_code, extra in cb_ops:
302 add_op(label, "ChannelBoolean", "Background", "ColorLoader", f"Operation = Input {{ Value = {op_code}, }}, {extra}")
303
304 # Blur (Gaussian, Box, FastGaussian + unlocked X/Y)
305 add_op("Blur_Gaussian_XY", "Blur", "Input", "ColorLoader", 'Filter = Input { Value = FuID { "Gaussian" }, }, LockBlurXY = Input { Value = 0, }, XBlurSize = Input { Value = 16.0, }, YBlurSize = Input { Value = 3.0, },')
306 add_op("Blur_Box_12", "Blur", "Input", "ColorLoader", 'Filter = Input { Value = FuID { "Box" }, }, XBlurSize = Input { Value = 12.0, },')
307 add_op("Blur_FastGauss_XY", "Blur", "Input", "ColorLoader", 'Filter = Input { Value = FuID { "Fast Gaussian" }, }, LockBlurXY = Input { Value = 0, }, XBlurSize = Input { Value = 4.0, }, YBlurSize = Input { Value = 20.0, },')
308
309 # Glow, SoftGlow, DirectionalBlur
310 add_op("Glow_UnlockedXY", "Glow", "Input", "FGLoader", "LockGlowSize = Input { Value = 0, }, XGlowSize = Input { Value = 18.0, }, YGlowSize = Input { Value = 3.0, }, Glow = Input { Value = 0.78, },", over_dark=True)
311 add_op("SoftGlow_UnlockedXY_Thresh", "SoftGlow", "Input", "ColorLoader", "LockGlowSize = Input { Value = 0, }, XGlowSize = Input { Value = 16.0, }, YGlowSize = Input { Value = 4.0, }, Gain = Input { Value = 2.2, }, Threshold = Input { Value = 0.45, },")
312 add_op("DirBlur_Centered_Glow", "DirectionalBlur", "Input", "ColorLoader", "Type = Input { Value = 2, }, Length = Input { Value = 0.08, }, Angle = Input { Value = 35.0, }, Glow = Input { Value = 0.35, }, Center = Input { Value = { 0.4, 0.6 }, },")
313
314 sw_nodes, sw_splines, out_op = build_switch_chain(cases, "BlackBG", "CB")
315 nodes.extend(sw_nodes)
316 nodes.append(make_saver(out_op, "matrix_color_blur"))
317 comp_path = ensure_dirs() / "comps" / "matrix_color_blur.comp"
318 comp_path.write_text(make_comp("\n".join(nodes + sw_splines), len(cases) - 1))
319 return comp_path, "matrix_color_blur", [(c[0], c[1]) for c in cases]
320
321
322def build_matrix_warps_shapes(assets: Dict[str, str]):
323 """Transform (Edges=0/1/2/3, Pivot, Angle, Aspect), DVE, CornerPositioner, Displace, Drip, Dent, Vortex, sRender+s*."""
324 nodes = [
325 make_loader("ColorLoader", assets["color"], post_mult=1),
326 make_loader("BumpLoader", assets["bump"], post_mult=1),
327 """\t\tBlackBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftAlpha = Input { Value = 1, }, }, },""",
328 ]
329 cases: List[Tuple[int, str, str]] = []
330 f = 0
331
332 for ed in (0, 1, 2, 3):
333 opn = f"Op_{f}"
334 nodes.append(f'\t\t{opn} = Transform {{ Inputs = {{ Input = Input {{ SourceOp = "ColorLoader", Source = "Output", }}, Center = Input {{ Value = {{ 0.72, 0.65 }}, }}, Pivot = Input {{ Value = {{ 0.25, 0.35 }}, }}, Size = Input {{ Value = 0.80, }}, Aspect = Input {{ Value = 1.35, }}, Angle = Input {{ Value = 28.0, }}, Edges = Input {{ Value = {ed}, }}, }}, }},')
335 cases.append((f, f"Transform_Edges={ed}_Pivot_Aspect", opn))
336 f += 1
337
338 warps = [
339 ("DVE_3D_Pivot", "DVE", 'Input = Input { SourceOp = "ColorLoader", Source = "Output", }, XRotation = Input { Value = 32, }, YRotation = Input { Value = -35, }, ZRotation = Input { Value = 18, }, ZMove = Input { Value = 1.35, }, Pivot = Input { Value = { 0.3, 0.6 }, }, Center = Input { Value = { 0.45, 0.55 }, },'),
340 ("CornerPositioner_Quad", "CornerPositioner", 'Input = Input { SourceOp = "ColorLoader", Source = "Output", }, TopLeft = Input { Value = { 0.15, 0.88 }, }, TopRight = Input { Value = { 0.92, 0.78 }, }, BottomLeft = Input { Value = { 0.08, 0.12 }, }, BottomRight = Input { Value = { 0.82, 0.22 }, },'),
341 ("Displace_Radial_Light", "Displace", 'Input = Input { SourceOp = "ColorLoader", Source = "Output", }, Foreground = Input { SourceOp = "BumpLoader", Source = "Output", }, Type = Input { Value = 0, }, RefractionStrength = Input { Value = 0.12, }, Spread = Input { Value = 0.25, }, LightPower = Input { Value = 0.6, },'),
342 ("Displace_XY_Offset", "Displace", 'Input = Input { SourceOp = "ColorLoader", Source = "Output", }, Foreground = Input { SourceOp = "BumpLoader", Source = "Output", }, Type = Input { Value = 1, }, XOffset = Input { Value = -0.5, }, YOffset = Input { Value = -0.5, }, XRefraction = Input { Value = 0.10, }, YRefraction = Input { Value = 0.08, },'),
343 ("Drip_Concentric", "Drip", 'Input = Input { SourceOp = "ColorLoader", Source = "Output", }, Center = Input { Value = { 0.45, 0.55 }, }, Strength = Input { Value = 1.0, }, Amplitude = Input { Value = 0.10, }, Frequency = Input { Value = 5.0, }, Phase = Input { Value = 0.4, }, Shape = Input { Value = 0, },'),
344 ("Dent_Bulge", "Dent", 'Input = Input { SourceOp = "ColorLoader", Source = "Output", }, Center = Input { Value = { 0.5, 0.5 }, }, Size = Input { Value = 0.65, }, Strength = Input { Value = 0.75, }, Type = Input { Value = 0, },'),
345 ("Dent_Pinch", "Dent", 'Input = Input { SourceOp = "ColorLoader", Source = "Output", }, Center = Input { Value = { 0.45, 0.55 }, }, Size = Input { Value = 0.60, }, Strength = Input { Value = 0.70, }, Type = Input { Value = 2, },'),
346 ("Vortex_Swirl", "Vortex", 'Input = Input { SourceOp = "ColorLoader", Source = "Output", }, Center = Input { Value = { 0.4, 0.6 }, }, Size = Input { Value = 0.65, }, Angle = Input { Value = 2.4, }, Power = Input { Value = 2.2, },'),
347 ]
348 for label, kind, inputs in warps:
349 opn = f"Op_{f}"
350 nodes.append(f"\t\t{opn} = {kind} {{ Inputs = {{ {inputs} }}, }},")
351 cases.append((f, label, opn))
352 f += 1
353
354 # sRender + sNGon / sRectangle / sEllipse / sTransform / sMerge / sBoolean / sOutline
355 nodes.append(
356 """\t\tS_NGon = sNGon { Inputs = { Sides = Input { Value = 5, }, Width = Input { Value = 0.45, }, Height = Input { Value = 0.45, }, Red = Input { Value = 0.95, }, Green = Input { Value = 0.3, }, Blue = Input { Value = 0.2, }, }, },
357\t\tS_Rect = sRectangle { Inputs = { Width = Input { Value = 0.35, }, Height = Input { Value = 0.35, }, CornerRadius = Input { Value = 0.08, }, ["Translate.X"] = Input { Value = 0.18, }, Red = Input { Value = 0.2, }, Green = Input { Value = 0.85, }, Blue = Input { Value = 0.4, }, }, },
358\t\tS_Ell = sEllipse { Inputs = { Width = Input { Value = 0.32, }, Height = Input { Value = 0.24, }, ["Translate.X"] = Input { Value = -0.15, }, ["Translate.Y"] = Input { Value = 0.15, }, Red = Input { Value = 0.25, }, Green = Input { Value = 0.55, }, Blue = Input { Value = 0.98, }, }, },
359\t\tS_XF = sTransform { Inputs = { Input = Input { SourceOp = "S_NGon", Source = "Output", }, XOffset = Input { Value = -0.15, }, YOffset = Input { Value = -0.10, }, ZRotation = Input { Value = 25.0, }, XSize = Input { Value = 0.85, }, YSize = Input { Value = 0.85, }, }, },
360\t\tS_Merge = sMerge { Inputs = { Input1 = Input { SourceOp = "S_XF", Source = "Output", }, Input2 = Input { SourceOp = "S_Rect", Source = "Output", }, }, },
361\t\tS_BoolSub = sBoolean { Inputs = { Operation = Input { Value = FuID { "Subtract" }, }, Input1 = Input { SourceOp = "S_Rect", Source = "Output", }, Input2 = Input { SourceOp = "S_Ell", Source = "Output", }, }, },
362\t\tS_BoolXor = sBoolean { Inputs = { Operation = Input { Value = FuID { "Xor" }, }, Input1 = Input { SourceOp = "S_NGon", Source = "Output", }, Input2 = Input { SourceOp = "S_Rect", Source = "Output", }, }, },
363\t\tS_Outl = sOutline { Inputs = { Input = Input { SourceOp = "S_Ell", Source = "Output", }, Thickness = Input { Value = 0.03, }, }, },"""
364 )
365 for label, s_src in [
366 ("sRender_NGon_XF_Merge", "S_Merge"),
367 ("sRender_sBoolean_Sub", "S_BoolSub"),
368 ("sRender_sBoolean_Xor", "S_BoolXor"),
369 ("sRender_sOutline_Ell", "S_Outl"),
370 ]:
371 opn = f"Op_{f}"
372 nodes.append(f'\t\t{opn} = sRender {{ Inputs = {{ Width = Input {{ Value = 256, }}, Height = Input {{ Value = 256, }}, Input = Input {{ SourceOp = "{s_src}", Source = "Output", }}, }}, }},')
373 cases.append((f, label, opn))
374 f += 1
375
376 sw_nodes, sw_splines, out_op = build_switch_chain(cases, "BlackBG", "WS")
377 nodes.extend(sw_nodes)
378 nodes.append(make_saver(out_op, "matrix_warps_shapes"))
379 comp_path = ensure_dirs() / "comps" / "matrix_warps_shapes.comp"
380 comp_path.write_text(make_comp("\n".join(nodes + sw_splines), len(cases) - 1))
381 return comp_path, "matrix_warps_shapes", [(c[0], c[1]) for c in cases]
382
383
384def build_matrix_3d(assets: Dict[str, str]):
385 """Cube3D, SurfaceFBXMesh, TextureTransformOperator, BumpMap, LightPoint (Linear/Quad), LightSpot, Duplicate3D, Displace3D, Override3D, ReplaceMaterial3D."""
386 nodes = [
387 make_loader("ColorLoader", assets["color"], post_mult=1),
388 make_loader("BumpLoader", assets["bump"], post_mult=1),
389 """\t\tBlackBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftAlpha = Input { Value = 1, }, }, },
390\t\tCamBase = Camera3D { Inputs = { ["Transform3DOp.Translate.Z"] = Input { Value = 4.2, }, AoV = Input { Value = 35.0, }, FilmGate = Input { Value = FuID { "User" }, }, ApertureW = Input { Value = 1.0, }, ApertureH = Input { Value = 1.0, }, }, },
391\t\tAmbLow = LightAmbient { Inputs = { Intensity = Input { Value = 0.20, }, }, },""",
392 ]
393 cases: List[Tuple[int, str, str]] = []
394 f = 0
395
396 def add_3d(label: str, scene_nodes: List[str], merge_inputs: str, lighting: int = 1) -> None:
397 nonlocal f
398 nodes.extend(scene_nodes)
399 m3d = f"M3D_{f}"
400 rnd = f"Op_{f}"
401 nodes.append(f"\t\t{m3d} = Merge3D {{ Inputs = {{ {merge_inputs} SceneInput9 = Input {{ SourceOp = \"CamBase\", Source = \"Output\", }}, }}, }},")
402 nodes.append(f'\t\t{rnd} = Renderer3D {{ Inputs = {{ Width = Input {{ Value = 256, }}, Height = Input {{ Value = 256, }}, ["RendererSoftware.LightingEnabled"] = Input {{ Value = {lighting}, }}, SceneInput = Input {{ SourceOp = "{m3d}", Source = "Output", }}, }}, }},')
403 cases.append((f, label, rnd))
404 f += 1
405
406 # 0: Cube3D textured
407 add_3d(
408 "Cube3D_Textured",
409 [
410 '\t\tTex0 = Texture2DOperator { Inputs = { Input = Input { SourceOp = "ColorLoader", Source = "Output", }, }, },',
411 '\t\tCube0 = Cube3D { Inputs = { ["SurfaceCubeInputs.Size"] = Input { Value = 1.4, }, ["Transform3DOp.Rotate.X"] = Input { Value = 25, }, ["Transform3DOp.Rotate.Y"] = Input { Value = 35, }, MaterialInput = Input { SourceOp = "Tex0", Source = "MaterialOutput", }, }, },',
412 ],
413 'SceneInput1 = Input { SourceOp = "Cube0", Source = "Output", },',
414 lighting=0,
415 )
416
417 # 1: SurfaceFBXMesh (cube.obj)
418 add_3d(
419 "SurfaceFBXMesh_OBJ",
420 [
421 '\t\tTex1 = Texture2DOperator { Inputs = { Input = Input { SourceOp = "ColorLoader", Source = "Output", }, }, },',
422 f'\t\tFbx1 = SurfaceFBXMesh {{ Inputs = {{ ImportFile = Input {{ Value = "{assets["cube_obj"]}", }}, ["Transform3DOp.Scale.X"] = Input {{ Value = 1.5, }}, ["Transform3DOp.Scale.Y"] = Input {{ Value = 1.5, }}, ["Transform3DOp.Scale.Z"] = Input {{ Value = 1.5, }}, ["Transform3DOp.Rotate.X"] = Input {{ Value = 25, }}, ["Transform3DOp.Rotate.Y"] = Input {{ Value = -35, }}, MaterialInput = Input {{ SourceOp = "Tex1", Source = "MaterialOutput", }}, }}, }},',
423 ],
424 'SceneInput1 = Input { SourceOp = "Fbx1", Source = "Output", },',
425 lighting=0,
426 )
427
428 # 2: TextureTransformOperator
429 add_3d(
430 "TextureTransformOperator",
431 [
432 '\t\tTex2 = Texture2DOperator { Inputs = { Input = Input { SourceOp = "ColorLoader", Source = "Output", }, }, },',
433 '\t\tTexXf2 = TextureTransformOperator { Inputs = { MaterialInput = Input { SourceOp = "Tex2", Source = "MaterialOutput", }, ["TranslationOffset.X"] = Input { Value = 0.25, }, ["TranslationOffset.Y"] = Input { Value = -0.15, }, ["Scale.X"] = Input { Value = 2.0, }, ["Scale.Y"] = Input { Value = 2.0, }, ["Rotation.Z"] = Input { Value = 30.0, }, WrapMode = Input { Value = FuID { "Wrap" }, }, }, },',
434 '\t\tPl2 = Shape3D { Inputs = { Shape = Input { Value = FuID { "SurfacePlaneInputs" }, }, ["SurfacePlaneInputs.Width"] = Input { Value = 2.2, }, ["SurfacePlaneInputs.Height"] = Input { Value = 2.2, }, MaterialInput = Input { SourceOp = "TexXf2", Source = "MaterialOutput", }, }, },',
435 ],
436 'SceneInput1 = Input { SourceOp = "Pl2", Source = "Output", },',
437 lighting=0,
438 )
439
440 # 3: BumpMap + MtlBlinn + LightPoint
441 add_3d(
442 "BumpMap_MtlBlinn",
443 [
444 '\t\tBm3 = BumpMap { Inputs = { Input = Input { SourceOp = "BumpLoader", Source = "Output", }, HeightScale = Input { Value = 4.0, }, }, },',
445 '\t\tMtl3 = MtlBlinn { Inputs = { ["Diffuse.Color.Red"] = Input { Value = 0.3, }, ["Diffuse.Color.Green"] = Input { Value = 0.7, }, ["Diffuse.Color.Blue"] = Input { Value = 0.95, }, ["Specular.Intensity"] = Input { Value = 1.0, }, ["Specular.Exponent"] = Input { Value = 28.0, }, ["Bumpmap.Material"] = Input { SourceOp = "Bm3", Source = "MaterialOutput", }, }, },',
446 '\t\tSph3 = Shape3D { Inputs = { Shape = Input { Value = FuID { "SurfaceSphereInputs" }, }, ["SurfaceSphereInputs.Radius"] = Input { Value = 1.0, }, MaterialInput = Input { SourceOp = "Mtl3", Source = "MaterialOutput", }, }, },',
447 '\t\tPt3 = LightPoint { Inputs = { ["Transform3DOp.Translate.X"] = Input { Value = 2.2, }, ["Transform3DOp.Translate.Y"] = Input { Value = 1.8, }, ["Transform3DOp.Translate.Z"] = Input { Value = 2.8, }, Intensity = Input { Value = 1.4, }, }, },',
448 ],
449 'SceneInput1 = Input { SourceOp = "Sph3", Source = "Output", }, SceneInput2 = Input { SourceOp = "Pt3", Source = "Output", }, SceneInput3 = Input { SourceOp = "AmbLow", Source = "Output", },',
450 lighting=1,
451 )
452
453 # 4 & 5: LightPoint Linear (DecayType=1) and Quadratic (DecayType=2)
454 for decay_t, d_name in ((1, "Linear"), (2, "Quadratic")):
455 add_3d(
456 f"LightPoint_Decay={d_name}",
457 [
458 f'\t\tMtl_{f} = MtlBlinn {{ Inputs = {{ ["Diffuse.Color.Red"] = Input {{ Value = 0.9, }}, ["Diffuse.Color.Green"] = Input {{ Value = 0.85, }}, ["Diffuse.Color.Blue"] = Input {{ Value = 0.75, }}, }}, }},',
459 f'\t\tPl_{f} = Shape3D {{ Inputs = {{ Shape = Input {{ Value = FuID {{ "SurfacePlaneInputs" }}, }}, ["SurfacePlaneInputs.Width"] = Input {{ Value = 2.8, }}, ["SurfacePlaneInputs.Height"] = Input {{ Value = 2.8, }}, MaterialInput = Input {{ SourceOp = "Mtl_{f}", Source = "MaterialOutput", }}, }}, }},',
460 f'\t\tPt_{f} = LightPoint {{ Inputs = {{ ["Transform3DOp.Translate.X"] = Input {{ Value = 0.8, }}, ["Transform3DOp.Translate.Y"] = Input {{ Value = 0.5, }}, ["Transform3DOp.Translate.Z"] = Input {{ Value = 1.6, }}, Intensity = Input {{ Value = 3.5, }}, DecayType = Input {{ Value = {decay_t}, }}, }}, }},',
461 ],
462 f'SceneInput1 = Input {{ SourceOp = "Pl_{f}", Source = "Output", }}, SceneInput2 = Input {{ SourceOp = "Pt_{f}", Source = "Output", }}, SceneInput3 = Input {{ SourceOp = "AmbLow", Source = "Output", }},',
463 lighting=1,
464 )
465
466 # 6: LightSpot
467 add_3d(
468 "LightSpot_ConePenumbra",
469 [
470 '\t\tMtl6 = MtlCookTorrance { Inputs = { ["Diffuse.Color.Red"] = Input { Value = 0.95, }, ["Diffuse.Color.Green"] = Input { Value = 0.75, }, ["Diffuse.Color.Blue"] = Input { Value = 0.45, }, ["Specular.Roughness"] = Input { Value = 0.3, }, }, },',
471 '\t\tPl6 = Shape3D { Inputs = { Shape = Input { Value = FuID { "SurfacePlaneInputs" }, }, ["SurfacePlaneInputs.Width"] = Input { Value = 3.0, }, ["SurfacePlaneInputs.Height"] = Input { Value = 3.0, }, MaterialInput = Input { SourceOp = "Mtl6", Source = "MaterialOutput", }, }, },',
472 '\t\tSp6 = LightSpot { Inputs = { ["Transform3DOp.Translate.X"] = Input { Value = -0.5, }, ["Transform3DOp.Translate.Z"] = Input { Value = 2.5, }, ["Transform3DOp.Rotate.Y"] = Input { Value = -10, }, ConeAngle = Input { Value = 35.0, }, PenumbraAngle = Input { Value = 12.0, }, Intensity = Input { Value = 1.8, }, DecayType = Input { Value = 1, }, }, },',
473 ],
474 'SceneInput1 = Input { SourceOp = "Pl6", Source = "Output", }, SceneInput2 = Input { SourceOp = "Sp6", Source = "Output", }, SceneInput3 = Input { SourceOp = "AmbLow", Source = "Output", },',
475 lighting=1,
476 )
477
478 # 7: Duplicate3D
479 add_3d(
480 "Duplicate3D_5x",
481 [
482 '\t\tBox7 = Shape3D { Inputs = { Shape = Input { Value = FuID { "SurfaceCubeInputs" }, }, ["SurfaceCubeInputs.Size"] = Input { Value = 0.35, }, ["Transform3DOp.Translate.X"] = Input { Value = -1.1, }, ["MtlStdInputs.Diffuse.Color.Red"] = Input { Value = 0.95, }, ["MtlStdInputs.Diffuse.Color.Green"] = Input { Value = 0.45, }, ["MtlStdInputs.Diffuse.Color.Blue"] = Input { Value = 0.15, }, }, },',
483 '\t\tDup7 = Duplicate3D { Inputs = { SceneInput = Input { SourceOp = "Box7", Source = "Output", }, FirstCopy = Input { Value = 0, }, LastCopy = Input { Value = 4, }, ["Translate.X"] = Input { Value = 0.55, }, ["Rotate.Z"] = Input { Value = 18.0, }, }, },',
484 ],
485 'SceneInput1 = Input { SourceOp = "Dup7", Source = "Output", },',
486 lighting=0,
487 )
488
489 # 8: Displace3D
490 add_3d(
491 "Displace3D_Bump",
492 [
493 '\t\tPl8 = Shape3D { Inputs = { Shape = Input { Value = FuID { "SurfacePlaneInputs" }, }, ["SurfacePlaneInputs.Width"] = Input { Value = 2.0, }, ["SurfacePlaneInputs.Height"] = Input { Value = 2.0, }, ["SurfacePlaneInputs.SubdivisionWidth"] = Input { Value = 32, }, ["SurfacePlaneInputs.SubdivisionHeight"] = Input { Value = 32, }, ["Transform3DOp.Rotate.X"] = Input { Value = -38.0, }, MaterialInput = Input { SourceOp = "ColorLoader", Source = "Output", }, }, },',
494 '\t\tDisp8 = Displace3D { Inputs = { SceneInput = Input { SourceOp = "Pl8", Source = "Output", }, Input = Input { SourceOp = "BumpLoader", Source = "Output", }, Scale = Input { Value = 0.6, }, }, },',
495 ],
496 'SceneInput1 = Input { SourceOp = "Disp8", Source = "Output", },',
497 lighting=0,
498 )
499
500 # 9: Override3D (hide + material override)
501 add_3d(
502 "Override3D_Hide_MatOvr",
503 [
504 '\t\tSph9L = Shape3D { Inputs = { Shape = Input { Value = FuID { "SurfaceSphereInputs" }, }, ["SurfaceSphereInputs.Radius"] = Input { Value = 0.55, }, ["Transform3DOp.Translate.X"] = Input { Value = -0.7, }, ["MtlStdInputs.Diffuse.Color.Red"] = Input { Value = 0.9, }, ["MtlStdInputs.Diffuse.Color.Green"] = Input { Value = 0.2, }, ["MtlStdInputs.Diffuse.Color.Blue"] = Input { Value = 0.2, }, }, },',
505 '\t\tOvr9Hide = Override3D { Inputs = { SceneInput = Input { SourceOp = "Sph9L", Source = "Output", }, ["Visibility.DoVisible"] = Input { Value = 1, }, ["Visibility.IsVisible"] = Input { Value = 0, }, }, },',
506 '\t\tSph9R = Shape3D { Inputs = { Shape = Input { Value = FuID { "SurfaceSphereInputs" }, }, ["SurfaceSphereInputs.Radius"] = Input { Value = 0.55, }, ["Transform3DOp.Translate.X"] = Input { Value = 0.7, }, }, },',
507 '\t\tTex9 = Texture2DOperator { Inputs = { Input = Input { SourceOp = "ColorLoader", Source = "Output", }, }, },',
508 '\t\tOvr9Mat = Override3D { Inputs = { SceneInput = Input { SourceOp = "Sph9R", Source = "Output", }, ["Material.DoMaterial"] = Input { Value = 1, }, MaterialInput = Input { SourceOp = "Tex9", Source = "MaterialOutput", }, }, },',
509 ],
510 'SceneInput1 = Input { SourceOp = "Ovr9Hide", Source = "Output", }, SceneInput2 = Input { SourceOp = "Ovr9Mat", Source = "Output", },',
511 lighting=0,
512 )
513
514 # 10: ReplaceMaterial3D
515 add_3d(
516 "ReplaceMaterial3D_Cook",
517 [
518 '\t\tTex10 = Texture2DOperator { Inputs = { Input = Input { SourceOp = "ColorLoader", Source = "Output", }, }, },',
519 '\t\tMtl10 = MtlCookTorrance { Inputs = { ["Diffuse.Color.Material"] = Input { SourceOp = "Tex10", Source = "MaterialOutput", }, ["Specular.Roughness"] = Input { Value = 0.25, }, }, },',
520 '\t\tSph10 = Shape3D { Inputs = { Shape = Input { Value = FuID { "SurfaceSphereInputs" }, }, ["SurfaceSphereInputs.Radius"] = Input { Value = 1.0, }, }, },',
521 '\t\tRep10 = ReplaceMaterial3D { Inputs = { SceneInput = Input { SourceOp = "Sph10", Source = "Output", }, MaterialInput = Input { SourceOp = "Mtl10", Source = "MaterialOutput", }, }, },',
522 '\t\tPt10 = LightPoint { Inputs = { ["Transform3DOp.Translate.X"] = Input { Value = 2.0, }, ["Transform3DOp.Translate.Y"] = Input { Value = 1.5, }, ["Transform3DOp.Translate.Z"] = Input { Value = 3.0, }, Intensity = Input { Value = 1.2, }, }, },',
523 ],
524 'SceneInput1 = Input { SourceOp = "Rep10", Source = "Output", }, SceneInput2 = Input { SourceOp = "Pt10", Source = "Output", }, SceneInput3 = Input { SourceOp = "AmbLow", Source = "Output", },',
525 lighting=1,
526 )
527
528 sw_nodes, sw_splines, out_op = build_switch_chain(cases, "BlackBG", "D3D")
529 nodes.extend(sw_nodes)
530 nodes.append(make_saver(out_op, "matrix_3d"))
531 comp_path = ensure_dirs() / "comps" / "matrix_3d.comp"
532 comp_path.write_text(make_comp("\n".join(nodes + sw_splines), len(cases) - 1))
533 return comp_path, "matrix_3d", [(c[0], c[1]) for c in cases]
534
535
536def build_matrix_misc(assets: Dict[str, str]):
537 """CustomTool (multi-input, getr1b, Setup1, Intermediate1, if), TimeSpeed, Switch, tool-level SourceOp instancing."""
538 nodes = [
539 make_loader("ColorLoader", assets["color"], post_mult=1),
540 make_loader("FGLoader", assets["fg"], post_mult=1),
541 """\t\tBlackBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftAlpha = Input { Value = 1, }, }, },
542\t\t-- CustomTool 0: Setup1, Intermediate1, if, getr1b, Image2
543\t\tOp_0 = Custom {
544\t\t\tInputs = {
545\t\t\t\tImage1 = Input { SourceOp = "ColorLoader", Source = "Output", },
546\t\t\t\tImage2 = Input { SourceOp = "FGLoader", Source = "Output", },
547\t\t\t\tNumberIn1 = Input { Value = 0.65, },
548\t\t\t\tPointIn1 = Input { Value = { 0.45, 0.55 }, },
549\t\t\t\tSetup1 = Input { Value = "1 - n1", },
550\t\t\t\tIntermediate1 = Input { Value = "max(0, 1 - dist(x, y, p1x, p1y) * 2)", },
551\t\t\t\tRedExpression = Input { Value = "if(x > p1x, getr1b(x - 0.1, y + 0.05), r2 * i1 + s1 * 0.2)", },
552\t\t\t\tGreenExpression = Input { Value = "if(y > p1y, g1 * i1, g2 + n1 * 0.1)", },
553\t\t\t\tBlueExpression = Input { Value = "b1 * (1 - i1) + b2 * i1", },
554\t\t\t\tAlphaExpression = Input { Value = "1", },
555\t\t\t},
556\t\t},
557\t\t-- TimeSpeed (frames 1 & 2 evaluate animated Transform at Speed=2.0, Delay=0.5)
558\t\tXfAnim = Transform {
559\t\t\tInputs = {
560\t\t\t\tInput = Input { SourceOp = "ColorLoader", Source = "Output", },
561\t\t\t\tAngle = Input { SourceOp = "TS_Angle", Source = "Value", },
562\t\t\t\tSize = Input { Value = 0.8, },
563\t\t\t},
564\t\t},
565\t\tOp_1 = TimeSpeed {
566\t\t\tInputs = {
567\t\t\t\tInput = Input { SourceOp = "XfAnim", Source = "Output", },
568\t\t\t\tSpeed = Input { Value = 2.0, },
569\t\t\t\tDelay = Input { Value = 0.5, },
570\t\t\t},
571\t\t},
572\t\t-- Switch (Fusion 21 native Source=0/1 with Input0/Input1)
573\t\tOp_2 = Switch {
574\t\t\tInputs = {
575\t\t\t\tSource = Input { Value = 0, },
576\t\t\t\tInput0 = Input { SourceOp = "ColorLoader", Source = "Output", },
577\t\t\t\tInput1 = Input { SourceOp = "FGLoader", Source = "Output", },
578\t\t\t},
579\t\t},
580\t\tOp_3 = Switch {
581\t\t\tInputs = {
582\t\t\t\tSource = Input { Value = 1, },
583\t\t\t\tInput0 = Input { SourceOp = "ColorLoader", Source = "Output", },
584\t\t\t\tInput1 = Input { SourceOp = "FGLoader", Source = "Output", },
585\t\t\t},
586\t\t},
587\t\t-- Tool-level SourceOp instancing
588\t\tMasterCC = ColorCorrector {
589\t\t\tInputs = {
590\t\t\t\tInput = Input { SourceOp = "ColorLoader", Source = "Output", },
591\t\t\t\tWheelHue1 = Input { Value = 0.25, },
592\t\t\t\tWheelSaturation1 = Input { Value = 1.45, },
593\t\t\t\tMasterRGBGain = Input { Value = 1.35, },
594\t\t\t\tMasterRGBGamma = Input { Value = 0.85, },
595\t\t\t},
596\t\t},
597\t\tOp_4 = ColorCorrector {
598\t\t\tSourceOp = "MasterCC",
599\t\t\tInputs = {
600\t\t\t\tInput = Input { SourceOp = "FGLoader", Source = "Output", },
601\t\t\t\tWheelHue1 = Input {},
602\t\t\t\tMasterRGBGain = Input { Value = 0.8, },
603\t\t\t},
604\t\t},
605\t\tOp_5 = Merge {
606\t\t\tInputs = {
607\t\t\t\tBackground = Input { SourceOp = "BlackBG", Source = "Output", },
608\t\t\t\tForeground = Input { SourceOp = "Op_4", Source = "Output", },
609\t\t\t},
610\t\t},""",
611 linear_spline("TS_Angle", {0: 0.0, 4: 180.0}),
612 ]
613 cases = [
614 (0, "CustomTool_multi_getr1b_Setup_Inter_if", "Op_0"),
615 (1, "TimeSpeed_f1_Speed2_Delay0.5", "Op_1"),
616 (2, "TimeSpeed_f2_Speed2_Delay0.5", "Op_1"),
617 (3, "Switch_Source0_Input0", "Op_2"),
618 (4, "Switch_Source1_Input1", "Op_3"),
619 (5, "SourceOp_Instance_ColorCorrector", "Op_5"),
620 ]
621 sw_nodes, sw_splines, out_op = build_switch_chain(cases, "BlackBG", "MS")
622 nodes.extend(sw_nodes)
623 nodes.append(make_saver(out_op, "matrix_misc"))
624 comp_path = ensure_dirs() / "comps" / "matrix_misc.comp"
625 comp_path.write_text(make_comp("\n".join(nodes + sw_splines), len(cases) - 1))
626 return comp_path, "matrix_misc", [(c[0], c[1]) for c in cases]
627
628
629def build_matrix_paint(assets: Dict[str, str]):
630 """Paint (PolylineStroke + WriteOnStart/End, BrushControls.Size/Softness, ApplyControls Color/Opacity, PaintApplyColor/Erase), Multistroke, PaintMask."""
631 nodes = [
632 make_loader("ColorLoader", assets["color"], post_mult=1),
633 """\t\tBlackBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftAlpha = Input { Value = 1, }, }, },
634\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, }, }, },
635\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, }, }, },
636\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, }, }, },""",
637 ]
638 cases: List[Tuple[int, str, str]] = []
639 f = 0
640
641 # 0: PolylineStroke SoftBrush basic
642 nodes.append(
643 """\t\tPS_0 = PolylineStroke {
644\t\t\tBrushes = { "SoftBrush" },
645\t\t\tApplyModes = { "PaintApplyColor" },
646\t\t\tInputs = {
647\t\t\t\tBrushControls = Input { Value = 1, },
648\t\t\t\tBrushShape = Input { Value = FuID { "SoftBrush" }, },
649\t\t\t\t["SoftBrush.Size"] = Input { Value = 0.08, },
650\t\t\t\t["SoftBrush.Softness"] = Input { Value = 0.5, },
651\t\t\t\t["PaintApplyColor.Red"] = Input { Value = 0.95, },
652\t\t\t\t["PaintApplyColor.Green"] = Input { Value = 0.40, },
653\t\t\t\t["PaintApplyColor.Blue"] = Input { Value = 0.12, },
654\t\t\t\t["PaintApplyColor.Opacity"] = Input { Value = 1.0, },
655\t\t\t\tPolyline = Input { Value = Polyline { Points = {
656\t\t\t\t\t{ X = -0.35, Y = -0.25, RX = 0.15, RY = 0.25 },
657\t\t\t\t\t{ X = 0.35, Y = 0.25, LX = -0.15, LY = -0.25 },
658\t\t\t\t} }, },
659\t\t\t},
660\t\t},
661\t\tOp_0 = Paint {
662\t\t\tInputs = {
663\t\t\t\tInput = Input { SourceOp = "DarkBG", Source = "Output", },
664\t\t\t\tPaint = Input { SourceOp = "PS_0", Source = "Out", },
665\t\t\t},
666\t\t},"""
667 )
668 cases.append((f, "Paint_Polyline_SoftBrush_0.5", "Op_0"))
669 f += 1
670
671 # 1: PolylineStroke SoftBrush Softness=1.0, Opacity=0.75
672 nodes.append(
673 """\t\tPS_1 = PolylineStroke {
674\t\t\tBrushes = { "SoftBrush" },
675\t\t\tApplyModes = { "PaintApplyColor" },
676\t\t\tInputs = {
677\t\t\t\tBrushControls = Input { Value = 1, },
678\t\t\t\tBrushShape = Input { Value = FuID { "SoftBrush" }, },
679\t\t\t\t["SoftBrush.Size"] = Input { Value = 0.14, },
680\t\t\t\t["SoftBrush.Softness"] = Input { Value = 1.0, },
681\t\t\t\t["PaintApplyColor.Red"] = Input { Value = 0.20, },
682\t\t\t\t["PaintApplyColor.Green"] = Input { Value = 0.90, },
683\t\t\t\t["PaintApplyColor.Blue"] = Input { Value = 0.45, },
684\t\t\t\t["PaintApplyColor.Opacity"] = Input { Value = 0.75, },
685\t\t\t\tPolyline = Input { Value = Polyline { Points = {
686\t\t\t\t\t{ Linear = true, X = -0.32, Y = 0.22 },
687\t\t\t\t\t{ Linear = true, X = 0.0, Y = -0.20 },
688\t\t\t\t\t{ Linear = true, X = 0.32, Y = 0.18 },
689\t\t\t\t} }, },
690\t\t\t},
691\t\t},
692\t\tOp_1 = Paint {
693\t\t\tInputs = {
694\t\t\t\tInput = Input { SourceOp = "ColorLoader", Source = "Output", },
695\t\t\t\tPaint = Input { SourceOp = "PS_1", Source = "Out", },
696\t\t\t},
697\t\t},"""
698 )
699 cases.append((f, "Paint_Polyline_Soft1_Opacity0.75", "Op_1"))
700 f += 1
701
702 # 2: PolylineStroke CircleBrush + WriteOnStart/WriteOnEnd
703 nodes.append(
704 """\t\tPS_2 = PolylineStroke {
705\t\t\tBrushes = { "CircleBrush" },
706\t\t\tApplyModes = { "PaintApplyColor" },
707\t\t\tInputs = {
708\t\t\t\tBrushControls = Input { Value = 1, },
709\t\t\t\tBrushShape = Input { Value = FuID { "CircleBrush" }, },
710\t\t\t\t["CircleBrush.Size"] = Input { Value = 0.10, },
711\t\t\t\t["PaintApplyColor.Red"] = Input { Value = 0.95, },
712\t\t\t\t["PaintApplyColor.Green"] = Input { Value = 0.20, },
713\t\t\t\t["PaintApplyColor.Blue"] = Input { Value = 0.85, },
714\t\t\t\t["PaintApplyColor.Opacity"] = Input { Value = 0.90, },
715\t\t\t\tWriteOnStart = Input { Value = 0.20, },
716\t\t\t\tWriteOnEnd = Input { Value = 0.75, },
717\t\t\t\tPolyline = Input { Value = Polyline { Points = {
718\t\t\t\t\t{ X = -0.35, Y = 0.0, RX = 0.12, RY = 0.30 },
719\t\t\t\t\t{ X = 0.35, Y = 0.0, LX = -0.12, LY = -0.30 },
720\t\t\t\t} }, },
721\t\t\t},
722\t\t},
723\t\tOp_2 = Paint {
724\t\t\tInputs = {
725\t\t\t\tInput = Input { SourceOp = "DarkBG", Source = "Output", },
726\t\t\t\tPaint = Input { SourceOp = "PS_2", Source = "Out", },
727\t\t\t},
728\t\t},"""
729 )
730 cases.append((f, "Paint_CircleBrush_WriteOn_0.2_0.75", "Op_2"))
731 f += 1
732
733 # 3: PolylineStroke Color -> Erase chain
734 nodes.append(
735 """\t\tPS_3a = PolylineStroke {
736\t\t\tBrushes = { "CircleBrush" },
737\t\t\tApplyModes = { "PaintApplyColor" },
738\t\t\tInputs = {
739\t\t\t\tBrushShape = Input { Value = FuID { "CircleBrush" }, },
740\t\t\t\t["CircleBrush.Size"] = Input { Value = 0.16, },
741\t\t\t\t["PaintApplyColor.Red"] = Input { Value = 0.95, },
742\t\t\t\t["PaintApplyColor.Green"] = Input { Value = 0.95, },
743\t\t\t\t["PaintApplyColor.Blue"] = Input { Value = 0.20, },
744\t\t\t\tPolyline = Input { Value = Polyline { Points = {
745\t\t\t\t\t{ Linear = true, X = -0.35, Y = 0.0 },
746\t\t\t\t\t{ Linear = true, X = 0.35, Y = 0.0 },
747\t\t\t\t} }, },
748\t\t\t},
749\t\t},
750\t\tPS_3b = PolylineStroke {
751\t\t\tBrushes = { "SoftBrush" },
752\t\t\tApplyModes = { "PaintApplyErase" },
753\t\t\tInputs = {
754\t\t\t\tPaint = Input { SourceOp = "PS_3a", Source = "Out", },
755\t\t\t\tBrushShape = Input { Value = FuID { "SoftBrush" }, },
756\t\t\t\tApplyMode = Input { Value = FuID { "PaintApplyErase" }, },
757\t\t\t\t["SoftBrush.Size"] = Input { Value = 0.09, },
758\t\t\t\t["SoftBrush.Softness"] = Input { Value = 0.4, },
759\t\t\t\t["PaintApplyErase.Opacity"] = Input { Value = 1.0, },
760\t\t\t\tPolyline = Input { Value = Polyline { Points = {
761\t\t\t\t\t{ Linear = true, X = 0.0, Y = -0.30 },
762\t\t\t\t\t{ Linear = true, X = 0.0, Y = 0.30 },
763\t\t\t\t} }, },
764\t\t\t},
765\t\t},
766\t\tOp_3 = Paint {
767\t\t\tInputs = {
768\t\t\t\tInput = Input { SourceOp = "ColorLoader", Source = "Output", },
769\t\t\t\tPaint = Input { SourceOp = "PS_3b", Source = "Out", },
770\t\t\t},
771\t\t},"""
772 )
773 cases.append((f, "Paint_Color_Then_Erase", "Op_3"))
774 f += 1
775
776 # 4: Multistroke with Time/Frames/Duration & per-stroke Params overrides (tested at frame 4)
777 nodes.append(
778 """\t\tMS_4 = Multistroke {
779\t\t\tBrushes = { "SoftBrush", "CircleBrush" },
780\t\t\tApplyModes = { "PaintApplyColor", "PaintApplyErase" },
781\t\t\tInputs = {
782\t\t\t\tBrushShape = Input { Value = FuID { "SoftBrush" }, },
783\t\t\t\t["SoftBrush.Size"] = Input { Value = 0.09, },
784\t\t\t\t["SoftBrush.Softness"] = Input { Value = 0.5, },
785\t\t\t\t["PaintApplyColor.Red"] = Input { Value = 0.25, },
786\t\t\t\t["PaintApplyColor.Green"] = Input { Value = 0.75, },
787\t\t\t\t["PaintApplyColor.Blue"] = Input { Value = 1.0, },
788\t\t\t},
789\t\t\tStrokes = {
790\t\t\t\t{
791\t\t\t\t\tTime = 0,
792\t\t\t\t\tFrames = 10,
793\t\t\t\t\tParams = {
794\t\t\t\t\t\tDuration = { Value = 10 },
795\t\t\t\t\t\t["SoftBrush.Size"] = { Value = 0.09 },
796\t\t\t\t\t\t["PaintApplyColor.Red"] = { Value = 0.25 },
797\t\t\t\t\t\t["PaintApplyColor.Green"] = { Value = 0.75 },
798\t\t\t\t\t\t["PaintApplyColor.Blue"] = { Value = 1.0 },
799\t\t\t\t\t},
800\t\t\t\t\t{ X = -0.35, Y = -0.20, T = 0 },
801\t\t\t\t\t{ X = 0.35, Y = 0.20, T = 10 },
802\t\t\t\t},
803\t\t\t\t{
804\t\t\t\t\tTime = 3,
805\t\t\t\t\tFrames = 4,
806\t\t\t\t\tParams = {
807\t\t\t\t\t\tDuration = { Value = 4 },
808\t\t\t\t\t\t["SoftBrush.Size"] = { Value = 0.12 },
809\t\t\t\t\t\t["PaintApplyColor.Red"] = { Value = 1.0 },
810\t\t\t\t\t\t["PaintApplyColor.Green"] = { Value = 0.2 },
811\t\t\t\t\t\t["PaintApplyColor.Blue"] = { Value = 0.2 },
812\t\t\t\t\t\t["PaintApplyColor.Opacity"] = { Value = 0.8 },
813\t\t\t\t\t},
814\t\t\t\t\t{ X = -0.30, Y = 0.25, T = 0 },
815\t\t\t\t\t{ X = 0.30, Y = -0.25, T = 10 },
816\t\t\t\t},
817\t\t\t\t{
818\t\t\t\t\tTime = 0,
819\t\t\t\t\tFrames = 2,
820\t\t\t\t\tParams = { Duration = { Value = 2 }, },
821\t\t\t\t\t{ X = 0.0, Y = 0.0, T = 0 },
822\t\t\t\t},
823\t\t\t},
824\t\t},
825\t\tOp_4 = Paint {
826\t\t\tInputs = {
827\t\t\t\tInput = Input { SourceOp = "DarkBG", Source = "Output", },
828\t\t\t\tPaint = Input { SourceOp = "MS_4", Source = "Out", },
829\t\t\t},
830\t\t},"""
831 )
832 cases.append((f, "Paint_Multistroke_Timed_Params", "Op_4"))
833 f += 1
834
835 # 5: PaintMask with SoftEdge + Level
836 nodes.append(
837 """\t\tPS_5 = PolylineStroke {
838\t\t\tBrushes = { "SoftBrush" },
839\t\t\tApplyModes = { "PaintApplyColor" },
840\t\t\tInputs = {
841\t\t\t\tBrushShape = Input { Value = FuID { "SoftBrush" }, },
842\t\t\t\t["SoftBrush.Size"] = Input { Value = 0.12, },
843\t\t\t\t["SoftBrush.Softness"] = Input { Value = 0.5, },
844\t\t\t\t["PaintApplyColor.Opacity"] = Input { Value = 0.85, },
845\t\t\t\tPolyline = Input { Value = Polyline { Points = {
846\t\t\t\t\t{ X = -0.30, Y = -0.25, RX = 0.20, RY = 0.0 },
847\t\t\t\t\t{ X = 0.30, Y = 0.25, LX = -0.20, LY = 0.0 },
848\t\t\t\t} }, },
849\t\t\t},
850\t\t},
851\t\tPM_5 = PaintMask {
852\t\t\tInputs = {
853\t\t\t\tMaskWidth = Input { Value = 256, },
854\t\t\t\tMaskHeight = Input { Value = 256, },
855\t\t\t\tSoftEdge = Input { Value = 0.02, },
856\t\t\t\tLevel = Input { Value = 0.9, },
857\t\t\t\tPaint = Input { SourceOp = "PS_5", Source = "Out", },
858\t\t\t},
859\t\t},
860\t\tOp_5 = Merge {
861\t\t\tInputs = {
862\t\t\t\tBackground = Input { SourceOp = "BlackBG", Source = "Output", },
863\t\t\t\tForeground = Input { SourceOp = "WhiteFG", Source = "Output", },
864\t\t\t\tEffectMask = Input { SourceOp = "PM_5", Source = "Mask", },
865\t\t\t},
866\t\t},"""
867 )
868 cases.append((f, "PaintMask_SoftEdge_Level", "Op_5"))
869 f += 1
870
871 # 6: PaintMask with Erase + Invert=1
872 nodes.append(
873 """\t\tPS_6a = PolylineStroke {
874\t\t\tBrushes = { "CircleBrush" },
875\t\t\tApplyModes = { "PaintApplyColor" },
876\t\t\tInputs = {
877\t\t\t\tBrushShape = Input { Value = FuID { "CircleBrush" }, },
878\t\t\t\t["CircleBrush.Size"] = Input { Value = 0.18, },
879\t\t\t\tPolyline = Input { Value = Polyline { Points = {
880\t\t\t\t\t{ Linear = true, X = -0.32, Y = 0.0 },
881\t\t\t\t\t{ Linear = true, X = 0.32, Y = 0.0 },
882\t\t\t\t} }, },
883\t\t\t},
884\t\t},
885\t\tPS_6b = PolylineStroke {
886\t\t\tBrushes = { "CircleBrush" },
887\t\t\tApplyModes = { "PaintApplyErase" },
888\t\t\tInputs = {
889\t\t\t\tPaint = Input { SourceOp = "PS_6a", Source = "Out", },
890\t\t\t\tBrushShape = Input { Value = FuID { "CircleBrush" }, },
891\t\t\t\tApplyMode = Input { Value = FuID { "PaintApplyErase" }, },
892\t\t\t\t["CircleBrush.Size"] = Input { Value = 0.08, },
893\t\t\t\tPolyline = Input { Value = Polyline { Points = {
894\t\t\t\t\t{ Linear = true, X = 0.0, Y = -0.25 },
895\t\t\t\t\t{ Linear = true, X = 0.0, Y = 0.25 },
896\t\t\t\t} }, },
897\t\t\t},
898\t\t},
899\t\tPM_6 = PaintMask {
900\t\t\tInputs = {
901\t\t\t\tMaskWidth = Input { Value = 256, },
902\t\t\t\tMaskHeight = Input { Value = 256, },
903\t\t\t\tInvert = Input { Value = 1, },
904\t\t\t\tPaint = Input { SourceOp = "PS_6b", Source = "Out", },
905\t\t\t},
906\t\t},
907\t\tOp_6 = Merge {
908\t\t\tInputs = {
909\t\t\t\tBackground = Input { SourceOp = "BlackBG", Source = "Output", },
910\t\t\t\tForeground = Input { SourceOp = "WhiteFG", Source = "Output", },
911\t\t\t\tEffectMask = Input { SourceOp = "PM_6", Source = "Mask", },
912\t\t\t},
913\t\t},"""
914 )
915 cases.append((f, "PaintMask_Erase_Invert1", "Op_6"))
916 f += 1
917
918 # 7: Paint with Blend=0.6 + EffectMask (dedicated PolylineStroke so Fusion does not share PS_0)
919 nodes.append(
920 """\t\tPS_7 = PolylineStroke {
921\t\t\tBrushes = { "SoftBrush" },
922\t\t\tApplyModes = { "PaintApplyColor" },
923\t\t\tInputs = {
924\t\t\t\tBrushControls = Input { Value = 1, },
925\t\t\t\tBrushShape = Input { Value = FuID { "SoftBrush" }, },
926\t\t\t\t["SoftBrush.Size"] = Input { Value = 0.08, },
927\t\t\t\t["SoftBrush.Softness"] = Input { Value = 0.5, },
928\t\t\t\t["PaintApplyColor.Red"] = Input { Value = 0.95, },
929\t\t\t\t["PaintApplyColor.Green"] = Input { Value = 0.40, },
930\t\t\t\t["PaintApplyColor.Blue"] = Input { Value = 0.12, },
931\t\t\t\t["PaintApplyColor.Opacity"] = Input { Value = 1.0, },
932\t\t\t\tPolyline = Input { Value = Polyline { Points = {
933\t\t\t\t\t{ X = -0.35, Y = -0.25, RX = 0.15, RY = 0.25 },
934\t\t\t\t\t{ X = 0.35, Y = 0.25, LX = -0.15, LY = -0.25 },
935\t\t\t\t} }, },
936\t\t\t},
937\t\t},
938\t\tOp_7 = Paint {
939\t\t\tInputs = {
940\t\t\t\tBlend = Input { Value = 0.6, },
941\t\t\t\tInput = Input { SourceOp = "ColorLoader", Source = "Output", },
942\t\t\t\tPaint = Input { SourceOp = "PS_7", Source = "Out", },
943\t\t\t\tEffectMask = Input { SourceOp = "MaskEll", Source = "Mask", },
944\t\t\t},
945\t\t},"""
946 )
947 cases.append((f, "Paint_Blend0.6_EffectMask", "Op_7"))
948 f += 1
949
950 sw_nodes, sw_splines, out_op = build_switch_chain(cases, "BlackBG", "PT")
951 nodes.extend(sw_nodes)
952 nodes.append(make_saver(out_op, "matrix_paint"))
953 comp_path = ensure_dirs() / "comps" / "matrix_paint.comp"
954 comp_path.write_text(make_comp("\n".join(nodes + sw_splines), len(cases) - 1))
955 return comp_path, "matrix_paint", [(c[0], c[1]) for c in cases]
956
957
958MATRIX_BUILDERS = {
959 "matrix_merge_modes": build_matrix_merge_modes,
960 "matrix_hdr_depth": build_matrix_hdr_depth,
961 "matrix_masks": build_matrix_masks,
962 "matrix_color_blur": build_matrix_color_blur,
963 "matrix_warps_shapes": build_matrix_warps_shapes,
964 "matrix_3d": build_matrix_3d,
965 "matrix_misc": build_matrix_misc,
966 "matrix_paint": build_matrix_paint,
967}
968
969
scripts/diff_fuzz/runner.py created+314
......@@ -0,0 +1,314 @@
1"""Render both engines (sg render + render-check), batch/bisect fuzz graphs, and print result tables."""
2
3import shutil
4import subprocess
5import time
6from pathlib import Path
7from typing import Any, Dict, List, Optional, Tuple
8
9from .assets import (
10 CONTAINER_ROOT,
11 REMOTE_ROOT,
12 compute_diff_metrics,
13 ensure_dirs,
14 ensure_render_check,
15 make_comp,
16 make_saver,
17 build_switch_chain,
18 use_smb,
19)
20from .fuzzer import FuzzGraph, SplineParam
21
22
23
24
25def run_comp_both(
26 comp_path: Path,
27 prefix: str,
28 frames: List[int],
29 labels: Dict[int, str],
30 render_gt: bool = True,
31 timeout_sec: int = 180,
32) -> Dict[int, Dict[str, Any]]:
33 """Renders comp via sg render (if render_gt) and render-check --render, returning per-frame metrics."""
34 root = ensure_dirs()
35 rc_bin = ensure_render_check()
36 start_f, end_f = min(frames), max(frames)
37
38 gt_error: Optional[str] = None
39 if render_gt:
40 if use_smb():
41 target_comp = str(comp_path)
42 else:
43 remote_comp = f"{REMOTE_ROOT}/comps/{comp_path.name}"
44 subprocess.run(["sg", "upload", str(comp_path), remote_comp], check=True, timeout=60)
45 target_comp = remote_comp
46
47 # Clear stale GT frames for this prefix
48 gt_dir = root / "gt"
49 for f in frames:
50 p = gt_dir / f"{prefix}_{f:04d}.png"
51 if p.exists():
52 p.unlink()
53
54 try:
55 cmd = ["sg", "render", target_comp, "--start", str(start_f), "--end", str(end_f)]
56 proc = subprocess.run(cmd, check=True, capture_output=True, text=True, timeout=timeout_sec)
57 combined_out = (proc.stdout or "") + "\n" + (proc.stderr or "")
58 if "ERROR: Render failed" in combined_out:
59 err_lines = [ln.strip() for ln in combined_out.splitlines() if "fail" in ln.lower() or "error" in ln.lower()]
60 gt_error = "sg render error: " + " | ".join(err_lines[:4])
61 except subprocess.TimeoutExpired:
62 gt_error = f"sg render timed out after {timeout_sec}s"
63 except subprocess.CalledProcessError as e:
64 gt_error = f"sg render failed (rc={e.returncode}): {(e.stderr or e.stdout or '').strip()[:300]}"
65
66 if use_smb() and gt_error is None:
67 # Wait briefly for SMB directory cache to surface newly written GT frames
68 expected_gt = [gt_dir / f"{prefix}_{f:04d}.png" for f in frames]
69 deadline = time.time() + 8.0
70 while not all(p.exists() for p in expected_gt) and time.time() < deadline:
71 _ = list(gt_dir.glob(f"{prefix}_*.png"))
72 time.sleep(0.25)
73
74 if not use_smb() and gt_error is None:
75 for f in frames:
76 fname = f"{prefix}_{f:04d}.png"
77 try:
78 subprocess.run(
79 ["sg", "download", f"{REMOTE_ROOT}/gt/{fname}", str(gt_dir / fname)],
80 check=True,
81 capture_output=True,
82 timeout=60,
83 )
84 except subprocess.CalledProcessError as e:
85 gt_error = f"sg download failed for {fname}: {e}"
86 break
87
88 eval_comp = comp_path
89 if not use_smb():
90 txt = comp_path.read_text().replace(CONTAINER_ROOT, str(root))
91 eval_comp = comp_path.with_suffix(".local.comp")
92 eval_comp.write_text(txt)
93
94 ours_sub = root / "ours" / prefix
95 if ours_sub.exists():
96 shutil.rmtree(ours_sub, ignore_errors=True)
97 ours_sub.mkdir(parents=True, exist_ok=True)
98
99 rc_error: Optional[str] = None
100 try:
101 subprocess.run(
102 [str(rc_bin), str(eval_comp), "--render", f"{start_f}..{end_f}", "--out-dir", str(ours_sub)],
103 check=True,
104 capture_output=True,
105 text=True,
106 timeout=timeout_sec,
107 )
108 except subprocess.TimeoutExpired:
109 rc_error = f"render-check timed out after {timeout_sec}s"
110 except subprocess.CalledProcessError as e:
111 rc_error = f"render-check failed (rc={e.returncode}): {(e.stderr or e.stdout or '').strip()[:300]}"
112
113 results: Dict[int, Dict[str, Any]] = {}
114 for f in frames:
115 label = labels.get(f, f"f{f}")
116 if gt_error is not None:
117 results[f] = {"frame": f, "label": label, "error": gt_error, "mae_pct": 100.0, "mae_255": 255.0, "rmse_255": 255.0}
118 continue
119 if rc_error is not None:
120 results[f] = {"frame": f, "label": label, "error": rc_error, "mae_pct": 100.0, "mae_255": 255.0, "rmse_255": 255.0}
121 continue
122 gt_p = root / "gt" / f"{prefix}_{f:04d}.png"
123 ours_p = ours_sub / f"{f:04d}.png"
124 m = compute_diff_metrics(ours_p, gt_p)
125 m["frame"] = f
126 m["label"] = label
127 results[f] = m
128 return results
129
130
131
132
133def write_standalone_graph_comp(graph: FuzzGraph, prefix: str) -> Path:
134 root = ensure_dirs()
135 tool_blocks, aux_blocks, out_op = graph.to_lua_defs(prefix="", frame_shift=0)
136 # Normalize over BlackBG so Saver compares RGB over opaque black consistently
137 tool_blocks.append('\t\t_BlackBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftAlpha = Input { Value = 1, }, }, },')
138 tool_blocks.append(f'\t\t_NormOut = Merge {{ Inputs = {{ Background = Input {{ SourceOp = "_BlackBG", Source = "Output", }}, Foreground = Input {{ SourceOp = "{out_op}", Source = "Output", }}, }}, }},')
139 tool_blocks.append(make_saver("_NormOut", prefix))
140 comp_path = root / "comps" / f"{prefix}.comp"
141 comp_path.write_text(make_comp("\n".join(tool_blocks + aux_blocks), graph.eval_frame, start_frame=graph.eval_frame))
142 return comp_path
143
144
145def run_multi_graph_batch(
146 items: List[Tuple[str, FuzzGraph]],
147 batch_prefix: str,
148 render_gt: bool = True,
149 timeout_sec: int = 180,
150) -> Dict[int, Dict[str, Any]]:
151 """Packs multiple FuzzGraphs into one multi-frame .comp using a Merge switch chain."""
152 root = ensure_dirs()
153 all_tools = [
154 '\t\t_BlackBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftAlpha = Input { Value = 1, }, }, },'
155 ]
156 all_aux: List[str] = []
157 cases: List[Tuple[int, str, str]] = []
158 labels: Dict[int, str] = {}
159
160 for f_idx, (label, g) in enumerate(items):
161 pfx = f"G{f_idx}_"
162 frame_shift = f_idx - g.eval_frame
163 tb, ab, out_op = g.to_lua_defs(prefix=pfx, frame_shift=frame_shift)
164 all_tools.extend(tb)
165 all_aux.extend(ab)
166 cases.append((f_idx, label, out_op))
167 labels[f_idx] = label
168
169 sw_nodes, sw_splines, final_op = build_switch_chain(cases, "_BlackBG", "FB")
170 all_tools.extend(sw_nodes)
171 all_aux.extend(sw_splines)
172 all_tools.append(make_saver(final_op, batch_prefix))
173
174 comp_path = root / "comps" / f"{batch_prefix}.comp"
175 comp_path.write_text(make_comp("\n".join(all_tools + all_aux), len(cases) - 1, start_frame=0))
176 return run_comp_both(
177 comp_path,
178 batch_prefix,
179 list(range(len(cases))),
180 labels,
181 render_gt=render_gt,
182 timeout_sec=timeout_sec,
183 )
184
185
186def bisect_failing_graph(
187 graph: FuzzGraph,
188 threshold_pct: float,
189 render_gt: bool = True,
190 timeout_sec: int = 180,
191) -> Dict[str, Any]:
192 """Node-by-node graph bisection that trims downstream & upstream nodes while preserving MAE > threshold."""
193 seed = graph.seed
194 print(f" [bisect] seed={seed} ({len(graph.nodes)} nodes) ...", flush=True)
195
196 # Step 0: Verify standalone reproduction
197 st_prefix = f"bisect_s{seed}_orig"
198 st_comp = write_standalone_graph_comp(graph, st_prefix)
199 st_res = run_comp_both(
200 st_comp, st_prefix, [graph.eval_frame], {graph.eval_frame: f"seed_{seed}"}, render_gt=render_gt, timeout_sec=timeout_sec
201 )[graph.eval_frame]
202 orig_mae = st_res["mae_pct"]
203 if orig_mae <= threshold_pct:
204 return {
205 "seed": seed,
206 "reproduced_standalone": False,
207 "orig_mae_pct": orig_mae,
208 "min_mae_pct": orig_mae,
209 "min_rmse_255": st_res["rmse_255"],
210 "note": "batch failure did not reproduce standalone",
211 "tools": graph.summary_tools(),
212 }
213
214 # Step 1: Prefix trim (find earliest failing sink node in topological order)
215 non_src = [n for n in graph.nodes if not n.is_source]
216 cur = graph.clone()
217 if len(non_src) > 1:
218 prefix_items = [(f"prefix_{nd.name}", graph.prune_to(nd.name)) for nd in non_src]
219 pref_res = run_multi_graph_batch(
220 prefix_items, f"bisect_s{seed}_prefixes", render_gt=render_gt, timeout_sec=timeout_sec
221 )
222 for idx, nd in enumerate(non_src):
223 if pref_res[idx]["mae_pct"] > threshold_pct:
224 cur = graph.prune_to(nd.name)
225 print(f" [prefix] trimmed sink to {nd.name} ({len(cur.nodes)} nodes, MAE={pref_res[idx]['mae_pct']:.2f}%)", flush=True)
226 break
227
228 # Step 2: Iterative upstream node & mask removal + spline flattening
229 for rnd in range(6):
230 candidates: List[Tuple[str, str, FuzzGraph]] = [] # (desc, action, candidate_graph)
231 # Try flattening splines first
232 flat = cur.flatten_splines()
233 if flat is not None:
234 candidates.append(("flatten_splines", "flatten", flat))
235 # Try stripping masks
236 for nd in cur.nodes:
237 if nd.mask is not None:
238 sm = cur.strip_mask(nd.name)
239 if sm is not None:
240 candidates.append((f"strip_mask:{nd.name}", "mask", sm))
241 # Try bypassing each upstream non-source node
242 for nd in cur.nodes:
243 if not nd.is_source and nd.name != cur.output_node():
244 bp = cur.bypass_node(nd.name)
245 if bp is not None:
246 candidates.append((f"bypass:{nd.name}", "bypass", bp))
247
248 if not candidates:
249 break
250
251 batch_items = [(desc, cg) for desc, _act, cg in candidates]
252 cand_res = run_multi_graph_batch(
253 batch_items, f"bisect_s{seed}_r{rnd}", render_gt=render_gt, timeout_sec=timeout_sec
254 )
255
256 # Pick best failing candidate: fewest nodes, fewest masks, no splines
257 failing: List[Tuple[Tuple[int, int, int], str, FuzzGraph, float]] = []
258 for idx, (desc, _act, cg) in enumerate(candidates):
259 m = cand_res[idx]
260 if m["mae_pct"] > threshold_pct:
261 mask_cnt = sum(1 for x in cg.nodes if x.mask is not None)
262 spline_cnt = sum(
263 1 for x in cg.nodes for v in x.params.values() if isinstance(v, SplineParam)
264 )
265 score = (len(cg.nodes), mask_cnt, spline_cnt)
266 failing.append((score, desc, cg, m["mae_pct"]))
267
268 if not failing:
269 break
270 failing.sort(key=lambda t: t[0])
271 _score, best_desc, best_cg, best_mae = failing[0]
272 cur = best_cg
273 print(f" [round {rnd}] {best_desc} -> {len(cur.nodes)} nodes (MAE={best_mae:.2f}%)", flush=True)
274
275 # Step 3: Standalone verification of minimal reproducer
276 repro_prefix = f"repro_seed_{seed}"
277 repro_comp = write_standalone_graph_comp(cur, repro_prefix)
278 final_res = run_comp_both(
279 repro_comp, repro_prefix, [cur.eval_frame], {cur.eval_frame: repro_prefix}, render_gt=render_gt, timeout_sec=timeout_sec
280 )[cur.eval_frame]
281
282 return {
283 "seed": seed,
284 "reproduced_standalone": True,
285 "orig_node_count": len(graph.nodes),
286 "min_node_count": len(cur.nodes),
287 "orig_mae_pct": orig_mae,
288 "min_mae_pct": final_res["mae_pct"],
289 "min_rmse_255": final_res["rmse_255"],
290 "comp_path": str(repro_comp),
291 "eval_frame": cur.eval_frame,
292 "tools": cur.summary_tools(),
293 }
294
295
296def print_table(title: str, rows: List[Dict[str, Any]], threshold_pct: float) -> None:
297 print(f"\n=== {title} ===")
298 print(f" {'Case':<44s} | {'MAE%':>7s} | {'MAE':>6s} | {'RMSE':>6s} | {'Status'}")
299 print(f" {'-'*44}-+-{'-'*7}-+-{'-'*6}-+-{'-'*6}-+-{'-'*18}")
300 for r in rows:
301 label = str(r.get("label", ""))[:44]
302 mae_pct = r.get("mae_pct", 100.0)
303 mae = r.get("mae_255", 255.0)
304 rmse = r.get("rmse_255", 255.0)
305 if r.get("error"):
306 status = f"ERR: {str(r['error'])[:28]}"
307 elif r.get("size_mismatch"):
308 status = f"SIZE {r.get('dims_ours')}!={r.get('dims_gt')}"
309 elif mae_pct > threshold_pct:
310 status = "FAIL"
311 else:
312 status = "PASS"
313 print(f" {label:<44s} | {mae_pct:6.2f}% | {mae:6.2f} | {rmse:6.2f} | {status}")
314