@needle-tools/engine 4.7.0-next.a507c47 → 4.7.0-next.bbbc637

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 (31) hide show
  1. package/dist/{needle-engine.bundle-8HzDjpUw.js → needle-engine.bundle-BOMrdPF_.js} +15 -15
  2. package/dist/{needle-engine.bundle-BRRl7L9U.umd.cjs → needle-engine.bundle-Bb7oB8Qy.umd.cjs} +5 -5
  3. package/dist/{needle-engine.bundle-CPBkAx_i.min.js → needle-engine.bundle-rzZz_U5k.min.js} +5 -5
  4. package/dist/needle-engine.js +2 -2
  5. package/dist/needle-engine.min.js +1 -1
  6. package/dist/needle-engine.umd.cjs +1 -1
  7. package/lib/engine/engine_context.js +1 -1
  8. package/lib/engine/engine_context.js.map +1 -1
  9. package/lib/engine/engine_three_utils.js +4 -0
  10. package/lib/engine/engine_three_utils.js.map +1 -1
  11. package/lib/engine/webcomponents/needle-engine.attributes.d.ts +1 -1
  12. package/lib/engine-components/Camera.js +1 -1
  13. package/lib/engine-components/Camera.js.map +1 -1
  14. package/lib/engine-components/CameraUtils.js +5 -3
  15. package/lib/engine-components/CameraUtils.js.map +1 -1
  16. package/lib/engine-components/Skybox.js +4 -4
  17. package/lib/engine-components/Skybox.js.map +1 -1
  18. package/package.json +1 -1
  19. package/plugins/common/logger.js +213 -0
  20. package/plugins/types/userconfig.d.ts +1 -1
  21. package/plugins/vite/alias.js +7 -2
  22. package/plugins/vite/imports-logger.js +1 -1
  23. package/plugins/vite/index.js +2 -0
  24. package/plugins/vite/logger.client.js +149 -0
  25. package/plugins/vite/logger.js +85 -0
  26. package/src/engine/engine_context.ts +1 -1
  27. package/src/engine/engine_three_utils.ts +3 -0
  28. package/src/engine/webcomponents/needle-engine.attributes.ts +1 -1
  29. package/src/engine-components/Camera.ts +1 -1
  30. package/src/engine-components/CameraUtils.ts +5 -3
  31. package/src/engine-components/Skybox.ts +5 -5
