#!/usr/bin/env node // Parses all reference GLBs in working/GLTFmodel and writes line-spec.json: // one teaching model per GLB, decomposed into 1-11 Box/Cylinder parts in // FreeCAD coordinates (Z-up, millimetres). // // Key difference from build-delta-spec.mjs: // - full node.matrix support (all 27 line GLBs store the root transform as a matrix) // - these GLBs are already Z-up (three.js exported from a Z-up scene), so the // axis map is identity, not DELTA's (x,-z,y) // - teaching-part clustering, dominant material per part, scene bbox self-check import fs from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { createHash } from "node:crypto"; const here = path.dirname(fileURLToPath(import.meta.url)); const sourceDir = process.argv[2] ?? "/home/mes123456/FreeCADWasmDev/working/GLTFmodel"; const outFile = path.join(here, "line-spec.json"); const inventoryFile = path.join(here, "line-inventory.md"); const overrides = JSON.parse(fs.readFileSync(path.join(here, "overrides.json"), "utf8")).models; const colorFile = path.join(here, "material-colors.json"); const sampledColors = fs.existsSync(colorFile) ? JSON.parse(fs.readFileSync(colorFile, "utf8")).files : {}; const roundMm = value => Math.round(value * 1000) / 1000; const toSrgb = value => value <= 0.0031308 ? 12.92 * value : 1.055 * Math.pow(value, 1 / 2.4) - 0.055; const toLinear = value => value <= 0.04045 ? value / 12.92 : Math.pow((value + 0.055) / 1.055, 2.4); // ---- 4x4 row-major helpers (glTF stores matrices column-major) ---- const identity = () => [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]; const mul = (a, b) => a.map((row, r) => [0, 1, 2, 3].map(c => row[0] * b[0][c] + row[1] * b[1][c] + row[2] * b[2][c] + row[3] * b[3][c])); const apply = (m, v) => [0, 1, 2].map(r => m[r][0] * v[0] + m[r][1] * v[1] + m[r][2] * v[2] + m[r][3]); const fromGltfMatrix = m => [0, 1, 2, 3].map(r => [0, 1, 2, 3].map(c => m[c * 4 + r])); const quatMatrix = q => { const [x, y, z, w] = q; return [ [1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w), 0], [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w), 0], [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y), 0], [0, 0, 0, 1], ]; }; const localMatrix = node => { if (node.matrix) return fromGltfMatrix(node.matrix); const m = quatMatrix(node.rotation ?? [0, 0, 0, 1]); const [tx, ty, tz] = node.translation ?? [0, 0, 0]; const [sx, sy, sz] = node.scale ?? [1, 1, 1]; m[0][3] = tx; m[1][3] = ty; m[2][3] = tz; for (let r = 0; r < 3; r++) { m[r][0] *= sx; m[r][1] *= sy; m[r][2] *= sz; } return m; }; const det3 = m => m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0]) + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]); const readGlb = file => { const buffer = fs.readFileSync(file); let offset = 12; let gltf = null; while (offset < buffer.length) { const length = buffer.readUInt32LE(offset); const type = buffer.toString("ascii", offset + 4, offset + 8); if (type === "JSON") gltf = JSON.parse(buffer.toString("utf8", offset + 8, offset + 8 + length)); offset += 8 + length; } if (!gltf) throw new Error(`no JSON chunk in ${file}`); return { buffer, gltf }; }; const materialInfo = (gltf, index, fileName) => { const material = gltf.materials?.[index]; if (!material) return { name: "", linear: [0.8, 0.8, 0.8], srgb: [0.906, 0.906, 0.906], colorSource: "default" }; const factor = material.pbrMetallicRoughness?.baseColorFactor?.slice(0, 3) ?? [1, 1, 1]; const sampled = sampledColors?.[fileName]?.[String(index)]; const srgb = sampled?.srgb ?? factor.map(toSrgb); return { name: material.name ?? `material-${index}`, linear: srgb.map(value => Math.round(toLinear(value) * 1e4) / 1e4), srgb: srgb.map(value => Math.round(value * 1e4) / 1e4), colorSource: sampled?.source ?? "baseColorFactor", }; }; const accessorBox = accessor => { if (!accessor?.min || !accessor?.max) return null; return { min: accessor.min.slice(0, 3), max: accessor.max.slice(0, 3) }; }; // ---- per-file analysis ---- const analyzeGlb = file => { const { buffer, gltf } = readGlb(file); const scene = gltf.scenes?.[gltf.scene ?? 0] ?? { nodes: [] }; const nodes = gltf.nodes ?? []; const meshes = gltf.meshes ?? []; const entries = []; const visit = (index, parentM, chain, top) => { const node = nodes[index]; const world = mul(parentM, localMatrix(node)); const name = node.name ?? `node-${index}`; const nextChain = [...chain, name]; if (node.mesh !== undefined) { const mesh = meshes[node.mesh]; const materialTris = new Map(); let triangles = 0; let bbox = null; for (const [primitiveIndex, primitive] of (mesh.primitives ?? []).entries()) { const accessor = gltf.accessors?.[primitive.attributes?.POSITION]; const box = accessorBox(accessor); const count = primitive.indices !== undefined ? gltf.accessors[primitive.indices].count / 3 : (accessor?.count ?? 0) / 3; triangles += count; if (primitive.material !== undefined) { materialTris.set(primitive.material, (materialTris.get(primitive.material) ?? 0) + count); } if (!box) continue; for (const x of [box.min[0], box.max[0]]) for (const y of [box.min[1], box.max[1]]) for (const z of [box.min[2], box.max[2]]) { const point = apply(world, [x, y, z]); if (!bbox) bbox = { min: point.slice(), max: point.slice() }; else for (let axis = 0; axis < 3; axis++) { bbox.min[axis] = Math.min(bbox.min[axis], point[axis]); bbox.max[axis] = Math.max(bbox.max[axis], point[axis]); } } entries.push({ key: `${index}:${primitiveIndex}`, nodeName: name, meshName: mesh.name ?? `mesh-${node.mesh}`, chain: nextChain, top, topName: nextChain[1] ?? nextChain[0] ?? name, bboxMm: bbox && { min: bbox.min.map(value => roundMm(value * 1000)), max: bbox.max.map(value => roundMm(value * 1000)), }, triangles: Math.round(count), materialTris, primitiveMaterial: primitive.material, }); bbox = null; } } for (const child of node.children ?? []) visit(child, world, nextChain, top ?? child); }; for (const rootIndex of scene.nodes ?? []) { const root = nodes[rootIndex]; const rootM = localMatrix(root); if (root.children?.length) { for (const child of root.children) visit(child, rootM, [root.name ?? `node-${rootIndex}`], child); } else { visit(rootIndex, identity(), [], rootIndex); } } // Dominant material per mesh entry. for (const entry of entries) { let best = entry.primitiveMaterial; let bestTris = -1; for (const [index, tris] of entry.materialTris) if (tris > bestTris) { best = index; bestTris = tris; } const material = materialInfo(gltf, best, path.basename(file)); entry.material = material.name; entry.color = material.srgb; entry.colorLinear = material.linear; entry.colorSource = material.colorSource; } return { buffer, gltf, entries }; }; const unionBox = items => items.reduce((box, item) => { if (!box) return { min: item.bboxMm.min.slice(), max: item.bboxMm.max.slice() }; for (let axis = 0; axis < 3; axis++) { box.min[axis] = Math.min(box.min[axis], item.bboxMm.min[axis]); box.max[axis] = Math.max(box.max[axis], item.bboxMm.max[axis]); } return box; }, null); const boxGap = (a, b) => { let sum = 0; for (let axis = 0; axis < 3; axis++) { const gap = Math.max(0, Math.max(a.min[axis] - b.max[axis], b.min[axis] - a.max[axis])); sum += gap * gap; } return Math.sqrt(sum); }; const boxCenter = box => [0, 1, 2].map(axis => (box.min[axis] + box.max[axis]) / 2); const centerDistance = (a, b) => { const ca = boxCenter(a); const cb = boxCenter(b); return Math.hypot(ca[0] - cb[0], ca[1] - cb[1], ca[2] - cb[2]); }; const clusterBox = cluster => unionBox(cluster); const mergeClosest = (clusters, target) => { const result = clusters.map(cluster => cluster.slice()); while (result.length > target) { let best = null; for (let i = 0; i < result.length; i++) for (let j = i + 1; j < result.length; j++) { const a = clusterBox(result[i]); const b = clusterBox(result[j]); const score = boxGap(a, b) + centerDistance(a, b) * 1e-6; if (!best || score < best.score) best = { i, j, score }; } result[best.i] = [...result[best.i], ...result[best.j]]; result.splice(best.j, 1); } return result; }; const splitLargest = (clusters, target) => { const result = clusters.map(cluster => cluster.slice()); while (result.length < target) { let index = -1; let size = 1; for (let i = 0; i < result.length; i++) if (result[i].length > size) { index = i; size = result[i].length; } if (index < 0) break; const parts = mergeClosest(result[index].map(entry => [entry]), 2); result.splice(index, 1, ...parts); } return result; }; const groupEntries = (entries, override) => { const byTop = new Map(); for (const entry of entries) { const topName = entry.topName ?? entry.nodeName; let key = entry.top; if (override.groupBy === "axis") key = /^[xyz]/i.test(topName) ? topName[0].toUpperCase() : "Other"; if (override.groupBy === "prefix") { key = override.prefixes.find(prefix => topName.startsWith(prefix)) ?? override.prefixes[0]; } if (!byTop.has(key)) byTop.set(key, []); byTop.get(key).push(entry); } let clusters = [...byTop.values()]; const budget = Math.max(1, Math.min(override.budget ?? clusters.length, entries.length)); if (clusters.length > budget) clusters = mergeClosest(clusters, budget); if (clusters.length < budget) clusters = splitLargest(clusters, budget); return { clusters, budget }; }; const sanitize = text => String(text).replace(/[^A-Za-z0-9_]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 32) || "Part"; const primitiveFor = (cluster, dims) => { const [x, y, z] = dims; // A cylinder is only allowed when its AABB would stay within tolerance: // the two cross-section dims must agree within 5% and Z must be the long axis. const square = Math.abs(x - y) <= Math.max(1, Math.min(x, y) * 0.05); if (!square) return "box"; if (z > Math.max(x, y) * 1.2) return "cylinder"; if (cluster.length === 1 && /料仓|电机|转盘|圆柱|轮|滚|灯|柱/.test(cluster[0].nodeName)) return "cylinder"; return "box"; }; const buildModel = (file, override) => { const { buffer, gltf, entries } = analyzeGlb(file); if (entries.length === 0) throw new Error(`no mesh entries in ${file}`); const overall = unionBox(entries); const { clusters, budget } = groupEntries(entries, override); const courseName = override.courseName ?? sanitize(path.basename(file, ".glb")); const label = override.label ?? path.basename(file, ".glb"); const parts = clusters.map((cluster, index) => { const box = unionBox(cluster); const dims = [0, 1, 2].map(axis => roundMm(box.max[axis] - box.min[axis])); const triangles = cluster.reduce((sum, entry) => sum + entry.triangles, 0); const materialCounts = new Map(); for (const entry of cluster) materialCounts.set(entry.material, (materialCounts.get(entry.material) ?? 0) + entry.triangles); let material = ""; let best = -1; for (const [name, count] of materialCounts) if (count > best) { material = name; best = count; } const colorEntry = cluster.find(entry => entry.material === material) ?? cluster[0]; const nodeNames = [...new Set(cluster.map(entry => entry.nodeName))]; return { partName: `${courseName}_P${String(index + 1).padStart(2, "0")}`, label: nodeNames.length === 1 ? nodeNames[0] : `${label} 部件 ${index + 1}`, primitive: primitiveFor(cluster, dims), fcLocalDims: dims, position: box.min.map(roundMm), rotation: { axis: [0, 0, 1], angleDeg: 0 }, worldBBox: [box.min[0], box.min[1], box.min[2], box.max[0], box.max[1], box.max[2]].map(roundMm), center: [0, 1, 2].map(axis => roundMm((box.min[axis] + box.max[axis]) / 2)), color: colorEntry.color, colorLinear: colorEntry.colorLinear, colorSource: colorEntry.colorSource, material, meshCount: new Set(cluster.map(entry => entry.key.split(":")[0])).size, triangleCount: Math.round(triangles), nodeNames: nodeNames.slice(0, 12), chain: cluster[0].chain, }; }); const modelBox = [overall.min[0], overall.min[1], overall.min[2], overall.max[0], overall.max[1], overall.max[2]] .map(roundMm); return { file: path.basename(file), name: courseName, label, sha256: createHash("sha256").update(buffer).digest("hex"), meshCount: new Set(entries.map(entry => entry.key.split(":")[0])).size, triangleCount: entries.reduce((sum, entry) => sum + entry.triangles, 0), partBudget: budget, overallBBox: modelBox, overallDims: [0, 1, 2].map(axis => roundMm(overall.max[axis] - overall.min[axis])), parts, }; }; const files = fs.readdirSync(sourceDir).filter(name => name.toLowerCase().endsWith(".glb")).sort(); const models = []; const warnings = []; for (const file of files) { const override = overrides[file]; if (!override) warnings.push(`no overrides entry for ${file}; using defaults`); models.push(buildModel(path.join(sourceDir, file), override ?? {})); } // Axis sanity check: the ground plane must span XY (4867 x 3673 mm) with a small Z thickness. const ground = models.find(model => model.file === "地面平面.glb"); if (ground) { const [x, y, z] = ground.overallDims; const ok = Math.abs(x - 4867.5) < 20 && Math.abs(y - 3673.2) < 20 && z < 400; if (!ok) throw new Error(`axis self-check failed: ground dims ${JSON.stringify(ground.overallDims)}; expected Z-up`); } const sceneMin = [0, 1, 2].map(axis => Math.min(...models.map(model => model.overallBBox[axis]))); const sceneMax = [0, 1, 2].map(axis => Math.max(...models.map(model => model.overallBBox[axis + 3]))); const sceneBBox = [...sceneMin, ...sceneMax].map(roundMm); const spec = { schema: "freecad-web-line-course/spec/v1", generatedAt: new Date().toISOString(), sourceDir, units: { sourceNumerics: "meters", target: "mm", upAxis: "Z-up (identity map, x*1000,y*1000,z*1000)" }, modelCount: models.length, partCount: models.reduce((sum, model) => sum + model.parts.length, 0), triangleCount: models.reduce((sum, model) => sum + model.triangleCount, 0), sceneBBox, warnings, models, }; fs.writeFileSync(outFile, `${JSON.stringify(spec, null, 2)}\n`); const lines = [ "# 生产线参考零件表", "", `生成时间:${spec.generatedAt}`, `模型数:${spec.modelCount},教学部件数:${spec.partCount},三角面:${spec.triangleCount}`, `整线包围盒(mm):${sceneBBox.map(value => value.toFixed(1)).join(", ")}`, "", "| 模型 | 文件 | 部件 | 尺寸 mm | 部件明细 |", "|---|---|---|---|---|", ]; for (const model of models) { const detail = model.parts.map(part => `${part.partName}(${part.primitive},${part.fcLocalDims.map(value => Math.round(value)).join("×")})`).join("; "); lines.push(`| ${model.label} | ${model.file} | ${model.parts.length} | ${model.overallDims.map(value => Math.round(value)).join("×")} | ${detail} |`); } fs.writeFileSync(inventoryFile, `${lines.join("\n")}\n`); // Small public index for the React reference viewer (GLBs are route-served, // never copied into public/dist). const publicIndex = path.resolve(here, "../../public/line/models.json"); fs.mkdirSync(path.dirname(publicIndex), { recursive: true }); fs.writeFileSync(publicIndex, `${JSON.stringify({ schema: "freecad-web-line-course/reference-models/v1", models: models.map(model => ({ file: model.file, name: model.name, label: model.label, dims: model.overallDims, parts: model.parts.length, })), }, null, 2)}\n`); console.log(JSON.stringify({ publicIndex, ok: true, outFile, inventoryFile, modelCount: spec.modelCount, partCount: spec.partCount, sceneBBox: spec.sceneBBox, warnings: warnings.length, }));