Files
vibemake/scripts/assemble-microduck.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

163 lines
11 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.
// Recover the supplied GLBs' assembly poses from their matching SolidWorks STEP.
// GLB bytes (including materials, colors and textures) are never rewritten.
import { readFileSync, writeFileSync, readdirSync, mkdirSync, copyFileSync, constants } from 'node:fs';
import { resolve, join, extname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { execFileSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import assert from 'node:assert/strict';
import { Matrix4, Vector3, Quaternion } from '../vendor/three/build/three.module.min.js';
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/鸭子.zip'));
const output = resolve(option('--out', join(ROOT, 'deliverables/experience-packages/microduck-parts-assembly')));
const sha = (value) => createHash('sha256').update(value).digest('hex');
const save = (path, data) => writeFileSync(path, JSON.stringify(data, null, 2) + '\n');
const stepBytes = extname(reference).toLowerCase() === '.zip'
? execFileSync('python3', ['-c', "import sys,zipfile; z=zipfile.ZipFile(sys.argv[1]); n=[n for n in z.namelist() if n.lower().endswith(('.step','.stp'))]; assert len(n)==1; sys.stdout.buffer.write(z.read(n[0]))", reference], { maxBuffer: 100 * 1024 * 1024 })
: readFileSync(reference);
// Names are STEP X2 escapes; ASCII parsing preserves all geometry/assembly data.
const entities = new Map([...stepBytes.toString('latin1').matchAll(/#(\d+)\s*=\s*([\s\S]*?);/g)].map((m) => [m[1], m[2]]));
const refs = (id) => [...entities.get(id).matchAll(/#(\d+)/g)].map((m) => m[1]);
const decode = (name) => name.replace(/\\X2\\(.*?)\\X0\\/g, (_, hex) => String.fromCharCode(...hex.match(/.{4}/g).map((x) => parseInt(x, 16))));
const names = new Map();
for (const [id, entity] of entities) if (/^PRODUCT_DEFINITION\s*\(/.test(entity)) {
const product = entities.get(refs(refs(id)[0])[0]);
names.set(id, decode(product.match(/'([^']*)'/)[1]));
}
function vector(id) {
const inner = [...entities.get(id).matchAll(/\(([^()]*)\)/g)].at(-1)[1];
return new Vector3(...inner.split(',').map(Number));
}
function axis(id) {
const [p, z, x] = refs(id).map(vector);
const y = new Vector3().crossVectors(z, x);
return new Matrix4().makeBasis(x, y, z).setPosition(p);
}
const occurrences = [];
for (const [id, entity] of entities) if (/^CONTEXT_DEPENDENT_SHAPE_REPRESENTATION\s*\(/.test(entity)) {
const [relation, definition] = refs(id), occurrence = refs(definition)[0];
const [parent, child] = refs(occurrence);
const [a, b] = refs(refs(relation).at(-1));
occurrences.push({ id: occurrence, parent, child, matrix: axis(a).multiply(axis(b).invert()) });
}
occurrences.sort((a, b) => Number(a.id) - Number(b.id));
const children = new Map();
for (const item of occurrences) {
if (!children.has(item.parent)) children.set(item.parent, []);
children.get(item.parent).push(item);
}
const roots = [...names.keys()].filter((id) => !occurrences.some((item) => item.child === id));
assert.equal(roots.length, 1, 'STEP 必须只有一个总装根节点');
const leaves = [];
function walk(id, matrix, path) {
if (!children.has(id)) leaves.push({ label: names.get(id), matrix, path });
else for (const child of children.get(id)) walk(child.child, matrix.clone().multiply(child.matrix), [...path, `${names.get(child.child)}@${child.id}`]);
}
walk(roots[0], new Matrix4(), [names.get(roots[0])]);
const filenames = readdirSync(source).filter((name) => /\.glb$/i.test(name));
const baseName = (name) => name.slice(0, -4).replace(/\.\d{3}$/, '');
const suffix = (name) => Number(name.match(/\.(\d{3})\.glb$/i)?.[1] ?? 0);
const sources = new Map();
for (const filename of filenames) {
const base = baseName(filename);
if (!sources.has(base)) sources.set(base, []);
sources.get(base).push(filename);
}
for (const [label, files] of sources) {
files.sort((a, b) => suffix(a) - suffix(b));
assert.equal(files.length, leaves.filter((leaf) => leaf.label === label).length, `零件数量不匹配:${label}`);
}
assert.equal(filenames.length, leaves.length, 'GLB 与 STEP 实例数量不匹配');
mkdirSync(output, { recursive: true });
const files = [], parts = [], records = [];
const used = new Map();
for (const [index, leaf] of leaves.entries()) {
const occurrenceIndex = used.get(leaf.label) ?? 0;
const filename = sources.get(leaf.label)?.[occurrenceIndex];
assert.ok(filename, `缺少分件:${leaf.label}`);
used.set(leaf.label, occurrenceIndex + 1);
const bytes = readFileSync(join(source, filename));
validateEmbeddedGlb(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.length));
const glb = JSON.parse(bytes.subarray(20, 20 + bytes.readUInt32LE(12)).toString());
assert.equal(glb.nodes.length, 1, `GLB 层级已改变:${filename}`);
assert.ok(!['matrix', 'translation', 'rotation', 'scale'].some((key) => key in glb.nodes[0]), `GLB 已带额外变换:${filename}`);
const matrix = leaf.matrix.clone();
for (const n of [12, 13, 14]) matrix.elements[n] /= 1000; // STEP millimeters → GLB meters.
const position = new Vector3(), quaternion = new Quaternion(), scale = new Vector3();
matrix.decompose(position, quaternion, scale);
quaternion.normalize();
assert.ok(scale.toArray().every((n) => Math.abs(n - 1) < 1e-8), `STEP 包含非刚性变换:${filename}`);
const restored = new Matrix4().compose(position, quaternion, new Vector3(1, 1, 1));
assert.ok(Math.max(...matrix.elements.map((n, i) => Math.abs(n - restored.elements[i]))) < 1e-8);
const group = leaf.path[1].split('@')[0];
let offset;
if (/螺钉/.test(leaf.label)) offset = new Vector3(0, 0, 0.025).applyQuaternion(quaternion);
else if (/^w_61702/.test(leaf.label)) offset = new Vector3(0.025, 0, 0).applyQuaternion(quaternion);
else if (/腿/.test(group)) offset = new Vector3(0, 0, position.z >= 0 ? 0.055 : -0.055);
else if (/嘴/.test(group)) offset = new Vector3(0, 0.055, 0);
else if (/头|脖/.test(group)) offset = new Vector3(-0.055, 0, 0);
else offset = new Vector3(0, 0.055, 0);
const part = { id: `duck-part-${String(index + 1).padStart(3, '0')}`, file: filename, parentId: null,
position: position.toArray(), quaternion: quaternion.toArray(), scale: [1, 1, 1], installOffset: offset.toArray() };
parts.push(part);
files.push({ path: filename, bytes: bytes.length, sha256: sha(bytes) });
copyFileSync(join(source, filename), join(output, filename), constants.COPYFILE_FICLONE);
assert.equal(sha(readFileSync(join(output, filename))), sha(bytes), '复制后 GLB 内容发生变化');
records.push({ ...leaf, matrix: matrix.toArray(), id: part.id, file: filename, group,
sourceNode: glb.nodes[0].name, materials: (glb.materials ?? []).map((material) => material.name), sha256: sha(bytes) });
}
// Display sequence, not a collision-checked manufacturing process.
// Repeated fasteners/servo components/bearing components are installed as groups.
const groupOrder = ['躯干装配', '腿装配 (R)', '腿装配(L)', '脖子装配', '头部', '嘴装配'];
const prettyGroup = (name) => ({ '腿装配 (R)': '右腿', '腿装配(L)': '左腿', '躯干装配': '躯干', '脖子装配': '颈部', '嘴装配': '嘴部' })[name] || name;
const rank = (name) => /^(trunk_base|foot_left|镜向foot_left)$/.test(name) ? 0 : /螺钉/.test(name) ? 5 : /shell/.test(name) ? 4 : /^(主舵|副舵|舵机主体)$/.test(name) ? 2 : /^w_|轴承/.test(name) ? 3 : 1;
const labels = {
trunk_base: '躯干底架', banana_pcb_locker: '板卡固定件', np_f970: '电池', power_support: '电源支架',
right_shell: '右侧外壳', '镜向left_shell': '左侧外壳', IMU: '惯性传感器', trunk_shell_left: '躯干盖板',
foot_left: '左脚脚板', '镜向foot_left': '右脚脚板', sole_left: '左脚鞋底', '镜向sole_left': '右脚鞋底',
ankle_left: '左踝支架', '镜向ankle_left': '右踝支架', left_upper_leg: '左大腿支架', '镜向left_upper_leg': '右大腿支架',
hip_I: '髋部连接件', leg: '腿部连杆', bearing_roll: '轴承支架', yaw2roll: '关节连接件',
upper_leg_rigidity_plate: '左大腿加强板', '镜向upper_leg_rigidity_plate': '右大腿加强板',
neck_holder: '颈部支架', 'neck_pitch-1': '颈部俯仰连接件', motor_support: '头部电机支架',
m12_lens_holder: '镜头固定座', lens: '镜头', face_part: '头部前面板', yaw_roll_motion: '头部转动连接件',
'noenoeil-': '眼部组件', 'bottom_head_shell-2': '头部下壳', 'top_head_shell-2': '头部上壳',
'BU elec_rpi_robot_hat_without_header': '无排针控制板', elec_rpi_robot_hat_with_header: '带排针控制板',
soft_mouth_top: '上嘴软质件', jaw: '下颌支架', jaw_soft: '下嘴软质件',
};
const steps = [];
for (const group of groupOrder) {
const batches = new Map();
for (const item of records.filter((r) => r.group === group)) {
const parentPath = item.path.slice(0, -1).join('/');
const kind = /^(主舵|副舵|舵机主体)$/.test(item.label) ? '舵机组件' : /^w_61702/.test(item.label) ? '轴承组件' : item.label;
const key = `${parentPath}/${kind}`;
if (!batches.has(key)) batches.set(key, { label: kind, parts: [], rank: rank(item.label) });
batches.get(key).parts.push(item.id);
}
for (const batch of [...batches.values()].sort((a, b) => a.rank - b.rank)) {
steps.push({ id: `duck-step-${String(steps.length + 1).padStart(3, '0')}`, label: `${prettyGroup(group)} · ${labels[batch.label] || batch.label}${batch.parts.length > 1 ? `(${batch.parts.length} 件)` : ''}`, parts: batch.parts });
}
}
const manifest = { schemaVersion: 1, kind: 'assembly', title: 'Microduck · 292 零件装配', unit: 'meter',
// Original STEP uses -X as up. Rotate the entire assembly once for the viewer.
displayQuaternion: [0, 0, -Math.SQRT1_2, Math.SQRT1_2], files, parts, steps };
validatePackage(manifest, 'assembly', 'https://assets.example.com/microduck/manifest.json');
save(join(output, 'manifest.json'), manifest);
save(join(output, 'alignment-report.json'), {
stepSha256: sha(stepBytes), partCount: parts.length, typeCount: sources.size, stepCount: steps.length,
method: 'STEP parent × child placements; translations converted from millimeters to meters. GLB local axes checked against the matching CAD surfaces.',
repeatedInstances: 'Same-name copies assigned in numeric GLB filename order to STEP occurrence traversal order. Exported loose GLBs have no original instance transforms.',
materials: 'Every supplied GLB is copied byte-for-byte; no material, texture, color or geometry overrides.',
sequence: 'Presentation sequence and insertion offsets; not a validated manufacturing or collision-free procedure.',
parts: records.map(({ matrix, ...record }) => ({ ...record, worldMatrix: matrix })),
});
console.log(JSON.stringify({ output, files: files.length, parts: parts.length, steps: steps.length,
totalMiB: files.reduce((sum, file) => sum + file.bytes, 0) / 1048576 }, null, 2));