@needle-tools/engine 4.7.0-next.22483b4 → 4.7.0-next.4bd7749

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 (43) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/{needle-engine.bundle-RgZNbAgp.js → needle-engine.bundle-BGHUA0S1.js} +21 -19
  3. package/dist/{needle-engine.bundle-CP5AJL1A.umd.cjs → needle-engine.bundle-DQ8S9diA.umd.cjs} +9 -7
  4. package/dist/{needle-engine.bundle-BnGp0ASs.min.js → needle-engine.bundle-kBkeRoLs.min.js} +9 -7
  5. package/dist/needle-engine.js +2 -2
  6. package/dist/needle-engine.min.js +1 -1
  7. package/dist/needle-engine.umd.cjs +1 -1
  8. package/lib/engine/engine_context.js +1 -1
  9. package/lib/engine/engine_context.js.map +1 -1
  10. package/lib/engine/engine_three_utils.js +4 -0
  11. package/lib/engine/engine_three_utils.js.map +1 -1
  12. package/lib/engine/webcomponents/needle-engine.attributes.d.ts +1 -1
  13. package/lib/engine-components/Camera.js +1 -1
  14. package/lib/engine-components/Camera.js.map +1 -1
  15. package/lib/engine-components/CameraUtils.js +5 -3
  16. package/lib/engine-components/CameraUtils.js.map +1 -1
  17. package/lib/engine-components/Skybox.js +4 -4
  18. package/lib/engine-components/Skybox.js.map +1 -1
  19. package/lib/engine-components/postprocessing/Effects/Antialiasing.js +1 -1
  20. package/lib/engine-components/postprocessing/Effects/Antialiasing.js.map +1 -1
  21. package/lib/engine-components/postprocessing/Effects/ScreenspaceAmbientOcclusionN8.js +1 -1
  22. package/lib/engine-components/postprocessing/PostProcessingHandler.js.map +1 -1
  23. package/lib/engine-components/postprocessing/Volume.js +1 -1
  24. package/lib/engine-components/postprocessing/Volume.js.map +1 -1
  25. package/package.json +1 -1
  26. package/plugins/common/logger.js +321 -0
  27. package/plugins/types/userconfig.d.ts +4 -2
  28. package/plugins/vite/alias.js +7 -2
  29. package/plugins/vite/imports-logger.js +1 -1
  30. package/plugins/vite/index.js +2 -0
  31. package/plugins/vite/logger.client.js +262 -0
  32. package/plugins/vite/logger.js +101 -0
  33. package/plugins/vite/materialx.js +6 -4
  34. package/src/engine/engine_context.ts +1 -1
  35. package/src/engine/engine_three_utils.ts +3 -0
  36. package/src/engine/webcomponents/needle-engine.attributes.ts +1 -1
  37. package/src/engine-components/Camera.ts +1 -1
  38. package/src/engine-components/CameraUtils.ts +5 -3
  39. package/src/engine-components/Skybox.ts +5 -5
  40. package/src/engine-components/postprocessing/Effects/Antialiasing.ts +1 -1
  41. package/src/engine-components/postprocessing/Effects/ScreenspaceAmbientOcclusionN8.ts +1 -1
  42. package/src/engine-components/postprocessing/PostProcessingHandler.ts +1 -2
  43. package/src/engine-components/postprocessing/Volume.ts +1 -1
@@ -79,7 +79,7 @@ varying vec2 vUv;
79
79
  void main(){
80
80
  vUv = uv;
81
81
  gl_Position = vec4(position.xy, 0., 1.0);
82
- }`);let Xd=Ou;const hn=class hn{static copyTexture(t,e){e||(e=this.blitMaterial),this.blitMaterial.reset();const i=e||this.blitMaterial;i.uniforms.map.value=t,i.needsUpdate=!0,i.uniformsNeedUpdate=!0;const n=i.vertexShader;i.vertexShader=Xd.vertex;const s=this.mesh;s.material=i,s.frustumCulled=!1,this.scene.children.length=0,this.scene.add(s),this.renderer.setSize(t.image.width,t.image.height),this.renderer.clear(),this.renderer.render(this.scene,this.perspectiveCam);const a=new d.Texture(this.renderer.domElement);return a.name="Copy",a.needsUpdate=!0,i.vertexShader=n,a}static blit(t,e,i){const{renderer:n=this.renderer,blitMaterial:s=this.blitMaterial,flipY:a=!1,depthTexture:l=null,depthTest:c=!0,depthWrite:h=!0}=i||{};this.blitMaterial.reset(),s.uniforms.map&&(s.uniforms.map.value=t),s.uniforms.flipY&&(s.uniforms.flipY.value=a),l?(s.uniforms.writeDepth=new d.Uniform$1(!0),s.uniforms.depthTexture.value=l):(s.uniforms.writeDepth=new d.Uniform$1(!1),s.uniforms.depthTexture.value=null),s.needsUpdate=!0,s.uniformsNeedUpdate=!0;const u=this.mesh;u.material=s,u.frustumCulled=!1,this.scene.children.length=0,this.scene.add(u);const f=n.getRenderTarget(),p=n.getContext(),g=p.getParameter(p.DEPTH_TEST),y=p.getParameter(p.DEPTH_WRITEMASK),b=p.getParameter(p.DEPTH_FUNC);c?n.getContext().enable(n.getContext().DEPTH_TEST):n.getContext().disable(n.getContext().DEPTH_TEST),n.state.buffers.depth.setMask(h),n.setClearColor(new d.Color(0,0,0),0),n.setPixelRatio(window.devicePixelRatio),n.setRenderTarget(e),n.clear(),n.render(this.scene,this.perspectiveCam),n.setRenderTarget(f);const _=n.state.buffers.depth;_.setTest(g),_.setMask(y),_.setFunc(b)}static textureToCanvas(t,e=!1){if(!t)return null;(e===!0||t.isCompressedTexture===!0)&&(t=M0(t));const i=t.image;if(QS(i)){const n=document.createElement("canvas");n.width=i.width,n.height=i.height;const s=n.getContext("2d");return s?(s.drawImage(i,0,0,i.width,i.height,0,0,n.width,n.height),n):(console.error("Failed getting canvas 2d context"),null)}return null}};r(hn,"planeGeometry",new d.PlaneGeometry(2,2,1,1)),r(hn,"renderer",new d.WebGLRenderer({antialias:!1,alpha:!0})),r(hn,"perspectiveCam",new d.PerspectiveCamera),r(hn,"orthographicCam",new d.OrthographicCamera),r(hn,"scene",new d.Scene),r(hn,"blitMaterial",new Xd),r(hn,"mesh",new d.Mesh(hn.planeGeometry,hn.blitMaterial));let Mr=hn;function M0(o){return Mr.copyTexture(o)}function XS(o,t=!1){return Mr.textureToCanvas(o,t)}function QS(o){return typeof HTMLImageElement<"u"&&o instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&o instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&o instanceof OffscreenCanvas||typeof ImageBitmap<"u"&&o instanceof ImageBitmap}function YS(o){const t=o.type;return t==="Mesh"||t==="SkinnedMesh"}function Km(o,t){t?o["needle:rendercustomshadow"]=!0:o["needle:rendercustomshadow"]=!1}function O0(o){if(o){if(o["needle:rendercustomshadow"]===!0)return!0;if(o["needle:rendercustomshadow"]==null)return!0}return!1}function li(o,t=void 0,e=void 0,i=void 0){const n=i||new d.Box3;n.makeEmpty();const s=[];function a(c){let h=!0;if(c.visible&&v0(c)!==!1&&!(c.type==="TransformControlsGizmo"||c.type==="TransformControlsPlane")){if(c instanceof d.Box3Helper&&(h=!1),c instanceof d.GridHelper&&(h=!1),c instanceof G.GroundedSkybox&&(h=!1),c.isGizmo===!0&&(h=!1),c.material instanceof d.ShadowMaterial&&(h=!1),YS(c)||(h=!1),e&&c.layers.test(e)===!1&&(h=!1),h){if(t&&Array.isArray(t)&&(t!=null&&t.includes(c)))return;if(typeof t=="function"&&t(c)===!0)return}if(c.isUI!==!0){if(h){const u=c.children;c.children=s;const f=c.position,p=c.scale;if(Number.isNaN(f.x)||Number.isNaN(f.y)||Number.isNaN(f.z)){console.warn(`Object "${c.name}" has NaN values in position or scale.... will ignore it`,f,p);return}n.expandByObject(c,!0),c.children=u}for(const u of c.children)a(u)}}}let l=!1;Array.isArray(o)||(o=[o]);for(const c of o)c&&(l=!0,c.updateMatrixWorld(),a(c));return l||console.warn("No objects to fit camera to..."),n}function k0(o,t,e){const i=li([o],e==null?void 0:e.ignore),n=new d.Vector3;i.getSize(n);const s=new d.Vector3;i.getCenter(s);const a=new d.Vector3;t.getSize(a);const l=new d.Vector3;t.getCenter(l);const c=new d.Vector3;c.set(a.x/n.x,a.y/n.y,a.z/n.z);const h=Math.min(c.x,c.y,c.z),u=(e==null?void 0:e.scale)!==!1;if(u&&za(o,Ue(o).multiplyScalar(h)),(e==null?void 0:e.position)!==!1){const f=new d.Vector3;i.getCenter(f),f.y=i.min.y;const p=new d.Vector3;t.getCenter(p),p.y=t.min.y;const g=p.clone().sub(f);u&&g.multiplyScalar(h),st(o,Q(o).add(g))}return{boundsBefore:i,scale:c}}function R0(o,t){const e=li([o]),i=new d.Vector3;e.getCenter(i),i.y=e.min.y;const n=t.clone().sub(i),s=Q(o);return st(o,s.add(n)),{offset:n,bounds:e}}function Zm(o,t,e,i){if(Array.isArray(t)){let a=!0;for(let l=0;l<t.length;l++)Zm(o,t[l],l,t)||(a=!1);return a}if(t.type==="MeshStandardMaterial"||t.type==="MeshBasicMaterial")return!1;if(t["material:fbx"]!=null)return!0;const n=new d.MeshStandardMaterial;n["material:fbx"]=t;const s=t;return s&&(s.map?n.color.set(1,1,1):n.color.copyLinearToSRGB(s.color),n.emissive.copyLinearToSRGB(s.emissive),n.emissiveIntensity=s.emissiveIntensity,n.opacity=s.opacity,n.displacementScale=s.displacementScale,n.transparent=s.transparent,n.bumpMap=s.bumpMap,n.aoMap=s.aoMap,n.map=s.map,n.displacementMap=s.displacementMap,n.emissiveMap=s.emissiveMap,n.normalMap=s.normalMap,n.envMap=s.envMap,n.alphaMap=s.alphaMap,n.metalness=s.reflectivity,n.vertexColors=s.vertexColors,s.shininess&&(n.roughness=1-Math.sqrt(s.shininess)/10),n.needsUpdate=!0),e===void 0?o.material=n:i[e]=n,!0}let Kh=!1;SS((...o)=>{var t;j()&&((t=re.Current)!=null&&t.isInXR)&&(br(!0),E0("error",...o))});function br(o){if(o){if(Kh)return;Kh=!0,ZS()}else{if(!Kh)return;Kh=!1,JS()}}const ac={log:void 0,warn:void 0,error:void 0};class KS{constructor(){r(this,"familyName","needle-xr");r(this,"root",null);r(this,"context",null);r(this,"defaultFontSize",.06);r(this,"targetObject",new d.Object3D);r(this,"userForwardViewPoint",new d.Vector3);r(this,"oneEuroFilter",new Gm(90,.8));r(this,"_lastElementRemoveTime",0);r(this,"onBeforeRender",()=>{var e,i;const t=(e=this.context)==null?void 0:e.mainCamera;if(this.context&&t instanceof d.PerspectiveCamera){const n=this.getRoot();Number.isNaN(n.position.x)&&n.position.set(0,0,0),Number.isNaN(n.quaternion.x)&&n.quaternion.set(0,0,0,1),this.context.scene.add(this.targetObject);const s=((i=this.context.xr)==null?void 0:i.rigScale)??1,a=3.5*s,l=t.worldForward;l.y=0,l.normalize().multiplyScalar(a),this.userForwardViewPoint.copy(t.worldPosition).sub(l),this.targetObject.position.distanceTo(this.userForwardViewPoint)>2*s&&(this.targetObject.position.copy(this.userForwardViewPoint),eh(this.targetObject,t,!0,!0),this.targetObject.rotateY(Math.PI)),this.oneEuroFilter.filter(this.targetObject.position,n.position,this.context.time.time);const h=this.context.time.deltaTime;if(n.quaternion.slerp(this.targetObject.quaternion,h*5),n.scale.setScalar(s),this.targetObject.removeFromParent(),this.context.scene.add(n),this.context.time.time-this._lastElementRemoveTime>.1){this._lastElementRemoveTime=this.context.time.time;const u=Date.now();for(let f=0;f<this._activeTexts.length;f++){const p=this._activeTexts[f];if(p instanceof ne.__webpack_exports__default.Text&&u-p._activatedTime>2e4){p.removeFromParent(),this._textBuffer.push(p),this._activeTexts.splice(f,1);break}}}}});r(this,"textOptions",{fontSize:this.defaultFontSize,fontFamily:this.familyName,padding:.03,margin:.005,color:0,backgroundColor:16777215,backgroundOpacity:.4,borderRadius:.03,offset:.025});r(this,"_textBuffer",[]);r(this,"_activeTexts",[]);this.ensureFont()}onEnable(){this.context=re.Current||re.All[0],this.context.pre_render_callbacks.push(this.onBeforeRender)}onDisable(){var t,e,i;(e=this.context)==null||e.pre_render_callbacks.splice((t=this.context)==null?void 0:t.pre_render_callbacks.indexOf(this.onBeforeRender),1),(i=this.root)==null||i.removeFromParent()}addLog(t,e){const i=this.getRoot(),n=this.getText();let s=16777215,a=0;switch(t){case"log":s=16777215,a=0;break;case"warn":s=16772761,a=4465152;break;case"error":s=16755370,a=7798784;break}e.length>1e3&&(e=e.substring(0,1e3)+"...");const l=new Date().toISOString().split("T")[1].split(".")[0];n.textContent="["+l+"] "+e,n.visible=!0,n._activatedTime=Date.now(),i.add(n),this._activeTexts.push(n),this.context&&this.context.scene.add(i),n.set({backgroundColor:s,color:a}),ne.__webpack_exports__default.update()}ensureFont(){let t=ne.__webpack_exports__default.FontLibrary.getFontFamily(this.familyName);if(!t){t=ne.__webpack_exports__default.FontLibrary.addFontFamily(this.familyName);const e=t.addVariant("normal","normal","./include/needle/arial-msdf.json","./include/needle/arial.png");e==null||e.addEventListener("ready",()=>{ne.__webpack_exports__default.update()})}}getText(){const t=this.getRoot();if(this._textBuffer.length>0){const i=this._textBuffer.pop();return i.visible=!0,setTimeout(()=>this.disableDepthTestRecursive(i),100),i}if(t.children.length>20&&this._activeTexts.length>0)return this._activeTexts.shift();const e=new ne.__webpack_exports__default.Text(this.textOptions);return setTimeout(()=>this.disableDepthTestRecursive(e),500),setTimeout(()=>this.disableDepthTestRecursive(e),1500),e}disableDepthTestRecursive(t,e=0){for(let n=0;n<t.children.length;n++){const s=t.children[n];s instanceof d.Object3D&&this.disableDepthTestRecursive(s,e+1)}t.renderOrder=10*e,t.layers.set(2);const i=t.material;i&&(i.depthWrite=!1,i.depthTest=!1,i.transparent=!0),e===0&&ne.__webpack_exports__default.update()}getRoot(){if(this.root)return this.root;const t=this.defaultFontSize,e={boxSizing:"border-box",fontFamily:this.familyName,width:"2.6",fontSize:t,color:0,lineHeight:1,backgroundColor:16777215,backgroundOpacity:0,whiteSpace:"pre-wrap",flexDirection:"column-reverse"};return this.root=new ne.__webpack_exports__default.Block(e),this.root}}let Ht=null;function ZS(){Ht||(Ht=new KS),Ht.onEnable();for(const o in ac){ac[o]=console[o];let t=!1;console[o]=function(){var e;if((e=ac[o])==null||e.apply(console,arguments),!t)try{t=!0,E0(o,...arguments)}finally{t=!1}}}}function JS(){Ht==null||Ht.onDisable();for(const o in ac)console[o]=ac[o]}const Ol=new Map;function E0(o,...t){try{switch(Ol.clear(),o){case"log":Ht==null||Ht.addLog("log",e());break;case"warn":Ht==null||Ht.addLog("warn",e());break;case"error":Ht==null||Ht.addLog("error",e());break}}catch(s){console.error("Error in spatial console",s)}finally{Ol.clear()}function e(){let s="";for(let a=0;a<t.length;a++){const l=t[a];s+=i(l),a<t.length-1&&(s+=", ")}return s}function i(s,a=0){if(typeof s=="string")return'"'+s+'"';if(typeof s=="number"){if(s%1!==0){const c=s.toFixed(5),h=c.indexOf(".");let u=c.length-1;for(;u>h&&c[u]==="0";)u--;return c.substring(0,u+1)}return s.toString()}else if(Array.isArray(s)){let l="[";for(let c=0;c<s.length;c++){const h=s[c];l+=i(h,a+1),c<s.length-1&&(l+=", ")}return l+="]",l}else{if(s===null)return"null";if(s===void 0)return"undefined";if(typeof s=="function")return s.name+"()"}if(s instanceof d.Vector2)return`(${i(s.x)}, ${i(s.y)})`;if(s instanceof d.Vector3)return`(${i(s.x)}, ${i(s.y)}, ${i(s.z)})`;if(s instanceof d.Vector4)return`(${i(s.x)}, ${i(s.y)}, ${i(s.z)}, ${i(s.w)})`;if(s instanceof d.Quaternion)return`(${i(s.x)}, ${i(s.y)}, ${i(s.z)}, ${i(s.w)})`;if(s instanceof d.Material||s instanceof d.Texture)return s.name;if(s instanceof d.Matrix3)return`[${s.elements.join(", ")}]`;if(s instanceof d.Matrix4)return`[${s.elements.join(", ")}]`;if(s instanceof d.Layers)return s.mask.toString();if(typeof s=="object"){if(Ol.has(s))return"*";let l=`{
82
+ }`);let Xd=Ou;const hn=class hn{static copyTexture(t,e){e||(e=this.blitMaterial),this.blitMaterial.reset();const i=e||this.blitMaterial;i.uniforms.map.value=t,i.needsUpdate=!0,i.uniformsNeedUpdate=!0;const n=i.vertexShader;i.vertexShader=Xd.vertex;const s=this.mesh;s.material=i,s.frustumCulled=!1,this.scene.children.length=0,this.scene.add(s),this.renderer.setSize(t.image.width,t.image.height),this.renderer.clear(),this.renderer.render(this.scene,this.perspectiveCam);const a=new d.Texture(this.renderer.domElement);return a.name="Copy",a.needsUpdate=!0,i.vertexShader=n,a}static blit(t,e,i){const{renderer:n=this.renderer,blitMaterial:s=this.blitMaterial,flipY:a=!1,depthTexture:l=null,depthTest:c=!0,depthWrite:h=!0}=i||{};this.blitMaterial.reset(),s.uniforms.map&&(s.uniforms.map.value=t),s.uniforms.flipY&&(s.uniforms.flipY.value=a),l?(s.uniforms.writeDepth=new d.Uniform$1(!0),s.uniforms.depthTexture.value=l):(s.uniforms.writeDepth=new d.Uniform$1(!1),s.uniforms.depthTexture.value=null),s.needsUpdate=!0,s.uniformsNeedUpdate=!0;const u=this.mesh;u.material=s,u.frustumCulled=!1,this.scene.children.length=0,this.scene.add(u);const f=n.getRenderTarget(),p=n.getContext(),g=p.getParameter(p.DEPTH_TEST),y=p.getParameter(p.DEPTH_WRITEMASK),b=p.getParameter(p.DEPTH_FUNC);c?n.getContext().enable(n.getContext().DEPTH_TEST):n.getContext().disable(n.getContext().DEPTH_TEST),n.state.buffers.depth.setMask(h),n.setClearColor(new d.Color(0,0,0),0),n.setPixelRatio(window.devicePixelRatio),n.setRenderTarget(e),n.clear(),n.render(this.scene,this.perspectiveCam),n.setRenderTarget(f);const _=n.state.buffers.depth;_.setTest(g),_.setMask(y),_.setFunc(b)}static textureToCanvas(t,e=!1){if(!t)return null;(e===!0||t.isCompressedTexture===!0)&&(t=M0(t));const i=t.image;if(QS(i)){const n=document.createElement("canvas");n.width=i.width,n.height=i.height;const s=n.getContext("2d");return s?(s.drawImage(i,0,0,i.width,i.height,0,0,n.width,n.height),n):(console.error("Failed getting canvas 2d context"),null)}return null}};r(hn,"planeGeometry",new d.PlaneGeometry(2,2,1,1)),r(hn,"renderer",new d.WebGLRenderer({antialias:!1,alpha:!0})),r(hn,"perspectiveCam",new d.PerspectiveCamera),r(hn,"orthographicCam",new d.OrthographicCamera),r(hn,"scene",new d.Scene),r(hn,"blitMaterial",new Xd),r(hn,"mesh",new d.Mesh(hn.planeGeometry,hn.blitMaterial));let Mr=hn;function M0(o){return Mr.copyTexture(o)}function XS(o,t=!1){return Mr.textureToCanvas(o,t)}function QS(o){return typeof HTMLImageElement<"u"&&o instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&o instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&o instanceof OffscreenCanvas||typeof ImageBitmap<"u"&&o instanceof ImageBitmap}function YS(o){const t=o.type;return t==="Mesh"||t==="SkinnedMesh"}function Km(o,t){t?o["needle:rendercustomshadow"]=!0:o["needle:rendercustomshadow"]=!1}function O0(o){if(o){if(o["needle:rendercustomshadow"]===!0)return!0;if(o["needle:rendercustomshadow"]==null)return!0}return!1}function li(o,t=void 0,e=void 0,i=void 0){const n=i||new d.Box3;n.makeEmpty();const s=[];function a(c){let h=!0;if(c.visible&&v0(c)!==!1&&!(c.type==="TransformControlsGizmo"||c.type==="TransformControlsPlane")){if(c instanceof d.Box3Helper&&(h=!1),c instanceof d.GridHelper&&(h=!1),c instanceof G.GroundedSkybox&&(h=!1),c.isGizmo===!0&&(h=!1),c.material instanceof d.ShadowMaterial&&(h=!1),YS(c)||(h=!1),e&&c.layers.test(e)===!1&&(h=!1),h){if(t&&Array.isArray(t)&&(t!=null&&t.includes(c)))return;if(typeof t=="function"&&t(c)===!0)return}if(c.isUI!==!0){if(h){const u=c.children;c.children=s;const f=c.position,p=c.scale;if(Number.isNaN(f.x)||Number.isNaN(f.y)||Number.isNaN(f.z)){console.warn(`Object "${c.name}" has NaN values in position or scale.... will ignore it`,f,p);return}c.geometry===null&&(c.geometry=void 0),n.expandByObject(c,!0),c.children=u}for(const u of c.children)a(u)}}}let l=!1;Array.isArray(o)||(o=[o]);for(const c of o)c&&(l=!0,c.updateMatrixWorld(),a(c));return l||console.warn("No objects to fit camera to..."),n}function k0(o,t,e){const i=li([o],e==null?void 0:e.ignore),n=new d.Vector3;i.getSize(n);const s=new d.Vector3;i.getCenter(s);const a=new d.Vector3;t.getSize(a);const l=new d.Vector3;t.getCenter(l);const c=new d.Vector3;c.set(a.x/n.x,a.y/n.y,a.z/n.z);const h=Math.min(c.x,c.y,c.z),u=(e==null?void 0:e.scale)!==!1;if(u&&za(o,Ue(o).multiplyScalar(h)),(e==null?void 0:e.position)!==!1){const f=new d.Vector3;i.getCenter(f),f.y=i.min.y;const p=new d.Vector3;t.getCenter(p),p.y=t.min.y;const g=p.clone().sub(f);u&&g.multiplyScalar(h),st(o,Q(o).add(g))}return{boundsBefore:i,scale:c}}function R0(o,t){const e=li([o]),i=new d.Vector3;e.getCenter(i),i.y=e.min.y;const n=t.clone().sub(i),s=Q(o);return st(o,s.add(n)),{offset:n,bounds:e}}function Zm(o,t,e,i){if(Array.isArray(t)){let a=!0;for(let l=0;l<t.length;l++)Zm(o,t[l],l,t)||(a=!1);return a}if(t.type==="MeshStandardMaterial"||t.type==="MeshBasicMaterial")return!1;if(t["material:fbx"]!=null)return!0;const n=new d.MeshStandardMaterial;n["material:fbx"]=t;const s=t;return s&&(s.map?n.color.set(1,1,1):n.color.copyLinearToSRGB(s.color),n.emissive.copyLinearToSRGB(s.emissive),n.emissiveIntensity=s.emissiveIntensity,n.opacity=s.opacity,n.displacementScale=s.displacementScale,n.transparent=s.transparent,n.bumpMap=s.bumpMap,n.aoMap=s.aoMap,n.map=s.map,n.displacementMap=s.displacementMap,n.emissiveMap=s.emissiveMap,n.normalMap=s.normalMap,n.envMap=s.envMap,n.alphaMap=s.alphaMap,n.metalness=s.reflectivity,n.vertexColors=s.vertexColors,s.shininess&&(n.roughness=1-Math.sqrt(s.shininess)/10),n.needsUpdate=!0),e===void 0?o.material=n:i[e]=n,!0}let Kh=!1;SS((...o)=>{var t;j()&&((t=re.Current)!=null&&t.isInXR)&&(br(!0),E0("error",...o))});function br(o){if(o){if(Kh)return;Kh=!0,ZS()}else{if(!Kh)return;Kh=!1,JS()}}const ac={log:void 0,warn:void 0,error:void 0};class KS{constructor(){r(this,"familyName","needle-xr");r(this,"root",null);r(this,"context",null);r(this,"defaultFontSize",.06);r(this,"targetObject",new d.Object3D);r(this,"userForwardViewPoint",new d.Vector3);r(this,"oneEuroFilter",new Gm(90,.8));r(this,"_lastElementRemoveTime",0);r(this,"onBeforeRender",()=>{var e,i;const t=(e=this.context)==null?void 0:e.mainCamera;if(this.context&&t instanceof d.PerspectiveCamera){const n=this.getRoot();Number.isNaN(n.position.x)&&n.position.set(0,0,0),Number.isNaN(n.quaternion.x)&&n.quaternion.set(0,0,0,1),this.context.scene.add(this.targetObject);const s=((i=this.context.xr)==null?void 0:i.rigScale)??1,a=3.5*s,l=t.worldForward;l.y=0,l.normalize().multiplyScalar(a),this.userForwardViewPoint.copy(t.worldPosition).sub(l),this.targetObject.position.distanceTo(this.userForwardViewPoint)>2*s&&(this.targetObject.position.copy(this.userForwardViewPoint),eh(this.targetObject,t,!0,!0),this.targetObject.rotateY(Math.PI)),this.oneEuroFilter.filter(this.targetObject.position,n.position,this.context.time.time);const h=this.context.time.deltaTime;if(n.quaternion.slerp(this.targetObject.quaternion,h*5),n.scale.setScalar(s),this.targetObject.removeFromParent(),this.context.scene.add(n),this.context.time.time-this._lastElementRemoveTime>.1){this._lastElementRemoveTime=this.context.time.time;const u=Date.now();for(let f=0;f<this._activeTexts.length;f++){const p=this._activeTexts[f];if(p instanceof ne.__webpack_exports__default.Text&&u-p._activatedTime>2e4){p.removeFromParent(),this._textBuffer.push(p),this._activeTexts.splice(f,1);break}}}}});r(this,"textOptions",{fontSize:this.defaultFontSize,fontFamily:this.familyName,padding:.03,margin:.005,color:0,backgroundColor:16777215,backgroundOpacity:.4,borderRadius:.03,offset:.025});r(this,"_textBuffer",[]);r(this,"_activeTexts",[]);this.ensureFont()}onEnable(){this.context=re.Current||re.All[0],this.context.pre_render_callbacks.push(this.onBeforeRender)}onDisable(){var t,e,i;(e=this.context)==null||e.pre_render_callbacks.splice((t=this.context)==null?void 0:t.pre_render_callbacks.indexOf(this.onBeforeRender),1),(i=this.root)==null||i.removeFromParent()}addLog(t,e){const i=this.getRoot(),n=this.getText();let s=16777215,a=0;switch(t){case"log":s=16777215,a=0;break;case"warn":s=16772761,a=4465152;break;case"error":s=16755370,a=7798784;break}e.length>1e3&&(e=e.substring(0,1e3)+"...");const l=new Date().toISOString().split("T")[1].split(".")[0];n.textContent="["+l+"] "+e,n.visible=!0,n._activatedTime=Date.now(),i.add(n),this._activeTexts.push(n),this.context&&this.context.scene.add(i),n.set({backgroundColor:s,color:a}),ne.__webpack_exports__default.update()}ensureFont(){let t=ne.__webpack_exports__default.FontLibrary.getFontFamily(this.familyName);if(!t){t=ne.__webpack_exports__default.FontLibrary.addFontFamily(this.familyName);const e=t.addVariant("normal","normal","./include/needle/arial-msdf.json","./include/needle/arial.png");e==null||e.addEventListener("ready",()=>{ne.__webpack_exports__default.update()})}}getText(){const t=this.getRoot();if(this._textBuffer.length>0){const i=this._textBuffer.pop();return i.visible=!0,setTimeout(()=>this.disableDepthTestRecursive(i),100),i}if(t.children.length>20&&this._activeTexts.length>0)return this._activeTexts.shift();const e=new ne.__webpack_exports__default.Text(this.textOptions);return setTimeout(()=>this.disableDepthTestRecursive(e),500),setTimeout(()=>this.disableDepthTestRecursive(e),1500),e}disableDepthTestRecursive(t,e=0){for(let n=0;n<t.children.length;n++){const s=t.children[n];s instanceof d.Object3D&&this.disableDepthTestRecursive(s,e+1)}t.renderOrder=10*e,t.layers.set(2);const i=t.material;i&&(i.depthWrite=!1,i.depthTest=!1,i.transparent=!0),e===0&&ne.__webpack_exports__default.update()}getRoot(){if(this.root)return this.root;const t=this.defaultFontSize,e={boxSizing:"border-box",fontFamily:this.familyName,width:"2.6",fontSize:t,color:0,lineHeight:1,backgroundColor:16777215,backgroundOpacity:0,whiteSpace:"pre-wrap",flexDirection:"column-reverse"};return this.root=new ne.__webpack_exports__default.Block(e),this.root}}let Ht=null;function ZS(){Ht||(Ht=new KS),Ht.onEnable();for(const o in ac){ac[o]=console[o];let t=!1;console[o]=function(){var e;if((e=ac[o])==null||e.apply(console,arguments),!t)try{t=!0,E0(o,...arguments)}finally{t=!1}}}}function JS(){Ht==null||Ht.onDisable();for(const o in ac)console[o]=ac[o]}const Ol=new Map;function E0(o,...t){try{switch(Ol.clear(),o){case"log":Ht==null||Ht.addLog("log",e());break;case"warn":Ht==null||Ht.addLog("warn",e());break;case"error":Ht==null||Ht.addLog("error",e());break}}catch(s){console.error("Error in spatial console",s)}finally{Ol.clear()}function e(){let s="";for(let a=0;a<t.length;a++){const l=t[a];s+=i(l),a<t.length-1&&(s+=", ")}return s}function i(s,a=0){if(typeof s=="string")return'"'+s+'"';if(typeof s=="number"){if(s%1!==0){const c=s.toFixed(5),h=c.indexOf(".");let u=c.length-1;for(;u>h&&c[u]==="0";)u--;return c.substring(0,u+1)}return s.toString()}else if(Array.isArray(s)){let l="[";for(let c=0;c<s.length;c++){const h=s[c];l+=i(h,a+1),c<s.length-1&&(l+=", ")}return l+="]",l}else{if(s===null)return"null";if(s===void 0)return"undefined";if(typeof s=="function")return s.name+"()"}if(s instanceof d.Vector2)return`(${i(s.x)}, ${i(s.y)})`;if(s instanceof d.Vector3)return`(${i(s.x)}, ${i(s.y)}, ${i(s.z)})`;if(s instanceof d.Vector4)return`(${i(s.x)}, ${i(s.y)}, ${i(s.z)}, ${i(s.w)})`;if(s instanceof d.Quaternion)return`(${i(s.x)}, ${i(s.y)}, ${i(s.z)}, ${i(s.w)})`;if(s instanceof d.Material||s instanceof d.Texture)return s.name;if(s instanceof d.Matrix3)return`[${s.elements.join(", ")}]`;if(s instanceof d.Matrix4)return`[${s.elements.join(", ")}]`;if(s instanceof d.Layers)return s.mask.toString();if(typeof s=="object"){if(Ol.has(s))return"*";let l=`{
83
83
  `;l+=n(a);const c=Object.keys(s);let h="";for(let u=0;u<c.length;u++){const f=c[u],p=s[f];if(Ol.has(p)){h+="";continue}Ol.set(p,!0),h+=f+":"+i(p,a+1),u<c.length-1&&(h+=", "),h.length>=60&&(h+=`
84
84
  `,h+=n(a),l+=h,h="")}return l+=h,l+=`
85
85
  }`,l}return s}function n(s){let a="";for(let l=0;l<s;l++)a+=" ";return a}}const eC=S("nodevlogs");function Ee(o,t=Mi.Log){Fn(t,o)}function me(o){Ee(o,Mi.Warn)}function ih(o){Ee(o,Mi.Error)}let Jp,Gf;function j(){if(eC)return!1;if(Jp!==void 0)return Jp;if(Gf!==void 0)return Gf;let o=Yt();return o||(o=window.location.hostname.endsWith(".local-credentialless.webcontainer.io")),Gf=o,o}function tC(o){Jp=o}let qt,vi=null,Un=null,kl=!1,d_=null;const T0="terminal",Gl=S("console"),iC=S("noerrors")||S("noconsole")||window.crossOriginIsolated;Gl&&Jm();if(!iC&&(Gl||Yt())){if(Yt()&&!Gl){const t=new URL(window.location.href);t.searchParams.set("console","1"),console.log('🌵 Tip: You can add the "?console" query parameter to the url to show the debug console (on mobile it will automatically open in the bottom right corner when your get errors during development. In VR a spatial console will appear.)',`
@@ -142,7 +142,7 @@ Open this page to get the console: `+t.toString())}const o=exports.DeviceUtiliti
142
142
  #__vconsole .vc-mask {
143
143
  overflow: hidden;
144
144
  }
145
- `,vi==null||vi.prepend(i),o===!0&&Hm()<=0&&A0(),console.log("🌵 Debug console has loaded")}},t.onerror=()=>{console.warn("🌵 Debug console failed to load."+(window.crossOriginIsolated?"This page is using cross-origin isolation, so external scripts can't be loaded.":"")),kl=!1,qt=null},t.src="https://cdn.jsdelivr.net/npm/vconsole@3.9.1/dist/vconsole.min.js",document.body.appendChild(t)}function aC(){if(!globalThis.VConsole)return;const o=new VConsole.VConsolePlugin("needle-console","🌵 Inspect glTF"),t=()=>document.querySelector("#__vc_plug_"+o._id+" iframe");return o.on("renderTab",function(e){const i=globalThis["needle:codegen_files"];if(!i||i.length===0)return;let n=globalThis["needle:codegen_files"][0];const s=n.indexOf("?");s>-1&&(n=n.substring(0,s));const l=location.protocol+"//"+location.host+location.pathname+"/"+n,c=encodeURIComponent(l);o.fullUrl="https://viewer.needle.tools?inspect&file="+c;var h='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';e(h)}),o.on("show",function(){const e=t();e&&e.src!==o.fullUrl&&(e.src=o.fullUrl)}),o.on("hide",function(){const e=t();e&&(e.src="")}),o.on("addTopBar",function(e){var i=new Array;i.push({name:"Open in new window ↗",onClick:function(n){window.open(o.fullUrl,"_blank"),qt==null||qt.hide()}}),i.push({name:"Reload",onClick:function(n){const s=t();s&&(s.src=o.fullUrl)}}),i.push({name:"Fullscreen",onClick:function(n){const s=t();s.requestFullscreen?s.requestFullscreen():s.webkitRequestFullscreen instanceof Function&&s.webkitRequestFullscreen()}}),e(i)}),o}function lC(){const o=document.querySelector("#__vconsole .vc-switch");return o||null}function cC(){const o=document.querySelector("#__vconsole");return o||null}const I0=S("debugdefines");Ao('if(!globalThis["NEEDLE_ENGINE_VERSION"]) globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";');Ao('if(!globalThis["NEEDLE_ENGINE_GENERATOR"]) globalThis["NEEDLE_ENGINE_GENERATOR"] = "unknown";');Ao('if(!globalThis["NEEDLE_PROJECT_BUILD_TIME"]) globalThis["NEEDLE_PROJECT_BUILD_TIME"] = "unknown";');Ao('if(!globalThis["NEEDLE_PUBLIC_KEY"]) globalThis["NEEDLE_PUBLIC_KEY"] = "unknown";');Ao('globalThis["__NEEDLE_ENGINE_VERSION__"] = "4.7.0-alpha";');Ao('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";');Ao('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Thu Jul 24 2025 13:57:39 GMT+0000 (Coordinated Universal Time)";');Ao('globalThis["__NEEDLE_PUBLIC_KEY__"] = "'+NEEDLE_PUBLIC_KEY+'";');const _n="4.7.0-alpha",Bu="undefined",eg="Thu Jul 24 2025 13:57:39 GMT+0000 (Coordinated Universal Time)";I0&&console.log(`Engine version: ${_n} (generator: ${Bu})
145
+ `,vi==null||vi.prepend(i),o===!0&&Hm()<=0&&A0(),console.log("🌵 Debug console has loaded")}},t.onerror=()=>{console.warn("🌵 Debug console failed to load."+(window.crossOriginIsolated?"This page is using cross-origin isolation, so external scripts can't be loaded.":"")),kl=!1,qt=null},t.src="https://cdn.jsdelivr.net/npm/vconsole@3.9.1/dist/vconsole.min.js",document.body.appendChild(t)}function aC(){if(!globalThis.VConsole)return;const o=new VConsole.VConsolePlugin("needle-console","🌵 Inspect glTF"),t=()=>document.querySelector("#__vc_plug_"+o._id+" iframe");return o.on("renderTab",function(e){const i=globalThis["needle:codegen_files"];if(!i||i.length===0)return;let n=globalThis["needle:codegen_files"][0];const s=n.indexOf("?");s>-1&&(n=n.substring(0,s));const l=location.protocol+"//"+location.host+location.pathname+"/"+n,c=encodeURIComponent(l);o.fullUrl="https://viewer.needle.tools?inspect&file="+c;var h='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';e(h)}),o.on("show",function(){const e=t();e&&e.src!==o.fullUrl&&(e.src=o.fullUrl)}),o.on("hide",function(){const e=t();e&&(e.src="")}),o.on("addTopBar",function(e){var i=new Array;i.push({name:"Open in new window ↗",onClick:function(n){window.open(o.fullUrl,"_blank"),qt==null||qt.hide()}}),i.push({name:"Reload",onClick:function(n){const s=t();s&&(s.src=o.fullUrl)}}),i.push({name:"Fullscreen",onClick:function(n){const s=t();s.requestFullscreen?s.requestFullscreen():s.webkitRequestFullscreen instanceof Function&&s.webkitRequestFullscreen()}}),e(i)}),o}function lC(){const o=document.querySelector("#__vconsole .vc-switch");return o||null}function cC(){const o=document.querySelector("#__vconsole");return o||null}const I0=S("debugdefines");Ao('if(!globalThis["NEEDLE_ENGINE_VERSION"]) globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";');Ao('if(!globalThis["NEEDLE_ENGINE_GENERATOR"]) globalThis["NEEDLE_ENGINE_GENERATOR"] = "unknown";');Ao('if(!globalThis["NEEDLE_PROJECT_BUILD_TIME"]) globalThis["NEEDLE_PROJECT_BUILD_TIME"] = "unknown";');Ao('if(!globalThis["NEEDLE_PUBLIC_KEY"]) globalThis["NEEDLE_PUBLIC_KEY"] = "unknown";');Ao('globalThis["__NEEDLE_ENGINE_VERSION__"] = "4.7.0";');Ao('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";');Ao('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Mon Jul 28 2025 09:07:25 GMT+0000 (Coordinated Universal Time)";');Ao('globalThis["__NEEDLE_PUBLIC_KEY__"] = "'+NEEDLE_PUBLIC_KEY+'";');const _n="4.7.0",Bu="undefined",eg="Mon Jul 28 2025 09:07:25 GMT+0000 (Coordinated Universal Time)";I0&&console.log(`Engine version: ${_n} (generator: ${Bu})
146
146
  Project built at ${eg}`);const _a=NEEDLE_PUBLIC_KEY,Es="needle_isActiveInHierarchy",tr="builtin_components",lc="needle_editor_guid";function Ao(o){try{(0,eval)(o)}catch(t){I0&&console.error(t)}}let j0,f_=null;function vn(){return j0}function tg(o){if(o==null){console.warn("Oh no: someone tried registering a non-existend gltf-loader. When you see this log it might mean that needle-engine is being imported multiple times. Please check your project setup.");return}f_!==o&&(f_=o,j0=new o)}const Si=Symbol("shadowDomOwner"),hC=S("debugpatch");function Fu(o,t,e,i){const n=hC===t;if(!e&&!i)return;const s=t+"___needle";uC(o,t,e,i);const a=Object.getOwnPropertyDescriptor(o,t),l=o[t];n&&console.log("Patch",o.constructor.name,t,a,l),a?(n&&console.log("Apply patch with existing descriptor",o.constructor.name,t,a),typeof a.value=="function"&&(o[t]=m_(a.value,o,t))):(n&&console.log("Create patch with new property",o.constructor.name,t,a),Object.defineProperty(o,t,{set:function(c){if(typeof c=="function")this[s]=m_(c,o,t);else{const h=this[s];B0(o,t,this,h,c),this[s]=c,F0(o,t,this,h,c)}},get:function(){const c=this[s];return typeof c=="function"&&c[s]?c[s]:c}}))}function dC(o,t,e){const i=ig(o,t);if(i)for(let n=i.length-1;n>=0;n--){const s=i[n];s.prefix===e&&(s.prefix=null),s.postfix===e&&(s.postfix=null),!s.prefix&&!s.postfix&&i.splice(n,1)}}const p_=Symbol("Needle:Patches:WrappedFunction");function m_(o,t,e){if(o[p_])return o;const i=function(...n){B0(t,e,this,...n);const s=o.apply(this,n);return F0(t,e,this,s,...n),s};return i[p_]=!0,i}const kd="Needle:Patches";function tm(){return globalThis[kd]||(globalThis[kd]=new WeakMap),globalThis[kd]}function ig(o,t){const e=tm().get(o);return e?e.get(t):null}function uC(o,t,e,i){let n=tm().get(o);n||(n=new Map,tm().set(o,n));let s=n.get(t);s||(s=[],n.set(t,s)),s.push({prefix:e,postfix:i})}function B0(o,t,e,...i){var s;if(!e)return;const n=ig(o,t);if(n)for(const a of n)(s=a.prefix)==null||s.call(e,...i)}function F0(o,t,e,i,...n){var a;if(!e)return;const s=ig(o,t);if(s)for(const l of s)(a=l.postfix)==null||a.call(e,i,...n)}const Na=[];function Uu(o){Na.indexOf(o)===-1&&Na.push(o)}function fC(o){const t=Na.indexOf(o);t!==-1&&Na.splice(t,1)}const Va=[];function ng(o){Va.indexOf(o)===-1&&Va.push(o)}function pC(o){const t=Va.indexOf(o);t!==-1&&Va.splice(t,1)}function U0(o){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-start",{detail:o}));for(let t=0;t<Na.length;t++)Na[t](o)}function z0(o){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-end",{detail:o}));for(let t=0;t<Va.length;t++)Va[t](o)}const et=S("debuginput");var zu=(o=>(o.Mouse="mouse",o.Touch="touch",o.Controller="controller",o.Hand="hand",o))(zu||{}),Re=(o=>(o.PointerDown="pointerdown",o.PointerUp="pointerup",o.PointerMove="pointermove",o.KeyDown="keydown",o.KeyUp="keyup",o.KeyPressed="keypress",o))(Re||{});class ys extends PointerEvent{constructor(e,i,n){super(e,n);r(this,"clientZ");r(this,"deviceIndex");r(this,"origin");r(this,"source");r(this,"mode");r(this,"_ray");r(this,"space");r(this,"isClick",!1);r(this,"isDoubleClick",!1);r(this,"_used",!1);r(this,"_pointerid");r(this,"_pointerType");r(this,"_type");r(this,"metadata",{});r(this,"intersections",new Array);r(this,"_immediatePropagationStopped",!1);r(this,"_propagationStopped",!1);this.clientZ=n.clientZ,this._pointerid=n.pointerId,this._pointerType=n.pointerType,this._type=e,this.deviceIndex=n.deviceIndex,this.origin=n.origin,this.source=i,this.mode=n.mode,this._ray=n.ray,this.space=n.device}get isSpatial(){return this.mode!="screen"}get ray(){return this._ray||(this._ray=new d.Ray(this.space.worldPosition.clone(),this.space.worldForward.clone())),this._ray}set ray(e){this._ray=e}get hasRay(){return this._ray!==void 0}get used(){return this._used}use(){this._used=!0}get pointerId(){return this._pointerid}get pointerType(){return this._pointerType}get type(){return this._type}get immediatePropagationStopped(){return this._immediatePropagationStopped}get propagationStopped(){return this._immediatePropagationStopped||this._propagationStopped}stopImmediatePropagation(){var e;this._immediatePropagationStopped=!0,super.stopImmediatePropagation(),(e=this.source)==null||e.stopImmediatePropagation()}stopPropagation(){var e;this._propagationStopped=!0,super.stopPropagation(),(e=this.source)==null||e.stopPropagation(),et&&console.warn("Stop propagation...",this.pointerId,this.pointerType)}}class ql extends KeyboardEvent{constructor(e,i,n){super(e,n);r(this,"source");this.source=i}stopImmediatePropagation(){var e;super.stopImmediatePropagation(),(e=this.source)==null||e.stopImmediatePropagation()}}class mC{constructor(t){r(this,"key");r(this,"keyType");r(this,"source");this.key=t.key,this.keyType=t.type,this.source=t}}var oi=(o=>(o[o.Early=-100]="Early",o[o.Default=0]="Default",o[o.Late=100]="Late",o))(oi||{});class N0{constructor(t){r(this,"_eventListeners",{});r(this,"_doubleClickTimeThreshold",.2);r(this,"_longPressTimeThreshold",1);r(this,"_setCursorTypes",[]);r(this,"context");r(this,"_pointerDown",[!1]);r(this,"_pointerUp",[!1]);r(this,"_pointerClick",[!1]);r(this,"_pointerDoubleClick",[!1]);r(this,"_pointerPressed",[!1]);r(this,"_pointerPositions",[new d.Vector2]);r(this,"_pointerPositionsLastFrame",[new d.Vector2]);r(this,"_pointerPositionsDelta",[new d.Vector2]);r(this,"_pointerPositionsRC",[new d.Vector2]);r(this,"_pointerPositionDown",[new d.Vector3]);r(this,"_pointerDownTime",[]);r(this,"_pointerUpTime",[]);r(this,"_pointerUpTimestamp",[]);r(this,"_pointerIds",[]);r(this,"_pointerTypes",[""]);r(this,"_mouseWheelChanged",[!1]);r(this,"_mouseWheelDeltaY",[0]);r(this,"_pointerEvent",[]);r(this,"_pointerEventsPressed",[]);r(this,"_pointerSpace",[]);r(this,"_pressedStack",new Map);r(this,"_htmlEventSource");r(this,"onLostFocus",()=>{for(const t in this.keysPressed)this.keysPressed[t].pressed=!1});r(this,"_receivedPointerMoveEventsThisFrame",new Array);r(this,"onEndOfFrame",()=>{this._receivedPointerMoveEventsThisFrame.length=0;for(let t=0;t<this._pointerUp.length;t++)this._pointerUp[t]=!1;for(let t=0;t<this._pointerDown.length;t++)this._pointerDown[t]=!1;for(let t=0;t<this._pointerClick.length;t++)this._pointerClick[t]=!1;for(let t=0;t<this._pointerDoubleClick.length;t++)this._pointerDoubleClick[t]=!1;for(const t of this._pointerPositionsDelta)t.set(0,0);for(let t=0;t<this._mouseWheelChanged.length;t++)this._mouseWheelChanged[t]=!1;for(let t=0;t<this._mouseWheelDeltaY.length;t++)this._mouseWheelDeltaY[t]=0});r(this,"onContextMenu",t=>{this.canReceiveInput(t)!==!1&&t instanceof PointerEvent&&t.pointerType});r(this,"keysPressed",{});r(this,"onKeyDown",t=>{if(et&&console.log(`key down ${t.code}, ${this.context.application.hasFocus}`,t),!this.context.application.hasFocus)return;const e=this.keysPressed[t.code];if(e&&e.pressed)return;this.keysPressed[t.code]={pressed:!0,frame:this.context.time.frameCount+1,startFrame:this.context.time.frameCount+1,key:t.key,code:t.code};const i=new ql("keydown",t,t);this.onDispatchEvent(i)});r(this,"onKeyPressed",t=>{if(!this.context.application.hasFocus)return;const e=this.keysPressed[t.code];if(!e)return;e.pressed=!0,e.frame=this.context.time.frameCount+1;const i=new ql("keypress",t,t);this.onDispatchEvent(i)});r(this,"onKeyUp",t=>{if(!this.context.application.hasFocus)return;const e=this.keysPressed[t.code];if(!e)return;e.pressed=!1,e.frame=this.context.time.frameCount+1;const i=new ql("keyup",t,t);this.onDispatchEvent(i)});r(this,"onWheelWindow",t=>{document.pointerLockElement&&this.onMouseWheel(t)});r(this,"onMouseWheel",t=>{if(this.canReceiveInput(t)===!1)return;this._mouseWheelDeltaY.length<=0&&this._mouseWheelDeltaY.push(0),this._mouseWheelChanged.length<=0&&this._mouseWheelChanged.push(!1),this._mouseWheelChanged[0]=!0;const e=this._mouseWheelDeltaY[0];this._mouseWheelDeltaY[0]=e+t.deltaY});r(this,"onPointerDown",t=>{if(this.context.isInAR||this.canReceiveInput(t)===!1)return;t.target instanceof HTMLElement&&t.target.setPointerCapture(t.pointerId);const e=this.getPointerId(t);et&&Ee(`pointer down #${e}, identifier:${t.pointerId}`);const i=this.getAndUpdateSpatialObjectForScreenPosition(e,t.clientX,t.clientY),n=new ys("pointerdown",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:e,button:t.button,clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,buttonName:this.getButtonName(t),device:i,pressure:t.pressure});this.onDown(n)});r(this,"onPointerMove",t=>{if(this.context.isInAR||this._receivedPointerMoveEventsThisFrame.includes(t.pointerId))return;this._receivedPointerMoveEventsThisFrame.push(t.pointerId);let e=t.button;t.pointerType==="mouse"&&(e=this.getFirstPressedButtonForPointer(0)??0);const i=this.getPointerId(t,e);e===-1&&(e=i);const n=this.getAndUpdateSpatialObjectForScreenPosition(i,t.clientX,t.clientY),s=new ys("pointermove",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:i,button:e,clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,buttonName:this.getButtonName(t),device:n,pressure:t.pressure});this.onMove(s)});r(this,"onPointerCancel",t=>{this.context.isInAR||(et&&console.log("Pointer cancel",t),this.onPointerUp(t))});r(this,"onPointerUp",t=>{if(this.context.isInAR)return;t.target instanceof HTMLElement&&t.target.releasePointerCapture(t.pointerId);const e=this.getPointerId(t),i=new ys("pointerup",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:e,button:t.button,clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,buttonName:this.getButtonName(t),device:this.getAndUpdateSpatialObjectForScreenPosition(e,t.clientX,t.clientY),pressure:t.pressure});this.onUp(i),this._pointerIds[e]=-1,et&&console.log("ID="+e,"PointerId="+t.pointerId,"ALL:",[...this._pointerIds])});r(this,"onTouchStart",t=>{if(this.context.isInAR)for(let e=0;e<t.changedTouches.length;e++){const i=t.changedTouches[e],n=this.getPointerIndex(i.identifier),s=this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),a=new ys("pointerdown",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:0,clientX:i.clientX,clientY:i.clientY,pointerType:"touch",buttonName:"unknown",device:s,pressure:i.force});this.onDown(a)}});r(this,"onTouchMove",t=>{if(this.context.isInAR)for(let e=0;e<t.changedTouches.length;e++){const i=t.changedTouches[e],n=this.getPointerIndex(i.identifier),s=this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),a=new ys("pointermove",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:0,clientX:i.clientX,clientY:i.clientY,pointerType:"touch",buttonName:"unknown",device:s,pressure:i.force});this.onMove(a)}});r(this,"onTouchEnd",t=>{if(this.context.isInAR)for(let e=0;e<t.changedTouches.length;e++){const i=t.changedTouches[e],n=this.getPointerIndex(i.identifier),s=new ys("pointerup",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:0,clientX:i.clientX,clientY:i.clientY,pointerType:"touch",buttonName:"unknown",device:this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),pressure:i.force});this.onUp(s),this._pointerIds[n]=-1}});r(this,"tempNearPlaneVector",new d.Vector3);r(this,"tempFarPlaneVector",new d.Vector3);r(this,"tempLookMatrix",new d.Matrix4);this.context=t,this.context.post_render_callbacks.push(this.onEndOfFrame)}addEventListener(t,e,i){if(this._eventListeners[t]||(this._eventListeners[t]=[]),!e||typeof e!="function"){console.error("Invalid call to addEventListener: callback is required and must be a function!");return}i?i={...i}:i={};let n=0;(i==null?void 0:i.queue)!=null&&(n=i.queue);const s=this._eventListeners[t],a=s.find(l=>l.priority===n);a?a.listeners.push({callback:e,options:i}):(s.push({priority:n,listeners:[{callback:e,options:i}]}),s.sort((l,c)=>l.priority-c.priority))}removeEventListener(t,e,i){if(!this._eventListeners[t]||!e)return;const n=this._eventListeners[t];if((i==null?void 0:i.queue)!=null){const s=n.find(l=>l.priority===i.queue);if(!s)return;const a=s.listeners.findIndex(l=>l.callback===e);a>=0&&s.listeners.splice(a,1)}else for(const s of n){const a=s.listeners.findIndex(l=>l.callback===e);a>=0&&s.listeners.splice(a,1)}}dispatchEvent(t){var i,n,s,a;let e=!1;if(t instanceof ql){const l=this._eventListeners[t.type];if(l)for(const c of l)for(let h=0;h<c.listeners.length;h++){const u=c.listeners[h];if((n=(i=u.options)==null?void 0:i.signal)!=null&&n.aborted){c.listeners.splice(h,1),h--;continue}u.options.once&&(c.listeners.splice(h,1),h--),u.callback(t)}}if(t instanceof ys){const l=this._eventListeners[t.type];if(l)for(const c of l){if(e)break;for(let h=0;h<c.listeners.length;h++){const u=c.listeners[h];if((a=(s=u.options)==null?void 0:s.signal)!=null&&a.aborted){c.listeners.splice(h,1),h--;continue}if(t.immediatePropagationStopped){e=!0,et&&console.log("immediatePropagationStopped",t.type);break}else t.propagationStopped&&(e=!0,et&&console.log("propagationStopped",t.type));u.options.once&&(c.listeners.splice(h,1),h--),u.callback(t)}}}}get mousePosition(){return this._pointerPositions[0]}get mousePositionRC(){return this._pointerPositionsRC[0]}get mouseDown(){return this._pointerDown[0]}get mouseUp(){return this._pointerUp[0]}get mouseClick(){return this._pointerClick[0]}get mouseDoubleClick(){return this._pointerDoubleClick[0]}get mousePressed(){return this._pointerPressed[0]}get mouseWheelChanged(){return this.getMouseWheelChanged(0)}get click(){return this._pointerClick[0]}get doubleClick(){return this._pointerDoubleClick[0]}getGamepad(t=0){return typeof navigator<"u"&&"getGamepads"in navigator&&navigator.getGamepads()[t]||null}setCursorPointer(){this.setCursor("pointer")}setCursorNormal(){this.unsetCursor("pointer")}setCursor(t){this._setCursorTypes.push(t),this._setCursorTypes.length>10&&this._setCursorTypes.shift(),this.updateCursor()}unsetCursor(t){for(let e=this._setCursorTypes.length-1;e>=0;e--)if(this._setCursorTypes[e]===t){this._setCursorTypes.splice(e,1),this.updateCursor();break}}updateCursor(){var t;((t=this._setCursorTypes)==null?void 0:t.length)==0?this.context.domElement.style.cursor="default":this.context.domElement.style.cursor=this._setCursorTypes[this._setCursorTypes.length-1]}getIsPointerIdInUse(t){for(const e of this._pointerEventsPressed)if(e.pointerId===t&&e.used)return!0;return!1}getPointerPressedCount(){let t=0;for(let e=0;e<this._pointerPressed.length;e++)this._pointerPressed[e]&&t++;return t}getPointerPosition(t){return t>=this._pointerPositions.length?null:this._pointerPositions[t]}getPointerPositionLastFrame(t){return t>=this._pointerPositionsLastFrame.length?null:this._pointerPositionsLastFrame[t]}getPointerPositionDelta(t){return t>=this._pointerPositionsDelta.length?null:this._pointerPositionsDelta[t]}getPointerPositionRC(t){return t>=this._pointerPositionsRC.length?null:this._pointerPositionsRC[t]}getPointerDown(t){return t>=this._pointerDown.length?!1:this._pointerDown[t]}getPointerUp(t){return t>=this._pointerUp.length?!1:this._pointerUp[t]}getPointerPressed(t){return t>=this._pointerPressed.length?!1:this._pointerPressed[t]}getPointerClicked(t){return t>=this._pointerClick.length?!1:this._pointerClick[t]}getPointerDoubleClicked(t){return t>=this._pointerDoubleClick.length?!1:this._pointerDoubleClick[t]}getPointerDownTime(t){return t>=this._pointerDownTime.length?-1:this._pointerDownTime[t]}getPointerUpTime(t){return t>=this._pointerUpTime.length?-1:this._pointerUpTime[t]}getPointerLongPress(t){return t>=this._pointerDownTime.length?!1:this.getPointerPressed(t)&&this.context.time.time-this._pointerDownTime[t]>this._longPressTimeThreshold}getIsMouse(t){return t<0||t>=this._pointerTypes.length?!1:this._pointerTypes[t]==="mouse"}getIsTouch(t){return t<0||t>=this._pointerTypes.length?!1:this._pointerTypes[t]==="touch"}getTouchesPressedCount(){let t=0;for(let e=0;e<this._pointerPressed.length;e++)this._pointerPressed[e]&&this.getIsTouch(e)&&t++;return t}getMouseWheelChanged(t=0){return t>=this._mouseWheelChanged.length?!1:this._mouseWheelChanged[t]}getMouseWheelDeltaY(t=0){return t>=this._mouseWheelDeltaY.length?0:this._mouseWheelDeltaY[t]}getPointerEvent(t){if(!(t>=this._pointerEvent.length))return this._pointerEvent[t]??void 0}*foreachPointerId(t){for(let e=0;e<this._pointerTypes.length;e++)if(this._pointerIsActive(e)){if(t!==void 0){const i=this._pointerTypes[e];if(Array.isArray(t)){let n=!1;for(const s of t)if(i===s){n=!0;break}if(!n)continue}else if(t!==i)continue}yield e}}*foreachTouchId(){for(let t=0;t<this._pointerTypes.length;t++)this._pointerTypes[t]==="touch"&&this._pointerIsActive[t]&&(yield t)}_pointerIsActive(t){return t<0?!1:this._pointerPressed[t]||this._pointerDown[t]||this._pointerUp[t]}onDownButton(t,e){let i=this._pressedStack.get(t);i||(i=[],this._pressedStack.set(t,i)),i.push(e)}onReleaseButton(t,e){const i=this._pressedStack.get(t);if(!i)return;const n=i.indexOf(e);n>=0&&i.splice(n,1)}getFirstPressedButtonForPointer(t){const e=this._pressedStack.get(t);if(e)return e[0]}getLatestPressedButtonForPointer(t){const e=this._pressedStack.get(t);if(e)return e[e.length-1]}getKeyDown(t){if(t!==void 0)return this.isKeyDown(t);for(const e in this.keysPressed){const i=this.keysPressed[e];if(i.startFrame===this.context.time.frameCount)return i.key}return null}getKeyPressed(t){if(t!==void 0)return this.isKeyPressed(t);for(const e in this.keysPressed){const i=this.keysPressed[e];if(i.pressed)return i.key}return null}getKeyUp(t){if(t!==void 0)return this.isKeyUp(t);for(const e in this.keysPressed){const i=this.keysPressed[e];return i.pressed===!1&&i.frame===this.context.time.frameCount}return null}isKeyDown(t){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const e=this.getCodeForCommonKeyName(t);if(e!==null){for(const n of e)if(this.isKeyDown(n))return!0;return!1}const i=this.keysPressed[t];return i?i.startFrame===this.context.time.frameCount&&i.pressed:!1}isKeyUp(t){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const e=this.getCodeForCommonKeyName(t);if(e!==null){for(const n of e)if(this.isKeyUp(n))return!0;return!1}const i=this.keysPressed[t];return i?i.frame===this.context.time.frameCount&&i.pressed===!1:!1}isKeyPressed(t){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const e=this.getCodeForCommonKeyName(t);if(e!==null){for(const n of e)if(this.isKeyPressed(n))return!0;return!1}const i=this.keysPressed[t];return i&&i.pressed||!1}getCodeForCommonKeyName(t){if(t.length===1){if(t>="0"&&t<="9")return["Digit"+t];if(t>="a"&&t<="z")return["Key"+t.toUpperCase()];if(t==" ")return["Space"]}switch(t){case"shift":case"Shift":return["ShiftLeft","ShiftRight"];case"control":case"Control":return["ControlLeft","ControlRight"];case"alt":case"Alt":return["AltLeft","AltRight"]}return null}createInputEvent(t){switch(t.type){case"pointerdown":et&&Ee("Create Pointer down"),this.onDownButton(t.deviceIndex,t.button),this.onDown(t);break;case"pointermove":et&&Ee("Create Pointer move"),this.onMove(t);break;case"pointerup":et&&Ee("Create Pointer up"),this.onUp(t),this.onReleaseButton(t.deviceIndex,t.button);break}}convertScreenspaceToRaycastSpace(t){return t.x=(t.x-this.context.domX)/this.context.domWidth*2-1,t.y=-((t.y-this.context.domY)/this.context.domHeight)*2+1,t}bindEvents(){this.unbindEvents(),this._htmlEventSource=this.context.renderer.domElement,window.addEventListener("contextmenu",this.onContextMenu),this._htmlEventSource.addEventListener("pointerdown",this.onPointerDown,{passive:!0}),window.addEventListener("pointermove",this.onPointerMove,{passive:!0,capture:!0}),window.addEventListener("pointerup",this.onPointerUp,{passive:!0}),window.addEventListener("pointercancel",this.onPointerCancel,{passive:!0}),window.addEventListener("touchstart",this.onTouchStart,{passive:!0}),window.addEventListener("touchmove",this.onTouchMove,{passive:!0}),window.addEventListener("touchend",this.onTouchEnd,{passive:!0}),this._htmlEventSource.addEventListener("wheel",this.onMouseWheel,{passive:!0}),window.addEventListener("wheel",this.onWheelWindow,{passive:!0}),window.addEventListener("keydown",this.onKeyDown,!1),window.addEventListener("keypress",this.onKeyPressed,!1),window.addEventListener("keyup",this.onKeyUp,!1),window.addEventListener("blur",this.onLostFocus)}unbindEvents(){var t,e;window.removeEventListener("contextmenu",this.onContextMenu),(t=this._htmlEventSource)==null||t.removeEventListener("pointerdown",this.onPointerDown),window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),window.removeEventListener("pointercancel",this.onPointerCancel),window.removeEventListener("touchstart",this.onTouchStart),window.removeEventListener("touchmove",this.onTouchMove),window.removeEventListener("touchend",this.onTouchEnd),(e=this._htmlEventSource)==null||e.removeEventListener("wheel",this.onMouseWheel,!1),window.removeEventListener("wheel",this.onWheelWindow,!1),window.removeEventListener("keydown",this.onKeyDown,!1),window.removeEventListener("keypress",this.onKeyPressed,!1),window.removeEventListener("keyup",this.onKeyUp,!1),window.removeEventListener("blur",this.onLostFocus)}dispose(){const t=this.context.post_render_callbacks.indexOf(this.onEndOfFrame);t>=0&&this.context.post_render_callbacks.splice(t,1),this.unbindEvents()}canReceiveInput(t){var e;return t.target===((e=this.context.renderer)==null?void 0:e.domElement)||t.target===this.context.domElement||this.context.isInAR||this.context.isInAR&&t.target===document.body&&exports.DeviceUtilities.isMozillaXR()?!0:(et&&console.warn("CanReceiveInput:False for",t.target),!1)}getPointerId(t,e){return t.pointerType==="mouse"?0+(e??t.button):this.getPointerIndex(t.pointerId)}getButtonName(t){const e=t.button;if(t.pointerType==="mouse")switch(e){case 0:return"left";case 1:return"middle";case 2:return"right"}return"unknown"}getAndUpdateSpatialObjectForScreenPosition(t,e,i){let n=this._pointerSpace[t];n||(n=new d.Object3D,this._pointerSpace[t]=n),this._pointerSpace[t]=n;const s=this.context.mainCamera;if(s){const a=this.tempNearPlaneVector.set(e,i,-1);this.convertScreenspaceToRaycastSpace(a);const l=this.tempFarPlaneVector.set(a.x,a.y,1);a.unproject(s),l.unproject(s);const c=s.worldUp||$(0,1,0).applyQuaternion(_e(s));this.tempLookMatrix.lookAt(l,a,c),n.position.set(a.x,a.y,a.z),n.quaternion.setFromRotationMatrix(this.tempLookMatrix)}return n}isInRect(t){if(this.context.isInXR)return!0;const e=this.context.domElement.getBoundingClientRect(),i=t.clientX,n=t.clientY,s=i>=e.x&&i<=e.right&&n>=e.y&&n<=e.bottom;return et&&!s&&console.log("Not in rect",e,i,n),s}onDown(t){const e=t.pointerId;if(this.getPointerPressed(e)&&console.warn(`Received pointerDown for pointerId that is already pressed: ${e}`,et?t:""),et&&console.log(t.pointerType,"DOWN",e),!!this.isInRect(t)){for(this.setPointerState(e,this._pointerPressed,!0),this.setPointerState(e,this._pointerDown,!0),this.setPointerStateT(e,this._pointerEvent,t.source);e>=this._pointerTypes.length;)this._pointerTypes.push(t.pointerType);for(this._pointerTypes[e]=t.pointerType;e>=this._pointerPositionDown.length;)this._pointerPositionDown.push(new d.Vector3);for(this._pointerPositionDown[e].set(t.clientX,t.clientY,t.clientZ??0);e>=this._pointerPositions.length;)this._pointerPositions.push(new d.Vector2);this._pointerPositions[e].set(t.clientX,t.clientY),e>=this._pointerDownTime.length&&this._pointerDownTime.push(0),this._pointerDownTime[e]=this.context.time.realtimeSinceStartup,this.updatePointerPosition(t),this._pointerEventsPressed.push(t),this.onDispatchEvent(t)}}onMove(t){const e=t.pointerId,i=this.getPointerPressed(e);i===!1&&!this.isInRect(t)||t.pointerType==="touch"&&!i||(this.updatePointerPosition(t),this.setPointerStateT(e,this._pointerEvent,t.source),this.onDispatchEvent(t))}onUp(t){const e=t.pointerId;if(!this.getPointerPressed(e)){et&&console.log(t.pointerType,"UP",e,"was not down");return}et&&console.log(t.pointerType,"UP",e),this.setPointerState(e,this._pointerPressed,!1),this.setPointerStateT(e,this._pointerEvent,t.source),this.setPointerState(e,this._pointerUp,!0),this.updatePointerPosition(t);for(let c=this._pointerEventsPressed.length-1;c>=0;c--)if(this._pointerEventsPressed[c].pointerId===e){this._pointerEventsPressed.splice(c,1);break}if(!this._pointerPositionDown[e]){et&&me("Received pointer up event without matching down event for button: "+e),console.warn("Received pointer up event without matching down event for button: "+e);return}const n=this._pointerUpTime[e],s=this._pointerDownTime[e],a=this.context.time.realtimeSinceStartup,l=a-s;if(e>=this._pointerUpTime.length&&this._pointerUpTime.push(-99),this._pointerUpTime[e]=a,l<1){let c=t.clientX-this._pointerPositionDown[e].x,h=t.clientY-this._pointerPositionDown[e].y,u=0;if(t.isSpatial&&t.clientZ!=null&&(u=t.clientZ-this._pointerPositionDown[e].z,c*=200,h*=200,u*=200),Math.abs(c)<5&&Math.abs(h)<5&&Math.abs(u)<5){this.setPointerState(e,this._pointerClick,!0),t.isClick=!0;const f=a-n;et&&console.log("CLICK",e,c,h,u,f),f<this._doubleClickTimeThreshold&&f>0&&(this.setPointerState(e,this._pointerDoubleClick,!0),t.isDoubleClick=!0)}}this.onDispatchEvent(t)}updatePointerPosition(t){const e=t.pointerId;for(;e>=this._pointerPositions.length;)this._pointerPositions.push(new d.Vector2);for(;e>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new d.Vector2);for(;e>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new d.Vector2);const i=this._pointerPositionsLastFrame[e];i.copy(this._pointerPositions[e]);const n=this._pointerPositionsDelta[e];let s=t.clientX-i.x,a=t.clientY-i.y;if(t.source instanceof MouseEvent||t.source instanceof TouchEvent){const u=t.source;s===0&&u.movementX!==0&&(s=u.movementX||0),a===0&&u.movementY!==0&&(a=u.movementY||0)}n.x+=s,n.y+=a,this._pointerPositions[e].x=t.clientX,this._pointerPositions[e].y=t.clientY;const l=t.clientX,c=t.clientY;for(;e>=this._pointerPositionsRC.length;)this._pointerPositionsRC.push(new d.Vector2);const h=this._pointerPositionsRC[e];h.set(l,c),this.convertScreenspaceToRaycastSpace(h)}getPointerIndex(t){let e=-1;for(let i=0;i<this._pointerIds.length;i++){if(this._pointerIds[i]===t)return i;e===-1&&this._pointerIds[i]===-1&&(e=i)}return e!==-1?(this._pointerIds[e]=t,e):(et&&console.log("PUSH pointerId:",t),this._pointerIds.push(t),this._pointerIds.length-1)}setPointerState(t,e,i){e[t]=i}setPointerStateT(t,e,i){return e[t]=i,i}onDispatchEvent(t){const e=X.Current;try{X.Current=this.context,this.dispatchEvent(t)}finally{X.Current=e}}}const Ta=new d.Matrix4().makeRotationY(Math.PI),Ni=new d.Quaternion().setFromAxisAngle(new d.Vector3(0,1,0),Math.PI),gC=S("debugwebxr");class yC{constructor(){r(this,"priority",-1e5);r(this,"gameObject");if(this.gameObject=new d.Object3D,this.gameObject.name="Implicit XR Rig",gC){const t=hg(16733661);t.position.y+=.5,this.gameObject.add(t)}}isXRRig(){return!0}get isActive(){return this.gameObject.visible}}const hs=S("debugwebxr"),Zh=S("debugcustomgesture"),_C="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",bC="generic-trigger",vC=new d.Quaternion().setFromEuler(new d.Euler(d.MathUtils.degToRad(0),d.MathUtils.degToRad(-90),d.MathUtils.degToRad(-90))),wC=new d.Vector3(.04,-.04,0);class sg{constructor(t,e,i){r(this,"xr");r(this,"inputSource");r(this,"index",0);r(this,"emitEvents",!0);r(this,"_connected",!0);r(this,"_isTracking",!1);r(this,"__gamepad");r(this,"__hand");r(this,"__side");r(this,"_hitTestSource");r(this,"_hasSelectEvent",!1);r(this,"_isMxInk",!1);r(this,"_isMetaQuestTouchController",!1);r(this,"_handJointPoses",new Map);r(this,"_gripMatrix",new d.Matrix4);r(this,"_gripPosition",new d.Vector3);r(this,"_gripQuaternion",new d.Quaternion);r(this,"_linearVelocity",new d.Vector3);r(this,"_rayPositionRaw",new d.Vector3);r(this,"_rayRotationRaw",new d.Quaternion);r(this,"_rayMatrix",new d.Matrix4);r(this,"_rayPosition",new d.Vector3);r(this,"_rayQuaternion",new d.Quaternion);r(this,"_gripWorldPosition",new d.Vector3);r(this,"_gripWorldQuaternion",new d.Quaternion);r(this,"_rayWorldPosition",new d.Vector3);r(this,"_rayWorldQuaternion",new d.Quaternion);r(this,"_pinchPosition",new d.Vector3);r(this,"_ray");r(this,"_hand_wristDotUp");r(this,"_object");r(this,"_gripSpaceObject");r(this,"_raySpaceObject");r(this,"model",null);r(this,"_debugAxesHelper",new d.AxesHelper(.15));r(this,"_debugGripAxesHelper",new d.AxesHelper(.07));r(this,"_debugRayAxesHelper",new d.AxesHelper(.07));r(this,"_hitTestSourcePromise",null);r(this,"onPointerHits",t=>{});r(this,"_needleGamepadButtons",{});r(this,"_buttonMap",new Map);r(this,"_motioncontroller");r(this,"_layout");r(this,"getMotionController");r(this,"emitPointerDownEvent",!0);r(this,"emitPointerUpEvent",!0);r(this,"emitPointerMoveEvent",!0);r(this,"pointerMoveDistanceThreshold",.03);r(this,"pointerMoveAngleThreshold",.05);r(this,"_selectButtonIndex");r(this,"_squeezeButtonIndex");r(this,"onSelectStart",t=>{var n,s,a,l;if(!this.emitPointerDownEvent||this.inputSource!==t.inputSource)return;this.onUpdateFrame(t.frame),this._hasSelectEvent=!0;const e=(n=this._layout)==null?void 0:n.selectComponentId,i=(l=(a=(s=this._layout)==null?void 0:s.components[e])==null?void 0:a.gamepadIndices)==null?void 0:l.button;i!==void 0&&(this._selectButtonIndex=i),!Zh&&(hs&&V.DrawDirection(this.rayWorldPosition,$(0,.01,1).applyQuaternion(this.rayWorldQuaternion),16711680,10),this.emitPointerEvent(Re.PointerDown,this._selectButtonIndex||0,"xr-standard-trigger",!0,t))});r(this,"onSelectEnd",t=>{this.emitPointerUpEvent&&(Zh||this.inputSource===t.inputSource&&this.emitPointerEvent(Re.PointerUp,this._selectButtonIndex||0,"xr-standard-trigger",!0,t))});r(this,"onSequeezeStart",t=>{var e,i,n;this.emitPointerDownEvent&&this.inputSource===t.inputSource&&(this._squeezeButtonIndex=(n=(i=(e=this._layout)==null?void 0:e.components["xr-standard-squeeze"])==null?void 0:i.gamepadIndices)==null?void 0:n.button,this._squeezeButtonIndex!==void 0&&(hs&&V.DrawDirection(this.rayWorldPosition,$(0,.01,1).applyQuaternion(this.rayWorldQuaternion),255,10),this.emitPointerEvent(Re.PointerDown,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,t)))});r(this,"onSequeezeEnd",t=>{this.emitPointerUpEvent&&this.inputSource===t.inputSource&&this._squeezeButtonIndex!==void 0&&this.emitPointerEvent(Re.PointerUp,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,t)});r(this,"states",{});r(this,"_didMoveLastFrame",!1);r(this,"_lastPointerMovePosition",new d.Vector3);r(this,"_lastPointerMoveQuaternion",new d.Quaternion);r(this,"pointerInit");this.xr=t,this.inputSource=e,this.index=i,this._object=new d.Object3D,this._object.name=`NeedleXRController_${i}`,hs&&(this._object.add(this._debugAxesHelper),this._gripSpaceObject=new d.Object3D,this._raySpaceObject=new d.Object3D,this._gripSpaceObject.name=`NeedleXRController_${i}_gripSpace`,this._raySpaceObject.name=`NeedleXRController_${i}_raySpace`,this._gripSpaceObject.add(this._debugGripAxesHelper),this._raySpaceObject.add(this._debugRayAxesHelper),this.xr.context.scene.add(this._gripSpaceObject),this.xr.context.scene.add(this._raySpaceObject)),this.xr.context.scene.add(this._object),this._ray=new d.Ray,this.pointerInit={origin:this,pointerType:this.hand?"hand":"controller",deviceIndex:this.index,pointerId:-1,mode:this.inputSource.targetRayMode,ray:this._ray,device:this._object,buttonName:"none"},this.initialize(),this.subscribeEvents()}get context(){return this.xr.context}get connected(){return this._connected}get isTracking(){return this._isTracking}get gamepad(){return this.__gamepad??(this.__gamepad=this.inputSource.gamepad)}get isHand(){return this.hand!=null}get hand(){return this.__hand??(this.__hand=this.inputSource.hand)}get handObject(){return this.context.renderer.xr.getHand(this.index)}get profiles(){return this.inputSource.profiles}get layout(){return this._layout}get targetRayMode(){return this.inputSource.targetRayMode}get targetRaySpace(){return this.inputSource.targetRaySpace}get gripSpace(){return this.inputSource.gripSpace}get side(){return this.__side??(this.__side=this.inputSource.handedness)}get isRight(){return this.side==="right"}get isLeft(){return this.side==="left"}get isStylus(){return this._isMxInk}getHitTestSource(){return this._hitTestSource||this._requestHitTestSource(),this._hitTestSource}get hasHitTestSource(){return this._hitTestSource}cancelHitTestSource(){this._hitTestSource&&(this._hitTestSource.cancel(),this._hitTestSource=void 0)}get hasSelectEvent(){return this._hasSelectEvent}getHitTest(){return this.xr.getHitTest(this)}getHandJointPose(t,e){var n;if(e=e||this.xr.frame,!this.hand||!(e!=null&&e.getJointPose)||!this.xr.referenceSpace)return null;let i=(n=this._handJointPoses)==null?void 0:n.get(t);return i||(i=e.getJointPose(t,this.xr.referenceSpace),i&&this._handJointPoses.set(t,i),i)}get gripPosition(){return $(this._gripPosition)}get gripQuaternion(){return un(this._gripQuaternion)}get gripMatrix(){return this._gripMatrix}get gripLinearVelocity(){return $(this._linearVelocity).applyQuaternion(Ni)}get rayPosition(){return $(this._rayPosition)}get rayQuaternion(){return un(this._rayQuaternion)}get gripWorldPosition(){return $(this._gripWorldPosition)}get gripWorldQuaternion(){return un(this._gripWorldQuaternion)}get rayWorldPosition(){return $(this._rayWorldPosition)}updateRayWorldPosition(){var e;const t=(e=this.xr.context.mainCamera)==null?void 0:e.parent;this._rayWorldPosition.copy(this._rayPositionRaw),t&&this._rayWorldPosition.applyMatrix4(t.matrixWorld)}get rayWorldQuaternion(){return un(this._rayWorldQuaternion)}get pinchPosition(){return $(this._pinchPosition)}updateRayWorldQuaternion(){var i;const t=(i=this.xr.context.mainCamera)==null?void 0:i.parent,e=t?_e(t):void 0;this._rayWorldQuaternion.copy(this._rayRotationRaw).multiply(Ni),e&&this._rayWorldQuaternion.premultiply(e)}get ray(){return this._ray.origin.copy(this.rayWorldPosition),this._ray.direction.copy($(0,0,1).applyQuaternion(this.rayWorldQuaternion)),this._ray}get handWristDotUp(){var e;if(this._hand_wristDotUp!==void 0)return this._hand_wristDotUp;const t=(e=this.handObject)==null?void 0:e.joints.wrist;if(t){const i=$(0,1,0).applyQuaternion(t.quaternion),n=$(0,1,0).dot(i);return this._hand_wristDotUp=n}}get isHandUpsideDown(){return this.handWristDotUp!==void 0?this.handWristDotUp<-.7:!1}get isTeleportGesture(){var t;return this.isHandUpsideDown&&((t=this.getGesture("pinch"))==null?void 0:t.isDown)}get object(){return this._object}async getModelUrl(){var t;return(t=this.getMotionController)==null?void 0:t.then(e=>(e==null?void 0:e.assetUrl)||null)}_requestHitTestSource(){var t;return this._hitTestSourcePromise?this._hitTestSourcePromise:this.xr.mode==="immersive-ar"&&this.inputSource.targetRayMode==="tracked-pointer"&&this.xr.session.requestHitTestSourceForTransientInput?this._hitTestSourcePromise=((t=this.xr.session.requestHitTestSourceForTransientInput({profile:this.inputSource.profiles[0],offsetRay:new XRRay}))==null?void 0:t.then(e=>(this._hitTestSourcePromise=null,this.connected?this._hitTestSource=e:(e.cancel(),null))))??null:null}onUpdate(t){this.onUpdateFrame(t),this.updateInputEvents(),this.onUpdateMove()}onRenderDebug(){var s;V.DrawSphere(this.rayWorldPosition,.003),V.DrawDirection(this.rayWorldPosition,$(0,0,10).applyQuaternion(this.rayWorldQuaternion));const e=(this.inputSource.gripSpace?this.gripWorldPosition:this.object.worldPosition).sub(this.object.worldForward.multiplyScalar(.1)),i=this.inputSource.profiles.join(`
147
147
  `);let n=`Controller[${this.index}] (${this.inputSource.targetRayMode}, ${this.side})
148
148
  C:${this.connected?"x":"-"} T:${this.isTracking?"x":"-"} Hand:${this.inputSource.hand?"x":"-"} Pen: ${this._isMxInk?"x":"-"}`;if(this.inputSource.hand&&(n+=`
@@ -936,7 +936,7 @@ ${e.path}! : AssetReference;
936
936
  Could not find method ${h.method} on object ${f.name}. Please rename ${h.method} to ${b}?
937
937
  `,f[b],`
938
938
  in script: `,f),me("EventList methods must start with lowercase letter, see console for details");return}else console.warn(`EventList method:
939
- Could not find method ${h.method} on object ${f.name}`,f,typeof f[h.method])};if(typeof f[h.method]!="function"){let b=!1,_=f;for(;_;){const v=Object.getOwnPropertyDescriptor(_,h.method);if(v&&(v.writable===!0||v.set)){b=!0;break}_=Object.getPrototypeOf(_)}!b&&(j()||dt)&&g()}}if(f){let g=h.argument;if(g!==void 0?g=u(g):h.arguments!==void 0&&(g=h.arguments.map(u)),!f[h.method])console.warn(`EventList method not found: "${h.method}" on ${f==null?void 0:f.name}`);else{g!==void 0&&!Array.isArray(g)&&(g=[g]);const b=new Cs(f,h.method,g,h.enabled);a.push(b)}}else j()&&console.warn("[Debug] EventList: Could not find event listener in scene",h,e.object,t)}const l=new ye(a);dt&&console.log(l);const c=e.target;return c!==void 0&&e.path!==void 0&&l.setEventTarget(e.path,c),l}}}const NP=new zP,cu=new WeakMap,VP=d.Texture.prototype.clone;d.Texture.prototype.clone=function(){const o=VP.call(this);return cu.has(o)||cu.set(o,this),o};class hw extends Ki{constructor(){super([Sr,d.WebGLRenderTarget])}onSerialize(t,e){}onDeserialize(t,e){if(t instanceof d.Texture&&e.type===Sr){let i=t;cu.has(i)&&(i=cu.get(i)),i.isRenderTargetTexture=!0,i.flipY=!0,i.offset.y=1,i.repeat.y=-1,i.needsUpdate=!0,i.mipmaps=[],i instanceof d.CompressedTexture&&(i.isCompressedTexture=!1,i.format=d.RGBAFormat);const n=new Sr(i.image.width,i.image.height,{colorSpace:d.LinearSRGBColorSpace});return n.texture=i,n}}}new hw;class dw extends Ki{constructor(){super([URL])}onSerialize(t,e){return null}onDeserialize(t,e){if(typeof t=="string"&&t.length>0)return To(e.gltfId,t)}}new dw;var $P=Object.defineProperty,WP=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&$P(t,e,n),n};class Ga extends D{awake(){Qt.createIfNoneExists(this.context)}onEnable(){var t;(t=Qt.get(this.context))==null||t.register(this)}onDisable(){var t;(t=Qt.get(this.context))==null||t.unregister(this)}}class Ei extends Ga{constructor(){super(...arguments);r(this,"targets",null);r(this,"raycastHits",[]);r(this,"ignoreSkinnedMeshes",!1)}start(){this.targets=[this.gameObject]}performRaycast(e=null){if(!this.targets)return null;e??(e=new Jn),e.targets=this.targets,e.results=this.raycastHits,e.useAcceleratedRaycast=!0;const i=e.testObject;this.ignoreSkinnedMeshes&&(e.testObject=s=>s instanceof d.SkinnedMesh?"continue in children":i?i(s):!0);const n=this.context.physics.raycast(e);return e.testObject=i,n}}WP([m()],Ei.prototype,"ignoreSkinnedMeshes");class Yu extends Ei{constructor(){super(),this.ignoreSkinnedMeshes=!0}}const Ru=class Ru extends Ga{performRaycast(t){if(!J.active||!Ru.allow||!(t!=null&&t.ray))return null;const e=t.ray.origin;return this.context.physics.sphereOverlap(e,.015,!1,!0)}};r(Ru,"allow",!0);let Tr=Ru;class kg{static getObject(t){const e=t[Si];return e&&(e.isComponent===!0?t=e.gameObject:t=e),t}static isInteractable(t,e){if(e&&(e.canvasGroup=void 0,e.graphic=void 0),t==null||!t.visible||(t=this.getObject(t),!t.visible))return!1;const i=this.tryFindCanvasGroup(t);if((i==null?void 0:i.isCanvasGroup)===!0&&(e&&(e.canvasGroup=i),i.blocksRaycasts===!1||i.interactable===!1))return!1;const n=Rr(t,s=>{if(s.isGraphic===!0)return s},!1);return e&&(n==null?void 0:n.isGraphic)===!0&&(e.graphic=n),!((n==null?void 0:n.raycastTarget)===!1||(n==null?void 0:n.layer)===2)}static tryFindCanvasGroup(t){if(!t)return null;const e=Rr(t,i=>{const n=i;if(n.blocksRaycasts!==void 0&&n.interactable!==void 0)return n},!1);return e!==void 0?e:this.tryFindCanvasGroup(t.parent)}}function Rg(o){const t=o[Si];return t||(o.parent?Rg(o.parent):null)}function HP(o){return o.isUI===!0||typeof o[Si]=="object"}function hu(o,t){if(!o)return;const e=o.material;if((e==null?void 0:e.isMaterial)===!0){const i=o.parent;i&&i.isText,e.side=t.doubleSided??!0?d.DoubleSide:d.FrontSide,e.shadowSide=t.doubleSided?d.DoubleSide:d.FrontSide,o.castShadow=t.castShadows?t.castShadows:!1,o.receiveShadow=t.receiveShadows?t.receiveShadows:!1}for(const i of o.children)hu(i,t)}function pa(o,t,e){o[t]===void 0&&console.warn("Field",t,"is undefined on",o);const i=Proxy.revocable(o[t],{set(a,l,c,h){const u=a[l],f=Reflect.set(a,l,c,h);return e(c,u),f}}),n=i.revoke,s=o[t];return i.revoke=()=>{o[t]=s,n()},o[t]=i.proxy,i}const rb=Symbol("Scheduled action");function GP(o,t,e=we.OnBeforeRender){let i=o[rb];i||(i=o[rb]={});const n=t.name;i[e]||(i[e]={});const s=i[e];if(s[n])return;function*l(){t==null||t.call(o),s[n]=null}const c=o.startCoroutine(l(),e);s[n]=c}const to=S("debugeventsystem");var Sm=(o=>(o.BeforeHandleInput="BeforeHandleInput",o.AfterHandleInput="AfterHandleInput",o))(Sm||{});sw(o=>{Qt.createIfNoneExists(o)});class Qt extends D{constructor(){super(...arguments);r(this,"raycaster",[]);r(this,"pressedByID",new Map);r(this,"hoveredByID",new Map);r(this,"onPointerEvent",e=>{if(e===void 0||e.propagationStopped||e.defaultPrevented||e.used)return;const i=new ph(this.context.input,e);this._currentPointerEventName=e.type,i.inputSource=this.context.input,i.isClick=e.isClick,i.isDoubleClick=e.isDoubleClick,i.isDown=e.type==Re.PointerDown,i.isUp=e.type==Re.PointerUp,i.isPressed=this.context.input.getPointerPressed(e.pointerId),to&&(i.isDown?console.log("DOWN",i.pointerId):i.isUp&&console.log("UP",i.pointerId),i.isClick&&console.log("CLICK",i.pointerId));const n=new Jn;e.hasRay?n.ray=e.ray:n.screenPoint=this.context.input.getPointerPositionRC(e.pointerId);const s=this.performRaycast(n);if(s){for(const l of s)l.event=e,e.intersections.push(l);e.origin.onPointerHits&&e.origin.onPointerHits({sender:this,event:e,hits:s})}to&&i.isClick&&Ee("EventSystem: "+i.pointerId+" - "+this.context.time.frame+" - Up:"+i.isUp+", Down:"+i.isDown);const a={sender:this,args:i,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:a})),this.handleIntersections(s,i),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:a}))});r(this,"_sortedHits",[]);r(this,"_testObjectsCache",new Map);r(this,"_currentlyActiveRaycaster",null);r(this,"_currentPointerEventName",null);r(this,"shouldRaycastObject",e=>{var a;const i=e&&"getComponent"in e?e.getComponent(Ga):null;if(i&&i!=this._currentlyActiveRaycaster)return!1;let n=null;if(HP(e)&&(n=(a=e[Si])==null?void 0:a.gameObject),this._testObjectsCache.has(e)||n&&this._testObjectsCache.has(n))return this._testObjectsCache.get(e)===!1?"continue in children":!0;{let l=lu(e,this._currentPointerEventName);if(!l&&n&&(l=lu(n,this._currentPointerEventName)),l){this._testObjectsCache.set(e,!0);for(const c of e.children)this.shouldRaycastObject_AddToYesCache(c);return!0}return this._testObjectsCache.set(e,!1),"continue in children"}});r(this,"_sortingBuffer",[]);r(this,"_noDepthTestingResults",[]);r(this,"out",{});r(this,"_capturedPointer",{});r(this,"pointerEnterSymbol",Symbol("pointerEnter"));r(this,"pointerExitSymbol",Symbol("pointerExit"));r(this,"currentActiveMeshUIComponents",[])}static ensureUpdateMeshUI(e,i,n=!1){fo.update(e,i,n)}static markUIDirty(e){fo.markDirty()}static createIfNoneExists(e){e.scene.getComponent(Qt)||e.scene.addComponent(Qt)}static get(e){return this.createIfNoneExists(e),e.scene.getComponent(Qt)}static get instance(){return this.get(X.Current)}register(e){var i;e&&this.raycaster&&!this.raycaster.includes(e)&&((i=this.raycaster)==null||i.push(e))}unregister(e){var n,s;const i=(n=this.raycaster)==null?void 0:n.indexOf(e);i!==void 0&&i!==-1&&((s=this.raycaster)==null||s.splice(i,1))}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.hoveredByID.size>0}awake(){this.gameObject!==this.context.scene&&(console.debug(`[Needle Engine] EventSystem is only allowed on the scene root. Disabling EventSystem on '${this.gameObject.name}'`),this.enabled=!1)}start(){this.context.scene.getComponent(Ga)||this.context.scene.addComponent(Ei)}onEnable(){this.context.input.addEventListener(Re.PointerDown,this.onPointerEvent),this.context.input.addEventListener(Re.PointerUp,this.onPointerEvent),this.context.input.addEventListener(Re.PointerMove,this.onPointerEvent)}onDisable(){this.context.input.removeEventListener(Re.PointerDown,this.onPointerEvent),this.context.input.removeEventListener(Re.PointerUp,this.onPointerEvent),this.context.input.removeEventListener(Re.PointerMove,this.onPointerEvent)}onBeforeRender(){this.resetMeshUIStates()}shouldRaycastObject_AddToYesCache(e){this._testObjectsCache.set(e,!0);for(const i of e.children)this.shouldRaycastObject_AddToYesCache(i)}performRaycast(e){if(!this.raycaster)return null;this._testObjectsCache.clear(),this._sortedHits.length=0,e||(e=new Jn),e.testObject=this.shouldRaycastObject;for(const i of this.raycaster){if(!i.activeAndEnabled)continue;this._currentlyActiveRaycaster=i;const n=i.performRaycast(e);this._currentlyActiveRaycaster=null,n&&n.length>0&&this._sortedHits.push(...n)}return this._sortedHits.sort((i,n)=>i.distance-n.distance),this._sortedHits}assignHitInformation(e,i){i?(e.intersection=i,e.point=i.point,e.normal=i.normal,e.face=i.face,e.distance=i.distance,e.instanceId=i.instanceId):(e.intersection=void 0,e.point=void 0,e.normal=void 0,e.face=void 0,e.distance=void 0,e.instanceId=void 0)}handleIntersections(e,i){var s;if(e!=null&&e.length){e=this.sortCandidates(e);for(const a of e){if(i.event.immediatePropagationStopped)return!1;if(this.assignHitInformation(i,a),this.handleEventOnObject(a.object,i))return!0}}this.assignHitInformation(i,e==null?void 0:e[0]),this.invokePointerCapture(i);const n=this.hoveredByID.get(i.pointerId);return n&&this.propagatePointerExit(n.obj,n.data,null),this.hoveredByID.delete(i.pointerId),i.isUp&&((s=this.pressedByID.get(i.pointerId))==null||s.handlers.forEach(a=>this.invokeOnPointerUp(i,a)),this.pressedByID.delete(i.pointerId)),!1}sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let i=0;i<e.length;i++){const n=e[i],s=n.object;if(s.material&&s.material.depthTest===!1){this._noDepthTestingResults.push(n);continue}this._sortingBuffer.push(n)}for(const i of this._sortingBuffer)this._noDepthTestingResults.push(i);return this._noDepthTestingResults}handleEventOnObject(e,i){if(!this.testIsVisible(e))return i.isClick&&to&&console.log("not allowed",e),!1;if(i.pointerId===void 0)return to&&console.error("Event without pointer can't be handled",i),!1;i.object=e;const n=e.parent,s=i.isClick??!1;let a=null;if(n&&n.isUI){const f=(i.isPressed||i.isClick)??!1;if(n[Si]){const p=n[Si].gameObject;if(p){if(!kg.isInteractable(p,this.out))return!1;a=this.out.canvasGroup??null,this.handleMeshUIIntersection(e,f),e=p}}}s&&to&&console.log(this.context.time.frame,e);const l=this.hoveredByID.get(i.pointerId),c=l==null?void 0:l.obj;c!==e&&c&&this.propagatePointerExit(c,l.data,e);const u=this.hoveredByID.get(i.pointerId);if(u?(u.obj=e,u.data=i):this.hoveredByID.set(i.pointerId,{obj:e,data:i}),i.isDown){const f=this.pressedByID.get(i.pointerId);f?(f.obj=e,f.data=i):this.pressedByID.set(i.pointerId,{obj:e,data:i,handlers:new Set})}return(a===null||a.interactable)&&this.handleMainInteraction(e,i,c??null),!0}propagate(e,i){for(;e;)C.foreachComponent(e,n=>{i(n)},!1),e=e.parent}handleMainInteraction(e,i,n){const s=this.pressedByID.get(i.pointerId),a=n!==e;let l=!0;switch(i.event.pointerType){case"mouse":case"touch":const c=this.context.input.getPointerPositionLastFrame(i.pointerId),h=this.context.input.getPointerPosition(i.pointerId);l=c&&!z.approximately(c,h);break}this.propagate(e,c=>{var u;const h=c;h.interactable!==!1&&(!h.activeAndEnabled||!h.enabled||(h.onPointerEnter&&a&&this.handlePointerEnter(h,i),i.isDown&&h.onPointerDown&&(h.onPointerDown(i),s==null||s.handlers.add(h),this.handlePointerCapture(i,h)),h.onPointerMove&&(l&&h.onPointerMove(i),this.handlePointerCapture(i,h)),i.isUp&&(h.onPointerUp&&(this.invokeOnPointerUp(i,h),s==null||s.handlers.delete(h)),h.onPointerExit&&((u=i.event)==null?void 0:u.pointerType)===zu.Touch&&(this.handlePointerExit(h,i),this.hoveredByID.delete(i.pointerId))),i.isClick&&h.onPointerClick&&h.onPointerClick(i)))}),i.isUp&&(s==null||s.handlers.forEach(c=>{this.invokeOnPointerUp(i,c)}),this.pressedByID.delete(i.pointerId))}propagatePointerExit(e,i,n){this.propagate(e,s=>{if(!s.gameObject||s.destroyed)return;const a=s;if(a.onPointerExit||a.onPointerEnter){if(n&&this.isChild(n,s.gameObject))return;this.handlePointerExit(a,i)}})}invokeOnPointerUp(e,i){var n;(n=i.onPointerUp)==null||n.call(i,e),this.releasePointerCapture(e,i)}handlePointerEnter(e,i){e.onPointerEnter&&this.updatePointerState(e,i.pointerId,this.pointerEnterSymbol,!0)&&e.onPointerEnter(i),this.updatePointerState(e,i.pointerId,this.pointerExitSymbol,!1)}handlePointerExit(e,i){e.onPointerExit&&this.updatePointerState(e,i.pointerId,this.pointerExitSymbol,!0)&&e.onPointerExit(i),this.updatePointerState(e,i.pointerId,this.pointerEnterSymbol,!1)}updatePointerState(e,i,n,s){let a=e[n];if(s)return a&&a.includes(i)?!1:(a=a||[],a.push(i),e[n]=a,!0);{if(!a||!a.includes(i))return!1;const l=a.indexOf(i);return l!==-1&&a.splice(l,1),!0}}handlePointerCapture(e,i){if(e.z__pointer_ctured){e.z__pointer_ctured=!1;const n=e.pointerId;if(i.onPointerMove){const s=this._capturedPointer[n]||[];s.push(i),this._capturedPointer[n]=s}else j()&&!i.z__warned_no_pointermove&&(i.z__warned_no_pointermove=!0,console.warn("PointerCapture was requested but the component doesn't implement onPointerMove. It will not receive any pointer events"))}else e.z__pointer_cture_rleased&&(e.z__pointer_cture_rleased=!1,this.releasePointerCapture(e,i))}releasePointerCapture(e,i){const n=e.pointerId;if(this._capturedPointer[n]){const s=this._capturedPointer[n].indexOf(i);s!==-1&&(this._capturedPointer[n].splice(s,1),to&&console.log("released pointer capture",n,i,this._capturedPointer))}}invokePointerCapture(e){var i;if(e.event.type===Re.PointerMove){const n=e.pointerId,s=this._capturedPointer[n];if(s){to&&console.log("Captured",n,s);for(let a=0;a<s.length;a++){const l=s[a];if(l.destroyed){s.splice(a,1),a--;continue}(i=l.onPointerMove)==null||i.call(l,e)}}}}isChild(e,i){return!e||!i?!1:e===i?!0:e.parent?this.isChild(e.parent,i):!1}handleMeshUiObjectWithoutShadowDom(e,i){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,i)}handleMeshUIIntersection(e,i){const n=fo.updateState(e,i);return n&&this.currentActiveMeshUIComponents.push(n),n!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&fo.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){const i=this.currentActiveMeshUIComponents[e];fo.resetState(i)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?C.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}}class fo{static markDirty(){this.needsUpdate=!0}static update(t,e,i=!1){if(i){t.update();return}const n=e.time.frameCount;for(const s of this.lastUpdateFrame)if(s.context===e){if(n===s.frame)return;s.frame=n;let a=this.needsUpdate||n<1;s.nextUpdate<=n&&(a=!0),a&&(to&&console.log("Update threemeshui"),this.needsUpdate=!1,s.nextUpdate=n+60,t.update());return}this.lastUpdateFrame=[{context:e,frame:n,nextUpdate:n+60}],t.update(),this.needsUpdate=!1}static updateState(t,e){let i=null;if(t&&(i=this.findBlockOrTextInParent(t),i&&i!==this.lastSelected)){if(i.interactable===!1)return null;this.needsUpdate=!0}return i}static resetLastSelected(){const t=this.lastSelected;t&&(this.lastSelected=null,this.resetState(t))}static resetState(t){t&&(this.needsUpdate=!0)}static findBlockOrTextInParent(t){return t?t.isBlock||t.isText?t:this.findBlockOrTextInParent(t.parent):null}}r(fo,"lastSelected",null),r(fo,"lastUpdateFrame",[]),r(fo,"needsUpdate",!1);var qP=Object.defineProperty,Te=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&qP(t,e,n),n};const Ui=S("debugorbit"),lp=S("freecam"),El=S("debugcamerafit"),cd=S("smoothcam"),XP={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let cp;class Bc extends CustomEvent{constructor(t,e){super("target-reached",{detail:{controls:t,type:e}})}}class ge extends D{constructor(){super(...arguments);r(this,"autoTarget",!0);r(this,"autoFit",!1);r(this,"enableRotate",!0);r(this,"autoRotate",!1);r(this,"autoRotateSpeed",1);r(this,"minAzimuthAngle",1/0);r(this,"maxAzimuthAngle",1/0);r(this,"minPolarAngle",0);r(this,"maxPolarAngle",Math.PI);r(this,"enableKeys",!1);r(this,"enableDamping",!0);r(this,"dampingFactor",.1);r(this,"enableZoom",!0);r(this,"minZoom",0);r(this,"maxZoom",1/0);r(this,"zoomSpeed",1);r(this,"zoomToCursor",!1);r(this,"enablePan",!0);r(this,"lookAtConstraint",null);r(this,"lookAtConstraint01",1);r(this,"allowInterrupt",!0);r(this,"middleClickToFocus",!0);r(this,"doubleClickToFocus",!0);r(this,"clickBackgroundToFitScene",2);r(this,"debugLog",!1);r(this,"targetLerpDuration",1);r(this,"_controls",null);r(this,"_cameraObject",null);r(this,"_lookTargetLerpActive",!1);r(this,"_lookTargetStartPosition",new d.Vector3);r(this,"_lookTargetEndPosition",new d.Vector3);r(this,"_lookTargetLerp01",0);r(this,"_lookTargetLerpDuration",0);r(this,"_cameraLerpActive",!1);r(this,"_cameraStartPosition",new d.Vector3);r(this,"_cameraEndPosition",new d.Vector3);r(this,"_cameraLerp01",0);r(this,"_cameraLerpDuration",0);r(this,"_fovLerpActive",!1);r(this,"_fovLerpStartValue",0);r(this,"_fovLerpEndValue",0);r(this,"_fovLerp01",0);r(this,"_fovLerpDuration",0);r(this,"_inputs",0);r(this,"_enableTime",0);r(this,"_startedListeningToKeyEvents",!1);r(this,"_eventSystem");r(this,"_afterHandleInputFn");r(this,"_camera",null);r(this,"_syncedTransform");r(this,"_didSetTarget",0);r(this,"targetElement",null);r(this,"_activePointerEvents");r(this,"_lastTimeClickOnBackground",-1);r(this,"_clickOnBackgroundCount",0);r(this,"_onPointerDown",e=>{this._activePointerEvents.push(e)});r(this,"_onPointerDownLate",e=>{e.used&&this._controls&&(this._controls.enabled=!1)});r(this,"_onPointerUp",e=>{for(let i=this._activePointerEvents.length-1;i>=0;i--){const n=this._activePointerEvents[i];if(n.pointerId===e.pointerId&&n.button===e.button){this._activePointerEvents.splice(i,1);break}}if(this.clickBackgroundToFitScene>0&&e.isClick&&e.button===0){if(e.hasRay||e.intersections.push(...this.context.physics.raycast()),e.intersections.length<=0){const i=this.context.time.time-this._lastTimeClickOnBackground;this._lastTimeClickOnBackground=this.context.time.time,this.clickBackgroundToFitScene<=1||i<this.clickBackgroundToFitScene*.15?(this._clickOnBackgroundCount+=1,this._clickOnBackgroundCount>=this.clickBackgroundToFitScene-1&&this.fitCamera(this.context.scene.children,{immediate:!1})):this._clickOnBackgroundCount=0}Ui&&console.log(this.clickBackgroundToFitScene,e.intersections.length,this._clickOnBackgroundCount)}});r(this,"_onPointerUpLate",e=>{this.doubleClickToFocus&&e.isDoubleClick&&!e.used&&this.setTargetFromRaycast()});r(this,"_orbitStartAngle",0);r(this,"onControlsChangeStarted",()=>{this._controls&&(this._orbitStartAngle=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle()),this._syncedTransform&&this._syncedTransform.requestOwnership()});r(this,"onControlsChangeEnded",()=>{if(this._controls&&this.autoTarget){const i=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle()-this._orbitStartAngle;Math.abs(i)<.01?(Ui&&console.debug("OrbitControls: No movement detected, updating target now"),this.updateTargetNow()):Ui&&console.debug("OrbitControls: Movement detected",i)}});r(this,"_shouldDisable",!1);r(this,"__onPreRender",()=>{const e=this.context.pre_render_callbacks.indexOf(this.__onPreRender);e>=0&&this.context.pre_render_callbacks.splice(e,1),this.autoFit&&(this.autoFit=!1,this.fitCamera({centerCamera:"y",immediate:!0,objects:this.scene.children}))});r(this,"_haveAttachedKeyboardEvents",!1)}get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){var i;(i=this.controls)==null||i.addEventListener("start",e)}get targetLerpSpeed(){return 5}set targetLerpSpeed(e){this.targetLerpDuration=1/e}awake(){Ui&&console.debug("OrbitControls",this),this._didSetTarget=0,this._startedListeningToKeyEvents=!1}start(){this._eventSystem=Qt.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(Sm.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){var e,i;(e=this._controls)==null||e.dispose(),(i=this._eventSystem)==null||i.removeEventListener(Sm.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._didSetTarget=0,this._enableTime=this.context.time.time;const e=C.getComponent(this.gameObject,ri);this._camera=e;let i=e==null?void 0:e.threeCamera;if(!i&&this.gameObject instanceof d.PerspectiveCamera&&(i=this.gameObject),i&&Kp(i,this,!0),!this._controls&&i instanceof d.Object3D){this._cameraObject=i;const n=this.targetElement??this.context.renderer.domElement,s=i==null?void 0:i.quaternion.clone();this._controls=new G.OrbitControls(i,n),i==null||i.quaternion.copy(s),cp===void 0&&(cp={...this._controls.keys});const a=Q(i),l=this.gameObject.worldForward,h=a.clone().sub(l.multiplyScalar(2.5));this._controls.target.copy(h)}if(this._controls)if(lp&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,exports.DeviceUtilities.isMobileDevice()&&(this.doubleClickToFocus=!0)),this._controls.addEventListener("start",this.onControlsChangeStarted),this._controls.addEventListener("end",this.onControlsChangeEnded),!this._startedListeningToKeyEvents&&this.enableKeys)this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(this.context.domElement);else try{this._controls.stopListenToKeyEvents()}catch{}this._syncedTransform=C.getComponent(this.gameObject,es)??void 0,this.context.pre_render_callbacks.push(this.__onPreRender),this._activePointerEvents=[],this.context.input.addEventListener("pointerdown",this._onPointerDown,{queue:oi.Early}),this.context.input.addEventListener("pointerdown",this._onPointerDownLate,{queue:oi.Late}),this.context.input.addEventListener("pointerup",this._onPointerUp,{queue:oi.Early}),this.context.input.addEventListener("pointerup",this._onPointerUpLate,{queue:oi.Late})}onDisable(){var e;if((e=this._camera)!=null&&e.threeCamera&&Kp(this._camera.threeCamera,this,!1),this._controls){this._controls.enabled=!1,this._controls.autoRotate=!1,this._controls.removeEventListener("start",this.onControlsChangeStarted),this._controls.removeEventListener("end",this.onControlsChangeEnded);try{this._controls.stopListenToKeyEvents()}catch{}this._startedListeningToKeyEvents=!1}this._activePointerEvents.length=0,this.context.input.removeEventListener("pointerdown",this._onPointerDown),this.context.input.removeEventListener("pointerdown",this._onPointerDownLate),this.context.input.removeEventListener("pointerup",this._onPointerUp),this.context.input.removeEventListener("pointerup",this._onPointerUpLate)}updateTargetNow(){var s,a,l;const e=new d.Ray((s=this._cameraObject)==null?void 0:s.worldPosition,(a=this._cameraObject)==null?void 0:a.worldForward.multiplyScalar(-1)),i=this.context.physics.raycastFromRay(e),n=i.length>0?i[0]:void 0;n&&n.distance>this.minZoom&&n.distance<this.maxZoom&&(Ui&&V.DrawWireSphere(n.point,.1,16711680,2),(l=this._controls)==null||l.target.copy(i[0].point))}afterHandleInput(e){e.detail.args.pointerId===0&&(e.detail.args.isDown?this._controls&&this._eventSystem&&(this._shouldDisable=this._eventSystem.hasActiveUI):(!e.detail.args.isPressed||e.detail.args.isUp)&&(this._shouldDisable=!1))}onBeforeRender(){var i,n,s,a;if(!this._controls)return;if(this._cameraObject!==this.context.mainCamera){this._controls.enabled=!1;return}if(this._controls.enabled=!0,(this.context.input.getPointerDown(1)||this.context.input.getPointerDown(2)||this.context.input.mouseWheelChanged||this.context.input.getPointerPressed(0)&&((i=this.context.input.getPointerPositionDelta(0))!=null&&i.length()))&&(this._inputs+=1),this._inputs>0&&this.allowInterrupt&&(this.enableRotate&&(this.autoRotate=!1),this._cameraLerpActive=!1,this._lookTargetLerpActive=!1),this._inputs=0,this.autoTarget&&this._didSetTarget++===0){const l=C.getComponent(this.gameObject,ri);if(l&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log("NO TARGET");const c=Q(l.threeCamera),h=Math.max(.01,c.length()),u=new d.Vector3(0,0,-h).applyMatrix4(l.threeCamera.matrixWorld);Ui&&V.DrawLine(c,u,5592575,10),this.setLookTargetPosition(u,!0)}if(!this.setLookTargetFromConstraint()){const c=new Jn;c.screenPoint=new d.Vector2(0,0),c.lineThreshold=.1;const h=this.context.physics.raycast(c);h.length>0&&this.setLookTargetPosition(h[0].point,!0),El&&console.log("OrbitControls hits",...h)}}if(this.middleClickToFocus&&this.context.input.getPointerClicked(1)&&this.setTargetFromRaycast(),this._lookTargetLerpActive||this._cameraLerpActive||this._fovLerpActive){if(this._cameraLerpActive&&this._cameraObject)if(this._cameraLerp01+=this.context.time.deltaTime/this._cameraLerpDuration,this._cameraLerp01>=1)this._cameraObject.position.copy(this._cameraEndPosition),this._cameraLerpActive=!1,this.dispatchEvent(new Bc(this,"camera"));else{const l=z.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,l)}if(this._lookTargetLerpActive)if(this._lookTargetLerp01+=this.context.time.deltaTime/this._lookTargetLerpDuration,this._lookTargetLerp01>=1)this._controls.target.copy(this._lookTargetEndPosition),this._lookTargetLerpActive=!1,this.dispatchEvent(new Bc(this,"lookat"));else{const l=z.easeInOutCubic(this._lookTargetLerp01);this._controls.target.lerpVectors(this._lookTargetStartPosition,this._lookTargetEndPosition,l)}if(this._fovLerpActive&&this._cameraObject){const l=this._cameraObject;if(this._fovLerp01+=this.context.time.deltaTime/this._fovLerpDuration,this._fovLerp01>=1)l.fov=this._fovLerpEndValue,this._fovLerpActive=!1;else{const c=z.easeInOutCubic(this._fovLerp01);l.fov=z.lerp(this._fovLerpStartValue,this._fovLerpEndValue,c)}l.updateProjectionMatrix()}}if(this._controls){if(this.debugLog&&(this._controls.domElement=this.context.renderer.domElement),this._controls.enabled=!this._shouldDisable&&this._camera===this.context.mainCameraComponent&&!this.context.isInXR&&!this._activePointerEvents.some(l=>l.used),this._controls.keys=this.enableKeys?cp:XP,this._controls.autoRotate=this.autoRotate,this._controls.autoRotateSpeed=this.autoRotateSpeed,this._controls.enableZoom=this.enableZoom,this._controls.zoomSpeed=this.zoomSpeed,this._controls.zoomToCursor=this.zoomToCursor,this._controls.enableDamping=this.enableDamping,this._controls.dampingFactor=this.dampingFactor,this._controls.enablePan=this.enablePan,this._controls.enableRotate=this.enableRotate,this._controls.minAzimuthAngle=this.minAzimuthAngle,this._controls.maxAzimuthAngle=this.maxAzimuthAngle,this._controls.minPolarAngle=this.minPolarAngle,this._controls.maxPolarAngle=this.maxPolarAngle,lp||(((s=(n=this._camera)==null?void 0:n.threeCamera)==null?void 0:s.type)==="PerspectiveCamera"?(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom,this._controls.minZoom=0,this._controls.maxZoom=1/0):(this._controls.minDistance=0,this._controls.maxDistance=1/0,this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom)),typeof cd=="number"||cd===!0){this._controls.enableDamping=!0;const l=typeof cd=="number"?cd:.99;this._controls.dampingFactor=Math.max(.001,1-Math.min(1,l))}this.allowInterrupt||(this._lookTargetLerpActive&&(this._controls.enablePan=!1),this._cameraLerpActive&&(this._controls.enableRotate=!1,this._controls.autoRotate=!1),(this._lookTargetLerpActive||this._cameraLerpActive)&&(this._controls.enableZoom=!1)),this.context.isInXR||(!lp&&((a=this.lookAtConstraint)!=null&&a.locked)&&this.setLookTargetFromConstraint(0,this.lookAtConstraint01),this._controls.update(this.context.time.deltaTime),Ui&&V.DrawWireSphere(this._controls.target,.1,65280))}}setCameraAndLookTarget(e,i=!1){if(!e)return(j()||Ui)&&console.warn("[OrbitControls] setCameraAndLookTarget target is null"),!1;if(!(e instanceof d.Object3D)&&!(e instanceof ri))return(j()||Ui)&&console.warn("[OrbitControls] setCameraAndLookTarget target is not an Object3D or Camera"),!1;e instanceof ri&&(e=e.gameObject);const n=e.worldPosition,s=e.worldForward;e instanceof d.Camera&&(Ui&&console.debug("[OrbitControls] setCameraAndLookTarget flip forward direction for camera"),s.multiplyScalar(-1));const a=new d.Ray(n,s);return Ui&&V.DrawRay(a.origin,a.direction,16711680,10),this.setTargetFromRaycast(a,i)||this.setLookTargetPosition(a.at(2,$()),i),this.setCameraTargetPosition(n,i),!0}setCameraTargetPosition(e,i=!1){var n;e&&(e instanceof d.Object3D&&(e=Q(e)),this._cameraEndPosition||(this._cameraEndPosition=new d.Vector3),this._cameraEndPosition.copy(e),i===!0?(this._cameraLerpActive=!1,this._cameraObject&&this._cameraObject.position.copy(this._cameraEndPosition)):this._cameraObject&&(this._cameraLerpActive=!0,this._cameraLerp01=0,this._cameraStartPosition.copy((n=this._cameraObject)==null?void 0:n.position),typeof i=="number"?this._cameraLerpDuration=i:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setFieldOfView(e,i=!1){var s;if(!this._controls||typeof e!="number")return;const n=(s=this._camera)==null?void 0:s.threeCamera;n&&(i===!0?n.fov=e:(this._fovLerpActive=!0,this._fovLerp01=0,this._fovLerpStartValue=n.fov,this._fovLerpEndValue=e,typeof i=="number"?this._fovLerpDuration=i:this._fovLerpDuration=this.targetLerpDuration))}setLookTargetPosition(e=null,i=!1){this._controls&&e&&(e instanceof d.Object3D&&(e=Q(e)),this._lookTargetEndPosition.copy(e),this._didSetTarget++,Ui&&(console.warn("OrbitControls: setLookTargetPosition",e,i),V.DrawWireSphere(this._lookTargetEndPosition,.2,16711680,2)),i===!0?this._controls.target.copy(this._lookTargetEndPosition):(this._lookTargetLerpActive=!0,this._lookTargetLerp01=0,this._lookTargetStartPosition.copy(this._controls.target),typeof i=="number"?this._lookTargetLerpDuration=i:this._lookTargetLerpDuration=this.targetLerpDuration))}get lookTargetLerpActive(){return this._lookTargetLerpActive}stopLookTargetLerp(){this._lookTargetLerpActive=!1}setLookTargetFromConstraint(e=0,i=1){var s,a;if(!this._controls||((s=this.lookAtConstraint)==null?void 0:s.enabled)===!1)return!1;const n=(a=this.lookAtConstraint)==null?void 0:a.sources;if(n&&n.length>0){const l=n[e];if(l)return l.getWorldPosition(this._lookTargetEndPosition),this.lerpLookTarget(this._lookTargetEndPosition,i),!0}return!1}lerpTarget(e,i){return this.lerpLookTarget(e,i)}lerpLookTarget(e,i){this._controls&&(i>=1?this._controls.target.copy(e):this._controls.target.lerp(e,i))}setTargetFromRaycast(e,i=!1){if(!this.controls)return!1;const n=e?this.context.physics.raycastFromRay(e):this.context.physics.raycast();for(const s of n)if(s.distance>0&&C.isActiveInHierarchy(s.object)){const a=Rg(s.object);if(a){const l=a.canvas;if(l!=null&&l.screenspace)break}return this.setLookTargetPosition(s.point,i),!0}return!1}fitCamera(e,i){var H,B;if(this.context.isInXR)return;let n;if(Array.isArray(e)?n=e:e&&"type"in e?n=e.children:e&&typeof e=="object"&&!(e instanceof d.Object3D)&&!Array.isArray(e)&&(i=e,n=i.objects),n&&!Array.isArray(n)&&(n=n.children),(!Array.isArray(n)||n&&n.length<=0)&&(n=this.context.scene.children),!Array.isArray(n)||n.length<=0){console.warn("No objects to fit camera to...");return}const s=this._cameraObject,a=this._controls;if(!s||!a){console.warn("No camera or controls found to fit camera to objects...");return}i||(i={});const{immediate:l=!1,centerCamera:c="y",cameraNearFar:h="auto",fitOffset:u=1.1,fov:f=s==null?void 0:s.fov}=i,p=new d.Vector3,g=new d.Vector3,y=li(n,void 0,(B=(H=this._camera)==null?void 0:H.threeCamera)==null?void 0:B.layers),b=y.clone();s.updateMatrixWorld(),s.updateProjectionMatrix(),y.getCenter(g);const _=new d.Vector3;if(y.getSize(_),y.applyMatrix4(s.matrixWorldInverse),y.getSize(p),y.setFromCenterAndSize(g,p),Number.isNaN(p.x)||Number.isNaN(p.y)||Number.isNaN(p.z)){console.warn("Camera fit size resultet in NaN",s,y,[...n]);return}if(p.length()<=1e-10){El&&console.warn("Camera fit size is zero",y,[...n]);return}const v=i.fov||s.fov,w=2*Math.atan(Math.tan(v*Math.PI/360/2)*s.aspect)/Math.PI*360,x=p.y/(2*Math.atan(Math.PI*v/360)),O=p.x/(2*Math.atan(Math.PI*w/360)),M=u*Math.max(x,O)+p.z/2;El&&console.log("Fit camera to objects",{fitHeightDistance:x,fitWidthDistance:O,distance:M,verticalFov:v,horizontalFov:w}),this.maxZoom=M*10,this.minZoom=M*.01;const R=.05,E=g.clone();if(E.y-=p.y*R,this.setLookTargetPosition(E,l),this.setFieldOfView(i.fov,l),h==null||h=="auto"){const I=C.findObjectOfType(ss),N=I?I.radius:0,Y=Math.max(_.x,_.y,_.z,N);s.near=M/100,s.far=Y+M*10,I&&(this.maxZoom=Math.max(Math.min(this.maxZoom,N*.5),M))}const F=a.getDistance();F<this.minZoom&&(this.minZoom=F*.9),F>this.maxZoom&&(this.maxZoom=F*1.1),s.updateMatrixWorld(),s.updateProjectionMatrix();const T=Q(s),L=g.clone();L.sub(T),c==="y"&&(L.y=0),L.normalize(),L.multiplyScalar(M),c==="y"&&(L.y+=-R*4*M);let A=g.clone().sub(L);s.parent&&(A=s.parent.worldToLocal(A)),this.setCameraTargetPosition(A,l),(El||i.debug)&&(V.DrawWireBox3(y,16777011,10),V.DrawWireBox3(b,65280,10),!this._haveAttachedKeyboardEvents&&El&&(this._haveAttachedKeyboardEvents=!0,document.body.addEventListener("keydown",I=>{if(I.code==="KeyF"){let N;this._cameraObject instanceof d.PerspectiveCamera&&(N=Math.random()*Math.random()*170+10),this.fitCamera({objects:n,fitOffset:u,immediate:!1,fov:N})}I.code==="KeyV"&&this._cameraObject instanceof d.PerspectiveCamera&&(this._cameraObject.fov=60)}))),this.onBeforeRender()}}Te([m()],ge.prototype,"autoTarget");Te([m()],ge.prototype,"autoFit");Te([m()],ge.prototype,"enableRotate");Te([m()],ge.prototype,"autoRotate");Te([m()],ge.prototype,"autoRotateSpeed");Te([m()],ge.prototype,"minAzimuthAngle");Te([m()],ge.prototype,"maxAzimuthAngle");Te([m()],ge.prototype,"minPolarAngle");Te([m()],ge.prototype,"maxPolarAngle");Te([m()],ge.prototype,"enableKeys");Te([m()],ge.prototype,"enableDamping");Te([m()],ge.prototype,"dampingFactor");Te([m()],ge.prototype,"enableZoom");Te([m()],ge.prototype,"minZoom");Te([m()],ge.prototype,"maxZoom");Te([m()],ge.prototype,"zoomSpeed");Te([m()],ge.prototype,"enablePan");Te([m(Ur)],ge.prototype,"lookAtConstraint");Te([m()],ge.prototype,"lookAtConstraint01");Te([m()],ge.prototype,"allowInterrupt");Te([m()],ge.prototype,"middleClickToFocus");Te([m()],ge.prototype,"doubleClickToFocus");Te([m()],ge.prototype,"clickBackgroundToFitScene");Te([m()],ge.prototype,"targetLerpDuration");var QP=Object.defineProperty,YP=Object.getOwnPropertyDescriptor,Kt=(o,t,e,i)=>{for(var n=i>1?void 0:i?YP(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&QP(t,e,n),n},Co=(o=>(o[o.None=0]="None",o[o.Skybox=1]="Skybox",o[o.SolidColor=2]="SolidColor",o[o.Uninitialized=4]="Uninitialized",o))(Co||{});const io=S("debugcam"),ab=S("debugscreenpointtoray");var pn;const Lt=(pn=class extends D{constructor(){super(...arguments);r(this,"_nearClipPlane",.1);r(this,"_farClipPlane",1e3);r(this,"orthographic",!1);r(this,"orthographicSize",5);r(this,"ARBackgroundAlpha",0);r(this,"_cullingMask",4294967295);r(this,"_backgroundBlurriness");r(this,"_backgroundIntensity");r(this,"_backgroundRotation");r(this,"_environmentIntensity");r(this,"_targetTexture",null);r(this,"_backgroundColor");r(this,"_fov");r(this,"_cam",null);r(this,"_clearFlags",2);r(this,"_skybox");r(this,"_frustum");r(this,"_projScreenMatrix",new d.Matrix4)}get isCamera(){return!0}get aspect(){return this._cam instanceof d.PerspectiveCamera?this._cam.aspect:this.context.domWidth/this.context.domHeight}set aspect(e){this._cam instanceof d.PerspectiveCamera&&this._cam.aspect!==e&&(this._cam.aspect=e,this._cam.updateProjectionMatrix())}get fieldOfView(){return this._cam instanceof d.PerspectiveCamera?this._cam.fov:this._fov}set fieldOfView(e){const i=this.fieldOfView!=e;if(this._fov=e,i&&this._cam&&this._cam instanceof d.PerspectiveCamera){if(this._fov===void 0){console.warn("Can not set undefined fov on PerspectiveCamera");return}this._cam.fov=this._fov,this._cam.updateProjectionMatrix()}}get nearClipPlane(){return this._nearClipPlane}set nearClipPlane(e){const i=this._nearClipPlane!=e;this._nearClipPlane=e,this._cam&&(i||this._cam.near!=e)&&(this._cam.near=e,this._cam.updateProjectionMatrix())}get farClipPlane(){return this._farClipPlane}set farClipPlane(e){const i=this._farClipPlane!=e;this._farClipPlane=e,this._cam&&(i||this._cam.far!=e)&&(this._cam.far=e,this._cam.updateProjectionMatrix())}applyClippingPlane(){this._cam&&(this._cam.near=this._nearClipPlane,this._cam.far=this._farClipPlane,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(e){if(typeof e=="string")switch(e){case"skybox":e=1;break;case"solidcolor":e=2;break;default:e=0;break}e!==this._clearFlags&&(this._clearFlags=e,this.applyClearFlagsIfIsActiveCamera())}set cullingMask(e){this._cullingMask=e,this._cam&&(this._cam.layers.mask=e)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}set cullingLayer(e){this.cullingMask=(1<<e|0)>>>0}set backgroundBlurriness(e){e!==this._backgroundBlurriness&&(e===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(e,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}set backgroundIntensity(e){e!==this._backgroundIntensity&&(e===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(e,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}set backgroundRotation(e){e!==this._backgroundRotation&&(e===void 0?this._backgroundRotation=void 0:this._backgroundRotation=e,this.applyClearFlagsIfIsActiveCamera())}get backgroundRotation(){return this._backgroundRotation}set environmentIntensity(e){this._environmentIntensity=e}get environmentIntensity(){return this._environmentIntensity}get backgroundColor(){return this._backgroundColor??null}set backgroundColor(e){e&&(this._backgroundColor||(this._backgroundColor=new ie(1,1,1,1)),this._backgroundColor.copy(e),(!("alpha"in e)||e.alpha===void 0)&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera())}set targetTexture(e){this._targetTexture=e}get targetTexture(){return this._targetTexture}get cam(){return this.threeCamera}get threeCamera(){return this.activeAndEnabled&&this.buildCamera(),this._cam}screenPointToRay(e,i,n){const s=this.threeCamera,a=pn._origin;a.set(e,i,-1),this.context.input.convertScreenspaceToRaycastSpace(a),ab&&console.log("screenPointToRay",e.toFixed(2),i.toFixed(2),"now:",a.x.toFixed(2),a.y.toFixed(2),"isInXR:"+this.context.isInXR),a.z=-1,a.unproject(s);const l=pn._direction.set(a.x,a.y,a.z),c=Q(s);return l.sub(c),l.normalize(),n?(n.set(c,l),n):new d.Ray(c.clone(),l.clone())}getFrustum(){return this._frustum||(this._frustum=new d.Frustum,this.updateFrustum()),this._frustum}updateFrustum(){this._frustum||(this._frustum=new d.Frustum),this._frustum.setFromProjectionMatrix(this.getProjectionScreenMatrix(this._projScreenMatrix,!0),this.context.renderer.coordinateSystem)}getProjectionScreenMatrix(e,i){return i&&this._projScreenMatrix.multiplyMatrices(this.threeCamera.projectionMatrix,this.threeCamera.matrixWorldInverse),e===this._projScreenMatrix?e:e.copy(this._projScreenMatrix)}awake(){ab&&window.addEventListener("pointerdown",e=>{const i=e.clientX,n=e.clientY;console.log("touch",i.toFixed(2),n.toFixed(2));const s=this.screenPointToRay(i,n),a="#"+Math.floor(Math.random()*16777215).toString(16);V.DrawRay(s.origin,s.direction,a,10)})}onEnable(){io&&console.log(`Camera enabled: "${this.name}". ClearFlags=${Co[this._clearFlags]}`,this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),ZP(this)),this.applyClearFlagsIfIsActiveCamera({applySkybox:!0})}onDisable(){this.context.removeCamera(this)}onBeforeRender(){if(this._cam&&(this._frustum&&this.updateFrustum(),this._clearFlags===2&&this.applyClearFlagsIfIsActiveCamera(),this._targetTexture)){this.context.isManagedExternally&&(this._warnedAboutExternalRenderer||(this._warnedAboutExternalRenderer=!0,console.warn("Rendering with external renderer is not supported yet. This may not work or throw errors. Please remove the the target texture from your camera: "+this.name,this.targetTexture))),this.context.composer;const e=this.context.renderer;if(e){const i=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,e),i==null||i.applyClearFlags()}}}buildCamera(){if(this._cam)return;const e=this.gameObject.isCamera;let i=null;if(e?(i=this.gameObject,i==null||i.layers.enableAll(),i instanceof d.PerspectiveCamera&&(this._fov=i.fov)):i=this.gameObject.children[0],i&&i.isCamera)i instanceof d.PerspectiveCamera&&(this._fov&&(i.fov=this._fov),i.near=this._nearClipPlane,i.far=this._farClipPlane,i.updateProjectionMatrix());else if(!this.orthographic)i=new d.PerspectiveCamera(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(i.fov=this.fieldOfView),this.gameObject.add(i);else{const n=this.orthographicSize*100;i=new d.OrthographicCamera(window.innerWidth/-n,window.innerWidth/n,window.innerHeight/n,window.innerHeight/-n,this._nearClipPlane,this._farClipPlane),this.gameObject.add(i)}this._cam=i,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(e){this.context.mainCameraComponent===this&&this.applyClearFlags(e)}applyClearFlags(e){var n;if(!this._cam){io&&console.log("Camera does not exist (apply clear flags)");return}if(this.fieldOfView=this._fov,io){const s=`[Camera] Apply ClearFlags: ${Co[this._clearFlags]} - "${this.name}"`;console.debug(s)}const i=this.context.domElement.getAttribute("background-image")||this.context.domElement.getAttribute("background-color")||this.context.domElement.getAttribute("skybox-image");switch(this._clearFlags){case 0:return;case 1:if(pn.backgroundShouldBeTransparent(this.context)&&(!this.ARBackgroundAlpha||this.ARBackgroundAlpha<.001)){this.context.scene.background=null,this.context.renderer.setClearColor(0,0);return}(!this.scene.background||!this._skybox||(e==null?void 0:e.applySkybox)===!0)&&this.applySceneSkybox(),this._backgroundBlurriness!==void 0&&!this.context.domElement.getAttribute("background-blurriness")?this.context.scene.backgroundBlurriness=this._backgroundBlurriness:io&&console.warn(`Camera "${this.name}" has no background blurriness`),this._backgroundIntensity!==void 0&&!this.context.domElement.getAttribute("background-intensity")&&(this.context.scene.backgroundIntensity=this._backgroundIntensity),this._backgroundRotation!==void 0&&!this.context.domElement.getAttribute("background-rotation")?this.context.scene.backgroundRotation=this._backgroundRotation:io&&console.warn(`Camera "${this.name}" has no background intensity`);break;case 2:if(this._backgroundColor&&!i){let s=this._backgroundColor.alpha;pn.backgroundShouldBeTransparent(this.context)&&(s=this.ARBackgroundAlpha??0),this.context.scene.background=null,(n=this.context.xr)!=null&&n.isVR?this.context.renderer.setClearColor(x0(this._backgroundColor).convertLinearToSRGB()):this.context.renderer.setClearColor(this._backgroundColor,s)}else this._backgroundColor||io&&console.warn(`[Camera] has no background color "${this.name}" `);break;case 4:i||(this.context.scene.background=null,this.context.renderer.setClearColor(0,0));break}}applySceneSkybox(){this._skybox||(this._skybox=new KP(this)),this._skybox.apply()}static backgroundShouldBeTransparent(e){var a,l,c,h;const i=(a=e.renderer.xr)==null?void 0:a.getSession();if(!i)return!1;if(typeof i._transparent=="boolean")return i._transparent;const n=i.environmentBlendMode;io&&Ee("Environment blend mode: "+n+" on "+navigator.userAgent);let s=n==="additive"||n==="alpha-blend";return e.isInAR&&n==="opaque"&&((l=navigator.userAgent)!=null&&l.includes("OculusBrowser")||(c=navigator.userAgent)!=null&&c.includes("Mozilla")&&((h=navigator.userAgent)!=null&&h.includes("Mobile WebXRViewer/v2")))&&(s=!0),i._transparent=s,s}},r(pn,"_origin",new d.Vector3),r(pn,"_direction",new d.Vector3),pn);Kt([m()],Lt.prototype,"aspect",1);Kt([m()],Lt.prototype,"fieldOfView",1);Kt([m()],Lt.prototype,"nearClipPlane",1);Kt([m()],Lt.prototype,"farClipPlane",1);Kt([m()],Lt.prototype,"clearFlags",1);Kt([m()],Lt.prototype,"orthographic",2);Kt([m()],Lt.prototype,"orthographicSize",2);Kt([m()],Lt.prototype,"ARBackgroundAlpha",2);Kt([m()],Lt.prototype,"cullingMask",1);Kt([m()],Lt.prototype,"backgroundBlurriness",1);Kt([m()],Lt.prototype,"backgroundIntensity",1);Kt([m(d.Euler)],Lt.prototype,"backgroundRotation",1);Kt([m()],Lt.prototype,"environmentIntensity",1);Kt([m(ie)],Lt.prototype,"backgroundColor",1);Kt([m(Sr)],Lt.prototype,"targetTexture",1);let ri=Lt;class KP{constructor(t){r(this,"_camera");r(this,"_skybox");this._camera=t}get context(){var t;return(t=this._camera)==null?void 0:t.context}apply(){var t;if(this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),!this._skybox)this._did_log_failed_to_find_skybox||(this._did_log_failed_to_find_skybox=!0,console.warn(`Camera "${this._camera.name}" has no skybox texture. ${this._camera.sourceId}`));else if(this.context.scene.background!==this._skybox){const e=this.context.domElement.getAttribute("background-image")||this.context.domElement.getAttribute("background-color")||this.context.domElement.getAttribute("skybox-image");io&&console.debug(`[Camera] Apply Skybox ${(t=this._skybox)==null?void 0:t.name} ${e} - "${this._camera.name}"`),e!=null&&e.length||(this._skybox.mapping=d.EquirectangularReflectionMapping,this.context.scene.background=this._skybox)}}}function ZP(o){S("freecam")&&o.context.mainCameraComponent===o&&C.getOrAddComponent(o.gameObject,ge)}class Ms extends D{constructor(){super(...arguments);r(this,"_listener",null);r(this,"onInteraction",()=>{this.destroyed||this.listener==null||this.addListenerIfItExists()})}get listener(){return this._listener==null&&(this._listener=new d.AudioListener),this._listener}onEnable(){wn.registerWaitForInteraction(this.onInteraction),this.addListenerIfItExists()}onDisable(){wn.unregisterWaitForInteraction(this.onInteraction),this.removeListenerIfItExists()}addListenerIfItExists(){const e=this._listener;if(!e||e!=null&&e.parent)return;const i=this.context.mainCameraComponent||C.getComponentInParent(this.gameObject,ri);i!=null&&i.threeCamera?i.threeCamera.add(e):this.gameObject.add(e),e.filter?(e.gain.connect(e.filter),e.filter.connect(e.context.destination)):e.gain.connect(e.context.destination)}removeListenerIfItExists(){const e=this._listener;e&&(e.removeFromParent(),e.filter&&e.filter.disconnect(),e.gain&&e.gain.disconnect())}}var JP=Object.defineProperty,eM=Object.getOwnPropertyDescriptor,Cn=(o,t,e,i)=>{for(var n=i>1?void 0:i?eM(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&JP(t,e,n),n};const gt=S("debugaudio"),Zi=class no extends D{constructor(){super(...arguments);r(this,"clip","");r(this,"playOnAwake",!1);r(this,"preload",!0);r(this,"playInBackground",!0);r(this,"_spatialBlend",0);r(this,"_minDistance",1);r(this,"_maxDistance",100);r(this,"_volume",1);r(this,"rollOffMode",0);r(this,"_loop",!1);r(this,"sound",null);r(this,"helper",null);r(this,"wasPlaying",!1);r(this,"audioLoader",null);r(this,"shouldPlay",!1);r(this,"_lastClipStartedLoading",null);r(this,"_audioElement",null);r(this,"onVisibilityChanged",()=>{switch(document.visibilityState){case"hidden":(this.playInBackground===!1||exports.DeviceUtilities.isMobileDevice())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":gt&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,no.userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&no.userInteractionRegistered&&this.wasPlaying&&this.play();break}});r(this,"onApplicationMuteChanged",()=>{var e,i;this.context.application.muted?(e=this.sound)==null||e.setVolume(0):(i=this.sound)==null||i.setVolume(this.volume)});r(this,"createAudio",e=>{if(this.destroyed){gt&&console.warn("AudioSource destroyed, not creating audio",this.name);return}gt&&console.log("AudioBuffer finished loading",e);const i=this.Sound;if(!i){gt&&console.warn("Failed getting sound?",this.name);return}i.isPlaying&&i.stop(),e&&i.setBuffer(e),i.loop=this._loop,this.context.application.muted?i.setVolume(0):i.setVolume(this.volume),i.autoplay=this.shouldPlay&&no.userInteractionRegistered,this.applySpatialDistanceSettings(),i.isPlaying&&i.stop(),no.registerWaitForAllowAudio(this.__onAllowAudioCallback)});r(this,"__onAllowAudioCallback",()=>{this.shouldPlay&&this.play()});r(this,"_lastContextTime",0);r(this,"_hasEnded",!0);r(this,"_needUpdateSpatialDistanceSettings",!1)}static get userInteractionRegistered(){return wn.userInteractionRegistered}static registerWaitForAllowAudio(e){wn.registerWaitForInteraction(e)}get isPlaying(){var e;return((e=this.sound)==null?void 0:e.isPlaying)??!1}get duration(){var e,i;return(i=(e=this.sound)==null?void 0:e.buffer)==null?void 0:i.duration}get time01(){var i;const e=this.duration;return e&&this.sound?((i=this.sound)==null?void 0:i.context.currentTime)/e:0}set time01(e){const i=this.duration;i&&this.sound&&(this.time=e*i)}get time(){var e,i;return(e=this.sound)!=null&&e.source?((i=this.sound.source)==null?void 0:i.context.currentTime)-this._lastContextTime+this.sound.offset:0}set time(e){if(this.sound){if(e===this.sound.offset)return;const i=this.isPlaying;this.stop(),this.sound.offset=e,i&&this.play()}}get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(e){this._loop=e,this.sound&&this.sound.setLoop(e)}get spatialBlend(){return this._spatialBlend}set spatialBlend(e){e!==this._spatialBlend&&(this._spatialBlend=e,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(e){this._minDistance!==e&&(this._minDistance=e,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(e){this._maxDistance!==e&&(this._maxDistance=e,this._needUpdateSpatialDistanceSettings=!0)}get volume(){return this._volume}set volume(e){this._volume=e,this.sound&&!this.context.application.muted&&(gt&&console.log(this.name,"audio set volume",e),this.sound.setVolume(e))}set pitch(e){this.sound&&this.sound.setPlaybackRate(e)}get pitch(){return this.sound?this.sound.getPlaybackRate():1}get Sound(){var e;if(!this.sound&&no.userInteractionRegistered){let i=this.gameObject.getComponent(Ms)??this.context.mainCamera.getComponent(Ms)??ch(Ms,this.context,!1);!i&&this.context.mainCamera&&(i=this.context.mainCamera.addComponent(Ms)),i!=null&&i.listener?(this.sound=new d.PositionalAudio(i.listener),(e=this.gameObject)==null||e.add(this.sound)):gt&&console.warn("No audio listener found in scene - can not play audio")}return this.sound}get ShouldPlay(){return this.shouldPlay}get audioContext(){var e;return(e=this.sound)==null?void 0:e.context}awake(){gt&&console.log("[AudioSource]",this),this.audioLoader=new d.AudioLoader,this.playOnAwake&&(this.shouldPlay=!0),this.preload&&typeof this.clip=="string"&&this.audioLoader.load(this.clip,this.createAudio,()=>{},console.error)}onEnable(){this.sound&&this.gameObject.add(this.sound),no.userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():no.registerWaitForAllowAudio(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.onNewClip(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(im.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(im.MuteChanged,this.onApplicationMuteChanged),this.pause()}applySpatialDistanceSettings(){const e=this.sound;if(!e)return;this._needUpdateSpatialDistanceSettings=!1;const i=z.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(gt&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+i),e.setRefDistance(i),e.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:e.setDistanceModel("exponential");break;case 1:e.setDistanceModel("linear");break;case 2:console.warn("Custom rolloff for AudioSource is not supported: "+this.name);break}this.spatialBlend>0?gt&&!this.helper&&(this.helper=new G.PositionalAudioHelper(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}async onNewClip(e){if(e&&(this.clip=e),typeof e=="string")if(gt&&console.log(e),e.endsWith(".mp3")||e.endsWith(".wav")){if(this.audioLoader||(this.audioLoader=new d.AudioLoader),this.shouldPlay=!0,this._lastClipStartedLoading===e){gt&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=e,gt&&console.log("load audio",e);const i=await this.audioLoader.loadAsync(e).catch(console.error);if(this.destroyed)return;this._lastClipStartedLoading===e&&(this._lastClipStartedLoading=null),i&&this.createAudio(i)}else console.warn("Unsupported audio clip type",e);else this.shouldPlay=!0,this.createAudio()}play(e=void 0){var n,s,a;!e&&this.clip&&(e=this.clip),e!==void 0&&typeof e!="string"&&!(e instanceof MediaStream)&&(j()&&console.warn("Called play on AudioSource with unknown argument type:",e+`
939
+ Could not find method ${h.method} on object ${f.name}`,f,typeof f[h.method])};if(typeof f[h.method]!="function"){let b=!1,_=f;for(;_;){const v=Object.getOwnPropertyDescriptor(_,h.method);if(v&&(v.writable===!0||v.set)){b=!0;break}_=Object.getPrototypeOf(_)}!b&&(j()||dt)&&g()}}if(f){let g=h.argument;if(g!==void 0?g=u(g):h.arguments!==void 0&&(g=h.arguments.map(u)),!f[h.method])console.warn(`EventList method not found: "${h.method}" on ${f==null?void 0:f.name}`);else{g!==void 0&&!Array.isArray(g)&&(g=[g]);const b=new Cs(f,h.method,g,h.enabled);a.push(b)}}else j()&&console.warn("[Debug] EventList: Could not find event listener in scene",h,e.object,t)}const l=new ye(a);dt&&console.log(l);const c=e.target;return c!==void 0&&e.path!==void 0&&l.setEventTarget(e.path,c),l}}}const NP=new zP,cu=new WeakMap,VP=d.Texture.prototype.clone;d.Texture.prototype.clone=function(){const o=VP.call(this);return cu.has(o)||cu.set(o,this),o};class hw extends Ki{constructor(){super([Sr,d.WebGLRenderTarget])}onSerialize(t,e){}onDeserialize(t,e){if(t instanceof d.Texture&&e.type===Sr){let i=t;cu.has(i)&&(i=cu.get(i)),i.isRenderTargetTexture=!0,i.flipY=!0,i.offset.y=1,i.repeat.y=-1,i.needsUpdate=!0,i.mipmaps=[],i instanceof d.CompressedTexture&&(i.isCompressedTexture=!1,i.format=d.RGBAFormat);const n=new Sr(i.image.width,i.image.height,{colorSpace:d.LinearSRGBColorSpace});return n.texture=i,n}}}new hw;class dw extends Ki{constructor(){super([URL])}onSerialize(t,e){return null}onDeserialize(t,e){if(typeof t=="string"&&t.length>0)return To(e.gltfId,t)}}new dw;var $P=Object.defineProperty,WP=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&$P(t,e,n),n};class Ga extends D{awake(){Qt.createIfNoneExists(this.context)}onEnable(){var t;(t=Qt.get(this.context))==null||t.register(this)}onDisable(){var t;(t=Qt.get(this.context))==null||t.unregister(this)}}class Ei extends Ga{constructor(){super(...arguments);r(this,"targets",null);r(this,"raycastHits",[]);r(this,"ignoreSkinnedMeshes",!1)}start(){this.targets=[this.gameObject]}performRaycast(e=null){if(!this.targets)return null;e??(e=new Jn),e.targets=this.targets,e.results=this.raycastHits,e.useAcceleratedRaycast=!0;const i=e.testObject;this.ignoreSkinnedMeshes&&(e.testObject=s=>s instanceof d.SkinnedMesh?"continue in children":i?i(s):!0);const n=this.context.physics.raycast(e);return e.testObject=i,n}}WP([m()],Ei.prototype,"ignoreSkinnedMeshes");class Yu extends Ei{constructor(){super(),this.ignoreSkinnedMeshes=!0}}const Ru=class Ru extends Ga{performRaycast(t){if(!J.active||!Ru.allow||!(t!=null&&t.ray))return null;const e=t.ray.origin;return this.context.physics.sphereOverlap(e,.015,!1,!0)}};r(Ru,"allow",!0);let Tr=Ru;class kg{static getObject(t){const e=t[Si];return e&&(e.isComponent===!0?t=e.gameObject:t=e),t}static isInteractable(t,e){if(e&&(e.canvasGroup=void 0,e.graphic=void 0),t==null||!t.visible||(t=this.getObject(t),!t.visible))return!1;const i=this.tryFindCanvasGroup(t);if((i==null?void 0:i.isCanvasGroup)===!0&&(e&&(e.canvasGroup=i),i.blocksRaycasts===!1||i.interactable===!1))return!1;const n=Rr(t,s=>{if(s.isGraphic===!0)return s},!1);return e&&(n==null?void 0:n.isGraphic)===!0&&(e.graphic=n),!((n==null?void 0:n.raycastTarget)===!1||(n==null?void 0:n.layer)===2)}static tryFindCanvasGroup(t){if(!t)return null;const e=Rr(t,i=>{const n=i;if(n.blocksRaycasts!==void 0&&n.interactable!==void 0)return n},!1);return e!==void 0?e:this.tryFindCanvasGroup(t.parent)}}function Rg(o){const t=o[Si];return t||(o.parent?Rg(o.parent):null)}function HP(o){return o.isUI===!0||typeof o[Si]=="object"}function hu(o,t){if(!o)return;const e=o.material;if((e==null?void 0:e.isMaterial)===!0){const i=o.parent;i&&i.isText,e.side=t.doubleSided??!0?d.DoubleSide:d.FrontSide,e.shadowSide=t.doubleSided?d.DoubleSide:d.FrontSide,o.castShadow=t.castShadows?t.castShadows:!1,o.receiveShadow=t.receiveShadows?t.receiveShadows:!1}for(const i of o.children)hu(i,t)}function pa(o,t,e){o[t]===void 0&&console.warn("Field",t,"is undefined on",o);const i=Proxy.revocable(o[t],{set(a,l,c,h){const u=a[l],f=Reflect.set(a,l,c,h);return e(c,u),f}}),n=i.revoke,s=o[t];return i.revoke=()=>{o[t]=s,n()},o[t]=i.proxy,i}const rb=Symbol("Scheduled action");function GP(o,t,e=we.OnBeforeRender){let i=o[rb];i||(i=o[rb]={});const n=t.name;i[e]||(i[e]={});const s=i[e];if(s[n])return;function*l(){t==null||t.call(o),s[n]=null}const c=o.startCoroutine(l(),e);s[n]=c}const to=S("debugeventsystem");var Sm=(o=>(o.BeforeHandleInput="BeforeHandleInput",o.AfterHandleInput="AfterHandleInput",o))(Sm||{});sw(o=>{Qt.createIfNoneExists(o)});class Qt extends D{constructor(){super(...arguments);r(this,"raycaster",[]);r(this,"pressedByID",new Map);r(this,"hoveredByID",new Map);r(this,"onPointerEvent",e=>{if(e===void 0||e.propagationStopped||e.defaultPrevented||e.used)return;const i=new ph(this.context.input,e);this._currentPointerEventName=e.type,i.inputSource=this.context.input,i.isClick=e.isClick,i.isDoubleClick=e.isDoubleClick,i.isDown=e.type==Re.PointerDown,i.isUp=e.type==Re.PointerUp,i.isPressed=this.context.input.getPointerPressed(e.pointerId),to&&(i.isDown?console.log("DOWN",i.pointerId):i.isUp&&console.log("UP",i.pointerId),i.isClick&&console.log("CLICK",i.pointerId));const n=new Jn;e.hasRay?n.ray=e.ray:n.screenPoint=this.context.input.getPointerPositionRC(e.pointerId);const s=this.performRaycast(n);if(s){for(const l of s)l.event=e,e.intersections.push(l);e.origin.onPointerHits&&e.origin.onPointerHits({sender:this,event:e,hits:s})}to&&i.isClick&&Ee("EventSystem: "+i.pointerId+" - "+this.context.time.frame+" - Up:"+i.isUp+", Down:"+i.isDown);const a={sender:this,args:i,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:a})),this.handleIntersections(s,i),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:a}))});r(this,"_sortedHits",[]);r(this,"_testObjectsCache",new Map);r(this,"_currentlyActiveRaycaster",null);r(this,"_currentPointerEventName",null);r(this,"shouldRaycastObject",e=>{var a;const i=e&&"getComponent"in e?e.getComponent(Ga):null;if(i&&i!=this._currentlyActiveRaycaster)return!1;let n=null;if(HP(e)&&(n=(a=e[Si])==null?void 0:a.gameObject),this._testObjectsCache.has(e)||n&&this._testObjectsCache.has(n))return this._testObjectsCache.get(e)===!1?"continue in children":!0;{let l=lu(e,this._currentPointerEventName);if(!l&&n&&(l=lu(n,this._currentPointerEventName)),l){this._testObjectsCache.set(e,!0);for(const c of e.children)this.shouldRaycastObject_AddToYesCache(c);return!0}return this._testObjectsCache.set(e,!1),"continue in children"}});r(this,"_sortingBuffer",[]);r(this,"_noDepthTestingResults",[]);r(this,"out",{});r(this,"_capturedPointer",{});r(this,"pointerEnterSymbol",Symbol("pointerEnter"));r(this,"pointerExitSymbol",Symbol("pointerExit"));r(this,"currentActiveMeshUIComponents",[])}static ensureUpdateMeshUI(e,i,n=!1){fo.update(e,i,n)}static markUIDirty(e){fo.markDirty()}static createIfNoneExists(e){e.scene.getComponent(Qt)||e.scene.addComponent(Qt)}static get(e){return this.createIfNoneExists(e),e.scene.getComponent(Qt)}static get instance(){return this.get(X.Current)}register(e){var i;e&&this.raycaster&&!this.raycaster.includes(e)&&((i=this.raycaster)==null||i.push(e))}unregister(e){var n,s;const i=(n=this.raycaster)==null?void 0:n.indexOf(e);i!==void 0&&i!==-1&&((s=this.raycaster)==null||s.splice(i,1))}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.hoveredByID.size>0}awake(){this.gameObject!==this.context.scene&&(console.debug(`[Needle Engine] EventSystem is only allowed on the scene root. Disabling EventSystem on '${this.gameObject.name}'`),this.enabled=!1)}start(){this.context.scene.getComponent(Ga)||this.context.scene.addComponent(Ei)}onEnable(){this.context.input.addEventListener(Re.PointerDown,this.onPointerEvent),this.context.input.addEventListener(Re.PointerUp,this.onPointerEvent),this.context.input.addEventListener(Re.PointerMove,this.onPointerEvent)}onDisable(){this.context.input.removeEventListener(Re.PointerDown,this.onPointerEvent),this.context.input.removeEventListener(Re.PointerUp,this.onPointerEvent),this.context.input.removeEventListener(Re.PointerMove,this.onPointerEvent)}onBeforeRender(){this.resetMeshUIStates()}shouldRaycastObject_AddToYesCache(e){this._testObjectsCache.set(e,!0);for(const i of e.children)this.shouldRaycastObject_AddToYesCache(i)}performRaycast(e){if(!this.raycaster)return null;this._testObjectsCache.clear(),this._sortedHits.length=0,e||(e=new Jn),e.testObject=this.shouldRaycastObject;for(const i of this.raycaster){if(!i.activeAndEnabled)continue;this._currentlyActiveRaycaster=i;const n=i.performRaycast(e);this._currentlyActiveRaycaster=null,n&&n.length>0&&this._sortedHits.push(...n)}return this._sortedHits.sort((i,n)=>i.distance-n.distance),this._sortedHits}assignHitInformation(e,i){i?(e.intersection=i,e.point=i.point,e.normal=i.normal,e.face=i.face,e.distance=i.distance,e.instanceId=i.instanceId):(e.intersection=void 0,e.point=void 0,e.normal=void 0,e.face=void 0,e.distance=void 0,e.instanceId=void 0)}handleIntersections(e,i){var s;if(e!=null&&e.length){e=this.sortCandidates(e);for(const a of e){if(i.event.immediatePropagationStopped)return!1;if(this.assignHitInformation(i,a),this.handleEventOnObject(a.object,i))return!0}}this.assignHitInformation(i,e==null?void 0:e[0]),this.invokePointerCapture(i);const n=this.hoveredByID.get(i.pointerId);return n&&this.propagatePointerExit(n.obj,n.data,null),this.hoveredByID.delete(i.pointerId),i.isUp&&((s=this.pressedByID.get(i.pointerId))==null||s.handlers.forEach(a=>this.invokeOnPointerUp(i,a)),this.pressedByID.delete(i.pointerId)),!1}sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let i=0;i<e.length;i++){const n=e[i],s=n.object;if(s.material&&s.material.depthTest===!1){this._noDepthTestingResults.push(n);continue}this._sortingBuffer.push(n)}for(const i of this._sortingBuffer)this._noDepthTestingResults.push(i);return this._noDepthTestingResults}handleEventOnObject(e,i){if(!this.testIsVisible(e))return i.isClick&&to&&console.log("not allowed",e),!1;if(i.pointerId===void 0)return to&&console.error("Event without pointer can't be handled",i),!1;i.object=e;const n=e.parent,s=i.isClick??!1;let a=null;if(n&&n.isUI){const f=(i.isPressed||i.isClick)??!1;if(n[Si]){const p=n[Si].gameObject;if(p){if(!kg.isInteractable(p,this.out))return!1;a=this.out.canvasGroup??null,this.handleMeshUIIntersection(e,f),e=p}}}s&&to&&console.log(this.context.time.frame,e);const l=this.hoveredByID.get(i.pointerId),c=l==null?void 0:l.obj;c!==e&&c&&this.propagatePointerExit(c,l.data,e);const u=this.hoveredByID.get(i.pointerId);if(u?(u.obj=e,u.data=i):this.hoveredByID.set(i.pointerId,{obj:e,data:i}),i.isDown){const f=this.pressedByID.get(i.pointerId);f?(f.obj=e,f.data=i):this.pressedByID.set(i.pointerId,{obj:e,data:i,handlers:new Set})}return(a===null||a.interactable)&&this.handleMainInteraction(e,i,c??null),!0}propagate(e,i){for(;e;)C.foreachComponent(e,n=>{i(n)},!1),e=e.parent}handleMainInteraction(e,i,n){const s=this.pressedByID.get(i.pointerId),a=n!==e;let l=!0;switch(i.event.pointerType){case"mouse":case"touch":const c=this.context.input.getPointerPositionLastFrame(i.pointerId),h=this.context.input.getPointerPosition(i.pointerId);l=c&&!z.approximately(c,h);break}this.propagate(e,c=>{var u;const h=c;h.interactable!==!1&&(!h.activeAndEnabled||!h.enabled||(h.onPointerEnter&&a&&this.handlePointerEnter(h,i),i.isDown&&h.onPointerDown&&(h.onPointerDown(i),s==null||s.handlers.add(h),this.handlePointerCapture(i,h)),h.onPointerMove&&(l&&h.onPointerMove(i),this.handlePointerCapture(i,h)),i.isUp&&(h.onPointerUp&&(this.invokeOnPointerUp(i,h),s==null||s.handlers.delete(h)),h.onPointerExit&&((u=i.event)==null?void 0:u.pointerType)===zu.Touch&&(this.handlePointerExit(h,i),this.hoveredByID.delete(i.pointerId))),i.isClick&&h.onPointerClick&&h.onPointerClick(i)))}),i.isUp&&(s==null||s.handlers.forEach(c=>{this.invokeOnPointerUp(i,c)}),this.pressedByID.delete(i.pointerId))}propagatePointerExit(e,i,n){this.propagate(e,s=>{if(!s.gameObject||s.destroyed)return;const a=s;if(a.onPointerExit||a.onPointerEnter){if(n&&this.isChild(n,s.gameObject))return;this.handlePointerExit(a,i)}})}invokeOnPointerUp(e,i){var n;(n=i.onPointerUp)==null||n.call(i,e),this.releasePointerCapture(e,i)}handlePointerEnter(e,i){e.onPointerEnter&&this.updatePointerState(e,i.pointerId,this.pointerEnterSymbol,!0)&&e.onPointerEnter(i),this.updatePointerState(e,i.pointerId,this.pointerExitSymbol,!1)}handlePointerExit(e,i){e.onPointerExit&&this.updatePointerState(e,i.pointerId,this.pointerExitSymbol,!0)&&e.onPointerExit(i),this.updatePointerState(e,i.pointerId,this.pointerEnterSymbol,!1)}updatePointerState(e,i,n,s){let a=e[n];if(s)return a&&a.includes(i)?!1:(a=a||[],a.push(i),e[n]=a,!0);{if(!a||!a.includes(i))return!1;const l=a.indexOf(i);return l!==-1&&a.splice(l,1),!0}}handlePointerCapture(e,i){if(e.z__pointer_ctured){e.z__pointer_ctured=!1;const n=e.pointerId;if(i.onPointerMove){const s=this._capturedPointer[n]||[];s.push(i),this._capturedPointer[n]=s}else j()&&!i.z__warned_no_pointermove&&(i.z__warned_no_pointermove=!0,console.warn("PointerCapture was requested but the component doesn't implement onPointerMove. It will not receive any pointer events"))}else e.z__pointer_cture_rleased&&(e.z__pointer_cture_rleased=!1,this.releasePointerCapture(e,i))}releasePointerCapture(e,i){const n=e.pointerId;if(this._capturedPointer[n]){const s=this._capturedPointer[n].indexOf(i);s!==-1&&(this._capturedPointer[n].splice(s,1),to&&console.log("released pointer capture",n,i,this._capturedPointer))}}invokePointerCapture(e){var i;if(e.event.type===Re.PointerMove){const n=e.pointerId,s=this._capturedPointer[n];if(s){to&&console.log("Captured",n,s);for(let a=0;a<s.length;a++){const l=s[a];if(l.destroyed){s.splice(a,1),a--;continue}(i=l.onPointerMove)==null||i.call(l,e)}}}}isChild(e,i){return!e||!i?!1:e===i?!0:e.parent?this.isChild(e.parent,i):!1}handleMeshUiObjectWithoutShadowDom(e,i){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,i)}handleMeshUIIntersection(e,i){const n=fo.updateState(e,i);return n&&this.currentActiveMeshUIComponents.push(n),n!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&fo.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){const i=this.currentActiveMeshUIComponents[e];fo.resetState(i)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?C.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}}class fo{static markDirty(){this.needsUpdate=!0}static update(t,e,i=!1){if(i){t.update();return}const n=e.time.frameCount;for(const s of this.lastUpdateFrame)if(s.context===e){if(n===s.frame)return;s.frame=n;let a=this.needsUpdate||n<1;s.nextUpdate<=n&&(a=!0),a&&(to&&console.log("Update threemeshui"),this.needsUpdate=!1,s.nextUpdate=n+60,t.update());return}this.lastUpdateFrame=[{context:e,frame:n,nextUpdate:n+60}],t.update(),this.needsUpdate=!1}static updateState(t,e){let i=null;if(t&&(i=this.findBlockOrTextInParent(t),i&&i!==this.lastSelected)){if(i.interactable===!1)return null;this.needsUpdate=!0}return i}static resetLastSelected(){const t=this.lastSelected;t&&(this.lastSelected=null,this.resetState(t))}static resetState(t){t&&(this.needsUpdate=!0)}static findBlockOrTextInParent(t){return t?t.isBlock||t.isText?t:this.findBlockOrTextInParent(t.parent):null}}r(fo,"lastSelected",null),r(fo,"lastUpdateFrame",[]),r(fo,"needsUpdate",!1);var qP=Object.defineProperty,Te=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&qP(t,e,n),n};const Ui=S("debugorbit"),lp=S("freecam"),El=S("debugcamerafit"),cd=S("smoothcam"),XP={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let cp;class Bc extends CustomEvent{constructor(t,e){super("target-reached",{detail:{controls:t,type:e}})}}class ge extends D{constructor(){super(...arguments);r(this,"autoTarget",!0);r(this,"autoFit",!1);r(this,"enableRotate",!0);r(this,"autoRotate",!1);r(this,"autoRotateSpeed",1);r(this,"minAzimuthAngle",1/0);r(this,"maxAzimuthAngle",1/0);r(this,"minPolarAngle",0);r(this,"maxPolarAngle",Math.PI);r(this,"enableKeys",!1);r(this,"enableDamping",!0);r(this,"dampingFactor",.1);r(this,"enableZoom",!0);r(this,"minZoom",0);r(this,"maxZoom",1/0);r(this,"zoomSpeed",1);r(this,"zoomToCursor",!1);r(this,"enablePan",!0);r(this,"lookAtConstraint",null);r(this,"lookAtConstraint01",1);r(this,"allowInterrupt",!0);r(this,"middleClickToFocus",!0);r(this,"doubleClickToFocus",!0);r(this,"clickBackgroundToFitScene",2);r(this,"debugLog",!1);r(this,"targetLerpDuration",1);r(this,"_controls",null);r(this,"_cameraObject",null);r(this,"_lookTargetLerpActive",!1);r(this,"_lookTargetStartPosition",new d.Vector3);r(this,"_lookTargetEndPosition",new d.Vector3);r(this,"_lookTargetLerp01",0);r(this,"_lookTargetLerpDuration",0);r(this,"_cameraLerpActive",!1);r(this,"_cameraStartPosition",new d.Vector3);r(this,"_cameraEndPosition",new d.Vector3);r(this,"_cameraLerp01",0);r(this,"_cameraLerpDuration",0);r(this,"_fovLerpActive",!1);r(this,"_fovLerpStartValue",0);r(this,"_fovLerpEndValue",0);r(this,"_fovLerp01",0);r(this,"_fovLerpDuration",0);r(this,"_inputs",0);r(this,"_enableTime",0);r(this,"_startedListeningToKeyEvents",!1);r(this,"_eventSystem");r(this,"_afterHandleInputFn");r(this,"_camera",null);r(this,"_syncedTransform");r(this,"_didSetTarget",0);r(this,"targetElement",null);r(this,"_activePointerEvents");r(this,"_lastTimeClickOnBackground",-1);r(this,"_clickOnBackgroundCount",0);r(this,"_onPointerDown",e=>{this._activePointerEvents.push(e)});r(this,"_onPointerDownLate",e=>{e.used&&this._controls&&(this._controls.enabled=!1)});r(this,"_onPointerUp",e=>{for(let i=this._activePointerEvents.length-1;i>=0;i--){const n=this._activePointerEvents[i];if(n.pointerId===e.pointerId&&n.button===e.button){this._activePointerEvents.splice(i,1);break}}if(this.clickBackgroundToFitScene>0&&e.isClick&&e.button===0){if(e.hasRay||e.intersections.push(...this.context.physics.raycast()),e.intersections.length<=0){const i=this.context.time.time-this._lastTimeClickOnBackground;this._lastTimeClickOnBackground=this.context.time.time,this.clickBackgroundToFitScene<=1||i<this.clickBackgroundToFitScene*.15?(this._clickOnBackgroundCount+=1,this._clickOnBackgroundCount>=this.clickBackgroundToFitScene-1&&this.fitCamera(this.context.scene.children,{immediate:!1})):this._clickOnBackgroundCount=0}Ui&&console.log(this.clickBackgroundToFitScene,e.intersections.length,this._clickOnBackgroundCount)}});r(this,"_onPointerUpLate",e=>{this.doubleClickToFocus&&e.isDoubleClick&&!e.used&&this.setTargetFromRaycast()});r(this,"_orbitStartAngle",0);r(this,"onControlsChangeStarted",()=>{this._controls&&(this._orbitStartAngle=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle()),this._syncedTransform&&this._syncedTransform.requestOwnership()});r(this,"onControlsChangeEnded",()=>{if(this._controls&&this.autoTarget){const i=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle()-this._orbitStartAngle;Math.abs(i)<.01?(Ui&&console.debug("OrbitControls: No movement detected, updating target now"),this.updateTargetNow()):Ui&&console.debug("OrbitControls: Movement detected",i)}});r(this,"_shouldDisable",!1);r(this,"__onPreRender",()=>{const e=this.context.pre_render_callbacks.indexOf(this.__onPreRender);e>=0&&this.context.pre_render_callbacks.splice(e,1),this.autoFit&&(this.autoFit=!1,this.fitCamera({centerCamera:"y",immediate:!0,objects:this.scene.children}))});r(this,"_haveAttachedKeyboardEvents",!1)}get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){var i;(i=this.controls)==null||i.addEventListener("start",e)}get targetLerpSpeed(){return 5}set targetLerpSpeed(e){this.targetLerpDuration=1/e}awake(){Ui&&console.debug("OrbitControls",this),this._didSetTarget=0,this._startedListeningToKeyEvents=!1}start(){this._eventSystem=Qt.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(Sm.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){var e,i;(e=this._controls)==null||e.dispose(),(i=this._eventSystem)==null||i.removeEventListener(Sm.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._didSetTarget=0,this._enableTime=this.context.time.time;const e=C.getComponent(this.gameObject,ri);this._camera=e;let i=e==null?void 0:e.threeCamera;if(!i&&this.gameObject instanceof d.PerspectiveCamera&&(i=this.gameObject),i&&Kp(i,this,!0),!this._controls&&i instanceof d.Object3D){this._cameraObject=i;const n=this.targetElement??this.context.renderer.domElement,s=i==null?void 0:i.quaternion.clone();this._controls=new G.OrbitControls(i,n),i==null||i.quaternion.copy(s),cp===void 0&&(cp={...this._controls.keys});const a=Q(i),l=this.gameObject.worldForward,h=a.clone().sub(l.multiplyScalar(2.5));this._controls.target.copy(h)}if(this._controls)if(lp&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,exports.DeviceUtilities.isMobileDevice()&&(this.doubleClickToFocus=!0)),this._controls.addEventListener("start",this.onControlsChangeStarted),this._controls.addEventListener("end",this.onControlsChangeEnded),!this._startedListeningToKeyEvents&&this.enableKeys)this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(this.context.domElement);else try{this._controls.stopListenToKeyEvents()}catch{}this._syncedTransform=C.getComponent(this.gameObject,es)??void 0,this.context.pre_render_callbacks.push(this.__onPreRender),this._activePointerEvents=[],this.context.input.addEventListener("pointerdown",this._onPointerDown,{queue:oi.Early}),this.context.input.addEventListener("pointerdown",this._onPointerDownLate,{queue:oi.Late}),this.context.input.addEventListener("pointerup",this._onPointerUp,{queue:oi.Early}),this.context.input.addEventListener("pointerup",this._onPointerUpLate,{queue:oi.Late})}onDisable(){var e;if((e=this._camera)!=null&&e.threeCamera&&Kp(this._camera.threeCamera,this,!1),this._controls){this._controls.enabled=!1,this._controls.autoRotate=!1,this._controls.removeEventListener("start",this.onControlsChangeStarted),this._controls.removeEventListener("end",this.onControlsChangeEnded);try{this._controls.stopListenToKeyEvents()}catch{}this._startedListeningToKeyEvents=!1}this._activePointerEvents.length=0,this.context.input.removeEventListener("pointerdown",this._onPointerDown),this.context.input.removeEventListener("pointerdown",this._onPointerDownLate),this.context.input.removeEventListener("pointerup",this._onPointerUp),this.context.input.removeEventListener("pointerup",this._onPointerUpLate)}updateTargetNow(){var s,a,l;const e=new d.Ray((s=this._cameraObject)==null?void 0:s.worldPosition,(a=this._cameraObject)==null?void 0:a.worldForward.multiplyScalar(-1)),i=this.context.physics.raycastFromRay(e),n=i.length>0?i[0]:void 0;n&&n.distance>this.minZoom&&n.distance<this.maxZoom&&(Ui&&V.DrawWireSphere(n.point,.1,16711680,2),(l=this._controls)==null||l.target.copy(i[0].point))}afterHandleInput(e){e.detail.args.pointerId===0&&(e.detail.args.isDown?this._controls&&this._eventSystem&&(this._shouldDisable=this._eventSystem.hasActiveUI):(!e.detail.args.isPressed||e.detail.args.isUp)&&(this._shouldDisable=!1))}onBeforeRender(){var i,n,s,a;if(!this._controls)return;if(this._cameraObject!==this.context.mainCamera){this._controls.enabled=!1;return}if(this._controls.enabled=!0,(this.context.input.getPointerDown(1)||this.context.input.getPointerDown(2)||this.context.input.mouseWheelChanged||this.context.input.getPointerPressed(0)&&((i=this.context.input.getPointerPositionDelta(0))!=null&&i.length()))&&(this._inputs+=1),this._inputs>0&&this.allowInterrupt&&(this.enableRotate&&(this.autoRotate=!1),this._cameraLerpActive=!1,this._lookTargetLerpActive=!1),this._inputs=0,this.autoTarget&&this._didSetTarget++===0){const l=C.getComponent(this.gameObject,ri);if(l&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log("NO TARGET");const c=Q(l.threeCamera),h=Math.max(.01,c.length()),u=new d.Vector3(0,0,-h).applyMatrix4(l.threeCamera.matrixWorld);Ui&&V.DrawLine(c,u,5592575,10),this.setLookTargetPosition(u,!0)}if(!this.setLookTargetFromConstraint()){const c=new Jn;c.screenPoint=new d.Vector2(0,0),c.lineThreshold=.1;const h=this.context.physics.raycast(c);h.length>0&&this.setLookTargetPosition(h[0].point,!0),El&&console.log("OrbitControls hits",...h)}}if(this.middleClickToFocus&&this.context.input.getPointerClicked(1)&&this.setTargetFromRaycast(),this._lookTargetLerpActive||this._cameraLerpActive||this._fovLerpActive){if(this._cameraLerpActive&&this._cameraObject)if(this._cameraLerp01+=this.context.time.deltaTime/this._cameraLerpDuration,this._cameraLerp01>=1)this._cameraObject.position.copy(this._cameraEndPosition),this._cameraLerpActive=!1,this.dispatchEvent(new Bc(this,"camera"));else{const l=z.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,l)}if(this._lookTargetLerpActive)if(this._lookTargetLerp01+=this.context.time.deltaTime/this._lookTargetLerpDuration,this._lookTargetLerp01>=1)this._controls.target.copy(this._lookTargetEndPosition),this._lookTargetLerpActive=!1,this.dispatchEvent(new Bc(this,"lookat"));else{const l=z.easeInOutCubic(this._lookTargetLerp01);this._controls.target.lerpVectors(this._lookTargetStartPosition,this._lookTargetEndPosition,l)}if(this._fovLerpActive&&this._cameraObject){const l=this._cameraObject;if(this._fovLerp01+=this.context.time.deltaTime/this._fovLerpDuration,this._fovLerp01>=1)l.fov=this._fovLerpEndValue,this._fovLerpActive=!1;else{const c=z.easeInOutCubic(this._fovLerp01);l.fov=z.lerp(this._fovLerpStartValue,this._fovLerpEndValue,c)}l.updateProjectionMatrix()}}if(this._controls){if(this.debugLog&&(this._controls.domElement=this.context.renderer.domElement),this._controls.enabled=!this._shouldDisable&&this._camera===this.context.mainCameraComponent&&!this.context.isInXR&&!this._activePointerEvents.some(l=>l.used),this._controls.keys=this.enableKeys?cp:XP,this._controls.autoRotate=this.autoRotate,this._controls.autoRotateSpeed=this.autoRotateSpeed,this._controls.enableZoom=this.enableZoom,this._controls.zoomSpeed=this.zoomSpeed,this._controls.zoomToCursor=this.zoomToCursor,this._controls.enableDamping=this.enableDamping,this._controls.dampingFactor=this.dampingFactor,this._controls.enablePan=this.enablePan,this._controls.enableRotate=this.enableRotate,this._controls.minAzimuthAngle=this.minAzimuthAngle,this._controls.maxAzimuthAngle=this.maxAzimuthAngle,this._controls.minPolarAngle=this.minPolarAngle,this._controls.maxPolarAngle=this.maxPolarAngle,lp||(((s=(n=this._camera)==null?void 0:n.threeCamera)==null?void 0:s.type)==="PerspectiveCamera"?(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom,this._controls.minZoom=0,this._controls.maxZoom=1/0):(this._controls.minDistance=0,this._controls.maxDistance=1/0,this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom)),typeof cd=="number"||cd===!0){this._controls.enableDamping=!0;const l=typeof cd=="number"?cd:.99;this._controls.dampingFactor=Math.max(.001,1-Math.min(1,l))}this.allowInterrupt||(this._lookTargetLerpActive&&(this._controls.enablePan=!1),this._cameraLerpActive&&(this._controls.enableRotate=!1,this._controls.autoRotate=!1),(this._lookTargetLerpActive||this._cameraLerpActive)&&(this._controls.enableZoom=!1)),this.context.isInXR||(!lp&&((a=this.lookAtConstraint)!=null&&a.locked)&&this.setLookTargetFromConstraint(0,this.lookAtConstraint01),this._controls.update(this.context.time.deltaTime),Ui&&V.DrawWireSphere(this._controls.target,.1,65280))}}setCameraAndLookTarget(e,i=!1){if(!e)return(j()||Ui)&&console.warn("[OrbitControls] setCameraAndLookTarget target is null"),!1;if(!(e instanceof d.Object3D)&&!(e instanceof ri))return(j()||Ui)&&console.warn("[OrbitControls] setCameraAndLookTarget target is not an Object3D or Camera"),!1;e instanceof ri&&(e=e.gameObject);const n=e.worldPosition,s=e.worldForward;e instanceof d.Camera&&(Ui&&console.debug("[OrbitControls] setCameraAndLookTarget flip forward direction for camera"),s.multiplyScalar(-1));const a=new d.Ray(n,s);return Ui&&V.DrawRay(a.origin,a.direction,16711680,10),this.setTargetFromRaycast(a,i)||this.setLookTargetPosition(a.at(2,$()),i),this.setCameraTargetPosition(n,i),!0}setCameraTargetPosition(e,i=!1){var n;e&&(e instanceof d.Object3D&&(e=Q(e)),this._cameraEndPosition||(this._cameraEndPosition=new d.Vector3),this._cameraEndPosition.copy(e),i===!0?(this._cameraLerpActive=!1,this._cameraObject&&this._cameraObject.position.copy(this._cameraEndPosition)):this._cameraObject&&(this._cameraLerpActive=!0,this._cameraLerp01=0,this._cameraStartPosition.copy((n=this._cameraObject)==null?void 0:n.position),typeof i=="number"?this._cameraLerpDuration=i:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setFieldOfView(e,i=!1){var s;if(!this._controls||typeof e!="number")return;const n=(s=this._camera)==null?void 0:s.threeCamera;n&&(i===!0?n.fov=e:(this._fovLerpActive=!0,this._fovLerp01=0,this._fovLerpStartValue=n.fov,this._fovLerpEndValue=e,typeof i=="number"?this._fovLerpDuration=i:this._fovLerpDuration=this.targetLerpDuration))}setLookTargetPosition(e=null,i=!1){this._controls&&e&&(e instanceof d.Object3D&&(e=Q(e)),this._lookTargetEndPosition.copy(e),this._didSetTarget++,Ui&&(console.warn("OrbitControls: setLookTargetPosition",e,i),V.DrawWireSphere(this._lookTargetEndPosition,.2,16711680,2)),i===!0?this._controls.target.copy(this._lookTargetEndPosition):(this._lookTargetLerpActive=!0,this._lookTargetLerp01=0,this._lookTargetStartPosition.copy(this._controls.target),typeof i=="number"?this._lookTargetLerpDuration=i:this._lookTargetLerpDuration=this.targetLerpDuration))}get lookTargetLerpActive(){return this._lookTargetLerpActive}stopLookTargetLerp(){this._lookTargetLerpActive=!1}setLookTargetFromConstraint(e=0,i=1){var s,a;if(!this._controls||((s=this.lookAtConstraint)==null?void 0:s.enabled)===!1)return!1;const n=(a=this.lookAtConstraint)==null?void 0:a.sources;if(n&&n.length>0){const l=n[e];if(l)return l.getWorldPosition(this._lookTargetEndPosition),this.lerpLookTarget(this._lookTargetEndPosition,i),!0}return!1}lerpTarget(e,i){return this.lerpLookTarget(e,i)}lerpLookTarget(e,i){this._controls&&(i>=1?this._controls.target.copy(e):this._controls.target.lerp(e,i))}setTargetFromRaycast(e,i=!1){if(!this.controls)return!1;const n=e?this.context.physics.raycastFromRay(e):this.context.physics.raycast();for(const s of n)if(s.distance>0&&C.isActiveInHierarchy(s.object)){const a=Rg(s.object);if(a){const l=a.canvas;if(l!=null&&l.screenspace)break}return this.setLookTargetPosition(s.point,i),!0}return!1}fitCamera(e,i){var H,B;if(this.context.isInXR)return;let n;if(Array.isArray(e)?n=e:e&&"type"in e?n=e.children:e&&typeof e=="object"&&!(e instanceof d.Object3D)&&!Array.isArray(e)&&(i=e,n=i.objects),n&&!Array.isArray(n)&&(n=n.children),(!Array.isArray(n)||n&&n.length<=0)&&(n=this.context.scene.children),!Array.isArray(n)||n.length<=0){console.warn("No objects to fit camera to...");return}const s=this._cameraObject,a=this._controls;if(!s||!a){console.warn("No camera or controls found to fit camera to objects...");return}i||(i={});const{immediate:l=!1,centerCamera:c="y",cameraNearFar:h="auto",fitOffset:u=1.1,fov:f=s==null?void 0:s.fov}=i,p=new d.Vector3,g=new d.Vector3,y=li(n,void 0,(B=(H=this._camera)==null?void 0:H.threeCamera)==null?void 0:B.layers),b=y.clone();s.updateMatrixWorld(),s.updateProjectionMatrix(),y.getCenter(g);const _=new d.Vector3;if(y.getSize(_),y.applyMatrix4(s.matrixWorldInverse),y.getSize(p),y.setFromCenterAndSize(g,p),Number.isNaN(p.x)||Number.isNaN(p.y)||Number.isNaN(p.z)){console.warn("Camera fit size resultet in NaN",s,y,[...n]);return}if(p.length()<=1e-10){El&&console.warn("Camera fit size is zero",y,[...n]);return}const v=i.fov||s.fov,w=2*Math.atan(Math.tan(v*Math.PI/360/2)*s.aspect)/Math.PI*360,x=p.y/(2*Math.atan(Math.PI*v/360)),O=p.x/(2*Math.atan(Math.PI*w/360)),M=u*Math.max(x,O)+p.z/2;El&&console.log("Fit camera to objects",{fitHeightDistance:x,fitWidthDistance:O,distance:M,verticalFov:v,horizontalFov:w}),this.maxZoom=M*10,this.minZoom=M*.01;const R=.05,E=g.clone();if(E.y-=p.y*R,this.setLookTargetPosition(E,l),this.setFieldOfView(i.fov,l),h==null||h=="auto"){const I=C.findObjectOfType(ss),N=I?I.radius:0,Y=Math.max(_.x,_.y,_.z,N);s.near=M/100,s.far=Y+M*10,I&&(this.maxZoom=Math.max(Math.min(this.maxZoom,N*.5),M))}const F=a.getDistance();F<this.minZoom&&(this.minZoom=F*.9),F>this.maxZoom&&(this.maxZoom=F*1.1),s.updateMatrixWorld(),s.updateProjectionMatrix();const T=Q(s),L=g.clone();L.sub(T),c==="y"&&(L.y=0),L.normalize(),L.multiplyScalar(M),c==="y"&&(L.y+=-R*4*M);let A=g.clone().sub(L);s.parent&&(A=s.parent.worldToLocal(A)),this.setCameraTargetPosition(A,l),(El||i.debug)&&(V.DrawWireBox3(y,16777011,10),V.DrawWireBox3(b,65280,10),!this._haveAttachedKeyboardEvents&&El&&(this._haveAttachedKeyboardEvents=!0,document.body.addEventListener("keydown",I=>{if(I.code==="KeyF"){let N;this._cameraObject instanceof d.PerspectiveCamera&&(N=Math.random()*Math.random()*170+10),this.fitCamera({objects:n,fitOffset:u,immediate:!1,fov:N})}I.code==="KeyV"&&this._cameraObject instanceof d.PerspectiveCamera&&(this._cameraObject.fov=60)}))),this.onBeforeRender()}}Te([m()],ge.prototype,"autoTarget");Te([m()],ge.prototype,"autoFit");Te([m()],ge.prototype,"enableRotate");Te([m()],ge.prototype,"autoRotate");Te([m()],ge.prototype,"autoRotateSpeed");Te([m()],ge.prototype,"minAzimuthAngle");Te([m()],ge.prototype,"maxAzimuthAngle");Te([m()],ge.prototype,"minPolarAngle");Te([m()],ge.prototype,"maxPolarAngle");Te([m()],ge.prototype,"enableKeys");Te([m()],ge.prototype,"enableDamping");Te([m()],ge.prototype,"dampingFactor");Te([m()],ge.prototype,"enableZoom");Te([m()],ge.prototype,"minZoom");Te([m()],ge.prototype,"maxZoom");Te([m()],ge.prototype,"zoomSpeed");Te([m()],ge.prototype,"enablePan");Te([m(Ur)],ge.prototype,"lookAtConstraint");Te([m()],ge.prototype,"lookAtConstraint01");Te([m()],ge.prototype,"allowInterrupt");Te([m()],ge.prototype,"middleClickToFocus");Te([m()],ge.prototype,"doubleClickToFocus");Te([m()],ge.prototype,"clickBackgroundToFitScene");Te([m()],ge.prototype,"targetLerpDuration");var QP=Object.defineProperty,YP=Object.getOwnPropertyDescriptor,Kt=(o,t,e,i)=>{for(var n=i>1?void 0:i?YP(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&QP(t,e,n),n},Co=(o=>(o[o.None=0]="None",o[o.Skybox=1]="Skybox",o[o.SolidColor=2]="SolidColor",o[o.Uninitialized=4]="Uninitialized",o))(Co||{});const io=S("debugcam"),ab=S("debugscreenpointtoray");var pn;const Lt=(pn=class extends D{constructor(){super(...arguments);r(this,"_nearClipPlane",.1);r(this,"_farClipPlane",1e3);r(this,"orthographic",!1);r(this,"orthographicSize",5);r(this,"ARBackgroundAlpha",0);r(this,"_cullingMask",4294967295);r(this,"_backgroundBlurriness");r(this,"_backgroundIntensity");r(this,"_backgroundRotation");r(this,"_environmentIntensity");r(this,"_targetTexture",null);r(this,"_backgroundColor");r(this,"_fov");r(this,"_cam",null);r(this,"_clearFlags",2);r(this,"_skybox");r(this,"_frustum");r(this,"_projScreenMatrix",new d.Matrix4)}get isCamera(){return!0}get aspect(){return this._cam instanceof d.PerspectiveCamera?this._cam.aspect:this.context.domWidth/this.context.domHeight}set aspect(e){this._cam instanceof d.PerspectiveCamera&&this._cam.aspect!==e&&(this._cam.aspect=e,this._cam.updateProjectionMatrix())}get fieldOfView(){return this._cam instanceof d.PerspectiveCamera?this._cam.fov:this._fov}set fieldOfView(e){const i=this.fieldOfView!=e;if(this._fov=e,i&&this._cam&&this._cam instanceof d.PerspectiveCamera){if(this._fov===void 0){console.warn("Can not set undefined fov on PerspectiveCamera");return}this._cam.fov=this._fov,this._cam.updateProjectionMatrix()}}get nearClipPlane(){return this._nearClipPlane}set nearClipPlane(e){const i=this._nearClipPlane!=e;this._nearClipPlane=e,this._cam&&(i||this._cam.near!=e)&&(this._cam.near=e,this._cam.updateProjectionMatrix())}get farClipPlane(){return this._farClipPlane}set farClipPlane(e){const i=this._farClipPlane!=e;this._farClipPlane=e,this._cam&&(i||this._cam.far!=e)&&(this._cam.far=e,this._cam.updateProjectionMatrix())}applyClippingPlane(){this._cam&&(this._cam.near=this._nearClipPlane,this._cam.far=this._farClipPlane,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(e){if(typeof e=="string")switch(e){case"skybox":e=1;break;case"solidcolor":e=2;break;default:e=0;break}e!==this._clearFlags&&(this._clearFlags=e,this.applyClearFlagsIfIsActiveCamera())}set cullingMask(e){this._cullingMask=e,this._cam&&(this._cam.layers.mask=e)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}set cullingLayer(e){this.cullingMask=(1<<e|0)>>>0}set backgroundBlurriness(e){e!==this._backgroundBlurriness&&(e===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(e,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}set backgroundIntensity(e){e!==this._backgroundIntensity&&(e===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(e,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}set backgroundRotation(e){e!==this._backgroundRotation&&(e===void 0?this._backgroundRotation=void 0:this._backgroundRotation=e,this.applyClearFlagsIfIsActiveCamera())}get backgroundRotation(){return this._backgroundRotation}set environmentIntensity(e){this._environmentIntensity=e}get environmentIntensity(){return this._environmentIntensity}get backgroundColor(){return this._backgroundColor??null}set backgroundColor(e){e&&(this._backgroundColor||(this._backgroundColor=new ie(1,1,1,1)),this._backgroundColor.copy(e),(!("alpha"in e)||e.alpha===void 0)&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera())}set targetTexture(e){this._targetTexture=e}get targetTexture(){return this._targetTexture}get cam(){return this.threeCamera}get threeCamera(){return this.activeAndEnabled&&this.buildCamera(),this._cam}screenPointToRay(e,i,n){const s=this.threeCamera,a=pn._origin;a.set(e,i,-1),this.context.input.convertScreenspaceToRaycastSpace(a),ab&&console.log("screenPointToRay",e.toFixed(2),i.toFixed(2),"now:",a.x.toFixed(2),a.y.toFixed(2),"isInXR:"+this.context.isInXR),a.z=-1,a.unproject(s);const l=pn._direction.set(a.x,a.y,a.z),c=Q(s);return l.sub(c),l.normalize(),n?(n.set(c,l),n):new d.Ray(c.clone(),l.clone())}getFrustum(){return this._frustum||(this._frustum=new d.Frustum,this.updateFrustum()),this._frustum}updateFrustum(){this._frustum||(this._frustum=new d.Frustum),this._frustum.setFromProjectionMatrix(this.getProjectionScreenMatrix(this._projScreenMatrix,!0),this.context.renderer.coordinateSystem)}getProjectionScreenMatrix(e,i){return i&&this._projScreenMatrix.multiplyMatrices(this.threeCamera.projectionMatrix,this.threeCamera.matrixWorldInverse),e===this._projScreenMatrix?e:e.copy(this._projScreenMatrix)}awake(){ab&&window.addEventListener("pointerdown",e=>{const i=e.clientX,n=e.clientY;console.log("touch",i.toFixed(2),n.toFixed(2));const s=this.screenPointToRay(i,n),a="#"+Math.floor(Math.random()*16777215).toString(16);V.DrawRay(s.origin,s.direction,a,10)})}onEnable(){io&&console.log(`Camera enabled: "${this.name}". ClearFlags=${Co[this._clearFlags]}`,this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),ZP(this)),this.applyClearFlagsIfIsActiveCamera({applySkybox:!0})}onDisable(){this.context.removeCamera(this)}onBeforeRender(){if(this._cam&&(this._frustum&&this.updateFrustum(),this._clearFlags===2&&this.applyClearFlagsIfIsActiveCamera(),this._targetTexture)){this.context.isManagedExternally&&(this._warnedAboutExternalRenderer||(this._warnedAboutExternalRenderer=!0,console.warn("Rendering with external renderer is not supported yet. This may not work or throw errors. Please remove the the target texture from your camera: "+this.name,this.targetTexture))),this.context.composer;const e=this.context.renderer;if(e){const i=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,e),i==null||i.applyClearFlags()}}}buildCamera(){if(this._cam)return;const e=this.gameObject.isCamera;let i=null;if(e?(i=this.gameObject,i==null||i.layers.enableAll(),i instanceof d.PerspectiveCamera&&(this._fov=i.fov)):i=this.gameObject.children[0],i&&i.isCamera)i instanceof d.PerspectiveCamera&&(this._fov&&(i.fov=this._fov),i.near=this._nearClipPlane,i.far=this._farClipPlane,i.updateProjectionMatrix());else if(!this.orthographic)i=new d.PerspectiveCamera(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(i.fov=this.fieldOfView),this.gameObject.add(i);else{const n=this.orthographicSize*100;i=new d.OrthographicCamera(window.innerWidth/-n,window.innerWidth/n,window.innerHeight/n,window.innerHeight/-n,this._nearClipPlane,this._farClipPlane),this.gameObject.add(i)}this._cam=i,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(e){this.context.mainCameraComponent===this&&this.applyClearFlags(e)}applyClearFlags(e){var n;if(!this._cam){io&&console.log("Camera does not exist (apply clear flags)");return}if(this.fieldOfView=this._fov,io){const s=`[Camera] Apply ClearFlags: ${Co[this._clearFlags]} - "${this.name}"`;console.debug(s)}const i=this.context.domElement.getAttribute("background-image")||this.context.domElement.getAttribute("background-color");switch(this._clearFlags){case 0:return;case 1:if(pn.backgroundShouldBeTransparent(this.context)&&(!this.ARBackgroundAlpha||this.ARBackgroundAlpha<.001)){this.context.scene.background=null,this.context.renderer.setClearColor(0,0);return}(!this.scene.background||!this._skybox||(e==null?void 0:e.applySkybox)===!0)&&this.applySceneSkybox(),this._backgroundBlurriness!==void 0&&!this.context.domElement.getAttribute("background-blurriness")?this.context.scene.backgroundBlurriness=this._backgroundBlurriness:io&&console.warn(`Camera "${this.name}" has no background blurriness`),this._backgroundIntensity!==void 0&&!this.context.domElement.getAttribute("background-intensity")&&(this.context.scene.backgroundIntensity=this._backgroundIntensity),this._backgroundRotation!==void 0&&!this.context.domElement.getAttribute("background-rotation")?this.context.scene.backgroundRotation=this._backgroundRotation:io&&console.warn(`Camera "${this.name}" has no background intensity`);break;case 2:if(this._backgroundColor&&!i){let s=this._backgroundColor.alpha;pn.backgroundShouldBeTransparent(this.context)&&(s=this.ARBackgroundAlpha??0),this.context.scene.background=null,(n=this.context.xr)!=null&&n.isVR?this.context.renderer.setClearColor(x0(this._backgroundColor).convertLinearToSRGB()):this.context.renderer.setClearColor(this._backgroundColor,s)}else this._backgroundColor||io&&console.warn(`[Camera] has no background color "${this.name}" `);break;case 4:i||(this.context.scene.background=null,this.context.renderer.setClearColor(0,0));break}}applySceneSkybox(){this._skybox||(this._skybox=new KP(this)),this._skybox.apply()}static backgroundShouldBeTransparent(e){var a,l,c,h;const i=(a=e.renderer.xr)==null?void 0:a.getSession();if(!i)return!1;if(typeof i._transparent=="boolean")return i._transparent;const n=i.environmentBlendMode;io&&Ee("Environment blend mode: "+n+" on "+navigator.userAgent);let s=n==="additive"||n==="alpha-blend";return e.isInAR&&n==="opaque"&&((l=navigator.userAgent)!=null&&l.includes("OculusBrowser")||(c=navigator.userAgent)!=null&&c.includes("Mozilla")&&((h=navigator.userAgent)!=null&&h.includes("Mobile WebXRViewer/v2")))&&(s=!0),i._transparent=s,s}},r(pn,"_origin",new d.Vector3),r(pn,"_direction",new d.Vector3),pn);Kt([m()],Lt.prototype,"aspect",1);Kt([m()],Lt.prototype,"fieldOfView",1);Kt([m()],Lt.prototype,"nearClipPlane",1);Kt([m()],Lt.prototype,"farClipPlane",1);Kt([m()],Lt.prototype,"clearFlags",1);Kt([m()],Lt.prototype,"orthographic",2);Kt([m()],Lt.prototype,"orthographicSize",2);Kt([m()],Lt.prototype,"ARBackgroundAlpha",2);Kt([m()],Lt.prototype,"cullingMask",1);Kt([m()],Lt.prototype,"backgroundBlurriness",1);Kt([m()],Lt.prototype,"backgroundIntensity",1);Kt([m(d.Euler)],Lt.prototype,"backgroundRotation",1);Kt([m()],Lt.prototype,"environmentIntensity",1);Kt([m(ie)],Lt.prototype,"backgroundColor",1);Kt([m(Sr)],Lt.prototype,"targetTexture",1);let ri=Lt;class KP{constructor(t){r(this,"_camera");r(this,"_skybox");this._camera=t}get context(){var t;return(t=this._camera)==null?void 0:t.context}apply(){var t;if(this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),!this._skybox)this._did_log_failed_to_find_skybox||(this._did_log_failed_to_find_skybox=!0,console.warn(`Camera "${this._camera.name}" has no skybox texture. ${this._camera.sourceId}`));else if(this.context.scene.background!==this._skybox){const e=this.context.domElement.getAttribute("background-image")||this.context.domElement.getAttribute("background-color")||this.context.domElement.getAttribute("skybox-image");io&&console.debug(`[Camera] Apply Skybox ${(t=this._skybox)==null?void 0:t.name} ${e} - "${this._camera.name}"`),e!=null&&e.length||(this._skybox.mapping=d.EquirectangularReflectionMapping,this.context.scene.background=this._skybox)}}}function ZP(o){S("freecam")&&o.context.mainCameraComponent===o&&C.getOrAddComponent(o.gameObject,ge)}class Ms extends D{constructor(){super(...arguments);r(this,"_listener",null);r(this,"onInteraction",()=>{this.destroyed||this.listener==null||this.addListenerIfItExists()})}get listener(){return this._listener==null&&(this._listener=new d.AudioListener),this._listener}onEnable(){wn.registerWaitForInteraction(this.onInteraction),this.addListenerIfItExists()}onDisable(){wn.unregisterWaitForInteraction(this.onInteraction),this.removeListenerIfItExists()}addListenerIfItExists(){const e=this._listener;if(!e||e!=null&&e.parent)return;const i=this.context.mainCameraComponent||C.getComponentInParent(this.gameObject,ri);i!=null&&i.threeCamera?i.threeCamera.add(e):this.gameObject.add(e),e.filter?(e.gain.connect(e.filter),e.filter.connect(e.context.destination)):e.gain.connect(e.context.destination)}removeListenerIfItExists(){const e=this._listener;e&&(e.removeFromParent(),e.filter&&e.filter.disconnect(),e.gain&&e.gain.disconnect())}}var JP=Object.defineProperty,eM=Object.getOwnPropertyDescriptor,Cn=(o,t,e,i)=>{for(var n=i>1?void 0:i?eM(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&JP(t,e,n),n};const gt=S("debugaudio"),Zi=class no extends D{constructor(){super(...arguments);r(this,"clip","");r(this,"playOnAwake",!1);r(this,"preload",!0);r(this,"playInBackground",!0);r(this,"_spatialBlend",0);r(this,"_minDistance",1);r(this,"_maxDistance",100);r(this,"_volume",1);r(this,"rollOffMode",0);r(this,"_loop",!1);r(this,"sound",null);r(this,"helper",null);r(this,"wasPlaying",!1);r(this,"audioLoader",null);r(this,"shouldPlay",!1);r(this,"_lastClipStartedLoading",null);r(this,"_audioElement",null);r(this,"onVisibilityChanged",()=>{switch(document.visibilityState){case"hidden":(this.playInBackground===!1||exports.DeviceUtilities.isMobileDevice())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":gt&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,no.userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&no.userInteractionRegistered&&this.wasPlaying&&this.play();break}});r(this,"onApplicationMuteChanged",()=>{var e,i;this.context.application.muted?(e=this.sound)==null||e.setVolume(0):(i=this.sound)==null||i.setVolume(this.volume)});r(this,"createAudio",e=>{if(this.destroyed){gt&&console.warn("AudioSource destroyed, not creating audio",this.name);return}gt&&console.log("AudioBuffer finished loading",e);const i=this.Sound;if(!i){gt&&console.warn("Failed getting sound?",this.name);return}i.isPlaying&&i.stop(),e&&i.setBuffer(e),i.loop=this._loop,this.context.application.muted?i.setVolume(0):i.setVolume(this.volume),i.autoplay=this.shouldPlay&&no.userInteractionRegistered,this.applySpatialDistanceSettings(),i.isPlaying&&i.stop(),no.registerWaitForAllowAudio(this.__onAllowAudioCallback)});r(this,"__onAllowAudioCallback",()=>{this.shouldPlay&&this.play()});r(this,"_lastContextTime",0);r(this,"_hasEnded",!0);r(this,"_needUpdateSpatialDistanceSettings",!1)}static get userInteractionRegistered(){return wn.userInteractionRegistered}static registerWaitForAllowAudio(e){wn.registerWaitForInteraction(e)}get isPlaying(){var e;return((e=this.sound)==null?void 0:e.isPlaying)??!1}get duration(){var e,i;return(i=(e=this.sound)==null?void 0:e.buffer)==null?void 0:i.duration}get time01(){var i;const e=this.duration;return e&&this.sound?((i=this.sound)==null?void 0:i.context.currentTime)/e:0}set time01(e){const i=this.duration;i&&this.sound&&(this.time=e*i)}get time(){var e,i;return(e=this.sound)!=null&&e.source?((i=this.sound.source)==null?void 0:i.context.currentTime)-this._lastContextTime+this.sound.offset:0}set time(e){if(this.sound){if(e===this.sound.offset)return;const i=this.isPlaying;this.stop(),this.sound.offset=e,i&&this.play()}}get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(e){this._loop=e,this.sound&&this.sound.setLoop(e)}get spatialBlend(){return this._spatialBlend}set spatialBlend(e){e!==this._spatialBlend&&(this._spatialBlend=e,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(e){this._minDistance!==e&&(this._minDistance=e,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(e){this._maxDistance!==e&&(this._maxDistance=e,this._needUpdateSpatialDistanceSettings=!0)}get volume(){return this._volume}set volume(e){this._volume=e,this.sound&&!this.context.application.muted&&(gt&&console.log(this.name,"audio set volume",e),this.sound.setVolume(e))}set pitch(e){this.sound&&this.sound.setPlaybackRate(e)}get pitch(){return this.sound?this.sound.getPlaybackRate():1}get Sound(){var e;if(!this.sound&&no.userInteractionRegistered){let i=this.gameObject.getComponent(Ms)??this.context.mainCamera.getComponent(Ms)??ch(Ms,this.context,!1);!i&&this.context.mainCamera&&(i=this.context.mainCamera.addComponent(Ms)),i!=null&&i.listener?(this.sound=new d.PositionalAudio(i.listener),(e=this.gameObject)==null||e.add(this.sound)):gt&&console.warn("No audio listener found in scene - can not play audio")}return this.sound}get ShouldPlay(){return this.shouldPlay}get audioContext(){var e;return(e=this.sound)==null?void 0:e.context}awake(){gt&&console.log("[AudioSource]",this),this.audioLoader=new d.AudioLoader,this.playOnAwake&&(this.shouldPlay=!0),this.preload&&typeof this.clip=="string"&&this.audioLoader.load(this.clip,this.createAudio,()=>{},console.error)}onEnable(){this.sound&&this.gameObject.add(this.sound),no.userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():no.registerWaitForAllowAudio(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.onNewClip(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(im.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(im.MuteChanged,this.onApplicationMuteChanged),this.pause()}applySpatialDistanceSettings(){const e=this.sound;if(!e)return;this._needUpdateSpatialDistanceSettings=!1;const i=z.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(gt&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+i),e.setRefDistance(i),e.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:e.setDistanceModel("exponential");break;case 1:e.setDistanceModel("linear");break;case 2:console.warn("Custom rolloff for AudioSource is not supported: "+this.name);break}this.spatialBlend>0?gt&&!this.helper&&(this.helper=new G.PositionalAudioHelper(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}async onNewClip(e){if(e&&(this.clip=e),typeof e=="string")if(gt&&console.log(e),e.endsWith(".mp3")||e.endsWith(".wav")){if(this.audioLoader||(this.audioLoader=new d.AudioLoader),this.shouldPlay=!0,this._lastClipStartedLoading===e){gt&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=e,gt&&console.log("load audio",e);const i=await this.audioLoader.loadAsync(e).catch(console.error);if(this.destroyed)return;this._lastClipStartedLoading===e&&(this._lastClipStartedLoading=null),i&&this.createAudio(i)}else console.warn("Unsupported audio clip type",e);else this.shouldPlay=!0,this.createAudio()}play(e=void 0){var n,s,a;!e&&this.clip&&(e=this.clip),e!==void 0&&typeof e!="string"&&!(e instanceof MediaStream)&&(j()&&console.warn("Called play on AudioSource with unknown argument type:",e+`
940
940
  Using the assigned clip instead:`,this.clip),e=this.clip);let i=!this.sound||e&&e!==this.clip;if(typeof e=="string"&&!this.audioLoader&&(i=!0),(e instanceof MediaStream||typeof e=="string")&&(this.clip=e),i){this.shouldPlay=!0,this.onNewClip(e);return}if(this.shouldPlay=!0,this._hasEnded=!1,gt&&console.log("play",(n=this.sound)==null?void 0:n.getVolume(),this.sound),this.sound&&!this.sound.isPlaying){const l=this.context.application.muted;l&&this.sound.setVolume(0),(s=this.gameObject)==null||s.add(this.sound),this.clip instanceof MediaStream?(this.sound.setMediaStreamSource(this.clip),this._audioElement||(this._audioElement=document.createElement("audio"),this._audioElement.style.display="none"),this._audioElement.parentNode||(a=this.context.domElement.shadowRoot)==null||a.append(this._audioElement),this._audioElement.srcObject=this.clip,this._audioElement.autoplay=!1):(this._audioElement&&this._audioElement.remove(),this.sound.play(l?.1:0))}}pause(){var e,i;gt&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&this.sound.source&&(this._lastContextTime=(e=this.sound)==null?void 0:e.context.currentTime,this.sound.pause()),(i=this._audioElement)==null||i.remove()}stop(){var e,i;gt&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.source&&(this._lastContextTime=(e=this.sound)==null?void 0:e.context.currentTime,gt&&console.log(this._lastContextTime),this.sound.stop()),(i=this._audioElement)==null||i.remove()}update(){this.helper&&(this.isPlaying&&this.helper.update(),this.helper.visible=this.isPlaying),this._needUpdateSpatialDistanceSettings&&this.applySpatialDistanceSettings(),this.sound&&!this.sound.isPlaying&&this.shouldPlay&&!this._hasEnded&&(this._hasEnded=!0,gt&&console.log("Audio clip ended",this.clip),this.dispatchEvent(new CustomEvent("ended",{detail:this})))}};Cn([m(URL)],Zi.prototype,"clip",2);Cn([m()],Zi.prototype,"playOnAwake",2);Cn([m()],Zi.prototype,"preload",2);Cn([m()],Zi.prototype,"playInBackground",2);Cn([m()],Zi.prototype,"loop",1);Cn([m()],Zi.prototype,"spatialBlend",1);Cn([m()],Zi.prototype,"minDistance",1);Cn([m()],Zi.prototype,"maxDistance",1);Cn([m()],Zi.prototype,"volume",1);Cn([m()],Zi.prototype,"pitch",1);Cn([m()],Zi.prototype,"rollOffMode",2);let qi=Zi;const tM=S("debugavatar"),ni=class ni extends D{constructor(){super(...arguments);r(this,"connectionId");r(this,"avatar")}static getAvatar(e){return e>=0&&e<ni.instances.length?ni.instances[e]:null}static onAvatarMarkerCreated(e){return ni._onNewAvatarMarkerAdded.push(e),e}static onAvatarMarkerDestroyed(e){return ni._onAvatarMarkerDestroyed.push(e),e}awake(){ni.instances.push(this),tM&&console.log(this);for(const e of ni._onNewAvatarMarkerAdded)e({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){ni.instances.splice(ni.instances.indexOf(this),1);for(const e of ni._onAvatarMarkerDestroyed)e({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}};r(ni,"instances",[]),r(ni,"_onNewAvatarMarkerAdded",[]),r(ni,"_onAvatarMarkerDestroyed",[]);let At=ni;class Ts{static Add(t,e,i=null){if(e){for(const n of this.Pois)if(n.obj===e)return;this.Pois.push({obj:e,avatar:i}),this.LastChangeTime=t.time.time}}static Remove(t,e){var i;if(e){for(const n of this.Pois)if(n.obj===e){this.Pois.splice(this.Pois.indexOf(n),1),this.LastChangeTime=(t==null?void 0:t.time.time)??((i=X.Current)==null?void 0:i.time.time);return}}}}r(Ts,"Pois",[]),r(Ts,"LastChangeTime",0);class iM{constructor(){r(this,"guid");r(this,"position",new d.Vector3)}}class Fc extends D{constructor(){super(...arguments);r(this,"target",null);r(this,"avatar",null);r(this,"_model",null);r(this,"_targetModel",new iM);r(this,"_currentTargetObject",null);r(this,"_lastUpdateTime",0);r(this,"_lookDuration",0);r(this,"_lastPoiChangedTime",0)}set controlledTarget(e){this.target=e;const i=k.get("MoveRandom");if(i&&this.target){const n=C.getComponent(this.target,i);n&&n.destroy()}}awake(){if(this.avatar=C.getComponentInParent(this.gameObject,At),this.avatar){const e=C.getComponentInParent(this.gameObject,At);this._model=new lg(this.context.connection,this.guid),e!=null&&e.isLocalAvatar&&this._model.requestOwnership()}this.context.connection.beginListen("avatar-look-target-changed",e=>{var i;this.target&&e&&e.guid===((i=this.avatar)==null?void 0:i.guid)&&st(this.target,e.position)})}update(){var i;if((!this.context.connection.isConnected||(i=this._model)!=null&&i.hasOwnership)&&(Ts.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=Ts.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){const n=Q(this._currentTargetObject);st(this.target,n),this.context.connection.isConnected&&this.avatar&&(this.context.connection.send("avatar-look-target-changed",this._targetModel),this._targetModel.guid=this.avatar.guid,this._targetModel.position.copy(n))}}selectTarget(){if(this.context.time.time-this._lastUpdateTime>this._lookDuration){this._lastUpdateTime=this.context.time.time,this._lookDuration=Math.random()*.5+.2;const i=Ts.Pois;if(i.length>0){const n=i[Math.floor(Math.random()*i.length)];if(n&&n.obj){if(n.avatar&&n.avatar===this.avatar)return;this._currentTargetObject=n.obj}}}}}function uw(o){const t=o;return!!(t.parser&&t.parser.json)}var Ku=(o=>(o[o.None=0]="None",o[o.DontExport=1]="DontExport",o))(Ku||{});function fw(o){return o&&o.isComponent}const nM=Symbol("object"),hp=new ki(()=>new d.Vector3,20);class pw{constructor(t,e,i,n,s,a){r(this,"_point");r(this,"_normal");r(this,"_tangentVelocity");r(this,"distance");r(this,"impulse");r(this,"friction");this._point=t,this.distance=e,this._normal=i,this.impulse=n,this.friction=s,this._tangentVelocity=a}get point(){return hp.get().set(this._point.x,this._point.y,this._point.z)}get normal(){return hp.get().set(this._normal.x,this._normal.y,this._normal.z)}get tangentVelocity(){return hp.get().set(this._tangentVelocity.x,this._tangentVelocity.y,this._tangentVelocity.z)}}class mw{constructor(t,e,i){r(this,"contacts");r(this,"me");r(this,"_collider");r(this,"_gameObject");this.me=t,this._collider=e,this._gameObject=e.gameObject,this.contacts=i}get collider(){return this._collider}get gameObject(){return this._gameObject}get rigidBody(){var t;return(t=this.collider)==null?void 0:t.attachedRigidbody}}class gw{constructor(t,e){r(this,"object");r(this,"collider");this.object=t,this.collider=e}}const $e=S("debugnetworkingstreams");var Nn=(o=>(o.Connected="peer-user-connected",o.StreamReceived="receive-stream",o.StreamEnded="call-ended",o.Disconnected="peer-user-disconnected",o.UserJoined="user-joined",o))(Nn||{});class Eg{constructor(t,e){r(this,"type","call-ended");r(this,"userId");r(this,"direction");this.userId=t,this.direction=e}}class yw{constructor(t,e,i){r(this,"type","receive-stream");r(this,"userId");r(this,"stream");r(this,"target");this.userId=t,this.stream=e,this.target=i}}class sM{constructor(t,e){r(this,"guid");r(this,"peerId");r(this,"dontSave",!0);this.guid=t.id,this.peerId=e}}var _w=(o=>(o.Incoming="incoming",o.Outgoing="outgoing",o))(_w||{});class oM extends d.EventDispatcher{constructor(e,i,n,s=null){super();r(this,"peerId");r(this,"userId");r(this,"direction");r(this,"call");r(this,"_stream",null);r(this,"_isDisposed",!1);this.peerId=i.peer,this.userId=e,this.call=i,this.direction=n,this._stream=s,i.on("stream",a=>{if($e&&console.log("Receive stream",`
941
941
  Audio:`,a.getAudioTracks(),`
942
942
  Video:`,a.getVideoTracks()),this._stream=a,n==="incoming"){const l=new yw(e,a,this);this.dispatchEvent(l)}}),i.on("close",()=>{this.dispatchEvent(new Eg(e,n))})}get stream(){return this._stream}close(){this._isDisposed||(this._isDisposed=!0,this.call.close(),Vn(this._stream))}get isOpen(){var e;return((e=this.call.peerConnection)==null?void 0:e.connectionState)==="connected"}get isOpening(){var e;return((e=this.call.peerConnection)==null?void 0:e.connectionState)==="connecting"}get isClosed(){return!this.isOpen||this._isDisposed}}function lb(o){return o=o.replace("a=fmtp:111 minptime=10;useinbandfec=1","a=fmtp:111 ptime=5;useinbandfec=1;stereo=1;maxplaybackrate=48000;maxaveragebitrat=128000;sprop-stereo=1"),o}const rr=class rr extends d.EventDispatcher{constructor(e,i){super();r(this,"updateCalls",()=>{var e;for(let i=this._incomingCalls.length-1;i>=0;i--){const n=this._incomingCalls[i];n.isClosed&&!n.isOpening&&this._incomingCalls.splice(i,1)}for(let i=this._outgoingCalls.length-1;i>=0;i--){const n=this._outgoingCalls[i];let s=!1;n.isClosed&&!n.isOpening&&((e=n.stream)!=null&&e.active?$e&&console.warn("!!! Stream is still active, don't remove call",n.userId,"Your id: "+this.context.connection.connectionId):($e&&console.warn("!!! Remove closed call",n.userId),s=!0)),this.context.connection.userIsInRoom(n.userId)===!1&&($e&&console.warn("!!! User is not in room anymore, remove call",n.userId),s=!0),s&&(n.close(),this._outgoingCalls.splice(i,1))}});r(this,"id");r(this,"context");r(this,"_incomingCalls",[]);r(this,"_outgoingCalls",[]);r(this,"_peer");r(this,"_enabled",!1);r(this,"_enabledPeer",!1);r(this,"onConnectRoomFn",this.onConnectRoom.bind(this));r(this,"onPeerConnect",e=>{if($e&&console.log("PEER opened as",e),e===null){console.error("Peer connection failed",e);return}this.context.connection.send("peer-user-connected",new sM(this,e))});r(this,"onPeerClose",()=>{$e&&console.log("PEER closed"),this.updateCalls()});r(this,"onPeerDisconnected",()=>{$e&&console.log("PEER disconnected"),this.updateCalls()});r(this,"onPeerError",e=>{$e&&console.error("PEER error",e)});r(this,"onPeerReceivingCall",e=>{e.answer(void 0,{sdpTransform:i=>lb(i)}),this.registerCall(e,"incoming",null)});this.context=e,this.id=i,this.setupPeer(),navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia}static getOrCreate(e,i){if(rr.instances.has(i))return rr.instances.get(i);const n=new rr(e,i);return rr.instances.set(i,n),n}getMyPeerId(){if(this.context.connection.connectionId)return this.getPeerIdFromUserId(this.context.connection.connectionId)}getPeerIdFromUserId(e){return this.id+"-"+e}getUserIdFromPeerId(e){return e.substring(this.id.length+1)}makeCall(e,i){var a;if(!(i!=null&&i.id)){$e?console.warn("Can not make a call: mediastream has no id or is undefined"):console.debug("Can not make a call: mediastream has no id or is undefined");return}const n={metadata:{userId:this.context.connection.connectionId,streamId:i.id},sdpTransform:l=>lb(l)},s=(a=this._peer)==null?void 0:a.call(e,i,n);if(s){const l=this.registerCall(s,"outgoing",i);return $e&&console.warn(`📞 CALL ${e}`,`
@@ -1270,7 +1270,7 @@ dateFormat X
1270
1270
  axisFormat %s
1271
1271
  `;const p=Array.from(s),g=new Set;for(const v of p)if(v.affectedObjects&&typeof v.affectedObjects!="string"){if(Array.isArray(v.affectedObjects))for(const w of v.affectedObjects)g.add(w);else g.add(v.affectedObjects);a&&(f+=`section ${v.animationName} (${v.id})
1272
1272
  `,f+=`${v.id} : ${v.start}, ${v.duration}s
1273
- `)}a&&s.size&&console.log(f);const y=new Set;for(const v of g){v.getPath||console.error("USDZExporter: Animation target object has no getPath method. This is likely a bug",v);let w=v.getPath();w.startsWith("<")&&(w=w.substring(1)),w.endsWith(">")&&(w=w.substring(0,w.length-1)),y.add({path:w,obj:v})}const b=Array.from(y).sort((v,w)=>v.path.length-w.path.length),_=new Array;for(let v=0;v<b.length;v++)for(let w=v+1;w<b.length;w++)if(b[w].path.startsWith(b[v].path)){const x=b[w],O=b[v];_.push({child:x.obj.displayName+" ("+x.path+")",parent:O.obj.displayName+" ("+O.path+")"})}_.length&&console.warn("USDZExporter: There are overlapping PlayAnimation actions. This can lead to undefined runtime behaviour when playing multiple animations. Please restructure the hierarchy so that animations don't overlap.",{overlappingTargets:_,playAnimationActions:s})}for(const f of new Set([...e,...i]))if(Array.isArray(f))for(const p of f)n.add(p.uuid);else n.add(f.uuid);yd&&console.log("All Behavior trigger sources and action targets",e,i,n),this.targetUuids=new Set(n)}onAfterHierarchy(t,e){var i;if((i=this.behaviours)!=null&&i.length){e.beginBlock('def Scope "Behaviors"');for(const n of this.behaviours)n.writeTo(this,t.document,e);e.closeBlock()}}async onAfterSerialize(t){yd&&console.log("onAfterSerialize behaviours",this.behaviourComponentsCopy);for(const e of this.behaviourComponentsCopy)typeof e.afterSerialize=="function"&&(e.afterSerialize.constructor.name==="AsyncFunction"?await e.afterSerialize(this,t):e.afterSerialize(this,t));for(const{clipUrl:e,filesKey:i}of this.audioClipsCopy){if(t.files[i])return;const a=await(await(await fetch(e)).blob()).arrayBuffer(),l=new Uint8Array(a);t.files[i]=l}this.behaviourComponentsCopy.length=0,this.audioClipsCopy.length=0}}class uy{get extensionName(){return"Physics"}onExportObject(t,e,i){const n=C.getComponents(t,ot).filter(c=>c.enabled),s=C.getComponents(t,di).filter(c=>c.enabled&&!c.isTrigger);let a=n.length>0?n[0]:null;const l=s.length>0?s[0]:null;l&&!a&&(a=new ot,a.isKinematic=!0),a&&e.addEventListener("serialize",(c,h)=>{var u,f,p;if(a){if(c.appendLine(),c.beginBlock('def RealityKitComponent "RigidBody"',"{",!0),a.useGravity||c.appendLine("bool gravityEnabled = 0"),c.appendLine('uniform token info:id = "RealityKit.RigidBody"'),a.isKinematic&&c.appendLine('token motionType = "Kinematic"'),c.beginBlock('def RealityKitStruct "massFrame"',"{",!0),c.appendLine(`float m_mass = ${a.mass}`),c.beginBlock('def RealityKitStruct "m_pose"',"{",!0),c.appendLine(`float3 position = (${a.centerOfMass.x}, ${a.centerOfMass.y}, ${a.centerOfMass.z})`),c.closeBlock("}"),c.closeBlock("}"),s.length>0){const g=s[0];c.beginBlock('def RealityKitStruct "material"',"{",!0);const y=g.sharedMaterial;y&&y.dynamicFriction!==void 0&&c.appendLine(`double dynamicFriction = ${(u=g.sharedMaterial)==null?void 0:u.dynamicFriction}`),y&&y.bounciness!==void 0&&c.appendLine(`double restitution = ${(f=g.sharedMaterial)==null?void 0:f.bounciness}`),y&&y.staticFriction!==void 0&&c.appendLine(`double staticFriction = ${(p=g.sharedMaterial)==null?void 0:p.staticFriction}`),c.closeBlock("}")}c.closeBlock("}")}}),l&&(e.addEventListener("serialize",(c,h)=>{var p;c.beginBlock('def RealityKitComponent "Collider"',"{",!0),c.appendLine("uint group = 1"),c.appendLine('uniform token info:id = "RealityKit.Collider"'),c.appendLine("uint mask = 4294967295");const f=l.isTrigger?"Trigger":"Default";if(c.appendLine(`token type = "${f}"`),c.beginBlock('def RealityKitStruct "Shape"',"{",!0),l instanceof rl){const g=l;c.appendLine('token shapeType = "Sphere"'),c.appendLine(`float radius = ${g.radius}`)}else if(l instanceof ef){const g=l;c.appendLine('token shapeType = "Box"'),c.appendLine(`float3 extent = (${g.size.x}, ${g.size.y}, ${g.size.z})`)}else if(l instanceof As){const g=l;c.appendLine('token shapeType = "Capsule"'),c.appendLine(`float radius = ${g.radius}`),c.appendLine(`float height = ${g.height}`)}else if(l instanceof jo&&((p=l.sharedMesh)!=null&&p.geometry)){const g=l.sharedMesh.geometry;g.boundingBox||g.computeBoundingBox();const y=l.sharedMesh.geometry.boundingBox;y&&(c.appendLine('token shapeType = "Box"'),c.appendLine(`float3 extent = (${y.max.x-y.min.x}, ${y.max.y-y.min.y}, ${y.max.z-y.min.z})`),console.log("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. MeshCollider will be exported as Box",l))}else console.warn("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. Ignoring collider:",l);c.beginBlock('def RealityKitStruct "pose"',"{",!0),c.closeBlock("}"),c.closeBlock("}"),c.closeBlock("}")}),s.length>1&&console.log("WARNING: Multiple colliders detected. visionOS / iOS can only support objects with a single collider, only exporting the first collider: ",l))}}const HO=S("debugshadowcomponents");ne.__webpack_exports__Block.prototype.interactable={get(){return this.interactive},set(o){this.interactable=o}};class Qi extends D{constructor(){super(...arguments);r(this,"_shadowComponent",null);r(this,"_controlsChildLayout",!0);r(this,"_root");r(this,"_parentComponent")}isRoot(){var e;return((e=this.Root)==null?void 0:e.gameObject)===this.gameObject}get canvas(){const e=this.Root;return e!=null&&e.isCanvas?e:null}get Canvas(){return this.canvas}markDirty(){Qt.markUIDirty(this.context)}get shadowComponent(){return this._shadowComponent}set shadowComponent(e){this._shadowComponent=e}get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(e){this._controlsChildLayout=e,this.shadowComponent&&(this.shadowComponent.autoLayout=e)}get Root(){return this._root===void 0&&(this._root=C.getComponentInParent(this.gameObject,Ch)),this._root}__internalNewInstanceCreated(e){return super.__internalNewInstanceCreated(e),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0,this}onEnable(){super.onEnable()}addShadowComponent(e,i){var a;if(!e)return;this.removeShadowComponent();const n=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=C.getComponentInParent(n,Qi),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have an UI element outside a Canvas? UI components must be a child of a Canvas component`,this);return}e.name=this.name+" ("+(this.constructor.name??"UI")+")",e.autoLayout=this._parentComponent.controlsChildLayout,e[Si]=this,this.setShadowComponentOwner(e);let s=!1;if(((a=this.Root)==null?void 0:a.gameObject)===this.gameObject)this.gameObject.add(e);else{const l=this._parentComponent.shadowComponent;l&&(l==null||l.add(e),s=!0)}this.shadowComponent=e,i&&i.shadowComponent&&this.shadowComponent&&i.shadowComponent.add(this.shadowComponent),oh&&e.add(new d.AxesHelper(.5)),this.onAfterAddedToScene(),s&&ne.__webpack_exports__update(),HO&&console.warn("Added shadow component",this.shadowComponent)}setShadowComponentOwner(e){if(e&&(e[Si]===void 0||e[Si]===this)&&(e[Si]=this,e.children))for(const i of e.children)this.setShadowComponentOwner(i)}traverseOwnedShadowComponents(e,i,n){if(e&&e[Si]===i){n(e);for(const s of e.children)this.traverseOwnedShadowComponents(s,i,n)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(e){this.shadowComponent&&(this.shadowComponent.interactable=e)}}class Ch extends Qi{awake(){super.awake()}}var GO=Object.defineProperty,qO=Object.getOwnPropertyDescriptor,Ph=(o,t,e,i)=>{for(var n=i>1?void 0:i?qO(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&GO(t,e,n),n};const Mp=S("debugui"),Op=S("debuguilayout");class ix{constructor(){r(this,"width");r(this,"height")}}class nx{constructor(){r(this,"x");r(this,"y");r(this,"width");r(this,"height")}}const cn=new d.Vector3,Il=new d.Matrix4,_d=new d.Quaternion,ul=class sx extends Qi{constructor(){super(...arguments);r(this,"_anchoredPosition");r(this,"sizeDelta",new d.Vector2(100,100));r(this,"pivot",new d.Vector2(.5,.5));r(this,"anchorMin",new d.Vector2(0,0));r(this,"anchorMax",new d.Vector2(1,1));r(this,"minWidth");r(this,"minHeight");r(this,"lastMatrix");r(this,"rectBlock");r(this,"_transformNeedsUpdate",!1);r(this,"_initialPosition");r(this,"_parentRectTransform");r(this,"_lastUpdateFrame",-1);r(this,"_lastAnchoring");r(this,"_createdBlocks",[]);r(this,"_createdTextBlocks",[])}get parent(){return this._parentRectTransform}get translation(){return this.gameObject.position}get rotation(){return this.gameObject.quaternion}get scale(){return this.gameObject.scale}get anchoredPosition(){return this._anchoredPosition||(this._anchoredPosition=new d.Vector2),this._anchoredPosition}set anchoredPosition(e){this._anchoredPosition=e}get width(){let e=this.sizeDelta.x;if(this.anchorMin.x!==this.anchorMax.x&&this._parentRectTransform){const i=this._parentRectTransform.width,n=this.anchorMax.x-this.anchorMin.x;e=i*n,e+=this.sizeDelta.x}return this.minWidth!==void 0&&e<this.minWidth?this.minWidth:e}get height(){let e=this.sizeDelta.y;if(this.anchorMin.y!==this.anchorMax.y&&this._parentRectTransform){const i=this._parentRectTransform.height,n=this.anchorMax.y-this.anchorMin.y;e=i*n,e+=this.sizeDelta.y}return this.minHeight!==void 0&&e<this.minHeight?this.minHeight:e}awake(){super.awake(),this._lastUpdateFrame=-1,this._parentRectTransform=void 0,this.rectBlock=new d.Object3D,this.rectBlock.name=this.name,this.lastMatrix=new d.Matrix4,this._lastAnchoring=null,this._initialPosition=this.gameObject.position.clone(),this._initialPosition.z=0,this._anchoredPosition||(this._anchoredPosition=new d.Vector2),pa(this,"_anchoredPosition",()=>{this.markDirty()}),pa(this,"sizeDelta",()=>{this.markDirty()}),pa(this,"pivot",()=>{this.markDirty()}),pa(this,"anchorMin",()=>{this.markDirty()}),pa(this,"anchorMax",()=>{this.markDirty()})}onEnable(){var e;super.onEnable(),this.rectBlock||(this.rectBlock=new d.Object3D),this.lastMatrix||(this.lastMatrix=new d.Matrix4),this._lastAnchoring||(this._lastAnchoring=new d.Vector2),this._initialPosition||(this._initialPosition=new d.Vector3),this._anchoredPosition||(this._anchoredPosition=new d.Vector2),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0,(e=this.canvas)==null||e.registerTransform(this)}onDisable(){var e;super.onDisable(),this.removeShadowComponent(),(e=this.canvas)==null||e.unregisterTransform(this)}onParentRectTransformChanged(e){this._transformNeedsUpdate||this.onApplyTransform(Op?`${e.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||(this._transformNeedsUpdate=!this.lastMatrix.equals(this.gameObject.matrix)),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(Op&&console.warn("RectTransform markDirty()",this.name),this._transformNeedsUpdate=!0,this._lastUpdateFrame=-1)}updateTransform(){(this._transformNeedsUpdate||!this.lastMatrix.equals(this.gameObject.matrix))&&this.canUpdate()&&this.onApplyTransform(this._transformNeedsUpdate?"Marked dirty":"Matrix changed")}canUpdate(){return this._transformNeedsUpdate&&this.activeAndEnabled&&this._lastUpdateFrame!==this.context.time.frame}onApplyTransform(e){var s;if(this.context.time.frameCount===this._lastUpdateFrame)return;this._lastUpdateFrame=this.context.time.frameCount;const i=this.shadowComponent;if(!i)return;this.gameObject.parent?this._parentRectTransform=C.getComponentInParent(this.gameObject.parent,sx):this._parentRectTransform=void 0,this._transformNeedsUpdate=!1,Op&&console.warn("RectTransform → ApplyTransform",this.name+" because "+e),this.isRoot()?this.Root.screenspace||(i.rotation.y=Math.PI):(i.matrix.identity(),i.matrixAutoUpdate=!1,cn.set(0,0,0),this.applyPivot(cn),i.matrix.setPosition(cn.x,cn.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(_d.copy(this.gameObject.quaternion),_d.x*=-1,_d.z*=-1,Il.makeRotationFromQuaternion(_d),i.matrix.premultiply(Il)),cn.set(0,0,0),this.applyAnchoring(cn),(s=this.canvas)!=null&&s.screenspace?cn.z+=.1:cn.z+=.01,Il.identity(),Il.setPosition(cn.x,cn.y,cn.z),i.matrix.premultiply(Il),i.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);const n=!0;for(const a of Hu(this.gameObject,Qi,n,1)){if(a===this||!a.activeAndEnabled)continue;const l=a;l.onParentRectTransformChanged&&l.onParentRectTransformChanged(this)}}applyAnchoring(e){this._lastAnchoring||(this._lastAnchoring=new d.Vector2);const i=this._lastAnchoring.sub(this._anchoredPosition);this.gameObject.position.x+=i.x,this.gameObject.position.y+=i.y,this._lastAnchoring.copy(this._anchoredPosition),e.x+=this._initialPosition.x-this.gameObject.position.x,e.y+=this._initialPosition.y-this.gameObject.position.y,e.z+=this._initialPosition.z-this.gameObject.position.z;const n=this._parentRectTransform;if(n){let s=0;const a=1-this.anchorMax.y-this.anchorMin.y;s-=n.height*.5*a,e.y+=s;let l=0;const c=1-this.anchorMax.x-this.anchorMin.x;l-=n.width*.5*c,e.x+=l}}applyPivot(e){if(this.pivot&&!this.isRoot()){const i=this.pivot.x-.5;e.x-=i*this.sizeDelta.x*this.gameObject.scale.x;const n=this.pivot.y-.5;e.y-=n*this.sizeDelta.y*this.gameObject.scale.y}}getBasicOptions(){const e={width:this.sizeDelta.x,height:this.sizeDelta.y,offset:0,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0,letterSpacing:-.03};return this.ensureValidSize(e),e}ensureValidSize(e,i=1e-4){return e.width<=0&&(e.width=i),e.height<=0&&(e.height=1e-4),e}createNewBlock(e){e={...this.getBasicOptions(),...e},Mp&&console.log(this.name,e);const i=new ne.__webpack_exports__Block(e);return this._createdBlocks.push(i),i}createNewText(e){Mp&&console.log(e),e={...this.getBasicOptions(),...e},Mp&&console.log(this.name,e);const i=new ne.__webpack_exports__Text(e);return this._createdTextBlocks.push(i),i}};Ph([m(d.Vector2)],ul.prototype,"anchoredPosition",1);Ph([m(d.Vector2)],ul.prototype,"sizeDelta",2);Ph([m(d.Vector2)],ul.prototype,"pivot",2);Ph([m(d.Vector2)],ul.prototype,"anchorMin",2);Ph([m(d.Vector2)],ul.prototype,"anchorMax",2);let xn=ul;var XO=Object.defineProperty,ox=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&XO(t,e,n),n};class fl extends D{constructor(){super(...arguments);r(this,"effectColor");r(this,"effectDistance")}}ox([m(ie)],fl.prototype,"effectColor");ox([m(d.Vector2)],fl.prototype,"effectDistance");var QO=Object.defineProperty,YO=Object.getOwnPropertyDescriptor,rx=(o,t,e,i)=>{for(var n=i>1?void 0:i?YO(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&QO(t,e,n),n};const bd={backgroundColor:new d.Color(1,1,1),backgroundOpacity:1,borderColor:new d.Color(1,1,1),borderOpacity:1};var Gn;const fy=(Gn=class extends Qi{constructor(){super(...arguments);r(this,"_alphaFactor",1);r(this,"sRGBColor",new d.Color(1,0,1));r(this,"raycastTarget",!0);r(this,"uiObject",null);r(this,"_color",null);r(this,"_rect",null);r(this,"_stateManager",null);r(this,"_currentlyCreatingPanel",!1)}get isGraphic(){return!0}get color(){return this._color||(this._color=new ie(1,1,1,1)),this._color}set color(e){(!this._color||this._color.r!==e.r||this._color.g!==e.g||this._color.b!==e.b||this._color.alpha!==e.alpha)&&(this._color||(this._color=new ie(1,1,1,1)),this._color.copy(e),this.onColorChanged())}setAlphaFactor(e){this._alphaFactor=e,this.onColorChanged()}get alphaFactor(){return this._alphaFactor}onColorChanged(){this.uiObject&&(this.sRGBColor.copy(this._color),this.sRGBColor.convertLinearToSRGB(),bd.backgroundColor=this.sRGBColor,bd.backgroundOpacity=this._color.alpha*this._alphaFactor,this.applyEffects(bd,this._alphaFactor),this.uiObject.set(bd),this.markDirty())}get m_Color(){return this._color}get rectTransform(){if(this._rect||(this._rect=C.getComponent(this.gameObject,xn)),!this._rect)throw new Error("Not Supported: Make sure to add a RectTransform component before adding a UI Graphic component.");return this._rect}onParentRectTransformChanged(){var e;(e=this.uiObject)==null||e.set({width:this.rectTransform.width,height:this.rectTransform.height}),this.markDirty()}__internalNewInstanceCreated(e){return super.__internalNewInstanceCreated(e),this._rect=null,this.uiObject=null,this._stateManager=null,this._color&&(this._color=this._color.clone()),this}setState(e){this.makePanel(),this.uiObject&&(this.uiObject.setState(e),this==null||this.markDirty())}setupState(e){this.makePanel(),this.uiObject&&(this._stateManager||(this._stateManager=new ne.SimpleStateBehavior(this.uiObject)),this.uiObject.setupState(e.state,e.attributes))}setOptions(e){this.makePanel(),this.uiObject&&this.uiObject.set(e)}awake(){super.awake(),this.makePanel(),pa(this,"_color",()=>GP(this,this.onColorChanged))}onEnable(){var e;super.onEnable(),this.uiObject&&((e=this.rectTransform.shadowComponent)==null||e.add(this.uiObject),this.addShadowComponent(this.uiObject,this.rectTransform))}onDisable(){super.onDisable(),this.uiObject&&this.removeShadowComponent()}makePanel(){if(this.uiObject||this._currentlyCreatingPanel)return;this._currentlyCreatingPanel=!0;const i={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:.015};this.onBeforeCreate(i),this.applyEffects(i),this.onCreate(i),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated(),this.onColorChanged()}onBeforeCreate(e){}onCreate(e){this.uiObject=this.rectTransform.createNewBlock(e),this.uiObject.name=this.name}onAfterCreated(){}applyEffects(e,i=1){var s;const n=(s=this.gameObject)==null?void 0:s.getComponent(fl);n&&(n.effectDistance&&(e.borderWidth=Math.max(Math.abs(n.effectDistance.x),Math.abs(n.effectDistance.y))),n.effectColor&&(e.borderColor=n.effectColor,e.borderOpacity=n.effectColor.alpha*i))}async setTexture(e){if(this.setOptions({backgroundOpacity:0}),e){if(Gn.textureCache.has(e))e=Gn.textureCache.get(e);else if(!e.isRenderTargetTexture){const i=e.clone();i.colorSpace=d.LinearSRGBColorSpace,Gn.textureCache.set(e,i),e=i}this.setOptions({backgroundImage:e,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"}),le.NEEDLE_progressive.assignTextureLOD(e,0).then(i=>{i instanceof d.Texture&&(e&&Gn.textureCache.set(e,i),this.setOptions({backgroundImage:i}),this.markDirty())})}else this.setOptions({backgroundImage:void 0,borderRadius:0,backgroundOpacity:this.color.alpha});this.markDirty()}onAfterAddedToScene(){super.onAfterAddedToScene(),this.shadowComponent&&(this.shadowComponent.offset=this.shadowComponent.position.z)}},r(Gn,"textureCache",new Map),Gn);rx([m(ie)],fy.prototype,"color",1);rx([m()],fy.prototype,"raycastTarget",2);let Mh=fy;class Oh extends Mh{constructor(){super(...arguments);r(this,"_flippedObject",!1)}onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}}var KO=Object.defineProperty,ZO=Object.getOwnPropertyDescriptor,Us=(o,t,e,i)=>{for(var n=i>1?void 0:i?ZO(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&KO(t,e,n),n};const Qo=S("debugtext");var tt=(o=>(o[o.UpperLeft=0]="UpperLeft",o[o.UpperCenter=1]="UpperCenter",o[o.UpperRight=2]="UpperRight",o[o.MiddleLeft=3]="MiddleLeft",o[o.MiddleCenter=4]="MiddleCenter",o[o.MiddleRight=5]="MiddleRight",o[o.LowerLeft=6]="LowerLeft",o[o.LowerCenter=7]="LowerCenter",o[o.LowerRight=8]="LowerRight",o))(tt||{}),ax=(o=>(o[o.Normal=0]="Normal",o[o.Bold=1]="Bold",o[o.Italic=2]="Italic",o[o.BoldAndItalic=3]="BoldAndItalic",o))(ax||{});class Dt extends Mh{constructor(){super(...arguments);r(this,"alignment",0);r(this,"verticalOverflow",0);r(this,"horizontalOverflow",0);r(this,"lineSpacing",1);r(this,"supportRichText",!1);r(this,"font");r(this,"fontStyle",0);r(this,"sRGBTextColor",new d.Color(1,0,1));r(this,"_text","");r(this,"_fontSize",12);r(this,"_textMeshUi",null);r(this,"_didHandleTextRenderOnTop",!1)}setAlphaFactor(e){var i;super.setAlphaFactor(e),(i=this.uiObject)==null||i.set({fontOpacity:this.color.alpha*this.alphaFactor}),this.markDirty()}get text(){return this._text}set text(e){e!==this._text&&(this._text=e,this.feedText(this.text,this.supportRichText),this.markDirty())}set_text(e){this.text=e}get fontSize(){return this._fontSize}set fontSize(e){var i;this._fontSize=e,(i=this.uiObject)==null||i.set({fontSize:e})}onColorChanged(){var e;this.sRGBTextColor.copy(this.color),this.sRGBTextColor.convertLinearToSRGB(),(e=this.uiObject)==null||e.set({color:this.sRGBTextColor,fontOpacity:this.color.alpha})}onParentRectTransformChanged(){super.onParentRectTransformChanged(),this.uiObject&&this.updateOverflow()}onBeforeCanvasRender(e){this.updateOverflow()}updateOverflow(){var i;const e=(i=this.uiObject)==null?void 0:i._overflow;e&&(e._needsUpdate=!0)}onCreate(e){Qo&&console.log(this),this.horizontalOverflow==1&&(e.whiteSpace="pre"),this.verticalOverflow==0&&(this.context.renderer.localClippingEnabled=!0,e.overflow="hidden"),this.horizontalOverflow==1&&this.verticalOverflow==0,e.lineHeight=this.lineSpacing,delete e.backgroundOpacity,delete e.backgroundColor,Qo&&(e.backgroundColor=16750848,e.backgroundOpacity=.5);const i=this.rectTransform;e={...e,...this.getTextOpts()},this.getAlignment(e),Qo&&(e.backgroundColor=Math.random()*16777215,e.backgroundOpacity=.1),this.uiObject=i.createNewText(e),this.feedText(this.text,this.supportRichText)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}getTextOpts(){const e=this.fontSize,i={color:this.color,fontOpacity:this.color.alpha,fontSize:e,fontKerning:"normal"};return this.setFont(i,this.fontStyle),i}onEnable(){var e;super.onEnable(),this._didHandleTextRenderOnTop=!1,this.uiObject&&this.uiObject.addAfterUpdate(()=>{this.setShadowComponentOwner(this.uiObject),this.markDirty()}),setTimeout(()=>this.markDirty(),10),(e=this.canvas)==null||e.registerEventReceiver(this)}onDisable(){var e;super.onDisable(),(e=this.canvas)==null||e.unregisterEventReceiver(this)}getAlignment(e){switch(e.flexDirection="column",this.alignment){case 0:case 3:case 6:e.textAlign="left";break;case 1:case 4:case 7:e.textAlign="center";break;case 2:case 5:case 8:e.textAlign="right";break}switch(this.alignment){default:case 0:case 1:case 2:e.alignItems="start";break;case 3:case 4:case 5:e.alignItems="center";break;case 6:case 7:case 8:e.alignItems="end";break}return e}feedText(e,i){var n,s,a;if(Qo&&console.log("feedText",this.uiObject,e,i),!!this.uiObject)if(this._textMeshUi||(this._textMeshUi=[]),this.uiObject.children.length=0,!i||e.length===0)this.uiObject.textContent=e;else{let l=this.getNextTag(e);if(l){if(l.startIndex>0){for(let u=this.uiObject.children.length-1;u>=0;u--){const f=this.uiObject.children[u];f.isUI&&(this.uiObject.remove(f),f.clear())}const h=new ne.__webpack_exports__Inline({textContent:e.substring(0,l.startIndex),color:"inherit"});this.uiObject.add(h)}}else{this.uiObject.textContent="",this.setOptions({textContent:e});return}const c=[];for(;l;){const h=this.getNextTag(e,l.endIndex),u={fontFamily:(n=this.uiObject)==null?void 0:n.get("fontFamily"),color:"inherit",textContent:""};if(h){u.textContent=this.getText(e,l,h),this.handleTag(l,u,c);const f=new ne.__webpack_exports__Inline(u);(s=this.uiObject)==null||s.add(f)}else{u.textContent=e.substring(l.endIndex),this.handleTag(l,u,c);const f=new ne.__webpack_exports__Inline(u);(a=this.uiObject)==null||a.add(f)}l=h}}}handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;const e=[],i=this.canvas,n={renderOnTop:i.renderOnTop,depthWrite:i.depthWrite,doubleSided:i.doubleSided};for(;;){let s=!1;if(this._textMeshUi)for(let a=0;a<this._textMeshUi.length;a++){if(e[a]===!0)continue;s=!0;const l=this._textMeshUi[a];l.textContent&&(hu(l,n),e[a]=!0)}if(!s)break;yield}}handleTag(e,i,n){if(!e.isEndTag){if(e.type.includes("color")){const s=new kp(e,{color:i.color});if(n.push(s),e.type.length>6){const a=parseInt("0x"+e.type.substring(7));i.color=a}else i.color=new d.Color(1,1,1)}else if(e.type=="b"){this.setFont(i,1);const s=new kp(e,{fontWeight:700});n.push(s)}else if(e.type=="i"){this.setFont(i,2);const s=new kp(e,{fontStyle:"italic"});n.push(s)}}}getText(e,i,n){return e.substring(i.endIndex,n.startIndex)}getNextTag(e,i=0){const n=e.indexOf("<",i),s=e.indexOf(">",n);if(n>=0&&s>=0){const a=e.substring(n+1,s);return{type:a,startIndex:n,endIndex:s+1,isEndTag:a.startsWith("/")}}return null}setFont(e,i){if(!this.font)return;const n=this.font,s=this.getFamilyNameWithCorrectSuffix(n,i);Qo&&console.log("Selected font family:"+s);let a=ne.__webpack_exports__FontLibrary.getFontFamily(s);switch(a||(a=ne.__webpack_exports__FontLibrary.addFontFamily(s)),e.fontFamily=a,i){default:case 0:e.fontWeight=400,e.fontStyle="normal";break;case 1:e.fontWeight=700,e.fontStyle="normal";break;case 2:e.fontWeight=400,e.fontStyle="italic";break;case 3:e.fontStyle="italic",e.fontWeight=400}let l=a.getVariant(e.fontWeight,e.fontStyle);if(!l){let c=s;c!=null&&c.endsWith("-msdf.json")||(c+="-msdf.json");let h=s;h!=null&&h.endsWith(".png")||(h+=".png"),l=a.addVariant(e.fontWeight,e.fontStyle,c,h),l==null||l.addEventListener("ready",()=>{this.markDirty()})}}getFamilyNameWithCorrectSuffix(e,i){var u;const n=e.lastIndexOf("-");if(n<0)return e;const s=(u=e.substring(n+1))==null?void 0:u.toLowerCase();if(JO.includes(s))return Qo&&console.warn("Unsupported font style: "+s),e;const a=e.lastIndexOf("/");let l=e;a>=0&&(l=l.substring(a+1));const c=l[0]===l[0].toUpperCase(),h=e.substring(0,n);switch(Qo&&console.log("Select font: ",e,ax[i],l,c,h),i){case 0:return c?h+"-Regular":h+"-regular";case 1:return c?h+"-Bold":h+"-bold";case 2:return c?h+"-Italic":h+"-italic";case 3:return c?h+"-BoldItalic":h+"-bolditalic";default:return e}}}Us([m()],Dt.prototype,"alignment",2);Us([m()],Dt.prototype,"verticalOverflow",2);Us([m()],Dt.prototype,"horizontalOverflow",2);Us([m()],Dt.prototype,"lineSpacing",2);Us([m()],Dt.prototype,"supportRichText",2);Us([m(URL)],Dt.prototype,"font",2);Us([m()],Dt.prototype,"fontStyle",2);Us([m()],Dt.prototype,"text",1);Us([m()],Dt.prototype,"fontSize",1);class kp{constructor(t,e){r(this,"tag");r(this,"previousValues");this.tag=t,this.previousValues=e}}const JO=["medium","mediumitalic","black","blackitalic","thin","thinitalic","extrabold","light","lightitalic","semibold"];class hr{constructor(t){r(this,"id");r(this,"content","");r(this,"font",[]);r(this,"pointSize",144);r(this,"width");r(this,"height");r(this,"depth");r(this,"wrapMode");r(this,"horizontalAlignment");r(this,"verticalAlignment");r(this,"material");this.id=t}static getId(){return this.global_id++}setDepth(t){return this.depth=t,this}setPointSize(t){return this.pointSize=t,this}setHorizontalAlignment(t){return this.horizontalAlignment=t,this}setVerticalAlignment(t){return this.verticalAlignment=t,this}writeTo(t,e){var n;e.beginBlock(`def Preliminary_Text "${this.id}"`,"(",!1),e.appendLine('prepend apiSchemas = ["MaterialBindingAPI"]'),e.closeBlock(")"),e.beginBlock(),this.content&&e.appendLine(`string content = "${this.content}"`),(!this.font||this.font.length<=0)&&(this.font||(this.font=[]),(n=this.font)==null||n.push("sans-serif"));const i=this.font.map(s=>`"${s}"`).join(", ");e.appendLine(`string[] font = [ ${i} ]`),e.appendLine(`double pointSize = ${this.pointSize}`),typeof this.width=="number"&&e.appendLine(`double width = ${this.width}`),typeof this.height=="number"&&e.appendLine(`double height = ${this.height}`),typeof this.depth=="number"&&e.appendLine(`double depth = ${this.depth}`),this.wrapMode&&e.appendLine(`token wrapMode = "${this.wrapMode}"`),this.horizontalAlignment&&e.appendLine(`token horizontalAlignment = "${this.horizontalAlignment}"`),this.verticalAlignment&&e.appendLine(`token verticalAlignment = "${this.verticalAlignment}"`),this.material!==void 0&&e.appendLine(`rel material:binding = </StageRoot/Materials/${of(this.material)}>`),e.closeBlock()}}r(hr,"global_id",0);class py{static singleLine(t,e,i){const n=new hr("text_"+hr.getId());return n.content=t,e&&(n.pointSize=e),i&&(n.depth=i),n}static multiLine(t,e,i,n,s,a){const l=new hr("text_"+hr.getId());return l.content=t,l.width=e,l.height=i,l.horizontalAlignment=n,l.verticalAlignment=s,a!==void 0&&(l.wrapMode=a),l}}const ek=new d.Matrix4().makeRotationY(Math.PI),tk=new d.Matrix4().makeScale(-1,1,-1);class ff{get extensionName(){return"text"}exportText(t,e,i){const n=C.getComponent(t,Dt);if(!n)return;const s=C.getComponent(t,xn);let a=100,l=100;s&&(a=s.width,l=s.height);const c=ek.clone();s&&c.premultiply(tk),e.setMatrix(c);const h=n.color.clone();e.material=new d.MeshStandardMaterial({color:h,emissive:h}),e.addEventListener("serialize",(u,f)=>{let p=n.text;p=p.replace(/\r/g,""),p=p.replace(/\n/g,"\\n");const g=py.multiLine(p,a,l,"center","bottom","flowing");this.setTextAlignment(g,n.alignment),this.setOverflow(g,n),e.material&&(g.material=e.material),g.pointSize=this.convertToTextSize(n.fontSize),g.depth=.001,g.writeTo(void 0,u)})}convertToTextSize(t){return 1/.0502*144*t}setOverflow(t,e){e.horizontalOverflow?t.wrapMode="singleLine":t.wrapMode="flowing"}setTextAlignment(t,e){switch(e){case tt.LowerLeft:case tt.MiddleLeft:case tt.UpperLeft:t.horizontalAlignment="left";break;case tt.LowerCenter:case tt.MiddleCenter:case tt.UpperCenter:t.horizontalAlignment="center";break;case tt.LowerRight:case tt.MiddleRight:case tt.UpperRight:t.horizontalAlignment="right";break}switch(e){case tt.LowerLeft:case tt.LowerCenter:case tt.LowerRight:t.verticalAlignment="bottom";break;case tt.MiddleLeft:case tt.MiddleCenter:case tt.MiddleRight:t.verticalAlignment="middle";break;case tt.UpperLeft:case tt.UpperCenter:case tt.UpperRight:t.verticalAlignment="top";break}}}var ik=Object.defineProperty,Ke=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&ik(t,e,n),n};const Eb=S("debuguilayout");class Gr{constructor(){r(this,"left",0);r(this,"right",0);r(this,"top",0);r(this,"bottom",0)}get vertical(){return this.top+this.bottom}get horizontal(){return this.left+this.right}}Ke([m()],Gr.prototype,"left");Ke([m()],Gr.prototype,"right");Ke([m()],Gr.prototype,"top");Ke([m()],Gr.prototype,"bottom");class Di extends D{constructor(){super(...arguments);r(this,"_rectTransform",null);r(this,"_needsUpdate",!1);r(this,"childAlignment",0);r(this,"reverseArrangement",!1);r(this,"spacing",0);r(this,"padding");r(this,"minWidth",0);r(this,"minHeight",0);r(this,"flexibleHeight",0);r(this,"flexibleWidth",0);r(this,"preferredHeight",0);r(this,"preferredWidth",0)}get rectTransform(){return this._rectTransform}onParentRectTransformChanged(e){this._needsUpdate=!0}get isDirty(){return this._needsUpdate}get isLayoutGroup(){return!0}updateLayout(){this._rectTransform&&(Eb&&console.warn("Layout Update",this.context.time.frame,this.name),this._needsUpdate=!1,this.onCalculateLayout(this._rectTransform))}start(){this._needsUpdate=!0}onEnable(){Eb&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(xn);const e=this.gameObject.getComponentInParent(Za);e&&e.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){const e=this.gameObject.getComponentInParent(Za);e&&e.unregisterLayoutGroup(this)}set m_Spacing(e){e!==this.spacing&&(this._needsUpdate=!0,this.spacing=e)}get m_Spacing(){return this.spacing}}Ke([m()],Di.prototype,"childAlignment");Ke([m()],Di.prototype,"reverseArrangement");Ke([m()],Di.prototype,"spacing");Ke([m(Gr)],Di.prototype,"padding");Ke([m()],Di.prototype,"minWidth");Ke([m()],Di.prototype,"minHeight");Ke([m()],Di.prototype,"flexibleHeight");Ke([m()],Di.prototype,"flexibleWidth");Ke([m()],Di.prototype,"preferredHeight");Ke([m()],Di.prototype,"preferredWidth");class Uo extends Di{constructor(){super(...arguments);r(this,"childControlHeight",!0);r(this,"childControlWidth",!0);r(this,"childForceExpandHeight",!1);r(this,"childForceExpandWidth",!1);r(this,"childScaleHeight",!1);r(this,"childScaleWidth",!1)}onCalculateLayout(e){var F;const i=this.primaryAxis,n=e.width;let s=n;const a=e.height;let l=a;s-=this.padding.horizontal,l-=this.padding.vertical,i==="x"?this.padding.horizontal:this.padding.vertical;const c=i==="x",h=c?"y":"x",u=c?this.childControlWidth:this.childControlHeight,f=c?this.childControlHeight:this.childControlWidth,p=c?this.childForceExpandWidth:this.childForceExpandHeight,g=c?this.childForceExpandHeight:this.childForceExpandWidth,y=c?l:s,b=c?n:a,_=.5*(c?this.childAlignment%3:Math.floor(this.childAlignment/3));let v=0;c?v+=this.padding.left:v+=this.padding.top;let w=0,x=0;for(let T=0;T<this.gameObject.children.length;T++){const L=this.gameObject.children[T],A=C.getComponent(L,xn);A!=null&&A.activeAndEnabled&&(x+=1,c?w+=A.width:w+=A.height)}let O=0;const M=this.spacing*(x-1);if(p||u){let T=0;c?T=s-=M:T=l-=M,x>0&&(O=T/x)}let R=0;R+=this.padding.left,R-=this.padding.right,_!==0&&(v=b-w,v*=_,v-=M*_,c?(v-=this.padding.right*_,v+=this.padding.left*(1-_),v<this.padding.left&&(v=this.padding.left)):(v-=this.padding.bottom*_,v+=this.padding.top*(1-_),v<this.padding.top&&(v=this.padding.top)));let E=1;for(let T=0;T<this.gameObject.children.length;T++){const L=this.gameObject.children[T],A=C.getComponent(L,xn);if(A!=null&&A.activeAndEnabled){(F=A.pivot)==null||F.set(.5,.5),A.anchorMin.set(0,1),A.anchorMax.set(0,1);const H=n*.5+R*.5;A.anchoredPosition.x!==H&&(A.anchoredPosition.x=H);const B=a*-.5;A.anchoredPosition.y!==B&&(A.anchoredPosition.y=B),g&&f&&A.sizeDelta[h]!==y&&(A.sizeDelta[h]=y),p&&u&&A.sizeDelta[i]!==O&&(A.sizeDelta[i]=O);const I=c?A.width:A.height,N=I*.5;if(v+=N,p){const Z=O*E-O*.5;Z>v&&(v=Z-O*.5+I+this.padding.left,v-=N)}let Y=v;i==="y"&&(Y=-Y),A.anchoredPosition[i]!==Y&&(A.anchoredPosition[i]=Y),v+=N,v+=this.spacing,E+=1}}}}Ke([m()],Uo.prototype,"childControlHeight");Ke([m()],Uo.prototype,"childControlWidth");Ke([m()],Uo.prototype,"childForceExpandHeight");Ke([m()],Uo.prototype,"childForceExpandWidth");Ke([m()],Uo.prototype,"childScaleHeight");Ke([m()],Uo.prototype,"childScaleWidth");class my extends Uo{get primaryAxis(){return"y"}}class gy extends Uo{get primaryAxis(){return"x"}}class yy extends Di{onCalculateLayout(){}}var nk=Object.defineProperty,sk=Object.getOwnPropertyDescriptor,as=(o,t,e,i)=>{for(var n=i>1?void 0:i?sk(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&nk(t,e,n),n},lx=(o=>(o[o.ScreenSpaceOverlay=0]="ScreenSpaceOverlay",o[o.ScreenSpaceCamera=1]="ScreenSpaceCamera",o[o.WorldSpace=2]="WorldSpace",o[o.Undefined=-1]="Undefined",o))(lx||{});const Rp=S("debuguilayout"),Yi=class cx extends Ch{constructor(){super(...arguments);r(this,"_renderOnTop");r(this,"_depthWrite",!1);r(this,"_doubleSided",!0);r(this,"_castShadows",!1);r(this,"_receiveShadows",!1);r(this,"_renderMode",-1);r(this,"_rootCanvas");r(this,"_scaleFactor",1);r(this,"worldCamera");r(this,"planeDistance",-1);r(this,"_boundRenderSettingsChanged",this.onRenderSettingsChanged.bind(this));r(this,"previousParent",null);r(this,"_lastMatrixWorld",null);r(this,"_rectTransforms",[]);r(this,"_layoutGroups",new Map);r(this,"_receivers",[]);r(this,"onBeforeRenderRoutine",()=>{var e,i,n,s;if(this.previousParent=this.gameObject.parent,((e=this.context.xr)!=null&&e.isVR||(i=this.context.xr)!=null&&i.isPassThrough)&&this.screenspace){this.gameObject.visible=!1,this.gameObject.removeFromParent();return}this.renderOnTop||this.screenspace?this.gameObject.removeFromParent():(this.onUpdateRenderMode(),this.handleLayoutUpdates(),(n=this.shadowComponent)==null||n.updateMatrixWorld(!0),(s=this.shadowComponent)==null||s.updateWorldMatrix(!0,!0),this.invokeBeforeRenderEvents(),Qt.ensureUpdateMeshUI(ne.ThreeMeshUI,this.context))});r(this,"onAfterRenderRoutine",()=>{var e,i,n,s,a;if(((e=this.context.xr)!=null&&e.isVR||(i=this.context.xr)!=null&&i.isPassThrough)&&this.screenspace){(n=this.previousParent)==null||n.add(this.gameObject);return}if((this.screenspace||this.renderOnTop)&&this.previousParent&&this.context.mainCamera){if(this.screenspace){const h=this.context.mainCamera;h==null||h.add(this.gameObject)}else this.previousParent.add(this.gameObject);const l=this.context.renderer.autoClear,c=this.context.renderer.autoClearColor;this.context.renderer.autoClear=!1,this.context.renderer.autoClearColor=!1,this.context.renderer.clearDepth(),this.onUpdateRenderMode(!0),this.handleLayoutUpdates(),(s=this.shadowComponent)==null||s.updateMatrixWorld(!0),this.invokeBeforeRenderEvents(),Qt.ensureUpdateMeshUI(ne.ThreeMeshUI,this.context,!0),this.context.renderer.render(this.gameObject,this.context.mainCamera),this.context.renderer.autoClear=l,this.context.renderer.autoClearColor=c,this.previousParent.add(this.gameObject)}(a=this._lastMatrixWorld)==null||a.copy(this.gameObject.matrixWorld)});r(this,"_updateRenderSettingsRoutine");r(this,"_activeRenderMode",-1);r(this,"_lastWidth",-1);r(this,"_lastHeight",-1)}get isCanvas(){return!0}get screenspace(){return this.renderMode!==2}set renderOnTop(e){e!==this._renderOnTop&&(this._renderOnTop=e,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop!==void 0?this._renderOnTop:!!(this.screenspace&&this._renderMode===0)}set depthWrite(e){this._depthWrite!==e&&(this._depthWrite=e,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}set doubleSided(e){this._doubleSided!==e&&(this._doubleSided=e,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}set castShadows(e){this._castShadows!==e&&(this._castShadows=e,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}set receiveShadows(e){this._receiveShadows!==e&&(this._receiveShadows=e,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}get renderMode(){return this._renderMode}set renderMode(e){this._renderMode!==e&&(this._renderMode=e,this.onRenderSettingsChanged())}set rootCanvas(e){this._rootCanvas instanceof cx||(this._rootCanvas=e)}get rootCanvas(){return this._rootCanvas}get scaleFactor(){return this._scaleFactor}set scaleFactor(e){this._scaleFactor=e}awake(){var e;this.shadowComponent=this.gameObject,this.previousParent=this.gameObject.parent,Rp&&console.log("Canvas.Awake()",((e=this.previousParent)==null?void 0:e.name)+"/"+this.gameObject.name),super.awake()}start(){this.applyRenderSettings()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this._lastMatrixWorld=new d.Matrix4,this.applyRenderSettings(),document.addEventListener("resize",this._boundRenderSettingsChanged),this.context.pre_render_callbacks.push(this.onBeforeRenderRoutine),this.context.post_render_callbacks.push(this.onAfterRenderRoutine)}onDisable(){super.onDisable(),document.removeEventListener("resize",this._boundRenderSettingsChanged);const e=this.context.pre_render_callbacks.indexOf(this.onBeforeRenderRoutine);e!==-1&&this.context.pre_render_callbacks.splice(e,1);const i=this.context.post_render_callbacks.indexOf(this.onAfterRenderRoutine);i!==-1&&this.context.post_render_callbacks.splice(i,1)}registerTransform(e){this._rectTransforms.push(e)}unregisterTransform(e){const i=this._rectTransforms.indexOf(e);i!==-1&&this._rectTransforms.splice(i,1)}registerLayoutGroup(e){const i=e.gameObject;this._layoutGroups.set(i,e)}unregisterLayoutGroup(e){const i=e.gameObject;this._layoutGroups.delete(i)}registerEventReceiver(e){this._receivers.push(e)}unregisterEventReceiver(e){const i=this._receivers.indexOf(e);i!==-1&&this._receivers.splice(i,1)}async onEnterXR(e){this.screenspace?(e.xr.isVR||e.xr.isPassThrough)&&(this.gameObject.visible=!1):(this.gameObject.visible=!1,await Jc(1).then(()=>{this.gameObject.visible=!0}))}onLeaveXR(e){this.screenspace&&(e.xr.isVR||e.xr.isPassThrough)&&(this.gameObject.visible=!0)}invokeBeforeRenderEvents(){var e;for(const i of this._receivers)(e=i.onBeforeCanvasRender)==null||e.call(i,this)}handleLayoutUpdates(){this._lastMatrixWorld===null&&(this._lastMatrixWorld=new d.Matrix4);const e=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);Rp&&e&&console.log("Canvas Layout changed",this.context.time.frameCount,this.name);for(const i of this._rectTransforms){e&&i.markDirty();let n=this._layoutGroups.get(i.gameObject);i.isDirty&&!n&&(n=i.gameObject.getComponentInParent(Di)),(i.isDirty||n!=null&&n.isDirty)&&(Rp&&console.log("CANVAS UPDATE ### "+i.name+" ##################################### "+this.context.time.frame),n==null||n.updateLayout(),i.updateTransform())}}applyRenderSettings(){this.onRenderSettingsChanged()}onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),we.OnBeforeRender))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),hu(this.shadowComponent,this);for(const e of C.getComponentsInChildren(this.gameObject,Qi))hu(e.shadowComponent,this)}}onUpdateRenderMode(e=!1){if(!e&&this._renderMode===this._activeRenderMode&&this._lastWidth===this.context.domWidth&&this._lastHeight===this.context.domHeight)return;this._activeRenderMode=this._renderMode;let i=this.context.mainCameraComponent,n=10;switch(i&&i.nearClipPlane>0&&i.farClipPlane>0&&(n=z.lerp(i.nearClipPlane,i.farClipPlane,.01)),this._renderMode===1&&(this.worldCamera&&(i=this.worldCamera),this.planeDistance>0&&(n=this.planeDistance)),this._renderMode){case 0:case 1:if(this._lastWidth=this.context.domWidth,this._lastHeight=this.context.domHeight,!i)return;const s=n+.01;this.gameObject.position.x=0,this.gameObject.position.y=0,this.gameObject.position.z=-s,this.gameObject.quaternion.identity();const a=this.gameObject.getComponent(xn);let l=!1;a.sizeDelta.x!==this.context.domWidth&&(l=!0),a.sizeDelta.y!==this.context.domHeight&&(l=!0);const c=i.fieldOfView*Math.PI/180,h=2*Math.tan(c/2)*Math.abs(s);this.gameObject.scale.x=h/this.context.domHeight,this.gameObject.scale.y=h/this.context.domHeight,this.gameObject.scale.z=.01,l&&(a.sizeDelta.x=this.context.domWidth,a.sizeDelta.y=this.context.domHeight,a==null||a.markDirty());break;case 2:this._lastWidth=-1,this._lastHeight=-1;break}}};as([m()],Yi.prototype,"renderOnTop",1);as([m()],Yi.prototype,"depthWrite",1);as([m()],Yi.prototype,"doubleSided",1);as([m()],Yi.prototype,"castShadows",1);as([m()],Yi.prototype,"receiveShadows",1);as([m()],Yi.prototype,"renderMode",1);as([m(Yi)],Yi.prototype,"rootCanvas",1);as([m()],Yi.prototype,"scaleFactor",1);as([m(ri)],Yi.prototype,"worldCamera",2);as([m()],Yi.prototype,"planeDistance",2);let Za=Yi;var ok=Object.defineProperty,rk=Object.getOwnPropertyDescriptor,_y=(o,t,e,i)=>{for(var n=i>1?void 0:i?rk(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&ok(t,e,n),n};class Ro extends D{constructor(){super(...arguments);r(this,"_alpha",1);r(this,"interactable",!0);r(this,"blocksRaycasts",!0);r(this,"_isDirty",!1);r(this,"_buffer",[])}get alpha(){return this._alpha}set alpha(e){e!==this._alpha&&(this._alpha=e,this.markDirty())}get isCanvasGroup(){return!0}markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),we.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}applyChangesNow(){this._buffer.length=0;for(const e of C.getComponentsInChildren(this.gameObject,Qi,this._buffer)){const i=e;i.setAlphaFactor&&i.setAlphaFactor(this._alpha)}}}_y([m()],Ro.prototype,"alpha",1);_y([m()],Ro.prototype,"interactable",2);_y([m()],Ro.prototype,"blocksRaycasts",2);class by{get extensionName(){return"tmui"}onExportObject(t,e,i){const n=C.getComponent(t,Za);if(n&&n.enabled&&n.renderMode===lx.WorldSpace){const s=new ff,a=C.getComponent(t,xn),l=C.getComponent(t,Ro),c=new Array;if(a){if(!C.isActiveSelf(t)){const f=C.isActiveSelf(t);C.setActive(t,!0),a.onEnable(),a.updateTransform(),c.push(()=>{a.onDisable(),C.setActive(t,f)})}t.traverse(f=>{if(!C.isActiveInHierarchy(f)){const p=C.isActiveSelf(f);C.setActive(f,!0);const g=C.getComponent(f,Qi);g&&(g.onEnable(),c.push(()=>{g.onDisable()}));const y=C.getComponent(f,xn);y&&(y.onEnable(),y.updateTransform(),y.onApplyTransform(),c.push(()=>{y.onDisable()}));const b=C.getComponent(f,Dt);b&&(b.onEnable(),c.push(()=>{b.onDisable()})),c.push(()=>{C.setActive(f,p)})}}),a.width,a.height;const h=Et.createEmpty(),u=a.shadowComponent;if(e.add(h),u){const f=u.matrix;h.setMatrix(f);const p=new Map,g=new Map;p.set(u,h),g.set(u,l?l.alpha:1),u.traverse(y=>{if(y===u)return;const b=Et.createEmpty();b.setMatrix(y.matrix);const _=y.parent,v=!!_&&typeof _.textContent=="string"&&_.textContent.length>0;let w=g.get(_)||1;const x=C.getComponent(y,Ro);if(x&&(w*=x.alpha),y instanceof d.Mesh&&v){const M=y[Si];M?s.exportText(M.gameObject,b,i):console.error("Error when exporting UI: shadow component owner not found. This is likely a bug.",y)}if(y instanceof d.Mesh&&!v){const M=y.geometry.clone();M.scale(1,1,-1),this.flipWindingOrder(M),b.geometry=M;const R=new d.Color,E=y.material.opacity;R.copy(y.material.color),b.material=new d.MeshBasicMaterial({color:R,opacity:E*w,map:y.material.map,transparent:!0})}p.set(y,b),g.set(y,w);const O=p.get(_);if(!O){console.error("Error when exporting UI: shadow component parent not found!",y,y.parent);return}O.add(b)})}}for(const h of c)h()}}flipWindingOrder(t){const e=t.index.array;for(let i=0,n=e.length/3;i<n;i++){const s=e[i*3];e[i*3]=e[i*3+2],e[i*3+2]=s}t.index.needsUpdate=!0}}const tc=S("debugusdz");function ak(o,t){var l;const e=[],i=C.getComponentsInChildren(o,xt),n=C.getComponentsInChildren(o,Tt),s=new Array,a=new Array;if(t.injectImplicitBehaviours)for(const c of i){if(!c||!c.runtimeAnimatorController||!c.enabled)continue;const h=c.runtimeAnimatorController.activeState;if(!h||!h.motion||!h.motion.clip||((l=h.motion.clip.tracks)==null?void 0:l.length)<1||s.includes(c))continue;const u=new Nc;u.animator=c,u.stateName=h.name,u.trigger="start",u.name="PlayAnimationOnClick_implicitAtStart_"+u.stateName;const f=new d.Object3D;C.addComponent(f,u),a.push(f),s.push(c),o.add(f)}else for(const c of i){if(!c||!c.runtimeAnimatorController||!c.enabled)continue;tc&&console.log(c);const h=[];for(const u of c.runtimeAnimatorController.enumerateActions()){tc&&console.log(u);const f=u.getClip();h.includes(f)||h.push(f)}e.push({root:c.gameObject,clips:h})}if(t.injectImplicitBehaviours)for(const c of n){if(!c||!c.clip||!c.enabled||!c.playAutomatically||s.includes(c))continue;const h=new Nc;h.animation=c,h.stateName=c.clip.name,h.trigger="start",h.name="PlayAnimationOnClick_implicitAtStart_"+h.stateName;const u=new d.Object3D;C.addComponent(u,h),a.push(u),s.push(c),o.add(u)}else for(const c of n){tc&&console.log(c);const h=[];for(const u of c.animations)h.includes(u)||h.push(u);e.push({root:c.gameObject,clips:h})}tc&&(e==null?void 0:e.length)>0&&console.log("USDZ Animation Clips without behaviours",e);for(const c of e)for(const h of c.clips)t.registerAnimation(c.root,h);return a}function lk(o,t){const e=C.getComponentsInChildren(o,qi),i=C.getComponentsInChildren(o,Oo),n=new Array,s=new Array;tc&&console.log({audioSources:e,playAudioOnClicks:i});for(const a of i){if(!a.target)continue;const l=e.indexOf(a.target);l>-1&&e.splice(l,1)}for(const a of e){if(!a||!a.clip||a.volume<=0||n.includes(a))continue;const l=new Oo;l.target=a,l.name="PlayAudioOnClick_implicitAtStart_",l.trigger="start";const c=new d.Object3D;C.addComponent(c,l),console.log("implicit PlayAudioOnStart",c,l),s.push(c),n.push(a),o.add(c)}return s}function ck(o){return new vt("DisableAtStart",wt.sceneStartTrigger(),fe.fadeAction(o,0,!1))}function Tb(o,t){const e=o.domElement.shadowRoot.querySelector("link[rel='ar']");if(e)return e;const i=document.createElement("div");i.classList.add("menu"),i.classList.add("quicklook-menu"),i.style.display="none",i.style.visibility="hidden";const n=document.createElement("button");n.id="open-in-ar",t?(n.innerText="View in AR",n.title="View this scene in AR. The scene will be exported to USDZ and opened with Apple's QuickLook."):(n.innerText="View in AR",n.title="Download this scene for AR. Open the downloaded USDZ file to view it in AR using Apple's QuickLook."),i.appendChild(n);const s=document.createElement("a");s.id="needle-usdz-link",s.style.display="none",s.rel="ar",s.href="",s.target="_blank",i.appendChild(s);const a=document.createElement("img");return a.id="button",s.appendChild(a),o.domElement.shadowRoot.appendChild(i),s}var hk=Object.defineProperty,Ct=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&hk(t,e,n),n};const gi=S("debugusdz"),dk=S("debugusdzpruning");class qr{constructor(){r(this,"callToAction");r(this,"checkoutTitle");r(this,"checkoutSubtitle");r(this,"callToActionURL")}}Ct([m()],qr.prototype,"callToAction");Ct([m()],qr.prototype,"checkoutTitle");Ct([m()],qr.prototype,"checkoutSubtitle");Ct([m()],qr.prototype,"callToActionURL");var Ps;const fi=(Ps=class extends D{constructor(){super(...arguments);r(this,"objectToExport");r(this,"autoExportAnimations",!0);r(this,"autoExportAudioSources",!0);r(this,"exportFileName");r(this,"customUsdzFile");r(this,"customBranding");r(this,"anchoringType","plane");r(this,"maxTextureSize",2048);r(this,"planeAnchoringAlignment","horizontal");r(this,"interactive",!0);r(this,"physics",!0);r(this,"allowCreateQuicklookButton",!0);r(this,"quickLookCompatible",!0);r(this,"extensions",[]);r(this,"link");r(this,"button");r(this,"onClickedOpenInARElement",e=>{e.preventDefault(),this.exportAndOpen()});r(this,"_currentExportTasks",new Map);r(this,"_previousTimeScale",1);r(this,"lastCallback");r(this,"_rootSessionRootWasAppliedTo",null);r(this,"_rootPositionBeforeExport",new d.Vector3);r(this,"_rootRotationBeforeExport",new d.Quaternion);r(this,"_rootScaleBeforeExport",new d.Vector3)}start(){var e,i,n;gi&&(console.log("USDZExporter",this),console.log("Debug USDZ Mode. Press 'T' to export"),window.addEventListener("keydown",s=>{switch(s.key){case"t":this.exportAndOpen();break}})),this.objectToExport||(this.objectToExport=this.gameObject),!((i=(e=this.objectToExport)==null?void 0:e.children)!=null&&i.length)&&!((n=this.objectToExport)!=null&&n.isMesh)&&(this.objectToExport=this.context.scene)}onEnable(){var n;const e=exports.DeviceUtilities.supportsQuickLookAR(),i=exports.DeviceUtilities.isiOS()||exports.DeviceUtilities.isiPad();!this.button&&(gi||e||i)&&(this.allowCreateQuicklookButton&&(this.button=this.createQuicklookButton()),this.lastCallback=this.quicklookCallback.bind(this),this.link=Tb(this.context,e),this.link.addEventListener("message",this.lastCallback)),gi&&Ee("USDZ Exporter enabled: "+this.name),(n=document.getElementById("open-in-ar"))==null||n.addEventListener("click",this.onClickedOpenInARElement),kc.registerExporter(this)}onDisable(){var e,i,n;(e=this.button)==null||e.remove(),(i=this.link)==null||i.removeEventListener("message",this.lastCallback),gi&&Ee("USDZ Exporter disabled: "+this.name),(n=document.getElementById("open-in-ar"))==null||n.removeEventListener("click",this.onClickedOpenInARElement),kc.unregisterExporter(this)}async exportAsync(){return this.exportAndOpen()}async exportAndOpen(){var n;let e=this.exportFileName??((n=this.objectToExport)==null?void 0:n.name)??this.name;if(e+="-"+Uw(),Qn()||(e!==""&&(e+="-"),e+="MadeWithNeedle"),this.link||(this.link=Tb(this.context,exports.DeviceUtilities.supportsQuickLookAR())),this.customUsdzFile)return gi&&console.log("Exporting custom usdz",this.customUsdzFile),this.openInQuickLook(this.customUsdzFile,e),null;if(!this.objectToExport)return console.warn("No object to export",this),null;const i=await this.export(this.objectToExport);return i?(gi&&console.log("USDZ generation done. Downloading as "+e),this.openInQuickLook(i,e),i):(console.error("USDZ generation failed. Please report a bug",this),null)}async export(e){if(!e)return console.warn("No object to export"),null;const i=this._currentExportTasks.get(e);if(i)return i;const n=this.internalExport(e);return n instanceof Promise?(this._currentExportTasks.set(e,n),n.then(s=>(this._currentExportTasks.delete(e),s)).catch(s=>(this._currentExportTasks.delete(e),console.error("Error during USDZ export – please report a bug!",s),null))):n}async internalExport(e){oe.start("export-usdz",{onProgress:R=>{this.dispatchEvent(new CustomEvent("export-progress",{detail:{progress:R}}))}}),oe.report("export-usdz",{message:"Starting export",totalSteps:40,currentStep:0}),oe.report("export-usdz",{message:"Load progressive textures",autoStep:5}),oe.start("export-usdz-textures","export-usdz");const i=C.getComponentsInChildren(e,ui);for(const R of i)R&&R.enabled&&R.updateSprite(!0);const n=C.getComponentsInChildren(e,Ti),s=new Array;let a=0;for(const R of n){for(const E of R.sharedMeshes)if(E){const F=le.NEEDLE_progressive.assignMeshLOD(E,0);F instanceof Promise&&s.push(new Promise((T,L)=>{F.then(()=>{a++,oe.report("export-usdz-textures",{message:"Loaded progressive mesh",currentStep:a,totalSteps:s.length}),T()}).catch(A=>L(A))}))}for(const E of R.sharedMaterials)if(E){const F=le.NEEDLE_progressive.assignTextureLOD(E,0);F instanceof Promise&&s.push(new Promise((T,L)=>{F.then(()=>{a++,oe.report("export-usdz-textures",{message:"Loaded progressive texture",currentStep:a,totalSteps:s.length}),T()}).catch(A=>L(A))}))}}gi&&Ee("Progressive Loading: "+s.length),await Promise.all(s),gi&&Ee("Progressive Loading: done"),oe.end("export-usdz-textures");const l=Xt.Global.Mask;Xt.Global.Set(Bn.AR);const c=new Ww,h=new rf(this.quickLookCompatible);let u;const f=[];this.interactive&&(f.push(new dy),f.push(new Wr),globalThis.NEEDLE_USE_RAPIER&&C.getComponentsInChildren(e,ot).length>0&&(this.physics?(u=new uy,f.push(u)):j()&&console.warn("USDZExporter: Physics export is disabled, but there are active Rigidbody components in the scene. They will not be exported.")),f.push(new ff),f.push(new by));const p=[h,...f,...this.extensions],g={self:this,exporter:c,extensions:p,object:e};oe.report("export-usdz","Invoking before-export"),this.dispatchEvent(new CustomEvent("before-export",{detail:g})),this.applyWebARSessionRoot(),this._previousTimeScale=this.context.time.timeScale,this.context.time.timeScale=0,oe.report("export-usdz","auto export animations and audio sources");const y=new Array;this.autoExportAnimations&&y.push(...ak(e,h)),p.find(R=>R.extensionName==="Audio")&&this.autoExportAudioSources&&y.push(...lk(e)),c.debug=gi,c.pruneUnusedNodes=!dk;const _=Xa.instance.objs.map(R=>R.batchedMesh);c.keepObject=R=>{let E=!0;const F=C.getComponent(R,Ti);return F&&!F.enabled&&(E=!1),E&&_.includes(R)&&(E=!1),E&&C.getComponentInParent(R,yh)&&(E=!1),E&&C.getComponentInParent(R,ss)&&(E=!1),gi&&!E&&console.log("USDZExporter: Discarding object",R),E},c.beforeWritingDocument=()=>{if(j()&&h&&u){const R=h.animatedRoots;for(const E of R){const F=C.getComponentsInChildren(E,ot).filter(L=>L.enabled),T=C.getComponents(E,di).filter(L=>L.enabled&&!L.isTrigger);(F.length>0||T.length>0)&&console.error("An animated object has physics components in its child hierarchy. This can lead to undefined behaviour due to a bug in Apple's QuickLook (FB15925487). Remove the physics components from child objects or verify that you get the expected results.",E)}}};const v=new Array;this.objectToExport&&this.quickLookCompatible&&this.interactive&&this.objectToExport.traverse(R=>{R.visible||v.push(R)});const w=p.find(R=>R.extensionName==="Behaviour");this.interactive&&w&&v.length>0&&w.addBehavior(ck(v));let x=!0;this.quickLookCompatible&&!this.interactive&&(x=!1),this.anchoringType!=="plane"&&this.anchoringType!=="none"&&this.anchoringType!=="image"&&this.anchoringType!=="face"&&(this.anchoringType="plane"),this.planeAnchoringAlignment!=="horizontal"&&this.planeAnchoringAlignment!=="vertical"&&this.planeAnchoringAlignment!=="any"&&(this.planeAnchoringAlignment="horizontal"),oe.report("export-usdz","Invoking exporter.parse");const O=await c.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:p,quickLookCompatible:this.quickLookCompatible,maxTextureSize:this.maxTextureSize,exportInvisible:x}),M=new Blob([O],{type:"model/vnd.usdz+zip"});this.revertWebARSessionRoot(),this.context.time.timeScale=this._previousTimeScale,oe.report("export-usdz","Invoking after-export"),this.dispatchEvent(new CustomEvent("after-export",{detail:g}));for(const R of y)C.destroy(R);return Xt.Global.Set(l),oe.end("export-usdz"),M}openInQuickLook(e,i){const n=e instanceof Blob?URL.createObjectURL(e):e,s=this.buildQuicklookOverlay();gi&&console.log("QuickLook Overlay",s);const a=s.callToAction?encodeURIComponent(s.callToAction):"",l=s.checkoutTitle?encodeURIComponent(s.checkoutTitle):"",c=s.checkoutSubtitle?encodeURIComponent(s.checkoutSubtitle):"";this.link.href=n+`#callToAction=${a}&checkoutTitle=${l}&checkoutSubtitle=${c}&callToActionURL=${s.callToActionURL}`,this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=i+".usdz",this.link.click()}download(e,i){Ps.save(e,i)}static save(e,i){const n=document.createElement("a");n.style.display="none",document.body.appendChild(n),typeof e=="string"?n.href=e:n.href=URL.createObjectURL(e),n.download=i,n.click(),n.remove()}quicklookCallback(e){if((e==null?void 0:e.data)=="_apple_ar_quicklook_button_tapped"){gi&&me("Quicklook closed via call to action button");var i=new CustomEvent("quicklook-button-tapped",{detail:this});if(this.dispatchEvent(i),!i.defaultPrevented){const n=new URLSearchParams(this.link.href);if(n){const s=n.get("callToActionURL");gi&&Ee("Quicklook url: "+s),s&&(Qn()?globalThis.open(s,"_blank"):console.warn("Quicklook closed: custom redirects require a Needle Engine Pro license: https://needle.tools/pricing",s))}}}}buildQuicklookOverlay(){var n,s,a,l,c,h;const e={};return this.customBranding&&Object.assign(e,this.customBranding),Qn()||(console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing"),e.callToAction="Close",e.checkoutTitle="🌵 Made with Needle",e.checkoutSubtitle="_"),(((n=e.callToAction)==null?void 0:n.length)||((s=e.checkoutTitle)==null?void 0:s.length)||((a=e.checkoutSubtitle)==null?void 0:a.length))&&((l=e.callToAction)!=null&&l.length||(e.callToAction="\0"),(c=e.checkoutTitle)!=null&&c.length||(e.checkoutTitle="\0"),(h=e.checkoutSubtitle)!=null&&h.length||(e.checkoutSubtitle="\0")),this.dispatchEvent(new CustomEvent("quicklook-overlay",{detail:e})),e}getARScaleAndTarget(){if(!this.objectToExport)return{scale:1,_invertForward:!1,target:this.gameObject,sessionRoot:null};const e=C.findObjectOfType(uf);let i=C.getComponentInParent(this.objectToExport,is);i||(i=C.getComponentInChildren(this.objectToExport,is));let n=1,s=!1;const a=this.objectToExport;return e?n=e.arScale:i&&(n=i.arScale,s=i.invertForward),{scale:1/n,_invertForward:s,target:a,sessionRoot:(i==null?void 0:i.gameObject)??null}}applyWebARSessionRoot(){if(!this.objectToExport)return;const{scale:e,_invertForward:i,target:n,sessionRoot:s}=this.getARScaleAndTarget(),a=s==null?void 0:s.matrixWorld.clone().invert();this._rootSessionRootWasAppliedTo=n,this._rootPositionBeforeExport.copy(n.position),this._rootRotationBeforeExport.copy(n.quaternion),this._rootScaleBeforeExport.copy(n.scale),n.scale.multiplyScalar(e),i&&n.quaternion.multiply(Ps.invertForwardQuaternion),n.updateMatrix(),n.updateMatrixWorld(!0),s&&a&&n.matrix.premultiply(a)}revertWebARSessionRoot(){if(!this.objectToExport||!this._rootSessionRootWasAppliedTo)return;const e=this._rootSessionRootWasAppliedTo;e.position.copy(this._rootPositionBeforeExport),e.quaternion.copy(this._rootRotationBeforeExport),e.scale.copy(this._rootScaleBeforeExport),e.updateMatrix(),e.updateMatrixWorld(!0),this._rootSessionRootWasAppliedTo=null}createQuicklookButton(){const i=Mo.getOrCreate().createQuicklookButton();return i.parentNode||this.context.menu.appendChild(i),i}},r(Ps,"invertForwardMatrix",new d.Matrix4().makeRotationY(Math.PI)),r(Ps,"invertForwardQuaternion",new d.Quaternion().setFromEuler(new d.Euler(0,Math.PI,0))),Ps);Ct([m(d.Object3D)],fi.prototype,"objectToExport");Ct([m()],fi.prototype,"autoExportAnimations");Ct([m()],fi.prototype,"autoExportAudioSources");Ct([m()],fi.prototype,"exportFileName");Ct([m(URL)],fi.prototype,"customUsdzFile");Ct([m(qr)],fi.prototype,"customBranding");Ct([m()],fi.prototype,"anchoringType");Ct([m()],fi.prototype,"maxTextureSize");Ct([m()],fi.prototype,"planeAnchoringAlignment");Ct([m()],fi.prototype,"interactive");Ct([m()],fi.prototype,"physics");Ct([m()],fi.prototype,"allowCreateQuicklookButton");Ct([m()],fi.prototype,"quickLookCompatible");let Kn=fi;var uk=Object.defineProperty,fk=Object.getOwnPropertyDescriptor,vy=(o,t,e,i)=>{for(var n=fk(t,e),s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&uk(t,e,n),n};class pl extends D{constructor(){super(...arguments);r(this,"_fog")}get fog(){return this._fog||(this._fog=new d.Fog(0,0,50)),this._fog}get mode(){return 1}set near(e){this.fog.near=e}get near(){return this.fog.near}set far(e){this.fog.far=e}get far(){return this.fog.far}set color(e){this.fog.color.copy(e)}get color(){return this.fog.color}onEnable(){this.scene.fog=this.fog}onDisable(){this.scene.fog===this._fog&&(this.scene.fog=null)}}vy([m()],pl.prototype,"near");vy([m()],pl.prototype,"far");vy([m(d.Color)],pl.prototype,"color");var pk=Object.defineProperty,wy=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&pk(t,e,n),n};class Xr extends D{constructor(){super(...arguments);r(this,"objectBounds",!1);r(this,"color");r(this,"isGizmo",!0);r(this,"_gizmoObject",null);r(this,"_boxHelper",null)}onEnable(){this.isGizmo&&!oh||(this._gizmoObject||(this.objectBounds?this._gizmoObject=new d.BoxHelper(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=hg(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),we.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){var e;for(;this._boxHelper;)(e=this._boxHelper)==null||e.update(),yield}}wy([m()],Xr.prototype,"objectBounds");wy([m(d.Color)],Xr.prototype,"color");wy([m()],Xr.prototype,"isGizmo");var mk=Object.defineProperty,xy=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&mk(t,e,n),n};class ml extends D{constructor(){super(...arguments);r(this,"isGizmo",!1);r(this,"color0");r(this,"color1");r(this,"gridHelper");r(this,"size");r(this,"divisions");r(this,"offset")}onEnable(){if(this.isGizmo&&!oh)return;const e=this.size,i=this.divisions;this.gridHelper||(this.gridHelper=new d.GridHelper(e,i,this.color0??new d.Color(.4,.4,.4),this.color1??new d.Color(.6,.6,.6)),this.offset!==void 0&&(this.gridHelper.position.y+=this.offset)),this.gridHelper&&this.gameObject.add(this.gridHelper)}onDisable(){this.gridHelper&&(this.gameObject.remove(this.gridHelper),this.gridHelper=null)}}xy([m()],ml.prototype,"isGizmo");xy([m(d.Color)],ml.prototype,"color0");xy([m(d.Color)],ml.prototype,"color1");var gk=Object.defineProperty,Sy=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&gk(t,e,n),n};class Cy extends D{constructor(){super(...arguments);r(this,"connectedBody");r(this,"_rigidBody",null)}get rigidBody(){return this._rigidBody}onEnable(){this._rigidBody||(this._rigidBody=this.gameObject.getComponent(ot)),this.rigidBody&&this.connectedBody&&this.startCoroutine(this.create())}*create(){yield,this.rigidBody&&this.connectedBody&&this.activeAndEnabled&&this.createJoint(this.rigidBody,this.connectedBody)}}Sy([m(ot)],Cy.prototype,"connectedBody");class Py extends Cy{createJoint(t,e){var i;(i=this.context.physics.engine)==null||i.addFixedJoint(t,e)}}class kh extends Cy{constructor(){super(...arguments);r(this,"anchor");r(this,"axis")}createJoint(e,i){var n;this.axis&&this.anchor&&((n=this.context.physics.engine)==null||n.addHingeJoint(e,i,this.anchor,this.axis))}}Sy([m(d.Vector3)],kh.prototype,"anchor");Sy([m(d.Vector3)],kh.prototype,"axis");var yk=Object.defineProperty,_k=Object.getOwnPropertyDescriptor,ls=(o,t,e,i)=>{for(var n=i>1?void 0:i?_k(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&yk(t,e,n),n};function Ep(o){return o*Math.PI/180}const Ab=300,Ks=S("debuglights");class pi extends D{constructor(){super(...arguments);r(this,"type",0);r(this,"range",1);r(this,"spotAngle",1);r(this,"innerSpotAngle",1);r(this,"_color",new d.Color(16777215));r(this,"_shadowNearPlane",.1);r(this,"_shadowBias",0);r(this,"_shadowNormalBias",0);r(this,"_overrideShadowBiasSettings",!1);r(this,"_shadows",1);r(this,"lightmapBakeType",4);r(this,"_intensity",-1);r(this,"_shadowDistance");r(this,"shadowWidth");r(this,"shadowHeight");r(this,"_shadowResolution");r(this,"light");r(this,"_webXRStartedListener");r(this,"_webXREndedListener");r(this,"_webARRoot")}set color(e){this._color=e,this.light!==void 0&&(this.light.color=e)}get color(){return this.light?this.light.color:this._color}set shadowNearPlane(e){var i,n;if(e!==this._shadowNearPlane&&(this._shadowNearPlane=e,((n=(i=this.light)==null?void 0:i.shadow)==null?void 0:n.camera)!==void 0)){const s=this.light.shadow.camera;s.near=e}}get shadowNearPlane(){return this._shadowNearPlane}set shadowBias(e){var i,n;e!==this._shadowBias&&(this._shadowBias=e,((n=(i=this.light)==null?void 0:i.shadow)==null?void 0:n.bias)!==void 0&&(this.light.shadow.bias=e,this.light.shadow.needsUpdate=!0))}get shadowBias(){return this._shadowBias}set shadowNormalBias(e){var i,n;e!==this._shadowNormalBias&&(this._shadowNormalBias=e,((n=(i=this.light)==null?void 0:i.shadow)==null?void 0:n.normalBias)!==void 0&&(this.light.shadow.normalBias=e,this.light.shadow.needsUpdate=!0))}get shadowNormalBias(){return this._shadowNormalBias}set shadows(e){this._shadows=e,this.light&&(this.light.castShadow=e!==0,this.updateShadowSoftHard())}get shadows(){return this._shadows}set intensity(e){var i;if(this._intensity=e,this.light){let n=1;if(this.context.isInXR&&this._webARRoot){const s=(i=this._webARRoot)==null?void 0:i.arScale;typeof s=="number"&&s>0&&(n/=s)}this.light.intensity=e*n}Ks&&console.log("Set light intensity to "+this._intensity,e,this)}get intensity(){return this._intensity}get shadowDistance(){const e=this.light;return e!=null&&e.shadow?e.shadow.camera.far:-1}set shadowDistance(e){this._shadowDistance=e;const i=this.light;if(i!=null&&i.shadow){const n=i.shadow.camera;n.far=e,n.updateProjectionMatrix()}}get shadowResolution(){const e=this.light;return e!=null&&e.shadow?e.shadow.mapSize.x:-1}set shadowResolution(e){if(e===this._shadowResolution)return;this._shadowResolution=e;const i=this.light;i!=null&&i.shadow&&(i.shadow.mapSize.set(e,e),i.shadow.needsUpdate=!0)}get isBaked(){return this.lightmapBakeType===2}get selfIsLight(){if(this.gameObject.isLight===!0)return!0;switch(this.gameObject.type){case"SpotLight":case"PointLight":case"DirectionalLight":return!0}return!1}getWorldPosition(e){return this.light?this.type===1?this.light.getWorldPosition(e).multiplyScalar(1):this.light.getWorldPosition(e):e}awake(){this.color=new d.Color(this.color??16777215),Ks&&console.log(this.name,this)}onEnable(){Ks&&console.log("ENABLE LIGHT",this.name),this.createLight(),!this.isBaked&&(this.light&&(this.light.visible=!0,this.light.intensity=this._intensity,Ks&&console.log("Set light intensity to "+this.light.intensity,this.name),this.selfIsLight||this.light.parent!==this.gameObject&&this.gameObject.add(this.light)),this.type===1&&this.startCoroutine(this.updateMainLightRoutine(),we.LateUpdate))}onDisable(){Ks&&console.log("DISABLE LIGHT",this.name),this.light&&(this.selfIsLight?this.light.intensity=0:this.light.visible=!1)}onEnterXR(e){this._webARRoot=C.getComponentInParent(this.gameObject,is)??void 0}onLeaveXR(e){}createLight(){const e=this.selfIsLight;if(e&&!this.light)switch(this.light=this.gameObject,this.light.name=this.name,this._intensity=this.light.intensity,this.type){case 1:this.setDirectionalLight(this.light);break}else if(!this.light)switch(this.type){case 1:const i=new d.DirectionalLight(this.color,this.intensity*Math.PI);if(i.position.set(0,0,-Ab*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(i.target),Pr(i.target,0,0,0),this.light=i,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),Ks){const l=new d.DirectionalLightHelper(this.light,.2,this.color);this.context.scene.add(l)}break;case 0:const n=new d.SpotLight(this.color,this.intensity*Math.PI,this.range,Ep(this.spotAngle/2),1-Ep(this.innerSpotAngle/2)/Ep(this.spotAngle/2),2);n.position.set(0,0,0),n.rotation.set(0,0,0),this.light=n;const s=n.target;n.add(s),s.position.set(0,0,this.range),s.rotation.set(0,0,0);break;case 2:const a=new d.PointLight(this.color,this.intensity*Math.PI,this.range);this.light=a;break}if(this.light){if(this._intensity>=0?this.light.intensity=this._intensity:this._intensity=this.light.intensity,this.shadows!==0?this.light.castShadow=!0:this.light.castShadow=!1,this.light.shadow){this._shadowResolution!==void 0&&this._shadowResolution>4?(this.light.shadow.mapSize.width=this._shadowResolution,this.light.shadow.mapSize.height=this._shadowResolution):(this.light.shadow.mapSize.width=2048,this.light.shadow.mapSize.height=2048),Ks&&console.log("Override shadow bias?",this._overrideShadowBiasSettings,this.shadowBias,this.shadowNormalBias),this.light.shadow.bias=this.shadowBias,this.light.shadow.normalBias=this.shadowNormalBias,this.updateShadowSoftHard();const i=this.light.shadow.camera;if(i.near=this.shadowNearPlane,this._shadowDistance!==void 0&&typeof this._shadowDistance=="number"?i.far=this._shadowDistance:i.far=Ab*Math.abs(this.gameObject.scale.z),this.gameObject.scale.set(1,1,1),this.shadowWidth!==void 0)i.left=-this.shadowWidth/2,i.right=this.shadowWidth/2;else{const n=this.gameObject.scale.x;i.left*=n,i.right*=n}if(this.shadowHeight!==void 0)i.top=this.shadowHeight/2,i.bottom=-this.shadowHeight/2;else{const n=this.gameObject.scale.y;i.top*=n,i.bottom*=n}this.light.shadow.needsUpdate=!0,Ks&&this.context.scene.add(new d.CameraHelper(i))}this.isBaked?this.light.removeFromParent():e||this.gameObject.add(this.light)}}*updateMainLightRoutine(){for(;;){this.type===1&&((!this.context.mainLight||this.intensity>this.context.mainLight.intensity)&&(this.context.mainLight=this),yield);break}}updateShadowSoftHard(){this.light&&this.light.shadow&&(this.shadows===2||(this.light.shadow.radius=1,this.light.shadow.blurSamples=1))}setDirectionalLight(e){e.add(e.target),e.target.position.set(0,0,-1)}}r(pi,"allowChangingRendererShadowMapType",!0);ls([m()],pi.prototype,"type",2);ls([m(d.Color)],pi.prototype,"color",1);ls([m()],pi.prototype,"shadowNearPlane",1);ls([m()],pi.prototype,"shadowBias",1);ls([m()],pi.prototype,"shadowNormalBias",1);ls([m()],pi.prototype,"shadows",1);ls([m()],pi.prototype,"lightmapBakeType",2);ls([m()],pi.prototype,"intensity",1);ls([m()],pi.prototype,"shadowDistance",1);ls([m()],pi.prototype,"shadowResolution",1);new d.Vector3(0,0,0);var bk=Object.defineProperty,Rh=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&bk(t,e,n),n};const Tp=S("debuglods"),vk=S("nolods");class gl{constructor(){r(this,"screenRelativeTransitionHeight");r(this,"distance");r(this,"renderers")}}Rh([m()],gl.prototype,"screenRelativeTransitionHeight");Rh([m()],gl.prototype,"distance");Rh([m(Ti)],gl.prototype,"renderers");class wk{constructor(t){r(this,"model");this.model=t}get renderers(){return this.model.renderers}}class Eh extends D{constructor(){super(...arguments);r(this,"fadeMode",0);r(this,"localReferencePoint");r(this,"lodCount",0);r(this,"size",0);r(this,"animateCrossFading",!1);r(this,"lodModels");r(this,"_lods",[]);r(this,"_settings",[]);r(this,"_lodsHandler");r(this,"_distanceFactor",1)}start(){if(Tp&&console.log("LODGROUP",this.name,this.lodModels,this),!vk&&!this._lodsHandler&&this.gameObject&&this.lodModels&&Array.isArray(this.lodModels)){const e=[];for(const n of this.lodModels){const s=new wk(n);this._lods.push(s);for(const a of s.renderers)e.includes(a)||e.push(a)}this._lodsHandler=new Array;for(let n=0;n<e.length;n++){const s=new d.LOD;this._lodsHandler.push(s),this.gameObject.add(s)}const i=new d.Object3D;i.name="Cull "+this.name;for(let n=0;n<e.length;n++){const s=e[n],a=this._lodsHandler[n],l=s.gameObject;Tp&&console.log(n,l.name);for(const c of this._lods){const h=c.model.distance;let u=null;if(c.renderers.includes(s)?u=l:u=i,u.type==="Group"){console.warn(`LODGroup ${this.name}: Group or MultiMaterial object's are not supported as LOD object: ${u.name}`);continue}Tp&&console.log("LEVEL",u.name,h),a.autoUpdate=!1,this.onAddLodLevel(a,u,c.model.distance)}}}}onAfterRender(){if(!this.gameObject||!this._lodsHandler)return;const e=this.context.mainCamera;if(e)for(const i of this._lodsHandler){i.update(e);const n=i.getCurrentLevel(),s=i.levels[n];i.layers.mask=s.object.layers.mask}}onAddLodLevel(e,i,n){if(i===this.gameObject){console.warn("LODGroup component must be on parent object and not mesh directly at the moment",i.name,i);return}e.addLevel(i,n*this._distanceFactor,.01);const s={lod:e,levelIndex:e.levels.length-1,distance:n};this._settings.push(s)}distanceFactor(e){if(e!==this._distanceFactor){this._distanceFactor=e;for(const i of this._settings){const n=i.lod.levels[i.levelIndex];n.distance=i.distance*e}}}}Rh([m(d.Vector3)],Eh.prototype,"localReferencePoint");Rh([m(gl)],Eh.prototype,"lodModels");var xk=Object.defineProperty,Sk=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&xk(t,e,n),n};const vd=S("debugnestedgltf");class pf extends D{constructor(){super(...arguments);r(this,"filePath");r(this,"loadAssetInParent",!0);r(this,"_isLoadingOrDoneLoading",!1)}listenToProgress(e){var i;(i=this.filePath)==null||i.beginListenDownload(e)}preload(){var e;(e=this.filePath)==null||e.preload()}async start(){var i,n,s,a,l;if(this._isLoadingOrDoneLoading)return;vd&&console.log(this,this.guid);const e=this.gameObject.parent;if(e){this._isLoadingOrDoneLoading=!0;const c=new Sn;c.idProvider=new bt(this.hash(this.guid)),c.parent=this.loadAssetInParent!==!1?e:this.gameObject,this.gameObject.updateMatrix();const h=this.gameObject.matrix;vd&&console.log("Load nested:",((i=this.filePath)==null?void 0:i.url)??this.filePath,this.gameObject.position);const u=await((s=(n=this.filePath)==null?void 0:n.instantiate)==null?void 0:s.call(this.filePath,c));vd&&console.log("Nested loaded:",((a=this.filePath)==null?void 0:a.url)??this.filePath,u),u&&this.loadAssetInParent!==!1&&(u.matrixAutoUpdate=!1,u.matrix.identity(),u.applyMatrix4(h),u.matrixAutoUpdate=!0,u.layers.disableAll(),u.layers.set(this.layer),this.dispatchEvent(new CustomEvent("loaded",{detail:{instance:u,assetReference:this.filePath}}))),vd&&console.log("Nested loading done:",((l=this.filePath)==null?void 0:l.url)??this.filePath,u)}}onDestroy(){var e;(e=this.filePath)==null||e.unload()}hash(e){let i=0;for(let n=0;n<e.length;n++)i=e.charCodeAt(n)+((i<<5)-i);return i}}Sk([m(te)],pf.prototype,"filePath");var Ck=Object.defineProperty,My=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&Ck(t,e,n),n};const Pk=S("debugnet"),mf=class Tm extends D{constructor(){super(...arguments);r(this,"url",null);r(this,"urlParameterName",null);r(this,"localhost",null)}awake(){Pk&&console.log(this),this.context.connection.registerProvider(this)}getWebsocketUrl(){let e=this.url?Tm.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){const a=S(this.urlParameterName);a&&typeof a=="string"&&(e=a)}if(!e)return null;const n=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(e);return n!=null&&n.groups?(n==null?void 0:n.groups.socket_prefix)?e:"wss://"+(n==null?void 0:n.groups.url):null}static GetUrl(e,i){let n=e;const s=Tm.IsLocalNetwork()&&i;if(s&&(n=i),e!=null&&e.startsWith("/")){const a=s?n:window.location.origin;a!=null&&a.endsWith("/")&&e.startsWith("/")&&(e=e.substring(1)),n=a+e}return n}static IsLocalNetwork(e=window.location.hostname){return Yt(e)}};My([m()],mf.prototype,"url");My([m()],mf.prototype,"urlParameterName");My([m()],mf.prototype,"localhost");let Oy=mf;var Mk=Object.defineProperty,gf=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&Mk(t,e,n),n};class Qr extends D{constructor(){super(...arguments);r(this,"referenceSpace");r(this,"from");r(this,"affectPosition",!1);r(this,"affectRotation",!1);r(this,"alignLookDirection",!1);r(this,"levelLookDirection",!1);r(this,"levelPosition",!1);r(this,"positionOffset",new d.Vector3(0,0,0));r(this,"rotationOffset",new d.Vector3(0,0,0));r(this,"offset",new d.Vector3(0,0,0))}update(){if(!this.from)return;var e=Q(this.from),i=_e(this.from);this.offset.copy(this.positionOffset);const n=this.offset.length();if(this.referenceSpace&&this.offset.transformDirection(this.referenceSpace.matrixWorld).multiplyScalar(n),e.add(this.offset),this.levelPosition&&this.referenceSpace){const c=new d.Plane(this.gameObject.up,0),h=Q(this.referenceSpace);c.setFromNormalAndCoplanarPoint(this.gameObject.up,h);const u=new d.Vector3(0,0,0);c.projectPoint(e,u),e.copy(u)}this.affectPosition&&st(this.gameObject,e);const s=new d.Euler(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),a=new d.Quaternion().setFromEuler(s);this.affectRotation&&Gi(this.gameObject,i.multiply(a));const l=new d.Vector3;this.from.getWorldDirection(l).multiplyScalar(50),this.levelLookDirection&&(l.y=0),this.alignLookDirection&&this.gameObject.lookAt(l)}}gf([m(C)],Qr.prototype,"referenceSpace");gf([m(C)],Qr.prototype,"from");gf([m(d.Vector3)],Qr.prototype,"positionOffset");gf([m(d.Vector3)],Qr.prototype,"rotationOffset");var Ok=Object.defineProperty,zo=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&Ok(t,e,n),n};class ai{constructor(t=0,e=0){r(this,"time",0);r(this,"value",0);r(this,"inTangent",1/0);r(this,"inWeight");r(this,"outTangent",1/0);r(this,"outWeight");r(this,"weightedMode");this.time=t,this.value=e}}zo([m()],ai.prototype,"time");zo([m()],ai.prototype,"value");zo([m()],ai.prototype,"inTangent");zo([m()],ai.prototype,"inWeight");zo([m()],ai.prototype,"outTangent");zo([m()],ai.prototype,"outWeight");zo([m()],ai.prototype,"weightedMode");const hx=class ic{constructor(){r(this,"keys",[])}static linearFromTo(t,e,i){const n=new ic,s=new ai;s.time=0,s.value=t;const a=new ai;return a.time=i,a.value=e,n.keys.push(s,a),n}static constant(t){const e=new ic,i=new ai;return i.time=0,i.value=t,e.keys.push(i),e}clone(){var e;const t=new ic;return t.keys=((e=this.keys)==null?void 0:e.map(i=>{const n=new ai;return n.time=i.time,n.value=i.value,n.inTangent=i.inTangent,n.inWeight=i.inWeight,n.outTangent=i.outTangent,n.outWeight=i.outWeight,n.weightedMode=i.weightedMode,n}))||[],t}get duration(){return!this.keys||this.keys.length==0?0:this.keys[this.keys.length-1].time}evaluate(t){if(!this.keys||this.keys.length==0)return 0;if(this.keys.length===1)return this.keys[0].value;if(this.keys[0].time>=t)return this.keys[0].value;for(let e=0;e<this.keys.length;e++){const i=this.keys[e];if(i.time<=t)if(e+1<this.keys.length){const s=this.keys[e+1];if(s.time<t)continue;return!isFinite(i.outTangent)||!isFinite(s.inTangent)?i.value:ic.interpolateValue(t,i,s)}else return i.value}return this.keys[this.keys.length-1].value}static interpolateValue(t,e,i){const n=e.time,s=e.value,a=e.outTangent,l=i.time,c=i.value,h=i.inTangent,u=l-n,f=u*u,p=f*u,g=((a+h)*u-2*(c-s))/p,y=(3*(c-s)-(h+2*a)*u)/f,b=a,_=s,v=t-n,w=v*v,x=w*v;return g*x+y*w+b*v+_}};zo([m(ai)],hx.prototype,"keys");let Th=hx;var kk=Object.defineProperty,P=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&kk(t,e,n),n};const wd=S("debugparticles");var bs=(o=>(o[o.Billboard=0]="Billboard",o[o.Stretch=1]="Stretch",o[o.HorizontalBillboard=2]="HorizontalBillboard",o[o.VerticalBillboard=3]="VerticalBillboard",o[o.Mesh=4]="Mesh",o))(bs||{});class Yr{constructor(){r(this,"alphaKeys",[]);r(this,"colorKeys",[])}get duration(){return 1}evaluate(t,e){let i,n=0,s=null,a=0;for(let l=0;l<this.alphaKeys.length;l++){const c=this.alphaKeys[l];(c.time<t||!i)&&(i=c,n=l)}for(let l=0;l<this.colorKeys.length;l++){const c=this.colorKeys[l];(c.time<t||!s)&&(s=c,a=l)}if(s)if(a+1<this.colorKeys.length){const c=this.colorKeys[a+1],h=z.remap(t,s.time,c.time,0,1);e.r=z.lerp(s.color.r,c.color.r,h),e.g=z.lerp(s.color.g,c.color.g,h),e.b=z.lerp(s.color.b,c.color.b,h)}else e.r=s.color.r,e.g=s.color.g,e.b=s.color.b;if(i)if(n+1<this.alphaKeys.length){const c=this.alphaKeys[n+1],h=z.remap(t,i.time,c.time,0,1);e.alpha=z.lerp(i.alpha,c.alpha,h)}else e.alpha=i.alpha;return e}}P([m()],Yr.prototype,"alphaKeys");P([m()],Yr.prototype,"colorKeys");var Vc=(o=>(o[o.Local=0]="Local",o[o.World=1]="World",o[o.Custom=2]="Custom",o))(Vc||{}),bu=(o=>(o[o.Sphere=0]="Sphere",o[o.SphereShell=1]="SphereShell",o[o.Hemisphere=2]="Hemisphere",o[o.HemisphereShell=3]="HemisphereShell",o[o.Cone=4]="Cone",o[o.Box=5]="Box",o[o.Mesh=6]="Mesh",o[o.ConeShell=7]="ConeShell",o[o.ConeVolume=8]="ConeVolume",o[o.ConeVolumeShell=9]="ConeVolumeShell",o[o.Circle=10]="Circle",o[o.CircleEdge=11]="CircleEdge",o[o.SingleSidedEdge=12]="SingleSidedEdge",o[o.MeshRenderer=13]="MeshRenderer",o[o.SkinnedMeshRenderer=14]="SkinnedMeshRenderer",o[o.BoxShell=15]="BoxShell",o[o.BoxEdge=16]="BoxEdge",o[o.Donut=17]="Donut",o[o.Rectangle=18]="Rectangle",o[o.Sprite=19]="Sprite",o[o.SpriteRenderer=20]="SpriteRenderer",o))(bu||{});const zs=class nc{constructor(){r(this,"mode","Constant");r(this,"constant");r(this,"constantMin");r(this,"constantMax");r(this,"curve");r(this,"curveMin");r(this,"curveMax");r(this,"curveMultiplier")}static constant(t){const e=new nc;return e.setConstant(t),e}static betweenTwoConstants(t,e){const i=new nc;return i.setMinMaxConstant(t,e),i}static curve(t,e=1){const i=new nc;return i.setCurve(t,e),i}setConstant(t){this.mode=0,this.constant=t}setMinMaxConstant(t,e){this.mode=3,this.constantMin=t,this.constantMax=e}setCurve(t,e=1){this.mode=1,this.curve=t,this.curveMultiplier=e}clone(){var e,i,n;const t=new nc;return t.mode=this.mode,t.constant=this.constant,t.constantMin=this.constantMin,t.constantMax=this.constantMax,t.curve=(e=this.curve)==null?void 0:e.clone(),t.curveMin=(i=this.curveMin)==null?void 0:i.clone(),t.curveMax=(n=this.curveMax)==null?void 0:n.clone(),t.curveMultiplier=this.curveMultiplier,t}evaluate(t,e){const i=e===void 0?Math.random():e;switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return t=z.clamp01(t),this.curve.evaluate(t)*this.curveMultiplier;case 2:case"TwoCurves":const n=t*this.curveMin.duration,s=t*this.curveMax.duration;return z.lerp(this.curveMin.evaluate(n),this.curveMax.evaluate(s),i%1)*this.curveMultiplier;case 3:case"TwoConstants":return z.lerp(this.constantMin,this.constantMax,i%1);default:this.curveMax.evaluate(t)*this.curveMultiplier;break}return 0}getMax(){switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return this.getMaxFromCurve(this.curve)*this.curveMultiplier;case 2:case"TwoCurves":return Math.max(this.getMaxFromCurve(this.curveMin),this.getMaxFromCurve(this.curveMax))*this.curveMultiplier;case 3:case"TwoConstants":return Math.max(this.constantMin,this.constantMax);default:return 0}}getMaxFromCurve(t){if(!t)return 0;let e=Number.MIN_VALUE;for(let i=0;i<t.keys.length;i++){const n=t.keys[i];n.value>e&&(e=n.value)}return e}};P([m()],zs.prototype,"mode");P([m()],zs.prototype,"constant");P([m()],zs.prototype,"constantMin");P([m()],zs.prototype,"constantMax");P([m(Th)],zs.prototype,"curve");P([m(Th)],zs.prototype,"curveMin");P([m(Th)],zs.prototype,"curveMax");P([m()],zs.prototype,"curveMultiplier");let q=zs;var Le;const No=(Le=class{constructor(){r(this,"mode",0);r(this,"color");r(this,"colorMin");r(this,"colorMax");r(this,"gradient");r(this,"gradientMin");r(this,"gradientMax")}static constant(t){const e=new Le;return e.constant(t),e}static betweenTwoColors(t,e){const i=new Le;return i.betweenTwoColors(t,e),i}constant(t){return this.mode=0,this.color=t,this}betweenTwoColors(t,e){return this.mode=2,this.colorMin=t,this.colorMax=e,this}evaluate(t,e){const i=e===void 0?Math.random():e;switch(this.mode){case 0:case"Color":return this.color;case 1:case"Gradient":return this.gradient.evaluate(t,Le._temp),Le._temp;case 2:case"TwoColors":return Le._temp.lerpColors(this.colorMin,this.colorMax,i);case 3:case"TwoGradients":return this.gradientMin.evaluate(t,Le._temp),this.gradientMax.evaluate(t,Le._temp2),Le._temp.lerp(Le._temp2,i);case 4:case"RandomColor":const s=Math.random();return this.gradientMin.evaluate(t,Le._temp),this.gradientMax.evaluate(t,Le._temp2),Le._temp.lerp(Le._temp2,s)}return Le._temp.set(16777215),Le._temp.alpha=1,Le._temp}},r(Le,"_temp",new ie(0,0,0,1)),r(Le,"_temp2",new ie(0,0,0,1)),Le);P([m()],No.prototype,"mode");P([m(ie)],No.prototype,"color");P([m(ie)],No.prototype,"colorMin");P([m(ie)],No.prototype,"colorMax");P([m(Yr)],No.prototype,"gradient");P([m(Yr)],No.prototype,"gradientMin");P([m(Yr)],No.prototype,"gradientMax");let Kr=No;var Am=(o=>(o[o.Hierarchy=0]="Hierarchy",o[o.Local=1]="Local",o[o.Shape=2]="Shape",o))(Am||{});class It{constructor(){r(this,"cullingMode");r(this,"duration");r(this,"emitterVelocityMode");r(this,"flipRotation");r(this,"gravityModifier");r(this,"gravityModifierMultiplier");r(this,"loop");r(this,"maxParticles");r(this,"playOnAwake");r(this,"prewarm");r(this,"ringBufferLoopRange");r(this,"ringBufferMode");r(this,"scalingMode");r(this,"simulationSpace");r(this,"simulationSpeed");r(this,"startColor");r(this,"startDelay");r(this,"startDelayMultiplier");r(this,"startLifetime");r(this,"startLifetimeMultiplier");r(this,"startRotation");r(this,"startRotationMultiplier");r(this,"startRotation3D");r(this,"startRotationX");r(this,"startRotationXMultiplier");r(this,"startRotationY");r(this,"startRotationYMultiplier");r(this,"startRotationZ");r(this,"startRotationZMultiplier");r(this,"startSize");r(this,"startSize3D");r(this,"startSizeMultiplier");r(this,"startSizeX");r(this,"startSizeXMultiplier");r(this,"startSizeY");r(this,"startSizeYMultiplier");r(this,"startSizeZ");r(this,"startSizeZMultiplier");r(this,"startSpeed");r(this,"startSpeedMultiplier");r(this,"stopAction");r(this,"useUnscaledTime")}}P([m(q)],It.prototype,"gravityModifier");P([m(Kr)],It.prototype,"startColor");P([m(q)],It.prototype,"startDelay");P([m(q)],It.prototype,"startLifetime");P([m(q)],It.prototype,"startRotation");P([m(q)],It.prototype,"startRotationX");P([m(q)],It.prototype,"startRotationY");P([m(q)],It.prototype,"startRotationZ");P([m(q)],It.prototype,"startSize");P([m(q)],It.prototype,"startSizeX");P([m(q)],It.prototype,"startSizeY");P([m(q)],It.prototype,"startSizeZ");P([m(q)],It.prototype,"startSpeed");class vu{constructor(){r(this,"cycleCount");r(this,"maxCount");r(this,"minCount");r(this,"probability");r(this,"repeatInterval");r(this,"time");r(this,"count");r(this,"_performed",0)}reset(){this._performed=0}run(t){if(t<=this.time)return 0;let e=0;if(this.cycleCount===0||this._performed<this.cycleCount){const i=this.time+this.repeatInterval*this._performed;if(t>=i&&(this._performed+=1,Math.random()<this.probability))switch(this.count.mode){case 0:e=this.count.constant;break;case 3:e=z.lerp(this.count.constantMin,this.count.constantMax,Math.random());break;case 1:e=this.count.curve.evaluate(Math.random());break;case 2:const n=Math.random();e=z.lerp(this.count.curveMin.evaluate(n),this.count.curveMax.evaluate(n),Math.random());break}}return e}}class Ns{constructor(){r(this,"enabled");r(this,"bursts");r(this,"rateOverTime");r(this,"rateOverTimeMultiplier");r(this,"rateOverDistance");r(this,"rateOverDistanceMultiplier");r(this,"system")}get burstCount(){var t;return((t=this.bursts)==null?void 0:t.length)??0}reset(){var t;(t=this.bursts)==null||t.forEach(e=>e.reset())}getBurst(){let t=0;if(this.burstCount>0)for(let e=0;e<this.burstCount;e++){const i=this.bursts[e];this.system.main.loop&&i.time>=this.system.time&&i.reset(),t+=Math.round(i.run(this.system.time))}return t}}P([m()],Ns.prototype,"enabled");P([m()],Ns.prototype,"bursts");P([m(q)],Ns.prototype,"rateOverTime");P([m()],Ns.prototype,"rateOverTimeMultiplier");P([m(q)],Ns.prototype,"rateOverDistance");P([m()],Ns.prototype,"rateOverDistanceMultiplier");class yf{constructor(){r(this,"enabled");r(this,"color")}}P([m(Kr)],yf.prototype,"color");class Zr{constructor(){r(this,"enabled");r(this,"separateAxes");r(this,"size");r(this,"sizeMultiplier");r(this,"x");r(this,"xMultiplier");r(this,"y");r(this,"yMultiplier");r(this,"z");r(this,"zMultiplier");r(this,"_time",0);r(this,"_temp",new d.Vector3)}evaluate(t,e,i){if(e||(e=this._temp),!this.enabled)return e.x=e.y=e.z=1,e;if(this.separateAxes)e.x=this.x.evaluate(t,i)*this.xMultiplier,e.y=this.y.evaluate(t,i)*this.yMultiplier,e.z=this.z.evaluate(t,i)*this.zMultiplier;else{const n=this.size.evaluate(t,i)*this.sizeMultiplier;e.x=n}return e}}P([m(q)],Zr.prototype,"size");P([m(q)],Zr.prototype,"x");P([m(q)],Zr.prototype,"y");P([m(q)],Zr.prototype,"z");var gn;const Ze=(gn=class{constructor(){r(this,"shapeType",5);r(this,"enabled",!0);r(this,"alignToDirection",!1);r(this,"angle",0);r(this,"arc",360);r(this,"arcSpread");r(this,"arcSpeedMultiplier");r(this,"arcMode");r(this,"boxThickness");r(this,"position");r(this,"rotation");r(this,"_rotation",new d.Euler);r(this,"scale");r(this,"radius");r(this,"radiusThickness");r(this,"sphericalDirectionAmount");r(this,"randomDirectionAmount");r(this,"randomPositionAmount");r(this,"meshShapeType");r(this,"meshRenderer");r(this,"_meshObj");r(this,"_meshGeometry");r(this,"system");r(this,"_space");r(this,"_worldSpaceMatrix",new d.Matrix4);r(this,"_worldSpaceMatrixInverse",new d.Matrix4);r(this,"_vector",new d.Vector3(0,0,0));r(this,"_temp",new d.Vector3(0,0,0));r(this,"_triangle",new d.Triangle);r(this,"_dir",new d.Vector3);r(this,"_loopTime",0);r(this,"_loopDirection",1);wd&&console.log(this)}get type(){return bu[this.shapeType]}initialize(t){this.onInitialize(t),t.position.x=this._vector.x,t.position.y=this._vector.y,t.position.z=this._vector.z}toJSON(){return this}clone(){return new gn}setMesh(t){this.meshRenderer=t,t?(this._meshObj=t.sharedMeshes[Math.floor(Math.random()*t.sharedMeshes.length)],this._meshGeometry=this._meshObj.geometry):(this._meshObj=void 0,this._meshGeometry=void 0)}update(t,e){}onUpdate(t,e,i,n){this.system=t,this._space=i,i===1&&(this._worldSpaceMatrix.copy(n.matrixWorld),this._worldSpaceMatrix.elements[0]=1,this._worldSpaceMatrix.elements[5]=1,this._worldSpaceMatrix.elements[10]=1,this._worldSpaceMatrixInverse.copy(this._worldSpaceMatrix).invert())}applyRotation(t){const e=this.rotation.x!==0||this.rotation.y!==0||this.rotation.z!==0;return e&&(this._rotation.x=z.toRadians(this.rotation.x),this._rotation.y=z.toRadians(this.rotation.y),this._rotation.z=z.toRadians(this.rotation.z),this._rotation.order="ZYX",t.applyEuler(this._rotation)),e}onInitialize(t){this._vector.set(0,0,0),t.mesh=void 0,t.mesh_geometry=void 0;const e=this._temp.copy(this.position),i=this._space===1;i&&e.applyQuaternion(this.system.worldQuaternion);let n=this.radius;if(i&&(n*=this.system.worldScale.x),this.enabled){switch(this.shapeType){case 5:wd&&V.DrawWireBox(this.position,this.scale,14540253,1),this._vector.x=Math.random()*this.scale.x-this.scale.x/2,this._vector.y=Math.random()*this.scale.y-this.scale.y/2,this._vector.z=Math.random()*this.scale.z-this.scale.z/2,this._vector.add(e);break;case 4:this.randomConePoint(this.position,this.angle,n,this.radiusThickness,this.arc,this.arcMode,this._vector);break;case 0:this.randomSpherePoint(this.position,n,this.radiusThickness,this.arc,this._vector);break;case 10:this.randomCirclePoint(this.position,n,this.radiusThickness,this.arc,this._vector);break;case 13:const s=this.meshRenderer;(s==null?void 0:s.destroyed)==!1&&this.setMesh(s);const a=t.mesh=this._meshObj,l=t.mesh_geometry=this._meshGeometry;if(a&&l)switch(this.meshShapeType){case 0:{const c=l.getAttribute("position"),h=Math.floor(Math.random()*c.count);this._vector.fromBufferAttribute(c,h),this._vector.applyMatrix4(a.matrixWorld),t.mesh_normal=h}break;case 1:break;case 2:{const c=l.index;if(c){let h=Math.random(),u=Math.random();h+u>1&&(h=1-h,u=1-u);const f=Math.floor(Math.random()*(c.count/3));let p=f*3,g=f*3+1,y=f*3+2;p=c.getX(p),g=c.getX(g),y=c.getX(y);const b=l.getAttribute("position");this._triangle.a.fromBufferAttribute(b,p),this._triangle.b.fromBufferAttribute(b,g),this._triangle.c.fromBufferAttribute(b,y),this._vector.set(0,0,0).addScaledVector(this._triangle.a,h).addScaledVector(this._triangle.b,u).addScaledVector(this._triangle.c,1-(h+u)),this._vector.applyMatrix4(a.matrixWorld),t.mesh_normal=f}}break}break;default:this._vector.set(0,0,0),j()&&!globalThis.__particlesystem_shapetype_unsupported&&(console.warn("ParticleSystem ShapeType is not supported:",bu[this.shapeType]),globalThis.__particlesystem_shapetype_unsupported=!0);break}this.randomizePosition(this._vector,this.randomPositionAmount)}this.applyRotation(this._vector),i&&(this._vector.applyQuaternion(this.system.worldQuaternion),this._vector.add(this.system.worldPos)),wd&&V.DrawSphere(this._vector,.03,16711680,.5,!0)}getDirection(t,e){var i;if(!this.enabled)return this._dir.set(0,0,1),this._dir;switch(this.shapeType){case 5:this._dir.set(0,0,1);break;case 4:this._dir.set(0,0,1);break;case 10:case 0:const n=e.x,s=e.y,a=e.z;this._dir.set(n,s,a),(i=this.system)!=null&&i.worldspace?this._dir.sub(this.system.worldPos):this._dir.sub(this.position);break;case 13:const l=t.mesh,c=t.mesh_geometry;if(l&&c)switch(this.meshShapeType){case 0:{const h=c.getAttribute("normal"),u=t.mesh_normal;this._dir.fromBufferAttribute(h,u)}break;case 1:break;case 2:{const h=c.index;if(h){const u=t.mesh_normal,f=h.getX(u*3),p=h.getX(u*3+1),g=h.getX(u*3+2),y=c.getAttribute("position"),b=$(),_=$(),v=$();b.fromBufferAttribute(y,f),_.fromBufferAttribute(y,p),v.fromBufferAttribute(y,g),b.sub(_),v.sub(_),b.cross(v),this._dir.copy(b).multiplyScalar(-1);const w=_e(l);this._dir.applyQuaternion(w)}}break}break;default:this._dir.set(0,0,1);break}return this._space===1&&this._dir.applyQuaternion(this.system.worldQuaternion),this.applyRotation(this._dir),this._dir.normalize(),this.spherizeDirection(this._dir,this.sphericalDirectionAmount),this.randomizeDirection(this._dir,this.randomDirectionAmount),wd&&(V.DrawSphere(e,.01,8925952,.5,!0),V.DrawDirection(e,this._dir,8925952,.5,!0)),this._dir}randomizePosition(t,e){if(e<=0)return;const i=gn._tempVec;i.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1),i.x*=e*this.scale.x,i.y*=e*this.scale.y,i.z*=e*this.scale.z,t.add(i)}randomizeDirection(t,e){if(e===0)return;const i=gn._randomQuat,n=gn._tempVec;n.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),i.setFromAxisAngle(n,e*Math.random()*Math.PI),t.applyQuaternion(i)}spherizeDirection(t,e){if(e===0)return;const i=Math.random()*Math.PI*2,n=Math.acos(1-Math.random()*2),s=Math.sin(n)*Math.cos(i),a=Math.sin(n)*Math.sin(i),l=Math.cos(n),c=new d.Vector3(s,a,l);t.lerp(c,e)}randomSpherePoint(t,e,i,n,s){const a=Math.random(),l=Math.random(),c=2*Math.PI*a*(n/360),h=Math.acos(2*l-1),u=z.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*e,f=t.x+this.scale.x*(-u*Math.sin(h)*Math.cos(c)),p=t.y+this.scale.y*(u*Math.sin(h)*Math.sin(c)),g=t.z+this.scale.z*(u*Math.cos(h));s.x=f,s.y=p,s.z=g}randomCirclePoint(t,e,i,n,s){const a=Math.random(),l=2*Math.PI*a*(n/360),c=z.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*e,h=t.x+this.scale.x*c*Math.cos(l),u=t.y+this.scale.y*c*Math.sin(l),f=t.z;s.x=h,s.y=u,s.z=f}randomConePoint(t,e,i,n,s,a,l){let c=0,h=0;switch(a){case 0:c=Math.random(),h=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:c=.5,h=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let u=2*Math.PI*c*(s/360);switch(a){case 2:case 1:u+=Math.PI+.5,u+=this._loopTime*Math.PI*2,u%=z.toRadians(s);break}const f=Math.acos(2*h-1),p=z.lerp(1,1-Math.pow(1-Math.random(),Math.PI),n)*i,g=t.x+-p*Math.sin(f)*Math.cos(u),y=t.y+p*Math.sin(f)*Math.sin(u),b=t.z;l.x=g*this.scale.x,l.y=y*this.scale.y,l.z=b*this.scale.z}},r(gn,"_randomQuat",new d.Quaternion),r(gn,"_tempVec",new d.Vector3),gn);P([m()],Ze.prototype,"shapeType");P([m()],Ze.prototype,"enabled");P([m()],Ze.prototype,"alignToDirection");P([m()],Ze.prototype,"angle");P([m()],Ze.prototype,"arc");P([m()],Ze.prototype,"arcSpread");P([m()],Ze.prototype,"arcSpeedMultiplier");P([m()],Ze.prototype,"arcMode");P([m(d.Vector3)],Ze.prototype,"boxThickness");P([m(d.Vector3)],Ze.prototype,"position");P([m(d.Vector3)],Ze.prototype,"rotation");P([m(d.Vector3)],Ze.prototype,"scale");P([m()],Ze.prototype,"radius");P([m()],Ze.prototype,"radiusThickness");P([m()],Ze.prototype,"sphericalDirectionAmount");P([m()],Ze.prototype,"randomDirectionAmount");P([m()],Ze.prototype,"randomPositionAmount");P([m()],Ze.prototype,"meshShapeType");P([m(bh)],Ze.prototype,"meshRenderer");let ky=Ze;class be{constructor(){r(this,"damping");r(this,"enabled");r(this,"frequency");r(this,"octaveCount");r(this,"octaveMultiplier");r(this,"octaveScale");r(this,"positionAmount");r(this,"quality");r(this,"remap");r(this,"remapEnabled");r(this,"remapMultiplier");r(this,"remapX");r(this,"remapXMultiplier");r(this,"remapY");r(this,"remapYMultiplier");r(this,"remapZ");r(this,"remapZMultiplier");r(this,"scrollSpeedMultiplier");r(this,"separateAxes");r(this,"strengthMultiplier");r(this,"strengthX");r(this,"strengthXMultiplier");r(this,"strengthY");r(this,"strengthYMultiplier");r(this,"strengthZ");r(this,"strengthZMultiplier");r(this,"_noise");r(this,"_time",0);r(this,"_temp",new d.Vector3)}update(t){this._time+=t.time.deltaTime*this.scrollSpeedMultiplier}apply(t,e,i,n,s,a){if(!this.enabled)return;this._noise||(this._noise=ae.createNoise4D(()=>0));const l=this._temp.set(e.x,e.y,e.z).multiplyScalar(this.frequency),c=this._noise(l.x,l.y,l.z,this._time),h=this._noise(l.x,l.y,l.z,this._time+1e3*this.frequency),u=this._noise(l.x,l.y,l.z,this._time+2e3*this.frequency);this._temp.set(c,h,u).normalize();const f=s/a;let p=this.positionAmount.evaluate(f);this.separateAxes?(this._temp.x*=p*this.strengthXMultiplier,this._temp.y*=p*this.strengthYMultiplier,this._temp.z*=p*this.strengthZMultiplier):(this.strengthX&&(p*=this.strengthX.evaluate(f)*1.5),this._temp.multiplyScalar(p)),i.x+=this._temp.x,i.y+=this._temp.y,i.z+=this._temp.z}}P([m()],be.prototype,"damping");P([m()],be.prototype,"enabled");P([m()],be.prototype,"frequency");P([m()],be.prototype,"octaveCount");P([m()],be.prototype,"octaveMultiplier");P([m()],be.prototype,"octaveScale");P([m(q)],be.prototype,"positionAmount");P([m()],be.prototype,"quality");P([m(q)],be.prototype,"remap");P([m()],be.prototype,"remapEnabled");P([m()],be.prototype,"remapMultiplier");P([m(q)],be.prototype,"remapX");P([m()],be.prototype,"remapXMultiplier");P([m(q)],be.prototype,"remapY");P([m()],be.prototype,"remapYMultiplier");P([m(q)],be.prototype,"remapZ");P([m()],be.prototype,"remapZMultiplier");P([m()],be.prototype,"scrollSpeedMultiplier");P([m()],be.prototype,"separateAxes");P([m()],be.prototype,"strengthMultiplier");P([m(q)],be.prototype,"strengthX");P([m()],be.prototype,"strengthXMultiplier");P([m(q)],be.prototype,"strengthY");P([m()],be.prototype,"strengthYMultiplier");P([m(q)],be.prototype,"strengthZ");P([m()],be.prototype,"strengthZMultiplier");class je{constructor(){r(this,"enabled");r(this,"attachRibbonToTransform",!1);r(this,"colorOverLifetime");r(this,"colorOverTrail");r(this,"dieWithParticles",!0);r(this,"inheritParticleColor",!0);r(this,"lifetime");r(this,"lifetimeMultiplier");r(this,"minVertexDistance",.2);r(this,"mode",0);r(this,"ratio",1);r(this,"ribbonCount",1);r(this,"shadowBias",0);r(this,"sizeAffectsLifetime",!1);r(this,"sizeAffectsWidth",!1);r(this,"splitSubEmitterRibbons",!1);r(this,"textureMode",0);r(this,"widthOverTrail");r(this,"widthOverTrailMultiplier");r(this,"worldSpace",!1)}getWidth(t,e,i,n){const s=this.widthOverTrail.evaluate(i,n);return t*=s,t}getColor(t,e,i){const n=this.colorOverTrail.evaluate(i),s=this.colorOverLifetime.evaluate(e);t.x*=n.r*s.r,t.y*=n.g*s.g,t.z*=n.b*s.b,"alpha"in n&&"alpha"in s&&(t.w*=n.alpha*s.alpha)}}P([m()],je.prototype,"enabled");P([m()],je.prototype,"attachRibbonToTransform");P([m(Kr)],je.prototype,"colorOverLifetime");P([m(Kr)],je.prototype,"colorOverTrail");P([m()],je.prototype,"dieWithParticles");P([m()],je.prototype,"inheritParticleColor");P([m(q)],je.prototype,"lifetime");P([m()],je.prototype,"lifetimeMultiplier");P([m()],je.prototype,"minVertexDistance");P([m()],je.prototype,"mode");P([m()],je.prototype,"ratio");P([m()],je.prototype,"ribbonCount");P([m()],je.prototype,"shadowBias");P([m()],je.prototype,"sizeAffectsLifetime");P([m()],je.prototype,"sizeAffectsWidth");P([m()],je.prototype,"splitSubEmitterRibbons");P([m()],je.prototype,"textureMode");P([m(q)],je.prototype,"widthOverTrail");P([m()],je.prototype,"widthOverTrailMultiplier");P([m()],je.prototype,"worldSpace");class ze{constructor(){r(this,"enabled");r(this,"space",0);r(this,"orbitalX");r(this,"orbitalY");r(this,"orbitalZ");r(this,"orbitalXMultiplier");r(this,"orbitalYMultiplier");r(this,"orbitalZMultiplier");r(this,"orbitalOffsetX");r(this,"orbitalOffsetY");r(this,"orbitalOffsetZ");r(this,"speedModifier");r(this,"speedModifierMultiplier");r(this,"x");r(this,"xMultiplier");r(this,"y");r(this,"yMultiplier");r(this,"z");r(this,"zMultiplier");r(this,"_system");r(this,"_temp",new d.Vector3);r(this,"_temp2",new d.Vector3);r(this,"_temp3",new d.Vector3);r(this,"_hasOrbital",!1);r(this,"_index",0);r(this,"_orbitalMatrix",new d.Matrix4)}update(t){this._system=t}init(t){this._index==0&&(t.debug=!0),this._index+=1,t.orbitx=this.orbitalX.evaluate(Math.random()),t.orbity=this.orbitalY.evaluate(Math.random()),t.orbitz=this.orbitalZ.evaluate(Math.random()),this._hasOrbital=t.orbitx!=0||t.orbity!=0||t.orbitz!=0}apply(t,e,i,n,s,a,l){var g;if(!this.enabled)return;const c=a/l,h=this.speedModifier.evaluate(c)*this.speedModifierMultiplier,u=this.x.evaluate(c),f=this.y.evaluate(c),p=this.z.evaluate(c);if(this._temp.set(-u,f,p),this._system&&this._system.main.simulationSpace===1&&this._temp.applyQuaternion(this._system.worldQuaternion),this._hasOrbital&&((g=this._system)==null?void 0:g.worldPos)){const b=this._temp2.set(i.x,i.y,i.z),_=this.orbitalXMultiplier,v=this.orbitalYMultiplier,w=this.orbitalZMultiplier,x=h*Math.PI*2*10,O=Math.cos(x*_),M=Math.sin(x*_),R=Math.cos(x*v),E=Math.sin(x*v),F=Math.cos(x*w),T=Math.sin(x*w),L=b.x*(R*F)+b.y*(R*T)+b.z*-E,A=b.x*(M*E*F-O*T)+b.y*(M*E*T+O*F)+b.z*(M*R),H=b.x*(O*E*F+M*T)+b.y*(O*E*T-M*F)+b.z*(O*R),B=this._temp3.set(b.x-L,b.y-A,b.z-H);B.normalize(),B.multiplyScalar(.2/s*Math.max(this.orbitalXMultiplier,this.orbitalYMultiplier,this.orbitalZMultiplier)),n.x+=B.x,n.y+=B.y,n.z+=B.z}n.x+=this._temp.x,n.y+=this._temp.y,n.z+=this._temp.z,n.x*=h,n.y*=h,n.z*=h}}P([m()],ze.prototype,"enabled");P([m()],ze.prototype,"space");P([m(q)],ze.prototype,"orbitalX");P([m(q)],ze.prototype,"orbitalY");P([m(q)],ze.prototype,"orbitalZ");P([m()],ze.prototype,"orbitalXMultiplier");P([m()],ze.prototype,"orbitalYMultiplier");P([m()],ze.prototype,"orbitalZMultiplier");P([m()],ze.prototype,"orbitalOffsetX");P([m()],ze.prototype,"orbitalOffsetY");P([m()],ze.prototype,"orbitalOffsetZ");P([m(q)],ze.prototype,"speedModifier");P([m()],ze.prototype,"speedModifierMultiplier");P([m(q)],ze.prototype,"x");P([m()],ze.prototype,"xMultiplier");P([m(q)],ze.prototype,"y");P([m()],ze.prototype,"yMultiplier");P([m(q)],ze.prototype,"z");P([m()],ze.prototype,"zMultiplier");class jt{constructor(){r(this,"animation");r(this,"enabled");r(this,"cycleCount");r(this,"frameOverTime");r(this,"frameOverTimeMultiplier");r(this,"numTilesX");r(this,"numTilesY");r(this,"startFrame");r(this,"startFrameMultiplier");r(this,"rowMode");r(this,"rowIndex");r(this,"spriteCount");r(this,"timeMode")}sampleOnceAtStart(){if(this.timeMode===0)switch(this.frameOverTime.mode){case 0:case 3:case 2:case 1:return!0}return!1}getStartIndex(){return this.sampleOnceAtStart()?Math.random()*(this.numTilesX*this.numTilesY):0}evaluate(t){if(!this.sampleOnceAtStart())return this.getIndex(t)}getIndex(t){const e=this.numTilesX*this.numTilesY;t=t*this.cycleCount;let i=this.frameOverTime.evaluate(t%1);return i*=this.frameOverTimeMultiplier,i*=e,i=i%e,i=Math.floor(i),i}}P([m()],jt.prototype,"animation");P([m()],jt.prototype,"enabled");P([m()],jt.prototype,"cycleCount");P([m(q)],jt.prototype,"frameOverTime");P([m()],jt.prototype,"frameOverTimeMultiplier");P([m()],jt.prototype,"numTilesX");P([m()],jt.prototype,"numTilesY");P([m(q)],jt.prototype,"startFrame");P([m()],jt.prototype,"startFrameMultiplier");P([m()],jt.prototype,"rowMode");P([m()],jt.prototype,"rowIndex");P([m()],jt.prototype,"spriteCount");P([m()],jt.prototype,"timeMode");class Pn{constructor(){r(this,"enabled");r(this,"separateAxes");r(this,"x");r(this,"xMultiplier");r(this,"y");r(this,"yMultiplier");r(this,"z");r(this,"zMultiplier")}evaluate(t,e){return this.enabled?this.separateAxes?0:this.z.evaluate(t,e)*-1:0}}P([m()],Pn.prototype,"enabled");P([m()],Pn.prototype,"separateAxes");P([m(q)],Pn.prototype,"x");P([m()],Pn.prototype,"xMultiplier");P([m(q)],Pn.prototype,"y");P([m()],Pn.prototype,"yMultiplier");P([m(q)],Pn.prototype,"z");P([m()],Pn.prototype,"zMultiplier");class Ji{constructor(){r(this,"enabled");r(this,"range");r(this,"separateAxes");r(this,"x");r(this,"xMultiplier");r(this,"y");r(this,"yMultiplier");r(this,"z");r(this,"zMultiplier")}evaluate(t,e){if(!this.enabled)return 0;if(!this.separateAxes){const i=z.lerp(this.range.x,this.range.y,e);return this.z.evaluate(i)*-1}return 0}}P([m()],Ji.prototype,"enabled");P([m()],Ji.prototype,"range");P([m()],Ji.prototype,"separateAxes");P([m(q)],Ji.prototype,"x");P([m()],Ji.prototype,"xMultiplier");P([m(q)],Ji.prototype,"y");P([m()],Ji.prototype,"yMultiplier");P([m(q)],Ji.prototype,"z");P([m()],Ji.prototype,"zMultiplier");class lt{constructor(){r(this,"enabled");r(this,"dampen");r(this,"drag");r(this,"dragMultiplier");r(this,"limit");r(this,"limitMultiplier");r(this,"separateAxes");r(this,"limitX");r(this,"limitXMultiplier");r(this,"limitY");r(this,"limitYMultiplier");r(this,"limitZ");r(this,"limitZMultiplier");r(this,"multiplyDragByParticleSize",!1);r(this,"multiplyDragByParticleVelocity",!1);r(this,"space");r(this,"_temp",new d.Vector3);r(this,"_temp2",new d.Vector3)}apply(t,e,i,n,s,a,l){if(this.enabled){const c=this.limit.evaluate(s)*this.limitMultiplier;if(e.length()>c){this._temp.copy(e).normalize().multiplyScalar(c);const u=this.dampen*.5;e.x=z.lerp(e.x,this._temp.x,u),e.y=z.lerp(e.y,this._temp.y,u),e.z=z.lerp(e.z,this._temp.z,u),i.x=z.lerp(i.x,this._temp.x,u),i.y=z.lerp(i.y,this._temp.y,u),i.z=z.lerp(i.z,this._temp.z,u)}}}}P([m()],lt.prototype,"enabled");P([m()],lt.prototype,"dampen");P([m(q)],lt.prototype,"drag");P([m()],lt.prototype,"dragMultiplier");P([m(q)],lt.prototype,"limit");P([m()],lt.prototype,"limitMultiplier");P([m()],lt.prototype,"separateAxes");P([m(q)],lt.prototype,"limitX");P([m()],lt.prototype,"limitXMultiplier");P([m(q)],lt.prototype,"limitY");P([m()],lt.prototype,"limitYMultiplier");P([m(q)],lt.prototype,"limitZ");P([m()],lt.prototype,"limitZMultiplier");P([m()],lt.prototype,"multiplyDragByParticleSize");P([m()],lt.prototype,"multiplyDragByParticleVelocity");P([m()],lt.prototype,"space");const Ah=class dx{constructor(){r(this,"enabled");r(this,"curve");r(this,"curveMultiplier");r(this,"mode");r(this,"system");r(this,"_temp",new d.Vector3);r(this,"_firstUpdate",!0);r(this,"_frames",0)}clone(){var e;const t=new dx;return t.enabled=this.enabled,t.curve=(e=this.curve)==null?void 0:e.clone(),t.curveMultiplier=this.curveMultiplier,t.mode=this.mode,t}get _lastWorldPosition(){return this.system._iv_lastWorldPosition||(this.system._iv_lastWorldPosition=new d.Vector3),this.system._iv_lastWorldPosition}get _velocity(){return this.system._iv_velocity||(this.system._iv_velocity=new d.Vector3),this.system._iv_velocity}awake(t){this.system=t,this.reset()}reset(){this._firstUpdate=!0}update(t){this.enabled&&this.system.worldspace!==!1&&(this._firstUpdate?(this._firstUpdate=!1,this._velocity.set(0,0,0),this._lastWorldPosition.copy(this.system.worldPos)):this._lastWorldPosition&&(this._velocity.copy(this.system.worldPos).sub(this._lastWorldPosition).multiplyScalar(1/this.system.deltaTime),this._lastWorldPosition.copy(this.system.worldPos)))}applyInitial(t){if(this.enabled&&this.system.worldspace!==!1&&this.mode===0){const e=this.curve.evaluate(Math.random(),Math.random());this._temp.copy(this._velocity).multiplyScalar(e),t.x+=this._temp.x,t.y+=this._temp.y,t.z+=this._temp.z}}applyCurrent(t,e,i){if(this.enabled&&this.system&&this.system.worldspace!==!1&&this.mode===1){const n=this.curve.evaluate(e,i);this._temp.copy(this._velocity).multiplyScalar(n),t.x+=this._temp.x,t.y+=this._temp.y,t.z+=this._temp.z}}};P([m()],Ah.prototype,"enabled");P([m(q)],Ah.prototype,"curve");P([m()],Ah.prototype,"curveMultiplier");P([m()],Ah.prototype,"mode");let Ry=Ah;class mi{constructor(){r(this,"enabled");r(this,"range");r(this,"separateAxes");r(this,"size");r(this,"sizeMultiplier");r(this,"x");r(this,"xMultiplier");r(this,"y");r(this,"yMultiplier");r(this,"z");r(this,"zMultiplier")}evaluate(t,e,i,n){const s=t.length(),a=z.remap(s,this.range.x,this.range.y,0,1),l=this.size.evaluate(a,i);return n.x*=l,n.y*=l,n.z*=l,n}}P([m()],mi.prototype,"enabled");P([m(d.Vector2)],mi.prototype,"range");P([m()],mi.prototype,"separateAxes");P([m(q)],mi.prototype,"size");P([m()],mi.prototype,"sizeMultiplier");P([m(q)],mi.prototype,"x");P([m()],mi.prototype,"xMultiplier");P([m(q)],mi.prototype,"y");P([m()],mi.prototype,"yMultiplier");P([m(q)],mi.prototype,"z");P([m()],mi.prototype,"zMultiplier");class yl{constructor(){r(this,"enabled");r(this,"range");r(this,"color")}evaluate(t,e,i){const n=t.length(),s=z.remap(n,this.range.x,this.range.y,0,1),a=this.color.evaluate(s,e);i.x*=a.r,i.y*=a.g,i.z*=a.b,"alpha"in a&&(i.w*=a.alpha)}}P([m()],yl.prototype,"enabled");P([m(d.Vector2)],yl.prototype,"range");P([m(Kr)],yl.prototype,"color");new d.Vector3(1,1,1);new d.Vector3(0,0,1);class Ey{constructor(t,e,i,n){r(this,"type","NeedleParticleSubEmitter");r(this,"emitterType");r(this,"emitterProbability");r(this,"q_",new d.Quaternion);r(this,"v_",new d.Vector3);r(this,"v2_",new d.Vector3);r(this,"_emitterMatrix",new ae.Matrix4);r(this,"_circularBuffer");this.system=t,this.particleSystem=e,this.subSystem=i,this.subParticleSystem=n,this.subParticleSystem&&this.subParticleSystem&&(this.subParticleSystem.onlyUsedByOther=!0);const s=1e3;this._circularBuffer=new ki(()=>new ae.Matrix4,s)}clone(){throw new Error("Method not implemented.")}initialize(t){t.emissionState={burstIndex:0,burstWaveIndex:0,time:0,waitEmiting:0},this._emitterMatrix.copy(this.subSystem.matrixWorld).invert().premultiply(this.system.matrixWorld),this._emitterMatrix.setPosition(0,0,0),this.emitterType===Lm.Birth&&this.run(t)}update(t,e){this.run(t)}frameUpdate(t){}toJSON(){}reset(){}run(t){if(this.subSystem.currentParticles>=this.subSystem.main.maxParticles||!this.subParticleSystem||!t.emissionState||this.emitterProbability&&Math.random()>this.emitterProbability)return;const e=this.system.deltaTime;if(this.emitterType===Lm.Death){let n=t.life;if(t[Sa]!==void 0&&(n=t[Sa]),!(t.age+e*1.2>=n))return;const a=this.subSystem.main.maxParticles-this.subSystem.currentParticles;t.emissionState.waitEmiting=a}const i=new ae.Matrix4;i.set(1,0,0,t.position.x,0,1,0,t.position.y,0,0,1,t.position.z,0,0,0,1),this.particleSystem.worldSpace||i.multiplyMatrices(this._emitterMatrix,i),this.subParticleSystem.emit(e,t.emissionState,i)}}var Rk=Object.defineProperty,Be=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&Rk(t,e,n),n};const oo=S("debugparticles"),Ek=S("noprogressive"),Tk=S("debugprogressive");var Lm=(o=>(o[o.Birth=0]="Birth",o[o.Collision=1]="Collision",o[o.Death=2]="Death",o[o.Trigger=3]="Trigger",o[o.Manual=4]="Manual",o))(Lm||{});class en extends D{constructor(){super(...arguments);r(this,"renderMode");r(this,"particleMaterial");r(this,"trailMaterial");r(this,"particleMesh");r(this,"maxParticleSize");r(this,"minParticleSize");r(this,"velocityScale");r(this,"cameraVelocityScale");r(this,"lengthScale")}start(){if(this.maxParticleSize!==.5&&this.minParticleSize!==0&&j()){const e=`ParticleSystem "${this.name}" has non-default min/max particle size. This may not render correctly. Please set min size to 0 and the max size to 0.5 and use the "StartSize" setting instead`;console.warn(e)}}get transparent(){var i;return((i=this.particleMaterial)==null?void 0:i.transparent)??!1}getMaterial(e=!1){let i=e===!0&&this.trailMaterial?this.trailMaterial:this.particleMaterial;if(i){if(i.type==="MeshStandardMaterial"){oo&&console.debug("ParticleSystemRenderer.getMaterial: MeshStandardMaterial detected, converting to MeshBasicMaterial. See https://github.com/Alchemist0823/three.quarks/issues/101"),"map"in i&&i.map&&(i.map.colorSpace=d.LinearSRGBColorSpace,i.map.premultiplyAlpha=!1);const n=new d.MeshBasicMaterial;n.copy(i),e?this.trailMaterial=n:this.particleMaterial=n}i.map&&(i.map.colorSpace=d.LinearSRGBColorSpace,i.map.premultiplyAlpha=!1),e&&i.side===d.FrontSide&&(i=i.clone(),i.side=d.BackSide,e?this.trailMaterial=i:this.particleMaterial=i)}return i&&!Ek&&i._didRequestTextureLOD===void 0&&(i._didRequestTextureLOD=0,Tk&&console.log("Load material LOD",i.name),le.NEEDLE_progressive.assignTextureLOD(i,0)),i}getMesh(e){let i=null;if(!i&&(this.particleMesh instanceof d.Mesh&&(i=this.particleMesh.geometry),i===null)){i=new d.PlaneGeometry(1,1);const s=i.attributes.uv;for(let a=0;a<s.count;a++)s.setX(a,1-s.getX(a))}return new d.Mesh(i,this.getMaterial())}}Be([m()],en.prototype,"renderMode");Be([m(d.Material)],en.prototype,"particleMaterial");Be([m(d.Material)],en.prototype,"trailMaterial");Be([m()],en.prototype,"maxParticleSize");Be([m()],en.prototype,"minParticleSize");Be([m()],en.prototype,"velocityScale");Be([m()],en.prototype,"cameraVelocityScale");Be([m()],en.prototype,"lengthScale");class xd{constructor(t,e=1){r(this,"_curve");r(this,"_factor");r(this,"type","function");this._curve=t,this._factor=e}startGen(t){}genValue(t,e){return this._curve.evaluate(e,Math.random())*this._factor}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}}class Ty{constructor(t){r(this,"type","value");r(this,"system");this.system=t}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}startGen(t){}}class Ak extends Ty{genValue(){return this.system.textureSheetAnimation.getStartIndex()}}class Lk extends Ty{constructor(){super(...arguments);r(this,"_lastPosition",new d.Vector3);r(this,"_lastDistance",0)}update(){const e=Q(this.system.gameObject);this._lastDistance=this._lastPosition.distanceTo(e),this._lastPosition.copy(e)}genValue(){if(!this.system.isPlaying||!this.system.emission.enabled||this.system.currentParticles>=this.system.maxParticles)return 0;let e=this.system.emission.rateOverTime.evaluate(this.system.time/this.system.duration,Math.random());if(this.system.deltaTime>0){const s=this.system.emission.rateOverDistance.evaluate(this.system.time/this.system.duration,Math.random());let l=this._lastDistance/this.system.deltaTime*s;Number.isFinite(l)||(l=0),e+=l}const i=this.system.emission.getBurst();i>0&&(e+=i/this.system.deltaTime);const n=this.system.maxParticles-this.system.currentParticles;return z.clamp(e,0,n/this.system.deltaTime)}}class Dk extends Ty{genValue(){return this.system.isPlaying,0}}class Vo{constructor(t){r(this,"system");r(this,"type");this.type=Object.getPrototypeOf(this).constructor.name||"ParticleSystemBaseBehaviour",t&&(this.system=t)}get context(){return this.system.context}initialize(t){}update(t,e){}frameUpdate(t){}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}reset(){}}class Ik extends Vo{constructor(){super(...arguments);r(this,"type","NeedleTextureSheet")}update(e,i){const n=this.system.textureSheetAnimation;if(n.enabled){const s=e.age/e.life,a=n.evaluate(s);a!==void 0&&(e.uvTile=a)}}}const Lb=Symbol("particleRotation");class jk extends Vo{constructor(){super(...arguments);r(this,"type","NeedleRotation")}initialize(e){e[Lb]=Math.random()}update(e,i){if(e.rotation===void 0)return;const n=e.age/e.life;if(typeof e.rotation=="number"&&(this.system.rotationOverLifetime.enabled?e.rotation+=this.system.rotationOverLifetime.evaluate(n,e[Lb])*i:this.system.renderer.renderMode===bs.Billboard&&(e.rotation=Math.PI),this.system.rotationBySpeed.enabled)){const s=e.velocity.length();e.rotation+=this.system.rotationBySpeed.evaluate(n,s)*i}}}const Db=Symbol("sizeLerpFactor"),Bk=new d.Vector3;class Fk extends Vo{constructor(){super(...arguments);r(this,"type","NeedleSize");r(this,"_minSize",0);r(this,"_maxSize",1)}initialize(e){e[Db]=Math.random(),this._minSize=this.system.renderer.minParticleSize,this._maxSize=this.system.renderer.maxParticleSize}update(e,i){const n=e.age/e.life;let s=1;this.system.sizeOverLifetime.enabled&&(s*=this.system.sizeOverLifetime.evaluate(n,void 0,e[Db]).x);let a=1;this.system.renderer.renderMode!==bs.Mesh&&(a=this.system.worldScale.x/this.system.cameraScale);const l=$(e.startSize).multiplyScalar(s*a);if(e.size.set(l.x,l.y,l.z),this.system.localspace){const c=ux(this.system,Bk);e.size.x*=c.x,e.size.y*=c.y,e.size.z*=c.z}}}const Sa=Symbol("particleLife"),Ap=Symbol("trailLifetime"),Ib=Symbol("trailStartLength"),Lp=Symbol("trailWidthRandom");class Uk extends Vo{constructor(){super(...arguments);r(this,"type","NeedleTrail")}initialize(e){e instanceof ae.TrailParticle&&(e[Sa]=e.life,this.system.trails.enabled&&this.system.trails.dieWithParticles===!1&&(e[Ap]=this.system.trails.lifetime.evaluate(Math.random(),Math.random()),e.life+=e[Ap]),e[Ib]=e.length,e[Lp]=Math.random())}update(e){var i;if((i=this.system.trails)!=null&&i.enabled&&e instanceof ae.TrailParticle){const n=e,s=e.age/e[Sa],a=e.previous.values(),l=e.previous.length;for(let c=0;c<l;c++){const u=a.next().value,f=1-c/(l-1),p=e.size;if(p.x<=0&&!this.system.trails.sizeAffectsWidth){const g=20*this.system.trails.widthOverTrail.evaluate(.5,n[Lp]);p.x=g,p.y=g,p.z=g}u.size=this.system.trails.getWidth(p.x,s,f,n[Lp]),u.color.copy(e.color),this.system.trails.getColor(u.color,s,f)}if(e.age>e[Sa]){e.velocity.set(0,0,0);const c=(e.age-e[Sa])/e[Ap];n.length=z.lerp(e[Ib],0,c)}}}}const Sd=Symbol("startVelocity"),jb=Symbol("gravityModifier"),Dp=Symbol("gravitySpeed"),Cd=Symbol("velocity lerp factor"),Dm=new d.Vector3;class zk extends Vo{constructor(){super(...arguments);r(this,"type","NeedleVelocity");r(this,"_gravityDirection",new d.Vector3)}initialize(e){var a,l;const i=this.system.main.simulationSpeed;e.startSpeed=this.system.main.startSpeed.evaluate(Math.random(),Math.random());const n=this.system.shape.getDirection(e,e.position);e.velocity.x=n.x*e.startSpeed,e.velocity.y=n.y*e.startSpeed,e.velocity.z=n.z*e.startSpeed,(a=this.system.inheritVelocity)!=null&&a.enabled&&this.system.inheritVelocity.applyInitial(e.velocity),e[Sd]?e[Sd].copy(e.velocity):e[Sd]=e.velocity.clone();const s=this.system.main.gravityModifier.evaluate(Math.random(),Math.random());e[jb]=s*i,e[Dp]=s*i*.5,e[Cd]=Math.random(),(l=this.system.velocityOverLifetime)==null||l.init(e),this._gravityDirection.set(0,-1,0),this.system.main.simulationSpace===Vc.Local&&this._gravityDirection.applyQuaternion(this.system.worldQuaternionInverted).normalize()}update(e,i){var p;const n=e[Sd],s=e[jb];if(s!==0){const g=s*e[Dp];Dm.copy(this._gravityDirection).multiplyScalar(g),e[Dp]+=i*.05,n.add(Dm)}e.velocity.copy(n);const a=e.age/e.life;(p=this.system.inheritVelocity)!=null&&p.enabled&&this.system.inheritVelocity.applyCurrent(e.velocity,a,e[Cd]);const l=this.system.noise;l.enabled&&l.apply(0,e.position,e.velocity,i,e.age,e.life);const c=this.system.sizeBySpeed;c!=null&&c.enabled&&(e.size=c.evaluate(e.velocity,a,e[Cd],e.size));const h=this.system.colorBySpeed;h!=null&&h.enabled&&h.evaluate(e.velocity,e[Cd],e.color);const u=this.system.velocityOverLifetime;u.enabled&&u.apply(e,0,e.position,e.velocity,i,e.age,e.life);const f=this.system.limitVelocityOverLifetime;if(f.enabled&&f.apply(e.position,n,e.velocity,e.size,a,i,1),this.system.worldspace){const g=this.system.worldScale;e.velocity.x*=g.x,e.velocity.y*=g.y,e.velocity.z*=g.z}}}const Bb=Symbol("colorLerpFactor"),Fb=new ie(1,1,1,1),Yo=new ie(1,1,1,1);class Nk extends Vo{constructor(){super(...arguments);r(this,"type","NeedleColor")}initialize(e){}_init(e){const i=this.system.renderer.particleMaterial;Yo.copy(this.system.main.startColor.evaluate(Math.random())),i!=null&&i.color&&(Fb.copy(i.color),Yo.multiply(Fb)),Yo.convertLinearToSRGB(),e.startColor.set(Yo.r,Yo.g,Yo.b,Yo.alpha),e.color.copy(e.startColor),e[Bb]=Math.random()}update(e,i){if(e.age===0&&this._init(e),this.system.colorOverLifetime.enabled){const n=e.age/e.life,s=this.system.colorOverLifetime.color.evaluate(n,e[Bb]);e.color.set(s.r,s.g,s.b,"alpha"in s?s.alpha:1).multiply(e.startColor)}else e.color.copy(e.startColor)}}class Vk{constructor(t){r(this,"system");r(this,"emission");r(this,"autoDestroy");r(this,"startLength");r(this,"emissionBursts");r(this,"onlyUsedByOther");r(this,"behaviors",[]);r(this,"rendererEmitterSettings",{startLength:new ae.ConstantValue(220),followLocalOrigin:!1});r(this,"flatWhiteTexture");r(this,"clonedTexture",{original:void 0,clone:void 0});this.system=t,this.emission=new Lk(this.system)}get anim(){return this.system.textureSheetAnimation}get prewarm(){return!1}get material(){return this.system.renderer.getMaterial(this.system.trails.enabled)}get layers(){return this.system.gameObject.layers}update(){this.emission.update()}get looping(){return this.system.main.loop}get duration(){return this.system.duration}get shape(){return this.system.shape}get startLife(){return new xd(this.system.main.startLifetime)}get startSpeed(){return new xd(this.system.main.startSpeed)}get startRotation(){return new xd(this.system.main.startRotation)}get startSize(){return new xd(this.system.main.startSize)}get startColor(){return new ae.ConstantColor(new ae.Vector4(1,1,1,1))}get emissionOverTime(){return this.emission}get emissionOverDistance(){return new Dk(this.system)}get instancingGeometry(){return this.system.renderer.getMesh(this.system.renderer.renderMode).geometry}get renderMode(){if(this.system.trails.enabled===!0)return ae.RenderMode.Trail;switch(this.system.renderer.renderMode){case bs.Billboard:return ae.RenderMode.BillBoard;case bs.Stretch:return ae.RenderMode.StretchedBillBoard;case bs.HorizontalBillboard:return ae.RenderMode.HorizontalBillBoard;case bs.VerticalBillboard:return ae.RenderMode.VerticalBillBoard;case bs.Mesh:return ae.RenderMode.Mesh}return ae.RenderMode.BillBoard}get speedFactor(){var e;let t=this.system.main.simulationSpeed;return((e=this.system.renderer)==null?void 0:e.renderMode)===bs.Stretch&&(t*=this.system.renderer.velocityScale??1),t}get texture(){const t=this.material;if(t&&t.map){const e=t.map;if(this.clonedTexture.original!==e||!this.clonedTexture.clone){const i=e.clone();i.premultiplyAlpha=!1,i.colorSpace=d.LinearSRGBColorSpace,this.clonedTexture.original=e,this.clonedTexture.clone=i}return this.clonedTexture.clone}return this.flatWhiteTexture||(this.flatWhiteTexture=Sg(new ie(1,1,1,1),1)),this.flatWhiteTexture}get startTileIndex(){return new Ak(this.system)}get uTileCount(){var t;return this.anim.enabled?(t=this.anim)==null?void 0:t.numTilesX:void 0}get vTileCount(){var t;return this.anim.enabled?(t=this.anim)==null?void 0:t.numTilesY:void 0}get renderOrder(){return 1}get blending(){var t;return((t=this.system.renderer.particleMaterial)==null?void 0:t.blending)??d.NormalBlending}get transparent(){return this.system.renderer.transparent}get worldSpace(){return this.system.main.simulationSpace===Vc.World}}class $k{constructor(){r(this,"burstParticleIndex",0);r(this,"burstParticleCount",0);r(this,"isBursting",!1);r(this,"travelDistance",0);r(this,"previousWorldPos");r(this,"burstIndex",0);r(this,"burstWaveIndex",0);r(this,"time",0);r(this,"waitEmiting",0)}}const Bt=class Nd extends D{constructor(){super(...arguments);r(this,"_state");r(this,"colorOverLifetime");r(this,"main");r(this,"emission");r(this,"sizeOverLifetime");r(this,"shape");r(this,"noise");r(this,"trails");r(this,"velocityOverLifetime");r(this,"limitVelocityOverLifetime");r(this,"inheritVelocity");r(this,"colorBySpeed");r(this,"textureSheetAnimation");r(this,"rotationOverLifetime");r(this,"rotationBySpeed");r(this,"sizeBySpeed");r(this,"_cameraScale",1);r(this,"__worldQuaternion",new d.Quaternion);r(this,"_worldQuaternionInverted",new d.Quaternion);r(this,"_worldScale",new d.Vector3);r(this,"_worldPositionFrame",-1);r(this,"_worldPos",new d.Vector3);r(this,"_renderer");r(this,"_batchSystem");r(this,"_particleSystem");r(this,"_interface");r(this,"_container");r(this,"_time",0);r(this,"_isPlaying",!0);r(this,"_isUsedAsSubsystem",!1);r(this,"_didPreWarm",!1);r(this,"_bursts");r(this,"_subEmitterSystems");r(this,"_lastBatchesCount",-1)}play(e=!1){var i;e&&C.foreachComponent(this.gameObject,n=>{n instanceof Nd&&n!==this&&n.play(!1)},!0),this._isPlaying=!0,this._particleSystem&&(this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1),(i=this.emission)==null||i.reset()}pause(e=!0){e&&C.foreachComponent(this.gameObject,i=>{i instanceof Nd&&i!==this&&i.pause(!1)},!0),this._isPlaying=!1}stop(e=!0,i=!1){e&&C.foreachComponent(this.gameObject,n=>{n instanceof Nd&&n!==this&&n.stop(!1,i)},!0),this._isPlaying=!1,this._time=0,i&&this.reset()}reset(){var e;this._time=0,this._particleSystem&&(this._particleSystem.particleNum=0,this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1,(e=this.emission)==null||e.reset())}emit(e){if(this._particleSystem){this.onUpdate(),e=Math.min(e,this.maxParticles-this.currentParticles),this._state||(this._state=new $k),this._state.waitEmiting=e,this._state.time=0;const i=this._particleSystem.emitEnded;this._particleSystem.emitEnded=!1,this._particleSystem.emit(this.deltaTime,this._state,this._particleSystem.emitter.matrixWorld),this._particleSystem.emitEnded=i}}get playOnAwake(){return this.main.playOnAwake}set playOnAwake(e){this.main.playOnAwake=e}get renderer(){return this._renderer}get isPlaying(){return this._isPlaying}get currentParticles(){var e;return((e=this._particleSystem)==null?void 0:e.particleNum)??0}get maxParticles(){return this.main.maxParticles}get time(){return this._time}get duration(){return this.main.duration}get deltaTime(){return this.context.time.deltaTime*this.main.simulationSpeed}get scale(){return this.gameObject.scale.x}get cameraScale(){return this._cameraScale}get container(){return this._container}get worldspace(){return this.main.simulationSpace===Vc.World}get localspace(){return this.main.simulationSpace===Vc.Local}get worldQuaternion(){return this.__worldQuaternion}get worldQuaternionInverted(){return this._worldQuaternionInverted}get worldScale(){return this._worldScale}get worldPos(){return this._worldPositionFrame!==this.context.time.frame&&(this._worldPositionFrame=this.context.time.frame,Q(this.gameObject,this._worldPos)),this._worldPos}get matrixWorld(){return this._container.matrixWorld}get isSubsystem(){return this._isUsedAsSubsystem}addBehaviour(e){return this._particleSystem?(e instanceof Vo&&(e.system=this),oo&&console.debug("Add custom ParticleSystem Behaviour",e),this._particleSystem.addBehavior(e),!0):!1}removeBehaviour(e){if(!this._particleSystem)return!1;const i=this._particleSystem.behaviors,n=i.indexOf(e);return n!==-1&&((j()||oo)&&console.debug("Remove custom ParticleSystem Behaviour",n,e),i.splice(n,1)),!0}removeAllBehaviours(){return this._particleSystem?(this._particleSystem.behaviors.length=0,!0):!1}get behaviours(){return this._particleSystem?this._particleSystem.behaviors:null}get particleSystem(){return this._particleSystem??null}set bursts(e){for(let i=0;i<e.length;i++){const n=e[i];if(!(n instanceof vu)){const s=new vu;Wa(s,n),e[i]=s}}this._bursts=e}set subEmitterSystems(e){for(let i=0;i<e.length;i++){const n=e[i];if(!(n instanceof wu)){const s=new wu;Wa(s,n),e[i]=s}}oo&&e.length>0&&console.log("SubEmitters: ",e,this),this._subEmitterSystems=e}onAfterDeserialize(e){if(this._subEmitterSystems&&Array.isArray(this._subEmitterSystems))for(const i of this._subEmitterSystems)i._deserialize(this.context,this.gameObject)}awake(){if(this._worldPositionFrame=-1,this._renderer=this.gameObject.getComponent(en),!this.main)throw new Error("Not Supported: ParticleSystem needs a serialized MainModule. Creating new particle systems at runtime is currently not supported.");this._container=new d.Object3D,this._container.matrixAutoUpdate=!1,this.context.scene.add(this._container),this._batchSystem=new ae.BatchedParticleRenderer,this._batchSystem.name=this.gameObject.name,this._container.add(this._batchSystem),this._interface=new Vk(this),this._particleSystem=new ae.ParticleSystem(this._interface),this._particleSystem.addBehavior(new Fk(this)),this._particleSystem.addBehavior(new Nk(this)),this._particleSystem.addBehavior(new Ik(this)),this._particleSystem.addBehavior(new jk(this)),this._particleSystem.addBehavior(new zk(this)),this._particleSystem.addBehavior(new Uk(this)),this._batchSystem.addSystem(this._particleSystem);const e=this._particleSystem.emitter;this.context.scene.add(e),this.inheritVelocity.system&&this.inheritVelocity.system!==this&&(this.inheritVelocity=this.inheritVelocity.clone()),this.inheritVelocity.awake(this),oo&&(console.log(this),this.gameObject.add(new d.AxesHelper(1)))}start(){this.addSubParticleSystems(),this.updateLayers(),this.renderer.particleMesh instanceof d.Mesh&&this._interface.renderMode==ae.RenderMode.Mesh&&le.NEEDLE_progressive.assignMeshLOD(this.renderer.particleMesh,0).then(e=>{e&&this.particleSystem&&this._interface.renderMode==ae.RenderMode.Mesh&&(this.particleSystem.instancingGeometry=e)})}onDestroy(){var e,i,n,s;(e=this._container)==null||e.removeFromParent(),(i=this._batchSystem)==null||i.removeFromParent(),(n=this._particleSystem)==null||n.emitter.removeFromParent(),(s=this._particleSystem)==null||s.dispose()}onEnable(){this.main&&(this.inheritVelocity&&(this.inheritVelocity.system=this),this._batchSystem&&(this._batchSystem.visible=!0),this.playOnAwake&&this.play(),this._isPlaying=this.playOnAwake)}onDisable(){this._batchSystem&&(this._batchSystem.visible=!1)}onBeforeRender(){var e;this.main&&(this._didPreWarm===!1&&((e=this.main)==null?void 0:e.prewarm)===!0&&(this._didPreWarm=!0,this.preWarm()),this.onUpdate(),this.onSimulate(this.deltaTime))}preWarm(){var u;if(!((u=this.emission)!=null&&u.enabled)||this.emission.rateOverTime.getMax()<=0)return;const i=1/60,n=this.main.duration,s=this.main.startLifetime.getMax(),l=Math.min(Math.max(n,s)/Math.max(.01,this.main.simulationSpeed),1e3),c=Math.ceil(l/i),h=Date.now();oo&&console.log(`Particles ${this.name} - Prewarm for ${c} frames (${l} sec). Duration: ${n}, Lifetime: ${s}`);for(let f=0;f<c&&!(this.currentParticles>=this.maxParticles);f++){const p=Date.now()-h;if(p>2e3){console.warn(`Particles ${this.name} - Prewarm took too long. Aborting: ${p}`);break}this.onUpdate(),this.onSimulate(i)}}onSimulate(e){if(this._batchSystem){let i=this.context.time.frameCount%60===0;this._lastBatchesCount!==this._batchSystem.batches.length&&(this._lastBatchesCount=this._batchSystem.batches.length,i=!0),i&&this.updateLayers(),this._batchSystem.update(e)}this._time+=e,this._time>this.duration&&(this._time=0)}updateLayers(){if(this._batchSystem)for(let e=0;e<this._batchSystem.batches.length;e++){const i=this._batchSystem.batches[e];i.layers.disableAll();const n=this.layer;i.layers.mask=1<<n}}onUpdate(){var s,a;if(this._bursts&&(this.emission.bursts=this._bursts,delete this._bursts),!this._isPlaying)return;const e=this.context.mainCamera;if(e){const l=Ue(e);this._cameraScale=l.x}const i=!this.worldspace,n=this.gameObject;if(_e(n,this.__worldQuaternion),this._worldQuaternionInverted.copy(this.__worldQuaternion).invert(),Ue(this.gameObject,this._worldScale),i&&this._container&&((s=this.gameObject)!=null&&s.parent)){const l=ux(this,Dm);this._container.matrix.makeScale(l.x,l.y,l.z),this._container.matrix.makeRotationFromQuaternion(this.__worldQuaternion),this._container.matrix.setPosition(this.worldPos),this._container.matrix.scale(this.gameObject.scale)}this.emission.system=this,this._interface.update(),this.shape.onUpdate(this,this.context,this.main.simulationSpace,this.gameObject),this.noise.update(this.context),(a=this.inheritVelocity)==null||a.update(this.context),this.velocityOverLifetime.update(this)}addSubParticleSystems(){var e;if(this._subEmitterSystems&&this._particleSystem)for(const i of this._subEmitterSystems){i.particleSystem&&(i.particleSystem.__internalAwake?i.particleSystem.__internalAwake():j()&&console.warn("SubParticleSystem serialization issue(?)",i.particleSystem,i));const n=(e=i.particleSystem)==null?void 0:e._particleSystem;if(n){i.particleSystem._isUsedAsSubsystem=!0;const s=new Ey(this,this._particleSystem,i.particleSystem,n);s.emitterType=i.type,s.emitterProbability=i.emitProbability,this._particleSystem.addBehavior(s)}else oo&&console.warn("Could not add SubParticleSystem",i,this)}}};Be([m(yf)],Bt.prototype,"colorOverLifetime");Be([m(It)],Bt.prototype,"main");Be([m(Ns)],Bt.prototype,"emission");Be([m(Zr)],Bt.prototype,"sizeOverLifetime");Be([m(ky)],Bt.prototype,"shape");Be([m(be)],Bt.prototype,"noise");Be([m(je)],Bt.prototype,"trails");Be([m(ze)],Bt.prototype,"velocityOverLifetime");Be([m(lt)],Bt.prototype,"limitVelocityOverLifetime");Be([m(Ry)],Bt.prototype,"inheritVelocity");Be([m(yl)],Bt.prototype,"colorBySpeed");Be([m(jt)],Bt.prototype,"textureSheetAnimation");Be([m(Pn)],Bt.prototype,"rotationOverLifetime");Be([m(Ji)],Bt.prototype,"rotationBySpeed");Be([m(mi)],Bt.prototype,"sizeBySpeed");let $c=Bt;class wu{constructor(){r(this,"particleSystem");r(this,"emitProbability",1);r(this,"properties");r(this,"type")}_deserialize(t,e){const i=this.particleSystem;if(i instanceof $c)return;let n="";i&&typeof i.guid=="string"&&(n=i.guid,this.particleSystem=C.findByGuid(n,e)),oo&&!(this.particleSystem instanceof $c)&&console.warn("Could not find particle system for sub emitter",n,e,this)}}function ux(o,t){if(t.set(1,1,1),o.gameObject.parent&&o.localspace)switch(o.main.scalingMode){case Am.Local:t=Ue(o.gameObject.parent,t),t.x=1/t.x,t.y=1/t.y,t.z=1/t.z;break;default:if(!o.unsupported_scaling_mode){o.unsupported_scaling_mode=!0;const e="ParticleSystem scale mode "+Am[o.main.scalingMode]+" is not supported";j()&&me(e),console.warn(e,o.name,o)}t=Ue(o.gameObject,t);break}return t}class Ja extends D{constructor(){super(...arguments);r(this,"_didAssignPlayerColor",!1);r(this,"tryAssignColor",()=>{const e=C.getComponentInParent(this.gameObject,yn);if(e&&e.owner)return this._didAssignPlayerColor=!0,this.assignUserColor(e.owner),!0;const i=C.getComponentInParent(this.gameObject,At);return i!=null&&i.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(i.connectionId),!0):!1})}onEnable(){this.context.connection.beginListen(ee.JoinedRoom,this.tryAssignColor),this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}onDisable(){this.context.connection.stopListen(ee.JoinedRoom,this.tryAssignColor)}*waitForConnection(){for(;!this.destroyed&&this.activeAndEnabled&&(yield xg(.2),!this.tryAssignColor()););}assignUserColor(e){const i=Ja.hashCode(e),n=Ja.colorFromHashCode(i);if(this.gameObject.type==="Mesh"){const s=this.gameObject;this.assignColor(n,e,s)}else if(this.gameObject.children)for(const s of this.gameObject.children){const a=s;a.material&&a.material.color&&this.assignColor(n,e,a)}}assignColor(e,i,n){let s=n.material;s&&(s._playerMaterial!==i&&(s=s.clone(),s._playerMaterial=i,n.material=s),s.color=e)}static hashCode(e){var i=0,n,s;if(e.length===0)return i;for(n=0;n<e.length;n++)s=e.charCodeAt(n),i=(i<<5)-i+s,i|=0;return i}static colorFromHashCode(e){const i=(e&16711680)>>16,n=(e&65280)>>8,s=e&255;return new d.Color(i/255,n/255,s/255)}}const sc=S("debugpost");let Im=null;function Wk(o){Im=o}function fx(o){let t=o.gameObject;for(;t;){for(const e of Hu(t))if(e.isPostProcessingManager===!0)return e;t=t.parent}return null}function Hk(o){let t=fx(o);if(!t)if(Im){sc&&console.warn("Adding postprocessing manager to the scene.");const e=o.scene;t=Oi(e,Im)}else j()&&console.warn("No post processing manager found");return t}const it={AT_START:-1e4,NormalPass:0,DepthDownsamplingPass:10,SSAO:20,SMAA:30,TiltShift:40,DepthOfField:50,ChromaticAberration:60,Bloom:70,Vignette:80,Pixelation:90,ToneMapping:100,HueSaturation:110,BrightnessContrast:120,Sharpening:130,AT_END:1e4};let qe=null;function Gk(o){sc==="verbose"&&console.debug("Before ordering effects",[...o]),qe||(qe=new Map,qe.set(exports.MODULES.POSTPROCESSING.MODULE.NormalPass,it.NormalPass),qe.set(exports.MODULES.POSTPROCESSING.MODULE.DepthDownsamplingPass,it.DepthDownsamplingPass),qe.set(exports.MODULES.POSTPROCESSING.MODULE.SMAAEffect,it.SMAA),qe.set(exports.MODULES.POSTPROCESSING.MODULE.SSAOEffect,it.SSAO),qe.set(exports.MODULES.POSTPROCESSING_AO.MODULE.N8AOPostPass,it.SSAO),qe.set(exports.MODULES.POSTPROCESSING_AO.MODULE.N8AOPass,it.SSAO),qe.set(exports.MODULES.POSTPROCESSING.MODULE.TiltShiftEffect,it.TiltShift),qe.set(exports.MODULES.POSTPROCESSING.MODULE.DepthOfFieldEffect,it.DepthOfField),qe.set(exports.MODULES.POSTPROCESSING.MODULE.ChromaticAberrationEffect,it.ChromaticAberration),qe.set(exports.MODULES.POSTPROCESSING.MODULE.BloomEffect,it.Bloom),qe.set(exports.MODULES.POSTPROCESSING.MODULE.SelectiveBloomEffect,it.Bloom),qe.set(exports.MODULES.POSTPROCESSING.MODULE.VignetteEffect,it.Vignette),qe.set(exports.MODULES.POSTPROCESSING.MODULE.PixelationEffect,it.Pixelation),qe.set(exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect,it.ToneMapping),qe.set(exports.MODULES.POSTPROCESSING.MODULE.HueSaturationEffect,it.HueSaturation),qe.set(exports.MODULES.POSTPROCESSING.MODULE.BrightnessContrastEffect,it.BrightnessContrast)),o.sort((t,e)=>{const i=typeof t.priority=="number"?t.priority:qe.get(t.effect.constructor)??Number.NEGATIVE_INFINITY,n=typeof e.priority=="number"?e.priority:qe.get(e.effect.constructor)??Number.NEGATIVE_INFINITY;return i===Number.NEGATIVE_INFINITY?(sc&&console.warn("Unknown effect found: ",t.constructor.name,t),1):n===Number.NEGATIVE_INFINITY?(sc&&console.warn("Unknown effect found: ",e.constructor.name,e),-1):i-n}),sc==="verbose"&&console.debug("After ordering effects",[...o])}var qk=Object.defineProperty,Xk=Object.getOwnPropertyDescriptor,px=(o,t,e,i)=>{for(var n=Xk(t,e),s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&qk(t,e,n),n};const Qk=S("debugpost");class U{constructor(t){r(this,"isVolumeParameter",!0);r(this,"_isInitialized",!1);r(this,"_active",!0);r(this,"_value");r(this,"_valueRaw");r(this,"_defaultValue");r(this,"valueProcessor");r(this,"onValueChanged");t!==void 0&&this.initialize(t)}get isInitialized(){return this._isInitialized}initialize(t){t!==void 0&&(this._value=t,this._defaultValue=t,this._valueRaw=t,this._isInitialized=!0)}get overrideState(){return this._active}set overrideState(t){if(this._active===t)return;this._active=t;const e=t?this._valueRaw:this._defaultValue;this.processValue(e,!0)}get value(){return this._valueRaw}set value(t){this.isInitialized||this.initialize(t),this.processValue(t,!1)}set defaultValue(t){this._defaultValue=t}__init(){this.processValue(this._valueRaw,!0)}processValue(t,e){if(t==null||!e&&this.testIfValueChanged(t)===!1)return;const i=this._value;Qk&&typeof i=="number"&&typeof t=="number"&&(i==null||i.toFixed(4),t==null||t.toFixed(4)),!this._active&&this._defaultValue!==void 0?(this._value=this._defaultValue,t=this._defaultValue,this._valueRaw=t):(this._valueRaw=t,this._active&&this.valueProcessor&&(t=this.valueProcessor(t)),this._value=t),this.onValueChanged&&this.onValueChanged(t,i,this)}testIfValueChanged(t){return this._valueRaw!==t}}px([m()],U.prototype,"overrideState");px([m()],U.prototype,"value");class Yk extends Ki{constructor(){super([U])}onSerialize(t,e){}onDeserialize(t,e){const i=e.target,n=e.path;let s;if(i&&n&&(s=i[n]),(typeof s!="object"||typeof s=="object"&&s.isVolumeParameter!==!0)&&(s=new U),typeof t=="object"&&"value"in t){const a=t.value;s.initialize(a),s.overrideState=t.overrideState}else s.value=t;return s}}new Yk;var Kk=Object.defineProperty,Zk=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&Kk(t,e,n),n};const Ip=S("debugpost");class Ye extends D{constructor(e=void 0){super();r(this,"order");r(this,"active",!0);r(this,"_manager",null);r(this,"_result");r(this,"_postprocessingContext",null);if(e)for(const i of Object.keys(e)){const n=e[i],s=this[i];s instanceof U?s.initialize(n):s!==void 0&&(this[i]=n)}}get isPostProcessingEffect(){return!0}onEnable(){super.onEnable(),Ip&&console.warn("Enable",this.constructor.name+(this.__internalDidAwakeAndStart?"":" (awake)")),this.__internalDidAwakeAndStart&&(this.active=!0),this.onEffectEnabled()}onDisable(){var e;super.onDisable(),Ip&&console.warn("Disable",this.constructor.name),(e=this._manager)==null||e.removeEffect(this),this.active=!1}onEffectEnabled(e){e&&e.isPostProcessingManager===!0?this._manager=e:this._manager||(this._manager=Hk(this)),this._manager.addEffect(this),this._manager.dirty=!0}init(){}get postprocessingContext(){return this._postprocessingContext}apply(e){var i;return this._postprocessingContext=e,this._result||(this.initParameters(),this._result=(i=this.onCreateEffect)==null?void 0:i.call(this)),this._result&&this.initParameters(),this._result}unapply(){}dispose(){Ip&&console.warn("DISPOSE",this),this._result&&(Array.isArray(this._result)?this._result.forEach(e=>e.dispose()):this._result.dispose()),this._result=void 0}initParameters(){const e=Object.keys(this);for(const i of e){const n=this[i];n instanceof U&&n.__init()}}onEditorModification(e){const i=e.propertyName;if(this[i]instanceof U){const n=e.value;return this[i].value=n,!0}}}Zk([m()],Ye.prototype,"active");var Jk=Object.defineProperty,eR=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&Jk(t,e,n),n};const tR=S("debugpost"),jm={};function tn(o,t){jm[o]=t}function iR(o){return o.__type in jm?jm[o.__type]:(tR&&o.__type&&console.warn("Unknown postprocessing type",o.__type,o),Ye)}class _f{constructor(){r(this,"components",[])}__init(t){var e;(e=this.components)==null||e.forEach(i=>{i.gameObject===void 0&&t.gameObject.addComponent(i),i.init()})}addEffect(t){this.components.push(t)}removeEffect(t){const e=this.components.indexOf(t);e>=0&&this.components.splice(e,1)}}eR([Br([o=>iR(o),Ye])],_f.prototype,"components");var nR=Object.defineProperty,sR=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&nR(t,e,n),n};const oR=S("debugpost");class Lh extends Ye{constructor(){super(...arguments);r(this,"preset",new U(2))}get typeName(){return"Antialiasing"}onCreateEffect(){var i;const e=new exports.MODULES.POSTPROCESSING.MODULE.SMAAEffect({preset:((i=this.preset)==null?void 0:i.value)??exports.MODULES.POSTPROCESSING.MODULE.SMAAPreset.HIGH,edgeDetectionMode:exports.MODULES.POSTPROCESSING.MODULE.EdgeDetectionMode.LUMA});return this.preset.onValueChanged=n=>{oR&&console.log("Antialiasing preset changed to",n,e),e.applyPreset(n)},e}}sR([m(U)],Lh.prototype,"preset");tn("Antialiasing",Lh);var rR=Object.defineProperty,Ay=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&rR(t,e,n),n},ur;const bf=(ur=class extends Ye{constructor(){super(...arguments);r(this,"threshold",new U(.9));r(this,"intensity",new U(1));r(this,"scatter",new U(.7));r(this,"selectiveBloom")}get typeName(){return"Bloom"}init(){this.threshold.valueProcessor=e=>e,this.intensity.valueProcessor=e=>e,this.scatter.valueProcessor=e=>e}onCreateEffect(){let e;if(this.selectiveBloom==null&&(this.selectiveBloom=ur.useSelectiveBloom),this.selectiveBloom){const i=e=new exports.MODULES.POSTPROCESSING.MODULE.SelectiveBloomEffect(this.context.scene,this.context.mainCamera,{blendFunction:exports.MODULES.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});i.inverted=!0}else e=new exports.MODULES.POSTPROCESSING.MODULE.BloomEffect({blendFunction:exports.MODULES.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});return this.intensity.onValueChanged=i=>{e.intensity=i},this.threshold.onValueChanged=i=>{e.luminanceMaterial.threshold=Math.pow(i,2.2)},this.scatter.onValueChanged=i=>{e.luminancePass.enabled=!0,e.luminanceMaterial.smoothing=i,e.mipmapBlurPass&&(e.mipmapBlurPass.radius=d.MathUtils.lerp(.1,.9,i))},e}},r(ur,"useSelectiveBloom",!1),ur);Ay([m(U)],bf.prototype,"threshold");Ay([m(U)],bf.prototype,"intensity");Ay([m(U)],bf.prototype,"scatter");let vf=bf;tn("Bloom",vf);var aR=Object.defineProperty,lR=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&aR(t,e,n),n};class Dh extends Ye{constructor(){super(...arguments);r(this,"intensity",new U(0))}get typeName(){return"ChromaticAberration"}onCreateEffect(){const e=new exports.MODULES.POSTPROCESSING.MODULE.ChromaticAberrationEffect;return e.offset=new d.Vector2(0,0),e.radialModulation=!0,e.modulationOffset=.15,this.intensity.valueProcessor=i=>i*.02,this.intensity.onValueChanged=i=>{e.offset.x=-i,e.offset.y=i},e}}lR([m(U)],Dh.prototype,"intensity");tn("ChromaticAberration",Dh);var oc=(o=>(o[o.None=0]="None",o[o.Neutral=1]="Neutral",o[o.ACES=2]="ACES",o[o.AgX=3]="AgX",o[o.KhronosNeutral=4]="KhronosNeutral",o))(oc||{});const Ub=new Map;function jp(o){switch(o){case 0:return d.LinearToneMapping;case 1:return d.ReinhardToneMapping;case 2:return d.ACESFilmicToneMapping;case 3:return d.AgXToneMapping;case 4:return d.NeutralToneMapping;default:return Ub.has(o)||(Ub.set(o,!0),console.warn("[Postprocessing] Unknown tone mapping mode",o)),d.NeutralToneMapping}}function cR(o){switch(o){case d.LinearToneMapping:return 0;case d.ACESFilmicToneMapping:return 2;case d.AgXToneMapping:return 3;case d.NeutralToneMapping:return 1;case d.ReinhardToneMapping:return 1;default:return 0}}function Vd(o){switch(o){case d.LinearToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR;case d.ACESFilmicToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.ACES_FILMIC;case d.AgXToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.AGX;case d.NeutralToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.NEUTRAL;case d.ReinhardToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.REINHARD;default:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR}}var hR=Object.defineProperty,mx=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&hR(t,e,n),n};const Bp=S("debugpost");class Eo extends Ye{constructor(){super(...arguments);r(this,"mode",new U(void 0));r(this,"exposure",new U(1));r(this,"_tonemappingEffect",null)}get typeName(){return"ToneMapping"}setMode(e){const i=oc[e];return i===void 0?(console.error("[PostProcessing] Invalid ToneMapping mode",e),this):(this.mode.value=i,this)}get isToneMapping(){return!0}onEffectEnabled(){const e=fx(this);e&&super.onEffectEnabled(e)}onCreateEffect(){var n;if(this.mode.isInitialized==!1){const s=cR(this.context.renderer.toneMapping);Bp&&console.log("[PostProcessing] Initializing ToneMapping mode to renderer.toneMapping",this.context.renderer.toneMapping+" → "+s),this.mode.initialize(s)}(n=this._tonemappingEffect)==null||n.dispose();const e=jp(this.mode.value),i=this._tonemappingEffect=new exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect({mode:Vd(e)});return this.mode.onValueChanged=s=>{if(typeof s=="string")s=Gv(s),i.mode=Vd(s);else{const a=jp(s);i.mode=Vd(a)}i.name="ToneMapping ("+oc[s]+")",Bp&&console.log("[PostProcessing] ToneMapping mode changed to",oc[s],e,i.mode)},Bp&&console.log("[PostProcessing] Use ToneMapping",oc[this.mode.value],e,i.mode,"renderer.tonemapping: "+this.context.renderer.toneMapping),i}onBeforeRender(){var e;if(this._tonemappingEffect&&((e=this.postprocessingContext)!=null&&e.handler.getEffectIsActive(this._tonemappingEffect))&&(this.mode.overrideState&&(this.context.renderer.toneMapping=jp(this.mode.value)),this.exposure.overrideState&&this.exposure.value!==void 0)){const i=Math.max(.01,this.exposure.value);this.context.renderer.toneMappingExposure=i}}}mx([m(U)],Eo.prototype,"mode");mx([m(U)],Eo.prototype,"exposure");tn("Tonemapping",Eo);var dR=Object.defineProperty,wf=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&dR(t,e,n),n};class $o extends Ye{constructor(){super(...arguments);r(this,"remap",!0);r(this,"postExposure",new U(1));r(this,"contrast",new U(0));r(this,"hueShift",new U(0));r(this,"saturation",new U(0))}get typeName(){return"ColorAdjustments"}init(){this.postExposure.valueProcessor=e=>(this.remap&&(e=Math.pow(2,e)),e),this.contrast.valueProcessor=e=>{if(!this.remap)return e;let i=1;return e>0?i=200:e<0&&(i=100),e/i},this.contrast.defaultValue=0,this.hueShift.valueProcessor=e=>this.remap?Math.PI*e/180:e,this.hueShift.defaultValue=0,this.saturation.valueProcessor=e=>this.remap?e<0?e/100:e/(100*Math.PI):e,this.saturation.defaultValue=0}onCreateEffect(){var a,l;const e=[];let i=(a=this.postprocessingContext)==null?void 0:a.components.find(c=>c instanceof Eo);i||(i=new Eo,(l=this.postprocessingContext)==null||l.components.push(i)),this.postExposure.onValueChanged=c=>{this.postExposure.overrideState&&i?i.exposure.value=c:console.warn("[PostProcessing] PostExposure is set to override but no ToneMappingEffect found in the postprocessing stack. Please add a ToneMappingEffect to your postprocessing stack to use PostExposure.")};const n=new exports.MODULES.POSTPROCESSING.MODULE.BrightnessContrastEffect;this.contrast.onValueChanged=c=>n.contrast=c;const s=new exports.MODULES.POSTPROCESSING.MODULE.HueSaturationEffect;return this.hueShift.onValueChanged=c=>s.hue=c,this.saturation.onValueChanged=c=>s.saturation=c,e.push(n),e.push(s),e}}wf([m(U)],$o.prototype,"postExposure");wf([m(U)],$o.prototype,"contrast");wf([m(U)],$o.prototype,"hueShift");wf([m(U)],$o.prototype,"saturation");tn("ColorAdjustments",$o);var uR=Object.defineProperty,Jr=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&uR(t,e,n),n};const fR=S("debugpost");class Mn extends Ye{constructor(){super(...arguments);r(this,"mode");r(this,"focusDistance",new U(1));r(this,"focalLength",new U(.2));r(this,"aperture",new U(20));r(this,"gaussianMaxRadius",new U);r(this,"resolutionScale",new U(1/window.devicePixelRatio));r(this,"bokehScale",new U)}get typeName(){return"DepthOfField"}init(){this.focalLength.valueProcessor=i=>{const n=i/300;return z.lerp(2,.01,n)};const e=20;this.aperture.valueProcessor=i=>{const n=1-i/32;return z.lerp(1,e,n)}}onCreateEffect(){if(this.mode===0){fR&&console.warn("DepthOfField: Mode is set to Off");return}const e=new exports.MODULES.POSTPROCESSING.MODULE.DepthOfFieldEffect(this.context.mainCamera,{worldFocusRange:.2,focalLength:1,bokehScale:20,resolutionScale:this.resolutionScale.value});return this.focusDistance.onValueChanged=i=>{e.cocMaterial.worldFocusDistance=i},this.focalLength.onValueChanged=i=>e.cocMaterial.worldFocusRange=i,this.aperture.onValueChanged=i=>e.bokehScale=i,this.resolutionScale&&(this.resolutionScale.onValueChanged=i=>e.resolution.scale=i),[e]}unapply(){}}Jr([m()],Mn.prototype,"mode");Jr([m(U)],Mn.prototype,"focusDistance");Jr([m(U)],Mn.prototype,"focalLength");Jr([m(U)],Mn.prototype,"aperture");Jr([m(U)],Mn.prototype,"gaussianMaxRadius");Jr([m(U)],Mn.prototype,"resolutionScale");Jr([m(U)],Mn.prototype,"bokehScale");tn("DepthOfField",Mn);class Wc extends Ye{constructor(e){super();r(this,"effect");this.effect=e}get typeName(){return this.effect.constructor.name}onCreateEffect(){return this.effect}}var pR=Object.defineProperty,mR=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&pR(t,e,n),n};class Ih extends Ye{constructor(){super(...arguments);r(this,"granularity",new U(10))}get typeName(){return"PixelationEffect"}onCreateEffect(){const e=new exports.MODULES.POSTPROCESSING.MODULE.PixelationEffect;return this.granularity.onValueChanged=i=>{e.granularity=i},e}}mR([m(U)],Ih.prototype,"granularity");tn("PixelationEffect",Ih);var gR=Object.defineProperty,jh=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&gR(t,e,n),n};class Vs extends Ye{constructor(){super(...arguments);r(this,"intensity",new U(2));r(this,"falloff",new U(1));r(this,"samples",new U(9));r(this,"color",new U(new d.Color(0,0,0)));r(this,"luminanceInfluence",new U(.7));r(this,"_ssao")}get typeName(){return"ScreenSpaceAmbientOcclusion"}onBeforeRender(){if(this._ssao&&this.context.mainCamera instanceof d.PerspectiveCamera){const e=this.context.mainCamera.far-this.context.mainCamera.near;this._ssao.ssaoMaterial.worldDistanceFalloff=e*.01,this._ssao.ssaoMaterial.worldDistanceThreshold=this.context.mainCamera.far}}onCreateEffect(){const e=this.context.mainCamera,i=new exports.MODULES.POSTPROCESSING.MODULE.NormalPass(this.context.scene,e),n=new exports.MODULES.POSTPROCESSING.MODULE.DepthDownsamplingPass({normalBuffer:i.texture,resolutionScale:.5}),s=this._ssao=new exports.MODULES.POSTPROCESSING.MODULE.SSAOEffect(e,i.texture,{normalDepthBuffer:n.texture,worldDistanceThreshold:1,worldDistanceFalloff:1,worldProximityThreshold:.1,worldProximityFalloff:2,intensity:1,blendFunction:exports.MODULES.POSTPROCESSING.MODULE.BlendFunction.MULTIPLY,luminanceInfluence:.5});this.intensity.onValueChanged=l=>{s.intensity=l},this.falloff.onValueChanged=l=>{s.ssaoMaterial.radius=l*.1},this.samples.onValueChanged=l=>{s.ssaoMaterial.samples=l},this.color.onValueChanged=l=>{s.color||(s.color=new d.Color),s.color.copy(l)},this.luminanceInfluence.onValueChanged=l=>{s.luminanceInfluence=l};const a=new Array;return a.push(i),a.push(n),a.push(s),a}}jh([m(U)],Vs.prototype,"intensity");jh([m(U)],Vs.prototype,"falloff");jh([m(U)],Vs.prototype,"samples");jh([m(U)],Vs.prototype,"color");jh([m(U)],Vs.prototype,"luminanceInfluence");tn("ScreenSpaceAmbientOcclusion",Vs);var yR=Object.defineProperty,ea=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&yR(t,e,n),n};const _R=S("debugN8AO");var Bm=(o=>(o[o.Performance=0]="Performance",o[o.Low=1]="Low",o[o.Medium=2]="Medium",o[o.High=3]="High",o[o.Ultra=4]="Ultra",o))(Bm||{});class On extends Ye{constructor(){super(...arguments);r(this,"gammaCorrection",!0);r(this,"aoRadius",new U(1));r(this,"falloff",new U(1));r(this,"intensity",new U(1));r(this,"color",new U(new d.Color(0,0,0)));r(this,"screenspaceRadius",!1);r(this,"quality",2);r(this,"_ssao")}get typeName(){return"ScreenSpaceAmbientOcclusionN8"}get pass(){return this._ssao}onValidate(){this._ssao&&(this._ssao.setQualityMode(Bm[this.quality]),this._ssao.configuration.gammaCorrection=this.gammaCorrection,this._ssao.configuration.screenSpaceRadius=this.screenspaceRadius)}onCreateEffect(){const e=this.context.mainCamera,i=this.context.domWidth,n=this.context.domHeight,s=this._ssao=new exports.MODULES.POSTPROCESSING_AO.MODULE.N8AOPostPass(this.context.scene,e,i,n);s.name="SSAO N8";const a=Bm[this.quality];s.setQualityMode(a),s.configuration.transparencyAware=!1;const l=new d.WebGLRenderTarget(i,n);return s.configuration.beautyRenderTarget=l,s.configuration.autoRenderBeauty=!1,s.configuration.gammaCorrection=this.gammaCorrection,s.configuration.screenSpaceRadius=this.screenspaceRadius,_R&&(s.enableDebugMode(),console.log(s),setInterval(()=>{console.log("SSAO",s.lastTime)},1e3),setInterval(()=>{console.log("SSAO",s.enabled,{ssao:s,autoRenderBeauty:s.configuration.autoRenderBeauty})},4e3)),this.intensity.onValueChanged=c=>{s.configuration.intensity=c},this.falloff.onValueChanged=c=>{s.configuration.distanceFalloff=c},this.aoRadius.onValueChanged=c=>{s.configuration.aoRadius=c},this.color.onValueChanged=c=>{s.color||(s.color=new d.Color),s.configuration.color.copy(c)},s}}ea([St(),m()],On.prototype,"gammaCorrection");ea([m(U)],On.prototype,"aoRadius");ea([m(U)],On.prototype,"falloff");ea([m(U)],On.prototype,"intensity");ea([m(U)],On.prototype,"color");ea([St(),m()],On.prototype,"screenspaceRadius");ea([St(),m()],On.prototype,"quality");tn("ScreenSpaceAmbientOcclusionN8",On);var bR=Object.defineProperty,vR=Object.getOwnPropertyDescriptor,gx=(o,t,e,i)=>{for(var n=vR(t,e),s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&bR(t,e,n),n};class Bh extends Ye{constructor(){super(...arguments);r(this,"order",it.Sharpening);r(this,"_effect");r(this,"_amount",1);r(this,"_radius",1)}get typeName(){return"Sharpening"}onCreateEffect(){return this._effect??(this._effect=new(wR())),this.effect}get effect(){return this._effect}set amount(e){this._amount=e,this._effect&&(this._effect.uniforms.get("amount").value=e)}get amount(){return this._effect?this._effect.uniforms.get("amount").value:this._amount}set radius(e){this._radius=e,this._effect&&(this._effect.uniforms.get("radius").value=e)}get radius(){return this._effect?this._effect.uniforms.get("radius").value:this._radius}}gx([m()],Bh.prototype,"amount");gx([m()],Bh.prototype,"radius");function wR(){const o=`
1273
+ `)}a&&s.size&&console.log(f);const y=new Set;for(const v of g){v.getPath||console.error("USDZExporter: Animation target object has no getPath method. This is likely a bug",v);let w=v.getPath();w.startsWith("<")&&(w=w.substring(1)),w.endsWith(">")&&(w=w.substring(0,w.length-1)),y.add({path:w,obj:v})}const b=Array.from(y).sort((v,w)=>v.path.length-w.path.length),_=new Array;for(let v=0;v<b.length;v++)for(let w=v+1;w<b.length;w++)if(b[w].path.startsWith(b[v].path)){const x=b[w],O=b[v];_.push({child:x.obj.displayName+" ("+x.path+")",parent:O.obj.displayName+" ("+O.path+")"})}_.length&&console.warn("USDZExporter: There are overlapping PlayAnimation actions. This can lead to undefined runtime behaviour when playing multiple animations. Please restructure the hierarchy so that animations don't overlap.",{overlappingTargets:_,playAnimationActions:s})}for(const f of new Set([...e,...i]))if(Array.isArray(f))for(const p of f)n.add(p.uuid);else n.add(f.uuid);yd&&console.log("All Behavior trigger sources and action targets",e,i,n),this.targetUuids=new Set(n)}onAfterHierarchy(t,e){var i;if((i=this.behaviours)!=null&&i.length){e.beginBlock('def Scope "Behaviors"');for(const n of this.behaviours)n.writeTo(this,t.document,e);e.closeBlock()}}async onAfterSerialize(t){yd&&console.log("onAfterSerialize behaviours",this.behaviourComponentsCopy);for(const e of this.behaviourComponentsCopy)typeof e.afterSerialize=="function"&&(e.afterSerialize.constructor.name==="AsyncFunction"?await e.afterSerialize(this,t):e.afterSerialize(this,t));for(const{clipUrl:e,filesKey:i}of this.audioClipsCopy){if(t.files[i])return;const a=await(await(await fetch(e)).blob()).arrayBuffer(),l=new Uint8Array(a);t.files[i]=l}this.behaviourComponentsCopy.length=0,this.audioClipsCopy.length=0}}class uy{get extensionName(){return"Physics"}onExportObject(t,e,i){const n=C.getComponents(t,ot).filter(c=>c.enabled),s=C.getComponents(t,di).filter(c=>c.enabled&&!c.isTrigger);let a=n.length>0?n[0]:null;const l=s.length>0?s[0]:null;l&&!a&&(a=new ot,a.isKinematic=!0),a&&e.addEventListener("serialize",(c,h)=>{var u,f,p;if(a){if(c.appendLine(),c.beginBlock('def RealityKitComponent "RigidBody"',"{",!0),a.useGravity||c.appendLine("bool gravityEnabled = 0"),c.appendLine('uniform token info:id = "RealityKit.RigidBody"'),a.isKinematic&&c.appendLine('token motionType = "Kinematic"'),c.beginBlock('def RealityKitStruct "massFrame"',"{",!0),c.appendLine(`float m_mass = ${a.mass}`),c.beginBlock('def RealityKitStruct "m_pose"',"{",!0),c.appendLine(`float3 position = (${a.centerOfMass.x}, ${a.centerOfMass.y}, ${a.centerOfMass.z})`),c.closeBlock("}"),c.closeBlock("}"),s.length>0){const g=s[0];c.beginBlock('def RealityKitStruct "material"',"{",!0);const y=g.sharedMaterial;y&&y.dynamicFriction!==void 0&&c.appendLine(`double dynamicFriction = ${(u=g.sharedMaterial)==null?void 0:u.dynamicFriction}`),y&&y.bounciness!==void 0&&c.appendLine(`double restitution = ${(f=g.sharedMaterial)==null?void 0:f.bounciness}`),y&&y.staticFriction!==void 0&&c.appendLine(`double staticFriction = ${(p=g.sharedMaterial)==null?void 0:p.staticFriction}`),c.closeBlock("}")}c.closeBlock("}")}}),l&&(e.addEventListener("serialize",(c,h)=>{var p;c.beginBlock('def RealityKitComponent "Collider"',"{",!0),c.appendLine("uint group = 1"),c.appendLine('uniform token info:id = "RealityKit.Collider"'),c.appendLine("uint mask = 4294967295");const f=l.isTrigger?"Trigger":"Default";if(c.appendLine(`token type = "${f}"`),c.beginBlock('def RealityKitStruct "Shape"',"{",!0),l instanceof rl){const g=l;c.appendLine('token shapeType = "Sphere"'),c.appendLine(`float radius = ${g.radius}`)}else if(l instanceof ef){const g=l;c.appendLine('token shapeType = "Box"'),c.appendLine(`float3 extent = (${g.size.x}, ${g.size.y}, ${g.size.z})`)}else if(l instanceof As){const g=l;c.appendLine('token shapeType = "Capsule"'),c.appendLine(`float radius = ${g.radius}`),c.appendLine(`float height = ${g.height}`)}else if(l instanceof jo&&((p=l.sharedMesh)!=null&&p.geometry)){const g=l.sharedMesh.geometry;g.boundingBox||g.computeBoundingBox();const y=l.sharedMesh.geometry.boundingBox;y&&(c.appendLine('token shapeType = "Box"'),c.appendLine(`float3 extent = (${y.max.x-y.min.x}, ${y.max.y-y.min.y}, ${y.max.z-y.min.z})`),console.log("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. MeshCollider will be exported as Box",l))}else console.warn("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. Ignoring collider:",l);c.beginBlock('def RealityKitStruct "pose"',"{",!0),c.closeBlock("}"),c.closeBlock("}"),c.closeBlock("}")}),s.length>1&&console.log("WARNING: Multiple colliders detected. visionOS / iOS can only support objects with a single collider, only exporting the first collider: ",l))}}const HO=S("debugshadowcomponents");ne.__webpack_exports__Block.prototype.interactable={get(){return this.interactive},set(o){this.interactable=o}};class Qi extends D{constructor(){super(...arguments);r(this,"_shadowComponent",null);r(this,"_controlsChildLayout",!0);r(this,"_root");r(this,"_parentComponent")}isRoot(){var e;return((e=this.Root)==null?void 0:e.gameObject)===this.gameObject}get canvas(){const e=this.Root;return e!=null&&e.isCanvas?e:null}get Canvas(){return this.canvas}markDirty(){Qt.markUIDirty(this.context)}get shadowComponent(){return this._shadowComponent}set shadowComponent(e){this._shadowComponent=e}get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(e){this._controlsChildLayout=e,this.shadowComponent&&(this.shadowComponent.autoLayout=e)}get Root(){return this._root===void 0&&(this._root=C.getComponentInParent(this.gameObject,Ch)),this._root}__internalNewInstanceCreated(e){return super.__internalNewInstanceCreated(e),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0,this}onEnable(){super.onEnable()}addShadowComponent(e,i){var a;if(!e)return;this.removeShadowComponent();const n=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=C.getComponentInParent(n,Qi),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have an UI element outside a Canvas? UI components must be a child of a Canvas component`,this);return}e.name=this.name+" ("+(this.constructor.name??"UI")+")",e.autoLayout=this._parentComponent.controlsChildLayout,e[Si]=this,this.setShadowComponentOwner(e);let s=!1;if(((a=this.Root)==null?void 0:a.gameObject)===this.gameObject)this.gameObject.add(e);else{const l=this._parentComponent.shadowComponent;l&&(l==null||l.add(e),s=!0)}this.shadowComponent=e,i&&i.shadowComponent&&this.shadowComponent&&i.shadowComponent.add(this.shadowComponent),oh&&e.add(new d.AxesHelper(.5)),this.onAfterAddedToScene(),s&&ne.__webpack_exports__update(),HO&&console.warn("Added shadow component",this.shadowComponent)}setShadowComponentOwner(e){if(e&&(e[Si]===void 0||e[Si]===this)&&(e[Si]=this,e.children))for(const i of e.children)this.setShadowComponentOwner(i)}traverseOwnedShadowComponents(e,i,n){if(e&&e[Si]===i){n(e);for(const s of e.children)this.traverseOwnedShadowComponents(s,i,n)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(e){this.shadowComponent&&(this.shadowComponent.interactable=e)}}class Ch extends Qi{awake(){super.awake()}}var GO=Object.defineProperty,qO=Object.getOwnPropertyDescriptor,Ph=(o,t,e,i)=>{for(var n=i>1?void 0:i?qO(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&GO(t,e,n),n};const Mp=S("debugui"),Op=S("debuguilayout");class ix{constructor(){r(this,"width");r(this,"height")}}class nx{constructor(){r(this,"x");r(this,"y");r(this,"width");r(this,"height")}}const cn=new d.Vector3,Il=new d.Matrix4,_d=new d.Quaternion,ul=class sx extends Qi{constructor(){super(...arguments);r(this,"_anchoredPosition");r(this,"sizeDelta",new d.Vector2(100,100));r(this,"pivot",new d.Vector2(.5,.5));r(this,"anchorMin",new d.Vector2(0,0));r(this,"anchorMax",new d.Vector2(1,1));r(this,"minWidth");r(this,"minHeight");r(this,"lastMatrix");r(this,"rectBlock");r(this,"_transformNeedsUpdate",!1);r(this,"_initialPosition");r(this,"_parentRectTransform");r(this,"_lastUpdateFrame",-1);r(this,"_lastAnchoring");r(this,"_createdBlocks",[]);r(this,"_createdTextBlocks",[])}get parent(){return this._parentRectTransform}get translation(){return this.gameObject.position}get rotation(){return this.gameObject.quaternion}get scale(){return this.gameObject.scale}get anchoredPosition(){return this._anchoredPosition||(this._anchoredPosition=new d.Vector2),this._anchoredPosition}set anchoredPosition(e){this._anchoredPosition=e}get width(){let e=this.sizeDelta.x;if(this.anchorMin.x!==this.anchorMax.x&&this._parentRectTransform){const i=this._parentRectTransform.width,n=this.anchorMax.x-this.anchorMin.x;e=i*n,e+=this.sizeDelta.x}return this.minWidth!==void 0&&e<this.minWidth?this.minWidth:e}get height(){let e=this.sizeDelta.y;if(this.anchorMin.y!==this.anchorMax.y&&this._parentRectTransform){const i=this._parentRectTransform.height,n=this.anchorMax.y-this.anchorMin.y;e=i*n,e+=this.sizeDelta.y}return this.minHeight!==void 0&&e<this.minHeight?this.minHeight:e}awake(){super.awake(),this._lastUpdateFrame=-1,this._parentRectTransform=void 0,this.rectBlock=new d.Object3D,this.rectBlock.name=this.name,this.lastMatrix=new d.Matrix4,this._lastAnchoring=null,this._initialPosition=this.gameObject.position.clone(),this._initialPosition.z=0,this._anchoredPosition||(this._anchoredPosition=new d.Vector2),pa(this,"_anchoredPosition",()=>{this.markDirty()}),pa(this,"sizeDelta",()=>{this.markDirty()}),pa(this,"pivot",()=>{this.markDirty()}),pa(this,"anchorMin",()=>{this.markDirty()}),pa(this,"anchorMax",()=>{this.markDirty()})}onEnable(){var e;super.onEnable(),this.rectBlock||(this.rectBlock=new d.Object3D),this.lastMatrix||(this.lastMatrix=new d.Matrix4),this._lastAnchoring||(this._lastAnchoring=new d.Vector2),this._initialPosition||(this._initialPosition=new d.Vector3),this._anchoredPosition||(this._anchoredPosition=new d.Vector2),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0,(e=this.canvas)==null||e.registerTransform(this)}onDisable(){var e;super.onDisable(),this.removeShadowComponent(),(e=this.canvas)==null||e.unregisterTransform(this)}onParentRectTransformChanged(e){this._transformNeedsUpdate||this.onApplyTransform(Op?`${e.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||(this._transformNeedsUpdate=!this.lastMatrix.equals(this.gameObject.matrix)),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(Op&&console.warn("RectTransform markDirty()",this.name),this._transformNeedsUpdate=!0,this._lastUpdateFrame=-1)}updateTransform(){(this._transformNeedsUpdate||!this.lastMatrix.equals(this.gameObject.matrix))&&this.canUpdate()&&this.onApplyTransform(this._transformNeedsUpdate?"Marked dirty":"Matrix changed")}canUpdate(){return this._transformNeedsUpdate&&this.activeAndEnabled&&this._lastUpdateFrame!==this.context.time.frame}onApplyTransform(e){var s;if(this.context.time.frameCount===this._lastUpdateFrame)return;this._lastUpdateFrame=this.context.time.frameCount;const i=this.shadowComponent;if(!i)return;this.gameObject.parent?this._parentRectTransform=C.getComponentInParent(this.gameObject.parent,sx):this._parentRectTransform=void 0,this._transformNeedsUpdate=!1,Op&&console.warn("RectTransform → ApplyTransform",this.name+" because "+e),this.isRoot()?this.Root.screenspace||(i.rotation.y=Math.PI):(i.matrix.identity(),i.matrixAutoUpdate=!1,cn.set(0,0,0),this.applyPivot(cn),i.matrix.setPosition(cn.x,cn.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(_d.copy(this.gameObject.quaternion),_d.x*=-1,_d.z*=-1,Il.makeRotationFromQuaternion(_d),i.matrix.premultiply(Il)),cn.set(0,0,0),this.applyAnchoring(cn),(s=this.canvas)!=null&&s.screenspace?cn.z+=.1:cn.z+=.01,Il.identity(),Il.setPosition(cn.x,cn.y,cn.z),i.matrix.premultiply(Il),i.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);const n=!0;for(const a of Hu(this.gameObject,Qi,n,1)){if(a===this||!a.activeAndEnabled)continue;const l=a;l.onParentRectTransformChanged&&l.onParentRectTransformChanged(this)}}applyAnchoring(e){this._lastAnchoring||(this._lastAnchoring=new d.Vector2);const i=this._lastAnchoring.sub(this._anchoredPosition);this.gameObject.position.x+=i.x,this.gameObject.position.y+=i.y,this._lastAnchoring.copy(this._anchoredPosition),e.x+=this._initialPosition.x-this.gameObject.position.x,e.y+=this._initialPosition.y-this.gameObject.position.y,e.z+=this._initialPosition.z-this.gameObject.position.z;const n=this._parentRectTransform;if(n){let s=0;const a=1-this.anchorMax.y-this.anchorMin.y;s-=n.height*.5*a,e.y+=s;let l=0;const c=1-this.anchorMax.x-this.anchorMin.x;l-=n.width*.5*c,e.x+=l}}applyPivot(e){if(this.pivot&&!this.isRoot()){const i=this.pivot.x-.5;e.x-=i*this.sizeDelta.x*this.gameObject.scale.x;const n=this.pivot.y-.5;e.y-=n*this.sizeDelta.y*this.gameObject.scale.y}}getBasicOptions(){const e={width:this.sizeDelta.x,height:this.sizeDelta.y,offset:0,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0,letterSpacing:-.03};return this.ensureValidSize(e),e}ensureValidSize(e,i=1e-4){return e.width<=0&&(e.width=i),e.height<=0&&(e.height=1e-4),e}createNewBlock(e){e={...this.getBasicOptions(),...e},Mp&&console.log(this.name,e);const i=new ne.__webpack_exports__Block(e);return this._createdBlocks.push(i),i}createNewText(e){Mp&&console.log(e),e={...this.getBasicOptions(),...e},Mp&&console.log(this.name,e);const i=new ne.__webpack_exports__Text(e);return this._createdTextBlocks.push(i),i}};Ph([m(d.Vector2)],ul.prototype,"anchoredPosition",1);Ph([m(d.Vector2)],ul.prototype,"sizeDelta",2);Ph([m(d.Vector2)],ul.prototype,"pivot",2);Ph([m(d.Vector2)],ul.prototype,"anchorMin",2);Ph([m(d.Vector2)],ul.prototype,"anchorMax",2);let xn=ul;var XO=Object.defineProperty,ox=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&XO(t,e,n),n};class fl extends D{constructor(){super(...arguments);r(this,"effectColor");r(this,"effectDistance")}}ox([m(ie)],fl.prototype,"effectColor");ox([m(d.Vector2)],fl.prototype,"effectDistance");var QO=Object.defineProperty,YO=Object.getOwnPropertyDescriptor,rx=(o,t,e,i)=>{for(var n=i>1?void 0:i?YO(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&QO(t,e,n),n};const bd={backgroundColor:new d.Color(1,1,1),backgroundOpacity:1,borderColor:new d.Color(1,1,1),borderOpacity:1};var Gn;const fy=(Gn=class extends Qi{constructor(){super(...arguments);r(this,"_alphaFactor",1);r(this,"sRGBColor",new d.Color(1,0,1));r(this,"raycastTarget",!0);r(this,"uiObject",null);r(this,"_color",null);r(this,"_rect",null);r(this,"_stateManager",null);r(this,"_currentlyCreatingPanel",!1)}get isGraphic(){return!0}get color(){return this._color||(this._color=new ie(1,1,1,1)),this._color}set color(e){(!this._color||this._color.r!==e.r||this._color.g!==e.g||this._color.b!==e.b||this._color.alpha!==e.alpha)&&(this._color||(this._color=new ie(1,1,1,1)),this._color.copy(e),this.onColorChanged())}setAlphaFactor(e){this._alphaFactor=e,this.onColorChanged()}get alphaFactor(){return this._alphaFactor}onColorChanged(){this.uiObject&&(this.sRGBColor.copy(this._color),this.sRGBColor.convertLinearToSRGB(),bd.backgroundColor=this.sRGBColor,bd.backgroundOpacity=this._color.alpha*this._alphaFactor,this.applyEffects(bd,this._alphaFactor),this.uiObject.set(bd),this.markDirty())}get m_Color(){return this._color}get rectTransform(){if(this._rect||(this._rect=C.getComponent(this.gameObject,xn)),!this._rect)throw new Error("Not Supported: Make sure to add a RectTransform component before adding a UI Graphic component.");return this._rect}onParentRectTransformChanged(){var e;(e=this.uiObject)==null||e.set({width:this.rectTransform.width,height:this.rectTransform.height}),this.markDirty()}__internalNewInstanceCreated(e){return super.__internalNewInstanceCreated(e),this._rect=null,this.uiObject=null,this._stateManager=null,this._color&&(this._color=this._color.clone()),this}setState(e){this.makePanel(),this.uiObject&&(this.uiObject.setState(e),this==null||this.markDirty())}setupState(e){this.makePanel(),this.uiObject&&(this._stateManager||(this._stateManager=new ne.SimpleStateBehavior(this.uiObject)),this.uiObject.setupState(e.state,e.attributes))}setOptions(e){this.makePanel(),this.uiObject&&this.uiObject.set(e)}awake(){super.awake(),this.makePanel(),pa(this,"_color",()=>GP(this,this.onColorChanged))}onEnable(){var e;super.onEnable(),this.uiObject&&((e=this.rectTransform.shadowComponent)==null||e.add(this.uiObject),this.addShadowComponent(this.uiObject,this.rectTransform))}onDisable(){super.onDisable(),this.uiObject&&this.removeShadowComponent()}makePanel(){if(this.uiObject||this._currentlyCreatingPanel)return;this._currentlyCreatingPanel=!0;const i={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:.015};this.onBeforeCreate(i),this.applyEffects(i),this.onCreate(i),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated(),this.onColorChanged()}onBeforeCreate(e){}onCreate(e){this.uiObject=this.rectTransform.createNewBlock(e),this.uiObject.name=this.name}onAfterCreated(){}applyEffects(e,i=1){var s;const n=(s=this.gameObject)==null?void 0:s.getComponent(fl);n&&(n.effectDistance&&(e.borderWidth=Math.max(Math.abs(n.effectDistance.x),Math.abs(n.effectDistance.y))),n.effectColor&&(e.borderColor=n.effectColor,e.borderOpacity=n.effectColor.alpha*i))}async setTexture(e){if(this.setOptions({backgroundOpacity:0}),e){if(Gn.textureCache.has(e))e=Gn.textureCache.get(e);else if(!e.isRenderTargetTexture){const i=e.clone();i.colorSpace=d.LinearSRGBColorSpace,Gn.textureCache.set(e,i),e=i}this.setOptions({backgroundImage:e,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"}),le.NEEDLE_progressive.assignTextureLOD(e,0).then(i=>{i instanceof d.Texture&&(e&&Gn.textureCache.set(e,i),this.setOptions({backgroundImage:i}),this.markDirty())})}else this.setOptions({backgroundImage:void 0,borderRadius:0,backgroundOpacity:this.color.alpha});this.markDirty()}onAfterAddedToScene(){super.onAfterAddedToScene(),this.shadowComponent&&(this.shadowComponent.offset=this.shadowComponent.position.z)}},r(Gn,"textureCache",new Map),Gn);rx([m(ie)],fy.prototype,"color",1);rx([m()],fy.prototype,"raycastTarget",2);let Mh=fy;class Oh extends Mh{constructor(){super(...arguments);r(this,"_flippedObject",!1)}onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}}var KO=Object.defineProperty,ZO=Object.getOwnPropertyDescriptor,Us=(o,t,e,i)=>{for(var n=i>1?void 0:i?ZO(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&KO(t,e,n),n};const Qo=S("debugtext");var tt=(o=>(o[o.UpperLeft=0]="UpperLeft",o[o.UpperCenter=1]="UpperCenter",o[o.UpperRight=2]="UpperRight",o[o.MiddleLeft=3]="MiddleLeft",o[o.MiddleCenter=4]="MiddleCenter",o[o.MiddleRight=5]="MiddleRight",o[o.LowerLeft=6]="LowerLeft",o[o.LowerCenter=7]="LowerCenter",o[o.LowerRight=8]="LowerRight",o))(tt||{}),ax=(o=>(o[o.Normal=0]="Normal",o[o.Bold=1]="Bold",o[o.Italic=2]="Italic",o[o.BoldAndItalic=3]="BoldAndItalic",o))(ax||{});class Dt extends Mh{constructor(){super(...arguments);r(this,"alignment",0);r(this,"verticalOverflow",0);r(this,"horizontalOverflow",0);r(this,"lineSpacing",1);r(this,"supportRichText",!1);r(this,"font");r(this,"fontStyle",0);r(this,"sRGBTextColor",new d.Color(1,0,1));r(this,"_text","");r(this,"_fontSize",12);r(this,"_textMeshUi",null);r(this,"_didHandleTextRenderOnTop",!1)}setAlphaFactor(e){var i;super.setAlphaFactor(e),(i=this.uiObject)==null||i.set({fontOpacity:this.color.alpha*this.alphaFactor}),this.markDirty()}get text(){return this._text}set text(e){e!==this._text&&(this._text=e,this.feedText(this.text,this.supportRichText),this.markDirty())}set_text(e){this.text=e}get fontSize(){return this._fontSize}set fontSize(e){var i;this._fontSize=e,(i=this.uiObject)==null||i.set({fontSize:e})}onColorChanged(){var e;this.sRGBTextColor.copy(this.color),this.sRGBTextColor.convertLinearToSRGB(),(e=this.uiObject)==null||e.set({color:this.sRGBTextColor,fontOpacity:this.color.alpha})}onParentRectTransformChanged(){super.onParentRectTransformChanged(),this.uiObject&&this.updateOverflow()}onBeforeCanvasRender(e){this.updateOverflow()}updateOverflow(){var i;const e=(i=this.uiObject)==null?void 0:i._overflow;e&&(e._needsUpdate=!0)}onCreate(e){Qo&&console.log(this),this.horizontalOverflow==1&&(e.whiteSpace="pre"),this.verticalOverflow==0&&(this.context.renderer.localClippingEnabled=!0,e.overflow="hidden"),this.horizontalOverflow==1&&this.verticalOverflow==0,e.lineHeight=this.lineSpacing,delete e.backgroundOpacity,delete e.backgroundColor,Qo&&(e.backgroundColor=16750848,e.backgroundOpacity=.5);const i=this.rectTransform;e={...e,...this.getTextOpts()},this.getAlignment(e),Qo&&(e.backgroundColor=Math.random()*16777215,e.backgroundOpacity=.1),this.uiObject=i.createNewText(e),this.feedText(this.text,this.supportRichText)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}getTextOpts(){const e=this.fontSize,i={color:this.color,fontOpacity:this.color.alpha,fontSize:e,fontKerning:"normal"};return this.setFont(i,this.fontStyle),i}onEnable(){var e;super.onEnable(),this._didHandleTextRenderOnTop=!1,this.uiObject&&this.uiObject.addAfterUpdate(()=>{this.setShadowComponentOwner(this.uiObject),this.markDirty()}),setTimeout(()=>this.markDirty(),10),(e=this.canvas)==null||e.registerEventReceiver(this)}onDisable(){var e;super.onDisable(),(e=this.canvas)==null||e.unregisterEventReceiver(this)}getAlignment(e){switch(e.flexDirection="column",this.alignment){case 0:case 3:case 6:e.textAlign="left";break;case 1:case 4:case 7:e.textAlign="center";break;case 2:case 5:case 8:e.textAlign="right";break}switch(this.alignment){default:case 0:case 1:case 2:e.alignItems="start";break;case 3:case 4:case 5:e.alignItems="center";break;case 6:case 7:case 8:e.alignItems="end";break}return e}feedText(e,i){var n,s,a;if(Qo&&console.log("feedText",this.uiObject,e,i),!!this.uiObject)if(this._textMeshUi||(this._textMeshUi=[]),this.uiObject.children.length=0,!i||e.length===0)this.uiObject.textContent=e;else{let l=this.getNextTag(e);if(l){if(l.startIndex>0){for(let u=this.uiObject.children.length-1;u>=0;u--){const f=this.uiObject.children[u];f.isUI&&(this.uiObject.remove(f),f.clear())}const h=new ne.__webpack_exports__Inline({textContent:e.substring(0,l.startIndex),color:"inherit"});this.uiObject.add(h)}}else{this.uiObject.textContent="",this.setOptions({textContent:e});return}const c=[];for(;l;){const h=this.getNextTag(e,l.endIndex),u={fontFamily:(n=this.uiObject)==null?void 0:n.get("fontFamily"),color:"inherit",textContent:""};if(h){u.textContent=this.getText(e,l,h),this.handleTag(l,u,c);const f=new ne.__webpack_exports__Inline(u);(s=this.uiObject)==null||s.add(f)}else{u.textContent=e.substring(l.endIndex),this.handleTag(l,u,c);const f=new ne.__webpack_exports__Inline(u);(a=this.uiObject)==null||a.add(f)}l=h}}}handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;const e=[],i=this.canvas,n={renderOnTop:i.renderOnTop,depthWrite:i.depthWrite,doubleSided:i.doubleSided};for(;;){let s=!1;if(this._textMeshUi)for(let a=0;a<this._textMeshUi.length;a++){if(e[a]===!0)continue;s=!0;const l=this._textMeshUi[a];l.textContent&&(hu(l,n),e[a]=!0)}if(!s)break;yield}}handleTag(e,i,n){if(!e.isEndTag){if(e.type.includes("color")){const s=new kp(e,{color:i.color});if(n.push(s),e.type.length>6){const a=parseInt("0x"+e.type.substring(7));i.color=a}else i.color=new d.Color(1,1,1)}else if(e.type=="b"){this.setFont(i,1);const s=new kp(e,{fontWeight:700});n.push(s)}else if(e.type=="i"){this.setFont(i,2);const s=new kp(e,{fontStyle:"italic"});n.push(s)}}}getText(e,i,n){return e.substring(i.endIndex,n.startIndex)}getNextTag(e,i=0){const n=e.indexOf("<",i),s=e.indexOf(">",n);if(n>=0&&s>=0){const a=e.substring(n+1,s);return{type:a,startIndex:n,endIndex:s+1,isEndTag:a.startsWith("/")}}return null}setFont(e,i){if(!this.font)return;const n=this.font,s=this.getFamilyNameWithCorrectSuffix(n,i);Qo&&console.log("Selected font family:"+s);let a=ne.__webpack_exports__FontLibrary.getFontFamily(s);switch(a||(a=ne.__webpack_exports__FontLibrary.addFontFamily(s)),e.fontFamily=a,i){default:case 0:e.fontWeight=400,e.fontStyle="normal";break;case 1:e.fontWeight=700,e.fontStyle="normal";break;case 2:e.fontWeight=400,e.fontStyle="italic";break;case 3:e.fontStyle="italic",e.fontWeight=400}let l=a.getVariant(e.fontWeight,e.fontStyle);if(!l){let c=s;c!=null&&c.endsWith("-msdf.json")||(c+="-msdf.json");let h=s;h!=null&&h.endsWith(".png")||(h+=".png"),l=a.addVariant(e.fontWeight,e.fontStyle,c,h),l==null||l.addEventListener("ready",()=>{this.markDirty()})}}getFamilyNameWithCorrectSuffix(e,i){var u;const n=e.lastIndexOf("-");if(n<0)return e;const s=(u=e.substring(n+1))==null?void 0:u.toLowerCase();if(JO.includes(s))return Qo&&console.warn("Unsupported font style: "+s),e;const a=e.lastIndexOf("/");let l=e;a>=0&&(l=l.substring(a+1));const c=l[0]===l[0].toUpperCase(),h=e.substring(0,n);switch(Qo&&console.log("Select font: ",e,ax[i],l,c,h),i){case 0:return c?h+"-Regular":h+"-regular";case 1:return c?h+"-Bold":h+"-bold";case 2:return c?h+"-Italic":h+"-italic";case 3:return c?h+"-BoldItalic":h+"-bolditalic";default:return e}}}Us([m()],Dt.prototype,"alignment",2);Us([m()],Dt.prototype,"verticalOverflow",2);Us([m()],Dt.prototype,"horizontalOverflow",2);Us([m()],Dt.prototype,"lineSpacing",2);Us([m()],Dt.prototype,"supportRichText",2);Us([m(URL)],Dt.prototype,"font",2);Us([m()],Dt.prototype,"fontStyle",2);Us([m()],Dt.prototype,"text",1);Us([m()],Dt.prototype,"fontSize",1);class kp{constructor(t,e){r(this,"tag");r(this,"previousValues");this.tag=t,this.previousValues=e}}const JO=["medium","mediumitalic","black","blackitalic","thin","thinitalic","extrabold","light","lightitalic","semibold"];class hr{constructor(t){r(this,"id");r(this,"content","");r(this,"font",[]);r(this,"pointSize",144);r(this,"width");r(this,"height");r(this,"depth");r(this,"wrapMode");r(this,"horizontalAlignment");r(this,"verticalAlignment");r(this,"material");this.id=t}static getId(){return this.global_id++}setDepth(t){return this.depth=t,this}setPointSize(t){return this.pointSize=t,this}setHorizontalAlignment(t){return this.horizontalAlignment=t,this}setVerticalAlignment(t){return this.verticalAlignment=t,this}writeTo(t,e){var n;e.beginBlock(`def Preliminary_Text "${this.id}"`,"(",!1),e.appendLine('prepend apiSchemas = ["MaterialBindingAPI"]'),e.closeBlock(")"),e.beginBlock(),this.content&&e.appendLine(`string content = "${this.content}"`),(!this.font||this.font.length<=0)&&(this.font||(this.font=[]),(n=this.font)==null||n.push("sans-serif"));const i=this.font.map(s=>`"${s}"`).join(", ");e.appendLine(`string[] font = [ ${i} ]`),e.appendLine(`double pointSize = ${this.pointSize}`),typeof this.width=="number"&&e.appendLine(`double width = ${this.width}`),typeof this.height=="number"&&e.appendLine(`double height = ${this.height}`),typeof this.depth=="number"&&e.appendLine(`double depth = ${this.depth}`),this.wrapMode&&e.appendLine(`token wrapMode = "${this.wrapMode}"`),this.horizontalAlignment&&e.appendLine(`token horizontalAlignment = "${this.horizontalAlignment}"`),this.verticalAlignment&&e.appendLine(`token verticalAlignment = "${this.verticalAlignment}"`),this.material!==void 0&&e.appendLine(`rel material:binding = </StageRoot/Materials/${of(this.material)}>`),e.closeBlock()}}r(hr,"global_id",0);class py{static singleLine(t,e,i){const n=new hr("text_"+hr.getId());return n.content=t,e&&(n.pointSize=e),i&&(n.depth=i),n}static multiLine(t,e,i,n,s,a){const l=new hr("text_"+hr.getId());return l.content=t,l.width=e,l.height=i,l.horizontalAlignment=n,l.verticalAlignment=s,a!==void 0&&(l.wrapMode=a),l}}const ek=new d.Matrix4().makeRotationY(Math.PI),tk=new d.Matrix4().makeScale(-1,1,-1);class ff{get extensionName(){return"text"}exportText(t,e,i){const n=C.getComponent(t,Dt);if(!n)return;const s=C.getComponent(t,xn);let a=100,l=100;s&&(a=s.width,l=s.height);const c=ek.clone();s&&c.premultiply(tk),e.setMatrix(c);const h=n.color.clone();e.material=new d.MeshStandardMaterial({color:h,emissive:h}),e.addEventListener("serialize",(u,f)=>{let p=n.text;p=p.replace(/\r/g,""),p=p.replace(/\n/g,"\\n");const g=py.multiLine(p,a,l,"center","bottom","flowing");this.setTextAlignment(g,n.alignment),this.setOverflow(g,n),e.material&&(g.material=e.material),g.pointSize=this.convertToTextSize(n.fontSize),g.depth=.001,g.writeTo(void 0,u)})}convertToTextSize(t){return 1/.0502*144*t}setOverflow(t,e){e.horizontalOverflow?t.wrapMode="singleLine":t.wrapMode="flowing"}setTextAlignment(t,e){switch(e){case tt.LowerLeft:case tt.MiddleLeft:case tt.UpperLeft:t.horizontalAlignment="left";break;case tt.LowerCenter:case tt.MiddleCenter:case tt.UpperCenter:t.horizontalAlignment="center";break;case tt.LowerRight:case tt.MiddleRight:case tt.UpperRight:t.horizontalAlignment="right";break}switch(e){case tt.LowerLeft:case tt.LowerCenter:case tt.LowerRight:t.verticalAlignment="bottom";break;case tt.MiddleLeft:case tt.MiddleCenter:case tt.MiddleRight:t.verticalAlignment="middle";break;case tt.UpperLeft:case tt.UpperCenter:case tt.UpperRight:t.verticalAlignment="top";break}}}var ik=Object.defineProperty,Ke=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&ik(t,e,n),n};const Eb=S("debuguilayout");class Gr{constructor(){r(this,"left",0);r(this,"right",0);r(this,"top",0);r(this,"bottom",0)}get vertical(){return this.top+this.bottom}get horizontal(){return this.left+this.right}}Ke([m()],Gr.prototype,"left");Ke([m()],Gr.prototype,"right");Ke([m()],Gr.prototype,"top");Ke([m()],Gr.prototype,"bottom");class Di extends D{constructor(){super(...arguments);r(this,"_rectTransform",null);r(this,"_needsUpdate",!1);r(this,"childAlignment",0);r(this,"reverseArrangement",!1);r(this,"spacing",0);r(this,"padding");r(this,"minWidth",0);r(this,"minHeight",0);r(this,"flexibleHeight",0);r(this,"flexibleWidth",0);r(this,"preferredHeight",0);r(this,"preferredWidth",0)}get rectTransform(){return this._rectTransform}onParentRectTransformChanged(e){this._needsUpdate=!0}get isDirty(){return this._needsUpdate}get isLayoutGroup(){return!0}updateLayout(){this._rectTransform&&(Eb&&console.warn("Layout Update",this.context.time.frame,this.name),this._needsUpdate=!1,this.onCalculateLayout(this._rectTransform))}start(){this._needsUpdate=!0}onEnable(){Eb&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(xn);const e=this.gameObject.getComponentInParent(Za);e&&e.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){const e=this.gameObject.getComponentInParent(Za);e&&e.unregisterLayoutGroup(this)}set m_Spacing(e){e!==this.spacing&&(this._needsUpdate=!0,this.spacing=e)}get m_Spacing(){return this.spacing}}Ke([m()],Di.prototype,"childAlignment");Ke([m()],Di.prototype,"reverseArrangement");Ke([m()],Di.prototype,"spacing");Ke([m(Gr)],Di.prototype,"padding");Ke([m()],Di.prototype,"minWidth");Ke([m()],Di.prototype,"minHeight");Ke([m()],Di.prototype,"flexibleHeight");Ke([m()],Di.prototype,"flexibleWidth");Ke([m()],Di.prototype,"preferredHeight");Ke([m()],Di.prototype,"preferredWidth");class Uo extends Di{constructor(){super(...arguments);r(this,"childControlHeight",!0);r(this,"childControlWidth",!0);r(this,"childForceExpandHeight",!1);r(this,"childForceExpandWidth",!1);r(this,"childScaleHeight",!1);r(this,"childScaleWidth",!1)}onCalculateLayout(e){var F;const i=this.primaryAxis,n=e.width;let s=n;const a=e.height;let l=a;s-=this.padding.horizontal,l-=this.padding.vertical,i==="x"?this.padding.horizontal:this.padding.vertical;const c=i==="x",h=c?"y":"x",u=c?this.childControlWidth:this.childControlHeight,f=c?this.childControlHeight:this.childControlWidth,p=c?this.childForceExpandWidth:this.childForceExpandHeight,g=c?this.childForceExpandHeight:this.childForceExpandWidth,y=c?l:s,b=c?n:a,_=.5*(c?this.childAlignment%3:Math.floor(this.childAlignment/3));let v=0;c?v+=this.padding.left:v+=this.padding.top;let w=0,x=0;for(let T=0;T<this.gameObject.children.length;T++){const L=this.gameObject.children[T],A=C.getComponent(L,xn);A!=null&&A.activeAndEnabled&&(x+=1,c?w+=A.width:w+=A.height)}let O=0;const M=this.spacing*(x-1);if(p||u){let T=0;c?T=s-=M:T=l-=M,x>0&&(O=T/x)}let R=0;R+=this.padding.left,R-=this.padding.right,_!==0&&(v=b-w,v*=_,v-=M*_,c?(v-=this.padding.right*_,v+=this.padding.left*(1-_),v<this.padding.left&&(v=this.padding.left)):(v-=this.padding.bottom*_,v+=this.padding.top*(1-_),v<this.padding.top&&(v=this.padding.top)));let E=1;for(let T=0;T<this.gameObject.children.length;T++){const L=this.gameObject.children[T],A=C.getComponent(L,xn);if(A!=null&&A.activeAndEnabled){(F=A.pivot)==null||F.set(.5,.5),A.anchorMin.set(0,1),A.anchorMax.set(0,1);const H=n*.5+R*.5;A.anchoredPosition.x!==H&&(A.anchoredPosition.x=H);const B=a*-.5;A.anchoredPosition.y!==B&&(A.anchoredPosition.y=B),g&&f&&A.sizeDelta[h]!==y&&(A.sizeDelta[h]=y),p&&u&&A.sizeDelta[i]!==O&&(A.sizeDelta[i]=O);const I=c?A.width:A.height,N=I*.5;if(v+=N,p){const Z=O*E-O*.5;Z>v&&(v=Z-O*.5+I+this.padding.left,v-=N)}let Y=v;i==="y"&&(Y=-Y),A.anchoredPosition[i]!==Y&&(A.anchoredPosition[i]=Y),v+=N,v+=this.spacing,E+=1}}}}Ke([m()],Uo.prototype,"childControlHeight");Ke([m()],Uo.prototype,"childControlWidth");Ke([m()],Uo.prototype,"childForceExpandHeight");Ke([m()],Uo.prototype,"childForceExpandWidth");Ke([m()],Uo.prototype,"childScaleHeight");Ke([m()],Uo.prototype,"childScaleWidth");class my extends Uo{get primaryAxis(){return"y"}}class gy extends Uo{get primaryAxis(){return"x"}}class yy extends Di{onCalculateLayout(){}}var nk=Object.defineProperty,sk=Object.getOwnPropertyDescriptor,as=(o,t,e,i)=>{for(var n=i>1?void 0:i?sk(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&nk(t,e,n),n},lx=(o=>(o[o.ScreenSpaceOverlay=0]="ScreenSpaceOverlay",o[o.ScreenSpaceCamera=1]="ScreenSpaceCamera",o[o.WorldSpace=2]="WorldSpace",o[o.Undefined=-1]="Undefined",o))(lx||{});const Rp=S("debuguilayout"),Yi=class cx extends Ch{constructor(){super(...arguments);r(this,"_renderOnTop");r(this,"_depthWrite",!1);r(this,"_doubleSided",!0);r(this,"_castShadows",!1);r(this,"_receiveShadows",!1);r(this,"_renderMode",-1);r(this,"_rootCanvas");r(this,"_scaleFactor",1);r(this,"worldCamera");r(this,"planeDistance",-1);r(this,"_boundRenderSettingsChanged",this.onRenderSettingsChanged.bind(this));r(this,"previousParent",null);r(this,"_lastMatrixWorld",null);r(this,"_rectTransforms",[]);r(this,"_layoutGroups",new Map);r(this,"_receivers",[]);r(this,"onBeforeRenderRoutine",()=>{var e,i,n,s;if(this.previousParent=this.gameObject.parent,((e=this.context.xr)!=null&&e.isVR||(i=this.context.xr)!=null&&i.isPassThrough)&&this.screenspace){this.gameObject.visible=!1,this.gameObject.removeFromParent();return}this.renderOnTop||this.screenspace?this.gameObject.removeFromParent():(this.onUpdateRenderMode(),this.handleLayoutUpdates(),(n=this.shadowComponent)==null||n.updateMatrixWorld(!0),(s=this.shadowComponent)==null||s.updateWorldMatrix(!0,!0),this.invokeBeforeRenderEvents(),Qt.ensureUpdateMeshUI(ne.ThreeMeshUI,this.context))});r(this,"onAfterRenderRoutine",()=>{var e,i,n,s,a;if(((e=this.context.xr)!=null&&e.isVR||(i=this.context.xr)!=null&&i.isPassThrough)&&this.screenspace){(n=this.previousParent)==null||n.add(this.gameObject);return}if((this.screenspace||this.renderOnTop)&&this.previousParent&&this.context.mainCamera){if(this.screenspace){const h=this.context.mainCamera;h==null||h.add(this.gameObject)}else this.previousParent.add(this.gameObject);const l=this.context.renderer.autoClear,c=this.context.renderer.autoClearColor;this.context.renderer.autoClear=!1,this.context.renderer.autoClearColor=!1,this.context.renderer.clearDepth(),this.onUpdateRenderMode(!0),this.handleLayoutUpdates(),(s=this.shadowComponent)==null||s.updateMatrixWorld(!0),this.invokeBeforeRenderEvents(),Qt.ensureUpdateMeshUI(ne.ThreeMeshUI,this.context,!0),this.context.renderer.render(this.gameObject,this.context.mainCamera),this.context.renderer.autoClear=l,this.context.renderer.autoClearColor=c,this.previousParent.add(this.gameObject)}(a=this._lastMatrixWorld)==null||a.copy(this.gameObject.matrixWorld)});r(this,"_updateRenderSettingsRoutine");r(this,"_activeRenderMode",-1);r(this,"_lastWidth",-1);r(this,"_lastHeight",-1)}get isCanvas(){return!0}get screenspace(){return this.renderMode!==2}set renderOnTop(e){e!==this._renderOnTop&&(this._renderOnTop=e,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop!==void 0?this._renderOnTop:!!(this.screenspace&&this._renderMode===0)}set depthWrite(e){this._depthWrite!==e&&(this._depthWrite=e,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}set doubleSided(e){this._doubleSided!==e&&(this._doubleSided=e,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}set castShadows(e){this._castShadows!==e&&(this._castShadows=e,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}set receiveShadows(e){this._receiveShadows!==e&&(this._receiveShadows=e,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}get renderMode(){return this._renderMode}set renderMode(e){this._renderMode!==e&&(this._renderMode=e,this.onRenderSettingsChanged())}set rootCanvas(e){this._rootCanvas instanceof cx||(this._rootCanvas=e)}get rootCanvas(){return this._rootCanvas}get scaleFactor(){return this._scaleFactor}set scaleFactor(e){this._scaleFactor=e}awake(){var e;this.shadowComponent=this.gameObject,this.previousParent=this.gameObject.parent,Rp&&console.log("Canvas.Awake()",((e=this.previousParent)==null?void 0:e.name)+"/"+this.gameObject.name),super.awake()}start(){this.applyRenderSettings()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this._lastMatrixWorld=new d.Matrix4,this.applyRenderSettings(),document.addEventListener("resize",this._boundRenderSettingsChanged),this.context.pre_render_callbacks.push(this.onBeforeRenderRoutine),this.context.post_render_callbacks.push(this.onAfterRenderRoutine)}onDisable(){super.onDisable(),document.removeEventListener("resize",this._boundRenderSettingsChanged);const e=this.context.pre_render_callbacks.indexOf(this.onBeforeRenderRoutine);e!==-1&&this.context.pre_render_callbacks.splice(e,1);const i=this.context.post_render_callbacks.indexOf(this.onAfterRenderRoutine);i!==-1&&this.context.post_render_callbacks.splice(i,1)}registerTransform(e){this._rectTransforms.push(e)}unregisterTransform(e){const i=this._rectTransforms.indexOf(e);i!==-1&&this._rectTransforms.splice(i,1)}registerLayoutGroup(e){const i=e.gameObject;this._layoutGroups.set(i,e)}unregisterLayoutGroup(e){const i=e.gameObject;this._layoutGroups.delete(i)}registerEventReceiver(e){this._receivers.push(e)}unregisterEventReceiver(e){const i=this._receivers.indexOf(e);i!==-1&&this._receivers.splice(i,1)}async onEnterXR(e){this.screenspace?(e.xr.isVR||e.xr.isPassThrough)&&(this.gameObject.visible=!1):(this.gameObject.visible=!1,await Jc(1).then(()=>{this.gameObject.visible=!0}))}onLeaveXR(e){this.screenspace&&(e.xr.isVR||e.xr.isPassThrough)&&(this.gameObject.visible=!0)}invokeBeforeRenderEvents(){var e;for(const i of this._receivers)(e=i.onBeforeCanvasRender)==null||e.call(i,this)}handleLayoutUpdates(){this._lastMatrixWorld===null&&(this._lastMatrixWorld=new d.Matrix4);const e=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);Rp&&e&&console.log("Canvas Layout changed",this.context.time.frameCount,this.name);for(const i of this._rectTransforms){e&&i.markDirty();let n=this._layoutGroups.get(i.gameObject);i.isDirty&&!n&&(n=i.gameObject.getComponentInParent(Di)),(i.isDirty||n!=null&&n.isDirty)&&(Rp&&console.log("CANVAS UPDATE ### "+i.name+" ##################################### "+this.context.time.frame),n==null||n.updateLayout(),i.updateTransform())}}applyRenderSettings(){this.onRenderSettingsChanged()}onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),we.OnBeforeRender))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),hu(this.shadowComponent,this);for(const e of C.getComponentsInChildren(this.gameObject,Qi))hu(e.shadowComponent,this)}}onUpdateRenderMode(e=!1){if(!e&&this._renderMode===this._activeRenderMode&&this._lastWidth===this.context.domWidth&&this._lastHeight===this.context.domHeight)return;this._activeRenderMode=this._renderMode;let i=this.context.mainCameraComponent,n=10;switch(i&&i.nearClipPlane>0&&i.farClipPlane>0&&(n=z.lerp(i.nearClipPlane,i.farClipPlane,.01)),this._renderMode===1&&(this.worldCamera&&(i=this.worldCamera),this.planeDistance>0&&(n=this.planeDistance)),this._renderMode){case 0:case 1:if(this._lastWidth=this.context.domWidth,this._lastHeight=this.context.domHeight,!i)return;const s=n+.01;this.gameObject.position.x=0,this.gameObject.position.y=0,this.gameObject.position.z=-s,this.gameObject.quaternion.identity();const a=this.gameObject.getComponent(xn);let l=!1;a.sizeDelta.x!==this.context.domWidth&&(l=!0),a.sizeDelta.y!==this.context.domHeight&&(l=!0);const c=i.fieldOfView*Math.PI/180,h=2*Math.tan(c/2)*Math.abs(s);this.gameObject.scale.x=h/this.context.domHeight,this.gameObject.scale.y=h/this.context.domHeight,this.gameObject.scale.z=.01,l&&(a.sizeDelta.x=this.context.domWidth,a.sizeDelta.y=this.context.domHeight,a==null||a.markDirty());break;case 2:this._lastWidth=-1,this._lastHeight=-1;break}}};as([m()],Yi.prototype,"renderOnTop",1);as([m()],Yi.prototype,"depthWrite",1);as([m()],Yi.prototype,"doubleSided",1);as([m()],Yi.prototype,"castShadows",1);as([m()],Yi.prototype,"receiveShadows",1);as([m()],Yi.prototype,"renderMode",1);as([m(Yi)],Yi.prototype,"rootCanvas",1);as([m()],Yi.prototype,"scaleFactor",1);as([m(ri)],Yi.prototype,"worldCamera",2);as([m()],Yi.prototype,"planeDistance",2);let Za=Yi;var ok=Object.defineProperty,rk=Object.getOwnPropertyDescriptor,_y=(o,t,e,i)=>{for(var n=i>1?void 0:i?rk(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&ok(t,e,n),n};class Ro extends D{constructor(){super(...arguments);r(this,"_alpha",1);r(this,"interactable",!0);r(this,"blocksRaycasts",!0);r(this,"_isDirty",!1);r(this,"_buffer",[])}get alpha(){return this._alpha}set alpha(e){e!==this._alpha&&(this._alpha=e,this.markDirty())}get isCanvasGroup(){return!0}markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),we.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}applyChangesNow(){this._buffer.length=0;for(const e of C.getComponentsInChildren(this.gameObject,Qi,this._buffer)){const i=e;i.setAlphaFactor&&i.setAlphaFactor(this._alpha)}}}_y([m()],Ro.prototype,"alpha",1);_y([m()],Ro.prototype,"interactable",2);_y([m()],Ro.prototype,"blocksRaycasts",2);class by{get extensionName(){return"tmui"}onExportObject(t,e,i){const n=C.getComponent(t,Za);if(n&&n.enabled&&n.renderMode===lx.WorldSpace){const s=new ff,a=C.getComponent(t,xn),l=C.getComponent(t,Ro),c=new Array;if(a){if(!C.isActiveSelf(t)){const f=C.isActiveSelf(t);C.setActive(t,!0),a.onEnable(),a.updateTransform(),c.push(()=>{a.onDisable(),C.setActive(t,f)})}t.traverse(f=>{if(!C.isActiveInHierarchy(f)){const p=C.isActiveSelf(f);C.setActive(f,!0);const g=C.getComponent(f,Qi);g&&(g.onEnable(),c.push(()=>{g.onDisable()}));const y=C.getComponent(f,xn);y&&(y.onEnable(),y.updateTransform(),y.onApplyTransform(),c.push(()=>{y.onDisable()}));const b=C.getComponent(f,Dt);b&&(b.onEnable(),c.push(()=>{b.onDisable()})),c.push(()=>{C.setActive(f,p)})}}),a.width,a.height;const h=Et.createEmpty(),u=a.shadowComponent;if(e.add(h),u){const f=u.matrix;h.setMatrix(f);const p=new Map,g=new Map;p.set(u,h),g.set(u,l?l.alpha:1),u.traverse(y=>{if(y===u)return;const b=Et.createEmpty();b.setMatrix(y.matrix);const _=y.parent,v=!!_&&typeof _.textContent=="string"&&_.textContent.length>0;let w=g.get(_)||1;const x=C.getComponent(y,Ro);if(x&&(w*=x.alpha),y instanceof d.Mesh&&v){const M=y[Si];M?s.exportText(M.gameObject,b,i):console.error("Error when exporting UI: shadow component owner not found. This is likely a bug.",y)}if(y instanceof d.Mesh&&!v){const M=y.geometry.clone();M.scale(1,1,-1),this.flipWindingOrder(M),b.geometry=M;const R=new d.Color,E=y.material.opacity;R.copy(y.material.color),b.material=new d.MeshBasicMaterial({color:R,opacity:E*w,map:y.material.map,transparent:!0})}p.set(y,b),g.set(y,w);const O=p.get(_);if(!O){console.error("Error when exporting UI: shadow component parent not found!",y,y.parent);return}O.add(b)})}}for(const h of c)h()}}flipWindingOrder(t){const e=t.index.array;for(let i=0,n=e.length/3;i<n;i++){const s=e[i*3];e[i*3]=e[i*3+2],e[i*3+2]=s}t.index.needsUpdate=!0}}const tc=S("debugusdz");function ak(o,t){var l;const e=[],i=C.getComponentsInChildren(o,xt),n=C.getComponentsInChildren(o,Tt),s=new Array,a=new Array;if(t.injectImplicitBehaviours)for(const c of i){if(!c||!c.runtimeAnimatorController||!c.enabled)continue;const h=c.runtimeAnimatorController.activeState;if(!h||!h.motion||!h.motion.clip||((l=h.motion.clip.tracks)==null?void 0:l.length)<1||s.includes(c))continue;const u=new Nc;u.animator=c,u.stateName=h.name,u.trigger="start",u.name="PlayAnimationOnClick_implicitAtStart_"+u.stateName;const f=new d.Object3D;C.addComponent(f,u),a.push(f),s.push(c),o.add(f)}else for(const c of i){if(!c||!c.runtimeAnimatorController||!c.enabled)continue;tc&&console.log(c);const h=[];for(const u of c.runtimeAnimatorController.enumerateActions()){tc&&console.log(u);const f=u.getClip();h.includes(f)||h.push(f)}e.push({root:c.gameObject,clips:h})}if(t.injectImplicitBehaviours)for(const c of n){if(!c||!c.clip||!c.enabled||!c.playAutomatically||s.includes(c))continue;const h=new Nc;h.animation=c,h.stateName=c.clip.name,h.trigger="start",h.name="PlayAnimationOnClick_implicitAtStart_"+h.stateName;const u=new d.Object3D;C.addComponent(u,h),a.push(u),s.push(c),o.add(u)}else for(const c of n){tc&&console.log(c);const h=[];for(const u of c.animations)h.includes(u)||h.push(u);e.push({root:c.gameObject,clips:h})}tc&&(e==null?void 0:e.length)>0&&console.log("USDZ Animation Clips without behaviours",e);for(const c of e)for(const h of c.clips)t.registerAnimation(c.root,h);return a}function lk(o,t){const e=C.getComponentsInChildren(o,qi),i=C.getComponentsInChildren(o,Oo),n=new Array,s=new Array;tc&&console.log({audioSources:e,playAudioOnClicks:i});for(const a of i){if(!a.target)continue;const l=e.indexOf(a.target);l>-1&&e.splice(l,1)}for(const a of e){if(!a||!a.clip||a.volume<=0||n.includes(a))continue;const l=new Oo;l.target=a,l.name="PlayAudioOnClick_implicitAtStart_",l.trigger="start";const c=new d.Object3D;C.addComponent(c,l),console.log("implicit PlayAudioOnStart",c,l),s.push(c),n.push(a),o.add(c)}return s}function ck(o){return new vt("DisableAtStart",wt.sceneStartTrigger(),fe.fadeAction(o,0,!1))}function Tb(o,t){const e=o.domElement.shadowRoot.querySelector("link[rel='ar']");if(e)return e;const i=document.createElement("div");i.classList.add("menu"),i.classList.add("quicklook-menu"),i.style.display="none",i.style.visibility="hidden";const n=document.createElement("button");n.id="open-in-ar",t?(n.innerText="View in AR",n.title="View this scene in AR. The scene will be exported to USDZ and opened with Apple's QuickLook."):(n.innerText="View in AR",n.title="Download this scene for AR. Open the downloaded USDZ file to view it in AR using Apple's QuickLook."),i.appendChild(n);const s=document.createElement("a");s.id="needle-usdz-link",s.style.display="none",s.rel="ar",s.href="",s.target="_blank",i.appendChild(s);const a=document.createElement("img");return a.id="button",s.appendChild(a),o.domElement.shadowRoot.appendChild(i),s}var hk=Object.defineProperty,Ct=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&hk(t,e,n),n};const gi=S("debugusdz"),dk=S("debugusdzpruning");class qr{constructor(){r(this,"callToAction");r(this,"checkoutTitle");r(this,"checkoutSubtitle");r(this,"callToActionURL")}}Ct([m()],qr.prototype,"callToAction");Ct([m()],qr.prototype,"checkoutTitle");Ct([m()],qr.prototype,"checkoutSubtitle");Ct([m()],qr.prototype,"callToActionURL");var Ps;const fi=(Ps=class extends D{constructor(){super(...arguments);r(this,"objectToExport");r(this,"autoExportAnimations",!0);r(this,"autoExportAudioSources",!0);r(this,"exportFileName");r(this,"customUsdzFile");r(this,"customBranding");r(this,"anchoringType","plane");r(this,"maxTextureSize",2048);r(this,"planeAnchoringAlignment","horizontal");r(this,"interactive",!0);r(this,"physics",!0);r(this,"allowCreateQuicklookButton",!0);r(this,"quickLookCompatible",!0);r(this,"extensions",[]);r(this,"link");r(this,"button");r(this,"onClickedOpenInARElement",e=>{e.preventDefault(),this.exportAndOpen()});r(this,"_currentExportTasks",new Map);r(this,"_previousTimeScale",1);r(this,"lastCallback");r(this,"_rootSessionRootWasAppliedTo",null);r(this,"_rootPositionBeforeExport",new d.Vector3);r(this,"_rootRotationBeforeExport",new d.Quaternion);r(this,"_rootScaleBeforeExport",new d.Vector3)}start(){var e,i,n;gi&&(console.log("USDZExporter",this),console.log("Debug USDZ Mode. Press 'T' to export"),window.addEventListener("keydown",s=>{switch(s.key){case"t":this.exportAndOpen();break}})),this.objectToExport||(this.objectToExport=this.gameObject),!((i=(e=this.objectToExport)==null?void 0:e.children)!=null&&i.length)&&!((n=this.objectToExport)!=null&&n.isMesh)&&(this.objectToExport=this.context.scene)}onEnable(){var n;const e=exports.DeviceUtilities.supportsQuickLookAR(),i=exports.DeviceUtilities.isiOS()||exports.DeviceUtilities.isiPad();!this.button&&(gi||e||i)&&(this.allowCreateQuicklookButton&&(this.button=this.createQuicklookButton()),this.lastCallback=this.quicklookCallback.bind(this),this.link=Tb(this.context,e),this.link.addEventListener("message",this.lastCallback)),gi&&Ee("USDZ Exporter enabled: "+this.name),(n=document.getElementById("open-in-ar"))==null||n.addEventListener("click",this.onClickedOpenInARElement),kc.registerExporter(this)}onDisable(){var e,i,n;(e=this.button)==null||e.remove(),(i=this.link)==null||i.removeEventListener("message",this.lastCallback),gi&&Ee("USDZ Exporter disabled: "+this.name),(n=document.getElementById("open-in-ar"))==null||n.removeEventListener("click",this.onClickedOpenInARElement),kc.unregisterExporter(this)}async exportAsync(){return this.exportAndOpen()}async exportAndOpen(){var n;let e=this.exportFileName??((n=this.objectToExport)==null?void 0:n.name)??this.name;if(e+="-"+Uw(),Qn()||(e!==""&&(e+="-"),e+="MadeWithNeedle"),this.link||(this.link=Tb(this.context,exports.DeviceUtilities.supportsQuickLookAR())),this.customUsdzFile)return gi&&console.log("Exporting custom usdz",this.customUsdzFile),this.openInQuickLook(this.customUsdzFile,e),null;if(!this.objectToExport)return console.warn("No object to export",this),null;const i=await this.export(this.objectToExport);return i?(gi&&console.log("USDZ generation done. Downloading as "+e),this.openInQuickLook(i,e),i):(console.error("USDZ generation failed. Please report a bug",this),null)}async export(e){if(!e)return console.warn("No object to export"),null;const i=this._currentExportTasks.get(e);if(i)return i;const n=this.internalExport(e);return n instanceof Promise?(this._currentExportTasks.set(e,n),n.then(s=>(this._currentExportTasks.delete(e),s)).catch(s=>(this._currentExportTasks.delete(e),console.error("Error during USDZ export – please report a bug!",s),null))):n}async internalExport(e){oe.start("export-usdz",{onProgress:R=>{this.dispatchEvent(new CustomEvent("export-progress",{detail:{progress:R}}))}}),oe.report("export-usdz",{message:"Starting export",totalSteps:40,currentStep:0}),oe.report("export-usdz",{message:"Load progressive textures",autoStep:5}),oe.start("export-usdz-textures","export-usdz");const i=C.getComponentsInChildren(e,ui);for(const R of i)R&&R.enabled&&R.updateSprite(!0);const n=C.getComponentsInChildren(e,Ti),s=new Array;let a=0;for(const R of n){for(const E of R.sharedMeshes)if(E){const F=le.NEEDLE_progressive.assignMeshLOD(E,0);F instanceof Promise&&s.push(new Promise((T,L)=>{F.then(()=>{a++,oe.report("export-usdz-textures",{message:"Loaded progressive mesh",currentStep:a,totalSteps:s.length}),T()}).catch(A=>L(A))}))}for(const E of R.sharedMaterials)if(E){const F=le.NEEDLE_progressive.assignTextureLOD(E,0);F instanceof Promise&&s.push(new Promise((T,L)=>{F.then(()=>{a++,oe.report("export-usdz-textures",{message:"Loaded progressive texture",currentStep:a,totalSteps:s.length}),T()}).catch(A=>L(A))}))}}gi&&Ee("Progressive Loading: "+s.length),await Promise.all(s),gi&&Ee("Progressive Loading: done"),oe.end("export-usdz-textures");const l=Xt.Global.Mask;Xt.Global.Set(Bn.AR);const c=new Ww,h=new rf(this.quickLookCompatible);let u;const f=[];this.interactive&&(f.push(new dy),f.push(new Wr),globalThis.NEEDLE_USE_RAPIER&&C.getComponentsInChildren(e,ot).length>0&&(this.physics?(u=new uy,f.push(u)):j()&&console.warn("USDZExporter: Physics export is disabled, but there are active Rigidbody components in the scene. They will not be exported.")),f.push(new ff),f.push(new by));const p=[h,...f,...this.extensions],g={self:this,exporter:c,extensions:p,object:e};oe.report("export-usdz","Invoking before-export"),this.dispatchEvent(new CustomEvent("before-export",{detail:g})),this.applyWebARSessionRoot(),this._previousTimeScale=this.context.time.timeScale,this.context.time.timeScale=0,oe.report("export-usdz","auto export animations and audio sources");const y=new Array;this.autoExportAnimations&&y.push(...ak(e,h)),p.find(R=>R.extensionName==="Audio")&&this.autoExportAudioSources&&y.push(...lk(e)),c.debug=gi,c.pruneUnusedNodes=!dk;const _=Xa.instance.objs.map(R=>R.batchedMesh);c.keepObject=R=>{let E=!0;const F=C.getComponent(R,Ti);return F&&!F.enabled&&(E=!1),E&&_.includes(R)&&(E=!1),E&&C.getComponentInParent(R,yh)&&(E=!1),E&&C.getComponentInParent(R,ss)&&(E=!1),gi&&!E&&console.log("USDZExporter: Discarding object",R),E},c.beforeWritingDocument=()=>{if(j()&&h&&u){const R=h.animatedRoots;for(const E of R){const F=C.getComponentsInChildren(E,ot).filter(L=>L.enabled),T=C.getComponents(E,di).filter(L=>L.enabled&&!L.isTrigger);(F.length>0||T.length>0)&&console.error("An animated object has physics components in its child hierarchy. This can lead to undefined behaviour due to a bug in Apple's QuickLook (FB15925487). Remove the physics components from child objects or verify that you get the expected results.",E)}}};const v=new Array;this.objectToExport&&this.quickLookCompatible&&this.interactive&&this.objectToExport.traverse(R=>{R.visible||v.push(R)});const w=p.find(R=>R.extensionName==="Behaviour");this.interactive&&w&&v.length>0&&w.addBehavior(ck(v));let x=!0;this.quickLookCompatible&&!this.interactive&&(x=!1),this.anchoringType!=="plane"&&this.anchoringType!=="none"&&this.anchoringType!=="image"&&this.anchoringType!=="face"&&(this.anchoringType="plane"),this.planeAnchoringAlignment!=="horizontal"&&this.planeAnchoringAlignment!=="vertical"&&this.planeAnchoringAlignment!=="any"&&(this.planeAnchoringAlignment="horizontal"),oe.report("export-usdz","Invoking exporter.parse");const O=await c.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:p,quickLookCompatible:this.quickLookCompatible,maxTextureSize:this.maxTextureSize,exportInvisible:x}),M=new Blob([O],{type:"model/vnd.usdz+zip"});this.revertWebARSessionRoot(),this.context.time.timeScale=this._previousTimeScale,oe.report("export-usdz","Invoking after-export"),this.dispatchEvent(new CustomEvent("after-export",{detail:g}));for(const R of y)C.destroy(R);return Xt.Global.Set(l),oe.end("export-usdz"),M}openInQuickLook(e,i){const n=e instanceof Blob?URL.createObjectURL(e):e,s=this.buildQuicklookOverlay();gi&&console.log("QuickLook Overlay",s);const a=s.callToAction?encodeURIComponent(s.callToAction):"",l=s.checkoutTitle?encodeURIComponent(s.checkoutTitle):"",c=s.checkoutSubtitle?encodeURIComponent(s.checkoutSubtitle):"";this.link.href=n+`#callToAction=${a}&checkoutTitle=${l}&checkoutSubtitle=${c}&callToActionURL=${s.callToActionURL}`,this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=i+".usdz",this.link.click()}download(e,i){Ps.save(e,i)}static save(e,i){const n=document.createElement("a");n.style.display="none",document.body.appendChild(n),typeof e=="string"?n.href=e:n.href=URL.createObjectURL(e),n.download=i,n.click(),n.remove()}quicklookCallback(e){if((e==null?void 0:e.data)=="_apple_ar_quicklook_button_tapped"){gi&&me("Quicklook closed via call to action button");var i=new CustomEvent("quicklook-button-tapped",{detail:this});if(this.dispatchEvent(i),!i.defaultPrevented){const n=new URLSearchParams(this.link.href);if(n){const s=n.get("callToActionURL");gi&&Ee("Quicklook url: "+s),s&&(Qn()?globalThis.open(s,"_blank"):console.warn("Quicklook closed: custom redirects require a Needle Engine Pro license: https://needle.tools/pricing",s))}}}}buildQuicklookOverlay(){var n,s,a,l,c,h;const e={};return this.customBranding&&Object.assign(e,this.customBranding),Qn()||(console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing"),e.callToAction="Close",e.checkoutTitle="🌵 Made with Needle",e.checkoutSubtitle="_"),(((n=e.callToAction)==null?void 0:n.length)||((s=e.checkoutTitle)==null?void 0:s.length)||((a=e.checkoutSubtitle)==null?void 0:a.length))&&((l=e.callToAction)!=null&&l.length||(e.callToAction="\0"),(c=e.checkoutTitle)!=null&&c.length||(e.checkoutTitle="\0"),(h=e.checkoutSubtitle)!=null&&h.length||(e.checkoutSubtitle="\0")),this.dispatchEvent(new CustomEvent("quicklook-overlay",{detail:e})),e}getARScaleAndTarget(){if(!this.objectToExport)return{scale:1,_invertForward:!1,target:this.gameObject,sessionRoot:null};const e=C.findObjectOfType(uf);let i=C.getComponentInParent(this.objectToExport,is);i||(i=C.getComponentInChildren(this.objectToExport,is));let n=1,s=!1;const a=this.objectToExport;return e?n=e.arScale:i&&(n=i.arScale,s=i.invertForward),{scale:1/n,_invertForward:s,target:a,sessionRoot:(i==null?void 0:i.gameObject)??null}}applyWebARSessionRoot(){if(!this.objectToExport)return;const{scale:e,_invertForward:i,target:n,sessionRoot:s}=this.getARScaleAndTarget(),a=s==null?void 0:s.matrixWorld.clone().invert();this._rootSessionRootWasAppliedTo=n,this._rootPositionBeforeExport.copy(n.position),this._rootRotationBeforeExport.copy(n.quaternion),this._rootScaleBeforeExport.copy(n.scale),n.scale.multiplyScalar(e),i&&n.quaternion.multiply(Ps.invertForwardQuaternion),n.updateMatrix(),n.updateMatrixWorld(!0),s&&a&&n.matrix.premultiply(a)}revertWebARSessionRoot(){if(!this.objectToExport||!this._rootSessionRootWasAppliedTo)return;const e=this._rootSessionRootWasAppliedTo;e.position.copy(this._rootPositionBeforeExport),e.quaternion.copy(this._rootRotationBeforeExport),e.scale.copy(this._rootScaleBeforeExport),e.updateMatrix(),e.updateMatrixWorld(!0),this._rootSessionRootWasAppliedTo=null}createQuicklookButton(){const i=Mo.getOrCreate().createQuicklookButton();return i.parentNode||this.context.menu.appendChild(i),i}},r(Ps,"invertForwardMatrix",new d.Matrix4().makeRotationY(Math.PI)),r(Ps,"invertForwardQuaternion",new d.Quaternion().setFromEuler(new d.Euler(0,Math.PI,0))),Ps);Ct([m(d.Object3D)],fi.prototype,"objectToExport");Ct([m()],fi.prototype,"autoExportAnimations");Ct([m()],fi.prototype,"autoExportAudioSources");Ct([m()],fi.prototype,"exportFileName");Ct([m(URL)],fi.prototype,"customUsdzFile");Ct([m(qr)],fi.prototype,"customBranding");Ct([m()],fi.prototype,"anchoringType");Ct([m()],fi.prototype,"maxTextureSize");Ct([m()],fi.prototype,"planeAnchoringAlignment");Ct([m()],fi.prototype,"interactive");Ct([m()],fi.prototype,"physics");Ct([m()],fi.prototype,"allowCreateQuicklookButton");Ct([m()],fi.prototype,"quickLookCompatible");let Kn=fi;var uk=Object.defineProperty,fk=Object.getOwnPropertyDescriptor,vy=(o,t,e,i)=>{for(var n=fk(t,e),s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&uk(t,e,n),n};class pl extends D{constructor(){super(...arguments);r(this,"_fog")}get fog(){return this._fog||(this._fog=new d.Fog(0,0,50)),this._fog}get mode(){return 1}set near(e){this.fog.near=e}get near(){return this.fog.near}set far(e){this.fog.far=e}get far(){return this.fog.far}set color(e){this.fog.color.copy(e)}get color(){return this.fog.color}onEnable(){this.scene.fog=this.fog}onDisable(){this.scene.fog===this._fog&&(this.scene.fog=null)}}vy([m()],pl.prototype,"near");vy([m()],pl.prototype,"far");vy([m(d.Color)],pl.prototype,"color");var pk=Object.defineProperty,wy=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&pk(t,e,n),n};class Xr extends D{constructor(){super(...arguments);r(this,"objectBounds",!1);r(this,"color");r(this,"isGizmo",!0);r(this,"_gizmoObject",null);r(this,"_boxHelper",null)}onEnable(){this.isGizmo&&!oh||(this._gizmoObject||(this.objectBounds?this._gizmoObject=new d.BoxHelper(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=hg(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),we.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){var e;for(;this._boxHelper;)(e=this._boxHelper)==null||e.update(),yield}}wy([m()],Xr.prototype,"objectBounds");wy([m(d.Color)],Xr.prototype,"color");wy([m()],Xr.prototype,"isGizmo");var mk=Object.defineProperty,xy=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&mk(t,e,n),n};class ml extends D{constructor(){super(...arguments);r(this,"isGizmo",!1);r(this,"color0");r(this,"color1");r(this,"gridHelper");r(this,"size");r(this,"divisions");r(this,"offset")}onEnable(){if(this.isGizmo&&!oh)return;const e=this.size,i=this.divisions;this.gridHelper||(this.gridHelper=new d.GridHelper(e,i,this.color0??new d.Color(.4,.4,.4),this.color1??new d.Color(.6,.6,.6)),this.offset!==void 0&&(this.gridHelper.position.y+=this.offset)),this.gridHelper&&this.gameObject.add(this.gridHelper)}onDisable(){this.gridHelper&&(this.gameObject.remove(this.gridHelper),this.gridHelper=null)}}xy([m()],ml.prototype,"isGizmo");xy([m(d.Color)],ml.prototype,"color0");xy([m(d.Color)],ml.prototype,"color1");var gk=Object.defineProperty,Sy=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&gk(t,e,n),n};class Cy extends D{constructor(){super(...arguments);r(this,"connectedBody");r(this,"_rigidBody",null)}get rigidBody(){return this._rigidBody}onEnable(){this._rigidBody||(this._rigidBody=this.gameObject.getComponent(ot)),this.rigidBody&&this.connectedBody&&this.startCoroutine(this.create())}*create(){yield,this.rigidBody&&this.connectedBody&&this.activeAndEnabled&&this.createJoint(this.rigidBody,this.connectedBody)}}Sy([m(ot)],Cy.prototype,"connectedBody");class Py extends Cy{createJoint(t,e){var i;(i=this.context.physics.engine)==null||i.addFixedJoint(t,e)}}class kh extends Cy{constructor(){super(...arguments);r(this,"anchor");r(this,"axis")}createJoint(e,i){var n;this.axis&&this.anchor&&((n=this.context.physics.engine)==null||n.addHingeJoint(e,i,this.anchor,this.axis))}}Sy([m(d.Vector3)],kh.prototype,"anchor");Sy([m(d.Vector3)],kh.prototype,"axis");var yk=Object.defineProperty,_k=Object.getOwnPropertyDescriptor,ls=(o,t,e,i)=>{for(var n=i>1?void 0:i?_k(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&yk(t,e,n),n};function Ep(o){return o*Math.PI/180}const Ab=300,Ks=S("debuglights");class pi extends D{constructor(){super(...arguments);r(this,"type",0);r(this,"range",1);r(this,"spotAngle",1);r(this,"innerSpotAngle",1);r(this,"_color",new d.Color(16777215));r(this,"_shadowNearPlane",.1);r(this,"_shadowBias",0);r(this,"_shadowNormalBias",0);r(this,"_overrideShadowBiasSettings",!1);r(this,"_shadows",1);r(this,"lightmapBakeType",4);r(this,"_intensity",-1);r(this,"_shadowDistance");r(this,"shadowWidth");r(this,"shadowHeight");r(this,"_shadowResolution");r(this,"light");r(this,"_webXRStartedListener");r(this,"_webXREndedListener");r(this,"_webARRoot")}set color(e){this._color=e,this.light!==void 0&&(this.light.color=e)}get color(){return this.light?this.light.color:this._color}set shadowNearPlane(e){var i,n;if(e!==this._shadowNearPlane&&(this._shadowNearPlane=e,((n=(i=this.light)==null?void 0:i.shadow)==null?void 0:n.camera)!==void 0)){const s=this.light.shadow.camera;s.near=e}}get shadowNearPlane(){return this._shadowNearPlane}set shadowBias(e){var i,n;e!==this._shadowBias&&(this._shadowBias=e,((n=(i=this.light)==null?void 0:i.shadow)==null?void 0:n.bias)!==void 0&&(this.light.shadow.bias=e,this.light.shadow.needsUpdate=!0))}get shadowBias(){return this._shadowBias}set shadowNormalBias(e){var i,n;e!==this._shadowNormalBias&&(this._shadowNormalBias=e,((n=(i=this.light)==null?void 0:i.shadow)==null?void 0:n.normalBias)!==void 0&&(this.light.shadow.normalBias=e,this.light.shadow.needsUpdate=!0))}get shadowNormalBias(){return this._shadowNormalBias}set shadows(e){this._shadows=e,this.light&&(this.light.castShadow=e!==0,this.updateShadowSoftHard())}get shadows(){return this._shadows}set intensity(e){var i;if(this._intensity=e,this.light){let n=1;if(this.context.isInXR&&this._webARRoot){const s=(i=this._webARRoot)==null?void 0:i.arScale;typeof s=="number"&&s>0&&(n/=s)}this.light.intensity=e*n}Ks&&console.log("Set light intensity to "+this._intensity,e,this)}get intensity(){return this._intensity}get shadowDistance(){const e=this.light;return e!=null&&e.shadow?e.shadow.camera.far:-1}set shadowDistance(e){this._shadowDistance=e;const i=this.light;if(i!=null&&i.shadow){const n=i.shadow.camera;n.far=e,n.updateProjectionMatrix()}}get shadowResolution(){const e=this.light;return e!=null&&e.shadow?e.shadow.mapSize.x:-1}set shadowResolution(e){if(e===this._shadowResolution)return;this._shadowResolution=e;const i=this.light;i!=null&&i.shadow&&(i.shadow.mapSize.set(e,e),i.shadow.needsUpdate=!0)}get isBaked(){return this.lightmapBakeType===2}get selfIsLight(){if(this.gameObject.isLight===!0)return!0;switch(this.gameObject.type){case"SpotLight":case"PointLight":case"DirectionalLight":return!0}return!1}getWorldPosition(e){return this.light?this.type===1?this.light.getWorldPosition(e).multiplyScalar(1):this.light.getWorldPosition(e):e}awake(){this.color=new d.Color(this.color??16777215),Ks&&console.log(this.name,this)}onEnable(){Ks&&console.log("ENABLE LIGHT",this.name),this.createLight(),!this.isBaked&&(this.light&&(this.light.visible=!0,this.light.intensity=this._intensity,Ks&&console.log("Set light intensity to "+this.light.intensity,this.name),this.selfIsLight||this.light.parent!==this.gameObject&&this.gameObject.add(this.light)),this.type===1&&this.startCoroutine(this.updateMainLightRoutine(),we.LateUpdate))}onDisable(){Ks&&console.log("DISABLE LIGHT",this.name),this.light&&(this.selfIsLight?this.light.intensity=0:this.light.visible=!1)}onEnterXR(e){this._webARRoot=C.getComponentInParent(this.gameObject,is)??void 0}onLeaveXR(e){}createLight(){const e=this.selfIsLight;if(e&&!this.light)switch(this.light=this.gameObject,this.light.name=this.name,this._intensity=this.light.intensity,this.type){case 1:this.setDirectionalLight(this.light);break}else if(!this.light)switch(this.type){case 1:const i=new d.DirectionalLight(this.color,this.intensity*Math.PI);if(i.position.set(0,0,-Ab*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(i.target),Pr(i.target,0,0,0),this.light=i,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),Ks){const l=new d.DirectionalLightHelper(this.light,.2,this.color);this.context.scene.add(l)}break;case 0:const n=new d.SpotLight(this.color,this.intensity*Math.PI,this.range,Ep(this.spotAngle/2),1-Ep(this.innerSpotAngle/2)/Ep(this.spotAngle/2),2);n.position.set(0,0,0),n.rotation.set(0,0,0),this.light=n;const s=n.target;n.add(s),s.position.set(0,0,this.range),s.rotation.set(0,0,0);break;case 2:const a=new d.PointLight(this.color,this.intensity*Math.PI,this.range);this.light=a;break}if(this.light){if(this._intensity>=0?this.light.intensity=this._intensity:this._intensity=this.light.intensity,this.shadows!==0?this.light.castShadow=!0:this.light.castShadow=!1,this.light.shadow){this._shadowResolution!==void 0&&this._shadowResolution>4?(this.light.shadow.mapSize.width=this._shadowResolution,this.light.shadow.mapSize.height=this._shadowResolution):(this.light.shadow.mapSize.width=2048,this.light.shadow.mapSize.height=2048),Ks&&console.log("Override shadow bias?",this._overrideShadowBiasSettings,this.shadowBias,this.shadowNormalBias),this.light.shadow.bias=this.shadowBias,this.light.shadow.normalBias=this.shadowNormalBias,this.updateShadowSoftHard();const i=this.light.shadow.camera;if(i.near=this.shadowNearPlane,this._shadowDistance!==void 0&&typeof this._shadowDistance=="number"?i.far=this._shadowDistance:i.far=Ab*Math.abs(this.gameObject.scale.z),this.gameObject.scale.set(1,1,1),this.shadowWidth!==void 0)i.left=-this.shadowWidth/2,i.right=this.shadowWidth/2;else{const n=this.gameObject.scale.x;i.left*=n,i.right*=n}if(this.shadowHeight!==void 0)i.top=this.shadowHeight/2,i.bottom=-this.shadowHeight/2;else{const n=this.gameObject.scale.y;i.top*=n,i.bottom*=n}this.light.shadow.needsUpdate=!0,Ks&&this.context.scene.add(new d.CameraHelper(i))}this.isBaked?this.light.removeFromParent():e||this.gameObject.add(this.light)}}*updateMainLightRoutine(){for(;;){this.type===1&&((!this.context.mainLight||this.intensity>this.context.mainLight.intensity)&&(this.context.mainLight=this),yield);break}}updateShadowSoftHard(){this.light&&this.light.shadow&&(this.shadows===2||(this.light.shadow.radius=1,this.light.shadow.blurSamples=1))}setDirectionalLight(e){e.add(e.target),e.target.position.set(0,0,-1)}}r(pi,"allowChangingRendererShadowMapType",!0);ls([m()],pi.prototype,"type",2);ls([m(d.Color)],pi.prototype,"color",1);ls([m()],pi.prototype,"shadowNearPlane",1);ls([m()],pi.prototype,"shadowBias",1);ls([m()],pi.prototype,"shadowNormalBias",1);ls([m()],pi.prototype,"shadows",1);ls([m()],pi.prototype,"lightmapBakeType",2);ls([m()],pi.prototype,"intensity",1);ls([m()],pi.prototype,"shadowDistance",1);ls([m()],pi.prototype,"shadowResolution",1);new d.Vector3(0,0,0);var bk=Object.defineProperty,Rh=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&bk(t,e,n),n};const Tp=S("debuglods"),vk=S("nolods");class gl{constructor(){r(this,"screenRelativeTransitionHeight");r(this,"distance");r(this,"renderers")}}Rh([m()],gl.prototype,"screenRelativeTransitionHeight");Rh([m()],gl.prototype,"distance");Rh([m(Ti)],gl.prototype,"renderers");class wk{constructor(t){r(this,"model");this.model=t}get renderers(){return this.model.renderers}}class Eh extends D{constructor(){super(...arguments);r(this,"fadeMode",0);r(this,"localReferencePoint");r(this,"lodCount",0);r(this,"size",0);r(this,"animateCrossFading",!1);r(this,"lodModels");r(this,"_lods",[]);r(this,"_settings",[]);r(this,"_lodsHandler");r(this,"_distanceFactor",1)}start(){if(Tp&&console.log("LODGROUP",this.name,this.lodModels,this),!vk&&!this._lodsHandler&&this.gameObject&&this.lodModels&&Array.isArray(this.lodModels)){const e=[];for(const n of this.lodModels){const s=new wk(n);this._lods.push(s);for(const a of s.renderers)e.includes(a)||e.push(a)}this._lodsHandler=new Array;for(let n=0;n<e.length;n++){const s=new d.LOD;this._lodsHandler.push(s),this.gameObject.add(s)}const i=new d.Object3D;i.name="Cull "+this.name;for(let n=0;n<e.length;n++){const s=e[n],a=this._lodsHandler[n],l=s.gameObject;Tp&&console.log(n,l.name);for(const c of this._lods){const h=c.model.distance;let u=null;if(c.renderers.includes(s)?u=l:u=i,u.type==="Group"){console.warn(`LODGroup ${this.name}: Group or MultiMaterial object's are not supported as LOD object: ${u.name}`);continue}Tp&&console.log("LEVEL",u.name,h),a.autoUpdate=!1,this.onAddLodLevel(a,u,c.model.distance)}}}}onAfterRender(){if(!this.gameObject||!this._lodsHandler)return;const e=this.context.mainCamera;if(e)for(const i of this._lodsHandler){i.update(e);const n=i.getCurrentLevel(),s=i.levels[n];i.layers.mask=s.object.layers.mask}}onAddLodLevel(e,i,n){if(i===this.gameObject){console.warn("LODGroup component must be on parent object and not mesh directly at the moment",i.name,i);return}e.addLevel(i,n*this._distanceFactor,.01);const s={lod:e,levelIndex:e.levels.length-1,distance:n};this._settings.push(s)}distanceFactor(e){if(e!==this._distanceFactor){this._distanceFactor=e;for(const i of this._settings){const n=i.lod.levels[i.levelIndex];n.distance=i.distance*e}}}}Rh([m(d.Vector3)],Eh.prototype,"localReferencePoint");Rh([m(gl)],Eh.prototype,"lodModels");var xk=Object.defineProperty,Sk=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&xk(t,e,n),n};const vd=S("debugnestedgltf");class pf extends D{constructor(){super(...arguments);r(this,"filePath");r(this,"loadAssetInParent",!0);r(this,"_isLoadingOrDoneLoading",!1)}listenToProgress(e){var i;(i=this.filePath)==null||i.beginListenDownload(e)}preload(){var e;(e=this.filePath)==null||e.preload()}async start(){var i,n,s,a,l;if(this._isLoadingOrDoneLoading)return;vd&&console.log(this,this.guid);const e=this.gameObject.parent;if(e){this._isLoadingOrDoneLoading=!0;const c=new Sn;c.idProvider=new bt(this.hash(this.guid)),c.parent=this.loadAssetInParent!==!1?e:this.gameObject,this.gameObject.updateMatrix();const h=this.gameObject.matrix;vd&&console.log("Load nested:",((i=this.filePath)==null?void 0:i.url)??this.filePath,this.gameObject.position);const u=await((s=(n=this.filePath)==null?void 0:n.instantiate)==null?void 0:s.call(this.filePath,c));vd&&console.log("Nested loaded:",((a=this.filePath)==null?void 0:a.url)??this.filePath,u),u&&this.loadAssetInParent!==!1&&(u.matrixAutoUpdate=!1,u.matrix.identity(),u.applyMatrix4(h),u.matrixAutoUpdate=!0,u.layers.disableAll(),u.layers.set(this.layer),this.dispatchEvent(new CustomEvent("loaded",{detail:{instance:u,assetReference:this.filePath}}))),vd&&console.log("Nested loading done:",((l=this.filePath)==null?void 0:l.url)??this.filePath,u)}}onDestroy(){var e;(e=this.filePath)==null||e.unload()}hash(e){let i=0;for(let n=0;n<e.length;n++)i=e.charCodeAt(n)+((i<<5)-i);return i}}Sk([m(te)],pf.prototype,"filePath");var Ck=Object.defineProperty,My=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&Ck(t,e,n),n};const Pk=S("debugnet"),mf=class Tm extends D{constructor(){super(...arguments);r(this,"url",null);r(this,"urlParameterName",null);r(this,"localhost",null)}awake(){Pk&&console.log(this),this.context.connection.registerProvider(this)}getWebsocketUrl(){let e=this.url?Tm.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){const a=S(this.urlParameterName);a&&typeof a=="string"&&(e=a)}if(!e)return null;const n=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(e);return n!=null&&n.groups?(n==null?void 0:n.groups.socket_prefix)?e:"wss://"+(n==null?void 0:n.groups.url):null}static GetUrl(e,i){let n=e;const s=Tm.IsLocalNetwork()&&i;if(s&&(n=i),e!=null&&e.startsWith("/")){const a=s?n:window.location.origin;a!=null&&a.endsWith("/")&&e.startsWith("/")&&(e=e.substring(1)),n=a+e}return n}static IsLocalNetwork(e=window.location.hostname){return Yt(e)}};My([m()],mf.prototype,"url");My([m()],mf.prototype,"urlParameterName");My([m()],mf.prototype,"localhost");let Oy=mf;var Mk=Object.defineProperty,gf=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&Mk(t,e,n),n};class Qr extends D{constructor(){super(...arguments);r(this,"referenceSpace");r(this,"from");r(this,"affectPosition",!1);r(this,"affectRotation",!1);r(this,"alignLookDirection",!1);r(this,"levelLookDirection",!1);r(this,"levelPosition",!1);r(this,"positionOffset",new d.Vector3(0,0,0));r(this,"rotationOffset",new d.Vector3(0,0,0));r(this,"offset",new d.Vector3(0,0,0))}update(){if(!this.from)return;var e=Q(this.from),i=_e(this.from);this.offset.copy(this.positionOffset);const n=this.offset.length();if(this.referenceSpace&&this.offset.transformDirection(this.referenceSpace.matrixWorld).multiplyScalar(n),e.add(this.offset),this.levelPosition&&this.referenceSpace){const c=new d.Plane(this.gameObject.up,0),h=Q(this.referenceSpace);c.setFromNormalAndCoplanarPoint(this.gameObject.up,h);const u=new d.Vector3(0,0,0);c.projectPoint(e,u),e.copy(u)}this.affectPosition&&st(this.gameObject,e);const s=new d.Euler(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),a=new d.Quaternion().setFromEuler(s);this.affectRotation&&Gi(this.gameObject,i.multiply(a));const l=new d.Vector3;this.from.getWorldDirection(l).multiplyScalar(50),this.levelLookDirection&&(l.y=0),this.alignLookDirection&&this.gameObject.lookAt(l)}}gf([m(C)],Qr.prototype,"referenceSpace");gf([m(C)],Qr.prototype,"from");gf([m(d.Vector3)],Qr.prototype,"positionOffset");gf([m(d.Vector3)],Qr.prototype,"rotationOffset");var Ok=Object.defineProperty,zo=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&Ok(t,e,n),n};class ai{constructor(t=0,e=0){r(this,"time",0);r(this,"value",0);r(this,"inTangent",1/0);r(this,"inWeight");r(this,"outTangent",1/0);r(this,"outWeight");r(this,"weightedMode");this.time=t,this.value=e}}zo([m()],ai.prototype,"time");zo([m()],ai.prototype,"value");zo([m()],ai.prototype,"inTangent");zo([m()],ai.prototype,"inWeight");zo([m()],ai.prototype,"outTangent");zo([m()],ai.prototype,"outWeight");zo([m()],ai.prototype,"weightedMode");const hx=class ic{constructor(){r(this,"keys",[])}static linearFromTo(t,e,i){const n=new ic,s=new ai;s.time=0,s.value=t;const a=new ai;return a.time=i,a.value=e,n.keys.push(s,a),n}static constant(t){const e=new ic,i=new ai;return i.time=0,i.value=t,e.keys.push(i),e}clone(){var e;const t=new ic;return t.keys=((e=this.keys)==null?void 0:e.map(i=>{const n=new ai;return n.time=i.time,n.value=i.value,n.inTangent=i.inTangent,n.inWeight=i.inWeight,n.outTangent=i.outTangent,n.outWeight=i.outWeight,n.weightedMode=i.weightedMode,n}))||[],t}get duration(){return!this.keys||this.keys.length==0?0:this.keys[this.keys.length-1].time}evaluate(t){if(!this.keys||this.keys.length==0)return 0;if(this.keys.length===1)return this.keys[0].value;if(this.keys[0].time>=t)return this.keys[0].value;for(let e=0;e<this.keys.length;e++){const i=this.keys[e];if(i.time<=t)if(e+1<this.keys.length){const s=this.keys[e+1];if(s.time<t)continue;return!isFinite(i.outTangent)||!isFinite(s.inTangent)?i.value:ic.interpolateValue(t,i,s)}else return i.value}return this.keys[this.keys.length-1].value}static interpolateValue(t,e,i){const n=e.time,s=e.value,a=e.outTangent,l=i.time,c=i.value,h=i.inTangent,u=l-n,f=u*u,p=f*u,g=((a+h)*u-2*(c-s))/p,y=(3*(c-s)-(h+2*a)*u)/f,b=a,_=s,v=t-n,w=v*v,x=w*v;return g*x+y*w+b*v+_}};zo([m(ai)],hx.prototype,"keys");let Th=hx;var kk=Object.defineProperty,P=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&kk(t,e,n),n};const wd=S("debugparticles");var bs=(o=>(o[o.Billboard=0]="Billboard",o[o.Stretch=1]="Stretch",o[o.HorizontalBillboard=2]="HorizontalBillboard",o[o.VerticalBillboard=3]="VerticalBillboard",o[o.Mesh=4]="Mesh",o))(bs||{});class Yr{constructor(){r(this,"alphaKeys",[]);r(this,"colorKeys",[])}get duration(){return 1}evaluate(t,e){let i,n=0,s=null,a=0;for(let l=0;l<this.alphaKeys.length;l++){const c=this.alphaKeys[l];(c.time<t||!i)&&(i=c,n=l)}for(let l=0;l<this.colorKeys.length;l++){const c=this.colorKeys[l];(c.time<t||!s)&&(s=c,a=l)}if(s)if(a+1<this.colorKeys.length){const c=this.colorKeys[a+1],h=z.remap(t,s.time,c.time,0,1);e.r=z.lerp(s.color.r,c.color.r,h),e.g=z.lerp(s.color.g,c.color.g,h),e.b=z.lerp(s.color.b,c.color.b,h)}else e.r=s.color.r,e.g=s.color.g,e.b=s.color.b;if(i)if(n+1<this.alphaKeys.length){const c=this.alphaKeys[n+1],h=z.remap(t,i.time,c.time,0,1);e.alpha=z.lerp(i.alpha,c.alpha,h)}else e.alpha=i.alpha;return e}}P([m()],Yr.prototype,"alphaKeys");P([m()],Yr.prototype,"colorKeys");var Vc=(o=>(o[o.Local=0]="Local",o[o.World=1]="World",o[o.Custom=2]="Custom",o))(Vc||{}),bu=(o=>(o[o.Sphere=0]="Sphere",o[o.SphereShell=1]="SphereShell",o[o.Hemisphere=2]="Hemisphere",o[o.HemisphereShell=3]="HemisphereShell",o[o.Cone=4]="Cone",o[o.Box=5]="Box",o[o.Mesh=6]="Mesh",o[o.ConeShell=7]="ConeShell",o[o.ConeVolume=8]="ConeVolume",o[o.ConeVolumeShell=9]="ConeVolumeShell",o[o.Circle=10]="Circle",o[o.CircleEdge=11]="CircleEdge",o[o.SingleSidedEdge=12]="SingleSidedEdge",o[o.MeshRenderer=13]="MeshRenderer",o[o.SkinnedMeshRenderer=14]="SkinnedMeshRenderer",o[o.BoxShell=15]="BoxShell",o[o.BoxEdge=16]="BoxEdge",o[o.Donut=17]="Donut",o[o.Rectangle=18]="Rectangle",o[o.Sprite=19]="Sprite",o[o.SpriteRenderer=20]="SpriteRenderer",o))(bu||{});const zs=class nc{constructor(){r(this,"mode","Constant");r(this,"constant");r(this,"constantMin");r(this,"constantMax");r(this,"curve");r(this,"curveMin");r(this,"curveMax");r(this,"curveMultiplier")}static constant(t){const e=new nc;return e.setConstant(t),e}static betweenTwoConstants(t,e){const i=new nc;return i.setMinMaxConstant(t,e),i}static curve(t,e=1){const i=new nc;return i.setCurve(t,e),i}setConstant(t){this.mode=0,this.constant=t}setMinMaxConstant(t,e){this.mode=3,this.constantMin=t,this.constantMax=e}setCurve(t,e=1){this.mode=1,this.curve=t,this.curveMultiplier=e}clone(){var e,i,n;const t=new nc;return t.mode=this.mode,t.constant=this.constant,t.constantMin=this.constantMin,t.constantMax=this.constantMax,t.curve=(e=this.curve)==null?void 0:e.clone(),t.curveMin=(i=this.curveMin)==null?void 0:i.clone(),t.curveMax=(n=this.curveMax)==null?void 0:n.clone(),t.curveMultiplier=this.curveMultiplier,t}evaluate(t,e){const i=e===void 0?Math.random():e;switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return t=z.clamp01(t),this.curve.evaluate(t)*this.curveMultiplier;case 2:case"TwoCurves":const n=t*this.curveMin.duration,s=t*this.curveMax.duration;return z.lerp(this.curveMin.evaluate(n),this.curveMax.evaluate(s),i%1)*this.curveMultiplier;case 3:case"TwoConstants":return z.lerp(this.constantMin,this.constantMax,i%1);default:this.curveMax.evaluate(t)*this.curveMultiplier;break}return 0}getMax(){switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return this.getMaxFromCurve(this.curve)*this.curveMultiplier;case 2:case"TwoCurves":return Math.max(this.getMaxFromCurve(this.curveMin),this.getMaxFromCurve(this.curveMax))*this.curveMultiplier;case 3:case"TwoConstants":return Math.max(this.constantMin,this.constantMax);default:return 0}}getMaxFromCurve(t){if(!t)return 0;let e=Number.MIN_VALUE;for(let i=0;i<t.keys.length;i++){const n=t.keys[i];n.value>e&&(e=n.value)}return e}};P([m()],zs.prototype,"mode");P([m()],zs.prototype,"constant");P([m()],zs.prototype,"constantMin");P([m()],zs.prototype,"constantMax");P([m(Th)],zs.prototype,"curve");P([m(Th)],zs.prototype,"curveMin");P([m(Th)],zs.prototype,"curveMax");P([m()],zs.prototype,"curveMultiplier");let q=zs;var Le;const No=(Le=class{constructor(){r(this,"mode",0);r(this,"color");r(this,"colorMin");r(this,"colorMax");r(this,"gradient");r(this,"gradientMin");r(this,"gradientMax")}static constant(t){const e=new Le;return e.constant(t),e}static betweenTwoColors(t,e){const i=new Le;return i.betweenTwoColors(t,e),i}constant(t){return this.mode=0,this.color=t,this}betweenTwoColors(t,e){return this.mode=2,this.colorMin=t,this.colorMax=e,this}evaluate(t,e){const i=e===void 0?Math.random():e;switch(this.mode){case 0:case"Color":return this.color;case 1:case"Gradient":return this.gradient.evaluate(t,Le._temp),Le._temp;case 2:case"TwoColors":return Le._temp.lerpColors(this.colorMin,this.colorMax,i);case 3:case"TwoGradients":return this.gradientMin.evaluate(t,Le._temp),this.gradientMax.evaluate(t,Le._temp2),Le._temp.lerp(Le._temp2,i);case 4:case"RandomColor":const s=Math.random();return this.gradientMin.evaluate(t,Le._temp),this.gradientMax.evaluate(t,Le._temp2),Le._temp.lerp(Le._temp2,s)}return Le._temp.set(16777215),Le._temp.alpha=1,Le._temp}},r(Le,"_temp",new ie(0,0,0,1)),r(Le,"_temp2",new ie(0,0,0,1)),Le);P([m()],No.prototype,"mode");P([m(ie)],No.prototype,"color");P([m(ie)],No.prototype,"colorMin");P([m(ie)],No.prototype,"colorMax");P([m(Yr)],No.prototype,"gradient");P([m(Yr)],No.prototype,"gradientMin");P([m(Yr)],No.prototype,"gradientMax");let Kr=No;var Am=(o=>(o[o.Hierarchy=0]="Hierarchy",o[o.Local=1]="Local",o[o.Shape=2]="Shape",o))(Am||{});class It{constructor(){r(this,"cullingMode");r(this,"duration");r(this,"emitterVelocityMode");r(this,"flipRotation");r(this,"gravityModifier");r(this,"gravityModifierMultiplier");r(this,"loop");r(this,"maxParticles");r(this,"playOnAwake");r(this,"prewarm");r(this,"ringBufferLoopRange");r(this,"ringBufferMode");r(this,"scalingMode");r(this,"simulationSpace");r(this,"simulationSpeed");r(this,"startColor");r(this,"startDelay");r(this,"startDelayMultiplier");r(this,"startLifetime");r(this,"startLifetimeMultiplier");r(this,"startRotation");r(this,"startRotationMultiplier");r(this,"startRotation3D");r(this,"startRotationX");r(this,"startRotationXMultiplier");r(this,"startRotationY");r(this,"startRotationYMultiplier");r(this,"startRotationZ");r(this,"startRotationZMultiplier");r(this,"startSize");r(this,"startSize3D");r(this,"startSizeMultiplier");r(this,"startSizeX");r(this,"startSizeXMultiplier");r(this,"startSizeY");r(this,"startSizeYMultiplier");r(this,"startSizeZ");r(this,"startSizeZMultiplier");r(this,"startSpeed");r(this,"startSpeedMultiplier");r(this,"stopAction");r(this,"useUnscaledTime")}}P([m(q)],It.prototype,"gravityModifier");P([m(Kr)],It.prototype,"startColor");P([m(q)],It.prototype,"startDelay");P([m(q)],It.prototype,"startLifetime");P([m(q)],It.prototype,"startRotation");P([m(q)],It.prototype,"startRotationX");P([m(q)],It.prototype,"startRotationY");P([m(q)],It.prototype,"startRotationZ");P([m(q)],It.prototype,"startSize");P([m(q)],It.prototype,"startSizeX");P([m(q)],It.prototype,"startSizeY");P([m(q)],It.prototype,"startSizeZ");P([m(q)],It.prototype,"startSpeed");class vu{constructor(){r(this,"cycleCount");r(this,"maxCount");r(this,"minCount");r(this,"probability");r(this,"repeatInterval");r(this,"time");r(this,"count");r(this,"_performed",0)}reset(){this._performed=0}run(t){if(t<=this.time)return 0;let e=0;if(this.cycleCount===0||this._performed<this.cycleCount){const i=this.time+this.repeatInterval*this._performed;if(t>=i&&(this._performed+=1,Math.random()<this.probability))switch(this.count.mode){case 0:e=this.count.constant;break;case 3:e=z.lerp(this.count.constantMin,this.count.constantMax,Math.random());break;case 1:e=this.count.curve.evaluate(Math.random());break;case 2:const n=Math.random();e=z.lerp(this.count.curveMin.evaluate(n),this.count.curveMax.evaluate(n),Math.random());break}}return e}}class Ns{constructor(){r(this,"enabled");r(this,"bursts");r(this,"rateOverTime");r(this,"rateOverTimeMultiplier");r(this,"rateOverDistance");r(this,"rateOverDistanceMultiplier");r(this,"system")}get burstCount(){var t;return((t=this.bursts)==null?void 0:t.length)??0}reset(){var t;(t=this.bursts)==null||t.forEach(e=>e.reset())}getBurst(){let t=0;if(this.burstCount>0)for(let e=0;e<this.burstCount;e++){const i=this.bursts[e];this.system.main.loop&&i.time>=this.system.time&&i.reset(),t+=Math.round(i.run(this.system.time))}return t}}P([m()],Ns.prototype,"enabled");P([m()],Ns.prototype,"bursts");P([m(q)],Ns.prototype,"rateOverTime");P([m()],Ns.prototype,"rateOverTimeMultiplier");P([m(q)],Ns.prototype,"rateOverDistance");P([m()],Ns.prototype,"rateOverDistanceMultiplier");class yf{constructor(){r(this,"enabled");r(this,"color")}}P([m(Kr)],yf.prototype,"color");class Zr{constructor(){r(this,"enabled");r(this,"separateAxes");r(this,"size");r(this,"sizeMultiplier");r(this,"x");r(this,"xMultiplier");r(this,"y");r(this,"yMultiplier");r(this,"z");r(this,"zMultiplier");r(this,"_time",0);r(this,"_temp",new d.Vector3)}evaluate(t,e,i){if(e||(e=this._temp),!this.enabled)return e.x=e.y=e.z=1,e;if(this.separateAxes)e.x=this.x.evaluate(t,i)*this.xMultiplier,e.y=this.y.evaluate(t,i)*this.yMultiplier,e.z=this.z.evaluate(t,i)*this.zMultiplier;else{const n=this.size.evaluate(t,i)*this.sizeMultiplier;e.x=n}return e}}P([m(q)],Zr.prototype,"size");P([m(q)],Zr.prototype,"x");P([m(q)],Zr.prototype,"y");P([m(q)],Zr.prototype,"z");var gn;const Ze=(gn=class{constructor(){r(this,"shapeType",5);r(this,"enabled",!0);r(this,"alignToDirection",!1);r(this,"angle",0);r(this,"arc",360);r(this,"arcSpread");r(this,"arcSpeedMultiplier");r(this,"arcMode");r(this,"boxThickness");r(this,"position");r(this,"rotation");r(this,"_rotation",new d.Euler);r(this,"scale");r(this,"radius");r(this,"radiusThickness");r(this,"sphericalDirectionAmount");r(this,"randomDirectionAmount");r(this,"randomPositionAmount");r(this,"meshShapeType");r(this,"meshRenderer");r(this,"_meshObj");r(this,"_meshGeometry");r(this,"system");r(this,"_space");r(this,"_worldSpaceMatrix",new d.Matrix4);r(this,"_worldSpaceMatrixInverse",new d.Matrix4);r(this,"_vector",new d.Vector3(0,0,0));r(this,"_temp",new d.Vector3(0,0,0));r(this,"_triangle",new d.Triangle);r(this,"_dir",new d.Vector3);r(this,"_loopTime",0);r(this,"_loopDirection",1);wd&&console.log(this)}get type(){return bu[this.shapeType]}initialize(t){this.onInitialize(t),t.position.x=this._vector.x,t.position.y=this._vector.y,t.position.z=this._vector.z}toJSON(){return this}clone(){return new gn}setMesh(t){this.meshRenderer=t,t?(this._meshObj=t.sharedMeshes[Math.floor(Math.random()*t.sharedMeshes.length)],this._meshGeometry=this._meshObj.geometry):(this._meshObj=void 0,this._meshGeometry=void 0)}update(t,e){}onUpdate(t,e,i,n){this.system=t,this._space=i,i===1&&(this._worldSpaceMatrix.copy(n.matrixWorld),this._worldSpaceMatrix.elements[0]=1,this._worldSpaceMatrix.elements[5]=1,this._worldSpaceMatrix.elements[10]=1,this._worldSpaceMatrixInverse.copy(this._worldSpaceMatrix).invert())}applyRotation(t){const e=this.rotation.x!==0||this.rotation.y!==0||this.rotation.z!==0;return e&&(this._rotation.x=z.toRadians(this.rotation.x),this._rotation.y=z.toRadians(this.rotation.y),this._rotation.z=z.toRadians(this.rotation.z),this._rotation.order="ZYX",t.applyEuler(this._rotation)),e}onInitialize(t){this._vector.set(0,0,0),t.mesh=void 0,t.mesh_geometry=void 0;const e=this._temp.copy(this.position),i=this._space===1;i&&e.applyQuaternion(this.system.worldQuaternion);let n=this.radius;if(i&&(n*=this.system.worldScale.x),this.enabled){switch(this.shapeType){case 5:wd&&V.DrawWireBox(this.position,this.scale,14540253,1),this._vector.x=Math.random()*this.scale.x-this.scale.x/2,this._vector.y=Math.random()*this.scale.y-this.scale.y/2,this._vector.z=Math.random()*this.scale.z-this.scale.z/2,this._vector.add(e);break;case 4:this.randomConePoint(this.position,this.angle,n,this.radiusThickness,this.arc,this.arcMode,this._vector);break;case 0:this.randomSpherePoint(this.position,n,this.radiusThickness,this.arc,this._vector);break;case 10:this.randomCirclePoint(this.position,n,this.radiusThickness,this.arc,this._vector);break;case 13:const s=this.meshRenderer;(s==null?void 0:s.destroyed)==!1&&this.setMesh(s);const a=t.mesh=this._meshObj,l=t.mesh_geometry=this._meshGeometry;if(a&&l)switch(this.meshShapeType){case 0:{const c=l.getAttribute("position"),h=Math.floor(Math.random()*c.count);this._vector.fromBufferAttribute(c,h),this._vector.applyMatrix4(a.matrixWorld),t.mesh_normal=h}break;case 1:break;case 2:{const c=l.index;if(c){let h=Math.random(),u=Math.random();h+u>1&&(h=1-h,u=1-u);const f=Math.floor(Math.random()*(c.count/3));let p=f*3,g=f*3+1,y=f*3+2;p=c.getX(p),g=c.getX(g),y=c.getX(y);const b=l.getAttribute("position");this._triangle.a.fromBufferAttribute(b,p),this._triangle.b.fromBufferAttribute(b,g),this._triangle.c.fromBufferAttribute(b,y),this._vector.set(0,0,0).addScaledVector(this._triangle.a,h).addScaledVector(this._triangle.b,u).addScaledVector(this._triangle.c,1-(h+u)),this._vector.applyMatrix4(a.matrixWorld),t.mesh_normal=f}}break}break;default:this._vector.set(0,0,0),j()&&!globalThis.__particlesystem_shapetype_unsupported&&(console.warn("ParticleSystem ShapeType is not supported:",bu[this.shapeType]),globalThis.__particlesystem_shapetype_unsupported=!0);break}this.randomizePosition(this._vector,this.randomPositionAmount)}this.applyRotation(this._vector),i&&(this._vector.applyQuaternion(this.system.worldQuaternion),this._vector.add(this.system.worldPos)),wd&&V.DrawSphere(this._vector,.03,16711680,.5,!0)}getDirection(t,e){var i;if(!this.enabled)return this._dir.set(0,0,1),this._dir;switch(this.shapeType){case 5:this._dir.set(0,0,1);break;case 4:this._dir.set(0,0,1);break;case 10:case 0:const n=e.x,s=e.y,a=e.z;this._dir.set(n,s,a),(i=this.system)!=null&&i.worldspace?this._dir.sub(this.system.worldPos):this._dir.sub(this.position);break;case 13:const l=t.mesh,c=t.mesh_geometry;if(l&&c)switch(this.meshShapeType){case 0:{const h=c.getAttribute("normal"),u=t.mesh_normal;this._dir.fromBufferAttribute(h,u)}break;case 1:break;case 2:{const h=c.index;if(h){const u=t.mesh_normal,f=h.getX(u*3),p=h.getX(u*3+1),g=h.getX(u*3+2),y=c.getAttribute("position"),b=$(),_=$(),v=$();b.fromBufferAttribute(y,f),_.fromBufferAttribute(y,p),v.fromBufferAttribute(y,g),b.sub(_),v.sub(_),b.cross(v),this._dir.copy(b).multiplyScalar(-1);const w=_e(l);this._dir.applyQuaternion(w)}}break}break;default:this._dir.set(0,0,1);break}return this._space===1&&this._dir.applyQuaternion(this.system.worldQuaternion),this.applyRotation(this._dir),this._dir.normalize(),this.spherizeDirection(this._dir,this.sphericalDirectionAmount),this.randomizeDirection(this._dir,this.randomDirectionAmount),wd&&(V.DrawSphere(e,.01,8925952,.5,!0),V.DrawDirection(e,this._dir,8925952,.5,!0)),this._dir}randomizePosition(t,e){if(e<=0)return;const i=gn._tempVec;i.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1),i.x*=e*this.scale.x,i.y*=e*this.scale.y,i.z*=e*this.scale.z,t.add(i)}randomizeDirection(t,e){if(e===0)return;const i=gn._randomQuat,n=gn._tempVec;n.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),i.setFromAxisAngle(n,e*Math.random()*Math.PI),t.applyQuaternion(i)}spherizeDirection(t,e){if(e===0)return;const i=Math.random()*Math.PI*2,n=Math.acos(1-Math.random()*2),s=Math.sin(n)*Math.cos(i),a=Math.sin(n)*Math.sin(i),l=Math.cos(n),c=new d.Vector3(s,a,l);t.lerp(c,e)}randomSpherePoint(t,e,i,n,s){const a=Math.random(),l=Math.random(),c=2*Math.PI*a*(n/360),h=Math.acos(2*l-1),u=z.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*e,f=t.x+this.scale.x*(-u*Math.sin(h)*Math.cos(c)),p=t.y+this.scale.y*(u*Math.sin(h)*Math.sin(c)),g=t.z+this.scale.z*(u*Math.cos(h));s.x=f,s.y=p,s.z=g}randomCirclePoint(t,e,i,n,s){const a=Math.random(),l=2*Math.PI*a*(n/360),c=z.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*e,h=t.x+this.scale.x*c*Math.cos(l),u=t.y+this.scale.y*c*Math.sin(l),f=t.z;s.x=h,s.y=u,s.z=f}randomConePoint(t,e,i,n,s,a,l){let c=0,h=0;switch(a){case 0:c=Math.random(),h=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:c=.5,h=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let u=2*Math.PI*c*(s/360);switch(a){case 2:case 1:u+=Math.PI+.5,u+=this._loopTime*Math.PI*2,u%=z.toRadians(s);break}const f=Math.acos(2*h-1),p=z.lerp(1,1-Math.pow(1-Math.random(),Math.PI),n)*i,g=t.x+-p*Math.sin(f)*Math.cos(u),y=t.y+p*Math.sin(f)*Math.sin(u),b=t.z;l.x=g*this.scale.x,l.y=y*this.scale.y,l.z=b*this.scale.z}},r(gn,"_randomQuat",new d.Quaternion),r(gn,"_tempVec",new d.Vector3),gn);P([m()],Ze.prototype,"shapeType");P([m()],Ze.prototype,"enabled");P([m()],Ze.prototype,"alignToDirection");P([m()],Ze.prototype,"angle");P([m()],Ze.prototype,"arc");P([m()],Ze.prototype,"arcSpread");P([m()],Ze.prototype,"arcSpeedMultiplier");P([m()],Ze.prototype,"arcMode");P([m(d.Vector3)],Ze.prototype,"boxThickness");P([m(d.Vector3)],Ze.prototype,"position");P([m(d.Vector3)],Ze.prototype,"rotation");P([m(d.Vector3)],Ze.prototype,"scale");P([m()],Ze.prototype,"radius");P([m()],Ze.prototype,"radiusThickness");P([m()],Ze.prototype,"sphericalDirectionAmount");P([m()],Ze.prototype,"randomDirectionAmount");P([m()],Ze.prototype,"randomPositionAmount");P([m()],Ze.prototype,"meshShapeType");P([m(bh)],Ze.prototype,"meshRenderer");let ky=Ze;class be{constructor(){r(this,"damping");r(this,"enabled");r(this,"frequency");r(this,"octaveCount");r(this,"octaveMultiplier");r(this,"octaveScale");r(this,"positionAmount");r(this,"quality");r(this,"remap");r(this,"remapEnabled");r(this,"remapMultiplier");r(this,"remapX");r(this,"remapXMultiplier");r(this,"remapY");r(this,"remapYMultiplier");r(this,"remapZ");r(this,"remapZMultiplier");r(this,"scrollSpeedMultiplier");r(this,"separateAxes");r(this,"strengthMultiplier");r(this,"strengthX");r(this,"strengthXMultiplier");r(this,"strengthY");r(this,"strengthYMultiplier");r(this,"strengthZ");r(this,"strengthZMultiplier");r(this,"_noise");r(this,"_time",0);r(this,"_temp",new d.Vector3)}update(t){this._time+=t.time.deltaTime*this.scrollSpeedMultiplier}apply(t,e,i,n,s,a){if(!this.enabled)return;this._noise||(this._noise=ae.createNoise4D(()=>0));const l=this._temp.set(e.x,e.y,e.z).multiplyScalar(this.frequency),c=this._noise(l.x,l.y,l.z,this._time),h=this._noise(l.x,l.y,l.z,this._time+1e3*this.frequency),u=this._noise(l.x,l.y,l.z,this._time+2e3*this.frequency);this._temp.set(c,h,u).normalize();const f=s/a;let p=this.positionAmount.evaluate(f);this.separateAxes?(this._temp.x*=p*this.strengthXMultiplier,this._temp.y*=p*this.strengthYMultiplier,this._temp.z*=p*this.strengthZMultiplier):(this.strengthX&&(p*=this.strengthX.evaluate(f)*1.5),this._temp.multiplyScalar(p)),i.x+=this._temp.x,i.y+=this._temp.y,i.z+=this._temp.z}}P([m()],be.prototype,"damping");P([m()],be.prototype,"enabled");P([m()],be.prototype,"frequency");P([m()],be.prototype,"octaveCount");P([m()],be.prototype,"octaveMultiplier");P([m()],be.prototype,"octaveScale");P([m(q)],be.prototype,"positionAmount");P([m()],be.prototype,"quality");P([m(q)],be.prototype,"remap");P([m()],be.prototype,"remapEnabled");P([m()],be.prototype,"remapMultiplier");P([m(q)],be.prototype,"remapX");P([m()],be.prototype,"remapXMultiplier");P([m(q)],be.prototype,"remapY");P([m()],be.prototype,"remapYMultiplier");P([m(q)],be.prototype,"remapZ");P([m()],be.prototype,"remapZMultiplier");P([m()],be.prototype,"scrollSpeedMultiplier");P([m()],be.prototype,"separateAxes");P([m()],be.prototype,"strengthMultiplier");P([m(q)],be.prototype,"strengthX");P([m()],be.prototype,"strengthXMultiplier");P([m(q)],be.prototype,"strengthY");P([m()],be.prototype,"strengthYMultiplier");P([m(q)],be.prototype,"strengthZ");P([m()],be.prototype,"strengthZMultiplier");class je{constructor(){r(this,"enabled");r(this,"attachRibbonToTransform",!1);r(this,"colorOverLifetime");r(this,"colorOverTrail");r(this,"dieWithParticles",!0);r(this,"inheritParticleColor",!0);r(this,"lifetime");r(this,"lifetimeMultiplier");r(this,"minVertexDistance",.2);r(this,"mode",0);r(this,"ratio",1);r(this,"ribbonCount",1);r(this,"shadowBias",0);r(this,"sizeAffectsLifetime",!1);r(this,"sizeAffectsWidth",!1);r(this,"splitSubEmitterRibbons",!1);r(this,"textureMode",0);r(this,"widthOverTrail");r(this,"widthOverTrailMultiplier");r(this,"worldSpace",!1)}getWidth(t,e,i,n){const s=this.widthOverTrail.evaluate(i,n);return t*=s,t}getColor(t,e,i){const n=this.colorOverTrail.evaluate(i),s=this.colorOverLifetime.evaluate(e);t.x*=n.r*s.r,t.y*=n.g*s.g,t.z*=n.b*s.b,"alpha"in n&&"alpha"in s&&(t.w*=n.alpha*s.alpha)}}P([m()],je.prototype,"enabled");P([m()],je.prototype,"attachRibbonToTransform");P([m(Kr)],je.prototype,"colorOverLifetime");P([m(Kr)],je.prototype,"colorOverTrail");P([m()],je.prototype,"dieWithParticles");P([m()],je.prototype,"inheritParticleColor");P([m(q)],je.prototype,"lifetime");P([m()],je.prototype,"lifetimeMultiplier");P([m()],je.prototype,"minVertexDistance");P([m()],je.prototype,"mode");P([m()],je.prototype,"ratio");P([m()],je.prototype,"ribbonCount");P([m()],je.prototype,"shadowBias");P([m()],je.prototype,"sizeAffectsLifetime");P([m()],je.prototype,"sizeAffectsWidth");P([m()],je.prototype,"splitSubEmitterRibbons");P([m()],je.prototype,"textureMode");P([m(q)],je.prototype,"widthOverTrail");P([m()],je.prototype,"widthOverTrailMultiplier");P([m()],je.prototype,"worldSpace");class ze{constructor(){r(this,"enabled");r(this,"space",0);r(this,"orbitalX");r(this,"orbitalY");r(this,"orbitalZ");r(this,"orbitalXMultiplier");r(this,"orbitalYMultiplier");r(this,"orbitalZMultiplier");r(this,"orbitalOffsetX");r(this,"orbitalOffsetY");r(this,"orbitalOffsetZ");r(this,"speedModifier");r(this,"speedModifierMultiplier");r(this,"x");r(this,"xMultiplier");r(this,"y");r(this,"yMultiplier");r(this,"z");r(this,"zMultiplier");r(this,"_system");r(this,"_temp",new d.Vector3);r(this,"_temp2",new d.Vector3);r(this,"_temp3",new d.Vector3);r(this,"_hasOrbital",!1);r(this,"_index",0);r(this,"_orbitalMatrix",new d.Matrix4)}update(t){this._system=t}init(t){this._index==0&&(t.debug=!0),this._index+=1,t.orbitx=this.orbitalX.evaluate(Math.random()),t.orbity=this.orbitalY.evaluate(Math.random()),t.orbitz=this.orbitalZ.evaluate(Math.random()),this._hasOrbital=t.orbitx!=0||t.orbity!=0||t.orbitz!=0}apply(t,e,i,n,s,a,l){var g;if(!this.enabled)return;const c=a/l,h=this.speedModifier.evaluate(c)*this.speedModifierMultiplier,u=this.x.evaluate(c),f=this.y.evaluate(c),p=this.z.evaluate(c);if(this._temp.set(-u,f,p),this._system&&this._system.main.simulationSpace===1&&this._temp.applyQuaternion(this._system.worldQuaternion),this._hasOrbital&&((g=this._system)==null?void 0:g.worldPos)){const b=this._temp2.set(i.x,i.y,i.z),_=this.orbitalXMultiplier,v=this.orbitalYMultiplier,w=this.orbitalZMultiplier,x=h*Math.PI*2*10,O=Math.cos(x*_),M=Math.sin(x*_),R=Math.cos(x*v),E=Math.sin(x*v),F=Math.cos(x*w),T=Math.sin(x*w),L=b.x*(R*F)+b.y*(R*T)+b.z*-E,A=b.x*(M*E*F-O*T)+b.y*(M*E*T+O*F)+b.z*(M*R),H=b.x*(O*E*F+M*T)+b.y*(O*E*T-M*F)+b.z*(O*R),B=this._temp3.set(b.x-L,b.y-A,b.z-H);B.normalize(),B.multiplyScalar(.2/s*Math.max(this.orbitalXMultiplier,this.orbitalYMultiplier,this.orbitalZMultiplier)),n.x+=B.x,n.y+=B.y,n.z+=B.z}n.x+=this._temp.x,n.y+=this._temp.y,n.z+=this._temp.z,n.x*=h,n.y*=h,n.z*=h}}P([m()],ze.prototype,"enabled");P([m()],ze.prototype,"space");P([m(q)],ze.prototype,"orbitalX");P([m(q)],ze.prototype,"orbitalY");P([m(q)],ze.prototype,"orbitalZ");P([m()],ze.prototype,"orbitalXMultiplier");P([m()],ze.prototype,"orbitalYMultiplier");P([m()],ze.prototype,"orbitalZMultiplier");P([m()],ze.prototype,"orbitalOffsetX");P([m()],ze.prototype,"orbitalOffsetY");P([m()],ze.prototype,"orbitalOffsetZ");P([m(q)],ze.prototype,"speedModifier");P([m()],ze.prototype,"speedModifierMultiplier");P([m(q)],ze.prototype,"x");P([m()],ze.prototype,"xMultiplier");P([m(q)],ze.prototype,"y");P([m()],ze.prototype,"yMultiplier");P([m(q)],ze.prototype,"z");P([m()],ze.prototype,"zMultiplier");class jt{constructor(){r(this,"animation");r(this,"enabled");r(this,"cycleCount");r(this,"frameOverTime");r(this,"frameOverTimeMultiplier");r(this,"numTilesX");r(this,"numTilesY");r(this,"startFrame");r(this,"startFrameMultiplier");r(this,"rowMode");r(this,"rowIndex");r(this,"spriteCount");r(this,"timeMode")}sampleOnceAtStart(){if(this.timeMode===0)switch(this.frameOverTime.mode){case 0:case 3:case 2:case 1:return!0}return!1}getStartIndex(){return this.sampleOnceAtStart()?Math.random()*(this.numTilesX*this.numTilesY):0}evaluate(t){if(!this.sampleOnceAtStart())return this.getIndex(t)}getIndex(t){const e=this.numTilesX*this.numTilesY;t=t*this.cycleCount;let i=this.frameOverTime.evaluate(t%1);return i*=this.frameOverTimeMultiplier,i*=e,i=i%e,i=Math.floor(i),i}}P([m()],jt.prototype,"animation");P([m()],jt.prototype,"enabled");P([m()],jt.prototype,"cycleCount");P([m(q)],jt.prototype,"frameOverTime");P([m()],jt.prototype,"frameOverTimeMultiplier");P([m()],jt.prototype,"numTilesX");P([m()],jt.prototype,"numTilesY");P([m(q)],jt.prototype,"startFrame");P([m()],jt.prototype,"startFrameMultiplier");P([m()],jt.prototype,"rowMode");P([m()],jt.prototype,"rowIndex");P([m()],jt.prototype,"spriteCount");P([m()],jt.prototype,"timeMode");class Pn{constructor(){r(this,"enabled");r(this,"separateAxes");r(this,"x");r(this,"xMultiplier");r(this,"y");r(this,"yMultiplier");r(this,"z");r(this,"zMultiplier")}evaluate(t,e){return this.enabled?this.separateAxes?0:this.z.evaluate(t,e)*-1:0}}P([m()],Pn.prototype,"enabled");P([m()],Pn.prototype,"separateAxes");P([m(q)],Pn.prototype,"x");P([m()],Pn.prototype,"xMultiplier");P([m(q)],Pn.prototype,"y");P([m()],Pn.prototype,"yMultiplier");P([m(q)],Pn.prototype,"z");P([m()],Pn.prototype,"zMultiplier");class Ji{constructor(){r(this,"enabled");r(this,"range");r(this,"separateAxes");r(this,"x");r(this,"xMultiplier");r(this,"y");r(this,"yMultiplier");r(this,"z");r(this,"zMultiplier")}evaluate(t,e){if(!this.enabled)return 0;if(!this.separateAxes){const i=z.lerp(this.range.x,this.range.y,e);return this.z.evaluate(i)*-1}return 0}}P([m()],Ji.prototype,"enabled");P([m()],Ji.prototype,"range");P([m()],Ji.prototype,"separateAxes");P([m(q)],Ji.prototype,"x");P([m()],Ji.prototype,"xMultiplier");P([m(q)],Ji.prototype,"y");P([m()],Ji.prototype,"yMultiplier");P([m(q)],Ji.prototype,"z");P([m()],Ji.prototype,"zMultiplier");class lt{constructor(){r(this,"enabled");r(this,"dampen");r(this,"drag");r(this,"dragMultiplier");r(this,"limit");r(this,"limitMultiplier");r(this,"separateAxes");r(this,"limitX");r(this,"limitXMultiplier");r(this,"limitY");r(this,"limitYMultiplier");r(this,"limitZ");r(this,"limitZMultiplier");r(this,"multiplyDragByParticleSize",!1);r(this,"multiplyDragByParticleVelocity",!1);r(this,"space");r(this,"_temp",new d.Vector3);r(this,"_temp2",new d.Vector3)}apply(t,e,i,n,s,a,l){if(this.enabled){const c=this.limit.evaluate(s)*this.limitMultiplier;if(e.length()>c){this._temp.copy(e).normalize().multiplyScalar(c);const u=this.dampen*.5;e.x=z.lerp(e.x,this._temp.x,u),e.y=z.lerp(e.y,this._temp.y,u),e.z=z.lerp(e.z,this._temp.z,u),i.x=z.lerp(i.x,this._temp.x,u),i.y=z.lerp(i.y,this._temp.y,u),i.z=z.lerp(i.z,this._temp.z,u)}}}}P([m()],lt.prototype,"enabled");P([m()],lt.prototype,"dampen");P([m(q)],lt.prototype,"drag");P([m()],lt.prototype,"dragMultiplier");P([m(q)],lt.prototype,"limit");P([m()],lt.prototype,"limitMultiplier");P([m()],lt.prototype,"separateAxes");P([m(q)],lt.prototype,"limitX");P([m()],lt.prototype,"limitXMultiplier");P([m(q)],lt.prototype,"limitY");P([m()],lt.prototype,"limitYMultiplier");P([m(q)],lt.prototype,"limitZ");P([m()],lt.prototype,"limitZMultiplier");P([m()],lt.prototype,"multiplyDragByParticleSize");P([m()],lt.prototype,"multiplyDragByParticleVelocity");P([m()],lt.prototype,"space");const Ah=class dx{constructor(){r(this,"enabled");r(this,"curve");r(this,"curveMultiplier");r(this,"mode");r(this,"system");r(this,"_temp",new d.Vector3);r(this,"_firstUpdate",!0);r(this,"_frames",0)}clone(){var e;const t=new dx;return t.enabled=this.enabled,t.curve=(e=this.curve)==null?void 0:e.clone(),t.curveMultiplier=this.curveMultiplier,t.mode=this.mode,t}get _lastWorldPosition(){return this.system._iv_lastWorldPosition||(this.system._iv_lastWorldPosition=new d.Vector3),this.system._iv_lastWorldPosition}get _velocity(){return this.system._iv_velocity||(this.system._iv_velocity=new d.Vector3),this.system._iv_velocity}awake(t){this.system=t,this.reset()}reset(){this._firstUpdate=!0}update(t){this.enabled&&this.system.worldspace!==!1&&(this._firstUpdate?(this._firstUpdate=!1,this._velocity.set(0,0,0),this._lastWorldPosition.copy(this.system.worldPos)):this._lastWorldPosition&&(this._velocity.copy(this.system.worldPos).sub(this._lastWorldPosition).multiplyScalar(1/this.system.deltaTime),this._lastWorldPosition.copy(this.system.worldPos)))}applyInitial(t){if(this.enabled&&this.system.worldspace!==!1&&this.mode===0){const e=this.curve.evaluate(Math.random(),Math.random());this._temp.copy(this._velocity).multiplyScalar(e),t.x+=this._temp.x,t.y+=this._temp.y,t.z+=this._temp.z}}applyCurrent(t,e,i){if(this.enabled&&this.system&&this.system.worldspace!==!1&&this.mode===1){const n=this.curve.evaluate(e,i);this._temp.copy(this._velocity).multiplyScalar(n),t.x+=this._temp.x,t.y+=this._temp.y,t.z+=this._temp.z}}};P([m()],Ah.prototype,"enabled");P([m(q)],Ah.prototype,"curve");P([m()],Ah.prototype,"curveMultiplier");P([m()],Ah.prototype,"mode");let Ry=Ah;class mi{constructor(){r(this,"enabled");r(this,"range");r(this,"separateAxes");r(this,"size");r(this,"sizeMultiplier");r(this,"x");r(this,"xMultiplier");r(this,"y");r(this,"yMultiplier");r(this,"z");r(this,"zMultiplier")}evaluate(t,e,i,n){const s=t.length(),a=z.remap(s,this.range.x,this.range.y,0,1),l=this.size.evaluate(a,i);return n.x*=l,n.y*=l,n.z*=l,n}}P([m()],mi.prototype,"enabled");P([m(d.Vector2)],mi.prototype,"range");P([m()],mi.prototype,"separateAxes");P([m(q)],mi.prototype,"size");P([m()],mi.prototype,"sizeMultiplier");P([m(q)],mi.prototype,"x");P([m()],mi.prototype,"xMultiplier");P([m(q)],mi.prototype,"y");P([m()],mi.prototype,"yMultiplier");P([m(q)],mi.prototype,"z");P([m()],mi.prototype,"zMultiplier");class yl{constructor(){r(this,"enabled");r(this,"range");r(this,"color")}evaluate(t,e,i){const n=t.length(),s=z.remap(n,this.range.x,this.range.y,0,1),a=this.color.evaluate(s,e);i.x*=a.r,i.y*=a.g,i.z*=a.b,"alpha"in a&&(i.w*=a.alpha)}}P([m()],yl.prototype,"enabled");P([m(d.Vector2)],yl.prototype,"range");P([m(Kr)],yl.prototype,"color");new d.Vector3(1,1,1);new d.Vector3(0,0,1);class Ey{constructor(t,e,i,n){r(this,"type","NeedleParticleSubEmitter");r(this,"emitterType");r(this,"emitterProbability");r(this,"q_",new d.Quaternion);r(this,"v_",new d.Vector3);r(this,"v2_",new d.Vector3);r(this,"_emitterMatrix",new ae.Matrix4);r(this,"_circularBuffer");this.system=t,this.particleSystem=e,this.subSystem=i,this.subParticleSystem=n,this.subParticleSystem&&this.subParticleSystem&&(this.subParticleSystem.onlyUsedByOther=!0);const s=1e3;this._circularBuffer=new ki(()=>new ae.Matrix4,s)}clone(){throw new Error("Method not implemented.")}initialize(t){t.emissionState={burstIndex:0,burstWaveIndex:0,time:0,waitEmiting:0},this._emitterMatrix.copy(this.subSystem.matrixWorld).invert().premultiply(this.system.matrixWorld),this._emitterMatrix.setPosition(0,0,0),this.emitterType===Lm.Birth&&this.run(t)}update(t,e){this.run(t)}frameUpdate(t){}toJSON(){}reset(){}run(t){if(this.subSystem.currentParticles>=this.subSystem.main.maxParticles||!this.subParticleSystem||!t.emissionState||this.emitterProbability&&Math.random()>this.emitterProbability)return;const e=this.system.deltaTime;if(this.emitterType===Lm.Death){let n=t.life;if(t[Sa]!==void 0&&(n=t[Sa]),!(t.age+e*1.2>=n))return;const a=this.subSystem.main.maxParticles-this.subSystem.currentParticles;t.emissionState.waitEmiting=a}const i=new ae.Matrix4;i.set(1,0,0,t.position.x,0,1,0,t.position.y,0,0,1,t.position.z,0,0,0,1),this.particleSystem.worldSpace||i.multiplyMatrices(this._emitterMatrix,i),this.subParticleSystem.emit(e,t.emissionState,i)}}var Rk=Object.defineProperty,Be=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&Rk(t,e,n),n};const oo=S("debugparticles"),Ek=S("noprogressive"),Tk=S("debugprogressive");var Lm=(o=>(o[o.Birth=0]="Birth",o[o.Collision=1]="Collision",o[o.Death=2]="Death",o[o.Trigger=3]="Trigger",o[o.Manual=4]="Manual",o))(Lm||{});class en extends D{constructor(){super(...arguments);r(this,"renderMode");r(this,"particleMaterial");r(this,"trailMaterial");r(this,"particleMesh");r(this,"maxParticleSize");r(this,"minParticleSize");r(this,"velocityScale");r(this,"cameraVelocityScale");r(this,"lengthScale")}start(){if(this.maxParticleSize!==.5&&this.minParticleSize!==0&&j()){const e=`ParticleSystem "${this.name}" has non-default min/max particle size. This may not render correctly. Please set min size to 0 and the max size to 0.5 and use the "StartSize" setting instead`;console.warn(e)}}get transparent(){var i;return((i=this.particleMaterial)==null?void 0:i.transparent)??!1}getMaterial(e=!1){let i=e===!0&&this.trailMaterial?this.trailMaterial:this.particleMaterial;if(i){if(i.type==="MeshStandardMaterial"){oo&&console.debug("ParticleSystemRenderer.getMaterial: MeshStandardMaterial detected, converting to MeshBasicMaterial. See https://github.com/Alchemist0823/three.quarks/issues/101"),"map"in i&&i.map&&(i.map.colorSpace=d.LinearSRGBColorSpace,i.map.premultiplyAlpha=!1);const n=new d.MeshBasicMaterial;n.copy(i),e?this.trailMaterial=n:this.particleMaterial=n}i.map&&(i.map.colorSpace=d.LinearSRGBColorSpace,i.map.premultiplyAlpha=!1),e&&i.side===d.FrontSide&&(i=i.clone(),i.side=d.BackSide,e?this.trailMaterial=i:this.particleMaterial=i)}return i&&!Ek&&i._didRequestTextureLOD===void 0&&(i._didRequestTextureLOD=0,Tk&&console.log("Load material LOD",i.name),le.NEEDLE_progressive.assignTextureLOD(i,0)),i}getMesh(e){let i=null;if(!i&&(this.particleMesh instanceof d.Mesh&&(i=this.particleMesh.geometry),i===null)){i=new d.PlaneGeometry(1,1);const s=i.attributes.uv;for(let a=0;a<s.count;a++)s.setX(a,1-s.getX(a))}return new d.Mesh(i,this.getMaterial())}}Be([m()],en.prototype,"renderMode");Be([m(d.Material)],en.prototype,"particleMaterial");Be([m(d.Material)],en.prototype,"trailMaterial");Be([m()],en.prototype,"maxParticleSize");Be([m()],en.prototype,"minParticleSize");Be([m()],en.prototype,"velocityScale");Be([m()],en.prototype,"cameraVelocityScale");Be([m()],en.prototype,"lengthScale");class xd{constructor(t,e=1){r(this,"_curve");r(this,"_factor");r(this,"type","function");this._curve=t,this._factor=e}startGen(t){}genValue(t,e){return this._curve.evaluate(e,Math.random())*this._factor}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}}class Ty{constructor(t){r(this,"type","value");r(this,"system");this.system=t}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}startGen(t){}}class Ak extends Ty{genValue(){return this.system.textureSheetAnimation.getStartIndex()}}class Lk extends Ty{constructor(){super(...arguments);r(this,"_lastPosition",new d.Vector3);r(this,"_lastDistance",0)}update(){const e=Q(this.system.gameObject);this._lastDistance=this._lastPosition.distanceTo(e),this._lastPosition.copy(e)}genValue(){if(!this.system.isPlaying||!this.system.emission.enabled||this.system.currentParticles>=this.system.maxParticles)return 0;let e=this.system.emission.rateOverTime.evaluate(this.system.time/this.system.duration,Math.random());if(this.system.deltaTime>0){const s=this.system.emission.rateOverDistance.evaluate(this.system.time/this.system.duration,Math.random());let l=this._lastDistance/this.system.deltaTime*s;Number.isFinite(l)||(l=0),e+=l}const i=this.system.emission.getBurst();i>0&&(e+=i/this.system.deltaTime);const n=this.system.maxParticles-this.system.currentParticles;return z.clamp(e,0,n/this.system.deltaTime)}}class Dk extends Ty{genValue(){return this.system.isPlaying,0}}class Vo{constructor(t){r(this,"system");r(this,"type");this.type=Object.getPrototypeOf(this).constructor.name||"ParticleSystemBaseBehaviour",t&&(this.system=t)}get context(){return this.system.context}initialize(t){}update(t,e){}frameUpdate(t){}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}reset(){}}class Ik extends Vo{constructor(){super(...arguments);r(this,"type","NeedleTextureSheet")}update(e,i){const n=this.system.textureSheetAnimation;if(n.enabled){const s=e.age/e.life,a=n.evaluate(s);a!==void 0&&(e.uvTile=a)}}}const Lb=Symbol("particleRotation");class jk extends Vo{constructor(){super(...arguments);r(this,"type","NeedleRotation")}initialize(e){e[Lb]=Math.random()}update(e,i){if(e.rotation===void 0)return;const n=e.age/e.life;if(typeof e.rotation=="number"&&(this.system.rotationOverLifetime.enabled?e.rotation+=this.system.rotationOverLifetime.evaluate(n,e[Lb])*i:this.system.renderer.renderMode===bs.Billboard&&(e.rotation=Math.PI),this.system.rotationBySpeed.enabled)){const s=e.velocity.length();e.rotation+=this.system.rotationBySpeed.evaluate(n,s)*i}}}const Db=Symbol("sizeLerpFactor"),Bk=new d.Vector3;class Fk extends Vo{constructor(){super(...arguments);r(this,"type","NeedleSize");r(this,"_minSize",0);r(this,"_maxSize",1)}initialize(e){e[Db]=Math.random(),this._minSize=this.system.renderer.minParticleSize,this._maxSize=this.system.renderer.maxParticleSize}update(e,i){const n=e.age/e.life;let s=1;this.system.sizeOverLifetime.enabled&&(s*=this.system.sizeOverLifetime.evaluate(n,void 0,e[Db]).x);let a=1;this.system.renderer.renderMode!==bs.Mesh&&(a=this.system.worldScale.x/this.system.cameraScale);const l=$(e.startSize).multiplyScalar(s*a);if(e.size.set(l.x,l.y,l.z),this.system.localspace){const c=ux(this.system,Bk);e.size.x*=c.x,e.size.y*=c.y,e.size.z*=c.z}}}const Sa=Symbol("particleLife"),Ap=Symbol("trailLifetime"),Ib=Symbol("trailStartLength"),Lp=Symbol("trailWidthRandom");class Uk extends Vo{constructor(){super(...arguments);r(this,"type","NeedleTrail")}initialize(e){e instanceof ae.TrailParticle&&(e[Sa]=e.life,this.system.trails.enabled&&this.system.trails.dieWithParticles===!1&&(e[Ap]=this.system.trails.lifetime.evaluate(Math.random(),Math.random()),e.life+=e[Ap]),e[Ib]=e.length,e[Lp]=Math.random())}update(e){var i;if((i=this.system.trails)!=null&&i.enabled&&e instanceof ae.TrailParticle){const n=e,s=e.age/e[Sa],a=e.previous.values(),l=e.previous.length;for(let c=0;c<l;c++){const u=a.next().value,f=1-c/(l-1),p=e.size;if(p.x<=0&&!this.system.trails.sizeAffectsWidth){const g=20*this.system.trails.widthOverTrail.evaluate(.5,n[Lp]);p.x=g,p.y=g,p.z=g}u.size=this.system.trails.getWidth(p.x,s,f,n[Lp]),u.color.copy(e.color),this.system.trails.getColor(u.color,s,f)}if(e.age>e[Sa]){e.velocity.set(0,0,0);const c=(e.age-e[Sa])/e[Ap];n.length=z.lerp(e[Ib],0,c)}}}}const Sd=Symbol("startVelocity"),jb=Symbol("gravityModifier"),Dp=Symbol("gravitySpeed"),Cd=Symbol("velocity lerp factor"),Dm=new d.Vector3;class zk extends Vo{constructor(){super(...arguments);r(this,"type","NeedleVelocity");r(this,"_gravityDirection",new d.Vector3)}initialize(e){var a,l;const i=this.system.main.simulationSpeed;e.startSpeed=this.system.main.startSpeed.evaluate(Math.random(),Math.random());const n=this.system.shape.getDirection(e,e.position);e.velocity.x=n.x*e.startSpeed,e.velocity.y=n.y*e.startSpeed,e.velocity.z=n.z*e.startSpeed,(a=this.system.inheritVelocity)!=null&&a.enabled&&this.system.inheritVelocity.applyInitial(e.velocity),e[Sd]?e[Sd].copy(e.velocity):e[Sd]=e.velocity.clone();const s=this.system.main.gravityModifier.evaluate(Math.random(),Math.random());e[jb]=s*i,e[Dp]=s*i*.5,e[Cd]=Math.random(),(l=this.system.velocityOverLifetime)==null||l.init(e),this._gravityDirection.set(0,-1,0),this.system.main.simulationSpace===Vc.Local&&this._gravityDirection.applyQuaternion(this.system.worldQuaternionInverted).normalize()}update(e,i){var p;const n=e[Sd],s=e[jb];if(s!==0){const g=s*e[Dp];Dm.copy(this._gravityDirection).multiplyScalar(g),e[Dp]+=i*.05,n.add(Dm)}e.velocity.copy(n);const a=e.age/e.life;(p=this.system.inheritVelocity)!=null&&p.enabled&&this.system.inheritVelocity.applyCurrent(e.velocity,a,e[Cd]);const l=this.system.noise;l.enabled&&l.apply(0,e.position,e.velocity,i,e.age,e.life);const c=this.system.sizeBySpeed;c!=null&&c.enabled&&(e.size=c.evaluate(e.velocity,a,e[Cd],e.size));const h=this.system.colorBySpeed;h!=null&&h.enabled&&h.evaluate(e.velocity,e[Cd],e.color);const u=this.system.velocityOverLifetime;u.enabled&&u.apply(e,0,e.position,e.velocity,i,e.age,e.life);const f=this.system.limitVelocityOverLifetime;if(f.enabled&&f.apply(e.position,n,e.velocity,e.size,a,i,1),this.system.worldspace){const g=this.system.worldScale;e.velocity.x*=g.x,e.velocity.y*=g.y,e.velocity.z*=g.z}}}const Bb=Symbol("colorLerpFactor"),Fb=new ie(1,1,1,1),Yo=new ie(1,1,1,1);class Nk extends Vo{constructor(){super(...arguments);r(this,"type","NeedleColor")}initialize(e){}_init(e){const i=this.system.renderer.particleMaterial;Yo.copy(this.system.main.startColor.evaluate(Math.random())),i!=null&&i.color&&(Fb.copy(i.color),Yo.multiply(Fb)),Yo.convertLinearToSRGB(),e.startColor.set(Yo.r,Yo.g,Yo.b,Yo.alpha),e.color.copy(e.startColor),e[Bb]=Math.random()}update(e,i){if(e.age===0&&this._init(e),this.system.colorOverLifetime.enabled){const n=e.age/e.life,s=this.system.colorOverLifetime.color.evaluate(n,e[Bb]);e.color.set(s.r,s.g,s.b,"alpha"in s?s.alpha:1).multiply(e.startColor)}else e.color.copy(e.startColor)}}class Vk{constructor(t){r(this,"system");r(this,"emission");r(this,"autoDestroy");r(this,"startLength");r(this,"emissionBursts");r(this,"onlyUsedByOther");r(this,"behaviors",[]);r(this,"rendererEmitterSettings",{startLength:new ae.ConstantValue(220),followLocalOrigin:!1});r(this,"flatWhiteTexture");r(this,"clonedTexture",{original:void 0,clone:void 0});this.system=t,this.emission=new Lk(this.system)}get anim(){return this.system.textureSheetAnimation}get prewarm(){return!1}get material(){return this.system.renderer.getMaterial(this.system.trails.enabled)}get layers(){return this.system.gameObject.layers}update(){this.emission.update()}get looping(){return this.system.main.loop}get duration(){return this.system.duration}get shape(){return this.system.shape}get startLife(){return new xd(this.system.main.startLifetime)}get startSpeed(){return new xd(this.system.main.startSpeed)}get startRotation(){return new xd(this.system.main.startRotation)}get startSize(){return new xd(this.system.main.startSize)}get startColor(){return new ae.ConstantColor(new ae.Vector4(1,1,1,1))}get emissionOverTime(){return this.emission}get emissionOverDistance(){return new Dk(this.system)}get instancingGeometry(){return this.system.renderer.getMesh(this.system.renderer.renderMode).geometry}get renderMode(){if(this.system.trails.enabled===!0)return ae.RenderMode.Trail;switch(this.system.renderer.renderMode){case bs.Billboard:return ae.RenderMode.BillBoard;case bs.Stretch:return ae.RenderMode.StretchedBillBoard;case bs.HorizontalBillboard:return ae.RenderMode.HorizontalBillBoard;case bs.VerticalBillboard:return ae.RenderMode.VerticalBillBoard;case bs.Mesh:return ae.RenderMode.Mesh}return ae.RenderMode.BillBoard}get speedFactor(){var e;let t=this.system.main.simulationSpeed;return((e=this.system.renderer)==null?void 0:e.renderMode)===bs.Stretch&&(t*=this.system.renderer.velocityScale??1),t}get texture(){const t=this.material;if(t&&t.map){const e=t.map;if(this.clonedTexture.original!==e||!this.clonedTexture.clone){const i=e.clone();i.premultiplyAlpha=!1,i.colorSpace=d.LinearSRGBColorSpace,this.clonedTexture.original=e,this.clonedTexture.clone=i}return this.clonedTexture.clone}return this.flatWhiteTexture||(this.flatWhiteTexture=Sg(new ie(1,1,1,1),1)),this.flatWhiteTexture}get startTileIndex(){return new Ak(this.system)}get uTileCount(){var t;return this.anim.enabled?(t=this.anim)==null?void 0:t.numTilesX:void 0}get vTileCount(){var t;return this.anim.enabled?(t=this.anim)==null?void 0:t.numTilesY:void 0}get renderOrder(){return 1}get blending(){var t;return((t=this.system.renderer.particleMaterial)==null?void 0:t.blending)??d.NormalBlending}get transparent(){return this.system.renderer.transparent}get worldSpace(){return this.system.main.simulationSpace===Vc.World}}class $k{constructor(){r(this,"burstParticleIndex",0);r(this,"burstParticleCount",0);r(this,"isBursting",!1);r(this,"travelDistance",0);r(this,"previousWorldPos");r(this,"burstIndex",0);r(this,"burstWaveIndex",0);r(this,"time",0);r(this,"waitEmiting",0)}}const Bt=class Nd extends D{constructor(){super(...arguments);r(this,"_state");r(this,"colorOverLifetime");r(this,"main");r(this,"emission");r(this,"sizeOverLifetime");r(this,"shape");r(this,"noise");r(this,"trails");r(this,"velocityOverLifetime");r(this,"limitVelocityOverLifetime");r(this,"inheritVelocity");r(this,"colorBySpeed");r(this,"textureSheetAnimation");r(this,"rotationOverLifetime");r(this,"rotationBySpeed");r(this,"sizeBySpeed");r(this,"_cameraScale",1);r(this,"__worldQuaternion",new d.Quaternion);r(this,"_worldQuaternionInverted",new d.Quaternion);r(this,"_worldScale",new d.Vector3);r(this,"_worldPositionFrame",-1);r(this,"_worldPos",new d.Vector3);r(this,"_renderer");r(this,"_batchSystem");r(this,"_particleSystem");r(this,"_interface");r(this,"_container");r(this,"_time",0);r(this,"_isPlaying",!0);r(this,"_isUsedAsSubsystem",!1);r(this,"_didPreWarm",!1);r(this,"_bursts");r(this,"_subEmitterSystems");r(this,"_lastBatchesCount",-1)}play(e=!1){var i;e&&C.foreachComponent(this.gameObject,n=>{n instanceof Nd&&n!==this&&n.play(!1)},!0),this._isPlaying=!0,this._particleSystem&&(this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1),(i=this.emission)==null||i.reset()}pause(e=!0){e&&C.foreachComponent(this.gameObject,i=>{i instanceof Nd&&i!==this&&i.pause(!1)},!0),this._isPlaying=!1}stop(e=!0,i=!1){e&&C.foreachComponent(this.gameObject,n=>{n instanceof Nd&&n!==this&&n.stop(!1,i)},!0),this._isPlaying=!1,this._time=0,i&&this.reset()}reset(){var e;this._time=0,this._particleSystem&&(this._particleSystem.particleNum=0,this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1,(e=this.emission)==null||e.reset())}emit(e){if(this._particleSystem){this.onUpdate(),e=Math.min(e,this.maxParticles-this.currentParticles),this._state||(this._state=new $k),this._state.waitEmiting=e,this._state.time=0;const i=this._particleSystem.emitEnded;this._particleSystem.emitEnded=!1,this._particleSystem.emit(this.deltaTime,this._state,this._particleSystem.emitter.matrixWorld),this._particleSystem.emitEnded=i}}get playOnAwake(){return this.main.playOnAwake}set playOnAwake(e){this.main.playOnAwake=e}get renderer(){return this._renderer}get isPlaying(){return this._isPlaying}get currentParticles(){var e;return((e=this._particleSystem)==null?void 0:e.particleNum)??0}get maxParticles(){return this.main.maxParticles}get time(){return this._time}get duration(){return this.main.duration}get deltaTime(){return this.context.time.deltaTime*this.main.simulationSpeed}get scale(){return this.gameObject.scale.x}get cameraScale(){return this._cameraScale}get container(){return this._container}get worldspace(){return this.main.simulationSpace===Vc.World}get localspace(){return this.main.simulationSpace===Vc.Local}get worldQuaternion(){return this.__worldQuaternion}get worldQuaternionInverted(){return this._worldQuaternionInverted}get worldScale(){return this._worldScale}get worldPos(){return this._worldPositionFrame!==this.context.time.frame&&(this._worldPositionFrame=this.context.time.frame,Q(this.gameObject,this._worldPos)),this._worldPos}get matrixWorld(){return this._container.matrixWorld}get isSubsystem(){return this._isUsedAsSubsystem}addBehaviour(e){return this._particleSystem?(e instanceof Vo&&(e.system=this),oo&&console.debug("Add custom ParticleSystem Behaviour",e),this._particleSystem.addBehavior(e),!0):!1}removeBehaviour(e){if(!this._particleSystem)return!1;const i=this._particleSystem.behaviors,n=i.indexOf(e);return n!==-1&&((j()||oo)&&console.debug("Remove custom ParticleSystem Behaviour",n,e),i.splice(n,1)),!0}removeAllBehaviours(){return this._particleSystem?(this._particleSystem.behaviors.length=0,!0):!1}get behaviours(){return this._particleSystem?this._particleSystem.behaviors:null}get particleSystem(){return this._particleSystem??null}set bursts(e){for(let i=0;i<e.length;i++){const n=e[i];if(!(n instanceof vu)){const s=new vu;Wa(s,n),e[i]=s}}this._bursts=e}set subEmitterSystems(e){for(let i=0;i<e.length;i++){const n=e[i];if(!(n instanceof wu)){const s=new wu;Wa(s,n),e[i]=s}}oo&&e.length>0&&console.log("SubEmitters: ",e,this),this._subEmitterSystems=e}onAfterDeserialize(e){if(this._subEmitterSystems&&Array.isArray(this._subEmitterSystems))for(const i of this._subEmitterSystems)i._deserialize(this.context,this.gameObject)}awake(){if(this._worldPositionFrame=-1,this._renderer=this.gameObject.getComponent(en),!this.main)throw new Error("Not Supported: ParticleSystem needs a serialized MainModule. Creating new particle systems at runtime is currently not supported.");this._container=new d.Object3D,this._container.matrixAutoUpdate=!1,this.context.scene.add(this._container),this._batchSystem=new ae.BatchedParticleRenderer,this._batchSystem.name=this.gameObject.name,this._container.add(this._batchSystem),this._interface=new Vk(this),this._particleSystem=new ae.ParticleSystem(this._interface),this._particleSystem.addBehavior(new Fk(this)),this._particleSystem.addBehavior(new Nk(this)),this._particleSystem.addBehavior(new Ik(this)),this._particleSystem.addBehavior(new jk(this)),this._particleSystem.addBehavior(new zk(this)),this._particleSystem.addBehavior(new Uk(this)),this._batchSystem.addSystem(this._particleSystem);const e=this._particleSystem.emitter;this.context.scene.add(e),this.inheritVelocity.system&&this.inheritVelocity.system!==this&&(this.inheritVelocity=this.inheritVelocity.clone()),this.inheritVelocity.awake(this),oo&&(console.log(this),this.gameObject.add(new d.AxesHelper(1)))}start(){this.addSubParticleSystems(),this.updateLayers(),this.renderer.particleMesh instanceof d.Mesh&&this._interface.renderMode==ae.RenderMode.Mesh&&le.NEEDLE_progressive.assignMeshLOD(this.renderer.particleMesh,0).then(e=>{e&&this.particleSystem&&this._interface.renderMode==ae.RenderMode.Mesh&&(this.particleSystem.instancingGeometry=e)})}onDestroy(){var e,i,n,s;(e=this._container)==null||e.removeFromParent(),(i=this._batchSystem)==null||i.removeFromParent(),(n=this._particleSystem)==null||n.emitter.removeFromParent(),(s=this._particleSystem)==null||s.dispose()}onEnable(){this.main&&(this.inheritVelocity&&(this.inheritVelocity.system=this),this._batchSystem&&(this._batchSystem.visible=!0),this.playOnAwake&&this.play(),this._isPlaying=this.playOnAwake)}onDisable(){this._batchSystem&&(this._batchSystem.visible=!1)}onBeforeRender(){var e;this.main&&(this._didPreWarm===!1&&((e=this.main)==null?void 0:e.prewarm)===!0&&(this._didPreWarm=!0,this.preWarm()),this.onUpdate(),this.onSimulate(this.deltaTime))}preWarm(){var u;if(!((u=this.emission)!=null&&u.enabled)||this.emission.rateOverTime.getMax()<=0)return;const i=1/60,n=this.main.duration,s=this.main.startLifetime.getMax(),l=Math.min(Math.max(n,s)/Math.max(.01,this.main.simulationSpeed),1e3),c=Math.ceil(l/i),h=Date.now();oo&&console.log(`Particles ${this.name} - Prewarm for ${c} frames (${l} sec). Duration: ${n}, Lifetime: ${s}`);for(let f=0;f<c&&!(this.currentParticles>=this.maxParticles);f++){const p=Date.now()-h;if(p>2e3){console.warn(`Particles ${this.name} - Prewarm took too long. Aborting: ${p}`);break}this.onUpdate(),this.onSimulate(i)}}onSimulate(e){if(this._batchSystem){let i=this.context.time.frameCount%60===0;this._lastBatchesCount!==this._batchSystem.batches.length&&(this._lastBatchesCount=this._batchSystem.batches.length,i=!0),i&&this.updateLayers(),this._batchSystem.update(e)}this._time+=e,this._time>this.duration&&(this._time=0)}updateLayers(){if(this._batchSystem)for(let e=0;e<this._batchSystem.batches.length;e++){const i=this._batchSystem.batches[e];i.layers.disableAll();const n=this.layer;i.layers.mask=1<<n}}onUpdate(){var s,a;if(this._bursts&&(this.emission.bursts=this._bursts,delete this._bursts),!this._isPlaying)return;const e=this.context.mainCamera;if(e){const l=Ue(e);this._cameraScale=l.x}const i=!this.worldspace,n=this.gameObject;if(_e(n,this.__worldQuaternion),this._worldQuaternionInverted.copy(this.__worldQuaternion).invert(),Ue(this.gameObject,this._worldScale),i&&this._container&&((s=this.gameObject)!=null&&s.parent)){const l=ux(this,Dm);this._container.matrix.makeScale(l.x,l.y,l.z),this._container.matrix.makeRotationFromQuaternion(this.__worldQuaternion),this._container.matrix.setPosition(this.worldPos),this._container.matrix.scale(this.gameObject.scale)}this.emission.system=this,this._interface.update(),this.shape.onUpdate(this,this.context,this.main.simulationSpace,this.gameObject),this.noise.update(this.context),(a=this.inheritVelocity)==null||a.update(this.context),this.velocityOverLifetime.update(this)}addSubParticleSystems(){var e;if(this._subEmitterSystems&&this._particleSystem)for(const i of this._subEmitterSystems){i.particleSystem&&(i.particleSystem.__internalAwake?i.particleSystem.__internalAwake():j()&&console.warn("SubParticleSystem serialization issue(?)",i.particleSystem,i));const n=(e=i.particleSystem)==null?void 0:e._particleSystem;if(n){i.particleSystem._isUsedAsSubsystem=!0;const s=new Ey(this,this._particleSystem,i.particleSystem,n);s.emitterType=i.type,s.emitterProbability=i.emitProbability,this._particleSystem.addBehavior(s)}else oo&&console.warn("Could not add SubParticleSystem",i,this)}}};Be([m(yf)],Bt.prototype,"colorOverLifetime");Be([m(It)],Bt.prototype,"main");Be([m(Ns)],Bt.prototype,"emission");Be([m(Zr)],Bt.prototype,"sizeOverLifetime");Be([m(ky)],Bt.prototype,"shape");Be([m(be)],Bt.prototype,"noise");Be([m(je)],Bt.prototype,"trails");Be([m(ze)],Bt.prototype,"velocityOverLifetime");Be([m(lt)],Bt.prototype,"limitVelocityOverLifetime");Be([m(Ry)],Bt.prototype,"inheritVelocity");Be([m(yl)],Bt.prototype,"colorBySpeed");Be([m(jt)],Bt.prototype,"textureSheetAnimation");Be([m(Pn)],Bt.prototype,"rotationOverLifetime");Be([m(Ji)],Bt.prototype,"rotationBySpeed");Be([m(mi)],Bt.prototype,"sizeBySpeed");let $c=Bt;class wu{constructor(){r(this,"particleSystem");r(this,"emitProbability",1);r(this,"properties");r(this,"type")}_deserialize(t,e){const i=this.particleSystem;if(i instanceof $c)return;let n="";i&&typeof i.guid=="string"&&(n=i.guid,this.particleSystem=C.findByGuid(n,e)),oo&&!(this.particleSystem instanceof $c)&&console.warn("Could not find particle system for sub emitter",n,e,this)}}function ux(o,t){if(t.set(1,1,1),o.gameObject.parent&&o.localspace)switch(o.main.scalingMode){case Am.Local:t=Ue(o.gameObject.parent,t),t.x=1/t.x,t.y=1/t.y,t.z=1/t.z;break;default:if(!o.unsupported_scaling_mode){o.unsupported_scaling_mode=!0;const e="ParticleSystem scale mode "+Am[o.main.scalingMode]+" is not supported";j()&&me(e),console.warn(e,o.name,o)}t=Ue(o.gameObject,t);break}return t}class Ja extends D{constructor(){super(...arguments);r(this,"_didAssignPlayerColor",!1);r(this,"tryAssignColor",()=>{const e=C.getComponentInParent(this.gameObject,yn);if(e&&e.owner)return this._didAssignPlayerColor=!0,this.assignUserColor(e.owner),!0;const i=C.getComponentInParent(this.gameObject,At);return i!=null&&i.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(i.connectionId),!0):!1})}onEnable(){this.context.connection.beginListen(ee.JoinedRoom,this.tryAssignColor),this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}onDisable(){this.context.connection.stopListen(ee.JoinedRoom,this.tryAssignColor)}*waitForConnection(){for(;!this.destroyed&&this.activeAndEnabled&&(yield xg(.2),!this.tryAssignColor()););}assignUserColor(e){const i=Ja.hashCode(e),n=Ja.colorFromHashCode(i);if(this.gameObject.type==="Mesh"){const s=this.gameObject;this.assignColor(n,e,s)}else if(this.gameObject.children)for(const s of this.gameObject.children){const a=s;a.material&&a.material.color&&this.assignColor(n,e,a)}}assignColor(e,i,n){let s=n.material;s&&(s._playerMaterial!==i&&(s=s.clone(),s._playerMaterial=i,n.material=s),s.color=e)}static hashCode(e){var i=0,n,s;if(e.length===0)return i;for(n=0;n<e.length;n++)s=e.charCodeAt(n),i=(i<<5)-i+s,i|=0;return i}static colorFromHashCode(e){const i=(e&16711680)>>16,n=(e&65280)>>8,s=e&255;return new d.Color(i/255,n/255,s/255)}}const sc=S("debugpost");let Im=null;function Wk(o){Im=o}function fx(o){let t=o.gameObject;for(;t;){for(const e of Hu(t))if(e.isPostProcessingManager===!0)return e;t=t.parent}return null}function Hk(o){let t=fx(o);if(!t)if(Im){sc&&console.warn("Adding postprocessing manager to the scene.");const e=o.scene;t=Oi(e,Im)}else j()&&console.warn("No post processing manager found");return t}const it={AT_START:-1e4,NormalPass:0,DepthDownsamplingPass:10,SSAO:20,SMAA:30,TiltShift:40,DepthOfField:50,ChromaticAberration:60,Bloom:70,Vignette:80,Pixelation:90,ToneMapping:100,HueSaturation:110,BrightnessContrast:120,Sharpening:130,AT_END:1e4};let qe=null;function Gk(o){sc==="verbose"&&console.debug("Before ordering effects",[...o]),qe||(qe=new Map,qe.set(exports.MODULES.POSTPROCESSING.MODULE.NormalPass,it.NormalPass),qe.set(exports.MODULES.POSTPROCESSING.MODULE.DepthDownsamplingPass,it.DepthDownsamplingPass),qe.set(exports.MODULES.POSTPROCESSING.MODULE.SMAAEffect,it.SMAA),qe.set(exports.MODULES.POSTPROCESSING.MODULE.SSAOEffect,it.SSAO),qe.set(exports.MODULES.POSTPROCESSING_AO.MODULE.N8AOPostPass,it.SSAO),qe.set(exports.MODULES.POSTPROCESSING_AO.MODULE.N8AOPass,it.SSAO),qe.set(exports.MODULES.POSTPROCESSING.MODULE.TiltShiftEffect,it.TiltShift),qe.set(exports.MODULES.POSTPROCESSING.MODULE.DepthOfFieldEffect,it.DepthOfField),qe.set(exports.MODULES.POSTPROCESSING.MODULE.ChromaticAberrationEffect,it.ChromaticAberration),qe.set(exports.MODULES.POSTPROCESSING.MODULE.BloomEffect,it.Bloom),qe.set(exports.MODULES.POSTPROCESSING.MODULE.SelectiveBloomEffect,it.Bloom),qe.set(exports.MODULES.POSTPROCESSING.MODULE.VignetteEffect,it.Vignette),qe.set(exports.MODULES.POSTPROCESSING.MODULE.PixelationEffect,it.Pixelation),qe.set(exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect,it.ToneMapping),qe.set(exports.MODULES.POSTPROCESSING.MODULE.HueSaturationEffect,it.HueSaturation),qe.set(exports.MODULES.POSTPROCESSING.MODULE.BrightnessContrastEffect,it.BrightnessContrast)),o.sort((t,e)=>{const i=typeof t.priority=="number"?t.priority:qe.get(t.effect.constructor)??Number.NEGATIVE_INFINITY,n=typeof e.priority=="number"?e.priority:qe.get(e.effect.constructor)??Number.NEGATIVE_INFINITY;return i===Number.NEGATIVE_INFINITY?(sc&&console.warn("Unknown effect found: ",t.constructor.name,t),1):n===Number.NEGATIVE_INFINITY?(sc&&console.warn("Unknown effect found: ",e.constructor.name,e),-1):i-n}),sc==="verbose"&&console.debug("After ordering effects",[...o])}var qk=Object.defineProperty,Xk=Object.getOwnPropertyDescriptor,px=(o,t,e,i)=>{for(var n=Xk(t,e),s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&qk(t,e,n),n};const Qk=S("debugpost");class U{constructor(t){r(this,"isVolumeParameter",!0);r(this,"_isInitialized",!1);r(this,"_active",!0);r(this,"_value");r(this,"_valueRaw");r(this,"_defaultValue");r(this,"valueProcessor");r(this,"onValueChanged");t!==void 0&&this.initialize(t)}get isInitialized(){return this._isInitialized}initialize(t){t!==void 0&&(this._value=t,this._defaultValue=t,this._valueRaw=t,this._isInitialized=!0)}get overrideState(){return this._active}set overrideState(t){if(this._active===t)return;this._active=t;const e=t?this._valueRaw:this._defaultValue;this.processValue(e,!0)}get value(){return this._valueRaw}set value(t){this.isInitialized||this.initialize(t),this.processValue(t,!1)}set defaultValue(t){this._defaultValue=t}__init(){this.processValue(this._valueRaw,!0)}processValue(t,e){if(t==null||!e&&this.testIfValueChanged(t)===!1)return;const i=this._value;Qk&&typeof i=="number"&&typeof t=="number"&&(i==null||i.toFixed(4),t==null||t.toFixed(4)),!this._active&&this._defaultValue!==void 0?(this._value=this._defaultValue,t=this._defaultValue,this._valueRaw=t):(this._valueRaw=t,this._active&&this.valueProcessor&&(t=this.valueProcessor(t)),this._value=t),this.onValueChanged&&this.onValueChanged(t,i,this)}testIfValueChanged(t){return this._valueRaw!==t}}px([m()],U.prototype,"overrideState");px([m()],U.prototype,"value");class Yk extends Ki{constructor(){super([U])}onSerialize(t,e){}onDeserialize(t,e){const i=e.target,n=e.path;let s;if(i&&n&&(s=i[n]),(typeof s!="object"||typeof s=="object"&&s.isVolumeParameter!==!0)&&(s=new U),typeof t=="object"&&"value"in t){const a=t.value;s.initialize(a),s.overrideState=t.overrideState}else s.value=t;return s}}new Yk;var Kk=Object.defineProperty,Zk=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&Kk(t,e,n),n};const Ip=S("debugpost");class Ye extends D{constructor(e=void 0){super();r(this,"order");r(this,"active",!0);r(this,"_manager",null);r(this,"_result");r(this,"_postprocessingContext",null);if(e)for(const i of Object.keys(e)){const n=e[i],s=this[i];s instanceof U?s.initialize(n):s!==void 0&&(this[i]=n)}}get isPostProcessingEffect(){return!0}onEnable(){super.onEnable(),Ip&&console.warn("Enable",this.constructor.name+(this.__internalDidAwakeAndStart?"":" (awake)")),this.__internalDidAwakeAndStart&&(this.active=!0),this.onEffectEnabled()}onDisable(){var e;super.onDisable(),Ip&&console.warn("Disable",this.constructor.name),(e=this._manager)==null||e.removeEffect(this),this.active=!1}onEffectEnabled(e){e&&e.isPostProcessingManager===!0?this._manager=e:this._manager||(this._manager=Hk(this)),this._manager.addEffect(this),this._manager.dirty=!0}init(){}get postprocessingContext(){return this._postprocessingContext}apply(e){var i;return this._postprocessingContext=e,this._result||(this.initParameters(),this._result=(i=this.onCreateEffect)==null?void 0:i.call(this)),this._result&&this.initParameters(),this._result}unapply(){}dispose(){Ip&&console.warn("DISPOSE",this),this._result&&(Array.isArray(this._result)?this._result.forEach(e=>e.dispose()):this._result.dispose()),this._result=void 0}initParameters(){const e=Object.keys(this);for(const i of e){const n=this[i];n instanceof U&&n.__init()}}onEditorModification(e){const i=e.propertyName;if(this[i]instanceof U){const n=e.value;return this[i].value=n,!0}}}Zk([m()],Ye.prototype,"active");var Jk=Object.defineProperty,eR=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&Jk(t,e,n),n};const tR=S("debugpost"),jm={};function tn(o,t){jm[o]=t}function iR(o){return o.__type in jm?jm[o.__type]:(tR&&o.__type&&console.warn("Unknown postprocessing type",o.__type,o),Ye)}class _f{constructor(){r(this,"components",[])}__init(t){var e;(e=this.components)==null||e.forEach(i=>{i.gameObject===void 0&&t.gameObject.addComponent(i),i.init()})}addEffect(t){this.components.push(t)}removeEffect(t){const e=this.components.indexOf(t);e>=0&&this.components.splice(e,1)}}eR([Br([o=>iR(o),Ye])],_f.prototype,"components");var nR=Object.defineProperty,sR=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&nR(t,e,n),n};const oR=S("debugpost");class Lh extends Ye{constructor(){super(...arguments);r(this,"preset",new U(2))}get typeName(){return"Antialiasing"}onCreateEffect(){var i;const e=new exports.MODULES.POSTPROCESSING.MODULE.SMAAEffect({preset:((i=this.preset)==null?void 0:i.value)??exports.MODULES.POSTPROCESSING.MODULE.SMAAPreset.HIGH,edgeDetectionMode:exports.MODULES.POSTPROCESSING.MODULE.EdgeDetectionMode.LUMA});return this.preset.onValueChanged=n=>{oR&&console.log("Antialiasing preset changed to",n),e.applyPreset(n)},e}}sR([m(U)],Lh.prototype,"preset");tn("Antialiasing",Lh);var rR=Object.defineProperty,Ay=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&rR(t,e,n),n},ur;const bf=(ur=class extends Ye{constructor(){super(...arguments);r(this,"threshold",new U(.9));r(this,"intensity",new U(1));r(this,"scatter",new U(.7));r(this,"selectiveBloom")}get typeName(){return"Bloom"}init(){this.threshold.valueProcessor=e=>e,this.intensity.valueProcessor=e=>e,this.scatter.valueProcessor=e=>e}onCreateEffect(){let e;if(this.selectiveBloom==null&&(this.selectiveBloom=ur.useSelectiveBloom),this.selectiveBloom){const i=e=new exports.MODULES.POSTPROCESSING.MODULE.SelectiveBloomEffect(this.context.scene,this.context.mainCamera,{blendFunction:exports.MODULES.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});i.inverted=!0}else e=new exports.MODULES.POSTPROCESSING.MODULE.BloomEffect({blendFunction:exports.MODULES.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});return this.intensity.onValueChanged=i=>{e.intensity=i},this.threshold.onValueChanged=i=>{e.luminanceMaterial.threshold=Math.pow(i,2.2)},this.scatter.onValueChanged=i=>{e.luminancePass.enabled=!0,e.luminanceMaterial.smoothing=i,e.mipmapBlurPass&&(e.mipmapBlurPass.radius=d.MathUtils.lerp(.1,.9,i))},e}},r(ur,"useSelectiveBloom",!1),ur);Ay([m(U)],bf.prototype,"threshold");Ay([m(U)],bf.prototype,"intensity");Ay([m(U)],bf.prototype,"scatter");let vf=bf;tn("Bloom",vf);var aR=Object.defineProperty,lR=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&aR(t,e,n),n};class Dh extends Ye{constructor(){super(...arguments);r(this,"intensity",new U(0))}get typeName(){return"ChromaticAberration"}onCreateEffect(){const e=new exports.MODULES.POSTPROCESSING.MODULE.ChromaticAberrationEffect;return e.offset=new d.Vector2(0,0),e.radialModulation=!0,e.modulationOffset=.15,this.intensity.valueProcessor=i=>i*.02,this.intensity.onValueChanged=i=>{e.offset.x=-i,e.offset.y=i},e}}lR([m(U)],Dh.prototype,"intensity");tn("ChromaticAberration",Dh);var oc=(o=>(o[o.None=0]="None",o[o.Neutral=1]="Neutral",o[o.ACES=2]="ACES",o[o.AgX=3]="AgX",o[o.KhronosNeutral=4]="KhronosNeutral",o))(oc||{});const Ub=new Map;function jp(o){switch(o){case 0:return d.LinearToneMapping;case 1:return d.ReinhardToneMapping;case 2:return d.ACESFilmicToneMapping;case 3:return d.AgXToneMapping;case 4:return d.NeutralToneMapping;default:return Ub.has(o)||(Ub.set(o,!0),console.warn("[Postprocessing] Unknown tone mapping mode",o)),d.NeutralToneMapping}}function cR(o){switch(o){case d.LinearToneMapping:return 0;case d.ACESFilmicToneMapping:return 2;case d.AgXToneMapping:return 3;case d.NeutralToneMapping:return 1;case d.ReinhardToneMapping:return 1;default:return 0}}function Vd(o){switch(o){case d.LinearToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR;case d.ACESFilmicToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.ACES_FILMIC;case d.AgXToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.AGX;case d.NeutralToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.NEUTRAL;case d.ReinhardToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.REINHARD;default:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR}}var hR=Object.defineProperty,mx=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&hR(t,e,n),n};const Bp=S("debugpost");class Eo extends Ye{constructor(){super(...arguments);r(this,"mode",new U(void 0));r(this,"exposure",new U(1));r(this,"_tonemappingEffect",null)}get typeName(){return"ToneMapping"}setMode(e){const i=oc[e];return i===void 0?(console.error("[PostProcessing] Invalid ToneMapping mode",e),this):(this.mode.value=i,this)}get isToneMapping(){return!0}onEffectEnabled(){const e=fx(this);e&&super.onEffectEnabled(e)}onCreateEffect(){var n;if(this.mode.isInitialized==!1){const s=cR(this.context.renderer.toneMapping);Bp&&console.log("[PostProcessing] Initializing ToneMapping mode to renderer.toneMapping",this.context.renderer.toneMapping+" → "+s),this.mode.initialize(s)}(n=this._tonemappingEffect)==null||n.dispose();const e=jp(this.mode.value),i=this._tonemappingEffect=new exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect({mode:Vd(e)});return this.mode.onValueChanged=s=>{if(typeof s=="string")s=Gv(s),i.mode=Vd(s);else{const a=jp(s);i.mode=Vd(a)}i.name="ToneMapping ("+oc[s]+")",Bp&&console.log("[PostProcessing] ToneMapping mode changed to",oc[s],e,i.mode)},Bp&&console.log("[PostProcessing] Use ToneMapping",oc[this.mode.value],e,i.mode,"renderer.tonemapping: "+this.context.renderer.toneMapping),i}onBeforeRender(){var e;if(this._tonemappingEffect&&((e=this.postprocessingContext)!=null&&e.handler.getEffectIsActive(this._tonemappingEffect))&&(this.mode.overrideState&&(this.context.renderer.toneMapping=jp(this.mode.value)),this.exposure.overrideState&&this.exposure.value!==void 0)){const i=Math.max(.01,this.exposure.value);this.context.renderer.toneMappingExposure=i}}}mx([m(U)],Eo.prototype,"mode");mx([m(U)],Eo.prototype,"exposure");tn("Tonemapping",Eo);var dR=Object.defineProperty,wf=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&dR(t,e,n),n};class $o extends Ye{constructor(){super(...arguments);r(this,"remap",!0);r(this,"postExposure",new U(1));r(this,"contrast",new U(0));r(this,"hueShift",new U(0));r(this,"saturation",new U(0))}get typeName(){return"ColorAdjustments"}init(){this.postExposure.valueProcessor=e=>(this.remap&&(e=Math.pow(2,e)),e),this.contrast.valueProcessor=e=>{if(!this.remap)return e;let i=1;return e>0?i=200:e<0&&(i=100),e/i},this.contrast.defaultValue=0,this.hueShift.valueProcessor=e=>this.remap?Math.PI*e/180:e,this.hueShift.defaultValue=0,this.saturation.valueProcessor=e=>this.remap?e<0?e/100:e/(100*Math.PI):e,this.saturation.defaultValue=0}onCreateEffect(){var a,l;const e=[];let i=(a=this.postprocessingContext)==null?void 0:a.components.find(c=>c instanceof Eo);i||(i=new Eo,(l=this.postprocessingContext)==null||l.components.push(i)),this.postExposure.onValueChanged=c=>{this.postExposure.overrideState&&i?i.exposure.value=c:console.warn("[PostProcessing] PostExposure is set to override but no ToneMappingEffect found in the postprocessing stack. Please add a ToneMappingEffect to your postprocessing stack to use PostExposure.")};const n=new exports.MODULES.POSTPROCESSING.MODULE.BrightnessContrastEffect;this.contrast.onValueChanged=c=>n.contrast=c;const s=new exports.MODULES.POSTPROCESSING.MODULE.HueSaturationEffect;return this.hueShift.onValueChanged=c=>s.hue=c,this.saturation.onValueChanged=c=>s.saturation=c,e.push(n),e.push(s),e}}wf([m(U)],$o.prototype,"postExposure");wf([m(U)],$o.prototype,"contrast");wf([m(U)],$o.prototype,"hueShift");wf([m(U)],$o.prototype,"saturation");tn("ColorAdjustments",$o);var uR=Object.defineProperty,Jr=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&uR(t,e,n),n};const fR=S("debugpost");class Mn extends Ye{constructor(){super(...arguments);r(this,"mode");r(this,"focusDistance",new U(1));r(this,"focalLength",new U(.2));r(this,"aperture",new U(20));r(this,"gaussianMaxRadius",new U);r(this,"resolutionScale",new U(1/window.devicePixelRatio));r(this,"bokehScale",new U)}get typeName(){return"DepthOfField"}init(){this.focalLength.valueProcessor=i=>{const n=i/300;return z.lerp(2,.01,n)};const e=20;this.aperture.valueProcessor=i=>{const n=1-i/32;return z.lerp(1,e,n)}}onCreateEffect(){if(this.mode===0){fR&&console.warn("DepthOfField: Mode is set to Off");return}const e=new exports.MODULES.POSTPROCESSING.MODULE.DepthOfFieldEffect(this.context.mainCamera,{worldFocusRange:.2,focalLength:1,bokehScale:20,resolutionScale:this.resolutionScale.value});return this.focusDistance.onValueChanged=i=>{e.cocMaterial.worldFocusDistance=i},this.focalLength.onValueChanged=i=>e.cocMaterial.worldFocusRange=i,this.aperture.onValueChanged=i=>e.bokehScale=i,this.resolutionScale&&(this.resolutionScale.onValueChanged=i=>e.resolution.scale=i),[e]}unapply(){}}Jr([m()],Mn.prototype,"mode");Jr([m(U)],Mn.prototype,"focusDistance");Jr([m(U)],Mn.prototype,"focalLength");Jr([m(U)],Mn.prototype,"aperture");Jr([m(U)],Mn.prototype,"gaussianMaxRadius");Jr([m(U)],Mn.prototype,"resolutionScale");Jr([m(U)],Mn.prototype,"bokehScale");tn("DepthOfField",Mn);class Wc extends Ye{constructor(e){super();r(this,"effect");this.effect=e}get typeName(){return this.effect.constructor.name}onCreateEffect(){return this.effect}}var pR=Object.defineProperty,mR=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&pR(t,e,n),n};class Ih extends Ye{constructor(){super(...arguments);r(this,"granularity",new U(10))}get typeName(){return"PixelationEffect"}onCreateEffect(){const e=new exports.MODULES.POSTPROCESSING.MODULE.PixelationEffect;return this.granularity.onValueChanged=i=>{e.granularity=i},e}}mR([m(U)],Ih.prototype,"granularity");tn("PixelationEffect",Ih);var gR=Object.defineProperty,jh=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&gR(t,e,n),n};class Vs extends Ye{constructor(){super(...arguments);r(this,"intensity",new U(2));r(this,"falloff",new U(1));r(this,"samples",new U(9));r(this,"color",new U(new d.Color(0,0,0)));r(this,"luminanceInfluence",new U(.7));r(this,"_ssao")}get typeName(){return"ScreenSpaceAmbientOcclusion"}onBeforeRender(){if(this._ssao&&this.context.mainCamera instanceof d.PerspectiveCamera){const e=this.context.mainCamera.far-this.context.mainCamera.near;this._ssao.ssaoMaterial.worldDistanceFalloff=e*.01,this._ssao.ssaoMaterial.worldDistanceThreshold=this.context.mainCamera.far}}onCreateEffect(){const e=this.context.mainCamera,i=new exports.MODULES.POSTPROCESSING.MODULE.NormalPass(this.context.scene,e),n=new exports.MODULES.POSTPROCESSING.MODULE.DepthDownsamplingPass({normalBuffer:i.texture,resolutionScale:.5}),s=this._ssao=new exports.MODULES.POSTPROCESSING.MODULE.SSAOEffect(e,i.texture,{normalDepthBuffer:n.texture,worldDistanceThreshold:1,worldDistanceFalloff:1,worldProximityThreshold:.1,worldProximityFalloff:2,intensity:1,blendFunction:exports.MODULES.POSTPROCESSING.MODULE.BlendFunction.MULTIPLY,luminanceInfluence:.5});this.intensity.onValueChanged=l=>{s.intensity=l},this.falloff.onValueChanged=l=>{s.ssaoMaterial.radius=l*.1},this.samples.onValueChanged=l=>{s.ssaoMaterial.samples=l},this.color.onValueChanged=l=>{s.color||(s.color=new d.Color),s.color.copy(l)},this.luminanceInfluence.onValueChanged=l=>{s.luminanceInfluence=l};const a=new Array;return a.push(i),a.push(n),a.push(s),a}}jh([m(U)],Vs.prototype,"intensity");jh([m(U)],Vs.prototype,"falloff");jh([m(U)],Vs.prototype,"samples");jh([m(U)],Vs.prototype,"color");jh([m(U)],Vs.prototype,"luminanceInfluence");tn("ScreenSpaceAmbientOcclusion",Vs);var yR=Object.defineProperty,ea=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&yR(t,e,n),n};const _R=S("debugN8AO");var Bm=(o=>(o[o.Performance=0]="Performance",o[o.Low=1]="Low",o[o.Medium=2]="Medium",o[o.High=3]="High",o[o.Ultra=4]="Ultra",o))(Bm||{});class On extends Ye{constructor(){super(...arguments);r(this,"gammaCorrection",!0);r(this,"aoRadius",new U(1));r(this,"falloff",new U(1));r(this,"intensity",new U(1));r(this,"color",new U(new d.Color(0,0,0)));r(this,"screenspaceRadius",!1);r(this,"quality",2);r(this,"_ssao")}get typeName(){return"ScreenSpaceAmbientOcclusionN8"}get pass(){return this._ssao}onValidate(){this._ssao&&(this._ssao.setQualityMode(Bm[this.quality]),this._ssao.configuration.gammaCorrection=this.gammaCorrection,this._ssao.configuration.screenSpaceRadius=this.screenspaceRadius)}onCreateEffect(){const e=this.context.mainCamera,i=this.context.domWidth,n=this.context.domHeight,s=this._ssao=new exports.MODULES.POSTPROCESSING_AO.MODULE.N8AOPostPass(this.context.scene,e,i,n);s.name="SSAO_N8";const a=Bm[this.quality];s.setQualityMode(a),s.configuration.transparencyAware=!1;const l=new d.WebGLRenderTarget(i,n);return s.configuration.beautyRenderTarget=l,s.configuration.autoRenderBeauty=!1,s.configuration.gammaCorrection=this.gammaCorrection,s.configuration.screenSpaceRadius=this.screenspaceRadius,_R&&(s.enableDebugMode(),console.log(s),setInterval(()=>{console.log("SSAO",s.lastTime)},1e3),setInterval(()=>{console.log("SSAO",s.enabled,{ssao:s,autoRenderBeauty:s.configuration.autoRenderBeauty})},4e3)),this.intensity.onValueChanged=c=>{s.configuration.intensity=c},this.falloff.onValueChanged=c=>{s.configuration.distanceFalloff=c},this.aoRadius.onValueChanged=c=>{s.configuration.aoRadius=c},this.color.onValueChanged=c=>{s.color||(s.color=new d.Color),s.configuration.color.copy(c)},s}}ea([St(),m()],On.prototype,"gammaCorrection");ea([m(U)],On.prototype,"aoRadius");ea([m(U)],On.prototype,"falloff");ea([m(U)],On.prototype,"intensity");ea([m(U)],On.prototype,"color");ea([St(),m()],On.prototype,"screenspaceRadius");ea([St(),m()],On.prototype,"quality");tn("ScreenSpaceAmbientOcclusionN8",On);var bR=Object.defineProperty,vR=Object.getOwnPropertyDescriptor,gx=(o,t,e,i)=>{for(var n=vR(t,e),s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&bR(t,e,n),n};class Bh extends Ye{constructor(){super(...arguments);r(this,"order",it.Sharpening);r(this,"_effect");r(this,"_amount",1);r(this,"_radius",1)}get typeName(){return"Sharpening"}onCreateEffect(){return this._effect??(this._effect=new(wR())),this.effect}get effect(){return this._effect}set amount(e){this._amount=e,this._effect&&(this._effect.uniforms.get("amount").value=e)}get amount(){return this._effect?this._effect.uniforms.get("amount").value:this._amount}set radius(e){this._radius=e,this._effect&&(this._effect.uniforms.get("radius").value=e)}get radius(){return this._effect?this._effect.uniforms.get("radius").value:this._radius}}gx([m()],Bh.prototype,"amount");gx([m()],Bh.prototype,"radius");function wR(){const o=`
1274
1274
  void mainSupport() {
1275
1275
  vUv = uv;
1276
1276
  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
@@ -1319,7 +1319,9 @@ axisFormat %s
1319
1319
  ---------------------------------
1320
1320
  • `+a.passes.map(f=>f.name).join(`
1321
1321
  • `)+`
1322
- `),ps&&this._onCreateEffectsDebug(this._composer,s)}createPassForMergeableEffects(t,e,i,n){if(t.length>0){const s=new exports.MODULES.POSTPROCESSING.MODULE.EffectPass(i,...t);s.name=t.map(a=>a.name).join(", "),s.mainScene=n,s.enabled=!0,s.renderToScreen=!1,e.addPass(s),t.length=0}}_onCreateEffectsDebug(t,e){if(ps==="passes"){const i=new exports.MODULES.POSTPROCESSING.MODULE.DepthEffect({blendFunction:exports.MODULES.POSTPROCESSING.MODULE.BlendFunction.NORMAL,inverted:!0});i.name="Depth Effect";const n=new exports.MODULES.POSTPROCESSING.MODULE.EffectPass(e,i);if(n.name="Depth Effect Pass",n.enabled=!1,t.passes.push(n),this._passIndices!==null){const a=[t.passes[0]];this._passIndices.length>0&&a.push(...this._passIndices.filter(l=>l!==0).map(l=>t.passes[l]).filter(l=>l)),a.length>0&&console.log("[PostProcessing] Passes (selected) →",a),t.passes.length=0;for(const l of a)l.enabled=!0,l.renderToScreen=!1,t.addPass(l)}const s=this.context.menu;if(s&&this._passIndices===null){this._menuEntry&&this._menuEntry.remove();const a=document.createElement("select");a.multiple=!0;const l=document.createElement("option");l.innerText="Final Output",l.value="-1",a.appendChild(l);for(const c of t.passes){const h=document.createElement("option");h.innerText=c.name,h.value=`${t.passes.indexOf(c)}`,h.title=c.name,a.appendChild(h)}s.appendChild(a),this._menuEntry=a,a.addEventListener("change",()=>{const c=Array.from(a.selectedOptions).map(h=>parseInt(h.value));c.length===1&&c[0]===-1?this._passIndices=null:this._passIndices=c,this.applyEffects(this.context)})}}}}var CR=Object.defineProperty,yx=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&CR(t,e,n),n};const Ko=S("debugpost");class bl extends D{constructor(){super(...arguments);r(this,"sharedProfile");r(this,"multisampling","auto");r(this,"_postprocessing");r(this,"_activeEffects",[]);r(this,"_effects",[]);r(this,"_componentEnabledTime",-1);r(this,"_multisampleAutoChangeTime",0);r(this,"_multisampleAutoDecreaseTime",0);r(this,"_lastApplyTime");r(this,"_rapidApplyCount",0);r(this,"_isDirty",!1);r(this,"_modificationQueue");r(this,"_recreateId",-1)}get isPostProcessingManager(){return!0}get effects(){return this._activeEffects}get dirty(){return this._isDirty}set dirty(e){this._isDirty=e}addEffect(e){let i=e;return i instanceof Ye||(i=new Wc(i)),i.gameObject===void 0&&this.gameObject.addComponent(i),this._effects.includes(i)||(this._effects.push(i),this._isDirty=!0),e}removeEffect(e){var n,s,a,l;let i=-1;if(e instanceof Ye?i=this._effects.indexOf(e):i=this._effects.findIndex(c=>c instanceof Wc&&c.effect===e),i!==-1)return this._effects.splice(i,1),this._isDirty=!0,e;if(e instanceof Ye){const c=(s=(n=this.sharedProfile)==null?void 0:n.components)==null?void 0:s.indexOf(e);c!==void 0&&c!==-1&&(this._isDirty=!0,(l=(a=this.sharedProfile)==null?void 0:a.components)==null||l.splice(c,1))}return e}markDirty(){this._isDirty=!0}awake(){var e;Ko&&(console.log("PostprocessingManager Awake",this),console.log("Press P to toggle post processing"),window.addEventListener("keydown",i=>{i.key==="p"&&(this.enabled=!this.enabled,Ee("Toggle PostProcessing "+this.name+": Enabled="+this.enabled),this.markDirty())})),(e=this.sharedProfile)==null||e.__init(this)}onEnable(){this._componentEnabledTime=this.context.time.realtimeSinceStartup,this._isDirty=!0}onDisable(){var e;(e=this._postprocessing)==null||e.unapply(),this._isDirty=!1}onBeforeRender(){if(!this.context.isInXR&&(this.context.mainCamera&&this._isDirty&&this.apply(),this.context.composer&&this._postprocessing&&this._postprocessing.composer===this.context.composer)){if(this.context.renderer.getContext().isContextLost()&&this.context.renderer.forceContextRestore(),this.context.composer.getRenderer()!==this.context.renderer&&this.context.composer.setRenderer(this.context.renderer),this.context.composer.setMainScene(this.context.scene),this.multisampling==="auto")if(this._postprocessing&&this._postprocessing.hasSmaaEffect)this._postprocessing.multisampling!==0&&(this._postprocessing.multisampling=0,(Ko||j())&&console.warn("[PostProcessing] Disabling multisampling you're using SMAA and have set the 'multisampling: auto' on your PostprocessingManager/Volume component. If you need anti-aliasing, consider adding an Antialiasing component or SMAA effect to the PostprocessingManager."));else{const e=this.context.time.realtimeSinceStartup-this._multisampleAutoChangeTime;if(this.context.time.realtimeSinceStartup-this._componentEnabledTime>2&&e>.5){const i=this._postprocessing.multisampling;if(this._postprocessing.multisampling>0&&this.context.time.smoothedFps<=50){this._multisampleAutoChangeTime=this.context.time.realtimeSinceStartup,this._multisampleAutoDecreaseTime=this.context.time.realtimeSinceStartup;let n=this._postprocessing.multisampling*.5;n=Math.floor(n),n!=this._postprocessing.multisampling&&(this._postprocessing.multisampling=n),Ko&&console.debug(`[PostProcessing] Reduced multisampling from ${i} to ${this._postprocessing.multisampling}`)}else if(e>1&&this.context.time.smoothedFps>=59&&this._postprocessing.multisampling<this.context.renderer.capabilities.maxSamples&&this.context.time.realtimeSinceStartup-this._multisampleAutoDecreaseTime>10){this._multisampleAutoChangeTime=this.context.time.realtimeSinceStartup;let n=this._postprocessing.multisampling<=0?1:this._postprocessing.multisampling*2;n=Math.floor(n),n!==this._postprocessing.multisampling&&(this._postprocessing.multisampling=n),Ko&&console.debug(`[PostProcessing] Increased multisampling from ${i} to ${this._postprocessing.multisampling}`)}}}else{const e=Math.max(0,Math.min(this.multisampling,this.context.renderer.capabilities.maxSamples));e!==this._postprocessing.multisampling&&(this._postprocessing.multisampling=e)}if(this.context.mainCamera){const e=this.context.composer.passes;for(const i of e)if(i.mainCamera&&i.mainCamera!==this.context.mainCamera){this.context.composer.setMainCamera(this.context.mainCamera);break}}}}onDestroy(){var e;(e=this._postprocessing)==null||e.dispose()}apply(){var e,i,n;if(Ko&&console.log(`Apply PostProcessing "${this.name||"unnamed"}"`),j()&&(this._lastApplyTime!==void 0&&Date.now()-this._lastApplyTime<100&&(this._rapidApplyCount++,this._rapidApplyCount===5&&console.warn("Detected rapid post processing modifications - this might be a bug",this)),this._lastApplyTime=Date.now()),this._isDirty=!1,this._activeEffects.length=0,(e=this.sharedProfile)!=null&&e.components){const s=this.sharedProfile.components;for(const a of s)a.active&&a.enabled&&!this._activeEffects.includes(a)&&this._activeEffects.push(a)}for(const s of this._effects)s.active&&s.enabled&&!this._activeEffects.includes(s)&&this._activeEffects.push(s);this._activeEffects.length>0?(this._postprocessing||(this._postprocessing=new Dy(this.context)),(i=this._postprocessing.apply(this._activeEffects))==null||i.then(()=>{this.activeAndEnabled&&(this._applyPostQueue(),this._postprocessing?(this.multisampling==="auto"?this._postprocessing.multisampling=exports.DeviceUtilities.isMobileDevice()?2:4:this._postprocessing.multisampling=Math.max(0,Math.min(this.multisampling,this.context.renderer.capabilities.maxSamples)),Ko&&console.debug(`[PostProcessing] Set multisampling to ${this._postprocessing.multisampling} (Is Mobile: ${exports.DeviceUtilities.isMobileDevice()})`)):Ko&&console.warn("[PostProcessing] No composer found"))})):(n=this._postprocessing)==null||n.unapply(!1)}_applyPostQueue(){if(this._modificationQueue){for(const e of this._modificationQueue.values())this.onEditorModification(e);this._modificationQueue.clear()}}onEditorModification(e){var i,n;if(e.propertyName.startsWith("postprocessing.")){if(!this._postprocessing)return this._modificationQueue||(this._modificationQueue=new Map),this._modificationQueue.set(e.propertyName,e),!0;if(!((i=this._activeEffects)!=null&&i.length))return;const s=e.propertyName.split(".");if(s.length===3||s.length===4){const a=s[1],l=s[2];for(const c of this._activeEffects)if(((n=c.typeName)==null?void 0:n.toLowerCase())===a.toLowerCase()){if(l==="active"){c.active=e.value,this.scheduleRecreate();return}if(!Pd.has(a)){const h=new Array;Pd.set(a,h);const u=Object.keys(c);for(const f of u)c[f]instanceof U&&h.push(f)}if(Pd.has(a)){const h=l.toLowerCase(),u=Pd.get(a);for(const f of u)if(f.toLowerCase()===h){const p=c[f];p instanceof U&&(s.length===4&&s[3]==="active"?(p.overrideState=e.value,this.scheduleRecreate()):p&&p.value!==void 0&&(p.value=e.value));return}}console.warn("Unknown modification",l);return}}return!0}return!1}scheduleRecreate(){const e=++this._recreateId;setTimeout(()=>{e===this._recreateId&&(this.onDisable(),this.onEnable())},200)}}yx([Br(_f)],bl.prototype,"sharedProfile");yx([Br()],bl.prototype,"multisampling");const Pd=new Map;Wk(bl);async function Iy(o){const{NeedleEngineWebComponent:t}=await Promise.resolve().then(()=>JE);t.observedAttributes.includes(o)||t.observedAttributes.push(o)}var PR=Object.defineProperty,pt=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&PR(t,e,n),n};const Mt=S("debugsceneswitcher"),MR=S("sceneswitcher:clearscene"),$d="scene";Iy($d);const Zs=Promise.resolve(!1);class He extends D{constructor(){super(...arguments);r(this,"autoLoadFirstScene",!0);r(this,"scenes",[]);r(this,"loadingScene");r(this,"queryParameterName","scene");r(this,"useSceneName",!0);r(this,"clamp",!0);r(this,"useHistory",!0);r(this,"useKeyboard",!0);r(this,"useSwipe",!0);r(this,"useSceneLighting",!0);r(this,"useSceneBackground",!0);r(this,"preloadNext",1);r(this,"preloadPrevious",1);r(this,"preloadConcurrent",2);r(this,"createMenuButtons",!1);r(this,"sceneLoadingStart",new ye);r(this,"sceneLoadingProgress",new ye);r(this,"sceneLoaded",new ye);r(this,"_currentIndex",-1);r(this,"_currentScene");r(this,"_engineElementOverserver");r(this,"_preloadScheduler");r(this,"_menuButtons");r(this,"onPopState",async e=>{if(!this.useHistory)return;const i=this.useHistory;try{this.useHistory=!1;let n=!1;if(this.queryParameterName&&(n=await this.tryLoadFromQueryParam()),!n){const s=e==null?void 0:e.state;if(s&&s.startsWith(this.guid)){const a=s.substr(this.guid.length+2);Mt&&console.log("PopState",a),await this.trySelectSceneFromValue(a)}}}finally{this.useHistory=i}});r(this,"normalizedSwipeThresholdX",.1);r(this,"_didSwipe",!1);r(this,"onInputPointerMove",e=>{if(this.useSwipe&&!this._didSwipe&&e.button===0&&e.pointerType==="touch"&&this.context.input.getPointerPressedCount()===1){const i=this.context.input.getPointerPositionDelta(e.button);if(i){const n=i.x/this.context.domWidth;n>=this.normalizedSwipeThresholdX?(this._didSwipe=!0,this.selectPrev()):n<=-this.normalizedSwipeThresholdX&&(this._didSwipe=!0,this.selectNext())}}});r(this,"onInputPointerUp",e=>{e.button===0&&(this._didSwipe=!1)});r(this,"onInputKeyDown",e=>{if(!this.useKeyboard||!this.scenes)return;const i=e.key.toLowerCase();if(!i)return;const n=parseInt(i)-1;if(n>=0){this.trySelectSceneFromValue(n);return}switch(i){case"arrowright":case"d":this.selectNext();break;case"arrowleft":case"a":this.selectPrev();break}});r(this,"__lastSwitchScene");r(this,"__lastSwitchScenePromise");r(this,"_currentlyLoadingScene");r(this,"_lastLoadingScene");r(this,"_loadingScenePromise");r(this,"_isCurrentlyLoading",!1);r(this,"_currentLoadingProgress")}get currentIndex(){return this._currentIndex}get currentLoadingProgress(){return this._currentLoadingProgress}get currentlyLoadingScene(){return this._currentlyLoadingScene}get currentlyLoadedScene(){return this._currentScene}awake(){this.scenes===void 0&&(this.scenes=[]);for(const e of this.scenes)e&&!e.hasUrl&&e.asset instanceof d.Object3D?C.remove(e.asset):e instanceof d.Object3D&&C.remove(e);Mt&&console.log("SceneSwitcher",this)}async onEnable(){if(globalThis.addEventListener("popstate",this.onPopState),this.context.input.addEventListener(Re.KeyDown,this.onInputKeyDown),this.context.input.addEventListener(Re.PointerMove,this.onInputPointerMove),this.context.input.addEventListener(Re.PointerUp,this.onInputPointerUp),this._engineElementOverserver||(this._engineElementOverserver=new MutationObserver(e=>{for(const i of e)if(i.type==="attributes"&&i.attributeName===$d){const n=this.context.domElement.getAttribute($d);n!==null&&this.trySelectSceneFromValue(n)}})),this._engineElementOverserver.observe(this.context.domElement,{attributes:!0}),this._preloadScheduler||(this._preloadScheduler=new OR(this)),this._preloadScheduler.maxLoadAhead=this.preloadNext,this._preloadScheduler.maxLoadBehind=this.preloadPrevious,this._preloadScheduler.maxConcurrent=this.preloadConcurrent,this._preloadScheduler.begin(2e3),this.autoLoadFirstScene&&this._currentIndex===-1&&!await this.tryLoadFromQueryParam()){const e=this.context.domElement.getAttribute($d);try{(e===null||!await this.trySelectSceneFromValue(e))&&this._currentIndex===-1&&this.select(0)}finally{}}this.createMenuButtons&&(this._menuButtons??(this._menuButtons=[]),this._menuButtons.push(this.context.menu.appendChild({label:"Previous",icon:"arrow_back_ios",onClick:()=>this.selectPrev(),priority:-1005,class:"row2"})),this._menuButtons.push(this.context.menu.appendChild({label:"Next",icon:"arrow_forward_ios",iconSide:"right",onClick:()=>this.selectNext(),priority:-1e3,class:"row2"})))}onDisable(){var e;if(globalThis.removeEventListener("popstate",this.onPopState),this.context.input.removeEventListener(Re.KeyDown,this.onInputKeyDown),this.context.input.removeEventListener(Re.PointerMove,this.onInputPointerMove),this.context.input.removeEventListener(Re.PointerUp,this.onInputPointerUp),(e=this._preloadScheduler)==null||e.stop(),this._menuButtons){for(const i of this._menuButtons)i.remove();this._menuButtons=void 0}}addScene(e){if(typeof e=="string"){let i=this.context.addressables.findAssetReference(e);return i||(i=new te(e),this.context.addressables.registerAssetReference(i)),this.scenes.push(i),i}return this.scenes.push(e),e}selectNext(){return this.select(this._currentIndex+1)}selectPrev(){return this.select(this._currentIndex-1)}select(e){var n,s,a;if(Mt&&console.log("select",e),typeof e=="object"&&console.warn('Switching to "'+e+'" might not work. Please either use an index or a AssetReference (not a scene reference)'),typeof e=="string"){const l=(n=this.scenes)==null?void 0:n.find(c=>c.url===e);if(!l){const c=te.getOrCreate(this.sourceId??"",e,this.context);return this.switchScene(c)}if(l)e=(s=this.scenes)==null?void 0:s.indexOf(l);else return Zs}if(!((a=this.scenes)!=null&&a.length))return Zs;if(e<0){if(this.clamp)return Zs;e=this.scenes.length-1}else if(e>=this.scenes.length){if(this.clamp)return Zs;e=0}const i=this.scenes[e];return this.switchScene(i)}unload(){return this.__lastSwitchScene=void 0,this.__lastSwitchScenePromise=void 0,this.__unloadCurrentScene()}async reload(){if(this.__lastSwitchScene){const e=this.__lastSwitchScene;return this.__lastSwitchScene=void 0,this.switchScene(e)}return!1}async switchScene(e){var n;if(!(e instanceof te)){const s=typeof e;if(s==="string")return this.select(e);if(s==="number")return this.select(e);if(e&&e instanceof d.Object3D){const a=(n=this.scenes)==null?void 0:n.indexOf(e);e=new te(e.name,void 0,e),a>=0&&(this.scenes[a]=e)}else return console.warn(`[SceneSwitcher] Can't switch to scene of type ${s}`),!1}return e.url===this.sourceId?(console.warn("[SceneSwitcher] Can't load own scene - prevent recursive loading",this.sourceId),!1):this.__lastSwitchScene===e&&this.__lastSwitchScenePromise?this.__lastSwitchScenePromise:(this.__lastSwitchScene=e,this.__lastSwitchScenePromise=this.__internalSwitchScene(e),await this.__lastSwitchScenePromise)}async __unloadCurrentScene(){const e=this._currentScene;if(this._currentScene=void 0,e){Mt&&console.log("UNLOAD",e.url,"HasURL?: "+e.hasUrl);const i=this.tryGetSceneEventListener(e.asset);if(i!=null&&i.sceneClosing){const n=i.sceneClosing();n instanceof Promise&&await n}e.hasUrl?e.unload():e.asset instanceof d.Object3D&&C.remove(e.asset)}}async __internalSwitchScene(e){var n,s,a,l,c;await this.__unloadCurrentScene();const i=this._currentIndex=((n=this.scenes)==null?void 0:n.indexOf(e))??-1;try{this._currentlyLoadingScene=e,this._currentLoadingProgress=new ProgressEvent("progress",{loaded:0,total:1});const h=new CustomEvent("loadscene-start",{detail:{scene:e,switcher:this,index:i}});this.dispatchEvent(h),(s=this.sceneLoadingStart)==null||s.invoke(h.detail),await this.onStartLoading(),await e.loadAssetAsync((f,p)=>{var g;if(Mt){const y=p.loaded/p.total,b="["+"=".repeat(Math.floor(y*20))+"-".repeat(20-Math.floor(y*20))+"]";console.debug(`[SceneSwitcher] Download ${(y*100).toFixed(1)} % ${b}`,e.url)}this._currentLoadingProgress=p,this.dispatchEvent(p),(g=this.sceneLoadingProgress)==null||g.invoke(p)}).catch(console.error),await this.onEndLoading();const u=new CustomEvent("loadscene-finished",{detail:{scene:e,switcher:this,index:i}});if(this.dispatchEvent(u),this._currentLoadingProgress=void 0,this._currentlyLoadingScene=void 0,u.defaultPrevented)return Mt&&console.warn("Adding loaded scene prevented:",e,u),!1;if(!e.asset)return Mt&&console.warn("Failed loading scene:",e),!1;if(this._currentIndex===i){if(Mt&&console.log("ADD",e.url),this._currentScene=e,MR){const g=((a=this.context.mainCameraComponent)==null?void 0:a.gameObject)||this.context.mainCamera;g==null||g.removeFromParent();const y=this.gameObject.removeFromParent();Ri(this.context.scene,!0,!0),this.context.scene=new d.Scene,this.context.scene.add(y),g&&this.context.scene.add(g)}if(C.add(e.asset,this.gameObject),this.useSceneLighting&&this.context.sceneLighting.enable(e),this.useSceneBackground){const g=this.context.lightmaps.tryGetSkybox(e.url);g?(g.mapping=d.EquirectangularReflectionMapping,this.context.scene.background=g):Mt&&console.warn("SceneSwitcher: Can't find skybox for scene "+e.url)}if(this.useHistory&&i>=0){let g=i.toString();if(this.useSceneName&&(e instanceof d.Object3D?g=e.name:e.url&&(g=zb(e.url))),(l=this.queryParameterName)!=null&&l.length)Mc(this.queryParameterName,g,this.useHistory);else{const y=history.state,b=this.guid+"::"+i;y!==b&&history.pushState(b,"unused",location.href)}}const f=this.tryGetSceneEventListener(e.asset);if(f!=null&&f.sceneOpened){const g=f.sceneOpened(this);g instanceof Promise&&await g}const p=new CustomEvent("scene-opened",{detail:{scene:e,switcher:this,index:i}});return this.dispatchEvent(p),(c=this.sceneLoaded)==null||c.invoke(this),!0}}catch(h){console.error(h)}return!1}preload(e){if(e>=0&&e<this.scenes.length){const i=this.scenes[e];if(i instanceof te)return i.preload()}return Zs}tryLoadFromQueryParam(){var i;if(!((i=this.queryParameterName)!=null&&i.length))return Zs;const e=S(this.queryParameterName);return typeof e=="boolean"?Zs:this.trySelectSceneFromValue(e)}trySelectSceneFromValue(e){if(typeof e=="string"){const i=parseInt(e);if(i>=0&&i<this.scenes.length)return this.select(i);{const n=e.toLowerCase();for(let s=0;s<this.scenes.length;s++){const a=this.scenes[s];if(!a)continue;if((a instanceof d.Object3D?a.name:zb(a.url)).toLowerCase().includes(n))return this.select(s)}}}else if(typeof e=="number"&&e>=0&&e<this.scenes.length)return this.select(e);return Yt()&&console.warn('Can not find scene: "'+e+'"',this),Zs}async onStartLoading(){var e,i;if(this._isCurrentlyLoading=!0,this.loadingScene&&(this._lastLoadingScene!==this.loadingScene&&(this._loadingScenePromise=void 0),this._lastLoadingScene=this.loadingScene,this._loadingScenePromise||(this._loadingScenePromise=(e=this.loadingScene)==null?void 0:e.loadAssetAsync().then(n=>n!=null)),await this._loadingScenePromise,this._isCurrentlyLoading&&((i=this.loadingScene)!=null&&i.asset))){Mt&&console.log("Add loading scene",this.loadingScene.url,this.loadingScene.asset);const n=this.loadingScene.asset;C.add(n,this.gameObject);const s=this.tryGetSceneEventListener(n);if(s!=null&&s.sceneOpened){const a=s.sceneOpened(this);a instanceof Promise&&await a}}if(this._isCurrentlyLoading){const n=this.tryGetSceneEventListener(this.gameObject);if(n&&n.sceneOpened){const s=n.sceneOpened(this);s instanceof Promise&&await s}}}async onEndLoading(){var e;if(this._isCurrentlyLoading=!1,(e=this.loadingScene)!=null&&e.asset){Mt&&console.log("Remove loading scene",this.loadingScene.url);const i=this.loadingScene.asset,n=this.tryGetSceneEventListener(i);if(typeof(n==null?void 0:n.sceneClosing)=="function"){const s=n.sceneClosing();s instanceof Promise&&await s}C.remove(i)}if(!this._isCurrentlyLoading){const i=this.tryGetSceneEventListener(this.gameObject);if(i&&i.sceneClosing){const n=i.sceneClosing();n instanceof Promise&&await n}}}tryGetSceneEventListener(e,i=0){if(!e)return null;const n=C.foreachComponent(e,s=>{const a=s;if(a.sceneClosing||a.sceneOpened)return a});if(i===0&&!n&&e.children.length)for(const s of e.children){const a=this.tryGetSceneEventListener(s,i+1);if(a)return a}return n||null}}pt([m()],He.prototype,"autoLoadFirstScene");pt([m(te)],He.prototype,"scenes");pt([m(te)],He.prototype,"loadingScene");pt([m()],He.prototype,"queryParameterName");pt([m()],He.prototype,"useSceneName");pt([m()],He.prototype,"clamp");pt([m()],He.prototype,"useHistory");pt([m()],He.prototype,"useKeyboard");pt([m()],He.prototype,"useSwipe");pt([m()],He.prototype,"useSceneLighting");pt([m()],He.prototype,"useSceneBackground");pt([m()],He.prototype,"preloadNext");pt([m()],He.prototype,"preloadPrevious");pt([m()],He.prototype,"preloadConcurrent");pt([m()],He.prototype,"createMenuButtons");pt([m(ye)],He.prototype,"sceneLoadingStart");pt([m(ye)],He.prototype,"sceneLoadingProgress");pt([m(ye)],He.prototype,"sceneLoaded");function zb(o){const t=o.split("/").pop(),e=t==null?void 0:t.split(".").shift();return e!=null&&e.length?e:o}class OR{constructor(t,e=1,i=1,n=2){r(this,"maxLoadAhead");r(this,"maxLoadBehind");r(this,"maxConcurrent");r(this,"_isRunning",!1);r(this,"_switcher");r(this,"_loadTasks",[]);r(this,"_maxConcurrentLoads",1);this._switcher=t,this.maxLoadAhead=e,this.maxLoadBehind=i,this.maxConcurrent=n}begin(t){if(this._isRunning)return;Mt&&console.log("Preload begin",{delay:t}),this._isRunning=!0;let e=-10,i,n;const s=this._switcher.scenes,a=Date.now()+t,l=setInterval(()=>{if(this.allLoaded()&&(Mt&&console.log("All scenes (pre-)loaded"),this.stop()),!this._isRunning){clearInterval(l);return}if(Date.now()<a||this.canLoadNewScene()===!1)return;(e===-10||e!==this._switcher.currentIndex)&&(e=this._switcher.currentIndex,n=0,i=0);const c=n%2===0;c&&(i+=1),n+=1;const h=c?this.maxLoadAhead:this.maxLoadBehind;if(i>h)return;const u=c?e+i:e-i;if(!(u<0)&&!(u<0||u>=s.length)&&!this._loadTasks.some(f=>f.index===u)){const f=s[u];Mt&&console.log("Preload scene",{roomIndex:u,searchForward:c,lastRoom:e,currentIndex:this._switcher.currentIndex,tasks:this._loadTasks.length},f==null?void 0:f.url),new kR(u,f,this._loadTasks)}},200)}stop(){this._isRunning=!1}canLoadNewScene(){return this._loadTasks.length<this._maxConcurrentLoads}allLoaded(){if(this._switcher.scenes){for(const t of this._switcher.scenes)if(t!=null&&t.isLoaded&&t.isLoaded()===!1)return!1}return!0}}class kR{constructor(t,e,i){r(this,"index");r(this,"asset");r(this,"tasks");this.index=t,this.asset=e,this.tasks=i,i.push(this),this.awaitLoading()}async awaitLoading(){this.asset&&!this.asset.isLoaded()&&(Mt&&console.log("Preload start: "+this.asset.url,this.index),await this.asset.preload(),Mt&&console.log("Preload finished: "+this.asset.url,this.index));const t=this.tasks.indexOf(this);t>=0&&this.tasks.splice(t,1)}}function RR(){return new Promise((o,t)=>{const i=()=>{i!=null&&(document.removeEventListener("pointerdown",i),document.removeEventListener("click",i),document.removeEventListener("dragstart",i),document.removeEventListener("touchstart",i),o())};document.addEventListener("pointerdown",i),document.addEventListener("click",i),document.addEventListener("dragstart",i),document.addEventListener("touchstart",i)})}async function ER(o){await RR(),o()}var TR=Object.defineProperty,AR=Object.getOwnPropertyDescriptor,Ii=(o,t,e,i)=>{for(var n=i>1?void 0:i?AR(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&TR(t,e,n),n};const ct=S("debugvideo");var _x=(o=>(o[o.None=0]="None",o[o.AdjustHeight=1]="AdjustHeight",o[o.AdjustWidth=2]="AdjustWidth",o))(_x||{}),bx=(o=>(o[o.VideoClip=0]="VideoClip",o[o.Url=1]="Url",o))(bx||{}),vx=(o=>(o[o.CameraFarPlane=0]="CameraFarPlane",o[o.CameraNearPlane=1]="CameraNearPlane",o[o.RenderTexture=2]="RenderTexture",o[o.MaterialOverride=3]="MaterialOverride",o))(vx||{});class rt extends D{constructor(){super();r(this,"playOnAwake",!0);r(this,"aspectMode",0);r(this,"clip",null);r(this,"source",1);r(this,"_url",null);r(this,"renderMode");r(this,"targetMaterialProperty");r(this,"targetMaterialRenderer");r(this,"targetTexture");r(this,"time",0);r(this,"_playbackSpeed",1);r(this,"_isLooping",!1);r(this,"_muted",!1);r(this,"_audioOutputMode",2);r(this,"playInBackground",!0);r(this,"_crossOrigin","anonymous");r(this,"_videoElement",null);r(this,"_videoTexture",null);r(this,"_videoMaterial",null);r(this,"_isPlaying",!1);r(this,"wasPlaying",!1);r(this,"visibilityChanged",e=>{switch(document.visibilityState){case"hidden":this.playInBackground||(this.wasPlaying=this._isPlaying,this.pause());break;case"visible":this.wasPlaying&&!this._isPlaying&&this.play();break}});r(this,"_receivedInput",!1);r(this,"_overlay",null);r(this,"_targetObjects");r(this,"_updateAspectRoutineId",-1);r(this,"_hls");r(this,"onHlsAvailable",()=>{var e;ct&&console.log("HLS: available",this.clip),!(!this.shouldUseM3U||!this.url)&&(this._hls||(this._hls=new Hls),this.videoElement.autoplay=!0,this._hls.loadSource(this.url),this._hls.attachMedia(this.videoElement),(e=this._videoElement)==null||e.play(),ct&&console.log("HLS: loaded",this.clip))});ER(()=>{this._receivedInput=!0,this.updateVideoElementSettings()}),this._targetObjects=[],S("videoscreenspace")&&window.addEventListener("keydown",e=>{e.key==="f"&&(this.screenspace=!this.screenspace)})}get url(){return this._url}set url(e){const n=this._url!==e;this.__didAwake?n&&this.setClipURL(e??""):this._url=e}get playbackSpeed(){var e;return((e=this._videoElement)==null?void 0:e.playbackRate)??this._playbackSpeed}set playbackSpeed(e){this._playbackSpeed=e,this._videoElement&&(this._videoElement.playbackRate=e)}get isLooping(){var e;return((e=this._videoElement)==null?void 0:e.loop)??this._isLooping}set isLooping(e){this._isLooping=e,this._videoElement&&(this._videoElement.loop=e)}get currentTime(){var e;return((e=this._videoElement)==null?void 0:e.currentTime)??this.time}set currentTime(e){this._videoElement?this._videoElement.currentTime=e:this.time=e}get isPlaying(){const e=this._videoElement;if(e){if(e.currentTime>0&&!e.paused&&!e.ended&&e.readyState>e.HAVE_CURRENT_DATA)return!0;if(e.srcObject&&e.srcObject.active)return!0}return!1}get crossOrigin(){var e;return((e=this._videoElement)==null?void 0:e.crossOrigin)??this._crossOrigin}set crossOrigin(e){this._crossOrigin=e,this._videoElement&&(e!==null?this._videoElement.setAttribute("crossorigin",e):this._videoElement.removeAttribute("crossorigin"))}get videoMaterial(){return!this._videoMaterial&&!this.create(!1)?null:this._videoMaterial}get videoTexture(){return!this._videoTexture&&!this.create(!1)?null:this._videoTexture}get videoElement(){return!this._videoElement&&!this.create(!1)?null:this._videoElement}requestPictureInPicture(){return this._videoElement?this._videoElement.requestPictureInPicture():null}get muted(){var e;return((e=this._videoElement)==null?void 0:e.muted)??this._muted}set muted(e){this._muted=e,this._videoElement&&(this._videoElement.muted=e)}get currentVideo(){return this.clip}set audioOutputMode(e){e!==this._audioOutputMode&&(e===1&&j()&&console.warn("VideoAudioOutputMode.AudioSource is not yet implemented"),this._audioOutputMode=e,this.updateVideoElementSettings())}get audioOutputMode(){return this._audioOutputMode}preloadVideo(){ct&&console.log("Video Preload: "+this.name,this.clip),this.create(!1)}preload(){this.preloadVideo()}setVideo(e){this.clip=e,this.source=0,this._videoElement?(this._videoElement.srcObject=e,this._isPlaying&&this.play(),this.updateAspect()):this.create(this.playOnAwake)}setClipURL(e){this._url!==e&&(this._url=e,this.source=1,ct&&console.log("set url",e),this._videoElement?e.endsWith(".m3u8")||e.includes(".m3u")?this.ensureM3UCanBePlayed():(this._videoElement.src=e,this._isPlaying&&(this.stop(),this.play())):this.create(this.playOnAwake))}onEnable(){var e,i;ct&&console.log("VideoPlayer.onEnable",bx[this.source],this.clip,this.url,this),window.addEventListener("visibilitychange",this.visibilityChanged),this.playOnAwake===!0?this.create(!0):this.preloadVideo(),this.screenspace?(e=this._overlay)==null||e.start():(i=this._overlay)==null||i.stop()}onDisable(){var e;window.removeEventListener("visibilitychange",this.visibilityChanged),(e=this._overlay)==null||e.stop(),this.pause()}onDestroy(){var e;this._videoElement&&((e=this.videoElement)==null||e.remove(),this._videoElement=null),this._videoTexture&&(this._videoTexture.dispose(),this._videoTexture=null)}play(){var e,i;if(this._videoElement||this.create(!1),!this._videoElement){ct&&console.warn("Can not play: no video element found",this);return}if(!(this._isPlaying&&!((e=this._videoElement)!=null&&e.ended)&&!((i=this._videoElement)!=null&&i.paused))){if(this._isPlaying=!0,this._receivedInput||(this._videoElement.muted=!0),this.handleBeginPlaying(!1),this.shouldUseM3U){this.ensureM3UCanBePlayed();return}ct&&console.log("Video Play()",this.clip,this._videoElement,this.time),this._videoElement.currentTime=this.time,this._videoElement.play().catch(n=>{var s;console.log(n),ct&&console.error("Error playing video",n,"CODE="+n.code,(s=this.videoElement)==null?void 0:s.src,this),setTimeout(()=>{this._isPlaying&&!this.destroyed&&this.activeAndEnabled&&this.play()},1e3)}),ct&&console.log("play",this._videoElement,this.time)}}stop(){this._isPlaying=!1,this.time=0,this._videoElement&&(this._videoElement.currentTime=0,this._videoElement.pause(),ct&&console.log("STOP",this))}pause(){var e,i;this.time=((e=this._videoElement)==null?void 0:e.currentTime)??0,this._isPlaying=!1,(i=this._videoElement)==null||i.pause(),ct&&console.log("PAUSE",this,this.currentTime)}create(e){let i;switch(this.source){case 0:i=this.clip;break;case 1:i=this.url,!(i!=null&&i.length)&&typeof this.clip=="string"&&(i=this.clip);break}return i?(this._videoElement||(ct&&console.warn("Create VideoElement",this),this._videoElement=this.createVideoElement(),this.context.domElement.shadowRoot.prepend(this._videoElement),this.updateVideoElementStyles()),typeof i=="string"?(ct&&console.log("Set Video src",i),this._videoElement.src=i):(ct&&console.log("Set Video srcObject",i),this._videoElement.srcObject=i),this._videoTexture||(this._videoTexture=new d.VideoTexture(this._videoElement)),this._videoTexture.flipY=!1,this._videoTexture.colorSpace=d.SRGBColorSpace,e&&this.handleBeginPlaying(e),ct&&console.log("Video: handle playing done...",i,e),!0):(ct&&console.warn("No video source set",this),!1)}updateAspect(){this.aspectMode!==0&&this.startCoroutine(this.updateAspectImpl())}get screenspace(){var e;return((e=this._overlay)==null?void 0:e.enabled)??!1}set screenspace(e){var i;if(e){if(!this._videoTexture)return;this._overlay||(this._overlay=new LR(this.context)),this._overlay.add(this._videoTexture)}else(i=this._overlay)==null||i.remove(this._videoTexture);this._overlay&&(this._overlay.enabled=e)}createVideoElement(){const e=document.createElement("video");return this._crossOrigin&&e.setAttribute("crossorigin",this._crossOrigin),ct&&console.log("created video element",e),e}handleBeginPlaying(e){var s,a;if(!this.activeAndEnabled||!this._videoElement)return;this._targetObjects.length=0;let i=this.gameObject;switch(this.renderMode){case 3:i=(s=this.targetMaterialRenderer)==null?void 0:s.gameObject,i||(i=(a=C.getComponent(this.gameObject,Ti))==null?void 0:a.gameObject);break;case 2:console.error("VideoPlayer renderTexture not implemented yet. Please use material override instead");return}if(!i){console.error("Missing target for video material renderer",this.name,vx[this.renderMode],this);return}const n=i.material;if(n){this._targetObjects.push(i),n!==this._videoMaterial&&(this._videoMaterial=n.clone(),i.material=this._videoMaterial);const l="map",c=this._videoMaterial;if(!this.targetMaterialProperty)c[l]=this._videoTexture;else switch(this.targetMaterialProperty){default:c[l]=this._videoTexture;break}}else{console.warn("Can not play video, no material found, this might be a multimaterial case which is not supported yet");return}this.updateVideoElementSettings(),this.updateVideoElementStyles(),e&&(this.shouldUseM3U&&this.ensureM3UCanBePlayed(),this.play())}updateVideoElementSettings(){if(!this._videoElement)return;this._videoElement.loop=this._isLooping,this._videoElement.currentTime=this.currentTime,this._videoElement.playbackRate=this._playbackSpeed,this._videoElement.playsInline=!0;let e=!this._receivedInput||this.audioOutputMode===0;!e&&this._muted&&(e=!0),this._videoElement.muted=e,this.playOnAwake&&(this._videoElement.autoplay=!0)}updateVideoElementStyles(){this._videoElement&&(this._videoElement.style.userSelect="none",this._videoElement.style.visibility="hidden",this._videoElement.style.display="none",this.updateAspect())}*updateAspectImpl(){const e=++this._updateAspectRoutineId,i=void 0,n=this.clip;for(;e===this._updateAspectRoutineId&&this.aspectMode!==0&&this.clip&&n===this.clip&&this._isPlaying;){if(!n||typeof n=="string")return;let s;for(const a of n.getVideoTracks()){const l=a.getSettings();if(l&&l.width&&l.height){s=l.width/l.height;break}else s=this.context.renderer.domElement.clientWidth/this.context.renderer.domElement.clientHeight}if(s===void 0){for(let a=0;a<10;a++)yield;if(!this.isPlaying)break;continue}if(i===s){yield;continue}for(const a of this._targetObjects){let l=1;if(a.parent){const c=Ue(a.parent);l=c.x/c.y}switch(this.aspectMode){case 1:a.scale.y=1/s*a.scale.x*l;break;case 2:a.scale.x=s*a.scale.y*l;break}}for(let a=0;a<3;a++)yield}}get shouldUseM3U(){return this.url!=null&&(this.url.endsWith(".m3u8")||this.url.endsWith(".m3u"))&&this.source===1}ensureM3UCanBePlayed(){if(!this.shouldUseM3U)return;let e=document.head.querySelector("script[data-hls_library]");e?globalThis.Hls?this.onHlsAvailable():e.addEventListener("load",this.onHlsAvailable):(ct&&console.log("HLS: load script"),e=document.createElement("script"),e.dataset.hls_library="hls.js",e.src="https://cdn.jsdelivr.net/npm/hls.js@1",e.addEventListener("load",this.onHlsAvailable),document.head.append(e))}}Ii([m()],rt.prototype,"playOnAwake",2);Ii([m()],rt.prototype,"aspectMode",2);Ii([m(URL)],rt.prototype,"clip",2);Ii([m()],rt.prototype,"source",2);Ii([m(URL)],rt.prototype,"url",1);Ii([m()],rt.prototype,"renderMode",2);Ii([m()],rt.prototype,"targetMaterialProperty",2);Ii([m(Ti)],rt.prototype,"targetMaterialRenderer",2);Ii([m(d.Texture)],rt.prototype,"targetTexture",2);Ii([m()],rt.prototype,"time",2);Ii([m()],rt.prototype,"playbackSpeed",1);Ii([m()],rt.prototype,"isLooping",1);Ii([m()],rt.prototype,"audioOutputMode",1);class LR{constructor(t){r(this,"context");r(this,"_videos",[]);r(this,"_screenspaceModeQuad");r(this,"_isInScreenspaceMode",!1);r(this,"_input");this.context=t,this._input=new DR(this)}get enabled(){return this._isInScreenspaceMode}set enabled(t){t?this.start():this.stop()}add(t){this._videos.indexOf(t)===-1&&this._videos.push(t)}remove(t){if(!t)return;const e=this._videos.indexOf(t);e>=0&&this._videos.splice(e,1)}start(){var n;if(this._isInScreenspaceMode||this._videos.length<0)return;const t=this._videos[this._videos.length-1];if(!t)return;if(this._isInScreenspaceMode=!0,!this._screenspaceModeQuad){if(this._screenspaceModeQuad=Do.createPrimitive(Or.Quad,{material:new IR(t)}),!this._screenspaceModeQuad)return;this._screenspaceModeQuad.geometry.scale(2,2,2)}const e=this._screenspaceModeQuad;this.context.scene.add(e),this.updateScreenspaceMaterialUniforms();const i=e.material;i==null||i.reset(),(n=this._input)==null||n.enable(i)}stop(){var t;this._isInScreenspaceMode=!1,this._screenspaceModeQuad&&((t=this._input)==null||t.disable(),this._screenspaceModeQuad.removeFromParent())}updateScreenspaceMaterialUniforms(){var e;const t=(e=this._screenspaceModeQuad)==null?void 0:e.material;t&&(t.screenAspect=this.context.domElement.clientWidth/this.context.domElement.clientHeight)}}class DR{constructor(t){r(this,"_onResizeScreenFn");r(this,"_onKeyUpFn");r(this,"_onMouseWheelFn");r(this,"context");r(this,"overlay");r(this,"_material");r(this,"_isPinching",!1);r(this,"_lastPinch",0);this.overlay=t,this.context=t.context}enable(t){this._material=t,window.addEventListener("resize",this._onResizeScreenFn=()=>{this.overlay.updateScreenspaceMaterialUniforms()}),window.addEventListener("keyup",this._onKeyUpFn=n=>{n.key==="Escape"&&this.overlay.stop()}),window.addEventListener("wheel",this._onMouseWheelFn=n=>{this.overlay.enabled&&(t.zoom+=n.deltaY*5e-4,n.preventDefault())},{passive:!1});const e=new d.Vector2;window.addEventListener("mousemove",n=>{if(this.overlay.enabled&&this.context.input.getPointerPressed(0)){const s=new d.Vector2(n.movementX,n.movementY);s.x/=this.context.domElement.clientWidth,s.y/=this.context.domElement.clientHeight,e.set(s.x,s.y),e.multiplyScalar(t.zoom/-this.context.time.deltaTime*.01),t.offset=t.offset.add(e)}}),window.addEventListener("pointermove",n=>{this.overlay.enabled&&this.context.input.getPointerPressed(0)&&this.context.input.getTouchesPressedCount()===1&&(e.set(n.movementX,n.movementY),e.multiplyScalar(t.zoom*-this.context.time.deltaTime*.05),t.offset=t.offset.add(e))});let i=0;window.addEventListener("touchstart",n=>{if(n.touches.length<2){this.context.time.time-i<.3&&this.overlay.stop(),i=this.context.time.time;return}this._isPinching=!0,this._lastPinch=0}),window.addEventListener("touchmove",n=>{if(!this._isPinching||!this._material)return;const s=n.touches[0],a=n.touches[1],l=s.clientX-a.clientX,c=s.clientY-a.clientY,h=Math.sqrt(l*l+c*c);if(this._lastPinch!==0){const u=h-this._lastPinch;this._material.zoom-=u*.004}this._lastPinch=h}),window.addEventListener("touchend",()=>{this._isPinching=!1})}disable(){this._onResizeScreenFn&&(window.removeEventListener("resize",this._onResizeScreenFn),this._onResizeScreenFn=void 0),this._onKeyUpFn&&(window.removeEventListener("keyup",this._onKeyUpFn),this._onKeyUpFn=void 0),this._onMouseWheelFn&&(window.removeEventListener("wheel",this._onMouseWheelFn),this._onMouseWheelFn=void 0)}}class IR extends d.ShaderMaterial{constructor(e){super();r(this,"_offset",new d.Vector2);this.uniforms={map:{value:e},screenAspect:{value:1},offsetScale:{value:new d.Vector4(0,0,1,1)}},this.vertexShader=`
1322
+ `),ps&&this._onCreateEffectsDebug(this._composer,s)}createPassForMergeableEffects(t,e,i,n){if(t.length>0){const s=new exports.MODULES.POSTPROCESSING.MODULE.EffectPass(i,...t);s.name=t.map(a=>a.name).join(", "),s.mainScene=n,s.enabled=!0,s.renderToScreen=!1,e.addPass(s),t.length=0}}_onCreateEffectsDebug(t,e){if(ps==="passes"){const i=new exports.MODULES.POSTPROCESSING.MODULE.DepthEffect({blendFunction:exports.MODULES.POSTPROCESSING.MODULE.BlendFunction.NORMAL,inverted:!0});i.name="Depth Effect";const n=new exports.MODULES.POSTPROCESSING.MODULE.EffectPass(e,i);if(n.name="Depth Effect Pass",n.enabled=!1,t.passes.push(n),this._passIndices!==null){const a=[t.passes[0]];this._passIndices.length>0&&a.push(...this._passIndices.filter(l=>l!==0).map(l=>t.passes[l]).filter(l=>l)),a.length>0&&console.log("[PostProcessing] Passes (selected) →",a),t.passes.length=0;for(const l of a)l.enabled=!0,l.renderToScreen=!1,t.addPass(l)}const s=this.context.menu;if(s&&this._passIndices===null){this._menuEntry&&this._menuEntry.remove();const a=document.createElement("select");a.multiple=!0;const l=document.createElement("option");l.innerText="Final Output",l.value="-1",a.appendChild(l);for(const c of t.passes){const h=document.createElement("option");h.innerText=c.name,h.value=`${t.passes.indexOf(c)}`,h.title=c.name,a.appendChild(h)}s.appendChild(a),this._menuEntry=a,a.addEventListener("change",()=>{const c=Array.from(a.selectedOptions).map(h=>parseInt(h.value));c.length===1&&c[0]===-1?this._passIndices=null:this._passIndices=c,this.applyEffects(this.context)})}}}}var CR=Object.defineProperty,yx=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&CR(t,e,n),n};const Ko=S("debugpost");class bl extends D{constructor(){super(...arguments);r(this,"sharedProfile");r(this,"multisampling","auto");r(this,"_postprocessing");r(this,"_activeEffects",[]);r(this,"_effects",[]);r(this,"_componentEnabledTime",-1);r(this,"_multisampleAutoChangeTime",0);r(this,"_multisampleAutoDecreaseTime",0);r(this,"_lastApplyTime");r(this,"_rapidApplyCount",0);r(this,"_isDirty",!1);r(this,"_modificationQueue");r(this,"_recreateId",-1)}get isPostProcessingManager(){return!0}get effects(){return this._activeEffects}get dirty(){return this._isDirty}set dirty(e){this._isDirty=e}addEffect(e){let i=e;return i instanceof Ye||(i=new Wc(i)),i.gameObject===void 0&&this.gameObject.addComponent(i),this._effects.includes(i)||(this._effects.push(i),this._isDirty=!0),e}removeEffect(e){var n,s,a,l;let i=-1;if(e instanceof Ye?i=this._effects.indexOf(e):i=this._effects.findIndex(c=>c instanceof Wc&&c.effect===e),i!==-1)return this._effects.splice(i,1),this._isDirty=!0,e;if(e instanceof Ye){const c=(s=(n=this.sharedProfile)==null?void 0:n.components)==null?void 0:s.indexOf(e);c!==void 0&&c!==-1&&(this._isDirty=!0,(l=(a=this.sharedProfile)==null?void 0:a.components)==null||l.splice(c,1))}return e}markDirty(){this._isDirty=!0}awake(){var e;Ko&&(console.log("PostprocessingManager Awake",this),console.log("Press P to toggle post processing"),window.addEventListener("keydown",i=>{i.key==="p"&&(this.enabled=!this.enabled,Ee("Toggle PostProcessing "+this.name+": Enabled="+this.enabled),this.markDirty())})),(e=this.sharedProfile)==null||e.__init(this)}onEnable(){this._componentEnabledTime=this.context.time.realtimeSinceStartup,this._isDirty=!0}onDisable(){var e;(e=this._postprocessing)==null||e.unapply(),this._isDirty=!1}onBeforeRender(){if(!this.context.isInXR&&(this.context.mainCamera&&this._isDirty&&this.apply(),this.context.composer&&this._postprocessing&&this._postprocessing.composer===this.context.composer)){if(this.context.renderer.getContext().isContextLost()&&this.context.renderer.forceContextRestore(),this.context.composer.getRenderer()!==this.context.renderer&&this.context.composer.setRenderer(this.context.renderer),this.context.composer.setMainScene(this.context.scene),this.multisampling==="auto")if(this._postprocessing&&this._postprocessing.hasSmaaEffect)this._postprocessing.multisampling!==0&&(this._postprocessing.multisampling=0,(Ko||j())&&console.log(`[PostProcessing] multisampling is disabled because it's set to 'auto' on your PostprocessingManager/Volume component that also has an SMAA effect.
1323
+
1324
+ If you need multisampling consider changing 'auto' to a fixed value (e.g. 4).`));else{const e=this.context.time.realtimeSinceStartup-this._multisampleAutoChangeTime;if(this.context.time.realtimeSinceStartup-this._componentEnabledTime>2&&e>.5){const i=this._postprocessing.multisampling;if(this._postprocessing.multisampling>0&&this.context.time.smoothedFps<=50){this._multisampleAutoChangeTime=this.context.time.realtimeSinceStartup,this._multisampleAutoDecreaseTime=this.context.time.realtimeSinceStartup;let n=this._postprocessing.multisampling*.5;n=Math.floor(n),n!=this._postprocessing.multisampling&&(this._postprocessing.multisampling=n),Ko&&console.debug(`[PostProcessing] Reduced multisampling from ${i} to ${this._postprocessing.multisampling}`)}else if(e>1&&this.context.time.smoothedFps>=59&&this._postprocessing.multisampling<this.context.renderer.capabilities.maxSamples&&this.context.time.realtimeSinceStartup-this._multisampleAutoDecreaseTime>10){this._multisampleAutoChangeTime=this.context.time.realtimeSinceStartup;let n=this._postprocessing.multisampling<=0?1:this._postprocessing.multisampling*2;n=Math.floor(n),n!==this._postprocessing.multisampling&&(this._postprocessing.multisampling=n),Ko&&console.debug(`[PostProcessing] Increased multisampling from ${i} to ${this._postprocessing.multisampling}`)}}}else{const e=Math.max(0,Math.min(this.multisampling,this.context.renderer.capabilities.maxSamples));e!==this._postprocessing.multisampling&&(this._postprocessing.multisampling=e)}if(this.context.mainCamera){const e=this.context.composer.passes;for(const i of e)if(i.mainCamera&&i.mainCamera!==this.context.mainCamera){this.context.composer.setMainCamera(this.context.mainCamera);break}}}}onDestroy(){var e;(e=this._postprocessing)==null||e.dispose()}apply(){var e,i,n;if(Ko&&console.log(`Apply PostProcessing "${this.name||"unnamed"}"`),j()&&(this._lastApplyTime!==void 0&&Date.now()-this._lastApplyTime<100&&(this._rapidApplyCount++,this._rapidApplyCount===5&&console.warn("Detected rapid post processing modifications - this might be a bug",this)),this._lastApplyTime=Date.now()),this._isDirty=!1,this._activeEffects.length=0,(e=this.sharedProfile)!=null&&e.components){const s=this.sharedProfile.components;for(const a of s)a.active&&a.enabled&&!this._activeEffects.includes(a)&&this._activeEffects.push(a)}for(const s of this._effects)s.active&&s.enabled&&!this._activeEffects.includes(s)&&this._activeEffects.push(s);this._activeEffects.length>0?(this._postprocessing||(this._postprocessing=new Dy(this.context)),(i=this._postprocessing.apply(this._activeEffects))==null||i.then(()=>{this.activeAndEnabled&&(this._applyPostQueue(),this._postprocessing?(this.multisampling==="auto"?this._postprocessing.multisampling=exports.DeviceUtilities.isMobileDevice()?2:4:this._postprocessing.multisampling=Math.max(0,Math.min(this.multisampling,this.context.renderer.capabilities.maxSamples)),Ko&&console.debug(`[PostProcessing] Set multisampling to ${this._postprocessing.multisampling} (Is Mobile: ${exports.DeviceUtilities.isMobileDevice()})`)):Ko&&console.warn("[PostProcessing] No composer found"))})):(n=this._postprocessing)==null||n.unapply(!1)}_applyPostQueue(){if(this._modificationQueue){for(const e of this._modificationQueue.values())this.onEditorModification(e);this._modificationQueue.clear()}}onEditorModification(e){var i,n;if(e.propertyName.startsWith("postprocessing.")){if(!this._postprocessing)return this._modificationQueue||(this._modificationQueue=new Map),this._modificationQueue.set(e.propertyName,e),!0;if(!((i=this._activeEffects)!=null&&i.length))return;const s=e.propertyName.split(".");if(s.length===3||s.length===4){const a=s[1],l=s[2];for(const c of this._activeEffects)if(((n=c.typeName)==null?void 0:n.toLowerCase())===a.toLowerCase()){if(l==="active"){c.active=e.value,this.scheduleRecreate();return}if(!Pd.has(a)){const h=new Array;Pd.set(a,h);const u=Object.keys(c);for(const f of u)c[f]instanceof U&&h.push(f)}if(Pd.has(a)){const h=l.toLowerCase(),u=Pd.get(a);for(const f of u)if(f.toLowerCase()===h){const p=c[f];p instanceof U&&(s.length===4&&s[3]==="active"?(p.overrideState=e.value,this.scheduleRecreate()):p&&p.value!==void 0&&(p.value=e.value));return}}console.warn("Unknown modification",l);return}}return!0}return!1}scheduleRecreate(){const e=++this._recreateId;setTimeout(()=>{e===this._recreateId&&(this.onDisable(),this.onEnable())},200)}}yx([Br(_f)],bl.prototype,"sharedProfile");yx([Br()],bl.prototype,"multisampling");const Pd=new Map;Wk(bl);async function Iy(o){const{NeedleEngineWebComponent:t}=await Promise.resolve().then(()=>JE);t.observedAttributes.includes(o)||t.observedAttributes.push(o)}var PR=Object.defineProperty,pt=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&PR(t,e,n),n};const Mt=S("debugsceneswitcher"),MR=S("sceneswitcher:clearscene"),$d="scene";Iy($d);const Zs=Promise.resolve(!1);class He extends D{constructor(){super(...arguments);r(this,"autoLoadFirstScene",!0);r(this,"scenes",[]);r(this,"loadingScene");r(this,"queryParameterName","scene");r(this,"useSceneName",!0);r(this,"clamp",!0);r(this,"useHistory",!0);r(this,"useKeyboard",!0);r(this,"useSwipe",!0);r(this,"useSceneLighting",!0);r(this,"useSceneBackground",!0);r(this,"preloadNext",1);r(this,"preloadPrevious",1);r(this,"preloadConcurrent",2);r(this,"createMenuButtons",!1);r(this,"sceneLoadingStart",new ye);r(this,"sceneLoadingProgress",new ye);r(this,"sceneLoaded",new ye);r(this,"_currentIndex",-1);r(this,"_currentScene");r(this,"_engineElementOverserver");r(this,"_preloadScheduler");r(this,"_menuButtons");r(this,"onPopState",async e=>{if(!this.useHistory)return;const i=this.useHistory;try{this.useHistory=!1;let n=!1;if(this.queryParameterName&&(n=await this.tryLoadFromQueryParam()),!n){const s=e==null?void 0:e.state;if(s&&s.startsWith(this.guid)){const a=s.substr(this.guid.length+2);Mt&&console.log("PopState",a),await this.trySelectSceneFromValue(a)}}}finally{this.useHistory=i}});r(this,"normalizedSwipeThresholdX",.1);r(this,"_didSwipe",!1);r(this,"onInputPointerMove",e=>{if(this.useSwipe&&!this._didSwipe&&e.button===0&&e.pointerType==="touch"&&this.context.input.getPointerPressedCount()===1){const i=this.context.input.getPointerPositionDelta(e.button);if(i){const n=i.x/this.context.domWidth;n>=this.normalizedSwipeThresholdX?(this._didSwipe=!0,this.selectPrev()):n<=-this.normalizedSwipeThresholdX&&(this._didSwipe=!0,this.selectNext())}}});r(this,"onInputPointerUp",e=>{e.button===0&&(this._didSwipe=!1)});r(this,"onInputKeyDown",e=>{if(!this.useKeyboard||!this.scenes)return;const i=e.key.toLowerCase();if(!i)return;const n=parseInt(i)-1;if(n>=0){this.trySelectSceneFromValue(n);return}switch(i){case"arrowright":case"d":this.selectNext();break;case"arrowleft":case"a":this.selectPrev();break}});r(this,"__lastSwitchScene");r(this,"__lastSwitchScenePromise");r(this,"_currentlyLoadingScene");r(this,"_lastLoadingScene");r(this,"_loadingScenePromise");r(this,"_isCurrentlyLoading",!1);r(this,"_currentLoadingProgress")}get currentIndex(){return this._currentIndex}get currentLoadingProgress(){return this._currentLoadingProgress}get currentlyLoadingScene(){return this._currentlyLoadingScene}get currentlyLoadedScene(){return this._currentScene}awake(){this.scenes===void 0&&(this.scenes=[]);for(const e of this.scenes)e&&!e.hasUrl&&e.asset instanceof d.Object3D?C.remove(e.asset):e instanceof d.Object3D&&C.remove(e);Mt&&console.log("SceneSwitcher",this)}async onEnable(){if(globalThis.addEventListener("popstate",this.onPopState),this.context.input.addEventListener(Re.KeyDown,this.onInputKeyDown),this.context.input.addEventListener(Re.PointerMove,this.onInputPointerMove),this.context.input.addEventListener(Re.PointerUp,this.onInputPointerUp),this._engineElementOverserver||(this._engineElementOverserver=new MutationObserver(e=>{for(const i of e)if(i.type==="attributes"&&i.attributeName===$d){const n=this.context.domElement.getAttribute($d);n!==null&&this.trySelectSceneFromValue(n)}})),this._engineElementOverserver.observe(this.context.domElement,{attributes:!0}),this._preloadScheduler||(this._preloadScheduler=new OR(this)),this._preloadScheduler.maxLoadAhead=this.preloadNext,this._preloadScheduler.maxLoadBehind=this.preloadPrevious,this._preloadScheduler.maxConcurrent=this.preloadConcurrent,this._preloadScheduler.begin(2e3),this.autoLoadFirstScene&&this._currentIndex===-1&&!await this.tryLoadFromQueryParam()){const e=this.context.domElement.getAttribute($d);try{(e===null||!await this.trySelectSceneFromValue(e))&&this._currentIndex===-1&&this.select(0)}finally{}}this.createMenuButtons&&(this._menuButtons??(this._menuButtons=[]),this._menuButtons.push(this.context.menu.appendChild({label:"Previous",icon:"arrow_back_ios",onClick:()=>this.selectPrev(),priority:-1005,class:"row2"})),this._menuButtons.push(this.context.menu.appendChild({label:"Next",icon:"arrow_forward_ios",iconSide:"right",onClick:()=>this.selectNext(),priority:-1e3,class:"row2"})))}onDisable(){var e;if(globalThis.removeEventListener("popstate",this.onPopState),this.context.input.removeEventListener(Re.KeyDown,this.onInputKeyDown),this.context.input.removeEventListener(Re.PointerMove,this.onInputPointerMove),this.context.input.removeEventListener(Re.PointerUp,this.onInputPointerUp),(e=this._preloadScheduler)==null||e.stop(),this._menuButtons){for(const i of this._menuButtons)i.remove();this._menuButtons=void 0}}addScene(e){if(typeof e=="string"){let i=this.context.addressables.findAssetReference(e);return i||(i=new te(e),this.context.addressables.registerAssetReference(i)),this.scenes.push(i),i}return this.scenes.push(e),e}selectNext(){return this.select(this._currentIndex+1)}selectPrev(){return this.select(this._currentIndex-1)}select(e){var n,s,a;if(Mt&&console.log("select",e),typeof e=="object"&&console.warn('Switching to "'+e+'" might not work. Please either use an index or a AssetReference (not a scene reference)'),typeof e=="string"){const l=(n=this.scenes)==null?void 0:n.find(c=>c.url===e);if(!l){const c=te.getOrCreate(this.sourceId??"",e,this.context);return this.switchScene(c)}if(l)e=(s=this.scenes)==null?void 0:s.indexOf(l);else return Zs}if(!((a=this.scenes)!=null&&a.length))return Zs;if(e<0){if(this.clamp)return Zs;e=this.scenes.length-1}else if(e>=this.scenes.length){if(this.clamp)return Zs;e=0}const i=this.scenes[e];return this.switchScene(i)}unload(){return this.__lastSwitchScene=void 0,this.__lastSwitchScenePromise=void 0,this.__unloadCurrentScene()}async reload(){if(this.__lastSwitchScene){const e=this.__lastSwitchScene;return this.__lastSwitchScene=void 0,this.switchScene(e)}return!1}async switchScene(e){var n;if(!(e instanceof te)){const s=typeof e;if(s==="string")return this.select(e);if(s==="number")return this.select(e);if(e&&e instanceof d.Object3D){const a=(n=this.scenes)==null?void 0:n.indexOf(e);e=new te(e.name,void 0,e),a>=0&&(this.scenes[a]=e)}else return console.warn(`[SceneSwitcher] Can't switch to scene of type ${s}`),!1}return e.url===this.sourceId?(console.warn("[SceneSwitcher] Can't load own scene - prevent recursive loading",this.sourceId),!1):this.__lastSwitchScene===e&&this.__lastSwitchScenePromise?this.__lastSwitchScenePromise:(this.__lastSwitchScene=e,this.__lastSwitchScenePromise=this.__internalSwitchScene(e),await this.__lastSwitchScenePromise)}async __unloadCurrentScene(){const e=this._currentScene;if(this._currentScene=void 0,e){Mt&&console.log("UNLOAD",e.url,"HasURL?: "+e.hasUrl);const i=this.tryGetSceneEventListener(e.asset);if(i!=null&&i.sceneClosing){const n=i.sceneClosing();n instanceof Promise&&await n}e.hasUrl?e.unload():e.asset instanceof d.Object3D&&C.remove(e.asset)}}async __internalSwitchScene(e){var n,s,a,l,c;await this.__unloadCurrentScene();const i=this._currentIndex=((n=this.scenes)==null?void 0:n.indexOf(e))??-1;try{this._currentlyLoadingScene=e,this._currentLoadingProgress=new ProgressEvent("progress",{loaded:0,total:1});const h=new CustomEvent("loadscene-start",{detail:{scene:e,switcher:this,index:i}});this.dispatchEvent(h),(s=this.sceneLoadingStart)==null||s.invoke(h.detail),await this.onStartLoading(),await e.loadAssetAsync((f,p)=>{var g;if(Mt){const y=p.loaded/p.total,b="["+"=".repeat(Math.floor(y*20))+"-".repeat(20-Math.floor(y*20))+"]";console.debug(`[SceneSwitcher] Download ${(y*100).toFixed(1)} % ${b}`,e.url)}this._currentLoadingProgress=p,this.dispatchEvent(p),(g=this.sceneLoadingProgress)==null||g.invoke(p)}).catch(console.error),await this.onEndLoading();const u=new CustomEvent("loadscene-finished",{detail:{scene:e,switcher:this,index:i}});if(this.dispatchEvent(u),this._currentLoadingProgress=void 0,this._currentlyLoadingScene=void 0,u.defaultPrevented)return Mt&&console.warn("Adding loaded scene prevented:",e,u),!1;if(!e.asset)return Mt&&console.warn("Failed loading scene:",e),!1;if(this._currentIndex===i){if(Mt&&console.log("ADD",e.url),this._currentScene=e,MR){const g=((a=this.context.mainCameraComponent)==null?void 0:a.gameObject)||this.context.mainCamera;g==null||g.removeFromParent();const y=this.gameObject.removeFromParent();Ri(this.context.scene,!0,!0),this.context.scene=new d.Scene,this.context.scene.add(y),g&&this.context.scene.add(g)}if(C.add(e.asset,this.gameObject),this.useSceneLighting&&this.context.sceneLighting.enable(e),this.useSceneBackground){const g=this.context.lightmaps.tryGetSkybox(e.url);g?(g.mapping=d.EquirectangularReflectionMapping,this.context.scene.background=g):Mt&&console.warn("SceneSwitcher: Can't find skybox for scene "+e.url)}if(this.useHistory&&i>=0){let g=i.toString();if(this.useSceneName&&(e instanceof d.Object3D?g=e.name:e.url&&(g=zb(e.url))),(l=this.queryParameterName)!=null&&l.length)Mc(this.queryParameterName,g,this.useHistory);else{const y=history.state,b=this.guid+"::"+i;y!==b&&history.pushState(b,"unused",location.href)}}const f=this.tryGetSceneEventListener(e.asset);if(f!=null&&f.sceneOpened){const g=f.sceneOpened(this);g instanceof Promise&&await g}const p=new CustomEvent("scene-opened",{detail:{scene:e,switcher:this,index:i}});return this.dispatchEvent(p),(c=this.sceneLoaded)==null||c.invoke(this),!0}}catch(h){console.error(h)}return!1}preload(e){if(e>=0&&e<this.scenes.length){const i=this.scenes[e];if(i instanceof te)return i.preload()}return Zs}tryLoadFromQueryParam(){var i;if(!((i=this.queryParameterName)!=null&&i.length))return Zs;const e=S(this.queryParameterName);return typeof e=="boolean"?Zs:this.trySelectSceneFromValue(e)}trySelectSceneFromValue(e){if(typeof e=="string"){const i=parseInt(e);if(i>=0&&i<this.scenes.length)return this.select(i);{const n=e.toLowerCase();for(let s=0;s<this.scenes.length;s++){const a=this.scenes[s];if(!a)continue;if((a instanceof d.Object3D?a.name:zb(a.url)).toLowerCase().includes(n))return this.select(s)}}}else if(typeof e=="number"&&e>=0&&e<this.scenes.length)return this.select(e);return Yt()&&console.warn('Can not find scene: "'+e+'"',this),Zs}async onStartLoading(){var e,i;if(this._isCurrentlyLoading=!0,this.loadingScene&&(this._lastLoadingScene!==this.loadingScene&&(this._loadingScenePromise=void 0),this._lastLoadingScene=this.loadingScene,this._loadingScenePromise||(this._loadingScenePromise=(e=this.loadingScene)==null?void 0:e.loadAssetAsync().then(n=>n!=null)),await this._loadingScenePromise,this._isCurrentlyLoading&&((i=this.loadingScene)!=null&&i.asset))){Mt&&console.log("Add loading scene",this.loadingScene.url,this.loadingScene.asset);const n=this.loadingScene.asset;C.add(n,this.gameObject);const s=this.tryGetSceneEventListener(n);if(s!=null&&s.sceneOpened){const a=s.sceneOpened(this);a instanceof Promise&&await a}}if(this._isCurrentlyLoading){const n=this.tryGetSceneEventListener(this.gameObject);if(n&&n.sceneOpened){const s=n.sceneOpened(this);s instanceof Promise&&await s}}}async onEndLoading(){var e;if(this._isCurrentlyLoading=!1,(e=this.loadingScene)!=null&&e.asset){Mt&&console.log("Remove loading scene",this.loadingScene.url);const i=this.loadingScene.asset,n=this.tryGetSceneEventListener(i);if(typeof(n==null?void 0:n.sceneClosing)=="function"){const s=n.sceneClosing();s instanceof Promise&&await s}C.remove(i)}if(!this._isCurrentlyLoading){const i=this.tryGetSceneEventListener(this.gameObject);if(i&&i.sceneClosing){const n=i.sceneClosing();n instanceof Promise&&await n}}}tryGetSceneEventListener(e,i=0){if(!e)return null;const n=C.foreachComponent(e,s=>{const a=s;if(a.sceneClosing||a.sceneOpened)return a});if(i===0&&!n&&e.children.length)for(const s of e.children){const a=this.tryGetSceneEventListener(s,i+1);if(a)return a}return n||null}}pt([m()],He.prototype,"autoLoadFirstScene");pt([m(te)],He.prototype,"scenes");pt([m(te)],He.prototype,"loadingScene");pt([m()],He.prototype,"queryParameterName");pt([m()],He.prototype,"useSceneName");pt([m()],He.prototype,"clamp");pt([m()],He.prototype,"useHistory");pt([m()],He.prototype,"useKeyboard");pt([m()],He.prototype,"useSwipe");pt([m()],He.prototype,"useSceneLighting");pt([m()],He.prototype,"useSceneBackground");pt([m()],He.prototype,"preloadNext");pt([m()],He.prototype,"preloadPrevious");pt([m()],He.prototype,"preloadConcurrent");pt([m()],He.prototype,"createMenuButtons");pt([m(ye)],He.prototype,"sceneLoadingStart");pt([m(ye)],He.prototype,"sceneLoadingProgress");pt([m(ye)],He.prototype,"sceneLoaded");function zb(o){const t=o.split("/").pop(),e=t==null?void 0:t.split(".").shift();return e!=null&&e.length?e:o}class OR{constructor(t,e=1,i=1,n=2){r(this,"maxLoadAhead");r(this,"maxLoadBehind");r(this,"maxConcurrent");r(this,"_isRunning",!1);r(this,"_switcher");r(this,"_loadTasks",[]);r(this,"_maxConcurrentLoads",1);this._switcher=t,this.maxLoadAhead=e,this.maxLoadBehind=i,this.maxConcurrent=n}begin(t){if(this._isRunning)return;Mt&&console.log("Preload begin",{delay:t}),this._isRunning=!0;let e=-10,i,n;const s=this._switcher.scenes,a=Date.now()+t,l=setInterval(()=>{if(this.allLoaded()&&(Mt&&console.log("All scenes (pre-)loaded"),this.stop()),!this._isRunning){clearInterval(l);return}if(Date.now()<a||this.canLoadNewScene()===!1)return;(e===-10||e!==this._switcher.currentIndex)&&(e=this._switcher.currentIndex,n=0,i=0);const c=n%2===0;c&&(i+=1),n+=1;const h=c?this.maxLoadAhead:this.maxLoadBehind;if(i>h)return;const u=c?e+i:e-i;if(!(u<0)&&!(u<0||u>=s.length)&&!this._loadTasks.some(f=>f.index===u)){const f=s[u];Mt&&console.log("Preload scene",{roomIndex:u,searchForward:c,lastRoom:e,currentIndex:this._switcher.currentIndex,tasks:this._loadTasks.length},f==null?void 0:f.url),new kR(u,f,this._loadTasks)}},200)}stop(){this._isRunning=!1}canLoadNewScene(){return this._loadTasks.length<this._maxConcurrentLoads}allLoaded(){if(this._switcher.scenes){for(const t of this._switcher.scenes)if(t!=null&&t.isLoaded&&t.isLoaded()===!1)return!1}return!0}}class kR{constructor(t,e,i){r(this,"index");r(this,"asset");r(this,"tasks");this.index=t,this.asset=e,this.tasks=i,i.push(this),this.awaitLoading()}async awaitLoading(){this.asset&&!this.asset.isLoaded()&&(Mt&&console.log("Preload start: "+this.asset.url,this.index),await this.asset.preload(),Mt&&console.log("Preload finished: "+this.asset.url,this.index));const t=this.tasks.indexOf(this);t>=0&&this.tasks.splice(t,1)}}function RR(){return new Promise((o,t)=>{const i=()=>{i!=null&&(document.removeEventListener("pointerdown",i),document.removeEventListener("click",i),document.removeEventListener("dragstart",i),document.removeEventListener("touchstart",i),o())};document.addEventListener("pointerdown",i),document.addEventListener("click",i),document.addEventListener("dragstart",i),document.addEventListener("touchstart",i)})}async function ER(o){await RR(),o()}var TR=Object.defineProperty,AR=Object.getOwnPropertyDescriptor,Ii=(o,t,e,i)=>{for(var n=i>1?void 0:i?AR(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&TR(t,e,n),n};const ct=S("debugvideo");var _x=(o=>(o[o.None=0]="None",o[o.AdjustHeight=1]="AdjustHeight",o[o.AdjustWidth=2]="AdjustWidth",o))(_x||{}),bx=(o=>(o[o.VideoClip=0]="VideoClip",o[o.Url=1]="Url",o))(bx||{}),vx=(o=>(o[o.CameraFarPlane=0]="CameraFarPlane",o[o.CameraNearPlane=1]="CameraNearPlane",o[o.RenderTexture=2]="RenderTexture",o[o.MaterialOverride=3]="MaterialOverride",o))(vx||{});class rt extends D{constructor(){super();r(this,"playOnAwake",!0);r(this,"aspectMode",0);r(this,"clip",null);r(this,"source",1);r(this,"_url",null);r(this,"renderMode");r(this,"targetMaterialProperty");r(this,"targetMaterialRenderer");r(this,"targetTexture");r(this,"time",0);r(this,"_playbackSpeed",1);r(this,"_isLooping",!1);r(this,"_muted",!1);r(this,"_audioOutputMode",2);r(this,"playInBackground",!0);r(this,"_crossOrigin","anonymous");r(this,"_videoElement",null);r(this,"_videoTexture",null);r(this,"_videoMaterial",null);r(this,"_isPlaying",!1);r(this,"wasPlaying",!1);r(this,"visibilityChanged",e=>{switch(document.visibilityState){case"hidden":this.playInBackground||(this.wasPlaying=this._isPlaying,this.pause());break;case"visible":this.wasPlaying&&!this._isPlaying&&this.play();break}});r(this,"_receivedInput",!1);r(this,"_overlay",null);r(this,"_targetObjects");r(this,"_updateAspectRoutineId",-1);r(this,"_hls");r(this,"onHlsAvailable",()=>{var e;ct&&console.log("HLS: available",this.clip),!(!this.shouldUseM3U||!this.url)&&(this._hls||(this._hls=new Hls),this.videoElement.autoplay=!0,this._hls.loadSource(this.url),this._hls.attachMedia(this.videoElement),(e=this._videoElement)==null||e.play(),ct&&console.log("HLS: loaded",this.clip))});ER(()=>{this._receivedInput=!0,this.updateVideoElementSettings()}),this._targetObjects=[],S("videoscreenspace")&&window.addEventListener("keydown",e=>{e.key==="f"&&(this.screenspace=!this.screenspace)})}get url(){return this._url}set url(e){const n=this._url!==e;this.__didAwake?n&&this.setClipURL(e??""):this._url=e}get playbackSpeed(){var e;return((e=this._videoElement)==null?void 0:e.playbackRate)??this._playbackSpeed}set playbackSpeed(e){this._playbackSpeed=e,this._videoElement&&(this._videoElement.playbackRate=e)}get isLooping(){var e;return((e=this._videoElement)==null?void 0:e.loop)??this._isLooping}set isLooping(e){this._isLooping=e,this._videoElement&&(this._videoElement.loop=e)}get currentTime(){var e;return((e=this._videoElement)==null?void 0:e.currentTime)??this.time}set currentTime(e){this._videoElement?this._videoElement.currentTime=e:this.time=e}get isPlaying(){const e=this._videoElement;if(e){if(e.currentTime>0&&!e.paused&&!e.ended&&e.readyState>e.HAVE_CURRENT_DATA)return!0;if(e.srcObject&&e.srcObject.active)return!0}return!1}get crossOrigin(){var e;return((e=this._videoElement)==null?void 0:e.crossOrigin)??this._crossOrigin}set crossOrigin(e){this._crossOrigin=e,this._videoElement&&(e!==null?this._videoElement.setAttribute("crossorigin",e):this._videoElement.removeAttribute("crossorigin"))}get videoMaterial(){return!this._videoMaterial&&!this.create(!1)?null:this._videoMaterial}get videoTexture(){return!this._videoTexture&&!this.create(!1)?null:this._videoTexture}get videoElement(){return!this._videoElement&&!this.create(!1)?null:this._videoElement}requestPictureInPicture(){return this._videoElement?this._videoElement.requestPictureInPicture():null}get muted(){var e;return((e=this._videoElement)==null?void 0:e.muted)??this._muted}set muted(e){this._muted=e,this._videoElement&&(this._videoElement.muted=e)}get currentVideo(){return this.clip}set audioOutputMode(e){e!==this._audioOutputMode&&(e===1&&j()&&console.warn("VideoAudioOutputMode.AudioSource is not yet implemented"),this._audioOutputMode=e,this.updateVideoElementSettings())}get audioOutputMode(){return this._audioOutputMode}preloadVideo(){ct&&console.log("Video Preload: "+this.name,this.clip),this.create(!1)}preload(){this.preloadVideo()}setVideo(e){this.clip=e,this.source=0,this._videoElement?(this._videoElement.srcObject=e,this._isPlaying&&this.play(),this.updateAspect()):this.create(this.playOnAwake)}setClipURL(e){this._url!==e&&(this._url=e,this.source=1,ct&&console.log("set url",e),this._videoElement?e.endsWith(".m3u8")||e.includes(".m3u")?this.ensureM3UCanBePlayed():(this._videoElement.src=e,this._isPlaying&&(this.stop(),this.play())):this.create(this.playOnAwake))}onEnable(){var e,i;ct&&console.log("VideoPlayer.onEnable",bx[this.source],this.clip,this.url,this),window.addEventListener("visibilitychange",this.visibilityChanged),this.playOnAwake===!0?this.create(!0):this.preloadVideo(),this.screenspace?(e=this._overlay)==null||e.start():(i=this._overlay)==null||i.stop()}onDisable(){var e;window.removeEventListener("visibilitychange",this.visibilityChanged),(e=this._overlay)==null||e.stop(),this.pause()}onDestroy(){var e;this._videoElement&&((e=this.videoElement)==null||e.remove(),this._videoElement=null),this._videoTexture&&(this._videoTexture.dispose(),this._videoTexture=null)}play(){var e,i;if(this._videoElement||this.create(!1),!this._videoElement){ct&&console.warn("Can not play: no video element found",this);return}if(!(this._isPlaying&&!((e=this._videoElement)!=null&&e.ended)&&!((i=this._videoElement)!=null&&i.paused))){if(this._isPlaying=!0,this._receivedInput||(this._videoElement.muted=!0),this.handleBeginPlaying(!1),this.shouldUseM3U){this.ensureM3UCanBePlayed();return}ct&&console.log("Video Play()",this.clip,this._videoElement,this.time),this._videoElement.currentTime=this.time,this._videoElement.play().catch(n=>{var s;console.log(n),ct&&console.error("Error playing video",n,"CODE="+n.code,(s=this.videoElement)==null?void 0:s.src,this),setTimeout(()=>{this._isPlaying&&!this.destroyed&&this.activeAndEnabled&&this.play()},1e3)}),ct&&console.log("play",this._videoElement,this.time)}}stop(){this._isPlaying=!1,this.time=0,this._videoElement&&(this._videoElement.currentTime=0,this._videoElement.pause(),ct&&console.log("STOP",this))}pause(){var e,i;this.time=((e=this._videoElement)==null?void 0:e.currentTime)??0,this._isPlaying=!1,(i=this._videoElement)==null||i.pause(),ct&&console.log("PAUSE",this,this.currentTime)}create(e){let i;switch(this.source){case 0:i=this.clip;break;case 1:i=this.url,!(i!=null&&i.length)&&typeof this.clip=="string"&&(i=this.clip);break}return i?(this._videoElement||(ct&&console.warn("Create VideoElement",this),this._videoElement=this.createVideoElement(),this.context.domElement.shadowRoot.prepend(this._videoElement),this.updateVideoElementStyles()),typeof i=="string"?(ct&&console.log("Set Video src",i),this._videoElement.src=i):(ct&&console.log("Set Video srcObject",i),this._videoElement.srcObject=i),this._videoTexture||(this._videoTexture=new d.VideoTexture(this._videoElement)),this._videoTexture.flipY=!1,this._videoTexture.colorSpace=d.SRGBColorSpace,e&&this.handleBeginPlaying(e),ct&&console.log("Video: handle playing done...",i,e),!0):(ct&&console.warn("No video source set",this),!1)}updateAspect(){this.aspectMode!==0&&this.startCoroutine(this.updateAspectImpl())}get screenspace(){var e;return((e=this._overlay)==null?void 0:e.enabled)??!1}set screenspace(e){var i;if(e){if(!this._videoTexture)return;this._overlay||(this._overlay=new LR(this.context)),this._overlay.add(this._videoTexture)}else(i=this._overlay)==null||i.remove(this._videoTexture);this._overlay&&(this._overlay.enabled=e)}createVideoElement(){const e=document.createElement("video");return this._crossOrigin&&e.setAttribute("crossorigin",this._crossOrigin),ct&&console.log("created video element",e),e}handleBeginPlaying(e){var s,a;if(!this.activeAndEnabled||!this._videoElement)return;this._targetObjects.length=0;let i=this.gameObject;switch(this.renderMode){case 3:i=(s=this.targetMaterialRenderer)==null?void 0:s.gameObject,i||(i=(a=C.getComponent(this.gameObject,Ti))==null?void 0:a.gameObject);break;case 2:console.error("VideoPlayer renderTexture not implemented yet. Please use material override instead");return}if(!i){console.error("Missing target for video material renderer",this.name,vx[this.renderMode],this);return}const n=i.material;if(n){this._targetObjects.push(i),n!==this._videoMaterial&&(this._videoMaterial=n.clone(),i.material=this._videoMaterial);const l="map",c=this._videoMaterial;if(!this.targetMaterialProperty)c[l]=this._videoTexture;else switch(this.targetMaterialProperty){default:c[l]=this._videoTexture;break}}else{console.warn("Can not play video, no material found, this might be a multimaterial case which is not supported yet");return}this.updateVideoElementSettings(),this.updateVideoElementStyles(),e&&(this.shouldUseM3U&&this.ensureM3UCanBePlayed(),this.play())}updateVideoElementSettings(){if(!this._videoElement)return;this._videoElement.loop=this._isLooping,this._videoElement.currentTime=this.currentTime,this._videoElement.playbackRate=this._playbackSpeed,this._videoElement.playsInline=!0;let e=!this._receivedInput||this.audioOutputMode===0;!e&&this._muted&&(e=!0),this._videoElement.muted=e,this.playOnAwake&&(this._videoElement.autoplay=!0)}updateVideoElementStyles(){this._videoElement&&(this._videoElement.style.userSelect="none",this._videoElement.style.visibility="hidden",this._videoElement.style.display="none",this.updateAspect())}*updateAspectImpl(){const e=++this._updateAspectRoutineId,i=void 0,n=this.clip;for(;e===this._updateAspectRoutineId&&this.aspectMode!==0&&this.clip&&n===this.clip&&this._isPlaying;){if(!n||typeof n=="string")return;let s;for(const a of n.getVideoTracks()){const l=a.getSettings();if(l&&l.width&&l.height){s=l.width/l.height;break}else s=this.context.renderer.domElement.clientWidth/this.context.renderer.domElement.clientHeight}if(s===void 0){for(let a=0;a<10;a++)yield;if(!this.isPlaying)break;continue}if(i===s){yield;continue}for(const a of this._targetObjects){let l=1;if(a.parent){const c=Ue(a.parent);l=c.x/c.y}switch(this.aspectMode){case 1:a.scale.y=1/s*a.scale.x*l;break;case 2:a.scale.x=s*a.scale.y*l;break}}for(let a=0;a<3;a++)yield}}get shouldUseM3U(){return this.url!=null&&(this.url.endsWith(".m3u8")||this.url.endsWith(".m3u"))&&this.source===1}ensureM3UCanBePlayed(){if(!this.shouldUseM3U)return;let e=document.head.querySelector("script[data-hls_library]");e?globalThis.Hls?this.onHlsAvailable():e.addEventListener("load",this.onHlsAvailable):(ct&&console.log("HLS: load script"),e=document.createElement("script"),e.dataset.hls_library="hls.js",e.src="https://cdn.jsdelivr.net/npm/hls.js@1",e.addEventListener("load",this.onHlsAvailable),document.head.append(e))}}Ii([m()],rt.prototype,"playOnAwake",2);Ii([m()],rt.prototype,"aspectMode",2);Ii([m(URL)],rt.prototype,"clip",2);Ii([m()],rt.prototype,"source",2);Ii([m(URL)],rt.prototype,"url",1);Ii([m()],rt.prototype,"renderMode",2);Ii([m()],rt.prototype,"targetMaterialProperty",2);Ii([m(Ti)],rt.prototype,"targetMaterialRenderer",2);Ii([m(d.Texture)],rt.prototype,"targetTexture",2);Ii([m()],rt.prototype,"time",2);Ii([m()],rt.prototype,"playbackSpeed",1);Ii([m()],rt.prototype,"isLooping",1);Ii([m()],rt.prototype,"audioOutputMode",1);class LR{constructor(t){r(this,"context");r(this,"_videos",[]);r(this,"_screenspaceModeQuad");r(this,"_isInScreenspaceMode",!1);r(this,"_input");this.context=t,this._input=new DR(this)}get enabled(){return this._isInScreenspaceMode}set enabled(t){t?this.start():this.stop()}add(t){this._videos.indexOf(t)===-1&&this._videos.push(t)}remove(t){if(!t)return;const e=this._videos.indexOf(t);e>=0&&this._videos.splice(e,1)}start(){var n;if(this._isInScreenspaceMode||this._videos.length<0)return;const t=this._videos[this._videos.length-1];if(!t)return;if(this._isInScreenspaceMode=!0,!this._screenspaceModeQuad){if(this._screenspaceModeQuad=Do.createPrimitive(Or.Quad,{material:new IR(t)}),!this._screenspaceModeQuad)return;this._screenspaceModeQuad.geometry.scale(2,2,2)}const e=this._screenspaceModeQuad;this.context.scene.add(e),this.updateScreenspaceMaterialUniforms();const i=e.material;i==null||i.reset(),(n=this._input)==null||n.enable(i)}stop(){var t;this._isInScreenspaceMode=!1,this._screenspaceModeQuad&&((t=this._input)==null||t.disable(),this._screenspaceModeQuad.removeFromParent())}updateScreenspaceMaterialUniforms(){var e;const t=(e=this._screenspaceModeQuad)==null?void 0:e.material;t&&(t.screenAspect=this.context.domElement.clientWidth/this.context.domElement.clientHeight)}}class DR{constructor(t){r(this,"_onResizeScreenFn");r(this,"_onKeyUpFn");r(this,"_onMouseWheelFn");r(this,"context");r(this,"overlay");r(this,"_material");r(this,"_isPinching",!1);r(this,"_lastPinch",0);this.overlay=t,this.context=t.context}enable(t){this._material=t,window.addEventListener("resize",this._onResizeScreenFn=()=>{this.overlay.updateScreenspaceMaterialUniforms()}),window.addEventListener("keyup",this._onKeyUpFn=n=>{n.key==="Escape"&&this.overlay.stop()}),window.addEventListener("wheel",this._onMouseWheelFn=n=>{this.overlay.enabled&&(t.zoom+=n.deltaY*5e-4,n.preventDefault())},{passive:!1});const e=new d.Vector2;window.addEventListener("mousemove",n=>{if(this.overlay.enabled&&this.context.input.getPointerPressed(0)){const s=new d.Vector2(n.movementX,n.movementY);s.x/=this.context.domElement.clientWidth,s.y/=this.context.domElement.clientHeight,e.set(s.x,s.y),e.multiplyScalar(t.zoom/-this.context.time.deltaTime*.01),t.offset=t.offset.add(e)}}),window.addEventListener("pointermove",n=>{this.overlay.enabled&&this.context.input.getPointerPressed(0)&&this.context.input.getTouchesPressedCount()===1&&(e.set(n.movementX,n.movementY),e.multiplyScalar(t.zoom*-this.context.time.deltaTime*.05),t.offset=t.offset.add(e))});let i=0;window.addEventListener("touchstart",n=>{if(n.touches.length<2){this.context.time.time-i<.3&&this.overlay.stop(),i=this.context.time.time;return}this._isPinching=!0,this._lastPinch=0}),window.addEventListener("touchmove",n=>{if(!this._isPinching||!this._material)return;const s=n.touches[0],a=n.touches[1],l=s.clientX-a.clientX,c=s.clientY-a.clientY,h=Math.sqrt(l*l+c*c);if(this._lastPinch!==0){const u=h-this._lastPinch;this._material.zoom-=u*.004}this._lastPinch=h}),window.addEventListener("touchend",()=>{this._isPinching=!1})}disable(){this._onResizeScreenFn&&(window.removeEventListener("resize",this._onResizeScreenFn),this._onResizeScreenFn=void 0),this._onKeyUpFn&&(window.removeEventListener("keyup",this._onKeyUpFn),this._onKeyUpFn=void 0),this._onMouseWheelFn&&(window.removeEventListener("wheel",this._onMouseWheelFn),this._onMouseWheelFn=void 0)}}class IR extends d.ShaderMaterial{constructor(e){super();r(this,"_offset",new d.Vector2);this.uniforms={map:{value:e},screenAspect:{value:1},offsetScale:{value:new d.Vector4(0,0,1,1)}},this.vertexShader=`
1323
1325
  uniform sampler2D map;
1324
1326
  uniform float screenAspect;
1325
1327
  uniform vec4 offsetScale;
@@ -1383,7 +1385,7 @@ axisFormat %s
1383
1385
  // be blended onto the scene.
1384
1386
  gl_FragColor = vec4(direct, max);
1385
1387
  return;
1386
- `)},e.userData.isLightBlendMaterial=!0}applyShadowMaterial(){if(this.targetMesh)if(this.targetMesh.material.type!=="ShadowMaterial"){const e=new d.ShadowMaterial;e.color=this.shadowColor,e.opacity=this.shadowColor.alpha,this.applyMaterialOptions(e),this.targetMesh.material=e,e.userData.isShadowCatcherMaterial=!0}else{const e=this.targetMesh.material;e.color=this.shadowColor,e.opacity=this.shadowColor.alpha,this.applyMaterialOptions(e),e.userData.isShadowCatcherMaterial=!0}}applyOccluderMaterial(){if(this.targetMesh){let e=this.targetMesh.material;if(!e){const i=new d.MeshBasicMaterial;this.targetMesh.material=i,e=i}e.depthWrite=!0,e.stencilWrite=!0,e.colorWrite=!1,this.gameObject.renderOrder=-100}}applyMaterialOptions(e){e&&(e.depthWrite=!1,e.stencilWrite=!1)}}xx([m()],Uh.prototype,"mode");xx([m(ie)],Uh.prototype,"shadowColor");var UR=Object.defineProperty,zh=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&UR(t,e,n),n};const Ot=S("debugskybox");Iy("skybox-image");Iy("environment-image");function Nb(o,t,e,i,n){const s=new xf;s.allowDrop=!1,s.allowNetworking=!1,s.background=e,s.environment=i,C.addComponent(o.scene,s);const a=l=>{typeof l=="string"&&(Ot&&console.log(n,"CHANGED TO",l),s.setSkybox(l))};return h0(o.domElement,n,a),s.addEventListener("destroy",()=>{Ot&&console.log("Destroyed attribute remote skybox",n),d0(o.domElement,n,a)}),s.setSkybox(t)}const xu=new Array;re.registerCallback(he.ContextCreationStart,o=>{var n;const t=o.context,e=t.domElement.getAttribute("skybox-image")||t.domElement.getAttribute("background-image"),i=t.domElement.getAttribute("environment-image");if(e){Ot&&console.log("Creating remote skybox to load "+e),((n=t.mainCameraComponent)==null?void 0:n.clearFlags)!==Co.Skybox&&console.warn('"skybox-image"/"background-image" attribute has no effect: camera clearflags are not set to "Skybox"');const s=Nb(t,e,!0,!1,"skybox-image");xu.push(s)}if(i){Ot&&console.log("Creating remote environment to load "+i);const s=Nb(t,i,!1,!0,"environment-image");xu.push(s)}});re.registerCallback(he.ContextCreationStart,()=>Promise.all(xu).finally(()=>{xu.length=0}));function Sx(){return globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES||(globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES=new Array),globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES}function Vb(o){const e=Sx().find(i=>i.src===o);return e?(Ot&&console.log("Skybox: Found previously loaded texture for "+o),e.texture):null}async function zR(o){const t=await o;ug(t,!0),Se(t)}function NR(o,t){const e=Sx();for(;e.length>5;){const i=e.shift();i&&zR(i.texture)}t.then(i=>ug(i,!1)),e.push({src:o,texture:t})}const Lr=class extends D{constructor(){super(...arguments);r(this,"url");r(this,"allowDrop",!0);r(this,"background",!0);r(this,"environment",!0);r(this,"allowNetworking",!0);r(this,"_loader");r(this,"_prevUrl");r(this,"_prevLoadedEnvironment");r(this,"_prevEnvironment",null);r(this,"_prevBackground",null);r(this,"validTextureTypes",[".ktx2",".hdr",".exr",".jpg",".jpeg",".png"]);r(this,"onDragOverEvent",e=>{if(this.allowDrop&&e.dataTransfer)for(const i of e.dataTransfer.types)(i==="text/uri-list"||i==="Files")&&e.preventDefault()});r(this,"onDrop",e=>{var i,n,s,a;if(this.allowDrop&&e.dataTransfer){for(const l of e.dataTransfer.types)if(Ot&&console.log(l),l==="text/uri-list"){const c=e.dataTransfer.getData(l);Ot&&console.log(l,c);let h=(n=(i=new RegExp(/polyhaven.com\/asset_img\/.+?\/(?<name>.+)\.png/).exec(c))==null?void 0:i.groups)==null?void 0:n.name;if(h||(h=(a=(s=new RegExp(/polyhaven\.com\/a\/(?<name>.+)/).exec(c))==null?void 0:s.groups)==null?void 0:a.name),Ot&&console.log(h),h){const u="https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/"+h+"_1k.exr";console.log(`[Remote Skybox] Setting skybox from url: ${u}`),e.preventDefault(),this.setSkybox(u);break}else if(this.isValidTextureType(c)){console.log("[Remote Skybox] Setting skybox from url: "+c),e.preventDefault(),this.setSkybox(c);break}else{console.warn(`[RemoteSkybox] Unknown url ${c}. If you want to load a skybox from a url, make sure it is a valid image url. Url must end with${this.validTextureTypes.join(", ")}.`);const u=new CustomEvent("dropped-unknown-url",{detail:{sender:this,event:e,url:c,apply:f=>{e.preventDefault(),this.setSkybox(f)}}});this.dispatchEvent(u)}}else if(l=="Files"){const c=e.dataTransfer.files.item(0);if(Ot&&console.log(l,c),!c)continue;if(!this.isValidTextureType(c.name)){console.warn(`[RemoteSkybox]: File "${c.name}" is not supported. Supported files are ${this.validTextureTypes.join(", ")}`);return}if(Vb(c.name)===null){const h=new Blob([c]),u=URL.createObjectURL(h);e.preventDefault(),this.setSkybox(u,c.name)}else e.preventDefault(),this.setSkybox(c.name);break}}})}onEnable(){this.setSkybox(this.url),this.registerDropEvents()}onDisable(){var e;this.context.scene.environment===this._prevLoadedEnvironment&&(this.context.scene.environment=this._prevEnvironment,ri.backgroundShouldBeTransparent(this.context)||(this.context.scene.background=this._prevBackground),this._prevLoadedEnvironment=void 0),this.unregisterDropEvents(),(e=this.context.mainCameraComponent)==null||e.applyClearFlags()}urlChangedSyncField(){this.allowNetworking&&this.url&&(this.isRemoteTexture(this.url)?this.setSkybox(this.url):Ot&&console.warn(`RemoteSkybox: Not setting skybox: ${this.url} is not a remote texture. If you want to set a local texture, set allowNetworking to false.`))}async setSkybox(e,i){var a;if(!this.activeAndEnabled||(e=VR(e,this.environment,this.background),!e))return!1;if(i??(i=e),this.isValidTextureType(i)||console.warn("Potentially invalid skybox url",i,"on",this.name),Ot&&console.log("Set remote skybox url: "+e),this._prevUrl===e&&this._prevLoadedEnvironment)return this.apply(),!0;(a=this._prevLoadedEnvironment)==null||a.dispose(),this._prevLoadedEnvironment=void 0,this._prevUrl=e;const n=await this.loadTexture(e,i);if(!n)return Ot&&console.warn("RemoteSkybox: Failed to load texture from url",e),!1;if(!this.enabled)return Ot&&console.warn("RemoteSkybox: Component is not enabled, aborting setSkybox"),!1;if(this._prevUrl!==e)return Ot&&console.warn("RemoteSkybox: URL changed while loading texture, aborting setSkybox"),!1;this.url=e;const s=e.lastIndexOf("/");return n.name=e.substring(s>=0?s+1:0),this._loader instanceof d.TextureLoader&&(n.colorSpace=d.SRGBColorSpace),this._prevLoadedEnvironment=n,this.apply(),!0}async loadTexture(e,i){var u,f,p,g,y;if(!e)return Promise.resolve(null);i??(i=e);const n=Vb(i);if(n){const b=await n;if(((f=(u=b.source)==null?void 0:u.data)==null?void 0:f.length)>0||(y=(g=(p=b.source)==null?void 0:p.data)==null?void 0:g.data)!=null&&y.length)return b}const s=i.endsWith(".exr"),a=i.endsWith(".hdr"),l=i.endsWith(".ktx2");if(s)this._loader instanceof G.EXRLoader||(this._loader=new G.EXRLoader);else if(a)this._loader instanceof G.RGBELoader||(this._loader=new G.RGBELoader);else if(l){if(!(this._loader instanceof G.KTX2Loader)){const{ktx2Loader:b}=le.createLoaders(this.context.renderer);this._loader=b}}else this._loader instanceof d.TextureLoader||(this._loader=new d.TextureLoader);Ot&&console.log("Loading skybox: "+e);const c=this._loader.loadAsync(e);return NR(i,c),await c}apply(){var i;const e=this._prevLoadedEnvironment;e&&(e instanceof d.CubeTexture||e instanceof d.CompressedCubeTexture||(e.mapping=d.EquirectangularRefractionMapping,e.needsUpdate=!0),this.context.scene.background!==e&&(this._prevBackground=this.context.scene.background),this.context.scene.environment!==e&&(this._prevEnvironment=this.context.scene.environment),Ot&&console.log("Set remote skybox",this.url,!ri.backgroundShouldBeTransparent(this.context)),this.environment&&(this.context.scene.environment=e),this.background&&!ri.backgroundShouldBeTransparent(this.context)&&(this.context.scene.background=e),((i=this.context.mainCameraComponent)==null?void 0:i.backgroundBlurriness)!==void 0&&(this.context.scene.backgroundBlurriness=this.context.mainCameraComponent.backgroundBlurriness))}isRemoteTexture(e){return e.startsWith("http://")||e.startsWith("https://")}isValidTextureType(e){for(const i of this.validTextureTypes)if(e.endsWith(i))return!0;return!1}registerDropEvents(){this.unregisterDropEvents(),this.context.domElement.addEventListener("dragover",this.onDragOverEvent),this.context.domElement.addEventListener("drop",this.onDrop)}unregisterDropEvents(){this.context.domElement.removeEventListener("dragover",this.onDragOverEvent),this.context.domElement.removeEventListener("drop",this.onDrop)}};zh([ly(Lr.prototype.urlChangedSyncField),m(URL)],Lr.prototype,"url");zh([m()],Lr.prototype,"allowDrop");zh([m()],Lr.prototype,"background");zh([m()],Lr.prototype,"environment");zh([m()],Lr.prototype,"allowNetworking");let xf=Lr;function VR(o,t,e){const i=t&&!e;switch(o==null?void 0:o.toLowerCase()){case"studio":return i?"https://cdn.needle.tools/static/skybox/modelviewer-Neutral-small.hdr":"https://cdn.needle.tools/static/skybox/modelviewer-Neutral.hdr";case"blurred-skybox":return i?"https://cdn.needle.tools/static/skybox/blurred-skybox-small.exr":"https://cdn.needle.tools/static/skybox/blurred-skybox.exr";case"quicklook-ar":return i?"https://cdn.needle.tools/static/skybox/QuickLook-ARMode-small.exr":"https://cdn.needle.tools/static/skybox/QuickLook-ARMode.exr";case"quicklook":return i?"https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode-small.exr":"https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode.exr"}return o===void 0?null:o}var $R=Object.defineProperty,Sf=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&$R(t,e,n),n},fr;const Nh=(fr=class extends D{constructor(){super(...arguments);r(this,"target",null);r(this,"followFactor",.1);r(this,"rotateFactor",.1);r(this,"positionAxes",wa.All);r(this,"flipForward",!1);r(this,"_firstUpdate",!0)}onBeforeRender(){this.updateNow(!1)}updateNow(e){if(!(!this.target||this.target===this.gameObject)){if(this.followFactor>0){const i=Q(this.target),n=this._firstUpdate||e?1:z.clamp01(this.context.time.deltaTime*this.followFactor),s=this.worldPosition;this.positionAxes&wa.X&&(s.x=z.lerp(s.x,i.x,n)),this.positionAxes&wa.Y&&(s.y=z.lerp(s.y,i.y,n)),this.positionAxes&wa.Z&&(s.z=z.lerp(s.z,i.z,n)),this.worldPosition=s}if(this.rotateFactor>0){const i=_e(this.target);this.flipForward&&i.premultiply(fr._invertForward);const n=this._firstUpdate||e?1:z.clamp01(this.context.time.deltaTime*this.rotateFactor);this.worldQuaternion=this.worldQuaternion.slerp(i,n)}this._firstUpdate=!1}}},r(fr,"_invertForward",new d.Quaternion().setFromAxisAngle(new d.Vector3(0,1,0),Math.PI)),fr);Sf([m(d.Object3D)],Nh.prototype,"target");Sf([m()],Nh.prototype,"followFactor");Sf([m()],Nh.prototype,"rotateFactor");Sf([m()],Nh.prototype,"positionAxes");let Cf=Nh;var WR=Object.defineProperty,Vh=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&WR(t,e,n),n};const yc=S("debugspatialtrigger"),$b=new d.Layers,Wb=new d.Layers;function HR(o,t){return $b.mask=o,Wb.mask=t,$b.test(Wb)}class Zn extends D{constructor(){super(...arguments);r(this,"triggerMask",0);r(this,"onEnter");r(this,"onStay");r(this,"onExit");r(this,"currentIntersected",[]);r(this,"lastIntersected",[])}start(){yc&&console.log(this.name,this.triggerMask,this)}update(){this.currentIntersected.length=0;for(const e of Pf.triggers)HR(e.triggerMask,this.triggerMask)&&e.test(this.gameObject)&&this.currentIntersected.push(e);for(let e=this.lastIntersected.length-1;e>=0;e--){const i=this.lastIntersected[e];this.currentIntersected.indexOf(i)<0&&(this.onExitTrigger(i),this.lastIntersected.splice(e,1))}for(const e of this.currentIntersected)this.lastIntersected.indexOf(e)<0&&this.onEnterTrigger(e),this.onStayTrigger(e);this.lastIntersected.length=0,this.lastIntersected.push(...this.currentIntersected)}onEnterTrigger(e){var i;yc&&console.log("ENTER TRIGGER",this.name,e.name,this,e),e.raiseOnEnterEvent(this),(i=this.onEnter)==null||i.invoke()}onExitTrigger(e){var i;yc&&console.log("EXIT TRIGGER",this.name,e.name),e.raiseOnExitEvent(this),(i=this.onExit)==null||i.invoke()}onStayTrigger(e){var i;e.raiseOnStayEvent(this),(i=this.onStay)==null||i.invoke()}}Vh([m()],Zn.prototype,"triggerMask");Vh([m(ye)],Zn.prototype,"onEnter");Vh([m(ye)],Zn.prototype,"onStay");Vh([m(ye)],Zn.prototype,"onExit");var ks;const Cx=(ks=class extends D{constructor(){super(...arguments);r(this,"triggerMask");r(this,"boxHelper")}start(){yc&&console.log(this.name,this.triggerMask,this)}onEnable(){var e;ks.triggers.push(this),this.boxHelper||(this.boxHelper=C.addComponent(this.gameObject,ts),(e=this.boxHelper)==null||e.showHelper(null,yc))}onDisable(){ks.triggers.splice(ks.triggers.indexOf(this),1)}test(e){return this.boxHelper?this.boxHelper.isInBox(e)??!1:!1}raiseOnEnterEvent(e){C.foreachComponent(this.gameObject,i=>{i!==e&&i instanceof Zn&&i.onEnterTrigger(this)},!1)}raiseOnStayEvent(e){C.foreachComponent(this.gameObject,i=>{i!==e&&i instanceof Zn&&i.onStayTrigger(this)},!1)}raiseOnExitEvent(e){C.foreachComponent(this.gameObject,i=>{i!==e&&i instanceof Zn&&i.onExitTrigger(this)},!1)}},r(ks,"triggers",[]),ks);Vh([m()],Cx.prototype,"triggerMask");let Pf=Cx;var GR=Object.defineProperty,qR=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&GR(t,e,n),n};const Pi=S("debugspectator");class Mf extends D{constructor(){super(...arguments);r(this,"cam",null);r(this,"useKeys",!0);r(this,"_mode",0);r(this,"orbit",null);r(this,"_handler");r(this,"eventSub_WebXRRequestStartEvent",null);r(this,"eventSub_WebXRStartEvent",null);r(this,"eventSub_WebXREndEvent",null);r(this,"_debug");r(this,"_networking")}get mode(){return this._mode}set mode(e){this._mode=e}get isSpectating(){var e;return((e=this._handler)==null?void 0:e.currentTarget)!==void 0}isSpectatingUser(e){var i;return((i=this.target)==null?void 0:i.userId)===e}isFollowedBy(e){var i;return(i=this.followers)==null?void 0:i.includes(e)}get followers(){return this._networking.followers}stopSpectating(){if(this.context.isInXR){this.followSelf();return}this.target=void 0}get localId(){return this.context.connection.connectionId??"local"}set target(e){var i;if(this._handler){const n=(i=this._handler.currentTarget)==null?void 0:i.userId,s=this.context.players.getPlayerView(this.localId);e===void 0||this.context.isInXR===!1&&(s==null?void 0:s.currentObject)===e.currentObject?this._handler.currentTarget!==void 0&&(this._handler.disable(),C.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),this._networking.onSpectatedObjectChanged(e,n)):this._handler.currentTarget!==e&&(this._handler.set(e),C.setActive(this.gameObject,!0),this.orbit&&(this.orbit.enabled=!1),this._networking.onSpectatedObjectChanged(e,n))}}get target(){var e;return(e=this._handler)==null?void 0:e.currentTarget}requestAllFollowMe(){this._networking.onRequestFollowMe()}get isSpectatingSelf(){var e,i;return this.isSpectating&&((e=this.target)==null?void 0:e.currentObject)===((i=this.context.players.getPlayerView(this.localId))==null?void 0:i.currentObject)}awake(){if(this._debug=new YR(this.context,this),this._networking=new JR(this.context,this),this._networking.awake(),C.setActive(this.gameObject,!1),this.cam=C.getComponent(this.gameObject,ri),!this.cam){console.warn("SpectatorCamera: Spectator camera needs camera component on the same object.",this);return}!this._handler&&this.cam&&(this._handler=new XR(this.context,this.cam,this)),this.orbit=C.getComponent(this.context.mainCamera,ge)}onDestroy(){var e,i;this.stopSpectating(),(e=this._handler)==null||e.destroy(),(i=this._networking)==null||i.destroy()}isSupportedPlatform(){const e=window.navigator.userAgent,i=/Windows|MacOS/.test(e),n=/Windows NT/.test(e)&&/Edg/.test(e)&&!/Win64/.test(e);return i&&!n}onBeforeXR(e){this.isSupportedPlatform()&&C.setActive(this.gameObject,!0)}onEnterXR(e){this.isSupportedPlatform()&&(Pi&&console.log(this.context.mainCamera),this.context.mainCamera&&this.followSelf())}onLeaveXR(e){var i,n;this.context.removeCamera(this.cam),C.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),(i=this._handler)==null||i.set(void 0),(n=this._handler)==null||n.disable(),this.isSpectatingSelf&&this.stopSpectating()}followSelf(){this.target=this.context.players.getPlayerView(this.context.connection.connectionId),this.target||(this.context.players.setPlayerView(this.localId,this.context.mainCamera,wo.Headset),this.target=this.context.players.getPlayerView(this.localId)),Pi&&console.log("Follow self",this.target)}onAfterRender(){var u,f,p;if(!this.cam)return;const e=this.context.renderer,i=e.xr.enabled;if(!e.xr.isPresenting&&!((u=this._handler)!=null&&u.currentTarget))return;(f=this._handler)==null||f.update(this._mode);const n=e.getRenderTarget();let s=null;const a=e.state;if(!n){if(!e.state.bindFramebuffer||!a.bindXRFramebuffer)return;s=e._framebuffer,a.bindXRFramebuffer(null)}this.setAvatarFlagsBeforeRender();const l=this.context.mainCameraComponent;if(l){const g=l.backgroundColor;g&&e.setClearColor(g,g.alpha),this.cam.backgroundColor=g,this.cam.clearFlags=l.clearFlags,this.cam.nearClipPlane=l.nearClipPlane,this.cam.farClipPlane=l.farClipPlane}else e.setClearColor(new d.Color(1,1,1));e.setRenderTarget(null),e.xr.enabled=!1;const c=(p=this.cam)==null?void 0:p.threeCamera;this.context.updateAspect(c);const h=e.xr.isPresenting;e.xr.isPresenting=!1,e.setSize(this.context.domWidth,this.context.domHeight),e.render(this.context.scene,c),e.xr.isPresenting=h,e.xr.enabled=i,n?e.setRenderTarget(n):a.bindXRFramebuffer&&a.bindXRFramebuffer(s),this.resetAvatarFlags()}setAvatarFlagsBeforeRender(){const e=this._mode===0;for(const i of At.instances)if(i.avatar&&"isLocalAvatar"in i.avatar&&"flags"in i.avatar){let n=Bn.All;this.isSpectatingSelf&&(n=e&&i.avatar.isLocalAvatar?Bn.FirstPerson:Bn.ThirdPerson);const s=i.avatar.flags;if(!s)continue;for(const a of s)a.UpdateVisible(n)}}resetAvatarFlags(){var e;for(const i of At.instances)if(i.avatar&&"flags"in i.avatar){const n=i.avatar.flags;if(!n)continue;for(const s of n)"isLocalAvatar"in i.avatar&&((e=i.avatar)!=null&&e.isLocalAvatar)?s.UpdateVisible(Bn.FirstPerson):s.UpdateVisible(Bn.ThirdPerson)}}}qR([m()],Mf.prototype,"useKeys");class XR{constructor(t,e,i){r(this,"context");r(this,"cam");r(this,"spectator");r(this,"follow");r(this,"target");r(this,"view");r(this,"currentObject");this.context=t,this.cam=e,this.spectator=i}get currentTarget(){return this.view}set(t){const e=t==null?void 0:t.currentObject;if(!e){this.spectator.stopSpectating();return}e!==this.currentObject&&(this.currentObject=e,this.view=t,this.follow||(this.follow=C.addComponent(this.cam.gameObject,Cf)),this.target||(this.target=new d.Object3D),e.add(this.target),this.follow.enabled=!0,this.follow.target=this.target,Pi&&console.log("FOLLOW",e),this.context.isInXR?this.context.removeCamera(this.cam):this.context.setCurrentCamera(this.cam))}disable(){Pi&&console.log("STOP FOLLOW",this.currentObject),this.view=void 0,this.currentObject=void 0,this.context.removeCamera(this.cam),this.follow&&(this.follow.enabled=!1)}destroy(){var t;(t=this.target)==null||t.removeFromParent(),this.follow&&C.destroy(this.follow)}update(t){var n,s,a,l,c,h;if(((n=this.currentTarget)==null?void 0:n.isConnected)===!1||((s=this.currentTarget)==null?void 0:s.removed)===!0){Pi&&console.log("Target disconnected or timeout",this.currentTarget),this.spectator.stopSpectating();return}this.currentTarget&&((a=this.currentTarget)==null?void 0:a.currentObject)!==this.currentObject&&(Pi&&console.log("Target changed",this.currentObject,"to",this.currentTarget.currentObject),this.set(this.currentTarget));const e=this.context.mainCamera;if(e){const u=this.cam.threeCamera;(u.near!==e.near||u.far!==e.far)&&(u.near=e.near,u.far=e.far,u.updateProjectionMatrix())}const i=(l=this.follow)==null?void 0:l.target;if(!(!i||!this.follow)){switch(t){case 0:((c=this.view)==null?void 0:c.viewDevice)!==wo.Browser?(this.follow.followFactor=5,this.follow.rotateFactor=5):(this.follow.followFactor=50,this.follow.rotateFactor=50),i.position.set(0,0,0);break;case 1:this.follow.followFactor=3,this.follow.rotateFactor=2,i.position.set(0,.5,1.5);break}this.follow.flipForward=!1,((h=this.view)==null?void 0:h.viewDevice)!==wo.Browser?i.quaternion.copy(QR):i.quaternion.identity()}}}const QR=new d.Quaternion().setFromAxisAngle(new d.Vector3(0,1,0),Math.PI);class YR{constructor(t,e){r(this,"context");r(this,"spectator");this.context=t,this.spectator=e,console.log("[Spectator Camera] Click other avatars or cameras to follow them. Press ESC to exit spectator mode."),this.context.domElement.addEventListener("keydown",n=>{if(!this.spectator.useKeys)return;n.key==="Escape"&&this.spectator.stopSpectating()});let i=0;this.context.input.addEventListener(Re.PointerDown,n=>{i=this.context.time.time}),this.context.input.addEventListener(Re.PointerUp,n=>{const s=this.context.time.time-i;s>1?this.spectator.stopSpectating():this.context.input.getPointerClicked(0)&&s<.3&&this.trySelectObject()})}trySelectObject(){const t=new Jn;t.setMask(16777215);const e=this.context.physics.raycast(t);if(Pi&&console.log(...e),e!=null&&e.length)for(const i of e){if(i.distance<.2)continue;const n=i.object,s=C.getComponentInParent(n,At),a=s==null?void 0:s.connectionId;if(a){const l=this.context.players.getPlayerView(a);this.spectator.target=l,Pi&&console.log("spectate",a,s);break}}}}class KR{constructor(t,e,i){r(this,"guid");r(this,"dontSave",!0);r(this,"targetUserId");r(this,"stoppedFollowing");this.guid=t,this.targetUserId=e,this.stoppedFollowing=i}}class ZR{constructor(t,e){r(this,"guid");r(this,"userId");this.guid=t.guid,this.userId=e}}class JR{constructor(t,e){r(this,"followers",[]);r(this,"context");r(this,"spectator");r(this,"_followerEventMethod");r(this,"_requestFollowMethod");r(this,"_joinedRoomMethod");r(this,"_lastRequestFollowUser");r(this,"_enforceFollowInterval");this.context=t,this.spectator=e,this._followerEventMethod=this.onFollowerEvent.bind(this),this._requestFollowMethod=this.onRequestFollowEvent.bind(this),this._joinedRoomMethod=this.onUserJoinedRoom.bind(this)}awake(){this.context.connection.beginListen("spectator-follower-changed",this._followerEventMethod),this.context.connection.beginListen("spectator-request-follow",this._requestFollowMethod),this.context.connection.beginListen(ee.JoinedRoom,this._joinedRoomMethod),this.context.domElement.addEventListener("keydown",t=>{this.spectator.useKeys&&(t.key==="f"?this.onRequestFollowMe():t.key==="Escape"&&this.onRequestFollowMe(!0))})}destroy(){this.context.connection.stopListen("spectator-follower-changed",this._followerEventMethod),this.context.connection.stopListen("spectator-request-follow",this._requestFollowMethod),this.context.connection.stopListen(ee.JoinedRoom,this._joinedRoomMethod)}onSpectatedObjectChanged(t,e){if(Pi&&console.log(this.context.connection.connectionId,"onSpectatedObjectChanged",t,e),this.context.connection.connectionId){const i=(t==null?void 0:t.userId)===void 0,n=i?e:t==null?void 0:t.userId,s=new KR(this.context.connection.connectionId,n,i);this.context.connection.send("spectator-follower-changed",s)}}onRequestFollowMe(t=!1){if(Pi&&console.log("Request follow",this.context.connection.connectionId),this.context.connection.connectionId){this.spectator.stopSpectating();const e=t?void 0:this.context.connection.connectionId,i=new ZR(this.spectator,e);this.context.connection.send("spectator-request-follow",i)}}onUserJoinedRoom(){S("followme")&&this.onRequestFollowMe()}onFollowerEvent(t){const e=t.targetUserId,i=t.guid;if(Pi&&console.log(t),e===this.context.connection.connectionId)if(t.stoppedFollowing){const n=this.followers.indexOf(i);n!==-1&&(this.followers.splice(n,1),this.removeDisconnectedFollowers(),console.log(i,"unfollows you",this.followers.length))}else this.followers.includes(i)||(this.followers.push(i),this.removeDisconnectedFollowers(),console.log(i,"follows you",this.followers.length))}removeDisconnectedFollowers(){for(let t=this.followers.length-1;t>=0;t--){const e=this.followers[t];this.context.connection.userIsInRoom(e)===!1&&this.followers.splice(t,1)}}onRequestFollowEvent(t){if(this._lastRequestFollowUser=t,t.userId===this.context.connection.connectionId)this.spectator.stopSpectating();else if(t.userId===void 0)this.spectator.stopSpectating();else{const e=this.context.players.getPlayerView(t.userId);if(e)this.spectator.target=e;else return Pi&&console.warn("Could not find view",t.userId),this.enforceFollow(),!1}return!0}enforceFollow(){this._enforceFollowInterval||(this._enforceFollowInterval=setInterval(()=>{this._lastRequestFollowUser===void 0||this._lastRequestFollowUser.userId&&this.spectator.isFollowedBy(this._lastRequestFollowUser.userId)?(clearInterval(this._enforceFollowInterval),this._enforceFollowInterval=void 0):(Pi&&console.log("REQUEST FOLLOW AGAIN",this._lastRequestFollowUser.userId),this.onRequestFollowEvent(this._lastRequestFollowUser))},1e3))}}class jn{constructor(){r(this,"bb",null);r(this,"bb_pos",0)}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsSyncedCameraModel(t,e){return(e||new jn).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSyncedCameraModel(t,e){return t.setPosition(t.position()+ae.SIZE_PREFIX_LENGTH),(e||new jn).__init(t.readInt32(t.position())+t.position(),t)}userId(t){const e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}guid(t){const e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}dontSave(){const t=this.bb.__offset(this.bb_pos,8);return t?!!this.bb.readInt8(this.bb_pos+t):!1}pos(t){const e=this.bb.__offset(this.bb_pos,10);return e?(t||new Cr).__init(this.bb_pos+e,this.bb):null}rot(t){const e=this.bb.__offset(this.bb_pos,12);return e?(t||new Cr).__init(this.bb_pos+e,this.bb):null}static startSyncedCameraModel(t){t.startObject(5)}static addUserId(t,e){t.addFieldOffset(0,e,0)}static addGuid(t,e){t.addFieldOffset(1,e,0)}static addDontSave(t,e){t.addFieldInt8(2,+e,0)}static addPos(t,e){t.addFieldStruct(3,e,0)}static addRot(t,e){t.addFieldStruct(4,e,0)}static endSyncedCameraModel(t){return t.endObject()}static finishSyncedCameraModelBuffer(t,e){t.finish(e)}static finishSizePrefixedSyncedCameraModelBuffer(t,e){t.finish(e,void 0,!0)}}var eE=Object.defineProperty,tE=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&eE(t,e,n),n};const Su="SCAM";rg(Su,jn.getRootAsSyncedCameraModel);const yi=new ae.Builder;class iE{constructor(t,e){r(this,"userId");r(this,"guid");this.guid=e,this.userId=t}send(t,e){if(t){yi.clear();const i=yi.createString(this.guid),n=yi.createString(this.userId);jn.startSyncedCameraModel(yi),jn.addGuid(yi,i),jn.addUserId(yi,n);const s=Q(t),a=ju(t);jn.addPos(yi,Cr.createVec3(yi,s.x,s.y,s.z)),jn.addRot(yi,Cr.createVec3(yi,a.x,a.y,a.z));const l=jn.endSyncedCameraModel(yi);yi.finish(l,Su),e.sendBinary(yi.asUint8Array())}}}var bo;const Px=(bo=class extends D{constructor(){super(...arguments);r(this,"cameraPrefab",null);r(this,"_lastWorldPosition");r(this,"_lastWorldQuaternion");r(this,"_model",null);r(this,"_needsUpdate",!0);r(this,"_lastUpdateTime",0);r(this,"remoteCams",{});r(this,"userToCamMap",{});r(this,"_camTimeoutInSeconds",10);r(this,"_receiveCallback",null)}getCameraObject(e){const i=this.userToCamMap[e];return i?this.remoteCams[i].obj:null}async awake(){this._lastWorldPosition=this.worldPosition.clone(),this._lastWorldQuaternion=this.worldQuaternion.clone(),this.cameraPrefab&&("uri"in this.cameraPrefab&&(this.cameraPrefab=await this.cameraPrefab.instantiate(this.gameObject)),this.cameraPrefab&&"isObject3D"in this.cameraPrefab&&(this.cameraPrefab.visible=!1))}onEnable(){this._receiveCallback=this.context.connection.beginListenBinary(Su,this.onReceivedRemoteCameraInfoBin.bind(this))}onDisable(){this.context.connection.stopListenBinary(Su,this._receiveCallback)}update(){for(const s in this.remoteCams){const a=this.remoteCams[s],l=this.context.time.realtimeSinceStartup-a.lastUpdate;if(!a||l>this._camTimeoutInSeconds){j()&&console.log("Remote cam timeout",s),a!=null&&a.obj&&C.destroy(a.obj),delete this.remoteCams[s],a&&delete this.userToCamMap[a.userId],bo.instances.push(a),this.context.players.removePlayerView(a.userId,wo.Browser);continue}}if(this.context.isInXR)return;const e=this.context.mainCamera;if(e===null){this.enabled=!1;return}if(!this.context.connection.isConnected||this.context.connection.connectionId===null)return;this._model===null&&(this._model=new iE(this.context.connection.connectionId,this.context.connection.connectionId+"_camera"));const i=Q(e),n=_e(e);(i.distanceTo(this._lastWorldPosition)>.001||n.angleTo(this._lastWorldQuaternion)>.01)&&(this._needsUpdate=!0),this._lastWorldPosition.copy(i),this._lastWorldQuaternion.copy(n),!((!this._needsUpdate||this.context.time.frameCount%2!==0)&&!(this.context.time.realtimeSinceStartup-this._lastUpdateTime>this._camTimeoutInSeconds*.5))&&(this._lastUpdateTime=this.context.time.realtimeSinceStartup,this._needsUpdate=!1,this._model.send(e,this.context.connection),this.context.isInXR||this.context.players.setPlayerView(this.context.connection.connectionId,e,wo.Browser))}onReceivedRemoteCameraInfoBin(e){const i=e.guid();if(!i)return;const n=e.userId();if(!n||!this.context.connection.userIsInRoom(n)||!this.cameraPrefab)return;let s=this.remoteCams[i];if(!s)if("isObject3D"in this.cameraPrefab){const h=new Sn;h.context=this.context;const u=C.instantiate(this.cameraPrefab,h);s=this.remoteCams[i]={obj:u,lastUpdate:this.context.time.realtimeSinceStartup,userId:n},s.obj.visible=!0,this.gameObject.add(u),this.userToCamMap[n]=i,bo.instances.push(s);const f=C.getOrAddComponent(u,At);f.connectionId=n,f.avatar=u}else return;const a=s.obj;this.context.players.setPlayerView(n,a,wo.Browser),s.lastUpdate=this.context.time.realtimeSinceStartup,Wi.markDirty(a);const l=e.pos();l&&Pr(a,l.x(),l.y(),l.z());const c=e.rot();c&&th(a,c.x(),c.y(),c.z())}},r(bo,"instances",[]),bo);tE([m([d.Object3D,te])],Px.prototype,"cameraPrefab");let jy=Px;var nE=Object.defineProperty,sE=Object.getOwnPropertyDescriptor,Ho=(o,t,e,i)=>{for(var n=i>1?void 0:i?sE(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&nE(t,e,n),n};const Up="view",zp=S("debugsyncedroom");class kn extends D{constructor(){super(...arguments);r(this,"roomName","");r(this,"urlParameterName","room");r(this,"joinRandomRoom");r(this,"requireRoomParameter",!1);r(this,"autoRejoin",!0);r(this,"createJoinButton",!0);r(this,"createViewOnlyButton",!1);r(this,"_lastJoinedRoom");r(this,"_roomPrefix","");r(this,"_lastPingTime",0);r(this,"_lastRoomTime",-1);r(this,"_userWantsToBeInARoom",!1);r(this,"_roomButton");r(this,"_roomButtonIconJoin");r(this,"_roomButtonIconLeave");r(this,"updateRoomButtonState",()=>{var e,i;this._roomButton&&(this.context.connection.isInRoom?(this._roomButton.title="Leave the networked room",this._roomButton.textContent="Leave Room",(e=this._roomButtonIconJoin)==null||e.remove(),this._roomButton.prepend(this._roomButtonIconLeave)):(this._roomButton.title="Create or join a networked room",this._roomButton.textContent="Join Room",(i=this._roomButtonIconLeave)==null||i.remove(),this._roomButton.prepend(this._roomButtonIconJoin)))});r(this,"_viewOnlyButton");r(this,"onCreateViewOnlyButton",()=>{if(!this._viewOnlyButton){const e=document.createElement("button");this._viewOnlyButton=e,e.classList.add("view-only-button"),e.setAttribute("priority","90"),e.onclick=()=>{var n;const i=this.getViewOnlyUrl();i!=null&&i.length?navigator.canShare({url:i})?(n=navigator.share({url:i}))==null||n.catch(s=>{console.warn(s)}):(navigator.clipboard.writeText(i),Ee("View only URL copied to clipboard")):me("Could not create view only URL")},e.title="Copy the view only URL: A page accessed by the view only URL can not be modified by visiting users.",e.textContent="Share View URL",e.prepend(_t("visibility"))}this.context.menu.appendChild(this._viewOnlyButton)})}get currentRoomName(){const e=S(Up);return e||S(this.urlParameterName)}set roomPrefix(e){this._roomPrefix=e}get roomPrefix(){return this._roomPrefix}awake(){var e;this.joinRandomRoom===void 0&&((e=this.roomName)==null?void 0:e.length)<=0&&(this.joinRandomRoom=!0),zp&&console.log(`SyncedRoom roomName:${this.roomName}, urlParamName:${this.urlParameterName}, joinRandomRoom:${this.joinRandomRoom}`)}onEnable(){const e=S(Up);if(e&&typeof e=="string"&&e.length>0){console.log("Join as viewer"),this.context.connection.joinRoom(e,!0);return}if(this.tryJoinRoom(),this.createJoinButton){const i=this.createRoomButton();this.context.menu.appendChild(i)}this.createViewOnlyButton&&this.onEnableViewOnlyButton()}onDisable(){var e;(e=this._roomButton)==null||e.remove(),this.onDisableViewOnlyButton(),this.roomName&&this.roomName.length>0&&this.context.connection.leaveRoom(this.roomName)}onDestroy(){this.destroyRoomButton()}tryJoinRandomRoom(){this.setRandomRoomUrlParameter(),this.tryJoinRoom()}tryJoinRoom(e=0){var n;e===void 0&&(e=0);let i=!1;if(((n=this.urlParameterName)==null?void 0:n.length)>0){const s=S(this.urlParameterName);if(s&&(typeof s=="string"||typeof s=="number")){i=!0;const a=l0(s.toString());this.roomName=a}else if(this.joinRandomRoom&&(console.log("No room name found in url, generating random one"),this.setRandomRoomUrlParameter(),e<1))return this.tryJoinRoom(e+1)}else this.joinRandomRoom&&(this.roomName===null||this.roomName===void 0||this.roomName.length<=0)&&(this.roomName=this.generateRoomName());return this.requireRoomParameter&&!i?((zp||j())&&console.warn('[SyncedRoom] Missing required room parameter "'+this.urlParameterName+`" in url - will not connect.
1388
+ `)},e.userData.isLightBlendMaterial=!0}applyShadowMaterial(){if(this.targetMesh)if(this.targetMesh.material.type!=="ShadowMaterial"){const e=new d.ShadowMaterial;e.color=this.shadowColor,e.opacity=this.shadowColor.alpha,this.applyMaterialOptions(e),this.targetMesh.material=e,e.userData.isShadowCatcherMaterial=!0}else{const e=this.targetMesh.material;e.color=this.shadowColor,e.opacity=this.shadowColor.alpha,this.applyMaterialOptions(e),e.userData.isShadowCatcherMaterial=!0}}applyOccluderMaterial(){if(this.targetMesh){let e=this.targetMesh.material;if(!e){const i=new d.MeshBasicMaterial;this.targetMesh.material=i,e=i}e.depthWrite=!0,e.stencilWrite=!0,e.colorWrite=!1,this.gameObject.renderOrder=-100}}applyMaterialOptions(e){e&&(e.depthWrite=!1,e.stencilWrite=!1)}}xx([m()],Uh.prototype,"mode");xx([m(ie)],Uh.prototype,"shadowColor");var UR=Object.defineProperty,zh=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&UR(t,e,n),n};const Ot=S("debugskybox");Iy("background-image");Iy("environment-image");function Nb(o,t,e,i,n){const s=new xf;s.allowDrop=!1,s.allowNetworking=!1,s.background=e,s.environment=i,C.addComponent(o.scene,s);const a=l=>{typeof l=="string"&&(Ot&&console.log(n,"CHANGED TO",l),s.setSkybox(l))};return h0(o.domElement,n,a),s.addEventListener("destroy",()=>{Ot&&console.log("Destroyed attribute remote skybox",n),d0(o.domElement,n,a)}),s.setSkybox(t)}const xu=new Array;re.registerCallback(he.ContextCreationStart,o=>{var n;const t=o.context,e=t.domElement.getAttribute("background-image"),i=t.domElement.getAttribute("environment-image");if(e){Ot&&console.log("Creating remote skybox to load "+e),((n=t.mainCameraComponent)==null?void 0:n.clearFlags)!==Co.Skybox&&console.warn('"background-image" attribute has no effect: camera clear flags are not set to "Skybox"');const s=Nb(t,e,!0,!1,"background-image");xu.push(s)}if(i){Ot&&console.log("Creating remote environment to load "+i);const s=Nb(t,i,!1,!0,"environment-image");xu.push(s)}});re.registerCallback(he.ContextCreationStart,()=>Promise.all(xu).finally(()=>{xu.length=0}));function Sx(){return globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES||(globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES=new Array),globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES}function Vb(o){const e=Sx().find(i=>i.src===o);return e?(Ot&&console.log("Skybox: Found previously loaded texture for "+o),e.texture):null}async function zR(o){const t=await o;ug(t,!0),Se(t)}function NR(o,t){const e=Sx();for(;e.length>5;){const i=e.shift();i&&zR(i.texture)}t.then(i=>ug(i,!1)),e.push({src:o,texture:t})}const Lr=class extends D{constructor(){super(...arguments);r(this,"url");r(this,"allowDrop",!0);r(this,"background",!0);r(this,"environment",!0);r(this,"allowNetworking",!0);r(this,"_loader");r(this,"_prevUrl");r(this,"_prevLoadedEnvironment");r(this,"_prevEnvironment",null);r(this,"_prevBackground",null);r(this,"validTextureTypes",[".ktx2",".hdr",".exr",".jpg",".jpeg",".png"]);r(this,"onDragOverEvent",e=>{if(this.allowDrop&&e.dataTransfer)for(const i of e.dataTransfer.types)(i==="text/uri-list"||i==="Files")&&e.preventDefault()});r(this,"onDrop",e=>{var i,n,s,a;if(this.allowDrop&&e.dataTransfer){for(const l of e.dataTransfer.types)if(Ot&&console.log(l),l==="text/uri-list"){const c=e.dataTransfer.getData(l);Ot&&console.log(l,c);let h=(n=(i=new RegExp(/polyhaven.com\/asset_img\/.+?\/(?<name>.+)\.png/).exec(c))==null?void 0:i.groups)==null?void 0:n.name;if(h||(h=(a=(s=new RegExp(/polyhaven\.com\/a\/(?<name>.+)/).exec(c))==null?void 0:s.groups)==null?void 0:a.name),Ot&&console.log(h),h){const u="https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/"+h+"_1k.exr";console.log(`[Remote Skybox] Setting skybox from url: ${u}`),e.preventDefault(),this.setSkybox(u);break}else if(this.isValidTextureType(c)){console.log("[Remote Skybox] Setting skybox from url: "+c),e.preventDefault(),this.setSkybox(c);break}else{console.warn(`[RemoteSkybox] Unknown url ${c}. If you want to load a skybox from a url, make sure it is a valid image url. Url must end with${this.validTextureTypes.join(", ")}.`);const u=new CustomEvent("dropped-unknown-url",{detail:{sender:this,event:e,url:c,apply:f=>{e.preventDefault(),this.setSkybox(f)}}});this.dispatchEvent(u)}}else if(l=="Files"){const c=e.dataTransfer.files.item(0);if(Ot&&console.log(l,c),!c)continue;if(!this.isValidTextureType(c.name)){console.warn(`[RemoteSkybox]: File "${c.name}" is not supported. Supported files are ${this.validTextureTypes.join(", ")}`);return}if(Vb(c.name)===null){const h=new Blob([c]),u=URL.createObjectURL(h);e.preventDefault(),this.setSkybox(u,c.name)}else e.preventDefault(),this.setSkybox(c.name);break}}})}onEnable(){this.setSkybox(this.url),this.registerDropEvents()}onDisable(){var e;this.context.scene.environment===this._prevLoadedEnvironment&&(this.context.scene.environment=this._prevEnvironment,ri.backgroundShouldBeTransparent(this.context)||(this.context.scene.background=this._prevBackground),this._prevLoadedEnvironment=void 0),this.unregisterDropEvents(),(e=this.context.mainCameraComponent)==null||e.applyClearFlags()}urlChangedSyncField(){this.allowNetworking&&this.url&&(this.isRemoteTexture(this.url)?this.setSkybox(this.url):Ot&&console.warn(`RemoteSkybox: Not setting skybox: ${this.url} is not a remote texture. If you want to set a local texture, set allowNetworking to false.`))}async setSkybox(e,i){var a;if(!this.activeAndEnabled||(e=VR(e,this.environment,this.background),!e))return!1;if(i??(i=e),this.isValidTextureType(i)||console.warn("Potentially invalid skybox url",i,"on",this.name),Ot&&console.log("Set remote skybox url: "+e),this._prevUrl===e&&this._prevLoadedEnvironment)return this.apply(),!0;(a=this._prevLoadedEnvironment)==null||a.dispose(),this._prevLoadedEnvironment=void 0,this._prevUrl=e;const n=await this.loadTexture(e,i);if(!n)return Ot&&console.warn("RemoteSkybox: Failed to load texture from url",e),!1;if(!this.enabled)return Ot&&console.warn("RemoteSkybox: Component is not enabled, aborting setSkybox"),!1;if(this._prevUrl!==e)return Ot&&console.warn("RemoteSkybox: URL changed while loading texture, aborting setSkybox"),!1;this.url=e;const s=e.lastIndexOf("/");return n.name=e.substring(s>=0?s+1:0),this._loader instanceof d.TextureLoader&&(n.colorSpace=d.SRGBColorSpace),this._prevLoadedEnvironment=n,this.apply(),!0}async loadTexture(e,i){var u,f,p,g,y;if(!e)return Promise.resolve(null);i??(i=e);const n=Vb(i);if(n){const b=await n;if(((f=(u=b.source)==null?void 0:u.data)==null?void 0:f.length)>0||(y=(g=(p=b.source)==null?void 0:p.data)==null?void 0:g.data)!=null&&y.length)return b}const s=i.endsWith(".exr"),a=i.endsWith(".hdr"),l=i.endsWith(".ktx2");if(s)this._loader instanceof G.EXRLoader||(this._loader=new G.EXRLoader);else if(a)this._loader instanceof G.RGBELoader||(this._loader=new G.RGBELoader);else if(l){if(!(this._loader instanceof G.KTX2Loader)){const{ktx2Loader:b}=le.createLoaders(this.context.renderer);this._loader=b}}else this._loader instanceof d.TextureLoader||(this._loader=new d.TextureLoader);Ot&&console.log("Loading skybox: "+e);const c=this._loader.loadAsync(e);return NR(i,c),await c}apply(){var i;const e=this._prevLoadedEnvironment;e&&(e instanceof d.CubeTexture||e instanceof d.CompressedCubeTexture||(e.mapping=d.EquirectangularRefractionMapping,e.needsUpdate=!0),this.context.scene.background!==e&&(this._prevBackground=this.context.scene.background),this.context.scene.environment!==e&&(this._prevEnvironment=this.context.scene.environment),Ot&&console.log("Set remote skybox",this.url,!ri.backgroundShouldBeTransparent(this.context)),this.environment&&(this.context.scene.environment=e),this.background&&!ri.backgroundShouldBeTransparent(this.context)&&(this.context.scene.background=e),((i=this.context.mainCameraComponent)==null?void 0:i.backgroundBlurriness)!==void 0&&(this.context.scene.backgroundBlurriness=this.context.mainCameraComponent.backgroundBlurriness))}isRemoteTexture(e){return e.startsWith("http://")||e.startsWith("https://")}isValidTextureType(e){for(const i of this.validTextureTypes)if(e.endsWith(i))return!0;return!1}registerDropEvents(){this.unregisterDropEvents(),this.context.domElement.addEventListener("dragover",this.onDragOverEvent),this.context.domElement.addEventListener("drop",this.onDrop)}unregisterDropEvents(){this.context.domElement.removeEventListener("dragover",this.onDragOverEvent),this.context.domElement.removeEventListener("drop",this.onDrop)}};zh([ly(Lr.prototype.urlChangedSyncField),m(URL)],Lr.prototype,"url");zh([m()],Lr.prototype,"allowDrop");zh([m()],Lr.prototype,"background");zh([m()],Lr.prototype,"environment");zh([m()],Lr.prototype,"allowNetworking");let xf=Lr;function VR(o,t,e){const i=t&&!e;switch(o==null?void 0:o.toLowerCase()){case"studio":return i?"https://cdn.needle.tools/static/skybox/modelviewer-Neutral-small.hdr":"https://cdn.needle.tools/static/skybox/modelviewer-Neutral.hdr";case"blurred-skybox":return i?"https://cdn.needle.tools/static/skybox/blurred-skybox-small.exr":"https://cdn.needle.tools/static/skybox/blurred-skybox.exr";case"quicklook-ar":return i?"https://cdn.needle.tools/static/skybox/QuickLook-ARMode-small.exr":"https://cdn.needle.tools/static/skybox/QuickLook-ARMode.exr";case"quicklook":return i?"https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode-small.exr":"https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode.exr"}return o===void 0?null:o}var $R=Object.defineProperty,Sf=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&$R(t,e,n),n},fr;const Nh=(fr=class extends D{constructor(){super(...arguments);r(this,"target",null);r(this,"followFactor",.1);r(this,"rotateFactor",.1);r(this,"positionAxes",wa.All);r(this,"flipForward",!1);r(this,"_firstUpdate",!0)}onBeforeRender(){this.updateNow(!1)}updateNow(e){if(!(!this.target||this.target===this.gameObject)){if(this.followFactor>0){const i=Q(this.target),n=this._firstUpdate||e?1:z.clamp01(this.context.time.deltaTime*this.followFactor),s=this.worldPosition;this.positionAxes&wa.X&&(s.x=z.lerp(s.x,i.x,n)),this.positionAxes&wa.Y&&(s.y=z.lerp(s.y,i.y,n)),this.positionAxes&wa.Z&&(s.z=z.lerp(s.z,i.z,n)),this.worldPosition=s}if(this.rotateFactor>0){const i=_e(this.target);this.flipForward&&i.premultiply(fr._invertForward);const n=this._firstUpdate||e?1:z.clamp01(this.context.time.deltaTime*this.rotateFactor);this.worldQuaternion=this.worldQuaternion.slerp(i,n)}this._firstUpdate=!1}}},r(fr,"_invertForward",new d.Quaternion().setFromAxisAngle(new d.Vector3(0,1,0),Math.PI)),fr);Sf([m(d.Object3D)],Nh.prototype,"target");Sf([m()],Nh.prototype,"followFactor");Sf([m()],Nh.prototype,"rotateFactor");Sf([m()],Nh.prototype,"positionAxes");let Cf=Nh;var WR=Object.defineProperty,Vh=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&WR(t,e,n),n};const yc=S("debugspatialtrigger"),$b=new d.Layers,Wb=new d.Layers;function HR(o,t){return $b.mask=o,Wb.mask=t,$b.test(Wb)}class Zn extends D{constructor(){super(...arguments);r(this,"triggerMask",0);r(this,"onEnter");r(this,"onStay");r(this,"onExit");r(this,"currentIntersected",[]);r(this,"lastIntersected",[])}start(){yc&&console.log(this.name,this.triggerMask,this)}update(){this.currentIntersected.length=0;for(const e of Pf.triggers)HR(e.triggerMask,this.triggerMask)&&e.test(this.gameObject)&&this.currentIntersected.push(e);for(let e=this.lastIntersected.length-1;e>=0;e--){const i=this.lastIntersected[e];this.currentIntersected.indexOf(i)<0&&(this.onExitTrigger(i),this.lastIntersected.splice(e,1))}for(const e of this.currentIntersected)this.lastIntersected.indexOf(e)<0&&this.onEnterTrigger(e),this.onStayTrigger(e);this.lastIntersected.length=0,this.lastIntersected.push(...this.currentIntersected)}onEnterTrigger(e){var i;yc&&console.log("ENTER TRIGGER",this.name,e.name,this,e),e.raiseOnEnterEvent(this),(i=this.onEnter)==null||i.invoke()}onExitTrigger(e){var i;yc&&console.log("EXIT TRIGGER",this.name,e.name),e.raiseOnExitEvent(this),(i=this.onExit)==null||i.invoke()}onStayTrigger(e){var i;e.raiseOnStayEvent(this),(i=this.onStay)==null||i.invoke()}}Vh([m()],Zn.prototype,"triggerMask");Vh([m(ye)],Zn.prototype,"onEnter");Vh([m(ye)],Zn.prototype,"onStay");Vh([m(ye)],Zn.prototype,"onExit");var ks;const Cx=(ks=class extends D{constructor(){super(...arguments);r(this,"triggerMask");r(this,"boxHelper")}start(){yc&&console.log(this.name,this.triggerMask,this)}onEnable(){var e;ks.triggers.push(this),this.boxHelper||(this.boxHelper=C.addComponent(this.gameObject,ts),(e=this.boxHelper)==null||e.showHelper(null,yc))}onDisable(){ks.triggers.splice(ks.triggers.indexOf(this),1)}test(e){return this.boxHelper?this.boxHelper.isInBox(e)??!1:!1}raiseOnEnterEvent(e){C.foreachComponent(this.gameObject,i=>{i!==e&&i instanceof Zn&&i.onEnterTrigger(this)},!1)}raiseOnStayEvent(e){C.foreachComponent(this.gameObject,i=>{i!==e&&i instanceof Zn&&i.onStayTrigger(this)},!1)}raiseOnExitEvent(e){C.foreachComponent(this.gameObject,i=>{i!==e&&i instanceof Zn&&i.onExitTrigger(this)},!1)}},r(ks,"triggers",[]),ks);Vh([m()],Cx.prototype,"triggerMask");let Pf=Cx;var GR=Object.defineProperty,qR=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&GR(t,e,n),n};const Pi=S("debugspectator");class Mf extends D{constructor(){super(...arguments);r(this,"cam",null);r(this,"useKeys",!0);r(this,"_mode",0);r(this,"orbit",null);r(this,"_handler");r(this,"eventSub_WebXRRequestStartEvent",null);r(this,"eventSub_WebXRStartEvent",null);r(this,"eventSub_WebXREndEvent",null);r(this,"_debug");r(this,"_networking")}get mode(){return this._mode}set mode(e){this._mode=e}get isSpectating(){var e;return((e=this._handler)==null?void 0:e.currentTarget)!==void 0}isSpectatingUser(e){var i;return((i=this.target)==null?void 0:i.userId)===e}isFollowedBy(e){var i;return(i=this.followers)==null?void 0:i.includes(e)}get followers(){return this._networking.followers}stopSpectating(){if(this.context.isInXR){this.followSelf();return}this.target=void 0}get localId(){return this.context.connection.connectionId??"local"}set target(e){var i;if(this._handler){const n=(i=this._handler.currentTarget)==null?void 0:i.userId,s=this.context.players.getPlayerView(this.localId);e===void 0||this.context.isInXR===!1&&(s==null?void 0:s.currentObject)===e.currentObject?this._handler.currentTarget!==void 0&&(this._handler.disable(),C.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),this._networking.onSpectatedObjectChanged(e,n)):this._handler.currentTarget!==e&&(this._handler.set(e),C.setActive(this.gameObject,!0),this.orbit&&(this.orbit.enabled=!1),this._networking.onSpectatedObjectChanged(e,n))}}get target(){var e;return(e=this._handler)==null?void 0:e.currentTarget}requestAllFollowMe(){this._networking.onRequestFollowMe()}get isSpectatingSelf(){var e,i;return this.isSpectating&&((e=this.target)==null?void 0:e.currentObject)===((i=this.context.players.getPlayerView(this.localId))==null?void 0:i.currentObject)}awake(){if(this._debug=new YR(this.context,this),this._networking=new JR(this.context,this),this._networking.awake(),C.setActive(this.gameObject,!1),this.cam=C.getComponent(this.gameObject,ri),!this.cam){console.warn("SpectatorCamera: Spectator camera needs camera component on the same object.",this);return}!this._handler&&this.cam&&(this._handler=new XR(this.context,this.cam,this)),this.orbit=C.getComponent(this.context.mainCamera,ge)}onDestroy(){var e,i;this.stopSpectating(),(e=this._handler)==null||e.destroy(),(i=this._networking)==null||i.destroy()}isSupportedPlatform(){const e=window.navigator.userAgent,i=/Windows|MacOS/.test(e),n=/Windows NT/.test(e)&&/Edg/.test(e)&&!/Win64/.test(e);return i&&!n}onBeforeXR(e){this.isSupportedPlatform()&&C.setActive(this.gameObject,!0)}onEnterXR(e){this.isSupportedPlatform()&&(Pi&&console.log(this.context.mainCamera),this.context.mainCamera&&this.followSelf())}onLeaveXR(e){var i,n;this.context.removeCamera(this.cam),C.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),(i=this._handler)==null||i.set(void 0),(n=this._handler)==null||n.disable(),this.isSpectatingSelf&&this.stopSpectating()}followSelf(){this.target=this.context.players.getPlayerView(this.context.connection.connectionId),this.target||(this.context.players.setPlayerView(this.localId,this.context.mainCamera,wo.Headset),this.target=this.context.players.getPlayerView(this.localId)),Pi&&console.log("Follow self",this.target)}onAfterRender(){var u,f,p;if(!this.cam)return;const e=this.context.renderer,i=e.xr.enabled;if(!e.xr.isPresenting&&!((u=this._handler)!=null&&u.currentTarget))return;(f=this._handler)==null||f.update(this._mode);const n=e.getRenderTarget();let s=null;const a=e.state;if(!n){if(!e.state.bindFramebuffer||!a.bindXRFramebuffer)return;s=e._framebuffer,a.bindXRFramebuffer(null)}this.setAvatarFlagsBeforeRender();const l=this.context.mainCameraComponent;if(l){const g=l.backgroundColor;g&&e.setClearColor(g,g.alpha),this.cam.backgroundColor=g,this.cam.clearFlags=l.clearFlags,this.cam.nearClipPlane=l.nearClipPlane,this.cam.farClipPlane=l.farClipPlane}else e.setClearColor(new d.Color(1,1,1));e.setRenderTarget(null),e.xr.enabled=!1;const c=(p=this.cam)==null?void 0:p.threeCamera;this.context.updateAspect(c);const h=e.xr.isPresenting;e.xr.isPresenting=!1,e.setSize(this.context.domWidth,this.context.domHeight),e.render(this.context.scene,c),e.xr.isPresenting=h,e.xr.enabled=i,n?e.setRenderTarget(n):a.bindXRFramebuffer&&a.bindXRFramebuffer(s),this.resetAvatarFlags()}setAvatarFlagsBeforeRender(){const e=this._mode===0;for(const i of At.instances)if(i.avatar&&"isLocalAvatar"in i.avatar&&"flags"in i.avatar){let n=Bn.All;this.isSpectatingSelf&&(n=e&&i.avatar.isLocalAvatar?Bn.FirstPerson:Bn.ThirdPerson);const s=i.avatar.flags;if(!s)continue;for(const a of s)a.UpdateVisible(n)}}resetAvatarFlags(){var e;for(const i of At.instances)if(i.avatar&&"flags"in i.avatar){const n=i.avatar.flags;if(!n)continue;for(const s of n)"isLocalAvatar"in i.avatar&&((e=i.avatar)!=null&&e.isLocalAvatar)?s.UpdateVisible(Bn.FirstPerson):s.UpdateVisible(Bn.ThirdPerson)}}}qR([m()],Mf.prototype,"useKeys");class XR{constructor(t,e,i){r(this,"context");r(this,"cam");r(this,"spectator");r(this,"follow");r(this,"target");r(this,"view");r(this,"currentObject");this.context=t,this.cam=e,this.spectator=i}get currentTarget(){return this.view}set(t){const e=t==null?void 0:t.currentObject;if(!e){this.spectator.stopSpectating();return}e!==this.currentObject&&(this.currentObject=e,this.view=t,this.follow||(this.follow=C.addComponent(this.cam.gameObject,Cf)),this.target||(this.target=new d.Object3D),e.add(this.target),this.follow.enabled=!0,this.follow.target=this.target,Pi&&console.log("FOLLOW",e),this.context.isInXR?this.context.removeCamera(this.cam):this.context.setCurrentCamera(this.cam))}disable(){Pi&&console.log("STOP FOLLOW",this.currentObject),this.view=void 0,this.currentObject=void 0,this.context.removeCamera(this.cam),this.follow&&(this.follow.enabled=!1)}destroy(){var t;(t=this.target)==null||t.removeFromParent(),this.follow&&C.destroy(this.follow)}update(t){var n,s,a,l,c,h;if(((n=this.currentTarget)==null?void 0:n.isConnected)===!1||((s=this.currentTarget)==null?void 0:s.removed)===!0){Pi&&console.log("Target disconnected or timeout",this.currentTarget),this.spectator.stopSpectating();return}this.currentTarget&&((a=this.currentTarget)==null?void 0:a.currentObject)!==this.currentObject&&(Pi&&console.log("Target changed",this.currentObject,"to",this.currentTarget.currentObject),this.set(this.currentTarget));const e=this.context.mainCamera;if(e){const u=this.cam.threeCamera;(u.near!==e.near||u.far!==e.far)&&(u.near=e.near,u.far=e.far,u.updateProjectionMatrix())}const i=(l=this.follow)==null?void 0:l.target;if(!(!i||!this.follow)){switch(t){case 0:((c=this.view)==null?void 0:c.viewDevice)!==wo.Browser?(this.follow.followFactor=5,this.follow.rotateFactor=5):(this.follow.followFactor=50,this.follow.rotateFactor=50),i.position.set(0,0,0);break;case 1:this.follow.followFactor=3,this.follow.rotateFactor=2,i.position.set(0,.5,1.5);break}this.follow.flipForward=!1,((h=this.view)==null?void 0:h.viewDevice)!==wo.Browser?i.quaternion.copy(QR):i.quaternion.identity()}}}const QR=new d.Quaternion().setFromAxisAngle(new d.Vector3(0,1,0),Math.PI);class YR{constructor(t,e){r(this,"context");r(this,"spectator");this.context=t,this.spectator=e,console.log("[Spectator Camera] Click other avatars or cameras to follow them. Press ESC to exit spectator mode."),this.context.domElement.addEventListener("keydown",n=>{if(!this.spectator.useKeys)return;n.key==="Escape"&&this.spectator.stopSpectating()});let i=0;this.context.input.addEventListener(Re.PointerDown,n=>{i=this.context.time.time}),this.context.input.addEventListener(Re.PointerUp,n=>{const s=this.context.time.time-i;s>1?this.spectator.stopSpectating():this.context.input.getPointerClicked(0)&&s<.3&&this.trySelectObject()})}trySelectObject(){const t=new Jn;t.setMask(16777215);const e=this.context.physics.raycast(t);if(Pi&&console.log(...e),e!=null&&e.length)for(const i of e){if(i.distance<.2)continue;const n=i.object,s=C.getComponentInParent(n,At),a=s==null?void 0:s.connectionId;if(a){const l=this.context.players.getPlayerView(a);this.spectator.target=l,Pi&&console.log("spectate",a,s);break}}}}class KR{constructor(t,e,i){r(this,"guid");r(this,"dontSave",!0);r(this,"targetUserId");r(this,"stoppedFollowing");this.guid=t,this.targetUserId=e,this.stoppedFollowing=i}}class ZR{constructor(t,e){r(this,"guid");r(this,"userId");this.guid=t.guid,this.userId=e}}class JR{constructor(t,e){r(this,"followers",[]);r(this,"context");r(this,"spectator");r(this,"_followerEventMethod");r(this,"_requestFollowMethod");r(this,"_joinedRoomMethod");r(this,"_lastRequestFollowUser");r(this,"_enforceFollowInterval");this.context=t,this.spectator=e,this._followerEventMethod=this.onFollowerEvent.bind(this),this._requestFollowMethod=this.onRequestFollowEvent.bind(this),this._joinedRoomMethod=this.onUserJoinedRoom.bind(this)}awake(){this.context.connection.beginListen("spectator-follower-changed",this._followerEventMethod),this.context.connection.beginListen("spectator-request-follow",this._requestFollowMethod),this.context.connection.beginListen(ee.JoinedRoom,this._joinedRoomMethod),this.context.domElement.addEventListener("keydown",t=>{this.spectator.useKeys&&(t.key==="f"?this.onRequestFollowMe():t.key==="Escape"&&this.onRequestFollowMe(!0))})}destroy(){this.context.connection.stopListen("spectator-follower-changed",this._followerEventMethod),this.context.connection.stopListen("spectator-request-follow",this._requestFollowMethod),this.context.connection.stopListen(ee.JoinedRoom,this._joinedRoomMethod)}onSpectatedObjectChanged(t,e){if(Pi&&console.log(this.context.connection.connectionId,"onSpectatedObjectChanged",t,e),this.context.connection.connectionId){const i=(t==null?void 0:t.userId)===void 0,n=i?e:t==null?void 0:t.userId,s=new KR(this.context.connection.connectionId,n,i);this.context.connection.send("spectator-follower-changed",s)}}onRequestFollowMe(t=!1){if(Pi&&console.log("Request follow",this.context.connection.connectionId),this.context.connection.connectionId){this.spectator.stopSpectating();const e=t?void 0:this.context.connection.connectionId,i=new ZR(this.spectator,e);this.context.connection.send("spectator-request-follow",i)}}onUserJoinedRoom(){S("followme")&&this.onRequestFollowMe()}onFollowerEvent(t){const e=t.targetUserId,i=t.guid;if(Pi&&console.log(t),e===this.context.connection.connectionId)if(t.stoppedFollowing){const n=this.followers.indexOf(i);n!==-1&&(this.followers.splice(n,1),this.removeDisconnectedFollowers(),console.log(i,"unfollows you",this.followers.length))}else this.followers.includes(i)||(this.followers.push(i),this.removeDisconnectedFollowers(),console.log(i,"follows you",this.followers.length))}removeDisconnectedFollowers(){for(let t=this.followers.length-1;t>=0;t--){const e=this.followers[t];this.context.connection.userIsInRoom(e)===!1&&this.followers.splice(t,1)}}onRequestFollowEvent(t){if(this._lastRequestFollowUser=t,t.userId===this.context.connection.connectionId)this.spectator.stopSpectating();else if(t.userId===void 0)this.spectator.stopSpectating();else{const e=this.context.players.getPlayerView(t.userId);if(e)this.spectator.target=e;else return Pi&&console.warn("Could not find view",t.userId),this.enforceFollow(),!1}return!0}enforceFollow(){this._enforceFollowInterval||(this._enforceFollowInterval=setInterval(()=>{this._lastRequestFollowUser===void 0||this._lastRequestFollowUser.userId&&this.spectator.isFollowedBy(this._lastRequestFollowUser.userId)?(clearInterval(this._enforceFollowInterval),this._enforceFollowInterval=void 0):(Pi&&console.log("REQUEST FOLLOW AGAIN",this._lastRequestFollowUser.userId),this.onRequestFollowEvent(this._lastRequestFollowUser))},1e3))}}class jn{constructor(){r(this,"bb",null);r(this,"bb_pos",0)}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsSyncedCameraModel(t,e){return(e||new jn).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSyncedCameraModel(t,e){return t.setPosition(t.position()+ae.SIZE_PREFIX_LENGTH),(e||new jn).__init(t.readInt32(t.position())+t.position(),t)}userId(t){const e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}guid(t){const e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}dontSave(){const t=this.bb.__offset(this.bb_pos,8);return t?!!this.bb.readInt8(this.bb_pos+t):!1}pos(t){const e=this.bb.__offset(this.bb_pos,10);return e?(t||new Cr).__init(this.bb_pos+e,this.bb):null}rot(t){const e=this.bb.__offset(this.bb_pos,12);return e?(t||new Cr).__init(this.bb_pos+e,this.bb):null}static startSyncedCameraModel(t){t.startObject(5)}static addUserId(t,e){t.addFieldOffset(0,e,0)}static addGuid(t,e){t.addFieldOffset(1,e,0)}static addDontSave(t,e){t.addFieldInt8(2,+e,0)}static addPos(t,e){t.addFieldStruct(3,e,0)}static addRot(t,e){t.addFieldStruct(4,e,0)}static endSyncedCameraModel(t){return t.endObject()}static finishSyncedCameraModelBuffer(t,e){t.finish(e)}static finishSizePrefixedSyncedCameraModelBuffer(t,e){t.finish(e,void 0,!0)}}var eE=Object.defineProperty,tE=(o,t,e,i)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=a(t,e,n)||n);return n&&eE(t,e,n),n};const Su="SCAM";rg(Su,jn.getRootAsSyncedCameraModel);const yi=new ae.Builder;class iE{constructor(t,e){r(this,"userId");r(this,"guid");this.guid=e,this.userId=t}send(t,e){if(t){yi.clear();const i=yi.createString(this.guid),n=yi.createString(this.userId);jn.startSyncedCameraModel(yi),jn.addGuid(yi,i),jn.addUserId(yi,n);const s=Q(t),a=ju(t);jn.addPos(yi,Cr.createVec3(yi,s.x,s.y,s.z)),jn.addRot(yi,Cr.createVec3(yi,a.x,a.y,a.z));const l=jn.endSyncedCameraModel(yi);yi.finish(l,Su),e.sendBinary(yi.asUint8Array())}}}var bo;const Px=(bo=class extends D{constructor(){super(...arguments);r(this,"cameraPrefab",null);r(this,"_lastWorldPosition");r(this,"_lastWorldQuaternion");r(this,"_model",null);r(this,"_needsUpdate",!0);r(this,"_lastUpdateTime",0);r(this,"remoteCams",{});r(this,"userToCamMap",{});r(this,"_camTimeoutInSeconds",10);r(this,"_receiveCallback",null)}getCameraObject(e){const i=this.userToCamMap[e];return i?this.remoteCams[i].obj:null}async awake(){this._lastWorldPosition=this.worldPosition.clone(),this._lastWorldQuaternion=this.worldQuaternion.clone(),this.cameraPrefab&&("uri"in this.cameraPrefab&&(this.cameraPrefab=await this.cameraPrefab.instantiate(this.gameObject)),this.cameraPrefab&&"isObject3D"in this.cameraPrefab&&(this.cameraPrefab.visible=!1))}onEnable(){this._receiveCallback=this.context.connection.beginListenBinary(Su,this.onReceivedRemoteCameraInfoBin.bind(this))}onDisable(){this.context.connection.stopListenBinary(Su,this._receiveCallback)}update(){for(const s in this.remoteCams){const a=this.remoteCams[s],l=this.context.time.realtimeSinceStartup-a.lastUpdate;if(!a||l>this._camTimeoutInSeconds){j()&&console.log("Remote cam timeout",s),a!=null&&a.obj&&C.destroy(a.obj),delete this.remoteCams[s],a&&delete this.userToCamMap[a.userId],bo.instances.push(a),this.context.players.removePlayerView(a.userId,wo.Browser);continue}}if(this.context.isInXR)return;const e=this.context.mainCamera;if(e===null){this.enabled=!1;return}if(!this.context.connection.isConnected||this.context.connection.connectionId===null)return;this._model===null&&(this._model=new iE(this.context.connection.connectionId,this.context.connection.connectionId+"_camera"));const i=Q(e),n=_e(e);(i.distanceTo(this._lastWorldPosition)>.001||n.angleTo(this._lastWorldQuaternion)>.01)&&(this._needsUpdate=!0),this._lastWorldPosition.copy(i),this._lastWorldQuaternion.copy(n),!((!this._needsUpdate||this.context.time.frameCount%2!==0)&&!(this.context.time.realtimeSinceStartup-this._lastUpdateTime>this._camTimeoutInSeconds*.5))&&(this._lastUpdateTime=this.context.time.realtimeSinceStartup,this._needsUpdate=!1,this._model.send(e,this.context.connection),this.context.isInXR||this.context.players.setPlayerView(this.context.connection.connectionId,e,wo.Browser))}onReceivedRemoteCameraInfoBin(e){const i=e.guid();if(!i)return;const n=e.userId();if(!n||!this.context.connection.userIsInRoom(n)||!this.cameraPrefab)return;let s=this.remoteCams[i];if(!s)if("isObject3D"in this.cameraPrefab){const h=new Sn;h.context=this.context;const u=C.instantiate(this.cameraPrefab,h);s=this.remoteCams[i]={obj:u,lastUpdate:this.context.time.realtimeSinceStartup,userId:n},s.obj.visible=!0,this.gameObject.add(u),this.userToCamMap[n]=i,bo.instances.push(s);const f=C.getOrAddComponent(u,At);f.connectionId=n,f.avatar=u}else return;const a=s.obj;this.context.players.setPlayerView(n,a,wo.Browser),s.lastUpdate=this.context.time.realtimeSinceStartup,Wi.markDirty(a);const l=e.pos();l&&Pr(a,l.x(),l.y(),l.z());const c=e.rot();c&&th(a,c.x(),c.y(),c.z())}},r(bo,"instances",[]),bo);tE([m([d.Object3D,te])],Px.prototype,"cameraPrefab");let jy=Px;var nE=Object.defineProperty,sE=Object.getOwnPropertyDescriptor,Ho=(o,t,e,i)=>{for(var n=i>1?void 0:i?sE(t,e):t,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&nE(t,e,n),n};const Up="view",zp=S("debugsyncedroom");class kn extends D{constructor(){super(...arguments);r(this,"roomName","");r(this,"urlParameterName","room");r(this,"joinRandomRoom");r(this,"requireRoomParameter",!1);r(this,"autoRejoin",!0);r(this,"createJoinButton",!0);r(this,"createViewOnlyButton",!1);r(this,"_lastJoinedRoom");r(this,"_roomPrefix","");r(this,"_lastPingTime",0);r(this,"_lastRoomTime",-1);r(this,"_userWantsToBeInARoom",!1);r(this,"_roomButton");r(this,"_roomButtonIconJoin");r(this,"_roomButtonIconLeave");r(this,"updateRoomButtonState",()=>{var e,i;this._roomButton&&(this.context.connection.isInRoom?(this._roomButton.title="Leave the networked room",this._roomButton.textContent="Leave Room",(e=this._roomButtonIconJoin)==null||e.remove(),this._roomButton.prepend(this._roomButtonIconLeave)):(this._roomButton.title="Create or join a networked room",this._roomButton.textContent="Join Room",(i=this._roomButtonIconLeave)==null||i.remove(),this._roomButton.prepend(this._roomButtonIconJoin)))});r(this,"_viewOnlyButton");r(this,"onCreateViewOnlyButton",()=>{if(!this._viewOnlyButton){const e=document.createElement("button");this._viewOnlyButton=e,e.classList.add("view-only-button"),e.setAttribute("priority","90"),e.onclick=()=>{var n;const i=this.getViewOnlyUrl();i!=null&&i.length?navigator.canShare({url:i})?(n=navigator.share({url:i}))==null||n.catch(s=>{console.warn(s)}):(navigator.clipboard.writeText(i),Ee("View only URL copied to clipboard")):me("Could not create view only URL")},e.title="Copy the view only URL: A page accessed by the view only URL can not be modified by visiting users.",e.textContent="Share View URL",e.prepend(_t("visibility"))}this.context.menu.appendChild(this._viewOnlyButton)})}get currentRoomName(){const e=S(Up);return e||S(this.urlParameterName)}set roomPrefix(e){this._roomPrefix=e}get roomPrefix(){return this._roomPrefix}awake(){var e;this.joinRandomRoom===void 0&&((e=this.roomName)==null?void 0:e.length)<=0&&(this.joinRandomRoom=!0),zp&&console.log(`SyncedRoom roomName:${this.roomName}, urlParamName:${this.urlParameterName}, joinRandomRoom:${this.joinRandomRoom}`)}onEnable(){const e=S(Up);if(e&&typeof e=="string"&&e.length>0){console.log("Join as viewer"),this.context.connection.joinRoom(e,!0);return}if(this.tryJoinRoom(),this.createJoinButton){const i=this.createRoomButton();this.context.menu.appendChild(i)}this.createViewOnlyButton&&this.onEnableViewOnlyButton()}onDisable(){var e;(e=this._roomButton)==null||e.remove(),this.onDisableViewOnlyButton(),this.roomName&&this.roomName.length>0&&this.context.connection.leaveRoom(this.roomName)}onDestroy(){this.destroyRoomButton()}tryJoinRandomRoom(){this.setRandomRoomUrlParameter(),this.tryJoinRoom()}tryJoinRoom(e=0){var n;e===void 0&&(e=0);let i=!1;if(((n=this.urlParameterName)==null?void 0:n.length)>0){const s=S(this.urlParameterName);if(s&&(typeof s=="string"||typeof s=="number")){i=!0;const a=l0(s.toString());this.roomName=a}else if(this.joinRandomRoom&&(console.log("No room name found in url, generating random one"),this.setRandomRoomUrlParameter(),e<1))return this.tryJoinRoom(e+1)}else this.joinRandomRoom&&(this.roomName===null||this.roomName===void 0||this.roomName.length<=0)&&(this.roomName=this.generateRoomName());return this.requireRoomParameter&&!i?((zp||j())&&console.warn('[SyncedRoom] Missing required room parameter "'+this.urlParameterName+`" in url - will not connect.
1387
1389
  To allow joining a room without a query parameter you can set "requireRoomParameter" to false.`),!1):(this.context.connection.isConnected||this.context.connection.connect(),this._lastJoinedRoom=this.roomName,this._roomPrefix&&(this.roomName=this._roomPrefix+this.roomName),this.roomName.length<=0?(console.warn(`[SyncedRoom] Room name is not set so we can not join a networked room.
1388
1390
  Please choose one of the following options to fix this:
1389
1391
  A) Set a room name in the SyncedRoom component
@@ -1601,4 +1603,4 @@ Error:`,l),null}}updateColliderCollisionGroups(t){const e=t[zt],i=t.membership;l
1601
1603
  justify-content: center;
1602
1604
  gap: .5rem;
1603
1605
  }
1604
- `),ce(this,gr).innerHTML=ce(this,$t).innerHTML,ce(this,gr).style.cssText="display: flex; align-items: center; justify-content: center;",ce(this,$t).innerHTML=ce(this,gr).outerHTML,ce(this,mr).innerHTML=ce(this,$t).outerHTML,ce(this,mr).prepend(ce(this,yr)),ou(ym,{element:ce(this,mr)}),(n=ce(this,Fa))==null||n.disconnect(),ce(this,Fa)??rn(this,Fa,new MutationObserver(()=>Ml(this,il,Nx).call(this))),ce(this,Fa).observe(ce(this,$t),{attributes:!0}),Hp&&console.log("Needle Button updated")},Nx=function(){ce(this,$t)&&(ce(this,$t).style.display==="none"?this.style.display="none":this.style.display==="none"&&(this.style.display=""))},Yc=new WeakMap,r(Yy,"observedAttributes",["ar","vr","quicklook"]);typeof window<"u"&&!window.customElements.get(t0)&&window.customElements.define(t0,Yy);const Hl=S("debugavatar");class Ky{constructor(t,e,i,n){r(this,"root");r(this,"head");r(this,"leftHand");r(this,"rigthHand");var s;this.root=t,this.head=e,this.leftHand=i,this.rigthHand=n,(s=this.root)==null||s.traverse(a=>a.layers.set(2))}get isValid(){return this.head!==null&&this.head!==void 0}}class Vx{constructor(){r(this,"avatarRegistryUrl",null)}async getOrCreateNewAvatarInstance(t,e){if(!e)return console.error("Can not create avatar: failed to provide id or root object"),null;let i=null;if(typeof e=="string"){if(i=await this.loadAvatar(t,e),!i){const s=new Sn;i=C.instantiate(Ua(e,t.scene),s)}}else i=e;if(!i)return null;const n=this.findAvatar(i);return n.isValid?(Hl&&console.log("[Custom Avatar] valid config",e,Hl?n:""),n):(console.warn("[Custom Avatar] config isn't valid",e,Hl?n:""),null)}async loadAvatar(t,e){if(console.assert(e!=null&&typeof e=="string","Avatar id must not be null"),e.length<=0||!e)return null;if(Hl&&console.log("[Custom Avatar] "+e+", loading..."),e.endsWith(".glb")||(e+=".glb"),this.avatarRegistryUrl===null){const n=await fetch("./"+e);let s=null;if(n.ok){const l=await n.blob();l&&(s=await l.arrayBuffer())}if(!s)return null;const a=await vn().parseSync(t,s,null,0);return(a==null?void 0:a.scene)??null}const i=new G.GLTFLoader;return Pg(i,t),new Promise((n,s)=>{const a=this.avatarRegistryUrl+"/"+e;i.load(a,async l=>{await vn().createBuiltinComponents(t,a,l,null,void 0),n(l.scene)},l=>{Hl&&console.log("[Custom Avatar] "+l.loaded/l.total*100+"% loaded of "+l.total/1024+"kB")},l=>{console.error("[Custom Avatar] Error when loading: "+l),n(null)})})}cacheModel(t,e){}findAvatar(t){const e=t;let i=e;i.children.length==1&&(i=t.children[0]);let n=this.findAvatarPart(i,["head"]);const s=this.findAvatarPart(i,["left","hand"]),a=this.findAvatarPart(i,["right","hand"]);if(!n){n=e;const c=new d.Vector3;new d.Box3().setFromObject(n).getSize(c);const h=Math.max(c.x,c.y,c.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+h+" meters! Should be < 0.3m"),h>.3&&n.scale.multiplyScalar(1/h*.3)}return new Ky(e,n,s,a)}findAvatarPart(t,e){const i=t.name.toLowerCase();let n=!0;for(const s of e){if(!n)break;i.indexOf(s)===-1&&(n=!1)}if(n)return t;if(t.children)for(const s of t.children){const a=this.findAvatarPart(s,e);if(a)return a}return null}handleCustomAvatarErrors(t){if(!t.ok)throw Error(t.statusText);return t}}class $x{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(t){}}class Wx{}const cT=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:fe,ActionCollection:Zw,ActionModel:xi,AlignmentConstraint:uh,Animation:Tt,AnimationCurve:Th,AnimationExtension:rf,AnimationTrackHandler:Rf,Animator:xt,AnimatorController:Hi,Antialiasing:Lh,AudioExtension:Wr,AudioListener:Ms,AudioSource:qi,AudioTrackHandler:el,Avatar:ko,AvatarBlink_Simple:zr,AvatarEyeLook_Rotation:Dg,AvatarLoader:Vx,AvatarMarker:At,AvatarModel:Ky,Avatar_Brain_LookAt:Fc,Avatar_MouthShapes:gh,Avatar_MustacheShake:Ag,Avatar_POI:Ts,AxesHelper:ol,BaseUIComponent:Qi,BasicIKConstraint:jg,BehaviorExtension:dy,BehaviorModel:vt,BloomEffect:vf,BoxCollider:ef,BoxGizmo:Xr,BoxHelperComponent:ts,Button:$s,CallInfo:Cs,Camera:ri,CameraTargetReachedEvent:Bc,Canvas:Za,CanvasGroup:Ro,CapsuleCollider:As,ChangeMaterialOnClick:iy,ChangeTransformOnClick:Hr,CharacterController:Nr,CharacterControllerInput:Is,ChromaticAberration:Dh,Collider:di,ColorAdjustments:$o,ColorBySpeedModule:yl,ColorOverLifetimeModule:yf,ContactShadows:yh,ControlTrackHandler:Ef,CustomBranding:qr,Deletable:zg,DeleteBox:qa,DepthOfField:Mn,DeviceFlag:tf,DocumentExtension:$x,DragControls:cr,DropListener:js,Duplicatable:$g,EffectWrapper:Wc,EmissionModule:Ns,EmphasizeOnClick:cl,EnvironmentScene:If,EventList:ye,EventListEvent:Qu,EventSystem:Qt,EventTrigger:sf,FieldWithDefault:Bw,FixedJoint:Py,Fog:pl,GltfExport:Zg,GltfExportBox:Yg,Gradient:Yr,Graphic:Mh,GraphicRaycaster:Yu,GridHelper:ml,GridLayoutGroup:yy,GroundProjectedEnv:ss,GroupActionModel:yo,HideOnStart:Qa,HingeJoint:kh,HorizontalLayoutGroup:gy,Image:vl,InheritVelocityModule:Ry,InputField:Vy,InstanceHandle:zc,InstancingHandler:Xa,Interactable:Ug,Keyframe:ai,LODGroup:Eh,LODModel:gl,Light:pi,LimitVelocityOverLifetimeModule:lt,LogStats:Fg,LookAt:$y,LookAtConstraint:Ur,MainModule:It,MaskableGraphic:Oh,MeshCollider:jo,MeshRenderer:bh,MinMaxCurve:q,MinMaxGradient:Kr,NeedleMenu:rs,NestedGltf:pf,Networking:Oy,NoiseModule:be,ObjectRaycaster:Ei,OffsetConstraint:Qr,OpenURL:wl,OrbitControls:ge,Outline:fl,Padding:Gr,ParticleBurst:vu,ParticleSubEmitter:Ey,ParticleSystem:$c,ParticleSystemRenderer:en,PhysicsExtension:uy,PixelationEffect:Ih,PlayAnimationOnClick:Nc,PlayAudioOnClick:Oo,PlayableDirector:tl,PlayerColor:Ja,PointerEventData:ph,PostProcessingHandler:Dy,PreliminaryAction:hl,PreliminaryTrigger:xh,RawImage:Lf,Rect:nx,RectTransform:xn,ReflectionProbe:Uc,RegisteredAnimationInfo:_o,RemoteSkybox:xf,Renderer:Ti,RendererLightmap:yu,Rigidbody:ot,RotationBySpeedModule:Ji,RotationOverLifetimeModule:Pn,SceneSwitcher:He,ScreenCapture:Wo,ScreenSpaceAmbientOcclusion:Vs,ScreenSpaceAmbientOcclusionN8:On,SetActiveOnClick:ny,ShadowCatcher:Uh,ShapeModule:ky,SharpeningEffect:Bh,SignalAsset:kf,SignalReceiver:Wh,SignalReceiverEvent:$h,SignalTrackHandler:Hc,Size:ix,SizeBySpeedModule:mi,SizeOverLifetimeModule:Zr,SkinnedMeshRenderer:Qg,SmoothFollow:Cf,SpatialGrabRaycaster:Tr,SpatialHtml:qh,SpatialTrigger:Pf,SpatialTriggerReceiver:Zn,SpectatorCamera:Mf,SphereCollider:rl,Sprite:Fs,SpriteData:Ba,SpriteRenderer:ui,SpriteSheet:Ka,SubEmitterSystem:wu,SyncedCamera:jy,SyncedRoom:kn,SyncedTransform:es,TapGestureTrigger:oy,TeleportTarget:df,TestRunner:By,TestSimulateUserData:Fy,Text:Dt,TextBuilder:py,TextExtension:ff,TextureSheetAnimationModule:jt,TiltShiftEffect:cs,ToneMappingEffect:Eo,TrailModule:je,TransformData:We,TransformGizmo:ia,TriggerBuilder:wt,TriggerModel:Po,UIRaycastUtils:kg,UIRootComponent:Ch,USDZExporter:Kn,USDZText:hr,USDZUIExtension:by,UsageMarker:_h,VariantAction:ty,VelocityOverLifetimeModule:ze,VerticalLayoutGroup:my,VideoPlayer:rt,Vignette:ta,VisibilityAction:Sh,Voip:Io,Volume:bl,VolumeParameter:U,VolumeProfile:_f,WebARCameraBackground:Qh,WebARSessionRoot:is,WebXR:uf,WebXRImageTracking:qc,WebXRImageTrackingModel:Hs,WebXRPlaneTracking:Gs,WebXRTrackedImage:Gc,XRControllerFollow:Ws,XRControllerModel:ns,XRControllerMovement:Ai,XRFlag:Vi,XRRig:Bf,XRState:Xt,__Ignore:Wx},Symbol.toStringTag,{value:"Module"})),Mu=S("debugmissingcamera");re.registerCallback(he.MissingCamera,o=>{var l,c,h,u;Mu&&console.warn("Creating missing camera");const t=o.context.scene,e=new d.PerspectiveCamera;e.name="Default Fallback Camera",t.add(e);const i=new ri;if(i.sourceId=((c=(l=o.files)==null?void 0:l[0])==null?void 0:c.src)??"unknown",i.fieldOfView=35,o.context.domElement.getAttribute("transparent")!=null)i.clearFlags=Co.Uninitialized;else if((h=o.context.domElement.getAttribute("skybox-image"))!=null&&h.length||(u=o.context.domElement.getAttribute("background-image"))!=null&&u.length||o.context.lightmaps.tryGetSkybox(i.sourceId))i.clearFlags=Co.Skybox,i.backgroundBlurriness=.2;else{if(i.clearFlags=Co.SolidColor,!o.context.domElement.getAttribute("background-color")){let f="#efefef";typeof window!==void 0&&window.matchMedia("(prefers-color-scheme: dark)").matches&&(f="#1f1f1f"),t.background=new d.Color(f)}if(!t.environment){const f=new d.PMREMGenerator$1(o.context.renderer),p=new If("neutral");t.environment=f.fromScene(p,.025).texture}}const s=wr(e,i,!0);e.position.x=0,e.position.y=1,e.position.z=2;const a=o.context.domElement;return(a==null?void 0:a.cameraControls)!=!1&&Hx(o.context,s),s});re.registerCallback(he.ContextCreated,o=>{if(!o.context.mainCamera){Mu&&console.log("Will not auto-fit because a default camera exists");return}const t=o.context.domElement;if((t==null?void 0:t.cameraControls)==!0){const e=b0(o.context.mainCamera);if((e==null?void 0:e.isCameraController)==!0){Mu&&console.log("Will not auto-fit because a camera controller exists");return}Hx(o.context)}});function Hx(o,t){t=t??o.mainCameraComponent;const e=t==null?void 0:t.gameObject;if(Mu&&console.log("Creating default camera controls",t==null?void 0:t.name),e){const i=rh(e,ge);i.sourceId=(t==null?void 0:t.sourceId)??"unknown";const n=o.domElement.getAttribute("auto-rotate");if(i.autoRotate=n!=null&&n!="0"&&(n==null?void 0:n.toLowerCase())!="false",i.autoRotateSpeed=.5,i.autoFit=!0,i.autoRotate&&n){const s=parseFloat(n);isNaN(s)||(i.autoRotateSpeed=s)}}else console.warn("Missing camera object, can not add orbit controls")}re.registerCallback(he.ContextCreated,o=>{const t=o.context.domElement.getAttribute("autoplay");if(t!==void 0&&(t===""||t==="true"||t==="1")&&o.files)for(const e of o.files)C.foreachComponent(e.file.scene,n=>{if(n.enabled!==!1){if(n instanceof Tt&&n.playAutomatically||n instanceof xt||n instanceof tl&&n.playOnAwake===!0)return!0;if(n instanceof Tt)return n.playAutomatically=!0,!0;if(n instanceof tl)return n.playOnAwake=!0,!0}},!0)!==!0&&Ha.assignAnimationsFromFile(e.file,{createAnimationComponent:(n,s)=>Oi(n,Tt)})});class hT extends ae.WorkerBase{constructor(){super(new Worker(new URL("/generateMeshBVH.worker-BaNp_Xtp.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:zf&&zf.tagName.toUpperCase()==="SCRIPT"&&zf.src||new URL("needle-engine.bundle-CP5AJL1A.umd.cjs",document.baseURI).href),{type:"module"})),this.name="GenerateMeshBVHWorker"}runTask(t,e,i={}){return new Promise((n,s)=>{if(e.getAttribute("position").isInterleavedBufferAttribute||e.index&&e.index.isInterleavedBufferAttribute)throw new Error("GenerateMeshBVHWorker: InterleavedBufferAttribute are not supported for the geometry attributes.");t.onerror=h=>{s(new Error(`[GenerateMeshBVHWorker] ${h.message||"Unknown error. Please check the server console. If you're using vite try adding 'three-mesh-bvh' to 'optimizeDeps.exclude' in your vite.config.js"}`))},t.onmessage=h=>{const{data:u}=h;if(u.error)s(new Error(u.error)),t.onmessage=null;else if(u.serialized){const{serialized:f,position:p}=u,g=ae.MeshBVH.deserialize(f,e,{setIndex:!1}),y=Object.assign({setBoundingBox:!0},i);if(e.attributes.position.array=p,f.index)if(e.index)e.index.array=f.index;else{const b=new d.BufferAttribute(f.index,1,!1);e.setIndex(b)}y.setBoundingBox&&(e.boundingBox=g.getBoundingBox(new d.Box3)),i.onProgress&&i.onProgress(u.progress),n(g),t.onmessage=null}else i.onProgress&&i.onProgress(u.progress)};const a=e.index?e.index.array:null,l=e.attributes.position.array,c=[l];a&&c.push(a),t.postMessage({index:a,position:l,options:{...i,onProgress:null,includedProgressCallback:!!i.onProgress,groups:[...e.groups]}},c.map(h=>h.buffer).filter(h=>typeof SharedArrayBuffer>"u"||!(h instanceof SharedArrayBuffer)))})}}const dT=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:hT},Symbol.toStringTag,{value:"Module"}));exports.$physicsKey=nM;exports.ActionBuilder=fe;exports.ActionCollection=Zw;exports.ActionModel=xi;exports.Addressables=jv;exports.AlignmentConstraint=uh;exports.AmbientMode=Da;exports.Animation=Tt;exports.AnimationCurve=Th;exports.AnimationExtension=rf;exports.AnimationTrackHandler=Rf;exports.AnimationUtils=Ha;exports.Animator=xt;exports.AnimatorConditionMode=so;exports.AnimatorController=Hi;exports.AnimatorControllerParameterType=Mg;exports.AnimatorStateInfo=Zl;exports.Antialiasing=Lh;exports.Application=wn;exports.AssetDatabase=J0;exports.AssetReference=te;exports.AudioExtension=Wr;exports.AudioListener=Ms;exports.AudioSource=qi;exports.AudioTrackHandler=el;exports.Avatar=ko;exports.AvatarBlink_Simple=zr;exports.AvatarEyeLook_Rotation=Dg;exports.AvatarLoader=Vx;exports.AvatarMarker=At;exports.AvatarModel=Ky;exports.Avatar_Brain_LookAt=Fc;exports.Avatar_MouthShapes=gh;exports.Avatar_MustacheShake=Ag;exports.Avatar_POI=Ts;exports.Axes=wa;exports.AxesHelper=ol;exports.BUILD_TIME=eg;exports.BaseUIComponent=Qi;exports.BasicIKConstraint=jg;exports.BehaviorExtension=dy;exports.BehaviorModel=vt;exports.BloomEffect=vf;exports.BoxCollider=ef;exports.BoxGizmo=Xr;exports.BoxHelperComponent=ts;exports.Button=$s;exports.ButtonsFactory=zn;exports.CallDirection=_w;exports.CallInfo=Cs;exports.Camera=ri;exports.CameraTargetReachedEvent=Bc;exports.Canvas=Za;exports.CanvasGroup=Ro;exports.CapsuleCollider=As;exports.ChangeMaterialOnClick=iy;exports.ChangeTransformOnClick=Hr;exports.CharacterController=Nr;exports.CharacterControllerInput=Is;exports.ChromaticAberration=Dh;exports.CircularBuffer=ki;exports.ClearFlags=Co;exports.ClipExtrapolation=Ln;exports.Collider=di;exports.Collision=mw;exports.CollisionDetectionMode=Xu;exports.ColorAdjustments=$o;exports.ColorBySpeedModule=yl;exports.ColorOverLifetimeModule=yf;exports.Component=lP;exports.Component$1=D;exports.ComponentLifecycleEvents=nh;exports.Components=cT;exports.ConnectionEvents=q0;exports.ContactPoint=pw;exports.ContactShadows=yh;exports.Context=X;exports.ContextArgs=K1;exports.ContextEvent=he;exports.ContextRegistry=re;exports.ControlTrackHandler=Ef;exports.CustomBranding=qr;exports.CustomShader=pu;exports.DefaultReflectionMode=su;exports.Deletable=zg;exports.DeleteBox=qa;exports.DepthOfField=Mn;exports.DeviceFlag=tf;exports.DocumentExtension=$x;exports.DragControls=cr;exports.DragMode=Ng;exports.DropListener=js;exports.Duplicatable=$g;exports.EffectWrapper=Wc;exports.EmissionModule=Ns;exports.EmphasizeOnClick=cl;exports.EngineLoadingView=Cu;exports.EnvironmentScene=If;exports.EventList=ye;exports.EventListEvent=Qu;exports.EventSystem=Qt;exports.EventTrigger=sf;exports.FieldWithDefault=Bw;exports.FileReference=Dc;exports.FileReferenceSerializer=Fv;exports.FileSpawnModel=MM;exports.File_Event=Sw;exports.FixedJoint=Py;exports.Fog=pl;exports.FrameEvent=we;exports.GENERATOR=Bu;exports.GameObject=C;exports.Gizmos=V;exports.GltfExport=Zg;exports.GltfExportBox=Yg;exports.Gradient=Yr;exports.Graphic=Mh;exports.GraphicRaycaster=Yu;exports.Graphics=Mr;exports.GridHelper=ml;exports.GridLayoutGroup=yy;exports.GroundProjectedEnv=ss;exports.GroupActionModel=yo;exports.HideFlags=Ku;exports.HideOnStart=Qa;exports.HingeJoint=kh;exports.HorizontalLayoutGroup=gy;exports.HostData=t1;exports.Image=vl;exports.ImageReference=Lc;exports.ImageReferenceSerializer=Bv;exports.InheritVelocityModule=Ry;exports.Input=N0;exports.InputEventQueue=oi;exports.InputEvents=Re;exports.InputField=Vy;exports.InstanceHandle=zc;exports.InstancingHandler=Xa;exports.InstancingUtil=Wi;exports.InstantiateEvent=hv;exports.InstantiateIdProvider=bt;exports.InstantiateOptions=Sn;exports.Interactable=Ug;exports.JoinedRoomResponse=MC;exports.KeyEventArgs=mC;exports.Keyframe=ai;exports.LODGroup=Eh;exports.LODModel=gl;exports.LeftRoomResponse=OC;exports.Light=pi;exports.LightData=$v;exports.LimitVelocityOverLifetimeModule=lt;exports.LoadingElementOptions=QE;exports.LogStats=Fg;exports.LogType=Mi;exports.LookAt=$y;exports.LookAtConstraint=Ur;exports.MainModule=It;exports.MarkerType=Uy;exports.MaskableGraphic=Oh;exports.Mathf=z;exports.MeshCollider=jo;exports.MeshRenderer=bh;exports.MinMaxCurve=q;exports.MinMaxGradient=Kr;exports.NEKeyboardEvent=ql;exports.NEPointerEvent=ys;exports.NeedleButtonElement=Yy;exports.NeedleEngineWebComponent=Qy;exports.NeedleMenu=rs;exports.NeedlePatchesKey=kd;exports.NeedleXRController=sg;exports.NeedleXRSession=J;exports.NeedleXRSync=Y0;exports.NeedleXRUtils=Z0;exports.NestedGltf=pf;exports.NetworkConnection=Q0;exports.NetworkedStreamEvents=Nn;exports.NetworkedStreams=mh;exports.Networking=Oy;exports.NewInstanceModel=uv;exports.NoiseModule=be;exports.ObjectRaycaster=Ei;exports.ObjectUtils=Do;exports.OffsetConstraint=Qr;exports.OneEuroFilter=Md;exports.OneEuroFilterXYZ=Gm;exports.OpenURL=wl;exports.OrbitControls=ge;exports.Outline=fl;exports.OwnershipEvent=X0;exports.OwnershipModel=lg;exports.PUBLIC_KEY=_a;exports.Padding=Gr;exports.ParticleBurst=vu;exports.ParticleSubEmitter=Ey;exports.ParticleSystem=$c;exports.ParticleSystemBaseBehaviour=Vo;exports.ParticleSystemRenderer=en;exports.ParticleSystemShapeType=bu;exports.PeerHandle=Ia;exports.PeerNetworking=G0;exports.Physics=Rc;exports.PhysicsExtension=uy;exports.PhysicsMaterialCombine=ht;exports.PixelationEffect=Ih;exports.PlayAnimationOnClick=Nc;exports.PlayAudioOnClick=Oo;exports.PlayableDirector=tl;exports.PlayerColor=Ja;exports.PlayerState=yn;exports.PlayerStateEvent=tx;exports.PlayerSync=cy;exports.PlayerView=zv;exports.PlayerViewManager=Nv;exports.PointerEventData=ph;exports.PointerType=zu;exports.PostProcessingEffect=Ye;exports.PostProcessingEffectOrder=it;exports.PostProcessingHandler=Dy;exports.PreliminaryAction=hl;exports.PreliminaryTrigger=xh;exports.PrimitiveType=Or;exports.Progress=oe;exports.PromiseAllWithErrors=Wm;exports.PromiseErrorResult=Xp;exports.RGBAColor=ie;exports.RapierPhysics=Pu;exports.RawImage=Lf;exports.RaycastOptions=Jn;exports.Rect=nx;exports.RectTransform=xn;exports.ReflectionProbe=Uc;exports.RegisteredAnimationInfo=_o;exports.RemoteSkybox=xf;exports.RenderTexture=Sr;exports.RenderTextureSerializer=hw;exports.Renderer=Ti;exports.RendererData=Vv;exports.RendererLightmap=yu;exports.Rigidbody=ot;exports.RigidbodyConstraints=Ne;exports.RoomEvents=ee;exports.RotationBySpeedModule=Ji;exports.RotationOverLifetimeModule=Pn;exports.SceneLightSettings=uu;exports.SceneSwitcher=He;exports.ScreenCapture=Wo;exports.ScreenSpaceAmbientOcclusion=Vs;exports.ScreenSpaceAmbientOcclusionN8=On;exports.SendQueue=fn;exports.SerializationContext=bg;exports.SetActiveOnClick=ny;exports.ShadowCatcher=Uh;exports.ShapeModule=ky;exports.SharpeningEffect=Bh;exports.SignalAsset=kf;exports.SignalReceiver=Wh;exports.SignalReceiverEvent=$h;exports.SignalTrackHandler=Hc;exports.Size=ix;exports.SizeBySpeedModule=mi;exports.SizeOverLifetimeModule=Zr;exports.SkinnedMeshRenderer=Qg;exports.SmoothFollow=Cf;exports.SpatialGrabRaycaster=Tr;exports.SpatialHtml=qh;exports.SpatialTrigger=Pf;exports.SpatialTriggerReceiver=Zn;exports.SpectatorCamera=Mf;exports.SphereCollider=rl;exports.SphereIntersection=dg;exports.SphereOverlapResult=gw;exports.Sprite=Fs;exports.SpriteData=Ba;exports.SpriteRenderer=ui;exports.SpriteSheet=Ka;exports.StateMachineBehaviour=pP;exports.StreamEndedEvent=Eg;exports.StreamReceivedEvent=yw;exports.SubEmitterSystem=wu;exports.SyncedCamera=jy;exports.SyncedRoom=kn;exports.SyncedTransform=es;exports.TapGestureTrigger=oy;exports.TeleportTarget=df;exports.TestRunner=By;exports.TestSceneUtils=nT;exports.TestSimulateUserData=Fy;exports.Text=Dt;exports.TextBuilder=py;exports.TextExtension=ff;exports.TextureSheetAnimationModule=jt;exports.TiltShiftEffect=cs;exports.Time=Wv;exports.ToneMappingEffect=Eo;exports.TrackHandler=Hh;exports.TrackType=_i;exports.TrailModule=je;exports.TransformData=We;exports.TransformGizmo=ia;exports.TriggerBuilder=wt;exports.TriggerModel=Po;exports.TypeStore=k;exports.UIRaycastUtils=kg;exports.UIRootComponent=Ch;exports.USDDocument=Jg;exports.USDObject=Et;exports.USDWriter=$w;exports.USDZExporter=Kn;exports.USDZExporter$1=Ww;exports.USDZText=hr;exports.USDZUIExtension=by;exports.UriSerializer=dw;exports.UsageMarker=_h;exports.UserJoinedOrLeftRoomModel=kC;exports.VERSION=_n;exports.VariantAction=ty;exports.VelocityOverLifetimeModule=ze;exports.VerticalLayoutGroup=my;exports.VideoPlayer=rt;exports.ViewDevice=wo;exports.Vignette=ta;exports.VisibilityAction=Sh;exports.Voip=Io;exports.Volume=bl;exports.VolumeParameter=U;exports.VolumeProfile=_f;exports.WaitForFrames=E1;exports.WaitForPromise=Uv;exports.WaitForSeconds=xg;exports.Watch=Rs;exports.WebARCameraBackground=Qh;exports.WebARSessionRoot=is;exports.WebXR=uf;exports.WebXRButtonFactory=Mo;exports.WebXRImageTracking=qc;exports.WebXRImageTrackingModel=Hs;exports.WebXRPlaneTracking=Gs;exports.WebXRTrackedImage=Gc;exports.XRControllerFollow=Ws;exports.XRControllerModel=ns;exports.XRControllerMovement=Ai;exports.XRFlag=Vi;exports.XRRig=Bf;exports.XRState=Xt;exports.XRStateFlag=Bn;exports.__Ignore=Wx;exports.__internalNotifyObjectDestroyed=sv;exports.activeInHierarchyFieldName=Es;exports.addAttributeChangeCallback=h0;exports.addComponent=Oi;exports.addCustomExtensionPlugin=XM;exports.addNewComponent=wr;exports.addPatch=Fu;exports.apply=$u;exports.applyHMRChanges=aP;exports.applyPrototypeExtensions=Cv;exports.beginListenDestroy=dv;exports.beginListenInstantiate=pv;exports.binaryIdentifierCasts=og;exports.build_scene_functions=Y1;exports.builtinComponentKeyName=tr;exports.calculateProgress01=Xy;exports.clearMessages=RS;exports.colorSerializer=IP;exports.compareAssociation=_v;exports.componentSerializer=jd;exports.copyTexture=M0;exports.createMotion=nw;exports.debugNet=Jt;exports.debugOwner=Xl;exports.decompressGpuTexture=Xw;exports.deepClone=Zc;exports.delay=bn;exports.delayForFrames=Jc;exports.deserializeObject=iu;exports.destroy=Ri;exports.destroyComponentInstance=Ov;exports.determineMimeTypeFromExtension=Cw;exports.disposeObjectResources=Se;exports.disposeStream=Vn;exports.editorGuidKeyName=lc;exports.enableSpatialConsole=br;exports.euler=BP;exports.eventListSerializer=NP;exports.exportAsGLTF=rT;exports.findByGuid=wg;exports.findObjectOfType=ch;exports.findObjectsOfType=Rv;exports.findResourceUsers=fg;exports.fitObjectIntoVolume=k0;exports.foreachComponent=Rr;exports.foreachComponentEnumerator=Hu;exports.forward=WS;exports.generateQRCode=u0;exports.generateSeed=fv;exports.getBoundingBox=li;exports.getCameraController=b0;exports.getComponent=jr;exports.getComponentInChildren=lh;exports.getComponentInParent=Ac;exports.getComponents=ah;exports.getComponentsInChildren=nl;exports.getComponentsInParent=Vu;exports.getFormattedDate=Uw;exports.getIconElement=_t;exports.getIconTexture=gm;exports.getLoader=vn;exports.getOrAddComponent=rh;exports.getParam=S;exports.getParentHierarchyPath=qS;exports.getPath=lS;exports.getPeerOptions=xC;exports.getPeerjsInstance=H0;exports.getResourceUserCount=GC;exports.getTempColor=x0;exports.getTempQuaternion=un;exports.getTempVector=$;exports.getUrlParams=Kc;exports.getVisibleInCustomShadowRendering=O0;exports.getWorldDirection=S0;exports.getWorldEuler=Qm;exports.getWorldPosition=Q;exports.getWorldQuaternion=_e;exports.getWorldRotation=ju;exports.getWorldScale=Ue;exports.hasCommercialLicense=Yn;exports.hasIndieLicense=dh;exports.hasPointerEventComponent=lu;exports.hasProLicense=Qn;exports.hideDebugConsole=A0;exports.imageToCanvas=Qw;exports.instantiate=Er;exports.invokeLoadedImportPluginHooks=Lw;exports.invokeXRSessionEnd=z0;exports.invokeXRSessionStart=U0;exports.isActiveInHierarchy=Ev;exports.isActiveSelf=sl;exports.isAndroidDevice=pS;exports.isAnimationAction=P0;exports.isComponent=fw;exports.isDebugMode=sS;exports.isDesktop=hS;exports.isDestroyed=kr;exports.isDevEnvironment=j;exports.isDisposed=WC;exports.isExporting=sT;exports.isGLTFModel=uw;exports.isHostedOnGlitch=n0;exports.isHotReloadEnabled=vm;exports.isHotReloading=oP;exports.isIPad=uS;exports.isIconElement=qv;exports.isLocalNetwork=Yt;exports.isMacOS=gS;exports.isMobileDevice=dS;exports.isMozillaXR=mS;exports.isQuest=bS;exports.isResourceTrackingEnabled=tv;exports.isSafari=_S;exports.isUsingInstancing=Wu;exports.isiOS=yS;exports.isiPad=fS;exports.loadAsset=$E;exports.loadSync=qy;exports.logHierarchy=qd;exports.lookAtInverse=jS;exports.lookAtObject=eh;exports.lookAtScreenPoint=BS;exports.makeId=rS;exports.makeIdFromRandomWords=a0;exports.makeNameSafe=Xi;exports.markAsInstancedRendered=Tv;exports.microphonePermissionsGranted=vS;exports.nameof=nS;exports.nameofFactory=o0;exports.objectSerializer=cw;exports.offXRSessionEnd=pC;exports.offXRSessionStart=fC;exports.onAfterRender=OP;exports.onBeforeRender=MP;exports.onClear=CP;exports.onDestroy=PP;exports.onInitialized=sw;exports.onStart=ow;exports.onUpdate=rw;exports.onXRSessionEnd=ng;exports.onXRSessionStart=Uu;exports.parseSync=Ix;exports.placeOnSurface=R0;exports.postprocessFBXMaterials=Zm;exports.prefix=RP;exports.pushState=r0;exports.randomNumber=aS;exports.registerBinaryType=rg;exports.registerComponent=Gu;exports.registerComponentExtension=Gg;exports.registerCustomEffectType=tn;exports.registerExportExtensions=qg;exports.registerExtensions=gu;exports.registerHotReloadType=Jv;exports.registerLoader=tg;exports.registerPrefabProvider=gv;exports.registerPrototypeExtensions=Pv;exports.registerType=r1;exports.relativePathPrefix=c0;exports.removeAttributeChangeCallback=d0;exports.removeComponent=vg;exports.removeCustomImportExtensionType=QM;exports.removePatch=dC;exports.resolveUrl=To;exports.sanitizeString=l0;exports.saveImage=Tx;exports.screenshot=ME;exports.screenshot2=Hy;exports.sendDestroyed=mg;exports.serializable=m;exports.serializeObject=vv;exports.serializeable=Br;exports.setActive=dc;exports.setAllowBalloonMessages=g0;exports.setAllowOverlayMessages=PS;exports.setAutoFitEnabled=Hd;exports.setCameraController=Kp;exports.setDestroyed=Lv;exports.setDevEnvironment=tC;exports.setDisposable=ug;exports.setDontDestroy=fa;exports.setOrAddParamsToUrl=qp;exports.setParam=oS;exports.setParamWithoutReload=Mc;exports.setPeerOptions=SC;exports.setResourceTrackingEnabled=$C;exports.setState=Vm;exports.setVisibleInCustomShadowRendering=Km;exports.setWorldEuler=Ym;exports.setWorldPosition=st;exports.setWorldPositionXYZ=Pr;exports.setWorldQuaternion=Gi;exports.setWorldQuaternionXYZW=Xm;exports.setWorldRotation=C0;exports.setWorldRotationXYZ=th;exports.setWorldScale=za;exports.showBalloonError=ih;exports.showBalloonMessage=Ee;exports.showBalloonWarning=me;exports.showDebugConsole=Jm;exports.slerp=IS;exports.syncDestroy=sh;exports.syncField=ly;exports.syncInstantiate=gg;exports.textureToCanvas=XS;exports.tryCastBinary=$0;exports.tryDetermineMimetypeFromBinary=Mw;exports.tryDetermineMimetypeFromURL=Pw;exports.tryFindObject=Ua;exports.tryGetGuid=W0;exports.unregisterHotReloadType=ew;exports.unwatchWrite=$m;exports.useForAutoFit=v0;exports.validate=St;exports.watchWrite=Iu;
1606
+ `),ce(this,gr).innerHTML=ce(this,$t).innerHTML,ce(this,gr).style.cssText="display: flex; align-items: center; justify-content: center;",ce(this,$t).innerHTML=ce(this,gr).outerHTML,ce(this,mr).innerHTML=ce(this,$t).outerHTML,ce(this,mr).prepend(ce(this,yr)),ou(ym,{element:ce(this,mr)}),(n=ce(this,Fa))==null||n.disconnect(),ce(this,Fa)??rn(this,Fa,new MutationObserver(()=>Ml(this,il,Nx).call(this))),ce(this,Fa).observe(ce(this,$t),{attributes:!0}),Hp&&console.log("Needle Button updated")},Nx=function(){ce(this,$t)&&(ce(this,$t).style.display==="none"?this.style.display="none":this.style.display==="none"&&(this.style.display=""))},Yc=new WeakMap,r(Yy,"observedAttributes",["ar","vr","quicklook"]);typeof window<"u"&&!window.customElements.get(t0)&&window.customElements.define(t0,Yy);const Hl=S("debugavatar");class Ky{constructor(t,e,i,n){r(this,"root");r(this,"head");r(this,"leftHand");r(this,"rigthHand");var s;this.root=t,this.head=e,this.leftHand=i,this.rigthHand=n,(s=this.root)==null||s.traverse(a=>a.layers.set(2))}get isValid(){return this.head!==null&&this.head!==void 0}}class Vx{constructor(){r(this,"avatarRegistryUrl",null)}async getOrCreateNewAvatarInstance(t,e){if(!e)return console.error("Can not create avatar: failed to provide id or root object"),null;let i=null;if(typeof e=="string"){if(i=await this.loadAvatar(t,e),!i){const s=new Sn;i=C.instantiate(Ua(e,t.scene),s)}}else i=e;if(!i)return null;const n=this.findAvatar(i);return n.isValid?(Hl&&console.log("[Custom Avatar] valid config",e,Hl?n:""),n):(console.warn("[Custom Avatar] config isn't valid",e,Hl?n:""),null)}async loadAvatar(t,e){if(console.assert(e!=null&&typeof e=="string","Avatar id must not be null"),e.length<=0||!e)return null;if(Hl&&console.log("[Custom Avatar] "+e+", loading..."),e.endsWith(".glb")||(e+=".glb"),this.avatarRegistryUrl===null){const n=await fetch("./"+e);let s=null;if(n.ok){const l=await n.blob();l&&(s=await l.arrayBuffer())}if(!s)return null;const a=await vn().parseSync(t,s,null,0);return(a==null?void 0:a.scene)??null}const i=new G.GLTFLoader;return Pg(i,t),new Promise((n,s)=>{const a=this.avatarRegistryUrl+"/"+e;i.load(a,async l=>{await vn().createBuiltinComponents(t,a,l,null,void 0),n(l.scene)},l=>{Hl&&console.log("[Custom Avatar] "+l.loaded/l.total*100+"% loaded of "+l.total/1024+"kB")},l=>{console.error("[Custom Avatar] Error when loading: "+l),n(null)})})}cacheModel(t,e){}findAvatar(t){const e=t;let i=e;i.children.length==1&&(i=t.children[0]);let n=this.findAvatarPart(i,["head"]);const s=this.findAvatarPart(i,["left","hand"]),a=this.findAvatarPart(i,["right","hand"]);if(!n){n=e;const c=new d.Vector3;new d.Box3().setFromObject(n).getSize(c);const h=Math.max(c.x,c.y,c.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+h+" meters! Should be < 0.3m"),h>.3&&n.scale.multiplyScalar(1/h*.3)}return new Ky(e,n,s,a)}findAvatarPart(t,e){const i=t.name.toLowerCase();let n=!0;for(const s of e){if(!n)break;i.indexOf(s)===-1&&(n=!1)}if(n)return t;if(t.children)for(const s of t.children){const a=this.findAvatarPart(s,e);if(a)return a}return null}handleCustomAvatarErrors(t){if(!t.ok)throw Error(t.statusText);return t}}class $x{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(t){}}class Wx{}const cT=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:fe,ActionCollection:Zw,ActionModel:xi,AlignmentConstraint:uh,Animation:Tt,AnimationCurve:Th,AnimationExtension:rf,AnimationTrackHandler:Rf,Animator:xt,AnimatorController:Hi,Antialiasing:Lh,AudioExtension:Wr,AudioListener:Ms,AudioSource:qi,AudioTrackHandler:el,Avatar:ko,AvatarBlink_Simple:zr,AvatarEyeLook_Rotation:Dg,AvatarLoader:Vx,AvatarMarker:At,AvatarModel:Ky,Avatar_Brain_LookAt:Fc,Avatar_MouthShapes:gh,Avatar_MustacheShake:Ag,Avatar_POI:Ts,AxesHelper:ol,BaseUIComponent:Qi,BasicIKConstraint:jg,BehaviorExtension:dy,BehaviorModel:vt,BloomEffect:vf,BoxCollider:ef,BoxGizmo:Xr,BoxHelperComponent:ts,Button:$s,CallInfo:Cs,Camera:ri,CameraTargetReachedEvent:Bc,Canvas:Za,CanvasGroup:Ro,CapsuleCollider:As,ChangeMaterialOnClick:iy,ChangeTransformOnClick:Hr,CharacterController:Nr,CharacterControllerInput:Is,ChromaticAberration:Dh,Collider:di,ColorAdjustments:$o,ColorBySpeedModule:yl,ColorOverLifetimeModule:yf,ContactShadows:yh,ControlTrackHandler:Ef,CustomBranding:qr,Deletable:zg,DeleteBox:qa,DepthOfField:Mn,DeviceFlag:tf,DocumentExtension:$x,DragControls:cr,DropListener:js,Duplicatable:$g,EffectWrapper:Wc,EmissionModule:Ns,EmphasizeOnClick:cl,EnvironmentScene:If,EventList:ye,EventListEvent:Qu,EventSystem:Qt,EventTrigger:sf,FieldWithDefault:Bw,FixedJoint:Py,Fog:pl,GltfExport:Zg,GltfExportBox:Yg,Gradient:Yr,Graphic:Mh,GraphicRaycaster:Yu,GridHelper:ml,GridLayoutGroup:yy,GroundProjectedEnv:ss,GroupActionModel:yo,HideOnStart:Qa,HingeJoint:kh,HorizontalLayoutGroup:gy,Image:vl,InheritVelocityModule:Ry,InputField:Vy,InstanceHandle:zc,InstancingHandler:Xa,Interactable:Ug,Keyframe:ai,LODGroup:Eh,LODModel:gl,Light:pi,LimitVelocityOverLifetimeModule:lt,LogStats:Fg,LookAt:$y,LookAtConstraint:Ur,MainModule:It,MaskableGraphic:Oh,MeshCollider:jo,MeshRenderer:bh,MinMaxCurve:q,MinMaxGradient:Kr,NeedleMenu:rs,NestedGltf:pf,Networking:Oy,NoiseModule:be,ObjectRaycaster:Ei,OffsetConstraint:Qr,OpenURL:wl,OrbitControls:ge,Outline:fl,Padding:Gr,ParticleBurst:vu,ParticleSubEmitter:Ey,ParticleSystem:$c,ParticleSystemRenderer:en,PhysicsExtension:uy,PixelationEffect:Ih,PlayAnimationOnClick:Nc,PlayAudioOnClick:Oo,PlayableDirector:tl,PlayerColor:Ja,PointerEventData:ph,PostProcessingHandler:Dy,PreliminaryAction:hl,PreliminaryTrigger:xh,RawImage:Lf,Rect:nx,RectTransform:xn,ReflectionProbe:Uc,RegisteredAnimationInfo:_o,RemoteSkybox:xf,Renderer:Ti,RendererLightmap:yu,Rigidbody:ot,RotationBySpeedModule:Ji,RotationOverLifetimeModule:Pn,SceneSwitcher:He,ScreenCapture:Wo,ScreenSpaceAmbientOcclusion:Vs,ScreenSpaceAmbientOcclusionN8:On,SetActiveOnClick:ny,ShadowCatcher:Uh,ShapeModule:ky,SharpeningEffect:Bh,SignalAsset:kf,SignalReceiver:Wh,SignalReceiverEvent:$h,SignalTrackHandler:Hc,Size:ix,SizeBySpeedModule:mi,SizeOverLifetimeModule:Zr,SkinnedMeshRenderer:Qg,SmoothFollow:Cf,SpatialGrabRaycaster:Tr,SpatialHtml:qh,SpatialTrigger:Pf,SpatialTriggerReceiver:Zn,SpectatorCamera:Mf,SphereCollider:rl,Sprite:Fs,SpriteData:Ba,SpriteRenderer:ui,SpriteSheet:Ka,SubEmitterSystem:wu,SyncedCamera:jy,SyncedRoom:kn,SyncedTransform:es,TapGestureTrigger:oy,TeleportTarget:df,TestRunner:By,TestSimulateUserData:Fy,Text:Dt,TextBuilder:py,TextExtension:ff,TextureSheetAnimationModule:jt,TiltShiftEffect:cs,ToneMappingEffect:Eo,TrailModule:je,TransformData:We,TransformGizmo:ia,TriggerBuilder:wt,TriggerModel:Po,UIRaycastUtils:kg,UIRootComponent:Ch,USDZExporter:Kn,USDZText:hr,USDZUIExtension:by,UsageMarker:_h,VariantAction:ty,VelocityOverLifetimeModule:ze,VerticalLayoutGroup:my,VideoPlayer:rt,Vignette:ta,VisibilityAction:Sh,Voip:Io,Volume:bl,VolumeParameter:U,VolumeProfile:_f,WebARCameraBackground:Qh,WebARSessionRoot:is,WebXR:uf,WebXRImageTracking:qc,WebXRImageTrackingModel:Hs,WebXRPlaneTracking:Gs,WebXRTrackedImage:Gc,XRControllerFollow:Ws,XRControllerModel:ns,XRControllerMovement:Ai,XRFlag:Vi,XRRig:Bf,XRState:Xt,__Ignore:Wx},Symbol.toStringTag,{value:"Module"})),Mu=S("debugmissingcamera");re.registerCallback(he.MissingCamera,o=>{var l,c,h;Mu&&console.warn("Creating missing camera");const t=o.context.scene,e=new d.PerspectiveCamera;e.name="Default Fallback Camera",t.add(e);const i=new ri;if(i.sourceId=((c=(l=o.files)==null?void 0:l[0])==null?void 0:c.src)??"unknown",i.fieldOfView=35,o.context.domElement.getAttribute("transparent")!=null)i.clearFlags=Co.Uninitialized;else if((h=o.context.domElement.getAttribute("background-image"))!=null&&h.length||o.context.lightmaps.tryGetSkybox(i.sourceId))i.clearFlags=Co.Skybox,o.context.domElement.getAttribute("background-blurriness")===null&&(o.context.scene.backgroundBlurriness=.2);else{if(i.clearFlags=Co.SolidColor,!o.context.domElement.getAttribute("background-color")){let u="#efefef";typeof window!==void 0&&window.matchMedia("(prefers-color-scheme: dark)").matches&&(u="#1f1f1f"),t.background=new d.Color(u)}if(!t.environment){const u=new d.PMREMGenerator$1(o.context.renderer),f=new If("neutral");t.environment=u.fromScene(f,.025).texture}}const s=wr(e,i,!0);e.position.x=0,e.position.y=1,e.position.z=2;const a=o.context.domElement;return(a==null?void 0:a.cameraControls)!=!1&&Hx(o.context,s),s});re.registerCallback(he.ContextCreated,o=>{if(!o.context.mainCamera){Mu&&console.log("Will not auto-fit because a default camera exists");return}const t=o.context.domElement;if((t==null?void 0:t.cameraControls)==!0){const e=b0(o.context.mainCamera);if((e==null?void 0:e.isCameraController)==!0){Mu&&console.log("Will not auto-fit because a camera controller exists");return}Hx(o.context)}});function Hx(o,t){t=t??o.mainCameraComponent;const e=t==null?void 0:t.gameObject;if(Mu&&console.log("Creating default camera controls",t==null?void 0:t.name),e){const i=rh(e,ge);i.sourceId=(t==null?void 0:t.sourceId)??"unknown";const n=o.domElement.getAttribute("auto-rotate");if(i.autoRotate=n!=null&&n!="0"&&(n==null?void 0:n.toLowerCase())!="false",i.autoRotateSpeed=.5,i.autoFit=!0,i.autoRotate&&n){const s=parseFloat(n);isNaN(s)||(i.autoRotateSpeed=s)}}else console.warn("Missing camera object, can not add orbit controls")}re.registerCallback(he.ContextCreated,o=>{const t=o.context.domElement.getAttribute("autoplay");if(t!==void 0&&(t===""||t==="true"||t==="1")&&o.files)for(const e of o.files)C.foreachComponent(e.file.scene,n=>{if(n.enabled!==!1){if(n instanceof Tt&&n.playAutomatically||n instanceof xt||n instanceof tl&&n.playOnAwake===!0)return!0;if(n instanceof Tt)return n.playAutomatically=!0,!0;if(n instanceof tl)return n.playOnAwake=!0,!0}},!0)!==!0&&Ha.assignAnimationsFromFile(e.file,{createAnimationComponent:(n,s)=>Oi(n,Tt)})});class hT extends ae.WorkerBase{constructor(){super(new Worker(new URL("/generateMeshBVH.worker-BaNp_Xtp.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:zf&&zf.tagName.toUpperCase()==="SCRIPT"&&zf.src||new URL("needle-engine.bundle-DQ8S9diA.umd.cjs",document.baseURI).href),{type:"module"})),this.name="GenerateMeshBVHWorker"}runTask(t,e,i={}){return new Promise((n,s)=>{if(e.getAttribute("position").isInterleavedBufferAttribute||e.index&&e.index.isInterleavedBufferAttribute)throw new Error("GenerateMeshBVHWorker: InterleavedBufferAttribute are not supported for the geometry attributes.");t.onerror=h=>{s(new Error(`[GenerateMeshBVHWorker] ${h.message||"Unknown error. Please check the server console. If you're using vite try adding 'three-mesh-bvh' to 'optimizeDeps.exclude' in your vite.config.js"}`))},t.onmessage=h=>{const{data:u}=h;if(u.error)s(new Error(u.error)),t.onmessage=null;else if(u.serialized){const{serialized:f,position:p}=u,g=ae.MeshBVH.deserialize(f,e,{setIndex:!1}),y=Object.assign({setBoundingBox:!0},i);if(e.attributes.position.array=p,f.index)if(e.index)e.index.array=f.index;else{const b=new d.BufferAttribute(f.index,1,!1);e.setIndex(b)}y.setBoundingBox&&(e.boundingBox=g.getBoundingBox(new d.Box3)),i.onProgress&&i.onProgress(u.progress),n(g),t.onmessage=null}else i.onProgress&&i.onProgress(u.progress)};const a=e.index?e.index.array:null,l=e.attributes.position.array,c=[l];a&&c.push(a),t.postMessage({index:a,position:l,options:{...i,onProgress:null,includedProgressCallback:!!i.onProgress,groups:[...e.groups]}},c.map(h=>h.buffer).filter(h=>typeof SharedArrayBuffer>"u"||!(h instanceof SharedArrayBuffer)))})}}const dT=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:hT},Symbol.toStringTag,{value:"Module"}));exports.$physicsKey=nM;exports.ActionBuilder=fe;exports.ActionCollection=Zw;exports.ActionModel=xi;exports.Addressables=jv;exports.AlignmentConstraint=uh;exports.AmbientMode=Da;exports.Animation=Tt;exports.AnimationCurve=Th;exports.AnimationExtension=rf;exports.AnimationTrackHandler=Rf;exports.AnimationUtils=Ha;exports.Animator=xt;exports.AnimatorConditionMode=so;exports.AnimatorController=Hi;exports.AnimatorControllerParameterType=Mg;exports.AnimatorStateInfo=Zl;exports.Antialiasing=Lh;exports.Application=wn;exports.AssetDatabase=J0;exports.AssetReference=te;exports.AudioExtension=Wr;exports.AudioListener=Ms;exports.AudioSource=qi;exports.AudioTrackHandler=el;exports.Avatar=ko;exports.AvatarBlink_Simple=zr;exports.AvatarEyeLook_Rotation=Dg;exports.AvatarLoader=Vx;exports.AvatarMarker=At;exports.AvatarModel=Ky;exports.Avatar_Brain_LookAt=Fc;exports.Avatar_MouthShapes=gh;exports.Avatar_MustacheShake=Ag;exports.Avatar_POI=Ts;exports.Axes=wa;exports.AxesHelper=ol;exports.BUILD_TIME=eg;exports.BaseUIComponent=Qi;exports.BasicIKConstraint=jg;exports.BehaviorExtension=dy;exports.BehaviorModel=vt;exports.BloomEffect=vf;exports.BoxCollider=ef;exports.BoxGizmo=Xr;exports.BoxHelperComponent=ts;exports.Button=$s;exports.ButtonsFactory=zn;exports.CallDirection=_w;exports.CallInfo=Cs;exports.Camera=ri;exports.CameraTargetReachedEvent=Bc;exports.Canvas=Za;exports.CanvasGroup=Ro;exports.CapsuleCollider=As;exports.ChangeMaterialOnClick=iy;exports.ChangeTransformOnClick=Hr;exports.CharacterController=Nr;exports.CharacterControllerInput=Is;exports.ChromaticAberration=Dh;exports.CircularBuffer=ki;exports.ClearFlags=Co;exports.ClipExtrapolation=Ln;exports.Collider=di;exports.Collision=mw;exports.CollisionDetectionMode=Xu;exports.ColorAdjustments=$o;exports.ColorBySpeedModule=yl;exports.ColorOverLifetimeModule=yf;exports.Component=lP;exports.Component$1=D;exports.ComponentLifecycleEvents=nh;exports.Components=cT;exports.ConnectionEvents=q0;exports.ContactPoint=pw;exports.ContactShadows=yh;exports.Context=X;exports.ContextArgs=K1;exports.ContextEvent=he;exports.ContextRegistry=re;exports.ControlTrackHandler=Ef;exports.CustomBranding=qr;exports.CustomShader=pu;exports.DefaultReflectionMode=su;exports.Deletable=zg;exports.DeleteBox=qa;exports.DepthOfField=Mn;exports.DeviceFlag=tf;exports.DocumentExtension=$x;exports.DragControls=cr;exports.DragMode=Ng;exports.DropListener=js;exports.Duplicatable=$g;exports.EffectWrapper=Wc;exports.EmissionModule=Ns;exports.EmphasizeOnClick=cl;exports.EngineLoadingView=Cu;exports.EnvironmentScene=If;exports.EventList=ye;exports.EventListEvent=Qu;exports.EventSystem=Qt;exports.EventTrigger=sf;exports.FieldWithDefault=Bw;exports.FileReference=Dc;exports.FileReferenceSerializer=Fv;exports.FileSpawnModel=MM;exports.File_Event=Sw;exports.FixedJoint=Py;exports.Fog=pl;exports.FrameEvent=we;exports.GENERATOR=Bu;exports.GameObject=C;exports.Gizmos=V;exports.GltfExport=Zg;exports.GltfExportBox=Yg;exports.Gradient=Yr;exports.Graphic=Mh;exports.GraphicRaycaster=Yu;exports.Graphics=Mr;exports.GridHelper=ml;exports.GridLayoutGroup=yy;exports.GroundProjectedEnv=ss;exports.GroupActionModel=yo;exports.HideFlags=Ku;exports.HideOnStart=Qa;exports.HingeJoint=kh;exports.HorizontalLayoutGroup=gy;exports.HostData=t1;exports.Image=vl;exports.ImageReference=Lc;exports.ImageReferenceSerializer=Bv;exports.InheritVelocityModule=Ry;exports.Input=N0;exports.InputEventQueue=oi;exports.InputEvents=Re;exports.InputField=Vy;exports.InstanceHandle=zc;exports.InstancingHandler=Xa;exports.InstancingUtil=Wi;exports.InstantiateEvent=hv;exports.InstantiateIdProvider=bt;exports.InstantiateOptions=Sn;exports.Interactable=Ug;exports.JoinedRoomResponse=MC;exports.KeyEventArgs=mC;exports.Keyframe=ai;exports.LODGroup=Eh;exports.LODModel=gl;exports.LeftRoomResponse=OC;exports.Light=pi;exports.LightData=$v;exports.LimitVelocityOverLifetimeModule=lt;exports.LoadingElementOptions=QE;exports.LogStats=Fg;exports.LogType=Mi;exports.LookAt=$y;exports.LookAtConstraint=Ur;exports.MainModule=It;exports.MarkerType=Uy;exports.MaskableGraphic=Oh;exports.Mathf=z;exports.MeshCollider=jo;exports.MeshRenderer=bh;exports.MinMaxCurve=q;exports.MinMaxGradient=Kr;exports.NEKeyboardEvent=ql;exports.NEPointerEvent=ys;exports.NeedleButtonElement=Yy;exports.NeedleEngineWebComponent=Qy;exports.NeedleMenu=rs;exports.NeedlePatchesKey=kd;exports.NeedleXRController=sg;exports.NeedleXRSession=J;exports.NeedleXRSync=Y0;exports.NeedleXRUtils=Z0;exports.NestedGltf=pf;exports.NetworkConnection=Q0;exports.NetworkedStreamEvents=Nn;exports.NetworkedStreams=mh;exports.Networking=Oy;exports.NewInstanceModel=uv;exports.NoiseModule=be;exports.ObjectRaycaster=Ei;exports.ObjectUtils=Do;exports.OffsetConstraint=Qr;exports.OneEuroFilter=Md;exports.OneEuroFilterXYZ=Gm;exports.OpenURL=wl;exports.OrbitControls=ge;exports.Outline=fl;exports.OwnershipEvent=X0;exports.OwnershipModel=lg;exports.PUBLIC_KEY=_a;exports.Padding=Gr;exports.ParticleBurst=vu;exports.ParticleSubEmitter=Ey;exports.ParticleSystem=$c;exports.ParticleSystemBaseBehaviour=Vo;exports.ParticleSystemRenderer=en;exports.ParticleSystemShapeType=bu;exports.PeerHandle=Ia;exports.PeerNetworking=G0;exports.Physics=Rc;exports.PhysicsExtension=uy;exports.PhysicsMaterialCombine=ht;exports.PixelationEffect=Ih;exports.PlayAnimationOnClick=Nc;exports.PlayAudioOnClick=Oo;exports.PlayableDirector=tl;exports.PlayerColor=Ja;exports.PlayerState=yn;exports.PlayerStateEvent=tx;exports.PlayerSync=cy;exports.PlayerView=zv;exports.PlayerViewManager=Nv;exports.PointerEventData=ph;exports.PointerType=zu;exports.PostProcessingEffect=Ye;exports.PostProcessingEffectOrder=it;exports.PostProcessingHandler=Dy;exports.PreliminaryAction=hl;exports.PreliminaryTrigger=xh;exports.PrimitiveType=Or;exports.Progress=oe;exports.PromiseAllWithErrors=Wm;exports.PromiseErrorResult=Xp;exports.RGBAColor=ie;exports.RapierPhysics=Pu;exports.RawImage=Lf;exports.RaycastOptions=Jn;exports.Rect=nx;exports.RectTransform=xn;exports.ReflectionProbe=Uc;exports.RegisteredAnimationInfo=_o;exports.RemoteSkybox=xf;exports.RenderTexture=Sr;exports.RenderTextureSerializer=hw;exports.Renderer=Ti;exports.RendererData=Vv;exports.RendererLightmap=yu;exports.Rigidbody=ot;exports.RigidbodyConstraints=Ne;exports.RoomEvents=ee;exports.RotationBySpeedModule=Ji;exports.RotationOverLifetimeModule=Pn;exports.SceneLightSettings=uu;exports.SceneSwitcher=He;exports.ScreenCapture=Wo;exports.ScreenSpaceAmbientOcclusion=Vs;exports.ScreenSpaceAmbientOcclusionN8=On;exports.SendQueue=fn;exports.SerializationContext=bg;exports.SetActiveOnClick=ny;exports.ShadowCatcher=Uh;exports.ShapeModule=ky;exports.SharpeningEffect=Bh;exports.SignalAsset=kf;exports.SignalReceiver=Wh;exports.SignalReceiverEvent=$h;exports.SignalTrackHandler=Hc;exports.Size=ix;exports.SizeBySpeedModule=mi;exports.SizeOverLifetimeModule=Zr;exports.SkinnedMeshRenderer=Qg;exports.SmoothFollow=Cf;exports.SpatialGrabRaycaster=Tr;exports.SpatialHtml=qh;exports.SpatialTrigger=Pf;exports.SpatialTriggerReceiver=Zn;exports.SpectatorCamera=Mf;exports.SphereCollider=rl;exports.SphereIntersection=dg;exports.SphereOverlapResult=gw;exports.Sprite=Fs;exports.SpriteData=Ba;exports.SpriteRenderer=ui;exports.SpriteSheet=Ka;exports.StateMachineBehaviour=pP;exports.StreamEndedEvent=Eg;exports.StreamReceivedEvent=yw;exports.SubEmitterSystem=wu;exports.SyncedCamera=jy;exports.SyncedRoom=kn;exports.SyncedTransform=es;exports.TapGestureTrigger=oy;exports.TeleportTarget=df;exports.TestRunner=By;exports.TestSceneUtils=nT;exports.TestSimulateUserData=Fy;exports.Text=Dt;exports.TextBuilder=py;exports.TextExtension=ff;exports.TextureSheetAnimationModule=jt;exports.TiltShiftEffect=cs;exports.Time=Wv;exports.ToneMappingEffect=Eo;exports.TrackHandler=Hh;exports.TrackType=_i;exports.TrailModule=je;exports.TransformData=We;exports.TransformGizmo=ia;exports.TriggerBuilder=wt;exports.TriggerModel=Po;exports.TypeStore=k;exports.UIRaycastUtils=kg;exports.UIRootComponent=Ch;exports.USDDocument=Jg;exports.USDObject=Et;exports.USDWriter=$w;exports.USDZExporter=Kn;exports.USDZExporter$1=Ww;exports.USDZText=hr;exports.USDZUIExtension=by;exports.UriSerializer=dw;exports.UsageMarker=_h;exports.UserJoinedOrLeftRoomModel=kC;exports.VERSION=_n;exports.VariantAction=ty;exports.VelocityOverLifetimeModule=ze;exports.VerticalLayoutGroup=my;exports.VideoPlayer=rt;exports.ViewDevice=wo;exports.Vignette=ta;exports.VisibilityAction=Sh;exports.Voip=Io;exports.Volume=bl;exports.VolumeParameter=U;exports.VolumeProfile=_f;exports.WaitForFrames=E1;exports.WaitForPromise=Uv;exports.WaitForSeconds=xg;exports.Watch=Rs;exports.WebARCameraBackground=Qh;exports.WebARSessionRoot=is;exports.WebXR=uf;exports.WebXRButtonFactory=Mo;exports.WebXRImageTracking=qc;exports.WebXRImageTrackingModel=Hs;exports.WebXRPlaneTracking=Gs;exports.WebXRTrackedImage=Gc;exports.XRControllerFollow=Ws;exports.XRControllerModel=ns;exports.XRControllerMovement=Ai;exports.XRFlag=Vi;exports.XRRig=Bf;exports.XRState=Xt;exports.XRStateFlag=Bn;exports.__Ignore=Wx;exports.__internalNotifyObjectDestroyed=sv;exports.activeInHierarchyFieldName=Es;exports.addAttributeChangeCallback=h0;exports.addComponent=Oi;exports.addCustomExtensionPlugin=XM;exports.addNewComponent=wr;exports.addPatch=Fu;exports.apply=$u;exports.applyHMRChanges=aP;exports.applyPrototypeExtensions=Cv;exports.beginListenDestroy=dv;exports.beginListenInstantiate=pv;exports.binaryIdentifierCasts=og;exports.build_scene_functions=Y1;exports.builtinComponentKeyName=tr;exports.calculateProgress01=Xy;exports.clearMessages=RS;exports.colorSerializer=IP;exports.compareAssociation=_v;exports.componentSerializer=jd;exports.copyTexture=M0;exports.createMotion=nw;exports.debugNet=Jt;exports.debugOwner=Xl;exports.decompressGpuTexture=Xw;exports.deepClone=Zc;exports.delay=bn;exports.delayForFrames=Jc;exports.deserializeObject=iu;exports.destroy=Ri;exports.destroyComponentInstance=Ov;exports.determineMimeTypeFromExtension=Cw;exports.disposeObjectResources=Se;exports.disposeStream=Vn;exports.editorGuidKeyName=lc;exports.enableSpatialConsole=br;exports.euler=BP;exports.eventListSerializer=NP;exports.exportAsGLTF=rT;exports.findByGuid=wg;exports.findObjectOfType=ch;exports.findObjectsOfType=Rv;exports.findResourceUsers=fg;exports.fitObjectIntoVolume=k0;exports.foreachComponent=Rr;exports.foreachComponentEnumerator=Hu;exports.forward=WS;exports.generateQRCode=u0;exports.generateSeed=fv;exports.getBoundingBox=li;exports.getCameraController=b0;exports.getComponent=jr;exports.getComponentInChildren=lh;exports.getComponentInParent=Ac;exports.getComponents=ah;exports.getComponentsInChildren=nl;exports.getComponentsInParent=Vu;exports.getFormattedDate=Uw;exports.getIconElement=_t;exports.getIconTexture=gm;exports.getLoader=vn;exports.getOrAddComponent=rh;exports.getParam=S;exports.getParentHierarchyPath=qS;exports.getPath=lS;exports.getPeerOptions=xC;exports.getPeerjsInstance=H0;exports.getResourceUserCount=GC;exports.getTempColor=x0;exports.getTempQuaternion=un;exports.getTempVector=$;exports.getUrlParams=Kc;exports.getVisibleInCustomShadowRendering=O0;exports.getWorldDirection=S0;exports.getWorldEuler=Qm;exports.getWorldPosition=Q;exports.getWorldQuaternion=_e;exports.getWorldRotation=ju;exports.getWorldScale=Ue;exports.hasCommercialLicense=Yn;exports.hasIndieLicense=dh;exports.hasPointerEventComponent=lu;exports.hasProLicense=Qn;exports.hideDebugConsole=A0;exports.imageToCanvas=Qw;exports.instantiate=Er;exports.invokeLoadedImportPluginHooks=Lw;exports.invokeXRSessionEnd=z0;exports.invokeXRSessionStart=U0;exports.isActiveInHierarchy=Ev;exports.isActiveSelf=sl;exports.isAndroidDevice=pS;exports.isAnimationAction=P0;exports.isComponent=fw;exports.isDebugMode=sS;exports.isDesktop=hS;exports.isDestroyed=kr;exports.isDevEnvironment=j;exports.isDisposed=WC;exports.isExporting=sT;exports.isGLTFModel=uw;exports.isHostedOnGlitch=n0;exports.isHotReloadEnabled=vm;exports.isHotReloading=oP;exports.isIPad=uS;exports.isIconElement=qv;exports.isLocalNetwork=Yt;exports.isMacOS=gS;exports.isMobileDevice=dS;exports.isMozillaXR=mS;exports.isQuest=bS;exports.isResourceTrackingEnabled=tv;exports.isSafari=_S;exports.isUsingInstancing=Wu;exports.isiOS=yS;exports.isiPad=fS;exports.loadAsset=$E;exports.loadSync=qy;exports.logHierarchy=qd;exports.lookAtInverse=jS;exports.lookAtObject=eh;exports.lookAtScreenPoint=BS;exports.makeId=rS;exports.makeIdFromRandomWords=a0;exports.makeNameSafe=Xi;exports.markAsInstancedRendered=Tv;exports.microphonePermissionsGranted=vS;exports.nameof=nS;exports.nameofFactory=o0;exports.objectSerializer=cw;exports.offXRSessionEnd=pC;exports.offXRSessionStart=fC;exports.onAfterRender=OP;exports.onBeforeRender=MP;exports.onClear=CP;exports.onDestroy=PP;exports.onInitialized=sw;exports.onStart=ow;exports.onUpdate=rw;exports.onXRSessionEnd=ng;exports.onXRSessionStart=Uu;exports.parseSync=Ix;exports.placeOnSurface=R0;exports.postprocessFBXMaterials=Zm;exports.prefix=RP;exports.pushState=r0;exports.randomNumber=aS;exports.registerBinaryType=rg;exports.registerComponent=Gu;exports.registerComponentExtension=Gg;exports.registerCustomEffectType=tn;exports.registerExportExtensions=qg;exports.registerExtensions=gu;exports.registerHotReloadType=Jv;exports.registerLoader=tg;exports.registerPrefabProvider=gv;exports.registerPrototypeExtensions=Pv;exports.registerType=r1;exports.relativePathPrefix=c0;exports.removeAttributeChangeCallback=d0;exports.removeComponent=vg;exports.removeCustomImportExtensionType=QM;exports.removePatch=dC;exports.resolveUrl=To;exports.sanitizeString=l0;exports.saveImage=Tx;exports.screenshot=ME;exports.screenshot2=Hy;exports.sendDestroyed=mg;exports.serializable=m;exports.serializeObject=vv;exports.serializeable=Br;exports.setActive=dc;exports.setAllowBalloonMessages=g0;exports.setAllowOverlayMessages=PS;exports.setAutoFitEnabled=Hd;exports.setCameraController=Kp;exports.setDestroyed=Lv;exports.setDevEnvironment=tC;exports.setDisposable=ug;exports.setDontDestroy=fa;exports.setOrAddParamsToUrl=qp;exports.setParam=oS;exports.setParamWithoutReload=Mc;exports.setPeerOptions=SC;exports.setResourceTrackingEnabled=$C;exports.setState=Vm;exports.setVisibleInCustomShadowRendering=Km;exports.setWorldEuler=Ym;exports.setWorldPosition=st;exports.setWorldPositionXYZ=Pr;exports.setWorldQuaternion=Gi;exports.setWorldQuaternionXYZW=Xm;exports.setWorldRotation=C0;exports.setWorldRotationXYZ=th;exports.setWorldScale=za;exports.showBalloonError=ih;exports.showBalloonMessage=Ee;exports.showBalloonWarning=me;exports.showDebugConsole=Jm;exports.slerp=IS;exports.syncDestroy=sh;exports.syncField=ly;exports.syncInstantiate=gg;exports.textureToCanvas=XS;exports.tryCastBinary=$0;exports.tryDetermineMimetypeFromBinary=Mw;exports.tryDetermineMimetypeFromURL=Pw;exports.tryFindObject=Ua;exports.tryGetGuid=W0;exports.unregisterHotReloadType=ew;exports.unwatchWrite=$m;exports.useForAutoFit=v0;exports.validate=St;exports.watchWrite=Iu;