Files
vibemake/scripts/generate-numbered-assembly.mjs
T

168 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.
// Offline: only validated JSON is consumed by the existing community viewer.
import { createHash } from 'node:crypto';
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
import { parseArgs } from 'node:util';
import { strict as assert } from 'node:assert';
import { NodeIO } from '@gltf-transform/core';
import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
import draco from 'draco3dgltf';
import { BufferAttribute, BufferGeometry, Matrix4, Quaternion, Vector3 } from 'three';
import { validateEmbeddedGlb, validatePackage } from '../js/experience-packages.js';
import { bindAssemblyFiles, resourceIndex } from '../js/project-resources.js';
import { numberedInput } from './lib/numbered-parts.mjs';
import { collider } from './lib/assembly-axis-planner.mjs';
import { planEntry, planGroupEntry } from './lib/numbered-axis.mjs';
const hash = data => createHash('sha256').update(data).digest('hex');
const clean = a => a.map(x=>Math.abs(x)<1e-14?0:x);
function rigidMeshes(doc, label) {
const r = doc.getRoot(), scene = r.getDefaultScene() ?? r.listScenes()[0], nodes = [];
assert.ok(scene && !r.listAnimations().length, `${label}:需要静态装配场景`);
scene.traverse(n=>{
if (!n.getMesh()) return;
assert.ok(!n.getSkin() && !n.getWeights().length && n.getMesh().listPrimitives().every(p=>!p.listTargets().length && p.getMode()===4), `${label}:仅支持刚性三角网格`);
nodes.push(n);
});
return nodes;
}
function geometry(mesh) {
const pos=[], idx=[], xyz=[];
for (const p of mesh.listPrimitives()) {
const a=p.getAttribute('POSITION'), i=p.getIndices(), base=pos.length/3;
assert.ok(a?.getType()==='VEC3','网格缺少三维顶点');
for(let n=0;n<a.getCount();n++) {
a.getElement(n,xyz); assert.ok(xyz.every(Number.isFinite),'无效顶点'); pos.push(...xyz);
}
const indices=i?.getArray() ?? Array.from({length:a.getCount()},(_,n)=>n);
assert.ok(indices.length%3===0 && indices.every(n=>n>=0 && n<a.getCount()),'无效三角面');
for(const index of indices) idx.push(base+index);
}
assert.ok(idx.length,'空网格');
const g=new BufferGeometry();
g.setAttribute('position',new BufferAttribute(new Float32Array(pos),3));
g.setIndex(new BufferAttribute(new Uint32Array(idx),1));
return g;
}
// Triangle comparison ignores primitive order, winding, indexing and material splits.
// Use exact decoded float32 coordinates: differing exports need explicit review.
function surface(g) {
const pos=g.attributes.position.array, arr=g.index.array, keys=[], vertex=[];
for (let i=0;i<pos.length;i+=3) vertex.push(pos[i]+','+pos[i+1]+','+pos[i+2]);
for (let i=0;i<arr.length;i+=3) keys.push([vertex[arr[i]],vertex[arr[i+1]],vertex[arr[i+2]]].sort().join(';'));
return hash(keys.sort().join('\n'));
}
function pose(source,target,label) {
assert.ok(Math.abs(source.determinant())>1e-15, `${label}:不可逆的分件坐标`);
const m=target.clone().multiply(source.clone().invert());
const p=new Vector3(),q=new Quaternion(),s=new Vector3();
m.decompose(p,q,s); q.normalize();
const r=new Matrix4().compose(p,q,s);
assert.ok(s.toArray().every(x=>x>0) && m.elements.every((x,i)=>Math.abs(x-r.elements[i])<1e-6),`${label}:当前播放器不支持此镜像或剪切变换`);
return { position:p.toArray(),quaternion:q.toArray(),scale:s.toArray() };
}
export async function generate(root, dest, log=console.log, options={}) {
root=path.resolve(root); dest=path.resolve(dest);
const destRel=path.relative(root,dest);
assert.ok(destRel==='..' || destRel.startsWith('..'+path.sep) || path.isAbsolute(destRel),'输出请放在输入目录以外');
assert.ok(!existsSync(dest),'输出目录已存在,请选择新的目录');
const {whole,parts:ordered}=numberedInput(root, options);
const groupNumbers=[...new Set(ordered.map(p=>p.group.number))];
const grouped=options.finalGroup !== undefined;
if (grouped) assert.ok(groupNumbers.length > 1 && options.finalGroup===groupNumbers.at(-1), '--final-group 须为最后一个部位编号,前面的部位分别预装');
const io=new NodeIO().registerExtensions(ALL_EXTENSIONS).registerDependencies({'draco3d.decoder':await draco.createDecoderModule()});
const read=async name=>{
const bytes=readFileSync(path.resolve(root,name));
validateEmbeddedGlb(bytes.buffer.slice(bytes.byteOffset,bytes.byteOffset+bytes.length));
return {doc:await io.readBinary(bytes),bytes};
};
const ref=await read(whole), nodes=rigidMeshes(ref.doc,whole);
assert.equal(nodes.length,ordered.length,`整机有 ${nodes.length} 个网格实例,零件文件有 ${ordered.length} 个`);
const byName=new Map(nodes.map(n=>[n.getName(),n]));
assert.ok(byName.size===nodes.length && !byName.has(''),'整机网格节点需要唯一的名称');
const title=path.parse(whole).name;
const raw={schemaVersion:1,kind:'assembly',unit:'meter',title:title+' · 分步装配',displayQuaternion:[0,0,0,1],files:[],parts:[],steps:[]};
if (grouped) {
raw.playback='grouped-v1';
raw.groups=groupNumbers.slice(0,-1).map(n=>({id:`group-${n}`,label:ordered.find(p=>p.group.number===n).group.path,parts:[]}));
}
const records=[], installed=[], used=new Set(), surfaceCache=new Map();
const groupColliders=new Map();
let joined=false;
for (const item of ordered) {
if (grouped && item.group.number===options.finalGroup && !joined) {
const obstacles=[];
for (const group of raw.groups) {
const moving=groupColliders.get(group.id);
const result=planGroupEntry(moving,obstacles);
const step={id:`join-${group.id}`,type:'join',groupId:group.id,label:`${options.finalGroup} 总装 · 合装${group.label}`,parts:group.parts,installOffset:clean(result.offset),
pathStatus:result.presentationOnly?'presentation':'checked'};
raw.steps.push(step);
records.push({id:step.id,label:step.label,groupId:group.id,...result});
obstacles.push(...moving);
log(`部件合装 ${group.label}:${result.status}`);
}
joined=true;
}
const {doc,bytes}=await read(item.path), loose=rigidMeshes(doc,item.path);
assert.equal(loose.length,1,`${item.path}:每个分件 GLB 应包含一个网格实例,可含多种材质`);
const n=loose[0], target=byName.get(n.getName()) ?? byName.get(item.stem) ?? byName.get(item.name);
assert.ok(target && !used.has(target),`${item.path}:未找到唯一整机实例(分件节点 ${n.getName()}),请核对名称`);
used.add(target);
const local=geometry(n.getMesh()), refMesh=target.getMesh();
if(!surfaceCache.has(refMesh)) surfaceCache.set(refMesh,surface(geometry(refMesh)));
assert.equal(surface(local),surfaceCache.get(refMesh),`${item.path}:与整机实例的解码网格不一致`);
const world=new Matrix4().fromArray(target.getWorldMatrix());
const placement=pose(new Matrix4().fromArray(n.getWorldMatrix()),world,item.path);
const id=`p-${item.group.number}-${item.number}`;
const moving=collider(id,local.clone().applyMatrix4(world));
const group=raw.groups?.find(g=>g.id===`group-${item.group.number}`);
const previous=group ? (groupColliders.get(group.id) ?? []) : installed;
const result=planEntry(moving,local,world,previous,item.name);
if (group) { previous.push(moving); groupColliders.set(group.id,previous); group.parts.push(id); }
installed.push(moving);
const label=`${item.group.path} · ${item.stepLabel ?? item.number} · ${item.name}`;
raw.files.push({path:item.path,bytes:bytes.length,sha256:hash(bytes)});
raw.parts.push({id,file:item.path,...placement,installOffset:clean(result.offset),...(result.headDirection?{focusDirection:result.headDirection}:{})});
raw.steps.push({id:`step-${item.group.number}-${item.number}`,label,parts:[id],...(group?{groupId:group.id}:{})});
records.push({id,label,file:item.path,wholeNode:target.getName(),...result});
log(`${installed.length}/${ordered.length} ${label}:${result.status}`);
}
const uri='https://assembly.invalid/steps.json';
const pkg=validatePackage(raw,'assembly',uri);
bindAssemblyFiles(pkg.files,resourceIndex(raw.files.map(f=>({relativePath:f.path,sizeBytes:f.bytes,url:new URL(f.path,uri).href}))));
const manifest=JSON.stringify(raw,null,2)+'\n';
assert.ok(Buffer.byteLength(manifest)<=2*1024*1024,'步骤超过播放器 JSON 大小限制');
const review=records.filter(r=>r.status.startsWith('review'));
mkdirSync(dest,{recursive:true});
writeFileSync(path.join(dest,title+'-装配步骤.json'),manifest,{flag:'wx'});
const report={whole,wholeSha256:hash(ref.bytes),steps:raw.steps.length,partCount:ordered.length,groups:raw.groups?.length ?? 0,needReview:review.length,seatingToleranceMeters:0.00015,
extraBefore:options.extraBefore ?? null,
counts:records.reduce((all,r)=>{all[r.status]=(all[r.status] ?? 0)+1;return all;},{}),
visualFits:'visual-thread-fit 检查完整头部通道和带径向余量的螺杆。visual-bore-axis 检查完整头部通道和半径为螺杆一半的孔芯。这两类仅用于轴向演示。',
note:'仅检查已装件与当前零件直线平移的网格表面;未检查末端 0.15 mm 配合、旋转、工具及真实装配工艺。',
review:review.map(r=>({step:r.id,label:r.label,file:r.file,reason:r.status})),records};
mkdirSync(path.join(dest,'核对记录'));
writeFileSync(path.join(dest,'核对记录','轴向检查.json'),JSON.stringify(report,null,2)+'\n');
writeFileSync(path.join(dest,'核对记录','待核对步骤.txt'),`以下 ${review.length} 步无法确认无碰撞的直线插入通路。普通零件原位显示;部件合装保留就位演示动画,但不是已经证明无碰撞的真实安装路线。\n\n`+review.map(r=>`${r.label}\n ${r.file ?? '整组部件合装'}\n ${r.status==='review-head'?'未能可靠区分螺丝头尾':'候选轴向受阻或检查未能确认'}\n`).join('\n'));
const fits=(report.counts['visual-thread-fit'] ?? 0)+(report.counts['visual-bore-axis'] ?? 0);
writeFileSync(path.join(dest,'上传说明.txt'),`整机模型单独上传 ${whole}。\n零件模型选择 ${root},保留全部编号部位子目录、文件名。\n拼装步骤只上传 ${title}-装配步骤.json。\n${grouped?`需要部署支持 grouped-v1 的新版前端。前 ${raw.groups.length} 组分别展示;第 ${options.finalGroup} 组前先合装这些部件,再安装该文件夹的零件。\n`:''}共 ${ordered.length} 个零件、${raw.steps.length} 个播放步骤,${fits} 步是螺丝沿孔轴展示,${review.length} 步需人工复核。普通待核对零件原位显示,待核对的部件合装使用就位演示动画(pathStatus: presentation),不能据此判断真实安装过程无碰撞。具体步号请看核对记录。\n原 GLB 几何、材质、颜色未修改。\n`);
return report;
}
if (pathToFileURL(path.resolve(process.argv[1] ?? '.')).href===import.meta.url) {
try {
const {values,positionals:[root,out]}=parseArgs({allowPositionals:true,options:{reference:{type:'string'},'final-group':{type:'string'},'extra-before':{type:'string'}}});
assert.ok(root && out,'用法:npm run assembly:generate -- "分组 GLB 目录" "新的输出目录" [--reference "整机.glb"] [--final-group 8]');
const options={reference:values.reference};
if (values['extra-before']) {
options.extraBefore=values['extra-before']==='end'?'end':Number(values['extra-before']);
assert.ok(options.extraBefore==='end'||Number.isSafeInteger(options.extraBefore)&&options.extraBefore>0,'附加件参数格式:--extra-before 步号,或 --extra-before end');
}
if(values['final-group']) options.finalGroup=Number(values['final-group']);
const r=await generate(root,out,console.log,options);
console.log(`完成:${path.resolve(out)}(${r.steps} 步,${r.needReview} 步需复核)`);
}
catch (err){console.error(err.message);process.exitCode=1;}
}