// Usage: pnpm generate:nodes [path/to/MaterialX] or pnpm check:nodes // Source: https://github.com/AcademySoftwareFoundation/MaterialX // MaterialX definitions: Copyright Contributors to the MaterialX Project, Apache-2.0. import { createHash } from 'node:crypto'; import { readdir, readFile, writeFile } from 'node:fs/promises'; import { join, relative, resolve as resolvePath } from 'node:path'; import { fileURLToPath } from 'node:url'; import { parseMaterialX } from '../packages/core/dist/index.js'; const repository = fileURLToPath(new URL('..', import.meta.url)); const args = process.argv.slice(2); const check = args.includes('--check'); const paths = args.filter((arg) => arg !== '--check'); if (paths.length > 1 || paths.some((arg) => arg.startsWith('--'))) throw new Error('Usage: generate-node-registry.mjs [path/to/MaterialX] [--check]'); const root = paths[0] ? resolvePath(paths[0]) : join(repository, 'submodules/MaterialX'); const cmake = await readFile(join(root, 'CMakeLists.txt'), 'utf8').catch((error) => { throw new Error( `MaterialX sources not found at ${root}. Place the upstream checkout in submodules/MaterialX or supply its path.`, { cause: error }, ); }); const version = ['MAJOR', 'MINOR', 'BUILD'] .map((part) => { const match = cmake.match(new RegExp(`set\\(MATERIALX_${part}_VERSION\\s+(\\d+)\\)`)); if (!match) throw new Error(`Cannot read MaterialX ${part} version from CMakeLists.txt`); return match[1]; }) .join('.'); const fingerprint = createHash('sha256'); fingerprint.update(cmake); let fileCount = 0; const definitions = new Map(); async function visit(directory) { for (const entry of (await readdir(directory, { withFileTypes: true })).toSorted((a, b) => a.name.localeCompare(b.name), )) { const path = join(directory, entry.name); if (entry.isDirectory()) await visit(path); else if (path.endsWith('.mtlx')) { const xml = await readFile(path, 'utf8'); fingerprint.update(`\0${relative(root, path).replaceAll('\\', '/')}\0${xml}`); fileCount++; for (const element of parseMaterialX(xml).elements) { if (element.name !== 'nodedef') continue; const name = element.attributes.name; if (!name || definitions.has(name)) throw new Error(`Missing or duplicate nodedef name in ${path}: ${name}`); definitions.set(name, element); } } } } await visit(join(root, 'libraries')); function resolve(def, seen = new Set()) { if (seen.has(def)) throw new Error('Cyclic nodedef inheritance'); seen.add(def); const parent = definitions.get(def.attributes.inherit); if (def.attributes.inherit && !parent) throw new Error(`Unknown inherited nodedef: ${def.attributes.inherit}`); if (!parent) return def; const base = resolve(parent, seen); const children = new Map(base.children.map((child) => [`${child.name}:${child.attributes.name}`, child])); for (const child of def.children) children.set(`${child.name}:${child.attributes.name}`, child); return { attributes: { ...base.attributes, ...def.attributes }, children: [...children.values()] }; } const specs = [...definitions.values()] .map((resolveDef) => { const def = resolve(resolveDef); const ports = (tag) => def.children .filter((child) => child.name === tag) .map(({ attributes }) => ({ name: attributes.name, type: attributes.type, ...(attributes.value !== undefined ? { value: attributes.value } : {}), attributes, })); const outputs = ports('output'); return { category: def.attributes.node, nodeDefName: def.attributes.name, type: def.attributes.type ?? (outputs.length === 1 ? outputs[0].type : 'multioutput'), nodeGroup: def.attributes.nodegroup, attributes: def.attributes, inputs: ports('input'), outputs, parameters: ports('parameter'), }; }) .filter((spec) => spec.category) .toSorted((a, b) => a.nodeDefName.localeCompare(b.nodeDefName)); const hash = fingerprint.digest('hex'); const generated = `import type { MaterialXNodeSpec } from '../types.js';\n\n// Generated by scripts/generate-node-registry.mjs from MaterialX ${version}.\n// Source: https://github.com/AcademySoftwareFoundation/MaterialX\n// SHA-256 of CMakeLists.txt and ${fileCount} library XML files: ${hash}\n// Copyright Contributors to the MaterialX Project. SPDX-License-Identifier: Apache-2.0\nexport const generatedNodeRegistry: MaterialXNodeSpec[] = ${JSON.stringify(specs, null, 2)};\n`; const outputs = [ ['packages/core/src/generated/node-registry.gen.ts', generated], ['packages/core/MATERIALX-LICENSE', await readFile(join(root, 'LICENSE'), 'utf8')], ]; for (const [path, content] of outputs) { const destination = join(repository, path); if (check) { const current = await readFile(destination, 'utf8').catch((error) => { if (error.code === 'ENOENT') return ''; throw error; }); if (current !== content) throw new Error(`${path} is out of date. Run pnpm generate:nodes with the intended MaterialX checkout.`); } else await writeFile(destination, content); } console.log(`${check ? 'Verified' : 'Generated'} ${specs.length} definitions from MaterialX ${version} (${hash}).`);