| 1 | #!/usr/bin/env python3 |
| 2 | """Export every supported Fusion 21.1 tool's input schema to scripts/tool_catalog.json. |
| 3 | |
| 4 | Runs the official `fuscript` Lua interpreter inside Snow Globe's Fusion container |
| 5 | (`comp:AddTool(kind)` -> `tool:GetInputList()` -> `inp:GetAttrs()`); no GUI or Fusion |
| 6 | binary internals are touched. The render node itself refuses comp-embedded scripts |
| 7 | ("Script execution blocked by preferences"), so `sg render` cannot host this. |
| 8 | |
| 9 | python3 scripts/fusion_introspect.py # all TOOL_METADATA tools |
| 10 | python3 scripts/fusion_introspect.py --tool Blur --tool Merge |
| 11 | """ |
| 12 | |
| 13 | from __future__ import annotations |
| 14 | |
| 15 | import argparse |
| 16 | import json |
| 17 | import os |
| 18 | import shlex |
| 19 | import subprocess |
| 20 | import sys |
| 21 | from pathlib import Path |
| 22 | from typing import Any, Dict, List, Optional, Tuple |
| 23 | |
| 24 | sys.path.insert(0, str(Path(__file__).resolve().parent)) |
| 25 | from gen_compatibility import TOOL_METADATA # noqa: E402 |
| 26 | |
| 27 | CATALOG = Path(__file__).resolve().parent / "tool_catalog.json" |
| 28 | HOST = os.environ.get("SNOWGLOBE_DEPLOY_HOST", "root@10.0.0.1") |
| 29 | PORT = os.environ.get("SNOWGLOBE_DEPLOY_PORT", "22") |
| 30 | FUSION_DIR = "/opt/BlackmagicDesign/FusionRenderNode21" |
| 31 | NON_RENDER = {"Note", "Underlay"} |
| 32 | BATCH = 20 |
| 33 | |
| 34 | # Raw `GetAttrs()` keys copied verbatim out of Lua; Python renames them into the catalog schema. |
| 35 | RAW_KEYS = ( |
| 36 | "INPS_ID INPS_Name INPS_DataType INPID_InputControl INPID_PreviewControl INPN_Default INPN_DefaultX " |
| 37 | "INPN_DefaultY INPN_MinScale INPN_MaxScale INPN_MinAllowed INPN_MaxAllowed INPB_Integer INPS_ICS_ControlPage " |
| 38 | "INPI_IC_ControlGroup INPI_IC_ControlID INPI_PC_ControlGroup INPI_PC_ControlID INPI_PC_GrabPriority " |
| 39 | "INPB_Required INPB_External INPB_Passive INPST_ComboControl_String INPIDT_ComboControl_ID " |
| 40 | "INPST_MultiButtonControl_String INPIDT_MultiButtonControl_ID" |
| 41 | ).split() |
| 42 | |
| 43 | # Values Fusion reports for an unconstrained input, plus `name == id` and non-numeric scales, are omitted to keep the catalog reviewable. |
| 44 | NEUTRAL = { |
| 45 | "integer": False, "control_group": 0, "control_id": 0, "grab_priority": 0, "animatable": False, |
| 46 | "min_allowed": -1000000, "max_allowed": 1000000, |
| 47 | } |
| 48 | # Pure layout widgets: no value, no render effect. |
| 49 | CHROME_CONTROLS = {"NestControl", "SeparatorControl", "SpacerControl", "LabelControl", "ButtonControl", "LayerControl", "LayerListControl"} |
| 50 | |
| 51 | # Per-tool bookkeeping present on nearly every tool: no render effect. |
| 52 | BOOKKEEPING_IDS = {"HideInputs", "Comments", "FrameRenderScript", "StartRenderScript", "EndRenderScript"} |
| 53 | BOOKKEEPING_PREFIXES = ("Gamut.", "ProcessLayers") |
| 54 | |
| 55 | LUA_TEMPLATE = r""" |
| 56 | local KEYS = %(keys)s |
| 57 | local KINDS = %(kinds)s |
| 58 | local function esc(s) |
| 59 | return '"' .. tostring(s):gsub('[%%c"\\]', function(c) |
| 60 | if c == '"' then return '\\"' elseif c == '\\' then return '\\\\' end |
| 61 | return string.format('\\u%%04x', c:byte()) |
| 62 | end) .. '"' |
| 63 | end |
| 64 | local function enc(v, depth) |
| 65 | local t = type(v) |
| 66 | if t == "nil" then return "null" |
| 67 | elseif t == "boolean" then return tostring(v) |
| 68 | elseif t == "number" then |
| 69 | if v ~= v or v == math.huge or v == -math.huge then return "null" end |
| 70 | return string.format("%%.17g", v) |
| 71 | elseif t == "string" then return esc(v) |
| 72 | elseif t == "table" and depth < 4 then |
| 73 | local n, parts = #v, {} |
| 74 | if n > 0 then |
| 75 | for i = 1, n do parts[i] = enc(v[i], depth + 1) end |
| 76 | return "[" .. table.concat(parts, ",") .. "]" |
| 77 | end |
| 78 | local keys, orig = {}, {} |
| 79 | for k in pairs(v) do keys[#keys + 1] = tostring(k); orig[tostring(k)] = k end |
| 80 | table.sort(keys) |
| 81 | for _, k in ipairs(keys) do parts[#parts + 1] = esc(k) .. ":" .. enc(v[orig[k]], depth + 1) end |
| 82 | if #parts == 0 then return "[]" end |
| 83 | return "{" .. table.concat(parts, ",") .. "}" |
| 84 | end |
| 85 | return "null" |
| 86 | end |
| 87 | local VALUELESS = { Image = true, Mask = true, DataType3D = true, Particles = true, Gradient = true } |
| 88 | |
| 89 | local fu = Fusion() |
| 90 | local comp = fu:NewComp() |
| 91 | for _, kind in ipairs(KINDS) do |
| 92 | local ok, tool = pcall(function() return comp:AddTool(kind, -32768, -32768) end) |
| 93 | if not ok or not tool then |
| 94 | print("@@SKIP\t" .. kind .. "\tAddTool returned nil") |
| 95 | else |
| 96 | local inputs, outputs = {}, {} |
| 97 | for _, inp in ipairs(tool:GetInputList()) do |
| 98 | local a = inp:GetAttrs() |
| 99 | local row = {} |
| 100 | for _, k in ipairs(KEYS) do row[k] = a[k] end |
| 101 | if not VALUELESS[a.INPS_DataType] then |
| 102 | local vok, val = pcall(function() return inp[0] end) |
| 103 | if vok then row.value = val end |
| 104 | end |
| 105 | inputs[#inputs + 1] = row |
| 106 | end |
| 107 | for _, out in ipairs(tool:GetOutputList()) do |
| 108 | local a = out:GetAttrs() |
| 109 | outputs[#outputs + 1] = { id = a.OUTS_ID, name = a.OUTS_Name, data_type = a.OUTS_DataType } |
| 110 | end |
| 111 | print("@@TOOL\t" .. kind .. "\t" .. enc({ reg_id = tool:GetAttrs().TOOLS_RegID, inputs = inputs, outputs = outputs }, 0)) |
| 112 | pcall(function() tool:Delete() end) |
| 113 | end |
| 114 | end |
| 115 | print("@@DONE") |
| 116 | """ |
| 117 | |
| 118 | CONTAINER_SH = ( |
| 119 | 'export NOMAD_TOKEN=$(cat /var/lib/snowglobe/nomad.token); ' |
| 120 | 'alloc=$(nomad job allocs -json fusion | python3 -c \'import json,sys; ' |
| 121 | 'print(next(a["ID"] for a in json.load(sys.stdin) if a["ClientStatus"]=="running"))\'); ' |
| 122 | 'exec podman exec -i app-$alloc sh -c %s' |
| 123 | ) |
| 124 | |
| 125 | |
| 126 | def lua_list(items: List[str]) -> str: |
| 127 | return "{" + ",".join(json.dumps(i) for i in items) + "}" |
| 128 | |
| 129 | |
| 130 | def run_fuscript(lua: str, timeout: int) -> str: |
| 131 | """Pipe a Lua script into `fuscript` inside the Fusion container and return stdout.""" |
| 132 | inner = f"cd {FUSION_DIR} && cat > /tmp/_introspect.lua && DISPLAY=:99 ./fuscript -l lua /tmp/_introspect.lua" |
| 133 | remote = CONTAINER_SH % shlex.quote(inner) |
| 134 | proc = subprocess.run( |
| 135 | ["ssh", "-T", "-o", "BatchMode=yes", "-p", PORT, HOST, remote], |
| 136 | input=lua, capture_output=True, text=True, timeout=timeout, |
| 137 | ) |
| 138 | return proc.stdout |
| 139 | |
| 140 | |
| 141 | def introspect(kinds: List[str], timeout: int = 300) -> Tuple[Dict[str, Any], Dict[str, str]]: |
| 142 | lua = LUA_TEMPLATE % {"keys": lua_list(RAW_KEYS), "kinds": lua_list(kinds)} |
| 143 | tools: Dict[str, Any] = {} |
| 144 | skipped: Dict[str, str] = {} |
| 145 | try: |
| 146 | out = run_fuscript(lua, timeout) |
| 147 | except subprocess.TimeoutExpired: |
| 148 | out = "" |
| 149 | for line in out.splitlines(): |
| 150 | if line.startswith("@@TOOL\t"): |
| 151 | _, kind, payload = line.split("\t", 2) |
| 152 | tools[kind] = json.loads(payload) |
| 153 | elif line.startswith("@@SKIP\t"): |
| 154 | _, kind, why = line.split("\t", 2) |
| 155 | skipped[kind] = why |
| 156 | for kind in kinds: |
| 157 | if kind not in tools and kind not in skipped: |
| 158 | skipped[kind] = "fuscript hung or crashed" |
| 159 | return tools, skipped |
| 160 | |
| 161 | |
| 162 | def shape_input(raw: Dict[str, Any]) -> Dict[str, Any]: |
| 163 | dtype = raw.get("INPS_DataType") |
| 164 | default: Any = raw.get("value") |
| 165 | if dtype == "Number": |
| 166 | default = raw.get("INPN_Default") |
| 167 | elif dtype == "Point": |
| 168 | default = default or [raw.get("INPN_DefaultX"), raw.get("INPN_DefaultY")] |
| 169 | entries = ( |
| 170 | raw.get("INPIDT_ComboControl_ID") |
| 171 | or raw.get("INPIDT_MultiButtonControl_ID") |
| 172 | or raw.get("INPST_ComboControl_String") |
| 173 | or raw.get("INPST_MultiButtonControl_String") |
| 174 | ) |
| 175 | row = { |
| 176 | "id": raw.get("INPS_ID"), |
| 177 | "name": raw.get("INPS_Name"), |
| 178 | "data_type": dtype, |
| 179 | "input_control": raw.get("INPID_InputControl"), |
| 180 | "preview_control": raw.get("INPID_PreviewControl"), |
| 181 | "default": default, |
| 182 | "min_scale": raw.get("INPN_MinScale"), |
| 183 | "max_scale": raw.get("INPN_MaxScale"), |
| 184 | "min_allowed": raw.get("INPN_MinAllowed"), |
| 185 | "max_allowed": raw.get("INPN_MaxAllowed"), |
| 186 | "integer": raw.get("INPB_Integer"), |
| 187 | "page": raw.get("INPS_ICS_ControlPage"), |
| 188 | "control_group": raw.get("INPI_IC_ControlGroup"), |
| 189 | "control_id": raw.get("INPI_IC_ControlID"), |
| 190 | "combo_entries": entries, |
| 191 | "main_input": bool(raw.get("INPB_Required")) and dtype in ("Image", "DataType3D", "Particles") or None, |
| 192 | "grab_priority": raw.get("INPI_PC_GrabPriority"), |
| 193 | "animatable": raw.get("INPB_External"), |
| 194 | } |
| 195 | if dtype not in ("Number", "Point"): |
| 196 | row["min_scale"] = row["max_scale"] = None |
| 197 | if row["name"] == row["id"]: |
| 198 | row["name"] = None |
| 199 | return {k: v for k, v in row.items() if v is not None and NEUTRAL.get(k, object()) != v} |
| 200 | |
| 201 | |
| 202 | def is_render_input(raw: Dict[str, Any]) -> bool: |
| 203 | iid = raw["INPS_ID"] |
| 204 | return ( |
| 205 | raw.get("INPID_InputControl") not in CHROME_CONTROLS |
| 206 | and iid not in BOOKKEEPING_IDS |
| 207 | and not iid.startswith(BOOKKEEPING_PREFIXES) |
| 208 | and not iid.endswith("_LayerSelect") |
| 209 | ) |
| 210 | |
| 211 | |
| 212 | def build_catalog(tools: Dict[str, Any], skipped: Dict[str, str]) -> Dict[str, Any]: |
| 213 | return { |
| 214 | "fusion_version": "21.1", |
| 215 | "tools": { |
| 216 | kind: { |
| 217 | "reg_id": t["reg_id"], |
| 218 | "inputs": [shape_input(r) for r in t["inputs"] if is_render_input(r)], |
| 219 | "outputs": t["outputs"], |
| 220 | } |
| 221 | for kind, t in sorted(tools.items()) |
| 222 | }, |
| 223 | "skipped": dict(sorted(skipped.items())), |
| 224 | } |
| 225 | |
| 226 | |
| 227 | def dump_catalog(catalog: Dict[str, Any]) -> str: |
| 228 | """One input per line: diffable without a megabyte-tall indent=1 dump.""" |
| 229 | one = lambda v: json.dumps(v, separators=(",", ":")) # noqa: E731 |
| 230 | out = ["{", f'"fusion_version":{one(catalog["fusion_version"])},', '"tools":{'] |
| 231 | tools = [] |
| 232 | for kind, t in catalog["tools"].items(): |
| 233 | inputs = ",\n".join(" " + one(i) for i in t["inputs"]) |
| 234 | tools.append(f'{one(kind)}:{{"reg_id":{one(t["reg_id"])},"outputs":{one(t["outputs"])},"inputs":[\n{inputs}\n]}}') |
| 235 | out.append(",\n".join(tools)) |
| 236 | out.append("},") |
| 237 | out.append(f'"skipped":{one(catalog["skipped"])}') |
| 238 | out.append("}") |
| 239 | return "\n".join(out) + "\n" |
| 240 | |
| 241 | |
| 242 | def candidate_kinds() -> List[Tuple[str, Tuple[str, ...]]]: |
| 243 | return [(m.name, m.aliases) for m in TOOL_METADATA if m.name not in NON_RENDER] |
| 244 | |
| 245 | |
| 246 | def main() -> int: |
| 247 | parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) |
| 248 | parser.add_argument("--tool", action="append", default=[], help="Only introspect these tools (merged into the existing catalog).") |
| 249 | parser.add_argument("--out", type=Path, default=CATALOG) |
| 250 | args = parser.parse_args() |
| 251 | |
| 252 | wanted = [(n, a) for n, a in candidate_kinds() if not args.tool or n in args.tool] |
| 253 | # Fusion registers some tools under their alias (Fuse.Cryptomatte -> Cryptomatte); try both. |
| 254 | kinds = [k for name, aliases in wanted for k in (name, *aliases)] |
| 255 | |
| 256 | tools: Dict[str, Any] = {} |
| 257 | skipped: Dict[str, str] = {} |
| 258 | for i in range(0, len(kinds), BATCH): |
| 259 | t, s = introspect(kinds[i : i + BATCH]) |
| 260 | tools.update(t) |
| 261 | skipped.update(s) |
| 262 | print(f" introspected {len(tools)} tools ({i + len(t) + len(s)}/{len(kinds)} kinds)", file=sys.stderr) |
| 263 | |
| 264 | # An alias that resolved stands in for its failed canonical name. |
| 265 | for name, aliases in wanted: |
| 266 | if name not in tools: |
| 267 | alias = next((a for a in aliases if a in tools), None) |
| 268 | if alias: |
| 269 | tools[name] = tools.pop(alias) |
| 270 | skipped.pop(name, None) |
| 271 | for a in aliases: |
| 272 | skipped.pop(a, None) |
| 273 | |
| 274 | catalog = build_catalog(tools, skipped) |
| 275 | if args.tool and args.out.exists(): |
| 276 | old = json.loads(args.out.read_text()) |
| 277 | old["tools"].update(catalog["tools"]) |
| 278 | old["skipped"] = {k: v for k, v in {**old["skipped"], **catalog["skipped"]}.items() if k not in old["tools"]} |
| 279 | catalog = old |
| 280 | args.out.write_text(dump_catalog(catalog)) |
| 281 | n_inputs = sum(len(t["inputs"]) for t in catalog["tools"].values()) |
| 282 | print(f"Wrote {args.out}: {len(catalog['tools'])} tools, {n_inputs} inputs, {len(catalog['skipped'])} skipped") |
| 283 | for k, v in catalog["skipped"].items(): |
| 284 | print(f" skipped {k}: {v}") |
| 285 | return 0 |
| 286 | |
| 287 | |
| 288 | if __name__ == "__main__": |
| 289 | raise SystemExit(main()) |