From 8ee57b10bd34e1327dca9974ff6854a7c8b0a3eb Mon Sep 17 00:00:00 2001 From: clover caruso Date: Mon, 30 Nov 2026 16:14:53 -0800 Subject: [PATCH] Add Csmith-style differential fuzzer and parameter matrix (#21) --- scripts/diff_fuzz.py | 2296 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 2296 insertions(+) create mode 100644 scripts/diff_fuzz.py diff --git a/scripts/diff_fuzz.py b/scripts/diff_fuzz.py new file mode 100644 index 0000000000000000000000000000000000000000..56eda76a3d614b62238f5054a3a17c4454a39240 --- /dev/null +++ b/scripts/diff_fuzz.py @@ -0,0 +1,2296 @@ +#!/usr/bin/env python3 +"""Csmith-style differential testing & fuzzing harness: Fusion Render Node 21.1 (sg render) vs Fission (render-check). + +Generates synthetic test plates & OBJ geometry (pure Python stdlib, no PIL/numpy), +runs an exhaustive edge-case parameter matrix (--matrix) across Merge, HDR/BitDepth, +Masks, Color/Blur/Glow, Warps/Shapes, 3D, and Misc tools, and runs a seeded randomized +DAG fuzzer (--fuzz) with automatic node-by-node graph bisection (--bisect). +""" + +import argparse +import json +import math +import os +import random +import re +import shutil +import struct +import subprocess +import sys +import time +import zlib +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Dict, List, Optional, Tuple + +REPO = Path("/Users/clo/dev/compositor") +RENDER_CHECK = REPO / "target/release/render-check" +SMB_ROOT = Path("/Volumes/clover/Project/CloverCompositor/probes/diff_fuzz") +REMOTE_ROOT = "/srv/clover/Project/CloverCompositor/probes/diff_fuzz" +CONTAINER_ROOT = "/Volumes/clover/Project/CloverCompositor/probes/diff_fuzz" +LOCAL_FALLBACK = Path("/tmp/fission_diff_fuzz") + +# --------------------------------------------------------------------------- +# Storage / SG Transport Helpers +# --------------------------------------------------------------------------- + + +def use_smb() -> bool: + return Path("/Volumes/clover/Project/CloverCompositor").exists() + + +def local_root() -> Path: + return SMB_ROOT if use_smb() else LOCAL_FALLBACK + + +def ensure_dirs() -> Path: + root = local_root() + for sub in ("assets", "comps", "gt", "ours"): + (root / sub).mkdir(parents=True, exist_ok=True) + return root + + +def sync_asset_to_remote(local_path: Path) -> None: + if not use_smb(): + subprocess.run( + ["sg", "upload", str(local_path), f"{REMOTE_ROOT}/assets/{local_path.name}"], + check=True, + timeout=60, + ) + + +def ensure_render_check() -> Path: + if RENDER_CHECK.exists(): + return RENDER_CHECK + print(f"[build] {RENDER_CHECK} missing; building render-check --release...", file=sys.stderr) + subprocess.run( + ["cargo", "build", "--release", "-p", "engine", "--bin", "render-check"], + cwd=str(REPO), + check=True, + timeout=600, + ) + return RENDER_CHECK + + +# --------------------------------------------------------------------------- +# Pure Python Stdlib PNG Encoder / Decoder & Diff Metrics +# --------------------------------------------------------------------------- + + +def write_png_rgba(path: Path, w: int, h: int, rgba_bytes: bytes) -> None: + def chunk(tag: bytes, data: bytes) -> bytes: + return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF) + + raw = bytearray() + stride = w * 4 + for y in range(h): + raw.append(0) + raw.extend(rgba_bytes[y * stride : (y + 1) * stride]) + + ihdr = struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0) + png = ( + b"\x89PNG\r\n\x1a\n" + + chunk(b"IHDR", ihdr) + + chunk(b"IDAT", zlib.compress(bytes(raw), level=6)) + + chunk(b"IEND", b"") + ) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(png) + + +def _paeth(a: int, b: int, c: int) -> int: + p = a + b - c + pa = abs(p - a) + pb = abs(p - b) + pc = abs(p - c) + if pa <= pb and pa <= pc: + return a + if pb <= pc: + return b + return c + + +def read_png_rgba(path: Path) -> Tuple[int, int, bytes]: + data = path.read_bytes() + if data[:8] != b"\x89PNG\r\n\x1a\n": + raise ValueError(f"Not a PNG file: {path}") + pos = 8 + w = h = bit_depth = color_type = interlace = 0 + idat = bytearray() + while pos + 8 <= len(data): + length = struct.unpack(">I", data[pos : pos + 4])[0] + tag = data[pos + 4 : pos + 8] + chunk_data = data[pos + 8 : pos + 8 + length] + pos += 12 + length + if tag == b"IHDR": + w, h, bit_depth, color_type, _comp, _filt, interlace = struct.unpack(">IIBBBBB", chunk_data) + elif tag == b"IDAT": + idat.extend(chunk_data) + elif tag == b"IEND": + break + + if interlace != 0: + raise ValueError(f"Interlaced PNG unsupported in pure-stdlib reader: {path}") + channels_map = {0: 1, 2: 3, 4: 2, 6: 4} + if color_type not in channels_map or bit_depth not in (8, 16): + raise ValueError(f"Unsupported PNG format (color={color_type}, depth={bit_depth}): {path}") + + ch = channels_map[color_type] + bypp = ch * (bit_depth // 8) + row_bytes = w * bypp + raw = zlib.decompress(bytes(idat)) + if len(raw) < h * (row_bytes + 1): + raise ValueError(f"Truncated PNG IDAT in {path}") + + prev = bytearray(row_bytes) + out = bytearray(w * h * 4) + idx_in = 0 + for y in range(h): + ftype = raw[idx_in] + idx_in += 1 + scan = bytearray(raw[idx_in : idx_in + row_bytes]) + idx_in += row_bytes + if ftype == 1: + for i in range(bypp, row_bytes): + scan[i] = (scan[i] + scan[i - bypp]) & 0xFF + elif ftype == 2: + for i in range(row_bytes): + scan[i] = (scan[i] + prev[i]) & 0xFF + elif ftype == 3: + for i in range(row_bytes): + a = scan[i - bypp] if i >= bypp else 0 + scan[i] = (scan[i] + ((a + prev[i]) >> 1)) & 0xFF + elif ftype == 4: + for i in range(row_bytes): + a = scan[i - bypp] if i >= bypp else 0 + b = prev[i] + c = prev[i - bypp] if i >= bypp else 0 + scan[i] = (scan[i] + _paeth(a, b, c)) & 0xFF + elif ftype != 0: + raise ValueError(f"Unknown PNG filter {ftype} in {path}") + prev = scan + + out_row = y * w * 4 + if bit_depth == 8: + if ch == 4: + out[out_row : out_row + w * 4] = scan + elif ch == 3: + for x in range(w): + si = x * 3 + di = out_row + x * 4 + out[di] = scan[si] + out[di + 1] = scan[si + 1] + out[di + 2] = scan[si + 2] + out[di + 3] = 255 + elif ch == 2: + for x in range(w): + si = x * 2 + di = out_row + x * 4 + v = scan[si] + out[di] = v + out[di + 1] = v + out[di + 2] = v + out[di + 3] = scan[si + 1] + else: + for x in range(w): + di = out_row + x * 4 + v = scan[x] + out[di] = v + out[di + 1] = v + out[di + 2] = v + out[di + 3] = 255 + else: + # 16-bit big endian -> 8-bit + for x in range(w): + si = x * bypp + di = out_row + x * 4 + vals = [((scan[si + k * 2] << 8) | scan[si + k * 2 + 1]) >> 8 for k in range(ch)] + if ch == 4: + out[di : di + 4] = bytes(vals) + elif ch == 3: + out[di : di + 4] = bytes((vals[0], vals[1], vals[2], 255)) + elif ch == 2: + out[di : di + 4] = bytes((vals[0], vals[0], vals[0], vals[1])) + else: + out[di : di + 4] = bytes((vals[0], vals[0], vals[0], 255)) + return w, h, bytes(out) + + +def compute_diff_metrics(ours_path: Path, gt_path: Path) -> Dict[str, Any]: + if not ours_path.exists(): + return {"error": f"missing ours: {ours_path}", "mae_pct": 100.0, "mae_255": 255.0, "rmse_255": 255.0} + if not gt_path.exists(): + return {"error": f"missing gt: {gt_path}", "mae_pct": 100.0, "mae_255": 255.0, "rmse_255": 255.0} + + ow, oh, ob = read_png_rgba(ours_path) + gw, gh, gb = read_png_rgba(gt_path) + size_mismatch = (ow != gw) or (oh != gh) + + # Compare over overlapping or resized if mismatched, matching render-check's RGB metric + cw = min(ow, gw) + ch = min(oh, gh) + if size_mismatch: + # Bilinear sample gt onto ow x oh just like render-check, but still flag size_mismatch! + sum_abs = 0 + sum_sq = 0 + max_diff = 0 + for y in range(oh): + gy = min(gh - 1, int((y + 0.5) * gh / oh)) + for x in range(ow): + gx = min(gw - 1, int((x + 0.5) * gw / ow)) + oi = (y * ow + x) * 4 + gi = (gy * gw + gx) * 4 + for c in range(3): + d = abs(ob[oi + c] - gb[gi + c]) + sum_abs += d + sum_sq += d * d + if d > max_diff: + max_diff = d + n = ow * oh * 3 + else: + sum_abs = 0 + sum_sq = 0 + max_diff = 0 + n = ow * oh * 3 + for i in range(0, ow * oh * 4, 4): + d0 = abs(ob[i] - gb[i]) + d1 = abs(ob[i + 1] - gb[i + 1]) + d2 = abs(ob[i + 2] - gb[i + 2]) + sum_abs += d0 + d1 + d2 + sum_sq += d0 * d0 + d1 * d1 + d2 * d2 + m = max(d0, d1, d2) + if m > max_diff: + max_diff = m + + mae_255 = sum_abs / max(1, n) + rmse_255 = math.sqrt(sum_sq / max(1, n)) + mae_pct = mae_255 / 2.55 + return { + "mae_255": round(mae_255, 4), + "mae_pct": round(mae_pct, 4), + "rmse_255": round(rmse_255, 4), + "max_diff": max_diff, + "dims_ours": [ow, oh], + "dims_gt": [gw, gh], + "size_mismatch": size_mismatch, + } + + +# --------------------------------------------------------------------------- +# Synthetic Test Plate & Geometry Generators +# --------------------------------------------------------------------------- + + +def _hsv_to_rgb(h: float, s: float, v: float) -> Tuple[float, float, float]: + h = (h % 1.0) * 6.0 + i = int(h) + f = h - i + p = v * (1.0 - s) + q = v * (1.0 - s * f) + t = v * (1.0 - s * (1.0 - f)) + return [(v, t, p), (q, v, p), (p, v, t), (p, q, v), (t, p, v), (v, p, q)][i % 6] + + +def _clamp8(v: float) -> int: + return max(0, min(255, int(round(v * 255.0)))) + + +def generate_assets() -> Dict[str, str]: + """Generates all synthetic test plates & cube.obj under probes/diff_fuzz/assets/.""" + root = ensure_dirs() + assets_dir = root / "assets" + + # 1. plate_color.png (256x256): HSV + gray/primary ramps + geometric edges + alpha gradient + p_color = assets_dir / "plate_color.png" + w, h = 256, 256 + buf = bytearray(w * h * 4) + for y in range(h): + ny = y / (h - 1) + for x in range(w): + nx = x / (w - 1) + r, g, b, a = 0.0, 0.0, 0.0, 1.0 + if ny < 0.40: + r, g, b = _hsv_to_rgb(nx, ny / 0.40, 0.90) + elif ny < 0.60: + if nx < 0.5: + g0 = nx * 2.0 + r, g, b = g0, g0, g0 + else: + bar = int((nx - 0.5) * 12.0) % 6 + r, g, b = [ + (0.95, 0.15, 0.15), + (0.15, 0.90, 0.20), + (0.15, 0.30, 0.95), + (0.95, 0.90, 0.15), + (0.15, 0.90, 0.95), + (0.95, 0.15, 0.90), + ][bar] + elif ny < 0.82: + # Sharp geometric edges (rotated diamond + circle + stripes) + r, g, b = 0.12, 0.14, 0.18 + dx, dy = abs(nx - 0.30), abs(ny - 0.71) + if dx + dy < 0.11: + r, g, b = 0.96, 0.52, 0.12 + if math.hypot(nx - 0.72, ny - 0.71) < 0.09: + r, g, b = 0.20, 0.85, 0.95 + if ((x + y) // 6) % 2 == 0 and 0.45 < nx < 0.58: + r, g, b = 0.92, 0.92, 0.92 + else: + r, g, b = _hsv_to_rgb(nx, 0.85, 0.92) + a = max(0.0, min(1.0, 1.0 - (ny - 0.82) / 0.18)) + idx = (y * w + x) * 4 + buf[idx] = _clamp8(r) + buf[idx + 1] = _clamp8(g) + buf[idx + 2] = _clamp8(b) + buf[idx + 3] = _clamp8(a) + write_png_rgba(p_color, w, h, bytes(buf)) + sync_asset_to_remote(p_color) + + # 2. plate_fg.png (256x256): semi-transparent shapes, fine diagonal stripes, soft radial falloff + p_fg = assets_dir / "plate_fg.png" + buf = bytearray(w * h * 4) + for y in range(h): + ny = y / (h - 1) + for x in range(w): + nx = x / (w - 1) + r, g, b, a = 0.0, 0.0, 0.0, 0.0 + # Soft radial falloff orb (top-left) + d_orb = math.hypot(nx - 0.28, ny - 0.28) + if d_orb < 0.22: + t = 1.0 - d_orb / 0.22 + 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) + a = t * t * (3.0 - 2.0 * t) + # Fine diagonal stripes block (top-right) + if 0.54 <= nx <= 0.90 and 0.10 <= ny <= 0.44: + stripe = ((x - y) // 2) % 2 == 0 + r, g, b = (0.95, 0.85, 0.15) if stripe else (0.15, 0.22, 0.55) + a = 0.85 if stripe else 0.55 + # Overlapping semi-transparent discs (bottom-left) + d1 = math.hypot(nx - 0.24, ny - 0.72) < 0.14 + d2 = math.hypot(nx - 0.36, ny - 0.72) < 0.14 + if d1 and d2: + r, g, b, a = 0.85, 0.55, 0.95, 0.75 + elif d1: + r, g, b, a = 0.10, 0.85, 0.90, 0.55 + elif d2: + r, g, b, a = 0.95, 0.20, 0.65, 0.55 + # Asymmetric crisp L-marker (bottom-right) + if (0.62 <= nx <= 0.68 and 0.58 <= ny <= 0.86) or (0.62 <= nx <= 0.86 and 0.80 <= ny <= 0.86): + r, g, b, a = 0.98, 0.98, 0.98, 1.0 + idx = (y * w + x) * 4 + buf[idx] = _clamp8(r) + buf[idx + 1] = _clamp8(g) + buf[idx + 2] = _clamp8(b) + buf[idx + 3] = _clamp8(a) + write_png_rgba(p_fg, w, h, bytes(buf)) + sync_asset_to_remote(p_fg) + + # 3. plate_small.png (160x120): mismatched resolution test plate + p_small = assets_dir / "plate_small.png" + sw, sh = 160, 120 + sbuf = bytearray(sw * sh * 4) + for y in range(sh): + ny = y / (sh - 1) + for x in range(sw): + nx = x / (sw - 1) + r, g, b, a = 0.18, 0.22, 0.30, 0.95 + if x < 5 or x >= sw - 5 or y < 5 or y >= sh - 5: + if y < 5: + r, g, b, a = 0.95, 0.20, 0.20, 1.0 + elif y >= sh - 5: + r, g, b, a = 0.20, 0.90, 0.25, 1.0 + elif x < 5: + r, g, b, a = 0.20, 0.40, 0.95, 1.0 + else: + r, g, b, a = 0.95, 0.85, 0.15, 1.0 + else: + if ((x // 10) + (y // 10)) % 2 == 0: + r, g, b = 0.72, 0.76, 0.82 + if abs(nx - ny) < 0.04 or abs(nx - (1.0 - ny)) < 0.04: + r, g, b = 0.95, 0.35, 0.10 + d_c = math.hypot(nx - 0.5, ny - 0.5) + if d_c < 0.22: + a = max(0.2, 1.0 - (0.22 - d_c) / 0.22 * 0.7) + idx = (y * sw + x) * 4 + sbuf[idx] = _clamp8(r) + sbuf[idx + 1] = _clamp8(g) + sbuf[idx + 2] = _clamp8(b) + sbuf[idx + 3] = _clamp8(a) + write_png_rgba(p_small, sw, sh, bytes(sbuf)) + sync_asset_to_remote(p_small) + + # 4. plate_bump.png (256x256): grayscale heightmap / bump test texture + p_bump = assets_dir / "plate_bump.png" + bbuf = bytearray(w * h * 4) + for y in range(h): + ny = y / (h - 1) + for x in range(w): + nx = x / (w - 1) + d = math.hypot(nx - 0.5, ny - 0.5) + dome = max(0.0, 1.0 - (d / 0.38) ** 2) ** 0.5 if d < 0.38 else 0.0 + ripple = 0.5 + 0.5 * math.sin(d * 48.0) + step = 0.25 * math.floor(nx * 5.0) / 4.0 + val = max(0.0, min(1.0, 0.50 * dome + 0.30 * ripple + 0.20 * step)) + v8 = _clamp8(val) + idx = (y * w + x) * 4 + bbuf[idx] = v8 + bbuf[idx + 1] = v8 + bbuf[idx + 2] = v8 + bbuf[idx + 3] = 255 + write_png_rgba(p_bump, w, h, bytes(bbuf)) + sync_asset_to_remote(p_bump) + + # 5. cube.obj: small valid triangulated OBJ mesh + p_obj = assets_dir / "cube.obj" + obj_text = """# Synthetic unit cube for SurfaceFBXMesh differential testing +o UnitCube +v -0.5 -0.5 0.5 +v 0.5 -0.5 0.5 +v 0.5 0.5 0.5 +v -0.5 0.5 0.5 +v -0.5 -0.5 -0.5 +v 0.5 -0.5 -0.5 +v 0.5 0.5 -0.5 +v -0.5 0.5 -0.5 +vt 0.0 0.0 +vt 1.0 0.0 +vt 1.0 1.0 +vt 0.0 1.0 +vn 0.0 0.0 1.0 +vn 0.0 0.0 -1.0 +vn 1.0 0.0 0.0 +vn -1.0 0.0 0.0 +vn 0.0 1.0 0.0 +vn 0.0 -1.0 0.0 +f 1/1/1 2/2/1 3/3/1 +f 1/1/1 3/3/1 4/4/1 +f 6/1/2 5/2/2 8/3/2 +f 6/1/2 8/3/2 7/4/2 +f 2/1/3 6/2/3 7/3/3 +f 2/1/3 7/3/3 3/4/3 +f 5/1/4 1/2/4 4/3/4 +f 5/1/4 4/3/4 8/4/4 +f 4/1/5 3/2/5 7/3/5 +f 4/1/5 7/3/5 8/4/5 +f 5/1/6 6/2/6 2/3/6 +f 5/1/6 2/3/6 1/4/6 +""" + p_obj.write_text(obj_text) + sync_asset_to_remote(p_obj) + + return { + "color": f"{CONTAINER_ROOT}/assets/plate_color.png", + "fg": f"{CONTAINER_ROOT}/assets/plate_fg.png", + "small": f"{CONTAINER_ROOT}/assets/plate_small.png", + "bump": f"{CONTAINER_ROOT}/assets/plate_bump.png", + "cube_obj": f"{CONTAINER_ROOT}/assets/cube.obj", + } + + +# --------------------------------------------------------------------------- +# Fusion .comp Serialization Primitives +# --------------------------------------------------------------------------- + + +def step_spline(name: str, frame_values: Dict[int, float]) -> str: + kfs = [f"\t\t\t\t[{f}] = {{ {v!r}, Flags = {{ StepIn = true }} }}," for f, v in sorted(frame_values.items())] + return f"\t\t{name} = BezierSpline {{\n\t\t\tKeyFrames = {{\n" + "\n".join(kfs) + "\n\t\t\t},\n\t\t}," + + +def linear_spline(name: str, frame_values: Dict[int, float]) -> str: + kfs = [f"\t\t\t\t[{f}] = {{ {v!r}, Flags = {{ Linear = true }} }}," for f, v in sorted(frame_values.items())] + return f"\t\t{name} = BezierSpline {{\n\t\t\tKeyFrames = {{\n" + "\n".join(kfs) + "\n\t\t\t},\n\t\t}," + + +def lut_bezier(name: str, pts: List[Tuple[float, float]]) -> str: + kfs = "\n".join(f"\t\t\t\t\t[{x}] = {{ {y} }}," for x, y in pts) + return ( + f"\t\t{name} = LUTBezier {{\n" + f"\t\t\tSmoothEndsTransition = true,\n" + f"\t\t\tKeyColorSplines = {{\n" + f"\t\t\t\t[0] = {{\n{kfs}\n\t\t\t\t}}\n" + f"\t\t\t}},\n\t\t}}," + ) + + +def make_loader(name: str, container_path: str, post_mult: int = 1, depth: Optional[int] = None) -> str: + extra = f"\n\t\t\t\tDepth = Input {{ Value = {depth}, }}," if depth is not None else "" + return f"""\t\t{name} = Loader {{ +\t\t\tClips = {{ +\t\t\t\tClip {{ +\t\t\t\t\tID = "Clip1", +\t\t\t\t\tFilename = "{container_path}", +\t\t\t\t\tFormatID = "PNGFormat", +\t\t\t\t\tLength = 1, +\t\t\t\t\tLengthSetManually = true, +\t\t\t\t\tTrimIn = 0, +\t\t\t\t\tTrimOut = 0, +\t\t\t\t\tExtendFirst = 0, +\t\t\t\t\tExtendLast = 0, +\t\t\t\t\tLoop = 1, +\t\t\t\t\tStartFrame = -1, +\t\t\t\t\tGlobalStart = 0, +\t\t\t\t\tGlobalEnd = 1000, +\t\t\t\t}}, +\t\t\t}}, +\t\t\tInputs = {{ +\t\t\t\t["Clip1.PNGFormat.PostMultiply"] = Input {{ Value = {post_mult}, }},{extra} +\t\t\t}}, +\t\t}},""" + + +def make_saver(src_op: str, prefix: str) -> str: + return f"""\t\tSaver1 = Saver {{ +\t\t\tInputs = {{ +\t\t\t\tClip = Input {{ +\t\t\t\t\tValue = Clip {{ +\t\t\t\t\t\tFilename = "{CONTAINER_ROOT}/gt/{prefix}_0000.png", +\t\t\t\t\t\tFormatID = "PNGFormat", +\t\t\t\t\t\tLength = 0, +\t\t\t\t\t\tSaving = true, +\t\t\t\t\t\tTrimIn = 0, +\t\t\t\t\t\tExtendFirst = 0, +\t\t\t\t\t\tExtendLast = 0, +\t\t\t\t\t\tLoop = 1, +\t\t\t\t\t\tAspectMode = 0, +\t\t\t\t\t\tDepth = 0, +\t\t\t\t\t\tGlobalStart = -2000000000, +\t\t\t\t\t\tGlobalEnd = 0, +\t\t\t\t\t}}, +\t\t\t\t}}, +\t\t\t\tOutputFormat = Input {{ Value = FuID {{ "PNGFormat" }}, }}, +\t\t\t\tInput = Input {{ SourceOp = "{src_op}", Source = "Output", }}, +\t\t\t}}, +\t\t}},""" + + +def make_comp(tools_body: str, end_frame: int, w: int = 256, h: int = 256, start_frame: int = 0) -> str: + return f"""Composition {{ +\tCurrentTime = {start_frame}, +\tRenderRange = {{ {start_frame}, {end_frame} }}, +\tGlobalRange = {{ {start_frame}, {end_frame} }}, +\tCurrentID = 500, +\tHiQ = true, +\tPlaybackUpdateMode = 0, +\tVersion = "Fusion Studio 21.1 build 23", +\tTools = ordered() {{ +{tools_body} +\t}}, +\tPrefs = {{ +\t\tComp = {{ +\t\t\tFrameFormat = {{ +\t\t\t\tWidth = {w}, +\t\t\t\tHeight = {h}, +\t\t\t\tRate = 24, +\t\t\t}}, +\t\t}}, +\t}}, +}} +""" + + +def build_switch_chain( + cases: List[Tuple[int, str, str]], + bg_name: str, + prefix_tag: str, +) -> Tuple[List[str], List[str], str]: + """Chains Merge switches so frame f outputs op_name for case (f, label, op_name).""" + nodes: List[str] = [] + splines: List[str] = [] + prev = bg_name + frames = [c[0] for c in cases] + for f, _label, op_name in cases: + bl = {fr: (1.0 if fr == f else 0.0) for fr in frames} + sname = f"{prefix_tag}_{f}_Blend" + splines.append(step_spline(sname, bl)) + sw_name = f"{prefix_tag}_Sw_{f}" + nodes.append( + f"""\t\t{sw_name} = Merge {{ +\t\t\tInputs = {{ +\t\t\t\tBlend = Input {{ SourceOp = "{sname}", Source = "Value", }}, +\t\t\t\tBackground = Input {{ SourceOp = "{prev}", Source = "Output", }}, +\t\t\t\tForeground = Input {{ SourceOp = "{op_name}", Source = "Output", }}, +\t\t\t}}, +\t\t}},""" + ) + prev = sw_name + return nodes, splines, prev + + +# --------------------------------------------------------------------------- +# Execution & Comparison Runner (sg render + render-check) +# --------------------------------------------------------------------------- + + +def run_comp_both( + comp_path: Path, + prefix: str, + frames: List[int], + labels: Dict[int, str], + render_gt: bool = True, + timeout_sec: int = 180, +) -> Dict[int, Dict[str, Any]]: + """Renders comp via sg render (if render_gt) and render-check --render, returning per-frame metrics.""" + root = ensure_dirs() + rc_bin = ensure_render_check() + start_f, end_f = min(frames), max(frames) + + gt_error: Optional[str] = None + if render_gt: + if use_smb(): + target_comp = str(comp_path) + else: + remote_comp = f"{REMOTE_ROOT}/comps/{comp_path.name}" + subprocess.run(["sg", "upload", str(comp_path), remote_comp], check=True, timeout=60) + target_comp = remote_comp + + # Clear stale GT frames for this prefix + gt_dir = root / "gt" + for f in frames: + p = gt_dir / f"{prefix}_{f:04d}.png" + if p.exists(): + p.unlink() + + try: + cmd = ["sg", "render", target_comp, "--start", str(start_f), "--end", str(end_f)] + proc = subprocess.run(cmd, check=True, capture_output=True, text=True, timeout=timeout_sec) + combined_out = (proc.stdout or "") + "\n" + (proc.stderr or "") + if "ERROR: Render failed" in combined_out: + err_lines = [ln.strip() for ln in combined_out.splitlines() if "fail" in ln.lower() or "error" in ln.lower()] + gt_error = "sg render error: " + " | ".join(err_lines[:4]) + except subprocess.TimeoutExpired: + gt_error = f"sg render timed out after {timeout_sec}s" + except subprocess.CalledProcessError as e: + gt_error = f"sg render failed (rc={e.returncode}): {(e.stderr or e.stdout or '').strip()[:300]}" + + if use_smb() and gt_error is None: + # Wait briefly for SMB directory cache to surface newly written GT frames + last_gt = gt_dir / f"{prefix}_{end_f:04d}.png" + deadline = time.time() + 4.0 + while not last_gt.exists() and time.time() < deadline: + time.sleep(0.25) + + if not use_smb() and gt_error is None: + for f in frames: + fname = f"{prefix}_{f:04d}.png" + try: + subprocess.run( + ["sg", "download", f"{REMOTE_ROOT}/gt/{fname}", str(gt_dir / fname)], + check=True, + capture_output=True, + timeout=60, + ) + except subprocess.CalledProcessError as e: + gt_error = f"sg download failed for {fname}: {e}" + break + + eval_comp = comp_path + if not use_smb(): + txt = comp_path.read_text().replace(CONTAINER_ROOT, str(root)) + eval_comp = comp_path.with_suffix(".local.comp") + eval_comp.write_text(txt) + + ours_sub = root / "ours" / prefix + if ours_sub.exists(): + shutil.rmtree(ours_sub, ignore_errors=True) + ours_sub.mkdir(parents=True, exist_ok=True) + + rc_error: Optional[str] = None + try: + subprocess.run( + [str(rc_bin), str(eval_comp), "--render", f"{start_f}..{end_f}", "--out-dir", str(ours_sub)], + check=True, + capture_output=True, + text=True, + timeout=timeout_sec, + ) + except subprocess.TimeoutExpired: + rc_error = f"render-check timed out after {timeout_sec}s" + except subprocess.CalledProcessError as e: + rc_error = f"render-check failed (rc={e.returncode}): {(e.stderr or e.stdout or '').strip()[:300]}" + + results: Dict[int, Dict[str, Any]] = {} + for f in frames: + label = labels.get(f, f"f{f}") + if gt_error is not None: + results[f] = {"frame": f, "label": label, "error": gt_error, "mae_pct": 100.0, "mae_255": 255.0, "rmse_255": 255.0} + continue + if rc_error is not None: + results[f] = {"frame": f, "label": label, "error": rc_error, "mae_pct": 100.0, "mae_255": 255.0, "rmse_255": 255.0} + continue + gt_p = root / "gt" / f"{prefix}_{f:04d}.png" + ours_p = ours_sub / f"{f:04d}.png" + m = compute_diff_metrics(ours_p, gt_p) + m["frame"] = f + m["label"] = label + results[f] = m + return results + + +# --------------------------------------------------------------------------- +# Matrix Suites (7 Exhaustive Edge-Case Suites) +# --------------------------------------------------------------------------- + + +def build_matrix_merge_modes(assets: Dict[str, str]): + """Sweeps all Merge ApplyModes, Operators, SubtractiveAdditive, AlphaGain/Gain, BurnIn, Edges, mismatched res, EffectMask.""" + nodes = [ + make_loader("ColorLoader", assets["color"], post_mult=1), + make_loader("FGLoader", assets["fg"], post_mult=1), + make_loader("SmallLoader", assets["small"], post_mult=1), + """\t\tBlackBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftAlpha = Input { Value = 1, }, }, }, +\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, }, }, }, +\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, }, }, },""", + ] + cases: List[Tuple[int, str, str]] = [] + f = 0 + + def add_case(label: str, fg: str, bg: str, extra: str, over_blue: bool = False) -> None: + nonlocal f + mname = f"M_{f}" + nodes.append( + f"""\t\t{mname} = Merge {{ +\t\t\tInputs = {{ +\t\t\t\tBackground = Input {{ SourceOp = "{bg}", Source = "Output", }}, +\t\t\t\tForeground = Input {{ SourceOp = "{fg}", Source = "Output", }}, +\t\t\t\tPerformDepthMerge = Input {{ Value = 0, }}, +\t\t\t\t{extra} +\t\t\t}}, +\t\t}},""" + ) + out_name = mname + if over_blue: + oname = f"Vis_{f}" + nodes.append( + f"""\t\t{oname} = Merge {{ +\t\t\tInputs = {{ +\t\t\t\tBackground = Input {{ SourceOp = "BlueBG", Source = "Output", }}, +\t\t\t\tForeground = Input {{ SourceOp = "{mname}", Source = "Output", }}, +\t\t\t}}, +\t\t}},""" + ) + out_name = oname + cases.append((f, label, out_name)) + f += 1 + + apply_modes = [ + "Normal", "Screen", "Multiply", "Dissolve", "SoftLight", "HardLight", + "Darken", "Lighten", "ColorDodge", "ColorBurn", "Difference", "Exclusion", + "Overlay", "Sub", + ] + for am in apply_modes: + add_case(f"ApplyMode={am}", "FGLoader", "ColorLoader", f'Size = Input {{ Value = 0.85, }}, ApplyMode = Input {{ Value = FuID {{ "{am}" }}, }},') + + operators = ["Over", "In", "Held Out", "Atop", "XOr", "Conjoint", "Disjoint"] + for op in operators: + add_case(f"Operator={op}", "FGLoader", "ColorLoader", f'Operator = Input {{ Value = FuID {{ "{op}" }}, }},', over_blue=True) + + for sa in (0.0, 0.5, 1.0): + add_case(f"SubAdd={sa}", "FGLoader", "ColorLoader", f"SubtractiveAdditive = Input {{ Value = {sa}, }},") + + for ag in (0.0, 0.5, 1.5): + add_case(f"Gain={ag}", "FGLoader", "ColorLoader", f"Gain = Input {{ Value = {ag}, }},") + add_case("AlphaGain=0.5", "FGLoader", "ColorLoader", "AlphaGain = Input { Value = 0.5, },") + + add_case("BurnIn=0.6", "FGLoader", "ColorLoader", "BurnIn = Input { Value = 0.6, },") + + for ed in (0, 1, 2, 3): + add_case( + f"Edges={ed}", + "SmallLoader", + "ColorLoader", + f"Center = Input {{ Value = {{ 0.78, 0.72 }}, }}, Size = Input {{ Value = 0.55, }}, Angle = Input {{ Value = 22, }}, Edges = Input {{ Value = {ed}, }},", + ) + + add_case("Mismatch_SmallOverColor", "SmallLoader", "ColorLoader", "Size = Input { Value = 0.8, }, Angle = Input { Value = 20, },") + add_case("Mismatch_ColorOverSmall", "ColorLoader", "SmallLoader", "Size = Input { Value = 0.5, }, Angle = Input { Value = -15, },", over_blue=True) + + for inv in (0, 1): + for mbm in (0, 1): + add_case( + f"Mask_inv{inv}_mbm{mbm}", + "FGLoader", + "ColorLoader", + f'EffectMask = Input {{ SourceOp = "MaskEll", Source = "Mask", }}, ApplyMaskInverted = Input {{ Value = {inv}, }}, MultiplyByMask = Input {{ Value = {mbm}, }},', + ) + + sw_nodes, sw_splines, out_op = build_switch_chain(cases, "BlackBG", "MM") + nodes.extend(sw_nodes) + nodes.append(make_saver(out_op, "matrix_merge_modes")) + comp_path = ensure_dirs() / "comps" / "matrix_merge_modes.comp" + comp_path.write_text(make_comp("\n".join(nodes + sw_splines), len(cases) - 1)) + return comp_path, "matrix_merge_modes", [(c[0], c[1]) for c in cases] + + +def build_matrix_hdr_depth(assets: Dict[str, str]): + """Tests BitDepth (int8/int16/float16/float32), HDR > 1.0, negative values, PreDividePostMultiply=0/1.""" + nodes = [ + make_loader("ColorLoader", assets["color"], post_mult=1), + make_loader("FGLoader", assets["fg"], post_mult=1), + """\t\tBlackBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftAlpha = Input { Value = 1, }, }, }, +\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, }, }, },""", + ] + cases: List[Tuple[int, str, str]] = [] + f = 0 + + for d_code, d_name in ((1, "int8"), (2, "int16"), (3, "float16"), (4, "float32")): + cd = f"CD_{f}" + up = f"Up_{f}" + bl = f"Bl_{f}" + dn = f"Dn_{f}" + nodes.append(f'\t\t{cd} = ChangeDepth {{ Inputs = {{ Input = Input {{ SourceOp = "ColorLoader", Source = "Output", }}, Depth = Input {{ Value = {d_code}, }}, }}, }},') + nodes.append(f'\t\t{up} = BrightnessContrast {{ Inputs = {{ Input = Input {{ SourceOp = "{cd}", Source = "Output", }}, Gain = Input {{ Value = 2.5, }}, }}, }},') + nodes.append(f'\t\t{bl} = Blur {{ Inputs = {{ Input = Input {{ SourceOp = "{up}", Source = "Output", }}, XBlurSize = Input {{ Value = 8.0, }}, }}, }},') + nodes.append(f'\t\t{dn} = BrightnessContrast {{ Inputs = {{ Input = Input {{ SourceOp = "{bl}", Source = "Output", }}, Gain = Input {{ Value = 0.4, }}, }}, }},') + cases.append((f, f"HDR_Depth={d_name}_Gain2.5_Blur_Gain0.4", dn)) + f += 1 + + # Negative value roundtrip across depths + for d_code, d_name in ((1, "int8"), (3, "float16"), (4, "float32")): + cd = f"CDN_{f}" + sub = f"Sub_{f}" + bl = f"BlN_{f}" + add = f"Add_{f}" + nodes.append(f'\t\t{cd} = ChangeDepth {{ Inputs = {{ Input = Input {{ SourceOp = "ColorLoader", Source = "Output", }}, Depth = Input {{ Value = {d_code}, }}, }}, }},') + nodes.append(f'\t\t{sub} = BrightnessContrast {{ Inputs = {{ Input = Input {{ SourceOp = "{cd}", Source = "Output", }}, Brightness = Input {{ Value = -0.4, }}, }}, }},') + nodes.append(f'\t\t{bl} = Blur {{ Inputs = {{ Input = Input {{ SourceOp = "{sub}", Source = "Output", }}, XBlurSize = Input {{ Value = 5.0, }}, }}, }},') + nodes.append(f'\t\t{add} = BrightnessContrast {{ Inputs = {{ Input = Input {{ SourceOp = "{bl}", Source = "Output", }}, Brightness = Input {{ Value = 0.4, }}, }}, }},') + cases.append((f, f"NegValues_Depth={d_name}", add)) + f += 1 + + # Background native Depth=3/4 HDR + for d_code, d_name in ((3, "float16"), (4, "float32")): + bg = f"BG_{f}" + up = f"BUp_{f}" + dn = f"BDn_{f}" + 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, }}, }}, }},') + nodes.append(f'\t\t{up} = BrightnessContrast {{ Inputs = {{ Input = Input {{ SourceOp = "{bg}", Source = "Output", }}, Gain = Input {{ Value = 3.0, }}, }}, }},') + nodes.append(f'\t\t{dn} = BrightnessContrast {{ Inputs = {{ Input = Input {{ SourceOp = "{up}", Source = "Output", }}, Gain = Input {{ Value = 0.333333, }}, }}, }},') + cases.append((f, f"BG_Depth={d_name}_HDR", dn)) + f += 1 + + # PreDividePostMultiply = 0 / 1 on semi-transparent FGLoader merged over DarkBG + for pd in (0, 1): + bc = f"BCPD_{f}" + m = f"MPD_{f}" + 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}, }}, }}, }},') + nodes.append(f'\t\t{m} = Merge {{ Inputs = {{ Background = Input {{ SourceOp = "DarkBG", Source = "Output", }}, Foreground = Input {{ SourceOp = "{bc}", Source = "Output", }}, }}, }},') + cases.append((f, f"BC_PreDiv={pd}", m)) + f += 1 + + sw_nodes, sw_splines, out_op = build_switch_chain(cases, "BlackBG", "HD") + nodes.extend(sw_nodes) + nodes.append(make_saver(out_op, "matrix_hdr_depth")) + comp_path = ensure_dirs() / "comps" / "matrix_hdr_depth.comp" + comp_path.write_text(make_comp("\n".join(nodes + sw_splines), len(cases) - 1)) + return comp_path, "matrix_hdr_depth", [(c[0], c[1]) for c in cases] + + +def build_matrix_masks(assets: Dict[str, str]): + """Chained multi-mask graphs (EllipseMask -> RectangleMask -> PolylineMask) testing all PaintModes, SoftEdge, BorderWidth, Invert, Level.""" + nodes = [ + """\t\tBlackBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftAlpha = Input { Value = 1, }, }, }, +\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, }, }, },""", + ] + cases: List[Tuple[int, str, str]] = [] + f = 0 + + paint_modes = ["Merge", "Add", "Subtract", "Minimum", "Maximum", "Average", "Multiply", "Replace", "Invert"] + for pm in paint_modes: + e = f"Ell_{f}" + r = f"Rect_{f}" + p = f"Poly_{f}" + m = f"Op_{f}" + 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, }}, }}, }},') + 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, }}, }}, }},') + nodes.append( + f"""\t\t{p} = PolylineMask {{ +\t\t\tInputs = {{ +\t\t\t\tEffectMask = Input {{ SourceOp = "{r}", Source = "Mask", }}, +\t\t\t\tPaintMode = Input {{ Value = FuID {{ "{pm}" }}, }}, +\t\t\t\tMaskWidth = Input {{ Value = 256, }}, +\t\t\t\tMaskHeight = Input {{ Value = 256, }}, +\t\t\t\tSoftEdge = Input {{ Value = 0.02, }}, +\t\t\t\tPolyline = Input {{ +\t\t\t\t\tValue = Polyline {{ +\t\t\t\t\t\tClosed = true, +\t\t\t\t\t\tPoints = {{ +\t\t\t\t\t\t\t{{ Linear = true, X = -0.25, Y = -0.25, RX = 0.16, RY = 0 }}, +\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 }}, +\t\t\t\t\t\t\t{{ Linear = true, X = 0.0, Y = 0.28, LX = 0.08, LY = -0.14 }}, +\t\t\t\t\t\t}}, +\t\t\t\t\t}}, +\t\t\t\t}}, +\t\t\t}}, +\t\t}},""" + ) + 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", }}, }}, }},') + cases.append((f, f"MaskChain_PaintMode={pm}", m)) + f += 1 + + # BorderWidth, Solid=0/1, SoftEdge, Invert, Level edge cases + extra_masks = [ + ("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, }, }, }'), + ("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, }, }, }'), + ("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" }, }, }, }'), + ("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 } } }, }, }, }'), + ] + for label, mdef in extra_masks: + mk = f"Mk_{f}" + m = f"Op_{f}" + nodes.append(f"\t\t{mk} = {mdef},") + 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", }}, }}, }},') + cases.append((f, label, m)) + f += 1 + + sw_nodes, sw_splines, out_op = build_switch_chain(cases, "BlackBG", "MK") + nodes.extend(sw_nodes) + nodes.append(make_saver(out_op, "matrix_masks")) + comp_path = ensure_dirs() / "comps" / "matrix_masks.comp" + comp_path.write_text(make_comp("\n".join(nodes + sw_splines), len(cases) - 1)) + return comp_path, "matrix_masks", [(c[0], c[1]) for c in cases] + + +def build_matrix_color_blur(assets: Dict[str, str]): + """ColorCorrector, ColorCurves, HueCurves, GamutConvert, ChannelBoolean, Blur, Glow, SoftGlow, DirectionalBlur.""" + nodes = [ + make_loader("ColorLoader", assets["color"], post_mult=1), + make_loader("FGLoader", assets["fg"], post_mult=1), + """\t\tBlackBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftAlpha = Input { Value = 1, }, }, }, +\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, }, }, },""", + lut_bezier("CC_Red", [(0.0, 0.0), (0.3, 0.55), (0.7, 0.45), (1.0, 0.95)]), + lut_bezier("CC_Green", [(0.0, 0.08), (0.5, 0.42), (1.0, 1.0)]), + lut_bezier("CC_Blue", [(0.0, 0.0), (0.5, 0.72), (1.0, 0.85)]), + lut_bezier("CC_Alpha", [(0.0, 0.0), (0.5, 0.85), (1.0, 1.0)]), + lut_bezier("HC_Hue", [(0, 1.25), (2, 0.85), (4, 1.15), (6, 1.25)]), + lut_bezier("HC_Sat", [(0, 1.0), (1, 0.3), (3, 1.7), (5, 0.6), (6, 1.0)]), + lut_bezier("HC_Lum", [(0, 1.0), (2, 0.6), (4, 1.4), (6, 1.0)]), + lut_bezier("HC_RSup", [(0, 0.5), (2, 1.0), (6, 0.5)]), + ] + cases: List[Tuple[int, str, str]] = [] + f = 0 + + def add_op(label: str, kind: str, in_port: str, src: str, extra: str, over_dark: bool = False) -> None: + nonlocal f + opn = f"Op_{f}" + nodes.append( + f"""\t\t{opn} = {kind} {{ +\t\t\tInputs = {{ +\t\t\t\t{in_port} = Input {{ SourceOp = "{src}", Source = "Output", }}, +\t\t\t\t{extra} +\t\t\t}}, +\t\t}},""" + ) + out_n = opn + if over_dark: + vn = f"Vis_{f}" + nodes.append(f'\t\t{vn} = Merge {{ Inputs = {{ Background = Input {{ SourceOp = "DarkBG", Source = "Output", }}, Foreground = Input {{ SourceOp = "{opn}", Source = "Output", }}, }}, }},') + out_n = vn + cases.append((f, label, out_n)) + f += 1 + + # ColorCorrector: SMH + Wheel Hue/Sat/Tint + PreDividePostMultiply + 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) + 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, },") + 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, },") + + # ColorCurves & HueCurves + 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) + 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", },') + + # GamutConvert + 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, },') + 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, },') + 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, },') + + # ChannelBoolean: Add/Sub/Mul/Div/Copy/Min/Max/Negative/Solid + cb_ops = [ + ("CB_Copy_BGR", 0, 'ToRed = Input { Value = 2, }, ToGreen = Input { Value = 1, }, ToBlue = Input { Value = 0, },'), + ("CB_Add", 1, 'Foreground = Input { SourceOp = "FGLoader", Source = "Output", },'), + ("CB_Sub", 2, 'Foreground = Input { SourceOp = "FGLoader", Source = "Output", },'), + ("CB_Mul", 6, 'Foreground = Input { SourceOp = "FGLoader", Source = "Output", },'), + ("CB_Div", 7, 'Foreground = Input { SourceOp = "FGLoader", Source = "Output", },'), + ("CB_Max", 8, 'Foreground = Input { SourceOp = "FGLoader", Source = "Output", },'), + ("CB_Min", 9, 'Foreground = Input { SourceOp = "FGLoader", Source = "Output", },'), + ("CB_Negative", 10, 'Foreground = Input { SourceOp = "FGLoader", Source = "Output", },'), + ("CB_Solid", 11, ''), + ] + for label, op_code, extra in cb_ops: + add_op(label, "ChannelBoolean", "Background", "ColorLoader", f"Operation = Input {{ Value = {op_code}, }}, {extra}") + + # Blur (Gaussian, Box, FastGaussian + unlocked X/Y) + 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, },') + add_op("Blur_Box_12", "Blur", "Input", "ColorLoader", 'Filter = Input { Value = FuID { "Box" }, }, XBlurSize = Input { Value = 12.0, },') + 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, },') + + # Glow, SoftGlow, DirectionalBlur + 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) + 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, },") + 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 }, },") + + sw_nodes, sw_splines, out_op = build_switch_chain(cases, "BlackBG", "CB") + nodes.extend(sw_nodes) + nodes.append(make_saver(out_op, "matrix_color_blur")) + comp_path = ensure_dirs() / "comps" / "matrix_color_blur.comp" + comp_path.write_text(make_comp("\n".join(nodes + sw_splines), len(cases) - 1)) + return comp_path, "matrix_color_blur", [(c[0], c[1]) for c in cases] + + +def build_matrix_warps_shapes(assets: Dict[str, str]): + """Transform (Edges=0/1/2/3, Pivot, Angle, Aspect), DVE, CornerPositioner, Displace, Drip, Dent, Vortex, sRender+s*.""" + nodes = [ + make_loader("ColorLoader", assets["color"], post_mult=1), + make_loader("BumpLoader", assets["bump"], post_mult=1), + """\t\tBlackBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftAlpha = Input { Value = 1, }, }, },""", + ] + cases: List[Tuple[int, str, str]] = [] + f = 0 + + for ed in (0, 1, 2, 3): + opn = f"Op_{f}" + 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}, }}, }}, }},') + cases.append((f, f"Transform_Edges={ed}_Pivot_Aspect", opn)) + f += 1 + + warps = [ + ("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 }, },'), + ("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 }, },'), + ("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, },'), + ("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, },'), + ("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, },'), + ("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, },'), + ("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, },'), + ("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, },'), + ] + for label, kind, inputs in warps: + opn = f"Op_{f}" + nodes.append(f"\t\t{opn} = {kind} {{ Inputs = {{ {inputs} }}, }},") + cases.append((f, label, opn)) + f += 1 + + # sRender + sNGon / sRectangle / sEllipse / sTransform / sMerge / sBoolean / sOutline + nodes.append( + """\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, }, }, }, +\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, }, }, }, +\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, }, }, }, +\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, }, }, }, +\t\tS_Merge = sMerge { Inputs = { Input1 = Input { SourceOp = "S_XF", Source = "Output", }, Input2 = Input { SourceOp = "S_Rect", Source = "Output", }, }, }, +\t\tS_BoolSub = sBoolean { Inputs = { Operation = Input { Value = FuID { "Subtract" }, }, Input1 = Input { SourceOp = "S_Rect", Source = "Output", }, Input2 = Input { SourceOp = "S_Ell", Source = "Output", }, }, }, +\t\tS_BoolXor = sBoolean { Inputs = { Operation = Input { Value = FuID { "Xor" }, }, Input1 = Input { SourceOp = "S_NGon", Source = "Output", }, Input2 = Input { SourceOp = "S_Rect", Source = "Output", }, }, }, +\t\tS_Outl = sOutline { Inputs = { Input = Input { SourceOp = "S_Ell", Source = "Output", }, Thickness = Input { Value = 0.03, }, }, },""" + ) + for label, s_src in [ + ("sRender_NGon_XF_Merge", "S_Merge"), + ("sRender_sBoolean_Sub", "S_BoolSub"), + ("sRender_sBoolean_Xor", "S_BoolXor"), + ("sRender_sOutline_Ell", "S_Outl"), + ]: + opn = f"Op_{f}" + nodes.append(f'\t\t{opn} = sRender {{ Inputs = {{ Width = Input {{ Value = 256, }}, Height = Input {{ Value = 256, }}, Input = Input {{ SourceOp = "{s_src}", Source = "Output", }}, }}, }},') + cases.append((f, label, opn)) + f += 1 + + sw_nodes, sw_splines, out_op = build_switch_chain(cases, "BlackBG", "WS") + nodes.extend(sw_nodes) + nodes.append(make_saver(out_op, "matrix_warps_shapes")) + comp_path = ensure_dirs() / "comps" / "matrix_warps_shapes.comp" + comp_path.write_text(make_comp("\n".join(nodes + sw_splines), len(cases) - 1)) + return comp_path, "matrix_warps_shapes", [(c[0], c[1]) for c in cases] + + +def build_matrix_3d(assets: Dict[str, str]): + """Cube3D, SurfaceFBXMesh, TextureTransformOperator, BumpMap, LightPoint (Linear/Quad), LightSpot, Duplicate3D, Displace3D, Override3D, ReplaceMaterial3D.""" + nodes = [ + make_loader("ColorLoader", assets["color"], post_mult=1), + make_loader("BumpLoader", assets["bump"], post_mult=1), + """\t\tBlackBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftAlpha = Input { Value = 1, }, }, }, +\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, }, }, }, +\t\tAmbLow = LightAmbient { Inputs = { Intensity = Input { Value = 0.20, }, }, },""", + ] + cases: List[Tuple[int, str, str]] = [] + f = 0 + + def add_3d(label: str, scene_nodes: List[str], merge_inputs: str, lighting: int = 1) -> None: + nonlocal f + nodes.extend(scene_nodes) + m3d = f"M3D_{f}" + rnd = f"Op_{f}" + nodes.append(f"\t\t{m3d} = Merge3D {{ Inputs = {{ {merge_inputs} SceneInput9 = Input {{ SourceOp = \"CamBase\", Source = \"Output\", }}, }}, }},") + 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", }}, }}, }},') + cases.append((f, label, rnd)) + f += 1 + + # 0: Cube3D textured + add_3d( + "Cube3D_Textured", + [ + '\t\tTex0 = Texture2DOperator { Inputs = { Input = Input { SourceOp = "ColorLoader", Source = "Output", }, }, },', + '\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", }, }, },', + ], + 'SceneInput1 = Input { SourceOp = "Cube0", Source = "Output", },', + lighting=0, + ) + + # 1: SurfaceFBXMesh (cube.obj) + add_3d( + "SurfaceFBXMesh_OBJ", + [ + '\t\tTex1 = Texture2DOperator { Inputs = { Input = Input { SourceOp = "ColorLoader", Source = "Output", }, }, },', + 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", }}, }}, }},', + ], + 'SceneInput1 = Input { SourceOp = "Fbx1", Source = "Output", },', + lighting=0, + ) + + # 2: TextureTransformOperator + add_3d( + "TextureTransformOperator", + [ + '\t\tTex2 = Texture2DOperator { Inputs = { Input = Input { SourceOp = "ColorLoader", Source = "Output", }, }, },', + '\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" }, }, }, },', + '\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", }, }, },', + ], + 'SceneInput1 = Input { SourceOp = "Pl2", Source = "Output", },', + lighting=0, + ) + + # 3: BumpMap + MtlBlinn + LightPoint + add_3d( + "BumpMap_MtlBlinn", + [ + '\t\tBm3 = BumpMap { Inputs = { Input = Input { SourceOp = "BumpLoader", Source = "Output", }, HeightScale = Input { Value = 4.0, }, }, },', + '\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", }, }, },', + '\t\tSph3 = Shape3D { Inputs = { Shape = Input { Value = FuID { "SurfaceSphereInputs" }, }, ["SurfaceSphereInputs.Radius"] = Input { Value = 1.0, }, MaterialInput = Input { SourceOp = "Mtl3", Source = "MaterialOutput", }, }, },', + '\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, }, }, },', + ], + 'SceneInput1 = Input { SourceOp = "Sph3", Source = "Output", }, SceneInput2 = Input { SourceOp = "Pt3", Source = "Output", }, SceneInput3 = Input { SourceOp = "AmbLow", Source = "Output", },', + lighting=1, + ) + + # 4 & 5: LightPoint Linear (DecayType=1) and Quadratic (DecayType=2) + for decay_t, d_name in ((1, "Linear"), (2, "Quadratic")): + add_3d( + f"LightPoint_Decay={d_name}", + [ + 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, }}, }}, }},', + 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", }}, }}, }},', + 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}, }}, }}, }},', + ], + f'SceneInput1 = Input {{ SourceOp = "Pl_{f}", Source = "Output", }}, SceneInput2 = Input {{ SourceOp = "Pt_{f}", Source = "Output", }}, SceneInput3 = Input {{ SourceOp = "AmbLow", Source = "Output", }},', + lighting=1, + ) + + # 6: LightSpot + add_3d( + "LightSpot_ConePenumbra", + [ + '\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, }, }, },', + '\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", }, }, },', + '\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, }, }, },', + ], + 'SceneInput1 = Input { SourceOp = "Pl6", Source = "Output", }, SceneInput2 = Input { SourceOp = "Sp6", Source = "Output", }, SceneInput3 = Input { SourceOp = "AmbLow", Source = "Output", },', + lighting=1, + ) + + # 7: Duplicate3D + add_3d( + "Duplicate3D_5x", + [ + '\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, }, }, },', + '\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, }, }, },', + ], + 'SceneInput1 = Input { SourceOp = "Dup7", Source = "Output", },', + lighting=0, + ) + + # 8: Displace3D + add_3d( + "Displace3D_Bump", + [ + '\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", }, }, },', + '\t\tDisp8 = Displace3D { Inputs = { SceneInput = Input { SourceOp = "Pl8", Source = "Output", }, Input = Input { SourceOp = "BumpLoader", Source = "Output", }, Scale = Input { Value = 0.6, }, }, },', + ], + 'SceneInput1 = Input { SourceOp = "Disp8", Source = "Output", },', + lighting=0, + ) + + # 9: Override3D (hide + material override) + add_3d( + "Override3D_Hide_MatOvr", + [ + '\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, }, }, },', + '\t\tOvr9Hide = Override3D { Inputs = { SceneInput = Input { SourceOp = "Sph9L", Source = "Output", }, ["Visibility.DoVisible"] = Input { Value = 1, }, ["Visibility.IsVisible"] = Input { Value = 0, }, }, },', + '\t\tSph9R = Shape3D { Inputs = { Shape = Input { Value = FuID { "SurfaceSphereInputs" }, }, ["SurfaceSphereInputs.Radius"] = Input { Value = 0.55, }, ["Transform3DOp.Translate.X"] = Input { Value = 0.7, }, }, },', + '\t\tTex9 = Texture2DOperator { Inputs = { Input = Input { SourceOp = "ColorLoader", Source = "Output", }, }, },', + '\t\tOvr9Mat = Override3D { Inputs = { SceneInput = Input { SourceOp = "Sph9R", Source = "Output", }, ["Material.DoMaterial"] = Input { Value = 1, }, MaterialInput = Input { SourceOp = "Tex9", Source = "MaterialOutput", }, }, },', + ], + 'SceneInput1 = Input { SourceOp = "Ovr9Hide", Source = "Output", }, SceneInput2 = Input { SourceOp = "Ovr9Mat", Source = "Output", },', + lighting=0, + ) + + # 10: ReplaceMaterial3D + add_3d( + "ReplaceMaterial3D_Cook", + [ + '\t\tTex10 = Texture2DOperator { Inputs = { Input = Input { SourceOp = "ColorLoader", Source = "Output", }, }, },', + '\t\tMtl10 = MtlCookTorrance { Inputs = { ["Diffuse.Color.Material"] = Input { SourceOp = "Tex10", Source = "MaterialOutput", }, ["Specular.Roughness"] = Input { Value = 0.25, }, }, },', + '\t\tSph10 = Shape3D { Inputs = { Shape = Input { Value = FuID { "SurfaceSphereInputs" }, }, ["SurfaceSphereInputs.Radius"] = Input { Value = 1.0, }, }, },', + '\t\tRep10 = ReplaceMaterial3D { Inputs = { SceneInput = Input { SourceOp = "Sph10", Source = "Output", }, MaterialInput = Input { SourceOp = "Mtl10", Source = "MaterialOutput", }, }, },', + '\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, }, }, },', + ], + 'SceneInput1 = Input { SourceOp = "Rep10", Source = "Output", }, SceneInput2 = Input { SourceOp = "Pt10", Source = "Output", }, SceneInput3 = Input { SourceOp = "AmbLow", Source = "Output", },', + lighting=1, + ) + + sw_nodes, sw_splines, out_op = build_switch_chain(cases, "BlackBG", "D3D") + nodes.extend(sw_nodes) + nodes.append(make_saver(out_op, "matrix_3d")) + comp_path = ensure_dirs() / "comps" / "matrix_3d.comp" + comp_path.write_text(make_comp("\n".join(nodes + sw_splines), len(cases) - 1)) + return comp_path, "matrix_3d", [(c[0], c[1]) for c in cases] + + +def build_matrix_misc(assets: Dict[str, str]): + """CustomTool (multi-input, getr1b, Setup1, Intermediate1, if), TimeSpeed, Switch, tool-level SourceOp instancing.""" + nodes = [ + make_loader("ColorLoader", assets["color"], post_mult=1), + make_loader("FGLoader", assets["fg"], post_mult=1), + """\t\tBlackBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftAlpha = Input { Value = 1, }, }, }, +\t\t-- CustomTool 0: Setup1, Intermediate1, if, getr1b, Image2 +\t\tOp_0 = Custom { +\t\t\tInputs = { +\t\t\t\tImage1 = Input { SourceOp = "ColorLoader", Source = "Output", }, +\t\t\t\tImage2 = Input { SourceOp = "FGLoader", Source = "Output", }, +\t\t\t\tNumberIn1 = Input { Value = 0.65, }, +\t\t\t\tPointIn1 = Input { Value = { 0.45, 0.55 }, }, +\t\t\t\tSetup1 = Input { Value = "1 - n1", }, +\t\t\t\tIntermediate1 = Input { Value = "max(0, 1 - dist(x, y, p1x, p1y) * 2)", }, +\t\t\t\tRedExpression = Input { Value = "if(x > p1x, getr1b(x - 0.1, y + 0.05), r2 * i1 + s1 * 0.2)", }, +\t\t\t\tGreenExpression = Input { Value = "if(y > p1y, g1 * i1, g2 + n1 * 0.1)", }, +\t\t\t\tBlueExpression = Input { Value = "b1 * (1 - i1) + b2 * i1", }, +\t\t\t\tAlphaExpression = Input { Value = "1", }, +\t\t\t}, +\t\t}, +\t\t-- TimeSpeed (frames 1 & 2 evaluate animated Transform at Speed=2.0, Delay=0.5) +\t\tXfAnim = Transform { +\t\t\tInputs = { +\t\t\t\tInput = Input { SourceOp = "ColorLoader", Source = "Output", }, +\t\t\t\tAngle = Input { SourceOp = "TS_Angle", Source = "Value", }, +\t\t\t\tSize = Input { Value = 0.8, }, +\t\t\t}, +\t\t}, +\t\tOp_1 = TimeSpeed { +\t\t\tInputs = { +\t\t\t\tInput = Input { SourceOp = "XfAnim", Source = "Output", }, +\t\t\t\tSpeed = Input { Value = 2.0, }, +\t\t\t\tDelay = Input { Value = 0.5, }, +\t\t\t}, +\t\t}, +\t\t-- Switch (Fusion 21 native Source=0/1 with Input0/Input1) +\t\tOp_2 = Switch { +\t\t\tInputs = { +\t\t\t\tSource = Input { Value = 0, }, +\t\t\t\tInput0 = Input { SourceOp = "ColorLoader", Source = "Output", }, +\t\t\t\tInput1 = Input { SourceOp = "FGLoader", Source = "Output", }, +\t\t\t}, +\t\t}, +\t\tOp_3 = Switch { +\t\t\tInputs = { +\t\t\t\tSource = Input { Value = 1, }, +\t\t\t\tInput0 = Input { SourceOp = "ColorLoader", Source = "Output", }, +\t\t\t\tInput1 = Input { SourceOp = "FGLoader", Source = "Output", }, +\t\t\t}, +\t\t}, +\t\t-- Tool-level SourceOp instancing +\t\tMasterCC = ColorCorrector { +\t\t\tInputs = { +\t\t\t\tInput = Input { SourceOp = "ColorLoader", Source = "Output", }, +\t\t\t\tWheelHue1 = Input { Value = 0.25, }, +\t\t\t\tWheelSaturation1 = Input { Value = 1.45, }, +\t\t\t\tMasterRGBGain = Input { Value = 1.35, }, +\t\t\t\tMasterRGBGamma = Input { Value = 0.85, }, +\t\t\t}, +\t\t}, +\t\tOp_4 = ColorCorrector { +\t\t\tSourceOp = "MasterCC", +\t\t\tInputs = { +\t\t\t\tInput = Input { SourceOp = "FGLoader", Source = "Output", }, +\t\t\t\tWheelHue1 = Input {}, +\t\t\t\tMasterRGBGain = Input { Value = 0.8, }, +\t\t\t}, +\t\t}, +\t\tOp_5 = Merge { +\t\t\tInputs = { +\t\t\t\tBackground = Input { SourceOp = "BlackBG", Source = "Output", }, +\t\t\t\tForeground = Input { SourceOp = "Op_4", Source = "Output", }, +\t\t\t}, +\t\t},""", + linear_spline("TS_Angle", {0: 0.0, 4: 180.0}), + ] + cases = [ + (0, "CustomTool_multi_getr1b_Setup_Inter_if", "Op_0"), + (1, "TimeSpeed_f1_Speed2_Delay0.5", "Op_1"), + (2, "TimeSpeed_f2_Speed2_Delay0.5", "Op_1"), + (3, "Switch_Source0_Input0", "Op_2"), + (4, "Switch_Source1_Input1", "Op_3"), + (5, "SourceOp_Instance_ColorCorrector", "Op_5"), + ] + sw_nodes, sw_splines, out_op = build_switch_chain(cases, "BlackBG", "MS") + nodes.extend(sw_nodes) + nodes.append(make_saver(out_op, "matrix_misc")) + comp_path = ensure_dirs() / "comps" / "matrix_misc.comp" + comp_path.write_text(make_comp("\n".join(nodes + sw_splines), len(cases) - 1)) + return comp_path, "matrix_misc", [(c[0], c[1]) for c in cases] + + +MATRIX_BUILDERS = { + "matrix_merge_modes": build_matrix_merge_modes, + "matrix_hdr_depth": build_matrix_hdr_depth, + "matrix_masks": build_matrix_masks, + "matrix_color_blur": build_matrix_color_blur, + "matrix_warps_shapes": build_matrix_warps_shapes, + "matrix_3d": build_matrix_3d, + "matrix_misc": build_matrix_misc, +} + + +# --------------------------------------------------------------------------- +# Randomized DAG Fuzzer + Auto-Bisector +# --------------------------------------------------------------------------- + + +@dataclass +class MaskNodeSpec: + name: str + kind: str # EllipseMask | RectangleMask | PolylineMask + params: Dict[str, Any] + paint_mode: Optional[str] = None + prev_mask: Optional[str] = None + + +@dataclass +class MaskChainSpec: + nodes: List[MaskNodeSpec] + apply_inverted: int = 0 + multiply_by_mask: int = 0 + + def output_name(self) -> str: + return self.nodes[-1].name + + +@dataclass +class SplineParam: + spline_name: str + kind: str # step | linear | expr_num | expr_pt + keyframes: Optional[Dict[int, float]] = None + expr_inputs: Optional[Dict[str, Any]] = None + + def eval_at(self, frame: int) -> Any: + if self.kind in ("step", "linear") and self.keyframes: + pts = sorted(self.keyframes.items()) + if frame <= pts[0][0]: + return pts[0][1] + if frame >= pts[-1][0]: + return pts[-1][1] + for (f0, v0), (f1, v1) in zip(pts, pts[1:]): + if f0 <= frame <= f1: + if self.kind == "step" or f1 == f0: + return v0 + t = (frame - f0) / (f1 - f0) + return round(v0 + (v1 - v0) * t, 5) + return 0.5 + + +@dataclass +class DagNode: + name: str + kind: str + is_source: bool + primary_port: Optional[str] = None + primary_src: Optional[str] = None + secondary_port: Optional[str] = None + secondary_src: Optional[str] = None + params: Dict[str, Any] = field(default_factory=dict) + mask: Optional[MaskChainSpec] = None + loader_path: Optional[str] = None + loader_post_mult: int = 1 + + +def _fmt_val(v: Any, prefix: str, frame_shift: int) -> Tuple[str, List[str]]: + """Formats a Fusion Input value and returns (lua_rhs, extra_aux_defs).""" + if isinstance(v, SplineParam): + sname = f"{prefix}{v.spline_name}" + if v.kind == "step" and v.keyframes is not None: + shifted = {k + frame_shift: val for k, val in v.keyframes.items()} + return f'Input {{ SourceOp = "{sname}", Source = "Value", }}', [step_spline(sname, shifted)] + if v.kind == "linear" and v.keyframes is not None: + shifted = {k + frame_shift: val for k, val in v.keyframes.items()} + return f'Input {{ SourceOp = "{sname}", Source = "Value", }}', [linear_spline(sname, shifted)] + if v.kind in ("expr_num", "expr_pt") and v.expr_inputs is not None: + src_port = "NumberResult" if v.kind == "expr_num" else "PointResult" + lines = [] + for ek, ev in v.expr_inputs.items(): + if isinstance(ev, str): + lines.append(f'{ek} = Input {{ Value = "{ev}", }},') + elif isinstance(ev, tuple): + lines.append(f"{ek} = Input {{ Value = {{ {ev[0]}, {ev[1]} }}, }},") + else: + lines.append(f"{ek} = Input {{ Value = {ev}, }},") + 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}," + return f'Input {{ SourceOp = "{sname}", Source = "{src_port}", }}', [expr_def] + if isinstance(v, tuple) and len(v) == 2 and v[0] == "FuID": + return f'Input {{ Value = FuID {{ "{v[1]}" }}, }}', [] + if isinstance(v, tuple) and len(v) == 2: + return f"Input {{ Value = {{ {v[0]}, {v[1]} }}, }}", [] + if isinstance(v, str): + return f'Input {{ Value = "{v}", }}', [] + return f"Input {{ Value = {v}, }}", [] + + +@dataclass +class FuzzGraph: + seed: int + eval_frame: int + nodes: List[DagNode] + + def clone(self) -> "FuzzGraph": + import copy + return copy.deepcopy(self) + + def output_node(self) -> str: + return self.nodes[-1].name + + def active_cone_set(self, target_name: str) -> set: + by_name = {n.name: n for n in self.nodes} + seen = set() + stack = [target_name] + while stack: + cur = stack.pop() + if cur in seen or cur not in by_name: + continue + seen.add(cur) + nd = by_name[cur] + if nd.primary_src: + stack.append(nd.primary_src) + if nd.secondary_src: + stack.append(nd.secondary_src) + return seen + + def prune_to(self, target_name: str) -> "FuzzGraph": + g = self.clone() + cone = g.active_cone_set(target_name) + g.nodes = [n for n in g.nodes if n.name in cone] + return g + + def bypass_node(self, node_name: str) -> Optional["FuzzGraph"]: + g = self.clone() + target = next((n for n in g.nodes if n.name == node_name), None) + if target is None or target.is_source or target.primary_src is None: + return None + repl = target.primary_src + for n in g.nodes: + if n.primary_src == node_name: + n.primary_src = repl + if n.secondary_src == node_name: + n.secondary_src = repl + g.nodes = [n for n in g.nodes if n.name != node_name] + if not g.nodes: + return None + return g.prune_to(g.nodes[-1].name) + + def strip_mask(self, node_name: str) -> Optional["FuzzGraph"]: + g = self.clone() + for n in g.nodes: + if n.name == node_name and n.mask is not None: + n.mask = None + return g + return None + + def flatten_splines(self) -> Optional["FuzzGraph"]: + g = self.clone() + changed = False + for n in g.nodes: + for k, v in list(n.params.items()): + if isinstance(v, SplineParam): + changed = True + if v.kind in ("step", "linear"): + n.params[k] = v.eval_at(g.eval_frame) + elif v.kind == "expr_num": + n.params[k] = 0.75 + else: + n.params[k] = (0.45, 0.55) + return g if changed else None + + def summary_tools(self) -> List[Dict[str, Any]]: + out = [] + for n in self.nodes: + p_short = {} + for k, v in n.params.items(): + if isinstance(v, SplineParam): + p_short[k] = f"<{v.kind}>" + elif isinstance(v, tuple) and len(v) == 2 and v[0] == "FuID": + p_short[k] = v[1] + else: + p_short[k] = v + entry: Dict[str, Any] = {"name": n.name, "kind": n.kind, "params": p_short} + if n.mask is not None: + entry["mask"] = [m.kind for m in n.mask.nodes] + out.append(entry) + return out + + def to_lua_defs(self, prefix: str = "", frame_shift: int = 0) -> Tuple[List[str], List[str], str]: + """Emits (tool_blocks, aux_splines_or_exprs, final_output_name).""" + tool_blocks: List[str] = [] + aux_blocks: List[str] = [] + + for n in self.nodes: + full_name = f"{prefix}{n.name}" + if n.kind == "Loader": + assert n.loader_path is not None + tool_blocks.append(make_loader(full_name, n.loader_path, post_mult=n.loader_post_mult)) + continue + + # Emit mask chain if present + if n.mask is not None: + for mi, mn in enumerate(n.mask.nodes): + mname = f"{prefix}{mn.name}" + in_lines = [] + if mn.prev_mask: + in_lines.append(f'EffectMask = Input {{ SourceOp = "{prefix}{mn.prev_mask}", Source = "Mask", }},') + if mn.paint_mode: + in_lines.append(f'PaintMode = Input {{ Value = FuID {{ "{mn.paint_mode}" }}, }},') + for pk, pv in mn.params.items(): + if pk == "Polyline": + in_lines.append(pv) + else: + rhs, extra = _fmt_val(pv, prefix, frame_shift) + in_lines.append(f"{pk} = {rhs},") + aux_blocks.extend(extra) + tool_blocks.append( + f"\t\t{mname} = {mn.kind} {{\n\t\t\tInputs = {{\n\t\t\t\t" + + "\n\t\t\t\t".join(in_lines) + + "\n\t\t\t},\n\t\t}," + ) + + in_lines = [] + if n.primary_port and n.primary_src: + in_lines.append(f'{n.primary_port} = Input {{ SourceOp = "{prefix}{n.primary_src}", Source = "Output", }},') + if n.secondary_port and n.secondary_src: + in_lines.append(f'{n.secondary_port} = Input {{ SourceOp = "{prefix}{n.secondary_src}", Source = "Output", }},') + if n.mask is not None: + in_lines.append(f'EffectMask = Input {{ SourceOp = "{prefix}{n.mask.output_name()}", Source = "Mask", }},') + if n.mask.apply_inverted: + in_lines.append("ApplyMaskInverted = Input { Value = 1, },") + if n.mask.multiply_by_mask: + in_lines.append("MultiplyByMask = Input { Value = 1, },") + + for pk, pv in n.params.items(): + rhs, extra = _fmt_val(pv, prefix, frame_shift) + in_lines.append(f"{pk} = {rhs},") + aux_blocks.extend(extra) + + tool_blocks.append( + f"\t\t{full_name} = {n.kind} {{\n\t\t\tInputs = {{\n\t\t\t\t" + + "\n\t\t\t\t".join(in_lines) + + "\n\t\t\t},\n\t\t}," + ) + + return tool_blocks, aux_blocks, f"{prefix}{self.nodes[-1].name}" + + +def _gen_mask_chain(rng: random.Random, tag: str) -> MaskChainSpec: + def one_mask(name: str, prev: Optional[str]) -> MaskNodeSpec: + kind = rng.choice(["EllipseMask", "RectangleMask", "PolylineMask"]) + soft = rng.choice([0.0, 0.015, 0.04, 0.09]) + inv = rng.choice([0, 0, 1]) + lvl = round(rng.uniform(0.55, 1.0), 3) + params: Dict[str, Any] = { + "MaskWidth": 256, + "MaskHeight": 256, + "SoftEdge": soft, + "Invert": inv, + "Level": lvl, + } + if kind in ("EllipseMask", "RectangleMask"): + params["Center"] = (round(rng.uniform(0.3, 0.7), 3), round(rng.uniform(0.3, 0.7), 3)) + params["Width"] = round(rng.uniform(0.25, 0.65), 3) + params["Height"] = round(rng.uniform(0.25, 0.65), 3) + params["Angle"] = round(rng.uniform(-45.0, 45.0), 1) + if kind == "RectangleMask" and rng.random() < 0.4: + params["CornerRadius"] = round(rng.uniform(0.1, 0.4), 2) + if rng.random() < 0.25: + params["Solid"] = 0 + params["BorderWidth"] = round(rng.uniform(0.02, 0.06), 3) + else: + x0 = round(rng.uniform(-0.35, -0.1), 3) + y0 = round(rng.uniform(-0.35, -0.1), 3) + x1 = round(rng.uniform(0.1, 0.35), 3) + y1 = round(rng.uniform(-0.3, 0.05), 3) + y2 = round(rng.uniform(0.15, 0.38), 3) + params["Polyline"] = ( + f"Polyline = Input {{ Value = Polyline {{ Closed = true, Points = {{ " + f"{{ Linear = true, X = {x0}, Y = {y0} }}, " + f"{{ Linear = true, X = {x1}, Y = {y1} }}, " + f"{{ Linear = true, X = 0.0, Y = {y2} }} }} }}, }}," + ) + pm = rng.choice(["Merge", "Add", "Subtract", "Minimum", "Maximum", "Multiply", "Invert"]) if prev else None + return MaskNodeSpec(name=name, kind=kind, params=params, paint_mode=pm, prev_mask=prev) + + m0 = one_mask(f"{tag}_M0", None) + chain = [m0] + if rng.random() < 0.45: + chain.append(one_mask(f"{tag}_M1", m0.name)) + return MaskChainSpec( + nodes=chain, + apply_inverted=1 if rng.random() < 0.3 else 0, + multiply_by_mask=1 if rng.random() < 0.25 else 0, + ) + + +def generate_random_dag(seed: int, assets: Dict[str, str]) -> FuzzGraph: + """Csmith-style seeded generator producing valid 4-9 node Fusion DAGs.""" + rng = random.Random(seed) + eval_frame = rng.choice([0, 1, 2]) + nodes: List[DagNode] = [] + + def make_source(idx: int) -> DagNode: + name = f"S{idx}" + stype = rng.choice(["Loader", "Loader", "Background", "FastNoise", "Plasma"]) + if stype == "Loader": + plate = rng.choice(["color", "fg", "small", "bump"]) + pm = rng.choice([1, 1, 0]) + return DagNode(name=name, kind="Loader", is_source=True, loader_path=assets[plate], loader_post_mult=pm) + if stype == "Background": + btype = rng.choice(["Solid", "Horizontal", "Vertical", "FourCorner"]) + p: Dict[str, Any] = { + "Width": 256, + "Height": 256, + "Type": ("FuID", btype), + "TopLeftRed": round(rng.uniform(0.05, 0.95), 3), + "TopLeftGreen": round(rng.uniform(0.05, 0.95), 3), + "TopLeftBlue": round(rng.uniform(0.05, 0.95), 3), + "TopLeftAlpha": round(rng.uniform(0.4, 1.0), 3), + } + if btype != "Solid": + p["TopRightRed"] = round(rng.uniform(0.05, 0.95), 3) + p["TopRightGreen"] = round(rng.uniform(0.05, 0.95), 3) + p["TopRightBlue"] = round(rng.uniform(0.05, 0.95), 3) + p["BottomLeftRed"] = round(rng.uniform(0.05, 0.95), 3) + p["BottomLeftGreen"] = round(rng.uniform(0.05, 0.95), 3) + p["BottomLeftBlue"] = round(rng.uniform(0.05, 0.95), 3) + if rng.random() < 0.35: + p["Depth"] = rng.choice([1, 3, 4]) + return DagNode(name=name, kind="Background", is_source=True, params=p) + if stype == "FastNoise": + return DagNode( + name=name, + kind="FastNoise", + is_source=True, + params={ + "Width": 256, + "Height": 256, + "Detail": round(rng.uniform(0.5, 6.0), 2), + "Contrast": round(rng.uniform(0.4, 2.2), 2), + "Brightness": round(rng.uniform(-0.3, 0.3), 2), + "XScale": round(rng.uniform(2.0, 18.0), 2), + "YScale": round(rng.uniform(2.0, 18.0), 2), + "Seethe": round(rng.uniform(0.0, 50.0), 2), + "Discontinuous": rng.choice([0, 1]), + "Color1Alpha": 1, + }, + ) + return DagNode( + name=name, + kind="Plasma", + is_source=True, + params={ + "Width": 256, + "Height": 256, + "Phase": round(rng.uniform(0.0, 1.0), 3), + "Scale": round(rng.uniform(0.6, 2.5), 2), + }, + ) + + num_sources = rng.choice([1, 2, 2]) + for si in range(num_sources): + nodes.append(make_source(si)) + + op_pool = [ + "Transform", "Merge", "Dissolve", "BrightnessContrast", "ColorCorrector", + "ChannelBoolean", "Blur", "Glow", "SoftGlow", "DirectionalBlur", + "DVE", "CornerPositioner", "Displace", "Vortex", "Drip", "Dent", + "ChangeDepth", "GamutConvert", "ColorGain", "Custom", + ] + num_internal = rng.randint(4, 9) + has_anim = rng.random() < 0.30 + has_inf_edges = False + + for ni in range(num_internal): + nname = f"N{ni}" + kind = rng.choice(op_pool) + if kind == "Drip" and has_inf_edges: + kind = "Dent" + # Prefer chaining mostly from recent nodes while allowing DAG forks from earlier nodes + avail = [n.name for n in nodes] + src_a = avail[-1] if rng.random() < 0.65 else rng.choice(avail) + src_b = rng.choice(avail) + + mask = _gen_mask_chain(rng, nname) if (kind not in ("ChangeDepth",) and rng.random() < 0.32) else None + blend = round(rng.uniform(0.55, 1.0), 2) if rng.random() < 0.25 else 1.0 + + prim_port = "Input" + sec_port: Optional[str] = None + sec_src: Optional[str] = None + params: Dict[str, Any] = {} + + if kind == "Transform": + ang: Any = round(rng.uniform(-45.0, 45.0), 1) + if has_anim and ni == 0: + ang = SplineParam(f"{nname}_Ang", "linear", keyframes={0: -15.0, 2: 35.0}) + ed_val = rng.choice([0, 1, 2, 3]) + if ed_val in (1, 3): + has_inf_edges = True + params = { + "Center": (round(rng.uniform(0.32, 0.68), 3), round(rng.uniform(0.32, 0.68), 3)), + "Pivot": (round(rng.uniform(0.25, 0.75), 3), round(rng.uniform(0.25, 0.75), 3)), + "Size": round(rng.uniform(0.65, 1.35), 3), + "Aspect": round(rng.uniform(0.75, 1.35), 3), + "Angle": ang, + "Edges": ed_val, + "Blend": blend, + } + elif kind == "Merge": + prim_port = "Background" + sec_port = "Foreground" + sec_src = src_b + m_edges = rng.choice([0, 1, 2, 3]) if rng.random() < 0.3 else 0 + if m_edges in (1, 3): + has_inf_edges = True + params = { + "ApplyMode": ("FuID", rng.choice(["Normal", "Screen", "Multiply", "Overlay", "Difference", "SoftLight", "HardLight", "ColorDodge", "Exclusion"])), + "Operator": ("FuID", rng.choice(["Over", "Over", "In", "Held Out", "Atop", "XOr"])), + "Size": round(rng.uniform(0.55, 1.15), 3), + "Angle": round(rng.uniform(-25.0, 25.0), 1), + "Center": (round(rng.uniform(0.35, 0.65), 3), round(rng.uniform(0.35, 0.65), 3)), + "Gain": round(rng.uniform(0.35, 1.25), 2), + "SubtractiveAdditive": rng.choice([0.0, 0.5, 1.0]), + "BurnIn": round(rng.uniform(0.0, 0.4), 2) if rng.random() < 0.35 else 0.0, + "Edges": m_edges, + "PerformDepthMerge": 0, + "Blend": blend, + } + elif kind == "Dissolve": + prim_port = "Background" + sec_port = "Foreground" + sec_src = src_b + params = {"Mix": round(rng.uniform(0.2, 0.85), 2), "Blend": blend} + elif kind == "BrightnessContrast": + g_val: Any = round(rng.uniform(0.5, 2.2), 2) + if has_anim and ni == 1: + g_val = SplineParam( + f"{nname}_ExprG", + "expr_num", + expr_inputs={"n1": round(rng.uniform(0.6, 1.6), 2), "NumberExpression": "n1 * 0.8 + 0.35"}, + ) + params = { + "Gain": g_val, + "Lift": round(rng.uniform(-0.15, 0.2), 2), + "Gamma": round(rng.uniform(0.6, 1.6), 2), + "Contrast": round(rng.uniform(-0.25, 0.45), 2), + "Brightness": round(rng.uniform(-0.2, 0.2), 2), + "Saturation": round(rng.uniform(0.3, 1.6), 2), + "PreDividePostMultiply": rng.choice([0, 1]), + "Blend": blend, + } + elif kind == "ColorCorrector": + params = { + "WheelHue1": round(rng.uniform(-0.35, 0.35), 3), + "WheelSaturation1": round(rng.uniform(0.5, 1.6), 2), + "WheelTintAngle1": round(rng.uniform(-0.5, 0.5), 3), + "WheelTintLength1": round(rng.uniform(0.0, 0.7), 2), + "TintMode": rng.choice([0, 1, 2]), + "MasterRGBGain": round(rng.uniform(0.65, 1.45), 2), + "ShadowsRGBGain": round(rng.uniform(0.65, 1.35), 2), + "HighlightsRGBGain": round(rng.uniform(0.65, 1.35), 2), + "PreDividePostMultiply": rng.choice([0, 1]), + "Blend": blend, + } + elif kind == "ChannelBoolean": + prim_port = "Background" + sec_port = "Foreground" + sec_src = src_b + params = { + "Operation": rng.choice([0, 1, 2, 6, 8, 9, 10, 13]), + "ToRed": rng.choice([0, 1, 2, 5, 10]), + "ToGreen": rng.choice([0, 1, 2, 6, 10]), + "ToBlue": rng.choice([0, 1, 2, 7, 10]), + "ToAlpha": rng.choice([3, 8, 16]), + "Blend": blend, + } + elif kind == "Blur": + params = { + "Filter": ("FuID", rng.choice(["Gaussian", "Box", "Fast Gaussian"])), + "LockBlurXY": 0, + "XBlurSize": round(rng.uniform(2.0, 18.0), 1), + "YBlurSize": round(rng.uniform(2.0, 18.0), 1), + "ClippingMode": ("FuID", rng.choice(["Frame", "None"])), + "Blend": blend, + } + elif kind == "Glow": + params = { + "LockGlowSize": 0, + "XGlowSize": round(rng.uniform(4.0, 20.0), 1), + "YGlowSize": round(rng.uniform(2.0, 14.0), 1), + "Glow": round(rng.uniform(0.4, 0.88), 2), + "Blend": blend, + } + elif kind == "SoftGlow": + params = { + "LockGlowSize": 0, + "XGlowSize": round(rng.uniform(4.0, 20.0), 1), + "YGlowSize": round(rng.uniform(2.0, 16.0), 1), + "Gain": round(rng.uniform(0.8, 2.5), 2), + "Threshold": round(rng.uniform(0.1, 0.65), 2), + "Blend": blend, + } + elif kind == "DirectionalBlur": + params = { + "Type": rng.choice([0, 1, 2]), + "Length": round(rng.uniform(0.02, 0.12), 3), + "Angle": round(rng.uniform(-90.0, 90.0), 1), + "Glow": round(rng.uniform(0.0, 0.4), 2), + "Blend": blend, + } + elif kind == "DVE": + params = { + "XRotation": round(rng.uniform(-35.0, 35.0), 1), + "YRotation": round(rng.uniform(-35.0, 35.0), 1), + "ZRotation": round(rng.uniform(-25.0, 25.0), 1), + "ZMove": round(rng.uniform(0.95, 1.6), 2), + "Pivot": (round(rng.uniform(0.3, 0.7), 2), round(rng.uniform(0.3, 0.7), 2)), + "Center": (round(rng.uniform(0.4, 0.6), 2), round(rng.uniform(0.4, 0.6), 2)), + "Blend": blend, + } + elif kind == "CornerPositioner": + params = { + "TopLeft": (round(rng.uniform(0.05, 0.28), 3), round(rng.uniform(0.72, 0.95), 3)), + "TopRight": (round(rng.uniform(0.72, 0.95), 3), round(rng.uniform(0.72, 0.95), 3)), + "BottomLeft": (round(rng.uniform(0.05, 0.28), 3), round(rng.uniform(0.05, 0.28), 3)), + "BottomRight": (round(rng.uniform(0.72, 0.95), 3), round(rng.uniform(0.05, 0.28), 3)), + "Blend": blend, + } + elif kind == "Displace": + sec_port = "Foreground" + sec_src = src_b + dtype = rng.choice([0, 1]) + if dtype == 0: + params = { + "Type": 0, + "RefractionStrength": round(rng.uniform(0.04, 0.16), 3), + "Spread": round(rng.uniform(0.0, 0.35), 2), + "LightPower": round(rng.uniform(0.0, 0.6), 2), + "Blend": blend, + } + else: + params = { + "Type": 1, + "XChannel": rng.choice([0, 1, 2]), + "YChannel": rng.choice([0, 1, 2]), + "XOffset": -0.5, + "YOffset": -0.5, + "XRefraction": round(rng.uniform(-0.12, 0.12), 3), + "YRefraction": round(rng.uniform(-0.12, 0.12), 3), + "Blend": blend, + } + elif kind == "Vortex": + params = { + "Center": (round(rng.uniform(0.35, 0.65), 2), round(rng.uniform(0.35, 0.65), 2)), + "Size": round(rng.uniform(0.35, 1.2), 2), + "Angle": round(rng.uniform(-2.5, 2.5), 2), + "Power": round(rng.uniform(0.8, 3.0), 2), + "Blend": blend, + } + elif kind == "Drip": + params = { + "Center": (round(rng.uniform(0.35, 0.65), 2), round(rng.uniform(0.35, 0.65), 2)), + "Strength": round(rng.uniform(0.4, 1.0), 2), + "Amplitude": round(rng.uniform(0.04, 0.14), 3), + "Frequency": round(rng.uniform(2.0, 7.0), 1), + "Phase": round(rng.uniform(0.0, 1.0), 2), + "Shape": rng.choice([0, 1]), + "Blend": blend, + } + elif kind == "Dent": + params = { + "Center": (round(rng.uniform(0.35, 0.65), 2), round(rng.uniform(0.35, 0.65), 2)), + "Size": round(rng.uniform(0.35, 0.85), 2), + "Strength": round(rng.uniform(0.3, 0.9), 2), + "Type": rng.choice([0, 1, 2, 3]), + "Blend": blend, + } + elif kind == "ChangeDepth": + params = {"Depth": rng.choice([1, 2, 3, 4])} + elif kind == "GamutConvert": + params = { + "SourceSpace": ("FuID", rng.choice(["NoChange", "sRGB", "Rec709"])), + "OutputSpace": ("FuID", rng.choice(["NoChange", "sRGB", "Rec709"])), + "RemoveGamma": rng.choice([0, 1]), + "AddGamma": rng.choice([0, 1]), + "PreDividePostMultiply": rng.choice([0, 1]), + "Blend": blend, + } + elif kind == "ColorGain": + params = { + "GainRed": round(rng.uniform(0.6, 1.5), 2), + "GainGreen": round(rng.uniform(0.6, 1.5), 2), + "GainBlue": round(rng.uniform(0.6, 1.5), 2), + "LiftGreen": round(rng.uniform(-0.1, 0.15), 2), + "GammaBlue": round(rng.uniform(0.7, 1.4), 2), + "MidHue": round(rng.uniform(0.1, 0.9), 2), + "PreDividePostMultiply": rng.choice([0, 1]), + "Blend": blend, + } + elif kind == "Custom": + prim_port = "Image1" + sec_port = "Image2" + sec_src = src_b + params = { + "NumberIn1": round(rng.uniform(0.3, 0.8), 2), + "PointIn1": (round(rng.uniform(0.3, 0.7), 2), round(rng.uniform(0.3, 0.7), 2)), + "Setup1": "1 - n1", + "Intermediate1": "max(0, 1 - dist(x, y, p1x, p1y) * 1.8)", + "RedExpression": "if(x > p1x, getr1b(x - 0.08, y) * i1 + r2 * s1, r1)", + "GreenExpression": "g1 * (1 - i1) + g2 * i1", + "BlueExpression": "b1 * n1 + b2 * (1 - n1)", + "AlphaExpression": "a1", + "Blend": blend, + } + + nodes.append( + DagNode( + name=nname, + kind=kind, + is_source=False, + primary_port=prim_port, + primary_src=src_a, + secondary_port=sec_port, + secondary_src=sec_src, + params=params, + mask=mask, + ) + ) + + return FuzzGraph(seed=seed, eval_frame=eval_frame, nodes=nodes) + + +def write_standalone_graph_comp(graph: FuzzGraph, prefix: str) -> Path: + root = ensure_dirs() + tool_blocks, aux_blocks, out_op = graph.to_lua_defs(prefix="", frame_shift=0) + # Normalize over BlackBG so Saver compares RGB over opaque black consistently + tool_blocks.append('\t\t_BlackBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftAlpha = Input { Value = 1, }, }, },') + tool_blocks.append(f'\t\t_NormOut = Merge {{ Inputs = {{ Background = Input {{ SourceOp = "_BlackBG", Source = "Output", }}, Foreground = Input {{ SourceOp = "{out_op}", Source = "Output", }}, }}, }},') + tool_blocks.append(make_saver("_NormOut", prefix)) + comp_path = root / "comps" / f"{prefix}.comp" + comp_path.write_text(make_comp("\n".join(tool_blocks + aux_blocks), graph.eval_frame, start_frame=graph.eval_frame)) + return comp_path + + +def run_multi_graph_batch( + items: List[Tuple[str, FuzzGraph]], + batch_prefix: str, + render_gt: bool = True, + timeout_sec: int = 180, +) -> Dict[int, Dict[str, Any]]: + """Packs multiple FuzzGraphs into one multi-frame .comp using a Merge switch chain.""" + root = ensure_dirs() + all_tools = [ + '\t\t_BlackBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftAlpha = Input { Value = 1, }, }, },' + ] + all_aux: List[str] = [] + cases: List[Tuple[int, str, str]] = [] + labels: Dict[int, str] = {} + + for f_idx, (label, g) in enumerate(items): + pfx = f"G{f_idx}_" + frame_shift = f_idx - g.eval_frame + tb, ab, out_op = g.to_lua_defs(prefix=pfx, frame_shift=frame_shift) + all_tools.extend(tb) + all_aux.extend(ab) + cases.append((f_idx, label, out_op)) + labels[f_idx] = label + + sw_nodes, sw_splines, final_op = build_switch_chain(cases, "_BlackBG", "FB") + all_tools.extend(sw_nodes) + all_aux.extend(sw_splines) + all_tools.append(make_saver(final_op, batch_prefix)) + + comp_path = root / "comps" / f"{batch_prefix}.comp" + comp_path.write_text(make_comp("\n".join(all_tools + all_aux), len(cases) - 1, start_frame=0)) + return run_comp_both( + comp_path, + batch_prefix, + list(range(len(cases))), + labels, + render_gt=render_gt, + timeout_sec=timeout_sec, + ) + + +def bisect_failing_graph( + graph: FuzzGraph, + threshold_pct: float, + render_gt: bool = True, + timeout_sec: int = 180, +) -> Dict[str, Any]: + """Node-by-node graph bisection that trims downstream & upstream nodes while preserving MAE > threshold.""" + seed = graph.seed + print(f" [bisect] seed={seed} ({len(graph.nodes)} nodes) ...", flush=True) + + # Step 0: Verify standalone reproduction + st_prefix = f"bisect_s{seed}_orig" + st_comp = write_standalone_graph_comp(graph, st_prefix) + st_res = run_comp_both( + st_comp, st_prefix, [graph.eval_frame], {graph.eval_frame: f"seed_{seed}"}, render_gt=render_gt, timeout_sec=timeout_sec + )[graph.eval_frame] + orig_mae = st_res["mae_pct"] + if orig_mae <= threshold_pct: + return { + "seed": seed, + "reproduced_standalone": False, + "orig_mae_pct": orig_mae, + "min_mae_pct": orig_mae, + "min_rmse_255": st_res["rmse_255"], + "note": "batch failure did not reproduce standalone", + "tools": graph.summary_tools(), + } + + # Step 1: Prefix trim (find earliest failing sink node in topological order) + non_src = [n for n in graph.nodes if not n.is_source] + cur = graph.clone() + if len(non_src) > 1: + prefix_items = [(f"prefix_{nd.name}", graph.prune_to(nd.name)) for nd in non_src] + pref_res = run_multi_graph_batch( + prefix_items, f"bisect_s{seed}_prefixes", render_gt=render_gt, timeout_sec=timeout_sec + ) + for idx, nd in enumerate(non_src): + if pref_res[idx]["mae_pct"] > threshold_pct: + cur = graph.prune_to(nd.name) + print(f" [prefix] trimmed sink to {nd.name} ({len(cur.nodes)} nodes, MAE={pref_res[idx]['mae_pct']:.2f}%)", flush=True) + break + + # Step 2: Iterative upstream node & mask removal + spline flattening + for rnd in range(6): + candidates: List[Tuple[str, str, FuzzGraph]] = [] # (desc, action, candidate_graph) + # Try flattening splines first + flat = cur.flatten_splines() + if flat is not None: + candidates.append(("flatten_splines", "flatten", flat)) + # Try stripping masks + for nd in cur.nodes: + if nd.mask is not None: + sm = cur.strip_mask(nd.name) + if sm is not None: + candidates.append((f"strip_mask:{nd.name}", "mask", sm)) + # Try bypassing each upstream non-source node + for nd in cur.nodes: + if not nd.is_source and nd.name != cur.output_node(): + bp = cur.bypass_node(nd.name) + if bp is not None: + candidates.append((f"bypass:{nd.name}", "bypass", bp)) + + if not candidates: + break + + batch_items = [(desc, cg) for desc, _act, cg in candidates] + cand_res = run_multi_graph_batch( + batch_items, f"bisect_s{seed}_r{rnd}", render_gt=render_gt, timeout_sec=timeout_sec + ) + + # Pick best failing candidate: fewest nodes, fewest masks, no splines + failing: List[Tuple[Tuple[int, int, int], str, FuzzGraph, float]] = [] + for idx, (desc, _act, cg) in enumerate(candidates): + m = cand_res[idx] + if m["mae_pct"] > threshold_pct: + mask_cnt = sum(1 for x in cg.nodes if x.mask is not None) + spline_cnt = sum( + 1 for x in cg.nodes for v in x.params.values() if isinstance(v, SplineParam) + ) + score = (len(cg.nodes), mask_cnt, spline_cnt) + failing.append((score, desc, cg, m["mae_pct"])) + + if not failing: + break + failing.sort(key=lambda t: t[0]) + _score, best_desc, best_cg, best_mae = failing[0] + cur = best_cg + print(f" [round {rnd}] {best_desc} -> {len(cur.nodes)} nodes (MAE={best_mae:.2f}%)", flush=True) + + # Step 3: Standalone verification of minimal reproducer + repro_prefix = f"repro_seed_{seed}" + repro_comp = write_standalone_graph_comp(cur, repro_prefix) + final_res = run_comp_both( + repro_comp, repro_prefix, [cur.eval_frame], {cur.eval_frame: repro_prefix}, render_gt=render_gt, timeout_sec=timeout_sec + )[cur.eval_frame] + + return { + "seed": seed, + "reproduced_standalone": True, + "orig_node_count": len(graph.nodes), + "min_node_count": len(cur.nodes), + "orig_mae_pct": orig_mae, + "min_mae_pct": final_res["mae_pct"], + "min_rmse_255": final_res["rmse_255"], + "comp_path": str(repro_comp), + "eval_frame": cur.eval_frame, + "tools": cur.summary_tools(), + } + + +# --------------------------------------------------------------------------- +# CLI & Main Entrypoint +# --------------------------------------------------------------------------- + + +def print_table(title: str, rows: List[Dict[str, Any]], threshold_pct: float) -> None: + print(f"\n=== {title} ===") + print(f" {'Case':<44s} | {'MAE%':>7s} | {'MAE':>6s} | {'RMSE':>6s} | {'Status'}") + print(f" {'-'*44}-+-{'-'*7}-+-{'-'*6}-+-{'-'*6}-+-{'-'*18}") + for r in rows: + label = str(r.get("label", ""))[:44] + mae_pct = r.get("mae_pct", 100.0) + mae = r.get("mae_255", 255.0) + rmse = r.get("rmse_255", 255.0) + if r.get("error"): + status = f"ERR: {str(r['error'])[:28]}" + elif r.get("size_mismatch"): + status = f"SIZE {r.get('dims_ours')}!={r.get('dims_gt')}" + elif mae_pct > threshold_pct: + status = "FAIL" + else: + status = "PASS" + print(f" {label:<44s} | {mae_pct:6.2f}% | {mae:6.2f} | {rmse:6.2f} | {status}") + + +def main() -> int: + parser = argparse.ArgumentParser(description="Fusion 21.1 vs Fission differential matrix & DAG fuzzer") + parser.add_argument("--matrix", action="store_true", help="Run all edge-case parameter matrix suites") + parser.add_argument("--suite", action="append", default=[], help="Specific matrix suite(s) to run") + parser.add_argument("--fuzz", action="store_true", help="Run seeded randomized DAG fuzzer") + parser.add_argument("--seeds", type=int, default=20, help="Number of random seeds to fuzz (default 20)") + parser.add_argument("--seed-start", type=int, default=1, help="Starting seed integer (default 1)") + parser.add_argument("--bisect", action="store_true", help="Auto-bisect failing fuzz seeds (> threshold MAE%)") + parser.add_argument("--threshold", type=float, default=1.5, help="MAE%% failure threshold (default 1.5)") + parser.add_argument("--batch-size", type=int, default=15, help="Seeds per batched Fusion render (default 15)") + parser.add_argument("--timeout", type=int, default=180, help="Per-render timeout in seconds (default 180)") + parser.add_argument("--no-gt", action="store_true", help="Skip sg render and reuse existing GT PNGs") + parser.add_argument("--report-json", type=str, default="", help="Write structured JSON report to path") + args = parser.parse_args() + + if not args.matrix and not args.fuzz: + parser.print_help() + return 1 + + assets = generate_assets() + report: Dict[str, Any] = { + "threshold_pct": args.threshold, + "matrix": {}, + "fuzz": {"seeds": [], "bisected": []}, + } + + if args.matrix: + suites = args.suite if args.suite else list(MATRIX_BUILDERS.keys()) + for sname in suites: + if sname not in MATRIX_BUILDERS: + print(f"Unknown matrix suite: {sname}", file=sys.stderr) + return 2 + comp_path, prefix, cases = MATRIX_BUILDERS[sname](assets) + frames = [c[0] for c in cases] + labels = {c[0]: c[1] for c in cases} + res = run_comp_both( + comp_path, + prefix, + frames, + labels, + render_gt=not args.no_gt, + timeout_sec=args.timeout, + ) + rows = [res[f] for f in frames] + print_table(sname, rows, args.threshold) + fails = [r for r in rows if r.get("mae_pct", 100.0) > args.threshold or r.get("size_mismatch") or r.get("error")] + mean_mae = sum(r["mae_pct"] for r in rows) / max(1, len(rows)) + report["matrix"][sname] = { + "total": len(rows), + "passed": len(rows) - len(fails), + "failed": len(fails), + "mean_mae_pct": round(mean_mae, 4), + "cases": rows, + } + + if args.fuzz: + seed_ids = list(range(args.seed_start, args.seed_start + args.seeds)) + graphs = {s: generate_random_dag(s, assets) for s in seed_ids} + fuzz_rows: List[Dict[str, Any]] = [] + + for chunk_idx in range(0, len(seed_ids), args.batch_size): + chunk = seed_ids[chunk_idx : chunk_idx + args.batch_size] + batch_items = [(f"seed_{s}_n{len(graphs[s].nodes)}", graphs[s]) for s in chunk] + batch_prefix = f"fuzz_batch_{chunk[0]}_{chunk[-1]}" + res = run_multi_graph_batch( + batch_items, + batch_prefix, + render_gt=not args.no_gt, + timeout_sec=args.timeout, + ) + # If the whole batch errored in sg render, fall back to individual seed renders + batch_errored = all(res[i].get("error") for i in range(len(chunk))) + if batch_errored: + print(f"[warn] Batch {batch_prefix} errored; falling back to per-seed renders...", file=sys.stderr) + for s in chunk: + g = graphs[s] + sp = f"fuzz_seed_{s}" + sc = write_standalone_graph_comp(g, sp) + sr = run_comp_both( + sc, sp, [g.eval_frame], {g.eval_frame: f"seed_{s}_n{len(g.nodes)}"}, + render_gt=not args.no_gt, timeout_sec=args.timeout, + )[g.eval_frame] + sr["seed"] = s + sr["tools"] = [n.kind for n in g.nodes if not n.is_source] + fuzz_rows.append(sr) + else: + for i, s in enumerate(chunk): + r = res[i] + r["seed"] = s + r["tools"] = [n.kind for n in graphs[s].nodes if not n.is_source] + fuzz_rows.append(r) + + print_table(f"fuzz seeds {args.seed_start}..{args.seed_start + args.seeds - 1}", fuzz_rows, args.threshold) + report["fuzz"]["seeds"] = fuzz_rows + + if args.bisect: + failing_seeds = [r for r in fuzz_rows if not r.get("error") and (r.get("mae_pct", 0.0) > args.threshold or r.get("size_mismatch"))] + print(f"\n=== Bisecting {len(failing_seeds)} failing seeds (MAE > {args.threshold}%) ===") + for r in failing_seeds: + s = r["seed"] + try: + b_res = bisect_failing_graph( + graphs[s], + threshold_pct=args.threshold, + render_gt=not args.no_gt, + timeout_sec=args.timeout, + ) + report["fuzz"]["bisected"].append(b_res) + except Exception as exc: + print(f" [bisect] seed={s} exception: {exc}", file=sys.stderr) + report["fuzz"]["bisected"].append({"seed": s, "error": str(exc)}) + + if args.report_json: + rp = Path(args.report_json) + rp.parent.mkdir(parents=True, exist_ok=True) + rp.write_text(json.dumps(report, indent=2)) + print(f"\n[report] Wrote JSON summary to {rp}") + + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) -- 2.54.1