@needle-tools/engine 4.5.0-alpha.2 → 4.5.0-alpha.3

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 (24) hide show
  1. package/CHANGELOG.md +1 -0
  2. package/dist/{needle-engine.bundle-53f80c62.js → needle-engine.bundle-1b8f44f4.js} +218 -198
  3. package/dist/{needle-engine.bundle-15b19b2c.light.min.js → needle-engine.bundle-56f095f1.light.min.js} +3 -3
  4. package/dist/{needle-engine.bundle-f3c8cffc.light.umd.cjs → needle-engine.bundle-9fe9a394.light.umd.cjs} +5 -5
  5. package/dist/{needle-engine.bundle-2024e2b3.min.js → needle-engine.bundle-baacde19.min.js} +3 -3
  6. package/dist/{needle-engine.bundle-1526f05b.light.js → needle-engine.bundle-d710d96f.light.js} +26 -6
  7. package/dist/{needle-engine.bundle-a52706c5.umd.cjs → needle-engine.bundle-ef2b8438.umd.cjs} +5 -5
  8. package/dist/needle-engine.js +2 -2
  9. package/dist/needle-engine.light.js +2 -2
  10. package/dist/needle-engine.light.min.js +1 -1
  11. package/dist/needle-engine.light.umd.cjs +1 -1
  12. package/dist/needle-engine.min.js +1 -1
  13. package/dist/needle-engine.umd.cjs +1 -1
  14. package/lib/engine/engine_context_registry.d.ts +2 -2
  15. package/lib/engine/engine_context_registry.js +2 -2
  16. package/lib/engine/engine_context_registry.js.map +1 -1
  17. package/lib/engine-components/ContactShadows.d.ts +12 -0
  18. package/lib/engine-components/ContactShadows.js +23 -0
  19. package/lib/engine-components/ContactShadows.js.map +1 -1
  20. package/lib/engine-components/webxr/controllers/XRControllerModel.js.map +1 -1
  21. package/package.json +1 -1
  22. package/src/engine/engine_context_registry.ts +2 -2
  23. package/src/engine-components/ContactShadows.ts +24 -0
  24. package/src/engine-components/webxr/controllers/XRControllerModel.ts +0 -2
@@ -130,7 +130,7 @@ Open this page to get the console: `+t.toString())}const s=exports.DeviceUtiliti
130
130
  #__vconsole .vc-mask {
131
131
  overflow: hidden;
132
132
  }
133
- `,mi==null||mi.prepend(i),s===!0&&Tm()<=0&&i0(),console.log("🌵 Debug console has loaded")}},t.onerror=()=>{console.warn("🌵 Debug console failed to load."+(window.crossOriginIsolated?"This page is using cross-origin isolation, so external scripts can't be loaded.":"")),ml=!1,Wt=null},t.src="https://unpkg.com/vconsole@latest/dist/vconsole.min.js",document.body.appendChild(t)}function CS(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("needle-console","🌵 Inspect glTF"),t=()=>document.querySelector("#__vc_plug_"+s._id+" iframe");return s.on("renderTab",function(e){const i=globalThis["needle:codegen_files"];if(!i||i.length===0)return;let n=globalThis["needle:codegen_files"][0];const o=n.indexOf("?");o>-1&&(n=n.substring(0,o));const l=location.protocol+"//"+location.host+location.pathname+"/"+n,c=encodeURIComponent(l);s.fullUrl="https://viewer.needle.tools?inspect&file="+c;var d='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';e(d)}),s.on("show",function(){const e=t();e&&e.src!==s.fullUrl&&(e.src=s.fullUrl)}),s.on("hide",function(){const e=t();e&&(e.src="")}),s.on("addTopBar",function(e){var i=new Array;i.push({name:"Open in new window ↗",onClick:function(n){window.open(s.fullUrl,"_blank"),Wt==null||Wt.hide()}}),i.push({name:"Reload",onClick:function(n){const o=t();o&&(o.src=s.fullUrl)}}),i.push({name:"Fullscreen",onClick:function(n){const o=t();o.requestFullscreen?o.requestFullscreen():o.webkitRequestFullscreen instanceof Function&&o.webkitRequestFullscreen()}}),e(i)}),s}function PS(){const s=document.querySelector("#__vconsole .vc-switch");return s||null}function OS(){const s=document.querySelector("#__vconsole");return s||null}const o0=x("debugdefines");_o('if(!globalThis[""4.5.0-alpha.2""]) globalThis[""4.5.0-alpha.2""] = "0.0.0";');_o('if(!globalThis[""undefined""]) globalThis[""undefined""] = "unknown";');_o('if(!globalThis[""Mon May 12 2025 19:38:07 GMT+0700 (Indochina Time)""]) globalThis[""Mon May 12 2025 19:38:07 GMT+0700 (Indochina Time)""] = "unknown";');_o('if(!globalThis[""npk_ad8e492e31253a2800d563522e42a7311d0d7b766ac4ec1f64d3b425f06eacbd""]) globalThis[""npk_ad8e492e31253a2800d563522e42a7311d0d7b766ac4ec1f64d3b425f06eacbd""] = "unknown";');_o('globalThis["__NEEDLE_ENGINE_VERSION__"] = "4.5.0-alpha.2";');_o('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";');_o('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Mon May 12 2025 19:38:07 GMT+0700 (Indochina Time)";');_o('globalThis["__NEEDLE_PUBLIC_KEY__"] = "npk_ad8e492e31253a2800d563522e42a7311d0d7b766ac4ec1f64d3b425f06eacbd";');const hn="4.5.0-alpha.2",Su="undefined",zm="Mon May 12 2025 19:38:07 GMT+0700 (Indochina Time)";o0&&console.log(`Engine version: ${hn} (generator: ${Su})
133
+ `,mi==null||mi.prepend(i),s===!0&&Tm()<=0&&i0(),console.log("🌵 Debug console has loaded")}},t.onerror=()=>{console.warn("🌵 Debug console failed to load."+(window.crossOriginIsolated?"This page is using cross-origin isolation, so external scripts can't be loaded.":"")),ml=!1,Wt=null},t.src="https://unpkg.com/vconsole@latest/dist/vconsole.min.js",document.body.appendChild(t)}function CS(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("needle-console","🌵 Inspect glTF"),t=()=>document.querySelector("#__vc_plug_"+s._id+" iframe");return s.on("renderTab",function(e){const i=globalThis["needle:codegen_files"];if(!i||i.length===0)return;let n=globalThis["needle:codegen_files"][0];const o=n.indexOf("?");o>-1&&(n=n.substring(0,o));const l=location.protocol+"//"+location.host+location.pathname+"/"+n,c=encodeURIComponent(l);s.fullUrl="https://viewer.needle.tools?inspect&file="+c;var d='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';e(d)}),s.on("show",function(){const e=t();e&&e.src!==s.fullUrl&&(e.src=s.fullUrl)}),s.on("hide",function(){const e=t();e&&(e.src="")}),s.on("addTopBar",function(e){var i=new Array;i.push({name:"Open in new window ↗",onClick:function(n){window.open(s.fullUrl,"_blank"),Wt==null||Wt.hide()}}),i.push({name:"Reload",onClick:function(n){const o=t();o&&(o.src=s.fullUrl)}}),i.push({name:"Fullscreen",onClick:function(n){const o=t();o.requestFullscreen?o.requestFullscreen():o.webkitRequestFullscreen instanceof Function&&o.webkitRequestFullscreen()}}),e(i)}),s}function PS(){const s=document.querySelector("#__vconsole .vc-switch");return s||null}function OS(){const s=document.querySelector("#__vconsole");return s||null}const o0=x("debugdefines");_o('if(!globalThis[""4.5.0-alpha.3""]) globalThis[""4.5.0-alpha.3""] = "0.0.0";');_o('if(!globalThis[""undefined""]) globalThis[""undefined""] = "unknown";');_o('if(!globalThis[""Mon May 12 2025 21:24:49 GMT+0700 (Indochina Time)""]) globalThis[""Mon May 12 2025 21:24:49 GMT+0700 (Indochina Time)""] = "unknown";');_o('if(!globalThis[""npk_ad8e492e31253a2800d563522e42a7311d0d7b766ac4ec1f64d3b425f06eacbd""]) globalThis[""npk_ad8e492e31253a2800d563522e42a7311d0d7b766ac4ec1f64d3b425f06eacbd""] = "unknown";');_o('globalThis["__NEEDLE_ENGINE_VERSION__"] = "4.5.0-alpha.3";');_o('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";');_o('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Mon May 12 2025 21:24:49 GMT+0700 (Indochina Time)";');_o('globalThis["__NEEDLE_PUBLIC_KEY__"] = "npk_ad8e492e31253a2800d563522e42a7311d0d7b766ac4ec1f64d3b425f06eacbd";');const hn="4.5.0-alpha.3",Su="undefined",zm="Mon May 12 2025 21:24:49 GMT+0700 (Indochina Time)";o0&&console.log(`Engine version: ${hn} (generator: ${Su})
134
134
  Project built at ${zm}`);const Jl="npk_ad8e492e31253a2800d563522e42a7311d0d7b766ac4ec1f64d3b425f06eacbd",ms="needle_isActiveInHierarchy",Uo="builtin_components",ec="needle_editor_guid";function _o(s){try{(0,eval)(s)}catch(t){o0&&console.error(t)}}let r0,zy=null;function un(){return r0}function Nm(s){if(s==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}zy!==s&&(zy=s,r0=new s)}const _i=Symbol("shadowDomOwner"),MS=x("debugpatch");function Cu(s,t,e,i){const n=MS===t;if(!e&&!i)return;const o=t+"___needle";ES(s,t,e,i);const a=Object.getOwnPropertyDescriptor(s,t),l=s[t];n&&console.log("Patch",s.constructor.name,t,a,l),a?(n&&console.log("Apply patch with existing descriptor",s.constructor.name,t,a),typeof a.value=="function"&&(s[t]=Vy(a.value,s,t))):(n&&console.log("Create patch with new property",s.constructor.name,t,a),Object.defineProperty(s,t,{set:function(c){if(typeof c=="function")this[o]=Vy(c,s,t);else{const d=this[o];a0(s,t,this,d,c),this[o]=c,l0(s,t,this,d,c)}},get:function(){const c=this[o];return typeof c=="function"&&c[o]?c[o]:c}}))}function RS(s,t,e){const i=Vm(s,t);if(i)for(let n=i.length-1;n>=0;n--){const o=i[n];o.prefix===e&&(o.prefix=null),o.postfix===e&&(o.postfix=null),!o.prefix&&!o.postfix&&i.splice(n,1)}}const Ny=Symbol("Needle:Patches:WrappedFunction");function Vy(s,t,e){if(s[Ny])return s;const i=function(...n){a0(t,e,this,...n);const o=s.apply(this,n);return l0(t,e,this,o,...n),o};return i[Ny]=!0,i}const pd="Needle:Patches";function Np(){return globalThis[pd]||(globalThis[pd]=new WeakMap),globalThis[pd]}function Vm(s,t){const e=Np().get(s);return e?e.get(t):null}function ES(s,t,e,i){let n=Np().get(s);n||(n=new Map,Np().set(s,n));let o=n.get(t);o||(o=[],n.set(t,o)),o.push({prefix:e,postfix:i})}function a0(s,t,e,...i){var o;if(!e)return;const n=Vm(s,t);if(n)for(const a of n)(o=a.prefix)==null||o.call(e,...i)}function l0(s,t,e,i,...n){var a;if(!e)return;const o=Vm(s,t);if(o)for(const l of o)(a=l.postfix)==null||a.call(e,i,...n)}const Ea=[];function Pu(s){Ea.indexOf(s)===-1&&Ea.push(s)}function kS(s){const t=Ea.indexOf(s);t!==-1&&Ea.splice(t,1)}const ka=[];function $m(s){ka.indexOf(s)===-1&&ka.push(s)}function TS(s){const t=ka.indexOf(s);t!==-1&&ka.splice(t,1)}function c0(s){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-start",{detail:s}));for(let t=0;t<Ea.length;t++)Ea[t](s)}function h0(s){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-end",{detail:s}));for(let t=0;t<ka.length;t++)ka[t](s)}const Je=x("debuginput");var Ou=(s=>(s.Mouse="mouse",s.Touch="touch",s.Controller="controller",s.Hand="hand",s))(Ou||{}),Ee=(s=>(s.PointerDown="pointerdown",s.PointerUp="pointerup",s.PointerMove="pointermove",s.KeyDown="keydown",s.KeyUp="keyup",s.KeyPressed="keypress",s))(Ee||{});class ss extends PointerEvent{constructor(e,i,n){super(e,n);r(this,"clientZ");r(this,"deviceIndex");r(this,"origin");r(this,"source");r(this,"mode");r(this,"_ray");r(this,"space");r(this,"isClick",!1);r(this,"isDoubleClick",!1);r(this,"_used",!1);r(this,"_pointerid");r(this,"_pointerType");r(this,"_type");r(this,"metadata",{});r(this,"intersections",new Array);r(this,"_immediatePropagationStopped",!1);r(this,"_propagationStopped",!1);this.clientZ=n.clientZ,this._pointerid=n.pointerId,this._pointerType=n.pointerType,this._type=e,this.deviceIndex=n.deviceIndex,this.origin=n.origin,this.source=i,this.mode=n.mode,this._ray=n.ray,this.space=n.device}get isSpatial(){return this.mode!="screen"}get ray(){return this._ray||(this._ray=new h.Ray(this.space.worldPosition.clone(),this.space.worldForward.clone())),this._ray}set ray(e){this._ray=e}get hasRay(){return this._ray!==void 0}get used(){return this._used}use(){this._used=!0}get pointerId(){return this._pointerid}get pointerType(){return this._pointerType}get type(){return this._type}get immediatePropagationStopped(){return this._immediatePropagationStopped}get propagationStopped(){return this._immediatePropagationStopped||this._propagationStopped}stopImmediatePropagation(){var e;this._immediatePropagationStopped=!0,super.stopImmediatePropagation(),(e=this.source)==null||e.stopImmediatePropagation()}stopPropagation(){var e;this._propagationStopped=!0,super.stopPropagation(),(e=this.source)==null||e.stopPropagation(),Je&&console.warn("Stop propagation...",this.pointerId,this.pointerType)}}class Il extends KeyboardEvent{constructor(e,i,n){super(e,n);r(this,"source");this.source=i}stopImmediatePropagation(){var e;super.stopImmediatePropagation(),(e=this.source)==null||e.stopImmediatePropagation()}}class AS{constructor(t){r(this,"key");r(this,"keyType");r(this,"source");this.key=t.key,this.keyType=t.type,this.source=t}}var ei=(s=>(s[s.Early=-100]="Early",s[s.Default=0]="Default",s[s.Late=100]="Late",s))(ei||{});class d0{constructor(t){r(this,"_eventListeners",{});r(this,"_doubleClickTimeThreshold",.2);r(this,"_longPressTimeThreshold",1);r(this,"_setCursorTypes",[]);r(this,"context");r(this,"_pointerDown",[!1]);r(this,"_pointerUp",[!1]);r(this,"_pointerClick",[!1]);r(this,"_pointerDoubleClick",[!1]);r(this,"_pointerPressed",[!1]);r(this,"_pointerPositions",[new h.Vector2]);r(this,"_pointerPositionsLastFrame",[new h.Vector2]);r(this,"_pointerPositionsDelta",[new h.Vector2]);r(this,"_pointerPositionsRC",[new h.Vector2]);r(this,"_pointerPositionDown",[new h.Vector3]);r(this,"_pointerDownTime",[]);r(this,"_pointerUpTime",[]);r(this,"_pointerUpTimestamp",[]);r(this,"_pointerIds",[]);r(this,"_pointerTypes",[""]);r(this,"_mouseWheelChanged",[!1]);r(this,"_mouseWheelDeltaY",[0]);r(this,"_pointerEvent",[]);r(this,"_pointerEventsPressed",[]);r(this,"_pointerSpace",[]);r(this,"_pressedStack",new Map);r(this,"_htmlEventSource");r(this,"onLostFocus",()=>{for(const t in this.keysPressed)this.keysPressed[t].pressed=!1});r(this,"_receivedPointerMoveEventsThisFrame",new Array);r(this,"onEndOfFrame",()=>{this._receivedPointerMoveEventsThisFrame.length=0;for(let t=0;t<this._pointerUp.length;t++)this._pointerUp[t]=!1;for(let t=0;t<this._pointerDown.length;t++)this._pointerDown[t]=!1;for(let t=0;t<this._pointerClick.length;t++)this._pointerClick[t]=!1;for(let t=0;t<this._pointerDoubleClick.length;t++)this._pointerDoubleClick[t]=!1;for(const t of this._pointerPositionsDelta)t.set(0,0);for(let t=0;t<this._mouseWheelChanged.length;t++)this._mouseWheelChanged[t]=!1;for(let t=0;t<this._mouseWheelDeltaY.length;t++)this._mouseWheelDeltaY[t]=0});r(this,"onContextMenu",t=>{this.canReceiveInput(t)!==!1&&t instanceof PointerEvent&&t.pointerType});r(this,"keysPressed",{});r(this,"onKeyDown",t=>{if(Je&&console.log(`key down ${t.code}, ${this.context.application.hasFocus}`,t),!this.context.application.hasFocus)return;const e=this.keysPressed[t.code];if(e&&e.pressed)return;this.keysPressed[t.code]={pressed:!0,frame:this.context.time.frameCount+1,startFrame:this.context.time.frameCount+1,key:t.key,code:t.code};const i=new Il("keydown",t,t);this.onDispatchEvent(i)});r(this,"onKeyPressed",t=>{if(!this.context.application.hasFocus)return;const e=this.keysPressed[t.code];if(!e)return;e.pressed=!0,e.frame=this.context.time.frameCount+1;const i=new Il("keypress",t,t);this.onDispatchEvent(i)});r(this,"onKeyUp",t=>{if(!this.context.application.hasFocus)return;const e=this.keysPressed[t.code];if(!e)return;e.pressed=!1,e.frame=this.context.time.frameCount+1;const i=new Il("keyup",t,t);this.onDispatchEvent(i)});r(this,"onWheelWindow",t=>{document.pointerLockElement&&this.onMouseWheel(t)});r(this,"onMouseWheel",t=>{if(this.canReceiveInput(t)===!1)return;this._mouseWheelDeltaY.length<=0&&this._mouseWheelDeltaY.push(0),this._mouseWheelChanged.length<=0&&this._mouseWheelChanged.push(!1),this._mouseWheelChanged[0]=!0;const e=this._mouseWheelDeltaY[0];this._mouseWheelDeltaY[0]=e+t.deltaY});r(this,"onPointerDown",t=>{if(this.context.isInAR||this.canReceiveInput(t)===!1)return;t.target instanceof HTMLElement&&t.target.setPointerCapture(t.pointerId);const e=this.getPointerId(t);Je&&Te(`pointer down #${e}, identifier:${t.pointerId}`);const i=this.getAndUpdateSpatialObjectForScreenPosition(e,t.clientX,t.clientY),n=new ss("pointerdown",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:e,button:t.button,clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,buttonName:this.getButtonName(t),device:i,pressure:t.pressure});this.onDown(n)});r(this,"onPointerMove",t=>{if(this.context.isInAR||this._receivedPointerMoveEventsThisFrame.includes(t.pointerId))return;this._receivedPointerMoveEventsThisFrame.push(t.pointerId);let e=t.button;t.pointerType==="mouse"&&(e=this.getFirstPressedButtonForPointer(0)??0);const i=this.getPointerId(t,e);e===-1&&(e=i);const n=this.getAndUpdateSpatialObjectForScreenPosition(i,t.clientX,t.clientY),o=new ss("pointermove",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:i,button:e,clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,buttonName:this.getButtonName(t),device:n,pressure:t.pressure});this.onMove(o)});r(this,"onPointerCancel",t=>{this.context.isInAR||(Je&&console.log("Pointer cancel",t),this.onPointerUp(t))});r(this,"onPointerUp",t=>{if(this.context.isInAR)return;t.target instanceof HTMLElement&&t.target.releasePointerCapture(t.pointerId);const e=this.getPointerId(t),i=new ss("pointerup",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:e,button:t.button,clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,buttonName:this.getButtonName(t),device:this.getAndUpdateSpatialObjectForScreenPosition(e,t.clientX,t.clientY),pressure:t.pressure});this.onUp(i),this._pointerIds[e]=-1,Je&&console.log("ID="+e,"PointerId="+t.pointerId,"ALL:",[...this._pointerIds])});r(this,"onTouchStart",t=>{if(this.context.isInAR)for(let e=0;e<t.changedTouches.length;e++){const i=t.changedTouches[e],n=this.getPointerIndex(i.identifier),o=this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),a=new ss("pointerdown",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:0,clientX:i.clientX,clientY:i.clientY,pointerType:"touch",buttonName:"unknown",device:o,pressure:i.force});this.onDown(a)}});r(this,"onTouchMove",t=>{if(this.context.isInAR)for(let e=0;e<t.changedTouches.length;e++){const i=t.changedTouches[e],n=this.getPointerIndex(i.identifier),o=this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),a=new ss("pointermove",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:0,clientX:i.clientX,clientY:i.clientY,pointerType:"touch",buttonName:"unknown",device:o,pressure:i.force});this.onMove(a)}});r(this,"onTouchEnd",t=>{if(this.context.isInAR)for(let e=0;e<t.changedTouches.length;e++){const i=t.changedTouches[e],n=this.getPointerIndex(i.identifier),o=new ss("pointerup",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:0,clientX:i.clientX,clientY:i.clientY,pointerType:"touch",buttonName:"unknown",device:this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),pressure:i.force});this.onUp(o),this._pointerIds[n]=-1}});r(this,"tempNearPlaneVector",new h.Vector3);r(this,"tempFarPlaneVector",new h.Vector3);r(this,"tempLookMatrix",new h.Matrix4);this.context=t,this.context.post_render_callbacks.push(this.onEndOfFrame)}addEventListener(t,e,i){if(this._eventListeners[t]||(this._eventListeners[t]=[]),!e||typeof e!="function"){console.error("Invalid call to addEventListener: callback is required and must be a function!");return}i?i={...i}:i={};let n=0;(i==null?void 0:i.queue)!=null&&(n=i.queue);const o=this._eventListeners[t],a=o.find(l=>l.priority===n);a?a.listeners.push({callback:e,options:i}):(o.push({priority:n,listeners:[{callback:e,options:i}]}),o.sort((l,c)=>l.priority-c.priority))}removeEventListener(t,e,i){if(!this._eventListeners[t]||!e)return;const n=this._eventListeners[t];if((i==null?void 0:i.queue)!=null){const o=n.find(l=>l.priority===i.queue);if(!o)return;const a=o.listeners.findIndex(l=>l.callback===e);a>=0&&o.listeners.splice(a,1)}else for(const o of n){const a=o.listeners.findIndex(l=>l.callback===e);a>=0&&o.listeners.splice(a,1)}}dispatchEvent(t){var i,n,o,a;let e=!1;if(t instanceof Il){const l=this._eventListeners[t.type];if(l)for(const c of l)for(let d=0;d<c.listeners.length;d++){const u=c.listeners[d];if((n=(i=u.options)==null?void 0:i.signal)!=null&&n.aborted){c.listeners.splice(d,1),d--;continue}u.options.once&&(c.listeners.splice(d,1),d--),u.callback(t)}}if(t instanceof ss){const l=this._eventListeners[t.type];if(l)for(const c of l){if(e)break;for(let d=0;d<c.listeners.length;d++){const u=c.listeners[d];if((a=(o=u.options)==null?void 0:o.signal)!=null&&a.aborted){c.listeners.splice(d,1),d--;continue}if(t.immediatePropagationStopped){e=!0,Je&&console.log("immediatePropagationStopped",t.type);break}else t.propagationStopped&&(e=!0,Je&&console.log("propagationStopped",t.type));u.options.once&&(c.listeners.splice(d,1),d--),u.callback(t)}}}}get mousePosition(){return this._pointerPositions[0]}get mousePositionRC(){return this._pointerPositionsRC[0]}get mouseDown(){return this._pointerDown[0]}get mouseUp(){return this._pointerUp[0]}get mouseClick(){return this._pointerClick[0]}get mouseDoubleClick(){return this._pointerDoubleClick[0]}get mousePressed(){return this._pointerPressed[0]}get mouseWheelChanged(){return this.getMouseWheelChanged(0)}get click(){return this._pointerClick[0]}get doubleClick(){return this._pointerDoubleClick[0]}getGamepad(t=0){return typeof navigator<"u"&&"getGamepads"in navigator&&navigator.getGamepads()[t]||null}setCursorPointer(){this.setCursor("pointer")}setCursorNormal(){this.unsetCursor("pointer")}setCursor(t){this._setCursorTypes.push(t),this._setCursorTypes.length>10&&this._setCursorTypes.shift(),this.updateCursor()}unsetCursor(t){for(let e=this._setCursorTypes.length-1;e>=0;e--)if(this._setCursorTypes[e]===t){this._setCursorTypes.splice(e,1),this.updateCursor();break}}updateCursor(){var t;((t=this._setCursorTypes)==null?void 0:t.length)==0?this.context.domElement.style.cursor="default":this.context.domElement.style.cursor=this._setCursorTypes[this._setCursorTypes.length-1]}getIsPointerIdInUse(t){for(const e of this._pointerEventsPressed)if(e.pointerId===t&&e.used)return!0;return!1}getPointerPressedCount(){let t=0;for(let e=0;e<this._pointerPressed.length;e++)this._pointerPressed[e]&&t++;return t}getPointerPosition(t){return t>=this._pointerPositions.length?null:this._pointerPositions[t]}getPointerPositionLastFrame(t){return t>=this._pointerPositionsLastFrame.length?null:this._pointerPositionsLastFrame[t]}getPointerPositionDelta(t){return t>=this._pointerPositionsDelta.length?null:this._pointerPositionsDelta[t]}getPointerPositionRC(t){return t>=this._pointerPositionsRC.length?null:this._pointerPositionsRC[t]}getPointerDown(t){return t>=this._pointerDown.length?!1:this._pointerDown[t]}getPointerUp(t){return t>=this._pointerUp.length?!1:this._pointerUp[t]}getPointerPressed(t){return t>=this._pointerPressed.length?!1:this._pointerPressed[t]}getPointerClicked(t){return t>=this._pointerClick.length?!1:this._pointerClick[t]}getPointerDoubleClicked(t){return t>=this._pointerDoubleClick.length?!1:this._pointerDoubleClick[t]}getPointerDownTime(t){return t>=this._pointerDownTime.length?-1:this._pointerDownTime[t]}getPointerUpTime(t){return t>=this._pointerUpTime.length?-1:this._pointerUpTime[t]}getPointerLongPress(t){return t>=this._pointerDownTime.length?!1:this.getPointerPressed(t)&&this.context.time.time-this._pointerDownTime[t]>this._longPressTimeThreshold}getIsMouse(t){return t<0||t>=this._pointerTypes.length?!1:this._pointerTypes[t]==="mouse"}getIsTouch(t){return t<0||t>=this._pointerTypes.length?!1:this._pointerTypes[t]==="touch"}getTouchesPressedCount(){let t=0;for(let e=0;e<this._pointerPressed.length;e++)this._pointerPressed[e]&&this.getIsTouch(e)&&t++;return t}getMouseWheelChanged(t=0){return t>=this._mouseWheelChanged.length?!1:this._mouseWheelChanged[t]}getMouseWheelDeltaY(t=0){return t>=this._mouseWheelDeltaY.length?0:this._mouseWheelDeltaY[t]}getPointerEvent(t){if(!(t>=this._pointerEvent.length))return this._pointerEvent[t]??void 0}*foreachPointerId(t){for(let e=0;e<this._pointerTypes.length;e++)if(this._pointerIsActive(e)){if(t!==void 0){const i=this._pointerTypes[e];if(Array.isArray(t)){let n=!1;for(const o of t)if(i===o){n=!0;break}if(!n)continue}else if(t!==i)continue}yield e}}*foreachTouchId(){for(let t=0;t<this._pointerTypes.length;t++)this._pointerTypes[t]==="touch"&&this._pointerIsActive[t]&&(yield t)}_pointerIsActive(t){return t<0?!1:this._pointerPressed[t]||this._pointerDown[t]||this._pointerUp[t]}onDownButton(t,e){let i=this._pressedStack.get(t);i||(i=[],this._pressedStack.set(t,i)),i.push(e)}onReleaseButton(t,e){const i=this._pressedStack.get(t);if(!i)return;const n=i.indexOf(e);n>=0&&i.splice(n,1)}getFirstPressedButtonForPointer(t){const e=this._pressedStack.get(t);if(e)return e[0]}getLatestPressedButtonForPointer(t){const e=this._pressedStack.get(t);if(e)return e[e.length-1]}getKeyDown(t){if(t!==void 0)return this.isKeyDown(t);for(const e in this.keysPressed){const i=this.keysPressed[e];if(i.startFrame===this.context.time.frameCount)return i.key}return null}getKeyPressed(t){if(t!==void 0)return this.isKeyPressed(t);for(const e in this.keysPressed){const i=this.keysPressed[e];if(i.pressed)return i.key}return null}getKeyUp(t){if(t!==void 0)return this.isKeyUp(t);for(const e in this.keysPressed){const i=this.keysPressed[e];return i.pressed===!1&&i.frame===this.context.time.frameCount}return null}isKeyDown(t){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const e=this.getCodeForCommonKeyName(t);if(e!==null){for(const n of e)if(this.isKeyDown(n))return!0;return!1}const i=this.keysPressed[t];return i?i.startFrame===this.context.time.frameCount&&i.pressed:!1}isKeyUp(t){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const e=this.getCodeForCommonKeyName(t);if(e!==null){for(const n of e)if(this.isKeyUp(n))return!0;return!1}const i=this.keysPressed[t];return i?i.frame===this.context.time.frameCount&&i.pressed===!1:!1}isKeyPressed(t){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const e=this.getCodeForCommonKeyName(t);if(e!==null){for(const n of e)if(this.isKeyPressed(n))return!0;return!1}const i=this.keysPressed[t];return i&&i.pressed||!1}getCodeForCommonKeyName(t){if(t.length===1){if(t>="0"&&t<="9")return["Digit"+t];if(t>="a"&&t<="z")return["Key"+t.toUpperCase()];if(t==" ")return["Space"]}switch(t){case"shift":case"Shift":return["ShiftLeft","ShiftRight"];case"control":case"Control":return["ControlLeft","ControlRight"];case"alt":case"Alt":return["AltLeft","AltRight"]}return null}createInputEvent(t){switch(t.type){case"pointerdown":Je&&Te("Create Pointer down"),this.onDownButton(t.deviceIndex,t.button),this.onDown(t);break;case"pointermove":Je&&Te("Create Pointer move"),this.onMove(t);break;case"pointerup":Je&&Te("Create Pointer up"),this.onUp(t),this.onReleaseButton(t.deviceIndex,t.button);break}}convertScreenspaceToRaycastSpace(t){return t.x=(t.x-this.context.domX)/this.context.domWidth*2-1,t.y=-((t.y-this.context.domY)/this.context.domHeight)*2+1,t}bindEvents(){this.unbindEvents(),this._htmlEventSource=this.context.renderer.domElement,window.addEventListener("contextmenu",this.onContextMenu),this._htmlEventSource.addEventListener("pointerdown",this.onPointerDown,{passive:!0}),window.addEventListener("pointermove",this.onPointerMove,{passive:!0,capture:!0}),window.addEventListener("pointerup",this.onPointerUp,{passive:!0}),window.addEventListener("pointercancel",this.onPointerCancel,{passive:!0}),window.addEventListener("touchstart",this.onTouchStart,{passive:!0}),window.addEventListener("touchmove",this.onTouchMove,{passive:!0}),window.addEventListener("touchend",this.onTouchEnd,{passive:!0}),this._htmlEventSource.addEventListener("wheel",this.onMouseWheel,{passive:!0}),window.addEventListener("wheel",this.onWheelWindow,{passive:!0}),window.addEventListener("keydown",this.onKeyDown,!1),window.addEventListener("keypress",this.onKeyPressed,!1),window.addEventListener("keyup",this.onKeyUp,!1),window.addEventListener("blur",this.onLostFocus)}unbindEvents(){var t,e;window.removeEventListener("contextmenu",this.onContextMenu),(t=this._htmlEventSource)==null||t.removeEventListener("pointerdown",this.onPointerDown),window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),window.removeEventListener("pointercancel",this.onPointerCancel),window.removeEventListener("touchstart",this.onTouchStart),window.removeEventListener("touchmove",this.onTouchMove),window.removeEventListener("touchend",this.onTouchEnd),(e=this._htmlEventSource)==null||e.removeEventListener("wheel",this.onMouseWheel,!1),window.removeEventListener("wheel",this.onWheelWindow,!1),window.removeEventListener("keydown",this.onKeyDown,!1),window.removeEventListener("keypress",this.onKeyPressed,!1),window.removeEventListener("keyup",this.onKeyUp,!1),window.removeEventListener("blur",this.onLostFocus)}dispose(){const t=this.context.post_render_callbacks.indexOf(this.onEndOfFrame);t>=0&&this.context.post_render_callbacks.splice(t,1),this.unbindEvents()}canReceiveInput(t){var e;return t.target===((e=this.context.renderer)==null?void 0:e.domElement)||t.target===this.context.domElement||this.context.isInAR||this.context.isInAR&&t.target===document.body&&exports.DeviceUtilities.isMozillaXR()?!0:(Je&&console.warn("CanReceiveInput:False for",t.target),!1)}getPointerId(t,e){return t.pointerType==="mouse"?0+(e??t.button):this.getPointerIndex(t.pointerId)}getButtonName(t){const e=t.button;if(t.pointerType==="mouse")switch(e){case 0:return"left";case 1:return"middle";case 2:return"right"}return"unknown"}getAndUpdateSpatialObjectForScreenPosition(t,e,i){let n=this._pointerSpace[t];n||(n=new h.Object3D,this._pointerSpace[t]=n),this._pointerSpace[t]=n;const o=this.context.mainCamera;if(o){const a=this.tempNearPlaneVector.set(e,i,-1);this.convertScreenspaceToRaycastSpace(a);const l=this.tempFarPlaneVector.set(a.x,a.y,1);a.unproject(o),l.unproject(o);const c=o.worldUp||$(0,1,0).applyQuaternion(ye(o));this.tempLookMatrix.lookAt(l,a,c),n.position.set(a.x,a.y,a.z),n.quaternion.setFromRotationMatrix(this.tempLookMatrix)}return n}isInRect(t){if(this.context.isInXR)return!0;const e=this.context.domElement.getBoundingClientRect(),i=t.clientX,n=t.clientY,o=i>=e.x&&i<=e.right&&n>=e.y&&n<=e.bottom;return Je&&!o&&console.log("Not in rect",e,i,n),o}onDown(t){const e=t.pointerId;if(this.getPointerPressed(e)&&console.warn(`Received pointerDown for pointerId that is already pressed: ${e}`,Je?t:""),Je&&console.log(t.pointerType,"DOWN",e),!!this.isInRect(t)){for(this.setPointerState(e,this._pointerPressed,!0),this.setPointerState(e,this._pointerDown,!0),this.setPointerStateT(e,this._pointerEvent,t.source);e>=this._pointerTypes.length;)this._pointerTypes.push(t.pointerType);for(this._pointerTypes[e]=t.pointerType;e>=this._pointerPositionDown.length;)this._pointerPositionDown.push(new h.Vector3);for(this._pointerPositionDown[e].set(t.clientX,t.clientY,t.clientZ??0);e>=this._pointerPositions.length;)this._pointerPositions.push(new h.Vector2);this._pointerPositions[e].set(t.clientX,t.clientY),e>=this._pointerDownTime.length&&this._pointerDownTime.push(0),this._pointerDownTime[e]=this.context.time.realtimeSinceStartup,this.updatePointerPosition(t),this._pointerEventsPressed.push(t),this.onDispatchEvent(t)}}onMove(t){const e=t.pointerId,i=this.getPointerPressed(e);i===!1&&!this.isInRect(t)||t.pointerType==="touch"&&!i||(this.updatePointerPosition(t),this.setPointerStateT(e,this._pointerEvent,t.source),this.onDispatchEvent(t))}onUp(t){const e=t.pointerId;if(!this.getPointerPressed(e)){Je&&console.log(t.pointerType,"UP",e,"was not down");return}Je&&console.log(t.pointerType,"UP",e),this.setPointerState(e,this._pointerPressed,!1),this.setPointerStateT(e,this._pointerEvent,t.source),this.setPointerState(e,this._pointerUp,!0),this.updatePointerPosition(t);for(let c=this._pointerEventsPressed.length-1;c>=0;c--)if(this._pointerEventsPressed[c].pointerId===e){this._pointerEventsPressed.splice(c,1);break}if(!this._pointerPositionDown[e]){Je&&pe("Received pointer up event without matching down event for button: "+e),console.warn("Received pointer up event without matching down event for button: "+e);return}const n=this._pointerUpTime[e],o=this._pointerDownTime[e],a=this.context.time.realtimeSinceStartup,l=a-o;if(e>=this._pointerUpTime.length&&this._pointerUpTime.push(-99),this._pointerUpTime[e]=a,l<1){let c=t.clientX-this._pointerPositionDown[e].x,d=t.clientY-this._pointerPositionDown[e].y,u=0;if(t.isSpatial&&t.clientZ!=null&&(u=t.clientZ-this._pointerPositionDown[e].z,c*=200,d*=200,u*=200),Math.abs(c)<5&&Math.abs(d)<5&&Math.abs(u)<5){this.setPointerState(e,this._pointerClick,!0),t.isClick=!0;const f=a-n;Je&&console.log("CLICK",e,c,d,u,f),f<this._doubleClickTimeThreshold&&f>0&&(this.setPointerState(e,this._pointerDoubleClick,!0),t.isDoubleClick=!0)}}this.onDispatchEvent(t)}updatePointerPosition(t){const e=t.pointerId;for(;e>=this._pointerPositions.length;)this._pointerPositions.push(new h.Vector2);for(;e>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new h.Vector2);for(;e>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new h.Vector2);const i=this._pointerPositionsLastFrame[e];i.copy(this._pointerPositions[e]);const n=this._pointerPositionsDelta[e];let o=t.clientX-i.x,a=t.clientY-i.y;if(t.source instanceof MouseEvent||t.source instanceof TouchEvent){const u=t.source;o===0&&u.movementX!==0&&(o=u.movementX||0),a===0&&u.movementY!==0&&(a=u.movementY||0)}n.x+=o,n.y+=a,this._pointerPositions[e].x=t.clientX,this._pointerPositions[e].y=t.clientY;const l=t.clientX,c=t.clientY;for(;e>=this._pointerPositionsRC.length;)this._pointerPositionsRC.push(new h.Vector2);const d=this._pointerPositionsRC[e];d.set(l,c),this.convertScreenspaceToRaycastSpace(d)}getPointerIndex(t){let e=-1;for(let i=0;i<this._pointerIds.length;i++){if(this._pointerIds[i]===t)return i;e===-1&&this._pointerIds[i]===-1&&(e=i)}return e!==-1?(this._pointerIds[e]=t,e):(Je&&console.log("PUSH pointerId:",t),this._pointerIds.push(t),this._pointerIds.length-1)}setPointerState(t,e,i){e[t]=i}setPointerStateT(t,e,i){return e[t]=i,i}onDispatchEvent(t){const e=Q.Current;try{Q.Current=this.context,this.dispatchEvent(t)}finally{Q.Current=e}}}const ya=new h.Matrix4().makeRotationY(Math.PI),Bi=new h.Quaternion().setFromAxisAngle(new h.Vector3(0,1,0),Math.PI),DS=x("debugwebxr");class LS{constructor(){r(this,"priority",-1e5);r(this,"gameObject");if(this.gameObject=new h.Object3D,this.gameObject.name="Implicit XR Rig",DS){const t=Ym(16733661);t.position.y+=.5,this.gameObject.add(t)}}isXRRig(){return!0}get isActive(){return this.gameObject.visible}}const Qn=x("debugwebxr"),Dh=x("debugcustomgesture"),IS="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",jS="generic-trigger",BS=new h.Quaternion().setFromEuler(new h.Euler(h.MathUtils.degToRad(0),h.MathUtils.degToRad(-90),h.MathUtils.degToRad(-90))),FS=new h.Vector3(.04,-.04,0);class Wm{constructor(t,e,i){r(this,"xr");r(this,"inputSource");r(this,"index",0);r(this,"emitEvents",!0);r(this,"_connected",!0);r(this,"_isTracking",!1);r(this,"__gamepad");r(this,"__hand");r(this,"__side");r(this,"_hitTestSource");r(this,"_hasSelectEvent",!1);r(this,"_isMxInk",!1);r(this,"_isMetaQuestTouchController",!1);r(this,"_handJointPoses",new Map);r(this,"_gripMatrix",new h.Matrix4);r(this,"_gripPosition",new h.Vector3);r(this,"_gripQuaternion",new h.Quaternion);r(this,"_linearVelocity",new h.Vector3);r(this,"_rayPositionRaw",new h.Vector3);r(this,"_rayRotationRaw",new h.Quaternion);r(this,"_rayMatrix",new h.Matrix4);r(this,"_rayPosition",new h.Vector3);r(this,"_rayQuaternion",new h.Quaternion);r(this,"_gripWorldPosition",new h.Vector3);r(this,"_gripWorldQuaternion",new h.Quaternion);r(this,"_rayWorldPosition",new h.Vector3);r(this,"_rayWorldQuaternion",new h.Quaternion);r(this,"_pinchPosition",new h.Vector3);r(this,"_ray");r(this,"_hand_wristDotUp");r(this,"_object");r(this,"_gripSpaceObject");r(this,"_raySpaceObject");r(this,"model",null);r(this,"_debugAxesHelper",new h.AxesHelper(.15));r(this,"_debugGripAxesHelper",new h.AxesHelper(.07));r(this,"_debugRayAxesHelper",new h.AxesHelper(.07));r(this,"_hitTestSourcePromise",null);r(this,"onPointerHits",t=>{});r(this,"_needleGamepadButtons",{});r(this,"_buttonMap",new Map);r(this,"_motioncontroller");r(this,"_layout");r(this,"getMotionController");r(this,"emitPointerDownEvent",!0);r(this,"emitPointerUpEvent",!0);r(this,"emitPointerMoveEvent",!0);r(this,"pointerMoveDistanceThreshold",.03);r(this,"pointerMoveAngleThreshold",.05);r(this,"_selectButtonIndex");r(this,"_squeezeButtonIndex");r(this,"onSelectStart",t=>{var n,o,a,l;if(!this.emitPointerDownEvent||this.inputSource!==t.inputSource)return;this.onUpdateFrame(t.frame),this._hasSelectEvent=!0;const e=(n=this._layout)==null?void 0:n.selectComponentId,i=(l=(a=(o=this._layout)==null?void 0:o.components[e])==null?void 0:a.gamepadIndices)==null?void 0:l.button;i!==void 0&&(this._selectButtonIndex=i),!Dh&&(Qn&&N.DrawDirection(this.rayWorldPosition,$(0,.01,1).applyQuaternion(this.rayWorldQuaternion),16711680,10),this.emitPointerEvent(Ee.PointerDown,this._selectButtonIndex||0,"xr-standard-trigger",!0,t))});r(this,"onSelectEnd",t=>{this.emitPointerUpEvent&&(Dh||this.inputSource===t.inputSource&&this.emitPointerEvent(Ee.PointerUp,this._selectButtonIndex||0,"xr-standard-trigger",!0,t))});r(this,"onSequeezeStart",t=>{var e,i,n;this.emitPointerDownEvent&&this.inputSource===t.inputSource&&(this._squeezeButtonIndex=(n=(i=(e=this._layout)==null?void 0:e.components["xr-standard-squeeze"])==null?void 0:i.gamepadIndices)==null?void 0:n.button,this._squeezeButtonIndex!==void 0&&(Qn&&N.DrawDirection(this.rayWorldPosition,$(0,.01,1).applyQuaternion(this.rayWorldQuaternion),255,10),this.emitPointerEvent(Ee.PointerDown,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,t)))});r(this,"onSequeezeEnd",t=>{this.emitPointerUpEvent&&this.inputSource===t.inputSource&&this._squeezeButtonIndex!==void 0&&this.emitPointerEvent(Ee.PointerUp,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,t)});r(this,"states",{});r(this,"_didMoveLastFrame",!1);r(this,"_lastPointerMovePosition",new h.Vector3);r(this,"_lastPointerMoveQuaternion",new h.Quaternion);r(this,"pointerInit");this.xr=t,this.inputSource=e,this.index=i,this._object=new h.Object3D,this._object.name=`NeedleXRController_${i}`,Qn&&(this._object.add(this._debugAxesHelper),this._gripSpaceObject=new h.Object3D,this._raySpaceObject=new h.Object3D,this._gripSpaceObject.name=`NeedleXRController_${i}_gripSpace`,this._raySpaceObject.name=`NeedleXRController_${i}_raySpace`,this._gripSpaceObject.add(this._debugGripAxesHelper),this._raySpaceObject.add(this._debugRayAxesHelper),this.xr.context.scene.add(this._gripSpaceObject),this.xr.context.scene.add(this._raySpaceObject)),this.xr.context.scene.add(this._object),this._ray=new h.Ray,this.pointerInit={origin:this,pointerType:this.hand?"hand":"controller",deviceIndex:this.index,pointerId:-1,mode:this.inputSource.targetRayMode,ray:this._ray,device:this._object,buttonName:"none"},this.initialize(),this.subscribeEvents()}get context(){return this.xr.context}get connected(){return this._connected}get isTracking(){return this._isTracking}get gamepad(){return this.__gamepad??(this.__gamepad=this.inputSource.gamepad)}get isHand(){return this.hand!=null}get hand(){return this.__hand??(this.__hand=this.inputSource.hand)}get handObject(){return this.context.renderer.xr.getHand(this.index)}get profiles(){return this.inputSource.profiles}get layout(){return this._layout}get targetRayMode(){return this.inputSource.targetRayMode}get targetRaySpace(){return this.inputSource.targetRaySpace}get gripSpace(){return this.inputSource.gripSpace}get side(){return this.__side??(this.__side=this.inputSource.handedness)}get isRight(){return this.side==="right"}get isLeft(){return this.side==="left"}get isStylus(){return this._isMxInk}getHitTestSource(){return this._hitTestSource||this._requestHitTestSource(),this._hitTestSource}get hasHitTestSource(){return this._hitTestSource}cancelHitTestSource(){this._hitTestSource&&(this._hitTestSource.cancel(),this._hitTestSource=void 0)}get hasSelectEvent(){return this._hasSelectEvent}getHitTest(){return this.xr.getHitTest(this)}getHandJointPose(t,e){var n;if(e=e||this.xr.frame,!this.hand||!(e!=null&&e.getJointPose)||!this.xr.referenceSpace)return null;let i=(n=this._handJointPoses)==null?void 0:n.get(t);return i||(i=e.getJointPose(t,this.xr.referenceSpace),i&&this._handJointPoses.set(t,i),i)}get gripPosition(){return $(this._gripPosition)}get gripQuaternion(){return an(this._gripQuaternion)}get gripMatrix(){return this._gripMatrix}get gripLinearVelocity(){return $(this._linearVelocity).applyQuaternion(Bi)}get rayPosition(){return $(this._rayPosition)}get rayQuaternion(){return an(this._rayQuaternion)}get gripWorldPosition(){return $(this._gripWorldPosition)}get gripWorldQuaternion(){return an(this._gripWorldQuaternion)}get rayWorldPosition(){return $(this._rayWorldPosition)}updateRayWorldPosition(){var e;const t=(e=this.xr.context.mainCamera)==null?void 0:e.parent;this._rayWorldPosition.copy(this._rayPositionRaw),t&&this._rayWorldPosition.applyMatrix4(t.matrixWorld)}get rayWorldQuaternion(){return an(this._rayWorldQuaternion)}get pinchPosition(){return $(this._pinchPosition)}updateRayWorldQuaternion(){var i;const t=(i=this.xr.context.mainCamera)==null?void 0:i.parent,e=t?ye(t):void 0;this._rayWorldQuaternion.copy(this._rayRotationRaw).multiply(Bi),e&&this._rayWorldQuaternion.premultiply(e)}get ray(){return this._ray.origin.copy(this.rayWorldPosition),this._ray.direction.copy($(0,0,1).applyQuaternion(this.rayWorldQuaternion)),this._ray}get handWristDotUp(){var e;if(this._hand_wristDotUp!==void 0)return this._hand_wristDotUp;const t=(e=this.handObject)==null?void 0:e.joints.wrist;if(t){const i=$(0,1,0).applyQuaternion(t.quaternion),n=$(0,1,0).dot(i);return this._hand_wristDotUp=n}}get isHandUpsideDown(){return this.handWristDotUp!==void 0?this.handWristDotUp<-.7:!1}get isTeleportGesture(){var t;return this.isHandUpsideDown&&((t=this.getGesture("pinch"))==null?void 0:t.isDown)}get object(){return this._object}async getModelUrl(){var t;return(t=this.getMotionController)==null?void 0:t.then(e=>(e==null?void 0:e.assetUrl)||null)}_requestHitTestSource(){var t;return this._hitTestSourcePromise?this._hitTestSourcePromise:this.xr.mode==="immersive-ar"&&this.inputSource.targetRayMode==="tracked-pointer"&&this.xr.session.requestHitTestSourceForTransientInput?this._hitTestSourcePromise=((t=this.xr.session.requestHitTestSourceForTransientInput({profile:this.inputSource.profiles[0],offsetRay:new XRRay}))==null?void 0:t.then(e=>(this._hitTestSourcePromise=null,this.connected?this._hitTestSource=e:(e.cancel(),null))))??null:null}onUpdate(t){this.onUpdateFrame(t),this.updateInputEvents(),this.onUpdateMove()}onRenderDebug(){var o;N.DrawSphere(this.rayWorldPosition,.003),N.DrawDirection(this.rayWorldPosition,$(0,0,10).applyQuaternion(this.rayWorldQuaternion));const e=(this.inputSource.gripSpace?this.gripWorldPosition:this.object.worldPosition).sub(this.object.worldForward.multiplyScalar(.1)),i=this.inputSource.profiles.join(`
135
135
  `);let n=`Controller[${this.index}] (${this.inputSource.targetRayMode}, ${this.side})
136
136
  C:${this.connected?"x":"-"} T:${this.isTracking?"x":"-"} Hand:${this.inputSource.hand?"x":"-"} Pen: ${this._isMxInk?"x":"-"}`;if(this.inputSource.hand&&(n+=`
@@ -929,10 +929,10 @@ Using the assigned clip instead:`,this.clip),t=this.clip);let e=!this.sound||t&&
929
929
  Audio:`,a.getAudioTracks(),`
930
930
  Video:`,a.getVideoTracks()),this._stream=a,n==="incoming"){const l=new zv(e,a,this);this.dispatchEvent(l)}}),i.on("close",()=>{this.dispatchEvent(new gg(e,n))})}get stream(){return this._stream}close(){this._isDisposed||(this._isDisposed=!0,this.call.close(),Ln(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 I_(s){return s=s.replace("a=fmtp:111 minptime=10;useinbandfec=1","a=fmtp:111 ptime=5;useinbandfec=1;stereo=1;maxplaybackrate=48000;maxaveragebitrat=128000;sprop-stereo=1"),s}const fa=class extends h.EventDispatcher{constructor(e,i){super();r(this,"updateCalls",()=>{var e;for(let i=this._incomingCalls.length-1;i>=0;i--){const n=this._incomingCalls[i];n.isClosed&&!n.isOpening&&this._incomingCalls.splice(i,1)}for(let i=this._outgoingCalls.length-1;i>=0;i--){const n=this._outgoingCalls[i];let o=!1;n.isClosed&&!n.isOpening&&((e=n.stream)!=null&&e.active?Ge&&console.warn("!!! Stream is still active, don't remove call",n.userId,"Your id: "+this.context.connection.connectionId):(Ge&&console.warn("!!! Remove closed call",n.userId),o=!0)),this.context.connection.userIsInRoom(n.userId)===!1&&(Ge&&console.warn("!!! User is not in room anymore, remove call",n.userId),o=!0),o&&(n.close(),this._outgoingCalls.splice(i,1))}});r(this,"id");r(this,"context");r(this,"_incomingCalls",[]);r(this,"_outgoingCalls",[]);r(this,"_peer");r(this,"_enabled",!1);r(this,"_enabledPeer",!1);r(this,"onConnectRoomFn",this.onConnectRoom.bind(this));r(this,"onPeerConnect",e=>{if(Ge&&console.log("PEER opened as",e),e===null){console.error("Peer connection failed",e);return}this.context.connection.send("peer-user-connected",new LP(this,e))});r(this,"onPeerClose",()=>{Ge&&console.log("PEER closed"),this.updateCalls()});r(this,"onPeerDisconnected",()=>{Ge&&console.log("PEER disconnected"),this.updateCalls()});r(this,"onPeerError",e=>{Ge&&console.error("PEER error",e)});r(this,"onPeerReceivingCall",e=>{e.answer(void 0,{sdpTransform:i=>I_(i)}),this.registerCall(e,"incoming",null)});this.context=e,this.id=i,this.setupPeer(),navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia}static getOrCreate(e,i){if(fa.instances.has(i))return fa.instances.get(i);const n=new fa(e,i);return fa.instances.set(i,n),n}getMyPeerId(){if(this.context.connection.connectionId)return this.getPeerIdFromUserId(this.context.connection.connectionId)}getPeerIdFromUserId(e){return this.id+"-"+e}getUserIdFromPeerId(e){return e.substring(this.id.length+1)}makeCall(e,i){var a;if(!(i!=null&&i.id)){Ge?console.warn("Can not make a call: mediastream has no id or is undefined"):console.debug("Can not make a call: mediastream has no id or is undefined");return}const n={metadata:{userId:this.context.connection.connectionId,streamId:i.id},sdpTransform:l=>I_(l)},o=(a=this._peer)==null?void 0:a.call(e,i,n);if(o){const l=this.registerCall(o,"outgoing",i);return Ge&&console.warn(`📞 CALL ${e}`,`
931
931
  Outgoing:`,this._outgoingCalls,`
932
- Incoming:`,this._incomingCalls),l}else Ge&&console.error("Failed to make call",e,i,this._peer)}closeAll(){for(const e of this._incomingCalls)e.close();for(const e of this._outgoingCalls)e.close();this.updateCalls()}get peer(){return this._peer}get incomingCalls(){return this._incomingCalls}enable(){this._enabled||(this._enabled=!0,this.context.connection.beginListen(J.JoinedRoom,this.onConnectRoomFn),this.subscribePeerEvents())}disable(){this._enabled&&(this._enabled=!1,this.context.connection.stopListen(J.JoinedRoom,this.onConnectRoomFn),this.unsubscribePeerEvents())}onConnectRoom(){this.setupPeer()}setupPeer(){if(this.context.connection.connectionId&&!this._enabledPeer){if(this._enabledPeer=!0,!this._peer){const e=this.getMyPeerId();e?this._peer=m0(e):console.error("Failed to setup peerjs because we dont have a connection id",this.context.connection.connectionId)}this._enabled&&this.subscribePeerEvents()}}subscribePeerEvents(){this._peer&&(this._peer.on("open",this.onPeerConnect),this._peer.on("close",this.onPeerClose),this._peer.on("call",this.onPeerReceivingCall),this._peer.on("disconnected",this.onPeerDisconnected),this._peer.on("error",this.onPeerError))}unsubscribePeerEvents(){this._peer&&(this._peer.off("open",this.onPeerConnect),this._peer.off("close",this.onPeerClose),this._peer.off("call",this.onPeerReceivingCall),this._peer.off("disconnected",this.onPeerDisconnected),this._peer.off("error",this.onPeerError))}registerCall(e,i,n){const o=e.metadata;(!o||!o.userId)&&console.error("Missing call metadata",e);const a=o.userId;i==="incoming"&&Ge?console.warn("← Receive call from",e.metadata,e.connectionId):Ge&&console.warn("→ Make call to",e.metadata);const l=i==="incoming"?this._incomingCalls:this._outgoingCalls,c=new IP(a,e,i,n);return l.push(c),e.on("error",d=>{console.error("Call error",d)}),e.on("close",()=>{Ge&&console.log("Call ended",e.metadata);const d=l.indexOf(c);d!==-1&&l.splice(d,1),c.close(),this.dispatchEvent(new gg(a,i))}),c.addEventListener("call-ended",d=>{this.dispatchEvent(d)}),i==="incoming"&&(c.addEventListener("receive-stream",d=>{this.dispatchEvent(d)}),e.on("stream",()=>{Ge&&console.log("Received stream for call",e.metadata);let d=0;const u=setInterval(()=>{const f=d===0;!c.isOpen&&f&&(Ge&&console.warn("Close call because stream is not active",e.metadata),d+=1,clearInterval(u),c.close())},2e3)})),c}};let ir=fa;r(ir,"instances",new Map);class nh extends h.EventDispatcher{constructor(e,i){super();r(this,"context");r(this,"peer");r(this,"_sendingStreams",new Map);r(this,"debug",!1);r(this,"_enabled",!1);r(this,"_tickIntervalId");r(this,"tick",()=>{this.updateSendingCalls()});r(this,"onJoinedRoom",e=>{this._sendingStreams.size>0&&(this.debug&&console.warn(`${e!=null&&e.userId?`User ${e.userId}`:"You"} joined room`,e,this._sendingStreams.size),this.updateSendingCalls())});r(this,"onLeftRoom",e=>{this.debug&&console.warn(`${(e==null?void 0:e.userId)||"You"} left room`,e),this.stopCallsToUsersThatAreNotInTheRoomAnymore(),this.peer.closeAll()});r(this,"onCallStreamReceived",e=>{this.debug&&console.log("Call with "+e.userId+" started"),this.dispatchEvent({type:"receive-stream",target:this,stream:e.stream,userId:e.userId}),this.debug&&this.debugLogCurrentState()});r(this,"onCallEnded",e=>{this.debug&&console.log("Call with "+e.userId+" ended"),this.dispatchEvent(e),this.debug&&this.debugLogCurrentState()});r(this,"onUserConnected",e=>{if(this.peer.id===e.guid){this.debug&&console.log("PEER USER CONNECTED",e.guid,e,this._sendingStreams.size);const i=this._sendingStreams.keys().next().value;this.peer.makeCall(e.peerId,i)}else Ge&&console.log("Unknown user connected",e.guid,e.peerId)});r(this,"onUserLeft",e=>{this.debug&&console.log("User left room: "+e.userId),this.stopCallsToUsersThatAreNotInTheRoomAnymore()});if(jv(e)){const n=e;e=n.context,i=ir.getOrCreate(n.context,n.guid)}else typeof i=="string"&&(i=ir.getOrCreate(e,i));if(e){if(!(e instanceof Q))throw new Error("Failed to create NetworkedStreams because context is not an instance of Context")}else throw new Error("Failed to create NetworkedStreams because context is undefined");if(!i)throw new Error("Failed to create NetworkedStreams because peer is undefined");this.context=e,this.peer=i,Ge&&(this.debug=!0)}static create(e,i){const n=ir.getOrCreate(e.context,i||e.context.connection.connectionId||e.guid);return new nh(e.context,n)}startSendingStream(e){this._sendingStreams.has(e)?console.warn("Received start sending stream with stream that is already being sent"):(this._sendingStreams.set(e,[]),this.updateSendingCalls())}stopSendingStream(e){if(e){const i=this._sendingStreams.get(e);if(i){for(const n of i)n.close();i.length=0}this._sendingStreams.delete(e),i&&this.debug&&this.debugLogCurrentState()}this.updateSendingCalls()}get enabled(){return this._enabled}enable(){this._enabled||(this._enabled=!0,this.peer.enable(),this.peer.addEventListener("receive-stream",this.onCallStreamReceived),this.peer.addEventListener("call-ended",this.onCallEnded),this.context.connection.beginListen("peer-user-connected",this.onUserConnected),this.context.connection.beginListen(J.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(J.UserJoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(J.UserLeftRoom,this.onUserLeft),this.context.connection.beginListen(J.LeftRoom,this.onLeftRoom),this._tickIntervalId=setInterval(this.tick,5e3))}disable(){this._enabled&&(this._enabled=!1,this.peer.disable(),this.peer.removeEventListener("receive-stream",this.onCallStreamReceived),this.peer.removeEventListener("call-ended",this.onCallEnded),this.context.connection.stopListen("peer-user-connected",this.onUserConnected),this.context.connection.stopListen(J.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(J.UserJoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(J.UserLeftRoom,this.onUserLeft),this.context.connection.stopListen(J.LeftRoom,this.onLeftRoom),this._tickIntervalId!=null&&(clearInterval(this._tickIntervalId),this._tickIntervalId=void 0))}updateSendingCalls(){const e=this.context.connection.connectionId;for(const i of this._sendingStreams.keys()){const n=this._sendingStreams.get(i)||[];for(const o of this.context.connection.usersInRoom()){if(o===e)continue;const a=this.peer.getPeerIdFromUserId(o);if(n.find(c=>{var d;return c.peerId===a&&c.direction==="outgoing"&&!c.isClosed&&((d=c.stream)==null?void 0:d.active)}))Ge&&console.debug("Already have a call with user "+o+" / peer "+a);else{const c=this.peer.makeCall(a,i);c&&n.push(c)}}this._sendingStreams.set(i,n)}this.stopCallsToUsersThatAreNotInTheRoomAnymore()}stopCallsToUsersThatAreNotInTheRoomAnymore(){for(const e of this._sendingStreams.keys()){const i=this._sendingStreams.get(e);if(i)for(let n=i.length-1;n>=0;n--){const o=i[n];this.context.connection.userIsInRoom(o.userId)?Ge&&(this.context.connection.connectionId===o.userId?console.warn(`You are still in the room [${n}] ${o.userId}`):console.log(`User is still in room [${n}] ${o.userId}`)):(Ge&&console.log(`Remove call ${[n]} to user that is not in room anymore ${o.userId}`),o.close(),i.splice(n,1))}}this.peer.updateCalls(),this.debug&&this.debugLogCurrentState()}debugLogCurrentState(){console.warn(`You (${this.context.connection.connectionId}) are currently sending ${this._sendingStreams.size} and receiving ${this.peer.incomingCalls.length} calls (${this.peer.incomingCalls.map(e=>e.userId).join(", ")})`,this.peer.incomingCalls)}}function Ln(s){if(s&&s instanceof MediaStream)for(const t of s.getTracks())t.stop()}var jP=Object.defineProperty,BP=Object.getOwnPropertyDescriptor,yg=(s,t,e,i)=>{for(var n=i>1?void 0:i?BP(t,e):t,o=s.length-1,a;o>=0;o--)(a=s[o])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&jP(t,e,n),n};const FP="noVoip",UP=x("debugvoip");class wo extends D{constructor(){super(...arguments);r(this,"autoConnect",!0);r(this,"runInBackground",!0);r(this,"createMenuButton",!0);r(this,"debug",!1);r(this,"_net");r(this,"_menubutton");r(this,"_allowSending",!0);r(this,"_outputStream",null);r(this,"onJoinedRoom",async()=>{this.debug&&console.log("VOIP: Joined room"),await dn(300),this.autoConnect&&!this.isSending&&this._allowSending&&this.connect()});r(this,"onLeftRoom",()=>{this.debug&&console.log("VOIP: Left room"),this.disconnect();for(const e of this._incomingStreams.values())Ln(e.srcObject);this._incomingStreams.clear()});r(this,"_incomingStreams",new Map);r(this,"onReceiveStream",e=>{const i=e.target.userId,n=e.stream;let o=this._incomingStreams.get(i);o||(o=new Audio,this._incomingStreams.set(i,o)),o.srcObject=n,o.setAttribute("autoplay","true"),$i.registerWaitForInteraction(()=>{o==null||o.play().catch(a=>{console.error("VOIP: Failed to play audio",a)})})});r(this,"onStreamEnded",e=>{const i=this._incomingStreams.get(e.userId);Ln(i==null?void 0:i.srcObject),this._incomingStreams.delete(e.userId)});r(this,"onEnabledChanged",()=>{for(const e of this._incomingStreams){const i=e[1];i.muted=!this.enabled}});r(this,"onVisibilityChanged",()=>{if(this.runInBackground)return;const i=!(document.visibilityState==="visible");this.setMuted(i);for(const n of this._incomingStreams){const o=n[1];o.muted=i}})}awake(){UP&&(this.debug=!0),this.debug&&(console.log("VOIP debugging: press 'v' to toggle mute or 'c' to toggle connect/disconnect"),window.addEventListener("keydown",async e=>{switch(e.key.toLowerCase()){case"v":console.log("MUTE?",!this.isMuted),this.setMuted(!this.isMuted);break;case"c":this.isSending?this.disconnect():this.connect();break}}),window.addEventListener("blur",()=>{console.log("VOIP: MUTE ON BLUR"),this.setMuted(!0)}),window.addEventListener("focus",()=>{console.log("VOIP: UNMUTE ON FOCUS"),this.setMuted(!1)}))}onEnable(){this._net||(this._net=nh.create(this)),this.debug&&(this._net.debug=!0),this._net.addEventListener(Dn.StreamReceived,this.onReceiveStream),this._net.addEventListener(Dn.StreamEnded,this.onStreamEnded),this._net.enable(),this.autoConnect&&this.context.connection.isConnected&&this.connect(),this.context.connection.beginListen(J.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(J.LeftRoom,this.onLeftRoom),this.onEnabledChanged(),this.updateButton(),window.addEventListener("visibilitychange",this.onVisibilityChanged)}onDisable(){var e;this._net&&(this._net.stopSendingStream(this._outputStream),this._net.removeEventListener(Dn.StreamReceived,this.onReceiveStream),this._net.removeEventListener(Dn.StreamEnded,this.onStreamEnded),(e=this._net)==null||e.disable()),this.context.connection.stopListen(J.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(J.LeftRoom,this.onLeftRoom),this.onEnabledChanged(),this.updateButton(),window.removeEventListener("visibilitychange",this.onVisibilityChanged)}onDestroy(){var e;(e=this._menubutton)==null||e.remove(),this._menubutton=void 0}get isSending(){return this._outputStream!=null&&this._outputStream.active}async connect(e){var i,n;if(!this._net)return console.error("Cannot connect to voice chat - NetworkedStreams not initialized. Make sure the component is enabled before calling this method."),!1;if(this.context.connection.isConnected){if(!await exports.DeviceUtilities.microphonePermissionsGranted())return console.error("Cannot connect to voice chat - microphone permissions not granted"),this.updateButton(),!1}else return console.error("Cannot connect to voice chat - not connected to server"),this.updateButton(),!1;return this._allowSending=!0,(i=this._net)==null||i.stopSendingStream(this._outputStream),Ln(this._outputStream),this._outputStream=await this.getAudioStream(e),this._outputStream?(this.debug&&console.log("VOIP: Got audio stream"),(n=this._net)==null||n.startSendingStream(this._outputStream),this.updateButton(),!0):(this.updateButton(),await exports.DeviceUtilities.microphonePermissionsGranted()?console.error("VOIP: Could not get audio stream - please make sure to connect an audio device and grant microphone permissions"):Wc("Microphone permissions not granted: Please grant microphone permissions to use voice chat"),(this.debug||I())&&console.log("VOIP: Failed to get audio stream"),!1)}disconnect(e){var i;e!=null&&e.remember&&(this._allowSending=!1),(i=this._net)==null||i.stopSendingStream(this._outputStream),Ln(this._outputStream),this._outputStream=null,this.updateButton()}setMuted(e){var n;const i=(n=this._outputStream)==null?void 0:n.getAudioTracks();if(i)for(const o of i)o.enabled=!e}get isMuted(){var i;if(this._outputStream===null)return!1;const e=(i=this._outputStream)==null?void 0:i.getAudioTracks();if(e){for(const n of e)if(!n.enabled)return!0}return!1}async updateButton(){var e;if(this.createMenuButton){if(this._menubutton||(this._menubutton=document.createElement("button"),this._menubutton.addEventListener("click",()=>{this.isSending?this.disconnect({remember:!0}):this.connect(),exports.DeviceUtilities.microphonePermissionsGranted().then(i=>{i||pe("<strong>Microphone permissions not granted</strong>. Please allow your browser to use the microphone to be able to talk. Click on the button on the left side of your browser's address bar to allow microphone permissions.")})})),this._menubutton){this.context.menu.appendChild(this._menubutton),this.activeAndEnabled?this._menubutton.style.display="":this._menubutton.style.display="none",this._menubutton.title=this.isSending?"Click to disable your microphone":"Click to enable your microphone";let i=(this.isSending,""),n=this.isSending?"mic":"mic_off";await exports.DeviceUtilities.microphonePermissionsGranted()||(i="No Permission",n="mic_off",this._menubutton.title="Microphone permissions not granted. Please allow your browser to use the microphone to be able to talk. This can usually be done in the addressbar of the webpage."),this._menubutton.innerText=i,this._menubutton.prepend(bt(n)),this.context.connection.isConnected==!1?this._menubutton.setAttribute("disabled",""):this._menubutton.removeAttribute("disabled")}}else this.activeAndEnabled||(e=this._menubutton)==null||e.remove()}getFrequency(e){return this.unsupported_getfrequency||(this.unsupported_getfrequency=!0,I()&&pe("VOIP: getFrequency is currently not supported"),console.warn("VOIP: getFrequency is currently not supported")),null}async getAudioStream(e){if(!navigator.mediaDevices.getUserMedia)return console.error("No getDisplayMedia support"),null;const i=async o=>await navigator.mediaDevices.getUserMedia({audio:o??!0,video:!1}).catch(a=>(console.warn("VOIP failed getting audio stream",a),null)),n=await i(e);if(!n)return null;if(exports.DeviceUtilities.isiOS()&&(e==null?void 0:e.deviceId)===void 0){const a=(await navigator.mediaDevices.enumerateDevices()).find(l=>(l.kind==="audioinput"||l.kind==="audiooutput")&&!l.label.includes("iPhone"));if(a){const l=Object.assign({},e);return l.deviceId=a.deviceId,await i(l)}}return n}}yg([p()],wo.prototype,"autoConnect",2);yg([p()],wo.prototype,"runInBackground",2);yg([p()],wo.prototype,"createMenuButton",2);var zP=Object.defineProperty,NP=Object.getOwnPropertyDescriptor,Vv=(s,t,e,i)=>{for(var n=i>1?void 0:i?NP(t,e):t,o=s.length-1,a;o>=0;o--)(a=s[o])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&zP(t,e,n),n};const VP=x("debugmouth");class sh extends D{constructor(){super(...arguments);r(this,"idle",[]);r(this,"talking",[]);r(this,"marker",null);r(this,"voip",null);r(this,"lastMouthChangeTime",0);r(this,"mouthChangeLength",0)}awake(){setTimeout(()=>{this.voip=S.findObjectOfType(wo,this.context),this.marker||(this.marker=S.getComponentInParent(this.gameObject,it))},3e3)}update(){var n;if(!this.voip||this.context.time.frameCount%10!==0)return;let e=((n=this.marker)==null?void 0:n.connectionId)??null;if(!e){VP&&(e=null);return}const i=this.voip.getFrequency(e)??0;this.updateLips(i)}updateLips(e){if(this.context.time.time-this.lastMouthChangeTime>this.mouthChangeLength){if(this.mouthChangeLength=.05+Math.random()*.1,this.talking&&this.talking.length>0&&e>30){this.lastMouthChangeTime=this.context.time.time;const i=Math.floor(Math.random()*this.talking.length);this.setMouthShapeActive(this.talking,i)}else if(this.idle.length>0&&this.context.time.time-this.lastMouthChangeTime>.5){this.lastMouthChangeTime=this.context.time.time;const i=Math.floor(Math.random()*this.idle.length);this.setMouthShapeActive(this.idle,i)}}}setMouthShapeActive(e,i){if(e){e!=this.idle?this.idle.map(n=>n.visible=!1):this.talking.map(n=>n.visible=!1);for(let n=0;n<e.length;n++){const o=e[n];o&&(o.visible=n===i)}}}}Vv([p(h.Object3D)],sh.prototype,"idle",2);Vv([p(h.Object3D)],sh.prototype,"talking",2);class _g extends D{constructor(){super(...arguments);r(this,"voip",null);r(this,"marker",null);r(this,"_startPosition",null)}awake(){this.voip=S.findObjectOfType(wo,this.context),this.marker=S.getComponentInParent(this.gameObject,it)}update(){if(!this.voip||!this.marker||this.context.time.frameCount%10!==0)return;const e=this.marker.connectionId,i=this.voip.getFrequency(e);if(i==null)return;this._startPosition||(this._startPosition=this.gameObject.position.clone());const n=i/100;this.gameObject.position.y=this._startPosition.y+n*.07}}var $P=Object.defineProperty,WP=Object.getOwnPropertyDescriptor,HP=(s,t,e,i)=>{for(var n=i>1?void 0:i?WP(t,e):t,o=s.length-1,a;o>=0;o--)(a=s[o])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&$P(t,e,n),n};const na=x("debugxrflags"),$v=x("disablexrflags");$v&&console.warn("XRFlags are disabled");var kn=(s=>(s[s.Never=0]="Never",s[s.Browser=1]="Browser",s[s.AR=2]="AR",s[s.VR=4]="VR",s[s.FirstPerson=8]="FirstPerson",s[s.ThirdPerson=16]="ThirdPerson",s[s.All=4294967295]="All",s))(kn||{});const xy=class{constructor(){r(this,"Mask",17)}Has(t){return(this.Mask&t)!==0}Set(t){na&&console.warn("Set XR flag state to",t),this.Mask=t,yi.Apply()}Enable(t){this.Mask|=t,yi.Apply()}Disable(t){this.Mask&=~t,yi.Apply()}Toggle(t){this.Mask^=t,yi.Apply()}EnableAll(){this.Mask=-1,yi.Apply()}DisableAll(){this.Mask=0,yi.Apply()}};let Et=xy;r(Et,"Global",new xy);var Tl;const es=(Tl=class extends D{constructor(){super(...arguments);r(this,"visibleIn")}static Apply(){for(const t of this.registry)t.UpdateVisible(Et.Global)}awake(){es.registry.push(this)}onEnable(){es.firstApply?this.UpdateVisible(Et.Global):(es.firstApply=!0,es.Apply())}onDestroy(){const t=es.registry.indexOf(this);t>=0&&es.registry.splice(t,1)}get isOn(){return this.gameObject.visible}UpdateVisible(t=null){if($v)return;let e;const i=t;if(i&&typeof i=="number"&&(console.assert(typeof i=="number","XRFlag.UpdateVisible: state must be a number",i),na&&console.log(i),es.buffer.Mask=i,t=es.buffer),t instanceof Et?(na&&console.warn(this.name,"use passed in mask",t.Mask,this.visibleIn),e=t.Has(this.visibleIn)):(na&&console.log(this.name,"use global mask"),Et.Global.Has(this.visibleIn)),e!==void 0)if(e)na&&console.log(this.name,"is visible",this.gameObject.uuid),S.setActive(this.gameObject,!0);else{if(na&&console.log(this.name,"is not visible",this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},r(Tl,"registry",[]),r(Tl,"firstApply"),r(Tl,"buffer",new Et),Tl);let yi=es;HP([p()],yi.prototype,"visibleIn",2);var GP=Object.defineProperty,qP=Object.getOwnPropertyDescriptor,Fu=(s,t,e,i)=>{for(var n=i>1?void 0:i?qP(t,e):t,o=s.length-1,a;o>=0;o--)(a=s[o])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&GP(t,e,n),n};class vr extends D{constructor(){super(...arguments);r(this,"eyes",[]);r(this,"lastBlinkTime",0);r(this,"blinkLength",0);r(this,"eyesOpen",!0);r(this,"state",null)}awake(){this.state=S.getComponentInParent(this.gameObject,yi)}update(){if(!this.gameObject||!this.gameObject.visible||!this.eyes||!Array.isArray(this.eyes)||this.eyes.length===0)return;if(this.context.time.time-this.lastBlinkTime>this.blinkLength){if(this.lastBlinkTime=this.context.time.time,this.state&&!this.state.isOn||!this.activeAndEnabled)return;if(this.eyesOpen=!this.eyesOpen,this.blinkLength=Math.random(),this.eyesOpen?(this.blinkLength*=3,this.blinkLength+=.5,Math.random()<.1&&(this.blinkLength=.1+Math.random()*.2)):(this.blinkLength*=Math.random()*.2,this.blinkLength+=.1),Math.random()<.1&&(this.blinkLength*=3),this.blinkLength=Math.max(.2,this.blinkLength),this.blinkLength=Math.min(3,this.blinkLength),this.eyes)for(const i of this.eyes)i&&(i.visible=this.eyesOpen)}}}Fu([p(h.Object3D)],vr.prototype,"eyes",2);Fu([p()],vr.prototype,"lastBlinkTime",2);Fu([p()],vr.prototype,"blinkLength",2);Fu([p()],vr.prototype,"eyesOpen",2);var XP=Object.defineProperty,QP=Object.getOwnPropertyDescriptor,bg=(s,t,e,i)=>{for(var n=i>1?void 0:i?QP(t,e):t,o=s.length-1,a;o>=0;o--)(a=s[o])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&XP(t,e,n),n},vp;const Wv=(vp=class extends D{constructor(){super(...arguments);r(this,"head",null);r(this,"eyes",null);r(this,"target",null);r(this,"brain",null);r(this,"vec",new h.Vector3);r(this,"currentTargetPoint",new h.Vector3)}awake(){this.brain||(this.brain=S.getComponentInParent(this.gameObject,Ac)),this.brain||(this.brain=S.addComponent(this.gameObject,Ac)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}update(){const t=this.target;if(t&&this.head){const e=this.eyes;if(e){const i=Z(t);this.currentTargetPoint.lerp(i,this.context.time.deltaTime/.1);const n=Z(this.head),o=this.vec.copy(this.currentTargetPoint).sub(n).normalize();if(o.length()<.1)return;const a=Wv.forward;if(a.set(0,0,1),a.applyQuaternion(ye(this.head)),a.dot(o)>.45)for(let c=0;c<e.length;c++)e[c].lookAt(this.currentTargetPoint)}}}},r(vp,"forward",new h.Vector3(0,0,1)),vp);let Fa=Wv;bg([p(h.Object3D)],Fa.prototype,"head",2);bg([p(h.Object3D)],Fa.prototype,"eyes",2);bg([p(h.Object3D)],Fa.prototype,"target",2);var YP=Object.defineProperty,KP=Object.getOwnPropertyDescriptor,vg=(s,t,e,i)=>{for(var n=i>1?void 0:i?KP(t,e):t,o=s.length-1,a;o>=0;o--)(a=s[o])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&YP(t,e,n),n};class Ua extends D{constructor(){super(...arguments);r(this,"length",1);r(this,"depthTest",!0);r(this,"isGizmo",!1);r(this,"_axes",null)}onEnable(){if(this.isGizmo&&!qc)return;this._axes||(this._axes=new h.AxesHelper(this.length)),this._axes.layers.disableAll(),this._axes.layers.set(this.layer),this.gameObject.add(this._axes);const e=this._axes.material;e&&e.depthTest!==void 0&&(e.depthTest=this.depthTest)}onDisable(){this._axes&&this.gameObject.remove(this._axes)}}vg([p()],Ua.prototype,"length",2);vg([p()],Ua.prototype,"depthTest",2);vg([p()],Ua.prototype,"isGizmo",2);class wg extends D{constructor(){super(...arguments);r(this,"from");r(this,"to");r(this,"hint");r(this,"desiredDistance",1)}onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;const e=Z(this.to).clone(),i=Z(this.from).clone(),n=e.distanceTo(i),o=e.clone();o.sub(i);const a=i.clone();a.add(e),a.multiplyScalar(.5);const l=Z(this.hint).clone();l.sub(a);const c=new h.Vector3;c.crossVectors(l,o),c.crossVectors(o,c),c.normalize();const d=n*.5,u=Math.max(this.desiredDistance,d),f=Math.sqrt(u*u-d*d),m=c.clone();m.multiplyScalar(f),m.add(a),nt(this.gameObject,m);const g=a.clone();g.sub(c),this.gameObject.lookAt(g)}}const ZP=x("gizmos"),JP=x("debugboxhelper"),on=class extends D{constructor(){super(...arguments);r(this,"box",null);r(this,"_lastMatrixUpdateFrame",-1);r(this,"_helper",null);r(this,"_color",null)}isInBox(e){var n;if(!e)return;if(this.box||(this.box=new h.Box3),si([e],void 0,void 0,on.testBox),on.testBox.isEmpty()){const o=Z(e,on._position);on.testBox.setFromCenterAndSize(o,on._emptyObjectSize)}this.updateBox();const i=(n=this.box)==null?void 0:n.intersectsBox(on.testBox);return i&&JP&&N.DrawWireBox3(on.testBox,16711680,5),i}intersects(e){return e?this.updateBox(!1).intersectsBox(e):!1}updateBox(e=!1){if(this.box||(this.box=new h.Box3),e||this.context.time.frameCount!=this._lastMatrixUpdateFrame){const i=this._lastMatrixUpdateFrame<0;this._lastMatrixUpdateFrame=this.context.time.frameCount;const n=i,o=Z(this.gameObject,on._position,n),a=Ue(this.gameObject,on._size);this.box.setFromCenterAndSize(o,a)}return this.box}awake(){this._helper=null,this._color=null,this.box=null}showHelper(e=null,i=!1){var n;if(!(!ZP&&!i)){if(this._helper){e&&((n=this._color)==null||n.set(e)),this.gameObject.add(this._helper);return}this._helper=Ym(e),this.gameObject.add(this._helper)}}};let ti=on;r(ti,"testBox",new h.Box3),r(ti,"_position",new h.Vector3),r(ti,"_size",new h.Vector3(.01,.01,.01)),r(ti,"_emptyObjectSize",new h.Vector3(.01,.01,.01));var eO=Object.defineProperty,tO=Object.getOwnPropertyDescriptor,oi=(s,t,e,i)=>{for(var n=i>1?void 0:i?tO(t,e):t,o=s.length-1,a;o>=0;o--)(a=s[o])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&eO(t,e,n),n};class ri extends D{constructor(){super(...arguments);r(this,"attachedRigidbody",null);r(this,"isTrigger",!1);r(this,"sharedMaterial");r(this,"membership",[0]);r(this,"filter");r(this,"updateProperties",()=>{var e;(e=this.context.physics.engine)==null||e.updateProperties(this)})}get isCollider(){return!0}awake(){super.awake(),this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(fe))}start(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(fe))}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(fe))}onDisable(){var e;(e=this.context.physics.engine)==null||e.removeBody(this)}get body(){var e;return(e=this.context.physics.engine)==null?void 0:e.getBody(this)}updatePhysicsMaterial(){var e;(e=this.context.physics.engine)==null||e.updatePhysicsMaterial(this)}}oi([p(fe)],ri.prototype,"attachedRigidbody",2);oi([p()],ri.prototype,"isTrigger",2);oi([p()],ri.prototype,"sharedMaterial",2);oi([p()],ri.prototype,"membership",2);oi([p()],ri.prototype,"filter",2);class za extends ri{constructor(){super(...arguments);r(this,"radius",.5);r(this,"center",new h.Vector3(0,0,0))}onEnable(){var e;super.onEnable(),(e=this.context.physics.engine)==null||e.addSphereCollider(this),wu(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),Em(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}}oi([Pt(),p()],za.prototype,"radius",2);oi([p(h.Vector3)],za.prototype,"center",2);const Hv=class extends ri{constructor(){super(...arguments);r(this,"size",new h.Vector3(1,1,1));r(this,"center",new h.Vector3(0,0,0))}static add(t,e){const i=xi(t,Hv);return i.autoFit(),(e==null?void 0:e.rigidbody)===!0&&xi(t,fe,{isKinematic:!1}),i}onEnable(){var t;super.onEnable(),(t=this.context.physics.engine)==null||t.addBoxCollider(this,this.size),wu(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),Em(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}autoFit(t){const e=this.gameObject,i=e.position.clone(),n=e.quaternion.clone(),o=e.scale.clone(),a=e.parent;e.position.set(0,0,0),e.quaternion.set(0,0,0,1),e.scale.set(1,1,1),e.parent=null,e.updateMatrix();const l=si([e]);e.position.copy(i),e.quaternion.copy(n),e.scale.copy(o),e.parent=a,(t==null?void 0:t.debug)===!0&&N.DrawWireBox3(l,16768256,20),this.size=l.getSize(new h.Vector3)||new h.Vector3(1,1,1),this.center=l.getCenter(new h.Vector3)||new h.Vector3(0,0,0),this.size.length()<=0&&this.size.set(.01,.01,.01)}};let Na=Hv;oi([Pt(),p(h.Vector3)],Na.prototype,"size",2);oi([p(h.Vector3)],Na.prototype,"center",2);class xo extends ri{constructor(){super(...arguments);r(this,"sharedMesh");r(this,"convex",!1)}onEnable(){var i,n,o;if(super.onEnable(),!this.context.physics.engine)return;(i=this.sharedMesh)!=null&&i.isMesh||(this.gameObject instanceof h.Mesh||this.gameObject instanceof h.Group)&&(this.sharedMesh=this.gameObject);const e=0;if((n=this.sharedMesh)!=null&&n.isMesh)this.context.physics.engine.addMeshCollider(this,this.sharedMesh,this.convex),le.NEEDLE_progressive.assignMeshLOD(this.sharedMesh,e).then(a=>{a&&this.activeAndEnabled&&this.context.physics.engine&&this.sharedMesh&&(this.context.physics.engine.removeBody(this),this.sharedMesh.geometry=a,this.context.physics.engine.addMeshCollider(this,this.sharedMesh,this.convex))});else{const a=this.sharedMesh;if(a!=null&&a.isGroup){console.warn(`MeshCollider mesh is a group "${((o=this.sharedMesh)==null?void 0:o.name)||this.gameObject.name}", adding all children as colliders. This is currently not fully supported (colliders can not be removed from world again)`,this);const l=new Array;for(const c in a.children){const d=a.children[c];d.isMesh&&(this.context.physics.engine.addMeshCollider(this,d,this.convex),l.push(le.NEEDLE_progressive.assignMeshLOD(d,e)))}Promise.all(l).then(c=>{var u,f;if(c.some(m=>m)==!1)return;(u=this.context.physics.engine)==null||u.removeBody(this);const d=new h.Mesh;for(const m of c)m&&this.activeAndEnabled&&(d.geometry=m,(f=this.context.physics.engine)==null||f.addMeshCollider(this,d,this.convex))})}else(I()||x("showcolliders"))&&console.warn(`[MeshCollider] A MeshCollider mesh is assigned to an unknown object on "${this.gameObject.name}", but it's neither a Mesh nor a Group. Please double check that you attached the collider component to the right object and report a bug otherwise!`,this)}}}oi([p(h.Mesh)],xo.prototype,"sharedMesh",2);oi([p()],xo.prototype,"convex",2);class vs extends ri{constructor(){super(...arguments);r(this,"center",new h.Vector3(0,0,0));r(this,"radius",.5);r(this,"height",2)}onEnable(){var e;super.onEnable(),(e=this.context.physics.engine)==null||e.addCapsuleCollider(this,this.height,this.radius)}}oi([p(h.Vector3)],vs.prototype,"center",2);oi([p()],vs.prototype,"radius",2);oi([p()],vs.prototype,"height",2);var iO=Object.defineProperty,nO=Object.getOwnPropertyDescriptor,xs=(s,t,e,i)=>{for(var n=i>1?void 0:i?nO(t,e):t,o=s.length-1,a;o>=0;o--)(a=s[o])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&iO(t,e,n),n};const j_=x("debugcharactercontroller");class wr extends D{constructor(){super(...arguments);r(this,"center",new h.Vector3(0,0,0));r(this,"radius",.5);r(this,"height",2);r(this,"_rigidbody",null);r(this,"_activeGroundCollisions");r(this,"_contactVelocity",new h.Vector3)}get rigidbody(){return this._rigidbody?this._rigidbody:(this._rigidbody=this.gameObject.getComponent(fe),this._rigidbody||(this._rigidbody=this.gameObject.addComponent(fe)),this.rigidbody)}awake(){this._activeGroundCollisions=new Set}onEnable(){const e=this.rigidbody;let i=this.gameObject.getComponent(vs);i||(i=this.gameObject.addComponent(vs)),i.center.copy(this.center),i.radius=this.radius,i.height=this.height;const n=new h.Vector3(0,0,1),o=new h.Vector3(1,0,0),a=new h.Vector3(0,1,0),l=this.gameObject.getWorldDirection(new h.Vector3);l.y=0;const c=o.dot(l)<0?-1:1,d=n.angleTo(l)*c;this.gameObject.setRotationFromAxisAngle(a,d),e.lockRotationX=!0,e.lockRotationY=!0,e.lockRotationZ=!0}move(e){this.gameObject.position.add(e)}onCollisionEnter(e){(e.contacts.length==0||e.contacts.some(i=>i.normal.y>.2))&&(this._activeGroundCollisions.add(e),j_&&console.log(`Collision(${this._activeGroundCollisions.size}): ${e.contacts.map(i=>i.normal.y.toFixed(2)).join(", ")} - ${this.isGrounded}`))}onCollisionExit(e){this._activeGroundCollisions.delete(e),j_&&console.log(`Collision(${this._activeGroundCollisions.size}) - ${this.isGrounded}`)}get isGrounded(){return this._activeGroundCollisions.size>0}get contactVelocity(){var e;this._contactVelocity.set(0,0,0);for(const i of this._activeGroundCollisions){const n=(e=this.context.physics.engine)==null?void 0:e.getLinearVelocity(i.collider);n&&(this._contactVelocity.x+=n.x,this._contactVelocity.y+=n.y,this._contactVelocity.z+=n.z)}return this._contactVelocity}}xs([p(h.Vector3)],wr.prototype,"center",2);xs([p()],wr.prototype,"radius",2);xs([p()],wr.prototype,"height",2);class Ss extends D{constructor(){super(...arguments);r(this,"controller");r(this,"movementSpeed",2);r(this,"rotationSpeed",2);r(this,"jumpForce",1);r(this,"doubleJumpForce",2);r(this,"animator");r(this,"lookForward",!0);r(this,"lookInput",new h.Vector2(0,0));r(this,"moveInput",new h.Vector2(0,0));r(this,"jumpInput",!1);r(this,"_currentSpeed",new h.Vector3(0,0,0));r(this,"_currentAngularSpeed",new h.Vector3(0,0,0));r(this,"_temp",new h.Vector3(0,0,0));r(this,"_jumpCount",0);r(this,"_currentRotation");r(this,"_raycastOptions",new zn)}awake(){this._currentRotation=new h.Quaternion}update(){const e=this.context.input;e.isKeyPressed("KeyW")?this.moveInput.y+=1:e.isKeyPressed("KeyS")&&(this.moveInput.y-=1),e.isKeyPressed("KeyD")?this.lookInput.x+=1:e.isKeyPressed("KeyA")&&(this.lookInput.x-=1),this.jumpInput||(this.jumpInput=e.isKeyDown("Space"))}move(e){this.moveInput.add(e)}look(e){this.lookInput.add(e)}jump(){this.jumpInput=!0}onBeforeRender(){this.handleInput(this.moveInput,this.lookInput,this.jumpInput),this.lookInput.set(0,0),this.moveInput.set(0,0),this.jumpInput=!1}handleInput(e,i,n){var o,a,l,c,d,u,f,m,g,y,_;if((o=this.controller)!=null&&o.isGrounded&&(this._jumpCount=0,this.doubleJumpForce>0&&((a=this.animator)==null||a.setBool("doubleJump",!1))),this._currentSpeed.z+=e.y*this.movementSpeed*this.context.time.deltaTime,(l=this.animator)==null||l.setBool("running",e.length()>.01),(d=this.animator)==null||d.setBool("jumping",((c=this.controller)==null?void 0:c.isGrounded)===!0&&n),this._temp.copy(this._currentSpeed),this._temp.applyQuaternion(this.gameObject.quaternion),this.controller?this.controller.move(this._temp):this.gameObject.position.add(this._temp),this._currentAngularSpeed.y+=z.toRadians(-i.x*this.rotationSpeed)*this.context.time.deltaTime,this.lookForward&&Math.abs(this._currentAngularSpeed.y)<.01){const b=this.context.mainCameraComponent.forward;b.y=0,b.normalize(),this._currentRotation.setFromUnitVectors(new h.Vector3(0,0,1),b),this.gameObject.quaternion.slerp(this._currentRotation,this.context.time.deltaTime*10)}if(this.gameObject.rotateY(this._currentAngularSpeed.y),this._currentSpeed.multiplyScalar(1-this.context.time.deltaTime*10),this._currentAngularSpeed.y*=1-this.context.time.deltaTime*10,this.controller&&n&&this.jumpForce>0){let b=(u=this.controller)==null?void 0:u.isGrounded;if(this.doubleJumpForce>0&&!((f=this.controller)!=null&&f.isGrounded)&&this._jumpCount===1&&(b=!0,(m=this.animator)==null||m.setBool("doubleJump",!0)),b){this._jumpCount+=1;const v=this.controller.rigidbody,w=this._jumpCount===2?this.doubleJumpForce:this.jumpForce;v.applyImpulse(new h.Vector3(0,1,0).multiplyScalar(w))}}if(this.controller){const b=(g=this.controller)==null?void 0:g.rigidbody.getVelocity().y;if(b<-1){this._raycastOptions.ray||(this._raycastOptions.ray=new h.Ray),this._raycastOptions.ray.origin.copy(Z(this.gameObject)),this._raycastOptions.ray.direction.set(0,-1,0);const v=this.layer;this.gameObject.layers.disableAll(),this.gameObject.layers.set(2);const w=this.context.physics.raycast(this._raycastOptions);this.gameObject.layers.set(v),(w.length&&w[0].distance>2||b<-10)&&((y=this.animator)==null||y.setBool("falling",!0))}else(_=this.animator)==null||_.setBool("falling",!1)}}}xs([p(wr)],Ss.prototype,"controller",2);xs([p()],Ss.prototype,"movementSpeed",2);xs([p()],Ss.prototype,"rotationSpeed",2);xs([p()],Ss.prototype,"jumpForce",2);xs([p()],Ss.prototype,"doubleJumpForce",2);xs([p(St)],Ss.prototype,"animator",2);var sO=Object.defineProperty,oO=Object.getOwnPropertyDescriptor,Va=(s,t,e,i)=>{for(var n=i>1?void 0:i?oO(t,e):t,o=s.length-1,a;o>=0;o--)(a=s[o])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&sO(t,e,n),n};const _l=x("debugcontactshadows");Rv(s=>{const t=s.domElement.getAttribute("contactshadows")||s.domElement.getAttribute("contact-shadows");if(t!=null&&t!="0"&&t!="false"){console.debug("Auto-creating ContactShadows because of `contactshadows` attribute");const e=gn.auto(s),i=parseFloat(t);isNaN(i)||(e.opacity=i,e.darkness=i)}});var wp;const Vl=(wp=class extends D{constructor(){super(...arguments);r(this,"autoFit",!1);r(this,"darkness",.5);r(this,"opacity",.5);r(this,"blur",4);r(this,"occludeBelowGround",!1);r(this,"backfaceShadows",!0);r(this,"minSize");r(this,"shadowsRoot",new h.Object3D);r(this,"shadowCamera");r(this,"shadowGroup",new h.Group);r(this,"renderTarget");r(this,"renderTargetBlur");r(this,"plane");r(this,"occluderMesh");r(this,"blurPlane");r(this,"depthMaterial");r(this,"horizontalBlurMaterial");r(this,"verticalBlurMaterial");r(this,"textureSize",512)}static auto(t){if(t||(t=Q.Current),!t)throw new Error("No context provided and no current context set.");let e=this._instances.get(t);if(!e||e.destroyed){const i=new h.Object3D;e=xi(i,Vl,{autoFit:!1,occludeBelowGround:!1}),this._instances.set(t,e)}return t.scene.add(e.gameObject),e.fitShadows(),e}fitShadows(){_l&&console.warn("Fitting shadows to scene"),Id(this.shadowsRoot,!1);const t=si(this.context.scene.children,[this.shadowsRoot]),e=Math.max(1,this.blur/32),i=t.max.x-t.min.x,n=t.max.z-t.min.z;t.expandByVector(new h.Vector3(e*i,0,e*n)),_l&&N.DrawWireBox3(t,16776960,60),this.gameObject.parent&&t.applyMatrix4(this.gameObject.parent.matrixWorld.clone().invert());const o=t.min,a=Math.max(1e-5,(t.max.y-o.y)*.002);t.max.y+=a,this.shadowsRoot.position.set((o.x+t.max.x)/2,o.y-a,(o.z+t.max.z)/2),this.shadowsRoot.scale.set(t.max.x-o.x,t.max.y-o.y,t.max.z-o.z),this.applyMinSize(),this.shadowsRoot.matrixWorldNeedsUpdate=!0,_l&&console.log("Fitted shadows to scene",this.shadowsRoot.scale.clone())}awake(){Vl._instances.set(this.context,this),this.shadowsRoot.hideFlags=Bu.DontExport,Id(this.shadowsRoot,!1)}start(){_l&&console.log("Create ContactShadows on "+this.gameObject.name,this),this.gameObject.add(this.shadowsRoot),this.shadowsRoot.add(this.shadowGroup),this.renderTarget=new h.WebGLRenderTarget(this.textureSize,this.textureSize),this.renderTarget.texture.generateMipmaps=!1,this.renderTargetBlur=new h.WebGLRenderTarget(this.textureSize,this.textureSize),this.renderTargetBlur.texture.generateMipmaps=!1;const t=new h.PlaneGeometry(1,1).rotateX(Math.PI/2);this.gameObject instanceof h.Mesh&&(console.warn("ContactShadows can not be added to a Mesh. Please add it to a Group or an empty Object"),hs(this.gameObject,!1));const e=new h.MeshBasicMaterial({map:this.renderTarget.texture,opacity:this.opacity,color:0,transparent:!0,depthWrite:!1,side:h.FrontSide});this.plane=new h.Mesh(t,e),this.plane.scale.y=-1,this.plane.layers.set(2),this.shadowsRoot.add(this.plane),this.plane&&(this.plane.renderOrder=1),this.occluderMesh=new h.Mesh(this.plane.geometry,new h.MeshBasicMaterial({depthWrite:!0,stencilWrite:!0,colorWrite:!1,side:h.BackSide})).translateY(-1e-4),this.occluderMesh.renderOrder=-100,this.occluderMesh.layers.set(2),this.shadowsRoot.add(this.occluderMesh),this.blurPlane=new h.Mesh(t),this.blurPlane.visible=!1,this.shadowGroup.add(this.blurPlane);const i=0,n=1;this.shadowCamera=new h.OrthographicCamera(-1/2,1/2,1/2,-1/2,i,n),this.shadowCamera.layers.enableAll(),this.shadowCamera.rotation.x=Math.PI/2,this.shadowGroup.add(this.shadowCamera),this.depthMaterial=new h.MeshDepthMaterial,this.depthMaterial.userData.darkness={value:this.darkness},this.depthMaterial.blending=h.CustomBlending,this.depthMaterial.blendEquation=h.MaxEquation,this.depthMaterial.onBeforeCompile=o=>{this.depthMaterial&&(o.uniforms.darkness=this.depthMaterial.userData.darkness,o.fragmentShader=`
932
+ Incoming:`,this._incomingCalls),l}else Ge&&console.error("Failed to make call",e,i,this._peer)}closeAll(){for(const e of this._incomingCalls)e.close();for(const e of this._outgoingCalls)e.close();this.updateCalls()}get peer(){return this._peer}get incomingCalls(){return this._incomingCalls}enable(){this._enabled||(this._enabled=!0,this.context.connection.beginListen(J.JoinedRoom,this.onConnectRoomFn),this.subscribePeerEvents())}disable(){this._enabled&&(this._enabled=!1,this.context.connection.stopListen(J.JoinedRoom,this.onConnectRoomFn),this.unsubscribePeerEvents())}onConnectRoom(){this.setupPeer()}setupPeer(){if(this.context.connection.connectionId&&!this._enabledPeer){if(this._enabledPeer=!0,!this._peer){const e=this.getMyPeerId();e?this._peer=m0(e):console.error("Failed to setup peerjs because we dont have a connection id",this.context.connection.connectionId)}this._enabled&&this.subscribePeerEvents()}}subscribePeerEvents(){this._peer&&(this._peer.on("open",this.onPeerConnect),this._peer.on("close",this.onPeerClose),this._peer.on("call",this.onPeerReceivingCall),this._peer.on("disconnected",this.onPeerDisconnected),this._peer.on("error",this.onPeerError))}unsubscribePeerEvents(){this._peer&&(this._peer.off("open",this.onPeerConnect),this._peer.off("close",this.onPeerClose),this._peer.off("call",this.onPeerReceivingCall),this._peer.off("disconnected",this.onPeerDisconnected),this._peer.off("error",this.onPeerError))}registerCall(e,i,n){const o=e.metadata;(!o||!o.userId)&&console.error("Missing call metadata",e);const a=o.userId;i==="incoming"&&Ge?console.warn("← Receive call from",e.metadata,e.connectionId):Ge&&console.warn("→ Make call to",e.metadata);const l=i==="incoming"?this._incomingCalls:this._outgoingCalls,c=new IP(a,e,i,n);return l.push(c),e.on("error",d=>{console.error("Call error",d)}),e.on("close",()=>{Ge&&console.log("Call ended",e.metadata);const d=l.indexOf(c);d!==-1&&l.splice(d,1),c.close(),this.dispatchEvent(new gg(a,i))}),c.addEventListener("call-ended",d=>{this.dispatchEvent(d)}),i==="incoming"&&(c.addEventListener("receive-stream",d=>{this.dispatchEvent(d)}),e.on("stream",()=>{Ge&&console.log("Received stream for call",e.metadata);let d=0;const u=setInterval(()=>{const f=d===0;!c.isOpen&&f&&(Ge&&console.warn("Close call because stream is not active",e.metadata),d+=1,clearInterval(u),c.close())},2e3)})),c}};let ir=fa;r(ir,"instances",new Map);class nh extends h.EventDispatcher{constructor(e,i){super();r(this,"context");r(this,"peer");r(this,"_sendingStreams",new Map);r(this,"debug",!1);r(this,"_enabled",!1);r(this,"_tickIntervalId");r(this,"tick",()=>{this.updateSendingCalls()});r(this,"onJoinedRoom",e=>{this._sendingStreams.size>0&&(this.debug&&console.warn(`${e!=null&&e.userId?`User ${e.userId}`:"You"} joined room`,e,this._sendingStreams.size),this.updateSendingCalls())});r(this,"onLeftRoom",e=>{this.debug&&console.warn(`${(e==null?void 0:e.userId)||"You"} left room`,e),this.stopCallsToUsersThatAreNotInTheRoomAnymore(),this.peer.closeAll()});r(this,"onCallStreamReceived",e=>{this.debug&&console.log("Call with "+e.userId+" started"),this.dispatchEvent({type:"receive-stream",target:this,stream:e.stream,userId:e.userId}),this.debug&&this.debugLogCurrentState()});r(this,"onCallEnded",e=>{this.debug&&console.log("Call with "+e.userId+" ended"),this.dispatchEvent(e),this.debug&&this.debugLogCurrentState()});r(this,"onUserConnected",e=>{if(this.peer.id===e.guid){this.debug&&console.log("PEER USER CONNECTED",e.guid,e,this._sendingStreams.size);const i=this._sendingStreams.keys().next().value;this.peer.makeCall(e.peerId,i)}else Ge&&console.log("Unknown user connected",e.guid,e.peerId)});r(this,"onUserLeft",e=>{this.debug&&console.log("User left room: "+e.userId),this.stopCallsToUsersThatAreNotInTheRoomAnymore()});if(jv(e)){const n=e;e=n.context,i=ir.getOrCreate(n.context,n.guid)}else typeof i=="string"&&(i=ir.getOrCreate(e,i));if(e){if(!(e instanceof Q))throw new Error("Failed to create NetworkedStreams because context is not an instance of Context")}else throw new Error("Failed to create NetworkedStreams because context is undefined");if(!i)throw new Error("Failed to create NetworkedStreams because peer is undefined");this.context=e,this.peer=i,Ge&&(this.debug=!0)}static create(e,i){const n=ir.getOrCreate(e.context,i||e.context.connection.connectionId||e.guid);return new nh(e.context,n)}startSendingStream(e){this._sendingStreams.has(e)?console.warn("Received start sending stream with stream that is already being sent"):(this._sendingStreams.set(e,[]),this.updateSendingCalls())}stopSendingStream(e){if(e){const i=this._sendingStreams.get(e);if(i){for(const n of i)n.close();i.length=0}this._sendingStreams.delete(e),i&&this.debug&&this.debugLogCurrentState()}this.updateSendingCalls()}get enabled(){return this._enabled}enable(){this._enabled||(this._enabled=!0,this.peer.enable(),this.peer.addEventListener("receive-stream",this.onCallStreamReceived),this.peer.addEventListener("call-ended",this.onCallEnded),this.context.connection.beginListen("peer-user-connected",this.onUserConnected),this.context.connection.beginListen(J.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(J.UserJoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(J.UserLeftRoom,this.onUserLeft),this.context.connection.beginListen(J.LeftRoom,this.onLeftRoom),this._tickIntervalId=setInterval(this.tick,5e3))}disable(){this._enabled&&(this._enabled=!1,this.peer.disable(),this.peer.removeEventListener("receive-stream",this.onCallStreamReceived),this.peer.removeEventListener("call-ended",this.onCallEnded),this.context.connection.stopListen("peer-user-connected",this.onUserConnected),this.context.connection.stopListen(J.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(J.UserJoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(J.UserLeftRoom,this.onUserLeft),this.context.connection.stopListen(J.LeftRoom,this.onLeftRoom),this._tickIntervalId!=null&&(clearInterval(this._tickIntervalId),this._tickIntervalId=void 0))}updateSendingCalls(){const e=this.context.connection.connectionId;for(const i of this._sendingStreams.keys()){const n=this._sendingStreams.get(i)||[];for(const o of this.context.connection.usersInRoom()){if(o===e)continue;const a=this.peer.getPeerIdFromUserId(o);if(n.find(c=>{var d;return c.peerId===a&&c.direction==="outgoing"&&!c.isClosed&&((d=c.stream)==null?void 0:d.active)}))Ge&&console.debug("Already have a call with user "+o+" / peer "+a);else{const c=this.peer.makeCall(a,i);c&&n.push(c)}}this._sendingStreams.set(i,n)}this.stopCallsToUsersThatAreNotInTheRoomAnymore()}stopCallsToUsersThatAreNotInTheRoomAnymore(){for(const e of this._sendingStreams.keys()){const i=this._sendingStreams.get(e);if(i)for(let n=i.length-1;n>=0;n--){const o=i[n];this.context.connection.userIsInRoom(o.userId)?Ge&&(this.context.connection.connectionId===o.userId?console.warn(`You are still in the room [${n}] ${o.userId}`):console.log(`User is still in room [${n}] ${o.userId}`)):(Ge&&console.log(`Remove call ${[n]} to user that is not in room anymore ${o.userId}`),o.close(),i.splice(n,1))}}this.peer.updateCalls(),this.debug&&this.debugLogCurrentState()}debugLogCurrentState(){console.warn(`You (${this.context.connection.connectionId}) are currently sending ${this._sendingStreams.size} and receiving ${this.peer.incomingCalls.length} calls (${this.peer.incomingCalls.map(e=>e.userId).join(", ")})`,this.peer.incomingCalls)}}function Ln(s){if(s&&s instanceof MediaStream)for(const t of s.getTracks())t.stop()}var jP=Object.defineProperty,BP=Object.getOwnPropertyDescriptor,yg=(s,t,e,i)=>{for(var n=i>1?void 0:i?BP(t,e):t,o=s.length-1,a;o>=0;o--)(a=s[o])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&jP(t,e,n),n};const FP="noVoip",UP=x("debugvoip");class wo extends D{constructor(){super(...arguments);r(this,"autoConnect",!0);r(this,"runInBackground",!0);r(this,"createMenuButton",!0);r(this,"debug",!1);r(this,"_net");r(this,"_menubutton");r(this,"_allowSending",!0);r(this,"_outputStream",null);r(this,"onJoinedRoom",async()=>{this.debug&&console.log("VOIP: Joined room"),await dn(300),this.autoConnect&&!this.isSending&&this._allowSending&&this.connect()});r(this,"onLeftRoom",()=>{this.debug&&console.log("VOIP: Left room"),this.disconnect();for(const e of this._incomingStreams.values())Ln(e.srcObject);this._incomingStreams.clear()});r(this,"_incomingStreams",new Map);r(this,"onReceiveStream",e=>{const i=e.target.userId,n=e.stream;let o=this._incomingStreams.get(i);o||(o=new Audio,this._incomingStreams.set(i,o)),o.srcObject=n,o.setAttribute("autoplay","true"),$i.registerWaitForInteraction(()=>{o==null||o.play().catch(a=>{console.error("VOIP: Failed to play audio",a)})})});r(this,"onStreamEnded",e=>{const i=this._incomingStreams.get(e.userId);Ln(i==null?void 0:i.srcObject),this._incomingStreams.delete(e.userId)});r(this,"onEnabledChanged",()=>{for(const e of this._incomingStreams){const i=e[1];i.muted=!this.enabled}});r(this,"onVisibilityChanged",()=>{if(this.runInBackground)return;const i=!(document.visibilityState==="visible");this.setMuted(i);for(const n of this._incomingStreams){const o=n[1];o.muted=i}})}awake(){UP&&(this.debug=!0),this.debug&&(console.log("VOIP debugging: press 'v' to toggle mute or 'c' to toggle connect/disconnect"),window.addEventListener("keydown",async e=>{switch(e.key.toLowerCase()){case"v":console.log("MUTE?",!this.isMuted),this.setMuted(!this.isMuted);break;case"c":this.isSending?this.disconnect():this.connect();break}}),window.addEventListener("blur",()=>{console.log("VOIP: MUTE ON BLUR"),this.setMuted(!0)}),window.addEventListener("focus",()=>{console.log("VOIP: UNMUTE ON FOCUS"),this.setMuted(!1)}))}onEnable(){this._net||(this._net=nh.create(this)),this.debug&&(this._net.debug=!0),this._net.addEventListener(Dn.StreamReceived,this.onReceiveStream),this._net.addEventListener(Dn.StreamEnded,this.onStreamEnded),this._net.enable(),this.autoConnect&&this.context.connection.isConnected&&this.connect(),this.context.connection.beginListen(J.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(J.LeftRoom,this.onLeftRoom),this.onEnabledChanged(),this.updateButton(),window.addEventListener("visibilitychange",this.onVisibilityChanged)}onDisable(){var e;this._net&&(this._net.stopSendingStream(this._outputStream),this._net.removeEventListener(Dn.StreamReceived,this.onReceiveStream),this._net.removeEventListener(Dn.StreamEnded,this.onStreamEnded),(e=this._net)==null||e.disable()),this.context.connection.stopListen(J.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(J.LeftRoom,this.onLeftRoom),this.onEnabledChanged(),this.updateButton(),window.removeEventListener("visibilitychange",this.onVisibilityChanged)}onDestroy(){var e;(e=this._menubutton)==null||e.remove(),this._menubutton=void 0}get isSending(){return this._outputStream!=null&&this._outputStream.active}async connect(e){var i,n;if(!this._net)return console.error("Cannot connect to voice chat - NetworkedStreams not initialized. Make sure the component is enabled before calling this method."),!1;if(this.context.connection.isConnected){if(!await exports.DeviceUtilities.microphonePermissionsGranted())return console.error("Cannot connect to voice chat - microphone permissions not granted"),this.updateButton(),!1}else return console.error("Cannot connect to voice chat - not connected to server"),this.updateButton(),!1;return this._allowSending=!0,(i=this._net)==null||i.stopSendingStream(this._outputStream),Ln(this._outputStream),this._outputStream=await this.getAudioStream(e),this._outputStream?(this.debug&&console.log("VOIP: Got audio stream"),(n=this._net)==null||n.startSendingStream(this._outputStream),this.updateButton(),!0):(this.updateButton(),await exports.DeviceUtilities.microphonePermissionsGranted()?console.error("VOIP: Could not get audio stream - please make sure to connect an audio device and grant microphone permissions"):Wc("Microphone permissions not granted: Please grant microphone permissions to use voice chat"),(this.debug||I())&&console.log("VOIP: Failed to get audio stream"),!1)}disconnect(e){var i;e!=null&&e.remember&&(this._allowSending=!1),(i=this._net)==null||i.stopSendingStream(this._outputStream),Ln(this._outputStream),this._outputStream=null,this.updateButton()}setMuted(e){var n;const i=(n=this._outputStream)==null?void 0:n.getAudioTracks();if(i)for(const o of i)o.enabled=!e}get isMuted(){var i;if(this._outputStream===null)return!1;const e=(i=this._outputStream)==null?void 0:i.getAudioTracks();if(e){for(const n of e)if(!n.enabled)return!0}return!1}async updateButton(){var e;if(this.createMenuButton){if(this._menubutton||(this._menubutton=document.createElement("button"),this._menubutton.addEventListener("click",()=>{this.isSending?this.disconnect({remember:!0}):this.connect(),exports.DeviceUtilities.microphonePermissionsGranted().then(i=>{i||pe("<strong>Microphone permissions not granted</strong>. Please allow your browser to use the microphone to be able to talk. Click on the button on the left side of your browser's address bar to allow microphone permissions.")})})),this._menubutton){this.context.menu.appendChild(this._menubutton),this.activeAndEnabled?this._menubutton.style.display="":this._menubutton.style.display="none",this._menubutton.title=this.isSending?"Click to disable your microphone":"Click to enable your microphone";let i=(this.isSending,""),n=this.isSending?"mic":"mic_off";await exports.DeviceUtilities.microphonePermissionsGranted()||(i="No Permission",n="mic_off",this._menubutton.title="Microphone permissions not granted. Please allow your browser to use the microphone to be able to talk. This can usually be done in the addressbar of the webpage."),this._menubutton.innerText=i,this._menubutton.prepend(bt(n)),this.context.connection.isConnected==!1?this._menubutton.setAttribute("disabled",""):this._menubutton.removeAttribute("disabled")}}else this.activeAndEnabled||(e=this._menubutton)==null||e.remove()}getFrequency(e){return this.unsupported_getfrequency||(this.unsupported_getfrequency=!0,I()&&pe("VOIP: getFrequency is currently not supported"),console.warn("VOIP: getFrequency is currently not supported")),null}async getAudioStream(e){if(!navigator.mediaDevices.getUserMedia)return console.error("No getDisplayMedia support"),null;const i=async o=>await navigator.mediaDevices.getUserMedia({audio:o??!0,video:!1}).catch(a=>(console.warn("VOIP failed getting audio stream",a),null)),n=await i(e);if(!n)return null;if(exports.DeviceUtilities.isiOS()&&(e==null?void 0:e.deviceId)===void 0){const a=(await navigator.mediaDevices.enumerateDevices()).find(l=>(l.kind==="audioinput"||l.kind==="audiooutput")&&!l.label.includes("iPhone"));if(a){const l=Object.assign({},e);return l.deviceId=a.deviceId,await i(l)}}return n}}yg([p()],wo.prototype,"autoConnect",2);yg([p()],wo.prototype,"runInBackground",2);yg([p()],wo.prototype,"createMenuButton",2);var zP=Object.defineProperty,NP=Object.getOwnPropertyDescriptor,Vv=(s,t,e,i)=>{for(var n=i>1?void 0:i?NP(t,e):t,o=s.length-1,a;o>=0;o--)(a=s[o])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&zP(t,e,n),n};const VP=x("debugmouth");class sh extends D{constructor(){super(...arguments);r(this,"idle",[]);r(this,"talking",[]);r(this,"marker",null);r(this,"voip",null);r(this,"lastMouthChangeTime",0);r(this,"mouthChangeLength",0)}awake(){setTimeout(()=>{this.voip=S.findObjectOfType(wo,this.context),this.marker||(this.marker=S.getComponentInParent(this.gameObject,it))},3e3)}update(){var n;if(!this.voip||this.context.time.frameCount%10!==0)return;let e=((n=this.marker)==null?void 0:n.connectionId)??null;if(!e){VP&&(e=null);return}const i=this.voip.getFrequency(e)??0;this.updateLips(i)}updateLips(e){if(this.context.time.time-this.lastMouthChangeTime>this.mouthChangeLength){if(this.mouthChangeLength=.05+Math.random()*.1,this.talking&&this.talking.length>0&&e>30){this.lastMouthChangeTime=this.context.time.time;const i=Math.floor(Math.random()*this.talking.length);this.setMouthShapeActive(this.talking,i)}else if(this.idle.length>0&&this.context.time.time-this.lastMouthChangeTime>.5){this.lastMouthChangeTime=this.context.time.time;const i=Math.floor(Math.random()*this.idle.length);this.setMouthShapeActive(this.idle,i)}}}setMouthShapeActive(e,i){if(e){e!=this.idle?this.idle.map(n=>n.visible=!1):this.talking.map(n=>n.visible=!1);for(let n=0;n<e.length;n++){const o=e[n];o&&(o.visible=n===i)}}}}Vv([p(h.Object3D)],sh.prototype,"idle",2);Vv([p(h.Object3D)],sh.prototype,"talking",2);class _g extends D{constructor(){super(...arguments);r(this,"voip",null);r(this,"marker",null);r(this,"_startPosition",null)}awake(){this.voip=S.findObjectOfType(wo,this.context),this.marker=S.getComponentInParent(this.gameObject,it)}update(){if(!this.voip||!this.marker||this.context.time.frameCount%10!==0)return;const e=this.marker.connectionId,i=this.voip.getFrequency(e);if(i==null)return;this._startPosition||(this._startPosition=this.gameObject.position.clone());const n=i/100;this.gameObject.position.y=this._startPosition.y+n*.07}}var $P=Object.defineProperty,WP=Object.getOwnPropertyDescriptor,HP=(s,t,e,i)=>{for(var n=i>1?void 0:i?WP(t,e):t,o=s.length-1,a;o>=0;o--)(a=s[o])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&$P(t,e,n),n};const na=x("debugxrflags"),$v=x("disablexrflags");$v&&console.warn("XRFlags are disabled");var kn=(s=>(s[s.Never=0]="Never",s[s.Browser=1]="Browser",s[s.AR=2]="AR",s[s.VR=4]="VR",s[s.FirstPerson=8]="FirstPerson",s[s.ThirdPerson=16]="ThirdPerson",s[s.All=4294967295]="All",s))(kn||{});const xy=class{constructor(){r(this,"Mask",17)}Has(t){return(this.Mask&t)!==0}Set(t){na&&console.warn("Set XR flag state to",t),this.Mask=t,yi.Apply()}Enable(t){this.Mask|=t,yi.Apply()}Disable(t){this.Mask&=~t,yi.Apply()}Toggle(t){this.Mask^=t,yi.Apply()}EnableAll(){this.Mask=-1,yi.Apply()}DisableAll(){this.Mask=0,yi.Apply()}};let Et=xy;r(Et,"Global",new xy);var Tl;const es=(Tl=class extends D{constructor(){super(...arguments);r(this,"visibleIn")}static Apply(){for(const t of this.registry)t.UpdateVisible(Et.Global)}awake(){es.registry.push(this)}onEnable(){es.firstApply?this.UpdateVisible(Et.Global):(es.firstApply=!0,es.Apply())}onDestroy(){const t=es.registry.indexOf(this);t>=0&&es.registry.splice(t,1)}get isOn(){return this.gameObject.visible}UpdateVisible(t=null){if($v)return;let e;const i=t;if(i&&typeof i=="number"&&(console.assert(typeof i=="number","XRFlag.UpdateVisible: state must be a number",i),na&&console.log(i),es.buffer.Mask=i,t=es.buffer),t instanceof Et?(na&&console.warn(this.name,"use passed in mask",t.Mask,this.visibleIn),e=t.Has(this.visibleIn)):(na&&console.log(this.name,"use global mask"),Et.Global.Has(this.visibleIn)),e!==void 0)if(e)na&&console.log(this.name,"is visible",this.gameObject.uuid),S.setActive(this.gameObject,!0);else{if(na&&console.log(this.name,"is not visible",this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},r(Tl,"registry",[]),r(Tl,"firstApply"),r(Tl,"buffer",new Et),Tl);let yi=es;HP([p()],yi.prototype,"visibleIn",2);var GP=Object.defineProperty,qP=Object.getOwnPropertyDescriptor,Fu=(s,t,e,i)=>{for(var n=i>1?void 0:i?qP(t,e):t,o=s.length-1,a;o>=0;o--)(a=s[o])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&GP(t,e,n),n};class vr extends D{constructor(){super(...arguments);r(this,"eyes",[]);r(this,"lastBlinkTime",0);r(this,"blinkLength",0);r(this,"eyesOpen",!0);r(this,"state",null)}awake(){this.state=S.getComponentInParent(this.gameObject,yi)}update(){if(!this.gameObject||!this.gameObject.visible||!this.eyes||!Array.isArray(this.eyes)||this.eyes.length===0)return;if(this.context.time.time-this.lastBlinkTime>this.blinkLength){if(this.lastBlinkTime=this.context.time.time,this.state&&!this.state.isOn||!this.activeAndEnabled)return;if(this.eyesOpen=!this.eyesOpen,this.blinkLength=Math.random(),this.eyesOpen?(this.blinkLength*=3,this.blinkLength+=.5,Math.random()<.1&&(this.blinkLength=.1+Math.random()*.2)):(this.blinkLength*=Math.random()*.2,this.blinkLength+=.1),Math.random()<.1&&(this.blinkLength*=3),this.blinkLength=Math.max(.2,this.blinkLength),this.blinkLength=Math.min(3,this.blinkLength),this.eyes)for(const i of this.eyes)i&&(i.visible=this.eyesOpen)}}}Fu([p(h.Object3D)],vr.prototype,"eyes",2);Fu([p()],vr.prototype,"lastBlinkTime",2);Fu([p()],vr.prototype,"blinkLength",2);Fu([p()],vr.prototype,"eyesOpen",2);var XP=Object.defineProperty,QP=Object.getOwnPropertyDescriptor,bg=(s,t,e,i)=>{for(var n=i>1?void 0:i?QP(t,e):t,o=s.length-1,a;o>=0;o--)(a=s[o])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&XP(t,e,n),n},vp;const Wv=(vp=class extends D{constructor(){super(...arguments);r(this,"head",null);r(this,"eyes",null);r(this,"target",null);r(this,"brain",null);r(this,"vec",new h.Vector3);r(this,"currentTargetPoint",new h.Vector3)}awake(){this.brain||(this.brain=S.getComponentInParent(this.gameObject,Ac)),this.brain||(this.brain=S.addComponent(this.gameObject,Ac)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}update(){const t=this.target;if(t&&this.head){const e=this.eyes;if(e){const i=Z(t);this.currentTargetPoint.lerp(i,this.context.time.deltaTime/.1);const n=Z(this.head),o=this.vec.copy(this.currentTargetPoint).sub(n).normalize();if(o.length()<.1)return;const a=Wv.forward;if(a.set(0,0,1),a.applyQuaternion(ye(this.head)),a.dot(o)>.45)for(let c=0;c<e.length;c++)e[c].lookAt(this.currentTargetPoint)}}}},r(vp,"forward",new h.Vector3(0,0,1)),vp);let Fa=Wv;bg([p(h.Object3D)],Fa.prototype,"head",2);bg([p(h.Object3D)],Fa.prototype,"eyes",2);bg([p(h.Object3D)],Fa.prototype,"target",2);var YP=Object.defineProperty,KP=Object.getOwnPropertyDescriptor,vg=(s,t,e,i)=>{for(var n=i>1?void 0:i?KP(t,e):t,o=s.length-1,a;o>=0;o--)(a=s[o])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&YP(t,e,n),n};class Ua extends D{constructor(){super(...arguments);r(this,"length",1);r(this,"depthTest",!0);r(this,"isGizmo",!1);r(this,"_axes",null)}onEnable(){if(this.isGizmo&&!qc)return;this._axes||(this._axes=new h.AxesHelper(this.length)),this._axes.layers.disableAll(),this._axes.layers.set(this.layer),this.gameObject.add(this._axes);const e=this._axes.material;e&&e.depthTest!==void 0&&(e.depthTest=this.depthTest)}onDisable(){this._axes&&this.gameObject.remove(this._axes)}}vg([p()],Ua.prototype,"length",2);vg([p()],Ua.prototype,"depthTest",2);vg([p()],Ua.prototype,"isGizmo",2);class wg extends D{constructor(){super(...arguments);r(this,"from");r(this,"to");r(this,"hint");r(this,"desiredDistance",1)}onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;const e=Z(this.to).clone(),i=Z(this.from).clone(),n=e.distanceTo(i),o=e.clone();o.sub(i);const a=i.clone();a.add(e),a.multiplyScalar(.5);const l=Z(this.hint).clone();l.sub(a);const c=new h.Vector3;c.crossVectors(l,o),c.crossVectors(o,c),c.normalize();const d=n*.5,u=Math.max(this.desiredDistance,d),f=Math.sqrt(u*u-d*d),m=c.clone();m.multiplyScalar(f),m.add(a),nt(this.gameObject,m);const g=a.clone();g.sub(c),this.gameObject.lookAt(g)}}const ZP=x("gizmos"),JP=x("debugboxhelper"),on=class extends D{constructor(){super(...arguments);r(this,"box",null);r(this,"_lastMatrixUpdateFrame",-1);r(this,"_helper",null);r(this,"_color",null)}isInBox(e){var n;if(!e)return;if(this.box||(this.box=new h.Box3),si([e],void 0,void 0,on.testBox),on.testBox.isEmpty()){const o=Z(e,on._position);on.testBox.setFromCenterAndSize(o,on._emptyObjectSize)}this.updateBox();const i=(n=this.box)==null?void 0:n.intersectsBox(on.testBox);return i&&JP&&N.DrawWireBox3(on.testBox,16711680,5),i}intersects(e){return e?this.updateBox(!1).intersectsBox(e):!1}updateBox(e=!1){if(this.box||(this.box=new h.Box3),e||this.context.time.frameCount!=this._lastMatrixUpdateFrame){const i=this._lastMatrixUpdateFrame<0;this._lastMatrixUpdateFrame=this.context.time.frameCount;const n=i,o=Z(this.gameObject,on._position,n),a=Ue(this.gameObject,on._size);this.box.setFromCenterAndSize(o,a)}return this.box}awake(){this._helper=null,this._color=null,this.box=null}showHelper(e=null,i=!1){var n;if(!(!ZP&&!i)){if(this._helper){e&&((n=this._color)==null||n.set(e)),this.gameObject.add(this._helper);return}this._helper=Ym(e),this.gameObject.add(this._helper)}}};let ti=on;r(ti,"testBox",new h.Box3),r(ti,"_position",new h.Vector3),r(ti,"_size",new h.Vector3(.01,.01,.01)),r(ti,"_emptyObjectSize",new h.Vector3(.01,.01,.01));var eO=Object.defineProperty,tO=Object.getOwnPropertyDescriptor,oi=(s,t,e,i)=>{for(var n=i>1?void 0:i?tO(t,e):t,o=s.length-1,a;o>=0;o--)(a=s[o])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&eO(t,e,n),n};class ri extends D{constructor(){super(...arguments);r(this,"attachedRigidbody",null);r(this,"isTrigger",!1);r(this,"sharedMaterial");r(this,"membership",[0]);r(this,"filter");r(this,"updateProperties",()=>{var e;(e=this.context.physics.engine)==null||e.updateProperties(this)})}get isCollider(){return!0}awake(){super.awake(),this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(fe))}start(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(fe))}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(fe))}onDisable(){var e;(e=this.context.physics.engine)==null||e.removeBody(this)}get body(){var e;return(e=this.context.physics.engine)==null?void 0:e.getBody(this)}updatePhysicsMaterial(){var e;(e=this.context.physics.engine)==null||e.updatePhysicsMaterial(this)}}oi([p(fe)],ri.prototype,"attachedRigidbody",2);oi([p()],ri.prototype,"isTrigger",2);oi([p()],ri.prototype,"sharedMaterial",2);oi([p()],ri.prototype,"membership",2);oi([p()],ri.prototype,"filter",2);class za extends ri{constructor(){super(...arguments);r(this,"radius",.5);r(this,"center",new h.Vector3(0,0,0))}onEnable(){var e;super.onEnable(),(e=this.context.physics.engine)==null||e.addSphereCollider(this),wu(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),Em(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}}oi([Pt(),p()],za.prototype,"radius",2);oi([p(h.Vector3)],za.prototype,"center",2);const Hv=class extends ri{constructor(){super(...arguments);r(this,"size",new h.Vector3(1,1,1));r(this,"center",new h.Vector3(0,0,0))}static add(t,e){const i=xi(t,Hv);return i.autoFit(),(e==null?void 0:e.rigidbody)===!0&&xi(t,fe,{isKinematic:!1}),i}onEnable(){var t;super.onEnable(),(t=this.context.physics.engine)==null||t.addBoxCollider(this,this.size),wu(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),Em(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}autoFit(t){const e=this.gameObject,i=e.position.clone(),n=e.quaternion.clone(),o=e.scale.clone(),a=e.parent;e.position.set(0,0,0),e.quaternion.set(0,0,0,1),e.scale.set(1,1,1),e.parent=null,e.updateMatrix();const l=si([e]);e.position.copy(i),e.quaternion.copy(n),e.scale.copy(o),e.parent=a,(t==null?void 0:t.debug)===!0&&N.DrawWireBox3(l,16768256,20),this.size=l.getSize(new h.Vector3)||new h.Vector3(1,1,1),this.center=l.getCenter(new h.Vector3)||new h.Vector3(0,0,0),this.size.length()<=0&&this.size.set(.01,.01,.01)}};let Na=Hv;oi([Pt(),p(h.Vector3)],Na.prototype,"size",2);oi([p(h.Vector3)],Na.prototype,"center",2);class xo extends ri{constructor(){super(...arguments);r(this,"sharedMesh");r(this,"convex",!1)}onEnable(){var i,n,o;if(super.onEnable(),!this.context.physics.engine)return;(i=this.sharedMesh)!=null&&i.isMesh||(this.gameObject instanceof h.Mesh||this.gameObject instanceof h.Group)&&(this.sharedMesh=this.gameObject);const e=0;if((n=this.sharedMesh)!=null&&n.isMesh)this.context.physics.engine.addMeshCollider(this,this.sharedMesh,this.convex),le.NEEDLE_progressive.assignMeshLOD(this.sharedMesh,e).then(a=>{a&&this.activeAndEnabled&&this.context.physics.engine&&this.sharedMesh&&(this.context.physics.engine.removeBody(this),this.sharedMesh.geometry=a,this.context.physics.engine.addMeshCollider(this,this.sharedMesh,this.convex))});else{const a=this.sharedMesh;if(a!=null&&a.isGroup){console.warn(`MeshCollider mesh is a group "${((o=this.sharedMesh)==null?void 0:o.name)||this.gameObject.name}", adding all children as colliders. This is currently not fully supported (colliders can not be removed from world again)`,this);const l=new Array;for(const c in a.children){const d=a.children[c];d.isMesh&&(this.context.physics.engine.addMeshCollider(this,d,this.convex),l.push(le.NEEDLE_progressive.assignMeshLOD(d,e)))}Promise.all(l).then(c=>{var u,f;if(c.some(m=>m)==!1)return;(u=this.context.physics.engine)==null||u.removeBody(this);const d=new h.Mesh;for(const m of c)m&&this.activeAndEnabled&&(d.geometry=m,(f=this.context.physics.engine)==null||f.addMeshCollider(this,d,this.convex))})}else(I()||x("showcolliders"))&&console.warn(`[MeshCollider] A MeshCollider mesh is assigned to an unknown object on "${this.gameObject.name}", but it's neither a Mesh nor a Group. Please double check that you attached the collider component to the right object and report a bug otherwise!`,this)}}}oi([p(h.Mesh)],xo.prototype,"sharedMesh",2);oi([p()],xo.prototype,"convex",2);class vs extends ri{constructor(){super(...arguments);r(this,"center",new h.Vector3(0,0,0));r(this,"radius",.5);r(this,"height",2)}onEnable(){var e;super.onEnable(),(e=this.context.physics.engine)==null||e.addCapsuleCollider(this,this.height,this.radius)}}oi([p(h.Vector3)],vs.prototype,"center",2);oi([p()],vs.prototype,"radius",2);oi([p()],vs.prototype,"height",2);var iO=Object.defineProperty,nO=Object.getOwnPropertyDescriptor,xs=(s,t,e,i)=>{for(var n=i>1?void 0:i?nO(t,e):t,o=s.length-1,a;o>=0;o--)(a=s[o])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&iO(t,e,n),n};const j_=x("debugcharactercontroller");class wr extends D{constructor(){super(...arguments);r(this,"center",new h.Vector3(0,0,0));r(this,"radius",.5);r(this,"height",2);r(this,"_rigidbody",null);r(this,"_activeGroundCollisions");r(this,"_contactVelocity",new h.Vector3)}get rigidbody(){return this._rigidbody?this._rigidbody:(this._rigidbody=this.gameObject.getComponent(fe),this._rigidbody||(this._rigidbody=this.gameObject.addComponent(fe)),this.rigidbody)}awake(){this._activeGroundCollisions=new Set}onEnable(){const e=this.rigidbody;let i=this.gameObject.getComponent(vs);i||(i=this.gameObject.addComponent(vs)),i.center.copy(this.center),i.radius=this.radius,i.height=this.height;const n=new h.Vector3(0,0,1),o=new h.Vector3(1,0,0),a=new h.Vector3(0,1,0),l=this.gameObject.getWorldDirection(new h.Vector3);l.y=0;const c=o.dot(l)<0?-1:1,d=n.angleTo(l)*c;this.gameObject.setRotationFromAxisAngle(a,d),e.lockRotationX=!0,e.lockRotationY=!0,e.lockRotationZ=!0}move(e){this.gameObject.position.add(e)}onCollisionEnter(e){(e.contacts.length==0||e.contacts.some(i=>i.normal.y>.2))&&(this._activeGroundCollisions.add(e),j_&&console.log(`Collision(${this._activeGroundCollisions.size}): ${e.contacts.map(i=>i.normal.y.toFixed(2)).join(", ")} - ${this.isGrounded}`))}onCollisionExit(e){this._activeGroundCollisions.delete(e),j_&&console.log(`Collision(${this._activeGroundCollisions.size}) - ${this.isGrounded}`)}get isGrounded(){return this._activeGroundCollisions.size>0}get contactVelocity(){var e;this._contactVelocity.set(0,0,0);for(const i of this._activeGroundCollisions){const n=(e=this.context.physics.engine)==null?void 0:e.getLinearVelocity(i.collider);n&&(this._contactVelocity.x+=n.x,this._contactVelocity.y+=n.y,this._contactVelocity.z+=n.z)}return this._contactVelocity}}xs([p(h.Vector3)],wr.prototype,"center",2);xs([p()],wr.prototype,"radius",2);xs([p()],wr.prototype,"height",2);class Ss extends D{constructor(){super(...arguments);r(this,"controller");r(this,"movementSpeed",2);r(this,"rotationSpeed",2);r(this,"jumpForce",1);r(this,"doubleJumpForce",2);r(this,"animator");r(this,"lookForward",!0);r(this,"lookInput",new h.Vector2(0,0));r(this,"moveInput",new h.Vector2(0,0));r(this,"jumpInput",!1);r(this,"_currentSpeed",new h.Vector3(0,0,0));r(this,"_currentAngularSpeed",new h.Vector3(0,0,0));r(this,"_temp",new h.Vector3(0,0,0));r(this,"_jumpCount",0);r(this,"_currentRotation");r(this,"_raycastOptions",new zn)}awake(){this._currentRotation=new h.Quaternion}update(){const e=this.context.input;e.isKeyPressed("KeyW")?this.moveInput.y+=1:e.isKeyPressed("KeyS")&&(this.moveInput.y-=1),e.isKeyPressed("KeyD")?this.lookInput.x+=1:e.isKeyPressed("KeyA")&&(this.lookInput.x-=1),this.jumpInput||(this.jumpInput=e.isKeyDown("Space"))}move(e){this.moveInput.add(e)}look(e){this.lookInput.add(e)}jump(){this.jumpInput=!0}onBeforeRender(){this.handleInput(this.moveInput,this.lookInput,this.jumpInput),this.lookInput.set(0,0),this.moveInput.set(0,0),this.jumpInput=!1}handleInput(e,i,n){var o,a,l,c,d,u,f,m,g,y,_;if((o=this.controller)!=null&&o.isGrounded&&(this._jumpCount=0,this.doubleJumpForce>0&&((a=this.animator)==null||a.setBool("doubleJump",!1))),this._currentSpeed.z+=e.y*this.movementSpeed*this.context.time.deltaTime,(l=this.animator)==null||l.setBool("running",e.length()>.01),(d=this.animator)==null||d.setBool("jumping",((c=this.controller)==null?void 0:c.isGrounded)===!0&&n),this._temp.copy(this._currentSpeed),this._temp.applyQuaternion(this.gameObject.quaternion),this.controller?this.controller.move(this._temp):this.gameObject.position.add(this._temp),this._currentAngularSpeed.y+=z.toRadians(-i.x*this.rotationSpeed)*this.context.time.deltaTime,this.lookForward&&Math.abs(this._currentAngularSpeed.y)<.01){const b=this.context.mainCameraComponent.forward;b.y=0,b.normalize(),this._currentRotation.setFromUnitVectors(new h.Vector3(0,0,1),b),this.gameObject.quaternion.slerp(this._currentRotation,this.context.time.deltaTime*10)}if(this.gameObject.rotateY(this._currentAngularSpeed.y),this._currentSpeed.multiplyScalar(1-this.context.time.deltaTime*10),this._currentAngularSpeed.y*=1-this.context.time.deltaTime*10,this.controller&&n&&this.jumpForce>0){let b=(u=this.controller)==null?void 0:u.isGrounded;if(this.doubleJumpForce>0&&!((f=this.controller)!=null&&f.isGrounded)&&this._jumpCount===1&&(b=!0,(m=this.animator)==null||m.setBool("doubleJump",!0)),b){this._jumpCount+=1;const v=this.controller.rigidbody,w=this._jumpCount===2?this.doubleJumpForce:this.jumpForce;v.applyImpulse(new h.Vector3(0,1,0).multiplyScalar(w))}}if(this.controller){const b=(g=this.controller)==null?void 0:g.rigidbody.getVelocity().y;if(b<-1){this._raycastOptions.ray||(this._raycastOptions.ray=new h.Ray),this._raycastOptions.ray.origin.copy(Z(this.gameObject)),this._raycastOptions.ray.direction.set(0,-1,0);const v=this.layer;this.gameObject.layers.disableAll(),this.gameObject.layers.set(2);const w=this.context.physics.raycast(this._raycastOptions);this.gameObject.layers.set(v),(w.length&&w[0].distance>2||b<-10)&&((y=this.animator)==null||y.setBool("falling",!0))}else(_=this.animator)==null||_.setBool("falling",!1)}}}xs([p(wr)],Ss.prototype,"controller",2);xs([p()],Ss.prototype,"movementSpeed",2);xs([p()],Ss.prototype,"rotationSpeed",2);xs([p()],Ss.prototype,"jumpForce",2);xs([p()],Ss.prototype,"doubleJumpForce",2);xs([p(St)],Ss.prototype,"animator",2);var sO=Object.defineProperty,oO=Object.getOwnPropertyDescriptor,Va=(s,t,e,i)=>{for(var n=i>1?void 0:i?oO(t,e):t,o=s.length-1,a;o>=0;o--)(a=s[o])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&sO(t,e,n),n};const _l=x("debugcontactshadows");Rv(s=>{const t=s.domElement.getAttribute("contactshadows")||s.domElement.getAttribute("contact-shadows");if(t!=null&&t!="0"&&t!="false"){console.debug("Auto-creating ContactShadows because of `contactshadows` attribute");const e=gn.auto(s),i=parseFloat(t);isNaN(i)||(e.opacity=i,e.darkness=i)}});var wp;const Vl=(wp=class extends D{constructor(){super(...arguments);r(this,"autoFit",!1);r(this,"darkness",.5);r(this,"opacity",.5);r(this,"blur",4);r(this,"occludeBelowGround",!1);r(this,"backfaceShadows",!0);r(this,"minSize");r(this,"manualUpdate",!1);r(this,"_needsUpdate",!1);r(this,"shadowsRoot",new h.Object3D);r(this,"shadowCamera");r(this,"shadowGroup",new h.Group);r(this,"renderTarget");r(this,"renderTargetBlur");r(this,"plane");r(this,"occluderMesh");r(this,"blurPlane");r(this,"depthMaterial");r(this,"horizontalBlurMaterial");r(this,"verticalBlurMaterial");r(this,"textureSize",512)}static auto(t){if(t||(t=Q.Current),!t)throw new Error("No context provided and no current context set.");let e=this._instances.get(t);if(!e||e.destroyed){const i=new h.Object3D;e=xi(i,Vl,{autoFit:!1,occludeBelowGround:!1}),this._instances.set(t,e)}return t.scene.add(e.gameObject),e.fitShadows(),e}set needsUpdate(t){this._needsUpdate=t}get needsUpdate(){return this._needsUpdate}fitShadows(){_l&&console.warn("Fitting shadows to scene"),Id(this.shadowsRoot,!1);const t=si(this.context.scene.children,[this.shadowsRoot]),e=Math.max(1,this.blur/32),i=t.max.x-t.min.x,n=t.max.z-t.min.z;t.expandByVector(new h.Vector3(e*i,0,e*n)),_l&&N.DrawWireBox3(t,16776960,60),this.gameObject.parent&&t.applyMatrix4(this.gameObject.parent.matrixWorld.clone().invert());const o=t.min,a=Math.max(1e-5,(t.max.y-o.y)*.002);t.max.y+=a,this.shadowsRoot.position.set((o.x+t.max.x)/2,o.y-a,(o.z+t.max.z)/2),this.shadowsRoot.scale.set(t.max.x-o.x,t.max.y-o.y,t.max.z-o.z),this.applyMinSize(),this.shadowsRoot.matrixWorldNeedsUpdate=!0,_l&&console.log("Fitted shadows to scene",this.shadowsRoot.scale.clone())}awake(){Vl._instances.set(this.context,this),this.shadowsRoot.hideFlags=Bu.DontExport,Id(this.shadowsRoot,!1)}start(){_l&&console.log("Create ContactShadows on "+this.gameObject.name,this),this.gameObject.add(this.shadowsRoot),this.shadowsRoot.add(this.shadowGroup),this.renderTarget=new h.WebGLRenderTarget(this.textureSize,this.textureSize),this.renderTarget.texture.generateMipmaps=!1,this.renderTargetBlur=new h.WebGLRenderTarget(this.textureSize,this.textureSize),this.renderTargetBlur.texture.generateMipmaps=!1;const t=new h.PlaneGeometry(1,1).rotateX(Math.PI/2);this.gameObject instanceof h.Mesh&&(console.warn("ContactShadows can not be added to a Mesh. Please add it to a Group or an empty Object"),hs(this.gameObject,!1));const e=new h.MeshBasicMaterial({map:this.renderTarget.texture,opacity:this.opacity,color:0,transparent:!0,depthWrite:!1,side:h.FrontSide});this.plane=new h.Mesh(t,e),this.plane.scale.y=-1,this.plane.layers.set(2),this.shadowsRoot.add(this.plane),this.plane&&(this.plane.renderOrder=1),this.occluderMesh=new h.Mesh(this.plane.geometry,new h.MeshBasicMaterial({depthWrite:!0,stencilWrite:!0,colorWrite:!1,side:h.BackSide})).translateY(-1e-4),this.occluderMesh.renderOrder=-100,this.occluderMesh.layers.set(2),this.shadowsRoot.add(this.occluderMesh),this.blurPlane=new h.Mesh(t),this.blurPlane.visible=!1,this.shadowGroup.add(this.blurPlane);const i=0,n=1;this.shadowCamera=new h.OrthographicCamera(-1/2,1/2,1/2,-1/2,i,n),this.shadowCamera.layers.enableAll(),this.shadowCamera.rotation.x=Math.PI/2,this.shadowGroup.add(this.shadowCamera),this.depthMaterial=new h.MeshDepthMaterial,this.depthMaterial.userData.darkness={value:this.darkness},this.depthMaterial.blending=h.CustomBlending,this.depthMaterial.blendEquation=h.MaxEquation,this.depthMaterial.onBeforeCompile=o=>{this.depthMaterial&&(o.uniforms.darkness=this.depthMaterial.userData.darkness,o.fragmentShader=`
933
933
  uniform float darkness;
934
934
  ${o.fragmentShader.replace("gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );","gl_FragColor = vec4( vec3( 1.0 ), ( 1.0 - fragCoordZ ) * darkness * opacity * (gl_FrontFacing ? 1.0 : 0.66) );")}
935
- `)},this.depthMaterial.depthTest=!1,this.depthMaterial.depthWrite=!1,this.horizontalBlurMaterial=new h.ShaderMaterial(Y.HorizontalBlurShader),this.horizontalBlurMaterial.depthTest=!1,this.verticalBlurMaterial=new h.ShaderMaterial(Y.VerticalBlurShader),this.verticalBlurMaterial.depthTest=!1,this.shadowGroup.visible=!1,this.autoFit?this.fitShadows():this.applyMinSize()}onDestroy(){var e,i,n,o,a,l,c,d;Vl._instances.get(this.context)===this&&Vl._instances.delete(this.context),(e=this.renderTarget)==null||e.dispose(),(i=this.renderTargetBlur)==null||i.dispose(),(n=this.depthMaterial)==null||n.dispose(),(o=this.horizontalBlurMaterial)==null||o.dispose(),(a=this.verticalBlurMaterial)==null||a.dispose(),(l=this.blurPlane)==null||l.geometry.dispose(),(c=this.plane)==null||c.geometry.dispose(),(d=this.occluderMesh)==null||d.geometry.dispose()}onBeforeRender(t){if(!this.renderTarget||!this.renderTargetBlur||!this.depthMaterial||!this.shadowCamera||!this.blurPlane||!this.shadowGroup||!this.plane||!this.horizontalBlurMaterial||!this.verticalBlurMaterial){_l&&console.error("ContactShadows: not initialized yet");return}const e=this.context.scene,i=this.context.renderer,n=i.getRenderTarget();this.shadowGroup.visible=!0,this.occluderMesh&&(this.occluderMesh.visible=!1);const o=this.plane.visible;this.plane.visible=!1,this.gameObject instanceof h.Mesh&&hs(this.gameObject,!1);const a=e.background;e.background=null,e.overrideMaterial=this.depthMaterial,this.backfaceShadows?this.depthMaterial.side=h.DoubleSide:this.depthMaterial.side=h.FrontSide;const l=i.getClearAlpha();i.setClearAlpha(0);const c=i.xr.enabled;i.xr.enabled=!1;const d=this.context.scene.matrixWorldAutoUpdate;this.context.scene.matrixWorldAutoUpdate=!1;const u=i.renderLists.get(e,0),f=u.transparent;B_.length=0,u.transparent=B_,Bf.length=0;for(const g of u.opaque){if(!g.object.visible)continue;const y=g.material;let _=g.material.colorWrite==!1||y.wireframe===!0||Kb(g.object)===!1;!_&&g.material.isLineMaterial&&(_=!0),!_&&g.material.isPointsMaterial&&(_=!0),_&&(Bf.push(g.object),g.object["needle:visible"]=g.object.visible,g.object.visible=!1)}i.setRenderTarget(this.renderTarget),i.clear(),i.render(e,this.shadowCamera),u.transparent=f;for(const g of Bf)g["needle:visible"]!=null&&(g.visible=g["needle:visible"]);e.overrideMaterial=null;const m=Math.max(this.blur,.05);this.blurShadow(m*2),this.blurShadow(m*.5),this.shadowGroup.visible=!1,this.occluderMesh&&(this.occluderMesh.visible=this.occludeBelowGround),this.plane.visible=o,i.setRenderTarget(n),i.setClearAlpha(l),e.background=a,i.xr.enabled=c,this.context.scene.matrixWorldAutoUpdate=d}blurShadow(t){if(!this.blurPlane||!this.shadowCamera||!this.renderTarget||!this.renderTargetBlur||!this.horizontalBlurMaterial||!this.verticalBlurMaterial)return;this.blurPlane.visible=!0;const e=this.shadowsRoot.worldScale,i=(e.x+e.z)/2,n=e.z/i,o=e.x/i;this.blurPlane.material=this.horizontalBlurMaterial,this.blurPlane.material.uniforms.tDiffuse.value=this.renderTarget.texture,this.horizontalBlurMaterial.uniforms.h.value=t*1/this.textureSize*n;const a=this.context.renderer,l=a.getRenderTarget();a.setRenderTarget(this.renderTargetBlur),a.render(this.blurPlane,this.shadowCamera),this.blurPlane.material=this.verticalBlurMaterial,this.blurPlane.material.uniforms.tDiffuse.value=this.renderTargetBlur.texture,this.verticalBlurMaterial.uniforms.v.value=t*1/this.textureSize*o,a.setRenderTarget(this.renderTarget),a.render(this.blurPlane,this.shadowCamera),this.blurPlane.visible=!1,a.setRenderTarget(l)}applyMinSize(){this.minSize&&this.shadowsRoot.scale.set(Math.max(this.minSize.x||0,this.shadowsRoot.scale.x),Math.max(this.minSize.y||0,this.shadowsRoot.scale.y),Math.max(this.minSize.z||0,this.shadowsRoot.scale.z))}},r(wp,"_instances",new Map),wp);let gn=Vl;Va([p()],gn.prototype,"autoFit",2);Va([p()],gn.prototype,"darkness",2);Va([p()],gn.prototype,"opacity",2);Va([p()],gn.prototype,"blur",2);Va([p()],gn.prototype,"occludeBelowGround",2);Va([p()],gn.prototype,"backfaceShadows",2);const B_=[],Bf=new Array,rO=x("logstats");class xg extends D{onEnable(){console.log(this),rO&&this.startCoroutine(this.run(),ve.OnAfterRender)}*run(){for(;this.enabled;){const t=this.context.renderer.info;console.log(t.memory,t.render,t.programs),yield}}}class oh extends D{constructor(){super(...arguments);r(this,"isUsed",!0);r(this,"usedBy",null)}}class Sg extends D{}const F_=x("debugdeletable"),bc=class extends ti{onEnable(){bc._instances.push(this)}onDisable(){const t=bc._instances.indexOf(this);t>=0&&bc._instances.splice(t,1)}};let nr=bc;r(nr,"_instances",[]);class Cg extends D{update(){for(const t of nr._instances){const e=this.gameObject;if(t.isInBox(e)===!0){const n=S.getComponentInParent(this.gameObject,oh);if(n)F_&&console.warn("DeleteBox: Not deleting object with usage marker",this.guid,n);else{if(F_)try{if(t.box){const o=t.box,a=ti.testBox;N.DrawWireBox3(o,16711680,5),N.DrawWireBox3(a,255,5),console.log("DeleteBox: Destroying",this.gameObject,{deleteBoxArea:o,deletedObjectArea:a})}else console.log("DeleteBox: Destroying",this.gameObject)}catch{}Gc(this.gameObject,this.context.connection)}}}}}var aO=Object.defineProperty,lO=Object.getOwnPropertyDescriptor,cO=(s,t,e,i)=>{for(var n=i>1?void 0:i?lO(t,e):t,o=s.length-1,a;o>=0;o--)(a=s[o])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&aO(t,e,n),n};class Uu extends D{constructor(){super(...arguments);r(this,"visibleOn")}onEnable(){this.apply()}apply(){this.test()||S.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:exports.DeviceUtilities.isMobileDevice()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}}cO([p()],Uu.prototype,"visibleOn",2);var hO=Object.defineProperty,dO=Object.getOwnPropertyDescriptor,xr=(s,t,e,i)=>{for(var n=i>1?void 0:i?dO(t,e):t,o=s.length-1,a;o>=0;o--)(a=s[o])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&hO(t,e,n),n};const In=x("debugdrag"),Ff=[];var Pg=(s=>(s[s.XZPlane=0]="XZPlane",s[s.Attached=1]="Attached",s[s.HitNormal=2]="HitNormal",s[s.DynamicViewAngle=3]="DynamicViewAngle",s[s.SnapToSurfaces=4]="SnapToSurfaces",s[s.None=5]="None",s))(Pg||{}),Al;const Ii=(Al=class extends D{constructor(){super(...arguments);r(this,"dragMode",3);r(this,"snapGridResolution",0);r(this,"keepRotation",!0);r(this,"xrDragMode",1);r(this,"xrKeepRotation",!1);r(this,"xrDistanceDragFactor",1);r(this,"showGizmo",!1);r(this,"_rigidbody",null);r(this,"_targetObject",null);r(this,"_dragHelper",null);r(this,"_draggingRigidbodies",[]);r(this,"_potentialDragStartEvt",null);r(this,"_dragHandlers",new Map);r(this,"_totalMovement",new h.Vector3);r(this,"_marker",null);r(this,"_isDragging",!1);r(this,"_didDrag",!1)}static get HasAnySelected(){return this._active>0}static get CurrentlySelected(){Ff.length=0;for(const t of this._instances)t._isDragging&&Ff.push(t);return Ff}get draggedObject(){return this._targetObject}setTargetObject(t){var i,n;this._targetObject=t;for(const o of this._dragHandlers.values())o.setTargetObject(t);const e="_rigidbody-was-kinematic";((i=this._rigidbody)==null?void 0:i[e])===!1&&(this._rigidbody.isKinematic=!1,this._rigidbody[e]=void 0),this._rigidbody=null,t&&(this._rigidbody=S.getComponentInChildren(t,fe),((n=this._rigidbody)==null?void 0:n.isKinematic)===!1&&(this._rigidbody.isKinematic=!0,this._rigidbody[e]=!1))}awake(){this._potentialDragStartEvt=null,this._dragHandlers=new Map,this._totalMovement=new h.Vector3,this._marker=null,this._isDragging=!1,this._didDrag=!1,this._dragHelper=null,this._draggingRigidbodies=[]}start(){this.gameObject.getComponentInParent(Pi)||this.gameObject.addComponent(Pi)}onEnable(){Ii._instances.push(this)}onDisable(){Ii._instances=Ii._instances.filter(t=>t!==this)}allowEdit(t=null){return this.context.connection.allowEditing}onPointerEnter(t){if(!this.allowEdit(this.gameObject)||t.mode!=="screen"||(t.event.mode==="tracked-pointer"||t.event.mode==="transient-pointer"?this.xrDragMode:this.dragMode)===5)return;const n=S.getComponentInParent(t.object,Ii);!n||n!==this||(Ii.lastHovered=t.object,this.context.domElement.style.cursor="pointer")}onPointerMove(t){(this._isDragging||this._potentialDragStartEvt!==null)&&t.use()}onPointerExit(t){this.allowEdit(this.gameObject)&&t.mode==="screen"&&Ii.lastHovered===t.object&&(this.context.domElement.style.cursor="auto")}onPointerDown(t){if(!(!this.allowEdit(this.gameObject)||t.used||(t.mode==="tracked-pointer"||t.mode==="transient-pointer"?this.xrDragMode:this.dragMode)===5)&&(Ii.lastHovered=t.object,t.button===0)){this._dragHandlers.size===0&&(this._didDrag=!1,this._totalMovement.set(0,0,0),this._potentialDragStartEvt=t),this._targetObject||this.setTargetObject(this.gameObject),Ii._active+=1;const n=new Uf(this,this._targetObject);if(this._dragHandlers.set(t.event.space,n),n.onDragStart(t),this._dragHandlers.size===2){const o=this._dragHandlers.values(),a=o.next().value,l=o.next().value;if(a instanceof Uf&&l instanceof Uf){const c=new uO(this,this._targetObject,a,l);this._dragHandlers.set(this.gameObject,c),c.onDragStart(t)}else console.error("Attempting to construct a MultiTouchDragHandler with invalid DragPointerHandlers. This is likely a bug.",{a,b:l})}t.use()}}onPointerUp(t){if(In&&N.DrawLabel(t.point??this.gameObject.worldPosition,"POINTERUP:"+t.pointerId+", "+t.button,.03,3),!this.allowEdit(this.gameObject)||t.button!==0)return;this._potentialDragStartEvt=null;const e=this._dragHandlers.get(t.event.space),i=this._dragHandlers.get(this.gameObject);i&&(i.handlerA===e||i.handlerB===e)&&(this._dragHandlers.delete(this.gameObject),i.onDragEnd(t)),e&&(Ii._active>0&&(Ii._active-=1),this.setTargetObject(null),e.onDragEnd&&e.onDragEnd(t),this._dragHandlers.delete(t.event.space),this._dragHandlers.size===0&&this.onLastDragEnd(t),t.use())}update(){for(const t of this._dragHandlers.values())t.collectMovementInfo&&t.collectMovementInfo(),t.getTotalMovement&&this._totalMovement.add(t.getTotalMovement());if(this._potentialDragStartEvt){if(!this._didDrag)if(this._totalMovement.length()>3e-4)this._didDrag=!0;else return;const t=this._potentialDragStartEvt;this._potentialDragStartEvt=null,this.onFirstDragStart(t)}for(const t of this._dragHandlers.values())t.onDragUpdate&&t.onDragUpdate(this._dragHandlers.size);this._dragHelper&&this._dragHelper.hasSelected&&this.onAnyDragUpdate()}onFirstDragStart(t){if(!t||!t.object)return;const e=S.getComponentInParent(t.object,Ii);if(!e||e!==this&&e._isDragging)return;const i=this._targetObject||this.gameObject;if(!i)return;this._isDragging=!0;const n=S.getComponentInChildren(i,Nn);In&&console.log("DRAG START",n,i),n&&(n.fastMode=!0,n==null||n.requestOwnership()),this._marker=S.addComponent(i,oh),this._draggingRigidbodies.length=0;const o=S.getComponentsInChildren(i,fe);o&&this._draggingRigidbodies.push(...o)}onAnyDragUpdate(){if(!this._dragHelper)return;this._dragHelper.showGizmo=this.showGizmo,this._dragHelper.onUpdate(this.context);for(const e of this._draggingRigidbodies)e.wakeUp(),e.resetVelocities(),e.resetForcesAndTorques();const t=this._targetObject||this.gameObject;Wi.markDirty(t)}onLastDragEnd(t){if(!this||!this._isDragging)return;this._isDragging=!1;for(const i of this._draggingRigidbodies)i.setVelocity(i.smoothedVelocity);if(this._draggingRigidbodies.length=0,this._targetObject=null,t!=null&&t.object){const i=S.getComponentInChildren(t.object,Nn);i&&(i.fastMode=!1)}if(this._marker&&this._marker.destroy(),!this._dragHelper)return;const e=this._dragHelper.selected;In&&console.log("DRAG END",e,e==null?void 0:e.visible),this._dragHelper.setSelected(null,this.context)}},r(Al,"_active",0),r(Al,"_instances",[]),r(Al,"lastHovered"),Al);let ii=Ii;xr([p()],ii.prototype,"dragMode",2);xr([p()],ii.prototype,"snapGridResolution",2);xr([p()],ii.prototype,"keepRotation",2);xr([p()],ii.prototype,"xrDragMode",2);xr([p()],ii.prototype,"xrKeepRotation",2);xr([p()],ii.prototype,"xrDistanceDragFactor",2);xr([p()],ii.prototype,"showGizmo",2);class uO{constructor(t,e,i,n){r(this,"handlerA");r(this,"handlerB");r(this,"context");r(this,"settings");r(this,"gameObject");r(this,"_handlerAAttachmentPoint",new h.Vector3);r(this,"_handlerBAttachmentPoint",new h.Vector3);r(this,"_followObject");r(this,"_manipulatorObject");r(this,"_deviceMode");r(this,"_followObjectStartWorldQuaternion",new h.Quaternion);r(this,"_manipulatorPosOffset",new h.Vector3);r(this,"_manipulatorRotOffset",new h.Quaternion);r(this,"_manipulatorScaleOffset",new h.Vector3);r(this,"_tempVec1",new h.Vector3);r(this,"_tempVec2",new h.Vector3);r(this,"_tempVec3",new h.Vector3);r(this,"tempLookMatrix",new h.Matrix4);r(this,"_initialScale",new h.Vector3);r(this,"_initialDistance",0);var a,l;this.context=t.context,this.settings=t,this.gameObject=e,this.handlerA=i,this.handlerB=n,this._followObject=new h.Object3D,this._manipulatorObject=new h.Object3D,this.context.scene.add(this._manipulatorObject);const o=(l=(a=G.active)==null?void 0:a.rig)==null?void 0:l.gameObject;if(!this.handlerA||!this.handlerB||!this.handlerA.hitPointInLocalSpace||!this.handlerB.hitPointInLocalSpace){console.error("Invalid: MultiTouchDragHandler needs two valid DragPointerHandlers with hitPointInLocalSpace set.");return}if(this._tempVec1.copy(this.handlerA.hitPointInLocalSpace),this._tempVec2.copy(this.handlerB.hitPointInLocalSpace),this.gameObject.localToWorld(this._tempVec1),this.gameObject.localToWorld(this._tempVec2),o&&(o.worldToLocal(this._tempVec1),o.worldToLocal(this._tempVec2)),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.02?(In&&console.log("Finding alternative drag attachment points since initial distance is too low: "+this._initialDistance.toFixed(2)),this.handlerA.followObject.parent.getWorldPosition(this._tempVec1),this.handlerB.followObject.parent.getWorldPosition(this._tempVec2),this._handlerAAttachmentPoint.copy(this._tempVec1),this._handlerBAttachmentPoint.copy(this._tempVec2),this.gameObject.worldToLocal(this._handlerAAttachmentPoint),this.gameObject.worldToLocal(this._handlerBAttachmentPoint),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.001&&(console.warn("Not supported right now – controller drag points for multitouch are too close!"),this._initialDistance=1)):(this._handlerAAttachmentPoint.copy(this.handlerA.hitPointInLocalSpace),this._handlerBAttachmentPoint.copy(this.handlerB.hitPointInLocalSpace)),this._tempVec3.lerpVectors(this._tempVec1,this._tempVec2,.5),this._initialScale.copy(e.scale),In){this._followObject.add(new h.AxesHelper(2)),this._manipulatorObject.add(new h.AxesHelper(5));const c=d=>`${d.x.toFixed(2)}, ${d.y.toFixed(2)}, ${d.z.toFixed(2)}`;N.DrawLine(this._tempVec1,this._tempVec2,65535,0,!1),N.DrawLabel(this._tempVec3,"A:B "+this._initialDistance.toFixed(2)+`
935
+ `)},this.depthMaterial.depthTest=!1,this.depthMaterial.depthWrite=!1,this.horizontalBlurMaterial=new h.ShaderMaterial(Y.HorizontalBlurShader),this.horizontalBlurMaterial.depthTest=!1,this.verticalBlurMaterial=new h.ShaderMaterial(Y.VerticalBlurShader),this.verticalBlurMaterial.depthTest=!1,this.shadowGroup.visible=!1,this.autoFit?this.fitShadows():this.applyMinSize()}onEnable(){this._needsUpdate=!0}onDestroy(){var e,i,n,o,a,l,c,d;Vl._instances.get(this.context)===this&&Vl._instances.delete(this.context),(e=this.renderTarget)==null||e.dispose(),(i=this.renderTargetBlur)==null||i.dispose(),(n=this.depthMaterial)==null||n.dispose(),(o=this.horizontalBlurMaterial)==null||o.dispose(),(a=this.verticalBlurMaterial)==null||a.dispose(),(l=this.blurPlane)==null||l.geometry.dispose(),(c=this.plane)==null||c.geometry.dispose(),(d=this.occluderMesh)==null||d.geometry.dispose()}onBeforeRender(t){if(this.manualUpdate&&!this._needsUpdate)return;if(this._needsUpdate=!1,!this.renderTarget||!this.renderTargetBlur||!this.depthMaterial||!this.shadowCamera||!this.blurPlane||!this.shadowGroup||!this.plane||!this.horizontalBlurMaterial||!this.verticalBlurMaterial){_l&&console.error("ContactShadows: not initialized yet");return}const e=this.context.scene,i=this.context.renderer,n=i.getRenderTarget();this.shadowGroup.visible=!0,this.occluderMesh&&(this.occluderMesh.visible=!1);const o=this.plane.visible;this.plane.visible=!1,this.gameObject instanceof h.Mesh&&hs(this.gameObject,!1);const a=e.background;e.background=null,e.overrideMaterial=this.depthMaterial,this.backfaceShadows?this.depthMaterial.side=h.DoubleSide:this.depthMaterial.side=h.FrontSide;const l=i.getClearAlpha();i.setClearAlpha(0);const c=i.xr.enabled;i.xr.enabled=!1;const d=this.context.scene.matrixWorldAutoUpdate;this.context.scene.matrixWorldAutoUpdate=!1;const u=i.renderLists.get(e,0),f=u.transparent;B_.length=0,u.transparent=B_,Bf.length=0;for(const g of u.opaque){if(!g.object.visible)continue;const y=g.material;let _=g.material.colorWrite==!1||y.wireframe===!0||Kb(g.object)===!1;!_&&g.material.isLineMaterial&&(_=!0),!_&&g.material.isPointsMaterial&&(_=!0),_&&(Bf.push(g.object),g.object["needle:visible"]=g.object.visible,g.object.visible=!1)}i.setRenderTarget(this.renderTarget),i.clear(),i.render(e,this.shadowCamera),u.transparent=f;for(const g of Bf)g["needle:visible"]!=null&&(g.visible=g["needle:visible"]);e.overrideMaterial=null;const m=Math.max(this.blur,.05);this.blurShadow(m*2),this.blurShadow(m*.5),this.shadowGroup.visible=!1,this.occluderMesh&&(this.occluderMesh.visible=this.occludeBelowGround),this.plane.visible=o,i.setRenderTarget(n),i.setClearAlpha(l),e.background=a,i.xr.enabled=c,this.context.scene.matrixWorldAutoUpdate=d}blurShadow(t){if(!this.blurPlane||!this.shadowCamera||!this.renderTarget||!this.renderTargetBlur||!this.horizontalBlurMaterial||!this.verticalBlurMaterial)return;this.blurPlane.visible=!0;const e=this.shadowsRoot.worldScale,i=(e.x+e.z)/2,n=e.z/i,o=e.x/i;this.blurPlane.material=this.horizontalBlurMaterial,this.blurPlane.material.uniforms.tDiffuse.value=this.renderTarget.texture,this.horizontalBlurMaterial.uniforms.h.value=t*1/this.textureSize*n;const a=this.context.renderer,l=a.getRenderTarget();a.setRenderTarget(this.renderTargetBlur),a.render(this.blurPlane,this.shadowCamera),this.blurPlane.material=this.verticalBlurMaterial,this.blurPlane.material.uniforms.tDiffuse.value=this.renderTargetBlur.texture,this.verticalBlurMaterial.uniforms.v.value=t*1/this.textureSize*o,a.setRenderTarget(this.renderTarget),a.render(this.blurPlane,this.shadowCamera),this.blurPlane.visible=!1,a.setRenderTarget(l)}applyMinSize(){this.minSize&&this.shadowsRoot.scale.set(Math.max(this.minSize.x||0,this.shadowsRoot.scale.x),Math.max(this.minSize.y||0,this.shadowsRoot.scale.y),Math.max(this.minSize.z||0,this.shadowsRoot.scale.z))}},r(wp,"_instances",new Map),wp);let gn=Vl;Va([p()],gn.prototype,"autoFit",2);Va([p()],gn.prototype,"darkness",2);Va([p()],gn.prototype,"opacity",2);Va([p()],gn.prototype,"blur",2);Va([p()],gn.prototype,"occludeBelowGround",2);Va([p()],gn.prototype,"backfaceShadows",2);const B_=[],Bf=new Array,rO=x("logstats");class xg extends D{onEnable(){console.log(this),rO&&this.startCoroutine(this.run(),ve.OnAfterRender)}*run(){for(;this.enabled;){const t=this.context.renderer.info;console.log(t.memory,t.render,t.programs),yield}}}class oh extends D{constructor(){super(...arguments);r(this,"isUsed",!0);r(this,"usedBy",null)}}class Sg extends D{}const F_=x("debugdeletable"),bc=class extends ti{onEnable(){bc._instances.push(this)}onDisable(){const t=bc._instances.indexOf(this);t>=0&&bc._instances.splice(t,1)}};let nr=bc;r(nr,"_instances",[]);class Cg extends D{update(){for(const t of nr._instances){const e=this.gameObject;if(t.isInBox(e)===!0){const n=S.getComponentInParent(this.gameObject,oh);if(n)F_&&console.warn("DeleteBox: Not deleting object with usage marker",this.guid,n);else{if(F_)try{if(t.box){const o=t.box,a=ti.testBox;N.DrawWireBox3(o,16711680,5),N.DrawWireBox3(a,255,5),console.log("DeleteBox: Destroying",this.gameObject,{deleteBoxArea:o,deletedObjectArea:a})}else console.log("DeleteBox: Destroying",this.gameObject)}catch{}Gc(this.gameObject,this.context.connection)}}}}}var aO=Object.defineProperty,lO=Object.getOwnPropertyDescriptor,cO=(s,t,e,i)=>{for(var n=i>1?void 0:i?lO(t,e):t,o=s.length-1,a;o>=0;o--)(a=s[o])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&aO(t,e,n),n};class Uu extends D{constructor(){super(...arguments);r(this,"visibleOn")}onEnable(){this.apply()}apply(){this.test()||S.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:exports.DeviceUtilities.isMobileDevice()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}}cO([p()],Uu.prototype,"visibleOn",2);var hO=Object.defineProperty,dO=Object.getOwnPropertyDescriptor,xr=(s,t,e,i)=>{for(var n=i>1?void 0:i?dO(t,e):t,o=s.length-1,a;o>=0;o--)(a=s[o])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&hO(t,e,n),n};const In=x("debugdrag"),Ff=[];var Pg=(s=>(s[s.XZPlane=0]="XZPlane",s[s.Attached=1]="Attached",s[s.HitNormal=2]="HitNormal",s[s.DynamicViewAngle=3]="DynamicViewAngle",s[s.SnapToSurfaces=4]="SnapToSurfaces",s[s.None=5]="None",s))(Pg||{}),Al;const Ii=(Al=class extends D{constructor(){super(...arguments);r(this,"dragMode",3);r(this,"snapGridResolution",0);r(this,"keepRotation",!0);r(this,"xrDragMode",1);r(this,"xrKeepRotation",!1);r(this,"xrDistanceDragFactor",1);r(this,"showGizmo",!1);r(this,"_rigidbody",null);r(this,"_targetObject",null);r(this,"_dragHelper",null);r(this,"_draggingRigidbodies",[]);r(this,"_potentialDragStartEvt",null);r(this,"_dragHandlers",new Map);r(this,"_totalMovement",new h.Vector3);r(this,"_marker",null);r(this,"_isDragging",!1);r(this,"_didDrag",!1)}static get HasAnySelected(){return this._active>0}static get CurrentlySelected(){Ff.length=0;for(const t of this._instances)t._isDragging&&Ff.push(t);return Ff}get draggedObject(){return this._targetObject}setTargetObject(t){var i,n;this._targetObject=t;for(const o of this._dragHandlers.values())o.setTargetObject(t);const e="_rigidbody-was-kinematic";((i=this._rigidbody)==null?void 0:i[e])===!1&&(this._rigidbody.isKinematic=!1,this._rigidbody[e]=void 0),this._rigidbody=null,t&&(this._rigidbody=S.getComponentInChildren(t,fe),((n=this._rigidbody)==null?void 0:n.isKinematic)===!1&&(this._rigidbody.isKinematic=!0,this._rigidbody[e]=!1))}awake(){this._potentialDragStartEvt=null,this._dragHandlers=new Map,this._totalMovement=new h.Vector3,this._marker=null,this._isDragging=!1,this._didDrag=!1,this._dragHelper=null,this._draggingRigidbodies=[]}start(){this.gameObject.getComponentInParent(Pi)||this.gameObject.addComponent(Pi)}onEnable(){Ii._instances.push(this)}onDisable(){Ii._instances=Ii._instances.filter(t=>t!==this)}allowEdit(t=null){return this.context.connection.allowEditing}onPointerEnter(t){if(!this.allowEdit(this.gameObject)||t.mode!=="screen"||(t.event.mode==="tracked-pointer"||t.event.mode==="transient-pointer"?this.xrDragMode:this.dragMode)===5)return;const n=S.getComponentInParent(t.object,Ii);!n||n!==this||(Ii.lastHovered=t.object,this.context.domElement.style.cursor="pointer")}onPointerMove(t){(this._isDragging||this._potentialDragStartEvt!==null)&&t.use()}onPointerExit(t){this.allowEdit(this.gameObject)&&t.mode==="screen"&&Ii.lastHovered===t.object&&(this.context.domElement.style.cursor="auto")}onPointerDown(t){if(!(!this.allowEdit(this.gameObject)||t.used||(t.mode==="tracked-pointer"||t.mode==="transient-pointer"?this.xrDragMode:this.dragMode)===5)&&(Ii.lastHovered=t.object,t.button===0)){this._dragHandlers.size===0&&(this._didDrag=!1,this._totalMovement.set(0,0,0),this._potentialDragStartEvt=t),this._targetObject||this.setTargetObject(this.gameObject),Ii._active+=1;const n=new Uf(this,this._targetObject);if(this._dragHandlers.set(t.event.space,n),n.onDragStart(t),this._dragHandlers.size===2){const o=this._dragHandlers.values(),a=o.next().value,l=o.next().value;if(a instanceof Uf&&l instanceof Uf){const c=new uO(this,this._targetObject,a,l);this._dragHandlers.set(this.gameObject,c),c.onDragStart(t)}else console.error("Attempting to construct a MultiTouchDragHandler with invalid DragPointerHandlers. This is likely a bug.",{a,b:l})}t.use()}}onPointerUp(t){if(In&&N.DrawLabel(t.point??this.gameObject.worldPosition,"POINTERUP:"+t.pointerId+", "+t.button,.03,3),!this.allowEdit(this.gameObject)||t.button!==0)return;this._potentialDragStartEvt=null;const e=this._dragHandlers.get(t.event.space),i=this._dragHandlers.get(this.gameObject);i&&(i.handlerA===e||i.handlerB===e)&&(this._dragHandlers.delete(this.gameObject),i.onDragEnd(t)),e&&(Ii._active>0&&(Ii._active-=1),this.setTargetObject(null),e.onDragEnd&&e.onDragEnd(t),this._dragHandlers.delete(t.event.space),this._dragHandlers.size===0&&this.onLastDragEnd(t),t.use())}update(){for(const t of this._dragHandlers.values())t.collectMovementInfo&&t.collectMovementInfo(),t.getTotalMovement&&this._totalMovement.add(t.getTotalMovement());if(this._potentialDragStartEvt){if(!this._didDrag)if(this._totalMovement.length()>3e-4)this._didDrag=!0;else return;const t=this._potentialDragStartEvt;this._potentialDragStartEvt=null,this.onFirstDragStart(t)}for(const t of this._dragHandlers.values())t.onDragUpdate&&t.onDragUpdate(this._dragHandlers.size);this._dragHelper&&this._dragHelper.hasSelected&&this.onAnyDragUpdate()}onFirstDragStart(t){if(!t||!t.object)return;const e=S.getComponentInParent(t.object,Ii);if(!e||e!==this&&e._isDragging)return;const i=this._targetObject||this.gameObject;if(!i)return;this._isDragging=!0;const n=S.getComponentInChildren(i,Nn);In&&console.log("DRAG START",n,i),n&&(n.fastMode=!0,n==null||n.requestOwnership()),this._marker=S.addComponent(i,oh),this._draggingRigidbodies.length=0;const o=S.getComponentsInChildren(i,fe);o&&this._draggingRigidbodies.push(...o)}onAnyDragUpdate(){if(!this._dragHelper)return;this._dragHelper.showGizmo=this.showGizmo,this._dragHelper.onUpdate(this.context);for(const e of this._draggingRigidbodies)e.wakeUp(),e.resetVelocities(),e.resetForcesAndTorques();const t=this._targetObject||this.gameObject;Wi.markDirty(t)}onLastDragEnd(t){if(!this||!this._isDragging)return;this._isDragging=!1;for(const i of this._draggingRigidbodies)i.setVelocity(i.smoothedVelocity);if(this._draggingRigidbodies.length=0,this._targetObject=null,t!=null&&t.object){const i=S.getComponentInChildren(t.object,Nn);i&&(i.fastMode=!1)}if(this._marker&&this._marker.destroy(),!this._dragHelper)return;const e=this._dragHelper.selected;In&&console.log("DRAG END",e,e==null?void 0:e.visible),this._dragHelper.setSelected(null,this.context)}},r(Al,"_active",0),r(Al,"_instances",[]),r(Al,"lastHovered"),Al);let ii=Ii;xr([p()],ii.prototype,"dragMode",2);xr([p()],ii.prototype,"snapGridResolution",2);xr([p()],ii.prototype,"keepRotation",2);xr([p()],ii.prototype,"xrDragMode",2);xr([p()],ii.prototype,"xrKeepRotation",2);xr([p()],ii.prototype,"xrDistanceDragFactor",2);xr([p()],ii.prototype,"showGizmo",2);class uO{constructor(t,e,i,n){r(this,"handlerA");r(this,"handlerB");r(this,"context");r(this,"settings");r(this,"gameObject");r(this,"_handlerAAttachmentPoint",new h.Vector3);r(this,"_handlerBAttachmentPoint",new h.Vector3);r(this,"_followObject");r(this,"_manipulatorObject");r(this,"_deviceMode");r(this,"_followObjectStartWorldQuaternion",new h.Quaternion);r(this,"_manipulatorPosOffset",new h.Vector3);r(this,"_manipulatorRotOffset",new h.Quaternion);r(this,"_manipulatorScaleOffset",new h.Vector3);r(this,"_tempVec1",new h.Vector3);r(this,"_tempVec2",new h.Vector3);r(this,"_tempVec3",new h.Vector3);r(this,"tempLookMatrix",new h.Matrix4);r(this,"_initialScale",new h.Vector3);r(this,"_initialDistance",0);var a,l;this.context=t.context,this.settings=t,this.gameObject=e,this.handlerA=i,this.handlerB=n,this._followObject=new h.Object3D,this._manipulatorObject=new h.Object3D,this.context.scene.add(this._manipulatorObject);const o=(l=(a=G.active)==null?void 0:a.rig)==null?void 0:l.gameObject;if(!this.handlerA||!this.handlerB||!this.handlerA.hitPointInLocalSpace||!this.handlerB.hitPointInLocalSpace){console.error("Invalid: MultiTouchDragHandler needs two valid DragPointerHandlers with hitPointInLocalSpace set.");return}if(this._tempVec1.copy(this.handlerA.hitPointInLocalSpace),this._tempVec2.copy(this.handlerB.hitPointInLocalSpace),this.gameObject.localToWorld(this._tempVec1),this.gameObject.localToWorld(this._tempVec2),o&&(o.worldToLocal(this._tempVec1),o.worldToLocal(this._tempVec2)),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.02?(In&&console.log("Finding alternative drag attachment points since initial distance is too low: "+this._initialDistance.toFixed(2)),this.handlerA.followObject.parent.getWorldPosition(this._tempVec1),this.handlerB.followObject.parent.getWorldPosition(this._tempVec2),this._handlerAAttachmentPoint.copy(this._tempVec1),this._handlerBAttachmentPoint.copy(this._tempVec2),this.gameObject.worldToLocal(this._handlerAAttachmentPoint),this.gameObject.worldToLocal(this._handlerBAttachmentPoint),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.001&&(console.warn("Not supported right now – controller drag points for multitouch are too close!"),this._initialDistance=1)):(this._handlerAAttachmentPoint.copy(this.handlerA.hitPointInLocalSpace),this._handlerBAttachmentPoint.copy(this.handlerB.hitPointInLocalSpace)),this._tempVec3.lerpVectors(this._tempVec1,this._tempVec2,.5),this._initialScale.copy(e.scale),In){this._followObject.add(new h.AxesHelper(2)),this._manipulatorObject.add(new h.AxesHelper(5));const c=d=>`${d.x.toFixed(2)}, ${d.y.toFixed(2)}, ${d.z.toFixed(2)}`;N.DrawLine(this._tempVec1,this._tempVec2,65535,0,!1),N.DrawLabel(this._tempVec3,"A:B "+this._initialDistance.toFixed(2)+`
936
936
  `+c(this._tempVec1)+`
937
937
  `+c(this._tempVec2),.03,5)}}onDragStart(t){this.gameObject.add(this._followObject),this._followObject.matrixAutoUpdate=!1,this._followObject.matrix.identity(),this._deviceMode=t.mode,this._followObjectStartWorldQuaternion.copy(this._followObject.worldQuaternion),this.alignManipulator(),this._manipulatorObject.attach(this._followObject),this._manipulatorPosOffset.copy(this._followObject.position),this._manipulatorRotOffset.copy(this._followObject.quaternion),this._manipulatorScaleOffset.copy(this._followObject.scale)}onDragEnd(t){if(!this.handlerA||!this.handlerB){console.error("onDragEnd called on MultiTouchDragHandler without valid handlers. This is likely a bug.");return}this.handlerA.recenter(),this.handlerB.recenter(),this._manipulatorObject.removeFromParent(),this._followObject.removeFromParent(),this._manipulatorObject.destroy(),this._followObject.destroy()}alignManipulator(){if(!this.handlerA||!this.handlerB){console.error("alignManipulator called on MultiTouchDragHandler without valid handlers. This is likely a bug.",this);return}if(!this.handlerA.followObject||!this.handlerB.followObject){console.error("alignManipulator called on MultiTouchDragHandler without valid follow objects. This is likely a bug.",this.handlerA,this.handlerB);return}this._tempVec1.copy(this._handlerAAttachmentPoint),this._tempVec2.copy(this._handlerBAttachmentPoint),this.handlerA.followObject.localToWorld(this._tempVec1),this.handlerB.followObject.localToWorld(this._tempVec2),this._tempVec3.lerpVectors(this._tempVec1,this._tempVec2,.5),this._manipulatorObject.position.copy(this._tempVec3);const t=this.context.mainCamera;this.tempLookMatrix.lookAt(this._tempVec3,this._tempVec2,t.worldUp),this._manipulatorObject.quaternion.setFromRotationMatrix(this.tempLookMatrix);const e=this._tempVec1.distanceTo(this._tempVec2);this._manipulatorObject.scale.copy(this._initialScale).multiplyScalar(e/this._initialDistance),this._manipulatorObject.updateMatrix(),this._manipulatorObject.updateMatrixWorld(!0),In&&(N.DrawLabel(this._tempVec3.clone().add(new h.Vector3(0,.2,0)),"A:B "+e.toFixed(2),.03),N.DrawLine(this._tempVec1,this._tempVec2,65280,0,!1))}onDragUpdate(){this.alignManipulator();const t=30,e=1;this._followObject.position.copy(this._manipulatorPosOffset),this._followObject.quaternion.copy(this._manipulatorRotOffset),this._followObject.scale.copy(this._manipulatorScaleOffset);const i=this.gameObject,n=this._followObject;if(!i){console.error("MultiTouchDragHandler has no dragged object. This is likely a bug.");return}n.updateMatrix(),n.updateMatrixWorld(!0);const a=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer"?this.settings.xrKeepRotation:this.settings.keepRotation;if(this.settings.snapGridResolution>0){const f=this._followObject.worldPosition,m=this.settings.snapGridResolution;f.x=Math.round(f.x/m)*m,f.y=Math.round(f.y/m)*m,f.z=Math.round(f.z/m)*m,this._followObject.worldPosition=f,this._followObject.updateMatrix()}a&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion,this._followObject.updateMatrix());const l=z.clamp01(this.context.time.deltaTime*t*e),c=i.worldPosition;c.lerp(n.worldPosition,l),i.worldPosition=c;const d=i.worldQuaternion;d.slerp(n.worldQuaternion,l),i.worldQuaternion=d;const u=i.worldScale;u.lerp(n.worldScale,l),i.worldScale=u}setTargetObject(t){this.gameObject=t}}class Uf{constructor(t,e){r(this,"context");r(this,"gameObject");r(this,"settings");r(this,"_lastRig");r(this,"_followObject");r(this,"_totalMovement",new h.Vector3);r(this,"_totalMovementAlongRayDirection",0);r(this,"_grabStartDistance",0);r(this,"_deviceMode");r(this,"_followObjectStartPosition",new h.Vector3);r(this,"_followObjectStartQuaternion",new h.Quaternion);r(this,"_followObjectStartWorldQuaternion",new h.Quaternion);r(this,"_lastDragPosRigSpace");r(this,"_tempVec",new h.Vector3);r(this,"_tempMat",new h.Matrix4);r(this,"_hitPointInLocalSpace",new h.Vector3);r(this,"_hitNormalInLocalSpace",new h.Vector3);r(this,"_bottomCenter",new h.Vector3);r(this,"_backCenter",new h.Vector3);r(this,"_backBottomCenter",new h.Vector3);r(this,"_bounds",new h.Box3);r(this,"_dragPlane",new h.Plane(new h.Vector3(0,1,0)));r(this,"_draggedOverObject",null);r(this,"_draggedOverObjectLastSetUp",null);r(this,"_draggedOverObjectLastNormal",new h.Vector3);r(this,"_draggedOverObjectDuration",0);r(this,"_hasLastSurfaceHitPoint",!1);r(this,"_lastSurfaceHitPoint",new h.Vector3);this.settings=t,this.context=t.context,this.gameObject=e,this._followObject=new h.Object3D}getTotalMovement(){return this._totalMovement}get followObject(){return this._followObject}get hitPointInLocalSpace(){return this._hitPointInLocalSpace}setTargetObject(t){this.gameObject=t}recenter(){var o,a;if(!this._followObject.parent){console.warn("Error: space follow object doesn't have parent but recenter() is called. This is likely a bug");return}if(!this.gameObject){console.warn("Error: space follow object doesn't have a gameObject");return}const t=this._followObject.parent;this.gameObject.add(this._followObject),this._followObject.matrixAutoUpdate=!1,this._followObject.position.set(0,0,0),this._followObject.quaternion.set(0,0,0,1),this._followObject.scale.set(1,1,1),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0),t.attach(this._followObject),this._followObjectStartPosition.copy(this._followObject.position),this._followObjectStartQuaternion.copy(this._followObject.quaternion),this._followObjectStartWorldQuaternion.copy(this._followObject.worldQuaternion),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);const e=this._hitPointInLocalSpace.clone();this.gameObject.localToWorld(e),this._grabStartDistance=e.distanceTo(t.worldPosition);const i=(a=(o=G.active)==null?void 0:o.rig)==null?void 0:a.gameObject,n=(i==null?void 0:i.worldScale.x)||1;this._grabStartDistance/=n,this._totalMovementAlongRayDirection=0,this._lastDragPosRigSpace=void 0,In&&(N.DrawLine(e,t.worldPosition,65280,.5,!1),N.DrawLabel(t.worldPosition.add(new h.Vector3(0,.1,0)),this._grabStartDistance.toFixed(2),.03,.5))}onDragStart(t){if(!this.gameObject){console.warn("Error: space follow object doesn't have a gameObject");return}if(t.event.space.add(this._followObject),this._lastDragPosRigSpace=void 0,t.point&&t.normal)this._hitPointInLocalSpace.copy(t.point),this.gameObject.worldToLocal(this._hitPointInLocalSpace),this._hitNormalInLocalSpace.copy(t.normal);else if(t){const _=t.event.space,b=_.worldPosition;this.gameObject.worldToLocal(b),this._hitPointInLocalSpace.copy(b);const v=_.worldUp;this._tempMat.copy(this.gameObject.matrixWorld).invert(),v.transformDirection(this._tempMat),this._hitNormalInLocalSpace.copy(v)}this.recenter(),this._totalMovement.set(0,0,0),this._deviceMode=t.mode;const i=this._followObject.parent.worldForward,o=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer"?this.settings.xrDragMode:this.settings.dragMode,a=this._hitPointInLocalSpace.clone();switch(this.gameObject.localToWorld(a),o){case 0:const _=new h.Vector3(0,1,0);this.gameObject.parent&&_.transformDirection(this.gameObject.parent.matrixWorld.clone().invert()),this._dragPlane.setFromNormalAndCoplanarPoint(_,a);break;case 2:const b=this._hitNormalInLocalSpace.clone();b.transformDirection(this.gameObject.matrixWorld),this._dragPlane.setFromNormalAndCoplanarPoint(b,a);break;case 1:this._dragPlane.setFromNormalAndCoplanarPoint(i,a);break;case 3:this.setPlaneViewAligned(a,!0);break;case 4:this.setPlaneViewAligned(a,!1);break}const l=this.gameObject.parent,c=this.gameObject.position.clone(),d=this.gameObject.quaternion.clone(),u=this.gameObject.scale.clone(),f=this.gameObject.matrixWorld.clone();l&&l.remove(this.gameObject),this.gameObject.position.set(0,0,0),this.gameObject.quaternion.set(0,0,0,1),this.gameObject.scale.set(1,1,1);const m=si([this.gameObject]);m.expandByPoint(this.gameObject.worldPosition);const g=new h.Vector3;m.getCenter(g);const y=new h.Vector3;m.getSize(y),this._bottomCenter.copy(g.clone().add(new h.Vector3(0,-y.y/2,0))),this._backCenter.copy(g.clone().add(new h.Vector3(0,0,y.z/2))),this._backBottomCenter.copy(g.clone().add(new h.Vector3(0,-y.y/2,y.z/2))),this._bounds.copy(m),l&&l.add(this.gameObject),this.gameObject.position.copy(c),this.gameObject.quaternion.copy(d),this.gameObject.scale.copy(u),this.gameObject.matrixWorld.copy(f),this._draggedOverObject=null,this._draggedOverObjectLastSetUp=null,this._draggedOverObjectLastNormal.set(0,1,0),this._draggedOverObjectDuration=0}collectMovementInfo(){var o,a;if(!this._followObject.parent)return;const t=this._followObject.parent;this._followObject.updateMatrix();const e=t.worldPosition,i=(a=(o=G.active)==null?void 0:o.rig)==null?void 0:a.gameObject;i&&i.worldToLocal(e),(this._lastDragPosRigSpace===void 0||i!=this._lastRig)&&(this._lastDragPosRigSpace=e.clone(),this._lastRig=i),this._tempVec.copy(e).sub(this._lastDragPosRigSpace);const n=t.worldForward;if(i&&(this._tempMat.copy(i.matrixWorld).invert(),n.transformDirection(this._tempMat)),this._totalMovementAlongRayDirection+=n.dot(this._tempVec),this._tempVec.x=Math.abs(this._tempVec.x),this._tempVec.y=Math.abs(this._tempVec.y),this._tempVec.z=Math.abs(this._tempVec.z),this._totalMovement.add(this._tempVec),this._lastDragPosRigSpace.copy(e),In){let l=e;i&&(l=l.clone(),l.transformDirection(i.matrixWorld)),N.DrawRay(l,n,255)}}onDragUpdate(t){if(t>1)return;const e=this.gameObject;if(!e||!this._followObject){console.warn("Warning: DragPointerHandler doesn't have a dragged object. This is likely a bug.");return}const i=this._followObject.parent;if(!i){console.warn("Warning: DragPointerHandler doesn't have a drag source. This is likely a bug.");return}this._followObject.updateMatrix();const n=i.worldPosition,o=i.worldForward,a=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer",l=a?this.settings.xrKeepRotation:this.settings.keepRotation,c=a?this.settings.xrDragMode:this.settings.dragMode;if(c===5)return;const d=10;l&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);let u=1,f=2;if(a&&this._grabStartDistance>.5){const w=1+this._totalMovementAlongRayDirection*(2*this.settings.xrDistanceDragFactor);u=Math.max(0,w),u=u*u*u}else this._grabStartDistance<=.5&&(f=3);this._followObject.position.copy(this._followObjectStartPosition),l||this._followObject.quaternion.copy(this._followObjectStartQuaternion),this._followObject.position.multiplyScalar(u),this._followObject.updateMatrix();const m=this._hasLastSurfaceHitPoint;this._hasLastSurfaceHitPoint=!1;const g=new h.Ray(n,o);if(c==4){const w=this.context.physics.raycastFromRay(g,{testObject:C=>C!==this.followObject&&C!==i&&C!==e});if(w.length>0){const C=w[0];if(this._draggedOverObject===C.object?this._draggedOverObjectDuration+=this.context.time.deltaTime:(this._draggedOverObject=C.object,this._draggedOverObjectDuration=0),C.face){this._hasLastSurfaceHitPoint=!0,this._lastSurfaceHitPoint.copy(C.point);const E=.15,O=this._draggedOverObjectDuration>=E,R=.001,A=this._totalMovement.length()>=R,j=$(C.normal||C.face.normal).applyQuaternion(C.object.worldQuaternion);if((O||A)&&(this._draggedOverObjectLastSetUp!==this._draggedOverObject||this._draggedOverObjectLastNormal.dot(j)<.999999||this.context.time.frame%60===0)){this._draggedOverObjectLastSetUp=this._draggedOverObject,this._draggedOverObjectLastNormal.copy(C.face.normal);const T=$(),B=$();this._bounds.getCenter(T),this._bounds.getSize(B),T.sub(B.multiplyScalar(.5).multiply(j)),this._hitPointInLocalSpace.copy(T),this._hitNormalInLocalSpace.copy(C.face.normal),this._bounds.getCenter(T),this._bounds.getSize(B),T.add(B.multiplyScalar(.5).multiply(C.face.normal));const F=$(this._hitPointInLocalSpace).add(T);this._followObject.localToWorld(F);const q=C.point;this._dragPlane.setFromNormalAndCoplanarPoint(j,q)}else if(!(O||A))return}}else m&&this.gameObject&&this.setPlaneViewAligned(this.gameObject.worldPosition,!1)}if(c!==1&&g.intersectPlane(this._dragPlane,this._tempVec)){this._followObject.worldPosition=this._tempVec,this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);const w=$(this._hitPointInLocalSpace);this._followObject.localToWorld(w),In&&N.DrawLine(w,this._tempVec,65535,0,!1),this._followObject.worldPosition=this._tempVec.multiplyScalar(2).sub(w),this._followObject.updateMatrix(),this._followObject.updateMatrix()}if(this.settings.snapGridResolution>0){const w=this._followObject.worldPosition,C=this.settings.snapGridResolution;w.x=Math.round(w.x/C)*C,w.y=Math.round(w.y/C)*C,w.z=Math.round(w.z/C)*C,this._followObject.worldPosition=w,this._followObject.updateMatrix()}l&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion,this._followObject.updateMatrix());const y=z.clamp01(this.context.time.deltaTime*d*f),_=z.clamp01(this.context.time.deltaTime*d*.5*f),b=e.worldPosition;b.lerp(this._followObject.worldPosition,y),e.worldPosition=b;const v=e.worldQuaternion;if(v.slerp(this._followObject.worldQuaternion,_),e.worldQuaternion=v,In){const w=this._hitPointInLocalSpace.clone();e.localToWorld(w),N.DrawSphere(w,.02,16711680);const C=this._hitNormalInLocalSpace.clone();C.applyQuaternion(v),N.DrawRay(w,C,16711680),N.DrawLabel(b.add(new h.Vector3(0,.25,0)),`Distance: ${this._totalMovement.length().toFixed(2)}
938
938
 
@@ -1266,7 +1266,7 @@ axisFormat %s
1266
1266
  outputColor = sharp;
1267
1267
  }
1268
1268
 
1269
- `;class e extends exports.MODULES.POSTPROCESSING.MODULE.Effect{constructor(){super("Sharpening",t,{vertexShader:s,blendFunction:exports.MODULES.POSTPROCESSING.MODULE.BlendFunction.NORMAL,uniforms:new Map([["amount",new h.Uniform$1(1)],["radius",new h.Uniform$1(1)]])})}}return e}var VE=Object.defineProperty,$E=Object.getOwnPropertyDescriptor,sl=(s,t,e,i)=>{for(var n=i>1?void 0:i?$E(t,e):t,o=s.length-1,a;o>=0;o--)(a=s[o])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&VE(t,e,n),n};class Xn extends Qe{constructor(){super(...arguments);r(this,"offset",new U(0));r(this,"rotation",new U(0));r(this,"focusArea",new U(.4));r(this,"feather",new U(.3));r(this,"kernelSize",new U(2));r(this,"resolutionScale",new U(1/window.devicePixelRatio))}get typeName(){return"TiltShiftEffect"}init(){this.offset.defaultValue=0,this.rotation.defaultValue=0,this.focusArea.defaultValue=.4,this.feather.defaultValue=.3,this.kernelSize.defaultValue=exports.MODULES.POSTPROCESSING.MODULE.KernelSize.MEDIUM,this.resolutionScale.defaultValue=1/window.devicePixelRatio}onCreateEffect(){const e=new exports.MODULES.POSTPROCESSING.MODULE.TiltShiftEffect({kernelSize:exports.MODULES.POSTPROCESSING.MODULE.KernelSize.VERY_LARGE,offset:this.offset.value,rotation:this.rotation.value,focusArea:this.focusArea.value,feather:this.feather.value});return this.offset.onValueChanged=i=>e.offset=i,this.rotation.onValueChanged=i=>e.rotation=i,this.focusArea.onValueChanged=i=>e.focusArea=i,this.feather.onValueChanged=i=>e.feather=i,this.kernelSize.onValueChanged=i=>e.blurPass.kernelSize=i,this.resolutionScale.onValueChanged=i=>e.resolution.scale=i/window.devicePixelRatio,e}}sl([p(U)],Xn.prototype,"offset",2);sl([p(U)],Xn.prototype,"rotation",2);sl([p(U)],Xn.prototype,"focusArea",2);sl([p(U)],Xn.prototype,"feather",2);sl([p(U)],Xn.prototype,"kernelSize",2);sl([p(U)],Xn.prototype,"resolutionScale",2);Ki("TiltShiftEffect",Xn);var WE=Object.defineProperty,HE=Object.getOwnPropertyDescriptor,sy=(s,t,e,i)=>{for(var n=i>1?void 0:i?HE(t,e):t,o=s.length-1,a;o>=0;o--)(a=s[o])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&WE(t,e,n),n};class Br extends Qe{constructor(){super(...arguments);r(this,"color",new U({r:0,g:0,b:0,a:1}));r(this,"intensity",new U(0));r(this,"center",new U({x:.5,y:.5}))}get typeName(){return"Vignette"}init(){this.color.defaultValue={r:0,g:0,b:0,a:1},this.intensity.defaultValue=0,this.center.defaultValue={x:.5,y:.5}}onCreateEffect(){const e=new exports.MODULES.POSTPROCESSING.MODULE.VignetteEffect;return this.intensity.onValueChanged=i=>{e.offset=i,this.updateDarkness(e)},this.color.onValueChanged=i=>{this.updateDarkness(e)},e}updateDarkness(e){const i=this.intensity.value;e.darkness=i}}sy([p(U)],Br.prototype,"color",2);sy([p(U)],Br.prototype,"intensity",2);sy([p(U)],Br.prototype,"center",2);Ki("Vignette",Br);globalThis.true=globalThis.true!==void 0?globalThis.true:!0;const Us=x("debugpost"),GE=x("debugpostpasses"),cp=Symbol("needle:postprocessing-handler"),hp=Symbol("needle:previous-autoclear-state");class oy{constructor(t){r(this,"_composer",null);r(this,"_lastVolumeComponents");r(this,"_effects",[]);r(this,"_isActive",!1);r(this,"context");r(this,"_menuEntry",null);r(this,"_passIndices",null);this.context=t}get isActive(){return this._isActive}get composer(){return this._composer}apply(t){return"env"in{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:ga&&ga.tagName.toUpperCase()==="SCRIPT"&&ga.src||new URL("needle-engine.bundle-a52706c5.umd.cjs",document.baseURI).href}&&{}.VITE_NEEDLE_USE_POSTPROCESSING==="false"?(Us?console.warn("Postprocessing is disabled via vite env setting"):console.debug("Postprocessing is disabled via vite env setting"),Promise.resolve()):(this._isActive=!0,this.onApply(this.context,t))}unapply(){var i;if(Us&&console.log("Unapplying postprocessing effects"),this._isActive=!1,this._lastVolumeComponents){for(const n of this._lastVolumeComponents)n.unapply();this._lastVolumeComponents.length=0}const t=this.context;t[cp]===this&&delete t[cp],t.composer===this._composer&&((i=t.composer)==null||i.dispose(),t.composer=null),typeof t.renderer[hp]=="boolean"&&(t.renderer.autoClear=t.renderer[hp])}dispose(){this.unapply();for(const t of this._effects)t.dispose();this._effects.length=0,this._composer=null}async onApply(t,e){if(!e)return;await Promise.all([exports.MODULES.POSTPROCESSING.load(),exports.MODULES.POSTPROCESSING_AO.load()]),t[cp]=this,Us&&console.log("Apply Postprocessing Effects",e),this._lastVolumeComponents=[...e],this._effects.length=0;const i={handler:this,components:this._lastVolumeComponents};for(let n=0;n<this._lastVolumeComponents.length;n++){const o=this._lastVolumeComponents[n];if(o.context=t,o.apply){if(o.active){if(!t.mainCameraComponent){console.error("No camera in scene found or available yet - can not create postprocessing effects");return}const a=o.apply(i);if(!a)continue;Array.isArray(a)?this._effects.push(...a):this._effects.push(a)}}else o.active&&pe("Volume component is not a VolumeComponent: "+o.__type)}if(this.context.renderer.toneMapping!=h.NoToneMapping&&!this._effects.find(n=>n instanceof exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect)){const n=new exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect;this._effects.push(n)}this.applyEffects(t)}applyEffects(t){const e=this._effects;if(e.length<=0)return;const i=t.mainCameraComponent,n=t.renderer,o=t.scene,a=i.threeCamera;n[hp]=n.autoClear,this._composer||(this._composer=new exports.MODULES.POSTPROCESSING.MODULE.EffectComposer(n,{frameBufferType:h.HalfFloatType,stencilBuffer:!0})),t.composer&&t.composer!==this._composer&&console.warn("There's already an active EffectComposer in your scene: replacing it with a new one. This might cause unexpected behaviour. Make sure to only use one PostprocessingManager/Volume in your scene."),t.composer=this._composer;const l=t.composer;l.setMainCamera(a),l.setRenderer(n),l.setMainScene(o);for(const d of l.passes)d.dispose();l.removeAllPasses();const c=new exports.MODULES.POSTPROCESSING.MODULE.RenderPass(o,a);if(c.name="Render To Screen",c.mainScene=o,l.addPass(c),GE){this.orderEffects();for(const d of e)if(d instanceof exports.MODULES.POSTPROCESSING.MODULE.Effect){const u=new exports.MODULES.POSTPROCESSING.MODULE.EffectPass(a,d);u.name=d.name,l.addPass(u)}else d instanceof exports.MODULES.POSTPROCESSING.MODULE.Pass,l.addPass(d)}else try{this.orderEffects();const d=[];for(const u of e)u instanceof exports.MODULES.POSTPROCESSING.MODULE.Effect?d.push(u):(u instanceof exports.MODULES.POSTPROCESSING.MODULE.Pass,l.addPass(u));if(d.length>0){const u=new exports.MODULES.POSTPROCESSING.MODULE.EffectPass(a,...d);u.name=d.map(f=>f.name).join(" "),u.mainScene=o,u.enabled=!0,l.addPass(u)}}catch(d){console.error("Error while applying postprocessing effects",d),l.removeAllPasses()}if(Us){console.log("[PostProcessing] Passes →",l.passes);const d=new exports.MODULES.POSTPROCESSING.MODULE.DepthEffect({blendFunction:exports.MODULES.POSTPROCESSING.MODULE.BlendFunction.NORMAL,inverted:!0});d.name="Depth Effect";const u=new exports.MODULES.POSTPROCESSING.MODULE.EffectPass(a,d);if(u.name="Depth Effect Pass",u.enabled=!1,l.passes.push(u),this._passIndices!==null){const m=[l.passes[0]];this._passIndices.length>0&&m.push(...this._passIndices.filter(g=>g!==0).map(g=>l.passes[g]).filter(g=>g)),m.length>0&&console.log("[PostProcessing] Passes (selected) →",m),l.passes.length=0;for(const g of m)g.enabled=!0,g.renderToScreen=!1,l.addPass(g)}const f=this.context.menu;if(f&&this._passIndices===null){this._menuEntry&&this._menuEntry.remove();const m=document.createElement("select");m.multiple=!0;const g=document.createElement("option");g.innerText="Final Output",g.value="-1",m.appendChild(g);for(const y of l.passes){const _=document.createElement("option");_.innerText=y.name,_.value=`${l.passes.indexOf(y)}`,_.title=y.name,m.appendChild(_)}f.appendChild(m),this._menuEntry=m,m.addEventListener("change",()=>{const y=Array.from(m.selectedOptions).map(_=>parseInt(_.value));y.length===1&&y[0]===-1?this._passIndices=null:this._passIndices=y,this.applyEffects(t)})}}}orderEffects(){var e;Us&&console.log("Before ordering effects",[...this._effects]),dp??(dp=[exports.MODULES.POSTPROCESSING.MODULE.NormalPass,exports.MODULES.POSTPROCESSING.MODULE.DepthDownsamplingPass,exports.MODULES.POSTPROCESSING.MODULE.SMAAEffect,exports.MODULES.POSTPROCESSING.MODULE.SSAOEffect,exports.MODULES.POSTPROCESSING_AO.MODULE.N8AOPostPass,exports.MODULES.POSTPROCESSING.MODULE.TiltShiftEffect,exports.MODULES.POSTPROCESSING.MODULE.DepthOfFieldEffect,exports.MODULES.POSTPROCESSING.MODULE.ChromaticAberrationEffect,exports.MODULES.POSTPROCESSING.MODULE.BloomEffect,exports.MODULES.POSTPROCESSING.MODULE.SelectiveBloomEffect,exports.MODULES.POSTPROCESSING.MODULE.VignetteEffect,exports.MODULES.POSTPROCESSING.MODULE.PixelationEffect,exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect,exports.MODULES.POSTPROCESSING.MODULE.HueSaturationEffect,exports.MODULES.POSTPROCESSING.MODULE.BrightnessContrastEffect]);const t=this._effects;t.sort((i,n)=>{const o=dp.findIndex(l=>i.constructor.name.endsWith(l.name)),a=dp.findIndex(l=>n.constructor.name.endsWith(l.name));return o<0?(Us&&console.warn("Unknown effect found: ",i.constructor.name),-1):a<0?(Us&&console.warn("Unknown effect found: ",n.constructor.name),1):o<0?1:a<0?-1:o-a}),Us&&console.log("After ordering effects",[...this._effects]);for(let i=0;i<t.length;i++){const n=t[i];if(((e=n==null?void 0:n.configuration)==null?void 0:e.gammaCorrection)!==void 0){const o=i===t.length-1;n.configuration.gammaCorrection=o}}}}let dp=null;var qE=Object.defineProperty,XE=Object.getOwnPropertyDescriptor,Uw=(s,t,e,i)=>{for(var n=i>1?void 0:i?XE(t,e):t,o=s.length-1,a;o>=0;o--)(a=s[o])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&qE(t,e,n),n};const Xr=x("debugpost");class ol extends D{constructor(){super(...arguments);r(this,"sharedProfile");r(this,"multisampling","auto");r(this,"_postprocessing");r(this,"_activeEffects",[]);r(this,"_effects",[]);r(this,"_componentEnabledTime",-1);r(this,"_multisampleAutoChangeTime",0);r(this,"_multisampleAutoDecreaseTime",0);r(this,"_lastApplyTime");r(this,"_rapidApplyCount",0);r(this,"_isDirty",!1);r(this,"_modificationQueue");r(this,"_recreateId",-1)}get isPostProcessingManager(){return!0}get effects(){return this._activeEffects}addEffect(e){let i=e;return i instanceof Qe||(i=new Lc(i)),i.gameObject===void 0&&this.gameObject.addComponent(i),this._effects.includes(i)||(this._effects.push(i),this._isDirty=!0),e}removeEffect(e){var n,o,a,l;let i=-1;if(e instanceof Qe?i=this._effects.indexOf(e):i=this._effects.findIndex(c=>c instanceof Lc&&c.effect===e),i!==-1)return this._effects.splice(i,1),this._isDirty=!0,e;if(e instanceof Qe){const c=(o=(n=this.sharedProfile)==null?void 0:n.components)==null?void 0:o.indexOf(e);c!==void 0&&c!==-1&&(this._isDirty=!0,(l=(a=this.sharedProfile)==null?void 0:a.components)==null||l.splice(c,1))}return e}markDirty(){this._isDirty=!0}awake(){var e;Xr&&(console.log("PostprocessingManager Awake",this),console.log("Press P to toggle post processing"),window.addEventListener("keydown",i=>{i.key==="p"&&(this.enabled=!this.enabled,Te("Toggle PostProcessing "+this.name+": Enabled="+this.enabled),this.markDirty())})),(e=this.sharedProfile)==null||e.__init(this)}onEnable(){this._componentEnabledTime=this.context.time.realtimeSinceStartup,this._isDirty=!0}onDisable(){var e;(e=this._postprocessing)==null||e.unapply(),this._isDirty=!1}onBeforeRender(){if(!this.context.isInXR&&(this.context.mainCamera&&this._isDirty&&this.apply(),this.context.composer&&this._postprocessing&&this._postprocessing.composer===this.context.composer)){this.context.renderer.getContext().isContextLost()&&this.context.renderer.forceContextRestore(),this.context.composer.getRenderer()!==this.context.renderer&&this.context.composer.setRenderer(this.context.renderer),this.context.composer.setMainScene(this.context.scene);const e=this.context.composer;if(this.multisampling==="auto"){const i=this.context.time.realtimeSinceStartup-this._multisampleAutoChangeTime;if(this.context.time.realtimeSinceStartup-this._componentEnabledTime>2&&i>.5){const n=e.multisampling;e.multisampling>0&&this.context.time.smoothedFps<=50?(this._multisampleAutoChangeTime=this.context.time.realtimeSinceStartup,this._multisampleAutoDecreaseTime=this.context.time.realtimeSinceStartup,e.multisampling*=.5,e.multisampling=Math.floor(e.multisampling),Xr&&console.debug(`[PostProcessing] Reduced multisampling from ${n} to ${e.multisampling}`)):i>1&&this.context.time.smoothedFps>=59&&e.multisampling<this.context.renderer.capabilities.maxSamples&&this.context.time.realtimeSinceStartup-this._multisampleAutoDecreaseTime>10&&(this._multisampleAutoChangeTime=this.context.time.realtimeSinceStartup,e.multisampling=e.multisampling<=0?1:e.multisampling*2,e.multisampling=Math.floor(e.multisampling),Xr&&console.debug(`[PostProcessing] Increased multisampling from ${n} to ${e.multisampling}`))}}else e.multisampling=Math.max(0,Math.min(this.multisampling,this.context.renderer.capabilities.maxSamples));if(this.context.mainCamera){const i=this.context.composer.passes;for(const n of i)if(n.mainCamera&&n.mainCamera!==this.context.mainCamera){this.context.composer.setMainCamera(this.context.mainCamera);break}}}}onDestroy(){var e;(e=this._postprocessing)==null||e.dispose()}apply(){var e,i;if(Xr&&console.log(`Apply PostProcessing "${this.name}"`),I()&&(this._lastApplyTime!==void 0&&Date.now()-this._lastApplyTime<100&&(this._rapidApplyCount++,this._rapidApplyCount===5&&console.warn("Detected rapid post processing modifications - this might be a bug",this)),this._lastApplyTime=Date.now()),this._isDirty=!1,this.unapply(),this._activeEffects.length=0,(e=this.sharedProfile)!=null&&e.components){const n=this.sharedProfile.components;for(const o of n)o.active&&o.enabled&&!this._activeEffects.includes(o)&&this._activeEffects.push(o)}for(const n of this._effects)n.active&&n.enabled&&!this._activeEffects.includes(n)&&this._activeEffects.push(n);this._activeEffects.length>0&&(this._postprocessing||(this._postprocessing=new oy(this.context)),(i=this._postprocessing.apply(this._activeEffects))==null||i.then(()=>{var o;if(!this.activeAndEnabled)return;this._applyPostQueue();const n=(o=this._postprocessing)==null?void 0:o.composer;n?(this.multisampling==="auto"?n.multisampling=exports.DeviceUtilities.isMobileDevice()?2:4:n.multisampling=Math.max(0,Math.min(this.multisampling,this.context.renderer.capabilities.maxSamples)),Xr&&console.debug(`[PostProcessing] Set multisampling to ${n.multisampling} (Is Mobile: ${exports.DeviceUtilities.isMobileDevice()})`)):Xr&&console.warn("[PostProcessing] No composer found")}))}unapply(){var e;(e=this._postprocessing)==null||e.unapply()}_applyPostQueue(){if(this._modificationQueue){for(const e of this._modificationQueue.values())this.onEditorModification(e);this._modificationQueue.clear()}}onEditorModification(e){var i,n;if(e.propertyName.startsWith("postprocessing.")){if(!this._postprocessing)return this._modificationQueue||(this._modificationQueue=new Map),this._modificationQueue.set(e.propertyName,e),!0;if(!((i=this._activeEffects)!=null&&i.length))return;const o=e.propertyName.split(".");if(o.length===3||o.length===4){const a=o[1],l=o[2];for(const c of this._activeEffects)if(((n=c.typeName)==null?void 0:n.toLowerCase())===a.toLowerCase()){if(l==="active"){c.active=e.value,this.scheduleRecreate();return}if(!od.has(a)){const d=new Array;od.set(a,d);const u=Object.keys(c);for(const f of u)c[f]instanceof U&&d.push(f)}if(od.has(a)){const d=l.toLowerCase(),u=od.get(a);for(const f of u)if(f.toLowerCase()===d){const m=c[f];m instanceof U&&(o.length===4&&o[3]==="active"?(m.overrideState=e.value,this.scheduleRecreate()):m&&m.value!==void 0&&(m.value=e.value));return}}console.warn("Unknown modification",l);return}}return!0}return!1}scheduleRecreate(){const e=++this._recreateId;setTimeout(()=>{e===this._recreateId&&(this.onDisable(),this.onEnable())},200)}}Uw([yr(Qu)],ol.prototype,"sharedProfile",2);Uw([yr()],ol.prototype,"multisampling",2);const od=new Map;tE(ol);async function ry(s){const{NeedleEngineHTMLElement:t}=await Promise.resolve().then(()=>VT);t.observedAttributes.includes(s)||t.observedAttributes.push(s)}var QE=Object.defineProperty,YE=Object.getOwnPropertyDescriptor,ft=(s,t,e,i)=>{for(var n=i>1?void 0:i?YE(t,e):t,o=s.length-1,a;o>=0;o--)(a=s[o])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&QE(t,e,n),n};const Rt=x("debugsceneswitcher"),KE=x("sceneswitcher:clearscene"),kd="scene";ry(kd);const zs=Promise.resolve(!1);class qe extends D{constructor(){super(...arguments);r(this,"autoLoadFirstScene",!0);r(this,"scenes",[]);r(this,"loadingScene");r(this,"queryParameterName","scene");r(this,"useSceneName",!0);r(this,"clamp",!0);r(this,"useHistory",!0);r(this,"useKeyboard",!0);r(this,"useSwipe",!0);r(this,"useSceneLighting",!0);r(this,"useSceneBackground",!0);r(this,"preloadNext",1);r(this,"preloadPrevious",1);r(this,"preloadConcurrent",2);r(this,"createMenuButtons",!1);r(this,"sceneLoadingStart",new ge);r(this,"sceneLoadingProgress",new ge);r(this,"sceneLoaded",new ge);r(this,"_currentIndex",-1);r(this,"_currentScene");r(this,"_engineElementOverserver");r(this,"_preloadScheduler");r(this,"_menuButtons");r(this,"onPopState",async e=>{if(!this.useHistory)return;const i=this.useHistory;try{this.useHistory=!1;let n=!1;if(this.queryParameterName&&(n=await this.tryLoadFromQueryParam()),!n){const o=e==null?void 0:e.state;if(o&&o.startsWith(this.guid)){const a=o.substr(this.guid.length+2);Rt&&console.log("PopState",a),await this.trySelectSceneFromValue(a)}}}finally{this.useHistory=i}});r(this,"normalizedSwipeThresholdX",.1);r(this,"_didSwipe",!1);r(this,"onInputPointerMove",e=>{if(this.useSwipe&&!this._didSwipe&&e.button===0&&e.pointerType==="touch"&&this.context.input.getPointerPressedCount()===1){const i=this.context.input.getPointerPositionDelta(e.button);if(i){const n=i.x/this.context.domWidth;n>=this.normalizedSwipeThresholdX?(this._didSwipe=!0,this.selectPrev()):n<=-this.normalizedSwipeThresholdX&&(this._didSwipe=!0,this.selectNext())}}});r(this,"onInputPointerUp",e=>{e.button===0&&(this._didSwipe=!1)});r(this,"onInputKeyDown",e=>{if(!this.useKeyboard||!this.scenes)return;const i=e.key.toLowerCase();if(!i)return;const n=parseInt(i)-1;if(n>=0){this.trySelectSceneFromValue(n);return}switch(i){case"arrowright":case"d":this.selectNext();break;case"arrowleft":case"a":this.selectPrev();break}});r(this,"__lastSwitchScene");r(this,"__lastSwitchScenePromise");r(this,"_currentlyLoadingScene");r(this,"_lastLoadingScene");r(this,"_loadingScenePromise");r(this,"_isCurrentlyLoading",!1);r(this,"_currentLoadingProgress")}get currentIndex(){return this._currentIndex}get currentLoadingProgress(){return this._currentLoadingProgress}get currentlyLoadingScene(){return this._currentlyLoadingScene}get currentlyLoadedScene(){return this._currentScene}awake(){this.scenes===void 0&&(this.scenes=[]);for(const e of this.scenes)e&&!e.hasUrl&&e.asset instanceof h.Object3D?S.remove(e.asset):e instanceof h.Object3D&&S.remove(e);Rt&&console.log("SceneSwitcher",this)}async onEnable(){if(globalThis.addEventListener("popstate",this.onPopState),this.context.input.addEventListener(Ee.KeyDown,this.onInputKeyDown),this.context.input.addEventListener(Ee.PointerMove,this.onInputPointerMove),this.context.input.addEventListener(Ee.PointerUp,this.onInputPointerUp),this._engineElementOverserver||(this._engineElementOverserver=new MutationObserver(e=>{for(const i of e)if(i.type==="attributes"&&i.attributeName===kd){const n=this.context.domElement.getAttribute(kd);n!==null&&this.trySelectSceneFromValue(n)}})),this._engineElementOverserver.observe(this.context.domElement,{attributes:!0}),this._preloadScheduler||(this._preloadScheduler=new ZE(this)),this._preloadScheduler.maxLoadAhead=this.preloadNext,this._preloadScheduler.maxLoadBehind=this.preloadPrevious,this._preloadScheduler.maxConcurrent=this.preloadConcurrent,this._preloadScheduler.begin(2e3),this.autoLoadFirstScene&&this._currentIndex===-1&&!await this.tryLoadFromQueryParam()){const e=this.context.domElement.getAttribute(kd);try{(e===null||!await this.trySelectSceneFromValue(e))&&this._currentIndex===-1&&this.select(0)}finally{}}this.createMenuButtons&&(this._menuButtons??(this._menuButtons=[]),this._menuButtons.push(this.context.menu.appendChild({label:"Previous",icon:"arrow_back_ios",onClick:()=>this.selectPrev(),priority:-1005,class:"row2"})),this._menuButtons.push(this.context.menu.appendChild({label:"Next",icon:"arrow_forward_ios",iconSide:"right",onClick:()=>this.selectNext(),priority:-1e3,class:"row2"})))}onDisable(){var e;if(globalThis.removeEventListener("popstate",this.onPopState),this.context.input.removeEventListener(Ee.KeyDown,this.onInputKeyDown),this.context.input.removeEventListener(Ee.PointerMove,this.onInputPointerMove),this.context.input.removeEventListener(Ee.PointerUp,this.onInputPointerUp),(e=this._preloadScheduler)==null||e.stop(),this._menuButtons){for(const i of this._menuButtons)i.remove();this._menuButtons=void 0}}addScene(e){if(typeof e=="string"){let i=this.context.addressables.findAssetReference(e);return i||(i=new ee(e),this.context.addressables.registerAssetReference(i)),this.scenes.push(i),i}return this.scenes.push(e),e}selectNext(){return this.select(this._currentIndex+1)}selectPrev(){return this.select(this._currentIndex-1)}select(e){var n,o,a;if(Rt&&console.log("select",e),typeof e=="object"&&console.warn('Switching to "'+e+'" might not work. Please either use an index or a AssetReference (not a scene reference)'),typeof e=="string"){const l=(n=this.scenes)==null?void 0:n.find(c=>c.url===e);if(!l){const c=ee.getOrCreate(this.sourceId??"",e,this.context);return this.switchScene(c)}if(l)e=(o=this.scenes)==null?void 0:o.indexOf(l);else return zs}if(!((a=this.scenes)!=null&&a.length))return zs;if(e<0){if(this.clamp)return zs;e=this.scenes.length-1}else if(e>=this.scenes.length){if(this.clamp)return zs;e=0}const i=this.scenes[e];return this.switchScene(i)}unload(){return this.__lastSwitchScene=void 0,this.__lastSwitchScenePromise=void 0,this.__unloadCurrentScene()}async reload(){if(this.__lastSwitchScene){const e=this.__lastSwitchScene;return this.__lastSwitchScene=void 0,this.switchScene(e)}return!1}async switchScene(e){var n;if(!(e instanceof ee)){const o=typeof e;if(o==="string")return this.select(e);if(o==="number")return this.select(e);if(e&&e instanceof h.Object3D){const a=(n=this.scenes)==null?void 0:n.indexOf(e);e=new ee(e.name,void 0,e),a>=0&&(this.scenes[a]=e)}else return console.warn(`[SceneSwitcher] Can't switch to scene of type ${o}`),!1}return e.url===this.sourceId?(console.warn("[SceneSwitcher] Can't load own scene - prevent recursive loading",this.sourceId),!1):this.__lastSwitchScene===e&&this.__lastSwitchScenePromise?this.__lastSwitchScenePromise:(this.__lastSwitchScene=e,this.__lastSwitchScenePromise=this.__internalSwitchScene(e),await this.__lastSwitchScenePromise)}async __unloadCurrentScene(){const e=this._currentScene;if(this._currentScene=void 0,e){Rt&&console.log("UNLOAD",e.url,"HasURL?: "+e.hasUrl);const i=this.tryGetSceneEventListener(e.asset);if(i!=null&&i.sceneClosing){const n=i.sceneClosing();n instanceof Promise&&await n}e.hasUrl?e.unload():e.asset instanceof h.Object3D&&S.remove(e.asset)}}async __internalSwitchScene(e){var n,o,a,l,c;await this.__unloadCurrentScene();const i=this._currentIndex=((n=this.scenes)==null?void 0:n.indexOf(e))??-1;try{this._currentlyLoadingScene=e,this._currentLoadingProgress=new ProgressEvent("progress",{loaded:0,total:1});const d=new CustomEvent("loadscene-start",{detail:{scene:e,switcher:this,index:i}});this.dispatchEvent(d),(o=this.sceneLoadingStart)==null||o.invoke(d.detail),await this.onStartLoading(),await e.loadAssetAsync((f,m)=>{var g;if(Rt){const y=m.loaded/m.total,_="["+"=".repeat(Math.floor(y*20))+"-".repeat(20-Math.floor(y*20))+"]";console.debug(`[SceneSwitcher] Download ${(y*100).toFixed(1)} % ${_}`,e.url)}this._currentLoadingProgress=m,this.dispatchEvent(m),(g=this.sceneLoadingProgress)==null||g.invoke(m)}).catch(console.error),await this.onEndLoading();const u=new CustomEvent("loadscene-finished",{detail:{scene:e,switcher:this,index:i}});if(this.dispatchEvent(u),this._currentLoadingProgress=void 0,this._currentlyLoadingScene=void 0,u.defaultPrevented)return Rt&&console.warn("Adding loaded scene prevented:",e,u),!1;if(!e.asset)return Rt&&console.warn("Failed loading scene:",e),!1;if(this._currentIndex===i){if(Rt&&console.log("ADD",e.url),this._currentScene=e,KE){const g=((a=this.context.mainCameraComponent)==null?void 0:a.gameObject)||this.context.mainCamera;g==null||g.removeFromParent();const y=this.gameObject.removeFromParent();Ci(this.context.scene,!0,!0),this.context.scene=new h.Scene,this.context.scene.add(y),g&&this.context.scene.add(g)}if(S.add(e.asset,this.gameObject),this.useSceneLighting&&this.context.sceneLighting.enable(e),this.useSceneBackground){const g=this.context.lightmaps.tryGetSkybox(e.url);g?(g.mapping=h.EquirectangularReflectionMapping,this.context.scene.background=g):Rt&&console.warn("SceneSwitcher: Can't find skybox for scene "+e.url)}if(this.useHistory&&i>=0){let g=i.toString();if(this.useSceneName&&(e instanceof h.Object3D?g=e.name:e.url&&(g=ub(e.url))),(l=this.queryParameterName)!=null&&l.length)Sc(this.queryParameterName,g,this.useHistory);else{const y=history.state,_=this.guid+"::"+i;y!==_&&history.pushState(_,"unused",location.href)}}const f=this.tryGetSceneEventListener(e.asset);if(f!=null&&f.sceneOpened){const g=f.sceneOpened(this);g instanceof Promise&&await g}const m=new CustomEvent("scene-opened",{detail:{scene:e,switcher:this,index:i}});return this.dispatchEvent(m),(c=this.sceneLoaded)==null||c.invoke(this),!0}}catch(d){console.error(d)}return!1}preload(e){if(e>=0&&e<this.scenes.length){const i=this.scenes[e];if(i instanceof ee)return i.preload()}return zs}tryLoadFromQueryParam(){var i;if(!((i=this.queryParameterName)!=null&&i.length))return zs;const e=x(this.queryParameterName);return typeof e=="boolean"?zs:this.trySelectSceneFromValue(e)}trySelectSceneFromValue(e){if(typeof e=="string"){const i=parseInt(e);if(i>=0&&i<this.scenes.length)return this.select(i);{const n=e.toLowerCase();for(let o=0;o<this.scenes.length;o++){const a=this.scenes[o];if(!a)continue;if((a instanceof h.Object3D?a.name:ub(a.url)).toLowerCase().includes(n))return this.select(o)}}}else if(typeof e=="number"&&e>=0&&e<this.scenes.length)return this.select(e);return Gt()&&console.warn('Can not find scene: "'+e+'"',this),zs}async onStartLoading(){var e,i;if(this._isCurrentlyLoading=!0,this.loadingScene&&(this._lastLoadingScene!==this.loadingScene&&(this._loadingScenePromise=void 0),this._lastLoadingScene=this.loadingScene,this._loadingScenePromise||(this._loadingScenePromise=(e=this.loadingScene)==null?void 0:e.loadAssetAsync().then(n=>n!=null)),await this._loadingScenePromise,this._isCurrentlyLoading&&((i=this.loadingScene)!=null&&i.asset))){Rt&&console.log("Add loading scene",this.loadingScene.url,this.loadingScene.asset);const n=this.loadingScene.asset;S.add(n,this.gameObject);const o=this.tryGetSceneEventListener(n);if(o!=null&&o.sceneOpened){const a=o.sceneOpened(this);a instanceof Promise&&await a}}if(this._isCurrentlyLoading){const n=this.tryGetSceneEventListener(this.gameObject);if(n&&n.sceneOpened){const o=n.sceneOpened(this);o instanceof Promise&&await o}}}async onEndLoading(){var e;if(this._isCurrentlyLoading=!1,(e=this.loadingScene)!=null&&e.asset){Rt&&console.log("Remove loading scene",this.loadingScene.url);const i=this.loadingScene.asset,n=this.tryGetSceneEventListener(i);if(typeof(n==null?void 0:n.sceneClosing)=="function"){const o=n.sceneClosing();o instanceof Promise&&await o}S.remove(i)}if(!this._isCurrentlyLoading){const i=this.tryGetSceneEventListener(this.gameObject);if(i&&i.sceneClosing){const n=i.sceneClosing();n instanceof Promise&&await n}}}tryGetSceneEventListener(e,i=0){if(!e)return null;const n=S.foreachComponent(e,o=>{const a=o;if(a.sceneClosing||a.sceneOpened)return a});if(i===0&&!n&&e.children.length)for(const o of e.children){const a=this.tryGetSceneEventListener(o,i+1);if(a)return a}return n||null}}ft([p()],qe.prototype,"autoLoadFirstScene",2);ft([p(ee)],qe.prototype,"scenes",2);ft([p(ee)],qe.prototype,"loadingScene",2);ft([p()],qe.prototype,"queryParameterName",2);ft([p()],qe.prototype,"useSceneName",2);ft([p()],qe.prototype,"clamp",2);ft([p()],qe.prototype,"useHistory",2);ft([p()],qe.prototype,"useKeyboard",2);ft([p()],qe.prototype,"useSwipe",2);ft([p()],qe.prototype,"useSceneLighting",2);ft([p()],qe.prototype,"useSceneBackground",2);ft([p()],qe.prototype,"preloadNext",2);ft([p()],qe.prototype,"preloadPrevious",2);ft([p()],qe.prototype,"preloadConcurrent",2);ft([p()],qe.prototype,"createMenuButtons",2);ft([p(ge)],qe.prototype,"sceneLoadingStart",2);ft([p(ge)],qe.prototype,"sceneLoadingProgress",2);ft([p(ge)],qe.prototype,"sceneLoaded",2);function ub(s){const t=s.split("/").pop(),e=t==null?void 0:t.split(".").shift();return e!=null&&e.length?e:s}class ZE{constructor(t,e=1,i=1,n=2){r(this,"maxLoadAhead");r(this,"maxLoadBehind");r(this,"maxConcurrent");r(this,"_isRunning",!1);r(this,"_switcher");r(this,"_loadTasks",[]);r(this,"_maxConcurrentLoads",1);this._switcher=t,this.maxLoadAhead=e,this.maxLoadBehind=i,this.maxConcurrent=n}begin(t){if(this._isRunning)return;Rt&&console.log("Preload begin",{delay:t}),this._isRunning=!0;let e=-10,i,n;const o=this._switcher.scenes,a=Date.now()+t,l=setInterval(()=>{if(this.allLoaded()&&(Rt&&console.log("All scenes (pre-)loaded"),this.stop()),!this._isRunning){clearInterval(l);return}if(Date.now()<a||this.canLoadNewScene()===!1)return;(e===-10||e!==this._switcher.currentIndex)&&(e=this._switcher.currentIndex,n=0,i=0);const c=n%2===0;c&&(i+=1),n+=1;const d=c?this.maxLoadAhead:this.maxLoadBehind;if(i>d)return;const u=c?e+i:e-i;if(!(u<0)&&!(u<0||u>=o.length)&&!this._loadTasks.some(f=>f.index===u)){const f=o[u];Rt&&console.log("Preload scene",{roomIndex:u,searchForward:c,lastRoom:e,currentIndex:this._switcher.currentIndex,tasks:this._loadTasks.length},f==null?void 0:f.url),new JE(u,f,this._loadTasks)}},200)}stop(){this._isRunning=!1}canLoadNewScene(){return this._loadTasks.length<this._maxConcurrentLoads}allLoaded(){if(this._switcher.scenes){for(const t of this._switcher.scenes)if(t!=null&&t.isLoaded&&t.isLoaded()===!1)return!1}return!0}}class JE{constructor(t,e,i){r(this,"index");r(this,"asset");r(this,"tasks");this.index=t,this.asset=e,this.tasks=i,i.push(this),this.awaitLoading()}async awaitLoading(){this.asset&&!this.asset.isLoaded()&&(Rt&&console.log("Preload start: "+this.asset.url,this.index),await this.asset.preload(),Rt&&console.log("Preload finished: "+this.asset.url,this.index));const t=this.tasks.indexOf(this);t>=0&&this.tasks.splice(t,1)}}function ek(){return new Promise((s,t)=>{const i=()=>{i!=null&&(document.removeEventListener("pointerdown",i),document.removeEventListener("click",i),document.removeEventListener("dragstart",i),document.removeEventListener("touchstart",i),s())};document.addEventListener("pointerdown",i),document.addEventListener("click",i),document.addEventListener("dragstart",i),document.addEventListener("touchstart",i)})}async function tk(s){await ek(),s()}var ik=Object.defineProperty,nk=Object.getOwnPropertyDescriptor,Ei=(s,t,e,i)=>{for(var n=i>1?void 0:i?nk(t,e):t,o=s.length-1,a;o>=0;o--)(a=s[o])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&ik(t,e,n),n};const at=x("debugvideo");var zw=(s=>(s[s.None=0]="None",s[s.AdjustHeight=1]="AdjustHeight",s[s.AdjustWidth=2]="AdjustWidth",s))(zw||{}),Nw=(s=>(s[s.VideoClip=0]="VideoClip",s[s.Url=1]="Url",s))(Nw||{}),Vw=(s=>(s[s.CameraFarPlane=0]="CameraFarPlane",s[s.CameraNearPlane=1]="CameraNearPlane",s[s.RenderTexture=2]="RenderTexture",s[s.MaterialOverride=3]="MaterialOverride",s))(Vw||{});class st extends D{constructor(){super();r(this,"playOnAwake",!0);r(this,"aspectMode",0);r(this,"clip",null);r(this,"source",1);r(this,"_url",null);r(this,"renderMode");r(this,"targetMaterialProperty");r(this,"targetMaterialRenderer");r(this,"targetTexture");r(this,"time",0);r(this,"_playbackSpeed",1);r(this,"_isLooping",!1);r(this,"_muted",!1);r(this,"_audioOutputMode",2);r(this,"playInBackground",!0);r(this,"_crossOrigin","anonymous");r(this,"_videoElement",null);r(this,"_videoTexture",null);r(this,"_videoMaterial",null);r(this,"_isPlaying",!1);r(this,"wasPlaying",!1);r(this,"visibilityChanged",e=>{switch(document.visibilityState){case"hidden":this.playInBackground||(this.wasPlaying=this._isPlaying,this.pause());break;case"visible":this.wasPlaying&&!this._isPlaying&&this.play();break}});r(this,"_receivedInput",!1);r(this,"_overlay",null);r(this,"_targetObjects");r(this,"_updateAspectRoutineId",-1);r(this,"_hls");r(this,"onHlsAvailable",()=>{var e;at&&console.log("HLS: available",this.clip),!(!this.shouldUseM3U||!this.url)&&(this._hls||(this._hls=new Hls),this.videoElement.autoplay=!0,this._hls.loadSource(this.url),this._hls.attachMedia(this.videoElement),(e=this._videoElement)==null||e.play(),at&&console.log("HLS: loaded",this.clip))});tk(()=>{this._receivedInput=!0,this.updateVideoElementSettings()}),this._targetObjects=[],x("videoscreenspace")&&window.addEventListener("keydown",e=>{e.key==="f"&&(this.screenspace=!this.screenspace)})}get url(){return this._url}set url(e){const n=this._url!==e;this.__didAwake?n&&this.setClipURL(e??""):this._url=e}get playbackSpeed(){var e;return((e=this._videoElement)==null?void 0:e.playbackRate)??this._playbackSpeed}set playbackSpeed(e){this._playbackSpeed=e,this._videoElement&&(this._videoElement.playbackRate=e)}get isLooping(){var e;return((e=this._videoElement)==null?void 0:e.loop)??this._isLooping}set isLooping(e){this._isLooping=e,this._videoElement&&(this._videoElement.loop=e)}get currentTime(){var e;return((e=this._videoElement)==null?void 0:e.currentTime)??this.time}set currentTime(e){this._videoElement?this._videoElement.currentTime=e:this.time=e}get isPlaying(){const e=this._videoElement;if(e){if(e.currentTime>0&&!e.paused&&!e.ended&&e.readyState>e.HAVE_CURRENT_DATA)return!0;if(e.srcObject&&e.srcObject.active)return!0}return!1}get crossOrigin(){var e;return((e=this._videoElement)==null?void 0:e.crossOrigin)??this._crossOrigin}set crossOrigin(e){this._crossOrigin=e,this._videoElement&&(e!==null?this._videoElement.setAttribute("crossorigin",e):this._videoElement.removeAttribute("crossorigin"))}get videoMaterial(){return!this._videoMaterial&&!this.create(!1)?null:this._videoMaterial}get videoTexture(){return!this._videoTexture&&!this.create(!1)?null:this._videoTexture}get videoElement(){return!this._videoElement&&!this.create(!1)?null:this._videoElement}requestPictureInPicture(){return this._videoElement?this._videoElement.requestPictureInPicture():null}get muted(){var e;return((e=this._videoElement)==null?void 0:e.muted)??this._muted}set muted(e){this._muted=e,this._videoElement&&(this._videoElement.muted=e)}get currentVideo(){return this.clip}set audioOutputMode(e){e!==this._audioOutputMode&&(e===1&&I()&&console.warn("VideoAudioOutputMode.AudioSource is not yet implemented"),this._audioOutputMode=e,this.updateVideoElementSettings())}get audioOutputMode(){return this._audioOutputMode}preloadVideo(){at&&console.log("Video Preload: "+this.name,this.clip),this.create(!1)}preload(){this.preloadVideo()}setVideo(e){this.clip=e,this.source=0,this._videoElement?(this._videoElement.srcObject=e,this._isPlaying&&this.play(),this.updateAspect()):this.create(this.playOnAwake)}setClipURL(e){this._url!==e&&(this._url=e,this.source=1,at&&console.log("set url",e),this._videoElement?e.endsWith(".m3u8")||e.includes(".m3u")?this.ensureM3UCanBePlayed():(this._videoElement.src=e,this._isPlaying&&(this.stop(),this.play())):this.create(this.playOnAwake))}onEnable(){var e,i;at&&console.log("VideoPlayer.onEnable",Nw[this.source],this.clip,this.url,this),window.addEventListener("visibilitychange",this.visibilityChanged),this.playOnAwake===!0?this.create(!0):this.preloadVideo(),this.screenspace?(e=this._overlay)==null||e.start():(i=this._overlay)==null||i.stop()}onDisable(){var e;window.removeEventListener("visibilitychange",this.visibilityChanged),(e=this._overlay)==null||e.stop(),this.pause()}onDestroy(){var e;this._videoElement&&((e=this.videoElement)==null||e.remove(),this._videoElement=null),this._videoTexture&&(this._videoTexture.dispose(),this._videoTexture=null)}play(){var e,i;if(this._videoElement||this.create(!1),!this._videoElement){at&&console.warn("Can not play: no video element found",this);return}if(!(this._isPlaying&&!((e=this._videoElement)!=null&&e.ended)&&!((i=this._videoElement)!=null&&i.paused))){if(this._isPlaying=!0,this._receivedInput||(this._videoElement.muted=!0),this.handleBeginPlaying(!1),this.shouldUseM3U){this.ensureM3UCanBePlayed();return}at&&console.log("Video Play()",this.clip,this._videoElement,this.time),this._videoElement.currentTime=this.time,this._videoElement.play().catch(n=>{var o;console.log(n),at&&console.error("Error playing video",n,"CODE="+n.code,(o=this.videoElement)==null?void 0:o.src,this),setTimeout(()=>{this._isPlaying&&!this.destroyed&&this.activeAndEnabled&&this.play()},1e3)}),at&&console.log("play",this._videoElement,this.time)}}stop(){this._isPlaying=!1,this.time=0,this._videoElement&&(this._videoElement.currentTime=0,this._videoElement.pause(),at&&console.log("STOP",this))}pause(){var e,i;this.time=((e=this._videoElement)==null?void 0:e.currentTime)??0,this._isPlaying=!1,(i=this._videoElement)==null||i.pause(),at&&console.log("PAUSE",this,this.currentTime)}create(e){let i;switch(this.source){case 0:i=this.clip;break;case 1:i=this.url,!(i!=null&&i.length)&&typeof this.clip=="string"&&(i=this.clip);break}return i?(this._videoElement||(at&&console.warn("Create VideoElement",this),this._videoElement=this.createVideoElement(),this.context.domElement.shadowRoot.prepend(this._videoElement),this.updateVideoElementStyles()),typeof i=="string"?(at&&console.log("Set Video src",i),this._videoElement.src=i):(at&&console.log("Set Video srcObject",i),this._videoElement.srcObject=i),this._videoTexture||(this._videoTexture=new h.VideoTexture(this._videoElement)),this._videoTexture.flipY=!1,this._videoTexture.colorSpace=h.SRGBColorSpace,e&&this.handleBeginPlaying(e),at&&console.log("Video: handle playing done...",i,e),!0):(at&&console.warn("No video source set",this),!1)}updateAspect(){this.aspectMode!==0&&this.startCoroutine(this.updateAspectImpl())}get screenspace(){var e;return((e=this._overlay)==null?void 0:e.enabled)??!1}set screenspace(e){var i;if(e){if(!this._videoTexture)return;this._overlay||(this._overlay=new sk(this.context)),this._overlay.add(this._videoTexture)}else(i=this._overlay)==null||i.remove(this._videoTexture);this._overlay&&(this._overlay.enabled=e)}createVideoElement(){const e=document.createElement("video");return this._crossOrigin&&e.setAttribute("crossorigin",this._crossOrigin),at&&console.log("created video element",e),e}handleBeginPlaying(e){var o,a;if(!this.activeAndEnabled||!this._videoElement)return;this._targetObjects.length=0;let i=this.gameObject;switch(this.renderMode){case 3:i=(o=this.targetMaterialRenderer)==null?void 0:o.gameObject,i||(i=(a=S.getComponent(this.gameObject,ze))==null?void 0:a.gameObject);break;case 2:console.error("VideoPlayer renderTexture not implemented yet. Please use material override instead");return}if(!i){console.error("Missing target for video material renderer",this.name,Vw[this.renderMode],this);return}const n=i.material;if(n){this._targetObjects.push(i),n!==this._videoMaterial&&(this._videoMaterial=n.clone(),i.material=this._videoMaterial);const l="map",c=this._videoMaterial;if(!this.targetMaterialProperty)c[l]=this._videoTexture;else switch(this.targetMaterialProperty){default:c[l]=this._videoTexture;break}}else{console.warn("Can not play video, no material found, this might be a multimaterial case which is not supported yet");return}this.updateVideoElementSettings(),this.updateVideoElementStyles(),e&&(this.shouldUseM3U&&this.ensureM3UCanBePlayed(),this.play())}updateVideoElementSettings(){if(!this._videoElement)return;this._videoElement.loop=this._isLooping,this._videoElement.currentTime=this.currentTime,this._videoElement.playbackRate=this._playbackSpeed,this._videoElement.playsInline=!0;let e=!this._receivedInput||this.audioOutputMode===0;!e&&this._muted&&(e=!0),this._videoElement.muted=e,this.playOnAwake&&(this._videoElement.autoplay=!0)}updateVideoElementStyles(){this._videoElement&&(this._videoElement.style.userSelect="none",this._videoElement.style.visibility="hidden",this._videoElement.style.display="none",this.updateAspect())}*updateAspectImpl(){const e=++this._updateAspectRoutineId,i=void 0,n=this.clip;for(;e===this._updateAspectRoutineId&&this.aspectMode!==0&&this.clip&&n===this.clip&&this._isPlaying;){if(!n||typeof n=="string")return;let o;for(const a of n.getVideoTracks()){const l=a.getSettings();if(l&&l.width&&l.height){o=l.width/l.height;break}else o=this.context.renderer.domElement.clientWidth/this.context.renderer.domElement.clientHeight}if(o===void 0){for(let a=0;a<10;a++)yield;if(!this.isPlaying)break;continue}if(i===o){yield;continue}for(const a of this._targetObjects){let l=1;if(a.parent){const c=Ue(a.parent);l=c.x/c.y}switch(this.aspectMode){case 1:a.scale.y=1/o*a.scale.x*l;break;case 2:a.scale.x=o*a.scale.y*l;break}}for(let a=0;a<3;a++)yield}}get shouldUseM3U(){return this.url!=null&&(this.url.endsWith(".m3u8")||this.url.endsWith(".m3u"))&&this.source===1}ensureM3UCanBePlayed(){if(!this.shouldUseM3U)return;let e=document.head.querySelector("script[data-hls_library]");e?globalThis.Hls?this.onHlsAvailable():e.addEventListener("load",this.onHlsAvailable):(at&&console.log("HLS: load script"),e=document.createElement("script"),e.dataset.hls_library="hls.js",e.src="https://cdn.jsdelivr.net/npm/hls.js@1",e.addEventListener("load",this.onHlsAvailable),document.head.append(e))}}Ei([p()],st.prototype,"playOnAwake",2);Ei([p()],st.prototype,"aspectMode",2);Ei([p(URL)],st.prototype,"clip",2);Ei([p()],st.prototype,"source",2);Ei([p(URL)],st.prototype,"url",1);Ei([p()],st.prototype,"renderMode",2);Ei([p()],st.prototype,"targetMaterialProperty",2);Ei([p(ze)],st.prototype,"targetMaterialRenderer",2);Ei([p(h.Texture)],st.prototype,"targetTexture",2);Ei([p()],st.prototype,"time",2);Ei([p()],st.prototype,"playbackSpeed",1);Ei([p()],st.prototype,"isLooping",1);Ei([p()],st.prototype,"audioOutputMode",1);class sk{constructor(t){r(this,"context");r(this,"_videos",[]);r(this,"_screenspaceModeQuad");r(this,"_isInScreenspaceMode",!1);r(this,"_input");this.context=t,this._input=new ok(this)}get enabled(){return this._isInScreenspaceMode}set enabled(t){t?this.start():this.stop()}add(t){this._videos.indexOf(t)===-1&&this._videos.push(t)}remove(t){if(!t)return;const e=this._videos.indexOf(t);e>=0&&this._videos.splice(e,1)}start(){var n;if(this._isInScreenspaceMode||this._videos.length<0)return;const t=this._videos[this._videos.length-1];if(!t)return;if(this._isInScreenspaceMode=!0,!this._screenspaceModeQuad){if(this._screenspaceModeQuad=vo.createPrimitive(ar.Quad,{material:new rk(t)}),!this._screenspaceModeQuad)return;this._screenspaceModeQuad.geometry.scale(2,2,2)}const e=this._screenspaceModeQuad;this.context.scene.add(e),this.updateScreenspaceMaterialUniforms();const i=e.material;i==null||i.reset(),(n=this._input)==null||n.enable(i)}stop(){var t;this._isInScreenspaceMode=!1,this._screenspaceModeQuad&&((t=this._input)==null||t.disable(),this._screenspaceModeQuad.removeFromParent())}updateScreenspaceMaterialUniforms(){var e;const t=(e=this._screenspaceModeQuad)==null?void 0:e.material;t&&(t.screenAspect=this.context.domElement.clientWidth/this.context.domElement.clientHeight)}}class ok{constructor(t){r(this,"_onResizeScreenFn");r(this,"_onKeyUpFn");r(this,"_onMouseWheelFn");r(this,"context");r(this,"overlay");r(this,"_material");r(this,"_isPinching",!1);r(this,"_lastPinch",0);this.overlay=t,this.context=t.context}enable(t){this._material=t,window.addEventListener("resize",this._onResizeScreenFn=()=>{this.overlay.updateScreenspaceMaterialUniforms()}),window.addEventListener("keyup",this._onKeyUpFn=n=>{n.key==="Escape"&&this.overlay.stop()}),window.addEventListener("wheel",this._onMouseWheelFn=n=>{this.overlay.enabled&&(t.zoom+=n.deltaY*5e-4,n.preventDefault())},{passive:!1});const e=new h.Vector2;window.addEventListener("mousemove",n=>{if(this.overlay.enabled&&this.context.input.getPointerPressed(0)){const o=new h.Vector2(n.movementX,n.movementY);o.x/=this.context.domElement.clientWidth,o.y/=this.context.domElement.clientHeight,e.set(o.x,o.y),e.multiplyScalar(t.zoom/-this.context.time.deltaTime*.01),t.offset=t.offset.add(e)}}),window.addEventListener("pointermove",n=>{this.overlay.enabled&&this.context.input.getPointerPressed(0)&&this.context.input.getTouchesPressedCount()===1&&(e.set(n.movementX,n.movementY),e.multiplyScalar(t.zoom*-this.context.time.deltaTime*.05),t.offset=t.offset.add(e))});let i=0;window.addEventListener("touchstart",n=>{if(n.touches.length<2){this.context.time.time-i<.3&&this.overlay.stop(),i=this.context.time.time;return}this._isPinching=!0,this._lastPinch=0}),window.addEventListener("touchmove",n=>{if(!this._isPinching||!this._material)return;const o=n.touches[0],a=n.touches[1],l=o.clientX-a.clientX,c=o.clientY-a.clientY,d=Math.sqrt(l*l+c*c);if(this._lastPinch!==0){const u=d-this._lastPinch;this._material.zoom-=u*.004}this._lastPinch=d}),window.addEventListener("touchend",()=>{this._isPinching=!1})}disable(){this._onResizeScreenFn&&(window.removeEventListener("resize",this._onResizeScreenFn),this._onResizeScreenFn=void 0),this._onKeyUpFn&&(window.removeEventListener("keyup",this._onKeyUpFn),this._onKeyUpFn=void 0),this._onMouseWheelFn&&(window.removeEventListener("wheel",this._onMouseWheelFn),this._onMouseWheelFn=void 0)}}class rk extends h.ShaderMaterial{constructor(e){super();r(this,"_offset",new h.Vector2);this.uniforms={map:{value:e},screenAspect:{value:1},offsetScale:{value:new h.Vector4(0,0,1,1)}},this.vertexShader=`
1269
+ `;class e extends exports.MODULES.POSTPROCESSING.MODULE.Effect{constructor(){super("Sharpening",t,{vertexShader:s,blendFunction:exports.MODULES.POSTPROCESSING.MODULE.BlendFunction.NORMAL,uniforms:new Map([["amount",new h.Uniform$1(1)],["radius",new h.Uniform$1(1)]])})}}return e}var VE=Object.defineProperty,$E=Object.getOwnPropertyDescriptor,sl=(s,t,e,i)=>{for(var n=i>1?void 0:i?$E(t,e):t,o=s.length-1,a;o>=0;o--)(a=s[o])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&VE(t,e,n),n};class Xn extends Qe{constructor(){super(...arguments);r(this,"offset",new U(0));r(this,"rotation",new U(0));r(this,"focusArea",new U(.4));r(this,"feather",new U(.3));r(this,"kernelSize",new U(2));r(this,"resolutionScale",new U(1/window.devicePixelRatio))}get typeName(){return"TiltShiftEffect"}init(){this.offset.defaultValue=0,this.rotation.defaultValue=0,this.focusArea.defaultValue=.4,this.feather.defaultValue=.3,this.kernelSize.defaultValue=exports.MODULES.POSTPROCESSING.MODULE.KernelSize.MEDIUM,this.resolutionScale.defaultValue=1/window.devicePixelRatio}onCreateEffect(){const e=new exports.MODULES.POSTPROCESSING.MODULE.TiltShiftEffect({kernelSize:exports.MODULES.POSTPROCESSING.MODULE.KernelSize.VERY_LARGE,offset:this.offset.value,rotation:this.rotation.value,focusArea:this.focusArea.value,feather:this.feather.value});return this.offset.onValueChanged=i=>e.offset=i,this.rotation.onValueChanged=i=>e.rotation=i,this.focusArea.onValueChanged=i=>e.focusArea=i,this.feather.onValueChanged=i=>e.feather=i,this.kernelSize.onValueChanged=i=>e.blurPass.kernelSize=i,this.resolutionScale.onValueChanged=i=>e.resolution.scale=i/window.devicePixelRatio,e}}sl([p(U)],Xn.prototype,"offset",2);sl([p(U)],Xn.prototype,"rotation",2);sl([p(U)],Xn.prototype,"focusArea",2);sl([p(U)],Xn.prototype,"feather",2);sl([p(U)],Xn.prototype,"kernelSize",2);sl([p(U)],Xn.prototype,"resolutionScale",2);Ki("TiltShiftEffect",Xn);var WE=Object.defineProperty,HE=Object.getOwnPropertyDescriptor,sy=(s,t,e,i)=>{for(var n=i>1?void 0:i?HE(t,e):t,o=s.length-1,a;o>=0;o--)(a=s[o])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&WE(t,e,n),n};class Br extends Qe{constructor(){super(...arguments);r(this,"color",new U({r:0,g:0,b:0,a:1}));r(this,"intensity",new U(0));r(this,"center",new U({x:.5,y:.5}))}get typeName(){return"Vignette"}init(){this.color.defaultValue={r:0,g:0,b:0,a:1},this.intensity.defaultValue=0,this.center.defaultValue={x:.5,y:.5}}onCreateEffect(){const e=new exports.MODULES.POSTPROCESSING.MODULE.VignetteEffect;return this.intensity.onValueChanged=i=>{e.offset=i,this.updateDarkness(e)},this.color.onValueChanged=i=>{this.updateDarkness(e)},e}updateDarkness(e){const i=this.intensity.value;e.darkness=i}}sy([p(U)],Br.prototype,"color",2);sy([p(U)],Br.prototype,"intensity",2);sy([p(U)],Br.prototype,"center",2);Ki("Vignette",Br);globalThis.true=globalThis.true!==void 0?globalThis.true:!0;const Us=x("debugpost"),GE=x("debugpostpasses"),cp=Symbol("needle:postprocessing-handler"),hp=Symbol("needle:previous-autoclear-state");class oy{constructor(t){r(this,"_composer",null);r(this,"_lastVolumeComponents");r(this,"_effects",[]);r(this,"_isActive",!1);r(this,"context");r(this,"_menuEntry",null);r(this,"_passIndices",null);this.context=t}get isActive(){return this._isActive}get composer(){return this._composer}apply(t){return"env"in{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:ga&&ga.tagName.toUpperCase()==="SCRIPT"&&ga.src||new URL("needle-engine.bundle-ef2b8438.umd.cjs",document.baseURI).href}&&{}.VITE_NEEDLE_USE_POSTPROCESSING==="false"?(Us?console.warn("Postprocessing is disabled via vite env setting"):console.debug("Postprocessing is disabled via vite env setting"),Promise.resolve()):(this._isActive=!0,this.onApply(this.context,t))}unapply(){var i;if(Us&&console.log("Unapplying postprocessing effects"),this._isActive=!1,this._lastVolumeComponents){for(const n of this._lastVolumeComponents)n.unapply();this._lastVolumeComponents.length=0}const t=this.context;t[cp]===this&&delete t[cp],t.composer===this._composer&&((i=t.composer)==null||i.dispose(),t.composer=null),typeof t.renderer[hp]=="boolean"&&(t.renderer.autoClear=t.renderer[hp])}dispose(){this.unapply();for(const t of this._effects)t.dispose();this._effects.length=0,this._composer=null}async onApply(t,e){if(!e)return;await Promise.all([exports.MODULES.POSTPROCESSING.load(),exports.MODULES.POSTPROCESSING_AO.load()]),t[cp]=this,Us&&console.log("Apply Postprocessing Effects",e),this._lastVolumeComponents=[...e],this._effects.length=0;const i={handler:this,components:this._lastVolumeComponents};for(let n=0;n<this._lastVolumeComponents.length;n++){const o=this._lastVolumeComponents[n];if(o.context=t,o.apply){if(o.active){if(!t.mainCameraComponent){console.error("No camera in scene found or available yet - can not create postprocessing effects");return}const a=o.apply(i);if(!a)continue;Array.isArray(a)?this._effects.push(...a):this._effects.push(a)}}else o.active&&pe("Volume component is not a VolumeComponent: "+o.__type)}if(this.context.renderer.toneMapping!=h.NoToneMapping&&!this._effects.find(n=>n instanceof exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect)){const n=new exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect;this._effects.push(n)}this.applyEffects(t)}applyEffects(t){const e=this._effects;if(e.length<=0)return;const i=t.mainCameraComponent,n=t.renderer,o=t.scene,a=i.threeCamera;n[hp]=n.autoClear,this._composer||(this._composer=new exports.MODULES.POSTPROCESSING.MODULE.EffectComposer(n,{frameBufferType:h.HalfFloatType,stencilBuffer:!0})),t.composer&&t.composer!==this._composer&&console.warn("There's already an active EffectComposer in your scene: replacing it with a new one. This might cause unexpected behaviour. Make sure to only use one PostprocessingManager/Volume in your scene."),t.composer=this._composer;const l=t.composer;l.setMainCamera(a),l.setRenderer(n),l.setMainScene(o);for(const d of l.passes)d.dispose();l.removeAllPasses();const c=new exports.MODULES.POSTPROCESSING.MODULE.RenderPass(o,a);if(c.name="Render To Screen",c.mainScene=o,l.addPass(c),GE){this.orderEffects();for(const d of e)if(d instanceof exports.MODULES.POSTPROCESSING.MODULE.Effect){const u=new exports.MODULES.POSTPROCESSING.MODULE.EffectPass(a,d);u.name=d.name,l.addPass(u)}else d instanceof exports.MODULES.POSTPROCESSING.MODULE.Pass,l.addPass(d)}else try{this.orderEffects();const d=[];for(const u of e)u instanceof exports.MODULES.POSTPROCESSING.MODULE.Effect?d.push(u):(u instanceof exports.MODULES.POSTPROCESSING.MODULE.Pass,l.addPass(u));if(d.length>0){const u=new exports.MODULES.POSTPROCESSING.MODULE.EffectPass(a,...d);u.name=d.map(f=>f.name).join(" "),u.mainScene=o,u.enabled=!0,l.addPass(u)}}catch(d){console.error("Error while applying postprocessing effects",d),l.removeAllPasses()}if(Us){console.log("[PostProcessing] Passes →",l.passes);const d=new exports.MODULES.POSTPROCESSING.MODULE.DepthEffect({blendFunction:exports.MODULES.POSTPROCESSING.MODULE.BlendFunction.NORMAL,inverted:!0});d.name="Depth Effect";const u=new exports.MODULES.POSTPROCESSING.MODULE.EffectPass(a,d);if(u.name="Depth Effect Pass",u.enabled=!1,l.passes.push(u),this._passIndices!==null){const m=[l.passes[0]];this._passIndices.length>0&&m.push(...this._passIndices.filter(g=>g!==0).map(g=>l.passes[g]).filter(g=>g)),m.length>0&&console.log("[PostProcessing] Passes (selected) →",m),l.passes.length=0;for(const g of m)g.enabled=!0,g.renderToScreen=!1,l.addPass(g)}const f=this.context.menu;if(f&&this._passIndices===null){this._menuEntry&&this._menuEntry.remove();const m=document.createElement("select");m.multiple=!0;const g=document.createElement("option");g.innerText="Final Output",g.value="-1",m.appendChild(g);for(const y of l.passes){const _=document.createElement("option");_.innerText=y.name,_.value=`${l.passes.indexOf(y)}`,_.title=y.name,m.appendChild(_)}f.appendChild(m),this._menuEntry=m,m.addEventListener("change",()=>{const y=Array.from(m.selectedOptions).map(_=>parseInt(_.value));y.length===1&&y[0]===-1?this._passIndices=null:this._passIndices=y,this.applyEffects(t)})}}}orderEffects(){var e;Us&&console.log("Before ordering effects",[...this._effects]),dp??(dp=[exports.MODULES.POSTPROCESSING.MODULE.NormalPass,exports.MODULES.POSTPROCESSING.MODULE.DepthDownsamplingPass,exports.MODULES.POSTPROCESSING.MODULE.SMAAEffect,exports.MODULES.POSTPROCESSING.MODULE.SSAOEffect,exports.MODULES.POSTPROCESSING_AO.MODULE.N8AOPostPass,exports.MODULES.POSTPROCESSING.MODULE.TiltShiftEffect,exports.MODULES.POSTPROCESSING.MODULE.DepthOfFieldEffect,exports.MODULES.POSTPROCESSING.MODULE.ChromaticAberrationEffect,exports.MODULES.POSTPROCESSING.MODULE.BloomEffect,exports.MODULES.POSTPROCESSING.MODULE.SelectiveBloomEffect,exports.MODULES.POSTPROCESSING.MODULE.VignetteEffect,exports.MODULES.POSTPROCESSING.MODULE.PixelationEffect,exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect,exports.MODULES.POSTPROCESSING.MODULE.HueSaturationEffect,exports.MODULES.POSTPROCESSING.MODULE.BrightnessContrastEffect]);const t=this._effects;t.sort((i,n)=>{const o=dp.findIndex(l=>i.constructor.name.endsWith(l.name)),a=dp.findIndex(l=>n.constructor.name.endsWith(l.name));return o<0?(Us&&console.warn("Unknown effect found: ",i.constructor.name),-1):a<0?(Us&&console.warn("Unknown effect found: ",n.constructor.name),1):o<0?1:a<0?-1:o-a}),Us&&console.log("After ordering effects",[...this._effects]);for(let i=0;i<t.length;i++){const n=t[i];if(((e=n==null?void 0:n.configuration)==null?void 0:e.gammaCorrection)!==void 0){const o=i===t.length-1;n.configuration.gammaCorrection=o}}}}let dp=null;var qE=Object.defineProperty,XE=Object.getOwnPropertyDescriptor,Uw=(s,t,e,i)=>{for(var n=i>1?void 0:i?XE(t,e):t,o=s.length-1,a;o>=0;o--)(a=s[o])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&qE(t,e,n),n};const Xr=x("debugpost");class ol extends D{constructor(){super(...arguments);r(this,"sharedProfile");r(this,"multisampling","auto");r(this,"_postprocessing");r(this,"_activeEffects",[]);r(this,"_effects",[]);r(this,"_componentEnabledTime",-1);r(this,"_multisampleAutoChangeTime",0);r(this,"_multisampleAutoDecreaseTime",0);r(this,"_lastApplyTime");r(this,"_rapidApplyCount",0);r(this,"_isDirty",!1);r(this,"_modificationQueue");r(this,"_recreateId",-1)}get isPostProcessingManager(){return!0}get effects(){return this._activeEffects}addEffect(e){let i=e;return i instanceof Qe||(i=new Lc(i)),i.gameObject===void 0&&this.gameObject.addComponent(i),this._effects.includes(i)||(this._effects.push(i),this._isDirty=!0),e}removeEffect(e){var n,o,a,l;let i=-1;if(e instanceof Qe?i=this._effects.indexOf(e):i=this._effects.findIndex(c=>c instanceof Lc&&c.effect===e),i!==-1)return this._effects.splice(i,1),this._isDirty=!0,e;if(e instanceof Qe){const c=(o=(n=this.sharedProfile)==null?void 0:n.components)==null?void 0:o.indexOf(e);c!==void 0&&c!==-1&&(this._isDirty=!0,(l=(a=this.sharedProfile)==null?void 0:a.components)==null||l.splice(c,1))}return e}markDirty(){this._isDirty=!0}awake(){var e;Xr&&(console.log("PostprocessingManager Awake",this),console.log("Press P to toggle post processing"),window.addEventListener("keydown",i=>{i.key==="p"&&(this.enabled=!this.enabled,Te("Toggle PostProcessing "+this.name+": Enabled="+this.enabled),this.markDirty())})),(e=this.sharedProfile)==null||e.__init(this)}onEnable(){this._componentEnabledTime=this.context.time.realtimeSinceStartup,this._isDirty=!0}onDisable(){var e;(e=this._postprocessing)==null||e.unapply(),this._isDirty=!1}onBeforeRender(){if(!this.context.isInXR&&(this.context.mainCamera&&this._isDirty&&this.apply(),this.context.composer&&this._postprocessing&&this._postprocessing.composer===this.context.composer)){this.context.renderer.getContext().isContextLost()&&this.context.renderer.forceContextRestore(),this.context.composer.getRenderer()!==this.context.renderer&&this.context.composer.setRenderer(this.context.renderer),this.context.composer.setMainScene(this.context.scene);const e=this.context.composer;if(this.multisampling==="auto"){const i=this.context.time.realtimeSinceStartup-this._multisampleAutoChangeTime;if(this.context.time.realtimeSinceStartup-this._componentEnabledTime>2&&i>.5){const n=e.multisampling;e.multisampling>0&&this.context.time.smoothedFps<=50?(this._multisampleAutoChangeTime=this.context.time.realtimeSinceStartup,this._multisampleAutoDecreaseTime=this.context.time.realtimeSinceStartup,e.multisampling*=.5,e.multisampling=Math.floor(e.multisampling),Xr&&console.debug(`[PostProcessing] Reduced multisampling from ${n} to ${e.multisampling}`)):i>1&&this.context.time.smoothedFps>=59&&e.multisampling<this.context.renderer.capabilities.maxSamples&&this.context.time.realtimeSinceStartup-this._multisampleAutoDecreaseTime>10&&(this._multisampleAutoChangeTime=this.context.time.realtimeSinceStartup,e.multisampling=e.multisampling<=0?1:e.multisampling*2,e.multisampling=Math.floor(e.multisampling),Xr&&console.debug(`[PostProcessing] Increased multisampling from ${n} to ${e.multisampling}`))}}else e.multisampling=Math.max(0,Math.min(this.multisampling,this.context.renderer.capabilities.maxSamples));if(this.context.mainCamera){const i=this.context.composer.passes;for(const n of i)if(n.mainCamera&&n.mainCamera!==this.context.mainCamera){this.context.composer.setMainCamera(this.context.mainCamera);break}}}}onDestroy(){var e;(e=this._postprocessing)==null||e.dispose()}apply(){var e,i;if(Xr&&console.log(`Apply PostProcessing "${this.name}"`),I()&&(this._lastApplyTime!==void 0&&Date.now()-this._lastApplyTime<100&&(this._rapidApplyCount++,this._rapidApplyCount===5&&console.warn("Detected rapid post processing modifications - this might be a bug",this)),this._lastApplyTime=Date.now()),this._isDirty=!1,this.unapply(),this._activeEffects.length=0,(e=this.sharedProfile)!=null&&e.components){const n=this.sharedProfile.components;for(const o of n)o.active&&o.enabled&&!this._activeEffects.includes(o)&&this._activeEffects.push(o)}for(const n of this._effects)n.active&&n.enabled&&!this._activeEffects.includes(n)&&this._activeEffects.push(n);this._activeEffects.length>0&&(this._postprocessing||(this._postprocessing=new oy(this.context)),(i=this._postprocessing.apply(this._activeEffects))==null||i.then(()=>{var o;if(!this.activeAndEnabled)return;this._applyPostQueue();const n=(o=this._postprocessing)==null?void 0:o.composer;n?(this.multisampling==="auto"?n.multisampling=exports.DeviceUtilities.isMobileDevice()?2:4:n.multisampling=Math.max(0,Math.min(this.multisampling,this.context.renderer.capabilities.maxSamples)),Xr&&console.debug(`[PostProcessing] Set multisampling to ${n.multisampling} (Is Mobile: ${exports.DeviceUtilities.isMobileDevice()})`)):Xr&&console.warn("[PostProcessing] No composer found")}))}unapply(){var e;(e=this._postprocessing)==null||e.unapply()}_applyPostQueue(){if(this._modificationQueue){for(const e of this._modificationQueue.values())this.onEditorModification(e);this._modificationQueue.clear()}}onEditorModification(e){var i,n;if(e.propertyName.startsWith("postprocessing.")){if(!this._postprocessing)return this._modificationQueue||(this._modificationQueue=new Map),this._modificationQueue.set(e.propertyName,e),!0;if(!((i=this._activeEffects)!=null&&i.length))return;const o=e.propertyName.split(".");if(o.length===3||o.length===4){const a=o[1],l=o[2];for(const c of this._activeEffects)if(((n=c.typeName)==null?void 0:n.toLowerCase())===a.toLowerCase()){if(l==="active"){c.active=e.value,this.scheduleRecreate();return}if(!od.has(a)){const d=new Array;od.set(a,d);const u=Object.keys(c);for(const f of u)c[f]instanceof U&&d.push(f)}if(od.has(a)){const d=l.toLowerCase(),u=od.get(a);for(const f of u)if(f.toLowerCase()===d){const m=c[f];m instanceof U&&(o.length===4&&o[3]==="active"?(m.overrideState=e.value,this.scheduleRecreate()):m&&m.value!==void 0&&(m.value=e.value));return}}console.warn("Unknown modification",l);return}}return!0}return!1}scheduleRecreate(){const e=++this._recreateId;setTimeout(()=>{e===this._recreateId&&(this.onDisable(),this.onEnable())},200)}}Uw([yr(Qu)],ol.prototype,"sharedProfile",2);Uw([yr()],ol.prototype,"multisampling",2);const od=new Map;tE(ol);async function ry(s){const{NeedleEngineHTMLElement:t}=await Promise.resolve().then(()=>VT);t.observedAttributes.includes(s)||t.observedAttributes.push(s)}var QE=Object.defineProperty,YE=Object.getOwnPropertyDescriptor,ft=(s,t,e,i)=>{for(var n=i>1?void 0:i?YE(t,e):t,o=s.length-1,a;o>=0;o--)(a=s[o])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&QE(t,e,n),n};const Rt=x("debugsceneswitcher"),KE=x("sceneswitcher:clearscene"),kd="scene";ry(kd);const zs=Promise.resolve(!1);class qe extends D{constructor(){super(...arguments);r(this,"autoLoadFirstScene",!0);r(this,"scenes",[]);r(this,"loadingScene");r(this,"queryParameterName","scene");r(this,"useSceneName",!0);r(this,"clamp",!0);r(this,"useHistory",!0);r(this,"useKeyboard",!0);r(this,"useSwipe",!0);r(this,"useSceneLighting",!0);r(this,"useSceneBackground",!0);r(this,"preloadNext",1);r(this,"preloadPrevious",1);r(this,"preloadConcurrent",2);r(this,"createMenuButtons",!1);r(this,"sceneLoadingStart",new ge);r(this,"sceneLoadingProgress",new ge);r(this,"sceneLoaded",new ge);r(this,"_currentIndex",-1);r(this,"_currentScene");r(this,"_engineElementOverserver");r(this,"_preloadScheduler");r(this,"_menuButtons");r(this,"onPopState",async e=>{if(!this.useHistory)return;const i=this.useHistory;try{this.useHistory=!1;let n=!1;if(this.queryParameterName&&(n=await this.tryLoadFromQueryParam()),!n){const o=e==null?void 0:e.state;if(o&&o.startsWith(this.guid)){const a=o.substr(this.guid.length+2);Rt&&console.log("PopState",a),await this.trySelectSceneFromValue(a)}}}finally{this.useHistory=i}});r(this,"normalizedSwipeThresholdX",.1);r(this,"_didSwipe",!1);r(this,"onInputPointerMove",e=>{if(this.useSwipe&&!this._didSwipe&&e.button===0&&e.pointerType==="touch"&&this.context.input.getPointerPressedCount()===1){const i=this.context.input.getPointerPositionDelta(e.button);if(i){const n=i.x/this.context.domWidth;n>=this.normalizedSwipeThresholdX?(this._didSwipe=!0,this.selectPrev()):n<=-this.normalizedSwipeThresholdX&&(this._didSwipe=!0,this.selectNext())}}});r(this,"onInputPointerUp",e=>{e.button===0&&(this._didSwipe=!1)});r(this,"onInputKeyDown",e=>{if(!this.useKeyboard||!this.scenes)return;const i=e.key.toLowerCase();if(!i)return;const n=parseInt(i)-1;if(n>=0){this.trySelectSceneFromValue(n);return}switch(i){case"arrowright":case"d":this.selectNext();break;case"arrowleft":case"a":this.selectPrev();break}});r(this,"__lastSwitchScene");r(this,"__lastSwitchScenePromise");r(this,"_currentlyLoadingScene");r(this,"_lastLoadingScene");r(this,"_loadingScenePromise");r(this,"_isCurrentlyLoading",!1);r(this,"_currentLoadingProgress")}get currentIndex(){return this._currentIndex}get currentLoadingProgress(){return this._currentLoadingProgress}get currentlyLoadingScene(){return this._currentlyLoadingScene}get currentlyLoadedScene(){return this._currentScene}awake(){this.scenes===void 0&&(this.scenes=[]);for(const e of this.scenes)e&&!e.hasUrl&&e.asset instanceof h.Object3D?S.remove(e.asset):e instanceof h.Object3D&&S.remove(e);Rt&&console.log("SceneSwitcher",this)}async onEnable(){if(globalThis.addEventListener("popstate",this.onPopState),this.context.input.addEventListener(Ee.KeyDown,this.onInputKeyDown),this.context.input.addEventListener(Ee.PointerMove,this.onInputPointerMove),this.context.input.addEventListener(Ee.PointerUp,this.onInputPointerUp),this._engineElementOverserver||(this._engineElementOverserver=new MutationObserver(e=>{for(const i of e)if(i.type==="attributes"&&i.attributeName===kd){const n=this.context.domElement.getAttribute(kd);n!==null&&this.trySelectSceneFromValue(n)}})),this._engineElementOverserver.observe(this.context.domElement,{attributes:!0}),this._preloadScheduler||(this._preloadScheduler=new ZE(this)),this._preloadScheduler.maxLoadAhead=this.preloadNext,this._preloadScheduler.maxLoadBehind=this.preloadPrevious,this._preloadScheduler.maxConcurrent=this.preloadConcurrent,this._preloadScheduler.begin(2e3),this.autoLoadFirstScene&&this._currentIndex===-1&&!await this.tryLoadFromQueryParam()){const e=this.context.domElement.getAttribute(kd);try{(e===null||!await this.trySelectSceneFromValue(e))&&this._currentIndex===-1&&this.select(0)}finally{}}this.createMenuButtons&&(this._menuButtons??(this._menuButtons=[]),this._menuButtons.push(this.context.menu.appendChild({label:"Previous",icon:"arrow_back_ios",onClick:()=>this.selectPrev(),priority:-1005,class:"row2"})),this._menuButtons.push(this.context.menu.appendChild({label:"Next",icon:"arrow_forward_ios",iconSide:"right",onClick:()=>this.selectNext(),priority:-1e3,class:"row2"})))}onDisable(){var e;if(globalThis.removeEventListener("popstate",this.onPopState),this.context.input.removeEventListener(Ee.KeyDown,this.onInputKeyDown),this.context.input.removeEventListener(Ee.PointerMove,this.onInputPointerMove),this.context.input.removeEventListener(Ee.PointerUp,this.onInputPointerUp),(e=this._preloadScheduler)==null||e.stop(),this._menuButtons){for(const i of this._menuButtons)i.remove();this._menuButtons=void 0}}addScene(e){if(typeof e=="string"){let i=this.context.addressables.findAssetReference(e);return i||(i=new ee(e),this.context.addressables.registerAssetReference(i)),this.scenes.push(i),i}return this.scenes.push(e),e}selectNext(){return this.select(this._currentIndex+1)}selectPrev(){return this.select(this._currentIndex-1)}select(e){var n,o,a;if(Rt&&console.log("select",e),typeof e=="object"&&console.warn('Switching to "'+e+'" might not work. Please either use an index or a AssetReference (not a scene reference)'),typeof e=="string"){const l=(n=this.scenes)==null?void 0:n.find(c=>c.url===e);if(!l){const c=ee.getOrCreate(this.sourceId??"",e,this.context);return this.switchScene(c)}if(l)e=(o=this.scenes)==null?void 0:o.indexOf(l);else return zs}if(!((a=this.scenes)!=null&&a.length))return zs;if(e<0){if(this.clamp)return zs;e=this.scenes.length-1}else if(e>=this.scenes.length){if(this.clamp)return zs;e=0}const i=this.scenes[e];return this.switchScene(i)}unload(){return this.__lastSwitchScene=void 0,this.__lastSwitchScenePromise=void 0,this.__unloadCurrentScene()}async reload(){if(this.__lastSwitchScene){const e=this.__lastSwitchScene;return this.__lastSwitchScene=void 0,this.switchScene(e)}return!1}async switchScene(e){var n;if(!(e instanceof ee)){const o=typeof e;if(o==="string")return this.select(e);if(o==="number")return this.select(e);if(e&&e instanceof h.Object3D){const a=(n=this.scenes)==null?void 0:n.indexOf(e);e=new ee(e.name,void 0,e),a>=0&&(this.scenes[a]=e)}else return console.warn(`[SceneSwitcher] Can't switch to scene of type ${o}`),!1}return e.url===this.sourceId?(console.warn("[SceneSwitcher] Can't load own scene - prevent recursive loading",this.sourceId),!1):this.__lastSwitchScene===e&&this.__lastSwitchScenePromise?this.__lastSwitchScenePromise:(this.__lastSwitchScene=e,this.__lastSwitchScenePromise=this.__internalSwitchScene(e),await this.__lastSwitchScenePromise)}async __unloadCurrentScene(){const e=this._currentScene;if(this._currentScene=void 0,e){Rt&&console.log("UNLOAD",e.url,"HasURL?: "+e.hasUrl);const i=this.tryGetSceneEventListener(e.asset);if(i!=null&&i.sceneClosing){const n=i.sceneClosing();n instanceof Promise&&await n}e.hasUrl?e.unload():e.asset instanceof h.Object3D&&S.remove(e.asset)}}async __internalSwitchScene(e){var n,o,a,l,c;await this.__unloadCurrentScene();const i=this._currentIndex=((n=this.scenes)==null?void 0:n.indexOf(e))??-1;try{this._currentlyLoadingScene=e,this._currentLoadingProgress=new ProgressEvent("progress",{loaded:0,total:1});const d=new CustomEvent("loadscene-start",{detail:{scene:e,switcher:this,index:i}});this.dispatchEvent(d),(o=this.sceneLoadingStart)==null||o.invoke(d.detail),await this.onStartLoading(),await e.loadAssetAsync((f,m)=>{var g;if(Rt){const y=m.loaded/m.total,_="["+"=".repeat(Math.floor(y*20))+"-".repeat(20-Math.floor(y*20))+"]";console.debug(`[SceneSwitcher] Download ${(y*100).toFixed(1)} % ${_}`,e.url)}this._currentLoadingProgress=m,this.dispatchEvent(m),(g=this.sceneLoadingProgress)==null||g.invoke(m)}).catch(console.error),await this.onEndLoading();const u=new CustomEvent("loadscene-finished",{detail:{scene:e,switcher:this,index:i}});if(this.dispatchEvent(u),this._currentLoadingProgress=void 0,this._currentlyLoadingScene=void 0,u.defaultPrevented)return Rt&&console.warn("Adding loaded scene prevented:",e,u),!1;if(!e.asset)return Rt&&console.warn("Failed loading scene:",e),!1;if(this._currentIndex===i){if(Rt&&console.log("ADD",e.url),this._currentScene=e,KE){const g=((a=this.context.mainCameraComponent)==null?void 0:a.gameObject)||this.context.mainCamera;g==null||g.removeFromParent();const y=this.gameObject.removeFromParent();Ci(this.context.scene,!0,!0),this.context.scene=new h.Scene,this.context.scene.add(y),g&&this.context.scene.add(g)}if(S.add(e.asset,this.gameObject),this.useSceneLighting&&this.context.sceneLighting.enable(e),this.useSceneBackground){const g=this.context.lightmaps.tryGetSkybox(e.url);g?(g.mapping=h.EquirectangularReflectionMapping,this.context.scene.background=g):Rt&&console.warn("SceneSwitcher: Can't find skybox for scene "+e.url)}if(this.useHistory&&i>=0){let g=i.toString();if(this.useSceneName&&(e instanceof h.Object3D?g=e.name:e.url&&(g=ub(e.url))),(l=this.queryParameterName)!=null&&l.length)Sc(this.queryParameterName,g,this.useHistory);else{const y=history.state,_=this.guid+"::"+i;y!==_&&history.pushState(_,"unused",location.href)}}const f=this.tryGetSceneEventListener(e.asset);if(f!=null&&f.sceneOpened){const g=f.sceneOpened(this);g instanceof Promise&&await g}const m=new CustomEvent("scene-opened",{detail:{scene:e,switcher:this,index:i}});return this.dispatchEvent(m),(c=this.sceneLoaded)==null||c.invoke(this),!0}}catch(d){console.error(d)}return!1}preload(e){if(e>=0&&e<this.scenes.length){const i=this.scenes[e];if(i instanceof ee)return i.preload()}return zs}tryLoadFromQueryParam(){var i;if(!((i=this.queryParameterName)!=null&&i.length))return zs;const e=x(this.queryParameterName);return typeof e=="boolean"?zs:this.trySelectSceneFromValue(e)}trySelectSceneFromValue(e){if(typeof e=="string"){const i=parseInt(e);if(i>=0&&i<this.scenes.length)return this.select(i);{const n=e.toLowerCase();for(let o=0;o<this.scenes.length;o++){const a=this.scenes[o];if(!a)continue;if((a instanceof h.Object3D?a.name:ub(a.url)).toLowerCase().includes(n))return this.select(o)}}}else if(typeof e=="number"&&e>=0&&e<this.scenes.length)return this.select(e);return Gt()&&console.warn('Can not find scene: "'+e+'"',this),zs}async onStartLoading(){var e,i;if(this._isCurrentlyLoading=!0,this.loadingScene&&(this._lastLoadingScene!==this.loadingScene&&(this._loadingScenePromise=void 0),this._lastLoadingScene=this.loadingScene,this._loadingScenePromise||(this._loadingScenePromise=(e=this.loadingScene)==null?void 0:e.loadAssetAsync().then(n=>n!=null)),await this._loadingScenePromise,this._isCurrentlyLoading&&((i=this.loadingScene)!=null&&i.asset))){Rt&&console.log("Add loading scene",this.loadingScene.url,this.loadingScene.asset);const n=this.loadingScene.asset;S.add(n,this.gameObject);const o=this.tryGetSceneEventListener(n);if(o!=null&&o.sceneOpened){const a=o.sceneOpened(this);a instanceof Promise&&await a}}if(this._isCurrentlyLoading){const n=this.tryGetSceneEventListener(this.gameObject);if(n&&n.sceneOpened){const o=n.sceneOpened(this);o instanceof Promise&&await o}}}async onEndLoading(){var e;if(this._isCurrentlyLoading=!1,(e=this.loadingScene)!=null&&e.asset){Rt&&console.log("Remove loading scene",this.loadingScene.url);const i=this.loadingScene.asset,n=this.tryGetSceneEventListener(i);if(typeof(n==null?void 0:n.sceneClosing)=="function"){const o=n.sceneClosing();o instanceof Promise&&await o}S.remove(i)}if(!this._isCurrentlyLoading){const i=this.tryGetSceneEventListener(this.gameObject);if(i&&i.sceneClosing){const n=i.sceneClosing();n instanceof Promise&&await n}}}tryGetSceneEventListener(e,i=0){if(!e)return null;const n=S.foreachComponent(e,o=>{const a=o;if(a.sceneClosing||a.sceneOpened)return a});if(i===0&&!n&&e.children.length)for(const o of e.children){const a=this.tryGetSceneEventListener(o,i+1);if(a)return a}return n||null}}ft([p()],qe.prototype,"autoLoadFirstScene",2);ft([p(ee)],qe.prototype,"scenes",2);ft([p(ee)],qe.prototype,"loadingScene",2);ft([p()],qe.prototype,"queryParameterName",2);ft([p()],qe.prototype,"useSceneName",2);ft([p()],qe.prototype,"clamp",2);ft([p()],qe.prototype,"useHistory",2);ft([p()],qe.prototype,"useKeyboard",2);ft([p()],qe.prototype,"useSwipe",2);ft([p()],qe.prototype,"useSceneLighting",2);ft([p()],qe.prototype,"useSceneBackground",2);ft([p()],qe.prototype,"preloadNext",2);ft([p()],qe.prototype,"preloadPrevious",2);ft([p()],qe.prototype,"preloadConcurrent",2);ft([p()],qe.prototype,"createMenuButtons",2);ft([p(ge)],qe.prototype,"sceneLoadingStart",2);ft([p(ge)],qe.prototype,"sceneLoadingProgress",2);ft([p(ge)],qe.prototype,"sceneLoaded",2);function ub(s){const t=s.split("/").pop(),e=t==null?void 0:t.split(".").shift();return e!=null&&e.length?e:s}class ZE{constructor(t,e=1,i=1,n=2){r(this,"maxLoadAhead");r(this,"maxLoadBehind");r(this,"maxConcurrent");r(this,"_isRunning",!1);r(this,"_switcher");r(this,"_loadTasks",[]);r(this,"_maxConcurrentLoads",1);this._switcher=t,this.maxLoadAhead=e,this.maxLoadBehind=i,this.maxConcurrent=n}begin(t){if(this._isRunning)return;Rt&&console.log("Preload begin",{delay:t}),this._isRunning=!0;let e=-10,i,n;const o=this._switcher.scenes,a=Date.now()+t,l=setInterval(()=>{if(this.allLoaded()&&(Rt&&console.log("All scenes (pre-)loaded"),this.stop()),!this._isRunning){clearInterval(l);return}if(Date.now()<a||this.canLoadNewScene()===!1)return;(e===-10||e!==this._switcher.currentIndex)&&(e=this._switcher.currentIndex,n=0,i=0);const c=n%2===0;c&&(i+=1),n+=1;const d=c?this.maxLoadAhead:this.maxLoadBehind;if(i>d)return;const u=c?e+i:e-i;if(!(u<0)&&!(u<0||u>=o.length)&&!this._loadTasks.some(f=>f.index===u)){const f=o[u];Rt&&console.log("Preload scene",{roomIndex:u,searchForward:c,lastRoom:e,currentIndex:this._switcher.currentIndex,tasks:this._loadTasks.length},f==null?void 0:f.url),new JE(u,f,this._loadTasks)}},200)}stop(){this._isRunning=!1}canLoadNewScene(){return this._loadTasks.length<this._maxConcurrentLoads}allLoaded(){if(this._switcher.scenes){for(const t of this._switcher.scenes)if(t!=null&&t.isLoaded&&t.isLoaded()===!1)return!1}return!0}}class JE{constructor(t,e,i){r(this,"index");r(this,"asset");r(this,"tasks");this.index=t,this.asset=e,this.tasks=i,i.push(this),this.awaitLoading()}async awaitLoading(){this.asset&&!this.asset.isLoaded()&&(Rt&&console.log("Preload start: "+this.asset.url,this.index),await this.asset.preload(),Rt&&console.log("Preload finished: "+this.asset.url,this.index));const t=this.tasks.indexOf(this);t>=0&&this.tasks.splice(t,1)}}function ek(){return new Promise((s,t)=>{const i=()=>{i!=null&&(document.removeEventListener("pointerdown",i),document.removeEventListener("click",i),document.removeEventListener("dragstart",i),document.removeEventListener("touchstart",i),s())};document.addEventListener("pointerdown",i),document.addEventListener("click",i),document.addEventListener("dragstart",i),document.addEventListener("touchstart",i)})}async function tk(s){await ek(),s()}var ik=Object.defineProperty,nk=Object.getOwnPropertyDescriptor,Ei=(s,t,e,i)=>{for(var n=i>1?void 0:i?nk(t,e):t,o=s.length-1,a;o>=0;o--)(a=s[o])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&ik(t,e,n),n};const at=x("debugvideo");var zw=(s=>(s[s.None=0]="None",s[s.AdjustHeight=1]="AdjustHeight",s[s.AdjustWidth=2]="AdjustWidth",s))(zw||{}),Nw=(s=>(s[s.VideoClip=0]="VideoClip",s[s.Url=1]="Url",s))(Nw||{}),Vw=(s=>(s[s.CameraFarPlane=0]="CameraFarPlane",s[s.CameraNearPlane=1]="CameraNearPlane",s[s.RenderTexture=2]="RenderTexture",s[s.MaterialOverride=3]="MaterialOverride",s))(Vw||{});class st extends D{constructor(){super();r(this,"playOnAwake",!0);r(this,"aspectMode",0);r(this,"clip",null);r(this,"source",1);r(this,"_url",null);r(this,"renderMode");r(this,"targetMaterialProperty");r(this,"targetMaterialRenderer");r(this,"targetTexture");r(this,"time",0);r(this,"_playbackSpeed",1);r(this,"_isLooping",!1);r(this,"_muted",!1);r(this,"_audioOutputMode",2);r(this,"playInBackground",!0);r(this,"_crossOrigin","anonymous");r(this,"_videoElement",null);r(this,"_videoTexture",null);r(this,"_videoMaterial",null);r(this,"_isPlaying",!1);r(this,"wasPlaying",!1);r(this,"visibilityChanged",e=>{switch(document.visibilityState){case"hidden":this.playInBackground||(this.wasPlaying=this._isPlaying,this.pause());break;case"visible":this.wasPlaying&&!this._isPlaying&&this.play();break}});r(this,"_receivedInput",!1);r(this,"_overlay",null);r(this,"_targetObjects");r(this,"_updateAspectRoutineId",-1);r(this,"_hls");r(this,"onHlsAvailable",()=>{var e;at&&console.log("HLS: available",this.clip),!(!this.shouldUseM3U||!this.url)&&(this._hls||(this._hls=new Hls),this.videoElement.autoplay=!0,this._hls.loadSource(this.url),this._hls.attachMedia(this.videoElement),(e=this._videoElement)==null||e.play(),at&&console.log("HLS: loaded",this.clip))});tk(()=>{this._receivedInput=!0,this.updateVideoElementSettings()}),this._targetObjects=[],x("videoscreenspace")&&window.addEventListener("keydown",e=>{e.key==="f"&&(this.screenspace=!this.screenspace)})}get url(){return this._url}set url(e){const n=this._url!==e;this.__didAwake?n&&this.setClipURL(e??""):this._url=e}get playbackSpeed(){var e;return((e=this._videoElement)==null?void 0:e.playbackRate)??this._playbackSpeed}set playbackSpeed(e){this._playbackSpeed=e,this._videoElement&&(this._videoElement.playbackRate=e)}get isLooping(){var e;return((e=this._videoElement)==null?void 0:e.loop)??this._isLooping}set isLooping(e){this._isLooping=e,this._videoElement&&(this._videoElement.loop=e)}get currentTime(){var e;return((e=this._videoElement)==null?void 0:e.currentTime)??this.time}set currentTime(e){this._videoElement?this._videoElement.currentTime=e:this.time=e}get isPlaying(){const e=this._videoElement;if(e){if(e.currentTime>0&&!e.paused&&!e.ended&&e.readyState>e.HAVE_CURRENT_DATA)return!0;if(e.srcObject&&e.srcObject.active)return!0}return!1}get crossOrigin(){var e;return((e=this._videoElement)==null?void 0:e.crossOrigin)??this._crossOrigin}set crossOrigin(e){this._crossOrigin=e,this._videoElement&&(e!==null?this._videoElement.setAttribute("crossorigin",e):this._videoElement.removeAttribute("crossorigin"))}get videoMaterial(){return!this._videoMaterial&&!this.create(!1)?null:this._videoMaterial}get videoTexture(){return!this._videoTexture&&!this.create(!1)?null:this._videoTexture}get videoElement(){return!this._videoElement&&!this.create(!1)?null:this._videoElement}requestPictureInPicture(){return this._videoElement?this._videoElement.requestPictureInPicture():null}get muted(){var e;return((e=this._videoElement)==null?void 0:e.muted)??this._muted}set muted(e){this._muted=e,this._videoElement&&(this._videoElement.muted=e)}get currentVideo(){return this.clip}set audioOutputMode(e){e!==this._audioOutputMode&&(e===1&&I()&&console.warn("VideoAudioOutputMode.AudioSource is not yet implemented"),this._audioOutputMode=e,this.updateVideoElementSettings())}get audioOutputMode(){return this._audioOutputMode}preloadVideo(){at&&console.log("Video Preload: "+this.name,this.clip),this.create(!1)}preload(){this.preloadVideo()}setVideo(e){this.clip=e,this.source=0,this._videoElement?(this._videoElement.srcObject=e,this._isPlaying&&this.play(),this.updateAspect()):this.create(this.playOnAwake)}setClipURL(e){this._url!==e&&(this._url=e,this.source=1,at&&console.log("set url",e),this._videoElement?e.endsWith(".m3u8")||e.includes(".m3u")?this.ensureM3UCanBePlayed():(this._videoElement.src=e,this._isPlaying&&(this.stop(),this.play())):this.create(this.playOnAwake))}onEnable(){var e,i;at&&console.log("VideoPlayer.onEnable",Nw[this.source],this.clip,this.url,this),window.addEventListener("visibilitychange",this.visibilityChanged),this.playOnAwake===!0?this.create(!0):this.preloadVideo(),this.screenspace?(e=this._overlay)==null||e.start():(i=this._overlay)==null||i.stop()}onDisable(){var e;window.removeEventListener("visibilitychange",this.visibilityChanged),(e=this._overlay)==null||e.stop(),this.pause()}onDestroy(){var e;this._videoElement&&((e=this.videoElement)==null||e.remove(),this._videoElement=null),this._videoTexture&&(this._videoTexture.dispose(),this._videoTexture=null)}play(){var e,i;if(this._videoElement||this.create(!1),!this._videoElement){at&&console.warn("Can not play: no video element found",this);return}if(!(this._isPlaying&&!((e=this._videoElement)!=null&&e.ended)&&!((i=this._videoElement)!=null&&i.paused))){if(this._isPlaying=!0,this._receivedInput||(this._videoElement.muted=!0),this.handleBeginPlaying(!1),this.shouldUseM3U){this.ensureM3UCanBePlayed();return}at&&console.log("Video Play()",this.clip,this._videoElement,this.time),this._videoElement.currentTime=this.time,this._videoElement.play().catch(n=>{var o;console.log(n),at&&console.error("Error playing video",n,"CODE="+n.code,(o=this.videoElement)==null?void 0:o.src,this),setTimeout(()=>{this._isPlaying&&!this.destroyed&&this.activeAndEnabled&&this.play()},1e3)}),at&&console.log("play",this._videoElement,this.time)}}stop(){this._isPlaying=!1,this.time=0,this._videoElement&&(this._videoElement.currentTime=0,this._videoElement.pause(),at&&console.log("STOP",this))}pause(){var e,i;this.time=((e=this._videoElement)==null?void 0:e.currentTime)??0,this._isPlaying=!1,(i=this._videoElement)==null||i.pause(),at&&console.log("PAUSE",this,this.currentTime)}create(e){let i;switch(this.source){case 0:i=this.clip;break;case 1:i=this.url,!(i!=null&&i.length)&&typeof this.clip=="string"&&(i=this.clip);break}return i?(this._videoElement||(at&&console.warn("Create VideoElement",this),this._videoElement=this.createVideoElement(),this.context.domElement.shadowRoot.prepend(this._videoElement),this.updateVideoElementStyles()),typeof i=="string"?(at&&console.log("Set Video src",i),this._videoElement.src=i):(at&&console.log("Set Video srcObject",i),this._videoElement.srcObject=i),this._videoTexture||(this._videoTexture=new h.VideoTexture(this._videoElement)),this._videoTexture.flipY=!1,this._videoTexture.colorSpace=h.SRGBColorSpace,e&&this.handleBeginPlaying(e),at&&console.log("Video: handle playing done...",i,e),!0):(at&&console.warn("No video source set",this),!1)}updateAspect(){this.aspectMode!==0&&this.startCoroutine(this.updateAspectImpl())}get screenspace(){var e;return((e=this._overlay)==null?void 0:e.enabled)??!1}set screenspace(e){var i;if(e){if(!this._videoTexture)return;this._overlay||(this._overlay=new sk(this.context)),this._overlay.add(this._videoTexture)}else(i=this._overlay)==null||i.remove(this._videoTexture);this._overlay&&(this._overlay.enabled=e)}createVideoElement(){const e=document.createElement("video");return this._crossOrigin&&e.setAttribute("crossorigin",this._crossOrigin),at&&console.log("created video element",e),e}handleBeginPlaying(e){var o,a;if(!this.activeAndEnabled||!this._videoElement)return;this._targetObjects.length=0;let i=this.gameObject;switch(this.renderMode){case 3:i=(o=this.targetMaterialRenderer)==null?void 0:o.gameObject,i||(i=(a=S.getComponent(this.gameObject,ze))==null?void 0:a.gameObject);break;case 2:console.error("VideoPlayer renderTexture not implemented yet. Please use material override instead");return}if(!i){console.error("Missing target for video material renderer",this.name,Vw[this.renderMode],this);return}const n=i.material;if(n){this._targetObjects.push(i),n!==this._videoMaterial&&(this._videoMaterial=n.clone(),i.material=this._videoMaterial);const l="map",c=this._videoMaterial;if(!this.targetMaterialProperty)c[l]=this._videoTexture;else switch(this.targetMaterialProperty){default:c[l]=this._videoTexture;break}}else{console.warn("Can not play video, no material found, this might be a multimaterial case which is not supported yet");return}this.updateVideoElementSettings(),this.updateVideoElementStyles(),e&&(this.shouldUseM3U&&this.ensureM3UCanBePlayed(),this.play())}updateVideoElementSettings(){if(!this._videoElement)return;this._videoElement.loop=this._isLooping,this._videoElement.currentTime=this.currentTime,this._videoElement.playbackRate=this._playbackSpeed,this._videoElement.playsInline=!0;let e=!this._receivedInput||this.audioOutputMode===0;!e&&this._muted&&(e=!0),this._videoElement.muted=e,this.playOnAwake&&(this._videoElement.autoplay=!0)}updateVideoElementStyles(){this._videoElement&&(this._videoElement.style.userSelect="none",this._videoElement.style.visibility="hidden",this._videoElement.style.display="none",this.updateAspect())}*updateAspectImpl(){const e=++this._updateAspectRoutineId,i=void 0,n=this.clip;for(;e===this._updateAspectRoutineId&&this.aspectMode!==0&&this.clip&&n===this.clip&&this._isPlaying;){if(!n||typeof n=="string")return;let o;for(const a of n.getVideoTracks()){const l=a.getSettings();if(l&&l.width&&l.height){o=l.width/l.height;break}else o=this.context.renderer.domElement.clientWidth/this.context.renderer.domElement.clientHeight}if(o===void 0){for(let a=0;a<10;a++)yield;if(!this.isPlaying)break;continue}if(i===o){yield;continue}for(const a of this._targetObjects){let l=1;if(a.parent){const c=Ue(a.parent);l=c.x/c.y}switch(this.aspectMode){case 1:a.scale.y=1/o*a.scale.x*l;break;case 2:a.scale.x=o*a.scale.y*l;break}}for(let a=0;a<3;a++)yield}}get shouldUseM3U(){return this.url!=null&&(this.url.endsWith(".m3u8")||this.url.endsWith(".m3u"))&&this.source===1}ensureM3UCanBePlayed(){if(!this.shouldUseM3U)return;let e=document.head.querySelector("script[data-hls_library]");e?globalThis.Hls?this.onHlsAvailable():e.addEventListener("load",this.onHlsAvailable):(at&&console.log("HLS: load script"),e=document.createElement("script"),e.dataset.hls_library="hls.js",e.src="https://cdn.jsdelivr.net/npm/hls.js@1",e.addEventListener("load",this.onHlsAvailable),document.head.append(e))}}Ei([p()],st.prototype,"playOnAwake",2);Ei([p()],st.prototype,"aspectMode",2);Ei([p(URL)],st.prototype,"clip",2);Ei([p()],st.prototype,"source",2);Ei([p(URL)],st.prototype,"url",1);Ei([p()],st.prototype,"renderMode",2);Ei([p()],st.prototype,"targetMaterialProperty",2);Ei([p(ze)],st.prototype,"targetMaterialRenderer",2);Ei([p(h.Texture)],st.prototype,"targetTexture",2);Ei([p()],st.prototype,"time",2);Ei([p()],st.prototype,"playbackSpeed",1);Ei([p()],st.prototype,"isLooping",1);Ei([p()],st.prototype,"audioOutputMode",1);class sk{constructor(t){r(this,"context");r(this,"_videos",[]);r(this,"_screenspaceModeQuad");r(this,"_isInScreenspaceMode",!1);r(this,"_input");this.context=t,this._input=new ok(this)}get enabled(){return this._isInScreenspaceMode}set enabled(t){t?this.start():this.stop()}add(t){this._videos.indexOf(t)===-1&&this._videos.push(t)}remove(t){if(!t)return;const e=this._videos.indexOf(t);e>=0&&this._videos.splice(e,1)}start(){var n;if(this._isInScreenspaceMode||this._videos.length<0)return;const t=this._videos[this._videos.length-1];if(!t)return;if(this._isInScreenspaceMode=!0,!this._screenspaceModeQuad){if(this._screenspaceModeQuad=vo.createPrimitive(ar.Quad,{material:new rk(t)}),!this._screenspaceModeQuad)return;this._screenspaceModeQuad.geometry.scale(2,2,2)}const e=this._screenspaceModeQuad;this.context.scene.add(e),this.updateScreenspaceMaterialUniforms();const i=e.material;i==null||i.reset(),(n=this._input)==null||n.enable(i)}stop(){var t;this._isInScreenspaceMode=!1,this._screenspaceModeQuad&&((t=this._input)==null||t.disable(),this._screenspaceModeQuad.removeFromParent())}updateScreenspaceMaterialUniforms(){var e;const t=(e=this._screenspaceModeQuad)==null?void 0:e.material;t&&(t.screenAspect=this.context.domElement.clientWidth/this.context.domElement.clientHeight)}}class ok{constructor(t){r(this,"_onResizeScreenFn");r(this,"_onKeyUpFn");r(this,"_onMouseWheelFn");r(this,"context");r(this,"overlay");r(this,"_material");r(this,"_isPinching",!1);r(this,"_lastPinch",0);this.overlay=t,this.context=t.context}enable(t){this._material=t,window.addEventListener("resize",this._onResizeScreenFn=()=>{this.overlay.updateScreenspaceMaterialUniforms()}),window.addEventListener("keyup",this._onKeyUpFn=n=>{n.key==="Escape"&&this.overlay.stop()}),window.addEventListener("wheel",this._onMouseWheelFn=n=>{this.overlay.enabled&&(t.zoom+=n.deltaY*5e-4,n.preventDefault())},{passive:!1});const e=new h.Vector2;window.addEventListener("mousemove",n=>{if(this.overlay.enabled&&this.context.input.getPointerPressed(0)){const o=new h.Vector2(n.movementX,n.movementY);o.x/=this.context.domElement.clientWidth,o.y/=this.context.domElement.clientHeight,e.set(o.x,o.y),e.multiplyScalar(t.zoom/-this.context.time.deltaTime*.01),t.offset=t.offset.add(e)}}),window.addEventListener("pointermove",n=>{this.overlay.enabled&&this.context.input.getPointerPressed(0)&&this.context.input.getTouchesPressedCount()===1&&(e.set(n.movementX,n.movementY),e.multiplyScalar(t.zoom*-this.context.time.deltaTime*.05),t.offset=t.offset.add(e))});let i=0;window.addEventListener("touchstart",n=>{if(n.touches.length<2){this.context.time.time-i<.3&&this.overlay.stop(),i=this.context.time.time;return}this._isPinching=!0,this._lastPinch=0}),window.addEventListener("touchmove",n=>{if(!this._isPinching||!this._material)return;const o=n.touches[0],a=n.touches[1],l=o.clientX-a.clientX,c=o.clientY-a.clientY,d=Math.sqrt(l*l+c*c);if(this._lastPinch!==0){const u=d-this._lastPinch;this._material.zoom-=u*.004}this._lastPinch=d}),window.addEventListener("touchend",()=>{this._isPinching=!1})}disable(){this._onResizeScreenFn&&(window.removeEventListener("resize",this._onResizeScreenFn),this._onResizeScreenFn=void 0),this._onKeyUpFn&&(window.removeEventListener("keyup",this._onKeyUpFn),this._onKeyUpFn=void 0),this._onMouseWheelFn&&(window.removeEventListener("wheel",this._onMouseWheelFn),this._onMouseWheelFn=void 0)}}class rk extends h.ShaderMaterial{constructor(e){super();r(this,"_offset",new h.Vector2);this.uniforms={map:{value:e},screenAspect:{value:1},offsetScale:{value:new h.Vector4(0,0,1,1)}},this.vertexShader=`
1270
1270
  uniform sampler2D map;
1271
1271
  uniform float screenAspect;
1272
1272
  uniform vec4 offsetScale;
@@ -1520,7 +1520,7 @@ Needle Engine: Begin loading `+i+`
1520
1520
  `,e),this.onBeforeBeginLoading();const l=[],c={context:this._context,name:"",progress:{},index:0,count:e.length,totalProgress01:this._loadingProgress01},d=new CustomEvent("progress",{detail:c}),u=new Array,f=new AbortController;this._abortController=f;const m={files:e,abortSignal:f.signal,onLoadingProgress:v=>{var C;if(Se&&console.debug("Loading progress: ",v),f.signal.aborted)return;const w=v.index;!u[w]&&v.name&&(u[w]=NT(v.name)),v.name=u[w],a&&((C=this._loadingView)==null||C.onLoadingUpdate(v)),c.name=v.name,c.progress=v.progress,this._loadingProgress01=py(v),c.totalProgress01=this._loadingProgress01,this.dispatchEvent(d)},onLoadingFinished:(v,w,C)=>{Se&&console.debug(`Finished loading "${w}" (aborted? ${f.signal.aborted})`),!f.signal.aborted&&C&&l.push({src:w,file:C})}},g=this.getAttribute("hash");g!=null&&(this._context.hash=g),this._context.alias=n,this._createContextPromise=this._context.create(m);const y=await this._createContextPromise;if(this.applyAttributes(),Se&&console.warn(`--------------
1521
1521
  Needle Engine: finished loading `+i+`
1522
1522
  `,e,`Aborted? ${f.signal.aborted}`),f.signal.aborted){console.log("Loading finished but aborted...");return}if(this._loadId!==i){console.log("Load id changed during loading process");return}this._loadingProgress01=1,a&&y&&((b=this._loadingView)==null||b.onLoadingUpdate(1,"creating scene")),this._didFullyLoad=!0,this.classList.remove("loading"),this.classList.add("loading-finished"),this.dispatchEvent(new CustomEvent("loadfinished",{detail:{context:this._context,src:n,loadedFiles:l}}))}applyAttributes(){var n,o;if((n=this._context)!=null&&n.renderer){const a=this.getAttribute("tonemapping")||this.getAttribute("tone-mapping");switch(a==null?void 0:a.toLowerCase()){case"none":this._context.renderer.toneMapping=h.NoToneMapping;break;case"linear":this._context.renderer.toneMapping=h.LinearToneMapping;break;case"neutral":this._context.renderer.toneMapping=h.NeutralToneMapping;break;case"agx":this._context.renderer.toneMapping=h.AgXToneMapping;break;default:a!=null&&console.warn("Invalid tone-mapping attribute: "+a)}const l=this.getAttribute("tone-mapping-exposure");if(l!=null){const c=parseFloat(l);isNaN(c)||(this._context.renderer.toneMappingExposure=c)}}const e=this.getAttribute("background-blurriness");if(e!=null){const a=parseFloat(e);a!==void 0&&this._context&&(this._context.scene.backgroundBlurriness=a)}const i=this.getAttribute("background-color");if((o=this._context)!=null&&o.renderer&&typeof i=="string"&&i.length>0){const a=ie.fromColorRepresentation(i);Se&&console.debug("<needle-engine> background-color changed, str:",i,"→",a),this._context.renderer.setClearColor(a,a.alpha),this.context.scene.background=null}}internalSetLoadingMessage(e){var i;(i=this._loadingView)==null||i.setMessage(e)}getSourceFiles(){const e=this.getAttribute("src");if(!e)return[];let i;Array.isArray(e)?i=e:e.startsWith("[")&&e.endsWith("]")?i=JSON.parse(e):e.includes(",")?i=e.split(","):i=[e];for(let n=i.length-1;n>=0;n--){const o=i[n];(o==="null"||o==="undefined"||(o==null?void 0:o.length)<=0)&&i.splice(n,1)}return i}checkIfSourceHasChanged(e,i){if((e==null?void 0:e.length)!==(i==null?void 0:i.length)||e==null&&i!==null||e!==null&&i==null)return!0;if(e!==null&&i!==null){for(let n=0;n<(e==null?void 0:e.length);n++)if(e[n]!==i[n])return!0}return!1}ensureLoadStartIsRegistered(){const e=this.getAttribute("loadstart");e&&this.registerEventFromAttribute("loadstart",e)}registerEventFromAttribute(e,i){const n=this._previouslyRegisteredMap.get(e);if(n&&(this._previouslyRegisteredMap.delete(e),this.removeEventListener(e,n)),typeof i=="string"&&i.length>0)try{const o=(0,eval)(i);typeof o=="function"&&(this._previouslyRegisteredMap.set(e,o),this.addEventListener(e,a=>o==null?void 0:o.call(globalThis,this._context,a)))}catch(o){console.error("Error registering event "+e+'="'+i+`" failed with the following error:
1523
- `,o)}}setPublicKey(){Jl.length>0&&this.setAttribute("public-key",Jl)}setVersion(){hn.length>0&&this.setAttribute("version",hn)}getAROverlayContainer(){return this._overlay_ar.createOverlayContainer(this)}getVROverlayContainer(){for(let e=0;e<this.children.length;e++){const i=this.children[e];if(i.classList.contains("vr"))return i}return null}onEnterAR(e){var n;this.onSetupAR();const i=this.getAROverlayContainer();this._overlay_ar.onBegin(this._context,i,e),this.dispatchEvent(new CustomEvent("enter-ar",{detail:{session:e,context:this._context,htmlContainer:(n=this._overlay_ar)==null?void 0:n.ARContainer}}))}onExitAR(e){var i;this._overlay_ar.onEnd(this._context),this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-ar",{detail:{session:e,context:this._context,htmlContainer:(i=this._overlay_ar)==null?void 0:i.ARContainer}}))}onEnterVR(e){this.onSetupVR(),this.dispatchEvent(new CustomEvent("enter-vr",{detail:{session:e,context:this._context}}))}onExitVR(e){this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-vr",{detail:{session:e,context:this._context}}))}onSetupAR(){this.classList.add(Rl),this.classList.remove(El);const e=this.getAROverlayContainer();Se&&console.warn("onSetupAR:",e),e&&(e.classList.add(Rl),e.classList.remove(El)),this.foreachHtmlElement(i=>this.setupElementsForMode(i,rx))}onSetupVR(){this.classList.remove(Rl),this.classList.remove(El),this.foreachHtmlElement(e=>this.setupElementsForMode(e,ax))}onSetupDesktop(){this.classList.remove(Rl),this.classList.add(El);const e=this.getAROverlayContainer();e&&(e.classList.remove(Rl),e.classList.add(El)),this.foreachHtmlElement(i=>this.setupElementsForMode(i,lx))}setupElementsForMode(e,i,n=null){var a,l;if(e===((l=(a=this._context)==null?void 0:a.renderer)==null?void 0:l.domElement)||e.id==="VRButton"||e.id==="ARButton")return;if(e.classList.contains(i))e.style.visibility="visible",e.style.display==="none"&&(e.style.display="block");else for(const c of UT)e.classList.contains(c)&&(e.style.visibility="hidden",e.style.display="none")}foreachHtmlElement(e){for(let i=0;i<this.children.length;i++){const n=this.children[i];n.style&&e(n)}}onBeforeBeginLoading(){const e=this.getAttribute("dracoDecoderPath");e&&(Se&&console.log("using custom draco decoder path",e),P_(e));const i=this.getAttribute("dracoDecoderType");i&&(Se&&console.log("using custom draco decoder type",i),O_(i));const n=this.getAttribute("ktx2DecoderPath");n&&(Se&&console.log("using custom ktx2 decoder path",n),M_(n))}}typeof window<"u"&&!window.customElements.get(Sb)&&window.customElements.define(Sb,my);function NT(s){if(s.startsWith("blob:"))return"blob";const t=s.split("/");let e=t[t.length-1];const i=e.indexOf("?");i>0&&(e=e.substring(0,i));const n=e.indexOf("=");n>0&&(e=e.substring(n));const o=e.split(".").pop(),l=o?["glb","gltf","usdz","usd","fbx","obj","mtl"].indexOf(o.toLowerCase()):-1;if(o&&l>=0&&(e=e.substring(0,e.length-o.length-1)),e=decodeURIComponent(e),e.length>3){let c="",d=!1;const u=["(",")","[","]","{","}",":",";",",",".","!","?"];for(let f=0;f<e.length;f++){let m=e[f];(m==="_"||m==="-")&&(m=" "),!(m===" "&&c.length<=0||u.includes(m)||(c.length===0&&(m=m.toUpperCase()),d&&m===" "))&&(d&&(m=m.toUpperCase()),d=!1,c+=m,m===" "&&(d=!0))}return I()&&e!==c&&console.debug('Generated display name: "'+e+'" → "'+c+'"'),c.trim()}return I()&&console.debug("Loading: use default name",e),e}const VT=Object.freeze(Object.defineProperty({__proto__:null,NeedleEngineHTMLElement:my},Symbol.toStringTag,{value:"Module"}));function $T(){$i.registerWaitForInteraction(()=>{const s=h.AudioContext.getContext();s.addEventListener("statechange",()=>{setTimeout(()=>{const t=s.state;(t==="suspended"||t==="interrupted")&&s.resume().then(()=>{console.log("AudioContext resumed successfully")}).catch(e=>{console.log("Failed to resume AudioContext: "+e)})},500)})})}setTimeout($T,1e3);const He=x("debugphysics"),mp=x("debugcolliderplacement"),gp=x("debugcollisions"),WT=x("showcolliders"),yp=x("debugraycasts"),Zt=Symbol("needle component"),Ut=Symbol("physics body"),Cb=Symbol("rigidbody");globalThis.true=globalThis.true!==void 0?globalThis.true:!0;He&&console.log("Use Rapier",!0,globalThis.true);re.registerCallback(de.ContextCreationStart,s=>{He&&console.log("Register rapier physics backend"),s.context.physics.engine=new Xs(s.context)});const xc=class{constructor(t){r(this,"debugRenderColliders",!1);r(this,"debugRenderRaycasts",!1);r(this,"context");r(this,"_initializePromise");r(this,"_isInitialized",!1);r(this,"rapierRay");r(this,"raycastVectorsBuffer",new Si(()=>new h.Vector3,10));r(this,"rapierSphere",null);r(this,"rapierColliderArray",[]);r(this,"rapierIdentityRotation",{x:0,y:0,z:0,w:1});r(this,"rapierForwardVector",{x:0,y:0,z:1});r(this,"enabled",!1);r(this,"_tempPosition",new h.Vector3);r(this,"_tempQuaternion",new h.Quaternion);r(this,"_tempScale",new h.Vector3);r(this,"_tempMatrix",new h.Matrix4);r(this,"_isUpdatingPhysicsWorld",!1);r(this,"_world");r(this,"_hasCreatedWorld",!1);r(this,"eventQueue");r(this,"collisionHandler");r(this,"objects",[]);r(this,"bodies",[]);r(this,"_meshCache",new Map);r(this,"_gravity",{x:0,y:-9.81,z:0});r(this,"lines");r(this,"_tempCenterPos",new h.Vector3);r(this,"_tempCenterVec",new h.Vector3);r(this,"_tempCenterQuaternion",new h.Quaternion);this.context=t}removeBody(t){var i,n,o;if(!t)return;this.validate();const e=t[Ut];if(t[Ut]=null,e&&this.world){const a=this.objects.findIndex(l=>l===t);if(a>=0){const l=this.bodies[a];if(this.bodies.splice(a,1),this.objects.splice(a,1),l instanceof exports.MODULES.RAPIER_PHYSICS.MODULE.Collider){const c=l;(i=this.world)==null||i.removeCollider(c,!0);const d=c.parent();d&&d.numColliders()<=0&&(d[Zt]||(n=this.world)==null||n.removeRigidBody(d))}else l instanceof exports.MODULES.RAPIER_PHYSICS.MODULE.RigidBody&&(l.numColliders()<=0?(o=this.world)==null||o.removeRigidBody(l):I()&&(l.did_log_removing||setTimeout(()=>{l.numColliders()>0&&(l.did_log_removing=!0,console.warn("RapierPhysics: removing rigidbody with colliders from the physics world is not possible right now, please remove the colliders first"))},1)))}}}updateBody(t,e,i){if(this.validate(),!!this.enabled&&!(t.destroyed||!t.gameObject)&&!(!e&&!i))if(t.isCollider===!0)console.warn("TODO: implement updating collider position");else{const n=t,o=n[Ut];o&&this.syncPhysicsBody(n.gameObject,o,e,i)}}updateProperties(t){if(this.validate(),t.isCollider){const e=t,i=e[Ut];i&&(this.internalUpdateColliderProperties(e,i),e.sharedMaterial&&this.updatePhysicsMaterial(e))}else{const e=t,i=this.internal_getRigidbody(e);i&&this.internalUpdateRigidbodyProperties(e,i)}}addForce(t,e,i){this.validate();const n=this.internal_getRigidbody(t);n?n.addForce(e,i):console.warn("Rigidbody doesn't exist: can not apply force (does your object with the Rigidbody have a collider?)")}addImpulse(t,e,i){this.validate();const n=this.internal_getRigidbody(t);n?n.applyImpulse(e,i):console.warn("Rigidbody doesn't exist: can not apply impulse (does your object with the Rigidbody have a collider?)")}getLinearVelocity(t){this.validate();const e=this.internal_getRigidbody(t);return e?e.linvel():null}getAngularVelocity(t){this.validate();const e=this.internal_getRigidbody(t);return e?e.angvel():null}resetForces(t,e){this.validate();const i=this.internal_getRigidbody(t);i==null||i.resetForces(e)}resetTorques(t,e){this.validate();const i=this.internal_getRigidbody(t);i==null||i.resetTorques(e)}applyImpulse(t,e,i){this.validate();const n=this.internal_getRigidbody(t);n?n.applyImpulse(e,i):console.warn("Rigidbody doesn't exist: can not apply impulse (does your object with the Rigidbody have a collider?)")}wakeup(t){this.validate();const e=this.internal_getRigidbody(t);e?e.wakeUp():console.warn("Rigidbody doesn't exist: can not wake up (does your object with the Rigidbody have a collider?)")}isSleeping(t){this.validate();const e=this.internal_getRigidbody(t);return e==null?void 0:e.isSleeping()}setAngularVelocity(t,e,i){this.validate();const n=this.internal_getRigidbody(t);n?n.setAngvel(e,i):console.warn("Rigidbody doesn't exist: can not set angular velocity (does your object with the Rigidbody have a collider?)")}setLinearVelocity(t,e,i){this.validate();const n=this.internal_getRigidbody(t);n?n.setLinvel(e,i):console.warn("Rigidbody doesn't exist: can not set linear velocity (does your object with the Rigidbody have a collider?)")}get isInitialized(){return this._isInitialized}async initialize(){return this._initializePromise||(this._initializePromise=this.internalInitialization()),this._initializePromise}async internalInitialization(){return x("__nophysics")?(console.warn("Physics are disabled"),!1):(He&&console.log("Initialize rapier physics engine"),"env"in{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:ga&&ga.tagName.toUpperCase()==="SCRIPT"&&ga.src||new URL("needle-engine.bundle-a52706c5.umd.cjs",document.baseURI).href}&&{}.VITE_NEEDLE_USE_RAPIER==="false"?(He&&console.log("Rapier disabled"),!1):this._hasCreatedWorld?(console.error("Invalid call to create physics world: world is already created"),!0):(this._hasCreatedWorld=!0,exports.MODULES.RAPIER_PHYSICS.MAYBEMODULE==null&&(He&&console.trace("Loading rapier physics engine"),await(await exports.MODULES.RAPIER_PHYSICS.load()).init()),He&&console.log("Physics engine initialized, creating world..."),this._world=new exports.MODULES.RAPIER_PHYSICS.MODULE.World(this._gravity),this.rapierRay=new exports.MODULES.RAPIER_PHYSICS.MODULE.Ray({x:0,y:0,z:0},{x:0,y:0,z:1}),this.enabled=!0,this._isInitialized=!0,He&&console.log("Physics world created"),!0))}validate(){this._isInitialized||He&&(this._lastWarnTime=this._lastWarnTime??0,Date.now()-this._lastWarnTime>1e3&&(this._lastWarnTime=Date.now(),console.warn("Physics engine is not initialized")))}raycast(t,e,i){var c;if(!this._isInitialized)return console.log("Physics engine is not initialized"),null;let n=i==null?void 0:i.maxDistance,o=i==null?void 0:i.solid;n===void 0&&(n=1/0),o===void 0&&(o=!0);const a=this.getPhysicsRay(this.rapierRay,t,e);if(!a)return null;(this.debugRenderRaycasts||yp)&&N.DrawRay(a.origin,a.dir,255,1);const l=(c=this.world)==null?void 0:c.castRay(a,n,o,i==null?void 0:i.queryFilterFlags,i==null?void 0:i.filterGroups,void 0,void 0,d=>{const u=d[Zt];return i!=null&&i.filterPredicate?i.filterPredicate(u):(i==null?void 0:i.useIgnoreRaycastLayer)!==!1?!(u!=null&&u.gameObject.layers.isEnabled(2)):!0});if(l){const d=a.pointAt(l.timeOfImpact),u=this.raycastVectorsBuffer.get();return u.set(d.x,d.y,d.z),{point:u,collider:l.collider[Zt]}}return null}raycastAndGetNormal(t,e,i){var c;if(!this._isInitialized)return null;let n=i==null?void 0:i.maxDistance,o=i==null?void 0:i.solid;n===void 0&&(n=1/0),o===void 0&&(o=!0);const a=this.getPhysicsRay(this.rapierRay,t,e);if(!a)return null;(this.debugRenderRaycasts||yp)&&N.DrawRay(a.origin,a.dir,255,1);const l=(c=this.world)==null?void 0:c.castRayAndGetNormal(a,n,o,i==null?void 0:i.queryFilterFlags,i==null?void 0:i.filterGroups,void 0,void 0,d=>{const u=d[Zt];return i!=null&&i.filterPredicate?i.filterPredicate(u):(i==null?void 0:i.useIgnoreRaycastLayer)!==!1?!(u!=null&&u.gameObject.layers.isEnabled(2)):!0});if(l){const d=a.pointAt(l.timeOfImpact),u=l.normal,f=this.raycastVectorsBuffer.get(),m=this.raycastVectorsBuffer.get();return f.set(d.x,d.y,d.z),m.set(u.x,u.y,u.z),{point:f,normal:m,collider:l.collider[Zt]}}return null}getPhysicsRay(t,e,i){var l,c,d;const n=(l=this.context)==null?void 0:l.mainCamera;if(e===void 0){const u=(c=this.context)==null?void 0:c.input.getPointerPosition(0);if(u)e=u;else return null}if(e.z===void 0){if(!n)return console.error("Can not perform raycast from 2d point - no main camera found"),null;const u=this.raycastVectorsBuffer.get();u.x=e.x,u.y=e.y,u.z=0,(u.x>1||u.y>1||u.y<-1||u.x<-1)&&(He&&console.warn("Converting screenspace to raycast space",u),(d=this.context)==null||d.input.convertScreenspaceToRaycastSpace(u)),u.unproject(n),e=u}const o=e;t.origin.x=o.x,t.origin.y=o.y,t.origin.z=o.z;const a=this.raycastVectorsBuffer.get();if(i)a.set(i.x,i.y,i.z);else{if(!n)return console.error("Can not perform raycast - no camera found"),null;a.set(t.origin.x,t.origin.y,t.origin.z);const u=Z(n);a.sub(u)}return a.normalize(),t.dir.x=a.x,t.dir.y=a.y,t.dir.z=a.z,t}sphereOverlap(t,e){return this.rapierColliderArray.length=0,this._isInitialized?this.world?(this.rapierSphere??(this.rapierSphere=new exports.MODULES.RAPIER_PHYSICS.MODULE.Ball(e)),this.rapierSphere.radius=e,(this.debugRenderRaycasts||yp)&&N.DrawWireSphere(t,e,3359999,1),this.world.intersectionsWithShape(t,this.rapierIdentityRotation,this.rapierSphere,i=>{const n=i[Zt],o=new Uv(n.gameObject,n);return this.rapierColliderArray.push(o),!0},void 0,void 0,void 0,void 0,i=>i.isSensor()?!1:i[Zt].gameObject.layers.isEnabled(2)==!1),this.rapierColliderArray):this.rapierColliderArray:this.rapierColliderArray}get world(){return this._world}get isUpdating(){return this._isUpdatingPhysicsWorld}get gravity(){var t;return((t=this.world)==null?void 0:t.gravity)??this._gravity}set gravity(t){this.world?this.world.gravity=t:this._gravity=t}clearCaches(){var t,e,i,n;this._meshCache.clear(),(t=this.eventQueue)!=null&&t.raw&&((e=this.eventQueue)==null||e.free()),(i=this.world)!=null&&i.bodies&&((n=this.world)==null||n.free())}async addBoxCollider(t,e){if(this._isInitialized||await this.initialize(),!t.activeAndEnabled)return;if(!this.enabled){He&&console.warn("Physics are disabled");return}const i=t.gameObject,n=Ue(i,this._tempPosition).multiply(e);n.multiplyScalar(.5),n.x<0&&(n.x=Math.abs(n.x)),n.y<0&&(n.y=Math.abs(n.y)),n.z<0&&(n.z=Math.abs(n.z));const o=1e-7;n.x<o&&(n.x=o),n.y<o&&(n.y=o),n.z<o&&(n.z=o);const a=exports.MODULES.RAPIER_PHYSICS.MODULE.ColliderDesc.cuboid(n.x,n.y,n.z);this.createCollider(t,a)}async addSphereCollider(t){if(this._isInitialized||await this.initialize(),!t.activeAndEnabled)return;if(!this.enabled){He&&console.warn("Physics are disabled");return}const e=exports.MODULES.RAPIER_PHYSICS.MODULE.ColliderDesc.ball(.5);this.createCollider(t,e),this.updateProperties(t)}async addCapsuleCollider(t,e,i){if(this._isInitialized||await this.initialize(),!t.activeAndEnabled)return;if(!this.enabled){He&&console.warn("Physics are disabled");return}const n=t.gameObject,o=Ue(n,this._tempPosition);o.x=Math.abs(o.x),o.y=Math.abs(o.y);const a=i*o.x;e=Math.max(e,a*2);const l=z.clamp(e*.5*o.y-i*o.x,0,Number.MAX_SAFE_INTEGER),c=exports.MODULES.RAPIER_PHYSICS.MODULE.ColliderDesc.capsule(l,a);this.createCollider(t,c)}async addMeshCollider(t,e,i,n){var f,m,g;let o=e.geometry;if(!o){He&&console.warn("Missing mesh geometry",e.name);return}(m=(f=o.index)==null?void 0:f.array)!=null&&m.length||(console.warn(`Your MeshCollider is missing vertices or indices in the assined mesh "${e.name}". Consider providing an indexed geometry.`),o=Y.mergeVertices(o));let a=null;const l=o.getAttribute("position");if(l instanceof h.InterleavedBufferAttribute){const y=l.count;a=new Float32Array(y*3);for(let _=0;_<y;_++){const b=l.getX(_),v=l.getY(_),w=l.getZ(_);a[_*3]=b,a[_*3+1]=v,a[_*3+2]=w}}else a=l.array;if(await this.initialize(),!this.enabled){He&&console.warn("Physics are disabled");return}if(!t.activeAndEnabled)return;const c=(g=o.index)==null?void 0:g.array,d=t.gameObject.worldScale.clone();if(n&&d.multiply(n),Math.abs(d.x-1)>1e-4||Math.abs(d.y-1)>1e-4||Math.abs(d.z-1)>1e-4){const y=`${o.uuid}_${d.x}_${d.y}_${d.z}_${i}`;if(this._meshCache.has(y))He&&console.warn("Use cached mesh collider"),a=this._meshCache.get(y);else{(He||I())&&console.debug(`[Performance] Your MeshCollider "${t.name}" is scaled: consider applying the scale to the collider mesh instead (${d.x}, ${d.y}, ${d.z})`);const _=new Float32Array(a.length);for(let b=0;b<a.length;b+=3)_[b]=a[b]*d.x,_[b+1]=a[b+1]*d.y,_[b+2]=a[b+2]*d.z;a=_,this._meshCache.set(y,_)}}const u=i?exports.MODULES.RAPIER_PHYSICS.MODULE.ColliderDesc.convexHull(a):exports.MODULES.RAPIER_PHYSICS.MODULE.ColliderDesc.trimesh(a,c);u&&this.createCollider(t,u)}updatePhysicsMaterial(t){if(!t)return;const e=t.sharedMaterial,i=t[Ut];if(i&&e){if(e.bounciness!==void 0&&i.setRestitution(e.bounciness),e.bounceCombine!==void 0)switch(e.bounceCombine){case lt.Average:i.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case lt.Maximum:i.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case lt.Minimum:i.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case lt.Multiply:i.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}if(e.dynamicFriction!==void 0&&i.setFriction(e.dynamicFriction),e.frictionCombine!==void 0)switch(e.frictionCombine){case lt.Average:i.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case lt.Maximum:i.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case lt.Minimum:i.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case lt.Multiply:i.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}}}getBody(t){return t?t[Ut]:null}getComponent(t){return t?t[Zt]:null}createCollider(t,e){var a;if(!this.world)throw new Error("Physics world not initialized");const i=this._tempMatrix;let n;t.attachedRigidbody?n=this.getRigidbody(t,this._tempMatrix):(He&&console.log("Create collider without rigidbody",t.name),i.makeRotationFromQuaternion(ye(t.gameObject)),i.setPosition(Z(t.gameObject))),i.decompose(this._tempPosition,this._tempQuaternion,this._tempScale),this.tryApplyCenter(t,this._tempPosition),e.setTranslation(this._tempPosition.x,this._tempPosition.y,this._tempPosition.z),e.setRotation(this._tempQuaternion),e.setSensor(t.isTrigger);const o=t.sharedMaterial;if(o){if(o.bounciness!==void 0&&e.setRestitution(o.bounciness),o.bounceCombine!==void 0)switch(o.bounceCombine){case lt.Average:e.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case lt.Maximum:e.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case lt.Minimum:e.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case lt.Multiply:e.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}if(o.dynamicFriction!==void 0&&e.setFriction(o.dynamicFriction),o.frictionCombine!==void 0)switch(o.frictionCombine){case lt.Average:e.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case lt.Maximum:e.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case lt.Minimum:e.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case lt.Multiply:e.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}}((a=t.attachedRigidbody)==null?void 0:a.autoMass)===!1&&(e.setDensity(1e-6),e.setMass(1e-6));try{const l=this.world.createCollider(e,n);return l[Zt]=t,t[Ut]=l,l.setActiveEvents(exports.MODULES.RAPIER_PHYSICS.MODULE.ActiveEvents.COLLISION_EVENTS),l.setActiveCollisionTypes(exports.MODULES.RAPIER_PHYSICS.MODULE.ActiveCollisionTypes.ALL),this.objects.push(t),this.bodies.push(l),this.updateColliderCollisionGroups(t),l}catch(l){return console.error('Error creating collider "'+t.name+`"
1523
+ `,o)}}setPublicKey(){Jl.length>0&&this.setAttribute("public-key",Jl)}setVersion(){hn.length>0&&this.setAttribute("version",hn)}getAROverlayContainer(){return this._overlay_ar.createOverlayContainer(this)}getVROverlayContainer(){for(let e=0;e<this.children.length;e++){const i=this.children[e];if(i.classList.contains("vr"))return i}return null}onEnterAR(e){var n;this.onSetupAR();const i=this.getAROverlayContainer();this._overlay_ar.onBegin(this._context,i,e),this.dispatchEvent(new CustomEvent("enter-ar",{detail:{session:e,context:this._context,htmlContainer:(n=this._overlay_ar)==null?void 0:n.ARContainer}}))}onExitAR(e){var i;this._overlay_ar.onEnd(this._context),this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-ar",{detail:{session:e,context:this._context,htmlContainer:(i=this._overlay_ar)==null?void 0:i.ARContainer}}))}onEnterVR(e){this.onSetupVR(),this.dispatchEvent(new CustomEvent("enter-vr",{detail:{session:e,context:this._context}}))}onExitVR(e){this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-vr",{detail:{session:e,context:this._context}}))}onSetupAR(){this.classList.add(Rl),this.classList.remove(El);const e=this.getAROverlayContainer();Se&&console.warn("onSetupAR:",e),e&&(e.classList.add(Rl),e.classList.remove(El)),this.foreachHtmlElement(i=>this.setupElementsForMode(i,rx))}onSetupVR(){this.classList.remove(Rl),this.classList.remove(El),this.foreachHtmlElement(e=>this.setupElementsForMode(e,ax))}onSetupDesktop(){this.classList.remove(Rl),this.classList.add(El);const e=this.getAROverlayContainer();e&&(e.classList.remove(Rl),e.classList.add(El)),this.foreachHtmlElement(i=>this.setupElementsForMode(i,lx))}setupElementsForMode(e,i,n=null){var a,l;if(e===((l=(a=this._context)==null?void 0:a.renderer)==null?void 0:l.domElement)||e.id==="VRButton"||e.id==="ARButton")return;if(e.classList.contains(i))e.style.visibility="visible",e.style.display==="none"&&(e.style.display="block");else for(const c of UT)e.classList.contains(c)&&(e.style.visibility="hidden",e.style.display="none")}foreachHtmlElement(e){for(let i=0;i<this.children.length;i++){const n=this.children[i];n.style&&e(n)}}onBeforeBeginLoading(){const e=this.getAttribute("dracoDecoderPath");e&&(Se&&console.log("using custom draco decoder path",e),P_(e));const i=this.getAttribute("dracoDecoderType");i&&(Se&&console.log("using custom draco decoder type",i),O_(i));const n=this.getAttribute("ktx2DecoderPath");n&&(Se&&console.log("using custom ktx2 decoder path",n),M_(n))}}typeof window<"u"&&!window.customElements.get(Sb)&&window.customElements.define(Sb,my);function NT(s){if(s.startsWith("blob:"))return"blob";const t=s.split("/");let e=t[t.length-1];const i=e.indexOf("?");i>0&&(e=e.substring(0,i));const n=e.indexOf("=");n>0&&(e=e.substring(n));const o=e.split(".").pop(),l=o?["glb","gltf","usdz","usd","fbx","obj","mtl"].indexOf(o.toLowerCase()):-1;if(o&&l>=0&&(e=e.substring(0,e.length-o.length-1)),e=decodeURIComponent(e),e.length>3){let c="",d=!1;const u=["(",")","[","]","{","}",":",";",",",".","!","?"];for(let f=0;f<e.length;f++){let m=e[f];(m==="_"||m==="-")&&(m=" "),!(m===" "&&c.length<=0||u.includes(m)||(c.length===0&&(m=m.toUpperCase()),d&&m===" "))&&(d&&(m=m.toUpperCase()),d=!1,c+=m,m===" "&&(d=!0))}return I()&&e!==c&&console.debug('Generated display name: "'+e+'" → "'+c+'"'),c.trim()}return I()&&console.debug("Loading: use default name",e),e}const VT=Object.freeze(Object.defineProperty({__proto__:null,NeedleEngineHTMLElement:my},Symbol.toStringTag,{value:"Module"}));function $T(){$i.registerWaitForInteraction(()=>{const s=h.AudioContext.getContext();s.addEventListener("statechange",()=>{setTimeout(()=>{const t=s.state;(t==="suspended"||t==="interrupted")&&s.resume().then(()=>{console.log("AudioContext resumed successfully")}).catch(e=>{console.log("Failed to resume AudioContext: "+e)})},500)})})}setTimeout($T,1e3);const He=x("debugphysics"),mp=x("debugcolliderplacement"),gp=x("debugcollisions"),WT=x("showcolliders"),yp=x("debugraycasts"),Zt=Symbol("needle component"),Ut=Symbol("physics body"),Cb=Symbol("rigidbody");globalThis.true=globalThis.true!==void 0?globalThis.true:!0;He&&console.log("Use Rapier",!0,globalThis.true);re.registerCallback(de.ContextCreationStart,s=>{He&&console.log("Register rapier physics backend"),s.context.physics.engine=new Xs(s.context)});const xc=class{constructor(t){r(this,"debugRenderColliders",!1);r(this,"debugRenderRaycasts",!1);r(this,"context");r(this,"_initializePromise");r(this,"_isInitialized",!1);r(this,"rapierRay");r(this,"raycastVectorsBuffer",new Si(()=>new h.Vector3,10));r(this,"rapierSphere",null);r(this,"rapierColliderArray",[]);r(this,"rapierIdentityRotation",{x:0,y:0,z:0,w:1});r(this,"rapierForwardVector",{x:0,y:0,z:1});r(this,"enabled",!1);r(this,"_tempPosition",new h.Vector3);r(this,"_tempQuaternion",new h.Quaternion);r(this,"_tempScale",new h.Vector3);r(this,"_tempMatrix",new h.Matrix4);r(this,"_isUpdatingPhysicsWorld",!1);r(this,"_world");r(this,"_hasCreatedWorld",!1);r(this,"eventQueue");r(this,"collisionHandler");r(this,"objects",[]);r(this,"bodies",[]);r(this,"_meshCache",new Map);r(this,"_gravity",{x:0,y:-9.81,z:0});r(this,"lines");r(this,"_tempCenterPos",new h.Vector3);r(this,"_tempCenterVec",new h.Vector3);r(this,"_tempCenterQuaternion",new h.Quaternion);this.context=t}removeBody(t){var i,n,o;if(!t)return;this.validate();const e=t[Ut];if(t[Ut]=null,e&&this.world){const a=this.objects.findIndex(l=>l===t);if(a>=0){const l=this.bodies[a];if(this.bodies.splice(a,1),this.objects.splice(a,1),l instanceof exports.MODULES.RAPIER_PHYSICS.MODULE.Collider){const c=l;(i=this.world)==null||i.removeCollider(c,!0);const d=c.parent();d&&d.numColliders()<=0&&(d[Zt]||(n=this.world)==null||n.removeRigidBody(d))}else l instanceof exports.MODULES.RAPIER_PHYSICS.MODULE.RigidBody&&(l.numColliders()<=0?(o=this.world)==null||o.removeRigidBody(l):I()&&(l.did_log_removing||setTimeout(()=>{l.numColliders()>0&&(l.did_log_removing=!0,console.warn("RapierPhysics: removing rigidbody with colliders from the physics world is not possible right now, please remove the colliders first"))},1)))}}}updateBody(t,e,i){if(this.validate(),!!this.enabled&&!(t.destroyed||!t.gameObject)&&!(!e&&!i))if(t.isCollider===!0)console.warn("TODO: implement updating collider position");else{const n=t,o=n[Ut];o&&this.syncPhysicsBody(n.gameObject,o,e,i)}}updateProperties(t){if(this.validate(),t.isCollider){const e=t,i=e[Ut];i&&(this.internalUpdateColliderProperties(e,i),e.sharedMaterial&&this.updatePhysicsMaterial(e))}else{const e=t,i=this.internal_getRigidbody(e);i&&this.internalUpdateRigidbodyProperties(e,i)}}addForce(t,e,i){this.validate();const n=this.internal_getRigidbody(t);n?n.addForce(e,i):console.warn("Rigidbody doesn't exist: can not apply force (does your object with the Rigidbody have a collider?)")}addImpulse(t,e,i){this.validate();const n=this.internal_getRigidbody(t);n?n.applyImpulse(e,i):console.warn("Rigidbody doesn't exist: can not apply impulse (does your object with the Rigidbody have a collider?)")}getLinearVelocity(t){this.validate();const e=this.internal_getRigidbody(t);return e?e.linvel():null}getAngularVelocity(t){this.validate();const e=this.internal_getRigidbody(t);return e?e.angvel():null}resetForces(t,e){this.validate();const i=this.internal_getRigidbody(t);i==null||i.resetForces(e)}resetTorques(t,e){this.validate();const i=this.internal_getRigidbody(t);i==null||i.resetTorques(e)}applyImpulse(t,e,i){this.validate();const n=this.internal_getRigidbody(t);n?n.applyImpulse(e,i):console.warn("Rigidbody doesn't exist: can not apply impulse (does your object with the Rigidbody have a collider?)")}wakeup(t){this.validate();const e=this.internal_getRigidbody(t);e?e.wakeUp():console.warn("Rigidbody doesn't exist: can not wake up (does your object with the Rigidbody have a collider?)")}isSleeping(t){this.validate();const e=this.internal_getRigidbody(t);return e==null?void 0:e.isSleeping()}setAngularVelocity(t,e,i){this.validate();const n=this.internal_getRigidbody(t);n?n.setAngvel(e,i):console.warn("Rigidbody doesn't exist: can not set angular velocity (does your object with the Rigidbody have a collider?)")}setLinearVelocity(t,e,i){this.validate();const n=this.internal_getRigidbody(t);n?n.setLinvel(e,i):console.warn("Rigidbody doesn't exist: can not set linear velocity (does your object with the Rigidbody have a collider?)")}get isInitialized(){return this._isInitialized}async initialize(){return this._initializePromise||(this._initializePromise=this.internalInitialization()),this._initializePromise}async internalInitialization(){return x("__nophysics")?(console.warn("Physics are disabled"),!1):(He&&console.log("Initialize rapier physics engine"),"env"in{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:ga&&ga.tagName.toUpperCase()==="SCRIPT"&&ga.src||new URL("needle-engine.bundle-ef2b8438.umd.cjs",document.baseURI).href}&&{}.VITE_NEEDLE_USE_RAPIER==="false"?(He&&console.log("Rapier disabled"),!1):this._hasCreatedWorld?(console.error("Invalid call to create physics world: world is already created"),!0):(this._hasCreatedWorld=!0,exports.MODULES.RAPIER_PHYSICS.MAYBEMODULE==null&&(He&&console.trace("Loading rapier physics engine"),await(await exports.MODULES.RAPIER_PHYSICS.load()).init()),He&&console.log("Physics engine initialized, creating world..."),this._world=new exports.MODULES.RAPIER_PHYSICS.MODULE.World(this._gravity),this.rapierRay=new exports.MODULES.RAPIER_PHYSICS.MODULE.Ray({x:0,y:0,z:0},{x:0,y:0,z:1}),this.enabled=!0,this._isInitialized=!0,He&&console.log("Physics world created"),!0))}validate(){this._isInitialized||He&&(this._lastWarnTime=this._lastWarnTime??0,Date.now()-this._lastWarnTime>1e3&&(this._lastWarnTime=Date.now(),console.warn("Physics engine is not initialized")))}raycast(t,e,i){var c;if(!this._isInitialized)return console.log("Physics engine is not initialized"),null;let n=i==null?void 0:i.maxDistance,o=i==null?void 0:i.solid;n===void 0&&(n=1/0),o===void 0&&(o=!0);const a=this.getPhysicsRay(this.rapierRay,t,e);if(!a)return null;(this.debugRenderRaycasts||yp)&&N.DrawRay(a.origin,a.dir,255,1);const l=(c=this.world)==null?void 0:c.castRay(a,n,o,i==null?void 0:i.queryFilterFlags,i==null?void 0:i.filterGroups,void 0,void 0,d=>{const u=d[Zt];return i!=null&&i.filterPredicate?i.filterPredicate(u):(i==null?void 0:i.useIgnoreRaycastLayer)!==!1?!(u!=null&&u.gameObject.layers.isEnabled(2)):!0});if(l){const d=a.pointAt(l.timeOfImpact),u=this.raycastVectorsBuffer.get();return u.set(d.x,d.y,d.z),{point:u,collider:l.collider[Zt]}}return null}raycastAndGetNormal(t,e,i){var c;if(!this._isInitialized)return null;let n=i==null?void 0:i.maxDistance,o=i==null?void 0:i.solid;n===void 0&&(n=1/0),o===void 0&&(o=!0);const a=this.getPhysicsRay(this.rapierRay,t,e);if(!a)return null;(this.debugRenderRaycasts||yp)&&N.DrawRay(a.origin,a.dir,255,1);const l=(c=this.world)==null?void 0:c.castRayAndGetNormal(a,n,o,i==null?void 0:i.queryFilterFlags,i==null?void 0:i.filterGroups,void 0,void 0,d=>{const u=d[Zt];return i!=null&&i.filterPredicate?i.filterPredicate(u):(i==null?void 0:i.useIgnoreRaycastLayer)!==!1?!(u!=null&&u.gameObject.layers.isEnabled(2)):!0});if(l){const d=a.pointAt(l.timeOfImpact),u=l.normal,f=this.raycastVectorsBuffer.get(),m=this.raycastVectorsBuffer.get();return f.set(d.x,d.y,d.z),m.set(u.x,u.y,u.z),{point:f,normal:m,collider:l.collider[Zt]}}return null}getPhysicsRay(t,e,i){var l,c,d;const n=(l=this.context)==null?void 0:l.mainCamera;if(e===void 0){const u=(c=this.context)==null?void 0:c.input.getPointerPosition(0);if(u)e=u;else return null}if(e.z===void 0){if(!n)return console.error("Can not perform raycast from 2d point - no main camera found"),null;const u=this.raycastVectorsBuffer.get();u.x=e.x,u.y=e.y,u.z=0,(u.x>1||u.y>1||u.y<-1||u.x<-1)&&(He&&console.warn("Converting screenspace to raycast space",u),(d=this.context)==null||d.input.convertScreenspaceToRaycastSpace(u)),u.unproject(n),e=u}const o=e;t.origin.x=o.x,t.origin.y=o.y,t.origin.z=o.z;const a=this.raycastVectorsBuffer.get();if(i)a.set(i.x,i.y,i.z);else{if(!n)return console.error("Can not perform raycast - no camera found"),null;a.set(t.origin.x,t.origin.y,t.origin.z);const u=Z(n);a.sub(u)}return a.normalize(),t.dir.x=a.x,t.dir.y=a.y,t.dir.z=a.z,t}sphereOverlap(t,e){return this.rapierColliderArray.length=0,this._isInitialized?this.world?(this.rapierSphere??(this.rapierSphere=new exports.MODULES.RAPIER_PHYSICS.MODULE.Ball(e)),this.rapierSphere.radius=e,(this.debugRenderRaycasts||yp)&&N.DrawWireSphere(t,e,3359999,1),this.world.intersectionsWithShape(t,this.rapierIdentityRotation,this.rapierSphere,i=>{const n=i[Zt],o=new Uv(n.gameObject,n);return this.rapierColliderArray.push(o),!0},void 0,void 0,void 0,void 0,i=>i.isSensor()?!1:i[Zt].gameObject.layers.isEnabled(2)==!1),this.rapierColliderArray):this.rapierColliderArray:this.rapierColliderArray}get world(){return this._world}get isUpdating(){return this._isUpdatingPhysicsWorld}get gravity(){var t;return((t=this.world)==null?void 0:t.gravity)??this._gravity}set gravity(t){this.world?this.world.gravity=t:this._gravity=t}clearCaches(){var t,e,i,n;this._meshCache.clear(),(t=this.eventQueue)!=null&&t.raw&&((e=this.eventQueue)==null||e.free()),(i=this.world)!=null&&i.bodies&&((n=this.world)==null||n.free())}async addBoxCollider(t,e){if(this._isInitialized||await this.initialize(),!t.activeAndEnabled)return;if(!this.enabled){He&&console.warn("Physics are disabled");return}const i=t.gameObject,n=Ue(i,this._tempPosition).multiply(e);n.multiplyScalar(.5),n.x<0&&(n.x=Math.abs(n.x)),n.y<0&&(n.y=Math.abs(n.y)),n.z<0&&(n.z=Math.abs(n.z));const o=1e-7;n.x<o&&(n.x=o),n.y<o&&(n.y=o),n.z<o&&(n.z=o);const a=exports.MODULES.RAPIER_PHYSICS.MODULE.ColliderDesc.cuboid(n.x,n.y,n.z);this.createCollider(t,a)}async addSphereCollider(t){if(this._isInitialized||await this.initialize(),!t.activeAndEnabled)return;if(!this.enabled){He&&console.warn("Physics are disabled");return}const e=exports.MODULES.RAPIER_PHYSICS.MODULE.ColliderDesc.ball(.5);this.createCollider(t,e),this.updateProperties(t)}async addCapsuleCollider(t,e,i){if(this._isInitialized||await this.initialize(),!t.activeAndEnabled)return;if(!this.enabled){He&&console.warn("Physics are disabled");return}const n=t.gameObject,o=Ue(n,this._tempPosition);o.x=Math.abs(o.x),o.y=Math.abs(o.y);const a=i*o.x;e=Math.max(e,a*2);const l=z.clamp(e*.5*o.y-i*o.x,0,Number.MAX_SAFE_INTEGER),c=exports.MODULES.RAPIER_PHYSICS.MODULE.ColliderDesc.capsule(l,a);this.createCollider(t,c)}async addMeshCollider(t,e,i,n){var f,m,g;let o=e.geometry;if(!o){He&&console.warn("Missing mesh geometry",e.name);return}(m=(f=o.index)==null?void 0:f.array)!=null&&m.length||(console.warn(`Your MeshCollider is missing vertices or indices in the assined mesh "${e.name}". Consider providing an indexed geometry.`),o=Y.mergeVertices(o));let a=null;const l=o.getAttribute("position");if(l instanceof h.InterleavedBufferAttribute){const y=l.count;a=new Float32Array(y*3);for(let _=0;_<y;_++){const b=l.getX(_),v=l.getY(_),w=l.getZ(_);a[_*3]=b,a[_*3+1]=v,a[_*3+2]=w}}else a=l.array;if(await this.initialize(),!this.enabled){He&&console.warn("Physics are disabled");return}if(!t.activeAndEnabled)return;const c=(g=o.index)==null?void 0:g.array,d=t.gameObject.worldScale.clone();if(n&&d.multiply(n),Math.abs(d.x-1)>1e-4||Math.abs(d.y-1)>1e-4||Math.abs(d.z-1)>1e-4){const y=`${o.uuid}_${d.x}_${d.y}_${d.z}_${i}`;if(this._meshCache.has(y))He&&console.warn("Use cached mesh collider"),a=this._meshCache.get(y);else{(He||I())&&console.debug(`[Performance] Your MeshCollider "${t.name}" is scaled: consider applying the scale to the collider mesh instead (${d.x}, ${d.y}, ${d.z})`);const _=new Float32Array(a.length);for(let b=0;b<a.length;b+=3)_[b]=a[b]*d.x,_[b+1]=a[b+1]*d.y,_[b+2]=a[b+2]*d.z;a=_,this._meshCache.set(y,_)}}const u=i?exports.MODULES.RAPIER_PHYSICS.MODULE.ColliderDesc.convexHull(a):exports.MODULES.RAPIER_PHYSICS.MODULE.ColliderDesc.trimesh(a,c);u&&this.createCollider(t,u)}updatePhysicsMaterial(t){if(!t)return;const e=t.sharedMaterial,i=t[Ut];if(i&&e){if(e.bounciness!==void 0&&i.setRestitution(e.bounciness),e.bounceCombine!==void 0)switch(e.bounceCombine){case lt.Average:i.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case lt.Maximum:i.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case lt.Minimum:i.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case lt.Multiply:i.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}if(e.dynamicFriction!==void 0&&i.setFriction(e.dynamicFriction),e.frictionCombine!==void 0)switch(e.frictionCombine){case lt.Average:i.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case lt.Maximum:i.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case lt.Minimum:i.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case lt.Multiply:i.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}}}getBody(t){return t?t[Ut]:null}getComponent(t){return t?t[Zt]:null}createCollider(t,e){var a;if(!this.world)throw new Error("Physics world not initialized");const i=this._tempMatrix;let n;t.attachedRigidbody?n=this.getRigidbody(t,this._tempMatrix):(He&&console.log("Create collider without rigidbody",t.name),i.makeRotationFromQuaternion(ye(t.gameObject)),i.setPosition(Z(t.gameObject))),i.decompose(this._tempPosition,this._tempQuaternion,this._tempScale),this.tryApplyCenter(t,this._tempPosition),e.setTranslation(this._tempPosition.x,this._tempPosition.y,this._tempPosition.z),e.setRotation(this._tempQuaternion),e.setSensor(t.isTrigger);const o=t.sharedMaterial;if(o){if(o.bounciness!==void 0&&e.setRestitution(o.bounciness),o.bounceCombine!==void 0)switch(o.bounceCombine){case lt.Average:e.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case lt.Maximum:e.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case lt.Minimum:e.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case lt.Multiply:e.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}if(o.dynamicFriction!==void 0&&e.setFriction(o.dynamicFriction),o.frictionCombine!==void 0)switch(o.frictionCombine){case lt.Average:e.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case lt.Maximum:e.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case lt.Minimum:e.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case lt.Multiply:e.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}}((a=t.attachedRigidbody)==null?void 0:a.autoMass)===!1&&(e.setDensity(1e-6),e.setMass(1e-6));try{const l=this.world.createCollider(e,n);return l[Zt]=t,t[Ut]=l,l.setActiveEvents(exports.MODULES.RAPIER_PHYSICS.MODULE.ActiveEvents.COLLISION_EVENTS),l.setActiveCollisionTypes(exports.MODULES.RAPIER_PHYSICS.MODULE.ActiveCollisionTypes.ALL),this.objects.push(t),this.bodies.push(l),this.updateColliderCollisionGroups(t),l}catch(l){return console.error('Error creating collider "'+t.name+`"
1524
1524
  Error:`,l),null}}updateColliderCollisionGroups(t){const e=t[Ut],i=t.membership;let n=0;if(i==null)n=65535;else for(let l=0;l<i.length;l++){const c=i[l];c>31?console.error(`Rapier only supports 32 layers, layer ${c} is not supported`):n|=1<<Math.floor(c)}const o=t.filter;let a=0;if(o==null)a=65535;else for(let l=0;l<o.length;l++){const c=o[l];c>31?console.error(`Rapier only supports 32 layers, layer ${c} is not supported`):a|=1<<Math.floor(c)}e.setCollisionGroups(n<<16|a)}getRigidbody(t,e){if(!this.world)throw new Error("Physics world not initialized");let i=null;if(t.attachedRigidbody){const n=t.attachedRigidbody;if(i=n[Ut],!i){const o=n.isKinematic&&!mp;He&&console.log("Create rigidbody",o);const a=o?exports.MODULES.RAPIER_PHYSICS.MODULE.RigidBodyDesc.kinematicPositionBased():exports.MODULES.RAPIER_PHYSICS.MODULE.RigidBodyDesc.dynamic(),l=Z(t.attachedRigidbody.gameObject);a.setTranslation(l.x,l.y,l.z),a.setRotation(ye(t.attachedRigidbody.gameObject)),a.centerOfMass=new exports.MODULES.RAPIER_PHYSICS.MODULE.Vector3(n.centerOfMass.x,n.centerOfMass.y,n.centerOfMass.z),i=this.world.createRigidBody(a),this.bodies.push(i),this.objects.push(n)}i[Zt]=n,n[Ut]=i,this.internalUpdateRigidbodyProperties(n,i),this.getRigidbodyRelativeMatrix(t.gameObject,n.gameObject,e),t[Cb]=i}else{const n=exports.MODULES.RAPIER_PHYSICS.MODULE.RigidBodyDesc.kinematicPositionBased(),o=Z(t.gameObject);n.setTranslation(o.x,o.y,o.z),n.setRotation(ye(t.gameObject)),i=this.world.createRigidBody(n),e.identity(),i[Zt]=null}return i}internal_getRigidbody(t){return t.isCollider===!0?t[Cb]:t[Ut]}internalUpdateColliderProperties(t,e){const i=e.shape;let n=!1;switch(i.type){case exports.MODULES.RAPIER_PHYSICS.MODULE.ShapeType.Ball:{const m=i,g=t,y=t.gameObject,_=Ue(y,this._tempPosition),b=Math.abs(g.radius*_.x);n=m.radius!==b,m.radius=b,n&&e.setShape(m);break}case exports.MODULES.RAPIER_PHYSICS.MODULE.ShapeType.Cuboid:const o=i,a=t,l=t.gameObject,c=Ue(l,this._tempPosition),d=Math.abs(a.size.x*.5*c.x),u=Math.abs(a.size.y*.5*c.y),f=Math.abs(a.size.z*.5*c.z);n=o.halfExtents.x!==d||o.halfExtents.y!==u||o.halfExtents.z!==f,o.halfExtents.x=d,o.halfExtents.y=u,o.halfExtents.z=f,n&&e.setShape(o);break}if(n){const o=t.attachedRigidbody;if(o!=null&&o.autoMass){const a=this.getBody(o);a==null||a.recomputeMassPropertiesFromColliders()}}this.updateColliderCollisionGroups(t),t.isTrigger!==e.isSensor()&&e.setSensor(t.isTrigger)}internalUpdateRigidbodyProperties(t,e){if(e.enableCcd(t.collisionDetectionMode!==Lu.Discrete),e.setLinearDamping(t.drag),e.setAngularDamping(t.angularDrag),e.setGravityScale(t.useGravity?t.gravityScale:0,!0),t.dominanceGroup<=127&&t.dominanceGroup>=-127?e.setDominanceGroup(Math.floor(t.dominanceGroup)):e.setDominanceGroup(0),t.autoMass){e.setAdditionalMass(0,!1);for(let i=0;i<e.numColliders();i++)e.collider(i).setDensity(1);e.recomputeMassPropertiesFromColliders()}else{e.setAdditionalMass(t.mass,!1);for(let i=0;i<e.numColliders();i++)e.collider(i).setDensity(1e-7);e.recomputeMassPropertiesFromColliders()}e.setEnabledRotations(!t.lockRotationX,!t.lockRotationY,!t.lockRotationZ,!1),e.setEnabledTranslations(!t.lockPositionX,!t.lockPositionY,!t.lockPositionZ,!1),t.isKinematic?e.setBodyType(exports.MODULES.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicPositionBased,!1):e.setBodyType(exports.MODULES.RAPIER_PHYSICS.MODULE.RigidBodyType.Dynamic,!1)}step(t){if(this.world&&this.enabled){if(this._isUpdatingPhysicsWorld=!0,this.eventQueue||(this.eventQueue=new exports.MODULES.RAPIER_PHYSICS.MODULE.EventQueue(!1)),t===void 0||t<=0){this._isUpdatingPhysicsWorld=!1;return}else t!==void 0&&(this.world.timestep=z.lerp(this.world.timestep,t,.8));try{this.world.step(this.eventQueue)}catch(e){console.warn("Error running physics step",e)}this._isUpdatingPhysicsWorld=!1}}postStep(){this.world&&this.enabled&&(this._isUpdatingPhysicsWorld=!0,this.syncObjects(),this._isUpdatingPhysicsWorld=!1,this.eventQueue&&!this.collisionHandler&&(this.collisionHandler=new HT(this.world,this.eventQueue)),this.collisionHandler&&(this.collisionHandler.handleCollisionEvents(),this.collisionHandler.update()),this.updateDebugRendering(this.world))}updateDebugRendering(t){var e,i,n,o;if(He||mp||WT||this.debugRenderColliders===!0){if(!this.lines){const l=new h.LineBasicMaterial({color:7855479,fog:!1}),c=new h.BufferGeometry;this.lines=new h.LineSegments(c,l),this.lines.layers.disableAll(),this.lines.layers.enable(2)}this.lines.parent!==((e=this.context)==null?void 0:e.scene)&&((i=this.context)==null||i.scene.add(this.lines));const a=t.debugRender();this.lines.geometry.setAttribute("position",new h.BufferAttribute(a.vertices,3)),this.lines.geometry.setAttribute("color",new h.BufferAttribute(a.colors,4)),(this.context.time.frame%30===0||((n=this.lines.geometry.boundingSphere)==null?void 0:n.radius)===0)&&this.lines.geometry.computeBoundingSphere()}else this.lines&&((o=this.context)==null||o.scene.remove(this.lines))}syncObjects(){if(!mp)for(let t=0;t<this.bodies.length;t++){const e=this.objects[t],i=this.bodies[t],n=e;if((n==null?void 0:n.isCollider)===!0&&!n.attachedRigidbody){const c=i.parent();c?this.syncPhysicsBody(e.gameObject,c,!0,!0):this.syncPhysicsBody(e.gameObject,i,!0,!0);continue}const o=i.translation(),a=i.rotation();if(Number.isNaN(o.x)||Number.isNaN(a.x)){!n.__COLLIDER_NAN&&I()&&(console.warn("Collider has NaN values",n.name,n.gameObject,i),n.__COLLIDER_NAN=!0);continue}const l=e.center;if(l&&l.isVector3){this._tempQuaternion.set(a.x,a.y,a.z,a.w);const c=this._tempPosition.copy(l).applyQuaternion(this._tempQuaternion),d=Ue(e.gameObject);c.multiply(d),o.x-=c.x,o.y-=c.y,o.z-=c.z}rr(e.gameObject,o.x,o.y,o.z),Lm(e.gameObject,a.x,a.y,a.z,a.w)}}syncPhysicsBody(t,e,i,n){if(e instanceof exports.MODULES.RAPIER_PHYSICS.MODULE.RigidBody){const o=Z(t,this._tempPosition),a=ye(t,this._tempQuaternion);switch(e.bodyType()){case exports.MODULES.RAPIER_PHYSICS.MODULE.RigidBodyType.Fixed:case exports.MODULES.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicPositionBased:case exports.MODULES.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicVelocityBased:i&&e.setNextKinematicTranslation(o),n&&e.setNextKinematicRotation(a);break;default:i&&e.setTranslation(o,!1),n&&e.setRotation(a,!1);break}}else if(e instanceof exports.MODULES.RAPIER_PHYSICS.MODULE.Collider){t.matrixWorldNeedsUpdate&&t.updateWorldMatrix(!0,!1),t.matrixWorld.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const o=this._tempPosition,a=this._tempQuaternion,l=e[Zt];if(this.tryApplyCenter(l,o),i){const c=e.translation();(c.x!==o.x||c.y!==o.y||c.z!==o.z)&&e.setTranslation(o)}if(n){const c=e.rotation();(c.x!==a.x||c.y!==a.y||c.z!==a.z||c.w!==a.w)&&e.setRotation(a)}}}tryApplyCenter(t,e){const i=t.center;i&&t.gameObject&&(i.x!==0||i.y!==0||i.z!==0)&&(this._tempCenterPos.x=i.x,this._tempCenterPos.y=i.y,this._tempCenterPos.z=i.z,Ue(t.gameObject,this._tempCenterVec),this._tempCenterPos.multiply(this._tempCenterVec),t.attachedRigidbody?this._tempCenterPos.applyQuaternion(t.gameObject.quaternion):(ye(t.gameObject,this._tempCenterQuaternion),this._tempCenterPos.applyQuaternion(this._tempCenterQuaternion)),e.x+=this._tempCenterPos.x,e.y+=this._tempCenterPos.y,e.z+=this._tempCenterPos.z)}getRigidbodyRelativeMatrix(t,e,i,n){if(n===void 0&&(n=xc._matricesBuffer,n.length=0),t===e){const o=Ue(t,this._tempPosition);i.makeScale(o.x,o.y,o.z);for(let a=n.length-1;a>=0;a--)i.multiply(n[a]);return i}return n.push(t.matrix),t.parent&&this.getRigidbodyRelativeMatrix(t.parent,e,i,n),i}addFixedJoint(t,e){if(!this.world){console.error("Physics world not initialized");return}const i=t[Ut],n=e[Ut];this.calculateJointRelativeMatrices(t.gameObject,e.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const o=exports.MODULES.RAPIER_PHYSICS.MODULE.JointData.fixed(xc.centerConnectionPos,xc.centerConnectionRot,this._tempPosition,this._tempQuaternion),a=this.world.createImpulseJoint(o,i,n,!0);He&&console.log("ADD FIXED JOINT",a)}addHingeJoint(t,e,i,n){if(!this.world){console.error("Physics world not initialized");return}const o=t[Ut],a=e[Ut];this.calculateJointRelativeMatrices(t.gameObject,e.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const l=exports.MODULES.RAPIER_PHYSICS.MODULE.JointData.revolute(i,this._tempPosition,n),c=this.world.createImpulseJoint(l,o,a,!0);He&&console.log("ADD HINGE JOINT",c)}calculateJointRelativeMatrices(t,e,i){t.updateWorldMatrix(!0,!1),e.updateWorldMatrix(!0,!1);const n=t.matrixWorld,o=e.matrixWorld;n.elements[0]=1,n.elements[5]=1,n.elements[10]=1,o.elements[0]=1,o.elements[5]=1,o.elements[10]=1,i.copy(o).premultiply(n.invert()).invert()}};let Xs=xc;r(Xs,"_didLoadPhysicsEngine",!1),r(Xs,"_matricesBuffer",[]),r(Xs,"centerConnectionPos",{x:0,y:0,z:0}),r(Xs,"centerConnectionRot",{x:0,y:0,z:0,w:1});class HT{constructor(t,e){r(this,"world");r(this,"eventQueue");r(this,"activeCollisions",[]);r(this,"activeCollisionsStay",[]);r(this,"activeTriggers",[]);this.world=t,this.eventQueue=e}handleCollisionEvents(){this.eventQueue&&this.world&&this.eventQueue.drainCollisionEvents((t,e,i)=>{const n=this.world.getCollider(t),o=this.world.getCollider(e);if(!n||!o)return;const a=n[Zt],l=o[Zt];gp&&console.log("EVT",a.name,l.name,i,n,o),a&&l&&(i?(this.onCollisionStarted(a,n,l,o),this.onCollisionStarted(l,o,a,n)):(this.onCollisionEnded(a,l),this.onCollisionEnded(l,a)))})}update(){this.onHandleCollisionStay()}onCollisionStarted(t,e,i,n){let o=null;if(t.isTrigger||i.isTrigger)cr(t.gameObject,a=>{a.onTriggerEnter&&!a.destroyed&&a.onTriggerEnter(i),this.activeTriggers.push({collider:t,component:a,otherCollider:i})});else{const a=t.gameObject;this.world.contactPair(e,n,(l,c)=>{cr(a,d=>{var f;if(d.destroyed)return;const u=d.onCollisionEnter||d.onCollisionStay||d.onCollisionExit;if(u||gp){if(!o){const m=[],g=l.normal();i instanceof xo&&i.convex&&(g.x=-g.x,g.y=-g.y,g.z=-g.z);for(let y=0;y<l.numSolverContacts();y++){const _=l.solverContactPoint(y),b=l.contactImpulse(y);if(_){const v=l.contactDist(y),w=l.solverContactFriction(y),C=l.solverContactTangentVelocity(y),E=new Bv(_,v,g,b,w,C);m.push(E),gp&&N.DrawDirection(_,g,16711680,3,!0)}}o=new Fv(a,i,m)}if(u){const m={collider:t,component:d,collision:o};this.activeCollisions.push(m),d.onCollisionStay&&this.activeCollisionsStay.push(m),(f=d.onCollisionEnter)==null||f.call(d,o)}}})})}}onHandleCollisionStay(){for(const t of this.activeCollisionsStay){const e=t.component;if(!e.destroyed&&e.activeAndEnabled&&e.onCollisionStay){if(t.collision.collider.destroyed)continue;const i=t.collision;e.onCollisionStay(i)}}for(const t of this.activeTriggers){const e=t.component;if(!e.destroyed&&e.activeAndEnabled&&e.onTriggerStay){const i=t.otherCollider;if(i.destroyed)continue;e.onTriggerStay(i)}}}onCollisionEnded(t,e){if(!(t.destroyed||e.destroyed)){for(let i=0;i<this.activeCollisions.length;i++){const n=this.activeCollisions[i],o=n.collider;if(o.destroyed||n.collision.collider.destroyed){this.activeCollisions.splice(i,1),i--;continue}if(o===t&&n.collision.collider===e){const a=n.component;if(this.activeCollisions.splice(i,1),i--,a.activeAndEnabled&&a.onCollisionExit){const l=n.collision;a.onCollisionExit(l)}}}for(let i=0;i<this.activeCollisionsStay.length;i++){const n=this.activeCollisionsStay[i],o=n.collider;if(o.destroyed||n.collision.collider.destroyed){this.activeCollisionsStay.splice(i,1),i--;continue}if(o===t&&n.collision.collider===e){const a=n.component;if(this.activeCollisionsStay.splice(i,1),i--,a.activeAndEnabled&&a.onCollisionExit){const l=n.collision;a.onCollisionExit(l)}}}for(let i=0;i<this.activeTriggers.length;i++){const n=this.activeTriggers[i],o=n.collider;if(o.destroyed||n.otherCollider.destroyed){this.activeTriggers.splice(i,1),i--;continue}if(o===t&&n.otherCollider===e){const a=n.component;if(this.activeTriggers.splice(i,1),i--,a.activeAndEnabled&&a.onTriggerExit){const l=n.otherCollider;a.onTriggerExit(l)}}}}}}class GT{static async createComparisonScene(t){const{files:e}=t,n=await Promise.all(e.map(b=>new ee(b).loadAssetAsync())),o=new h.Scene;let a=0;for(const b of n)if(b instanceof h.Object3D){b.position.y=a,o.add(b);const v=si([b]);a+=v.getSize(new h.Vector3).y,a+=.1}const l=new h.PerspectiveCamera(20);o.add(l);const c=t.environment||"https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/studio_small_09_1k.exr";if(c){let b=null;if(c.endsWith(".hdr")){const v=(await Promise.resolve().then(()=>require("./three-examples-a36ec195.umd.cjs")).then(w=>w.RGBELoader$1)).RGBELoader;b=new v}else if(c.endsWith(".exr")){const v=(await Promise.resolve().then(()=>require("./three-examples-a36ec195.umd.cjs")).then(w=>w.EXRLoader$1)).EXRLoader;b=new v}if(b){const v=await b.loadAsync(c).catch(w=>(console.error(w),null));v&&(v.mapping=h.EquirectangularReflectionMapping,v.needsUpdate=!0,o.background=v,o.environment=v,o.backgroundBlurriness=.75)}else console.warn("Unsupported environment map format",c)}const d=si(o.children),u=d.getCenter(new h.Vector3),f=d.getSize(new h.Vector3),g=Math.max(f.x,f.y,f.z)/(2*Math.tan(Math.PI*l.fov/360));l.position.set(u.x,u.y,g),l.lookAt(u);const y=new Y.OrbitControls(l,t.domElement||document.body);y.target=u,y.update();const _=(t.domElement||document.body).getBoundingClientRect();return l.aspect=_.width/_.height,l.updateProjectionMatrix(),{scene:o,camera:l}}}let Mm=0;function Pb(s){s?Mm++:Mm--}function qT(){return Mm>0}const XT={binary:!0,animations:!0};async function QT(s){if(!s.context)throw new Error("No context provided to exportAsGLTF");s.scene||(s.scene=s.context.scene);const t={...XT,...s},{context:e}=t,i=new Y.GLTFExporter;i.register(l=>new ew(l)),i.register(l=>new SO(l)),i.register(l=>new Qv(l)),kg(i,t.context);const n={binary:t.binary,animations:KT(e,t.scene,[])},o=new YT;console.debug("Exporting GLTF",n),o.onBeforeExport(t),Pb(!0);const a=await i.parseAsync(t.scene,n).catch(l=>(console.error(l),null));if(Pb(!1),o.onAfterExport(t),!a)throw new Error("Failed to export GLTF");if(t.downloadAs!=null){let l=null;if(a instanceof ArrayBuffer?l=new Blob([a],{type:"application/octet-stream"}):console.error("Can not download GLTF as a blob",a),l){const c=URL.createObjectURL(l),d=document.createElement("a");d.href=c;let u=t.downloadAs;!u.endsWith(".glb")&&!u.endsWith(".gltf")&&(u+=t.binary?".glb":".gltf"),d.download=u,d.click()}}return a}const Ob=Symbol("needle:weight");class YT{constructor(){r(this,"_undo",[])}onBeforeExport(t){t.context.animations.mixers.forEach(e=>{const i=Aa.tryGetActionsFromMixer(e);if(i)for(let n=0;n<i.length;n++){const o=i[n];o[Ob]=o.weight,o.weight=0,this._undo.push(()=>{o.weight=o[Ob]})}e.update(0)}),t.context.scene.traverse(e=>{if(!cm(e)){const i=e.parent;i&&(e.removeFromParent(),this._undo.push(()=>i.add(e)))}})}onAfterExport(t){this._undo.forEach(e=>e()),this._undo.length=0}}function KT(s,t,e){s.animations.mixers.forEach(n=>{const o=Aa.tryGetActionsFromMixer(n);if(o)for(let a=0;a<o.length;a++){const c=o[a].getClip();e.push(c)}}),Array.isArray(t)||(t=[t]);for(const n of t)Aa.tryGetAnimationClipsFromObjectHierarchy(n,e);const i=new Set(e);return Array.from(i)}const Mb="needle-button",_p=I();var Xo,Qo,Yo,Nt,ls,Oa,bu,cx,vu,hx,Fc;class gy extends HTMLElement{constructor(){super();Ti(this,bu);Ti(this,vu);Ti(this,Xo,void 0);Ti(this,Qo,void 0);Ti(this,Yo,void 0);Ti(this,Nt,void 0);Ti(this,ls,void 0);Ti(this,Oa,void 0);Ti(this,Fc,e=>{_p&&console.log("Needle Button clicked"),!e.defaultPrevented&&he(this,Nt)&&he(this,Nt).click()});this.removeEventListener("click",he(this,Fc)),this.addEventListener("click",he(this,Fc))}attributeChangedCallback(e,i,n){fl(this,bu,cx).call(this)}}Xo=new WeakMap,Qo=new WeakMap,Yo=new WeakMap,Nt=new WeakMap,ls=new WeakMap,Oa=new WeakMap,bu=new WeakSet,cx=function(){var i,n;if((i=he(this,Nt))==null||i.remove(),this.getAttribute("ar")!=null)he(this,ls)??Ji(this,ls,new bs),Ji(this,Nt,he(this,ls).createARButton());else if(this.getAttribute("vr")!=null)he(this,ls)??Ji(this,ls,new bs),Ji(this,Nt,he(this,ls).createVRButton());else if(this.getAttribute("quicklook")!=null)he(this,ls)??Ji(this,ls,new bs),Ji(this,Nt,he(this,ls).createQuicklookButton());else{_p?console.warn("No button type specified for <needle-button>. Use either ar, vr or quicklook attribute."):console.debug("No button type specified for <needle-button>. Use either ar, vr or quicklook attribute.");return}he(this,Xo)??Ji(this,Xo,this.attachShadow({mode:"open"})),he(this,Qo)??Ji(this,Qo,document.createElement("slot")),he(this,Yo)??Ji(this,Yo,document.createElement("style")),he(this,Yo).innerHTML=`
1525
1525
  button {
1526
1526
  all: initial;