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.
278 lines
22 KiB
JavaScript
278 lines
22 KiB
JavaScript
// Reproducible assembly package from the user's numbered order and current whole GLB.
|
|
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 draco3d from 'draco3dgltf';
|
|
import { Vector3, Quaternion, Matrix4, BufferGeometry, BufferAttribute } from 'three';
|
|
import { collider, checkFiniteAxis, VIEW_AXES } from './lib/assembly-axis-planner.mjs';
|
|
import { validatePackage } from '../js/experience-packages.js';
|
|
|
|
const sourcePath='/Users/jerry/Downloads/鸭子_压缩.glb';
|
|
const orderPath='/Users/jerry/Downloads/鸭子顺序';
|
|
const output=new URL('../deliverables/experience-packages/microduck-current/',import.meta.url).pathname;
|
|
const refining=process.argv.includes('--refine');
|
|
const previousManifest=refining?JSON.parse(fs.readFileSync(path.join(output,'manifest.json'))):null;
|
|
const previousReview=refining?JSON.parse(fs.readFileSync(path.join(output,'axis-review.json'))):null;
|
|
fs.mkdirSync(output,{recursive:true});
|
|
const bytes=fs.readFileSync(sourcePath), source=JSON.parse(bytes.subarray(20,20+bytes.readUInt32LE(12)).toString());
|
|
const binOffset=20+bytes.readUInt32LE(12)+8;
|
|
const canonical=s=>s.trim().replace(/^镜向/,'').replace(/^BU /,'').replace(/\.\d+$/,'').replace(/^0914舵机装配1$/,'0914舵机装配');
|
|
const clean=a=>a.map(x=>Math.abs(x)<1e-11?0:x);
|
|
const vec=a=>new Vector3(...a);
|
|
const hash=b=>createHash('sha256').update(b).digest('hex');
|
|
const write=(name,value)=>fs.writeFileSync(path.join(output,name),JSON.stringify(value,null,2)+'\n');
|
|
const order=[];
|
|
function walk(dir){for(const f of fs.readdirSync(dir,{withFileTypes:true})){
|
|
const filename=path.join(dir,f.name);if(f.isDirectory()){walk(filename);continue;}
|
|
if(!/\.(step|stp|sldprt)$/i.test(f.name))continue;
|
|
const m=/^([1-5])-(\d+)-?(.*)\.(step|stp|sldprt)$/i.exec(f.name);assert.ok(m,f.name);
|
|
let group=+m[1],n=+m[2],label=m[3];
|
|
if(group===3&&f.name.includes('0914舵机')){n=+f.name[2];label='0914舵机装配';}
|
|
order.push({group,n,label:label.trim(),code:`${group}-${n}`,source:path.relative(orderPath,filename)});
|
|
}}
|
|
walk(orderPath);order.sort((a,b)=>a.group-b.group||a.n-b.n);
|
|
for(const g of [1,2,3,4,5])assert.deepEqual(order.filter(o=>o.group===g).map(o=>o.n),Array.from({length:[0,52,52,47,24,64][g]},(_,i)=>i+1));
|
|
const nodes=source.nodes.map((n,index)=>({index,name:n.name,key:canonical(n.name),position:n.translation??[0,0,0],quaternion:n.rotation??[0,0,0,1]}));
|
|
assert.equal(nodes.length,242);assert.ok(source.nodes.every(n=>!n.children?.length));
|
|
const old=JSON.parse(fs.readFileSync('/Users/jerry/Downloads/小鸭子-双腿及躯干-当前上传/小鸭子-双腿及躯干-149步装配.json'));
|
|
const oldQ=new Quaternion(...old.displayQuaternion),oldParts=new Map(old.parts.map(p=>[p.id,p]));
|
|
const oldSteps=new Map(old.steps.map(s=>[s.id.split('-').slice(-2).join('-'),s]));
|
|
const used=new Set(),mapping=new Map();
|
|
function assign(o,node,method){assert.ok(node,`No node ${o.code}`);assert.ok(!used.has(node.index),`Duplicate ${o.code}: ${node.index}`);used.add(node.index);mapping.set(o.code,{...o,node:node.index,name:node.name,method});}
|
|
function options(o){return nodes.filter(n=>!used.has(n.index)&&n.key===canonical(o.label));}
|
|
function target(o){const s=oldSteps.get(o.code);return s?vec(oldParts.get(s.parts[0]).position).applyQuaternion(oldQ):null;}
|
|
for(const o of order.filter(o=>o.group<=3)){
|
|
const t=target(o);if(!t)continue;
|
|
const matches=options(o).filter(n=>vec(n.position).distanceTo(t)<.0001);assert.ok(matches.length<=1,`Ambiguous ${o.code}`);
|
|
if(matches.length)assign(o,matches[0],'原步骤位置与新整机一致');
|
|
}
|
|
for(const o of order.filter(o=>o.group<=3&&!mapping.has(o.code)&&oldSteps.has(o.code))){
|
|
const t=target(o), choices=options(o).sort((a,b)=>vec(a.position).distanceTo(t)-vec(b.position).distanceTo(t));
|
|
if(!choices.length){console.log('UNMATCHED',o.code,o.label);continue;}
|
|
assign(o,choices[0],'同名零件按整机位置匹配');mapping.get(o.code).oldDistanceMm=vec(choices[0].position).distanceTo(t)*1000;
|
|
}
|
|
write('mapping-initial.json',{source:sourcePath,sourceSha256:hash(bytes),order,matches:[...mapping.values()],remaining:nodes.filter(n=>!used.has(n.index))});
|
|
// Current whole-model instances: keep their actual geometry/specification even where
|
|
// the numbered filename has a different screw length. Such differences are reported.
|
|
const manual={
|
|
'3-36':101,'3-37':102,
|
|
'4-1':6,'4-14':32,'4-15':127,'4-16':128,'4-17':31,'4-18':133,'4-19':134,
|
|
'4-20':7,'4-21':129,'4-22':130,'4-23':131,'4-24':132,
|
|
'5-1':33,'5-2':9,'5-21':55,'5-22':220,'5-23':221,'5-24':186,'5-25':187,
|
|
'5-26':48,'5-27':18,'5-28':8,'5-29':49,'5-30':65,'5-31':10,'5-32':233,
|
|
'5-33':56,'5-40':30,'5-45':21,'5-46':241,'5-47':85,'5-48':89,
|
|
'5-49':29,'5-50':83,'5-51':84,'5-52':87,'5-53':90,
|
|
'5-54':20,'5-55':86,'5-56':88,'5-57':91,'5-58':92,
|
|
'5-59':19,'5-60':34,'5-61':39,'5-62':194,'5-63':195,'5-64':222,
|
|
};
|
|
for(const [g,start,indices] of [[4,2,[205,206,207,208,209,211,226,227,228,229,230,231]],
|
|
[5,3,[199,200,201,202,203,204]],[5,9,[214,215,216,217,218,219,180,181,182,183,184,185]],
|
|
[5,34,[188,189,190,191,192,193]],[5,41,[135,136,137,138]]])
|
|
indices.forEach((v,i)=>{manual[`${g}-${start+i}`]=v;});
|
|
for(const o of order.filter(o=>!mapping.has(o.code)))assign(o,nodes[manual[o.code]],'新整机对应组件与紧固孔位');
|
|
assert.equal(mapping.size,239);
|
|
const extras=[{node:41,code:'3-44',reason:'整机附带的 trunk_shell_left,与外壳一起显示'},
|
|
{node:66,code:'5-49',reason:'整机摄像头与镜头支架一起安装'},
|
|
{node:225,code:'4-13',reason:'整机额外的 M2x8.047,保留原位置,与颈部最后一颗螺丝一起显示;清单未单列'}];
|
|
assert.deepEqual(nodes.filter(n=>!used.has(n.index)).map(n=>n.index),extras.map(e=>e.node).sort((a,b)=>a-b));
|
|
const mismatches=[...mapping.values()].filter(m=>nodes[m.node].key!==canonical(m.label));
|
|
write('mapping.json',{source:sourcePath,sourceSha256:hash(bytes),steps:order.map(o=>mapping.get(o.code)),extras,mismatches});
|
|
console.log('Mapped',mapping.size,'numbered steps;',extras.length,'whole-model extras;',mismatches.length,'label differences');
|
|
|
|
// Extract the original compressed mesh and embedded textures byte-for-byte.
|
|
// This does not decode/re-encode geometry, change materials, or resize textures.
|
|
function extract(index){
|
|
const node=source.nodes[index],out={asset:structuredClone(source.asset),scene:0,scenes:[{nodes:[0]}],
|
|
nodes:[{name:node.name,mesh:0}],meshes:[],materials:[],textures:[],images:[],samplers:[],accessors:[],bufferViews:[],buffers:[]},
|
|
maps=new Map(),chunks=[];let total=0;
|
|
const copy=(type,i,fn)=>{if(!maps.has(type))maps.set(type,new Map());const m=maps.get(type);
|
|
if(m.has(i))return m.get(i);const n=out[type].length;m.set(i,n);out[type].push(null);out[type][n]=fn(structuredClone(source[type][i]));return n;};
|
|
const view=i=>copy('bufferViews',i,v=>{
|
|
const chunk=bytes.subarray(binOffset+(v.byteOffset??0),binOffset+(v.byteOffset??0)+v.byteLength);
|
|
assert.equal(chunk.length,v.byteLength);const pad=(4-total%4)%4;if(pad){chunks.push(Buffer.alloc(pad));total+=pad;}
|
|
v.buffer=0;v.byteOffset=total;chunks.push(chunk);total+=chunk.length;return v;
|
|
});
|
|
const accessor=i=>copy('accessors',i,a=>{if(a.bufferView!==undefined)a.bufferView=view(a.bufferView);
|
|
if(a.sparse){a.sparse.indices.bufferView=view(a.sparse.indices.bufferView);a.sparse.values.bufferView=view(a.sparse.values.bufferView);}return a;});
|
|
const image=i=>copy('images',i,a=>{assert.ok(a.bufferView!==undefined&&!a.uri);a.bufferView=view(a.bufferView);return a;});
|
|
const texture=i=>copy('textures',i,t=>{if(t.source!==undefined)t.source=image(t.source);if(t.sampler!==undefined)t.sampler=copy('samplers',t.sampler,v=>v);assert.ok(!t.extensions);return t;});
|
|
const material=i=>copy('materials',i,m=>{function scan(v){for(const[k,x]of Object.entries(v))if(x&&typeof x==='object'){
|
|
if(/Texture$/.test(k)&&x.index!==undefined)x.index=texture(x.index);else scan(x);}}scan(m);return m;});
|
|
out.meshes.push(structuredClone(source.meshes[node.mesh]));
|
|
for(const p of out.meshes[0].primitives){for(const k of Object.keys(p.attributes))p.attributes[k]=accessor(p.attributes[k]);
|
|
if(p.indices!==undefined)p.indices=accessor(p.indices);if(p.material!==undefined)p.material=material(p.material);
|
|
if(p.extensions?.KHR_draco_mesh_compression)p.extensions.KHR_draco_mesh_compression.bufferView=view(p.extensions.KHR_draco_mesh_compression.bufferView);
|
|
assert.ok(!p.targets);
|
|
}
|
|
out.extensionsUsed=source.extensionsUsed;out.extensionsRequired=source.extensionsRequired;
|
|
out.buffers=[{byteLength:total}];let json=Buffer.from(JSON.stringify(out));json=Buffer.concat([json,Buffer.alloc((4-json.length%4)%4,32)]);
|
|
const bin=Buffer.concat([...chunks,Buffer.alloc((4-total%4)%4)]),h=Buffer.alloc(20),bh=Buffer.alloc(8);
|
|
h.writeUInt32LE(0x46546c67,0);h.writeUInt32LE(2,4);h.writeUInt32LE(28+json.length+bin.length,8);h.writeUInt32LE(json.length,12);h.writeUInt32LE(0x4e4f534a,16);
|
|
bh.writeUInt32LE(bin.length,0);bh.writeUInt32LE(0x004e4942,4);return Buffer.concat([h,json,bh,bin]);
|
|
}
|
|
const parts=nodes.map(n=>({id:`duck-${String(n.index).padStart(3,'0')}`,file:`${n.name}.glb`,parentId:null,
|
|
position:n.position,quaternion:new Quaternion(...n.quaternion).normalize().toArray(),scale:source.nodes[n.index].scale??[1,1,1],installOffset:[0,.04,0]}));
|
|
const files=[];
|
|
for(const p of parts){const b=extract(+p.id.slice(5));fs.writeFileSync(path.join(output,p.file),b);files.push({path:p.file,bytes:b.length,sha256:hash(b)});}
|
|
const tools=structuredClone(old.tools);
|
|
for(const tool of tools) tool.tipAxis=[0,0,-1];
|
|
for(const t of tools){const b=fs.readFileSync(path.join('/Users/jerry/Downloads/小鸭子-扳手装配/零件模型',t.file));fs.writeFileSync(path.join(output,t.file),b);files.push({path:t.file,bytes:b.length,sha256:hash(b)});}
|
|
const manifest={schemaVersion:1,kind:'assembly',title:'小鸭子 · 最新整机与完整编号顺序',unit:'meter',displayQuaternion:[0,0,0,1],files,parts,
|
|
steps:order.map(o=>({id:`step-${o.code}`,label:`${o.code} · ${o.label}`,parts:[parts[mapping.get(o.code).node].id,...extras.filter(e=>e.code===o.code).map(e=>parts[e.node].id)]})),tools};
|
|
validatePackage(manifest,'assembly','http://localhost:8090/manifest.json');
|
|
write('input.json',manifest);
|
|
console.log('Extracted',files.length,'files, total MiB',files.reduce((s,f)=>s+f.bytes,0)/1024**2);
|
|
|
|
// Decode only for analysis. Output GLBs remain byte-preserving extractions above.
|
|
const io=new NodeIO().registerExtensions(ALL_EXTENSIONS).registerDependencies({'draco3d.decoder':await draco3d.createDecoderModule()});
|
|
const doc=await io.readBinary(bytes),geometry=new Map(),facts=[];
|
|
for(const [i,n] of doc.getRoot().listNodes().entries()){
|
|
const arrays=[],indices=[];let count=0;
|
|
for(const p of n.getMesh().listPrimitives()){
|
|
const a=p.getAttribute('POSITION').getArray();arrays.push(a);for(const ix of p.getIndices().getArray())indices.push(ix+count);count+=a.length/3;
|
|
}
|
|
const positions=new Float32Array(count*3);let cursor=0;for(const a of arrays){positions.set(a,cursor);cursor+=a.length;}
|
|
const g=new BufferGeometry().setAttribute('position',new BufferAttribute(positions,3));g.setIndex(new BufferAttribute(new Uint32Array(indices),1));g.computeBoundingBox();
|
|
geometry.set(i,g);facts.push({node:i,name:n.getName(),min:g.boundingBox.min.toArray(),max:g.boundingBox.max.toArray(),vertices:count,triangles:indices.length/3});
|
|
}
|
|
write('geometry-facts.json',facts);console.log('Geometry decoded');
|
|
|
|
function principalAxes(g){
|
|
const a=g.attributes.position,mean=new Vector3(),p=new Vector3();for(let i=0;i<a.count;i++)mean.add(p.fromBufferAttribute(a,i));mean.divideScalar(a.count);
|
|
const c=Array.from({length:3},()=>[0,0,0]),v=[[1,0,0],[0,1,0],[0,0,1]];
|
|
for(let i=0;i<a.count;i++){const q=p.fromBufferAttribute(a,i).sub(mean).toArray();for(let r=0;r<3;r++)for(let s=0;s<3;s++)c[r][s]+=q[r]*q[s];}
|
|
for(let k=0;k<30;k++){
|
|
let r=0,s=1;for(const [i,j]of[[0,2],[1,2]])if(Math.abs(c[i][j])>Math.abs(c[r][s])){r=i;s=j;}
|
|
if(Math.abs(c[r][s])<1e-15)break;
|
|
const t=.5*Math.atan2(2*c[r][s],c[s][s]-c[r][r]),co=Math.cos(t),si=Math.sin(t),rr=c[r][r],ss=c[s][s],rs=c[r][s];
|
|
c[r][r]=co*co*rr-2*si*co*rs+si*si*ss;c[s][s]=si*si*rr+2*si*co*rs+co*co*ss;c[r][s]=c[s][r]=0;
|
|
for(let i=0;i<3;i++)if(i!==r&&i!==s){const ir=c[i][r],is=c[i][s];c[i][r]=c[r][i]=co*ir-si*is;c[i][s]=c[s][i]=si*ir+co*is;}
|
|
for(let i=0;i<3;i++){const ir=v[i][r],is=v[i][s];v[i][r]=co*ir-si*is;v[i][s]=si*ir+co*is;}
|
|
}
|
|
return [0,1,2].map(i=>({value:c[i][i],vector:new Vector3(v[0][i],v[1][i],v[2][i])})).sort((a,b)=>a.value-b.value);
|
|
}
|
|
function screwGeometry(g){
|
|
let axis=principalAxes(g)[2].vector;
|
|
// End caps provide exact axial normals, removing tessellation-induced PCA tilt.
|
|
const a=g.attributes.position,idx=g.index.array,groups=new Map(),v0=new Vector3(),v1=new Vector3(),v2=new Vector3(),cross=new Vector3();
|
|
for(let i=0;i<idx.length;i+=3){v0.fromBufferAttribute(a,idx[i]);v1.fromBufferAttribute(a,idx[i+1]).sub(v0);v2.fromBufferAttribute(a,idx[i+2]).sub(v0);
|
|
cross.crossVectors(v1,v2);const area=cross.length();if(area<1e-15)continue;cross.divideScalar(area);
|
|
if(Math.abs(cross.dot(axis))<.97)continue;if(cross.dot(axis)<0)cross.negate();
|
|
const key=cross.toArray().map(x=>Math.round(x*1000)).join(',');if(!groups.has(key))groups.set(key,{area:0,normal:new Vector3()});
|
|
const b=groups.get(key);b.area+=area;b.normal.addScaledVector(cross,area);
|
|
}
|
|
const dominant=[...groups.values()].sort((a,b)=>b.area-a.area)[0];assert.ok(dominant);axis=dominant.normal.normalize();
|
|
const project=axis=>{let min=Infinity,max=-Infinity;for(let i=0;i<a.count;i++){const d=v0.fromBufferAttribute(a,i).dot(axis);min=Math.min(min,d);max=Math.max(max,d);}return{min,max};};
|
|
let {min,max}=project(axis);
|
|
const center=g.boundingBox.getCenter(new Vector3()),radialCenter=center.clone().addScaledVector(axis,-center.dot(axis));
|
|
const width=(at)=>{let radius=0;for(let i=0;i<a.count;i++){v0.fromBufferAttribute(a,i);const d=v0.dot(axis);if(Math.abs(d-at)>.0006)continue;radius=Math.max(radius,v0.addScaledVector(axis,-d).distanceTo(radialCenter));}return radius;};
|
|
const lo=width(min),hi=width(max);if(lo>hi){axis.negate();({min,max}=project(axis));}
|
|
// Center the head cap in two perpendicular coordinates; no node-origin assumption.
|
|
const u=new Vector3().crossVectors(axis,Math.abs(axis.x)<.8?new Vector3(1,0,0):new Vector3(0,1,0)).normalize(),v=new Vector3().crossVectors(axis,u);
|
|
let u0=Infinity,u1=-Infinity,vv0=Infinity,vv1=-Infinity;
|
|
for(let i=0;i<a.count;i++){v0.fromBufferAttribute(a,i);if(v0.dot(axis)<max-.0006)continue;const x=v0.dot(u),y=v0.dot(v);u0=Math.min(u0,x);u1=Math.max(u1,x);vv0=Math.min(vv0,y);vv1=Math.max(vv1,y);}
|
|
const socket=axis.clone().multiplyScalar(max-.00035).addScaledVector(u,(u0+u1)/2).addScaledVector(v,(vv0+vv1)/2);
|
|
return{outward:axis,socket,headRadii:[lo,hi],length:max-min};
|
|
}
|
|
const screwFacts=[];
|
|
for(const p of parts){
|
|
const i=+p.id.slice(5);if(!/螺钉/.test(nodes[i].name))continue;
|
|
const s=screwGeometry(geometry.get(i)),q=new Quaternion(...p.quaternion),outward=s.outward.clone().applyQuaternion(q).normalize();
|
|
p.installOffset=clean(outward.clone().multiplyScalar(.018).toArray());
|
|
if(/^标准杯头/.test(nodes[i].name)){
|
|
const inward=s.outward.clone().negate(),toolQ=new Quaternion().setFromUnitVectors(new Vector3(0,0,-1),inward)
|
|
.multiply(new Quaternion().setFromAxisAngle(new Vector3(0,0,1),Math.PI/6));
|
|
p.installation={type:'screw',toolId:tools[0].id,axis:clean(inward.toArray()),socketPosition:clean(s.socket.toArray()),toolQuaternion:toolQ.toArray(),
|
|
direction:'clockwise',turns:3,travel:.0012,approachDuration:.45,engageDuration:.3,tightenDuration:2.4,retractDuration:.35,toolClearance:.012};
|
|
}
|
|
screwFacts.push({node:i,name:nodes[i].name,outward:outward.toArray(),localOutward:s.outward.toArray(),socket:s.socket.toArray(),headRadii:s.headRadii,length:s.length});
|
|
}
|
|
write('screw-axes.json',screwFacts);
|
|
const worldGeometry=new Map();
|
|
function getCollider(i){if(!worldGeometry.has(i)){
|
|
const p=parts[i],g=geometry.get(i).clone().applyMatrix4(new Matrix4().compose(vec(p.position),new Quaternion(...p.quaternion),vec(p.scale)));
|
|
worldGeometry.set(i,collider(p.id,g));}return worldGeometry.get(i);}
|
|
const records=[],installed=[];
|
|
const idIndex=new Map(parts.map((p,i)=>[p.id,i]));
|
|
function candidates(o,indices){
|
|
const p=parts[indices[0]],out=[],add=(name,v)=>{v=v.clone().normalize();if(v.lengthSq()&&!out.some(c=>vec(c.vector).distanceTo(v)<1e-4))out.push({name,vector:clean(v.toArray())});};
|
|
const local=v=>vec(v).applyQuaternion(new Quaternion(...p.quaternion));
|
|
const prev=oldSteps.get(o.code);let preference=prev?vec(oldParts.get(prev.parts[0]).installOffset).applyQuaternion(oldQ):vec([0,1,0]);
|
|
if(o.group<=2&&[1,2].includes(o.n)){
|
|
if(refining&&o.n===2){const up=local([0,0,1]);if(up.y<0)up.negate();add('沿脚板法向从上往下',up);}
|
|
add('从上往下',vec([0,1,0]));return out;
|
|
}
|
|
if(o.group<=2&&o.n===7){
|
|
const foot=parts[mapping.get(`${o.group}-2`).node],up=vec([0,0,1]).applyQuaternion(new Quaternion(...foot.quaternion));if(up.y<0)up.negate();
|
|
add('沿脚板法向从上往下',up);add('从上往下',vec([0,1,0]));
|
|
for(const z of refining?[.08,.15,.25,.4,.6,.8]:[.15])for(const x of refining?[-.2,0,.2]:[0])add(`上方进入 ${x},${z}`,up.clone().add(vec([x,0,o.group===1?-z:z])));
|
|
return out;
|
|
}
|
|
if(/^(w_61702|深沟球轴承)/.test(o.label)){
|
|
const normal=principalAxes(geometry.get(indices[0]))[0].vector.applyQuaternion(new Quaternion(...p.quaternion));if(normal.dot(preference)<0)normal.negate();
|
|
add('沿轴承孔轴线',normal);add('反向沿轴承孔轴线',normal.clone().negate());return out;
|
|
}
|
|
if(o.group===4&&[14,17].includes(o.n)){add('从支架外侧插入',vec([0,0,o.n===14?1:-1]));return out;}
|
|
if(o.group===5&&[45,46,49,60].includes(o.n))preference=vec([1,0,0]);
|
|
if(o.group===5&&o.n===61)preference=vec([0,1,0]);
|
|
add('优先安装方向',preference);
|
|
for(const a of VIEW_AXES)add(a.label,vec(a.vector));
|
|
// Local fit normals also cover the slightly tilted leg and head components.
|
|
if(o.group<=2||o.group===5)for(const a of VIEW_AXES)add(`零件局部 ${a.name}`,local(a.vector));
|
|
if(refining&&[...previousReview.records].find(r=>r.code===o.code)?.selected.firstContact>.004)
|
|
for(const x of [-1,0,1])for(const y of [-1,0,1])for(const z of [-1,0,1])if(x||y||z)add(`斜向 ${x},${y},${z}`,vec([x,y,z]));
|
|
return out;
|
|
}
|
|
function sampledPath(moving,obstacles,vector,travel){
|
|
const v=vec(vector),sweeps=moving.map(m=>m.box.clone().union(m.box.clone().translate(v.clone().multiplyScalar(travel))));
|
|
const relevant=obstacles.filter(b=>sweeps.some(s=>s.intersectsBox(b.box))),matrix=new Matrix4();
|
|
let firstContact=0,hits=0,checks=0;const states=[],spacing=refining?.0005:.001;
|
|
for(let d=travel;d>.00015;d-=spacing){const offset=v.clone().multiplyScalar(d);matrix.makeTranslation(...offset.toArray());let hit=false;
|
|
for(const a of moving){const box=a.box.clone().translate(offset);for(const b of relevant){if(box.intersectsBox(b.box)&&b.bvh.intersectsGeometry(a.geometry,matrix)){hit=true;break;}}if(hit)break;}
|
|
checks++;states.push({d,hit});if(hit){hits++;if(!firstContact)firstContact=d;}
|
|
}
|
|
if(refining){
|
|
// Choose a visible entry window within the available space, never launch a
|
|
// bearing from the opposite leg. Report residual terminal contact explicitly.
|
|
const ascending=[...states].reverse();let window=null;
|
|
for(let a=0;a<ascending.length;){if(ascending[a].hit){a++;continue;}let b=a;
|
|
while(b+1<ascending.length&&!ascending[b+1].hit)b++;
|
|
const available=ascending[b].d-spacing;
|
|
if(available-ascending[a].d>=.004){window={travel:available,firstContact:a?ascending[a-1].d:0};break;}a=b+1;
|
|
}
|
|
if(window)return{...window,hits,checks,fullTravel:travel,sampleSpacing:spacing};
|
|
}
|
|
return{firstContact,hits,checks,sampleSpacing:spacing};
|
|
}
|
|
for(const [i,o]of order.entries()){
|
|
const step=manifest.steps[i],indices=step.parts.map(id=>idIndex.get(id)),moving=indices.map(getCollider),p=parts[indices[0]],fastener=/螺钉/.test(o.label);
|
|
const record={code:o.code,label:step.label,nodes:indices};
|
|
if(fastener){
|
|
if(refining){Object.assign(record,previousReview.records[i]);for(const ix of indices)parts[ix].installOffset=previousManifest.parts[ix].installOffset;}
|
|
else {
|
|
// Each screw keeps its own measured axis, including a grouped extra instance.
|
|
record.kind='screw';record.selected={name:'沿螺丝自身轴线',vector:vec(p.installOffset).normalize().toArray(),travel:.018};
|
|
record.check=checkFiniteAxis([moving[0]],installed,record.selected.vector,.018,{maxMilliseconds:900,maxIterations:160});
|
|
}
|
|
}else{
|
|
const travel=o.group<=2&&[1,2,7].includes(o.n)?.055:.045;
|
|
record.candidates=candidates(o,indices).map(c=>({...c,travel,...sampledPath(moving,installed,c.vector,travel)}));
|
|
record.candidates.sort((a,b)=>a.firstContact-b.firstContact||a.hits-b.hits);
|
|
const selected=record.candidates[0];record.kind='component';record.selected=selected;
|
|
record.check=checkFiniteAxis(moving,installed,selected.vector,selected.travel,{maxMilliseconds:2500,maxIterations:250});
|
|
for(const ix of indices)parts[ix].installOffset=clean(vec(selected.vector).multiplyScalar(selected.travel).toArray());
|
|
}
|
|
record.offsets=indices.map(ix=>parts[ix].installOffset);records.push(record);installed.push(...moving);
|
|
write('axis-review.progress.json',{completed:i+1,total:order.length,records});
|
|
console.log(`${i+1}/239 ${o.code} ${record.selected.name}: ${record.check.status} contact=${((record.check.remaining??0)*1000).toFixed(2)}mm`);
|
|
}
|
|
validatePackage(manifest,'assembly','http://localhost:8090/manifest.json');
|
|
write('manifest.json',manifest);
|
|
write('manifest.notes.json',{steps:records.map(r=>({reason:`${r.selected.name};装入距离 ${Math.round(r.selected.travel*1000)} mm。${['foundation','clear-to-seating'].includes(r.check.status)?'平移路径检查通过(保留最后 0.15 mm 装配接触区)。':'末段存在接触或尚未验证,见说明。'}`}))});
|
|
write('axis-review.json',{sourceSha256:hash(bytes),method:'Triangle BVH: candidate screening at 1 mm, then conservative advancement; fixed screw axes and bearing fit axes.',
|
|
collisionCertified:false,seatingToleranceMeters:.00015,limitations:['终点配合接触、螺丝旋转与扳手扫掠不在本次平移路径认证范围内。','同规格紧固件在同一组内沿原整机孔位依次安装;单件顺序文件没有独立实例坐标。'],records});
|
|
console.log('DONE',output);
|