lowpoly-coder-4b / export_glb.mjs
Mike0021's picture
Add export_glb.mjs
6ce4f2d verified
Raw History Blame Contribute Delete
4.44 kB
// Turn a LowPoly Coder 4B reply into a .glb file.
//
// npm install three@0.180.0
// node export_glb.mjs reply.txt asset.glb
//
// reply.txt is the model's full answer (spec lines + one ```javascript block defining buildAsset(THREE)).
// The code runs in a node:vm context with a time limit. node:vm is NOT a security boundary: generated code
// is untrusted, so run this inside a container or VM without network or secrets.
//
// Output: one glTF node per mesh (named as in the code), world transforms baked into the vertices,
// one material per mesh (base colour from MeshStandardMaterial.color, metallic/roughness copied).
// Triangles are written unindexed and without normals, so glTF viewers shade them flat, as intended.
import fs from 'node:fs';
import vm from 'node:vm';
import * as THREE from 'three';
const [, , inPath, outPath = 'asset.glb'] = process.argv;
if (!inPath) { console.error('usage: node export_glb.mjs reply.txt [asset.glb]'); process.exit(2); }
const reply = fs.readFileSync(inPath, 'utf8').split('</think>').pop();
const blocks = [...reply.matchAll(/```(?:javascript|js)?\s*\n([\s\S]*?)```/g)].map(m => m[1]);
const code = blocks.find(b => b.includes('function buildAsset'));
if (!code) { console.error('no ```javascript block with function buildAsset found'); process.exit(1); }
const ctx = vm.createContext({ THREE, Math, console });
const root = new vm.Script(code + '\n;buildAsset(THREE);').runInContext(ctx, { timeout: 10000 });
if (!root || !root.isObject3D) { console.error('buildAsset did not return a THREE.Object3D'); process.exit(1); }
root.updateMatrixWorld(true);
const meshes = [];
root.traverse(o => { if (o.isMesh && o.geometry?.attributes?.position) meshes.push(o); });
if (!meshes.length) { console.error('no meshes'); process.exit(1); }
const chunks = [], json = { asset: { version: '2.0', generator: 'lowpoly-coder-4b export_glb.mjs' }, scene: 0,
scenes: [{ name: root.name || 'asset', nodes: [] }], nodes: [], meshes: [], materials: [], accessors: [], bufferViews: [], buffers: [] };
let offset = 0, triangles = 0;
for (const m of meshes) {
const g = m.geometry.index ? m.geometry.toNonIndexed() : m.geometry;
const p = g.attributes.position, v = new THREE.Vector3();
const pos = new Float32Array(p.count * 3), mn = [Infinity, Infinity, Infinity], mx = [-Infinity, -Infinity, -Infinity];
for (let i = 0; i < p.count; i++) {
v.fromBufferAttribute(p, i).applyMatrix4(m.matrixWorld);
const a = [v.x, v.y, v.z];
for (let k = 0; k < 3; k++) { pos[i * 3 + k] = a[k]; mn[k] = Math.min(mn[k], a[k]); mx[k] = Math.max(mx[k], a[k]); }
}
if (!pos.every(Number.isFinite)) { console.error(`mesh "${m.name}" has non-finite coordinates`); process.exit(1); }
const mat = Array.isArray(m.material) ? m.material[0] : m.material, c = mat?.color ?? new THREE.Color(0.8, 0.8, 0.8);
json.materials.push({ name: mat?.name || m.name, pbrMetallicRoughness: { baseColorFactor: [c.r, c.g, c.b, 1],
metallicFactor: mat?.metalness ?? 0, roughnessFactor: mat?.roughness ?? 1 }, doubleSided: false });
json.bufferViews.push({ buffer: 0, byteOffset: offset, byteLength: pos.byteLength, target: 34962 });
json.accessors.push({ bufferView: json.bufferViews.length - 1, componentType: 5126, count: p.count, type: 'VEC3', min: mn, max: mx });
json.meshes.push({ name: m.name, primitives: [{ attributes: { POSITION: json.accessors.length - 1 }, material: json.materials.length - 1 }] });
json.nodes.push({ name: m.name || `mesh_${json.nodes.length}`, mesh: json.meshes.length - 1 });
json.scenes[0].nodes.push(json.nodes.length - 1);
chunks.push(Buffer.from(pos.buffer)); offset += pos.byteLength; triangles += p.count / 3;
}
json.buffers.push({ byteLength: offset });
const pad = (b, fill) => Buffer.concat([b, Buffer.alloc((4 - (b.length % 4)) % 4, fill)]);
const jsonBuf = pad(Buffer.from(JSON.stringify(json)), 0x20), binBuf = pad(Buffer.concat(chunks), 0);
const header = Buffer.alloc(12), jh = Buffer.alloc(8), bh = Buffer.alloc(8);
header.writeUInt32LE(0x46546c67, 0); header.writeUInt32LE(2, 4); header.writeUInt32LE(12 + 8 + jsonBuf.length + 8 + binBuf.length, 8);
jh.writeUInt32LE(jsonBuf.length, 0); jh.writeUInt32LE(0x4e4f534a, 4); bh.writeUInt32LE(binBuf.length, 0); bh.writeUInt32LE(0x004e4942, 4);
fs.writeFileSync(outPath, Buffer.concat([header, jh, jsonBuf, bh, binBuf]));
console.log(`wrote ${outPath}: ${meshes.length} meshes, ${triangles} triangles`);