04_geo.js 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981
  1. /* =========================================================
  2. 几何引擎:参数化壳体 + 材质 + 爆炸图 + 标注 + 导出
  3. 1 单位 = 1 mm
  4. ========================================================= */
  5. const STAGE = (function(){
  6. const B = BABYLON;
  7. const V3 = function(x,y,z){ return new B.Vector3(x,y,z); };
  8. let engine=null, scene=null, camera=null, ground=null, root=null, dimRoot=null, shadowMat=null;
  9. let host=null, canvas=null, readyFlag=false, pending=null;
  10. let labels=[], labelEls=[];
  11. const matCache={}, fixedCache={};
  12. let cur={ project:'silicone', params:{}, material:'', explode:0, dims:true, cutForce:false };
  13. let parts=[];
  14. let customMap={}, cutaway=false, selCb=null, dragCb=null, custUid=1, solo=null;
  15. /* ---------------- 材质 ---------------- */
  16. function pbr(key,cfg){
  17. if(matCache[key]) return matCache[key];
  18. const m=new B.PBRMaterial('mat-'+key,scene);
  19. m.albedoColor=B.Color3.FromHexString(cfg.albedo);
  20. m.metallic=cfg.metallic!==undefined?cfg.metallic:0;
  21. m.roughness=cfg.rough!==undefined?cfg.rough:0.5;
  22. if(cfg.cc!==undefined){
  23. m.clearCoat.isEnabled=true;
  24. m.clearCoat.intensity=cfg.cc;
  25. m.clearCoat.roughness=Math.max(0.03,1-(cfg.cci||0.35));
  26. }
  27. if(cfg.alpha!==undefined){
  28. m.alpha=cfg.alpha;
  29. m.transparencyMode=B.Material.MATERIAL_ALPHABLEND;
  30. }
  31. if(cfg.env!==undefined) m.environmentIntensity=cfg.env;
  32. m.backFaceCulling=false;
  33. matCache[key]=m;
  34. return m;
  35. }
  36. function fixed(key){
  37. if(fixedCache[key]) return fixedCache[key];
  38. fixedCache[key]=pbr('fx-'+key, FIXED_MATS[key]);
  39. return fixedCache[key];
  40. }
  41. /* 半透明「透视」材质:爆炸/剖视时让内部结构可见 */
  42. function ghost(key){
  43. const gk='gh-'+key;
  44. if(matCache[gk]) return matCache[gk];
  45. const src=MATERIALS[key]||MATERIALS[PROJECTS[cur.project].materials[0]];
  46. const cfg=Object.assign({},src,{alpha:0.30,env:0.2,cc:0.05});
  47. return pbr(gk,cfg);
  48. }
  49. /* ---------------- 2D 轮廓 ---------------- */
  50. function roundedPath(w,h,r,seg){
  51. const hw=w/2,hh=h/2;
  52. r=Math.max(0.05,Math.min(r,Math.min(hw,hh)-0.02));
  53. const pts=[];
  54. const corners=[
  55. {cx:hw-r,cz:hh-r,a0:0},
  56. {cx:-(hw-r),cz:hh-r,a0:90},
  57. {cx:-(hw-r),cz:-(hh-r),a0:180},
  58. {cx:hw-r,cz:-(hh-r),a0:270}
  59. ];
  60. for(const c of corners){
  61. for(let i=0;i<seg;i++){
  62. const a=(c.a0+90*i/seg)*Math.PI/180;
  63. pts.push({x:c.cx+r*Math.cos(a),z:c.cz+r*Math.sin(a)});
  64. }
  65. }
  66. return pts;
  67. }
  68. function radialN(p){ const l=Math.hypot(p.x,p.z)||1; return V3(p.x/l,0,p.z/l); }
  69. function assemble(name,chunks,parent){
  70. const pos=[],idx=[],nrm=[];
  71. let base=0;
  72. chunks.forEach(ch=>{
  73. ch.p.forEach(v=>pos.push(v.x,v.y,v.z));
  74. ch.n.forEach(v=>nrm.push(v.x,v.y,v.z));
  75. ch.i.forEach(i=>idx.push(i+base));
  76. base+=ch.p.length;
  77. });
  78. const vd=new B.VertexData();
  79. vd.positions=pos; vd.indices=idx; vd.normals=nrm;
  80. const mesh=new B.Mesh(name,scene);
  81. vd.applyToMesh(mesh);
  82. if(parent) mesh.parent=parent;
  83. return mesh;
  84. }
  85. /* 环带(上下两个同点数轮廓) */
  86. function ringStrip(ringA,yA,ringB,yB,nf){
  87. const N=ringA.length,p=[],n=[],i=[];
  88. for(let k=0;k<N;k++){
  89. const a=ringA[k],b=ringB[k];
  90. p.push(V3(a.x,yA,a.z),V3(b.x,yB,b.z));
  91. n.push(nf(a,true),nf(b,false));
  92. }
  93. for(let k=0;k<N;k++){
  94. const a1=k*2,b1=k*2+1,a2=((k+1)%N)*2,b2=((k+1)%N)*2+1;
  95. i.push(a1,a2,b2,a1,b2,b1);
  96. }
  97. return {p,n,i};
  98. }
  99. /* 空心圆角框(表壳类) */
  100. function hollowFrame(name,spec,parent){
  101. const {ow,od,orr,iw,id,irr,y0,y1,chamfer,seg}=spec;
  102. const A=roundedPath(ow,od,orr,seg);
  103. const Bc=roundedPath(ow,od,orr,seg);
  104. const C=roundedPath(Math.max(1,ow-2*chamfer),Math.max(1,od-2*chamfer),Math.max(0.2,orr-chamfer),seg);
  105. const D=roundedPath(iw,id,irr,seg);
  106. const E=roundedPath(iw,id,irr,seg);
  107. const ch=[];
  108. ch.push(ringStrip(A,y0,Bc,y1-chamfer,p=>radialN(p)));
  109. ch.push(ringStrip(Bc,y1-chamfer,C,y1,p=>{
  110. const r=radialN(p); return V3(r.x*0.707,0.707,r.z*0.707);
  111. }));
  112. ch.push(ringStrip(C,y1,D,y1,()=>V3(0,1,0)));
  113. ch.push(ringStrip(D,y1,E,y0,p=>{
  114. const r=radialN(p); return V3(-r.x,0,-r.z);
  115. }));
  116. ch.push(ringStrip(E,y0,A,y0,()=>V3(0,-1,0)));
  117. return assemble(name,ch,parent);
  118. }
  119. /* 实心圆角板 */
  120. function solidSlab(name,spec,parent){
  121. const {w,d,r,y0,y1,seg}=spec;
  122. const A=roundedPath(w,d,r,seg);
  123. const ch=[];
  124. ch.push(ringStrip(A,y0,roundedPath(w,d,r,seg),y1,p=>radialN(p)));
  125. const tp=[V3(0,y1,0)],tn=[V3(0,1,0)],ti=[];
  126. A.forEach(p=>{ tp.push(V3(p.x,y1,p.z)); tn.push(V3(0,1,0)); });
  127. for(let k=0;k<A.length;k++) ti.push(0,1+k,1+((k+1)%A.length));
  128. ch.push({p:tp,n:tn,i:ti});
  129. const bp=[V3(0,y0,0)],bn=[V3(0,-1,0)],bi=[];
  130. A.forEach(p=>{ bp.push(V3(p.x,y0,p.z)); bn.push(V3(0,-1,0)); });
  131. for(let k=0;k<A.length;k++) bi.push(0,1+((k+1)%A.length),1+k);
  132. ch.push({p:bp,n:bn,i:bi});
  133. return assemble(name,ch,parent);
  134. }
  135. /* 回转体:profile = [{r,y}] 闭合,按 CCW 给出(法线自动朝外) */
  136. function revolve(name,profile,seg,parent){
  137. const ch=[];
  138. for(let k=0;k<profile.length;k++){
  139. const p0=profile[k],p1=profile[(k+1)%profile.length];
  140. const dr=p1.r-p0.r,dy=p1.y-p0.y,len=Math.hypot(dr,dy);
  141. if(len<1e-4) continue;
  142. const n2r=dy/len,n2y=-dr/len;
  143. const pos=[],nrm=[],idx=[];
  144. for(let j=0;j<seg;j++){
  145. const th=j/seg*Math.PI*2, th2=((j+1)%seg)/seg*Math.PI*2;
  146. const c0=Math.cos(th),s0=Math.sin(th),c1=Math.cos(th2),s1=Math.sin(th2);
  147. 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));
  148. 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));
  149. }
  150. for(let j=0;j<seg;j++){
  151. const b=j*4;
  152. idx.push(b,b+1,b+2,b,b+2,b+3);
  153. }
  154. ch.push({p:pos,n:nrm,i:idx});
  155. }
  156. return assemble(name,ch,parent);
  157. }
  158. function arcPts(cx,cy,r,a0,a1,n){
  159. const out=[];
  160. for(let i=0;i<=n;i++){
  161. const a=(a0+(a1-a0)*i/n)*Math.PI/180;
  162. out.push({r:cx+r*Math.cos(a),y:cy+r*Math.sin(a)});
  163. }
  164. return out;
  165. }
  166. function dedupe(pts){
  167. const out=[];
  168. pts.forEach(p=>{
  169. const last=out[out.length-1];
  170. if(!last||Math.abs(last.r-p.r)>1e-4||Math.abs(last.y-p.y)>1e-4) out.push(p);
  171. });
  172. if(out.length>2){
  173. const f=out[0],l=out[out.length-1];
  174. if(Math.abs(f.r-l.r)<1e-4&&Math.abs(f.y-l.y)<1e-4) out.pop();
  175. }
  176. return out;
  177. }
  178. /* ---------------- 场景 ---------------- */
  179. function init(canvasEl,hostEl){
  180. canvas=canvasEl; host=hostEl;
  181. engine=new B.Engine(canvas,true,{preserveDrawingBuffer:true,stencil:true,alpha:true},true);
  182. engine.setHardwareScalingLevel(1/Math.min(2,window.devicePixelRatio||1));
  183. scene=new B.Scene(engine);
  184. scene.clearColor=new B.Color4(0,0,0,0);
  185. scene.ambientColor=new B.Color3(0.16,0.18,0.22);
  186. camera=new B.ArcRotateCamera('cam',-1.05,1.03,150,V3(0,0,0),scene);
  187. camera.lowerRadiusLimit=18; camera.upperRadiusLimit=900;
  188. camera.lowerBetaLimit=0.1; camera.upperBetaLimit=1.54;
  189. camera.wheelDeltaPercentage=0.02;
  190. camera.pinchDeltaPercentage=0.03;
  191. camera.attachControl(canvas,true);
  192. camera.minZ=0.1; camera.fov=0.75; camera.inertia=0.72;
  193. camera.pinchZoom=true;
  194. camera.panningSensibility=160;
  195. camera.angularSensibilityX=760; camera.angularSensibilityY=760;
  196. camera.useNaturalPinchZoom=true;
  197. camera.allowUpsideDown=false;
  198. const hemi=new B.HemisphericLight('hemi',V3(0.1,1,0.2),scene);
  199. hemi.intensity=0.5;
  200. hemi.groundColor=new B.Color3(0.10,0.12,0.16);
  201. const d1=new B.DirectionalLight('d1',V3(-0.5,-1,-0.7),scene);
  202. d1.intensity=1.5; d1.position=V3(140,200,160);
  203. const d2=new B.DirectionalLight('d2',V3(0.8,-0.55,0.7),scene);
  204. d2.intensity=0.85; d2.position=V3(-160,120,-180);
  205. try{
  206. const env=B.CubeTexture.CreateFromPrefilteredData('https://assets.babylonjs.com/environments/environmentSpecular.env',scene);
  207. scene.environmentTexture=env;
  208. scene.environmentIntensity=0.9;
  209. }catch(e){ scene.environmentIntensity=0; }
  210. const dt=new B.DynamicTexture('shadowTex',{width:256,height:256},scene,false);
  211. const ctx=dt.getContext();
  212. const g=ctx.createRadialGradient(128,128,6,128,128,126);
  213. g.addColorStop(0,'rgba(0,0,0,0.55)');
  214. g.addColorStop(0.4,'rgba(0,0,0,0.28)');
  215. g.addColorStop(0.72,'rgba(0,0,0,0.09)');
  216. g.addColorStop(1,'rgba(0,0,0,0)');
  217. ctx.fillStyle=g; ctx.fillRect(0,0,256,256); dt.update();
  218. ground=B.MeshBuilder.CreateGround('ground',{width:300,height:300},scene);
  219. shadowMat=new B.StandardMaterial('shadowMat',scene);
  220. shadowMat.diffuseTexture=dt; shadowMat.opacityTexture=dt;
  221. shadowMat.emissiveColor=new B.Color3(0,0,0);
  222. shadowMat.specularColor=new B.Color3(0,0,0);
  223. shadowMat.disableLighting=true;
  224. shadowMat.backFaceCulling=false;
  225. ground.material=shadowMat; ground.isPickable=false;
  226. engine.runRenderLoop(()=>{
  227. if(scene) scene.render();
  228. updateLabels();
  229. });
  230. new ResizeObserver(()=>engine.resize()).observe(host);
  231. window.addEventListener('resize',()=>engine.resize());
  232. readyFlag=true;
  233. scene.onPointerObservable.add(pi=>{
  234. if(pi.type===B.PointerEventTypes.POINTERDOUBLETAP){
  235. const m2=pi.pickInfo&&pi.pickInfo.pickedMesh;
  236. const md2=m2&&m2.metadata;
  237. if(md2&&md2.part) focusPart(md2.part); else frame();
  238. return;
  239. }
  240. if(pi.type!==B.PointerEventTypes.POINTERPICK) return;
  241. const m=pi.pickInfo&&pi.pickInfo.pickedMesh;
  242. if(!m) return;
  243. const md=m.metadata||{};
  244. if(!md.part){ if(selCb) selCb(null); return; }
  245. highlight(md.part);
  246. if(selCb) selCb(md.part,md.custom?m:null);
  247. });
  248. ensureLabelHost();
  249. if(pending){ const p=pending; pending=null; load(p.project,p.params,p.material,p.explode); }
  250. }
  251. function ensureLabelHost(){
  252. if(!host) return null;
  253. let el=host.querySelector('.dimlayer');
  254. if(!el){ el=document.createElement('div'); el.className='dimlayer'; host.appendChild(el); }
  255. return el;
  256. }
  257. /* ---------------- 标注 ---------------- */
  258. function addDim(a,b,text,color){
  259. if(!dimRoot) dimRoot=new B.TransformNode('dims',scene);
  260. const col=B.Color3.FromHexString(color||'#7ec8ff');
  261. const line=B.MeshBuilder.CreateLines('dl',{points:[a,b]},scene);
  262. line.color=col; line.parent=dimRoot; line.isPickable=false;
  263. const dir=b.subtract(a);
  264. if(dir.length()>0.05){
  265. const d=dir.normalize();
  266. const perp=V3(-d.z,0.4,d.x);
  267. if(perp.length()>0.05){
  268. perp.normalize();
  269. [a,b].forEach(pt=>{
  270. const tick=B.MeshBuilder.CreateLines('tk',{points:[pt.add(perp.scale(2.0)),pt.subtract(perp.scale(2.0))]},scene);
  271. tick.color=col; tick.parent=dimRoot; tick.isPickable=false;
  272. });
  273. }
  274. }
  275. labels.push({p:a.add(b).scale(0.5),t:text});
  276. }
  277. /* ---------------- 建模:三款 ---------------- */
  278. function buildSilicone(p){
  279. const g=new B.TransformNode('root',scene);
  280. const seg=24;
  281. const t=p.t, ow=p.w+2*t, od=p.d+2*t, y0=-p.h/2, y1=p.h/2;
  282. const ir=Math.max(0.5,p.r), orr=ir+t;
  283. const body=hollowFrame('body',{ow,od,orr,iw:p.w,id:p.d,irr:ir,y0,y1,chamfer:0.7,seg},g);
  284. body.metadata={role:'body',part:'body'};
  285. 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);
  286. floor.metadata={role:'body',part:'floor'};
  287. const hx=p.hg/2, hz=-(od/2-3.0);
  288. const hornL=B.MeshBuilder.CreateCylinder('hornL',{diameterBottom:p.hd,diameterTop:p.hd*0.28,height:p.hh,tessellation:18},scene);
  289. hornL.position=V3(-hx,y1+p.hh/2-0.45,hz); hornL.rotation.x=-0.28; hornL.rotation.z=-0.10; hornL.parent=g;
  290. hornL.metadata={role:'accent',part:'hornL'};
  291. const hornR=B.MeshBuilder.CreateCylinder('hornR',{diameterBottom:p.hd,diameterTop:p.hd*0.28,height:p.hh,tessellation:18},scene);
  292. hornR.position=V3(hx,y1+p.hh/2-0.45,hz); hornR.rotation.x=-0.28; hornR.rotation.z=0.10; hornR.parent=g;
  293. hornR.metadata={role:'accent',part:'hornR'};
  294. 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);
  295. screen.metadata={role:'glass',part:'screen'};
  296. const crown=B.MeshBuilder.CreateCylinder('crown',{diameter:3.2,height:2.2,tessellation:16},scene);
  297. crown.rotation.z=Math.PI/2;
  298. crown.position=V3(ow/2+p.cr*0.5,y0+p.h*0.55,0); crown.parent=g;
  299. crown.metadata={role:'body',part:'crown'};
  300. addDim(V3(-ow/2,y0-5.5,od/2+2.5),V3(ow/2,y0-5.5,od/2+2.5),'外宽 '+ow.toFixed(1));
  301. addDim(V3(-(ow/2+4),y0-1,od/2+3),V3(-(ow/2+4),y1,od/2+3),'总高 '+p.h.toFixed(1));
  302. addDim(V3(ow/2+11,y0-5.5,-od/2),V3(ow/2+11,y0-5.5,od/2),'外深 '+od.toFixed(1));
  303. 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));
  304. return {root:g,size:V3(ow,p.h+p.hh*2,od),parts:[
  305. {id:'body',node:body,ex:V3(0,0,0)},
  306. {id:'floor',node:floor,ex:V3(0,-14,0)},
  307. {id:'hornL',node:hornL,ex:V3(-7,16,0)},
  308. {id:'hornR',node:hornR,ex:V3(7,16,0)},
  309. {id:'screen',node:screen,ex:V3(0,20,0)},
  310. {id:'crown',node:crown,ex:V3(16,4,0)}
  311. ]};
  312. }
  313. function buildRecorder(p){
  314. const g=new B.TransformNode('root',scene);
  315. const seg=48;
  316. const ro=p.D/2, ri=ro-p.t, y0=-p.H/2, y1=p.H/2;
  317. const r=Math.min(p.t*0.65,1.8);
  318. const bodyProf=dedupe([
  319. {r:ri,y:y0+r},
  320. ...arcPts(ri+r,y0+r,r,180,270,3),
  321. ...arcPts(ro-r,y0+r,r,270,360,3),
  322. {r:ro,y:y1},
  323. {r:ri,y:y1}
  324. ]);
  325. const body=revolve('body',bodyProf,seg,g);
  326. body.metadata={role:'body',part:'body'};
  327. const base=revolve('base',dedupe([
  328. {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}
  329. ]),seg,g);
  330. base.metadata={role:'body',part:'base'};
  331. // 上盖穹顶
  332. const dome=p.dm, lidPts=[{r:0.5,y:y1},{r:ro-0.2,y:y1}];
  333. const steps=9;
  334. for(let i=0;i<=steps;i++){
  335. const a=i/steps*Math.PI/2;
  336. lidPts.push({r:0.5+(ro-0.7)*Math.cos(a),y:y1+dome*Math.sin(a)});
  337. }
  338. const lid=revolve('lid',dedupe(lidPts),seg,g);
  339. lid.metadata={role:'body',part:'lid'};
  340. const loop=B.MeshBuilder.CreateTorus('loop',{diameter:p.ld+p.t*1.9,thickness:p.t*0.9,tessellation:28},scene);
  341. loop.rotation.x=Math.PI/2;
  342. loop.position=V3(ro+p.lh*0.55,y1-1.6,0); loop.parent=g;
  343. loop.metadata={role:'body',part:'loop'};
  344. const micMeshes=[];
  345. const micR=Math.max(4,ro*0.4);
  346. for(let i=0;i<4;i++){
  347. const a=Math.PI/4+i*Math.PI/2;
  348. const m=B.MeshBuilder.CreateCylinder('mic'+i,{diameter:1.0,height:1.8,tessellation:10},scene);
  349. m.position=V3(Math.cos(a)*micR,y1+dome*0.72+0.2,Math.sin(a)*micR);
  350. m.parent=g; m.material=fixed('dark');
  351. m.metadata={role:'dark',part:'mic'};
  352. micMeshes.push(m);
  353. }
  354. const usb=B.MeshBuilder.CreateBox('usbc',{width:1.4,height:3.2,depth:9.0},scene);
  355. usb.position=V3(ro-0.4,y0+3.0,0); usb.parent=g; usb.material=fixed('dark');
  356. usb.metadata={role:'dark',part:'usbc'};
  357. const btn=B.MeshBuilder.CreateCylinder('btn',{diameter:3.6,height:1.2,tessellation:20},scene);
  358. btn.rotation.z=Math.PI/2; btn.position=V3(-ro+0.1,y1-1.2,0); btn.parent=g;
  359. btn.metadata={role:'body',part:'btn'};
  360. const pcb=B.MeshBuilder.CreateCylinder('pcb',{diameter:Math.min(ro*2-5,26),height:1.2,tessellation:32},scene);
  361. pcb.position=V3(0,y1-3.4,0); pcb.parent=g; pcb.material=fixed('pcb');
  362. pcb.metadata={role:'pcb',part:'pcb'};
  363. const cell=B.MeshBuilder.CreateCylinder('cell',{diameter:Math.min(ro*2-8,20),height:5.4,tessellation:28},scene);
  364. cell.position=V3(0,y0+4.4,0); cell.parent=g; cell.material=fixed('cell');
  365. cell.metadata={role:'cell',part:'cell'};
  366. addDim(V3(-ro,y0-7,0),V3(ro,y0-7,0),'Ø'+p.D.toFixed(1));
  367. addDim(V3(ro+9,y0,0),V3(ro+9,y1,0),'高 '+p.H.toFixed(1));
  368. addDim(V3(0,y1+6,0),V3(ro+p.lh+2,y1+6,0),'挂环 '+p.lh.toFixed(1));
  369. const ps=[
  370. {id:'body',node:body,ex:V3(0,0,0)},
  371. {id:'base',node:base,ex:V3(0,-16,0)},
  372. {id:'cell',node:cell,ex:V3(0,2,0)},
  373. {id:'pcb',node:pcb,ex:V3(0,14,0)},
  374. {id:'lid',node:lid,ex:V3(0,26,0)},
  375. {id:'loop',node:loop,ex:V3(18,2,0)},
  376. {id:'btn',node:btn,ex:V3(-18,2,0)},
  377. {id:'usbc',node:usb,ex:V3(16,-2,0)}
  378. ];
  379. micMeshes.forEach(m=>ps.push({id:'mic',node:m,ex:V3(0,30,0)}));
  380. return {root:g,size:V3(p.D+10,p.H+p.dm, p.D),parts:ps};
  381. }
  382. function buildRound(p){
  383. const g=new B.TransformNode('root',scene);
  384. const seg=64;
  385. const ro=p.D/2, y0=-p.H/2, y1=p.H/2, bd=p.bd/2, sd=p.sd/2, dep=p.dep;
  386. const re=Math.min(3.0,p.t*1.3);
  387. /* CNC 弧面:外壁 → 顶部凸圆 R → 极短平台 → 屏边凹圆 R → 沉台
  388. 全部由工艺参数驱动,工厂按 rimR / dep / cham 直接编程 */
  389. const rimR=Math.max(0.4,Math.min(p.rimR||1.8, (ro-bd)*0.55));
  390. const cham=Math.max(0,Math.min(p.cham||0.5, (ro-bd)*0.35));
  391. const seam=Math.max(0.5,Math.min(p.dep||1.2, ro-rimR-bd+0.02));
  392. const flat=Math.max(0,ro-rimR-(bd+seam));
  393. const bezelProf=dedupe([
  394. {r:sd,y:y0},
  395. {r:Math.max(sd,ro-cham),y:y0},
  396. ...(cham>0.05?arcPts(ro-cham,y0+cham,cham,270,360,3):[{r:ro,y:y0}]),
  397. {r:ro,y:y1-rimR},
  398. ...arcPts(ro-rimR,y1-rimR,rimR,0,90,6),
  399. ...(flat>0.15?[{r:bd+seam,y:y1}]:[]),
  400. ...arcPts(bd+seam,y1-seam,seam,90,180,6),
  401. {r:sd,y:y1-seam}
  402. ]);
  403. const bezel=revolve('bezel',bezelProf,seg,g);
  404. bezel.metadata={role:'body',part:'bezel'};
  405. const seatY=y1-seam;
  406. const black=B.MeshBuilder.CreateCylinder('black',{diameter:p.bd-0.3,height:0.6,tessellation:seg},scene);
  407. black.position=V3(0,seatY+0.3,0); black.parent=g; black.material=fixed('dark');
  408. black.metadata={role:'dark',part:'black'};
  409. const glass=B.MeshBuilder.CreateCylinder('glass',{diameter:p.sd+0.4,height:0.8,tessellation:seg},scene);
  410. glass.position=V3(0,seatY+0.4,0); glass.parent=g; glass.material=fixed('glass');
  411. glass.metadata={role:'glass',part:'glass'};
  412. const capProf=dedupe([
  413. {r:0.6,y:y0},
  414. {r:ro-p.t-0.6,y:y0},
  415. {r:ro-p.t-0.6,y:y0+p.cap-0.5},
  416. ...arcPts(ro-p.t-1.1,y0+p.cap-0.5,0.5,0,90,2),
  417. {r:0.6,y:y0+p.cap}
  418. ]);
  419. const cap=revolve('cap',capProf,seg,g);
  420. cap.metadata={role:'body',part:'cap'};
  421. const th=B.MeshBuilder.CreateTorus('thread',{diameter:p.D-p.t*2-1.6,thickness:0.9,tessellation:seg},scene);
  422. th.position=V3(0,y0+p.cap+0.05,0); th.parent=g; th.material=fixed('dark');
  423. th.metadata={role:'dark',part:'thread'};
  424. const bosses=[];
  425. for(let i=0;i<4;i++){
  426. const a=Math.PI/4+i*Math.PI/2;
  427. const b=B.MeshBuilder.CreateCylinder('boss'+i,{diameter:4.2,height:5.2,tessellation:14},scene);
  428. b.position=V3(Math.cos(a)*(ro-9),y0+p.cap+2.8,Math.sin(a)*(ro-9));
  429. b.parent=g; b.material=fixed('brass');
  430. b.metadata={role:'brass',part:'boss'};
  431. bosses.push(b);
  432. }
  433. const pcb=B.MeshBuilder.CreateCylinder('pcb',{diameter:Math.min(44,p.D-14),height:1.2,tessellation:40},scene);
  434. pcb.position=V3(0,y1-dep-3.4,0); pcb.parent=g; pcb.material=fixed('pcbDark');
  435. pcb.metadata={role:'pcb',part:'pcb'};
  436. const cell=B.MeshBuilder.CreateCylinder('cell',{diameter:Math.min(36,p.D-22),height:5.0,tessellation:36},scene);
  437. cell.position=V3(0,y0+p.cap+4.6,0); cell.parent=g; cell.material=fixed('cell');
  438. cell.metadata={role:'cell',part:'cell'};
  439. const sb=B.MeshBuilder.CreateBox('sbtn',{width:1.2,height:5.4,depth:2.0},scene);
  440. sb.position=V3(ro-0.1,1.6,-2); sb.parent=g;
  441. sb.metadata={role:'body',part:'sbtn'};
  442. const usb=B.MeshBuilder.CreateBox('usbc',{width:1.5,height:3.2,depth:8.8},scene);
  443. usb.position=V3(-ro+0.4,y0+5.4,0); usb.parent=g; usb.material=fixed('dark');
  444. usb.metadata={role:'dark',part:'usbc'};
  445. addDim(V3(-ro,y0-7,0),V3(ro,y0-7,0),'Ø'+p.D.toFixed(2));
  446. addDim(V3(ro+6,y0,0),V3(ro+6,y1,0),'厚 '+p.H.toFixed(2));
  447. addDim(V3(-sd,y1+8.5,0),V3(sd,y1+8.5,0),'屏 Ø'+p.sd.toFixed(2));
  448. const ps=[
  449. {id:'bezel',node:bezel,ex:V3(0,0,0)},
  450. {id:'black',node:black,ex:V3(0,22,0)},
  451. {id:'glass',node:glass,ex:V3(0,32,0)},
  452. {id:'pcb',node:pcb,ex:V3(0,8,0)},
  453. {id:'cell',node:cell,ex:V3(0,-10,0)},
  454. {id:'cap',node:cap,ex:V3(0,-28,0)},
  455. {id:'thread',node:th,ex:V3(0,-20,0)},
  456. {id:'sbtn',node:sb,ex:V3(18,2,0)},
  457. {id:'usbc',node:usb,ex:V3(-18,-2,0)}
  458. ];
  459. bosses.forEach(b=>ps.push({id:'boss',node:b,ex:V3(0,-16,0)}));
  460. return {root:g,size:V3(p.D,p.H,p.D),parts:ps};
  461. }
  462. /* ---------------- 自定义结构件(轻量参数化建模) ---------------- */
  463. /* 形体库:按工艺预置的标准件参数(M2/M2.5/M3 自攻预钻孔按常用规范) */
  464. const PRIMS={
  465. box: {n:'方块', d:{w:8, h:6, dd:8}, tag:'基础'},
  466. cyl: {n:'圆柱', d:{dia:10,h:8}, tag:'基础'},
  467. rib: {n:'加强筋', d:{w:14, h:5, dd:1.2}, tag:'基础'},
  468. pocket:{n:'凹槽(铣削)', d:{w:10, h:2, dd:10}, tag:'基础'},
  469. hole: {n:'开孔(钻孔)', d:{dia:3, h:1}, tag:'基础'},
  470. boss2: {n:'螺丝柱 M2', d:{dia:4.0,h:7,dd:1.6},tag:'紧固'},
  471. boss25:{n:'螺丝柱 M2.5', d:{dia:4.8,h:8,dd:2.1},tag:'紧固'},
  472. boss3: {n:'螺丝柱 M3', d:{dia:5.6,h:9,dd:2.6},tag:'紧固'},
  473. thru25:{n:'M2.5 过孔', d:{dia:2.7,h:1,dd:2.7},tag:'紧固'},
  474. pin3: {n:'定位销 Ø3', d:{dia:3,h:4}, tag:'紧固'},
  475. pad4: {n:'四角柱组 M2.5',d:{w:30,h:7,dd:30,dia:4.8,hd:2.1},tag:'腔体'},
  476. wall: {n:'分隔墙', d:{w:20,h:6,dd:0.8}, tag:'腔体'},
  477. tray: {n:'电池仓', d:{w:22,h:3,dd:18}, tag:'腔体'},
  478. clip: {n:'卡扣', d:{w:5,h:4,dd:1.2}, tag:'腔体'}
  479. };
  480. const FASTEN_TYPES=['boss2','boss25','boss3','thru25','pin3','pad4'];
  481. function cavInfo(){
  482. const id=cur.project,p=cur.params;
  483. if(id==='silicone') return {kind:'rect',w:p.w,d:p.d,h:p.h};
  484. if(id==='recorder') return {kind:'cyl',r:(p.D-2*p.t)/2,h:p.H-1.2-p.dm};
  485. return {kind:'cyl',r:(p.D-2*p.t)/2,h:p.H-p.cap-p.dep};
  486. }
  487. function newSpec(type){
  488. const base=(PRIMS[type]||PRIMS.box).d;
  489. const s={uid:custUid++,type:type,x:0,z:0,y:0,draft:1,snap:0.5,note:''};
  490. Object.keys(base).forEach(k=>s[k]=base[k]);
  491. return s;
  492. }
  493. /* 空心柱(螺丝柱 / 过孔):径向回转,内外壁 + 上下环面 */
  494. function hollowBoss(name,od,pid,h,tess){
  495. const ri=Math.max(0.25,pid/2), ro=Math.max(ri+0.4,od/2), hh=Math.max(0.2,h/2);
  496. return revolve(name,[{r:ri,y:-hh},{r:ro,y:-hh},{r:ro,y:hh},{r:ri,y:hh}],tess||20,null);
  497. }
  498. function mergeAll(ms,name){
  499. if(!ms.length) return null;
  500. const mm=B.Mesh.MergeMeshes(ms,true,true);
  501. if(mm) mm.name=name;
  502. return mm||ms[0];
  503. }
  504. function buildPrim(s){
  505. const t=s.type;
  506. let m=null;
  507. const rect=(t==='box'||t==='pocket'||t==='rib'||t==='wall'||t==='clip');
  508. if(rect){
  509. 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);
  510. if(t==='rib'||t==='wall'){
  511. 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);
  512. const pos=m.getVerticesData(B.VertexBuffer.PositionKind);
  513. 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; } } }
  514. m.updateVerticesData(B.VertexBuffer.PositionKind,pos);
  515. }
  516. }else if(t==='tray'){
  517. const w=Math.max(4,s.w), dp=Math.max(4,s.dd), h=Math.max(1,s.h);
  518. const tw=Math.min(1.4,Math.max(0.6,Math.min(w,dp)/12));
  519. const ps=[];
  520. const base=B.MeshBuilder.CreateBox('trb',{width:w,height:tw,depth:dp},scene);
  521. base.position.y=-h/2+tw/2; ps.push(base);
  522. [-1,1].forEach(sg=>{
  523. const xw=B.MeshBuilder.CreateBox('trx',{width:tw,height:h,depth:dp},scene);
  524. xw.position.x=sg*(w/2-tw/2); ps.push(xw);
  525. const zw=B.MeshBuilder.CreateBox('trz',{width:w,height:h,depth:tw},scene);
  526. zw.position.z=sg*(dp/2-tw/2); ps.push(zw);
  527. });
  528. m=mergeAll(ps,'c'+s.uid);
  529. }else if(t==='pad4'){
  530. const w=Math.max(8,s.w), dp=Math.max(8,s.dd), od=Math.max(2,s.dia||4.8);
  531. const pid=Math.max(0.8,s.hd||2.1), h=Math.max(2,s.h);
  532. const ps=[];
  533. [-1,1].forEach(sx=>[-1,1].forEach(sz=>{
  534. const b=hollowBoss('pb',od,pid,h,16);
  535. b.position.x=sx*Math.max(0,w/2-od/2); b.position.z=sz*Math.max(0,dp/2-od/2);
  536. ps.push(b);
  537. }));
  538. m=mergeAll(ps,'c'+s.uid);
  539. }else if(t==='boss2'||t==='boss25'||t==='boss3'||t==='thru25'){
  540. m=hollowBoss('c'+s.uid,Math.max(1.2,s.dia),Math.max(0.4,s.dd),Math.max(0.4,s.h),20);
  541. }else if(t==='pin3'){
  542. m=B.MeshBuilder.CreateCylinder('c'+s.uid,{diameter:Math.max(0.6,s.dia),height:Math.max(0.4,s.h),tessellation:20},scene);
  543. }else{
  544. m=B.MeshBuilder.CreateCylinder('c'+s.uid,{diameter:Math.max(0.4,s.dia),height:Math.max(0.2,s.h),tessellation:24},scene);
  545. }
  546. m.position=V3(s.x||0,s.y||0,s.z||0);
  547. if(s.rot) m.rotation.y=s.rot*Math.PI/180;
  548. const role=FASTEN_TYPES.indexOf(t)>=0?'brass':((t==='pocket'||t==='hole')?'cut':'body');
  549. m.metadata={role:role,part:'c'+s.uid,custom:true,owner:s.owner||null};
  550. const db=new B.PointerDragBehavior({dragPlaneNormal:V3(0,1,0)});
  551. db.useObjectOrientationForDragging=false;
  552. db.onDragStartObservable.add(()=>{ if(camera) camera.detachControl(); });
  553. db.onDragEndObservable.add(()=>{ if(camera&&canvas) camera.attachControl(canvas,true); });
  554. db.onDragObservable.add(()=>{
  555. const st=Math.max(0.1,s.snap||0.5);
  556. m.position.x=Math.round(m.position.x/st)*st;
  557. m.position.z=Math.round(m.position.z/st)*st;
  558. const cav=cavInfo();
  559. const cw=s.w!==undefined?s.w:s.dia, cd=s.dd!==undefined?s.dd:s.dia;
  560. if(cav.kind==='cyl'){
  561. const r=Math.hypot(m.position.x,m.position.z);
  562. const rr=cav.r-Math.max(cw,cd)/2-0.5;
  563. if(r>0.2&&rr>0&&Math.abs(r-rr)<1.5){
  564. m.position.x=Math.round((m.position.x/r*rr)*10)/10;
  565. m.position.z=Math.round((m.position.z/r*rr)*10)/10;
  566. }
  567. }else{
  568. const xz=cav.d/2-cd/2-0.5, xx=cav.w/2-cw/2-0.5;
  569. if(Math.abs(Math.abs(m.position.z)-xz)<1.5) m.position.z=(m.position.z<0?-1:1)*xz;
  570. if(Math.abs(Math.abs(m.position.x)-xx)<1.5) m.position.x=(m.position.x<0?-1:1)*xx;
  571. }
  572. s.x=+m.position.x.toFixed(2); s.z=+m.position.z.toFixed(2);
  573. if(dragCb) dragCb(s);
  574. });
  575. m.addBehavior(db);
  576. return m;
  577. }
  578. function buildCustom(parent){
  579. labels.length=labels.length; // 保持已有标注
  580. const list=customMap[cur.project]||[];
  581. list.forEach(s=>{
  582. const m=buildPrim(s);
  583. m.parent=parent;
  584. parts.push({id:'c'+s.uid,node:m,ex:V3(0,0,0),custom:true,spec:s});
  585. });
  586. }
  587. const OUTER={silicone:['body'],recorder:['body','lid'],round:['bezel','cap']};
  588. /* ---------------- 材质应用 ---------------- */
  589. function applyMaterial(key){
  590. if(!root) return;
  591. const cfg=MATERIALS[key]||MATERIALS[PROJECTS[cur.project].materials[0]];
  592. if(!cfg) return;
  593. const useKey=MATERIALS[key]?key:PROJECTS[cur.project].materials[0];
  594. const bodyM=pbr(useKey,MATERIALS[useKey]);
  595. const accentKey=useKey.indexOf('sil-')===0?'sil-black':useKey;
  596. const accentM=pbr(accentKey,MATERIALS[accentKey]);
  597. const outer=OUTER[cur.project]||[];
  598. root.getChildMeshes().forEach(m=>{
  599. const role=m.metadata&&m.metadata.role;
  600. const pid=m.metadata&&m.metadata.part;
  601. if(role==='body') m.material=(cutaway&&outer.indexOf(pid)>=0)?ghost(useKey):bodyM;
  602. else if(role==='accent') m.material=accentM;
  603. else if(role==='glass') m.material=fixed('glass');
  604. else if(role==='pcb') m.material=fixed('pcb');
  605. else if(role==='cell') m.material=fixed('cell');
  606. else if(role==='brass') m.material=fixed('brass');
  607. else if(role==='dark') m.material=fixed('dark');
  608. else if(role==='cut') m.material=fixed('cut');
  609. });
  610. }
  611. /* ---------------- 单件隔离编辑 ---------------- */
  612. function applySolo(id){
  613. if(!root) return;
  614. root.getChildMeshes().forEach(m=>{
  615. const md=m.metadata||{};
  616. const keep=!id||md.part===id||md.owner===id;
  617. m.setEnabled(!!keep);
  618. });
  619. if(dimRoot) dimRoot.setEnabled(!id&&cur.dims);
  620. const layer=host&&host.querySelector('.dimlayer');
  621. if(layer) layer.style.display=(!id&&cur.dims)?'block':'none';
  622. }
  623. function frameSolo(id){
  624. if(!root||!camera) return;
  625. const ms=root.getChildMeshes().filter(m=>m.metadata&&(m.metadata.part===id||m.metadata.owner===id)&&m.isEnabled());
  626. if(!ms.length) return;
  627. const bi=ms[0].getHierarchyBoundingVectors();
  628. const c=bi.max.add(bi.min).scale(0.5);
  629. const dim=Math.max(bi.max.x-bi.min.x,bi.max.y-bi.min.y,bi.max.z-bi.min.z);
  630. camera.target=c;
  631. camera.alpha=-0.95; camera.beta=1.16;
  632. camera.radius=Math.max(34,dim*2.35);
  633. camera.lowerRadiusLimit=Math.max(10,dim*0.6);
  634. }
  635. function focusPart(id){
  636. if(!root||!camera) return;
  637. const ms=root.getChildMeshes().filter(m=>m.metadata&&(m.metadata.part===id||m.metadata.owner===id)&&m.isEnabled());
  638. if(!ms.length) return;
  639. const bi=ms[0].getHierarchyBoundingVectors();
  640. const c=bi.max.add(bi.min).scale(0.5);
  641. const dim=Math.max(bi.max.x-bi.min.x,bi.max.y-bi.min.y,bi.max.z-bi.min.z);
  642. camera.target=c;
  643. camera.radius=Math.max(22,dim*2.1);
  644. }
  645. function setSolo(id){
  646. solo=id||null;
  647. if(!root) return;
  648. cutaway=false;
  649. applyMaterial(cur.material);
  650. applySolo(solo);
  651. if(solo) frameSolo(solo); else frame();
  652. if(cur.hl&&solo&&cur.hl!==solo) highlight(solo);
  653. }
  654. /* ---------------- 组装/重建 ---------------- */
  655. function rebuild(reframe){
  656. if(!scene) return;
  657. if(root){ root.dispose(); root=null; }
  658. if(dimRoot){ dimRoot.dispose(); dimRoot=null; }
  659. labels=[]; labelEls.forEach(e=>e.remove()); labelEls=[];
  660. const proj=PROJECTS[cur.project];
  661. const p={};
  662. proj.params.forEach(x=>{ p[x.k]=x.def; });
  663. Object.assign(p,cur.params||{});
  664. const out=(cur.project==='silicone')?buildSilicone(p):(cur.project==='recorder')?buildRecorder(p):buildRound(p);
  665. root=out.root; parts=out.parts;
  666. buildCustom(root);
  667. parts.forEach(pt=>{
  668. if(!pt.node) return;
  669. pt.basePos=pt.node.position.clone();
  670. pt.node.metadata=Object.assign({},pt.node.metadata||{},{part:pt.id});
  671. });
  672. applyMaterial(cur.material);
  673. applyExplode(cur.explode);
  674. if(solo) applySolo(solo);
  675. placeGround();
  676. if(reframe!==false) frame();
  677. refreshDims();
  678. if(cur.hl) highlight(cur.hl);
  679. }
  680. function placeGround(){
  681. if(!root||!ground) return;
  682. const bi=root.getHierarchyBoundingVectors();
  683. const dim=Math.max(bi.max.x-bi.min.x,bi.max.y-bi.min.y,bi.max.z-bi.min.z);
  684. ground.position.y=bi.min.y-0.2;
  685. ground.scaling.x=ground.scaling.z=Math.max(1,dim/60);
  686. }
  687. function frame(){
  688. if(!root||!camera) return;
  689. const bi=root.getHierarchyBoundingVectors();
  690. const c=bi.max.add(bi.min).scale(0.5);
  691. const dim=Math.max(bi.max.x-bi.min.x,bi.max.y-bi.min.y,bi.max.z-bi.min.z);
  692. camera.target=c;
  693. const aspect=(engine?engine.getRenderWidth():1)/Math.max(1,(engine?engine.getRenderHeight():1));
  694. const pad=Math.max(1,1.18/Math.max(0.6,aspect));
  695. camera.radius=Math.max(95,dim*1.98*pad);
  696. camera.lowerRadiusLimit=Math.max(22,dim*0.85);
  697. camera.upperRadiusLimit=Math.max(400,dim*7);
  698. }
  699. function applyExplode(v){
  700. cur.explode=v||0;
  701. parts.forEach(pt=>{
  702. if(!pt.node||!pt.basePos) return;
  703. pt.node.position=pt.basePos.add(pt.ex.scale(cur.explode));
  704. });
  705. const wantCut=!solo&&((cur.explode>0.2)||!!cur.cutForce);
  706. if(wantCut!==cutaway){
  707. cutaway=wantCut;
  708. applyMaterial(cur.material);
  709. }
  710. }
  711. function highlight(partId){
  712. cur.hl=partId;
  713. if(!root) return;
  714. root.getChildMeshes().forEach(m=>{
  715. m.renderOutline=false;
  716. if(partId&&m.metadata&&m.metadata.part===partId){
  717. m.renderOutline=true;
  718. m.outlineColor=new B.Color3(0.25,0.75,1);
  719. m.outlineWidth=0.9;
  720. }
  721. });
  722. }
  723. function setView(name){
  724. if(!camera) return;
  725. 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]};
  726. const v=map[name]||map.iso;
  727. let t=0; const fromA=camera.alpha,fromB=camera.beta,dur=0.42;
  728. const obs=scene.onBeforeRenderObservable.add(()=>{
  729. t+=engine.getDeltaTime()/1000;
  730. const k=Math.min(1,t/dur), e=1-Math.pow(1-k,3);
  731. camera.alpha=fromA+(v[0]-fromA)*e;
  732. camera.beta=fromB+(v[1]-fromB)*e;
  733. if(k>=1) scene.onBeforeRenderObservable.remove(obs);
  734. });
  735. }
  736. function refreshDims(){
  737. const layer=ensureLabelHost();
  738. if(!layer) return;
  739. layer.innerHTML=''; labelEls=[];
  740. labels.forEach(l=>{
  741. const d=document.createElement('div');
  742. d.className='dimtag'; d.textContent=l.t;
  743. layer.appendChild(d); labelEls.push(d);
  744. });
  745. layer.style.display=(cur.dims&&!solo)?'block':'none';
  746. if(dimRoot) dimRoot.setEnabled(cur.dims&&!solo);
  747. }
  748. function setDims(on){
  749. cur.dims=!!on;
  750. const layer=host&&host.querySelector('.dimlayer');
  751. if(layer) layer.style.display=cur.dims?'block':'none';
  752. if(dimRoot) dimRoot.setEnabled(cur.dims);
  753. }
  754. let lastW=0,lastH=0;
  755. function updateLabels(){
  756. if(!camera||!labelEls.length) return;
  757. const rw=engine.getRenderWidth(), rh=engine.getRenderHeight();
  758. if(rw!==lastW||rh!==lastH){ lastW=rw; lastH=rh; }
  759. const vp=camera.viewport.toGlobal(rw,rh);
  760. const tm=scene.getTransformMatrix();
  761. const cssW=host.clientWidth, cssH=host.clientHeight;
  762. for(let i=0;i<labels.length;i++){
  763. const el=labelEls[i]; if(!el) continue;
  764. const pr=B.Vector3.Project(labels[i].p,B.Matrix.Identity(),tm,vp);
  765. if(pr.z<0||pr.z>1){ el.style.opacity='0'; continue; }
  766. el.style.opacity='1';
  767. const x=Math.min(Math.max((pr.x/rw)*cssW,34),cssW-34);
  768. const y=Math.min(Math.max((pr.y/rh)*cssH,16),cssH-16);
  769. el.style.left=x.toFixed(1)+'px';
  770. el.style.top=y.toFixed(1)+'px';
  771. }
  772. }
  773. function load(projectId,params,material,explode){
  774. if(!readyFlag){ pending={project:projectId,params:params,material:material,explode:explode}; return; }
  775. cur.project=projectId;
  776. cur.params=Object.assign({},params||{});
  777. cur.material=material||PROJECTS[projectId].materials[0];
  778. cur.explode=explode||0;
  779. cur.hl=null;
  780. rebuild();
  781. }
  782. /* ---------------- 导出 ---------------- */
  783. function collectMeshes(partId){
  784. if(!root) return [];
  785. const out=[];
  786. root.getChildMeshes().forEach(m=>{
  787. if(partId){
  788. const md=m.metadata||{};
  789. if(md.part!==partId&&md.owner!==partId) return;
  790. }
  791. if(!m.getTotalVertices()) return;
  792. const role=m.metadata&&m.metadata.role;
  793. const isCustom=!!(m.metadata&&m.metadata.custom);
  794. if(role==='cut') return;
  795. if(!isCustom&&(role==='dark'||role==='glass'||role==='brass'||role==='pcb'||role==='cell')) return;
  796. out.push(m);
  797. });
  798. return out;
  799. }
  800. function exportMesh(kind,name,partId){
  801. const meshes=collectMeshes(partId);
  802. if(!meshes.length) return null;
  803. if(kind==='stl'){
  804. const lines=['solid '+name];
  805. meshes.forEach(m=>{
  806. const pos=m.getVerticesData(B.VertexBuffer.PositionKind);
  807. const idx=m.getIndices();
  808. m.computeWorldMatrix(true);
  809. const wm=m.getWorldMatrix();
  810. for(let i=0;i<idx.length;i+=3){
  811. const a=B.Vector3.TransformCoordinates(V3(pos[idx[i]*3],pos[idx[i]*3+1],pos[idx[i]*3+2]),wm);
  812. const b=B.Vector3.TransformCoordinates(V3(pos[idx[i+1]*3],pos[idx[i+1]*3+1],pos[idx[i+1]*3+2]),wm);
  813. const c=B.Vector3.TransformCoordinates(V3(pos[idx[i+2]*3],pos[idx[i+2]*3+1],pos[idx[i+2]*3+2]),wm);
  814. const n=B.Vector3.Cross(b.subtract(a),c.subtract(a));
  815. if(n.length()<1e-8) continue;
  816. n.normalize();
  817. lines.push('facet normal '+n.x.toFixed(5)+' '+n.y.toFixed(5)+' '+n.z.toFixed(5),' outer loop');
  818. [a,b,c].forEach(v=>lines.push(' vertex '+v.x.toFixed(4)+' '+v.y.toFixed(4)+' '+v.z.toFixed(4)));
  819. lines.push(' endloop','endfacet');
  820. }
  821. });
  822. lines.push('endsolid '+name);
  823. return {text:lines.join('\n'),ext:'stl'};
  824. }
  825. const out=['# Pocket Shell Studio · unit mm · '+name];
  826. let voff=0;
  827. meshes.forEach((m,mi)=>{
  828. const pos=m.getVerticesData(B.VertexBuffer.PositionKind);
  829. const nrm=m.getVerticesData(B.VertexBuffer.NormalKind);
  830. const idx=m.getIndices();
  831. m.computeWorldMatrix(true);
  832. const wm=m.getWorldMatrix();
  833. out.push('o '+name+'_'+((m.metadata&&m.metadata.part)||mi));
  834. for(let i=0;i<pos.length;i+=3){
  835. const v=B.Vector3.TransformCoordinates(V3(pos[i],pos[i+1],pos[i+2]),wm);
  836. out.push('v '+v.x.toFixed(4)+' '+v.y.toFixed(4)+' '+v.z.toFixed(4));
  837. }
  838. 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));
  839. for(let i=0;i<idx.length;i+=3){
  840. const a=idx[i]+1+voff,b=idx[i+1]+1+voff,c=idx[i+2]+1+voff;
  841. out.push('f '+a+'//'+a+' '+b+'//'+b+' '+c+'//'+c);
  842. }
  843. voff+=pos.length/3;
  844. });
  845. return {text:out.join('\n'),ext:'obj'};
  846. }
  847. return {
  848. init:init,
  849. load:load,
  850. setParams:function(p){ cur.params=Object.assign({},p); rebuild(false); },
  851. setMaterial:function(k){ cur.material=k; applyMaterial(k); },
  852. setExplode:function(v){ applyExplode(v); },
  853. setSolo:function(id){ setSolo(id); },
  854. isSolo:function(){ return solo; },
  855. setCutaway:function(on){ cur.cutForce=!!on; cutaway=!!on||cur.explode>0.2; applyMaterial(cur.material); },
  856. isCutaway:function(){ return cutaway; },
  857. setDims:setDims,
  858. setView:setView,
  859. frame:function(){ frame(); },
  860. focusPart:focusPart,
  861. highlight:highlight,
  862. /* ---- 自定义结构件 ---- */
  863. PRIMS:PRIMS,
  864. setCustom:function(projectId,list){
  865. customMap[projectId]=(list||[]).map(s=>Object.assign({},s));
  866. if(cur.project===projectId) rebuild(false);
  867. },
  868. customList:function(){ return (customMap[cur.project]||[]).map(s=>Object.assign({},s)); },
  869. addCustom:function(type,patch){
  870. const s=Object.assign(newSpec(type),patch||{});
  871. (customMap[cur.project]=customMap[cur.project]||[]).push(s);
  872. rebuild(false);
  873. highlight('c'+s.uid);
  874. return Object.assign({},s);
  875. },
  876. updateCustom:function(uid,patch){
  877. const l=customMap[cur.project]||[];
  878. const s=l.find(x=>x.uid===uid);
  879. if(!s) return null;
  880. Object.assign(s,patch||{});
  881. rebuild(false);
  882. highlight('c'+uid);
  883. return Object.assign({},s);
  884. },
  885. removeCustom:function(uid){
  886. const l=customMap[cur.project]||[];
  887. const i=l.findIndex(x=>x.uid===uid);
  888. if(i>=0) l.splice(i,1);
  889. rebuild(false);
  890. },
  891. clearCustom:function(){ customMap[cur.project]=[]; rebuild(false); },
  892. onSelect:function(cb){ selCb=cb; },
  893. onDrag:function(cb){ dragCb=cb; },
  894. snapshot:function(){ if(!engine) return null; scene.render(); return canvas.toDataURL('image/png'); },
  895. exportSTL:function(n){ return exportMesh('stl',n); },
  896. exportOBJ:function(n){ return exportMesh('obj',n); },
  897. exportSTLPart:function(n,pid){ return exportMesh('stl',n,pid); },
  898. exportOBJPart:function(n,pid){ return exportMesh('obj',n,pid); },
  899. partIds:function(){ return parts.map(p=>({id:p.id,custom:!!p.custom})); },
  900. parts:function(){ return parts; },
  901. isReady:function(){ return readyFlag; }
  902. };
  903. })();