@volter/editor 0.5.59 → 0.5.60

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/BUNDLED_NOTICES +6 -6
  2. package/dist/.vite/manifest.json +206 -232
  3. package/dist/assets/{AudioViewer-C5C4xeUl.js → AudioViewer-C9JP7n49.js} +1 -1
  4. package/dist/assets/{EntityModelDocument-DyhU8umO.js → EntityModelDocument-SFgsuX4_.js} +1 -1
  5. package/dist/assets/{EnvironmentAssetDocument-D_VZ2iFj.js → EnvironmentAssetDocument-DEqKuki2.js} +1 -1
  6. package/dist/assets/{GameplaySessionTimeline-kIIuhFBI.js → GameplaySessionTimeline-BtEPIu2F.js} +1 -1
  7. package/dist/assets/{ImageViewer-Crv-yzT_.js → ImageViewer-CyIXlQTG.js} +1 -1
  8. package/dist/assets/{InspectorObjectPreview-CO-GVXfu.js → InspectorObjectPreview-MDmTPFBT.js} +1 -1
  9. package/dist/assets/{JsonAssetDocument-Dtg2QwPN.js → JsonAssetDocument-Zyv_CDpC.js} +1 -1
  10. package/dist/assets/{ModelAssetDocument-BpZ8SZXe.js → ModelAssetDocument-BKdnWaJL.js} +1 -1
  11. package/dist/assets/{NonThreeAuthoringBootstrap-0nm5Hl3v.js → NonThreeAuthoringBootstrap-ab96Xbnn.js} +2 -2
  12. package/dist/assets/{Object3DPreview-dHzSO5Ym.js → Object3DPreview-ChopdNF4.js} +2 -2
  13. package/dist/assets/{OnlineAssetDetail-DAdWXnmZ.js → OnlineAssetDetail-B_l8XkeE.js} +2 -2
  14. package/dist/assets/{SourceAssetViewer-D3m0wF8T.js → SourceAssetViewer-zpxF5DOe.js} +2 -2
  15. package/dist/assets/{StageHost-DD_m8W0k.js → StageHost-B4P-uvV9.js} +4 -4
  16. package/dist/assets/{ToolObject3DPreview-CWdklUZ1.js → ToolObject3DPreview-DGcT5dDK.js} +1 -1
  17. package/dist/assets/{TransientHint-aFFUtbSY.js → TransientHint-9_u15mth.js} +1 -1
  18. package/dist/assets/{VideoViewer-BhH8aSzx.js → VideoViewer-3I_zUWEC.js} +1 -1
  19. package/dist/assets/{asset-editor-persistence-D5wYXQEL.js → asset-editor-persistence-B6Yg7dTC.js} +1 -1
  20. package/dist/assets/{blender-node-editor.document-D-hrVHmR.js → blender-node-editor.document-DGn6U6Kf.js} +1 -1
  21. package/dist/assets/blender-properties-tab-DkE9ensL.js +3 -0
  22. package/dist/assets/blender-runtime-host-JKPuUKtZ.js +4 -0
  23. package/dist/assets/{blender-runtime-skin-AJdtKKnf.js → blender-runtime-skin-BFLh4nHG.js} +1 -1
  24. package/dist/assets/{blender-runtime.document-JlYY0bb7.js → blender-runtime.document-C60VEa1_.js} +3 -3
  25. package/dist/assets/{blender-timeline.document-5UN8V20F.js → blender-timeline.document-D9BOYb0q.js} +1 -1
  26. package/dist/assets/{blender-uv-editor.document-maFJQzgA.js → blender-uv-editor.document-BK2pP2sR.js} +1 -1
  27. package/dist/assets/{blender-version.status-CukRH8K3.js → blender-version.status-ZqfW0upF.js} +1 -1
  28. package/dist/assets/{blender.command-CY6QiXxp.js → blender.command-BLtAEuIZ.js} +1 -1
  29. package/dist/assets/{browserAll-BQIn-DRw.js → browserAll-DTuU4PmC.js} +1 -1
  30. package/dist/assets/{edit-mode-authoring-CWTeROGv.js → edit-mode-authoring-DBEoND0w.js} +1 -1
  31. package/dist/assets/{hosted-asset-materialization-DcthzsYS.js → hosted-asset-materialization-6HtWQ0od.js} +1 -1
  32. package/dist/assets/{index-DmtPt6RQ.js → index-DuB3wHKD.js} +12 -12
  33. package/dist/assets/{models.finder-CrDJ41Cp.js → models.finder-Bs46IncP.js} +1 -1
  34. package/dist/assets/{product-CqAh01LU.js → product-FSoI1WhZ.js} +1 -1
  35. package/dist/assets/properties-bone-constraints.inspector-QML_-0yQ.js +1 -0
  36. package/dist/assets/properties-bone.inspector-DSDyP6-P.js +1 -0
  37. package/dist/assets/properties-collection.inspector-jic5mzgz.js +1 -0
  38. package/dist/assets/properties-constraints.inspector-TLHv00p7.js +1 -0
  39. package/dist/assets/properties-data.inspector-BJBPl88V.js +1 -0
  40. package/dist/assets/properties-material.inspector-xxWuVjrx.js +1 -0
  41. package/dist/assets/properties-modifiers.inspector-CWjdmu_J.js +1 -0
  42. package/dist/assets/properties-object.inspector-D15l44Tq.js +1 -0
  43. package/dist/assets/properties-output.inspector-DVuGGSBb.js +1 -0
  44. package/dist/assets/properties-particles.inspector-B94x32Ez.js +1 -0
  45. package/dist/assets/properties-physics.inspector-9EYMjwFP.js +1 -0
  46. package/dist/assets/properties-render.inspector-8yA_8luD.js +1 -0
  47. package/dist/assets/properties-scene.inspector-WM7qZhJ4.js +1 -0
  48. package/dist/assets/properties-texture.inspector-Cno5lCIz.js +1 -0
  49. package/dist/assets/properties-view-layer.inspector--PX0c9h6.js +1 -0
  50. package/dist/assets/properties-world.inspector-C3EuydM_.js +1 -0
  51. package/dist/assets/{react-story-board-CnCZAhn6.js → react-story-board-d_OfX68Z.js} +1 -1
  52. package/dist/assets/{react-three-rapier.esm-DsJqtzy_.js → react-three-rapier.esm-Ch_Gf2qR.js} +1 -1
  53. package/dist/assets/{spark.module-uQlq--TY.js → spark.module-B_-x7Z29.js} +1 -1
  54. package/dist/assets/{stage-keyboard-DzZMNYAr.js → stage-keyboard-C9wzGFxu.js} +1 -1
  55. package/dist/assets/{stage-overlay-set-D6OOz1L9.js → stage-overlay-set-D7J-N5eX.js} +1 -1
  56. package/dist/assets/{stage-presence-markers-BUaSzKCv.js → stage-presence-markers-DvbNl1W4.js} +1 -1
  57. package/dist/assets/{story-capture-C2ExQiuI.js → story-capture-D0H-H2_b.js} +1 -1
  58. package/dist/assets/{story-pixi-preview-C6n-a2_M.js → story-pixi-preview-Cafk1Xbk.js} +1 -1
  59. package/dist/assets/{story-three-preview-BazrPMDu.js → story-three-preview-ByMTQc8w.js} +2 -2
  60. package/dist/assets/{webworkerAll-FJN9IDir.js → webworkerAll-CS1yjkoi.js} +1 -1
  61. package/dist/assets/{world-documents-B6usBw3s.js → world-documents-CWiw361z.js} +1 -1
  62. package/dist-node/cli.js +7 -7
  63. package/package.json +7 -7
  64. package/dist/assets/blender-outliner-model-FscHWpfW.js +0 -1
  65. package/dist/assets/blender-properties-tab-Czi3_yYZ.js +0 -3
  66. package/dist/assets/blender-runtime-host-C3rVDyG8.js +0 -4
  67. package/dist/assets/properties-bone-constraints.inspector-BPN6BRJV.js +0 -1
  68. package/dist/assets/properties-bone.inspector-C4xD61mX.js +0 -1
  69. package/dist/assets/properties-collection.inspector-BTps8t6G.js +0 -1
  70. package/dist/assets/properties-constraints.inspector-BVvP6esW.js +0 -1
  71. package/dist/assets/properties-data.inspector-CKKO8DVT.js +0 -1
  72. package/dist/assets/properties-material.inspector-BGfT8kHT.js +0 -1
  73. package/dist/assets/properties-modifiers.inspector-DJRANpOY.js +0 -1
  74. package/dist/assets/properties-object.inspector-CgVfWmw2.js +0 -1
  75. package/dist/assets/properties-output.inspector-CBl5xEMZ.js +0 -1
  76. package/dist/assets/properties-particles.inspector-CxVZ09ZY.js +0 -1
  77. package/dist/assets/properties-physics.inspector-DmG3i3vY.js +0 -1
  78. package/dist/assets/properties-render.inspector-TCoPfEn0.js +0 -1
  79. package/dist/assets/properties-scene.inspector-BjsTOBiY.js +0 -1
  80. package/dist/assets/properties-texture.inspector-D1X9iyVV.js +0 -1
  81. package/dist/assets/properties-view-layer.inspector-dXTVxzzk.js +0 -1
  82. package/dist/assets/properties-world.inspector-CRxJK930.js +0 -1
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/spark.module-uQlq--TY.js","assets/three.module-BynznMJN.js","assets/index-DmtPt6RQ.js","assets/index-DaQZGF7d.js","assets/_commonjsHelpers-D6-XlEtG.js","assets/index-D_NuPfjr.js","assets/jsx-runtime-DPjLkJKQ.js","assets/index-CtzuWnCS.js","assets/index-CinJrH5C.js","assets/index-D2LwEE0L.js","assets/client-DNXj_opT.js","assets/index-D2fNXpHa.css","assets/index-C5UECeSr.js","assets/stage-overlay-set-D6OOz1L9.js","assets/TransientHint-aFFUtbSY.js","assets/clip-planes-CnAI6DZn.js","assets/OrbitControls-BHxt84w6.js","assets/LineSegments2-vfeDUBfs.js","assets/viewport-pick-context-DkawXbEi.js","assets/editor-presentation-activity-C7SNSmTd.js","assets/stage-keyboard-DzZMNYAr.js","assets/stage-presence-markers-BUaSzKCv.js"])))=>i.map(i=>d[i]);
2
- import{g as xt,dA as Rt,dB as X,ac as Ie,dC as ue,dD as Kn,dE as Gs,dF as mr,dG as ze,dH as un,dI as to,dJ as eo,dK as io,dL as gl,dM as Sn,dN as so,d0 as ki,a3 as jt,Z as Fi,dO as Ir,dP as yl,dQ as _l,dR as vl,dS as xl,dT as wl,Q as Sl,dU as bl,dV as Ml,dW as ro,dX as no,dY as oo,G as ao,t as Nt,dZ as Cl,d_ as Pl,d$ as lo,cL as ho,cj as Al,_ as Ss,e0 as pn,e1 as bs,e2 as El,bT as Tl,e3 as zl,e4 as pa,e5 as Ol,e6 as co,e7 as Il,e8 as Rl,e9 as kl,bd as Ae,a4 as Ee,ea as pe,bD as Fl,T as Xs,eb as fa,ec as Bl,ed as Nl,bc as Ti,bG as Hl,ee as Ll,by as Dl,ef as Ul,eg as Vl,eh as jl,ei as Gl,aH as Xl,ej as Wl,W as Jl,ek as ma,el as Yl,em as ql,en as Zl,w as uo,eo as Ql,bL as po,ep as $l,eq as Kl,er as th,es as eh,dz as ih,et as sh,eu as rh,ev as nh,ew as oh,dv as ah,K as lh,ex as hh,ey as ch,bS as dh,ez as uh,eA as ph,eB as fh,eC as mh}from"./index-DmtPt6RQ.js";import{a as T}from"./jsx-runtime-DPjLkJKQ.js";import{r as F}from"./index-DaQZGF7d.js";import"./index-CtzuWnCS.js";import{a$ as ga,e as ya,i as Ms,L as Ui,X as gh,b1 as Tt,Z as We,aR as bn,bT as yh,am as _a,d as B,C as _h,V as v,Q as wt,au as Yt,av as Je,aD as Ze,bU as Ot,bJ as mt,aa as Re,aC as Vi,a0 as E,bV as Ve,b7 as Wt,bW as zi,bp as fe,as as va,x as Mn,bo as Cn,ay as de,az as It,an as vh,U as Xt,g as ji,ab as ce,bP as sr,bx as xh,bX as wh,aN as Sh,aB as kt,bc as xa,aH as wa,aG as Cs,bF as Sa,bY as bh,bZ as Mh,ap as ie,bl as Pn,by as Ch,b6 as Ph,b_ as Ah,aX as ba,b4 as Eh,bQ as Th,b5 as zh,aY as gr,b3 as Ma,$ as pi,k as Ca,w as yr,b$ as Oh,c0 as Ih,ae as Rh,c1 as kh,ax as Fh,c2 as Bh,c3 as Nh,b as Dt,c4 as An,a as Jt,c5 as Pa,bK as Hh,c6 as Lh,bf as Dh,aW as Aa,p as Ea,P as fo,M as Rr,c7 as Uh,c8 as Vh,c9 as jh,ca as Gh,cb as Xh,bb as Wh,bd as Jh,aE as Yh,cc as mo,S as qh,W as go,H as Zh,a_ as Qh,Y as $h,K as Kh,v as tc,aZ as ec,br as ic,a1 as yo}from"./three.module-BynznMJN.js";import"./index-D2LwEE0L.js";import{E as _o,a as vo,f as sc}from"./clip-planes-CnAI6DZn.js";import{O as rc}from"./OrbitControls-BHxt84w6.js";import{b as En,L as Tn,a as zn}from"./LineSegments2-vfeDUBfs.js";import{s as xo,g as nc}from"./viewport-pick-context-DkawXbEi.js";import{s as oc,i as kr}from"./editor-presentation-activity-C7SNSmTd.js";const Ta=30;function za(o,t,e){return o<t?t:o>e?e:o}function ac(o,t){const e=o.animations;if(e.length===0)return null;const i=new ga(o);let s=e[0];if(!s)return null;const r=a=>{i.stopAllAction();const l=i.clipAction(a);l.paused=!0,l.play(),s=a};r(s);const n=t.attach({id:o.uuid,label:o.name||s.name||"Clip",range:()=>({start:0,end:s?.duration??0,fps:Ta}),seek:a=>{i.setTime(za(a,0,s?.duration??0))},clips:()=>e.map(a=>({id:a.name,label:a.name})),setClip:a=>{const l=e.find(h=>h.name===a);l&&r(l)}});return()=>{n(),i.stopAllAction(),i.uncacheRoot(o)}}function lc(o,t){const e=xt(o,"_animationRuntime");if(!e)return null;const i=[...e.clips.entries()];let s=i[0]?.[1];if(!s)return null;const r=a=>{e.mixer.stopAllAction();const l=e.mixer.clipAction(a);l.paused=!0,l.play(),s=a};return t.attach({id:o.uuid,label:o.name||s.name||"Animation",range:()=>({start:0,end:s?.duration??0,fps:Ta}),seek:a=>{e.mixer.setTime(za(a,0,s?.duration??0))},clips:()=>i.map(([a,l])=>({id:a,label:l.name||a})),setClip:a=>{const l=e.clips.get(a);l&&r(l)}})}function hc(o,t){const e=new Map,i=()=>{const s=new Set;o.traverse(r=>{if(e.has(r.uuid)){s.add(r.uuid);return}const n=lc(r,t)??ac(r,t);n&&(e.set(r.uuid,n),s.add(r.uuid))});for(const[r,n]of[...e])s.has(r)||(n(),e.delete(r))};return i(),{refresh:i,dispose:()=>{for(const s of e.values())s();e.clear()}}}let fi=0,fn=[];function cc(){fi+=1}function dc(){if(fi=Math.max(0,fi-1),fi===0){const o=fn;fn=[];for(const t of o)t()}}function uc(){return fi>0}function pc(){return fi===0?Promise.resolve():new Promise(o=>{fn.push(o)})}const be=()=>globalThis.performance?.now()??Date.now();function fc(o,t){return o.length===0?0:o[Math.min(o.length-1,Math.floor((o.length-1)*t))]??0}function mc(o=!1){const t=new Set,e=[],i=new Map,s=new Map,r=new Map;let n=[],a=[],l=o,h=!1,d=!1,c=0,p=0,u=0;const f=[];let m=0,y=0,g={gpuMs:null,drawCalls:0,triangles:0,geometries:0,textures:0,renderPasses:null},_={enabled:l,recording:d,fps:0,cpuMs:0,p95Ms:0,p99Ms:0,frames:[],phases:[],systems:[],components:[],render:g};function M(){const w=e.at(-1),C=e.slice();let x;const b=P=>(x??=C.map(A=>A.intervalMs).filter(A=>A>0).sort((A,N)=>A-N),fc(x,P));_={enabled:l,recording:d,fps:w?.intervalMs?1e3/w.intervalMs:0,cpuMs:w?.cpuMs??0,get p95Ms(){return b(.95)},get p99Ms(){return b(.99)},frames:C,phases:w?.phases??[],systems:[...s].map(([P,A])=>({name:P,ms:A})).sort((P,A)=>A.ms-P.ms),components:[...r].map(([P,A])=>({name:P,ms:A})).sort((P,A)=>A.ms-P.ms),render:g};for(const P of t)P()}return{get enabled(){return l},set enabled(w){l!==w&&(l=w,w&&!h&&(u=0),M())},get telemetryEnabled(){return h},set telemetryEnabled(w){if(h===w)return;const C=!l&&!h;h=w,w&&C&&(u=0),M()},get recording(){return d},startRecording(){const w=!l&&!h;l=!0,w&&(u=0),d=!0,e.length=0,M()},stopRecording(){d=!1,M()},clear(){e.length=0,M()},beginFrame(){!l&&!h||(i.clear(),s.clear(),r.clear(),n=[],a=[],f.length=0,g={gpuMs:null,drawCalls:0,triangles:0,geometries:0,textures:0,renderPasses:null},p=be())},beginPhase(){l&&f.push(be())},endPhase(w){if(!l)return;const C=f.pop()??p,x=be()-C,b=i.get(w);i.set(w,{ms:(b?.ms??0)+x,startMs:b?.startMs??C-p}),d&&performance.measure(`vgai.phase.${w}`,{start:C,duration:x})},systemObserver:{beginSystem(){l&&(m=be())},endSystem(w,C,x){if(!l)return;const b=be(),P=`${w} / ${C} / ${x}`;s.set(P,(s.get(P)??0)+b-m),n.push({name:P,phase:C,startMs:m-p,ms:b-m})}},beginComponent(){d&&(y=be())},endComponent(w,C=""){if(!d)return;const x=be();r.set(w,(r.get(w)??0)+x-y),a.push({name:w,phase:C,startMs:y-p,ms:x-y})},reportRender(w){l&&(g={gpuMs:w.gpuMs??g.gpuMs,drawCalls:g.drawCalls+w.drawCalls,triangles:g.triangles+w.triangles,geometries:g.geometries+w.geometries,textures:g.textures+w.textures,renderPasses:w.renderPasses===void 0?g.renderPasses:(g.renderPasses??0)+w.renderPasses})},endFrame(){if(!l&&!h)return;const w=be(),C=u===0?0:p-u;u=p;const x={id:++c,timestamp:w,intervalMs:C,cpuMs:w-p,phases:[...i].map(([b,{ms:P,startMs:A}])=>({name:b,ms:P,startMs:A})).sort((b,P)=>P.ms-b.ms),systems:n.slice(),components:a.slice(),render:{...g}};e.push(x),e.length>600&&e.splice(0,e.length-600),d&&performance.measure("vgai.frame",{start:p,duration:x.cpuMs}),M()},subscribe(w){return t.add(w),()=>{t.delete(w)}},getSnapshot(){return _},exportJSON(){return JSON.stringify({version:2,capturedAt:new Date().toISOString(),frames:e},null,2)}}}const Oa=256;function gc(o){const t=Math.min(1,Math.max(0,o));return t<=.0031308?t*12.92:1.055*t**(1/2.4)-.055}function Fr(o,t,e){const i=Math.hypot(o,t,e)||1;return[o/i,t/i,e/i]}function yc(o=Oa){const t=document.createElement("canvas");t.width=o,t.height=o;const e=t.getContext("2d");if(!e)return t;const i=e.createImageData(o,o),s=Fr(-.45,.62,.64),r=Fr(.65,-.35,.5),n=Fr(s[0],s[1],s[2]+1),a=[.7,.69,.68],l=[.34,.4,.52],h=[.85,.88,1];for(let d=0;d<o;d++)for(let c=0;c<o;c++){const p=(c+.5)/o/.5-1,u=1-(d+.5)/o/.5,f=p*p+u*u,m=f>1,y=m?1/Math.sqrt(f):1,g=p*y,_=u*y,M=m?0:Math.sqrt(Math.max(0,1-f)),w=Math.max(0,g*s[0]+_*s[1]+M*s[2]),C=Math.max(0,g*r[0]+_*r[1]+M*r[2]),x=Math.max(0,g*n[0]+_*n[1]+M*n[2])**42*.5,b=(1-M)**3.2*.4,P=(d*o+c)*4;for(let A=0;A<3;A++){const N=a[A]*(.16+.8*w)+l[A]*.3*C+h[A]*b+x;i.data[P+A]=Math.round(gc(N)*255)}i.data[P+3]=255}return e.putImageData(i,0,0),t}function _c(o=Oa){const t=new ya(yc(o));return t.colorSpace=Ms,t.minFilter=Ui,t.magFilter=Ui,t.generateMipmaps=!1,t.needsUpdate=!0,t}function vc(o){return o.color?.clone()??new B(12502993)}function Br(o,t){return o[t]??null}class xc{_derived=new Map;_normals=new gh;_matcap=null;_matcapTexture=null;_overdraw=new Tt({color:16777215,transparent:!0,opacity:.08,depthTest:!1,depthWrite:!1,blending:bn,side:We,toneMapped:!1});render(t,e,i,s=()=>!0){if(e==="solid"){i();return}const r=[];t.traverse(n=>{const a=n;!a.isMesh||!a.material||!s(a)||(r.push({mesh:a,material:a.material}),a.material=Array.isArray(a.material)?a.material.map(l=>this._materialFor(l,e)):this._materialFor(a.material,e))});try{i()}finally{for(const{mesh:n,material:a}of r)n.material=a}}dispose(){for(const t of this._derived.values())t.clay.dispose(),t.unlit.dispose(),t.wireframe.dispose();this._derived.clear(),this._normals.dispose(),this._overdraw.dispose(),this._matcap?.dispose(),this._matcapTexture?.dispose(),this._matcap=null,this._matcapTexture=null}_materialFor(t,e){if(e==="normals")return this._normals;if(e==="overdraw")return this._overdraw;if(e==="matcap")return this._matcap||(this._matcapTexture=_c(),this._matcap=new yh({matcap:this._matcapTexture,toneMapped:!1})),this._matcap;let i=this._derived.get(t);if(!i){const s={color:vc(t),map:Br(t,"map"),alphaMap:Br(t,"alphaMap"),alphaTest:t.alphaTest,opacity:t.opacity,transparent:t.transparent,side:t.side,depthTest:t.depthTest,depthWrite:t.depthWrite,vertexColors:!!t.vertexColors,fog:t.fog??!0};i={clay:new _a({color:11450048,roughness:.82,metalness:0,flatShading:!0,alphaMap:Br(t,"alphaMap"),alphaTest:t.alphaTest,opacity:t.opacity,transparent:t.transparent,side:t.side,depthTest:t.depthTest,depthWrite:t.depthWrite}),unlit:new Tt(s),wireframe:new Tt({...s,wireframe:!0})},this._derived.set(t,i)}return i[e]}}function or(o){const t=xt(o,"constraints");return Array.isArray(t)?t.filter(e=>!!e&&typeof e=="object"&&typeof e.getSnapshot=="function"&&!!e.config):[]}function Li(o){const t=xt(o,"reflectionProbe");if(!t||typeof t!="object")return null;const e=t;return e.config&&typeof e.recapture=="function"&&typeof e.getSnapshot=="function"?t:null}function mn(o){const t=xt(o,"triggerVolume");if(!t||typeof t!="object")return null;const{radius:e}=t;return typeof e=="number"&&Number.isFinite(e)&&e>0?{radius:e}:null}const Le=new Yt,Et=new v,Me=new v,ot=new wt,wo={X:new v(1,0,0),Y:new v(0,1,0),Z:new v(0,0,1)},Nr={type:"change"},So={type:"mouseDown",mode:null},bo={type:"mouseUp",mode:null},Mo={type:"objectChange"};class Hr extends _h{constructor(t,e=null){super(void 0,e);const i=new Pc(this);this._root=i;const s=new Ac;this._gizmo=s,i.add(s);const r=new Ec;this._plane=r,i.add(r);const n=this;function a(M,w){let C=w;Object.defineProperty(n,M,{get:function(){return C!==void 0?C:w},set:function(x){C!==x&&(C=x,r[M]=x,s[M]=x,n.dispatchEvent({type:M+"-changed",value:x}),n.dispatchEvent(Nr))}}),n[M]=w,r[M]=w,s[M]=w}a("camera",t),a("object",void 0),a("enabled",!0),a("axis",null),a("mode","translate"),a("translationSnap",null),a("rotationSnap",null),a("scaleSnap",null),a("space","world"),a("size",1),a("dragging",!1),a("showX",!0),a("showY",!0),a("showZ",!0),a("minX",-1/0),a("maxX",1/0),a("minY",-1/0),a("maxY",1/0),a("minZ",-1/0),a("maxZ",1/0);const l=new v,h=new v,d=new wt,c=new wt,p=new v,u=new wt,f=new v,m=new v,y=new v,g=0,_=new v;a("worldPosition",l),a("worldPositionStart",h),a("worldQuaternion",d),a("worldQuaternionStart",c),a("cameraPosition",p),a("cameraQuaternion",u),a("pointStart",f),a("pointEnd",m),a("rotationAxis",y),a("rotationAngle",g),a("eye",_),this._offset=new v,this._startNorm=new v,this._endNorm=new v,this._cameraScale=new v,this._parentPosition=new v,this._parentQuaternion=new wt,this._parentQuaternionInv=new wt,this._parentScale=new v,this._worldScaleStart=new v,this._worldQuaternionInv=new wt,this._worldScale=new v,this._positionStart=new v,this._quaternionStart=new wt,this._scaleStart=new v,this._getPointer=wc.bind(this),this._onPointerDown=bc.bind(this),this._onPointerHover=Sc.bind(this),this._onPointerMove=Mc.bind(this),this._onPointerUp=Cc.bind(this),e!==null&&this.connect(e)}connect(t){super.connect(t),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointermove",this._onPointerHover),this.domElement.addEventListener("pointerup",this._onPointerUp),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointermove",this._onPointerHover),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.domElement.style.touchAction="auto"}getHelper(){return this._root}pointerHover(t){if(this.object===void 0||this.dragging===!0)return;t!==null&&Le.setFromCamera(t,this.camera);const e=Lr(this._gizmo.picker[this.mode],Le);e?this.axis=e.object.name:this.axis=null}pointerDown(t){if(!(this.object===void 0||this.dragging===!0||t!=null&&t.button!==0)&&this.axis!==null){t!==null&&Le.setFromCamera(t,this.camera);const e=Lr(this._plane,Le,!0);e&&(this.object.updateMatrixWorld(),this.object.parent.updateMatrixWorld(),this._positionStart.copy(this.object.position),this._quaternionStart.copy(this.object.quaternion),this._scaleStart.copy(this.object.scale),this.object.matrixWorld.decompose(this.worldPositionStart,this.worldQuaternionStart,this._worldScaleStart),this.pointStart.copy(e.point).sub(this.worldPositionStart)),this.dragging=!0,So.mode=this.mode,this.dispatchEvent(So)}}pointerMove(t){const e=this.axis,i=this.mode,s=this.object;let r=this.space;if(i==="scale"?r="local":(e==="E"||e==="XYZE"||e==="XYZ")&&(r="world"),s===void 0||e===null||this.dragging===!1||t!==null&&t.button!==-1)return;t!==null&&Le.setFromCamera(t,this.camera);const n=Lr(this._plane,Le,!0);if(n){if(this.pointEnd.copy(n.point).sub(this.worldPositionStart),i==="translate")this._offset.copy(this.pointEnd).sub(this.pointStart),r==="local"&&e!=="XYZ"&&this._offset.applyQuaternion(this._worldQuaternionInv),e.indexOf("X")===-1&&(this._offset.x=0),e.indexOf("Y")===-1&&(this._offset.y=0),e.indexOf("Z")===-1&&(this._offset.z=0),r==="local"&&e!=="XYZ"?this._offset.applyQuaternion(this._quaternionStart).divide(this._parentScale):this._offset.applyQuaternion(this._parentQuaternionInv).divide(this._parentScale),s.position.copy(this._offset).add(this._positionStart),this.translationSnap&&(r==="local"&&(s.position.applyQuaternion(ot.copy(this._quaternionStart).invert()),e.search("X")!==-1&&(s.position.x=Math.round(s.position.x/this.translationSnap)*this.translationSnap),e.search("Y")!==-1&&(s.position.y=Math.round(s.position.y/this.translationSnap)*this.translationSnap),e.search("Z")!==-1&&(s.position.z=Math.round(s.position.z/this.translationSnap)*this.translationSnap),s.position.applyQuaternion(this._quaternionStart)),r==="world"&&(s.parent&&s.position.add(Et.setFromMatrixPosition(s.parent.matrixWorld)),e.search("X")!==-1&&(s.position.x=Math.round(s.position.x/this.translationSnap)*this.translationSnap),e.search("Y")!==-1&&(s.position.y=Math.round(s.position.y/this.translationSnap)*this.translationSnap),e.search("Z")!==-1&&(s.position.z=Math.round(s.position.z/this.translationSnap)*this.translationSnap),s.parent&&s.position.sub(Et.setFromMatrixPosition(s.parent.matrixWorld)))),s.position.x=Math.max(this.minX,Math.min(this.maxX,s.position.x)),s.position.y=Math.max(this.minY,Math.min(this.maxY,s.position.y)),s.position.z=Math.max(this.minZ,Math.min(this.maxZ,s.position.z));else if(i==="scale"){if(e.search("XYZ")!==-1){let a=this.pointEnd.length()/this.pointStart.length();this.pointEnd.dot(this.pointStart)<0&&(a*=-1),Me.set(a,a,a)}else Et.copy(this.pointStart),Me.copy(this.pointEnd),Et.applyQuaternion(this._worldQuaternionInv),Me.applyQuaternion(this._worldQuaternionInv),Me.divide(Et),e.search("X")===-1&&(Me.x=1),e.search("Y")===-1&&(Me.y=1),e.search("Z")===-1&&(Me.z=1);s.scale.copy(this._scaleStart).multiply(Me),this.scaleSnap&&(e.search("X")!==-1&&(s.scale.x=Math.round(s.scale.x/this.scaleSnap)*this.scaleSnap||this.scaleSnap),e.search("Y")!==-1&&(s.scale.y=Math.round(s.scale.y/this.scaleSnap)*this.scaleSnap||this.scaleSnap),e.search("Z")!==-1&&(s.scale.z=Math.round(s.scale.z/this.scaleSnap)*this.scaleSnap||this.scaleSnap))}else if(i==="rotate"){this._offset.copy(this.pointEnd).sub(this.pointStart);const a=20/this.worldPosition.distanceTo(Et.setFromMatrixPosition(this.camera.matrixWorld));let l=!1;e==="XYZE"?(this.rotationAxis.copy(this._offset).cross(this.eye).normalize(),this.rotationAngle=this._offset.dot(Et.copy(this.rotationAxis).cross(this.eye))*a):(e==="X"||e==="Y"||e==="Z")&&(this.rotationAxis.copy(wo[e]),Et.copy(wo[e]),r==="local"&&Et.applyQuaternion(this.worldQuaternion),Et.cross(this.eye),Et.length()===0?l=!0:this.rotationAngle=this._offset.dot(Et.normalize())*a),(e==="E"||l)&&(this.rotationAxis.copy(this.eye),this.rotationAngle=this.pointEnd.angleTo(this.pointStart),this._startNorm.copy(this.pointStart).normalize(),this._endNorm.copy(this.pointEnd).normalize(),this.rotationAngle*=this._endNorm.cross(this._startNorm).dot(this.eye)<0?1:-1),this.rotationSnap&&(this.rotationAngle=Math.round(this.rotationAngle/this.rotationSnap)*this.rotationSnap),r==="local"&&e!=="E"&&e!=="XYZE"?(s.quaternion.copy(this._quaternionStart),s.quaternion.multiply(ot.setFromAxisAngle(this.rotationAxis,this.rotationAngle)).normalize()):(this.rotationAxis.applyQuaternion(this._parentQuaternionInv),s.quaternion.copy(ot.setFromAxisAngle(this.rotationAxis,this.rotationAngle)),s.quaternion.multiply(this._quaternionStart).normalize())}this.dispatchEvent(Nr),this.dispatchEvent(Mo)}}pointerUp(t){t!==null&&t.button!==0||(this.dragging&&this.axis!==null&&(bo.mode=this.mode,this.dispatchEvent(bo)),this.dragging=!1,this.axis=null)}dispose(){this.disconnect(),this._root.dispose()}attach(t){return this.object=t,this._root.visible=!0,this}detach(){return this.object=void 0,this.axis=null,this._root.visible=!1,this}reset(){this.enabled&&this.dragging&&(this.object.position.copy(this._positionStart),this.object.quaternion.copy(this._quaternionStart),this.object.scale.copy(this._scaleStart),this.dispatchEvent(Nr),this.dispatchEvent(Mo),this.pointStart.copy(this.pointEnd))}getRaycaster(){return Le}getMode(){return this.mode}setMode(t){this.mode=t}setTranslationSnap(t){this.translationSnap=t}setRotationSnap(t){this.rotationSnap=t}setScaleSnap(t){this.scaleSnap=t}setSize(t){this.size=t}setSpace(t){this.space=t}setColors(t,e,i,s){const r=this._gizmo.materialLib;r.xAxis.color.set(t),r.yAxis.color.set(e),r.zAxis.color.set(i),r.active.color.set(s),r.xAxisTransparent.color.set(t),r.yAxisTransparent.color.set(e),r.zAxisTransparent.color.set(i),r.activeTransparent.color.set(s),r.xAxis._color&&r.xAxis._color.set(t),r.yAxis._color&&r.yAxis._color.set(e),r.zAxis._color&&r.zAxis._color.set(i),r.active._color&&r.active._color.set(s),r.xAxisTransparent._color&&r.xAxisTransparent._color.set(t),r.yAxisTransparent._color&&r.yAxisTransparent._color.set(e),r.zAxisTransparent._color&&r.zAxisTransparent._color.set(i),r.activeTransparent._color&&r.activeTransparent._color.set(s)}}function wc(o){if(this.domElement.ownerDocument.pointerLockElement)return{x:0,y:0,button:o.button};{const t=this.domElement.getBoundingClientRect();return{x:(o.clientX-t.left)/t.width*2-1,y:-(o.clientY-t.top)/t.height*2+1,button:o.button}}}function Sc(o){if(this.enabled)switch(o.pointerType){case"mouse":case"pen":this.pointerHover(this._getPointer(o));break}}function bc(o){this.enabled&&(document.pointerLockElement||this.domElement.setPointerCapture(o.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.pointerHover(this._getPointer(o)),this.pointerDown(this._getPointer(o)))}function Mc(o){this.enabled&&this.pointerMove(this._getPointer(o))}function Cc(o){this.enabled&&(this.domElement.releasePointerCapture(o.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.pointerUp(this._getPointer(o)))}function Lr(o,t,e){const i=t.intersectObject(o,!0);for(let s=0;s<i.length;s++)if(i[s].object.visible||e)return i[s];return!1}const Ws=new va,it=new v(0,1,0),Co=new v(0,0,0),Po=new Mn,Js=new wt,rr=new wt,$t=new v,Ao=new Mn,Bi=new v(1,0,0),Ue=new v(0,1,0),Ni=new v(0,0,1),Ys=new v,Oi=new v,Ii=new v;class Pc extends Je{constructor(t){super(),this.isTransformControlsRoot=!0,this.controls=t,this.visible=!1}updateMatrixWorld(t){const e=this.controls;e.object!==void 0&&(e.object.updateMatrixWorld(),e.object.parent===null?console.error("TransformControls: The attached 3D object must be a part of the scene graph."):e.object.parent.matrixWorld.decompose(e._parentPosition,e._parentQuaternion,e._parentScale),e.object.matrixWorld.decompose(e.worldPosition,e.worldQuaternion,e._worldScale),e._parentQuaternionInv.copy(e._parentQuaternion).invert(),e._worldQuaternionInv.copy(e.worldQuaternion).invert()),e.camera.updateMatrixWorld(),e.camera.matrixWorld.decompose(e.cameraPosition,e.cameraQuaternion,e._cameraScale),e.camera.isOrthographicCamera?e.camera.getWorldDirection(e.eye).negate():e.eye.copy(e.cameraPosition).sub(e.worldPosition).normalize(),super.updateMatrixWorld(t)}dispose(){this.traverse(function(t){t.geometry&&t.geometry.dispose(),t.material&&t.material.dispose()})}}class Ac extends Je{constructor(){super(),this.isTransformControlsGizmo=!0,this.type="TransformControlsGizmo";const t=new Tt({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),e=new Ze({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),i=t.clone();i.opacity=.15;const s=e.clone();s.opacity=.5;const r=t.clone();r.color.setHex(16711680);const n=t.clone();n.color.setHex(65280);const a=t.clone();a.color.setHex(255);const l=t.clone();l.color.setHex(16711680),l.opacity=.5;const h=t.clone();h.color.setHex(65280),h.opacity=.5;const d=t.clone();d.color.setHex(255),d.opacity=.5;const c=t.clone();c.opacity=.25;const p=t.clone();p.color.setHex(16776960),p.opacity=.25;const u=t.clone();u.color.setHex(16776960);const f=t.clone();f.color.setHex(7895160),this.materialLib={xAxis:r,yAxis:n,zAxis:a,active:u,xAxisTransparent:l,yAxisTransparent:h,zAxisTransparent:d,activeTransparent:p};const m=new Ot(0,.04,.1,12);m.translate(0,.05,0);const y=new mt(.08,.08,.08);y.translate(0,.04,0);const g=new Re;g.setAttribute("position",new Vi([0,0,0,1,0,0],3));const _=new Ot(.0075,.0075,.5,3);_.translate(0,.25,0);function M(K,lt){const st=new zi(K,.0075,3,64,lt*Math.PI*2);return st.rotateY(Math.PI/2),st.rotateX(Math.PI/2),st}function w(){const K=new Re;return K.setAttribute("position",new Vi([0,0,0,1,1,1],3)),K}const C={X:[[new E(m,r),[.5,0,0],[0,0,-Math.PI/2]],[new E(m,r),[-.5,0,0],[0,0,Math.PI/2]],[new E(_,r),[0,0,0],[0,0,-Math.PI/2]]],Y:[[new E(m,n),[0,.5,0]],[new E(m,n),[0,-.5,0],[Math.PI,0,0]],[new E(_,n)]],Z:[[new E(m,a),[0,0,.5],[Math.PI/2,0,0]],[new E(m,a),[0,0,-.5],[-Math.PI/2,0,0]],[new E(_,a),null,[Math.PI/2,0,0]]],XYZ:[[new E(new Ve(.1,0),c),[0,0,0]]],XY:[[new E(new mt(.15,.15,.01),d),[.15,.15,0]]],YZ:[[new E(new mt(.15,.15,.01),l),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new E(new mt(.15,.15,.01),h),[.15,0,.15],[-Math.PI/2,0,0]]]},x={X:[[new E(new Ot(.2,0,.6,4),i),[.3,0,0],[0,0,-Math.PI/2]],[new E(new Ot(.2,0,.6,4),i),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new E(new Ot(.2,0,.6,4),i),[0,.3,0]],[new E(new Ot(.2,0,.6,4),i),[0,-.3,0],[0,0,Math.PI]]],Z:[[new E(new Ot(.2,0,.6,4),i),[0,0,.3],[Math.PI/2,0,0]],[new E(new Ot(.2,0,.6,4),i),[0,0,-.3],[-Math.PI/2,0,0]]],XYZ:[[new E(new Ve(.2,0),i)]],XY:[[new E(new mt(.2,.2,.01),i),[.15,.15,0]]],YZ:[[new E(new mt(.2,.2,.01),i),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new E(new mt(.2,.2,.01),i),[.15,0,.15],[-Math.PI/2,0,0]]]},b={START:[[new E(new Ve(.01,2),s),null,null,null,"helper"]],END:[[new E(new Ve(.01,2),s),null,null,null,"helper"]],DELTA:[[new Wt(w(),s),null,null,null,"helper"]],X:[[new Wt(g,s),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new Wt(g,s),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new Wt(g,s),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]},P={XYZE:[[new E(M(.5,1),f),null,[0,Math.PI/2,0]]],X:[[new E(M(.5,.5),r)]],Y:[[new E(M(.5,.5),n),null,[0,0,-Math.PI/2]]],Z:[[new E(M(.5,.5),a),null,[0,Math.PI/2,0]]],E:[[new E(M(.75,1),p),null,[0,Math.PI/2,0]]]},A={AXIS:[[new Wt(g,s),[-1e3,0,0],null,[1e6,1,1],"helper"]]},N={XYZE:[[new E(new fe(.25,10,8),i)]],X:[[new E(new zi(.5,.1,4,24),i),[0,0,0],[0,-Math.PI/2,-Math.PI/2]]],Y:[[new E(new zi(.5,.1,4,24),i),[0,0,0],[Math.PI/2,0,0]]],Z:[[new E(new zi(.5,.1,4,24),i),[0,0,0],[0,0,-Math.PI/2]]],E:[[new E(new zi(.75,.1,2,24),i)]]},J={X:[[new E(y,r),[.5,0,0],[0,0,-Math.PI/2]],[new E(_,r),[0,0,0],[0,0,-Math.PI/2]],[new E(y,r),[-.5,0,0],[0,0,Math.PI/2]]],Y:[[new E(y,n),[0,.5,0]],[new E(_,n)],[new E(y,n),[0,-.5,0],[0,0,Math.PI]]],Z:[[new E(y,a),[0,0,.5],[Math.PI/2,0,0]],[new E(_,a),[0,0,0],[Math.PI/2,0,0]],[new E(y,a),[0,0,-.5],[-Math.PI/2,0,0]]],XY:[[new E(new mt(.15,.15,.01),d),[.15,.15,0]]],YZ:[[new E(new mt(.15,.15,.01),l),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new E(new mt(.15,.15,.01),h),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new E(new mt(.1,.1,.1),c)]]},$={X:[[new E(new Ot(.2,0,.6,4),i),[.3,0,0],[0,0,-Math.PI/2]],[new E(new Ot(.2,0,.6,4),i),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new E(new Ot(.2,0,.6,4),i),[0,.3,0]],[new E(new Ot(.2,0,.6,4),i),[0,-.3,0],[0,0,Math.PI]]],Z:[[new E(new Ot(.2,0,.6,4),i),[0,0,.3],[Math.PI/2,0,0]],[new E(new Ot(.2,0,.6,4),i),[0,0,-.3],[-Math.PI/2,0,0]]],XY:[[new E(new mt(.2,.2,.01),i),[.15,.15,0]]],YZ:[[new E(new mt(.2,.2,.01),i),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new E(new mt(.2,.2,.01),i),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new E(new mt(.2,.2,.2),i),[0,0,0]]]},gt={X:[[new Wt(g,s),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new Wt(g,s),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new Wt(g,s),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]};function Y(K){const lt=new Je;for(const st in K)for(let ct=K[st].length;ct--;){const tt=K[st][ct][0].clone(),dt=K[st][ct][1],ut=K[st][ct][2],V=K[st][ct][3],yt=K[st][ct][4];tt.name=st,tt.tag=yt,dt&&tt.position.set(dt[0],dt[1],dt[2]),ut&&tt.rotation.set(ut[0],ut[1],ut[2]),V&&tt.scale.set(V[0],V[1],V[2]),tt.updateMatrix();const D=tt.geometry.clone();D.applyMatrix4(tt.matrix),tt.geometry=D,tt.renderOrder=1/0,tt.position.set(0,0,0),tt.rotation.set(0,0,0),tt.scale.set(1,1,1),lt.add(tt)}return lt}this.gizmo={},this.picker={},this.helper={},this.add(this.gizmo.translate=Y(C)),this.add(this.gizmo.rotate=Y(P)),this.add(this.gizmo.scale=Y(J)),this.add(this.picker.translate=Y(x)),this.add(this.picker.rotate=Y(N)),this.add(this.picker.scale=Y($)),this.add(this.helper.translate=Y(b)),this.add(this.helper.rotate=Y(A)),this.add(this.helper.scale=Y(gt)),this.picker.translate.visible=!1,this.picker.rotate.visible=!1,this.picker.scale.visible=!1}updateMatrixWorld(t){const i=(this.mode==="scale"?"local":this.space)==="local"?this.worldQuaternion:rr;this.gizmo.translate.visible=this.mode==="translate",this.gizmo.rotate.visible=this.mode==="rotate",this.gizmo.scale.visible=this.mode==="scale",this.helper.translate.visible=this.mode==="translate",this.helper.rotate.visible=this.mode==="rotate",this.helper.scale.visible=this.mode==="scale";let s=[];s=s.concat(this.picker[this.mode].children),s=s.concat(this.gizmo[this.mode].children),s=s.concat(this.helper[this.mode].children);for(let r=0;r<s.length;r++){const n=s[r];n.visible=!0,n.rotation.set(0,0,0),n.position.copy(this.worldPosition);let a;if(this.camera.isOrthographicCamera?a=(this.camera.top-this.camera.bottom)/this.camera.zoom:a=this.worldPosition.distanceTo(this.cameraPosition)*Math.min(1.9*Math.tan(Math.PI*this.camera.fov/360)/this.camera.zoom,7),n.scale.set(1,1,1).multiplyScalar(a*this.size/4),n.tag==="helper"){n.visible=!1,n.name==="AXIS"?(n.visible=!!this.axis,this.axis==="X"&&(ot.setFromEuler(Ws.set(0,0,0)),n.quaternion.copy(i).multiply(ot),Math.abs(it.copy(Bi).applyQuaternion(i).dot(this.eye))>.9&&(n.visible=!1)),this.axis==="Y"&&(ot.setFromEuler(Ws.set(0,0,Math.PI/2)),n.quaternion.copy(i).multiply(ot),Math.abs(it.copy(Ue).applyQuaternion(i).dot(this.eye))>.9&&(n.visible=!1)),this.axis==="Z"&&(ot.setFromEuler(Ws.set(0,Math.PI/2,0)),n.quaternion.copy(i).multiply(ot),Math.abs(it.copy(Ni).applyQuaternion(i).dot(this.eye))>.9&&(n.visible=!1)),this.axis==="XYZE"&&(ot.setFromEuler(Ws.set(0,Math.PI/2,0)),it.copy(this.rotationAxis),n.quaternion.setFromRotationMatrix(Po.lookAt(Co,it,Ue)),n.quaternion.multiply(ot),n.visible=this.dragging),this.axis==="E"&&(n.visible=!1)):n.name==="START"?(n.position.copy(this.worldPositionStart),n.visible=this.dragging):n.name==="END"?(n.position.copy(this.worldPosition),n.visible=this.dragging):n.name==="DELTA"?(n.position.copy(this.worldPositionStart),n.quaternion.copy(this.worldQuaternionStart),Et.set(1e-10,1e-10,1e-10).add(this.worldPositionStart).sub(this.worldPosition).multiplyScalar(-1),Et.applyQuaternion(this.worldQuaternionStart.clone().invert()),n.scale.copy(Et),n.visible=this.dragging):(n.quaternion.copy(i),this.dragging?n.position.copy(this.worldPositionStart):n.position.copy(this.worldPosition),this.axis&&(n.visible=this.axis.search(n.name)!==-1));continue}n.quaternion.copy(i),this.mode==="translate"||this.mode==="scale"?(n.name==="X"&&Math.abs(it.copy(Bi).applyQuaternion(i).dot(this.eye))>.99&&(n.scale.set(1e-10,1e-10,1e-10),n.visible=!1),n.name==="Y"&&Math.abs(it.copy(Ue).applyQuaternion(i).dot(this.eye))>.99&&(n.scale.set(1e-10,1e-10,1e-10),n.visible=!1),n.name==="Z"&&Math.abs(it.copy(Ni).applyQuaternion(i).dot(this.eye))>.99&&(n.scale.set(1e-10,1e-10,1e-10),n.visible=!1),n.name==="XY"&&Math.abs(it.copy(Ni).applyQuaternion(i).dot(this.eye))<.2&&(n.scale.set(1e-10,1e-10,1e-10),n.visible=!1),n.name==="YZ"&&Math.abs(it.copy(Bi).applyQuaternion(i).dot(this.eye))<.2&&(n.scale.set(1e-10,1e-10,1e-10),n.visible=!1),n.name==="XZ"&&Math.abs(it.copy(Ue).applyQuaternion(i).dot(this.eye))<.2&&(n.scale.set(1e-10,1e-10,1e-10),n.visible=!1)):this.mode==="rotate"&&(Js.copy(i),it.copy(this.eye).applyQuaternion(ot.copy(i).invert()),n.name.search("E")!==-1&&n.quaternion.setFromRotationMatrix(Po.lookAt(this.eye,Co,Ue)),n.name==="X"&&(ot.setFromAxisAngle(Bi,Math.atan2(-it.y,it.z)),ot.multiplyQuaternions(Js,ot),n.quaternion.copy(ot)),n.name==="Y"&&(ot.setFromAxisAngle(Ue,Math.atan2(it.x,it.z)),ot.multiplyQuaternions(Js,ot),n.quaternion.copy(ot)),n.name==="Z"&&(ot.setFromAxisAngle(Ni,Math.atan2(it.y,it.x)),ot.multiplyQuaternions(Js,ot),n.quaternion.copy(ot))),n.visible=n.visible&&(n.name.indexOf("X")===-1||this.showX),n.visible=n.visible&&(n.name.indexOf("Y")===-1||this.showY),n.visible=n.visible&&(n.name.indexOf("Z")===-1||this.showZ),n.visible=n.visible&&(n.name.indexOf("E")===-1||this.showX&&this.showY&&this.showZ),n.material._color=n.material._color||n.material.color.clone(),n.material._opacity=n.material._opacity||n.material.opacity,n.material.color.copy(n.material._color),n.material.opacity=n.material._opacity,this.enabled&&this.axis&&(n.name===this.axis?(n.material.color.copy(this.materialLib.active.color),n.material.opacity=1):this.axis.split("").some(function(l){return n.name===l})&&(n.material.color.copy(this.materialLib.active.color),n.material.opacity=1))}super.updateMatrixWorld(t)}}class Ec extends E{constructor(){super(new Cn(1e5,1e5,2,2),new Tt({visible:!1,wireframe:!0,side:We,transparent:!0,opacity:.1,toneMapped:!1})),this.isTransformControlsPlane=!0,this.type="TransformControlsPlane"}updateMatrixWorld(t){let e=this.space;switch(this.position.copy(this.worldPosition),this.mode==="scale"&&(e="local"),Ys.copy(Bi).applyQuaternion(e==="local"?this.worldQuaternion:rr),Oi.copy(Ue).applyQuaternion(e==="local"?this.worldQuaternion:rr),Ii.copy(Ni).applyQuaternion(e==="local"?this.worldQuaternion:rr),it.copy(Oi),this.mode){case"translate":case"scale":switch(this.axis){case"X":it.copy(this.eye).cross(Ys),$t.copy(Ys).cross(it);break;case"Y":it.copy(this.eye).cross(Oi),$t.copy(Oi).cross(it);break;case"Z":it.copy(this.eye).cross(Ii),$t.copy(Ii).cross(it);break;case"XY":$t.copy(Ii);break;case"YZ":$t.copy(Ys);break;case"XZ":it.copy(Ii),$t.copy(Oi);break;case"XYZ":case"E":$t.set(0,0,0);break}break;case"rotate":default:$t.set(0,0,0)}$t.length()===0?this.quaternion.copy(this.cameraQuaternion):(Ao.lookAt(Et.set(0,0,0),$t,it),this.quaternion.setFromRotationMatrix(Ao)),super.updateMatrixWorld(t)}}const At=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"];let Eo=1234567;const Ia=Math.PI/180,Ra=180/Math.PI;function Tc(){const o=Math.random()*4294967295|0,t=Math.random()*4294967295|0,e=Math.random()*4294967295|0,i=Math.random()*4294967295|0;return(At[o&255]+At[o>>8&255]+At[o>>16&255]+At[o>>24&255]+"-"+At[t&255]+At[t>>8&255]+"-"+At[t>>16&15|64]+At[t>>24&255]+"-"+At[e&63|128]+At[e>>8&255]+"-"+At[e>>16&255]+At[e>>24&255]+At[i&255]+At[i>>8&255]+At[i>>16&255]+At[i>>24&255]).toLowerCase()}function ee(o,t,e){return Math.max(t,Math.min(e,o))}function ka(o,t){return(o%t+t)%t}function zc(o,t,e,i,s){return i+(o-t)*(s-i)/(e-t)}function Oc(o,t,e){return o!==t?(e-o)/(t-o):0}function Fa(o,t,e){return(1-e)*o+e*t}function Ic(o,t,e,i){return Fa(o,t,1-Math.exp(-e*i))}function Rc(o,t=1){return t-Math.abs(ka(o,t*2)-t)}function kc(o,t,e){return o<=t?0:o>=e?1:(o=(o-t)/(e-t),o*o*(3-2*o))}function Fc(o,t,e){return o<=t?0:o>=e?1:(o=(o-t)/(e-t),o*o*o*(o*(o*6-15)+10))}function Bc(o,t){return o+Math.floor(Math.random()*(t-o+1))}function Nc(o,t){return o+Math.random()*(t-o)}function Hc(o){return o*(.5-Math.random())}function Lc(o){o!==void 0&&(Eo=o);let t=Eo+=1831565813;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}function Dc(o){return o*Ia}function Uc(o){return o*Ra}function Vc(o){return(o&o-1)===0&&o!==0}function jc(o){return Math.pow(2,Math.ceil(Math.log(o)/Math.LN2))}function Gc(o){return Math.pow(2,Math.floor(Math.log(o)/Math.LN2))}function Xc(o,t,e,i,s){const r=Math.cos,n=Math.sin,a=r(e/2),l=n(e/2),h=r((t+i)/2),d=n((t+i)/2),c=r((t-i)/2),p=n((t-i)/2),u=r((i-t)/2),f=n((i-t)/2);switch(s){case"XYX":o.set(a*d,l*c,l*p,a*h);break;case"YZY":o.set(l*p,a*d,l*c,a*h);break;case"ZXZ":o.set(l*c,l*p,a*d,a*h);break;case"XZX":o.set(a*d,l*f,l*u,a*h);break;case"YXY":o.set(l*u,a*d,l*f,a*h);break;case"ZYZ":o.set(l*f,l*u,a*d,a*h);break;default:console.warn("../math.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+s)}}function Wc(o,t){switch(t.constructor){case Float32Array:return o;case Uint32Array:return o/4294967295;case Uint16Array:return o/65535;case Uint8Array:return o/255;case Int32Array:return Math.max(o/2147483647,-1);case Int16Array:return Math.max(o/32767,-1);case Int8Array:return Math.max(o/127,-1);default:throw new Error("Invalid component type.")}}function Jc(o,t){switch(t.constructor){case Float32Array:return o;case Uint32Array:return Math.round(o*4294967295);case Uint16Array:return Math.round(o*65535);case Uint8Array:return Math.round(o*255);case Int32Array:return Math.round(o*2147483647);case Int16Array:return Math.round(o*32767);case Int8Array:return Math.round(o*127);default:throw new Error("Invalid component type.")}}const Si={DEG2RAD:Ia,RAD2DEG:Ra,generateUUID:Tc,clamp:ee,euclideanModulo:ka,mapLinear:zc,inverseLerp:Oc,lerp:Fa,damp:Ic,pingpong:Rc,smoothstep:kc,smootherstep:Fc,randInt:Bc,randFloat:Nc,randFloatSpread:Hc,seededRandom:Lc,degToRad:Dc,radToDeg:Uc,isPowerOfTwo:Vc,ceilPowerOfTwo:jc,floorPowerOfTwo:Gc,setQuaternionFromProperEuler:Xc,normalize:Jc,denormalize:Wc};class W{constructor(t=0,e=0,i=0,s=1){this.isQuaternion=!0,this._x=t,this._y=e,this._z=i,this._w=s}static slerpFlat(t,e,i,s,r,n,a){let l=i[s+0],h=i[s+1],d=i[s+2],c=i[s+3];const p=r[n+0],u=r[n+1],f=r[n+2],m=r[n+3];if(a===0){t[e+0]=l,t[e+1]=h,t[e+2]=d,t[e+3]=c;return}if(a===1){t[e+0]=p,t[e+1]=u,t[e+2]=f,t[e+3]=m;return}if(c!==m||l!==p||h!==u||d!==f){let y=1-a;const g=l*p+h*u+d*f+c*m,_=g>=0?1:-1,M=1-g*g;if(M>Number.EPSILON){const C=Math.sqrt(M),x=Math.atan2(C,g*_);y=Math.sin(y*x)/C,a=Math.sin(a*x)/C}const w=a*_;if(l=l*y+p*w,h=h*y+u*w,d=d*y+f*w,c=c*y+m*w,y===1-a){const C=1/Math.sqrt(l*l+h*h+d*d+c*c);l*=C,h*=C,d*=C,c*=C}}t[e]=l,t[e+1]=h,t[e+2]=d,t[e+3]=c}static multiplyQuaternionsFlat(t,e,i,s,r,n){const a=i[s],l=i[s+1],h=i[s+2],d=i[s+3],c=r[n],p=r[n+1],u=r[n+2],f=r[n+3];return t[e]=a*f+d*c+l*u-h*p,t[e+1]=l*f+d*p+h*c-a*u,t[e+2]=h*f+d*u+a*p-l*c,t[e+3]=d*f-a*c-l*p-h*u,t}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get w(){return this._w}set w(t){this._w=t,this._onChangeCallback()}set(t,e,i,s){return this._x=t,this._y=e,this._z=i,this._w=s,this._onChangeCallback(),this}clone(){return new W(this._x,this._y,this._z,this._w)}copy(t){return this._x=t.x,this._y=t.y,this._z=t.z,this._w=t.w,this._onChangeCallback(),this}setFromEuler(t,e=!0){const i=t._x,s=t._y,r=t._z,n=t._order,a=Math.cos,l=Math.sin,h=a(i/2),d=a(s/2),c=a(r/2),p=l(i/2),u=l(s/2),f=l(r/2);switch(n){case"XYZ":this._x=p*d*c+h*u*f,this._y=h*u*c-p*d*f,this._z=h*d*f+p*u*c,this._w=h*d*c-p*u*f;break;case"YXZ":this._x=p*d*c+h*u*f,this._y=h*u*c-p*d*f,this._z=h*d*f-p*u*c,this._w=h*d*c+p*u*f;break;case"ZXY":this._x=p*d*c-h*u*f,this._y=h*u*c+p*d*f,this._z=h*d*f+p*u*c,this._w=h*d*c-p*u*f;break;case"ZYX":this._x=p*d*c-h*u*f,this._y=h*u*c+p*d*f,this._z=h*d*f-p*u*c,this._w=h*d*c+p*u*f;break;case"YZX":this._x=p*d*c+h*u*f,this._y=h*u*c+p*d*f,this._z=h*d*f-p*u*c,this._w=h*d*c-p*u*f;break;case"XZY":this._x=p*d*c-h*u*f,this._y=h*u*c-p*d*f,this._z=h*d*f+p*u*c,this._w=h*d*c+p*u*f;break;default:console.warn("../math.Quaternion: .setFromEuler() encountered an unknown order: "+n)}return e===!0&&this._onChangeCallback(),this}setFromAxisAngle(t,e){const i=e/2,s=Math.sin(i);return this._x=t.x*s,this._y=t.y*s,this._z=t.z*s,this._w=Math.cos(i),this._onChangeCallback(),this}setFromRotationMatrix(t){const e=t.elements,i=e[0],s=e[4],r=e[8],n=e[1],a=e[5],l=e[9],h=e[2],d=e[6],c=e[10],p=i+a+c;if(p>0){const u=.5/Math.sqrt(p+1);this._w=.25/u,this._x=(d-l)*u,this._y=(r-h)*u,this._z=(n-s)*u}else if(i>a&&i>c){const u=2*Math.sqrt(1+i-a-c);this._w=(d-l)/u,this._x=.25*u,this._y=(s+n)/u,this._z=(r+h)/u}else if(a>c){const u=2*Math.sqrt(1+a-i-c);this._w=(r-h)/u,this._x=(s+n)/u,this._y=.25*u,this._z=(l+d)/u}else{const u=2*Math.sqrt(1+c-i-a);this._w=(n-s)/u,this._x=(r+h)/u,this._y=(l+d)/u,this._z=.25*u}return this._onChangeCallback(),this}setFromUnitVectors(t,e){let i=t.dot(e)+1;return i<Number.EPSILON?(i=0,Math.abs(t.x)>Math.abs(t.z)?(this._x=-t.y,this._y=t.x,this._z=0,this._w=i):(this._x=0,this._y=-t.z,this._z=t.y,this._w=i)):(this._x=t.y*e.z-t.z*e.y,this._y=t.z*e.x-t.x*e.z,this._z=t.x*e.y-t.y*e.x,this._w=i),this.normalize()}angleTo(t){return 2*Math.acos(Math.abs(ee(this.dot(t),-1,1)))}rotateTowards(t,e){const i=this.angleTo(t);if(i===0)return this;const s=Math.min(1,e/i);return this.slerp(t,s),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(t){return this._x*t._x+this._y*t._y+this._z*t._z+this._w*t._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let t=this.length();return t===0?(this._x=0,this._y=0,this._z=0,this._w=1):(t=1/t,this._x=this._x*t,this._y=this._y*t,this._z=this._z*t,this._w=this._w*t),this._onChangeCallback(),this}multiply(t){return this.multiplyQuaternions(this,t)}premultiply(t){return this.multiplyQuaternions(t,this)}multiplyQuaternions(t,e){const i=t._x,s=t._y,r=t._z,n=t._w,a=e._x,l=e._y,h=e._z,d=e._w;return this._x=i*d+n*a+s*h-r*l,this._y=s*d+n*l+r*a-i*h,this._z=r*d+n*h+i*l-s*a,this._w=n*d-i*a-s*l-r*h,this._onChangeCallback(),this}slerp(t,e){if(e===0)return this;if(e===1)return this.copy(t);const i=this._x,s=this._y,r=this._z,n=this._w;let a=n*t._w+i*t._x+s*t._y+r*t._z;if(a<0?(this._w=-t._w,this._x=-t._x,this._y=-t._y,this._z=-t._z,a=-a):this.copy(t),a>=1)return this._w=n,this._x=i,this._y=s,this._z=r,this;const l=1-a*a;if(l<=Number.EPSILON){const u=1-e;return this._w=u*n+e*this._w,this._x=u*i+e*this._x,this._y=u*s+e*this._y,this._z=u*r+e*this._z,this.normalize(),this}const h=Math.sqrt(l),d=Math.atan2(h,a),c=Math.sin((1-e)*d)/h,p=Math.sin(e*d)/h;return this._w=n*c+this._w*p,this._x=i*c+this._x*p,this._y=s*c+this._y*p,this._z=r*c+this._z*p,this._onChangeCallback(),this}slerpQuaternions(t,e,i){return this.copy(t).slerp(e,i)}random(){const t=2*Math.PI*Math.random(),e=2*Math.PI*Math.random(),i=Math.random(),s=Math.sqrt(1-i),r=Math.sqrt(i);return this.set(s*Math.sin(t),s*Math.cos(t),r*Math.sin(e),r*Math.cos(e))}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._w===this._w}fromArray(t,e=0){return this._x=t[e],this._y=t[e+1],this._z=t[e+2],this._w=t[e+3],this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._w,t}toJSON(){return this.toArray()}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class I{constructor(t=0,e=0,i=0){this.isVector3=!0,I.prototype.isVector3=!0,this.x=t,this.y=e,this.z=i}set(t,e,i){return i===void 0&&(i=this.z),this.x=t,this.y=e,this.z=i,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+t)}}clone(){return new I(this.x,this.y,this.z)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this}multiplyVectors(t,e){return this.x=t.x*e.x,this.y=t.y*e.y,this.z=t.z*e.z,this}applyEuler(t){return this.applyQuaternion(To.setFromEuler(t))}applyAxisAngle(t,e){return this.applyQuaternion(To.setFromAxisAngle(t,e))}applyMatrix3(t){const e=this.x,i=this.y,s=this.z,r=t.elements;return this.x=r[0]*e+r[3]*i+r[6]*s,this.y=r[1]*e+r[4]*i+r[7]*s,this.z=r[2]*e+r[5]*i+r[8]*s,this}applyNormalMatrix(t){return this.applyMatrix3(t).normalize()}applyMatrix4(t){const e=this.x,i=this.y,s=this.z,r=t.elements,n=1/(r[3]*e+r[7]*i+r[11]*s+r[15]);return this.x=(r[0]*e+r[4]*i+r[8]*s+r[12])*n,this.y=(r[1]*e+r[5]*i+r[9]*s+r[13])*n,this.z=(r[2]*e+r[6]*i+r[10]*s+r[14])*n,this}applyQuaternion(t){const e=this.x,i=this.y,s=this.z,r=t.x,n=t.y,a=t.z,l=t.w,h=2*(n*s-a*i),d=2*(a*e-r*s),c=2*(r*i-n*e);return this.x=e+l*h+n*c-a*d,this.y=i+l*d+a*h-r*c,this.z=s+l*c+r*d-n*h,this}transformDirection(t){const e=this.x,i=this.y,s=this.z,r=t.elements;return this.x=r[0]*e+r[4]*i+r[8]*s,this.y=r[1]*e+r[5]*i+r[9]*s,this.z=r[2]*e+r[6]*i+r[10]*s,this.normalize()}divide(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this}divideScalar(t){return this.multiplyScalar(1/t)}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this}clamp(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this.z=Math.max(t.z,Math.min(e.z,this.z)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this.z=Math.max(t,Math.min(e,this.z)),this}clampLength(t,e){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Math.max(t,Math.min(e,i)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this}lerpVectors(t,e,i){return this.x=t.x+(e.x-t.x)*i,this.y=t.y+(e.y-t.y)*i,this.z=t.z+(e.z-t.z)*i,this}cross(t){return this.crossVectors(this,t)}crossVectors(t,e){const i=t.x,s=t.y,r=t.z,n=e.x,a=e.y,l=e.z;return this.x=s*l-r*a,this.y=r*n-i*l,this.z=i*a-s*n,this}projectOnVector(t){const e=t.lengthSq();if(e===0)return this.set(0,0,0);const i=t.dot(this)/e;return this.copy(t).multiplyScalar(i)}projectOnPlane(t){return Dr.copy(this).projectOnVector(t),this.sub(Dr)}reflect(t){return this.sub(Dr.copy(t).multiplyScalar(2*this.dot(t)))}angleTo(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(e===0)return Math.PI/2;const i=this.dot(t)/e;return Math.acos(ee(i,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,i=this.y-t.y,s=this.z-t.z;return e*e+i*i+s*s}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)+Math.abs(this.z-t.z)}setFromSphericalCoords(t,e,i){const s=Math.sin(e)*t;return this.x=s*Math.sin(i),this.y=Math.cos(e)*t,this.z=s*Math.cos(i),this}setFromCylindricalCoords(t,e,i){return this.x=t*Math.sin(e),this.y=i,this.z=t*Math.cos(e),this}setFromMatrixPosition(t){const e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this}setFromMatrixScale(t){const e=this.setFromMatrixColumn(t,0).length(),i=this.setFromMatrixColumn(t,1).length(),s=this.setFromMatrixColumn(t,2).length();return this.x=e,this.y=i,this.z=s,this}setFromMatrixColumn(t,e){return this.fromArray(t.elements,e*4)}setFromMatrix3Column(t,e){return this.fromArray(t.elements,e*3)}setFromEuler(t){return this.x=t._x,this.y=t._y,this.z=t._z,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const t=Math.random()*Math.PI*2,e=Math.random()*2-1,i=Math.sqrt(1-e*e);return this.x=i*Math.cos(t),this.y=e,this.z=i*Math.sin(t),this}abs(){return this.x=Math.abs(this.x),this.y=Math.abs(this.y),this.z=Math.abs(this.z),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const Dr=new I,To=new W,qs=2e3,zo=2001;class Zt{constructor(t,e,i,s,r,n,a,l,h,d,c,p,u,f,m,y){this.isMatrix4=!0,Zt.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],t!==void 0&&this.set(t,e,i,s,r,n,a,l,h,d,c,p,u,f,m,y)}extractPosition(t){return console.warn("THREE.Matrix4: .extractPosition() has been renamed to .copyPosition()."),this.copyPosition(t)}multiplyToArray(t,e,i){return console.error("THREE.Matrix4: .multiplyToArray() has been removed."),this}setRotationFromQuaternion(t){return this.makeRotationFromQuaternion(t)}set(t,e,i,s,r,n,a,l,h,d,c,p,u,f,m,y){const g=this.elements;return g[0]=t,g[4]=e,g[8]=i,g[12]=s,g[1]=r,g[5]=n,g[9]=a,g[13]=l,g[2]=h,g[6]=d,g[10]=c,g[14]=p,g[3]=u,g[7]=f,g[11]=m,g[15]=y,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new Zt().fromArray(this.elements)}copy(t){const e=this.elements,i=t.elements;return e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=i[3],e[4]=i[4],e[5]=i[5],e[6]=i[6],e[7]=i[7],e[8]=i[8],e[9]=i[9],e[10]=i[10],e[11]=i[11],e[12]=i[12],e[13]=i[13],e[14]=i[14],e[15]=i[15],this}copyPosition(t){const e=this.elements,i=t.elements;return e[12]=i[12],e[13]=i[13],e[14]=i[14],this}setFromMatrix3(t){const e=t.elements;return this.set(e[0],e[3],e[6],0,e[1],e[4],e[7],0,e[2],e[5],e[8],0,0,0,0,1),this}extractBasis(t,e,i){return t.setFromMatrixColumn(this,0),e.setFromMatrixColumn(this,1),i.setFromMatrixColumn(this,2),this}makeBasis(t,e,i){return this.set(t.x,e.x,i.x,0,t.y,e.y,i.y,0,t.z,e.z,i.z,0,0,0,0,1),this}extractRotation(t){const e=this.elements,i=t.elements,s=1/li.setFromMatrixColumn(t,0).length(),r=1/li.setFromMatrixColumn(t,1).length(),n=1/li.setFromMatrixColumn(t,2).length();return e[0]=i[0]*s,e[1]=i[1]*s,e[2]=i[2]*s,e[3]=0,e[4]=i[4]*r,e[5]=i[5]*r,e[6]=i[6]*r,e[7]=0,e[8]=i[8]*n,e[9]=i[9]*n,e[10]=i[10]*n,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromEuler(t){const e=this.elements,i=t.x,s=t.y,r=t.z,n=Math.cos(i),a=Math.sin(i),l=Math.cos(s),h=Math.sin(s),d=Math.cos(r),c=Math.sin(r);if(t.order==="XYZ"){const p=n*d,u=n*c,f=a*d,m=a*c;e[0]=l*d,e[4]=-l*c,e[8]=h,e[1]=u+f*h,e[5]=p-m*h,e[9]=-a*l,e[2]=m-p*h,e[6]=f+u*h,e[10]=n*l}else if(t.order==="YXZ"){const p=l*d,u=l*c,f=h*d,m=h*c;e[0]=p+m*a,e[4]=f*a-u,e[8]=n*h,e[1]=n*c,e[5]=n*d,e[9]=-a,e[2]=u*a-f,e[6]=m+p*a,e[10]=n*l}else if(t.order==="ZXY"){const p=l*d,u=l*c,f=h*d,m=h*c;e[0]=p-m*a,e[4]=-n*c,e[8]=f+u*a,e[1]=u+f*a,e[5]=n*d,e[9]=m-p*a,e[2]=-n*h,e[6]=a,e[10]=n*l}else if(t.order==="ZYX"){const p=n*d,u=n*c,f=a*d,m=a*c;e[0]=l*d,e[4]=f*h-u,e[8]=p*h+m,e[1]=l*c,e[5]=m*h+p,e[9]=u*h-f,e[2]=-h,e[6]=a*l,e[10]=n*l}else if(t.order==="YZX"){const p=n*l,u=n*h,f=a*l,m=a*h;e[0]=l*d,e[4]=m-p*c,e[8]=f*c+u,e[1]=c,e[5]=n*d,e[9]=-a*d,e[2]=-h*d,e[6]=u*c+f,e[10]=p-m*c}else if(t.order==="XZY"){const p=n*l,u=n*h,f=a*l,m=a*h;e[0]=l*d,e[4]=-c,e[8]=h*d,e[1]=p*c+m,e[5]=n*d,e[9]=u*c-f,e[2]=f*c-u,e[6]=a*d,e[10]=m*c+p}return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromQuaternion(t){return this.compose(Yc,t,qc)}lookAt(t,e,i){const s=this.elements;return Bt.subVectors(t,e),Bt.lengthSq()===0&&(Bt.z=1),Bt.normalize(),Ce.crossVectors(i,Bt),Ce.lengthSq()===0&&(Math.abs(i.z)===1?Bt.x+=1e-4:Bt.z+=1e-4,Bt.normalize(),Ce.crossVectors(i,Bt)),Ce.normalize(),Zs.crossVectors(Bt,Ce),s[0]=Ce.x,s[4]=Zs.x,s[8]=Bt.x,s[1]=Ce.y,s[5]=Zs.y,s[9]=Bt.y,s[2]=Ce.z,s[6]=Zs.z,s[10]=Bt.z,this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const i=t.elements,s=e.elements,r=this.elements,n=i[0],a=i[4],l=i[8],h=i[12],d=i[1],c=i[5],p=i[9],u=i[13],f=i[2],m=i[6],y=i[10],g=i[14],_=i[3],M=i[7],w=i[11],C=i[15],x=s[0],b=s[4],P=s[8],A=s[12],N=s[1],J=s[5],$=s[9],gt=s[13],Y=s[2],K=s[6],lt=s[10],st=s[14],ct=s[3],tt=s[7],dt=s[11],ut=s[15];return r[0]=n*x+a*N+l*Y+h*ct,r[4]=n*b+a*J+l*K+h*tt,r[8]=n*P+a*$+l*lt+h*dt,r[12]=n*A+a*gt+l*st+h*ut,r[1]=d*x+c*N+p*Y+u*ct,r[5]=d*b+c*J+p*K+u*tt,r[9]=d*P+c*$+p*lt+u*dt,r[13]=d*A+c*gt+p*st+u*ut,r[2]=f*x+m*N+y*Y+g*ct,r[6]=f*b+m*J+y*K+g*tt,r[10]=f*P+m*$+y*lt+g*dt,r[14]=f*A+m*gt+y*st+g*ut,r[3]=_*x+M*N+w*Y+C*ct,r[7]=_*b+M*J+w*K+C*tt,r[11]=_*P+M*$+w*lt+C*dt,r[15]=_*A+M*gt+w*st+C*ut,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[4]*=t,e[8]*=t,e[12]*=t,e[1]*=t,e[5]*=t,e[9]*=t,e[13]*=t,e[2]*=t,e[6]*=t,e[10]*=t,e[14]*=t,e[3]*=t,e[7]*=t,e[11]*=t,e[15]*=t,this}determinant(){const t=this.elements,e=t[0],i=t[4],s=t[8],r=t[12],n=t[1],a=t[5],l=t[9],h=t[13],d=t[2],c=t[6],p=t[10],u=t[14],f=t[3],m=t[7],y=t[11],g=t[15];return f*(+r*l*c-s*h*c-r*a*p+i*h*p+s*a*u-i*l*u)+m*(+e*l*u-e*h*p+r*n*p-s*n*u+s*h*d-r*l*d)+y*(+e*h*c-e*a*u-r*n*c+i*n*u+r*a*d-i*h*d)+g*(-s*a*d-e*l*c+e*a*p+s*n*c-i*n*p+i*l*d)}transpose(){const t=this.elements;let e;return e=t[1],t[1]=t[4],t[4]=e,e=t[2],t[2]=t[8],t[8]=e,e=t[6],t[6]=t[9],t[9]=e,e=t[3],t[3]=t[12],t[12]=e,e=t[7],t[7]=t[13],t[13]=e,e=t[11],t[11]=t[14],t[14]=e,this}setPosition(t,e,i){const s=this.elements;return t.isVector3?(s[12]=t.x,s[13]=t.y,s[14]=t.z):(s[12]=t,s[13]=e,s[14]=i),this}invert(){const t=this.elements,e=t[0],i=t[1],s=t[2],r=t[3],n=t[4],a=t[5],l=t[6],h=t[7],d=t[8],c=t[9],p=t[10],u=t[11],f=t[12],m=t[13],y=t[14],g=t[15],_=c*y*h-m*p*h+m*l*u-a*y*u-c*l*g+a*p*g,M=f*p*h-d*y*h-f*l*u+n*y*u+d*l*g-n*p*g,w=d*m*h-f*c*h+f*a*u-n*m*u-d*a*g+n*c*g,C=f*c*l-d*m*l-f*a*p+n*m*p+d*a*y-n*c*y,x=e*_+i*M+s*w+r*C;if(x===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const b=1/x;return t[0]=_*b,t[1]=(m*p*r-c*y*r-m*s*u+i*y*u+c*s*g-i*p*g)*b,t[2]=(a*y*r-m*l*r+m*s*h-i*y*h-a*s*g+i*l*g)*b,t[3]=(c*l*r-a*p*r-c*s*h+i*p*h+a*s*u-i*l*u)*b,t[4]=M*b,t[5]=(d*y*r-f*p*r+f*s*u-e*y*u-d*s*g+e*p*g)*b,t[6]=(f*l*r-n*y*r-f*s*h+e*y*h+n*s*g-e*l*g)*b,t[7]=(n*p*r-d*l*r+d*s*h-e*p*h-n*s*u+e*l*u)*b,t[8]=w*b,t[9]=(f*c*r-d*m*r-f*i*u+e*m*u+d*i*g-e*c*g)*b,t[10]=(n*m*r-f*a*r+f*i*h-e*m*h-n*i*g+e*a*g)*b,t[11]=(d*a*r-n*c*r-d*i*h+e*c*h+n*i*u-e*a*u)*b,t[12]=C*b,t[13]=(d*m*s-f*c*s+f*i*p-e*m*p-d*i*y+e*c*y)*b,t[14]=(f*a*s-n*m*s-f*i*l+e*m*l+n*i*y-e*a*y)*b,t[15]=(n*c*s-d*a*s+d*i*l-e*c*l-n*i*p+e*a*p)*b,this}scale(t){const e=this.elements,i=t.x,s=t.y,r=t.z;return e[0]*=i,e[4]*=s,e[8]*=r,e[1]*=i,e[5]*=s,e[9]*=r,e[2]*=i,e[6]*=s,e[10]*=r,e[3]*=i,e[7]*=s,e[11]*=r,this}getMaxScaleOnAxis(){const t=this.elements,e=t[0]*t[0]+t[1]*t[1]+t[2]*t[2],i=t[4]*t[4]+t[5]*t[5]+t[6]*t[6],s=t[8]*t[8]+t[9]*t[9]+t[10]*t[10];return Math.sqrt(Math.max(e,i,s))}makeTranslation(t,e,i){return t.isVector3?this.set(1,0,0,t.x,0,1,0,t.y,0,0,1,t.z,0,0,0,1):this.set(1,0,0,t,0,1,0,e,0,0,1,i,0,0,0,1),this}makeRotationX(t){const e=Math.cos(t),i=Math.sin(t);return this.set(1,0,0,0,0,e,-i,0,0,i,e,0,0,0,0,1),this}makeRotationY(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,0,i,0,0,1,0,0,-i,0,e,0,0,0,0,1),this}makeRotationZ(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,-i,0,0,i,e,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(t,e){const i=Math.cos(e),s=Math.sin(e),r=1-i,n=t.x,a=t.y,l=t.z,h=r*n,d=r*a;return this.set(h*n+i,h*a-s*l,h*l+s*a,0,h*a+s*l,d*a+i,d*l-s*n,0,h*l-s*a,d*l+s*n,r*l*l+i,0,0,0,0,1),this}makeScale(t,e,i){return this.set(t,0,0,0,0,e,0,0,0,0,i,0,0,0,0,1),this}makeShear(t,e,i,s,r,n){return this.set(1,i,r,0,t,1,n,0,e,s,1,0,0,0,0,1),this}compose(t,e,i){const s=this.elements,r=e._x,n=e._y,a=e._z,l=e._w,h=r+r,d=n+n,c=a+a,p=r*h,u=r*d,f=r*c,m=n*d,y=n*c,g=a*c,_=l*h,M=l*d,w=l*c,C=i.x,x=i.y,b=i.z;return s[0]=(1-(m+g))*C,s[1]=(u+w)*C,s[2]=(f-M)*C,s[3]=0,s[4]=(u-w)*x,s[5]=(1-(p+g))*x,s[6]=(y+_)*x,s[7]=0,s[8]=(f+M)*b,s[9]=(y-_)*b,s[10]=(1-(p+m))*b,s[11]=0,s[12]=t.x,s[13]=t.y,s[14]=t.z,s[15]=1,this}decompose(t,e,i){const s=this.elements;let r=li.set(s[0],s[1],s[2]).length();const n=li.set(s[4],s[5],s[6]).length(),a=li.set(s[8],s[9],s[10]).length();this.determinant()<0&&(r=-r),t.x=s[12],t.y=s[13],t.z=s[14],Gt.copy(this);const h=1/r,d=1/n,c=1/a;return Gt.elements[0]*=h,Gt.elements[1]*=h,Gt.elements[2]*=h,Gt.elements[4]*=d,Gt.elements[5]*=d,Gt.elements[6]*=d,Gt.elements[8]*=c,Gt.elements[9]*=c,Gt.elements[10]*=c,e.setFromRotationMatrix(Gt),i.x=r,i.y=n,i.z=a,this}makePerspective(t,e,i,s,r,n,a=qs){const l=this.elements,h=2*r/(e-t),d=2*r/(i-s),c=(e+t)/(e-t),p=(i+s)/(i-s);let u,f;if(a===qs)u=-(n+r)/(n-r),f=-2*n*r/(n-r);else if(a===zo)u=-n/(n-r),f=-n*r/(n-r);else throw new Error("Matrix4.makePerspective(): Invalid coordinate system: "+a);return l[0]=h,l[4]=0,l[8]=c,l[12]=0,l[1]=0,l[5]=d,l[9]=p,l[13]=0,l[2]=0,l[6]=0,l[10]=u,l[14]=f,l[3]=0,l[7]=0,l[11]=-1,l[15]=0,this}makeOrthographic(t,e,i,s,r,n,a=qs){const l=this.elements,h=1/(e-t),d=1/(i-s),c=1/(n-r),p=(e+t)*h,u=(i+s)*d;let f,m;if(a===qs)f=(n+r)*c,m=-2*c;else if(a===zo)f=r*c,m=-1*c;else throw new Error("../math.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);return l[0]=2*h,l[4]=0,l[8]=0,l[12]=-p,l[1]=0,l[5]=2*d,l[9]=0,l[13]=-u,l[2]=0,l[6]=0,l[10]=m,l[14]=-f,l[3]=0,l[7]=0,l[11]=0,l[15]=1,this}equals(t){const e=this.elements,i=t.elements;for(let s=0;s<16;s++)if(e[s]!==i[s])return!1;return!0}fromArray(t,e=0){for(let i=0;i<16;i++)this.elements[i]=t[i+e];return this}toArray(t=[],e=0){const i=this.elements;return t[e]=i[0],t[e+1]=i[1],t[e+2]=i[2],t[e+3]=i[3],t[e+4]=i[4],t[e+5]=i[5],t[e+6]=i[6],t[e+7]=i[7],t[e+8]=i[8],t[e+9]=i[9],t[e+10]=i[10],t[e+11]=i[11],t[e+12]=i[12],t[e+13]=i[13],t[e+14]=i[14],t[e+15]=i[15],t}}const li=new I,Gt=new Zt,Yc=new I(0,0,0),qc=new I(1,1,1),Ce=new I,Zs=new I,Bt=new I,Oo=new Zt,Io=new W;class Gi{constructor(t=0,e=0,i=0,s=Gi.DEFAULT_ORDER){this.isEuler=!0,this._x=t,this._y=e,this._z=i,this._order=s}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get order(){return this._order}set order(t){this._order=t,this._onChangeCallback()}set(t,e,i,s=this._order){return this._x=t,this._y=e,this._z=i,this._order=s,this._onChangeCallback(),this}clone(){return new Gi(this._x,this._y,this._z,this._order)}copy(t){return this._x=t._x,this._y=t._y,this._z=t._z,this._order=t._order,this._onChangeCallback(),this}setFromRotationMatrix(t,e=this._order,i=!0){const s=t.elements,r=s[0],n=s[4],a=s[8],l=s[1],h=s[5],d=s[9],c=s[2],p=s[6],u=s[10];switch(e){case"XYZ":this._y=Math.asin(ee(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-d,u),this._z=Math.atan2(-n,r)):(this._x=Math.atan2(p,h),this._z=0);break;case"YXZ":this._x=Math.asin(-ee(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(a,u),this._z=Math.atan2(l,h)):(this._y=Math.atan2(-c,r),this._z=0);break;case"ZXY":this._x=Math.asin(ee(p,-1,1)),Math.abs(p)<.9999999?(this._y=Math.atan2(-c,u),this._z=Math.atan2(-n,h)):(this._y=0,this._z=Math.atan2(l,r));break;case"ZYX":this._y=Math.asin(-ee(c,-1,1)),Math.abs(c)<.9999999?(this._x=Math.atan2(p,u),this._z=Math.atan2(l,r)):(this._x=0,this._z=Math.atan2(-n,h));break;case"YZX":this._z=Math.asin(ee(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(-d,h),this._y=Math.atan2(-c,r)):(this._x=0,this._y=Math.atan2(a,u));break;case"XZY":this._z=Math.asin(-ee(n,-1,1)),Math.abs(n)<.9999999?(this._x=Math.atan2(p,h),this._y=Math.atan2(a,r)):(this._x=Math.atan2(-d,u),this._y=0);break;default:console.warn("../math.Euler: .setFromRotationMatrix() encountered an unknown order: "+e)}return this._order=e,i===!0&&this._onChangeCallback(),this}setFromQuaternion(t,e,i){return Oo.makeRotationFromQuaternion(t),this.setFromRotationMatrix(Oo,e,i)}setFromVector3(t,e=this._order){return this.set(t.x,t.y,t.z,e)}reorder(t){return Io.setFromEuler(this),this.setFromQuaternion(Io,t)}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._order===this._order}fromArray(t){return this._x=t[0],this._y=t[1],this._z=t[2],t[3]!==void 0&&(this._order=t[3]),this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._order,t}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(t){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}Gi.DEFAULT_ORDER="XYZ";class gi{constructor(t=0,e=0){this.x=t,this.y=e}get width(){return this.x}set width(t){this.x=t}get height(){return this.y}set height(t){this.y=t}set(t,e){return this.x=t,this.y=e,this}setScalar(t){return this.x=t,this.y=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+t)}}clone(){return new gi(this.x,this.y)}copy(t){return this.x=t.x,this.y=t.y,this}add(t){return this.x+=t.x,this.y+=t.y,this}addScalar(t){return this.x+=t,this.y+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this}subScalar(t){return this.x-=t,this.y-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this}multiply(t){return this.x*=t.x,this.y*=t.y,this}multiplyScalar(t){return this.x*=t,this.y*=t,this}divide(t){return this.x/=t.x,this.y/=t.y,this}divideScalar(t){return this.multiplyScalar(1/t)}applyMatrix3(t){const e=this.x,i=this.y,s=t.elements;return this.x=s[0]*e+s[3]*i+s[6],this.y=s[1]*e+s[4]*i+s[7],this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this}clamp(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this}clampLength(t,e){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Math.max(t,Math.min(e,i)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(t){return this.x*t.x+this.y*t.y}cross(t){return this.x*t.y-this.y*t.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(e===0)return Math.PI/2;const i=this.dot(t)/e;return Math.acos(ee(i,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,i=this.y-t.y;return e*e+i*i}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this}lerpVectors(t,e,i){return this.x=t.x+(e.x-t.x)*i,this.y=t.y+(e.y-t.y)*i,this}equals(t){return t.x===this.x&&t.y===this.y}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t}rotateAround(t,e){const i=Math.cos(e),s=Math.sin(e),r=this.x-t.x,n=this.y-t.y;return this.x=r*i-n*s+t.x,this.y=r*s+n*i+t.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}gi.isVector2=!0;class Ht{constructor(t=0,e=0,i=0,s=1){Ht.prototype.isVector4=!0,this.x=t,this.y=e,this.z=i,this.w=s}get width(){return this.z}set width(t){this.z=t}get height(){return this.w}set height(t){this.w=t}set(t,e,i,s){return this.x=t,this.y=e,this.z=i,this.w=s,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this.w=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setW(t){return this.w=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;case 3:this.w=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+t)}}clone(){return new Ht(this.x,this.y,this.z,this.w)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this.w+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this.w=t.w+e.w,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this.w+=t.w*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this.w-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this.w=t.w-e.w,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this}applyMatrix4(t){const e=this.x,i=this.y,s=this.z,r=this.w,n=t.elements;return this.x=n[0]*e+n[4]*i+n[8]*s+n[12]*r,this.y=n[1]*e+n[5]*i+n[9]*s+n[13]*r,this.z=n[2]*e+n[6]*i+n[10]*s+n[14]*r,this.w=n[3]*e+n[7]*i+n[11]*s+n[15]*r,this}divideScalar(t){return this.multiplyScalar(1/t)}setAxisAngleFromQuaternion(t){this.w=2*Math.acos(t.w);const e=Math.sqrt(1-t.w*t.w);return e<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=t.x/e,this.y=t.y/e,this.z=t.z/e),this}setAxisAngleFromRotationMatrix(t){let e,i,s,r;const l=t.elements,h=l[0],d=l[4],c=l[8],p=l[1],u=l[5],f=l[9],m=l[2],y=l[6],g=l[10];if(Math.abs(d-p)<.01&&Math.abs(c-m)<.01&&Math.abs(f-y)<.01){if(Math.abs(d+p)<.1&&Math.abs(c+m)<.1&&Math.abs(f+y)<.1&&Math.abs(h+u+g-3)<.1)return this.set(1,0,0,0),this;e=Math.PI;const M=(h+1)/2,w=(u+1)/2,C=(g+1)/2,x=(d+p)/4,b=(c+m)/4,P=(f+y)/4;return M>w&&M>C?M<.01?(i=0,s=.707106781,r=.707106781):(i=Math.sqrt(M),s=x/i,r=b/i):w>C?w<.01?(i=.707106781,s=0,r=.707106781):(s=Math.sqrt(w),i=x/s,r=P/s):C<.01?(i=.707106781,s=.707106781,r=0):(r=Math.sqrt(C),i=b/r,s=P/r),this.set(i,s,r,e),this}let _=Math.sqrt((y-f)*(y-f)+(c-m)*(c-m)+(p-d)*(p-d));return Math.abs(_)<.001&&(_=1),this.x=(y-f)/_,this.y=(c-m)/_,this.z=(p-d)/_,this.w=Math.acos((h+u+g-1)/2),this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this.w=Math.min(this.w,t.w),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this.w=Math.max(this.w,t.w),this}clamp(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this.z=Math.max(t.z,Math.min(e.z,this.z)),this.w=Math.max(t.w,Math.min(e.w,this.w)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this.z=Math.max(t,Math.min(e,this.z)),this.w=Math.max(t,Math.min(e,this.w)),this}clampLength(t,e){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Math.max(t,Math.min(e,i)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z+this.w*t.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this.w+=(t.w-this.w)*e,this}lerpVectors(t,e,i){return this.x=t.x+(e.x-t.x)*i,this.y=t.y+(e.y-t.y)*i,this.z=t.z+(e.z-t.z)*i,this.w=t.w+(e.w-t.w)*i,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z&&t.w===this.w}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this.w=t[e+3],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t[e+3]=this.w,t}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class se{constructor(t,e,i,s,r,n,a,l,h){se.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],t!==void 0&&this.set(t,e,i,s,r,n,a,l,h)}set(t,e,i,s,r,n,a,l,h){const d=this.elements;return d[0]=t,d[1]=s,d[2]=a,d[3]=e,d[4]=r,d[5]=l,d[6]=i,d[7]=n,d[8]=h,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(t){const e=this.elements,i=t.elements;return e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=i[3],e[4]=i[4],e[5]=i[5],e[6]=i[6],e[7]=i[7],e[8]=i[8],this}extractBasis(t,e,i){return t.setFromMatrix3Column(this,0),e.setFromMatrix3Column(this,1),i.setFromMatrix3Column(this,2),this}setFromMatrix4(t){const e=t.elements;return this.set(e[0],e[4],e[8],e[1],e[5],e[9],e[2],e[6],e[10]),this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const i=t.elements,s=e.elements,r=this.elements,n=i[0],a=i[3],l=i[6],h=i[1],d=i[4],c=i[7],p=i[2],u=i[5],f=i[8],m=s[0],y=s[3],g=s[6],_=s[1],M=s[4],w=s[7],C=s[2],x=s[5],b=s[8];return r[0]=n*m+a*_+l*C,r[3]=n*y+a*M+l*x,r[6]=n*g+a*w+l*b,r[1]=h*m+d*_+c*C,r[4]=h*y+d*M+c*x,r[7]=h*g+d*w+c*b,r[2]=p*m+u*_+f*C,r[5]=p*y+u*M+f*x,r[8]=p*g+u*w+f*b,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[3]*=t,e[6]*=t,e[1]*=t,e[4]*=t,e[7]*=t,e[2]*=t,e[5]*=t,e[8]*=t,this}determinant(){const t=this.elements,e=t[0],i=t[1],s=t[2],r=t[3],n=t[4],a=t[5],l=t[6],h=t[7],d=t[8];return e*n*d-e*a*h-i*r*d+i*a*l+s*r*h-s*n*l}invert(){const t=this.elements,e=t[0],i=t[1],s=t[2],r=t[3],n=t[4],a=t[5],l=t[6],h=t[7],d=t[8],c=d*n-a*h,p=a*l-d*r,u=h*r-n*l,f=e*c+i*p+s*u;if(f===0)return this.set(0,0,0,0,0,0,0,0,0);const m=1/f;return t[0]=c*m,t[1]=(s*h-d*i)*m,t[2]=(a*i-s*n)*m,t[3]=p*m,t[4]=(d*e-s*l)*m,t[5]=(s*r-a*e)*m,t[6]=u*m,t[7]=(i*l-h*e)*m,t[8]=(n*e-i*r)*m,this}transpose(){let t;const e=this.elements;return t=e[1],e[1]=e[3],e[3]=t,t=e[2],e[2]=e[6],e[6]=t,t=e[5],e[5]=e[7],e[7]=t,this}getNormalMatrix(t){return this.setFromMatrix4(t).invert().transpose()}transposeIntoArray(t){const e=this.elements;return t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8],this}setUvTransform(t,e,i,s,r,n,a){const l=Math.cos(r),h=Math.sin(r);return this.set(i*l,i*h,-i*(l*n+h*a)+n+t,-s*h,s*l,-s*(-h*n+l*a)+a+e,0,0,1),this}scale(t,e){return this.premultiply(Ur.makeScale(t,e)),this}rotate(t){return this.premultiply(Ur.makeRotation(-t)),this}translate(t,e){return this.premultiply(Ur.makeTranslation(t,e)),this}makeTranslation(t,e){return t.isVector2?this.set(1,0,t.x,0,1,t.y,0,0,1):this.set(1,0,t,0,1,e,0,0,1),this}makeRotation(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,-i,0,i,e,0,0,0,1),this}makeScale(t,e){return this.set(t,0,0,0,e,0,0,0,1),this}equals(t){const e=this.elements,i=t.elements;for(let s=0;s<9;s++)if(e[s]!==i[s])return!1;return!0}fromArray(t,e=0){for(let i=0;i<9;i++)this.elements[i]=t[i+e];return this}toArray(t=[],e=0){const i=this.elements;return t[e]=i[0],t[e+1]=i[1],t[e+2]=i[2],t[e+3]=i[3],t[e+4]=i[4],t[e+5]=i[5],t[e+6]=i[6],t[e+7]=i[7],t[e+8]=i[8],t}clone(){return new se().fromArray(this.elements)}}const Ur=new se;var zt;(function(o){o[o.Random=0]="Random",o[o.Loop=1]="Loop",o[o.PingPong=2]="PingPong",o[o.Burst=3]="Burst"})(zt||(zt={}));function bi(o,t,e,i){let s;switch(zt.Random===o?t=Math.random():zt.Burst===o&&i.isBursting&&(t=i.burstParticleIndex/i.burstParticleCount),e>0?s=Math.floor(t/e)*e:s=t,o){case zt.Loop:s=s%1;break;case zt.PingPong:s=Math.abs(s%2-1);break}return s}class je{constructor(t,e,i,s){this.p=[t,e,i,s]}genValue(t){const e=t*t,i=t*t*t,s=1-t,r=s*s,n=r*s;return this.p[0]*n+this.p[1]*r*t*3+this.p[2]*s*e*3+this.p[3]*i}derivativeCoefficients(t){const e=[];for(let i=t,s=i.length-1;s>0;s--){const r=[];for(let n=0;n<s;n++){const a=s*(i[n+1]-i[n]);r.push(a)}e.push(r),i=r}return e}getSlope(t){const e=this.derivativeCoefficients(this.p)[0],i=1-t,s=i*i,r=i*t*2,n=t*t;return s*e[0]+r*e[1]+n*e[2]}controlCurve(t,e){this.p[1]=t/3+this.p[0],this.p[2]=this.p[3]-e/3}hull(t){let e=this.p,i=[],s,r=0,n=0,a=0;const l=[];for(l[r++]=e[0],l[r++]=e[1],l[r++]=e[2],l[r++]=e[3];e.length>1;){for(i=[],n=0,a=e.length-1;n<a;n++)s=t*e[n]+(1-t)*e[n+1],l[r++]=s,i.push(s);e=i}return l}split(t){const e=this.hull(t);return{left:new je(e[0],e[4],e[7],e[9]),right:new je(e[9],e[8],e[6],e[3]),span:e}}clone(){return new je(this.p[0],this.p[1],this.p[2],this.p[3])}toJSON(){return{p0:this.p[0],p1:this.p[1],p2:this.p[2],p3:this.p[3]}}static fromJSON(t){return new je(t.p0,t.p1,t.p2,t.p3)}}const Xi=o=>({r:o.x,g:o.y,b:o.z,a:o.w}),Wi=o=>new Ht(o.r,o.g,o.b,o.a),Zc=(o,t)=>{switch(t){case"Vector3":return new I(o.x,o.y,o.z);case"Vector4":return new Ht(o.x,o.y,o.z,o.w);case"Color":return new I(o.r,o.g,o.b);case"Number":return o;default:return o}},Qc=(o,t)=>{switch(t){case"Vector3":return{x:o.x,y:o.y,z:o.z};case"Vector4":return{x:o.x,y:o.y,z:o.z,w:o.w};case"Color":return{r:o.x,g:o.y,b:o.z};case"Number":return o;default:return o}};class ar{constructor(t,e){this.a=t,this.b=e,this.type="value"}startGen(t){}genColor(t,e){const i=Math.random();return e.copy(this.a).lerp(this.b,i)}toJSON(){return{type:"RandomColor",a:Xi(this.a),b:Xi(this.b)}}static fromJSON(t){return new ar(Wi(t.a),Wi(t.b))}clone(){return new ar(this.a.clone(),this.b.clone())}}class yi{constructor(t,e){this.a=t,this.b=e,this.indexCount=-1,this.type="value"}startGen(t){this.indexCount=t.length,t.push(Math.random())}genColor(t,e){return this.indexCount===-1&&this.startGen(t),e.copy(this.a).lerp(this.b,t[this.indexCount])}toJSON(){return{type:"ColorRange",a:Xi(this.a),b:Xi(this.b)}}static fromJSON(t){return new yi(Wi(t.a),Wi(t.b))}clone(){return new yi(this.a.clone(),this.b.clone())}}class Oe{constructor(t,e){this.subType=e,this.type="function",this.keys=t}findKey(t){let e=0,i=0,s=this.keys.length-1;for(;i+1<s;)if(e=Math.floor((i+s)/2),t<this.getStartX(e))s=e-1;else if(t>this.getEndX(e))i=e+1;else return e;for(let r=i;r<=s;r++)if(t>=this.getStartX(r)&&t<=this.getEndX(r))return r;return-1}getStartX(t){return this.keys[t][1]}getEndX(t){return t+1<this.keys.length?this.keys[t+1][1]:1}genValue(t,e){const i=this.findKey(e);return this.subType==="Number"?i===-1?this.keys[0][0]:i+1>=this.keys.length?this.keys[this.keys.length-1][0]:(this.keys[i+1][0]-this.keys[i][0])*((e-this.getStartX(i))/(this.getEndX(i)-this.getStartX(i)))+this.keys[i][0]:i===-1?t.copy(this.keys[0][0]):i+1>=this.keys.length?t.copy(this.keys[this.keys.length-1][0]):t.copy(this.keys[i][0]).lerp(this.keys[i+1][0],(e-this.getStartX(i))/(this.getEndX(i)-this.getStartX(i)))}toJSON(){return this.keys[0][0].constructor.name,{type:"CLinearFunction",subType:this.subType,keys:this.keys.map(([t,e])=>({value:Qc(t,this.subType),pos:e}))}}static fromJSON(t){return new Oe(t.keys.map(e=>[Zc(e.value,t.subType),e.pos]),t.subType)}clone(){return this.subType==="Number"?new Oe(this.keys.map(([t,e])=>[t,e]),this.subType):new Oe(this.keys.map(([t,e])=>[t.clone(),e]),this.subType)}}const Qs=new I;class Ge{constructor(t=[[new I(0,0,0),0],[new I(1,1,1),0]],e=[[1,0],[1,1]]){this.type="function",this.color=new Oe(t,"Color"),this.alpha=new Oe(e,"Number")}genColor(t,e,i){return this.color.genValue(Qs,i),e.set(Qs.x,Qs.y,Qs.z,this.alpha.genValue(1,i))}toJSON(){return{type:"Gradient",color:this.color.toJSON(),alpha:this.alpha.toJSON()}}static fromJSON(t){if(t.functions){const e=t.functions.map(i=>[yi.fromJSON(i.function).a,i.start]);return t.functions.length>0&&e.push([yi.fromJSON(t.functions[t.functions.length-1].function).b,1]),new Ge(e.map(i=>[new I(i[0].x,i[0].y,i[0].z),i[1]]),e.map(i=>[i[0].w,i[1]]))}else{const e=new Ge;return e.alpha=Oe.fromJSON(t.alpha),e.color=Oe.fromJSON(t.color),e}}clone(){const t=new Ge;return t.alpha=this.alpha.clone(),t.color=this.color.clone(),t}startGen(t){}}const Vr=new Ht;class lr{constructor(t,e){this.indexCount=0,this.type="function",this.gradient1=t,this.gradient2=e}startGen(t){this.indexCount=t.length,t.push(Math.random())}genColor(t,e,i){return this.gradient1.genColor(t,e,i),this.gradient2.genColor(t,Vr,i),t&&t[this.indexCount]!==void 0?e.lerp(Vr,t[this.indexCount]):e.lerp(Vr,Math.random()),e}toJSON(){return{type:"RandomColorBetweenGradient",gradient1:this.gradient1.toJSON(),gradient2:this.gradient2.toJSON()}}static fromJSON(t){return new lr(Ge.fromJSON(t.gradient1),Ge.fromJSON(t.gradient2))}clone(){return new lr(this.gradient1.clone(),this.gradient2.clone())}}class _i{constructor(t){this.color=t,this.type="value"}startGen(t){}genColor(t,e){return e.copy(this.color)}toJSON(){return{type:"ConstantColor",color:Xi(this.color)}}static fromJSON(t){return new _i(Wi(t.color))}clone(){return new _i(this.color.clone())}}function On(o){switch(o.type){case"ConstantColor":return _i.fromJSON(o);case"ColorRange":return yi.fromJSON(o);case"RandomColor":return ar.fromJSON(o);case"Gradient":return Ge.fromJSON(o);case"RandomColorBetweenGradient":return lr.fromJSON(o);default:return new _i(new Ht(1,1,1,1))}}class Q{constructor(t){this.value=t,this.type="value"}startGen(t){}genValue(t){return this.value}toJSON(){return{type:"ConstantValue",value:this.value}}static fromJSON(t){return new Q(t.value)}clone(){return new Q(this.value)}}class Ye{constructor(t,e){this.a=t,this.b=e,this.indexCount=-1,this.type="value"}startGen(t){this.indexCount=t.length,t.push(Math.random())}genValue(t){return this.indexCount===-1&&this.startGen(t),Si.lerp(this.a,this.b,t[this.indexCount])}toJSON(){return{type:"IntervalValue",a:this.a,b:this.b}}static fromJSON(t){return new Ye(t.a,t.b)}clone(){return new Ye(this.a,this.b)}}class $c{constructor(){this.functions=new Array}findFunction(t){let e=0,i=0,s=this.functions.length-1;for(;i+1<s;)if(e=Math.floor((i+s)/2),t<this.getStartX(e))s=e-1;else if(t>this.getEndX(e))i=e+1;else return e;for(let r=i;r<=s;r++)if(t>=this.functions[r][1]&&t<=this.getEndX(r))return r;return-1}getStartX(t){return this.functions[t][1]}setStartX(t,e){t>0&&(this.functions[t][1]=e)}getEndX(t){return t+1<this.functions.length?this.functions[t+1][1]:1}setEndX(t,e){t+1<this.functions.length&&(this.functions[t+1][1]=e)}insertFunction(t,e){const i=this.findFunction(t);this.functions.splice(i+1,0,[e,t])}removeFunction(t){return this.functions.splice(t,1)[0][0]}getFunction(t){return this.functions[t][0]}setFunction(t,e){this.functions[t][0]=e}get numOfFunctions(){return this.functions.length}}class Ji extends $c{constructor(t=[[new je(0,1/3,1/3*2,1),0]]){super(),this.type="function",this.functions=t}genValue(t,e=0){const i=this.findFunction(e);return i===-1?0:this.functions[i][0].genValue((e-this.getStartX(i))/(this.getEndX(i)-this.getStartX(i)))}toSVG(t,e){if(e<1)return"";let i=["M",0,this.functions[0][0].p[0]].join(" ");for(let s=1/e;s<=1;s+=1/e)i=[i,"L",s*t,this.genValue(void 0,s)].join(" ");return i}toJSON(){return{type:"PiecewiseBezier",functions:this.functions.map(([t,e])=>({function:t.toJSON(),start:e}))}}static fromJSON(t){return new Ji(t.functions.map(e=>[je.fromJSON(e.function),e.start]))}clone(){return new Ji(this.functions.map(([t,e])=>[t.clone(),e]))}startGen(t){}}function L(o){switch(o.type){case"ConstantValue":return Q.fromJSON(o);case"IntervalValue":return Ye.fromJSON(o);case"PiecewiseBezier":return Ji.fromJSON(o);default:return new Q(0)}}class Yi{constructor(){this.indexCount=0,this.type="rotation"}startGen(t){this.indexCount=t.length,t.push(new W);let e,i,s,r,n,a;do e=Math.random()*2-1,i=Math.random()*2-1,s=e*e+i*i;while(s>1);do r=Math.random()*2-1,n=Math.random()*2-1,a=r*r+n*n;while(a>1);const l=Math.sqrt((1-s)/a);t[this.indexCount].set(e,i,l*r,l*n)}genValue(t,e,i,s){return this.indexCount===-1&&this.startGen(t),e.copy(t[this.indexCount]),e}toJSON(){return{type:"RandomQuat"}}static fromJSON(t){return new Yi}clone(){return new Yi}}class qi{constructor(t,e){this.axis=t,this.angle=e,this.type="rotation"}startGen(t){this.angle.startGen(t)}genValue(t,e,i,s){return e.setFromAxisAngle(this.axis,this.angle.genValue(t,s)*i)}toJSON(){return{type:"AxisAngle",axis:{x:this.axis.x,y:this.axis.y,z:this.axis.z},angle:this.angle.toJSON()}}static fromJSON(t){return new qi(new I(t.axis.x,t.axis.y,t.axis.z),L(t.angle))}clone(){return new qi(this.axis.clone(),this.angle.clone())}}class hr{constructor(t,e,i,s){this.angleX=t,this.angleY=e,this.angleZ=i,this.type="rotation",this.eular=new Gi(0,0,0,s)}startGen(t){this.angleX.startGen(t),this.angleY.startGen(t),this.angleZ.startGen(t)}genValue(t,e,i,s){return this.eular.set(this.angleX.genValue(t,s)*i,this.angleY.genValue(t,s)*i,this.angleZ.genValue(t,s)*i),e.setFromEuler(this.eular)}toJSON(){return{type:"Euler",angleX:this.angleX.toJSON(),angleY:this.angleY.toJSON(),angleZ:this.angleZ.toJSON(),eulerOrder:this.eular.order}}static fromJSON(t){return new hr(L(t.angleX),L(t.angleY),L(t.angleZ),t.eulerOrder)}clone(){return new hr(this.angleX,this.angleY,this.angleZ,this.eular.order)}}function Ba(o){switch(o.type){case"AxisAngle":return qi.fromJSON(o);case"Euler":return hr.fromJSON(o);case"RandomQuat":return Yi.fromJSON(o);default:return new Yi}}class qe{constructor(t,e,i){this.x=t,this.y=e,this.z=i,this.type="vec3function"}startGen(t){this.x.startGen(t),this.y.startGen(t),this.z.startGen(t)}genValue(t,e,i){return e.set(this.x.genValue(t,i),this.y.genValue(t,i),this.z.genValue(t,i))}toJSON(){return{type:"Vector3Function",x:this.x.toJSON(),y:this.y.toJSON(),z:this.z.toJSON()}}static fromJSON(t){return new qe(L(t.x),L(t.y),L(t.z))}clone(){return new qe(this.x,this.y,this.z)}}function Kc(o){switch(o.type){case"Vector3Function":return qe.fromJSON(o);default:return new qe(new Q(0),new Q(0),new Q(0))}}function cr(o){switch(o.type){case"ConstantValue":case"IntervalValue":case"PiecewiseBezier":return L(o);case"AxisAngle":case"RandomQuat":case"Euler":return Ba(o);case"Vector3Function":return Kc(o);default:return new Q(0)}}class Zi{constructor(t={}){this.type="cone",this.currentValue=0,this.radius=t.radius??10,this.arc=t.arc??2*Math.PI,this.thickness=t.thickness??1,this.angle=t.angle??Math.PI/6,this.mode=t.mode??zt.Random,this.spread=t.spread??0,this.speed=t.speed??new Q(1),this.memory=[]}update(t,e){zt.Random!=this.mode&&(this.currentValue+=this.speed.genValue(this.memory,t.emissionState.time/t.duration)*e)}initialize(t,e){const i=bi(this.mode,this.currentValue,this.spread,e),s=Si.lerp(1-this.thickness,1,Math.random()),r=i*this.arc,n=Math.sqrt(s),a=Math.sin(r),l=Math.cos(r);t.position.x=n*l,t.position.y=n*a,t.position.z=0;const h=this.angle*n;t.velocity.set(0,0,Math.cos(h)).addScaledVector(t.position,Math.sin(h)).multiplyScalar(t.startSpeed),t.position.multiplyScalar(this.radius)}toJSON(){return{type:"cone",radius:this.radius,arc:this.arc,thickness:this.thickness,angle:this.angle,mode:this.mode,spread:this.spread,speed:this.speed.toJSON()}}static fromJSON(t){return new Zi({radius:t.radius,arc:t.arc,thickness:t.thickness,angle:t.angle,mode:t.mode,speed:t.speed?L(t.speed):void 0,spread:t.spread})}clone(){return new Zi({radius:this.radius,arc:this.arc,thickness:this.thickness,angle:this.angle,mode:this.mode,speed:this.speed.clone(),spread:this.spread})}}class Qi{constructor(t={}){this.type="circle",this.currentValue=0,this.radius=t.radius??10,this.arc=t.arc??2*Math.PI,this.thickness=t.thickness??1,this.mode=t.mode??zt.Random,this.spread=t.spread??0,this.speed=t.speed??new Q(1),this.memory=[]}update(t,e){this.currentValue+=this.speed.genValue(this.memory,t.emissionState.time/t.duration)*e}initialize(t,e){const i=bi(this.mode,this.currentValue,this.spread,e),s=Si.lerp(1-this.thickness,1,Math.random()),r=i*this.arc;t.position.x=Math.cos(r),t.position.y=Math.sin(r),t.position.z=0,t.velocity.copy(t.position).multiplyScalar(t.startSpeed),t.position.multiplyScalar(this.radius*s)}toJSON(){return{type:"circle",radius:this.radius,arc:this.arc,thickness:this.thickness,mode:this.mode,spread:this.spread,speed:this.speed.toJSON()}}static fromJSON(t){return new Qi({radius:t.radius,arc:t.arc,thickness:t.thickness,mode:t.mode,speed:t.speed?L(t.speed):void 0,spread:t.spread})}clone(){return new Qi({radius:this.radius,arc:this.arc,thickness:this.thickness,mode:this.mode,speed:this.speed.clone(),spread:this.spread})}}function $s(o,t){return Math.floor(Math.random()*(t-o))+o}const Ps=new I(0,1,0),As=new I(0,0,0),td=new I(1,1,1),Ro=new I(0,0,1);class $i{constructor(t={}){this.type="donut",this.currentValue=0,this.radius=t.radius??10,this.arc=t.arc??2*Math.PI,this.thickness=t.thickness??1,this.donutRadius=t.donutRadius??this.radius*.2,this.mode=t.mode??zt.Random,this.spread=t.spread??0,this.speed=t.speed??new Q(1),this.memory=[],this._m1=new Zt}update(t,e){zt.Random!=this.mode&&(this.currentValue+=this.speed.genValue(this.memory,t.emissionState.time/t.duration)*e)}initialize(t,e){const i=bi(this.mode,this.currentValue,this.spread,e),s=Math.random(),r=Si.lerp(1-this.thickness,1,Math.random()),n=i*this.arc,a=s*Math.PI*2,l=Math.sin(n),h=Math.cos(n);t.position.x=this.radius*h,t.position.y=this.radius*l,t.position.z=0,t.velocity.z=this.donutRadius*r*Math.sin(a),t.velocity.x=this.donutRadius*r*Math.cos(a)*h,t.velocity.y=this.donutRadius*r*Math.cos(a)*l,t.position.add(t.velocity),t.velocity.normalize().multiplyScalar(t.startSpeed),t.rotation instanceof W&&(this._m1.lookAt(As,t.velocity,Ps),t.rotation.setFromRotationMatrix(this._m1))}toJSON(){return{type:"donut",radius:this.radius,arc:this.arc,thickness:this.thickness,donutRadius:this.donutRadius,mode:this.mode,spread:this.spread,speed:this.speed.toJSON()}}static fromJSON(t){return new $i({radius:t.radius,arc:t.arc,thickness:t.thickness,donutRadius:t.donutRadius,mode:t.mode,speed:t.speed?L(t.speed):void 0,spread:t.spread})}clone(){return new $i({radius:this.radius,arc:this.arc,thickness:this.thickness,donutRadius:this.donutRadius,mode:this.mode,speed:this.speed.clone(),spread:this.spread})}}class Ki{constructor(){this.type="point",this._m1=new Zt}update(t,e){}initialize(t){const e=Math.random(),i=Math.random(),s=e*Math.PI*2,r=Math.acos(2*i-1),n=Math.cbrt(Math.random()),a=Math.sin(s),l=Math.cos(s),h=Math.sin(r),d=Math.cos(r);t.velocity.x=n*h*l,t.velocity.y=n*h*a,t.velocity.z=n*d,t.velocity.multiplyScalar(t.startSpeed),t.position.setScalar(0),t.rotation instanceof W&&(this._m1.lookAt(As,t.position,Ps),t.rotation.setFromRotationMatrix(this._m1))}toJSON(){return{type:"point"}}static fromJSON(t){return new Ki}clone(){return new Ki}}class vi{constructor(t={}){this.type="sphere",this.currentValue=0,this.radius=t.radius??10,this.arc=t.arc??2*Math.PI,this.thickness=t.thickness??1,this.mode=t.mode??zt.Random,this.spread=t.spread??0,this.speed=t.speed??new Q(1),this.memory=[],this._m1=new Zt}update(t,e){zt.Random!=this.mode&&(this.currentValue+=this.speed.genValue(this.memory,t.emissionState.time/t.duration)*e)}initialize(t,e){const i=bi(this.mode,this.currentValue,this.spread,e),s=Math.random(),r=Si.lerp(1-this.thickness,1,Math.random()),n=i*this.arc,a=Math.acos(2*s-1),l=Math.sin(n),h=Math.cos(n),d=Math.sin(a),c=Math.cos(a);t.position.x=d*h,t.position.y=d*l,t.position.z=c,t.velocity.copy(t.position).multiplyScalar(t.startSpeed),t.position.multiplyScalar(this.radius*r),t.rotation instanceof W&&(this._m1.lookAt(As,t.position,Ps),t.rotation.setFromRotationMatrix(this._m1))}toJSON(){return{type:"sphere",radius:this.radius,arc:this.arc,thickness:this.thickness,mode:this.mode,spread:this.spread,speed:this.speed.toJSON()}}static fromJSON(t){return new vi({radius:t.radius,arc:t.arc,thickness:t.thickness,mode:t.mode,speed:t.speed?L(t.speed):void 0,spread:t.spread})}clone(){return new vi({radius:this.radius,arc:this.arc,thickness:this.thickness,mode:this.mode,speed:this.speed.clone(),spread:this.spread})}}class ts{constructor(t={}){this.type="hemisphere",this.currentValue=0,this.radius=t.radius??10,this.arc=t.arc??2*Math.PI,this.thickness=t.thickness??1,this.mode=t.mode??zt.Random,this.spread=t.spread??0,this.speed=t.speed??new Q(1),this.memory=[],this._m1=new Zt}update(t,e){zt.Random!=this.mode&&(this.currentValue+=this.speed.genValue(this.memory,t.emissionState.time/t.duration)*e)}initialize(t,e){const i=bi(this.mode,this.currentValue,this.spread,e),s=Math.random(),r=Si.lerp(1-this.thickness,1,Math.random()),n=i*this.arc,a=Math.acos(s),l=Math.sin(n),h=Math.cos(n),d=Math.sin(a),c=Math.cos(a);t.position.x=d*h,t.position.y=d*l,t.position.z=c,t.velocity.copy(t.position).multiplyScalar(t.startSpeed),t.position.multiplyScalar(this.radius*r),t.rotation instanceof W&&(this._m1.lookAt(As,t.position,Ps),t.rotation.setFromRotationMatrix(this._m1))}toJSON(){return{type:"hemisphere",radius:this.radius,arc:this.arc,thickness:this.thickness,mode:this.mode,spread:this.spread,speed:this.speed.toJSON()}}static fromJSON(t){return new ts({radius:t.radius,arc:t.arc,thickness:t.thickness,mode:t.mode,speed:t.speed?L(t.speed):void 0,spread:t.spread})}clone(){return new ts({radius:this.radius,arc:this.arc,thickness:this.thickness,mode:this.mode,speed:this.speed.clone(),spread:this.spread})}}class es{constructor(t={}){this.type="grid",this.width=t.width??1,this.height=t.height??1,this.column=t.column??10,this.row=t.row??10}initialize(t){const e=Math.floor(Math.random()*this.row),i=Math.floor(Math.random()*this.column);t.position.x=i*this.width/this.column-this.width/2,t.position.y=e*this.height/this.row-this.height/2,t.position.z=0,t.velocity.set(0,0,t.startSpeed)}toJSON(){return{type:"grid",width:this.width,height:this.height,column:this.column,row:this.row}}static fromJSON(t){return new es(t)}clone(){return new es({width:this.width,height:this.height,column:this.column,row:this.row})}update(t,e){}}class is{constructor(t={}){this.type="rectangle",this.currentValue=0,this.width=t.width??10,this.height=t.height??10,this.thickness=t.thickness??1,this.mode=t.mode??zt.Random,this.spread=t.spread??0,this.speed=t.speed??new Q(1),this.memory=[],this._m1=new Zt}update(t,e){this.currentValue+=this.speed.genValue(this.memory,t.emissionState.time/t.duration)*e}initialize(t,e){const i=bi(this.mode,this.currentValue,this.spread,e),s=2*(this.width+this.height),r=i*s;let n,a;r<this.width?(n=r-this.width/2,a=-this.height/2):r<this.width+this.height?(n=this.width/2,a=r-this.width-this.height/2):r<2*this.width+this.height?(n=this.width/2-(r-this.width-this.height),a=this.height/2):(n=-this.width/2,a=this.height/2-(r-2*this.width-this.height));const l=Math.random(),h=1-this.thickness*l;t.position.x=n*h,t.position.y=a*h,t.position.z=0,t.velocity.x=n,t.velocity.y=a,t.velocity.z=0,t.velocity.normalize().multiplyScalar(t.startSpeed),t.rotation instanceof W&&(this._m1.lookAt(As,t.velocity,Ps),t.rotation.setFromRotationMatrix(this._m1))}toJSON(){return{type:"rectangle",width:this.width,height:this.height,thickness:this.thickness,mode:this.mode,spread:this.spread,speed:this.speed.toJSON()}}static fromJSON(t){return new is({width:t.width,height:t.height,thickness:t.thickness,mode:t.mode,speed:t.speed?L(t.speed):void 0,spread:t.spread})}clone(){return new is({width:this.width,height:this.height,thickness:this.thickness,mode:this.mode,speed:this.speed.clone(),spread:this.spread})}}const gn={circle:{type:"circle",params:[["radius",["number"]],["arc",["radian"]],["thickness",["number"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]]],constructor:Qi,loadJSON:Qi.fromJSON},cone:{type:"cone",params:[["radius",["number"]],["arc",["radian"]],["thickness",["number"]],["angle",["radian"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]]],constructor:Zi,loadJSON:Zi.fromJSON},donut:{type:"donut",params:[["radius",["number"]],["arc",["radian"]],["thickness",["number"]],["donutRadius",["number"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]]],constructor:$i,loadJSON:$i.fromJSON},point:{type:"point",params:[],constructor:Ki,loadJSON:Ki.fromJSON},sphere:{type:"sphere",params:[["radius",["number"]],["arc",["radian"]],["thickness",["number"]],["angle",["radian"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]]],constructor:vi,loadJSON:vi.fromJSON},hemisphere:{type:"hemisphere",params:[["radius",["number"]],["arc",["radian"]],["thickness",["number"]],["angle",["radian"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]]],constructor:ts,loadJSON:ts.fromJSON},grid:{type:"grid",params:[["width",["number"]],["height",["number"]],["rows",["number"]],["column",["number"]]],constructor:es,loadJSON:es.fromJSON},rectangle:{type:"rectangle",params:[["width",["number"]],["height",["number"]],["thickness",["number"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]]],constructor:is,loadJSON:is.fromJSON}};function ed(o,t){return gn[o.type].loadJSON(o,t)}class ss{constructor(t){this.color=t,this.type="ColorOverLife"}initialize(t){this.color.startGen(t.memory)}update(t,e){this.color.genColor(t.memory,t.color,t.age/t.life),t.color.x*=t.startColor.x,t.color.y*=t.startColor.y,t.color.z*=t.startColor.z,t.color.w*=t.startColor.w}frameUpdate(t){}toJSON(){return{type:this.type,color:this.color.toJSON()}}static fromJSON(t){return new ss(On(t.color))}clone(){return new ss(this.color.clone())}reset(){}}class rs{constructor(t){this.angularVelocity=t,this.type="RotationOverLife"}initialize(t){typeof t.rotation=="number"&&this.angularVelocity.startGen(t.memory)}update(t,e){typeof t.rotation=="number"&&(t.rotation+=e*this.angularVelocity.genValue(t.memory,t.age/t.life))}toJSON(){return{type:this.type,angularVelocity:this.angularVelocity.toJSON()}}static fromJSON(t){return new rs(L(t.angularVelocity))}frameUpdate(t){}clone(){return new rs(this.angularVelocity.clone())}reset(){}}class ns{constructor(t){this.angularVelocity=t,this.type="Rotation3DOverLife",this.tempQuat=new W,this.tempQuat2=new W}initialize(t){t.rotation instanceof W&&(t.angularVelocity=new W,this.angularVelocity.startGen(t.memory))}update(t,e){t.rotation instanceof W&&(this.angularVelocity.genValue(t.memory,this.tempQuat,e,t.age/t.life),t.rotation.multiply(this.tempQuat))}toJSON(){return{type:this.type,angularVelocity:this.angularVelocity.toJSON()}}static fromJSON(t){return new ns(Ba(t.angularVelocity))}frameUpdate(t){}clone(){return new ns(this.angularVelocity.clone())}reset(){}}class os{initialize(t,e){this.ps=e,this.x.startGen(t.memory),this.y.startGen(t.memory),this.z.startGen(t.memory)}constructor(t,e,i){this.x=t,this.y=e,this.z=i,this.type="ForceOverLife",this._temp=new I,this._tempScale=new I,this._tempQ=new W}update(t,e){this._temp.set(this.x.genValue(t.memory,t.age/t.life),this.y.genValue(t.memory,t.age/t.life),this.z.genValue(t.memory,t.age/t.life)),this.ps.worldSpace?t.velocity.addScaledVector(this._temp,e):(this._temp.multiply(this._tempScale).applyQuaternion(this._tempQ),t.velocity.addScaledVector(this._temp,e))}toJSON(){return{type:this.type,x:this.x.toJSON(),y:this.y.toJSON(),z:this.z.toJSON()}}static fromJSON(t){return new os(L(t.x),L(t.y),L(t.z))}frameUpdate(t){if(this.ps&&!this.ps.worldSpace){const e=this._temp,i=this._tempQ,s=this._tempScale;this.ps.emitter.matrixWorld.decompose(e,i,s),i.invert(),s.set(1/s.x,1/s.y,1/s.z)}}clone(){return new os(this.x.clone(),this.y.clone(),this.z.clone())}reset(){}}class as{initialize(t){this.size.startGen(t.memory)}constructor(t){this.size=t,this.type="SizeOverLife"}update(t){this.size instanceof qe?this.size.genValue(t.memory,t.size,t.age/t.life).multiply(t.startSize):t.size.copy(t.startSize).multiplyScalar(this.size.genValue(t.memory,t.age/t.life))}toJSON(){return{type:this.type,size:this.size.toJSON()}}static fromJSON(t){return new as(cr(t.size))}frameUpdate(t){}clone(){return new as(this.size.clone())}reset(){}}class ls{initialize(t){this.speed.startGen(t.memory)}constructor(t){this.speed=t,this.type="SpeedOverLife"}update(t){t.speedModifier=this.speed.genValue(t.memory,t.age/t.life)}toJSON(){return{type:this.type,speed:this.speed.toJSON()}}static fromJSON(t){return new ls(L(t.speed))}frameUpdate(t){}clone(){return new ls(this.speed.clone())}reset(){}}class hs{constructor(t){this.frame=t,this.type="FrameOverLife"}initialize(t){this.frame.startGen(t.memory)}update(t,e){this.frame instanceof Ji&&(t.uvTile=this.frame.genValue(t.memory,t.age/t.life))}frameUpdate(t){}toJSON(){return{type:this.type,frame:this.frame.toJSON()}}static fromJSON(t){return new hs(L(t.frame))}clone(){return new hs(this.frame.clone())}reset(){}}class cs{constructor(t,e=new I(0,1,0)){this.orbitSpeed=t,this.axis=e,this.type="OrbitOverLife",this.temp=new I,this.rotation=new W}initialize(t){this.orbitSpeed.startGen(t.memory)}update(t,e){this.temp.copy(t.position).projectOnVector(this.axis),this.rotation.setFromAxisAngle(this.axis,this.orbitSpeed.genValue(t.memory,t.age/t.life)*e),t.position.sub(this.temp),t.position.applyQuaternion(this.rotation),t.position.add(this.temp)}frameUpdate(t){}toJSON(){return{type:this.type,orbitSpeed:this.orbitSpeed.toJSON(),axis:[this.axis.x,this.axis.y,this.axis.z]}}static fromJSON(t){return new cs(L(t.orbitSpeed),t.axis?new I(t.axis[0],t.axis[1],t.axis[2]):void 0)}clone(){return new cs(this.orbitSpeed.clone())}reset(){}}class jr{constructor(t){this.data=t,this.next=null,this.prev=null}hasPrev(){return this.prev!==null}hasNext(){return this.next!==null}}class id{constructor(){this.length=0,this.head=this.tail=null}isEmpty(){return this.head===null}clear(){this.length=0,this.head=this.tail=null}front(){return this.head===null?null:this.head.data}back(){return this.tail===null?null:this.tail.data}dequeue(){if(this.head){const t=this.head.data;return this.head=this.head.next,this.head?this.head.prev=null:this.tail=null,this.length--,t}}pop(){if(this.tail){const t=this.tail.data;return this.tail=this.tail.prev,this.tail?this.tail.next=null:this.head=null,this.length--,t}}queue(t){const e=new jr(t);this.tail||(this.tail=e),this.head&&(this.head.prev=e,e.next=this.head),this.head=e,this.length++}push(t){const e=new jr(t);this.head||(this.head=e),this.tail&&(this.tail.next=e,e.prev=this.tail),this.tail=e,this.length++}insertBefore(t,e){const i=new jr(e);i.next=t,i.prev=t.prev,i.prev!==null&&(i.prev.next=i),i.next.prev=i,t==this.head&&(this.head=i),this.length++}remove(t){if(this.head===null||this.tail===null)return;let e=this.head;for(t===this.head.data&&(this.head=this.head.next),t===this.tail.data&&(this.tail=this.tail.prev);e.next!==null&&e.data!==t;)e=e.next;e.data===t&&(e.prev!==null&&(e.prev.next=e.next),e.next!==null&&(e.next.prev=e.prev),this.length--)}*values(){let t=this.head;for(;t!==null;)yield t.data,t=t.next}}class sd{constructor(){this.startSpeed=0,this.startColor=new Ht,this.startSize=new I(1,1,1),this.position=new I,this.velocity=new I,this.age=0,this.life=1,this.size=new I(1,1,1),this.speedModifier=1,this.rotation=0,this.color=new Ht,this.uvTile=0,this.memory=[]}get died(){return this.age>=this.life}reset(){this.memory.length=0}}class rd{constructor(t,e,i){this.position=t,this.size=e,this.color=i}}class yn{constructor(){this.startSpeed=0,this.startColor=new Ht,this.startSize=new I(1,1,1),this.position=new I,this.velocity=new I,this.age=0,this.life=1,this.size=new I(1,1,1),this.length=100,this.speedModifier=1,this.color=new Ht,this.previous=new id,this.uvTile=0,this.memory=[]}update(){for(this.age<=this.life?this.previous.push(new rd(this.position.clone(),this.size.x,this.color.clone())):this.previous.length>0&&this.previous.dequeue();this.previous.length>this.length;)this.previous.dequeue()}get died(){return this.age>=this.life}reset(){this.memory.length=0,this.previous.clear()}}class ds{initialize(t){this.width.startGen(t.memory)}constructor(t){this.width=t,this.type="WidthOverLength"}update(t){if(t instanceof yn){const e=t.previous.values();for(let i=0;i<t.previous.length;i++){const s=e.next();s.value.size=this.width.genValue(t.memory,(t.previous.length-i)/t.length)}}}frameUpdate(t){}toJSON(){return{type:this.type,width:this.width.toJSON()}}static fromJSON(t){return new ds(L(t.width))}clone(){return new ds(this.width.clone())}reset(){}}class us{constructor(t,e){this.direction=t,this.magnitude=e,this.type="ApplyForce",this.memory={data:[],dataCount:0},this.magnitudeValue=this.magnitude.genValue(this.memory)}initialize(t){}update(t,e){t.velocity.addScaledVector(this.direction,this.magnitudeValue*e)}frameUpdate(t){this.magnitudeValue=this.magnitude.genValue(this.memory)}toJSON(){return{type:this.type,direction:[this.direction.x,this.direction.y,this.direction.z],magnitude:this.magnitude.toJSON()}}static fromJSON(t){return new us(new I(t.direction[0],t.direction[1],t.direction[2]),L(t.magnitude??t.force))}clone(){return new us(this.direction.clone(),this.magnitude.clone())}reset(){}}class ps{constructor(t,e){this.center=t,this.magnitude=e,this.type="GravityForce",this.temp=new I}initialize(t){}update(t,e){this.temp.copy(this.center).sub(t.position).normalize(),t.velocity.addScaledVector(this.temp,this.magnitude/t.position.distanceToSquared(this.center)*e)}frameUpdate(t){}toJSON(){return{type:this.type,center:[this.center.x,this.center.y,this.center.z],magnitude:this.magnitude}}static fromJSON(t){return new ps(new I(t.center[0],t.center[1],t.center[2]),t.magnitude)}clone(){return new ps(this.center.clone(),this.magnitude)}reset(){}}class fs{constructor(t){this.angle=t,this.type="ChangeEmitDirection",this._temp=new I,this._q=new W,this.memory={data:[],dataCount:0}}initialize(t){const e=t.velocity.length();e!=0&&(t.velocity.normalize(),t.velocity.x===0&&t.velocity.y===0?this._temp.set(0,t.velocity.z,0):this._temp.set(-t.velocity.y,t.velocity.x,0),this.angle.startGen(this.memory),this._q.setFromAxisAngle(this._temp.normalize(),this.angle.genValue(this.memory)),this._temp.copy(t.velocity),t.velocity.applyQuaternion(this._q),this._q.setFromAxisAngle(this._temp,Math.random()*Math.PI*2),t.velocity.applyQuaternion(this._q),t.velocity.setLength(e))}update(t,e){}frameUpdate(t){}toJSON(){return{type:this.type,angle:this.angle.toJSON()}}static fromJSON(t){return new fs(L(t.angle))}clone(){return new fs(this.angle)}reset(){}}var ci;(function(o){o[o.Death=0]="Death",o[o.Birth=1]="Birth",o[o.Frame=2]="Frame"})(ci||(ci={}));class xi{constructor(t,e,i,s=ci.Frame,r=1){this.particleSystem=t,this.useVelocityAsBasis=e,this.subParticleSystem=i,this.mode=s,this.emitProbability=r,this.type="EmitSubParticleSystem",this.q_=new W,this.v_=new I,this.v2_=new I,this.subEmissions=new Array,this.subParticleSystem&&this.subParticleSystem.system&&(this.subParticleSystem.system.onlyUsedByOther=!0)}initialize(t){}update(t,e){this.mode===ci.Frame?this.emit(t,e):this.mode===ci.Birth&&t.age===0?this.emit(t,e):this.mode===ci.Death&&t.age+e>=t.life&&this.emit(t,e)}emit(t,e){if(!this.subParticleSystem||Math.random()>this.emitProbability)return;const i=new Zt;this.setMatrixFromParticle(i,t),this.subEmissions.push({burstParticleCount:0,burstParticleIndex:0,isBursting:!1,burstIndex:0,burstWaveIndex:0,time:0,waitEmiting:0,matrix:i,travelDistance:0,particle:t})}frameUpdate(t){if(this.subParticleSystem)for(let e=0;e<this.subEmissions.length;e++)if(this.subEmissions[e].time>=this.subParticleSystem.system.duration)this.subEmissions[e]=this.subEmissions[this.subEmissions.length-1],this.subEmissions.length=this.subEmissions.length-1,e--;else{const i=this.subEmissions[e];i.particle&&i.particle.age<i.particle.life?this.setMatrixFromParticle(i.matrix,i.particle):i.particle=void 0,this.subParticleSystem.system.emit(t,i,i.matrix)}}toJSON(){return{type:this.type,subParticleSystem:this.subParticleSystem?this.subParticleSystem.uuid:"",useVelocityAsBasis:this.useVelocityAsBasis,mode:this.mode,emitProbability:this.emitProbability}}static fromJSON(t,e){return new xi(e,t.useVelocityAsBasis,t.subParticleSystem,t.mode,t.emitProbability)}clone(){return new xi(this.particleSystem,this.useVelocityAsBasis,this.subParticleSystem,this.mode,this.emitProbability)}reset(){}setMatrixFromParticle(t,e){let i;if(e.rotation===void 0||this.useVelocityAsBasis)if(e.velocity.x===0&&e.velocity.y===0&&(e.velocity.z===1||e.velocity.z===0))t.set(1,0,0,e.position.x,0,1,0,e.position.y,0,0,1,e.position.z,0,0,0,1);else{this.v_.copy(Ro).cross(e.velocity),this.v2_.copy(e.velocity).cross(this.v_);const s=this.v_.length(),r=this.v2_.length();t.set(this.v_.x/s,this.v2_.x/r,e.velocity.x,e.position.x,this.v_.y/s,this.v2_.y/r,e.velocity.y,e.position.y,this.v_.z/s,this.v2_.z/r,e.velocity.z,e.position.z,0,0,0,1)}else e.rotation instanceof W?i=e.rotation:(this.q_.setFromAxisAngle(Ro,e.rotation),i=this.q_),t.compose(e.position,i,td);this.particleSystem.worldSpace||t.multiplyMatrices(this.particleSystem.emitter.matrixWorld,t)}}const nd=.5*(Math.sqrt(3)-1),Ri=(3-Math.sqrt(3))/6,od=1/3,Kt=1/6,ad=(Math.sqrt(5)-1)/4,Ct=(5-Math.sqrt(5))/20,vt=new Float32Array([1,1,0,-1,1,0,1,-1,0,-1,-1,0,1,0,1,-1,0,1,1,0,-1,-1,0,-1,0,1,1,0,-1,1,0,1,-1,0,-1,-1]),ft=new Float32Array([0,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,1,0,1,1,1,0,1,-1,1,0,-1,1,1,0,-1,-1,-1,0,1,1,-1,0,1,-1,-1,0,-1,1,-1,0,-1,-1,1,1,0,1,1,1,0,-1,1,-1,0,1,1,-1,0,-1,-1,1,0,1,-1,1,0,-1,-1,-1,0,1,-1,-1,0,-1,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,0]);class Na{constructor(t=Math.random){const e=typeof t=="function"?t:hd(t);this.p=ld(e),this.perm=new Uint8Array(512),this.permMod12=new Uint8Array(512);for(let i=0;i<512;i++)this.perm[i]=this.p[i&255],this.permMod12[i]=this.perm[i]%12}noise2D(t,e){const i=this.permMod12,s=this.perm;let r=0,n=0,a=0;const l=(t+e)*nd,h=Math.floor(t+l),d=Math.floor(e+l),c=(h+d)*Ri,p=h-c,u=d-c,f=t-p,m=e-u;let y,g;f>m?(y=1,g=0):(y=0,g=1);const _=f-y+Ri,M=m-g+Ri,w=f-1+2*Ri,C=m-1+2*Ri,x=h&255,b=d&255;let P=.5-f*f-m*m;if(P>=0){const J=i[x+s[b]]*3;P*=P,r=P*P*(vt[J]*f+vt[J+1]*m)}let A=.5-_*_-M*M;if(A>=0){const J=i[x+y+s[b+g]]*3;A*=A,n=A*A*(vt[J]*_+vt[J+1]*M)}let N=.5-w*w-C*C;if(N>=0){const J=i[x+1+s[b+1]]*3;N*=N,a=N*N*(vt[J]*w+vt[J+1]*C)}return 70*(r+n+a)}noise3D(t,e,i){const s=this.permMod12,r=this.perm;let n,a,l,h;const d=(t+e+i)*od,c=Math.floor(t+d),p=Math.floor(e+d),u=Math.floor(i+d),f=(c+p+u)*Kt,m=c-f,y=p-f,g=u-f,_=t-m,M=e-y,w=i-g;let C,x,b,P,A,N;_>=M?M>=w?(C=1,x=0,b=0,P=1,A=1,N=0):_>=w?(C=1,x=0,b=0,P=1,A=0,N=1):(C=0,x=0,b=1,P=1,A=0,N=1):M<w?(C=0,x=0,b=1,P=0,A=1,N=1):_<w?(C=0,x=1,b=0,P=0,A=1,N=1):(C=0,x=1,b=0,P=1,A=1,N=0);const J=_-C+Kt,$=M-x+Kt,gt=w-b+Kt,Y=_-P+2*Kt,K=M-A+2*Kt,lt=w-N+2*Kt,st=_-1+3*Kt,ct=M-1+3*Kt,tt=w-1+3*Kt,dt=c&255,ut=p&255,V=u&255;let yt=.6-_*_-M*M-w*w;if(yt<0)n=0;else{const at=s[dt+r[ut+r[V]]]*3;yt*=yt,n=yt*yt*(vt[at]*_+vt[at+1]*M+vt[at+2]*w)}let D=.6-J*J-$*$-gt*gt;if(D<0)a=0;else{const at=s[dt+C+r[ut+x+r[V+b]]]*3;D*=D,a=D*D*(vt[at]*J+vt[at+1]*$+vt[at+2]*gt)}let Ft=.6-Y*Y-K*K-lt*lt;if(Ft<0)l=0;else{const at=s[dt+P+r[ut+A+r[V+N]]]*3;Ft*=Ft,l=Ft*Ft*(vt[at]*Y+vt[at+1]*K+vt[at+2]*lt)}let Pt=.6-st*st-ct*ct-tt*tt;if(Pt<0)h=0;else{const at=s[dt+1+r[ut+1+r[V+1]]]*3;Pt*=Pt,h=Pt*Pt*(vt[at]*st+vt[at+1]*ct+vt[at+2]*tt)}return 32*(n+a+l+h)}noise4D(t,e,i,s){const r=this.perm;let n,a,l,h,d;const c=(t+e+i+s)*ad,p=Math.floor(t+c),u=Math.floor(e+c),f=Math.floor(i+c),m=Math.floor(s+c),y=(p+u+f+m)*Ct,g=p-y,_=u-y,M=f-y,w=m-y,C=t-g,x=e-_,b=i-M,P=s-w;let A=0,N=0,J=0,$=0;C>x?A++:N++,C>b?A++:J++,C>P?A++:$++,x>b?N++:J++,x>P?N++:$++,b>P?J++:$++;const gt=A>=3?1:0,Y=N>=3?1:0,K=J>=3?1:0,lt=$>=3?1:0,st=A>=2?1:0,ct=N>=2?1:0,tt=J>=2?1:0,dt=$>=2?1:0,ut=A>=1?1:0,V=N>=1?1:0,yt=J>=1?1:0,D=$>=1?1:0,Ft=C-gt+Ct,Pt=x-Y+Ct,at=b-K+Ct,Qe=P-lt+Ct,$e=C-st+2*Ct,ke=x-ct+2*Ct,Ke=b-tt+2*Ct,ti=P-dt+2*Ct,ei=C-ut+3*Ct,me=x-V+3*Ct,ii=b-yt+3*Ct,si=P-D+3*Ct,Fe=C-1+4*Ct,re=x-1+4*Ct,ge=b-1+4*Ct,ye=P-1+4*Ct,Qt=p&255,ne=u&255,_t=f&255,oe=m&255;let _e=.6-C*C-x*x-b*b-P*P;if(_e<0)n=0;else{const et=r[Qt+r[ne+r[_t+r[oe]]]]%32*4;_e*=_e,n=_e*_e*(ft[et]*C+ft[et+1]*x+ft[et+2]*b+ft[et+3]*P)}let ve=.6-Ft*Ft-Pt*Pt-at*at-Qe*Qe;if(ve<0)a=0;else{const et=r[Qt+gt+r[ne+Y+r[_t+K+r[oe+lt]]]]%32*4;ve*=ve,a=ve*ve*(ft[et]*Ft+ft[et+1]*Pt+ft[et+2]*at+ft[et+3]*Qe)}let Be=.6-$e*$e-ke*ke-Ke*Ke-ti*ti;if(Be<0)l=0;else{const et=r[Qt+st+r[ne+ct+r[_t+tt+r[oe+dt]]]]%32*4;Be*=Be,l=Be*Be*(ft[et]*$e+ft[et+1]*ke+ft[et+2]*Ke+ft[et+3]*ti)}let Ne=.6-ei*ei-me*me-ii*ii-si*si;if(Ne<0)h=0;else{const et=r[Qt+ut+r[ne+V+r[_t+yt+r[oe+D]]]]%32*4;Ne*=Ne,h=Ne*Ne*(ft[et]*ei+ft[et+1]*me+ft[et+2]*ii+ft[et+3]*si)}let xe=.6-Fe*Fe-re*re-ge*ge-ye*ye;if(xe<0)d=0;else{const et=r[Qt+1+r[ne+1+r[_t+1+r[oe+1]]]]%32*4;xe*=xe,d=xe*xe*(ft[et]*Fe+ft[et+1]*re+ft[et+2]*ge+ft[et+3]*ye)}return 27*(n+a+l+h+d)}}function ld(o){const t=new Uint8Array(256);for(let e=0;e<256;e++)t[e]=e;for(let e=0;e<255;e++){const i=e+~~(o()*(256-e)),s=t[e];t[e]=t[i],t[i]=s}return t}function hd(o){let t=0,e=0,i=0,s=1;const r=cd();return t=r(" "),e=r(" "),i=r(" "),t-=r(o),t<0&&(t+=1),e-=r(o),e<0&&(e+=1),i-=r(o),i<0&&(i+=1),function(){const n=2091639*t+s*23283064365386963e-26;return t=e,e=i,i=n-(s=n|0)}}function cd(){let o=4022871197;return function(t){t=t.toString();for(let e=0;e<t.length;e++){o+=t.charCodeAt(e);let i=.02519603282416938*o;o=i>>>0,i-=o,i*=o,o=i>>>0,i-=o,o+=i*4294967296}return(o>>>0)*23283064365386963e-26}}class ms{constructor(t,e,i,s){this.scale=t,this.octaves=e,this.velocityMultiplier=i,this.timeScale=s,this.type="TurbulenceField",this.generator=new Na,this.timeOffset=new I,this.temp=new I,this.temp2=new I,this.timeOffset.x=Math.random()/this.scale.x*this.timeScale.x,this.timeOffset.y=Math.random()/this.scale.y*this.timeScale.y,this.timeOffset.z=Math.random()/this.scale.z*this.timeScale.z}initialize(t){}update(t,e){const i=t.position.x/this.scale.x,s=t.position.y/this.scale.y,r=t.position.z/this.scale.z;this.temp.set(0,0,0);let n=1;for(let a=0;a<this.octaves;a++)this.temp2.set(this.generator.noise4D(i*n,s*n,r*n,this.timeOffset.x*n)/n,this.generator.noise4D(i*n,s*n,r*n,this.timeOffset.y*n)/n,this.generator.noise4D(i*n,s*n,r*n,this.timeOffset.z*n)/n),this.temp.add(this.temp2),n*=2;this.temp.multiply(this.velocityMultiplier),t.velocity.addScaledVector(this.temp,e)}toJSON(){return{type:this.type,scale:[this.scale.x,this.scale.y,this.scale.z],octaves:this.octaves,velocityMultiplier:[this.velocityMultiplier.x,this.velocityMultiplier.y,this.velocityMultiplier.z],timeScale:[this.timeScale.x,this.timeScale.y,this.timeScale.z]}}frameUpdate(t){this.timeOffset.x+=t*this.timeScale.x,this.timeOffset.y+=t*this.timeScale.y,this.timeOffset.z+=t*this.timeScale.z}static fromJSON(t){return new ms(new I(t.scale[0],t.scale[1],t.scale[2]),t.octaves,new I(t.velocityMultiplier[0],t.velocityMultiplier[1],t.velocityMultiplier[2]),new I(t.timeScale[0],t.timeScale[1],t.timeScale[2]))}clone(){return new ms(this.scale.clone(),this.octaves,this.velocityMultiplier.clone(),this.timeScale.clone())}reset(){}}const te=[],Gr=new I,Xr=new W;class gs{constructor(t,e,i=new Q(1),s=new Q(0)){if(this.frequency=t,this.power=e,this.positionAmount=i,this.rotationAmount=s,this.type="Noise",this.duration=0,te.length===0)for(let r=0;r<100;r++)te.push(new Na)}initialize(t){t.lastPosNoise=new I,typeof t.rotation=="number"?t.lastRotNoise=0:t.lastRotNoise=new W,t.generatorIndex=[$s(0,100),$s(0,100),$s(0,100),$s(0,100)],this.positionAmount.startGen(t.memory),this.rotationAmount.startGen(t.memory),this.frequency.startGen(t.memory),this.power.startGen(t.memory)}update(t,e){let i=this.frequency.genValue(t.memory,t.age/t.life),s=this.power.genValue(t.memory,t.age/t.life),r=this.positionAmount.genValue(t.memory,t.age/t.life),n=this.rotationAmount.genValue(t.memory,t.age/t.life);r>0&&t.lastPosNoise!==void 0&&(t.position.sub(t.lastPosNoise),Gr.set(te[t.generatorIndex[0]].noise2D(0,t.age*i)*s*r,te[t.generatorIndex[1]].noise2D(0,t.age*i)*s*r,te[t.generatorIndex[2]].noise2D(0,t.age*i)*s*r),t.position.add(Gr),t.lastPosNoise.copy(Gr)),n>0&&t.lastRotNoise!==void 0&&(typeof t.rotation=="number"?(t.rotation-=t.lastRotNoise,t.rotation+=te[t.generatorIndex[3]].noise2D(0,t.age*i)*Math.PI*s*n):(t.lastRotNoise.invert(),t.rotation.multiply(t.lastRotNoise),Xr.set(te[t.generatorIndex[0]].noise2D(0,t.age*i)*s*n,te[t.generatorIndex[1]].noise2D(0,t.age*i)*s*n,te[t.generatorIndex[2]].noise2D(0,t.age*i)*s*n,te[t.generatorIndex[3]].noise2D(0,t.age*i)*s*n).normalize(),t.rotation.multiply(Xr),t.lastRotNoise.copy(Xr)))}toJSON(){return{type:this.type,frequency:this.frequency.toJSON(),power:this.power.toJSON(),positionAmount:this.positionAmount.toJSON(),rotationAmount:this.rotationAmount.toJSON()}}frameUpdate(t){this.duration+=t}static fromJSON(t){return new gs(L(t.frequency),L(t.power),L(t.positionAmount),L(t.rotationAmount))}clone(){return new gs(this.frequency.clone(),this.power.clone(),this.positionAmount.clone(),this.rotationAmount.clone())}reset(){}}class ys{constructor(t,e){this.color=t,this.speedRange=e,this.type="ColorBySpeed"}initialize(t){this.color.startGen(t.memory)}update(t,e){const i=(t.startSpeed-this.speedRange.a)/(this.speedRange.b-this.speedRange.a);this.color.genColor(t.memory,t.color,i),t.color.x*=t.startColor.x,t.color.y*=t.startColor.y,t.color.z*=t.startColor.z,t.color.w*=t.startColor.w}frameUpdate(t){}toJSON(){return{type:this.type,color:this.color.toJSON(),speedRange:this.speedRange.toJSON()}}static fromJSON(t){return new ys(On(t.color),Ye.fromJSON(t.speedRange))}clone(){return new ys(this.color.clone(),this.speedRange.clone())}reset(){}}class _s{initialize(t){this.size.startGen(t.memory)}constructor(t,e){this.size=t,this.speedRange=e,this.type="SizeBySpeed"}update(t){const e=(t.startSpeed-this.speedRange.a)/(this.speedRange.b-this.speedRange.a);this.size instanceof qe?this.size.genValue(t.memory,t.size,e).multiply(t.startSize):t.size.copy(t.startSize).multiplyScalar(this.size.genValue(t.memory,e))}toJSON(){return{type:this.type,size:this.size.toJSON(),speedRange:this.speedRange.toJSON()}}static fromJSON(t){return new _s(cr(t.size),Ye.fromJSON(t.speedRange))}frameUpdate(t){}clone(){return new _s(this.size.clone(),this.speedRange.clone())}reset(){}}class vs{constructor(t,e){this.angularVelocity=t,this.speedRange=e,this.type="RotationBySpeed",this.tempQuat=new W}initialize(t){typeof t.rotation=="number"&&this.angularVelocity.startGen(t.memory)}update(t,e){if(typeof t.rotation=="number"){const i=(t.startSpeed-this.speedRange.a)/(this.speedRange.b-this.speedRange.a);t.rotation+=e*this.angularVelocity.genValue(t.memory,i)}}toJSON(){return{type:this.type,angularVelocity:this.angularVelocity.toJSON(),speedRange:this.speedRange.toJSON()}}static fromJSON(t){return new vs(L(t.angularVelocity),Ye.fromJSON(t.speedRange))}frameUpdate(t){}clone(){return new vs(this.angularVelocity.clone(),this.speedRange.clone())}reset(){}}class xs{initialize(t){this.speed.startGen(t.memory)}constructor(t,e){this.speed=t,this.dampen=e,this.type="LimitSpeedOverLife"}update(t,e){let i=t.velocity.length(),s=this.speed.genValue(t.memory,t.age/t.life);if(i>s){const r=(i-s)/i;t.velocity.multiplyScalar(1-r*this.dampen*e*20)}}toJSON(){return{type:this.type,speed:this.speed.toJSON(),dampen:this.dampen}}static fromJSON(t){return new xs(L(t.speed),t.dampen)}frameUpdate(t){}clone(){return new xs(this.speed.clone(),this.dampen)}reset(){}}const dr={ApplyForce:{type:"ApplyForce",constructor:us,params:[["direction",["vec3"]],["magnitude",["value"]]],loadJSON:us.fromJSON},Noise:{type:"Noise",constructor:gs,params:[["frequency",["value"]],["power",["value"]],["positionAmount",["value"]],["rotationAmount",["value"]]],loadJSON:gs.fromJSON},TurbulenceField:{type:"TurbulenceField",constructor:ms,params:[["scale",["vec3"]],["octaves",["number"]],["velocityMultiplier",["vec3"]],["timeScale",["vec3"]]],loadJSON:ms.fromJSON},GravityForce:{type:"GravityForce",constructor:ps,params:[["center",["vec3"]],["magnitude",["number"]]],loadJSON:ps.fromJSON},ColorOverLife:{type:"ColorOverLife",constructor:ss,params:[["color",["colorFunc"]]],loadJSON:ss.fromJSON},RotationOverLife:{type:"RotationOverLife",constructor:rs,params:[["angularVelocity",["value","valueFunc"]]],loadJSON:rs.fromJSON},Rotation3DOverLife:{type:"Rotation3DOverLife",constructor:ns,params:[["angularVelocity",["rotationFunc"]]],loadJSON:ns.fromJSON},SizeOverLife:{type:"SizeOverLife",constructor:as,params:[["size",["value","valueFunc","vec3Func"]]],loadJSON:as.fromJSON},ColorBySpeed:{type:"ColorBySpeed",constructor:ys,params:[["color",["colorFunc"]],["speedRange",["range"]]],loadJSON:ys.fromJSON},RotationBySpeed:{type:"RotationBySpeed",constructor:vs,params:[["angularVelocity",["value","valueFunc"]],["speedRange",["range"]]],loadJSON:vs.fromJSON},SizeBySpeed:{type:"SizeBySpeed",constructor:_s,params:[["size",["value","valueFunc","vec3Func"]],["speedRange",["range"]]],loadJSON:_s.fromJSON},SpeedOverLife:{type:"SpeedOverLife",constructor:ls,params:[["speed",["value","valueFunc"]]],loadJSON:ls.fromJSON},FrameOverLife:{type:"FrameOverLife",constructor:hs,params:[["frame",["value","valueFunc"]]],loadJSON:hs.fromJSON},ForceOverLife:{type:"ForceOverLife",constructor:os,params:[["x",["value","valueFunc"]],["y",["value","valueFunc"]],["z",["value","valueFunc"]]],loadJSON:os.fromJSON},OrbitOverLife:{type:"OrbitOverLife",constructor:cs,params:[["orbitSpeed",["value","valueFunc"]],["axis",["vec3"]]],loadJSON:cs.fromJSON},WidthOverLength:{type:"WidthOverLength",constructor:ds,params:[["width",["value","valueFunc"]]],loadJSON:ds.fromJSON},ChangeEmitDirection:{type:"ChangeEmitDirection",constructor:fs,params:[["angle",["value"]]],loadJSON:fs.fromJSON},EmitSubParticleSystem:{type:"EmitSubParticleSystem",constructor:xi,params:[["particleSystem",["self"]],["useVelocityAsBasis",["boolean"]],["subParticleSystem",["particleSystem"]],["mode",["number"]],["emitProbability",["number"]]],loadJSON:xi.fromJSON},LimitSpeedOverLife:{type:"LimitSpeedOverLife",constructor:xs,params:[["speed",["value","valueFunc"]],["dampen",["number"]]],loadJSON:xs.fromJSON}};function dd(o,t){return dr[o.type]?dr[o.type].loadJSON(o,t):null}const ud=[];function pd(o){if(!ud.find(e=>e.id===o.id)){for(const e of o.emitterShapes)gn[e.type]||(gn[e.type]=e);for(const e of o.behaviors)dr[e.type]||(dr[e.type]=e)}}class ws{get geometry(){return this._geometry}set geometry(t){if(this._geometry=t,t===void 0||typeof t=="string")return;const e=new Bh;this._triangleIndexToArea.length=0;let i=0;if(!t.getIndex())return;const s=t.getIndex().array,r=s.length/3;this._triangleIndexToArea.push(0);for(let n=0;n<r;n++)e.setFromAttributeAndIndices(t.getAttribute("position"),s[n*3],s[n*3+1],s[n*3+2]),i+=e.getArea(),this._triangleIndexToArea.push(i);t.userData.triangleIndexToArea=this._triangleIndexToArea}constructor(t){this.type="mesh_surface",this._triangleIndexToArea=[],this._tempA=new v,this._tempB=new v,this._tempC=new v,t&&(this.geometry=t)}initialize(t){const e=this._geometry;if(!e||e.getIndex()===null){t.position.set(0,0,0),t.velocity.set(0,0,1).multiplyScalar(t.startSpeed);return}const i=this._triangleIndexToArea.length-1;let s=0,r=i;const n=Math.random()*this._triangleIndexToArea[i];for(;s+1<r;){const u=Math.floor((s+r)/2);n<this._triangleIndexToArea[u]?r=u:s=u}let a=Math.random(),l=Math.random();a+l>1&&(a=1-a,l=1-l);const h=e.getIndex().array[s*3],d=e.getIndex().array[s*3+1],c=e.getIndex().array[s*3+2],p=e.getAttribute("position");this._tempA.fromBufferAttribute(p,h),this._tempB.fromBufferAttribute(p,d),this._tempC.fromBufferAttribute(p,c),this._tempB.sub(this._tempA),this._tempC.sub(this._tempA),this._tempA.addScaledVector(this._tempB,a).addScaledVector(this._tempC,l),t.position.copy(this._tempA),this._tempA.copy(this._tempB).cross(this._tempC).normalize(),t.velocity.copy(this._tempA).normalize().multiplyScalar(t.startSpeed)}toJSON(){return{type:"mesh_surface",mesh:this._geometry?this._geometry.uuid:""}}static fromJSON(t,e){return new ws(e.geometries[t.geometry])}clone(){return new ws(this._geometry)}update(t,e){}}const fd={id:"three.quarks",emitterShapes:[{type:"mesh_surface",params:[["geometry",["geometry"]]],constructor:ws,loadJSON:ws.fromJSON}],behaviors:[]};var md=`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/spark.module-B_-x7Z29.js","assets/three.module-BynznMJN.js","assets/index-DuB3wHKD.js","assets/index-DaQZGF7d.js","assets/_commonjsHelpers-D6-XlEtG.js","assets/index-D_NuPfjr.js","assets/jsx-runtime-DPjLkJKQ.js","assets/index-CtzuWnCS.js","assets/index-CinJrH5C.js","assets/index-D2LwEE0L.js","assets/client-DNXj_opT.js","assets/index-D2fNXpHa.css","assets/index-C5UECeSr.js","assets/stage-overlay-set-D7J-N5eX.js","assets/TransientHint-9_u15mth.js","assets/clip-planes-CnAI6DZn.js","assets/OrbitControls-BHxt84w6.js","assets/LineSegments2-vfeDUBfs.js","assets/viewport-pick-context-DkawXbEi.js","assets/editor-presentation-activity-C7SNSmTd.js","assets/stage-keyboard-C9wzGFxu.js","assets/stage-presence-markers-DvbNl1W4.js"])))=>i.map(i=>d[i]);
2
+ import{g as xt,dA as Rt,dB as X,ac as Ie,dC as ue,dD as Kn,dE as Gs,dF as mr,dG as ze,dH as un,dI as to,dJ as eo,dK as io,dL as gl,dM as Sn,dN as so,d0 as ki,a3 as jt,Z as Fi,dO as Ir,dP as yl,dQ as _l,dR as vl,dS as xl,dT as wl,Q as Sl,dU as bl,dV as Ml,dW as ro,dX as no,dY as oo,G as ao,t as Nt,dZ as Cl,d_ as Pl,d$ as lo,cL as ho,cj as Al,_ as Ss,e0 as pn,e1 as bs,e2 as El,bT as Tl,e3 as zl,e4 as pa,e5 as Ol,e6 as co,e7 as Il,e8 as Rl,e9 as kl,bd as Ae,a4 as Ee,ea as pe,bD as Fl,T as Xs,eb as fa,ec as Bl,ed as Nl,bc as Ti,bG as Hl,ee as Ll,by as Dl,ef as Ul,eg as Vl,eh as jl,ei as Gl,aH as Xl,ej as Wl,W as Jl,ek as ma,el as Yl,em as ql,en as Zl,w as uo,eo as Ql,bL as po,ep as $l,eq as Kl,er as th,es as eh,dz as ih,et as sh,eu as rh,ev as nh,ew as oh,dv as ah,K as lh,ex as hh,ey as ch,bS as dh,ez as uh,eA as ph,eB as fh,eC as mh}from"./index-DuB3wHKD.js";import{a as T}from"./jsx-runtime-DPjLkJKQ.js";import{r as F}from"./index-DaQZGF7d.js";import"./index-CtzuWnCS.js";import{a$ as ga,e as ya,i as Ms,L as Ui,X as gh,b1 as Tt,Z as We,aR as bn,bT as yh,am as _a,d as B,C as _h,V as v,Q as wt,au as Yt,av as Je,aD as Ze,bU as Ot,bJ as mt,aa as Re,aC as Vi,a0 as E,bV as Ve,b7 as Wt,bW as zi,bp as fe,as as va,x as Mn,bo as Cn,ay as de,az as It,an as vh,U as Xt,g as ji,ab as ce,bP as sr,bx as xh,bX as wh,aN as Sh,aB as kt,bc as xa,aH as wa,aG as Cs,bF as Sa,bY as bh,bZ as Mh,ap as ie,bl as Pn,by as Ch,b6 as Ph,b_ as Ah,aX as ba,b4 as Eh,bQ as Th,b5 as zh,aY as gr,b3 as Ma,$ as pi,k as Ca,w as yr,b$ as Oh,c0 as Ih,ae as Rh,c1 as kh,ax as Fh,c2 as Bh,c3 as Nh,b as Dt,c4 as An,a as Jt,c5 as Pa,bK as Hh,c6 as Lh,bf as Dh,aW as Aa,p as Ea,P as fo,M as Rr,c7 as Uh,c8 as Vh,c9 as jh,ca as Gh,cb as Xh,bb as Wh,bd as Jh,aE as Yh,cc as mo,S as qh,W as go,H as Zh,a_ as Qh,Y as $h,K as Kh,v as tc,aZ as ec,br as ic,a1 as yo}from"./three.module-BynznMJN.js";import"./index-D2LwEE0L.js";import{E as _o,a as vo,f as sc}from"./clip-planes-CnAI6DZn.js";import{O as rc}from"./OrbitControls-BHxt84w6.js";import{b as En,L as Tn,a as zn}from"./LineSegments2-vfeDUBfs.js";import{s as xo,g as nc}from"./viewport-pick-context-DkawXbEi.js";import{s as oc,i as kr}from"./editor-presentation-activity-C7SNSmTd.js";const Ta=30;function za(o,t,e){return o<t?t:o>e?e:o}function ac(o,t){const e=o.animations;if(e.length===0)return null;const i=new ga(o);let s=e[0];if(!s)return null;const r=a=>{i.stopAllAction();const l=i.clipAction(a);l.paused=!0,l.play(),s=a};r(s);const n=t.attach({id:o.uuid,label:o.name||s.name||"Clip",range:()=>({start:0,end:s?.duration??0,fps:Ta}),seek:a=>{i.setTime(za(a,0,s?.duration??0))},clips:()=>e.map(a=>({id:a.name,label:a.name})),setClip:a=>{const l=e.find(h=>h.name===a);l&&r(l)}});return()=>{n(),i.stopAllAction(),i.uncacheRoot(o)}}function lc(o,t){const e=xt(o,"_animationRuntime");if(!e)return null;const i=[...e.clips.entries()];let s=i[0]?.[1];if(!s)return null;const r=a=>{e.mixer.stopAllAction();const l=e.mixer.clipAction(a);l.paused=!0,l.play(),s=a};return t.attach({id:o.uuid,label:o.name||s.name||"Animation",range:()=>({start:0,end:s?.duration??0,fps:Ta}),seek:a=>{e.mixer.setTime(za(a,0,s?.duration??0))},clips:()=>i.map(([a,l])=>({id:a,label:l.name||a})),setClip:a=>{const l=e.clips.get(a);l&&r(l)}})}function hc(o,t){const e=new Map,i=()=>{const s=new Set;o.traverse(r=>{if(e.has(r.uuid)){s.add(r.uuid);return}const n=lc(r,t)??ac(r,t);n&&(e.set(r.uuid,n),s.add(r.uuid))});for(const[r,n]of[...e])s.has(r)||(n(),e.delete(r))};return i(),{refresh:i,dispose:()=>{for(const s of e.values())s();e.clear()}}}let fi=0,fn=[];function cc(){fi+=1}function dc(){if(fi=Math.max(0,fi-1),fi===0){const o=fn;fn=[];for(const t of o)t()}}function uc(){return fi>0}function pc(){return fi===0?Promise.resolve():new Promise(o=>{fn.push(o)})}const be=()=>globalThis.performance?.now()??Date.now();function fc(o,t){return o.length===0?0:o[Math.min(o.length-1,Math.floor((o.length-1)*t))]??0}function mc(o=!1){const t=new Set,e=[],i=new Map,s=new Map,r=new Map;let n=[],a=[],l=o,h=!1,d=!1,c=0,p=0,u=0;const f=[];let m=0,y=0,g={gpuMs:null,drawCalls:0,triangles:0,geometries:0,textures:0,renderPasses:null},_={enabled:l,recording:d,fps:0,cpuMs:0,p95Ms:0,p99Ms:0,frames:[],phases:[],systems:[],components:[],render:g};function M(){const w=e.at(-1),C=e.slice();let x;const b=P=>(x??=C.map(A=>A.intervalMs).filter(A=>A>0).sort((A,N)=>A-N),fc(x,P));_={enabled:l,recording:d,fps:w?.intervalMs?1e3/w.intervalMs:0,cpuMs:w?.cpuMs??0,get p95Ms(){return b(.95)},get p99Ms(){return b(.99)},frames:C,phases:w?.phases??[],systems:[...s].map(([P,A])=>({name:P,ms:A})).sort((P,A)=>A.ms-P.ms),components:[...r].map(([P,A])=>({name:P,ms:A})).sort((P,A)=>A.ms-P.ms),render:g};for(const P of t)P()}return{get enabled(){return l},set enabled(w){l!==w&&(l=w,w&&!h&&(u=0),M())},get telemetryEnabled(){return h},set telemetryEnabled(w){if(h===w)return;const C=!l&&!h;h=w,w&&C&&(u=0),M()},get recording(){return d},startRecording(){const w=!l&&!h;l=!0,w&&(u=0),d=!0,e.length=0,M()},stopRecording(){d=!1,M()},clear(){e.length=0,M()},beginFrame(){!l&&!h||(i.clear(),s.clear(),r.clear(),n=[],a=[],f.length=0,g={gpuMs:null,drawCalls:0,triangles:0,geometries:0,textures:0,renderPasses:null},p=be())},beginPhase(){l&&f.push(be())},endPhase(w){if(!l)return;const C=f.pop()??p,x=be()-C,b=i.get(w);i.set(w,{ms:(b?.ms??0)+x,startMs:b?.startMs??C-p}),d&&performance.measure(`vgai.phase.${w}`,{start:C,duration:x})},systemObserver:{beginSystem(){l&&(m=be())},endSystem(w,C,x){if(!l)return;const b=be(),P=`${w} / ${C} / ${x}`;s.set(P,(s.get(P)??0)+b-m),n.push({name:P,phase:C,startMs:m-p,ms:b-m})}},beginComponent(){d&&(y=be())},endComponent(w,C=""){if(!d)return;const x=be();r.set(w,(r.get(w)??0)+x-y),a.push({name:w,phase:C,startMs:y-p,ms:x-y})},reportRender(w){l&&(g={gpuMs:w.gpuMs??g.gpuMs,drawCalls:g.drawCalls+w.drawCalls,triangles:g.triangles+w.triangles,geometries:g.geometries+w.geometries,textures:g.textures+w.textures,renderPasses:w.renderPasses===void 0?g.renderPasses:(g.renderPasses??0)+w.renderPasses})},endFrame(){if(!l&&!h)return;const w=be(),C=u===0?0:p-u;u=p;const x={id:++c,timestamp:w,intervalMs:C,cpuMs:w-p,phases:[...i].map(([b,{ms:P,startMs:A}])=>({name:b,ms:P,startMs:A})).sort((b,P)=>P.ms-b.ms),systems:n.slice(),components:a.slice(),render:{...g}};e.push(x),e.length>600&&e.splice(0,e.length-600),d&&performance.measure("vgai.frame",{start:p,duration:x.cpuMs}),M()},subscribe(w){return t.add(w),()=>{t.delete(w)}},getSnapshot(){return _},exportJSON(){return JSON.stringify({version:2,capturedAt:new Date().toISOString(),frames:e},null,2)}}}const Oa=256;function gc(o){const t=Math.min(1,Math.max(0,o));return t<=.0031308?t*12.92:1.055*t**(1/2.4)-.055}function Fr(o,t,e){const i=Math.hypot(o,t,e)||1;return[o/i,t/i,e/i]}function yc(o=Oa){const t=document.createElement("canvas");t.width=o,t.height=o;const e=t.getContext("2d");if(!e)return t;const i=e.createImageData(o,o),s=Fr(-.45,.62,.64),r=Fr(.65,-.35,.5),n=Fr(s[0],s[1],s[2]+1),a=[.7,.69,.68],l=[.34,.4,.52],h=[.85,.88,1];for(let d=0;d<o;d++)for(let c=0;c<o;c++){const p=(c+.5)/o/.5-1,u=1-(d+.5)/o/.5,f=p*p+u*u,m=f>1,y=m?1/Math.sqrt(f):1,g=p*y,_=u*y,M=m?0:Math.sqrt(Math.max(0,1-f)),w=Math.max(0,g*s[0]+_*s[1]+M*s[2]),C=Math.max(0,g*r[0]+_*r[1]+M*r[2]),x=Math.max(0,g*n[0]+_*n[1]+M*n[2])**42*.5,b=(1-M)**3.2*.4,P=(d*o+c)*4;for(let A=0;A<3;A++){const N=a[A]*(.16+.8*w)+l[A]*.3*C+h[A]*b+x;i.data[P+A]=Math.round(gc(N)*255)}i.data[P+3]=255}return e.putImageData(i,0,0),t}function _c(o=Oa){const t=new ya(yc(o));return t.colorSpace=Ms,t.minFilter=Ui,t.magFilter=Ui,t.generateMipmaps=!1,t.needsUpdate=!0,t}function vc(o){return o.color?.clone()??new B(12502993)}function Br(o,t){return o[t]??null}class xc{_derived=new Map;_normals=new gh;_matcap=null;_matcapTexture=null;_overdraw=new Tt({color:16777215,transparent:!0,opacity:.08,depthTest:!1,depthWrite:!1,blending:bn,side:We,toneMapped:!1});render(t,e,i,s=()=>!0){if(e==="solid"){i();return}const r=[];t.traverse(n=>{const a=n;!a.isMesh||!a.material||!s(a)||(r.push({mesh:a,material:a.material}),a.material=Array.isArray(a.material)?a.material.map(l=>this._materialFor(l,e)):this._materialFor(a.material,e))});try{i()}finally{for(const{mesh:n,material:a}of r)n.material=a}}dispose(){for(const t of this._derived.values())t.clay.dispose(),t.unlit.dispose(),t.wireframe.dispose();this._derived.clear(),this._normals.dispose(),this._overdraw.dispose(),this._matcap?.dispose(),this._matcapTexture?.dispose(),this._matcap=null,this._matcapTexture=null}_materialFor(t,e){if(e==="normals")return this._normals;if(e==="overdraw")return this._overdraw;if(e==="matcap")return this._matcap||(this._matcapTexture=_c(),this._matcap=new yh({matcap:this._matcapTexture,toneMapped:!1})),this._matcap;let i=this._derived.get(t);if(!i){const s={color:vc(t),map:Br(t,"map"),alphaMap:Br(t,"alphaMap"),alphaTest:t.alphaTest,opacity:t.opacity,transparent:t.transparent,side:t.side,depthTest:t.depthTest,depthWrite:t.depthWrite,vertexColors:!!t.vertexColors,fog:t.fog??!0};i={clay:new _a({color:11450048,roughness:.82,metalness:0,flatShading:!0,alphaMap:Br(t,"alphaMap"),alphaTest:t.alphaTest,opacity:t.opacity,transparent:t.transparent,side:t.side,depthTest:t.depthTest,depthWrite:t.depthWrite}),unlit:new Tt(s),wireframe:new Tt({...s,wireframe:!0})},this._derived.set(t,i)}return i[e]}}function or(o){const t=xt(o,"constraints");return Array.isArray(t)?t.filter(e=>!!e&&typeof e=="object"&&typeof e.getSnapshot=="function"&&!!e.config):[]}function Li(o){const t=xt(o,"reflectionProbe");if(!t||typeof t!="object")return null;const e=t;return e.config&&typeof e.recapture=="function"&&typeof e.getSnapshot=="function"?t:null}function mn(o){const t=xt(o,"triggerVolume");if(!t||typeof t!="object")return null;const{radius:e}=t;return typeof e=="number"&&Number.isFinite(e)&&e>0?{radius:e}:null}const Le=new Yt,Et=new v,Me=new v,ot=new wt,wo={X:new v(1,0,0),Y:new v(0,1,0),Z:new v(0,0,1)},Nr={type:"change"},So={type:"mouseDown",mode:null},bo={type:"mouseUp",mode:null},Mo={type:"objectChange"};class Hr extends _h{constructor(t,e=null){super(void 0,e);const i=new Pc(this);this._root=i;const s=new Ac;this._gizmo=s,i.add(s);const r=new Ec;this._plane=r,i.add(r);const n=this;function a(M,w){let C=w;Object.defineProperty(n,M,{get:function(){return C!==void 0?C:w},set:function(x){C!==x&&(C=x,r[M]=x,s[M]=x,n.dispatchEvent({type:M+"-changed",value:x}),n.dispatchEvent(Nr))}}),n[M]=w,r[M]=w,s[M]=w}a("camera",t),a("object",void 0),a("enabled",!0),a("axis",null),a("mode","translate"),a("translationSnap",null),a("rotationSnap",null),a("scaleSnap",null),a("space","world"),a("size",1),a("dragging",!1),a("showX",!0),a("showY",!0),a("showZ",!0),a("minX",-1/0),a("maxX",1/0),a("minY",-1/0),a("maxY",1/0),a("minZ",-1/0),a("maxZ",1/0);const l=new v,h=new v,d=new wt,c=new wt,p=new v,u=new wt,f=new v,m=new v,y=new v,g=0,_=new v;a("worldPosition",l),a("worldPositionStart",h),a("worldQuaternion",d),a("worldQuaternionStart",c),a("cameraPosition",p),a("cameraQuaternion",u),a("pointStart",f),a("pointEnd",m),a("rotationAxis",y),a("rotationAngle",g),a("eye",_),this._offset=new v,this._startNorm=new v,this._endNorm=new v,this._cameraScale=new v,this._parentPosition=new v,this._parentQuaternion=new wt,this._parentQuaternionInv=new wt,this._parentScale=new v,this._worldScaleStart=new v,this._worldQuaternionInv=new wt,this._worldScale=new v,this._positionStart=new v,this._quaternionStart=new wt,this._scaleStart=new v,this._getPointer=wc.bind(this),this._onPointerDown=bc.bind(this),this._onPointerHover=Sc.bind(this),this._onPointerMove=Mc.bind(this),this._onPointerUp=Cc.bind(this),e!==null&&this.connect(e)}connect(t){super.connect(t),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointermove",this._onPointerHover),this.domElement.addEventListener("pointerup",this._onPointerUp),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointermove",this._onPointerHover),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.domElement.style.touchAction="auto"}getHelper(){return this._root}pointerHover(t){if(this.object===void 0||this.dragging===!0)return;t!==null&&Le.setFromCamera(t,this.camera);const e=Lr(this._gizmo.picker[this.mode],Le);e?this.axis=e.object.name:this.axis=null}pointerDown(t){if(!(this.object===void 0||this.dragging===!0||t!=null&&t.button!==0)&&this.axis!==null){t!==null&&Le.setFromCamera(t,this.camera);const e=Lr(this._plane,Le,!0);e&&(this.object.updateMatrixWorld(),this.object.parent.updateMatrixWorld(),this._positionStart.copy(this.object.position),this._quaternionStart.copy(this.object.quaternion),this._scaleStart.copy(this.object.scale),this.object.matrixWorld.decompose(this.worldPositionStart,this.worldQuaternionStart,this._worldScaleStart),this.pointStart.copy(e.point).sub(this.worldPositionStart)),this.dragging=!0,So.mode=this.mode,this.dispatchEvent(So)}}pointerMove(t){const e=this.axis,i=this.mode,s=this.object;let r=this.space;if(i==="scale"?r="local":(e==="E"||e==="XYZE"||e==="XYZ")&&(r="world"),s===void 0||e===null||this.dragging===!1||t!==null&&t.button!==-1)return;t!==null&&Le.setFromCamera(t,this.camera);const n=Lr(this._plane,Le,!0);if(n){if(this.pointEnd.copy(n.point).sub(this.worldPositionStart),i==="translate")this._offset.copy(this.pointEnd).sub(this.pointStart),r==="local"&&e!=="XYZ"&&this._offset.applyQuaternion(this._worldQuaternionInv),e.indexOf("X")===-1&&(this._offset.x=0),e.indexOf("Y")===-1&&(this._offset.y=0),e.indexOf("Z")===-1&&(this._offset.z=0),r==="local"&&e!=="XYZ"?this._offset.applyQuaternion(this._quaternionStart).divide(this._parentScale):this._offset.applyQuaternion(this._parentQuaternionInv).divide(this._parentScale),s.position.copy(this._offset).add(this._positionStart),this.translationSnap&&(r==="local"&&(s.position.applyQuaternion(ot.copy(this._quaternionStart).invert()),e.search("X")!==-1&&(s.position.x=Math.round(s.position.x/this.translationSnap)*this.translationSnap),e.search("Y")!==-1&&(s.position.y=Math.round(s.position.y/this.translationSnap)*this.translationSnap),e.search("Z")!==-1&&(s.position.z=Math.round(s.position.z/this.translationSnap)*this.translationSnap),s.position.applyQuaternion(this._quaternionStart)),r==="world"&&(s.parent&&s.position.add(Et.setFromMatrixPosition(s.parent.matrixWorld)),e.search("X")!==-1&&(s.position.x=Math.round(s.position.x/this.translationSnap)*this.translationSnap),e.search("Y")!==-1&&(s.position.y=Math.round(s.position.y/this.translationSnap)*this.translationSnap),e.search("Z")!==-1&&(s.position.z=Math.round(s.position.z/this.translationSnap)*this.translationSnap),s.parent&&s.position.sub(Et.setFromMatrixPosition(s.parent.matrixWorld)))),s.position.x=Math.max(this.minX,Math.min(this.maxX,s.position.x)),s.position.y=Math.max(this.minY,Math.min(this.maxY,s.position.y)),s.position.z=Math.max(this.minZ,Math.min(this.maxZ,s.position.z));else if(i==="scale"){if(e.search("XYZ")!==-1){let a=this.pointEnd.length()/this.pointStart.length();this.pointEnd.dot(this.pointStart)<0&&(a*=-1),Me.set(a,a,a)}else Et.copy(this.pointStart),Me.copy(this.pointEnd),Et.applyQuaternion(this._worldQuaternionInv),Me.applyQuaternion(this._worldQuaternionInv),Me.divide(Et),e.search("X")===-1&&(Me.x=1),e.search("Y")===-1&&(Me.y=1),e.search("Z")===-1&&(Me.z=1);s.scale.copy(this._scaleStart).multiply(Me),this.scaleSnap&&(e.search("X")!==-1&&(s.scale.x=Math.round(s.scale.x/this.scaleSnap)*this.scaleSnap||this.scaleSnap),e.search("Y")!==-1&&(s.scale.y=Math.round(s.scale.y/this.scaleSnap)*this.scaleSnap||this.scaleSnap),e.search("Z")!==-1&&(s.scale.z=Math.round(s.scale.z/this.scaleSnap)*this.scaleSnap||this.scaleSnap))}else if(i==="rotate"){this._offset.copy(this.pointEnd).sub(this.pointStart);const a=20/this.worldPosition.distanceTo(Et.setFromMatrixPosition(this.camera.matrixWorld));let l=!1;e==="XYZE"?(this.rotationAxis.copy(this._offset).cross(this.eye).normalize(),this.rotationAngle=this._offset.dot(Et.copy(this.rotationAxis).cross(this.eye))*a):(e==="X"||e==="Y"||e==="Z")&&(this.rotationAxis.copy(wo[e]),Et.copy(wo[e]),r==="local"&&Et.applyQuaternion(this.worldQuaternion),Et.cross(this.eye),Et.length()===0?l=!0:this.rotationAngle=this._offset.dot(Et.normalize())*a),(e==="E"||l)&&(this.rotationAxis.copy(this.eye),this.rotationAngle=this.pointEnd.angleTo(this.pointStart),this._startNorm.copy(this.pointStart).normalize(),this._endNorm.copy(this.pointEnd).normalize(),this.rotationAngle*=this._endNorm.cross(this._startNorm).dot(this.eye)<0?1:-1),this.rotationSnap&&(this.rotationAngle=Math.round(this.rotationAngle/this.rotationSnap)*this.rotationSnap),r==="local"&&e!=="E"&&e!=="XYZE"?(s.quaternion.copy(this._quaternionStart),s.quaternion.multiply(ot.setFromAxisAngle(this.rotationAxis,this.rotationAngle)).normalize()):(this.rotationAxis.applyQuaternion(this._parentQuaternionInv),s.quaternion.copy(ot.setFromAxisAngle(this.rotationAxis,this.rotationAngle)),s.quaternion.multiply(this._quaternionStart).normalize())}this.dispatchEvent(Nr),this.dispatchEvent(Mo)}}pointerUp(t){t!==null&&t.button!==0||(this.dragging&&this.axis!==null&&(bo.mode=this.mode,this.dispatchEvent(bo)),this.dragging=!1,this.axis=null)}dispose(){this.disconnect(),this._root.dispose()}attach(t){return this.object=t,this._root.visible=!0,this}detach(){return this.object=void 0,this.axis=null,this._root.visible=!1,this}reset(){this.enabled&&this.dragging&&(this.object.position.copy(this._positionStart),this.object.quaternion.copy(this._quaternionStart),this.object.scale.copy(this._scaleStart),this.dispatchEvent(Nr),this.dispatchEvent(Mo),this.pointStart.copy(this.pointEnd))}getRaycaster(){return Le}getMode(){return this.mode}setMode(t){this.mode=t}setTranslationSnap(t){this.translationSnap=t}setRotationSnap(t){this.rotationSnap=t}setScaleSnap(t){this.scaleSnap=t}setSize(t){this.size=t}setSpace(t){this.space=t}setColors(t,e,i,s){const r=this._gizmo.materialLib;r.xAxis.color.set(t),r.yAxis.color.set(e),r.zAxis.color.set(i),r.active.color.set(s),r.xAxisTransparent.color.set(t),r.yAxisTransparent.color.set(e),r.zAxisTransparent.color.set(i),r.activeTransparent.color.set(s),r.xAxis._color&&r.xAxis._color.set(t),r.yAxis._color&&r.yAxis._color.set(e),r.zAxis._color&&r.zAxis._color.set(i),r.active._color&&r.active._color.set(s),r.xAxisTransparent._color&&r.xAxisTransparent._color.set(t),r.yAxisTransparent._color&&r.yAxisTransparent._color.set(e),r.zAxisTransparent._color&&r.zAxisTransparent._color.set(i),r.activeTransparent._color&&r.activeTransparent._color.set(s)}}function wc(o){if(this.domElement.ownerDocument.pointerLockElement)return{x:0,y:0,button:o.button};{const t=this.domElement.getBoundingClientRect();return{x:(o.clientX-t.left)/t.width*2-1,y:-(o.clientY-t.top)/t.height*2+1,button:o.button}}}function Sc(o){if(this.enabled)switch(o.pointerType){case"mouse":case"pen":this.pointerHover(this._getPointer(o));break}}function bc(o){this.enabled&&(document.pointerLockElement||this.domElement.setPointerCapture(o.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.pointerHover(this._getPointer(o)),this.pointerDown(this._getPointer(o)))}function Mc(o){this.enabled&&this.pointerMove(this._getPointer(o))}function Cc(o){this.enabled&&(this.domElement.releasePointerCapture(o.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.pointerUp(this._getPointer(o)))}function Lr(o,t,e){const i=t.intersectObject(o,!0);for(let s=0;s<i.length;s++)if(i[s].object.visible||e)return i[s];return!1}const Ws=new va,it=new v(0,1,0),Co=new v(0,0,0),Po=new Mn,Js=new wt,rr=new wt,$t=new v,Ao=new Mn,Bi=new v(1,0,0),Ue=new v(0,1,0),Ni=new v(0,0,1),Ys=new v,Oi=new v,Ii=new v;class Pc extends Je{constructor(t){super(),this.isTransformControlsRoot=!0,this.controls=t,this.visible=!1}updateMatrixWorld(t){const e=this.controls;e.object!==void 0&&(e.object.updateMatrixWorld(),e.object.parent===null?console.error("TransformControls: The attached 3D object must be a part of the scene graph."):e.object.parent.matrixWorld.decompose(e._parentPosition,e._parentQuaternion,e._parentScale),e.object.matrixWorld.decompose(e.worldPosition,e.worldQuaternion,e._worldScale),e._parentQuaternionInv.copy(e._parentQuaternion).invert(),e._worldQuaternionInv.copy(e.worldQuaternion).invert()),e.camera.updateMatrixWorld(),e.camera.matrixWorld.decompose(e.cameraPosition,e.cameraQuaternion,e._cameraScale),e.camera.isOrthographicCamera?e.camera.getWorldDirection(e.eye).negate():e.eye.copy(e.cameraPosition).sub(e.worldPosition).normalize(),super.updateMatrixWorld(t)}dispose(){this.traverse(function(t){t.geometry&&t.geometry.dispose(),t.material&&t.material.dispose()})}}class Ac extends Je{constructor(){super(),this.isTransformControlsGizmo=!0,this.type="TransformControlsGizmo";const t=new Tt({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),e=new Ze({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),i=t.clone();i.opacity=.15;const s=e.clone();s.opacity=.5;const r=t.clone();r.color.setHex(16711680);const n=t.clone();n.color.setHex(65280);const a=t.clone();a.color.setHex(255);const l=t.clone();l.color.setHex(16711680),l.opacity=.5;const h=t.clone();h.color.setHex(65280),h.opacity=.5;const d=t.clone();d.color.setHex(255),d.opacity=.5;const c=t.clone();c.opacity=.25;const p=t.clone();p.color.setHex(16776960),p.opacity=.25;const u=t.clone();u.color.setHex(16776960);const f=t.clone();f.color.setHex(7895160),this.materialLib={xAxis:r,yAxis:n,zAxis:a,active:u,xAxisTransparent:l,yAxisTransparent:h,zAxisTransparent:d,activeTransparent:p};const m=new Ot(0,.04,.1,12);m.translate(0,.05,0);const y=new mt(.08,.08,.08);y.translate(0,.04,0);const g=new Re;g.setAttribute("position",new Vi([0,0,0,1,0,0],3));const _=new Ot(.0075,.0075,.5,3);_.translate(0,.25,0);function M(K,lt){const st=new zi(K,.0075,3,64,lt*Math.PI*2);return st.rotateY(Math.PI/2),st.rotateX(Math.PI/2),st}function w(){const K=new Re;return K.setAttribute("position",new Vi([0,0,0,1,1,1],3)),K}const C={X:[[new E(m,r),[.5,0,0],[0,0,-Math.PI/2]],[new E(m,r),[-.5,0,0],[0,0,Math.PI/2]],[new E(_,r),[0,0,0],[0,0,-Math.PI/2]]],Y:[[new E(m,n),[0,.5,0]],[new E(m,n),[0,-.5,0],[Math.PI,0,0]],[new E(_,n)]],Z:[[new E(m,a),[0,0,.5],[Math.PI/2,0,0]],[new E(m,a),[0,0,-.5],[-Math.PI/2,0,0]],[new E(_,a),null,[Math.PI/2,0,0]]],XYZ:[[new E(new Ve(.1,0),c),[0,0,0]]],XY:[[new E(new mt(.15,.15,.01),d),[.15,.15,0]]],YZ:[[new E(new mt(.15,.15,.01),l),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new E(new mt(.15,.15,.01),h),[.15,0,.15],[-Math.PI/2,0,0]]]},x={X:[[new E(new Ot(.2,0,.6,4),i),[.3,0,0],[0,0,-Math.PI/2]],[new E(new Ot(.2,0,.6,4),i),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new E(new Ot(.2,0,.6,4),i),[0,.3,0]],[new E(new Ot(.2,0,.6,4),i),[0,-.3,0],[0,0,Math.PI]]],Z:[[new E(new Ot(.2,0,.6,4),i),[0,0,.3],[Math.PI/2,0,0]],[new E(new Ot(.2,0,.6,4),i),[0,0,-.3],[-Math.PI/2,0,0]]],XYZ:[[new E(new Ve(.2,0),i)]],XY:[[new E(new mt(.2,.2,.01),i),[.15,.15,0]]],YZ:[[new E(new mt(.2,.2,.01),i),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new E(new mt(.2,.2,.01),i),[.15,0,.15],[-Math.PI/2,0,0]]]},b={START:[[new E(new Ve(.01,2),s),null,null,null,"helper"]],END:[[new E(new Ve(.01,2),s),null,null,null,"helper"]],DELTA:[[new Wt(w(),s),null,null,null,"helper"]],X:[[new Wt(g,s),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new Wt(g,s),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new Wt(g,s),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]},P={XYZE:[[new E(M(.5,1),f),null,[0,Math.PI/2,0]]],X:[[new E(M(.5,.5),r)]],Y:[[new E(M(.5,.5),n),null,[0,0,-Math.PI/2]]],Z:[[new E(M(.5,.5),a),null,[0,Math.PI/2,0]]],E:[[new E(M(.75,1),p),null,[0,Math.PI/2,0]]]},A={AXIS:[[new Wt(g,s),[-1e3,0,0],null,[1e6,1,1],"helper"]]},N={XYZE:[[new E(new fe(.25,10,8),i)]],X:[[new E(new zi(.5,.1,4,24),i),[0,0,0],[0,-Math.PI/2,-Math.PI/2]]],Y:[[new E(new zi(.5,.1,4,24),i),[0,0,0],[Math.PI/2,0,0]]],Z:[[new E(new zi(.5,.1,4,24),i),[0,0,0],[0,0,-Math.PI/2]]],E:[[new E(new zi(.75,.1,2,24),i)]]},J={X:[[new E(y,r),[.5,0,0],[0,0,-Math.PI/2]],[new E(_,r),[0,0,0],[0,0,-Math.PI/2]],[new E(y,r),[-.5,0,0],[0,0,Math.PI/2]]],Y:[[new E(y,n),[0,.5,0]],[new E(_,n)],[new E(y,n),[0,-.5,0],[0,0,Math.PI]]],Z:[[new E(y,a),[0,0,.5],[Math.PI/2,0,0]],[new E(_,a),[0,0,0],[Math.PI/2,0,0]],[new E(y,a),[0,0,-.5],[-Math.PI/2,0,0]]],XY:[[new E(new mt(.15,.15,.01),d),[.15,.15,0]]],YZ:[[new E(new mt(.15,.15,.01),l),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new E(new mt(.15,.15,.01),h),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new E(new mt(.1,.1,.1),c)]]},$={X:[[new E(new Ot(.2,0,.6,4),i),[.3,0,0],[0,0,-Math.PI/2]],[new E(new Ot(.2,0,.6,4),i),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new E(new Ot(.2,0,.6,4),i),[0,.3,0]],[new E(new Ot(.2,0,.6,4),i),[0,-.3,0],[0,0,Math.PI]]],Z:[[new E(new Ot(.2,0,.6,4),i),[0,0,.3],[Math.PI/2,0,0]],[new E(new Ot(.2,0,.6,4),i),[0,0,-.3],[-Math.PI/2,0,0]]],XY:[[new E(new mt(.2,.2,.01),i),[.15,.15,0]]],YZ:[[new E(new mt(.2,.2,.01),i),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new E(new mt(.2,.2,.01),i),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new E(new mt(.2,.2,.2),i),[0,0,0]]]},gt={X:[[new Wt(g,s),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new Wt(g,s),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new Wt(g,s),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]};function Y(K){const lt=new Je;for(const st in K)for(let ct=K[st].length;ct--;){const tt=K[st][ct][0].clone(),dt=K[st][ct][1],ut=K[st][ct][2],V=K[st][ct][3],yt=K[st][ct][4];tt.name=st,tt.tag=yt,dt&&tt.position.set(dt[0],dt[1],dt[2]),ut&&tt.rotation.set(ut[0],ut[1],ut[2]),V&&tt.scale.set(V[0],V[1],V[2]),tt.updateMatrix();const D=tt.geometry.clone();D.applyMatrix4(tt.matrix),tt.geometry=D,tt.renderOrder=1/0,tt.position.set(0,0,0),tt.rotation.set(0,0,0),tt.scale.set(1,1,1),lt.add(tt)}return lt}this.gizmo={},this.picker={},this.helper={},this.add(this.gizmo.translate=Y(C)),this.add(this.gizmo.rotate=Y(P)),this.add(this.gizmo.scale=Y(J)),this.add(this.picker.translate=Y(x)),this.add(this.picker.rotate=Y(N)),this.add(this.picker.scale=Y($)),this.add(this.helper.translate=Y(b)),this.add(this.helper.rotate=Y(A)),this.add(this.helper.scale=Y(gt)),this.picker.translate.visible=!1,this.picker.rotate.visible=!1,this.picker.scale.visible=!1}updateMatrixWorld(t){const i=(this.mode==="scale"?"local":this.space)==="local"?this.worldQuaternion:rr;this.gizmo.translate.visible=this.mode==="translate",this.gizmo.rotate.visible=this.mode==="rotate",this.gizmo.scale.visible=this.mode==="scale",this.helper.translate.visible=this.mode==="translate",this.helper.rotate.visible=this.mode==="rotate",this.helper.scale.visible=this.mode==="scale";let s=[];s=s.concat(this.picker[this.mode].children),s=s.concat(this.gizmo[this.mode].children),s=s.concat(this.helper[this.mode].children);for(let r=0;r<s.length;r++){const n=s[r];n.visible=!0,n.rotation.set(0,0,0),n.position.copy(this.worldPosition);let a;if(this.camera.isOrthographicCamera?a=(this.camera.top-this.camera.bottom)/this.camera.zoom:a=this.worldPosition.distanceTo(this.cameraPosition)*Math.min(1.9*Math.tan(Math.PI*this.camera.fov/360)/this.camera.zoom,7),n.scale.set(1,1,1).multiplyScalar(a*this.size/4),n.tag==="helper"){n.visible=!1,n.name==="AXIS"?(n.visible=!!this.axis,this.axis==="X"&&(ot.setFromEuler(Ws.set(0,0,0)),n.quaternion.copy(i).multiply(ot),Math.abs(it.copy(Bi).applyQuaternion(i).dot(this.eye))>.9&&(n.visible=!1)),this.axis==="Y"&&(ot.setFromEuler(Ws.set(0,0,Math.PI/2)),n.quaternion.copy(i).multiply(ot),Math.abs(it.copy(Ue).applyQuaternion(i).dot(this.eye))>.9&&(n.visible=!1)),this.axis==="Z"&&(ot.setFromEuler(Ws.set(0,Math.PI/2,0)),n.quaternion.copy(i).multiply(ot),Math.abs(it.copy(Ni).applyQuaternion(i).dot(this.eye))>.9&&(n.visible=!1)),this.axis==="XYZE"&&(ot.setFromEuler(Ws.set(0,Math.PI/2,0)),it.copy(this.rotationAxis),n.quaternion.setFromRotationMatrix(Po.lookAt(Co,it,Ue)),n.quaternion.multiply(ot),n.visible=this.dragging),this.axis==="E"&&(n.visible=!1)):n.name==="START"?(n.position.copy(this.worldPositionStart),n.visible=this.dragging):n.name==="END"?(n.position.copy(this.worldPosition),n.visible=this.dragging):n.name==="DELTA"?(n.position.copy(this.worldPositionStart),n.quaternion.copy(this.worldQuaternionStart),Et.set(1e-10,1e-10,1e-10).add(this.worldPositionStart).sub(this.worldPosition).multiplyScalar(-1),Et.applyQuaternion(this.worldQuaternionStart.clone().invert()),n.scale.copy(Et),n.visible=this.dragging):(n.quaternion.copy(i),this.dragging?n.position.copy(this.worldPositionStart):n.position.copy(this.worldPosition),this.axis&&(n.visible=this.axis.search(n.name)!==-1));continue}n.quaternion.copy(i),this.mode==="translate"||this.mode==="scale"?(n.name==="X"&&Math.abs(it.copy(Bi).applyQuaternion(i).dot(this.eye))>.99&&(n.scale.set(1e-10,1e-10,1e-10),n.visible=!1),n.name==="Y"&&Math.abs(it.copy(Ue).applyQuaternion(i).dot(this.eye))>.99&&(n.scale.set(1e-10,1e-10,1e-10),n.visible=!1),n.name==="Z"&&Math.abs(it.copy(Ni).applyQuaternion(i).dot(this.eye))>.99&&(n.scale.set(1e-10,1e-10,1e-10),n.visible=!1),n.name==="XY"&&Math.abs(it.copy(Ni).applyQuaternion(i).dot(this.eye))<.2&&(n.scale.set(1e-10,1e-10,1e-10),n.visible=!1),n.name==="YZ"&&Math.abs(it.copy(Bi).applyQuaternion(i).dot(this.eye))<.2&&(n.scale.set(1e-10,1e-10,1e-10),n.visible=!1),n.name==="XZ"&&Math.abs(it.copy(Ue).applyQuaternion(i).dot(this.eye))<.2&&(n.scale.set(1e-10,1e-10,1e-10),n.visible=!1)):this.mode==="rotate"&&(Js.copy(i),it.copy(this.eye).applyQuaternion(ot.copy(i).invert()),n.name.search("E")!==-1&&n.quaternion.setFromRotationMatrix(Po.lookAt(this.eye,Co,Ue)),n.name==="X"&&(ot.setFromAxisAngle(Bi,Math.atan2(-it.y,it.z)),ot.multiplyQuaternions(Js,ot),n.quaternion.copy(ot)),n.name==="Y"&&(ot.setFromAxisAngle(Ue,Math.atan2(it.x,it.z)),ot.multiplyQuaternions(Js,ot),n.quaternion.copy(ot)),n.name==="Z"&&(ot.setFromAxisAngle(Ni,Math.atan2(it.y,it.x)),ot.multiplyQuaternions(Js,ot),n.quaternion.copy(ot))),n.visible=n.visible&&(n.name.indexOf("X")===-1||this.showX),n.visible=n.visible&&(n.name.indexOf("Y")===-1||this.showY),n.visible=n.visible&&(n.name.indexOf("Z")===-1||this.showZ),n.visible=n.visible&&(n.name.indexOf("E")===-1||this.showX&&this.showY&&this.showZ),n.material._color=n.material._color||n.material.color.clone(),n.material._opacity=n.material._opacity||n.material.opacity,n.material.color.copy(n.material._color),n.material.opacity=n.material._opacity,this.enabled&&this.axis&&(n.name===this.axis?(n.material.color.copy(this.materialLib.active.color),n.material.opacity=1):this.axis.split("").some(function(l){return n.name===l})&&(n.material.color.copy(this.materialLib.active.color),n.material.opacity=1))}super.updateMatrixWorld(t)}}class Ec extends E{constructor(){super(new Cn(1e5,1e5,2,2),new Tt({visible:!1,wireframe:!0,side:We,transparent:!0,opacity:.1,toneMapped:!1})),this.isTransformControlsPlane=!0,this.type="TransformControlsPlane"}updateMatrixWorld(t){let e=this.space;switch(this.position.copy(this.worldPosition),this.mode==="scale"&&(e="local"),Ys.copy(Bi).applyQuaternion(e==="local"?this.worldQuaternion:rr),Oi.copy(Ue).applyQuaternion(e==="local"?this.worldQuaternion:rr),Ii.copy(Ni).applyQuaternion(e==="local"?this.worldQuaternion:rr),it.copy(Oi),this.mode){case"translate":case"scale":switch(this.axis){case"X":it.copy(this.eye).cross(Ys),$t.copy(Ys).cross(it);break;case"Y":it.copy(this.eye).cross(Oi),$t.copy(Oi).cross(it);break;case"Z":it.copy(this.eye).cross(Ii),$t.copy(Ii).cross(it);break;case"XY":$t.copy(Ii);break;case"YZ":$t.copy(Ys);break;case"XZ":it.copy(Ii),$t.copy(Oi);break;case"XYZ":case"E":$t.set(0,0,0);break}break;case"rotate":default:$t.set(0,0,0)}$t.length()===0?this.quaternion.copy(this.cameraQuaternion):(Ao.lookAt(Et.set(0,0,0),$t,it),this.quaternion.setFromRotationMatrix(Ao)),super.updateMatrixWorld(t)}}const At=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"];let Eo=1234567;const Ia=Math.PI/180,Ra=180/Math.PI;function Tc(){const o=Math.random()*4294967295|0,t=Math.random()*4294967295|0,e=Math.random()*4294967295|0,i=Math.random()*4294967295|0;return(At[o&255]+At[o>>8&255]+At[o>>16&255]+At[o>>24&255]+"-"+At[t&255]+At[t>>8&255]+"-"+At[t>>16&15|64]+At[t>>24&255]+"-"+At[e&63|128]+At[e>>8&255]+"-"+At[e>>16&255]+At[e>>24&255]+At[i&255]+At[i>>8&255]+At[i>>16&255]+At[i>>24&255]).toLowerCase()}function ee(o,t,e){return Math.max(t,Math.min(e,o))}function ka(o,t){return(o%t+t)%t}function zc(o,t,e,i,s){return i+(o-t)*(s-i)/(e-t)}function Oc(o,t,e){return o!==t?(e-o)/(t-o):0}function Fa(o,t,e){return(1-e)*o+e*t}function Ic(o,t,e,i){return Fa(o,t,1-Math.exp(-e*i))}function Rc(o,t=1){return t-Math.abs(ka(o,t*2)-t)}function kc(o,t,e){return o<=t?0:o>=e?1:(o=(o-t)/(e-t),o*o*(3-2*o))}function Fc(o,t,e){return o<=t?0:o>=e?1:(o=(o-t)/(e-t),o*o*o*(o*(o*6-15)+10))}function Bc(o,t){return o+Math.floor(Math.random()*(t-o+1))}function Nc(o,t){return o+Math.random()*(t-o)}function Hc(o){return o*(.5-Math.random())}function Lc(o){o!==void 0&&(Eo=o);let t=Eo+=1831565813;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}function Dc(o){return o*Ia}function Uc(o){return o*Ra}function Vc(o){return(o&o-1)===0&&o!==0}function jc(o){return Math.pow(2,Math.ceil(Math.log(o)/Math.LN2))}function Gc(o){return Math.pow(2,Math.floor(Math.log(o)/Math.LN2))}function Xc(o,t,e,i,s){const r=Math.cos,n=Math.sin,a=r(e/2),l=n(e/2),h=r((t+i)/2),d=n((t+i)/2),c=r((t-i)/2),p=n((t-i)/2),u=r((i-t)/2),f=n((i-t)/2);switch(s){case"XYX":o.set(a*d,l*c,l*p,a*h);break;case"YZY":o.set(l*p,a*d,l*c,a*h);break;case"ZXZ":o.set(l*c,l*p,a*d,a*h);break;case"XZX":o.set(a*d,l*f,l*u,a*h);break;case"YXY":o.set(l*u,a*d,l*f,a*h);break;case"ZYZ":o.set(l*f,l*u,a*d,a*h);break;default:console.warn("../math.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+s)}}function Wc(o,t){switch(t.constructor){case Float32Array:return o;case Uint32Array:return o/4294967295;case Uint16Array:return o/65535;case Uint8Array:return o/255;case Int32Array:return Math.max(o/2147483647,-1);case Int16Array:return Math.max(o/32767,-1);case Int8Array:return Math.max(o/127,-1);default:throw new Error("Invalid component type.")}}function Jc(o,t){switch(t.constructor){case Float32Array:return o;case Uint32Array:return Math.round(o*4294967295);case Uint16Array:return Math.round(o*65535);case Uint8Array:return Math.round(o*255);case Int32Array:return Math.round(o*2147483647);case Int16Array:return Math.round(o*32767);case Int8Array:return Math.round(o*127);default:throw new Error("Invalid component type.")}}const Si={DEG2RAD:Ia,RAD2DEG:Ra,generateUUID:Tc,clamp:ee,euclideanModulo:ka,mapLinear:zc,inverseLerp:Oc,lerp:Fa,damp:Ic,pingpong:Rc,smoothstep:kc,smootherstep:Fc,randInt:Bc,randFloat:Nc,randFloatSpread:Hc,seededRandom:Lc,degToRad:Dc,radToDeg:Uc,isPowerOfTwo:Vc,ceilPowerOfTwo:jc,floorPowerOfTwo:Gc,setQuaternionFromProperEuler:Xc,normalize:Jc,denormalize:Wc};class W{constructor(t=0,e=0,i=0,s=1){this.isQuaternion=!0,this._x=t,this._y=e,this._z=i,this._w=s}static slerpFlat(t,e,i,s,r,n,a){let l=i[s+0],h=i[s+1],d=i[s+2],c=i[s+3];const p=r[n+0],u=r[n+1],f=r[n+2],m=r[n+3];if(a===0){t[e+0]=l,t[e+1]=h,t[e+2]=d,t[e+3]=c;return}if(a===1){t[e+0]=p,t[e+1]=u,t[e+2]=f,t[e+3]=m;return}if(c!==m||l!==p||h!==u||d!==f){let y=1-a;const g=l*p+h*u+d*f+c*m,_=g>=0?1:-1,M=1-g*g;if(M>Number.EPSILON){const C=Math.sqrt(M),x=Math.atan2(C,g*_);y=Math.sin(y*x)/C,a=Math.sin(a*x)/C}const w=a*_;if(l=l*y+p*w,h=h*y+u*w,d=d*y+f*w,c=c*y+m*w,y===1-a){const C=1/Math.sqrt(l*l+h*h+d*d+c*c);l*=C,h*=C,d*=C,c*=C}}t[e]=l,t[e+1]=h,t[e+2]=d,t[e+3]=c}static multiplyQuaternionsFlat(t,e,i,s,r,n){const a=i[s],l=i[s+1],h=i[s+2],d=i[s+3],c=r[n],p=r[n+1],u=r[n+2],f=r[n+3];return t[e]=a*f+d*c+l*u-h*p,t[e+1]=l*f+d*p+h*c-a*u,t[e+2]=h*f+d*u+a*p-l*c,t[e+3]=d*f-a*c-l*p-h*u,t}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get w(){return this._w}set w(t){this._w=t,this._onChangeCallback()}set(t,e,i,s){return this._x=t,this._y=e,this._z=i,this._w=s,this._onChangeCallback(),this}clone(){return new W(this._x,this._y,this._z,this._w)}copy(t){return this._x=t.x,this._y=t.y,this._z=t.z,this._w=t.w,this._onChangeCallback(),this}setFromEuler(t,e=!0){const i=t._x,s=t._y,r=t._z,n=t._order,a=Math.cos,l=Math.sin,h=a(i/2),d=a(s/2),c=a(r/2),p=l(i/2),u=l(s/2),f=l(r/2);switch(n){case"XYZ":this._x=p*d*c+h*u*f,this._y=h*u*c-p*d*f,this._z=h*d*f+p*u*c,this._w=h*d*c-p*u*f;break;case"YXZ":this._x=p*d*c+h*u*f,this._y=h*u*c-p*d*f,this._z=h*d*f-p*u*c,this._w=h*d*c+p*u*f;break;case"ZXY":this._x=p*d*c-h*u*f,this._y=h*u*c+p*d*f,this._z=h*d*f+p*u*c,this._w=h*d*c-p*u*f;break;case"ZYX":this._x=p*d*c-h*u*f,this._y=h*u*c+p*d*f,this._z=h*d*f-p*u*c,this._w=h*d*c+p*u*f;break;case"YZX":this._x=p*d*c+h*u*f,this._y=h*u*c+p*d*f,this._z=h*d*f-p*u*c,this._w=h*d*c-p*u*f;break;case"XZY":this._x=p*d*c-h*u*f,this._y=h*u*c-p*d*f,this._z=h*d*f+p*u*c,this._w=h*d*c+p*u*f;break;default:console.warn("../math.Quaternion: .setFromEuler() encountered an unknown order: "+n)}return e===!0&&this._onChangeCallback(),this}setFromAxisAngle(t,e){const i=e/2,s=Math.sin(i);return this._x=t.x*s,this._y=t.y*s,this._z=t.z*s,this._w=Math.cos(i),this._onChangeCallback(),this}setFromRotationMatrix(t){const e=t.elements,i=e[0],s=e[4],r=e[8],n=e[1],a=e[5],l=e[9],h=e[2],d=e[6],c=e[10],p=i+a+c;if(p>0){const u=.5/Math.sqrt(p+1);this._w=.25/u,this._x=(d-l)*u,this._y=(r-h)*u,this._z=(n-s)*u}else if(i>a&&i>c){const u=2*Math.sqrt(1+i-a-c);this._w=(d-l)/u,this._x=.25*u,this._y=(s+n)/u,this._z=(r+h)/u}else if(a>c){const u=2*Math.sqrt(1+a-i-c);this._w=(r-h)/u,this._x=(s+n)/u,this._y=.25*u,this._z=(l+d)/u}else{const u=2*Math.sqrt(1+c-i-a);this._w=(n-s)/u,this._x=(r+h)/u,this._y=(l+d)/u,this._z=.25*u}return this._onChangeCallback(),this}setFromUnitVectors(t,e){let i=t.dot(e)+1;return i<Number.EPSILON?(i=0,Math.abs(t.x)>Math.abs(t.z)?(this._x=-t.y,this._y=t.x,this._z=0,this._w=i):(this._x=0,this._y=-t.z,this._z=t.y,this._w=i)):(this._x=t.y*e.z-t.z*e.y,this._y=t.z*e.x-t.x*e.z,this._z=t.x*e.y-t.y*e.x,this._w=i),this.normalize()}angleTo(t){return 2*Math.acos(Math.abs(ee(this.dot(t),-1,1)))}rotateTowards(t,e){const i=this.angleTo(t);if(i===0)return this;const s=Math.min(1,e/i);return this.slerp(t,s),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(t){return this._x*t._x+this._y*t._y+this._z*t._z+this._w*t._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let t=this.length();return t===0?(this._x=0,this._y=0,this._z=0,this._w=1):(t=1/t,this._x=this._x*t,this._y=this._y*t,this._z=this._z*t,this._w=this._w*t),this._onChangeCallback(),this}multiply(t){return this.multiplyQuaternions(this,t)}premultiply(t){return this.multiplyQuaternions(t,this)}multiplyQuaternions(t,e){const i=t._x,s=t._y,r=t._z,n=t._w,a=e._x,l=e._y,h=e._z,d=e._w;return this._x=i*d+n*a+s*h-r*l,this._y=s*d+n*l+r*a-i*h,this._z=r*d+n*h+i*l-s*a,this._w=n*d-i*a-s*l-r*h,this._onChangeCallback(),this}slerp(t,e){if(e===0)return this;if(e===1)return this.copy(t);const i=this._x,s=this._y,r=this._z,n=this._w;let a=n*t._w+i*t._x+s*t._y+r*t._z;if(a<0?(this._w=-t._w,this._x=-t._x,this._y=-t._y,this._z=-t._z,a=-a):this.copy(t),a>=1)return this._w=n,this._x=i,this._y=s,this._z=r,this;const l=1-a*a;if(l<=Number.EPSILON){const u=1-e;return this._w=u*n+e*this._w,this._x=u*i+e*this._x,this._y=u*s+e*this._y,this._z=u*r+e*this._z,this.normalize(),this}const h=Math.sqrt(l),d=Math.atan2(h,a),c=Math.sin((1-e)*d)/h,p=Math.sin(e*d)/h;return this._w=n*c+this._w*p,this._x=i*c+this._x*p,this._y=s*c+this._y*p,this._z=r*c+this._z*p,this._onChangeCallback(),this}slerpQuaternions(t,e,i){return this.copy(t).slerp(e,i)}random(){const t=2*Math.PI*Math.random(),e=2*Math.PI*Math.random(),i=Math.random(),s=Math.sqrt(1-i),r=Math.sqrt(i);return this.set(s*Math.sin(t),s*Math.cos(t),r*Math.sin(e),r*Math.cos(e))}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._w===this._w}fromArray(t,e=0){return this._x=t[e],this._y=t[e+1],this._z=t[e+2],this._w=t[e+3],this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._w,t}toJSON(){return this.toArray()}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class I{constructor(t=0,e=0,i=0){this.isVector3=!0,I.prototype.isVector3=!0,this.x=t,this.y=e,this.z=i}set(t,e,i){return i===void 0&&(i=this.z),this.x=t,this.y=e,this.z=i,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+t)}}clone(){return new I(this.x,this.y,this.z)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this}multiplyVectors(t,e){return this.x=t.x*e.x,this.y=t.y*e.y,this.z=t.z*e.z,this}applyEuler(t){return this.applyQuaternion(To.setFromEuler(t))}applyAxisAngle(t,e){return this.applyQuaternion(To.setFromAxisAngle(t,e))}applyMatrix3(t){const e=this.x,i=this.y,s=this.z,r=t.elements;return this.x=r[0]*e+r[3]*i+r[6]*s,this.y=r[1]*e+r[4]*i+r[7]*s,this.z=r[2]*e+r[5]*i+r[8]*s,this}applyNormalMatrix(t){return this.applyMatrix3(t).normalize()}applyMatrix4(t){const e=this.x,i=this.y,s=this.z,r=t.elements,n=1/(r[3]*e+r[7]*i+r[11]*s+r[15]);return this.x=(r[0]*e+r[4]*i+r[8]*s+r[12])*n,this.y=(r[1]*e+r[5]*i+r[9]*s+r[13])*n,this.z=(r[2]*e+r[6]*i+r[10]*s+r[14])*n,this}applyQuaternion(t){const e=this.x,i=this.y,s=this.z,r=t.x,n=t.y,a=t.z,l=t.w,h=2*(n*s-a*i),d=2*(a*e-r*s),c=2*(r*i-n*e);return this.x=e+l*h+n*c-a*d,this.y=i+l*d+a*h-r*c,this.z=s+l*c+r*d-n*h,this}transformDirection(t){const e=this.x,i=this.y,s=this.z,r=t.elements;return this.x=r[0]*e+r[4]*i+r[8]*s,this.y=r[1]*e+r[5]*i+r[9]*s,this.z=r[2]*e+r[6]*i+r[10]*s,this.normalize()}divide(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this}divideScalar(t){return this.multiplyScalar(1/t)}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this}clamp(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this.z=Math.max(t.z,Math.min(e.z,this.z)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this.z=Math.max(t,Math.min(e,this.z)),this}clampLength(t,e){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Math.max(t,Math.min(e,i)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this}lerpVectors(t,e,i){return this.x=t.x+(e.x-t.x)*i,this.y=t.y+(e.y-t.y)*i,this.z=t.z+(e.z-t.z)*i,this}cross(t){return this.crossVectors(this,t)}crossVectors(t,e){const i=t.x,s=t.y,r=t.z,n=e.x,a=e.y,l=e.z;return this.x=s*l-r*a,this.y=r*n-i*l,this.z=i*a-s*n,this}projectOnVector(t){const e=t.lengthSq();if(e===0)return this.set(0,0,0);const i=t.dot(this)/e;return this.copy(t).multiplyScalar(i)}projectOnPlane(t){return Dr.copy(this).projectOnVector(t),this.sub(Dr)}reflect(t){return this.sub(Dr.copy(t).multiplyScalar(2*this.dot(t)))}angleTo(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(e===0)return Math.PI/2;const i=this.dot(t)/e;return Math.acos(ee(i,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,i=this.y-t.y,s=this.z-t.z;return e*e+i*i+s*s}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)+Math.abs(this.z-t.z)}setFromSphericalCoords(t,e,i){const s=Math.sin(e)*t;return this.x=s*Math.sin(i),this.y=Math.cos(e)*t,this.z=s*Math.cos(i),this}setFromCylindricalCoords(t,e,i){return this.x=t*Math.sin(e),this.y=i,this.z=t*Math.cos(e),this}setFromMatrixPosition(t){const e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this}setFromMatrixScale(t){const e=this.setFromMatrixColumn(t,0).length(),i=this.setFromMatrixColumn(t,1).length(),s=this.setFromMatrixColumn(t,2).length();return this.x=e,this.y=i,this.z=s,this}setFromMatrixColumn(t,e){return this.fromArray(t.elements,e*4)}setFromMatrix3Column(t,e){return this.fromArray(t.elements,e*3)}setFromEuler(t){return this.x=t._x,this.y=t._y,this.z=t._z,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const t=Math.random()*Math.PI*2,e=Math.random()*2-1,i=Math.sqrt(1-e*e);return this.x=i*Math.cos(t),this.y=e,this.z=i*Math.sin(t),this}abs(){return this.x=Math.abs(this.x),this.y=Math.abs(this.y),this.z=Math.abs(this.z),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const Dr=new I,To=new W,qs=2e3,zo=2001;class Zt{constructor(t,e,i,s,r,n,a,l,h,d,c,p,u,f,m,y){this.isMatrix4=!0,Zt.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],t!==void 0&&this.set(t,e,i,s,r,n,a,l,h,d,c,p,u,f,m,y)}extractPosition(t){return console.warn("THREE.Matrix4: .extractPosition() has been renamed to .copyPosition()."),this.copyPosition(t)}multiplyToArray(t,e,i){return console.error("THREE.Matrix4: .multiplyToArray() has been removed."),this}setRotationFromQuaternion(t){return this.makeRotationFromQuaternion(t)}set(t,e,i,s,r,n,a,l,h,d,c,p,u,f,m,y){const g=this.elements;return g[0]=t,g[4]=e,g[8]=i,g[12]=s,g[1]=r,g[5]=n,g[9]=a,g[13]=l,g[2]=h,g[6]=d,g[10]=c,g[14]=p,g[3]=u,g[7]=f,g[11]=m,g[15]=y,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new Zt().fromArray(this.elements)}copy(t){const e=this.elements,i=t.elements;return e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=i[3],e[4]=i[4],e[5]=i[5],e[6]=i[6],e[7]=i[7],e[8]=i[8],e[9]=i[9],e[10]=i[10],e[11]=i[11],e[12]=i[12],e[13]=i[13],e[14]=i[14],e[15]=i[15],this}copyPosition(t){const e=this.elements,i=t.elements;return e[12]=i[12],e[13]=i[13],e[14]=i[14],this}setFromMatrix3(t){const e=t.elements;return this.set(e[0],e[3],e[6],0,e[1],e[4],e[7],0,e[2],e[5],e[8],0,0,0,0,1),this}extractBasis(t,e,i){return t.setFromMatrixColumn(this,0),e.setFromMatrixColumn(this,1),i.setFromMatrixColumn(this,2),this}makeBasis(t,e,i){return this.set(t.x,e.x,i.x,0,t.y,e.y,i.y,0,t.z,e.z,i.z,0,0,0,0,1),this}extractRotation(t){const e=this.elements,i=t.elements,s=1/li.setFromMatrixColumn(t,0).length(),r=1/li.setFromMatrixColumn(t,1).length(),n=1/li.setFromMatrixColumn(t,2).length();return e[0]=i[0]*s,e[1]=i[1]*s,e[2]=i[2]*s,e[3]=0,e[4]=i[4]*r,e[5]=i[5]*r,e[6]=i[6]*r,e[7]=0,e[8]=i[8]*n,e[9]=i[9]*n,e[10]=i[10]*n,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromEuler(t){const e=this.elements,i=t.x,s=t.y,r=t.z,n=Math.cos(i),a=Math.sin(i),l=Math.cos(s),h=Math.sin(s),d=Math.cos(r),c=Math.sin(r);if(t.order==="XYZ"){const p=n*d,u=n*c,f=a*d,m=a*c;e[0]=l*d,e[4]=-l*c,e[8]=h,e[1]=u+f*h,e[5]=p-m*h,e[9]=-a*l,e[2]=m-p*h,e[6]=f+u*h,e[10]=n*l}else if(t.order==="YXZ"){const p=l*d,u=l*c,f=h*d,m=h*c;e[0]=p+m*a,e[4]=f*a-u,e[8]=n*h,e[1]=n*c,e[5]=n*d,e[9]=-a,e[2]=u*a-f,e[6]=m+p*a,e[10]=n*l}else if(t.order==="ZXY"){const p=l*d,u=l*c,f=h*d,m=h*c;e[0]=p-m*a,e[4]=-n*c,e[8]=f+u*a,e[1]=u+f*a,e[5]=n*d,e[9]=m-p*a,e[2]=-n*h,e[6]=a,e[10]=n*l}else if(t.order==="ZYX"){const p=n*d,u=n*c,f=a*d,m=a*c;e[0]=l*d,e[4]=f*h-u,e[8]=p*h+m,e[1]=l*c,e[5]=m*h+p,e[9]=u*h-f,e[2]=-h,e[6]=a*l,e[10]=n*l}else if(t.order==="YZX"){const p=n*l,u=n*h,f=a*l,m=a*h;e[0]=l*d,e[4]=m-p*c,e[8]=f*c+u,e[1]=c,e[5]=n*d,e[9]=-a*d,e[2]=-h*d,e[6]=u*c+f,e[10]=p-m*c}else if(t.order==="XZY"){const p=n*l,u=n*h,f=a*l,m=a*h;e[0]=l*d,e[4]=-c,e[8]=h*d,e[1]=p*c+m,e[5]=n*d,e[9]=u*c-f,e[2]=f*c-u,e[6]=a*d,e[10]=m*c+p}return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromQuaternion(t){return this.compose(Yc,t,qc)}lookAt(t,e,i){const s=this.elements;return Bt.subVectors(t,e),Bt.lengthSq()===0&&(Bt.z=1),Bt.normalize(),Ce.crossVectors(i,Bt),Ce.lengthSq()===0&&(Math.abs(i.z)===1?Bt.x+=1e-4:Bt.z+=1e-4,Bt.normalize(),Ce.crossVectors(i,Bt)),Ce.normalize(),Zs.crossVectors(Bt,Ce),s[0]=Ce.x,s[4]=Zs.x,s[8]=Bt.x,s[1]=Ce.y,s[5]=Zs.y,s[9]=Bt.y,s[2]=Ce.z,s[6]=Zs.z,s[10]=Bt.z,this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const i=t.elements,s=e.elements,r=this.elements,n=i[0],a=i[4],l=i[8],h=i[12],d=i[1],c=i[5],p=i[9],u=i[13],f=i[2],m=i[6],y=i[10],g=i[14],_=i[3],M=i[7],w=i[11],C=i[15],x=s[0],b=s[4],P=s[8],A=s[12],N=s[1],J=s[5],$=s[9],gt=s[13],Y=s[2],K=s[6],lt=s[10],st=s[14],ct=s[3],tt=s[7],dt=s[11],ut=s[15];return r[0]=n*x+a*N+l*Y+h*ct,r[4]=n*b+a*J+l*K+h*tt,r[8]=n*P+a*$+l*lt+h*dt,r[12]=n*A+a*gt+l*st+h*ut,r[1]=d*x+c*N+p*Y+u*ct,r[5]=d*b+c*J+p*K+u*tt,r[9]=d*P+c*$+p*lt+u*dt,r[13]=d*A+c*gt+p*st+u*ut,r[2]=f*x+m*N+y*Y+g*ct,r[6]=f*b+m*J+y*K+g*tt,r[10]=f*P+m*$+y*lt+g*dt,r[14]=f*A+m*gt+y*st+g*ut,r[3]=_*x+M*N+w*Y+C*ct,r[7]=_*b+M*J+w*K+C*tt,r[11]=_*P+M*$+w*lt+C*dt,r[15]=_*A+M*gt+w*st+C*ut,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[4]*=t,e[8]*=t,e[12]*=t,e[1]*=t,e[5]*=t,e[9]*=t,e[13]*=t,e[2]*=t,e[6]*=t,e[10]*=t,e[14]*=t,e[3]*=t,e[7]*=t,e[11]*=t,e[15]*=t,this}determinant(){const t=this.elements,e=t[0],i=t[4],s=t[8],r=t[12],n=t[1],a=t[5],l=t[9],h=t[13],d=t[2],c=t[6],p=t[10],u=t[14],f=t[3],m=t[7],y=t[11],g=t[15];return f*(+r*l*c-s*h*c-r*a*p+i*h*p+s*a*u-i*l*u)+m*(+e*l*u-e*h*p+r*n*p-s*n*u+s*h*d-r*l*d)+y*(+e*h*c-e*a*u-r*n*c+i*n*u+r*a*d-i*h*d)+g*(-s*a*d-e*l*c+e*a*p+s*n*c-i*n*p+i*l*d)}transpose(){const t=this.elements;let e;return e=t[1],t[1]=t[4],t[4]=e,e=t[2],t[2]=t[8],t[8]=e,e=t[6],t[6]=t[9],t[9]=e,e=t[3],t[3]=t[12],t[12]=e,e=t[7],t[7]=t[13],t[13]=e,e=t[11],t[11]=t[14],t[14]=e,this}setPosition(t,e,i){const s=this.elements;return t.isVector3?(s[12]=t.x,s[13]=t.y,s[14]=t.z):(s[12]=t,s[13]=e,s[14]=i),this}invert(){const t=this.elements,e=t[0],i=t[1],s=t[2],r=t[3],n=t[4],a=t[5],l=t[6],h=t[7],d=t[8],c=t[9],p=t[10],u=t[11],f=t[12],m=t[13],y=t[14],g=t[15],_=c*y*h-m*p*h+m*l*u-a*y*u-c*l*g+a*p*g,M=f*p*h-d*y*h-f*l*u+n*y*u+d*l*g-n*p*g,w=d*m*h-f*c*h+f*a*u-n*m*u-d*a*g+n*c*g,C=f*c*l-d*m*l-f*a*p+n*m*p+d*a*y-n*c*y,x=e*_+i*M+s*w+r*C;if(x===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const b=1/x;return t[0]=_*b,t[1]=(m*p*r-c*y*r-m*s*u+i*y*u+c*s*g-i*p*g)*b,t[2]=(a*y*r-m*l*r+m*s*h-i*y*h-a*s*g+i*l*g)*b,t[3]=(c*l*r-a*p*r-c*s*h+i*p*h+a*s*u-i*l*u)*b,t[4]=M*b,t[5]=(d*y*r-f*p*r+f*s*u-e*y*u-d*s*g+e*p*g)*b,t[6]=(f*l*r-n*y*r-f*s*h+e*y*h+n*s*g-e*l*g)*b,t[7]=(n*p*r-d*l*r+d*s*h-e*p*h-n*s*u+e*l*u)*b,t[8]=w*b,t[9]=(f*c*r-d*m*r-f*i*u+e*m*u+d*i*g-e*c*g)*b,t[10]=(n*m*r-f*a*r+f*i*h-e*m*h-n*i*g+e*a*g)*b,t[11]=(d*a*r-n*c*r-d*i*h+e*c*h+n*i*u-e*a*u)*b,t[12]=C*b,t[13]=(d*m*s-f*c*s+f*i*p-e*m*p-d*i*y+e*c*y)*b,t[14]=(f*a*s-n*m*s-f*i*l+e*m*l+n*i*y-e*a*y)*b,t[15]=(n*c*s-d*a*s+d*i*l-e*c*l-n*i*p+e*a*p)*b,this}scale(t){const e=this.elements,i=t.x,s=t.y,r=t.z;return e[0]*=i,e[4]*=s,e[8]*=r,e[1]*=i,e[5]*=s,e[9]*=r,e[2]*=i,e[6]*=s,e[10]*=r,e[3]*=i,e[7]*=s,e[11]*=r,this}getMaxScaleOnAxis(){const t=this.elements,e=t[0]*t[0]+t[1]*t[1]+t[2]*t[2],i=t[4]*t[4]+t[5]*t[5]+t[6]*t[6],s=t[8]*t[8]+t[9]*t[9]+t[10]*t[10];return Math.sqrt(Math.max(e,i,s))}makeTranslation(t,e,i){return t.isVector3?this.set(1,0,0,t.x,0,1,0,t.y,0,0,1,t.z,0,0,0,1):this.set(1,0,0,t,0,1,0,e,0,0,1,i,0,0,0,1),this}makeRotationX(t){const e=Math.cos(t),i=Math.sin(t);return this.set(1,0,0,0,0,e,-i,0,0,i,e,0,0,0,0,1),this}makeRotationY(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,0,i,0,0,1,0,0,-i,0,e,0,0,0,0,1),this}makeRotationZ(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,-i,0,0,i,e,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(t,e){const i=Math.cos(e),s=Math.sin(e),r=1-i,n=t.x,a=t.y,l=t.z,h=r*n,d=r*a;return this.set(h*n+i,h*a-s*l,h*l+s*a,0,h*a+s*l,d*a+i,d*l-s*n,0,h*l-s*a,d*l+s*n,r*l*l+i,0,0,0,0,1),this}makeScale(t,e,i){return this.set(t,0,0,0,0,e,0,0,0,0,i,0,0,0,0,1),this}makeShear(t,e,i,s,r,n){return this.set(1,i,r,0,t,1,n,0,e,s,1,0,0,0,0,1),this}compose(t,e,i){const s=this.elements,r=e._x,n=e._y,a=e._z,l=e._w,h=r+r,d=n+n,c=a+a,p=r*h,u=r*d,f=r*c,m=n*d,y=n*c,g=a*c,_=l*h,M=l*d,w=l*c,C=i.x,x=i.y,b=i.z;return s[0]=(1-(m+g))*C,s[1]=(u+w)*C,s[2]=(f-M)*C,s[3]=0,s[4]=(u-w)*x,s[5]=(1-(p+g))*x,s[6]=(y+_)*x,s[7]=0,s[8]=(f+M)*b,s[9]=(y-_)*b,s[10]=(1-(p+m))*b,s[11]=0,s[12]=t.x,s[13]=t.y,s[14]=t.z,s[15]=1,this}decompose(t,e,i){const s=this.elements;let r=li.set(s[0],s[1],s[2]).length();const n=li.set(s[4],s[5],s[6]).length(),a=li.set(s[8],s[9],s[10]).length();this.determinant()<0&&(r=-r),t.x=s[12],t.y=s[13],t.z=s[14],Gt.copy(this);const h=1/r,d=1/n,c=1/a;return Gt.elements[0]*=h,Gt.elements[1]*=h,Gt.elements[2]*=h,Gt.elements[4]*=d,Gt.elements[5]*=d,Gt.elements[6]*=d,Gt.elements[8]*=c,Gt.elements[9]*=c,Gt.elements[10]*=c,e.setFromRotationMatrix(Gt),i.x=r,i.y=n,i.z=a,this}makePerspective(t,e,i,s,r,n,a=qs){const l=this.elements,h=2*r/(e-t),d=2*r/(i-s),c=(e+t)/(e-t),p=(i+s)/(i-s);let u,f;if(a===qs)u=-(n+r)/(n-r),f=-2*n*r/(n-r);else if(a===zo)u=-n/(n-r),f=-n*r/(n-r);else throw new Error("Matrix4.makePerspective(): Invalid coordinate system: "+a);return l[0]=h,l[4]=0,l[8]=c,l[12]=0,l[1]=0,l[5]=d,l[9]=p,l[13]=0,l[2]=0,l[6]=0,l[10]=u,l[14]=f,l[3]=0,l[7]=0,l[11]=-1,l[15]=0,this}makeOrthographic(t,e,i,s,r,n,a=qs){const l=this.elements,h=1/(e-t),d=1/(i-s),c=1/(n-r),p=(e+t)*h,u=(i+s)*d;let f,m;if(a===qs)f=(n+r)*c,m=-2*c;else if(a===zo)f=r*c,m=-1*c;else throw new Error("../math.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);return l[0]=2*h,l[4]=0,l[8]=0,l[12]=-p,l[1]=0,l[5]=2*d,l[9]=0,l[13]=-u,l[2]=0,l[6]=0,l[10]=m,l[14]=-f,l[3]=0,l[7]=0,l[11]=0,l[15]=1,this}equals(t){const e=this.elements,i=t.elements;for(let s=0;s<16;s++)if(e[s]!==i[s])return!1;return!0}fromArray(t,e=0){for(let i=0;i<16;i++)this.elements[i]=t[i+e];return this}toArray(t=[],e=0){const i=this.elements;return t[e]=i[0],t[e+1]=i[1],t[e+2]=i[2],t[e+3]=i[3],t[e+4]=i[4],t[e+5]=i[5],t[e+6]=i[6],t[e+7]=i[7],t[e+8]=i[8],t[e+9]=i[9],t[e+10]=i[10],t[e+11]=i[11],t[e+12]=i[12],t[e+13]=i[13],t[e+14]=i[14],t[e+15]=i[15],t}}const li=new I,Gt=new Zt,Yc=new I(0,0,0),qc=new I(1,1,1),Ce=new I,Zs=new I,Bt=new I,Oo=new Zt,Io=new W;class Gi{constructor(t=0,e=0,i=0,s=Gi.DEFAULT_ORDER){this.isEuler=!0,this._x=t,this._y=e,this._z=i,this._order=s}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get order(){return this._order}set order(t){this._order=t,this._onChangeCallback()}set(t,e,i,s=this._order){return this._x=t,this._y=e,this._z=i,this._order=s,this._onChangeCallback(),this}clone(){return new Gi(this._x,this._y,this._z,this._order)}copy(t){return this._x=t._x,this._y=t._y,this._z=t._z,this._order=t._order,this._onChangeCallback(),this}setFromRotationMatrix(t,e=this._order,i=!0){const s=t.elements,r=s[0],n=s[4],a=s[8],l=s[1],h=s[5],d=s[9],c=s[2],p=s[6],u=s[10];switch(e){case"XYZ":this._y=Math.asin(ee(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-d,u),this._z=Math.atan2(-n,r)):(this._x=Math.atan2(p,h),this._z=0);break;case"YXZ":this._x=Math.asin(-ee(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(a,u),this._z=Math.atan2(l,h)):(this._y=Math.atan2(-c,r),this._z=0);break;case"ZXY":this._x=Math.asin(ee(p,-1,1)),Math.abs(p)<.9999999?(this._y=Math.atan2(-c,u),this._z=Math.atan2(-n,h)):(this._y=0,this._z=Math.atan2(l,r));break;case"ZYX":this._y=Math.asin(-ee(c,-1,1)),Math.abs(c)<.9999999?(this._x=Math.atan2(p,u),this._z=Math.atan2(l,r)):(this._x=0,this._z=Math.atan2(-n,h));break;case"YZX":this._z=Math.asin(ee(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(-d,h),this._y=Math.atan2(-c,r)):(this._x=0,this._y=Math.atan2(a,u));break;case"XZY":this._z=Math.asin(-ee(n,-1,1)),Math.abs(n)<.9999999?(this._x=Math.atan2(p,h),this._y=Math.atan2(a,r)):(this._x=Math.atan2(-d,u),this._y=0);break;default:console.warn("../math.Euler: .setFromRotationMatrix() encountered an unknown order: "+e)}return this._order=e,i===!0&&this._onChangeCallback(),this}setFromQuaternion(t,e,i){return Oo.makeRotationFromQuaternion(t),this.setFromRotationMatrix(Oo,e,i)}setFromVector3(t,e=this._order){return this.set(t.x,t.y,t.z,e)}reorder(t){return Io.setFromEuler(this),this.setFromQuaternion(Io,t)}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._order===this._order}fromArray(t){return this._x=t[0],this._y=t[1],this._z=t[2],t[3]!==void 0&&(this._order=t[3]),this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._order,t}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(t){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}Gi.DEFAULT_ORDER="XYZ";class gi{constructor(t=0,e=0){this.x=t,this.y=e}get width(){return this.x}set width(t){this.x=t}get height(){return this.y}set height(t){this.y=t}set(t,e){return this.x=t,this.y=e,this}setScalar(t){return this.x=t,this.y=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+t)}}clone(){return new gi(this.x,this.y)}copy(t){return this.x=t.x,this.y=t.y,this}add(t){return this.x+=t.x,this.y+=t.y,this}addScalar(t){return this.x+=t,this.y+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this}subScalar(t){return this.x-=t,this.y-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this}multiply(t){return this.x*=t.x,this.y*=t.y,this}multiplyScalar(t){return this.x*=t,this.y*=t,this}divide(t){return this.x/=t.x,this.y/=t.y,this}divideScalar(t){return this.multiplyScalar(1/t)}applyMatrix3(t){const e=this.x,i=this.y,s=t.elements;return this.x=s[0]*e+s[3]*i+s[6],this.y=s[1]*e+s[4]*i+s[7],this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this}clamp(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this}clampLength(t,e){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Math.max(t,Math.min(e,i)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(t){return this.x*t.x+this.y*t.y}cross(t){return this.x*t.y-this.y*t.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(e===0)return Math.PI/2;const i=this.dot(t)/e;return Math.acos(ee(i,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,i=this.y-t.y;return e*e+i*i}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this}lerpVectors(t,e,i){return this.x=t.x+(e.x-t.x)*i,this.y=t.y+(e.y-t.y)*i,this}equals(t){return t.x===this.x&&t.y===this.y}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t}rotateAround(t,e){const i=Math.cos(e),s=Math.sin(e),r=this.x-t.x,n=this.y-t.y;return this.x=r*i-n*s+t.x,this.y=r*s+n*i+t.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}gi.isVector2=!0;class Ht{constructor(t=0,e=0,i=0,s=1){Ht.prototype.isVector4=!0,this.x=t,this.y=e,this.z=i,this.w=s}get width(){return this.z}set width(t){this.z=t}get height(){return this.w}set height(t){this.w=t}set(t,e,i,s){return this.x=t,this.y=e,this.z=i,this.w=s,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this.w=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setW(t){return this.w=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;case 3:this.w=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+t)}}clone(){return new Ht(this.x,this.y,this.z,this.w)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this.w+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this.w=t.w+e.w,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this.w+=t.w*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this.w-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this.w=t.w-e.w,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this}applyMatrix4(t){const e=this.x,i=this.y,s=this.z,r=this.w,n=t.elements;return this.x=n[0]*e+n[4]*i+n[8]*s+n[12]*r,this.y=n[1]*e+n[5]*i+n[9]*s+n[13]*r,this.z=n[2]*e+n[6]*i+n[10]*s+n[14]*r,this.w=n[3]*e+n[7]*i+n[11]*s+n[15]*r,this}divideScalar(t){return this.multiplyScalar(1/t)}setAxisAngleFromQuaternion(t){this.w=2*Math.acos(t.w);const e=Math.sqrt(1-t.w*t.w);return e<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=t.x/e,this.y=t.y/e,this.z=t.z/e),this}setAxisAngleFromRotationMatrix(t){let e,i,s,r;const l=t.elements,h=l[0],d=l[4],c=l[8],p=l[1],u=l[5],f=l[9],m=l[2],y=l[6],g=l[10];if(Math.abs(d-p)<.01&&Math.abs(c-m)<.01&&Math.abs(f-y)<.01){if(Math.abs(d+p)<.1&&Math.abs(c+m)<.1&&Math.abs(f+y)<.1&&Math.abs(h+u+g-3)<.1)return this.set(1,0,0,0),this;e=Math.PI;const M=(h+1)/2,w=(u+1)/2,C=(g+1)/2,x=(d+p)/4,b=(c+m)/4,P=(f+y)/4;return M>w&&M>C?M<.01?(i=0,s=.707106781,r=.707106781):(i=Math.sqrt(M),s=x/i,r=b/i):w>C?w<.01?(i=.707106781,s=0,r=.707106781):(s=Math.sqrt(w),i=x/s,r=P/s):C<.01?(i=.707106781,s=.707106781,r=0):(r=Math.sqrt(C),i=b/r,s=P/r),this.set(i,s,r,e),this}let _=Math.sqrt((y-f)*(y-f)+(c-m)*(c-m)+(p-d)*(p-d));return Math.abs(_)<.001&&(_=1),this.x=(y-f)/_,this.y=(c-m)/_,this.z=(p-d)/_,this.w=Math.acos((h+u+g-1)/2),this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this.w=Math.min(this.w,t.w),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this.w=Math.max(this.w,t.w),this}clamp(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this.z=Math.max(t.z,Math.min(e.z,this.z)),this.w=Math.max(t.w,Math.min(e.w,this.w)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this.z=Math.max(t,Math.min(e,this.z)),this.w=Math.max(t,Math.min(e,this.w)),this}clampLength(t,e){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Math.max(t,Math.min(e,i)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z+this.w*t.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this.w+=(t.w-this.w)*e,this}lerpVectors(t,e,i){return this.x=t.x+(e.x-t.x)*i,this.y=t.y+(e.y-t.y)*i,this.z=t.z+(e.z-t.z)*i,this.w=t.w+(e.w-t.w)*i,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z&&t.w===this.w}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this.w=t[e+3],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t[e+3]=this.w,t}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class se{constructor(t,e,i,s,r,n,a,l,h){se.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],t!==void 0&&this.set(t,e,i,s,r,n,a,l,h)}set(t,e,i,s,r,n,a,l,h){const d=this.elements;return d[0]=t,d[1]=s,d[2]=a,d[3]=e,d[4]=r,d[5]=l,d[6]=i,d[7]=n,d[8]=h,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(t){const e=this.elements,i=t.elements;return e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=i[3],e[4]=i[4],e[5]=i[5],e[6]=i[6],e[7]=i[7],e[8]=i[8],this}extractBasis(t,e,i){return t.setFromMatrix3Column(this,0),e.setFromMatrix3Column(this,1),i.setFromMatrix3Column(this,2),this}setFromMatrix4(t){const e=t.elements;return this.set(e[0],e[4],e[8],e[1],e[5],e[9],e[2],e[6],e[10]),this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const i=t.elements,s=e.elements,r=this.elements,n=i[0],a=i[3],l=i[6],h=i[1],d=i[4],c=i[7],p=i[2],u=i[5],f=i[8],m=s[0],y=s[3],g=s[6],_=s[1],M=s[4],w=s[7],C=s[2],x=s[5],b=s[8];return r[0]=n*m+a*_+l*C,r[3]=n*y+a*M+l*x,r[6]=n*g+a*w+l*b,r[1]=h*m+d*_+c*C,r[4]=h*y+d*M+c*x,r[7]=h*g+d*w+c*b,r[2]=p*m+u*_+f*C,r[5]=p*y+u*M+f*x,r[8]=p*g+u*w+f*b,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[3]*=t,e[6]*=t,e[1]*=t,e[4]*=t,e[7]*=t,e[2]*=t,e[5]*=t,e[8]*=t,this}determinant(){const t=this.elements,e=t[0],i=t[1],s=t[2],r=t[3],n=t[4],a=t[5],l=t[6],h=t[7],d=t[8];return e*n*d-e*a*h-i*r*d+i*a*l+s*r*h-s*n*l}invert(){const t=this.elements,e=t[0],i=t[1],s=t[2],r=t[3],n=t[4],a=t[5],l=t[6],h=t[7],d=t[8],c=d*n-a*h,p=a*l-d*r,u=h*r-n*l,f=e*c+i*p+s*u;if(f===0)return this.set(0,0,0,0,0,0,0,0,0);const m=1/f;return t[0]=c*m,t[1]=(s*h-d*i)*m,t[2]=(a*i-s*n)*m,t[3]=p*m,t[4]=(d*e-s*l)*m,t[5]=(s*r-a*e)*m,t[6]=u*m,t[7]=(i*l-h*e)*m,t[8]=(n*e-i*r)*m,this}transpose(){let t;const e=this.elements;return t=e[1],e[1]=e[3],e[3]=t,t=e[2],e[2]=e[6],e[6]=t,t=e[5],e[5]=e[7],e[7]=t,this}getNormalMatrix(t){return this.setFromMatrix4(t).invert().transpose()}transposeIntoArray(t){const e=this.elements;return t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8],this}setUvTransform(t,e,i,s,r,n,a){const l=Math.cos(r),h=Math.sin(r);return this.set(i*l,i*h,-i*(l*n+h*a)+n+t,-s*h,s*l,-s*(-h*n+l*a)+a+e,0,0,1),this}scale(t,e){return this.premultiply(Ur.makeScale(t,e)),this}rotate(t){return this.premultiply(Ur.makeRotation(-t)),this}translate(t,e){return this.premultiply(Ur.makeTranslation(t,e)),this}makeTranslation(t,e){return t.isVector2?this.set(1,0,t.x,0,1,t.y,0,0,1):this.set(1,0,t,0,1,e,0,0,1),this}makeRotation(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,-i,0,i,e,0,0,0,1),this}makeScale(t,e){return this.set(t,0,0,0,e,0,0,0,1),this}equals(t){const e=this.elements,i=t.elements;for(let s=0;s<9;s++)if(e[s]!==i[s])return!1;return!0}fromArray(t,e=0){for(let i=0;i<9;i++)this.elements[i]=t[i+e];return this}toArray(t=[],e=0){const i=this.elements;return t[e]=i[0],t[e+1]=i[1],t[e+2]=i[2],t[e+3]=i[3],t[e+4]=i[4],t[e+5]=i[5],t[e+6]=i[6],t[e+7]=i[7],t[e+8]=i[8],t}clone(){return new se().fromArray(this.elements)}}const Ur=new se;var zt;(function(o){o[o.Random=0]="Random",o[o.Loop=1]="Loop",o[o.PingPong=2]="PingPong",o[o.Burst=3]="Burst"})(zt||(zt={}));function bi(o,t,e,i){let s;switch(zt.Random===o?t=Math.random():zt.Burst===o&&i.isBursting&&(t=i.burstParticleIndex/i.burstParticleCount),e>0?s=Math.floor(t/e)*e:s=t,o){case zt.Loop:s=s%1;break;case zt.PingPong:s=Math.abs(s%2-1);break}return s}class je{constructor(t,e,i,s){this.p=[t,e,i,s]}genValue(t){const e=t*t,i=t*t*t,s=1-t,r=s*s,n=r*s;return this.p[0]*n+this.p[1]*r*t*3+this.p[2]*s*e*3+this.p[3]*i}derivativeCoefficients(t){const e=[];for(let i=t,s=i.length-1;s>0;s--){const r=[];for(let n=0;n<s;n++){const a=s*(i[n+1]-i[n]);r.push(a)}e.push(r),i=r}return e}getSlope(t){const e=this.derivativeCoefficients(this.p)[0],i=1-t,s=i*i,r=i*t*2,n=t*t;return s*e[0]+r*e[1]+n*e[2]}controlCurve(t,e){this.p[1]=t/3+this.p[0],this.p[2]=this.p[3]-e/3}hull(t){let e=this.p,i=[],s,r=0,n=0,a=0;const l=[];for(l[r++]=e[0],l[r++]=e[1],l[r++]=e[2],l[r++]=e[3];e.length>1;){for(i=[],n=0,a=e.length-1;n<a;n++)s=t*e[n]+(1-t)*e[n+1],l[r++]=s,i.push(s);e=i}return l}split(t){const e=this.hull(t);return{left:new je(e[0],e[4],e[7],e[9]),right:new je(e[9],e[8],e[6],e[3]),span:e}}clone(){return new je(this.p[0],this.p[1],this.p[2],this.p[3])}toJSON(){return{p0:this.p[0],p1:this.p[1],p2:this.p[2],p3:this.p[3]}}static fromJSON(t){return new je(t.p0,t.p1,t.p2,t.p3)}}const Xi=o=>({r:o.x,g:o.y,b:o.z,a:o.w}),Wi=o=>new Ht(o.r,o.g,o.b,o.a),Zc=(o,t)=>{switch(t){case"Vector3":return new I(o.x,o.y,o.z);case"Vector4":return new Ht(o.x,o.y,o.z,o.w);case"Color":return new I(o.r,o.g,o.b);case"Number":return o;default:return o}},Qc=(o,t)=>{switch(t){case"Vector3":return{x:o.x,y:o.y,z:o.z};case"Vector4":return{x:o.x,y:o.y,z:o.z,w:o.w};case"Color":return{r:o.x,g:o.y,b:o.z};case"Number":return o;default:return o}};class ar{constructor(t,e){this.a=t,this.b=e,this.type="value"}startGen(t){}genColor(t,e){const i=Math.random();return e.copy(this.a).lerp(this.b,i)}toJSON(){return{type:"RandomColor",a:Xi(this.a),b:Xi(this.b)}}static fromJSON(t){return new ar(Wi(t.a),Wi(t.b))}clone(){return new ar(this.a.clone(),this.b.clone())}}class yi{constructor(t,e){this.a=t,this.b=e,this.indexCount=-1,this.type="value"}startGen(t){this.indexCount=t.length,t.push(Math.random())}genColor(t,e){return this.indexCount===-1&&this.startGen(t),e.copy(this.a).lerp(this.b,t[this.indexCount])}toJSON(){return{type:"ColorRange",a:Xi(this.a),b:Xi(this.b)}}static fromJSON(t){return new yi(Wi(t.a),Wi(t.b))}clone(){return new yi(this.a.clone(),this.b.clone())}}class Oe{constructor(t,e){this.subType=e,this.type="function",this.keys=t}findKey(t){let e=0,i=0,s=this.keys.length-1;for(;i+1<s;)if(e=Math.floor((i+s)/2),t<this.getStartX(e))s=e-1;else if(t>this.getEndX(e))i=e+1;else return e;for(let r=i;r<=s;r++)if(t>=this.getStartX(r)&&t<=this.getEndX(r))return r;return-1}getStartX(t){return this.keys[t][1]}getEndX(t){return t+1<this.keys.length?this.keys[t+1][1]:1}genValue(t,e){const i=this.findKey(e);return this.subType==="Number"?i===-1?this.keys[0][0]:i+1>=this.keys.length?this.keys[this.keys.length-1][0]:(this.keys[i+1][0]-this.keys[i][0])*((e-this.getStartX(i))/(this.getEndX(i)-this.getStartX(i)))+this.keys[i][0]:i===-1?t.copy(this.keys[0][0]):i+1>=this.keys.length?t.copy(this.keys[this.keys.length-1][0]):t.copy(this.keys[i][0]).lerp(this.keys[i+1][0],(e-this.getStartX(i))/(this.getEndX(i)-this.getStartX(i)))}toJSON(){return this.keys[0][0].constructor.name,{type:"CLinearFunction",subType:this.subType,keys:this.keys.map(([t,e])=>({value:Qc(t,this.subType),pos:e}))}}static fromJSON(t){return new Oe(t.keys.map(e=>[Zc(e.value,t.subType),e.pos]),t.subType)}clone(){return this.subType==="Number"?new Oe(this.keys.map(([t,e])=>[t,e]),this.subType):new Oe(this.keys.map(([t,e])=>[t.clone(),e]),this.subType)}}const Qs=new I;class Ge{constructor(t=[[new I(0,0,0),0],[new I(1,1,1),0]],e=[[1,0],[1,1]]){this.type="function",this.color=new Oe(t,"Color"),this.alpha=new Oe(e,"Number")}genColor(t,e,i){return this.color.genValue(Qs,i),e.set(Qs.x,Qs.y,Qs.z,this.alpha.genValue(1,i))}toJSON(){return{type:"Gradient",color:this.color.toJSON(),alpha:this.alpha.toJSON()}}static fromJSON(t){if(t.functions){const e=t.functions.map(i=>[yi.fromJSON(i.function).a,i.start]);return t.functions.length>0&&e.push([yi.fromJSON(t.functions[t.functions.length-1].function).b,1]),new Ge(e.map(i=>[new I(i[0].x,i[0].y,i[0].z),i[1]]),e.map(i=>[i[0].w,i[1]]))}else{const e=new Ge;return e.alpha=Oe.fromJSON(t.alpha),e.color=Oe.fromJSON(t.color),e}}clone(){const t=new Ge;return t.alpha=this.alpha.clone(),t.color=this.color.clone(),t}startGen(t){}}const Vr=new Ht;class lr{constructor(t,e){this.indexCount=0,this.type="function",this.gradient1=t,this.gradient2=e}startGen(t){this.indexCount=t.length,t.push(Math.random())}genColor(t,e,i){return this.gradient1.genColor(t,e,i),this.gradient2.genColor(t,Vr,i),t&&t[this.indexCount]!==void 0?e.lerp(Vr,t[this.indexCount]):e.lerp(Vr,Math.random()),e}toJSON(){return{type:"RandomColorBetweenGradient",gradient1:this.gradient1.toJSON(),gradient2:this.gradient2.toJSON()}}static fromJSON(t){return new lr(Ge.fromJSON(t.gradient1),Ge.fromJSON(t.gradient2))}clone(){return new lr(this.gradient1.clone(),this.gradient2.clone())}}class _i{constructor(t){this.color=t,this.type="value"}startGen(t){}genColor(t,e){return e.copy(this.color)}toJSON(){return{type:"ConstantColor",color:Xi(this.color)}}static fromJSON(t){return new _i(Wi(t.color))}clone(){return new _i(this.color.clone())}}function On(o){switch(o.type){case"ConstantColor":return _i.fromJSON(o);case"ColorRange":return yi.fromJSON(o);case"RandomColor":return ar.fromJSON(o);case"Gradient":return Ge.fromJSON(o);case"RandomColorBetweenGradient":return lr.fromJSON(o);default:return new _i(new Ht(1,1,1,1))}}class Q{constructor(t){this.value=t,this.type="value"}startGen(t){}genValue(t){return this.value}toJSON(){return{type:"ConstantValue",value:this.value}}static fromJSON(t){return new Q(t.value)}clone(){return new Q(this.value)}}class Ye{constructor(t,e){this.a=t,this.b=e,this.indexCount=-1,this.type="value"}startGen(t){this.indexCount=t.length,t.push(Math.random())}genValue(t){return this.indexCount===-1&&this.startGen(t),Si.lerp(this.a,this.b,t[this.indexCount])}toJSON(){return{type:"IntervalValue",a:this.a,b:this.b}}static fromJSON(t){return new Ye(t.a,t.b)}clone(){return new Ye(this.a,this.b)}}class $c{constructor(){this.functions=new Array}findFunction(t){let e=0,i=0,s=this.functions.length-1;for(;i+1<s;)if(e=Math.floor((i+s)/2),t<this.getStartX(e))s=e-1;else if(t>this.getEndX(e))i=e+1;else return e;for(let r=i;r<=s;r++)if(t>=this.functions[r][1]&&t<=this.getEndX(r))return r;return-1}getStartX(t){return this.functions[t][1]}setStartX(t,e){t>0&&(this.functions[t][1]=e)}getEndX(t){return t+1<this.functions.length?this.functions[t+1][1]:1}setEndX(t,e){t+1<this.functions.length&&(this.functions[t+1][1]=e)}insertFunction(t,e){const i=this.findFunction(t);this.functions.splice(i+1,0,[e,t])}removeFunction(t){return this.functions.splice(t,1)[0][0]}getFunction(t){return this.functions[t][0]}setFunction(t,e){this.functions[t][0]=e}get numOfFunctions(){return this.functions.length}}class Ji extends $c{constructor(t=[[new je(0,1/3,1/3*2,1),0]]){super(),this.type="function",this.functions=t}genValue(t,e=0){const i=this.findFunction(e);return i===-1?0:this.functions[i][0].genValue((e-this.getStartX(i))/(this.getEndX(i)-this.getStartX(i)))}toSVG(t,e){if(e<1)return"";let i=["M",0,this.functions[0][0].p[0]].join(" ");for(let s=1/e;s<=1;s+=1/e)i=[i,"L",s*t,this.genValue(void 0,s)].join(" ");return i}toJSON(){return{type:"PiecewiseBezier",functions:this.functions.map(([t,e])=>({function:t.toJSON(),start:e}))}}static fromJSON(t){return new Ji(t.functions.map(e=>[je.fromJSON(e.function),e.start]))}clone(){return new Ji(this.functions.map(([t,e])=>[t.clone(),e]))}startGen(t){}}function L(o){switch(o.type){case"ConstantValue":return Q.fromJSON(o);case"IntervalValue":return Ye.fromJSON(o);case"PiecewiseBezier":return Ji.fromJSON(o);default:return new Q(0)}}class Yi{constructor(){this.indexCount=0,this.type="rotation"}startGen(t){this.indexCount=t.length,t.push(new W);let e,i,s,r,n,a;do e=Math.random()*2-1,i=Math.random()*2-1,s=e*e+i*i;while(s>1);do r=Math.random()*2-1,n=Math.random()*2-1,a=r*r+n*n;while(a>1);const l=Math.sqrt((1-s)/a);t[this.indexCount].set(e,i,l*r,l*n)}genValue(t,e,i,s){return this.indexCount===-1&&this.startGen(t),e.copy(t[this.indexCount]),e}toJSON(){return{type:"RandomQuat"}}static fromJSON(t){return new Yi}clone(){return new Yi}}class qi{constructor(t,e){this.axis=t,this.angle=e,this.type="rotation"}startGen(t){this.angle.startGen(t)}genValue(t,e,i,s){return e.setFromAxisAngle(this.axis,this.angle.genValue(t,s)*i)}toJSON(){return{type:"AxisAngle",axis:{x:this.axis.x,y:this.axis.y,z:this.axis.z},angle:this.angle.toJSON()}}static fromJSON(t){return new qi(new I(t.axis.x,t.axis.y,t.axis.z),L(t.angle))}clone(){return new qi(this.axis.clone(),this.angle.clone())}}class hr{constructor(t,e,i,s){this.angleX=t,this.angleY=e,this.angleZ=i,this.type="rotation",this.eular=new Gi(0,0,0,s)}startGen(t){this.angleX.startGen(t),this.angleY.startGen(t),this.angleZ.startGen(t)}genValue(t,e,i,s){return this.eular.set(this.angleX.genValue(t,s)*i,this.angleY.genValue(t,s)*i,this.angleZ.genValue(t,s)*i),e.setFromEuler(this.eular)}toJSON(){return{type:"Euler",angleX:this.angleX.toJSON(),angleY:this.angleY.toJSON(),angleZ:this.angleZ.toJSON(),eulerOrder:this.eular.order}}static fromJSON(t){return new hr(L(t.angleX),L(t.angleY),L(t.angleZ),t.eulerOrder)}clone(){return new hr(this.angleX,this.angleY,this.angleZ,this.eular.order)}}function Ba(o){switch(o.type){case"AxisAngle":return qi.fromJSON(o);case"Euler":return hr.fromJSON(o);case"RandomQuat":return Yi.fromJSON(o);default:return new Yi}}class qe{constructor(t,e,i){this.x=t,this.y=e,this.z=i,this.type="vec3function"}startGen(t){this.x.startGen(t),this.y.startGen(t),this.z.startGen(t)}genValue(t,e,i){return e.set(this.x.genValue(t,i),this.y.genValue(t,i),this.z.genValue(t,i))}toJSON(){return{type:"Vector3Function",x:this.x.toJSON(),y:this.y.toJSON(),z:this.z.toJSON()}}static fromJSON(t){return new qe(L(t.x),L(t.y),L(t.z))}clone(){return new qe(this.x,this.y,this.z)}}function Kc(o){switch(o.type){case"Vector3Function":return qe.fromJSON(o);default:return new qe(new Q(0),new Q(0),new Q(0))}}function cr(o){switch(o.type){case"ConstantValue":case"IntervalValue":case"PiecewiseBezier":return L(o);case"AxisAngle":case"RandomQuat":case"Euler":return Ba(o);case"Vector3Function":return Kc(o);default:return new Q(0)}}class Zi{constructor(t={}){this.type="cone",this.currentValue=0,this.radius=t.radius??10,this.arc=t.arc??2*Math.PI,this.thickness=t.thickness??1,this.angle=t.angle??Math.PI/6,this.mode=t.mode??zt.Random,this.spread=t.spread??0,this.speed=t.speed??new Q(1),this.memory=[]}update(t,e){zt.Random!=this.mode&&(this.currentValue+=this.speed.genValue(this.memory,t.emissionState.time/t.duration)*e)}initialize(t,e){const i=bi(this.mode,this.currentValue,this.spread,e),s=Si.lerp(1-this.thickness,1,Math.random()),r=i*this.arc,n=Math.sqrt(s),a=Math.sin(r),l=Math.cos(r);t.position.x=n*l,t.position.y=n*a,t.position.z=0;const h=this.angle*n;t.velocity.set(0,0,Math.cos(h)).addScaledVector(t.position,Math.sin(h)).multiplyScalar(t.startSpeed),t.position.multiplyScalar(this.radius)}toJSON(){return{type:"cone",radius:this.radius,arc:this.arc,thickness:this.thickness,angle:this.angle,mode:this.mode,spread:this.spread,speed:this.speed.toJSON()}}static fromJSON(t){return new Zi({radius:t.radius,arc:t.arc,thickness:t.thickness,angle:t.angle,mode:t.mode,speed:t.speed?L(t.speed):void 0,spread:t.spread})}clone(){return new Zi({radius:this.radius,arc:this.arc,thickness:this.thickness,angle:this.angle,mode:this.mode,speed:this.speed.clone(),spread:this.spread})}}class Qi{constructor(t={}){this.type="circle",this.currentValue=0,this.radius=t.radius??10,this.arc=t.arc??2*Math.PI,this.thickness=t.thickness??1,this.mode=t.mode??zt.Random,this.spread=t.spread??0,this.speed=t.speed??new Q(1),this.memory=[]}update(t,e){this.currentValue+=this.speed.genValue(this.memory,t.emissionState.time/t.duration)*e}initialize(t,e){const i=bi(this.mode,this.currentValue,this.spread,e),s=Si.lerp(1-this.thickness,1,Math.random()),r=i*this.arc;t.position.x=Math.cos(r),t.position.y=Math.sin(r),t.position.z=0,t.velocity.copy(t.position).multiplyScalar(t.startSpeed),t.position.multiplyScalar(this.radius*s)}toJSON(){return{type:"circle",radius:this.radius,arc:this.arc,thickness:this.thickness,mode:this.mode,spread:this.spread,speed:this.speed.toJSON()}}static fromJSON(t){return new Qi({radius:t.radius,arc:t.arc,thickness:t.thickness,mode:t.mode,speed:t.speed?L(t.speed):void 0,spread:t.spread})}clone(){return new Qi({radius:this.radius,arc:this.arc,thickness:this.thickness,mode:this.mode,speed:this.speed.clone(),spread:this.spread})}}function $s(o,t){return Math.floor(Math.random()*(t-o))+o}const Ps=new I(0,1,0),As=new I(0,0,0),td=new I(1,1,1),Ro=new I(0,0,1);class $i{constructor(t={}){this.type="donut",this.currentValue=0,this.radius=t.radius??10,this.arc=t.arc??2*Math.PI,this.thickness=t.thickness??1,this.donutRadius=t.donutRadius??this.radius*.2,this.mode=t.mode??zt.Random,this.spread=t.spread??0,this.speed=t.speed??new Q(1),this.memory=[],this._m1=new Zt}update(t,e){zt.Random!=this.mode&&(this.currentValue+=this.speed.genValue(this.memory,t.emissionState.time/t.duration)*e)}initialize(t,e){const i=bi(this.mode,this.currentValue,this.spread,e),s=Math.random(),r=Si.lerp(1-this.thickness,1,Math.random()),n=i*this.arc,a=s*Math.PI*2,l=Math.sin(n),h=Math.cos(n);t.position.x=this.radius*h,t.position.y=this.radius*l,t.position.z=0,t.velocity.z=this.donutRadius*r*Math.sin(a),t.velocity.x=this.donutRadius*r*Math.cos(a)*h,t.velocity.y=this.donutRadius*r*Math.cos(a)*l,t.position.add(t.velocity),t.velocity.normalize().multiplyScalar(t.startSpeed),t.rotation instanceof W&&(this._m1.lookAt(As,t.velocity,Ps),t.rotation.setFromRotationMatrix(this._m1))}toJSON(){return{type:"donut",radius:this.radius,arc:this.arc,thickness:this.thickness,donutRadius:this.donutRadius,mode:this.mode,spread:this.spread,speed:this.speed.toJSON()}}static fromJSON(t){return new $i({radius:t.radius,arc:t.arc,thickness:t.thickness,donutRadius:t.donutRadius,mode:t.mode,speed:t.speed?L(t.speed):void 0,spread:t.spread})}clone(){return new $i({radius:this.radius,arc:this.arc,thickness:this.thickness,donutRadius:this.donutRadius,mode:this.mode,speed:this.speed.clone(),spread:this.spread})}}class Ki{constructor(){this.type="point",this._m1=new Zt}update(t,e){}initialize(t){const e=Math.random(),i=Math.random(),s=e*Math.PI*2,r=Math.acos(2*i-1),n=Math.cbrt(Math.random()),a=Math.sin(s),l=Math.cos(s),h=Math.sin(r),d=Math.cos(r);t.velocity.x=n*h*l,t.velocity.y=n*h*a,t.velocity.z=n*d,t.velocity.multiplyScalar(t.startSpeed),t.position.setScalar(0),t.rotation instanceof W&&(this._m1.lookAt(As,t.position,Ps),t.rotation.setFromRotationMatrix(this._m1))}toJSON(){return{type:"point"}}static fromJSON(t){return new Ki}clone(){return new Ki}}class vi{constructor(t={}){this.type="sphere",this.currentValue=0,this.radius=t.radius??10,this.arc=t.arc??2*Math.PI,this.thickness=t.thickness??1,this.mode=t.mode??zt.Random,this.spread=t.spread??0,this.speed=t.speed??new Q(1),this.memory=[],this._m1=new Zt}update(t,e){zt.Random!=this.mode&&(this.currentValue+=this.speed.genValue(this.memory,t.emissionState.time/t.duration)*e)}initialize(t,e){const i=bi(this.mode,this.currentValue,this.spread,e),s=Math.random(),r=Si.lerp(1-this.thickness,1,Math.random()),n=i*this.arc,a=Math.acos(2*s-1),l=Math.sin(n),h=Math.cos(n),d=Math.sin(a),c=Math.cos(a);t.position.x=d*h,t.position.y=d*l,t.position.z=c,t.velocity.copy(t.position).multiplyScalar(t.startSpeed),t.position.multiplyScalar(this.radius*r),t.rotation instanceof W&&(this._m1.lookAt(As,t.position,Ps),t.rotation.setFromRotationMatrix(this._m1))}toJSON(){return{type:"sphere",radius:this.radius,arc:this.arc,thickness:this.thickness,mode:this.mode,spread:this.spread,speed:this.speed.toJSON()}}static fromJSON(t){return new vi({radius:t.radius,arc:t.arc,thickness:t.thickness,mode:t.mode,speed:t.speed?L(t.speed):void 0,spread:t.spread})}clone(){return new vi({radius:this.radius,arc:this.arc,thickness:this.thickness,mode:this.mode,speed:this.speed.clone(),spread:this.spread})}}class ts{constructor(t={}){this.type="hemisphere",this.currentValue=0,this.radius=t.radius??10,this.arc=t.arc??2*Math.PI,this.thickness=t.thickness??1,this.mode=t.mode??zt.Random,this.spread=t.spread??0,this.speed=t.speed??new Q(1),this.memory=[],this._m1=new Zt}update(t,e){zt.Random!=this.mode&&(this.currentValue+=this.speed.genValue(this.memory,t.emissionState.time/t.duration)*e)}initialize(t,e){const i=bi(this.mode,this.currentValue,this.spread,e),s=Math.random(),r=Si.lerp(1-this.thickness,1,Math.random()),n=i*this.arc,a=Math.acos(s),l=Math.sin(n),h=Math.cos(n),d=Math.sin(a),c=Math.cos(a);t.position.x=d*h,t.position.y=d*l,t.position.z=c,t.velocity.copy(t.position).multiplyScalar(t.startSpeed),t.position.multiplyScalar(this.radius*r),t.rotation instanceof W&&(this._m1.lookAt(As,t.position,Ps),t.rotation.setFromRotationMatrix(this._m1))}toJSON(){return{type:"hemisphere",radius:this.radius,arc:this.arc,thickness:this.thickness,mode:this.mode,spread:this.spread,speed:this.speed.toJSON()}}static fromJSON(t){return new ts({radius:t.radius,arc:t.arc,thickness:t.thickness,mode:t.mode,speed:t.speed?L(t.speed):void 0,spread:t.spread})}clone(){return new ts({radius:this.radius,arc:this.arc,thickness:this.thickness,mode:this.mode,speed:this.speed.clone(),spread:this.spread})}}class es{constructor(t={}){this.type="grid",this.width=t.width??1,this.height=t.height??1,this.column=t.column??10,this.row=t.row??10}initialize(t){const e=Math.floor(Math.random()*this.row),i=Math.floor(Math.random()*this.column);t.position.x=i*this.width/this.column-this.width/2,t.position.y=e*this.height/this.row-this.height/2,t.position.z=0,t.velocity.set(0,0,t.startSpeed)}toJSON(){return{type:"grid",width:this.width,height:this.height,column:this.column,row:this.row}}static fromJSON(t){return new es(t)}clone(){return new es({width:this.width,height:this.height,column:this.column,row:this.row})}update(t,e){}}class is{constructor(t={}){this.type="rectangle",this.currentValue=0,this.width=t.width??10,this.height=t.height??10,this.thickness=t.thickness??1,this.mode=t.mode??zt.Random,this.spread=t.spread??0,this.speed=t.speed??new Q(1),this.memory=[],this._m1=new Zt}update(t,e){this.currentValue+=this.speed.genValue(this.memory,t.emissionState.time/t.duration)*e}initialize(t,e){const i=bi(this.mode,this.currentValue,this.spread,e),s=2*(this.width+this.height),r=i*s;let n,a;r<this.width?(n=r-this.width/2,a=-this.height/2):r<this.width+this.height?(n=this.width/2,a=r-this.width-this.height/2):r<2*this.width+this.height?(n=this.width/2-(r-this.width-this.height),a=this.height/2):(n=-this.width/2,a=this.height/2-(r-2*this.width-this.height));const l=Math.random(),h=1-this.thickness*l;t.position.x=n*h,t.position.y=a*h,t.position.z=0,t.velocity.x=n,t.velocity.y=a,t.velocity.z=0,t.velocity.normalize().multiplyScalar(t.startSpeed),t.rotation instanceof W&&(this._m1.lookAt(As,t.velocity,Ps),t.rotation.setFromRotationMatrix(this._m1))}toJSON(){return{type:"rectangle",width:this.width,height:this.height,thickness:this.thickness,mode:this.mode,spread:this.spread,speed:this.speed.toJSON()}}static fromJSON(t){return new is({width:t.width,height:t.height,thickness:t.thickness,mode:t.mode,speed:t.speed?L(t.speed):void 0,spread:t.spread})}clone(){return new is({width:this.width,height:this.height,thickness:this.thickness,mode:this.mode,speed:this.speed.clone(),spread:this.spread})}}const gn={circle:{type:"circle",params:[["radius",["number"]],["arc",["radian"]],["thickness",["number"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]]],constructor:Qi,loadJSON:Qi.fromJSON},cone:{type:"cone",params:[["radius",["number"]],["arc",["radian"]],["thickness",["number"]],["angle",["radian"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]]],constructor:Zi,loadJSON:Zi.fromJSON},donut:{type:"donut",params:[["radius",["number"]],["arc",["radian"]],["thickness",["number"]],["donutRadius",["number"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]]],constructor:$i,loadJSON:$i.fromJSON},point:{type:"point",params:[],constructor:Ki,loadJSON:Ki.fromJSON},sphere:{type:"sphere",params:[["radius",["number"]],["arc",["radian"]],["thickness",["number"]],["angle",["radian"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]]],constructor:vi,loadJSON:vi.fromJSON},hemisphere:{type:"hemisphere",params:[["radius",["number"]],["arc",["radian"]],["thickness",["number"]],["angle",["radian"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]]],constructor:ts,loadJSON:ts.fromJSON},grid:{type:"grid",params:[["width",["number"]],["height",["number"]],["rows",["number"]],["column",["number"]]],constructor:es,loadJSON:es.fromJSON},rectangle:{type:"rectangle",params:[["width",["number"]],["height",["number"]],["thickness",["number"]],["mode",["emitterMode"]],["spread",["number"]],["speed",["valueFunc","value"]]],constructor:is,loadJSON:is.fromJSON}};function ed(o,t){return gn[o.type].loadJSON(o,t)}class ss{constructor(t){this.color=t,this.type="ColorOverLife"}initialize(t){this.color.startGen(t.memory)}update(t,e){this.color.genColor(t.memory,t.color,t.age/t.life),t.color.x*=t.startColor.x,t.color.y*=t.startColor.y,t.color.z*=t.startColor.z,t.color.w*=t.startColor.w}frameUpdate(t){}toJSON(){return{type:this.type,color:this.color.toJSON()}}static fromJSON(t){return new ss(On(t.color))}clone(){return new ss(this.color.clone())}reset(){}}class rs{constructor(t){this.angularVelocity=t,this.type="RotationOverLife"}initialize(t){typeof t.rotation=="number"&&this.angularVelocity.startGen(t.memory)}update(t,e){typeof t.rotation=="number"&&(t.rotation+=e*this.angularVelocity.genValue(t.memory,t.age/t.life))}toJSON(){return{type:this.type,angularVelocity:this.angularVelocity.toJSON()}}static fromJSON(t){return new rs(L(t.angularVelocity))}frameUpdate(t){}clone(){return new rs(this.angularVelocity.clone())}reset(){}}class ns{constructor(t){this.angularVelocity=t,this.type="Rotation3DOverLife",this.tempQuat=new W,this.tempQuat2=new W}initialize(t){t.rotation instanceof W&&(t.angularVelocity=new W,this.angularVelocity.startGen(t.memory))}update(t,e){t.rotation instanceof W&&(this.angularVelocity.genValue(t.memory,this.tempQuat,e,t.age/t.life),t.rotation.multiply(this.tempQuat))}toJSON(){return{type:this.type,angularVelocity:this.angularVelocity.toJSON()}}static fromJSON(t){return new ns(Ba(t.angularVelocity))}frameUpdate(t){}clone(){return new ns(this.angularVelocity.clone())}reset(){}}class os{initialize(t,e){this.ps=e,this.x.startGen(t.memory),this.y.startGen(t.memory),this.z.startGen(t.memory)}constructor(t,e,i){this.x=t,this.y=e,this.z=i,this.type="ForceOverLife",this._temp=new I,this._tempScale=new I,this._tempQ=new W}update(t,e){this._temp.set(this.x.genValue(t.memory,t.age/t.life),this.y.genValue(t.memory,t.age/t.life),this.z.genValue(t.memory,t.age/t.life)),this.ps.worldSpace?t.velocity.addScaledVector(this._temp,e):(this._temp.multiply(this._tempScale).applyQuaternion(this._tempQ),t.velocity.addScaledVector(this._temp,e))}toJSON(){return{type:this.type,x:this.x.toJSON(),y:this.y.toJSON(),z:this.z.toJSON()}}static fromJSON(t){return new os(L(t.x),L(t.y),L(t.z))}frameUpdate(t){if(this.ps&&!this.ps.worldSpace){const e=this._temp,i=this._tempQ,s=this._tempScale;this.ps.emitter.matrixWorld.decompose(e,i,s),i.invert(),s.set(1/s.x,1/s.y,1/s.z)}}clone(){return new os(this.x.clone(),this.y.clone(),this.z.clone())}reset(){}}class as{initialize(t){this.size.startGen(t.memory)}constructor(t){this.size=t,this.type="SizeOverLife"}update(t){this.size instanceof qe?this.size.genValue(t.memory,t.size,t.age/t.life).multiply(t.startSize):t.size.copy(t.startSize).multiplyScalar(this.size.genValue(t.memory,t.age/t.life))}toJSON(){return{type:this.type,size:this.size.toJSON()}}static fromJSON(t){return new as(cr(t.size))}frameUpdate(t){}clone(){return new as(this.size.clone())}reset(){}}class ls{initialize(t){this.speed.startGen(t.memory)}constructor(t){this.speed=t,this.type="SpeedOverLife"}update(t){t.speedModifier=this.speed.genValue(t.memory,t.age/t.life)}toJSON(){return{type:this.type,speed:this.speed.toJSON()}}static fromJSON(t){return new ls(L(t.speed))}frameUpdate(t){}clone(){return new ls(this.speed.clone())}reset(){}}class hs{constructor(t){this.frame=t,this.type="FrameOverLife"}initialize(t){this.frame.startGen(t.memory)}update(t,e){this.frame instanceof Ji&&(t.uvTile=this.frame.genValue(t.memory,t.age/t.life))}frameUpdate(t){}toJSON(){return{type:this.type,frame:this.frame.toJSON()}}static fromJSON(t){return new hs(L(t.frame))}clone(){return new hs(this.frame.clone())}reset(){}}class cs{constructor(t,e=new I(0,1,0)){this.orbitSpeed=t,this.axis=e,this.type="OrbitOverLife",this.temp=new I,this.rotation=new W}initialize(t){this.orbitSpeed.startGen(t.memory)}update(t,e){this.temp.copy(t.position).projectOnVector(this.axis),this.rotation.setFromAxisAngle(this.axis,this.orbitSpeed.genValue(t.memory,t.age/t.life)*e),t.position.sub(this.temp),t.position.applyQuaternion(this.rotation),t.position.add(this.temp)}frameUpdate(t){}toJSON(){return{type:this.type,orbitSpeed:this.orbitSpeed.toJSON(),axis:[this.axis.x,this.axis.y,this.axis.z]}}static fromJSON(t){return new cs(L(t.orbitSpeed),t.axis?new I(t.axis[0],t.axis[1],t.axis[2]):void 0)}clone(){return new cs(this.orbitSpeed.clone())}reset(){}}class jr{constructor(t){this.data=t,this.next=null,this.prev=null}hasPrev(){return this.prev!==null}hasNext(){return this.next!==null}}class id{constructor(){this.length=0,this.head=this.tail=null}isEmpty(){return this.head===null}clear(){this.length=0,this.head=this.tail=null}front(){return this.head===null?null:this.head.data}back(){return this.tail===null?null:this.tail.data}dequeue(){if(this.head){const t=this.head.data;return this.head=this.head.next,this.head?this.head.prev=null:this.tail=null,this.length--,t}}pop(){if(this.tail){const t=this.tail.data;return this.tail=this.tail.prev,this.tail?this.tail.next=null:this.head=null,this.length--,t}}queue(t){const e=new jr(t);this.tail||(this.tail=e),this.head&&(this.head.prev=e,e.next=this.head),this.head=e,this.length++}push(t){const e=new jr(t);this.head||(this.head=e),this.tail&&(this.tail.next=e,e.prev=this.tail),this.tail=e,this.length++}insertBefore(t,e){const i=new jr(e);i.next=t,i.prev=t.prev,i.prev!==null&&(i.prev.next=i),i.next.prev=i,t==this.head&&(this.head=i),this.length++}remove(t){if(this.head===null||this.tail===null)return;let e=this.head;for(t===this.head.data&&(this.head=this.head.next),t===this.tail.data&&(this.tail=this.tail.prev);e.next!==null&&e.data!==t;)e=e.next;e.data===t&&(e.prev!==null&&(e.prev.next=e.next),e.next!==null&&(e.next.prev=e.prev),this.length--)}*values(){let t=this.head;for(;t!==null;)yield t.data,t=t.next}}class sd{constructor(){this.startSpeed=0,this.startColor=new Ht,this.startSize=new I(1,1,1),this.position=new I,this.velocity=new I,this.age=0,this.life=1,this.size=new I(1,1,1),this.speedModifier=1,this.rotation=0,this.color=new Ht,this.uvTile=0,this.memory=[]}get died(){return this.age>=this.life}reset(){this.memory.length=0}}class rd{constructor(t,e,i){this.position=t,this.size=e,this.color=i}}class yn{constructor(){this.startSpeed=0,this.startColor=new Ht,this.startSize=new I(1,1,1),this.position=new I,this.velocity=new I,this.age=0,this.life=1,this.size=new I(1,1,1),this.length=100,this.speedModifier=1,this.color=new Ht,this.previous=new id,this.uvTile=0,this.memory=[]}update(){for(this.age<=this.life?this.previous.push(new rd(this.position.clone(),this.size.x,this.color.clone())):this.previous.length>0&&this.previous.dequeue();this.previous.length>this.length;)this.previous.dequeue()}get died(){return this.age>=this.life}reset(){this.memory.length=0,this.previous.clear()}}class ds{initialize(t){this.width.startGen(t.memory)}constructor(t){this.width=t,this.type="WidthOverLength"}update(t){if(t instanceof yn){const e=t.previous.values();for(let i=0;i<t.previous.length;i++){const s=e.next();s.value.size=this.width.genValue(t.memory,(t.previous.length-i)/t.length)}}}frameUpdate(t){}toJSON(){return{type:this.type,width:this.width.toJSON()}}static fromJSON(t){return new ds(L(t.width))}clone(){return new ds(this.width.clone())}reset(){}}class us{constructor(t,e){this.direction=t,this.magnitude=e,this.type="ApplyForce",this.memory={data:[],dataCount:0},this.magnitudeValue=this.magnitude.genValue(this.memory)}initialize(t){}update(t,e){t.velocity.addScaledVector(this.direction,this.magnitudeValue*e)}frameUpdate(t){this.magnitudeValue=this.magnitude.genValue(this.memory)}toJSON(){return{type:this.type,direction:[this.direction.x,this.direction.y,this.direction.z],magnitude:this.magnitude.toJSON()}}static fromJSON(t){return new us(new I(t.direction[0],t.direction[1],t.direction[2]),L(t.magnitude??t.force))}clone(){return new us(this.direction.clone(),this.magnitude.clone())}reset(){}}class ps{constructor(t,e){this.center=t,this.magnitude=e,this.type="GravityForce",this.temp=new I}initialize(t){}update(t,e){this.temp.copy(this.center).sub(t.position).normalize(),t.velocity.addScaledVector(this.temp,this.magnitude/t.position.distanceToSquared(this.center)*e)}frameUpdate(t){}toJSON(){return{type:this.type,center:[this.center.x,this.center.y,this.center.z],magnitude:this.magnitude}}static fromJSON(t){return new ps(new I(t.center[0],t.center[1],t.center[2]),t.magnitude)}clone(){return new ps(this.center.clone(),this.magnitude)}reset(){}}class fs{constructor(t){this.angle=t,this.type="ChangeEmitDirection",this._temp=new I,this._q=new W,this.memory={data:[],dataCount:0}}initialize(t){const e=t.velocity.length();e!=0&&(t.velocity.normalize(),t.velocity.x===0&&t.velocity.y===0?this._temp.set(0,t.velocity.z,0):this._temp.set(-t.velocity.y,t.velocity.x,0),this.angle.startGen(this.memory),this._q.setFromAxisAngle(this._temp.normalize(),this.angle.genValue(this.memory)),this._temp.copy(t.velocity),t.velocity.applyQuaternion(this._q),this._q.setFromAxisAngle(this._temp,Math.random()*Math.PI*2),t.velocity.applyQuaternion(this._q),t.velocity.setLength(e))}update(t,e){}frameUpdate(t){}toJSON(){return{type:this.type,angle:this.angle.toJSON()}}static fromJSON(t){return new fs(L(t.angle))}clone(){return new fs(this.angle)}reset(){}}var ci;(function(o){o[o.Death=0]="Death",o[o.Birth=1]="Birth",o[o.Frame=2]="Frame"})(ci||(ci={}));class xi{constructor(t,e,i,s=ci.Frame,r=1){this.particleSystem=t,this.useVelocityAsBasis=e,this.subParticleSystem=i,this.mode=s,this.emitProbability=r,this.type="EmitSubParticleSystem",this.q_=new W,this.v_=new I,this.v2_=new I,this.subEmissions=new Array,this.subParticleSystem&&this.subParticleSystem.system&&(this.subParticleSystem.system.onlyUsedByOther=!0)}initialize(t){}update(t,e){this.mode===ci.Frame?this.emit(t,e):this.mode===ci.Birth&&t.age===0?this.emit(t,e):this.mode===ci.Death&&t.age+e>=t.life&&this.emit(t,e)}emit(t,e){if(!this.subParticleSystem||Math.random()>this.emitProbability)return;const i=new Zt;this.setMatrixFromParticle(i,t),this.subEmissions.push({burstParticleCount:0,burstParticleIndex:0,isBursting:!1,burstIndex:0,burstWaveIndex:0,time:0,waitEmiting:0,matrix:i,travelDistance:0,particle:t})}frameUpdate(t){if(this.subParticleSystem)for(let e=0;e<this.subEmissions.length;e++)if(this.subEmissions[e].time>=this.subParticleSystem.system.duration)this.subEmissions[e]=this.subEmissions[this.subEmissions.length-1],this.subEmissions.length=this.subEmissions.length-1,e--;else{const i=this.subEmissions[e];i.particle&&i.particle.age<i.particle.life?this.setMatrixFromParticle(i.matrix,i.particle):i.particle=void 0,this.subParticleSystem.system.emit(t,i,i.matrix)}}toJSON(){return{type:this.type,subParticleSystem:this.subParticleSystem?this.subParticleSystem.uuid:"",useVelocityAsBasis:this.useVelocityAsBasis,mode:this.mode,emitProbability:this.emitProbability}}static fromJSON(t,e){return new xi(e,t.useVelocityAsBasis,t.subParticleSystem,t.mode,t.emitProbability)}clone(){return new xi(this.particleSystem,this.useVelocityAsBasis,this.subParticleSystem,this.mode,this.emitProbability)}reset(){}setMatrixFromParticle(t,e){let i;if(e.rotation===void 0||this.useVelocityAsBasis)if(e.velocity.x===0&&e.velocity.y===0&&(e.velocity.z===1||e.velocity.z===0))t.set(1,0,0,e.position.x,0,1,0,e.position.y,0,0,1,e.position.z,0,0,0,1);else{this.v_.copy(Ro).cross(e.velocity),this.v2_.copy(e.velocity).cross(this.v_);const s=this.v_.length(),r=this.v2_.length();t.set(this.v_.x/s,this.v2_.x/r,e.velocity.x,e.position.x,this.v_.y/s,this.v2_.y/r,e.velocity.y,e.position.y,this.v_.z/s,this.v2_.z/r,e.velocity.z,e.position.z,0,0,0,1)}else e.rotation instanceof W?i=e.rotation:(this.q_.setFromAxisAngle(Ro,e.rotation),i=this.q_),t.compose(e.position,i,td);this.particleSystem.worldSpace||t.multiplyMatrices(this.particleSystem.emitter.matrixWorld,t)}}const nd=.5*(Math.sqrt(3)-1),Ri=(3-Math.sqrt(3))/6,od=1/3,Kt=1/6,ad=(Math.sqrt(5)-1)/4,Ct=(5-Math.sqrt(5))/20,vt=new Float32Array([1,1,0,-1,1,0,1,-1,0,-1,-1,0,1,0,1,-1,0,1,1,0,-1,-1,0,-1,0,1,1,0,-1,1,0,1,-1,0,-1,-1]),ft=new Float32Array([0,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,1,0,1,1,1,0,1,-1,1,0,-1,1,1,0,-1,-1,-1,0,1,1,-1,0,1,-1,-1,0,-1,1,-1,0,-1,-1,1,1,0,1,1,1,0,-1,1,-1,0,1,1,-1,0,-1,-1,1,0,1,-1,1,0,-1,-1,-1,0,1,-1,-1,0,-1,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,0]);class Na{constructor(t=Math.random){const e=typeof t=="function"?t:hd(t);this.p=ld(e),this.perm=new Uint8Array(512),this.permMod12=new Uint8Array(512);for(let i=0;i<512;i++)this.perm[i]=this.p[i&255],this.permMod12[i]=this.perm[i]%12}noise2D(t,e){const i=this.permMod12,s=this.perm;let r=0,n=0,a=0;const l=(t+e)*nd,h=Math.floor(t+l),d=Math.floor(e+l),c=(h+d)*Ri,p=h-c,u=d-c,f=t-p,m=e-u;let y,g;f>m?(y=1,g=0):(y=0,g=1);const _=f-y+Ri,M=m-g+Ri,w=f-1+2*Ri,C=m-1+2*Ri,x=h&255,b=d&255;let P=.5-f*f-m*m;if(P>=0){const J=i[x+s[b]]*3;P*=P,r=P*P*(vt[J]*f+vt[J+1]*m)}let A=.5-_*_-M*M;if(A>=0){const J=i[x+y+s[b+g]]*3;A*=A,n=A*A*(vt[J]*_+vt[J+1]*M)}let N=.5-w*w-C*C;if(N>=0){const J=i[x+1+s[b+1]]*3;N*=N,a=N*N*(vt[J]*w+vt[J+1]*C)}return 70*(r+n+a)}noise3D(t,e,i){const s=this.permMod12,r=this.perm;let n,a,l,h;const d=(t+e+i)*od,c=Math.floor(t+d),p=Math.floor(e+d),u=Math.floor(i+d),f=(c+p+u)*Kt,m=c-f,y=p-f,g=u-f,_=t-m,M=e-y,w=i-g;let C,x,b,P,A,N;_>=M?M>=w?(C=1,x=0,b=0,P=1,A=1,N=0):_>=w?(C=1,x=0,b=0,P=1,A=0,N=1):(C=0,x=0,b=1,P=1,A=0,N=1):M<w?(C=0,x=0,b=1,P=0,A=1,N=1):_<w?(C=0,x=1,b=0,P=0,A=1,N=1):(C=0,x=1,b=0,P=1,A=1,N=0);const J=_-C+Kt,$=M-x+Kt,gt=w-b+Kt,Y=_-P+2*Kt,K=M-A+2*Kt,lt=w-N+2*Kt,st=_-1+3*Kt,ct=M-1+3*Kt,tt=w-1+3*Kt,dt=c&255,ut=p&255,V=u&255;let yt=.6-_*_-M*M-w*w;if(yt<0)n=0;else{const at=s[dt+r[ut+r[V]]]*3;yt*=yt,n=yt*yt*(vt[at]*_+vt[at+1]*M+vt[at+2]*w)}let D=.6-J*J-$*$-gt*gt;if(D<0)a=0;else{const at=s[dt+C+r[ut+x+r[V+b]]]*3;D*=D,a=D*D*(vt[at]*J+vt[at+1]*$+vt[at+2]*gt)}let Ft=.6-Y*Y-K*K-lt*lt;if(Ft<0)l=0;else{const at=s[dt+P+r[ut+A+r[V+N]]]*3;Ft*=Ft,l=Ft*Ft*(vt[at]*Y+vt[at+1]*K+vt[at+2]*lt)}let Pt=.6-st*st-ct*ct-tt*tt;if(Pt<0)h=0;else{const at=s[dt+1+r[ut+1+r[V+1]]]*3;Pt*=Pt,h=Pt*Pt*(vt[at]*st+vt[at+1]*ct+vt[at+2]*tt)}return 32*(n+a+l+h)}noise4D(t,e,i,s){const r=this.perm;let n,a,l,h,d;const c=(t+e+i+s)*ad,p=Math.floor(t+c),u=Math.floor(e+c),f=Math.floor(i+c),m=Math.floor(s+c),y=(p+u+f+m)*Ct,g=p-y,_=u-y,M=f-y,w=m-y,C=t-g,x=e-_,b=i-M,P=s-w;let A=0,N=0,J=0,$=0;C>x?A++:N++,C>b?A++:J++,C>P?A++:$++,x>b?N++:J++,x>P?N++:$++,b>P?J++:$++;const gt=A>=3?1:0,Y=N>=3?1:0,K=J>=3?1:0,lt=$>=3?1:0,st=A>=2?1:0,ct=N>=2?1:0,tt=J>=2?1:0,dt=$>=2?1:0,ut=A>=1?1:0,V=N>=1?1:0,yt=J>=1?1:0,D=$>=1?1:0,Ft=C-gt+Ct,Pt=x-Y+Ct,at=b-K+Ct,Qe=P-lt+Ct,$e=C-st+2*Ct,ke=x-ct+2*Ct,Ke=b-tt+2*Ct,ti=P-dt+2*Ct,ei=C-ut+3*Ct,me=x-V+3*Ct,ii=b-yt+3*Ct,si=P-D+3*Ct,Fe=C-1+4*Ct,re=x-1+4*Ct,ge=b-1+4*Ct,ye=P-1+4*Ct,Qt=p&255,ne=u&255,_t=f&255,oe=m&255;let _e=.6-C*C-x*x-b*b-P*P;if(_e<0)n=0;else{const et=r[Qt+r[ne+r[_t+r[oe]]]]%32*4;_e*=_e,n=_e*_e*(ft[et]*C+ft[et+1]*x+ft[et+2]*b+ft[et+3]*P)}let ve=.6-Ft*Ft-Pt*Pt-at*at-Qe*Qe;if(ve<0)a=0;else{const et=r[Qt+gt+r[ne+Y+r[_t+K+r[oe+lt]]]]%32*4;ve*=ve,a=ve*ve*(ft[et]*Ft+ft[et+1]*Pt+ft[et+2]*at+ft[et+3]*Qe)}let Be=.6-$e*$e-ke*ke-Ke*Ke-ti*ti;if(Be<0)l=0;else{const et=r[Qt+st+r[ne+ct+r[_t+tt+r[oe+dt]]]]%32*4;Be*=Be,l=Be*Be*(ft[et]*$e+ft[et+1]*ke+ft[et+2]*Ke+ft[et+3]*ti)}let Ne=.6-ei*ei-me*me-ii*ii-si*si;if(Ne<0)h=0;else{const et=r[Qt+ut+r[ne+V+r[_t+yt+r[oe+D]]]]%32*4;Ne*=Ne,h=Ne*Ne*(ft[et]*ei+ft[et+1]*me+ft[et+2]*ii+ft[et+3]*si)}let xe=.6-Fe*Fe-re*re-ge*ge-ye*ye;if(xe<0)d=0;else{const et=r[Qt+1+r[ne+1+r[_t+1+r[oe+1]]]]%32*4;xe*=xe,d=xe*xe*(ft[et]*Fe+ft[et+1]*re+ft[et+2]*ge+ft[et+3]*ye)}return 27*(n+a+l+h+d)}}function ld(o){const t=new Uint8Array(256);for(let e=0;e<256;e++)t[e]=e;for(let e=0;e<255;e++){const i=e+~~(o()*(256-e)),s=t[e];t[e]=t[i],t[i]=s}return t}function hd(o){let t=0,e=0,i=0,s=1;const r=cd();return t=r(" "),e=r(" "),i=r(" "),t-=r(o),t<0&&(t+=1),e-=r(o),e<0&&(e+=1),i-=r(o),i<0&&(i+=1),function(){const n=2091639*t+s*23283064365386963e-26;return t=e,e=i,i=n-(s=n|0)}}function cd(){let o=4022871197;return function(t){t=t.toString();for(let e=0;e<t.length;e++){o+=t.charCodeAt(e);let i=.02519603282416938*o;o=i>>>0,i-=o,i*=o,o=i>>>0,i-=o,o+=i*4294967296}return(o>>>0)*23283064365386963e-26}}class ms{constructor(t,e,i,s){this.scale=t,this.octaves=e,this.velocityMultiplier=i,this.timeScale=s,this.type="TurbulenceField",this.generator=new Na,this.timeOffset=new I,this.temp=new I,this.temp2=new I,this.timeOffset.x=Math.random()/this.scale.x*this.timeScale.x,this.timeOffset.y=Math.random()/this.scale.y*this.timeScale.y,this.timeOffset.z=Math.random()/this.scale.z*this.timeScale.z}initialize(t){}update(t,e){const i=t.position.x/this.scale.x,s=t.position.y/this.scale.y,r=t.position.z/this.scale.z;this.temp.set(0,0,0);let n=1;for(let a=0;a<this.octaves;a++)this.temp2.set(this.generator.noise4D(i*n,s*n,r*n,this.timeOffset.x*n)/n,this.generator.noise4D(i*n,s*n,r*n,this.timeOffset.y*n)/n,this.generator.noise4D(i*n,s*n,r*n,this.timeOffset.z*n)/n),this.temp.add(this.temp2),n*=2;this.temp.multiply(this.velocityMultiplier),t.velocity.addScaledVector(this.temp,e)}toJSON(){return{type:this.type,scale:[this.scale.x,this.scale.y,this.scale.z],octaves:this.octaves,velocityMultiplier:[this.velocityMultiplier.x,this.velocityMultiplier.y,this.velocityMultiplier.z],timeScale:[this.timeScale.x,this.timeScale.y,this.timeScale.z]}}frameUpdate(t){this.timeOffset.x+=t*this.timeScale.x,this.timeOffset.y+=t*this.timeScale.y,this.timeOffset.z+=t*this.timeScale.z}static fromJSON(t){return new ms(new I(t.scale[0],t.scale[1],t.scale[2]),t.octaves,new I(t.velocityMultiplier[0],t.velocityMultiplier[1],t.velocityMultiplier[2]),new I(t.timeScale[0],t.timeScale[1],t.timeScale[2]))}clone(){return new ms(this.scale.clone(),this.octaves,this.velocityMultiplier.clone(),this.timeScale.clone())}reset(){}}const te=[],Gr=new I,Xr=new W;class gs{constructor(t,e,i=new Q(1),s=new Q(0)){if(this.frequency=t,this.power=e,this.positionAmount=i,this.rotationAmount=s,this.type="Noise",this.duration=0,te.length===0)for(let r=0;r<100;r++)te.push(new Na)}initialize(t){t.lastPosNoise=new I,typeof t.rotation=="number"?t.lastRotNoise=0:t.lastRotNoise=new W,t.generatorIndex=[$s(0,100),$s(0,100),$s(0,100),$s(0,100)],this.positionAmount.startGen(t.memory),this.rotationAmount.startGen(t.memory),this.frequency.startGen(t.memory),this.power.startGen(t.memory)}update(t,e){let i=this.frequency.genValue(t.memory,t.age/t.life),s=this.power.genValue(t.memory,t.age/t.life),r=this.positionAmount.genValue(t.memory,t.age/t.life),n=this.rotationAmount.genValue(t.memory,t.age/t.life);r>0&&t.lastPosNoise!==void 0&&(t.position.sub(t.lastPosNoise),Gr.set(te[t.generatorIndex[0]].noise2D(0,t.age*i)*s*r,te[t.generatorIndex[1]].noise2D(0,t.age*i)*s*r,te[t.generatorIndex[2]].noise2D(0,t.age*i)*s*r),t.position.add(Gr),t.lastPosNoise.copy(Gr)),n>0&&t.lastRotNoise!==void 0&&(typeof t.rotation=="number"?(t.rotation-=t.lastRotNoise,t.rotation+=te[t.generatorIndex[3]].noise2D(0,t.age*i)*Math.PI*s*n):(t.lastRotNoise.invert(),t.rotation.multiply(t.lastRotNoise),Xr.set(te[t.generatorIndex[0]].noise2D(0,t.age*i)*s*n,te[t.generatorIndex[1]].noise2D(0,t.age*i)*s*n,te[t.generatorIndex[2]].noise2D(0,t.age*i)*s*n,te[t.generatorIndex[3]].noise2D(0,t.age*i)*s*n).normalize(),t.rotation.multiply(Xr),t.lastRotNoise.copy(Xr)))}toJSON(){return{type:this.type,frequency:this.frequency.toJSON(),power:this.power.toJSON(),positionAmount:this.positionAmount.toJSON(),rotationAmount:this.rotationAmount.toJSON()}}frameUpdate(t){this.duration+=t}static fromJSON(t){return new gs(L(t.frequency),L(t.power),L(t.positionAmount),L(t.rotationAmount))}clone(){return new gs(this.frequency.clone(),this.power.clone(),this.positionAmount.clone(),this.rotationAmount.clone())}reset(){}}class ys{constructor(t,e){this.color=t,this.speedRange=e,this.type="ColorBySpeed"}initialize(t){this.color.startGen(t.memory)}update(t,e){const i=(t.startSpeed-this.speedRange.a)/(this.speedRange.b-this.speedRange.a);this.color.genColor(t.memory,t.color,i),t.color.x*=t.startColor.x,t.color.y*=t.startColor.y,t.color.z*=t.startColor.z,t.color.w*=t.startColor.w}frameUpdate(t){}toJSON(){return{type:this.type,color:this.color.toJSON(),speedRange:this.speedRange.toJSON()}}static fromJSON(t){return new ys(On(t.color),Ye.fromJSON(t.speedRange))}clone(){return new ys(this.color.clone(),this.speedRange.clone())}reset(){}}class _s{initialize(t){this.size.startGen(t.memory)}constructor(t,e){this.size=t,this.speedRange=e,this.type="SizeBySpeed"}update(t){const e=(t.startSpeed-this.speedRange.a)/(this.speedRange.b-this.speedRange.a);this.size instanceof qe?this.size.genValue(t.memory,t.size,e).multiply(t.startSize):t.size.copy(t.startSize).multiplyScalar(this.size.genValue(t.memory,e))}toJSON(){return{type:this.type,size:this.size.toJSON(),speedRange:this.speedRange.toJSON()}}static fromJSON(t){return new _s(cr(t.size),Ye.fromJSON(t.speedRange))}frameUpdate(t){}clone(){return new _s(this.size.clone(),this.speedRange.clone())}reset(){}}class vs{constructor(t,e){this.angularVelocity=t,this.speedRange=e,this.type="RotationBySpeed",this.tempQuat=new W}initialize(t){typeof t.rotation=="number"&&this.angularVelocity.startGen(t.memory)}update(t,e){if(typeof t.rotation=="number"){const i=(t.startSpeed-this.speedRange.a)/(this.speedRange.b-this.speedRange.a);t.rotation+=e*this.angularVelocity.genValue(t.memory,i)}}toJSON(){return{type:this.type,angularVelocity:this.angularVelocity.toJSON(),speedRange:this.speedRange.toJSON()}}static fromJSON(t){return new vs(L(t.angularVelocity),Ye.fromJSON(t.speedRange))}frameUpdate(t){}clone(){return new vs(this.angularVelocity.clone(),this.speedRange.clone())}reset(){}}class xs{initialize(t){this.speed.startGen(t.memory)}constructor(t,e){this.speed=t,this.dampen=e,this.type="LimitSpeedOverLife"}update(t,e){let i=t.velocity.length(),s=this.speed.genValue(t.memory,t.age/t.life);if(i>s){const r=(i-s)/i;t.velocity.multiplyScalar(1-r*this.dampen*e*20)}}toJSON(){return{type:this.type,speed:this.speed.toJSON(),dampen:this.dampen}}static fromJSON(t){return new xs(L(t.speed),t.dampen)}frameUpdate(t){}clone(){return new xs(this.speed.clone(),this.dampen)}reset(){}}const dr={ApplyForce:{type:"ApplyForce",constructor:us,params:[["direction",["vec3"]],["magnitude",["value"]]],loadJSON:us.fromJSON},Noise:{type:"Noise",constructor:gs,params:[["frequency",["value"]],["power",["value"]],["positionAmount",["value"]],["rotationAmount",["value"]]],loadJSON:gs.fromJSON},TurbulenceField:{type:"TurbulenceField",constructor:ms,params:[["scale",["vec3"]],["octaves",["number"]],["velocityMultiplier",["vec3"]],["timeScale",["vec3"]]],loadJSON:ms.fromJSON},GravityForce:{type:"GravityForce",constructor:ps,params:[["center",["vec3"]],["magnitude",["number"]]],loadJSON:ps.fromJSON},ColorOverLife:{type:"ColorOverLife",constructor:ss,params:[["color",["colorFunc"]]],loadJSON:ss.fromJSON},RotationOverLife:{type:"RotationOverLife",constructor:rs,params:[["angularVelocity",["value","valueFunc"]]],loadJSON:rs.fromJSON},Rotation3DOverLife:{type:"Rotation3DOverLife",constructor:ns,params:[["angularVelocity",["rotationFunc"]]],loadJSON:ns.fromJSON},SizeOverLife:{type:"SizeOverLife",constructor:as,params:[["size",["value","valueFunc","vec3Func"]]],loadJSON:as.fromJSON},ColorBySpeed:{type:"ColorBySpeed",constructor:ys,params:[["color",["colorFunc"]],["speedRange",["range"]]],loadJSON:ys.fromJSON},RotationBySpeed:{type:"RotationBySpeed",constructor:vs,params:[["angularVelocity",["value","valueFunc"]],["speedRange",["range"]]],loadJSON:vs.fromJSON},SizeBySpeed:{type:"SizeBySpeed",constructor:_s,params:[["size",["value","valueFunc","vec3Func"]],["speedRange",["range"]]],loadJSON:_s.fromJSON},SpeedOverLife:{type:"SpeedOverLife",constructor:ls,params:[["speed",["value","valueFunc"]]],loadJSON:ls.fromJSON},FrameOverLife:{type:"FrameOverLife",constructor:hs,params:[["frame",["value","valueFunc"]]],loadJSON:hs.fromJSON},ForceOverLife:{type:"ForceOverLife",constructor:os,params:[["x",["value","valueFunc"]],["y",["value","valueFunc"]],["z",["value","valueFunc"]]],loadJSON:os.fromJSON},OrbitOverLife:{type:"OrbitOverLife",constructor:cs,params:[["orbitSpeed",["value","valueFunc"]],["axis",["vec3"]]],loadJSON:cs.fromJSON},WidthOverLength:{type:"WidthOverLength",constructor:ds,params:[["width",["value","valueFunc"]]],loadJSON:ds.fromJSON},ChangeEmitDirection:{type:"ChangeEmitDirection",constructor:fs,params:[["angle",["value"]]],loadJSON:fs.fromJSON},EmitSubParticleSystem:{type:"EmitSubParticleSystem",constructor:xi,params:[["particleSystem",["self"]],["useVelocityAsBasis",["boolean"]],["subParticleSystem",["particleSystem"]],["mode",["number"]],["emitProbability",["number"]]],loadJSON:xi.fromJSON},LimitSpeedOverLife:{type:"LimitSpeedOverLife",constructor:xs,params:[["speed",["value","valueFunc"]],["dampen",["number"]]],loadJSON:xs.fromJSON}};function dd(o,t){return dr[o.type]?dr[o.type].loadJSON(o,t):null}const ud=[];function pd(o){if(!ud.find(e=>e.id===o.id)){for(const e of o.emitterShapes)gn[e.type]||(gn[e.type]=e);for(const e of o.behaviors)dr[e.type]||(dr[e.type]=e)}}class ws{get geometry(){return this._geometry}set geometry(t){if(this._geometry=t,t===void 0||typeof t=="string")return;const e=new Bh;this._triangleIndexToArea.length=0;let i=0;if(!t.getIndex())return;const s=t.getIndex().array,r=s.length/3;this._triangleIndexToArea.push(0);for(let n=0;n<r;n++)e.setFromAttributeAndIndices(t.getAttribute("position"),s[n*3],s[n*3+1],s[n*3+2]),i+=e.getArea(),this._triangleIndexToArea.push(i);t.userData.triangleIndexToArea=this._triangleIndexToArea}constructor(t){this.type="mesh_surface",this._triangleIndexToArea=[],this._tempA=new v,this._tempB=new v,this._tempC=new v,t&&(this.geometry=t)}initialize(t){const e=this._geometry;if(!e||e.getIndex()===null){t.position.set(0,0,0),t.velocity.set(0,0,1).multiplyScalar(t.startSpeed);return}const i=this._triangleIndexToArea.length-1;let s=0,r=i;const n=Math.random()*this._triangleIndexToArea[i];for(;s+1<r;){const u=Math.floor((s+r)/2);n<this._triangleIndexToArea[u]?r=u:s=u}let a=Math.random(),l=Math.random();a+l>1&&(a=1-a,l=1-l);const h=e.getIndex().array[s*3],d=e.getIndex().array[s*3+1],c=e.getIndex().array[s*3+2],p=e.getAttribute("position");this._tempA.fromBufferAttribute(p,h),this._tempB.fromBufferAttribute(p,d),this._tempC.fromBufferAttribute(p,c),this._tempB.sub(this._tempA),this._tempC.sub(this._tempA),this._tempA.addScaledVector(this._tempB,a).addScaledVector(this._tempC,l),t.position.copy(this._tempA),this._tempA.copy(this._tempB).cross(this._tempC).normalize(),t.velocity.copy(this._tempA).normalize().multiplyScalar(t.startSpeed)}toJSON(){return{type:"mesh_surface",mesh:this._geometry?this._geometry.uuid:""}}static fromJSON(t,e){return new ws(e.geometries[t.geometry])}clone(){return new ws(this._geometry)}update(t,e){}}const fd={id:"three.quarks",emitterShapes:[{type:"mesh_surface",params:[["geometry",["geometry"]]],constructor:ws,loadJSON:ws.fromJSON}],behaviors:[]};var md=`
3
3
  #ifdef SOFT_PARTICLES
4
4
 
5
5
  /* #ifdef LOGDEPTH
@@ -1117,10 +1117,10 @@ void main() {`).replace("gl_FragColor = vec4( diffuseColor.rgb, alpha );","gl_Fr
1117
1117
  gl_FragColor = vec4(mix(uColor, uMajorColor, majorShare), alpha);
1118
1118
  #include <colorspace_fragment>
1119
1119
  }
1120
- `,transparent:!0,depthWrite:!1,side:We}),i=new E(t,e);return i.name="editor-floor-grid",i}class Nn{setTransformMode(t){this._store.setTransformMode(t)}camera;orthographicCamera;orbitControls;transformControls;_auxRotateControls;_auxScaleControls;_activeGizmo;raycaster=(()=>{const t=new Yt;return t.layers.enableAll(),t})();grid;_boxHelpers=new Map;_unsubscribeSelectionTheme=()=>{};_constraintHelpers=new Map;_constraintControlRaycaster=(()=>{const t=new Yt;return t.layers.enableAll(),t})();_hoveredConstraintControl=null;_constraintControlPointerSession=!1;_reflectionProbeHelpers=new Map;_triggerVolumeHelpers=new Map;_cameraHelpers=new Map;_lightHelpers=new Map;_audioHelpers=new Map;_spatialHandleRoots=[];_spatialHandleMeshes=[];_spatialHandleRaycaster=(()=>{const t=new Yt;return t.layers.enableAll(),t})();_activeSpatialHandle=null;_hoveredSpatialHandle=null;_spatialHandleDragPlane=new fo;_spatialHandleDragOffset=new v;_spatialHandleDragPoint=new v;_orbitEnabledBeforeHandleDrag=!0;_transformEnabledBeforeHandleDrag=!0;_gizmoHelper;_editorAmbient;_editorDirLight;_lightRig;_scene;_contentBoundsBox=new ie;_contentBoundsAt=0;_renderer;_sparkRenderer=null;_sparkRendererLoading=!1;_sparkRendererFailed=!1;_lastSparkDiscoveryAt=Number.NEGATIVE_INFINITY;_disposed=!1;_editorObjects=[];_axisLines=null;_axesWanted=!1;_lookAxisHexes=null;_lookGridHex=null;_lookBackgroundHex=null;_lookToneMapping=null;_lookExposure=null;_lookGizmoSizePx=null;_lookAxisFrame=nn;_appliedAxisSigns=[1,1,1];_lookBoxSelect=null;_store;_objectMap=new Map;_canvas;_interactionElement;_onInteractionPointerUp;_onInteractionDblClick;_authoring;_pick;_standaloneAuthoring;_publishPickContext;_onlineAssetResolver;_onProjectionChange;_pointerDownPos=new Jt;_skipNextSync=!1;_marqueeActive=!1;_pointerSessionActive=!1;_marqueeDiv=null;_pointerDownButton=-1;_altDragOrbit=!1;_vcScene=new yr;_vcCamera;_vcClickTargets=[];_vcBalls=[];_vcStalks=[];_vcSize=mi;_vcMarginRight=Ku;_vcMarginTop=Ja;_chromeInsetPx=0;_vcDir=new v;_previewClearColor=new B;_cameraView=null;_projection="perspective";_pendingProjection=null;_viewportAspect=1;_orthographicHeight=10;_cameraViewMode=null;_orbitEnabledBeforeCameraView=!0;_orbitTargetBeforeCameraView=new v;_lastGizmoObjectMap=null;_lastGizmoSig="";_lastGizmoEpoch=-1;_threejsToolContextActive=!1;_threeSurfaceShowing=!1;_vcRaycaster=new Yt;_dropOverlay=null;_groundPlane=new fo(new v(0,1,0),0);_dragStartPos=new v;_dragStartQuat=new wt;_dragStartScale=new v;_attachedAuthoringId=null;_otherDragObjects=[];_allDragObjects=[];_preservedChildObjects=[];_activeTransformEditIds=[];_pivotDummy=new Je;_dummyIsPresentationAnchor=!1;_pivotPos=new v;_surfaceSnapRaycaster=new Yt;_surfaceSnapIndicator;_vertexSnapTargets=[];_vertexSnapIndicator;_vertexSnapThreshold=20;batchedRenderer;_helpers=new Map;_snapAnimating=!1;_snapStartTime=0;_snapDuration=400;_snapQ1=new wt;_snapQ2=new wt;_snapDist=0;_flyActive=!1;_orbitGesture=!1;_orbitGestureCounted=!1;_snapHold=!1;_flyKeys=new Set;_flySpeed=5;_flyEuler=new va(0,0,0,"YXZ");_rightMouseDown=!1;constructor(t,e,i,s=t,r={}){this._canvas=t,this._interactionElement=s,this._scene=e,this._renderer=r.renderer,this._store=i,this._authoring=r.authoring??(()=>Gs().activeAuthoring(this._store)),this._pick=r.pick,this._standaloneAuthoring=r.authoring!==void 0,this._publishPickContext=r.publishPickContext??!0,this._chromeInsetPx=r.chromeInsetPx??0,this._onlineAssetResolver=r.onlineAssetResolver,this._onProjectionChange=r.onProjectionChange,this.camera=new Ca(Zo(t.clientWidth/Math.max(1,t.clientHeight)),t.clientWidth/t.clientHeight,_o,vo),this.camera.position.copy(qu).multiplyScalar(17.32),this.camera.lookAt(0,0,0),this.camera.layers.enableAll(),this._viewportAspect=t.clientWidth/Math.max(1,t.clientHeight),this.orthographicCamera=new pi(-5,5,5,-5,_o,vo),this.orthographicCamera.layers.enableAll(),this._syncOrthographicFromPerspective(),this.grid=sp(400),this.grid.layers.set(X),e.add(this.grid);const n=new Tn;n.setPositions(ep()),n.setColors(new Array(fr*2*2*3).fill(1)),this._axisLines=new En(n,new zn({vertexColors:!0,linewidth:2,transparent:!0,opacity:1,depthWrite:!1,toneMapped:!1})),ip(this._axisLines.material,this.grid.material.uniforms.uGrazingFade),this._axisLines.visible=!1,this._axisLines.layers.set(X),e.add(this._axisLines),this._unsubscribeSelectionTheme=mr(t,()=>{const l=ze(t).visible;for(const h of this._boxHelpers.values())h instanceof en&&h.setColor(l);this._applyViewportLook(un(t)),this._lookGizmoSizePx=to(t),this._applyGizmoSize(),this._readLookStage(t)}),this._lightRig=r?.lightRig!==!1,this._editorAmbient=new Ma(16777215,.5),this._editorAmbient.layers.set(X),e.add(this._editorAmbient),this._editorDirLight=new gr(16777215,1),this._editorDirLight.position.set(10,20,10),this._editorDirLight.layers.set(X),e.add(this._editorDirLight),this._editorAmbient.visible=this._lightRig,this._editorDirLight.visible=this._lightRig,this.batchedRenderer=new kn,this.batchedRenderer.layers.set(X),e.add(this.batchedRenderer),s.addEventListener("wheel",this._onTrackpadWheel,{passive:!1}),this.orbitControls=new rc(this.camera,s),this.orbitControls.enableDamping=!0,this.orbitControls.dampingFactor=.1,this.orbitControls.mouseButtons={LEFT:-1,MIDDLE:Rr.PAN,RIGHT:Rr.ROTATE},this.transformControls=new Hr(this.camera,t),this._auxScaleControls=new Hr(this.camera,t),this._auxScaleControls.setMode("scale"),this._auxRotateControls=new Hr(this.camera,t),this._auxRotateControls.setMode("rotate"),this._activeGizmo=this.transformControls;const a=l=>{l.getRaycaster().layers.enableAll(),l.addEventListener("dragging-changed",h=>{const d=h.value;if(d?cc():dc(),this.orbitControls.enabled=!d,d){this._activeGizmo=l;for(const m of this._allGizmos())m!==l&&(m.enabled=!1);const c=l.object,p=l.mode==="translate"?"position":l.mode==="rotate"?"rotation":"scale",u=m=>this._authoring().transforms?.editability?.(m,p).writable??!0,f=this._attachedAuthoringId??(c&&this._authoringIdForObject(c))??"";if(c){if(this._dragStartPos.copy(c.position),this._dragStartQuat.copy(c.quaternion),this._dragStartScale.copy(c.scale),this._otherDragObjects=[],this._allDragObjects=[],this._pivotPos.copy(c.position),c===this._pivotDummy?null:this._authoringIdForObject(c))for(const _ of this._store.selectedEntityIds){if(_===f||!u(_))continue;const M=this._objectForAuthoringId(_);M&&this._otherDragObjects.push({id:_,obj:M,startPos:M.position.clone(),startQuat:M.quaternion.clone(),startScale:M.scale.clone()})}else for(const _ of this._store.selectedEntityIds){if(!u(_))continue;const M=this._objectForAuthoringId(_);M&&this._allDragObjects.push({id:_,obj:M,startPos:M.position.clone(),startQuat:M.quaternion.clone(),startScale:M.scale.clone()})}const y=c===this._pivotDummy?this._allDragObjects.map(({id:_})=>_):[f,...this._otherDragObjects.map(({id:_})=>_)];this._preservedChildObjects=this._preparePreservedChildren(y.filter(Boolean)),this._activeTransformEditIds=[...new Set([...y.filter(Boolean),...this._preservedChildObjects.map(({id:_})=>_)])];const g=this._authoring();for(const _ of this._activeTransformEditIds)ro(g,_)}}else this._surfaceSnapIndicator.visible=!1,this._vertexSnapIndicator.visible=!1,this.syncFromStore()}),l.addEventListener("objectChange",()=>{const h=l.object;if(!h)return;const d=l.mode,c=this._store.pivotMode==="individual-origins"||this._dummyIsPresentationAnchor,u=this._allDragObjects.length>0?this._allDragObjects:this._otherDragObjects;if(u.length>0){if(d==="translate"){const f=h.position.clone().sub(this._dragStartPos);for(const{obj:m,startPos:y}of u)m.position.copy(y).add(f)}else if(d==="rotate"){const f=h.quaternion.clone().multiply(this._dragStartQuat.clone().invert());if(c)for(const{obj:m,startQuat:y}of u)m.quaternion.copy(f).multiply(y);else for(const{obj:m,startPos:y,startQuat:g}of u){const _=y.clone().sub(this._pivotPos);_.applyQuaternion(f),m.position.copy(this._pivotPos).add(_),m.quaternion.copy(f).multiply(g)}}else if(d==="scale"){const f=new v(this._dragStartScale.x!==0?h.scale.x/this._dragStartScale.x:1,this._dragStartScale.y!==0?h.scale.y/this._dragStartScale.y:1,this._dragStartScale.z!==0?h.scale.z/this._dragStartScale.z:1);if(c)for(const{obj:m,startScale:y}of u)m.scale.copy(y).multiply(f);else for(const{obj:m,startPos:y,startScale:g}of u){const _=y.clone().sub(this._pivotPos);_.multiply(f),m.position.copy(this._pivotPos).add(_),m.scale.copy(g).multiply(f)}}}d==="translate"&&this._store.vertexSnapActive&&this._vertexSnapTargets.length>0?this._applyVertexSnap(h,u):d==="translate"&&this._store.snapToSurface&&this._applySurfaceSnap(h,u),this._restorePreservedChildren();for(const f of this._boxHelpers.values())"update"in f&&f.update();this._flushGizmoToStoreLive()}),l.addEventListener("mouseUp",()=>{this._flushGizmoToStore()})};a(this.transformControls),a(this._auxRotateControls),a(this._auxScaleControls),this._gizmoHelper=this.transformControls.getHelper(),this._gizmoHelper.traverse(l=>l.layers.set(X)),e.add(this._gizmoHelper);for(const l of[this._auxRotateControls,this._auxScaleControls]){const h=l.getHelper();h.traverse(d=>d.layers.set(X)),h.visible=!1,e.add(h)}this._pivotDummy.layers.set(X),e.add(this._pivotDummy),this._surfaceSnapIndicator=new E(new Uh(.08,.12,16),new Tt({color:65416,side:We,depthTest:!1})),this._surfaceSnapIndicator.rotation.x=-Math.PI/2,this._surfaceSnapIndicator.visible=!1,this._surfaceSnapIndicator.renderOrder=999,this._surfaceSnapIndicator.layers.set(X),e.add(this._surfaceSnapIndicator),this._vertexSnapIndicator=new E(new fe(1,8,8),new Tt({color:65450,depthTest:!1})),this._vertexSnapIndicator.visible=!1,this._vertexSnapIndicator.renderOrder=999,this._vertexSnapIndicator.layers.set(X),e.add(this._vertexSnapIndicator),this._patchGizmo(this._gizmoHelper),this._patchGizmo(this._auxRotateControls.getHelper()),this._patchGizmo(this._auxScaleControls.getHelper()),this._dropNegativeAxisHandles(this._gizmoHelper,["translate","scale"]),this._dropNegativeAxisHandles(this._auxScaleControls.getHelper(),["scale"]),this._patchCombinedScaleGizmo(this._auxScaleControls.getHelper()),this._lookGizmoSizePx=to(t),this._applyGizmoSize(),this._lookAxisFrame=eo(t)==="z"?qo:nn,this._lookBoxSelect=io(t),this._applyGizmoAxisFrame(),this._vcCamera=new pi(-1.5,1.5,1.5,-1.5,.1,10),this._initOrientationGizmo(),window.addEventListener("keydown",this._onFlyKeyDown),window.addEventListener("keyup",this._onFlyKeyUp),s.addEventListener("pointerdown",this._onFlyPointerDown),s.addEventListener("pointerup",this._onFlyPointerUp),s.addEventListener("pointermove",this._onFlyPointerMove),s.addEventListener("wheel",this._onFlyWheel,{passive:!1}),t.addEventListener("pointerdown",this._onAltOrbitStart,{capture:!0}),window.addEventListener("pointerup",this._onAltOrbitRelease,{capture:!0}),window.addEventListener("pointercancel",this._onAltOrbitRelease,{capture:!0}),this.orbitControls.addEventListener("change",()=>{this._orbitGesture&&!this._orbitGestureCounted&&(this._orbitGestureCounted=!0,Ru())}),window.addEventListener("keydown",this._onSnapHoldKey),window.addEventListener("keyup",this._onSnapHoldKey),t.addEventListener("pointerdown",this._onPointerDown),s.addEventListener("pointermove",this._onPointerMove),this._onInteractionPointerUp=l=>{(l.target===t||l.target===s||this._pointerSessionActive)&&this._onPointerUp(l)},s.addEventListener("pointerup",this._onInteractionPointerUp),this._onInteractionDblClick=l=>{(l.target===t||l.target===s)&&this._onDoubleClick(l)},s.addEventListener("dblclick",this._onInteractionDblClick),t.addEventListener("dragover",this._onDragOver),t.addEventListener("dragleave",this._onDragLeave),t.addEventListener("drop",this._onDrop),this._editorObjects=[this.grid,...this._axisLines?[this._axisLines]:[],this._editorAmbient,this._editorDirLight,this.batchedRenderer,this._gizmoHelper,this._auxRotateControls.getHelper(),this._auxScaleControls.getHelper(),this._pivotDummy,this._surfaceSnapIndicator,this._vertexSnapIndicator],this._publishPickContext&&this._installPickContext(this.camera)}setScene(t){if(t===this._scene)return;for(const i of this._editorObjects)i.removeFromParent(),t.add(i);for(const i of this._boxHelpers.values())i.removeFromParent(),t.add(i);for(const i of this._constraintHelpers.values())i.removeFromParent(),t.add(i);for(const i of this._reflectionProbeHelpers.values())i.removeFromParent(),t.add(i);for(const i of this._triggerVolumeHelpers.values())i.removeFromParent(),t.add(i);for(const{helper:i}of this._cameraHelpers.values())i.removeFromParent(),t.add(i);for(const i of this._spatialHandleRoots)i.removeFromParent(),t.add(i);this._scene=t,this._contentBoundsAt=0;const e=this._lightRig&&!this._store.isAdoptedSceneActive;this._editorAmbient.visible=e,this._editorDirLight.visible=e}get currentScene(){return this._scene}get renderCamera(){return this._cameraView??this.freeCamera}get freeCamera(){return this._projection==="orthographic"?this.orthographicCamera:this.camera}get projection(){return this._projection}_installPickContext(t){this._publishPickContext&&xo({camera:t,canvas:this._canvas,editorControls:{activate:(e,i)=>this._selectConstraintControlAt({clientX:e,clientY:i},!1),hover:(e,i)=>this._hoverConstraintControlAt({clientX:e,clientY:i}),clearHover:()=>this._clearConstraintControlHover()}})}setProjection(t){if(this._cameraView){this._pendingProjection=t;return}if(this._projection===t)return;t==="orthographic"?this._syncOrthographicFromPerspective():this._syncPerspectiveFromOrthographic(),this._projection=t;const e=this.freeCamera;this.orbitControls.object=e;for(const i of this._allGizmos())i.camera=e;this._applyGizmoSize(),this.orbitControls.update(),this._installPickContext(e),this._onProjectionChange?.(t)}_syncOrthographicFromPerspective(t=!1){const e=Math.max(.01,this.camera.position.distanceTo(this.orbitControls?.target??new v));t||(this._orthographicHeight=2*e*Math.tan(Dt.degToRad(this.camera.fov*.5))),this.orthographicCamera.position.copy(this.camera.position),this.orthographicCamera.quaternion.copy(this.camera.quaternion),this.orthographicCamera.up.copy(this.camera.up),this.orthographicCamera.zoom=1,this._applyOrthographicFrustum(),this.orthographicCamera.updateMatrixWorld(!0)}_syncPerspectiveFromOrthographic(){const e=this._orthographicHeight/Math.max(this.orthographicCamera.zoom,.01)/(2*Math.tan(Dt.degToRad(this.camera.fov*.5))),i=this.orthographicCamera.position.clone().sub(this.orbitControls.target).normalize();this.camera.position.copy(this.orbitControls.target).add(i.multiplyScalar(e)),this.camera.quaternion.copy(this.orthographicCamera.quaternion),this.camera.up.copy(this.orthographicCamera.up),this.camera.updateMatrixWorld(!0)}_applyOrthographicFrustum(){const t=this._orthographicHeight*.5,e=t*this._viewportAspect;this.orthographicCamera.left=-e,this.orthographicCamera.right=e,this.orthographicCamera.top=t,this.orthographicCamera.bottom=-t,this.orthographicCamera.updateProjectionMatrix()}get cameraViewMode(){return this._cameraViewMode}setCameraView(t,e){if(this.clearCameraView(),this._cameraView=t,this._cameraViewMode=e,this._orbitEnabledBeforeCameraView=this.orbitControls.enabled,this._orbitTargetBeforeCameraView.copy(this.orbitControls.target),e==="pilot"){const i=t.getWorldPosition(new v),s=t.getWorldDirection(new v),r=Math.max(1,this.freeCamera.position.distanceTo(this.orbitControls.target));this.orbitControls.object=t,this.orbitControls.target.copy(i).add(s.multiplyScalar(r)),this.orbitControls.enabled=!0,this.orbitControls.update()}else this.orbitControls.enabled=!1;this._publishPickContext&&this._installPickContext(t)}clearCameraView(){if(!this._cameraView)return;this._flyActive&&this._exitFlyMode(),this.orbitControls.object=this.freeCamera,this.orbitControls.target.copy(this._orbitTargetBeforeCameraView),this.orbitControls.enabled=this._orbitEnabledBeforeCameraView,this.orbitControls.update(),this._cameraView=null,this._cameraViewMode=null;const t=this._pendingProjection;this._pendingProjection=null,t&&t!==this._projection&&this.setProjection(t),this._publishPickContext&&this._installPickContext(this.freeCamera)}get objectMap(){return this._objectMap}set objectMap(t){this._objectMap=t}attach(t){const e=this._objectForAuthoringId(t);e&&(this._attachedAuthoringId=t,this._attachGizmosTo(e))}detach(){this._attachedAuthoringId=null,this._detachGizmos()}_objectForAuthoringId(t){const e=this._authoring();return e.hierarchy.node(t)===null?null:gl(e,this._objectMap,t)}_authoringIdForObject(t){return this._authoring().hierarchy.idForObject3D?.(t)??Sn(t)??null}_hasBoundableGeometry(t){return Da([t]).length>0}_makeDiagnosticBounds(t){if(this._hasBoundableGeometry(t))return new so(t,ze(this._canvas).visible);const e=new mt(ir,ir,ir),i=new An(e);e.dispose();const s=new Ze({color:new B(ze(this._canvas).visible),toneMapped:!1}),r=new Cs(i,s);return t.getWorldPosition(r.position),r.isBoxHelper=!0,r._entityObj=t,r}_syncBoxHelpers(){for(const e of this._boxHelpers.values())this._scene.remove(e),e.geometry.dispose(),e.material.dispose();this._boxHelpers.clear();const t=(e,i)=>{i.layers.set(X),this._scene.add(i),this._boxHelpers.set(e,i)};if(this._store.showHelpers&&this._store.helperVisibility.bounds)for(const e of this._objectMap.keys()){const i=this._objectForAuthoringId(e);i&&t(`bounds:${e}`,this._makeDiagnosticBounds(i))}for(const e of this._store.selectedEntityIds){const i=this._objectForAuthoringId(e);!i||this._hasBoundableGeometry(i)||this._standaloneAuthoring&&i.isBone||[...this._constraintHelpers.values()].some(s=>s.presents(i))||t(`selection:${e}`,new en(i,{fixedSize:ir,color:ze(this._canvas).visible}))}}_syncReflectionProbeHelpers(t=null){if(t===null){const e=new Map,i=new Set;for(const[s,r]of this._objectMap)!r||i.has(r)||!Li(r)||(i.add(r),e.set(s,r));for(const[s,r]of this._reflectionProbeHelpers)e.get(s)!==r.source&&(r.dispose(),this._reflectionProbeHelpers.delete(s));for(const[s,r]of e)this._ensureReflectionProbeHelper(s,r)}else{let e=!1;for(const i of t){const s=this._objectMap.get(i),r=s&&Li(s)?s:null,n=this._reflectionProbeHelpers.get(i);n&&n.source!==r&&(r===null&&(e=!0),n.dispose(),this._reflectionProbeHelpers.delete(i)),r&&![...this._reflectionProbeHelpers.values()].some(a=>a.source===r)&&this._ensureReflectionProbeHelper(i,r)}if(e){this._syncReflectionProbeHelpers();return}}for(const[e,i]of this._reflectionProbeHelpers)i.setSelected(this._store.selectedEntityIds.has(e)),i.visible=this._threejsToolContextActive&&this._store.showHelpers&&this._store.helperVisibility.reflectionProbes,i.update()}_ensureReflectionProbeHelper(t,e){if(this._reflectionProbeHelpers.has(t))return;const i=new jd(e);this._reflectionProbeHelpers.set(t,i),this._scene.add(i)}_syncTriggerVolumeHelpers(t=null){if(t===null){const i=new Map,s=new Set;for(const[r,n]of this._objectMap)!n||s.has(n)||!mn(n)||(s.add(n),i.set(r,n));for(const[r,n]of this._triggerVolumeHelpers)i.get(r)!==n.source&&this._disposeTriggerVolumeHelper(r,n);for(const[r,n]of i)this._ensureTriggerVolumeHelper(r,n)}else{let i=!1;for(const s of t){const r=this._objectMap.get(s),n=r&&mn(r)?r:null,a=this._triggerVolumeHelpers.get(s);a&&a.source!==n&&(n===null&&(i=!0),this._disposeTriggerVolumeHelper(s,a)),n&&![...this._triggerVolumeHelpers.values()].some(l=>l.source===n)&&this._ensureTriggerVolumeHelper(s,n)}if(i){this._syncTriggerVolumeHelpers();return}}const e=this._threeSurfaceShowing&&this._store.showHelpers&&this._store.helperVisibility.triggerVolumes;for(const[i,s]of this._triggerVolumeHelpers)s.setSelected(this._store.selectedEntityIds.has(i)),s.visible=e,s.update()}_ensureTriggerVolumeHelper(t,e){if(this._triggerVolumeHelpers.has(t))return;const i=new Ou(e);this._triggerVolumeHelpers.set(t,i),this._scene.add(i)}_disposeTriggerVolumeHelper(t,e){e.dispose(),this._triggerVolumeHelpers.delete(t)}_syncConstraintHelpers(t=null){if(t===null){const i=new Map,s=new Set;for(const[r,n]of this._objectMap)!n||s.has(n)||or(n).length===0||(s.add(n),i.set(r,n));for(const[r,n]of this._constraintHelpers)i.get(r)!==n.source&&(this._disposeConstraintHelper(n),this._constraintHelpers.delete(r));for(const[r,n]of i)this._ensureConstraintHelper(r,n)}else{let i=!1;for(const s of t){const r=this._objectMap.get(s),n=r&&or(r).length>0?r:null,a=this._constraintHelpers.get(s);a&&a.source!==n&&(n===null&&(i=!0),this._disposeConstraintHelper(a),this._constraintHelpers.delete(s)),n&&![...this._constraintHelpers.values()].some(l=>l.source===n)&&this._ensureConstraintHelper(s,n)}if(i){this._syncConstraintHelpers();return}}const e=new Set;for(const i of this._store.selectedEntityIds){const s=this._objectForAuthoringId(i);s&&e.add(s)}for(const[i,s]of this._constraintHelpers)s.setSelected(this._store.selectedEntityIds.has(i)),s.setSelectedObjects(e),s.visible=this._threejsToolContextActive&&this._store.showHelpers&&this._store.helperVisibility.constraints,s.update(this.camera)}_ensureConstraintHelper(t,e){if(this._constraintHelpers.has(t))return;const i=new Hd(e);this._constraintHelpers.set(t,i),this._scene.add(i)}_disposeConstraintHelper(t){this._hoveredConstraintControl?.helper===t&&(this._hoveredConstraintControl=null),t.dispose()}_raycastConstraintControl(t){const e=[];for(const n of this._constraintHelpers.values())n.visible&&e.push(...n.controlMeshes());if(e.length===0)return null;const i=this._canvas.getBoundingClientRect(),s=new Jt((t.clientX-i.left)/i.width*2-1,-((t.clientY-i.top)/i.height)*2+1);this._constraintControlRaycaster.setFromCamera(s,this.renderCamera);const r=this._constraintControlRaycaster.intersectObjects(e,!1)[0]?.object;if(!r)return null;for(const n of this._constraintHelpers.values()){const a=n.controlFor(r);if(a)return{helper:n,control:a}}return null}_updateConstraintControlHover(t){if(t.buttons&1)return this._constraintControlPointerSession;const e=this._hoverConstraintControlAt(t);return e?(this._hoveredSpatialHandle&&($r(this._hoveredSpatialHandle,!1),this._hoveredSpatialHandle=null),this._canvas.style.cursor=e,!0):(this._canvas.style.cursor="",!1)}_hoverConstraintControlAt(t){const e=this._raycastConstraintControl(t),i=this._hoveredConstraintControl;return e?(i?.mesh!==e.control.mesh&&(i&&i.helper.setHoveredControl(null),e.helper.setHoveredControl(e.control.mesh),this._hoveredConstraintControl={helper:e.helper,mesh:e.control.mesh}),this._authoringIdForObject(e.control.object)?"pointer":"not-allowed"):(this._clearConstraintControlHover(),null)}_clearConstraintControlHover(){this._hoveredConstraintControl?.helper.setHoveredControl(null),this._hoveredConstraintControl=null}_selectConstraintControlAt(t,e=!0){const i=this._raycastConstraintControl(t);if(!i)return!1;this._constraintControlPointerSession=e;const s=this._authoringIdForObject(i.control.object);if(s){const r=this._authoring();ki(r,[s],{intent:"exact"})||this._store.select(s),jt(`${i.control.label} selected — move it with the gizmo.`)}else jt(`${i.control.label} is a runtime-only constraint control.`);return!0}_syncCameraHelpers(t=null){if(t===null){const i=new Map;for(const[s,r]of this._objectMap){const n=this._nativeCamera(r);n&&i.set(s,n)}for(const[s,r]of this._cameraHelpers)i.get(s)!==r.source&&this._disposeCameraHelper(s,r);for(const[s,r]of i)this._ensureCameraHelper(s,r)}else{let i=!1;for(const s of t){const r=this._objectMap.get(s),n=r?this._nativeCamera(r):null,a=this._cameraHelpers.get(s);a&&a.source!==n&&(n===null&&(i=!0),this._disposeCameraHelper(s,a)),n&&![...this._cameraHelpers.values()].some(l=>l.source===n)&&this._ensureCameraHelper(s,n)}if(i){this._syncCameraHelpers();return}}const e=this._threeSurfaceShowing&&this._store.showHelpers&&this._store.helperVisibility.cameras;for(const i of this._cameraHelpers.values())i.helper.visible=e,i.helper.update()}_syncLightHelpers(t=null){if(t===null){const i=new Map;for(const[s,r]of this._objectMap){const n=this._nativeLight(r);n&&i.set(s,n)}for(const[s,r]of this._lightHelpers)i.get(s)!==r.source&&this._disposeLightHelper(s,r);for(const[s,r]of i)this._ensureLightHelper(s,r)}else{let i=!1;for(const s of t){const r=this._objectMap.get(s),n=r?this._nativeLight(r):null,a=this._lightHelpers.get(s);a&&a.source!==n&&(n===null&&(i=!0),this._disposeLightHelper(s,a)),n&&![...this._lightHelpers.values()].some(l=>l.source===n)&&this._ensureLightHelper(s,n)}if(i){this._syncLightHelpers();return}}const e=this._threeSurfaceShowing&&this._store.showHelpers&&this._store.helperVisibility.lights;for(const i of this._lightHelpers.values())i.helper.visible=e,i.helper.update?.()}_nativeLight(t){return t.isLight?t:null}_disposeLightHelper(t,e){e.helper.removeFromParent(),e.helper.dispose?.(),this._lightHelpers.delete(t)}_ensureLightHelper(t,e){if(this._lightHelpers.has(t))return;const i=.5;let s=null;const r=e;try{r.isDirectionalLight?s=new Vh(e,i):r.isPointLight?s=new jh(e,i):r.isSpotLight?s=new Gh(e):r.isHemisphereLight&&(s=new Xh(e,i))}catch{s=null}s&&(s.name=`Light helper: ${e.name||t}`,s.userData.editorOnly=!0,s.traverse(n=>n.layers.set(X)),s.layers.set(X),this._lightHelpers.set(t,{source:e,helper:s}),this._scene.add(s))}_syncAudioHelpers(t=null){if(t===null){const i=new Map;for(const[s,r]of this._objectMap){const n=this._nativeAudio(r);n&&i.set(s,n)}for(const[s,r]of this._audioHelpers)i.get(s)!==r.source&&this._disposeAudioHelper(s,r);for(const[s,r]of i)this._ensureAudioHelper(s,r)}else for(const i of t){const s=this._objectMap.get(i),r=s?this._nativeAudio(s):null,n=this._audioHelpers.get(i);n&&n.source!==r&&this._disposeAudioHelper(i,n),r&&![...this._audioHelpers.values()].some(a=>a.source===r)&&this._ensureAudioHelper(i,r)}const e=this._threeSurfaceShowing&&this._store.showHelpers&&this._store.helperVisibility.audio;for(const i of this._audioHelpers.values())i.helper.visible=e}_nativeAudio(t){const e=t.type;return e==="Audio"||e==="PositionalAudio"||e==="AudioListener"?t:null}_ensureAudioHelper(t,e){if(this._audioHelpers.has(t))return;const i=new kt,s=e.type==="AudioListener"?8377599:16763274,r=new E(new Ve(.16),new Tt({color:s,wireframe:!0,depthTest:!1}));i.add(r),i.name=`Audio helper: ${e.name||t}`,i.userData.editorOnly=!0,i.traverse(n=>n.layers.set(X)),i.layers.set(X),e.add(i),this._audioHelpers.set(t,{source:e,helper:i})}_disposeAudioHelper(t,e){e.helper.traverse(i=>{const s=i;s.geometry?.dispose?.(),s.material?.dispose?.()}),e.helper.removeFromParent(),this._audioHelpers.delete(t)}_disposeCameraHelper(t,e){e.helper.removeFromParent(),e.helper.dispose(),this._cameraHelpers.delete(t)}_ensureCameraHelper(t,e){if(this._cameraHelpers.has(t))return;let i;try{i=new Wh(e)}catch(s){this._refuseCameraOverlay(t,e,s);return}i.name=`Camera frustum: ${e.name||t}`,i.userData.editorOnly=!0,i.layers.set(X),this._cameraHelpers.set(t,{source:e,helper:i}),this._scene.add(i)}_refusedCameraOverlays=new Set;_refuseCameraOverlay(t,e,i){this._refusedCameraOverlays.has(t)||(this._refusedCameraOverlays.add(t),Fi.warn(`Helpers → Cameras draws no frustum for "${e.name||e.type}": ${i instanceof Error?i.message:String(i)}. This world's camera was constructed by the GAME's own copy of three, and \`THREE.CameraHelper\` is the editor's class reading fields off it that that revision does not define. Every other camera capability (framing, selection, inspection) is unaffected. It closes when the game resolves \`three\` to the host's instance — a bare, un-rewritten \`import 'three'\` in its own source.`,"authoring"))}_nativeCamera(t){if(t.isCamera)return t;const e=xt(t,"_camera");return e?.isCamera?e:null}_syncSpatialHandles(){Vo(this._spatialHandleRoots),this._spatialHandleRoots=[],this._spatialHandleMeshes=[],this._hoveredSpatialHandle=null;const t=Ir(this._authoring());if(!t||!this._threejsToolContextActive||!this._store.showHelpers)return;const e=this._store.helperVisibility;for(const i of this._store.selectedEntityIds){const s=t.layers(i).filter(n=>n.category in e?e[n.category]:!0),r=lu(i,s);for(const n of r.handles)Uo(n,this.renderCamera);for(const n of r.roots)this._scene.add(n);this._spatialHandleRoots.push(...r.roots),this._spatialHandleMeshes.push(...r.handles)}}_raycastSpatialHandle(t){if(this._spatialHandleMeshes.length===0)return null;const e=this._canvas.getBoundingClientRect(),i=new Jt((t.clientX-e.left)/e.width*2-1,-((t.clientY-e.top)/e.height)*2+1);return this._spatialHandleRaycaster.setFromCamera(i,this.renderCamera),this._spatialHandleRaycaster.intersectObjects(this._spatialHandleMeshes,!1)[0]?.object??null}_spatialHandleWorldPoint(t){const e=this._canvas.getBoundingClientRect(),i=new Jt((t.clientX-e.left)/e.width*2-1,-((t.clientY-e.top)/e.height)*2+1);this._spatialHandleRaycaster.setFromCamera(i,this.renderCamera);const s=new v;return this._spatialHandleRaycaster.ray.intersectPlane(this._spatialHandleDragPlane,s)?s.add(this._spatialHandleDragOffset):null}_finishSpatialHandleDrag(t){const e=this._activeSpatialHandle;this._activeSpatialHandle=null,this.orbitControls.enabled=this._orbitEnabledBeforeHandleDrag,this.transformControls.enabled=this._transformEnabledBeforeHandleDrag,this.syncFromStore(),this._canvas.style.cursor="",t&&e&&Ir(this._authoring())?.commit(e.nodeId,e.handle.id,[this._spatialHandleDragPoint.x,this._spatialHandleDragPoint.y,this._spatialHandleDragPoint.z])}_updateSpatialHandleDrag(t){const e=this._activeSpatialHandle;if(!e)return!1;const i=this._spatialHandleWorldPoint(t);return i&&(this._spatialHandleDragPoint.copy(i),Ir(this._authoring())?.preview(e.nodeId,e.handle.id,[i.x,i.y,i.z]),this._syncSpatialHandles(),this._canvas.style.cursor="grabbing"),!0}_updateSpatialHandleHover(t){if(t.buttons&1||this._spatialHandleMeshes.length===0)return;const e=this._raycastSpatialHandle(t);if(e===this._hoveredSpatialHandle)return;if(this._hoveredSpatialHandle&&$r(this._hoveredSpatialHandle,!1),this._hoveredSpatialHandle=e,!e){this._canvas.style.cursor="";return}$r(e,!0);const i=Do(e);this._canvas.style.cursor=i?.handle.writable?"grab":"not-allowed"}_updateEditorHandleInteraction(t){return this._updateSpatialHandleDrag(t)||this._updateConstraintControlHover(t)}_previewInfrastructure(){return[this.grid,...this._axisLines?[this._axisLines]:[],this._gizmoHelper,this._auxRotateControls.getHelper(),this._auxScaleControls.getHelper(),...this._boxHelpers.values(),...this._constraintHelpers.values(),...this._reflectionProbeHelpers.values(),...this._triggerVolumeHelpers.values(),...[...this._cameraHelpers.values()].map(({helper:t})=>t),...this._spatialHandleRoots]}_suspendPreviewInfrastructure(){const t=this._previewInfrastructure().map(e=>[e,e.visible]);for(const[e]of t)e.visible=!1;return()=>{for(const[e,i]of t)e.visible=i}}_allGizmos(){return[this.transformControls,this._auxRotateControls,this._auxScaleControls]}_anyGizmoDragging(){return this._allGizmos().some(t=>t.dragging)}_attachGizmosTo(t){this.transformControls.attach(t),this._auxRotateControls.attach(t),this._auxScaleControls.attach(t)}_detachGizmos(){for(const t of this._allGizmos())t.detach()}syncFromStore(){this._gizmoHelper.traverse(x=>x.layers.set(X));const t=this._store.transformMode,i=t==="combined"||t==="select"?"translate":t;this.transformControls.mode!==i&&this.transformControls.setMode(i),this._applySnapToGizmos();for(const x of this._allGizmos())x.setSpace(this._store.transformSpace);const s=Gs(),r=this._authoring(),n=s.toolOwner(r,this._store.selectedEntityIds);this._threejsToolContextActive=(this._standaloneAuthoring||s.toolOwnerPainted(this._store,n))&&n?.kind==="three";const a=this._standaloneAuthoring||s.threeSurfaceShowing(this._store,r);this._threeSurfaceShowing=a,this.grid.visible=this._store.showGrid&&a,this._axisLines&&(this._axisLines.visible=this.grid.visible&&this._axesWanted);const l=this._store.helperVisibility,h=this._standaloneAuthoring?null:s.threeViewportRootId(this._store),d=h!==null&&Al(h);d&&s.applyRootHiddenVisibility(this._objectMap,h),d&&s.suppressRootEnvironment(this._scene);const c=this._store.gizmoEpoch,p=`${this._store.showHelpers}|${JSON.stringify(l)}|${h??""}|${d}|${this._threejsToolContextActive}`,u=this._objectMap!==this._lastGizmoObjectMap,f=p!==this._lastGizmoSig,m=u?null:this._store.ingestObjectMapMembershipChangesSince(this._lastGizmoEpoch),y=u||f||m===null?null:m.changedIds,g=y===null||y.size>0;if(this._lastGizmoObjectMap=this._objectMap,this._lastGizmoSig=p,this._lastGizmoEpoch=c,g){s.applyRootHiddenVisibility(this._objectMap,h);const x=y===null?ku(this._objectMap):Fu(this._objectMap,y);for(const b of x)b.traverse(P=>{if(xt(P,"editorIcon")){P.visible=this._store.showHelpers;return}if(!xt(P,"editorHelper"))return;const A=xt(P,"editorHelperType");if(A==="skeletons"){P.visible=this._store.showHelpers&&(l.skeletons||!!xt(P,"skeletonEnabled"));return}A&&A in l?P.visible=this._store.showHelpers&&l[A]:P.visible=this._store.showHelpers});for(const[b,P]of this._helpers)P.visible=this._store.showHelpers&&(!(b in l)||l[b]);this._syncCameraHelpers(y),this._syncLightHelpers(y)}this._syncAudioHelpers(y),this._syncReflectionProbeHelpers(y),this._syncTriggerVolumeHelpers(y),this._syncConstraintHelpers(y);const _=this._threejsToolContextActive&&r.capabilities.transform&&t!=="select"?this._store.selectedEntityId:null,M=t==="translate"||t==="combined"?"position":t==="rotate"?"rotation":"scale",C=_?t==="combined"?(x=>["position","rotation","scale"].some(b=>r.transforms?.editability?.(x,b).writable??!0))(_):r.transforms?.editability?.(_,M).writable??!0:!1;if(_&&C){if(!this._anyGizmoDragging())if(this._store.pivotMode==="median-point"&&this._store.selectedEntityIds.size>1){const x=new v;let b=0;for(const P of this._store.selectedEntityIds){if(!(r.transforms?.editability?.(P,M).writable??!0))continue;const A=this._objectForAuthoringId(P);A&&(x.add(A.getWorldPosition(Lu)),b++)}b>0&&x.divideScalar(b),this._pivotDummy.position.copy(x),this._pivotDummy.quaternion.identity(),this._pivotDummy.scale.set(1,1,1),this._attachedAuthoringId=null,this._dummyIsPresentationAnchor=!1,this._attachGizmosTo(this._pivotDummy)}else{const x=this._objectForAuthoringId(_),b=xt(x,"pivot"),P=b&&(b[0]!==0||b[1]!==0||b[2]!==0),A=P?null:this._centreAnchorFor(x);if(A&&x)this._pivotDummy.position.copy(A),this._pivotDummy.quaternion.copy(x.getWorldQuaternion(rn)),this._pivotDummy.scale.copy(x.getWorldScale(Yo)),this._attachedAuthoringId=_,this._dummyIsPresentationAnchor=!0,this._attachGizmosTo(this._pivotDummy);else if(P&&x){const N=new v(b[0],b[1],b[2]);N.applyQuaternion(x.getWorldQuaternion(rn)),this._pivotDummy.position.copy(x.getWorldPosition(Jo)).add(N),this._pivotDummy.quaternion.copy(rn),this._pivotDummy.scale.copy(x.getWorldScale(Yo)),this._attachedAuthoringId=_,this._dummyIsPresentationAnchor=!1,this._attachGizmosTo(this._pivotDummy)}else this._dummyIsPresentationAnchor=!1,this.attach(_)}}else this.detach();this._syncBoxHelpers(),this._syncSpatialHandles(),this._syncCombinedGizmoHalves()}_applySnapToGizmos(){const t=this._store.snapEnabled||this._snapHold,e=this._store.snapValues;for(const i of this._allGizmos())i.setTranslationSnap(t?e.translate:null),i.setRotationSnap(t?Dt.degToRad(e.rotate):null),i.setScaleSnap(t?e.scale:null)}_onAltOrbitStart=t=>{t.altKey&&t.button===0&&(this._altDragOrbit=!0,this.orbitControls.mouseButtons.LEFT=Rr.ROTATE),(t.button===2||t.altKey&&t.button===0)&&(this._orbitGesture=!0)};_onAltOrbitRelease=()=>{this._orbitGesture=!1,this._orbitGestureCounted=!1,this._altDragOrbit&&(this._altDragOrbit=!1,this.orbitControls.mouseButtons.LEFT=-1)};_onSnapHoldKey=t=>{const e=t.ctrlKey||t.metaKey;if(e!==this._snapHold&&(this._snapHold=e,this._applySnapToGizmos(),e&&this._anyGizmoDragging()&&!this._store.snapEnabled)){const{translate:i,rotate:s,scale:r}=this._store.snapValues;jt(`Snapping while held: ${i} units · ${s}° · ×${r}`)}};_syncCombinedGizmoHalves(){if(this._anyGizmoDragging())return;const t=this._store.transformMode==="combined",e=this._attachedAuthoringId,i=this._authoring().transforms?.editability,s=h=>e===null||(i?.(e,h).writable??!0),r=t&&this._auxRotateControls.object!==void 0&&s("rotation"),n=t&&this._auxScaleControls.object!==void 0&&s("scale");this._auxRotateControls.enabled=r,this._auxScaleControls.enabled=n;const a=this._auxRotateControls.getHelper(),l=this._auxScaleControls.getHelper();a.visible=r,l.visible=n;for(const h of[a,l])h.traverse(d=>d.layers.set(X));this.transformControls.enabled=!0}moveGizmosTo(t){const e=this._gizmoObjects();for(const i of e)t.add(i)}restoreGizmos(){const t=this._gizmoObjects();for(const e of t)this._scene.add(e)}_gizmoObjects(){return[this.grid,...this._axisLines?[this._axisLines]:[],this._editorAmbient,this._editorDirLight,this.batchedRenderer,this._gizmoHelper,this._auxRotateControls.getHelper(),this._auxScaleControls.getHelper(),this._pivotDummy,this._surfaceSnapIndicator,...[...this._cameraHelpers.values()].map(({helper:t})=>t),...this._spatialHandleRoots]}_contentBounds(t=!1){const e=performance.now(),i=this._contentBoundsAt===0||e-this._contentBoundsAt>Bu;if(t||i){this._contentBoundsBox.makeEmpty();for(const s of this._scene.children)ue(s)||yl(this._contentBoundsBox,s);this._contentBoundsAt=e}return this._contentBoundsBox}_measureContentBounds(){const t=[];for(const e of this._scene.children)ue(e)||_l(e,t);this._contentBoundsBox.makeEmpty();for(const e of t)this._contentBoundsBox.union(e);return this._contentBoundsAt=performance.now(),t}_updateClipPlanes(){const t=this._contentBounds();let e=0,i=0;t.isEmpty()||(t.getBoundingSphere(sn),e=this.freeCamera.position.distanceTo(sn.center),i=sn.radius);const{near:s,far:r}=sc(e,i);s===this.camera.near&&r===this.camera.far||(this.camera.near=s,this.camera.far=r,this.camera.updateProjectionMatrix(),this.orthographicCamera.near=s,this.orthographicCamera.far=r,this.orthographicCamera.updateProjectionMatrix())}seedFromGameCamera(t){const e=No(this._measureContentBounds()),i=qd(t,e);if(!i)return!1;const s=this.camera.position.clone(),r=this.orbitControls.target.clone();this.camera.position.copy(i.position),this.orbitControls.target.copy(i.target),this.camera.lookAt(this.orbitControls.target),this.camera.updateMatrixWorld(!0);const n=this._scene.children.filter(a=>!ue(a));return Kd(this.camera,n,i.position.distanceTo(i.target))?(this._updateClipPlanes(),this.orbitControls.update(),!0):(this.camera.position.copy(s),this.orbitControls.target.copy(r),this.camera.lookAt(this.orbitControls.target),this.camera.updateMatrixWorld(!0),!1)}focusOnScene(){const t=No(this._measureContentBounds());if(t.isEmpty())return!1;const e=t.getCenter(new v),i=this.camera.position.clone().sub(this.orbitControls.target).normalize(),s=Xe(t,this.camera,i);return Number.isFinite(s)?(this.camera.position.copy(e).add(i.multiplyScalar(s)),this.orbitControls.target.copy(e),this._orthographicHeight=Math.max(t.getSize(new v).y,t.getSize(new v).x/this._viewportAspect)*1.15,this._syncOrthographicFromPerspective(!0),this._updateClipPlanes(),!0):!1}focusOn(t){const e=this._contentOrProbeBounds(t),i=e.getCenter(new v),s=this.camera.position.clone().sub(this.orbitControls.target).normalize(),r=Xe(e,this.camera,s);this.camera.position.copy(i).add(s.multiplyScalar(r)),this.orbitControls.target.copy(i);const n=e.getSize(new v);this._orthographicHeight=Math.max(n.y,n.x/this._viewportAspect,.01)*1.15,this._syncOrthographicFromPerspective(!0)}activateVertexSnap(){this._vertexSnapTargets=this._collectVertices(this._store.selectedEntityIds)}deactivateVertexSnap(){this._vertexSnapTargets=[],this._vertexSnapIndicator.visible=!1}focusOnMultiple(t){if(t.length===0)return;if(t.length===1){this.focusOn(t[0]);return}const e=new ie;for(const a of t)e.union(this._contentOrProbeBounds(a));const i=e.getCenter(new v),s=this.camera.position.clone().sub(this.orbitControls.target).normalize(),r=Xe(e,this.camera,s);this.camera.position.copy(i).add(s.multiplyScalar(r)),this.orbitControls.target.copy(i);const n=e.getSize(new v);this._orthographicHeight=Math.max(n.y,n.x/this._viewportAspect,.01)*1.15,this._syncOrthographicFromPerspective(!0)}_centreAnchorFor(t){const e=this._store.gizmoAnchor;if(!t||e==="pivot"||e==="auto"&&vl(t)===0)return null;const i=Ie(t);if(i.isEmpty()||e==="auto"&&!xl(t,i)?.worldAnchored)return null;const s=i.getCenter(new v);return t.updateWorldMatrix(!0,!1),s.distanceToSquared(t.getWorldPosition(Jo))<Du?null:s}_contentOrProbeBounds(t){const e=Li(t);if(!e)return Ie(t);const i=e.config,[s,r,n]=i.size,a=i.shape==="sphere"?new v(1,1,1).multiplyScalar(Math.max(.01,i.radius)):new v(Math.max(.01,s),Math.max(.01,r),Math.max(.01,n)).multiplyScalar(.5);return t.updateWorldMatrix(!0,!1),new ie(a.clone().negate(),a).applyMatrix4(t.matrixWorld)}setHelper(t,e){const i=this._helpers.get(t);if(i&&(this._scene.remove(i),this._helpers.delete(t)),!e)return;Rt(e,"editorHelper",!0),Rt(e,"editorHelperType",t);const s=this._store.helperVisibility;e.visible=this._store.showHelpers&&(!(t in s)||s[t]),this._scene.add(e),this._helpers.set(t,e)}setViewPreset(t){this._projection==="orthographic"&&this.setProjection("perspective");const e=this.orbitControls.target.clone(),i=this.camera.position.distanceTo(e),s=new v;switch(t){case"top":s.set(0,1,0);break;case"front":s.set(0,0,1);break;case"right":s.set(1,0,0);break;case"perspective":s.set(1,1,1).normalize();break}this.camera.position.copy(e).add(s.multiplyScalar(i)),this.camera.lookAt(e),t!=="perspective"&&this.setProjection("orthographic"),this.orbitControls.update()}setPose(t,e,i){this.setProjection("perspective"),this.camera.position.set(t.x,t.y,t.z),this.orbitControls.target.set(e.x,e.y,e.z),this.camera.lookAt(this.orbitControls.target),i!==void 0&&(this.camera.fov=i,this.camera.updateProjectionMatrix()),this.orbitControls.update()}resize(t,e){this._viewportAspect=Math.max(1,t)/Math.max(1,e),this.camera.aspect=this._viewportAspect,this.camera.fov=Zo(this._viewportAspect),this.camera.updateProjectionMatrix(),this._applyOrthographicFrustum(),this._applyGizmoSize()}update(t=0){this._ensureSparkRenderer(),this._syncLookBackground();const e=this.transformControls.object;if(e&&e!==this._pivotDummy&&!e.parent&&(this._detachGizmos(),this.syncFromStore()),this._updateFlyCamera(t),this.orbitControls.update(),this._snapAnimating){const i=performance.now()-this._snapStartTime;let s=Math.min(i/this._snapDuration,1);s=s<.5?4*s*s*s:1-(-2*s+2)**3/2;const r=new wt().slerpQuaternions(this._snapQ1,this._snapQ2,s),n=new v(0,0,1).applyQuaternion(r);this.freeCamera.position.copy(this.orbitControls.target).add(n.multiplyScalar(this._snapDist)),this.freeCamera.lookAt(this.orbitControls.target),s>=1&&(this._snapAnimating=!1)}for(const i of this._boxHelpers.values()){if(i instanceof en){i.updateIfNeeded();continue}const s=i;s._entityObj?s._entityObj.getWorldPosition(i.position):i instanceof so&&i.update()}for(const i of this._constraintHelpers.values())i.update(this.camera);for(const i of this._reflectionProbeHelpers.values())i.update();for(const i of this._triggerVolumeHelpers.values())i.update();for(const{helper:i}of this._cameraHelpers.values())i.update();for(const i of this._spatialHandleMeshes)Uo(i,this.renderCamera);this._enforceLodForcedLevels(),this._updateClipPlanes()}_enforceLodForcedLevels(){const t=new Set(this._objectMap.values());for(const[e,i]of this._store.lodForcedLevels){const s=this._objectMap.get(e),r=s?wl(s,a=>t.has(a)):null;if(!r||r.levels.length===0)continue;r.autoUpdate=!1;const n=Math.min(Math.max(i,0),r.levels.length-1);for(let a=0;a<r.levels.length;a++)r.levels[a].object.visible=a===n}}renderWithInfrastructure(t){const e=this._sparkRenderer,i=this._cameraView?this._suspendPreviewInfrastructure():null;e&&this._scene.add(e);try{t()}finally{e?.removeFromParent(),i?.()}}renderViewCube(t){if(!this._threeSurfaceShowing||this._cameraView)return;const e=t.domElement.clientWidth,i=t.domElement.clientHeight,s=this._vcSize,r=this._vcDir.subVectors(this.freeCamera.position,this.orbitControls.target).normalize();this._vcCamera.position.copy(r.multiplyScalar(4)),this._vcCamera.up.copy(this.freeCamera.up),this._vcCamera.lookAt(0,0,0),this._syncOrientationGizmoDepth();const n=e-s-this._vcMarginRight-this._chromeInsetPx,a=i-s-this._vcMarginTop-this._chromeInsetPx,l=t.autoClear;try{t.setScissorTest(!0),t.setViewport(n,a,s,s),t.setScissor(n,a,s,s),t.clear(!1,!0,!1),t.autoClear=!1,t.render(this._vcScene,this._vcCamera)}finally{t.autoClear=l,t.setScissorTest(!1),t.setViewport(0,0,e,i)}}renderCameraPreview(t,e,i){if(!e||!i||this._cameraView)return;const s=t.domElement.clientWidth,r=t.domElement.clientHeight,n=t.domElement.getBoundingClientRect(),a=i.getBoundingClientRect(),l=Math.round(a.left-n.left),h=Math.round(n.bottom-a.bottom),d=Math.max(1,Math.round(a.width)),c=Math.max(1,Math.round(a.height));if(l>=s||h>=r||l+d<=0||h+c<=0)return;const p=this._suspendPreviewInfrastructure(),u=t.getClearColor(this._previewClearColor),f=t.getClearAlpha();try{t.setScissorTest(!0),t.setViewport(l,h,d,c),t.setScissor(l,h,d,c),t.setClearColor(1118740,1),t.clear(),t.render(this._scene,e)}finally{t.setScissorTest(!1),t.setViewport(0,0,s,r),t.setClearColor(u,f),p()}}get isFlying(){return this._flyActive}_inputDisconnected=!1;disconnectInput(){if(!this._inputDisconnected){this._inputDisconnected=!0,this._publishPickContext&&xo(null),window.removeEventListener("keydown",this._onFlyKeyDown),window.removeEventListener("keyup",this._onFlyKeyUp),this._interactionElement.removeEventListener("pointerdown",this._onFlyPointerDown),this._canvas.removeEventListener("pointerdown",this._onAltOrbitStart,{capture:!0}),window.removeEventListener("pointerup",this._onAltOrbitRelease,{capture:!0}),window.removeEventListener("pointercancel",this._onAltOrbitRelease,{capture:!0}),window.removeEventListener("keydown",this._onSnapHoldKey),window.removeEventListener("keyup",this._onSnapHoldKey),this._interactionElement.removeEventListener("pointerup",this._onFlyPointerUp),this._interactionElement.removeEventListener("pointermove",this._onFlyPointerMove),this._interactionElement.removeEventListener("wheel",this._onFlyWheel),this._interactionElement.removeEventListener("wheel",this._onTrackpadWheel),this._canvas.removeEventListener("pointerdown",this._onPointerDown),this._interactionElement.removeEventListener("pointermove",this._onPointerMove),this._onInteractionPointerUp&&this._interactionElement.removeEventListener("pointerup",this._onInteractionPointerUp),this._onInteractionDblClick&&this._interactionElement.removeEventListener("dblclick",this._onInteractionDblClick),this._canvas.removeEventListener("dragover",this._onDragOver),this._canvas.removeEventListener("dragleave",this._onDragLeave),this._canvas.removeEventListener("drop",this._onDrop),this.orbitControls.dispose();for(const t of this._allGizmos())t.dispose()}}_applyViewportLook(t){this._lookGridHex=t.grid??10066329;const e=this.grid.material.uniforms.uGrazingFade;if(e&&(e.value=t.background!==null?1:0),this._paintLookGrid(),this._axesWanted=t.axisX!==null&&t.axisY!==null,this._lookAxisHexes=t.axisX!==null&&t.axisY!==null?{x:t.axisX,y:t.axisY}:null,this._paintLookAxes(),this._axisLines&&(this._axisLines.visible=this.grid.visible&&this._axesWanted),t.background!==null){const i=this._scene.background,s=i===null||i instanceof B&&[this._lookBackgroundHex,t.background].includes(i.getHex());this._lookBackgroundHex=t.background,s&&this._paintLookBackground()}else this._lookBackgroundHex=null}_paintLookGrid(){const t=this._lookGridHex;if(t===null)return;const e=this._lookBackgroundHex??4144959,i=a=>{const l=t>>a&255,h=e>>a&255;return Math.round(Math.min(255,Math.max(0,h+(l-h)*Gu)))},s=i(16)<<16|i(8)<<8|i(0),r=Go(t,this._renderer),n=Go(s,this._renderer);this.grid.material.uniforms.uColor?.value?.copy(r),this.grid.material.uniforms.uMajorColor?.value?.copy(n)}_paintLookAxes(){const t=this._lookAxisHexes;if(!this._axisLines||t===null)return;const e=new B(t.x),i=new B(t.y),s=[];for(const r of[e,i])for(let n=0;n<fr*2;n++)s.push(r.r,r.g,r.b);this._axisLines.geometry.setColors(s)}_paintLookBackground(){this._lookBackgroundHex!==null&&(this._scene.background=new B(this._lookBackgroundHex))}_syncLookBackground(){this._renderer&&(this._renderer.toneMapping===this._lookToneMapping&&this._renderer.toneMappingExposure===this._lookExposure||(this._paintLookGrid(),this._lookToneMapping=this._renderer.toneMapping,this._lookExposure=this._renderer.toneMappingExposure))}dispose(){this._disposed=!0,this._unsubscribeSelectionTheme(),this._axisLines&&(this._scene.remove(this._axisLines),this._axisLines.geometry.dispose(),this._axisLines.material.dispose(),this._axisLines=null),this.clearCameraView(),this._sparkRenderer&&(this._scene.remove(this._sparkRenderer),Sl(this._sparkRenderer),this._sparkRenderer=null),this.disconnectInput(),this._hideDropOverlay();for(const t of this._helpers.values())this._scene.remove(t);this._helpers.clear();for(const t of this._boxHelpers.values())this._scene.remove(t),t.geometry.dispose(),t.material.dispose();this._boxHelpers.clear();for(const t of this._reflectionProbeHelpers.values())t.dispose();this._reflectionProbeHelpers.clear();for(const t of this._triggerVolumeHelpers.values())t.dispose();this._triggerVolumeHelpers.clear();for(const t of this._constraintHelpers.values())t.dispose();this._constraintHelpers.clear();for(const{helper:t}of this._cameraHelpers.values())t.dispose();this._cameraHelpers.clear(),Vo(this._spatialHandleRoots),this._spatialHandleRoots=[],this._spatialHandleMeshes=[]}_ensureSparkRenderer(){if(!this._renderer||this._sparkRenderer||this._sparkRendererLoading||this._sparkRendererFailed)return;const t=performance.now();bl(this._lastSparkDiscoveryAt,t)&&(this._lastSparkDiscoveryAt=t,Ml(this._scene)&&(this._sparkRendererLoading=!0,Ss(async()=>{const{SparkRenderer:e}=await import("./spark.module-uQlq--TY.js");return{SparkRenderer:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11])).then(({SparkRenderer:e})=>{if(this._disposed||!this._renderer)return;const i=new e({renderer:this._renderer,enableLod:!1});i.traverse(s=>Rt(s,"engineInternal",!0)),this._sparkRenderer=i}).catch(e=>{this._sparkRendererFailed=!0,console.error("Failed to install SparkRenderer in the editor viewport.",e)}).finally(()=>{this._sparkRendererLoading=!1})))}_buildOrientationGizmo(){if(this._vcScene!==void 0){for(const t of[...this._vcScene.children])this._vcScene.remove(t);this._vcBalls.length=0,this._vcStalks.length=0,this._vcClickTargets.length=0,this._initOrientationGizmo()}}_initOrientationGizmo(){const t=mi/3,e=xn/t,i=Zu/t,s=Xa/t/2,r=[new v(1,0,0),new v(0,1,0),new v(0,0,1)],n=new fe(e*.6,8,8),a=new Tt({visible:!1});for(let l=0;l<3;l++){const[h,d]=this._lookAxisFrame[l],c=Xu[h],p=Vu[h],u=r[l].clone().multiplyScalar(d),f=new E(new Ot(s,s,i,8),new Tt({color:c,transparent:!0,depthTest:!1}));f.position.copy(u).multiplyScalar(i/2),f.quaternion.setFromUnitVectors(new v(0,1,0),u),this._vcScene.add(f),this._vcStalks.push({mesh:f,direction:u.clone()});for(const m of[1,-1]){const y=u.clone().multiplyScalar(m),g=new xa(new Jh({map:Yu(c,m>0?p:null),transparent:!0,depthTest:!1}));g.position.copy(y).multiplyScalar(i),g.scale.setScalar(e),this._vcScene.add(g),this._vcBalls.push({sprite:g,direction:y.clone(),positive:m>0});const _=new E(n,a);_.position.copy(g.position),Rt(_,"vcDirIdx",l*2+(d*m>0?0:1)),this._vcScene.add(_),this._vcClickTargets.push(_)}}}_syncOrientationGizmoDepth(){const t=mi/3,e=this._vcDir.copy(this._vcCamera.position).normalize();for(const{sprite:i,direction:s,positive:r}of this._vcBalls){const n=(s.dot(e)+1)/2,a=i.material;a.opacity=r?1:.56+n*.44,i.scale.setScalar((xn+Qu*n)/t),i.renderOrder=10+Math.round(n*100)}for(const{mesh:i,direction:s}of this._vcStalks){const r=(s.dot(e)+1)/2;i.material.opacity=.35+r*.65,i.renderOrder=Math.round(r*100)}}_isOverViewCube(t,e){const i=this._canvas.getBoundingClientRect(),s=t-i.left,r=e-i.top,n=i.width-this._vcSize-this._vcMarginRight,a=this._vcMarginTop;return s>=n&&s<=n+this._vcSize&&r>=a&&r<=a+this._vcSize}_handleViewCubeClick(t){if(!this._isOverViewCube(t.clientX,t.clientY))return!1;const e=this._canvas.getBoundingClientRect(),i=t.clientX-e.left,s=t.clientY-e.top,r=e.width-this._vcSize-this._vcMarginRight,n=this._vcMarginTop,a=(i-r)/this._vcSize*2-1,l=-((s-n)/this._vcSize*2-1);this._vcRaycaster.setFromCamera(new Jt(a,l),this._vcCamera);const h=this._vcRaycaster.intersectObjects(this._vcClickTargets);if(h.length===0)return!0;const d=xt(h[0].object,"vcDirIdx"),c=Uu[d],p=new v().subVectors(this.freeCamera.position,this.orbitControls.target).normalize();return this._snapDist=this.freeCamera.position.distanceTo(this.orbitControls.target),this._snapQ1.setFromUnitVectors(new v(0,0,1),p),this._snapQ2.setFromUnitVectors(new v(0,0,1),c),this._snapStartTime=performance.now(),this._snapAnimating=!0,!0}_flushGizmoToStoreLive(){this._skipNextSync=!0;const t=this._authoring(),e=(s,r)=>{s&&no(t,s,{position:r.position.toArray(),rotation:r.quaternion.toArray(),scale:r.scale.toArray()})},i=this._activeGizmo.object;i&&i!==this._pivotDummy&&e(this._attachedAuthoringId??this._authoringIdForObject(i),i);for(const{id:s,obj:r}of this._otherDragObjects)e(s,r);for(const{id:s,obj:r}of this._allDragObjects)e(s,r);for(const{id:s,obj:r}of this._preservedChildObjects)e(s,r)}_preparePreservedChildren(t){if(!this._store.preserveChildrenTransform)return[];const e=this._authoring(),i=new Set(t),s=new Map;for(const r of i){const n=this._preservedChildrenForParent(e,r,i,s);if(typeof n=="string")return jt(n),[];for(const a of n)s.set(a.id,a)}return[...s.values()]}_preservedChildrenForParent(t,e,i,s){const r=[];for(const n of t.hierarchy.node(e)?.childIds??[]){if(i.has(n)||s.has(n))continue;const a=this._objectForAuthoringId(n);if(!a?.parent)continue;const l=this._unwritableTransformChannel(t,n);if(l){const h=t.hierarchy.node(n)?.label??n;return`Preserve Children Transform needs writable ${l} on ${h}. The parent will transform normally.`}a.updateWorldMatrix(!0,!1),r.push({id:n,obj:a,worldMatrix:a.matrixWorld.clone()})}return r}_unwritableTransformChannel(t,e){return["position","rotation","scale"].find(i=>!(t.transforms?.editability?.(e,i).writable??!1))}_restorePreservedChildren(){const t=new Mn;for(const e of this._preservedChildObjects){const i=e.obj.parent;i&&(i.updateWorldMatrix(!0,!1),t.copy(i.matrixWorld).invert().multiply(e.worldMatrix),t.decompose(e.obj.position,e.obj.quaternion,e.obj.scale),e.obj.updateMatrix(),e.obj.updateWorldMatrix(!1,!0))}}_belongsToRoots(t,e){let i=t;for(;i;){if(e.has(i))return!0;i=i.parent}return!1}_floorSnapPosition(t,e){t.updateWorldMatrix(!0,!0);const i=Ie(t);if(i.isEmpty())return null;const s=Math.min((i.max.x-i.min.x)*.1,.05),r=Math.min((i.max.z-i.min.z)*.1,.05),n=[[(i.min.x+i.max.x)/2,(i.min.z+i.max.z)/2],[i.min.x+s,i.min.z+r],[i.max.x-s,i.min.z+r],[i.min.x+s,i.max.z-r],[i.max.x-s,i.max.z-r]],a=new Yt;a.layers.enableAll();const l=i.min.y+Math.max((i.max.y-i.min.y)*.001,.001);let h=Number.NEGATIVE_INFINITY;for(const[p,u]of n){a.set(new v(p,l,u),new v(0,-1,0));const f=a.intersectObjects(this._scene.children,!0).find(m=>!this._belongsToRoots(m.object,e)&&!ue(m.object)&&m.point.y<=l);f&&(h=Math.max(h,f.point.y))}if(!Number.isFinite(h))return null;const d=h-i.min.y;if(Math.abs(d)<1e-6)return null;const c=t.getWorldPosition(new v);return c.y+=d,t.parent?(t.parent.updateWorldMatrix(!0,!1),t.parent.worldToLocal(c)):c}snapSelectionToFloor(){const t=this._authoring(),e=t.transforms;if(!e){jt("This document does not expose writable transforms.");return}const i=[...this._store.selectedEntityIds].map(l=>({id:l,obj:this._objectForAuthoringId(l)})).filter(l=>!!l.obj&&(e.editability?.(l.id,"position").writable??!0)),s=new Set(i.map(({obj:l})=>l)),r=i.filter(({obj:l})=>{let h=l.parent;for(;h;){if(s.has(h))return!1;h=h.parent}return!0});if(r.length===0){jt("Select an object with a writable position first.");return}const n=new Set(r.map(({obj:l})=>l)),a=[];for(const l of r){const h=this._floorSnapPosition(l.obj,n);h&&a.push({...l,position:h})}if(a.length===0){jt("No solid scene surface was found beneath the selection.");return}for(const{id:l}of a)ro(t,l);for(const{obj:l,position:h}of a)l.position.copy(h);this._skipNextSync=!0;for(const{id:l,obj:h}of a)no(t,l,{position:h.position.toArray(),rotation:h.quaternion.toArray(),scale:h.scale.toArray()});for(const{id:l}of a)oo(t,l);this.syncFromStore()}_applySurfaceSnap(t,e){const i=new Set,s=this._attachedAuthoringId??this._authoringIdForObject(t);s&&i.add(s);for(const{id:h}of e)i.add(h);const r=[];for(const[h,d]of this._objectMap)i.has(h)||r.push(d);if(r.push(this.grid),r.length===0){this._surfaceSnapIndicator.visible=!1;return}const n=t.position.clone();n.y+=50,this._surfaceSnapRaycaster.set(n,new v(0,-1,0)),this._surfaceSnapRaycaster.far=200;const l=this._surfaceSnapRaycaster.intersectObjects(r,!0).find(h=>h.object===this.grid||!ue(h.object));if(l){const h=l.point,d=h.y,c=d-t.position.y;t.position.y=d;for(const{obj:u}of e)u.position.y+=c;this._surfaceSnapIndicator.position.copy(h),this._surfaceSnapIndicator.position.y+=.01;const p=l.face?.normal;if(p){const u=p.clone().transformDirection(l.object.matrixWorld);this._surfaceSnapIndicator.quaternion.setFromUnitVectors(new v(0,1,0),u)}this._surfaceSnapIndicator.visible=!0}else this._surfaceSnapIndicator.visible=!1}_collectVertices(t){const e=[];for(const[s,r]of this._objectMap)t.has(s)||r.traverse(n=>{if(ue(n))return;const a=n;if(!a.isMesh||!a.geometry)return;const l=a.geometry.getAttribute("position");if(!l)return;const h=Math.min(l.count,1e3),d=a.matrixWorld;for(let c=0;c<h;c++){const p=new v(l.getX(c),l.getY(c),l.getZ(c));p.applyMatrix4(d),e.push(p)}});return e}_applyVertexSnap(t,e){const i=t.position,s=i.clone().project(this.renderCamera),r=this._canvas.getBoundingClientRect(),n=(s.x+1)/2*r.width,a=(-s.y+1)/2*r.height;let l=this._vertexSnapThreshold,h=null;for(const d of this._vertexSnapTargets){const c=d.clone().project(this.renderCamera);if(c.z>1)continue;const p=(c.x+1)/2*r.width,u=(-c.y+1)/2*r.height,f=n-p,m=a-u,y=Math.sqrt(f*f+m*m);y<l&&(l=y,h=d)}if(h){const d=h.clone().sub(i);t.position.copy(h);for(const{obj:p}of e)p.position.add(d);this._vertexSnapIndicator.position.copy(h),this._vertexSnapIndicator.visible=!0;const c=h.distanceTo(this.renderCamera.position);this._vertexSnapIndicator.scale.setScalar(c*.008)}else this._vertexSnapIndicator.visible=!1}_flushGizmoToStore(){this._flushGizmoToStoreLive();const t=this._activeTransformEditIds;this._activeTransformEditIds=[],this._otherDragObjects=[],this._allDragObjects=[],this._preservedChildObjects=[];const e=this._authoring();for(const i of t)oo(e,i)}consumeSkipSync(){return this._skipNextSync?(this._skipNextSync=!1,!0):!1}_applyGizmoSize(){if(this.transformControls===void 0)return;const t=this._lookGizmoSizePx,e=Math.max(1,this._canvas.clientHeight),i=t===null?null:2*t,s=i===null?1:this.freeCamera instanceof pi?4*i/e:i/(.2375*e);for(const r of this._allGizmos())r.size=s}_dropNegativeAxisHandles(t,e){const i=t.children.find(r=>r.isTransformControlsGizmo);if(!i)return;const s={X:new v(1,0,0),Y:new v(0,1,0),Z:new v(0,0,1)};for(const r of e)for(const n of[i.gizmo[r],i.picker[r]])if(n)for(const a of[...n.children]){const l=s[a.name];if(l===void 0)continue;const h=a;if(!h.geometry)continue;h.geometry.computeBoundingBox();const d=h.geometry.boundingBox;d&&d.getCenter(new v).dot(l)<0&&n.remove(a)}}_axisColorMap(){const t=r=>new B(...De[this._lookAxisFrame[r][0]]),e=t(0),i=t(1),s=t(2);return{X:e,Y:i,Z:s,XY:s,YZ:e,XZ:i}}_readLookStage(t){this._lookAxisFrame=eo(t)==="z"?qo:nn,this._lookBoxSelect=io(t),this._applyGizmoAxisFrame(),this._buildOrientationGizmo()}_applyGizmoAxisFrame(){if(this.transformControls===void 0)return;const t=this._lookAxisFrame.map(([,a])=>a),e=[0,1,2].map(a=>t[a]===this._appliedAxisSigns[a]?1:-1),i=e.some(a=>a===-1),s=this._axisColorMap(),r={X:new B(...De[0]),Y:new B(...De[1]),Z:new B(...De[2]),XY:new B(...De[2]),YZ:new B(...De[0]),XZ:new B(...De[1])},n=(a,l,h,d=!1)=>{a&&a.traverse(c=>{const p=c;h&&p.geometry&&p.geometry.scale(e[0],e[1],e[2]),d&&p.material&&!Array.isArray(p.material)&&!p.userData.vgaiOwnMaterial&&(p.material=p.material.clone(),p.userData.vgaiOwnMaterial=!0);const u=p.material;if(!u||Array.isArray(u))return;h&&(u.side=We);const f=l[c.name];f&&u.color&&(u.color.copy(f),u._color=void 0)})};for(const a of this._allGizmos()){const l=a.getHelper().children.find(h=>h.isTransformControlsGizmo);if(l)for(const h of["gizmo","picker","helper"])n(l[h]?.translate,s,i),n(l[h]?.rotate,s,!1),n(l[h]?.scale,r,!1,!0)}i&&(this._appliedAxisSigns=t)}_patchGizmo(t){const e=this._axisColorMap(),i={XY:[-.075,-.075,0],YZ:[0,-.075,-.075],XZ:[-.075,0,-.075]};t.traverse(s=>{const r=s,n=e[s.name];if(n&&r.material){const l=r.material;l.color&&l.color.copy(n)}const a=i[s.name];a&&r.geometry&&r.geometry.translate(a[0],a[1],a[2])})}_patchCombinedScaleGizmo(t){const i=t.children.find(a=>a.isTransformControlsGizmo);if(!i)return;const s={X:new v(1,0,0),Y:new v(0,1,0),Z:new v(0,0,1)},r=.54+.55,n=.3;for(const[a,l]of[[i.gizmo.scale,!1],[i.picker.scale,!0]])if(a)for(const h of[...a.children]){const d=h,c=s[h.name],p=c!==void 0&&d.geometry?.type==="CylinderGeometry"&&d.geometry.parameters.radiusTop<.05;if(c===void 0||p){a.remove(h);continue}d.geometry.computeBoundingBox();const u=d.geometry.boundingBox;if(!u)continue;const f=Math.sign(u.getCenter(new v).dot(c))||1;if(l){const y=c.clone().multiplyScalar(f*r);d.geometry.dispose(),d.geometry=new mt(n,n,n).translate(y.x,y.y,y.z);continue}const m=c.clone().multiplyScalar(f*.55);d.geometry.translate(m.x,m.y,m.z)}}_projectToScreen(t){const e=new v;t.getWorldPosition(e),e.project(this.renderCamera);const i=this._canvas.getBoundingClientRect();return new Jt((e.x+1)/2*i.width+i.left,(-e.y+1)/2*i.height+i.top)}static _FLY_KEYS=new Set(["w","a","s","d","q","e"]);_enterFlyMode(){this._flyActive||this._cameraViewMode!=="view"&&(this._flyActive=!0,this._snapAnimating=!1,this.orbitControls.enabled=!1,this._flyEuler.setFromQuaternion(this.renderCamera.quaternion,"YXZ"),this.orbitControls.dispatchEvent({type:"start"}),this._canvas.requestPointerLock?.())}_exitFlyMode(){if(!this._flyActive)return;this._flyActive=!1,this._flyKeys.clear(),this.orbitControls.enabled=this._cameraViewMode!=="view",document.exitPointerLock();const t=this.renderCamera,e=new v(0,0,-1).applyQuaternion(t.quaternion),i=t.position.distanceTo(this.orbitControls.target);this.orbitControls.target.copy(t.position).add(e.multiplyScalar(Math.max(i,5))),this.orbitControls.dispatchEvent({type:"end"})}_updateFlyCamera(t){if(!this._flyActive||this._flyKeys.size===0)return;const e=this.renderCamera,i=this._flySpeed*(this._flyKeys.has("shift")?3:1),s=new v(0,0,-1).applyQuaternion(e.quaternion),r=new v(1,0,0).applyQuaternion(e.quaternion),n=new v;this._flyKeys.has("w")&&n.add(s),this._flyKeys.has("s")&&n.sub(s),this._flyKeys.has("d")&&n.add(r),this._flyKeys.has("a")&&n.sub(r),this._flyKeys.has("e")&&(n.y+=1),this._flyKeys.has("q")&&(n.y-=1),n.lengthSq()>0&&(n.normalize().multiplyScalar(i*t),e.position.add(n),this.orbitControls.dispatchEvent({type:"change"}))}_onFlyKeyDown=t=>{if(!this._rightMouseDown||t.target instanceof HTMLInputElement||t.target instanceof HTMLTextAreaElement||t.target instanceof HTMLSelectElement)return;const e=t.key.toLowerCase();if(e==="shift"){this._flyKeys.add("shift");return}Nn._FLY_KEYS.has(e)&&(t.preventDefault(),t.stopPropagation(),this._flyKeys.add(e),this._flyActive||this._enterFlyMode())};_onFlyKeyUp=t=>{const e=t.key.toLowerCase();if(e==="shift"){this._flyKeys.delete("shift");return}this._flyKeys.delete(e)};_onFlyPointerDown=t=>{t.button===2&&(this._rightMouseDown=!0)};_onFlyPointerUp=t=>{t.button===2&&(this._rightMouseDown=!1,this._flyActive&&this._exitFlyMode())};_onFlyPointerMove=t=>{if(!this._flyActive)return;const e=.002;this._flyEuler.y-=t.movementX*e,this._flyEuler.x-=t.movementY*e,this._flyEuler.x=Math.max(-Math.PI/2+.01,Math.min(Math.PI/2-.01,this._flyEuler.x)),this.renderCamera.quaternion.setFromEuler(this._flyEuler),this.orbitControls.dispatchEvent({type:"change"})};_onTrackpadWheel=t=>{if(this._flyActive||!this.orbitControls.enabled||t.ctrlKey||Math.abs(t.deltaX)<.5&&!t.shiftKey)return;t.preventDefault(),t.stopImmediatePropagation();const e=this._interactionElement.clientHeight||1,i=this.camera.position.distanceTo(this.orbitControls.target),s=2*Math.tan(this.camera.fov/2*Math.PI/180)*i/e,r=t.deltaMode===1?16:1,n=d=>Math.sign(d)*Math.min(Math.abs(d*r),30),a=new v().setFromMatrixColumn(this.camera.matrix,0),l=new v().setFromMatrixColumn(this.camera.matrix,1),h=a.multiplyScalar(n(t.deltaX)*s).add(l.multiplyScalar(-n(t.deltaY)*s));this.camera.position.add(h),this.orbitControls.target.add(h),this.orbitControls.update()};_onFlyWheel=t=>{if(!this._flyActive)return;t.preventDefault();const e=t.deltaY>0?.85:1.18;this._flySpeed=Math.max(.5,Math.min(100,this._flySpeed*e))};_onPointerDown=t=>{if(this._pointerDownPos.set(t.clientX,t.clientY),this._pointerDownButton=t.button,this._marqueeActive=!1,this._pointerSessionActive=!0,this._constraintControlPointerSession=!1,t.button===0&&!t.altKey){if(this._selectConstraintControlAt(t))return;const e=this._raycastSpatialHandle(t),i=e?Do(e):null;if(e&&i?.handle.writable){t.stopPropagation(),this._activeSpatialHandle=i,this._spatialHandleDragPoint.copy(e.position),this._orbitEnabledBeforeHandleDrag=this.orbitControls.enabled,this._transformEnabledBeforeHandleDrag=this.transformControls.enabled,this.orbitControls.enabled=!1;for(const n of this._allGizmos())n.enabled=!1;const s=this.renderCamera.getWorldDirection(new v);this._spatialHandleDragPlane.setFromNormalAndCoplanarPoint(s,e.position),this._spatialHandleDragOffset.set(0,0,0);const r=this._spatialHandleWorldPoint(t);r&&this._spatialHandleDragOffset.subVectors(e.position,r),this._canvas.style.cursor="grabbing"}}};_onPointerMove=t=>{if(this._updateEditorHandleInteraction(t)||(this._updateSpatialHandleHover(t),!this._pointerSessionActive)||!(t.buttons&1)||this._pointerDownButton!==0||this._anyGizmoDragging()||this._altDragOrbit)return;const e=t.clientX-this._pointerDownPos.x,i=t.clientY-this._pointerDownPos.y;if(!this._marqueeActive&&Math.sqrt(e*e+i*i)>5){const s=this._canvas.getBoundingClientRect(),r=this._pointerDownPos.x-s.left,n=this._pointerDownPos.y-s.top,a=s.width-this._vcSize-this._vcMarginRight;if(r>=a&&r<=a+this._vcSize&&n>=this._vcMarginTop&&n<=this._vcMarginTop+this._vcSize)return;this._marqueeActive=!0,this.orbitControls.enabled=!1,this._marqueeDiv||(this._marqueeDiv=document.createElement("div"),Object.assign(this._marqueeDiv.style,{position:"fixed",border:`1px solid ${Nt.accent.default}`,background:Nt.accent.muted,pointerEvents:"none",zIndex:ao.sticky}),(document.getElementById("editor-chrome-root")??document.body).appendChild(this._marqueeDiv))}if(this._marqueeActive&&this._marqueeDiv){const s=Math.min(this._pointerDownPos.x,t.clientX),r=Math.min(this._pointerDownPos.y,t.clientY),n=Math.abs(t.clientX-this._pointerDownPos.x),a=Math.abs(t.clientY-this._pointerDownPos.y);Object.assign(this._marqueeDiv.style,{left:`${s}px`,top:`${r}px`,width:`${n}px`,height:`${a}px`,display:"block"})}};_onPointerUp=t=>{if(!this._pointerSessionActive)return;if(this._pointerSessionActive=!1,this._activeSpatialHandle){this._finishSpatialHandleDrag(!0);return}if(this._constraintControlPointerSession){this._constraintControlPointerSession=!1;return}if(this._marqueeActive){this._marqueeActive=!1,this.orbitControls.enabled=!0,this._marqueeDiv&&(this._marqueeDiv.style.display="none");const n=Math.min(this._pointerDownPos.x,t.clientX),a=Math.max(this._pointerDownPos.x,t.clientX),l=Math.min(this._pointerDownPos.y,t.clientY),h=Math.max(this._pointerDownPos.y,t.clientY),d=[],c=new v,p=new ie;for(const[u,f]of this._objectMap){if(!f.visible||f.isCamera===!0)continue;if(p.setFromObject(f),p.isEmpty()){const b=this._projectToScreen(f);b.x>=n&&b.x<=a&&b.y>=l&&b.y<=h&&d.push(u);continue}const m=this._lookBoxSelect==="touch",y=this._canvas.getBoundingClientRect();let g=!0,_=Number.POSITIVE_INFINITY,M=Number.NEGATIVE_INFINITY,w=Number.POSITIVE_INFINITY,C=Number.NEGATIVE_INFINITY;for(let b=0;b<8;b++){if(c.set(b&1?p.max.x:p.min.x,b&2?p.max.y:p.min.y,b&4?p.max.z:p.min.z),c.project(this.camera),c.z<-1||c.z>1){if(g=!1,!m)break;continue}const P=y.left+(c.x+1)*y.width/2,A=y.top+(1-c.y)*y.height/2;(P<n||P>a||A<l||A>h)&&(g=!1),_=Math.min(_,P),M=Math.max(M,P),w=Math.min(w,A),C=Math.max(C,A)}const x=_<=M&&M>=n&&_<=a&&C>=l&&w<=h;(m?x:g)&&d.push(u)}if(t.shiftKey)for(const u of d)this._store.addToSelection(u);else ki(this._authoring(),d);return}if(t.button!==0)return;const e=t.clientX-this._pointerDownPos.x,i=t.clientY-this._pointerDownPos.y;if(Math.sqrt(e*e+i*i)>5||this._anyGizmoDragging()||this._threejsToolContextActive&&this._handleViewCubeClick(t))return;const s=t.shiftKey&&(t.metaKey||t.ctrlKey),r=Cl(this._scopeAuthoring(),()=>this._pickAt(t.clientX,t.clientY,s?"deep":"normal"));s?ki(this._authoring(),r?[r]:[]):t.shiftKey&&r?this._store.toggleSelection(r):(t.metaKey||t.ctrlKey)&&r?this._store.toggleSelection(r):ki(this._authoring(),r?[r]:[])};_scopeAuthoring(){return this._standaloneAuthoring?this._authoring():Gs().panelAuthoring(this._store)}_pickAt(t,e,i){return this._pick?this._pick(t,e):Gs().pick(this._store,t,e,i)}_onDoubleClick=t=>{if(t.button!==0||this._anyGizmoDragging()||this._marqueeActive||this._threejsToolContextActive&&this._isOverViewCube(t.clientX,t.clientY))return;const e=this._pickAt(t.clientX,t.clientY,"normal");e&&Pl(this._scopeAuthoring(),e,()=>this._pickAt(t.clientX,t.clientY,"normal"))};_raycastGroundPlane(t){const e=this._canvas.getBoundingClientRect(),i=new Jt((t.clientX-e.left)/e.width*2-1,-((t.clientY-e.top)/e.height)*2+1);this.raycaster.setFromCamera(i,this.renderCamera);const s=lo("three");this._groundPlane.set(s.up==="z"?Hu:Nu,-s.groundHeight);const r=new v;return this.raycaster.ray.intersectPlane(this._groundPlane,r)}_showDropOverlay(){if(this._dropOverlay)return;const t=document.createElement("div");Object.assign(t.style,{position:"fixed",inset:"0",pointerEvents:"none",border:`2px dashed ${Nt.accent.default}`,background:Nt.accent.muted,zIndex:ao.base}),(document.getElementById("editor-chrome-root")??document.body).appendChild(t),this._dropOverlay=t}_hideDropOverlay(){this._dropOverlay&&(this._dropOverlay.remove(),this._dropOverlay=null)}_onDragOver=t=>{t.dataTransfer?.types.includes("application/x-editor-asset")&&(t.preventDefault(),t.dataTransfer.dropEffect="copy",this._showDropOverlay())};_onDragLeave=t=>{this._hideDropOverlay()};_onDrop=t=>{this._hideDropOverlay();const e=t.dataTransfer?.getData("application/x-editor-asset");if(!e)return;t.preventDefault();let i;try{i=JSON.parse(e)}catch{return}const s=lo("three"),r=this._raycastGroundPlane(t),n=c=>Math.round(c*100)/100,a=s.up==="z"?[n(r?.x??0),n(r?.y??0),s.groundHeight]:[n(r?.x??0),s.groundHeight,n(r?.z??0)],l=this._authoring(),h=l.assetDrop,d=i.component??{kind:"file",name:i.name};if(!h){Fi.warn(`Dropped “${i.name}” was not placed: this document does not accept dropped assets.`,"editor");return}if(i.online){const c=i.online,p=this._onlineAssetResolver;if(!p){Fi.warn(`Dropped “${i.name}” was not placed: this viewport has no online-asset resolver installed.`,"editor");return}jt(`Downloading ${c.name} from the library…`),p(c).then(u=>{u?(jt(`${c.name} downloaded — placing it.`),ho(l,"",u,{position:a})):jt(`Could not download ${c.name} — see the Console.`)}).catch(()=>{jt(`Could not download ${c.name} — see the Console.`),Fi.error(`Could not download ${c.name}.`,"asset")});return}ho(l,"",i.path,{position:a,item:d})}}class rp extends kt{constructor(t,e){super(),this.bones=t;const i=new Set;for(const a of t){const l=a.parent;l?.isBone&&this.addSegment(l,a,i);for(const h of a.children)h.isBone&&this.addSegment(a,h,i)}this.linePositions=new Float32Array(Math.max(this.segments.length*6,6));const s=new Tn;s.setPositions(this.linePositions),this.lineMaterial=new zn({color:e,linewidth:5,worldUnits:!1,depthTest:!1,depthWrite:!1,toneMapped:!1,alphaToCoverage:!0}),this.lines=new En(s,this.lineMaterial),this.lines.onBeforeRender=a=>{a.getSize(this.lineMaterial.resolution)},this.lines.frustumCulled=!1,this.lines.renderOrder=1001,this.add(this.lines),this.pointPositions=new Float32Array(Math.max(t.length*3,3));const r=new Re;r.setAttribute("position",new ce(this.pointPositions,3));const n=new Yh({color:e,size:11,sizeAttenuation:!1,depthTest:!1,depthWrite:!1,toneMapped:!1});this.points=new wa(r,n),this.points.frustumCulled=!1,this.points.renderOrder=1002,this.add(this.points),this.name="__object3d_document_bone_selection",pn(this,"editorHelper",!0),this.traverse(a=>a.layers.set(X)),this.update()}segments=[];linePositions;pointPositions;lines;lineMaterial;points;worldPosition=new v;setColor(t){this.lineMaterial.color.setHex(t),this.points.material.color.setHex(t)}update(){let t=0;for(const[s,r]of this.segments)s.getWorldPosition(this.worldPosition),this.linePositions.set(this.worldPosition.toArray(),t),r.getWorldPosition(this.worldPosition),this.linePositions.set(this.worldPosition.toArray(),t+3),t+=6;const e=this.lines.geometry.getAttribute("instanceStart");e&&(e.data.needsUpdate=!0),t=0;for(const s of this.bones)s.getWorldPosition(this.worldPosition),this.pointPositions.set(this.worldPosition.toArray(),t),t+=3;const i=this.points.geometry.getAttribute("position");i&&(i.needsUpdate=!0)}dispose(){this.lines.geometry.dispose(),this.lineMaterial.dispose(),this.points.geometry.dispose(),this.points.material.dispose()}addSegment(t,e,i){const s=`${t.uuid}:${e.uuid}`;i.has(s)||(i.add(s),this.segments.push([t,e]))}}const np="skeletons",on=new B(58879),an=new B(16756736);function op(o){const t=o.geometry.getAttribute("color");for(let i=0;i<t.count;i+=2)t.setXYZ(i,on.r,on.g,on.b),i+1<t.count&&t.setXYZ(i+1,an.r,an.g,an.b);t.needsUpdate=!0,o.renderOrder=999;const e=o.material;e.depthTest=!1,e.depthWrite=!1,e.toneMapped=!1,pn(o,"editorHelper",!0),pn(o,"editorHelperType",np),o.traverse(i=>i.layers.set(X))}const Qo=o=>!bs(o),ap=1,lp=700,hp=.001,cp=Math.PI-.001,dp=o=>o<.5?4*o*o*o:1-(-2*o+2)**3/2,up=o=>o;function hi(o,t){return typeof o=="number"&&Number.isFinite(o)?o:t}const $o={mode:"solid",grid:!0,background:"neutral",exposure:1,projection:"perspective",lighting:"studio",skeleton:!1,bounds:!1};class pp{constructor(t,e,i,s,r,n=[],a,l=new B(2106410),h=null){this.documentId=t,this.root=e,this.scene=i,this.renderer=s,this.viewport=r,this.editorLights=n,this.authoring=a,this.neutralBackground=l,this.frameBox=h,this.unsubscribeSelectionTheme=mr(s.domElement,this.syncSelectionTheme),r.orbitControls.addEventListener("start",this.cancelLookForHuman)}profiler=mc();shading=new xc;helpers=[];skeletonHelper=null;boundsHelper=null;boneSelectionHighlight=null;boneSelectionSignature="";composer=null;composerLoading=!1;disposed=!1;sceneRenderPass=null;selectionOutline=null;selectionOutlinePass=null;selectedObjects=[];renderWidth=1;renderHeight=1;orthographicCamera=new pi;captureAspect=null;cameraOverride=null;beforeRender=null;state=$o;version=0;listeners=new Set;unsubscribeSelectionTheme=()=>{};flight=null;flightPose=new v;topologyOverlay=null;topologyFollowers=[];replaceContent(t,e){this.selectionOutline?.selection.clear(),this.selectedObjects=[],this.boneSelectionSignature="",this.clearBoneSelectionHighlight(),this.clearSkeletonHelper(),this.clearBoundsHelper(),this.clearTopologyOverlay(),this.root=t,this.authoring=e,this.state.mode==="wireframe"&&this.buildTopologyOverlay(),this.state.bounds&&(this.boundsHelper=new mo(t,16757844),this.addHelper(this.boundsHelper,"bounds")),this.syncSelectionPresentation(),this.refreshSkeletonHelper(),this.notify()}cancelLookForHuman=()=>{this.settleFlight("human")};syncSelectionTheme=()=>{const t=ze(this.renderer.domElement).visible;this.selectionOutline&&Cu(this.selectionOutline,ze(this.renderer.domElement)),this.boneSelectionHighlight?.setColor(t)};subscribe=t=>(this.listeners.add(t),()=>this.listeners.delete(t));getSnapshot=()=>this.version;presentation(){return this.state}resolveFrameBounds(){const t=this.authoring?.selection?.get()??[];if(t.length>0){const e=new ie;let i=!1;for(const s of t){const r=this.authoring?.hierarchy.object3D?.(s);if(!r)continue;const n=Ie(r);n.isEmpty()||(e.union(n),i=!0)}if(i)return e}return this.frameBox&&!this.frameBox.isEmpty()?this.frameBox:Ie(this.root)}frame(t=1){const e=this.resolveFrameBounds();if(e.isEmpty()){let a=0,l=0;return this.root.traverse(h=>{const d=h.geometry;d&&(a+=1,l+=d.getAttribute("position")?.count??0)}),Fi.warn(`frame: nothing to frame — root "${this.root.name}" (${this.root.children.length} children, ${a} meshes, ${l} positions), selection ${JSON.stringify(this.authoring?.selection?.get()??[])}, frameBox ${this.frameBox?this.frameBox.isEmpty()?"empty":"set":"none"}`,"document"),!1}this.settleFlight("superseded");const i=e.getCenter(new v),s=this.viewport.camera.position.clone().sub(this.viewport.orbitControls.target).normalize();s.lengthSq()===0&&s.set(.8,.5,-1).normalize();const r=Math.min(10,Math.max(.1,hi(t,1))),n=Xe(e,this.viewport.camera,s)*r;return this.viewport.setPose(i.clone().addScaledVector(s,n),i),!0}orbit(t){return this.launchFlight(hi(t.azimuth,0),hi(t.elevation,0),Math.min(60,Math.max(0,hi(t.duration,.6))),dp)}turntable(t){const e=hi(t.revolutions,1);return this.launchFlight(e*Math.PI*2,0,Math.min(60,Math.max(0,hi(t.seconds,6))),up)}looking(){return this.flight!==null}launchFlight(t,e,i,s){this.settleFlight("superseded");const r=this.viewport.camera,n=this.viewport.orbitControls.target.clone(),a=new qh().setFromVector3(r.position.clone().sub(n)),l=a.radius>1e-4?a.radius:Math.max(this.resolveFrameBounds().getSize(new v).length(),1),h={pivot:n,radius:l,startTheta:a.theta,startPhi:a.phi,deltaTheta:t,deltaPhi:-e,duration:i,ease:s,elapsed:0,theta:a.theta,phi:a.phi,settle:null};this.flight=h;const d=new Promise(c=>{h.settle=c});return this.applyFlightPose(h,0),i<=0&&this.settleFlight(null),d}applyFlightPose(t,e){const i=t.ease(e);t.theta=t.startTheta+t.deltaTheta*i,t.phi=Math.min(cp,Math.max(hp,t.startPhi+t.deltaPhi*i));const s=this.viewport.camera;s.position.setFromSphericalCoords(t.radius,t.phi,t.theta).add(t.pivot),this.viewport.orbitControls.target.copy(t.pivot),s.lookAt(t.pivot),s.updateMatrixWorld(),this.flightPose.copy(s.position)}advanceLook(t){const e=this.flight;if(!e)return;const i=Math.max(1e-4,e.radius*.001);if(this.viewport.camera.position.distanceToSquared(this.flightPose)>i*i){this.settleFlight("human");return}t>0&&Number.isFinite(t)&&(e.elapsed+=t);const s=e.duration<=0?1:Math.min(1,e.elapsed/e.duration);this.applyFlightPose(e,s),s>=1&&this.settleFlight(null)}settleFlight(t){const e=this.flight;if(!e)return;this.flight=null;const i={completed:t===null,azimuth:e.theta,elevation:Math.PI/2-e.phi,seconds:Math.min(e.elapsed,e.duration)};e.settle?.(t===null?i:{...i,cancelledBy:t})}select(t){this.authoring&&ki(this.authoring,[...t])}selection(){return[...this.authoring?.selection?.get()??[]]}idForObject(t){return this.authoring?.hierarchy.idForObject3D?.(t)??null}syncSelectionPresentation(){const t=(this.authoring?.selection?.get()??[]).map(s=>this.authoring?.hierarchy.object3D?.(s)??null).filter(s=>s!==null);this.selectedObjects=t,this.selectionOutline&&(jo(this.selectionOutline,this.selectionOutlineWanted?t:[]),this.syncComposerOutput());const e=t.filter(s=>!!s.isBone),i=e.map(s=>s.uuid).join("\0");i!==this.boneSelectionSignature&&(this.boneSelectionSignature=i,this.clearBoneSelectionHighlight(),e.length>0&&(this.boneSelectionHighlight=new rp(e,ze(this.renderer.domElement).visible),this.scene.add(this.boneSelectionHighlight)),this.refreshSkeletonHelper())}frameSelection(){return this.frameIds(this.authoring?.selection?.get()??[])}frameIds(t){this.settleFlight("superseded");const e=t.map(i=>this.authoring?.hierarchy.object3D?.(i)??null).filter(i=>i!==null);return e.length===0?!1:e.every(i=>i.isBone)?(this.frameBones(e),!0):(this.viewport.focusOnMultiple(e),!0)}setViewPreset(t){this.settleFlight("superseded");const e=this.resolveFrameBounds();if(e.isEmpty())return;const i=e.getCenter(new v),s=El(t),r=Xe(e,this.viewport.camera,s),n=i.clone().addScaledVector(s,r);this.viewport.camera.up.set(0,t==="top"?0:1,t==="top"?-1:0),this.viewport.setPose(n,i),this.setProjection(t==="isometric"?"perspective":"orthographic")}setCameraPose(t,e,i){this.settleFlight("superseded"),this.viewport.setPose(t,e,i)}cameraPose(){return{position:this.viewport.camera.position.toArray(),target:this.viewport.orbitControls.target.toArray(),fov:this.viewport.camera.fov}}camera(){return this.cameraOverride?this.cameraOverride:this.state.projection==="perspective"?this.viewport.camera:(this.syncOrthographicCamera(),this.orthographicCamera)}projection(){return this.state.projection}setProjection(t){this.state.projection!==t&&(this.state={...this.state,projection:t},this.notify())}lightingAvailable(){return this.editorLights.length>0}setLighting(t){this.state.lighting!==t&&(this.setLightingValues(t),this.state={...this.state,lighting:t},this.notify())}setMode(t){this.state.mode!==t&&(this.clearDiagnosticPresentation(),this.state={...this.state,mode:t},t==="uv"?this.scene.overrideMaterial=new ji({vertexShader:"varying vec2 vUv; void main(){ vUv=uv; gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.0); }",fragmentShader:"varying vec2 vUv; void main(){ gl_FragColor=vec4(vUv,0.0,1.0); }"}):t==="vertex-colors"?this.scene.overrideMaterial=new Tt({vertexColors:!0}):t==="wireframe"&&this.buildTopologyOverlay(),this.notify())}buildTopologyOverlay(){const t=new kt,e=[];this.root.updateMatrixWorld(!0),this.root.traverse(i=>{const s=i;if(!s.isMesh||!s.geometry)return;const r=new Cs(new An(s.geometry,ap),new Ze({color:1119773,toneMapped:!1,transparent:!0,opacity:.85,depthTest:!1,depthWrite:!1}));r.matrixAutoUpdate=!1,r.matrixWorldAutoUpdate=!1,r.matrixWorld.copy(s.matrixWorld),r.frustumCulled=!1,r.renderOrder=2,t.add(r),e.push({line:r,source:s})}),e.length!==0&&(this.topologyOverlay=t,this.topologyFollowers=e,this.addHelper(t,"topology"))}syncTopologyOverlay(){this.topologyFollowers.some(({source:t})=>t.parent===null)&&(this.clearTopologyOverlay(),this.buildTopologyOverlay());for(const{line:t,source:e}of this.topologyFollowers)t.matrixWorld.copy(e.matrixWorld),t.visible=e.visible}clearTopologyOverlay(){for(const{line:i}of this.topologyFollowers.splice(0))i.geometry.dispose(),i.material.dispose();const t=this.topologyOverlay;if(this.topologyOverlay=null,!t)return;t.removeFromParent();const e=this.helpers.indexOf(t);e>=0&&this.helpers.splice(e,1)}setBounds(t){this.state.bounds!==t&&(this.state={...this.state,bounds:t},t?(this.boundsHelper=new mo(this.root,16757844),this.addHelper(this.boundsHelper,"bounds")):this.clearBoundsHelper(),this.notify())}setSkeleton(t){this.state.skeleton!==t&&(this.state={...this.state,skeleton:t},this.refreshSkeletonHelper(),this.notify())}setGrid(t){this.state.grid!==t&&(this.viewport.grid.visible=t,this.state={...this.state,grid:t},this.notify())}neutralBackgroundTexture(){return this.neutralBackground}setNeutralBackground(t){const e=this.scene.background===this.neutralBackground;this.neutralBackground=t,e&&(this.scene.background=t)}setBackground(t){this.state.background!==t&&(this.scene.background=t==="transparent"?null:this.neutralBackground,this.state={...this.state,background:t},this.notify())}setExposure(t){!Number.isFinite(t)||t<.2||t>2||this.state.exposure!==t&&(this.renderer.toneMappingExposure=t,this.state={...this.state,exposure:t},this.notify())}resetPresentation(){this.clearDiagnosticPresentation(),this.state=$o,this.refreshSkeletonHelper(),this.clearBoundsHelper(),this.viewport.grid.visible=!0,this.scene.background=this.neutralBackground,this.renderer.toneMappingExposure=1,this.setLightingValues("studio"),this.viewport.camera.up.set(0,1,0),this.frame(),this.notify()}setBeforeRender(t){this.beforeRender=t}presentedFrameWaiters=[];presentsFrames=!1;setPresentsFrames(t){this.presentsFrames=t,t||this.resolvePresentedFrame(null)}requestPresentedFrame(){return this.presentsFrames?new Promise(t=>{let e=!1;const i=s=>{e||(e=!0,t(s))};this.presentedFrameWaiters.push(i),setTimeout(()=>i(null),lp)}):Promise.resolve(null)}servePresentedFrame(){if(this.presentedFrameWaiters.length===0)return;const t=this.renderer.domElement,e=document.createElement("canvas");e.width=Math.max(1,t.width),e.height=Math.max(1,t.height);const i=e.getContext("2d");if(!i){this.resolvePresentedFrame(null);return}i.drawImage(t,0,0),this.resolvePresentedFrame(e)}resolvePresentedFrame(t){const e=this.presentedFrameWaiters;this.presentedFrameWaiters=[];for(const i of e)i(t)}render(t){this.beforeRender?.(),this.boneSelectionHighlight?.update();const e=this.camera(),i=this.state.mode;if(this.boundsHelper?.update(),i==="uv"||i==="vertex-colors"){t(e);return}if(i==="wireframe"&&this.topologyOverlay){this.syncTopologyOverlay(),this.shading.render(this.scene,"clay",()=>t(e),Qo);return}this.shading.render(this.scene,i,()=>t(e),Qo)}renderViewport(t=0){this.advanceLook(t),this.ensureComposer(),this.render(e=>{const i=this.composer;if(!i){this.renderer.render(this.scene,e);return}i.setMainScene(this.scene),i.setMainCamera(e),i.render(t)})}resize(t,e){this.renderWidth=Math.max(1,t),this.renderHeight=Math.max(1,e),this.composer?.setSize(this.renderWidth,this.renderHeight)}renderCapture(t,e){this.render(i=>{if(!e){t(i);return}const s=this.scene.background,r=this.renderer.getClearColor(new B),n=this.renderer.getClearAlpha();try{this.scene.background=null,this.renderer.setClearColor(0,0),t(i)}finally{this.scene.background=s,this.renderer.setClearColor(r,n)}})}captureImage(t=512){const e=typeof t=="number"?t:t.width,i=typeof t=="number"?t:t.height;if(!Number.isFinite(e)||e<1||!Number.isFinite(i)||i<1)return null;const s=Math.min(2048,Math.round(e)),r=Math.min(2048,Math.round(i)),n=s*2,a=r*2,l=new go(n,a,{type:Zh}),h=new go(n,a),d=this.renderer.getRenderTarget(),c=this.renderer.getPixelRatio(),p=this.viewport.camera,u=p.aspect;try{this.captureAspect=s/r;const f=typeof t=="number"?void 0:t.camera;f?this.cameraOverride=f:(p.aspect=s/r,p.updateProjectionMatrix()),this.renderer.setPixelRatio(1),this.renderer.setRenderTarget(l),this.renderCapture(x=>this.renderSolidForCapture(x,l,n,a),typeof t!="number"&&t.transparent===!0),Tl(typeof t!="number"&&t.transparent===!0).render(this.renderer,h,l,0,!1);const m=n*4,y=new Uint8Array(m*a);this.renderer.readRenderTargetPixels(h,0,0,n,a,y);const g=document.createElement("canvas");g.width=n,g.height=a;const _=g.getContext("2d");if(!_)return null;const M=_.createImageData(n,a);for(let x=0;x<a;x++){const b=(a-1-x)*m,P=x*m;M.data.set(y.subarray(b,b+m),P)}_.putImageData(M,0,0);const w=document.createElement("canvas");w.width=s,w.height=r;const C=w.getContext("2d");return C?(C.drawImage(g,0,0,s,r),w.toDataURL("image/png")):null}finally{this.captureAspect=null,this.cameraOverride=null,p.aspect=u,p.updateProjectionMatrix(),this.renderer.setRenderTarget(d),this.renderer.setPixelRatio(c),h.dispose(),l.dispose()}}dispose(){this.disposed=!0,this.settleFlight("closed"),this.viewport.orbitControls.removeEventListener("start",this.cancelLookForHuman),this.unsubscribeSelectionTheme(),this.clearDiagnosticPresentation(),this.clearBoneSelectionHighlight(),this.clearBoundsHelper(),this.clearSkeletonHelper(),this.selectionOutline?.selection.clear(),this.composer?.dispose(),this.sceneRenderPass=null,this.selectionOutline=null,this.selectionOutlinePass=null,this.composer=null,this.shading.dispose(),this.listeners.clear()}addHelper(t,e){t.name=`__object3d_document_${e}`,Rt(t,"editorHelper",!0),this.scene.add(t),this.helpers.push(t)}get selectionOutlineEnabled(){return this.selectionOutlineWanted}set selectionOutlineEnabled(t){t!==this.selectionOutlineWanted&&(this.selectionOutlineWanted=t,t?this.syncSelectionPresentation():(this.selectionOutline?.selection.clear(),this.syncComposerOutput()))}selectionOutlineWanted=!0;ensureComposer(){this.selectionOutlineWanted&&(this.composer||this.composerLoading||this.disposed||(this.composerLoading=!0,Ss(()=>import("./index-C5UECeSr.js"),__vite__mapDeps([12,1])).then(t=>{if(this.composerLoading=!1,this.disposed||this.composer)return;const e=this.camera(),i=new t.EffectComposer(this.renderer);this.sceneRenderPass=new t.RenderPass(this.scene,e),i.addPass(this.sceneRenderPass),this.selectionOutline=bu(t,this.scene,e,ze(this.renderer.domElement)),this.syncSelectionTheme(),jo(this.selectionOutline,this.selectedObjects),this.selectionOutlinePass=new t.EffectPass(e,this.selectionOutline),i.addPass(this.selectionOutlinePass),this.composer=i,this.syncComposerOutput(),i.setSize(this.renderWidth,this.renderHeight)}).catch(()=>{this.composerLoading=!1})))}renderSolidForCapture(t,e,i,s){const r=this.composer,n=(this.selectionOutline?.selection.size??0)>0;if(!r||!n||!this.sceneRenderPass||!this.selectionOutlinePass){this.renderer.render(this.scene,t);return}const a=this.renderWidth,l=this.renderHeight;try{this.sceneRenderPass.renderToScreen=!1,this.selectionOutlinePass.renderToScreen=!1,r.setSize(i,s,!1),this.sceneRenderPass.render(this.renderer,r.inputBuffer,r.outputBuffer,0),this.selectionOutlinePass.render(this.renderer,r.inputBuffer,e,0)}finally{r.setSize(a,l,!1),this.syncComposerOutput(),this.renderer.setRenderTarget(e)}}syncComposerOutput(){const t=(this.selectionOutline?.selection.size??0)>0;this.sceneRenderPass&&(this.sceneRenderPass.renderToScreen=!t),this.selectionOutlinePass&&(this.selectionOutlinePass.enabled=t,this.selectionOutlinePass.renderToScreen=t)}refreshSkeletonHelper(){const t=this.state.skeleton||this.boneSelectionHighlight!==null;t&&!this.skeletonHelper?(this.skeletonHelper=new Qh(this.root),op(this.skeletonHelper),this.scene.add(this.skeletonHelper)):t||this.clearSkeletonHelper()}clearSkeletonHelper(){this.skeletonHelper&&(this.skeletonHelper.removeFromParent(),this.skeletonHelper.dispose(),this.skeletonHelper=null)}clearBoneSelectionHighlight(){this.boneSelectionHighlight&&(this.boneSelectionHighlight.removeFromParent(),this.boneSelectionHighlight.dispose(),this.boneSelectionHighlight=null)}clearBoundsHelper(){if(!this.boundsHelper)return;const t=this.boundsHelper;this.boundsHelper=null;const e=this.helpers.indexOf(t);e>=0&&this.helpers.splice(e,1),t.removeFromParent(),t.geometry.dispose(),Array.isArray(t.material)?t.material.forEach(i=>{i.dispose()}):t.material.dispose()}frameBones(t){const e=new ie,i=new v;for(const l of t){e.expandByPoint(l.getWorldPosition(i)),l.parent?.isBone&&e.expandByPoint(l.parent.getWorldPosition(i));for(const h of l.children)h.isBone&&e.expandByPoint(h.getWorldPosition(i))}const s=e.getCenter(new v),r=Math.max(e.getSize(new v).length(),.2);e.expandByScalar(r*.35);const n=this.viewport.camera.position.clone().sub(this.viewport.orbitControls.target).normalize(),a=Xe(e,this.viewport.camera,n);this.viewport.setPose(s.clone().addScaledVector(n,a),s)}syncOrthographicCamera(){const t=this.viewport.camera,e=this.viewport.orbitControls.target,i=Math.max(t.position.distanceTo(e),.001),s=Math.max(i*Math.tan(Dt.degToRad(t.fov)/2),.001),r=Math.max(this.renderer.domElement.clientWidth,1),n=Math.max(this.renderer.domElement.clientHeight,1),a=this.captureAspect??r/n;this.orthographicCamera.left=-s*a,this.orthographicCamera.right=s*a,this.orthographicCamera.top=s,this.orthographicCamera.bottom=-s,this.orthographicCamera.near=t.near,this.orthographicCamera.far=t.far,this.orthographicCamera.position.copy(t.position),this.orthographicCamera.quaternion.copy(t.quaternion),this.orthographicCamera.up.copy(t.up),this.orthographicCamera.layers.mask=t.layers.mask,this.orthographicCamera.updateProjectionMatrix(),this.orthographicCamera.updateMatrixWorld(!0)}setLightingValues(t){for(const e of this.editorLights)e instanceof ba?e.intensity=t==="flat"?2:t==="outdoor"?1.15:1.7:e instanceof gr&&(e.intensity=t==="flat"?0:t==="outdoor"?2.2:2.4,e.color.set(16777215))}clearDiagnosticPresentation(){this.clearTopologyOverlay(),this.scene.overrideMaterial?.dispose(),this.scene.overrideMaterial=null;for(const t of this.helpers.splice(0)){t.removeFromParent();const e=t;e.geometry?.dispose();const i=e.material;Array.isArray(i)?i.forEach(s=>{s.dispose()}):i?.dispose()}}notify(){this.version++;for(const t of this.listeners)t()}}class fp{constructor(t){this.options=t}active=null;settling=!1;idleWaiters=new Set;begin(t){if(this.active||this.settling)return!1;try{const e=this.options.begin(t);return e?(this.active={pointerId:t.pointerId,gesture:e},!0):!1}catch(e){return this.options.reportError(e),!1}}update(t){if(!(!this.active||this.active.pointerId!==t.pointerId))try{this.active.gesture.update(t)}catch(e){this.cancelWithError(e)}}async commit(t){const e=this.take(t.pointerId);if(!e)return!1;this.settling=!0;try{return await e.commit(t),await this.options.persist(e.label),!0}catch(i){try{await e.cancel()}catch(s){return this.options.reportError({operationError:i,rollbackError:s}),!1}return this.options.reportError(i),!1}finally{this.settling=!1;for(const i of this.idleWaiters)i();this.idleWaiters.clear()}}async cancel(t){const e=this.take(t);if(!e)return!1;this.settling=!0;try{return await e.cancel(),!0}catch(i){return this.options.reportError(i),!1}finally{this.settling=!1;for(const i of this.idleWaiters)i();this.idleWaiters.clear()}}async settle(){this.active&&await this.cancel(),this.settling&&await new Promise(t=>this.idleWaiters.add(t))}hasActiveGesture(){return this.active!==null}take(t){if(!this.active||t!==void 0&&this.active.pointerId!==t)return null;const e=this.active.gesture;return this.active=null,e}async cancelWithError(t){const e=this.take();if(e){this.settling=!0;try{await e.cancel(),this.options.reportError(t)}catch(i){this.options.reportError({operationError:t,rollbackError:i})}finally{this.settling=!1;for(const i of this.idleWaiters)i();this.idleWaiters.clear()}}}}function Te(o){const t=xt(o,"authoringSubject");return t&&typeof t.label=="string"&&typeof t.kind=="string"?t:null}function Ko(o){return o.depthWrite===!1&&o.side===$h}function mp(o){const t=o.material;return t?Array.isArray(t)?t.length>0&&t.every(Ko):Ko(t):!1}function qa(o,t,e,i=()=>!1,s){const r=nc();if(!r)return[];const n=r.canvas.getBoundingClientRect();if(n.width<=0||n.height<=0||!Number.isFinite(t)||!Number.isFinite(e)||t<n.left||e<n.top||t>=n.left+n.width||e>=n.top+n.height)return[];const a=new Jt((t-n.left)/n.width*2-1,-((e-n.top)/n.height)*2+1),l=new Yt;l.layers.enableAll(),l.setFromCamera(a,r.camera);const h=new Set(s?.objects??o.objectMap.values()),d=[...h].filter(f=>{for(let m=f.parent;m;m=m.parent)if(h.has(m))return!1;return!0});for(const f of d)f.traverse(m=>{const y=m;y.isSkinnedMesh&&(y.boundingBox=null,y.boundingSphere=null)});const c=l.intersectObjects(d,!0),p=[],u=new Set;for(const f of c){if(ue(f.object)||mp(f.object))continue;let m=f.object,y=null;if(s)for(;m&&y===null;)y=s.idForObject3D(m),m=m.parent;else{const g=zl(m);y=g?Sn(g)??null:null}y!==null&&!i(y)&&!u.has(y)&&(u.add(y),p.push(y))}return gp(p,d,c.length,t,e),p}function gp(o,t,e,i,s){o.length>0||i===0&&s===0||console.info(`[viewport-pick] click selected nothing (candidates ${t.length}, rayHits ${e}, resolvedIds 0)`)}function yp(o,t,e,i=()=>!1,s){return qa(o,t,e,i,s)[0]??null}const ta={count:0,meshes:0,lights:0,instancedMeshes:0,instances:0};let ea=0;function _p(o){let t=0,e=0;for(const i of o.values()){const s=i.object;s.isInstancedMesh&&(t++,e+=typeof s.count=="number"?s.count:0)}return{instancedMeshes:t,instances:e}}function Za(o){let t=0,e=0;for(const i of o.values()){const s=i.object;s.isLight?e++:s.isMesh&&t++}return{count:o.size,meshes:t,lights:e,..._p(o)}}function vp(o,t){const e=new Map,i=[],s=t.skip??bs;t.begin?.(o);const r=(n,a,l,h)=>{if(s(n))return;const d=t.identify(n,{path:a,ownerId:l,ownedByAncestor:h});d!==null&&(pa(n,d),e.set(d,{object:n,id:d,parentId:l,childIds:[]}),l===null?i.push(d):e.get(l)?.childIds.push(d));const c=h||d!==null;n.children.forEach((p,u)=>{r(p,[...a,u],d??l,c)}),t.leave?.(n,d)};return o.children.forEach((n,a)=>{r(n,[a],null,!1)}),{nodes:e,rootIds:i,stats:Za(e)}}const xp="r3f:";function wp(o,t){return`${xp}${o}:${t}`}function Sp(o){return{project:t=>vp(t,{skip:e=>!!xt(e,"editorHelper")||e.isSkeletonHelper===!0,identify:(e,i)=>`source-object:${o}:${i.path.join(".")}`})}}function bp(o){const t=Te(o);return t?t.kind:or(o).length>0?"constraint-owner":Li(o)?"reflection-probe":o.isSkinnedMesh?"skinned-mesh":o.isBone?"bone":o.isLight?"light":o.isCamera?"camera":o.type==="Audio"||o.type==="PositionalAudio"||o.type==="AudioListener"?"audio":o.isMesh?"mesh":o.children.length>0?"group":"object"}function Mp(o,t){for(let e=o.parent;e!==null;e=e.parent)if(e===t)return!0;return!1}function ia(o,t){if(o===t)return!0;for(let e=o.parent;e!==null;e=e.parent)if(e===t)return!0;return!1}class Cp{constructor(t,e={}){this.identity=t,this.options=e}nodesById=new Map;objectsById=new Map;idsByObjectIndex=new Map;roots=[];walkStats=ta;project(t){if(!t)return this.nodesById=new Map,this.objectsById=new Map,this.idsByObjectIndex=new Map,this.roots=[],this.walkStats=ta,this.walkStats;const{nodes:e,rootIds:i,stats:s}=this.identity.project(t);return this.nodesById=e,this.objectsById=new Map([...e].map(([r,n])=>[r,n.object])),this.idsByObjectIndex=new Map([...e].map(([r,n])=>[n.object,r])),this.roots=i,this.walkStats=s,s}projectSubtrees(t,e){const i=this.identity.incremental;if(t===null||i?.kind!=="live-oid")return null;const s=e.filter((g,_)=>e.indexOf(g)===_&&!e.some(M=>M!==g&&Mp(g,M))),r=this.roots,n=new Set,a=new Set,l=new Set;for(const g of s)g.traverse(_=>{const M=this.idsByObjectIndex.get(_);if(M===void 0)return;const w=this.nodesById.get(M);w?.parentId!==null&&w?.parentId!==void 0&&l.add(w.parentId),n.add(M),this.nodesById.delete(M),this.objectsById.delete(M),this.idsByObjectIndex.delete(_)});const h=bs,d=(g,_)=>{const M=this.objectsById.get(g);return M===void 0||M===_},c=(g,_)=>{const M=Sn(g);if(M!==void 0&&d(M,g))return M;const w=Ol(g);if(w!==void 0){const C=wp(i.worldId,w);let x=0,b=co(C,x);for(;!d(b,g);)b=co(C,++x);return b}if(!_||xt(g,"authoringRoot")===!0){let C=`live:${i.worldId}:${ea++}`;for(;!d(C,g);)C=`live:${i.worldId}:${ea++}`;return C}return null},p=(g,_,M)=>{if(h(g))return;const w=c(g,M);w!==null&&(pa(g,w),this.nodesById.set(w,{object:g,id:w,parentId:_,childIds:[]}),this.objectsById.set(w,g),this.idsByObjectIndex.set(g,w),a.add(w),_!==null&&l.add(_));const C=w??_,x=M||w!==null;for(const b of g.children)p(b,C,x)};for(const g of s){if(!ia(g,t))continue;let _=g.parent,M=null;for(;_!==null&&_!==t;){const w=this.idsByObjectIndex.get(_);if(w!==void 0){M=w;break}_=_.parent}p(g,M,M!==null)}const u=g=>{const _=[],M=w=>{if(h(w))return;const C=this.idsByObjectIndex.get(w);if(C!==void 0){_.push(C);return}for(const x of w.children)M(x)};for(const w of g.children)M(w);return _};for(const g of l){const _=this.nodesById.get(g);_!==void 0&&_.childIds.splice(0,_.childIds.length,...u(_.object))}for(const g of a){const _=this.nodesById.get(g);_!==void 0&&_.childIds.splice(0,_.childIds.length,...u(_.object))}const f=u(t),m=this.roots.filter(g=>{const _=this.objectsById.get(g);return _!==void 0&&!ia(_,t)&&!n.has(g)});this.roots=[...f,...m],this.walkStats=Za(this.nodesById);const y=r.length!==this.roots.length||r.some((g,_)=>g!==this.roots[_]);return{removedIds:n,addedIds:a,changedParentIds:l,rootsChanged:y}}get nodes(){return this.nodesById}get objects(){return this.objectsById}get idsByObject(){return this.idsByObjectIndex}get rootIds(){return this.roots}get stats(){return this.walkStats}node(t){return this.nodesById.get(t)??null}rootNodes(){return this.roots.map(t=>this.nodesById.get(t)).filter(t=>t!==void 0)}objectOf(t){return this.objectsById.get(t)??null}idOf(t){return this.idsByObjectIndex.get(t)??null}childIdsOf(t){const e=[];for(const i of t){const s=this.idsByObjectIndex.get(i);s!==void 0&&e.push(s)}return e}objectMapSnapshot(){return new Map(this.objectsById)}pick(t,e,i,s){return yp(t,e,i,s,this.pickProjection())}candidates(t,e,i,s){return qa(t,e,i,s,this.pickProjection())}pickProjection(){if(this.options.pickScope!=="store-object-map")return{objects:this.objectsById.values(),idForObject3D:t=>this.idOf(t)}}}const sa=new v,ra=new wt,na=new v;function Pp(o){return o.matrixAutoUpdate===!1?(o.matrix.decompose(sa,ra,na),{position:sa.toArray(),quaternion:ra.toArray(),scale:na.toArray()}):{position:o.position.toArray(),quaternion:o.quaternion.toArray(),scale:o.scale.toArray()}}function Ap(o,t){return o.length===t.length&&o.every((e,i)=>e===t[i])}class Ep{constructor(t){this.options=t,this.selected=[...t.initial]}adopted=[];selected;current(){const t=[...this.options.store.selectedEntityIds].filter(this.options.owns);return Ap(t,this.adopted)||(this.adopted=t,this.selected=t,this.options.onChange?.(t)),[...this.selected]}publish(t){this.selected=[...t];const e=this.selected.filter(this.options.owns);this.adopted=e,this.options.onChange?.(e),this.options.store.selectMultiple(e)}}function Tp(o){if(!o)return{position:[0,0,0],rotation:[0,0,0,1],scale:[1,1,1]};const t=Pp(o);return{position:t.position,rotation:t.quaternion,scale:t.scale}}function ln(o){return o.type==="Object3D"&&o.name===""&&Te(o)===null&&o.userData.oid===void 0&&xt(o,"authoringInstance")===void 0&&xt(o,"authoringRoot")!==!0&&xt(o,"vgaiComponentRoot")===void 0}class zp{constructor(t){this.options=t,this.rootIdSet=new Set(t.rootIds)}rootIdSet;childObjects(t){return t.children.flatMap(e=>bs(e)?[]:ln(e)?this.childObjects(e):[e])}childIds(t){return this.options.projector.childIdsOf(this.childObjects(t))}rootObjects(){return this.options.rootIds.flatMap(t=>{const e=this.options.projector.objectOf(t);return e?ln(e)?this.childObjects(e):[e]:[]})}rootIds(){return this.options.projector.childIdsOf(this.rootObjects())}parentId(t){const{projector:e,scene:i,documentNodeId:s}=this.options,r=e.idOf(t);if(r!==null&&this.rootIdSet.has(r))return s;let n=t.parent;for(;n&&n!==i&&ln(n);)n=n.parent;return n&&n!==i?e.idOf(n)??s:s}node(t){const e=Te(t);return{id:this.options.projector.idOf(t),label:e?.label||t.name||t.type||"Object3D",role:"entity",kind:bp(t),...e?.typeLabel?{typeLabel:e.typeLabel}:{},parentId:this.parentId(t),childIds:this.childIds(t)}}}const oa=new WeakMap;function Op(o){let t=!1;if(o.traverse(s=>{xt(s,"gaussianSplat")&&(t=!0)}),t)return"Gaussian splat";const e=Il(o),i=Rl(o);return{static:"Static model",animated:"Animated model",rigged:"Rigged model",skinned:"Skinned model"}[kl(e,i)]}function aa(o){const t=o.material;return Array.isArray(t)?t[0]??null:t??null}function la(o){return o?.color??null}class Hn{constructor(t,e,i){if(this.store=t,this.scene=e,this.options=i,this.provenance=i.provenance??(i.documentKind==="asset"?{source:"document",label:"derived asset",detail:"Loaded from an ordinary project asset. Edit its source or import recipe."}:{source:"source-code",label:"source",detail:"Instantiated from project TypeScript. Edit source or exposed parameters, then rebuild."}),this.documentNodeId=`object3d-document:${i.documentId}`,this.projector=new Cp(Sp(i.documentId)),this.indexGraph(),i.hierarchyRoots&&new Set(i.hierarchyRoots).size!==i.hierarchyRoots.length)throw new Error(`Object3D document "${i.title}" declared the same hierarchy root twice.`);const s=new Set(i.hierarchyRoots??[]);for(const r of s){let n=r.parent;for(;n&&n!==e;){if(s.has(n))throw new Error(`Object3D document "${i.title}" declared nested hierarchy roots; roots must be non-overlapping.`);n=n.parent}}this.hierarchyRootIds=i.hierarchyRoots?i.hierarchyRoots.map(r=>{const n=this.idByObject.get(r);if(!n)throw new Error(`Object3D document "${i.title}" declared a hierarchy root outside its native graph.`);return n}):[...this.projector.rootIds],this.view=new zp({projector:this.projector,scene:e,documentNodeId:this.documentNodeId,rootIds:this.hierarchyRootIds}),this.selectionState=new Ep({store:t,owns:r=>this.byId.has(r),initial:[this.documentNodeId],onChange:r=>this.syncMarkedSelection(r)})}documentNodeId;projector;hierarchyRootIds;view;selectionState;markedSelection=new Set;capabilities={transform:!1,inspectorFields:!0,persist:!1};provenance;disposed=!1;dispose(){if(!this.disposed){this.disposed=!0;for(const t of this.watchedForStructure)t.removeEventListener("childadded",this.onStructureChanged),t.removeEventListener("childremoved",this.onStructureChanged);this.watchedForStructure=[]}}watchedForStructure=[];structureReindexQueued=!1;onStructureChanged=t=>{bs(t.child)||this.scheduleStructureReindex()};indexGraph(){this.projector.project(this.scene),this.watchStructure()}watchStructure(){const t=i=>i;for(const i of this.watchedForStructure)t(i).removeEventListener("childadded",this.onStructureChanged),t(i).removeEventListener("childremoved",this.onStructureChanged);this.watchedForStructure=[];const e=i=>{t(i).addEventListener("childadded",this.onStructureChanged),t(i).addEventListener("childremoved",this.onStructureChanged),this.watchedForStructure.push(i)};e(this.scene);for(const[,i]of this.byId)e(i)}scheduleStructureReindex(){this.disposed||this.structureReindexQueued||(this.structureReindexQueued=!0,queueMicrotask(()=>{if(this.structureReindexQueued=!1,this.disposed||(this.indexGraph(),this.store.scene!==this.scene))return;const t=this.store.objectMap;t.clear();for(const[i,s]of this.byId)t.set(i,s);const e=[...this.store.selectedEntityIds].filter(i=>i===this.documentNodeId||this.byId.has(i));e.length!==this.store.selectedEntityIds.size&&this.store.selectMultiple(e),this.store.notifyIngestObjectMapEdit()}))}get byId(){return this.projector.objects}get idByObject(){return this.projector.idsByObject}documentTypeLabel(){if(this.options.documentKind!=="asset")return;const t=this.scene.children.find(s=>this.idByObject.has(s))??null;if(!t)return;const e=oa.get(t);if(e!==void 0)return e;const i=Op(t);return oa.set(t,i),i}hierarchy={roots:()=>[this.hierarchy.node(this.documentNodeId)],node:t=>{if(t===this.documentNodeId){const i=this.documentTypeLabel();return{id:t,label:this.options.title,secondaryLabel:this.options.sourcePath,role:"document",kind:this.options.documentKind==="asset"?"model-asset":"three-source",...i?{typeLabel:i}:{},parentId:null,childIds:this.view.rootIds()}}const e=this.byId.get(t);return e?this.view.node(e):null},object3D:t=>this.byId.get(t)??null,idForObject3D:t=>this.idByObject.get(t)??null};selection={get:()=>this.selectionState.current(),set:t=>this.selectionState.publish(t.filter(e=>e===this.documentNodeId||this.byId.has(e)))};static READ_ONLY_REASON="This document shows what the module builds; its properties are read-only here. Edit the module.";readOnly=()=>({writable:!1,reason:Hn.READ_ONLY_REASON});transforms={get:t=>Tp(this.byId.get(t)??null),beginEdit:()=>{},apply:()=>{},endEdit:()=>{}};inspector={properties:t=>{if(t===this.documentNodeId)return this.options.audit===!1?[]:[{path:"name",label:"Name",type:"string",readonly:!0},{path:"source.path",label:"Source",type:"string",readonly:!0}];const e=this.byId.get(t);if(!e)return[];const i=Te(e);if(i?.fields)return i.fields().map(({value:l,...h})=>h);const s=[{path:"name",label:"Name",type:"string",readonly:!0},{path:"visible",label:"Visible",type:"boolean",readonly:!0},{path:"object.type",label:"Native type",type:"string",readonly:!0}],r=e;if(r.isMesh&&r.geometry){const l=r.geometry.getAttribute("position");s.push({path:"mesh.vertices",label:"Vertices",type:"number",readonly:!0,group:"Mesh"}),l&&s.push({path:"mesh.triangles",label:"Triangles",type:"number",readonly:!0,group:"Mesh"})}const n=aa(e);n&&(s.push({path:"material.type",label:"Material",type:"string",readonly:!0,group:"Material"}),la(n)&&s.push({path:"material.color",label:"Color",type:"color",readonly:!0,group:"Material"}));const a=e;return a.isSkinnedMesh&&a.skeleton&&s.push({path:"skin.bones",label:"Bones",type:"number",readonly:!0,group:"Skin"}),s},get:(t,e)=>{if(t===this.documentNodeId)return e==="name"?this.options.title:e==="source.path"?this.options.sourcePath:void 0;const i=this.byId.get(t);if(!i)return;const r=Te(i)?.fields?.().find(l=>l.path===e);if(r)return r.value();if(e==="name")return i.name||i.type;if(e==="visible")return i.visible;if(e==="object.type")return i.type;const n=i;if(e==="mesh.vertices")return n.geometry?.getAttribute("position")?.count??0;if(e==="mesh.triangles"){const l=n.geometry;return(l?.index?.count??l?.getAttribute("position")?.count??0)/3}const a=aa(i);if(e==="material.type")return a?.type;if(e==="material.color"){const l=la(a);return l?`#${l.getHexString()}`:void 0}if(e==="skin.bones")return i.skeleton?.bones.length??0},set:()=>{},editability:()=>this.readOnly()};subscribe(t){return this.store.subscribe(t)}get documentId(){return this.documentNodeId}get documentRootObject(){const t=this.hierarchy.node(this.documentNodeId)?.childIds[0];return t?this.byId.get(t)??null:null}syncMarkedSelection(t){const e=new Set(t.map(i=>this.byId.get(i)??null).filter(i=>i!==null).filter(i=>Te(i)?.selectionChanged!==void 0));for(const i of this.markedSelection)e.has(i)||Te(i)?.selectionChanged?.(!1);for(const i of e)this.markedSelection.has(i)||Te(i)?.selectionChanged?.(!0);this.markedSelection=e}}class Ip{constructor(t,e){this.frame=t,this.releaseRenderer=e,this.unsubscribeActivity=oc(()=>this.syncActivity())}rafId=0;running=!1;disposed=!1;active=!1;unsubscribeActivity;get isDisposed(){return this.disposed}get isRunning(){return this.running}setActive(t){this.disposed||(this.active=t,this.syncActivity())}syncActivity(){this.active&&kr()?this.start():this.stop()}redraw(){this.running&&!this.disposed&&kr()&&this.guardedFrame(performance.now())}dispose(){this.stop(),!this.disposed&&(this.disposed=!0,this.unsubscribeActivity(),this.releaseRenderer())}start(){this.disposed||this.running||(this.running=!0,this.guardedFrame(performance.now(),!0),!(!this.running||this.disposed)&&(this.rafId=requestAnimationFrame(this.tick)))}lastFrameFailure=null;guardedFrame(t,e=!1){try{this.frame(t,e),this.lastFrameFailure=null}catch(i){const s=i instanceof Error?i.message:String(i);s!==this.lastFrameFailure&&(this.lastFrameFailure=s,console.error("[document renderer] a frame threw; the loop continues:",i))}}stop(){this.running=!1,this.rafId!==0&&(cancelAnimationFrame(this.rafId),this.rafId=0)}tick=t=>{if(!(!this.running||this.disposed)){if(!kr()){this.stop();return}this.guardedFrame(t),!(!this.running||this.disposed)&&(this.rafId=requestAnimationFrame(this.tick))}}}const Rp=F.lazy(async()=>({default:(await Ss(()=>import("./stage-overlay-set-D6OOz1L9.js"),__vite__mapDeps([13,6,4,3,5,2,7,8,9,10,1,11,14,15,16,17,18,19]))).StageOverlaySet}));function kp(o){return T.jsx(F.Suspense,{fallback:null,children:T.jsx(Rp,{...o})})}const Fp=[.25,.5,1,2];function Bp(o,t){const e=Math.round(o*t);return`${o.toFixed(2)}s · f${e}`}function Np({transport:o}){const t=F.useSyncExternalStore(F.useCallback(c=>o?o.subscribe(c):()=>{},[o]),F.useCallback(()=>o?.snapshot()??null,[o]));if(!o||!t||t.activeSubject===null)return null;const e=t.driver==="world",i=t.playbackState==="playing",{start:s,end:r,fps:n,loop:a}=t.range,l=t.subjects.find(c=>c.id===t.activeSubject),h=t.subjects.length>1?t.subjects:null,d=o.activeClips();return T.jsxs("section",{"aria-label":"Transport","data-testid":"stage-transport-strip",style:{display:"flex",alignItems:"center",gap:"var(--vgai-space-2)",padding:"var(--vgai-space-1) var(--vgai-space-3)",borderTop:`var(--vgai-stroke-resting) solid ${Nt.boundary.default}`,background:Nt.surface.raised},children:[T.jsx(Ae,{size:"compact","aria-label":i?"Pause":"Play",disabled:e,onClick:()=>i?o.pause():o.play(),children:T.jsx(Ee,{icon:i?pe.transport.pause:pe.transport.play})}),T.jsx(Ae,{size:"compact","aria-label":"Stop",disabled:e,onClick:()=>o.stop(),children:T.jsx(Ee,{icon:pe.transport.stop})}),T.jsx(Fl,{"aria-label":"Playhead",type:"range",min:s,max:r,step:1/n,value:t.time,disabled:e,onChange:c=>o.seek(Number(c.target.value)),style:{flex:1}}),T.jsx(Xs,{as:"span",variant:"caption",children:Bp(t.time,n)}),h?T.jsx("select",{"aria-label":"Subject",value:t.activeSubject,disabled:e,onChange:c=>o.setActiveSubject(c.target.value),children:h.map(c=>T.jsx("option",{value:c.id,children:c.label},c.id))}):null,d?T.jsx("select",{"aria-label":"Clip",disabled:e,onChange:c=>o.setActiveClip(c.target.value),children:d.map(c=>T.jsx("option",{value:c.id,children:c.label},c.id))}):null,T.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"var(--vgai-space-1)"},children:[T.jsx("input",{type:"checkbox",checked:a,disabled:e,onChange:c=>o.setLoop(c.target.checked)}),T.jsx(Xs,{as:"span",variant:"caption",children:"Loop"})]}),T.jsx("select",{"aria-label":"Speed",value:String(t.timeScale),disabled:e,onChange:c=>o.setTimeScale(Number(c.target.value)),children:Fp.map(c=>T.jsxs("option",{value:String(c),children:[c,"×"]},c))}),e?T.jsx(Xs,{as:"span",variant:"caption",children:"The world is driving time (Play); pause the game to scrub"}):l?T.jsx(Xs,{as:"span",variant:"caption",children:l.label}):null]})}const wf=[.8,.5,-1],hn=new B(1975600),cn=new B(5004144);function Hp(){const o=typeof document>"u"?null:document.querySelector("[data-vgai-palette]");if(!o)return{bottom:hn.clone(),top:cn.clone()};const t=getComputedStyle(o),e=document.createElement("canvas");e.width=e.height=1;const i=e.getContext("2d"),s=(h,d)=>{const c=t.getPropertyValue(h).trim();if(!i||!c||!CSS.supports("color",c))return d.clone();i.fillStyle=d.getStyle(),i.fillRect(0,0,1,1),i.fillStyle=t.getPropertyValue("--vgai-surface-shell").trim(),i.fillRect(0,0,1,1),i.fillStyle=c,i.fillRect(0,0,1,1);const[p,u,f]=i.getImageData(0,0,1,1).data;return new B().setRGB(p/255,u/255,f/255,Ms)},r=s("--vgai-surface-panel",hn),n=s("--vgai-surface-raised",cn),a=r.lerp(hn,.25).lerp(new B(16777215),.03),l=n.lerp(cn,.25).lerp(new B(16777215),.04);return{bottom:a,top:l}}function Lp(o){if(typeof document>"u"||typeof MutationObserver>"u")return()=>{};const t=document.querySelector("[data-vgai-palette]");if(!t)return()=>{};const e=new MutationObserver(o);return e.observe(t,{attributes:!0,attributeFilter:["data-vgai-palette","data-vgai-material"]}),()=>e.disconnect()}function Qa(o=Hp()){const e=new Uint8Array(512),i=new B;for(let r=0;r<128;r++)i.copy(o.bottom).lerp(o.top,r/127).convertLinearToSRGB(),e[r*4]=Math.round(i.r*255),e[r*4+1]=Math.round(i.g*255),e[r*4+2]=Math.round(i.b*255),e[r*4+3]=255;const s=new Kh(e,1,128,tc);return s.colorSpace=Ms,s.magFilter=Ui,s.minFilter=Ui,s.needsUpdate=!0,s}function Dp(o){const t=Ie(o);if(t.isEmpty())return{size:50,centre:[0,0]};const e=Math.max(t.max.x-t.min.x,t.max.z-t.min.z);return{size:Math.min(Math.max(Math.ceil(e/10)*10+20,50),1e3),centre:[(t.min.x+t.max.x)/2,(t.min.z+t.max.z)/2]}}function Up(o){for(const t of[1,2,5,10])if(o/t<=60)return Math.round(o/t);return Math.round(o/10)}function Vp(o,t){const e=t/2,i=e*.55,s=e;o.onBeforeCompile=r=>{r.uniforms.uGridFadeStart={value:i},r.uniforms.uGridFadeEnd={value:s},r.vertexShader=r.vertexShader.replace("#include <common>",`#include <common>
1120
+ `,transparent:!0,depthWrite:!1,side:We}),i=new E(t,e);return i.name="editor-floor-grid",i}class Nn{setTransformMode(t){this._store.setTransformMode(t)}camera;orthographicCamera;orbitControls;transformControls;_auxRotateControls;_auxScaleControls;_activeGizmo;raycaster=(()=>{const t=new Yt;return t.layers.enableAll(),t})();grid;_boxHelpers=new Map;_unsubscribeSelectionTheme=()=>{};_constraintHelpers=new Map;_constraintControlRaycaster=(()=>{const t=new Yt;return t.layers.enableAll(),t})();_hoveredConstraintControl=null;_constraintControlPointerSession=!1;_reflectionProbeHelpers=new Map;_triggerVolumeHelpers=new Map;_cameraHelpers=new Map;_lightHelpers=new Map;_audioHelpers=new Map;_spatialHandleRoots=[];_spatialHandleMeshes=[];_spatialHandleRaycaster=(()=>{const t=new Yt;return t.layers.enableAll(),t})();_activeSpatialHandle=null;_hoveredSpatialHandle=null;_spatialHandleDragPlane=new fo;_spatialHandleDragOffset=new v;_spatialHandleDragPoint=new v;_orbitEnabledBeforeHandleDrag=!0;_transformEnabledBeforeHandleDrag=!0;_gizmoHelper;_editorAmbient;_editorDirLight;_lightRig;_scene;_contentBoundsBox=new ie;_contentBoundsAt=0;_renderer;_sparkRenderer=null;_sparkRendererLoading=!1;_sparkRendererFailed=!1;_lastSparkDiscoveryAt=Number.NEGATIVE_INFINITY;_disposed=!1;_editorObjects=[];_axisLines=null;_axesWanted=!1;_lookAxisHexes=null;_lookGridHex=null;_lookBackgroundHex=null;_lookToneMapping=null;_lookExposure=null;_lookGizmoSizePx=null;_lookAxisFrame=nn;_appliedAxisSigns=[1,1,1];_lookBoxSelect=null;_store;_objectMap=new Map;_canvas;_interactionElement;_onInteractionPointerUp;_onInteractionDblClick;_authoring;_pick;_standaloneAuthoring;_publishPickContext;_onlineAssetResolver;_onProjectionChange;_pointerDownPos=new Jt;_skipNextSync=!1;_marqueeActive=!1;_pointerSessionActive=!1;_marqueeDiv=null;_pointerDownButton=-1;_altDragOrbit=!1;_vcScene=new yr;_vcCamera;_vcClickTargets=[];_vcBalls=[];_vcStalks=[];_vcSize=mi;_vcMarginRight=Ku;_vcMarginTop=Ja;_chromeInsetPx=0;_vcDir=new v;_previewClearColor=new B;_cameraView=null;_projection="perspective";_pendingProjection=null;_viewportAspect=1;_orthographicHeight=10;_cameraViewMode=null;_orbitEnabledBeforeCameraView=!0;_orbitTargetBeforeCameraView=new v;_lastGizmoObjectMap=null;_lastGizmoSig="";_lastGizmoEpoch=-1;_threejsToolContextActive=!1;_threeSurfaceShowing=!1;_vcRaycaster=new Yt;_dropOverlay=null;_groundPlane=new fo(new v(0,1,0),0);_dragStartPos=new v;_dragStartQuat=new wt;_dragStartScale=new v;_attachedAuthoringId=null;_otherDragObjects=[];_allDragObjects=[];_preservedChildObjects=[];_activeTransformEditIds=[];_pivotDummy=new Je;_dummyIsPresentationAnchor=!1;_pivotPos=new v;_surfaceSnapRaycaster=new Yt;_surfaceSnapIndicator;_vertexSnapTargets=[];_vertexSnapIndicator;_vertexSnapThreshold=20;batchedRenderer;_helpers=new Map;_snapAnimating=!1;_snapStartTime=0;_snapDuration=400;_snapQ1=new wt;_snapQ2=new wt;_snapDist=0;_flyActive=!1;_orbitGesture=!1;_orbitGestureCounted=!1;_snapHold=!1;_flyKeys=new Set;_flySpeed=5;_flyEuler=new va(0,0,0,"YXZ");_rightMouseDown=!1;constructor(t,e,i,s=t,r={}){this._canvas=t,this._interactionElement=s,this._scene=e,this._renderer=r.renderer,this._store=i,this._authoring=r.authoring??(()=>Gs().activeAuthoring(this._store)),this._pick=r.pick,this._standaloneAuthoring=r.authoring!==void 0,this._publishPickContext=r.publishPickContext??!0,this._chromeInsetPx=r.chromeInsetPx??0,this._onlineAssetResolver=r.onlineAssetResolver,this._onProjectionChange=r.onProjectionChange,this.camera=new Ca(Zo(t.clientWidth/Math.max(1,t.clientHeight)),t.clientWidth/t.clientHeight,_o,vo),this.camera.position.copy(qu).multiplyScalar(17.32),this.camera.lookAt(0,0,0),this.camera.layers.enableAll(),this._viewportAspect=t.clientWidth/Math.max(1,t.clientHeight),this.orthographicCamera=new pi(-5,5,5,-5,_o,vo),this.orthographicCamera.layers.enableAll(),this._syncOrthographicFromPerspective(),this.grid=sp(400),this.grid.layers.set(X),e.add(this.grid);const n=new Tn;n.setPositions(ep()),n.setColors(new Array(fr*2*2*3).fill(1)),this._axisLines=new En(n,new zn({vertexColors:!0,linewidth:2,transparent:!0,opacity:1,depthWrite:!1,toneMapped:!1})),ip(this._axisLines.material,this.grid.material.uniforms.uGrazingFade),this._axisLines.visible=!1,this._axisLines.layers.set(X),e.add(this._axisLines),this._unsubscribeSelectionTheme=mr(t,()=>{const l=ze(t).visible;for(const h of this._boxHelpers.values())h instanceof en&&h.setColor(l);this._applyViewportLook(un(t)),this._lookGizmoSizePx=to(t),this._applyGizmoSize(),this._readLookStage(t)}),this._lightRig=r?.lightRig!==!1,this._editorAmbient=new Ma(16777215,.5),this._editorAmbient.layers.set(X),e.add(this._editorAmbient),this._editorDirLight=new gr(16777215,1),this._editorDirLight.position.set(10,20,10),this._editorDirLight.layers.set(X),e.add(this._editorDirLight),this._editorAmbient.visible=this._lightRig,this._editorDirLight.visible=this._lightRig,this.batchedRenderer=new kn,this.batchedRenderer.layers.set(X),e.add(this.batchedRenderer),s.addEventListener("wheel",this._onTrackpadWheel,{passive:!1}),this.orbitControls=new rc(this.camera,s),this.orbitControls.enableDamping=!0,this.orbitControls.dampingFactor=.1,this.orbitControls.mouseButtons={LEFT:-1,MIDDLE:Rr.PAN,RIGHT:Rr.ROTATE},this.transformControls=new Hr(this.camera,t),this._auxScaleControls=new Hr(this.camera,t),this._auxScaleControls.setMode("scale"),this._auxRotateControls=new Hr(this.camera,t),this._auxRotateControls.setMode("rotate"),this._activeGizmo=this.transformControls;const a=l=>{l.getRaycaster().layers.enableAll(),l.addEventListener("dragging-changed",h=>{const d=h.value;if(d?cc():dc(),this.orbitControls.enabled=!d,d){this._activeGizmo=l;for(const m of this._allGizmos())m!==l&&(m.enabled=!1);const c=l.object,p=l.mode==="translate"?"position":l.mode==="rotate"?"rotation":"scale",u=m=>this._authoring().transforms?.editability?.(m,p).writable??!0,f=this._attachedAuthoringId??(c&&this._authoringIdForObject(c))??"";if(c){if(this._dragStartPos.copy(c.position),this._dragStartQuat.copy(c.quaternion),this._dragStartScale.copy(c.scale),this._otherDragObjects=[],this._allDragObjects=[],this._pivotPos.copy(c.position),c===this._pivotDummy?null:this._authoringIdForObject(c))for(const _ of this._store.selectedEntityIds){if(_===f||!u(_))continue;const M=this._objectForAuthoringId(_);M&&this._otherDragObjects.push({id:_,obj:M,startPos:M.position.clone(),startQuat:M.quaternion.clone(),startScale:M.scale.clone()})}else for(const _ of this._store.selectedEntityIds){if(!u(_))continue;const M=this._objectForAuthoringId(_);M&&this._allDragObjects.push({id:_,obj:M,startPos:M.position.clone(),startQuat:M.quaternion.clone(),startScale:M.scale.clone()})}const y=c===this._pivotDummy?this._allDragObjects.map(({id:_})=>_):[f,...this._otherDragObjects.map(({id:_})=>_)];this._preservedChildObjects=this._preparePreservedChildren(y.filter(Boolean)),this._activeTransformEditIds=[...new Set([...y.filter(Boolean),...this._preservedChildObjects.map(({id:_})=>_)])];const g=this._authoring();for(const _ of this._activeTransformEditIds)ro(g,_)}}else this._surfaceSnapIndicator.visible=!1,this._vertexSnapIndicator.visible=!1,this.syncFromStore()}),l.addEventListener("objectChange",()=>{const h=l.object;if(!h)return;const d=l.mode,c=this._store.pivotMode==="individual-origins"||this._dummyIsPresentationAnchor,u=this._allDragObjects.length>0?this._allDragObjects:this._otherDragObjects;if(u.length>0){if(d==="translate"){const f=h.position.clone().sub(this._dragStartPos);for(const{obj:m,startPos:y}of u)m.position.copy(y).add(f)}else if(d==="rotate"){const f=h.quaternion.clone().multiply(this._dragStartQuat.clone().invert());if(c)for(const{obj:m,startQuat:y}of u)m.quaternion.copy(f).multiply(y);else for(const{obj:m,startPos:y,startQuat:g}of u){const _=y.clone().sub(this._pivotPos);_.applyQuaternion(f),m.position.copy(this._pivotPos).add(_),m.quaternion.copy(f).multiply(g)}}else if(d==="scale"){const f=new v(this._dragStartScale.x!==0?h.scale.x/this._dragStartScale.x:1,this._dragStartScale.y!==0?h.scale.y/this._dragStartScale.y:1,this._dragStartScale.z!==0?h.scale.z/this._dragStartScale.z:1);if(c)for(const{obj:m,startScale:y}of u)m.scale.copy(y).multiply(f);else for(const{obj:m,startPos:y,startScale:g}of u){const _=y.clone().sub(this._pivotPos);_.multiply(f),m.position.copy(this._pivotPos).add(_),m.scale.copy(g).multiply(f)}}}d==="translate"&&this._store.vertexSnapActive&&this._vertexSnapTargets.length>0?this._applyVertexSnap(h,u):d==="translate"&&this._store.snapToSurface&&this._applySurfaceSnap(h,u),this._restorePreservedChildren();for(const f of this._boxHelpers.values())"update"in f&&f.update();this._flushGizmoToStoreLive()}),l.addEventListener("mouseUp",()=>{this._flushGizmoToStore()})};a(this.transformControls),a(this._auxRotateControls),a(this._auxScaleControls),this._gizmoHelper=this.transformControls.getHelper(),this._gizmoHelper.traverse(l=>l.layers.set(X)),e.add(this._gizmoHelper);for(const l of[this._auxRotateControls,this._auxScaleControls]){const h=l.getHelper();h.traverse(d=>d.layers.set(X)),h.visible=!1,e.add(h)}this._pivotDummy.layers.set(X),e.add(this._pivotDummy),this._surfaceSnapIndicator=new E(new Uh(.08,.12,16),new Tt({color:65416,side:We,depthTest:!1})),this._surfaceSnapIndicator.rotation.x=-Math.PI/2,this._surfaceSnapIndicator.visible=!1,this._surfaceSnapIndicator.renderOrder=999,this._surfaceSnapIndicator.layers.set(X),e.add(this._surfaceSnapIndicator),this._vertexSnapIndicator=new E(new fe(1,8,8),new Tt({color:65450,depthTest:!1})),this._vertexSnapIndicator.visible=!1,this._vertexSnapIndicator.renderOrder=999,this._vertexSnapIndicator.layers.set(X),e.add(this._vertexSnapIndicator),this._patchGizmo(this._gizmoHelper),this._patchGizmo(this._auxRotateControls.getHelper()),this._patchGizmo(this._auxScaleControls.getHelper()),this._dropNegativeAxisHandles(this._gizmoHelper,["translate","scale"]),this._dropNegativeAxisHandles(this._auxScaleControls.getHelper(),["scale"]),this._patchCombinedScaleGizmo(this._auxScaleControls.getHelper()),this._lookGizmoSizePx=to(t),this._applyGizmoSize(),this._lookAxisFrame=eo(t)==="z"?qo:nn,this._lookBoxSelect=io(t),this._applyGizmoAxisFrame(),this._vcCamera=new pi(-1.5,1.5,1.5,-1.5,.1,10),this._initOrientationGizmo(),window.addEventListener("keydown",this._onFlyKeyDown),window.addEventListener("keyup",this._onFlyKeyUp),s.addEventListener("pointerdown",this._onFlyPointerDown),s.addEventListener("pointerup",this._onFlyPointerUp),s.addEventListener("pointermove",this._onFlyPointerMove),s.addEventListener("wheel",this._onFlyWheel,{passive:!1}),t.addEventListener("pointerdown",this._onAltOrbitStart,{capture:!0}),window.addEventListener("pointerup",this._onAltOrbitRelease,{capture:!0}),window.addEventListener("pointercancel",this._onAltOrbitRelease,{capture:!0}),this.orbitControls.addEventListener("change",()=>{this._orbitGesture&&!this._orbitGestureCounted&&(this._orbitGestureCounted=!0,Ru())}),window.addEventListener("keydown",this._onSnapHoldKey),window.addEventListener("keyup",this._onSnapHoldKey),t.addEventListener("pointerdown",this._onPointerDown),s.addEventListener("pointermove",this._onPointerMove),this._onInteractionPointerUp=l=>{(l.target===t||l.target===s||this._pointerSessionActive)&&this._onPointerUp(l)},s.addEventListener("pointerup",this._onInteractionPointerUp),this._onInteractionDblClick=l=>{(l.target===t||l.target===s)&&this._onDoubleClick(l)},s.addEventListener("dblclick",this._onInteractionDblClick),t.addEventListener("dragover",this._onDragOver),t.addEventListener("dragleave",this._onDragLeave),t.addEventListener("drop",this._onDrop),this._editorObjects=[this.grid,...this._axisLines?[this._axisLines]:[],this._editorAmbient,this._editorDirLight,this.batchedRenderer,this._gizmoHelper,this._auxRotateControls.getHelper(),this._auxScaleControls.getHelper(),this._pivotDummy,this._surfaceSnapIndicator,this._vertexSnapIndicator],this._publishPickContext&&this._installPickContext(this.camera)}setScene(t){if(t===this._scene)return;for(const i of this._editorObjects)i.removeFromParent(),t.add(i);for(const i of this._boxHelpers.values())i.removeFromParent(),t.add(i);for(const i of this._constraintHelpers.values())i.removeFromParent(),t.add(i);for(const i of this._reflectionProbeHelpers.values())i.removeFromParent(),t.add(i);for(const i of this._triggerVolumeHelpers.values())i.removeFromParent(),t.add(i);for(const{helper:i}of this._cameraHelpers.values())i.removeFromParent(),t.add(i);for(const i of this._spatialHandleRoots)i.removeFromParent(),t.add(i);this._scene=t,this._contentBoundsAt=0;const e=this._lightRig&&!this._store.isAdoptedSceneActive;this._editorAmbient.visible=e,this._editorDirLight.visible=e}get currentScene(){return this._scene}get renderCamera(){return this._cameraView??this.freeCamera}get freeCamera(){return this._projection==="orthographic"?this.orthographicCamera:this.camera}get projection(){return this._projection}_installPickContext(t){this._publishPickContext&&xo({camera:t,canvas:this._canvas,editorControls:{activate:(e,i)=>this._selectConstraintControlAt({clientX:e,clientY:i},!1),hover:(e,i)=>this._hoverConstraintControlAt({clientX:e,clientY:i}),clearHover:()=>this._clearConstraintControlHover()}})}setProjection(t){if(this._cameraView){this._pendingProjection=t;return}if(this._projection===t)return;t==="orthographic"?this._syncOrthographicFromPerspective():this._syncPerspectiveFromOrthographic(),this._projection=t;const e=this.freeCamera;this.orbitControls.object=e;for(const i of this._allGizmos())i.camera=e;this._applyGizmoSize(),this.orbitControls.update(),this._installPickContext(e),this._onProjectionChange?.(t)}_syncOrthographicFromPerspective(t=!1){const e=Math.max(.01,this.camera.position.distanceTo(this.orbitControls?.target??new v));t||(this._orthographicHeight=2*e*Math.tan(Dt.degToRad(this.camera.fov*.5))),this.orthographicCamera.position.copy(this.camera.position),this.orthographicCamera.quaternion.copy(this.camera.quaternion),this.orthographicCamera.up.copy(this.camera.up),this.orthographicCamera.zoom=1,this._applyOrthographicFrustum(),this.orthographicCamera.updateMatrixWorld(!0)}_syncPerspectiveFromOrthographic(){const e=this._orthographicHeight/Math.max(this.orthographicCamera.zoom,.01)/(2*Math.tan(Dt.degToRad(this.camera.fov*.5))),i=this.orthographicCamera.position.clone().sub(this.orbitControls.target).normalize();this.camera.position.copy(this.orbitControls.target).add(i.multiplyScalar(e)),this.camera.quaternion.copy(this.orthographicCamera.quaternion),this.camera.up.copy(this.orthographicCamera.up),this.camera.updateMatrixWorld(!0)}_applyOrthographicFrustum(){const t=this._orthographicHeight*.5,e=t*this._viewportAspect;this.orthographicCamera.left=-e,this.orthographicCamera.right=e,this.orthographicCamera.top=t,this.orthographicCamera.bottom=-t,this.orthographicCamera.updateProjectionMatrix()}get cameraViewMode(){return this._cameraViewMode}setCameraView(t,e){if(this.clearCameraView(),this._cameraView=t,this._cameraViewMode=e,this._orbitEnabledBeforeCameraView=this.orbitControls.enabled,this._orbitTargetBeforeCameraView.copy(this.orbitControls.target),e==="pilot"){const i=t.getWorldPosition(new v),s=t.getWorldDirection(new v),r=Math.max(1,this.freeCamera.position.distanceTo(this.orbitControls.target));this.orbitControls.object=t,this.orbitControls.target.copy(i).add(s.multiplyScalar(r)),this.orbitControls.enabled=!0,this.orbitControls.update()}else this.orbitControls.enabled=!1;this._publishPickContext&&this._installPickContext(t)}clearCameraView(){if(!this._cameraView)return;this._flyActive&&this._exitFlyMode(),this.orbitControls.object=this.freeCamera,this.orbitControls.target.copy(this._orbitTargetBeforeCameraView),this.orbitControls.enabled=this._orbitEnabledBeforeCameraView,this.orbitControls.update(),this._cameraView=null,this._cameraViewMode=null;const t=this._pendingProjection;this._pendingProjection=null,t&&t!==this._projection&&this.setProjection(t),this._publishPickContext&&this._installPickContext(this.freeCamera)}get objectMap(){return this._objectMap}set objectMap(t){this._objectMap=t}attach(t){const e=this._objectForAuthoringId(t);e&&(this._attachedAuthoringId=t,this._attachGizmosTo(e))}detach(){this._attachedAuthoringId=null,this._detachGizmos()}_objectForAuthoringId(t){const e=this._authoring();return e.hierarchy.node(t)===null?null:gl(e,this._objectMap,t)}_authoringIdForObject(t){return this._authoring().hierarchy.idForObject3D?.(t)??Sn(t)??null}_hasBoundableGeometry(t){return Da([t]).length>0}_makeDiagnosticBounds(t){if(this._hasBoundableGeometry(t))return new so(t,ze(this._canvas).visible);const e=new mt(ir,ir,ir),i=new An(e);e.dispose();const s=new Ze({color:new B(ze(this._canvas).visible),toneMapped:!1}),r=new Cs(i,s);return t.getWorldPosition(r.position),r.isBoxHelper=!0,r._entityObj=t,r}_syncBoxHelpers(){for(const e of this._boxHelpers.values())this._scene.remove(e),e.geometry.dispose(),e.material.dispose();this._boxHelpers.clear();const t=(e,i)=>{i.layers.set(X),this._scene.add(i),this._boxHelpers.set(e,i)};if(this._store.showHelpers&&this._store.helperVisibility.bounds)for(const e of this._objectMap.keys()){const i=this._objectForAuthoringId(e);i&&t(`bounds:${e}`,this._makeDiagnosticBounds(i))}for(const e of this._store.selectedEntityIds){const i=this._objectForAuthoringId(e);!i||this._hasBoundableGeometry(i)||this._standaloneAuthoring&&i.isBone||[...this._constraintHelpers.values()].some(s=>s.presents(i))||t(`selection:${e}`,new en(i,{fixedSize:ir,color:ze(this._canvas).visible}))}}_syncReflectionProbeHelpers(t=null){if(t===null){const e=new Map,i=new Set;for(const[s,r]of this._objectMap)!r||i.has(r)||!Li(r)||(i.add(r),e.set(s,r));for(const[s,r]of this._reflectionProbeHelpers)e.get(s)!==r.source&&(r.dispose(),this._reflectionProbeHelpers.delete(s));for(const[s,r]of e)this._ensureReflectionProbeHelper(s,r)}else{let e=!1;for(const i of t){const s=this._objectMap.get(i),r=s&&Li(s)?s:null,n=this._reflectionProbeHelpers.get(i);n&&n.source!==r&&(r===null&&(e=!0),n.dispose(),this._reflectionProbeHelpers.delete(i)),r&&![...this._reflectionProbeHelpers.values()].some(a=>a.source===r)&&this._ensureReflectionProbeHelper(i,r)}if(e){this._syncReflectionProbeHelpers();return}}for(const[e,i]of this._reflectionProbeHelpers)i.setSelected(this._store.selectedEntityIds.has(e)),i.visible=this._threejsToolContextActive&&this._store.showHelpers&&this._store.helperVisibility.reflectionProbes,i.update()}_ensureReflectionProbeHelper(t,e){if(this._reflectionProbeHelpers.has(t))return;const i=new jd(e);this._reflectionProbeHelpers.set(t,i),this._scene.add(i)}_syncTriggerVolumeHelpers(t=null){if(t===null){const i=new Map,s=new Set;for(const[r,n]of this._objectMap)!n||s.has(n)||!mn(n)||(s.add(n),i.set(r,n));for(const[r,n]of this._triggerVolumeHelpers)i.get(r)!==n.source&&this._disposeTriggerVolumeHelper(r,n);for(const[r,n]of i)this._ensureTriggerVolumeHelper(r,n)}else{let i=!1;for(const s of t){const r=this._objectMap.get(s),n=r&&mn(r)?r:null,a=this._triggerVolumeHelpers.get(s);a&&a.source!==n&&(n===null&&(i=!0),this._disposeTriggerVolumeHelper(s,a)),n&&![...this._triggerVolumeHelpers.values()].some(l=>l.source===n)&&this._ensureTriggerVolumeHelper(s,n)}if(i){this._syncTriggerVolumeHelpers();return}}const e=this._threeSurfaceShowing&&this._store.showHelpers&&this._store.helperVisibility.triggerVolumes;for(const[i,s]of this._triggerVolumeHelpers)s.setSelected(this._store.selectedEntityIds.has(i)),s.visible=e,s.update()}_ensureTriggerVolumeHelper(t,e){if(this._triggerVolumeHelpers.has(t))return;const i=new Ou(e);this._triggerVolumeHelpers.set(t,i),this._scene.add(i)}_disposeTriggerVolumeHelper(t,e){e.dispose(),this._triggerVolumeHelpers.delete(t)}_syncConstraintHelpers(t=null){if(t===null){const i=new Map,s=new Set;for(const[r,n]of this._objectMap)!n||s.has(n)||or(n).length===0||(s.add(n),i.set(r,n));for(const[r,n]of this._constraintHelpers)i.get(r)!==n.source&&(this._disposeConstraintHelper(n),this._constraintHelpers.delete(r));for(const[r,n]of i)this._ensureConstraintHelper(r,n)}else{let i=!1;for(const s of t){const r=this._objectMap.get(s),n=r&&or(r).length>0?r:null,a=this._constraintHelpers.get(s);a&&a.source!==n&&(n===null&&(i=!0),this._disposeConstraintHelper(a),this._constraintHelpers.delete(s)),n&&![...this._constraintHelpers.values()].some(l=>l.source===n)&&this._ensureConstraintHelper(s,n)}if(i){this._syncConstraintHelpers();return}}const e=new Set;for(const i of this._store.selectedEntityIds){const s=this._objectForAuthoringId(i);s&&e.add(s)}for(const[i,s]of this._constraintHelpers)s.setSelected(this._store.selectedEntityIds.has(i)),s.setSelectedObjects(e),s.visible=this._threejsToolContextActive&&this._store.showHelpers&&this._store.helperVisibility.constraints,s.update(this.camera)}_ensureConstraintHelper(t,e){if(this._constraintHelpers.has(t))return;const i=new Hd(e);this._constraintHelpers.set(t,i),this._scene.add(i)}_disposeConstraintHelper(t){this._hoveredConstraintControl?.helper===t&&(this._hoveredConstraintControl=null),t.dispose()}_raycastConstraintControl(t){const e=[];for(const n of this._constraintHelpers.values())n.visible&&e.push(...n.controlMeshes());if(e.length===0)return null;const i=this._canvas.getBoundingClientRect(),s=new Jt((t.clientX-i.left)/i.width*2-1,-((t.clientY-i.top)/i.height)*2+1);this._constraintControlRaycaster.setFromCamera(s,this.renderCamera);const r=this._constraintControlRaycaster.intersectObjects(e,!1)[0]?.object;if(!r)return null;for(const n of this._constraintHelpers.values()){const a=n.controlFor(r);if(a)return{helper:n,control:a}}return null}_updateConstraintControlHover(t){if(t.buttons&1)return this._constraintControlPointerSession;const e=this._hoverConstraintControlAt(t);return e?(this._hoveredSpatialHandle&&($r(this._hoveredSpatialHandle,!1),this._hoveredSpatialHandle=null),this._canvas.style.cursor=e,!0):(this._canvas.style.cursor="",!1)}_hoverConstraintControlAt(t){const e=this._raycastConstraintControl(t),i=this._hoveredConstraintControl;return e?(i?.mesh!==e.control.mesh&&(i&&i.helper.setHoveredControl(null),e.helper.setHoveredControl(e.control.mesh),this._hoveredConstraintControl={helper:e.helper,mesh:e.control.mesh}),this._authoringIdForObject(e.control.object)?"pointer":"not-allowed"):(this._clearConstraintControlHover(),null)}_clearConstraintControlHover(){this._hoveredConstraintControl?.helper.setHoveredControl(null),this._hoveredConstraintControl=null}_selectConstraintControlAt(t,e=!0){const i=this._raycastConstraintControl(t);if(!i)return!1;this._constraintControlPointerSession=e;const s=this._authoringIdForObject(i.control.object);if(s){const r=this._authoring();ki(r,[s],{intent:"exact"})||this._store.select(s),jt(`${i.control.label} selected — move it with the gizmo.`)}else jt(`${i.control.label} is a runtime-only constraint control.`);return!0}_syncCameraHelpers(t=null){if(t===null){const i=new Map;for(const[s,r]of this._objectMap){const n=this._nativeCamera(r);n&&i.set(s,n)}for(const[s,r]of this._cameraHelpers)i.get(s)!==r.source&&this._disposeCameraHelper(s,r);for(const[s,r]of i)this._ensureCameraHelper(s,r)}else{let i=!1;for(const s of t){const r=this._objectMap.get(s),n=r?this._nativeCamera(r):null,a=this._cameraHelpers.get(s);a&&a.source!==n&&(n===null&&(i=!0),this._disposeCameraHelper(s,a)),n&&![...this._cameraHelpers.values()].some(l=>l.source===n)&&this._ensureCameraHelper(s,n)}if(i){this._syncCameraHelpers();return}}const e=this._threeSurfaceShowing&&this._store.showHelpers&&this._store.helperVisibility.cameras;for(const i of this._cameraHelpers.values())i.helper.visible=e,i.helper.update()}_syncLightHelpers(t=null){if(t===null){const i=new Map;for(const[s,r]of this._objectMap){const n=this._nativeLight(r);n&&i.set(s,n)}for(const[s,r]of this._lightHelpers)i.get(s)!==r.source&&this._disposeLightHelper(s,r);for(const[s,r]of i)this._ensureLightHelper(s,r)}else{let i=!1;for(const s of t){const r=this._objectMap.get(s),n=r?this._nativeLight(r):null,a=this._lightHelpers.get(s);a&&a.source!==n&&(n===null&&(i=!0),this._disposeLightHelper(s,a)),n&&![...this._lightHelpers.values()].some(l=>l.source===n)&&this._ensureLightHelper(s,n)}if(i){this._syncLightHelpers();return}}const e=this._threeSurfaceShowing&&this._store.showHelpers&&this._store.helperVisibility.lights;for(const i of this._lightHelpers.values())i.helper.visible=e,i.helper.update?.()}_nativeLight(t){return t.isLight?t:null}_disposeLightHelper(t,e){e.helper.removeFromParent(),e.helper.dispose?.(),this._lightHelpers.delete(t)}_ensureLightHelper(t,e){if(this._lightHelpers.has(t))return;const i=.5;let s=null;const r=e;try{r.isDirectionalLight?s=new Vh(e,i):r.isPointLight?s=new jh(e,i):r.isSpotLight?s=new Gh(e):r.isHemisphereLight&&(s=new Xh(e,i))}catch{s=null}s&&(s.name=`Light helper: ${e.name||t}`,s.userData.editorOnly=!0,s.traverse(n=>n.layers.set(X)),s.layers.set(X),this._lightHelpers.set(t,{source:e,helper:s}),this._scene.add(s))}_syncAudioHelpers(t=null){if(t===null){const i=new Map;for(const[s,r]of this._objectMap){const n=this._nativeAudio(r);n&&i.set(s,n)}for(const[s,r]of this._audioHelpers)i.get(s)!==r.source&&this._disposeAudioHelper(s,r);for(const[s,r]of i)this._ensureAudioHelper(s,r)}else for(const i of t){const s=this._objectMap.get(i),r=s?this._nativeAudio(s):null,n=this._audioHelpers.get(i);n&&n.source!==r&&this._disposeAudioHelper(i,n),r&&![...this._audioHelpers.values()].some(a=>a.source===r)&&this._ensureAudioHelper(i,r)}const e=this._threeSurfaceShowing&&this._store.showHelpers&&this._store.helperVisibility.audio;for(const i of this._audioHelpers.values())i.helper.visible=e}_nativeAudio(t){const e=t.type;return e==="Audio"||e==="PositionalAudio"||e==="AudioListener"?t:null}_ensureAudioHelper(t,e){if(this._audioHelpers.has(t))return;const i=new kt,s=e.type==="AudioListener"?8377599:16763274,r=new E(new Ve(.16),new Tt({color:s,wireframe:!0,depthTest:!1}));i.add(r),i.name=`Audio helper: ${e.name||t}`,i.userData.editorOnly=!0,i.traverse(n=>n.layers.set(X)),i.layers.set(X),e.add(i),this._audioHelpers.set(t,{source:e,helper:i})}_disposeAudioHelper(t,e){e.helper.traverse(i=>{const s=i;s.geometry?.dispose?.(),s.material?.dispose?.()}),e.helper.removeFromParent(),this._audioHelpers.delete(t)}_disposeCameraHelper(t,e){e.helper.removeFromParent(),e.helper.dispose(),this._cameraHelpers.delete(t)}_ensureCameraHelper(t,e){if(this._cameraHelpers.has(t))return;let i;try{i=new Wh(e)}catch(s){this._refuseCameraOverlay(t,e,s);return}i.name=`Camera frustum: ${e.name||t}`,i.userData.editorOnly=!0,i.layers.set(X),this._cameraHelpers.set(t,{source:e,helper:i}),this._scene.add(i)}_refusedCameraOverlays=new Set;_refuseCameraOverlay(t,e,i){this._refusedCameraOverlays.has(t)||(this._refusedCameraOverlays.add(t),Fi.warn(`Helpers → Cameras draws no frustum for "${e.name||e.type}": ${i instanceof Error?i.message:String(i)}. This world's camera was constructed by the GAME's own copy of three, and \`THREE.CameraHelper\` is the editor's class reading fields off it that that revision does not define. Every other camera capability (framing, selection, inspection) is unaffected. It closes when the game resolves \`three\` to the host's instance — a bare, un-rewritten \`import 'three'\` in its own source.`,"authoring"))}_nativeCamera(t){if(t.isCamera)return t;const e=xt(t,"_camera");return e?.isCamera?e:null}_syncSpatialHandles(){Vo(this._spatialHandleRoots),this._spatialHandleRoots=[],this._spatialHandleMeshes=[],this._hoveredSpatialHandle=null;const t=Ir(this._authoring());if(!t||!this._threejsToolContextActive||!this._store.showHelpers)return;const e=this._store.helperVisibility;for(const i of this._store.selectedEntityIds){const s=t.layers(i).filter(n=>n.category in e?e[n.category]:!0),r=lu(i,s);for(const n of r.handles)Uo(n,this.renderCamera);for(const n of r.roots)this._scene.add(n);this._spatialHandleRoots.push(...r.roots),this._spatialHandleMeshes.push(...r.handles)}}_raycastSpatialHandle(t){if(this._spatialHandleMeshes.length===0)return null;const e=this._canvas.getBoundingClientRect(),i=new Jt((t.clientX-e.left)/e.width*2-1,-((t.clientY-e.top)/e.height)*2+1);return this._spatialHandleRaycaster.setFromCamera(i,this.renderCamera),this._spatialHandleRaycaster.intersectObjects(this._spatialHandleMeshes,!1)[0]?.object??null}_spatialHandleWorldPoint(t){const e=this._canvas.getBoundingClientRect(),i=new Jt((t.clientX-e.left)/e.width*2-1,-((t.clientY-e.top)/e.height)*2+1);this._spatialHandleRaycaster.setFromCamera(i,this.renderCamera);const s=new v;return this._spatialHandleRaycaster.ray.intersectPlane(this._spatialHandleDragPlane,s)?s.add(this._spatialHandleDragOffset):null}_finishSpatialHandleDrag(t){const e=this._activeSpatialHandle;this._activeSpatialHandle=null,this.orbitControls.enabled=this._orbitEnabledBeforeHandleDrag,this.transformControls.enabled=this._transformEnabledBeforeHandleDrag,this.syncFromStore(),this._canvas.style.cursor="",t&&e&&Ir(this._authoring())?.commit(e.nodeId,e.handle.id,[this._spatialHandleDragPoint.x,this._spatialHandleDragPoint.y,this._spatialHandleDragPoint.z])}_updateSpatialHandleDrag(t){const e=this._activeSpatialHandle;if(!e)return!1;const i=this._spatialHandleWorldPoint(t);return i&&(this._spatialHandleDragPoint.copy(i),Ir(this._authoring())?.preview(e.nodeId,e.handle.id,[i.x,i.y,i.z]),this._syncSpatialHandles(),this._canvas.style.cursor="grabbing"),!0}_updateSpatialHandleHover(t){if(t.buttons&1||this._spatialHandleMeshes.length===0)return;const e=this._raycastSpatialHandle(t);if(e===this._hoveredSpatialHandle)return;if(this._hoveredSpatialHandle&&$r(this._hoveredSpatialHandle,!1),this._hoveredSpatialHandle=e,!e){this._canvas.style.cursor="";return}$r(e,!0);const i=Do(e);this._canvas.style.cursor=i?.handle.writable?"grab":"not-allowed"}_updateEditorHandleInteraction(t){return this._updateSpatialHandleDrag(t)||this._updateConstraintControlHover(t)}_previewInfrastructure(){return[this.grid,...this._axisLines?[this._axisLines]:[],this._gizmoHelper,this._auxRotateControls.getHelper(),this._auxScaleControls.getHelper(),...this._boxHelpers.values(),...this._constraintHelpers.values(),...this._reflectionProbeHelpers.values(),...this._triggerVolumeHelpers.values(),...[...this._cameraHelpers.values()].map(({helper:t})=>t),...this._spatialHandleRoots]}_suspendPreviewInfrastructure(){const t=this._previewInfrastructure().map(e=>[e,e.visible]);for(const[e]of t)e.visible=!1;return()=>{for(const[e,i]of t)e.visible=i}}_allGizmos(){return[this.transformControls,this._auxRotateControls,this._auxScaleControls]}_anyGizmoDragging(){return this._allGizmos().some(t=>t.dragging)}_attachGizmosTo(t){this.transformControls.attach(t),this._auxRotateControls.attach(t),this._auxScaleControls.attach(t)}_detachGizmos(){for(const t of this._allGizmos())t.detach()}syncFromStore(){this._gizmoHelper.traverse(x=>x.layers.set(X));const t=this._store.transformMode,i=t==="combined"||t==="select"?"translate":t;this.transformControls.mode!==i&&this.transformControls.setMode(i),this._applySnapToGizmos();for(const x of this._allGizmos())x.setSpace(this._store.transformSpace);const s=Gs(),r=this._authoring(),n=s.toolOwner(r,this._store.selectedEntityIds);this._threejsToolContextActive=(this._standaloneAuthoring||s.toolOwnerPainted(this._store,n))&&n?.kind==="three";const a=this._standaloneAuthoring||s.threeSurfaceShowing(this._store,r);this._threeSurfaceShowing=a,this.grid.visible=this._store.showGrid&&a,this._axisLines&&(this._axisLines.visible=this.grid.visible&&this._axesWanted);const l=this._store.helperVisibility,h=this._standaloneAuthoring?null:s.threeViewportRootId(this._store),d=h!==null&&Al(h);d&&s.applyRootHiddenVisibility(this._objectMap,h),d&&s.suppressRootEnvironment(this._scene);const c=this._store.gizmoEpoch,p=`${this._store.showHelpers}|${JSON.stringify(l)}|${h??""}|${d}|${this._threejsToolContextActive}`,u=this._objectMap!==this._lastGizmoObjectMap,f=p!==this._lastGizmoSig,m=u?null:this._store.ingestObjectMapMembershipChangesSince(this._lastGizmoEpoch),y=u||f||m===null?null:m.changedIds,g=y===null||y.size>0;if(this._lastGizmoObjectMap=this._objectMap,this._lastGizmoSig=p,this._lastGizmoEpoch=c,g){s.applyRootHiddenVisibility(this._objectMap,h);const x=y===null?ku(this._objectMap):Fu(this._objectMap,y);for(const b of x)b.traverse(P=>{if(xt(P,"editorIcon")){P.visible=this._store.showHelpers;return}if(!xt(P,"editorHelper"))return;const A=xt(P,"editorHelperType");if(A==="skeletons"){P.visible=this._store.showHelpers&&(l.skeletons||!!xt(P,"skeletonEnabled"));return}A&&A in l?P.visible=this._store.showHelpers&&l[A]:P.visible=this._store.showHelpers});for(const[b,P]of this._helpers)P.visible=this._store.showHelpers&&(!(b in l)||l[b]);this._syncCameraHelpers(y),this._syncLightHelpers(y)}this._syncAudioHelpers(y),this._syncReflectionProbeHelpers(y),this._syncTriggerVolumeHelpers(y),this._syncConstraintHelpers(y);const _=this._threejsToolContextActive&&r.capabilities.transform&&t!=="select"?this._store.selectedEntityId:null,M=t==="translate"||t==="combined"?"position":t==="rotate"?"rotation":"scale",C=_?t==="combined"?(x=>["position","rotation","scale"].some(b=>r.transforms?.editability?.(x,b).writable??!0))(_):r.transforms?.editability?.(_,M).writable??!0:!1;if(_&&C){if(!this._anyGizmoDragging())if(this._store.pivotMode==="median-point"&&this._store.selectedEntityIds.size>1){const x=new v;let b=0;for(const P of this._store.selectedEntityIds){if(!(r.transforms?.editability?.(P,M).writable??!0))continue;const A=this._objectForAuthoringId(P);A&&(x.add(A.getWorldPosition(Lu)),b++)}b>0&&x.divideScalar(b),this._pivotDummy.position.copy(x),this._pivotDummy.quaternion.identity(),this._pivotDummy.scale.set(1,1,1),this._attachedAuthoringId=null,this._dummyIsPresentationAnchor=!1,this._attachGizmosTo(this._pivotDummy)}else{const x=this._objectForAuthoringId(_),b=xt(x,"pivot"),P=b&&(b[0]!==0||b[1]!==0||b[2]!==0),A=P?null:this._centreAnchorFor(x);if(A&&x)this._pivotDummy.position.copy(A),this._pivotDummy.quaternion.copy(x.getWorldQuaternion(rn)),this._pivotDummy.scale.copy(x.getWorldScale(Yo)),this._attachedAuthoringId=_,this._dummyIsPresentationAnchor=!0,this._attachGizmosTo(this._pivotDummy);else if(P&&x){const N=new v(b[0],b[1],b[2]);N.applyQuaternion(x.getWorldQuaternion(rn)),this._pivotDummy.position.copy(x.getWorldPosition(Jo)).add(N),this._pivotDummy.quaternion.copy(rn),this._pivotDummy.scale.copy(x.getWorldScale(Yo)),this._attachedAuthoringId=_,this._dummyIsPresentationAnchor=!1,this._attachGizmosTo(this._pivotDummy)}else this._dummyIsPresentationAnchor=!1,this.attach(_)}}else this.detach();this._syncBoxHelpers(),this._syncSpatialHandles(),this._syncCombinedGizmoHalves()}_applySnapToGizmos(){const t=this._store.snapEnabled||this._snapHold,e=this._store.snapValues;for(const i of this._allGizmos())i.setTranslationSnap(t?e.translate:null),i.setRotationSnap(t?Dt.degToRad(e.rotate):null),i.setScaleSnap(t?e.scale:null)}_onAltOrbitStart=t=>{t.altKey&&t.button===0&&(this._altDragOrbit=!0,this.orbitControls.mouseButtons.LEFT=Rr.ROTATE),(t.button===2||t.altKey&&t.button===0)&&(this._orbitGesture=!0)};_onAltOrbitRelease=()=>{this._orbitGesture=!1,this._orbitGestureCounted=!1,this._altDragOrbit&&(this._altDragOrbit=!1,this.orbitControls.mouseButtons.LEFT=-1)};_onSnapHoldKey=t=>{const e=t.ctrlKey||t.metaKey;if(e!==this._snapHold&&(this._snapHold=e,this._applySnapToGizmos(),e&&this._anyGizmoDragging()&&!this._store.snapEnabled)){const{translate:i,rotate:s,scale:r}=this._store.snapValues;jt(`Snapping while held: ${i} units · ${s}° · ×${r}`)}};_syncCombinedGizmoHalves(){if(this._anyGizmoDragging())return;const t=this._store.transformMode==="combined",e=this._attachedAuthoringId,i=this._authoring().transforms?.editability,s=h=>e===null||(i?.(e,h).writable??!0),r=t&&this._auxRotateControls.object!==void 0&&s("rotation"),n=t&&this._auxScaleControls.object!==void 0&&s("scale");this._auxRotateControls.enabled=r,this._auxScaleControls.enabled=n;const a=this._auxRotateControls.getHelper(),l=this._auxScaleControls.getHelper();a.visible=r,l.visible=n;for(const h of[a,l])h.traverse(d=>d.layers.set(X));this.transformControls.enabled=!0}moveGizmosTo(t){const e=this._gizmoObjects();for(const i of e)t.add(i)}restoreGizmos(){const t=this._gizmoObjects();for(const e of t)this._scene.add(e)}_gizmoObjects(){return[this.grid,...this._axisLines?[this._axisLines]:[],this._editorAmbient,this._editorDirLight,this.batchedRenderer,this._gizmoHelper,this._auxRotateControls.getHelper(),this._auxScaleControls.getHelper(),this._pivotDummy,this._surfaceSnapIndicator,...[...this._cameraHelpers.values()].map(({helper:t})=>t),...this._spatialHandleRoots]}_contentBounds(t=!1){const e=performance.now(),i=this._contentBoundsAt===0||e-this._contentBoundsAt>Bu;if(t||i){this._contentBoundsBox.makeEmpty();for(const s of this._scene.children)ue(s)||yl(this._contentBoundsBox,s);this._contentBoundsAt=e}return this._contentBoundsBox}_measureContentBounds(){const t=[];for(const e of this._scene.children)ue(e)||_l(e,t);this._contentBoundsBox.makeEmpty();for(const e of t)this._contentBoundsBox.union(e);return this._contentBoundsAt=performance.now(),t}_updateClipPlanes(){const t=this._contentBounds();let e=0,i=0;t.isEmpty()||(t.getBoundingSphere(sn),e=this.freeCamera.position.distanceTo(sn.center),i=sn.radius);const{near:s,far:r}=sc(e,i);s===this.camera.near&&r===this.camera.far||(this.camera.near=s,this.camera.far=r,this.camera.updateProjectionMatrix(),this.orthographicCamera.near=s,this.orthographicCamera.far=r,this.orthographicCamera.updateProjectionMatrix())}seedFromGameCamera(t){const e=No(this._measureContentBounds()),i=qd(t,e);if(!i)return!1;const s=this.camera.position.clone(),r=this.orbitControls.target.clone();this.camera.position.copy(i.position),this.orbitControls.target.copy(i.target),this.camera.lookAt(this.orbitControls.target),this.camera.updateMatrixWorld(!0);const n=this._scene.children.filter(a=>!ue(a));return Kd(this.camera,n,i.position.distanceTo(i.target))?(this._updateClipPlanes(),this.orbitControls.update(),!0):(this.camera.position.copy(s),this.orbitControls.target.copy(r),this.camera.lookAt(this.orbitControls.target),this.camera.updateMatrixWorld(!0),!1)}focusOnScene(){const t=No(this._measureContentBounds());if(t.isEmpty())return!1;const e=t.getCenter(new v),i=this.camera.position.clone().sub(this.orbitControls.target).normalize(),s=Xe(t,this.camera,i);return Number.isFinite(s)?(this.camera.position.copy(e).add(i.multiplyScalar(s)),this.orbitControls.target.copy(e),this._orthographicHeight=Math.max(t.getSize(new v).y,t.getSize(new v).x/this._viewportAspect)*1.15,this._syncOrthographicFromPerspective(!0),this._updateClipPlanes(),!0):!1}focusOn(t){const e=this._contentOrProbeBounds(t),i=e.getCenter(new v),s=this.camera.position.clone().sub(this.orbitControls.target).normalize(),r=Xe(e,this.camera,s);this.camera.position.copy(i).add(s.multiplyScalar(r)),this.orbitControls.target.copy(i);const n=e.getSize(new v);this._orthographicHeight=Math.max(n.y,n.x/this._viewportAspect,.01)*1.15,this._syncOrthographicFromPerspective(!0)}activateVertexSnap(){this._vertexSnapTargets=this._collectVertices(this._store.selectedEntityIds)}deactivateVertexSnap(){this._vertexSnapTargets=[],this._vertexSnapIndicator.visible=!1}focusOnMultiple(t){if(t.length===0)return;if(t.length===1){this.focusOn(t[0]);return}const e=new ie;for(const a of t)e.union(this._contentOrProbeBounds(a));const i=e.getCenter(new v),s=this.camera.position.clone().sub(this.orbitControls.target).normalize(),r=Xe(e,this.camera,s);this.camera.position.copy(i).add(s.multiplyScalar(r)),this.orbitControls.target.copy(i);const n=e.getSize(new v);this._orthographicHeight=Math.max(n.y,n.x/this._viewportAspect,.01)*1.15,this._syncOrthographicFromPerspective(!0)}_centreAnchorFor(t){const e=this._store.gizmoAnchor;if(!t||e==="pivot"||e==="auto"&&vl(t)===0)return null;const i=Ie(t);if(i.isEmpty()||e==="auto"&&!xl(t,i)?.worldAnchored)return null;const s=i.getCenter(new v);return t.updateWorldMatrix(!0,!1),s.distanceToSquared(t.getWorldPosition(Jo))<Du?null:s}_contentOrProbeBounds(t){const e=Li(t);if(!e)return Ie(t);const i=e.config,[s,r,n]=i.size,a=i.shape==="sphere"?new v(1,1,1).multiplyScalar(Math.max(.01,i.radius)):new v(Math.max(.01,s),Math.max(.01,r),Math.max(.01,n)).multiplyScalar(.5);return t.updateWorldMatrix(!0,!1),new ie(a.clone().negate(),a).applyMatrix4(t.matrixWorld)}setHelper(t,e){const i=this._helpers.get(t);if(i&&(this._scene.remove(i),this._helpers.delete(t)),!e)return;Rt(e,"editorHelper",!0),Rt(e,"editorHelperType",t);const s=this._store.helperVisibility;e.visible=this._store.showHelpers&&(!(t in s)||s[t]),this._scene.add(e),this._helpers.set(t,e)}setViewPreset(t){this._projection==="orthographic"&&this.setProjection("perspective");const e=this.orbitControls.target.clone(),i=this.camera.position.distanceTo(e),s=new v;switch(t){case"top":s.set(0,1,0);break;case"front":s.set(0,0,1);break;case"right":s.set(1,0,0);break;case"perspective":s.set(1,1,1).normalize();break}this.camera.position.copy(e).add(s.multiplyScalar(i)),this.camera.lookAt(e),t!=="perspective"&&this.setProjection("orthographic"),this.orbitControls.update()}setPose(t,e,i){this.setProjection("perspective"),this.camera.position.set(t.x,t.y,t.z),this.orbitControls.target.set(e.x,e.y,e.z),this.camera.lookAt(this.orbitControls.target),i!==void 0&&(this.camera.fov=i,this.camera.updateProjectionMatrix()),this.orbitControls.update()}resize(t,e){this._viewportAspect=Math.max(1,t)/Math.max(1,e),this.camera.aspect=this._viewportAspect,this.camera.fov=Zo(this._viewportAspect),this.camera.updateProjectionMatrix(),this._applyOrthographicFrustum(),this._applyGizmoSize()}update(t=0){this._ensureSparkRenderer(),this._syncLookBackground();const e=this.transformControls.object;if(e&&e!==this._pivotDummy&&!e.parent&&(this._detachGizmos(),this.syncFromStore()),this._updateFlyCamera(t),this.orbitControls.update(),this._snapAnimating){const i=performance.now()-this._snapStartTime;let s=Math.min(i/this._snapDuration,1);s=s<.5?4*s*s*s:1-(-2*s+2)**3/2;const r=new wt().slerpQuaternions(this._snapQ1,this._snapQ2,s),n=new v(0,0,1).applyQuaternion(r);this.freeCamera.position.copy(this.orbitControls.target).add(n.multiplyScalar(this._snapDist)),this.freeCamera.lookAt(this.orbitControls.target),s>=1&&(this._snapAnimating=!1)}for(const i of this._boxHelpers.values()){if(i instanceof en){i.updateIfNeeded();continue}const s=i;s._entityObj?s._entityObj.getWorldPosition(i.position):i instanceof so&&i.update()}for(const i of this._constraintHelpers.values())i.update(this.camera);for(const i of this._reflectionProbeHelpers.values())i.update();for(const i of this._triggerVolumeHelpers.values())i.update();for(const{helper:i}of this._cameraHelpers.values())i.update();for(const i of this._spatialHandleMeshes)Uo(i,this.renderCamera);this._enforceLodForcedLevels(),this._updateClipPlanes()}_enforceLodForcedLevels(){const t=new Set(this._objectMap.values());for(const[e,i]of this._store.lodForcedLevels){const s=this._objectMap.get(e),r=s?wl(s,a=>t.has(a)):null;if(!r||r.levels.length===0)continue;r.autoUpdate=!1;const n=Math.min(Math.max(i,0),r.levels.length-1);for(let a=0;a<r.levels.length;a++)r.levels[a].object.visible=a===n}}renderWithInfrastructure(t){const e=this._sparkRenderer,i=this._cameraView?this._suspendPreviewInfrastructure():null;e&&this._scene.add(e);try{t()}finally{e?.removeFromParent(),i?.()}}renderViewCube(t){if(!this._threeSurfaceShowing||this._cameraView)return;const e=t.domElement.clientWidth,i=t.domElement.clientHeight,s=this._vcSize,r=this._vcDir.subVectors(this.freeCamera.position,this.orbitControls.target).normalize();this._vcCamera.position.copy(r.multiplyScalar(4)),this._vcCamera.up.copy(this.freeCamera.up),this._vcCamera.lookAt(0,0,0),this._syncOrientationGizmoDepth();const n=e-s-this._vcMarginRight-this._chromeInsetPx,a=i-s-this._vcMarginTop-this._chromeInsetPx,l=t.autoClear;try{t.setScissorTest(!0),t.setViewport(n,a,s,s),t.setScissor(n,a,s,s),t.clear(!1,!0,!1),t.autoClear=!1,t.render(this._vcScene,this._vcCamera)}finally{t.autoClear=l,t.setScissorTest(!1),t.setViewport(0,0,e,i)}}renderCameraPreview(t,e,i){if(!e||!i||this._cameraView)return;const s=t.domElement.clientWidth,r=t.domElement.clientHeight,n=t.domElement.getBoundingClientRect(),a=i.getBoundingClientRect(),l=Math.round(a.left-n.left),h=Math.round(n.bottom-a.bottom),d=Math.max(1,Math.round(a.width)),c=Math.max(1,Math.round(a.height));if(l>=s||h>=r||l+d<=0||h+c<=0)return;const p=this._suspendPreviewInfrastructure(),u=t.getClearColor(this._previewClearColor),f=t.getClearAlpha();try{t.setScissorTest(!0),t.setViewport(l,h,d,c),t.setScissor(l,h,d,c),t.setClearColor(1118740,1),t.clear(),t.render(this._scene,e)}finally{t.setScissorTest(!1),t.setViewport(0,0,s,r),t.setClearColor(u,f),p()}}get isFlying(){return this._flyActive}_inputDisconnected=!1;disconnectInput(){if(!this._inputDisconnected){this._inputDisconnected=!0,this._publishPickContext&&xo(null),window.removeEventListener("keydown",this._onFlyKeyDown),window.removeEventListener("keyup",this._onFlyKeyUp),this._interactionElement.removeEventListener("pointerdown",this._onFlyPointerDown),this._canvas.removeEventListener("pointerdown",this._onAltOrbitStart,{capture:!0}),window.removeEventListener("pointerup",this._onAltOrbitRelease,{capture:!0}),window.removeEventListener("pointercancel",this._onAltOrbitRelease,{capture:!0}),window.removeEventListener("keydown",this._onSnapHoldKey),window.removeEventListener("keyup",this._onSnapHoldKey),this._interactionElement.removeEventListener("pointerup",this._onFlyPointerUp),this._interactionElement.removeEventListener("pointermove",this._onFlyPointerMove),this._interactionElement.removeEventListener("wheel",this._onFlyWheel),this._interactionElement.removeEventListener("wheel",this._onTrackpadWheel),this._canvas.removeEventListener("pointerdown",this._onPointerDown),this._interactionElement.removeEventListener("pointermove",this._onPointerMove),this._onInteractionPointerUp&&this._interactionElement.removeEventListener("pointerup",this._onInteractionPointerUp),this._onInteractionDblClick&&this._interactionElement.removeEventListener("dblclick",this._onInteractionDblClick),this._canvas.removeEventListener("dragover",this._onDragOver),this._canvas.removeEventListener("dragleave",this._onDragLeave),this._canvas.removeEventListener("drop",this._onDrop),this.orbitControls.dispose();for(const t of this._allGizmos())t.dispose()}}_applyViewportLook(t){this._lookGridHex=t.grid??10066329;const e=this.grid.material.uniforms.uGrazingFade;if(e&&(e.value=t.background!==null?1:0),this._paintLookGrid(),this._axesWanted=t.axisX!==null&&t.axisY!==null,this._lookAxisHexes=t.axisX!==null&&t.axisY!==null?{x:t.axisX,y:t.axisY}:null,this._paintLookAxes(),this._axisLines&&(this._axisLines.visible=this.grid.visible&&this._axesWanted),t.background!==null){const i=this._scene.background,s=i===null||i instanceof B&&[this._lookBackgroundHex,t.background].includes(i.getHex());this._lookBackgroundHex=t.background,s&&this._paintLookBackground()}else this._lookBackgroundHex=null}_paintLookGrid(){const t=this._lookGridHex;if(t===null)return;const e=this._lookBackgroundHex??4144959,i=a=>{const l=t>>a&255,h=e>>a&255;return Math.round(Math.min(255,Math.max(0,h+(l-h)*Gu)))},s=i(16)<<16|i(8)<<8|i(0),r=Go(t,this._renderer),n=Go(s,this._renderer);this.grid.material.uniforms.uColor?.value?.copy(r),this.grid.material.uniforms.uMajorColor?.value?.copy(n)}_paintLookAxes(){const t=this._lookAxisHexes;if(!this._axisLines||t===null)return;const e=new B(t.x),i=new B(t.y),s=[];for(const r of[e,i])for(let n=0;n<fr*2;n++)s.push(r.r,r.g,r.b);this._axisLines.geometry.setColors(s)}_paintLookBackground(){this._lookBackgroundHex!==null&&(this._scene.background=new B(this._lookBackgroundHex))}_syncLookBackground(){this._renderer&&(this._renderer.toneMapping===this._lookToneMapping&&this._renderer.toneMappingExposure===this._lookExposure||(this._paintLookGrid(),this._lookToneMapping=this._renderer.toneMapping,this._lookExposure=this._renderer.toneMappingExposure))}dispose(){this._disposed=!0,this._unsubscribeSelectionTheme(),this._axisLines&&(this._scene.remove(this._axisLines),this._axisLines.geometry.dispose(),this._axisLines.material.dispose(),this._axisLines=null),this.clearCameraView(),this._sparkRenderer&&(this._scene.remove(this._sparkRenderer),Sl(this._sparkRenderer),this._sparkRenderer=null),this.disconnectInput(),this._hideDropOverlay();for(const t of this._helpers.values())this._scene.remove(t);this._helpers.clear();for(const t of this._boxHelpers.values())this._scene.remove(t),t.geometry.dispose(),t.material.dispose();this._boxHelpers.clear();for(const t of this._reflectionProbeHelpers.values())t.dispose();this._reflectionProbeHelpers.clear();for(const t of this._triggerVolumeHelpers.values())t.dispose();this._triggerVolumeHelpers.clear();for(const t of this._constraintHelpers.values())t.dispose();this._constraintHelpers.clear();for(const{helper:t}of this._cameraHelpers.values())t.dispose();this._cameraHelpers.clear(),Vo(this._spatialHandleRoots),this._spatialHandleRoots=[],this._spatialHandleMeshes=[]}_ensureSparkRenderer(){if(!this._renderer||this._sparkRenderer||this._sparkRendererLoading||this._sparkRendererFailed)return;const t=performance.now();bl(this._lastSparkDiscoveryAt,t)&&(this._lastSparkDiscoveryAt=t,Ml(this._scene)&&(this._sparkRendererLoading=!0,Ss(async()=>{const{SparkRenderer:e}=await import("./spark.module-B_-x7Z29.js");return{SparkRenderer:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11])).then(({SparkRenderer:e})=>{if(this._disposed||!this._renderer)return;const i=new e({renderer:this._renderer,enableLod:!1});i.traverse(s=>Rt(s,"engineInternal",!0)),this._sparkRenderer=i}).catch(e=>{this._sparkRendererFailed=!0,console.error("Failed to install SparkRenderer in the editor viewport.",e)}).finally(()=>{this._sparkRendererLoading=!1})))}_buildOrientationGizmo(){if(this._vcScene!==void 0){for(const t of[...this._vcScene.children])this._vcScene.remove(t);this._vcBalls.length=0,this._vcStalks.length=0,this._vcClickTargets.length=0,this._initOrientationGizmo()}}_initOrientationGizmo(){const t=mi/3,e=xn/t,i=Zu/t,s=Xa/t/2,r=[new v(1,0,0),new v(0,1,0),new v(0,0,1)],n=new fe(e*.6,8,8),a=new Tt({visible:!1});for(let l=0;l<3;l++){const[h,d]=this._lookAxisFrame[l],c=Xu[h],p=Vu[h],u=r[l].clone().multiplyScalar(d),f=new E(new Ot(s,s,i,8),new Tt({color:c,transparent:!0,depthTest:!1}));f.position.copy(u).multiplyScalar(i/2),f.quaternion.setFromUnitVectors(new v(0,1,0),u),this._vcScene.add(f),this._vcStalks.push({mesh:f,direction:u.clone()});for(const m of[1,-1]){const y=u.clone().multiplyScalar(m),g=new xa(new Jh({map:Yu(c,m>0?p:null),transparent:!0,depthTest:!1}));g.position.copy(y).multiplyScalar(i),g.scale.setScalar(e),this._vcScene.add(g),this._vcBalls.push({sprite:g,direction:y.clone(),positive:m>0});const _=new E(n,a);_.position.copy(g.position),Rt(_,"vcDirIdx",l*2+(d*m>0?0:1)),this._vcScene.add(_),this._vcClickTargets.push(_)}}}_syncOrientationGizmoDepth(){const t=mi/3,e=this._vcDir.copy(this._vcCamera.position).normalize();for(const{sprite:i,direction:s,positive:r}of this._vcBalls){const n=(s.dot(e)+1)/2,a=i.material;a.opacity=r?1:.56+n*.44,i.scale.setScalar((xn+Qu*n)/t),i.renderOrder=10+Math.round(n*100)}for(const{mesh:i,direction:s}of this._vcStalks){const r=(s.dot(e)+1)/2;i.material.opacity=.35+r*.65,i.renderOrder=Math.round(r*100)}}_isOverViewCube(t,e){const i=this._canvas.getBoundingClientRect(),s=t-i.left,r=e-i.top,n=i.width-this._vcSize-this._vcMarginRight,a=this._vcMarginTop;return s>=n&&s<=n+this._vcSize&&r>=a&&r<=a+this._vcSize}_handleViewCubeClick(t){if(!this._isOverViewCube(t.clientX,t.clientY))return!1;const e=this._canvas.getBoundingClientRect(),i=t.clientX-e.left,s=t.clientY-e.top,r=e.width-this._vcSize-this._vcMarginRight,n=this._vcMarginTop,a=(i-r)/this._vcSize*2-1,l=-((s-n)/this._vcSize*2-1);this._vcRaycaster.setFromCamera(new Jt(a,l),this._vcCamera);const h=this._vcRaycaster.intersectObjects(this._vcClickTargets);if(h.length===0)return!0;const d=xt(h[0].object,"vcDirIdx"),c=Uu[d],p=new v().subVectors(this.freeCamera.position,this.orbitControls.target).normalize();return this._snapDist=this.freeCamera.position.distanceTo(this.orbitControls.target),this._snapQ1.setFromUnitVectors(new v(0,0,1),p),this._snapQ2.setFromUnitVectors(new v(0,0,1),c),this._snapStartTime=performance.now(),this._snapAnimating=!0,!0}_flushGizmoToStoreLive(){this._skipNextSync=!0;const t=this._authoring(),e=(s,r)=>{s&&no(t,s,{position:r.position.toArray(),rotation:r.quaternion.toArray(),scale:r.scale.toArray()})},i=this._activeGizmo.object;i&&i!==this._pivotDummy&&e(this._attachedAuthoringId??this._authoringIdForObject(i),i);for(const{id:s,obj:r}of this._otherDragObjects)e(s,r);for(const{id:s,obj:r}of this._allDragObjects)e(s,r);for(const{id:s,obj:r}of this._preservedChildObjects)e(s,r)}_preparePreservedChildren(t){if(!this._store.preserveChildrenTransform)return[];const e=this._authoring(),i=new Set(t),s=new Map;for(const r of i){const n=this._preservedChildrenForParent(e,r,i,s);if(typeof n=="string")return jt(n),[];for(const a of n)s.set(a.id,a)}return[...s.values()]}_preservedChildrenForParent(t,e,i,s){const r=[];for(const n of t.hierarchy.node(e)?.childIds??[]){if(i.has(n)||s.has(n))continue;const a=this._objectForAuthoringId(n);if(!a?.parent)continue;const l=this._unwritableTransformChannel(t,n);if(l){const h=t.hierarchy.node(n)?.label??n;return`Preserve Children Transform needs writable ${l} on ${h}. The parent will transform normally.`}a.updateWorldMatrix(!0,!1),r.push({id:n,obj:a,worldMatrix:a.matrixWorld.clone()})}return r}_unwritableTransformChannel(t,e){return["position","rotation","scale"].find(i=>!(t.transforms?.editability?.(e,i).writable??!1))}_restorePreservedChildren(){const t=new Mn;for(const e of this._preservedChildObjects){const i=e.obj.parent;i&&(i.updateWorldMatrix(!0,!1),t.copy(i.matrixWorld).invert().multiply(e.worldMatrix),t.decompose(e.obj.position,e.obj.quaternion,e.obj.scale),e.obj.updateMatrix(),e.obj.updateWorldMatrix(!1,!0))}}_belongsToRoots(t,e){let i=t;for(;i;){if(e.has(i))return!0;i=i.parent}return!1}_floorSnapPosition(t,e){t.updateWorldMatrix(!0,!0);const i=Ie(t);if(i.isEmpty())return null;const s=Math.min((i.max.x-i.min.x)*.1,.05),r=Math.min((i.max.z-i.min.z)*.1,.05),n=[[(i.min.x+i.max.x)/2,(i.min.z+i.max.z)/2],[i.min.x+s,i.min.z+r],[i.max.x-s,i.min.z+r],[i.min.x+s,i.max.z-r],[i.max.x-s,i.max.z-r]],a=new Yt;a.layers.enableAll();const l=i.min.y+Math.max((i.max.y-i.min.y)*.001,.001);let h=Number.NEGATIVE_INFINITY;for(const[p,u]of n){a.set(new v(p,l,u),new v(0,-1,0));const f=a.intersectObjects(this._scene.children,!0).find(m=>!this._belongsToRoots(m.object,e)&&!ue(m.object)&&m.point.y<=l);f&&(h=Math.max(h,f.point.y))}if(!Number.isFinite(h))return null;const d=h-i.min.y;if(Math.abs(d)<1e-6)return null;const c=t.getWorldPosition(new v);return c.y+=d,t.parent?(t.parent.updateWorldMatrix(!0,!1),t.parent.worldToLocal(c)):c}snapSelectionToFloor(){const t=this._authoring(),e=t.transforms;if(!e){jt("This document does not expose writable transforms.");return}const i=[...this._store.selectedEntityIds].map(l=>({id:l,obj:this._objectForAuthoringId(l)})).filter(l=>!!l.obj&&(e.editability?.(l.id,"position").writable??!0)),s=new Set(i.map(({obj:l})=>l)),r=i.filter(({obj:l})=>{let h=l.parent;for(;h;){if(s.has(h))return!1;h=h.parent}return!0});if(r.length===0){jt("Select an object with a writable position first.");return}const n=new Set(r.map(({obj:l})=>l)),a=[];for(const l of r){const h=this._floorSnapPosition(l.obj,n);h&&a.push({...l,position:h})}if(a.length===0){jt("No solid scene surface was found beneath the selection.");return}for(const{id:l}of a)ro(t,l);for(const{obj:l,position:h}of a)l.position.copy(h);this._skipNextSync=!0;for(const{id:l,obj:h}of a)no(t,l,{position:h.position.toArray(),rotation:h.quaternion.toArray(),scale:h.scale.toArray()});for(const{id:l}of a)oo(t,l);this.syncFromStore()}_applySurfaceSnap(t,e){const i=new Set,s=this._attachedAuthoringId??this._authoringIdForObject(t);s&&i.add(s);for(const{id:h}of e)i.add(h);const r=[];for(const[h,d]of this._objectMap)i.has(h)||r.push(d);if(r.push(this.grid),r.length===0){this._surfaceSnapIndicator.visible=!1;return}const n=t.position.clone();n.y+=50,this._surfaceSnapRaycaster.set(n,new v(0,-1,0)),this._surfaceSnapRaycaster.far=200;const l=this._surfaceSnapRaycaster.intersectObjects(r,!0).find(h=>h.object===this.grid||!ue(h.object));if(l){const h=l.point,d=h.y,c=d-t.position.y;t.position.y=d;for(const{obj:u}of e)u.position.y+=c;this._surfaceSnapIndicator.position.copy(h),this._surfaceSnapIndicator.position.y+=.01;const p=l.face?.normal;if(p){const u=p.clone().transformDirection(l.object.matrixWorld);this._surfaceSnapIndicator.quaternion.setFromUnitVectors(new v(0,1,0),u)}this._surfaceSnapIndicator.visible=!0}else this._surfaceSnapIndicator.visible=!1}_collectVertices(t){const e=[];for(const[s,r]of this._objectMap)t.has(s)||r.traverse(n=>{if(ue(n))return;const a=n;if(!a.isMesh||!a.geometry)return;const l=a.geometry.getAttribute("position");if(!l)return;const h=Math.min(l.count,1e3),d=a.matrixWorld;for(let c=0;c<h;c++){const p=new v(l.getX(c),l.getY(c),l.getZ(c));p.applyMatrix4(d),e.push(p)}});return e}_applyVertexSnap(t,e){const i=t.position,s=i.clone().project(this.renderCamera),r=this._canvas.getBoundingClientRect(),n=(s.x+1)/2*r.width,a=(-s.y+1)/2*r.height;let l=this._vertexSnapThreshold,h=null;for(const d of this._vertexSnapTargets){const c=d.clone().project(this.renderCamera);if(c.z>1)continue;const p=(c.x+1)/2*r.width,u=(-c.y+1)/2*r.height,f=n-p,m=a-u,y=Math.sqrt(f*f+m*m);y<l&&(l=y,h=d)}if(h){const d=h.clone().sub(i);t.position.copy(h);for(const{obj:p}of e)p.position.add(d);this._vertexSnapIndicator.position.copy(h),this._vertexSnapIndicator.visible=!0;const c=h.distanceTo(this.renderCamera.position);this._vertexSnapIndicator.scale.setScalar(c*.008)}else this._vertexSnapIndicator.visible=!1}_flushGizmoToStore(){this._flushGizmoToStoreLive();const t=this._activeTransformEditIds;this._activeTransformEditIds=[],this._otherDragObjects=[],this._allDragObjects=[],this._preservedChildObjects=[];const e=this._authoring();for(const i of t)oo(e,i)}consumeSkipSync(){return this._skipNextSync?(this._skipNextSync=!1,!0):!1}_applyGizmoSize(){if(this.transformControls===void 0)return;const t=this._lookGizmoSizePx,e=Math.max(1,this._canvas.clientHeight),i=t===null?null:2*t,s=i===null?1:this.freeCamera instanceof pi?4*i/e:i/(.2375*e);for(const r of this._allGizmos())r.size=s}_dropNegativeAxisHandles(t,e){const i=t.children.find(r=>r.isTransformControlsGizmo);if(!i)return;const s={X:new v(1,0,0),Y:new v(0,1,0),Z:new v(0,0,1)};for(const r of e)for(const n of[i.gizmo[r],i.picker[r]])if(n)for(const a of[...n.children]){const l=s[a.name];if(l===void 0)continue;const h=a;if(!h.geometry)continue;h.geometry.computeBoundingBox();const d=h.geometry.boundingBox;d&&d.getCenter(new v).dot(l)<0&&n.remove(a)}}_axisColorMap(){const t=r=>new B(...De[this._lookAxisFrame[r][0]]),e=t(0),i=t(1),s=t(2);return{X:e,Y:i,Z:s,XY:s,YZ:e,XZ:i}}_readLookStage(t){this._lookAxisFrame=eo(t)==="z"?qo:nn,this._lookBoxSelect=io(t),this._applyGizmoAxisFrame(),this._buildOrientationGizmo()}_applyGizmoAxisFrame(){if(this.transformControls===void 0)return;const t=this._lookAxisFrame.map(([,a])=>a),e=[0,1,2].map(a=>t[a]===this._appliedAxisSigns[a]?1:-1),i=e.some(a=>a===-1),s=this._axisColorMap(),r={X:new B(...De[0]),Y:new B(...De[1]),Z:new B(...De[2]),XY:new B(...De[2]),YZ:new B(...De[0]),XZ:new B(...De[1])},n=(a,l,h,d=!1)=>{a&&a.traverse(c=>{const p=c;h&&p.geometry&&p.geometry.scale(e[0],e[1],e[2]),d&&p.material&&!Array.isArray(p.material)&&!p.userData.vgaiOwnMaterial&&(p.material=p.material.clone(),p.userData.vgaiOwnMaterial=!0);const u=p.material;if(!u||Array.isArray(u))return;h&&(u.side=We);const f=l[c.name];f&&u.color&&(u.color.copy(f),u._color=void 0)})};for(const a of this._allGizmos()){const l=a.getHelper().children.find(h=>h.isTransformControlsGizmo);if(l)for(const h of["gizmo","picker","helper"])n(l[h]?.translate,s,i),n(l[h]?.rotate,s,!1),n(l[h]?.scale,r,!1,!0)}i&&(this._appliedAxisSigns=t)}_patchGizmo(t){const e=this._axisColorMap(),i={XY:[-.075,-.075,0],YZ:[0,-.075,-.075],XZ:[-.075,0,-.075]};t.traverse(s=>{const r=s,n=e[s.name];if(n&&r.material){const l=r.material;l.color&&l.color.copy(n)}const a=i[s.name];a&&r.geometry&&r.geometry.translate(a[0],a[1],a[2])})}_patchCombinedScaleGizmo(t){const i=t.children.find(a=>a.isTransformControlsGizmo);if(!i)return;const s={X:new v(1,0,0),Y:new v(0,1,0),Z:new v(0,0,1)},r=.54+.55,n=.3;for(const[a,l]of[[i.gizmo.scale,!1],[i.picker.scale,!0]])if(a)for(const h of[...a.children]){const d=h,c=s[h.name],p=c!==void 0&&d.geometry?.type==="CylinderGeometry"&&d.geometry.parameters.radiusTop<.05;if(c===void 0||p){a.remove(h);continue}d.geometry.computeBoundingBox();const u=d.geometry.boundingBox;if(!u)continue;const f=Math.sign(u.getCenter(new v).dot(c))||1;if(l){const y=c.clone().multiplyScalar(f*r);d.geometry.dispose(),d.geometry=new mt(n,n,n).translate(y.x,y.y,y.z);continue}const m=c.clone().multiplyScalar(f*.55);d.geometry.translate(m.x,m.y,m.z)}}_projectToScreen(t){const e=new v;t.getWorldPosition(e),e.project(this.renderCamera);const i=this._canvas.getBoundingClientRect();return new Jt((e.x+1)/2*i.width+i.left,(-e.y+1)/2*i.height+i.top)}static _FLY_KEYS=new Set(["w","a","s","d","q","e"]);_enterFlyMode(){this._flyActive||this._cameraViewMode!=="view"&&(this._flyActive=!0,this._snapAnimating=!1,this.orbitControls.enabled=!1,this._flyEuler.setFromQuaternion(this.renderCamera.quaternion,"YXZ"),this.orbitControls.dispatchEvent({type:"start"}),this._canvas.requestPointerLock?.())}_exitFlyMode(){if(!this._flyActive)return;this._flyActive=!1,this._flyKeys.clear(),this.orbitControls.enabled=this._cameraViewMode!=="view",document.exitPointerLock();const t=this.renderCamera,e=new v(0,0,-1).applyQuaternion(t.quaternion),i=t.position.distanceTo(this.orbitControls.target);this.orbitControls.target.copy(t.position).add(e.multiplyScalar(Math.max(i,5))),this.orbitControls.dispatchEvent({type:"end"})}_updateFlyCamera(t){if(!this._flyActive||this._flyKeys.size===0)return;const e=this.renderCamera,i=this._flySpeed*(this._flyKeys.has("shift")?3:1),s=new v(0,0,-1).applyQuaternion(e.quaternion),r=new v(1,0,0).applyQuaternion(e.quaternion),n=new v;this._flyKeys.has("w")&&n.add(s),this._flyKeys.has("s")&&n.sub(s),this._flyKeys.has("d")&&n.add(r),this._flyKeys.has("a")&&n.sub(r),this._flyKeys.has("e")&&(n.y+=1),this._flyKeys.has("q")&&(n.y-=1),n.lengthSq()>0&&(n.normalize().multiplyScalar(i*t),e.position.add(n),this.orbitControls.dispatchEvent({type:"change"}))}_onFlyKeyDown=t=>{if(!this._rightMouseDown||t.target instanceof HTMLInputElement||t.target instanceof HTMLTextAreaElement||t.target instanceof HTMLSelectElement)return;const e=t.key.toLowerCase();if(e==="shift"){this._flyKeys.add("shift");return}Nn._FLY_KEYS.has(e)&&(t.preventDefault(),t.stopPropagation(),this._flyKeys.add(e),this._flyActive||this._enterFlyMode())};_onFlyKeyUp=t=>{const e=t.key.toLowerCase();if(e==="shift"){this._flyKeys.delete("shift");return}this._flyKeys.delete(e)};_onFlyPointerDown=t=>{t.button===2&&(this._rightMouseDown=!0)};_onFlyPointerUp=t=>{t.button===2&&(this._rightMouseDown=!1,this._flyActive&&this._exitFlyMode())};_onFlyPointerMove=t=>{if(!this._flyActive)return;const e=.002;this._flyEuler.y-=t.movementX*e,this._flyEuler.x-=t.movementY*e,this._flyEuler.x=Math.max(-Math.PI/2+.01,Math.min(Math.PI/2-.01,this._flyEuler.x)),this.renderCamera.quaternion.setFromEuler(this._flyEuler),this.orbitControls.dispatchEvent({type:"change"})};_onTrackpadWheel=t=>{if(this._flyActive||!this.orbitControls.enabled||t.ctrlKey||Math.abs(t.deltaX)<.5&&!t.shiftKey)return;t.preventDefault(),t.stopImmediatePropagation();const e=this._interactionElement.clientHeight||1,i=this.camera.position.distanceTo(this.orbitControls.target),s=2*Math.tan(this.camera.fov/2*Math.PI/180)*i/e,r=t.deltaMode===1?16:1,n=d=>Math.sign(d)*Math.min(Math.abs(d*r),30),a=new v().setFromMatrixColumn(this.camera.matrix,0),l=new v().setFromMatrixColumn(this.camera.matrix,1),h=a.multiplyScalar(n(t.deltaX)*s).add(l.multiplyScalar(-n(t.deltaY)*s));this.camera.position.add(h),this.orbitControls.target.add(h),this.orbitControls.update()};_onFlyWheel=t=>{if(!this._flyActive)return;t.preventDefault();const e=t.deltaY>0?.85:1.18;this._flySpeed=Math.max(.5,Math.min(100,this._flySpeed*e))};_onPointerDown=t=>{if(this._pointerDownPos.set(t.clientX,t.clientY),this._pointerDownButton=t.button,this._marqueeActive=!1,this._pointerSessionActive=!0,this._constraintControlPointerSession=!1,t.button===0&&!t.altKey){if(this._selectConstraintControlAt(t))return;const e=this._raycastSpatialHandle(t),i=e?Do(e):null;if(e&&i?.handle.writable){t.stopPropagation(),this._activeSpatialHandle=i,this._spatialHandleDragPoint.copy(e.position),this._orbitEnabledBeforeHandleDrag=this.orbitControls.enabled,this._transformEnabledBeforeHandleDrag=this.transformControls.enabled,this.orbitControls.enabled=!1;for(const n of this._allGizmos())n.enabled=!1;const s=this.renderCamera.getWorldDirection(new v);this._spatialHandleDragPlane.setFromNormalAndCoplanarPoint(s,e.position),this._spatialHandleDragOffset.set(0,0,0);const r=this._spatialHandleWorldPoint(t);r&&this._spatialHandleDragOffset.subVectors(e.position,r),this._canvas.style.cursor="grabbing"}}};_onPointerMove=t=>{if(this._updateEditorHandleInteraction(t)||(this._updateSpatialHandleHover(t),!this._pointerSessionActive)||!(t.buttons&1)||this._pointerDownButton!==0||this._anyGizmoDragging()||this._altDragOrbit)return;const e=t.clientX-this._pointerDownPos.x,i=t.clientY-this._pointerDownPos.y;if(!this._marqueeActive&&Math.sqrt(e*e+i*i)>5){const s=this._canvas.getBoundingClientRect(),r=this._pointerDownPos.x-s.left,n=this._pointerDownPos.y-s.top,a=s.width-this._vcSize-this._vcMarginRight;if(r>=a&&r<=a+this._vcSize&&n>=this._vcMarginTop&&n<=this._vcMarginTop+this._vcSize)return;this._marqueeActive=!0,this.orbitControls.enabled=!1,this._marqueeDiv||(this._marqueeDiv=document.createElement("div"),Object.assign(this._marqueeDiv.style,{position:"fixed",border:`1px solid ${Nt.accent.default}`,background:Nt.accent.muted,pointerEvents:"none",zIndex:ao.sticky}),(document.getElementById("editor-chrome-root")??document.body).appendChild(this._marqueeDiv))}if(this._marqueeActive&&this._marqueeDiv){const s=Math.min(this._pointerDownPos.x,t.clientX),r=Math.min(this._pointerDownPos.y,t.clientY),n=Math.abs(t.clientX-this._pointerDownPos.x),a=Math.abs(t.clientY-this._pointerDownPos.y);Object.assign(this._marqueeDiv.style,{left:`${s}px`,top:`${r}px`,width:`${n}px`,height:`${a}px`,display:"block"})}};_onPointerUp=t=>{if(!this._pointerSessionActive)return;if(this._pointerSessionActive=!1,this._activeSpatialHandle){this._finishSpatialHandleDrag(!0);return}if(this._constraintControlPointerSession){this._constraintControlPointerSession=!1;return}if(this._marqueeActive){this._marqueeActive=!1,this.orbitControls.enabled=!0,this._marqueeDiv&&(this._marqueeDiv.style.display="none");const n=Math.min(this._pointerDownPos.x,t.clientX),a=Math.max(this._pointerDownPos.x,t.clientX),l=Math.min(this._pointerDownPos.y,t.clientY),h=Math.max(this._pointerDownPos.y,t.clientY),d=[],c=new v,p=new ie;for(const[u,f]of this._objectMap){if(!f.visible||f.isCamera===!0)continue;if(p.setFromObject(f),p.isEmpty()){const b=this._projectToScreen(f);b.x>=n&&b.x<=a&&b.y>=l&&b.y<=h&&d.push(u);continue}const m=this._lookBoxSelect==="touch",y=this._canvas.getBoundingClientRect();let g=!0,_=Number.POSITIVE_INFINITY,M=Number.NEGATIVE_INFINITY,w=Number.POSITIVE_INFINITY,C=Number.NEGATIVE_INFINITY;for(let b=0;b<8;b++){if(c.set(b&1?p.max.x:p.min.x,b&2?p.max.y:p.min.y,b&4?p.max.z:p.min.z),c.project(this.camera),c.z<-1||c.z>1){if(g=!1,!m)break;continue}const P=y.left+(c.x+1)*y.width/2,A=y.top+(1-c.y)*y.height/2;(P<n||P>a||A<l||A>h)&&(g=!1),_=Math.min(_,P),M=Math.max(M,P),w=Math.min(w,A),C=Math.max(C,A)}const x=_<=M&&M>=n&&_<=a&&C>=l&&w<=h;(m?x:g)&&d.push(u)}if(t.shiftKey)for(const u of d)this._store.addToSelection(u);else ki(this._authoring(),d);return}if(t.button!==0)return;const e=t.clientX-this._pointerDownPos.x,i=t.clientY-this._pointerDownPos.y;if(Math.sqrt(e*e+i*i)>5||this._anyGizmoDragging()||this._threejsToolContextActive&&this._handleViewCubeClick(t))return;const s=t.shiftKey&&(t.metaKey||t.ctrlKey),r=Cl(this._scopeAuthoring(),()=>this._pickAt(t.clientX,t.clientY,s?"deep":"normal"));s?ki(this._authoring(),r?[r]:[]):t.shiftKey&&r?this._store.toggleSelection(r):(t.metaKey||t.ctrlKey)&&r?this._store.toggleSelection(r):ki(this._authoring(),r?[r]:[])};_scopeAuthoring(){return this._standaloneAuthoring?this._authoring():Gs().panelAuthoring(this._store)}_pickAt(t,e,i){return this._pick?this._pick(t,e):Gs().pick(this._store,t,e,i)}_onDoubleClick=t=>{if(t.button!==0||this._anyGizmoDragging()||this._marqueeActive||this._threejsToolContextActive&&this._isOverViewCube(t.clientX,t.clientY))return;const e=this._pickAt(t.clientX,t.clientY,"normal");e&&Pl(this._scopeAuthoring(),e,()=>this._pickAt(t.clientX,t.clientY,"normal"))};_raycastGroundPlane(t){const e=this._canvas.getBoundingClientRect(),i=new Jt((t.clientX-e.left)/e.width*2-1,-((t.clientY-e.top)/e.height)*2+1);this.raycaster.setFromCamera(i,this.renderCamera);const s=lo("three");this._groundPlane.set(s.up==="z"?Hu:Nu,-s.groundHeight);const r=new v;return this.raycaster.ray.intersectPlane(this._groundPlane,r)}_showDropOverlay(){if(this._dropOverlay)return;const t=document.createElement("div");Object.assign(t.style,{position:"fixed",inset:"0",pointerEvents:"none",border:`2px dashed ${Nt.accent.default}`,background:Nt.accent.muted,zIndex:ao.base}),(document.getElementById("editor-chrome-root")??document.body).appendChild(t),this._dropOverlay=t}_hideDropOverlay(){this._dropOverlay&&(this._dropOverlay.remove(),this._dropOverlay=null)}_onDragOver=t=>{t.dataTransfer?.types.includes("application/x-editor-asset")&&(t.preventDefault(),t.dataTransfer.dropEffect="copy",this._showDropOverlay())};_onDragLeave=t=>{this._hideDropOverlay()};_onDrop=t=>{this._hideDropOverlay();const e=t.dataTransfer?.getData("application/x-editor-asset");if(!e)return;t.preventDefault();let i;try{i=JSON.parse(e)}catch{return}const s=lo("three"),r=this._raycastGroundPlane(t),n=c=>Math.round(c*100)/100,a=s.up==="z"?[n(r?.x??0),n(r?.y??0),s.groundHeight]:[n(r?.x??0),s.groundHeight,n(r?.z??0)],l=this._authoring(),h=l.assetDrop,d=i.component??{kind:"file",name:i.name};if(!h){Fi.warn(`Dropped “${i.name}” was not placed: this document does not accept dropped assets.`,"editor");return}if(i.online){const c=i.online,p=this._onlineAssetResolver;if(!p){Fi.warn(`Dropped “${i.name}” was not placed: this viewport has no online-asset resolver installed.`,"editor");return}jt(`Downloading ${c.name} from the library…`),p(c).then(u=>{u?(jt(`${c.name} downloaded — placing it.`),ho(l,"",u,{position:a})):jt(`Could not download ${c.name} — see the Console.`)}).catch(()=>{jt(`Could not download ${c.name} — see the Console.`),Fi.error(`Could not download ${c.name}.`,"asset")});return}ho(l,"",i.path,{position:a,item:d})}}class rp extends kt{constructor(t,e){super(),this.bones=t;const i=new Set;for(const a of t){const l=a.parent;l?.isBone&&this.addSegment(l,a,i);for(const h of a.children)h.isBone&&this.addSegment(a,h,i)}this.linePositions=new Float32Array(Math.max(this.segments.length*6,6));const s=new Tn;s.setPositions(this.linePositions),this.lineMaterial=new zn({color:e,linewidth:5,worldUnits:!1,depthTest:!1,depthWrite:!1,toneMapped:!1,alphaToCoverage:!0}),this.lines=new En(s,this.lineMaterial),this.lines.onBeforeRender=a=>{a.getSize(this.lineMaterial.resolution)},this.lines.frustumCulled=!1,this.lines.renderOrder=1001,this.add(this.lines),this.pointPositions=new Float32Array(Math.max(t.length*3,3));const r=new Re;r.setAttribute("position",new ce(this.pointPositions,3));const n=new Yh({color:e,size:11,sizeAttenuation:!1,depthTest:!1,depthWrite:!1,toneMapped:!1});this.points=new wa(r,n),this.points.frustumCulled=!1,this.points.renderOrder=1002,this.add(this.points),this.name="__object3d_document_bone_selection",pn(this,"editorHelper",!0),this.traverse(a=>a.layers.set(X)),this.update()}segments=[];linePositions;pointPositions;lines;lineMaterial;points;worldPosition=new v;setColor(t){this.lineMaterial.color.setHex(t),this.points.material.color.setHex(t)}update(){let t=0;for(const[s,r]of this.segments)s.getWorldPosition(this.worldPosition),this.linePositions.set(this.worldPosition.toArray(),t),r.getWorldPosition(this.worldPosition),this.linePositions.set(this.worldPosition.toArray(),t+3),t+=6;const e=this.lines.geometry.getAttribute("instanceStart");e&&(e.data.needsUpdate=!0),t=0;for(const s of this.bones)s.getWorldPosition(this.worldPosition),this.pointPositions.set(this.worldPosition.toArray(),t),t+=3;const i=this.points.geometry.getAttribute("position");i&&(i.needsUpdate=!0)}dispose(){this.lines.geometry.dispose(),this.lineMaterial.dispose(),this.points.geometry.dispose(),this.points.material.dispose()}addSegment(t,e,i){const s=`${t.uuid}:${e.uuid}`;i.has(s)||(i.add(s),this.segments.push([t,e]))}}const np="skeletons",on=new B(58879),an=new B(16756736);function op(o){const t=o.geometry.getAttribute("color");for(let i=0;i<t.count;i+=2)t.setXYZ(i,on.r,on.g,on.b),i+1<t.count&&t.setXYZ(i+1,an.r,an.g,an.b);t.needsUpdate=!0,o.renderOrder=999;const e=o.material;e.depthTest=!1,e.depthWrite=!1,e.toneMapped=!1,pn(o,"editorHelper",!0),pn(o,"editorHelperType",np),o.traverse(i=>i.layers.set(X))}const Qo=o=>!bs(o),ap=1,lp=700,hp=.001,cp=Math.PI-.001,dp=o=>o<.5?4*o*o*o:1-(-2*o+2)**3/2,up=o=>o;function hi(o,t){return typeof o=="number"&&Number.isFinite(o)?o:t}const $o={mode:"solid",grid:!0,background:"neutral",exposure:1,projection:"perspective",lighting:"studio",skeleton:!1,bounds:!1};class pp{constructor(t,e,i,s,r,n=[],a,l=new B(2106410),h=null){this.documentId=t,this.root=e,this.scene=i,this.renderer=s,this.viewport=r,this.editorLights=n,this.authoring=a,this.neutralBackground=l,this.frameBox=h,this.unsubscribeSelectionTheme=mr(s.domElement,this.syncSelectionTheme),r.orbitControls.addEventListener("start",this.cancelLookForHuman)}profiler=mc();shading=new xc;helpers=[];skeletonHelper=null;boundsHelper=null;boneSelectionHighlight=null;boneSelectionSignature="";composer=null;composerLoading=!1;disposed=!1;sceneRenderPass=null;selectionOutline=null;selectionOutlinePass=null;selectedObjects=[];renderWidth=1;renderHeight=1;orthographicCamera=new pi;captureAspect=null;cameraOverride=null;beforeRender=null;state=$o;version=0;listeners=new Set;unsubscribeSelectionTheme=()=>{};flight=null;flightPose=new v;topologyOverlay=null;topologyFollowers=[];replaceContent(t,e){this.selectionOutline?.selection.clear(),this.selectedObjects=[],this.boneSelectionSignature="",this.clearBoneSelectionHighlight(),this.clearSkeletonHelper(),this.clearBoundsHelper(),this.clearTopologyOverlay(),this.root=t,this.authoring=e,this.state.mode==="wireframe"&&this.buildTopologyOverlay(),this.state.bounds&&(this.boundsHelper=new mo(t,16757844),this.addHelper(this.boundsHelper,"bounds")),this.syncSelectionPresentation(),this.refreshSkeletonHelper(),this.notify()}cancelLookForHuman=()=>{this.settleFlight("human")};syncSelectionTheme=()=>{const t=ze(this.renderer.domElement).visible;this.selectionOutline&&Cu(this.selectionOutline,ze(this.renderer.domElement)),this.boneSelectionHighlight?.setColor(t)};subscribe=t=>(this.listeners.add(t),()=>this.listeners.delete(t));getSnapshot=()=>this.version;presentation(){return this.state}resolveFrameBounds(){const t=this.authoring?.selection?.get()??[];if(t.length>0){const e=new ie;let i=!1;for(const s of t){const r=this.authoring?.hierarchy.object3D?.(s);if(!r)continue;const n=Ie(r);n.isEmpty()||(e.union(n),i=!0)}if(i)return e}return this.frameBox&&!this.frameBox.isEmpty()?this.frameBox:Ie(this.root)}frame(t=1){const e=this.resolveFrameBounds();if(e.isEmpty()){let a=0,l=0;return this.root.traverse(h=>{const d=h.geometry;d&&(a+=1,l+=d.getAttribute("position")?.count??0)}),Fi.warn(`frame: nothing to frame — root "${this.root.name}" (${this.root.children.length} children, ${a} meshes, ${l} positions), selection ${JSON.stringify(this.authoring?.selection?.get()??[])}, frameBox ${this.frameBox?this.frameBox.isEmpty()?"empty":"set":"none"}`,"document"),!1}this.settleFlight("superseded");const i=e.getCenter(new v),s=this.viewport.camera.position.clone().sub(this.viewport.orbitControls.target).normalize();s.lengthSq()===0&&s.set(.8,.5,-1).normalize();const r=Math.min(10,Math.max(.1,hi(t,1))),n=Xe(e,this.viewport.camera,s)*r;return this.viewport.setPose(i.clone().addScaledVector(s,n),i),!0}orbit(t){return this.launchFlight(hi(t.azimuth,0),hi(t.elevation,0),Math.min(60,Math.max(0,hi(t.duration,.6))),dp)}turntable(t){const e=hi(t.revolutions,1);return this.launchFlight(e*Math.PI*2,0,Math.min(60,Math.max(0,hi(t.seconds,6))),up)}looking(){return this.flight!==null}launchFlight(t,e,i,s){this.settleFlight("superseded");const r=this.viewport.camera,n=this.viewport.orbitControls.target.clone(),a=new qh().setFromVector3(r.position.clone().sub(n)),l=a.radius>1e-4?a.radius:Math.max(this.resolveFrameBounds().getSize(new v).length(),1),h={pivot:n,radius:l,startTheta:a.theta,startPhi:a.phi,deltaTheta:t,deltaPhi:-e,duration:i,ease:s,elapsed:0,theta:a.theta,phi:a.phi,settle:null};this.flight=h;const d=new Promise(c=>{h.settle=c});return this.applyFlightPose(h,0),i<=0&&this.settleFlight(null),d}applyFlightPose(t,e){const i=t.ease(e);t.theta=t.startTheta+t.deltaTheta*i,t.phi=Math.min(cp,Math.max(hp,t.startPhi+t.deltaPhi*i));const s=this.viewport.camera;s.position.setFromSphericalCoords(t.radius,t.phi,t.theta).add(t.pivot),this.viewport.orbitControls.target.copy(t.pivot),s.lookAt(t.pivot),s.updateMatrixWorld(),this.flightPose.copy(s.position)}advanceLook(t){const e=this.flight;if(!e)return;const i=Math.max(1e-4,e.radius*.001);if(this.viewport.camera.position.distanceToSquared(this.flightPose)>i*i){this.settleFlight("human");return}t>0&&Number.isFinite(t)&&(e.elapsed+=t);const s=e.duration<=0?1:Math.min(1,e.elapsed/e.duration);this.applyFlightPose(e,s),s>=1&&this.settleFlight(null)}settleFlight(t){const e=this.flight;if(!e)return;this.flight=null;const i={completed:t===null,azimuth:e.theta,elevation:Math.PI/2-e.phi,seconds:Math.min(e.elapsed,e.duration)};e.settle?.(t===null?i:{...i,cancelledBy:t})}select(t){this.authoring&&ki(this.authoring,[...t])}selection(){return[...this.authoring?.selection?.get()??[]]}idForObject(t){return this.authoring?.hierarchy.idForObject3D?.(t)??null}syncSelectionPresentation(){const t=(this.authoring?.selection?.get()??[]).map(s=>this.authoring?.hierarchy.object3D?.(s)??null).filter(s=>s!==null);this.selectedObjects=t,this.selectionOutline&&(jo(this.selectionOutline,this.selectionOutlineWanted?t:[]),this.syncComposerOutput());const e=t.filter(s=>!!s.isBone),i=e.map(s=>s.uuid).join("\0");i!==this.boneSelectionSignature&&(this.boneSelectionSignature=i,this.clearBoneSelectionHighlight(),e.length>0&&(this.boneSelectionHighlight=new rp(e,ze(this.renderer.domElement).visible),this.scene.add(this.boneSelectionHighlight)),this.refreshSkeletonHelper())}frameSelection(){return this.frameIds(this.authoring?.selection?.get()??[])}frameIds(t){this.settleFlight("superseded");const e=t.map(i=>this.authoring?.hierarchy.object3D?.(i)??null).filter(i=>i!==null);return e.length===0?!1:e.every(i=>i.isBone)?(this.frameBones(e),!0):(this.viewport.focusOnMultiple(e),!0)}setViewPreset(t){this.settleFlight("superseded");const e=this.resolveFrameBounds();if(e.isEmpty())return;const i=e.getCenter(new v),s=El(t),r=Xe(e,this.viewport.camera,s),n=i.clone().addScaledVector(s,r);this.viewport.camera.up.set(0,t==="top"?0:1,t==="top"?-1:0),this.viewport.setPose(n,i),this.setProjection(t==="isometric"?"perspective":"orthographic")}setCameraPose(t,e,i){this.settleFlight("superseded"),this.viewport.setPose(t,e,i)}cameraPose(){return{position:this.viewport.camera.position.toArray(),target:this.viewport.orbitControls.target.toArray(),fov:this.viewport.camera.fov}}camera(){return this.cameraOverride?this.cameraOverride:this.state.projection==="perspective"?this.viewport.camera:(this.syncOrthographicCamera(),this.orthographicCamera)}projection(){return this.state.projection}setProjection(t){this.state.projection!==t&&(this.state={...this.state,projection:t},this.notify())}lightingAvailable(){return this.editorLights.length>0}setLighting(t){this.state.lighting!==t&&(this.setLightingValues(t),this.state={...this.state,lighting:t},this.notify())}setMode(t){this.state.mode!==t&&(this.clearDiagnosticPresentation(),this.state={...this.state,mode:t},t==="uv"?this.scene.overrideMaterial=new ji({vertexShader:"varying vec2 vUv; void main(){ vUv=uv; gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.0); }",fragmentShader:"varying vec2 vUv; void main(){ gl_FragColor=vec4(vUv,0.0,1.0); }"}):t==="vertex-colors"?this.scene.overrideMaterial=new Tt({vertexColors:!0}):t==="wireframe"&&this.buildTopologyOverlay(),this.notify())}buildTopologyOverlay(){const t=new kt,e=[];this.root.updateMatrixWorld(!0),this.root.traverse(i=>{const s=i;if(!s.isMesh||!s.geometry)return;const r=new Cs(new An(s.geometry,ap),new Ze({color:1119773,toneMapped:!1,transparent:!0,opacity:.85,depthTest:!1,depthWrite:!1}));r.matrixAutoUpdate=!1,r.matrixWorldAutoUpdate=!1,r.matrixWorld.copy(s.matrixWorld),r.frustumCulled=!1,r.renderOrder=2,t.add(r),e.push({line:r,source:s})}),e.length!==0&&(this.topologyOverlay=t,this.topologyFollowers=e,this.addHelper(t,"topology"))}syncTopologyOverlay(){this.topologyFollowers.some(({source:t})=>t.parent===null)&&(this.clearTopologyOverlay(),this.buildTopologyOverlay());for(const{line:t,source:e}of this.topologyFollowers)t.matrixWorld.copy(e.matrixWorld),t.visible=e.visible}clearTopologyOverlay(){for(const{line:i}of this.topologyFollowers.splice(0))i.geometry.dispose(),i.material.dispose();const t=this.topologyOverlay;if(this.topologyOverlay=null,!t)return;t.removeFromParent();const e=this.helpers.indexOf(t);e>=0&&this.helpers.splice(e,1)}setBounds(t){this.state.bounds!==t&&(this.state={...this.state,bounds:t},t?(this.boundsHelper=new mo(this.root,16757844),this.addHelper(this.boundsHelper,"bounds")):this.clearBoundsHelper(),this.notify())}setSkeleton(t){this.state.skeleton!==t&&(this.state={...this.state,skeleton:t},this.refreshSkeletonHelper(),this.notify())}setGrid(t){this.state.grid!==t&&(this.viewport.grid.visible=t,this.state={...this.state,grid:t},this.notify())}neutralBackgroundTexture(){return this.neutralBackground}setNeutralBackground(t){const e=this.scene.background===this.neutralBackground;this.neutralBackground=t,e&&(this.scene.background=t)}setBackground(t){this.state.background!==t&&(this.scene.background=t==="transparent"?null:this.neutralBackground,this.state={...this.state,background:t},this.notify())}setExposure(t){!Number.isFinite(t)||t<.2||t>2||this.state.exposure!==t&&(this.renderer.toneMappingExposure=t,this.state={...this.state,exposure:t},this.notify())}resetPresentation(){this.clearDiagnosticPresentation(),this.state=$o,this.refreshSkeletonHelper(),this.clearBoundsHelper(),this.viewport.grid.visible=!0,this.scene.background=this.neutralBackground,this.renderer.toneMappingExposure=1,this.setLightingValues("studio"),this.viewport.camera.up.set(0,1,0),this.frame(),this.notify()}setBeforeRender(t){this.beforeRender=t}presentedFrameWaiters=[];presentsFrames=!1;setPresentsFrames(t){this.presentsFrames=t,t||this.resolvePresentedFrame(null)}requestPresentedFrame(){return this.presentsFrames?new Promise(t=>{let e=!1;const i=s=>{e||(e=!0,t(s))};this.presentedFrameWaiters.push(i),setTimeout(()=>i(null),lp)}):Promise.resolve(null)}servePresentedFrame(){if(this.presentedFrameWaiters.length===0)return;const t=this.renderer.domElement,e=document.createElement("canvas");e.width=Math.max(1,t.width),e.height=Math.max(1,t.height);const i=e.getContext("2d");if(!i){this.resolvePresentedFrame(null);return}i.drawImage(t,0,0),this.resolvePresentedFrame(e)}resolvePresentedFrame(t){const e=this.presentedFrameWaiters;this.presentedFrameWaiters=[];for(const i of e)i(t)}render(t){this.beforeRender?.(),this.boneSelectionHighlight?.update();const e=this.camera(),i=this.state.mode;if(this.boundsHelper?.update(),i==="uv"||i==="vertex-colors"){t(e);return}if(i==="wireframe"&&this.topologyOverlay){this.syncTopologyOverlay(),this.shading.render(this.scene,"clay",()=>t(e),Qo);return}this.shading.render(this.scene,i,()=>t(e),Qo)}renderViewport(t=0){this.advanceLook(t),this.ensureComposer(),this.render(e=>{const i=this.composer;if(!i){this.renderer.render(this.scene,e);return}i.setMainScene(this.scene),i.setMainCamera(e),i.render(t)})}resize(t,e){this.renderWidth=Math.max(1,t),this.renderHeight=Math.max(1,e),this.composer?.setSize(this.renderWidth,this.renderHeight)}renderCapture(t,e){this.render(i=>{if(!e){t(i);return}const s=this.scene.background,r=this.renderer.getClearColor(new B),n=this.renderer.getClearAlpha();try{this.scene.background=null,this.renderer.setClearColor(0,0),t(i)}finally{this.scene.background=s,this.renderer.setClearColor(r,n)}})}captureImage(t=512){const e=typeof t=="number"?t:t.width,i=typeof t=="number"?t:t.height;if(!Number.isFinite(e)||e<1||!Number.isFinite(i)||i<1)return null;const s=Math.min(2048,Math.round(e)),r=Math.min(2048,Math.round(i)),n=s*2,a=r*2,l=new go(n,a,{type:Zh}),h=new go(n,a),d=this.renderer.getRenderTarget(),c=this.renderer.getPixelRatio(),p=this.viewport.camera,u=p.aspect;try{this.captureAspect=s/r;const f=typeof t=="number"?void 0:t.camera;f?this.cameraOverride=f:(p.aspect=s/r,p.updateProjectionMatrix()),this.renderer.setPixelRatio(1),this.renderer.setRenderTarget(l),this.renderCapture(x=>this.renderSolidForCapture(x,l,n,a),typeof t!="number"&&t.transparent===!0),Tl(typeof t!="number"&&t.transparent===!0).render(this.renderer,h,l,0,!1);const m=n*4,y=new Uint8Array(m*a);this.renderer.readRenderTargetPixels(h,0,0,n,a,y);const g=document.createElement("canvas");g.width=n,g.height=a;const _=g.getContext("2d");if(!_)return null;const M=_.createImageData(n,a);for(let x=0;x<a;x++){const b=(a-1-x)*m,P=x*m;M.data.set(y.subarray(b,b+m),P)}_.putImageData(M,0,0);const w=document.createElement("canvas");w.width=s,w.height=r;const C=w.getContext("2d");return C?(C.drawImage(g,0,0,s,r),w.toDataURL("image/png")):null}finally{this.captureAspect=null,this.cameraOverride=null,p.aspect=u,p.updateProjectionMatrix(),this.renderer.setRenderTarget(d),this.renderer.setPixelRatio(c),h.dispose(),l.dispose()}}dispose(){this.disposed=!0,this.settleFlight("closed"),this.viewport.orbitControls.removeEventListener("start",this.cancelLookForHuman),this.unsubscribeSelectionTheme(),this.clearDiagnosticPresentation(),this.clearBoneSelectionHighlight(),this.clearBoundsHelper(),this.clearSkeletonHelper(),this.selectionOutline?.selection.clear(),this.composer?.dispose(),this.sceneRenderPass=null,this.selectionOutline=null,this.selectionOutlinePass=null,this.composer=null,this.shading.dispose(),this.listeners.clear()}addHelper(t,e){t.name=`__object3d_document_${e}`,Rt(t,"editorHelper",!0),this.scene.add(t),this.helpers.push(t)}get selectionOutlineEnabled(){return this.selectionOutlineWanted}set selectionOutlineEnabled(t){t!==this.selectionOutlineWanted&&(this.selectionOutlineWanted=t,t?this.syncSelectionPresentation():(this.selectionOutline?.selection.clear(),this.syncComposerOutput()))}selectionOutlineWanted=!0;ensureComposer(){this.selectionOutlineWanted&&(this.composer||this.composerLoading||this.disposed||(this.composerLoading=!0,Ss(()=>import("./index-C5UECeSr.js"),__vite__mapDeps([12,1])).then(t=>{if(this.composerLoading=!1,this.disposed||this.composer)return;const e=this.camera(),i=new t.EffectComposer(this.renderer);this.sceneRenderPass=new t.RenderPass(this.scene,e),i.addPass(this.sceneRenderPass),this.selectionOutline=bu(t,this.scene,e,ze(this.renderer.domElement)),this.syncSelectionTheme(),jo(this.selectionOutline,this.selectedObjects),this.selectionOutlinePass=new t.EffectPass(e,this.selectionOutline),i.addPass(this.selectionOutlinePass),this.composer=i,this.syncComposerOutput(),i.setSize(this.renderWidth,this.renderHeight)}).catch(()=>{this.composerLoading=!1})))}renderSolidForCapture(t,e,i,s){const r=this.composer,n=(this.selectionOutline?.selection.size??0)>0;if(!r||!n||!this.sceneRenderPass||!this.selectionOutlinePass){this.renderer.render(this.scene,t);return}const a=this.renderWidth,l=this.renderHeight;try{this.sceneRenderPass.renderToScreen=!1,this.selectionOutlinePass.renderToScreen=!1,r.setSize(i,s,!1),this.sceneRenderPass.render(this.renderer,r.inputBuffer,r.outputBuffer,0),this.selectionOutlinePass.render(this.renderer,r.inputBuffer,e,0)}finally{r.setSize(a,l,!1),this.syncComposerOutput(),this.renderer.setRenderTarget(e)}}syncComposerOutput(){const t=(this.selectionOutline?.selection.size??0)>0;this.sceneRenderPass&&(this.sceneRenderPass.renderToScreen=!t),this.selectionOutlinePass&&(this.selectionOutlinePass.enabled=t,this.selectionOutlinePass.renderToScreen=t)}refreshSkeletonHelper(){const t=this.state.skeleton||this.boneSelectionHighlight!==null;t&&!this.skeletonHelper?(this.skeletonHelper=new Qh(this.root),op(this.skeletonHelper),this.scene.add(this.skeletonHelper)):t||this.clearSkeletonHelper()}clearSkeletonHelper(){this.skeletonHelper&&(this.skeletonHelper.removeFromParent(),this.skeletonHelper.dispose(),this.skeletonHelper=null)}clearBoneSelectionHighlight(){this.boneSelectionHighlight&&(this.boneSelectionHighlight.removeFromParent(),this.boneSelectionHighlight.dispose(),this.boneSelectionHighlight=null)}clearBoundsHelper(){if(!this.boundsHelper)return;const t=this.boundsHelper;this.boundsHelper=null;const e=this.helpers.indexOf(t);e>=0&&this.helpers.splice(e,1),t.removeFromParent(),t.geometry.dispose(),Array.isArray(t.material)?t.material.forEach(i=>{i.dispose()}):t.material.dispose()}frameBones(t){const e=new ie,i=new v;for(const l of t){e.expandByPoint(l.getWorldPosition(i)),l.parent?.isBone&&e.expandByPoint(l.parent.getWorldPosition(i));for(const h of l.children)h.isBone&&e.expandByPoint(h.getWorldPosition(i))}const s=e.getCenter(new v),r=Math.max(e.getSize(new v).length(),.2);e.expandByScalar(r*.35);const n=this.viewport.camera.position.clone().sub(this.viewport.orbitControls.target).normalize(),a=Xe(e,this.viewport.camera,n);this.viewport.setPose(s.clone().addScaledVector(n,a),s)}syncOrthographicCamera(){const t=this.viewport.camera,e=this.viewport.orbitControls.target,i=Math.max(t.position.distanceTo(e),.001),s=Math.max(i*Math.tan(Dt.degToRad(t.fov)/2),.001),r=Math.max(this.renderer.domElement.clientWidth,1),n=Math.max(this.renderer.domElement.clientHeight,1),a=this.captureAspect??r/n;this.orthographicCamera.left=-s*a,this.orthographicCamera.right=s*a,this.orthographicCamera.top=s,this.orthographicCamera.bottom=-s,this.orthographicCamera.near=t.near,this.orthographicCamera.far=t.far,this.orthographicCamera.position.copy(t.position),this.orthographicCamera.quaternion.copy(t.quaternion),this.orthographicCamera.up.copy(t.up),this.orthographicCamera.layers.mask=t.layers.mask,this.orthographicCamera.updateProjectionMatrix(),this.orthographicCamera.updateMatrixWorld(!0)}setLightingValues(t){for(const e of this.editorLights)e instanceof ba?e.intensity=t==="flat"?2:t==="outdoor"?1.15:1.7:e instanceof gr&&(e.intensity=t==="flat"?0:t==="outdoor"?2.2:2.4,e.color.set(16777215))}clearDiagnosticPresentation(){this.clearTopologyOverlay(),this.scene.overrideMaterial?.dispose(),this.scene.overrideMaterial=null;for(const t of this.helpers.splice(0)){t.removeFromParent();const e=t;e.geometry?.dispose();const i=e.material;Array.isArray(i)?i.forEach(s=>{s.dispose()}):i?.dispose()}}notify(){this.version++;for(const t of this.listeners)t()}}class fp{constructor(t){this.options=t}active=null;settling=!1;idleWaiters=new Set;begin(t){if(this.active||this.settling)return!1;try{const e=this.options.begin(t);return e?(this.active={pointerId:t.pointerId,gesture:e},!0):!1}catch(e){return this.options.reportError(e),!1}}update(t){if(!(!this.active||this.active.pointerId!==t.pointerId))try{this.active.gesture.update(t)}catch(e){this.cancelWithError(e)}}async commit(t){const e=this.take(t.pointerId);if(!e)return!1;this.settling=!0;try{return await e.commit(t),await this.options.persist(e.label),!0}catch(i){try{await e.cancel()}catch(s){return this.options.reportError({operationError:i,rollbackError:s}),!1}return this.options.reportError(i),!1}finally{this.settling=!1;for(const i of this.idleWaiters)i();this.idleWaiters.clear()}}async cancel(t){const e=this.take(t);if(!e)return!1;this.settling=!0;try{return await e.cancel(),!0}catch(i){return this.options.reportError(i),!1}finally{this.settling=!1;for(const i of this.idleWaiters)i();this.idleWaiters.clear()}}async settle(){this.active&&await this.cancel(),this.settling&&await new Promise(t=>this.idleWaiters.add(t))}hasActiveGesture(){return this.active!==null}take(t){if(!this.active||t!==void 0&&this.active.pointerId!==t)return null;const e=this.active.gesture;return this.active=null,e}async cancelWithError(t){const e=this.take();if(e){this.settling=!0;try{await e.cancel(),this.options.reportError(t)}catch(i){this.options.reportError({operationError:t,rollbackError:i})}finally{this.settling=!1;for(const i of this.idleWaiters)i();this.idleWaiters.clear()}}}}function Te(o){const t=xt(o,"authoringSubject");return t&&typeof t.label=="string"&&typeof t.kind=="string"?t:null}function Ko(o){return o.depthWrite===!1&&o.side===$h}function mp(o){const t=o.material;return t?Array.isArray(t)?t.length>0&&t.every(Ko):Ko(t):!1}function qa(o,t,e,i=()=>!1,s){const r=nc();if(!r)return[];const n=r.canvas.getBoundingClientRect();if(n.width<=0||n.height<=0||!Number.isFinite(t)||!Number.isFinite(e)||t<n.left||e<n.top||t>=n.left+n.width||e>=n.top+n.height)return[];const a=new Jt((t-n.left)/n.width*2-1,-((e-n.top)/n.height)*2+1),l=new Yt;l.layers.enableAll(),l.setFromCamera(a,r.camera);const h=new Set(s?.objects??o.objectMap.values()),d=[...h].filter(f=>{for(let m=f.parent;m;m=m.parent)if(h.has(m))return!1;return!0});for(const f of d)f.traverse(m=>{const y=m;y.isSkinnedMesh&&(y.boundingBox=null,y.boundingSphere=null)});const c=l.intersectObjects(d,!0),p=[],u=new Set;for(const f of c){if(ue(f.object)||mp(f.object))continue;let m=f.object,y=null;if(s)for(;m&&y===null;)y=s.idForObject3D(m),m=m.parent;else{const g=zl(m);y=g?Sn(g)??null:null}y!==null&&!i(y)&&!u.has(y)&&(u.add(y),p.push(y))}return gp(p,d,c.length,t,e),p}function gp(o,t,e,i,s){o.length>0||i===0&&s===0||console.info(`[viewport-pick] click selected nothing (candidates ${t.length}, rayHits ${e}, resolvedIds 0)`)}function yp(o,t,e,i=()=>!1,s){return qa(o,t,e,i,s)[0]??null}const ta={count:0,meshes:0,lights:0,instancedMeshes:0,instances:0};let ea=0;function _p(o){let t=0,e=0;for(const i of o.values()){const s=i.object;s.isInstancedMesh&&(t++,e+=typeof s.count=="number"?s.count:0)}return{instancedMeshes:t,instances:e}}function Za(o){let t=0,e=0;for(const i of o.values()){const s=i.object;s.isLight?e++:s.isMesh&&t++}return{count:o.size,meshes:t,lights:e,..._p(o)}}function vp(o,t){const e=new Map,i=[],s=t.skip??bs;t.begin?.(o);const r=(n,a,l,h)=>{if(s(n))return;const d=t.identify(n,{path:a,ownerId:l,ownedByAncestor:h});d!==null&&(pa(n,d),e.set(d,{object:n,id:d,parentId:l,childIds:[]}),l===null?i.push(d):e.get(l)?.childIds.push(d));const c=h||d!==null;n.children.forEach((p,u)=>{r(p,[...a,u],d??l,c)}),t.leave?.(n,d)};return o.children.forEach((n,a)=>{r(n,[a],null,!1)}),{nodes:e,rootIds:i,stats:Za(e)}}const xp="r3f:";function wp(o,t){return`${xp}${o}:${t}`}function Sp(o){return{project:t=>vp(t,{skip:e=>!!xt(e,"editorHelper")||e.isSkeletonHelper===!0,identify:(e,i)=>`source-object:${o}:${i.path.join(".")}`})}}function bp(o){const t=Te(o);return t?t.kind:or(o).length>0?"constraint-owner":Li(o)?"reflection-probe":o.isSkinnedMesh?"skinned-mesh":o.isBone?"bone":o.isLight?"light":o.isCamera?"camera":o.type==="Audio"||o.type==="PositionalAudio"||o.type==="AudioListener"?"audio":o.isMesh?"mesh":o.children.length>0?"group":"object"}function Mp(o,t){for(let e=o.parent;e!==null;e=e.parent)if(e===t)return!0;return!1}function ia(o,t){if(o===t)return!0;for(let e=o.parent;e!==null;e=e.parent)if(e===t)return!0;return!1}class Cp{constructor(t,e={}){this.identity=t,this.options=e}nodesById=new Map;objectsById=new Map;idsByObjectIndex=new Map;roots=[];walkStats=ta;project(t){if(!t)return this.nodesById=new Map,this.objectsById=new Map,this.idsByObjectIndex=new Map,this.roots=[],this.walkStats=ta,this.walkStats;const{nodes:e,rootIds:i,stats:s}=this.identity.project(t);return this.nodesById=e,this.objectsById=new Map([...e].map(([r,n])=>[r,n.object])),this.idsByObjectIndex=new Map([...e].map(([r,n])=>[n.object,r])),this.roots=i,this.walkStats=s,s}projectSubtrees(t,e){const i=this.identity.incremental;if(t===null||i?.kind!=="live-oid")return null;const s=e.filter((g,_)=>e.indexOf(g)===_&&!e.some(M=>M!==g&&Mp(g,M))),r=this.roots,n=new Set,a=new Set,l=new Set;for(const g of s)g.traverse(_=>{const M=this.idsByObjectIndex.get(_);if(M===void 0)return;const w=this.nodesById.get(M);w?.parentId!==null&&w?.parentId!==void 0&&l.add(w.parentId),n.add(M),this.nodesById.delete(M),this.objectsById.delete(M),this.idsByObjectIndex.delete(_)});const h=bs,d=(g,_)=>{const M=this.objectsById.get(g);return M===void 0||M===_},c=(g,_)=>{const M=Sn(g);if(M!==void 0&&d(M,g))return M;const w=Ol(g);if(w!==void 0){const C=wp(i.worldId,w);let x=0,b=co(C,x);for(;!d(b,g);)b=co(C,++x);return b}if(!_||xt(g,"authoringRoot")===!0){let C=`live:${i.worldId}:${ea++}`;for(;!d(C,g);)C=`live:${i.worldId}:${ea++}`;return C}return null},p=(g,_,M)=>{if(h(g))return;const w=c(g,M);w!==null&&(pa(g,w),this.nodesById.set(w,{object:g,id:w,parentId:_,childIds:[]}),this.objectsById.set(w,g),this.idsByObjectIndex.set(g,w),a.add(w),_!==null&&l.add(_));const C=w??_,x=M||w!==null;for(const b of g.children)p(b,C,x)};for(const g of s){if(!ia(g,t))continue;let _=g.parent,M=null;for(;_!==null&&_!==t;){const w=this.idsByObjectIndex.get(_);if(w!==void 0){M=w;break}_=_.parent}p(g,M,M!==null)}const u=g=>{const _=[],M=w=>{if(h(w))return;const C=this.idsByObjectIndex.get(w);if(C!==void 0){_.push(C);return}for(const x of w.children)M(x)};for(const w of g.children)M(w);return _};for(const g of l){const _=this.nodesById.get(g);_!==void 0&&_.childIds.splice(0,_.childIds.length,...u(_.object))}for(const g of a){const _=this.nodesById.get(g);_!==void 0&&_.childIds.splice(0,_.childIds.length,...u(_.object))}const f=u(t),m=this.roots.filter(g=>{const _=this.objectsById.get(g);return _!==void 0&&!ia(_,t)&&!n.has(g)});this.roots=[...f,...m],this.walkStats=Za(this.nodesById);const y=r.length!==this.roots.length||r.some((g,_)=>g!==this.roots[_]);return{removedIds:n,addedIds:a,changedParentIds:l,rootsChanged:y}}get nodes(){return this.nodesById}get objects(){return this.objectsById}get idsByObject(){return this.idsByObjectIndex}get rootIds(){return this.roots}get stats(){return this.walkStats}node(t){return this.nodesById.get(t)??null}rootNodes(){return this.roots.map(t=>this.nodesById.get(t)).filter(t=>t!==void 0)}objectOf(t){return this.objectsById.get(t)??null}idOf(t){return this.idsByObjectIndex.get(t)??null}childIdsOf(t){const e=[];for(const i of t){const s=this.idsByObjectIndex.get(i);s!==void 0&&e.push(s)}return e}objectMapSnapshot(){return new Map(this.objectsById)}pick(t,e,i,s){return yp(t,e,i,s,this.pickProjection())}candidates(t,e,i,s){return qa(t,e,i,s,this.pickProjection())}pickProjection(){if(this.options.pickScope!=="store-object-map")return{objects:this.objectsById.values(),idForObject3D:t=>this.idOf(t)}}}const sa=new v,ra=new wt,na=new v;function Pp(o){return o.matrixAutoUpdate===!1?(o.matrix.decompose(sa,ra,na),{position:sa.toArray(),quaternion:ra.toArray(),scale:na.toArray()}):{position:o.position.toArray(),quaternion:o.quaternion.toArray(),scale:o.scale.toArray()}}function Ap(o,t){return o.length===t.length&&o.every((e,i)=>e===t[i])}class Ep{constructor(t){this.options=t,this.selected=[...t.initial]}adopted=[];selected;current(){const t=[...this.options.store.selectedEntityIds].filter(this.options.owns);return Ap(t,this.adopted)||(this.adopted=t,this.selected=t,this.options.onChange?.(t)),[...this.selected]}publish(t){this.selected=[...t];const e=this.selected.filter(this.options.owns);this.adopted=e,this.options.onChange?.(e),this.options.store.selectMultiple(e)}}function Tp(o){if(!o)return{position:[0,0,0],rotation:[0,0,0,1],scale:[1,1,1]};const t=Pp(o);return{position:t.position,rotation:t.quaternion,scale:t.scale}}function ln(o){return o.type==="Object3D"&&o.name===""&&Te(o)===null&&o.userData.oid===void 0&&xt(o,"authoringInstance")===void 0&&xt(o,"authoringRoot")!==!0&&xt(o,"vgaiComponentRoot")===void 0}class zp{constructor(t){this.options=t,this.rootIdSet=new Set(t.rootIds)}rootIdSet;childObjects(t){return t.children.flatMap(e=>bs(e)?[]:ln(e)?this.childObjects(e):[e])}childIds(t){return this.options.projector.childIdsOf(this.childObjects(t))}rootObjects(){return this.options.rootIds.flatMap(t=>{const e=this.options.projector.objectOf(t);return e?ln(e)?this.childObjects(e):[e]:[]})}rootIds(){return this.options.projector.childIdsOf(this.rootObjects())}parentId(t){const{projector:e,scene:i,documentNodeId:s}=this.options,r=e.idOf(t);if(r!==null&&this.rootIdSet.has(r))return s;let n=t.parent;for(;n&&n!==i&&ln(n);)n=n.parent;return n&&n!==i?e.idOf(n)??s:s}node(t){const e=Te(t);return{id:this.options.projector.idOf(t),label:e?.label||t.name||t.type||"Object3D",role:"entity",kind:bp(t),...e?.typeLabel?{typeLabel:e.typeLabel}:{},parentId:this.parentId(t),childIds:this.childIds(t)}}}const oa=new WeakMap;function Op(o){let t=!1;if(o.traverse(s=>{xt(s,"gaussianSplat")&&(t=!0)}),t)return"Gaussian splat";const e=Il(o),i=Rl(o);return{static:"Static model",animated:"Animated model",rigged:"Rigged model",skinned:"Skinned model"}[kl(e,i)]}function aa(o){const t=o.material;return Array.isArray(t)?t[0]??null:t??null}function la(o){return o?.color??null}class Hn{constructor(t,e,i){if(this.store=t,this.scene=e,this.options=i,this.provenance=i.provenance??(i.documentKind==="asset"?{source:"document",label:"derived asset",detail:"Loaded from an ordinary project asset. Edit its source or import recipe."}:{source:"source-code",label:"source",detail:"Instantiated from project TypeScript. Edit source or exposed parameters, then rebuild."}),this.documentNodeId=`object3d-document:${i.documentId}`,this.projector=new Cp(Sp(i.documentId)),this.indexGraph(),i.hierarchyRoots&&new Set(i.hierarchyRoots).size!==i.hierarchyRoots.length)throw new Error(`Object3D document "${i.title}" declared the same hierarchy root twice.`);const s=new Set(i.hierarchyRoots??[]);for(const r of s){let n=r.parent;for(;n&&n!==e;){if(s.has(n))throw new Error(`Object3D document "${i.title}" declared nested hierarchy roots; roots must be non-overlapping.`);n=n.parent}}this.hierarchyRootIds=i.hierarchyRoots?i.hierarchyRoots.map(r=>{const n=this.idByObject.get(r);if(!n)throw new Error(`Object3D document "${i.title}" declared a hierarchy root outside its native graph.`);return n}):[...this.projector.rootIds],this.view=new zp({projector:this.projector,scene:e,documentNodeId:this.documentNodeId,rootIds:this.hierarchyRootIds}),this.selectionState=new Ep({store:t,owns:r=>this.byId.has(r),initial:[this.documentNodeId],onChange:r=>this.syncMarkedSelection(r)})}documentNodeId;projector;hierarchyRootIds;view;selectionState;markedSelection=new Set;capabilities={transform:!1,inspectorFields:!0,persist:!1};provenance;disposed=!1;dispose(){if(!this.disposed){this.disposed=!0;for(const t of this.watchedForStructure)t.removeEventListener("childadded",this.onStructureChanged),t.removeEventListener("childremoved",this.onStructureChanged);this.watchedForStructure=[]}}watchedForStructure=[];structureReindexQueued=!1;onStructureChanged=t=>{bs(t.child)||this.scheduleStructureReindex()};indexGraph(){this.projector.project(this.scene),this.watchStructure()}watchStructure(){const t=i=>i;for(const i of this.watchedForStructure)t(i).removeEventListener("childadded",this.onStructureChanged),t(i).removeEventListener("childremoved",this.onStructureChanged);this.watchedForStructure=[];const e=i=>{t(i).addEventListener("childadded",this.onStructureChanged),t(i).addEventListener("childremoved",this.onStructureChanged),this.watchedForStructure.push(i)};e(this.scene);for(const[,i]of this.byId)e(i)}scheduleStructureReindex(){this.disposed||this.structureReindexQueued||(this.structureReindexQueued=!0,queueMicrotask(()=>{if(this.structureReindexQueued=!1,this.disposed||(this.indexGraph(),this.store.scene!==this.scene))return;const t=this.store.objectMap;t.clear();for(const[i,s]of this.byId)t.set(i,s);const e=[...this.store.selectedEntityIds].filter(i=>i===this.documentNodeId||this.byId.has(i));e.length!==this.store.selectedEntityIds.size&&this.store.selectMultiple(e),this.store.notifyIngestObjectMapEdit()}))}get byId(){return this.projector.objects}get idByObject(){return this.projector.idsByObject}documentTypeLabel(){if(this.options.documentKind!=="asset")return;const t=this.scene.children.find(s=>this.idByObject.has(s))??null;if(!t)return;const e=oa.get(t);if(e!==void 0)return e;const i=Op(t);return oa.set(t,i),i}hierarchy={roots:()=>[this.hierarchy.node(this.documentNodeId)],node:t=>{if(t===this.documentNodeId){const i=this.documentTypeLabel();return{id:t,label:this.options.title,secondaryLabel:this.options.sourcePath,role:"document",kind:this.options.documentKind==="asset"?"model-asset":"three-source",...i?{typeLabel:i}:{},parentId:null,childIds:this.view.rootIds()}}const e=this.byId.get(t);return e?this.view.node(e):null},object3D:t=>this.byId.get(t)??null,idForObject3D:t=>this.idByObject.get(t)??null};selection={get:()=>this.selectionState.current(),set:t=>this.selectionState.publish(t.filter(e=>e===this.documentNodeId||this.byId.has(e)))};static READ_ONLY_REASON="This document shows what the module builds; its properties are read-only here. Edit the module.";readOnly=()=>({writable:!1,reason:Hn.READ_ONLY_REASON});transforms={get:t=>Tp(this.byId.get(t)??null),beginEdit:()=>{},apply:()=>{},endEdit:()=>{}};inspector={properties:t=>{if(t===this.documentNodeId)return this.options.audit===!1?[]:[{path:"name",label:"Name",type:"string",readonly:!0},{path:"source.path",label:"Source",type:"string",readonly:!0}];const e=this.byId.get(t);if(!e)return[];const i=Te(e);if(i?.fields)return i.fields().map(({value:l,...h})=>h);const s=[{path:"name",label:"Name",type:"string",readonly:!0},{path:"visible",label:"Visible",type:"boolean",readonly:!0},{path:"object.type",label:"Native type",type:"string",readonly:!0}],r=e;if(r.isMesh&&r.geometry){const l=r.geometry.getAttribute("position");s.push({path:"mesh.vertices",label:"Vertices",type:"number",readonly:!0,group:"Mesh"}),l&&s.push({path:"mesh.triangles",label:"Triangles",type:"number",readonly:!0,group:"Mesh"})}const n=aa(e);n&&(s.push({path:"material.type",label:"Material",type:"string",readonly:!0,group:"Material"}),la(n)&&s.push({path:"material.color",label:"Color",type:"color",readonly:!0,group:"Material"}));const a=e;return a.isSkinnedMesh&&a.skeleton&&s.push({path:"skin.bones",label:"Bones",type:"number",readonly:!0,group:"Skin"}),s},get:(t,e)=>{if(t===this.documentNodeId)return e==="name"?this.options.title:e==="source.path"?this.options.sourcePath:void 0;const i=this.byId.get(t);if(!i)return;const r=Te(i)?.fields?.().find(l=>l.path===e);if(r)return r.value();if(e==="name")return i.name||i.type;if(e==="visible")return i.visible;if(e==="object.type")return i.type;const n=i;if(e==="mesh.vertices")return n.geometry?.getAttribute("position")?.count??0;if(e==="mesh.triangles"){const l=n.geometry;return(l?.index?.count??l?.getAttribute("position")?.count??0)/3}const a=aa(i);if(e==="material.type")return a?.type;if(e==="material.color"){const l=la(a);return l?`#${l.getHexString()}`:void 0}if(e==="skin.bones")return i.skeleton?.bones.length??0},set:()=>{},editability:()=>this.readOnly()};subscribe(t){return this.store.subscribe(t)}get documentId(){return this.documentNodeId}get documentRootObject(){const t=this.hierarchy.node(this.documentNodeId)?.childIds[0];return t?this.byId.get(t)??null:null}syncMarkedSelection(t){const e=new Set(t.map(i=>this.byId.get(i)??null).filter(i=>i!==null).filter(i=>Te(i)?.selectionChanged!==void 0));for(const i of this.markedSelection)e.has(i)||Te(i)?.selectionChanged?.(!1);for(const i of e)this.markedSelection.has(i)||Te(i)?.selectionChanged?.(!0);this.markedSelection=e}}class Ip{constructor(t,e){this.frame=t,this.releaseRenderer=e,this.unsubscribeActivity=oc(()=>this.syncActivity())}rafId=0;running=!1;disposed=!1;active=!1;unsubscribeActivity;get isDisposed(){return this.disposed}get isRunning(){return this.running}setActive(t){this.disposed||(this.active=t,this.syncActivity())}syncActivity(){this.active&&kr()?this.start():this.stop()}redraw(){this.running&&!this.disposed&&kr()&&this.guardedFrame(performance.now())}dispose(){this.stop(),!this.disposed&&(this.disposed=!0,this.unsubscribeActivity(),this.releaseRenderer())}start(){this.disposed||this.running||(this.running=!0,this.guardedFrame(performance.now(),!0),!(!this.running||this.disposed)&&(this.rafId=requestAnimationFrame(this.tick)))}lastFrameFailure=null;guardedFrame(t,e=!1){try{this.frame(t,e),this.lastFrameFailure=null}catch(i){const s=i instanceof Error?i.message:String(i);s!==this.lastFrameFailure&&(this.lastFrameFailure=s,console.error("[document renderer] a frame threw; the loop continues:",i))}}stop(){this.running=!1,this.rafId!==0&&(cancelAnimationFrame(this.rafId),this.rafId=0)}tick=t=>{if(!(!this.running||this.disposed)){if(!kr()){this.stop();return}this.guardedFrame(t),!(!this.running||this.disposed)&&(this.rafId=requestAnimationFrame(this.tick))}}}const Rp=F.lazy(async()=>({default:(await Ss(()=>import("./stage-overlay-set-D7J-N5eX.js"),__vite__mapDeps([13,6,4,3,5,2,7,8,9,10,1,11,14,15,16,17,18,19]))).StageOverlaySet}));function kp(o){return T.jsx(F.Suspense,{fallback:null,children:T.jsx(Rp,{...o})})}const Fp=[.25,.5,1,2];function Bp(o,t){const e=Math.round(o*t);return`${o.toFixed(2)}s · f${e}`}function Np({transport:o}){const t=F.useSyncExternalStore(F.useCallback(c=>o?o.subscribe(c):()=>{},[o]),F.useCallback(()=>o?.snapshot()??null,[o]));if(!o||!t||t.activeSubject===null)return null;const e=t.driver==="world",i=t.playbackState==="playing",{start:s,end:r,fps:n,loop:a}=t.range,l=t.subjects.find(c=>c.id===t.activeSubject),h=t.subjects.length>1?t.subjects:null,d=o.activeClips();return T.jsxs("section",{"aria-label":"Transport","data-testid":"stage-transport-strip",style:{display:"flex",alignItems:"center",gap:"var(--vgai-space-2)",padding:"var(--vgai-space-1) var(--vgai-space-3)",borderTop:`var(--vgai-stroke-resting) solid ${Nt.boundary.default}`,background:Nt.surface.raised},children:[T.jsx(Ae,{size:"compact","aria-label":i?"Pause":"Play",disabled:e,onClick:()=>i?o.pause():o.play(),children:T.jsx(Ee,{icon:i?pe.transport.pause:pe.transport.play})}),T.jsx(Ae,{size:"compact","aria-label":"Stop",disabled:e,onClick:()=>o.stop(),children:T.jsx(Ee,{icon:pe.transport.stop})}),T.jsx(Fl,{"aria-label":"Playhead",type:"range",min:s,max:r,step:1/n,value:t.time,disabled:e,onChange:c=>o.seek(Number(c.target.value)),style:{flex:1}}),T.jsx(Xs,{as:"span",variant:"caption",children:Bp(t.time,n)}),h?T.jsx("select",{"aria-label":"Subject",value:t.activeSubject,disabled:e,onChange:c=>o.setActiveSubject(c.target.value),children:h.map(c=>T.jsx("option",{value:c.id,children:c.label},c.id))}):null,d?T.jsx("select",{"aria-label":"Clip",disabled:e,onChange:c=>o.setActiveClip(c.target.value),children:d.map(c=>T.jsx("option",{value:c.id,children:c.label},c.id))}):null,T.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"var(--vgai-space-1)"},children:[T.jsx("input",{type:"checkbox",checked:a,disabled:e,onChange:c=>o.setLoop(c.target.checked)}),T.jsx(Xs,{as:"span",variant:"caption",children:"Loop"})]}),T.jsx("select",{"aria-label":"Speed",value:String(t.timeScale),disabled:e,onChange:c=>o.setTimeScale(Number(c.target.value)),children:Fp.map(c=>T.jsxs("option",{value:String(c),children:[c,"×"]},c))}),e?T.jsx(Xs,{as:"span",variant:"caption",children:"The world is driving time (Play); pause the game to scrub"}):l?T.jsx(Xs,{as:"span",variant:"caption",children:l.label}):null]})}const wf=[.8,.5,-1],hn=new B(1975600),cn=new B(5004144);function Hp(){const o=typeof document>"u"?null:document.querySelector("[data-vgai-palette]");if(!o)return{bottom:hn.clone(),top:cn.clone()};const t=getComputedStyle(o),e=document.createElement("canvas");e.width=e.height=1;const i=e.getContext("2d"),s=(h,d)=>{const c=t.getPropertyValue(h).trim();if(!i||!c||!CSS.supports("color",c))return d.clone();i.fillStyle=d.getStyle(),i.fillRect(0,0,1,1),i.fillStyle=t.getPropertyValue("--vgai-surface-shell").trim(),i.fillRect(0,0,1,1),i.fillStyle=c,i.fillRect(0,0,1,1);const[p,u,f]=i.getImageData(0,0,1,1).data;return new B().setRGB(p/255,u/255,f/255,Ms)},r=s("--vgai-surface-panel",hn),n=s("--vgai-surface-raised",cn),a=r.lerp(hn,.25).lerp(new B(16777215),.03),l=n.lerp(cn,.25).lerp(new B(16777215),.04);return{bottom:a,top:l}}function Lp(o){if(typeof document>"u"||typeof MutationObserver>"u")return()=>{};const t=document.querySelector("[data-vgai-palette]");if(!t)return()=>{};const e=new MutationObserver(o);return e.observe(t,{attributes:!0,attributeFilter:["data-vgai-palette","data-vgai-material"]}),()=>e.disconnect()}function Qa(o=Hp()){const e=new Uint8Array(512),i=new B;for(let r=0;r<128;r++)i.copy(o.bottom).lerp(o.top,r/127).convertLinearToSRGB(),e[r*4]=Math.round(i.r*255),e[r*4+1]=Math.round(i.g*255),e[r*4+2]=Math.round(i.b*255),e[r*4+3]=255;const s=new Kh(e,1,128,tc);return s.colorSpace=Ms,s.magFilter=Ui,s.minFilter=Ui,s.needsUpdate=!0,s}function Dp(o){const t=Ie(o);if(t.isEmpty())return{size:50,centre:[0,0]};const e=Math.max(t.max.x-t.min.x,t.max.z-t.min.z);return{size:Math.min(Math.max(Math.ceil(e/10)*10+20,50),1e3),centre:[(t.min.x+t.max.x)/2,(t.min.z+t.max.z)/2]}}function Up(o){for(const t of[1,2,5,10])if(o/t<=60)return Math.round(o/t);return Math.round(o/10)}function Vp(o,t){const e=t/2,i=e*.55,s=e;o.onBeforeCompile=r=>{r.uniforms.uGridFadeStart={value:i},r.uniforms.uGridFadeEnd={value:s},r.vertexShader=r.vertexShader.replace("#include <common>",`#include <common>
1121
1121
  varying vec2 vGridPlanePosition;`).replace("#include <begin_vertex>",`#include <begin_vertex>
1122
1122
  vGridPlanePosition = position.xz;`),r.fragmentShader=r.fragmentShader.replace("#include <common>",`#include <common>
1123
1123
  varying vec2 vGridPlanePosition;
1124
1124
  uniform float uGridFadeStart;
1125
1125
  uniform float uGridFadeEnd;`).replace("#include <color_fragment>",`#include <color_fragment>
1126
- diffuseColor.a *= 1.0 - smoothstep(uGridFadeStart, uGridFadeEnd, length(vGridPlanePosition));`)},o.customProgramCacheKey=()=>`vgai-grid-fade:${i}:${s}`}const jp=.85;function Gp(o,t){const{environment:e,background:i=!0,keyLight:s=!0,grid:r=!1}=t,n=[],a=[];let l=null;if(e&&(o.environment=e.texture),i&&(l=Qa(),o.background=l),s){const u=new gr(16777215,1.9);u.name="vgai:standard-dressing-key",u.position.set(6,10,-4),u.castShadow=!0,Rt(u,"editorHelper",!0),o.add(u),n.push(u),a.push(u)}let h=null,d="";const c=u=>{if(!r)return;const{size:f,centre:m}=Dp(u),y=`${f}:${m.join(":")}`;if(y===d)return;d=y,h&&(h.removeFromParent(),h.dispose(),n.splice(n.indexOf(h),1));const g=new ec(f,Up(f),10066329,10066329);h=g;const _=g.material;_.transparent=!0,_.opacity=.35,_.depthWrite=!1,Vp(_,f),g.name="vgai:standard-dressing-grid",g.position.set(m[0],-.02,m[1]),g.layers.set(X),Rt(g,"editorHelper",!0),o.add(g),n.push(g)};c(t.content??o);let p=!1;return{backgroundTexture:l,lights:a,frameContent:c,dispose(){if(!p){p=!0;for(const u of n)u.removeFromParent(),u.dispose?.();e&&(o.environment===e.texture&&(o.environment=null),e.dispose()),l&&(o.background===l&&(o.background=null),l.dispose())}}}}const Xp=tp;function Wp(o){return mr(null,o)}const Jp=()=>()=>{},ha=()=>0,Yp=5,qp=58;function Zp({viewport:o,session:t,store:e,projection:i,displayName:s,objectName:r,statistics:n}){F.useSyncExternalStore(e.subscribe,e.getShellSnapshot??e.getSnapshot),F.useSyncExternalStore(t?.subscribe??Jp,t?.getSnapshot??ha,t?.getSnapshot??ha);const l=F.useSyncExternalStore(Wp,fa)?Nt.content.onAccent:Nt.content.primary;if(!o)return null;const h=Bl(o.camera.position.clone().sub(o.orbitControls.target))??"User",d=t?.projection()??i,c=`${h} ${d==="perspective"?"Perspective":"Orthographic"}`,p=e.selectedEntityId,u=(p===null?null:r(p))||null,f=u===null||u===s?s:`${s} | ${u}`,m=g=>{const _=o.renderCamera;if(_ instanceof pi){_.zoom=Math.max(.01,_.zoom/g),_.updateProjectionMatrix();return}const M=o.orbitControls.target;o.camera.position.sub(M).multiplyScalar(g).add(M),o.orbitControls.update()},y=g=>{g.preventDefault();const _=g.currentTarget;_.setPointerCapture(g.pointerId);let M=g.clientX,w=g.clientY;const C=new v,x=new v,b=A=>{const N=A.clientX-M,J=A.clientY-w;M=A.clientX,w=A.clientY;const $=o.camera,gt=o.orbitControls.target,Y=$.position.distanceTo(gt),K=Math.max(1,_.ownerDocument.defaultView?.innerHeight??1),lt=2*Y*Math.tan(Dt.degToRad($.fov/2))/K;C.setFromMatrixColumn($.matrixWorld,0).multiplyScalar(-N*lt),x.setFromMatrixColumn($.matrixWorld,1).multiplyScalar(J*lt),$.position.add(C).add(x),gt.add(C).add(x),o.orbitControls.update()},P=()=>{_.removeEventListener("pointermove",b),_.removeEventListener("pointerup",P),_.removeEventListener("pointercancel",P)};_.addEventListener("pointermove",b),_.addEventListener("pointerup",P),_.addEventListener("pointercancel",P)};return T.jsxs(T.Fragment,{children:[T.jsxs("div",{"data-testid":"viewport-view-text","aria-hidden":"true",style:{position:"absolute",top:"var(--vgai-space-3)",left:"calc(var(--vgai-space-4) + var(--vgai-control-comfortable-height) * 2 + var(--vgai-space-4))",display:"flex",flexDirection:"column",gap:"var(--vgai-space-1)",fontSize:"var(--vgai-font-sm)",color:l,textShadow:"var(--vgai-content-text-shadow, none)",pointerEvents:"none",userSelect:"none"},children:[T.jsx("span",{children:c}),T.jsx("span",{children:f}),n&&n.length>0?T.jsx("div",{"data-testid":"viewport-statistics",style:{display:"grid",gridTemplateColumns:`${qp}px auto`,rowGap:"var(--vgai-space-1)",marginTop:Nl[Yp]},children:n.map(g=>T.jsxs(F.Fragment,{children:[T.jsx("span",{children:g.label}),T.jsx("span",{children:g.value})]},g.id))}):null]}),T.jsxs("div",{"data-testid":"viewport-navigation",role:"toolbar","aria-label":"Navigation","aria-orientation":"vertical",className:"vgai-chrome-island vgai-viewport-navigation",style:{position:"absolute",top:Xp,right:"var(--vgai-space-6)",display:"flex",flexDirection:"column",gap:"var(--vgai-space-1)",padding:"var(--vgai-space-1) 0",borderRadius:"var(--vgai-radius-full)",background:"var(--vgai-island-surface, var(--vgai-surface-overlay))",pointerEvents:"auto"},children:[T.jsx(Ti,{text:"Zoom in",children:T.jsx(Ae,{size:"comfortable","aria-label":"Zoom in",onClick:()=>m(.8),children:T.jsx(Ee,{size:"2xl",icon:pe.viewport.zoomIn})})}),T.jsx(Ti,{text:"Zoom out",children:T.jsx(Ae,{size:"comfortable","aria-label":"Zoom out",onClick:()=>m(1.25),children:T.jsx(Ee,{size:"2xl",icon:pe.viewport.zoomOut})})}),T.jsx(Ti,{text:"Pan (drag)",children:T.jsx(Ae,{size:"comfortable","aria-label":"Pan the view",onPointerDown:y,children:T.jsx(Ee,{size:"2xl",icon:pe.viewport.pan})})}),T.jsx(Ti,{text:"Frame all",children:T.jsx(Ae,{size:"comfortable","aria-label":"Frame all",onClick:()=>{t?.frame()||o.focusOn(o.orbitControls.object)},children:T.jsx(Ee,{size:"2xl",icon:pe.viewport.frame})})}),T.jsx(Ti,{text:d==="perspective"?"Orthographic":"Perspective",children:T.jsx(Ae,{size:"comfortable","aria-label":"Toggle perspective and orthographic","aria-pressed":d==="orthographic",onClick:()=>{const g=d==="perspective"?"orthographic":"perspective";t?t.setProjection(g):o.setProjection(g)},children:T.jsx(Ee,{size:"2xl",icon:pe.viewport.projection})})})]})]})}const Qp="Preparing the viewport…";function $p({testId:o,children:t}){return T.jsx("div",{"data-testid":o,style:{position:"absolute",inset:0,padding:16,fontSize:12,color:Nt.content.muted,pointerEvents:"none"},children:t})}const Kp=F.lazy(async()=>({default:(await Ss(()=>import("./stage-keyboard-DzZMNYAr.js"),__vite__mapDeps([20,3,4,5,2,6,7,8,9,10,1,11]))).StageKeyboardBinding})),ca=()=>ph(),dn=12;function da(o){if(!o)return null;const t=new ie(new v(o.min[0],o.min[1],o.min[2]),new v(o.max[0],o.max[1],o.max[2]));return t.isEmpty()?null:t}function tf(o){return mr(null,o)}let ef=0;const Di=new Map;function sf(o){const t=Di.get(o)??[];let e=t.find(i=>!i.inUse);return e||(e={documentId:o,store:new ma,inUse:!1,source:null,camera:null,presentation:null,transport:null,contentSeconds:0,transportAdvances:0},t.push(e),Di.set(o,t)),e.inUse=!0,e}function ua(o){o.inUse=!1,queueMicrotask(()=>{if(o.inUse||Jl().some(i=>i.descriptor.id===o.documentId))return;o.source?.dispose(),o.source=null;const t=Di.get(o.documentId);if(!t)return;const e=t.filter(i=>i!==o||i.inUse);e.length>0?Di.set(o.documentId,e):Di.delete(o.documentId)})}function rf({canvasHostRef:o}){return T.jsx("div",{ref:o,style:{position:"absolute",inset:0}})}function nf(o,t,e,i,s){if(t==="inspector-preview"){const l=dh();return l.canvas.setAttribute("aria-label",`${e} authoring viewport`),o.appendChild(l.canvas),{canvas:l.canvas,renderer:l.renderer,lease:l}}const r=uh(i.width,i.height,s),{canvas:n,renderer:a}=r;return n.setAttribute("aria-label",`${e} authoring viewport`),o.appendChild(n),{canvas:n,renderer:a,lease:r}}class of{constructor(t,e,i){this.lane=t,this.surface=e,this.store=i??new ma,this.transport=new ch(this.store)}scene=new yr;store;cleanups=[];rendererSession=new Ip((t,e)=>this.frame?.(t,e),()=>{});viewport=null;session=null;dressing=null;defaultEnvironment=null;defaultBackground=null;adapter=null;content=null;frame=null;syncHostScene=null;presence=null;initialized=!1;contentSeconds=0;transportAdvances=0;users=0;closed=!1;released=!1;get isClosed(){return this.closed}transport;borrow(){this.users++;let t=!1;return()=>{t||(t=!0,this.users--,this.releaseIfClosed())}}close(){this.closed=!0,this.frame=null,this.syncHostScene=null,this.session?.setBeforeRender(null),this.session?.setPresentsFrames(!1),this.rendererSession.setActive(!1),this.content?.dispose(),this.transport.dispose(),this.releaseIfClosed()}releaseIfClosed(){if(!this.closed||this.users!==0||this.released)return;this.released=!0;const{lease:t,renderer:e,canvas:i}=this.surface;for(const s of[...this.cleanups.splice(0),()=>this.session?.dispose(),()=>this.viewport?.dispose(),()=>this.rendererSession.dispose(),()=>this.dressing?.dispose(),...t?[()=>t.release()]:[()=>e.dispose(),()=>e.forceContextLoss(),()=>i.remove()]])try{s()}catch(r){console.error("Object3D document cleanup failed.",r)}}}function $a({documentId:o,sourcePath:t,build:e,displayName:i="Source Object3D",background:s,cameraDirection:r,persistence:n,documentSource:a,authoring:l,interaction:h,selectionOutline:d=!0,active:c=!0,audit:p=!0,chromeless:u=!1,modelSource:f,assetType:m,sourceAuthoring:y,dressing:g,rendererLane:_="own",onOpenNode:M,frameBounds:w,openingFrameBounds:C,openingFit:x,statistics:b}){F.useEffect(()=>{if(!u)return Hl(o)},[o,u]);const P=Ll(),A=P??Wl(),N=A?Dl(A,o,u?"embedded":"document"):null,J=F.useSyncExternalStore(tf,fa),$=N!==null&&Ul(N,J),gt=F.useRef($);gt.current=$;const Y=N!==null&&Vl(N),K=F.useRef(Y);K.current=Y;const lt=N!==null&&jl(N),st=F.useRef(lt);st.current=lt;const ct=Gl(),tt=F.useRef(ct);tt.current=ct;const dt=F.useRef(null),ut=F.useRef(null),V=F.useRef(null),yt=F.useRef(null);(!yt.current||yt.current.documentId!==o)&&(yt.current&&ua(yt.current),yt.current=sf(o)),F.useEffect(()=>{const q=yt.current;return()=>ua(q)},[o]);const D=yt.current,Ft=c,[Pt,at]=F.useState(Ft);F.useEffect(()=>at(Ft),[Ft]);const Qe=F.useRef(d);F.useEffect(()=>{Qe.current=d;const q=V.current?.session;q&&(q.selectionOutlineEnabled=_!=="inspector-preview"&&d)},[d,_]);const $e=F.useRef(Promise.resolve()),ke=F.useRef(!1);F.useEffect(()=>{if(Pt)return re.current=!1,_e("building"),()=>{const q=V.current;q&&(ke.current=!me.current,D.camera=q.store.cameraPose,D.presentation=q.session?.presentation()??null,D.transport=q.transport.snapshot(),D.contentSeconds=q.contentSeconds,D.transportAdvances=q.transportAdvances),ye.current=null,Qt.current=null,ge.current=null,Fe.current=null,q?.close(),V.current=null}},[o,_,D,Pt]);const Ke=F.useRef(M);Ke.current=M;const ti=F.useRef(w);ti.current=w;const ei=F.useRef(C);ei.current=C;const me=F.useRef(c);me.current=c;const ii=F.useRef(c),si=F.useRef({build:e,sourcePath:t});F.useEffect(()=>{const q=si.current;si.current={build:e,sourcePath:t},!(q.build===e&&q.sourcePath===t)&&!Pt&&D.source&&(D.source.dispose(),D.source=null)},[e,D,t,Pt]);const Fe=F.useRef(null),re=F.useRef(!1),ge=F.useRef(null),ye=F.useRef(null),Qt=F.useRef(null),[ne,_t]=F.useState(null),[oe,_e]=F.useState("building"),[ve,Be]=F.useState("perspective"),[Ne,xe]=F.useState(null),et=F.useRef(null);et.current=Ne;const _r=r?.[0],vr=r?.[1],xr=r?.[2],Mi=f?.kind,wr=f?.kind==="project-file"?f.path:void 0,Ts=f?.kind==="entity"?f.entityId:void 0,Sr=g?.environment,Ln=g?.background,br=g?.keyLight,Mr=g?.grid,zs=g?.viewLocked,Dn=g?.toneMapping;c&&fh(o),F.useEffect(()=>{let q=!1;if(!Pt)return;const Pr=async()=>{for(await V.current?.content?.settle();uc();)await pc();if(q)return;const ht=dt.current,Vn=ut.current;if(!ht||!Vn)return;if(!e||t===void 0){_t("This stage shows `build` content and was given no `build()`/`sourcePath`.");return}let G;try{G=D.source??e(),D.source=null}catch(bt){_t(bt instanceof Error?bt.message:String(bt));return}try{V.current||(Yl(),V.current=new of(_,nf(Vn,_,i,{width:Math.max(1,ht.clientWidth),height:Math.max(1,ht.clientHeight)},()=>{at(!1),window.setTimeout(()=>{me.current&&at(!0)},0)}),D.store),V.current.contentSeconds=D.contentSeconds,V.current.transportAdvances=D.transportAdvances)}catch(bt){throw G.dispose(),bt}const S=V.current,el=S.borrow(),{renderer:St,canvas:Ut,lease:Ar}=S.surface,rt=S.store;u||(S.cleanups.push(ql(o,rt)),S.cleanups.push(Zl(o,S.transport)));const Is=uo();Is&&rt.attachHistory(Is);const il=_==="inspector-preview",ri=gt.current,jn=K.current,Gn=st.current,nt=new yr;Sr!==!1&&(nt.environmentIntensity=jp);const Rs=G.root.parent;nt.add(G.root),G.animations&&(G.root.animations=[...G.animations]);const Er={root:G.root,animations:G.root.animations};let Ci=null,Pi=null,ni=null,oi=null,Lt=null,ks=null,Fs=null,Bs=null,Ns=null,Hs=null,Xn=null,Wn=null,Jn=!1,Ls=!1,Ds=null;const Tr={scene:nt,settle:()=>Lt?.settle()??Promise.resolve(),dispose:()=>Ds||(Ls=!0,ks&&ht.removeEventListener("pointerdown",ks,!0),Fs&&ht.removeEventListener("pointermove",Fs,!0),Bs&&ht.removeEventListener("pointerup",Bs,!0),Ns&&ht.removeEventListener("pointercancel",Ns,!0),Hs&&window.removeEventListener("keydown",Hs),Ds=(async()=>{await Lt?.settle();const bt=[];for(const zr of[()=>oi?.dispose(),()=>Pi?.dispose?.(),()=>Ci?.dispose(),()=>nt.removeFromParent(),()=>{ke.current?D.source=G:G.dispose(),ke.current=!1},el])try{zr()}catch(ae){bt.push(ae)}bt.length&&console.error("Object3D source cleanup failed.",...bt)})(),Ds)};try{const bt=async R=>{try{const H=Er;if(a&&!n){if(!H)throw new Error("Project history is unavailable; the edit was not saved.");const z=uo();if(!z)throw new Error("Project history is unavailable; the edit was not saved.");const k=a.serialize(H);if(k===null)return _t(null),!1;const j=await ca().replaceSource(z,{file:a.path,source:k,label:R??a.label??`Edit ${i}`});return _t(null),j}if(!n)throw new Error("This Asset Lab document has no persistence binding.");if(!ni||!H)throw new Error("Project history is unavailable; the edit was not saved.");const{persisted:Z}=await(await ni).commit(H,R);return _t(null),Z}catch(H){throw _t(H instanceof Error?H.message:JSON.stringify(H)),H}};Ci=new Hn(rt,nt,{documentId:o,title:i,sourcePath:t,documentKind:Gn?"asset":"source",audit:p,...G.hierarchyRoots?{hierarchyRoots:G.hierarchyRoots}:{},...Mi==="project-file"&&wr?{modelSource:{kind:Mi,path:wr}}:Mi==="entity"&&Ts?{modelSource:{kind:Mi,entityId:Ts}}:{}});const zr={documentId:o,sourcePath:t,root:G.root,animations:G.root.animations,scene:nt,defaultAdapter:Ci,commit:bt};Pi=l?.(zr)??null,!Pi&&y&&(Pi=y({store:rt,scene:nt,...G.hierarchyRoots?{hierarchyRoots:G.hierarchyRoots}:{}}),Ci.dispose()),ni=n&&Is?ca().openPersistence({binding:n,document:Er,history:Is}):null,ni&&ni.catch(R=>{!Ls&&V.current?.content===Tr&&_t(R instanceof Error?R.message:JSON.stringify(R))});const ae=Pi?.adapter??Ci;if(!S.dressing){St.outputColorSpace=Ms,St.toneMapping=Dn??Aa,St.shadowMap.enabled=!0,St.shadowMap.type=ic,St.info.autoReset=!1,St.setPixelRatio(Math.min(window.devicePixelRatio,2)),ri&&St.setClearColor(0,0);const R=Sr===!1?null:Ar&&"environment"in Ar?Ar.environment():Ql(St),H=un(Ut);S.dressing=Gp(S.scene,{environment:R,background:!ri&&s===void 0&&Ln!==!1&&H.background===null,keyLight:br!==!1,grid:Mr===!0,content:G.root}),!ri&&s!==void 0?S.scene.background=new B(s):!ri&&H.background!==null&&(S.scene.background=new B(H.background)),S.defaultEnvironment=S.scene.environment,S.defaultBackground=S.scene.background,S.cleanups.push(()=>{S.defaultBackground instanceof yo&&S.defaultBackground!==S.dressing?.backgroundTexture&&S.defaultBackground.dispose()})}const Yn=(R,H)=>{const Z=S.adapter,z=S.viewport;if(!Z||!z)return null;const k=Ut.getBoundingClientRect(),j=new Jt((R-k.left)/Math.max(k.width,1)*2-1,-((H-k.top)/Math.max(k.height,1))*2+1),Mt=new Yt;Mt.layers.enableAll(),Mt.setFromCamera(j,S.session?.camera()??z.camera);for(const Se of Mt.intersectObjects([...rt.objectMap.values()],!0)){if(ue(Se.object))continue;let he=Se.object;for(;he;){const js=Z.hierarchy.idForObject3D?.(he);if(js)return js;he=he.parent}}return null};if(!S.viewport){S.viewport=new Nn(Ut,S.scene,rt,ht,{renderer:St,authoring:()=>S.adapter??ae,pick:Yn,publishPickContext:!1,onProjectionChange:Be,chromeInsetPx:u||jn?0:dn,lightRig:br!==!1}),Mr===!0&&S.viewport.grid.removeFromParent();const R=H=>{const Z=Yn(H.clientX,H.clientY),z=Z?S.adapter?.hierarchy.object3D?.(Z):null;z&&Ke.current?.(z)};ht.addEventListener("dblclick",R),S.cleanups.push(()=>ht.removeEventListener("dblclick",R))}const U=S.viewport;if(zs){const R=U.camera;S.scene.add(R),R.add(zs),S.cleanups.push(()=>{zs.removeFromParent(),R.removeFromParent()})}if(h){const R=new kt;R.name="__object3d_document_overlay",Rt(R,"editorHelper",!0),nt.add(R),oi=h.setup({root:G.root,scene:nt,renderer:St,overlay:R,camera:()=>S.session?.camera()??U.camera,writable:n!==void 0||a!==void 0});const H=z=>{const k=Ut.getBoundingClientRect(),j=new Jt((z.clientX-k.left)/Math.max(k.width,1)*2-1,-((z.clientY-k.top)/Math.max(k.height,1))*2+1),Mt=new Yt;return Mt.layers.enableAll(),Mt.setFromCamera(j,S.session?.camera()??U.camera),{pointerId:z.pointerId,button:z.button,buttons:z.buttons,clientX:z.clientX,clientY:z.clientY,altKey:z.altKey,ctrlKey:z.ctrlKey,metaKey:z.metaKey,shiftKey:z.shiftKey,ray:Mt.ray.clone(),hits:Mt.intersectObjects([G.root,R],!0)}};Lt=new fp({begin:z=>{if(!n&&!a)throw new Error("This Asset Lab document has no persistence binding; project gestures are read-only.");return oi.begin(z)},persist:async z=>{await bt(z)},reportError:z=>_t(z instanceof Error?z.message:JSON.stringify(z))});const Z=z=>{z.preventDefault(),z.stopPropagation()};ks=z=>{z.target instanceof Element&&z.target.closest('[role="alert"], [role="toolbar"]')!==null||Lt?.begin(H(z))&&(Z(z),z.isTrusted&&Ut.setPointerCapture?.(z.pointerId))},Fs=z=>{Lt?.hasActiveGesture()&&(Z(z),Lt.update(H(z)))},Bs=z=>{Lt?.hasActiveGesture()&&(Z(z),Ut.hasPointerCapture?.(z.pointerId)&&Ut.releasePointerCapture?.(z.pointerId),Lt.commit(H(z)))},Ns=z=>{Lt?.hasActiveGesture()&&(Z(z),Lt.cancel(z.pointerId))},Hs=z=>{z.key!=="Escape"||!Lt?.hasActiveGesture()||(z.preventDefault(),Lt.cancel())},Xn=()=>{ht.addEventListener("pointerdown",ks,!0),ht.addEventListener("pointermove",Fs,!0),ht.addEventListener("pointerup",Bs,!0),ht.addEventListener("pointercancel",Ns,!0),window.addEventListener("keydown",Hs)}}const He=S.content,qn=[...rt.selectedEntityIds],Ai=S.adapter,sl=new Map(rt.objectMap),Ei=S.session?.root,rl=S.frame,nl=S.syncHostScene,ol=ye.current,al=Qt.current,ll=ge.current,Zn=S.session?.neutralBackgroundTexture(),hl=S.dressing.lights.map(R=>R.visible),cl=S.cleanups.length,dl=S.initialized;if(Wn=()=>{nt.removeFromParent(),Rs&&Rs.add(G.root),He&&S.scene.add(He.scene),S.adapter=Ai,S.content=He,S.frame=rl,S.syncHostScene=nl,S.initialized=dl;for(const R of S.cleanups.splice(cl))R();!Ei&&S.session&&(S.session.dispose(),S.session=null),rt.objectMap.clear();for(const[R,H]of sl)rt.objectMap.set(R,H);He&&rt.bindScene(He.scene,St,U.batchedRenderer,U.camera),Ei&&Ai&&S.session?.replaceContent(Ei,Ai),ye.current=ol,Qt.current=al,ge.current=ll,et.current=Ai,xe(Ai),Zn!==void 0&&S.session?.setNeutralBackground(Zn),S.dressing?.lights.forEach((R,H)=>{R.visible=hl[H]??!0}),Ei&&S.dressing?.frameContent(Ei),rt.selectMultiple(qn),rt.notifyIngestObjectMapEdit()},He?.scene.removeFromParent(),S.scene.add(nt),S.adapter=ae,S.content=Tr,rt.bindScene(nt,St,U.batchedRenderer,U.camera),rt.setOrbitTarget(U.orbitControls.target),rt.objectMap.clear(),nt.traverse(R=>{const H=ae.hierarchy.idForObject3D?.(R);H&&rt.objectMap.set(H,R)}),S.session)S.session.replaceContent(G.root,ae);else{const R=da(ti.current),H=da(ei.current)??R;if(H||U.focusOn(G.root),_r!==void 0&&vr!==void 0&&xr!==void 0){const Z=H??Ie(G.root),z=Z.getCenter(new v),k=new v(_r,vr,xr).normalize(),j=Xe(Z,U.camera,k)*Math.min(10,Math.max(.1,x??1));U.camera.position.copy(z).add(k.multiplyScalar(j)),U.orbitControls.target.copy(z)}if(S.session=new pp(o,G.root,S.scene,St,U,S.dressing.lights,ae,ri?null:s===void 0?S.dressing.backgroundTexture:new B(s),R),S.session.selectionOutlineEnabled=!il&&Qe.current,!ri&&s===void 0&&S.dressing.backgroundTexture){const Z=S.session;S.cleanups.push(Lp(()=>{const z=un(Ut).background;if(z!==null){S.scene.background=new B(z);return}const k=S.defaultBackground;S.defaultBackground=Qa(),Z.neutralBackgroundTexture()===k&&Z.setNeutralBackground(S.defaultBackground),k instanceof yo&&k!==S.dressing?.backgroundTexture&&k.dispose()}))}}const Us=D.camera;Us&&(U.setProjection(ve),U.setPose(Us.position,Us.target,Us.fov||void 0),D.camera=null);const pt=S.session;ye.current=Er,Qt.current=ni,ge.current=oi,et.current=ae,xe(ae);let Qn=!1;G.root.traverse(R=>{R.isLight&&(Qn=!0)});for(const R of S.dressing.lights)R.visible=!Qn;S.dressing.frameContent(G.root),rt.selectMultiple(qn.filter(R=>rt.objectMap.has(R))),rt.notifyIngestObjectMapEdit(),pt.syncSelectionPresentation(),Xn?.(),_t(null),u||po(o);let Vs=nt.background;pt.setNeutralBackground(Vs??S.defaultBackground);const le=D.presentation;le&&(pt.setMode(le.mode),pt.setGrid(le.grid),pt.setBackground(le.background),pt.setExposure(le.exposure),pt.setProjection(le.projection),pt.setLighting(le.lighting),pt.setSkeleton(le.skeleton),pt.setBounds(le.bounds),D.presentation=null);const ul=()=>{S.scene.environment=nt.environment??S.defaultEnvironment,S.scene.fog=nt.fog,S.scene.environmentIntensity=nt.environmentIntensity,S.scene.environmentRotation.copy(nt.environmentRotation),S.scene.backgroundIntensity=nt.backgroundIntensity,S.scene.backgroundBlurriness=nt.backgroundBlurriness,S.scene.backgroundRotation.copy(nt.backgroundRotation),Vs!==nt.background&&(Vs=nt.background,pt.setNeutralBackground(Vs??S.defaultBackground))};S.syncHostScene=ul,pt.setBeforeRender(()=>S.syncHostScene?.()),pt.setPresentsFrames(!0);const pl=R=>{Ls||!(R>0)||!Number.isFinite(R)||(S.contentSeconds+=R,S.transportAdvances++,G.update?.(R))},fl=hc(G.root,S.transport);S.cleanups.push(()=>fl.dispose());const we=D.transport;we&&(we.activeSubject&&S.transport.setActiveSubject(we.activeSubject),S.transport.setLoop(we.range.loop),S.transport.setTimeScale(we.timeScale),S.transport.seek(we.time),we.playbackState==="playing"?S.transport.play():we.playbackState==="paused"&&S.transport.pause(),D.transport=null);let Or=performance.now();const ml=(R,H)=>{if(Ls||!St||!U)return;const Z=St,z=U,k=pt?.profiler;k?.beginFrame(),H&&(Or=R);const j=Math.min((R-Or)/1e3,.1);Or=R,k?.beginPhase();const Mt=S.transport.tick(j);Mt>0&&pl(Mt),oi?.prepareFrame?.(j),oi?.update?.(j),k?.endPhase("animation"),k?.beginPhase(),S.presence?.syncMarkers(j),U.update(j),u||$l(o,j),U.batchedRenderer.update(j),k?.endPhase("editor"),k?.beginPhase(),Z.info.reset();const Se=!re.current&&Kl()===o;Se&&th(o);const he=Se?Date.now():0,js=S.scene.overrideMaterial,$n=pt.presentation().mode;$n!=="uv"&&$n!=="vertex-colors"&&(S.scene.overrideMaterial=nt.overrideMaterial);try{z.renderWithInfrastructure(()=>{pt.renderViewport(j),z.renderViewCube(Z)})}finally{S.scene.overrideMaterial=js}pt.servePresentedFrame(),re.current||(re.current=!0,Se&&eh("first-render",Date.now()-he),ih(o),_e("ready")),k?.reportRender({gpuMs:null,drawCalls:Z.info.render.calls,triangles:Z.info.render.triangles,geometries:Z.info.memory.geometries,textures:Z.info.memory.textures}),k?.endPhase("render"),k?.endFrame();const Vt=tt.current;if(Vt&&P&&sh(P)===rt){const ai=pt.cameraPose();Vt.frameTime=j*1e3,Vt.fps=j>0?1/j:0,Vt.drawCalls=Z.info.render.calls,Vt.triangles=Z.info.render.triangles,Vt.cameraPosition.x=ai.position[0],Vt.cameraPosition.y=ai.position[1],Vt.cameraPosition.z=ai.position[2],Vt.cameraTarget.x=ai.target[0],Vt.cameraTarget.y=ai.target[1],Vt.cameraTarget.z=ai.target[2]}};if(S.frame=ml,Fe.current=S.rendererSession,!S.initialized){u||(S.cleanups.push(rh({camera:U.camera,orbit:U.orbitControls,scene:S.scene},()=>null,(k,j)=>U.setHelper(k,j),{documentId:o})),Ss(()=>import("./stage-presence-markers-BUaSzKCv.js"),__vite__mapDeps([21,6,4,3,5,7,8,2,9,10,1,11])).then(k=>{if(S.isClosed||V.current!==S||S.presence)return;const j=k.bindStagePresenceMarkers({scene:S.scene,store:rt,documentId:o,container:ht,canvas:Ut,viewport:U,readVisibleCameraPose:()=>{const Mt=S.session?.camera()??U.renderCamera,Se=Mt.getWorldPosition(new v),he=Mt.fov;return{position:Se,target:U.orbitControls.target,fov:typeof he=="number"?he:0}}});S.presence=j,S.cleanups.push(()=>j.dispose())}),S.cleanups.push(nh(pt)),S.cleanups.push(oh({id:o,label:i,kind:Gn?"asset":"source",profiler:pt.profiler}))),!u&&!jn&&S.cleanups.push(ah(o,()=>({adapter:S.adapter,nodeId:S.adapter?.selection?.get()[0]??null})));const R=u?`${o}#chromeless-${++ef}`:o;S.cleanups.push(lh({id:R,label:i,contentClock:()=>S.contentSeconds,transportAdvances:()=>S.transportAdvances})),S.cleanups.push(rt.onViewportAction(k=>{switch(k.type){case"focus-selection":case"focus-scene":!S.session?.frame()&&S.session?.root&&U.focusOn(S.session.root);break;case"focus-entity":{const j=S.adapter?.hierarchy.object3D?.(k.id)??null;j&&U.focusOn(j);break}case"snap-selection-to-floor":U.snapSelectionToFloor();break;case"set-view-preset":U.setViewPreset(k.preset);break;case"set-camera-pose":U.setPose(k.position,k.target,k.fov);break}}));let H="";S.cleanups.push(rt.subscribe(()=>{U.objectMap=rt.objectMap,U.syncFromStore(),S.session?.syncSelectionPresentation();const k=(S.adapter?.selection?.get()??[]).join("\0");k!==H&&(H=k,u||po(o))}));const Z=()=>{const k=Math.max(1,ht.clientWidth),j=Math.max(1,ht.clientHeight),Mt=St.getPixelRatio();(Ut.width!==Math.floor(k*Mt)||Ut.height!==Math.floor(j*Mt))&&St.setSize(k,j,!1),U.resize(k,j),S.session?.resize(k,j),S.rendererSession.redraw()},z=new ResizeObserver(Z);z.observe(ht),S.cleanups.push(()=>z.disconnect()),Z(),S.initialized=!0,hh()}U.objectMap=rt.objectMap,U.syncFromStore(),S.rendererSession.setActive(me.current),S.rendererSession.redraw(),Jn=!0,He?.dispose()}catch(bt){if(!Jn)try{Wn?.()}finally{Rs&&G.root.parent===nt&&Rs.add(G.root),Tr.dispose()}console.error(`[object3d document] ${i}: source update failed`,bt),_t(bt instanceof Error?bt.message:String(bt))}},tl=$e.current.then(Pr);return $e.current=tl.catch(ht=>{q||_t(ht instanceof Error?ht.message:String(ht))}),()=>{q=!0}},[l,s,e,_r,vr,xr,i,o,$,Ln,Sr,Mr,br,zs,Dn,u,Ts,Mi,wr,h,n,a,_,D,Pt,y,t]),F.useEffect(()=>{const q=Fe.current,Pr=c&&!ii.current;ii.current=c,q&&(Pr&&(re.current=!1,mh(o)),q.setActive(c))},[c,o]);const Os=V.current,Cr=oe==="ready"&&Os?.viewport?{store:Os.store,viewport:Os.viewport,canvas:Os.surface.canvas}:null,Ka=F.useCallback(()=>{const q=et.current;return q?{adapter:q,nodeId:q.selection?.get()[0]??q.hierarchy.roots()[0]?.id??null}:null},[]),Un=T.jsx("div",{"data-testid":"tool-object3d-authoring","data-vgai-chromeless":u||void 0,className:$?"vgai-object3d-studio-stage":void 0,style:{position:u||Y?"relative":"absolute",...u?{width:"100%",height:"100%"}:Y?{flex:1,minHeight:0}:{inset:-dn},overflow:"hidden",background:$?void 0:Nt.surface.raised,pointerEvents:"auto"},children:T.jsxs("div",{ref:dt,style:{position:"absolute",inset:0,minHeight:0,overflow:"hidden"},children:[T.jsx(rf,{canvasHostRef:ut}),c&&Cr&&!u?T.jsx(F.Suspense,{fallback:null,children:T.jsx(Kp,{stage:Cr})}):null,P&&!u?T.jsx(kp,{store:P,documentId:o,stage:Cr,active:c,chrome:"document"}):null,ne&&T.jsx("div",{role:"alert",style:{position:"absolute",insetInline:0,top:0,display:"flex",justifyContent:"center",padding:"var(--vgai-space-3)",pointerEvents:"none"},children:T.jsxs("div",{className:"vgai-chrome-island",style:{display:"flex",alignItems:"center",gap:"var(--vgai-space-3)",maxWidth:"80%",padding:"var(--vgai-space-2) var(--vgai-space-3)",borderRadius:"var(--vgai-radius-md)",border:`var(--vgai-stroke-resting) solid ${Nt.semantic.danger}`,background:Nt.surface.raised,color:Nt.semantic.danger,pointerEvents:"auto"},children:[T.jsx("span",{children:ne}),T.jsx(Ae,{size:"compact","aria-label":"Dismiss",onClick:()=>_t(null),"data-testid":"object3d-document-error-dismiss",children:T.jsx(Ee,{icon:pe.action.close})})]})}),!ne&&oe==="building"&&T.jsx($p,{testId:"object3d-document-status",children:Qp}),T.jsx("div",{style:{position:"absolute",inset:u||Y?0:dn,pointerEvents:"none"},children:!u&&oe==="ready"&&V.current&&T.jsx(Zp,{viewport:V.current.viewport,session:V.current.session,store:V.current.store,projection:ve,displayName:i,...b?{statistics:b}:{},objectName:q=>V.current?.adapter?.hierarchy.object3D?.(q)?.name??V.current?.store.objectMap.get(q)?.name??null})})]})});return Y?T.jsx(Xl,{documentId:o,active:c,type:m??(Ts?"entity":"model"),title:i,status:t,selection:Ka,fill:!0,children:T.jsxs("div",{className:"vgai-object3d-asset-workspace",children:[Un,T.jsx(Np,{transport:V.current?.transport??null})]})}):Un}function af(o){return T.jsx($a,{...o})}const Sf=Object.freeze(Object.defineProperty({__proto__:null,Object3DDocumentViewport:$a,ToolObject3DAuthoring:af},Symbol.toStringTag,{value:"Module"}));export{On as C,cr as G,$a as O,vf as Q,wf as S,L as V,$p as a,Qp as b,Sf as c,Wo as o,xf as s};
1126
+ diffuseColor.a *= 1.0 - smoothstep(uGridFadeStart, uGridFadeEnd, length(vGridPlanePosition));`)},o.customProgramCacheKey=()=>`vgai-grid-fade:${i}:${s}`}const jp=.85;function Gp(o,t){const{environment:e,background:i=!0,keyLight:s=!0,grid:r=!1}=t,n=[],a=[];let l=null;if(e&&(o.environment=e.texture),i&&(l=Qa(),o.background=l),s){const u=new gr(16777215,1.9);u.name="vgai:standard-dressing-key",u.position.set(6,10,-4),u.castShadow=!0,Rt(u,"editorHelper",!0),o.add(u),n.push(u),a.push(u)}let h=null,d="";const c=u=>{if(!r)return;const{size:f,centre:m}=Dp(u),y=`${f}:${m.join(":")}`;if(y===d)return;d=y,h&&(h.removeFromParent(),h.dispose(),n.splice(n.indexOf(h),1));const g=new ec(f,Up(f),10066329,10066329);h=g;const _=g.material;_.transparent=!0,_.opacity=.35,_.depthWrite=!1,Vp(_,f),g.name="vgai:standard-dressing-grid",g.position.set(m[0],-.02,m[1]),g.layers.set(X),Rt(g,"editorHelper",!0),o.add(g),n.push(g)};c(t.content??o);let p=!1;return{backgroundTexture:l,lights:a,frameContent:c,dispose(){if(!p){p=!0;for(const u of n)u.removeFromParent(),u.dispose?.();e&&(o.environment===e.texture&&(o.environment=null),e.dispose()),l&&(o.background===l&&(o.background=null),l.dispose())}}}}const Xp=tp;function Wp(o){return mr(null,o)}const Jp=()=>()=>{},ha=()=>0,Yp=5,qp=58;function Zp({viewport:o,session:t,store:e,projection:i,displayName:s,objectName:r,statistics:n}){F.useSyncExternalStore(e.subscribe,e.getShellSnapshot??e.getSnapshot),F.useSyncExternalStore(t?.subscribe??Jp,t?.getSnapshot??ha,t?.getSnapshot??ha);const l=F.useSyncExternalStore(Wp,fa)?Nt.content.onAccent:Nt.content.primary;if(!o)return null;const h=Bl(o.camera.position.clone().sub(o.orbitControls.target))??"User",d=t?.projection()??i,c=`${h} ${d==="perspective"?"Perspective":"Orthographic"}`,p=e.selectedEntityId,u=(p===null?null:r(p))||null,f=u===null||u===s?s:`${s} | ${u}`,m=g=>{const _=o.renderCamera;if(_ instanceof pi){_.zoom=Math.max(.01,_.zoom/g),_.updateProjectionMatrix();return}const M=o.orbitControls.target;o.camera.position.sub(M).multiplyScalar(g).add(M),o.orbitControls.update()},y=g=>{g.preventDefault();const _=g.currentTarget;_.setPointerCapture(g.pointerId);let M=g.clientX,w=g.clientY;const C=new v,x=new v,b=A=>{const N=A.clientX-M,J=A.clientY-w;M=A.clientX,w=A.clientY;const $=o.camera,gt=o.orbitControls.target,Y=$.position.distanceTo(gt),K=Math.max(1,_.ownerDocument.defaultView?.innerHeight??1),lt=2*Y*Math.tan(Dt.degToRad($.fov/2))/K;C.setFromMatrixColumn($.matrixWorld,0).multiplyScalar(-N*lt),x.setFromMatrixColumn($.matrixWorld,1).multiplyScalar(J*lt),$.position.add(C).add(x),gt.add(C).add(x),o.orbitControls.update()},P=()=>{_.removeEventListener("pointermove",b),_.removeEventListener("pointerup",P),_.removeEventListener("pointercancel",P)};_.addEventListener("pointermove",b),_.addEventListener("pointerup",P),_.addEventListener("pointercancel",P)};return T.jsxs(T.Fragment,{children:[T.jsxs("div",{"data-testid":"viewport-view-text","aria-hidden":"true",style:{position:"absolute",top:"var(--vgai-space-3)",left:"calc(var(--vgai-space-4) + var(--vgai-control-comfortable-height) * 2 + var(--vgai-space-4))",display:"flex",flexDirection:"column",gap:"var(--vgai-space-1)",fontSize:"var(--vgai-font-sm)",color:l,textShadow:"var(--vgai-content-text-shadow, none)",pointerEvents:"none",userSelect:"none"},children:[T.jsx("span",{children:c}),T.jsx("span",{children:f}),n&&n.length>0?T.jsx("div",{"data-testid":"viewport-statistics",style:{display:"grid",gridTemplateColumns:`${qp}px auto`,rowGap:"var(--vgai-space-1)",marginTop:Nl[Yp]},children:n.map(g=>T.jsxs(F.Fragment,{children:[T.jsx("span",{children:g.label}),T.jsx("span",{children:g.value})]},g.id))}):null]}),T.jsxs("div",{"data-testid":"viewport-navigation",role:"toolbar","aria-label":"Navigation","aria-orientation":"vertical",className:"vgai-chrome-island vgai-viewport-navigation",style:{position:"absolute",top:Xp,right:"var(--vgai-space-6)",display:"flex",flexDirection:"column",gap:"var(--vgai-space-1)",padding:"var(--vgai-space-1) 0",borderRadius:"var(--vgai-radius-full)",background:"var(--vgai-island-surface, var(--vgai-surface-overlay))",pointerEvents:"auto"},children:[T.jsx(Ti,{text:"Zoom in",children:T.jsx(Ae,{size:"comfortable","aria-label":"Zoom in",onClick:()=>m(.8),children:T.jsx(Ee,{size:"2xl",icon:pe.viewport.zoomIn})})}),T.jsx(Ti,{text:"Zoom out",children:T.jsx(Ae,{size:"comfortable","aria-label":"Zoom out",onClick:()=>m(1.25),children:T.jsx(Ee,{size:"2xl",icon:pe.viewport.zoomOut})})}),T.jsx(Ti,{text:"Pan (drag)",children:T.jsx(Ae,{size:"comfortable","aria-label":"Pan the view",onPointerDown:y,children:T.jsx(Ee,{size:"2xl",icon:pe.viewport.pan})})}),T.jsx(Ti,{text:"Frame all",children:T.jsx(Ae,{size:"comfortable","aria-label":"Frame all",onClick:()=>{t?.frame()||o.focusOn(o.orbitControls.object)},children:T.jsx(Ee,{size:"2xl",icon:pe.viewport.frame})})}),T.jsx(Ti,{text:d==="perspective"?"Orthographic":"Perspective",children:T.jsx(Ae,{size:"comfortable","aria-label":"Toggle perspective and orthographic","aria-pressed":d==="orthographic",onClick:()=>{const g=d==="perspective"?"orthographic":"perspective";t?t.setProjection(g):o.setProjection(g)},children:T.jsx(Ee,{size:"2xl",icon:pe.viewport.projection})})})]})]})}const Qp="Preparing the viewport…";function $p({testId:o,children:t}){return T.jsx("div",{"data-testid":o,style:{position:"absolute",inset:0,padding:16,fontSize:12,color:Nt.content.muted,pointerEvents:"none"},children:t})}const Kp=F.lazy(async()=>({default:(await Ss(()=>import("./stage-keyboard-C9wzGFxu.js"),__vite__mapDeps([20,3,4,5,2,6,7,8,9,10,1,11]))).StageKeyboardBinding})),ca=()=>ph(),dn=12;function da(o){if(!o)return null;const t=new ie(new v(o.min[0],o.min[1],o.min[2]),new v(o.max[0],o.max[1],o.max[2]));return t.isEmpty()?null:t}function tf(o){return mr(null,o)}let ef=0;const Di=new Map;function sf(o){const t=Di.get(o)??[];let e=t.find(i=>!i.inUse);return e||(e={documentId:o,store:new ma,inUse:!1,source:null,camera:null,presentation:null,transport:null,contentSeconds:0,transportAdvances:0},t.push(e),Di.set(o,t)),e.inUse=!0,e}function ua(o){o.inUse=!1,queueMicrotask(()=>{if(o.inUse||Jl().some(i=>i.descriptor.id===o.documentId))return;o.source?.dispose(),o.source=null;const t=Di.get(o.documentId);if(!t)return;const e=t.filter(i=>i!==o||i.inUse);e.length>0?Di.set(o.documentId,e):Di.delete(o.documentId)})}function rf({canvasHostRef:o}){return T.jsx("div",{ref:o,style:{position:"absolute",inset:0}})}function nf(o,t,e,i,s){if(t==="inspector-preview"){const l=dh();return l.canvas.setAttribute("aria-label",`${e} authoring viewport`),o.appendChild(l.canvas),{canvas:l.canvas,renderer:l.renderer,lease:l}}const r=uh(i.width,i.height,s),{canvas:n,renderer:a}=r;return n.setAttribute("aria-label",`${e} authoring viewport`),o.appendChild(n),{canvas:n,renderer:a,lease:r}}class of{constructor(t,e,i){this.lane=t,this.surface=e,this.store=i??new ma,this.transport=new ch(this.store)}scene=new yr;store;cleanups=[];rendererSession=new Ip((t,e)=>this.frame?.(t,e),()=>{});viewport=null;session=null;dressing=null;defaultEnvironment=null;defaultBackground=null;adapter=null;content=null;frame=null;syncHostScene=null;presence=null;initialized=!1;contentSeconds=0;transportAdvances=0;users=0;closed=!1;released=!1;get isClosed(){return this.closed}transport;borrow(){this.users++;let t=!1;return()=>{t||(t=!0,this.users--,this.releaseIfClosed())}}close(){this.closed=!0,this.frame=null,this.syncHostScene=null,this.session?.setBeforeRender(null),this.session?.setPresentsFrames(!1),this.rendererSession.setActive(!1),this.content?.dispose(),this.transport.dispose(),this.releaseIfClosed()}releaseIfClosed(){if(!this.closed||this.users!==0||this.released)return;this.released=!0;const{lease:t,renderer:e,canvas:i}=this.surface;for(const s of[...this.cleanups.splice(0),()=>this.session?.dispose(),()=>this.viewport?.dispose(),()=>this.rendererSession.dispose(),()=>this.dressing?.dispose(),...t?[()=>t.release()]:[()=>e.dispose(),()=>e.forceContextLoss(),()=>i.remove()]])try{s()}catch(r){console.error("Object3D document cleanup failed.",r)}}}function $a({documentId:o,sourcePath:t,build:e,displayName:i="Source Object3D",background:s,cameraDirection:r,persistence:n,documentSource:a,authoring:l,interaction:h,selectionOutline:d=!0,active:c=!0,audit:p=!0,chromeless:u=!1,modelSource:f,assetType:m,sourceAuthoring:y,dressing:g,rendererLane:_="own",onOpenNode:M,frameBounds:w,openingFrameBounds:C,openingFit:x,statistics:b}){F.useEffect(()=>{if(!u)return Hl(o)},[o,u]);const P=Ll(),A=P??Wl(),N=A?Dl(A,o,u?"embedded":"document"):null,J=F.useSyncExternalStore(tf,fa),$=N!==null&&Ul(N,J),gt=F.useRef($);gt.current=$;const Y=N!==null&&Vl(N),K=F.useRef(Y);K.current=Y;const lt=N!==null&&jl(N),st=F.useRef(lt);st.current=lt;const ct=Gl(),tt=F.useRef(ct);tt.current=ct;const dt=F.useRef(null),ut=F.useRef(null),V=F.useRef(null),yt=F.useRef(null);(!yt.current||yt.current.documentId!==o)&&(yt.current&&ua(yt.current),yt.current=sf(o)),F.useEffect(()=>{const q=yt.current;return()=>ua(q)},[o]);const D=yt.current,Ft=c,[Pt,at]=F.useState(Ft);F.useEffect(()=>at(Ft),[Ft]);const Qe=F.useRef(d);F.useEffect(()=>{Qe.current=d;const q=V.current?.session;q&&(q.selectionOutlineEnabled=_!=="inspector-preview"&&d)},[d,_]);const $e=F.useRef(Promise.resolve()),ke=F.useRef(!1);F.useEffect(()=>{if(Pt)return re.current=!1,_e("building"),()=>{const q=V.current;q&&(ke.current=!me.current,D.camera=q.store.cameraPose,D.presentation=q.session?.presentation()??null,D.transport=q.transport.snapshot(),D.contentSeconds=q.contentSeconds,D.transportAdvances=q.transportAdvances),ye.current=null,Qt.current=null,ge.current=null,Fe.current=null,q?.close(),V.current=null}},[o,_,D,Pt]);const Ke=F.useRef(M);Ke.current=M;const ti=F.useRef(w);ti.current=w;const ei=F.useRef(C);ei.current=C;const me=F.useRef(c);me.current=c;const ii=F.useRef(c),si=F.useRef({build:e,sourcePath:t});F.useEffect(()=>{const q=si.current;si.current={build:e,sourcePath:t},!(q.build===e&&q.sourcePath===t)&&!Pt&&D.source&&(D.source.dispose(),D.source=null)},[e,D,t,Pt]);const Fe=F.useRef(null),re=F.useRef(!1),ge=F.useRef(null),ye=F.useRef(null),Qt=F.useRef(null),[ne,_t]=F.useState(null),[oe,_e]=F.useState("building"),[ve,Be]=F.useState("perspective"),[Ne,xe]=F.useState(null),et=F.useRef(null);et.current=Ne;const _r=r?.[0],vr=r?.[1],xr=r?.[2],Mi=f?.kind,wr=f?.kind==="project-file"?f.path:void 0,Ts=f?.kind==="entity"?f.entityId:void 0,Sr=g?.environment,Ln=g?.background,br=g?.keyLight,Mr=g?.grid,zs=g?.viewLocked,Dn=g?.toneMapping;c&&fh(o),F.useEffect(()=>{let q=!1;if(!Pt)return;const Pr=async()=>{for(await V.current?.content?.settle();uc();)await pc();if(q)return;const ht=dt.current,Vn=ut.current;if(!ht||!Vn)return;if(!e||t===void 0){_t("This stage shows `build` content and was given no `build()`/`sourcePath`.");return}let G;try{G=D.source??e(),D.source=null}catch(bt){_t(bt instanceof Error?bt.message:String(bt));return}try{V.current||(Yl(),V.current=new of(_,nf(Vn,_,i,{width:Math.max(1,ht.clientWidth),height:Math.max(1,ht.clientHeight)},()=>{at(!1),window.setTimeout(()=>{me.current&&at(!0)},0)}),D.store),V.current.contentSeconds=D.contentSeconds,V.current.transportAdvances=D.transportAdvances)}catch(bt){throw G.dispose(),bt}const S=V.current,el=S.borrow(),{renderer:St,canvas:Ut,lease:Ar}=S.surface,rt=S.store;u||(S.cleanups.push(ql(o,rt)),S.cleanups.push(Zl(o,S.transport)));const Is=uo();Is&&rt.attachHistory(Is);const il=_==="inspector-preview",ri=gt.current,jn=K.current,Gn=st.current,nt=new yr;Sr!==!1&&(nt.environmentIntensity=jp);const Rs=G.root.parent;nt.add(G.root),G.animations&&(G.root.animations=[...G.animations]);const Er={root:G.root,animations:G.root.animations};let Ci=null,Pi=null,ni=null,oi=null,Lt=null,ks=null,Fs=null,Bs=null,Ns=null,Hs=null,Xn=null,Wn=null,Jn=!1,Ls=!1,Ds=null;const Tr={scene:nt,settle:()=>Lt?.settle()??Promise.resolve(),dispose:()=>Ds||(Ls=!0,ks&&ht.removeEventListener("pointerdown",ks,!0),Fs&&ht.removeEventListener("pointermove",Fs,!0),Bs&&ht.removeEventListener("pointerup",Bs,!0),Ns&&ht.removeEventListener("pointercancel",Ns,!0),Hs&&window.removeEventListener("keydown",Hs),Ds=(async()=>{await Lt?.settle();const bt=[];for(const zr of[()=>oi?.dispose(),()=>Pi?.dispose?.(),()=>Ci?.dispose(),()=>nt.removeFromParent(),()=>{ke.current?D.source=G:G.dispose(),ke.current=!1},el])try{zr()}catch(ae){bt.push(ae)}bt.length&&console.error("Object3D source cleanup failed.",...bt)})(),Ds)};try{const bt=async R=>{try{const H=Er;if(a&&!n){if(!H)throw new Error("Project history is unavailable; the edit was not saved.");const z=uo();if(!z)throw new Error("Project history is unavailable; the edit was not saved.");const k=a.serialize(H);if(k===null)return _t(null),!1;const j=await ca().replaceSource(z,{file:a.path,source:k,label:R??a.label??`Edit ${i}`});return _t(null),j}if(!n)throw new Error("This Asset Lab document has no persistence binding.");if(!ni||!H)throw new Error("Project history is unavailable; the edit was not saved.");const{persisted:Z}=await(await ni).commit(H,R);return _t(null),Z}catch(H){throw _t(H instanceof Error?H.message:JSON.stringify(H)),H}};Ci=new Hn(rt,nt,{documentId:o,title:i,sourcePath:t,documentKind:Gn?"asset":"source",audit:p,...G.hierarchyRoots?{hierarchyRoots:G.hierarchyRoots}:{},...Mi==="project-file"&&wr?{modelSource:{kind:Mi,path:wr}}:Mi==="entity"&&Ts?{modelSource:{kind:Mi,entityId:Ts}}:{}});const zr={documentId:o,sourcePath:t,root:G.root,animations:G.root.animations,scene:nt,defaultAdapter:Ci,commit:bt};Pi=l?.(zr)??null,!Pi&&y&&(Pi=y({store:rt,scene:nt,...G.hierarchyRoots?{hierarchyRoots:G.hierarchyRoots}:{}}),Ci.dispose()),ni=n&&Is?ca().openPersistence({binding:n,document:Er,history:Is}):null,ni&&ni.catch(R=>{!Ls&&V.current?.content===Tr&&_t(R instanceof Error?R.message:JSON.stringify(R))});const ae=Pi?.adapter??Ci;if(!S.dressing){St.outputColorSpace=Ms,St.toneMapping=Dn??Aa,St.shadowMap.enabled=!0,St.shadowMap.type=ic,St.info.autoReset=!1,St.setPixelRatio(Math.min(window.devicePixelRatio,2)),ri&&St.setClearColor(0,0);const R=Sr===!1?null:Ar&&"environment"in Ar?Ar.environment():Ql(St),H=un(Ut);S.dressing=Gp(S.scene,{environment:R,background:!ri&&s===void 0&&Ln!==!1&&H.background===null,keyLight:br!==!1,grid:Mr===!0,content:G.root}),!ri&&s!==void 0?S.scene.background=new B(s):!ri&&H.background!==null&&(S.scene.background=new B(H.background)),S.defaultEnvironment=S.scene.environment,S.defaultBackground=S.scene.background,S.cleanups.push(()=>{S.defaultBackground instanceof yo&&S.defaultBackground!==S.dressing?.backgroundTexture&&S.defaultBackground.dispose()})}const Yn=(R,H)=>{const Z=S.adapter,z=S.viewport;if(!Z||!z)return null;const k=Ut.getBoundingClientRect(),j=new Jt((R-k.left)/Math.max(k.width,1)*2-1,-((H-k.top)/Math.max(k.height,1))*2+1),Mt=new Yt;Mt.layers.enableAll(),Mt.setFromCamera(j,S.session?.camera()??z.camera);for(const Se of Mt.intersectObjects([...rt.objectMap.values()],!0)){if(ue(Se.object))continue;let he=Se.object;for(;he;){const js=Z.hierarchy.idForObject3D?.(he);if(js)return js;he=he.parent}}return null};if(!S.viewport){S.viewport=new Nn(Ut,S.scene,rt,ht,{renderer:St,authoring:()=>S.adapter??ae,pick:Yn,publishPickContext:!1,onProjectionChange:Be,chromeInsetPx:u||jn?0:dn,lightRig:br!==!1}),Mr===!0&&S.viewport.grid.removeFromParent();const R=H=>{const Z=Yn(H.clientX,H.clientY),z=Z?S.adapter?.hierarchy.object3D?.(Z):null;z&&Ke.current?.(z)};ht.addEventListener("dblclick",R),S.cleanups.push(()=>ht.removeEventListener("dblclick",R))}const U=S.viewport;if(zs){const R=U.camera;S.scene.add(R),R.add(zs),S.cleanups.push(()=>{zs.removeFromParent(),R.removeFromParent()})}if(h){const R=new kt;R.name="__object3d_document_overlay",Rt(R,"editorHelper",!0),nt.add(R),oi=h.setup({root:G.root,scene:nt,renderer:St,overlay:R,camera:()=>S.session?.camera()??U.camera,writable:n!==void 0||a!==void 0});const H=z=>{const k=Ut.getBoundingClientRect(),j=new Jt((z.clientX-k.left)/Math.max(k.width,1)*2-1,-((z.clientY-k.top)/Math.max(k.height,1))*2+1),Mt=new Yt;return Mt.layers.enableAll(),Mt.setFromCamera(j,S.session?.camera()??U.camera),{pointerId:z.pointerId,button:z.button,buttons:z.buttons,clientX:z.clientX,clientY:z.clientY,altKey:z.altKey,ctrlKey:z.ctrlKey,metaKey:z.metaKey,shiftKey:z.shiftKey,ray:Mt.ray.clone(),hits:Mt.intersectObjects([G.root,R],!0)}};Lt=new fp({begin:z=>{if(!n&&!a)throw new Error("This Asset Lab document has no persistence binding; project gestures are read-only.");return oi.begin(z)},persist:async z=>{await bt(z)},reportError:z=>_t(z instanceof Error?z.message:JSON.stringify(z))});const Z=z=>{z.preventDefault(),z.stopPropagation()};ks=z=>{z.target instanceof Element&&z.target.closest('[role="alert"], [role="toolbar"]')!==null||Lt?.begin(H(z))&&(Z(z),z.isTrusted&&Ut.setPointerCapture?.(z.pointerId))},Fs=z=>{Lt?.hasActiveGesture()&&(Z(z),Lt.update(H(z)))},Bs=z=>{Lt?.hasActiveGesture()&&(Z(z),Ut.hasPointerCapture?.(z.pointerId)&&Ut.releasePointerCapture?.(z.pointerId),Lt.commit(H(z)))},Ns=z=>{Lt?.hasActiveGesture()&&(Z(z),Lt.cancel(z.pointerId))},Hs=z=>{z.key!=="Escape"||!Lt?.hasActiveGesture()||(z.preventDefault(),Lt.cancel())},Xn=()=>{ht.addEventListener("pointerdown",ks,!0),ht.addEventListener("pointermove",Fs,!0),ht.addEventListener("pointerup",Bs,!0),ht.addEventListener("pointercancel",Ns,!0),window.addEventListener("keydown",Hs)}}const He=S.content,qn=[...rt.selectedEntityIds],Ai=S.adapter,sl=new Map(rt.objectMap),Ei=S.session?.root,rl=S.frame,nl=S.syncHostScene,ol=ye.current,al=Qt.current,ll=ge.current,Zn=S.session?.neutralBackgroundTexture(),hl=S.dressing.lights.map(R=>R.visible),cl=S.cleanups.length,dl=S.initialized;if(Wn=()=>{nt.removeFromParent(),Rs&&Rs.add(G.root),He&&S.scene.add(He.scene),S.adapter=Ai,S.content=He,S.frame=rl,S.syncHostScene=nl,S.initialized=dl;for(const R of S.cleanups.splice(cl))R();!Ei&&S.session&&(S.session.dispose(),S.session=null),rt.objectMap.clear();for(const[R,H]of sl)rt.objectMap.set(R,H);He&&rt.bindScene(He.scene,St,U.batchedRenderer,U.camera),Ei&&Ai&&S.session?.replaceContent(Ei,Ai),ye.current=ol,Qt.current=al,ge.current=ll,et.current=Ai,xe(Ai),Zn!==void 0&&S.session?.setNeutralBackground(Zn),S.dressing?.lights.forEach((R,H)=>{R.visible=hl[H]??!0}),Ei&&S.dressing?.frameContent(Ei),rt.selectMultiple(qn),rt.notifyIngestObjectMapEdit()},He?.scene.removeFromParent(),S.scene.add(nt),S.adapter=ae,S.content=Tr,rt.bindScene(nt,St,U.batchedRenderer,U.camera),rt.setOrbitTarget(U.orbitControls.target),rt.objectMap.clear(),nt.traverse(R=>{const H=ae.hierarchy.idForObject3D?.(R);H&&rt.objectMap.set(H,R)}),S.session)S.session.replaceContent(G.root,ae);else{const R=da(ti.current),H=da(ei.current)??R;if(H||U.focusOn(G.root),_r!==void 0&&vr!==void 0&&xr!==void 0){const Z=H??Ie(G.root),z=Z.getCenter(new v),k=new v(_r,vr,xr).normalize(),j=Xe(Z,U.camera,k)*Math.min(10,Math.max(.1,x??1));U.camera.position.copy(z).add(k.multiplyScalar(j)),U.orbitControls.target.copy(z)}if(S.session=new pp(o,G.root,S.scene,St,U,S.dressing.lights,ae,ri?null:s===void 0?S.dressing.backgroundTexture:new B(s),R),S.session.selectionOutlineEnabled=!il&&Qe.current,!ri&&s===void 0&&S.dressing.backgroundTexture){const Z=S.session;S.cleanups.push(Lp(()=>{const z=un(Ut).background;if(z!==null){S.scene.background=new B(z);return}const k=S.defaultBackground;S.defaultBackground=Qa(),Z.neutralBackgroundTexture()===k&&Z.setNeutralBackground(S.defaultBackground),k instanceof yo&&k!==S.dressing?.backgroundTexture&&k.dispose()}))}}const Us=D.camera;Us&&(U.setProjection(ve),U.setPose(Us.position,Us.target,Us.fov||void 0),D.camera=null);const pt=S.session;ye.current=Er,Qt.current=ni,ge.current=oi,et.current=ae,xe(ae);let Qn=!1;G.root.traverse(R=>{R.isLight&&(Qn=!0)});for(const R of S.dressing.lights)R.visible=!Qn;S.dressing.frameContent(G.root),rt.selectMultiple(qn.filter(R=>rt.objectMap.has(R))),rt.notifyIngestObjectMapEdit(),pt.syncSelectionPresentation(),Xn?.(),_t(null),u||po(o);let Vs=nt.background;pt.setNeutralBackground(Vs??S.defaultBackground);const le=D.presentation;le&&(pt.setMode(le.mode),pt.setGrid(le.grid),pt.setBackground(le.background),pt.setExposure(le.exposure),pt.setProjection(le.projection),pt.setLighting(le.lighting),pt.setSkeleton(le.skeleton),pt.setBounds(le.bounds),D.presentation=null);const ul=()=>{S.scene.environment=nt.environment??S.defaultEnvironment,S.scene.fog=nt.fog,S.scene.environmentIntensity=nt.environmentIntensity,S.scene.environmentRotation.copy(nt.environmentRotation),S.scene.backgroundIntensity=nt.backgroundIntensity,S.scene.backgroundBlurriness=nt.backgroundBlurriness,S.scene.backgroundRotation.copy(nt.backgroundRotation),Vs!==nt.background&&(Vs=nt.background,pt.setNeutralBackground(Vs??S.defaultBackground))};S.syncHostScene=ul,pt.setBeforeRender(()=>S.syncHostScene?.()),pt.setPresentsFrames(!0);const pl=R=>{Ls||!(R>0)||!Number.isFinite(R)||(S.contentSeconds+=R,S.transportAdvances++,G.update?.(R))},fl=hc(G.root,S.transport);S.cleanups.push(()=>fl.dispose());const we=D.transport;we&&(we.activeSubject&&S.transport.setActiveSubject(we.activeSubject),S.transport.setLoop(we.range.loop),S.transport.setTimeScale(we.timeScale),S.transport.seek(we.time),we.playbackState==="playing"?S.transport.play():we.playbackState==="paused"&&S.transport.pause(),D.transport=null);let Or=performance.now();const ml=(R,H)=>{if(Ls||!St||!U)return;const Z=St,z=U,k=pt?.profiler;k?.beginFrame(),H&&(Or=R);const j=Math.min((R-Or)/1e3,.1);Or=R,k?.beginPhase();const Mt=S.transport.tick(j);Mt>0&&pl(Mt),oi?.prepareFrame?.(j),oi?.update?.(j),k?.endPhase("animation"),k?.beginPhase(),S.presence?.syncMarkers(j),U.update(j),u||$l(o,j),U.batchedRenderer.update(j),k?.endPhase("editor"),k?.beginPhase(),Z.info.reset();const Se=!re.current&&Kl()===o;Se&&th(o);const he=Se?Date.now():0,js=S.scene.overrideMaterial,$n=pt.presentation().mode;$n!=="uv"&&$n!=="vertex-colors"&&(S.scene.overrideMaterial=nt.overrideMaterial);try{z.renderWithInfrastructure(()=>{pt.renderViewport(j),z.renderViewCube(Z)})}finally{S.scene.overrideMaterial=js}pt.servePresentedFrame(),re.current||(re.current=!0,Se&&eh("first-render",Date.now()-he),ih(o),_e("ready")),k?.reportRender({gpuMs:null,drawCalls:Z.info.render.calls,triangles:Z.info.render.triangles,geometries:Z.info.memory.geometries,textures:Z.info.memory.textures}),k?.endPhase("render"),k?.endFrame();const Vt=tt.current;if(Vt&&P&&sh(P)===rt){const ai=pt.cameraPose();Vt.frameTime=j*1e3,Vt.fps=j>0?1/j:0,Vt.drawCalls=Z.info.render.calls,Vt.triangles=Z.info.render.triangles,Vt.cameraPosition.x=ai.position[0],Vt.cameraPosition.y=ai.position[1],Vt.cameraPosition.z=ai.position[2],Vt.cameraTarget.x=ai.target[0],Vt.cameraTarget.y=ai.target[1],Vt.cameraTarget.z=ai.target[2]}};if(S.frame=ml,Fe.current=S.rendererSession,!S.initialized){u||(S.cleanups.push(rh({camera:U.camera,orbit:U.orbitControls,scene:S.scene},()=>null,(k,j)=>U.setHelper(k,j),{documentId:o})),Ss(()=>import("./stage-presence-markers-DvbNl1W4.js"),__vite__mapDeps([21,6,4,3,5,7,8,2,9,10,1,11])).then(k=>{if(S.isClosed||V.current!==S||S.presence)return;const j=k.bindStagePresenceMarkers({scene:S.scene,store:rt,documentId:o,container:ht,canvas:Ut,viewport:U,readVisibleCameraPose:()=>{const Mt=S.session?.camera()??U.renderCamera,Se=Mt.getWorldPosition(new v),he=Mt.fov;return{position:Se,target:U.orbitControls.target,fov:typeof he=="number"?he:0}}});S.presence=j,S.cleanups.push(()=>j.dispose())}),S.cleanups.push(nh(pt)),S.cleanups.push(oh({id:o,label:i,kind:Gn?"asset":"source",profiler:pt.profiler}))),!u&&!jn&&S.cleanups.push(ah(o,()=>({adapter:S.adapter,nodeId:S.adapter?.selection?.get()[0]??null})));const R=u?`${o}#chromeless-${++ef}`:o;S.cleanups.push(lh({id:R,label:i,contentClock:()=>S.contentSeconds,transportAdvances:()=>S.transportAdvances})),S.cleanups.push(rt.onViewportAction(k=>{switch(k.type){case"focus-selection":case"focus-scene":!S.session?.frame()&&S.session?.root&&U.focusOn(S.session.root);break;case"focus-entity":{const j=S.adapter?.hierarchy.object3D?.(k.id)??null;j&&U.focusOn(j);break}case"snap-selection-to-floor":U.snapSelectionToFloor();break;case"set-view-preset":U.setViewPreset(k.preset);break;case"set-camera-pose":U.setPose(k.position,k.target,k.fov);break}}));let H="";S.cleanups.push(rt.subscribe(()=>{U.objectMap=rt.objectMap,U.syncFromStore(),S.session?.syncSelectionPresentation();const k=(S.adapter?.selection?.get()??[]).join("\0");k!==H&&(H=k,u||po(o))}));const Z=()=>{const k=Math.max(1,ht.clientWidth),j=Math.max(1,ht.clientHeight),Mt=St.getPixelRatio();(Ut.width!==Math.floor(k*Mt)||Ut.height!==Math.floor(j*Mt))&&St.setSize(k,j,!1),U.resize(k,j),S.session?.resize(k,j),S.rendererSession.redraw()},z=new ResizeObserver(Z);z.observe(ht),S.cleanups.push(()=>z.disconnect()),Z(),S.initialized=!0,hh()}U.objectMap=rt.objectMap,U.syncFromStore(),S.rendererSession.setActive(me.current),S.rendererSession.redraw(),Jn=!0,He?.dispose()}catch(bt){if(!Jn)try{Wn?.()}finally{Rs&&G.root.parent===nt&&Rs.add(G.root),Tr.dispose()}console.error(`[object3d document] ${i}: source update failed`,bt),_t(bt instanceof Error?bt.message:String(bt))}},tl=$e.current.then(Pr);return $e.current=tl.catch(ht=>{q||_t(ht instanceof Error?ht.message:String(ht))}),()=>{q=!0}},[l,s,e,_r,vr,xr,i,o,$,Ln,Sr,Mr,br,zs,Dn,u,Ts,Mi,wr,h,n,a,_,D,Pt,y,t]),F.useEffect(()=>{const q=Fe.current,Pr=c&&!ii.current;ii.current=c,q&&(Pr&&(re.current=!1,mh(o)),q.setActive(c))},[c,o]);const Os=V.current,Cr=oe==="ready"&&Os?.viewport?{store:Os.store,viewport:Os.viewport,canvas:Os.surface.canvas}:null,Ka=F.useCallback(()=>{const q=et.current;return q?{adapter:q,nodeId:q.selection?.get()[0]??q.hierarchy.roots()[0]?.id??null}:null},[]),Un=T.jsx("div",{"data-testid":"tool-object3d-authoring","data-vgai-chromeless":u||void 0,className:$?"vgai-object3d-studio-stage":void 0,style:{position:u||Y?"relative":"absolute",...u?{width:"100%",height:"100%"}:Y?{flex:1,minHeight:0}:{inset:-dn},overflow:"hidden",background:$?void 0:Nt.surface.raised,pointerEvents:"auto"},children:T.jsxs("div",{ref:dt,style:{position:"absolute",inset:0,minHeight:0,overflow:"hidden"},children:[T.jsx(rf,{canvasHostRef:ut}),c&&Cr&&!u?T.jsx(F.Suspense,{fallback:null,children:T.jsx(Kp,{stage:Cr})}):null,P&&!u?T.jsx(kp,{store:P,documentId:o,stage:Cr,active:c,chrome:"document"}):null,ne&&T.jsx("div",{role:"alert",style:{position:"absolute",insetInline:0,top:0,display:"flex",justifyContent:"center",padding:"var(--vgai-space-3)",pointerEvents:"none"},children:T.jsxs("div",{className:"vgai-chrome-island",style:{display:"flex",alignItems:"center",gap:"var(--vgai-space-3)",maxWidth:"80%",padding:"var(--vgai-space-2) var(--vgai-space-3)",borderRadius:"var(--vgai-radius-md)",border:`var(--vgai-stroke-resting) solid ${Nt.semantic.danger}`,background:Nt.surface.raised,color:Nt.semantic.danger,pointerEvents:"auto"},children:[T.jsx("span",{children:ne}),T.jsx(Ae,{size:"compact","aria-label":"Dismiss",onClick:()=>_t(null),"data-testid":"object3d-document-error-dismiss",children:T.jsx(Ee,{icon:pe.action.close})})]})}),!ne&&oe==="building"&&T.jsx($p,{testId:"object3d-document-status",children:Qp}),T.jsx("div",{style:{position:"absolute",inset:u||Y?0:dn,pointerEvents:"none"},children:!u&&oe==="ready"&&V.current&&T.jsx(Zp,{viewport:V.current.viewport,session:V.current.session,store:V.current.store,projection:ve,displayName:i,...b?{statistics:b}:{},objectName:q=>V.current?.adapter?.hierarchy.object3D?.(q)?.name??V.current?.store.objectMap.get(q)?.name??null})})]})});return Y?T.jsx(Xl,{documentId:o,active:c,type:m??(Ts?"entity":"model"),title:i,status:t,selection:Ka,fill:!0,children:T.jsxs("div",{className:"vgai-object3d-asset-workspace",children:[Un,T.jsx(Np,{transport:V.current?.transport??null})]})}):Un}function af(o){return T.jsx($a,{...o})}const Sf=Object.freeze(Object.defineProperty({__proto__:null,Object3DDocumentViewport:$a,ToolObject3DAuthoring:af},Symbol.toStringTag,{value:"Module"}));export{On as C,cr as G,$a as O,vf as Q,wf as S,L as V,$p as a,Qp as b,Sf as c,Wo as o,xf as s};