| ... | @@ -0,0 +1,2296 @@ |
| 1 | #!/usr/bin/env python3 |
| 2 | """Csmith-style differential testing & fuzzing harness: Fusion Render Node 21.1 (sg render) vs Fission (render-check). |
| 3 | |
| 4 | Generates synthetic test plates & OBJ geometry (pure Python stdlib, no PIL/numpy), |
| 5 | runs an exhaustive edge-case parameter matrix (--matrix) across Merge, HDR/BitDepth, |
| 6 | Masks, Color/Blur/Glow, Warps/Shapes, 3D, and Misc tools, and runs a seeded randomized |
| 7 | DAG fuzzer (--fuzz) with automatic node-by-node graph bisection (--bisect). |
| 8 | """ |
| 9 | |
| 10 | import argparse |
| 11 | import json |
| 12 | import math |
| 13 | import os |
| 14 | import random |
| 15 | import re |
| 16 | import shutil |
| 17 | import struct |
| 18 | import subprocess |
| 19 | import sys |
| 20 | import time |
| 21 | import zlib |
| 22 | from dataclasses import dataclass, field |
| 23 | from pathlib import Path |
| 24 | from typing import Any, Dict, List, Optional, Tuple |
| 25 | |
| 26 | REPO = Path("/Users/clo/dev/compositor") |
| 27 | RENDER_CHECK = REPO / "target/release/render-check" |
| 28 | SMB_ROOT = Path("/Volumes/clover/Project/CloverCompositor/probes/diff_fuzz") |
| 29 | REMOTE_ROOT = "/srv/clover/Project/CloverCompositor/probes/diff_fuzz" |
| 30 | CONTAINER_ROOT = "/Volumes/clover/Project/CloverCompositor/probes/diff_fuzz" |
| 31 | LOCAL_FALLBACK = Path("/tmp/fission_diff_fuzz") |
| 32 | |
| 33 | # --------------------------------------------------------------------------- |
| 34 | # Storage / SG Transport Helpers |
| 35 | # --------------------------------------------------------------------------- |
| 36 | |
| 37 | |
| 38 | def use_smb() -> bool: |
| 39 | return Path("/Volumes/clover/Project/CloverCompositor").exists() |
| 40 | |
| 41 | |
| 42 | def local_root() -> Path: |
| 43 | return SMB_ROOT if use_smb() else LOCAL_FALLBACK |
| 44 | |
| 45 | |
| 46 | def ensure_dirs() -> Path: |
| 47 | root = local_root() |
| 48 | for sub in ("assets", "comps", "gt", "ours"): |
| 49 | (root / sub).mkdir(parents=True, exist_ok=True) |
| 50 | return root |
| 51 | |
| 52 | |
| 53 | def sync_asset_to_remote(local_path: Path) -> None: |
| 54 | if not use_smb(): |
| 55 | subprocess.run( |
| 56 | ["sg", "upload", str(local_path), f"{REMOTE_ROOT}/assets/{local_path.name}"], |
| 57 | check=True, |
| 58 | timeout=60, |
| 59 | ) |
| 60 | |
| 61 | |
| 62 | def ensure_render_check() -> Path: |
| 63 | if RENDER_CHECK.exists(): |
| 64 | return RENDER_CHECK |
| 65 | print(f"[build] {RENDER_CHECK} missing; building render-check --release...", file=sys.stderr) |
| 66 | subprocess.run( |
| 67 | ["cargo", "build", "--release", "-p", "engine", "--bin", "render-check"], |
| 68 | cwd=str(REPO), |
| 69 | check=True, |
| 70 | timeout=600, |
| 71 | ) |
| 72 | return RENDER_CHECK |
| 73 | |
| 74 | |
| 75 | # --------------------------------------------------------------------------- |
| 76 | # Pure Python Stdlib PNG Encoder / Decoder & Diff Metrics |
| 77 | # --------------------------------------------------------------------------- |
| 78 | |
| 79 | |
| 80 | def write_png_rgba(path: Path, w: int, h: int, rgba_bytes: bytes) -> None: |
| 81 | def chunk(tag: bytes, data: bytes) -> bytes: |
| 82 | return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF) |
| 83 | |
| 84 | raw = bytearray() |
| 85 | stride = w * 4 |
| 86 | for y in range(h): |
| 87 | raw.append(0) |
| 88 | raw.extend(rgba_bytes[y * stride : (y + 1) * stride]) |
| 89 | |
| 90 | ihdr = struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0) |
| 91 | png = ( |
| 92 | b"\x89PNG\r\n\x1a\n" |
| 93 | + chunk(b"IHDR", ihdr) |
| 94 | + chunk(b"IDAT", zlib.compress(bytes(raw), level=6)) |
| 95 | + chunk(b"IEND", b"") |
| 96 | ) |
| 97 | path.parent.mkdir(parents=True, exist_ok=True) |
| 98 | path.write_bytes(png) |
| 99 | |
| 100 | |
| 101 | def _paeth(a: int, b: int, c: int) -> int: |
| 102 | p = a + b - c |
| 103 | pa = abs(p - a) |
| 104 | pb = abs(p - b) |
| 105 | pc = abs(p - c) |
| 106 | if pa <= pb and pa <= pc: |
| 107 | return a |
| 108 | if pb <= pc: |
| 109 | return b |
| 110 | return c |
| 111 | |
| 112 | |
| 113 | def read_png_rgba(path: Path) -> Tuple[int, int, bytes]: |
| 114 | data = path.read_bytes() |
| 115 | if data[:8] != b"\x89PNG\r\n\x1a\n": |
| 116 | raise ValueError(f"Not a PNG file: {path}") |
| 117 | pos = 8 |
| 118 | w = h = bit_depth = color_type = interlace = 0 |
| 119 | idat = bytearray() |
| 120 | while pos + 8 <= len(data): |
| 121 | length = struct.unpack(">I", data[pos : pos + 4])[0] |
| 122 | tag = data[pos + 4 : pos + 8] |
| 123 | chunk_data = data[pos + 8 : pos + 8 + length] |
| 124 | pos += 12 + length |
| 125 | if tag == b"IHDR": |
| 126 | w, h, bit_depth, color_type, _comp, _filt, interlace = struct.unpack(">IIBBBBB", chunk_data) |
| 127 | elif tag == b"IDAT": |
| 128 | idat.extend(chunk_data) |
| 129 | elif tag == b"IEND": |
| 130 | break |
| 131 | |
| 132 | if interlace != 0: |
| 133 | raise ValueError(f"Interlaced PNG unsupported in pure-stdlib reader: {path}") |
| 134 | channels_map = {0: 1, 2: 3, 4: 2, 6: 4} |
| 135 | if color_type not in channels_map or bit_depth not in (8, 16): |
| 136 | raise ValueError(f"Unsupported PNG format (color={color_type}, depth={bit_depth}): {path}") |
| 137 | |
| 138 | ch = channels_map[color_type] |
| 139 | bypp = ch * (bit_depth // 8) |
| 140 | row_bytes = w * bypp |
| 141 | raw = zlib.decompress(bytes(idat)) |
| 142 | if len(raw) < h * (row_bytes + 1): |
| 143 | raise ValueError(f"Truncated PNG IDAT in {path}") |
| 144 | |
| 145 | prev = bytearray(row_bytes) |
| 146 | out = bytearray(w * h * 4) |
| 147 | idx_in = 0 |
| 148 | for y in range(h): |
| 149 | ftype = raw[idx_in] |
| 150 | idx_in += 1 |
| 151 | scan = bytearray(raw[idx_in : idx_in + row_bytes]) |
| 152 | idx_in += row_bytes |
| 153 | if ftype == 1: |
| 154 | for i in range(bypp, row_bytes): |
| 155 | scan[i] = (scan[i] + scan[i - bypp]) & 0xFF |
| 156 | elif ftype == 2: |
| 157 | for i in range(row_bytes): |
| 158 | scan[i] = (scan[i] + prev[i]) & 0xFF |
| 159 | elif ftype == 3: |
| 160 | for i in range(row_bytes): |
| 161 | a = scan[i - bypp] if i >= bypp else 0 |
| 162 | scan[i] = (scan[i] + ((a + prev[i]) >> 1)) & 0xFF |
| 163 | elif ftype == 4: |
| 164 | for i in range(row_bytes): |
| 165 | a = scan[i - bypp] if i >= bypp else 0 |
| 166 | b = prev[i] |
| 167 | c = prev[i - bypp] if i >= bypp else 0 |
| 168 | scan[i] = (scan[i] + _paeth(a, b, c)) & 0xFF |
| 169 | elif ftype != 0: |
| 170 | raise ValueError(f"Unknown PNG filter {ftype} in {path}") |
| 171 | prev = scan |
| 172 | |
| 173 | out_row = y * w * 4 |
| 174 | if bit_depth == 8: |
| 175 | if ch == 4: |
| 176 | out[out_row : out_row + w * 4] = scan |
| 177 | elif ch == 3: |
| 178 | for x in range(w): |
| 179 | si = x * 3 |
| 180 | di = out_row + x * 4 |
| 181 | out[di] = scan[si] |
| 182 | out[di + 1] = scan[si + 1] |
| 183 | out[di + 2] = scan[si + 2] |
| 184 | out[di + 3] = 255 |
| 185 | elif ch == 2: |
| 186 | for x in range(w): |
| 187 | si = x * 2 |
| 188 | di = out_row + x * 4 |
| 189 | v = scan[si] |
| 190 | out[di] = v |
| 191 | out[di + 1] = v |
| 192 | out[di + 2] = v |
| 193 | out[di + 3] = scan[si + 1] |
| 194 | else: |
| 195 | for x in range(w): |
| 196 | di = out_row + x * 4 |
| 197 | v = scan[x] |
| 198 | out[di] = v |
| 199 | out[di + 1] = v |
| 200 | out[di + 2] = v |
| 201 | out[di + 3] = 255 |
| 202 | else: |
| 203 | # 16-bit big endian -> 8-bit |
| 204 | for x in range(w): |
| 205 | si = x * bypp |
| 206 | di = out_row + x * 4 |
| 207 | vals = [((scan[si + k * 2] << 8) | scan[si + k * 2 + 1]) >> 8 for k in range(ch)] |
| 208 | if ch == 4: |
| 209 | out[di : di + 4] = bytes(vals) |
| 210 | elif ch == 3: |
| 211 | out[di : di + 4] = bytes((vals[0], vals[1], vals[2], 255)) |
| 212 | elif ch == 2: |
| 213 | out[di : di + 4] = bytes((vals[0], vals[0], vals[0], vals[1])) |
| 214 | else: |
| 215 | out[di : di + 4] = bytes((vals[0], vals[0], vals[0], 255)) |
| 216 | return w, h, bytes(out) |
| 217 | |
| 218 | |
| 219 | def compute_diff_metrics(ours_path: Path, gt_path: Path) -> Dict[str, Any]: |
| 220 | if not ours_path.exists(): |
| 221 | return {"error": f"missing ours: {ours_path}", "mae_pct": 100.0, "mae_255": 255.0, "rmse_255": 255.0} |
| 222 | if not gt_path.exists(): |
| 223 | return {"error": f"missing gt: {gt_path}", "mae_pct": 100.0, "mae_255": 255.0, "rmse_255": 255.0} |
| 224 | |
| 225 | ow, oh, ob = read_png_rgba(ours_path) |
| 226 | gw, gh, gb = read_png_rgba(gt_path) |
| 227 | size_mismatch = (ow != gw) or (oh != gh) |
| 228 | |
| 229 | # Compare over overlapping or resized if mismatched, matching render-check's RGB metric |
| 230 | cw = min(ow, gw) |
| 231 | ch = min(oh, gh) |
| 232 | if size_mismatch: |
| 233 | # Bilinear sample gt onto ow x oh just like render-check, but still flag size_mismatch! |
| 234 | sum_abs = 0 |
| 235 | sum_sq = 0 |
| 236 | max_diff = 0 |
| 237 | for y in range(oh): |
| 238 | gy = min(gh - 1, int((y + 0.5) * gh / oh)) |
| 239 | for x in range(ow): |
| 240 | gx = min(gw - 1, int((x + 0.5) * gw / ow)) |
| 241 | oi = (y * ow + x) * 4 |
| 242 | gi = (gy * gw + gx) * 4 |
| 243 | for c in range(3): |
| 244 | d = abs(ob[oi + c] - gb[gi + c]) |
| 245 | sum_abs += d |
| 246 | sum_sq += d * d |
| 247 | if d > max_diff: |
| 248 | max_diff = d |
| 249 | n = ow * oh * 3 |
| 250 | else: |
| 251 | sum_abs = 0 |
| 252 | sum_sq = 0 |
| 253 | max_diff = 0 |
| 254 | n = ow * oh * 3 |
| 255 | for i in range(0, ow * oh * 4, 4): |
| 256 | d0 = abs(ob[i] - gb[i]) |
| 257 | d1 = abs(ob[i + 1] - gb[i + 1]) |
| 258 | d2 = abs(ob[i + 2] - gb[i + 2]) |
| 259 | sum_abs += d0 + d1 + d2 |
| 260 | sum_sq += d0 * d0 + d1 * d1 + d2 * d2 |
| 261 | m = max(d0, d1, d2) |
| 262 | if m > max_diff: |
| 263 | max_diff = m |
| 264 | |
| 265 | mae_255 = sum_abs / max(1, n) |
| 266 | rmse_255 = math.sqrt(sum_sq / max(1, n)) |
| 267 | mae_pct = mae_255 / 2.55 |
| 268 | return { |
| 269 | "mae_255": round(mae_255, 4), |
| 270 | "mae_pct": round(mae_pct, 4), |
| 271 | "rmse_255": round(rmse_255, 4), |
| 272 | "max_diff": max_diff, |
| 273 | "dims_ours": [ow, oh], |
| 274 | "dims_gt": [gw, gh], |
| 275 | "size_mismatch": size_mismatch, |
| 276 | } |
| 277 | |
| 278 | |
| 279 | # --------------------------------------------------------------------------- |
| 280 | # Synthetic Test Plate & Geometry Generators |
| 281 | # --------------------------------------------------------------------------- |
| 282 | |
| 283 | |
| 284 | def _hsv_to_rgb(h: float, s: float, v: float) -> Tuple[float, float, float]: |
| 285 | h = (h % 1.0) * 6.0 |
| 286 | i = int(h) |
| 287 | f = h - i |
| 288 | p = v * (1.0 - s) |
| 289 | q = v * (1.0 - s * f) |
| 290 | t = v * (1.0 - s * (1.0 - f)) |
| 291 | return [(v, t, p), (q, v, p), (p, v, t), (p, q, v), (t, p, v), (v, p, q)][i % 6] |
| 292 | |
| 293 | |
| 294 | def _clamp8(v: float) -> int: |
| 295 | return max(0, min(255, int(round(v * 255.0)))) |
| 296 | |
| 297 | |
| 298 | def generate_assets() -> Dict[str, str]: |
| 299 | """Generates all synthetic test plates & cube.obj under probes/diff_fuzz/assets/.""" |
| 300 | root = ensure_dirs() |
| 301 | assets_dir = root / "assets" |
| 302 | |
| 303 | # 1. plate_color.png (256x256): HSV + gray/primary ramps + geometric edges + alpha gradient |
| 304 | p_color = assets_dir / "plate_color.png" |
| 305 | w, h = 256, 256 |
| 306 | buf = bytearray(w * h * 4) |
| 307 | for y in range(h): |
| 308 | ny = y / (h - 1) |
| 309 | for x in range(w): |
| 310 | nx = x / (w - 1) |
| 311 | r, g, b, a = 0.0, 0.0, 0.0, 1.0 |
| 312 | if ny < 0.40: |
| 313 | r, g, b = _hsv_to_rgb(nx, ny / 0.40, 0.90) |
| 314 | elif ny < 0.60: |
| 315 | if nx < 0.5: |
| 316 | g0 = nx * 2.0 |
| 317 | r, g, b = g0, g0, g0 |
| 318 | else: |
| 319 | bar = int((nx - 0.5) * 12.0) % 6 |
| 320 | r, g, b = [ |
| 321 | (0.95, 0.15, 0.15), |
| 322 | (0.15, 0.90, 0.20), |
| 323 | (0.15, 0.30, 0.95), |
| 324 | (0.95, 0.90, 0.15), |
| 325 | (0.15, 0.90, 0.95), |
| 326 | (0.95, 0.15, 0.90), |
| 327 | ][bar] |
| 328 | elif ny < 0.82: |
| 329 | # Sharp geometric edges (rotated diamond + circle + stripes) |
| 330 | r, g, b = 0.12, 0.14, 0.18 |
| 331 | dx, dy = abs(nx - 0.30), abs(ny - 0.71) |
| 332 | if dx + dy < 0.11: |
| 333 | r, g, b = 0.96, 0.52, 0.12 |
| 334 | if math.hypot(nx - 0.72, ny - 0.71) < 0.09: |
| 335 | r, g, b = 0.20, 0.85, 0.95 |
| 336 | if ((x + y) // 6) % 2 == 0 and 0.45 < nx < 0.58: |
| 337 | r, g, b = 0.92, 0.92, 0.92 |
| 338 | else: |
| 339 | r, g, b = _hsv_to_rgb(nx, 0.85, 0.92) |
| 340 | a = max(0.0, min(1.0, 1.0 - (ny - 0.82) / 0.18)) |
| 341 | idx = (y * w + x) * 4 |
| 342 | buf[idx] = _clamp8(r) |
| 343 | buf[idx + 1] = _clamp8(g) |
| 344 | buf[idx + 2] = _clamp8(b) |
| 345 | buf[idx + 3] = _clamp8(a) |
| 346 | write_png_rgba(p_color, w, h, bytes(buf)) |
| 347 | sync_asset_to_remote(p_color) |
| 348 | |
| 349 | # 2. plate_fg.png (256x256): semi-transparent shapes, fine diagonal stripes, soft radial falloff |
| 350 | p_fg = assets_dir / "plate_fg.png" |
| 351 | buf = bytearray(w * h * 4) |
| 352 | for y in range(h): |
| 353 | ny = y / (h - 1) |
| 354 | for x in range(w): |
| 355 | nx = x / (w - 1) |
| 356 | r, g, b, a = 0.0, 0.0, 0.0, 0.0 |
| 357 | # Soft radial falloff orb (top-left) |
| 358 | d_orb = math.hypot(nx - 0.28, ny - 0.28) |
| 359 | if d_orb < 0.22: |
| 360 | t = 1.0 - d_orb / 0.22 |
| 361 | r, g, b = 0.95 * t + 0.2 * (1.0 - t), 0.35 + 0.55 * math.sin(d_orb * 40.0) ** 2, 0.90 * (1.0 - 0.4 * t) |
| 362 | a = t * t * (3.0 - 2.0 * t) |
| 363 | # Fine diagonal stripes block (top-right) |
| 364 | if 0.54 <= nx <= 0.90 and 0.10 <= ny <= 0.44: |
| 365 | stripe = ((x - y) // 2) % 2 == 0 |
| 366 | r, g, b = (0.95, 0.85, 0.15) if stripe else (0.15, 0.22, 0.55) |
| 367 | a = 0.85 if stripe else 0.55 |
| 368 | # Overlapping semi-transparent discs (bottom-left) |
| 369 | d1 = math.hypot(nx - 0.24, ny - 0.72) < 0.14 |
| 370 | d2 = math.hypot(nx - 0.36, ny - 0.72) < 0.14 |
| 371 | if d1 and d2: |
| 372 | r, g, b, a = 0.85, 0.55, 0.95, 0.75 |
| 373 | elif d1: |
| 374 | r, g, b, a = 0.10, 0.85, 0.90, 0.55 |
| 375 | elif d2: |
| 376 | r, g, b, a = 0.95, 0.20, 0.65, 0.55 |
| 377 | # Asymmetric crisp L-marker (bottom-right) |
| 378 | if (0.62 <= nx <= 0.68 and 0.58 <= ny <= 0.86) or (0.62 <= nx <= 0.86 and 0.80 <= ny <= 0.86): |
| 379 | r, g, b, a = 0.98, 0.98, 0.98, 1.0 |
| 380 | idx = (y * w + x) * 4 |
| 381 | buf[idx] = _clamp8(r) |
| 382 | buf[idx + 1] = _clamp8(g) |
| 383 | buf[idx + 2] = _clamp8(b) |
| 384 | buf[idx + 3] = _clamp8(a) |
| 385 | write_png_rgba(p_fg, w, h, bytes(buf)) |
| 386 | sync_asset_to_remote(p_fg) |
| 387 | |
| 388 | # 3. plate_small.png (160x120): mismatched resolution test plate |
| 389 | p_small = assets_dir / "plate_small.png" |
| 390 | sw, sh = 160, 120 |
| 391 | sbuf = bytearray(sw * sh * 4) |
| 392 | for y in range(sh): |
| 393 | ny = y / (sh - 1) |
| 394 | for x in range(sw): |
| 395 | nx = x / (sw - 1) |
| 396 | r, g, b, a = 0.18, 0.22, 0.30, 0.95 |
| 397 | if x < 5 or x >= sw - 5 or y < 5 or y >= sh - 5: |
| 398 | if y < 5: |
| 399 | r, g, b, a = 0.95, 0.20, 0.20, 1.0 |
| 400 | elif y >= sh - 5: |
| 401 | r, g, b, a = 0.20, 0.90, 0.25, 1.0 |
| 402 | elif x < 5: |
| 403 | r, g, b, a = 0.20, 0.40, 0.95, 1.0 |
| 404 | else: |
| 405 | r, g, b, a = 0.95, 0.85, 0.15, 1.0 |
| 406 | else: |
| 407 | if ((x // 10) + (y // 10)) % 2 == 0: |
| 408 | r, g, b = 0.72, 0.76, 0.82 |
| 409 | if abs(nx - ny) < 0.04 or abs(nx - (1.0 - ny)) < 0.04: |
| 410 | r, g, b = 0.95, 0.35, 0.10 |
| 411 | d_c = math.hypot(nx - 0.5, ny - 0.5) |
| 412 | if d_c < 0.22: |
| 413 | a = max(0.2, 1.0 - (0.22 - d_c) / 0.22 * 0.7) |
| 414 | idx = (y * sw + x) * 4 |
| 415 | sbuf[idx] = _clamp8(r) |
| 416 | sbuf[idx + 1] = _clamp8(g) |
| 417 | sbuf[idx + 2] = _clamp8(b) |
| 418 | sbuf[idx + 3] = _clamp8(a) |
| 419 | write_png_rgba(p_small, sw, sh, bytes(sbuf)) |
| 420 | sync_asset_to_remote(p_small) |
| 421 | |
| 422 | # 4. plate_bump.png (256x256): grayscale heightmap / bump test texture |
| 423 | p_bump = assets_dir / "plate_bump.png" |
| 424 | bbuf = bytearray(w * h * 4) |
| 425 | for y in range(h): |
| 426 | ny = y / (h - 1) |
| 427 | for x in range(w): |
| 428 | nx = x / (w - 1) |
| 429 | d = math.hypot(nx - 0.5, ny - 0.5) |
| 430 | dome = max(0.0, 1.0 - (d / 0.38) ** 2) ** 0.5 if d < 0.38 else 0.0 |
| 431 | ripple = 0.5 + 0.5 * math.sin(d * 48.0) |
| 432 | step = 0.25 * math.floor(nx * 5.0) / 4.0 |
| 433 | val = max(0.0, min(1.0, 0.50 * dome + 0.30 * ripple + 0.20 * step)) |
| 434 | v8 = _clamp8(val) |
| 435 | idx = (y * w + x) * 4 |
| 436 | bbuf[idx] = v8 |
| 437 | bbuf[idx + 1] = v8 |
| 438 | bbuf[idx + 2] = v8 |
| 439 | bbuf[idx + 3] = 255 |
| 440 | write_png_rgba(p_bump, w, h, bytes(bbuf)) |
| 441 | sync_asset_to_remote(p_bump) |
| 442 | |
| 443 | # 5. cube.obj: small valid triangulated OBJ mesh |
| 444 | p_obj = assets_dir / "cube.obj" |
| 445 | obj_text = """# Synthetic unit cube for SurfaceFBXMesh differential testing |
| 446 | o UnitCube |
| 447 | v -0.5 -0.5 0.5 |
| 448 | v 0.5 -0.5 0.5 |
| 449 | v 0.5 0.5 0.5 |
| 450 | v -0.5 0.5 0.5 |
| 451 | v -0.5 -0.5 -0.5 |
| 452 | v 0.5 -0.5 -0.5 |
| 453 | v 0.5 0.5 -0.5 |
| 454 | v -0.5 0.5 -0.5 |
| 455 | vt 0.0 0.0 |
| 456 | vt 1.0 0.0 |
| 457 | vt 1.0 1.0 |
| 458 | vt 0.0 1.0 |
| 459 | vn 0.0 0.0 1.0 |
| 460 | vn 0.0 0.0 -1.0 |
| 461 | vn 1.0 0.0 0.0 |
| 462 | vn -1.0 0.0 0.0 |
| 463 | vn 0.0 1.0 0.0 |
| 464 | vn 0.0 -1.0 0.0 |
| 465 | f 1/1/1 2/2/1 3/3/1 |
| 466 | f 1/1/1 3/3/1 4/4/1 |
| 467 | f 6/1/2 5/2/2 8/3/2 |
| 468 | f 6/1/2 8/3/2 7/4/2 |
| 469 | f 2/1/3 6/2/3 7/3/3 |
| 470 | f 2/1/3 7/3/3 3/4/3 |
| 471 | f 5/1/4 1/2/4 4/3/4 |
| 472 | f 5/1/4 4/3/4 8/4/4 |
| 473 | f 4/1/5 3/2/5 7/3/5 |
| 474 | f 4/1/5 7/3/5 8/4/5 |
| 475 | f 5/1/6 6/2/6 2/3/6 |
| 476 | f 5/1/6 2/3/6 1/4/6 |
| 477 | """ |
| 478 | p_obj.write_text(obj_text) |
| 479 | sync_asset_to_remote(p_obj) |
| 480 | |
| 481 | return { |
| 482 | "color": f"{CONTAINER_ROOT}/assets/plate_color.png", |
| 483 | "fg": f"{CONTAINER_ROOT}/assets/plate_fg.png", |
| 484 | "small": f"{CONTAINER_ROOT}/assets/plate_small.png", |
| 485 | "bump": f"{CONTAINER_ROOT}/assets/plate_bump.png", |
| 486 | "cube_obj": f"{CONTAINER_ROOT}/assets/cube.obj", |
| 487 | } |
| 488 | |
| 489 | |
| 490 | # --------------------------------------------------------------------------- |
| 491 | # Fusion .comp Serialization Primitives |
| 492 | # --------------------------------------------------------------------------- |
| 493 | |
| 494 | |
| 495 | def step_spline(name: str, frame_values: Dict[int, float]) -> str: |
| 496 | kfs = [f"\t\t\t\t[{f}] = {{ {v!r}, Flags = {{ StepIn = true }} }}," for f, v in sorted(frame_values.items())] |
| 497 | return f"\t\t{name} = BezierSpline {{\n\t\t\tKeyFrames = {{\n" + "\n".join(kfs) + "\n\t\t\t},\n\t\t}," |
| 498 | |
| 499 | |
| 500 | def linear_spline(name: str, frame_values: Dict[int, float]) -> str: |
| 501 | kfs = [f"\t\t\t\t[{f}] = {{ {v!r}, Flags = {{ Linear = true }} }}," for f, v in sorted(frame_values.items())] |
| 502 | return f"\t\t{name} = BezierSpline {{\n\t\t\tKeyFrames = {{\n" + "\n".join(kfs) + "\n\t\t\t},\n\t\t}," |
| 503 | |
| 504 | |
| 505 | def lut_bezier(name: str, pts: List[Tuple[float, float]]) -> str: |
| 506 | kfs = "\n".join(f"\t\t\t\t\t[{x}] = {{ {y} }}," for x, y in pts) |
| 507 | return ( |
| 508 | f"\t\t{name} = LUTBezier {{\n" |
| 509 | f"\t\t\tSmoothEndsTransition = true,\n" |
| 510 | f"\t\t\tKeyColorSplines = {{\n" |
| 511 | f"\t\t\t\t[0] = {{\n{kfs}\n\t\t\t\t}}\n" |
| 512 | f"\t\t\t}},\n\t\t}}," |
| 513 | ) |
| 514 | |
| 515 | |
| 516 | def make_loader(name: str, container_path: str, post_mult: int = 1, depth: Optional[int] = None) -> str: |
| 517 | extra = f"\n\t\t\t\tDepth = Input {{ Value = {depth}, }}," if depth is not None else "" |
| 518 | return f"""\t\t{name} = Loader {{ |
| 519 | \t\t\tClips = {{ |
| 520 | \t\t\t\tClip {{ |
| 521 | \t\t\t\t\tID = "Clip1", |
| 522 | \t\t\t\t\tFilename = "{container_path}", |
| 523 | \t\t\t\t\tFormatID = "PNGFormat", |
| 524 | \t\t\t\t\tLength = 1, |
| 525 | \t\t\t\t\tLengthSetManually = true, |
| 526 | \t\t\t\t\tTrimIn = 0, |
| 527 | \t\t\t\t\tTrimOut = 0, |
| 528 | \t\t\t\t\tExtendFirst = 0, |
| 529 | \t\t\t\t\tExtendLast = 0, |
| 530 | \t\t\t\t\tLoop = 1, |
| 531 | \t\t\t\t\tStartFrame = -1, |
| 532 | \t\t\t\t\tGlobalStart = 0, |
| 533 | \t\t\t\t\tGlobalEnd = 1000, |
| 534 | \t\t\t\t}}, |
| 535 | \t\t\t}}, |
| 536 | \t\t\tInputs = {{ |
| 537 | \t\t\t\t["Clip1.PNGFormat.PostMultiply"] = Input {{ Value = {post_mult}, }},{extra} |
| 538 | \t\t\t}}, |
| 539 | \t\t}},""" |
| 540 | |
| 541 | |
| 542 | def make_saver(src_op: str, prefix: str) -> str: |
| 543 | return f"""\t\tSaver1 = Saver {{ |
| 544 | \t\t\tInputs = {{ |
| 545 | \t\t\t\tClip = Input {{ |
| 546 | \t\t\t\t\tValue = Clip {{ |
| 547 | \t\t\t\t\t\tFilename = "{CONTAINER_ROOT}/gt/{prefix}_0000.png", |
| 548 | \t\t\t\t\t\tFormatID = "PNGFormat", |
| 549 | \t\t\t\t\t\tLength = 0, |
| 550 | \t\t\t\t\t\tSaving = true, |
| 551 | \t\t\t\t\t\tTrimIn = 0, |
| 552 | \t\t\t\t\t\tExtendFirst = 0, |
| 553 | \t\t\t\t\t\tExtendLast = 0, |
| 554 | \t\t\t\t\t\tLoop = 1, |
| 555 | \t\t\t\t\t\tAspectMode = 0, |
| 556 | \t\t\t\t\t\tDepth = 0, |
| 557 | \t\t\t\t\t\tGlobalStart = -2000000000, |
| 558 | \t\t\t\t\t\tGlobalEnd = 0, |
| 559 | \t\t\t\t\t}}, |
| 560 | \t\t\t\t}}, |
| 561 | \t\t\t\tOutputFormat = Input {{ Value = FuID {{ "PNGFormat" }}, }}, |
| 562 | \t\t\t\tInput = Input {{ SourceOp = "{src_op}", Source = "Output", }}, |
| 563 | \t\t\t}}, |
| 564 | \t\t}},""" |
| 565 | |
| 566 | |
| 567 | def make_comp(tools_body: str, end_frame: int, w: int = 256, h: int = 256, start_frame: int = 0) -> str: |
| 568 | return f"""Composition {{ |
| 569 | \tCurrentTime = {start_frame}, |
| 570 | \tRenderRange = {{ {start_frame}, {end_frame} }}, |
| 571 | \tGlobalRange = {{ {start_frame}, {end_frame} }}, |
| 572 | \tCurrentID = 500, |
| 573 | \tHiQ = true, |
| 574 | \tPlaybackUpdateMode = 0, |
| 575 | \tVersion = "Fusion Studio 21.1 build 23", |
| 576 | \tTools = ordered() {{ |
| 577 | {tools_body} |
| 578 | \t}}, |
| 579 | \tPrefs = {{ |
| 580 | \t\tComp = {{ |
| 581 | \t\t\tFrameFormat = {{ |
| 582 | \t\t\t\tWidth = {w}, |
| 583 | \t\t\t\tHeight = {h}, |
| 584 | \t\t\t\tRate = 24, |
| 585 | \t\t\t}}, |
| 586 | \t\t}}, |
| 587 | \t}}, |
| 588 | }} |
| 589 | """ |
| 590 | |
| 591 | |
| 592 | def build_switch_chain( |
| 593 | cases: List[Tuple[int, str, str]], |
| 594 | bg_name: str, |
| 595 | prefix_tag: str, |
| 596 | ) -> Tuple[List[str], List[str], str]: |
| 597 | """Chains Merge switches so frame f outputs op_name for case (f, label, op_name).""" |
| 598 | nodes: List[str] = [] |
| 599 | splines: List[str] = [] |
| 600 | prev = bg_name |
| 601 | frames = [c[0] for c in cases] |
| 602 | for f, _label, op_name in cases: |
| 603 | bl = {fr: (1.0 if fr == f else 0.0) for fr in frames} |
| 604 | sname = f"{prefix_tag}_{f}_Blend" |
| 605 | splines.append(step_spline(sname, bl)) |
| 606 | sw_name = f"{prefix_tag}_Sw_{f}" |
| 607 | nodes.append( |
| 608 | f"""\t\t{sw_name} = Merge {{ |
| 609 | \t\t\tInputs = {{ |
| 610 | \t\t\t\tBlend = Input {{ SourceOp = "{sname}", Source = "Value", }}, |
| 611 | \t\t\t\tBackground = Input {{ SourceOp = "{prev}", Source = "Output", }}, |
| 612 | \t\t\t\tForeground = Input {{ SourceOp = "{op_name}", Source = "Output", }}, |
| 613 | \t\t\t}}, |
| 614 | \t\t}},""" |
| 615 | ) |
| 616 | prev = sw_name |
| 617 | return nodes, splines, prev |
| 618 | |
| 619 | |
| 620 | # --------------------------------------------------------------------------- |
| 621 | # Execution & Comparison Runner (sg render + render-check) |
| 622 | # --------------------------------------------------------------------------- |
| 623 | |
| 624 | |
| 625 | def run_comp_both( |
| 626 | comp_path: Path, |
| 627 | prefix: str, |
| 628 | frames: List[int], |
| 629 | labels: Dict[int, str], |
| 630 | render_gt: bool = True, |
| 631 | timeout_sec: int = 180, |
| 632 | ) -> Dict[int, Dict[str, Any]]: |
| 633 | """Renders comp via sg render (if render_gt) and render-check --render, returning per-frame metrics.""" |
| 634 | root = ensure_dirs() |
| 635 | rc_bin = ensure_render_check() |
| 636 | start_f, end_f = min(frames), max(frames) |
| 637 | |
| 638 | gt_error: Optional[str] = None |
| 639 | if render_gt: |
| 640 | if use_smb(): |
| 641 | target_comp = str(comp_path) |
| 642 | else: |
| 643 | remote_comp = f"{REMOTE_ROOT}/comps/{comp_path.name}" |
| 644 | subprocess.run(["sg", "upload", str(comp_path), remote_comp], check=True, timeout=60) |
| 645 | target_comp = remote_comp |
| 646 | |
| 647 | # Clear stale GT frames for this prefix |
| 648 | gt_dir = root / "gt" |
| 649 | for f in frames: |
| 650 | p = gt_dir / f"{prefix}_{f:04d}.png" |
| 651 | if p.exists(): |
| 652 | p.unlink() |
| 653 | |
| 654 | try: |
| 655 | cmd = ["sg", "render", target_comp, "--start", str(start_f), "--end", str(end_f)] |
| 656 | proc = subprocess.run(cmd, check=True, capture_output=True, text=True, timeout=timeout_sec) |
| 657 | combined_out = (proc.stdout or "") + "\n" + (proc.stderr or "") |
| 658 | if "ERROR: Render failed" in combined_out: |
| 659 | err_lines = [ln.strip() for ln in combined_out.splitlines() if "fail" in ln.lower() or "error" in ln.lower()] |
| 660 | gt_error = "sg render error: " + " | ".join(err_lines[:4]) |
| 661 | except subprocess.TimeoutExpired: |
| 662 | gt_error = f"sg render timed out after {timeout_sec}s" |
| 663 | except subprocess.CalledProcessError as e: |
| 664 | gt_error = f"sg render failed (rc={e.returncode}): {(e.stderr or e.stdout or '').strip()[:300]}" |
| 665 | |
| 666 | if use_smb() and gt_error is None: |
| 667 | # Wait briefly for SMB directory cache to surface newly written GT frames |
| 668 | last_gt = gt_dir / f"{prefix}_{end_f:04d}.png" |
| 669 | deadline = time.time() + 4.0 |
| 670 | while not last_gt.exists() and time.time() < deadline: |
| 671 | time.sleep(0.25) |
| 672 | |
| 673 | if not use_smb() and gt_error is None: |
| 674 | for f in frames: |
| 675 | fname = f"{prefix}_{f:04d}.png" |
| 676 | try: |
| 677 | subprocess.run( |
| 678 | ["sg", "download", f"{REMOTE_ROOT}/gt/{fname}", str(gt_dir / fname)], |
| 679 | check=True, |
| 680 | capture_output=True, |
| 681 | timeout=60, |
| 682 | ) |
| 683 | except subprocess.CalledProcessError as e: |
| 684 | gt_error = f"sg download failed for {fname}: {e}" |
| 685 | break |
| 686 | |
| 687 | eval_comp = comp_path |
| 688 | if not use_smb(): |
| 689 | txt = comp_path.read_text().replace(CONTAINER_ROOT, str(root)) |
| 690 | eval_comp = comp_path.with_suffix(".local.comp") |
| 691 | eval_comp.write_text(txt) |
| 692 | |
| 693 | ours_sub = root / "ours" / prefix |
| 694 | if ours_sub.exists(): |
| 695 | shutil.rmtree(ours_sub, ignore_errors=True) |
| 696 | ours_sub.mkdir(parents=True, exist_ok=True) |
| 697 | |
| 698 | rc_error: Optional[str] = None |
| 699 | try: |
| 700 | subprocess.run( |
| 701 | [str(rc_bin), str(eval_comp), "--render", f"{start_f}..{end_f}", "--out-dir", str(ours_sub)], |
| 702 | check=True, |
| 703 | capture_output=True, |
| 704 | text=True, |
| 705 | timeout=timeout_sec, |
| 706 | ) |
| 707 | except subprocess.TimeoutExpired: |
| 708 | rc_error = f"render-check timed out after {timeout_sec}s" |
| 709 | except subprocess.CalledProcessError as e: |
| 710 | rc_error = f"render-check failed (rc={e.returncode}): {(e.stderr or e.stdout or '').strip()[:300]}" |
| 711 | |
| 712 | results: Dict[int, Dict[str, Any]] = {} |
| 713 | for f in frames: |
| 714 | label = labels.get(f, f"f{f}") |
| 715 | if gt_error is not None: |
| 716 | results[f] = {"frame": f, "label": label, "error": gt_error, "mae_pct": 100.0, "mae_255": 255.0, "rmse_255": 255.0} |
| 717 | continue |
| 718 | if rc_error is not None: |
| 719 | results[f] = {"frame": f, "label": label, "error": rc_error, "mae_pct": 100.0, "mae_255": 255.0, "rmse_255": 255.0} |
| 720 | continue |
| 721 | gt_p = root / "gt" / f"{prefix}_{f:04d}.png" |
| 722 | ours_p = ours_sub / f"{f:04d}.png" |
| 723 | m = compute_diff_metrics(ours_p, gt_p) |
| 724 | m["frame"] = f |
| 725 | m["label"] = label |
| 726 | results[f] = m |
| 727 | return results |
| 728 | |
| 729 | |
| 730 | # --------------------------------------------------------------------------- |
| 731 | # Matrix Suites (7 Exhaustive Edge-Case Suites) |
| 732 | # --------------------------------------------------------------------------- |
| 733 | |
| 734 | |
| 735 | def build_matrix_merge_modes(assets: Dict[str, str]): |
| 736 | """Sweeps all Merge ApplyModes, Operators, SubtractiveAdditive, AlphaGain/Gain, BurnIn, Edges, mismatched res, EffectMask.""" |
| 737 | nodes = [ |
| 738 | make_loader("ColorLoader", assets["color"], post_mult=1), |
| 739 | make_loader("FGLoader", assets["fg"], post_mult=1), |
| 740 | make_loader("SmallLoader", assets["small"], post_mult=1), |
| 741 | """\t\tBlackBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftAlpha = Input { Value = 1, }, }, }, |
| 742 | \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, }, }, }, |
| 743 | \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, }, }, },""", |
| 744 | ] |
| 745 | cases: List[Tuple[int, str, str]] = [] |
| 746 | f = 0 |
| 747 | |
| 748 | def add_case(label: str, fg: str, bg: str, extra: str, over_blue: bool = False) -> None: |
| 749 | nonlocal f |
| 750 | mname = f"M_{f}" |
| 751 | nodes.append( |
| 752 | f"""\t\t{mname} = Merge {{ |
| 753 | \t\t\tInputs = {{ |
| 754 | \t\t\t\tBackground = Input {{ SourceOp = "{bg}", Source = "Output", }}, |
| 755 | \t\t\t\tForeground = Input {{ SourceOp = "{fg}", Source = "Output", }}, |
| 756 | \t\t\t\tPerformDepthMerge = Input {{ Value = 0, }}, |
| 757 | \t\t\t\t{extra} |
| 758 | \t\t\t}}, |
| 759 | \t\t}},""" |
| 760 | ) |
| 761 | out_name = mname |
| 762 | if over_blue: |
| 763 | oname = f"Vis_{f}" |
| 764 | nodes.append( |
| 765 | f"""\t\t{oname} = Merge {{ |
| 766 | \t\t\tInputs = {{ |
| 767 | \t\t\t\tBackground = Input {{ SourceOp = "BlueBG", Source = "Output", }}, |
| 768 | \t\t\t\tForeground = Input {{ SourceOp = "{mname}", Source = "Output", }}, |
| 769 | \t\t\t}}, |
| 770 | \t\t}},""" |
| 771 | ) |
| 772 | out_name = oname |
| 773 | cases.append((f, label, out_name)) |
| 774 | f += 1 |
| 775 | |
| 776 | apply_modes = [ |
| 777 | "Normal", "Screen", "Multiply", "Dissolve", "SoftLight", "HardLight", |
| 778 | "Darken", "Lighten", "ColorDodge", "ColorBurn", "Difference", "Exclusion", |
| 779 | "Overlay", "Sub", |
| 780 | ] |
| 781 | for am in apply_modes: |
| 782 | add_case(f"ApplyMode={am}", "FGLoader", "ColorLoader", f'Size = Input {{ Value = 0.85, }}, ApplyMode = Input {{ Value = FuID {{ "{am}" }}, }},') |
| 783 | |
| 784 | operators = ["Over", "In", "Held Out", "Atop", "XOr", "Conjoint", "Disjoint"] |
| 785 | for op in operators: |
| 786 | add_case(f"Operator={op}", "FGLoader", "ColorLoader", f'Operator = Input {{ Value = FuID {{ "{op}" }}, }},', over_blue=True) |
| 787 | |
| 788 | for sa in (0.0, 0.5, 1.0): |
| 789 | add_case(f"SubAdd={sa}", "FGLoader", "ColorLoader", f"SubtractiveAdditive = Input {{ Value = {sa}, }},") |
| 790 | |
| 791 | for ag in (0.0, 0.5, 1.5): |
| 792 | add_case(f"Gain={ag}", "FGLoader", "ColorLoader", f"Gain = Input {{ Value = {ag}, }},") |
| 793 | add_case("AlphaGain=0.5", "FGLoader", "ColorLoader", "AlphaGain = Input { Value = 0.5, },") |
| 794 | |
| 795 | add_case("BurnIn=0.6", "FGLoader", "ColorLoader", "BurnIn = Input { Value = 0.6, },") |
| 796 | |
| 797 | for ed in (0, 1, 2, 3): |
| 798 | add_case( |
| 799 | f"Edges={ed}", |
| 800 | "SmallLoader", |
| 801 | "ColorLoader", |
| 802 | f"Center = Input {{ Value = {{ 0.78, 0.72 }}, }}, Size = Input {{ Value = 0.55, }}, Angle = Input {{ Value = 22, }}, Edges = Input {{ Value = {ed}, }},", |
| 803 | ) |
| 804 | |
| 805 | add_case("Mismatch_SmallOverColor", "SmallLoader", "ColorLoader", "Size = Input { Value = 0.8, }, Angle = Input { Value = 20, },") |
| 806 | add_case("Mismatch_ColorOverSmall", "ColorLoader", "SmallLoader", "Size = Input { Value = 0.5, }, Angle = Input { Value = -15, },", over_blue=True) |
| 807 | |
| 808 | for inv in (0, 1): |
| 809 | for mbm in (0, 1): |
| 810 | add_case( |
| 811 | f"Mask_inv{inv}_mbm{mbm}", |
| 812 | "FGLoader", |
| 813 | "ColorLoader", |
| 814 | f'EffectMask = Input {{ SourceOp = "MaskEll", Source = "Mask", }}, ApplyMaskInverted = Input {{ Value = {inv}, }}, MultiplyByMask = Input {{ Value = {mbm}, }},', |
| 815 | ) |
| 816 | |
| 817 | sw_nodes, sw_splines, out_op = build_switch_chain(cases, "BlackBG", "MM") |
| 818 | nodes.extend(sw_nodes) |
| 819 | nodes.append(make_saver(out_op, "matrix_merge_modes")) |
| 820 | comp_path = ensure_dirs() / "comps" / "matrix_merge_modes.comp" |
| 821 | comp_path.write_text(make_comp("\n".join(nodes + sw_splines), len(cases) - 1)) |
| 822 | return comp_path, "matrix_merge_modes", [(c[0], c[1]) for c in cases] |
| 823 | |
| 824 | |
| 825 | def build_matrix_hdr_depth(assets: Dict[str, str]): |
| 826 | """Tests BitDepth (int8/int16/float16/float32), HDR > 1.0, negative values, PreDividePostMultiply=0/1.""" |
| 827 | nodes = [ |
| 828 | make_loader("ColorLoader", assets["color"], post_mult=1), |
| 829 | make_loader("FGLoader", assets["fg"], post_mult=1), |
| 830 | """\t\tBlackBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftAlpha = Input { Value = 1, }, }, }, |
| 831 | \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, }, }, },""", |
| 832 | ] |
| 833 | cases: List[Tuple[int, str, str]] = [] |
| 834 | f = 0 |
| 835 | |
| 836 | for d_code, d_name in ((1, "int8"), (2, "int16"), (3, "float16"), (4, "float32")): |
| 837 | cd = f"CD_{f}" |
| 838 | up = f"Up_{f}" |
| 839 | bl = f"Bl_{f}" |
| 840 | dn = f"Dn_{f}" |
| 841 | nodes.append(f'\t\t{cd} = ChangeDepth {{ Inputs = {{ Input = Input {{ SourceOp = "ColorLoader", Source = "Output", }}, Depth = Input {{ Value = {d_code}, }}, }}, }},') |
| 842 | nodes.append(f'\t\t{up} = BrightnessContrast {{ Inputs = {{ Input = Input {{ SourceOp = "{cd}", Source = "Output", }}, Gain = Input {{ Value = 2.5, }}, }}, }},') |
| 843 | nodes.append(f'\t\t{bl} = Blur {{ Inputs = {{ Input = Input {{ SourceOp = "{up}", Source = "Output", }}, XBlurSize = Input {{ Value = 8.0, }}, }}, }},') |
| 844 | nodes.append(f'\t\t{dn} = BrightnessContrast {{ Inputs = {{ Input = Input {{ SourceOp = "{bl}", Source = "Output", }}, Gain = Input {{ Value = 0.4, }}, }}, }},') |
| 845 | cases.append((f, f"HDR_Depth={d_name}_Gain2.5_Blur_Gain0.4", dn)) |
| 846 | f += 1 |
| 847 | |
| 848 | # Negative value roundtrip across depths |
| 849 | for d_code, d_name in ((1, "int8"), (3, "float16"), (4, "float32")): |
| 850 | cd = f"CDN_{f}" |
| 851 | sub = f"Sub_{f}" |
| 852 | bl = f"BlN_{f}" |
| 853 | add = f"Add_{f}" |
| 854 | nodes.append(f'\t\t{cd} = ChangeDepth {{ Inputs = {{ Input = Input {{ SourceOp = "ColorLoader", Source = "Output", }}, Depth = Input {{ Value = {d_code}, }}, }}, }},') |
| 855 | nodes.append(f'\t\t{sub} = BrightnessContrast {{ Inputs = {{ Input = Input {{ SourceOp = "{cd}", Source = "Output", }}, Brightness = Input {{ Value = -0.4, }}, }}, }},') |
| 856 | nodes.append(f'\t\t{bl} = Blur {{ Inputs = {{ Input = Input {{ SourceOp = "{sub}", Source = "Output", }}, XBlurSize = Input {{ Value = 5.0, }}, }}, }},') |
| 857 | nodes.append(f'\t\t{add} = BrightnessContrast {{ Inputs = {{ Input = Input {{ SourceOp = "{bl}", Source = "Output", }}, Brightness = Input {{ Value = 0.4, }}, }}, }},') |
| 858 | cases.append((f, f"NegValues_Depth={d_name}", add)) |
| 859 | f += 1 |
| 860 | |
| 861 | # Background native Depth=3/4 HDR |
| 862 | for d_code, d_name in ((3, "float16"), (4, "float32")): |
| 863 | bg = f"BG_{f}" |
| 864 | up = f"BUp_{f}" |
| 865 | dn = f"BDn_{f}" |
| 866 | 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, }}, }}, }},') |
| 867 | nodes.append(f'\t\t{up} = BrightnessContrast {{ Inputs = {{ Input = Input {{ SourceOp = "{bg}", Source = "Output", }}, Gain = Input {{ Value = 3.0, }}, }}, }},') |
| 868 | nodes.append(f'\t\t{dn} = BrightnessContrast {{ Inputs = {{ Input = Input {{ SourceOp = "{up}", Source = "Output", }}, Gain = Input {{ Value = 0.333333, }}, }}, }},') |
| 869 | cases.append((f, f"BG_Depth={d_name}_HDR", dn)) |
| 870 | f += 1 |
| 871 | |
| 872 | # PreDividePostMultiply = 0 / 1 on semi-transparent FGLoader merged over DarkBG |
| 873 | for pd in (0, 1): |
| 874 | bc = f"BCPD_{f}" |
| 875 | m = f"MPD_{f}" |
| 876 | 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}, }}, }}, }},') |
| 877 | nodes.append(f'\t\t{m} = Merge {{ Inputs = {{ Background = Input {{ SourceOp = "DarkBG", Source = "Output", }}, Foreground = Input {{ SourceOp = "{bc}", Source = "Output", }}, }}, }},') |
| 878 | cases.append((f, f"BC_PreDiv={pd}", m)) |
| 879 | f += 1 |
| 880 | |
| 881 | sw_nodes, sw_splines, out_op = build_switch_chain(cases, "BlackBG", "HD") |
| 882 | nodes.extend(sw_nodes) |
| 883 | nodes.append(make_saver(out_op, "matrix_hdr_depth")) |
| 884 | comp_path = ensure_dirs() / "comps" / "matrix_hdr_depth.comp" |
| 885 | comp_path.write_text(make_comp("\n".join(nodes + sw_splines), len(cases) - 1)) |
| 886 | return comp_path, "matrix_hdr_depth", [(c[0], c[1]) for c in cases] |
| 887 | |
| 888 | |
| 889 | def build_matrix_masks(assets: Dict[str, str]): |
| 890 | """Chained multi-mask graphs (EllipseMask -> RectangleMask -> PolylineMask) testing all PaintModes, SoftEdge, BorderWidth, Invert, Level.""" |
| 891 | nodes = [ |
| 892 | """\t\tBlackBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftAlpha = Input { Value = 1, }, }, }, |
| 893 | \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, }, }, },""", |
| 894 | ] |
| 895 | cases: List[Tuple[int, str, str]] = [] |
| 896 | f = 0 |
| 897 | |
| 898 | paint_modes = ["Merge", "Add", "Subtract", "Minimum", "Maximum", "Average", "Multiply", "Replace", "Invert"] |
| 899 | for pm in paint_modes: |
| 900 | e = f"Ell_{f}" |
| 901 | r = f"Rect_{f}" |
| 902 | p = f"Poly_{f}" |
| 903 | m = f"Op_{f}" |
| 904 | 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, }}, }}, }},') |
| 905 | 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, }}, }}, }},') |
| 906 | nodes.append( |
| 907 | f"""\t\t{p} = PolylineMask {{ |
| 908 | \t\t\tInputs = {{ |
| 909 | \t\t\t\tEffectMask = Input {{ SourceOp = "{r}", Source = "Mask", }}, |
| 910 | \t\t\t\tPaintMode = Input {{ Value = FuID {{ "{pm}" }}, }}, |
| 911 | \t\t\t\tMaskWidth = Input {{ Value = 256, }}, |
| 912 | \t\t\t\tMaskHeight = Input {{ Value = 256, }}, |
| 913 | \t\t\t\tSoftEdge = Input {{ Value = 0.02, }}, |
| 914 | \t\t\t\tPolyline = Input {{ |
| 915 | \t\t\t\t\tValue = Polyline {{ |
| 916 | \t\t\t\t\t\tClosed = true, |
| 917 | \t\t\t\t\t\tPoints = {{ |
| 918 | \t\t\t\t\t\t\t{{ Linear = true, X = -0.25, Y = -0.25, RX = 0.16, RY = 0 }}, |
| 919 | \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 }}, |
| 920 | \t\t\t\t\t\t\t{{ Linear = true, X = 0.0, Y = 0.28, LX = 0.08, LY = -0.14 }}, |
| 921 | \t\t\t\t\t\t}}, |
| 922 | \t\t\t\t\t}}, |
| 923 | \t\t\t\t}}, |
| 924 | \t\t\t}}, |
| 925 | \t\t}},""" |
| 926 | ) |
| 927 | 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", }}, }}, }},') |
| 928 | cases.append((f, f"MaskChain_PaintMode={pm}", m)) |
| 929 | f += 1 |
| 930 | |
| 931 | # BorderWidth, Solid=0/1, SoftEdge, Invert, Level edge cases |
| 932 | extra_masks = [ |
| 933 | ("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, }, }, }'), |
| 934 | ("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, }, }, }'), |
| 935 | ("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" }, }, }, }'), |
| 936 | ("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 } } }, }, }, }'), |
| 937 | ] |
| 938 | for label, mdef in extra_masks: |
| 939 | mk = f"Mk_{f}" |
| 940 | m = f"Op_{f}" |
| 941 | nodes.append(f"\t\t{mk} = {mdef},") |
| 942 | 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", }}, }}, }},') |
| 943 | cases.append((f, label, m)) |
| 944 | f += 1 |
| 945 | |
| 946 | sw_nodes, sw_splines, out_op = build_switch_chain(cases, "BlackBG", "MK") |
| 947 | nodes.extend(sw_nodes) |
| 948 | nodes.append(make_saver(out_op, "matrix_masks")) |
| 949 | comp_path = ensure_dirs() / "comps" / "matrix_masks.comp" |
| 950 | comp_path.write_text(make_comp("\n".join(nodes + sw_splines), len(cases) - 1)) |
| 951 | return comp_path, "matrix_masks", [(c[0], c[1]) for c in cases] |
| 952 | |
| 953 | |
| 954 | def build_matrix_color_blur(assets: Dict[str, str]): |
| 955 | """ColorCorrector, ColorCurves, HueCurves, GamutConvert, ChannelBoolean, Blur, Glow, SoftGlow, DirectionalBlur.""" |
| 956 | nodes = [ |
| 957 | make_loader("ColorLoader", assets["color"], post_mult=1), |
| 958 | make_loader("FGLoader", assets["fg"], post_mult=1), |
| 959 | """\t\tBlackBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftAlpha = Input { Value = 1, }, }, }, |
| 960 | \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, }, }, },""", |
| 961 | lut_bezier("CC_Red", [(0.0, 0.0), (0.3, 0.55), (0.7, 0.45), (1.0, 0.95)]), |
| 962 | lut_bezier("CC_Green", [(0.0, 0.08), (0.5, 0.42), (1.0, 1.0)]), |
| 963 | lut_bezier("CC_Blue", [(0.0, 0.0), (0.5, 0.72), (1.0, 0.85)]), |
| 964 | lut_bezier("CC_Alpha", [(0.0, 0.0), (0.5, 0.85), (1.0, 1.0)]), |
| 965 | lut_bezier("HC_Hue", [(0, 1.25), (2, 0.85), (4, 1.15), (6, 1.25)]), |
| 966 | lut_bezier("HC_Sat", [(0, 1.0), (1, 0.3), (3, 1.7), (5, 0.6), (6, 1.0)]), |
| 967 | lut_bezier("HC_Lum", [(0, 1.0), (2, 0.6), (4, 1.4), (6, 1.0)]), |
| 968 | lut_bezier("HC_RSup", [(0, 0.5), (2, 1.0), (6, 0.5)]), |
| 969 | ] |
| 970 | cases: List[Tuple[int, str, str]] = [] |
| 971 | f = 0 |
| 972 | |
| 973 | def add_op(label: str, kind: str, in_port: str, src: str, extra: str, over_dark: bool = False) -> None: |
| 974 | nonlocal f |
| 975 | opn = f"Op_{f}" |
| 976 | nodes.append( |
| 977 | f"""\t\t{opn} = {kind} {{ |
| 978 | \t\t\tInputs = {{ |
| 979 | \t\t\t\t{in_port} = Input {{ SourceOp = "{src}", Source = "Output", }}, |
| 980 | \t\t\t\t{extra} |
| 981 | \t\t\t}}, |
| 982 | \t\t}},""" |
| 983 | ) |
| 984 | out_n = opn |
| 985 | if over_dark: |
| 986 | vn = f"Vis_{f}" |
| 987 | nodes.append(f'\t\t{vn} = Merge {{ Inputs = {{ Background = Input {{ SourceOp = "DarkBG", Source = "Output", }}, Foreground = Input {{ SourceOp = "{opn}", Source = "Output", }}, }}, }},') |
| 988 | out_n = vn |
| 989 | cases.append((f, label, out_n)) |
| 990 | f += 1 |
| 991 | |
| 992 | # ColorCorrector: SMH + Wheel Hue/Sat/Tint + PreDividePostMultiply |
| 993 | 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) |
| 994 | 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, },") |
| 995 | 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, },") |
| 996 | |
| 997 | # ColorCurves & HueCurves |
| 998 | 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) |
| 999 | 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", },') |
| 1000 | |
| 1001 | # GamutConvert |
| 1002 | 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, },') |
| 1003 | 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, },') |
| 1004 | 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, },') |
| 1005 | |
| 1006 | # ChannelBoolean: Add/Sub/Mul/Div/Copy/Min/Max/Negative/Solid |
| 1007 | cb_ops = [ |
| 1008 | ("CB_Copy_BGR", 0, 'ToRed = Input { Value = 2, }, ToGreen = Input { Value = 1, }, ToBlue = Input { Value = 0, },'), |
| 1009 | ("CB_Add", 1, 'Foreground = Input { SourceOp = "FGLoader", Source = "Output", },'), |
| 1010 | ("CB_Sub", 2, 'Foreground = Input { SourceOp = "FGLoader", Source = "Output", },'), |
| 1011 | ("CB_Mul", 6, 'Foreground = Input { SourceOp = "FGLoader", Source = "Output", },'), |
| 1012 | ("CB_Div", 7, 'Foreground = Input { SourceOp = "FGLoader", Source = "Output", },'), |
| 1013 | ("CB_Max", 8, 'Foreground = Input { SourceOp = "FGLoader", Source = "Output", },'), |
| 1014 | ("CB_Min", 9, 'Foreground = Input { SourceOp = "FGLoader", Source = "Output", },'), |
| 1015 | ("CB_Negative", 10, 'Foreground = Input { SourceOp = "FGLoader", Source = "Output", },'), |
| 1016 | ("CB_Solid", 11, ''), |
| 1017 | ] |
| 1018 | for label, op_code, extra in cb_ops: |
| 1019 | add_op(label, "ChannelBoolean", "Background", "ColorLoader", f"Operation = Input {{ Value = {op_code}, }}, {extra}") |
| 1020 | |
| 1021 | # Blur (Gaussian, Box, FastGaussian + unlocked X/Y) |
| 1022 | 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, },') |
| 1023 | add_op("Blur_Box_12", "Blur", "Input", "ColorLoader", 'Filter = Input { Value = FuID { "Box" }, }, XBlurSize = Input { Value = 12.0, },') |
| 1024 | 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, },') |
| 1025 | |
| 1026 | # Glow, SoftGlow, DirectionalBlur |
| 1027 | 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) |
| 1028 | 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, },") |
| 1029 | 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 }, },") |
| 1030 | |
| 1031 | sw_nodes, sw_splines, out_op = build_switch_chain(cases, "BlackBG", "CB") |
| 1032 | nodes.extend(sw_nodes) |
| 1033 | nodes.append(make_saver(out_op, "matrix_color_blur")) |
| 1034 | comp_path = ensure_dirs() / "comps" / "matrix_color_blur.comp" |
| 1035 | comp_path.write_text(make_comp("\n".join(nodes + sw_splines), len(cases) - 1)) |
| 1036 | return comp_path, "matrix_color_blur", [(c[0], c[1]) for c in cases] |
| 1037 | |
| 1038 | |
| 1039 | def build_matrix_warps_shapes(assets: Dict[str, str]): |
| 1040 | """Transform (Edges=0/1/2/3, Pivot, Angle, Aspect), DVE, CornerPositioner, Displace, Drip, Dent, Vortex, sRender+s*.""" |
| 1041 | nodes = [ |
| 1042 | make_loader("ColorLoader", assets["color"], post_mult=1), |
| 1043 | make_loader("BumpLoader", assets["bump"], post_mult=1), |
| 1044 | """\t\tBlackBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftAlpha = Input { Value = 1, }, }, },""", |
| 1045 | ] |
| 1046 | cases: List[Tuple[int, str, str]] = [] |
| 1047 | f = 0 |
| 1048 | |
| 1049 | for ed in (0, 1, 2, 3): |
| 1050 | opn = f"Op_{f}" |
| 1051 | 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}, }}, }}, }},') |
| 1052 | cases.append((f, f"Transform_Edges={ed}_Pivot_Aspect", opn)) |
| 1053 | f += 1 |
| 1054 | |
| 1055 | warps = [ |
| 1056 | ("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 }, },'), |
| 1057 | ("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 }, },'), |
| 1058 | ("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, },'), |
| 1059 | ("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, },'), |
| 1060 | ("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, },'), |
| 1061 | ("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, },'), |
| 1062 | ("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, },'), |
| 1063 | ("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, },'), |
| 1064 | ] |
| 1065 | for label, kind, inputs in warps: |
| 1066 | opn = f"Op_{f}" |
| 1067 | nodes.append(f"\t\t{opn} = {kind} {{ Inputs = {{ {inputs} }}, }},") |
| 1068 | cases.append((f, label, opn)) |
| 1069 | f += 1 |
| 1070 | |
| 1071 | # sRender + sNGon / sRectangle / sEllipse / sTransform / sMerge / sBoolean / sOutline |
| 1072 | nodes.append( |
| 1073 | """\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, }, }, }, |
| 1074 | \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, }, }, }, |
| 1075 | \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, }, }, }, |
| 1076 | \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, }, }, }, |
| 1077 | \t\tS_Merge = sMerge { Inputs = { Input1 = Input { SourceOp = "S_XF", Source = "Output", }, Input2 = Input { SourceOp = "S_Rect", Source = "Output", }, }, }, |
| 1078 | \t\tS_BoolSub = sBoolean { Inputs = { Operation = Input { Value = FuID { "Subtract" }, }, Input1 = Input { SourceOp = "S_Rect", Source = "Output", }, Input2 = Input { SourceOp = "S_Ell", Source = "Output", }, }, }, |
| 1079 | \t\tS_BoolXor = sBoolean { Inputs = { Operation = Input { Value = FuID { "Xor" }, }, Input1 = Input { SourceOp = "S_NGon", Source = "Output", }, Input2 = Input { SourceOp = "S_Rect", Source = "Output", }, }, }, |
| 1080 | \t\tS_Outl = sOutline { Inputs = { Input = Input { SourceOp = "S_Ell", Source = "Output", }, Thickness = Input { Value = 0.03, }, }, },""" |
| 1081 | ) |
| 1082 | for label, s_src in [ |
| 1083 | ("sRender_NGon_XF_Merge", "S_Merge"), |
| 1084 | ("sRender_sBoolean_Sub", "S_BoolSub"), |
| 1085 | ("sRender_sBoolean_Xor", "S_BoolXor"), |
| 1086 | ("sRender_sOutline_Ell", "S_Outl"), |
| 1087 | ]: |
| 1088 | opn = f"Op_{f}" |
| 1089 | nodes.append(f'\t\t{opn} = sRender {{ Inputs = {{ Width = Input {{ Value = 256, }}, Height = Input {{ Value = 256, }}, Input = Input {{ SourceOp = "{s_src}", Source = "Output", }}, }}, }},') |
| 1090 | cases.append((f, label, opn)) |
| 1091 | f += 1 |
| 1092 | |
| 1093 | sw_nodes, sw_splines, out_op = build_switch_chain(cases, "BlackBG", "WS") |
| 1094 | nodes.extend(sw_nodes) |
| 1095 | nodes.append(make_saver(out_op, "matrix_warps_shapes")) |
| 1096 | comp_path = ensure_dirs() / "comps" / "matrix_warps_shapes.comp" |
| 1097 | comp_path.write_text(make_comp("\n".join(nodes + sw_splines), len(cases) - 1)) |
| 1098 | return comp_path, "matrix_warps_shapes", [(c[0], c[1]) for c in cases] |
| 1099 | |
| 1100 | |
| 1101 | def build_matrix_3d(assets: Dict[str, str]): |
| 1102 | """Cube3D, SurfaceFBXMesh, TextureTransformOperator, BumpMap, LightPoint (Linear/Quad), LightSpot, Duplicate3D, Displace3D, Override3D, ReplaceMaterial3D.""" |
| 1103 | nodes = [ |
| 1104 | make_loader("ColorLoader", assets["color"], post_mult=1), |
| 1105 | make_loader("BumpLoader", assets["bump"], post_mult=1), |
| 1106 | """\t\tBlackBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftAlpha = Input { Value = 1, }, }, }, |
| 1107 | \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, }, }, }, |
| 1108 | \t\tAmbLow = LightAmbient { Inputs = { Intensity = Input { Value = 0.20, }, }, },""", |
| 1109 | ] |
| 1110 | cases: List[Tuple[int, str, str]] = [] |
| 1111 | f = 0 |
| 1112 | |
| 1113 | def add_3d(label: str, scene_nodes: List[str], merge_inputs: str, lighting: int = 1) -> None: |
| 1114 | nonlocal f |
| 1115 | nodes.extend(scene_nodes) |
| 1116 | m3d = f"M3D_{f}" |
| 1117 | rnd = f"Op_{f}" |
| 1118 | nodes.append(f"\t\t{m3d} = Merge3D {{ Inputs = {{ {merge_inputs} SceneInput9 = Input {{ SourceOp = \"CamBase\", Source = \"Output\", }}, }}, }},") |
| 1119 | 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", }}, }}, }},') |
| 1120 | cases.append((f, label, rnd)) |
| 1121 | f += 1 |
| 1122 | |
| 1123 | # 0: Cube3D textured |
| 1124 | add_3d( |
| 1125 | "Cube3D_Textured", |
| 1126 | [ |
| 1127 | '\t\tTex0 = Texture2DOperator { Inputs = { Input = Input { SourceOp = "ColorLoader", Source = "Output", }, }, },', |
| 1128 | '\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", }, }, },', |
| 1129 | ], |
| 1130 | 'SceneInput1 = Input { SourceOp = "Cube0", Source = "Output", },', |
| 1131 | lighting=0, |
| 1132 | ) |
| 1133 | |
| 1134 | # 1: SurfaceFBXMesh (cube.obj) |
| 1135 | add_3d( |
| 1136 | "SurfaceFBXMesh_OBJ", |
| 1137 | [ |
| 1138 | '\t\tTex1 = Texture2DOperator { Inputs = { Input = Input { SourceOp = "ColorLoader", Source = "Output", }, }, },', |
| 1139 | 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", }}, }}, }},', |
| 1140 | ], |
| 1141 | 'SceneInput1 = Input { SourceOp = "Fbx1", Source = "Output", },', |
| 1142 | lighting=0, |
| 1143 | ) |
| 1144 | |
| 1145 | # 2: TextureTransformOperator |
| 1146 | add_3d( |
| 1147 | "TextureTransformOperator", |
| 1148 | [ |
| 1149 | '\t\tTex2 = Texture2DOperator { Inputs = { Input = Input { SourceOp = "ColorLoader", Source = "Output", }, }, },', |
| 1150 | '\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" }, }, }, },', |
| 1151 | '\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", }, }, },', |
| 1152 | ], |
| 1153 | 'SceneInput1 = Input { SourceOp = "Pl2", Source = "Output", },', |
| 1154 | lighting=0, |
| 1155 | ) |
| 1156 | |
| 1157 | # 3: BumpMap + MtlBlinn + LightPoint |
| 1158 | add_3d( |
| 1159 | "BumpMap_MtlBlinn", |
| 1160 | [ |
| 1161 | '\t\tBm3 = BumpMap { Inputs = { Input = Input { SourceOp = "BumpLoader", Source = "Output", }, HeightScale = Input { Value = 4.0, }, }, },', |
| 1162 | '\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", }, }, },', |
| 1163 | '\t\tSph3 = Shape3D { Inputs = { Shape = Input { Value = FuID { "SurfaceSphereInputs" }, }, ["SurfaceSphereInputs.Radius"] = Input { Value = 1.0, }, MaterialInput = Input { SourceOp = "Mtl3", Source = "MaterialOutput", }, }, },', |
| 1164 | '\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, }, }, },', |
| 1165 | ], |
| 1166 | 'SceneInput1 = Input { SourceOp = "Sph3", Source = "Output", }, SceneInput2 = Input { SourceOp = "Pt3", Source = "Output", }, SceneInput3 = Input { SourceOp = "AmbLow", Source = "Output", },', |
| 1167 | lighting=1, |
| 1168 | ) |
| 1169 | |
| 1170 | # 4 & 5: LightPoint Linear (DecayType=1) and Quadratic (DecayType=2) |
| 1171 | for decay_t, d_name in ((1, "Linear"), (2, "Quadratic")): |
| 1172 | add_3d( |
| 1173 | f"LightPoint_Decay={d_name}", |
| 1174 | [ |
| 1175 | 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, }}, }}, }},', |
| 1176 | 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", }}, }}, }},', |
| 1177 | 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}, }}, }}, }},', |
| 1178 | ], |
| 1179 | f'SceneInput1 = Input {{ SourceOp = "Pl_{f}", Source = "Output", }}, SceneInput2 = Input {{ SourceOp = "Pt_{f}", Source = "Output", }}, SceneInput3 = Input {{ SourceOp = "AmbLow", Source = "Output", }},', |
| 1180 | lighting=1, |
| 1181 | ) |
| 1182 | |
| 1183 | # 6: LightSpot |
| 1184 | add_3d( |
| 1185 | "LightSpot_ConePenumbra", |
| 1186 | [ |
| 1187 | '\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, }, }, },', |
| 1188 | '\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", }, }, },', |
| 1189 | '\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, }, }, },', |
| 1190 | ], |
| 1191 | 'SceneInput1 = Input { SourceOp = "Pl6", Source = "Output", }, SceneInput2 = Input { SourceOp = "Sp6", Source = "Output", }, SceneInput3 = Input { SourceOp = "AmbLow", Source = "Output", },', |
| 1192 | lighting=1, |
| 1193 | ) |
| 1194 | |
| 1195 | # 7: Duplicate3D |
| 1196 | add_3d( |
| 1197 | "Duplicate3D_5x", |
| 1198 | [ |
| 1199 | '\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, }, }, },', |
| 1200 | '\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, }, }, },', |
| 1201 | ], |
| 1202 | 'SceneInput1 = Input { SourceOp = "Dup7", Source = "Output", },', |
| 1203 | lighting=0, |
| 1204 | ) |
| 1205 | |
| 1206 | # 8: Displace3D |
| 1207 | add_3d( |
| 1208 | "Displace3D_Bump", |
| 1209 | [ |
| 1210 | '\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", }, }, },', |
| 1211 | '\t\tDisp8 = Displace3D { Inputs = { SceneInput = Input { SourceOp = "Pl8", Source = "Output", }, Input = Input { SourceOp = "BumpLoader", Source = "Output", }, Scale = Input { Value = 0.6, }, }, },', |
| 1212 | ], |
| 1213 | 'SceneInput1 = Input { SourceOp = "Disp8", Source = "Output", },', |
| 1214 | lighting=0, |
| 1215 | ) |
| 1216 | |
| 1217 | # 9: Override3D (hide + material override) |
| 1218 | add_3d( |
| 1219 | "Override3D_Hide_MatOvr", |
| 1220 | [ |
| 1221 | '\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, }, }, },', |
| 1222 | '\t\tOvr9Hide = Override3D { Inputs = { SceneInput = Input { SourceOp = "Sph9L", Source = "Output", }, ["Visibility.DoVisible"] = Input { Value = 1, }, ["Visibility.IsVisible"] = Input { Value = 0, }, }, },', |
| 1223 | '\t\tSph9R = Shape3D { Inputs = { Shape = Input { Value = FuID { "SurfaceSphereInputs" }, }, ["SurfaceSphereInputs.Radius"] = Input { Value = 0.55, }, ["Transform3DOp.Translate.X"] = Input { Value = 0.7, }, }, },', |
| 1224 | '\t\tTex9 = Texture2DOperator { Inputs = { Input = Input { SourceOp = "ColorLoader", Source = "Output", }, }, },', |
| 1225 | '\t\tOvr9Mat = Override3D { Inputs = { SceneInput = Input { SourceOp = "Sph9R", Source = "Output", }, ["Material.DoMaterial"] = Input { Value = 1, }, MaterialInput = Input { SourceOp = "Tex9", Source = "MaterialOutput", }, }, },', |
| 1226 | ], |
| 1227 | 'SceneInput1 = Input { SourceOp = "Ovr9Hide", Source = "Output", }, SceneInput2 = Input { SourceOp = "Ovr9Mat", Source = "Output", },', |
| 1228 | lighting=0, |
| 1229 | ) |
| 1230 | |
| 1231 | # 10: ReplaceMaterial3D |
| 1232 | add_3d( |
| 1233 | "ReplaceMaterial3D_Cook", |
| 1234 | [ |
| 1235 | '\t\tTex10 = Texture2DOperator { Inputs = { Input = Input { SourceOp = "ColorLoader", Source = "Output", }, }, },', |
| 1236 | '\t\tMtl10 = MtlCookTorrance { Inputs = { ["Diffuse.Color.Material"] = Input { SourceOp = "Tex10", Source = "MaterialOutput", }, ["Specular.Roughness"] = Input { Value = 0.25, }, }, },', |
| 1237 | '\t\tSph10 = Shape3D { Inputs = { Shape = Input { Value = FuID { "SurfaceSphereInputs" }, }, ["SurfaceSphereInputs.Radius"] = Input { Value = 1.0, }, }, },', |
| 1238 | '\t\tRep10 = ReplaceMaterial3D { Inputs = { SceneInput = Input { SourceOp = "Sph10", Source = "Output", }, MaterialInput = Input { SourceOp = "Mtl10", Source = "MaterialOutput", }, }, },', |
| 1239 | '\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, }, }, },', |
| 1240 | ], |
| 1241 | 'SceneInput1 = Input { SourceOp = "Rep10", Source = "Output", }, SceneInput2 = Input { SourceOp = "Pt10", Source = "Output", }, SceneInput3 = Input { SourceOp = "AmbLow", Source = "Output", },', |
| 1242 | lighting=1, |
| 1243 | ) |
| 1244 | |
| 1245 | sw_nodes, sw_splines, out_op = build_switch_chain(cases, "BlackBG", "D3D") |
| 1246 | nodes.extend(sw_nodes) |
| 1247 | nodes.append(make_saver(out_op, "matrix_3d")) |
| 1248 | comp_path = ensure_dirs() / "comps" / "matrix_3d.comp" |
| 1249 | comp_path.write_text(make_comp("\n".join(nodes + sw_splines), len(cases) - 1)) |
| 1250 | return comp_path, "matrix_3d", [(c[0], c[1]) for c in cases] |
| 1251 | |
| 1252 | |
| 1253 | def build_matrix_misc(assets: Dict[str, str]): |
| 1254 | """CustomTool (multi-input, getr1b, Setup1, Intermediate1, if), TimeSpeed, Switch, tool-level SourceOp instancing.""" |
| 1255 | nodes = [ |
| 1256 | make_loader("ColorLoader", assets["color"], post_mult=1), |
| 1257 | make_loader("FGLoader", assets["fg"], post_mult=1), |
| 1258 | """\t\tBlackBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftAlpha = Input { Value = 1, }, }, }, |
| 1259 | \t\t-- CustomTool 0: Setup1, Intermediate1, if, getr1b, Image2 |
| 1260 | \t\tOp_0 = Custom { |
| 1261 | \t\t\tInputs = { |
| 1262 | \t\t\t\tImage1 = Input { SourceOp = "ColorLoader", Source = "Output", }, |
| 1263 | \t\t\t\tImage2 = Input { SourceOp = "FGLoader", Source = "Output", }, |
| 1264 | \t\t\t\tNumberIn1 = Input { Value = 0.65, }, |
| 1265 | \t\t\t\tPointIn1 = Input { Value = { 0.45, 0.55 }, }, |
| 1266 | \t\t\t\tSetup1 = Input { Value = "1 - n1", }, |
| 1267 | \t\t\t\tIntermediate1 = Input { Value = "max(0, 1 - dist(x, y, p1x, p1y) * 2)", }, |
| 1268 | \t\t\t\tRedExpression = Input { Value = "if(x > p1x, getr1b(x - 0.1, y + 0.05), r2 * i1 + s1 * 0.2)", }, |
| 1269 | \t\t\t\tGreenExpression = Input { Value = "if(y > p1y, g1 * i1, g2 + n1 * 0.1)", }, |
| 1270 | \t\t\t\tBlueExpression = Input { Value = "b1 * (1 - i1) + b2 * i1", }, |
| 1271 | \t\t\t\tAlphaExpression = Input { Value = "1", }, |
| 1272 | \t\t\t}, |
| 1273 | \t\t}, |
| 1274 | \t\t-- TimeSpeed (frames 1 & 2 evaluate animated Transform at Speed=2.0, Delay=0.5) |
| 1275 | \t\tXfAnim = Transform { |
| 1276 | \t\t\tInputs = { |
| 1277 | \t\t\t\tInput = Input { SourceOp = "ColorLoader", Source = "Output", }, |
| 1278 | \t\t\t\tAngle = Input { SourceOp = "TS_Angle", Source = "Value", }, |
| 1279 | \t\t\t\tSize = Input { Value = 0.8, }, |
| 1280 | \t\t\t}, |
| 1281 | \t\t}, |
| 1282 | \t\tOp_1 = TimeSpeed { |
| 1283 | \t\t\tInputs = { |
| 1284 | \t\t\t\tInput = Input { SourceOp = "XfAnim", Source = "Output", }, |
| 1285 | \t\t\t\tSpeed = Input { Value = 2.0, }, |
| 1286 | \t\t\t\tDelay = Input { Value = 0.5, }, |
| 1287 | \t\t\t}, |
| 1288 | \t\t}, |
| 1289 | \t\t-- Switch (Fusion 21 native Source=0/1 with Input0/Input1) |
| 1290 | \t\tOp_2 = Switch { |
| 1291 | \t\t\tInputs = { |
| 1292 | \t\t\t\tSource = Input { Value = 0, }, |
| 1293 | \t\t\t\tInput0 = Input { SourceOp = "ColorLoader", Source = "Output", }, |
| 1294 | \t\t\t\tInput1 = Input { SourceOp = "FGLoader", Source = "Output", }, |
| 1295 | \t\t\t}, |
| 1296 | \t\t}, |
| 1297 | \t\tOp_3 = Switch { |
| 1298 | \t\t\tInputs = { |
| 1299 | \t\t\t\tSource = Input { Value = 1, }, |
| 1300 | \t\t\t\tInput0 = Input { SourceOp = "ColorLoader", Source = "Output", }, |
| 1301 | \t\t\t\tInput1 = Input { SourceOp = "FGLoader", Source = "Output", }, |
| 1302 | \t\t\t}, |
| 1303 | \t\t}, |
| 1304 | \t\t-- Tool-level SourceOp instancing |
| 1305 | \t\tMasterCC = ColorCorrector { |
| 1306 | \t\t\tInputs = { |
| 1307 | \t\t\t\tInput = Input { SourceOp = "ColorLoader", Source = "Output", }, |
| 1308 | \t\t\t\tWheelHue1 = Input { Value = 0.25, }, |
| 1309 | \t\t\t\tWheelSaturation1 = Input { Value = 1.45, }, |
| 1310 | \t\t\t\tMasterRGBGain = Input { Value = 1.35, }, |
| 1311 | \t\t\t\tMasterRGBGamma = Input { Value = 0.85, }, |
| 1312 | \t\t\t}, |
| 1313 | \t\t}, |
| 1314 | \t\tOp_4 = ColorCorrector { |
| 1315 | \t\t\tSourceOp = "MasterCC", |
| 1316 | \t\t\tInputs = { |
| 1317 | \t\t\t\tInput = Input { SourceOp = "FGLoader", Source = "Output", }, |
| 1318 | \t\t\t\tWheelHue1 = Input {}, |
| 1319 | \t\t\t\tMasterRGBGain = Input { Value = 0.8, }, |
| 1320 | \t\t\t}, |
| 1321 | \t\t}, |
| 1322 | \t\tOp_5 = Merge { |
| 1323 | \t\t\tInputs = { |
| 1324 | \t\t\t\tBackground = Input { SourceOp = "BlackBG", Source = "Output", }, |
| 1325 | \t\t\t\tForeground = Input { SourceOp = "Op_4", Source = "Output", }, |
| 1326 | \t\t\t}, |
| 1327 | \t\t},""", |
| 1328 | linear_spline("TS_Angle", {0: 0.0, 4: 180.0}), |
| 1329 | ] |
| 1330 | cases = [ |
| 1331 | (0, "CustomTool_multi_getr1b_Setup_Inter_if", "Op_0"), |
| 1332 | (1, "TimeSpeed_f1_Speed2_Delay0.5", "Op_1"), |
| 1333 | (2, "TimeSpeed_f2_Speed2_Delay0.5", "Op_1"), |
| 1334 | (3, "Switch_Source0_Input0", "Op_2"), |
| 1335 | (4, "Switch_Source1_Input1", "Op_3"), |
| 1336 | (5, "SourceOp_Instance_ColorCorrector", "Op_5"), |
| 1337 | ] |
| 1338 | sw_nodes, sw_splines, out_op = build_switch_chain(cases, "BlackBG", "MS") |
| 1339 | nodes.extend(sw_nodes) |
| 1340 | nodes.append(make_saver(out_op, "matrix_misc")) |
| 1341 | comp_path = ensure_dirs() / "comps" / "matrix_misc.comp" |
| 1342 | comp_path.write_text(make_comp("\n".join(nodes + sw_splines), len(cases) - 1)) |
| 1343 | return comp_path, "matrix_misc", [(c[0], c[1]) for c in cases] |
| 1344 | |
| 1345 | |
| 1346 | MATRIX_BUILDERS = { |
| 1347 | "matrix_merge_modes": build_matrix_merge_modes, |
| 1348 | "matrix_hdr_depth": build_matrix_hdr_depth, |
| 1349 | "matrix_masks": build_matrix_masks, |
| 1350 | "matrix_color_blur": build_matrix_color_blur, |
| 1351 | "matrix_warps_shapes": build_matrix_warps_shapes, |
| 1352 | "matrix_3d": build_matrix_3d, |
| 1353 | "matrix_misc": build_matrix_misc, |
| 1354 | } |
| 1355 | |
| 1356 | |
| 1357 | # --------------------------------------------------------------------------- |
| 1358 | # Randomized DAG Fuzzer + Auto-Bisector |
| 1359 | # --------------------------------------------------------------------------- |
| 1360 | |
| 1361 | |
| 1362 | @dataclass |
| 1363 | class MaskNodeSpec: |
| 1364 | name: str |
| 1365 | kind: str # EllipseMask | RectangleMask | PolylineMask |
| 1366 | params: Dict[str, Any] |
| 1367 | paint_mode: Optional[str] = None |
| 1368 | prev_mask: Optional[str] = None |
| 1369 | |
| 1370 | |
| 1371 | @dataclass |
| 1372 | class MaskChainSpec: |
| 1373 | nodes: List[MaskNodeSpec] |
| 1374 | apply_inverted: int = 0 |
| 1375 | multiply_by_mask: int = 0 |
| 1376 | |
| 1377 | def output_name(self) -> str: |
| 1378 | return self.nodes[-1].name |
| 1379 | |
| 1380 | |
| 1381 | @dataclass |
| 1382 | class SplineParam: |
| 1383 | spline_name: str |
| 1384 | kind: str # step | linear | expr_num | expr_pt |
| 1385 | keyframes: Optional[Dict[int, float]] = None |
| 1386 | expr_inputs: Optional[Dict[str, Any]] = None |
| 1387 | |
| 1388 | def eval_at(self, frame: int) -> Any: |
| 1389 | if self.kind in ("step", "linear") and self.keyframes: |
| 1390 | pts = sorted(self.keyframes.items()) |
| 1391 | if frame <= pts[0][0]: |
| 1392 | return pts[0][1] |
| 1393 | if frame >= pts[-1][0]: |
| 1394 | return pts[-1][1] |
| 1395 | for (f0, v0), (f1, v1) in zip(pts, pts[1:]): |
| 1396 | if f0 <= frame <= f1: |
| 1397 | if self.kind == "step" or f1 == f0: |
| 1398 | return v0 |
| 1399 | t = (frame - f0) / (f1 - f0) |
| 1400 | return round(v0 + (v1 - v0) * t, 5) |
| 1401 | return 0.5 |
| 1402 | |
| 1403 | |
| 1404 | @dataclass |
| 1405 | class DagNode: |
| 1406 | name: str |
| 1407 | kind: str |
| 1408 | is_source: bool |
| 1409 | primary_port: Optional[str] = None |
| 1410 | primary_src: Optional[str] = None |
| 1411 | secondary_port: Optional[str] = None |
| 1412 | secondary_src: Optional[str] = None |
| 1413 | params: Dict[str, Any] = field(default_factory=dict) |
| 1414 | mask: Optional[MaskChainSpec] = None |
| 1415 | loader_path: Optional[str] = None |
| 1416 | loader_post_mult: int = 1 |
| 1417 | |
| 1418 | |
| 1419 | def _fmt_val(v: Any, prefix: str, frame_shift: int) -> Tuple[str, List[str]]: |
| 1420 | """Formats a Fusion Input value and returns (lua_rhs, extra_aux_defs).""" |
| 1421 | if isinstance(v, SplineParam): |
| 1422 | sname = f"{prefix}{v.spline_name}" |
| 1423 | if v.kind == "step" and v.keyframes is not None: |
| 1424 | shifted = {k + frame_shift: val for k, val in v.keyframes.items()} |
| 1425 | return f'Input {{ SourceOp = "{sname}", Source = "Value", }}', [step_spline(sname, shifted)] |
| 1426 | if v.kind == "linear" and v.keyframes is not None: |
| 1427 | shifted = {k + frame_shift: val for k, val in v.keyframes.items()} |
| 1428 | return f'Input {{ SourceOp = "{sname}", Source = "Value", }}', [linear_spline(sname, shifted)] |
| 1429 | if v.kind in ("expr_num", "expr_pt") and v.expr_inputs is not None: |
| 1430 | src_port = "NumberResult" if v.kind == "expr_num" else "PointResult" |
| 1431 | lines = [] |
| 1432 | for ek, ev in v.expr_inputs.items(): |
| 1433 | if isinstance(ev, str): |
| 1434 | lines.append(f'{ek} = Input {{ Value = "{ev}", }},') |
| 1435 | elif isinstance(ev, tuple): |
| 1436 | lines.append(f"{ek} = Input {{ Value = {{ {ev[0]}, {ev[1]} }}, }},") |
| 1437 | else: |
| 1438 | lines.append(f"{ek} = Input {{ Value = {ev}, }},") |
| 1439 | 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}," |
| 1440 | return f'Input {{ SourceOp = "{sname}", Source = "{src_port}", }}', [expr_def] |
| 1441 | if isinstance(v, tuple) and len(v) == 2 and v[0] == "FuID": |
| 1442 | return f'Input {{ Value = FuID {{ "{v[1]}" }}, }}', [] |
| 1443 | if isinstance(v, tuple) and len(v) == 2: |
| 1444 | return f"Input {{ Value = {{ {v[0]}, {v[1]} }}, }}", [] |
| 1445 | if isinstance(v, str): |
| 1446 | return f'Input {{ Value = "{v}", }}', [] |
| 1447 | return f"Input {{ Value = {v}, }}", [] |
| 1448 | |
| 1449 | |
| 1450 | @dataclass |
| 1451 | class FuzzGraph: |
| 1452 | seed: int |
| 1453 | eval_frame: int |
| 1454 | nodes: List[DagNode] |
| 1455 | |
| 1456 | def clone(self) -> "FuzzGraph": |
| 1457 | import copy |
| 1458 | return copy.deepcopy(self) |
| 1459 | |
| 1460 | def output_node(self) -> str: |
| 1461 | return self.nodes[-1].name |
| 1462 | |
| 1463 | def active_cone_set(self, target_name: str) -> set: |
| 1464 | by_name = {n.name: n for n in self.nodes} |
| 1465 | seen = set() |
| 1466 | stack = [target_name] |
| 1467 | while stack: |
| 1468 | cur = stack.pop() |
| 1469 | if cur in seen or cur not in by_name: |
| 1470 | continue |
| 1471 | seen.add(cur) |
| 1472 | nd = by_name[cur] |
| 1473 | if nd.primary_src: |
| 1474 | stack.append(nd.primary_src) |
| 1475 | if nd.secondary_src: |
| 1476 | stack.append(nd.secondary_src) |
| 1477 | return seen |
| 1478 | |
| 1479 | def prune_to(self, target_name: str) -> "FuzzGraph": |
| 1480 | g = self.clone() |
| 1481 | cone = g.active_cone_set(target_name) |
| 1482 | g.nodes = [n for n in g.nodes if n.name in cone] |
| 1483 | return g |
| 1484 | |
| 1485 | def bypass_node(self, node_name: str) -> Optional["FuzzGraph"]: |
| 1486 | g = self.clone() |
| 1487 | target = next((n for n in g.nodes if n.name == node_name), None) |
| 1488 | if target is None or target.is_source or target.primary_src is None: |
| 1489 | return None |
| 1490 | repl = target.primary_src |
| 1491 | for n in g.nodes: |
| 1492 | if n.primary_src == node_name: |
| 1493 | n.primary_src = repl |
| 1494 | if n.secondary_src == node_name: |
| 1495 | n.secondary_src = repl |
| 1496 | g.nodes = [n for n in g.nodes if n.name != node_name] |
| 1497 | if not g.nodes: |
| 1498 | return None |
| 1499 | return g.prune_to(g.nodes[-1].name) |
| 1500 | |
| 1501 | def strip_mask(self, node_name: str) -> Optional["FuzzGraph"]: |
| 1502 | g = self.clone() |
| 1503 | for n in g.nodes: |
| 1504 | if n.name == node_name and n.mask is not None: |
| 1505 | n.mask = None |
| 1506 | return g |
| 1507 | return None |
| 1508 | |
| 1509 | def flatten_splines(self) -> Optional["FuzzGraph"]: |
| 1510 | g = self.clone() |
| 1511 | changed = False |
| 1512 | for n in g.nodes: |
| 1513 | for k, v in list(n.params.items()): |
| 1514 | if isinstance(v, SplineParam): |
| 1515 | changed = True |
| 1516 | if v.kind in ("step", "linear"): |
| 1517 | n.params[k] = v.eval_at(g.eval_frame) |
| 1518 | elif v.kind == "expr_num": |
| 1519 | n.params[k] = 0.75 |
| 1520 | else: |
| 1521 | n.params[k] = (0.45, 0.55) |
| 1522 | return g if changed else None |
| 1523 | |
| 1524 | def summary_tools(self) -> List[Dict[str, Any]]: |
| 1525 | out = [] |
| 1526 | for n in self.nodes: |
| 1527 | p_short = {} |
| 1528 | for k, v in n.params.items(): |
| 1529 | if isinstance(v, SplineParam): |
| 1530 | p_short[k] = f"<{v.kind}>" |
| 1531 | elif isinstance(v, tuple) and len(v) == 2 and v[0] == "FuID": |
| 1532 | p_short[k] = v[1] |
| 1533 | else: |
| 1534 | p_short[k] = v |
| 1535 | entry: Dict[str, Any] = {"name": n.name, "kind": n.kind, "params": p_short} |
| 1536 | if n.mask is not None: |
| 1537 | entry["mask"] = [m.kind for m in n.mask.nodes] |
| 1538 | out.append(entry) |
| 1539 | return out |
| 1540 | |
| 1541 | def to_lua_defs(self, prefix: str = "", frame_shift: int = 0) -> Tuple[List[str], List[str], str]: |
| 1542 | """Emits (tool_blocks, aux_splines_or_exprs, final_output_name).""" |
| 1543 | tool_blocks: List[str] = [] |
| 1544 | aux_blocks: List[str] = [] |
| 1545 | |
| 1546 | for n in self.nodes: |
| 1547 | full_name = f"{prefix}{n.name}" |
| 1548 | if n.kind == "Loader": |
| 1549 | assert n.loader_path is not None |
| 1550 | tool_blocks.append(make_loader(full_name, n.loader_path, post_mult=n.loader_post_mult)) |
| 1551 | continue |
| 1552 | |
| 1553 | # Emit mask chain if present |
| 1554 | if n.mask is not None: |
| 1555 | for mi, mn in enumerate(n.mask.nodes): |
| 1556 | mname = f"{prefix}{mn.name}" |
| 1557 | in_lines = [] |
| 1558 | if mn.prev_mask: |
| 1559 | in_lines.append(f'EffectMask = Input {{ SourceOp = "{prefix}{mn.prev_mask}", Source = "Mask", }},') |
| 1560 | if mn.paint_mode: |
| 1561 | in_lines.append(f'PaintMode = Input {{ Value = FuID {{ "{mn.paint_mode}" }}, }},') |
| 1562 | for pk, pv in mn.params.items(): |
| 1563 | if pk == "Polyline": |
| 1564 | in_lines.append(pv) |
| 1565 | else: |
| 1566 | rhs, extra = _fmt_val(pv, prefix, frame_shift) |
| 1567 | in_lines.append(f"{pk} = {rhs},") |
| 1568 | aux_blocks.extend(extra) |
| 1569 | tool_blocks.append( |
| 1570 | f"\t\t{mname} = {mn.kind} {{\n\t\t\tInputs = {{\n\t\t\t\t" |
| 1571 | + "\n\t\t\t\t".join(in_lines) |
| 1572 | + "\n\t\t\t},\n\t\t}," |
| 1573 | ) |
| 1574 | |
| 1575 | in_lines = [] |
| 1576 | if n.primary_port and n.primary_src: |
| 1577 | in_lines.append(f'{n.primary_port} = Input {{ SourceOp = "{prefix}{n.primary_src}", Source = "Output", }},') |
| 1578 | if n.secondary_port and n.secondary_src: |
| 1579 | in_lines.append(f'{n.secondary_port} = Input {{ SourceOp = "{prefix}{n.secondary_src}", Source = "Output", }},') |
| 1580 | if n.mask is not None: |
| 1581 | in_lines.append(f'EffectMask = Input {{ SourceOp = "{prefix}{n.mask.output_name()}", Source = "Mask", }},') |
| 1582 | if n.mask.apply_inverted: |
| 1583 | in_lines.append("ApplyMaskInverted = Input { Value = 1, },") |
| 1584 | if n.mask.multiply_by_mask: |
| 1585 | in_lines.append("MultiplyByMask = Input { Value = 1, },") |
| 1586 | |
| 1587 | for pk, pv in n.params.items(): |
| 1588 | rhs, extra = _fmt_val(pv, prefix, frame_shift) |
| 1589 | in_lines.append(f"{pk} = {rhs},") |
| 1590 | aux_blocks.extend(extra) |
| 1591 | |
| 1592 | tool_blocks.append( |
| 1593 | f"\t\t{full_name} = {n.kind} {{\n\t\t\tInputs = {{\n\t\t\t\t" |
| 1594 | + "\n\t\t\t\t".join(in_lines) |
| 1595 | + "\n\t\t\t},\n\t\t}," |
| 1596 | ) |
| 1597 | |
| 1598 | return tool_blocks, aux_blocks, f"{prefix}{self.nodes[-1].name}" |
| 1599 | |
| 1600 | |
| 1601 | def _gen_mask_chain(rng: random.Random, tag: str) -> MaskChainSpec: |
| 1602 | def one_mask(name: str, prev: Optional[str]) -> MaskNodeSpec: |
| 1603 | kind = rng.choice(["EllipseMask", "RectangleMask", "PolylineMask"]) |
| 1604 | soft = rng.choice([0.0, 0.015, 0.04, 0.09]) |
| 1605 | inv = rng.choice([0, 0, 1]) |
| 1606 | lvl = round(rng.uniform(0.55, 1.0), 3) |
| 1607 | params: Dict[str, Any] = { |
| 1608 | "MaskWidth": 256, |
| 1609 | "MaskHeight": 256, |
| 1610 | "SoftEdge": soft, |
| 1611 | "Invert": inv, |
| 1612 | "Level": lvl, |
| 1613 | } |
| 1614 | if kind in ("EllipseMask", "RectangleMask"): |
| 1615 | params["Center"] = (round(rng.uniform(0.3, 0.7), 3), round(rng.uniform(0.3, 0.7), 3)) |
| 1616 | params["Width"] = round(rng.uniform(0.25, 0.65), 3) |
| 1617 | params["Height"] = round(rng.uniform(0.25, 0.65), 3) |
| 1618 | params["Angle"] = round(rng.uniform(-45.0, 45.0), 1) |
| 1619 | if kind == "RectangleMask" and rng.random() < 0.4: |
| 1620 | params["CornerRadius"] = round(rng.uniform(0.1, 0.4), 2) |
| 1621 | if rng.random() < 0.25: |
| 1622 | params["Solid"] = 0 |
| 1623 | params["BorderWidth"] = round(rng.uniform(0.02, 0.06), 3) |
| 1624 | else: |
| 1625 | x0 = round(rng.uniform(-0.35, -0.1), 3) |
| 1626 | y0 = round(rng.uniform(-0.35, -0.1), 3) |
| 1627 | x1 = round(rng.uniform(0.1, 0.35), 3) |
| 1628 | y1 = round(rng.uniform(-0.3, 0.05), 3) |
| 1629 | y2 = round(rng.uniform(0.15, 0.38), 3) |
| 1630 | params["Polyline"] = ( |
| 1631 | f"Polyline = Input {{ Value = Polyline {{ Closed = true, Points = {{ " |
| 1632 | f"{{ Linear = true, X = {x0}, Y = {y0} }}, " |
| 1633 | f"{{ Linear = true, X = {x1}, Y = {y1} }}, " |
| 1634 | f"{{ Linear = true, X = 0.0, Y = {y2} }} }} }}, }}," |
| 1635 | ) |
| 1636 | pm = rng.choice(["Merge", "Add", "Subtract", "Minimum", "Maximum", "Multiply", "Invert"]) if prev else None |
| 1637 | return MaskNodeSpec(name=name, kind=kind, params=params, paint_mode=pm, prev_mask=prev) |
| 1638 | |
| 1639 | m0 = one_mask(f"{tag}_M0", None) |
| 1640 | chain = [m0] |
| 1641 | if rng.random() < 0.45: |
| 1642 | chain.append(one_mask(f"{tag}_M1", m0.name)) |
| 1643 | return MaskChainSpec( |
| 1644 | nodes=chain, |
| 1645 | apply_inverted=1 if rng.random() < 0.3 else 0, |
| 1646 | multiply_by_mask=1 if rng.random() < 0.25 else 0, |
| 1647 | ) |
| 1648 | |
| 1649 | |
| 1650 | def generate_random_dag(seed: int, assets: Dict[str, str]) -> FuzzGraph: |
| 1651 | """Csmith-style seeded generator producing valid 4-9 node Fusion DAGs.""" |
| 1652 | rng = random.Random(seed) |
| 1653 | eval_frame = rng.choice([0, 1, 2]) |
| 1654 | nodes: List[DagNode] = [] |
| 1655 | |
| 1656 | def make_source(idx: int) -> DagNode: |
| 1657 | name = f"S{idx}" |
| 1658 | stype = rng.choice(["Loader", "Loader", "Background", "FastNoise", "Plasma"]) |
| 1659 | if stype == "Loader": |
| 1660 | plate = rng.choice(["color", "fg", "small", "bump"]) |
| 1661 | pm = rng.choice([1, 1, 0]) |
| 1662 | return DagNode(name=name, kind="Loader", is_source=True, loader_path=assets[plate], loader_post_mult=pm) |
| 1663 | if stype == "Background": |
| 1664 | btype = rng.choice(["Solid", "Horizontal", "Vertical", "FourCorner"]) |
| 1665 | p: Dict[str, Any] = { |
| 1666 | "Width": 256, |
| 1667 | "Height": 256, |
| 1668 | "Type": ("FuID", btype), |
| 1669 | "TopLeftRed": round(rng.uniform(0.05, 0.95), 3), |
| 1670 | "TopLeftGreen": round(rng.uniform(0.05, 0.95), 3), |
| 1671 | "TopLeftBlue": round(rng.uniform(0.05, 0.95), 3), |
| 1672 | "TopLeftAlpha": round(rng.uniform(0.4, 1.0), 3), |
| 1673 | } |
| 1674 | if btype != "Solid": |
| 1675 | p["TopRightRed"] = round(rng.uniform(0.05, 0.95), 3) |
| 1676 | p["TopRightGreen"] = round(rng.uniform(0.05, 0.95), 3) |
| 1677 | p["TopRightBlue"] = round(rng.uniform(0.05, 0.95), 3) |
| 1678 | p["BottomLeftRed"] = round(rng.uniform(0.05, 0.95), 3) |
| 1679 | p["BottomLeftGreen"] = round(rng.uniform(0.05, 0.95), 3) |
| 1680 | p["BottomLeftBlue"] = round(rng.uniform(0.05, 0.95), 3) |
| 1681 | if rng.random() < 0.35: |
| 1682 | p["Depth"] = rng.choice([1, 3, 4]) |
| 1683 | return DagNode(name=name, kind="Background", is_source=True, params=p) |
| 1684 | if stype == "FastNoise": |
| 1685 | return DagNode( |
| 1686 | name=name, |
| 1687 | kind="FastNoise", |
| 1688 | is_source=True, |
| 1689 | params={ |
| 1690 | "Width": 256, |
| 1691 | "Height": 256, |
| 1692 | "Detail": round(rng.uniform(0.5, 6.0), 2), |
| 1693 | "Contrast": round(rng.uniform(0.4, 2.2), 2), |
| 1694 | "Brightness": round(rng.uniform(-0.3, 0.3), 2), |
| 1695 | "XScale": round(rng.uniform(2.0, 18.0), 2), |
| 1696 | "YScale": round(rng.uniform(2.0, 18.0), 2), |
| 1697 | "Seethe": round(rng.uniform(0.0, 50.0), 2), |
| 1698 | "Discontinuous": rng.choice([0, 1]), |
| 1699 | "Color1Alpha": 1, |
| 1700 | }, |
| 1701 | ) |
| 1702 | return DagNode( |
| 1703 | name=name, |
| 1704 | kind="Plasma", |
| 1705 | is_source=True, |
| 1706 | params={ |
| 1707 | "Width": 256, |
| 1708 | "Height": 256, |
| 1709 | "Phase": round(rng.uniform(0.0, 1.0), 3), |
| 1710 | "Scale": round(rng.uniform(0.6, 2.5), 2), |
| 1711 | }, |
| 1712 | ) |
| 1713 | |
| 1714 | num_sources = rng.choice([1, 2, 2]) |
| 1715 | for si in range(num_sources): |
| 1716 | nodes.append(make_source(si)) |
| 1717 | |
| 1718 | op_pool = [ |
| 1719 | "Transform", "Merge", "Dissolve", "BrightnessContrast", "ColorCorrector", |
| 1720 | "ChannelBoolean", "Blur", "Glow", "SoftGlow", "DirectionalBlur", |
| 1721 | "DVE", "CornerPositioner", "Displace", "Vortex", "Drip", "Dent", |
| 1722 | "ChangeDepth", "GamutConvert", "ColorGain", "Custom", |
| 1723 | ] |
| 1724 | num_internal = rng.randint(4, 9) |
| 1725 | has_anim = rng.random() < 0.30 |
| 1726 | has_inf_edges = False |
| 1727 | |
| 1728 | for ni in range(num_internal): |
| 1729 | nname = f"N{ni}" |
| 1730 | kind = rng.choice(op_pool) |
| 1731 | if kind == "Drip" and has_inf_edges: |
| 1732 | kind = "Dent" |
| 1733 | # Prefer chaining mostly from recent nodes while allowing DAG forks from earlier nodes |
| 1734 | avail = [n.name for n in nodes] |
| 1735 | src_a = avail[-1] if rng.random() < 0.65 else rng.choice(avail) |
| 1736 | src_b = rng.choice(avail) |
| 1737 | |
| 1738 | mask = _gen_mask_chain(rng, nname) if (kind not in ("ChangeDepth",) and rng.random() < 0.32) else None |
| 1739 | blend = round(rng.uniform(0.55, 1.0), 2) if rng.random() < 0.25 else 1.0 |
| 1740 | |
| 1741 | prim_port = "Input" |
| 1742 | sec_port: Optional[str] = None |
| 1743 | sec_src: Optional[str] = None |
| 1744 | params: Dict[str, Any] = {} |
| 1745 | |
| 1746 | if kind == "Transform": |
| 1747 | ang: Any = round(rng.uniform(-45.0, 45.0), 1) |
| 1748 | if has_anim and ni == 0: |
| 1749 | ang = SplineParam(f"{nname}_Ang", "linear", keyframes={0: -15.0, 2: 35.0}) |
| 1750 | ed_val = rng.choice([0, 1, 2, 3]) |
| 1751 | if ed_val in (1, 3): |
| 1752 | has_inf_edges = True |
| 1753 | params = { |
| 1754 | "Center": (round(rng.uniform(0.32, 0.68), 3), round(rng.uniform(0.32, 0.68), 3)), |
| 1755 | "Pivot": (round(rng.uniform(0.25, 0.75), 3), round(rng.uniform(0.25, 0.75), 3)), |
| 1756 | "Size": round(rng.uniform(0.65, 1.35), 3), |
| 1757 | "Aspect": round(rng.uniform(0.75, 1.35), 3), |
| 1758 | "Angle": ang, |
| 1759 | "Edges": ed_val, |
| 1760 | "Blend": blend, |
| 1761 | } |
| 1762 | elif kind == "Merge": |
| 1763 | prim_port = "Background" |
| 1764 | sec_port = "Foreground" |
| 1765 | sec_src = src_b |
| 1766 | m_edges = rng.choice([0, 1, 2, 3]) if rng.random() < 0.3 else 0 |
| 1767 | if m_edges in (1, 3): |
| 1768 | has_inf_edges = True |
| 1769 | params = { |
| 1770 | "ApplyMode": ("FuID", rng.choice(["Normal", "Screen", "Multiply", "Overlay", "Difference", "SoftLight", "HardLight", "ColorDodge", "Exclusion"])), |
| 1771 | "Operator": ("FuID", rng.choice(["Over", "Over", "In", "Held Out", "Atop", "XOr"])), |
| 1772 | "Size": round(rng.uniform(0.55, 1.15), 3), |
| 1773 | "Angle": round(rng.uniform(-25.0, 25.0), 1), |
| 1774 | "Center": (round(rng.uniform(0.35, 0.65), 3), round(rng.uniform(0.35, 0.65), 3)), |
| 1775 | "Gain": round(rng.uniform(0.35, 1.25), 2), |
| 1776 | "SubtractiveAdditive": rng.choice([0.0, 0.5, 1.0]), |
| 1777 | "BurnIn": round(rng.uniform(0.0, 0.4), 2) if rng.random() < 0.35 else 0.0, |
| 1778 | "Edges": m_edges, |
| 1779 | "PerformDepthMerge": 0, |
| 1780 | "Blend": blend, |
| 1781 | } |
| 1782 | elif kind == "Dissolve": |
| 1783 | prim_port = "Background" |
| 1784 | sec_port = "Foreground" |
| 1785 | sec_src = src_b |
| 1786 | params = {"Mix": round(rng.uniform(0.2, 0.85), 2), "Blend": blend} |
| 1787 | elif kind == "BrightnessContrast": |
| 1788 | g_val: Any = round(rng.uniform(0.5, 2.2), 2) |
| 1789 | if has_anim and ni == 1: |
| 1790 | g_val = SplineParam( |
| 1791 | f"{nname}_ExprG", |
| 1792 | "expr_num", |
| 1793 | expr_inputs={"n1": round(rng.uniform(0.6, 1.6), 2), "NumberExpression": "n1 * 0.8 + 0.35"}, |
| 1794 | ) |
| 1795 | params = { |
| 1796 | "Gain": g_val, |
| 1797 | "Lift": round(rng.uniform(-0.15, 0.2), 2), |
| 1798 | "Gamma": round(rng.uniform(0.6, 1.6), 2), |
| 1799 | "Contrast": round(rng.uniform(-0.25, 0.45), 2), |
| 1800 | "Brightness": round(rng.uniform(-0.2, 0.2), 2), |
| 1801 | "Saturation": round(rng.uniform(0.3, 1.6), 2), |
| 1802 | "PreDividePostMultiply": rng.choice([0, 1]), |
| 1803 | "Blend": blend, |
| 1804 | } |
| 1805 | elif kind == "ColorCorrector": |
| 1806 | params = { |
| 1807 | "WheelHue1": round(rng.uniform(-0.35, 0.35), 3), |
| 1808 | "WheelSaturation1": round(rng.uniform(0.5, 1.6), 2), |
| 1809 | "WheelTintAngle1": round(rng.uniform(-0.5, 0.5), 3), |
| 1810 | "WheelTintLength1": round(rng.uniform(0.0, 0.7), 2), |
| 1811 | "TintMode": rng.choice([0, 1, 2]), |
| 1812 | "MasterRGBGain": round(rng.uniform(0.65, 1.45), 2), |
| 1813 | "ShadowsRGBGain": round(rng.uniform(0.65, 1.35), 2), |
| 1814 | "HighlightsRGBGain": round(rng.uniform(0.65, 1.35), 2), |
| 1815 | "PreDividePostMultiply": rng.choice([0, 1]), |
| 1816 | "Blend": blend, |
| 1817 | } |
| 1818 | elif kind == "ChannelBoolean": |
| 1819 | prim_port = "Background" |
| 1820 | sec_port = "Foreground" |
| 1821 | sec_src = src_b |
| 1822 | params = { |
| 1823 | "Operation": rng.choice([0, 1, 2, 6, 8, 9, 10, 13]), |
| 1824 | "ToRed": rng.choice([0, 1, 2, 5, 10]), |
| 1825 | "ToGreen": rng.choice([0, 1, 2, 6, 10]), |
| 1826 | "ToBlue": rng.choice([0, 1, 2, 7, 10]), |
| 1827 | "ToAlpha": rng.choice([3, 8, 16]), |
| 1828 | "Blend": blend, |
| 1829 | } |
| 1830 | elif kind == "Blur": |
| 1831 | params = { |
| 1832 | "Filter": ("FuID", rng.choice(["Gaussian", "Box", "Fast Gaussian"])), |
| 1833 | "LockBlurXY": 0, |
| 1834 | "XBlurSize": round(rng.uniform(2.0, 18.0), 1), |
| 1835 | "YBlurSize": round(rng.uniform(2.0, 18.0), 1), |
| 1836 | "ClippingMode": ("FuID", rng.choice(["Frame", "None"])), |
| 1837 | "Blend": blend, |
| 1838 | } |
| 1839 | elif kind == "Glow": |
| 1840 | params = { |
| 1841 | "LockGlowSize": 0, |
| 1842 | "XGlowSize": round(rng.uniform(4.0, 20.0), 1), |
| 1843 | "YGlowSize": round(rng.uniform(2.0, 14.0), 1), |
| 1844 | "Glow": round(rng.uniform(0.4, 0.88), 2), |
| 1845 | "Blend": blend, |
| 1846 | } |
| 1847 | elif kind == "SoftGlow": |
| 1848 | params = { |
| 1849 | "LockGlowSize": 0, |
| 1850 | "XGlowSize": round(rng.uniform(4.0, 20.0), 1), |
| 1851 | "YGlowSize": round(rng.uniform(2.0, 16.0), 1), |
| 1852 | "Gain": round(rng.uniform(0.8, 2.5), 2), |
| 1853 | "Threshold": round(rng.uniform(0.1, 0.65), 2), |
| 1854 | "Blend": blend, |
| 1855 | } |
| 1856 | elif kind == "DirectionalBlur": |
| 1857 | params = { |
| 1858 | "Type": rng.choice([0, 1, 2]), |
| 1859 | "Length": round(rng.uniform(0.02, 0.12), 3), |
| 1860 | "Angle": round(rng.uniform(-90.0, 90.0), 1), |
| 1861 | "Glow": round(rng.uniform(0.0, 0.4), 2), |
| 1862 | "Blend": blend, |
| 1863 | } |
| 1864 | elif kind == "DVE": |
| 1865 | params = { |
| 1866 | "XRotation": round(rng.uniform(-35.0, 35.0), 1), |
| 1867 | "YRotation": round(rng.uniform(-35.0, 35.0), 1), |
| 1868 | "ZRotation": round(rng.uniform(-25.0, 25.0), 1), |
| 1869 | "ZMove": round(rng.uniform(0.95, 1.6), 2), |
| 1870 | "Pivot": (round(rng.uniform(0.3, 0.7), 2), round(rng.uniform(0.3, 0.7), 2)), |
| 1871 | "Center": (round(rng.uniform(0.4, 0.6), 2), round(rng.uniform(0.4, 0.6), 2)), |
| 1872 | "Blend": blend, |
| 1873 | } |
| 1874 | elif kind == "CornerPositioner": |
| 1875 | params = { |
| 1876 | "TopLeft": (round(rng.uniform(0.05, 0.28), 3), round(rng.uniform(0.72, 0.95), 3)), |
| 1877 | "TopRight": (round(rng.uniform(0.72, 0.95), 3), round(rng.uniform(0.72, 0.95), 3)), |
| 1878 | "BottomLeft": (round(rng.uniform(0.05, 0.28), 3), round(rng.uniform(0.05, 0.28), 3)), |
| 1879 | "BottomRight": (round(rng.uniform(0.72, 0.95), 3), round(rng.uniform(0.05, 0.28), 3)), |
| 1880 | "Blend": blend, |
| 1881 | } |
| 1882 | elif kind == "Displace": |
| 1883 | sec_port = "Foreground" |
| 1884 | sec_src = src_b |
| 1885 | dtype = rng.choice([0, 1]) |
| 1886 | if dtype == 0: |
| 1887 | params = { |
| 1888 | "Type": 0, |
| 1889 | "RefractionStrength": round(rng.uniform(0.04, 0.16), 3), |
| 1890 | "Spread": round(rng.uniform(0.0, 0.35), 2), |
| 1891 | "LightPower": round(rng.uniform(0.0, 0.6), 2), |
| 1892 | "Blend": blend, |
| 1893 | } |
| 1894 | else: |
| 1895 | params = { |
| 1896 | "Type": 1, |
| 1897 | "XChannel": rng.choice([0, 1, 2]), |
| 1898 | "YChannel": rng.choice([0, 1, 2]), |
| 1899 | "XOffset": -0.5, |
| 1900 | "YOffset": -0.5, |
| 1901 | "XRefraction": round(rng.uniform(-0.12, 0.12), 3), |
| 1902 | "YRefraction": round(rng.uniform(-0.12, 0.12), 3), |
| 1903 | "Blend": blend, |
| 1904 | } |
| 1905 | elif kind == "Vortex": |
| 1906 | params = { |
| 1907 | "Center": (round(rng.uniform(0.35, 0.65), 2), round(rng.uniform(0.35, 0.65), 2)), |
| 1908 | "Size": round(rng.uniform(0.35, 1.2), 2), |
| 1909 | "Angle": round(rng.uniform(-2.5, 2.5), 2), |
| 1910 | "Power": round(rng.uniform(0.8, 3.0), 2), |
| 1911 | "Blend": blend, |
| 1912 | } |
| 1913 | elif kind == "Drip": |
| 1914 | params = { |
| 1915 | "Center": (round(rng.uniform(0.35, 0.65), 2), round(rng.uniform(0.35, 0.65), 2)), |
| 1916 | "Strength": round(rng.uniform(0.4, 1.0), 2), |
| 1917 | "Amplitude": round(rng.uniform(0.04, 0.14), 3), |
| 1918 | "Frequency": round(rng.uniform(2.0, 7.0), 1), |
| 1919 | "Phase": round(rng.uniform(0.0, 1.0), 2), |
| 1920 | "Shape": rng.choice([0, 1]), |
| 1921 | "Blend": blend, |
| 1922 | } |
| 1923 | elif kind == "Dent": |
| 1924 | params = { |
| 1925 | "Center": (round(rng.uniform(0.35, 0.65), 2), round(rng.uniform(0.35, 0.65), 2)), |
| 1926 | "Size": round(rng.uniform(0.35, 0.85), 2), |
| 1927 | "Strength": round(rng.uniform(0.3, 0.9), 2), |
| 1928 | "Type": rng.choice([0, 1, 2, 3]), |
| 1929 | "Blend": blend, |
| 1930 | } |
| 1931 | elif kind == "ChangeDepth": |
| 1932 | params = {"Depth": rng.choice([1, 2, 3, 4])} |
| 1933 | elif kind == "GamutConvert": |
| 1934 | params = { |
| 1935 | "SourceSpace": ("FuID", rng.choice(["NoChange", "sRGB", "Rec709"])), |
| 1936 | "OutputSpace": ("FuID", rng.choice(["NoChange", "sRGB", "Rec709"])), |
| 1937 | "RemoveGamma": rng.choice([0, 1]), |
| 1938 | "AddGamma": rng.choice([0, 1]), |
| 1939 | "PreDividePostMultiply": rng.choice([0, 1]), |
| 1940 | "Blend": blend, |
| 1941 | } |
| 1942 | elif kind == "ColorGain": |
| 1943 | params = { |
| 1944 | "GainRed": round(rng.uniform(0.6, 1.5), 2), |
| 1945 | "GainGreen": round(rng.uniform(0.6, 1.5), 2), |
| 1946 | "GainBlue": round(rng.uniform(0.6, 1.5), 2), |
| 1947 | "LiftGreen": round(rng.uniform(-0.1, 0.15), 2), |
| 1948 | "GammaBlue": round(rng.uniform(0.7, 1.4), 2), |
| 1949 | "MidHue": round(rng.uniform(0.1, 0.9), 2), |
| 1950 | "PreDividePostMultiply": rng.choice([0, 1]), |
| 1951 | "Blend": blend, |
| 1952 | } |
| 1953 | elif kind == "Custom": |
| 1954 | prim_port = "Image1" |
| 1955 | sec_port = "Image2" |
| 1956 | sec_src = src_b |
| 1957 | params = { |
| 1958 | "NumberIn1": round(rng.uniform(0.3, 0.8), 2), |
| 1959 | "PointIn1": (round(rng.uniform(0.3, 0.7), 2), round(rng.uniform(0.3, 0.7), 2)), |
| 1960 | "Setup1": "1 - n1", |
| 1961 | "Intermediate1": "max(0, 1 - dist(x, y, p1x, p1y) * 1.8)", |
| 1962 | "RedExpression": "if(x > p1x, getr1b(x - 0.08, y) * i1 + r2 * s1, r1)", |
| 1963 | "GreenExpression": "g1 * (1 - i1) + g2 * i1", |
| 1964 | "BlueExpression": "b1 * n1 + b2 * (1 - n1)", |
| 1965 | "AlphaExpression": "a1", |
| 1966 | "Blend": blend, |
| 1967 | } |
| 1968 | |
| 1969 | nodes.append( |
| 1970 | DagNode( |
| 1971 | name=nname, |
| 1972 | kind=kind, |
| 1973 | is_source=False, |
| 1974 | primary_port=prim_port, |
| 1975 | primary_src=src_a, |
| 1976 | secondary_port=sec_port, |
| 1977 | secondary_src=sec_src, |
| 1978 | params=params, |
| 1979 | mask=mask, |
| 1980 | ) |
| 1981 | ) |
| 1982 | |
| 1983 | return FuzzGraph(seed=seed, eval_frame=eval_frame, nodes=nodes) |
| 1984 | |
| 1985 | |
| 1986 | def write_standalone_graph_comp(graph: FuzzGraph, prefix: str) -> Path: |
| 1987 | root = ensure_dirs() |
| 1988 | tool_blocks, aux_blocks, out_op = graph.to_lua_defs(prefix="", frame_shift=0) |
| 1989 | # Normalize over BlackBG so Saver compares RGB over opaque black consistently |
| 1990 | tool_blocks.append('\t\t_BlackBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftAlpha = Input { Value = 1, }, }, },') |
| 1991 | tool_blocks.append(f'\t\t_NormOut = Merge {{ Inputs = {{ Background = Input {{ SourceOp = "_BlackBG", Source = "Output", }}, Foreground = Input {{ SourceOp = "{out_op}", Source = "Output", }}, }}, }},') |
| 1992 | tool_blocks.append(make_saver("_NormOut", prefix)) |
| 1993 | comp_path = root / "comps" / f"{prefix}.comp" |
| 1994 | comp_path.write_text(make_comp("\n".join(tool_blocks + aux_blocks), graph.eval_frame, start_frame=graph.eval_frame)) |
| 1995 | return comp_path |
| 1996 | |
| 1997 | |
| 1998 | def run_multi_graph_batch( |
| 1999 | items: List[Tuple[str, FuzzGraph]], |
| 2000 | batch_prefix: str, |
| 2001 | render_gt: bool = True, |
| 2002 | timeout_sec: int = 180, |
| 2003 | ) -> Dict[int, Dict[str, Any]]: |
| 2004 | """Packs multiple FuzzGraphs into one multi-frame .comp using a Merge switch chain.""" |
| 2005 | root = ensure_dirs() |
| 2006 | all_tools = [ |
| 2007 | '\t\t_BlackBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, TopLeftAlpha = Input { Value = 1, }, }, },' |
| 2008 | ] |
| 2009 | all_aux: List[str] = [] |
| 2010 | cases: List[Tuple[int, str, str]] = [] |
| 2011 | labels: Dict[int, str] = {} |
| 2012 | |
| 2013 | for f_idx, (label, g) in enumerate(items): |
| 2014 | pfx = f"G{f_idx}_" |
| 2015 | frame_shift = f_idx - g.eval_frame |
| 2016 | tb, ab, out_op = g.to_lua_defs(prefix=pfx, frame_shift=frame_shift) |
| 2017 | all_tools.extend(tb) |
| 2018 | all_aux.extend(ab) |
| 2019 | cases.append((f_idx, label, out_op)) |
| 2020 | labels[f_idx] = label |
| 2021 | |
| 2022 | sw_nodes, sw_splines, final_op = build_switch_chain(cases, "_BlackBG", "FB") |
| 2023 | all_tools.extend(sw_nodes) |
| 2024 | all_aux.extend(sw_splines) |
| 2025 | all_tools.append(make_saver(final_op, batch_prefix)) |
| 2026 | |
| 2027 | comp_path = root / "comps" / f"{batch_prefix}.comp" |
| 2028 | comp_path.write_text(make_comp("\n".join(all_tools + all_aux), len(cases) - 1, start_frame=0)) |
| 2029 | return run_comp_both( |
| 2030 | comp_path, |
| 2031 | batch_prefix, |
| 2032 | list(range(len(cases))), |
| 2033 | labels, |
| 2034 | render_gt=render_gt, |
| 2035 | timeout_sec=timeout_sec, |
| 2036 | ) |
| 2037 | |
| 2038 | |
| 2039 | def bisect_failing_graph( |
| 2040 | graph: FuzzGraph, |
| 2041 | threshold_pct: float, |
| 2042 | render_gt: bool = True, |
| 2043 | timeout_sec: int = 180, |
| 2044 | ) -> Dict[str, Any]: |
| 2045 | """Node-by-node graph bisection that trims downstream & upstream nodes while preserving MAE > threshold.""" |
| 2046 | seed = graph.seed |
| 2047 | print(f" [bisect] seed={seed} ({len(graph.nodes)} nodes) ...", flush=True) |
| 2048 | |
| 2049 | # Step 0: Verify standalone reproduction |
| 2050 | st_prefix = f"bisect_s{seed}_orig" |
| 2051 | st_comp = write_standalone_graph_comp(graph, st_prefix) |
| 2052 | st_res = run_comp_both( |
| 2053 | st_comp, st_prefix, [graph.eval_frame], {graph.eval_frame: f"seed_{seed}"}, render_gt=render_gt, timeout_sec=timeout_sec |
| 2054 | )[graph.eval_frame] |
| 2055 | orig_mae = st_res["mae_pct"] |
| 2056 | if orig_mae <= threshold_pct: |
| 2057 | return { |
| 2058 | "seed": seed, |
| 2059 | "reproduced_standalone": False, |
| 2060 | "orig_mae_pct": orig_mae, |
| 2061 | "min_mae_pct": orig_mae, |
| 2062 | "min_rmse_255": st_res["rmse_255"], |
| 2063 | "note": "batch failure did not reproduce standalone", |
| 2064 | "tools": graph.summary_tools(), |
| 2065 | } |
| 2066 | |
| 2067 | # Step 1: Prefix trim (find earliest failing sink node in topological order) |
| 2068 | non_src = [n for n in graph.nodes if not n.is_source] |
| 2069 | cur = graph.clone() |
| 2070 | if len(non_src) > 1: |
| 2071 | prefix_items = [(f"prefix_{nd.name}", graph.prune_to(nd.name)) for nd in non_src] |
| 2072 | pref_res = run_multi_graph_batch( |
| 2073 | prefix_items, f"bisect_s{seed}_prefixes", render_gt=render_gt, timeout_sec=timeout_sec |
| 2074 | ) |
| 2075 | for idx, nd in enumerate(non_src): |
| 2076 | if pref_res[idx]["mae_pct"] > threshold_pct: |
| 2077 | cur = graph.prune_to(nd.name) |
| 2078 | print(f" [prefix] trimmed sink to {nd.name} ({len(cur.nodes)} nodes, MAE={pref_res[idx]['mae_pct']:.2f}%)", flush=True) |
| 2079 | break |
| 2080 | |
| 2081 | # Step 2: Iterative upstream node & mask removal + spline flattening |
| 2082 | for rnd in range(6): |
| 2083 | candidates: List[Tuple[str, str, FuzzGraph]] = [] # (desc, action, candidate_graph) |
| 2084 | # Try flattening splines first |
| 2085 | flat = cur.flatten_splines() |
| 2086 | if flat is not None: |
| 2087 | candidates.append(("flatten_splines", "flatten", flat)) |
| 2088 | # Try stripping masks |
| 2089 | for nd in cur.nodes: |
| 2090 | if nd.mask is not None: |
| 2091 | sm = cur.strip_mask(nd.name) |
| 2092 | if sm is not None: |
| 2093 | candidates.append((f"strip_mask:{nd.name}", "mask", sm)) |
| 2094 | # Try bypassing each upstream non-source node |
| 2095 | for nd in cur.nodes: |
| 2096 | if not nd.is_source and nd.name != cur.output_node(): |
| 2097 | bp = cur.bypass_node(nd.name) |
| 2098 | if bp is not None: |
| 2099 | candidates.append((f"bypass:{nd.name}", "bypass", bp)) |
| 2100 | |
| 2101 | if not candidates: |
| 2102 | break |
| 2103 | |
| 2104 | batch_items = [(desc, cg) for desc, _act, cg in candidates] |
| 2105 | cand_res = run_multi_graph_batch( |
| 2106 | batch_items, f"bisect_s{seed}_r{rnd}", render_gt=render_gt, timeout_sec=timeout_sec |
| 2107 | ) |
| 2108 | |
| 2109 | # Pick best failing candidate: fewest nodes, fewest masks, no splines |
| 2110 | failing: List[Tuple[Tuple[int, int, int], str, FuzzGraph, float]] = [] |
| 2111 | for idx, (desc, _act, cg) in enumerate(candidates): |
| 2112 | m = cand_res[idx] |
| 2113 | if m["mae_pct"] > threshold_pct: |
| 2114 | mask_cnt = sum(1 for x in cg.nodes if x.mask is not None) |
| 2115 | spline_cnt = sum( |
| 2116 | 1 for x in cg.nodes for v in x.params.values() if isinstance(v, SplineParam) |
| 2117 | ) |
| 2118 | score = (len(cg.nodes), mask_cnt, spline_cnt) |
| 2119 | failing.append((score, desc, cg, m["mae_pct"])) |
| 2120 | |
| 2121 | if not failing: |
| 2122 | break |
| 2123 | failing.sort(key=lambda t: t[0]) |
| 2124 | _score, best_desc, best_cg, best_mae = failing[0] |
| 2125 | cur = best_cg |
| 2126 | print(f" [round {rnd}] {best_desc} -> {len(cur.nodes)} nodes (MAE={best_mae:.2f}%)", flush=True) |
| 2127 | |
| 2128 | # Step 3: Standalone verification of minimal reproducer |
| 2129 | repro_prefix = f"repro_seed_{seed}" |
| 2130 | repro_comp = write_standalone_graph_comp(cur, repro_prefix) |
| 2131 | final_res = run_comp_both( |
| 2132 | repro_comp, repro_prefix, [cur.eval_frame], {cur.eval_frame: repro_prefix}, render_gt=render_gt, timeout_sec=timeout_sec |
| 2133 | )[cur.eval_frame] |
| 2134 | |
| 2135 | return { |
| 2136 | "seed": seed, |
| 2137 | "reproduced_standalone": True, |
| 2138 | "orig_node_count": len(graph.nodes), |
| 2139 | "min_node_count": len(cur.nodes), |
| 2140 | "orig_mae_pct": orig_mae, |
| 2141 | "min_mae_pct": final_res["mae_pct"], |
| 2142 | "min_rmse_255": final_res["rmse_255"], |
| 2143 | "comp_path": str(repro_comp), |
| 2144 | "eval_frame": cur.eval_frame, |
| 2145 | "tools": cur.summary_tools(), |
| 2146 | } |
| 2147 | |
| 2148 | |
| 2149 | # --------------------------------------------------------------------------- |
| 2150 | # CLI & Main Entrypoint |
| 2151 | # --------------------------------------------------------------------------- |
| 2152 | |
| 2153 | |
| 2154 | def print_table(title: str, rows: List[Dict[str, Any]], threshold_pct: float) -> None: |
| 2155 | print(f"\n=== {title} ===") |
| 2156 | print(f" {'Case':<44s} | {'MAE%':>7s} | {'MAE':>6s} | {'RMSE':>6s} | {'Status'}") |
| 2157 | print(f" {'-'*44}-+-{'-'*7}-+-{'-'*6}-+-{'-'*6}-+-{'-'*18}") |
| 2158 | for r in rows: |
| 2159 | label = str(r.get("label", ""))[:44] |
| 2160 | mae_pct = r.get("mae_pct", 100.0) |
| 2161 | mae = r.get("mae_255", 255.0) |
| 2162 | rmse = r.get("rmse_255", 255.0) |
| 2163 | if r.get("error"): |
| 2164 | status = f"ERR: {str(r['error'])[:28]}" |
| 2165 | elif r.get("size_mismatch"): |
| 2166 | status = f"SIZE {r.get('dims_ours')}!={r.get('dims_gt')}" |
| 2167 | elif mae_pct > threshold_pct: |
| 2168 | status = "FAIL" |
| 2169 | else: |
| 2170 | status = "PASS" |
| 2171 | print(f" {label:<44s} | {mae_pct:6.2f}% | {mae:6.2f} | {rmse:6.2f} | {status}") |
| 2172 | |
| 2173 | |
| 2174 | def main() -> int: |
| 2175 | parser = argparse.ArgumentParser(description="Fusion 21.1 vs Fission differential matrix & DAG fuzzer") |
| 2176 | parser.add_argument("--matrix", action="store_true", help="Run all edge-case parameter matrix suites") |
| 2177 | parser.add_argument("--suite", action="append", default=[], help="Specific matrix suite(s) to run") |
| 2178 | parser.add_argument("--fuzz", action="store_true", help="Run seeded randomized DAG fuzzer") |
| 2179 | parser.add_argument("--seeds", type=int, default=20, help="Number of random seeds to fuzz (default 20)") |
| 2180 | parser.add_argument("--seed-start", type=int, default=1, help="Starting seed integer (default 1)") |
| 2181 | parser.add_argument("--bisect", action="store_true", help="Auto-bisect failing fuzz seeds (> threshold MAE%)") |
| 2182 | parser.add_argument("--threshold", type=float, default=1.5, help="MAE%% failure threshold (default 1.5)") |
| 2183 | parser.add_argument("--batch-size", type=int, default=15, help="Seeds per batched Fusion render (default 15)") |
| 2184 | parser.add_argument("--timeout", type=int, default=180, help="Per-render timeout in seconds (default 180)") |
| 2185 | parser.add_argument("--no-gt", action="store_true", help="Skip sg render and reuse existing GT PNGs") |
| 2186 | parser.add_argument("--report-json", type=str, default="", help="Write structured JSON report to path") |
| 2187 | args = parser.parse_args() |
| 2188 | |
| 2189 | if not args.matrix and not args.fuzz: |
| 2190 | parser.print_help() |
| 2191 | return 1 |
| 2192 | |
| 2193 | assets = generate_assets() |
| 2194 | report: Dict[str, Any] = { |
| 2195 | "threshold_pct": args.threshold, |
| 2196 | "matrix": {}, |
| 2197 | "fuzz": {"seeds": [], "bisected": []}, |
| 2198 | } |
| 2199 | |
| 2200 | if args.matrix: |
| 2201 | suites = args.suite if args.suite else list(MATRIX_BUILDERS.keys()) |
| 2202 | for sname in suites: |
| 2203 | if sname not in MATRIX_BUILDERS: |
| 2204 | print(f"Unknown matrix suite: {sname}", file=sys.stderr) |
| 2205 | return 2 |
| 2206 | comp_path, prefix, cases = MATRIX_BUILDERS[sname](assets) |
| 2207 | frames = [c[0] for c in cases] |
| 2208 | labels = {c[0]: c[1] for c in cases} |
| 2209 | res = run_comp_both( |
| 2210 | comp_path, |
| 2211 | prefix, |
| 2212 | frames, |
| 2213 | labels, |
| 2214 | render_gt=not args.no_gt, |
| 2215 | timeout_sec=args.timeout, |
| 2216 | ) |
| 2217 | rows = [res[f] for f in frames] |
| 2218 | print_table(sname, rows, args.threshold) |
| 2219 | fails = [r for r in rows if r.get("mae_pct", 100.0) > args.threshold or r.get("size_mismatch") or r.get("error")] |
| 2220 | mean_mae = sum(r["mae_pct"] for r in rows) / max(1, len(rows)) |
| 2221 | report["matrix"][sname] = { |
| 2222 | "total": len(rows), |
| 2223 | "passed": len(rows) - len(fails), |
| 2224 | "failed": len(fails), |
| 2225 | "mean_mae_pct": round(mean_mae, 4), |
| 2226 | "cases": rows, |
| 2227 | } |
| 2228 | |
| 2229 | if args.fuzz: |
| 2230 | seed_ids = list(range(args.seed_start, args.seed_start + args.seeds)) |
| 2231 | graphs = {s: generate_random_dag(s, assets) for s in seed_ids} |
| 2232 | fuzz_rows: List[Dict[str, Any]] = [] |
| 2233 | |
| 2234 | for chunk_idx in range(0, len(seed_ids), args.batch_size): |
| 2235 | chunk = seed_ids[chunk_idx : chunk_idx + args.batch_size] |
| 2236 | batch_items = [(f"seed_{s}_n{len(graphs[s].nodes)}", graphs[s]) for s in chunk] |
| 2237 | batch_prefix = f"fuzz_batch_{chunk[0]}_{chunk[-1]}" |
| 2238 | res = run_multi_graph_batch( |
| 2239 | batch_items, |
| 2240 | batch_prefix, |
| 2241 | render_gt=not args.no_gt, |
| 2242 | timeout_sec=args.timeout, |
| 2243 | ) |
| 2244 | # If the whole batch errored in sg render, fall back to individual seed renders |
| 2245 | batch_errored = all(res[i].get("error") for i in range(len(chunk))) |
| 2246 | if batch_errored: |
| 2247 | print(f"[warn] Batch {batch_prefix} errored; falling back to per-seed renders...", file=sys.stderr) |
| 2248 | for s in chunk: |
| 2249 | g = graphs[s] |
| 2250 | sp = f"fuzz_seed_{s}" |
| 2251 | sc = write_standalone_graph_comp(g, sp) |
| 2252 | sr = run_comp_both( |
| 2253 | sc, sp, [g.eval_frame], {g.eval_frame: f"seed_{s}_n{len(g.nodes)}"}, |
| 2254 | render_gt=not args.no_gt, timeout_sec=args.timeout, |
| 2255 | )[g.eval_frame] |
| 2256 | sr["seed"] = s |
| 2257 | sr["tools"] = [n.kind for n in g.nodes if not n.is_source] |
| 2258 | fuzz_rows.append(sr) |
| 2259 | else: |
| 2260 | for i, s in enumerate(chunk): |
| 2261 | r = res[i] |
| 2262 | r["seed"] = s |
| 2263 | r["tools"] = [n.kind for n in graphs[s].nodes if not n.is_source] |
| 2264 | fuzz_rows.append(r) |
| 2265 | |
| 2266 | print_table(f"fuzz seeds {args.seed_start}..{args.seed_start + args.seeds - 1}", fuzz_rows, args.threshold) |
| 2267 | report["fuzz"]["seeds"] = fuzz_rows |
| 2268 | |
| 2269 | if args.bisect: |
| 2270 | 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"))] |
| 2271 | print(f"\n=== Bisecting {len(failing_seeds)} failing seeds (MAE > {args.threshold}%) ===") |
| 2272 | for r in failing_seeds: |
| 2273 | s = r["seed"] |
| 2274 | try: |
| 2275 | b_res = bisect_failing_graph( |
| 2276 | graphs[s], |
| 2277 | threshold_pct=args.threshold, |
| 2278 | render_gt=not args.no_gt, |
| 2279 | timeout_sec=args.timeout, |
| 2280 | ) |
| 2281 | report["fuzz"]["bisected"].append(b_res) |
| 2282 | except Exception as exc: |
| 2283 | print(f" [bisect] seed={s} exception: {exc}", file=sys.stderr) |
| 2284 | report["fuzz"]["bisected"].append({"seed": s, "error": str(exc)}) |
| 2285 | |
| 2286 | if args.report_json: |
| 2287 | rp = Path(args.report_json) |
| 2288 | rp.parent.mkdir(parents=True, exist_ok=True) |
| 2289 | rp.write_text(json.dumps(report, indent=2)) |
| 2290 | print(f"\n[report] Wrote JSON summary to {rp}") |
| 2291 | |
| 2292 | return 0 |
| 2293 | |
| 2294 | |
| 2295 | if __name__ == "__main__": |
| 2296 | raise SystemExit(main()) |