1c837766cd
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.
156 lines
10 KiB
JavaScript
156 lines
10 KiB
JavaScript
// Numbered CAD supplies order/placements; the existing GLBs and materials stay intact.
|
||
import { readFileSync, writeFileSync, readdirSync, mkdirSync, copyFileSync, constants } from 'node:fs';
|
||
import { join } from 'node:path';
|
||
import { createHash } from 'node:crypto';
|
||
import assert from 'node:assert/strict';
|
||
import { Matrix4, Vector3, Quaternion } from 'three';
|
||
import { stepPlacements } from './lib/step-placements.mjs';
|
||
import { validatePackage, validateEmbeddedGlb } from '../js/experience-packages.js';
|
||
|
||
const previous = '/Users/jerry/Downloads/小鸭子-扳手装配';
|
||
const assets = join(previous, '零件模型');
|
||
const leftSource = '/Users/jerry/Downloads/小鸭子-52步装配-当前上传/小鸭子-左腿-52步装配.json';
|
||
const rightInput = '/Users/jerry/Downloads/2-0腿装配(R)stp';
|
||
const trunkInput = '/Users/jerry/Downloads/躯干顺序(stp)';
|
||
const preview = new URL('../deliverables/experience-packages/microduck-numbered-body/', import.meta.url).pathname;
|
||
const original = JSON.parse(readFileSync(join(previous, '鸭子-拼装步骤-带扳手.json')));
|
||
const alignment = JSON.parse(readFileSync(new URL('../deliverables/experience-packages/microduck-parts-assembly/alignment-report.json', import.meta.url)));
|
||
const raw = JSON.parse(readFileSync(leftSource));
|
||
const byId = new Map(original.parts.map(p => [p.id, p]));
|
||
const id = n => `duck-part-${String(n).padStart(3, '0')}`;
|
||
const canonical = name => name.replace(/^镜向/, '').replace(/^0914舵机装配1$/, '0914舵机装配');
|
||
const matrix = p => new Matrix4().compose(new Vector3(...p.position), new Quaternion(...p.quaternion), new Vector3(...p.scale));
|
||
const display = new Quaternion(...raw.displayQuaternion);
|
||
const clean = a => a.map(n => Math.abs(n) < 1e-12 ? 0 : n);
|
||
const notes = JSON.parse(readFileSync(new URL('../deliverables/experience-packages/microduck-left-numbered/directions-52.notes.json', import.meta.url))).steps;
|
||
const records = [], rightParts = [], rightSteps = [];
|
||
const cad = stepPlacements(join(rightInput, '2-0-腿装配 (R).STEP'));
|
||
const numbered = cad.top.map(o => {
|
||
const m = /^2-(\d+)-(.+)$/.exec(o.name); assert.ok(m, o.name);
|
||
return { ...o, n: +m[1], label: m[2] };
|
||
}).sort((a, b) => a.n - b.n);
|
||
assert.deepEqual(numbered.map(o => o.n), Array.from({ length: 52 }, (_, i) => i + 1));
|
||
// Independent STEP filenames confirm the list, including mirrored names in the total assembly.
|
||
for (const o of numbered) assert.ok(readdirSync(rightInput).some(f =>
|
||
f.startsWith(`2-${o.n}-`) && canonical(f.replace(/^2-\d+-/, '').replace(/\.step$/i, '')) === canonical(o.label)), o.name);
|
||
const groups = new Map();
|
||
for (const a of alignment.parts.filter(p => p.group === '腿装配 (R)')) {
|
||
const key = a.path[2];
|
||
if (!groups.has(key)) groups.set(key, { key, label: canonical(key.split('@')[0]), parts: [] });
|
||
groups.get(key).parts.push(byId.get(a.id));
|
||
}
|
||
const used = new Set(), matched = new Map();
|
||
const candidates = o => [...groups.values()].filter(g => !used.has(g.key) && g.label === canonical(o.label));
|
||
const distance = (o, g) => new Vector3().setFromMatrixPosition(o.matrix).distanceTo(new Vector3(...g.parts[0].position));
|
||
// Reserve exact matches first so moved screws cannot steal another step's instance.
|
||
for (const o of numbered) {
|
||
const near = candidates(o).filter(g => distance(o, g) < 0.0001);
|
||
assert.ok(near.length <= 1, `Ambiguous exact match: ${o.name}`);
|
||
if (near.length) { used.add(near[0].key); matched.set(o.n, near[0]); }
|
||
}
|
||
for (const o of numbered.filter(o => !matched.has(o.n))) {
|
||
const options = candidates(o).sort((a, b) => /螺钉/.test(o.label)
|
||
? a.parts[0].file.localeCompare(b.parts[0].file, 'en', { numeric: true }) : distance(o, a) - distance(o, b));
|
||
assert.ok(options.length, `No matching GLB: ${o.name}`);
|
||
if (!/螺钉/.test(o.label)) {
|
||
assert.ok(distance(o, options[0]) < 0.005, `Unexplained changed component: ${o.name}`);
|
||
assert.ok(options.length === 1 || distance(o, options[1]) > distance(o, options[0]) + 0.001);
|
||
}
|
||
used.add(options[0].key); matched.set(o.n, options[0]);
|
||
}
|
||
|
||
function screwOffset(p) {
|
||
return clean(new Vector3(...(p.installation?.axis ?? [0, 0, -1])).negate().normalize()
|
||
.multiplyScalar(0.020).applyQuaternion(new Quaternion(...p.quaternion)).toArray());
|
||
}
|
||
for (const o of numbered) {
|
||
const g = matched.get(o.n), selected = structuredClone(g.parts);
|
||
const delta = o.matrix.clone().multiply(matrix(g.parts[0]).invert());
|
||
for (const p of selected) {
|
||
const position = new Vector3(), q = new Quaternion(), scale = new Vector3();
|
||
delta.clone().multiply(matrix(p)).decompose(position, q, scale);
|
||
assert.ok(scale.toArray().every(v => Math.abs(v - 1) < 1e-8));
|
||
p.position = clean(position.toArray()); p.quaternion = clean(q.normalize().toArray());
|
||
}
|
||
// Mirror the previously revised left-leg approach as a starting preference only.
|
||
// The optimizer checks the actual right GLBs and all previously installed parts.
|
||
const leftPart = raw.parts.find(p => p.id === raw.steps[o.n - 1].parts[0]);
|
||
const offset = [...leftPart.installOffset]; offset[2] *= -1;
|
||
selected.forEach(p => { p.installOffset = /螺钉/.test(o.label) ? screwOffset(p) : offset; });
|
||
const step = { id: `right-2-${o.n}`, label: `2-${o.n} · ${o.label}`, parts: selected.map(p => p.id) };
|
||
rightParts.push(...selected); rightSteps.push(step);
|
||
records.push({ code: `2-${o.n}`, files: selected.map(p => p.file), ids: step.parts,
|
||
placement: '本次右腿编号总装矩阵', displacementMm: distance(o, g) * 1000,
|
||
previousPositions: g.parts.map(p => p.position), positions: selected.map(p => p.position) });
|
||
notes.push({ label: step.label, reason: /螺钉/.test(o.label)
|
||
? '沿螺丝自身轴线进入,保留已有工具动画'
|
||
: '采用本次右腿总装位置;以左腿修订方向的镜像作为轴向优化初始值' });
|
||
}
|
||
assert.equal(rightParts.length, 72);
|
||
|
||
// Trunk files encode order, not instance placement. Reuse original whole-robot poses.
|
||
// Repeated fasteners moved into the numbered legs need NEW instances here, with their
|
||
// original hip locations; reuse their unchanged GLB rather than moving the leg screw.
|
||
const trunkMap = new Map([
|
||
[1,[14]], [2,[17,18,19]], [3,[36]], [4,[37]], [5,[20,21,22]], [6,[39]], [7,[40]],
|
||
[8,[1,2,3,4,5]], [9,[6,7,8,9,10]], [10,[283]],
|
||
[11,[241]], [12,[287]], [13,[288]], [14,[289]], [15,[290]], [16,[291]],
|
||
[17,[284]], [18,[285]], [19,[282]], [20,[286]], [21,[292]], [22,[114]],
|
||
[23,[121]], [24,[122]], [25,[123]], [26,[124]], [27,[125]], [28,[126]],
|
||
[29,[119]], [30,[120]], [31,[113]], [32,[117]], [33,[118]],
|
||
[34,[13]], [35,[12]],
|
||
// 3-36 / 3-37 intentionally omitted: user confirmed skipping these two unknown poses.
|
||
[38,[43]], [39,[24]], [40,[44]], [41,[45]], [42,[46]],
|
||
[43,[15]], [44,[16]], [45,[41]], [46,[35]], [47,[38]],
|
||
]);
|
||
const expectedLabels = new Map([...trunkMap].map(([n, ids]) => [n,
|
||
[2,5].includes(n) ? '0914舵机装配' : [8,9].includes(n) ? 'w_61702-2rs1'
|
||
: byId.get(id(ids[0])).file.replace(/(?:\.\d+)?\.glb$/, '')]));
|
||
const trunkFiles = readdirSync(trunkInput).filter(f => /\.step$/i.test(f));
|
||
assert.equal(trunkFiles.length, 47);
|
||
const trunkParts = [], trunkSteps = [];
|
||
const bodyPreferred = new Map([
|
||
[1,[-1,0,0]], [2,[-1,0,0]], [5,[-1,0,0]],
|
||
[8,[1,0,0]], [9,[1,0,0]], [10,[-1,0,0]], [22,[-1,0,0]],
|
||
[34,[0,-1,0]], [35,[0,-1,0]], [38,[0,1,0]], [43,[0,0,1]], [44,[0,0,-1]],
|
||
]);
|
||
for (const [n, ids] of trunkMap) {
|
||
const label = expectedLabels.get(n), source = `3-${n}${label}.step`;
|
||
assert.ok(trunkFiles.includes(source), `Missing numbered source: ${source}`);
|
||
const selected = ids.map((num, i) => ({ ...structuredClone(byId.get(id(num))), id: `trunk-3-${n}-part-${i+1}` }));
|
||
const screw = selected.every(p => /螺钉/.test(p.file));
|
||
assert.ok(screw || bodyPreferred.has(n));
|
||
for (const p of selected) p.installOffset = screw ? screwOffset(p)
|
||
: new Vector3(...bodyPreferred.get(n)).multiplyScalar(0.055).toArray();
|
||
const step = { id: `trunk-3-${n}`, label: `3-${n} · ${label}`, parts: selected.map(p => p.id) };
|
||
trunkParts.push(...selected); trunkSteps.push(step);
|
||
records.push({ code: `3-${n}`, source, files: selected.map(p => p.file), ids: step.parts,
|
||
originalIds: ids.map(id), placement: '原整机对应部件/配套孔位;重复同规格件按组件分组顺序', positions: selected.map(p => p.position) });
|
||
notes.push({ label: step.label, reason: screw ? '原整机孔位,沿螺丝自身轴线进入;同规格紧固件复用 GLB、实例独立'
|
||
: '保持原整机最终位置;按前面已经安装的左右腿与躯干零件优化进入方向' });
|
||
}
|
||
assert.equal(trunkSteps.length, 45); assert.equal(trunkParts.length, 57);
|
||
const parts = [...raw.parts, ...rightParts, ...trunkParts];
|
||
const steps = [...raw.steps, ...rightSteps, ...trunkSteps];
|
||
const files = new Set([...parts.map(p => p.file), ...raw.tools.map(t => t.file)]);
|
||
const manifest = { ...raw, title: 'Microduck · 左腿、右腿、躯干编号装配(149步)',
|
||
files: original.files.filter(f => files.has(f.path)), parts, steps };
|
||
assert.equal(steps.length, 149); assert.equal(parts.length, 201);
|
||
assert.equal(new Set(parts.map(p => p.id)).size, parts.length);
|
||
validatePackage(manifest, 'assembly', 'http://localhost:8090/manifest.json');
|
||
mkdirSync(preview, { recursive: true });
|
||
for (const f of manifest.files) {
|
||
const bytes = readFileSync(join(assets, f.path));
|
||
assert.equal(bytes.length, f.bytes);
|
||
assert.equal(createHash('sha256').update(bytes).digest('hex'), f.sha256);
|
||
validateEmbeddedGlb(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength));
|
||
copyFileSync(join(assets, f.path), join(preview, f.path), constants.COPYFILE_FICLONE);
|
||
}
|
||
const save = (name, data) => writeFileSync(join(preview, name), JSON.stringify(data, null, 2)+'\n');
|
||
save('input.json', manifest);
|
||
save('input.notes.json', { steps: notes });
|
||
save('mapping.json', { sources: { leftSource, rightInput, trunkInput }, steps: records,
|
||
skipped: ['3-36', '3-37'], skipReason: '无唯一安装位置;用户确认先跳过,保留其他编号' });
|
||
console.log(JSON.stringify({ preview, steps: steps.length, parts: parts.length, files: files.size,
|
||
rightChangedPositions: records.filter(r => r.displacementMm > .1).map(r => [r.code,r.displacementMm]), skipped:['3-36','3-37'] }, null, 2));
|