198 lines
13 KiB
JavaScript
198 lines
13 KiB
JavaScript
import test from 'node:test';
|
||
import assert from 'node:assert/strict';
|
||
import { copyFileSync, mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from 'node:fs';
|
||
import os from 'node:os';
|
||
import path from 'node:path';
|
||
import { Document, NodeIO } from '@gltf-transform/core';
|
||
import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
|
||
import { draco } from '@gltf-transform/functions';
|
||
import draco3d from 'draco3dgltf';
|
||
import { BufferGeometry, Float32BufferAttribute, BoxGeometry, CylinderGeometry, Matrix4, Quaternion, Vector3 } from 'three';
|
||
import { generate } from '../scripts/generate-numbered-assembly.mjs';
|
||
import { numberedInput } from '../scripts/lib/numbered-parts.mjs';
|
||
import { screwHead, planGroupEntry } from '../scripts/lib/numbered-axis.mjs';
|
||
import { hexInstallation, measureHexKey } from '../scripts/lib/numbered-tool.mjs';
|
||
import { validatePackage, visibleAssemblyParts } from '../js/experience-packages.js';
|
||
import { resourceIndex } from '../js/project-resources.js';
|
||
|
||
const workspace=t=>{const dir=mkdtempSync(path.join(os.tmpdir(),'make-parts-'));t.after(()=>rmSync(dir,{recursive:true,force:true}));return dir;};
|
||
test('orders by numeric group and local sequence, reports missing/duplicate/unnumbered files together', t=>{
|
||
const p=workspace(t);writeFileSync(path.join(p,'whole.glb'),'');
|
||
for(let i=10;i>=1;i--){
|
||
const dir=path.join(p,i+'部');mkdirSync(dir);
|
||
for(let j=12;j>=1;j--)writeFileSync(path.join(dir,(j===11?'2':'1')+'-'+j+'-零件.007.glb'),'');
|
||
}
|
||
const input=numberedInput(p);assert.equal(input.parts[10].number,11);assert.equal(input.parts[108].group.number,10);
|
||
const dir=path.join(p,'1部');rmSync(path.join(dir,'1-3-零件.007.glb'));
|
||
writeFileSync(path.join(dir,'1-2-重复.glb'),'');writeFileSync(path.join(dir,'螺丝.012.glb'),'');
|
||
assert.throws(()=>numberedInput(p),e=>['缺号:3','重复编号 2','螺丝.012.glb'].every(s=>e.message.includes(s)));
|
||
});
|
||
test('identifies either screw head end, declines a symmetric shaft',()=>{
|
||
function part(head,tail){
|
||
const all=[];
|
||
for(const [z,r] of [[-.008,tail],[0,head]])for(let i=0;i<24;i++)all.push(r*Math.cos(i*Math.PI/12),r*Math.sin(i*Math.PI/12),z);
|
||
return new BufferGeometry().setAttribute('position',new Float32BufferAttribute(all,3));
|
||
}
|
||
assert.deepEqual(screwHead(part(.002,.001)).vector.toArray(),[0,0,1]);
|
||
assert.deepEqual(screwHead(part(.001,.002)).vector.toArray(),[0,0,-1]);
|
||
assert.equal(screwHead(part(.001,.001)),null);
|
||
});
|
||
test('Draco parts: restores final pose despite loose transform, binds grouped upload paths, rejects wrong mesh',async t=>{
|
||
const p=workspace(t), dir=path.join(p,'source'), group=path.join(dir,'1测试');mkdirSync(group,{recursive:true});
|
||
const io=new NodeIO().registerExtensions(ALL_EXTENSIONS).registerDependencies({'draco3d.encoder':await draco3d.createEncoderModule()});
|
||
async function writeGlb(file,entries) {
|
||
const d=new Document(), b=d.createBuffer(), s=d.createScene();
|
||
for(const [name,x,w] of entries) {
|
||
const g=new BoxGeometry(w,.008,.006);
|
||
const a=d.createAccessor().setType('VEC3').setArray(g.attributes.position.array).setBuffer(b);
|
||
const idx=d.createAccessor().setType('SCALAR').setArray(g.index.array).setBuffer(b);
|
||
const prim=d.createPrimitive().setAttribute('POSITION',a).setIndices(idx);
|
||
s.addChild(d.createNode(name).setTranslation([x,0,0]).setMesh(d.createMesh().addPrimitive(prim)));
|
||
}
|
||
await d.transform(draco());await io.write(file,d);
|
||
}
|
||
await writeGlb(path.join(dir,'整机.glb'),[['left',.1,.02],['right',.3,.015]]);
|
||
await writeGlb(path.join(group,'1-1-甲.glb'),[['left',-.1,.02]]);
|
||
await writeGlb(path.join(group,'1-2-乙.glb'),[['right',0,.015]]);
|
||
const out=path.join(p,'out'),r=await generate(dir,out,()=>{});
|
||
const raw=JSON.parse(readFileSync(path.join(out,'整机-装配步骤.json')));
|
||
assert.equal(r.needReview,0);assert.equal(r.steps,2);assert.equal(raw.files[0].path,'1测试/1-1-甲.glb');
|
||
assert.ok(Math.abs(raw.parts[0].position[0]-.2)<1e-6);assert.ok(Math.hypot(...raw.parts[1].installOffset)>0);
|
||
// Whole model may be external; local components are built independently and
|
||
// joined before the final folder's fasteners. No geometry is re-exported.
|
||
const third=path.join(dir,'2总装');mkdirSync(third);
|
||
await writeGlb(path.join(third,'2-1-丙.glb'),[['final',.5,.01]]);
|
||
const last=path.join(dir,'3总装');mkdirSync(last);
|
||
await writeGlb(path.join(last,'3-1-丁.glb'),[['cap',.7,.01]]);
|
||
const external=path.join(p,'外部整机.glb');
|
||
await writeGlb(external,[['left',.1,.02],['right',.3,.015],['final',.5,.01],['cap',.7,.01]]);
|
||
const groupedOut=path.join(p,'grouped');
|
||
const grouped=await generate(dir,groupedOut,()=>{},{reference:external,finalGroup:3});
|
||
const groupedRaw=JSON.parse(readFileSync(path.join(groupedOut,'外部整机-装配步骤.json')));
|
||
assert.equal(grouped.steps,6);assert.equal(groupedRaw.steps[3].type,'join');
|
||
assert.equal(groupedRaw.steps[5].groupId,undefined);
|
||
assert.equal(grouped.records.find(r=>r.id==='p-2-1').status,'foundation');
|
||
assert.deepEqual(groupedRaw.groups[0].parts,['p-1-1','p-1-2']);
|
||
const flat=path.join(p,'flat');
|
||
mkdirSync(flat);
|
||
for (const [source, name] of [
|
||
[path.join(group,'1-1-甲.glb'),'1-1-甲.glb'],
|
||
[path.join(group,'1-2-乙.glb'),'1+2-乙.glb'],
|
||
[path.join(third,'2-1-丙.glb'),'1+3-丙.glb'],
|
||
[path.join(last,'3-1-丁.glb'),'1-4-丁.glb'],
|
||
]) copyFileSync(source,path.join(flat,name));
|
||
const flatOut=path.join(p,'flat-out');
|
||
const isolated=await generate(flat,flatOut,()=>{},{reference:external});
|
||
const flatRaw=JSON.parse(readFileSync(path.join(flatOut,'外部整机-装配步骤.json')));
|
||
assert.deepEqual(flatRaw.files.map(file=>file.path),['1-1-甲.glb','1+2-乙.glb','1+3-丙.glb','1-4-丁.glb']);
|
||
assert.deepEqual(flatRaw.steps.map(step=>step.visibleParts),[undefined,['p-1-2'],['p-1-2','p-1-3'],undefined]);
|
||
assert.equal(isolated.records[1].status,'foundation','the hidden base does not obstruct the isolated group');
|
||
assert.notEqual(isolated.records[3].status,'foundation','the regular step uses the accumulated assembly');
|
||
const rules=path.join(p,'rules');
|
||
const layout=['1腿/1-1.glb','2髋/2A/2A-1.glb','2髋/2B/2B-1.glb','2髋/!2/!2-1.glb','2髋/!2/!2-2.glb',
|
||
'3盖/3-1.glb','3盖/#3-2.glb','3盖/3-3.glb','3盖/#3-4.glb','3盖/3+5.glb','3盖/3+6.glb','3盖/3-7.glb','#4总装/#4-1.glb'];
|
||
const references=layout.map((_,i)=>[`part-${i}`,i*.1,.01]);
|
||
const ruleReference=path.join(p,'规则整机.glb');
|
||
await writeGlb(ruleReference,references);
|
||
for (const [i,file] of [...layout.entries()].reverse()) {
|
||
const target=path.join(rules,file);
|
||
mkdirSync(path.dirname(target),{recursive:true});
|
||
await writeGlb(target,[[references[i][0],0,.01]]);
|
||
}
|
||
const ruleOut=path.join(p,'rule-out');
|
||
const ruled=await generate(rules,ruleOut,()=>{},{reference:ruleReference});
|
||
const ruleRaw=JSON.parse(readFileSync(path.join(ruleOut,'规则整机-装配步骤.json')));
|
||
const parsed=validatePackage(ruleRaw,'assembly','https://example.com/rp1/steps.json');
|
||
const ids=ruleRaw.parts.map(part=>part.id);
|
||
assert.deepEqual(ruleRaw.files.map(file=>file.path),layout);
|
||
assert.deepEqual(parsed.steps.flatMap((step,index)=>step.type==='join'?[]:[[...visibleAssemblyParts(parsed,index)]]),
|
||
[[0],[1],[2],[1,2,3],[1,2,3,4],[5],[0,1,2,3,4,5,6],[5,6,7],[0,1,2,3,4,5,6,7,8],[9],[9,10],[5,6,7,8,9,10,11],
|
||
layout.map((_,i)=>i)].map(scope=>scope.map(i=>ids[i])));
|
||
assert.equal(ruled.records.find(record=>record.id==='p-3-5').status,'foundation');
|
||
assert.equal(parsed.playback,'scoped-v1');
|
||
assert.equal(parsed.steps.filter(step=>step.type==='join').length,7);
|
||
assert.deepEqual(parsed.steps.slice(-4,-1).map(step=>step.groupId),['group-1','group-2','group-3']);
|
||
assert.match(parsed.files.get(layout.at(-1)).url,/\/%234.*\/%234-1\.glb$/);
|
||
const signed='https://example.com/rp1/'+layout.at(-1)+'?signature=x%2By%23z';
|
||
assert.match(resourceIndex([{relativePath:layout.at(-1),url:signed,sizeBytes:1}],{assembly:true}).get(layout.at(-1)).url,
|
||
/\/%234.*\/%234-1\.glb\?signature=x%2By%23z$/);
|
||
rmSync(third,{recursive:true});
|
||
rmSync(last,{recursive:true});
|
||
await writeGlb(path.join(group,'1-2-乙.glb'),[['right',0,.025]]);
|
||
const invalid=path.join(p,'invalid');await assert.rejects(generate(dir,invalid,()=>{}),/网格不一致/);assert.equal(existsSync(invalid),false);
|
||
});
|
||
|
||
test('hex tool measures and aligns to a recessed socket and skips blocked or mismatched fasteners',()=>{
|
||
const tipGeometry=new CylinderGeometry(.0017/Math.sqrt(3),.0017/Math.sqrt(3),.02,6).rotateX(Math.PI/2);
|
||
const tool=measureHexKey([tipGeometry],'key.glb');
|
||
assert.ok(Math.abs(tool.acrossFlats-.0017)<1e-8);
|
||
// Shaft, circular head and hex socket wall, including a floor below its rim.
|
||
const rings=[[-.008,.0011],[-.0015,.0011],[-.0015,.0025],[0,.0025],[0,.0009,true],[-.001,.0009,true],[-.001,0]];
|
||
const vertices=[], indices=[];
|
||
const sides=36;
|
||
for (const [z,r,hex] of rings) for (let i=0;i<sides;i++) {
|
||
const theta=2*Math.PI*i/sides;
|
||
const radius=hex ? r/Math.cos(theta-Math.round(theta/(Math.PI/3))*Math.PI/3) : r;
|
||
vertices.push(radius*Math.cos(theta),radius*Math.sin(theta),z);
|
||
}
|
||
for (let ring=0;ring<rings.length-1;ring++) for (let i=0;i<sides;i++) {
|
||
const a=ring*sides+i,b=ring*sides+(i+1)%sides;
|
||
indices.push(a,b,a+sides,b,b+sides,a+sides);
|
||
}
|
||
const screw=new BufferGeometry().setAttribute('position',new Float32BufferAttribute(vertices,3)).setIndex(indices);
|
||
const source=new Matrix4().makeRotationY(.4).setPosition(.02,.03,.04);
|
||
const pose={scale:[1,1,1]}, result={status:'clear-to-seating',offset:[0,0,.01]};
|
||
const match=hexInstallation(screw,source,pose,result,tool);
|
||
assert.ok(match.installation,match.reason);
|
||
assert.ok(Math.abs(match.acrossFlats-.0018)<1e-8);
|
||
const m=match.installation;
|
||
const toolAxis=new Vector3(...tool.config.tipAxis).applyQuaternion(new Quaternion(...m.toolQuaternion));
|
||
assert.ok(toolAxis.distanceTo(new Vector3(...m.axis))<1e-8);
|
||
assert.ok(new Vector3(...m.socketPosition).distanceTo(new Vector3(0,0,-.0005).applyMatrix4(source))<1e-8);
|
||
assert.equal(hexInstallation(screw,source,pose,result,{...tool,acrossFlats:.002}).reason,'扳手尺寸与六角孔不匹配');
|
||
assert.equal(hexInstallation(screw,source,pose,{status:'review-path'},tool).reason,'安装方向未确认');
|
||
});
|
||
|
||
test('compact prefixes keep both digits and extra caps retain original relative paths', t=>{
|
||
const dir=workspace(t),g=path.join(dir,'1部');mkdirSync(g);
|
||
writeFileSync(path.join(dir,'整机.glb'),'');
|
||
for(let i=1;i<=13;i++)writeFileSync(path.join(g,`1-${i}STP39-14.glb`),'');
|
||
writeFileSync(path.join(g,'1-附加-端盖.glb'),'');
|
||
assert.throws(()=>numberedInput(dir),/附加件/);
|
||
const {parts}=numberedInput(dir,{extraBefore:13});
|
||
assert.equal(parts[9].number,10);
|
||
assert.equal(parts[9].name,'STP39-14');
|
||
assert.deepEqual(parts.slice(-2).map(p=>p.path),['1部/1-附加-端盖.glb','1部/1-13STP39-14.glb']);
|
||
});
|
||
|
||
test('a threaded pilot hole admits an axial preview but a solid plate or an obstructed head does not',async()=>{
|
||
const {CylinderGeometry,Matrix4,Vector3}=await import('three');
|
||
const {mergeGeometries}=await import('three/addons/utils/BufferGeometryUtils.js');
|
||
const {collider}=await import('../scripts/lib/assembly-axis-planner.mjs');
|
||
const {threadFit}=await import('../scripts/lib/thread-fit.mjs');
|
||
const shaft=new CylinderGeometry(.001,.001,.006,32).translate(0,-.003,0);
|
||
const cap=new CylinderGeometry(.002,.002,.0016,32).translate(0,.0008,0);
|
||
const local=mergeGeometries([shaft,cap]);local.computeBoundingBox();
|
||
const around=bore=>{
|
||
const rim=new CylinderGeometry(bore,bore,.006,48,1,true).translate(0,-.003,0);
|
||
return [collider('rim',rim)];
|
||
};
|
||
const check=obstacles=>threadFit(local,new Matrix4(),new Vector3(0,1,0),obstacles,.02);
|
||
assert.equal(check(around(.00089))?.status,'visual-thread-fit');
|
||
assert.equal(check(around(.00062))?.status,'visual-bore-axis');
|
||
const block=collider('plate',new BoxGeometry(.01,.00001,.01).translate(0,-.003,0));
|
||
assert.equal(check([block]),null);
|
||
const lip=collider('lip',new BoxGeometry(.0001,.00001,.0001).translate(.0016,.003,0));
|
||
assert.equal(check([...around(.00089),lip]),null);
|
||
});
|
||
|
||
test('group placement always has a visible move; blocked presentation paths stay explicitly unverified',async()=>{
|
||
const {collider}=await import('../scripts/lib/assembly-axis-planner.mjs');
|
||
const moving=[collider('moving',new BoxGeometry(.01,.01,.01))];
|
||
const first=planGroupEntry(moving,[]);
|
||
assert.equal(first.status,'foundation');assert.ok(Math.hypot(...first.offset)>0);
|
||
const blocked=planGroupEntry(moving,[collider('closed shell',new BoxGeometry(.06,.06,.06))]);
|
||
assert.equal(blocked.status,'review-path');assert.equal(blocked.presentationOnly,true);
|
||
assert.ok(Math.hypot(...blocked.offset)>0);assert.ok(blocked.checks.length>0);
|
||
});
|