@@ -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 Bb=Db;const Gs=class{static copyTexture(e,t){t||(t=this.blitMaterial),this.blitMaterial.reset();const s=t||this.blitMaterial;s.uniforms.map.value=e,s.needsUpdate=!0,s.uniformsNeedUpdate=!0;const o=s.vertexShader;s.vertexShader=Bb.vertex;const r=this.mesh;r.material=s,r.frustumCulled=!1,this.scene.children.length=0,this.scene.add(r),this.renderer.setSize(e.image.width,e.image.height),this.renderer.clear(),this.renderer.render(this.scene,this.perspectiveCam);const l=new je(this.renderer.domElement);return l.name="Copy",l.needsUpdate=!0,s.vertexShader=o,l}static blit(e,t,s){const{renderer:o=this.renderer,blitMaterial:r=this.blitMaterial,flipY:l=!1,depthTexture:c=null,depthTest:h=!0,depthWrite:d=!0}=s||{};this.blitMaterial.reset(),r.uniforms.map&&(r.uniforms.map.value=e),r.uniforms.flipY&&(r.uniforms.flipY.value=l),c?(r.uniforms.writeDepth=new Qi(!0),r.uniforms.depthTexture.value=c):(r.uniforms.writeDepth=new Qi(!1),r.uniforms.depthTexture.value=null),r.needsUpdate=!0,r.uniformsNeedUpdate=!0;const u=this.mesh;u.material=r,u.frustumCulled=!1,this.scene.children.length=0,this.scene.add(u);const p=o.getRenderTarget(),g=o.getContext(),f=g.getParameter(g.DEPTH_TEST),y=g.getParameter(g.DEPTH_WRITEMASK),v=g.getParameter(g.DEPTH_FUNC);h?o.getContext().enable(o.getContext().DEPTH_TEST):o.getContext().disable(o.getContext().DEPTH_TEST),o.state.buffers.depth.setMask(d),o.setClearColor(new oe(0,0,0),0),o.setPixelRatio(window.devicePixelRatio),o.setRenderTarget(t),o.clear(),o.render(this.scene,this.perspectiveCam),o.setRenderTarget(p);const b=o.state.buffers.depth;b.setTest(f),b.setMask(y),b.setFunc(v)}static textureToCanvas(e,t=!1){if(!e)return null;(t===!0||e.isCompressedTexture===!0)&&(e=Fb(e));const s=e.image;if(Tk(s)){const o=document.createElement("canvas");o.width=s.width,o.height=s.height;const r=o.getContext("2d");return r?(r.drawImage(s,0,0,s.width,s.height,0,0,o.width,o.height),o):(console.error("Failed getting canvas 2d context"),null)}return null}};a(Gs,"planeGeometry",new Ns(2,2,1,1)),a(Gs,"renderer",new fr({antialias:!1,alpha:!0})),a(Gs,"perspectiveCam",new we),a(Gs,"orthographicCam",new ud),a(Gs,"scene",new xi),a(Gs,"blitMaterial",new Bb),a(Gs,"mesh",new G(Gs.planeGeometry,Gs.blitMaterial));let Jl=Gs;function Fb(n){return Jl.copyTexture(n)}function Rk(n,e=!1){return Jl.textureToCanvas(n,e)}function Tk(n){return typeof HTMLImageElement<"u"&&n instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&n instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&n instanceof OffscreenCanvas||typeof ImageBitmap<"u"&&n instanceof ImageBitmap}function Ek(n){const e=n.type;return e==="Mesh"||e==="SkinnedMesh"}function mg(n,e){e?n["needle:rendercustomshadow"]=!0:n["needle:rendercustomshadow"]=!1}function Ub(n){return!!(n&&(n["needle:rendercustomshadow"]===!0||n["needle:rendercustomshadow"]==null))}function si(n,e=void 0,t=void 0,s=void 0){const o=s||new Si;o.makeEmpty();const r=[];function l(h){let d=!0;if(h.visible&&Pb(h)!==!1&&!(h.type==="TransformControlsGizmo"||h.type==="TransformControlsPlane")){if(h instanceof EC&&(d=!1),h instanceof Mm&&(d=!1),h instanceof ka&&(d=!1),h.isGizmo===!0&&(d=!1),h.material instanceof kv&&(d=!1),Ek(h)||(d=!1),t&&h.layers.test(t)===!1&&(d=!1),d&&(e&&Array.isArray(e)&&e!=null&&e.includes(h)||typeof e=="function"&&e(h)===!0))return;if(h.isUI!==!0){if(d){const u=h.children;h.children=r;const p=h.position,g=h.scale;if(Number.isNaN(p.x)||Number.isNaN(p.y)||Number.isNaN(p.z)){console.warn(`Object "${h.name}" has NaN values in position or scale.... will ignore it`,p,g);return}o.expandByObject(h,!0),h.children=u}for(const u of h.children)l(u)}}}let c=!1;Array.isArray(n)||(n=[n]);for(const h of n)h&&(c=!0,h.updateMatrixWorld(),l(h));return c||console.warn("No objects to fit camera to..."),o}function zb(n,e,t){const s=si([n],t?.ignore),o=new S;s.getSize(o);const r=new S;s.getCenter(r);const l=new S;e.getSize(l);const c=new S;e.getCenter(c);const h=new S;h.set(l.x/o.x,l.y/o.y,l.z/o.z);const d=Math.min(h.x,h.y,h.z),u=t?.scale!==!1;if(u&&Ta(n,Ge(n).multiplyScalar(d)),t?.position!==!1){const p=new S;s.getCenter(p),p.y=s.min.y;const g=new S;e.getCenter(g),g.y=e.min.y;const f=g.clone().sub(p);u&&f.multiplyScalar(d),lt(n,ee(n).add(f))}return{boundsBefore:s,scale:h}}function Nb(n,e){const t=si([n]),s=new S;t.getCenter(s),s.y=t.min.y;const o=e.clone().sub(s),r=ee(n);return lt(n,r.add(o)),{offset:o,bounds:t}}function gg(n,e,t,s){if(Array.isArray(e)){let l=!0;for(let c=0;c<e.length;c++)gg(n,e[c],c,e)||(l=!1);return l}if(e.type==="MeshStandardMaterial"||e.type==="MeshBasicMaterial")return!1;if(e["material:fbx"]!=null)return!0;const o=new bt;o["material:fbx"]=e;const r=e;return r&&(r.map?o.color.set(1,1,1):o.color.copyLinearToSRGB(r.color),o.emissive.copyLinearToSRGB(r.emissive),o.emissiveIntensity=r.emissiveIntensity,o.opacity=r.opacity,o.displacementScale=r.displacementScale,o.transparent=r.transparent,o.bumpMap=r.bumpMap,o.aoMap=r.aoMap,o.map=r.map,o.displacementMap=r.displacementMap,o.emissiveMap=r.emissiveMap,o.normalMap=r.normalMap,o.envMap=r.envMap,o.alphaMap=r.alphaMap,o.metalness=r.reflectivity,o.vertexColors=r.vertexColors,r.shininess&&(o.roughness=1-Math.sqrt(r.shininess)/10),o.needsUpdate=!0),t===void 0?n.material=o:s[t]=o,!0}let Ld=!1;nk((...n)=>{var e;F()&&(e=pe.Current)!=null&&e.isInXR&&(wr(!0),Wb("error",...n))});function wr(n){if(n){if(Ld)return;Ld=!0,Ik()}else{if(!Ld)return;Ld=!1,Lk()}}const ec={log:void 0,warn:void 0,error:void 0};class Ak{constructor(){a(this,"familyName","needle-xr"),a(this,"root",null),a(this,"context",null),a(this,"defaultFontSize",.06),a(this,"targetObject",new E),a(this,"userForwardViewPoint",new S),a(this,"oneEuroFilter",new og(90,.8)),a(this,"_lastElementRemoveTime",0),a(this,"onBeforeRender",()=>{var e,t;const s=(e=this.context)==null?void 0:e.mainCamera;if(this.context&&s instanceof we){const o=this.getRoot();Number.isNaN(o.position.x)&&o.position.set(0,0,0),Number.isNaN(o.quaternion.x)&&o.quaternion.set(0,0,0,1),this.context.scene.add(this.targetObject);const r=((t=this.context.xr)==null?void 0:t.rigScale)??1,l=3.5*r,c=s.worldForward;c.y=0,c.normalize().multiplyScalar(l),this.userForwardViewPoint.copy(s.worldPosition).sub(c),this.targetObject.position.distanceTo(this.userForwardViewPoint)>2*r&&(this.targetObject.position.copy(this.userForwardViewPoint),Kl(this.targetObject,s,!0,!0),this.targetObject.rotateY(Math.PI)),this.oneEuroFilter.filter(this.targetObject.position,o.position,this.context.time.time);const h=this.context.time.deltaTime;if(o.quaternion.slerp(this.targetObject.quaternion,h*5),o.scale.setScalar(r),this.targetObject.removeFromParent(),this.context.scene.add(o),this.context.time.time-this._lastElementRemoveTime>.1){this._lastElementRemoveTime=this.context.time.time;const d=Date.now();for(let u=0;u<this._activeTexts.length;u++){const p=this._activeTexts[u];if(p instanceof Re.Text&&d-p._activatedTime>2e4){p.removeFromParent(),this._textBuffer.push(p),this._activeTexts.splice(u,1);break}}}}}),a(this,"textOptions",{fontSize:this.defaultFontSize,fontFamily:this.familyName,padding:.03,margin:.005,color:0,backgroundColor:16777215,backgroundOpacity:.4,borderRadius:.03,offset:.025}),a(this,"_textBuffer",[]),a(this,"_activeTexts",[]),this.ensureFont()}onEnable(){this.context=pe.Current||pe.All[0],this.context.pre_render_callbacks.push(this.onBeforeRender)}onDisable(){var e,t,s;(t=this.context)==null||t.pre_render_callbacks.splice((e=this.context)==null?void 0:e.pre_render_callbacks.indexOf(this.onBeforeRender),1),(s=this.root)==null||s.removeFromParent()}addLog(e,t){const s=this.getRoot(),o=this.getText();let r=16777215,l=0;switch(e){case"log":r=16777215,l=0;break;case"warn":r=16772761,l=4465152;break;case"error":r=16755370,l=7798784;break}t.length>1e3&&(t=t.substring(0,1e3)+"...");const c=new Date().toISOString().split("T")[1].split(".")[0];o.textContent="["+c+"] "+t,o.visible=!0,o._activatedTime=Date.now(),s.add(o),this._activeTexts.push(o),this.context&&this.context.scene.add(s),o.set({backgroundColor:r,color:l}),Re.update()}ensureFont(){let e=Re.FontLibrary.getFontFamily(this.familyName);if(!e){e=Re.FontLibrary.addFontFamily(this.familyName);const t=e.addVariant("normal","normal","./include/needle/arial-msdf.json","./include/needle/arial.png");t?.addEventListener("ready",()=>{Re.update()})}}getText(){const e=this.getRoot();if(this._textBuffer.length>0){const s=this._textBuffer.pop();return s.visible=!0,setTimeout(()=>this.disableDepthTestRecursive(s),100),s}if(e.children.length>20&&this._activeTexts.length>0)return this._activeTexts.shift();const t=new Re.Text(this.textOptions);return setTimeout(()=>this.disableDepthTestRecursive(t),500),setTimeout(()=>this.disableDepthTestRecursive(t),1500),t}disableDepthTestRecursive(e,t=0){for(let o=0;o<e.children.length;o++){const r=e.children[o];r instanceof E&&this.disableDepthTestRecursive(r,t+1)}e.renderOrder=10*t,e.layers.set(2);const s=e.material;s&&(s.depthWrite=!1,s.depthTest=!1,s.transparent=!0),t===0&&Re.update()}getRoot(){if(this.root)return this.root;const e=this.defaultFontSize,t={boxSizing:"border-box",fontFamily:this.familyName,width:"2.6",fontSize:e,color:0,lineHeight:1,backgroundColor:16777215,backgroundOpacity:0,whiteSpace:"pre-wrap",flexDirection:"column-reverse"};return this.root=new Re.Block(t),this.root}}let _s=null;function Ik(){_s||(_s=new Ak),_s.onEnable();for(const n in ec){ec[n]=console[n];let e=!1;console[n]=function(){var t;if((t=ec[n])==null||t.apply(console,arguments),!e)try{e=!0,Wb(n,...arguments)}finally{e=!1}}}}function Lk(){_s?.onDisable();for(const n in ec)console[n]=ec[n]}const tc=new Map;function Wb(n,...e){try{switch(tc.clear(),n){case"log":_s?.addLog("log",t());break;case"warn":_s?.addLog("warn",t());break;case"error":_s?.addLog("error",t());break}}catch(r){console.error("Error in spatial console",r)}finally{tc.clear()}function t(){let r="";for(let l=0;l<e.length;l++){const c=e[l];r+=s(c),l<e.length-1&&(r+=", ")}return r}function s(r,l=0){if(typeof r=="string")return'"'+r+'"';if(typeof r=="number"){if(r%1!==0){const c=r.toFixed(5),h=c.indexOf(".");let d=c.length-1;for(;d>h&&c[d]==="0";)d--;return c.substring(0,d+1)}return r.toString()}else if(Array.isArray(r)){let c="[";for(let h=0;h<r.length;h++){const d=r[h];c+=s(d,l+1),h<r.length-1&&(c+=", ")}return c+="]",c}else{if(r===null)return"null";if(r===void 0)return"undefined";if(typeof r=="function")return r.name+"()"}if(r instanceof re)return`(${s(r.x)}, ${s(r.y)})`;if(r instanceof S)return`(${s(r.x)}, ${s(r.y)}, ${s(r.z)})`;if(r instanceof fe)return`(${s(r.x)}, ${s(r.y)}, ${s(r.z)}, ${s(r.w)})`;if(r instanceof V)return`(${s(r.x)}, ${s(r.y)}, ${s(r.z)}, ${s(r.w)})`;if(r instanceof Pe||r instanceof je)return r.name;if(r instanceof Mv)return`[${r.elements.join(", ")}]`;if(r instanceof se)return`[${r.elements.join(", ")}]`;if(r instanceof uo)return r.mask.toString();if(typeof r=="object"){if(tc.has(r))return"*";let c=`{
82
+ }`);let Bb=Db;const Gs=class{static copyTexture(e,t){t||(t=this.blitMaterial),this.blitMaterial.reset();const s=t||this.blitMaterial;s.uniforms.map.value=e,s.needsUpdate=!0,s.uniformsNeedUpdate=!0;const o=s.vertexShader;s.vertexShader=Bb.vertex;const r=this.mesh;r.material=s,r.frustumCulled=!1,this.scene.children.length=0,this.scene.add(r),this.renderer.setSize(e.image.width,e.image.height),this.renderer.clear(),this.renderer.render(this.scene,this.perspectiveCam);const l=new je(this.renderer.domElement);return l.name="Copy",l.needsUpdate=!0,s.vertexShader=o,l}static blit(e,t,s){const{renderer:o=this.renderer,blitMaterial:r=this.blitMaterial,flipY:l=!1,depthTexture:c=null,depthTest:h=!0,depthWrite:d=!0}=s||{};this.blitMaterial.reset(),r.uniforms.map&&(r.uniforms.map.value=e),r.uniforms.flipY&&(r.uniforms.flipY.value=l),c?(r.uniforms.writeDepth=new Qi(!0),r.uniforms.depthTexture.value=c):(r.uniforms.writeDepth=new Qi(!1),r.uniforms.depthTexture.value=null),r.needsUpdate=!0,r.uniformsNeedUpdate=!0;const u=this.mesh;u.material=r,u.frustumCulled=!1,this.scene.children.length=0,this.scene.add(u);const p=o.getRenderTarget(),g=o.getContext(),f=g.getParameter(g.DEPTH_TEST),y=g.getParameter(g.DEPTH_WRITEMASK),v=g.getParameter(g.DEPTH_FUNC);h?o.getContext().enable(o.getContext().DEPTH_TEST):o.getContext().disable(o.getContext().DEPTH_TEST),o.state.buffers.depth.setMask(d),o.setClearColor(new oe(0,0,0),0),o.setPixelRatio(window.devicePixelRatio),o.setRenderTarget(t),o.clear(),o.render(this.scene,this.perspectiveCam),o.setRenderTarget(p);const b=o.state.buffers.depth;b.setTest(f),b.setMask(y),b.setFunc(v)}static textureToCanvas(e,t=!1){if(!e)return null;(t===!0||e.isCompressedTexture===!0)&&(e=Fb(e));const s=e.image;if(Tk(s)){const o=document.createElement("canvas");o.width=s.width,o.height=s.height;const r=o.getContext("2d");return r?(r.drawImage(s,0,0,s.width,s.height,0,0,o.width,o.height),o):(console.error("Failed getting canvas 2d context"),null)}return null}};a(Gs,"planeGeometry",new Ns(2,2,1,1)),a(Gs,"renderer",new fr({antialias:!1,alpha:!0})),a(Gs,"perspectiveCam",new we),a(Gs,"orthographicCam",new ud),a(Gs,"scene",new xi),a(Gs,"blitMaterial",new Bb),a(Gs,"mesh",new G(Gs.planeGeometry,Gs.blitMaterial));let Jl=Gs;function Fb(n){return Jl.copyTexture(n)}function Rk(n,e=!1){return Jl.textureToCanvas(n,e)}function Tk(n){return typeof HTMLImageElement<"u"&&n instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&n instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&n instanceof OffscreenCanvas||typeof ImageBitmap<"u"&&n instanceof ImageBitmap}function Ek(n){const e=n.type;return e==="Mesh"||e==="SkinnedMesh"}function mg(n,e){e?n["needle:rendercustomshadow"]=!0:n["needle:rendercustomshadow"]=!1}function Ub(n){return!!(n&&(n["needle:rendercustomshadow"]===!0||n["needle:rendercustomshadow"]==null))}function si(n,e=void 0,t=void 0,s=void 0){const o=s||new Si;o.makeEmpty();const r=[];function l(h){let d=!0;if(h.visible&&Pb(h)!==!1&&!(h.type==="TransformControlsGizmo"||h.type==="TransformControlsPlane")){if(h instanceof EC&&(d=!1),h instanceof Mm&&(d=!1),h instanceof ka&&(d=!1),h.isGizmo===!0&&(d=!1),h.material instanceof kv&&(d=!1),Ek(h)||(d=!1),t&&h.layers.test(t)===!1&&(d=!1),d&&(e&&Array.isArray(e)&&e!=null&&e.includes(h)||typeof e=="function"&&e(h)===!0))return;if(h.isUI!==!0){if(d){const u=h.children;h.children=r;const p=h.position,g=h.scale;if(Number.isNaN(p.x)||Number.isNaN(p.y)||Number.isNaN(p.z)){console.warn(`Object "${h.name}" has NaN values in position or scale.... will ignore it`,p,g);return}h.geometry===null&&(h.geometry=void 0),o.expandByObject(h,!0),h.children=u}for(const u of h.children)l(u)}}}let c=!1;Array.isArray(n)||(n=[n]);for(const h of n)h&&(c=!0,h.updateMatrixWorld(),l(h));return c||console.warn("No objects to fit camera to..."),o}function zb(n,e,t){const s=si([n],t?.ignore),o=new S;s.getSize(o);const r=new S;s.getCenter(r);const l=new S;e.getSize(l);const c=new S;e.getCenter(c);const h=new S;h.set(l.x/o.x,l.y/o.y,l.z/o.z);const d=Math.min(h.x,h.y,h.z),u=t?.scale!==!1;if(u&&Ta(n,Ge(n).multiplyScalar(d)),t?.position!==!1){const p=new S;s.getCenter(p),p.y=s.min.y;const g=new S;e.getCenter(g),g.y=e.min.y;const f=g.clone().sub(p);u&&f.multiplyScalar(d),lt(n,ee(n).add(f))}return{boundsBefore:s,scale:h}}function Nb(n,e){const t=si([n]),s=new S;t.getCenter(s),s.y=t.min.y;const o=e.clone().sub(s),r=ee(n);return lt(n,r.add(o)),{offset:o,bounds:t}}function gg(n,e,t,s){if(Array.isArray(e)){let l=!0;for(let c=0;c<e.length;c++)gg(n,e[c],c,e)||(l=!1);return l}if(e.type==="MeshStandardMaterial"||e.type==="MeshBasicMaterial")return!1;if(e["material:fbx"]!=null)return!0;const o=new bt;o["material:fbx"]=e;const r=e;return r&&(r.map?o.color.set(1,1,1):o.color.copyLinearToSRGB(r.color),o.emissive.copyLinearToSRGB(r.emissive),o.emissiveIntensity=r.emissiveIntensity,o.opacity=r.opacity,o.displacementScale=r.displacementScale,o.transparent=r.transparent,o.bumpMap=r.bumpMap,o.aoMap=r.aoMap,o.map=r.map,o.displacementMap=r.displacementMap,o.emissiveMap=r.emissiveMap,o.normalMap=r.normalMap,o.envMap=r.envMap,o.alphaMap=r.alphaMap,o.metalness=r.reflectivity,o.vertexColors=r.vertexColors,r.shininess&&(o.roughness=1-Math.sqrt(r.shininess)/10),o.needsUpdate=!0),t===void 0?n.material=o:s[t]=o,!0}let Ld=!1;nk((...n)=>{var e;F()&&(e=pe.Current)!=null&&e.isInXR&&(wr(!0),Wb("error",...n))});function wr(n){if(n){if(Ld)return;Ld=!0,Ik()}else{if(!Ld)return;Ld=!1,Lk()}}const ec={log:void 0,warn:void 0,error:void 0};class Ak{constructor(){a(this,"familyName","needle-xr"),a(this,"root",null),a(this,"context",null),a(this,"defaultFontSize",.06),a(this,"targetObject",new E),a(this,"userForwardViewPoint",new S),a(this,"oneEuroFilter",new og(90,.8)),a(this,"_lastElementRemoveTime",0),a(this,"onBeforeRender",()=>{var e,t;const s=(e=this.context)==null?void 0:e.mainCamera;if(this.context&&s instanceof we){const o=this.getRoot();Number.isNaN(o.position.x)&&o.position.set(0,0,0),Number.isNaN(o.quaternion.x)&&o.quaternion.set(0,0,0,1),this.context.scene.add(this.targetObject);const r=((t=this.context.xr)==null?void 0:t.rigScale)??1,l=3.5*r,c=s.worldForward;c.y=0,c.normalize().multiplyScalar(l),this.userForwardViewPoint.copy(s.worldPosition).sub(c),this.targetObject.position.distanceTo(this.userForwardViewPoint)>2*r&&(this.targetObject.position.copy(this.userForwardViewPoint),Kl(this.targetObject,s,!0,!0),this.targetObject.rotateY(Math.PI)),this.oneEuroFilter.filter(this.targetObject.position,o.position,this.context.time.time);const h=this.context.time.deltaTime;if(o.quaternion.slerp(this.targetObject.quaternion,h*5),o.scale.setScalar(r),this.targetObject.removeFromParent(),this.context.scene.add(o),this.context.time.time-this._lastElementRemoveTime>.1){this._lastElementRemoveTime=this.context.time.time;const d=Date.now();for(let u=0;u<this._activeTexts.length;u++){const p=this._activeTexts[u];if(p instanceof Re.Text&&d-p._activatedTime>2e4){p.removeFromParent(),this._textBuffer.push(p),this._activeTexts.splice(u,1);break}}}}}),a(this,"textOptions",{fontSize:this.defaultFontSize,fontFamily:this.familyName,padding:.03,margin:.005,color:0,backgroundColor:16777215,backgroundOpacity:.4,borderRadius:.03,offset:.025}),a(this,"_textBuffer",[]),a(this,"_activeTexts",[]),this.ensureFont()}onEnable(){this.context=pe.Current||pe.All[0],this.context.pre_render_callbacks.push(this.onBeforeRender)}onDisable(){var e,t,s;(t=this.context)==null||t.pre_render_callbacks.splice((e=this.context)==null?void 0:e.pre_render_callbacks.indexOf(this.onBeforeRender),1),(s=this.root)==null||s.removeFromParent()}addLog(e,t){const s=this.getRoot(),o=this.getText();let r=16777215,l=0;switch(e){case"log":r=16777215,l=0;break;case"warn":r=16772761,l=4465152;break;case"error":r=16755370,l=7798784;break}t.length>1e3&&(t=t.substring(0,1e3)+"...");const c=new Date().toISOString().split("T")[1].split(".")[0];o.textContent="["+c+"] "+t,o.visible=!0,o._activatedTime=Date.now(),s.add(o),this._activeTexts.push(o),this.context&&this.context.scene.add(s),o.set({backgroundColor:r,color:l}),Re.update()}ensureFont(){let e=Re.FontLibrary.getFontFamily(this.familyName);if(!e){e=Re.FontLibrary.addFontFamily(this.familyName);const t=e.addVariant("normal","normal","./include/needle/arial-msdf.json","./include/needle/arial.png");t?.addEventListener("ready",()=>{Re.update()})}}getText(){const e=this.getRoot();if(this._textBuffer.length>0){const s=this._textBuffer.pop();return s.visible=!0,setTimeout(()=>this.disableDepthTestRecursive(s),100),s}if(e.children.length>20&&this._activeTexts.length>0)return this._activeTexts.shift();const t=new Re.Text(this.textOptions);return setTimeout(()=>this.disableDepthTestRecursive(t),500),setTimeout(()=>this.disableDepthTestRecursive(t),1500),t}disableDepthTestRecursive(e,t=0){for(let o=0;o<e.children.length;o++){const r=e.children[o];r instanceof E&&this.disableDepthTestRecursive(r,t+1)}e.renderOrder=10*t,e.layers.set(2);const s=e.material;s&&(s.depthWrite=!1,s.depthTest=!1,s.transparent=!0),t===0&&Re.update()}getRoot(){if(this.root)return this.root;const e=this.defaultFontSize,t={boxSizing:"border-box",fontFamily:this.familyName,width:"2.6",fontSize:e,color:0,lineHeight:1,backgroundColor:16777215,backgroundOpacity:0,whiteSpace:"pre-wrap",flexDirection:"column-reverse"};return this.root=new Re.Block(t),this.root}}let _s=null;function Ik(){_s||(_s=new Ak),_s.onEnable();for(const n in ec){ec[n]=console[n];let e=!1;console[n]=function(){var t;if((t=ec[n])==null||t.apply(console,arguments),!e)try{e=!0,Wb(n,...arguments)}finally{e=!1}}}}function Lk(){_s?.onDisable();for(const n in ec)console[n]=ec[n]}const tc=new Map;function Wb(n,...e){try{switch(tc.clear(),n){case"log":_s?.addLog("log",t());break;case"warn":_s?.addLog("warn",t());break;case"error":_s?.addLog("error",t());break}}catch(r){console.error("Error in spatial console",r)}finally{tc.clear()}function t(){let r="";for(let l=0;l<e.length;l++){const c=e[l];r+=s(c),l<e.length-1&&(r+=", ")}return r}function s(r,l=0){if(typeof r=="string")return'"'+r+'"';if(typeof r=="number"){if(r%1!==0){const c=r.toFixed(5),h=c.indexOf(".");let d=c.length-1;for(;d>h&&c[d]==="0";)d--;return c.substring(0,d+1)}return r.toString()}else if(Array.isArray(r)){let c="[";for(let h=0;h<r.length;h++){const d=r[h];c+=s(d,l+1),h<r.length-1&&(c+=", ")}return c+="]",c}else{if(r===null)return"null";if(r===void 0)return"undefined";if(typeof r=="function")return r.name+"()"}if(r instanceof re)return`(${s(r.x)}, ${s(r.y)})`;if(r instanceof S)return`(${s(r.x)}, ${s(r.y)}, ${s(r.z)})`;if(r instanceof fe)return`(${s(r.x)}, ${s(r.y)}, ${s(r.z)}, ${s(r.w)})`;if(r instanceof V)return`(${s(r.x)}, ${s(r.y)}, ${s(r.z)}, ${s(r.w)})`;if(r instanceof Pe||r instanceof je)return r.name;if(r instanceof Mv)return`[${r.elements.join(", ")}]`;if(r instanceof se)return`[${r.elements.join(", ")}]`;if(r instanceof uo)return r.mask.toString();if(typeof r=="object"){if(tc.has(r))return"*";let c=`{
83
83
  `;c+=o(l);const h=Object.keys(r);let d="";for(let u=0;u<h.length;u++){const p=h[u],g=r[p];if(tc.has(g)){d+="";continue}tc.set(g,!0),d+=p+":"+s(g,l+1),u<h.length-1&&(d+=", "),d.length>=60&&(d+=`
84
84
  `,d+=o(l),c+=d,d="")}return c+=d,c+=`
85
85
  }`,c}return r}function o(r){let l="";for(let c=0;c<r;c++)l+=" ";return l}}const jk=C("nodevlogs");function De(n,e=ki.Log){Hs(e,n)}function be(n){De(n,ki.Warn)}function ic(n){De(n,ki.Error)}let fg,yg;function F(){if(jk)return!1;if(fg!==void 0)return fg;if(yg!==void 0)return yg;let n=Xt();return n||(n=window.location.hostname.endsWith(".local-credentialless.webcontainer.io")),yg=n,n}function Dk(n){fg=n}let ni,Ki=null,qs=null,sc=!1,Vb=null;const $b="terminal",nc=C("console"),Bk=C("noerrors")||C("noconsole")||window.crossOriginIsolated;if(nc&&bg(),!Bk&&(nc||Xt())){if(Xt()&&!nc){const e=new URL(window.location.href);e.searchParams.set("console","1"),console.log('\u{1F335} 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: `+e.toString())}const n=X.isMobileDevice()||X
142
142
  #__vconsole .vc-mask {
143
143
  overflow: hidden;
144
144
  }
145
- `,Ki?.prepend(s),n===!0&&tg()<=0&&Hb(),console.log("\u{1F335} Debug console has loaded")}},e.onerror=()=>{console.warn("\u{1F335} Debug console failed to load."+(window.crossOriginIsolated?"This page is using cross-origin isolation, so external scripts can't be loaded.":"")),sc=!1,ni=null},e.src="https://cdn.jsdelivr.net/npm/vconsole@3.9.1/dist/vconsole.min.js",document.body.appendChild(e)}function Wk(){if(!globalThis.VConsole)return;const n=new VConsole.VConsolePlugin("needle-console","\u{1F335} Inspect glTF"),e=()=>document.querySelector("#__vc_plug_"+n._id+" iframe");return n.on("renderTab",function(t){const s=globalThis["needle:codegen_files"];if(!s||s.length===0)return;let o=globalThis["needle:codegen_files"][0];const r=o.indexOf("?");r>-1&&(o=o.substring(0,r));const l=location.protocol+"//"+location.host+location.pathname+"/"+o,c=encodeURIComponent(l);n.fullUrl="https://viewer.needle.tools?inspect&file="+c;var h='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';t(h)}),n.on("show",function(){const t=e();t&&t.src!==n.fullUrl&&(t.src=n.fullUrl)}),n.on("hide",function(){const t=e();t&&(t.src="")}),n.on("addTopBar",function(t){var s=new Array;s.push({name:"Open in new window \u2197",onClick:function(o){window.open(n.fullUrl,"_blank"),ni?.hide()}}),s.push({name:"Reload",onClick:function(o){const r=e();r&&(r.src=n.fullUrl)}}),s.push({name:"Fullscreen",onClick:function(o){const r=e();r.requestFullscreen?r.requestFullscreen():r.webkitRequestFullscreen instanceof Function&&r.webkitRequestFullscreen()}}),t(s)}),n}function Vk(){return document.querySelector("#__vconsole .vc-switch")||null}function $k(){return document.querySelector("#__vconsole")||null}const Qb=C("debugdefines");bo('if(!globalThis["NEEDLE_ENGINE_VERSION"]) globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";'),bo('if(!globalThis["NEEDLE_ENGINE_GENERATOR"]) globalThis["NEEDLE_ENGINE_GENERATOR"] = "unknown";'),bo('if(!globalThis["NEEDLE_PROJECT_BUILD_TIME"]) globalThis["NEEDLE_PROJECT_BUILD_TIME"] = "unknown";'),bo('if(!globalThis["NEEDLE_PUBLIC_KEY"]) globalThis["NEEDLE_PUBLIC_KEY"] = "unknown";'),bo('globalThis["__NEEDLE_ENGINE_VERSION__"] = "4.7.0-alpha";'),bo('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";'),bo('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Fri Jul 25 2025 10:04:19 GMT+0000 (Coordinated Universal Time)";'),bo('globalThis["__NEEDLE_PUBLIC_KEY__"] = "'+NEEDLE_PUBLIC_KEY+'";');const ws="4.7.0-alpha",jd="undefined",_g="Fri Jul 25 2025 10:04:19 GMT+0000 (Coordinated Universal Time)";Qb&&console.log(`Engine version: ${ws} (generator: ${jd})
145
+ `,Ki?.prepend(s),n===!0&&tg()<=0&&Hb(),console.log("\u{1F335} Debug console has loaded")}},e.onerror=()=>{console.warn("\u{1F335} Debug console failed to load."+(window.crossOriginIsolated?"This page is using cross-origin isolation, so external scripts can't be loaded.":"")),sc=!1,ni=null},e.src="https://cdn.jsdelivr.net/npm/vconsole@3.9.1/dist/vconsole.min.js",document.body.appendChild(e)}function Wk(){if(!globalThis.VConsole)return;const n=new VConsole.VConsolePlugin("needle-console","\u{1F335} Inspect glTF"),e=()=>document.querySelector("#__vc_plug_"+n._id+" iframe");return n.on("renderTab",function(t){const s=globalThis["needle:codegen_files"];if(!s||s.length===0)return;let o=globalThis["needle:codegen_files"][0];const r=o.indexOf("?");r>-1&&(o=o.substring(0,r));const l=location.protocol+"//"+location.host+location.pathname+"/"+o,c=encodeURIComponent(l);n.fullUrl="https://viewer.needle.tools?inspect&file="+c;var h='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';t(h)}),n.on("show",function(){const t=e();t&&t.src!==n.fullUrl&&(t.src=n.fullUrl)}),n.on("hide",function(){const t=e();t&&(t.src="")}),n.on("addTopBar",function(t){var s=new Array;s.push({name:"Open in new window \u2197",onClick:function(o){window.open(n.fullUrl,"_blank"),ni?.hide()}}),s.push({name:"Reload",onClick:function(o){const r=e();r&&(r.src=n.fullUrl)}}),s.push({name:"Fullscreen",onClick:function(o){const r=e();r.requestFullscreen?r.requestFullscreen():r.webkitRequestFullscreen instanceof Function&&r.webkitRequestFullscreen()}}),t(s)}),n}function Vk(){return document.querySelector("#__vconsole .vc-switch")||null}function $k(){return document.querySelector("#__vconsole")||null}const Qb=C("debugdefines");bo('if(!globalThis["NEEDLE_ENGINE_VERSION"]) globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";'),bo('if(!globalThis["NEEDLE_ENGINE_GENERATOR"]) globalThis["NEEDLE_ENGINE_GENERATOR"] = "unknown";'),bo('if(!globalThis["NEEDLE_PROJECT_BUILD_TIME"]) globalThis["NEEDLE_PROJECT_BUILD_TIME"] = "unknown";'),bo('if(!globalThis["NEEDLE_PUBLIC_KEY"]) globalThis["NEEDLE_PUBLIC_KEY"] = "unknown";'),bo('globalThis["__NEEDLE_ENGINE_VERSION__"] = "4.7.0-alpha";'),bo('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";'),bo('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Fri Jul 25 2025 19:09:52 GMT+0000 (Coordinated Universal Time)";'),bo('globalThis["__NEEDLE_PUBLIC_KEY__"] = "'+NEEDLE_PUBLIC_KEY+'";');const ws="4.7.0-alpha",jd="undefined",_g="Fri Jul 25 2025 19:09:52 GMT+0000 (Coordinated Universal Time)";Qb&&console.log(`Engine version: ${ws} (generator: ${jd})
146
146
  Project built at ${_g}`);const Ea=NEEDLE_PUBLIC_KEY,En="needle_isActiveInHierarchy",xr="builtin_components",oc="needle_editor_guid";function bo(n){try{(0,eval)(n)}catch(e){Qb&&console.error(e)}}let Yb,Kb=null;function xs(){return Yb}function wg(n){if(n==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}Kb!==n&&(Kb=n,Yb=new n)}const Mi=Symbol("shadowDomOwner"),Hk=C("debugpatch");function Dd(n,e,t,s){const o=Hk===e;if(!t&&!s)return;const r=e+"___needle";qk(n,e,t,s);const l=Object.getOwnPropertyDescriptor(n,e),c=n[e];o&&console.log("Patch",n.constructor.name,e,l,c),l?(o&&console.log("Apply patch with existing descriptor",n.constructor.name,e,l),typeof l.value=="function"&&(n[e]=Jb(l.value,n,e))):(o&&console.log("Create patch with new property",n.constructor.name,e,l),Object.defineProperty(n,e,{set:function(h){if(typeof h=="function")this[r]=Jb(h,n,e);else{const d=this[r];e_(n,e,this,d,h),this[r]=h,t_(n,e,this,d,h)}},get:function(){const h=this[r];return typeof h=="function"&&h[r]?h[r]:h}}))}function Gk(n,e,t){const s=Sg(n,e);if(s)for(let o=s.length-1;o>=0;o--){const r=s[o];r.prefix===t&&(r.prefix=null),r.postfix===t&&(r.postfix=null),!r.prefix&&!r.postfix&&s.splice(o,1)}}const Zb=Symbol("Needle:Patches:WrappedFunction");function Jb(n,e,t){if(n[Zb])return n;const s=function(...o){e_(e,t,this,...o);const r=n.apply(this,o);return t_(e,t,this,r,...o),r};return s[Zb]=!0,s}const Bd="Needle:Patches";function xg(){return globalThis[Bd]||(globalThis[Bd]=new WeakMap),globalThis[Bd]}function Sg(n,e){const t=xg().get(n);return t?t.get(e):null}function qk(n,e,t,s){let o=xg().get(n);o||(o=new Map,xg().set(n,o));let r=o.get(e);r||(r=[],o.set(e,r)),r.push({prefix:t,postfix:s})}function e_(n,e,t,...s){var o;if(!t)return;const r=Sg(n,e);if(r)for(const l of r)(o=l.prefix)==null||o.call(t,...s)}function t_(n,e,t,s,...o){var r;if(!t)return;const l=Sg(n,e);if(l)for(const c of l)(r=c.postfix)==null||r.call(t,s,...o)}const Aa=[];function Fd(n){Aa.indexOf(n)===-1&&Aa.push(n)}function Xk(n){const e=Aa.indexOf(n);e!==-1&&Aa.splice(e,1)}const Ia=[];function Cg(n){Ia.indexOf(n)===-1&&Ia.push(n)}function Qk(n){const e=Ia.indexOf(n);e!==-1&&Ia.splice(e,1)}function i_(n){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-start",{detail:n}));for(let e=0;e<Aa.length;e++)Aa[e](n)}function s_(n){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-end",{detail:n}));for(let e=0;e<Ia.length;e++)Ia[e](n)}const ct=C("debuginput");var Ud=(n=>(n.Mouse="mouse",n.Touch="touch",n.Controller="controller",n.Hand="hand",n))(Ud||{}),Be=(n=>(n.PointerDown="pointerdown",n.PointerUp="pointerup",n.PointerMove="pointermove",n.KeyDown="keydown",n.KeyUp="keyup",n.KeyPressed="keypress",n))(Be||{});class An extends PointerEvent{constructor(e,t,s){super(e,s),a(this,"clientZ"),a(this,"deviceIndex"),a(this,"origin"),a(this,"source"),a(this,"mode"),a(this,"_ray"),a(this,"space"),a(this,"isClick",!1),a(this,"isDoubleClick",!1),a(this,"_used",!1),a(this,"_pointerid"),a(this,"_pointerType"),a(this,"_type"),a(this,"metadata",{}),a(this,"intersections",new Array),a(this,"_immediatePropagationStopped",!1),a(this,"_propagationStopped",!1),this.clientZ=s.clientZ,this._pointerid=s.pointerId,this._pointerType=s.pointerType,this._type=e,this.deviceIndex=s.deviceIndex,this.origin=s.origin,this.source=t,this.mode=s.mode,this._ray=s.ray,this.space=s.device}get isSpatial(){return this.mode!="screen"}get ray(){return this._ray||(this._ray=new po(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(),ct&&console.warn("Stop propagation...",this.pointerId,this.pointerType)}}class rc extends KeyboardEvent{constructor(e,t,s){super(e,s),a(this,"source"),this.source=t}stopImmediatePropagation(){var e;super.stopImmediatePropagation(),(e=this.source)==null||e.stopImmediatePropagation()}}class Yk{constructor(e){a(this,"key"),a(this,"keyType"),a(this,"source"),this.key=e.key,this.keyType=e.type,this.source=e}}var oi=(n=>(n[n.Early=-100]="Early",n[n.Default=0]="Default",n[n.Late=100]="Late",n))(oi||{});class n_{constructor(e){a(this,"_eventListeners",{}),a(this,"_doubleClickTimeThreshold",.2),a(this,"_longPressTimeThreshold",1),a(this,"_setCursorTypes",[]),a(this,"context"),a(this,"_pointerDown",[!1]),a(this,"_pointerUp",[!1]),a(this,"_pointerClick",[!1]),a(this,"_pointerDoubleClick",[!1]),a(this,"_pointerPressed",[!1]),a(this,"_pointerPositions",[new re]),a(this,"_pointerPositionsLastFrame",[new re]),a(this,"_pointerPositionsDelta",[new re]),a(this,"_pointerPositionsRC",[new re]),a(this,"_pointerPositionDown",[new S]),a(this,"_pointerDownTime",[]),a(this,"_pointerUpTime",[]),a(this,"_pointerUpTimestamp",[]),a(this,"_pointerIds",[]),a(this,"_pointerTypes",[""]),a(this,"_mouseWheelChanged",[!1]),a(this,"_mouseWheelDeltaY",[0]),a(this,"_pointerEvent",[]),a(this,"_pointerEventsPressed",[]),a(this,"_pointerSpace",[]),a(this,"_pressedStack",new Map),a(this,"_htmlEventSource"),a(this,"onLostFocus",()=>{for(const t in this.keysPressed)this.keysPressed[t].pressed=!1}),a(this,"_receivedPointerMoveEventsThisFrame",new Array),a(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}),a(this,"onContextMenu",t=>{this.canReceiveInput(t)!==!1&&t instanceof PointerEvent&&t.pointerType}),a(this,"keysPressed",{}),a(this,"onKeyDown",t=>{if(ct&&console.log(`key down ${t.code}, ${this.context.application.hasFocus}`,t),!this.context.application.hasFocus)return;const s=this.keysPressed[t.code];if(s&&s.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 o=new rc("keydown",t,t);this.onDispatchEvent(o)}),a(this,"onKeyPressed",t=>{if(!this.context.application.hasFocus)return;const s=this.keysPressed[t.code];if(!s)return;s.pressed=!0,s.frame=this.context.time.frameCount+1;const o=new rc("keypress",t,t);this.onDispatchEvent(o)}),a(this,"onKeyUp",t=>{if(!this.context.application.hasFocus)return;const s=this.keysPressed[t.code];if(!s)return;s.pressed=!1,s.frame=this.context.time.frameCount+1;const o=new rc("keyup",t,t);this.onDispatchEvent(o)}),a(this,"onWheelWindow",t=>{document.pointerLockElement&&this.onMouseWheel(t)}),a(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 s=this._mouseWheelDeltaY[0];this._mouseWheelDeltaY[0]=s+t.deltaY}),a(this,"onPointerDown",t=>{if(this.context.isInAR||this.canReceiveInput(t)===!1)return;t.target instanceof HTMLElement&&t.target.setPointerCapture(t.pointerId);const s=this.getPointerId(t);ct&&De(`pointer down #${s}, identifier:${t.pointerId}`);const o=this.getAndUpdateSpatialObjectForScreenPosition(s,t.clientX,t.clientY),r=new An("pointerdown",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:s,button:t.button,clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,buttonName:this.getButtonName(t),device:o,pressure:t.pressure});this.onDown(r)}),a(this,"onPointerMove",t=>{if(this.context.isInAR||this._receivedPointerMoveEventsThisFrame.includes(t.pointerId))return;this._receivedPointerMoveEventsThisFrame.push(t.pointerId);let s=t.button;t.pointerType==="mouse"&&(s=this.getFirstPressedButtonForPointer(0)??0);const o=this.getPointerId(t,s);s===-1&&(s=o);const r=this.getAndUpdateSpatialObjectForScreenPosition(o,t.clientX,t.clientY),l=new An("pointermove",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:o,button:s,clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,buttonName:this.getButtonName(t),device:r,pressure:t.pressure});this.onMove(l)}),a(this,"onPointerCancel",t=>{this.context.isInAR||(ct&&console.log("Pointer cancel",t),this.onPointerUp(t))}),a(this,"onPointerUp",t=>{if(this.context.isInAR)return;t.target instanceof HTMLElement&&t.target.releasePointerCapture(t.pointerId);const s=this.getPointerId(t),o=new An("pointerup",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:s,button:t.button,clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,buttonName:this.getButtonName(t),device:this.getAndUpdateSpatialObjectForScreenPosition(s,t.clientX,t.clientY),pressure:t.pressure});this.onUp(o),this._pointerIds[s]=-1,ct&&console.log("ID="+s,"PointerId="+t.pointerId,"ALL:",[...this._pointerIds])}),a(this,"onTouchStart",t=>{if(this.context.isInAR)for(let s=0;s<t.changedTouches.length;s++){const o=t.changedTouches[s],r=this.getPointerIndex(o.identifier),l=this.getAndUpdateSpatialObjectForScreenPosition(r,o.clientX,o.clientY),c=new An("pointerdown",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:r,button:0,clientX:o.clientX,clientY:o.clientY,pointerType:"touch",buttonName:"unknown",device:l,pressure:o.force});this.onDown(c)}}),a(this,"onTouchMove",t=>{if(this.context.isInAR)for(let s=0;s<t.changedTouches.length;s++){const o=t.changedTouches[s],r=this.getPointerIndex(o.identifier),l=this.getAndUpdateSpatialObjectForScreenPosition(r,o.clientX,o.clientY),c=new An("pointermove",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:r,button:0,clientX:o.clientX,clientY:o.clientY,pointerType:"touch",buttonName:"unknown",device:l,pressure:o.force});this.onMove(c)}}),a(this,"onTouchEnd",t=>{if(this.context.isInAR)for(let s=0;s<t.changedTouches.length;s++){const o=t.changedTouches[s],r=this.getPointerIndex(o.identifier),l=new An("pointerup",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:r,button:0,clientX:o.clientX,clientY:o.clientY,pointerType:"touch",buttonName:"unknown",device:this.getAndUpdateSpatialObjectForScreenPosition(r,o.clientX,o.clientY),pressure:o.force});this.onUp(l),this._pointerIds[r]=-1}}),a(this,"tempNearPlaneVector",new S),a(this,"tempFarPlaneVector",new S),a(this,"tempLookMatrix",new se),this.context=e,this.context.post_render_callbacks.push(this.onEndOfFrame)}addEventListener(e,t,s){if(this._eventListeners[e]||(this._eventListeners[e]=[]),!t||typeof t!="function"){console.error("Invalid call to addEventListener: callback is required and must be a function!");return}s?s={...s}:s={};let o=0;s?.queue!=null&&(o=s.queue);const r=this._eventListeners[e],l=r.find(c=>c.priority===o);l?l.listeners.push({callback:t,options:s}):(r.push({priority:o,listeners:[{callback:t,options:s}]}),r.sort((c,h)=>c.priority-h.priority))}removeEventListener(e,t,s){if(!this._eventListeners[e]||!t)return;const o=this._eventListeners[e];if(s?.queue!=null){const r=o.find(c=>c.priority===s.queue);if(!r)return;const l=r.listeners.findIndex(c=>c.callback===t);l>=0&&r.listeners.splice(l,1)}else for(const r of o){const l=r.listeners.findIndex(c=>c.callback===t);l>=0&&r.listeners.splice(l,1)}}dispatchEvent(e){var t,s,o,r;let l=!1;if(e instanceof rc){const c=this._eventListeners[e.type];if(c)for(const h of c)for(let d=0;d<h.listeners.length;d++){const u=h.listeners[d];if((s=(t=u.options)==null?void 0:t.signal)!=null&&s.aborted){h.listeners.splice(d,1),d--;continue}u.options.once&&(h.listeners.splice(d,1),d--),u.callback(e)}}if(e instanceof An){const c=this._eventListeners[e.type];if(c)for(const h of c){if(l)break;for(let d=0;d<h.listeners.length;d++){const u=h.listeners[d];if((r=(o=u.options)==null?void 0:o.signal)!=null&&r.aborted){h.listeners.splice(d,1),d--;continue}if(e.immediatePropagationStopped){l=!0,ct&&console.log("immediatePropagationStopped",e.type);break}else e.propagationStopped&&(l=!0,ct&&console.log("propagationStopped",e.type));u.options.once&&(h.listeners.splice(d,1),d--),u.callback(e)}}}}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(e=0){return typeof navigator<"u"&&"getGamepads"in navigator&&navigator.getGamepads()[e]||null}setCursorPointer(){this.setCursor("pointer")}setCursorNormal(){this.unsetCursor("pointer")}setCursor(e){this._setCursorTypes.push(e),this._setCursorTypes.length>10&&this._setCursorTypes.shift(),this.updateCursor()}unsetCursor(e){for(let t=this._setCursorTypes.length-1;t>=0;t--)if(this._setCursorTypes[t]===e){this._setCursorTypes.splice(t,1),this.updateCursor();break}}updateCursor(){var e;((e=this._setCursorTypes)==null?void 0:e.length)==0?this.context.domElement.style.cursor="default":this.context.domElement.style.cursor=this._setCursorTypes[this._setCursorTypes.length-1]}getIsPointerIdInUse(e){for(const t of this._pointerEventsPressed)if(t.pointerId===e&&t.used)return!0;return!1}getPointerPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&e++;return e}getPointerPosition(e){return e>=this._pointerPositions.length?null:this._pointerPositions[e]}getPointerPositionLastFrame(e){return e>=this._pointerPositionsLastFrame.length?null:this._pointerPositionsLastFrame[e]}getPointerPositionDelta(e){return e>=this._pointerPositionsDelta.length?null:this._pointerPositionsDelta[e]}getPointerPositionRC(e){return e>=this._pointerPositionsRC.length?null:this._pointerPositionsRC[e]}getPointerDown(e){return e>=this._pointerDown.length?!1:this._pointerDown[e]}getPointerUp(e){return e>=this._pointerUp.length?!1:this._pointerUp[e]}getPointerPressed(e){return e>=this._pointerPressed.length?!1:this._pointerPressed[e]}getPointerClicked(e){return e>=this._pointerClick.length?!1:this._pointerClick[e]}getPointerDoubleClicked(e){return e>=this._pointerDoubleClick.length?!1:this._pointerDoubleClick[e]}getPointerDownTime(e){return e>=this._pointerDownTime.length?-1:this._pointerDownTime[e]}getPointerUpTime(e){return e>=this._pointerUpTime.length?-1:this._pointerUpTime[e]}getPointerLongPress(e){return e>=this._pointerDownTime.length?!1:this.getPointerPressed(e)&&this.context.time.time-this._pointerDownTime[e]>this._longPressTimeThreshold}getIsMouse(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="mouse"}getIsTouch(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="touch"}getTouchesPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&this.getIsTouch(t)&&e++;return e}getMouseWheelChanged(e=0){return e>=this._mouseWheelChanged.length?!1:this._mouseWheelChanged[e]}getMouseWheelDeltaY(e=0){return e>=this._mouseWheelDeltaY.length?0:this._mouseWheelDeltaY[e]}getPointerEvent(e){if(!(e>=this._pointerEvent.length))return this._pointerEvent[e]??void 0}*foreachPointerId(e){for(let t=0;t<this._pointerTypes.length;t++)if(this._pointerIsActive(t)){if(e!==void 0){const s=this._pointerTypes[t];if(Array.isArray(e)){let o=!1;for(const r of e)if(s===r){o=!0;break}if(!o)continue}else if(e!==s)continue}yield t}}*foreachTouchId(){for(let e=0;e<this._pointerTypes.length;e++)this._pointerTypes[e]==="touch"&&this._pointerIsActive[e]&&(yield e)}_pointerIsActive(e){return e<0?!1:this._pointerPressed[e]||this._pointerDown[e]||this._pointerUp[e]}onDownButton(e,t){let s=this._pressedStack.get(e);s||(s=[],this._pressedStack.set(e,s)),s.push(t)}onReleaseButton(e,t){const s=this._pressedStack.get(e);if(!s)return;const o=s.indexOf(t);o>=0&&s.splice(o,1)}getFirstPressedButtonForPointer(e){const t=this._pressedStack.get(e);if(t)return t[0]}getLatestPressedButtonForPointer(e){const t=this._pressedStack.get(e);if(t)return t[t.length-1]}getKeyDown(e){if(e!==void 0)return this.isKeyDown(e);for(const t in this.keysPressed){const s=this.keysPressed[t];if(s.startFrame===this.context.time.frameCount)return s.key}return null}getKeyPressed(e){if(e!==void 0)return this.isKeyPressed(e);for(const t in this.keysPressed){const s=this.keysPressed[t];if(s.pressed)return s.key}return null}getKeyUp(e){if(e!==void 0)return this.isKeyUp(e);for(const t in this.keysPressed){const s=this.keysPressed[t];return s.pressed===!1&&s.frame===this.context.time.frameCount}return null}isKeyDown(e){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const t=this.getCodeForCommonKeyName(e);if(t!==null){for(const o of t)if(this.isKeyDown(o))return!0;return!1}const s=this.keysPressed[e];return s?s.startFrame===this.context.time.frameCount&&s.pressed:!1}isKeyUp(e){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const t=this.getCodeForCommonKeyName(e);if(t!==null){for(const o of t)if(this.isKeyUp(o))return!0;return!1}const s=this.keysPressed[e];return s?s.frame===this.context.time.frameCount&&s.pressed===!1:!1}isKeyPressed(e){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const t=this.getCodeForCommonKeyName(e);if(t!==null){for(const o of t)if(this.isKeyPressed(o))return!0;return!1}const s=this.keysPressed[e];return s&&s.pressed||!1}getCodeForCommonKeyName(e){if(e.length===1){if(e>="0"&&e<="9")return["Digit"+e];if(e>="a"&&e<="z")return["Key"+e.toUpperCase()];if(e==" ")return["Space"]}switch(e){case"shift":case"Shift":return["ShiftLeft","ShiftRight"];case"control":case"Control":return["ControlLeft","ControlRight"];case"alt":case"Alt":return["AltLeft","AltRight"]}return null}createInputEvent(e){switch(e.type){case"pointerdown":ct&&De("Create Pointer down"),this.onDownButton(e.deviceIndex,e.button),this.onDown(e);break;case"pointermove":ct&&De("Create Pointer move"),this.onMove(e);break;case"pointerup":ct&&De("Create Pointer up"),this.onUp(e),this.onReleaseButton(e.deviceIndex,e.button);break}}convertScreenspaceToRaycastSpace(e){return e.x=(e.x-this.context.domX)/this.context.domWidth*2-1,e.y=-((e.y-this.context.domY)/this.context.domHeight)*2+1,e}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 e,t;window.removeEventListener("contextmenu",this.onContextMenu),(e=this._htmlEventSource)==null||e.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),(t=this._htmlEventSource)==null||t.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 e=this.context.post_render_callbacks.indexOf(this.onEndOfFrame);e>=0&&this.context.post_render_callbacks.splice(e,1),this.unbindEvents()}canReceiveInput(e){var t;return e.target===((t=this.context.renderer)==null?void 0:t.domElement)||e.target===this.context.domElement||this.context.isInAR||this.context.isInAR&&e.target===document.body&&X.isMozillaXR()?!0:(ct&&console.warn("CanReceiveInput:False for",e.target),!1)}getPointerId(e,t){return e.pointerType==="mouse"?0+(t??e.button):this.getPointerIndex(e.pointerId)}getButtonName(e){const t=e.button;if(e.pointerType==="mouse")switch(t){case 0:return"left";case 1:return"middle";case 2:return"right"}return"unknown"}getAndUpdateSpatialObjectForScreenPosition(e,t,s){let o=this._pointerSpace[e];o||(o=new E,this._pointerSpace[e]=o),this._pointerSpace[e]=o;const r=this.context.mainCamera;if(r){const l=this.tempNearPlaneVector.set(t,s,-1);this.convertScreenspaceToRaycastSpace(l);const c=this.tempFarPlaneVector.set(l.x,l.y,1);l.unproject(r),c.unproject(r);const h=r.worldUp||q(0,1,0).applyQuaternion(Se(r));this.tempLookMatrix.lookAt(c,l,h),o.position.set(l.x,l.y,l.z),o.quaternion.setFromRotationMatrix(this.tempLookMatrix)}return o}isInRect(e){if(this.context.isInXR)return!0;const t=this.context.domElement.getBoundingClientRect(),s=e.clientX,o=e.clientY,r=s>=t.x&&s<=t.right&&o>=t.y&&o<=t.bottom;return ct&&!r&&console.log("Not in rect",t,s,o),r}onDown(e){const t=e.pointerId;if(this.getPointerPressed(t)&&console.warn(`Received pointerDown for pointerId that is already pressed: ${t}`,ct?e:""),ct&&console.log(e.pointerType,"DOWN",t),!!this.isInRect(e)){for(this.setPointerState(t,this._pointerPressed,!0),this.setPointerState(t,this._pointerDown,!0),this.setPointerStateT(t,this._pointerEvent,e.source);t>=this._pointerTypes.length;)this._pointerTypes.push(e.pointerType);for(this._pointerTypes[t]=e.pointerType;t>=this._pointerPositionDown.length;)this._pointerPositionDown.push(new S);for(this._pointerPositionDown[t].set(e.clientX,e.clientY,e.clientZ??0);t>=this._pointerPositions.length;)this._pointerPositions.push(new re);this._pointerPositions[t].set(e.clientX,e.clientY),t>=this._pointerDownTime.length&&this._pointerDownTime.push(0),this._pointerDownTime[t]=this.context.time.realtimeSinceStartup,this.updatePointerPosition(e),this._pointerEventsPressed.push(e),this.onDispatchEvent(e)}}onMove(e){const t=e.pointerId,s=this.getPointerPressed(t);s===!1&&!this.isInRect(e)||e.pointerType==="touch"&&!s||(this.updatePointerPosition(e),this.setPointerStateT(t,this._pointerEvent,e.source),this.onDispatchEvent(e))}onUp(e){const t=e.pointerId;if(!this.getPointerPressed(t)){ct&&console.log(e.pointerType,"UP",t,"was not down");return}ct&&console.log(e.pointerType,"UP",t),this.setPointerState(t,this._pointerPressed,!1),this.setPointerStateT(t,this._pointerEvent,e.source),this.setPointerState(t,this._pointerUp,!0),this.updatePointerPosition(e);for(let c=this._pointerEventsPressed.length-1;c>=0;c--)if(this._pointerEventsPressed[c].pointerId===t){this._pointerEventsPressed.splice(c,1);break}if(!this._pointerPositionDown[t]){ct&&be("Received pointer up event without matching down event for button: "+t),console.warn("Received pointer up event without matching down event for button: "+t);return}const s=this._pointerUpTime[t],o=this._pointerDownTime[t],r=this.context.time.realtimeSinceStartup,l=r-o;if(t>=this._pointerUpTime.length&&this._pointerUpTime.push(-99),this._pointerUpTime[t]=r,l<1){let c=e.clientX-this._pointerPositionDown[t].x,h=e.clientY-this._pointerPositionDown[t].y,d=0;if(e.isSpatial&&e.clientZ!=null&&(d=e.clientZ-this._pointerPositionDown[t].z,c*=200,h*=200,d*=200),Math.abs(c)<5&&Math.abs(h)<5&&Math.abs(d)<5){this.setPointerState(t,this._pointerClick,!0),e.isClick=!0;const u=r-s;ct&&console.log("CLICK",t,c,h,d,u),u<this._doubleClickTimeThreshold&&u>0&&(this.setPointerState(t,this._pointerDoubleClick,!0),e.isDoubleClick=!0)}}this.onDispatchEvent(e)}updatePointerPosition(e){const t=e.pointerId;for(;t>=this._pointerPositions.length;)this._pointerPositions.push(new re);for(;t>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new re);for(;t>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new re);const s=this._pointerPositionsLastFrame[t];s.copy(this._pointerPositions[t]);const o=this._pointerPositionsDelta[t];let r=e.clientX-s.x,l=e.clientY-s.y;if(e.source instanceof MouseEvent||e.source instanceof TouchEvent){const u=e.source;r===0&&u.movementX!==0&&(r=u.movementX||0),l===0&&u.movementY!==0&&(l=u.movementY||0)}o.x+=r,o.y+=l,this._pointerPositions[t].x=e.clientX,this._pointerPositions[t].y=e.clientY;const c=e.clientX,h=e.clientY;for(;t>=this._pointerPositionsRC.length;)this._pointerPositionsRC.push(new re);const d=this._pointerPositionsRC[t];d.set(c,h),this.convertScreenspaceToRaycastSpace(d)}getPointerIndex(e){let t=-1;for(let s=0;s<this._pointerIds.length;s++){if(this._pointerIds[s]===e)return s;t===-1&&this._pointerIds[s]===-1&&(t=s)}return t!==-1?(this._pointerIds[t]=e,t):(ct&&console.log("PUSH pointerId:",e),this._pointerIds.push(e),this._pointerIds.length-1)}setPointerState(e,t,s){t[e]=s}setPointerStateT(e,t,s){return t[e]=s,s}onDispatchEvent(e){const t=J.Current;try{J.Current=this.context,this.dispatchEvent(e)}finally{J.Current=t}}}const La=new se().makeRotationY(Math.PI),Zi=new V().setFromAxisAngle(new S(0,1,0),Math.PI),Kk=C("debugwebxr");class Zk{constructor(){if(a(this,"priority",-1e5),a(this,"gameObject"),this.gameObject=new E,this.gameObject.name="Implicit XR Rig",Kk){const e=Vg(16733661);e.position.y+=.5,this.gameObject.add(e)}}isXRRig(){return!0}get isActive(){return this.gameObject.visible}}const In=C("debugwebxr"),zd=C("debugcustomgesture"),Jk="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",eM="generic-trigger",tM=new V().setFromEuler(new Dt(Cn.degToRad(0),Cn.degToRad(-90),Cn.degToRad(-90))),iM=new S(.04,-.04,0);class Pg{constructor(e,t,s){a(this,"xr"),a(this,"inputSource"),a(this,"index",0),a(this,"emitEvents",!0),a(this,"_connected",!0),a(this,"_isTracking",!1),a(this,"__gamepad"),a(this,"__hand"),a(this,"__side"),a(this,"_hitTestSource"),a(this,"_hasSelectEvent",!1),a(this,"_isMxInk",!1),a(this,"_isMetaQuestTouchController",!1),a(this,"_handJointPoses",new Map),a(this,"_gripMatrix",new se),a(this,"_gripPosition",new S),a(this,"_gripQuaternion",new V),a(this,"_linearVelocity",new S),a(this,"_rayPositionRaw",new S),a(this,"_rayRotationRaw",new V),a(this,"_rayMatrix",new se),a(this,"_rayPosition",new S),a(this,"_rayQuaternion",new V),a(this,"_gripWorldPosition",new S),a(this,"_gripWorldQuaternion",new V),a(this,"_rayWorldPosition",new S),a(this,"_rayWorldQuaternion",new V),a(this,"_pinchPosition",new S),a(this,"_ray"),a(this,"_hand_wristDotUp"),a(this,"_object"),a(this,"_gripSpaceObject"),a(this,"_raySpaceObject"),a(this,"model",null),a(this,"_debugAxesHelper",new Ci(.15)),a(this,"_debugGripAxesHelper",new Ci(.07)),a(this,"_debugRayAxesHelper",new Ci(.07)),a(this,"_hitTestSourcePromise",null),a(this,"onPointerHits",o=>{}),a(this,"_needleGamepadButtons",{}),a(this,"_buttonMap",new Map),a(this,"_motioncontroller"),a(this,"_layout"),a(this,"getMotionController"),a(this,"emitPointerDownEvent",!0),a(this,"emitPointerUpEvent",!0),a(this,"emitPointerMoveEvent",!0),a(this,"pointerMoveDistanceThreshold",.03),a(this,"pointerMoveAngleThreshold",.05),a(this,"_selectButtonIndex"),a(this,"_squeezeButtonIndex"),a(this,"onSelectStart",o=>{var r,l,c,h;if(!this.emitPointerDownEvent||this.inputSource!==o.inputSource)return;this.onUpdateFrame(o.frame),this._hasSelectEvent=!0;const d=(r=this._layout)==null?void 0:r.selectComponentId,u=(h=(c=(l=this._layout)==null?void 0:l.components[d])==null?void 0:c.gamepadIndices)==null?void 0:h.button;u!==void 0&&(this._selectButtonIndex=u),!zd&&(In&&$.DrawDirection(this.rayWorldPosition,q(0,.01,1).applyQuaternion(this.rayWorldQuaternion),16711680,10),this.emitPointerEvent(Be.PointerDown,this._selectButtonIndex||0,"xr-standard-trigger",!0,o))}),a(this,"onSelectEnd",o=>{this.emitPointerUpEvent&&(zd||this.inputSource===o.inputSource&&this.emitPointerEvent(Be.PointerUp,this._selectButtonIndex||0,"xr-standard-trigger",!0,o))}),a(this,"onSequeezeStart",o=>{var r,l,c;this.emitPointerDownEvent&&this.inputSource===o.inputSource&&(this._squeezeButtonIndex=(c=(l=(r=this._layout)==null?void 0:r.components["xr-standard-squeeze"])==null?void 0:l.gamepadIndices)==null?void 0:c.button,this._squeezeButtonIndex!==void 0&&(In&&$.DrawDirection(this.rayWorldPosition,q(0,.01,1).applyQuaternion(this.rayWorldQuaternion),255,10),this.emitPointerEvent(Be.PointerDown,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,o)))}),a(this,"onSequeezeEnd",o=>{this.emitPointerUpEvent&&this.inputSource===o.inputSource&&this._squeezeButtonIndex!==void 0&&this.emitPointerEvent(Be.PointerUp,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,o)}),a(this,"states",{}),a(this,"_didMoveLastFrame",!1),a(this,"_lastPointerMovePosition",new S),a(this,"_lastPointerMoveQuaternion",new V),a(this,"pointerInit"),this.xr=e,this.inputSource=t,this.index=s,this._object=new E,this._object.name=`NeedleXRController_${s}`,In&&(this._object.add(this._debugAxesHelper),this._gripSpaceObject=new E,this._raySpaceObject=new E,this._gripSpaceObject.name=`NeedleXRController_${s}_gripSpace`,this._raySpaceObject.name=`NeedleXRController_${s}_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 po,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(e,t){var s;if(t=t||this.xr.frame,!this.hand||!(t!=null&&t.getJointPose)||!this.xr.referenceSpace)return null;let o=(s=this._handJointPoses)==null?void 0:s.get(e);return o||(o=t.getJointPose(e,this.xr.referenceSpace),o&&this._handJointPoses.set(e,o),o)}get gripPosition(){return q(this._gripPosition)}get gripQuaternion(){return bs(this._gripQuaternion)}get gripMatrix(){return this._gripMatrix}get gripLinearVelocity(){return q(this._linearVelocity).applyQuaternion(Zi)}get rayPosition(){return q(this._rayPosition)}get rayQuaternion(){return bs(this._rayQuaternion)}get gripWorldPosition(){return q(this._gripWorldPosition)}get gripWorldQuaternion(){return bs(this._gripWorldQuaternion)}get rayWorldPosition(){return q(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 bs(this._rayWorldQuaternion)}get pinchPosition(){return q(this._pinchPosition)}updateRayWorldQuaternion(){var e;const t=(e=this.xr.context.mainCamera)==null?void 0:e.parent,s=t?Se(t):void 0;this._rayWorldQuaternion.copy(this._rayRotationRaw).multiply(Zi),s&&this._rayWorldQuaternion.premultiply(s)}get ray(){return this._ray.origin.copy(this.rayWorldPosition),this._ray.direction.copy(q(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 s=q(0,1,0).applyQuaternion(t.quaternion),o=q(0,1,0).dot(s);return this._hand_wristDotUp=o}}get isHandUpsideDown(){return this.handWristDotUp!==void 0?this.handWristDotUp<-.7:!1}get isTeleportGesture(){var e;return this.isHandUpsideDown&&((e=this.getGesture("pinch"))==null?void 0:e.isDown)}get object(){return this._object}async getModelUrl(){var e;return(e=this.getMotionController)==null?void 0:e.then(t=>t?.assetUrl||null)}_requestHitTestSource(){var e;return this._hitTestSourcePromise?this._hitTestSourcePromise:this.xr.mode==="immersive-ar"&&this.inputSource.targetRayMode==="tracked-pointer"&&this.xr.session.requestHitTestSourceForTransientInput?this._hitTestSourcePromise=((e=this.xr.session.requestHitTestSourceForTransientInput({profile:this.inputSource.profiles[0],offsetRay:new XRRay}))==null?void 0:e.then(t=>(this._hitTestSourcePromise=null,this.connected?this._hitTestSource=t:(t.cancel(),null))))??null:null}onUpdate(e){this.onUpdateFrame(e),this.updateInputEvents(),this.onUpdateMove()}onRenderDebug(){var e;$.DrawSphere(this.rayWorldPosition,.003),$.DrawDirection(this.rayWorldPosition,q(0,0,10).applyQuaternion(this.rayWorldQuaternion));const t=(this.inputSource.gripSpace?this.gripWorldPosition:this.object.worldPosition).sub(this.object.worldForward.multiplyScalar(.1)),s=this.inputSource.profiles.join(`
147
147
  `);let o=`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&&(o+=`
@@ -936,7 +936,7 @@ ${t.path}! : AssetReference;
936
936
  Could not find method ${d.method} on object ${p.name}. Please rename ${d.method} to ${y}?
937
937
  `,p[y],`
938
938
  in script: `,p),be("EventList methods must start with lowercase letter, see console for details");return}else console.warn(`EventList method:
939
- Could not find method ${d.method} on object ${p.name}`,p,typeof p[d.method])};if(typeof p[d.method]!="function"){let y=!1,v=p;for(;v;){const b=Object.getOwnPropertyDescriptor(v,d.method);if(b&&(b.writable===!0||b.set)){y=!0;break}v=Object.getPrototypeOf(v)}!y&&(F()||wt)&&f()}}if(p){let f=d.argument;if(f!==void 0?f=u(f):d.arguments!==void 0&&(f=d.arguments.map(u)),!p[d.method])console.warn(`EventList method not found: "${d.method}" on ${p?.name}`);else{f!==void 0&&!Array.isArray(f)&&(f=[f]);const y=new Un(p,d.method,f,d.enabled);l.push(y)}}else F()&&console.warn("[Debug] EventList: Could not find event listener in scene",d,t.object,e)}const c=new xe(l);wt&&console.log(c);const h=t.target;return h!==void 0&&t.path!==void 0&&c.setEventTarget(t.path,h),c}}}const CT=new ST,Eu=new WeakMap,PT=je.prototype.clone;je.prototype.clone=function(){const n=PT.call(this);return Eu.has(n)||Eu.set(n,this),n};class Cx extends es{constructor(){super([Ac,$s])}onSerialize(e,t){}onDeserialize(e,t){if(e instanceof je&&t.type===Ac){let s=e;Eu.has(s)&&(s=Eu.get(s)),s.isRenderTargetTexture=!0,s.flipY=!0,s.offset.y=1,s.repeat.y=-1,s.needsUpdate=!0,s.mipmaps=[],s instanceof XC&&(s.isCompressedTexture=!1,s.format=fd);const o=new Ac(s.image.width,s.image.height,{colorSpace:On});return o.texture=s,o}}}new Cx;class Px extends es{constructor(){super([URL])}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"&&e.length>0)return yo(t.gltfId,e)}}new Px;var OT=Object.defineProperty,kT=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&OT(e,t,o),o};class Ya extends I{awake(){ii.createIfNoneExists(this.context)}onEnable(){var e;(e=ii.get(this.context))==null||e.register(this)}onDisable(){var e;(e=ii.get(this.context))==null||e.unregister(this)}}class ji extends Ya{constructor(){super(...arguments),a(this,"targets",null),a(this,"raycastHits",[]),a(this,"ignoreSkinnedMeshes",!1)}start(){this.targets=[this.gameObject]}performRaycast(e=null){if(!this.targets)return null;e??(e=new Qs),e.targets=this.targets,e.results=this.raycastHits,e.useAcceleratedRaycast=!0;const t=e.testObject;this.ignoreSkinnedMeshes&&(e.testObject=o=>o instanceof Pn?"continue in children":t?t(o):!0);const s=this.context.physics.raycast(e);return e.testObject=t,s}}kT([m()],ji.prototype,"ignoreSkinnedMeshes");class Au extends ji{constructor(){super(),this.ignoreSkinnedMeshes=!0}}const Ox=class yC extends Ya{performRaycast(e){if(!ne.active||!yC.allow||!(e!=null&&e.ray))return null;const t=e.ray.origin;return this.context.physics.sphereOverlap(t,.015,!1,!0)}};a(Ox,"allow",!0);let Dc=Ox;class zf{static getObject(e){const t=e[Mi];return t&&(t.isComponent===!0?e=t.gameObject:e=t),e}static isInteractable(e,t){if(t&&(t.canvasGroup=void 0,t.graphic=void 0),e==null||!e.visible||(e=this.getObject(e),!e.visible))return!1;const s=this.tryFindCanvasGroup(e);if(s?.isCanvasGroup===!0&&(t&&(t.canvasGroup=s),s.blocksRaycasts===!1||s.interactable===!1))return!1;const o=Ar(e,r=>{if(r.isGraphic===!0)return r},!1);return t&&o?.isGraphic===!0&&(t.graphic=o),!(o?.raycastTarget===!1||o?.layer===2)}static tryFindCanvasGroup(e){if(!e)return null;const t=Ar(e,s=>{const o=s;if(o.blocksRaycasts!==void 0&&o.interactable!==void 0)return o},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}}function Nf(n){return n[Mi]||(n.parent?Nf(n.parent):null)}function MT(n){return n.isUI===!0||typeof n[Mi]=="object"}function Iu(n,e){if(!n)return;const t=n.material;if(t?.isMaterial===!0){const s=n.parent;s&&s.isText,t.side=e.doubleSided??!0?Pi:fo,t.shadowSide=e.doubleSided?Pi:fo,n.castShadow=e.castShadows?e.castShadows:!1,n.receiveShadow=e.receiveShadows?e.receiveShadows:!1}for(const s of n.children)Iu(s,e)}function Ka(n,e,t){n[e]===void 0&&console.warn("Field",e,"is undefined on",n);const s=Proxy.revocable(n[e],{set(l,c,h,d){const u=l[c],p=Reflect.set(l,c,h,d);return t(h,u),p}}),o=s.revoke,r=n[e];return s.revoke=()=>{n[e]=r,o()},n[e]=s.proxy,s}const kx=Symbol("Scheduled action");function RT(n,e,t=Oe.OnBeforeRender){let s=n[kx];s||(s=n[kx]={});const o=e.name;s[t]||(s[t]={});const r=s[t];if(r[o])return;function*l(){e?.call(n),r[o]=null}const c=n.startCoroutine(l(),t);r[o]=c}const Eo=C("debugeventsystem");var Wf=(n=>(n.BeforeHandleInput="BeforeHandleInput",n.AfterHandleInput="AfterHandleInput",n))(Wf||{});vx(n=>{ii.createIfNoneExists(n)});class ii extends I{constructor(){super(...arguments),a(this,"raycaster",[]),a(this,"pressedByID",new Map),a(this,"hoveredByID",new Map),a(this,"onPointerEvent",e=>{if(e===void 0||e.propagationStopped||e.defaultPrevented||e.used)return;const t=new cd(this.context.input,e);this._currentPointerEventName=e.type,t.inputSource=this.context.input,t.isClick=e.isClick,t.isDoubleClick=e.isDoubleClick,t.isDown=e.type==Be.PointerDown,t.isUp=e.type==Be.PointerUp,t.isPressed=this.context.input.getPointerPressed(e.pointerId),Eo&&(t.isDown?console.log("DOWN",t.pointerId):t.isUp&&console.log("UP",t.pointerId),t.isClick&&console.log("CLICK",t.pointerId));const s=new Qs;e.hasRay?s.ray=e.ray:s.screenPoint=this.context.input.getPointerPositionRC(e.pointerId);const o=this.performRaycast(s);if(o){for(const l of o)l.event=e,e.intersections.push(l);e.origin.onPointerHits&&e.origin.onPointerHits({sender:this,event:e,hits:o})}Eo&&t.isClick&&De("EventSystem: "+t.pointerId+" - "+this.context.time.frame+" - Up:"+t.isUp+", Down:"+t.isDown);const r={sender:this,args:t,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:r})),this.handleIntersections(o,t),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:r}))}),a(this,"_sortedHits",[]),a(this,"_testObjectsCache",new Map),a(this,"_currentlyActiveRaycaster",null),a(this,"_currentPointerEventName",null),a(this,"shouldRaycastObject",e=>{var t;const s=e&&"getComponent"in e?e.getComponent(Ya):null;if(s&&s!=this._currentlyActiveRaycaster)return!1;let o=null;if(MT(e)&&(o=(t=e[Mi])==null?void 0:t.gameObject),this._testObjectsCache.has(e)||o&&this._testObjectsCache.has(o))return this._testObjectsCache.get(e)===!1?"continue in children":!0;{let r=Mu(e,this._currentPointerEventName);if(!r&&o&&(r=Mu(o,this._currentPointerEventName)),r){this._testObjectsCache.set(e,!0);for(const l of e.children)this.shouldRaycastObject_AddToYesCache(l);return!0}return this._testObjectsCache.set(e,!1),"continue in children"}}),a(this,"_sortingBuffer",[]),a(this,"_noDepthTestingResults",[]),a(this,"out",{}),a(this,"_capturedPointer",{}),a(this,"pointerEnterSymbol",Symbol("pointerEnter")),a(this,"pointerExitSymbol",Symbol("pointerExit")),a(this,"currentActiveMeshUIComponents",[])}static ensureUpdateMeshUI(e,t,s=!1){Ao.update(e,t,s)}static markUIDirty(e){Ao.markDirty()}static createIfNoneExists(e){e.scene.getComponent(ii)||e.scene.addComponent(ii)}static get(e){return this.createIfNoneExists(e),e.scene.getComponent(ii)}static get instance(){return this.get(J.Current)}register(e){var t;e&&this.raycaster&&!this.raycaster.includes(e)&&((t=this.raycaster)==null||t.push(e))}unregister(e){var t,s;const o=(t=this.raycaster)==null?void 0:t.indexOf(e);o!==void 0&&o!==-1&&((s=this.raycaster)==null||s.splice(o,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(Ya)||this.context.scene.addComponent(ji)}onEnable(){this.context.input.addEventListener(Be.PointerDown,this.onPointerEvent),this.context.input.addEventListener(Be.PointerUp,this.onPointerEvent),this.context.input.addEventListener(Be.PointerMove,this.onPointerEvent)}onDisable(){this.context.input.removeEventListener(Be.PointerDown,this.onPointerEvent),this.context.input.removeEventListener(Be.PointerUp,this.onPointerEvent),this.context.input.removeEventListener(Be.PointerMove,this.onPointerEvent)}onBeforeRender(){this.resetMeshUIStates()}shouldRaycastObject_AddToYesCache(e){this._testObjectsCache.set(e,!0);for(const t of e.children)this.shouldRaycastObject_AddToYesCache(t)}performRaycast(e){if(!this.raycaster)return null;this._testObjectsCache.clear(),this._sortedHits.length=0,e||(e=new Qs),e.testObject=this.shouldRaycastObject;for(const t of this.raycaster){if(!t.activeAndEnabled)continue;this._currentlyActiveRaycaster=t;const s=t.performRaycast(e);this._currentlyActiveRaycaster=null,s&&s.length>0&&this._sortedHits.push(...s)}return this._sortedHits.sort((t,s)=>t.distance-s.distance),this._sortedHits}assignHitInformation(e,t){t?(e.intersection=t,e.point=t.point,e.normal=t.normal,e.face=t.face,e.distance=t.distance,e.instanceId=t.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,t){var s;if(e!=null&&e.length){e=this.sortCandidates(e);for(const r of e){if(t.event.immediatePropagationStopped)return!1;if(this.assignHitInformation(t,r),this.handleEventOnObject(r.object,t))return!0}}this.assignHitInformation(t,e?.[0]),this.invokePointerCapture(t);const o=this.hoveredByID.get(t.pointerId);return o&&this.propagatePointerExit(o.obj,o.data,null),this.hoveredByID.delete(t.pointerId),t.isUp&&((s=this.pressedByID.get(t.pointerId))==null||s.handlers.forEach(r=>this.invokeOnPointerUp(t,r)),this.pressedByID.delete(t.pointerId)),!1}sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let t=0;t<e.length;t++){const s=e[t],o=s.object;if(o.material&&o.material.depthTest===!1){this._noDepthTestingResults.push(s);continue}this._sortingBuffer.push(s)}for(const t of this._sortingBuffer)this._noDepthTestingResults.push(t);return this._noDepthTestingResults}handleEventOnObject(e,t){if(!this.testIsVisible(e))return t.isClick&&Eo&&console.log("not allowed",e),!1;if(t.pointerId===void 0)return Eo&&console.error("Event without pointer can't be handled",t),!1;t.object=e;const s=e.parent,o=t.isClick??!1;let r=null;if(s&&s.isUI){const d=(t.isPressed||t.isClick)??!1;if(s[Mi]){const u=s[Mi].gameObject;if(u){if(!zf.isInteractable(u,this.out))return!1;r=this.out.canvasGroup??null,this.handleMeshUIIntersection(e,d),e=u}}}o&&Eo&&console.log(this.context.time.frame,e);const l=this.hoveredByID.get(t.pointerId),c=l?.obj;c!==e&&c&&this.propagatePointerExit(c,l.data,e);const h=this.hoveredByID.get(t.pointerId);if(h?(h.obj=e,h.data=t):this.hoveredByID.set(t.pointerId,{obj:e,data:t}),t.isDown){const d=this.pressedByID.get(t.pointerId);d?(d.obj=e,d.data=t):this.pressedByID.set(t.pointerId,{obj:e,data:t,handlers:new Set})}return(r===null||r.interactable)&&this.handleMainInteraction(e,t,c??null),!0}propagate(e,t){for(;e;)P.foreachComponent(e,s=>{t(s)},!1),e=e.parent}handleMainInteraction(e,t,s){const o=this.pressedByID.get(t.pointerId),r=s!==e;let l=!0;switch(t.event.pointerType){case"mouse":case"touch":const c=this.context.input.getPointerPositionLastFrame(t.pointerId),h=this.context.input.getPointerPosition(t.pointerId);l=c&&!W.approximately(c,h);break}this.propagate(e,c=>{var h;const d=c;d.interactable!==!1&&(!d.activeAndEnabled||!d.enabled||(d.onPointerEnter&&r&&this.handlePointerEnter(d,t),t.isDown&&d.onPointerDown&&(d.onPointerDown(t),o?.handlers.add(d),this.handlePointerCapture(t,d)),d.onPointerMove&&(l&&d.onPointerMove(t),this.handlePointerCapture(t,d)),t.isUp&&(d.onPointerUp&&(this.invokeOnPointerUp(t,d),o?.handlers.delete(d)),d.onPointerExit&&((h=t.event)==null?void 0:h.pointerType)===Ud.Touch&&(this.handlePointerExit(d,t),this.hoveredByID.delete(t.pointerId))),t.isClick&&d.onPointerClick&&d.onPointerClick(t)))}),t.isUp&&(o?.handlers.forEach(c=>{this.invokeOnPointerUp(t,c)}),this.pressedByID.delete(t.pointerId))}propagatePointerExit(e,t,s){this.propagate(e,o=>{if(!o.gameObject||o.destroyed)return;const r=o;if(r.onPointerExit||r.onPointerEnter){if(s&&this.isChild(s,o.gameObject))return;this.handlePointerExit(r,t)}})}invokeOnPointerUp(e,t){var s;(s=t.onPointerUp)==null||s.call(t,e),this.releasePointerCapture(e,t)}handlePointerEnter(e,t){e.onPointerEnter&&this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!0)&&e.onPointerEnter(t),this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!1)}handlePointerExit(e,t){e.onPointerExit&&this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!0)&&e.onPointerExit(t),this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!1)}updatePointerState(e,t,s,o){let r=e[s];if(o)return r&&r.includes(t)?!1:(r=r||[],r.push(t),e[s]=r,!0);{if(!r||!r.includes(t))return!1;const l=r.indexOf(t);return l!==-1&&r.splice(l,1),!0}}handlePointerCapture(e,t){if(e.z__pointer_ctured){e.z__pointer_ctured=!1;const s=e.pointerId;if(t.onPointerMove){const o=this._capturedPointer[s]||[];o.push(t),this._capturedPointer[s]=o}else F()&&!t.z__warned_no_pointermove&&(t.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,t))}releasePointerCapture(e,t){const s=e.pointerId;if(this._capturedPointer[s]){const o=this._capturedPointer[s].indexOf(t);o!==-1&&(this._capturedPointer[s].splice(o,1),Eo&&console.log("released pointer capture",s,t,this._capturedPointer))}}invokePointerCapture(e){var t;if(e.event.type===Be.PointerMove){const s=e.pointerId,o=this._capturedPointer[s];if(o){Eo&&console.log("Captured",s,o);for(let r=0;r<o.length;r++){const l=o[r];if(l.destroyed){o.splice(r,1),r--;continue}(t=l.onPointerMove)==null||t.call(l,e)}}}}isChild(e,t){return!e||!t?!1:e===t?!0:e.parent?this.isChild(e.parent,t):!1}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}handleMeshUIIntersection(e,t){const s=Ao.updateState(e,t);return s&&this.currentActiveMeshUIComponents.push(s),s!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&Ao.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){const t=this.currentActiveMeshUIComponents[e];Ao.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?P.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}}class Ao{static markDirty(){this.needsUpdate=!0}static update(e,t,s=!1){if(s){e.update();return}const o=t.time.frameCount;for(const r of this.lastUpdateFrame)if(r.context===t){if(o===r.frame)return;r.frame=o;let l=this.needsUpdate||o<1;r.nextUpdate<=o&&(l=!0),l&&(Eo&&console.log("Update threemeshui"),this.needsUpdate=!1,r.nextUpdate=o+60,e.update());return}this.lastUpdateFrame=[{context:t,frame:o,nextUpdate:o+60}],e.update(),this.needsUpdate=!1}static updateState(e,t){let s=null;if(e&&(s=this.findBlockOrTextInParent(e),s&&s!==this.lastSelected)){if(s.interactable===!1)return null;this.needsUpdate=!0}return s}static resetLastSelected(){const e=this.lastSelected;e&&(this.lastSelected=null,this.resetState(e))}static resetState(e){e&&(this.needsUpdate=!0)}static findBlockOrTextInParent(e){return e?e.isBlock||e.isText?e:this.findBlockOrTextInParent(e.parent):null}}a(Ao,"lastSelected",null),a(Ao,"lastUpdateFrame",[]),a(Ao,"needsUpdate",!1);var TT=Object.defineProperty,Ue=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&TT(e,t,o),o};const is=C("debugorbit"),Vf=C("freecam"),Bc=C("debugcamerafit"),Lu=C("smoothcam"),ET={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let $f;class Fc extends CustomEvent{constructor(e,t){super("target-reached",{detail:{controls:e,type:t}})}}class _e extends I{constructor(){super(...arguments),a(this,"autoTarget",!0),a(this,"autoFit",!1),a(this,"enableRotate",!0),a(this,"autoRotate",!1),a(this,"autoRotateSpeed",1),a(this,"minAzimuthAngle",1/0),a(this,"maxAzimuthAngle",1/0),a(this,"minPolarAngle",0),a(this,"maxPolarAngle",Math.PI),a(this,"enableKeys",!1),a(this,"enableDamping",!0),a(this,"dampingFactor",.1),a(this,"enableZoom",!0),a(this,"minZoom",0),a(this,"maxZoom",1/0),a(this,"zoomSpeed",1),a(this,"zoomToCursor",!1),a(this,"enablePan",!0),a(this,"lookAtConstraint",null),a(this,"lookAtConstraint01",1),a(this,"allowInterrupt",!0),a(this,"middleClickToFocus",!0),a(this,"doubleClickToFocus",!0),a(this,"clickBackgroundToFitScene",2),a(this,"debugLog",!1),a(this,"targetLerpDuration",1),a(this,"_controls",null),a(this,"_cameraObject",null),a(this,"_lookTargetLerpActive",!1),a(this,"_lookTargetStartPosition",new S),a(this,"_lookTargetEndPosition",new S),a(this,"_lookTargetLerp01",0),a(this,"_lookTargetLerpDuration",0),a(this,"_cameraLerpActive",!1),a(this,"_cameraStartPosition",new S),a(this,"_cameraEndPosition",new S),a(this,"_cameraLerp01",0),a(this,"_cameraLerpDuration",0),a(this,"_fovLerpActive",!1),a(this,"_fovLerpStartValue",0),a(this,"_fovLerpEndValue",0),a(this,"_fovLerp01",0),a(this,"_fovLerpDuration",0),a(this,"_inputs",0),a(this,"_enableTime",0),a(this,"_startedListeningToKeyEvents",!1),a(this,"_eventSystem"),a(this,"_afterHandleInputFn"),a(this,"_camera",null),a(this,"_syncedTransform"),a(this,"_didSetTarget",0),a(this,"targetElement",null),a(this,"_activePointerEvents"),a(this,"_lastTimeClickOnBackground",-1),a(this,"_clickOnBackgroundCount",0),a(this,"_onPointerDown",e=>{this._activePointerEvents.push(e)}),a(this,"_onPointerDownLate",e=>{e.used&&this._controls&&(this._controls.enabled=!1)}),a(this,"_onPointerUp",e=>{for(let t=this._activePointerEvents.length-1;t>=0;t--){const s=this._activePointerEvents[t];if(s.pointerId===e.pointerId&&s.button===e.button){this._activePointerEvents.splice(t,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 t=this.context.time.time-this._lastTimeClickOnBackground;this._lastTimeClickOnBackground=this.context.time.time,this.clickBackgroundToFitScene<=1||t<this.clickBackgroundToFitScene*.15?(this._clickOnBackgroundCount+=1,this._clickOnBackgroundCount>=this.clickBackgroundToFitScene-1&&this.fitCamera(this.context.scene.children,{immediate:!1})):this._clickOnBackgroundCount=0}is&&console.log(this.clickBackgroundToFitScene,e.intersections.length,this._clickOnBackgroundCount)}}),a(this,"_onPointerUpLate",e=>{this.doubleClickToFocus&&e.isDoubleClick&&!e.used&&this.setTargetFromRaycast()}),a(this,"_orbitStartAngle",0),a(this,"onControlsChangeStarted",()=>{this._controls&&(this._orbitStartAngle=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle()),this._syncedTransform&&this._syncedTransform.requestOwnership()}),a(this,"onControlsChangeEnded",()=>{if(this._controls&&this.autoTarget){const e=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle()-this._orbitStartAngle;Math.abs(e)<.01?(is&&console.debug("OrbitControls: No movement detected, updating target now"),this.updateTargetNow()):is&&console.debug("OrbitControls: Movement detected",e)}}),a(this,"_shouldDisable",!1),a(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}))}),a(this,"_haveAttachedKeyboardEvents",!1)}get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){var t;(t=this.controls)==null||t.addEventListener("start",e)}get targetLerpSpeed(){return 5}set targetLerpSpeed(e){this.targetLerpDuration=1/e}awake(){is&&console.debug("OrbitControls",this),this._didSetTarget=0,this._startedListeningToKeyEvents=!1}start(){this._eventSystem=ii.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(Wf.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){var e,t;(e=this._controls)==null||e.dispose(),(t=this._eventSystem)==null||t.removeEventListener(Wf.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._didSetTarget=0,this._enableTime=this.context.time.time;const e=P.getComponent(this.gameObject,ci);this._camera=e;let t=e?.threeCamera;if(!t&&this.gameObject instanceof we&&(t=this.gameObject),t&&rg(t,this,!0),!this._controls&&t instanceof E){this._cameraObject=t;const s=this.targetElement??this.context.renderer.domElement,o=t?.quaternion.clone();this._controls=new $v(t,s),t?.quaternion.copy(o),$f===void 0&&($f={...this._controls.keys});const r=ee(t),l=this.gameObject.worldForward,c=r.clone().sub(l.multiplyScalar(2.5));this._controls.target.copy(c)}if(this._controls)if(Vf&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,X.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=P.getComponent(this.gameObject,sn)??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&&rg(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 e,t,s;const o=new po((e=this._cameraObject)==null?void 0:e.worldPosition,(t=this._cameraObject)==null?void 0:t.worldForward.multiplyScalar(-1)),r=this.context.physics.raycastFromRay(o),l=r.length>0?r[0]:void 0;l&&l.distance>this.minZoom&&l.distance<this.maxZoom&&(is&&$.DrawWireSphere(l.point,.1,16711680,2),(s=this._controls)==null||s.target.copy(r[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 e,t,s,o;if(!!this._controls){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)&&(e=this.context.input.getPointerPositionDelta(0))!=null&&e.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 r=P.getComponent(this.gameObject,ci);if(r&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log("NO TARGET");const l=ee(r.threeCamera),c=Math.max(.01,l.length()),h=new S(0,0,-c).applyMatrix4(r.threeCamera.matrixWorld);is&&$.DrawLine(l,h,5592575,10),this.setLookTargetPosition(h,!0)}if(!this.setLookTargetFromConstraint()){const l=new Qs;l.screenPoint=new re(0,0),l.lineThreshold=.1;const c=this.context.physics.raycast(l);c.length>0&&this.setLookTargetPosition(c[0].point,!0),Bc&&console.log("OrbitControls hits",...c)}}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 Fc(this,"camera"));else{const r=W.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,r)}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 Fc(this,"lookat"));else{const r=W.easeInOutCubic(this._lookTargetLerp01);this._controls.target.lerpVectors(this._lookTargetStartPosition,this._lookTargetEndPosition,r)}if(this._fovLerpActive&&this._cameraObject){const r=this._cameraObject;if(this._fovLerp01+=this.context.time.deltaTime/this._fovLerpDuration,this._fovLerp01>=1)r.fov=this._fovLerpEndValue,this._fovLerpActive=!1;else{const l=W.easeInOutCubic(this._fovLerp01);r.fov=W.lerp(this._fovLerpStartValue,this._fovLerpEndValue,l)}r.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(r=>r.used),this._controls.keys=this.enableKeys?$f:ET,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,Vf||(((s=(t=this._camera)==null?void 0:t.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 Lu=="number"||Lu===!0){this._controls.enableDamping=!0;const r=typeof Lu=="number"?Lu:.99;this._controls.dampingFactor=Math.max(.001,1-Math.min(1,r))}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||(!Vf&&(o=this.lookAtConstraint)!=null&&o.locked&&this.setLookTargetFromConstraint(0,this.lookAtConstraint01),this._controls.update(this.context.time.deltaTime),is&&$.DrawWireSphere(this._controls.target,.1,65280))}}}setCameraAndLookTarget(e,t=!1){if(!e)return(F()||is)&&console.warn("[OrbitControls] setCameraAndLookTarget target is null"),!1;if(!(e instanceof E)&&!(e instanceof ci))return(F()||is)&&console.warn("[OrbitControls] setCameraAndLookTarget target is not an Object3D or Camera"),!1;e instanceof ci&&(e=e.gameObject);const s=e.worldPosition,o=e.worldForward;e instanceof QC&&(is&&console.debug("[OrbitControls] setCameraAndLookTarget flip forward direction for camera"),o.multiplyScalar(-1));const r=new po(s,o);return is&&$.DrawRay(r.origin,r.direction,16711680,10),this.setTargetFromRaycast(r,t)||this.setLookTargetPosition(r.at(2,q()),t),this.setCameraTargetPosition(s,t),!0}setCameraTargetPosition(e,t=!1){var s;e&&(e instanceof E&&(e=ee(e)),this._cameraEndPosition||(this._cameraEndPosition=new S),this._cameraEndPosition.copy(e),t===!0?(this._cameraLerpActive=!1,this._cameraObject&&this._cameraObject.position.copy(this._cameraEndPosition)):this._cameraObject&&(this._cameraLerpActive=!0,this._cameraLerp01=0,this._cameraStartPosition.copy((s=this._cameraObject)==null?void 0:s.position),typeof t=="number"?this._cameraLerpDuration=t:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setFieldOfView(e,t=!1){var s;if(!this._controls||typeof e!="number")return;const o=(s=this._camera)==null?void 0:s.threeCamera;o&&(t===!0?o.fov=e:(this._fovLerpActive=!0,this._fovLerp01=0,this._fovLerpStartValue=o.fov,this._fovLerpEndValue=e,typeof t=="number"?this._fovLerpDuration=t:this._fovLerpDuration=this.targetLerpDuration))}setLookTargetPosition(e=null,t=!1){this._controls&&e&&(e instanceof E&&(e=ee(e)),this._lookTargetEndPosition.copy(e),this._didSetTarget++,is&&(console.warn("OrbitControls: setLookTargetPosition",e,t),$.DrawWireSphere(this._lookTargetEndPosition,.2,16711680,2)),t===!0?this._controls.target.copy(this._lookTargetEndPosition):(this._lookTargetLerpActive=!0,this._lookTargetLerp01=0,this._lookTargetStartPosition.copy(this._controls.target),typeof t=="number"?this._lookTargetLerpDuration=t:this._lookTargetLerpDuration=this.targetLerpDuration))}get lookTargetLerpActive(){return this._lookTargetLerpActive}stopLookTargetLerp(){this._lookTargetLerpActive=!1}setLookTargetFromConstraint(e=0,t=1){var s,o;if(!this._controls||((s=this.lookAtConstraint)==null?void 0:s.enabled)===!1)return!1;const r=(o=this.lookAtConstraint)==null?void 0:o.sources;if(r&&r.length>0){const l=r[e];if(l)return l.getWorldPosition(this._lookTargetEndPosition),this.lerpLookTarget(this._lookTargetEndPosition,t),!0}return!1}lerpTarget(e,t){return this.lerpLookTarget(e,t)}lerpLookTarget(e,t){this._controls&&(t>=1?this._controls.target.copy(e):this._controls.target.lerp(e,t))}setTargetFromRaycast(e,t=!1){if(!this.controls)return!1;const s=e?this.context.physics.raycastFromRay(e):this.context.physics.raycast();for(const o of s)if(o.distance>0&&P.isActiveInHierarchy(o.object)){const r=Nf(o.object);if(r){const l=r.canvas;if(l!=null&&l.screenspace)break}return this.setLookTargetPosition(o.point,t),!0}return!1}fitCamera(e,t){var s,o;if(this.context.isInXR)return;let r;if(Array.isArray(e)?r=e:e&&"type"in e?r=e.children:e&&typeof e=="object"&&!(e instanceof E)&&!Array.isArray(e)&&(t=e,r=t.objects),r&&!Array.isArray(r)&&(r=r.children),(!Array.isArray(r)||r&&r.length<=0)&&(r=this.context.scene.children),!Array.isArray(r)||r.length<=0){console.warn("No objects to fit camera to...");return}const l=this._cameraObject,c=this._controls;if(!l||!c){console.warn("No camera or controls found to fit camera to objects...");return}t||(t={});const{immediate:h=!1,centerCamera:d="y",cameraNearFar:u="auto",fitOffset:p=1.1,fov:g=l?.fov}=t,f=new S,y=new S,v=si(r,void 0,(o=(s=this._camera)==null?void 0:s.threeCamera)==null?void 0:o.layers),b=v.clone();l.updateMatrixWorld(),l.updateProjectionMatrix(),v.getCenter(y);const _=new S;if(v.getSize(_),v.applyMatrix4(l.matrixWorldInverse),v.getSize(f),v.setFromCenterAndSize(y,f),Number.isNaN(f.x)||Number.isNaN(f.y)||Number.isNaN(f.z)){console.warn("Camera fit size resultet in NaN",l,v,[...r]);return}if(f.length()<=1e-10){Bc&&console.warn("Camera fit size is zero",v,[...r]);return}const w=t.fov||l.fov,x=2*Math.atan(Math.tan(w*Math.PI/360/2)*l.aspect)/Math.PI*360,k=f.y/(2*Math.atan(Math.PI*w/360)),M=f.x/(2*Math.atan(Math.PI*x/360)),T=p*Math.max(k,M)+f.z/2;Bc&&console.log("Fit camera to objects",{fitHeightDistance:k,fitWidthDistance:M,distance:T,verticalFov:w,horizontalFov:x}),this.maxZoom=T*10,this.minZoom=T*.01;const L=.05,D=y.clone();if(D.y-=f.y*L,this.setLookTargetPosition(D,h),this.setFieldOfView(t.fov,h),u==null||u=="auto"){const U=P.findObjectOfType(en),B=U?U.radius:0,Q=Math.max(_.x,_.y,_.z,B);l.near=T/100,l.far=Q+T*10,U&&(this.maxZoom=Math.max(Math.min(this.maxZoom,B*.5),T))}const z=c.getDistance();z<this.minZoom&&(this.minZoom=z*.9),z>this.maxZoom&&(this.maxZoom=z*1.1),l.updateMatrixWorld(),l.updateProjectionMatrix();const j=ee(l),H=y.clone();H.sub(j),d==="y"&&(H.y=0),H.normalize(),H.multiplyScalar(T),d==="y"&&(H.y+=-L*4*T);let K=y.clone().sub(H);l.parent&&(K=l.parent.worldToLocal(K)),this.setCameraTargetPosition(K,h),(Bc||t.debug)&&($.DrawWireBox3(v,16777011,10),$.DrawWireBox3(b,65280,10),!this._haveAttachedKeyboardEvents&&Bc&&(this._haveAttachedKeyboardEvents=!0,document.body.addEventListener("keydown",U=>{if(U.code==="KeyF"){let B;this._cameraObject instanceof we&&(B=Math.random()*Math.random()*170+10),this.fitCamera({objects:r,fitOffset:p,immediate:!1,fov:B})}U.code==="KeyV"&&this._cameraObject instanceof we&&(this._cameraObject.fov=60)}))),this.onBeforeRender()}}Ue([m()],_e.prototype,"autoTarget"),Ue([m()],_e.prototype,"autoFit"),Ue([m()],_e.prototype,"enableRotate"),Ue([m()],_e.prototype,"autoRotate"),Ue([m()],_e.prototype,"autoRotateSpeed"),Ue([m()],_e.prototype,"minAzimuthAngle"),Ue([m()],_e.prototype,"maxAzimuthAngle"),Ue([m()],_e.prototype,"minPolarAngle"),Ue([m()],_e.prototype,"maxPolarAngle"),Ue([m()],_e.prototype,"enableKeys"),Ue([m()],_e.prototype,"enableDamping"),Ue([m()],_e.prototype,"dampingFactor"),Ue([m()],_e.prototype,"enableZoom"),Ue([m()],_e.prototype,"minZoom"),Ue([m()],_e.prototype,"maxZoom"),Ue([m()],_e.prototype,"zoomSpeed"),Ue([m()],_e.prototype,"enablePan"),Ue([m(Fr)],_e.prototype,"lookAtConstraint"),Ue([m()],_e.prototype,"lookAtConstraint01"),Ue([m()],_e.prototype,"allowInterrupt"),Ue([m()],_e.prototype,"middleClickToFocus"),Ue([m()],_e.prototype,"doubleClickToFocus"),Ue([m()],_e.prototype,"clickBackgroundToFitScene"),Ue([m()],_e.prototype,"targetLerpDuration");var AT=Object.defineProperty,IT=Object.getOwnPropertyDescriptor,Yt=(n,e,t,s)=>{for(var o=s>1?void 0:s?IT(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&AT(e,t,o),o},Io=(n=>(n[n.None=0]="None",n[n.Skybox=1]="Skybox",n[n.SolidColor=2]="SolidColor",n[n.Uninitialized=4]="Uninitialized",n))(Io||{});const Lo=C("debugcam"),Mx=C("debugscreenpointtoray");var jo;const Ut=(jo=class extends I{constructor(){super(...arguments),a(this,"_nearClipPlane",.1),a(this,"_farClipPlane",1e3),a(this,"orthographic",!1),a(this,"orthographicSize",5),a(this,"ARBackgroundAlpha",0),a(this,"_cullingMask",4294967295),a(this,"_backgroundBlurriness"),a(this,"_backgroundIntensity"),a(this,"_backgroundRotation"),a(this,"_environmentIntensity"),a(this,"_targetTexture",null),a(this,"_backgroundColor"),a(this,"_fov"),a(this,"_cam",null),a(this,"_clearFlags",2),a(this,"_skybox"),a(this,"_frustum"),a(this,"_projScreenMatrix",new se)}get isCamera(){return!0}get aspect(){return this._cam instanceof we?this._cam.aspect:this.context.domWidth/this.context.domHeight}set aspect(n){this._cam instanceof we&&this._cam.aspect!==n&&(this._cam.aspect=n,this._cam.updateProjectionMatrix())}get fieldOfView(){return this._cam instanceof we?this._cam.fov:this._fov}set fieldOfView(n){const e=this.fieldOfView!=n;if(this._fov=n,e&&this._cam&&this._cam instanceof we){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(n){const e=this._nearClipPlane!=n;this._nearClipPlane=n,this._cam&&(e||this._cam.near!=n)&&(this._cam.near=n,this._cam.updateProjectionMatrix())}get farClipPlane(){return this._farClipPlane}set farClipPlane(n){const e=this._farClipPlane!=n;this._farClipPlane=n,this._cam&&(e||this._cam.far!=n)&&(this._cam.far=n,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(n){if(typeof n=="string")switch(n){case"skybox":n=1;break;case"solidcolor":n=2;break;default:n=0;break}n!==this._clearFlags&&(this._clearFlags=n,this.applyClearFlagsIfIsActiveCamera())}set cullingMask(n){this._cullingMask=n,this._cam&&(this._cam.layers.mask=n)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}set cullingLayer(n){this.cullingMask=(1<<n|0)>>>0}set backgroundBlurriness(n){n!==this._backgroundBlurriness&&(n===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(n,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}set backgroundIntensity(n){n!==this._backgroundIntensity&&(n===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(n,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}set backgroundRotation(n){n!==this._backgroundRotation&&(n===void 0?this._backgroundRotation=void 0:this._backgroundRotation=n,this.applyClearFlagsIfIsActiveCamera())}get backgroundRotation(){return this._backgroundRotation}set environmentIntensity(n){this._environmentIntensity=n}get environmentIntensity(){return this._environmentIntensity}get backgroundColor(){return this._backgroundColor??null}set backgroundColor(n){n&&(this._backgroundColor||(this._backgroundColor=new he(1,1,1,1)),this._backgroundColor.copy(n),(!("alpha"in n)||n.alpha===void 0)&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera())}set targetTexture(n){this._targetTexture=n}get targetTexture(){return this._targetTexture}get cam(){return this.threeCamera}get threeCamera(){return this.activeAndEnabled&&this.buildCamera(),this._cam}screenPointToRay(n,e,t){const s=this.threeCamera,o=jo._origin;o.set(n,e,-1),this.context.input.convertScreenspaceToRaycastSpace(o),Mx&&console.log("screenPointToRay",n.toFixed(2),e.toFixed(2),"now:",o.x.toFixed(2),o.y.toFixed(2),"isInXR:"+this.context.isInXR),o.z=-1,o.unproject(s);const r=jo._direction.set(o.x,o.y,o.z),l=ee(s);return r.sub(l),r.normalize(),t?(t.set(l,r),t):new po(l.clone(),r.clone())}getFrustum(){return this._frustum||(this._frustum=new jv,this.updateFrustum()),this._frustum}updateFrustum(){this._frustum||(this._frustum=new jv),this._frustum.setFromProjectionMatrix(this.getProjectionScreenMatrix(this._projScreenMatrix,!0),this.context.renderer.coordinateSystem)}getProjectionScreenMatrix(n,e){return e&&this._projScreenMatrix.multiplyMatrices(this.threeCamera.projectionMatrix,this.threeCamera.matrixWorldInverse),n===this._projScreenMatrix?n:n.copy(this._projScreenMatrix)}awake(){Mx&&window.addEventListener("pointerdown",n=>{const e=n.clientX,t=n.clientY;console.log("touch",e.toFixed(2),t.toFixed(2));const s=this.screenPointToRay(e,t),o="#"+Math.floor(Math.random()*16777215).toString(16);$.DrawRay(s.origin,s.direction,o,10)})}onEnable(){Lo&&console.log(`Camera enabled: "${this.name}". ClearFlags=${Io[this._clearFlags]}`,this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),jT(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 n=this.context.renderer;if(n){const e=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,n),e?.applyClearFlags()}}}buildCamera(){if(this._cam)return;const n=this.gameObject.isCamera;let e=null;if(n?(e=this.gameObject,e?.layers.enableAll(),e instanceof we&&(this._fov=e.fov)):e=this.gameObject.children[0],e&&e.isCamera)e instanceof we&&(this._fov&&(e.fov=this._fov),e.near=this._nearClipPlane,e.far=this._farClipPlane,e.updateProjectionMatrix());else if(!this.orthographic)e=new we(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(e.fov=this.fieldOfView),this.gameObject.add(e);else{const t=this.orthographicSize*100;e=new ud(window.innerWidth/-t,window.innerWidth/t,window.innerHeight/t,window.innerHeight/-t,this._nearClipPlane,this._farClipPlane),this.gameObject.add(e)}this._cam=e,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(n){this.context.mainCameraComponent===this&&this.applyClearFlags(n)}applyClearFlags(n){var e;if(!this._cam){Lo&&console.log("Camera does not exist (apply clear flags)");return}if(this.fieldOfView=this._fov,Lo){const s=`[Camera] Apply ClearFlags: ${Io[this._clearFlags]} - "${this.name}"`;console.debug(s)}const t=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(jo.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||n?.applySkybox===!0)&&this.applySceneSkybox(),this._backgroundBlurriness!==void 0&&!this.context.domElement.getAttribute("background-blurriness")?this.context.scene.backgroundBlurriness=this._backgroundBlurriness:Lo&&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:Lo&&console.warn(`Camera "${this.name}" has no background intensity`);break;case 2:if(this._backgroundColor&&!t){let s=this._backgroundColor.alpha;jo.backgroundShouldBeTransparent(this.context)&&(s=this.ARBackgroundAlpha??0),this.context.scene.background=null,(e=this.context.xr)!=null&&e.isVR?this.context.renderer.setClearColor(kb(this._backgroundColor).convertLinearToSRGB()):this.context.renderer.setClearColor(this._backgroundColor,s)}else this._backgroundColor||Lo&&console.warn(`[Camera] has no background color "${this.name}" `);break;case 4:t||(this.context.scene.background=null,this.context.renderer.setClearColor(0,0));break}}applySceneSkybox(){this._skybox||(this._skybox=new LT(this)),this._skybox.apply()}static backgroundShouldBeTransparent(n){var e,t,s,o;const r=(e=n.renderer.xr)==null?void 0:e.getSession();if(!r)return!1;if(typeof r._transparent=="boolean")return r._transparent;const l=r.environmentBlendMode;Lo&&De("Environment blend mode: "+l+" on "+navigator.userAgent);let c=l==="additive"||l==="alpha-blend";return n.isInAR&&l==="opaque"&&((t=navigator.userAgent)!=null&&t.includes("OculusBrowser")||(s=navigator.userAgent)!=null&&s.includes("Mozilla")&&(o=navigator.userAgent)!=null&&o.includes("Mobile WebXRViewer/v2"))&&(c=!0),r._transparent=c,c}},a(jo,"_origin",new S),a(jo,"_direction",new S),jo);Yt([m()],Ut.prototype,"aspect",1),Yt([m()],Ut.prototype,"fieldOfView",1),Yt([m()],Ut.prototype,"nearClipPlane",1),Yt([m()],Ut.prototype,"farClipPlane",1),Yt([m()],Ut.prototype,"clearFlags",1),Yt([m()],Ut.prototype,"orthographic",2),Yt([m()],Ut.prototype,"orthographicSize",2),Yt([m()],Ut.prototype,"ARBackgroundAlpha",2),Yt([m()],Ut.prototype,"cullingMask",1),Yt([m()],Ut.prototype,"backgroundBlurriness",1),Yt([m()],Ut.prototype,"backgroundIntensity",1),Yt([m(Dt)],Ut.prototype,"backgroundRotation",1),Yt([m()],Ut.prototype,"environmentIntensity",1),Yt([m(he)],Ut.prototype,"backgroundColor",1),Yt([m(Ac)],Ut.prototype,"targetTexture",1);let ci=Ut;class LT{constructor(e){a(this,"_camera"),a(this,"_skybox"),this._camera=e}get context(){var e;return(e=this._camera)==null?void 0:e.context}apply(){var e;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 t=this.context.domElement.getAttribute("background-image")||this.context.domElement.getAttribute("background-color")||this.context.domElement.getAttribute("skybox-image");Lo&&console.debug(`[Camera] Apply Skybox ${(e=this._skybox)==null?void 0:e.name} ${t} - "${this._camera.name}"`),t!=null&&t.length||(this._skybox.mapping=kn,this.context.scene.background=this._skybox)}}}function jT(n){C("freecam")&&n.context.mainCameraComponent===n&&P.getOrAddComponent(n.gameObject,_e)}class zn extends I{constructor(){super(...arguments),a(this,"_listener",null),a(this,"onInteraction",()=>{this.destroyed||this.listener==null||this.addListenerIfItExists()})}get listener(){return this._listener==null&&(this._listener=new YC),this._listener}onEnable(){Ln.registerWaitForInteraction(this.onInteraction),this.addListenerIfItExists()}onDisable(){Ln.unregisterWaitForInteraction(this.onInteraction),this.removeListenerIfItExists()}addListenerIfItExists(){const e=this._listener;if(!e||e!=null&&e.parent)return;const t=this.context.mainCameraComponent||P.getComponentInParent(this.gameObject,ci);t!=null&&t.threeCamera?t.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 DT=Object.defineProperty,BT=Object.getOwnPropertyDescriptor,Os=(n,e,t,s)=>{for(var o=s>1?void 0:s?BT(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&DT(e,t,o),o};const Et=C("debugaudio"),ss=class ur extends I{constructor(){super(...arguments),a(this,"clip",""),a(this,"playOnAwake",!1),a(this,"preload",!0),a(this,"playInBackground",!0),a(this,"_spatialBlend",0),a(this,"_minDistance",1),a(this,"_maxDistance",100),a(this,"_volume",1),a(this,"rollOffMode",0),a(this,"_loop",!1),a(this,"sound",null),a(this,"helper",null),a(this,"wasPlaying",!1),a(this,"audioLoader",null),a(this,"shouldPlay",!1),a(this,"_lastClipStartedLoading",null),a(this,"_audioElement",null),a(this,"onVisibilityChanged",()=>{switch(document.visibilityState){case"hidden":(this.playInBackground===!1||X.isMobileDevice())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":Et&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,ur.userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&ur.userInteractionRegistered&&this.wasPlaying&&this.play();break}}),a(this,"onApplicationMuteChanged",()=>{var e,t;this.context.application.muted?(e=this.sound)==null||e.setVolume(0):(t=this.sound)==null||t.setVolume(this.volume)}),a(this,"createAudio",e=>{if(this.destroyed){Et&&console.warn("AudioSource destroyed, not creating audio",this.name);return}Et&&console.log("AudioBuffer finished loading",e);const t=this.Sound;if(!t){Et&&console.warn("Failed getting sound?",this.name);return}t.isPlaying&&t.stop(),e&&t.setBuffer(e),t.loop=this._loop,this.context.application.muted?t.setVolume(0):t.setVolume(this.volume),t.autoplay=this.shouldPlay&&ur.userInteractionRegistered,this.applySpatialDistanceSettings(),t.isPlaying&&t.stop(),ur.registerWaitForAllowAudio(this.__onAllowAudioCallback)}),a(this,"__onAllowAudioCallback",()=>{this.shouldPlay&&this.play()}),a(this,"_lastContextTime",0),a(this,"_hasEnded",!0),a(this,"_needUpdateSpatialDistanceSettings",!1)}static get userInteractionRegistered(){return Ln.userInteractionRegistered}static registerWaitForAllowAudio(e){Ln.registerWaitForInteraction(e)}get isPlaying(){var e;return((e=this.sound)==null?void 0:e.isPlaying)??!1}get duration(){var e,t;return(t=(e=this.sound)==null?void 0:e.buffer)==null?void 0:t.duration}get time01(){var e;const t=this.duration;return t&&this.sound?((e=this.sound)==null?void 0:e.context.currentTime)/t:0}set time01(e){const t=this.duration;t&&this.sound&&(this.time=e*t)}get time(){var e,t;return(e=this.sound)!=null&&e.source?((t=this.sound.source)==null?void 0:t.context.currentTime)-this._lastContextTime+this.sound.offset:0}set time(e){if(this.sound){if(e===this.sound.offset)return;const t=this.isPlaying;this.stop(),this.sound.offset=e,t&&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&&(Et&&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&&ur.userInteractionRegistered){let t=this.gameObject.getComponent(zn)??this.context.mainCamera.getComponent(zn)??xc(zn,this.context,!1);!t&&this.context.mainCamera&&(t=this.context.mainCamera.addComponent(zn)),t!=null&&t.listener?(this.sound=new KC(t.listener),(e=this.gameObject)==null||e.add(this.sound)):Et&&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(){Et&&console.log("[AudioSource]",this),this.audioLoader=new jm,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),ur.userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():ur.registerWaitForAllowAudio(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.onNewClip(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(Og.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(Og.MuteChanged,this.onApplicationMuteChanged),this.pause()}applySpatialDistanceSettings(){const e=this.sound;if(!e)return;this._needUpdateSpatialDistanceSettings=!1;const t=W.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(Et&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+t),e.setRefDistance(t),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?Et&&!this.helper&&(this.helper=new tO(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(Et&&console.log(e),e.endsWith(".mp3")||e.endsWith(".wav")){if(this.audioLoader||(this.audioLoader=new jm),this.shouldPlay=!0,this._lastClipStartedLoading===e){Et&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=e,Et&&console.log("load audio",e);const t=await this.audioLoader.loadAsync(e).catch(console.error);if(this.destroyed)return;this._lastClipStartedLoading===e&&(this._lastClipStartedLoading=null),t&&this.createAudio(t)}else console.warn("Unsupported audio clip type",e);else this.shouldPlay=!0,this.createAudio()}play(e=void 0){var t,s,o;!e&&this.clip&&(e=this.clip),e!==void 0&&typeof e!="string"&&!(e instanceof MediaStream)&&(F()&&console.warn("Called play on AudioSource with unknown argument type:",e+`
939
+ Could not find method ${d.method} on object ${p.name}`,p,typeof p[d.method])};if(typeof p[d.method]!="function"){let y=!1,v=p;for(;v;){const b=Object.getOwnPropertyDescriptor(v,d.method);if(b&&(b.writable===!0||b.set)){y=!0;break}v=Object.getPrototypeOf(v)}!y&&(F()||wt)&&f()}}if(p){let f=d.argument;if(f!==void 0?f=u(f):d.arguments!==void 0&&(f=d.arguments.map(u)),!p[d.method])console.warn(`EventList method not found: "${d.method}" on ${p?.name}`);else{f!==void 0&&!Array.isArray(f)&&(f=[f]);const y=new Un(p,d.method,f,d.enabled);l.push(y)}}else F()&&console.warn("[Debug] EventList: Could not find event listener in scene",d,t.object,e)}const c=new xe(l);wt&&console.log(c);const h=t.target;return h!==void 0&&t.path!==void 0&&c.setEventTarget(t.path,h),c}}}const CT=new ST,Eu=new WeakMap,PT=je.prototype.clone;je.prototype.clone=function(){const n=PT.call(this);return Eu.has(n)||Eu.set(n,this),n};class Cx extends es{constructor(){super([Ac,$s])}onSerialize(e,t){}onDeserialize(e,t){if(e instanceof je&&t.type===Ac){let s=e;Eu.has(s)&&(s=Eu.get(s)),s.isRenderTargetTexture=!0,s.flipY=!0,s.offset.y=1,s.repeat.y=-1,s.needsUpdate=!0,s.mipmaps=[],s instanceof XC&&(s.isCompressedTexture=!1,s.format=fd);const o=new Ac(s.image.width,s.image.height,{colorSpace:On});return o.texture=s,o}}}new Cx;class Px extends es{constructor(){super([URL])}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"&&e.length>0)return yo(t.gltfId,e)}}new Px;var OT=Object.defineProperty,kT=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&OT(e,t,o),o};class Ya extends I{awake(){ii.createIfNoneExists(this.context)}onEnable(){var e;(e=ii.get(this.context))==null||e.register(this)}onDisable(){var e;(e=ii.get(this.context))==null||e.unregister(this)}}class ji extends Ya{constructor(){super(...arguments),a(this,"targets",null),a(this,"raycastHits",[]),a(this,"ignoreSkinnedMeshes",!1)}start(){this.targets=[this.gameObject]}performRaycast(e=null){if(!this.targets)return null;e??(e=new Qs),e.targets=this.targets,e.results=this.raycastHits,e.useAcceleratedRaycast=!0;const t=e.testObject;this.ignoreSkinnedMeshes&&(e.testObject=o=>o instanceof Pn?"continue in children":t?t(o):!0);const s=this.context.physics.raycast(e);return e.testObject=t,s}}kT([m()],ji.prototype,"ignoreSkinnedMeshes");class Au extends ji{constructor(){super(),this.ignoreSkinnedMeshes=!0}}const Ox=class yC extends Ya{performRaycast(e){if(!ne.active||!yC.allow||!(e!=null&&e.ray))return null;const t=e.ray.origin;return this.context.physics.sphereOverlap(t,.015,!1,!0)}};a(Ox,"allow",!0);let Dc=Ox;class zf{static getObject(e){const t=e[Mi];return t&&(t.isComponent===!0?e=t.gameObject:e=t),e}static isInteractable(e,t){if(t&&(t.canvasGroup=void 0,t.graphic=void 0),e==null||!e.visible||(e=this.getObject(e),!e.visible))return!1;const s=this.tryFindCanvasGroup(e);if(s?.isCanvasGroup===!0&&(t&&(t.canvasGroup=s),s.blocksRaycasts===!1||s.interactable===!1))return!1;const o=Ar(e,r=>{if(r.isGraphic===!0)return r},!1);return t&&o?.isGraphic===!0&&(t.graphic=o),!(o?.raycastTarget===!1||o?.layer===2)}static tryFindCanvasGroup(e){if(!e)return null;const t=Ar(e,s=>{const o=s;if(o.blocksRaycasts!==void 0&&o.interactable!==void 0)return o},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}}function Nf(n){return n[Mi]||(n.parent?Nf(n.parent):null)}function MT(n){return n.isUI===!0||typeof n[Mi]=="object"}function Iu(n,e){if(!n)return;const t=n.material;if(t?.isMaterial===!0){const s=n.parent;s&&s.isText,t.side=e.doubleSided??!0?Pi:fo,t.shadowSide=e.doubleSided?Pi:fo,n.castShadow=e.castShadows?e.castShadows:!1,n.receiveShadow=e.receiveShadows?e.receiveShadows:!1}for(const s of n.children)Iu(s,e)}function Ka(n,e,t){n[e]===void 0&&console.warn("Field",e,"is undefined on",n);const s=Proxy.revocable(n[e],{set(l,c,h,d){const u=l[c],p=Reflect.set(l,c,h,d);return t(h,u),p}}),o=s.revoke,r=n[e];return s.revoke=()=>{n[e]=r,o()},n[e]=s.proxy,s}const kx=Symbol("Scheduled action");function RT(n,e,t=Oe.OnBeforeRender){let s=n[kx];s||(s=n[kx]={});const o=e.name;s[t]||(s[t]={});const r=s[t];if(r[o])return;function*l(){e?.call(n),r[o]=null}const c=n.startCoroutine(l(),t);r[o]=c}const Eo=C("debugeventsystem");var Wf=(n=>(n.BeforeHandleInput="BeforeHandleInput",n.AfterHandleInput="AfterHandleInput",n))(Wf||{});vx(n=>{ii.createIfNoneExists(n)});class ii extends I{constructor(){super(...arguments),a(this,"raycaster",[]),a(this,"pressedByID",new Map),a(this,"hoveredByID",new Map),a(this,"onPointerEvent",e=>{if(e===void 0||e.propagationStopped||e.defaultPrevented||e.used)return;const t=new cd(this.context.input,e);this._currentPointerEventName=e.type,t.inputSource=this.context.input,t.isClick=e.isClick,t.isDoubleClick=e.isDoubleClick,t.isDown=e.type==Be.PointerDown,t.isUp=e.type==Be.PointerUp,t.isPressed=this.context.input.getPointerPressed(e.pointerId),Eo&&(t.isDown?console.log("DOWN",t.pointerId):t.isUp&&console.log("UP",t.pointerId),t.isClick&&console.log("CLICK",t.pointerId));const s=new Qs;e.hasRay?s.ray=e.ray:s.screenPoint=this.context.input.getPointerPositionRC(e.pointerId);const o=this.performRaycast(s);if(o){for(const l of o)l.event=e,e.intersections.push(l);e.origin.onPointerHits&&e.origin.onPointerHits({sender:this,event:e,hits:o})}Eo&&t.isClick&&De("EventSystem: "+t.pointerId+" - "+this.context.time.frame+" - Up:"+t.isUp+", Down:"+t.isDown);const r={sender:this,args:t,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:r})),this.handleIntersections(o,t),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:r}))}),a(this,"_sortedHits",[]),a(this,"_testObjectsCache",new Map),a(this,"_currentlyActiveRaycaster",null),a(this,"_currentPointerEventName",null),a(this,"shouldRaycastObject",e=>{var t;const s=e&&"getComponent"in e?e.getComponent(Ya):null;if(s&&s!=this._currentlyActiveRaycaster)return!1;let o=null;if(MT(e)&&(o=(t=e[Mi])==null?void 0:t.gameObject),this._testObjectsCache.has(e)||o&&this._testObjectsCache.has(o))return this._testObjectsCache.get(e)===!1?"continue in children":!0;{let r=Mu(e,this._currentPointerEventName);if(!r&&o&&(r=Mu(o,this._currentPointerEventName)),r){this._testObjectsCache.set(e,!0);for(const l of e.children)this.shouldRaycastObject_AddToYesCache(l);return!0}return this._testObjectsCache.set(e,!1),"continue in children"}}),a(this,"_sortingBuffer",[]),a(this,"_noDepthTestingResults",[]),a(this,"out",{}),a(this,"_capturedPointer",{}),a(this,"pointerEnterSymbol",Symbol("pointerEnter")),a(this,"pointerExitSymbol",Symbol("pointerExit")),a(this,"currentActiveMeshUIComponents",[])}static ensureUpdateMeshUI(e,t,s=!1){Ao.update(e,t,s)}static markUIDirty(e){Ao.markDirty()}static createIfNoneExists(e){e.scene.getComponent(ii)||e.scene.addComponent(ii)}static get(e){return this.createIfNoneExists(e),e.scene.getComponent(ii)}static get instance(){return this.get(J.Current)}register(e){var t;e&&this.raycaster&&!this.raycaster.includes(e)&&((t=this.raycaster)==null||t.push(e))}unregister(e){var t,s;const o=(t=this.raycaster)==null?void 0:t.indexOf(e);o!==void 0&&o!==-1&&((s=this.raycaster)==null||s.splice(o,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(Ya)||this.context.scene.addComponent(ji)}onEnable(){this.context.input.addEventListener(Be.PointerDown,this.onPointerEvent),this.context.input.addEventListener(Be.PointerUp,this.onPointerEvent),this.context.input.addEventListener(Be.PointerMove,this.onPointerEvent)}onDisable(){this.context.input.removeEventListener(Be.PointerDown,this.onPointerEvent),this.context.input.removeEventListener(Be.PointerUp,this.onPointerEvent),this.context.input.removeEventListener(Be.PointerMove,this.onPointerEvent)}onBeforeRender(){this.resetMeshUIStates()}shouldRaycastObject_AddToYesCache(e){this._testObjectsCache.set(e,!0);for(const t of e.children)this.shouldRaycastObject_AddToYesCache(t)}performRaycast(e){if(!this.raycaster)return null;this._testObjectsCache.clear(),this._sortedHits.length=0,e||(e=new Qs),e.testObject=this.shouldRaycastObject;for(const t of this.raycaster){if(!t.activeAndEnabled)continue;this._currentlyActiveRaycaster=t;const s=t.performRaycast(e);this._currentlyActiveRaycaster=null,s&&s.length>0&&this._sortedHits.push(...s)}return this._sortedHits.sort((t,s)=>t.distance-s.distance),this._sortedHits}assignHitInformation(e,t){t?(e.intersection=t,e.point=t.point,e.normal=t.normal,e.face=t.face,e.distance=t.distance,e.instanceId=t.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,t){var s;if(e!=null&&e.length){e=this.sortCandidates(e);for(const r of e){if(t.event.immediatePropagationStopped)return!1;if(this.assignHitInformation(t,r),this.handleEventOnObject(r.object,t))return!0}}this.assignHitInformation(t,e?.[0]),this.invokePointerCapture(t);const o=this.hoveredByID.get(t.pointerId);return o&&this.propagatePointerExit(o.obj,o.data,null),this.hoveredByID.delete(t.pointerId),t.isUp&&((s=this.pressedByID.get(t.pointerId))==null||s.handlers.forEach(r=>this.invokeOnPointerUp(t,r)),this.pressedByID.delete(t.pointerId)),!1}sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let t=0;t<e.length;t++){const s=e[t],o=s.object;if(o.material&&o.material.depthTest===!1){this._noDepthTestingResults.push(s);continue}this._sortingBuffer.push(s)}for(const t of this._sortingBuffer)this._noDepthTestingResults.push(t);return this._noDepthTestingResults}handleEventOnObject(e,t){if(!this.testIsVisible(e))return t.isClick&&Eo&&console.log("not allowed",e),!1;if(t.pointerId===void 0)return Eo&&console.error("Event without pointer can't be handled",t),!1;t.object=e;const s=e.parent,o=t.isClick??!1;let r=null;if(s&&s.isUI){const d=(t.isPressed||t.isClick)??!1;if(s[Mi]){const u=s[Mi].gameObject;if(u){if(!zf.isInteractable(u,this.out))return!1;r=this.out.canvasGroup??null,this.handleMeshUIIntersection(e,d),e=u}}}o&&Eo&&console.log(this.context.time.frame,e);const l=this.hoveredByID.get(t.pointerId),c=l?.obj;c!==e&&c&&this.propagatePointerExit(c,l.data,e);const h=this.hoveredByID.get(t.pointerId);if(h?(h.obj=e,h.data=t):this.hoveredByID.set(t.pointerId,{obj:e,data:t}),t.isDown){const d=this.pressedByID.get(t.pointerId);d?(d.obj=e,d.data=t):this.pressedByID.set(t.pointerId,{obj:e,data:t,handlers:new Set})}return(r===null||r.interactable)&&this.handleMainInteraction(e,t,c??null),!0}propagate(e,t){for(;e;)P.foreachComponent(e,s=>{t(s)},!1),e=e.parent}handleMainInteraction(e,t,s){const o=this.pressedByID.get(t.pointerId),r=s!==e;let l=!0;switch(t.event.pointerType){case"mouse":case"touch":const c=this.context.input.getPointerPositionLastFrame(t.pointerId),h=this.context.input.getPointerPosition(t.pointerId);l=c&&!W.approximately(c,h);break}this.propagate(e,c=>{var h;const d=c;d.interactable!==!1&&(!d.activeAndEnabled||!d.enabled||(d.onPointerEnter&&r&&this.handlePointerEnter(d,t),t.isDown&&d.onPointerDown&&(d.onPointerDown(t),o?.handlers.add(d),this.handlePointerCapture(t,d)),d.onPointerMove&&(l&&d.onPointerMove(t),this.handlePointerCapture(t,d)),t.isUp&&(d.onPointerUp&&(this.invokeOnPointerUp(t,d),o?.handlers.delete(d)),d.onPointerExit&&((h=t.event)==null?void 0:h.pointerType)===Ud.Touch&&(this.handlePointerExit(d,t),this.hoveredByID.delete(t.pointerId))),t.isClick&&d.onPointerClick&&d.onPointerClick(t)))}),t.isUp&&(o?.handlers.forEach(c=>{this.invokeOnPointerUp(t,c)}),this.pressedByID.delete(t.pointerId))}propagatePointerExit(e,t,s){this.propagate(e,o=>{if(!o.gameObject||o.destroyed)return;const r=o;if(r.onPointerExit||r.onPointerEnter){if(s&&this.isChild(s,o.gameObject))return;this.handlePointerExit(r,t)}})}invokeOnPointerUp(e,t){var s;(s=t.onPointerUp)==null||s.call(t,e),this.releasePointerCapture(e,t)}handlePointerEnter(e,t){e.onPointerEnter&&this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!0)&&e.onPointerEnter(t),this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!1)}handlePointerExit(e,t){e.onPointerExit&&this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!0)&&e.onPointerExit(t),this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!1)}updatePointerState(e,t,s,o){let r=e[s];if(o)return r&&r.includes(t)?!1:(r=r||[],r.push(t),e[s]=r,!0);{if(!r||!r.includes(t))return!1;const l=r.indexOf(t);return l!==-1&&r.splice(l,1),!0}}handlePointerCapture(e,t){if(e.z__pointer_ctured){e.z__pointer_ctured=!1;const s=e.pointerId;if(t.onPointerMove){const o=this._capturedPointer[s]||[];o.push(t),this._capturedPointer[s]=o}else F()&&!t.z__warned_no_pointermove&&(t.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,t))}releasePointerCapture(e,t){const s=e.pointerId;if(this._capturedPointer[s]){const o=this._capturedPointer[s].indexOf(t);o!==-1&&(this._capturedPointer[s].splice(o,1),Eo&&console.log("released pointer capture",s,t,this._capturedPointer))}}invokePointerCapture(e){var t;if(e.event.type===Be.PointerMove){const s=e.pointerId,o=this._capturedPointer[s];if(o){Eo&&console.log("Captured",s,o);for(let r=0;r<o.length;r++){const l=o[r];if(l.destroyed){o.splice(r,1),r--;continue}(t=l.onPointerMove)==null||t.call(l,e)}}}}isChild(e,t){return!e||!t?!1:e===t?!0:e.parent?this.isChild(e.parent,t):!1}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}handleMeshUIIntersection(e,t){const s=Ao.updateState(e,t);return s&&this.currentActiveMeshUIComponents.push(s),s!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&Ao.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){const t=this.currentActiveMeshUIComponents[e];Ao.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?P.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}}class Ao{static markDirty(){this.needsUpdate=!0}static update(e,t,s=!1){if(s){e.update();return}const o=t.time.frameCount;for(const r of this.lastUpdateFrame)if(r.context===t){if(o===r.frame)return;r.frame=o;let l=this.needsUpdate||o<1;r.nextUpdate<=o&&(l=!0),l&&(Eo&&console.log("Update threemeshui"),this.needsUpdate=!1,r.nextUpdate=o+60,e.update());return}this.lastUpdateFrame=[{context:t,frame:o,nextUpdate:o+60}],e.update(),this.needsUpdate=!1}static updateState(e,t){let s=null;if(e&&(s=this.findBlockOrTextInParent(e),s&&s!==this.lastSelected)){if(s.interactable===!1)return null;this.needsUpdate=!0}return s}static resetLastSelected(){const e=this.lastSelected;e&&(this.lastSelected=null,this.resetState(e))}static resetState(e){e&&(this.needsUpdate=!0)}static findBlockOrTextInParent(e){return e?e.isBlock||e.isText?e:this.findBlockOrTextInParent(e.parent):null}}a(Ao,"lastSelected",null),a(Ao,"lastUpdateFrame",[]),a(Ao,"needsUpdate",!1);var TT=Object.defineProperty,Ue=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&TT(e,t,o),o};const is=C("debugorbit"),Vf=C("freecam"),Bc=C("debugcamerafit"),Lu=C("smoothcam"),ET={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let $f;class Fc extends CustomEvent{constructor(e,t){super("target-reached",{detail:{controls:e,type:t}})}}class _e extends I{constructor(){super(...arguments),a(this,"autoTarget",!0),a(this,"autoFit",!1),a(this,"enableRotate",!0),a(this,"autoRotate",!1),a(this,"autoRotateSpeed",1),a(this,"minAzimuthAngle",1/0),a(this,"maxAzimuthAngle",1/0),a(this,"minPolarAngle",0),a(this,"maxPolarAngle",Math.PI),a(this,"enableKeys",!1),a(this,"enableDamping",!0),a(this,"dampingFactor",.1),a(this,"enableZoom",!0),a(this,"minZoom",0),a(this,"maxZoom",1/0),a(this,"zoomSpeed",1),a(this,"zoomToCursor",!1),a(this,"enablePan",!0),a(this,"lookAtConstraint",null),a(this,"lookAtConstraint01",1),a(this,"allowInterrupt",!0),a(this,"middleClickToFocus",!0),a(this,"doubleClickToFocus",!0),a(this,"clickBackgroundToFitScene",2),a(this,"debugLog",!1),a(this,"targetLerpDuration",1),a(this,"_controls",null),a(this,"_cameraObject",null),a(this,"_lookTargetLerpActive",!1),a(this,"_lookTargetStartPosition",new S),a(this,"_lookTargetEndPosition",new S),a(this,"_lookTargetLerp01",0),a(this,"_lookTargetLerpDuration",0),a(this,"_cameraLerpActive",!1),a(this,"_cameraStartPosition",new S),a(this,"_cameraEndPosition",new S),a(this,"_cameraLerp01",0),a(this,"_cameraLerpDuration",0),a(this,"_fovLerpActive",!1),a(this,"_fovLerpStartValue",0),a(this,"_fovLerpEndValue",0),a(this,"_fovLerp01",0),a(this,"_fovLerpDuration",0),a(this,"_inputs",0),a(this,"_enableTime",0),a(this,"_startedListeningToKeyEvents",!1),a(this,"_eventSystem"),a(this,"_afterHandleInputFn"),a(this,"_camera",null),a(this,"_syncedTransform"),a(this,"_didSetTarget",0),a(this,"targetElement",null),a(this,"_activePointerEvents"),a(this,"_lastTimeClickOnBackground",-1),a(this,"_clickOnBackgroundCount",0),a(this,"_onPointerDown",e=>{this._activePointerEvents.push(e)}),a(this,"_onPointerDownLate",e=>{e.used&&this._controls&&(this._controls.enabled=!1)}),a(this,"_onPointerUp",e=>{for(let t=this._activePointerEvents.length-1;t>=0;t--){const s=this._activePointerEvents[t];if(s.pointerId===e.pointerId&&s.button===e.button){this._activePointerEvents.splice(t,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 t=this.context.time.time-this._lastTimeClickOnBackground;this._lastTimeClickOnBackground=this.context.time.time,this.clickBackgroundToFitScene<=1||t<this.clickBackgroundToFitScene*.15?(this._clickOnBackgroundCount+=1,this._clickOnBackgroundCount>=this.clickBackgroundToFitScene-1&&this.fitCamera(this.context.scene.children,{immediate:!1})):this._clickOnBackgroundCount=0}is&&console.log(this.clickBackgroundToFitScene,e.intersections.length,this._clickOnBackgroundCount)}}),a(this,"_onPointerUpLate",e=>{this.doubleClickToFocus&&e.isDoubleClick&&!e.used&&this.setTargetFromRaycast()}),a(this,"_orbitStartAngle",0),a(this,"onControlsChangeStarted",()=>{this._controls&&(this._orbitStartAngle=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle()),this._syncedTransform&&this._syncedTransform.requestOwnership()}),a(this,"onControlsChangeEnded",()=>{if(this._controls&&this.autoTarget){const e=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle()-this._orbitStartAngle;Math.abs(e)<.01?(is&&console.debug("OrbitControls: No movement detected, updating target now"),this.updateTargetNow()):is&&console.debug("OrbitControls: Movement detected",e)}}),a(this,"_shouldDisable",!1),a(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}))}),a(this,"_haveAttachedKeyboardEvents",!1)}get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){var t;(t=this.controls)==null||t.addEventListener("start",e)}get targetLerpSpeed(){return 5}set targetLerpSpeed(e){this.targetLerpDuration=1/e}awake(){is&&console.debug("OrbitControls",this),this._didSetTarget=0,this._startedListeningToKeyEvents=!1}start(){this._eventSystem=ii.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(Wf.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){var e,t;(e=this._controls)==null||e.dispose(),(t=this._eventSystem)==null||t.removeEventListener(Wf.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._didSetTarget=0,this._enableTime=this.context.time.time;const e=P.getComponent(this.gameObject,ci);this._camera=e;let t=e?.threeCamera;if(!t&&this.gameObject instanceof we&&(t=this.gameObject),t&&rg(t,this,!0),!this._controls&&t instanceof E){this._cameraObject=t;const s=this.targetElement??this.context.renderer.domElement,o=t?.quaternion.clone();this._controls=new $v(t,s),t?.quaternion.copy(o),$f===void 0&&($f={...this._controls.keys});const r=ee(t),l=this.gameObject.worldForward,c=r.clone().sub(l.multiplyScalar(2.5));this._controls.target.copy(c)}if(this._controls)if(Vf&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,X.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=P.getComponent(this.gameObject,sn)??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&&rg(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 e,t,s;const o=new po((e=this._cameraObject)==null?void 0:e.worldPosition,(t=this._cameraObject)==null?void 0:t.worldForward.multiplyScalar(-1)),r=this.context.physics.raycastFromRay(o),l=r.length>0?r[0]:void 0;l&&l.distance>this.minZoom&&l.distance<this.maxZoom&&(is&&$.DrawWireSphere(l.point,.1,16711680,2),(s=this._controls)==null||s.target.copy(r[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 e,t,s,o;if(!!this._controls){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)&&(e=this.context.input.getPointerPositionDelta(0))!=null&&e.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 r=P.getComponent(this.gameObject,ci);if(r&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log("NO TARGET");const l=ee(r.threeCamera),c=Math.max(.01,l.length()),h=new S(0,0,-c).applyMatrix4(r.threeCamera.matrixWorld);is&&$.DrawLine(l,h,5592575,10),this.setLookTargetPosition(h,!0)}if(!this.setLookTargetFromConstraint()){const l=new Qs;l.screenPoint=new re(0,0),l.lineThreshold=.1;const c=this.context.physics.raycast(l);c.length>0&&this.setLookTargetPosition(c[0].point,!0),Bc&&console.log("OrbitControls hits",...c)}}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 Fc(this,"camera"));else{const r=W.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,r)}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 Fc(this,"lookat"));else{const r=W.easeInOutCubic(this._lookTargetLerp01);this._controls.target.lerpVectors(this._lookTargetStartPosition,this._lookTargetEndPosition,r)}if(this._fovLerpActive&&this._cameraObject){const r=this._cameraObject;if(this._fovLerp01+=this.context.time.deltaTime/this._fovLerpDuration,this._fovLerp01>=1)r.fov=this._fovLerpEndValue,this._fovLerpActive=!1;else{const l=W.easeInOutCubic(this._fovLerp01);r.fov=W.lerp(this._fovLerpStartValue,this._fovLerpEndValue,l)}r.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(r=>r.used),this._controls.keys=this.enableKeys?$f:ET,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,Vf||(((s=(t=this._camera)==null?void 0:t.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 Lu=="number"||Lu===!0){this._controls.enableDamping=!0;const r=typeof Lu=="number"?Lu:.99;this._controls.dampingFactor=Math.max(.001,1-Math.min(1,r))}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||(!Vf&&(o=this.lookAtConstraint)!=null&&o.locked&&this.setLookTargetFromConstraint(0,this.lookAtConstraint01),this._controls.update(this.context.time.deltaTime),is&&$.DrawWireSphere(this._controls.target,.1,65280))}}}setCameraAndLookTarget(e,t=!1){if(!e)return(F()||is)&&console.warn("[OrbitControls] setCameraAndLookTarget target is null"),!1;if(!(e instanceof E)&&!(e instanceof ci))return(F()||is)&&console.warn("[OrbitControls] setCameraAndLookTarget target is not an Object3D or Camera"),!1;e instanceof ci&&(e=e.gameObject);const s=e.worldPosition,o=e.worldForward;e instanceof QC&&(is&&console.debug("[OrbitControls] setCameraAndLookTarget flip forward direction for camera"),o.multiplyScalar(-1));const r=new po(s,o);return is&&$.DrawRay(r.origin,r.direction,16711680,10),this.setTargetFromRaycast(r,t)||this.setLookTargetPosition(r.at(2,q()),t),this.setCameraTargetPosition(s,t),!0}setCameraTargetPosition(e,t=!1){var s;e&&(e instanceof E&&(e=ee(e)),this._cameraEndPosition||(this._cameraEndPosition=new S),this._cameraEndPosition.copy(e),t===!0?(this._cameraLerpActive=!1,this._cameraObject&&this._cameraObject.position.copy(this._cameraEndPosition)):this._cameraObject&&(this._cameraLerpActive=!0,this._cameraLerp01=0,this._cameraStartPosition.copy((s=this._cameraObject)==null?void 0:s.position),typeof t=="number"?this._cameraLerpDuration=t:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setFieldOfView(e,t=!1){var s;if(!this._controls||typeof e!="number")return;const o=(s=this._camera)==null?void 0:s.threeCamera;o&&(t===!0?o.fov=e:(this._fovLerpActive=!0,this._fovLerp01=0,this._fovLerpStartValue=o.fov,this._fovLerpEndValue=e,typeof t=="number"?this._fovLerpDuration=t:this._fovLerpDuration=this.targetLerpDuration))}setLookTargetPosition(e=null,t=!1){this._controls&&e&&(e instanceof E&&(e=ee(e)),this._lookTargetEndPosition.copy(e),this._didSetTarget++,is&&(console.warn("OrbitControls: setLookTargetPosition",e,t),$.DrawWireSphere(this._lookTargetEndPosition,.2,16711680,2)),t===!0?this._controls.target.copy(this._lookTargetEndPosition):(this._lookTargetLerpActive=!0,this._lookTargetLerp01=0,this._lookTargetStartPosition.copy(this._controls.target),typeof t=="number"?this._lookTargetLerpDuration=t:this._lookTargetLerpDuration=this.targetLerpDuration))}get lookTargetLerpActive(){return this._lookTargetLerpActive}stopLookTargetLerp(){this._lookTargetLerpActive=!1}setLookTargetFromConstraint(e=0,t=1){var s,o;if(!this._controls||((s=this.lookAtConstraint)==null?void 0:s.enabled)===!1)return!1;const r=(o=this.lookAtConstraint)==null?void 0:o.sources;if(r&&r.length>0){const l=r[e];if(l)return l.getWorldPosition(this._lookTargetEndPosition),this.lerpLookTarget(this._lookTargetEndPosition,t),!0}return!1}lerpTarget(e,t){return this.lerpLookTarget(e,t)}lerpLookTarget(e,t){this._controls&&(t>=1?this._controls.target.copy(e):this._controls.target.lerp(e,t))}setTargetFromRaycast(e,t=!1){if(!this.controls)return!1;const s=e?this.context.physics.raycastFromRay(e):this.context.physics.raycast();for(const o of s)if(o.distance>0&&P.isActiveInHierarchy(o.object)){const r=Nf(o.object);if(r){const l=r.canvas;if(l!=null&&l.screenspace)break}return this.setLookTargetPosition(o.point,t),!0}return!1}fitCamera(e,t){var s,o;if(this.context.isInXR)return;let r;if(Array.isArray(e)?r=e:e&&"type"in e?r=e.children:e&&typeof e=="object"&&!(e instanceof E)&&!Array.isArray(e)&&(t=e,r=t.objects),r&&!Array.isArray(r)&&(r=r.children),(!Array.isArray(r)||r&&r.length<=0)&&(r=this.context.scene.children),!Array.isArray(r)||r.length<=0){console.warn("No objects to fit camera to...");return}const l=this._cameraObject,c=this._controls;if(!l||!c){console.warn("No camera or controls found to fit camera to objects...");return}t||(t={});const{immediate:h=!1,centerCamera:d="y",cameraNearFar:u="auto",fitOffset:p=1.1,fov:g=l?.fov}=t,f=new S,y=new S,v=si(r,void 0,(o=(s=this._camera)==null?void 0:s.threeCamera)==null?void 0:o.layers),b=v.clone();l.updateMatrixWorld(),l.updateProjectionMatrix(),v.getCenter(y);const _=new S;if(v.getSize(_),v.applyMatrix4(l.matrixWorldInverse),v.getSize(f),v.setFromCenterAndSize(y,f),Number.isNaN(f.x)||Number.isNaN(f.y)||Number.isNaN(f.z)){console.warn("Camera fit size resultet in NaN",l,v,[...r]);return}if(f.length()<=1e-10){Bc&&console.warn("Camera fit size is zero",v,[...r]);return}const w=t.fov||l.fov,x=2*Math.atan(Math.tan(w*Math.PI/360/2)*l.aspect)/Math.PI*360,k=f.y/(2*Math.atan(Math.PI*w/360)),M=f.x/(2*Math.atan(Math.PI*x/360)),T=p*Math.max(k,M)+f.z/2;Bc&&console.log("Fit camera to objects",{fitHeightDistance:k,fitWidthDistance:M,distance:T,verticalFov:w,horizontalFov:x}),this.maxZoom=T*10,this.minZoom=T*.01;const L=.05,D=y.clone();if(D.y-=f.y*L,this.setLookTargetPosition(D,h),this.setFieldOfView(t.fov,h),u==null||u=="auto"){const U=P.findObjectOfType(en),B=U?U.radius:0,Q=Math.max(_.x,_.y,_.z,B);l.near=T/100,l.far=Q+T*10,U&&(this.maxZoom=Math.max(Math.min(this.maxZoom,B*.5),T))}const z=c.getDistance();z<this.minZoom&&(this.minZoom=z*.9),z>this.maxZoom&&(this.maxZoom=z*1.1),l.updateMatrixWorld(),l.updateProjectionMatrix();const j=ee(l),H=y.clone();H.sub(j),d==="y"&&(H.y=0),H.normalize(),H.multiplyScalar(T),d==="y"&&(H.y+=-L*4*T);let K=y.clone().sub(H);l.parent&&(K=l.parent.worldToLocal(K)),this.setCameraTargetPosition(K,h),(Bc||t.debug)&&($.DrawWireBox3(v,16777011,10),$.DrawWireBox3(b,65280,10),!this._haveAttachedKeyboardEvents&&Bc&&(this._haveAttachedKeyboardEvents=!0,document.body.addEventListener("keydown",U=>{if(U.code==="KeyF"){let B;this._cameraObject instanceof we&&(B=Math.random()*Math.random()*170+10),this.fitCamera({objects:r,fitOffset:p,immediate:!1,fov:B})}U.code==="KeyV"&&this._cameraObject instanceof we&&(this._cameraObject.fov=60)}))),this.onBeforeRender()}}Ue([m()],_e.prototype,"autoTarget"),Ue([m()],_e.prototype,"autoFit"),Ue([m()],_e.prototype,"enableRotate"),Ue([m()],_e.prototype,"autoRotate"),Ue([m()],_e.prototype,"autoRotateSpeed"),Ue([m()],_e.prototype,"minAzimuthAngle"),Ue([m()],_e.prototype,"maxAzimuthAngle"),Ue([m()],_e.prototype,"minPolarAngle"),Ue([m()],_e.prototype,"maxPolarAngle"),Ue([m()],_e.prototype,"enableKeys"),Ue([m()],_e.prototype,"enableDamping"),Ue([m()],_e.prototype,"dampingFactor"),Ue([m()],_e.prototype,"enableZoom"),Ue([m()],_e.prototype,"minZoom"),Ue([m()],_e.prototype,"maxZoom"),Ue([m()],_e.prototype,"zoomSpeed"),Ue([m()],_e.prototype,"enablePan"),Ue([m(Fr)],_e.prototype,"lookAtConstraint"),Ue([m()],_e.prototype,"lookAtConstraint01"),Ue([m()],_e.prototype,"allowInterrupt"),Ue([m()],_e.prototype,"middleClickToFocus"),Ue([m()],_e.prototype,"doubleClickToFocus"),Ue([m()],_e.prototype,"clickBackgroundToFitScene"),Ue([m()],_e.prototype,"targetLerpDuration");var AT=Object.defineProperty,IT=Object.getOwnPropertyDescriptor,Yt=(n,e,t,s)=>{for(var o=s>1?void 0:s?IT(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&AT(e,t,o),o},Io=(n=>(n[n.None=0]="None",n[n.Skybox=1]="Skybox",n[n.SolidColor=2]="SolidColor",n[n.Uninitialized=4]="Uninitialized",n))(Io||{});const Lo=C("debugcam"),Mx=C("debugscreenpointtoray");var jo;const Ut=(jo=class extends I{constructor(){super(...arguments),a(this,"_nearClipPlane",.1),a(this,"_farClipPlane",1e3),a(this,"orthographic",!1),a(this,"orthographicSize",5),a(this,"ARBackgroundAlpha",0),a(this,"_cullingMask",4294967295),a(this,"_backgroundBlurriness"),a(this,"_backgroundIntensity"),a(this,"_backgroundRotation"),a(this,"_environmentIntensity"),a(this,"_targetTexture",null),a(this,"_backgroundColor"),a(this,"_fov"),a(this,"_cam",null),a(this,"_clearFlags",2),a(this,"_skybox"),a(this,"_frustum"),a(this,"_projScreenMatrix",new se)}get isCamera(){return!0}get aspect(){return this._cam instanceof we?this._cam.aspect:this.context.domWidth/this.context.domHeight}set aspect(n){this._cam instanceof we&&this._cam.aspect!==n&&(this._cam.aspect=n,this._cam.updateProjectionMatrix())}get fieldOfView(){return this._cam instanceof we?this._cam.fov:this._fov}set fieldOfView(n){const e=this.fieldOfView!=n;if(this._fov=n,e&&this._cam&&this._cam instanceof we){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(n){const e=this._nearClipPlane!=n;this._nearClipPlane=n,this._cam&&(e||this._cam.near!=n)&&(this._cam.near=n,this._cam.updateProjectionMatrix())}get farClipPlane(){return this._farClipPlane}set farClipPlane(n){const e=this._farClipPlane!=n;this._farClipPlane=n,this._cam&&(e||this._cam.far!=n)&&(this._cam.far=n,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(n){if(typeof n=="string")switch(n){case"skybox":n=1;break;case"solidcolor":n=2;break;default:n=0;break}n!==this._clearFlags&&(this._clearFlags=n,this.applyClearFlagsIfIsActiveCamera())}set cullingMask(n){this._cullingMask=n,this._cam&&(this._cam.layers.mask=n)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}set cullingLayer(n){this.cullingMask=(1<<n|0)>>>0}set backgroundBlurriness(n){n!==this._backgroundBlurriness&&(n===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(n,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}set backgroundIntensity(n){n!==this._backgroundIntensity&&(n===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(n,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}set backgroundRotation(n){n!==this._backgroundRotation&&(n===void 0?this._backgroundRotation=void 0:this._backgroundRotation=n,this.applyClearFlagsIfIsActiveCamera())}get backgroundRotation(){return this._backgroundRotation}set environmentIntensity(n){this._environmentIntensity=n}get environmentIntensity(){return this._environmentIntensity}get backgroundColor(){return this._backgroundColor??null}set backgroundColor(n){n&&(this._backgroundColor||(this._backgroundColor=new he(1,1,1,1)),this._backgroundColor.copy(n),(!("alpha"in n)||n.alpha===void 0)&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera())}set targetTexture(n){this._targetTexture=n}get targetTexture(){return this._targetTexture}get cam(){return this.threeCamera}get threeCamera(){return this.activeAndEnabled&&this.buildCamera(),this._cam}screenPointToRay(n,e,t){const s=this.threeCamera,o=jo._origin;o.set(n,e,-1),this.context.input.convertScreenspaceToRaycastSpace(o),Mx&&console.log("screenPointToRay",n.toFixed(2),e.toFixed(2),"now:",o.x.toFixed(2),o.y.toFixed(2),"isInXR:"+this.context.isInXR),o.z=-1,o.unproject(s);const r=jo._direction.set(o.x,o.y,o.z),l=ee(s);return r.sub(l),r.normalize(),t?(t.set(l,r),t):new po(l.clone(),r.clone())}getFrustum(){return this._frustum||(this._frustum=new jv,this.updateFrustum()),this._frustum}updateFrustum(){this._frustum||(this._frustum=new jv),this._frustum.setFromProjectionMatrix(this.getProjectionScreenMatrix(this._projScreenMatrix,!0),this.context.renderer.coordinateSystem)}getProjectionScreenMatrix(n,e){return e&&this._projScreenMatrix.multiplyMatrices(this.threeCamera.projectionMatrix,this.threeCamera.matrixWorldInverse),n===this._projScreenMatrix?n:n.copy(this._projScreenMatrix)}awake(){Mx&&window.addEventListener("pointerdown",n=>{const e=n.clientX,t=n.clientY;console.log("touch",e.toFixed(2),t.toFixed(2));const s=this.screenPointToRay(e,t),o="#"+Math.floor(Math.random()*16777215).toString(16);$.DrawRay(s.origin,s.direction,o,10)})}onEnable(){Lo&&console.log(`Camera enabled: "${this.name}". ClearFlags=${Io[this._clearFlags]}`,this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),jT(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 n=this.context.renderer;if(n){const e=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,n),e?.applyClearFlags()}}}buildCamera(){if(this._cam)return;const n=this.gameObject.isCamera;let e=null;if(n?(e=this.gameObject,e?.layers.enableAll(),e instanceof we&&(this._fov=e.fov)):e=this.gameObject.children[0],e&&e.isCamera)e instanceof we&&(this._fov&&(e.fov=this._fov),e.near=this._nearClipPlane,e.far=this._farClipPlane,e.updateProjectionMatrix());else if(!this.orthographic)e=new we(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(e.fov=this.fieldOfView),this.gameObject.add(e);else{const t=this.orthographicSize*100;e=new ud(window.innerWidth/-t,window.innerWidth/t,window.innerHeight/t,window.innerHeight/-t,this._nearClipPlane,this._farClipPlane),this.gameObject.add(e)}this._cam=e,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(n){this.context.mainCameraComponent===this&&this.applyClearFlags(n)}applyClearFlags(n){var e;if(!this._cam){Lo&&console.log("Camera does not exist (apply clear flags)");return}if(this.fieldOfView=this._fov,Lo){const s=`[Camera] Apply ClearFlags: ${Io[this._clearFlags]} - "${this.name}"`;console.debug(s)}const t=this.context.domElement.getAttribute("background-image")||this.context.domElement.getAttribute("background-color");switch(this._clearFlags){case 0:return;case 1:if(jo.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||n?.applySkybox===!0)&&this.applySceneSkybox(),this._backgroundBlurriness!==void 0&&!this.context.domElement.getAttribute("background-blurriness")?this.context.scene.backgroundBlurriness=this._backgroundBlurriness:Lo&&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:Lo&&console.warn(`Camera "${this.name}" has no background intensity`);break;case 2:if(this._backgroundColor&&!t){let s=this._backgroundColor.alpha;jo.backgroundShouldBeTransparent(this.context)&&(s=this.ARBackgroundAlpha??0),this.context.scene.background=null,(e=this.context.xr)!=null&&e.isVR?this.context.renderer.setClearColor(kb(this._backgroundColor).convertLinearToSRGB()):this.context.renderer.setClearColor(this._backgroundColor,s)}else this._backgroundColor||Lo&&console.warn(`[Camera] has no background color "${this.name}" `);break;case 4:t||(this.context.scene.background=null,this.context.renderer.setClearColor(0,0));break}}applySceneSkybox(){this._skybox||(this._skybox=new LT(this)),this._skybox.apply()}static backgroundShouldBeTransparent(n){var e,t,s,o;const r=(e=n.renderer.xr)==null?void 0:e.getSession();if(!r)return!1;if(typeof r._transparent=="boolean")return r._transparent;const l=r.environmentBlendMode;Lo&&De("Environment blend mode: "+l+" on "+navigator.userAgent);let c=l==="additive"||l==="alpha-blend";return n.isInAR&&l==="opaque"&&((t=navigator.userAgent)!=null&&t.includes("OculusBrowser")||(s=navigator.userAgent)!=null&&s.includes("Mozilla")&&(o=navigator.userAgent)!=null&&o.includes("Mobile WebXRViewer/v2"))&&(c=!0),r._transparent=c,c}},a(jo,"_origin",new S),a(jo,"_direction",new S),jo);Yt([m()],Ut.prototype,"aspect",1),Yt([m()],Ut.prototype,"fieldOfView",1),Yt([m()],Ut.prototype,"nearClipPlane",1),Yt([m()],Ut.prototype,"farClipPlane",1),Yt([m()],Ut.prototype,"clearFlags",1),Yt([m()],Ut.prototype,"orthographic",2),Yt([m()],Ut.prototype,"orthographicSize",2),Yt([m()],Ut.prototype,"ARBackgroundAlpha",2),Yt([m()],Ut.prototype,"cullingMask",1),Yt([m()],Ut.prototype,"backgroundBlurriness",1),Yt([m()],Ut.prototype,"backgroundIntensity",1),Yt([m(Dt)],Ut.prototype,"backgroundRotation",1),Yt([m()],Ut.prototype,"environmentIntensity",1),Yt([m(he)],Ut.prototype,"backgroundColor",1),Yt([m(Ac)],Ut.prototype,"targetTexture",1);let ci=Ut;class LT{constructor(e){a(this,"_camera"),a(this,"_skybox"),this._camera=e}get context(){var e;return(e=this._camera)==null?void 0:e.context}apply(){var e;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 t=this.context.domElement.getAttribute("background-image")||this.context.domElement.getAttribute("background-color")||this.context.domElement.getAttribute("skybox-image");Lo&&console.debug(`[Camera] Apply Skybox ${(e=this._skybox)==null?void 0:e.name} ${t} - "${this._camera.name}"`),t!=null&&t.length||(this._skybox.mapping=kn,this.context.scene.background=this._skybox)}}}function jT(n){C("freecam")&&n.context.mainCameraComponent===n&&P.getOrAddComponent(n.gameObject,_e)}class zn extends I{constructor(){super(...arguments),a(this,"_listener",null),a(this,"onInteraction",()=>{this.destroyed||this.listener==null||this.addListenerIfItExists()})}get listener(){return this._listener==null&&(this._listener=new YC),this._listener}onEnable(){Ln.registerWaitForInteraction(this.onInteraction),this.addListenerIfItExists()}onDisable(){Ln.unregisterWaitForInteraction(this.onInteraction),this.removeListenerIfItExists()}addListenerIfItExists(){const e=this._listener;if(!e||e!=null&&e.parent)return;const t=this.context.mainCameraComponent||P.getComponentInParent(this.gameObject,ci);t!=null&&t.threeCamera?t.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 DT=Object.defineProperty,BT=Object.getOwnPropertyDescriptor,Os=(n,e,t,s)=>{for(var o=s>1?void 0:s?BT(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&DT(e,t,o),o};const Et=C("debugaudio"),ss=class ur extends I{constructor(){super(...arguments),a(this,"clip",""),a(this,"playOnAwake",!1),a(this,"preload",!0),a(this,"playInBackground",!0),a(this,"_spatialBlend",0),a(this,"_minDistance",1),a(this,"_maxDistance",100),a(this,"_volume",1),a(this,"rollOffMode",0),a(this,"_loop",!1),a(this,"sound",null),a(this,"helper",null),a(this,"wasPlaying",!1),a(this,"audioLoader",null),a(this,"shouldPlay",!1),a(this,"_lastClipStartedLoading",null),a(this,"_audioElement",null),a(this,"onVisibilityChanged",()=>{switch(document.visibilityState){case"hidden":(this.playInBackground===!1||X.isMobileDevice())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":Et&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,ur.userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&ur.userInteractionRegistered&&this.wasPlaying&&this.play();break}}),a(this,"onApplicationMuteChanged",()=>{var e,t;this.context.application.muted?(e=this.sound)==null||e.setVolume(0):(t=this.sound)==null||t.setVolume(this.volume)}),a(this,"createAudio",e=>{if(this.destroyed){Et&&console.warn("AudioSource destroyed, not creating audio",this.name);return}Et&&console.log("AudioBuffer finished loading",e);const t=this.Sound;if(!t){Et&&console.warn("Failed getting sound?",this.name);return}t.isPlaying&&t.stop(),e&&t.setBuffer(e),t.loop=this._loop,this.context.application.muted?t.setVolume(0):t.setVolume(this.volume),t.autoplay=this.shouldPlay&&ur.userInteractionRegistered,this.applySpatialDistanceSettings(),t.isPlaying&&t.stop(),ur.registerWaitForAllowAudio(this.__onAllowAudioCallback)}),a(this,"__onAllowAudioCallback",()=>{this.shouldPlay&&this.play()}),a(this,"_lastContextTime",0),a(this,"_hasEnded",!0),a(this,"_needUpdateSpatialDistanceSettings",!1)}static get userInteractionRegistered(){return Ln.userInteractionRegistered}static registerWaitForAllowAudio(e){Ln.registerWaitForInteraction(e)}get isPlaying(){var e;return((e=this.sound)==null?void 0:e.isPlaying)??!1}get duration(){var e,t;return(t=(e=this.sound)==null?void 0:e.buffer)==null?void 0:t.duration}get time01(){var e;const t=this.duration;return t&&this.sound?((e=this.sound)==null?void 0:e.context.currentTime)/t:0}set time01(e){const t=this.duration;t&&this.sound&&(this.time=e*t)}get time(){var e,t;return(e=this.sound)!=null&&e.source?((t=this.sound.source)==null?void 0:t.context.currentTime)-this._lastContextTime+this.sound.offset:0}set time(e){if(this.sound){if(e===this.sound.offset)return;const t=this.isPlaying;this.stop(),this.sound.offset=e,t&&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&&(Et&&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&&ur.userInteractionRegistered){let t=this.gameObject.getComponent(zn)??this.context.mainCamera.getComponent(zn)??xc(zn,this.context,!1);!t&&this.context.mainCamera&&(t=this.context.mainCamera.addComponent(zn)),t!=null&&t.listener?(this.sound=new KC(t.listener),(e=this.gameObject)==null||e.add(this.sound)):Et&&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(){Et&&console.log("[AudioSource]",this),this.audioLoader=new jm,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),ur.userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():ur.registerWaitForAllowAudio(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.onNewClip(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(Og.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(Og.MuteChanged,this.onApplicationMuteChanged),this.pause()}applySpatialDistanceSettings(){const e=this.sound;if(!e)return;this._needUpdateSpatialDistanceSettings=!1;const t=W.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(Et&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+t),e.setRefDistance(t),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?Et&&!this.helper&&(this.helper=new tO(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(Et&&console.log(e),e.endsWith(".mp3")||e.endsWith(".wav")){if(this.audioLoader||(this.audioLoader=new jm),this.shouldPlay=!0,this._lastClipStartedLoading===e){Et&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=e,Et&&console.log("load audio",e);const t=await this.audioLoader.loadAsync(e).catch(console.error);if(this.destroyed)return;this._lastClipStartedLoading===e&&(this._lastClipStartedLoading=null),t&&this.createAudio(t)}else console.warn("Unsupported audio clip type",e);else this.shouldPlay=!0,this.createAudio()}play(e=void 0){var t,s,o;!e&&this.clip&&(e=this.clip),e!==void 0&&typeof e!="string"&&!(e instanceof MediaStream)&&(F()&&console.warn("Called play on AudioSource with unknown argument type:",e+`
940
940
  Using the assigned clip instead:`,this.clip),e=this.clip);let r=!this.sound||e&&e!==this.clip;if(typeof e=="string"&&!this.audioLoader&&(r=!0),(e instanceof MediaStream||typeof e=="string")&&(this.clip=e),r){this.shouldPlay=!0,this.onNewClip(e);return}if(this.shouldPlay=!0,this._hasEnded=!1,Et&&console.log("play",(t=this.sound)==null?void 0:t.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||(o=this.context.domElement.shadowRoot)==null||o.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,t;Et&&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()),(t=this._audioElement)==null||t.remove()}stop(){var e,t;Et&&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,Et&&console.log(this._lastContextTime),this.sound.stop()),(t=this._audioElement)==null||t.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,Et&&console.log("Audio clip ended",this.clip),this.dispatchEvent(new CustomEvent("ended",{detail:this})))}};Os([m(URL)],ss.prototype,"clip",2),Os([m()],ss.prototype,"playOnAwake",2),Os([m()],ss.prototype,"preload",2),Os([m()],ss.prototype,"playInBackground",2),Os([m()],ss.prototype,"loop",1),Os([m()],ss.prototype,"spatialBlend",1),Os([m()],ss.prototype,"minDistance",1),Os([m()],ss.prototype,"maxDistance",1),Os([m()],ss.prototype,"volume",1),Os([m()],ss.prototype,"pitch",1),Os([m()],ss.prototype,"rollOffMode",2);let ns=ss;const FT=C("debugavatar"),ju=class wn extends I{constructor(){super(...arguments),a(this,"connectionId"),a(this,"avatar")}static getAvatar(e){return e>=0&&e<wn.instances.length?wn.instances[e]:null}static onAvatarMarkerCreated(e){return wn._onNewAvatarMarkerAdded.push(e),e}static onAvatarMarkerDestroyed(e){return wn._onAvatarMarkerDestroyed.push(e),e}awake(){wn.instances.push(this),FT&&console.log(this);for(const e of wn._onNewAvatarMarkerAdded)e({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){wn.instances.splice(wn.instances.indexOf(this),1);for(const e of wn._onAvatarMarkerDestroyed)e({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}};a(ju,"instances",[]),a(ju,"_onNewAvatarMarkerAdded",[]),a(ju,"_onAvatarMarkerDestroyed",[]);let hi=ju;class Nn{static Add(e,t,s=null){if(t){for(const o of this.Pois)if(o.obj===t)return;this.Pois.push({obj:t,avatar:s}),this.LastChangeTime=e.time.time}}static Remove(e,t){var s;if(t){for(const o of this.Pois)if(o.obj===t){this.Pois.splice(this.Pois.indexOf(o),1),this.LastChangeTime=e?.time.time??((s=J.Current)==null?void 0:s.time.time);return}}}}a(Nn,"Pois",[]),a(Nn,"LastChangeTime",0);class UT{constructor(){a(this,"guid"),a(this,"position",new S)}}class Uc extends I{constructor(){super(...arguments),a(this,"target",null),a(this,"avatar",null),a(this,"_model",null),a(this,"_targetModel",new UT),a(this,"_currentTargetObject",null),a(this,"_lastUpdateTime",0),a(this,"_lookDuration",0),a(this,"_lastPoiChangedTime",0)}set controlledTarget(e){this.target=e;const t=R.get("MoveRandom");if(t&&this.target){const s=P.getComponent(this.target,t);s&&s.destroy()}}awake(){if(this.avatar=P.getComponentInParent(this.gameObject,hi),this.avatar){const e=P.getComponentInParent(this.gameObject,hi);this._model=new Ag(this.context.connection,this.guid),e!=null&&e.isLocalAvatar&&this._model.requestOwnership()}this.context.connection.beginListen("avatar-look-target-changed",e=>{var t;this.target&&e&&e.guid===((t=this.avatar)==null?void 0:t.guid)&&lt(this.target,e.position)})}update(){var e;if((!this.context.connection.isConnected||(e=this._model)!=null&&e.hasOwnership)&&(Nn.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=Nn.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){const t=ee(this._currentTargetObject);lt(this.target,t),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(t))}}selectTarget(){if(this.context.time.time-this._lastUpdateTime>this._lookDuration){this._lastUpdateTime=this.context.time.time,this._lookDuration=Math.random()*.5+.2;const e=Nn.Pois;if(e.length>0){const t=e[Math.floor(Math.random()*e.length)];if(t&&t.obj){if(t.avatar&&t.avatar===this.avatar)return;this._currentTargetObject=t.obj}}}}}function Rx(n){const e=n;return!!(e.parser&&e.parser.json)}var Du=(n=>(n[n.None=0]="None",n[n.DontExport=1]="DontExport",n))(Du||{});function Tx(n){return n&&n.isComponent}const zT=Symbol("object"),Hf=new Oi(()=>new S,20);class Ex{constructor(e,t,s,o,r,l){a(this,"_point"),a(this,"_normal"),a(this,"_tangentVelocity"),a(this,"distance"),a(this,"impulse"),a(this,"friction"),this._point=e,this.distance=t,this._normal=s,this.impulse=o,this.friction=r,this._tangentVelocity=l}get point(){return Hf.get().set(this._point.x,this._point.y,this._point.z)}get normal(){return Hf.get().set(this._normal.x,this._normal.y,this._normal.z)}get tangentVelocity(){return Hf.get().set(this._tangentVelocity.x,this._tangentVelocity.y,this._tangentVelocity.z)}}class Ax{constructor(e,t,s){a(this,"contacts"),a(this,"me"),a(this,"_collider"),a(this,"_gameObject"),this.me=e,this._collider=t,this._gameObject=t.gameObject,this.contacts=s}get collider(){return this._collider}get gameObject(){return this._gameObject}get rigidBody(){var e;return(e=this.collider)==null?void 0:e.attachedRigidbody}}class Ix{constructor(e,t){a(this,"object"),a(this,"collider"),this.object=e,this.collider=t}}const Ye=C("debugnetworkingstreams");var nn=(n=>(n.Connected="peer-user-connected",n.StreamReceived="receive-stream",n.StreamEnded="call-ended",n.Disconnected="peer-user-disconnected",n.UserJoined="user-joined",n))(nn||{});class Gf{constructor(e,t){a(this,"type","call-ended"),a(this,"userId"),a(this,"direction"),this.userId=e,this.direction=t}}class Lx{constructor(e,t,s){a(this,"type","receive-stream"),a(this,"userId"),a(this,"stream"),a(this,"target"),this.userId=e,this.stream=t,this.target=s}}class NT{constructor(e,t){a(this,"guid"),a(this,"peerId"),a(this,"dontSave",!0),this.guid=e.id,this.peerId=t}}var jx=(n=>(n.Incoming="incoming",n.Outgoing="outgoing",n))(jx||{});class WT extends Dm{constructor(e,t,s,o=null){super(),a(this,"peerId"),a(this,"userId"),a(this,"direction"),a(this,"call"),a(this,"_stream",null),a(this,"_isDisposed",!1),this.peerId=t.peer,this.userId=e,this.call=t,this.direction=s,this._stream=o,t.on("stream",r=>{if(Ye&&console.log("Receive stream",`
941
941
  Audio:`,r.getAudioTracks(),`
942
942
  Video:`,r.getVideoTracks()),this._stream=r,s==="incoming"){const l=new Lx(e,r,this);this.dispatchEvent(l)}}),t.on("close",()=>{this.dispatchEvent(new Gf(e,s))})}get stream(){return this._stream}close(){this._isDisposed||(this._isDisposed=!0,this.call.close(),on(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 Dx(n){return n=n.replace("a=fmtp:111 minptime=10;useinbandfec=1","a=fmtp:111 ptime=5;useinbandfec=1;stereo=1;maxplaybackrate=48000;maxaveragebitrat=128000;sprop-stereo=1"),n}const Bx=class nd extends Dm{constructor(e,t){super(),a(this,"updateCalls",()=>{var s;for(let o=this._incomingCalls.length-1;o>=0;o--){const r=this._incomingCalls[o];r.isClosed&&!r.isOpening&&this._incomingCalls.splice(o,1)}for(let o=this._outgoingCalls.length-1;o>=0;o--){const r=this._outgoingCalls[o];let l=!1;r.isClosed&&!r.isOpening&&((s=r.stream)!=null&&s.active?Ye&&console.warn("!!! Stream is still active, don't remove call",r.userId,"Your id: "+this.context.connection.connectionId):(Ye&&console.warn("!!! Remove closed call",r.userId),l=!0)),this.context.connection.userIsInRoom(r.userId)===!1&&(Ye&&console.warn("!!! User is not in room anymore, remove call",r.userId),l=!0),l&&(r.close(),this._outgoingCalls.splice(o,1))}}),a(this,"id"),a(this,"context"),a(this,"_incomingCalls",[]),a(this,"_outgoingCalls",[]),a(this,"_peer"),a(this,"_enabled",!1),a(this,"_enabledPeer",!1),a(this,"onConnectRoomFn",this.onConnectRoom.bind(this)),a(this,"onPeerConnect",s=>{if(Ye&&console.log("PEER opened as",s),s===null){console.error("Peer connection failed",s);return}this.context.connection.send("peer-user-connected",new NT(this,s))}),a(this,"onPeerClose",()=>{Ye&&console.log("PEER closed"),this.updateCalls()}),a(this,"onPeerDisconnected",()=>{Ye&&console.log("PEER disconnected"),this.updateCalls()}),a(this,"onPeerError",s=>{Ye&&console.error("PEER error",s)}),a(this,"onPeerReceivingCall",s=>{s.answer(void 0,{sdpTransform:o=>Dx(o)}),this.registerCall(s,"incoming",null)}),this.context=e,this.id=t,this.setupPeer(),navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia}static getOrCreate(e,t){if(nd.instances.has(t))return nd.instances.get(t);const s=new nd(e,t);return nd.instances.set(t,s),s}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,t){var s;if(!(t!=null&&t.id)){Ye?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 o={metadata:{userId:this.context.connection.connectionId,streamId:t.id},sdpTransform:l=>Dx(l)},r=(s=this._peer)==null?void 0:s.call(e,t,o);if(r){const l=this.registerCall(r,"outgoing",t);return Ye&&console.warn(`\u{1F4DE} CALL ${e}`,`
@@ -1385,7 +1385,7 @@ If you need multisampling consider changing 'auto' to a fixed value (e.g. 4).`))
1385
1385
  // be blended onto the scene.
1386
1386
  gl_FragColor = vec4(direct, max);
1387
1387
  return;
1388
- `)},e.userData.isLightBlendMaterial=!0}applyShadowMaterial(){if(this.targetMesh)if(this.targetMesh.material.type!=="ShadowMaterial"){const e=new kv;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 t=new Me;this.targetMesh.material=t,e=t}e.depthWrite=!0,e.stencilWrite=!0,e.colorWrite=!1,this.gameObject.renderOrder=-100}}applyMaterialOptions(e){e&&(e.depthWrite=!1,e.stencilWrite=!1)}}PS([m()],Rh.prototype,"mode"),PS([m(he)],Rh.prototype,"shadowColor");var SI=Object.defineProperty,Th=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&SI(e,t,o),o};const Gt=C("debugskybox");Ny("skybox-image"),Ny("environment-image");function OS(n,e,t,s,o){const r=new qp;r.allowDrop=!1,r.allowNetworking=!1,r.background=t,r.environment=s,P.addComponent(n.scene,r);const l=c=>{typeof c=="string"&&(Gt&&console.log(o,"CHANGED TO",c),r.setSkybox(c))};return pb(n.domElement,o,l),r.addEventListener("destroy",()=>{Gt&&console.log("Destroyed attribute remote skybox",o),mb(n.domElement,o,l)}),r.setSkybox(e)}const Gp=new Array;pe.registerCallback(me.ContextCreationStart,n=>{var e;const t=n.context,s=t.domElement.getAttribute("skybox-image")||t.domElement.getAttribute("background-image"),o=t.domElement.getAttribute("environment-image");if(s){Gt&&console.log("Creating remote skybox to load "+s),((e=t.mainCameraComponent)==null?void 0:e.clearFlags)!==Io.Skybox&&console.warn('"skybox-image"/"background-image" attribute has no effect: camera clearflags are not set to "Skybox"');const r=OS(t,s,!0,!1,"skybox-image");Gp.push(r)}if(o){Gt&&console.log("Creating remote environment to load "+o);const r=OS(t,o,!1,!0,"environment-image");Gp.push(r)}}),pe.registerCallback(me.ContextCreationStart,()=>Promise.all(Gp).finally(()=>{Gp.length=0}));function kS(){return globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES||(globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES=new Array),globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES}function MS(n){const e=kS().find(t=>t.src===n);return e?(Gt&&console.log("Skybox: Found previously loaded texture for "+n),e.texture):null}async function CI(n){const e=await n;qg(e,!0),Te(e)}function PI(n,e){const t=kS();for(;t.length>5;){const s=t.shift();s&&CI(s.texture)}e.then(s=>qg(s,!1)),t.push({src:n,texture:e})}const ha=class extends I{constructor(){super(...arguments),a(this,"url"),a(this,"allowDrop",!0),a(this,"background",!0),a(this,"environment",!0),a(this,"allowNetworking",!0),a(this,"_loader"),a(this,"_prevUrl"),a(this,"_prevLoadedEnvironment"),a(this,"_prevEnvironment",null),a(this,"_prevBackground",null),a(this,"validTextureTypes",[".ktx2",".hdr",".exr",".jpg",".jpeg",".png"]),a(this,"onDragOverEvent",n=>{if(this.allowDrop&&n.dataTransfer)for(const e of n.dataTransfer.types)(e==="text/uri-list"||e==="Files")&&n.preventDefault()}),a(this,"onDrop",n=>{var e,t,s,o;if(this.allowDrop&&n.dataTransfer){for(const r of n.dataTransfer.types)if(Gt&&console.log(r),r==="text/uri-list"){const l=n.dataTransfer.getData(r);Gt&&console.log(r,l);let c=(t=(e=new RegExp(/polyhaven.com\/asset_img\/.+?\/(?<name>.+)\.png/).exec(l))==null?void 0:e.groups)==null?void 0:t.name;if(c||(c=(o=(s=new RegExp(/polyhaven\.com\/a\/(?<name>.+)/).exec(l))==null?void 0:s.groups)==null?void 0:o.name),Gt&&console.log(c),c){const h="https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/"+c+"_1k.exr";console.log(`[Remote Skybox] Setting skybox from url: ${h}`),n.preventDefault(),this.setSkybox(h);break}else if(this.isValidTextureType(l)){console.log("[Remote Skybox] Setting skybox from url: "+l),n.preventDefault(),this.setSkybox(l);break}else{console.warn(`[RemoteSkybox] Unknown url ${l}. 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 h=new CustomEvent("dropped-unknown-url",{detail:{sender:this,event:n,url:l,apply:d=>{n.preventDefault(),this.setSkybox(d)}}});this.dispatchEvent(h)}}else if(r=="Files"){const l=n.dataTransfer.files.item(0);if(Gt&&console.log(r,l),!l)continue;if(!this.isValidTextureType(l.name)){console.warn(`[RemoteSkybox]: File "${l.name}" is not supported. Supported files are ${this.validTextureTypes.join(", ")}`);return}if(MS(l.name)===null){const c=new Blob([l]),h=URL.createObjectURL(c);n.preventDefault(),this.setSkybox(h,l.name)}else n.preventDefault(),this.setSkybox(l.name);break}}})}onEnable(){this.setSkybox(this.url),this.registerDropEvents()}onDisable(){var n;this.context.scene.environment===this._prevLoadedEnvironment&&(this.context.scene.environment=this._prevEnvironment,ci.backgroundShouldBeTransparent(this.context)||(this.context.scene.background=this._prevBackground),this._prevLoadedEnvironment=void 0),this.unregisterDropEvents(),(n=this.context.mainCameraComponent)==null||n.applyClearFlags()}urlChangedSyncField(){this.allowNetworking&&this.url&&(this.isRemoteTexture(this.url)?this.setSkybox(this.url):Gt&&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(n,e){var t;if(!this.activeAndEnabled||(n=OI(n,this.environment,this.background),!n))return!1;if(e??(e=n),this.isValidTextureType(e)||console.warn("Potentially invalid skybox url",e,"on",this.name),Gt&&console.log("Set remote skybox url: "+n),this._prevUrl===n&&this._prevLoadedEnvironment)return this.apply(),!0;(t=this._prevLoadedEnvironment)==null||t.dispose(),this._prevLoadedEnvironment=void 0,this._prevUrl=n;const s=await this.loadTexture(n,e);if(!s)return Gt&&console.warn("RemoteSkybox: Failed to load texture from url",n),!1;if(!this.enabled)return Gt&&console.warn("RemoteSkybox: Component is not enabled, aborting setSkybox"),!1;if(this._prevUrl!==n)return Gt&&console.warn("RemoteSkybox: URL changed while loading texture, aborting setSkybox"),!1;this.url=n;const o=n.lastIndexOf("/");return s.name=n.substring(o>=0?o+1:0),this._loader instanceof Sa&&(s.colorSpace=Mn),this._prevLoadedEnvironment=s,this.apply(),!0}async loadTexture(n,e){var t,s,o,r,l;if(!n)return Promise.resolve(null);e??(e=n);const c=MS(e);if(c){const g=await c;if(((s=(t=g.source)==null?void 0:t.data)==null?void 0:s.length)>0||(l=(r=(o=g.source)==null?void 0:o.data)==null?void 0:r.data)!=null&&l.length)return g}const h=e.endsWith(".exr"),d=e.endsWith(".hdr"),u=e.endsWith(".ktx2");if(h)this._loader instanceof Cd||(this._loader=new Cd);else if(d)this._loader instanceof Wm||(this._loader=new Wm);else if(u){if(!(this._loader instanceof hO)){const{ktx2Loader:g}=Nm(this.context.renderer);this._loader=g}}else this._loader instanceof Sa||(this._loader=new Sa);Gt&&console.log("Loading skybox: "+n);const p=this._loader.loadAsync(n);return PI(e,p),await p}apply(){var n;const e=this._prevLoadedEnvironment;e&&(e instanceof BP||e instanceof FP||(e.mapping=UP,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),Gt&&console.log("Set remote skybox",this.url,!ci.backgroundShouldBeTransparent(this.context)),this.environment&&(this.context.scene.environment=e),this.background&&!ci.backgroundShouldBeTransparent(this.context)&&(this.context.scene.background=e),((n=this.context.mainCameraComponent)==null?void 0:n.backgroundBlurriness)!==void 0&&(this.context.scene.backgroundBlurriness=this.context.mainCameraComponent.backgroundBlurriness))}isRemoteTexture(n){return n.startsWith("http://")||n.startsWith("https://")}isValidTextureType(n){for(const e of this.validTextureTypes)if(n.endsWith(e))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)}};Th([q0(ha.prototype.urlChangedSyncField),m(URL)],ha.prototype,"url"),Th([m()],ha.prototype,"allowDrop"),Th([m()],ha.prototype,"background"),Th([m()],ha.prototype,"environment"),Th([m()],ha.prototype,"allowNetworking");let qp=ha;function OI(n,e,t){const s=e&&!t;switch(n?.toLowerCase()){case"studio":return s?"https://cdn.needle.tools/static/skybox/modelviewer-Neutral-small.hdr":"https://cdn.needle.tools/static/skybox/modelviewer-Neutral.hdr";case"blurred-skybox":return s?"https://cdn.needle.tools/static/skybox/blurred-skybox-small.exr":"https://cdn.needle.tools/static/skybox/blurred-skybox.exr";case"quicklook-ar":return s?"https://cdn.needle.tools/static/skybox/QuickLook-ARMode-small.exr":"https://cdn.needle.tools/static/skybox/QuickLook-ARMode.exr";case"quicklook":return s?"https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode-small.exr":"https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode.exr"}return n===void 0?null:n}var kI=Object.defineProperty,Xp=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&kI(e,t,o),o},Qp;const Eh=(Qp=class extends I{constructor(){super(...arguments),a(this,"target",null),a(this,"followFactor",.1),a(this,"rotateFactor",.1),a(this,"positionAxes",Xa.All),a(this,"flipForward",!1),a(this,"_firstUpdate",!0)}onBeforeRender(){this.updateNow(!1)}updateNow(n){if(!(!this.target||this.target===this.gameObject)){if(this.followFactor>0){const e=ee(this.target),t=this._firstUpdate||n?1:W.clamp01(this.context.time.deltaTime*this.followFactor),s=this.worldPosition;this.positionAxes&Xa.X&&(s.x=W.lerp(s.x,e.x,t)),this.positionAxes&Xa.Y&&(s.y=W.lerp(s.y,e.y,t)),this.positionAxes&Xa.Z&&(s.z=W.lerp(s.z,e.z,t)),this.worldPosition=s}if(this.rotateFactor>0){const e=Se(this.target);this.flipForward&&e.premultiply(Qp._invertForward);const t=this._firstUpdate||n?1:W.clamp01(this.context.time.deltaTime*this.rotateFactor);this.worldQuaternion=this.worldQuaternion.slerp(e,t)}this._firstUpdate=!1}}},a(Qp,"_invertForward",new V().setFromAxisAngle(new S(0,1,0),Math.PI)),Qp);Xp([m(E)],Eh.prototype,"target"),Xp([m()],Eh.prototype,"followFactor"),Xp([m()],Eh.prototype,"rotateFactor"),Xp([m()],Eh.prototype,"positionAxes");let Yp=Eh;var MI=Object.defineProperty,Ah=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&MI(e,t,o),o};const Ih=C("debugspatialtrigger"),RS=new uo,TS=new uo;function RI(n,e){return RS.mask=n,TS.mask=e,RS.test(TS)}class vn extends I{constructor(){super(...arguments),a(this,"triggerMask",0),a(this,"onEnter"),a(this,"onStay"),a(this,"onExit"),a(this,"currentIntersected",[]),a(this,"lastIntersected",[])}start(){Ih&&console.log(this.name,this.triggerMask,this)}update(){this.currentIntersected.length=0;for(const e of Kp.triggers)RI(e.triggerMask,this.triggerMask)&&e.test(this.gameObject)&&this.currentIntersected.push(e);for(let e=this.lastIntersected.length-1;e>=0;e--){const t=this.lastIntersected[e];this.currentIntersected.indexOf(t)<0&&(this.onExitTrigger(t),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 t;Ih&&console.log("ENTER TRIGGER",this.name,e.name,this,e),e.raiseOnEnterEvent(this),(t=this.onEnter)==null||t.invoke()}onExitTrigger(e){var t;Ih&&console.log("EXIT TRIGGER",this.name,e.name),e.raiseOnExitEvent(this),(t=this.onExit)==null||t.invoke()}onStayTrigger(e){var t;e.raiseOnStayEvent(this),(t=this.onStay)==null||t.invoke()}}Ah([m()],vn.prototype,"triggerMask"),Ah([m(xe)],vn.prototype,"onEnter"),Ah([m(xe)],vn.prototype,"onStay"),Ah([m(xe)],vn.prototype,"onExit");var Rl;const ES=(Rl=class extends I{constructor(){super(...arguments),a(this,"triggerMask"),a(this,"boxHelper")}start(){Ih&&console.log(this.name,this.triggerMask,this)}onEnable(){var n;Rl.triggers.push(this),this.boxHelper||(this.boxHelper=P.addComponent(this.gameObject,Bo),(n=this.boxHelper)==null||n.showHelper(null,Ih))}onDisable(){Rl.triggers.splice(Rl.triggers.indexOf(this),1)}test(n){return this.boxHelper?this.boxHelper.isInBox(n)??!1:!1}raiseOnEnterEvent(n){P.foreachComponent(this.gameObject,e=>{e!==n&&e instanceof vn&&e.onEnterTrigger(this)},!1)}raiseOnStayEvent(n){P.foreachComponent(this.gameObject,e=>{e!==n&&e instanceof vn&&e.onStayTrigger(this)},!1)}raiseOnExitEvent(n){P.foreachComponent(this.gameObject,e=>{e!==n&&e instanceof vn&&e.onExitTrigger(this)},!1)}},a(Rl,"triggers",[]),Rl);Ah([m()],ES.prototype,"triggerMask");let Kp=ES;var TI=Object.defineProperty,EI=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&TI(e,t,o),o};const Hi=C("debugspectator");class Zp extends I{constructor(){super(...arguments),a(this,"cam",null),a(this,"useKeys",!0),a(this,"_mode",0),a(this,"orbit",null),a(this,"_handler"),a(this,"eventSub_WebXRRequestStartEvent",null),a(this,"eventSub_WebXRStartEvent",null),a(this,"eventSub_WebXREndEvent",null),a(this,"_debug"),a(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 t;return((t=this.target)==null?void 0:t.userId)===e}isFollowedBy(e){var t;return(t=this.followers)==null?void 0:t.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 t;if(this._handler){const s=(t=this._handler.currentTarget)==null?void 0:t.userId,o=this.context.players.getPlayerView(this.localId);e===void 0||this.context.isInXR===!1&&o?.currentObject===e.currentObject?this._handler.currentTarget!==void 0&&(this._handler.disable(),P.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),this._networking.onSpectatedObjectChanged(e,s)):this._handler.currentTarget!==e&&(this._handler.set(e),P.setActive(this.gameObject,!0),this.orbit&&(this.orbit.enabled=!1),this._networking.onSpectatedObjectChanged(e,s))}}get target(){var e;return(e=this._handler)==null?void 0:e.currentTarget}requestAllFollowMe(){this._networking.onRequestFollowMe()}get isSpectatingSelf(){var e,t;return this.isSpectating&&((e=this.target)==null?void 0:e.currentObject)===((t=this.context.players.getPlayerView(this.localId))==null?void 0:t.currentObject)}awake(){if(this._debug=new LI(this.context,this),this._networking=new BI(this.context,this),this._networking.awake(),P.setActive(this.gameObject,!1),this.cam=P.getComponent(this.gameObject,ci),!this.cam){console.warn("SpectatorCamera: Spectator camera needs camera component on the same object.",this);return}!this._handler&&this.cam&&(this._handler=new AI(this.context,this.cam,this)),this.orbit=P.getComponent(this.context.mainCamera,_e)}onDestroy(){var e,t;this.stopSpectating(),(e=this._handler)==null||e.destroy(),(t=this._networking)==null||t.destroy()}isSupportedPlatform(){const e=window.navigator.userAgent,t=/Windows|MacOS/.test(e),s=/Windows NT/.test(e)&&/Edg/.test(e)&&!/Win64/.test(e);return t&&!s}onBeforeXR(e){this.isSupportedPlatform()&&P.setActive(this.gameObject,!0)}onEnterXR(e){this.isSupportedPlatform()&&(Hi&&console.log(this.context.mainCamera),this.context.mainCamera&&this.followSelf())}onLeaveXR(e){var t,s;this.context.removeCamera(this.cam),P.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),(t=this._handler)==null||t.set(void 0),(s=this._handler)==null||s.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,Co.Headset),this.target=this.context.players.getPlayerView(this.localId)),Hi&&console.log("Follow self",this.target)}onAfterRender(){var e,t,s;if(!this.cam)return;const o=this.context.renderer,r=o.xr.enabled;if(!o.xr.isPresenting&&!((e=this._handler)!=null&&e.currentTarget))return;(t=this._handler)==null||t.update(this._mode);const l=o.getRenderTarget();let c=null;const h=o.state;if(!l){if(!o.state.bindFramebuffer||!h.bindXRFramebuffer)return;c=o._framebuffer,h.bindXRFramebuffer(null)}this.setAvatarFlagsBeforeRender();const d=this.context.mainCameraComponent;if(d){const g=d.backgroundColor;g&&o.setClearColor(g,g.alpha),this.cam.backgroundColor=g,this.cam.clearFlags=d.clearFlags,this.cam.nearClipPlane=d.nearClipPlane,this.cam.farClipPlane=d.farClipPlane}else o.setClearColor(new oe(1,1,1));o.setRenderTarget(null),o.xr.enabled=!1;const u=(s=this.cam)==null?void 0:s.threeCamera;this.context.updateAspect(u);const p=o.xr.isPresenting;o.xr.isPresenting=!1,o.setSize(this.context.domWidth,this.context.domHeight),o.render(this.context.scene,u),o.xr.isPresenting=p,o.xr.enabled=r,l?o.setRenderTarget(l):h.bindXRFramebuffer&&h.bindXRFramebuffer(c),this.resetAvatarFlags()}setAvatarFlagsBeforeRender(){const e=this._mode===0;for(const t of hi.instances)if(t.avatar&&"isLocalAvatar"in t.avatar&&"flags"in t.avatar){let s=rn.All;this.isSpectatingSelf&&(s=e&&t.avatar.isLocalAvatar?rn.FirstPerson:rn.ThirdPerson);const o=t.avatar.flags;if(!o)continue;for(const r of o)r.UpdateVisible(s)}}resetAvatarFlags(){var e;for(const t of hi.instances)if(t.avatar&&"flags"in t.avatar){const s=t.avatar.flags;if(!s)continue;for(const o of s)"isLocalAvatar"in t.avatar&&(e=t.avatar)!=null&&e.isLocalAvatar?o.UpdateVisible(rn.FirstPerson):o.UpdateVisible(rn.ThirdPerson)}}}EI([m()],Zp.prototype,"useKeys");class AI{constructor(e,t,s){a(this,"context"),a(this,"cam"),a(this,"spectator"),a(this,"follow"),a(this,"target"),a(this,"view"),a(this,"currentObject"),this.context=e,this.cam=t,this.spectator=s}get currentTarget(){return this.view}set(e){const t=e?.currentObject;if(!t){this.spectator.stopSpectating();return}t!==this.currentObject&&(this.currentObject=t,this.view=e,this.follow||(this.follow=P.addComponent(this.cam.gameObject,Yp)),this.target||(this.target=new E),t.add(this.target),this.follow.enabled=!0,this.follow.target=this.target,Hi&&console.log("FOLLOW",t),this.context.isInXR?this.context.removeCamera(this.cam):this.context.setCurrentCamera(this.cam))}disable(){Hi&&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 e;(e=this.target)==null||e.removeFromParent(),this.follow&&P.destroy(this.follow)}update(e){var t,s,o,r,l,c;if(((t=this.currentTarget)==null?void 0:t.isConnected)===!1||((s=this.currentTarget)==null?void 0:s.removed)===!0){Hi&&console.log("Target disconnected or timeout",this.currentTarget),this.spectator.stopSpectating();return}this.currentTarget&&((o=this.currentTarget)==null?void 0:o.currentObject)!==this.currentObject&&(Hi&&console.log("Target changed",this.currentObject,"to",this.currentTarget.currentObject),this.set(this.currentTarget));const h=this.context.mainCamera;if(h){const u=this.cam.threeCamera;(u.near!==h.near||u.far!==h.far)&&(u.near=h.near,u.far=h.far,u.updateProjectionMatrix())}const d=(r=this.follow)==null?void 0:r.target;if(!(!d||!this.follow)){switch(e){case 0:((l=this.view)==null?void 0:l.viewDevice)!==Co.Browser?(this.follow.followFactor=5,this.follow.rotateFactor=5):(this.follow.followFactor=50,this.follow.rotateFactor=50),d.position.set(0,0,0);break;case 1:this.follow.followFactor=3,this.follow.rotateFactor=2,d.position.set(0,.5,1.5);break}this.follow.flipForward=!1,((c=this.view)==null?void 0:c.viewDevice)!==Co.Browser?d.quaternion.copy(II):d.quaternion.identity()}}}const II=new V().setFromAxisAngle(new S(0,1,0),Math.PI);class LI{constructor(e,t){a(this,"context"),a(this,"spectator"),this.context=e,this.spectator=t,console.log("[Spectator Camera] Click other avatars or cameras to follow them. Press ESC to exit spectator mode."),this.context.domElement.addEventListener("keydown",o=>{!this.spectator.useKeys||o.key==="Escape"&&this.spectator.stopSpectating()});let s=0;this.context.input.addEventListener(Be.PointerDown,o=>{s=this.context.time.time}),this.context.input.addEventListener(Be.PointerUp,o=>{const r=this.context.time.time-s;r>1?this.spectator.stopSpectating():this.context.input.getPointerClicked(0)&&r<.3&&this.trySelectObject()})}trySelectObject(){const e=new Qs;e.setMask(16777215);const t=this.context.physics.raycast(e);if(Hi&&console.log(...t),t!=null&&t.length)for(const s of t){if(s.distance<.2)continue;const o=s.object,r=P.getComponentInParent(o,hi),l=r?.connectionId;if(l){const c=this.context.players.getPlayerView(l);this.spectator.target=c,Hi&&console.log("spectate",l,r);break}}}}class jI{constructor(e,t,s){a(this,"guid"),a(this,"dontSave",!0),a(this,"targetUserId"),a(this,"stoppedFollowing"),this.guid=e,this.targetUserId=t,this.stoppedFollowing=s}}class DI{constructor(e,t){a(this,"guid"),a(this,"userId"),this.guid=e.guid,this.userId=t}}class BI{constructor(e,t){a(this,"followers",[]),a(this,"context"),a(this,"spectator"),a(this,"_followerEventMethod"),a(this,"_requestFollowMethod"),a(this,"_joinedRoomMethod"),a(this,"_lastRequestFollowUser"),a(this,"_enforceFollowInterval"),this.context=e,this.spectator=t,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(ie.JoinedRoom,this._joinedRoomMethod),this.context.domElement.addEventListener("keydown",e=>{this.spectator.useKeys&&(e.key==="f"?this.onRequestFollowMe():e.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(ie.JoinedRoom,this._joinedRoomMethod)}onSpectatedObjectChanged(e,t){if(Hi&&console.log(this.context.connection.connectionId,"onSpectatedObjectChanged",e,t),this.context.connection.connectionId){const s=e?.userId===void 0,o=s?t:e?.userId,r=new jI(this.context.connection.connectionId,o,s);this.context.connection.send("spectator-follower-changed",r)}}onRequestFollowMe(e=!1){if(Hi&&console.log("Request follow",this.context.connection.connectionId),this.context.connection.connectionId){this.spectator.stopSpectating();const t=e?void 0:this.context.connection.connectionId,s=new DI(this.spectator,t);this.context.connection.send("spectator-request-follow",s)}}onUserJoinedRoom(){C("followme")&&this.onRequestFollowMe()}onFollowerEvent(e){const t=e.targetUserId,s=e.guid;if(Hi&&console.log(e),t===this.context.connection.connectionId)if(e.stoppedFollowing){const o=this.followers.indexOf(s);o!==-1&&(this.followers.splice(o,1),this.removeDisconnectedFollowers(),console.log(s,"unfollows you",this.followers.length))}else this.followers.includes(s)||(this.followers.push(s),this.removeDisconnectedFollowers(),console.log(s,"follows you",this.followers.length))}removeDisconnectedFollowers(){for(let e=this.followers.length-1;e>=0;e--){const t=this.followers[e];this.context.connection.userIsInRoom(t)===!1&&this.followers.splice(e,1)}}onRequestFollowEvent(e){if(this._lastRequestFollowUser=e,e.userId===this.context.connection.connectionId)this.spectator.stopSpectating();else if(e.userId===void 0)this.spectator.stopSpectating();else{const t=this.context.players.getPlayerView(e.userId);if(t)this.spectator.target=t;else return Hi&&console.warn("Could not find view",e.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):(Hi&&console.log("REQUEST FOLLOW AGAIN",this._lastRequestFollowUser.userId),this.onRequestFollowEvent(this._lastRequestFollowUser))},1e3))}}class Sn{constructor(){a(this,"bb",null),a(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedCameraModel(e,t){return(t||new Sn).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedCameraModel(e,t){return e.setPosition(e.position()+Kv),(t||new Sn).__init(e.readInt32(e.position())+e.position(),e)}userId(e){const t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}guid(e){const t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__string(this.bb_pos+t,e):null}dontSave(){const e=this.bb.__offset(this.bb_pos,8);return e?!!this.bb.readInt8(this.bb_pos+e):!1}pos(e){const t=this.bb.__offset(this.bb_pos,10);return t?(e||new Ur).__init(this.bb_pos+t,this.bb):null}rot(e){const t=this.bb.__offset(this.bb_pos,12);return t?(e||new Ur).__init(this.bb_pos+t,this.bb):null}static startSyncedCameraModel(e){e.startObject(5)}static addUserId(e,t){e.addFieldOffset(0,t,0)}static addGuid(e,t){e.addFieldOffset(1,t,0)}static addDontSave(e,t){e.addFieldInt8(2,+t,0)}static addPos(e,t){e.addFieldStruct(3,t,0)}static addRot(e,t){e.addFieldStruct(4,t,0)}static endSyncedCameraModel(e){return e.endObject()}static finishSyncedCameraModelBuffer(e,t){e.finish(t)}static finishSizePrefixedSyncedCameraModelBuffer(e,t){e.finish(t,void 0,!0)}}var FI=Object.defineProperty,UI=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&FI(e,t,o),o};const Jp="SCAM";Tg(Jp,Sn.getRootAsSyncedCameraModel);const Gi=new $m;class zI{constructor(e,t){a(this,"userId"),a(this,"guid"),this.guid=t,this.userId=e}send(e,t){if(e){Gi.clear();const s=Gi.createString(this.guid),o=Gi.createString(this.userId);Sn.startSyncedCameraModel(Gi),Sn.addGuid(Gi,s),Sn.addUserId(Gi,o);const r=ee(e),l=Ad(e);Sn.addPos(Gi,Ur.createVec3(Gi,r.x,r.y,r.z)),Sn.addRot(Gi,Ur.createVec3(Gi,l.x,l.y,l.z));const c=Sn.endSyncedCameraModel(Gi);Gi.finish(c,Jp),t.sendBinary(Gi.asUint8Array())}}}var Lh;const AS=(Lh=class extends I{constructor(){super(...arguments),a(this,"cameraPrefab",null),a(this,"_lastWorldPosition"),a(this,"_lastWorldQuaternion"),a(this,"_model",null),a(this,"_needsUpdate",!0),a(this,"_lastUpdateTime",0),a(this,"remoteCams",{}),a(this,"userToCamMap",{}),a(this,"_camTimeoutInSeconds",10),a(this,"_receiveCallback",null)}getCameraObject(n){const e=this.userToCamMap[n];return e?this.remoteCams[e].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(Jp,this.onReceivedRemoteCameraInfoBin.bind(this))}onDisable(){this.context.connection.stopListenBinary(Jp,this._receiveCallback)}update(){for(const s in this.remoteCams){const o=this.remoteCams[s],r=this.context.time.realtimeSinceStartup-o.lastUpdate;if(!o||r>this._camTimeoutInSeconds){F()&&console.log("Remote cam timeout",s),o!=null&&o.obj&&P.destroy(o.obj),delete this.remoteCams[s],o&&delete this.userToCamMap[o.userId],Lh.instances.push(o),this.context.players.removePlayerView(o.userId,Co.Browser);continue}}if(this.context.isInXR)return;const n=this.context.mainCamera;if(n===null){this.enabled=!1;return}if(!this.context.connection.isConnected||this.context.connection.connectionId===null)return;this._model===null&&(this._model=new zI(this.context.connection.connectionId,this.context.connection.connectionId+"_camera"));const e=ee(n),t=Se(n);(e.distanceTo(this._lastWorldPosition)>.001||t.angleTo(this._lastWorldQuaternion)>.01)&&(this._needsUpdate=!0),this._lastWorldPosition.copy(e),this._lastWorldQuaternion.copy(t),!((!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(n,this.context.connection),this.context.isInXR||this.context.players.setPlayerView(this.context.connection.connectionId,n,Co.Browser))}onReceivedRemoteCameraInfoBin(n){const e=n.guid();if(!e)return;const t=n.userId();if(!t||!this.context.connection.userIsInRoom(t)||!this.cameraPrefab)return;let s=this.remoteCams[e];if(!s)if("isObject3D"in this.cameraPrefab){const c=new Fs;c.context=this.context;const h=P.instantiate(this.cameraPrefab,c);s=this.remoteCams[e]={obj:h,lastUpdate:this.context.time.realtimeSinceStartup,userId:t},s.obj.visible=!0,this.gameObject.add(h),this.userToCamMap[t]=e,Lh.instances.push(s);const d=P.getOrAddComponent(h,hi);d.connectionId=t,d.avatar=h}else return;const o=s.obj;this.context.players.setPlayerView(t,o,Co.Browser),s.lastUpdate=this.context.time.realtimeSinceStartup,ms.markDirty(o);const r=n.pos();r&&br(o,r.x(),r.y(),r.z());const l=n.rot();l&&Zl(o,l.x(),l.y(),l.z())}},a(Lh,"instances",[]),Lh);UI([m([E,ce])],AS.prototype,"cameraPrefab");let Wy=AS;var NI=Object.defineProperty,WI=Object.getOwnPropertyDescriptor,lr=(n,e,t,s)=>{for(var o=s>1?void 0:s?WI(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&NI(e,t,o),o};const Vy="view",$y=C("debugsyncedroom");class Ls extends I{constructor(){super(...arguments),a(this,"roomName",""),a(this,"urlParameterName","room"),a(this,"joinRandomRoom"),a(this,"requireRoomParameter",!1),a(this,"autoRejoin",!0),a(this,"createJoinButton",!0),a(this,"createViewOnlyButton",!1),a(this,"_lastJoinedRoom"),a(this,"_roomPrefix",""),a(this,"_lastPingTime",0),a(this,"_lastRoomTime",-1),a(this,"_userWantsToBeInARoom",!1),a(this,"_roomButton"),a(this,"_roomButtonIconJoin"),a(this,"_roomButtonIconLeave"),a(this,"updateRoomButtonState",()=>{var e,t;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",(t=this._roomButtonIconLeave)==null||t.remove(),this._roomButton.prepend(this._roomButtonIconJoin)))}),a(this,"_viewOnlyButton"),a(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 t;const s=this.getViewOnlyUrl();s!=null&&s.length?navigator.canShare({url:s})?(t=navigator.share({url:s}))==null||t.catch(o=>{console.warn(o)}):(navigator.clipboard.writeText(s),De("View only URL copied to clipboard")):be("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(Mt("visibility"))}this.context.menu.appendChild(this._viewOnlyButton)})}get currentRoomName(){return C(Vy)||C(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),$y&&console.log(`SyncedRoom roomName:${this.roomName}, urlParamName:${this.urlParameterName}, joinRandomRoom:${this.joinRandomRoom}`)}onEnable(){const e=C(Vy);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 t=this.createRoomButton();this.context.menu.appendChild(t)}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 t;e===void 0&&(e=0);let s=!1;if(((t=this.urlParameterName)==null?void 0:t.length)>0){const o=C(this.urlParameterName);if(o&&(typeof o=="string"||typeof o=="number")){s=!0;const r=db(o.toString());this.roomName=r}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&&!s?(($y||F())&&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 kv;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 t=new Me;this.targetMesh.material=t,e=t}e.depthWrite=!0,e.stencilWrite=!0,e.colorWrite=!1,this.gameObject.renderOrder=-100}}applyMaterialOptions(e){e&&(e.depthWrite=!1,e.stencilWrite=!1)}}PS([m()],Rh.prototype,"mode"),PS([m(he)],Rh.prototype,"shadowColor");var SI=Object.defineProperty,Th=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&SI(e,t,o),o};const Gt=C("debugskybox");Ny("background-image"),Ny("environment-image");function OS(n,e,t,s,o){const r=new qp;r.allowDrop=!1,r.allowNetworking=!1,r.background=t,r.environment=s,P.addComponent(n.scene,r);const l=c=>{typeof c=="string"&&(Gt&&console.log(o,"CHANGED TO",c),r.setSkybox(c))};return pb(n.domElement,o,l),r.addEventListener("destroy",()=>{Gt&&console.log("Destroyed attribute remote skybox",o),mb(n.domElement,o,l)}),r.setSkybox(e)}const Gp=new Array;pe.registerCallback(me.ContextCreationStart,n=>{var e;const t=n.context,s=t.domElement.getAttribute("background-image"),o=t.domElement.getAttribute("environment-image");if(s){Gt&&console.log("Creating remote skybox to load "+s),((e=t.mainCameraComponent)==null?void 0:e.clearFlags)!==Io.Skybox&&console.warn('"background-image" attribute has no effect: camera clear flags are not set to "Skybox"');const r=OS(t,s,!0,!1,"background-image");Gp.push(r)}if(o){Gt&&console.log("Creating remote environment to load "+o);const r=OS(t,o,!1,!0,"environment-image");Gp.push(r)}}),pe.registerCallback(me.ContextCreationStart,()=>Promise.all(Gp).finally(()=>{Gp.length=0}));function kS(){return globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES||(globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES=new Array),globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES}function MS(n){const e=kS().find(t=>t.src===n);return e?(Gt&&console.log("Skybox: Found previously loaded texture for "+n),e.texture):null}async function CI(n){const e=await n;qg(e,!0),Te(e)}function PI(n,e){const t=kS();for(;t.length>5;){const s=t.shift();s&&CI(s.texture)}e.then(s=>qg(s,!1)),t.push({src:n,texture:e})}const ha=class extends I{constructor(){super(...arguments),a(this,"url"),a(this,"allowDrop",!0),a(this,"background",!0),a(this,"environment",!0),a(this,"allowNetworking",!0),a(this,"_loader"),a(this,"_prevUrl"),a(this,"_prevLoadedEnvironment"),a(this,"_prevEnvironment",null),a(this,"_prevBackground",null),a(this,"validTextureTypes",[".ktx2",".hdr",".exr",".jpg",".jpeg",".png"]),a(this,"onDragOverEvent",n=>{if(this.allowDrop&&n.dataTransfer)for(const e of n.dataTransfer.types)(e==="text/uri-list"||e==="Files")&&n.preventDefault()}),a(this,"onDrop",n=>{var e,t,s,o;if(this.allowDrop&&n.dataTransfer){for(const r of n.dataTransfer.types)if(Gt&&console.log(r),r==="text/uri-list"){const l=n.dataTransfer.getData(r);Gt&&console.log(r,l);let c=(t=(e=new RegExp(/polyhaven.com\/asset_img\/.+?\/(?<name>.+)\.png/).exec(l))==null?void 0:e.groups)==null?void 0:t.name;if(c||(c=(o=(s=new RegExp(/polyhaven\.com\/a\/(?<name>.+)/).exec(l))==null?void 0:s.groups)==null?void 0:o.name),Gt&&console.log(c),c){const h="https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/"+c+"_1k.exr";console.log(`[Remote Skybox] Setting skybox from url: ${h}`),n.preventDefault(),this.setSkybox(h);break}else if(this.isValidTextureType(l)){console.log("[Remote Skybox] Setting skybox from url: "+l),n.preventDefault(),this.setSkybox(l);break}else{console.warn(`[RemoteSkybox] Unknown url ${l}. 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 h=new CustomEvent("dropped-unknown-url",{detail:{sender:this,event:n,url:l,apply:d=>{n.preventDefault(),this.setSkybox(d)}}});this.dispatchEvent(h)}}else if(r=="Files"){const l=n.dataTransfer.files.item(0);if(Gt&&console.log(r,l),!l)continue;if(!this.isValidTextureType(l.name)){console.warn(`[RemoteSkybox]: File "${l.name}" is not supported. Supported files are ${this.validTextureTypes.join(", ")}`);return}if(MS(l.name)===null){const c=new Blob([l]),h=URL.createObjectURL(c);n.preventDefault(),this.setSkybox(h,l.name)}else n.preventDefault(),this.setSkybox(l.name);break}}})}onEnable(){this.setSkybox(this.url),this.registerDropEvents()}onDisable(){var n;this.context.scene.environment===this._prevLoadedEnvironment&&(this.context.scene.environment=this._prevEnvironment,ci.backgroundShouldBeTransparent(this.context)||(this.context.scene.background=this._prevBackground),this._prevLoadedEnvironment=void 0),this.unregisterDropEvents(),(n=this.context.mainCameraComponent)==null||n.applyClearFlags()}urlChangedSyncField(){this.allowNetworking&&this.url&&(this.isRemoteTexture(this.url)?this.setSkybox(this.url):Gt&&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(n,e){var t;if(!this.activeAndEnabled||(n=OI(n,this.environment,this.background),!n))return!1;if(e??(e=n),this.isValidTextureType(e)||console.warn("Potentially invalid skybox url",e,"on",this.name),Gt&&console.log("Set remote skybox url: "+n),this._prevUrl===n&&this._prevLoadedEnvironment)return this.apply(),!0;(t=this._prevLoadedEnvironment)==null||t.dispose(),this._prevLoadedEnvironment=void 0,this._prevUrl=n;const s=await this.loadTexture(n,e);if(!s)return Gt&&console.warn("RemoteSkybox: Failed to load texture from url",n),!1;if(!this.enabled)return Gt&&console.warn("RemoteSkybox: Component is not enabled, aborting setSkybox"),!1;if(this._prevUrl!==n)return Gt&&console.warn("RemoteSkybox: URL changed while loading texture, aborting setSkybox"),!1;this.url=n;const o=n.lastIndexOf("/");return s.name=n.substring(o>=0?o+1:0),this._loader instanceof Sa&&(s.colorSpace=Mn),this._prevLoadedEnvironment=s,this.apply(),!0}async loadTexture(n,e){var t,s,o,r,l;if(!n)return Promise.resolve(null);e??(e=n);const c=MS(e);if(c){const g=await c;if(((s=(t=g.source)==null?void 0:t.data)==null?void 0:s.length)>0||(l=(r=(o=g.source)==null?void 0:o.data)==null?void 0:r.data)!=null&&l.length)return g}const h=e.endsWith(".exr"),d=e.endsWith(".hdr"),u=e.endsWith(".ktx2");if(h)this._loader instanceof Cd||(this._loader=new Cd);else if(d)this._loader instanceof Wm||(this._loader=new Wm);else if(u){if(!(this._loader instanceof hO)){const{ktx2Loader:g}=Nm(this.context.renderer);this._loader=g}}else this._loader instanceof Sa||(this._loader=new Sa);Gt&&console.log("Loading skybox: "+n);const p=this._loader.loadAsync(n);return PI(e,p),await p}apply(){var n;const e=this._prevLoadedEnvironment;e&&(e instanceof BP||e instanceof FP||(e.mapping=UP,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),Gt&&console.log("Set remote skybox",this.url,!ci.backgroundShouldBeTransparent(this.context)),this.environment&&(this.context.scene.environment=e),this.background&&!ci.backgroundShouldBeTransparent(this.context)&&(this.context.scene.background=e),((n=this.context.mainCameraComponent)==null?void 0:n.backgroundBlurriness)!==void 0&&(this.context.scene.backgroundBlurriness=this.context.mainCameraComponent.backgroundBlurriness))}isRemoteTexture(n){return n.startsWith("http://")||n.startsWith("https://")}isValidTextureType(n){for(const e of this.validTextureTypes)if(n.endsWith(e))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)}};Th([q0(ha.prototype.urlChangedSyncField),m(URL)],ha.prototype,"url"),Th([m()],ha.prototype,"allowDrop"),Th([m()],ha.prototype,"background"),Th([m()],ha.prototype,"environment"),Th([m()],ha.prototype,"allowNetworking");let qp=ha;function OI(n,e,t){const s=e&&!t;switch(n?.toLowerCase()){case"studio":return s?"https://cdn.needle.tools/static/skybox/modelviewer-Neutral-small.hdr":"https://cdn.needle.tools/static/skybox/modelviewer-Neutral.hdr";case"blurred-skybox":return s?"https://cdn.needle.tools/static/skybox/blurred-skybox-small.exr":"https://cdn.needle.tools/static/skybox/blurred-skybox.exr";case"quicklook-ar":return s?"https://cdn.needle.tools/static/skybox/QuickLook-ARMode-small.exr":"https://cdn.needle.tools/static/skybox/QuickLook-ARMode.exr";case"quicklook":return s?"https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode-small.exr":"https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode.exr"}return n===void 0?null:n}var kI=Object.defineProperty,Xp=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&kI(e,t,o),o},Qp;const Eh=(Qp=class extends I{constructor(){super(...arguments),a(this,"target",null),a(this,"followFactor",.1),a(this,"rotateFactor",.1),a(this,"positionAxes",Xa.All),a(this,"flipForward",!1),a(this,"_firstUpdate",!0)}onBeforeRender(){this.updateNow(!1)}updateNow(n){if(!(!this.target||this.target===this.gameObject)){if(this.followFactor>0){const e=ee(this.target),t=this._firstUpdate||n?1:W.clamp01(this.context.time.deltaTime*this.followFactor),s=this.worldPosition;this.positionAxes&Xa.X&&(s.x=W.lerp(s.x,e.x,t)),this.positionAxes&Xa.Y&&(s.y=W.lerp(s.y,e.y,t)),this.positionAxes&Xa.Z&&(s.z=W.lerp(s.z,e.z,t)),this.worldPosition=s}if(this.rotateFactor>0){const e=Se(this.target);this.flipForward&&e.premultiply(Qp._invertForward);const t=this._firstUpdate||n?1:W.clamp01(this.context.time.deltaTime*this.rotateFactor);this.worldQuaternion=this.worldQuaternion.slerp(e,t)}this._firstUpdate=!1}}},a(Qp,"_invertForward",new V().setFromAxisAngle(new S(0,1,0),Math.PI)),Qp);Xp([m(E)],Eh.prototype,"target"),Xp([m()],Eh.prototype,"followFactor"),Xp([m()],Eh.prototype,"rotateFactor"),Xp([m()],Eh.prototype,"positionAxes");let Yp=Eh;var MI=Object.defineProperty,Ah=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&MI(e,t,o),o};const Ih=C("debugspatialtrigger"),RS=new uo,TS=new uo;function RI(n,e){return RS.mask=n,TS.mask=e,RS.test(TS)}class vn extends I{constructor(){super(...arguments),a(this,"triggerMask",0),a(this,"onEnter"),a(this,"onStay"),a(this,"onExit"),a(this,"currentIntersected",[]),a(this,"lastIntersected",[])}start(){Ih&&console.log(this.name,this.triggerMask,this)}update(){this.currentIntersected.length=0;for(const e of Kp.triggers)RI(e.triggerMask,this.triggerMask)&&e.test(this.gameObject)&&this.currentIntersected.push(e);for(let e=this.lastIntersected.length-1;e>=0;e--){const t=this.lastIntersected[e];this.currentIntersected.indexOf(t)<0&&(this.onExitTrigger(t),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 t;Ih&&console.log("ENTER TRIGGER",this.name,e.name,this,e),e.raiseOnEnterEvent(this),(t=this.onEnter)==null||t.invoke()}onExitTrigger(e){var t;Ih&&console.log("EXIT TRIGGER",this.name,e.name),e.raiseOnExitEvent(this),(t=this.onExit)==null||t.invoke()}onStayTrigger(e){var t;e.raiseOnStayEvent(this),(t=this.onStay)==null||t.invoke()}}Ah([m()],vn.prototype,"triggerMask"),Ah([m(xe)],vn.prototype,"onEnter"),Ah([m(xe)],vn.prototype,"onStay"),Ah([m(xe)],vn.prototype,"onExit");var Rl;const ES=(Rl=class extends I{constructor(){super(...arguments),a(this,"triggerMask"),a(this,"boxHelper")}start(){Ih&&console.log(this.name,this.triggerMask,this)}onEnable(){var n;Rl.triggers.push(this),this.boxHelper||(this.boxHelper=P.addComponent(this.gameObject,Bo),(n=this.boxHelper)==null||n.showHelper(null,Ih))}onDisable(){Rl.triggers.splice(Rl.triggers.indexOf(this),1)}test(n){return this.boxHelper?this.boxHelper.isInBox(n)??!1:!1}raiseOnEnterEvent(n){P.foreachComponent(this.gameObject,e=>{e!==n&&e instanceof vn&&e.onEnterTrigger(this)},!1)}raiseOnStayEvent(n){P.foreachComponent(this.gameObject,e=>{e!==n&&e instanceof vn&&e.onStayTrigger(this)},!1)}raiseOnExitEvent(n){P.foreachComponent(this.gameObject,e=>{e!==n&&e instanceof vn&&e.onExitTrigger(this)},!1)}},a(Rl,"triggers",[]),Rl);Ah([m()],ES.prototype,"triggerMask");let Kp=ES;var TI=Object.defineProperty,EI=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&TI(e,t,o),o};const Hi=C("debugspectator");class Zp extends I{constructor(){super(...arguments),a(this,"cam",null),a(this,"useKeys",!0),a(this,"_mode",0),a(this,"orbit",null),a(this,"_handler"),a(this,"eventSub_WebXRRequestStartEvent",null),a(this,"eventSub_WebXRStartEvent",null),a(this,"eventSub_WebXREndEvent",null),a(this,"_debug"),a(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 t;return((t=this.target)==null?void 0:t.userId)===e}isFollowedBy(e){var t;return(t=this.followers)==null?void 0:t.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 t;if(this._handler){const s=(t=this._handler.currentTarget)==null?void 0:t.userId,o=this.context.players.getPlayerView(this.localId);e===void 0||this.context.isInXR===!1&&o?.currentObject===e.currentObject?this._handler.currentTarget!==void 0&&(this._handler.disable(),P.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),this._networking.onSpectatedObjectChanged(e,s)):this._handler.currentTarget!==e&&(this._handler.set(e),P.setActive(this.gameObject,!0),this.orbit&&(this.orbit.enabled=!1),this._networking.onSpectatedObjectChanged(e,s))}}get target(){var e;return(e=this._handler)==null?void 0:e.currentTarget}requestAllFollowMe(){this._networking.onRequestFollowMe()}get isSpectatingSelf(){var e,t;return this.isSpectating&&((e=this.target)==null?void 0:e.currentObject)===((t=this.context.players.getPlayerView(this.localId))==null?void 0:t.currentObject)}awake(){if(this._debug=new LI(this.context,this),this._networking=new BI(this.context,this),this._networking.awake(),P.setActive(this.gameObject,!1),this.cam=P.getComponent(this.gameObject,ci),!this.cam){console.warn("SpectatorCamera: Spectator camera needs camera component on the same object.",this);return}!this._handler&&this.cam&&(this._handler=new AI(this.context,this.cam,this)),this.orbit=P.getComponent(this.context.mainCamera,_e)}onDestroy(){var e,t;this.stopSpectating(),(e=this._handler)==null||e.destroy(),(t=this._networking)==null||t.destroy()}isSupportedPlatform(){const e=window.navigator.userAgent,t=/Windows|MacOS/.test(e),s=/Windows NT/.test(e)&&/Edg/.test(e)&&!/Win64/.test(e);return t&&!s}onBeforeXR(e){this.isSupportedPlatform()&&P.setActive(this.gameObject,!0)}onEnterXR(e){this.isSupportedPlatform()&&(Hi&&console.log(this.context.mainCamera),this.context.mainCamera&&this.followSelf())}onLeaveXR(e){var t,s;this.context.removeCamera(this.cam),P.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),(t=this._handler)==null||t.set(void 0),(s=this._handler)==null||s.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,Co.Headset),this.target=this.context.players.getPlayerView(this.localId)),Hi&&console.log("Follow self",this.target)}onAfterRender(){var e,t,s;if(!this.cam)return;const o=this.context.renderer,r=o.xr.enabled;if(!o.xr.isPresenting&&!((e=this._handler)!=null&&e.currentTarget))return;(t=this._handler)==null||t.update(this._mode);const l=o.getRenderTarget();let c=null;const h=o.state;if(!l){if(!o.state.bindFramebuffer||!h.bindXRFramebuffer)return;c=o._framebuffer,h.bindXRFramebuffer(null)}this.setAvatarFlagsBeforeRender();const d=this.context.mainCameraComponent;if(d){const g=d.backgroundColor;g&&o.setClearColor(g,g.alpha),this.cam.backgroundColor=g,this.cam.clearFlags=d.clearFlags,this.cam.nearClipPlane=d.nearClipPlane,this.cam.farClipPlane=d.farClipPlane}else o.setClearColor(new oe(1,1,1));o.setRenderTarget(null),o.xr.enabled=!1;const u=(s=this.cam)==null?void 0:s.threeCamera;this.context.updateAspect(u);const p=o.xr.isPresenting;o.xr.isPresenting=!1,o.setSize(this.context.domWidth,this.context.domHeight),o.render(this.context.scene,u),o.xr.isPresenting=p,o.xr.enabled=r,l?o.setRenderTarget(l):h.bindXRFramebuffer&&h.bindXRFramebuffer(c),this.resetAvatarFlags()}setAvatarFlagsBeforeRender(){const e=this._mode===0;for(const t of hi.instances)if(t.avatar&&"isLocalAvatar"in t.avatar&&"flags"in t.avatar){let s=rn.All;this.isSpectatingSelf&&(s=e&&t.avatar.isLocalAvatar?rn.FirstPerson:rn.ThirdPerson);const o=t.avatar.flags;if(!o)continue;for(const r of o)r.UpdateVisible(s)}}resetAvatarFlags(){var e;for(const t of hi.instances)if(t.avatar&&"flags"in t.avatar){const s=t.avatar.flags;if(!s)continue;for(const o of s)"isLocalAvatar"in t.avatar&&(e=t.avatar)!=null&&e.isLocalAvatar?o.UpdateVisible(rn.FirstPerson):o.UpdateVisible(rn.ThirdPerson)}}}EI([m()],Zp.prototype,"useKeys");class AI{constructor(e,t,s){a(this,"context"),a(this,"cam"),a(this,"spectator"),a(this,"follow"),a(this,"target"),a(this,"view"),a(this,"currentObject"),this.context=e,this.cam=t,this.spectator=s}get currentTarget(){return this.view}set(e){const t=e?.currentObject;if(!t){this.spectator.stopSpectating();return}t!==this.currentObject&&(this.currentObject=t,this.view=e,this.follow||(this.follow=P.addComponent(this.cam.gameObject,Yp)),this.target||(this.target=new E),t.add(this.target),this.follow.enabled=!0,this.follow.target=this.target,Hi&&console.log("FOLLOW",t),this.context.isInXR?this.context.removeCamera(this.cam):this.context.setCurrentCamera(this.cam))}disable(){Hi&&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 e;(e=this.target)==null||e.removeFromParent(),this.follow&&P.destroy(this.follow)}update(e){var t,s,o,r,l,c;if(((t=this.currentTarget)==null?void 0:t.isConnected)===!1||((s=this.currentTarget)==null?void 0:s.removed)===!0){Hi&&console.log("Target disconnected or timeout",this.currentTarget),this.spectator.stopSpectating();return}this.currentTarget&&((o=this.currentTarget)==null?void 0:o.currentObject)!==this.currentObject&&(Hi&&console.log("Target changed",this.currentObject,"to",this.currentTarget.currentObject),this.set(this.currentTarget));const h=this.context.mainCamera;if(h){const u=this.cam.threeCamera;(u.near!==h.near||u.far!==h.far)&&(u.near=h.near,u.far=h.far,u.updateProjectionMatrix())}const d=(r=this.follow)==null?void 0:r.target;if(!(!d||!this.follow)){switch(e){case 0:((l=this.view)==null?void 0:l.viewDevice)!==Co.Browser?(this.follow.followFactor=5,this.follow.rotateFactor=5):(this.follow.followFactor=50,this.follow.rotateFactor=50),d.position.set(0,0,0);break;case 1:this.follow.followFactor=3,this.follow.rotateFactor=2,d.position.set(0,.5,1.5);break}this.follow.flipForward=!1,((c=this.view)==null?void 0:c.viewDevice)!==Co.Browser?d.quaternion.copy(II):d.quaternion.identity()}}}const II=new V().setFromAxisAngle(new S(0,1,0),Math.PI);class LI{constructor(e,t){a(this,"context"),a(this,"spectator"),this.context=e,this.spectator=t,console.log("[Spectator Camera] Click other avatars or cameras to follow them. Press ESC to exit spectator mode."),this.context.domElement.addEventListener("keydown",o=>{!this.spectator.useKeys||o.key==="Escape"&&this.spectator.stopSpectating()});let s=0;this.context.input.addEventListener(Be.PointerDown,o=>{s=this.context.time.time}),this.context.input.addEventListener(Be.PointerUp,o=>{const r=this.context.time.time-s;r>1?this.spectator.stopSpectating():this.context.input.getPointerClicked(0)&&r<.3&&this.trySelectObject()})}trySelectObject(){const e=new Qs;e.setMask(16777215);const t=this.context.physics.raycast(e);if(Hi&&console.log(...t),t!=null&&t.length)for(const s of t){if(s.distance<.2)continue;const o=s.object,r=P.getComponentInParent(o,hi),l=r?.connectionId;if(l){const c=this.context.players.getPlayerView(l);this.spectator.target=c,Hi&&console.log("spectate",l,r);break}}}}class jI{constructor(e,t,s){a(this,"guid"),a(this,"dontSave",!0),a(this,"targetUserId"),a(this,"stoppedFollowing"),this.guid=e,this.targetUserId=t,this.stoppedFollowing=s}}class DI{constructor(e,t){a(this,"guid"),a(this,"userId"),this.guid=e.guid,this.userId=t}}class BI{constructor(e,t){a(this,"followers",[]),a(this,"context"),a(this,"spectator"),a(this,"_followerEventMethod"),a(this,"_requestFollowMethod"),a(this,"_joinedRoomMethod"),a(this,"_lastRequestFollowUser"),a(this,"_enforceFollowInterval"),this.context=e,this.spectator=t,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(ie.JoinedRoom,this._joinedRoomMethod),this.context.domElement.addEventListener("keydown",e=>{this.spectator.useKeys&&(e.key==="f"?this.onRequestFollowMe():e.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(ie.JoinedRoom,this._joinedRoomMethod)}onSpectatedObjectChanged(e,t){if(Hi&&console.log(this.context.connection.connectionId,"onSpectatedObjectChanged",e,t),this.context.connection.connectionId){const s=e?.userId===void 0,o=s?t:e?.userId,r=new jI(this.context.connection.connectionId,o,s);this.context.connection.send("spectator-follower-changed",r)}}onRequestFollowMe(e=!1){if(Hi&&console.log("Request follow",this.context.connection.connectionId),this.context.connection.connectionId){this.spectator.stopSpectating();const t=e?void 0:this.context.connection.connectionId,s=new DI(this.spectator,t);this.context.connection.send("spectator-request-follow",s)}}onUserJoinedRoom(){C("followme")&&this.onRequestFollowMe()}onFollowerEvent(e){const t=e.targetUserId,s=e.guid;if(Hi&&console.log(e),t===this.context.connection.connectionId)if(e.stoppedFollowing){const o=this.followers.indexOf(s);o!==-1&&(this.followers.splice(o,1),this.removeDisconnectedFollowers(),console.log(s,"unfollows you",this.followers.length))}else this.followers.includes(s)||(this.followers.push(s),this.removeDisconnectedFollowers(),console.log(s,"follows you",this.followers.length))}removeDisconnectedFollowers(){for(let e=this.followers.length-1;e>=0;e--){const t=this.followers[e];this.context.connection.userIsInRoom(t)===!1&&this.followers.splice(e,1)}}onRequestFollowEvent(e){if(this._lastRequestFollowUser=e,e.userId===this.context.connection.connectionId)this.spectator.stopSpectating();else if(e.userId===void 0)this.spectator.stopSpectating();else{const t=this.context.players.getPlayerView(e.userId);if(t)this.spectator.target=t;else return Hi&&console.warn("Could not find view",e.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):(Hi&&console.log("REQUEST FOLLOW AGAIN",this._lastRequestFollowUser.userId),this.onRequestFollowEvent(this._lastRequestFollowUser))},1e3))}}class Sn{constructor(){a(this,"bb",null),a(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedCameraModel(e,t){return(t||new Sn).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedCameraModel(e,t){return e.setPosition(e.position()+Kv),(t||new Sn).__init(e.readInt32(e.position())+e.position(),e)}userId(e){const t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}guid(e){const t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__string(this.bb_pos+t,e):null}dontSave(){const e=this.bb.__offset(this.bb_pos,8);return e?!!this.bb.readInt8(this.bb_pos+e):!1}pos(e){const t=this.bb.__offset(this.bb_pos,10);return t?(e||new Ur).__init(this.bb_pos+t,this.bb):null}rot(e){const t=this.bb.__offset(this.bb_pos,12);return t?(e||new Ur).__init(this.bb_pos+t,this.bb):null}static startSyncedCameraModel(e){e.startObject(5)}static addUserId(e,t){e.addFieldOffset(0,t,0)}static addGuid(e,t){e.addFieldOffset(1,t,0)}static addDontSave(e,t){e.addFieldInt8(2,+t,0)}static addPos(e,t){e.addFieldStruct(3,t,0)}static addRot(e,t){e.addFieldStruct(4,t,0)}static endSyncedCameraModel(e){return e.endObject()}static finishSyncedCameraModelBuffer(e,t){e.finish(t)}static finishSizePrefixedSyncedCameraModelBuffer(e,t){e.finish(t,void 0,!0)}}var FI=Object.defineProperty,UI=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&FI(e,t,o),o};const Jp="SCAM";Tg(Jp,Sn.getRootAsSyncedCameraModel);const Gi=new $m;class zI{constructor(e,t){a(this,"userId"),a(this,"guid"),this.guid=t,this.userId=e}send(e,t){if(e){Gi.clear();const s=Gi.createString(this.guid),o=Gi.createString(this.userId);Sn.startSyncedCameraModel(Gi),Sn.addGuid(Gi,s),Sn.addUserId(Gi,o);const r=ee(e),l=Ad(e);Sn.addPos(Gi,Ur.createVec3(Gi,r.x,r.y,r.z)),Sn.addRot(Gi,Ur.createVec3(Gi,l.x,l.y,l.z));const c=Sn.endSyncedCameraModel(Gi);Gi.finish(c,Jp),t.sendBinary(Gi.asUint8Array())}}}var Lh;const AS=(Lh=class extends I{constructor(){super(...arguments),a(this,"cameraPrefab",null),a(this,"_lastWorldPosition"),a(this,"_lastWorldQuaternion"),a(this,"_model",null),a(this,"_needsUpdate",!0),a(this,"_lastUpdateTime",0),a(this,"remoteCams",{}),a(this,"userToCamMap",{}),a(this,"_camTimeoutInSeconds",10),a(this,"_receiveCallback",null)}getCameraObject(n){const e=this.userToCamMap[n];return e?this.remoteCams[e].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(Jp,this.onReceivedRemoteCameraInfoBin.bind(this))}onDisable(){this.context.connection.stopListenBinary(Jp,this._receiveCallback)}update(){for(const s in this.remoteCams){const o=this.remoteCams[s],r=this.context.time.realtimeSinceStartup-o.lastUpdate;if(!o||r>this._camTimeoutInSeconds){F()&&console.log("Remote cam timeout",s),o!=null&&o.obj&&P.destroy(o.obj),delete this.remoteCams[s],o&&delete this.userToCamMap[o.userId],Lh.instances.push(o),this.context.players.removePlayerView(o.userId,Co.Browser);continue}}if(this.context.isInXR)return;const n=this.context.mainCamera;if(n===null){this.enabled=!1;return}if(!this.context.connection.isConnected||this.context.connection.connectionId===null)return;this._model===null&&(this._model=new zI(this.context.connection.connectionId,this.context.connection.connectionId+"_camera"));const e=ee(n),t=Se(n);(e.distanceTo(this._lastWorldPosition)>.001||t.angleTo(this._lastWorldQuaternion)>.01)&&(this._needsUpdate=!0),this._lastWorldPosition.copy(e),this._lastWorldQuaternion.copy(t),!((!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(n,this.context.connection),this.context.isInXR||this.context.players.setPlayerView(this.context.connection.connectionId,n,Co.Browser))}onReceivedRemoteCameraInfoBin(n){const e=n.guid();if(!e)return;const t=n.userId();if(!t||!this.context.connection.userIsInRoom(t)||!this.cameraPrefab)return;let s=this.remoteCams[e];if(!s)if("isObject3D"in this.cameraPrefab){const c=new Fs;c.context=this.context;const h=P.instantiate(this.cameraPrefab,c);s=this.remoteCams[e]={obj:h,lastUpdate:this.context.time.realtimeSinceStartup,userId:t},s.obj.visible=!0,this.gameObject.add(h),this.userToCamMap[t]=e,Lh.instances.push(s);const d=P.getOrAddComponent(h,hi);d.connectionId=t,d.avatar=h}else return;const o=s.obj;this.context.players.setPlayerView(t,o,Co.Browser),s.lastUpdate=this.context.time.realtimeSinceStartup,ms.markDirty(o);const r=n.pos();r&&br(o,r.x(),r.y(),r.z());const l=n.rot();l&&Zl(o,l.x(),l.y(),l.z())}},a(Lh,"instances",[]),Lh);UI([m([E,ce])],AS.prototype,"cameraPrefab");let Wy=AS;var NI=Object.defineProperty,WI=Object.getOwnPropertyDescriptor,lr=(n,e,t,s)=>{for(var o=s>1?void 0:s?WI(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&NI(e,t,o),o};const Vy="view",$y=C("debugsyncedroom");class Ls extends I{constructor(){super(...arguments),a(this,"roomName",""),a(this,"urlParameterName","room"),a(this,"joinRandomRoom"),a(this,"requireRoomParameter",!1),a(this,"autoRejoin",!0),a(this,"createJoinButton",!0),a(this,"createViewOnlyButton",!1),a(this,"_lastJoinedRoom"),a(this,"_roomPrefix",""),a(this,"_lastPingTime",0),a(this,"_lastRoomTime",-1),a(this,"_userWantsToBeInARoom",!1),a(this,"_roomButton"),a(this,"_roomButtonIconJoin"),a(this,"_roomButtonIconLeave"),a(this,"updateRoomButtonState",()=>{var e,t;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",(t=this._roomButtonIconLeave)==null||t.remove(),this._roomButton.prepend(this._roomButtonIconJoin)))}),a(this,"_viewOnlyButton"),a(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 t;const s=this.getViewOnlyUrl();s!=null&&s.length?navigator.canShare({url:s})?(t=navigator.share({url:s}))==null||t.catch(o=>{console.warn(o)}):(navigator.clipboard.writeText(s),De("View only URL copied to clipboard")):be("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(Mt("visibility"))}this.context.menu.appendChild(this._viewOnlyButton)})}get currentRoomName(){return C(Vy)||C(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),$y&&console.log(`SyncedRoom roomName:${this.roomName}, urlParamName:${this.urlParameterName}, joinRandomRoom:${this.joinRandomRoom}`)}onEnable(){const e=C(Vy);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 t=this.createRoomButton();this.context.menu.appendChild(t)}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 t;e===void 0&&(e=0);let s=!1;if(((t=this.urlParameterName)==null?void 0:t.length)>0){const o=C(this.urlParameterName);if(o&&(typeof o=="string"||typeof o=="number")){s=!0;const r=db(o.toString());this.roomName=r}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&&!s?(($y||F())&&console.warn('[SyncedRoom] Missing required room parameter "'+this.urlParameterName+`" in url - will not connect.
1389
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.
1390
1390
  Please choose one of the following options to fix this:
1391
1391
  A) Set a room name in the SyncedRoom component
@@ -1603,4 +1603,4 @@ Error:`,c),null}}updateColliderCollisionGroups(e){const t=e[ti],s=e.membership;l
1603
1603
  justify-content: center;
1604
1604
  gap: .5rem;
1605
1605
  }
1606
- `),ge(this,ya).innerHTML=ge(this,wi).innerHTML,ge(this,ya).style.cssText="display: flex; align-items: center; justify-content: center;",ge(this,wi).innerHTML=ge(this,ya).outerHTML,ge(this,fa).innerHTML=ge(this,wi).outerHTML,ge(this,fa).prepend(ge(this,va)),fu(kf,{element:ge(this,fa)}),(e=ge(this,Dl))==null||e.disconnect(),ge(this,Dl)??zs(this,Dl,new MutationObserver(()=>dd(this,pm,cC).call(this))),ge(this,Dl).observe(ge(this,wi),{attributes:!0}),mv&&console.log("Needle Button updated")},cC=function(){ge(this,wi)&&(ge(this,wi).style.display==="none"?this.style.display="none":this.style.display==="none"&&(this.style.display=""))},mm=new WeakMap,a(gv,"observedAttributes",["ar","vr","quicklook"]),typeof window<"u"&&!window.customElements.get(aC)&&window.customElements.define(aC,gv);const id=C("debugavatar");class fv{constructor(e,t,s,o){a(this,"root"),a(this,"head"),a(this,"leftHand"),a(this,"rigthHand");var r;this.root=e,this.head=t,this.leftHand=s,this.rigthHand=o,(r=this.root)==null||r.traverse(l=>l.layers.set(2))}get isValid(){return this.head!==null&&this.head!==void 0}}class hC{constructor(){a(this,"avatarRegistryUrl",null)}async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let s=null;if(typeof t=="string"){if(s=await this.loadAvatar(e,t),!s){const r=new Fs;s=P.instantiate(Ma(t,e.scene),r)}}else s=t;if(!s)return null;const o=this.findAvatar(s);return o.isValid?(id&&console.log("[Custom Avatar] valid config",t,id?o:""),o):(console.warn("[Custom Avatar] config isn't valid",t,id?o:""),null)}async loadAvatar(e,t){if(console.assert(t!=null&&typeof t=="string","Avatar id must not be null"),t.length<=0||!t)return null;if(id&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){const o=await fetch("./"+t);let r=null;if(o.ok){const c=await o.blob();c&&(r=await c.arrayBuffer())}if(!r)return null;const l=await xs().parseSync(e,r,null,0);return l?.scene??null}const s=new Rn;return jf(s,e),new Promise((o,r)=>{const l=this.avatarRegistryUrl+"/"+t;s.load(l,async c=>{await xs().createBuiltinComponents(e,l,c,null,void 0),o(c.scene)},c=>{id&&console.log("[Custom Avatar] "+c.loaded/c.total*100+"% loaded of "+c.total/1024+"kB")},c=>{console.error("[Custom Avatar] Error when loading: "+c),o(null)})})}cacheModel(e,t){}findAvatar(e){const t=e;let s=t;s.children.length==1&&(s=e.children[0]);let o=this.findAvatarPart(s,["head"]);const r=this.findAvatarPart(s,["left","hand"]),l=this.findAvatarPart(s,["right","hand"]);if(!o){o=t;const c=new S;new Si().setFromObject(o).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&&o.scale.multiplyScalar(1/h*.3)}return new fv(t,o,r,l)}findAvatarPart(e,t){const s=e.name.toLowerCase();let o=!0;for(const r of t){if(!o)break;s.indexOf(r)===-1&&(o=!1)}if(o)return e;if(e.children)for(const r of e.children){const l=this.findAvatarPart(r,t);if(l)return l}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}}class dC{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(e){}}class uC{}const qL=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:ve,ActionCollection:V1,ActionModel:ks,AlignmentConstraint:Tc,Animation:Ft,AnimationCurve:mh,AnimationExtension:dp,AnimationTrackHandler:im,Animator:Rt,AnimatorController:gs,Antialiasing:bh,AudioExtension:_a,AudioListener:zn,AudioSource:ns,AudioTrackHandler:sm,Avatar:Go,AvatarBlink_Simple:zr,AvatarEyeLook_Rotation:Kf,AvatarLoader:hC,AvatarMarker:hi,AvatarModel:fv,Avatar_Brain_LookAt:Uc,Avatar_MouthShapes:zc,Avatar_MustacheShake:Xf,Avatar_POI:Nn,AxesHelper:Ja,BaseUIComponent:ps,BasicIKConstraint:Jf,BehaviorExtension:Z0,BehaviorModel:Jt,BloomEffect:Np,BoxCollider:Nu,BoxGizmo:ea,BoxHelperComponent:Bo,Button:no,CallInfo:Un,Camera:ci,CameraTargetReachedEvent:Fc,Canvas:_l,CanvasGroup:Ko,CapsuleCollider:Wn,ChangeMaterialOnClick:B0,ChangeTransformOnClick:Xr,CharacterController:Nr,CharacterControllerInput:$n,ChromaticAberration:_h,Collider:ui,ColorAdjustments:or,ColorBySpeedModule:Pl,ColorOverLifetimeModule:Ip,ContactShadows:Vc,ControlTrackHandler:nm,CustomBranding:Jr,Deletable:n0,DeleteBox:Wu,DepthOfField:As,DeviceFlag:Vu,DocumentExtension:dC,DragControls:Hr,DropListener:Hn,Duplicatable:h0,EffectWrapper:xh,EmissionModule:eo,EmphasizeOnClick:ul,EnvironmentScene:cm,EventList:xe,EventListEvent:Ru,EventSystem:ii,EventTrigger:qu,FieldWithDefault:y1,FixedJoint:fy,Fog:xl,GltfExport:P0,GltfExportBox:S0,Gradient:ia,Graphic:lh,GraphicRaycaster:Au,GridHelper:Sl,GridLayoutGroup:ay,GroundProjectedEnv:en,GroupActionModel:Wo,HideOnStart:pp,HingeJoint:dh,HorizontalLayoutGroup:ry,Image:El,InheritVelocityModule:Sy,InputField:Yy,InstanceHandle:w0,InstancingHandler:Ju,Interactable:s0,Keyframe:vi,LODGroup:ph,LODModel:Cl,Light:yi,LimitVelocityOverLifetimeModule:gt,LogStats:i0,LookAt:Ky,LookAtConstraint:Fr,MainModule:Wt,MaskableGraphic:ch,MeshCollider:Fo,MeshRenderer:Qc,MinMaxCurve:Z,MinMaxGradient:sa,NeedleMenu:un,NestedGltf:kp,Networking:_y,NoiseModule:Ce,ObjectRaycaster:ji,OffsetConstraint:ta,OpenURL:Al,OrbitControls:_e,Outline:bl,Padding:Zr,ParticleBurst:Ap,ParticleSubEmitter:Cy,ParticleSystem:yh,ParticleSystemRenderer:ds,PhysicsExtension:J0,PixelationEffect:Sh,PlayAnimationOnClick:Jc,PlayAudioOnClick:Vo,PlayableDirector:Tl,PlayerColor:Nl,PointerEventData:cd,PostProcessingHandler:zy,PreliminaryAction:pl,PreliminaryTrigger:eh,RawImage:am,Rect:Z1,RectTransform:Ts,ReflectionProbe:qc,RegisteredAnimationInfo:mr,RemoteSkybox:qp,Renderer:Ui,RendererLightmap:ep,Rigidbody:dt,RotationBySpeedModule:hs,RotationOverLifetimeModule:Es,SceneSwitcher:Ze,ScreenCapture:ar,ScreenSpaceAmbientOcclusion:to,ScreenSpaceAmbientOcclusionN8:Is,SetActiveOnClick:F0,ShadowCatcher:Rh,ShapeModule:xy,SharpeningEffect:Ph,SignalAsset:tm,SignalReceiver:Dh,SignalReceiverEvent:jh,SignalTrackHandler:Fh,Size:K1,SizeBySpeedModule:bi,SizeOverLifetimeModule:na,SkinnedMeshRenderer:x0,SmoothFollow:Yp,SpatialGrabRaycaster:Dc,SpatialHtml:Nh,SpatialTrigger:Kp,SpatialTriggerReceiver:vn,SpectatorCamera:Zp,SphereCollider:el,Sprite:Qn,SpriteData:fl,SpriteRenderer:gi,SpriteSheet:gl,SubEmitterSystem:Bp,SyncedCamera:Wy,SyncedRoom:Ls,SyncedTransform:sn,TapGestureTrigger:N0,TeleportTarget:_p,TestRunner:Hy,TestSimulateUserData:Gy,Text:Nt,TextBuilder:ny,TextExtension:Pp,TextureSheetAnimationModule:Vt,TiltShiftEffect:yn,ToneMappingEffect:nr,TrailModule:We,TransformData:ut,TransformGizmo:da,TriggerBuilder:At,TriggerModel:dl,UIRaycastUtils:zf,UIRootComponent:oh,USDZExporter:gn,USDZText:Kr,USDZUIExtension:hy,UsageMarker:$c,VariantAction:j0,VelocityOverLifetimeModule:qe,VerticalLayoutGroup:oy,VideoPlayer:yt,Vignette:la,VisibilityAction:th,Voip:Do,Volume:Ml,VolumeParameter:N,VolumeProfile:Fp,WebARCameraBackground:Hh,WebARSessionRoot:$o,WebXR:wp,WebXRImageTracking:Gh,WebXRImageTrackingModel:ro,WebXRPlaneTracking:ao,WebXRTrackedImage:tv,XRControllerFollow:oo,XRControllerModel:pn,XRControllerMovement:Ni,XRFlag:os,XRRig:um,XRState:Di,__Ignore:uC},Symbol.toStringTag,{value:"Module"})),gm=C("debugmissingcamera");pe.registerCallback(me.MissingCamera,n=>{var e,t,s,o;gm&&console.warn("Creating missing camera");const r=n.context.scene,l=new we;l.name="Default Fallback Camera",r.add(l);const c=new ci;if(c.sourceId=((t=(e=n.files)==null?void 0:e[0])==null?void 0:t.src)??"unknown",c.fieldOfView=35,n.context.domElement.getAttribute("transparent")!=null)c.clearFlags=Io.Uninitialized;else if((s=n.context.domElement.getAttribute("skybox-image"))!=null&&s.length||(o=n.context.domElement.getAttribute("background-image"))!=null&&o.length||n.context.lightmaps.tryGetSkybox(c.sourceId))c.clearFlags=Io.Skybox,c.backgroundBlurriness=.2;else{if(c.clearFlags=Io.SolidColor,!n.context.domElement.getAttribute("background-color")){let u="#efefef";typeof window!==void 0&&window.matchMedia("(prefers-color-scheme: dark)").matches&&(u="#1f1f1f"),r.background=new oe(u)}if(!r.environment){const u=new HP(n.context.renderer),p=new cm("neutral");r.environment=u.fromScene(p,.025).texture}}const h=Mr(l,c,!0);l.position.x=0,l.position.y=1,l.position.z=2;const d=n.context.domElement;return d?.cameraControls!=!1&&pC(n.context,h),h}),pe.registerCallback(me.ContextCreated,n=>{if(!n.context.mainCamera){gm&&console.log("Will not auto-fit because a default camera exists");return}const e=n.context.domElement;if(e?.cameraControls==!0){const t=Cb(n.context.mainCamera);if(t?.isCameraController==!0){gm&&console.log("Will not auto-fit because a camera controller exists");return}pC(n.context)}});function pC(n,e){e=e??n.mainCameraComponent;const t=e?.gameObject;if(gm&&console.log("Creating default camera controls",e?.name),t){const s=vc(t,_e);s.sourceId=e?.sourceId??"unknown";const o=n.domElement.getAttribute("auto-rotate");if(s.autoRotate=o!=null&&o!="0"&&o?.toLowerCase()!="false",s.autoRotateSpeed=.5,s.autoFit=!0,s.autoRotate&&o){const r=parseFloat(o);isNaN(r)||(s.autoRotateSpeed=r)}}else console.warn("Missing camera object, can not add orbit controls")}pe.registerCallback(me.ContextCreated,n=>{const e=n.context.domElement.getAttribute("autoplay");if(e!==void 0&&(e===""||e==="true"||e==="1")&&n.files)for(const t of n.files)P.foreachComponent(t.file.scene,s=>{if(s.enabled!==!1){if(s instanceof Ft&&s.playAutomatically||s instanceof Rt||s instanceof Tl&&s.playOnAwake===!0)return!0;if(s instanceof Ft)return s.playAutomatically=!0,!0;if(s instanceof Tl)return s.playOnAwake=!0,!0}},!0)!==!0&&Ga.assignAnimationsFromFile(t.file,{createAnimationComponent:(s,o)=>Ei(s,Ft)})});class XL extends PO{constructor(){super(new Worker(new URL("/generateMeshBVH.worker-BaNp_Xtp.js",import.meta.url),{type:"module"})),this.name="GenerateMeshBVHWorker"}runTask(e,t,s={}){return new Promise((o,r)=>{if(t.getAttribute("position").isInterleavedBufferAttribute||t.index&&t.index.isInterleavedBufferAttribute)throw new Error("GenerateMeshBVHWorker: InterleavedBufferAttribute are not supported for the geometry attributes.");e.onerror=d=>{r(new Error(`[GenerateMeshBVHWorker] ${d.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"}`))},e.onmessage=d=>{const{data:u}=d;if(u.error)r(new Error(u.error)),e.onmessage=null;else if(u.serialized){const{serialized:p,position:g}=u,f=OO.deserialize(p,t,{setIndex:!1}),y=Object.assign({setBoundingBox:!0},s);if(t.attributes.position.array=g,p.index)if(t.index)t.index.array=p.index;else{const v=new _t(p.index,1,!1);t.setIndex(v)}y.setBoundingBox&&(t.boundingBox=f.getBoundingBox(new Si)),s.onProgress&&s.onProgress(u.progress),o(f),e.onmessage=null}else s.onProgress&&s.onProgress(u.progress)};const l=t.index?t.index.array:null,c=t.attributes.position.array,h=[c];l&&h.push(l),e.postMessage({index:l,position:c,options:{...s,onProgress:null,includedProgressCallback:!!s.onProgress,groups:[...t.groups]}},h.map(d=>d.buffer).filter(d=>typeof SharedArrayBuffer>"u"||!(d instanceof SharedArrayBuffer)))})}}const QL=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:XL},Symbol.toStringTag,{value:"Module"}));export{zT as $physicsKey,ve as ActionBuilder,V1 as ActionCollection,ks as ActionModel,kw as Addressables,Tc as AlignmentConstraint,qa as AmbientMode,Ft as Animation,mh as AnimationCurve,dp as AnimationExtension,im as AnimationTrackHandler,Ga as AnimationUtils,Rt as Animator,Mo as AnimatorConditionMode,gs as AnimatorController,Bf as AnimatorControllerParameterType,Ec as AnimatorStateInfo,bh as Antialiasing,Ln as Application,j_ as AssetDatabase,ce as AssetReference,_a as AudioExtension,zn as AudioListener,ns as AudioSource,sm as AudioTrackHandler,Go as Avatar,zr as AvatarBlink_Simple,Kf as AvatarEyeLook_Rotation,hC as AvatarLoader,hi as AvatarMarker,fv as AvatarModel,Uc as Avatar_Brain_LookAt,zc as Avatar_MouthShapes,Xf as Avatar_MustacheShake,Nn as Avatar_POI,Xa as Axes,Ja as AxesHelper,_g as BUILD_TIME,ps as BaseUIComponent,Jf as BasicIKConstraint,Z0 as BehaviorExtension,Jt as BehaviorModel,Ir as BlobStorage,Np as BloomEffect,Nu as BoxCollider,ea as BoxGizmo,Bo as BoxHelperComponent,no as Button,Po as ButtonsFactory,jx as CallDirection,Un as CallInfo,ci as Camera,Fc as CameraTargetReachedEvent,_l as Canvas,Ko as CanvasGroup,Wn as CapsuleCollider,B0 as ChangeMaterialOnClick,Xr as ChangeTransformOnClick,Nr as CharacterController,$n as CharacterControllerInput,_h as ChromaticAberration,Oi as CircularBuffer,Io as ClearFlags,bn as ClipExtrapolation,ui as Collider,Ax as Collision,ku as CollisionDetectionMode,or as ColorAdjustments,Pl as ColorBySpeedModule,Ip as ColorOverLifetimeModule,$R as Component,I as Component$1,uc as ComponentLifecycleEvents,qL as Components,y_ as ConnectionEvents,Ex as ContactPoint,Vc as ContactShadows,J as Context,IR as ContextArgs,me as ContextEvent,pe as ContextRegistry,nm as ControlTrackHandler,Jr as CustomBranding,o1 as CustomShader,mu as DefaultReflectionMode,n0 as Deletable,Wu as DeleteBox,As as DepthOfField,Vu as DeviceFlag,X as DeviceUtilities,dC as DocumentExtension,Hr as DragControls,r0 as DragMode,Hn as DropListener,h0 as Duplicatable,xh as EffectWrapper,eo as EmissionModule,ul as EmphasizeOnClick,JS as EngineLoadingView,cm as EnvironmentScene,xe as EventList,Ru as EventListEvent,ii as EventSystem,qu as EventTrigger,y1 as FieldWithDefault,_f as FileReference,Aw as FileReferenceSerializer,cE as FileSpawnModel,Gx as File_Event,fy as FixedJoint,xl as Fog,Oe as FrameEvent,jd as GENERATOR,P as GameObject,$ as Gizmos,P0 as GltfExport,S0 as GltfExportBox,ia as Gradient,lh as Graphic,Au as GraphicRaycaster,Jl as Graphics,Sl as GridHelper,ay as GridLayoutGroup,en as GroundProjectedEnv,Wo as GroupActionModel,Du as HideFlags,pp as HideOnStart,dh as HingeJoint,ry as HorizontalLayoutGroup,DM as HostData,El as Image,bf as ImageReference,Tw as ImageReferenceSerializer,Sy as InheritVelocityModule,n_ as Input,oi as InputEventQueue,Be as InputEvents,Yy as InputField,w0 as InstanceHandle,Ju as InstancingHandler,ms as InstancingUtil,X_ as InstantiateEvent,jt as InstantiateIdProvider,Fs as InstantiateOptions,s0 as Interactable,$h as InternalScreenshotUtils,aM as JoinedRoomResponse,Yk as KeyEventArgs,vi as Keyframe,ph as LODGroup,Cl as LODModel,lM as LeftRoomResponse,yi as Light,Nw as LightData,gt as LimitVelocityOverLifetimeModule,IL as LoadingElementOptions,i0 as LogStats,ki as LogType,Ky as LookAt,Fr as LookAtConstraint,A as MODULES,Wt as MainModule,qy as MarkerType,ch as MaskableGraphic,W as Mathf,Fo as MeshCollider,Qc as MeshRenderer,Z as MinMaxCurve,sa as MinMaxGradient,rc as NEKeyboardEvent,An as NEPointerEvent,gv as NeedleButtonElement,l0 as NeedleEngineModelLoader,cv as NeedleEngineWebComponent,un as NeedleMenu,Bd as NeedlePatchesKey,Pg as NeedleXRController,ne as NeedleXRSession,__ as NeedleXRSync,O_ as NeedleXRUtils,kp as NestedGltf,b_ as NetworkConnection,nn as NetworkedStreamEvents,hd as NetworkedStreams,_y as Networking,Y_ as NewInstanceModel,Ce as NoiseModule,ji as ObjectRaycaster,wo as ObjectUtils,ta as OffsetConstraint,Md as OneEuroFilter,og as OneEuroFilterXYZ,Al as OpenURL,_e as OrbitControls,bl as Outline,v_ as OwnershipEvent,Ag as OwnershipModel,Ea as PUBLIC_KEY,Zr as Padding,Ap as ParticleBurst,Cy as ParticleSubEmitter,yh as ParticleSystem,sr as ParticleSystemBaseBehaviour,ds as ParticleSystemRenderer,Ep as ParticleSystemShapeType,Bu as PeerHandle,g_ as PeerNetworking,Gg as Physics,J0 as PhysicsExtension,xt as PhysicsMaterialCombine,Sh as PixelationEffect,Jc as PlayAnimationOnClick,Vo as PlayAudioOnClick,Tl as PlayableDirector,Nl as PlayerColor,Ms as PlayerState,Q1 as PlayerStateEvent,X0 as PlayerSync,Dw as PlayerView,Bw as PlayerViewManager,cd as PointerEventData,Ud as PointerType,rt as PostProcessingEffect,ft as PostProcessingEffectOrder,zy as PostProcessingHandler,pl as PreliminaryAction,eh as PreliminaryTrigger,zo as PreviewHelper,Cr as PrimitiveType,de as Progress,Jm as PromiseAllWithErrors,Zm as PromiseErrorResult,he as RGBAColor,nC as RapierPhysics,am as RawImage,Qs as RaycastOptions,Z1 as Rect,Ts as RectTransform,qc as ReflectionProbe,mr as RegisteredAnimationInfo,qp as RemoteSkybox,Ac as RenderTexture,Cx as RenderTextureSerializer,Ui as Renderer,zw as RendererData,ep as RendererLightmap,dt as Rigidbody,Qe as RigidbodyConstraints,ie as RoomEvents,hs as RotationBySpeedModule,Es as RotationOverLifetimeModule,Qu as SceneLightSettings,Ze as SceneSwitcher,ar as ScreenCapture,to as ScreenSpaceAmbientOcclusion,Is as ScreenSpaceAmbientOcclusionN8,Ss as SendQueue,df as SerializationContext,F0 as SetActiveOnClick,Rh as ShadowCatcher,xy as ShapeModule,Ph as SharpeningEffect,tm as SignalAsset,Dh as SignalReceiver,jh as SignalReceiverEvent,Fh as SignalTrackHandler,K1 as Size,bi as SizeBySpeedModule,na as SizeOverLifetimeModule,x0 as SkinnedMeshRenderer,Yp as SmoothFollow,Dc as SpatialGrabRaycaster,Nh as SpatialHtml,Kp as SpatialTrigger,vn as SpatialTriggerReceiver,Zp as SpectatorCamera,el as SphereCollider,Hg as SphereIntersection,Ix as SphereOverlapResult,Qn as Sprite,fl as SpriteData,gi as SpriteRenderer,gl as SpriteSheet,YR as StateMachineBehaviour,Gf as StreamEndedEvent,Lx as StreamReceivedEvent,Bp as SubEmitterSystem,Wy as SyncedCamera,Ls as SyncedRoom,sn as SyncedTransform,N0 as TapGestureTrigger,_p as TeleportTarget,Hy as TestRunner,NL as TestSceneUtils,Gy as TestSimulateUserData,Nt as Text,ny as TextBuilder,Pp as TextExtension,Vt as TextureSheetAnimationModule,yn as TiltShiftEffect,Vw as Time,nr as ToneMappingEffect,Bh as TrackHandler,qi as TrackType,We as TrailModule,ut as TransformData,da as TransformGizmo,At as TriggerBuilder,dl as TriggerModel,R as TypeStore,zf as UIRaycastUtils,oh as UIRootComponent,O0 as USDDocument,mi as USDObject,C1 as USDWriter,gn as USDZExporter,P1 as USDZExporter$1,Kr as USDZText,hy as USDZUIExtension,Px as UriSerializer,$c as UsageMarker,cM as UserJoinedOrLeftRoomModel,ws as VERSION,j0 as VariantAction,qe as VelocityOverLifetimeModule,oy as VerticalLayoutGroup,yt as VideoPlayer,Co as ViewDevice,la as Vignette,th as VisibilityAction,Do as Voip,Ml as Volume,N as VolumeParameter,Fp as VolumeProfile,dR as WaitForFrames,Iw as WaitForPromise,wf as WaitForSeconds,lo as Watch,Hh as WebARCameraBackground,$o as WebARSessionRoot,wp as WebXR,ml as WebXRButtonFactory,Gh as WebXRImageTracking,ro as WebXRImageTrackingModel,ao as WebXRPlaneTracking,tv as WebXRTrackedImage,oo as XRControllerFollow,pn as XRControllerModel,Ni as XRControllerMovement,os as XRFlag,um as XRRig,Di as XRState,rn as XRStateFlag,uC as __Ignore,z_ as __internalNotifyObjectDestroyed,En as activeInHierarchyFieldName,pb as addAttributeChangeCallback,Ei as addComponent,EE as addCustomExtensionPlugin,Mr as addNewComponent,Dd as addPatch,ou as apply,VR as applyHMRChanges,uw as applyPrototypeExtensions,Q_ as beginListenDestroy,Z_ as beginListenInstantiate,Rg as binaryIdentifierCasts,AR as build_scene_functions,xr as builtinComponentKeyName,lv as calculateProgress01,hk as clearMessages,vT as colorSerializer,iw as compareAssociation,Tu as componentSerializer,Fb as copyTexture,mx as createMotion,ri as debugNet,ac as debugOwner,T1 as decompressGpuTexture,ql as deepClone,vs as delay,Xl as delayForFrames,su as deserializeObject,Ai as destroy,fw as destroyComponentInstance,qx as determineMimeTypeFromExtension,Te as disposeObjectResources,on as disposeStream,oc as editorGuidKeyName,wr as enableSpatialConsole,_T as euler,CT as eventListSerializer,$L as exportAsGLTF,gf as findByGuid,xc as findObjectOfType,bw as findObjectsOfType,Xg as findResourceUsers,zb as fitObjectIntoVolume,Ar as foreachComponent,hu as foreachComponentEnumerator,Pk as forward,gb as generateQRCode,K_ as generateSeed,si as getBoundingBox,Cb as getCameraController,Rr as getComponent,_c as getComponentInChildren,wc as getComponentInParent,bc as getComponents,Wa as getComponentsInChildren,nu as getComponentsInParent,b1 as getFormattedDate,Mt as getIconElement,Of as getIconTexture,xs as getLoader,vc as getOrAddComponent,C as getParam,Mk as getParentHierarchyPath,VO as getPath,sM as getPeerOptions,p_ as getPeerjsInstance,kM as getResourceUserCount,kb as getTempColor,bs as getTempQuaternion,q as getTempVector,Hl as getUrlParams,Ub as getVisibleInCustomShadowRendering,Eb as getWorldDirection,ug as getWorldEuler,ee as getWorldPosition,Se as getWorldQuaternion,Ad as getWorldRotation,Ge as getWorldScale,Js as hasCommercialLicense,kc as hasIndieLicense,Mu as hasPointerEventComponent,Zs as hasProLicense,Hb as hideDebugConsole,E1 as imageToCanvas,Ha as instantiate,a1 as invokeLoadedImportPluginHooks,s_ as invokeXRSessionEnd,i_ as invokeXRSessionStart,_w as isActiveInHierarchy,Va as isActiveSelf,QO as isAndroidDevice,jb as isAnimationAction,Tx as isComponent,UO as isDebugMode,HO as isDesktop,Er as isDestroyed,F as isDevEnvironment,PM as isDisposed,WL as isExporting,Rx as isGLTFModel,sb as isHostedOnGlitch,Df as isHotReloadEnabled,NR as isHotReloading,qO as isIPad,qw as isIconElement,Xt as isLocalNetwork,KO as isMacOS,GO as isMobileDevice,YO as isMozillaXR,ek as isQuest,B_ as isResourceTrackingEnabled,JO as isSafari,au as isUsingInstancing,ZO as isiOS,XO as isiPad,kL as loadAsset,av as loadSync,Id as logHierarchy,yk as lookAtInverse,Kl as lookAtObject,vk as lookAtScreenPoint,NO as makeId,hb as makeIdFromRandomWords,as as makeNameSafe,ww as markAsInstancedRendered,tk as microphonePermissionsGranted,FO as nameof,rb as nameofFactory,Sx as objectSerializer,Qk as offXRSessionEnd,Xk as offXRSessionStart,hT as onAfterRender,cT as onBeforeRender,aT as onClear,lT as onDestroy,vx as onInitialized,bx as onStart,_x as onUpdate,Cg as onXRSessionEnd,Fd as onXRSessionStart,qS as parseSync,Nb as placeOnSurface,gg as postprocessFBXMaterials,uT as prefix,ab as pushState,WO as randomNumber,Tg as registerBinaryType,bu as registerComponent,y0 as registerComponentExtension,us as registerCustomEffectType,v0 as registerExportExtensions,Ku as registerExtensions,lx as registerHotReloadType,wg as registerLoader,ew as registerPrefabProvider,pw as registerPrototypeExtensions,NM as registerType,ub as relativePathPrefix,mb as removeAttributeChangeCallback,mf as removeComponent,AE as removeCustomImportExtensionType,Gk as removePatch,yo as resolveUrl,db as sanitizeString,zS as saveImage,hL as screenshot,Jy as screenshot2,nf as sendDestroyed,m as serializable,rw as serializeObject,Dr as serializeable,Sc as setActive,bb as setAllowBalloonMessages,rk as setAllowOverlayMessages,Td as setAutoFitEnabled,rg as setCameraController,Sw as setDestroyed,Dk as setDevEnvironment,qg as setDisposable,$a as setDontDestroy,Qm as setOrAddParamsToUrl,zO as setParam,Gl as setParamWithoutReload,nM as setPeerOptions,CM as setResourceTrackingEnabled,Ym as setState,mg as setVisibleInCustomShadowRendering,pg as setWorldEuler,lt as setWorldPosition,br as setWorldPositionXYZ,Yi as setWorldQuaternion,dg as setWorldQuaternionXYZW,Lb as setWorldRotation,Zl as setWorldRotationXYZ,Ta as setWorldScale,ic as showBalloonError,De as showBalloonMessage,be as showBalloonWarning,bg as showDebugConsole,fk as slerp,fc as syncDestroy,q0 as syncField,of as syncInstantiate,Rk as textureToCanvas,d_ as tryCastBinary,Qx as tryDetermineMimetypeFromBinary,Xx as tryDetermineMimetypeFromURL,Ma as tryFindObject,u_ as tryGetGuid,cx as unregisterHotReloadType,Km as unwatchWrite,Pb as useForAutoFit,Tt as validate,Od as watchWrite};
1606
+ `),ge(this,ya).innerHTML=ge(this,wi).innerHTML,ge(this,ya).style.cssText="display: flex; align-items: center; justify-content: center;",ge(this,wi).innerHTML=ge(this,ya).outerHTML,ge(this,fa).innerHTML=ge(this,wi).outerHTML,ge(this,fa).prepend(ge(this,va)),fu(kf,{element:ge(this,fa)}),(e=ge(this,Dl))==null||e.disconnect(),ge(this,Dl)??zs(this,Dl,new MutationObserver(()=>dd(this,pm,cC).call(this))),ge(this,Dl).observe(ge(this,wi),{attributes:!0}),mv&&console.log("Needle Button updated")},cC=function(){ge(this,wi)&&(ge(this,wi).style.display==="none"?this.style.display="none":this.style.display==="none"&&(this.style.display=""))},mm=new WeakMap,a(gv,"observedAttributes",["ar","vr","quicklook"]),typeof window<"u"&&!window.customElements.get(aC)&&window.customElements.define(aC,gv);const id=C("debugavatar");class fv{constructor(e,t,s,o){a(this,"root"),a(this,"head"),a(this,"leftHand"),a(this,"rigthHand");var r;this.root=e,this.head=t,this.leftHand=s,this.rigthHand=o,(r=this.root)==null||r.traverse(l=>l.layers.set(2))}get isValid(){return this.head!==null&&this.head!==void 0}}class hC{constructor(){a(this,"avatarRegistryUrl",null)}async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let s=null;if(typeof t=="string"){if(s=await this.loadAvatar(e,t),!s){const r=new Fs;s=P.instantiate(Ma(t,e.scene),r)}}else s=t;if(!s)return null;const o=this.findAvatar(s);return o.isValid?(id&&console.log("[Custom Avatar] valid config",t,id?o:""),o):(console.warn("[Custom Avatar] config isn't valid",t,id?o:""),null)}async loadAvatar(e,t){if(console.assert(t!=null&&typeof t=="string","Avatar id must not be null"),t.length<=0||!t)return null;if(id&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){const o=await fetch("./"+t);let r=null;if(o.ok){const c=await o.blob();c&&(r=await c.arrayBuffer())}if(!r)return null;const l=await xs().parseSync(e,r,null,0);return l?.scene??null}const s=new Rn;return jf(s,e),new Promise((o,r)=>{const l=this.avatarRegistryUrl+"/"+t;s.load(l,async c=>{await xs().createBuiltinComponents(e,l,c,null,void 0),o(c.scene)},c=>{id&&console.log("[Custom Avatar] "+c.loaded/c.total*100+"% loaded of "+c.total/1024+"kB")},c=>{console.error("[Custom Avatar] Error when loading: "+c),o(null)})})}cacheModel(e,t){}findAvatar(e){const t=e;let s=t;s.children.length==1&&(s=e.children[0]);let o=this.findAvatarPart(s,["head"]);const r=this.findAvatarPart(s,["left","hand"]),l=this.findAvatarPart(s,["right","hand"]);if(!o){o=t;const c=new S;new Si().setFromObject(o).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&&o.scale.multiplyScalar(1/h*.3)}return new fv(t,o,r,l)}findAvatarPart(e,t){const s=e.name.toLowerCase();let o=!0;for(const r of t){if(!o)break;s.indexOf(r)===-1&&(o=!1)}if(o)return e;if(e.children)for(const r of e.children){const l=this.findAvatarPart(r,t);if(l)return l}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}}class dC{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(e){}}class uC{}const qL=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:ve,ActionCollection:V1,ActionModel:ks,AlignmentConstraint:Tc,Animation:Ft,AnimationCurve:mh,AnimationExtension:dp,AnimationTrackHandler:im,Animator:Rt,AnimatorController:gs,Antialiasing:bh,AudioExtension:_a,AudioListener:zn,AudioSource:ns,AudioTrackHandler:sm,Avatar:Go,AvatarBlink_Simple:zr,AvatarEyeLook_Rotation:Kf,AvatarLoader:hC,AvatarMarker:hi,AvatarModel:fv,Avatar_Brain_LookAt:Uc,Avatar_MouthShapes:zc,Avatar_MustacheShake:Xf,Avatar_POI:Nn,AxesHelper:Ja,BaseUIComponent:ps,BasicIKConstraint:Jf,BehaviorExtension:Z0,BehaviorModel:Jt,BloomEffect:Np,BoxCollider:Nu,BoxGizmo:ea,BoxHelperComponent:Bo,Button:no,CallInfo:Un,Camera:ci,CameraTargetReachedEvent:Fc,Canvas:_l,CanvasGroup:Ko,CapsuleCollider:Wn,ChangeMaterialOnClick:B0,ChangeTransformOnClick:Xr,CharacterController:Nr,CharacterControllerInput:$n,ChromaticAberration:_h,Collider:ui,ColorAdjustments:or,ColorBySpeedModule:Pl,ColorOverLifetimeModule:Ip,ContactShadows:Vc,ControlTrackHandler:nm,CustomBranding:Jr,Deletable:n0,DeleteBox:Wu,DepthOfField:As,DeviceFlag:Vu,DocumentExtension:dC,DragControls:Hr,DropListener:Hn,Duplicatable:h0,EffectWrapper:xh,EmissionModule:eo,EmphasizeOnClick:ul,EnvironmentScene:cm,EventList:xe,EventListEvent:Ru,EventSystem:ii,EventTrigger:qu,FieldWithDefault:y1,FixedJoint:fy,Fog:xl,GltfExport:P0,GltfExportBox:S0,Gradient:ia,Graphic:lh,GraphicRaycaster:Au,GridHelper:Sl,GridLayoutGroup:ay,GroundProjectedEnv:en,GroupActionModel:Wo,HideOnStart:pp,HingeJoint:dh,HorizontalLayoutGroup:ry,Image:El,InheritVelocityModule:Sy,InputField:Yy,InstanceHandle:w0,InstancingHandler:Ju,Interactable:s0,Keyframe:vi,LODGroup:ph,LODModel:Cl,Light:yi,LimitVelocityOverLifetimeModule:gt,LogStats:i0,LookAt:Ky,LookAtConstraint:Fr,MainModule:Wt,MaskableGraphic:ch,MeshCollider:Fo,MeshRenderer:Qc,MinMaxCurve:Z,MinMaxGradient:sa,NeedleMenu:un,NestedGltf:kp,Networking:_y,NoiseModule:Ce,ObjectRaycaster:ji,OffsetConstraint:ta,OpenURL:Al,OrbitControls:_e,Outline:bl,Padding:Zr,ParticleBurst:Ap,ParticleSubEmitter:Cy,ParticleSystem:yh,ParticleSystemRenderer:ds,PhysicsExtension:J0,PixelationEffect:Sh,PlayAnimationOnClick:Jc,PlayAudioOnClick:Vo,PlayableDirector:Tl,PlayerColor:Nl,PointerEventData:cd,PostProcessingHandler:zy,PreliminaryAction:pl,PreliminaryTrigger:eh,RawImage:am,Rect:Z1,RectTransform:Ts,ReflectionProbe:qc,RegisteredAnimationInfo:mr,RemoteSkybox:qp,Renderer:Ui,RendererLightmap:ep,Rigidbody:dt,RotationBySpeedModule:hs,RotationOverLifetimeModule:Es,SceneSwitcher:Ze,ScreenCapture:ar,ScreenSpaceAmbientOcclusion:to,ScreenSpaceAmbientOcclusionN8:Is,SetActiveOnClick:F0,ShadowCatcher:Rh,ShapeModule:xy,SharpeningEffect:Ph,SignalAsset:tm,SignalReceiver:Dh,SignalReceiverEvent:jh,SignalTrackHandler:Fh,Size:K1,SizeBySpeedModule:bi,SizeOverLifetimeModule:na,SkinnedMeshRenderer:x0,SmoothFollow:Yp,SpatialGrabRaycaster:Dc,SpatialHtml:Nh,SpatialTrigger:Kp,SpatialTriggerReceiver:vn,SpectatorCamera:Zp,SphereCollider:el,Sprite:Qn,SpriteData:fl,SpriteRenderer:gi,SpriteSheet:gl,SubEmitterSystem:Bp,SyncedCamera:Wy,SyncedRoom:Ls,SyncedTransform:sn,TapGestureTrigger:N0,TeleportTarget:_p,TestRunner:Hy,TestSimulateUserData:Gy,Text:Nt,TextBuilder:ny,TextExtension:Pp,TextureSheetAnimationModule:Vt,TiltShiftEffect:yn,ToneMappingEffect:nr,TrailModule:We,TransformData:ut,TransformGizmo:da,TriggerBuilder:At,TriggerModel:dl,UIRaycastUtils:zf,UIRootComponent:oh,USDZExporter:gn,USDZText:Kr,USDZUIExtension:hy,UsageMarker:$c,VariantAction:j0,VelocityOverLifetimeModule:qe,VerticalLayoutGroup:oy,VideoPlayer:yt,Vignette:la,VisibilityAction:th,Voip:Do,Volume:Ml,VolumeParameter:N,VolumeProfile:Fp,WebARCameraBackground:Hh,WebARSessionRoot:$o,WebXR:wp,WebXRImageTracking:Gh,WebXRImageTrackingModel:ro,WebXRPlaneTracking:ao,WebXRTrackedImage:tv,XRControllerFollow:oo,XRControllerModel:pn,XRControllerMovement:Ni,XRFlag:os,XRRig:um,XRState:Di,__Ignore:uC},Symbol.toStringTag,{value:"Module"})),gm=C("debugmissingcamera");pe.registerCallback(me.MissingCamera,n=>{var e,t,s;gm&&console.warn("Creating missing camera");const o=n.context.scene,r=new we;r.name="Default Fallback Camera",o.add(r);const l=new ci;if(l.sourceId=((t=(e=n.files)==null?void 0:e[0])==null?void 0:t.src)??"unknown",l.fieldOfView=35,n.context.domElement.getAttribute("transparent")!=null)l.clearFlags=Io.Uninitialized;else if((s=n.context.domElement.getAttribute("background-image"))!=null&&s.length||n.context.lightmaps.tryGetSkybox(l.sourceId))l.clearFlags=Io.Skybox,n.context.domElement.getAttribute("background-blurriness")===null&&(n.context.scene.backgroundBlurriness=.2);else{if(l.clearFlags=Io.SolidColor,!n.context.domElement.getAttribute("background-color")){let d="#efefef";typeof window!==void 0&&window.matchMedia("(prefers-color-scheme: dark)").matches&&(d="#1f1f1f"),o.background=new oe(d)}if(!o.environment){const d=new HP(n.context.renderer),u=new cm("neutral");o.environment=d.fromScene(u,.025).texture}}const c=Mr(r,l,!0);r.position.x=0,r.position.y=1,r.position.z=2;const h=n.context.domElement;return h?.cameraControls!=!1&&pC(n.context,c),c}),pe.registerCallback(me.ContextCreated,n=>{if(!n.context.mainCamera){gm&&console.log("Will not auto-fit because a default camera exists");return}const e=n.context.domElement;if(e?.cameraControls==!0){const t=Cb(n.context.mainCamera);if(t?.isCameraController==!0){gm&&console.log("Will not auto-fit because a camera controller exists");return}pC(n.context)}});function pC(n,e){e=e??n.mainCameraComponent;const t=e?.gameObject;if(gm&&console.log("Creating default camera controls",e?.name),t){const s=vc(t,_e);s.sourceId=e?.sourceId??"unknown";const o=n.domElement.getAttribute("auto-rotate");if(s.autoRotate=o!=null&&o!="0"&&o?.toLowerCase()!="false",s.autoRotateSpeed=.5,s.autoFit=!0,s.autoRotate&&o){const r=parseFloat(o);isNaN(r)||(s.autoRotateSpeed=r)}}else console.warn("Missing camera object, can not add orbit controls")}pe.registerCallback(me.ContextCreated,n=>{const e=n.context.domElement.getAttribute("autoplay");if(e!==void 0&&(e===""||e==="true"||e==="1")&&n.files)for(const t of n.files)P.foreachComponent(t.file.scene,s=>{if(s.enabled!==!1){if(s instanceof Ft&&s.playAutomatically||s instanceof Rt||s instanceof Tl&&s.playOnAwake===!0)return!0;if(s instanceof Ft)return s.playAutomatically=!0,!0;if(s instanceof Tl)return s.playOnAwake=!0,!0}},!0)!==!0&&Ga.assignAnimationsFromFile(t.file,{createAnimationComponent:(s,o)=>Ei(s,Ft)})});class XL extends PO{constructor(){super(new Worker(new URL("/generateMeshBVH.worker-BaNp_Xtp.js",import.meta.url),{type:"module"})),this.name="GenerateMeshBVHWorker"}runTask(e,t,s={}){return new Promise((o,r)=>{if(t.getAttribute("position").isInterleavedBufferAttribute||t.index&&t.index.isInterleavedBufferAttribute)throw new Error("GenerateMeshBVHWorker: InterleavedBufferAttribute are not supported for the geometry attributes.");e.onerror=d=>{r(new Error(`[GenerateMeshBVHWorker] ${d.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"}`))},e.onmessage=d=>{const{data:u}=d;if(u.error)r(new Error(u.error)),e.onmessage=null;else if(u.serialized){const{serialized:p,position:g}=u,f=OO.deserialize(p,t,{setIndex:!1}),y=Object.assign({setBoundingBox:!0},s);if(t.attributes.position.array=g,p.index)if(t.index)t.index.array=p.index;else{const v=new _t(p.index,1,!1);t.setIndex(v)}y.setBoundingBox&&(t.boundingBox=f.getBoundingBox(new Si)),s.onProgress&&s.onProgress(u.progress),o(f),e.onmessage=null}else s.onProgress&&s.onProgress(u.progress)};const l=t.index?t.index.array:null,c=t.attributes.position.array,h=[c];l&&h.push(l),e.postMessage({index:l,position:c,options:{...s,onProgress:null,includedProgressCallback:!!s.onProgress,groups:[...t.groups]}},h.map(d=>d.buffer).filter(d=>typeof SharedArrayBuffer>"u"||!(d instanceof SharedArrayBuffer)))})}}const QL=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:XL},Symbol.toStringTag,{value:"Module"}));export{zT as $physicsKey,ve as ActionBuilder,V1 as ActionCollection,ks as ActionModel,kw as Addressables,Tc as AlignmentConstraint,qa as AmbientMode,Ft as Animation,mh as AnimationCurve,dp as AnimationExtension,im as AnimationTrackHandler,Ga as AnimationUtils,Rt as Animator,Mo as AnimatorConditionMode,gs as AnimatorController,Bf as AnimatorControllerParameterType,Ec as AnimatorStateInfo,bh as Antialiasing,Ln as Application,j_ as AssetDatabase,ce as AssetReference,_a as AudioExtension,zn as AudioListener,ns as AudioSource,sm as AudioTrackHandler,Go as Avatar,zr as AvatarBlink_Simple,Kf as AvatarEyeLook_Rotation,hC as AvatarLoader,hi as AvatarMarker,fv as AvatarModel,Uc as Avatar_Brain_LookAt,zc as Avatar_MouthShapes,Xf as Avatar_MustacheShake,Nn as Avatar_POI,Xa as Axes,Ja as AxesHelper,_g as BUILD_TIME,ps as BaseUIComponent,Jf as BasicIKConstraint,Z0 as BehaviorExtension,Jt as BehaviorModel,Ir as BlobStorage,Np as BloomEffect,Nu as BoxCollider,ea as BoxGizmo,Bo as BoxHelperComponent,no as Button,Po as ButtonsFactory,jx as CallDirection,Un as CallInfo,ci as Camera,Fc as CameraTargetReachedEvent,_l as Canvas,Ko as CanvasGroup,Wn as CapsuleCollider,B0 as ChangeMaterialOnClick,Xr as ChangeTransformOnClick,Nr as CharacterController,$n as CharacterControllerInput,_h as ChromaticAberration,Oi as CircularBuffer,Io as ClearFlags,bn as ClipExtrapolation,ui as Collider,Ax as Collision,ku as CollisionDetectionMode,or as ColorAdjustments,Pl as ColorBySpeedModule,Ip as ColorOverLifetimeModule,$R as Component,I as Component$1,uc as ComponentLifecycleEvents,qL as Components,y_ as ConnectionEvents,Ex as ContactPoint,Vc as ContactShadows,J as Context,IR as ContextArgs,me as ContextEvent,pe as ContextRegistry,nm as ControlTrackHandler,Jr as CustomBranding,o1 as CustomShader,mu as DefaultReflectionMode,n0 as Deletable,Wu as DeleteBox,As as DepthOfField,Vu as DeviceFlag,X as DeviceUtilities,dC as DocumentExtension,Hr as DragControls,r0 as DragMode,Hn as DropListener,h0 as Duplicatable,xh as EffectWrapper,eo as EmissionModule,ul as EmphasizeOnClick,JS as EngineLoadingView,cm as EnvironmentScene,xe as EventList,Ru as EventListEvent,ii as EventSystem,qu as EventTrigger,y1 as FieldWithDefault,_f as FileReference,Aw as FileReferenceSerializer,cE as FileSpawnModel,Gx as File_Event,fy as FixedJoint,xl as Fog,Oe as FrameEvent,jd as GENERATOR,P as GameObject,$ as Gizmos,P0 as GltfExport,S0 as GltfExportBox,ia as Gradient,lh as Graphic,Au as GraphicRaycaster,Jl as Graphics,Sl as GridHelper,ay as GridLayoutGroup,en as GroundProjectedEnv,Wo as GroupActionModel,Du as HideFlags,pp as HideOnStart,dh as HingeJoint,ry as HorizontalLayoutGroup,DM as HostData,El as Image,bf as ImageReference,Tw as ImageReferenceSerializer,Sy as InheritVelocityModule,n_ as Input,oi as InputEventQueue,Be as InputEvents,Yy as InputField,w0 as InstanceHandle,Ju as InstancingHandler,ms as InstancingUtil,X_ as InstantiateEvent,jt as InstantiateIdProvider,Fs as InstantiateOptions,s0 as Interactable,$h as InternalScreenshotUtils,aM as JoinedRoomResponse,Yk as KeyEventArgs,vi as Keyframe,ph as LODGroup,Cl as LODModel,lM as LeftRoomResponse,yi as Light,Nw as LightData,gt as LimitVelocityOverLifetimeModule,IL as LoadingElementOptions,i0 as LogStats,ki as LogType,Ky as LookAt,Fr as LookAtConstraint,A as MODULES,Wt as MainModule,qy as MarkerType,ch as MaskableGraphic,W as Mathf,Fo as MeshCollider,Qc as MeshRenderer,Z as MinMaxCurve,sa as MinMaxGradient,rc as NEKeyboardEvent,An as NEPointerEvent,gv as NeedleButtonElement,l0 as NeedleEngineModelLoader,cv as NeedleEngineWebComponent,un as NeedleMenu,Bd as NeedlePatchesKey,Pg as NeedleXRController,ne as NeedleXRSession,__ as NeedleXRSync,O_ as NeedleXRUtils,kp as NestedGltf,b_ as NetworkConnection,nn as NetworkedStreamEvents,hd as NetworkedStreams,_y as Networking,Y_ as NewInstanceModel,Ce as NoiseModule,ji as ObjectRaycaster,wo as ObjectUtils,ta as OffsetConstraint,Md as OneEuroFilter,og as OneEuroFilterXYZ,Al as OpenURL,_e as OrbitControls,bl as Outline,v_ as OwnershipEvent,Ag as OwnershipModel,Ea as PUBLIC_KEY,Zr as Padding,Ap as ParticleBurst,Cy as ParticleSubEmitter,yh as ParticleSystem,sr as ParticleSystemBaseBehaviour,ds as ParticleSystemRenderer,Ep as ParticleSystemShapeType,Bu as PeerHandle,g_ as PeerNetworking,Gg as Physics,J0 as PhysicsExtension,xt as PhysicsMaterialCombine,Sh as PixelationEffect,Jc as PlayAnimationOnClick,Vo as PlayAudioOnClick,Tl as PlayableDirector,Nl as PlayerColor,Ms as PlayerState,Q1 as PlayerStateEvent,X0 as PlayerSync,Dw as PlayerView,Bw as PlayerViewManager,cd as PointerEventData,Ud as PointerType,rt as PostProcessingEffect,ft as PostProcessingEffectOrder,zy as PostProcessingHandler,pl as PreliminaryAction,eh as PreliminaryTrigger,zo as PreviewHelper,Cr as PrimitiveType,de as Progress,Jm as PromiseAllWithErrors,Zm as PromiseErrorResult,he as RGBAColor,nC as RapierPhysics,am as RawImage,Qs as RaycastOptions,Z1 as Rect,Ts as RectTransform,qc as ReflectionProbe,mr as RegisteredAnimationInfo,qp as RemoteSkybox,Ac as RenderTexture,Cx as RenderTextureSerializer,Ui as Renderer,zw as RendererData,ep as RendererLightmap,dt as Rigidbody,Qe as RigidbodyConstraints,ie as RoomEvents,hs as RotationBySpeedModule,Es as RotationOverLifetimeModule,Qu as SceneLightSettings,Ze as SceneSwitcher,ar as ScreenCapture,to as ScreenSpaceAmbientOcclusion,Is as ScreenSpaceAmbientOcclusionN8,Ss as SendQueue,df as SerializationContext,F0 as SetActiveOnClick,Rh as ShadowCatcher,xy as ShapeModule,Ph as SharpeningEffect,tm as SignalAsset,Dh as SignalReceiver,jh as SignalReceiverEvent,Fh as SignalTrackHandler,K1 as Size,bi as SizeBySpeedModule,na as SizeOverLifetimeModule,x0 as SkinnedMeshRenderer,Yp as SmoothFollow,Dc as SpatialGrabRaycaster,Nh as SpatialHtml,Kp as SpatialTrigger,vn as SpatialTriggerReceiver,Zp as SpectatorCamera,el as SphereCollider,Hg as SphereIntersection,Ix as SphereOverlapResult,Qn as Sprite,fl as SpriteData,gi as SpriteRenderer,gl as SpriteSheet,YR as StateMachineBehaviour,Gf as StreamEndedEvent,Lx as StreamReceivedEvent,Bp as SubEmitterSystem,Wy as SyncedCamera,Ls as SyncedRoom,sn as SyncedTransform,N0 as TapGestureTrigger,_p as TeleportTarget,Hy as TestRunner,NL as TestSceneUtils,Gy as TestSimulateUserData,Nt as Text,ny as TextBuilder,Pp as TextExtension,Vt as TextureSheetAnimationModule,yn as TiltShiftEffect,Vw as Time,nr as ToneMappingEffect,Bh as TrackHandler,qi as TrackType,We as TrailModule,ut as TransformData,da as TransformGizmo,At as TriggerBuilder,dl as TriggerModel,R as TypeStore,zf as UIRaycastUtils,oh as UIRootComponent,O0 as USDDocument,mi as USDObject,C1 as USDWriter,gn as USDZExporter,P1 as USDZExporter$1,Kr as USDZText,hy as USDZUIExtension,Px as UriSerializer,$c as UsageMarker,cM as UserJoinedOrLeftRoomModel,ws as VERSION,j0 as VariantAction,qe as VelocityOverLifetimeModule,oy as VerticalLayoutGroup,yt as VideoPlayer,Co as ViewDevice,la as Vignette,th as VisibilityAction,Do as Voip,Ml as Volume,N as VolumeParameter,Fp as VolumeProfile,dR as WaitForFrames,Iw as WaitForPromise,wf as WaitForSeconds,lo as Watch,Hh as WebARCameraBackground,$o as WebARSessionRoot,wp as WebXR,ml as WebXRButtonFactory,Gh as WebXRImageTracking,ro as WebXRImageTrackingModel,ao as WebXRPlaneTracking,tv as WebXRTrackedImage,oo as XRControllerFollow,pn as XRControllerModel,Ni as XRControllerMovement,os as XRFlag,um as XRRig,Di as XRState,rn as XRStateFlag,uC as __Ignore,z_ as __internalNotifyObjectDestroyed,En as activeInHierarchyFieldName,pb as addAttributeChangeCallback,Ei as addComponent,EE as addCustomExtensionPlugin,Mr as addNewComponent,Dd as addPatch,ou as apply,VR as applyHMRChanges,uw as applyPrototypeExtensions,Q_ as beginListenDestroy,Z_ as beginListenInstantiate,Rg as binaryIdentifierCasts,AR as build_scene_functions,xr as builtinComponentKeyName,lv as calculateProgress01,hk as clearMessages,vT as colorSerializer,iw as compareAssociation,Tu as componentSerializer,Fb as copyTexture,mx as createMotion,ri as debugNet,ac as debugOwner,T1 as decompressGpuTexture,ql as deepClone,vs as delay,Xl as delayForFrames,su as deserializeObject,Ai as destroy,fw as destroyComponentInstance,qx as determineMimeTypeFromExtension,Te as disposeObjectResources,on as disposeStream,oc as editorGuidKeyName,wr as enableSpatialConsole,_T as euler,CT as eventListSerializer,$L as exportAsGLTF,gf as findByGuid,xc as findObjectOfType,bw as findObjectsOfType,Xg as findResourceUsers,zb as fitObjectIntoVolume,Ar as foreachComponent,hu as foreachComponentEnumerator,Pk as forward,gb as generateQRCode,K_ as generateSeed,si as getBoundingBox,Cb as getCameraController,Rr as getComponent,_c as getComponentInChildren,wc as getComponentInParent,bc as getComponents,Wa as getComponentsInChildren,nu as getComponentsInParent,b1 as getFormattedDate,Mt as getIconElement,Of as getIconTexture,xs as getLoader,vc as getOrAddComponent,C as getParam,Mk as getParentHierarchyPath,VO as getPath,sM as getPeerOptions,p_ as getPeerjsInstance,kM as getResourceUserCount,kb as getTempColor,bs as getTempQuaternion,q as getTempVector,Hl as getUrlParams,Ub as getVisibleInCustomShadowRendering,Eb as getWorldDirection,ug as getWorldEuler,ee as getWorldPosition,Se as getWorldQuaternion,Ad as getWorldRotation,Ge as getWorldScale,Js as hasCommercialLicense,kc as hasIndieLicense,Mu as hasPointerEventComponent,Zs as hasProLicense,Hb as hideDebugConsole,E1 as imageToCanvas,Ha as instantiate,a1 as invokeLoadedImportPluginHooks,s_ as invokeXRSessionEnd,i_ as invokeXRSessionStart,_w as isActiveInHierarchy,Va as isActiveSelf,QO as isAndroidDevice,jb as isAnimationAction,Tx as isComponent,UO as isDebugMode,HO as isDesktop,Er as isDestroyed,F as isDevEnvironment,PM as isDisposed,WL as isExporting,Rx as isGLTFModel,sb as isHostedOnGlitch,Df as isHotReloadEnabled,NR as isHotReloading,qO as isIPad,qw as isIconElement,Xt as isLocalNetwork,KO as isMacOS,GO as isMobileDevice,YO as isMozillaXR,ek as isQuest,B_ as isResourceTrackingEnabled,JO as isSafari,au as isUsingInstancing,ZO as isiOS,XO as isiPad,kL as loadAsset,av as loadSync,Id as logHierarchy,yk as lookAtInverse,Kl as lookAtObject,vk as lookAtScreenPoint,NO as makeId,hb as makeIdFromRandomWords,as as makeNameSafe,ww as markAsInstancedRendered,tk as microphonePermissionsGranted,FO as nameof,rb as nameofFactory,Sx as objectSerializer,Qk as offXRSessionEnd,Xk as offXRSessionStart,hT as onAfterRender,cT as onBeforeRender,aT as onClear,lT as onDestroy,vx as onInitialized,bx as onStart,_x as onUpdate,Cg as onXRSessionEnd,Fd as onXRSessionStart,qS as parseSync,Nb as placeOnSurface,gg as postprocessFBXMaterials,uT as prefix,ab as pushState,WO as randomNumber,Tg as registerBinaryType,bu as registerComponent,y0 as registerComponentExtension,us as registerCustomEffectType,v0 as registerExportExtensions,Ku as registerExtensions,lx as registerHotReloadType,wg as registerLoader,ew as registerPrefabProvider,pw as registerPrototypeExtensions,NM as registerType,ub as relativePathPrefix,mb as removeAttributeChangeCallback,mf as removeComponent,AE as removeCustomImportExtensionType,Gk as removePatch,yo as resolveUrl,db as sanitizeString,zS as saveImage,hL as screenshot,Jy as screenshot2,nf as sendDestroyed,m as serializable,rw as serializeObject,Dr as serializeable,Sc as setActive,bb as setAllowBalloonMessages,rk as setAllowOverlayMessages,Td as setAutoFitEnabled,rg as setCameraController,Sw as setDestroyed,Dk as setDevEnvironment,qg as setDisposable,$a as setDontDestroy,Qm as setOrAddParamsToUrl,zO as setParam,Gl as setParamWithoutReload,nM as setPeerOptions,CM as setResourceTrackingEnabled,Ym as setState,mg as setVisibleInCustomShadowRendering,pg as setWorldEuler,lt as setWorldPosition,br as setWorldPositionXYZ,Yi as setWorldQuaternion,dg as setWorldQuaternionXYZW,Lb as setWorldRotation,Zl as setWorldRotationXYZ,Ta as setWorldScale,ic as showBalloonError,De as showBalloonMessage,be as showBalloonWarning,bg as showDebugConsole,fk as slerp,fc as syncDestroy,q0 as syncField,of as syncInstantiate,Rk as textureToCanvas,d_ as tryCastBinary,Qx as tryDetermineMimetypeFromBinary,Xx as tryDetermineMimetypeFromURL,Ma as tryFindObject,u_ as tryGetGuid,cx as unregisterHotReloadType,Km as unwatchWrite,Pb as useForAutoFit,Tt as validate,Od as watchWrite};