| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981 |
- /* =========================================================
- 几何引擎:参数化壳体 + 材质 + 爆炸图 + 标注 + 导出
- 1 单位 = 1 mm
- ========================================================= */
- const STAGE = (function(){
- const B = BABYLON;
- const V3 = function(x,y,z){ return new B.Vector3(x,y,z); };
- let engine=null, scene=null, camera=null, ground=null, root=null, dimRoot=null, shadowMat=null;
- let host=null, canvas=null, readyFlag=false, pending=null;
- let labels=[], labelEls=[];
- const matCache={}, fixedCache={};
- let cur={ project:'silicone', params:{}, material:'', explode:0, dims:true, cutForce:false };
- let parts=[];
- let customMap={}, cutaway=false, selCb=null, dragCb=null, custUid=1, solo=null;
- /* ---------------- 材质 ---------------- */
- function pbr(key,cfg){
- if(matCache[key]) return matCache[key];
- const m=new B.PBRMaterial('mat-'+key,scene);
- m.albedoColor=B.Color3.FromHexString(cfg.albedo);
- m.metallic=cfg.metallic!==undefined?cfg.metallic:0;
- m.roughness=cfg.rough!==undefined?cfg.rough:0.5;
- if(cfg.cc!==undefined){
- m.clearCoat.isEnabled=true;
- m.clearCoat.intensity=cfg.cc;
- m.clearCoat.roughness=Math.max(0.03,1-(cfg.cci||0.35));
- }
- if(cfg.alpha!==undefined){
- m.alpha=cfg.alpha;
- m.transparencyMode=B.Material.MATERIAL_ALPHABLEND;
- }
- if(cfg.env!==undefined) m.environmentIntensity=cfg.env;
- m.backFaceCulling=false;
- matCache[key]=m;
- return m;
- }
- function fixed(key){
- if(fixedCache[key]) return fixedCache[key];
- fixedCache[key]=pbr('fx-'+key, FIXED_MATS[key]);
- return fixedCache[key];
- }
- /* 半透明「透视」材质:爆炸/剖视时让内部结构可见 */
- function ghost(key){
- const gk='gh-'+key;
- if(matCache[gk]) return matCache[gk];
- const src=MATERIALS[key]||MATERIALS[PROJECTS[cur.project].materials[0]];
- const cfg=Object.assign({},src,{alpha:0.30,env:0.2,cc:0.05});
- return pbr(gk,cfg);
- }
- /* ---------------- 2D 轮廓 ---------------- */
- function roundedPath(w,h,r,seg){
- const hw=w/2,hh=h/2;
- r=Math.max(0.05,Math.min(r,Math.min(hw,hh)-0.02));
- const pts=[];
- const corners=[
- {cx:hw-r,cz:hh-r,a0:0},
- {cx:-(hw-r),cz:hh-r,a0:90},
- {cx:-(hw-r),cz:-(hh-r),a0:180},
- {cx:hw-r,cz:-(hh-r),a0:270}
- ];
- for(const c of corners){
- for(let i=0;i<seg;i++){
- const a=(c.a0+90*i/seg)*Math.PI/180;
- pts.push({x:c.cx+r*Math.cos(a),z:c.cz+r*Math.sin(a)});
- }
- }
- return pts;
- }
- function radialN(p){ const l=Math.hypot(p.x,p.z)||1; return V3(p.x/l,0,p.z/l); }
- function assemble(name,chunks,parent){
- const pos=[],idx=[],nrm=[];
- let base=0;
- chunks.forEach(ch=>{
- ch.p.forEach(v=>pos.push(v.x,v.y,v.z));
- ch.n.forEach(v=>nrm.push(v.x,v.y,v.z));
- ch.i.forEach(i=>idx.push(i+base));
- base+=ch.p.length;
- });
- const vd=new B.VertexData();
- vd.positions=pos; vd.indices=idx; vd.normals=nrm;
- const mesh=new B.Mesh(name,scene);
- vd.applyToMesh(mesh);
- if(parent) mesh.parent=parent;
- return mesh;
- }
- /* 环带(上下两个同点数轮廓) */
- function ringStrip(ringA,yA,ringB,yB,nf){
- const N=ringA.length,p=[],n=[],i=[];
- for(let k=0;k<N;k++){
- const a=ringA[k],b=ringB[k];
- p.push(V3(a.x,yA,a.z),V3(b.x,yB,b.z));
- n.push(nf(a,true),nf(b,false));
- }
- for(let k=0;k<N;k++){
- const a1=k*2,b1=k*2+1,a2=((k+1)%N)*2,b2=((k+1)%N)*2+1;
- i.push(a1,a2,b2,a1,b2,b1);
- }
- return {p,n,i};
- }
- /* 空心圆角框(表壳类) */
- function hollowFrame(name,spec,parent){
- const {ow,od,orr,iw,id,irr,y0,y1,chamfer,seg}=spec;
- const A=roundedPath(ow,od,orr,seg);
- const Bc=roundedPath(ow,od,orr,seg);
- const C=roundedPath(Math.max(1,ow-2*chamfer),Math.max(1,od-2*chamfer),Math.max(0.2,orr-chamfer),seg);
- const D=roundedPath(iw,id,irr,seg);
- const E=roundedPath(iw,id,irr,seg);
- const ch=[];
- ch.push(ringStrip(A,y0,Bc,y1-chamfer,p=>radialN(p)));
- ch.push(ringStrip(Bc,y1-chamfer,C,y1,p=>{
- const r=radialN(p); return V3(r.x*0.707,0.707,r.z*0.707);
- }));
- ch.push(ringStrip(C,y1,D,y1,()=>V3(0,1,0)));
- ch.push(ringStrip(D,y1,E,y0,p=>{
- const r=radialN(p); return V3(-r.x,0,-r.z);
- }));
- ch.push(ringStrip(E,y0,A,y0,()=>V3(0,-1,0)));
- return assemble(name,ch,parent);
- }
- /* 实心圆角板 */
- function solidSlab(name,spec,parent){
- const {w,d,r,y0,y1,seg}=spec;
- const A=roundedPath(w,d,r,seg);
- const ch=[];
- ch.push(ringStrip(A,y0,roundedPath(w,d,r,seg),y1,p=>radialN(p)));
- const tp=[V3(0,y1,0)],tn=[V3(0,1,0)],ti=[];
- A.forEach(p=>{ tp.push(V3(p.x,y1,p.z)); tn.push(V3(0,1,0)); });
- for(let k=0;k<A.length;k++) ti.push(0,1+k,1+((k+1)%A.length));
- ch.push({p:tp,n:tn,i:ti});
- const bp=[V3(0,y0,0)],bn=[V3(0,-1,0)],bi=[];
- A.forEach(p=>{ bp.push(V3(p.x,y0,p.z)); bn.push(V3(0,-1,0)); });
- for(let k=0;k<A.length;k++) bi.push(0,1+((k+1)%A.length),1+k);
- ch.push({p:bp,n:bn,i:bi});
- return assemble(name,ch,parent);
- }
- /* 回转体:profile = [{r,y}] 闭合,按 CCW 给出(法线自动朝外) */
- function revolve(name,profile,seg,parent){
- const ch=[];
- for(let k=0;k<profile.length;k++){
- const p0=profile[k],p1=profile[(k+1)%profile.length];
- const dr=p1.r-p0.r,dy=p1.y-p0.y,len=Math.hypot(dr,dy);
- if(len<1e-4) continue;
- const n2r=dy/len,n2y=-dr/len;
- const pos=[],nrm=[],idx=[];
- for(let j=0;j<seg;j++){
- const th=j/seg*Math.PI*2, th2=((j+1)%seg)/seg*Math.PI*2;
- const c0=Math.cos(th),s0=Math.sin(th),c1=Math.cos(th2),s1=Math.sin(th2);
- pos.push(V3(p0.r*c0,p0.y,p0.r*s0),V3(p1.r*c0,p1.y,p1.r*s0),V3(p1.r*c1,p1.y,p1.r*s1),V3(p0.r*c1,p0.y,p0.r*s1));
- nrm.push(V3(n2r*c0,n2y,n2r*s0),V3(n2r*c0,n2y,n2r*s0),V3(n2r*c1,n2y,n2r*s1),V3(n2r*c1,n2y,n2r*s1));
- }
- for(let j=0;j<seg;j++){
- const b=j*4;
- idx.push(b,b+1,b+2,b,b+2,b+3);
- }
- ch.push({p:pos,n:nrm,i:idx});
- }
- return assemble(name,ch,parent);
- }
- function arcPts(cx,cy,r,a0,a1,n){
- const out=[];
- for(let i=0;i<=n;i++){
- const a=(a0+(a1-a0)*i/n)*Math.PI/180;
- out.push({r:cx+r*Math.cos(a),y:cy+r*Math.sin(a)});
- }
- return out;
- }
- function dedupe(pts){
- const out=[];
- pts.forEach(p=>{
- const last=out[out.length-1];
- if(!last||Math.abs(last.r-p.r)>1e-4||Math.abs(last.y-p.y)>1e-4) out.push(p);
- });
- if(out.length>2){
- const f=out[0],l=out[out.length-1];
- if(Math.abs(f.r-l.r)<1e-4&&Math.abs(f.y-l.y)<1e-4) out.pop();
- }
- return out;
- }
- /* ---------------- 场景 ---------------- */
- function init(canvasEl,hostEl){
- canvas=canvasEl; host=hostEl;
- engine=new B.Engine(canvas,true,{preserveDrawingBuffer:true,stencil:true,alpha:true},true);
- engine.setHardwareScalingLevel(1/Math.min(2,window.devicePixelRatio||1));
- scene=new B.Scene(engine);
- scene.clearColor=new B.Color4(0,0,0,0);
- scene.ambientColor=new B.Color3(0.16,0.18,0.22);
- camera=new B.ArcRotateCamera('cam',-1.05,1.03,150,V3(0,0,0),scene);
- camera.lowerRadiusLimit=18; camera.upperRadiusLimit=900;
- camera.lowerBetaLimit=0.1; camera.upperBetaLimit=1.54;
- camera.wheelDeltaPercentage=0.02;
- camera.pinchDeltaPercentage=0.03;
- camera.attachControl(canvas,true);
- camera.minZ=0.1; camera.fov=0.75; camera.inertia=0.72;
- camera.pinchZoom=true;
- camera.panningSensibility=160;
- camera.angularSensibilityX=760; camera.angularSensibilityY=760;
- camera.useNaturalPinchZoom=true;
- camera.allowUpsideDown=false;
- const hemi=new B.HemisphericLight('hemi',V3(0.1,1,0.2),scene);
- hemi.intensity=0.5;
- hemi.groundColor=new B.Color3(0.10,0.12,0.16);
- const d1=new B.DirectionalLight('d1',V3(-0.5,-1,-0.7),scene);
- d1.intensity=1.5; d1.position=V3(140,200,160);
- const d2=new B.DirectionalLight('d2',V3(0.8,-0.55,0.7),scene);
- d2.intensity=0.85; d2.position=V3(-160,120,-180);
- try{
- const env=B.CubeTexture.CreateFromPrefilteredData('https://assets.babylonjs.com/environments/environmentSpecular.env',scene);
- scene.environmentTexture=env;
- scene.environmentIntensity=0.9;
- }catch(e){ scene.environmentIntensity=0; }
- const dt=new B.DynamicTexture('shadowTex',{width:256,height:256},scene,false);
- const ctx=dt.getContext();
- const g=ctx.createRadialGradient(128,128,6,128,128,126);
- g.addColorStop(0,'rgba(0,0,0,0.55)');
- g.addColorStop(0.4,'rgba(0,0,0,0.28)');
- g.addColorStop(0.72,'rgba(0,0,0,0.09)');
- g.addColorStop(1,'rgba(0,0,0,0)');
- ctx.fillStyle=g; ctx.fillRect(0,0,256,256); dt.update();
- ground=B.MeshBuilder.CreateGround('ground',{width:300,height:300},scene);
- shadowMat=new B.StandardMaterial('shadowMat',scene);
- shadowMat.diffuseTexture=dt; shadowMat.opacityTexture=dt;
- shadowMat.emissiveColor=new B.Color3(0,0,0);
- shadowMat.specularColor=new B.Color3(0,0,0);
- shadowMat.disableLighting=true;
- shadowMat.backFaceCulling=false;
- ground.material=shadowMat; ground.isPickable=false;
- engine.runRenderLoop(()=>{
- if(scene) scene.render();
- updateLabels();
- });
- new ResizeObserver(()=>engine.resize()).observe(host);
- window.addEventListener('resize',()=>engine.resize());
- readyFlag=true;
- scene.onPointerObservable.add(pi=>{
- if(pi.type===B.PointerEventTypes.POINTERDOUBLETAP){
- const m2=pi.pickInfo&&pi.pickInfo.pickedMesh;
- const md2=m2&&m2.metadata;
- if(md2&&md2.part) focusPart(md2.part); else frame();
- return;
- }
- if(pi.type!==B.PointerEventTypes.POINTERPICK) return;
- const m=pi.pickInfo&&pi.pickInfo.pickedMesh;
- if(!m) return;
- const md=m.metadata||{};
- if(!md.part){ if(selCb) selCb(null); return; }
- highlight(md.part);
- if(selCb) selCb(md.part,md.custom?m:null);
- });
- ensureLabelHost();
- if(pending){ const p=pending; pending=null; load(p.project,p.params,p.material,p.explode); }
- }
- function ensureLabelHost(){
- if(!host) return null;
- let el=host.querySelector('.dimlayer');
- if(!el){ el=document.createElement('div'); el.className='dimlayer'; host.appendChild(el); }
- return el;
- }
- /* ---------------- 标注 ---------------- */
- function addDim(a,b,text,color){
- if(!dimRoot) dimRoot=new B.TransformNode('dims',scene);
- const col=B.Color3.FromHexString(color||'#7ec8ff');
- const line=B.MeshBuilder.CreateLines('dl',{points:[a,b]},scene);
- line.color=col; line.parent=dimRoot; line.isPickable=false;
- const dir=b.subtract(a);
- if(dir.length()>0.05){
- const d=dir.normalize();
- const perp=V3(-d.z,0.4,d.x);
- if(perp.length()>0.05){
- perp.normalize();
- [a,b].forEach(pt=>{
- const tick=B.MeshBuilder.CreateLines('tk',{points:[pt.add(perp.scale(2.0)),pt.subtract(perp.scale(2.0))]},scene);
- tick.color=col; tick.parent=dimRoot; tick.isPickable=false;
- });
- }
- }
- labels.push({p:a.add(b).scale(0.5),t:text});
- }
- /* ---------------- 建模:三款 ---------------- */
- function buildSilicone(p){
- const g=new B.TransformNode('root',scene);
- const seg=24;
- const t=p.t, ow=p.w+2*t, od=p.d+2*t, y0=-p.h/2, y1=p.h/2;
- const ir=Math.max(0.5,p.r), orr=ir+t;
- const body=hollowFrame('body',{ow,od,orr,iw:p.w,id:p.d,irr:ir,y0,y1,chamfer:0.7,seg},g);
- body.metadata={role:'body',part:'body'};
- const floor=solidSlab('floor',{w:p.w-0.4,d:p.d-0.4,r:Math.max(0.5,ir-0.2),y0,y1:y0+1.2,seg},g);
- floor.metadata={role:'body',part:'floor'};
- const hx=p.hg/2, hz=-(od/2-3.0);
- const hornL=B.MeshBuilder.CreateCylinder('hornL',{diameterBottom:p.hd,diameterTop:p.hd*0.28,height:p.hh,tessellation:18},scene);
- hornL.position=V3(-hx,y1+p.hh/2-0.45,hz); hornL.rotation.x=-0.28; hornL.rotation.z=-0.10; hornL.parent=g;
- hornL.metadata={role:'accent',part:'hornL'};
- const hornR=B.MeshBuilder.CreateCylinder('hornR',{diameterBottom:p.hd,diameterTop:p.hd*0.28,height:p.hh,tessellation:18},scene);
- hornR.position=V3(hx,y1+p.hh/2-0.45,hz); hornR.rotation.x=-0.28; hornR.rotation.z=0.10; hornR.parent=g;
- hornR.metadata={role:'accent',part:'hornR'};
- const screen=solidSlab('screen',{w:Math.max(6,p.w-2.8),d:Math.max(6,p.d-2.8),r:Math.max(0.4,ir-1.4),y0:y1-0.62,y1:y1-0.30,seg},g);
- screen.metadata={role:'glass',part:'screen'};
- const crown=B.MeshBuilder.CreateCylinder('crown',{diameter:3.2,height:2.2,tessellation:16},scene);
- crown.rotation.z=Math.PI/2;
- crown.position=V3(ow/2+p.cr*0.5,y0+p.h*0.55,0); crown.parent=g;
- crown.metadata={role:'body',part:'crown'};
- addDim(V3(-ow/2,y0-5.5,od/2+2.5),V3(ow/2,y0-5.5,od/2+2.5),'外宽 '+ow.toFixed(1));
- addDim(V3(-(ow/2+4),y0-1,od/2+3),V3(-(ow/2+4),y1,od/2+3),'总高 '+p.h.toFixed(1));
- addDim(V3(ow/2+11,y0-5.5,-od/2),V3(ow/2+11,y0-5.5,od/2),'外深 '+od.toFixed(1));
- addDim(V3(-p.hg/2,y1+p.hh+2.0,hz),V3(p.hg/2,y1+p.hh+2.0,hz),'角距 '+p.hg.toFixed(1));
- return {root:g,size:V3(ow,p.h+p.hh*2,od),parts:[
- {id:'body',node:body,ex:V3(0,0,0)},
- {id:'floor',node:floor,ex:V3(0,-14,0)},
- {id:'hornL',node:hornL,ex:V3(-7,16,0)},
- {id:'hornR',node:hornR,ex:V3(7,16,0)},
- {id:'screen',node:screen,ex:V3(0,20,0)},
- {id:'crown',node:crown,ex:V3(16,4,0)}
- ]};
- }
- function buildRecorder(p){
- const g=new B.TransformNode('root',scene);
- const seg=48;
- const ro=p.D/2, ri=ro-p.t, y0=-p.H/2, y1=p.H/2;
- const r=Math.min(p.t*0.65,1.8);
- const bodyProf=dedupe([
- {r:ri,y:y0+r},
- ...arcPts(ri+r,y0+r,r,180,270,3),
- ...arcPts(ro-r,y0+r,r,270,360,3),
- {r:ro,y:y1},
- {r:ri,y:y1}
- ]);
- const body=revolve('body',bodyProf,seg,g);
- body.metadata={role:'body',part:'body'};
- const base=revolve('base',dedupe([
- {r:0.6,y:y0},{r:Math.max(2,ro-1.2),y:y0},{r:Math.max(2,ro-1.2),y:y0+1.1},{r:0.6,y:y0+1.1}
- ]),seg,g);
- base.metadata={role:'body',part:'base'};
- // 上盖穹顶
- const dome=p.dm, lidPts=[{r:0.5,y:y1},{r:ro-0.2,y:y1}];
- const steps=9;
- for(let i=0;i<=steps;i++){
- const a=i/steps*Math.PI/2;
- lidPts.push({r:0.5+(ro-0.7)*Math.cos(a),y:y1+dome*Math.sin(a)});
- }
- const lid=revolve('lid',dedupe(lidPts),seg,g);
- lid.metadata={role:'body',part:'lid'};
- const loop=B.MeshBuilder.CreateTorus('loop',{diameter:p.ld+p.t*1.9,thickness:p.t*0.9,tessellation:28},scene);
- loop.rotation.x=Math.PI/2;
- loop.position=V3(ro+p.lh*0.55,y1-1.6,0); loop.parent=g;
- loop.metadata={role:'body',part:'loop'};
- const micMeshes=[];
- const micR=Math.max(4,ro*0.4);
- for(let i=0;i<4;i++){
- const a=Math.PI/4+i*Math.PI/2;
- const m=B.MeshBuilder.CreateCylinder('mic'+i,{diameter:1.0,height:1.8,tessellation:10},scene);
- m.position=V3(Math.cos(a)*micR,y1+dome*0.72+0.2,Math.sin(a)*micR);
- m.parent=g; m.material=fixed('dark');
- m.metadata={role:'dark',part:'mic'};
- micMeshes.push(m);
- }
- const usb=B.MeshBuilder.CreateBox('usbc',{width:1.4,height:3.2,depth:9.0},scene);
- usb.position=V3(ro-0.4,y0+3.0,0); usb.parent=g; usb.material=fixed('dark');
- usb.metadata={role:'dark',part:'usbc'};
- const btn=B.MeshBuilder.CreateCylinder('btn',{diameter:3.6,height:1.2,tessellation:20},scene);
- btn.rotation.z=Math.PI/2; btn.position=V3(-ro+0.1,y1-1.2,0); btn.parent=g;
- btn.metadata={role:'body',part:'btn'};
- const pcb=B.MeshBuilder.CreateCylinder('pcb',{diameter:Math.min(ro*2-5,26),height:1.2,tessellation:32},scene);
- pcb.position=V3(0,y1-3.4,0); pcb.parent=g; pcb.material=fixed('pcb');
- pcb.metadata={role:'pcb',part:'pcb'};
- const cell=B.MeshBuilder.CreateCylinder('cell',{diameter:Math.min(ro*2-8,20),height:5.4,tessellation:28},scene);
- cell.position=V3(0,y0+4.4,0); cell.parent=g; cell.material=fixed('cell');
- cell.metadata={role:'cell',part:'cell'};
- addDim(V3(-ro,y0-7,0),V3(ro,y0-7,0),'Ø'+p.D.toFixed(1));
- addDim(V3(ro+9,y0,0),V3(ro+9,y1,0),'高 '+p.H.toFixed(1));
- addDim(V3(0,y1+6,0),V3(ro+p.lh+2,y1+6,0),'挂环 '+p.lh.toFixed(1));
- const ps=[
- {id:'body',node:body,ex:V3(0,0,0)},
- {id:'base',node:base,ex:V3(0,-16,0)},
- {id:'cell',node:cell,ex:V3(0,2,0)},
- {id:'pcb',node:pcb,ex:V3(0,14,0)},
- {id:'lid',node:lid,ex:V3(0,26,0)},
- {id:'loop',node:loop,ex:V3(18,2,0)},
- {id:'btn',node:btn,ex:V3(-18,2,0)},
- {id:'usbc',node:usb,ex:V3(16,-2,0)}
- ];
- micMeshes.forEach(m=>ps.push({id:'mic',node:m,ex:V3(0,30,0)}));
- return {root:g,size:V3(p.D+10,p.H+p.dm, p.D),parts:ps};
- }
- function buildRound(p){
- const g=new B.TransformNode('root',scene);
- const seg=64;
- const ro=p.D/2, y0=-p.H/2, y1=p.H/2, bd=p.bd/2, sd=p.sd/2, dep=p.dep;
- const re=Math.min(3.0,p.t*1.3);
- /* CNC 弧面:外壁 → 顶部凸圆 R → 极短平台 → 屏边凹圆 R → 沉台
- 全部由工艺参数驱动,工厂按 rimR / dep / cham 直接编程 */
- const rimR=Math.max(0.4,Math.min(p.rimR||1.8, (ro-bd)*0.55));
- const cham=Math.max(0,Math.min(p.cham||0.5, (ro-bd)*0.35));
- const seam=Math.max(0.5,Math.min(p.dep||1.2, ro-rimR-bd+0.02));
- const flat=Math.max(0,ro-rimR-(bd+seam));
- const bezelProf=dedupe([
- {r:sd,y:y0},
- {r:Math.max(sd,ro-cham),y:y0},
- ...(cham>0.05?arcPts(ro-cham,y0+cham,cham,270,360,3):[{r:ro,y:y0}]),
- {r:ro,y:y1-rimR},
- ...arcPts(ro-rimR,y1-rimR,rimR,0,90,6),
- ...(flat>0.15?[{r:bd+seam,y:y1}]:[]),
- ...arcPts(bd+seam,y1-seam,seam,90,180,6),
- {r:sd,y:y1-seam}
- ]);
- const bezel=revolve('bezel',bezelProf,seg,g);
- bezel.metadata={role:'body',part:'bezel'};
- const seatY=y1-seam;
- const black=B.MeshBuilder.CreateCylinder('black',{diameter:p.bd-0.3,height:0.6,tessellation:seg},scene);
- black.position=V3(0,seatY+0.3,0); black.parent=g; black.material=fixed('dark');
- black.metadata={role:'dark',part:'black'};
- const glass=B.MeshBuilder.CreateCylinder('glass',{diameter:p.sd+0.4,height:0.8,tessellation:seg},scene);
- glass.position=V3(0,seatY+0.4,0); glass.parent=g; glass.material=fixed('glass');
- glass.metadata={role:'glass',part:'glass'};
- const capProf=dedupe([
- {r:0.6,y:y0},
- {r:ro-p.t-0.6,y:y0},
- {r:ro-p.t-0.6,y:y0+p.cap-0.5},
- ...arcPts(ro-p.t-1.1,y0+p.cap-0.5,0.5,0,90,2),
- {r:0.6,y:y0+p.cap}
- ]);
- const cap=revolve('cap',capProf,seg,g);
- cap.metadata={role:'body',part:'cap'};
- const th=B.MeshBuilder.CreateTorus('thread',{diameter:p.D-p.t*2-1.6,thickness:0.9,tessellation:seg},scene);
- th.position=V3(0,y0+p.cap+0.05,0); th.parent=g; th.material=fixed('dark');
- th.metadata={role:'dark',part:'thread'};
- const bosses=[];
- for(let i=0;i<4;i++){
- const a=Math.PI/4+i*Math.PI/2;
- const b=B.MeshBuilder.CreateCylinder('boss'+i,{diameter:4.2,height:5.2,tessellation:14},scene);
- b.position=V3(Math.cos(a)*(ro-9),y0+p.cap+2.8,Math.sin(a)*(ro-9));
- b.parent=g; b.material=fixed('brass');
- b.metadata={role:'brass',part:'boss'};
- bosses.push(b);
- }
- const pcb=B.MeshBuilder.CreateCylinder('pcb',{diameter:Math.min(44,p.D-14),height:1.2,tessellation:40},scene);
- pcb.position=V3(0,y1-dep-3.4,0); pcb.parent=g; pcb.material=fixed('pcbDark');
- pcb.metadata={role:'pcb',part:'pcb'};
- const cell=B.MeshBuilder.CreateCylinder('cell',{diameter:Math.min(36,p.D-22),height:5.0,tessellation:36},scene);
- cell.position=V3(0,y0+p.cap+4.6,0); cell.parent=g; cell.material=fixed('cell');
- cell.metadata={role:'cell',part:'cell'};
- const sb=B.MeshBuilder.CreateBox('sbtn',{width:1.2,height:5.4,depth:2.0},scene);
- sb.position=V3(ro-0.1,1.6,-2); sb.parent=g;
- sb.metadata={role:'body',part:'sbtn'};
- const usb=B.MeshBuilder.CreateBox('usbc',{width:1.5,height:3.2,depth:8.8},scene);
- usb.position=V3(-ro+0.4,y0+5.4,0); usb.parent=g; usb.material=fixed('dark');
- usb.metadata={role:'dark',part:'usbc'};
- addDim(V3(-ro,y0-7,0),V3(ro,y0-7,0),'Ø'+p.D.toFixed(2));
- addDim(V3(ro+6,y0,0),V3(ro+6,y1,0),'厚 '+p.H.toFixed(2));
- addDim(V3(-sd,y1+8.5,0),V3(sd,y1+8.5,0),'屏 Ø'+p.sd.toFixed(2));
- const ps=[
- {id:'bezel',node:bezel,ex:V3(0,0,0)},
- {id:'black',node:black,ex:V3(0,22,0)},
- {id:'glass',node:glass,ex:V3(0,32,0)},
- {id:'pcb',node:pcb,ex:V3(0,8,0)},
- {id:'cell',node:cell,ex:V3(0,-10,0)},
- {id:'cap',node:cap,ex:V3(0,-28,0)},
- {id:'thread',node:th,ex:V3(0,-20,0)},
- {id:'sbtn',node:sb,ex:V3(18,2,0)},
- {id:'usbc',node:usb,ex:V3(-18,-2,0)}
- ];
- bosses.forEach(b=>ps.push({id:'boss',node:b,ex:V3(0,-16,0)}));
- return {root:g,size:V3(p.D,p.H,p.D),parts:ps};
- }
- /* ---------------- 自定义结构件(轻量参数化建模) ---------------- */
- /* 形体库:按工艺预置的标准件参数(M2/M2.5/M3 自攻预钻孔按常用规范) */
- const PRIMS={
- box: {n:'方块', d:{w:8, h:6, dd:8}, tag:'基础'},
- cyl: {n:'圆柱', d:{dia:10,h:8}, tag:'基础'},
- rib: {n:'加强筋', d:{w:14, h:5, dd:1.2}, tag:'基础'},
- pocket:{n:'凹槽(铣削)', d:{w:10, h:2, dd:10}, tag:'基础'},
- hole: {n:'开孔(钻孔)', d:{dia:3, h:1}, tag:'基础'},
- boss2: {n:'螺丝柱 M2', d:{dia:4.0,h:7,dd:1.6},tag:'紧固'},
- boss25:{n:'螺丝柱 M2.5', d:{dia:4.8,h:8,dd:2.1},tag:'紧固'},
- boss3: {n:'螺丝柱 M3', d:{dia:5.6,h:9,dd:2.6},tag:'紧固'},
- thru25:{n:'M2.5 过孔', d:{dia:2.7,h:1,dd:2.7},tag:'紧固'},
- pin3: {n:'定位销 Ø3', d:{dia:3,h:4}, tag:'紧固'},
- pad4: {n:'四角柱组 M2.5',d:{w:30,h:7,dd:30,dia:4.8,hd:2.1},tag:'腔体'},
- wall: {n:'分隔墙', d:{w:20,h:6,dd:0.8}, tag:'腔体'},
- tray: {n:'电池仓', d:{w:22,h:3,dd:18}, tag:'腔体'},
- clip: {n:'卡扣', d:{w:5,h:4,dd:1.2}, tag:'腔体'}
- };
- const FASTEN_TYPES=['boss2','boss25','boss3','thru25','pin3','pad4'];
- function cavInfo(){
- const id=cur.project,p=cur.params;
- if(id==='silicone') return {kind:'rect',w:p.w,d:p.d,h:p.h};
- if(id==='recorder') return {kind:'cyl',r:(p.D-2*p.t)/2,h:p.H-1.2-p.dm};
- return {kind:'cyl',r:(p.D-2*p.t)/2,h:p.H-p.cap-p.dep};
- }
- function newSpec(type){
- const base=(PRIMS[type]||PRIMS.box).d;
- const s={uid:custUid++,type:type,x:0,z:0,y:0,draft:1,snap:0.5,note:''};
- Object.keys(base).forEach(k=>s[k]=base[k]);
- return s;
- }
- /* 空心柱(螺丝柱 / 过孔):径向回转,内外壁 + 上下环面 */
- function hollowBoss(name,od,pid,h,tess){
- const ri=Math.max(0.25,pid/2), ro=Math.max(ri+0.4,od/2), hh=Math.max(0.2,h/2);
- return revolve(name,[{r:ri,y:-hh},{r:ro,y:-hh},{r:ro,y:hh},{r:ri,y:hh}],tess||20,null);
- }
- function mergeAll(ms,name){
- if(!ms.length) return null;
- const mm=B.Mesh.MergeMeshes(ms,true,true);
- if(mm) mm.name=name;
- return mm||ms[0];
- }
- function buildPrim(s){
- const t=s.type;
- let m=null;
- const rect=(t==='box'||t==='pocket'||t==='rib'||t==='wall'||t==='clip');
- if(rect){
- m=B.MeshBuilder.CreateBox('c'+s.uid,{width:Math.max(0.2,s.w),height:Math.max(0.2,s.h),depth:Math.max(0.2,s.dd)},scene);
- if(t==='rib'||t==='wall'){
- const dr=Math.min(0.35,Math.tan(Math.max(0,s.draft||0)*Math.PI/180)*s.h/Math.max(1,s.dd)*1.6);
- const pos=m.getVerticesData(B.VertexBuffer.PositionKind);
- if(pos){ for(let i=0;i<pos.length;i+=3){ if(pos[i+1]>0){ pos[i]*=1-dr; pos[i+2]*=1-dr; } } }
- m.updateVerticesData(B.VertexBuffer.PositionKind,pos);
- }
- }else if(t==='tray'){
- const w=Math.max(4,s.w), dp=Math.max(4,s.dd), h=Math.max(1,s.h);
- const tw=Math.min(1.4,Math.max(0.6,Math.min(w,dp)/12));
- const ps=[];
- const base=B.MeshBuilder.CreateBox('trb',{width:w,height:tw,depth:dp},scene);
- base.position.y=-h/2+tw/2; ps.push(base);
- [-1,1].forEach(sg=>{
- const xw=B.MeshBuilder.CreateBox('trx',{width:tw,height:h,depth:dp},scene);
- xw.position.x=sg*(w/2-tw/2); ps.push(xw);
- const zw=B.MeshBuilder.CreateBox('trz',{width:w,height:h,depth:tw},scene);
- zw.position.z=sg*(dp/2-tw/2); ps.push(zw);
- });
- m=mergeAll(ps,'c'+s.uid);
- }else if(t==='pad4'){
- const w=Math.max(8,s.w), dp=Math.max(8,s.dd), od=Math.max(2,s.dia||4.8);
- const pid=Math.max(0.8,s.hd||2.1), h=Math.max(2,s.h);
- const ps=[];
- [-1,1].forEach(sx=>[-1,1].forEach(sz=>{
- const b=hollowBoss('pb',od,pid,h,16);
- b.position.x=sx*Math.max(0,w/2-od/2); b.position.z=sz*Math.max(0,dp/2-od/2);
- ps.push(b);
- }));
- m=mergeAll(ps,'c'+s.uid);
- }else if(t==='boss2'||t==='boss25'||t==='boss3'||t==='thru25'){
- m=hollowBoss('c'+s.uid,Math.max(1.2,s.dia),Math.max(0.4,s.dd),Math.max(0.4,s.h),20);
- }else if(t==='pin3'){
- m=B.MeshBuilder.CreateCylinder('c'+s.uid,{diameter:Math.max(0.6,s.dia),height:Math.max(0.4,s.h),tessellation:20},scene);
- }else{
- m=B.MeshBuilder.CreateCylinder('c'+s.uid,{diameter:Math.max(0.4,s.dia),height:Math.max(0.2,s.h),tessellation:24},scene);
- }
- m.position=V3(s.x||0,s.y||0,s.z||0);
- if(s.rot) m.rotation.y=s.rot*Math.PI/180;
- const role=FASTEN_TYPES.indexOf(t)>=0?'brass':((t==='pocket'||t==='hole')?'cut':'body');
- m.metadata={role:role,part:'c'+s.uid,custom:true,owner:s.owner||null};
- const db=new B.PointerDragBehavior({dragPlaneNormal:V3(0,1,0)});
- db.useObjectOrientationForDragging=false;
- db.onDragStartObservable.add(()=>{ if(camera) camera.detachControl(); });
- db.onDragEndObservable.add(()=>{ if(camera&&canvas) camera.attachControl(canvas,true); });
- db.onDragObservable.add(()=>{
- const st=Math.max(0.1,s.snap||0.5);
- m.position.x=Math.round(m.position.x/st)*st;
- m.position.z=Math.round(m.position.z/st)*st;
- const cav=cavInfo();
- const cw=s.w!==undefined?s.w:s.dia, cd=s.dd!==undefined?s.dd:s.dia;
- if(cav.kind==='cyl'){
- const r=Math.hypot(m.position.x,m.position.z);
- const rr=cav.r-Math.max(cw,cd)/2-0.5;
- if(r>0.2&&rr>0&&Math.abs(r-rr)<1.5){
- m.position.x=Math.round((m.position.x/r*rr)*10)/10;
- m.position.z=Math.round((m.position.z/r*rr)*10)/10;
- }
- }else{
- const xz=cav.d/2-cd/2-0.5, xx=cav.w/2-cw/2-0.5;
- if(Math.abs(Math.abs(m.position.z)-xz)<1.5) m.position.z=(m.position.z<0?-1:1)*xz;
- if(Math.abs(Math.abs(m.position.x)-xx)<1.5) m.position.x=(m.position.x<0?-1:1)*xx;
- }
- s.x=+m.position.x.toFixed(2); s.z=+m.position.z.toFixed(2);
- if(dragCb) dragCb(s);
- });
- m.addBehavior(db);
- return m;
- }
- function buildCustom(parent){
- labels.length=labels.length; // 保持已有标注
- const list=customMap[cur.project]||[];
- list.forEach(s=>{
- const m=buildPrim(s);
- m.parent=parent;
- parts.push({id:'c'+s.uid,node:m,ex:V3(0,0,0),custom:true,spec:s});
- });
- }
- const OUTER={silicone:['body'],recorder:['body','lid'],round:['bezel','cap']};
- /* ---------------- 材质应用 ---------------- */
- function applyMaterial(key){
- if(!root) return;
- const cfg=MATERIALS[key]||MATERIALS[PROJECTS[cur.project].materials[0]];
- if(!cfg) return;
- const useKey=MATERIALS[key]?key:PROJECTS[cur.project].materials[0];
- const bodyM=pbr(useKey,MATERIALS[useKey]);
- const accentKey=useKey.indexOf('sil-')===0?'sil-black':useKey;
- const accentM=pbr(accentKey,MATERIALS[accentKey]);
- const outer=OUTER[cur.project]||[];
- root.getChildMeshes().forEach(m=>{
- const role=m.metadata&&m.metadata.role;
- const pid=m.metadata&&m.metadata.part;
- if(role==='body') m.material=(cutaway&&outer.indexOf(pid)>=0)?ghost(useKey):bodyM;
- else if(role==='accent') m.material=accentM;
- else if(role==='glass') m.material=fixed('glass');
- else if(role==='pcb') m.material=fixed('pcb');
- else if(role==='cell') m.material=fixed('cell');
- else if(role==='brass') m.material=fixed('brass');
- else if(role==='dark') m.material=fixed('dark');
- else if(role==='cut') m.material=fixed('cut');
- });
- }
- /* ---------------- 单件隔离编辑 ---------------- */
- function applySolo(id){
- if(!root) return;
- root.getChildMeshes().forEach(m=>{
- const md=m.metadata||{};
- const keep=!id||md.part===id||md.owner===id;
- m.setEnabled(!!keep);
- });
- if(dimRoot) dimRoot.setEnabled(!id&&cur.dims);
- const layer=host&&host.querySelector('.dimlayer');
- if(layer) layer.style.display=(!id&&cur.dims)?'block':'none';
- }
- function frameSolo(id){
- if(!root||!camera) return;
- const ms=root.getChildMeshes().filter(m=>m.metadata&&(m.metadata.part===id||m.metadata.owner===id)&&m.isEnabled());
- if(!ms.length) return;
- const bi=ms[0].getHierarchyBoundingVectors();
- const c=bi.max.add(bi.min).scale(0.5);
- const dim=Math.max(bi.max.x-bi.min.x,bi.max.y-bi.min.y,bi.max.z-bi.min.z);
- camera.target=c;
- camera.alpha=-0.95; camera.beta=1.16;
- camera.radius=Math.max(34,dim*2.35);
- camera.lowerRadiusLimit=Math.max(10,dim*0.6);
- }
- function focusPart(id){
- if(!root||!camera) return;
- const ms=root.getChildMeshes().filter(m=>m.metadata&&(m.metadata.part===id||m.metadata.owner===id)&&m.isEnabled());
- if(!ms.length) return;
- const bi=ms[0].getHierarchyBoundingVectors();
- const c=bi.max.add(bi.min).scale(0.5);
- const dim=Math.max(bi.max.x-bi.min.x,bi.max.y-bi.min.y,bi.max.z-bi.min.z);
- camera.target=c;
- camera.radius=Math.max(22,dim*2.1);
- }
- function setSolo(id){
- solo=id||null;
- if(!root) return;
- cutaway=false;
- applyMaterial(cur.material);
- applySolo(solo);
- if(solo) frameSolo(solo); else frame();
- if(cur.hl&&solo&&cur.hl!==solo) highlight(solo);
- }
- /* ---------------- 组装/重建 ---------------- */
- function rebuild(reframe){
- if(!scene) return;
- if(root){ root.dispose(); root=null; }
- if(dimRoot){ dimRoot.dispose(); dimRoot=null; }
- labels=[]; labelEls.forEach(e=>e.remove()); labelEls=[];
- const proj=PROJECTS[cur.project];
- const p={};
- proj.params.forEach(x=>{ p[x.k]=x.def; });
- Object.assign(p,cur.params||{});
- const out=(cur.project==='silicone')?buildSilicone(p):(cur.project==='recorder')?buildRecorder(p):buildRound(p);
- root=out.root; parts=out.parts;
- buildCustom(root);
- parts.forEach(pt=>{
- if(!pt.node) return;
- pt.basePos=pt.node.position.clone();
- pt.node.metadata=Object.assign({},pt.node.metadata||{},{part:pt.id});
- });
- applyMaterial(cur.material);
- applyExplode(cur.explode);
- if(solo) applySolo(solo);
- placeGround();
- if(reframe!==false) frame();
- refreshDims();
- if(cur.hl) highlight(cur.hl);
- }
- function placeGround(){
- if(!root||!ground) return;
- const bi=root.getHierarchyBoundingVectors();
- const dim=Math.max(bi.max.x-bi.min.x,bi.max.y-bi.min.y,bi.max.z-bi.min.z);
- ground.position.y=bi.min.y-0.2;
- ground.scaling.x=ground.scaling.z=Math.max(1,dim/60);
- }
- function frame(){
- if(!root||!camera) return;
- const bi=root.getHierarchyBoundingVectors();
- const c=bi.max.add(bi.min).scale(0.5);
- const dim=Math.max(bi.max.x-bi.min.x,bi.max.y-bi.min.y,bi.max.z-bi.min.z);
- camera.target=c;
- const aspect=(engine?engine.getRenderWidth():1)/Math.max(1,(engine?engine.getRenderHeight():1));
- const pad=Math.max(1,1.18/Math.max(0.6,aspect));
- camera.radius=Math.max(95,dim*1.98*pad);
- camera.lowerRadiusLimit=Math.max(22,dim*0.85);
- camera.upperRadiusLimit=Math.max(400,dim*7);
- }
- function applyExplode(v){
- cur.explode=v||0;
- parts.forEach(pt=>{
- if(!pt.node||!pt.basePos) return;
- pt.node.position=pt.basePos.add(pt.ex.scale(cur.explode));
- });
- const wantCut=!solo&&((cur.explode>0.2)||!!cur.cutForce);
- if(wantCut!==cutaway){
- cutaway=wantCut;
- applyMaterial(cur.material);
- }
- }
- function highlight(partId){
- cur.hl=partId;
- if(!root) return;
- root.getChildMeshes().forEach(m=>{
- m.renderOutline=false;
- if(partId&&m.metadata&&m.metadata.part===partId){
- m.renderOutline=true;
- m.outlineColor=new B.Color3(0.25,0.75,1);
- m.outlineWidth=0.9;
- }
- });
- }
- function setView(name){
- if(!camera) return;
- const map={iso:[-1.05,1.03],front:[-Math.PI/2,1.53],side:[0,1.53],top:[-Math.PI/2,0.17],low:[-0.55,1.38]};
- const v=map[name]||map.iso;
- let t=0; const fromA=camera.alpha,fromB=camera.beta,dur=0.42;
- const obs=scene.onBeforeRenderObservable.add(()=>{
- t+=engine.getDeltaTime()/1000;
- const k=Math.min(1,t/dur), e=1-Math.pow(1-k,3);
- camera.alpha=fromA+(v[0]-fromA)*e;
- camera.beta=fromB+(v[1]-fromB)*e;
- if(k>=1) scene.onBeforeRenderObservable.remove(obs);
- });
- }
- function refreshDims(){
- const layer=ensureLabelHost();
- if(!layer) return;
- layer.innerHTML=''; labelEls=[];
- labels.forEach(l=>{
- const d=document.createElement('div');
- d.className='dimtag'; d.textContent=l.t;
- layer.appendChild(d); labelEls.push(d);
- });
- layer.style.display=(cur.dims&&!solo)?'block':'none';
- if(dimRoot) dimRoot.setEnabled(cur.dims&&!solo);
- }
- function setDims(on){
- cur.dims=!!on;
- const layer=host&&host.querySelector('.dimlayer');
- if(layer) layer.style.display=cur.dims?'block':'none';
- if(dimRoot) dimRoot.setEnabled(cur.dims);
- }
- let lastW=0,lastH=0;
- function updateLabels(){
- if(!camera||!labelEls.length) return;
- const rw=engine.getRenderWidth(), rh=engine.getRenderHeight();
- if(rw!==lastW||rh!==lastH){ lastW=rw; lastH=rh; }
- const vp=camera.viewport.toGlobal(rw,rh);
- const tm=scene.getTransformMatrix();
- const cssW=host.clientWidth, cssH=host.clientHeight;
- for(let i=0;i<labels.length;i++){
- const el=labelEls[i]; if(!el) continue;
- const pr=B.Vector3.Project(labels[i].p,B.Matrix.Identity(),tm,vp);
- if(pr.z<0||pr.z>1){ el.style.opacity='0'; continue; }
- el.style.opacity='1';
- const x=Math.min(Math.max((pr.x/rw)*cssW,34),cssW-34);
- const y=Math.min(Math.max((pr.y/rh)*cssH,16),cssH-16);
- el.style.left=x.toFixed(1)+'px';
- el.style.top=y.toFixed(1)+'px';
- }
- }
- function load(projectId,params,material,explode){
- if(!readyFlag){ pending={project:projectId,params:params,material:material,explode:explode}; return; }
- cur.project=projectId;
- cur.params=Object.assign({},params||{});
- cur.material=material||PROJECTS[projectId].materials[0];
- cur.explode=explode||0;
- cur.hl=null;
- rebuild();
- }
- /* ---------------- 导出 ---------------- */
- function collectMeshes(partId){
- if(!root) return [];
- const out=[];
- root.getChildMeshes().forEach(m=>{
- if(partId){
- const md=m.metadata||{};
- if(md.part!==partId&&md.owner!==partId) return;
- }
- if(!m.getTotalVertices()) return;
- const role=m.metadata&&m.metadata.role;
- const isCustom=!!(m.metadata&&m.metadata.custom);
- if(role==='cut') return;
- if(!isCustom&&(role==='dark'||role==='glass'||role==='brass'||role==='pcb'||role==='cell')) return;
- out.push(m);
- });
- return out;
- }
- function exportMesh(kind,name,partId){
- const meshes=collectMeshes(partId);
- if(!meshes.length) return null;
- if(kind==='stl'){
- const lines=['solid '+name];
- meshes.forEach(m=>{
- const pos=m.getVerticesData(B.VertexBuffer.PositionKind);
- const idx=m.getIndices();
- m.computeWorldMatrix(true);
- const wm=m.getWorldMatrix();
- for(let i=0;i<idx.length;i+=3){
- const a=B.Vector3.TransformCoordinates(V3(pos[idx[i]*3],pos[idx[i]*3+1],pos[idx[i]*3+2]),wm);
- const b=B.Vector3.TransformCoordinates(V3(pos[idx[i+1]*3],pos[idx[i+1]*3+1],pos[idx[i+1]*3+2]),wm);
- const c=B.Vector3.TransformCoordinates(V3(pos[idx[i+2]*3],pos[idx[i+2]*3+1],pos[idx[i+2]*3+2]),wm);
- const n=B.Vector3.Cross(b.subtract(a),c.subtract(a));
- if(n.length()<1e-8) continue;
- n.normalize();
- lines.push('facet normal '+n.x.toFixed(5)+' '+n.y.toFixed(5)+' '+n.z.toFixed(5),' outer loop');
- [a,b,c].forEach(v=>lines.push(' vertex '+v.x.toFixed(4)+' '+v.y.toFixed(4)+' '+v.z.toFixed(4)));
- lines.push(' endloop','endfacet');
- }
- });
- lines.push('endsolid '+name);
- return {text:lines.join('\n'),ext:'stl'};
- }
- const out=['# Pocket Shell Studio · unit mm · '+name];
- let voff=0;
- meshes.forEach((m,mi)=>{
- const pos=m.getVerticesData(B.VertexBuffer.PositionKind);
- const nrm=m.getVerticesData(B.VertexBuffer.NormalKind);
- const idx=m.getIndices();
- m.computeWorldMatrix(true);
- const wm=m.getWorldMatrix();
- out.push('o '+name+'_'+((m.metadata&&m.metadata.part)||mi));
- for(let i=0;i<pos.length;i+=3){
- const v=B.Vector3.TransformCoordinates(V3(pos[i],pos[i+1],pos[i+2]),wm);
- out.push('v '+v.x.toFixed(4)+' '+v.y.toFixed(4)+' '+v.z.toFixed(4));
- }
- for(let i=0;i<nrm.length;i+=3) out.push('vn '+nrm[i].toFixed(4)+' '+nrm[i+1].toFixed(4)+' '+nrm[i+2].toFixed(4));
- for(let i=0;i<idx.length;i+=3){
- const a=idx[i]+1+voff,b=idx[i+1]+1+voff,c=idx[i+2]+1+voff;
- out.push('f '+a+'//'+a+' '+b+'//'+b+' '+c+'//'+c);
- }
- voff+=pos.length/3;
- });
- return {text:out.join('\n'),ext:'obj'};
- }
- return {
- init:init,
- load:load,
- setParams:function(p){ cur.params=Object.assign({},p); rebuild(false); },
- setMaterial:function(k){ cur.material=k; applyMaterial(k); },
- setExplode:function(v){ applyExplode(v); },
- setSolo:function(id){ setSolo(id); },
- isSolo:function(){ return solo; },
- setCutaway:function(on){ cur.cutForce=!!on; cutaway=!!on||cur.explode>0.2; applyMaterial(cur.material); },
- isCutaway:function(){ return cutaway; },
- setDims:setDims,
- setView:setView,
- frame:function(){ frame(); },
- focusPart:focusPart,
- highlight:highlight,
- /* ---- 自定义结构件 ---- */
- PRIMS:PRIMS,
- setCustom:function(projectId,list){
- customMap[projectId]=(list||[]).map(s=>Object.assign({},s));
- if(cur.project===projectId) rebuild(false);
- },
- customList:function(){ return (customMap[cur.project]||[]).map(s=>Object.assign({},s)); },
- addCustom:function(type,patch){
- const s=Object.assign(newSpec(type),patch||{});
- (customMap[cur.project]=customMap[cur.project]||[]).push(s);
- rebuild(false);
- highlight('c'+s.uid);
- return Object.assign({},s);
- },
- updateCustom:function(uid,patch){
- const l=customMap[cur.project]||[];
- const s=l.find(x=>x.uid===uid);
- if(!s) return null;
- Object.assign(s,patch||{});
- rebuild(false);
- highlight('c'+uid);
- return Object.assign({},s);
- },
- removeCustom:function(uid){
- const l=customMap[cur.project]||[];
- const i=l.findIndex(x=>x.uid===uid);
- if(i>=0) l.splice(i,1);
- rebuild(false);
- },
- clearCustom:function(){ customMap[cur.project]=[]; rebuild(false); },
- onSelect:function(cb){ selCb=cb; },
- onDrag:function(cb){ dragCb=cb; },
- snapshot:function(){ if(!engine) return null; scene.render(); return canvas.toDataURL('image/png'); },
- exportSTL:function(n){ return exportMesh('stl',n); },
- exportOBJ:function(n){ return exportMesh('obj',n); },
- exportSTLPart:function(n,pid){ return exportMesh('stl',n,pid); },
- exportOBJPart:function(n,pid){ return exportMesh('obj',n,pid); },
- partIds:function(){ return parts.map(p=>({id:p.id,custom:!!p.custom})); },
- parts:function(){ return parts; },
- isReady:function(){ return readyFlag; }
- };
- })();
|