Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(scripts): add glTF validation, geometry, and PBR-class inspectors
nirholas2189614c0510
diff --git a/package.json b/package.jsonindex 6843e1df0..55f7dcc3e 100644--- a/package.json+++ b/package.json@@ -320,6 +320,8 @@"build:extension": "node scripts/build-extension-icons.mjs && node scripts/build-extension.mjs","build:extension:prod": "node scripts/build-extension-icons.mjs && node scripts/build-extension.mjs --prod","optimize:glb": "node scripts/optimize-glb.mjs",+ "validate:glb": "node scripts/validate-glb.mjs",+ "inspect:glb": "node scripts/inspect-glb-geometry.mjs","compress:glbs": "node scripts/compress-glbs.mjs","vendor:meshopt": "node scripts/vendor-meshopt-decoder.mjs","fetch-animations": "node scripts/download-animations.mjs",diff --git a/scripts/README.md b/scripts/README.mdindex 713574488..af5c5e91e 100644--- a/scripts/README.md+++ b/scripts/README.md@@ -48,6 +48,68 @@ extensions (clearcoat, transmission, sheen, ior, anisotropy, volume) arepresent. This is the ground truth for auditing whether a forge lane emits afull PBR set or just albedo, without opening the GLB in a 3D editor by hand.+### `inspect-glb-geometry.mjs`: meshes, attributes, and container extensions++```sh+node scripts/inspect-glb-geometry.mjs public/avatars/default.glb+node scripts/inspect-glb-geometry.mjs public/avatars/ # a whole directory+node scripts/inspect-glb-geometry.mjs --json a.glb b.glb+```++The mesh-side companion to the two PBR inspectors above. Prints mesh and skin+names, per-primitive vertex attributes, vertex/index counts, and the `POSITION`+component type, plus `extensionsUsed` / `extensionsRequired`.++Three questions it answers that the material inspectors cannot: a primitive with+no `NORMAL` renders flat-shaded and one with no `TEXCOORD_0` cannot receive any+texture a forge lane derives for it, so an "it came back untextured" report is+often an attribute problem; a `POSITION` that is not `FLOAT` means the mesh is+quantized (`KHR_mesh_quantization`, usually beside `EXT_meshopt_compression`),+which is why every mesh-consuming worker decodes before it reads; and mesh and+skin names are what a rig mapper matches on, so an avatar that will not drive the+shared clip library is diagnosed here first.++### `validate-glb.mjs`: Khronos glTF-Validator over a file, a directory, or a URL++```sh+node scripts/validate-glb.mjs public/avatars/default.glb+npm run validate:glb -- public/avatars/ # every model in a directory+npm run validate:glb -- --verbose model.glb # warnings and infos too+npm run validate:glb -- --json out/ > report.json+```++The PBR inspectors answer "what does this model carry"; this answers "is it+legal glTF at all", which is a different failure. A GLB can carry a complete+texture set and still be rejected by a strict viewer because a derived WebP map+was written without declaring `EXT_texture_webp`, an accessor's min/max+disagrees with its data, or a normalized attribute uses a component type the+spec forbids. Those show as a blank model in a third-party embed and as nothing+at all in our own forgiving viewer.++Errors print by default and warnings/infos behind `--verbose`. A `.gltf` with+external buffers resolves them relative to the file. Exit code is 1 when any+model reports a validation error, so it works as a gate on a pipeline that+writes GLBs.++### `derive-pbr-classes.mjs`: run the PBR derive pass across every material class++```sh+node scripts/derive-pbr-classes.mjs model.glb+node scripts/derive-pbr-classes.mjs model.glb --classes=glass,person --out=/tmp/pbr+node scripts/derive-pbr-classes.mjs model.glb --json+```++[`api/_lib/glb-pbr-derive.js`](../api/_lib/glb-pbr-derive.js) fills a model's+missing PBR channels from a material class: skin gets sheen and a pulled-down+specular, glass gets transmission and an IOR, car paint gets a clearcoat. The+class is normally picked from the generation prompt, which makes a change to the+class table or to the classifier easy to ship and hard to see. This runs one+input GLB through each class in turn and prints the table it applied next to+what the pass actually derived.++With `--out` each class writes `<out>/<basename>.<class>.glb`, ready to open in+the viewer or hand to `inspect-glb-materials.mjs` for the channel matrix.+### `set-r2-cors.mjs` — apply the bucket CORS policyRuns the canonical CORS policy against the R2 bucket holding all mediadiff --git a/scripts/derive-pbr-classes.mjs b/scripts/derive-pbr-classes.mjsnew file mode 100644index 000000000..d775be563--- /dev/null+++ b/scripts/derive-pbr-classes.mjs@@ -0,0 +1,118 @@+#!/usr/bin/env node+/**+ * Exercise the PBR derivation pass across every material class.+ *+ * api/_lib/glb-pbr-derive.js fills a model's missing PBR channels from a+ * material class: skin gets sheen and a pulled-down specular, glass gets+ * transmission and an IOR, car paint gets a clearcoat. The class is normally+ * picked from the generation prompt, which means a change to the class table or+ * to the classifier is easy to ship and hard to see. This runs one input GLB+ * through each class in turn and prints what the pass actually derived, so the+ * table can be reviewed as a table instead of one generation at a time.+ *+ * node scripts/derive-pbr-classes.mjs model.glb+ * node scripts/derive-pbr-classes.mjs model.glb --out=/tmp/pbr --classes=glass,person+ * node scripts/derive-pbr-classes.mjs model.glb --json+ *+ * With --out, each class writes `<out>/<basename>.<class>.glb`, ready to open in+ * the viewer or hand to scripts/inspect-glb-materials.mjs for the channel table.+ * Without it nothing is written and only the report is printed.+ */++import { readFile, writeFile, mkdir } from 'node:fs/promises';+import { basename, extname, resolve, join } from 'node:path';+import {+ derivePbrChannels,+ MATERIAL_CLASSES,+ MATERIAL_CLASS_IDS,+} from '../api/_lib/glb-pbr-derive.js';++function parseArgs(argv) {+ const args = { input: null, out: null, classes: MATERIAL_CLASS_IDS, tier: 'standard', json: false };+ for (const raw of argv) {+ if (raw === '--json') args.json = true;+ else if (raw.startsWith('--out=')) args.out = raw.slice('--out='.length);+ else if (raw.startsWith('--tier=')) args.tier = raw.slice('--tier='.length);+ else if (raw.startsWith('--classes=')) args.classes = raw.slice('--classes='.length).split(',').map((s) => s.trim()).filter(Boolean);+ else if (raw.startsWith('--')) throw new Error(`unknown flag ${raw}`);+ else if (args.input) throw new Error('only one input GLB is supported');+ else args.input = raw;+ }+ const unknown = args.classes.filter((c) => !MATERIAL_CLASS_IDS.includes(c));+ if (unknown.length) throw new Error(`unknown material class(es): ${unknown.join(', ')}. Known: ${MATERIAL_CLASS_IDS.join(', ')}`);+ if (!['draft', 'standard', 'high'].includes(args.tier)) throw new Error(`--tier must be draft, standard or high`);+ return args;+}++/** The class table itself, so a run shows what it is applying, not just the result. */+function printClassTable(ids) {+ console.log('material classes');+ for (const id of ids) {+ const c = MATERIAL_CLASSES[id];+ const roughness = typeof c.roughness === 'object' ? `${c.roughness.base} [${c.roughness.min}..${c.roughness.max}]` : String(c.roughness);+ const ext = Object.keys(c.ext || {}).join(', ') || '(none)';+ console.log(` ${id.padEnd(13)} metallic=${c.metallic} roughness=${roughness.padEnd(22)} ext: ${ext}`);+ }+}++async function main() {+ const args = parseArgs(process.argv.slice(2));+ if (!args.input) {+ console.error('usage: node scripts/derive-pbr-classes.mjs <model.glb> [--classes=a,b] [--tier=standard] [--out=<dir>] [--json]');+ process.exit(2);+ }++ const buf = await readFile(resolve(args.input));+ if (args.out) await mkdir(resolve(args.out), { recursive: true });+ const stem = basename(args.input, extname(args.input));++ if (!args.json) {+ printClassTable(args.classes);+ console.log(`\ninput ${args.input} ${(buf.byteLength / 1024).toFixed(1)} KiB tier=${args.tier}\n`);+ }++ const results = [];+ for (const materialClass of args.classes) {+ const r = await derivePbrChannels(buf, { materialClass, tier: args.tier });+ let outPath = null;+ if (args.out) {+ outPath = join(resolve(args.out), `${stem}.${materialClass}.glb`);+ await writeFile(outPath, r.buffer);+ }+ const row = {+ materialClass,+ changed: r.changed,+ inputBytes: r.inputBytes,+ outputBytes: r.outputBytes,+ materialsCreated: r.materialsCreated,+ normalsFilled: r.normalsFilled,+ materials: r.materials,+ outPath,+ };+ results.push(row);+ if (!args.json) {+ const derived = [...new Set(r.materials.flatMap((m) => m.derived))].sort();+ console.log(+ ` ${materialClass.padEnd(13)} ${r.changed ? 'changed' : 'no-op '} ${(r.outputBytes / 1024).toFixed(1).padStart(8)} KiB derived: ${derived.join(', ') || '(nothing)'}`,+ );+ if (outPath) console.log(` wrote ${outPath}`);+ }+ }++ if (args.json) {+ console.log(JSON.stringify({ generatedAt: new Date().toISOString(), input: args.input, tier: args.tier, results }, null, 2));+ } else {+ const inert = results.filter((r) => !r.changed).map((r) => r.materialClass);+ console.log('');+ console.log(+ inert.length+ ? `${inert.length} class(es) derived nothing on this input: ${inert.join(', ')}`+ : `All ${results.length} class(es) derived at least one channel.`,+ );+ }+}++main().catch((err) => {+ console.error(err.message || err);+ process.exit(2);+});diff --git a/scripts/inspect-glb-geometry.mjs b/scripts/inspect-glb-geometry.mjsnew file mode 100644index 000000000..61dbeb45b--- /dev/null+++ b/scripts/inspect-glb-geometry.mjs@@ -0,0 +1,191 @@+#!/usr/bin/env node+/**+ * Geometry and container inspector for GLB files.+ *+ * scripts/inspect-glb-materials.mjs and scripts/inspect-pbr-channels.mjs both+ * answer questions about surfaces. This one answers questions about the mesh+ * underneath: what the meshes are called, which vertex attributes each+ * primitive actually carries, how those attributes are stored, and which+ * container extensions the file declares.+ *+ * That matters in three places on this platform:+ *+ * - A primitive with no NORMAL renders flat-shaded, and a primitive with no+ * TEXCOORD_0 cannot receive any texture a forge lane derives for it, so a+ * "the model came back untextured" report is often an attribute problem+ * rather than a texture problem.+ * - POSITION stored as anything but FLOAT means the mesh is quantized+ * (KHR_mesh_quantization, usually alongside EXT_meshopt_compression). Most+ * three.ws avatars are, which is exactly why every mesh-consuming worker+ * has to decode before it reads (see gltf_meshopt.decode_if_meshopt).+ * - Mesh and node names are what a rig mapper matches on, so an avatar whose+ * skeleton will not drive the shared clip library is diagnosed here first.+ *+ * node scripts/inspect-glb-geometry.mjs public/avatars/default.glb+ * node scripts/inspect-glb-geometry.mjs public/avatars/ # a whole directory+ * node scripts/inspect-glb-geometry.mjs --json a.glb b.glb+ */++import { readFile, readdir, stat } from 'node:fs/promises';+import { basename, extname, resolve, join } from 'node:path';+import { NodeIO } from '@gltf-transform/core';+import { ALL_EXTENSIONS } from '@gltf-transform/extensions';+import { MeshoptDecoder } from 'meshoptimizer';++const MODEL_EXTENSIONS = new Set(['.glb', '.gltf']);++// glTF accessor componentType enums. POSITION is FLOAT in an unquantized mesh;+// anything else here means the geometry was compressed on the way in.+const COMPONENT_TYPES = {+ 5120: 'BYTE',+ 5121: 'UNSIGNED_BYTE',+ 5122: 'SHORT',+ 5123: 'UNSIGNED_SHORT',+ 5125: 'UNSIGNED_INT',+ 5126: 'FLOAT',+};++function parseArgs(argv) {+ const args = { inputs: [], json: false };+ for (const raw of argv) {+ if (raw === '--json') args.json = true;+ else if (raw.startsWith('--')) throw new Error(`unknown flag ${raw}`);+ else args.inputs.push(raw);+ }+ return args;+}++async function expand(input) {+ if (/^https?:\/\//i.test(input)) return [input];+ const info = await stat(resolve(input));+ if (!info.isDirectory()) return [input];+ const names = await readdir(resolve(input));+ return names+ .filter((n) => MODEL_EXTENSIONS.has(extname(n).toLowerCase()))+ .sort()+ .map((n) => join(input, n));+}++async function loadBytes(source) {+ if (/^https?:\/\//i.test(source)) {+ const res = await fetch(source, { redirect: 'follow' });+ if (!res.ok) throw new Error(`${source} returned HTTP ${res.status}`);+ return new Uint8Array(await res.arrayBuffer());+ }+ return new Uint8Array(await readFile(resolve(source)));+}++async function makeIO() {+ await MeshoptDecoder.ready;+ return new NodeIO()+ .registerExtensions(ALL_EXTENSIONS)+ .registerDependencies({ 'meshopt.decoder': MeshoptDecoder });+}++export async function inspectGeometry(source) {+ const bytes = await loadBytes(source);+ const io = await makeIO();+ const doc = await io.readBinary(bytes);+ const root = doc.getRoot();++ const meshes = root.listMeshes().map((mesh) => ({+ name: mesh.getName() || '(unnamed)',+ primitives: mesh.listPrimitives().map((prim) => {+ const position = prim.getAttribute('POSITION');+ const indices = prim.getIndices();+ return {+ semantics: prim.listSemantics().sort(),+ vertexCount: position ? position.getCount() : 0,+ indexCount: indices ? indices.getCount() : 0,+ positionComponentType: position+ ? COMPONENT_TYPES[position.getComponentType()] || String(position.getComponentType())+ : null,+ positionNormalized: position ? position.getNormalized() : false,+ material: prim.getMaterial()?.getName() || null,+ };+ }),+ }));++ const skins = root.listSkins().map((skin) => ({+ name: skin.getName() || '(unnamed)',+ jointCount: skin.listJoints().length,+ }));++ return {+ source,+ bytes: bytes.byteLength,+ extensionsUsed: root.listExtensionsUsed().map((e) => e.extensionName).sort(),+ extensionsRequired: root.listExtensionsRequired().map((e) => e.extensionName).sort(),+ meshCount: meshes.length,+ // A skin is what makes an avatar drivable by the shared clip library; a+ // mesh with none falls back to the default rig rather than animating.+ skins,+ animations: root.listAnimations().map((a) => a.getName() || '(unnamed)'),+ meshes,+ };+}++function printReport(r) {+ console.log(`\n${r.source}`);+ console.log(` ${(r.bytes / 1024).toFixed(1)} KiB, ${r.meshCount} mesh(es), ${r.skins.length} skin(s), ${r.animations.length} animation(s)`);+ console.log(` extensionsUsed ${r.extensionsUsed.join(', ') || '(none)'}`);+ if (r.extensionsRequired.length) console.log(` extensionsRequired ${r.extensionsRequired.join(', ')}`);+ for (const skin of r.skins) console.log(` skin "${skin.name}" ${skin.jointCount} joints`);+ if (r.animations.length) console.log(` animations ${r.animations.join(', ')}`);+ for (const mesh of r.meshes) {+ console.log(` mesh "${mesh.name}"`);+ for (const p of mesh.primitives) {+ const quantized = p.positionComponentType && p.positionComponentType !== 'FLOAT';+ console.log(+ ` ${String(p.vertexCount).padStart(7)} verts ${String(p.indexCount).padStart(7)} indices POSITION=${p.positionComponentType || 'MISSING'}${quantized ? ' (quantized)' : ''}`,+ );+ console.log(` attributes ${p.semantics.join(', ')}`);+ const missing = ['NORMAL', 'TEXCOORD_0'].filter((s) => !p.semantics.includes(s));+ if (missing.length) console.log(` MISSING ${missing.join(', ')}`);+ if (p.material) console.log(` material ${p.material}`);+ }+ }+}++async function main() {+ const args = parseArgs(process.argv.slice(2));+ if (args.inputs.length === 0) {+ console.error('usage: node scripts/inspect-glb-geometry.mjs [--json] <glb path, directory, or url>...');+ process.exit(2);+ }++ const sources = [];+ for (const input of args.inputs) sources.push(...(await expand(input)));+ if (sources.length === 0) {+ console.error(`no .glb or .gltf files found in: ${args.inputs.join(', ')}`);+ process.exit(2);+ }++ const reports = [];+ let failures = 0;+ for (const source of sources) {+ try {+ reports.push(await inspectGeometry(source));+ } catch (err) {+ failures++;+ reports.push({ source, error: String(err.message || err) });+ }+ }++ if (args.json) {+ console.log(JSON.stringify({ generatedAt: new Date().toISOString(), models: reports }, null, 2));+ } else {+ for (const r of reports) {+ if (r.error) console.error(`\n${basename(r.source)}\n ERROR ${r.error}`);+ else printReport(r);+ }+ }+ if (failures > 0) process.exit(2);+}++if (process.argv[1] && import.meta.url === new URL(`file://${resolve(process.argv[1])}`).href) {+ main().catch((err) => {+ console.error(err);+ process.exit(2);+ });+}diff --git a/scripts/validate-glb.mjs b/scripts/validate-glb.mjsnew file mode 100644index 000000000..b3deab1be--- /dev/null+++ b/scripts/validate-glb.mjs@@ -0,0 +1,163 @@+#!/usr/bin/env node+/**+ * Khronos glTF-Validator over one or more models.+ *+ * The PBR inspectors in this directory answer "what does this model carry";+ * this one answers "is it legal glTF at all". They are different failures: a+ * GLB can carry a complete texture set and still be rejected by a strict viewer+ * because a derived WebP map was written without declaring EXT_texture_webp, an+ * accessor's min/max disagrees with its data, or a normalized attribute uses a+ * component type the spec forbids. Those show up as a blank model in a third+ * party embed and as nothing at all in our own viewer, which is forgiving.+ *+ * node scripts/validate-glb.mjs public/avatars/default.glb+ * node scripts/validate-glb.mjs out/ # every .glb/.gltf in a directory+ * node scripts/validate-glb.mjs --verbose a.glb # warnings and infos too+ * node scripts/validate-glb.mjs --json out/ > report.json+ *+ * Exit code is 1 when any model reports a validation error, so this doubles as+ * a gate on a pipeline that writes GLBs (`npm run validate:glb`).+ */++import { readFile, readdir, stat } from 'node:fs/promises';+import { basename, dirname, extname, resolve, join } from 'node:path';+import { validateBytes } from 'gltf-validator';++const MODEL_EXTENSIONS = new Set(['.glb', '.gltf']);+const SEVERITY = ['ERROR', 'WARNING', 'INFO', 'HINT'];++function parseArgs(argv) {+ const args = { inputs: [], verbose: false, json: false, maxIssues: 20 };+ for (const raw of argv) {+ if (raw === '--verbose') args.verbose = true;+ else if (raw === '--json') args.json = true;+ else if (raw.startsWith('--max-issues=')) args.maxIssues = Number(raw.slice('--max-issues='.length));+ else if (raw.startsWith('--')) throw new Error(`unknown flag ${raw}`);+ else args.inputs.push(raw);+ }+ if (!Number.isFinite(args.maxIssues) || args.maxIssues < 1) throw new Error('--max-issues must be a positive number');+ return args;+}++/** A directory expands to the models inside it; a file or URL stands alone. */+async function expand(input) {+ if (/^https?:\/\//i.test(input)) return [input];+ const info = await stat(resolve(input));+ if (!info.isDirectory()) return [input];+ const names = await readdir(resolve(input));+ return names+ .filter((n) => MODEL_EXTENSIONS.has(extname(n).toLowerCase()))+ .sort()+ .map((n) => join(input, n));+}++async function loadBytes(source) {+ if (/^https?:\/\//i.test(source)) {+ const res = await fetch(source, { redirect: 'follow' });+ if (!res.ok) throw new Error(`${source} returned HTTP ${res.status}`);+ return new Uint8Array(await res.arrayBuffer());+ }+ return new Uint8Array(await readFile(resolve(source)));+}++/**+ * A .gltf file keeps its buffers and images beside it, and the validator cannot+ * read them on its own. Resolving them relative to the model is what separates+ * a real structural error from a pile of phantom "resource not found" ones.+ */+function externalResourceFunction(source) {+ if (/^https?:\/\//i.test(source)) {+ const base = new URL(source);+ return async (uri) => new Uint8Array(await (await fetch(new URL(uri, base))).arrayBuffer());+ }+ const dir = dirname(resolve(source));+ return async (uri) => new Uint8Array(await readFile(join(dir, decodeURIComponent(uri))));+}++export async function validateOne(source, { maxIssues = 20 } = {}) {+ const bytes = await loadBytes(source);+ const report = await validateBytes(bytes, {+ maxIssues,+ uri: source,+ externalResourceFunction: externalResourceFunction(source),+ });+ const issues = report.issues;+ return {+ source,+ bytes: bytes.byteLength,+ generator: report.info?.generator ?? null,+ version: report.info?.version ?? null,+ extensionsUsed: report.info?.extensionsUsed ?? [],+ errors: issues.numErrors,+ warnings: issues.numWarnings,+ infos: issues.numInfos,+ hints: issues.numHints,+ messages: issues.messages.map((m) => ({+ severity: SEVERITY[m.severity] ?? String(m.severity),+ code: m.code,+ message: m.message,+ pointer: m.pointer ?? null,+ })),+ };+}++function printReport(r, verbose) {+ const head = `${basename(r.source).padEnd(34)} errors=${r.errors} warnings=${r.warnings} infos=${r.infos}`;+ console.log(head);+ const shown = verbose ? r.messages : r.messages.filter((m) => m.severity === 'ERROR');+ for (const m of shown) {+ console.log(` ${m.severity.padEnd(7)} ${m.code} ${m.message}${m.pointer ? ` ${m.pointer}` : ''}`);+ }+}++async function main() {+ const args = parseArgs(process.argv.slice(2));+ if (args.inputs.length === 0) {+ console.error('usage: node scripts/validate-glb.mjs [--verbose] [--json] [--max-issues=N] <glb/gltf path, directory, or url>...');+ process.exit(2);+ }++ const sources = [];+ for (const input of args.inputs) sources.push(...(await expand(input)));+ if (sources.length === 0) {+ console.error(`no .glb or .gltf files found in: ${args.inputs.join(', ')}`);+ process.exit(2);+ }++ const reports = [];+ let unreadable = 0;+ for (const source of sources) {+ try {+ reports.push(await validateOne(source, { maxIssues: args.maxIssues }));+ } catch (err) {+ unreadable++;+ reports.push({ source, error: String(err.message || err) });+ }+ }++ if (args.json) {+ console.log(JSON.stringify({ generatedAt: new Date().toISOString(), models: reports }, null, 2));+ } else {+ for (const r of reports) {+ if (r.error) console.error(`${basename(r.source).padEnd(34)} UNREADABLE ${r.error}`);+ else printReport(r, args.verbose);+ }+ const invalid = reports.filter((r) => !r.error && r.errors > 0);+ console.log('');+ console.log(+ invalid.length+ ? `${invalid.length} of ${sources.length} model(s) failed validation: ${invalid.map((r) => basename(r.source)).join(', ')}`+ : `All ${sources.length - unreadable} readable model(s) are valid glTF.`,+ );+ }++ if (unreadable > 0) process.exit(2);+ if (reports.some((r) => !r.error && r.errors > 0)) process.exit(1);+}++if (process.argv[1] && import.meta.url === new URL(`file://${resolve(process.argv[1])}`).href) {+ main().catch((err) => {+ console.error(err);+ process.exit(2);+ });+}