Files
vibemake/scripts/enrich-numbered-assembly.mjs

148 lines
11 KiB
JavaScript

// Add presentation entry moves and measured tool docking without re-exporting GLBs.
// Usage: node scripts/enrich-numbered-assembly.mjs manifest parts-root report tool.glb output
import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { NodeIO } from '@gltf-transform/core';
import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
import draco from 'draco3dgltf';
import { BufferGeometry, Float32BufferAttribute, Matrix4, Vector3, Quaternion, Group, Mesh } from '../vendor/three/build/three.module.min.js';
import { screwHead } from '../js/assembly-head.js';
import { inferToolTipAxis, ScrewTransition } from '../js/assembly-motion.js';
import { validatePackage } from '../js/experience-packages.js';
const [manifestPath, root, reportPath, toolPath, output] = process.argv.slice(2);
assert.ok(output, 'Required: manifest parts-root report tool.glb output');
assert.ok(!fs.existsSync(output), 'Choose a new output directory');
const read = filename => JSON.parse(fs.readFileSync(filename));
const sha = bytes => createHash('sha256').update(bytes).digest('hex');
const clean = vector => vector.toArray().map(x => Math.abs(x) < 1e-12 ? 0 : x);
const raw = read(manifestPath), config = structuredClone(raw), report = read(reportPath);
const records = new Map(report.records.map(record => [record.id, record]));
const io = new NodeIO().registerExtensions(ALL_EXTENSIONS).registerDependencies({ 'draco3d.decoder': await draco.createDecoderModule() });
const facts = [];
async function geometry(filename) {
const document = await io.read(filename), vertices = [], indices = [], point = new Vector3();
const scene = document.getRoot().getDefaultScene() ?? document.getRoot().listScenes()[0];
assert.ok(scene, `Missing scene: ${filename}`);
scene.traverse(node => {
if (!node.getMesh()) return;
assert.ok(!node.getSkin(), 'Only rigid meshes are supported');
const world = new Matrix4().fromArray(node.getWorldMatrix());
for (const primitive of node.getMesh().listPrimitives()) {
assert.equal(primitive.getMode(), 4);
const position = primitive.getAttribute('POSITION'), base = vertices.length / 3;
for (let i = 0; i < position.getCount(); i++) {
point.fromArray(position.getElement(i, [])).applyMatrix4(world);
vertices.push(...point.toArray());
}
for (const index of primitive.getIndices()?.getArray() ?? Array.from({ length: position.getCount() }, (_, i) => i)) indices.push(base + index);
}
});
const result = new BufferGeometry().setAttribute('position', new Float32BufferAttribute(vertices, 3));
result.setIndex(indices); result.computeBoundingBox();
return result;
}
// This supplied L-key has its long working end at minimum Z. Measure the cap
// in GLB root coordinates (including the exported node translation).
const toolGeometry = await geometry(toolPath), toolPoints = toolGeometry.attributes.position;
const tip = new Vector3(), point = new Vector3(); let capCount = 0;
for (let i = 0; i < toolPoints.count; i++) {
point.fromBufferAttribute(toolPoints, i);
if (Math.abs(point.z - toolGeometry.boundingBox.min.z) < 1e-7) { tip.add(point); capCount++; }
}
assert.ok(capCount >= 3); tip.divideScalar(capCount);
const template = new Group(); template.add(new Mesh(toolGeometry));
const tipAxis = new Vector3(...inferToolTipAxis(template, tip.toArray()));
assert.ok(tipAxis.dot(new Vector3(0, 0, -1)) > .999, 'Tool working end must be verified');
const tool = { id: 'hex-key', file: path.basename(toolPath), tipPosition: clean(tip), tipAxis: clean(tipAxis) };
assert.ok(!config.files.some(file => file.path === tool.file), 'Tool filename already exists');
config.tools = [tool];
const toolBytes = fs.readFileSync(toolPath);
config.files.push({ path: tool.file, bytes: toolBytes.length, sha256: sha(toolBytes) });
for (const part of config.parts) {
const record = records.get(part.id); assert.ok(record, `Missing axis record: ${part.id}`);
const entry = config.files.find(file => file.path === part.file), filename = path.join(root, part.file);
const bytes = fs.readFileSync(filename);
assert.equal(bytes.length, entry.bytes); assert.equal(sha(bytes), entry.sha256, `Changed source: ${part.file}`);
const g = await geometry(filename), originalOffset = [...part.installOffset];
const detail = { id: part.id, file: part.file, originalStatus: record.status, originalOffset };
if (record.fastener) {
const head = screwHead(g); assert.ok(head, `Ambiguous screw head: ${part.file}`);
const outward = head.vector, inward = outward.clone().negate();
const axisIndex = outward.toArray().findIndex(value => Math.abs(value) > .99), dimensions = ['x', 'y', 'z'];
const k = dimensions[axisIndex], [u, v] = dimensions.filter(value => value !== k);
const extremum = outward.getComponent(axisIndex) > 0 ? g.boundingBox.max[k] : g.boundingBox.min[k];
const cap = { minU: Infinity, maxU: -Infinity, minV: Infinity, maxV: -Infinity };
for (let i = 0; i < g.attributes.position.count; i++) {
point.fromBufferAttribute(g.attributes.position, i);
if (Math.abs(point[k] - extremum) > .0004) continue;
cap.minU = Math.min(cap.minU, point[u]); cap.maxU = Math.max(cap.maxU, point[u]);
cap.minV = Math.min(cap.minV, point[v]); cap.maxV = Math.max(cap.maxV, point[v]);
}
const socket = new Vector3(); socket[k] = extremum; socket[u] = (cap.minU + cap.maxU) / 2; socket[v] = (cap.minV + cap.maxV) / 2;
socket.addScaledVector(outward, -.00035);
const worldOutward = outward.clone().applyQuaternion(new Quaternion(...part.quaternion)).normalize();
assert.ok(!part.focusDirection || worldOutward.dot(new Vector3(...part.focusDirection)) > .99999, `Head direction changed: ${part.id}`);
if (!Math.hypot(...part.installOffset)) part.installOffset = clean(worldOutward.clone().multiplyScalar(.018));
assert.ok(new Vector3(...part.installOffset).normalize().dot(worldOutward) > .9999, `Wrong entry side: ${part.id}`);
const rotation = new Quaternion().setFromUnitVectors(tipAxis, inward);
part.installation = { type: 'screw', toolId: tool.id, axis: clean(inward), socketPosition: clean(socket), toolQuaternion: rotation.toArray(),
direction: 'clockwise', turns: 3, travel: .0012, approachDuration: 1, engageDuration: .5, tightenDuration: 3.2, retractDuration: .65, toolClearance: .014 };
part.focusDirection = clean(worldOutward);
Object.assign(detail, { localHead: clean(outward), socket: clean(socket), headWidthRatio: head.widthRatio });
// Exercise the actual player, not a duplicated formula: docking remains on
// the head side throughout rotation and restores the exact final pose.
const instance = new Group(); instance.scale.fromArray(part.scale);
const toolInstance = new Group(), transition = new ScrewTransition(instance, part, toolInstance, tool);
const m = part.installation;
for (const fraction of [0, .17, .5, .83, .999]) {
transition.sample(m.approachDuration + m.engageDuration + m.tightenDuration * fraction);
instance.updateMatrixWorld(true);
const actualTip = toolInstance.localToWorld(tip.clone()), expected = instance.localToWorld(socket.clone());
assert.ok(actualTip.distanceTo(expected) < 1e-8, `Tool missed socket: ${part.id}`);
const handle = toolInstance.localToWorld(tip.clone().addScaledVector(tipAxis, -.03)).sub(actualTip).normalize();
const headWorld = outward.clone().applyQuaternion(instance.quaternion);
assert.ok(handle.dot(headWorld) > .9999, `Tool behind screw: ${part.id}`);
}
transition.sample(transition.duration);
assert.deepEqual(instance.position.toArray(), part.position);
assert.deepEqual(instance.quaternion.toArray(), part.quaternion);
transition.dispose();
} else if (!Math.hypot(...part.installOffset)) {
// A failed collision check is NOT proof of an acceptable assembly route.
// Retain the diagnostics and give it an explicitly unverified display move.
const candidates = (record.checks ?? []).filter(check => Number.isFinite(check.remaining) && check.length > 0);
candidates.sort((a, b) => a.remaining - b.remaining || b.length - a.length);
const chosen = candidates[0];
part.installOffset = chosen ? chosen.vector.map(value => value * chosen.length) : [0, Math.min(.06, Math.max(.025, g.boundingBox.getSize(new Vector3()).length())), 0];
detail.selectedCandidate = chosen ?? null;
}
detail.offset = part.installOffset;
detail.presentationOnly = !Math.hypot(...originalOffset) && record.status !== 'foundation';
assert.ok(Math.hypot(...part.installOffset) > .001, `No entry motion: ${part.id}`);
facts.push(detail); g.dispose();
}
assert.deepEqual(config.steps, raw.steps);
for (let i = 0; i < raw.parts.length; i++) for (const key of ['id', 'file', 'parentId', 'position', 'quaternion', 'scale']) assert.deepEqual(config.parts[i][key], raw.parts[i][key]);
validatePackage(config, 'assembly', 'http://localhost:8090/manifest.json');
const partsRoot = path.join(output, '零件模型');
fs.mkdirSync(partsRoot, { recursive: true }); fs.mkdirSync(path.join(output, '核对记录'));
for (const file of raw.files) {
const destination = path.join(partsRoot, file.path); fs.mkdirSync(path.dirname(destination), { recursive: true });
fs.copyFileSync(path.join(root, file.path), destination);
}
fs.copyFileSync(toolPath, path.join(partsRoot, tool.file));
fs.writeFileSync(path.join(output, 'Microban-装配步骤-带扳手.json'), JSON.stringify(config, null, 2) + '\n');
const summary = { parts: config.parts.length, steps: config.steps.length, screws: config.parts.filter(p => p.installation).length,
addedEntryMoves: facts.filter(f => !Math.hypot(...f.originalOffset)).length, presentationOnly: facts.filter(f => f.presentationOnly).length,
files: config.files.length, tool, note: '补充的演示路径不等于无碰撞路径。保留原始检查记录;扳手对接几何轴心,未验证工具与周围零件的完整扫掠空间及机械规格适配。', partsReview: facts };
fs.writeFileSync(path.join(output, '核对记录/动画与对接检查.json'), JSON.stringify(summary, null, 2) + '\n');
fs.copyFileSync(reportPath, path.join(output, '核对记录/原轴向检查.json'));
fs.writeFileSync(path.join(output, '上传说明.txt'), `Microban 分组装配 · 扳手动画版\n\n1. 后台“零件模型”:选择此处的“零件模型”文件夹,包含 8 个部位文件夹和内六角扳手.glb,共 ${config.files.length} 个 GLB。保留文件名和子目录。\n2. 后台“拼装步骤 JSON”:上传 Microban-装配步骤-带扳手.json。\n3. 整机 GLB 不变,无需重传。核对记录不要上传。\n\n保留 ${config.parts.length} 个零件、${config.steps.length} 步、原顺序和最终姿态。前七组独立安装,之后合装七个部件,再安装第八组。\n${summary.screws} 个螺丝步骤加入扳手:移近、对接螺丝头、顺时针拧紧、退出。工具不计入整机零件。\n补上 ${summary.addedEntryMoves} 个原位出现的进入动画。其中 ${summary.presentationOnly} 条是演示路径,不能当作已经通过无碰撞检查;原始诊断保存在核对记录。工具对接位置与方向已验证,工具扫掠避障及实际螺丝规格适配尚未验证。\n所有 GLB 原样复制,材质与颜色未改。\n\n本地预览:http://localhost:8090/deliverables/microban-wrench-20261105/index.html\n`);
console.log(JSON.stringify({ output, ...Object.fromEntries(Object.entries(summary).filter(([key]) => !['partsReview', 'tool'].includes(key))) }, null, 2));