Files
vibemake/scripts/assemble-microban.mjs
T
Jerry 1c837766cd feat: integrate robot assembly and simulation with resilient loading
Add backend-driven assembly and simulation experiences, MAKE branding, mobile rendering budgets and desktop-only CAD/PCB routes. Improve logo loading progress, document image recovery and URDF request handling; include dev packaging and regression coverage.
2026-10-30 18:38:39 +08:00

189 lines
12 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Restore the supplied loose GLBs using the reference assembly, without changing their geometry/materials.
import { Document, NodeIO } from '@gltf-transform/core';
import { mergeDocuments, unpartition } from '@gltf-transform/functions';
import { Matrix4, Vector3, Quaternion } from '../vendor/three/build/three.module.min.js';
import { mkdirSync, readdirSync, readFileSync, writeFileSync, cpSync, rmSync } from 'node:fs';
import { join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { createHash } from 'node:crypto';
import { execFileSync } from 'node:child_process';
import assert from 'node:assert/strict';
import { validatePackage, validateEmbeddedGlb } from '../js/experience-packages.js';
const ROOT = fileURLToPath(new URL('..', import.meta.url));
const args = process.argv.slice(2);
const option = (name, fallback) => args.includes(name) ? args[args.indexOf(name) + 1] : fallback;
const SOURCE = resolve(option('--parts', '/Users/jerry/Downloads/glb分散零件'));
const REFERENCE = resolve(option('--reference', '/Users/jerry/Downloads/机器人.glb'));
const OUT = join(ROOT, 'deliverables/experience-packages');
const NAME = 'microban-parts-assembly';
const DIRECTORY = join(OUT, NAME);
const io = new NodeIO();
const sha = (bytes) => createHash('sha256').update(bytes).digest('hex');
const saveJson = (path, data) => writeFileSync(path, JSON.stringify(data, null, 2) + '\n');
const reference = await io.read(REFERENCE);
const references = new Map(reference.getRoot().listNodes().filter((node) => node.getMesh()).map((node) => [node.getName(), node]));
const sources = readdirSync(SOURCE).filter((name) => /\.glb$/i.test(name)).sort();
assert.equal(sources.length, references.size, '分件数量与参考总装不一致');
// The supplied exporters bake an extra -90° X rotation into loose geometry.
// Reversing it gives EXACTLY the same triangle surfaces as the reference.
const undoExportRotation = new Matrix4().makeRotationX(Math.PI / 2);
const displayQuaternion = [-Math.SQRT1_2, 0, 0, Math.SQRT1_2];
const root = new Document();
const scene = root.createScene('机器人 · 分件重组');
root.getRoot().setDefaultScene(scene);
const templates = new Map();
const files = [], records = [], parts = [];
let maxPositionError = 0, triangles = 0;
// Compare surfaces independently of vertex ordering, winding and material splits.
// Two supplied parts have different material splits but identical surfaces.
function surface(mesh, undoRotation) {
const counts = new Map();
let count = 0;
for (const primitive of mesh.listPrimitives()) {
assert.equal(primitive.getMode(), 4, '只支持三角网格');
const positions = primitive.getAttribute('POSITION').getArray();
const indices = primitive.getIndices()?.getArray() || Array.from({ length: positions.length / 3 }, (_, i) => i);
for (let i = 0; i < indices.length; i += 3) {
const vertices = [];
for (let k = 0; k < 3; k++) {
const offset = indices[i + k] * 3;
const [x, y, z] = positions.subarray(offset, offset + 3);
vertices.push((undoRotation ? [x, -z, y] : [x, y, z]).join(','));
}
const key = vertices.sort().join(';');
counts.set(key, (counts.get(key) || 0) + 1);
count++;
}
}
return { counts, count };
}
// Exported copies often differ only in object names. Keep one byte-identical
// source GLB per visual definition; each instance still has its original pose.
function visualFingerprint(bytes) {
const jsonLength = bytes.readUInt32LE(12);
const json = JSON.parse(bytes.subarray(20, 20 + jsonLength).toString());
const clean = (value) => Array.isArray(value) ? value.map(clean) : value && typeof value === 'object'
? Object.fromEntries(Object.keys(value).sort().filter((key) => key !== 'name').map((key) => [key, clean(value[key])])) : value;
const hash = createHash('sha256');
hash.update(JSON.stringify(clean(json)));
hash.update(bytes.subarray(20 + jsonLength));
return hash.digest('hex');
}
rmSync(DIRECTORY, { recursive: true, force: true });
mkdirSync(join(DIRECTORY, 'parts'), { recursive: true });
for (const filename of sources) {
const path = join(SOURCE, filename), bytes = readFileSync(path);
validateEmbeddedGlb(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.length));
const source = await io.read(path);
assert.equal(source.getRoot().listNodes().length, 1, `分件层级改变:${filename}`);
const node = source.getRoot().listNodes()[0];
assert.deepEqual(node.getMatrix(), new Matrix4().toArray(), `分件已带额外变换:${filename}`);
const target = references.get(node.getName());
assert.ok(target, `无法匹配:${filename}`);
const a = surface(target.getMesh(), false), b = surface(node.getMesh(), true);
assert.equal(a.count, b.count, `三角面数量改变:${filename}`);
assert.equal(a.counts.size, b.counts.size, `表面不匹配:${filename}`);
for (const [key, count] of a.counts) assert.equal(b.counts.get(key), count, `表面不匹配:${filename}`);
triangles += a.count;
const referenceWorld = new Matrix4().fromArray(target.getWorldMatrix());
const expected = referenceWorld.clone().multiply(undoExportRotation);
const position = new Vector3(), rotation = new Quaternion(), scale = new Vector3();
expected.decompose(position, rotation, scale);
rotation.normalize();
const restored = new Matrix4().compose(position, rotation, scale);
let error = 0;
for (const primitive of node.getMesh().listPrimitives()) {
const positions = primitive.getAttribute('POSITION').getArray();
for (let i = 0; i < positions.length; i += 3) {
const point = new Vector3().fromArray(positions, i);
error = Math.max(error, point.clone().applyMatrix4(expected).distanceTo(point.applyMatrix4(restored)));
}
}
assert.ok(error < 1e-6, `恢复后的顶点误差过大:${filename} ${error}`);
maxPositionError = Math.max(maxPositionError, error);
const fingerprint = visualFingerprint(bytes);
let template = templates.get(fingerprint);
if (!template) {
const file = `parts/${filename}`;
cpSync(path, join(DIRECTORY, file));
files.push({ path: file, bytes: bytes.length, sha256: sha(bytes) });
const copied = mergeDocuments(root, source);
const mesh = copied.get(node).getMesh();
copied.get(source.getRoot().listScenes()[0]).dispose();
copied.get(node).dispose();
template = { file, mesh };
templates.set(fingerprint, template);
}
const id = `part-${String(parts.length + 1).padStart(3, '0')}`;
const part = { id, file: template.file, position: position.toArray(), quaternion: rotation.toArray(), scale: scale.toArray(),
installOffset: [0.035, position.y > 0 ? 0.055 : -0.055, 0.035] };
parts.push(part);
scene.addChild(root.createNode(node.getName()).setMesh(template.mesh).setTranslation(part.position).setRotation(part.quaternion).setScale(part.scale));
records.push({ id, source: filename, sourceSha256: sha(bytes), file: part.file, referenceNode: target.getName(),
referenceGroup: target.getParentNode()?.getName(), triangleCount: a.count, maxPositionErrorMeters: error, surfaceMatches: true });
}
assert.equal(new Set(records.map((record) => record.referenceNode)).size, references.size, '存在重复匹配或缺件');
const groups = [
['foot _1_', '脚部 1'], ['foot _2_', '脚部 2'], ['ankle_block _2_', '踝部 1'], ['ankle_block _3_', '踝部 2'],
['tibia _1_', '小腿 1'], ['tibia _2_', '小腿 2'], ['femur _1_', '大腿 1'], ['femur _2_', '大腿 2'],
['hip_block _1_', '髋部支架 1'], ['hip_block _3_', '髋部支架 2'], ['hip _1_', '髋部 1'], ['hip _2_', '髋部 2'],
['trunk _1_', '躯干'], ['shoulder _1_', '肩部 1'], ['shoulder _2_', '肩部 2'],
['humerus _1_', '上臂 1'], ['humerus _2_', '上臂 2'], ['radius _1_', '前臂 1'], ['radius _2_', '前臂 2'], ['head _1_', '头部'],
];
const label = (name) => {
for (const [pattern, value] of [[/^(STP39|BTS2)/, '螺钉'], [/^XL330/, '舵机'], [/^(foot)/, '脚板'], [/^tibia/, '小腿外壳'], [/^femur/, '大腿外壳'], [/^chest/, '胸部面板'], [/^head/, '头部外壳'], [/^raspberry/, '主控板'], [/^battery/, '电池'], [/^switch/, '开关'], [/^(.*shim|washer)/, '垫片'], [/^spacer/, '隔柱'], [/^DC15/, '关节连接件']]) if (pattern.test(name)) return value;
return '结构零件';
};
const rank = (name) => /^(STP39|BTS2)/.test(name) ? 4 : /(shim|washer|spacer|DC15)/.test(name) ? 3 : /^XL330/.test(name) ? 1 : 0;
const ordered = groups.flatMap(([group, title]) => records.filter((item) => item.referenceGroup === group)
.sort((a, b) => rank(a.source) - rank(b.source) || a.source.localeCompare(b.source, 'en', { numeric: true }))
.map((item) => ({ ...item, title })));
assert.equal(ordered.length, parts.length, '存在未编排的子总成');
const steps = ordered.map((item, i) => ({ id: `step-${i + 1}`, label: `${item.title} · ${label(item.source)}`, parts: [item.id] }));
const manifest = { schemaVersion: 1, kind: 'assembly', title: 'Microban · 275 零件装配', unit: 'meter', displayQuaternion, files, parts, steps };
validatePackage(manifest, 'assembly', `https://assets.example.com/${NAME}/manifest.json`);
saveJson(join(DIRECTORY, 'manifest.json'), manifest);
const report = { referenceSha256: sha(readFileSync(REFERENCE)), partCount: parts.length, uniqueGlbs: files.length,
triangleCount: triangles, maxPositionErrorMeters: maxPositionError, allTriangleSurfacesMatch: true,
materialSource: 'Unmodified supplied loose GLBs; these differ from the reference model materials.',
coordinateMethod: 'Reference world matrix × inverse of loose-export X(-90deg) rotation; no independent centering/scaling.',
stepOrder: 'Presentation sequence by source subassembly, not a validated manufacturing process.', parts: records };
saveJson(join(DIRECTORY, 'alignment-report.json'), report);
writeFileSync(join(DIRECTORY, 'README.txt'), `Microban 分件装配包\n\n${parts.length} 个零件实例,根据完整机器人 GLB 的原始变换恢复。\n${files.length} 个独立 GLB:几何、材质和内嵌变换完全相同的分件复用一份原文件,减少下载与解析。\n所有模型三角面已逐件核对;总计 ${triangles} 个三角面。\n恢复位置的最大数值误差:${maxPositionError.toExponential(3)} 米。\nGLB 原文件与材质未改动。新分件的材质与旧整机有所不同,预览使用新分件自带材质。\n完整校验映射见 alignment-report.json。\n\n上传此 ZIP,后端解压后将 manifest.json 的地址写入 assemblyManifestUrl。\n显示整体时,275 个实例按原始位置组成机器人。逐步装配时,每步安装一个零件,可播放、暂停或拖动进度。\n安装最终位置来自原模型;显示顺序按子总成编排,用于展示,不代表已验证的制造工艺。\n`);
await root.transform(unpartition());
const assembledFile = join(OUT, 'microban-reassembled.glb');
await io.write(assembledFile, root);
// Verify that serializing the combined GLB has not changed any recovered pose.
const reread = await io.read(assembledFile);
assert.equal(reread.getRoot().listNodes().filter((node) => node.getMesh()).length, parts.length);
let exportedPositionError = 0;
for (const node of reread.getRoot().listNodes()) {
const expected = new Matrix4().fromArray(references.get(node.getName()).getWorldMatrix()).multiply(undoExportRotation);
const exported = new Matrix4().fromArray(node.getWorldMatrix());
for (const primitive of node.getMesh().listPrimitives()) {
const positions = primitive.getAttribute('POSITION').getArray();
for (let i = 0; i < positions.length; i += 3) {
const point = new Vector3().fromArray(positions, i);
exportedPositionError = Math.max(exportedPositionError, point.clone().applyMatrix4(expected).distanceTo(point.applyMatrix4(exported)));
}
}
}
assert.ok(exportedPositionError < 1e-6, '合并 GLB 导出后的顶点误差过大');
report.combinedGlbPositionErrorMeters = exportedPositionError;
report.combinedGlbSha256 = sha(readFileSync(assembledFile));
saveJson(join(DIRECTORY, 'alignment-report.json'), report);
const zip = join(OUT, NAME + '.zip');
rmSync(zip, { force: true });
execFileSync('zip', ['-q', '-r', zip, '.'], { cwd: DIRECTORY });
execFileSync('unzip', ['-tq', zip]);
console.log(JSON.stringify({ package: zip, combined: assembledFile, parts: parts.length, uniqueGlbs: files.length,
triangles, maxPositionErrorMeters: maxPositionError, packageMB: readFileSync(zip).length / 1048576 }, null, 2));