| 1 | #!/usr/bin/env python3 |
| 2 | """Generic per-node fuzzer: Fusion 21.1 (`sg render`) vs Fission (`render-check`), driven by tool_catalog.json. |
| 3 | |
| 4 | For one tool, builds a multi-frame comp where frame 0 uses every default and frames 1..N-1 each |
| 5 | instantiate the tool with a deterministic stratified variation of its catalog inputs; a Switch picks |
| 6 | instance `f` at frame `f`. Scores `accuracy = max(0, 100 - mae_pct)` per frame into accuracy_ledger.json. |
| 7 | |
| 8 | python3 scripts/fuzz_node.py --tool Blur --frames 12 |
| 9 | python3 scripts/fuzz_node.py --category "Color & Depth" |
| 10 | python3 scripts/fuzz_node.py --all |
| 11 | """ |
| 12 | |
| 13 | from __future__ import annotations |
| 14 | |
| 15 | import argparse |
| 16 | import hashlib |
| 17 | import json |
| 18 | import os |
| 19 | import random |
| 20 | import re |
| 21 | import subprocess |
| 22 | import sys |
| 23 | import time |
| 24 | from datetime import datetime, timezone |
| 25 | from pathlib import Path |
| 26 | from typing import Any, Dict, List, Optional, Sequence, Tuple |
| 27 | |
| 28 | SCRIPTS = Path(__file__).resolve().parent |
| 29 | sys.path.insert(0, str(SCRIPTS)) |
| 30 | |
| 31 | import diff_fuzz.assets as assets # noqa: E402 |
| 32 | from diff_fuzz.assets import CONTAINER_ROOT, generate_assets, linear_spline, make_comp, make_loader, make_saver, step_spline # noqa: E402 |
| 33 | from diff_fuzz.runner import alpha_mae_pct, run_comp_both # noqa: E402 |
| 34 | from gen_compatibility import TOOL_METADATA # noqa: E402 |
| 35 | |
| 36 | CATALOG = SCRIPTS / "tool_catalog.json" |
| 37 | LEDGER = SCRIPTS / "accuracy_ledger.json" |
| 38 | PREBUILT_RENDER_CHECK = Path(os.environ.get("FISSION_RENDER_CHECK", "/Users/clo/dev/compositor/target/release/render-check")) |
| 39 | if PREBUILT_RENDER_CHECK.exists(): |
| 40 | assets.RENDER_CHECK = PREBUILT_RENDER_CHECK |
| 41 | |
| 42 | SIZE = 256 |
| 43 | FRAME_TIMEOUT = 20 |
| 44 | GOLDEN = 0.6180339887498949 |
| 45 | |
| 46 | |
| 47 | class FuID(str): |
| 48 | pass |
| 49 | |
| 50 | |
| 51 | # Tools the generic wiring cannot drive yet, with the reason recorded in the ledger. |
| 52 | UNSUPPORTED_RIG = { |
| 53 | "Loader": "needs a footage clip; every probe already exercises it", |
| 54 | "Saver": "output node; every probe already exercises it", |
| 55 | "Switch": "routing node; used by the fuzzer itself", |
| 56 | "Fuse.Switch": "routing node; used by the fuzzer itself", |
| 57 | "MacroOperator": "container node with no inputs of its own", |
| 58 | "GroupOperator": "container node with no inputs of its own", |
| 59 | "Tracker": "needs tracked footage", |
| 60 | "Fuse.Cryptomatte": "needs cryptomatte object-ID metadata", |
| 61 | "Dimension.OpticalFlow": "needs auxiliary vector channels", |
| 62 | "Dimension.CopyAux": "needs auxiliary channels", |
| 63 | "Paint": "needs painted strokes", |
| 64 | "PolylineStroke": "needs painted strokes", |
| 65 | "Multistroke": "needs painted strokes", |
| 66 | "PaintMask": "needs painted strokes", |
| 67 | "SurfaceFBXMesh": "needs a mesh file", |
| 68 | "GridWarp": "needs mesh-point data", |
| 69 | } |
| 70 | UNRIGGED_DOMAINS = ("DataType3D", "MtlGraph3D", "Particles") |
| 71 | RIGS = { |
| 72 | "scene": { |
| 73 | "Bender3D", "Camera3D", "Cube3D", "Displace3D", "Duplicate3D", "Fog3D", "ImagePlane3D", "LightAmbient", "LightDirectional", "LightDome", |
| 74 | "LightPoint", "LightSpot", "Locator3D", "Merge3D", "Override3D", "Renderer3D", "ReplaceMaterial3D", "ReplaceNormals3D", "Replicate3D", |
| 75 | "Ribbon3D", "Shape3D", "Text3D", "Transform3D", "Triangulate3D", "UVMap", "Weld3D", |
| 76 | }, |
| 77 | "material": { |
| 78 | "MtlBlinn", "MtlPhong", "MtlCookTorrance", "MtlWard", "MtlReflect", "MtlChanBool", "MtlMerge3D", "MtlPBRUber", "MtlStereoMix3D", |
| 79 | "SphereMap", "CubeMap", "FalloffOperator", "FastNoiseTexture3D", "TexCatcher", "TexGradient", |
| 80 | "BumpMap", "Texture2DOperator", "TextureTransformOperator", |
| 81 | }, |
| 82 | "particle": { |
| 83 | "pEmitter", "pRender", "pMerge", "pDirectionalForce", "pDrag", "pTurbulence", "pPointForce", "pBounce", "pKill", |
| 84 | "pVortex", "pFlock", "pSpawn", "pChangeStyle", "pGradientForce", |
| 85 | "pAvoid", "pCustom", "pCustomForce", "pFollow", "pImageEmitter", "pTangentForce", |
| 86 | }, |
| 87 | "time": {"TimeSpeed", "TimeStretcher"}, |
| 88 | } |
| 89 | |
| 90 | SLIDER_CONTROLS = { |
| 91 | "SliderControl", "ScrewControl", "RangeControl", "ColorControl", "LevelsControl", "LevelsOutputControl", |
| 92 | "ColorWheelControl", "ColorSuppressionControl", None, |
| 93 | } |
| 94 | CHOICE_CONTROLS = {"CheckboxControl", "MultiButtonControl", "MultiButtonIDControl", "ComboControl", "ComboIDControl"} |
| 95 | # Inputs whose variation tests plumbing the engine intentionally lacks, that resize the frame, or that need |
| 96 | # data the rigs lack (Renderer3D deep output, Displace3D camera, TimeSpeed/TimeStretcher optical flow: Fusion fails the frame). |
| 97 | DENY_IDS = { |
| 98 | "MotionBlur", "ShutterAngle", "CenterBias", "SampleSpread", "UseGPU", "HideInputs", "HiQOnly", |
| 99 | "Width", "Height", "PixelAspect", "Depth", "UseFrameFormatSettings", "AutoResolution", "ProcessMode", |
| 100 | "UseObject", "UseMaterial", "ObjectID", "MaterialID", "CorrectEdges", "ProxyScale", "MaskWidth", "MaskHeight", |
| 101 | "RendererType", "OutputType", "PointCamera", "InterpolateBetweenFrames", |
| 102 | } |
| 103 | # TimeSpeed fails the frame in Fusion once a reversed Speed reaches ~-24 frames of source time. |
| 104 | INPUT_RANGES = {("TimeSpeed", "Speed"): (-2.0, 3.0)} |
| 105 | DENY_PREFIXES = ("Gamut.", "ProcessLayers", "Comments", "Layer", "Motion", "Reset", "Stereo", "EnableWarp.") |
| 106 | DENY_SUFFIXES = ("_LayerSelect", "Nest", "Notify") |
| 107 | MASK_IDS = ("ApplyMaskInverted", "MultiplyByMask", "FitMask", "MaskChannel", "MaskLow", "MaskHigh", "MaskClipBlack", "MaskClipWhite") |
| 108 | IMAGE_INPUT_IDS = ("Input", "Background", "Foreground", "Image", "Source", "Image1", "Image2", "Image3", "BlurImage") |
| 109 | # Renderer3D pinned to OpenGL: the catalog only lists RendererSoftware.* inputs, whose lighting toggles are remapped in `rig_frame`. |
| 110 | RENDERER3D = { |
| 111 | "Width": SIZE, "Height": SIZE, "RendererType": FuID("RendererOpenGL"), |
| 112 | "RendererOpenGL.LightingEnabled": 1, "RendererOpenGL.ShadowsEnabled": 1, |
| 113 | } |
| 114 | EMITTER = {"RandomSeed": 42, "Style": FuID("ParticleStyleBlob"), "Number": 20, "Velocity": 0.05} |
| 115 | PRENDER = {"OutputMode": FuID("TwoD"), "Width": SIZE, "Height": SIZE} |
| 116 | TOOL_OVERRIDES: Dict[str, Dict[str, Any]] = { |
| 117 | "TextPlus": {"StyledText": "Fission", "Size": 0.12}, |
| 118 | "Text3D": {"StyledText": "FISSION", "Font": "Open Sans", "Size": 0.25}, |
| 119 | "Renderer3D": RENDERER3D, |
| 120 | "Camera3D": {"Transform3DOp.Translate.Z": 3.0}, |
| 121 | "LightPoint": {"Transform3DOp.Translate.X": 1.2, "Transform3DOp.Translate.Y": 2.0, "Transform3DOp.Translate.Z": 2.0}, |
| 122 | "LightSpot": {"Transform3DOp.Translate.Y": 2.0, "Transform3DOp.Translate.Z": 3.0, "Transform3DOp.Rotate.X": -35.0}, |
| 123 | "LightDirectional": {"Transform3DOp.Rotate.X": -40.0, "Transform3DOp.Rotate.Y": 25.0}, |
| 124 | "pEmitter": EMITTER, |
| 125 | "pRender": PRENDER, |
| 126 | } |
| 127 | # Image-slot a texture plugs into on tools that otherwise render untextured. |
| 128 | TEXTURE_SLOT = {"Shape3D": "MaterialInput", "ImagePlane3D": "MaterialInput", "Cube3D": "FrontMaterialInput"} |
| 129 | |
| 130 | |
| 131 | def lua_key(name: str) -> str: |
| 132 | return name if re.fullmatch(r"[A-Za-z_]\w*", name) else f'["{name}"]' |
| 133 | |
| 134 | |
| 135 | def lua_val(v: Any) -> str: |
| 136 | if isinstance(v, FuID): |
| 137 | return f'FuID {{ "{v}" }}' |
| 138 | if isinstance(v, str): |
| 139 | return json.dumps(v) |
| 140 | if isinstance(v, (list, tuple)): |
| 141 | return "{ " + ", ".join(lua_val(x) for x in v) + " }" |
| 142 | if isinstance(v, bool): |
| 143 | return "1" if v else "0" |
| 144 | if isinstance(v, float): |
| 145 | return repr(round(v, 6)) |
| 146 | return str(v) |
| 147 | |
| 148 | |
| 149 | def op_block(name: str, kind: str, inputs: Dict[str, Any], links: Dict[str, Tuple[str, str]]) -> str: |
| 150 | rows = [f"\t\t\t\t{lua_key(k)} = Input {{ Value = {lua_val(v)}, }}," for k, v in inputs.items()] |
| 151 | rows += [f'\t\t\t\t{lua_key(k)} = Input {{ SourceOp = "{op}", Source = "{src}", }},' for k, (op, src) in links.items()] |
| 152 | return f"\t\t{name} = {kind} {{\n\t\t\tInputs = {{\n" + "\n".join(rows) + "\n\t\t\t},\n\t\t}," |
| 153 | |
| 154 | |
| 155 | def unit(tool: str, input_id: str, k: int) -> float: |
| 156 | """Deterministic low-discrepancy sample in [0.04, 0.96] per (tool, input, frame).""" |
| 157 | phase = int.from_bytes(hashlib.sha256(f"{tool}/{input_id}".encode()).digest()[:4], "big") / 2**32 |
| 158 | return 0.04 + 0.92 * ((phase + k * GOLDEN) % 1.0) |
| 159 | |
| 160 | |
| 161 | def switch_tree(leaves: List[str]) -> Tuple[str, List[str], List[str]]: |
| 162 | """Binary tree of 2-input Switches: frame f descends via bit L of f. Fusion's Switch only exposes Input0/Input1 from a .comp.""" |
| 163 | nodes: List[str] = [] |
| 164 | splines: List[str] = [] |
| 165 | level, layer = 0, leaves |
| 166 | while len(layer) > 1: |
| 167 | sel = f"SwSel{level}" |
| 168 | splines.append(step_spline(sel, {f: float((f >> level) & 1) for f in range(len(leaves))})) |
| 169 | nxt: List[str] = [] |
| 170 | for j in range(0, len(layer), 2): |
| 171 | if j + 1 == len(layer): |
| 172 | nxt.append(layer[j]) |
| 173 | continue |
| 174 | name = f"Sw{level}_{j // 2}" |
| 175 | nodes.append(op_block(name, "Switch", {}, { |
| 176 | "Source": (sel, "Value"), "Input0": (layer[j], "Output"), "Input1": (layer[j + 1], "Output"), |
| 177 | })) |
| 178 | nxt.append(name) |
| 179 | layer, level = nxt, level + 1 |
| 180 | return layer[0], nodes, splines |
| 181 | |
| 182 | |
| 183 | class Fuzzer: |
| 184 | def __init__(self, tool: str, catalog: Dict[str, Any], frames: int): |
| 185 | self.tool = tool |
| 186 | self.spec = catalog["tools"][tool] |
| 187 | self.kind = self.spec["reg_id"] |
| 188 | self.frames = frames |
| 189 | self.inputs: Dict[str, Dict[str, Any]] = {i["id"]: i for i in self.spec["inputs"]} |
| 190 | self.in_types = {i["data_type"] for i in self.spec["inputs"] if i.get("data_type") in ("Image", "Mask", "ShapeTree", "DataType3D", "MtlGraph3D", "Particles")} |
| 191 | self.out_type = self.spec["outputs"][0].get("data_type") if self.spec["outputs"] else None |
| 192 | self.out_id = self.spec["outputs"][0]["id"] if self.spec["outputs"] else "Output" |
| 193 | self.wired_images = [i for i in IMAGE_INPUT_IDS if self.inputs.get(i, {}).get("data_type") == "Image"] |
| 194 | self.shape_inputs = [i["id"] for i in self.spec["inputs"] if i.get("data_type") == "ShapeTree"] |
| 195 | self.rig = next((r for r, tools_ in RIGS.items() if tool in tools_), None) |
| 196 | |
| 197 | def skip_reason(self) -> Optional[str]: |
| 198 | if self.tool in UNSUPPORTED_RIG: |
| 199 | return UNSUPPORTED_RIG[self.tool] |
| 200 | if self.rig is None and any(d in {self.out_type, *self.in_types} for d in UNRIGGED_DOMAINS): |
| 201 | return "no 3D/material/particle rig for this tool" |
| 202 | return None |
| 203 | |
| 204 | # ---- variation sampling ------------------------------------------------------------- |
| 205 | |
| 206 | def eligible(self, i: Dict[str, Any]) -> bool: |
| 207 | iid, dt, ic = i["id"], i.get("data_type"), i.get("input_control") |
| 208 | if iid in DENY_IDS or iid in MASK_IDS or iid == "Blend" or iid.startswith(DENY_PREFIXES) or iid.endswith(DENY_SUFFIXES): |
| 209 | return False |
| 210 | if "MotionBlur" in self.inputs and iid == "Quality": |
| 211 | return False |
| 212 | if dt == "Point" and ic == "OffsetControl": |
| 213 | return i.get("default") is not None |
| 214 | if dt == "FuID": |
| 215 | return ic in CHOICE_CONTROLS and bool(i.get("combo_entries")) |
| 216 | if dt != "Number": |
| 217 | return False |
| 218 | if ic in CHOICE_CONTROLS: |
| 219 | return True |
| 220 | return ic in SLIDER_CONTROLS and i.get("max_scale", 0) > i.get("min_scale", 0) |
| 221 | |
| 222 | def sample(self, i: Dict[str, Any], k: int) -> Any: |
| 223 | u = unit(self.tool, i["id"], k) |
| 224 | dt, ic, entries = i.get("data_type"), i.get("input_control"), i.get("combo_entries") |
| 225 | default = i.get("default") |
| 226 | if dt == "Point": |
| 227 | return [round(c + (unit(self.tool, f"{i['id']}/{axis}", k) - 0.5) * 0.6, 4) for axis, c in enumerate(default[:2])] |
| 228 | if dt == "FuID": |
| 229 | return FuID(entries[min(len(entries) - 1, int(u * len(entries)))]) |
| 230 | if ic == "CheckboxControl" or (ic == "MultiButtonControl" and (not entries or len(entries) == 1)): |
| 231 | return 1 - int(bool(default)) |
| 232 | if ic in ("ComboControl", "MultiButtonControl"): |
| 233 | if not entries: |
| 234 | return default if default is not None else 0 |
| 235 | n = len(entries) |
| 236 | alt = [x for x in range(n) if x != default] |
| 237 | return alt[int(u * len(alt)) % len(alt)] if alt else default |
| 238 | lo = max(i["min_scale"], i.get("min_allowed", -1e6)) |
| 239 | hi = min(i["max_scale"], i.get("max_allowed", 1e6)) |
| 240 | lo, hi = INPUT_RANGES.get((self.tool, i["id"]), (lo, hi)) |
| 241 | v = lo + u * (hi - lo) |
| 242 | return int(round(v)) if i.get("integer") else round(v, 5) |
| 243 | |
| 244 | def plan(self) -> List[Tuple[str, Dict[str, Any], bool]]: |
| 245 | """(label, overrides, wire_mask) per frame; frame 0 is pure defaults.""" |
| 246 | pool = [i for i in self.spec["inputs"] if self.eligible(i)] |
| 247 | random.Random(self.tool).shuffle(pool) |
| 248 | has_mask = "EffectMask" in self.inputs |
| 249 | plan: List[Tuple[str, Dict[str, Any], bool]] = [("defaults", {}, False)] |
| 250 | cursor = 0 |
| 251 | for k in range(1, self.frames): |
| 252 | ov: Dict[str, Any] = {} |
| 253 | wire = False |
| 254 | if k == 1 and "Blend" in self.inputs: |
| 255 | ov["Blend"] = round(0.15 + 0.7 * unit(self.tool, "Blend", k), 4) |
| 256 | elif k == 2 and has_mask: |
| 257 | wire = True |
| 258 | for mid in MASK_IDS: |
| 259 | mi = self.inputs.get(mid) |
| 260 | if mi and self.eligible_mask(mi): |
| 261 | ov[mid] = self.sample(mi, k) if mid != "MultiplyByMask" else 1 |
| 262 | if k == self.frames - 1 and k > 3: |
| 263 | chosen = pool[:10] |
| 264 | else: |
| 265 | m = 1 + (k % 3) |
| 266 | chosen = [pool[(cursor + j) % len(pool)] for j in range(m)] if pool else [] |
| 267 | cursor += m |
| 268 | for i in chosen: |
| 269 | ov[i["id"]] = self.sample(i, k) |
| 270 | label = ", ".join(f"{a}={b}" for a, b in ov.items()) or "defaults" |
| 271 | plan.append((("mask: " if wire else "") + label, ov, wire)) |
| 272 | return plan |
| 273 | |
| 274 | def eligible_mask(self, i: Dict[str, Any]) -> bool: |
| 275 | return i.get("data_type") in ("Number", "FuID") and i.get("input_control") in (CHOICE_CONTROLS | SLIDER_CONTROLS) |
| 276 | |
| 277 | # ---- comp construction --------------------------------------------------------------- |
| 278 | |
| 279 | def fixed_inputs(self) -> Dict[str, Any]: |
| 280 | fixed: Dict[str, Any] = dict(TOOL_OVERRIDES.get(self.tool, {})) |
| 281 | if not self.wired_images: |
| 282 | for dim in ("Width", "Height", "MaskWidth", "MaskHeight"): |
| 283 | if dim in self.inputs: |
| 284 | fixed[dim] = SIZE |
| 285 | return fixed |
| 286 | |
| 287 | def rig_shared(self) -> List[str]: |
| 288 | """Nodes every frame's rig reuses: a lit textured sphere scene, and the animated plate for the time rig.""" |
| 289 | a = ("PlateA", "Output") |
| 290 | sphere = {"Shape": FuID("SurfaceSphereInputs")} |
| 291 | t3 = lambda x=0.0, y=0.0, z=0.0: {"Transform3DOp.Translate.X": x, "Transform3DOp.Translate.Y": y, "Transform3DOp.Translate.Z": z} |
| 292 | if self.rig == "time": |
| 293 | return [ |
| 294 | linear_spline("TimeA", {0: 0.0, 48: 1.0}), |
| 295 | linear_spline("TimeB", {0: 1.0, 48: 0.0}), |
| 296 | op_block("TimeBG", "Background", { |
| 297 | "Width": SIZE, "Height": SIZE, "Type": FuID("Horizontal"), "TopLeftBlue": 0.2, "TopRightBlue": 0.2, |
| 298 | "TopLeftAlpha": 1, "TopRightAlpha": 1, |
| 299 | }, { |
| 300 | "TopLeftRed": ("TimeA", "Value"), "TopLeftGreen": ("TimeB", "Value"), |
| 301 | "TopRightRed": ("TimeB", "Value"), "TopRightGreen": ("TimeA", "Value"), |
| 302 | }), |
| 303 | ] |
| 304 | if self.rig not in ("scene", "material"): |
| 305 | return [] |
| 306 | return [ |
| 307 | op_block("Cam", "Camera3D", {"Transform3DOp.Translate.Z": 3.0}, {}), |
| 308 | op_block("Pt", "LightPoint", t3(1.5, 1.5, 3.0), {}), |
| 309 | op_block("Amb", "LightAmbient", {"Intensity": 0.25}, {}), |
| 310 | op_block("BaseDir", "LightDirectional", {"Intensity": 0.4, "Transform3DOp.Rotate.X": -30.0, "Transform3DOp.Rotate.Y": 20.0}, {}), |
| 311 | op_block("Sph", "Shape3D", sphere, {"MaterialInput": a}), |
| 312 | op_block("SphL", "Shape3D", {**sphere, "SurfaceSphereInputs.Radius": 0.5, **t3(-0.7)}, {"MaterialInput": a}), |
| 313 | op_block("BoxR", "Shape3D", {"Shape": FuID("SurfaceCubeInputs"), "SurfaceCubeInputs.Size": 0.8, **t3(0.8)}, {"MaterialInput": ("PlateB", "Output")}), |
| 314 | op_block("WSph", "Shape3D", {**sphere, "SurfaceSphereInputs.Radius": 0.5}, {}), |
| 315 | op_block("Wall", "Shape3D", {"Shape": FuID("SurfacePlaneInputs"), "SurfacePlaneInputs.Width": 6.0, "SurfacePlaneInputs.Height": 6.0, **t3(z=-0.8)}, {}), |
| 316 | op_block("Noise", "FastNoise", {"Width": SIZE, "Height": SIZE}, {}), |
| 317 | op_block("RedMtl", "MtlBlinn", {"Diffuse.Color.Red": 0.9, "Diffuse.Color.Green": 0.15, "Diffuse.Color.Blue": 0.1}, {}), |
| 318 | op_block("BaseTex", "Texture2DOperator", {}, {"Input": a}), |
| 319 | ] |
| 320 | |
| 321 | def rig_frame(self, f: int, name: str, inputs: Dict[str, Any], links: Dict[str, Tuple[str, str]]) -> Tuple[List[str], str]: |
| 322 | """Harness for one variation: tool `name` placed in its rig; returns (nodes, op feeding the Switch tree).""" |
| 323 | t, a = self.tool, ("PlateA", "Output") |
| 324 | if self.rig == "time": |
| 325 | links.update({i: ("TimeBG", "Output") for i in self.wired_images}) |
| 326 | return [op_block(name, self.kind, inputs, links)], name |
| 327 | if self.rig == "particle": |
| 328 | emitter = (f"E{f}", "Output") |
| 329 | nodes = [] if t == "pEmitter" else [op_block(emitter[0], "pEmitter", EMITTER, {})] |
| 330 | if t == "pMerge": |
| 331 | nodes.append(op_block(f"E2_{f}", "pEmitter", {**EMITTER, "RandomSeed": 7, "SphereRgn.Translate.X": 0.3}, {})) |
| 332 | links.update({"Particles1": emitter, "Particles2": (f"E2_{f}", "Output")}) |
| 333 | elif t != "pEmitter": |
| 334 | links["Input"] = emitter |
| 335 | if t == "pGradientForce" and "Bitmap" in self.inputs: |
| 336 | links["Bitmap"] = ("Noise", "Output") |
| 337 | nodes.append(op_block(name, self.kind, inputs, links)) |
| 338 | if t == "pRender": |
| 339 | return nodes, name |
| 340 | return nodes + [op_block(f"R{f}", "pRender", PRENDER, {"Input": (name, self.out_id)})], f"R{f}" |
| 341 | |
| 342 | tool_out = (name, self.out_id) |
| 343 | lit = ["Sph", "Pt", "Amb", "Cam"] |
| 344 | if self.rig == "material": |
| 345 | nodes, mtl = [], (name, "MaterialOutput") |
| 346 | if t in ("MtlBlinn", "MtlPhong", "MtlCookTorrance", "MtlWard"): |
| 347 | links["Diffuse.Color.Material"] = a |
| 348 | elif t == "MtlPBRUber": |
| 349 | if "BaseColor.Color.Material" in self.inputs: |
| 350 | links["BaseColor.Color.Material"] = a |
| 351 | elif t == "MtlMerge3D": |
| 352 | links["BackgroundMaterial"] = ("RedMtl", "MaterialOutput") |
| 353 | links["ForegroundMaterial"] = ("BaseTex", "MaterialOutput") |
| 354 | elif t == "MtlStereoMix3D": |
| 355 | links["LeftEyeMaterial"] = ("RedMtl", "MaterialOutput") |
| 356 | links["RightEyeMaterial"] = ("BaseTex", "MaterialOutput") |
| 357 | elif t == "MtlReflect": |
| 358 | links["BackgroundMaterial"] = ("RedMtl", "MaterialOutput") |
| 359 | links["Reflection.Color.Material"] = a |
| 360 | elif t == "MtlChanBool": |
| 361 | links["Background"] = ("RedMtl", "MaterialOutput") |
| 362 | elif t == "FalloffOperator": |
| 363 | links["FaceOnMaterial"] = ("RedMtl", "MaterialOutput") |
| 364 | links["GlancingMaterial"] = ("BaseTex", "MaterialOutput") |
| 365 | elif t == "SphereMap": |
| 366 | links["Image"] = a |
| 367 | elif t == "CubeMap": |
| 368 | for face in ("Front", "Back", "Left", "Right", "Top", "Bottom"): |
| 369 | if face in self.inputs: |
| 370 | links[face] = a |
| 371 | elif t == "BumpMap": |
| 372 | links["Input"] = ("Noise", "Output") |
| 373 | nodes.append(op_block(f"Bm{f}", "MtlBlinn", {}, {"Diffuse.Color.Material": a, "Bumpmap.Material": mtl})) |
| 374 | mtl = (f"Bm{f}", "MaterialOutput") |
| 375 | elif t == "TextureTransformOperator": |
| 376 | links["MaterialInput"] = ("BaseTex", "MaterialOutput") |
| 377 | nodes += [op_block(name, self.kind, inputs, links), op_block(f"S{f}", "Shape3D", {"Shape": FuID("SurfaceSphereInputs")}, {"MaterialInput": mtl})] |
| 378 | scene = [(f"S{f}", "Output")] + [(n, "Output") for n in lit[1:]] |
| 379 | else: |
| 380 | scene = [(n, "Output") for n in lit] |
| 381 | if t in ("Shape3D", "Cube3D", "ImagePlane3D", "Text3D", "Ribbon3D"): |
| 382 | if t in TEXTURE_SLOT: |
| 383 | links[TEXTURE_SLOT[t]] = a |
| 384 | scene[0] = tool_out |
| 385 | elif t in ("LightAmbient", "LightDirectional", "LightPoint", "LightSpot", "LightDome"): |
| 386 | scene = [(n, "Output") for n in ("WSph", "Wall", "Cam")] + [tool_out] |
| 387 | if t in ("LightAmbient", "LightDome"): |
| 388 | scene.append(("BaseDir", "Output")) |
| 389 | elif t == "Locator3D": |
| 390 | scene.append(tool_out) |
| 391 | elif t == "Camera3D": |
| 392 | scene[3] = tool_out |
| 393 | elif t == "Merge3D": |
| 394 | links.update({"SceneInput1": ("SphL", "Output"), "SceneInput2": ("BoxR", "Output")}) |
| 395 | scene[0] = tool_out |
| 396 | elif t == "Replicate3D": |
| 397 | links.update({"Destination": ("BoxR", "Output"), "Input1": ("SphL", "Output")}) |
| 398 | scene[0] = tool_out |
| 399 | elif t == "Renderer3D": |
| 400 | inputs = {k.replace("RendererSoftware.", "RendererOpenGL.") if k.endswith(("LightingEnabled", "ShadowsEnabled")) else k: v for k, v in inputs.items()} |
| 401 | links["SceneInput"] = (f"M{f}", "Output") |
| 402 | else: |
| 403 | links["SceneInput"] = ("Sph", "Output") |
| 404 | if t == "Displace3D": |
| 405 | links["Input"] = ("Noise", "Output") |
| 406 | elif t == "ReplaceMaterial3D": |
| 407 | links["MaterialInput"] = ("RedMtl", "MaterialOutput") |
| 408 | scene[0] = tool_out |
| 409 | nodes = [op_block(name, self.kind, inputs, links)] |
| 410 | nodes.append(op_block(f"M{f}", "Merge3D", {}, {f"SceneInput{k + 1}": src for k, src in enumerate(scene)})) |
| 411 | if t == "Renderer3D": |
| 412 | return nodes, name |
| 413 | return nodes + [op_block(f"Ren{f}", "Renderer3D", RENDERER3D, {"SceneInput": (f"M{f}", "Output")})], f"Ren{f}" |
| 414 | |
| 415 | def build(self, plates: Dict[str, str]) -> Tuple[str, List[Tuple[int, str]]]: |
| 416 | tools: List[str] = [ |
| 417 | make_loader("PlateA", plates["color"]), |
| 418 | make_loader("PlateB", plates["fg"]), |
| 419 | make_loader("PlateC", plates["bump"]), |
| 420 | f'\t\tBlackBG = Background {{ Inputs = {{ Width = Input {{ Value = {SIZE}, }}, Height = Input {{ Value = {SIZE}, }}, TopLeftAlpha = Input {{ Value = 1, }}, }}, }},', |
| 421 | f'\t\tWhiteBG = Background {{ Inputs = {{ Width = Input {{ Value = {SIZE}, }}, Height = Input {{ Value = {SIZE}, }}, TopLeftRed = Input {{ Value = 1, }}, TopLeftGreen = Input {{ Value = 1, }}, TopLeftBlue = Input {{ Value = 1, }}, TopLeftAlpha = Input {{ Value = 1, }}, }}, }},', |
| 422 | op_block("MaskSrc", "Background", { |
| 423 | "Width": SIZE, "Height": SIZE, "Type": FuID("Corner"), |
| 424 | "TopLeftRed": 1, "TopLeftGreen": 1, "TopLeftBlue": 1, "TopLeftAlpha": 0.0, |
| 425 | "TopRightRed": 1, "TopRightGreen": 1, "TopRightBlue": 1, "TopRightAlpha": 1.0, |
| 426 | "BottomLeftRed": 1, "BottomLeftGreen": 1, "BottomLeftBlue": 1, "BottomLeftAlpha": 0.8, |
| 427 | "BottomRightRed": 1, "BottomRightGreen": 1, "BottomRightBlue": 1, "BottomRightAlpha": 0.2, |
| 428 | }, {}), |
| 429 | ] |
| 430 | tools += self.rig_shared() |
| 431 | if self.shape_inputs or self.out_type == "ShapeTree" or self.kind == "sRender": |
| 432 | tools.append(op_block("ShapeA", "sRectangle", {}, {})) |
| 433 | tools.append(op_block("ShapeB", "sEllipse", {}, {})) |
| 434 | plates_by_slot = ["PlateA", "PlateB", "PlateC"] |
| 435 | fixed = self.fixed_inputs() |
| 436 | plan = self.plan() |
| 437 | cases: List[Tuple[int, str]] = [] |
| 438 | outs: List[str] = [] |
| 439 | for f, (label, overrides, wire_mask) in enumerate(plan): |
| 440 | links: Dict[str, Tuple[str, str]] = {} |
| 441 | for slot, iid in enumerate(self.wired_images): |
| 442 | links[iid] = (plates_by_slot[slot % 3], "Output") |
| 443 | for slot, iid in enumerate(self.shape_inputs): |
| 444 | links[iid] = (("ShapeA", "ShapeB")[slot % 2], "Output") |
| 445 | if self.kind == "sRender" and "Input" not in links: |
| 446 | links["Input"] = ("ShapeA", "Output") |
| 447 | if wire_mask: |
| 448 | links["EffectMask"] = ("MaskSrc", "Output") |
| 449 | inputs = {**fixed, **overrides} |
| 450 | name = f"T{f}" |
| 451 | if self.rig: |
| 452 | nodes, out = self.rig_frame(f, name, inputs, links) |
| 453 | tools += nodes |
| 454 | outs.append(out) |
| 455 | cases.append((f, label)) |
| 456 | continue |
| 457 | tools.append(op_block(name, self.kind, inputs, links)) |
| 458 | out = name |
| 459 | if self.out_type == "Mask": |
| 460 | out = f"W{f}" |
| 461 | tools.append(op_block(out, "Merge", {}, { |
| 462 | "Background": ("BlackBG", "Output"), |
| 463 | "Foreground": ("WhiteBG", "Output"), |
| 464 | "EffectMask": (name, self.out_id), |
| 465 | })) |
| 466 | elif self.out_type == "ShapeTree": |
| 467 | out = f"R{f}" |
| 468 | tools.append(op_block(out, "sRender", {"Width": SIZE, "Height": SIZE}, {"Input": (name, self.out_id)})) |
| 469 | outs.append(out) |
| 470 | cases.append((f, label)) |
| 471 | root, tree, splines = switch_tree(outs) |
| 472 | tools += tree |
| 473 | tools.append(make_saver(root, f"fn_{self.tool_slug()}")) |
| 474 | comp = make_comp("\n".join(tools + splines), len(outs) - 1, w=SIZE, h=SIZE) |
| 475 | if self.rig == "time": # Fusion fails any request outside GlobalRange, and retiming reaches far outside the render range |
| 476 | comp = comp.replace(f"GlobalRange = {{ 0, {len(outs) - 1} }}", "GlobalRange = { -100, 200 }") |
| 477 | return comp, cases |
| 478 | |
| 479 | def tool_slug(self) -> str: |
| 480 | return re.sub(r"\W", "_", self.tool) |
| 481 | |
| 482 | |
| 483 | def score(rows: Dict[int, Dict[str, Any]], labels: Dict[int, str]) -> Dict[str, Any]: |
| 484 | per_frame: List[Dict[str, Any]] = [] |
| 485 | gt_errors: List[str] = [] |
| 486 | for f in sorted(rows): |
| 487 | r = rows[f] |
| 488 | err = r.get("error") |
| 489 | if err and (err.startswith("sg render") or err.startswith("missing gt")): |
| 490 | gt_errors.append(err) |
| 491 | continue |
| 492 | if err or r.get("size_mismatch"): |
| 493 | acc = alpha = 0.0 |
| 494 | else: |
| 495 | acc = max(0.0, 100.0 - r["mae_pct"]) |
| 496 | alpha = max(0.0, 100.0 - r.get("alpha_mae_pct", 0.0)) |
| 497 | row = {"frame": f, "label": labels[f], "accuracy": round(acc, 4), "alpha_accuracy": round(alpha, 4)} |
| 498 | if err: |
| 499 | row["error"] = err[:160] |
| 500 | elif r.get("size_mismatch"): |
| 501 | row["error"] = f"size mismatch ours={r['dims_ours']} fusion={r['dims_gt']}" |
| 502 | per_frame.append(row) |
| 503 | if not per_frame: |
| 504 | return {"skipped": gt_errors[0] if gt_errors else "no frames rendered"} |
| 505 | accs = [p["accuracy"] for p in per_frame] |
| 506 | alphas = [p["alpha_accuracy"] for p in per_frame] |
| 507 | return { |
| 508 | "mean_accuracy": round(sum(accs) / len(accs), 4), |
| 509 | "min_accuracy": round(min(accs), 4), |
| 510 | "mean_alpha_accuracy": round(sum(alphas) / len(alphas), 4), |
| 511 | "min_alpha_accuracy": round(min(alphas), 4), |
| 512 | "frames": len(per_frame), |
| 513 | "timestamp": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), |
| 514 | "per_frame": per_frame, |
| 515 | } |
| 516 | |
| 517 | |
| 518 | def fuzz_tool(tool: str, catalog: Dict[str, Any], frames: int, plates: Dict[str, str], timeout: int) -> Dict[str, Any]: |
| 519 | fz = Fuzzer(tool, catalog, frames) |
| 520 | reason = fz.skip_reason() |
| 521 | if reason: |
| 522 | return {"skipped": reason} |
| 523 | comp_text, cases = fz.build(plates) |
| 524 | root = assets.ensure_dirs() |
| 525 | prefix = f"fn_{fz.tool_slug()}" |
| 526 | comp_path = root / "comps" / f"{prefix}.comp" |
| 527 | comp_path.write_text(comp_text) |
| 528 | labels = dict(cases) |
| 529 | rows = run_comp_both(comp_path, prefix, [f for f, _ in cases], labels, render_gt=True, timeout_sec=timeout) |
| 530 | def rescore(f: int, error: Optional[str] = None) -> None: |
| 531 | ours, gt = root / "ours" / prefix / f"{f:04d}.png", root / "gt" / f"{prefix}_{f:04d}.png" |
| 532 | m = assets.compute_diff_metrics(ours, gt) |
| 533 | if "error" not in m: |
| 534 | m["alpha_mae_pct"] = alpha_mae_pct(ours, gt) |
| 535 | elif error and m["error"].startswith("missing ours"): |
| 536 | m["error"] = error |
| 537 | rows[f] = {**m, "frame": f, "label": labels[f]} |
| 538 | |
| 539 | hung = [f for f, r in rows.items() if str(r.get("error", "")).startswith("render-check timed out")] |
| 540 | for f in hung: # one slow frame must not zero the whole tool |
| 541 | out = root / "ours" / prefix / f"{f:04d}.png" |
| 542 | out.unlink(missing_ok=True) |
| 543 | try: |
| 544 | subprocess.run([str(assets.RENDER_CHECK), str(comp_path), str(f), "--out", str(out)], capture_output=True, timeout=FRAME_TIMEOUT) |
| 545 | except (subprocess.TimeoutExpired, subprocess.CalledProcessError): |
| 546 | pass |
| 547 | rescore(f, f"render-check hung or failed (>{FRAME_TIMEOUT}s)") |
| 548 | for _ in range(4): # SMB directory cache can lag behind sg render |
| 549 | late = [f for f, r in rows.items() if str(r.get("error", "")).startswith("missing gt")] |
| 550 | if not late: |
| 551 | break |
| 552 | time.sleep(5) |
| 553 | for f in late: |
| 554 | rescore(f) |
| 555 | for r in rows.values(): |
| 556 | if "license server" in str(r.get("error", "")): |
| 557 | raise SystemExit(f"STOP: {r['error']}") |
| 558 | return score(rows, labels) |
| 559 | |
| 560 | |
| 561 | def paper_clover(suite: Path, archive_report: Optional[Path]) -> Dict[str, Any]: |
| 562 | """Mean `100 - MAE%` over the private suite frames and archive_diff comps rendered by both engines.""" |
| 563 | proc = subprocess.run([str(assets.RENDER_CHECK), "--suite", str(suite)], capture_output=True, text=True, timeout=1800) |
| 564 | out = proc.stdout + proc.stderr |
| 565 | suite_acc = [100.0 - float(m.group(1)) for m in re.finditer(r"^(?:PASS|FAIL)\s+\S+\s+\d+\s+([\d.]+)%", out, re.M)] |
| 566 | archive_acc: List[float] = [] |
| 567 | if archive_report: |
| 568 | report = json.loads(archive_report.read_text()) |
| 569 | archive_acc = [100.0 - c["mae_pct"] for c in report["cases"] if c.get("status") == "ok"] |
| 570 | both = suite_acc + archive_acc |
| 571 | if not both: |
| 572 | raise SystemExit("paper-clover: no suite or archive results found") |
| 573 | return { |
| 574 | "mean_accuracy": round(sum(both) / len(both), 4), |
| 575 | "suite": {"cases": len(suite_acc), "mean_accuracy": round(sum(suite_acc) / max(1, len(suite_acc)), 4)}, |
| 576 | "archive": {"cases": len(archive_acc), "mean_accuracy": round(sum(archive_acc) / max(1, len(archive_acc)), 4)}, |
| 577 | "timestamp": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), |
| 578 | } |
| 579 | |
| 580 | |
| 581 | def load_ledger(path: Path) -> Dict[str, Any]: |
| 582 | if path.exists(): |
| 583 | return json.loads(path.read_text()) |
| 584 | return {"fusion_version": "21.1", "tools": {}, "skipped": {}} |
| 585 | |
| 586 | |
| 587 | def save_ledger(path: Path, ledger: Dict[str, Any]) -> None: |
| 588 | ledger["tools"] = dict(sorted(ledger["tools"].items())) |
| 589 | ledger["skipped"] = dict(sorted(ledger["skipped"].items())) |
| 590 | path.write_text(json.dumps(ledger, indent=1) + "\n") |
| 591 | |
| 592 | |
| 593 | def main() -> int: |
| 594 | parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) |
| 595 | parser.add_argument("--tool", action="append", default=[], help="Tool class to fuzz (repeatable)") |
| 596 | parser.add_argument("--category", action="append", default=[], help="Fuzz every tool in a compatibility.md category") |
| 597 | parser.add_argument("--all", action="store_true", help="Fuzz every cataloged tool") |
| 598 | parser.add_argument("--paper-clover", action="store_true", help="Refresh the Paper Clover comps headline from the private suite + archive report") |
| 599 | parser.add_argument("--suite", type=Path, default=Path("/Users/clo/dev/compositor/private/suite.txt")) |
| 600 | parser.add_argument("--archive-report", type=Path, help="scripts/archive_diff.py --report-json output") |
| 601 | parser.add_argument("--frames", type=int, default=12, help="Frames per tool (default 12)") |
| 602 | parser.add_argument("--timeout", type=int, default=90, help="Per-render timeout in seconds") |
| 603 | parser.add_argument("--ledger", type=Path, default=LEDGER) |
| 604 | parser.add_argument("--catalog", type=Path, default=CATALOG) |
| 605 | parser.add_argument("--dry-run", action="store_true", help="Write comps only; do not render") |
| 606 | args = parser.parse_args() |
| 607 | |
| 608 | if args.paper_clover: |
| 609 | ledger = load_ledger(args.ledger) |
| 610 | ledger["paper_clover"] = paper_clover(args.suite, args.archive_report) |
| 611 | save_ledger(args.ledger, ledger) |
| 612 | print(json.dumps(ledger["paper_clover"])) |
| 613 | return 0 |
| 614 | |
| 615 | catalog = json.loads(args.catalog.read_text()) |
| 616 | meta = {m.name: m for m in TOOL_METADATA} |
| 617 | if args.all: |
| 618 | names = list(catalog["tools"]) |
| 619 | else: |
| 620 | names = list(args.tool) |
| 621 | for cat in args.category: |
| 622 | names += [m.name for m in TOOL_METADATA if m.category == cat and m.name in catalog["tools"]] |
| 623 | if not names: |
| 624 | parser.print_help() |
| 625 | return 2 |
| 626 | unknown = [n for n in names if n not in catalog["tools"]] |
| 627 | if unknown: |
| 628 | print(f"Not in catalog: {unknown}", file=sys.stderr) |
| 629 | return 2 |
| 630 | |
| 631 | plates = generate_assets() |
| 632 | ledger = load_ledger(args.ledger) |
| 633 | for tool in dict.fromkeys(names): |
| 634 | t0 = time.time() |
| 635 | if args.dry_run: |
| 636 | fz = Fuzzer(tool, catalog, args.frames) |
| 637 | print(f"{tool}: skip={fz.skip_reason()}") |
| 638 | if not fz.skip_reason(): |
| 639 | comp, _ = fz.build(plates) |
| 640 | (assets.ensure_dirs() / "comps" / f"fn_{fz.tool_slug()}.comp").write_text(comp) |
| 641 | continue |
| 642 | result = fuzz_tool(tool, catalog, args.frames, plates, args.timeout) |
| 643 | if "skipped" in result: |
| 644 | ledger["tools"].pop(tool, None) |
| 645 | ledger["skipped"][tool] = result["skipped"] |
| 646 | print(f"{tool:<24s} SKIPPED: {result['skipped'][:100]}", flush=True) |
| 647 | else: |
| 648 | ledger["skipped"].pop(tool, None) |
| 649 | result["category"] = meta[tool].category if tool in meta else None |
| 650 | ledger["tools"][tool] = result |
| 651 | worst = min(result["per_frame"], key=lambda p: p["accuracy"]) |
| 652 | print(f"{tool:<24s} mean={result['mean_accuracy']:7.3f}% min={result['min_accuracy']:7.3f}% " |
| 653 | f"alpha_mean={result['mean_alpha_accuracy']:7.3f}% frames={result['frames']} " |
| 654 | f"({time.time() - t0:.0f}s) worst f{worst['frame']}: {worst['label'][:70]}", flush=True) |
| 655 | save_ledger(args.ledger, ledger) |
| 656 | return 0 |
| 657 | |
| 658 | |
| 659 | if __name__ == "__main__": |
| 660 | raise SystemExit(main()) |