@needle-tools/engine 4.11.5-next.b4a2f9e → 4.11.5-next.d95d573

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.
@@ -141,7 +141,7 @@ void main(){
141
141
  #__vconsole .vc-mask {
142
142
  overflow: hidden;
143
143
  }
144
- `,Co?.prepend(i),s===!0&&Ab()<=0&&Yb(),console.log("🌵 Debug console has loaded")}},e.onerror=()=>{console.warn("🌵 Debug console failed to load."+(window.crossOriginIsolated?"This page is using cross-origin isolation, so external scripts can't be loaded.":"")),sl=!1,Ri=null},e.src="https://cdn.jsdelivr.net/npm/vconsole@3.15.1/dist/vconsole.min.js",document.body.appendChild(e)}function PS(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("needle-console","🌵 Inspect glTF"),e=()=>document.querySelector("#__vc_plug_"+s._id+" iframe");return s.on("renderTab",function(t){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 a=location.protocol+"//"+location.host+location.pathname+"/"+n,l=encodeURIComponent(a);s.fullUrl="https://viewer.needle.tools?inspect&file="+l;var h='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';t(h)}),s.on("show",function(){const t=e();t&&t.src!==s.fullUrl&&(t.src=s.fullUrl)}),s.on("hide",function(){const t=e();t&&(t.src="")}),s.on("addTopBar",function(t){var i=new Array;i.push({name:"Open in new window ↗",onClick:function(n){window.open(s.fullUrl,"_blank"),Ri?.hide()}}),i.push({name:"Reload",onClick:function(n){const o=e();o&&(o.src=s.fullUrl)}}),i.push({name:"Fullscreen",onClick:function(n){const o=e();o.requestFullscreen?o.requestFullscreen():o.webkitRequestFullscreen instanceof Function&&o.webkitRequestFullscreen()}}),t(i)}),s}function OS(){const s=document.querySelector("#__vconsole .vc-switch");return s||null}function MS(){const s=document.querySelector("#__vconsole");return s||null}const Kb=x("debugdefines");ro('if(!globalThis["NEEDLE_ENGINE_VERSION"]) globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";');ro('if(!globalThis["NEEDLE_ENGINE_GENERATOR"]) globalThis["NEEDLE_ENGINE_GENERATOR"] = "unknown";');ro('if(!globalThis["NEEDLE_PROJECT_BUILD_TIME"]) globalThis["NEEDLE_PROJECT_BUILD_TIME"] = "unknown";');ro('if(!globalThis["NEEDLE_PUBLIC_KEY"]) globalThis["NEEDLE_PUBLIC_KEY"] = "unknown";');ro('globalThis["__NEEDLE_ENGINE_VERSION__"] = "4.11.5-beta";');ro('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";');ro('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Thu Oct 30 2025 17:20:04 GMT+0000 (Coordinated Universal Time)";');ro('globalThis["__NEEDLE_PUBLIC_KEY__"] = "'+NEEDLE_PUBLIC_KEY+'";');const tn="4.11.5-beta",Kd="undefined",Sm="Thu Oct 30 2025 17:20:04 GMT+0000 (Coordinated Universal Time)";Kb&&console.log(`Engine version: ${tn} (generator: ${Kd})
144
+ `,Co?.prepend(i),s===!0&&Ab()<=0&&Yb(),console.log("🌵 Debug console has loaded")}},e.onerror=()=>{console.warn("🌵 Debug console failed to load."+(window.crossOriginIsolated?"This page is using cross-origin isolation, so external scripts can't be loaded.":"")),sl=!1,Ri=null},e.src="https://cdn.jsdelivr.net/npm/vconsole@3.15.1/dist/vconsole.min.js",document.body.appendChild(e)}function PS(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("needle-console","🌵 Inspect glTF"),e=()=>document.querySelector("#__vc_plug_"+s._id+" iframe");return s.on("renderTab",function(t){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 a=location.protocol+"//"+location.host+location.pathname+"/"+n,l=encodeURIComponent(a);s.fullUrl="https://viewer.needle.tools?inspect&file="+l;var h='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';t(h)}),s.on("show",function(){const t=e();t&&t.src!==s.fullUrl&&(t.src=s.fullUrl)}),s.on("hide",function(){const t=e();t&&(t.src="")}),s.on("addTopBar",function(t){var i=new Array;i.push({name:"Open in new window ↗",onClick:function(n){window.open(s.fullUrl,"_blank"),Ri?.hide()}}),i.push({name:"Reload",onClick:function(n){const o=e();o&&(o.src=s.fullUrl)}}),i.push({name:"Fullscreen",onClick:function(n){const o=e();o.requestFullscreen?o.requestFullscreen():o.webkitRequestFullscreen instanceof Function&&o.webkitRequestFullscreen()}}),t(i)}),s}function OS(){const s=document.querySelector("#__vconsole .vc-switch");return s||null}function MS(){const s=document.querySelector("#__vconsole");return s||null}const Kb=x("debugdefines");ro('if(!globalThis["NEEDLE_ENGINE_VERSION"]) globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";');ro('if(!globalThis["NEEDLE_ENGINE_GENERATOR"]) globalThis["NEEDLE_ENGINE_GENERATOR"] = "unknown";');ro('if(!globalThis["NEEDLE_PROJECT_BUILD_TIME"]) globalThis["NEEDLE_PROJECT_BUILD_TIME"] = "unknown";');ro('if(!globalThis["NEEDLE_PUBLIC_KEY"]) globalThis["NEEDLE_PUBLIC_KEY"] = "unknown";');ro('globalThis["__NEEDLE_ENGINE_VERSION__"] = "4.11.5";');ro('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";');ro('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Fri Oct 31 2025 12:26:25 GMT+0000 (Coordinated Universal Time)";');ro('globalThis["__NEEDLE_PUBLIC_KEY__"] = "'+NEEDLE_PUBLIC_KEY+'";');const tn="4.11.5",Kd="undefined",Sm="Fri Oct 31 2025 12:26:25 GMT+0000 (Coordinated Universal Time)";Kb&&console.log(`Engine version: ${tn} (generator: ${Kd})
145
145
  Project built at ${Sm}`);const ea=NEEDLE_PUBLIC_KEY,ls="needle_isActiveInHierarchy",Do="builtin_components",Ul="needle_editor_guid";function ro(s){try{(0,eval)(s)}catch(e){Kb&&console.error(e)}}let Zb,Iy=null;function rn(){return Zb}function Cm(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}Iy!==s&&(Iy=s,Zb=new s)}const ai=Symbol("shadowDomOwner"),kS=x("debugpatch");function Zd(s,e,t,i){const n=kS===e;if(!t&&!i)return;const o=e+"___needle";RS(s,e,t,i);const r=Object.getOwnPropertyDescriptor(s,e),a=s[e];n&&console.log("Patch",s.constructor.name,e,r,a),r?(n&&console.log("Apply patch with existing descriptor",s.constructor.name,e,r),typeof r.value=="function"&&(s[e]=By(r.value,s,e))):(n&&console.log("Create patch with new property",s.constructor.name,e,r),Object.defineProperty(s,e,{set:function(l){if(typeof l=="function")this[o]=By(l,s,e);else{const h=this[o];Jb(s,e,this,h,l),this[o]=l,e0(s,e,this,h,l)}},get:function(){const l=this[o];return typeof l=="function"&&l[o]?l[o]:l}}))}function ES(s,e,t){const i=Pm(s,e);if(i)for(let n=i.length-1;n>=0;n--){const o=i[n];o.prefix===t&&(o.prefix=null),o.postfix===t&&(o.postfix=null),!o.prefix&&!o.postfix&&i.splice(n,1)}}const jy=Symbol("Needle:Patches:WrappedFunction");function By(s,e,t){if(s[jy])return s;const i=function(...n){Jb(e,t,this,...n);const o=s.apply(this,n);return e0(e,t,this,o,...n),o};return i[jy]=!0,i}const Jh="Needle:Patches";function wp(){return globalThis[Jh]||(globalThis[Jh]=new WeakMap),globalThis[Jh]}function Pm(s,e){const t=wp().get(s);return t?t.get(e):null}function RS(s,e,t,i){let n=wp().get(s);n||(n=new Map,wp().set(s,n));let o=n.get(e);o||(o=[],n.set(e,o)),o.push({prefix:t,postfix:i})}function Jb(s,e,t,...i){if(!t)return;const n=Pm(s,e);if(n)for(const o of n)o.prefix?.call(t,...i)}function e0(s,e,t,i,...n){if(!t)return;const o=Pm(s,e);if(o)for(const r of o)r.postfix?.call(t,i,...n)}const ya=[];function Jd(s){ya.indexOf(s)===-1&&ya.push(s)}function TS(s){const e=ya.indexOf(s);e!==-1&&ya.splice(e,1)}const _a=[];function Om(s){_a.indexOf(s)===-1&&_a.push(s)}function AS(s){const e=_a.indexOf(s);e!==-1&&_a.splice(e,1)}function t0(s){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-start",{detail:s}));for(let e=0;e<ya.length;e++)ya[e](s)}function i0(s){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-end",{detail:s}));for(let e=0;e<_a.length;e++)_a[e](s)}const Xe=x("debuginput");var eu=(s=>(s.Mouse="mouse",s.Touch="touch",s.Controller="controller",s.Hand="hand",s))(eu||{}),xe=(s=>(s.PointerDown="pointerdown",s.PointerUp="pointerup",s.PointerMove="pointermove",s.KeyDown="keydown",s.KeyUp="keyup",s.KeyPressed="keypress",s))(xe||{});class Zn extends PointerEvent{clientZ;deviceIndex;origin;source;mode;get isSpatial(){return this.mode!="screen"}get ray(){return this._ray||(this._ray=new c.Ray(this.space.worldPosition.clone(),this.space.worldForward.clone())),this._ray}set ray(e){this._ray=e}get hasRay(){return this._ray!==void 0}_ray;space;isClick=!1;isDoubleClick=!1;get used(){return this._used}_used=!1;use(){this._used=!0}get pointerId(){return this._pointerid}_pointerid;get pointerType(){return this._pointerType}_pointerType;get type(){return this._type}_type;metadata={};intersections=new Array;constructor(e,t,i){super(e,i),this.clientZ=i.clientZ,this._pointerid=i.pointerId,this._pointerType=i.pointerType,this._type=e,this.deviceIndex=i.deviceIndex,this.origin=i.origin,this.source=t,this.mode=i.mode,this._ray=i.ray,this.space=i.device}_immediatePropagationStopped=!1;get immediatePropagationStopped(){return this._immediatePropagationStopped}_propagationStopped=!1;get propagationStopped(){return this._immediatePropagationStopped||this._propagationStopped}stopImmediatePropagation(){this._immediatePropagationStopped=!0,super.stopImmediatePropagation(),this.source?.stopImmediatePropagation()}stopPropagation(){this._propagationStopped=!0,super.stopPropagation(),this.source?.stopPropagation(),Xe&&console.warn("Stop propagation...",this.pointerId,this.pointerType)}}class wl extends KeyboardEvent{source;constructor(e,t,i){super(e,i),this.source=t}stopImmediatePropagation(){super.stopImmediatePropagation(),this.source?.stopImmediatePropagation()}}class DS{key;keyType;source;constructor(e){this.key=e.key,this.keyType=e.type,this.source=e}}var Xt=(s=>(s[s.Early=-100]="Early",s[s.Default=0]="Default",s[s.Late=100]="Late",s))(Xt||{});class n0{_eventListeners={};addEventListener(e,t,i){if(this._eventListeners[e]||(this._eventListeners[e]=[]),!t||typeof t!="function"){console.error("Invalid call to addEventListener: callback is required and must be a function!");return}i?i={...i}:i={};let n=0;i?.queue!=null&&(n=i.queue);const o=this._eventListeners[e],r=o.find(a=>a.priority===n);r?r.listeners.push({callback:t,options:i}):(o.push({priority:n,listeners:[{callback:t,options:i}]}),o.sort((a,l)=>a.priority-l.priority))}removeEventListener(e,t,i){if(!this._eventListeners[e]||!t)return;const n=this._eventListeners[e];if(i?.queue!=null){const o=n.find(a=>a.priority===i.queue);if(!o)return;const r=o.listeners.findIndex(a=>a.callback===t);r>=0&&o.listeners.splice(r,1)}else for(const o of n){const r=o.listeners.findIndex(a=>a.callback===t);r>=0&&o.listeners.splice(r,1)}}dispatchEvent(e){let t=!1;if(e instanceof wl){const i=this._eventListeners[e.type];if(i)for(const n of i)for(let o=0;o<n.listeners.length;o++){const r=n.listeners[o];if(r.options?.signal?.aborted){n.listeners.splice(o,1),o--;continue}r.options.once&&(n.listeners.splice(o,1),o--),r.callback(e)}}if(e instanceof Zn){const i=this._eventListeners[e.type];if(i)for(const n of i){if(t)break;for(let o=0;o<n.listeners.length;o++){const r=n.listeners[o];if(r.options?.signal?.aborted){n.listeners.splice(o,1),o--;continue}if(e.immediatePropagationStopped){t=!0,Xe&&console.log("immediatePropagationStopped",e.type);break}else e.propagationStopped&&(t=!0,Xe&&console.log("propagationStopped",e.type));r.options.once&&(n.listeners.splice(o,1),o--),r.callback(e)}}}}_doubleClickTimeThreshold=.2;_longPressTimeThreshold=1;get mousePosition(){return this._pointerPositions[0]}get mousePositionRC(){return this._pointerPositionsRC[0]}get mouseDown(){return this._pointerDown[0]}get mouseUp(){return this._pointerUp[0]}get mouseClick(){return this._pointerClick[0]}get mouseDoubleClick(){return this._pointerDoubleClick[0]}get mousePressed(){return this._pointerPressed[0]}get mouseWheelChanged(){return this.getMouseWheelChanged(0)}get click(){return this._pointerClick[0]}get doubleClick(){return this._pointerDoubleClick[0]}getGamepad(e=0){return typeof navigator<"u"&&"getGamepads"in navigator&&navigator.getGamepads()[e]||null}_setCursorTypes=[];setCursorPointer(){this.setCursor("pointer")}setCursorNormal(){this.unsetCursor("pointer")}setCursor(e){this._setCursorTypes.push(e),this._setCursorTypes.length>10&&this._setCursorTypes.shift(),this.updateCursor()}unsetCursor(e){for(let t=this._setCursorTypes.length-1;t>=0;t--)if(this._setCursorTypes[t]===e){this._setCursorTypes.splice(t,1),this.updateCursor();break}}updateCursor(){this._setCursorTypes?.length==0?this.context.domElement.style.cursor="default":this.context.domElement.style.cursor=this._setCursorTypes[this._setCursorTypes.length-1]}getIsPointerIdInUse(e){for(const t of this._pointerEventsPressed)if(t.pointerId===e&&t.used)return!0;return!1}getPointerPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&e++;return e}getPointerPosition(e){return e>=this._pointerPositions.length?null:this._pointerPositions[e]}getPointerPositionLastFrame(e){return e>=this._pointerPositionsLastFrame.length?null:this._pointerPositionsLastFrame[e]}getPointerPositionDelta(e){return e>=this._pointerPositionsDelta.length?null:this._pointerPositionsDelta[e]}getPointerPositionRC(e){return e>=this._pointerPositionsRC.length?null:this._pointerPositionsRC[e]}getPointerDown(e){return e>=this._pointerDown.length?!1:this._pointerDown[e]}getPointerUp(e){return e>=this._pointerUp.length?!1:this._pointerUp[e]}getPointerPressed(e){return e>=this._pointerPressed.length?!1:this._pointerPressed[e]}getPointerClicked(e){return e>=this._pointerClick.length?!1:this._pointerClick[e]}getPointerDoubleClicked(e){return e>=this._pointerDoubleClick.length?!1:this._pointerDoubleClick[e]}getPointerDownTime(e){return e>=this._pointerDownTime.length?-1:this._pointerDownTime[e]}getPointerUpTime(e){return e>=this._pointerUpTime.length?-1:this._pointerUpTime[e]}getPointerLongPress(e){return e>=this._pointerDownTime.length?!1:this.getPointerPressed(e)&&this.context.time.time-this._pointerDownTime[e]>this._longPressTimeThreshold}getIsMouse(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="mouse"}getIsTouch(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="touch"}getTouchesPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&this.getIsTouch(t)&&e++;return e}getMouseWheelChanged(e=0){return e>=this._mouseWheelChanged.length?!1:this._mouseWheelChanged[e]}getMouseWheelDeltaY(e=0){return e>=this._mouseWheelDeltaY.length?0:this._mouseWheelDeltaY[e]}getPointerEvent(e){if(!(e>=this._pointerEvent.length))return this._pointerEvent[e]??void 0}*foreachPointerId(e){for(let t=0;t<this._pointerTypes.length;t++)if(this._pointerIsActive(t)){if(e!==void 0){const i=this._pointerTypes[t];if(Array.isArray(e)){let n=!1;for(const o of e)if(i===o){n=!0;break}if(!n)continue}else if(e!==i)continue}yield t}}*foreachTouchId(){for(let e=0;e<this._pointerTypes.length;e++)this._pointerTypes[e]==="touch"&&this._pointerIsActive[e]&&(yield e)}_pointerIsActive(e){return e<0?!1:this._pointerPressed[e]||this._pointerDown[e]||this._pointerUp[e]}context;_pointerDown=[!1];_pointerUp=[!1];_pointerClick=[!1];_pointerDoubleClick=[!1];_pointerPressed=[!1];_pointerPositions=[new c.Vector2];_pointerPositionsLastFrame=[new c.Vector2];_pointerPositionsDelta=[new c.Vector2];_pointerPositionsRC=[new c.Vector2];_pointerPositionDown=[new c.Vector3];_pointerDownTime=[];_pointerUpTime=[];_pointerUpTimestamp=[];_pointerIds=[];_pointerTypes=[""];_mouseWheelChanged=[!1];_mouseWheelDeltaY=[0];_pointerEvent=[];_pointerEventsPressed=[];_pointerSpace=[];_pressedStack=new Map;onDownButton(e,t){let i=this._pressedStack.get(e);i||(i=[],this._pressedStack.set(e,i)),i.push(t)}onReleaseButton(e,t){const i=this._pressedStack.get(e);if(!i)return;const n=i.indexOf(t);n>=0&&i.splice(n,1)}getFirstPressedButtonForPointer(e){const t=this._pressedStack.get(e);if(t)return t[0]}getLatestPressedButtonForPointer(e){const t=this._pressedStack.get(e);if(t)return t[t.length-1]}getKeyDown(e){if(e!==void 0)return this.isKeyDown(e);for(const t in this.keysPressed){const i=this.keysPressed[t];if(i.startFrame===this.context.time.frameCount)return i.key}return null}getKeyPressed(e){if(e!==void 0)return this.isKeyPressed(e);for(const t in this.keysPressed){const i=this.keysPressed[t];if(i.pressed)return i.key}return null}getKeyUp(e){if(e!==void 0)return this.isKeyUp(e);for(const t in this.keysPressed){const i=this.keysPressed[t];return i.pressed===!1&&i.frame===this.context.time.frameCount}return null}isKeyDown(e){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const t=this.getCodeForCommonKeyName(e);if(t!==null){for(const n of t)if(this.isKeyDown(n))return!0;return!1}const i=this.keysPressed[e];return i?i.startFrame===this.context.time.frameCount&&i.pressed:!1}isKeyUp(e){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const t=this.getCodeForCommonKeyName(e);if(t!==null){for(const n of t)if(this.isKeyUp(n))return!0;return!1}const i=this.keysPressed[e];return i?i.frame===this.context.time.frameCount&&i.pressed===!1:!1}isKeyPressed(e){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const t=this.getCodeForCommonKeyName(e);if(t!==null){for(const n of t)if(this.isKeyPressed(n))return!0;return!1}const i=this.keysPressed[e];return i&&i.pressed||!1}getCodeForCommonKeyName(e){if(e.length===1){if(e>="0"&&e<="9")return["Digit"+e];if(e>="a"&&e<="z")return["Key"+e.toUpperCase()];if(e==" ")return["Space"]}switch(e){case"shift":case"Shift":return["ShiftLeft","ShiftRight"];case"control":case"Control":return["ControlLeft","ControlRight"];case"alt":case"Alt":return["AltLeft","AltRight"]}return null}createInputEvent(e){switch(e.type){case"pointerdown":Xe&&Ce("Create Pointer down"),this.onDownButton(e.deviceIndex,e.button),this.onDown(e);break;case"pointermove":Xe&&Ce("Create Pointer move"),this.onMove(e);break;case"pointerup":Xe&&Ce("Create Pointer up"),this.onUp(e),this.onReleaseButton(e.deviceIndex,e.button);break}}convertScreenspaceToRaycastSpace(e){return e.x=(e.x-this.context.domX)/this.context.domWidth*2-1,e.y=-((e.y-this.context.domY)/this.context.domHeight)*2+1,e}constructor(e){this.context=e,this.context.post_render_callbacks.push(this.onEndOfFrame)}_htmlEventSource;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(){for(const e in this._eventListeners)this._eventListeners[e].length=0;window.removeEventListener("contextmenu",this.onContextMenu),this._htmlEventSource?.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),this._htmlEventSource?.removeEventListener("wheel",this.onMouseWheel,!1),window.removeEventListener("wheel",this.onWheelWindow,!1),window.removeEventListener("keydown",this.onKeyDown,!1),window.removeEventListener("keypress",this.onKeyPressed,!1),window.removeEventListener("keyup",this.onKeyUp,!1),window.removeEventListener("blur",this.onLostFocus)}dispose(){const e=this.context.post_render_callbacks.indexOf(this.onEndOfFrame);e>=0&&this.context.post_render_callbacks.splice(e,1),this.unbindEvents()}onLostFocus=()=>{for(const e in this.keysPressed)this.keysPressed[e].pressed=!1};_receivedPointerMoveEventsThisFrame=new Array;onEndOfFrame=()=>{this._receivedPointerMoveEventsThisFrame.length=0;for(let e=0;e<this._pointerUp.length;e++)this._pointerUp[e]=!1;for(let e=0;e<this._pointerDown.length;e++)this._pointerDown[e]=!1;for(let e=0;e<this._pointerClick.length;e++)this._pointerClick[e]=!1;for(let e=0;e<this._pointerDoubleClick.length;e++)this._pointerDoubleClick[e]=!1;for(const e of this._pointerPositionsDelta)e.set(0,0);for(let e=0;e<this._mouseWheelChanged.length;e++)this._mouseWheelChanged[e]=!1;for(let e=0;e<this._mouseWheelDeltaY.length;e++)this._mouseWheelDeltaY[e]=0};canReceiveInput(e){return e.target===this.context.renderer?.domElement||e.target===this.context.domElement||this.context.isInAR||this.context.isInAR&&e.target===document.body&&exports.DeviceUtilities.isMozillaXR()?!0:(Xe&&console.warn("CanReceiveInput:False for",e.target),!1)}onContextMenu=e=>{this.canReceiveInput(e)!==!1&&e instanceof PointerEvent&&e.pointerType};keysPressed={};onKeyDown=e=>{if(Xe&&console.log(`key down ${e.code}, ${this.context.application.hasFocus}`,e),!this.context.application.hasFocus)return;const t=this.keysPressed[e.code];if(t&&t.pressed)return;this.keysPressed[e.code]={pressed:!0,frame:this.context.time.frameCount+1,startFrame:this.context.time.frameCount+1,key:e.key,code:e.code};const i=new wl("keydown",e,e);this.onDispatchEvent(i)};onKeyPressed=e=>{if(!this.context.application.hasFocus)return;const t=this.keysPressed[e.code];if(!t)return;t.pressed=!0,t.frame=this.context.time.frameCount+1;const i=new wl("keypress",e,e);this.onDispatchEvent(i)};onKeyUp=e=>{if(!this.context.application.hasFocus)return;const t=this.keysPressed[e.code];if(!t)return;t.pressed=!1,t.frame=this.context.time.frameCount+1;const i=new wl("keyup",e,e);this.onDispatchEvent(i)};onWheelWindow=e=>{document.pointerLockElement&&this.onMouseWheel(e)};onMouseWheel=e=>{if(this.canReceiveInput(e)===!1)return;this._mouseWheelDeltaY.length<=0&&this._mouseWheelDeltaY.push(0),this._mouseWheelChanged.length<=0&&this._mouseWheelChanged.push(!1),this._mouseWheelChanged[0]=!0;const t=this._mouseWheelDeltaY[0];this._mouseWheelDeltaY[0]=t+e.deltaY};onPointerDown=e=>{if(this.context.isInAR||this.canReceiveInput(e)===!1)return;e.target instanceof HTMLElement&&e.target.setPointerCapture(e.pointerId);const t=this.getPointerId(e);Xe&&Ce(`pointer down #${t}, identifier:${e.pointerId}`);const i=this.getAndUpdateSpatialObjectForScreenPosition(t,e.clientX,e.clientY),n=new Zn("pointerdown",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:t,button:e.button,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,buttonName:this.getButtonName(e),device:i,pressure:e.pressure});this.onDown(n)};onPointerMove=e=>{if(this.context.isInAR||this._receivedPointerMoveEventsThisFrame.includes(e.pointerId))return;this._receivedPointerMoveEventsThisFrame.push(e.pointerId);let t=e.button;e.pointerType==="mouse"&&(t=this.getFirstPressedButtonForPointer(0)??0);const i=this.getPointerId(e,t);t===-1&&(t=i);const n=this.getAndUpdateSpatialObjectForScreenPosition(i,e.clientX,e.clientY),o=new Zn("pointermove",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:i,button:t,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,buttonName:this.getButtonName(e),device:n,pressure:e.pressure});this.onMove(o)};onPointerCancel=e=>{this.context.isInAR||(Xe&&console.log("Pointer cancel",e),this.onPointerUp(e))};onPointerUp=e=>{if(this.context.isInAR)return;e.target instanceof HTMLElement&&e.target.releasePointerCapture(e.pointerId);const t=this.getPointerId(e),i=new Zn("pointerup",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:t,button:e.button,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,buttonName:this.getButtonName(e),device:this.getAndUpdateSpatialObjectForScreenPosition(t,e.clientX,e.clientY),pressure:e.pressure});this.onUp(i),this._pointerIds[t]=-1,Xe&&console.log("ID="+t,"PointerId="+e.pointerId,"ALL:",[...this._pointerIds])};getPointerId(e,t){return e.pointerType==="mouse"?0+(t??e.button):this.getPointerIndex(e.pointerId)}getButtonName(e){const t=e.button;if(e.pointerType==="mouse")switch(t){case 0:return"left";case 1:return"middle";case 2:return"right"}return"unknown"}onTouchStart=e=>{if(this.context.isInAR)for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t],n=this.getPointerIndex(i.identifier),o=this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),r=new Zn("pointerdown",e,{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(r)}};onTouchMove=e=>{if(this.context.isInAR)for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t],n=this.getPointerIndex(i.identifier),o=this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),r=new Zn("pointermove",e,{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(r)}};onTouchEnd=e=>{if(this.context.isInAR)for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t],n=this.getPointerIndex(i.identifier),o=new Zn("pointerup",e,{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}};tempNearPlaneVector=new c.Vector3;tempFarPlaneVector=new c.Vector3;tempLookMatrix=new c.Matrix4;getAndUpdateSpatialObjectForScreenPosition(e,t,i){let n=this._pointerSpace[e];n||(n=new c.Object3D,this._pointerSpace[e]=n),this._pointerSpace[e]=n;const o=this.context.mainCamera;if(o){const r=this.tempNearPlaneVector.set(t,i,-1);this.convertScreenspaceToRaycastSpace(r);const a=this.tempFarPlaneVector.set(r.x,r.y,1);r.unproject(o),a.unproject(o);const l=o.worldUp||j(0,1,0).applyQuaternion(ue(o));this.tempLookMatrix.lookAt(a,r,l),n.position.set(r.x,r.y,r.z),n.quaternion.setFromRotationMatrix(this.tempLookMatrix)}return n}isInRect(e){if(this.context.isInXR)return!0;const t=this.context.domElement.getBoundingClientRect(),i=e.clientX,n=e.clientY,o=i>=t.x&&i<=t.right&&n>=t.y&&n<=t.bottom;return Xe&&!o&&console.log("Not in rect",t,i,n),o}onDown(e){const t=e.pointerId;if(this.getPointerPressed(t)&&console.warn(`Received pointerDown for pointerId that is already pressed: ${t}`,Xe?e:""),Xe&&console.log(e.pointerType,"DOWN",t),!!this.isInRect(e)){for(this.setPointerState(t,this._pointerPressed,!0),this.setPointerState(t,this._pointerDown,!0),this.setPointerStateT(t,this._pointerEvent,e.source);t>=this._pointerTypes.length;)this._pointerTypes.push(e.pointerType);for(this._pointerTypes[t]=e.pointerType;t>=this._pointerPositionDown.length;)this._pointerPositionDown.push(new c.Vector3);for(this._pointerPositionDown[t].set(e.clientX,e.clientY,e.clientZ??0);t>=this._pointerPositions.length;)this._pointerPositions.push(new c.Vector2);this._pointerPositions[t].set(e.clientX,e.clientY),t>=this._pointerDownTime.length&&this._pointerDownTime.push(0),this._pointerDownTime[t]=this.context.time.realtimeSinceStartup,this.updatePointerPosition(e),this._pointerEventsPressed.push(e),this.onDispatchEvent(e)}}onMove(e){const t=e.pointerId,i=this.getPointerPressed(t);i===!1&&!this.isInRect(e)||e.pointerType==="touch"&&!i||(this.updatePointerPosition(e),this.setPointerStateT(t,this._pointerEvent,e.source),this.onDispatchEvent(e))}onUp(e){const t=e.pointerId;if(!this.getPointerPressed(t)){Xe&&console.log(e.pointerType,"UP",t,"was not down");return}Xe&&console.log(e.pointerType,"UP",t),this.setPointerState(t,this._pointerPressed,!1),this.setPointerStateT(t,this._pointerEvent,e.source),this.setPointerState(t,this._pointerUp,!0),this.updatePointerPosition(e);for(let l=this._pointerEventsPressed.length-1;l>=0;l--)if(this._pointerEventsPressed[l].pointerId===t){this._pointerEventsPressed.splice(l,1);break}if(!this._pointerPositionDown[t]){Xe&&de("Received pointer up event without matching down event for button: "+t),console.warn("Received pointer up event without matching down event for button: "+t);return}const n=this._pointerUpTime[t],o=this._pointerDownTime[t],r=this.context.time.realtimeSinceStartup,a=r-o;if(t>=this._pointerUpTime.length&&this._pointerUpTime.push(-99),this._pointerUpTime[t]=r,a<1){let l=e.clientX-this._pointerPositionDown[t].x,h=e.clientY-this._pointerPositionDown[t].y,d=0;if(e.isSpatial&&e.clientZ!=null&&(d=e.clientZ-this._pointerPositionDown[t].z,l*=200,h*=200,d*=200),Math.abs(l)<5&&Math.abs(h)<5&&Math.abs(d)<5){this.setPointerState(t,this._pointerClick,!0),e.isClick=!0;const u=r-n;Xe&&console.log("CLICK",t,l,h,d,u),u<this._doubleClickTimeThreshold&&u>0&&(this.setPointerState(t,this._pointerDoubleClick,!0),e.isDoubleClick=!0)}}this.onDispatchEvent(e)}updatePointerPosition(e){const t=e.pointerId;for(;t>=this._pointerPositions.length;)this._pointerPositions.push(new c.Vector2);for(;t>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new c.Vector2);for(;t>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new c.Vector2);const i=this._pointerPositionsLastFrame[t];i.copy(this._pointerPositions[t]);const n=this._pointerPositionsDelta[t];let o=e.clientX-i.x,r=e.clientY-i.y;if(e.source instanceof MouseEvent||e.source instanceof TouchEvent){const d=e.source;o===0&&d.movementX!==0&&(o=d.movementX||0),r===0&&d.movementY!==0&&(r=d.movementY||0)}n.x+=o,n.y+=r,this._pointerPositions[t].x=e.clientX,this._pointerPositions[t].y=e.clientY;const a=e.clientX,l=e.clientY;for(;t>=this._pointerPositionsRC.length;)this._pointerPositionsRC.push(new c.Vector2);const h=this._pointerPositionsRC[t];h.set(a,l),this.convertScreenspaceToRaycastSpace(h)}getPointerIndex(e){let t=-1;for(let i=0;i<this._pointerIds.length;i++){if(this._pointerIds[i]===e)return i;t===-1&&this._pointerIds[i]===-1&&(t=i)}return t!==-1?(this._pointerIds[t]=e,t):(Xe&&console.log("PUSH pointerId:",e),this._pointerIds.push(e),this._pointerIds.length-1)}setPointerState(e,t,i){t[e]=i}setPointerStateT(e,t,i){return t[e]=i,i}onDispatchEvent(e){const t=N.Current;try{N.Current=this.context,this.dispatchEvent(e)}finally{N.Current=t}}}const aa=new c.Matrix4().makeRotationY(Math.PI),ki=new c.Quaternion().setFromAxisAngle(new c.Vector3(0,1,0),Math.PI),LS=x("debugwebxr");class IS{priority=-1e5;gameObject;isXRRig(){return!0}get isActive(){return this.gameObject.visible}constructor(){if(this.gameObject=new c.Object3D,this.gameObject.name="Implicit XR Rig",LS){const e=Dm(16733661);e.position.y+=.5,this.gameObject.add(e)}}}const Hn=x("debugwebxr"),vh=x("debugcustomgesture"),jS="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",BS="generic-trigger",FS=new c.Quaternion().setFromEuler(new c.Euler(c.MathUtils.degToRad(0),c.MathUtils.degToRad(-90),c.MathUtils.degToRad(-90))),US=new c.Vector3(.04,-.04,0);class Mm{xr;get context(){return this.xr.context}inputSource;index=0;emitEvents=!0;get connected(){return this._connected}_connected=!0;get isTracking(){return this._isTracking}_isTracking=!1;get gamepad(){return this.__gamepad??=this.inputSource.gamepad}__gamepad;get isHand(){return this.hand!=null}get hand(){return this.__hand??=this.inputSource.hand}__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.inputSource.handedness}__side=void 0;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)}_hitTestSource=void 0;_hasSelectEvent=!1;get hasSelectEvent(){return this._hasSelectEvent}_isMxInk=!1;_isMetaQuestTouchController=!1;getHitTest(){return this.xr.getHitTest(this)}_handJointPoses=new Map;getHandJointPose(e,t){if(t=t||this.xr.frame,!this.hand||!t?.getJointPose||!this.xr.referenceSpace)return null;let i=this._handJointPoses?.get(e);return i||(i=t.getJointPose(e,this.xr.referenceSpace),i&&this._handJointPoses.set(e,i),i)}_gripMatrix=new c.Matrix4;_gripPosition=new c.Vector3;_gripQuaternion=new c.Quaternion;_linearVelocity=new c.Vector3;_rayPositionRaw=new c.Vector3;_rayRotationRaw=new c.Quaternion;_rayMatrix=new c.Matrix4;_rayPosition=new c.Vector3;_rayQuaternion=new c.Quaternion;get gripPosition(){return j(this._gripPosition)}get gripQuaternion(){return qt(this._gripQuaternion)}get gripMatrix(){return this._gripMatrix}get gripLinearVelocity(){return j(this._linearVelocity).applyQuaternion(ki)}get rayPosition(){return j(this._rayPosition)}get rayQuaternion(){return qt(this._rayQuaternion)}get gripWorldPosition(){return j(this._gripWorldPosition)}_gripWorldPosition=new c.Vector3;get gripWorldQuaternion(){return qt(this._gripWorldQuaternion)}_gripWorldQuaternion=new c.Quaternion;get rayWorldPosition(){return j(this._rayWorldPosition)}_rayWorldPosition=new c.Vector3;updateRayWorldPosition(){const e=this.xr.context.mainCamera?.parent;this._rayWorldPosition.copy(this._rayPositionRaw),e&&this._rayWorldPosition.applyMatrix4(e.matrixWorld)}get rayWorldQuaternion(){return qt(this._rayWorldQuaternion)}_rayWorldQuaternion=new c.Quaternion;get pinchPosition(){return j(this._pinchPosition)}_pinchPosition=new c.Vector3;updateRayWorldQuaternion(){const e=this.xr.context.mainCamera?.parent,t=e?ue(e):void 0;this._rayWorldQuaternion.copy(this._rayRotationRaw).multiply(ki),t&&this._rayWorldQuaternion.premultiply(t)}get ray(){return this._ray.origin.copy(this.rayWorldPosition),this._ray.direction.copy(j(0,0,1).applyQuaternion(this.rayWorldQuaternion)),this._ray}_ray;_hand_wristDotUp=void 0;get handWristDotUp(){if(this._hand_wristDotUp!==void 0)return this._hand_wristDotUp;const e=this.handObject?.joints.wrist;if(e){const t=j(0,1,0).applyQuaternion(e.quaternion),i=j(0,1,0).dot(t);return this._hand_wristDotUp=i}}get isHandUpsideDown(){return this.handWristDotUp!==void 0?this.handWristDotUp<-.7:!1}get isTeleportGesture(){return this.isHandUpsideDown&&this.getGesture("pinch")?.isDown}get object(){return this._object}_object;_gripSpaceObject;_raySpaceObject;model=null;_debugAxesHelper=new c.AxesHelper(.15);_debugGripAxesHelper=new c.AxesHelper(.07);_debugRayAxesHelper=new c.AxesHelper(.07);async getModelUrl(){return this.getMotionController?.then(e=>e?.assetUrl||null)}constructor(e,t,i){this.xr=e,this.inputSource=t,this.index=i,this._object=new c.Object3D,this._object.name=`NeedleXRController_${i}`,Hn&&(this._object.add(this._debugAxesHelper),this._gripSpaceObject=new c.Object3D,this._raySpaceObject=new c.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 c.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()}_hitTestSourcePromise=null;_requestHitTestSource(){return this._hitTestSourcePromise?this._hitTestSourcePromise:this.xr.mode==="immersive-ar"&&this.inputSource.targetRayMode==="tracked-pointer"&&this.xr.session.requestHitTestSourceForTransientInput?this._hitTestSourcePromise=this.xr.session.requestHitTestSourceForTransientInput({profile:this.inputSource.profiles[0],offsetRay:new XRRay})?.then(e=>(this._hitTestSourcePromise=null,this.connected?this._hitTestSource=e:(e.cancel(),null)))??null:null}onPointerHits=e=>{};onUpdate(e){this.onUpdateFrame(e),this.updateInputEvents(),this.onUpdateMove()}onRenderDebug(){B.DrawSphere(this.rayWorldPosition,.003),B.DrawDirection(this.rayWorldPosition,j(0,0,10).applyQuaternion(this.rayWorldQuaternion));const t=(this.inputSource.gripSpace?this.gripWorldPosition:this.object.worldPosition).sub(this.object.worldForward.multiplyScalar(.1)),i=this.inputSource.profiles.join(`
146
146
  `);let n=`Controller[${this.index}] (${this.inputSource.targetRayMode}, ${this.side})
147
147
  C:${this.connected?"x":"-"} T:${this.isTracking?"x":"-"} Hand:${this.inputSource.hand?"x":"-"} Pen: ${this._isMxInk?"x":"-"}`;if(this.inputSource.hand&&(n+=`
@@ -163,7 +163,7 @@ or by using the once option like onStart(()=>{}, { once:true }).
163
163
  See https://engine.needle.tools/docs/scripting.html#special-lifecycle-hooks for more information.`))}}function ao(s,e){const t=ia.get(e);if(t){for(let n=0;n<t.length;n++)if(t[n].method===s){t.splice(n,1);return}}const i=la.get(e);if(i){for(let n=0;n<i.length;n++)if(i[n].method===s){i.splice(n,1);return}}}function gn(s,e){e===re.ContextCreated&&Sp.delete(s),s0(s,e)}function s0(s,e){e===pe.Start&&la.get(re.ContextCreated)&&s0(s,re.ContextCreated);const t=e===pe.Start||e===re.ContextCreated,i=ia.get(e);i&&i.length>0&&Vy(s,i,t);const n=la.get(e);if(n&&n.length>0){const o=[...n];n.length=0,Vy(s,o,t),o.length>0&&(ia.has(e)||ia.set(e,new Array),ia.get(e).push(...o))}}const wh=new Array,Ny={context:null};function Vy(s,e,t){wh.length=0;for(let n=0;n<e.length;n++)wh.push(e[n]);let i=Sp.get(s);for(let n=0;n<wh.length;n++){const o=wh[n];let r=!0;if(i&&i.has(o)&&(r=!1),r)try{Ny.context=s,o.method?.call(Ny,s)}catch(a){console.error("Error in lifecycle method",a)}if(o.options?.once){for(let a=0;a<e.length;a++)if(e[a]===o){e.splice(a,1);break}}else t&&(i||(i=new Set,Sp.set(s,i)),i.add(o))}}const Sp=new WeakMap,km={};function Em(s,e){km[s]=e}function o0(s){const e=s.getBufferIdentifier(),t=km[e];return t(s)}function r0(s){return typeof s.guid=="function"?s.guid():null}let Rm;function zS(){return Rm}function NS(s){Rm=s}function a0(s,e){return e||(e={}),e={...Rm,...e},s?new se.$70d766613f57b014$export$2e2bcd8739ae039(s,e):new se.$70d766613f57b014$export$2e2bcd8739ae039(e)}async function $y(){const s=await Promise.resolve().then(()=>require("./vendor-6kAXU6fm.umd.cjs")).then(e=>e.bundler);return console.log(s),s.default===void 0?s:s.default}class l0{get isHost(){return this._host!==void 0}_host;_client;_clientData;constructor(){this.onEnable()}onEnable(){this.trySetupHost("HOST-5980e65c-8438-453e-8b35-f13c736dcd81")}async trySetupHost(e){const t=await $y(),i=new t(e);i.on("error",n=>{console.error(n),this._host=void 0,this.trySetupClient(e)}),i.on("open",n=>{this._host=new $S(i)})}async trySetupClient(e){const t=await $y();this._client=new t,this._client.on("error",i=>{console.error("Client error",i)}),this._client.on("open",i=>{console.log("client connected",i),this._clientData=this._client.connect(e,{metadata:{id:i}}),this._clientData.on("open",()=>{console.log("Connected to host")}),this._clientData.on("data",n=>{console.log("<<",n)})})}}class VS{_peer;constructor(e){this._peer=e}}class $S extends VS{get isHost(){return!0}_connections=[];constructor(e){super(e),console.log("I AM THE HOST"),this._peer?.on("connection",this.onConnection.bind(this)),this._peer.on("close",()=>{this.broadcast("BYE")}),setInterval(()=>{this.broadcast("HELLO")},2e3)}onConnection(e){console.log("host connection",e),e.on("open",()=>{this._connections.push(e),this.broadcastConnection(e)})}broadcastConnection(e){const t=this._connections.map(i=>i.metadata?.id).filter(i=>i!==void 0);this.broadcast({type:"connection-list",connections:t})}broadcast(e){if(e!=null){console.log(">>",e);for(const t in this._peer.connections){const i=this._peer.connections[t];if(i)if(Array.isArray(i))for(const n of i)n&&n.send(e);else console.warn(i)}}}}var Zi=(s=>(s[s.OnConnection=0]="OnConnection",s[s.OnRoomJoin=1]="OnRoomJoin",s[s.Queued=2]="Queued",s[s.Immediate=3]="Immediate",s))(Zi||{});const Wy="https://urls.needle.tools/default-networking-backend/index";let xi="wss://networking.needle.tools/socket";const Nt=!!x("debugnet"),xl=!!(Nt||x("debugowner")),xh=x("debugnetbin");var c0=(s=>(s.ConnectionInfo="connection-start-info",s))(c0||{}),Q=(s=>(s.Join="join-room",s.Leave="leave-room",s.JoinedRoom="joined-room",s.LeftRoom="left-room",s.UserJoinedRoom="user-joined-room",s.UserLeftRoom="user-left-room",s.RoomStateSent="room-state-sent",s))(Q||{});class WS{room;viewId;allowEditing;inRoom}class HS{room}class GS{userId}var h0=(s=>(s.RequestHasOwner="request-has-owner",s.ResponseHasOwner="response-has-owner",s.RequestIsOwner="request-is-owner",s.ResponseIsOwner="response-is-owner",s.RequestOwnership="request-ownership",s.GainedOwnership="gained-ownership",s.RemoveOwnership="remove-ownership",s.LostOwnership="lost-ownership",s.GainedOwnershipBroadcast="gained-ownership-broadcast",s.LostOwnershipBroadcast="lost-ownership-broadcast",s))(h0||{});class Tm{guid;connection;get hasOwnership(){return this._hasOwnership}get isOwned(){return this._isOwned}get isConnected(){return this.connection.isConnected}_hasOwnership=!1;_isOwned=void 0;_gainSubscription;_lostSubscription;_hasOwnerResponse;constructor(e,t){this.connection=e,this.guid=t,this._gainSubscription=this.onGainedOwnership.bind(this),this._lostSubscription=this.onLostOwnership.bind(this),e.beginListen("lost-ownership",this._lostSubscription),e.beginListen("gained-ownership-broadcast",this._gainSubscription),this._hasOwnerResponse=this.onHasOwnerResponse.bind(this),e.beginListen("response-has-owner",this._hasOwnerResponse)}_isWaitingForOwnershipResponseCallback=null;updateIsOwned(){this.connection.send("request-has-owner",{guid:this.guid})}onHasOwnerResponse(e){e.guid===this.guid&&(this._isOwned=e.value)}requestOwnershipIfNotOwned(){return this._isWaitingForOwnershipResponseCallback!==null?this:(this._isWaitingForOwnershipResponseCallback=this.waitForHasOwnershipRequestResponse.bind(this),this.connection.beginListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this.connection.send("request-has-owner",{guid:this.guid}),this)}waitForHasOwnershipRequestResponse(e){e.guid===this.guid&&(this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this._isOwned=e.value,e.value||(xl&&console.log("request ownership",this.guid),this.requestOwnership()))}requestOwnershipAsync(){return new Promise((e,t)=>{this.requestOwnership();let i=0;const n=()=>{if(i++>10)return t("Timeout");setTimeout(()=>{this.hasOwnership?e(this):n()},100)};n()})}requestOwnership(){return xl&&console.log("Request ownership",this.guid),this.connection.send("request-ownership",{guid:this.guid}),this}freeOwnership(){return this.connection.send("remove-ownership",{guid:this.guid}),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this}destroy(){this.connection.stopListen("gained-ownership",this._gainSubscription),this.connection.stopListen("lost-ownership",this._lostSubscription),this.connection.stopListen("response-has-owner",this._hasOwnerResponse),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null)}onGainedOwnership(e){e.guid===this.guid&&(this._isOwned=!0,this.connection.connectionId===e.owner?(xl&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(xl&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}}class d0{context;_peer=null;constructor(e){this.context=e}get peer(){return this._peer||(this._peer=new l0),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return Nt}get isConnected(){return this.connected}get currentRoomName(){return this._currentRoomName}get allowEditing(){return this._currentRoomAllowEditing}get currentRoomViewId(){return this._currentRoomViewId}getViewOnlyUrl(){if(this.currentRoomViewId===null)return null;const e=new URL(window.location.href);return e.searchParams.set("view",this.currentRoomViewId),e.href}get isInRoom(){return this._isInRoom}get currentLatency(){return this._currentDelay}get currentServerUrl(){return this._ws?.url??null}sendPing(){this.send("ping",{time:this.context.time.time})}userIsInRoom(e){return this._currentInRoom.indexOf(e)!==-1}_usersInRoomCopy=[];usersInRoom(e=null){e||(e=this._usersInRoomCopy),e.length=0;for(const t of this._currentInRoom)e.push(t);return e}joinRoom(e,t=!1){return e?e.length>1024?(console.error('Room name too long, can not join: "'+e+'". Max length is 1024 characters.'),!1):(this.isInRoom&&this.currentRoomName!==e&&console.warn("Needle Engine is already connected to a networking room. Connecting to multiple rooms is not supported"),this.connect(),Nt&&console.log("join: "+e),this.send("join-room",{room:e,viewOnly:t},Zi.OnConnection),!0):(console.error('Missing room name, can not join: "'+e+'"'),!1)}leaveRoom(e=null){return e||(e=this.currentRoomName),e?(this.send("leave-room",{room:e}),!0):(console.error('Missing room name, can not join: "'+e+'"'),!1)}send(e,t=null,i=Zi.Queued){if(t===null&&(t={}),i===Zi.Queued){this._defaultMessagesBuffer.push({key:e,value:t});return}return this.sendWithWebsocket(e,t,i)}sendDeleteRemoteState(e){this.send("delete-state",{guid:e,dontSave:!0}),delete this._state[e]}sendDeleteRemoteStateAll(){this.send("delete-all-state"),this._state={}}sendBinary(e){xh&&console.log("<< send binary",this.context.time.frame,e.length/1024+" KB"),this._ws?.send(e)}_defaultMessagesBuffer=[];_defaultMessagesBufferArray=[];sendBufferedMessagesNow(){if(!this._ws)return;this._defaultMessagesBufferArray.length=0;const e=Object.keys(this._defaultMessagesBuffer).length;for(const i in this._defaultMessagesBuffer){const n=this._defaultMessagesBuffer[i];if(e<=1){this.sendWithWebsocket(n.key,n.value,Zi.Immediate);break}const o=this.toMessage(n.key,n.value);this._defaultMessagesBufferArray.push(o)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&Nt&&console.log("SEND BUFFERED",this._defaultMessagesBufferArray.length),this._defaultMessagesBufferArray.length<=0)return;const t=JSON.stringify(this._defaultMessagesBufferArray);this._ws?.send(t)}beginListen(e,t){return this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t),t}stopListening(e,t){return this.stopListen(e,t)}stopListen(e,t){if(!t||!this._listeners[e])return;const i=this._listeners[e].indexOf(t);i>=0&&this._listeners[e].splice(i,1)}beginListenBinary(e,t){return this._listenersBinary[e]||(this._listenersBinary[e]=[]),this._listenersBinary[e].push(t),t}stopListenBinary(e,t){if(!this._listenersBinary[e])return;const i=this._listenersBinary[e].indexOf(t);i>=0&&this._listenersBinary[e].splice(i,1)}netWebSocketUrlProvider;registerProvider(e){this.netWebSocketUrlProvider=e}async connect(e){if(this.connected&&e&&e!==xi)return Promise.reject("Can not connect to different server url. Please disconnect first.");if(this.connected)return Promise.resolve(!0);e&&console.debug("Connecting to user provided url "+e);const t=e||this.netWebSocketUrlProvider?.getWebsocketUrl();return t?xi=t:Pb()&&(xi="wss://"+window.location.host+"/socket"),this.connectWebsocket()}disconnect(){this._ws?.close(),this._ws=void 0,xi=void 0,this._currentRoomAllowEditing=!0,this._currentRoomName=null,this._currentRoomViewId=null,this._isInRoom=!1,this._currentInRoom.length=0,this._state={},this._currentDelay=-1}_listeners={};_listenersBinary={};connected=!1;channelId;_connectionId=null;_ws;_waitingForSocket={};_isInRoom=!1;_currentRoomName=null;_currentRoomViewId=null;_currentRoomAllowEditing=!0;_currentInRoom=[];_state={};_currentDelay=-1;_connectingToWebsocketPromise=null;connectWebsocket(){return this._connectingToWebsocketPromise?this._connectingToWebsocketPromise:this._connectingToWebsocketPromise=new Promise(async(e,t)=>{let i=!1;const n=h=>{i||(i=!0,e(h))};if(xi===void 0&&(console.log("Fetch default backend url: "+Wy),xi=await(await fetch(Wy)).text()),xi===void 0){n(!1);return}console.debug(`⊡ Connecting to networking backend on
164
164
  `+xi);const o=await Promise.resolve().then(()=>require("./vendor-6kAXU6fm.umd.cjs")).then(h=>h.index),r=o.default?.WebsocketBuilder??o.WebsocketBuilder,a=o.default?.ExponentialBackoff??o.ExponentialBackoff,l=new r(xi).withMaxRetries(10).withBackoff(new a(2e3,4)).onOpen(()=>{this._connectingToWebsocketPromise=null,this._ws=l,this.connected=!0,A()||Nt?console.log(`⊞ Connected to networking backend
165
165
  `+xi):console.debug("⊞ Connected to networking backend",xi),n(!0),this.onSendQueued(Zi.OnConnection)}).onClose(h=>{this._connectingToWebsocketPromise=null,this.connected=!1,this._isInRoom=!1,n(!1);let d="Websocket connection closed...";xi?.includes("/socket")||(d+=' Do you perhaps mean to connect to "/socket"?'),console.error(d)}).onError(h=>{console.error("⊠ Websocket connection failed..."),n(!1)}).onRetry(()=>{console.log("→ Retry connecting to networking websocket")}).build();l.addEventListener(o.WebsocketEvent.message,(h,d)=>{this.onMessage(h,d)})})}onMessage(e,t){const i=t.data;try{if(typeof i!="string"){i.size&&this.handleIncomingBinaryMessage(i);return}const n=JSON.parse(i);if(Array.isArray(n))for(const o of n)this.handleIncomingStringMessage(o);else this.handleIncomingStringMessage(n);return}catch(n){Nt&&i==="pong"?console.log("<<",i):A()&&console.error("Failed to parse message",n)}}async handleIncomingBinaryMessage(e){xh&&console.log("<< bin",this.context.time.frame);const t=await e.arrayBuffer();var i=new Uint8Array(t);const n=new se.ByteBuffer(i),o=n.getBufferIdentifier(),r=this._listenersBinary[o],a=o0(n),l=r0(a);if(l&&typeof l=="string"&&(this._state[l]=a),!r)return;const h=a??n;for(const d of r)d(h)}handleIncomingStringMessage(e){if(Nt&&console.log("<<",e.key??e),e.key)switch(e.key){case"connection-start-info":if(e.data){const r=e.data;r&&(console.assert(r.id!==void 0&&r.id!==null&&r.id.length>0,"server did not send connection id",r.id),console.debug("Your id is: "+r.id,this.context.alias??""),this._connectionId=r.id)}else console.warn("Expected connection id in "+e.key);break;case"joined-room":if(Nt&&console.log(e),e){this._isInRoom=!0;const r=e;this._currentRoomName=r.room,this._currentRoomViewId=r.viewId,this._currentRoomAllowEditing=r.allowEditing??!0,this._currentInRoom.length=0,this._currentInRoom.push(...r.inRoom),(xh||A())&&console.debug("Joined Needle Engine Room: "+r.room);const a=new URL(window.location.href);a.searchParams.has("room")&&a.searchParams.delete("room"),a.searchParams.set("view",this._currentRoomViewId),console.debug(`Room view id: ${this._currentRoomViewId}
166
- ${a.href}`)}this.onSendQueued(Zi.OnRoomJoin);break;case"left-room":const n=e;n.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentRoomAllowEditing=!0,this._currentInRoom.length=0,(xh||A())&&console.debug("Left Needle Engine Room: "+n.room));break;case"user-joined-room":if(e.data){const r=e.data;this._currentInRoom.push(r.userId),Nt&&console.log(r.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(e.data){const r=e.data,a=this._currentInRoom.indexOf(r.userId);a>=0&&(Nt&&console.log(r.userId+" left","now in room:",this._currentInRoom),this._currentInRoom.splice(a,1)),r.userId===this.connectionId&&console.log("you left the room")}break;case"all-room-state-deleted":Nt&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":const o=e.data?.time;o&&(this._currentDelay=this.context.time.time-o),Nt&&console.log(`Current latency: ${(this._currentDelay*1e3).toFixed()} ms`,"Clients in room: "+this._currentInRoom?.length);break}const t=e.data;t&&(this._state[t.guid]=t);let i=this._listeners[e.key];if(i){i=[...i];for(const n of i)try{n(e.data)}catch(o){console.error('Error invoking callback for "'+e.key+'"',o)}}}toMessage(e,t){return{key:e,data:t}}sendWithWebsocket(e,t,i=Zi.OnRoomJoin){if(!this._ws){const o=this._waitingForSocket[i]||[];o.push(()=>this.sendWithWebsocket(e,t,i)),this._waitingForSocket[i]=o;return}const n=JSON.stringify(this.toMessage(e,t));Nt&&console.log(">>",e),this._ws.send(n)}onSendQueued(e){const t=this._waitingForSocket[e];if(t){for(const i of t)i();t.length=0}}}const zl=x("debugwebxr");class df{controllerStates=[];userId;context;userStateEvtName;constructor(e,t){this.userId=e,this.context=t,this.userStateEvtName="xr-sync-user-state-"+e,this.context.connection.beginListen(this.userStateEvtName,this.onReceivedControllerState)}dispose(){this.context.connection.stopListen(this.userStateEvtName,this.onReceivedControllerState)}onReceivedControllerState=e=>{zl&&console.log(`XRSync: Received change for ${this.userId}: ${e.type} ${e.handedness}; tracked=${e.isTracking}`);let t=!1;for(let i=0;i<this.controllerStates.length;i++)if(this.controllerStates[i].index===e.index){this.controllerStates[i]=e,t=!0;break}t||this.controllerStates.push(e)};update(e){if(this.context.connection.isConnected!=!1){for(let t=this.controllerStates.length-1;t>=0;t--){const i=this.controllerStates[t];let n=!1;for(let o=0;o<e.controllers.length;o++)e.controllers[o].index===i.index&&(n=!0);n||(zl&&console.log(`XRSync: ${i.type} ${i.handedness} removed`,i.index),this.controllerStates.splice(t,1),this.sendControllerRemoved(i))}for(const t of e.controllers)this.updateControllerStates(t)}}onExitXR(e){for(const t of this.controllerStates)this.sendControllerRemoved(t);this.controllerStates.length=0}sendControllerRemoved(e){e.isTracking=!1,e.guid="",this.context.connection.send(this.userStateEvtName,e),this.context.connection.sendDeleteRemoteState(e.guid)}updateControllerStates(e){const t=this.controllerStates.find(i=>i.index===e.index);if(t){let i=!1;i||=t.isTracking!=e.isTracking,i&&(t.isTracking=e.isTracking,this.context.connection.send(this.userStateEvtName,t))}else{const i={guid:this.userId+"-"+e.index,isTracking:e.isTracking,handedness:e.side,index:e.index,type:e.hand?"hand":"controller"};this.controllerStates.push(i),this.context.connection.send(this.userStateEvtName,i),zl&&console.log(`XRSync: ${i.type} ${i.handedness} added`,i.index)}}}class u0{hasState(e){return e?this._states.has(e):!1}isTracking(e,t){if(!e)return;const i=this._states.get(e);return i?i.controllerStates.find(o=>o.handedness===t)?.isTracking||!1:void 0}getDeviceType(e,t){if(!e)return;const i=this._states.get(e);return i?i.controllerStates.find(o=>o.handedness===t)?.type||"unknown":void 0}context;constructor(e){this.context=e,this.context.connection.beginListen(Q.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Q.LeftRoom,this.onLeftRoom),this.context.connection.beginListen(Q.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.beginListen(Q.UserLeftRoom,this.onOtherUserLeftRoom)}destroy(){this.context.connection.stopListen(Q.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Q.LeftRoom,this.onLeftRoom),this.context.connection.stopListen(Q.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.stopListen(Q.UserLeftRoom,this.onOtherUserLeftRoom)}onJoinedRoom=()=>{if(this.context.connection.connectionId){this._states.has(this.context.connection.connectionId)||(zl&&console.log("XRSync: Local user joined room",this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new df(this.context.connection.connectionId,this.context)));for(const e of this.context.connection.usersInRoom())this._states.has(e)||this._states.set(e,new df(e,this.context))}};onLeftRoom=()=>{this.context.connection.connectionId&&(this._states.has(this.context.connection.connectionId)||(this._states.get(this.context.connection.connectionId)?.dispose(),this._states.delete(this.context.connection.connectionId)))};onOtherUserJoinedRoom=e=>{const t=e.userId;this._states.has(t)||(zl&&console.log("XRSync: Remote user joined room",t),this._states.set(t,new df(t,this.context)))};onOtherUserLeftRoom=e=>{const t=e.userId;this._states.has(t)||(this._states.get(t)?.dispose(),this._states.delete(t))};_states=new Map;onUpdate(e){this.context.connection.isConnected&&this.context.connection.connectionId&&this._states.get(this.context.connection.connectionId)?.update(e)}onExitXR(e){this.context.connection.isConnected&&this.context.connection.connectionId&&this._states.get(this.context.connection.connectionId)?.onExitXR(e)}}class Hy{_fadeToColorQuad;_fadeToColorMaterial;constructor(){this._fadeToColorMaterial=new c.MeshBasicMaterial({color:0,transparent:!0,depthTest:!1,fog:!1,side:c.DoubleSide}),this._fadeToColorQuad=new c.Mesh(new c.PlaneGeometry(10,10),this._fadeToColorMaterial)}dispose(){this._fadeToColorQuad.geometry.dispose(),this._fadeToColorMaterial.dispose()}update(e,t){const i=this._fadeToColorQuad,n=this._fadeToColorMaterial;i.parent!==e&&n.opacity>0?e.add(i):n.opacity===0&&i.removeFromParent(),i.layers.set(2),i.material=this._fadeToColorMaterial,i.position.z=-1,i.renderOrder=1/0;const o=this._requestedFadeValue;n.opacity=L.lerp(n.opacity,o,t/.03),Math.abs(n.opacity-o)<=.01&&this._transitionResolve&&(this._transitionResolve(),this._transitionResolve=null,this._transitionPromise=null,this._requestedFadeValue=0)}remove(){this._fadeToColorQuad.removeFromParent()}fadeTransition(){if(this._transitionPromise)return this._transitionPromise;this._requestedFadeValue=1;const e=new Promise(t=>{this._transitionResolve=t});return this._transitionPromise=e,e}_requestedFadeValue=0;_transitionPromise=null;_transitionResolve=null}var Jo=(s=>(s[s.Quad=0]="Quad",s[s.Cube=1]="Cube",s[s.Sphere=2]="Sphere",s[s.Cylinder=3]="Cylinder",s[s.RoundedCube=10]="RoundedCube",s))(Jo||{});class hr{static createText(e,t){let i=null;const n=t?.font||XS(t?.familyFamily||null);n instanceof q.Font?i=this.#t(e,n,t):i==null&&(i=new c.BufferGeometry);const o=t?.color||16777215,r=new c.Mesh(i,t?.material??new c.MeshStandardMaterial({color:o}));return this.applyDefaultObjectOptions(r,t),n instanceof Promise?n.then(a=>{r.geometry=this.#t(e,a,t),t?.onGeometry&&t.onGeometry(r)}):t?.onGeometry&&t.onGeometry(r),r}static#t(e,t,i){const n=i?.depth||.1;return new q.TextGeometry(e,{font:t,size:1,depth:n,height:n,bevelEnabled:i?.bevel||!1,bevelThickness:.01,bevelOffset:.01,bevelSize:.01})}static createOccluder(e){const t=new c.MeshBasicMaterial({colorWrite:!1,depthWrite:!0,side:c.DoubleSide});return this.createPrimitive(e,{material:t})}static createPrimitive(e,t){let i;const n=t?.color||16777215;switch(e){case"Quad":case 0:{const o=new c.PlaneGeometry(1,1,1,1),r=t?.material??new c.MeshStandardMaterial({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new c.Mesh(o,r),i.name="Quad"}break;case"Cube":case 1:{const o=new c.BoxGeometry(1,1,1),r=t?.material??new c.MeshStandardMaterial({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new c.Mesh(o,r),i.name="Cube"}break;case 10:case"RoundedCube":{const o=qS(1,1,1,.1,2),r=t?.material??new c.MeshStandardMaterial({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new c.Mesh(o,r),i.name="RoundedCube"}break;case"Sphere":case 2:{const o=new c.SphereGeometry(.5,16,16),r=t?.material??new c.MeshStandardMaterial({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new c.Mesh(o,r),i.name="Sphere"}break;case"Cylinder":case 3:{const o=new c.CylinderGeometry(.5,.5,1,32),r=t?.material??new c.MeshStandardMaterial({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new c.Mesh(o,r),i.name="Cylinder"}break;case"ShaderBall":i=new c.Group,i.name="ShaderBall",QS(i,t);break}return this.applyDefaultObjectOptions(i,t),i}static createSprite(e){const i=new c.SpriteMaterial({color:16777215});e?.texture&&"map"in i&&(i.map=e.texture);const n=new c.Sprite(i);return this.applyDefaultObjectOptions(n,e),n}static applyDefaultObjectOptions(e,t){e.receiveShadow=!0,e.castShadow=!0,t?.name&&(e.name=t.name),t?.position&&(Array.isArray(t.position)?e.position.set(t.position[0],t.position[1],t.position[2]):e.position.set(t.position.x||0,t.position.y||0,t.position.z||0)),t?.rotation&&(Array.isArray(t.rotation)?e.rotation.set(t.rotation[0],t.rotation[1],t.rotation[2]):e.rotation.set(t.rotation.x||0,t.rotation.y||0,t.rotation.z||0)),t?.scale&&(typeof t.scale=="number"?e.scale.set(t.scale,t.scale,t.scale):Array.isArray(t.scale)?e.scale.set(t.scale[0],t.scale[1],t.scale[2]):e.scale.set(t.scale.x||1,t.scale.y||1,t.scale.z||1)),t?.receiveShadow!=null&&(e.receiveShadow=t.receiveShadow),t?.castShadow!=null&&(e.castShadow=t.castShadow),t?.parent&&t.parent.add(e)}}function qS(s,e,t,i,n){const o=new c.Shape,r=1e-5,a=i-r;o.absarc(r,r,r,-Math.PI/2,-Math.PI,!0),o.absarc(r,e-a*2,r,Math.PI,Math.PI/2,!0),o.absarc(s-a*2,e-a*2,r,Math.PI/2,0,!0),o.absarc(s-a*2,r,r,0,-Math.PI/2,!0);const l=new c.ExtrudeGeometry(o,{bevelEnabled:!0,bevelSegments:n*2,steps:1,bevelSize:a,bevelThickness:i,curveSegments:n,UVGenerator:{generateTopUV:(h,d)=>{const u=[];for(let p=0;p<d.length;p+=3)u.push(new c.Vector2(d[p]/s,d[p+1]/e));return u},generateSideWallUV:(h,d,u,p,m,y)=>{const _=[];return _.push(new c.Vector2(d[u]/s,d[u+1]/e)),_.push(new c.Vector2(d[p]/s,d[p+1]/e)),_.push(new c.Vector2(d[m]/s,d[m+1]/e)),_.push(new c.Vector2(d[y]/s,d[y+1]/e)),_}}});return l.scale(1,1,1-i),l.center(),l.index||l.setIndex(Array.from({length:l.attributes.position.count},(h,d)=>d)),l.computeVertexNormals(),l}const Sh=new Map;function XS(s){let e="";switch(s){default:case"OpenSans":e="https://cdn.needle.tools/static/fonts/facetype/Open Sans_Regular_ascii.json";break;case"Helvetiker":e="https://raw.githubusercontent.com/mrdoob/three.js/master/examples/fonts/helvetiker_regular.typeface.json";break}if(Sh.has(e)){const n=Sh.get(e);if(n)return n}const t=new q.FontLoader,i=new Promise((n,o)=>{t.load(e,r=>{Sh.set(e,r),n(r)},void 0,o)});return Sh.set(e,i),i}let uf=!1,ff=null;function QS(s,e){if(ff===null){const t="https://cdn.needle.tools/static/models/shaderball.glb",i=new q.GLTFLoader,n=ne.createLoaders(null);i.setDRACOLoader(n.dracoLoader),i.setKTX2Loader(n.ktx2Loader),uf=!0,ff=i.loadAsync(t).then(o=>{const r=o.scene;return r.position.y-=.5,r}).catch(o=>(console.warn("Failed to load shaderball mesh: "+o.message),qy())).finally(()=>{uf=!1})}if(uf){const t=qy();t.name="ShaderBall-Placeholder";const i=t.children[0];i?.type==="Mesh"&&Gy(i,e),s.add(t)}ff.then(t=>{s.children.forEach(o=>{o.name==="ShaderBall-Placeholder"&&s.remove(o)});const i=t.clone(),n=i.children[0];n?.type==="Mesh"&&(n.geometry.attributes.tangent||n.geometry.computeTangents(),Gy(n,e)),s.add(i)})}function Gy(s,e){if(e?.color||e?.material||e?.texture){const i=e?.material??s.material?.clone()??new c.MeshStandardMaterial;e.color&&"color"in i&&i.color instanceof c.Color&&i.color.set(e.color),e?.texture&&"map"in i&&(i.map=e.texture),s.material=i}}function qy(){return new c.Group().add(hr.createPrimitive("Sphere",{material:new c.MeshBasicMaterial({transparent:!0,opacity:.1})}))}class ba{static _active=null;static get active(){return this._active}static _requestInFlight=!1;static async start(e,t){if(this._active)return console.error("Cannot start a new XR session while one is already active"),null;if(this._requestInFlight)return console.error("Cannot start a new XR session while a request is already in flight"),null;if("xr"in navigator&&navigator.xr){if(!t)return console.error("XRSessionInit must be provided"),null;this._requestInFlight=!0;const i=await navigator.xr.requestSession(e,t);return i.addEventListener("end",()=>{this._active=null}),this._requestInFlight?(this._requestInFlight=!1,this._active=new ba(e,t,i),this._active):(i.end(),null)}return null}static async handoff(){return this._active?this._active.handoff():null}static async stop(){this._requestInFlight=!1,this._active&&(await this._active.end(),await Bn(100)),this._active=null}_session;_mode;_init;get isAR(){return this._mode==="immersive-ar"}_renderer;_camera;_scene;constructor(e,t,i){this._mode=e,this._init=t,this._session=i,this._session.addEventListener("end",this.onEnd),this._renderer=new c.WebGLRenderer({alpha:!0}),this._renderer.setAnimationLoop(this.onFrame),this._renderer.xr.setSession(i),this._renderer.xr.enabled=!0,this._camera=new c.PerspectiveCamera,this._scene=new c.Scene,this._scene.fog=new c.Fog(4473924,10,250),this._scene.add(this._camera),this.setupScene()}end(){return this._session?this._session.end():Promise.resolve()}async handoff(){if(!this._session)throw new Error("Cannot handoff a session that has already ended");const e={session:this._session,mode:this._mode,init:this._init};return await this.onBeforeHandoff(),this.onEnd(),this._session=null,e}onEnd=()=>{this._session?.removeEventListener("end",this.onEnd),this._renderer.setAnimationLoop(null),this._renderer.dispose(),this._scene.clear()};_lastTime=0;onFrame=(e,t)=>{const i=e-this._lastTime;this.update(e,i),this._camera.parent!==this._scene&&this._scene.add(this._camera),this._renderer.render(this._scene,this._camera)};async onBeforeHandoff(){await Bn(1e3),this._scene.clear()}_objects=[];setupScene(){this._scene.background=new c.Color(0),this._scene.add(new c.GridHelper(5,10,1118481,1118481));const e=new c.DirectionalLight(16777215,1);e.position.set(0,20,0),e.castShadow=!1,this._scene.add(e);const t=new c.DirectionalLight(16777215,1);t.position.set(0,-1,0),t.castShadow=!1,this._scene.add(t);const i=new c.PointLight(16777215,1,100,1);i.position.set(0,2,0),i.castShadow=!1,i.distance=200,this._scene.add(i);const n=50;for(let o=0;o<100;o++){const r=new c.MeshStandardMaterial({color:2236962,metalness:1,roughness:.8});this.isAR&&(r.emissive=new c.Color(Math.random(),Math.random(),Math.random()),r.emissiveIntensity=Math.random());const a=L.random(0,1)>.5?Jo.Sphere:Jo.Cube,l=hr.createPrimitive(a,{material:r});l.position.x=L.random(-n,n),l.position.y=L.random(-2,n),l.position.z=L.random(-n,n),l.rotation.x=L.random(0,Math.PI*2),l.rotation.y=L.random(0,Math.PI*2),l.rotation.z=L.random(0,Math.PI*2),l.scale.multiplyScalar(.5+Math.random()*10);const h=l.position.distanceTo(this._camera.position)-l.scale.x;h<1&&l.position.multiplyScalar(1+1/h),this._objects.push(l),this._scene.add(l)}}update(e,t){const i=e*4e-4;for(let n=0;n<this._objects.length;n++){const o=this._objects[n];o.position.y+=Math.sin(i+n*.5)*.005,o.rotateY(.002)}}}var ic;(s=>{const e=[];function t(){if(!e?.length)return!1;for(const o of e)o.exportAndOpen();return!0}s.exportAndOpen=t;function i(o){e.push(o)}s.registerExporter=i;function n(o){if(!e)return;const r=e.indexOf(o);r>=0&&e.splice(r,1)}s.unregisterExporter=n})(ic||(ic={}));const Le=x("debugwebxr"),Xy=x("stats");let pf=0;function YS(s){let e=null;const t=s;return t.getAROverlayContainer?e=t.getAROverlayContainer():e=s,e}KS();async function KS(){if(x("debugasap")){let s=globalThis["needle:XRSession"];if(s instanceof Promise){delete globalThis["needle:XRSession"],ae.addContextCreatedCallback(async e=>{if(!s)return;No(!0);const t=await s;if(t){const i=G.getDefaultSessionInit("immersive-vr");G.setSession("immersive-vr",t,i,e.context)}else console.error("NeedleXRSession: ASAP session was rejected");s=void 0});return}}if("xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent)){console.warn("WebXRViewer does not support addEventListener");return}navigator.xr?.addEventListener("sessiongranted",async()=>{No(!0),console.log("Received Session Granted..."),await Bn(100);const s=sessionStorage.getItem("needle_xr_session_mode"),e=sessionStorage.getItem("needle_xr_session_init")??null,t=e?JSON.parse(e):null;let i=null;if(f0()&&(await ba.start(s||"immersive-vr",t||G.getDefaultSessionInit("immersive-vr")),await eC(),i=await ba.handoff()),i)G.setSession(i.mode,i.session,i.init,N.Current);else if(s&&e){console.log("Session Granted: Restore last session");const n=JSON.parse(e);G.start(s,n).catch(o=>console.warn(o))}else G.start("immersive-vr").catch(n=>console.warn("Session Granted failed:",n))},{once:!0})}}function ZS(s,e){sessionStorage.setItem("needle_xr_session_mode",s),sessionStorage.setItem("needle_xr_session_init",JSON.stringify(e))}function JS(){sessionStorage.removeItem("needle_xr_session_mode"),sessionStorage.removeItem("needle_xr_session_init")}const Am=new Set;ae.registerCallback(re.ContextCreationStart,async s=>{Am.add(s.context)});ae.registerCallback(re.ContextCreated,async s=>{Am.delete(s.context);const e=s.context?.domElement.getAttribute("autostart")||null;tC(e)});function f0(){return Am.size>0}function eC(){return new Promise(s=>{const e=Date.now(),t=setInterval(()=>{(!f0()||Date.now()-e>6e4)&&(clearInterval(t),s())},100)})}exports.DeviceUtilities.isDesktop()&&A()&&window.addEventListener("keydown",s=>{(s.key==="x"||s.key==="Escape")&&G.active&&G.stop()});function tC(s){if(s)switch(s?.toLowerCase()){case"ar":an.registerWaitForInteraction(()=>{G.start("ar")});break}}const Ch=Symbol("initial-fov");class G{static _sync=null;static getXRSync(e){return this._sync||(this._sync=new u0(e)),this._sync}static get currentSessionRequest(){return this._currentSessionRequestMode}static _currentSessionRequestMode=null;static get active(){return this._activeSession}static get activeMode(){return this._activeSession?.mode??null}static get xrSystem(){return"xr"in navigator?navigator.xr:void 0}static isXRSupported(){return Promise.all([this.isVRSupported(),this.isARSupported()]).then(e=>e.some(t=>t)).catch(()=>!1)}static isVRSupported(){return this.isSessionSupported("immersive-vr")}static isARSupported(){return this.isSessionSupported("immersive-ar")}static isSessionSupported(e){return this.xrSystem?.isSessionSupported(e).catch(t=>(Le&&console.error(t),!1))??Promise.resolve(!1)}static _currentSessionRequest;static _activeSession;static onSessionRequestStart(e){this._sessionRequestStartListeners.push(e)}static offSessionRequestStart(e){const t=this._sessionRequestStartListeners.indexOf(e);t>=0&&this._sessionRequestStartListeners.splice(t,1)}static _sessionRequestStartListeners=[];static onSessionRequestEnd(e){this._sessionRequestEndListeners.push(e)}static offSessionRequestEnd(e){const t=this._sessionRequestEndListeners.indexOf(e);t>=0&&this._sessionRequestEndListeners.splice(t,1)}static _sessionRequestEndListeners=[];static onXRSessionStart(e){this._xrStartListeners.push(e)}static offXRSessionStart(e){const t=this._xrStartListeners.indexOf(e);t>=0&&this._xrStartListeners.splice(t,1)}static _xrStartListeners=[];static onXRSessionEnd(e){this._xrEndListeners.push(e)}static offXRSessionEnd(e){const t=this._xrEndListeners.indexOf(e);t>=0&&this._xrEndListeners.splice(t,1)}static _xrEndListeners=[];static onControllerAdded(e){this._controllerAddedListeners.push(e)}static offControllerAdded(e){const t=this._controllerAddedListeners.indexOf(e);t>=0&&this._controllerAddedListeners.splice(t,1)}static _controllerAddedListeners=[];static onControllerRemoved(e){this._controllerRemovedListeners.push(e)}static offControllerRemoved(e){const t=this._controllerRemovedListeners.indexOf(e);t>=0&&this._controllerRemovedListeners.splice(t,1)}static _controllerRemovedListeners=[];static offerSession(e,t,i){return"xr"in navigator&&navigator.xr&&"offerSession"in navigator.xr?(typeof navigator.xr.offerSession=="function"&&(console.log("WebXR offerSession is available - requesting mode: "+e),t=="default"&&(t=this.getDefaultSessionInit(e)),navigator.xr.offerSession(e,{...t}).then(n=>G.setSession(e,n,t,i)).catch(n=>{console.log("XRSession offer rejected (perhaps because another call to offerSession was made or a call to requestSession was made)")})),!0):!1}static getDefaultSessionInit(e){switch(e){case"immersive-ar":const t=["anchors","local-floor","layers","dom-overlay","hit-test","unbounded"];return exports.DeviceUtilities.isVisionOS()||t.push("hand-tracking"),{optionalFeatures:t};case"immersive-vr":const i=["local-floor","bounded-floor","high-fixed-foveation-level","layers"];return exports.DeviceUtilities.isVisionOS()||i.push("hand-tracking"),{optionalFeatures:i};default:return console.warn("No default session init for mode",e),{}}}static async start(e,t,i){if(exports.DeviceUtilities.isiOS()){if(e==="ar")if(await this.isARSupported())e="immersive-ar";else return ic.exportAndOpen(),null}else e=="ar"&&(e="immersive-ar");if(A()&&x("debugxrpreroom"))return console.warn("Debug: Starting temporary XR session"),await ba.start(e,t||G.getDefaultSessionInit(e)),null;if(this._currentSessionRequest)return console.warn("A XRSession is already being requested"),(Le||A())&&de("A XRSession is already being requested"),this._currentSessionRequest.then(()=>this._activeSession);if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;if(i||(i=N.Current),i||(i=ae.All[0]),!i)throw new Error("No Needle Engine Context found");switch(t||(t={}),e){case"immersive-ar":{if(await this.xrSystem?.isSessionSupported("immersive-ar")!==!0)return console.error(e+" is not supported by this browser."),null;const l=this.getDefaultSessionInit(e),h=YS(i.domElement);h&&!exports.DeviceUtilities.isQuest()&&(l.domOverlay={root:h},l.optionalFeatures.push("dom-overlay")),t={...l,...t}}break;case"immersive-vr":{if(await this.xrSystem?.isSessionSupported("immersive-vr")!==!0)return console.error(e+" is not supported by this browser."),null;t={...this.getDefaultSessionInit(e),...t}}break;default:console.warn("No default session init for mode",e);break}t.optionalFeatures??=[],t.requiredFeatures??=[],await ba.stop();const n=e=="immersive-ar"?i.scripts_immersive_ar:i.scripts_immersive_vr;Le?console.log(`%cRequesting ${e} session`,"font-weight:bold;",t,n):console.log(`%cRequesting ${e} session`,"font-weight:bold;");for(const a of n)a.onBeforeXR&&a.onBeforeXR(e,t);for(const a of this._sessionRequestStartListeners)a({mode:e,init:t});Le&&Ce("Requesting "+e+" session ("+Date.now()+")"),this._currentSessionRequest=navigator?.xr?.requestSession(e,t),this._currentSessionRequestMode=e;const o=await this._currentSessionRequest?.catch(a=>{console.error(a,"Code: "+a.code),a.code===9&&de("Make sure your device has the required permissions (e.g. camera access)"),console.log("If the specified XR configuration is not supported (e.g. entering AR doesnt work) - make sure you access the website on a secure connection (HTTPS) and your device has the required permissions (e.g. camera access)"),location.protocol==="http:"&&de("XR requires a secure connection (HTTPS)")});this._currentSessionRequest=void 0,this._currentSessionRequestMode=null;for(const a of this._sessionRequestEndListeners)a({mode:e,init:t,newSession:o||null});return o?this.setSession(e,o,t,i):(console.warn("XR Session request was rejected"),null)}static setSession(e,t,i,n){if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;const o=e=="immersive-ar"?n.scripts_immersive_ar:n.scripts_immersive_vr;return this._activeSession=new G(e,t,n,{scripts:o,controller_added:this._controllerAddedListeners,controller_removed:this._controllerRemovedListeners,init:i}),t.addEventListener("end",this.onEnd),Le?console.log(`%cStarted ${e} session`,"font-weight:bold;",o):console.log(`%cStarted ${e} session`,"font-weight:bold;"),this._activeSession}static $_stop_request=Symbol();static stop(){const e=this._activeSession;e&&(e[this.$_stop_request]===void 0?(Le&&console.log("[NeedleXRSession] Stopping XR Session... (new)"),e[this.$_stop_request]=setTimeout(()=>{e.end()})):Le&&console.warn("[NeedleXRSession] XR Session stop already requested"))}static onEnd=()=>{Le&&console.log("XR Session ended"),this._activeSession=null};context;get sync(){return G._sync}get running(){return!this._ended&&this.session!=null}session;mode;get interactionMode(){return this.session.interactionMode}get visibilityState(){return this.session.visibilityState}get isVisibleBlurred(){return this.session.visibilityState==="visible-blurred"}get isSystemKeyboardSupported(){return this.session.isSystemKeyboardSupported}get environmentBlendMode(){return this.session.environmentBlendMode}get frame(){return this.context.xrFrame}controllers=[];get leftController(){return this.controllers.find(e=>e.side==="left")}get rightController(){return this.controllers.find(e=>e.side==="right")}getController(e){return typeof e=="number"?this.controllers[e]||null:this.controllers.find(t=>t.side===e)||null}get isPassThrough(){return!!(this.environmentBlendMode!=="opaque"&&this.interactionMode==="world-space"||this.mode==="immersive-ar"&&this.environmentBlendMode!=="opaque"&&this.controllers.some(e=>e.inputSource.targetRayMode==="tracked-pointer")||A()&&exports.DeviceUtilities.isDesktop()&&this.mode==="immersive-ar")}get isAR(){return this.mode==="immersive-ar"}get isVR(){return this.mode==="immersive-vr"}get isScreenBasedAR(){return this.isAR&&!this.isPassThrough}get posePosition(){return this._transformPosition}get poseOrientation(){return this._transformOrientation}get referenceSpace(){return this.context.renderer.xr.getReferenceSpace()}get viewerPose(){return this._viewerPose}get isTrackingImages(){if(this.frame&&"getImageTrackingResults"in this.frame&&typeof this.frame.getImageTrackingResults=="function")try{const e=this.frame.getImageTrackingResults();for(const t of e)if(t.trackingState==="tracked")return!0}catch{return!1}return!1}get rig(){const e=this._rigs[0]??null;return e?.gameObject&&er(e.gameObject)||e?.isActive===!1?(this.updateActiveXRRig(),this._rigs[0]??null):e}_rigScale=1;_lastRigScaleUpdate=-1;get rigScale(){return this._rigs[0]?(this._lastRigScaleUpdate!==this.context.time.frame&&(this._lastRigScaleUpdate=this.context.time.frame,this._rigScale=this._rigs[0].gameObject.worldScale.x),this._rigScale):1}addRig(e){this._rigs.indexOf(e)>=0||(e.priority===void 0&&(e.priority=0),this._rigs.push(e),this.updateActiveXRRig())}removeRig(e){const t=this._rigs.indexOf(e);t!==-1&&(this._rigs.splice(t,1),this.updateActiveXRRig())}setRigActive(e){const t=this._rigs.indexOf(e),i=this._rigs[0];this._rigs.splice(t,1),this._rigs.unshift(e),e.priority=i?.priority??0,this.updateActiveXRRig()}getUserOffsetInRig(){const e=this.context.mainCamera?.position;if(!e||!this.rig)return j(0,0,0);const t=j(e);return t.x*=-1,t.z*=-1,t.applyQuaternion(qt(this.rig.gameObject.quaternion)),t}updateActiveXRRig(){const e=this._rigs[0]??null;this._defaultRig.gameObject.parent!==this.context.scene&&this.context.scene.add(this._defaultRig.gameObject),this._defaultRig.gameObject.visible=!0,this._rigs.includes(this._defaultRig)||this._rigs.push(this._defaultRig);let t=this._rigs[0];t&&t.priority===void 0&&(t.priority=0);for(let i=1;i<this._rigs.length;i++){const n=this._rigs[i];if(n.isActive){if(er(n.gameObject)){this._rigs.splice(i,1),i--;continue}(!t||t.isActive===!1||n.priority!==void 0&&n.priority>t.priority)&&(t=n)}}if(e!==t){const i=this._rigs.indexOf(t);i>=0&&this._rigs.splice(i,1),this._rigs.unshift(t)}Le&&(e===t?console.log("Updated Active XR Rig:",t,"prev:",e):console.log("Updated Active XRRig:",t," (the same as before)"))}_rigs=[];_viewerHitTestSource=null;getHitTest(e){if(e)return this.getControllerHitTest(e);if(!this._viewerHitTestSource)return null;const t=this._viewerHitTestSource,i=this.frame.getHitTestResults(t);if(i.length>0){const n=i[0];return this.convertHitTestResult(n)}return null}getControllerHitTest(e){const t=e.getHitTestSource();if(!t)return null;const i=this.frame.getHitTestResultsForTransientInput(t);for(const n of i)if(n.inputSource===e.inputSource)for(const o of n.results)return this.convertHitTestResult(o);return null}convertHitTestResult(e){const t=this.context.renderer.xr.getReferenceSpace(),i=t&&e.getPose(t);if(i){const n=j(i.transform.position),o=qt(i.transform.orientation),r=this.context.mainCamera;if(r?.parent!==this._cameraRenderParent&&n.applyMatrix4(aa),r?.parent){n.applyMatrix4(r.parent.matrixWorld),o.multiply(ki);const a=ue(r.parent);a.premultiply(ki),o.premultiply(a)}return{hit:e,position:n,quaternion:o}}return null}convertSpace(e){const t=j(e.position);t.applyMatrix4(aa);const i=qt(e.orientation);return i.premultiply(ki),{position:t,quaternion:i}}_defaultRig;_xr_scripts;_xr_update_scripts=[];_inactive_scripts=[];_controllerAdded;_controllerRemoved;_originalCameraWorldPosition;_originalCameraWorldRotation;_originalCameraWorldScale;_originalCameraParent;_mainCamera=null;constructor(e,t,i,n){ZS(e,n.init),this.session=t,this.mode=e,this.context=i,(Le||x("console"))&&No(!0),this._xr_scripts=[...n.scripts],this._xr_update_scripts=this._xr_scripts.filter(o=>typeof o.onUpdateXR=="function"),this._controllerAdded=n.controller_added,this._controllerRemoved=n.controller_removed,us(this.onBefore,pe.LateUpdate),this.context.pre_render_callbacks.push(this.onBeforeRender),this.context.post_render_callbacks.push(this.onAfterRender),(n.init.optionalFeatures?.includes("hit-test")||n.init.requiredFeatures?.includes("hit-test"))&&t.requestReferenceSpace("viewer").then(o=>t.requestHitTestSource?.call(t,{space:o})?.then(r=>this._viewerHitTestSource=r).catch(r=>console.error(r))).catch(o=>console.error(o)),this.context.mainCamera&&(this._originalCameraWorldPosition=X(this.context.mainCamera,new c.Vector3),this._originalCameraWorldRotation=ue(this.context.mainCamera,new c.Quaternion),this._originalCameraWorldScale=je(this.context.mainCamera,new c.Vector3),this._originalCameraParent=this.context.mainCamera.parent,this.context.mainCamera instanceof c.PerspectiveCamera&&(this.context.mainCamera[Ch]=this.context.mainCamera.fov)),this._defaultRig=new IS,this.context.scene.add(this._defaultRig.gameObject),this.addRig(this._defaultRig);for(let o=0;o<t.inputSources.length;o++){const r=t.inputSources[o];if(!r.handedness){console.warn("Input source in xr session has no handedness - ignoring",o);continue}this.onInputSourceAdded(r)}this.session.addEventListener("end",this.onEnd),this.session.addEventListener("inputsourceschange",o=>{for(const r of o.removed)this.disconnectInputSource(r);for(const r of o.added)this.onInputSourceAdded(r)}),this.context.xr=this,this.context.renderer.xr.setSession(this.session).then(this.onRendererSessionSet),"controllerAutoUpdate"in this.context.renderer.xr?(console.debug("Disabling three.js controllerAutoUpdate"),this.context.renderer.xr.controllerAutoUpdate=!1):Le&&console.warn("controllerAutoUpdate is not available in three.js - cannot disable it")}onRendererSessionSet=()=>{this.running&&(this.context.renderer.xr.enabled=!0,this.context.renderer.xr.updateCamera(this.context.mainCamera),this.context.mainCameraComponent?.applyClearFlags())};onInputSourceAdded=e=>{if(e.targetRayMode==="screen")return;let t=0;for(let n=0;n<this.session.inputSources.length;n++)if(this.session.inputSources[n]===e){t=n;break}if(this.controllers.find(n=>n.inputSource===e)){console.debug("Controller already exists for input source",t);return}else if(this._newControllers.find(n=>n.inputSource===e)){console.debug("Controller already registered for input source",t);return}const i=new Mm(this,e,t);this._newControllers.push(i)};disconnectInputSource(e){const t=(o,r)=>{if(o.inputSource===e){Le&&console.log("Disconnecting controller",o.index);const a=r.indexOf(o);a>=0&&r.splice(a,1),this.invokeControllerEvent(o,this._controllerRemoved,"removed");const l={xr:this,controller:o,change:"removed"};for(const h of this._xr_scripts)h.onXRControllerRemoved&&h.onXRControllerRemoved(l);o.onDisconnected()}},i=[...this.controllers];for(let o=i.length-1;o>=0;o--){const r=i[o];t(r,this.controllers)}const n=[...this._newControllers];for(let o=n.length-1;o>=0;o--){const r=n[o];t(r,this._newControllers)}}end(){this._ended||this.session.end().catch(e=>console.warn(e))}_ended=!1;_newControllers=[];onEnd=e=>{if(this._ended)return;this._ended=!0,console.debug("XR Session ended"),JS(),this.onAfterRender(),this.revertCustomForward(),this._didStart=!1,this._previousCameraParent=null,this.requestedCameraNearPlane=null,ao(this.onBefore,pe.LateUpdate);const t=this.context.pre_render_callbacks.indexOf(this.onBeforeRender);t>=0&&this.context.pre_render_callbacks.splice(t,1);const i=this.context.post_render_callbacks.indexOf(this.onAfterRender);i>=0&&this.context.post_render_callbacks.splice(i,1),this.context.xr=null,this.context.renderer.xr.enabled=!1,this.context.pre_update_oneshot_callbacks.push(()=>{this.context.mainCameraComponent?.applyClearFlags(),this.context.mainCameraComponent?.applyClippingPlane()}),i0({session:this});for(const o of G._xrEndListeners)o({xr:this});const n=[...this.controllers];for(let o=0;o<n.length;o++)this.disconnectInputSource(n[o].inputSource);this.controllers.length=0,this._newControllers.length=0;for(const o of this._xr_scripts)o?.onLeaveXR?.({xr:this});this.sync?.onExitXR(this),this.context.mainCamera&&(this._originalCameraParent?.add(this.context.mainCamera),this._originalCameraWorldPosition&&ot(this.context.mainCamera,this._originalCameraWorldPosition),this._originalCameraWorldRotation&&on(this.context.mainCamera,this._originalCameraWorldRotation),this._originalCameraWorldScale&&ga(this.context.mainCamera,this._originalCameraWorldScale),this.context.mainCamera instanceof c.PerspectiveCamera&&this.context.mainCamera[Ch]&&(this.context.mainCamera.fov=this.context.mainCamera[Ch],this.context.mainCamera[Ch]=0)),this.context.requestSizeUpdate(),this._defaultRig.gameObject.removeFromParent(),No(!1)};_didStart=!1;onBefore=e=>{const t=e.xrFrame;if(!t)return;this.context.xr=this,this.context.mainCameraComponent&&this.context.mainCameraComponent!==this._mainCamera&&(this._mainCamera=this.context.mainCameraComponent),this.rig?.isActive==!1&&(Le&&console.warn("Latest rig is not active - trying to activate a different rig",this.rig),this.updateActiveXRRig()),this.rig&&this._mainCamera?.gameObject&&this._mainCamera?.gameObject?.parent!==this.rig.gameObject&&this.rig.gameObject.add(this._mainCamera?.gameObject),this.internalUpdateState(),this.applyCustomForward();const i={xr:this};if(this._didStart){if(this.context.new_scripts_xr.length>0){const n=[...this.context.new_scripts_xr];for(let o=0;o<n.length;o++){const r=this.context.new_scripts_xr[o];if(!r||r.destroyed||r.supportsXR?.(this.mode)==!1){this.context.new_scripts_xr.splice(o,1);continue}if(!r.activeAndEnabled){this.context.new_scripts_xr.splice(o,1),this.markInactive(r);continue}if(this.addScript(r)){this.invokeCallback_EnterXR(r);for(const a of this.controllers)this.invokeCallback_ControllerAdded(r,a)}}}}else{if(this._didStart=!0,this.mode==="immersive-vr"){const o=Ft(this.context.scene.children);if(o){const r=o.getSize(j());if(r.length()>0){const a=this._defaultRig.gameObject;a.position.set(o.min.x+r.x*.5,o.min.y,o.max.z+r.z*.5+1.5);const l=o.getCenter(j());l.y=a.position.y,a.lookAt(l)}}}t0({session:this}),cr();for(const o of G._xrStartListeners)o(i);const n=[...this._xr_scripts];Le&&console.log("NeedleXRSession start, handle scripts:",n);for(const o of n){if(o.destroyed){this._script_to_remove.push(o);continue}if(!o.activeAndEnabled){this.markInactive(o);continue}this.invokeCallback_EnterXR(o);for(const r of this.controllers)this.invokeCallback_ControllerAdded(o,r)}}this.syncCameraCullingMask();for(const n of this.controllers)n.onUpdate(t);if(this._newControllers.length>0){const n=[...this._newControllers];this._newControllers.length=0;for(const o of n){if(!o.connected){console.warn("New controller is not connected",o);continue}this.controllers.push(o);for(const r of this._xr_scripts){if(r.destroyed){this._script_to_remove.push(r);continue}r.activeAndEnabled!==!1&&this.invokeCallback_ControllerAdded(r,o)}}this.controllers.sort((o,r)=>o.index-r.index)}Le&&this.context.time.frame%30===0&&this.controllers.length<=0&&this.session.inputSources.length>0&&(No(!0),console.error("XRControllers are not added but inputSources are present"));for(const n of this._xr_update_scripts){if(n.destroyed===!0){this._script_to_remove.push(n);continue}if(n.activeAndEnabled===!1){this.markInactive(n);continue}n.onUpdateXR&&n.onUpdateXR(i)}if(this.handleInactiveScripts(),this._script_to_remove.length>0){const n=[...new Set(this._script_to_remove)];this._script_to_remove.length=0;for(const o of n)!o.destroyed&&this.running&&o.onLeaveXR?.(i),this.removeScript(o)}this.sync?.onUpdate(this),this.onRenderDebug()};onRenderDebug(){if(Le)for(const e of this.controllers)e.onRenderDebug();if((Le||Xy)&&this.rig&&(pf++,pf>=20)){const e=this.rig.gameObject.worldPosition,t=this.rig.gameObject.worldForward;e.add(t.multiplyScalar(1.5));const i=this.rig.gameObject.worldUp;e.add(i.multiplyScalar(2.5));let n="";if(n+=`${this.context.time.smoothedFps.toFixed(0)} FPS`,n+=`, calls: ${this.context.renderer.info.render.calls}, tris: ${this.context.renderer.info.render.triangles.toLocaleString()}`,Le||Xy)for(const o of this.controllers)n+=`
166
+ ${a.href}`)}this.onSendQueued(Zi.OnRoomJoin);break;case"left-room":const n=e;n.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentRoomAllowEditing=!0,this._currentInRoom.length=0,(xh||A())&&console.debug("Left Needle Engine Room: "+n.room));break;case"user-joined-room":if(e.data){const r=e.data;this._currentInRoom.push(r.userId),Nt&&console.log(r.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(e.data){const r=e.data,a=this._currentInRoom.indexOf(r.userId);a>=0&&(Nt&&console.log(r.userId+" left","now in room:",this._currentInRoom),this._currentInRoom.splice(a,1)),r.userId===this.connectionId&&console.log("you left the room")}break;case"all-room-state-deleted":Nt&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":const o=e.data?.time;o&&(this._currentDelay=this.context.time.time-o),Nt&&console.log(`Current latency: ${(this._currentDelay*1e3).toFixed()} ms`,"Clients in room: "+this._currentInRoom?.length);break}const t=e.data;t&&(this._state[t.guid]=t);let i=this._listeners[e.key];if(i){i=[...i];for(const n of i)try{n(e.data)}catch(o){console.error('Error invoking callback for "'+e.key+'"',o)}}}toMessage(e,t){return{key:e,data:t}}sendWithWebsocket(e,t,i=Zi.OnRoomJoin){if(!this._ws){const o=this._waitingForSocket[i]||[];o.push(()=>this.sendWithWebsocket(e,t,i)),this._waitingForSocket[i]=o;return}const n=JSON.stringify(this.toMessage(e,t));Nt&&console.log(">>",e),this._ws.send(n)}onSendQueued(e){const t=this._waitingForSocket[e];if(t){for(const i of t)i();t.length=0}}}const zl=x("debugwebxr");class df{controllerStates=[];userId;context;userStateEvtName;constructor(e,t){this.userId=e,this.context=t,this.userStateEvtName="xr-sync-user-state-"+e,this.context.connection.beginListen(this.userStateEvtName,this.onReceivedControllerState)}dispose(){this.context.connection.stopListen(this.userStateEvtName,this.onReceivedControllerState)}onReceivedControllerState=e=>{zl&&console.log(`XRSync: Received change for ${this.userId}: ${e.type} ${e.handedness}; tracked=${e.isTracking}`);let t=!1;for(let i=0;i<this.controllerStates.length;i++)if(this.controllerStates[i].index===e.index){this.controllerStates[i]=e,t=!0;break}t||this.controllerStates.push(e)};update(e){if(this.context.connection.isConnected!=!1){for(let t=this.controllerStates.length-1;t>=0;t--){const i=this.controllerStates[t];let n=!1;for(let o=0;o<e.controllers.length;o++)e.controllers[o].index===i.index&&(n=!0);n||(zl&&console.log(`XRSync: ${i.type} ${i.handedness} removed`,i.index),this.controllerStates.splice(t,1),this.sendControllerRemoved(i))}for(const t of e.controllers)this.updateControllerStates(t)}}onExitXR(e){for(const t of this.controllerStates)this.sendControllerRemoved(t);this.controllerStates.length=0}sendControllerRemoved(e){e.isTracking=!1,e.guid="",this.context.connection.send(this.userStateEvtName,e),this.context.connection.sendDeleteRemoteState(e.guid)}updateControllerStates(e){const t=this.controllerStates.find(i=>i.index===e.index);if(t){let i=!1;i||=t.isTracking!=e.isTracking,i&&(t.isTracking=e.isTracking,this.context.connection.send(this.userStateEvtName,t))}else{const i={guid:this.userId+"-"+e.index,isTracking:e.isTracking,handedness:e.side,index:e.index,type:e.hand?"hand":"controller"};this.controllerStates.push(i),this.context.connection.send(this.userStateEvtName,i),zl&&console.log(`XRSync: ${i.type} ${i.handedness} added`,i.index)}}}class u0{hasState(e){return e?this._states.has(e):!1}isTracking(e,t){if(!e)return;const i=this._states.get(e);return i?i.controllerStates.find(o=>o.handedness===t)?.isTracking||!1:void 0}getDeviceType(e,t){if(!e)return;const i=this._states.get(e);return i?i.controllerStates.find(o=>o.handedness===t)?.type||"unknown":void 0}context;constructor(e){this.context=e,this.context.connection.beginListen(Q.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Q.LeftRoom,this.onLeftRoom),this.context.connection.beginListen(Q.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.beginListen(Q.UserLeftRoom,this.onOtherUserLeftRoom)}destroy(){this.context.connection.stopListen(Q.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Q.LeftRoom,this.onLeftRoom),this.context.connection.stopListen(Q.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.stopListen(Q.UserLeftRoom,this.onOtherUserLeftRoom)}onJoinedRoom=()=>{if(this.context.connection.connectionId){this._states.has(this.context.connection.connectionId)||(zl&&console.log("XRSync: Local user joined room",this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new df(this.context.connection.connectionId,this.context)));for(const e of this.context.connection.usersInRoom())this._states.has(e)||this._states.set(e,new df(e,this.context))}};onLeftRoom=()=>{this.context.connection.connectionId&&(this._states.has(this.context.connection.connectionId)||(this._states.get(this.context.connection.connectionId)?.dispose(),this._states.delete(this.context.connection.connectionId)))};onOtherUserJoinedRoom=e=>{const t=e.userId;this._states.has(t)||(zl&&console.log("XRSync: Remote user joined room",t),this._states.set(t,new df(t,this.context)))};onOtherUserLeftRoom=e=>{const t=e.userId;this._states.has(t)||(this._states.get(t)?.dispose(),this._states.delete(t))};_states=new Map;onUpdate(e){this.context.connection.isConnected&&this.context.connection.connectionId&&this._states.get(this.context.connection.connectionId)?.update(e)}onExitXR(e){this.context.connection.isConnected&&this.context.connection.connectionId&&this._states.get(this.context.connection.connectionId)?.onExitXR(e)}}class Hy{_fadeToColorQuad;_fadeToColorMaterial;constructor(){this._fadeToColorMaterial=new c.MeshBasicMaterial({color:0,transparent:!0,depthTest:!1,fog:!1,side:c.DoubleSide}),this._fadeToColorQuad=new c.Mesh(new c.PlaneGeometry(10,10),this._fadeToColorMaterial)}dispose(){this._fadeToColorQuad.geometry.dispose(),this._fadeToColorMaterial.dispose()}update(e,t){const i=this._fadeToColorQuad,n=this._fadeToColorMaterial;i.parent!==e&&n.opacity>0?e.add(i):n.opacity===0&&i.removeFromParent(),i.layers.set(2),i.material=this._fadeToColorMaterial,i.position.z=-1,i.renderOrder=1/0;const o=this._requestedFadeValue;n.opacity=L.lerp(n.opacity,o,t/.03),Math.abs(n.opacity-o)<=.01&&this._transitionResolve&&(this._transitionResolve(),this._transitionResolve=null,this._transitionPromise=null,this._requestedFadeValue=0)}remove(){this._fadeToColorQuad.removeFromParent()}fadeTransition(){if(this._transitionPromise)return this._transitionPromise;this._requestedFadeValue=1;const e=new Promise(t=>{this._transitionResolve=t});return this._transitionPromise=e,e}_requestedFadeValue=0;_transitionPromise=null;_transitionResolve=null}var Jo=(s=>(s[s.Quad=0]="Quad",s[s.Cube=1]="Cube",s[s.Sphere=2]="Sphere",s[s.Cylinder=3]="Cylinder",s[s.RoundedCube=10]="RoundedCube",s))(Jo||{});class hr{static createText(e,t){let i=null;const n=t?.font||XS(t?.familyFamily||null);n instanceof q.Font?i=this.#t(e,n,t):i==null&&(i=new c.BufferGeometry);const o=t?.color||16777215,r=new c.Mesh(i,t?.material??new c.MeshStandardMaterial({color:o}));return this.applyDefaultObjectOptions(r,t),n instanceof Promise?n.then(a=>{r.geometry=this.#t(e,a,t),t?.onGeometry&&t.onGeometry(r)}):t?.onGeometry&&t.onGeometry(r),r}static#t(e,t,i){const n=i?.depth||.1;return new q.TextGeometry(e,{font:t,size:1,depth:n,height:n,bevelEnabled:i?.bevel||!1,bevelThickness:.01,bevelOffset:.01,bevelSize:.01})}static createOccluder(e){const t=new c.MeshBasicMaterial({colorWrite:!1,depthWrite:!0,side:c.DoubleSide});return this.createPrimitive(e,{material:t})}static createPrimitive(e,t){let i;const n=t?.color||16777215;switch(e){case"Quad":case 0:{const o=new c.PlaneGeometry(1,1,1,1),r=t?.material??new c.MeshStandardMaterial({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new c.Mesh(o,r),i.name="Quad"}break;case"Cube":case 1:{const o=new c.BoxGeometry(1,1,1),r=t?.material??new c.MeshStandardMaterial({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new c.Mesh(o,r),i.name="Cube"}break;case 10:case"RoundedCube":{const o=qS(1,1,1,.1,2),r=t?.material??new c.MeshStandardMaterial({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new c.Mesh(o,r),i.name="RoundedCube"}break;case"Sphere":case 2:{const o=new c.SphereGeometry(.5,16,16),r=t?.material??new c.MeshStandardMaterial({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new c.Mesh(o,r),i.name="Sphere"}break;case"Cylinder":case 3:{const o=new c.CylinderGeometry(.5,.5,1,32),r=t?.material??new c.MeshStandardMaterial({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new c.Mesh(o,r),i.name="Cylinder"}break;case"ShaderBall":i=new c.Group,i.name="ShaderBall",QS(i,t);break}return this.applyDefaultObjectOptions(i,t),i}static createSprite(e){const i=new c.SpriteMaterial({color:16777215});e?.texture&&"map"in i&&(i.map=e.texture);const n=new c.Sprite(i);return this.applyDefaultObjectOptions(n,e),n}static applyDefaultObjectOptions(e,t){e.receiveShadow=!0,e.castShadow=!0,t?.name&&(e.name=t.name),t?.position&&(Array.isArray(t.position)?e.position.set(t.position[0],t.position[1],t.position[2]):e.position.set(t.position.x||0,t.position.y||0,t.position.z||0)),t?.rotation&&(Array.isArray(t.rotation)?e.rotation.set(t.rotation[0],t.rotation[1],t.rotation[2]):e.rotation.set(t.rotation.x||0,t.rotation.y||0,t.rotation.z||0)),t?.scale&&(typeof t.scale=="number"?e.scale.set(t.scale,t.scale,t.scale):Array.isArray(t.scale)?e.scale.set(t.scale[0],t.scale[1],t.scale[2]):e.scale.set(t.scale.x||1,t.scale.y||1,t.scale.z||1)),t?.receiveShadow!=null&&(e.receiveShadow=t.receiveShadow),t?.castShadow!=null&&(e.castShadow=t.castShadow),t?.parent&&t.parent.add(e)}}function qS(s,e,t,i,n){const o=new c.Shape,r=1e-5,a=i-r;o.absarc(r,r,r,-Math.PI/2,-Math.PI,!0),o.absarc(r,e-a*2,r,Math.PI,Math.PI/2,!0),o.absarc(s-a*2,e-a*2,r,Math.PI/2,0,!0),o.absarc(s-a*2,r,r,0,-Math.PI/2,!0);const l=new c.ExtrudeGeometry(o,{bevelEnabled:!0,bevelSegments:n*2,steps:1,bevelSize:a,bevelThickness:i,curveSegments:n,UVGenerator:{generateTopUV:(h,d)=>{const u=[];for(let p=0;p<d.length;p+=3)u.push(new c.Vector2(d[p]/s,d[p+1]/e));return u},generateSideWallUV:(h,d,u,p,m,y)=>{const _=[];return _.push(new c.Vector2(d[u]/s,d[u+1]/e)),_.push(new c.Vector2(d[p]/s,d[p+1]/e)),_.push(new c.Vector2(d[m]/s,d[m+1]/e)),_.push(new c.Vector2(d[y]/s,d[y+1]/e)),_}}});return l.scale(1,1,1-i),l.center(),l.index||l.setIndex(Array.from({length:l.attributes.position.count},(h,d)=>d)),l.computeVertexNormals(),l}const Sh=new Map;function XS(s){let e="";switch(s){default:case"OpenSans":e="https://cdn.needle.tools/static/fonts/facetype/Open Sans_Regular_ascii.json";break;case"Helvetiker":e="https://raw.githubusercontent.com/mrdoob/three.js/master/examples/fonts/helvetiker_regular.typeface.json";break}if(Sh.has(e)){const n=Sh.get(e);if(n)return n}const t=new q.FontLoader,i=new Promise((n,o)=>{t.load(e,r=>{Sh.set(e,r),n(r)},void 0,o)});return Sh.set(e,i),i}let uf=!1,ff=null;function QS(s,e){if(ff===null){const t="https://cdn.needle.tools/static/models/shaderball.glb",i=new q.GLTFLoader,n=ne.createLoaders(null);i.setDRACOLoader(n.dracoLoader),i.setKTX2Loader(n.ktx2Loader),uf=!0,ff=i.loadAsync(t).then(o=>{const r=o.scene;return r.position.y-=.5,r}).catch(o=>(console.warn("Failed to load shaderball mesh: "+o.message),qy())).finally(()=>{uf=!1})}if(uf){const t=qy();t.name="ShaderBall-Placeholder";const i=t.children[0];i?.type==="Mesh"&&Gy(i,e),s.add(t)}ff.then(t=>{s.children.forEach(o=>{o.name==="ShaderBall-Placeholder"&&s.remove(o)});const i=t.clone(),n=i.children[0];n?.type==="Mesh"&&(n.geometry.attributes.tangent||n.geometry.computeTangents(),Gy(n,e)),s.add(i)})}function Gy(s,e){if(e?.color||e?.material||e?.texture){const i=e?.material??s.material?.clone()??new c.MeshStandardMaterial;e.color&&"color"in i&&i.color instanceof c.Color&&i.color.set(e.color),e?.texture&&"map"in i&&(i.map=e.texture),s.material=i}}function qy(){return new c.Group().add(hr.createPrimitive("Sphere",{material:new c.MeshBasicMaterial({transparent:!0,opacity:.1})}))}class ba{static _active=null;static get active(){return this._active}static _requestInFlight=!1;static async start(e,t){if(this._active)return console.error("Cannot start a new XR session while one is already active"),null;if(this._requestInFlight)return console.error("Cannot start a new XR session while a request is already in flight"),null;if("xr"in navigator&&navigator.xr){if(!t)return console.error("XRSessionInit must be provided"),null;this._requestInFlight=!0;const i=await navigator.xr.requestSession(e,t);return i.addEventListener("end",()=>{this._active=null}),this._requestInFlight?(this._requestInFlight=!1,this._active=new ba(e,t,i),this._active):(i.end(),null)}return null}static async handoff(){return this._active?this._active.handoff():null}static async stop(){this._requestInFlight=!1,this._active&&(await this._active.end(),await Bn(100)),this._active=null}_session;_mode;_init;get isAR(){return this._mode==="immersive-ar"}_renderer;_camera;_scene;constructor(e,t,i){this._mode=e,this._init=t,this._session=i,this._session.addEventListener("end",this.onEnd),this._renderer=new c.WebGLRenderer({alpha:!0}),this._renderer.setAnimationLoop(this.onFrame),this._renderer.xr.setSession(i),this._renderer.xr.enabled=!0,this._camera=new c.PerspectiveCamera,this._scene=new c.Scene,this._scene.fog=new c.Fog(4473924,10,250),this._scene.add(this._camera),this.setupScene()}end(){return this._session?this._session.end():Promise.resolve()}async handoff(){if(!this._session)throw new Error("Cannot handoff a session that has already ended");const e={session:this._session,mode:this._mode,init:this._init};return await this.onBeforeHandoff(),this.onEnd(),this._session=null,e}onEnd=()=>{this._session?.removeEventListener("end",this.onEnd),this._renderer.setAnimationLoop(null),this._renderer.dispose(),this._scene.clear()};_lastTime=0;onFrame=(e,t)=>{const i=e-this._lastTime;this.update(e,i),this._camera.parent!==this._scene&&this._scene.add(this._camera),this._renderer.render(this._scene,this._camera)};async onBeforeHandoff(){await Bn(1e3),this._scene.clear()}_objects=[];setupScene(){this._scene.background=new c.Color(0),this._scene.add(new c.GridHelper(5,10,1118481,1118481));const e=new c.DirectionalLight(16777215,1);e.position.set(0,20,0),e.castShadow=!1,this._scene.add(e);const t=new c.DirectionalLight(16777215,1);t.position.set(0,-1,0),t.castShadow=!1,this._scene.add(t);const i=new c.PointLight(16777215,1,100,1);i.position.set(0,2,0),i.castShadow=!1,i.distance=200,this._scene.add(i);const n=50;for(let o=0;o<100;o++){const r=new c.MeshStandardMaterial({color:2236962,metalness:1,roughness:.8});this.isAR&&(r.emissive=new c.Color(Math.random(),Math.random(),Math.random()),r.emissiveIntensity=Math.random());const a=L.random(0,1)>.5?Jo.Sphere:Jo.Cube,l=hr.createPrimitive(a,{material:r});l.position.x=L.random(-n,n),l.position.y=L.random(-2,n),l.position.z=L.random(-n,n),l.rotation.x=L.random(0,Math.PI*2),l.rotation.y=L.random(0,Math.PI*2),l.rotation.z=L.random(0,Math.PI*2),l.scale.multiplyScalar(.5+Math.random()*10);const h=l.position.distanceTo(this._camera.position)-l.scale.x;h<1&&l.position.multiplyScalar(1+1/h),this._objects.push(l),this._scene.add(l)}}update(e,t){const i=e*4e-4;for(let n=0;n<this._objects.length;n++){const o=this._objects[n];o.position.y+=Math.sin(i+n*.5)*.005,o.rotateY(.002)}}}var ic;(s=>{const e=[];function t(){if(!e?.length)return!1;for(const o of e)o.exportAndOpen();return!0}s.exportAndOpen=t;function i(o){e.push(o)}s.registerExporter=i;function n(o){if(!e)return;const r=e.indexOf(o);r>=0&&e.splice(r,1)}s.unregisterExporter=n})(ic||(ic={}));const Le=x("debugwebxr"),Xy=x("stats");let pf=0;function YS(s){let e=null;const t=s;return t.getAROverlayContainer?e=t.getAROverlayContainer():e=s,e}KS();async function KS(){if(x("debugasap")){let s=globalThis["needle:XRSession"];if(s instanceof Promise){delete globalThis["needle:XRSession"],ae.addContextCreatedCallback(async e=>{if(!s)return;No(!0);const t=await s;if(t){const i=G.getDefaultSessionInit("immersive-vr");G.setSession("immersive-vr",t,i,e.context)}else console.error("NeedleXRSession: ASAP session was rejected");s=void 0});return}}if("xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent)){console.warn("WebXRViewer does not support addEventListener");return}navigator.xr?.addEventListener("sessiongranted",async()=>{No(!0),console.log("Received Session Granted..."),await Bn(100);const s=sessionStorage.getItem("needle_xr_session_mode"),e=sessionStorage.getItem("needle_xr_session_init")??null,t=e?JSON.parse(e):null;let i=null;if(f0()&&(await ba.start(s||"immersive-vr",t||G.getDefaultSessionInit("immersive-vr")),await eC(),i=await ba.handoff()),i)G.setSession(i.mode,i.session,i.init,N.Current);else if(s&&e){console.log("Session Granted: Restore last session");const n=JSON.parse(e);G.start(s,n).catch(o=>console.warn(o))}else G.start("immersive-vr").catch(n=>console.warn("Session Granted failed:",n))},{once:!0})}}function ZS(s,e){sessionStorage.setItem("needle_xr_session_mode",s),sessionStorage.setItem("needle_xr_session_init",JSON.stringify(e))}function JS(){sessionStorage.removeItem("needle_xr_session_mode"),sessionStorage.removeItem("needle_xr_session_init")}const Am=new Set;ae.registerCallback(re.ContextCreationStart,async s=>{Am.add(s.context)});ae.registerCallback(re.ContextCreated,async s=>{Am.delete(s.context);const e=s.context?.domElement.getAttribute("autostart")||null;tC(e)});function f0(){return Am.size>0}function eC(){return new Promise(s=>{const e=Date.now(),t=setInterval(()=>{(!f0()||Date.now()-e>6e4)&&(clearInterval(t),s())},100)})}exports.DeviceUtilities.isDesktop()&&A()&&window.addEventListener("keydown",s=>{(s.key==="x"||s.key==="Escape")&&G.active&&G.stop()});function tC(s){if(s)switch(s?.toLowerCase()){case"ar":an.registerWaitForInteraction(()=>{G.start("ar")});break}}const Ch=Symbol("initial-fov");class G{static _sync=null;static getXRSync(e){return this._sync||(this._sync=new u0(e)),this._sync}static get currentSessionRequest(){return this._currentSessionRequestMode}static _currentSessionRequestMode=null;static get active(){return this._activeSession}static get activeMode(){return this._activeSession?.mode??null}static get xrSystem(){return"xr"in navigator?navigator.xr:void 0}static isXRSupported(){return Promise.all([this.isVRSupported(),this.isARSupported()]).then(e=>e.some(t=>t)).catch(()=>!1)}static isVRSupported(){return this.isSessionSupported("immersive-vr")}static isARSupported(){return this.isSessionSupported("immersive-ar")}static isSessionSupported(e){return this.xrSystem?.isSessionSupported(e).catch(t=>(Le&&console.error(t),!1))??Promise.resolve(!1)}static _currentSessionRequest;static _activeSession;static onSessionRequestStart(e){this._sessionRequestStartListeners.push(e)}static offSessionRequestStart(e){const t=this._sessionRequestStartListeners.indexOf(e);t>=0&&this._sessionRequestStartListeners.splice(t,1)}static _sessionRequestStartListeners=[];static onSessionRequestEnd(e){this._sessionRequestEndListeners.push(e)}static offSessionRequestEnd(e){const t=this._sessionRequestEndListeners.indexOf(e);t>=0&&this._sessionRequestEndListeners.splice(t,1)}static _sessionRequestEndListeners=[];static onXRSessionStart(e){this._xrStartListeners.push(e)}static offXRSessionStart(e){const t=this._xrStartListeners.indexOf(e);t>=0&&this._xrStartListeners.splice(t,1)}static _xrStartListeners=[];static onXRSessionEnd(e){this._xrEndListeners.push(e)}static offXRSessionEnd(e){const t=this._xrEndListeners.indexOf(e);t>=0&&this._xrEndListeners.splice(t,1)}static _xrEndListeners=[];static onControllerAdded(e){this._controllerAddedListeners.push(e)}static offControllerAdded(e){const t=this._controllerAddedListeners.indexOf(e);t>=0&&this._controllerAddedListeners.splice(t,1)}static _controllerAddedListeners=[];static onControllerRemoved(e){this._controllerRemovedListeners.push(e)}static offControllerRemoved(e){const t=this._controllerRemovedListeners.indexOf(e);t>=0&&this._controllerRemovedListeners.splice(t,1)}static _controllerRemovedListeners=[];static offerSession(e,t,i){return"xr"in navigator&&navigator.xr&&"offerSession"in navigator.xr?(typeof navigator.xr.offerSession=="function"&&(console.log("WebXR offerSession is available - requesting mode: "+e),t=="default"&&(t=this.getDefaultSessionInit(e)),navigator.xr.offerSession(e,{...t}).then(n=>G.setSession(e,n,t,i)).catch(n=>{console.log("XRSession offer rejected (perhaps because another call to offerSession was made or a call to requestSession was made)")})),!0):!1}static getDefaultSessionInit(e){switch(e){case"immersive-ar":const t=["anchors","local-floor","layers","dom-overlay","hit-test","unbounded"];return exports.DeviceUtilities.isVisionOS()||t.push("hand-tracking"),{optionalFeatures:t};case"immersive-vr":const i=["local-floor","bounded-floor","high-fixed-foveation-level","layers"];return exports.DeviceUtilities.isVisionOS()||i.push("hand-tracking"),{optionalFeatures:i};default:return console.warn("No default session init for mode",e),{}}}static async start(e,t,i){if(exports.DeviceUtilities.isiOS()){if(e==="ar")if(await this.isARSupported())e="immersive-ar";else return ic.exportAndOpen(),null}else e=="ar"&&(e="immersive-ar");if(A()&&x("debugxrpreroom"))return console.warn("Debug: Starting temporary XR session"),await ba.start(e,t||G.getDefaultSessionInit(e)),null;if(this._currentSessionRequest)return console.warn("A XRSession is already being requested"),(Le||A())&&de("A XRSession is already being requested"),this._currentSessionRequest.then(()=>this._activeSession);if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;if(i||(i=N.Current),i||(i=ae.All[0]),!i)throw new Error("No Needle Engine Context found");switch(t||(t={}),e){case"immersive-ar":{if(await this.xrSystem?.isSessionSupported("immersive-ar")!==!0)return console.error(e+" is not supported by this browser."),null;const l=this.getDefaultSessionInit(e),h=YS(i.domElement);h&&!exports.DeviceUtilities.isQuest()&&(l.domOverlay={root:h},l.optionalFeatures.push("dom-overlay")),t={...l,...t}}break;case"immersive-vr":{if(await this.xrSystem?.isSessionSupported("immersive-vr")!==!0)return console.error(e+" is not supported by this browser."),null;t={...this.getDefaultSessionInit(e),...t}}break;default:console.warn("No default session init for mode",e);break}t.optionalFeatures??=[],t.requiredFeatures??=[],await ba.stop();const n=e=="immersive-ar"?i.scripts_immersive_ar:i.scripts_immersive_vr;Le?console.log(`%cRequesting ${e} session`,"font-weight:bold;",t,n):console.log(`%cRequesting ${e} session`,"font-weight:bold;");for(const a of n)a.onBeforeXR&&a.activeAndEnabled&&!a.destroyed&&a.onBeforeXR(e,t);for(const a of this._sessionRequestStartListeners)a({mode:e,init:t});Le&&Ce("Requesting "+e+" session ("+Date.now()+")"),this._currentSessionRequest=navigator?.xr?.requestSession(e,t),this._currentSessionRequestMode=e;const o=await this._currentSessionRequest?.catch(a=>{console.error(a,"Code: "+a.code),a.code===9&&de("Make sure your device has the required permissions (e.g. camera access)"),console.log("If the specified XR configuration is not supported (e.g. entering AR doesnt work) - make sure you access the website on a secure connection (HTTPS) and your device has the required permissions (e.g. camera access)"),location.protocol==="http:"&&de("XR requires a secure connection (HTTPS)")});this._currentSessionRequest=void 0,this._currentSessionRequestMode=null;for(const a of this._sessionRequestEndListeners)a({mode:e,init:t,newSession:o||null});return o?this.setSession(e,o,t,i):(console.warn("XR Session request was rejected"),null)}static setSession(e,t,i,n){if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;const o=e=="immersive-ar"?n.scripts_immersive_ar:n.scripts_immersive_vr;return this._activeSession=new G(e,t,n,{scripts:o,controller_added:this._controllerAddedListeners,controller_removed:this._controllerRemovedListeners,init:i}),t.addEventListener("end",this.onEnd),Le?console.log(`%cStarted ${e} session`,"font-weight:bold;",o):console.log(`%cStarted ${e} session`,"font-weight:bold;"),this._activeSession}static $_stop_request=Symbol();static stop(){const e=this._activeSession;e&&(e[this.$_stop_request]===void 0?(Le&&console.log("[NeedleXRSession] Stopping XR Session... (new)"),e[this.$_stop_request]=setTimeout(()=>{e.end()})):Le&&console.warn("[NeedleXRSession] XR Session stop already requested"))}static onEnd=()=>{Le&&console.log("XR Session ended"),this._activeSession=null};context;get sync(){return G._sync}get running(){return!this._ended&&this.session!=null}session;mode;get interactionMode(){return this.session.interactionMode}get visibilityState(){return this.session.visibilityState}get isVisibleBlurred(){return this.session.visibilityState==="visible-blurred"}get isSystemKeyboardSupported(){return this.session.isSystemKeyboardSupported}get environmentBlendMode(){return this.session.environmentBlendMode}get frame(){return this.context.xrFrame}controllers=[];get leftController(){return this.controllers.find(e=>e.side==="left")}get rightController(){return this.controllers.find(e=>e.side==="right")}getController(e){return typeof e=="number"?this.controllers[e]||null:this.controllers.find(t=>t.side===e)||null}get isPassThrough(){return!!(this.environmentBlendMode!=="opaque"&&this.interactionMode==="world-space"||this.mode==="immersive-ar"&&this.environmentBlendMode!=="opaque"&&this.controllers.some(e=>e.inputSource.targetRayMode==="tracked-pointer")||A()&&exports.DeviceUtilities.isDesktop()&&this.mode==="immersive-ar")}get isAR(){return this.mode==="immersive-ar"}get isVR(){return this.mode==="immersive-vr"}get isScreenBasedAR(){return this.isAR&&!this.isPassThrough}get posePosition(){return this._transformPosition}get poseOrientation(){return this._transformOrientation}get referenceSpace(){return this.context.renderer.xr.getReferenceSpace()}get viewerPose(){return this._viewerPose}get isTrackingImages(){if(this.frame&&"getImageTrackingResults"in this.frame&&typeof this.frame.getImageTrackingResults=="function")try{const e=this.frame.getImageTrackingResults();for(const t of e)if(t.trackingState==="tracked")return!0}catch{return!1}return!1}get rig(){const e=this._rigs[0]??null;return e?.gameObject&&er(e.gameObject)||e?.isActive===!1?(this.updateActiveXRRig(),this._rigs[0]??null):e}_rigScale=1;_lastRigScaleUpdate=-1;get rigScale(){return this._rigs[0]?(this._lastRigScaleUpdate!==this.context.time.frame&&(this._lastRigScaleUpdate=this.context.time.frame,this._rigScale=this._rigs[0].gameObject.worldScale.x),this._rigScale):1}addRig(e){this._rigs.indexOf(e)>=0||(e.priority===void 0&&(e.priority=0),this._rigs.push(e),this.updateActiveXRRig())}removeRig(e){const t=this._rigs.indexOf(e);t!==-1&&(this._rigs.splice(t,1),this.updateActiveXRRig())}setRigActive(e){const t=this._rigs.indexOf(e),i=this._rigs[0];this._rigs.splice(t,1),this._rigs.unshift(e),e.priority=i?.priority??0,this.updateActiveXRRig()}getUserOffsetInRig(){const e=this.context.mainCamera?.position;if(!e||!this.rig)return j(0,0,0);const t=j(e);return t.x*=-1,t.z*=-1,t.applyQuaternion(qt(this.rig.gameObject.quaternion)),t}updateActiveXRRig(){const e=this._rigs[0]??null;this._defaultRig.gameObject.parent!==this.context.scene&&this.context.scene.add(this._defaultRig.gameObject),this._defaultRig.gameObject.visible=!0,this._rigs.includes(this._defaultRig)||this._rigs.push(this._defaultRig);let t=this._rigs[0];t&&t.priority===void 0&&(t.priority=0);for(let i=1;i<this._rigs.length;i++){const n=this._rigs[i];if(n.isActive){if(er(n.gameObject)){this._rigs.splice(i,1),i--;continue}(!t||t.isActive===!1||n.priority!==void 0&&n.priority>t.priority)&&(t=n)}}if(e!==t){const i=this._rigs.indexOf(t);i>=0&&this._rigs.splice(i,1),this._rigs.unshift(t)}Le&&(e===t?console.log("Updated Active XR Rig:",t,"prev:",e):console.log("Updated Active XRRig:",t," (the same as before)"))}_rigs=[];_viewerHitTestSource=null;getHitTest(e){if(e)return this.getControllerHitTest(e);if(!this._viewerHitTestSource)return null;const t=this._viewerHitTestSource,i=this.frame.getHitTestResults(t);if(i.length>0){const n=i[0];return this.convertHitTestResult(n)}return null}getControllerHitTest(e){const t=e.getHitTestSource();if(!t)return null;const i=this.frame.getHitTestResultsForTransientInput(t);for(const n of i)if(n.inputSource===e.inputSource)for(const o of n.results)return this.convertHitTestResult(o);return null}convertHitTestResult(e){const t=this.context.renderer.xr.getReferenceSpace(),i=t&&e.getPose(t);if(i){const n=j(i.transform.position),o=qt(i.transform.orientation),r=this.context.mainCamera;if(r?.parent!==this._cameraRenderParent&&n.applyMatrix4(aa),r?.parent){n.applyMatrix4(r.parent.matrixWorld),o.multiply(ki);const a=ue(r.parent);a.premultiply(ki),o.premultiply(a)}return{hit:e,position:n,quaternion:o}}return null}convertSpace(e){const t=j(e.position);t.applyMatrix4(aa);const i=qt(e.orientation);return i.premultiply(ki),{position:t,quaternion:i}}_defaultRig;_xr_scripts;_xr_update_scripts=[];_inactive_scripts=[];_controllerAdded;_controllerRemoved;_originalCameraWorldPosition;_originalCameraWorldRotation;_originalCameraWorldScale;_originalCameraParent;_mainCamera=null;constructor(e,t,i,n){ZS(e,n.init),this.session=t,this.mode=e,this.context=i,(Le||x("console"))&&No(!0),this._xr_scripts=[...n.scripts],this._xr_update_scripts=this._xr_scripts.filter(o=>typeof o.onUpdateXR=="function"),this._controllerAdded=n.controller_added,this._controllerRemoved=n.controller_removed,us(this.onBefore,pe.LateUpdate),this.context.pre_render_callbacks.push(this.onBeforeRender),this.context.post_render_callbacks.push(this.onAfterRender),(n.init.optionalFeatures?.includes("hit-test")||n.init.requiredFeatures?.includes("hit-test"))&&t.requestReferenceSpace("viewer").then(o=>t.requestHitTestSource?.call(t,{space:o})?.then(r=>this._viewerHitTestSource=r).catch(r=>console.error(r))).catch(o=>console.error(o)),this.context.mainCamera&&(this._originalCameraWorldPosition=X(this.context.mainCamera,new c.Vector3),this._originalCameraWorldRotation=ue(this.context.mainCamera,new c.Quaternion),this._originalCameraWorldScale=je(this.context.mainCamera,new c.Vector3),this._originalCameraParent=this.context.mainCamera.parent,this.context.mainCamera instanceof c.PerspectiveCamera&&(this.context.mainCamera[Ch]=this.context.mainCamera.fov)),this._defaultRig=new IS,this.context.scene.add(this._defaultRig.gameObject),this.addRig(this._defaultRig);for(let o=0;o<t.inputSources.length;o++){const r=t.inputSources[o];if(!r.handedness){console.warn("Input source in xr session has no handedness - ignoring",o);continue}this.onInputSourceAdded(r)}this.session.addEventListener("end",this.onEnd),this.session.addEventListener("inputsourceschange",o=>{for(const r of o.removed)this.disconnectInputSource(r);for(const r of o.added)this.onInputSourceAdded(r)}),this.context.xr=this,this.context.renderer.xr.setSession(this.session).then(this.onRendererSessionSet),"controllerAutoUpdate"in this.context.renderer.xr?(console.debug("Disabling three.js controllerAutoUpdate"),this.context.renderer.xr.controllerAutoUpdate=!1):Le&&console.warn("controllerAutoUpdate is not available in three.js - cannot disable it")}onRendererSessionSet=()=>{this.running&&(this.context.renderer.xr.enabled=!0,this.context.renderer.xr.updateCamera(this.context.mainCamera),this.context.mainCameraComponent?.applyClearFlags())};onInputSourceAdded=e=>{if(e.targetRayMode==="screen")return;let t=0;for(let n=0;n<this.session.inputSources.length;n++)if(this.session.inputSources[n]===e){t=n;break}if(this.controllers.find(n=>n.inputSource===e)){console.debug("Controller already exists for input source",t);return}else if(this._newControllers.find(n=>n.inputSource===e)){console.debug("Controller already registered for input source",t);return}const i=new Mm(this,e,t);this._newControllers.push(i)};disconnectInputSource(e){const t=(o,r)=>{if(o.inputSource===e){Le&&console.log("Disconnecting controller",o.index);const a=r.indexOf(o);a>=0&&r.splice(a,1),this.invokeControllerEvent(o,this._controllerRemoved,"removed");const l={xr:this,controller:o,change:"removed"};for(const h of this._xr_scripts)h.onXRControllerRemoved&&h.onXRControllerRemoved(l);o.onDisconnected()}},i=[...this.controllers];for(let o=i.length-1;o>=0;o--){const r=i[o];t(r,this.controllers)}const n=[...this._newControllers];for(let o=n.length-1;o>=0;o--){const r=n[o];t(r,this._newControllers)}}end(){this._ended||this.session.end().catch(e=>console.warn(e))}_ended=!1;_newControllers=[];onEnd=e=>{if(this._ended)return;this._ended=!0,console.debug("XR Session ended"),JS(),this.onAfterRender(),this.revertCustomForward(),this._didStart=!1,this._previousCameraParent=null,this.requestedCameraNearPlane=null,ao(this.onBefore,pe.LateUpdate);const t=this.context.pre_render_callbacks.indexOf(this.onBeforeRender);t>=0&&this.context.pre_render_callbacks.splice(t,1);const i=this.context.post_render_callbacks.indexOf(this.onAfterRender);i>=0&&this.context.post_render_callbacks.splice(i,1),this.context.xr=null,this.context.renderer.xr.enabled=!1,this.context.pre_update_oneshot_callbacks.push(()=>{this.context.mainCameraComponent?.applyClearFlags(),this.context.mainCameraComponent?.applyClippingPlane()}),i0({session:this});for(const o of G._xrEndListeners)o({xr:this});const n=[...this.controllers];for(let o=0;o<n.length;o++)this.disconnectInputSource(n[o].inputSource);this.controllers.length=0,this._newControllers.length=0;for(const o of this._xr_scripts)o?.onLeaveXR?.({xr:this});this.sync?.onExitXR(this),this.context.mainCamera&&(this._originalCameraParent?.add(this.context.mainCamera),this._originalCameraWorldPosition&&ot(this.context.mainCamera,this._originalCameraWorldPosition),this._originalCameraWorldRotation&&on(this.context.mainCamera,this._originalCameraWorldRotation),this._originalCameraWorldScale&&ga(this.context.mainCamera,this._originalCameraWorldScale),this.context.mainCamera instanceof c.PerspectiveCamera&&this.context.mainCamera[Ch]&&(this.context.mainCamera.fov=this.context.mainCamera[Ch],this.context.mainCamera[Ch]=0)),this.context.requestSizeUpdate(),this._defaultRig.gameObject.removeFromParent(),No(!1)};_didStart=!1;onBefore=e=>{const t=e.xrFrame;if(!t)return;this.context.xr=this,this.context.mainCameraComponent&&this.context.mainCameraComponent!==this._mainCamera&&(this._mainCamera=this.context.mainCameraComponent),this.rig?.isActive==!1&&(Le&&console.warn("Latest rig is not active - trying to activate a different rig",this.rig),this.updateActiveXRRig()),this.rig&&this._mainCamera?.gameObject&&this._mainCamera?.gameObject?.parent!==this.rig.gameObject&&this.rig.gameObject.add(this._mainCamera?.gameObject),this.internalUpdateState(),this.applyCustomForward();const i={xr:this};if(this._didStart){if(this.context.new_scripts_xr.length>0){const n=[...this.context.new_scripts_xr];for(let o=0;o<n.length;o++){const r=this.context.new_scripts_xr[o];if(!r||r.destroyed||r.supportsXR?.(this.mode)==!1){this.context.new_scripts_xr.splice(o,1);continue}if(!r.activeAndEnabled){this.context.new_scripts_xr.splice(o,1),this.markInactive(r);continue}if(this.addScript(r)){this.invokeCallback_EnterXR(r);for(const a of this.controllers)this.invokeCallback_ControllerAdded(r,a)}}}}else{if(this._didStart=!0,this.mode==="immersive-vr"){const o=Ft(this.context.scene.children);if(o){const r=o.getSize(j());if(r.length()>0){const a=this._defaultRig.gameObject;a.position.set(o.min.x+r.x*.5,o.min.y,o.max.z+r.z*.5+1.5);const l=o.getCenter(j());l.y=a.position.y,a.lookAt(l)}}}t0({session:this}),cr();for(const o of G._xrStartListeners)o(i);const n=[...this._xr_scripts];Le&&console.log("NeedleXRSession start, handle scripts:",n);for(const o of n){if(o.destroyed){this._script_to_remove.push(o);continue}if(!o.activeAndEnabled){this.markInactive(o);continue}this.invokeCallback_EnterXR(o);for(const r of this.controllers)this.invokeCallback_ControllerAdded(o,r)}}this.syncCameraCullingMask();for(const n of this.controllers)n.onUpdate(t);if(this._newControllers.length>0){const n=[...this._newControllers];this._newControllers.length=0;for(const o of n){if(!o.connected){console.warn("New controller is not connected",o);continue}this.controllers.push(o);for(const r of this._xr_scripts){if(r.destroyed){this._script_to_remove.push(r);continue}r.activeAndEnabled!==!1&&this.invokeCallback_ControllerAdded(r,o)}}this.controllers.sort((o,r)=>o.index-r.index)}Le&&this.context.time.frame%30===0&&this.controllers.length<=0&&this.session.inputSources.length>0&&(No(!0),console.error("XRControllers are not added but inputSources are present"));for(const n of this._xr_update_scripts){if(n.destroyed===!0){this._script_to_remove.push(n);continue}if(n.activeAndEnabled===!1){this.markInactive(n);continue}n.onUpdateXR&&n.onUpdateXR(i)}if(this.handleInactiveScripts(),this._script_to_remove.length>0){const n=[...new Set(this._script_to_remove)];this._script_to_remove.length=0;for(const o of n)!o.destroyed&&this.running&&o.onLeaveXR?.(i),this.removeScript(o)}this.sync?.onUpdate(this),this.onRenderDebug()};onRenderDebug(){if(Le)for(const e of this.controllers)e.onRenderDebug();if((Le||Xy)&&this.rig&&(pf++,pf>=20)){const e=this.rig.gameObject.worldPosition,t=this.rig.gameObject.worldForward;e.add(t.multiplyScalar(1.5));const i=this.rig.gameObject.worldUp;e.add(i.multiplyScalar(2.5));let n="";if(n+=`${this.context.time.smoothedFps.toFixed(0)} FPS`,n+=`, calls: ${this.context.renderer.info.render.calls}, tris: ${this.context.renderer.info.render.triangles.toLocaleString()}`,Le||Xy)for(const o of this.controllers)n+=`
167
167
  ${o.hand?"hand":"ctrl"} ${o.inputSource.handedness}[${o.index}] con:${o.connected} tr:${o.isTracking} hts:${o.hasHitTestSource?"yes":"no"}`;pf=0,B.DrawLabel(e,n,void 0,1/60*20)}}onBeforeRender=()=>{this.context.mainCamera&&(this.updateFade(this.context.mainCamera),this.requestedCameraNearPlane!==null&&this.context.mainCamera instanceof c.PerspectiveCamera&&(this.context.mainCamera.near=this.requestedCameraNearPlane,this.requestedCameraNearPlane=null))};onAfterRender=()=>{if(this.onUpdateFade_PostRender(),exports.DeviceUtilities.isDesktop()||!this._renderOnceOnDevice){const e=this.context.renderer;if(e.xr.isPresenting&&this.context.mainCamera){this._renderOnceOnDevice=!0;const t=e.xr.enabled,i=e.getRenderTarget(),n=this.context.scene.background;e.xr.enabled=!1,e.setRenderTarget(null),this.isPassThrough&&(this.context.scene.background=null),this.context.composer?this.context.composer.render(this.context.time.deltaTime):e.render(this.context.scene,this.context.mainCamera),e.xr.enabled=t,e.setRenderTarget(i),this.context.scene.background=n}}};addScript(e){return this._xr_scripts.includes(e)?!1:(Le&&console.log("Register new XRScript",e),this._xr_scripts.push(e),typeof e.onUpdateXR=="function"&&this._xr_update_scripts.push(e),!0)}markInactive(e){if(!(this._inactive_scripts.indexOf(e)>=0)){this.removeScript(e,!1),this._inactive_scripts.push(e);for(const t of this.controllers)this.invokeCallback_ControllerRemoved(e,t);this.invokeCallback_LeaveXR(e)}}handleInactiveScripts(){if(this._inactive_scripts.length>0)for(let e=this._inactive_scripts.length-1;e>=0;e--){const t=this._inactive_scripts[e];if(t.activeAndEnabled){this._inactive_scripts.splice(e,1),this.addScript(t),this.invokeCallback_EnterXR(t);for(const i of this.controllers)this.invokeCallback_ControllerAdded(t,i)}}}_script_to_remove=[];removeScript(e,t=!0){Le&&console.log("Remove XRScript",e);const i=this._xr_scripts.indexOf(e);i>=0&&this._xr_scripts.splice(i,1);const n=this._xr_update_scripts.indexOf(e);if(n>=0&&this._xr_update_scripts.splice(n,1),t){const o=this._inactive_scripts.indexOf(e);o>=0&&this._inactive_scripts.splice(o,1)}}invokeCallback_EnterXR(e){e.onEnterXR&&e.onEnterXR({xr:this})}invokeCallback_ControllerAdded(e,t){e.onXRControllerAdded&&e.onXRControllerAdded({xr:this,controller:t,change:"added"})}invokeCallback_ControllerRemoved(e,t){e.onXRControllerRemoved&&e.onXRControllerRemoved({xr:this,controller:t,change:"removed"})}invokeCallback_LeaveXR(e){e.onLeaveXR&&!e.destroyed&&e.onLeaveXR({xr:this})}syncCameraCullingMask(){const e=this.context.xrCamera,t=this.context.mainCameraComponent?.cullingMask;if(e&&t!==void 0){for(const i of e.cameras)i.layers.mask=t;e.layers.mask=t}else if(e){for(const i of e.cameras)i.layers.enableAll();e.layers.enableAll()}}invokeControllerEvent(e,t,i){for(let n=t.length-1;n>=0;n--){const o=t[n];if(o)try{o({xr:this,controller:e,change:i})}catch(r){console.error(r)}}}_camera;_cameraRenderParent=new c.Object3D().rotateY(Math.PI);_previousCameraParent;_customforward=!0;originalCameraNearPlane;requestedCameraNearPlane=null;applyCustomForward(){if(this.context.mainCamera&&this._customforward){this._camera=this.context.mainCamera,this._camera.parent!==this._cameraRenderParent&&(this._previousCameraParent=this._camera.parent,this._previousCameraParent?.add(this._cameraRenderParent)),this._cameraRenderParent.name="XR Camera Render Parent",this._cameraRenderParent.add(this._camera);{let e=.02;const t=.001;if(this.rig){const i=je(this.rig.gameObject);e*=i.x}this._camera instanceof c.PerspectiveCamera&&Math.abs(this._camera.near-e)>t&&(this.isAR?this.originalCameraNearPlane=this._camera.near:this._camera.near=e,Le&&console.debug(`Setting camera near plane to ${e} (was ${this.originalCameraNearPlane}) to account for XR rendering scale`))}}}revertCustomForward(){this._camera&&this._previousCameraParent&&this._previousCameraParent.add(this._camera),this._previousCameraParent=null,this._camera instanceof c.PerspectiveCamera&&this.originalCameraNearPlane!=null&&(this._camera.near=this.originalCameraNearPlane,this.originalCameraNearPlane=void 0)}_viewerPose;_transformOrientation=new c.Quaternion;_transformPosition=new c.Vector3;internalUpdateState(){const e=this.context.renderer.xr.getReferenceSpace();if(!e){this._viewerPose=void 0;return}if(this._viewerPose=this.frame.getViewerPose(e),this._viewerPose){const t=this._viewerPose.transform;this._transformPosition.set(t.position.x,t.position.y,t.position.z),this._transformOrientation.set(t.orientation.x,t.orientation.y,t.orientation.z,t.orientation.w)}}_transition;get transition(){return this._transition||(this._transition=new Hy),this._transition}fadeTransition(){return this._transition||(this._transition=new Hy),this._transition.fadeTransition()}updateFade(e){this._transition&&e instanceof c.PerspectiveCamera&&this._transition.update(e,this.context.time.deltaTime)}onUpdateFade_PostRender(){this._transition?.remove()}}const mf=x("debugwebxr");class p0{static tryFindAvatarObjects(e,t,i){if(i.head&&i.leftHand&&i.rightHand)return;const n=e.name.toLocaleLowerCase();!i.head&&n.includes("head")&&(mf&&console.log("FOUND AVATAR HEAD",e.name),i.head=new Y("",t,e)),n.includes("hand")&&(!i.leftHand&&n.includes("left")&&(mf&&console.log("FOUND AVATAR LEFT HAND",e.name),i.leftHand=new Y("",t,e)),!i.rightHand&&n.includes("right")&&(mf&&console.log("FOUND AVATAR RIGHT HAND",e.name),i.rightHand=new Y("",t,e)));for(let o=0;o<e.children.length;o++){if(i.head&&i.leftHand&&i.rightHand)return;const r=e.children[o];this.tryFindAvatarObjects(r,t,i)}}}class Z extends c.Color{alpha=1;get isRGBAColor(){return!0}set a(e){this.alpha=e}get a(){return this.alpha}constructor(e,t,i,n){super(),typeof e=="number"&&typeof t=="number"&&typeof i=="number"?(this.set(e,t,i),this.alpha=typeof n=="number"?n:1):e!==void 0&&(this.set(e),this.alpha=1)}clone(){const e=super.clone();return e.alpha=this.alpha,e}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,"alpha"in e&&typeof e.alpha=="number"?this.alpha=e.alpha:typeof e.a=="number"&&(this.alpha=e.a),this}lerp(e,t){const i=e;return i.alpha!=null&&(this.alpha=L.lerp(this.alpha,i.alpha,t)),super.lerp(e,t)}lerpColors(e,t,i){const n=e,o=t;return n.alpha!=null&&o.alpha!=null&&(this.alpha=L.lerp(n.alpha,o.alpha,i)),super.lerpColors(e,t,i)}multiply(e){const t=e;return t.alpha!=null&&(this.alpha=this.alpha*t.alpha),super.multiply(e)}fromArray(e,t=0){return this.alpha=e[t+3],super.fromArray(e,t)}static fromColorRepresentation(e){if(typeof e=="string"){if(e.trim()==="transparent")return new Z(0,0,0,0);if(e.startsWith("#")&&e.length===9){const t=parseInt(e.slice(1,9),16),i=t>>24&255,n=t>>16&255,o=t>>8&255,r=t>>0&255;return new Z(i/255,n/255,o/255,r/255)}else if(e.startsWith("#")){const t=parseInt(e.slice(1),16),i=t>>16&255,n=t>>8&255,o=t>>0&255;return new Z(i/255,n/255,o/255,1)}else if(e.startsWith("rgba")){const t=e.slice(5,-1).split(",").map(Number);return new Z(t[0]/255,t[1]/255,t[2]/255,t[3])}else if(e.startsWith("rgb")){const t=e.slice(4,-1).split(",").map(Number);return new Z(t[0]/255,t[1]/255,t[2]/255,1)}}else if(Array.isArray(e)){if(e.length===4)return new Z(e[0],e[1],e[2],e[3]);if(e.length===3)return new Z(e[0],e[1],e[2],1);console.error("Invalid color array length. Expected 3 or 4, got "+e.length)}return new Z(e)}}const bt=new c.Vector3,Qy=new c.Vector3,Yy=new c.Quaternion,iC=x("debuggizmos"),qi=8947848,gf=32;class B{constructor(){}static enabled=!0;static isGizmo(e){return e[Cp]!==void 0}static setVisible(e){for(const t of Si.timedObjectsBuffer)t.visible=e}static DrawLabel(e,t,i=.05,n=0,o,r,a){if(!B.enabled)return null;o||(o=qi);const l=G.active?.rigScale??1,h=Si.getTextLabel(n,t,i*l,o,r);return a instanceof c.Object3D&&a.add(h),h.position.x=e.x,h.position.y=e.y,h.position.z=e.z,h}static DrawRay(e,t,i=qi,n=0,o=!0){if(!B.enabled)return;const r=Si.getLine(n),a=r.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),bt.set(t.x,t.y,t.z).multiplyScalar(999999999),a.setXYZ(1,e.x+bt.x,e.y+bt.y,e.z+bt.z),a.needsUpdate=!0,r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1,Ki(r.material,i)}static DrawDirection(e,t,i=qi,n=0,o=!0,r=1){if(!B.enabled)return;const a=Si.getLine(n),l=a.geometry.getAttribute("position");l.setXYZ(0,e.x,e.y,e.z),t.w!==void 0?(bt.set(0,0,-r),Yy.set(t.x,t.y,t.z,t.w),bt.applyQuaternion(Yy)):(bt.set(t.x,t.y,t.z),bt.multiplyScalar(r)),l.setXYZ(1,e.x+bt.x,e.y+bt.y,e.z+bt.z),l.needsUpdate=!0,a.material.depthTest=o,a.material.depthWrite=!1,Ki(a.material,i)}static DrawLine(e,t,i=qi,n=0,o=!0){if(!B.enabled)return;const r=Si.getLine(n),a=r.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),a.setXYZ(1,t.x,t.y,t.z),a.needsUpdate=!0,r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1,Ki(r.material,i)}static DrawCircle(e,t,i,n=qi,o=0,r=!0){if(!B.enabled)return;const a=Si.getCircle(o);a.position.set(e.x,e.y,e.z),a.scale.set(i,i,i),a.quaternion.setFromUnitVectors(this._up,bt.set(t.x,t.y,t.z).normalize()),a.material.depthTest=r,a.material.depthWrite=!1,a.material.fog=!1,Ki(a.material,n)}static DrawWireSphere(e,t,i=qi,n=0,o=!0){if(!B.enabled)return;const r=Si.getSphere(t,n,!0);Zo(r,e.x,e.y,e.z),r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1,Ki(r.material,i)}static DrawSphere(e,t,i=qi,n=0,o=!0){if(!B.enabled)return;const r=Si.getSphere(t,n,!1);Zo(r,e.x,e.y,e.z),r.material.depthTest=o,r.material.depthWrite=!1,Ki(r.material,i)}static DrawWireBox(e,t,i=qi,n=0,o=!0,r=void 0){if(!B.enabled)return;const a=Si.getBox(n);a.position.set(e.x,e.y,e.z),a.scale.set(t.x,t.y,t.z),r?a.quaternion.copy(r):a.quaternion.identity(),a.material.depthTest=o,a.material.wireframe=!0,a.material.depthWrite=!1,a.material.fog=!1,Ki(a.material,i)}static DrawWireBox3(e,t=qi,i=0,n=!0){if(!B.enabled)return;const o=Si.getBox(i);o.position.copy(e.getCenter(bt)),o.scale.copy(e.getSize(bt)),o.material.depthTest=n,o.material.wireframe=!0,o.material.depthWrite=!1,o.material.fog=!1,Ki(o.material,t)}static _up=new c.Vector3(0,1,0);static DrawArrow(e,t,i=qi,n=0,o=!0,r=!1){if(!B.enabled)return;const a=Si.getArrowHead(n);a.position.set(t.x,t.y,t.z),a.quaternion.setFromUnitVectors(this._up.set(0,1,0),bt.set(t.x,t.y,t.z).sub(Qy.set(e.x,e.y,e.z)).normalize());const h=bt.set(t.x,t.y,t.z).sub(Qy.set(e.x,e.y,e.z)).length()*.1;a.scale.set(h,h,h),a.material.depthTest=o,a.material.wireframe=r,Ki(a.material,i),this.DrawLine(e,t,i,n,o)}static DrawWireMesh(e){const t=Si.getMesh(e.duration??0);"mesh"in e?(t.geometry=e.mesh.geometry,t.matrixWorld.copy(e.mesh.matrixWorld)):(t.geometry=e.geometry,t.matrixWorld.copy(e.matrix)),t.matrixAutoUpdate=!1,t.matrixWorldAutoUpdate=!1,t.material.depthTest=e.depthTest??!0,t.material.wireframe=!0,Ki(t.material,e.color??qi)}}const nC=new c.BoxGeometry(1,1,1);function Dm(s=null){const e=new c.Color(s??14540253),t=new c.EdgesGeometry(nC);return new c.LineSegments(t,new c.LineBasicMaterial({color:e}))}function Ki(s,e){if(Array.isArray(s)){for(const i of s)Ki(i,e);return}const t=e instanceof Z?e.a:1;s.color.set(e),s.opacity=t,s.transparent=t<1}const Cp=Symbol("GizmoCache");class Si{static familyName="needle-gizmos";static ensureFont(){let e=ee.__webpack_exports__default.FontLibrary.getFontFamily(this.familyName);e||(e=ee.__webpack_exports__default.FontLibrary.addFontFamily(this.familyName),e.addVariant("normal","normal","https://uploads.needle.tools/include/font-msdf.json","https://uploads.needle.tools/include/font.png")?.addEventListener("ready",()=>{ee.__webpack_exports__default.update()}))}static getTextLabel(e,t,i,n,o){this.ensureFont();let r=this.textLabelCache.pop(),a=1;o&&typeof o=="string"&&o?.length>=8&&o.startsWith("#")?(a=parseInt(o.substring(7),16)/255,o=o.substring(0,7),iC&&console.log(o,a)):typeof o=="object"&&o.a!==void 0&&(a=o.a);const l={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:i,color:n,lineHeight:1,backgroundColor:o??void 0,backgroundOpacity:a,textContent:t,borderRadius:.5*i,padding:.8*i,whiteSpace:"pre",offset:.05*i};if(r)r.set(l);else{r=new ee.__webpack_exports__Text(l);const h=this,d=r;d.setText=function(u){this.set({textContent:u}),h.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(N.Current,r,e,this.textLabelCache),r}static getBox(e){let t=this.boxesCache.pop();if(!t){const i=new c.BoxGeometry(1,1,1);t=new c.Mesh(i)}return this.registerTimedObject(N.Current,t,e,this.boxesCache),t}static getLine(e){let t=this.linesCache.pop();if(!t){t=new c.Line;let i=t.geometry.getAttribute("position");i||(i=new c.BufferAttribute(new Float32Array(6),3),t.geometry.setAttribute("position",i))}return t.frustumCulled=!1,this.registerTimedObject(N.Current,t,e,this.linesCache),t}static getCircle(e){let t=this.circlesCache.pop();if(!t){t=new c.Line;let i=t.geometry.getAttribute("position");if(!i){i=new c.BufferAttribute(new Float32Array(gf*3),3),t.geometry.setAttribute("position",i);const n=j(0,1,0),o=j(0,0,1),r=j(o);r.cross(n).normalize();const a=j(r),l=Math.PI*2/(gf-1);for(let h=0;h<gf+1;h++){const d=l*h;n.copy(a).multiplyScalar(Math.cos(d)*1),r.copy(o).multiplyScalar(Math.sin(d)*1);const u=n.add(r);i.setXYZ(h,u.x,u.y,u.z)}}}return t.frustumCulled=!1,this.registerTimedObject(N.Current,t,e,this.circlesCache),t}static getSphere(e,t,i){let n=this.spheresCache.pop();return n||(n=new c.Mesh(new c.SphereGeometry(1,8,8))),n.scale.set(e,e,e),n.material.wireframe=i,this.registerTimedObject(N.Current,n,t,this.spheresCache),n}static getArrowHead(e){let t=this.arrowHeadsCache.pop();return t||(t=new c.Mesh(new c.CylinderGeometry(0,.5,1,8))),this.registerTimedObject(N.Current,t,e,this.arrowHeadsCache),t}static getMesh(e){let t=this.mesh.pop();return t||(t=new c.Mesh,t.material=new c.MeshBasicMaterial),this.registerTimedObject(N.Current,t,e,this.mesh),t}static linesCache=[];static circlesCache=[];static spheresCache=[];static boxesCache=[];static arrowHeadsCache=[];static mesh=[];static textLabelCache=[];static registerTimedObject(e,t,i,n){if(!e){console.error("No Needle Engine context available. Did you call a Gizmos function in global scope?");return}const o=this.contextBeforeRenderCallbacks.get(e),r=this.contextPostRenderCallbacks.get(e);if(o){if(e.pre_render_callbacks[e.pre_render_callbacks.length-1]!==o){const a=e.pre_render_callbacks.indexOf(o);a>=0&&e.pre_render_callbacks.splice(a,1),e.pre_render_callbacks.push(o)}}else{const a=()=>{this.onBeforeRender(e,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(e,a),e.pre_render_callbacks.push(a)}if(r){if(e.post_render_callbacks[e.post_render_callbacks.length-1]!==r){const a=e.post_render_callbacks.indexOf(r);a>=0&&e.post_render_callbacks.splice(a,1),e.post_render_callbacks.push(r)}}else{const a=()=>{this.onPostRender(e,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(e,a),e.post_render_callbacks.push(a)}t.traverse(a=>{a.layers.disableAll(),a.layers.enable(2)}),t.renderOrder=999999,t[Cp]=n,t.castShadow=!1,t.receiveShadow=!1,t.isGizmo=!0,this.timedObjectsBuffer.push(t),this.timesBuffer.push(N.Current.time.realtimeSinceStartup+i),e.scene.add(t)}static timedObjectsBuffer=new Array;static timesBuffer=new Array;static contextPostRenderCallbacks=new Map;static contextBeforeRenderCallbacks=new Map;static tmuiNeedsUpdate=!1;static onBeforeRender(e,t){this.tmuiNeedsUpdate&&(this.tmuiNeedsUpdate=!1,ee.__webpack_exports__default.update());for(let i=0;i<t.length;i++){const n=t[i];if(e.mainCamera&&n instanceof ee.__webpack_exports__default.MeshUIBaseElement){if(er(n))continue;const o=e.isInVR,r=!1,a=!o;xc(n,e.mainCamera,r,a)}}}static onPostRender(e,t,i){const n=e.time.realtimeSinceStartup;for(let o=t.length-1;o>=0;o--){const r=t[o];n>=i[o]-1e-6&&(t.splice(o,1),i.splice(o,1),r.removeFromParent(),er(r)!=!0&&r[Cp].push(r))}}}const It=x("debugphysics"),Ky=new c.Layers;class lo{static AllLayers=4294967295;ray;cam;screenPoint;raycaster;results;targets;recursive=!0;minDistance;maxDistance;lineThreshold;layerMask;ignore;testObject;useAcceleratedRaycast;allowSlowRaycastFallback=!0;screenPointFromOffset(e,t){this.screenPoint===void 0&&(this.screenPoint=new c.Vector2),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setLayer(e){Ky.set(e),this.layerMask=Ky}setMask(e){this.layerMask||(this.layerMask=new c.Layers);const t=this.layerMask;t?t.mask=e:this.layerMask=e}}class Lm{distance;point;object;constructor(e,t,i){this.object=e,this.distance=t,this.point=i}}class va{static _raycasting=0;static get raycasting(){return this._raycasting>0}raycastPhysicsFast(e,t=void 0,i=1/0,n=!0){return this.context.physics.engine?.raycast(e,t,{maxDistance:i,solid:n})??null}raycastPhysicsFastAndGetNormal(e,t=void 0,i=1/0,n=!0){return this.context.physics.engine?.raycastAndGetNormal(e,t,{maxDistance:i,solid:n})??null}sphereOverlapPhysics(e,t){return this.context.physics.engine?.sphereOverlap(e,t)??null}context;engine;constructor(e){this.context=e}raycaster=new c.Raycaster;defaultRaycastOptions=new lo;targetBuffer=new Array(1);defaultThresholds={Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}};sphereResults=new Array;sphereMask=new c.Layers;sphere=new c.Sphere;sphereOverlap(e,t,i=!0,n=!1,o=null){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;const r=this.sphereMask;r.enableAll(),r.disable(2);for(const a of this.context.scene.children)this.intersectSphere(a,e,t,r,this.sphereResults,i,n,o);return this.sphereResults.sort((a,l)=>a.distance-l.distance)}raycastFromRay(e,t=null){const i=t??this.defaultRaycastOptions;i.ray=e;const n=this.raycast(i);return i===this.defaultRaycastOptions&&(i.ray=void 0),n}raycast(e=null){It&&performance.mark("raycast.start"),e||(e=this.defaultRaycastOptions);const t=e.screenPoint??this.context.input.mousePositionRC,i=e.raycaster??this.raycaster;if(i.near=e.minDistance??0,i.far=e.maxDistance??1/0,i.params=this.defaultThresholds,e.lineThreshold===void 0&&(e.lineThreshold=-1),i.params.Line={threshold:e.lineThreshold},e.ray)i.ray.copy(e.ray);else{const a=e.cam??this.context.mainCamera;if(!a)return It&&console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];const l=this.context.xrCamera;this.context.isInXR&&l instanceof c.ArrayCamera&&l.cameras.length>0?i.setFromCamera(t,l.cameras[0]):i.setFromCamera(t,a)}let n=e.targets;n||(n=this.targetBuffer,n.length=1,n[0]=this.context.scene);let o=e.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),o||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),o=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof c.Layers?i.layers.mask=e.layerMask.mask:i.layers.mask=e.layerMask:(i.layers.enableAll(),i.layers.disable(2)),It&&console.time("raycast"),o.length=0,va._raycasting++,this.intersect(this.raycaster,n,o,e),o.sort((a,l)=>a.distance-l.distance);const r=e.ignore;return r!==void 0&&r.length>0&&(o=o.filter(a=>!r.includes(a.object))),va._raycasting--,It&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",o?.length?[...o]:"nothing"),performance.mark("raycast.end"),performance.measure("raycast","raycast.start","raycast.end")),o}intersect(e,t,i,n){for(const o of t){if(!o||o.visible===!1||B.isGizmo(o)||n.lineThreshold!==void 0&&n.lineThreshold<0&&o instanceof c.Line)continue;let r=!0;const a=o,l=a.geometry;if(o.raycastAllowed===!1&&(r=!1),r&&n.testObject){const h=n.testObject?.(o);if(h===!1)continue;h==="continue in children"&&(r=!1)}else r&&(l&&Zy(l)||(r=!1));if(r){const h=i.length,d=o.raycastPreference||"lod";let u=d!=="bounds";if(n.precise===!1&&(u=!1),l&&(u||=l.getAttribute("position")?.array?.length<64),a instanceof q.GroundedSkybox&&(u=!1),d==="lod"){const p=ne.getRaycastMesh(o);p&&(a.geometry=p)}if(!u&&oC(a,e,i)||(n.useAcceleratedRaycast!==!1?Sd.runMeshBVHRaycast(e,a,i,this.context,n):e.intersectObject(a,!1,i)),a.geometry=l,It&&i.length!=h){const p=i[i.length-1];B.DrawWireSphere(p.point,.1,7798784,1,!1),B.DrawWireMesh({mesh:o,depthTest:!1,duration:.2,color:7798784})}}n.recursive!==!1&&this.intersect(e,o.children,i,n)}return i}tempBoundingBox=new c.Box3;intersectSphere(e,t,i,n,o,r,a,l){let h=e&&e.isMesh&&e.layers.test(n)&&!B.isGizmo(e);h&&=e.visible,h&&=!(e instanceof c.Line),h&&=!(e instanceof q.GroundedSkybox);const d=e,u=d.geometry;if(h&&l){const p=l(e);if(p===!1)return;p==="continue in children"&&(h=!1)}if(u&&Zy(u)||(h=!1),h){if(a){const p=this.sphere;p.center.copy(t),p.radius=i;const m=o.length;if(Sd.runMeshBVHRaycast(this.sphere,d,o,this.context,{}),m!=o.length&&!r)return}else if(u.boundingBox||u.computeBoundingBox(),u.boundingBox){d.matrixWorldNeedsUpdate&&d.updateWorldMatrix(!1,!1);const p=this.tempBoundingBox.copy(u.boundingBox).applyMatrix4(d.matrixWorld),m=this.sphere;if(m.center.copy(t),m.radius=i,m.intersectsBox(p)){const y=X(e),_=y.distanceTo(m.center),g=new Lm(e,_,y);if(o.push(g),!r)return}}}if(e.children)for(const p of e.children){const m=o.length;if(this.intersectSphere(p,t,i,n,o,r,a,l),m!=o.length&&!r)return}}}function Zy(s){return!(s.index&&s.index.array.length<3)}const Po=new c.Sphere,Ph=new c.Plane,sC=new c.Matrix3;function oC(s,e,t){const i=s._computeIntersections;if(!i)return!1;let n=s["_computeIntersections:Needle"];return n||(n=s["_computeIntersections:Needle"]=function(o,r,a){const l=this,h=l.geometry.boundingSphere;if(h){if(l instanceof q.GroundedSkybox){Ph.setFromNormalAndCoplanarPoint(j(0,1,0),j(0,-l.position.y,0)),Ph.applyMatrix4(l.matrixWorld,sC);const u=o.ray.intersectPlane(Ph,j());if(u){Po.copy(h),Po.applyMatrix4(l.matrixWorld);const m=j(u).sub(o.ray.origin).length(),y=Po.radius*.5;m<y&&r.push({distance:m,point:u,object:l,normal:Ph.normal.clone()})}return}Po.copy(h),Po.applyMatrix4(l.matrixWorld);const d=o.ray.intersectSphere(Po,j());if(d){const u=j(d).sub(o.ray.origin),p=u.length();if(p>Po.radius){const m=u.clone().normalize();r.push({distance:p,point:d,object:l,normal:m})}}}}),s._computeIntersections=n,e.intersectObject(s,!1,t),s._computeIntersections=i,!0}var Sd;(s=>{let e=0;function t(b,v,R,O,M){if(!v.geometry||!v.geometry.hasAttribute("position"))return!1;const T=v.geometry;if(v?.isSkinnedMesh){const D=v,I=D.bvhNeedsUpdate;if(!D.staticGenerator)l(),r&&(D.staticGenerator=new r(v),D.staticGenerator.applyWorldTransforms=!1,D.staticGeometry=D.staticGenerator.generate(),T.boundsTree=a?.call(D.staticGeometry),D.staticGeometryLastUpdate=performance.now()+Math.random()*200,D.bvhNeedsUpdate=!0);else if(T.boundsTree&&(D.autoUpdateMeshBvhInterval!==void 0&&D.autoUpdateMeshBvhInterval>=0||I===!0)){const V=performance.now(),W=V-D.staticGeometryLastUpdate,k=D.autoUpdateMeshBvhInterval??100;(I||W>k)&&(It&&console.warn(`Physics: updating skinned mesh bvh for ${v.name} after ${W.toFixed(2)}ms`),D.bvhNeedsUpdate=!1,D.staticGeometryLastUpdate=V,D.staticGenerator?.generate(D.staticGeometry),T.boundsTree.refit())}}else if(!T.boundsTree){d||w();let D=!0;if((O.xr||T[y]===!1||T.getAttribute("position")?.isInterleavedBufferAttribute||T.index&&T.index?.isInterleavedBufferAttribute||e>10)&&(D=!1),D&&p){if(T[m]===void 0){let I=null;if(g.length>0){const V=g.shift();V&&!V.running&&(I=V)}if(!I&&_.length<3)try{I=new p,_.push(I)}catch(V){V instanceof DOMException&&V.name==="SecurityError"?(console.warn("Failed to create MeshBVH worker, falling back to main thread generation. This can happen when running from file://, if the browser does not support workers or if the browser is blocking workers for other reasons."),console.debug(V),e+=10):(console.error("Failed to create MeshBVH worker"),console.debug(V)),e++}if(I!=null&&!I.running){const V=v.name;It&&console.log("<<<< worker start",V,I),T[m]="queued",performance.mark("bvh.create.start");const W=T.clone();try{I.generate(W).then(k=>{T[m]="done",T.boundsTree=k}).catch(k=>{T[m]="failed - "+k?.message,T[y]=!1,It&&console.error("Failed to generate mesh bvh on worker",k)}).finally(()=>{It&&console.log(">>>>> worker done",V,{hasBoundsTre:T.boundsTree!=null}),g.push(I),W.dispose(),performance.mark("bvh.create.end"),performance.measure("bvh.create (worker)","bvh.create.start","bvh.create.end")})}catch(k){console.error("Failed to generate mesh bvh on worker",k)}}else It&&console.warn("No worker available")}}else(!u||!D)&&(l(),o&&(performance.mark("bvh.create.start"),T.boundsTree=new o(T),performance.mark("bvh.create.end"),performance.measure("bvh.create","bvh.create.start","bvh.create.end")))}if(b instanceof c.Raycaster){const D=b,I=v.raycast;if(T.boundsTree)l(),n&&(v.acceleratedRaycast||(v.acceleratedRaycast=n.bind(v),It&&console.debug(`Physics: bind acceleratedRaycast fn to "${v.name}"`)),v.raycast=v.acceleratedRaycast);else if(It&&console.warn("No bounds tree found for mesh",v.name,{workerTask:T[m],hasAcceleratedRaycast:n!=null}),M.allowSlowRaycastFallback===!1&&(T.getAttribute("position")?.array?.length??0)>2e3)return It&&console.warn("Skipping raycast because no bounds tree is available and allowSlowRaycastFallback is false"),!1;const V=D.firstHitOnly;return D.firstHitOnly=!1,D.intersectObject(v,!1,R),D.firstHitOnly=V,v.raycast=I,!0}else if(b instanceof c.Sphere){const D=T.boundsTree;if(D){const I=b;if(h.copy(v.matrixWorld).invert(),I.applyMatrix4(h),D.intersectsSphere(I)){const W=X(v),k=W.distanceTo(I.center),U=new Lm(v,k,W);R.push(U)}}return!0}return!1}s.runMeshBVHRaycast=t;let i=!1,n=null,o=null,r=null,a=null;function l(){i||(i=!0,Promise.resolve().then(()=>require("./vendor-6kAXU6fm.umd.cjs")).then(b=>b.index$1).then(b=>{n=b.acceleratedRaycast,o=b.MeshBVH,r=b.StaticGeometryGenerator,a=b.computeBoundsTree}).catch(b=>{(It||A())&&console.error("Failed to load BVH library...",b.message)}))}const h=new c.Matrix4;let d=!1,u=!1,p=null;const m=Symbol("Needle:MeshBVH-Worker"),y=Symbol("Needle:MeshBVH-CanUseWorker"),_=[],g=[];function w(){d=!0,u=!0,Promise.resolve().then(()=>lT).then(b=>{p=b.GenerateMeshBVHWorker}).catch(b=>{It||A()?console.warn("Failed to setup mesh bvh worker"):console.debug("Failed to setup mesh bvh worker",b)}).finally(()=>{u=!1})}})(Sd||(Sd={}));const Jy=Symbol("gltf-loader-internal-usage-tracker"),rC=x("debugusers");class ca{get name(){return"NEEDLE_internal_usage_tracker"}static isLoading(e){return ca._loadingProcesses>0}static _loadingProcesses=0;parser;_getDependency;_loadingId;_loadedObjects=new Set;constructor(e){this.parser=e,this._getDependency=this.parser.getDependency,this._loadingId=Date.now().toString()}beforeRoot(){ca._loadingProcesses++;const e=this,t=this._getDependency;return this.parser.getDependency=function(i,n){const o=t.call(this,i,n);return o.then(r=>(r&&(e._loadedObjects.add(r),r[Jy]=e._loadingId),r)),o},null}afterRoot(e){ca._loadingProcesses--,this.parser.getDependency=this._getDependency;for(const t of this._loadedObjects)delete t[Jy],t instanceof c.Object3D&&(t.parent||t instanceof c.Mesh&&setTimeout(()=>{rC&&console.warn("> GLTF LOADER: Mesh not used in scene!",t),t.material=null,t.geometry=null},1e3));return null}}class m0{constructor(){window.addEventListener("unhandledrejection",e=>{if(e.defaultPrevented)return;const t=e?.reason?.path;if(t){const i=t[0];i&&i.tagName==="IMG"&&(console.warn(`Could not load image:
168
168
  `+i.src),e.preventDefault())}})}}const tu=x("trackresources");function g0(){return tu==="dispose"}let dr=!0;tu===0&&(dr=!1);function aC(s){dr=s}function y0(){return dr}const _0=Symbol("disposable");function b0(s,e){s&&(s[_0]=e,$o&&console.warn("Set disposable",e,s))}const v0=Symbol("disposed");function lC(s){return s[v0]===!0}function _e(s){if(s){if(s[_0]===!1){$o&&console.warn("Object is marked as not disposable",s);return}if(typeof s=="object"&&(s[v0]=!0),s instanceof c.Scene)_e(s.environment),_e(s.background),_e(s.customDepthMaterial),_e(s.customDistanceMaterial);else if(s instanceof c.SkinnedMesh)_e(s.geometry),_e(s.material),_e(s.skeleton),_e(s.bindMatrix),_e(s.bindMatrixInverse),_e(s.customDepthMaterial),_e(s.customDistanceMaterial),s.visible=!1;else if(s instanceof c.Mesh)_e(s.geometry),_e(s.material),_e(s.customDepthMaterial),_e(s.customDistanceMaterial),s.visible=!1;else if(s instanceof c.Object3D)s.visible=!1;else if(s instanceof c.BufferGeometry){Ir(s);for(const e of Object.keys(s.attributes)){const t=s.attributes[e];_e(t)}}else if(s instanceof c.BufferAttribute||s instanceof c.InterleavedBufferAttribute)$o&&console.warn("BufferAttribute dispose not supported",s.count);else if(s instanceof Array)for(const e of s)e instanceof c.Material&&_e(e);else if(s instanceof c.Material){Ir(s);for(const t of Object.keys(s)){const i=s[t];i instanceof c.Texture&&_e(i)}const e=s.uniforms;if(e)for(const t of Object.keys(e)){const i=e[t];i instanceof c.Texture?_e(i):i instanceof c.Uniform$1&&_e(i.value)}}else s instanceof c.Texture?(Ir(s),Ir(s.source),s.source?.data instanceof ImageBitmap&&Ir(s.source.data)):s instanceof c.Skeleton?(Ir(s.boneTexture),s.boneTexture=null):s instanceof c.Bone||!(s instanceof c.Object3D)&&$o&&console.warn("Unknown object type",s)}}function Ir(s){s&&(($o||g0()||tu)&&console.warn("🧨 FREE",s),s instanceof ImageBitmap||"dispose"in s&&typeof s.dispose=="function"&&s.dispose())}function cC(s){}const hC=new Set;function Im(s,e,t=null,i){if(i||(i=hC,i.clear()),!s)return i;const n=s[nc];if(n)for(const o of n)i.has(o)||t?.call(null,o)!==!1&&(i.add(o),e&&Im(o,!0,t,i));return i}function dC(s){return s[Sl]}const $o=x("debugresourceusers")||x("debugmemory"),nc=Symbol("needle-resource-users"),Sl=Symbol("needle-resource-users-count");function Rt(s,e){Zd(s,e,function(t,i){dr&&!va.raycasting&&(Cd(nc,this,t,!1),Cd(nc,this,i,!0))})}dr&&(Rt(c.Mesh.prototype,"material"),Rt(c.Mesh.prototype,"geometry"),Rt(c.Material.prototype,"map"),Rt(c.Material.prototype,"bumpMap"),Rt(c.Material.prototype,"alphaMap"),Rt(c.Material.prototype,"normalMap"),Rt(c.Material.prototype,"displacementMap"),Rt(c.Material.prototype,"roughnessMap"),Rt(c.Material.prototype,"metalnessMap"),Rt(c.Material.prototype,"emissiveMap"),Rt(c.Material.prototype,"specularMap"),Rt(c.Material.prototype,"envMap"),Rt(c.Material.prototype,"lightMap"),Rt(c.Material.prototype,"aoMap"),Rt(c.Material.prototype,"gradientMap"));function uC(s){if(dr===!1)return;const e=s[nc];if(e)for(const t of e)Cd(nc,t,s,!1)}dr&&Zd(c.Material.prototype,"dispose",function(){uC(this)});let Pp=0;function Cd(s,e,t,i){if(Pp>0)return;if(Array.isArray(t)){for(const o of t)Cd(s,e,o,i);return}if(!t)return;let n=t[s];if(n||(n=new Set),i){if(e&&!n.has(e)){n.add(e);let o=t[Sl]||0;o+=1,t[Sl]=o,$o&&console.warn(`🟢 Added user of "${t.type}"`,e,t,o,"users:",n)}}else if(e&&n.has(e)){n.delete(e);let o=t[Sl]||0;o>0&&(o-=1,t[Sl]=o),$o&&console.warn(`🔴 Removed user of "${t.type}"`,e,t,o,"users:",n),o<=0&&(ca.isLoading(t)||(tu&&console.warn(`🔴 Removed all user of "${t.type}"`,t),g0()&&_e(t)))}t[s]=n}try{Zd(c.WebGLRenderer.prototype,"render",function(){Pp++},function(){Pp--})}catch(s){console.warn("Could not wrap WebGLRenderer.render",s)}const e_=x("debugcomponentevents");class iu{static eventListeners=new Map;static addComponentLifecylceEventListener(e,t){this.eventListeners.has(e)&&this.eventListeners.set(e,[]);let i=this.eventListeners.get(e);i||(i=[]),i.push(t),this.eventListeners.set(e,i),e_&&console.log("Added event listener for "+e,this.eventListeners)}static removeComponentLifecylceEventListener(e,t){const i=this.eventListeners.get(e);if(!i)return;const n=i.indexOf(t);n<0||i.splice(n,1)}static dispatchComponentLifecycleEvent(e,t){const i=this.eventListeners.get(e);if(e_&&console.log("Dispatching event "+e,i),!!i)for(const n of i)n(t)}}const sc=Symbol("NEEDLE_NEED_UPDATE_INSTANCE"),w0=Symbol("isUsingInstancing"),x0=Symbol("instancingRenderer"),Cl=Symbol("instancingAutoUpdateBounds");class Di{static isUsingInstancing(e){return e[w0]===!0}static getRenderer(e){return e[x0]||null}setAutoUpdateBounds(e,t){const i=Di.getRenderer(e);i&&(i[Cl]=t)}static markDirty(e,t=!0){if(e&&(this.isUsingInstancing(e)&&(e[sc]=!0,e.matrixWorldNeedsUpdate=!0),t))for(const i of e.children)Di.markDirty(i,!0)}}exports.NEEDLE_ENGINE_FEATURE_FLAGS=void 0;(s=>{s.experimentalSmartHierarchyUpdate=!1})(exports.NEEDLE_ENGINE_FEATURE_FLAGS||(exports.NEEDLE_ENGINE_FEATURE_FLAGS={}));function ha(s,e){try{e||s()}catch(t){return console.error(t),!1}return!0}const Op=x("debugnewscripts"),fC=x("debughierarchy"),we=[];function pC(){return we.length>0}function Pd(s){if(Op&&console.log("Register new components",s.new_scripts.length,[...s.new_scripts],s.alias?"element: "+s.alias:s.hash,s),s.new_scripts_pre_setup_callbacks.length>0){for(const e of s.new_scripts_pre_setup_callbacks)e&&e();s.new_scripts_pre_setup_callbacks.length=0}if(!(s.new_scripts.length<=0)){we.length=0,s.new_scripts.length>0&&we.push(...s.new_scripts),s.new_scripts.length=0;for(let e=0;e<we.length;e++)try{const t=we[e];if(t.isComponent!==!0){(A()||Op)&&console.error(`Registered script is not a Needle Engine component.
169
169
  The script will be ignored. Please make sure your component extends "Behaviour" imported from "@needle-tools/engine"
@@ -1272,7 +1272,7 @@ ${a.join(`
1272
1272
  `)}`:""}
1273
1273
  }`}function G_(s){return`(${s.r}, ${s.g}, ${s.b})`}function q_(s){return`(${s.x}, ${s.y})`}const Cg=[1023,33777,33778,33779,35842,35843,37496,37808,37809,37810,37811,37812,37813,37814,37815,37816,37817,37818,37819,37820,37821,36492];x("debugusdz");class gt{static global_id=0;id;trigger;action;exclusive=!1;makeExclusive(e){return this.exclusive=e,this}constructor(e,t,i){this.id="Behavior_"+mi(e)+"_"+gt.global_id++,this.trigger=t,this.action=i}writeTo(e,t,i){if(!this.trigger||!this.action)return;i.beginBlock(`def Preliminary_Behavior "${this.id}"`);let n="";if(Array.isArray(this.trigger)){n="[";for(let o=0;o<this.trigger.length;o++){const r=this.trigger[o];n+="<"+r.id+">",o+1<this.trigger.length&&(n+=", ")}n+="]"}else n=`<${this.trigger.id}>`;if(i.appendLine(`rel triggers = ${n}`),i.appendLine(`rel actions = <${this.action.id}>`),i.appendLine(`uniform bool exclusive = ${this.exclusive?1:0}`),i.appendLine(),Array.isArray(this.trigger))for(const o of this.trigger)o.writeTo(t,i),i.appendLine();else this.trigger.writeTo(t,i);i.appendLine(),this.action.writeTo(t,i),i.closeBlock()}}const $r=new Set;function Gp(s,e){let t="";if(Array.isArray(s)){$r.clear();let i="[ ";for(let n=0;n<s.length;n++){let o=s[n];if(!o){console.warn("Invalid target object in behavior",s+". Is the object exported?");continue}if(typeof o=="string"){if($r.has(o))continue;i+=o,$r.add(o)}else if(typeof o=="object"){if(o.isObject3D&&(o=e.findById(o.uuid),!o)){console.warn("Invalid target object in behavior",s+". Is the object exported?");continue}const r=o.getPath?.call(o);if($r.has(r))continue;i+=r,$r.add(r)}n+1<s.length&&(i+=", ")}i+=" ]",t=i,$r.clear()}else if(typeof s=="object"){const i=s;if(i.isObject3D&&(s=e.findById(i.uuid)),!s)throw console.error("Invalid target object in behavior, the target object is likely missing from USDZ export. Is the object exported?",i),new Error(`Invalid target object in behavior, the target object is likely missing from USDZ export. Please report a bug. uuid: ${i.uuid}.`);t=s.getPath?.call(s)}return t}class Ks{static global_id=0;id;targetId;tokenId;type;distance;constructor(e,t){e&&(this.targetId=e),t?this.id=t:this.id="Trigger_"+Ks.global_id++}writeTo(e,t){t.beginBlock(`def Preliminary_Trigger "${this.id}"`),this.targetId&&(typeof this.targetId!="string"&&(this.targetId=Gp(this.targetId,e)),t.appendLine("rel affectedObjects = "+this.targetId)),this.tokenId&&t.appendLine(`token info:id = "${this.tokenId}"`),this.type&&t.appendLine(`token type = "${this.type}"`),typeof this.distance=="number"&&t.appendLine(`double distance = ${this.distance}`),t.closeBlock()}}function X_(s,e={direct:!0,indirect:!0}){const t=Ne.createEmpty();t.name="InputTarget_"+t.name,t.displayName=void 0,t.type="RealityKitComponent",t.onSerialize=i=>{i.appendLine("bool allowsDirectInput = "+(e.direct?1:0)),i.appendLine("bool allowsIndirectInput = "+(e.indirect?1:0)),i.appendLine('uniform token info:id = "RealityKit.InputTarget"')},s.add(t)}class St{static __sceneStartTrigger;static sceneStartTrigger(){if(this.__sceneStartTrigger!==void 0)return this.__sceneStartTrigger;const e=new Ks(void 0,"SceneStart");return e.tokenId="SceneTransition",e.type="enter",this.__sceneStartTrigger=e,e}static tapTrigger(e,t={direct:!0,indirect:!0}){const i=new Ks(e);if(Array.isArray(e)&&e.length>1)for(const n of e)n instanceof Ne&&X_(n,t);else e instanceof Ne&&X_(e,t);return i.tokenId="TapGesture",i}static isTapTrigger(e){return e?.tokenId==="TapGesture"}static proximityToCameraTrigger(e,t){const i=new Ks(e);return i.tokenId="ProximityToCamera",i.distance=t,i}}class Uo{static global_id=0;static getId(){return this.global_id++}id;actions;loops=0;performCount=1;type="serial";multiplePerformOperation=void 0;constructor(e,t){this.id=e,this.actions=t}addAction(e){return this.actions.push(e),this}makeParallel(){return this.type="parallel",this}makeSequence(){return this.type="serial",this}makeLooping(){return this.loops=1,this.performCount=0,this}makeRepeat(e){return this.performCount=e,this}writeTo(e,t){t.beginBlock(`def Preliminary_Action "${this.id}"`),t.beginArray("rel actions");for(const i of this.actions){if(!i)continue;const n=i===this.actions[this.actions.length-1];t.appendLine("<"+i.id+">"+(n?"":", "))}t.closeArray(),t.appendLine(),t.appendLine('token info:id = "Group"'),t.appendLine(`bool loops = ${this.loops}`),t.appendLine(`int performCount = ${this.loops>0?0:Math.max(0,this.performCount)}`),t.appendLine(`token type = "${this.type}"`),typeof this.multiplePerformOperation=="string"&&t.appendLine(`token multiplePerformOperation = "${this.multiplePerformOperation}"`),t.appendLine();for(const i of this.actions)i&&(i.writeTo(e,t),t.appendLine());t.closeBlock()}}class Gt{static global_id=0;id;tokenId;affectedObjects;easeType;motionType=void 0;duration;moveDistance;style;type;front;up;start;animationSpeed;reversed;pingPong;xFormTarget;audio;gain;auralMode;multiplePerformOperation;velocity;comment;animationName;clone(){const e=new Gt,t=e.id;return Object.assign(e,this),e.id=t,e}constructor(e,t){e&&(this.affectedObjects=e),t?this.id=t:this.id="Action",this.id+="_"+Gt.global_id++}writeTo(e,t){t.beginBlock(`def Preliminary_Action "${this.id}"`),this.comment&&t.appendLine(`# ${this.comment}`),this.affectedObjects&&(typeof this.affectedObjects!="string"&&(this.affectedObjects=Gp(this.affectedObjects,e)),t.appendLine("rel affectedObjects = "+this.affectedObjects)),typeof this.duration=="number"&&(typeof this.animationSpeed=="number"&&this.animationSpeed!==1?t.appendLine(`double duration = ${this.duration/this.animationSpeed} `):t.appendLine(`double duration = ${this.duration} `)),this.easeType&&t.appendLine(`token easeType = "${this.easeType}"`),this.tokenId&&t.appendLine(`token info:id = "${this.tokenId}"`),this.tokenId==="ChangeScene"&&t.appendLine("rel scene = </StageRoot/Scenes/Scene>"),this.motionType!==void 0&&t.appendLine(`token motionType = "${this.motionType}"`),typeof this.moveDistance=="number"&&t.appendLine(`double moveDistance = ${this.moveDistance} `),this.style&&t.appendLine(`token style = "${this.style}"`),this.type&&t.appendLine(`token type = "${this.type}"`),this.front&&t.appendLine(`vector3d front = (${this.front.x}, ${this.front.y}, ${this.front.z})`),this.up&&t.appendLine(`vector3d upVector = (${this.up.x}, ${this.up.y}, ${this.up.z})`),typeof this.start=="number"&&t.appendLine(`double start = ${this.start} `),typeof this.animationSpeed=="number"&&t.appendLine(`double animationSpeed = ${this.animationSpeed.toFixed(2)} `),typeof this.reversed=="boolean"&&t.appendLine(`bool reversed = ${this.reversed}`),typeof this.pingPong=="boolean"&&t.appendLine(`bool reverses = ${this.pingPong}`),this.xFormTarget&&(typeof this.xFormTarget!="string"&&(this.xFormTarget=Gp(this.xFormTarget,e)),t.appendLine(`rel xformTarget = ${this.xFormTarget}`)),typeof this.audio=="string"&&t.appendLine(`asset audio = @${this.audio}@`),typeof this.gain=="number"&&t.appendLine(`double gain = ${this.gain}`),typeof this.auralMode=="string"&&t.appendLine(`token auralMode = "${this.auralMode}"`),typeof this.multiplePerformOperation=="string"&&t.appendLine(`token multiplePerformOperation = "${this.multiplePerformOperation}"`),typeof this.velocity=="object"&&t.appendLine(`vector3d velocity = (${this.velocity.x}, ${this.velocity.y}, ${this.velocity.z})`),t.closeBlock()}}class Ai{x=0;y=0;z=0;constructor(e,t,i){this.x=e,this.y=t,this.z=i}static get up(){return new Ai(0,1,0)}static get right(){return new Ai(1,0,0)}static get forward(){return new Ai(0,0,1)}static get back(){return new Ai(0,0,-1)}static get zero(){return new Ai(0,0,0)}}class le{static sequence(...e){return new Uo("Group_"+Uo.getId(),e).makeSequence()}static parallel(...e){return new Uo("Group_"+Uo.getId(),e).makeParallel()}static fadeAction(e,t,i){const n=new Gt(e);return n.tokenId="Visibility",n.type=i?"show":"hide",n.duration=t,n.style="basic",n.motionType="none",n.moveDistance=0,n.easeType="none",n}static startAnimationAction(e,t,i=!1,n=!1){const o=new Gt(e);o.tokenId="StartAnimation";const r=t.start,a=t.duration,l=t.speed,h=t.clipName;if(o.comment=`Animation: ${h}, start=${r*60}, length=${a*60}, end=${(r+a)*60}`,o.animationName=h,o.start=r,o.duration=a,o.animationSpeed=l,o.reversed=i,o.pingPong=n,o.multiplePerformOperation="allow",i&&(o.start-=a),n){o.pingPong=!1;const d=o.clone();return d.reversed=!i,d.start=o.start,d.reversed&&(d.start-=a),le.sequence(o,d)}return o}static waitAction(e){const t=new Gt;return t.tokenId="Wait",t.duration=e,t.motionType=void 0,t}static lookAtCameraAction(e,t,i,n){const o=new Gt(e);return o.tokenId="LookAtCamera",o.duration=t===void 0?9999999999999:t,o.front=i??Ai.forward,o.up=n??Ai.up,o}static emphasize(e,t,i="bounce",n=1,o="basic"){const r=new Gt(e);return r.tokenId="Emphasize",r.duration=t,r.style=o??"basic",r.motionType=i,r.moveDistance=n,r}static transformAction(e,t,i,n,o="inout"){const r=new Gt(e);return r.tokenId="Transform",r.duration=i,r.duration=Math.max(1e-6,i),r.type=n,r.easeType=i>0?o:"none",Array.isArray(t)&&console.error("Transform target must not be an array",t),r.xFormTarget=t,r}static playAudioAction(e,t,i="play",n=1,o="spatial"){const r=new Gt(e);return r.tokenId="Audio",r.type=i,r.audio=t,r.gain=n,r.auralMode=o,r.multiplePerformOperation="allow",r}static impulseAction(e,t){const i=new Gt(e);return i.tokenId="Impulse",i.velocity=t,i}}class iM{get id(){return this.object.uuid}object;model;constructor(e){this.object=e}apply(e){if(!this.model&&(this.model=e.findById(this.object.uuid),!this.model)){console.error("could not find model with id "+this.object.uuid);return}this.onApply(e)}}class Pg extends iM{constructor(e,t,i,n){super(e),this.matrix=t,this.material=i,this.geometry=n}matrix;material;geometry;onApply(e){const t=this.model;if(!t)return;t.parent?.isDynamic||Ne.createEmptyParent(t);const i=t.clone();this.matrix&&i.setMatrix(this.matrix),this.material&&(i.material=this.material),this.geometry&&(i.geometry=this.geometry),t.parent?.add(i)}_enableAction;_disableAction;enable(){return this._enableAction?this._enableAction:(this._enableAction=le.fadeAction(this.object,0,!0),this._enableAction)}disable(){return this._disableAction?this._disableAction:(this._disableAction=le.fadeAction(this.object,0,!1),this._disableAction)}}class gw{actions;sortedActions;constructor(e){this.actions=[...e]}organize(){this.sortedActions={};for(const e of this.actions){const t=e.id;this.sortedActions[t]||(this.sortedActions[t]=[]),this.sortedActions[t].push(e)}}getActions(e){return this.sortedActions||this.organize(),this.sortedActions[e.uuid]}}const Pn=x("debugusdzanimation"),qp=x("debugusdzanimationserialization");class qs{_start;get start(){return this._start===void 0&&(this._start=this.ext.getStartTimeByClip(this.clip)),this._start}get duration(){return this.clip?.duration??ke.restPoseClipDuration}get nearestAnimatedRoot(){return this._nearestAnimatedRoot}get clipName(){return this.clip?.name??"rest"}ext;root;_nearestAnimatedRoot=void 0;clip;speed;constructor(e,t,i){this.ext=e,this.root=t,this.clip=i,this._nearestAnimatedRoot=this.getNearestAnimatedRoot()}static isDescendantOf(e,t){let i=t;if(!i||!e)return!1;for(;i;){if(!i)return!1;if(i===e)return!0;i=i.parent}return!1}getNearestAnimatedRoot(){let e;try{for(const t of this.clip?.tracks??[]){const i=c.PropertyBinding.parseTrackName(t.name);let n=c.PropertyBinding.findNode(this.root,i.nodeName);if(n)if(!e)e=n;else{if(n===e||qs.isDescendantOf(e,n))continue;if(!qs.isDescendantOf(n,e)){for(;!qs.isDescendantOf(n,e)&&n.parent;)n=n.parent;qs.isDescendantOf(n,e)||console.error("USDZExporter: Animation clip targets multiple roots that are not parent/child. Please report a bug",this.root,this.clip,e,n)}e=n}}}catch(t){console.error("USDZExporter: Exception when trying to find nearest animated root. Please report a bug",t),e=void 0}return e}}class ke{clip;pos;rot;scale;root;target;duration=0;useRootMotion=!1;static frameRate=60;static animationDurationPadding=6/60;static restPoseClipDuration=6/60;constructor(e,t,i){if(this.root=e,this.target=t,this.clip=i,i?this.duration=i.duration:this.duration=ke.restPoseClipDuration,i&&i.tracks){const o=Math.max(...i.tracks.map(r=>r.times[r.times.length-1]));o!==this.duration&&(console.warn("USDZExporter: Animation clip duration does not match the maximum time value in the tracks.",i,o,this.duration),this.duration=o)}const n=S.getComponent(e,rt);n&&(this.useRootMotion=n.applyRootMotion)}addTrack(e){if(!this.clip){console.error("This is a rest clip but you're trying to add tracks to it – this is likely a bug");return}e.name.endsWith("position")?this.pos=e:e.name.endsWith("quaternion")?this.rot=e:e.name.endsWith("scale")?this.scale=e:(e.name.endsWith("activeSelf")?console.warn("[USDZ] Animation of enabled/disabled state is not supported for USDZ export and will NOT be exported: "+e.name+" on "+(this.root?.name??this.target.name)+". Animate scale 0/1 instead."):console.warn("[USDZ] Animation track type not supported for USDZ export and will NOT be exported: "+e.name+" on "+(this.root?.name??this.target.name)+". Only .position, .rotation, .scale are supported."),A()&&de("[USDZ] Some animations can't be exported. See console for details."))}getFrames(){return this.clip?Math.max(this.pos?.times?.length??0,this.rot?.times?.length??0,this.scale?.times?.length??0):2}getDuration(){return this.duration}getSortedTimesArray(e=!0,t=!0,i=!0){if(!this.clip)return[0,this.duration];const n=this.pos?.times,o=this.rot?.times,r=this.scale?.times,a=[];if(e&&n)for(const l of n)a.push(l);if(t&&o)for(const l of o)a.push(l);if(i&&r)for(const l of r)a.push(l);return a.includes(0)||a.push(0),a.sort((l,h)=>l-h),[...new Set(a)]}*getValues(e,t=!0,i=!0,n=!0){const o=new c.Vector3,r=new c.Quaternion,a=new c.Vector3(1,1,1),l=this.target,h=t?this.pos?.createInterpolant():void 0,d=i?this.rot?.createInterpolant():void 0,u=n?this.scale?.createInterpolant():void 0;h||o.set(l.position.x,l.position.y,l.position.z),d||r.set(l.quaternion.x,l.quaternion.y,l.quaternion.z,l.quaternion.w),u||a.set(l.scale.x,l.scale.y,l.scale.z),h&&h.valueSize!==3&&(h.valueSize=3),d&&d.valueSize!==4&&(d.valueSize=4),u&&u.valueSize!==3&&(u.valueSize=3);const p=0;for(let m=0-p;m<e.length+p;m++){let y=0,_=0;if(m<0?(y=e[0],_=y-ke.animationDurationPadding/2+1/60):m>=e.length?(y=e[e.length-1],_=y+ke.animationDurationPadding/2-1/60):(y=e[m],_=y),h){const g=h.evaluate(y);o.set(g[0],g[1],g[2])}if(d){const g=d.evaluate(y);r.set(g[0],g[1],g[2],g[3])}if(u){const g=u.evaluate(y);a.set(g[0],g[1],g[2])}if(this.useRootMotion&&l===this.root){const g=new c.Matrix4;g.compose(o,r,a),g.multiply(l.matrix),g.decompose(o,r,a)}yield{time:_,translation:o,rotation:r,scale:a,index:m}}}}class xu{get extensionName(){return"animation"}get animationData(){return this.dict}get registeredClips(){return this.clipToStartTime.keys()}get animatedRoots(){return this.rootTargetMap.keys()}get holdClipMap(){return this.clipToHoldClip}dict=new Map;rootTargetMap=new Map;rootAndClipToRegisteredAnimationMap=new Map;rootToRegisteredClip=new Map;lastClipEndTime=0;clipToStartTime=new Map;clipToHoldClip=new Map;serializers=[];injectRestPoses=!1;injectImplicitBehaviours=!1;constructor(e){this.injectRestPoses=e,this.injectImplicitBehaviours=e}getStartTimeCode(){return!this.injectRestPoses||this.rootAndClipToRegisteredAnimationMap.size===0?0:(ke.restPoseClipDuration+ke.animationDurationPadding)*60}getEndTimeCode(){let e=0;for(const[t,i]of this.rootAndClipToRegisteredAnimationMap){const n=i.start+i.duration;n>e&&(e=n)}return e*60}getClipCount(e){return this.rootToRegisteredClip.get(e)?.length??0??0}getStartTimeByClip(e){return e?this.clipToStartTime.has(e)?this.clipToStartTime.get(e):(console.error("USDZExporter: Missing start time for clip – please report a bug.",e),0):0}registerAnimation(e,t){if(!e)return null;this.rootTargetMap.has(e)||this.rootTargetMap.set(e,[]);const i=e.uuid+(t?.uuid??"-rest");if(this.rootAndClipToRegisteredAnimationMap.has(i))return this.rootAndClipToRegisteredAnimationMap.get(i);Pn&&console.log("registerAnimation",e,t);const n=this.injectRestPoses?1:0,o=(this.rootToRegisteredClip.get(e)?.length??0)+n,r=this.rootTargetMap.get(e),a=new Set(r);if(t&&t.tracks)for(const h of t.tracks){const d=c.PropertyBinding.parseTrackName(h.name),u=c.PropertyBinding.findNode(e,d.nodeName);if(!u){console.warn("no object found for track",h.name,"using "+e.name+" instead");continue}this.dict.has(u)||this.dict.set(u,[]);const p=this.dict.get(u);if(!p){console.warn("no transform data found for target ",u,"at slot "+o+", this is likely a bug");continue}a.delete(u),this.injectRestPoses&&!p[0]&&(console.log("Injecting rest pose",u,t,"at slot",o),p[0]=new ke(null,u,null));let m=p[o];m||(m=new ke(e,u,t),p[o]=m),m.addTrack(h),r?.includes(u)||r?.push(u)}Pn&&console.log("Unregistered nodes for this clip",a,"clip",t,"at slot",o,"for root",e,"targets",r);for(const h of a){const d=this.dict.get(h);if(!d)continue;if(this.injectRestPoses&&!d[0]){console.warn("Adding rest pose for ",h,t,"at slot",o,"This is likely a bug, should have been added earlier.");const p=new ke(null,h,null);d[0]=p}let u=d[o];u||(Pn&&console.log("Adding padding clip for ",h,t,"at slot",o),u=new ke(e,h,t),d[o]=u)}const l=new qs(this,e,t);if(this.rootAndClipToRegisteredAnimationMap.set(i,l),Pn&&console.log({root:e,clip:t,info:l}),t){const h=this.rootToRegisteredClip.get(e);if(h?h.push(t):this.rootToRegisteredClip.set(e,[t]),!this.clipToStartTime.get(t)){this.lastClipEndTime==null&&(this.lastClipEndTime=ke.restPoseClipDuration);let u=this.lastClipEndTime+ke.animationDurationPadding,p=u+t.duration;const m=Math.round(u*60)/60,y=Math.round(p*60)/60;Math.abs(m-u)<.01&&(u=m),Math.abs(y-p)<.01&&(p=y),u=Math.ceil(u),p=u+t.duration,this.clipToStartTime.set(t,u),this.lastClipEndTime=p}}return l}onAfterHierarchy(e){Pn&&console.log("Animation clips per animation target node",this.dict)}onAfterBuildDocument(e){Pn&&console.log("Animation data",{dict:this.dict,rootTargetMap:this.rootTargetMap,rootToRegisteredClip:this.rootToRegisteredClip});for(const t of this.rootTargetMap.keys()){const i=this.rootTargetMap.get(t);if(!i)continue;let n;const o=[];for(const r of i){const a=this.dict.get(r);if(!a){console.error("No data found for target on USDZ export – please report a bug!",r);continue}n===void 0&&(n=a?.length),n!==a?.length&&console.error("Different array lengths for targets – please report a bug!",a);for(let l=0;l<a.length;l++){let h=a[l];if(!h){const u=l-(this.injectRestPoses?1:0);a[l]=new ke(null,r,this.rootToRegisteredClip.get(t)[u]),h=a[l]}const d=h.getDuration();if(o[l]===void 0)o[l]=d;else if(o[l]!==d){console.error("Error during UDSZ export: Encountered different animation durations for animated targets. Please report a bug!",{datas:a,target:r}),o[l]=d;continue}}}}for(const t of this.serializers){const i=t.model?.parent,n=i?.isDynamic===!0;qp&&console.log(n,t.model?.parent),n&&t.registerCallback(i)}}onExportObject(e,t,i){S.foreachComponent(e,o=>{const r=o;typeof r.createAnimation=="function"&&r.createAnimation(this,t,i)},!1);const n=new nM(e,this);this.serializers.push(n),n.registerCallback(t)}}class nM{model=void 0;object;animationData;ext;callback;constructor(e,t){this.object=e,this.animationData=t.animationData,this.ext=t}registerCallback(e){this.model&&this.callback&&this.model.removeEventListener("serialize",this.callback),this.callback||(this.callback=this.onSerialize.bind(this)),qp&&console.log("REPARENT",e),this.model=e,this.callback&&this.model.addEventListener("serialize",this.callback)}skinnedMeshExport(e,t,i){const n=this.model,o=this.animationData;if(n&&n.skinnedMesh){let r=function(k){const U=[];for(const[z,K]of k){let J=`${z} : [`;const he=[];for(const me of K)he.push(`(${te(me.x)}, ${te(me.y)}, ${te(me.z)})`);J=J.concat(he.join(", ")),J=J.concat("],"),U.push(J)}return U},a=function(k){const U=[];for(const[z,K]of k){let J=`${z} : [`;const he=[];for(const me of K)he.push(`(${te(me.w)}, ${te(me.x)}, ${te(me.y)}, ${te(me.z)})`);J=J.concat(he.join(", ")),J=J.concat("],"),U.push(J)}return U},l=function(k){let U,z=!0;const K=new Map;for(const[he,me]of k){U===void 0&&(U=me.length),U!==me.length&&(z=!1);let Ge=0;for(const wi of me)Ge++,wi||(K.has(he)||K.set(he,[]),K.get(he).push(Ge))}Pn&&console.log("Bone count: ",k.size,"TransformData entries per bone: ",U,"Undefined bone entries: ",K),console.assert(z,"All bones should have the same number of TransformData entries",k),console.assert(K.size===0,"All TransformData entries should be set",K);const J=[];for(const[he,me]of k)for(let Ge=0;Ge<me.length;Ge++){const wi=me[Ge],yh=i.getStartTimeByClip(wi.clip);J.length<=Ge&&J.push({pos:[],rot:[],scale:[],timeOffset:yh});const ks=J[Ge];ks.pos.push(...wi.getSortedTimesArray(!0,!1,!1)),ks.rot.push(...wi.getSortedTimesArray(!1,!0,!1)),ks.scale.push(...wi.getSortedTimesArray(!1,!1,!0))}for(const he of J)he.pos.sort((me,Ge)=>me-Ge),he.rot.sort((me,Ge)=>me-Ge),he.scale.sort((me,Ge)=>me-Ge),he.pos=[...new Set(he.pos)],he.rot=[...new Set(he.rot)],he.scale=[...new Set(he.scale)];return J},h=function(k,U,z){const K=new Map,J=new Map,he=new Map,me=U.length;for(const Ge of z){const wi=k.get(Ge);let yh;wi?console.assert(wi.length===me,"We should have the same number of TransformData entries for each bone",wi,U):yh=new ke(null,Ge,null);for(let ks=0;ks<me;ks++){const nf=wi?wi[ks]:yh,Lr=U[ks];for(const{time:tl,translation:il}of nf.getValues(Lr.pos,!0,!1,!1)){const Hi=(tl+Lr.timeOffset)*60;K.has(Hi)||K.set(Hi,new Array),K.get(Hi).push(il.clone())}for(const{time:tl,rotation:il}of nf.getValues(Lr.rot,!1,!0,!1)){const Hi=(tl+Lr.timeOffset)*60;J.has(Hi)||J.set(Hi,new Array),J.get(Hi).push(il.clone())}for(const{time:tl,scale:il}of nf.getValues(Lr.scale,!1,!1,!0)){const Hi=(tl+Lr.timeOffset)*60;he.has(Hi)||he.set(Hi,new Array),he.get(Hi).push(il.clone())}}}return{position:K.size==0?void 0:K,quaternion:J.size==0?void 0:J,scale:he.size==0?void 0:he}},d=function(k){const U=[];for(const z of k)U.push(`(${te(z.x)}, ${te(z.y)}, ${te(z.z)})`);return U.join(", ")},u=function(k){const U=[];for(const z of k)U.push(`(${te(z.w)}, ${te(z.x)}, ${te(z.y)}, ${te(z.z)})`);return U.join(", ")},p=function(k){const U=new Map;if(Pn){const z=new Array;for(const[K,J]of o)z.push(K.uuid+": "+J.length+" "+J.map(he=>he.clip?.uuid.substring(0,6)).join(" "));console.log(`getPerBoneTransformData
1274
1274
  `+z.join(`
1275
- `))}for(const z of k){const K=o.get(z);K&&U.set(z,K)}return U},m=function(k){const U=p(k),z=l(U);return h(U,z,k)};const y=n.skinnedMesh.skeleton,_=new Array,g=[],w=[];for(const k of y.bones){g.push(k),w.push(k.uuid);const U=y.boneInverses[y.bones.indexOf(k)];_.push({bone:k,inverse:U})}let b=1e4;for(;w.length<y.bones.length&&b-- >0;)for(const k of g){const U=k.children;for(const z of U)if(w.indexOf(z.uuid)===-1&&y.bones.indexOf(z)!==-1){g.push(z),w.push(z.uuid);const K=y.boneInverses[y.bones.indexOf(z)];_.push({bone:z,inverse:K})}}b<=0&&console.error("Failed to sort bones in skinned mesh",n.skinnedMesh,y.bones,w);for(const k of rw(y.bones))_.push({bone:k,inverse:k.matrixWorld.clone().invert()});const v=_[0].bone.parent;v||console.error("No bone parent found for skinned mesh during USDZ export",n.skinnedMesh),_.sort((k,U)=>ua(k.bone,v)>ua(U.bone,v)?1:-1);const R=t.quickLookCompatible,O=[],M=[],T=[],D=[];for(const{bone:k}of _){if(R){const U=k.scale;U.x==0&&(U.x=1e-5),U.y==0&&(U.y=1e-5),U.z==0&&(U.z=1e-5),O.push(new c.Matrix4().compose(k.position,k.quaternion,k.scale))}else O.push(k.matrix.clone());M.push(k.position),T.push(k.quaternion),D.push(k.scale)}const I=_.map(k=>'"'+ua(k.bone,v)+'"').join(", "),V=_.map(k=>W_(k.inverse.clone().invert())).join(", ");e.beginBlock('def Skeleton "Rig"'),e.appendLine(`uniform matrix4d[] bindTransforms = [${V}]`),e.appendLine(`uniform token[] joints = [${I}]`),e.appendLine('uniform token purpose = "guide"'),e.appendLine(`uniform matrix4d[] restTransforms = [${O.map(k=>W_(k)).join(", ")}]`);const W=m(_.map(k=>k.bone));if(Pn){let k=1e7,U=0;for(const z of W.position?.keys()??[])k=Math.min(k,z),U=Math.max(U,z);console.log("Time samples",k,U,W)}if(e.beginBlock('def SkelAnimation "_anim"'),e.appendLine(`uniform token[] joints = [${I}]`),e.appendLine(`quatf[] rotations = [${u(T)}]`),W&&W.quaternion){e.beginBlock("quatf[] rotations.timeSamples = {","");const k=a(W.quaternion);for(const U of k)e.appendLine(U);e.closeBlock()}if(e.appendLine(`half3[] scales = [${d(D)}]`),W&&W.scale){e.beginBlock("half3[] scales.timeSamples = {","");const k=r(W.scale);for(const U of k)e.appendLine(U);e.closeBlock()}if(e.appendLine(`float3[] translations = [${d(M)}]`),W&&W.position){e.beginBlock("float3[] translations.timeSamples = {","");const k=r(W.position);for(const U of k)e.appendLine(U);e.closeBlock()}e.closeBlock(),e.closeBlock()}}onSerialize(e,t){if(!this.model)return;const i=this.animationData.get(this.object);if(i)for(let d=0;d<i.length;d++)i[d]===void 0&&(i[d]=new ke(null,this.object,null));const n=this.ext;this.skinnedMeshExport(e,t,n);const o=this.object,r=this.model,a=this.animationData.get(o);if(!a||o.isSkinnedMesh)return;qp&&console.log("SERIALIZE",this.model.name,this.object.type,a);const l=Intl.NumberFormat("en-US",{maximumFractionDigits:3,minimumFractionDigits:0,useGrouping:!1});function h(d,u){if(d.some(m=>m&&{position:m.pos,rotation:m.rot,scale:m.scale}[u])){switch(u){case"position":r.needsTranslate=!0,e.beginBlock("double3 xformOp:translate.timeSamples = {","");break;case"rotation":r.needsOrient=!0,e.beginBlock("quatf xformOp:orient.timeSamples = {","");break;case"scale":r.needsScale=!0,e.beginBlock("double3 xformOp:scale.timeSamples = {","");break}for(let m=0;m<d.length;m++){const y=d[m];if(!y)continue;const _=n.getStartTimeByClip(y.clip),g=y.getSortedTimesArray(u==="position",u==="rotation",u==="scale");if(!g||g.length===0){console.error("got an animated object but no time values?",o,y);continue}const w=!y.clip,b=u==="position"&&(y.pos||w),v=u==="rotation"&&(y.rot||w),R=u==="scale"&&(y.scale||w);if(b||v||R){const O=y.clip?.name??"rest",M=y.getDuration();Pn&&console.log("Write .timeSamples:",O,_,M,d),e.appendLine("# "+O+": start="+l.format(_*ke.frameRate)+", length="+l.format(M*ke.frameRate)+", frames="+y.getFrames())}if(b)for(const{time:O,translation:M}of y.getValues(g,!0,!1,!1)){const D=`${l.format((_+O)*ke.frameRate)}: (${te(M.x)}, ${te(M.y)}, ${te(M.z)}),`;e.appendLine(D)}if(v)for(const{time:O,rotation:M}of y.getValues(g,!1,!0,!1)){const D=`${l.format((_+O)*ke.frameRate)}: (${te(M.w)}, ${te(M.x)}, ${te(M.y)}, ${te(M.z)}),`;e.appendLine(D)}if(R)for(const{time:O,scale:M}of y.getValues(g,!1,!1,!0)){const D=`${l.format((_+O)*ke.frameRate)}: (${te(M.x)}, ${te(M.y)}, ${te(M.z)}),`;e.appendLine(D)}}e.closeBlock()}}h(a,"position"),h(a,"rotation"),h(a,"scale")}}const sM=x("debugusdz");class br{static getName(e){const t=e.split(".").pop();let n=e.split(".").slice(0,-1).join(".").split("/").pop()?.replace(".","_");return n||(n="Audio_"+Math.random().toString(36).substring(2,15)),mi(n)+"."+t}get extensionName(){return"Audio"}files=new Array;onExportObject(e,t,i){const n=S.getComponents(e,pi);if(n.length)for(const o of n){if(!o.clip||typeof o.clip!="string"||!o.playOnAwake)continue;const r=o.clip.split("/").pop()||"Audio",a=br.getName(o.clip),l=mi(a);if(!this.files.some(h=>h.path===o.clip)){this.files.push({path:o.clip,name:a});const h=a.toLowerCase();i.quickLookCompatible&&!h.endsWith(".mp3")&&!h.endsWith(".wav")&&!h.endsWith(".m4a")&&console.error("Audio file "+o.clip+" from "+o.name+" is not an MP3 or WAV file. QuickLook may not support playing it.")}i.quickLookCompatible||t.addEventListener("serialize",(h,d)=>{h.appendLine(),h.beginBlock(`def SpatialAudio "${l}"`,"(",!1),h.appendLine(`displayName = "${r}"`),h.closeBlock(")"),h.beginBlock(),h.appendLine(`uniform asset filePath = @audio/${a}@`),h.appendLine(`uniform token auralMode = "${o.spatialBlend>0?"spatial":"nonSpatial"}"`),h.appendLine(`uniform token playbackMode = "${o.loop?"loopFromStage":"onceFromStart"}"`),h.appendLine(`uniform float gain = ${o.volume}`),h.closeBlock()})}}async onAfterSerialize(e){for(const t of this.files){const i="audio/"+t.name;if(e.files[i]){sM&&console.warn("Audio file with name "+i+" already exists in the context. Skipping.");continue}const r=await(await(await fetch(t.path)).blob()).arrayBuffer(),a=new Uint8Array(r);e.files[i]=a}}}var oM=Object.defineProperty,Ee=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&oM(e,t,n),n};const Q_=x("debugusdzbehaviours");function zc(s){s&&(s.getComponentInParent(xa)||(A()&&console.debug('Raycaster on "'+s.name+'" was automatically added, because no raycaster was found in the parent hierarchy.'),s.addComponent(fi)))}class vr extends E{object;target;duration=1;relativeMotion=!1;coroutine=null;targetPos=new c.Vector3;targetRot=new c.Quaternion;targetScale=new c.Vector3;start(){zc(this.gameObject)}onPointerEnter(){this.context.input.setCursor("pointer")}onPointerExit(){this.context.input.unsetCursor("pointer")}onPointerClick(e){e.use(),this.coroutine&&this.stopCoroutine(this.coroutine),this.relativeMotion?this.coroutine=this.startCoroutine(this.moveRelative()):this.coroutine=this.startCoroutine(this.moveToTarget())}*moveToTarget(){if(!this.target||!this.object)return;const e=X(this.object).clone(),t=X(this.target).clone(),i=ue(this.object).clone(),n=ue(this.target).clone(),o=je(this.object).clone(),r=je(this.target).clone(),a=e.distanceTo(t),l=i.angleTo(n),h=o.distanceTo(r);if(a<.01&&l<.01&&h<.01){ot(this.object,t),on(this.object,n),ga(this.object,r),this.coroutine=null;return}let d=0,u=0;for(;d<1;)d+=this.context.time.deltaTime/this.duration,d>1&&(d=1),u=d<.5?4*d*d*d:1-Math.pow(-2*d+2,3)/2,this.targetPos.lerpVectors(e,t,u),this.targetRot.slerpQuaternions(i,n,u),this.targetScale.lerpVectors(o,r,u),ot(this.object,this.targetPos),on(this.object,this.targetRot),ga(this.object,this.targetScale),yield;this.coroutine=null}*moveRelative(){if(!this.target||!this.object)return;const e=this.object.position.clone(),t=this.object.quaternion.clone(),i=this.object.scale.clone(),n=this.target.position.clone(),o=this.target.quaternion.clone(),r=this.target.scale.clone();n.applyQuaternion(this.object.quaternion),this.targetPos.copy(this.object.position).add(n),this.targetRot.copy(this.object.quaternion).multiply(o),this.targetScale.copy(this.object.scale).multiply(r);let a=0,l=0;for(;a<1;)a+=this.context.time.deltaTime/this.duration,a>1&&(a=1),l=a<.5?4*a*a*a:1-Math.pow(-2*a+2,3)/2,this.object.position.lerpVectors(e,this.targetPos,l),this.object.quaternion.slerpQuaternions(t,this.targetRot,l),this.object.scale.lerpVectors(i,this.targetScale,l),yield;this.coroutine=null}beforeCreateDocument(e){if(this.target&&this.object&&this.gameObject){const t=new gt("Move to "+this.target?.name,St.tapTrigger(this.gameObject),le.transformAction(this.object,this.target,this.duration,this.relativeMotion?"relative":"absolute"));e.addBehavior(t)}}}Ee([f(c.Object3D)],vr.prototype,"object");Ee([f(c.Object3D)],vr.prototype,"target");Ee([f()],vr.prototype,"duration");Ee([f()],vr.prototype,"relativeMotion");const Su=class At extends E{materialToSwitch;variantMaterial;fadeDuration=0;start(){this._objectsWithThisMaterial=this.objectsWithThisMaterial,zc(this.gameObject),A()&&this._objectsWithThisMaterial.length<=0&&console.warn('ChangeMaterialOnClick: No objects found with material "'+this.materialToSwitch?.name+'"')}onPointerEnter(e){this.context.input.setCursor("pointer")}onPointerExit(e){this.context.input.unsetCursor("pointer")}onPointerClick(e){if(e.use(),!!this.variantMaterial)for(let t=0;t<this.objectsWithThisMaterial.length;t++){const i=this.objectsWithThisMaterial[t];i.material=this.variantMaterial}}_objectsWithThisMaterial=null;get objectsWithThisMaterial(){return this._objectsWithThisMaterial!=null?this._objectsWithThisMaterial:(this._objectsWithThisMaterial=[],this.variantMaterial&&this.materialToSwitch&&this.context.scene.traverse(e=>{if(e instanceof c.Mesh)if(Array.isArray(e.material)){for(const t of e.material)if(t===this.materialToSwitch){this.objectsWithThisMaterial.push(e);break}}else e.material===this.materialToSwitch?this.objectsWithThisMaterial.push(e):L0(e.material,this.materialToSwitch)&&this.objectsWithThisMaterial.push(e)}),this._objectsWithThisMaterial)}selfModel;targetModels;static _materialTriggersPerId={};static _startHiddenBehaviour=null;static _parallelStartHiddenActions=[];async beforeCreateDocument(e,t){this.targetModels=[],At._materialTriggersPerId={},At.variantSwitchIndex=0,this.materialToSwitch&&await ne.NEEDLE_progressive.assignTextureLOD(this.materialToSwitch,0),this.variantMaterial&&await ne.NEEDLE_progressive.assignTextureLOD(this.variantMaterial,0)}createBehaviours(e,t,i){this.objectsWithThisMaterial.find(o=>o.uuid===t.uuid)&&this.targetModels.push(t),this.gameObject.uuid===t.uuid&&(this.selfModel=t,this.materialToSwitch&&(At._materialTriggersPerId[this.materialToSwitch.uuid]||(At._materialTriggersPerId[this.materialToSwitch.uuid]=[]),At._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(e,t){if(!this.materialToSwitch)return;const i=At._materialTriggersPerId[this.materialToSwitch.uuid];if(i){const n={};for(const o of i){const r=o.createVariants();r&&r.length>0&&(n[o.selfModel.uuid]=r)}for(const o of i){const r=[];for(const a in n)a!==o.selfModel.uuid&&r.push(...n[a]);o.createAndAttachBehaviors(e,n[o.selfModel.uuid],r)}}delete At._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(e,t,i){const n=[],o=Math.max(0,this.fadeDuration);n.push(le.fadeAction([...this.targetModels,...i],o,!1)),n.push(le.fadeAction(t,o,!0)),e.addBehavior(new gt("Select_"+this.selfModel.name,St.tapTrigger(this.selfModel),le.parallel(...n))),At._parallelStartHiddenActions.push(...t),At._startHiddenBehaviour||(At._startHiddenBehaviour=new gt("StartHidden_"+this.selfModel.name,St.sceneStartTrigger(),le.fadeAction(At._parallelStartHiddenActions,o,!1)),e.addBehavior(At._startHiddenBehaviour))}static getMaterialName(e){return mi(e.name||"Material")+"_"+e.id}static variantSwitchIndex=0;createVariants(){if(!this.variantMaterial)return null;const e=[];for(const t of this.targetModels){const i=t.clone();i.name+="_Variant_"+At.variantSwitchIndex+++"_"+At.getMaterialName(this.variantMaterial),i.displayName=i.displayName+": Variant with material "+this.variantMaterial.name,i.material=this.variantMaterial,i.geometry=t.geometry,i.transform=t.transform,(!t.parent||!t.parent.isEmpty())&&Ne.createEmptyParent(t),t.parent&&t.parent.add(i),e.push(i)}return e}};Ee([f(c.Material)],Su.prototype,"materialToSwitch");Ee([f(c.Material)],Su.prototype,"variantMaterial");Ee([f()],Su.prototype,"fadeDuration");let Og=Su;const Nc=class Pe extends E{target;toggleOnClick=!1;targetState=!0;hideSelf=!0;start(){zc(this.gameObject)}onPointerEnter(){this.context.input.setCursor("pointer")}onPointerExit(){this.context.input.unsetCursor("pointer")}onPointerClick(e){e.use(),!this.toggleOnClick&&this.hideSelf&&(this.gameObject.visible=!1),this.target&&(this.target.visible=this.toggleOnClick?!this.target.visible:this.targetState)}selfModel;selfModelClone;targetModel;toggleModel;createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.selfModel=t,this.selfModelClone=t.clone())}stateBeforeCreatingDocument=!1;targetStateBeforeCreatingDocument=!1;static clonedToggleIndex=0;static wasVisible=Symbol("usdz_SetActiveOnClick_wasVisible");static toggleClone=Symbol("clone for toggling");static reverseToggleClone=Symbol("clone for reverse toggling");beforeCreateDocument(){this.target&&(this.gameObject[Pe.wasVisible]===void 0&&(this.gameObject[Pe.wasVisible]=this.gameObject.activeSelf),this.target[Pe.wasVisible]===void 0&&(this.target[Pe.wasVisible]=this.target.activeSelf),this.stateBeforeCreatingDocument=this.gameObject[Pe.wasVisible],this.targetStateBeforeCreatingDocument=this.target[Pe.wasVisible],this.gameObject.visible=!0,this.target.visible=!0)}afterCreateDocument(e,t){if(!this.target)return;this.targetModel=t.document.findById(this.target.uuid);const i=this.selfModel;if(this.selfModel&&this.targetModel){let n=this.selfModel,o=this.targetState;if(this.toggleOnClick)if(o=!this.targetStateBeforeCreatingDocument,!this.selfModelClone.geometry)(!this.selfModel.parent||this.selfModel.parent.isEmpty())&&Sg.createEmptyParent(this.selfModel),this.toggleModel=this.selfModel.deepClone(),this.toggleModel.name+="_toggle",this.selfModel.parent.add(this.toggleModel);else{if(!this.gameObject[Pe.toggleClone]){const l=this.selfModelClone.clone();l.setMatrix(new c.Matrix4),l.name+="_toggle"+Pe.clonedToggleIndex++,i.add(l),this.gameObject[Pe.toggleClone]=l,console.warn("USDZExport: Toggle "+this.gameObject.name+" doesn't have geometry. It will be deep cloned and nested behaviours will likely not work.")}const a=this.gameObject[Pe.toggleClone];if(!this.gameObject[Pe.reverseToggleClone]){const l=this.selfModelClone.clone();l.setMatrix(new c.Matrix4),l.name+="_toggleReverse"+Pe.clonedToggleIndex++,i.add(l),this.gameObject[Pe.reverseToggleClone]=l}this.toggleModel=this.gameObject[Pe.reverseToggleClone],(!this.toggleModel.geometry||!a.geometry)&&console.error("triggers without childs and without geometry won't work!",this,i.geometry),n=a,i.geometry=null,i.material=null}if(this.toggleModel){if(this.toggleOnClick){const a=[];a.push(le.fadeAction(n,0,!1)),a.push(le.fadeAction(this.toggleModel,0,!0)),a.push(le.fadeAction(this.targetModel,0,o)),e.addBehavior(new gt("Toggle_"+n.name+"_ToggleTo"+(o?"On":"Off"),St.tapTrigger(n),le.parallel(...a)));const l=[];l.push(le.fadeAction(this.toggleModel,0,!1)),l.push(le.fadeAction(n,0,!0)),l.push(le.fadeAction(this.targetModel,0,!o)),e.addBehavior(new gt("Toggle_"+n.name+"_ToggleTo"+(o?"Off":"On"),St.tapTrigger(this.toggleModel),le.parallel(...l)))}}else{const a=[];this.hideSelf&&a.push(le.fadeAction(n,0,!1)),a.push(le.fadeAction(this.targetModel,0,o)),e.addBehavior(new gt("Toggle_"+n.name+"_ToggleTo"+(o?"On":"Off"),St.tapTrigger(n),a.length>1?le.parallel(...a):a[0]))}const r=new Array;this.targetStateBeforeCreatingDocument||r.push(this.targetModel),this.stateBeforeCreatingDocument||r.push(i),this.toggleModel&&r.push(this.toggleModel),Ei.add(r,e)}}afterSerialize(e,t){this.gameObject[Pe.wasVisible]!==void 0&&(this.gameObject.visible=this.gameObject[Pe.wasVisible],delete this.gameObject[Pe.wasVisible]),this.target&&this.target[Pe.wasVisible]!==void 0&&(this.target.visible=this.target[Pe.wasVisible],delete this.target[Pe.wasVisible]),delete this.gameObject[Pe.toggleClone],delete this.gameObject[Pe.reverseToggleClone]}};Ee([f(c.Object3D)],Nc.prototype,"target");Ee([f()],Nc.prototype,"toggleOnClick");Ee([f()],Nc.prototype,"targetState");Ee([f()],Nc.prototype,"hideSelf");let Mg=Nc;class Ei extends E{static _fadeBehaviour;static _fadeObjects=[];static add(e,t){const i=Array.isArray(e)?e:[e];for(const n of i)Ei._fadeObjects.includes(n)||(console.log("adding hide on start",n),Ei._fadeObjects.push(n));Ei._fadeBehaviour===void 0&&(Ei._fadeBehaviour=new gt("HideOnStart",St.sceneStartTrigger(),le.fadeAction(Ei._fadeObjects,0,!1)),t.addBehavior(Ei._fadeBehaviour))}start(){S.setActive(this.gameObject,!1)}createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.wasVisible||Ei.add(t,e))}wasVisible=!1;beforeCreateDocument(){this.wasVisible=S.isActiveSelf(this.gameObject)}}class La extends E{target;duration=.5;motionType="bounce";beforeCreateDocument(){}createBehaviours(e,t,i){if(this.target&&t.uuid===this.gameObject.uuid){const n=new gt("emphasize "+this.name,St.tapTrigger(this.gameObject),le.emphasize(this.target,this.duration,this.motionType,void 0,"basic"));e.addBehavior(n)}}afterCreateDocument(e,t){}}Ee([f()],La.prototype,"target");Ee([f()],La.prototype,"duration");Ee([f()],La.prototype,"motionType");class to extends E{target;clip="";toggleOnClick=!1;trigger="tap";start(){zc(this.gameObject)}ensureAudioSource(){if(!this.target){const e=this.gameObject.addComponent(pi);e&&(this.target=e,e.spatialBlend=1,e.volume=1,e.loop=!1,e.preload=!0)}}onPointerEnter(){this.context.input.setCursor("pointer")}onPointerExit(){this.context.input.unsetCursor("pointer")}onPointerClick(e){e.use(),!(!this.target?.clip&&!this.clip)&&(this.ensureAudioSource(),this.target&&(this.target.isPlaying&&this.toggleOnClick?this.target.stop():(!this.toggleOnClick&&this.target.isPlaying&&this.target.stop(),this.clip?this.target.play(this.clip):this.target.play())))}createBehaviours(e,t,i){if(!(!this.target&&!this.clip)&&t.uuid===this.gameObject.uuid){const n=this.clip?this.clip:this.target?this.target.clip:void 0;if(!n||typeof n!="string")return;const o=this.target?this.target.gameObject:this.gameObject;br.getName(n);const r=this.target?this.target.volume:1,a=this.target&&this.target.spatialBlend==0?"nonSpatial":"spatial";let l=!1;this.gameObject.traverse(p=>{p instanceof c.Mesh&&p.visible&&(l=!0)}),l=!0;const h=e.addAudioClip(n);let d=le.playAudioAction(o,h,"play",r,a);this.target&&this.target.loop&&(d=le.sequence(d).makeLooping());const u=this.name?"_"+this.name:"";if(l&&this.trigger==="tap"){this.toggleOnClick&&(d.multiplePerformOperation="stop");const p=new gt("playAudio"+u,St.tapTrigger(t),d);e.addBehavior(p)}if(this.target&&this.target.playOnAwake&&this.target.enabled)if(l&&this.trigger==="tap")console.warn("USDZExport: Audio sources that are played on tap can't also auto-play at scene start due to a QuickLook bug.");else{const p=new gt("playAudioOnStart"+u,St.sceneStartTrigger(),d);e.addBehavior(p)}}}}Ee([f(pi)],to.prototype,"target");Ee([f(URL)],to.prototype,"clip");Ee([f()],to.prototype,"toggleOnClick");const kg=class vn extends E{animator;stateName;trigger="tap";animation;get target(){return this.animator?.gameObject||this.animation?.gameObject}start(){zc(this.gameObject)}onPointerEnter(){this.context.input.setCursor("pointer")}onPointerExit(){this.context.input.unsetCursor("pointer")}onPointerClick(e){e.use(),this.target&&this.stateName&&this.animator?.play(this.stateName,0,0,.1)}selfModel;stateAnimationModel;animationSequence=new Array;animationLoopAfterSequence=new Array;randomOffsetNormalized=0;createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.selfModel=t)}static animationActions=[];static rootsWithExclusivePlayback=new Set;afterSerialize(){if(vn.rootsWithExclusivePlayback.size>1){const e='Multiple root objects targeted by more than one animation. To work around QuickLook bug FB13410767, animations will be set as "exclusive" and activating them will stop other animations being marked as exclusive.';A()&&de(e),console.warn(e,...vn.rootsWithExclusivePlayback)}vn.animationActions=[],vn.rootsWithExclusivePlayback=new Set}afterCreateDocument(e,t){if(this.animationSequence===void 0&&this.animationLoopAfterSequence===void 0||!this.stateAnimationModel||!this.target)return;const i=t.document,n=t.extensions.find(a=>a instanceof xu);if(!n)return;const o=n.getClipCount(this.target)>1;o&&(A()&&console.warn("Setting exclusive playback for "+this.target.name+"@"+this.stateName+" because it has "+n.getClipCount(this.target)+" animations. This works around QuickLook bug FB13410767."),vn.rootsWithExclusivePlayback.add(this.target));const r=this.name?this.name:"";i.traverse(a=>{if(a.uuid===this.target?.uuid){const l=vn.getActionForSequences(i,a,this.animationSequence,this.animationLoopAfterSequence,this.randomOffsetNormalized),h=new gt(this.trigger+"_"+r+"_toPlayAnimation_"+this.stateName+"_on_"+this.target?.name,this.trigger=="tap"?St.tapTrigger(this.selfModel):St.sceneStartTrigger(),l);o&&h.makeExclusive(!0),e.addBehavior(h)}})}static getActionForSequences(e,t,i,n,o){const r=(l,h)=>{let d=vn.animationActions.find(u=>u.affectedObjects==l&&u.start==h.start&&u.duration==h.duration&&u.animationSpeed==h.speed);return d||(d=le.startAnimationAction(l,h),vn.animationActions.push(d)),d},a=le.sequence();if(i&&i.length>0)for(const l of i)a.addAction(r(t,l));if(n&&n.length>0){const l=a.actions.length==0?a:le.sequence();for(const h of n)l.addAction(r(t,h));l.makeLooping(),a!==l&&a.addAction(l)}return o&&o>0&&a.actions.unshift(le.waitAction(o)),a}static getAndRegisterAnimationSequences(e,t,i){if(!t)return;const n=t.getComponent(rt),o=t.getComponent(Ct);if(!n&&!o)return;if(n&&!i)throw new Error("PlayAnimationOnClick: No stateName specified for animator "+n.name+" on "+t.name);let r=[],a=[];if(o){const y=e.registerAnimation(t,o.clip);y&&(o.loop?a.push(y):r.push(y));let _=0;if(o.minMaxOffsetNormalized){const g=o.minMaxOffsetNormalized.x,w=o.minMaxOffsetNormalized.y;_=(o.clip?.duration||1)*(g+Math.random()*(w-g))}return{animationSequence:r,animationLoopAfterSequence:a,randomTimeOffset:_}}const l=n?.runtimeAnimatorController;let h=l?.findState(i),d=[],u=[];if(l&&h){const y=new Array;y.push(h);let _=!1;for(;y.length<100;){if(!h||h===null||!h.transitions||h.transitions.length===0){h.motion?.isLooping&&(_=!0);break}const g=h.transitions.find(b=>b.conditions.length===0),w=g?l.getState(g.destinationState,0):null;if(w&&y.includes(w)){h=w,_=!0;break}else if(g){if(h=w,!h)break;y.push(h)}else{_=h.motion?.isLooping??!1;break}}if(_&&h){const g=y.indexOf(h);d=y.slice(0,g),u=y.slice(g),Q_&&console.log("found loop from "+i,"states until loop",d,"states looping",u)}else d=y,u=[],Q_&&console.log("found no loop from "+i,"states",d);if(!u.length){const g=d[d.length-1],w=g.motion?.clip;if(w){let b;if(e.holdClipMap.has(w))b=e.holdClipMap.get(w);else{const v=g.name+"_hold";b=w.clone(),b.duration=1,b.name=v;const R=w.duration;b.tracks=w.tracks.map(O=>{const M=O.clone();M.times=new Float32Array([0,R]);const T=O.values.length,D=O.getValueSize(),I=O.values.slice(T-D,T);return M.values=new Float32Array(2*D),M.values.set(I,0),M.values.set(I,D),M}),b.name=v,e.holdClipMap.set(w,b)}if(b){const v={name:b.name,motion:{clip:b,isLooping:!1,name:b.name},speed:1,transitions:[],behaviours:[],hash:g.hash+1};u.push(v)}}}}if(d.length===1&&(!d[0].motion?.clip||d[0].motion?.clip.tracks?.length===0)){r=new Array;const y=e.registerAnimation(t,null);y&&r.push(y);return}if(d=d.filter(y=>y.motion?.clip&&y.motion?.clip.tracks?.length>0),u=u.filter(y=>y.motion?.clip&&y.motion?.clip.tracks?.length>0),d.length===0&&u.length===0){console.warn("No clips found for state "+i+" on "+n?.name+", can't export animation data");return}const p=(y,_)=>{if(!t)return;const g=e.registerAnimation(t,y.motion.clip??null);g?(g.speed=y.speed,_.push(g)):console.warn("Couldn't register animation for state "+y.name+" on "+n?.name)};if(d.length>0){r=new Array;for(const y of d)p(y,r)}if(u.length>0){a=new Array;for(const y of u)p(y,a)}let m=0;if(n&&l&&n.minMaxOffsetNormalized){const y=n.minMaxOffsetNormalized.x,_=n.minMaxOffsetNormalized.y;m=((d.length?d[0]:u.length?u[0]:null)?.motion.clip?.duration||1)*(y+Math.random()*(_-y))}return{animationSequence:r,animationLoopAfterSequence:a,randomTimeOffset:m}}createAnimation(e,t,i){if(!this.target||!this.animator&&!this.animation)return;const n=vn.getAndRegisterAnimationSequences(e,this.target,this.stateName);n&&(this.animationSequence=n.animationSequence,this.animationLoopAfterSequence=n.animationLoopAfterSequence,this.randomOffsetNormalized=n.randomTimeOffset,this.stateAnimationModel=t)}};Ee([f(rt)],kg.prototype,"animator");Ee([f()],kg.prototype,"stateName");let dc=kg;class Ia extends E{getType(){}target;getDuration(){}}Ee([f(c.Object3D)],Ia.prototype,"target");class Vc extends E{target}Ee([f(Ia)],Vc.prototype,"target");class $c extends Ia{type=1;duration=1;getType(){switch(this.type){case 1:return"hide";case 0:return"show"}}getDuration(){return this.duration}}Ee([f()],$c.prototype,"type");Ee([f()],$c.prototype,"duration");class Eg extends Vc{}class Zs{static _instance;static create(){return new Zs}static getOrCreate(){return this._instance||(this._instance=this.create()),this._instance}get isSecureConnection(){return window.location.protocol==="https:"}get quicklookButton(){return this._quicklookButton}_quicklookButton;get arButton(){return this._arButton}_arButton;get vrButton(){return this._vrButton}_vrButton;get sendToQuestButton(){return this._sendToQuestButton}_sendToQuestButton;get qrButton(){return Ji.getOrCreate().createQRCode()}createQuicklookButton(){if(this._quicklookButton)return this._quicklookButton;const e=document.createElement("button");this._quicklookButton=e,e.dataset.needle="quicklook-button";const t=exports.DeviceUtilities.supportsQuickLookAR();e.innerText="View in AR",e.prepend(pt("view_in_ar"));let i=!1,n=null;return e.addEventListener("click",()=>{n=ka(sn),n||(i=!0,n=new sn),i&&(n.objectToExport=N.Current.scene),n?(e.classList.add("this-mode-is-requested"),n.exportAndOpen().then(()=>{e.classList.remove("this-mode-is-requested")}).catch(o=>{e.classList.remove("this-mode-is-requested"),console.error(o)})):console.warn("No USDZExporter component found in the scene")}),this.hideElementDuringXRSession(e),e}createARButton(e){if(this._arButton)return this._arButton;const t="immersive-ar",i=document.createElement("button");return this._arButton=i,i.classList.add("webxr-button"),i.dataset.needle="webxr-ar-button",i.innerText="Enter AR",i.prepend(pt("view_in_ar")),i.title="Click to start an AR session",i.addEventListener("click",()=>G.start(t,e)),this.updateSessionSupported(i,t),this.listenToXRSessionState(i,t),this.hideElementDuringXRSession(i),this.isSecureConnection||(i.disabled=!0,i.title="WebXR requires a secure connection (HTTPS)"),exports.DeviceUtilities.isMozillaXR()||navigator.xr?.addEventListener("devicechange",()=>this.updateSessionSupported(i,t)),i}createVRButton(e){if(this._vrButton)return this._vrButton;const t="immersive-vr",i=document.createElement("button");return this._vrButton=i,i.classList.add("webxr-button"),i.dataset.needle="webxr-vr-button",i.innerText="Enter VR",i.prepend(pt("panorama_photosphere")),i.title="Click to start a VR session",i.addEventListener("click",()=>G.start(t,e)),this.updateSessionSupported(i,t),this.listenToXRSessionState(i,t),this.hideElementDuringXRSession(i),this.isSecureConnection||(i.disabled=!0,i.title="WebXR requires a secure connection (HTTPS)"),exports.DeviceUtilities.isMozillaXR()||navigator.xr?.addEventListener("devicechange",()=>this.updateSessionSupported(i,t)),i}createSendToQuestButton(){if(this._sendToQuestButton)return this._sendToQuestButton;const e="https://oculus.com/open_url/?url=",t=document.createElement("button");return this._sendToQuestButton=t,t.dataset.needle="webxr-sendtoquest-button",t.innerText="Open on Quest",t.prepend(pt("share_windows")),t.title="Click to send this page to the Oculus Browser on your Quest",t.addEventListener("click",()=>{const i=encodeURIComponent(window.location.href),n=e+i;window.open(n)==null&&Ce("This page doesn't allow popups. Please paste "+n+" into your browser.")}),this.listenToXRSessionState(t),this.hideElementDuringXRSession(t),exports.DeviceUtilities.isMozillaXR()||navigator.xr?.addEventListener("devicechange",()=>{navigator.xr?.isSessionSupported("immersive-vr")?t.style.display="none":t.style.display=""}),t}createQRCode(){return Ji.getOrCreate().createQRCode()}updateSessionSupported(e,t){if(!("xr"in navigator)){e.style.display="none";return}G.isSessionSupported(t).then(i=>{e.style.display=i?"":"none",A()&&!i&&console.log('[WebXR] "'+t+'" is not supported on this device – make sure your server runs using HTTPS and you have a device connected that supports '+t)})}hideElementDuringXRSession(e){Jd(t=>{e["previous-display"]=e.style.display,e.style.display="none"}),Om(t=>{e["previous-display"]!=null&&(e.style.display=e["previous-display"])})}listenToXRSessionState(e,t){t&&(G.onSessionRequestStart(i=>{i.mode===t?e.classList.add("this-mode-is-requested"):(e["was-disabled"]=e.disabled,e.disabled=!0,e.classList.add("other-mode-is-requested"))}),G.onSessionRequestEnd(i=>{e.classList.remove("this-mode-is-requested"),e.classList.remove("other-mode-is-requested"),e.disabled=e["was-disabled"]}))}}var rM=Object.defineProperty,aM=Object.getOwnPropertyDescriptor,at=(s,e,t,i)=>{for(var n=i>1?void 0:i?aM(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&rM(e,t,n),n};const Xl=x("debugspriterenderer"),lM=x("wireframe");class rr{static cache={};static getOrCreateGeometry(e){if(e.__cached_geometry)return e.__cached_geometry;if(e.guid&&rr.cache[e.guid])return Xl&&console.log("Take cached geometry for sprite",e.guid),rr.cache[e.guid];const t=new c.BufferGeometry;e.__cached_geometry=t;const i=new Float32Array(e.triangles.length*3),n=new Float32Array(e.triangles.length*2);for(let o=0;o<e.triangles.length;o+=1){const r=e.triangles[o];i[o*3]=-e.vertices[r].x,i[o*3+1]=e.vertices[r].y,i[o*3+2]=0;const a=e.uv[r];n[o*2]=a.x,n[o*2+1]=1-a.y}return t.setAttribute("position",new c.BufferAttribute(i,3)),t.setAttribute("uv",new c.BufferAttribute(n,2)),e.guid&&(this.cache[e.guid]=t),Xl&&console.log("Built sprite geometry",e,t),t}}class cM{x;y}function yw(s){s&&(s.colorSpace!=c.SRGBColorSpace&&(s.colorSpace=c.SRGBColorSpace,s.needsUpdate=!0),s.minFilter==c.NearestFilter&&s.magFilter==c.NearestFilter&&(s.anisotropy=1,s.needsUpdate=!0))}let ys=class{constructor(e){e&&(this.texture=e,this.triangles=[0,1,2,0,2,3],this.uv=[{x:0,y:0},{x:1,y:0},{x:1,y:1},{x:0,y:1}],this.vertices=[{x:-.5,y:-.5},{x:.5,y:-.5},{x:.5,y:.5},{x:-.5,y:.5}])}guid;texture;triangles;uv;vertices;__cached_geometry;get mesh(){return this._mesh||(this._mesh=new c.Mesh(rr.getOrCreateGeometry(this),this.material)),this._mesh}_mesh;get material(){return this._material||(this.texture&&yw(this.texture),this._material=new c.MeshBasicMaterial({map:this.texture,color:16777215,side:c.DoubleSide,transparent:!0})),this._material}_material;getGeometry(){return rr.getOrCreateGeometry(this)}};at([f()],ys.prototype,"guid",2);at([f(c.Texture)],ys.prototype,"texture",2);at([Be()],ys.prototype,"triangles",2);at([Be()],ys.prototype,"uv",2);at([Be()],ys.prototype,"vertices",2);const $f=Symbol("spriteOwner");class Sa{sprites;constructor(){this.sprites=[]}}at([f(ys)],Sa.prototype,"sprites",2);const Rg=class Xp{static create(){const e=new Xp;return e.spriteSheet=new Sa,e}constructor(){}clone(){const e=new Xp;return e.index=this.index,e.spriteSheet=this.spriteSheet,e}set sprite(e){e&&(this.spriteSheet?((this.index===null||this.index===void 0)&&(this.index=0),this.spriteSheet.sprites[this.index]=e):(this.spriteSheet=new Sa,this.spriteSheet.sprites=[e],this.index=0))}get sprite(){if(this.spriteSheet)return this.spriteSheet.sprites[this.index]}spriteSheet;index=0;update(e){if(!this.spriteSheet)return;const t=this.index;if(t<0||t>=this.spriteSheet.sprites.length)return;const i=this.spriteSheet.sprites[t],n=i?.texture;if(n&&(yw(n),!i.__hasLoadedProgressive)){i.__hasLoadedProgressive=!0;const o=n;ne.NEEDLE_progressive.assignTextureLOD(n,0).then(r=>{r instanceof c.Texture&&(i.texture=r,e?.map===o&&(e.map=r,e.needsUpdate=!0))})}}};at([f(Sa)],Rg.prototype,"spriteSheet",2);at([f()],Rg.prototype,"index",2);let fa=Rg;class ei extends E{drawMode=0;size={x:1,y:1};color;sharedMaterial;transparent=!0;cutoutThreshold=0;castShadows=!1;renderOrder=0;toneMapped=!0;set texture(e){if(!this._spriteSheet)return;const t=this._spriteSheet.spriteSheet?.sprites[this.spriteIndex];t&&(t.texture=e,this.updateSprite())}addSprite(e,t=!1){if(this._spriteSheet||(this._spriteSheet=fa.create()),!this._spriteSheet.spriteSheet)return-1;this._spriteSheet.spriteSheet?.sprites.push(e);const i=this._spriteSheet.spriteSheet?.sprites.length-1;return t&&(this.spriteIndex=i),i}get sprite(){return this._spriteSheet}set sprite(e){if(e!==this._spriteSheet)if(typeof e=="number"){const t=Math.round(e);Xl&&console.log("[SpriteSheet] Set index to "+t+" (was "+this.spriteIndex+")",e),this.spriteIndex=t}else e instanceof ys?(this._spriteSheet||(this._spriteSheet=fa.create()),this._spriteSheet.sprite!=e&&(this._spriteSheet.sprite=e),this.updateSprite()):e!=this._spriteSheet&&(this._spriteSheet=e,this.updateSprite())}set spriteIndex(e){this._spriteSheet&&(this._spriteSheet.index=e,this.updateSprite())}get spriteIndex(){return this._spriteSheet?.index??0}get spriteFrames(){return this._spriteSheet?.spriteSheet?.sprites.length??0}_spriteSheet;_currentSprite;awake(){this._currentSprite=void 0,this._spriteSheet?this._spriteSheet=this._spriteSheet.clone():this._spriteSheet=fa.create(),Xl&&console.log("Awake",this.name,this,this.sprite)}start(){this._currentSprite?this.gameObject&&this.gameObject.add(this._currentSprite):this.updateSprite()}updateSprite(e=!1){if(!this.__didAwake&&!e)return!1;const t=this._spriteSheet;if(!t?.spriteSheet?.sprites)return console.warn("SpriteRenderer has no data or spritesheet assigned..."),!1;const i=t.spriteSheet.sprites[this.spriteIndex];if(!i)return Xl&&console.warn("Sprite not found",this.spriteIndex,t.spriteSheet.sprites),!1;if(this._currentSprite)this._currentSprite.geometry=rr.getOrCreateGeometry(i),this._currentSprite.material.map=i.texture;else{const n=new c.MeshBasicMaterial({color:16777215,side:c.DoubleSide});if(lM&&(n.wireframe=!0),this.color&&(n.color||(n.color=new c.Color),n.color.copy(this.color),n.opacity=this.color.alpha),n.transparent=!0,n.toneMapped=this.toneMapped,n.depthWrite=!1,i.texture&&!n.wireframe){let o=i.texture;o[$f]!==void 0&&o[$f]!==this&&this.spriteFrames>1&&(o=i.texture=o.clone()),o[$f]=this,n.map=o}this.sharedMaterial=n,this._currentSprite=new c.Mesh(rr.getOrCreateGeometry(i),n),this._currentSprite.renderOrder=Math.round(this.renderOrder),ne.NEEDLE_progressive.assignTextureLOD(n,0)}return this._currentSprite.parent!==this.gameObject&&(this.drawMode===2&&this._currentSprite.scale.set(this.size.x,this.size.y,1),this.gameObject&&this.gameObject.add(this._currentSprite)),this._currentSprite&&this._currentSprite.layers.set(this.layer),this.sharedMaterial&&(this.sharedMaterial.alphaTest=this.cutoutThreshold,this.sharedMaterial.transparent=this.transparent),this._currentSprite.castShadow=this.castShadows,t?.update(this.sharedMaterial),!0}}at([f()],ei.prototype,"drawMode",2);at([f(cM)],ei.prototype,"size",2);at([f(Z)],ei.prototype,"color",2);at([f(c.Material)],ei.prototype,"sharedMaterial",2);at([f()],ei.prototype,"transparent",2);at([f()],ei.prototype,"cutoutThreshold",2);at([f()],ei.prototype,"castShadows",2);at([f()],ei.prototype,"renderOrder",2);at([f()],ei.prototype,"toneMapped",2);at([f(fa)],ei.prototype,"sprite",1);const Y_=x("debugwebxr"),hM=new c.Matrix4().makeRotationY(Math.PI);class di extends E{static _eventListeners={};static onPlaced(e){const t="placed";return this._eventListeners[t]||(this._eventListeners[t]=[]),this._eventListeners[t].push(e),()=>{const i=this._eventListeners[t].indexOf(e);i>=0&&this._eventListeners[t].splice(i,1)}}static _hasPlaced=!1;static get hasPlaced(){return this._hasPlaced}get arScale(){return this._arScale}set arScale(e){this._arScale=Math.max(1e-6,e),this.onSetScale()}_arScale=1;invertForward=!1;customReticle;arTouchTransform=!0;autoPlace=!1;autoCenter=!1;useXRAnchor=!1;_isPlacing=!0;_startOffset=new c.Matrix4;_createdPlacementObject=null;_reparentedComponents=[];_placementScene=new c.Scene;_reticle=[];_hits=[];_placementStartTime=-1;_rigPlacementMatrix;_anchor=null;userInput;onEnable(){this.customReticle?.preload()}supportsXR(e){return e==="immersive-ar"}onEnterXR(e){Y_&&console.log("ENTER WEBXR: SessionRoot start..."),this._anchor=null,di._hasPlaced=!1,this.gameObject.updateMatrixWorld(),this._startOffset.copy(this.gameObject.matrixWorld);const t=new c.Object3D;this._createdPlacementObject=t,t.name="AR Session Root",this._placementScene.name="AR Placement Scene",this._placementScene.children.length=0;for(let i=this.context.scene.children.length-1;i>=0;i--){const n=this.context.scene.children[i];this._placementScene.add(n)}if(this.context.scene.add(t),this.autoCenter){const i=Ft(this._placementScene.children),n=i.getCenter(new c.Vector3),o=i.getSize(new c.Vector3),r=new c.Matrix4;r.makeTranslation(n.x,n.y-o.y*.5,n.z),this._startOffset.multiply(r)}this._reparentedComponents.length=0,this._reparentedComponents.push({comp:this,originalObject:this.gameObject}),S.addComponent(t,this);for(const i of this._reticle)ji(i);this._reticle.length=0,this._isPlacing=!0,this.context.input.addEventListener("pointerup",this.onPlaceScene,{queue:Xt.Early})}onLeaveXR(){this.context.input.removeEventListener("pointerup",this.onPlaceScene,{queue:Xt.Early}),this.onRevertSceneChanges(),this._anchor=null,di._hasPlaced=!1,this._rigPlacementMatrix=void 0}onUpdateXR(e){if(e.xr.isTrackingImages){for(const t of this._reticle)t.visible=!1;return}if(this._isPlacing){const t=e.xr.rig?.gameObject;t&&t.parent!==this.context.scene&&this.context.scene.add(t);let i=!1;if(e.xr.isPassThrough&&e.xr.controllers.length>0&&!this.autoPlace)for(const n of e.xr.controllers){const o=n.getHitTest();o&&(i=!0,this.updateReticleAndHits(e.xr,n.index,o,e.xr.rigScale))}if(!i){const n=e.xr.getHitTest();n&&this.updateReticleAndHits(e.xr,0,n,e.xr.rigScale)}}else{if(this._anchor&&e.xr.referenceSpace){const t=e.xr.frame.getPose(this._anchor.anchorSpace,e.xr.referenceSpace);if(t&&this.context.time.frame%20===0){const i=e.xr.convertSpace(t.transform),n=this._reticle[0];n&&(n.position.copy(i.position),n.quaternion.copy(i.quaternion),this.onApplyPose(n))}}if(this.arTouchTransform?(this.userInput||(this.userInput=new Vd(this.context)),this.userInput?.enable()):this.userInput?.disable(),this.arTouchTransform&&this.userInput?.hasChanged){if(e.xr.rig){const t=e.xr.rig.gameObject;this.userInput.applyMatrixTo(t.matrix,!0),t.matrix.decompose(t.position,t.quaternion,t.scale),this.userInput.factor=t.scale.x}this.userInput.reset()}}}updateReticleAndHits(e,t,i,n){this._hits[t]=i.hit;let o=this._reticle[t];if(!o){if(this.customReticle)if(this.customReticle.asset)o=ir(this.customReticle.asset);else{this.customReticle.loadAssetAsync();return}else o=new c.Mesh(new c.RingGeometry(.07,.09,32).rotateX(-Math.PI/2),new c.MeshBasicMaterial({side:c.DoubleSide,depthTest:!1,depthWrite:!1,transparent:!0,opacity:1,color:15658734})),o.name="AR Placement Reticle";if(Y_){const r=new c.AxesHelper(1);r.position.y+=.01,o.add(r)}this._reticle[t]=o,o.matrixAutoUpdate=!1,o.visible=!1}if(o.lastPos=o.lastPos||i.position.clone(),o.lastQuat=o.lastQuat||i.quaternion.clone(),o.position.copy(o.lastPos.lerp(i.position,this.context.time.deltaTime/.1)),o.lastPos.copy(o.position),o.quaternion.copy(o.lastQuat.slerp(i.quaternion,this.context.time.deltaTime/.05)),o.lastQuat.copy(o.quaternion),o.scale.set(n,n,n),this.customReticle&&this.applyViewBasedTransform(o),o.updateMatrix(),o.visible=!0,o.parent!==this.context.scene&&this.context.scene.add(o),this._placementStartTime<0&&(this._placementStartTime=this.context.time.realtimeSinceStartup),this.autoPlace)if(this.upVec.set(0,1,0).applyQuaternion(o.quaternion),this.upVec.dot(j(0,1,0))>.9){let a=o["autoplace:timer"]||0;a>=1?(o.visible=!1,this.onPlaceScene(null)):(a+=this.context.time.deltaTime,o["autoplace:timer"]=a)}else o["autoplace:timer"]=0}onPlaceScene=e=>{if(this._isPlacing==!1||e?.used)return;let t=this._reticle[0];if(!t){console.warn("No reticle to place...");return}if(!t.visible&&!this.autoPlace){console.warn("Reticle is not visible (can not place)");return}if(G.active?.isTrackingImages){console.warn("Scene Placement is disabled while images are being tracked");return}let i=this._hits[0];if(e&&e.origin instanceof Mm){const n=this._reticle[e.origin.index];n&&(t=n,i=this._hits[e.origin.index])}if(e&&(e.stopImmediatePropagation(),e.stopPropagation(),e.use()),this._isPlacing=!1,this.context.input.removeEventListener("pointerup",this.onPlaceScene),this.onRevertSceneChanges(),t.position.copy(t.lastPos),t.quaternion.copy(t.lastQuat),this.onApplyPose(t),di._hasPlaced=!0,this.useXRAnchor&&this.onCreateAnchor(G.active,i),this.context.xr)for(const n of this.context.xr.controllers)n.cancelHitTestSource()};onSetScale(){if(!di._hasPlaced)return;const e=G.active?.rig?.gameObject;if(e){const t=G.active?.rigScale||1,i=1/this._arScale*t,n=new c.Matrix4().makeScale(i,i,i).invert();e.matrix.premultiply(n),e.matrix.decompose(e.position,e.quaternion,e.scale)}}onRevertSceneChanges(){for(const e of this._reticle)e&&(e.visible=!1,e?.removeFromParent());this._reticle.length=0;for(let e=this._placementScene.children.length-1;e>=0;e--){const t=this._placementScene.children[e];this.context.scene.add(t)}this._createdPlacementObject?.removeFromParent();for(const e of this._reparentedComponents)S.addComponent(e.originalObject,e.comp)}async onCreateAnchor(e,t){if(t.createAnchor===void 0){console.warn("Hit does not support creating an anchor",t),A()&&de("Hit does not support creating an anchor");return}else{const i=await t.createAnchor(e.viewerPose.transform);e.running&&i&&(this._anchor=i)}}upVec=new c.Vector3(0,1,0);lookPoint=new c.Vector3;worldUpVec=new c.Vector3(0,1,0);applyViewBasedTransform(e){const t=this.context.mainCamera,i=e,n=t.worldPosition,o=i.worldPosition;this.upVec.set(0,1,0).applyQuaternion(e.quaternion);const r=t.worldPosition;r&&e.position.clone().sub(r).angleTo(this.upVec)<Math.PI/2&&this.upVec.negate();const a=this.upVec.angleTo(this.worldUpVec)*180/Math.PI,l=30;a>l&&a<180-l||a<-l&&a>-180+l?(this.lookPoint.copy(e.position).add(this.upVec),this.lookPoint.y=e.position.y,e.lookAt(this.lookPoint)):(n.y=o.y,e.lookAt(n))}onApplyPose(e){const t=G.active?.rig?.gameObject;if(!t){console.warn("No rig object to place");return}const i=t.parent||this.context.scene;this._rigPlacementMatrix?this._rigPlacementMatrix?.decompose(t.position,t.quaternion,t.scale):this._rigPlacementMatrix=t.matrix.clone(),this.applyViewBasedTransform(e),e.updateMatrix(),this.context.scene.add(e),e.attach(t),e.removeFromParent(),t.scale.set(this.arScale,this.arScale,this.arScale),t.position.multiplyScalar(this.arScale),t.updateMatrix(),this.invertForward&&t.matrix.premultiply(hM),t.matrix.premultiply(this._startOffset),t.matrix.decompose(t.position,t.quaternion,t.scale),i.add(t)}}class Vd{static up=new c.Vector3(0,1,0);static zero=new c.Vector3(0,0,0);static one=new c.Vector3(1,1,1);oneFingerDrag=!0;twoFingerRotate=!0;twoFingerScale=!0;factor=1;context;offset;plane;_scale=1;_hasChanged=!1;get scale(){return this._scale}constructor(e){this.context=e,this.offset=new c.Matrix4,this.plane=new c.Plane,this.plane.setFromNormalAndCoplanarPoint(Vd.up,Vd.zero)}_enabled=!1;reset(){this._scale=1,this.offset.identity(),this._hasChanged=!0}get hasChanged(){return this._hasChanged}applyMatrixTo(e,t){this._hasChanged=!1,t?(this.offset.invert(),e.premultiply(this.offset)):e.multiply(this.offset)}currentlyUsedPointerIds=new Set;currentlyUnusedPointerIds=new Set;get isActive(){return this.currentlyUsedPointerIds.size<=0&&this.currentlyUnusedPointerIds.size>0}enable(){this._enabled||(this._enabled=!0,this.context.input.addEventListener("pointerdown",this.onPointerDownEarly,{queue:Xt.Early}),this.context.input.addEventListener("pointerdown",this.onPointerDownLate,{queue:Xt.Late}),this.context.input.addEventListener("pointerup",this.onPointerUpEarly,{queue:Xt.Early}),window.addEventListener("touchstart",this.touchStart,{passive:!1}),window.addEventListener("touchmove",this.touchMove,{passive:!1}),window.addEventListener("touchend",this.touchEnd,{passive:!1}))}disable(){this._enabled&&(this._enabled=!1,this.context.input.removeEventListener("pointerdown",this.onPointerDownEarly,{queue:Xt.Early}),this.context.input.removeEventListener("pointerdown",this.onPointerDownLate,{queue:Xt.Late}),this.context.input.removeEventListener("pointerup",this.onPointerUpEarly,{queue:Xt.Early}),window.removeEventListener("touchstart",this.touchStart),window.removeEventListener("touchmove",this.touchMove),window.removeEventListener("touchend",this.touchEnd))}onPointerDownEarly=e=>{this.isActive&&e.stopPropagation()};onPointerDownLate=e=>{e.used?this.currentlyUsedPointerIds.add(e.pointerId):this.currentlyUsedPointerIds.size<=0&&this.currentlyUnusedPointerIds.add(e.pointerId)};onPointerUpEarly=e=>{this.currentlyUsedPointerIds.delete(e.pointerId),this.currentlyUnusedPointerIds.delete(e.pointerId)};prev=new Map;_didMultitouch=!1;touchStart=e=>{if(!e.defaultPrevented)for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t],n=exports.DeviceUtilities.isAndroidDevice()&&i.clientY<window.innerHeight*.1;this.prev.has(i.identifier)||this.prev.set(i.identifier,{ignore:n,x:0,z:0,screenx:0,screeny:0});const o=this.prev.get(i.identifier);if(o){const r=this.getPositionOnPlane(i.clientX,i.clientY);o.x=r.x,o.z=r.z,o.screenx=i.clientX,o.screeny=i.clientY}}};touchEnd=e=>{e.touches.length<=0&&(this._didMultitouch=!1);for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t];this.prev.delete(i.identifier)}};touchMove=e=>{if(!e.defaultPrevented&&this.isActive){if(e.touches.length===1){if(this._didMultitouch)return;const t=e.touches[0],i=this.prev.get(t.identifier);if(!i||i.ignore)return;const n=this.getPositionOnPlane(t.clientX,t.clientY),o=n.x-i.x,r=n.z-i.z;if(o===0&&r===0)return;this.oneFingerDrag&&this.addMovement(o,r),i.x=n.x,i.z=n.z,i.screenx=t.clientX,i.screeny=t.clientY;return}else if(e.touches.length===2){this._didMultitouch=!0;const t=e.touches[0],i=e.touches[1],n=this.prev.get(t.identifier),o=this.prev.get(i.identifier);if(!n||!o)return;if(this.twoFingerRotate){const r=Math.atan2(t.clientY-i.clientY,t.clientX-i.clientX),a=Math.atan2(n.screeny-o.screeny,n.screenx-o.screenx),l=r-a;Math.abs(l)>.001&&this.addRotation(l)}if(this.twoFingerScale){const r=t.clientX-i.clientX,a=t.clientY-i.clientY,l=Math.sqrt(r*r+a*a),h=n.screenx-o.screenx,d=n.screeny-o.screeny,u=Math.sqrt(h*h+d*d),p=l-u;Math.abs(p)>2&&this.addScale(p)}n.screenx=t.clientX,n.screeny=t.clientY,o.screenx=i.clientX,o.screeny=i.clientY}}};_raycaster=new c.Raycaster;_intersection=new c.Vector3;_screenPos=new c.Vector3;getPositionOnPlane(e,t){const i=this.context.mainCamera;return this._screenPos.x=e/window.innerWidth*2-1,this._screenPos.y=-(t/window.innerHeight)*2+1,this._screenPos.z=1,this._screenPos.unproject(i),this._raycaster.set(i.position,this._screenPos.sub(i.position)),this._raycaster.ray.intersectPlane(this.plane,this._intersection),this._intersection}addMovement(e,t){e/=this._scale,t/=this._scale,e*=this.factor,t*=this.factor,this.offset.elements[12]+=e,this.offset.elements[14]+=t,(e!==0||t!==0)&&(this._hasChanged=!0)}_tempMatrix=new c.Matrix4;addScale(e){e/=window.innerWidth,e*=-1,this._scale*=1+e,this._tempMatrix.makeScale(1-e,1-e,1-e),this.offset.premultiply(this._tempMatrix),e!==0&&(this._hasChanged=!0)}addRotation(e){e*=-1,this._tempMatrix.makeRotationY(e),this.offset.premultiply(this._tempMatrix),e!==0&&(this._hasChanged=!0)}}const Hs=x("debugautosync"),Wf=Symbol("syncerId");class dM{_syncers={};getOrCreateSyncer(e){if(!e.guid)return null;if(this._syncers[e.guid])return this._syncers[e.guid];const t=new uM(e);return t[Wf]=e.guid,this._syncers[t[Wf]]=t,t}removeSyncer(e){delete this._syncers[e[Wf]]}}const Tg=new dM;class uM{comp;constructor(e){this.comp=e}hasChanges=!1;changedProperties={};get networkingKey(){return this.comp.guid}_isReceiving=!1;_isInit=!1;init(e){if(this._isInit)return;this._isInit=!0,this.comp=e,this.comp.context.post_render_callbacks.push(this.onHandleSending),this.comp.context.connection.beginListen(this.networkingKey,this.onHandleReceiving);const t=this.comp.context.connection.tryGetState(this.comp.guid);t&&this.onHandleReceiving(t)}destroy(){this._isInit&&(this.comp.context.post_render_callbacks.splice(this.comp.context.post_render_callbacks.indexOf(this.onHandleSending),1),this.comp.context.connection.stopListen(this.networkingKey,this.onHandleReceiving),this.comp=null,this._isInit=!1)}notifyChanged(e,t){this._isReceiving||(Hs&&console.log("Property changed: "+e,t),this.hasChanges=!0,this.changedProperties[e]=t)}onHandleSending=()=>{if(!this.hasChanges)return;this.hasChanges=!1;const e=this.comp.context.connection;if(!e||!e.isConnected||!e.isInRoom){for(const t in this.changedProperties)delete this.changedProperties[t];return}for(const t in this.changedProperties){const i=this.changedProperties[t];Hs&&console.log("SEND",this.comp.guid,this.networkingKey),e.send(this.networkingKey,{guid:this.comp.guid,property:t,data:i},Zi.Queued),delete this.changedProperties[t]}};onHandleReceiving=e=>{if(Hs&&console.log("SYNCFIELD RECEIVE",this.comp.name,this.comp.guid,e),!!this._isInit&&this.comp&&e.guid===this.comp.guid)try{this._isReceiving=!0,this.comp[e.property]=e.data}catch(t){console.error(t)}finally{this._isReceiving=!1}}}function fM(s,e){let t=e!==s;return!t&&s&&e&&(Array.isArray(s)&&Array.isArray(e)||typeof s=="object"&&typeof e=="object")&&(t=!0),t}const Ql=Symbol("AutoSyncHandler");function pM(s){if(s[Ql])return s[Ql];const e=Tg.getOrCreateSyncer(s);return e?.init(s),s[Ql]=e,e}function mM(s){const e=s[Ql];e&&(Tg.removeSyncer(e),e.destroy(),delete s[Ql])}const Ag=function(s=null){return function(e,t){let i="";typeof t=="string"?i=t:i=t.name;let n=null,o;typeof s=="string"?o=e[s]:typeof s=="function"&&(o=s),o==null&&(A()||Hs)&&s!=null&&console.warn('syncField: no callback function found for property "'+i+'"','"'+s+'"');const r=e,a=r.__internalAwake;if(typeof a!="function"){(Hs||A())&&console.error('@syncField can currently only used on Needle Engine Components, custom object of type "'+e?.constructor?.name+'" is not supported',e);return}Hs&&console.log(i);const l=Symbol(i);r.__internalAwake=function(){if(this[l]!==void 0)return;if(this[l]=this[i],n=Tg.getOrCreateSyncer(this),Object.getOwnPropertyDescriptor(this,i)?.set===void 0){let u=!1;Object.defineProperty(this,i,{set:function(p){const m=this[l];if(this[l]=p,u){(A()||Hs)&&console.warn("Recursive call detected",i);return}u=!0;try{const y=fM(p,m);Hs&&console.log("SyncField assignment",i,"changed?",y,p,o),y&&o?.call(this,p,m)!==!1&&pM(this)?.notifyChanged(i,p)}finally{u=!1}},get:function(){return this[l]},configurable:!0,enumerable:!0})}n?.init(this),a.call(this)};const h=r.__internalDestroy;r.__internalDestroy=function(){mM(this),h.call(this)}}};var gM=Object.defineProperty,Cu=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&gM(e,t,n),n};const Lt=x("debugplayersync"),Pu=class _w extends E{static async setupFrom(e,t){const i=Y.getOrCreateFromUrl(e);if(!i.asset){const r=await i.loadAssetAsync();r&&S.getOrAddComponent(r,en)}const n=new _w;n._internalInit(t),n.asset=i;const o=new c.Object3D;return o.guid=e,S.addComponent(o,n),n}autoSync=!0;asset;onPlayerSpawned;_localInstance;awake(){this.watchTabVisible(),this.onPlayerSpawned||(this.onPlayerSpawned=new oe)}onEnable(){this.context.connection.beginListen(Q.RoomStateSent,this.onJoinedRoom),this.context.connection.beginListen(Q.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Q.LeftRoom,this.destroyInstance),this.context.connection.isInRoom&&this.onJoinedRoom()}onDisable(){this.context.connection.stopListen(Q.RoomStateSent,this.onJoinedRoom),this.context.connection.stopListen(Q.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Q.LeftRoom,this.destroyInstance)}onJoinedRoom=()=>{Lt&&console.log("PlayerSync.joinedRoom. autoSync is set to "+this.autoSync),this.autoSync&&this.getInstance()};async getInstance(){if(this._localInstance)return this._localInstance;if(Lt&&console.log("PlayerSync.createInstance",this.asset?.url),!this.asset?.asset&&!this.asset?.url)return console.error('PlayerSync: can not create an instance because "asset" is not set and or has no URL!'),null;this.gameObject.guid||console.warn("PlayerSync: gameObject has no guid! This might cause issues with syncing the player state."),this._localInstance=this.asset?.instantiateSynced({parent:this.gameObject,deleteOnDisconnect:!0},!0);const e=await this._localInstance;if(e){const t=S.getComponentsInChildren(e,en);if(Lt&&console.log(`PlayerSync.createInstance: found ${t?.length} PlayerState components. Owner: ${this.context.connection.connectionId}`),t?.length){for(const i of t)i.owner=this.context.connection.connectionId;this.onPlayerSpawned?.invoke(e)}else this._localInstance=void 0,console.error("<strong>Failed finding PlayerState on "+this.asset?.url+"</strong>: please make sure the asset has a PlayerState component!"),S.destroySynced(e)}else this._localInstance=void 0,console.warn("PlayerSync: failed instantiating asset!");return this._localInstance}destroyInstance=()=>{this._localInstance?.then(e=>{Lt&&console.log("PlayerSync.destroyInstance",e),Pc(e,this.context.connection,!0,{saveInRoom:!1})}),this._localInstance=void 0};watchTabVisible(){window.addEventListener("visibilitychange",e=>{if(document.visibilityState==="visible")for(let t=en.all.length-1;t>=0;t--){const i=en.all[t];(!i.owner||!this.context.connection.userIsInRoom(i.owner))&&i.doDestroy()}})}};Cu([f()],Pu.prototype,"autoSync");Cu([f(Y)],Pu.prototype,"asset");Cu([f(oe)],Pu.prototype,"onPlayerSpawned");let Dg=Pu;var bw=(s=>(s.OwnerChanged="ownerChanged",s))(bw||{});const Qp=class ut extends E{static _all=[];static get all(){return ut._all}static _local=[];static get local(){return ut._local}static getFor(e){if(e instanceof c.Object3D)return S.getComponentInParent(e,ut);if(e instanceof E)return S.getComponentInParent(e.gameObject,ut)}static isLocalPlayer(e){return ut.getFor(e)?.isLocalPlayer??!1}static _callbacks={};static addEventListener(e,t){return this._callbacks[e]||(this._callbacks[e]=[]),this._callbacks[e].push(t),t}static removeEventListener(e,t){if(!this._callbacks[e])return;const i=this._callbacks[e].indexOf(t);i>=0&&this._callbacks[e].splice(i,1)}static dispatchEvent(e,t){if(this._callbacks[e])for(const i of this._callbacks[e])i(t)}onOwnerChangeEvent=new oe;onFirstOwnerChangeEvent=new oe;hasOwner=!1;owner;dontDestroy=!1;get isLocalPlayer(){return this.owner===this.context.connection.connectionId}onOwnerChange(e,t){Lt&&console.log(`PlayerSync.onOwnerChange: ${t} → ${e} (me: ${this.context.connection.connectionId})`);const i=ut._local.indexOf(this);i>=0&&ut._local.splice(i,1);const n={playerState:this,oldValue:t,newValue:e};if(this.hasOwner||(this.hasOwner=!0,this.onFirstOwnerChangeEvent?.invoke(n)),this.onOwnerChangeEvent?.invoke(n),this.owner===this.context.connection.connectionId){ut._local.push(this);const r=new CustomEvent("local-owner-changed",{detail:n});this.dispatchEvent(r)}const o=new CustomEvent("owner-changed",{detail:n});this.dispatchEvent(o),ut.dispatchEvent("ownerChanged",o)}awake(){ut.all.push(this),Lt&&console.log("Registered new PlayerState",this.guid,ut.all.length-1,ut.all),this.context.connection.beginListen(Q.UserLeftRoom,this.onUserLeftRoom)}async start(){Lt&&console.log("PLAYERSTATE.START, owner: "+this.owner,this.context.connection.usersInRoom([])),this.owner?(this.context.connection.isInRoom||await Bn(300),this.context.connection.userIsInRoom(this.owner)==!1&&(Lt&&console.log(`PlayerSync.start → doDestroy "${this.name}" because user "${this.owner}" is not in room anymore...`,"Currently in room:",...this.context.connection.usersInRoom()),this.doDestroy())):this.owner||(Lt&&console.warn("PlayerState.start → owner is undefined!",this.name),setTimeout(()=>{!this.destroyed&&!this.owner?this.dontDestroy?Lt&&console.warn("PlayerState.start → owner is still undefined but dontDestroy is set to true",this.name):(Lt&&console.warn(`PlayerState.start → owner is still undefined: destroying "${this.name}" instance now`),this.doDestroy()):Lt&&console.log("PlayerState.start → owner is assigned",this.owner)},2e3))}doDestroy(){Lt&&console.log("PlayerSync.doDestroy → syncDestroy",this.name),Pc(this.gameObject,this.context.connection,!0,{saveInRoom:!1})}onDestroy(){if(Lt&&console.warn("PlayerState.onDestroy",this.owner),this.context.connection.stopListen(Q.UserLeftRoom,this.onUserLeftRoom),ut.all.splice(ut.all.indexOf(this),1),this.isLocalPlayer){const e=ut._local.indexOf(this);e>=0&&ut._local.splice(e,1)}}onUserLeftRoom=e=>{if(e.userId===this.owner){Lt&&console.log("PLAYERSYNC LEFT",this.owner),this.doDestroy();return}}};Cu([Ag(Qp.prototype.onOwnerChange)],Qp.prototype,"owner");let en=Qp;var yM=Object.defineProperty,ja=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&yM(e,t,n),n};class Nn extends E{position="bottom";showNeedleLogo=!1;showSpatialMenu;createFullscreenButton;createMuteButton;createQRCodeButton;onEnable(){this.applyOptions()}applyOptions(){this.context.menu.setPosition(this.position),this.context.menu.showNeedleLogo(this.showNeedleLogo),this.createFullscreenButton===!0&&this.context.menu.showFullscreenOption(!0),this.createMuteButton===!0&&this.context.menu.showAudioPlaybackOption(!0),this.showSpatialMenu===!0&&this.context.menu.showSpatialMenu(this.showSpatialMenu),this.createQRCodeButton===!0&&(exports.DeviceUtilities.isMobileDevice()||this.context.menu.showQRCodeButton(!0))}}ja([f()],Nn.prototype,"position");ja([f()],Nn.prototype,"showNeedleLogo");ja([f()],Nn.prototype,"showSpatialMenu");ja([f()],Nn.prototype,"createFullscreenButton");ja([f()],Nn.prototype,"createMuteButton");ja([f()],Nn.prototype,"createQRCodeButton");var _M=Object.defineProperty,Lg=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&_M(e,t,n),n};const al=x("debugwebxr"),K_=new c.Quaternion().setFromAxisAngle(new c.Vector3(0,1,0),Math.PI);class io extends E{head;leftHand;rightHand;_leftHandMeshes;_rightHandMeshes;_syncTransforms;async onEnterXR(e){if(!this.activeAndEnabled)return;al&&console.warn("AVATAR ENTER XR",this.guid,this.sourceId,this,this.activeAndEnabled),this._syncTransforms&&(this._syncTransforms.length=0),await this.prepareAvatar();const t=en.getFor(this);if(t?.owner){const i=this.gameObject.addComponent(Se);i.avatar=this.gameObject,i.connectionId=t.owner}else this.context.connection.isConnected?console.error("No player state found for avatar",this):t&&!this.context.connection.isConnected&&(t.dontDestroy=!0)}onLeaveXR(e){const t=this.gameObject.getComponent(Se);t&&t.destroy()}onUpdateXR(e){if(!this.activeAndEnabled)return;const t=en.isLocalPlayer(this);if(!t)return;const i=e.xr;if(i.rig&&i.rig.gameObject!==this.gameObject.parent&&(this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),this.gameObject.scale.set(1,1,1),i.rig.gameObject.add(this.gameObject)),this._syncTransforms&&t)for(const l of this._syncTransforms)l.fastMode=!0,l.isOwned()||l.requestOwnership();if(this.head&&this.context.mainCamera){const l=this.head.asset;if(l.position.copy(this.context.mainCamera.position),l.position.x*=-1,l.position.z*=-1,l.quaternion.copy(this.context.mainCamera.quaternion),l.quaternion.x*=-1,this.context.time.frameCount%10===0&&this.head.asset){const h=S.getComponentsInChildren(this.head.asset,Ti);for(const d of h)d.enabled=!1,d.gameObject.visible=!1}}const n=e.xr.leftController,o=this.leftHand?.asset;n&&o?(o.position.copy(n.gripPosition),o.quaternion.copy(n.gripQuaternion),o.quaternion.multiply(K_),o.visible=n.isTracking,this.updateHandVisibility(n,o,this._leftHandMeshes)):o&&o.visible&&(o.visible=!1);const r=e.xr.rightController,a=this.rightHand?.asset;r&&a?(a.position.copy(r.gripPosition),a.quaternion.copy(r.gripQuaternion),a.quaternion.multiply(K_),a.visible=r.isTracking,this.updateHandVisibility(r,a,this._rightHandMeshes)):a&&a.visible&&(a.visible=!1)}onBeforeRender(){this.context.xr&&this.context.time.frame%10===0&&this.updateRemoteAvatarVisibility()}updateHandVisibility(e,t,i){if(i){const n=e.model&&e.model.visible&&e.model!==t;i.forEach(o=>{ts(o,!n)})}}updateRemoteAvatarVisibility(){if(this.context.connection.isConnected){const e=en.getFor(this);if(e&&e.isLocalPlayer==!1){const t=G.getXRSync(this.context);if(t&&t.hasState(e.owner)){this.tryFindAvatarObjectsIfMissing();const i=this.leftHand?.asset;i&&(i.visible=t?.isTracking(e.owner,"left")??!1);const n=this.rightHand?.asset;n&&(n.visible=t?.isTracking(e.owner,"right")??!1)}if(this.head?.asset){const i=S.getComponentsInChildren(this.head.asset,Ti);for(const n of i)n.enabled=!1,n.gameObject.visible=!0}}}}tryFindAvatarObjectsIfMissing(){if(!this.head||!this.leftHand||!this.rightHand){const e={head:this.head,leftHand:this.leftHand,rightHand:this.rightHand};p0.tryFindAvatarObjects(this.gameObject,this.sourceId||"",e),e.head&&(this.head=e.head),e.leftHand&&(this.leftHand=e.leftHand),e.rightHand&&(this.rightHand=e.rightHand)}}async prepareAvatar(){if(this.tryFindAvatarObjectsIfMissing(),this.head)this.head instanceof c.Object3D&&(this.head=new Y("",this.sourceId,this.head));else{const e=new c.Object3D;e.name="Head";const t=hr.createPrimitive(Jo.Cube);e.add(t),this.gameObject.add(e),this.head=new Y("",this.sourceId,e),al&&console.log("Create head",e)}if(this.rightHand)this.rightHand instanceof c.Object3D&&(this.rightHand=new Y("",this.sourceId,this.rightHand));else{const e=new c.Object3D;e.name="Right Hand",this.gameObject.add(e),this.rightHand=new Y("",this.sourceId,e),al&&console.log("Create right hand",e)}if(this.leftHand)this.leftHand instanceof c.Object3D&&(this.leftHand=new Y("",this.sourceId,this.leftHand));else{const e=new c.Object3D;e.name="Left Hand",this.gameObject.add(e),this.leftHand=new Y("",this.sourceId,e),al&&console.log("Create left hand",e)}await this.loadAvatarObjects(this.head,this.leftHand,this.rightHand),this._leftHandMeshes=[],this.leftHand.asset?.traverse(e=>{e?.isMesh&&this._leftHandMeshes.push(e)}),this._rightHandMeshes=[],this.rightHand.asset?.traverse(e=>{e?.isMesh&&this._rightHandMeshes.push(e)}),en.isLocalPlayer(this.gameObject)&&(this._syncTransforms=S.getComponentsInChildren(this.gameObject,ln))}async loadAvatarObjects(e,t,i){const n=e.loadAssetAsync(),o=t.loadAssetAsync(),r=i.loadAssetAsync(),a=new Array;n&&a.push(n),o&&a.push(o),r&&a.push(r);const l=await fm(a);al&&console.log("Avatar loaded results:",l)}}Lg([f(Y)],io.prototype,"head");Lg([f(Y)],io.prototype,"leftHand");Lg([f(Y)],io.prototype,"rightHand");var bM=Object.defineProperty,Ou=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&bM(e,t,n),n};const As=x("debugwebxr"),Ds=new Array;class ds extends E{createControllerModel=!0;createHandModel=!0;customLeftHand;customRightHand;static factory=new q.XRControllerModelFactory;supportsXR(e){return e==="immersive-vr"||e==="immersive-ar"}_models=new Array;async onXRControllerAdded(e){if(!(e.xr.isVR||e.xr.isPassThrough))return;console.debug("XR Controller Added",e.controller.side,e.controller.index);const{controller:i}=e;if(this.createControllerModel||this.createHandModel){if(i.hand){if(this.createHandModel){const n=await this.loadHandModel(this,i);if(!n||!i.connected||!i.isHand){n?.handObject&&qr(n.handObject,!1),n?.handObject?.destroy();return}this._models.push({controller:i,model:n.handObject,handmesh:n.handmesh}),this._models.sort((o,r)=>o.controller.index-r.controller.index),this.scene.add(n.handObject),i.model=n.handObject}}else if(this.createControllerModel){const n=await i.getModelUrl();if(n){const o=await this.loadModel(i,n);if(!o||!i.connected||i.isHand)return;this._models.push({controller:i,model:o}),this._models.sort((r,a)=>r.controller.index-a.controller.index),this.scene.add(o),o.traverse(r=>{r.layers.set(2),r.matrixAutoUpdate=!1,r.updateMatrix()}),i.model=o}else i.targetRayMode!=="transient-pointer"&&console.warn("XRControllerModel: no model found for "+i.side)}}}onXRControllerRemoved(e){console.debug("XR Controller Removed",e.controller.side,e.controller.index);const t=this._models.findIndex(n=>n.controller===e.controller),i=this._models[t];i&&(this._models.splice(t,1),i.model&&(qr(i.model,!1),i.model.destroy(),i.model=void 0))}onBeforeXR(e,t){this.createHandModel&&(this.customLeftHand||this.customRightHand)&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.includes("hand-tracking")||t.optionalFeatures.push("hand-tracking"))}onLeaveXR(e){for(const t of this._models)t&&(t.model&&(qr(t.model,!1),t.model.destroy(),t.model=void 0),t.controller.model===t.model&&(t.controller.model=null));this._models.length=0}onBeforeRender(){if(G.active&&(As&&(Ds[0]=Date.now()),this.updateRendering(G.active),As)){const e=Date.now()-Ds[0];Ds.push(e),Ds.length>=30&&(Ds[0]=0,Ds.reduce((t,i)=>t+i,0)/Ds.length,Ds.length=0)}}updateRendering(e){for(let t=0;t<this._models.length;t++){const i=this._models[t];if(!i)continue;const n=i.controller;if(!n.connected){As&&console.warn("XRControllerModel.onUpdateXR: controller is not connected anymore",n.side,n.hand);continue}if(i.model&&!i.handmesh)i.model.matrixAutoUpdate=!1,i.model.matrix.copy(n.gripMatrix),i.model.visible=n.isTracking,e.rig?.gameObject.add(i.model);else if(n.inputSource.hand&&i.handmesh){const o=e.referenceSpace,r=this.context.renderer.xr.getHand(n.index);if(o&&e.frame.getJointPose){for(const a of n.inputSource.hand.values()){const l=r.joints[a.jointName];if(l){const h=n.getHandJointPose(a);if(h){const d=h.transform.position,u=h.transform.orientation;l.position.copy(d),l.quaternion.copy(u),l.matrixAutoUpdate=!1}l.visible=h!=null}}i.model&&(i.model.visible=n.isTracking,i.model.visible&&i.model.parent!==e.rig?.gameObject&&e.rig?.gameObject.add(i.model)),i.model?.visible&&(i.handmesh?.updateMesh(),i.model.matrixAutoUpdate=!1,i.model.matrix.identity(),i.model.applyMatrix4(aa))}}}}async loadModel(e,t){if(!e.connected)return console.warn("XRControllerModel.onXRControllerAdded: controller is not connected anymore",e.side),null;const n=await Y.getOrCreate("",t).instantiate();return qr(n),G.active?.isPassThrough&&n.traverseVisible(o=>{this.makeOccluder(o)}),n}async loadHandModel(e,t){const i=this.context,n=i.renderer.xr.getHand(t.index);n||(As?B.DrawLabel(t.rayWorldPosition,"No hand found for index "+t.index,.05,5):console.warn("No hand found for index "+t.index));const o=new q.GLTFLoader;Xm(o,i),await zd(o,i,this.sourceId??"",this.sourceId??"");const r=ug(o);let a="";const l=t.side==="left"?this.customLeftHand:this.customRightHand;l?(a=l.url.split(".").slice(0,-1).join("."),o.setPath("")):(a=t.inputSource.handedness==="left"?"left":"right",o.setPath("https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/"));const h=new c.Object3D;qr(h);const d=new q.XRHandMeshModel(h,n,o.path,a,o,u=>{const p=r?.gltf;p?.scene.children?.length===0&&(p.scene.children[0]=u),r?.gltf&&rn().createBuiltinComponents(e.context,e.sourceId||a,r.gltf,null,r),u.traverse(m=>{m.layers.set(2),G.active?.isPassThrough&&!l&&this.makeOccluder(m),m instanceof c.Mesh&&ne.NEEDLE_progressive.assignMeshLOD(m,0)}),t.connected||(As&&B.DrawLabel(t.rayWorldPosition,"Hand is loaded but not connected anymore",.05,5),u.removeFromParent())});if(As&&h.add(new c.AxesHelper(.5)),t.inputSource.hand){As&&console.log(t.inputSource.hand);for(const u of t.inputSource.hand.values())if(n.joints[u.jointName]===void 0){const p=new c.Group;p.matrixAutoUpdate=!1,p.visible=!0,n.joints[u.jointName]=p,n.add(p)}}else As&&B.DrawLabel(t.rayWorldPosition,"No inputSource.hand found for index "+t.index,.05,5);return{handObject:h,handmesh:d}}makeOccluder(e){if(e instanceof c.Mesh){let t=e.material;t instanceof c.Material&&(t=e.material=t.clone(),t.depthWrite=!0,t.depthTest=!0,t.colorWrite=!1,e.receiveShadow=!1,e.renderOrder=-100)}}}Ou([f()],ds.prototype,"createControllerModel");Ou([f()],ds.prototype,"createHandModel");Ou([f(Y)],ds.prototype,"customLeftHand");Ou([f(Y)],ds.prototype,"customRightHand");class Mu extends E{}var vM=Object.defineProperty,fo=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&vM(e,t,n),n};const Hf=x("debugwebxr");class gi extends E{movementSpeed=1.5;rotationStep=30;useTeleport=!0;usePinchToTeleport=!0;useTeleportTarget=!1;useTeleportFade=!1;showRays=!0;showHits=!0;isXRMovementHandler=!0;xrSessionMode="immersive-vr";_didApplyRotation=!1;_didTeleport=!1;onUpdateXR(e){const t=e.xr.rig;if(!t?.gameObject||e.xr.isPassThrough)return;const i=e.xr.leftController,n=e.xr.rightController;i&&this.onHandleMovement(i,t.gameObject),n&&(this.onHandleRotation(n,t.gameObject),this.useTeleport&&this.onHandleTeleport(n,t.gameObject))}onLeaveXR(e){for(const t of this._lines)t.removeFromParent();for(const t of this._hitDiscs)t?.removeFromParent()}onBeforeRender(){this.context.xr?.running&&(this.showRays&&this.renderRays(this.context.xr),this.showHits&&this.renderHits(this.context.xr))}onHandleMovement(e,t){const i=e.getStick("xr-standard-thumbstick");if(i.x!=0||i.y!=0){const n=j(i.x,0,i.y);n.multiplyScalar(this.context.time.deltaTimeUnscaled*this.movementSpeed);const o=je(t);n.multiplyScalar(o.x),n.applyQuaternion(e.xr.poseOrientation),n.y=0,n.applyQuaternion(t.worldQuaternion),A()&&Number.isNaN(n.x)&&console.error("Stick movement resulted in NaN",{stick:i,vec:n}),t.position.add(n),t.updateWorldMatrix(!1,!1);for(const r of t.children)r.updateWorldMatrix(!1,!1)}}onHandleRotation(e,t){if(e._isMxInk)return;const n=e.getStick("xr-standard-thumbstick").x;if(this._didApplyRotation)Math.abs(n)<.3&&(this._didApplyRotation=!1);else if(Math.abs(n)>.5){this._didApplyRotation=!0;const o=n>0?1:-1,r=X(this.context.mainCamera).clone();t.rotateY(o*L.toRadians(this.rotationStep));const l=X(this.context.mainCamera).clone().sub(r);l.y=0,t.position.sub(l)}}_teleportBuffer=new Array;onHandleTeleport(e,t){let i=0;if(e.hand&&this.usePinchToTeleport&&e.isTeleportGesture){const n=e.getPointerId("primary");if(n!=null&&this.context.input.getIsPointerIdInUse(n))return;const o=e.getGesture("pinch");o&&(i=o.value)}else i=e.getStick("xr-standard-thumbstick")?.y;if(this._didTeleport)i>=0&&i<.4?this._didTeleport=!1:i<0&&i>-.4&&(this._didTeleport=!1);else if(i>.8){this._didTeleport=!0;const n=this.context.physics.raycastFromRay(e.ray)[0];if(n&&n.object instanceof q.GroundedSkybox){const r=n.normal?.dot(j(0,1,0));if(r!==void 0&&r<.4)return}let o=n?.point;if(!o&&!this.useTeleportTarget){this._plane||(this._plane=new c.Plane(new c.Vector3(0,1,0),0));const r=t.worldPosition;this._plane.setFromNormalAndCoplanarPoint(new c.Vector3(0,1,0),r);const a=e.ray;o=r.clone(),this._plane.intersectLine(new c.Line3(a.origin,j(a.direction).multiplyScalar(1e4).add(a.origin)),o),o.distanceTo(r)>t.scale.x*10&&(o=null)}if(o){if(this.useTeleportTarget&&!S.getComponentInParent(n.object,Mu))return;const r=o.clone();if(Hf&&B.DrawSphere(o,.025,16711680,5),this.context.mainCamera?.position){const l=this.context.xr?.getUserOffsetInRig();l&&(l.y=0,r.sub(l),Hf&&B.DrawWireSphere(l.add(r),.025,65280,5))}this._teleportBuffer.push(t.matrix.clone()),this._teleportBuffer.length>10&&this._teleportBuffer.shift(),this.useTeleportFade?e.xr.fadeTransition()?.then(()=>{t.worldPosition=r}):t.worldPosition=r}}else if(i<-.8&&(this._didTeleport=!0,this._teleportBuffer.length>0)){const n=this._teleportBuffer.pop();n&&n.decompose(t.position,t.quaternion,t.scale)}}_plane=null;_lines=[];_hitDiscs=[];_hitDistances=[];_lastHitDistances=[];renderRays(e){for(let t=0;t<this._lines.length;t++){const i=this._lines[t];i&&(i.visible=!1)}for(let t=0;t<e.controllers.length;t++){const i=e.controllers[t];let n=this._lines[t];if(!i.connected||!i.isTracking||!i.ray||i.targetRayMode==="transient-pointer"||!i.hasSelectEvent){n&&(n.visible=!1);continue}n||(n=this.createRayLineObject(),n.scale.z=.5,this._lines[t]=n),i.updateRayWorldPosition(),i.updateRayWorldQuaternion();const o=i.rayWorldPosition,r=i.rayWorldQuaternion;n.position.copy(o),n.quaternion.copy(r);const a=e.rigScale,l=this.usePinchToTeleport&&i.isTeleportGesture,h=this._lastHitDistances[t],d=this._hitDistances[t]!=null,u=h??a;n.scale.set(a,a,u),n.visible=!0,n.layers.disableAll(),n.layers.enable(2);let p=n.material.opacity;l?p=1:this.showHits&&u<e.rigScale*.5?p=0:i.getButton("primary")?.pressed?p=.5:p=d?.2:.1,n.material.opacity=L.lerp(n.material.opacity,p,this.context.time.deltaTimeUnscaled/.1),n.parent!==this.context.scene&&this.context.scene.add(n)}}renderHits(e){for(const t of this._hitDiscs){if(!t)continue;const i=t.controller;if(!i||!i.connected||!i.isTracking){t.visible=!1;continue}}for(let t=0;t<e.controllers.length;t++){const i=e.controllers[t];if(!i.connected||!i.isTracking||!i.ray||!i.hasSelectEvent)continue;let n=this._hitDiscs[t],o=!0;const r=i.getPointerId("primary");r!=null&&this.context.input.getIsPointerIdInUse(r)&&(n&&(n.visible=!1),this._hitDistances[t]=null,this._lastHitDistances[t]=0,o=!1);const a=this.context.time.smoothedFps>=59?1:10;if((this.context.time.frame+i.index)%a!==0&&(o=!1),!o){const d=this._hitDiscs[t];d&&d.visible&&d.hit&&this.updateHitPointerPosition(i,d,d.hit.distance);continue}const l=this.context.physics.raycastFromRay(i.ray,{testObject:this.hitPointRaycastFilter,precise:!1});let h=l.find(d=>this.usePinchToTeleport&&i.isTeleportGesture?!0:this.isObjectWithInteractiveComponent(d.object));if(h||(h=l[0]),n&&(n.controller=i,n.hit=h),this._hitDistances[t]=h?.distance||null,h){this._lastHitDistances[t]=h.distance;const d=e.rigScale??1;Hf&&(B.DrawWireSphere(h.point,.025*d,16711680),B.DrawLabel(j(0,.2,0).add(h.point),h.object.name,.02,0)),n||(n=this.createHitPointObject(),this._hitDiscs[t]=n),n.hit=h,n.visible=h.distance>d*.05;let u=.01*(d+h.distance);const p=i.getButton("primary")?.pressed;p&&(u*=1.1),n.scale.set(u,u,u),n.layers.set(2);let m=n.material.opacity;if(p?m=1:m=h.distance<.15*d?.2:.6,n.material.opacity=L.lerp(n.material.opacity,m,this.context.time.deltaTimeUnscaled/.1),n.visible){if(h.normal){this.updateHitPointerPosition(i,n,h.distance);const y=h.normal.applyQuaternion(ue(h.object));n.quaternion.setFromUnitVectors(wM,y)}else this.updateHitPointerPosition(i,n,h.distance);n.parent!==this.context.scene&&this.context.scene.add(n)}}else this._hitDiscs[t]&&(this._hitDiscs[t].visible=!1)}}isObjectWithInteractiveComponent(e,t=0){return Id(e)||e.isUI===!0?!0:e.isScene?!1:e.parent?this.isObjectWithInteractiveComponent(e.parent,t+1):!1}updateHitPointerPosition(e,t,i){const n=j(e.rayWorldPosition);n.add(j(0,0,i-.01).applyQuaternion(e.rayWorldQuaternion)),t.position.lerp(n,this.context.time.deltaTimeUnscaled/.05)}hitPointRaycastFilter=e=>e.type==="SkinnedMesh"?"continue in children":!0;createHitPointObject(){const e=new c.Mesh(new c.SphereGeometry(.3,6,6),new c.MeshBasicMaterial({color:15658734,opacity:.7,transparent:!0,depthTest:!1,depthWrite:!1,side:c.DoubleSide}));return e.layers.disableAll(),e.layers.enable(2),e}createRayLineObject(){const e=new q.Line2;e.layers.disableAll(),e.layers.enable(2);const t=new q.LineGeometry;e.geometry=t;const i=new Float32Array(9);i.set([0,0,.02,0,0,.4,0,0,1]),t.setPositions(i);const n=new Float32Array(9);n.set([1,1,1,.1,.1,.1,0,0,0]),t.setColors(n);const o=new q.LineMaterial({color:16777215,vertexColors:!0,worldUnits:!0,linewidth:.004,transparent:!0,depthWrite:!1,blending:c.AdditiveBlending,dashed:!1});return e.material=o,e}}fo([f()],gi.prototype,"movementSpeed");fo([f()],gi.prototype,"rotationStep");fo([f()],gi.prototype,"useTeleport");fo([f()],gi.prototype,"usePinchToTeleport");fo([f()],gi.prototype,"useTeleportTarget");fo([f()],gi.prototype,"useTeleportFade");fo([f()],gi.prototype,"showRays");fo([f()],gi.prototype,"showHits");const wM=new c.Vector3(0,1,0);var xM=Object.defineProperty,lt=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&xM(e,t,n),n};const ll=x("debugwebxr"),SM=x("debugusdz"),Je=class Jr extends E{createVRButton=!0;createARButton=!0;createSendToQuestButton=!0;createQRCode=!0;useDefaultControls=!0;showControllerModels=!0;showHandModels=!0;usePlacementReticle=!0;customARPlacementReticle;usePlacementAdjustment=!0;arScale=1;useXRAnchor=!1;autoPlace=!1;autoCenter=!1;useQuicklookExport=!1;useDepthSensing=!1;useSpatialGrab=!0;defaultAvatar;_playerSync;_createdComponentsInSession=[];_usdzExporter;static activeWebXRComponent=null;awake(){G.getXRSync(this.context)}onEnable(){window.location.protocol!=="https:"&&de('<a href="https://developer.mozilla.org/en-US/docs/Web/API/WebXR_Device_API" target="_blank">WebXR</a> only works on secure connections (https).'),this.useQuicklookExport&&(S.findObjectOfType(sn)||(ll&&console.log("WebXR: Adding USDZExporter"),this._usdzExporter=S.addComponent(this.gameObject,sn),this._usdzExporter.objectToExport=this.context.scene,this._usdzExporter.autoExportAnimations=!0,this._usdzExporter.autoExportAudioSources=!0)),this.handleCreatingHTML(),this.handleOfferSession(),this.defaultAvatar===!0&&(ll&&console.warn("WebXR: No default avatar set, using static default avatar"),this.defaultAvatar=new Y("https://cdn.needle.tools/static/avatars/DefaultAvatar.glb")),this.defaultAvatar&&(this._playerSync=this.gameObject.getOrAddComponent(Dg),this._playerSync.autoSync=!1),this._playerSync&&typeof this.defaultAvatar!="boolean"&&(this._playerSync.asset=this.defaultAvatar,this._playerSync.onPlayerSpawned?.removeEventListener(this.onAvatarSpawned),this._playerSync.onPlayerSpawned?.addEventListener(this.onAvatarSpawned))}onDisable(){this._usdzExporter?.destroy(),this.removeButtons()}async handleOfferSession(){return this.createVRButton&&await G.isVRSupported()&&this.createVRButton?G.offerSession("immersive-vr","default",this.context):this.createARButton&&await G.isARSupported()&&this.createARButton?G.offerSession("immersive-ar","default",this.context):!1}get session(){return G.active??null}get sessionMode(){return G.activeMode??null}get arSessionRoot(){return this._activeWebARSessionRoot}async enterVR(e){return G.start("immersive-vr",e,this.context)}async enterAR(e){return G.start("immersive-ar",e,this.context)}exitXR(){G.stop()}_exitXRMenuButton;_previousXRState=0;_spatialGrabRaycaster;_activeWebARSessionRoot=null;get isActiveWebXR(){return!Jr.activeWebXRComponent||Jr.activeWebXRComponent===this}onBeforeXR(e,t){if(!this.isActiveWebXR){console.warn(`WebXR: another WebXR component is already active (${Jr.activeWebXRComponent?.name}). This is ignored: ${this.name}`);return}Jr.activeWebXRComponent=this,e=="immersive-ar"&&this.useDepthSensing&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.push("depth-sensing"))}async onEnterXR(e){if(!this.isActiveWebXR)return;ll&&console.log("WebXR onEnterXR"),this._previousXRState=jt.Global.Mask;const t=e.xr.isVR;if(jt.Global.Set(t?Mn.VR:Mn.AR),e.xr.isAR){let i=S.findObjectOfType(di);if(!i)if(this.usePlacementReticle){const n=new c.Object3D;for(const o of this.context.scene.children)n.add(o);this.context.scene.add(n),i=S.addComponent(n,di),this._createdComponentsInSession.push(i)}else(ll||A())&&console.warn("WebXR: No WebARSessionRoot found in scene and usePlacementReticle is disabled in WebXR component.");this._activeWebARSessionRoot=i,i&&(i.customReticle=this.customARPlacementReticle,i.arScale=this.arScale,i.arTouchTransform=this.usePlacementAdjustment,i.autoPlace=this.autoPlace,i.autoCenter=this.autoCenter,i.useXRAnchor=this.useXRAnchor)}this.useDefaultControls&&this.setDefaultMovementEnabled(!0),(this.showControllerModels||this.showHandModels)&&this.setDefaultControllerRenderingEnabled(!0),this.useSpatialGrab&&(this._spatialGrabRaycaster=S.findObjectOfType(nr)??void 0,this._spatialGrabRaycaster||(this._spatialGrabRaycaster=this.gameObject.addComponent(nr))),this.createLocalAvatar(e.xr),e.xr.isScreenBasedAR||(this._exitXRMenuButton=this.context.menu.appendChild({label:"Quit XR",onClick:()=>this.exitXR(),icon:"exit_to_app",priority:2e4}))}onUpdateXR(e){this.isActiveWebXR&&this._spatialGrabRaycaster&&(this._spatialGrabRaycaster.enabled=this.useSpatialGrab)}onLeaveXR(e){if(this._exitXRMenuButton?.remove(),!!this.isActiveWebXR){jt.Global.Set(this._previousXRState),this._playerSync?.destroyInstance();for(const t of this._createdComponentsInSession)t.destroy();this._createdComponentsInSession.length=0,this._activeWebARSessionRoot=null,this.handleOfferSession(),wc(1).then(()=>Jr.activeWebXRComponent=null)}}setDefaultMovementEnabled(e){let t=this.gameObject.getComponent(gi);return!t&&e&&(t=this.gameObject.addComponent(gi),this._createdComponentsInSession.push(t)),t&&(t.enabled=e),t}setDefaultControllerRenderingEnabled(e){let t=this.gameObject.getComponent(ds);return!t&&e&&(t=this.gameObject.addComponent(ds),this._createdComponentsInSession.push(t),t.createControllerModel=this.showControllerModels,t.createHandModel==this.showHandModels),t&&(t.enabled=e),t}async createLocalAvatar(e){this._playerSync&&e.running&&typeof this.defaultAvatar!="boolean"&&(this._playerSync.asset=this.defaultAvatar,await this._playerSync.getInstance())}onAvatarSpawned=e=>{ll&&console.log("WebXR.onAvatarSpawned",e);let t=S.getComponentInChildren(e,io);t??=S.addComponent(e,io)};getButtonsContainer(){return this.getButtonsFactory()}getButtonsFactory(){return this._buttonFactory||(this._buttonFactory=Zs.getOrCreate()),this._buttonFactory}_buttonFactory;handleCreatingHTML(){if(this.createARButton||this.createVRButton||this.useQuicklookExport){if((exports.DeviceUtilities.isiOS()&&exports.DeviceUtilities.isSafari()||SM)&&this.useQuicklookExport){const t=S.findObjectOfType(sn);if(!t||t&&t.allowCreateQuicklookButton){const i=this.getButtonsFactory().createQuicklookButton();this.addButton(i,50)}}if(this.createARButton){const t=this.getButtonsFactory().createARButton();this.addButton(t,50)}if(this.createVRButton){const t=this.getButtonsFactory().createVRButton();this.addButton(t,50)}}if(this.createSendToQuestButton&&!exports.DeviceUtilities.isQuest()&&G.isVRSupported().then(t=>{if(!t){const i=this.getButtonsFactory().createSendToQuestButton();this.addButton(i,50)}}),this.createQRCode){const t=ka(Nn);if(t&&t.createQRCodeButton===!1)A()&&console.warn("WebXR: QRCode button is disabled in the Needle Menu component");else if(!exports.DeviceUtilities.isMobileDevice()){const i=Ji.getOrCreate().createQRCode();this.addButton(i,50)}}}_buttons=[];addButton(e,t){this._buttons.push(e),e.setAttribute("priority",t.toString()),this.context.menu.appendChild(e)}removeButtons(){for(const e of this._buttons)e.remove();this._buttons.length=0}};lt([f()],Je.prototype,"createVRButton");lt([f()],Je.prototype,"createARButton");lt([f()],Je.prototype,"createSendToQuestButton");lt([f()],Je.prototype,"createQRCode");lt([f()],Je.prototype,"useDefaultControls");lt([f()],Je.prototype,"showControllerModels");lt([f()],Je.prototype,"showHandModels");lt([f()],Je.prototype,"usePlacementReticle");lt([f(Y)],Je.prototype,"customARPlacementReticle");lt([f()],Je.prototype,"usePlacementAdjustment");lt([f()],Je.prototype,"arScale");lt([f()],Je.prototype,"useXRAnchor");lt([f()],Je.prototype,"autoPlace");lt([f()],Je.prototype,"autoCenter");lt([f()],Je.prototype,"useQuicklookExport");lt([f()],Je.prototype,"useDepthSensing");lt([f()],Je.prototype,"useSpatialGrab");lt([f(Y)],Je.prototype,"defaultAvatar");let ku=Je;const zh=x("debugusdzbehaviours");class Ig{get extensionName(){return"Behaviour"}behaviours=[];addBehavior(e){this.behaviours.push(e)}addAudioClip(e){if(!e||typeof e!="string")return"";const i="audio/"+br.getName(e);return this.audioClips.push({clipUrl:e,filesKey:i}),i}behaviourComponents=[];behaviourComponentsCopy=[];audioClips=[];audioClipsCopy=[];targetUuids=new Set;getAllTargetUuids(){return this.targetUuids}onBeforeBuildDocument(e){if(!e.root)return Promise.resolve();const t=[];return e.root.traverse(i=>{S.foreachComponent(i,n=>{const o=n;if(typeof o.createBehaviours=="function"||typeof o.beforeCreateDocument=="function"||typeof o.afterCreateDocument=="function"||typeof o.afterSerialize=="function"){this.behaviourComponents.push(o);const r=o.beforeCreateDocument?.call(o,this,e);r instanceof Promise&&t.push(r)}},!1)}),zh&&console.log("onBeforeBuildDocument: all components",this.behaviourComponents),Promise.all(t)}onExportObject(e,t,i){for(const n of this.behaviourComponents)n.createBehaviours?.call(n,this,t,i)}onAfterBuildDocument(e){for(const u of this.behaviourComponents)typeof u.afterCreateDocument=="function"&&u.afterCreateDocument(this,e);this.behaviourComponentsCopy=this.behaviourComponents.slice(),this.behaviourComponents.length=0,this.audioClipsCopy=this.audioClips.slice(),this.audioClips.length=0;const t=new Set,i=new Set,n=new Set,o=new Set,r=zh;let a=`graph LR
1275
+ `))}for(const z of k){const K=o.get(z);K&&U.set(z,K)}return U},m=function(k){const U=p(k),z=l(U);return h(U,z,k)};const y=n.skinnedMesh.skeleton,_=new Array,g=[],w=[];for(const k of y.bones){g.push(k),w.push(k.uuid);const U=y.boneInverses[y.bones.indexOf(k)];_.push({bone:k,inverse:U})}let b=1e4;for(;w.length<y.bones.length&&b-- >0;)for(const k of g){const U=k.children;for(const z of U)if(w.indexOf(z.uuid)===-1&&y.bones.indexOf(z)!==-1){g.push(z),w.push(z.uuid);const K=y.boneInverses[y.bones.indexOf(z)];_.push({bone:z,inverse:K})}}b<=0&&console.error("Failed to sort bones in skinned mesh",n.skinnedMesh,y.bones,w);for(const k of rw(y.bones))_.push({bone:k,inverse:k.matrixWorld.clone().invert()});const v=_[0].bone.parent;v||console.error("No bone parent found for skinned mesh during USDZ export",n.skinnedMesh),_.sort((k,U)=>ua(k.bone,v)>ua(U.bone,v)?1:-1);const R=t.quickLookCompatible,O=[],M=[],T=[],D=[];for(const{bone:k}of _){if(R){const U=k.scale;U.x==0&&(U.x=1e-5),U.y==0&&(U.y=1e-5),U.z==0&&(U.z=1e-5),O.push(new c.Matrix4().compose(k.position,k.quaternion,k.scale))}else O.push(k.matrix.clone());M.push(k.position),T.push(k.quaternion),D.push(k.scale)}const I=_.map(k=>'"'+ua(k.bone,v)+'"').join(", "),V=_.map(k=>W_(k.inverse.clone().invert())).join(", ");e.beginBlock('def Skeleton "Rig"'),e.appendLine(`uniform matrix4d[] bindTransforms = [${V}]`),e.appendLine(`uniform token[] joints = [${I}]`),e.appendLine('uniform token purpose = "guide"'),e.appendLine(`uniform matrix4d[] restTransforms = [${O.map(k=>W_(k)).join(", ")}]`);const W=m(_.map(k=>k.bone));if(Pn){let k=1e7,U=0;for(const z of W.position?.keys()??[])k=Math.min(k,z),U=Math.max(U,z);console.log("Time samples",k,U,W)}if(e.beginBlock('def SkelAnimation "_anim"'),e.appendLine(`uniform token[] joints = [${I}]`),e.appendLine(`quatf[] rotations = [${u(T)}]`),W&&W.quaternion){e.beginBlock("quatf[] rotations.timeSamples = {","");const k=a(W.quaternion);for(const U of k)e.appendLine(U);e.closeBlock()}if(e.appendLine(`half3[] scales = [${d(D)}]`),W&&W.scale){e.beginBlock("half3[] scales.timeSamples = {","");const k=r(W.scale);for(const U of k)e.appendLine(U);e.closeBlock()}if(e.appendLine(`float3[] translations = [${d(M)}]`),W&&W.position){e.beginBlock("float3[] translations.timeSamples = {","");const k=r(W.position);for(const U of k)e.appendLine(U);e.closeBlock()}e.closeBlock(),e.closeBlock()}}onSerialize(e,t){if(!this.model)return;const i=this.animationData.get(this.object);if(i)for(let d=0;d<i.length;d++)i[d]===void 0&&(i[d]=new ke(null,this.object,null));const n=this.ext;this.skinnedMeshExport(e,t,n);const o=this.object,r=this.model,a=this.animationData.get(o);if(!a||o.isSkinnedMesh)return;qp&&console.log("SERIALIZE",this.model.name,this.object.type,a);const l=Intl.NumberFormat("en-US",{maximumFractionDigits:3,minimumFractionDigits:0,useGrouping:!1});function h(d,u){if(d.some(m=>m&&{position:m.pos,rotation:m.rot,scale:m.scale}[u])){switch(u){case"position":r.needsTranslate=!0,e.beginBlock("double3 xformOp:translate.timeSamples = {","");break;case"rotation":r.needsOrient=!0,e.beginBlock("quatf xformOp:orient.timeSamples = {","");break;case"scale":r.needsScale=!0,e.beginBlock("double3 xformOp:scale.timeSamples = {","");break}for(let m=0;m<d.length;m++){const y=d[m];if(!y)continue;const _=n.getStartTimeByClip(y.clip),g=y.getSortedTimesArray(u==="position",u==="rotation",u==="scale");if(!g||g.length===0){console.error("got an animated object but no time values?",o,y);continue}const w=!y.clip,b=u==="position"&&(y.pos||w),v=u==="rotation"&&(y.rot||w),R=u==="scale"&&(y.scale||w);if(b||v||R){const O=y.clip?.name??"rest",M=y.getDuration();Pn&&console.log("Write .timeSamples:",O,_,M,d),e.appendLine("# "+O+": start="+l.format(_*ke.frameRate)+", length="+l.format(M*ke.frameRate)+", frames="+y.getFrames())}if(b)for(const{time:O,translation:M}of y.getValues(g,!0,!1,!1)){const D=`${l.format((_+O)*ke.frameRate)}: (${te(M.x)}, ${te(M.y)}, ${te(M.z)}),`;e.appendLine(D)}if(v)for(const{time:O,rotation:M}of y.getValues(g,!1,!0,!1)){const D=`${l.format((_+O)*ke.frameRate)}: (${te(M.w)}, ${te(M.x)}, ${te(M.y)}, ${te(M.z)}),`;e.appendLine(D)}if(R)for(const{time:O,scale:M}of y.getValues(g,!1,!1,!0)){const D=`${l.format((_+O)*ke.frameRate)}: (${te(M.x)}, ${te(M.y)}, ${te(M.z)}),`;e.appendLine(D)}}e.closeBlock()}}h(a,"position"),h(a,"rotation"),h(a,"scale")}}const sM=x("debugusdz");class br{static getName(e){const t=e.split(".").pop();let n=e.split(".").slice(0,-1).join(".").split("/").pop()?.replace(".","_");return n||(n="Audio_"+Math.random().toString(36).substring(2,15)),mi(n)+"."+t}get extensionName(){return"Audio"}files=new Array;onExportObject(e,t,i){const n=S.getComponents(e,pi);if(n.length)for(const o of n){if(!o.clip||typeof o.clip!="string"||!o.playOnAwake)continue;const r=o.clip.split("/").pop()||"Audio",a=br.getName(o.clip),l=mi(a);if(!this.files.some(h=>h.path===o.clip)){this.files.push({path:o.clip,name:a});const h=a.toLowerCase();i.quickLookCompatible&&!h.endsWith(".mp3")&&!h.endsWith(".wav")&&!h.endsWith(".m4a")&&console.error("Audio file "+o.clip+" from "+o.name+" is not an MP3 or WAV file. QuickLook may not support playing it.")}i.quickLookCompatible||t.addEventListener("serialize",(h,d)=>{h.appendLine(),h.beginBlock(`def SpatialAudio "${l}"`,"(",!1),h.appendLine(`displayName = "${r}"`),h.closeBlock(")"),h.beginBlock(),h.appendLine(`uniform asset filePath = @audio/${a}@`),h.appendLine(`uniform token auralMode = "${o.spatialBlend>0?"spatial":"nonSpatial"}"`),h.appendLine(`uniform token playbackMode = "${o.loop?"loopFromStage":"onceFromStart"}"`),h.appendLine(`uniform float gain = ${o.volume}`),h.closeBlock()})}}async onAfterSerialize(e){for(const t of this.files){const i="audio/"+t.name;if(e.files[i]){sM&&console.warn("Audio file with name "+i+" already exists in the context. Skipping.");continue}const r=await(await(await fetch(t.path)).blob()).arrayBuffer(),a=new Uint8Array(r);e.files[i]=a}}}var oM=Object.defineProperty,Ee=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&oM(e,t,n),n};const Q_=x("debugusdzbehaviours");function zc(s){s&&(s.getComponentInParent(xa)||(A()&&console.debug('Raycaster on "'+s.name+'" was automatically added, because no raycaster was found in the parent hierarchy.'),s.addComponent(fi)))}class vr extends E{object;target;duration=1;relativeMotion=!1;coroutine=null;targetPos=new c.Vector3;targetRot=new c.Quaternion;targetScale=new c.Vector3;start(){zc(this.gameObject)}onPointerEnter(){this.context.input.setCursor("pointer")}onPointerExit(){this.context.input.unsetCursor("pointer")}onPointerClick(e){e.use(),this.coroutine&&this.stopCoroutine(this.coroutine),this.relativeMotion?this.coroutine=this.startCoroutine(this.moveRelative()):this.coroutine=this.startCoroutine(this.moveToTarget())}*moveToTarget(){if(!this.target||!this.object)return;const e=X(this.object).clone(),t=X(this.target).clone(),i=ue(this.object).clone(),n=ue(this.target).clone(),o=je(this.object).clone(),r=je(this.target).clone(),a=e.distanceTo(t),l=i.angleTo(n),h=o.distanceTo(r);if(a<.01&&l<.01&&h<.01){ot(this.object,t),on(this.object,n),ga(this.object,r),this.coroutine=null;return}let d=0,u=0;for(;d<1;)d+=this.context.time.deltaTime/this.duration,d>1&&(d=1),u=d<.5?4*d*d*d:1-Math.pow(-2*d+2,3)/2,this.targetPos.lerpVectors(e,t,u),this.targetRot.slerpQuaternions(i,n,u),this.targetScale.lerpVectors(o,r,u),ot(this.object,this.targetPos),on(this.object,this.targetRot),ga(this.object,this.targetScale),yield;this.coroutine=null}*moveRelative(){if(!this.target||!this.object)return;const e=this.object.position.clone(),t=this.object.quaternion.clone(),i=this.object.scale.clone(),n=this.target.position.clone(),o=this.target.quaternion.clone(),r=this.target.scale.clone();n.applyQuaternion(this.object.quaternion),this.targetPos.copy(this.object.position).add(n),this.targetRot.copy(this.object.quaternion).multiply(o),this.targetScale.copy(this.object.scale).multiply(r);let a=0,l=0;for(;a<1;)a+=this.context.time.deltaTime/this.duration,a>1&&(a=1),l=a<.5?4*a*a*a:1-Math.pow(-2*a+2,3)/2,this.object.position.lerpVectors(e,this.targetPos,l),this.object.quaternion.slerpQuaternions(t,this.targetRot,l),this.object.scale.lerpVectors(i,this.targetScale,l),yield;this.coroutine=null}beforeCreateDocument(e){if(this.target&&this.object&&this.gameObject){const t=new gt("Move to "+this.target?.name,St.tapTrigger(this.gameObject),le.transformAction(this.object,this.target,this.duration,this.relativeMotion?"relative":"absolute"));e.addBehavior(t)}}}Ee([f(c.Object3D)],vr.prototype,"object");Ee([f(c.Object3D)],vr.prototype,"target");Ee([f()],vr.prototype,"duration");Ee([f()],vr.prototype,"relativeMotion");const Su=class At extends E{materialToSwitch;variantMaterial;fadeDuration=0;start(){this._objectsWithThisMaterial=this.objectsWithThisMaterial,zc(this.gameObject),A()&&this._objectsWithThisMaterial.length<=0&&console.warn('ChangeMaterialOnClick: No objects found with material "'+this.materialToSwitch?.name+'"')}onPointerEnter(e){this.context.input.setCursor("pointer")}onPointerExit(e){this.context.input.unsetCursor("pointer")}onPointerClick(e){if(e.use(),!!this.variantMaterial)for(let t=0;t<this.objectsWithThisMaterial.length;t++){const i=this.objectsWithThisMaterial[t];i.material=this.variantMaterial}}_objectsWithThisMaterial=null;get objectsWithThisMaterial(){return this._objectsWithThisMaterial!=null?this._objectsWithThisMaterial:(this._objectsWithThisMaterial=[],this.variantMaterial&&this.materialToSwitch&&this.context.scene.traverse(e=>{if(e instanceof c.Mesh)if(Array.isArray(e.material)){for(const t of e.material)if(t===this.materialToSwitch){this.objectsWithThisMaterial.push(e);break}}else e.material===this.materialToSwitch?this.objectsWithThisMaterial.push(e):L0(e.material,this.materialToSwitch)&&this.objectsWithThisMaterial.push(e)}),this._objectsWithThisMaterial)}selfModel;targetModels;static _materialTriggersPerId={};static _startHiddenBehaviour=null;static _parallelStartHiddenActions=[];async beforeCreateDocument(e,t){this.targetModels=[],At._materialTriggersPerId={},At.variantSwitchIndex=0,this.materialToSwitch&&await ne.NEEDLE_progressive.assignTextureLOD(this.materialToSwitch,0),this.variantMaterial&&await ne.NEEDLE_progressive.assignTextureLOD(this.variantMaterial,0)}createBehaviours(e,t,i){this.objectsWithThisMaterial.find(o=>o.uuid===t.uuid)&&this.targetModels.push(t),this.gameObject.uuid===t.uuid&&(this.selfModel=t,this.materialToSwitch&&(At._materialTriggersPerId[this.materialToSwitch.uuid]||(At._materialTriggersPerId[this.materialToSwitch.uuid]=[]),At._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(e,t){if(!this.materialToSwitch)return;const i=At._materialTriggersPerId[this.materialToSwitch.uuid];if(i){const n={};for(const o of i){const r=o.createVariants();r&&r.length>0&&(n[o.selfModel.uuid]=r)}for(const o of i){const r=[];for(const a in n)a!==o.selfModel.uuid&&r.push(...n[a]);o.createAndAttachBehaviors(e,n[o.selfModel.uuid],r)}}delete At._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(e,t,i){const n=[],o=Math.max(0,this.fadeDuration);n.push(le.fadeAction([...this.targetModels,...i],o,!1)),n.push(le.fadeAction(t,o,!0)),e.addBehavior(new gt("Select_"+this.selfModel.name,St.tapTrigger(this.selfModel),le.parallel(...n))),At._parallelStartHiddenActions.push(...t),At._startHiddenBehaviour||(At._startHiddenBehaviour=new gt("StartHidden_"+this.selfModel.name,St.sceneStartTrigger(),le.fadeAction(At._parallelStartHiddenActions,o,!1)),e.addBehavior(At._startHiddenBehaviour))}static getMaterialName(e){return mi(e.name||"Material")+"_"+e.id}static variantSwitchIndex=0;createVariants(){if(!this.variantMaterial)return null;const e=[];for(const t of this.targetModels){const i=t.clone();i.name+="_Variant_"+At.variantSwitchIndex+++"_"+At.getMaterialName(this.variantMaterial),i.displayName=i.displayName+": Variant with material "+this.variantMaterial.name,i.material=this.variantMaterial,i.geometry=t.geometry,i.transform=t.transform,(!t.parent||!t.parent.isEmpty())&&Ne.createEmptyParent(t),t.parent&&t.parent.add(i),e.push(i)}return e}};Ee([f(c.Material)],Su.prototype,"materialToSwitch");Ee([f(c.Material)],Su.prototype,"variantMaterial");Ee([f()],Su.prototype,"fadeDuration");let Og=Su;const Nc=class Pe extends E{target;toggleOnClick=!1;targetState=!0;hideSelf=!0;start(){zc(this.gameObject)}onPointerEnter(){this.context.input.setCursor("pointer")}onPointerExit(){this.context.input.unsetCursor("pointer")}onPointerClick(e){e.use(),!this.toggleOnClick&&this.hideSelf&&(this.gameObject.visible=!1),this.target&&(this.target.visible=this.toggleOnClick?!this.target.visible:this.targetState)}selfModel;selfModelClone;targetModel;toggleModel;createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.selfModel=t,this.selfModelClone=t.clone())}stateBeforeCreatingDocument=!1;targetStateBeforeCreatingDocument=!1;static clonedToggleIndex=0;static wasVisible=Symbol("usdz_SetActiveOnClick_wasVisible");static toggleClone=Symbol("clone for toggling");static reverseToggleClone=Symbol("clone for reverse toggling");beforeCreateDocument(){this.target&&(this.gameObject[Pe.wasVisible]===void 0&&(this.gameObject[Pe.wasVisible]=this.gameObject.activeSelf),this.target[Pe.wasVisible]===void 0&&(this.target[Pe.wasVisible]=this.target.activeSelf),this.stateBeforeCreatingDocument=this.gameObject[Pe.wasVisible],this.targetStateBeforeCreatingDocument=this.target[Pe.wasVisible],this.gameObject.visible=!0,this.target.visible=!0)}afterCreateDocument(e,t){if(!this.target)return;this.targetModel=t.document.findById(this.target.uuid);const i=this.selfModel;if(this.selfModel&&this.targetModel){let n=this.selfModel,o=this.targetState;if(this.toggleOnClick)if(o=!this.targetStateBeforeCreatingDocument,!this.selfModelClone.geometry)(!this.selfModel.parent||this.selfModel.parent.isEmpty())&&Sg.createEmptyParent(this.selfModel),this.toggleModel=this.selfModel.deepClone(),this.toggleModel.name+="_toggle",this.selfModel.parent.add(this.toggleModel);else{if(!this.gameObject[Pe.toggleClone]){const l=this.selfModelClone.clone();l.setMatrix(new c.Matrix4),l.name+="_toggle"+Pe.clonedToggleIndex++,i.add(l),this.gameObject[Pe.toggleClone]=l,console.warn("USDZExport: Toggle "+this.gameObject.name+" doesn't have geometry. It will be deep cloned and nested behaviours will likely not work.")}const a=this.gameObject[Pe.toggleClone];if(!this.gameObject[Pe.reverseToggleClone]){const l=this.selfModelClone.clone();l.setMatrix(new c.Matrix4),l.name+="_toggleReverse"+Pe.clonedToggleIndex++,i.add(l),this.gameObject[Pe.reverseToggleClone]=l}this.toggleModel=this.gameObject[Pe.reverseToggleClone],(!this.toggleModel.geometry||!a.geometry)&&console.error("triggers without childs and without geometry won't work!",this,i.geometry),n=a,i.geometry=null,i.material=null}if(this.toggleModel){if(this.toggleOnClick){const a=[];a.push(le.fadeAction(n,0,!1)),a.push(le.fadeAction(this.toggleModel,0,!0)),a.push(le.fadeAction(this.targetModel,0,o)),e.addBehavior(new gt("Toggle_"+n.name+"_ToggleTo"+(o?"On":"Off"),St.tapTrigger(n),le.parallel(...a)));const l=[];l.push(le.fadeAction(this.toggleModel,0,!1)),l.push(le.fadeAction(n,0,!0)),l.push(le.fadeAction(this.targetModel,0,!o)),e.addBehavior(new gt("Toggle_"+n.name+"_ToggleTo"+(o?"Off":"On"),St.tapTrigger(this.toggleModel),le.parallel(...l)))}}else{const a=[];this.hideSelf&&a.push(le.fadeAction(n,0,!1)),a.push(le.fadeAction(this.targetModel,0,o)),e.addBehavior(new gt("Toggle_"+n.name+"_ToggleTo"+(o?"On":"Off"),St.tapTrigger(n),a.length>1?le.parallel(...a):a[0]))}const r=new Array;this.targetStateBeforeCreatingDocument||r.push(this.targetModel),this.stateBeforeCreatingDocument||r.push(i),this.toggleModel&&r.push(this.toggleModel),Ei.add(r,e)}}afterSerialize(e,t){this.gameObject[Pe.wasVisible]!==void 0&&(this.gameObject.visible=this.gameObject[Pe.wasVisible],delete this.gameObject[Pe.wasVisible]),this.target&&this.target[Pe.wasVisible]!==void 0&&(this.target.visible=this.target[Pe.wasVisible],delete this.target[Pe.wasVisible]),delete this.gameObject[Pe.toggleClone],delete this.gameObject[Pe.reverseToggleClone]}};Ee([f(c.Object3D)],Nc.prototype,"target");Ee([f()],Nc.prototype,"toggleOnClick");Ee([f()],Nc.prototype,"targetState");Ee([f()],Nc.prototype,"hideSelf");let Mg=Nc;class Ei extends E{static _fadeBehaviour;static _fadeObjects=[];static add(e,t){const i=Array.isArray(e)?e:[e];for(const n of i)Ei._fadeObjects.includes(n)||(console.log("adding hide on start",n),Ei._fadeObjects.push(n));Ei._fadeBehaviour===void 0&&(Ei._fadeBehaviour=new gt("HideOnStart",St.sceneStartTrigger(),le.fadeAction(Ei._fadeObjects,0,!1)),t.addBehavior(Ei._fadeBehaviour))}start(){S.setActive(this.gameObject,!1)}createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.wasVisible||Ei.add(t,e))}wasVisible=!1;beforeCreateDocument(){this.wasVisible=S.isActiveSelf(this.gameObject)}}class La extends E{target;duration=.5;motionType="bounce";beforeCreateDocument(){}createBehaviours(e,t,i){if(this.target&&t.uuid===this.gameObject.uuid){const n=new gt("emphasize "+this.name,St.tapTrigger(this.gameObject),le.emphasize(this.target,this.duration,this.motionType,void 0,"basic"));e.addBehavior(n)}}afterCreateDocument(e,t){}}Ee([f()],La.prototype,"target");Ee([f()],La.prototype,"duration");Ee([f()],La.prototype,"motionType");class to extends E{target;clip="";toggleOnClick=!1;trigger="tap";start(){zc(this.gameObject)}ensureAudioSource(){if(!this.target){const e=this.gameObject.addComponent(pi);e&&(this.target=e,e.spatialBlend=1,e.volume=1,e.loop=!1,e.preload=!0)}}onPointerEnter(){this.context.input.setCursor("pointer")}onPointerExit(){this.context.input.unsetCursor("pointer")}onPointerClick(e){e.use(),!(!this.target?.clip&&!this.clip)&&(this.ensureAudioSource(),this.target&&(this.target.isPlaying&&this.toggleOnClick?this.target.stop():(!this.toggleOnClick&&this.target.isPlaying&&this.target.stop(),this.clip?this.target.play(this.clip):this.target.play())))}createBehaviours(e,t,i){if(!(!this.target&&!this.clip)&&t.uuid===this.gameObject.uuid){const n=this.clip?this.clip:this.target?this.target.clip:void 0;if(!n||typeof n!="string")return;const o=this.target?this.target.gameObject:this.gameObject;br.getName(n);const r=this.target?this.target.volume:1,a=this.target&&this.target.spatialBlend==0?"nonSpatial":"spatial";let l=!1;this.gameObject.traverse(p=>{p instanceof c.Mesh&&p.visible&&(l=!0)}),l=!0;const h=e.addAudioClip(n);let d=le.playAudioAction(o,h,"play",r,a);this.target&&this.target.loop&&(d=le.sequence(d).makeLooping());const u=this.name?"_"+this.name:"";if(l&&this.trigger==="tap"){this.toggleOnClick&&(d.multiplePerformOperation="stop");const p=new gt("playAudio"+u,St.tapTrigger(t),d);e.addBehavior(p)}if(this.target&&this.target.playOnAwake&&this.target.enabled)if(l&&this.trigger==="tap")console.warn("USDZExport: Audio sources that are played on tap can't also auto-play at scene start due to a QuickLook bug.");else{const p=new gt("playAudioOnStart"+u,St.sceneStartTrigger(),d);e.addBehavior(p)}}}}Ee([f(pi)],to.prototype,"target");Ee([f(URL)],to.prototype,"clip");Ee([f()],to.prototype,"toggleOnClick");const kg=class vn extends E{animator;stateName;trigger="tap";animation;get target(){return this.animator?.gameObject||this.animation?.gameObject}start(){zc(this.gameObject)}onPointerEnter(){this.context.input.setCursor("pointer")}onPointerExit(){this.context.input.unsetCursor("pointer")}onPointerClick(e){e.use(),this.target&&this.stateName&&this.animator?.play(this.stateName,0,0,.1)}selfModel;stateAnimationModel;animationSequence=new Array;animationLoopAfterSequence=new Array;randomOffsetNormalized=0;createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.selfModel=t)}static animationActions=[];static rootsWithExclusivePlayback=new Set;afterSerialize(){if(vn.rootsWithExclusivePlayback.size>1){const e='Multiple root objects targeted by more than one animation. To work around QuickLook bug FB13410767, animations will be set as "exclusive" and activating them will stop other animations being marked as exclusive.';A()&&de(e),console.warn(e,...vn.rootsWithExclusivePlayback)}vn.animationActions=[],vn.rootsWithExclusivePlayback=new Set}afterCreateDocument(e,t){if(this.animationSequence===void 0&&this.animationLoopAfterSequence===void 0||!this.stateAnimationModel||!this.target)return;const i=t.document,n=t.extensions.find(a=>a instanceof xu);if(!n)return;const o=n.getClipCount(this.target)>1;o&&(A()&&console.warn("Setting exclusive playback for "+this.target.name+"@"+this.stateName+" because it has "+n.getClipCount(this.target)+" animations. This works around QuickLook bug FB13410767."),vn.rootsWithExclusivePlayback.add(this.target));const r=this.name?this.name:"";i.traverse(a=>{if(a.uuid===this.target?.uuid){const l=vn.getActionForSequences(i,a,this.animationSequence,this.animationLoopAfterSequence,this.randomOffsetNormalized),h=new gt(this.trigger+"_"+r+"_toPlayAnimation_"+this.stateName+"_on_"+this.target?.name,this.trigger=="tap"?St.tapTrigger(this.selfModel):St.sceneStartTrigger(),l);o&&h.makeExclusive(!0),e.addBehavior(h)}})}static getActionForSequences(e,t,i,n,o){const r=(l,h)=>{let d=vn.animationActions.find(u=>u.affectedObjects==l&&u.start==h.start&&u.duration==h.duration&&u.animationSpeed==h.speed);return d||(d=le.startAnimationAction(l,h),vn.animationActions.push(d)),d},a=le.sequence();if(i&&i.length>0)for(const l of i)a.addAction(r(t,l));if(n&&n.length>0){const l=a.actions.length==0?a:le.sequence();for(const h of n)l.addAction(r(t,h));l.makeLooping(),a!==l&&a.addAction(l)}return o&&o>0&&a.actions.unshift(le.waitAction(o)),a}static getAndRegisterAnimationSequences(e,t,i){if(!t)return;const n=t.getComponent(rt),o=t.getComponent(Ct);if(!n&&!o)return;if(n&&!i)throw new Error("PlayAnimationOnClick: No stateName specified for animator "+n.name+" on "+t.name);let r=[],a=[];if(o){const y=e.registerAnimation(t,o.clip);y&&(o.loop?a.push(y):r.push(y));let _=0;if(o.minMaxOffsetNormalized){const g=o.minMaxOffsetNormalized.x,w=o.minMaxOffsetNormalized.y;_=(o.clip?.duration||1)*(g+Math.random()*(w-g))}return{animationSequence:r,animationLoopAfterSequence:a,randomTimeOffset:_}}const l=n?.runtimeAnimatorController;let h=l?.findState(i),d=[],u=[];if(l&&h){const y=new Array;y.push(h);let _=!1;for(;y.length<100;){if(!h||h===null||!h.transitions||h.transitions.length===0){h.motion?.isLooping&&(_=!0);break}const g=h.transitions.find(b=>b.conditions.length===0),w=g?l.getState(g.destinationState,0):null;if(w&&y.includes(w)){h=w,_=!0;break}else if(g){if(h=w,!h)break;y.push(h)}else{_=h.motion?.isLooping??!1;break}}if(_&&h){const g=y.indexOf(h);d=y.slice(0,g),u=y.slice(g),Q_&&console.log("found loop from "+i,"states until loop",d,"states looping",u)}else d=y,u=[],Q_&&console.log("found no loop from "+i,"states",d);if(!u.length){const g=d[d.length-1],w=g.motion?.clip;if(w){let b;if(e.holdClipMap.has(w))b=e.holdClipMap.get(w);else{const v=g.name+"_hold";b=w.clone(),b.duration=1,b.name=v;const R=w.duration;b.tracks=w.tracks.map(O=>{const M=O.clone();M.times=new Float32Array([0,R]);const T=O.values.length,D=O.getValueSize(),I=O.values.slice(T-D,T);return M.values=new Float32Array(2*D),M.values.set(I,0),M.values.set(I,D),M}),b.name=v,e.holdClipMap.set(w,b)}if(b){const v={name:b.name,motion:{clip:b,isLooping:!1,name:b.name},speed:1,transitions:[],behaviours:[],hash:g.hash+1};u.push(v)}}}}if(d.length===1&&(!d[0].motion?.clip||d[0].motion?.clip.tracks?.length===0)){r=new Array;const y=e.registerAnimation(t,null);y&&r.push(y);return}if(d=d.filter(y=>y.motion?.clip&&y.motion?.clip.tracks?.length>0),u=u.filter(y=>y.motion?.clip&&y.motion?.clip.tracks?.length>0),d.length===0&&u.length===0){console.warn("No clips found for state "+i+" on "+n?.name+", can't export animation data");return}const p=(y,_)=>{if(!t)return;const g=e.registerAnimation(t,y.motion.clip??null);g?(g.speed=y.speed,_.push(g)):console.warn("Couldn't register animation for state "+y.name+" on "+n?.name)};if(d.length>0){r=new Array;for(const y of d)p(y,r)}if(u.length>0){a=new Array;for(const y of u)p(y,a)}let m=0;if(n&&l&&n.minMaxOffsetNormalized){const y=n.minMaxOffsetNormalized.x,_=n.minMaxOffsetNormalized.y;m=((d.length?d[0]:u.length?u[0]:null)?.motion.clip?.duration||1)*(y+Math.random()*(_-y))}return{animationSequence:r,animationLoopAfterSequence:a,randomTimeOffset:m}}createAnimation(e,t,i){if(!this.target||!this.animator&&!this.animation)return;const n=vn.getAndRegisterAnimationSequences(e,this.target,this.stateName);n&&(this.animationSequence=n.animationSequence,this.animationLoopAfterSequence=n.animationLoopAfterSequence,this.randomOffsetNormalized=n.randomTimeOffset,this.stateAnimationModel=t)}};Ee([f(rt)],kg.prototype,"animator");Ee([f()],kg.prototype,"stateName");let dc=kg;class Ia extends E{getType(){}target;getDuration(){}}Ee([f(c.Object3D)],Ia.prototype,"target");class Vc extends E{target}Ee([f(Ia)],Vc.prototype,"target");class $c extends Ia{type=1;duration=1;getType(){switch(this.type){case 1:return"hide";case 0:return"show"}}getDuration(){return this.duration}}Ee([f()],$c.prototype,"type");Ee([f()],$c.prototype,"duration");class Eg extends Vc{}class Zs{static _instance;static create(){return new Zs}static getOrCreate(){return this._instance||(this._instance=this.create()),this._instance}get isSecureConnection(){return window.location.protocol==="https:"}get quicklookButton(){return this._quicklookButton}_quicklookButton;get arButton(){return this._arButton}_arButton;get vrButton(){return this._vrButton}_vrButton;get sendToQuestButton(){return this._sendToQuestButton}_sendToQuestButton;get qrButton(){return Ji.getOrCreate().createQRCode()}createQuicklookButton(){if(this._quicklookButton)return this._quicklookButton;const e=document.createElement("button");this._quicklookButton=e,e.dataset.needle="quicklook-button";const t=exports.DeviceUtilities.supportsQuickLookAR();e.innerText="View in AR",e.prepend(pt("view_in_ar"));let i=!1,n=null;return e.addEventListener("click",()=>{n=ka(sn),n||(i=!0,n=new sn),i&&(n.objectToExport=N.Current.scene),n?(e.classList.add("this-mode-is-requested"),n.exportAndOpen().then(()=>{e.classList.remove("this-mode-is-requested")}).catch(o=>{e.classList.remove("this-mode-is-requested"),console.error(o)})):console.warn("No USDZExporter component found in the scene")}),this.hideElementDuringXRSession(e),e}createARButton(e){if(this._arButton)return this._arButton;const t="immersive-ar",i=document.createElement("button");return this._arButton=i,i.classList.add("webxr-button"),i.dataset.needle="webxr-ar-button",i.innerText="Enter AR",i.prepend(pt("view_in_ar")),i.title="Click to start an AR session",i.addEventListener("click",()=>G.start(t,e)),this.updateSessionSupported(i,t),this.listenToXRSessionState(i,t),this.hideElementDuringXRSession(i),this.isSecureConnection||(i.disabled=!0,i.title="WebXR requires a secure connection (HTTPS)"),exports.DeviceUtilities.isMozillaXR()||navigator.xr?.addEventListener("devicechange",()=>this.updateSessionSupported(i,t)),i}createVRButton(e){if(this._vrButton)return this._vrButton;const t="immersive-vr",i=document.createElement("button");return this._vrButton=i,i.classList.add("webxr-button"),i.dataset.needle="webxr-vr-button",i.innerText="Enter VR",i.prepend(pt("panorama_photosphere")),i.title="Click to start a VR session",i.addEventListener("click",()=>G.start(t,e)),this.updateSessionSupported(i,t),this.listenToXRSessionState(i,t),this.hideElementDuringXRSession(i),this.isSecureConnection||(i.disabled=!0,i.title="WebXR requires a secure connection (HTTPS)"),exports.DeviceUtilities.isMozillaXR()||navigator.xr?.addEventListener("devicechange",()=>this.updateSessionSupported(i,t)),i}createSendToQuestButton(){if(this._sendToQuestButton)return this._sendToQuestButton;const e="https://oculus.com/open_url/?url=",t=document.createElement("button");return this._sendToQuestButton=t,t.dataset.needle="webxr-sendtoquest-button",t.innerText="Open on Quest",t.prepend(pt("share_windows")),t.title="Click to send this page to the Oculus Browser on your Quest",t.addEventListener("click",()=>{const i=encodeURIComponent(window.location.href),n=e+i;window.open(n)==null&&Ce("This page doesn't allow popups. Please paste "+n+" into your browser.")}),this.listenToXRSessionState(t),this.hideElementDuringXRSession(t),exports.DeviceUtilities.isMozillaXR()||navigator.xr?.addEventListener("devicechange",()=>{navigator.xr?.isSessionSupported("immersive-vr")?t.style.display="none":t.style.display=""}),t}createQRCode(){return Ji.getOrCreate().createQRCode()}updateSessionSupported(e,t){if(!("xr"in navigator)){e.style.display="none";return}G.isSessionSupported(t).then(i=>{e.style.display=i?"":"none",A()&&!i&&console.log('[WebXR] "'+t+'" is not supported on this device – make sure your server runs using HTTPS and you have a device connected that supports '+t)})}hideElementDuringXRSession(e){Jd(t=>{e["previous-display"]=e.style.display,e.style.display="none"}),Om(t=>{e["previous-display"]!=null&&(e.style.display=e["previous-display"])})}listenToXRSessionState(e,t){t&&(G.onSessionRequestStart(i=>{i.mode===t?e.classList.add("this-mode-is-requested"):(e["was-disabled"]=e.disabled,e.disabled=!0,e.classList.add("other-mode-is-requested"))}),G.onSessionRequestEnd(i=>{e.classList.remove("this-mode-is-requested"),e.classList.remove("other-mode-is-requested"),e.disabled=e["was-disabled"]}))}}var rM=Object.defineProperty,aM=Object.getOwnPropertyDescriptor,at=(s,e,t,i)=>{for(var n=i>1?void 0:i?aM(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&rM(e,t,n),n};const Xl=x("debugspriterenderer"),lM=x("wireframe");class rr{static cache={};static getOrCreateGeometry(e){if(e.__cached_geometry)return e.__cached_geometry;if(e.guid&&rr.cache[e.guid])return Xl&&console.log("Take cached geometry for sprite",e.guid),rr.cache[e.guid];const t=new c.BufferGeometry;e.__cached_geometry=t;const i=new Float32Array(e.triangles.length*3),n=new Float32Array(e.triangles.length*2);for(let o=0;o<e.triangles.length;o+=1){const r=e.triangles[o];i[o*3]=-e.vertices[r].x,i[o*3+1]=e.vertices[r].y,i[o*3+2]=0;const a=e.uv[r];n[o*2]=a.x,n[o*2+1]=1-a.y}return t.setAttribute("position",new c.BufferAttribute(i,3)),t.setAttribute("uv",new c.BufferAttribute(n,2)),e.guid&&(this.cache[e.guid]=t),Xl&&console.log("Built sprite geometry",e,t),t}}class cM{x;y}function yw(s){s&&(s.colorSpace!=c.SRGBColorSpace&&(s.colorSpace=c.SRGBColorSpace,s.needsUpdate=!0),s.minFilter==c.NearestFilter&&s.magFilter==c.NearestFilter&&(s.anisotropy=1,s.needsUpdate=!0))}let ys=class{constructor(e){e&&(this.texture=e,this.triangles=[0,1,2,0,2,3],this.uv=[{x:0,y:0},{x:1,y:0},{x:1,y:1},{x:0,y:1}],this.vertices=[{x:-.5,y:-.5},{x:.5,y:-.5},{x:.5,y:.5},{x:-.5,y:.5}])}guid;texture;triangles;uv;vertices;__cached_geometry;get mesh(){return this._mesh||(this._mesh=new c.Mesh(rr.getOrCreateGeometry(this),this.material)),this._mesh}_mesh;get material(){return this._material||(this.texture&&yw(this.texture),this._material=new c.MeshBasicMaterial({map:this.texture,color:16777215,side:c.DoubleSide,transparent:!0})),this._material}_material;getGeometry(){return rr.getOrCreateGeometry(this)}};at([f()],ys.prototype,"guid",2);at([f(c.Texture)],ys.prototype,"texture",2);at([Be()],ys.prototype,"triangles",2);at([Be()],ys.prototype,"uv",2);at([Be()],ys.prototype,"vertices",2);const $f=Symbol("spriteOwner");class Sa{sprites;constructor(){this.sprites=[]}}at([f(ys)],Sa.prototype,"sprites",2);const Rg=class Xp{static create(){const e=new Xp;return e.spriteSheet=new Sa,e}constructor(){}clone(){const e=new Xp;return e.index=this.index,e.spriteSheet=this.spriteSheet,e}set sprite(e){e&&(this.spriteSheet?((this.index===null||this.index===void 0)&&(this.index=0),this.spriteSheet.sprites[this.index]=e):(this.spriteSheet=new Sa,this.spriteSheet.sprites=[e],this.index=0))}get sprite(){if(this.spriteSheet)return this.spriteSheet.sprites[this.index]}spriteSheet;index=0;update(e){if(!this.spriteSheet)return;const t=this.index;if(t<0||t>=this.spriteSheet.sprites.length)return;const i=this.spriteSheet.sprites[t],n=i?.texture;if(n&&(yw(n),!i.__hasLoadedProgressive)){i.__hasLoadedProgressive=!0;const o=n;ne.NEEDLE_progressive.assignTextureLOD(n,0).then(r=>{r instanceof c.Texture&&(i.texture=r,e?.map===o&&(e.map=r,e.needsUpdate=!0))})}}};at([f(Sa)],Rg.prototype,"spriteSheet",2);at([f()],Rg.prototype,"index",2);let fa=Rg;class ei extends E{drawMode=0;size={x:1,y:1};color;sharedMaterial;transparent=!0;cutoutThreshold=0;castShadows=!1;renderOrder=0;toneMapped=!0;set texture(e){if(!this._spriteSheet)return;const t=this._spriteSheet.spriteSheet?.sprites[this.spriteIndex];t&&(t.texture=e,this.updateSprite())}addSprite(e,t=!1){if(this._spriteSheet||(this._spriteSheet=fa.create()),!this._spriteSheet.spriteSheet)return-1;this._spriteSheet.spriteSheet?.sprites.push(e);const i=this._spriteSheet.spriteSheet?.sprites.length-1;return t&&(this.spriteIndex=i),i}get sprite(){return this._spriteSheet}set sprite(e){if(e!==this._spriteSheet)if(typeof e=="number"){const t=Math.round(e);Xl&&console.log("[SpriteSheet] Set index to "+t+" (was "+this.spriteIndex+")",e),this.spriteIndex=t}else e instanceof ys?(this._spriteSheet||(this._spriteSheet=fa.create()),this._spriteSheet.sprite!=e&&(this._spriteSheet.sprite=e),this.updateSprite()):e!=this._spriteSheet&&(this._spriteSheet=e,this.updateSprite())}set spriteIndex(e){this._spriteSheet&&(this._spriteSheet.index=e,this.updateSprite())}get spriteIndex(){return this._spriteSheet?.index??0}get spriteFrames(){return this._spriteSheet?.spriteSheet?.sprites.length??0}_spriteSheet;_currentSprite;awake(){this._currentSprite=void 0,this._spriteSheet?this._spriteSheet=this._spriteSheet.clone():this._spriteSheet=fa.create(),Xl&&console.log("Awake",this.name,this,this.sprite)}start(){this._currentSprite?this.gameObject&&this.gameObject.add(this._currentSprite):this.updateSprite()}updateSprite(e=!1){if(!this.__didAwake&&!e)return!1;const t=this._spriteSheet;if(!t?.spriteSheet?.sprites)return console.warn("SpriteRenderer has no data or spritesheet assigned..."),!1;const i=t.spriteSheet.sprites[this.spriteIndex];if(!i)return Xl&&console.warn("Sprite not found",this.spriteIndex,t.spriteSheet.sprites),!1;if(this._currentSprite)this._currentSprite.geometry=rr.getOrCreateGeometry(i),this._currentSprite.material.map=i.texture;else{const n=new c.MeshBasicMaterial({color:16777215,side:c.DoubleSide});if(lM&&(n.wireframe=!0),this.color&&(n.color||(n.color=new c.Color),n.color.copy(this.color),n.opacity=this.color.alpha),n.transparent=!0,n.toneMapped=this.toneMapped,n.depthWrite=!1,i.texture&&!n.wireframe){let o=i.texture;o[$f]!==void 0&&o[$f]!==this&&this.spriteFrames>1&&(o=i.texture=o.clone()),o[$f]=this,n.map=o}this.sharedMaterial=n,this._currentSprite=new c.Mesh(rr.getOrCreateGeometry(i),n),this._currentSprite.renderOrder=Math.round(this.renderOrder),ne.NEEDLE_progressive.assignTextureLOD(n,0)}return this._currentSprite.parent!==this.gameObject&&(this.drawMode===2&&this._currentSprite.scale.set(this.size.x,this.size.y,1),this.gameObject&&this.gameObject.add(this._currentSprite)),this._currentSprite&&this._currentSprite.layers.set(this.layer),this.sharedMaterial&&(this.sharedMaterial.alphaTest=this.cutoutThreshold,this.sharedMaterial.transparent=this.transparent),this._currentSprite.castShadow=this.castShadows,t?.update(this.sharedMaterial),!0}}at([f()],ei.prototype,"drawMode",2);at([f(cM)],ei.prototype,"size",2);at([f(Z)],ei.prototype,"color",2);at([f(c.Material)],ei.prototype,"sharedMaterial",2);at([f()],ei.prototype,"transparent",2);at([f()],ei.prototype,"cutoutThreshold",2);at([f()],ei.prototype,"castShadows",2);at([f()],ei.prototype,"renderOrder",2);at([f()],ei.prototype,"toneMapped",2);at([f(fa)],ei.prototype,"sprite",1);const Y_=x("debugwebxr"),hM=new c.Matrix4().makeRotationY(Math.PI);class di extends E{static _eventListeners={};static onPlaced(e){const t="placed";return this._eventListeners[t]||(this._eventListeners[t]=[]),this._eventListeners[t].push(e),()=>{const i=this._eventListeners[t].indexOf(e);i>=0&&this._eventListeners[t].splice(i,1)}}static _hasPlaced=!1;static get hasPlaced(){return this._hasPlaced}get arScale(){return this._arScale}set arScale(e){this._arScale=Math.max(1e-6,e),this.onSetScale()}_arScale=1;invertForward=!1;customReticle;arTouchTransform=!0;autoPlace=!1;autoCenter=!1;useXRAnchor=!1;_isPlacing=!0;_startOffset=new c.Matrix4;_createdPlacementObject=null;_reparentedComponents=[];_placementScene=new c.Scene;_reticle=[];_hits=[];_placementStartTime=-1;_rigPlacementMatrix;_anchor=null;userInput;onEnable(){this.customReticle?.preload()}supportsXR(e){return e==="immersive-ar"}onEnterXR(e){Y_&&console.log("ENTER WEBXR: SessionRoot start..."),this._anchor=null,di._hasPlaced=!1,this.gameObject.updateMatrixWorld(),this._startOffset.copy(this.gameObject.matrixWorld);const t=new c.Object3D;this._createdPlacementObject=t,t.name="AR Session Root",this._placementScene.name="AR Placement Scene",this._placementScene.children.length=0;for(let i=this.context.scene.children.length-1;i>=0;i--){const n=this.context.scene.children[i];this._placementScene.add(n)}if(this.context.scene.add(t),this.autoCenter){const i=Ft(this._placementScene.children),n=i.getCenter(new c.Vector3),o=i.getSize(new c.Vector3),r=new c.Matrix4;r.makeTranslation(n.x,n.y-o.y*.5,n.z),this._startOffset.multiply(r)}this._reparentedComponents.length=0,this._reparentedComponents.push({comp:this,originalObject:this.gameObject}),S.addComponent(t,this);for(const i of this._reticle)ji(i);this._reticle.length=0,this._isPlacing=!0,this.context.input.addEventListener("pointerup",this.onPlaceScene,{queue:Xt.Early})}onLeaveXR(){this.context.input.removeEventListener("pointerup",this.onPlaceScene,{queue:Xt.Early}),this.onRevertSceneChanges(),this._anchor=null,di._hasPlaced=!1,this._rigPlacementMatrix=void 0}onUpdateXR(e){if(e.xr.isTrackingImages){for(const t of this._reticle)t.visible=!1;return}if(this._isPlacing){const t=e.xr.rig?.gameObject;t&&t.parent!==this.context.scene&&this.context.scene.add(t);let i=!1;if(e.xr.isPassThrough&&e.xr.controllers.length>0&&!this.autoPlace)for(const n of e.xr.controllers){const o=n.getHitTest();o&&(i=!0,this.updateReticleAndHits(e.xr,n.index,o,e.xr.rigScale))}if(!i){const n=e.xr.getHitTest();n&&this.updateReticleAndHits(e.xr,0,n,e.xr.rigScale)}}else{if(this._anchor&&e.xr.referenceSpace){const t=e.xr.frame.getPose(this._anchor.anchorSpace,e.xr.referenceSpace);if(t&&this.context.time.frame%20===0){const i=e.xr.convertSpace(t.transform),n=this._reticle[0];n&&(n.position.copy(i.position),n.quaternion.copy(i.quaternion),this.onApplyPose(n))}}if(this.arTouchTransform?(this.userInput||(this.userInput=new Vd(this.context)),this.userInput?.enable()):this.userInput?.disable(),this.arTouchTransform&&this.userInput?.hasChanged){if(e.xr.rig){const t=e.xr.rig.gameObject;this.userInput.applyMatrixTo(t.matrix,!0),t.matrix.decompose(t.position,t.quaternion,t.scale),this.userInput.factor=t.scale.x}this.userInput.reset()}}}updateReticleAndHits(e,t,i,n){this._hits[t]=i.hit;let o=this._reticle[t];if(!o){if(this.customReticle)if(this.customReticle.asset)o=ir(this.customReticle.asset);else{this.customReticle.loadAssetAsync();return}else o=new c.Mesh(new c.RingGeometry(.07,.09,32).rotateX(-Math.PI/2),new c.MeshBasicMaterial({side:c.DoubleSide,depthTest:!1,depthWrite:!1,transparent:!0,opacity:1,color:15658734})),o.name="AR Placement Reticle";if(Y_){const r=new c.AxesHelper(1);r.position.y+=.01,o.add(r)}this._reticle[t]=o,o.matrixAutoUpdate=!1,o.visible=!1}if(o.lastPos=o.lastPos||i.position.clone(),o.lastQuat=o.lastQuat||i.quaternion.clone(),o.position.copy(o.lastPos.lerp(i.position,this.context.time.deltaTime/.1)),o.lastPos.copy(o.position),o.quaternion.copy(o.lastQuat.slerp(i.quaternion,this.context.time.deltaTime/.05)),o.lastQuat.copy(o.quaternion),o.scale.set(n,n,n),this.customReticle&&this.applyViewBasedTransform(o),o.updateMatrix(),o.visible=!0,o.parent!==this.context.scene&&this.context.scene.add(o),this._placementStartTime<0&&(this._placementStartTime=this.context.time.realtimeSinceStartup),this.autoPlace)if(this.upVec.set(0,1,0).applyQuaternion(o.quaternion),this.upVec.dot(j(0,1,0))>.9){let a=o["autoplace:timer"]||0;a>=1?(o.visible=!1,this.onPlaceScene(null)):(a+=this.context.time.deltaTime,o["autoplace:timer"]=a)}else o["autoplace:timer"]=0}onPlaceScene=e=>{if(this._isPlacing==!1||e?.used)return;let t=this._reticle[0];if(!t){console.warn("No reticle to place...");return}if(!t.visible&&!this.autoPlace){console.warn("Reticle is not visible (can not place)");return}if(G.active?.isTrackingImages){console.warn("Scene Placement is disabled while images are being tracked");return}let i=this._hits[0];if(e&&e.origin instanceof Mm){const n=this._reticle[e.origin.index];n&&(t=n,i=this._hits[e.origin.index])}if(e&&(e.stopImmediatePropagation(),e.stopPropagation(),e.use()),this._isPlacing=!1,this.context.input.removeEventListener("pointerup",this.onPlaceScene),this.onRevertSceneChanges(),t.position.copy(t.lastPos),t.quaternion.copy(t.lastQuat),this.onApplyPose(t),di._hasPlaced=!0,this.useXRAnchor&&this.onCreateAnchor(G.active,i),this.context.xr)for(const n of this.context.xr.controllers)n.cancelHitTestSource()};onSetScale(){if(!di._hasPlaced)return;const e=G.active?.rig?.gameObject;if(e){const t=G.active?.rigScale||1,i=1/this._arScale*t,n=new c.Matrix4().makeScale(i,i,i).invert();e.matrix.premultiply(n),e.matrix.decompose(e.position,e.quaternion,e.scale)}}onRevertSceneChanges(){for(const e of this._reticle)e&&(e.visible=!1,e?.removeFromParent());this._reticle.length=0;for(let e=this._placementScene.children.length-1;e>=0;e--){const t=this._placementScene.children[e];this.context.scene.add(t)}this._createdPlacementObject?.removeFromParent();for(const e of this._reparentedComponents)S.addComponent(e.originalObject,e.comp)}async onCreateAnchor(e,t){if(t.createAnchor===void 0){console.warn("Hit does not support creating an anchor",t),A()&&de("Hit does not support creating an anchor");return}else{const i=await t.createAnchor(e.viewerPose.transform);e.running&&i&&(this._anchor=i)}}upVec=new c.Vector3(0,1,0);lookPoint=new c.Vector3;worldUpVec=new c.Vector3(0,1,0);applyViewBasedTransform(e){const t=this.context.mainCamera,i=e,n=t.worldPosition,o=i.worldPosition;this.upVec.set(0,1,0).applyQuaternion(e.quaternion);const r=t.worldPosition;r&&e.position.clone().sub(r).angleTo(this.upVec)<Math.PI/2&&this.upVec.negate();const a=this.upVec.angleTo(this.worldUpVec)*180/Math.PI,l=30;a>l&&a<180-l||a<-l&&a>-180+l?(this.lookPoint.copy(e.position).add(this.upVec),this.lookPoint.y=e.position.y,e.lookAt(this.lookPoint)):(n.y=o.y,e.lookAt(n))}onApplyPose(e){const t=G.active?.rig?.gameObject;if(!t){console.warn("No rig object to place");return}const i=t.parent||this.context.scene;this._rigPlacementMatrix?this._rigPlacementMatrix?.decompose(t.position,t.quaternion,t.scale):this._rigPlacementMatrix=t.matrix.clone(),this.applyViewBasedTransform(e),e.updateMatrix(),this.context.scene.add(e),e.attach(t),e.removeFromParent(),t.scale.set(this.arScale,this.arScale,this.arScale),t.position.multiplyScalar(this.arScale),t.updateMatrix(),this.invertForward&&t.matrix.premultiply(hM),t.matrix.premultiply(this._startOffset),t.matrix.decompose(t.position,t.quaternion,t.scale),i.add(t)}}class Vd{static up=new c.Vector3(0,1,0);static zero=new c.Vector3(0,0,0);static one=new c.Vector3(1,1,1);oneFingerDrag=!0;twoFingerRotate=!0;twoFingerScale=!0;factor=1;context;offset;plane;_scale=1;_hasChanged=!1;get scale(){return this._scale}constructor(e){this.context=e,this.offset=new c.Matrix4,this.plane=new c.Plane,this.plane.setFromNormalAndCoplanarPoint(Vd.up,Vd.zero)}_enabled=!1;reset(){this._scale=1,this.offset.identity(),this._hasChanged=!0}get hasChanged(){return this._hasChanged}applyMatrixTo(e,t){this._hasChanged=!1,t?(this.offset.invert(),e.premultiply(this.offset)):e.multiply(this.offset)}currentlyUsedPointerIds=new Set;currentlyUnusedPointerIds=new Set;get isActive(){return this.currentlyUsedPointerIds.size<=0&&this.currentlyUnusedPointerIds.size>0}enable(){this._enabled||(this._enabled=!0,this.context.input.addEventListener("pointerdown",this.onPointerDownEarly,{queue:Xt.Early}),this.context.input.addEventListener("pointerdown",this.onPointerDownLate,{queue:Xt.Late}),this.context.input.addEventListener("pointerup",this.onPointerUpEarly,{queue:Xt.Early}),window.addEventListener("touchstart",this.touchStart,{passive:!1}),window.addEventListener("touchmove",this.touchMove,{passive:!1}),window.addEventListener("touchend",this.touchEnd,{passive:!1}))}disable(){this._enabled&&(this._enabled=!1,this.context.input.removeEventListener("pointerdown",this.onPointerDownEarly,{queue:Xt.Early}),this.context.input.removeEventListener("pointerdown",this.onPointerDownLate,{queue:Xt.Late}),this.context.input.removeEventListener("pointerup",this.onPointerUpEarly,{queue:Xt.Early}),window.removeEventListener("touchstart",this.touchStart),window.removeEventListener("touchmove",this.touchMove),window.removeEventListener("touchend",this.touchEnd))}onPointerDownEarly=e=>{this.isActive&&e.stopPropagation()};onPointerDownLate=e=>{e.used?this.currentlyUsedPointerIds.add(e.pointerId):this.currentlyUsedPointerIds.size<=0&&this.currentlyUnusedPointerIds.add(e.pointerId)};onPointerUpEarly=e=>{this.currentlyUsedPointerIds.delete(e.pointerId),this.currentlyUnusedPointerIds.delete(e.pointerId)};prev=new Map;_didMultitouch=!1;touchStart=e=>{if(!e.defaultPrevented)for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t],n=exports.DeviceUtilities.isAndroidDevice()&&i.clientY<window.innerHeight*.1;this.prev.has(i.identifier)||this.prev.set(i.identifier,{ignore:n,x:0,z:0,screenx:0,screeny:0});const o=this.prev.get(i.identifier);if(o){const r=this.getPositionOnPlane(i.clientX,i.clientY);o.x=r.x,o.z=r.z,o.screenx=i.clientX,o.screeny=i.clientY}}};touchEnd=e=>{e.touches.length<=0&&(this._didMultitouch=!1);for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t];this.prev.delete(i.identifier)}};touchMove=e=>{if(!e.defaultPrevented&&this.isActive){if(e.touches.length===1){if(this._didMultitouch)return;const t=e.touches[0],i=this.prev.get(t.identifier);if(!i||i.ignore)return;const n=this.getPositionOnPlane(t.clientX,t.clientY),o=n.x-i.x,r=n.z-i.z;if(o===0&&r===0)return;this.oneFingerDrag&&this.addMovement(o,r),i.x=n.x,i.z=n.z,i.screenx=t.clientX,i.screeny=t.clientY;return}else if(e.touches.length===2){this._didMultitouch=!0;const t=e.touches[0],i=e.touches[1],n=this.prev.get(t.identifier),o=this.prev.get(i.identifier);if(!n||!o)return;if(this.twoFingerRotate){const r=Math.atan2(t.clientY-i.clientY,t.clientX-i.clientX),a=Math.atan2(n.screeny-o.screeny,n.screenx-o.screenx),l=r-a;Math.abs(l)>.001&&this.addRotation(l)}if(this.twoFingerScale){const r=t.clientX-i.clientX,a=t.clientY-i.clientY,l=Math.sqrt(r*r+a*a),h=n.screenx-o.screenx,d=n.screeny-o.screeny,u=Math.sqrt(h*h+d*d),p=l-u;Math.abs(p)>2&&this.addScale(p)}n.screenx=t.clientX,n.screeny=t.clientY,o.screenx=i.clientX,o.screeny=i.clientY}}};_raycaster=new c.Raycaster;_intersection=new c.Vector3;_screenPos=new c.Vector3;getPositionOnPlane(e,t){const i=this.context.mainCamera;return this._screenPos.x=e/window.innerWidth*2-1,this._screenPos.y=-(t/window.innerHeight)*2+1,this._screenPos.z=1,this._screenPos.unproject(i),this._raycaster.set(i.position,this._screenPos.sub(i.position)),this._raycaster.ray.intersectPlane(this.plane,this._intersection),this._intersection}addMovement(e,t){e/=this._scale,t/=this._scale,e*=this.factor,t*=this.factor,this.offset.elements[12]+=e,this.offset.elements[14]+=t,(e!==0||t!==0)&&(this._hasChanged=!0)}_tempMatrix=new c.Matrix4;addScale(e){e/=window.innerWidth,e*=-1,this._scale*=1+e,this._tempMatrix.makeScale(1-e,1-e,1-e),this.offset.premultiply(this._tempMatrix),e!==0&&(this._hasChanged=!0)}addRotation(e){e*=-1,this._tempMatrix.makeRotationY(e),this.offset.premultiply(this._tempMatrix),e!==0&&(this._hasChanged=!0)}}const Hs=x("debugautosync"),Wf=Symbol("syncerId");class dM{_syncers={};getOrCreateSyncer(e){if(!e.guid)return null;if(this._syncers[e.guid])return this._syncers[e.guid];const t=new uM(e);return t[Wf]=e.guid,this._syncers[t[Wf]]=t,t}removeSyncer(e){delete this._syncers[e[Wf]]}}const Tg=new dM;class uM{comp;constructor(e){this.comp=e}hasChanges=!1;changedProperties={};get networkingKey(){return this.comp.guid}_isReceiving=!1;_isInit=!1;init(e){if(this._isInit)return;this._isInit=!0,this.comp=e,this.comp.context.post_render_callbacks.push(this.onHandleSending),this.comp.context.connection.beginListen(this.networkingKey,this.onHandleReceiving);const t=this.comp.context.connection.tryGetState(this.comp.guid);t&&this.onHandleReceiving(t)}destroy(){this._isInit&&(this.comp.context.post_render_callbacks.splice(this.comp.context.post_render_callbacks.indexOf(this.onHandleSending),1),this.comp.context.connection.stopListen(this.networkingKey,this.onHandleReceiving),this.comp=null,this._isInit=!1)}notifyChanged(e,t){this._isReceiving||(Hs&&console.log("Property changed: "+e,t),this.hasChanges=!0,this.changedProperties[e]=t)}onHandleSending=()=>{if(!this.hasChanges)return;this.hasChanges=!1;const e=this.comp.context.connection;if(!e||!e.isConnected||!e.isInRoom){for(const t in this.changedProperties)delete this.changedProperties[t];return}for(const t in this.changedProperties){const i=this.changedProperties[t];Hs&&console.log("SEND",this.comp.guid,this.networkingKey),e.send(this.networkingKey,{guid:this.comp.guid,property:t,data:i},Zi.Queued),delete this.changedProperties[t]}};onHandleReceiving=e=>{if(Hs&&console.log("SYNCFIELD RECEIVE",this.comp.name,this.comp.guid,e),!!this._isInit&&this.comp&&e.guid===this.comp.guid)try{this._isReceiving=!0,this.comp[e.property]=e.data}catch(t){console.error(t)}finally{this._isReceiving=!1}}}function fM(s,e){let t=e!==s;return!t&&s&&e&&(Array.isArray(s)&&Array.isArray(e)||typeof s=="object"&&typeof e=="object")&&(t=!0),t}const Ql=Symbol("AutoSyncHandler");function pM(s){if(s[Ql])return s[Ql];const e=Tg.getOrCreateSyncer(s);return e?.init(s),s[Ql]=e,e}function mM(s){const e=s[Ql];e&&(Tg.removeSyncer(e),e.destroy(),delete s[Ql])}const Ag=function(s=null){return function(e,t){let i="";typeof t=="string"?i=t:i=t.name;let n=null,o;typeof s=="string"?o=e[s]:typeof s=="function"&&(o=s),o==null&&(A()||Hs)&&s!=null&&console.warn('syncField: no callback function found for property "'+i+'"','"'+s+'"');const r=e,a=r.__internalAwake;if(typeof a!="function"){(Hs||A())&&console.error('@syncField can currently only used on Needle Engine Components, custom object of type "'+e?.constructor?.name+'" is not supported',e);return}Hs&&console.log(i);const l=Symbol(i);r.__internalAwake=function(){if(this[l]!==void 0)return;if(this[l]=this[i],n=Tg.getOrCreateSyncer(this),Object.getOwnPropertyDescriptor(this,i)?.set===void 0){let u=!1;Object.defineProperty(this,i,{set:function(p){const m=this[l];if(this[l]=p,u){(A()||Hs)&&console.warn("Recursive call detected",i);return}u=!0;try{const y=fM(p,m);Hs&&console.log("SyncField assignment",i,"changed?",y,p,o),y&&o?.call(this,p,m)!==!1&&pM(this)?.notifyChanged(i,p)}finally{u=!1}},get:function(){return this[l]},configurable:!0,enumerable:!0})}n?.init(this),a.call(this)};const h=r.__internalDestroy;r.__internalDestroy=function(){mM(this),h.call(this)}}};var gM=Object.defineProperty,Cu=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&gM(e,t,n),n};const Lt=x("debugplayersync"),Pu=class _w extends E{static async setupFrom(e,t){const i=Y.getOrCreateFromUrl(e);if(!i.asset){const r=await i.loadAssetAsync();r&&S.getOrAddComponent(r,en)}const n=new _w;n._internalInit(t),n.asset=i;const o=new c.Object3D;return o.guid=e,S.addComponent(o,n),n}autoSync=!0;asset;onPlayerSpawned;_localInstance;awake(){this.watchTabVisible(),this.onPlayerSpawned||(this.onPlayerSpawned=new oe)}onEnable(){this.context.connection.beginListen(Q.RoomStateSent,this.onJoinedRoom),this.context.connection.beginListen(Q.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Q.LeftRoom,this.destroyInstance),this.context.connection.isInRoom&&this.onJoinedRoom()}onDisable(){this.context.connection.stopListen(Q.RoomStateSent,this.onJoinedRoom),this.context.connection.stopListen(Q.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Q.LeftRoom,this.destroyInstance)}onJoinedRoom=()=>{Lt&&console.log("PlayerSync.joinedRoom. autoSync is set to "+this.autoSync),this.autoSync&&this.getInstance()};async getInstance(){if(this._localInstance)return this._localInstance;if(Lt&&console.log("PlayerSync.createInstance",this.asset?.url),!this.asset?.asset&&!this.asset?.url)return console.error('PlayerSync: can not create an instance because "asset" is not set and or has no URL!'),null;this.gameObject.guid||console.warn("PlayerSync: gameObject has no guid! This might cause issues with syncing the player state."),this._localInstance=this.asset?.instantiateSynced({parent:this.gameObject,deleteOnDisconnect:!0},!0);const e=await this._localInstance;if(e){const t=S.getComponentsInChildren(e,en);if(Lt&&console.log(`PlayerSync.createInstance: found ${t?.length} PlayerState components. Owner: ${this.context.connection.connectionId}`),t?.length){for(const i of t)i.owner=this.context.connection.connectionId;this.onPlayerSpawned?.invoke(e)}else this._localInstance=void 0,console.error("<strong>Failed finding PlayerState on "+this.asset?.url+"</strong>: please make sure the asset has a PlayerState component!"),S.destroySynced(e)}else this._localInstance=void 0,console.warn("PlayerSync: failed instantiating asset!");return this._localInstance}destroyInstance=()=>{this._localInstance?.then(e=>{Lt&&console.log("PlayerSync.destroyInstance",e),Pc(e,this.context.connection,!0,{saveInRoom:!1})}),this._localInstance=void 0};watchTabVisible(){window.addEventListener("visibilitychange",e=>{if(document.visibilityState==="visible")for(let t=en.all.length-1;t>=0;t--){const i=en.all[t];(!i.owner||!this.context.connection.userIsInRoom(i.owner))&&i.doDestroy()}})}};Cu([f()],Pu.prototype,"autoSync");Cu([f(Y)],Pu.prototype,"asset");Cu([f(oe)],Pu.prototype,"onPlayerSpawned");let Dg=Pu;var bw=(s=>(s.OwnerChanged="ownerChanged",s))(bw||{});const Qp=class ut extends E{static _all=[];static get all(){return ut._all}static _local=[];static get local(){return ut._local}static getFor(e){if(e instanceof c.Object3D)return S.getComponentInParent(e,ut);if(e instanceof E)return S.getComponentInParent(e.gameObject,ut)}static isLocalPlayer(e){return ut.getFor(e)?.isLocalPlayer??!1}static _callbacks={};static addEventListener(e,t){return this._callbacks[e]||(this._callbacks[e]=[]),this._callbacks[e].push(t),t}static removeEventListener(e,t){if(!this._callbacks[e])return;const i=this._callbacks[e].indexOf(t);i>=0&&this._callbacks[e].splice(i,1)}static dispatchEvent(e,t){if(this._callbacks[e])for(const i of this._callbacks[e])i(t)}onOwnerChangeEvent=new oe;onFirstOwnerChangeEvent=new oe;hasOwner=!1;owner;dontDestroy=!1;get isLocalPlayer(){return this.owner===this.context.connection.connectionId}onOwnerChange(e,t){Lt&&console.log(`PlayerSync.onOwnerChange: ${t} → ${e} (me: ${this.context.connection.connectionId})`);const i=ut._local.indexOf(this);i>=0&&ut._local.splice(i,1);const n={playerState:this,oldValue:t,newValue:e};if(this.hasOwner||(this.hasOwner=!0,this.onFirstOwnerChangeEvent?.invoke(n)),this.onOwnerChangeEvent?.invoke(n),this.owner===this.context.connection.connectionId){ut._local.push(this);const r=new CustomEvent("local-owner-changed",{detail:n});this.dispatchEvent(r)}const o=new CustomEvent("owner-changed",{detail:n});this.dispatchEvent(o),ut.dispatchEvent("ownerChanged",o)}awake(){ut.all.push(this),Lt&&console.log("Registered new PlayerState",this.guid,ut.all.length-1,ut.all),this.context.connection.beginListen(Q.UserLeftRoom,this.onUserLeftRoom)}async start(){Lt&&console.log("PLAYERSTATE.START, owner: "+this.owner,this.context.connection.usersInRoom([])),this.owner?(this.context.connection.isInRoom||await Bn(300),this.context.connection.userIsInRoom(this.owner)==!1&&(Lt&&console.log(`PlayerSync.start → doDestroy "${this.name}" because user "${this.owner}" is not in room anymore...`,"Currently in room:",...this.context.connection.usersInRoom()),this.doDestroy())):this.owner||(Lt&&console.warn("PlayerState.start → owner is undefined!",this.name),setTimeout(()=>{!this.destroyed&&!this.owner?this.dontDestroy?Lt&&console.warn("PlayerState.start → owner is still undefined but dontDestroy is set to true",this.name):(Lt&&console.warn(`PlayerState.start → owner is still undefined: destroying "${this.name}" instance now`),this.doDestroy()):Lt&&console.log("PlayerState.start → owner is assigned",this.owner)},2e3))}doDestroy(){Lt&&console.log("PlayerSync.doDestroy → syncDestroy",this.name),Pc(this.gameObject,this.context.connection,!0,{saveInRoom:!1})}onDestroy(){if(Lt&&console.warn("PlayerState.onDestroy",this.owner),this.context.connection.stopListen(Q.UserLeftRoom,this.onUserLeftRoom),ut.all.splice(ut.all.indexOf(this),1),this.isLocalPlayer){const e=ut._local.indexOf(this);e>=0&&ut._local.splice(e,1)}}onUserLeftRoom=e=>{if(e.userId===this.owner){Lt&&console.log("PLAYERSYNC LEFT",this.owner),this.doDestroy();return}}};Cu([Ag(Qp.prototype.onOwnerChange)],Qp.prototype,"owner");let en=Qp;var yM=Object.defineProperty,ja=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&yM(e,t,n),n};class Nn extends E{position="bottom";showNeedleLogo=!1;showSpatialMenu;createFullscreenButton;createMuteButton;createQRCodeButton;onEnable(){this.applyOptions()}applyOptions(){this.context.menu.setPosition(this.position),this.context.menu.showNeedleLogo(this.showNeedleLogo),this.createFullscreenButton===!0&&this.context.menu.showFullscreenOption(!0),this.createMuteButton===!0&&this.context.menu.showAudioPlaybackOption(!0),this.showSpatialMenu===!0&&this.context.menu.showSpatialMenu(this.showSpatialMenu),this.createQRCodeButton===!0&&(exports.DeviceUtilities.isMobileDevice()||this.context.menu.showQRCodeButton(!0))}}ja([f()],Nn.prototype,"position");ja([f()],Nn.prototype,"showNeedleLogo");ja([f()],Nn.prototype,"showSpatialMenu");ja([f()],Nn.prototype,"createFullscreenButton");ja([f()],Nn.prototype,"createMuteButton");ja([f()],Nn.prototype,"createQRCodeButton");var _M=Object.defineProperty,Lg=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&_M(e,t,n),n};const al=x("debugwebxr"),K_=new c.Quaternion().setFromAxisAngle(new c.Vector3(0,1,0),Math.PI);class io extends E{head;leftHand;rightHand;_leftHandMeshes;_rightHandMeshes;_syncTransforms;async onEnterXR(e){if(!this.activeAndEnabled)return;al&&console.warn("AVATAR ENTER XR",this.guid,this.sourceId,this,this.activeAndEnabled),this._syncTransforms&&(this._syncTransforms.length=0),await this.prepareAvatar();const t=en.getFor(this);if(t?.owner){const i=this.gameObject.addComponent(Se);i.avatar=this.gameObject,i.connectionId=t.owner}else this.context.connection.isConnected?console.error("No player state found for avatar",this):t&&!this.context.connection.isConnected&&(t.dontDestroy=!0)}onLeaveXR(e){const t=this.gameObject.getComponent(Se);t&&t.destroy()}onUpdateXR(e){if(!this.activeAndEnabled)return;const t=en.isLocalPlayer(this);if(!t)return;const i=e.xr;if(i.rig&&i.rig.gameObject!==this.gameObject.parent&&(this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),this.gameObject.scale.set(1,1,1),i.rig.gameObject.add(this.gameObject)),this._syncTransforms&&t)for(const l of this._syncTransforms)l.fastMode=!0,l.isOwned()||l.requestOwnership();if(this.head&&this.context.mainCamera){const l=this.head.asset;if(l.position.copy(this.context.mainCamera.position),l.position.x*=-1,l.position.z*=-1,l.quaternion.copy(this.context.mainCamera.quaternion),l.quaternion.x*=-1,this.context.time.frameCount%10===0&&this.head.asset){const h=S.getComponentsInChildren(this.head.asset,Ti);for(const d of h)d.enabled=!1,d.gameObject.visible=!1}}const n=e.xr.leftController,o=this.leftHand?.asset;n&&o?(o.position.copy(n.gripPosition),o.quaternion.copy(n.gripQuaternion),o.quaternion.multiply(K_),o.visible=n.isTracking,this.updateHandVisibility(n,o,this._leftHandMeshes)):o&&o.visible&&(o.visible=!1);const r=e.xr.rightController,a=this.rightHand?.asset;r&&a?(a.position.copy(r.gripPosition),a.quaternion.copy(r.gripQuaternion),a.quaternion.multiply(K_),a.visible=r.isTracking,this.updateHandVisibility(r,a,this._rightHandMeshes)):a&&a.visible&&(a.visible=!1)}onBeforeRender(){this.context.xr&&this.context.time.frame%10===0&&this.updateRemoteAvatarVisibility()}updateHandVisibility(e,t,i){if(i){const n=e.model&&e.model.visible&&e.model!==t;i.forEach(o=>{ts(o,!n)})}}updateRemoteAvatarVisibility(){if(this.context.connection.isConnected){const e=en.getFor(this);if(e&&e.isLocalPlayer==!1){const t=G.getXRSync(this.context);if(t&&t.hasState(e.owner)){this.tryFindAvatarObjectsIfMissing();const i=this.leftHand?.asset;i&&(i.visible=t?.isTracking(e.owner,"left")??!1);const n=this.rightHand?.asset;n&&(n.visible=t?.isTracking(e.owner,"right")??!1)}if(this.head?.asset){const i=S.getComponentsInChildren(this.head.asset,Ti);for(const n of i)n.enabled=!1,n.gameObject.visible=!0}}}}tryFindAvatarObjectsIfMissing(){if(!this.head||!this.leftHand||!this.rightHand){const e={head:this.head,leftHand:this.leftHand,rightHand:this.rightHand};p0.tryFindAvatarObjects(this.gameObject,this.sourceId||"",e),e.head&&(this.head=e.head),e.leftHand&&(this.leftHand=e.leftHand),e.rightHand&&(this.rightHand=e.rightHand)}}async prepareAvatar(){if(this.tryFindAvatarObjectsIfMissing(),this.head)this.head instanceof c.Object3D&&(this.head=new Y("",this.sourceId,this.head));else{const e=new c.Object3D;e.name="Head";const t=hr.createPrimitive(Jo.Cube);e.add(t),this.gameObject.add(e),this.head=new Y("",this.sourceId,e),al&&console.log("Create head",e)}if(this.rightHand)this.rightHand instanceof c.Object3D&&(this.rightHand=new Y("",this.sourceId,this.rightHand));else{const e=new c.Object3D;e.name="Right Hand",this.gameObject.add(e),this.rightHand=new Y("",this.sourceId,e),al&&console.log("Create right hand",e)}if(this.leftHand)this.leftHand instanceof c.Object3D&&(this.leftHand=new Y("",this.sourceId,this.leftHand));else{const e=new c.Object3D;e.name="Left Hand",this.gameObject.add(e),this.leftHand=new Y("",this.sourceId,e),al&&console.log("Create left hand",e)}await this.loadAvatarObjects(this.head,this.leftHand,this.rightHand),this._leftHandMeshes=[],this.leftHand.asset?.traverse(e=>{e?.isMesh&&this._leftHandMeshes.push(e)}),this._rightHandMeshes=[],this.rightHand.asset?.traverse(e=>{e?.isMesh&&this._rightHandMeshes.push(e)}),en.isLocalPlayer(this.gameObject)&&(this._syncTransforms=S.getComponentsInChildren(this.gameObject,ln))}async loadAvatarObjects(e,t,i){const n=e.loadAssetAsync(),o=t.loadAssetAsync(),r=i.loadAssetAsync(),a=new Array;n&&a.push(n),o&&a.push(o),r&&a.push(r);const l=await fm(a);al&&console.log("Avatar loaded results:",l)}}Lg([f(Y)],io.prototype,"head");Lg([f(Y)],io.prototype,"leftHand");Lg([f(Y)],io.prototype,"rightHand");var bM=Object.defineProperty,Ou=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&bM(e,t,n),n};const As=x("debugwebxr"),Ds=new Array;class ds extends E{createControllerModel=!0;createHandModel=!0;customLeftHand;customRightHand;static factory=new q.XRControllerModelFactory;supportsXR(e){return e==="immersive-vr"||e==="immersive-ar"}_models=new Array;async onXRControllerAdded(e){if(!(e.xr.isVR||e.xr.isPassThrough))return;console.debug("XR Controller Added",e.controller.side,e.controller.index);const{controller:i}=e;if(this.createControllerModel||this.createHandModel){if(i.hand){if(this.createHandModel){const n=await this.loadHandModel(this,i);if(!n||!i.connected||!i.isHand){n?.handObject&&qr(n.handObject,!1),n?.handObject?.destroy();return}this._models.push({controller:i,model:n.handObject,handmesh:n.handmesh}),this._models.sort((o,r)=>o.controller.index-r.controller.index),this.scene.add(n.handObject),i.model=n.handObject}}else if(this.createControllerModel){const n=await i.getModelUrl();if(n){const o=await this.loadModel(i,n);if(!o||!i.connected||i.isHand)return;this._models.push({controller:i,model:o}),this._models.sort((r,a)=>r.controller.index-a.controller.index),this.scene.add(o),o.traverse(r=>{r.layers.set(2),r.matrixAutoUpdate=!1,r.updateMatrix()}),i.model=o}else i.targetRayMode!=="transient-pointer"&&console.warn("XRControllerModel: no model found for "+i.side)}}}onXRControllerRemoved(e){console.debug("XR Controller Removed",e.controller.side,e.controller.index);const t=this._models.findIndex(n=>n.controller===e.controller),i=this._models[t];i&&(this._models.splice(t,1),i.model&&(qr(i.model,!1),i.model.destroy(),i.model=void 0))}onBeforeXR(e,t){this.createHandModel&&(this.customLeftHand||this.customRightHand)&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.includes("hand-tracking")||t.optionalFeatures.push("hand-tracking"))}onLeaveXR(e){for(const t of this._models)t&&(t.model&&(qr(t.model,!1),t.model.destroy(),t.model=void 0),t.controller.model===t.model&&(t.controller.model=null));this._models.length=0}onBeforeRender(){if(G.active&&(As&&(Ds[0]=Date.now()),this.updateRendering(G.active),As)){const e=Date.now()-Ds[0];Ds.push(e),Ds.length>=30&&(Ds[0]=0,Ds.reduce((t,i)=>t+i,0)/Ds.length,Ds.length=0)}}updateRendering(e){for(let t=0;t<this._models.length;t++){const i=this._models[t];if(!i)continue;const n=i.controller;if(!n.connected){As&&console.warn("XRControllerModel.onUpdateXR: controller is not connected anymore",n.side,n.hand);continue}if(i.model&&!i.handmesh)i.model.matrixAutoUpdate=!1,i.model.matrix.copy(n.gripMatrix),i.model.visible=n.isTracking,e.rig?.gameObject.add(i.model);else if(n.inputSource.hand&&i.handmesh){const o=e.referenceSpace,r=this.context.renderer.xr.getHand(n.index);if(o&&e.frame.getJointPose){for(const a of n.inputSource.hand.values()){const l=r.joints[a.jointName];if(l){const h=n.getHandJointPose(a);if(h){const d=h.transform.position,u=h.transform.orientation;l.position.copy(d),l.quaternion.copy(u),l.matrixAutoUpdate=!1}l.visible=h!=null}}i.model&&(i.model.visible=n.isTracking,i.model.visible&&i.model.parent!==e.rig?.gameObject&&e.rig?.gameObject.add(i.model)),i.model?.visible&&(i.handmesh?.updateMesh(),i.model.matrixAutoUpdate=!1,i.model.matrix.identity(),i.model.applyMatrix4(aa))}}}}async loadModel(e,t){if(!e.connected)return console.warn("XRControllerModel.onXRControllerAdded: controller is not connected anymore",e.side),null;const n=await Y.getOrCreate("",t).instantiate();return qr(n),G.active?.isPassThrough&&n.traverseVisible(o=>{this.makeOccluder(o)}),n}async loadHandModel(e,t){const i=this.context,n=i.renderer.xr.getHand(t.index);n||(As?B.DrawLabel(t.rayWorldPosition,"No hand found for index "+t.index,.05,5):console.warn("No hand found for index "+t.index));const o=new q.GLTFLoader;Xm(o,i),await zd(o,i,this.sourceId??"",this.sourceId??"");const r=ug(o);let a="";const l=t.side==="left"?this.customLeftHand:this.customRightHand;l?(a=l.url.split(".").slice(0,-1).join("."),o.setPath("")):(a=t.inputSource.handedness==="left"?"left":"right",o.setPath("https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/"));const h=new c.Object3D;qr(h);const d=new q.XRHandMeshModel(h,n,o.path,a,o,u=>{const p=r?.gltf;p?.scene.children?.length===0&&(p.scene.children[0]=u),r?.gltf&&rn().createBuiltinComponents(e.context,e.sourceId||a,r.gltf,null,r),u.traverse(m=>{m.layers.set(2),G.active?.isPassThrough&&!l&&this.makeOccluder(m),m instanceof c.Mesh&&ne.NEEDLE_progressive.assignMeshLOD(m,0)}),t.connected||(As&&B.DrawLabel(t.rayWorldPosition,"Hand is loaded but not connected anymore",.05,5),u.removeFromParent())});if(As&&h.add(new c.AxesHelper(.5)),t.inputSource.hand){As&&console.log(t.inputSource.hand);for(const u of t.inputSource.hand.values())if(n.joints[u.jointName]===void 0){const p=new c.Group;p.matrixAutoUpdate=!1,p.visible=!0,n.joints[u.jointName]=p,n.add(p)}}else As&&B.DrawLabel(t.rayWorldPosition,"No inputSource.hand found for index "+t.index,.05,5);return{handObject:h,handmesh:d}}makeOccluder(e){if(e instanceof c.Mesh){let t=e.material;t instanceof c.Material&&(t=e.material=t.clone(),t.depthWrite=!0,t.depthTest=!0,t.colorWrite=!1,e.receiveShadow=!1,e.renderOrder=-100)}}}Ou([f()],ds.prototype,"createControllerModel");Ou([f()],ds.prototype,"createHandModel");Ou([f(Y)],ds.prototype,"customLeftHand");Ou([f(Y)],ds.prototype,"customRightHand");class Mu extends E{}var vM=Object.defineProperty,fo=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&vM(e,t,n),n};const Hf=x("debugwebxr");class gi extends E{movementSpeed=1.5;rotationStep=30;useTeleport=!0;usePinchToTeleport=!0;useTeleportTarget=!1;useTeleportFade=!1;showRays=!0;showHits=!0;isXRMovementHandler=!0;xrSessionMode="immersive-vr";_didApplyRotation=!1;_didTeleport=!1;onUpdateXR(e){const t=e.xr.rig;if(!t?.gameObject||e.xr.isPassThrough)return;const i=e.xr.leftController,n=e.xr.rightController;i&&this.onHandleMovement(i,t.gameObject),n&&(this.onHandleRotation(n,t.gameObject),this.useTeleport&&this.onHandleTeleport(n,t.gameObject))}onLeaveXR(e){for(const t of this._lines)t.removeFromParent();for(const t of this._hitDiscs)t?.removeFromParent()}onBeforeRender(){this.context.xr?.running&&(this.showRays&&this.renderRays(this.context.xr),this.showHits&&this.renderHits(this.context.xr))}onHandleMovement(e,t){const i=e.getStick("xr-standard-thumbstick");if(i.x!=0||i.y!=0){const n=j(i.x,0,i.y);n.multiplyScalar(this.context.time.deltaTimeUnscaled*this.movementSpeed);const o=je(t);n.multiplyScalar(o.x),n.applyQuaternion(e.xr.poseOrientation),n.y=0,n.applyQuaternion(t.worldQuaternion),A()&&Number.isNaN(n.x)&&console.error("Stick movement resulted in NaN",{stick:i,vec:n}),t.position.add(n),t.updateWorldMatrix(!1,!1);for(const r of t.children)r.updateWorldMatrix(!1,!1)}}onHandleRotation(e,t){if(e._isMxInk)return;const n=e.getStick("xr-standard-thumbstick").x;if(this._didApplyRotation)Math.abs(n)<.3&&(this._didApplyRotation=!1);else if(Math.abs(n)>.5){this._didApplyRotation=!0;const o=n>0?1:-1,r=X(this.context.mainCamera).clone();t.rotateY(o*L.toRadians(this.rotationStep));const l=X(this.context.mainCamera).clone().sub(r);l.y=0,t.position.sub(l)}}_teleportBuffer=new Array;onHandleTeleport(e,t){let i=0;if(e.hand&&this.usePinchToTeleport&&e.isTeleportGesture){const n=e.getPointerId("primary");if(n!=null&&this.context.input.getIsPointerIdInUse(n))return;const o=e.getGesture("pinch");o&&(i=o.value)}else i=e.getStick("xr-standard-thumbstick")?.y;if(this._didTeleport)i>=0&&i<.4?this._didTeleport=!1:i<0&&i>-.4&&(this._didTeleport=!1);else if(i>.8){this._didTeleport=!0;const n=this.context.physics.raycastFromRay(e.ray)[0];if(n&&n.object instanceof q.GroundedSkybox){const r=n.normal?.dot(j(0,1,0));if(r!==void 0&&r<.4)return}let o=n?.point;if(!o&&!this.useTeleportTarget){this._plane||(this._plane=new c.Plane(new c.Vector3(0,1,0),0));const r=t.worldPosition;this._plane.setFromNormalAndCoplanarPoint(new c.Vector3(0,1,0),r);const a=e.ray;o=r.clone(),this._plane.intersectLine(new c.Line3(a.origin,j(a.direction).multiplyScalar(1e4).add(a.origin)),o),o.distanceTo(r)>t.scale.x*10&&(o=null)}if(o){if(this.useTeleportTarget&&!S.getComponentInParent(n.object,Mu))return;const r=o.clone();if(Hf&&B.DrawSphere(o,.025,16711680,5),this.context.mainCamera?.position){const l=this.context.xr?.getUserOffsetInRig();l&&(l.y=0,r.sub(l),Hf&&B.DrawWireSphere(l.add(r),.025,65280,5))}this._teleportBuffer.push(t.matrix.clone()),this._teleportBuffer.length>10&&this._teleportBuffer.shift(),this.useTeleportFade?e.xr.fadeTransition()?.then(()=>{t.worldPosition=r}):t.worldPosition=r}}else if(i<-.8&&(this._didTeleport=!0,this._teleportBuffer.length>0)){const n=this._teleportBuffer.pop();n&&n.decompose(t.position,t.quaternion,t.scale)}}_plane=null;_lines=[];_hitDiscs=[];_hitDistances=[];_lastHitDistances=[];renderRays(e){for(let t=0;t<this._lines.length;t++){const i=this._lines[t];i&&(i.visible=!1)}for(let t=0;t<e.controllers.length;t++){const i=e.controllers[t];let n=this._lines[t];if(!i.connected||!i.isTracking||!i.ray||i.targetRayMode==="transient-pointer"||!i.hasSelectEvent){n&&(n.visible=!1);continue}n||(n=this.createRayLineObject(),n.scale.z=.5,this._lines[t]=n),i.updateRayWorldPosition(),i.updateRayWorldQuaternion();const o=i.rayWorldPosition,r=i.rayWorldQuaternion;n.position.copy(o),n.quaternion.copy(r);const a=e.rigScale,l=this.usePinchToTeleport&&i.isTeleportGesture,h=this._lastHitDistances[t],d=this._hitDistances[t]!=null,u=h??a;n.scale.set(a,a,u),n.visible=!0,n.layers.disableAll(),n.layers.enable(2);let p=n.material.opacity;l?p=1:this.showHits&&u<e.rigScale*.5?p=0:i.getButton("primary")?.pressed?p=.5:p=d?.2:.1,n.material.opacity=L.lerp(n.material.opacity,p,this.context.time.deltaTimeUnscaled/.1),n.parent!==this.context.scene&&this.context.scene.add(n)}}renderHits(e){for(const t of this._hitDiscs){if(!t)continue;const i=t.controller;if(!i||!i.connected||!i.isTracking){t.visible=!1;continue}}for(let t=0;t<e.controllers.length;t++){const i=e.controllers[t];if(!i.connected||!i.isTracking||!i.ray||!i.hasSelectEvent)continue;let n=this._hitDiscs[t],o=!0;const r=i.getPointerId("primary");r!=null&&this.context.input.getIsPointerIdInUse(r)&&(n&&(n.visible=!1),this._hitDistances[t]=null,this._lastHitDistances[t]=0,o=!1);const a=this.context.time.smoothedFps>=59?1:10;if((this.context.time.frame+i.index)%a!==0&&(o=!1),!o){const d=this._hitDiscs[t];d&&d.visible&&d.hit&&this.updateHitPointerPosition(i,d,d.hit.distance);continue}const l=this.context.physics.raycastFromRay(i.ray,{testObject:this.hitPointRaycastFilter,precise:!1});let h=l.find(d=>this.usePinchToTeleport&&i.isTeleportGesture?!0:this.isObjectWithInteractiveComponent(d.object));if(h||(h=l[0]),n&&(n.controller=i,n.hit=h),this._hitDistances[t]=h?.distance||null,h){this._lastHitDistances[t]=h.distance;const d=e.rigScale??1;Hf&&(B.DrawWireSphere(h.point,.025*d,16711680),B.DrawLabel(j(0,.2,0).add(h.point),h.object.name,.02,0)),n||(n=this.createHitPointObject(),this._hitDiscs[t]=n),n.hit=h,n.visible=h.distance>d*.05;let u=.01*(d+h.distance);const p=i.getButton("primary")?.pressed;p&&(u*=1.1),n.scale.set(u,u,u),n.layers.set(2);let m=n.material.opacity;if(p?m=1:m=h.distance<.15*d?.2:.6,n.material.opacity=L.lerp(n.material.opacity,m,this.context.time.deltaTimeUnscaled/.1),n.visible){if(h.normal){this.updateHitPointerPosition(i,n,h.distance);const y=h.normal.applyQuaternion(ue(h.object));n.quaternion.setFromUnitVectors(wM,y)}else this.updateHitPointerPosition(i,n,h.distance);n.parent!==this.context.scene&&this.context.scene.add(n)}}else this._hitDiscs[t]&&(this._hitDiscs[t].visible=!1)}}isObjectWithInteractiveComponent(e,t=0){return Id(e)||e.isUI===!0?!0:e.isScene?!1:e.parent?this.isObjectWithInteractiveComponent(e.parent,t+1):!1}updateHitPointerPosition(e,t,i){const n=j(e.rayWorldPosition);n.add(j(0,0,i-.01).applyQuaternion(e.rayWorldQuaternion)),t.position.lerp(n,this.context.time.deltaTimeUnscaled/.05)}hitPointRaycastFilter=e=>e.type==="SkinnedMesh"?"continue in children":!0;createHitPointObject(){const e=new c.Mesh(new c.SphereGeometry(.3,6,6),new c.MeshBasicMaterial({color:15658734,opacity:.7,transparent:!0,depthTest:!1,depthWrite:!1,side:c.DoubleSide}));return e.layers.disableAll(),e.layers.enable(2),e}createRayLineObject(){const e=new q.Line2;e.layers.disableAll(),e.layers.enable(2);const t=new q.LineGeometry;e.geometry=t;const i=new Float32Array(9);i.set([0,0,.02,0,0,.4,0,0,1]),t.setPositions(i);const n=new Float32Array(9);n.set([1,1,1,.1,.1,.1,0,0,0]),t.setColors(n);const o=new q.LineMaterial({color:16777215,vertexColors:!0,worldUnits:!0,linewidth:.004,transparent:!0,depthWrite:!1,blending:c.AdditiveBlending,dashed:!1});return e.material=o,e}}fo([f()],gi.prototype,"movementSpeed");fo([f()],gi.prototype,"rotationStep");fo([f()],gi.prototype,"useTeleport");fo([f()],gi.prototype,"usePinchToTeleport");fo([f()],gi.prototype,"useTeleportTarget");fo([f()],gi.prototype,"useTeleportFade");fo([f()],gi.prototype,"showRays");fo([f()],gi.prototype,"showHits");const wM=new c.Vector3(0,1,0);var xM=Object.defineProperty,lt=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&xM(e,t,n),n};const ll=x("debugwebxr"),SM=x("debugusdz"),Je=class Jr extends E{createVRButton=!0;createARButton=!0;createSendToQuestButton=!0;createQRCode=!0;useDefaultControls=!0;showControllerModels=!0;showHandModels=!0;usePlacementReticle=!0;customARPlacementReticle;usePlacementAdjustment=!0;arScale=1;useXRAnchor=!1;autoPlace=!1;autoCenter=!1;useQuicklookExport=!1;useDepthSensing=!1;useSpatialGrab=!0;defaultAvatar;_playerSync;_createdComponentsInSession=[];_usdzExporter;static activeWebXRComponent=null;awake(){G.getXRSync(this.context)}onEnable(){window.location.protocol!=="https:"&&de('<a href="https://developer.mozilla.org/en-US/docs/Web/API/WebXR_Device_API" target="_blank">WebXR</a> only works on secure connections (https).'),this.useQuicklookExport&&(S.findObjectOfType(sn)||(ll&&console.log("WebXR: Adding USDZExporter"),this._usdzExporter=S.addComponent(this.gameObject,sn),this._usdzExporter.objectToExport=this.context.scene,this._usdzExporter.autoExportAnimations=!0,this._usdzExporter.autoExportAudioSources=!0)),this.handleCreatingHTML(),this.handleOfferSession(),this.defaultAvatar===!0&&(ll&&console.warn("WebXR: No default avatar set, using static default avatar"),this.defaultAvatar=new Y("https://cdn.needle.tools/static/avatars/DefaultAvatar.glb")),this.defaultAvatar&&(this._playerSync=this.gameObject.getOrAddComponent(Dg),this._playerSync.autoSync=!1),this._playerSync&&typeof this.defaultAvatar!="boolean"&&(this._playerSync.asset=this.defaultAvatar,this._playerSync.onPlayerSpawned?.removeEventListener(this.onAvatarSpawned),this._playerSync.onPlayerSpawned?.addEventListener(this.onAvatarSpawned))}onDisable(){this._usdzExporter?.destroy(),this.removeButtons()}async handleOfferSession(){return this.createVRButton&&await G.isVRSupported()&&this.createVRButton?G.offerSession("immersive-vr","default",this.context):this.createARButton&&await G.isARSupported()&&this.createARButton?G.offerSession("immersive-ar","default",this.context):!1}get session(){return G.active??null}get sessionMode(){return G.activeMode??null}get arSessionRoot(){return this._activeWebARSessionRoot}async enterVR(e){return G.start("immersive-vr",e,this.context)}async enterAR(e){return G.start("immersive-ar",e,this.context)}exitXR(){G.stop()}_exitXRMenuButton;_previousXRState=0;_spatialGrabRaycaster;_activeWebARSessionRoot=null;get isActiveWebXR(){return!Jr.activeWebXRComponent||Jr.activeWebXRComponent===this}onBeforeXR(e,t){if(!this.isActiveWebXR){console.warn(`WebXR: another WebXR component is already active (${Jr.activeWebXRComponent?.name}). This is ignored: ${this.name}`);return}if(this.activeAndEnabled===!1||this.destroyed){console.debug("[WebXR] onBeforeXR called on disabled or destroyed component");return}Jr.activeWebXRComponent=this,e=="immersive-ar"&&this.useDepthSensing&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.push("depth-sensing"))}async onEnterXR(e){if(!this.isActiveWebXR)return;ll&&console.log("WebXR onEnterXR"),this._previousXRState=jt.Global.Mask;const t=e.xr.isVR;if(jt.Global.Set(t?Mn.VR:Mn.AR),e.xr.isAR){let i=S.findObjectOfType(di);if(!i)if(this.usePlacementReticle){const n=new c.Object3D;for(const o of this.context.scene.children)n.add(o);this.context.scene.add(n),i=S.addComponent(n,di),this._createdComponentsInSession.push(i)}else(ll||A())&&console.warn("WebXR: No WebARSessionRoot found in scene and usePlacementReticle is disabled in WebXR component.");this._activeWebARSessionRoot=i,i&&(i.customReticle=this.customARPlacementReticle,i.arScale=this.arScale,i.arTouchTransform=this.usePlacementAdjustment,i.autoPlace=this.autoPlace,i.autoCenter=this.autoCenter,i.useXRAnchor=this.useXRAnchor)}this.useDefaultControls&&this.setDefaultMovementEnabled(!0),(this.showControllerModels||this.showHandModels)&&this.setDefaultControllerRenderingEnabled(!0),this.useSpatialGrab&&(this._spatialGrabRaycaster=S.findObjectOfType(nr)??void 0,this._spatialGrabRaycaster||(this._spatialGrabRaycaster=this.gameObject.addComponent(nr))),this.createLocalAvatar(e.xr),e.xr.isScreenBasedAR||(this._exitXRMenuButton=this.context.menu.appendChild({label:"Quit XR",onClick:()=>this.exitXR(),icon:"exit_to_app",priority:2e4}))}onUpdateXR(e){this.isActiveWebXR&&this._spatialGrabRaycaster&&(this._spatialGrabRaycaster.enabled=this.useSpatialGrab)}onLeaveXR(e){if(this._exitXRMenuButton?.remove(),!!this.isActiveWebXR){jt.Global.Set(this._previousXRState),this._playerSync?.destroyInstance();for(const t of this._createdComponentsInSession)t.destroy();this._createdComponentsInSession.length=0,this._activeWebARSessionRoot=null,this.handleOfferSession(),wc(1).then(()=>Jr.activeWebXRComponent=null)}}setDefaultMovementEnabled(e){let t=this.gameObject.getComponent(gi);return!t&&e&&(t=this.gameObject.addComponent(gi),this._createdComponentsInSession.push(t)),t&&(t.enabled=e),t}setDefaultControllerRenderingEnabled(e){let t=this.gameObject.getComponent(ds);return!t&&e&&(t=this.gameObject.addComponent(ds),this._createdComponentsInSession.push(t),t.createControllerModel=this.showControllerModels,t.createHandModel==this.showHandModels),t&&(t.enabled=e),t}async createLocalAvatar(e){this._playerSync&&e.running&&typeof this.defaultAvatar!="boolean"&&(this._playerSync.asset=this.defaultAvatar,await this._playerSync.getInstance())}onAvatarSpawned=e=>{ll&&console.log("WebXR.onAvatarSpawned",e);let t=S.getComponentInChildren(e,io);t??=S.addComponent(e,io)};getButtonsContainer(){return this.getButtonsFactory()}getButtonsFactory(){return this._buttonFactory||(this._buttonFactory=Zs.getOrCreate()),this._buttonFactory}_buttonFactory;handleCreatingHTML(){if(this.createARButton||this.createVRButton||this.useQuicklookExport){if((exports.DeviceUtilities.isiOS()&&exports.DeviceUtilities.isSafari()||SM)&&this.useQuicklookExport){const t=S.findObjectOfType(sn);if(!t||t&&t.allowCreateQuicklookButton){const i=this.getButtonsFactory().createQuicklookButton();this.addButton(i,50)}}if(this.createARButton){const t=this.getButtonsFactory().createARButton();this.addButton(t,50)}if(this.createVRButton){const t=this.getButtonsFactory().createVRButton();this.addButton(t,50)}}if(this.createSendToQuestButton&&!exports.DeviceUtilities.isQuest()&&G.isVRSupported().then(t=>{if(!t){const i=this.getButtonsFactory().createSendToQuestButton();this.addButton(i,50)}}),this.createQRCode){const t=ka(Nn);if(t&&t.createQRCodeButton===!1)A()&&console.warn("WebXR: QRCode button is disabled in the Needle Menu component");else if(!exports.DeviceUtilities.isMobileDevice()){const i=Ji.getOrCreate().createQRCode();this.addButton(i,50)}}}_buttons=[];addButton(e,t){this._buttons.push(e),e.setAttribute("priority",t.toString()),this.context.menu.appendChild(e)}removeButtons(){for(const e of this._buttons)e.remove();this._buttons.length=0}};lt([f()],Je.prototype,"createVRButton");lt([f()],Je.prototype,"createARButton");lt([f()],Je.prototype,"createSendToQuestButton");lt([f()],Je.prototype,"createQRCode");lt([f()],Je.prototype,"useDefaultControls");lt([f()],Je.prototype,"showControllerModels");lt([f()],Je.prototype,"showHandModels");lt([f()],Je.prototype,"usePlacementReticle");lt([f(Y)],Je.prototype,"customARPlacementReticle");lt([f()],Je.prototype,"usePlacementAdjustment");lt([f()],Je.prototype,"arScale");lt([f()],Je.prototype,"useXRAnchor");lt([f()],Je.prototype,"autoPlace");lt([f()],Je.prototype,"autoCenter");lt([f()],Je.prototype,"useQuicklookExport");lt([f()],Je.prototype,"useDepthSensing");lt([f()],Je.prototype,"useSpatialGrab");lt([f(Y)],Je.prototype,"defaultAvatar");let ku=Je;const zh=x("debugusdzbehaviours");class Ig{get extensionName(){return"Behaviour"}behaviours=[];addBehavior(e){this.behaviours.push(e)}addAudioClip(e){if(!e||typeof e!="string")return"";const i="audio/"+br.getName(e);return this.audioClips.push({clipUrl:e,filesKey:i}),i}behaviourComponents=[];behaviourComponentsCopy=[];audioClips=[];audioClipsCopy=[];targetUuids=new Set;getAllTargetUuids(){return this.targetUuids}onBeforeBuildDocument(e){if(!e.root)return Promise.resolve();const t=[];return e.root.traverse(i=>{S.foreachComponent(i,n=>{const o=n;if(typeof o.createBehaviours=="function"||typeof o.beforeCreateDocument=="function"||typeof o.afterCreateDocument=="function"||typeof o.afterSerialize=="function"){this.behaviourComponents.push(o);const r=o.beforeCreateDocument?.call(o,this,e);r instanceof Promise&&t.push(r)}},!1)}),zh&&console.log("onBeforeBuildDocument: all components",this.behaviourComponents),Promise.all(t)}onExportObject(e,t,i){for(const n of this.behaviourComponents)n.createBehaviours?.call(n,this,t,i)}onAfterBuildDocument(e){for(const u of this.behaviourComponents)typeof u.afterCreateDocument=="function"&&u.afterCreateDocument(this,e);this.behaviourComponentsCopy=this.behaviourComponents.slice(),this.behaviourComponents.length=0,this.audioClipsCopy=this.audioClips.slice(),this.audioClips.length=0;const t=new Set,i=new Set,n=new Set,o=new Set,r=zh;let a=`graph LR
1276
1276
  `,l="";function h(u){if(u instanceof Uo){r&&(a+=`subgraph Group_${u.id}
1277
1277
  `);for(const p of u.actions)r&&(a+=`${u.id}[${u.id}] -- ${u.type},loops:${u.loops} --> ${p.id}[${p.id}]
1278
1278
  `),h(p);r&&(a+=`end
@@ -1649,4 +1649,4 @@ Error:`,r),null}}updateColliderCollisionGroups(e){const t=e[wt],i=e.membership;l
1649
1649
  justify-content: center;
1650
1650
  gap: .5rem;
1651
1651
  }
1652
- `),this.#n.innerHTML=this.#e.innerHTML,this.#n.style.cssText="display: flex; align-items: center; justify-content: center;",this.#e.innerHTML=this.#n.outerHTML,this.#t.innerHTML=this.#e.outerHTML,this.#t.prepend(this.#s),Ad(Bp,{element:this.#t}),this.#o?.disconnect(),this.#o??=new MutationObserver(()=>this.#l()),this.#o.observe(this.#e,{attributes:!0}),fp&&console.log("Needle Button updated")}#l(){this.#e&&(this.#e.style.display==="none"?this.style.display="none":this.style.display==="none"&&(this.style.display=""))}#r=e=>{fp&&console.log("Needle Button clicked"),!e.defaultPrevented&&this.#e&&this.#e.click()}}typeof window<"u"&&!window.customElements.get(Cb)&&window.customElements.define(Cb,cx);const vl=x("debugavatar");class wy{root;head;leftHand;rigthHand;get isValid(){return this.head!==null&&this.head!==void 0}constructor(e,t,i,n){this.root=e,this.head=t,this.leftHand=i,this.rigthHand=n,this.root?.traverse(o=>o.layers.set(2))}}class hx{avatarRegistryUrl=null;async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let i=null;if(typeof t=="string"){if(i=await this.loadAvatar(e,t),!i){const o=new hn;i=S.instantiate(ma(t,e.scene),o)}}else i=t;if(!i)return null;const n=this.findAvatar(i);return n.isValid?(vl&&console.log("[Custom Avatar] valid config",t,vl?n:""),n):(console.warn("[Custom Avatar] config isn't valid",t,vl?n:""),null)}async loadAvatar(e,t){if(console.assert(t!=null&&typeof t=="string","Avatar id must not be null"),t.length<=0||!t)return null;if(vl&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){const n=await fetch("./"+t);let o=null;if(n.ok){const a=await n.blob();a&&(o=await a.arrayBuffer())}return o?(await rn().parseSync(e,o,null,0))?.scene??null:null}const i=new q.GLTFLoader;return Xm(i,e),new Promise((n,o)=>{const r=this.avatarRegistryUrl+"/"+t;i.load(r,async a=>{await rn().createBuiltinComponents(e,r,a,null,void 0),n(a.scene)},a=>{vl&&console.log("[Custom Avatar] "+a.loaded/a.total*100+"% loaded of "+a.total/1024+"kB")},a=>{console.error("[Custom Avatar] Error when loading: "+a),n(null)})})}cacheModel(e,t){}findAvatar(e){const t=e;let i=t;i.children.length==1&&(i=e.children[0]);let n=this.findAvatarPart(i,["head"]);const o=this.findAvatarPart(i,["left","hand"]),r=this.findAvatarPart(i,["right","hand"]);if(!n){n=t;const l=new c.Vector3;new c.Box3().setFromObject(n).getSize(l);const h=Math.max(l.x,l.y,l.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+h+" meters! Should be < 0.3m"),h>.3&&n.scale.multiplyScalar(1/h*.3)}return new wy(t,n,o,r)}findAvatarPart(e,t){const i=e.name.toLowerCase();let n=!0;for(const o of t){if(!n)break;i.indexOf(o)===-1&&(n=!1)}if(n)return e;if(e.children)for(const o of e.children){const r=this.findAvatarPart(o,t);if(r)return r}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}}class dx{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(e){}}class ux{}const rT=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:le,ActionCollection:gw,ActionModel:Gt,AlignmentConstraint:Ac,Animation:Ct,AnimationCurve:Zc,AnimationExtension:xu,AnimationTrackHandler:mc,Animator:rt,AnimatorController:Li,Antialiasing:eh,Attractor:$a,AudioExtension:br,AudioListener:ss,AudioSource:pi,AudioTrackHandler:rs,Avatar:io,AvatarBlink_Simple:mr,AvatarEyeLook_Rotation:ng,AvatarLoader:hx,AvatarMarker:Se,AvatarModel:wy,Avatar_Brain_LookAt:cc,Avatar_MouthShapes:jc,Avatar_MustacheShake:tg,Avatar_POI:Yo,AxesHelper:Ra,BaseUIComponent:Bi,BasicIKConstraint:og,BehaviorExtension:Ig,BehaviorModel:gt,BloomEffect:Iu,BoxCollider:yu,BoxGizmo:Sr,BoxHelperComponent:nt,Button:Ss,CallInfo:ns,Camera:Qt,CameraTargetReachedEvent:lc,Canvas:Ca,CanvasGroup:no,CapsuleCollider:hs,ChangeMaterialOnClick:Og,ChangeTransformOnClick:vr,CharacterController:gr,CharacterControllerInput:ps,ChromaticAberration:th,ClickThrough:Zu,Collider:Jt,ColorAdjustments:_o,ColorBySpeedModule:Va,ColorOverLifetimeModule:Au,ContactShadows:Bc,ControlTrackHandler:Hu,CursorFollow:Dr,CustomBranding:xr,Deletable:cg,DeleteBox:Ys,DepthOfField:fn,DeviceFlag:_u,DocumentExtension:dx,DragControls:Fo,DropListener:gs,Duplicatable:yg,EffectWrapper:pc,EmissionModule:vs,EmphasizeOnClick:La,EnvironmentScene:Yu,EventList:oe,EventListEvent:uu,EventSystem:Bt,EventTrigger:vu,FieldWithDefault:Kv,FixedJoint:Qg,Fog:Ua,GltfExport:xg,GltfExportBox:vg,Gradient:Pr,Graphic:Gc,GraphicRaycaster:fu,GridHelper:za,GridLayoutGroup:Ng,GroundProjectedEnv:Un,GroupActionModel:Uo,HideOnStart:Ei,HingeJoint:Xc,HorizontalLayoutGroup:zg,get HoverAnimation(){return exports.HoverAnimation},Image:Qa,InheritVelocityModule:Jg,InputField:fy,InstanceHandle:Ko,InstancingHandler:or,Interactable:lg,Keyframe:Yt,LODGroup:Yc,LODModel:Na,Light:ii,LimitVelocityOverLifetimeModule:et,LogStats:ag,LookAt:py,LookAtConstraint:pr,MainModule:Mt,MarkerTrackHandler:Wu,MaskableGraphic:qc,MeshCollider:ho,MeshRenderer:Uc,MinMaxCurve:H,MinMaxGradient:Or,NeedleMenu:Nn,NestedGltf:Kc,Networking:Kg,NoiseModule:fe,ObjectRaycaster:fi,OffsetConstraint:Cr,OpenURL:Ya,OrbitControls:ce,Outline:Fa,Padding:wr,ParticleBurst:Wd,ParticleSubEmitter:ey,ParticleSystem:fc,ParticleSystemRenderer:Vi,PhysicsExtension:jg,PixelationEffect:ih,PlayAnimationOnClick:dc,PlayAudioOnClick:to,PlayableDirector:lr,PlayerColor:Pa,PointerEventData:Lc,PostProcessingHandler:oy,PreliminaryAction:Ia,PreliminaryTrigger:Vc,RawImage:Xu,Rect:ww,RectTransform:cn,ReflectionProbe:hc,RegisteredAnimationInfo:qs,RemoteSkybox:Bu,Renderer:Ut,RendererLightmap:pg,Rigidbody:Ve,RotationBySpeedModule:Ni,RotationOverLifetimeModule:un,SceneSwitcher:Fe,ScreenCapture:bo,ScreenSpaceAmbientOcclusion:ws,ScreenSpaceAmbientOcclusionN8:pn,ScrollFollow:Cs,SeeThrough:xs,SetActiveOnClick:Mg,ShadowCatcher:rh,ShapeModule:Zg,SharpeningEffect:sh,SignalAsset:$u,SignalReceiver:dh,SignalReceiverEvent:hh,SignalTrackHandler:gc,Size:vw,SizeBySpeedModule:ni,SizeOverLifetimeModule:Mr,SkinnedMeshRenderer:mg,SmoothFollow:Uu,SpatialGrabRaycaster:nr,SpatialHtml:fh,SpatialTrigger:zu,SpatialTriggerReceiver:jn,SpectatorCamera:Nu,SphereCollider:Ta,SplineContainer:Tr,SplineData:Fn,SplineWalker:Wi,Sprite:ys,SpriteData:fa,SpriteRenderer:ei,SpriteSheet:Sa,SubEmitterSystem:Hd,SyncedCamera:ay,SyncedRoom:mn,SyncedTransform:ln,TapGestureTrigger:Eg,TeleportTarget:Mu,TestRunner:ly,TestSimulateUserData:cy,Text:Ot,TextBuilder:Fg,TextExtension:Eu,TextureSheetAnimationModule:kt,TiltShiftEffect:Wn,ToneMappingEffect:so,TrailModule:Re,TransformData:ke,TransformGizmo:Ar,TriggerBuilder:St,TriggerModel:Ks,UIRaycastUtils:Km,UIRootComponent:Wc,USDZExporter:sn,USDZText:oa,USDZUIExtension:$g,UsageMarker:Fc,VariantAction:Pg,VelocityOverLifetimeModule:De,VerticalLayoutGroup:Ug,VideoPlayer:Ze,get ViewBox(){return exports.ViewBox},Vignette:Rr,VisibilityAction:$c,Voip:co,Volume:Ha,VolumeParameter:F,VolumeProfile:Du,WebARCameraBackground:mh,WebARSessionRoot:di,WebXR:ku,WebXRImageTracking:gh,WebXRImageTrackingModel:Os,WebXRPlaneTracking:Ms,WebXRTrackedImage:Oa,XRControllerFollow:Ps,XRControllerModel:ds,XRControllerMovement:gi,XRFlag:Ti,XRRig:tf,XRState:jt,__Ignore:ux},Symbol.toStringTag,{value:"Module"})),_c=x("debugmissingcamera");ae.registerCallback(re.MissingCamera,s=>{_c&&console.warn("Creating missing camera");const e=s.context.scene,t=new c.PerspectiveCamera;t.name="Default Fallback Camera",e.add(t);const i=new Qt;if(i.sourceId=s.files?.[0]?.src??"unknown",i.fieldOfView=35,s.context.domElement.getAttribute("transparent")!=null)i.clearFlags=Qo.Uninitialized;else if(s.context.domElement.getAttribute("background-image")?.length||s.context.lightmaps.tryGetSkybox(i.sourceId))i.clearFlags=Qo.Skybox;else{if(i.clearFlags=Qo.SolidColor,!s.context.domElement.getAttribute("background-color")){let a="#efefef";typeof window!==void 0&&window.matchMedia("(prefers-color-scheme: dark)").matches&&(a="#1f1f1f"),e.background=new c.Color(a)}if(!e.environment){const a=new c.PMREMGenerator$1(s.context.renderer),l=new Yu("neutral");e.environment=a.fromScene(l,.025).texture}}const o=Wo(t,i,!0);return t.position.x=0,t.position.y=1,t.position.z=2,s.context.domElement?.cameraControls!=!1&&fx(s.context,o),o});ae.registerCallback(re.ContextCreated,s=>{if(!s.context.mainCamera){_c&&console.log("Will not auto-fit because a default camera exists");return}if(s.context.domElement?.cameraControls==!0){if(Bb(s.context.mainCamera)?.isCameraController==!0){_c&&console.log("Will not auto-fit because a camera controller exists");return}fx(s.context)}});function fx(s,e){e=e??s.mainCameraComponent;const t=e?.gameObject;if(_c&&console.log("Creating default camera controls",e?.name),t){const i=Mc(t,ce);i.sourceId=e?.sourceId??"unknown";const n=s.domElement.getAttribute("auto-rotate");i.autoRotate=n!="0"&&n?.toLowerCase()!="false";const o=Number.parseFloat(n||".5");i.autoRotateSpeed=isNaN(o)?.5:o,_c&&console.log("Auto-rotate",i.autoRotate,"speed:",i.autoRotateSpeed);const r=s.domElement.getAttribute("auto-fit");i.autoFit=r!=="0"&&r?.toLowerCase()!="false",i.autoTarget=!0}else console.warn("Missing camera object, can not add orbit controls")}ae.registerCallback(re.ContextCreated,s=>{const e=s.context.domElement.getAttribute("autoplay");if(e!==void 0&&(e===""||e==="true"||e==="1")&&s.files)for(const t of s.files)S.foreachComponent(t.file.scene,n=>{if(n.enabled!==!1){if(n instanceof Ct&&n.playAutomatically||n instanceof rt||n instanceof lr&&n.playOnAwake===!0)return!0;if(n instanceof Ct)return n.playAutomatically=!0,!0;if(n instanceof lr)return n.playOnAwake=!0,!0}},!0)!==!0&&eo.autoplayAnimations(t.file)});exports.SplineUtils=void 0;(s=>{function e(t,i=!1,n=.75){const o=new Tr,r=1-L.clamp(n,0,1);return t.forEach((a,l)=>{const h=new c.Vector3;l<t.length-1?h.subVectors(t[l+1],a).normalize().multiplyScalar(r):i&&t.length>1&&h.subVectors(t[0],a).normalize().multiplyScalar(r);const d=new Fn;d.position.copy(a),d.tangentIn.copy(h),d.tangentOut.copy(h),o.addKnot(d)}),o.closed=i,o}s.createFromPoints=e})(exports.SplineUtils||(exports.SplineUtils={}));class aT extends se.WorkerBase{constructor(){super(new Worker(new URL("/generateMeshBVH.worker-B9bjdr6J.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:sf&&sf.tagName.toUpperCase()==="SCRIPT"&&sf.src||new URL("needle-engine.bundle-DG38kMjs.umd.cjs",document.baseURI).href),{type:"module"})),this.name="GenerateMeshBVHWorker"}runTask(e,t,i={}){return new Promise((n,o)=>{if(t.getAttribute("position").isInterleavedBufferAttribute||t.index&&t.index.isInterleavedBufferAttribute)throw new Error("GenerateMeshBVHWorker: InterleavedBufferAttribute are not supported for the geometry attributes.");e.onerror=h=>{o(new Error(`[GenerateMeshBVHWorker] ${h.message||"Unknown error. Please check the server console. If you're using vite try adding 'three-mesh-bvh' to 'optimizeDeps.exclude' in your vite.config.js"}`))},e.onmessage=h=>{const{data:d}=h;if(d.error)o(new Error(d.error)),e.onmessage=null;else if(d.serialized){const{serialized:u,position:p}=d,m=se.MeshBVH.deserialize(u,t,{setIndex:!1}),y=Object.assign({setBoundingBox:!0},i);if(t.attributes.position.array=p,u.index)if(t.index)t.index.array=u.index;else{const _=new c.BufferAttribute(u.index,1,!1);t.setIndex(_)}y.setBoundingBox&&(t.boundingBox=m.getBoundingBox(new c.Box3)),i.onProgress&&i.onProgress(d.progress),n(m),e.onmessage=null}else i.onProgress&&i.onProgress(d.progress)};const r=t.index?t.index.array:null,a=t.attributes.position.array,l=[a];r&&l.push(r),e.postMessage({index:r,position:a,options:{...i,onProgress:null,includedProgressCallback:!!i.onProgress,groups:[...t.groups]}},l.map(h=>h.buffer).filter(h=>typeof SharedArrayBuffer>"u"||!(h instanceof SharedArrayBuffer)))})}}const lT=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:aT},Symbol.toStringTag,{value:"Module"}));exports.$physicsKey=IP;exports.ActionBuilder=le;exports.ActionCollection=gw;exports.ActionModel=Gt;exports.Addressables=Z0;exports.AlignmentConstraint=Ac;exports.AmbientMode=da;exports.Animation=Ct;exports.AnimationCurve=Zc;exports.AnimationExtension=xu;exports.AnimationTrackHandler=mc;exports.AnimationUtils=eo;exports.Animator=rt;exports.AnimatorConditionMode=Vs;exports.AnimatorController=Li;exports.AnimatorControllerParameterType=Qm;exports.AnimatorStateInfo=Pl;exports.Antialiasing=eh;exports.Application=an;exports.AssetDatabase=m0;exports.AssetReference=Y;exports.Attractor=$a;exports.AudioExtension=br;exports.AudioListener=ss;exports.AudioSource=pi;exports.AudioTrackHandler=rs;exports.Avatar=io;exports.AvatarBlink_Simple=mr;exports.AvatarEyeLook_Rotation=ng;exports.AvatarLoader=hx;exports.AvatarMarker=Se;exports.AvatarModel=wy;exports.Avatar_Brain_LookAt=cc;exports.Avatar_MouthShapes=jc;exports.Avatar_MustacheShake=tg;exports.Avatar_POI=Yo;exports.Axes=na;exports.AxesHelper=Ra;exports.BUILD_TIME=Sm;exports.BaseUIComponent=Bi;exports.BasicIKConstraint=og;exports.BehaviorExtension=Ig;exports.BehaviorModel=gt;exports.BloomEffect=Iu;exports.BoxCollider=yu;exports.BoxGizmo=Sr;exports.BoxHelperComponent=nt;exports.Button=Ss;exports.ButtonsFactory=Ji;exports.CallDirection=Iv;exports.CallInfo=ns;exports.Camera=Qt;exports.CameraTargetReachedEvent=lc;exports.Canvas=Ca;exports.CanvasGroup=no;exports.CapsuleCollider=hs;exports.ChangeMaterialOnClick=Og;exports.ChangeTransformOnClick=vr;exports.CharacterController=gr;exports.CharacterControllerInput=ps;exports.ChromaticAberration=th;exports.CircularBuffer=ui;exports.ClearFlags=Qo;exports.ClickThrough=Zu;exports.ClipExtrapolation=xn;exports.Collider=Jt;exports.Collision=Av;exports.CollisionDetectionMode=du;exports.ColorAdjustments=_o;exports.ColorBySpeedModule=Va;exports.ColorOverLifetimeModule=Au;exports.Component=V1;exports.Component$1=E;exports.ComponentLifecycleEvents=iu;exports.Components=rT;exports.ConnectionEvents=c0;exports.ContactPoint=Tv;exports.ContactShadows=Bc;exports.Context=N;exports.ContextArgs=M1;exports.ContextEvent=re;exports.ContextRegistry=ae;exports.ControlTrackHandler=Hu;exports.CursorFollow=Dr;exports.CustomBranding=xr;exports.CustomShader=ye;exports.DefaultReflectionMode=Rd;exports.Deletable=cg;exports.DeleteBox=Ys;exports.DepthOfField=fn;exports.DeviceFlag=_u;exports.DocumentExtension=dx;exports.DragControls=Fo;exports.DragMode=hg;exports.DropListener=gs;exports.Duplicatable=yg;exports.EffectWrapper=pc;exports.EmissionModule=vs;exports.EmphasizeOnClick=La;exports.EngineLoadingView=yc;exports.EnvironmentScene=Yu;exports.EventList=oe;exports.EventListEvent=uu;exports.EventSystem=Bt;exports.EventTrigger=vu;exports.FieldWithDefault=Kv;exports.FileReference=qo;exports.FileReferenceSerializer=ev;exports.FileSpawnModel=sO;exports.File_Event=Vv;exports.FixedJoint=Qg;exports.Fog=Ua;exports.FrameEvent=pe;exports.GENERATOR=Kd;exports.GameObject=S;exports.Gizmos=B;exports.GltfExport=xg;exports.GltfExportBox=vg;exports.Gradient=Pr;exports.Graphic=Gc;exports.GraphicRaycaster=fu;exports.Graphics=Js;exports.GridHelper=za;exports.GridLayoutGroup=Ng;exports.GroundProjectedEnv=Un;exports.GroupActionModel=Uo;exports.HideFlags=pu;exports.HideOnStart=Ei;exports.HingeJoint=Xc;exports.HorizontalLayoutGroup=zg;exports.HostData=vC;exports.Image=Qa;exports.ImageReference=Go;exports.ImageReferenceSerializer=J0;exports.InheritVelocityModule=Jg;exports.Input=n0;exports.InputEventQueue=Xt;exports.InputEvents=xe;exports.InputField=fy;exports.InstanceHandle=Ko;exports.InstancingHandler=or;exports.InstancingUtil=Di;exports.InstantiateEvent=O0;exports.InstantiateIdProvider=mt;exports.InstantiateOptions=hn;exports.Interactable=lg;exports.JoinedRoomResponse=WS;exports.KeyEventArgs=DS;exports.Keyframe=Yt;exports.LODGroup=Yc;exports.LODModel=Na;exports.LeftRoomResponse=HS;exports.Light=ii;exports.LightData=ov;exports.LimitVelocityOverLifetimeModule=et;exports.LoadingElementOptions=HR;exports.LogStats=ag;exports.LogType=hi;exports.LookAt=py;exports.LookAtConstraint=pr;exports.MainModule=Mt;exports.MarkerTrackHandler=Wu;exports.MarkerType=hy;exports.MaskableGraphic=qc;exports.Mathf=L;exports.MeshCollider=ho;exports.MeshRenderer=Uc;exports.MinMaxCurve=H;exports.MinMaxGradient=Or;exports.NEKeyboardEvent=wl;exports.NEPointerEvent=Zn;exports.NeedleButtonElement=cx;exports.NeedleEngineWebComponent=vy;exports.NeedleMenu=Nn;exports.NeedlePatchesKey=Jh;exports.NeedleXRController=Mm;exports.NeedleXRSession=G;exports.NeedleXRSync=u0;exports.NeedleXRUtils=p0;exports.NestedGltf=Kc;exports.NetworkConnection=d0;exports.NetworkedStreamEvents=Rn;exports.NetworkedStreams=Ic;exports.Networking=Kg;exports.NewInstanceModel=k0;exports.NoiseModule=fe;exports.ObjectRaycaster=fi;exports.ObjectUtils=hr;exports.OffsetConstraint=Cr;exports.OneEuroFilter=Kh;exports.OneEuroFilterXYZ=mm;exports.OpenURL=Ya;exports.OrbitControls=ce;exports.Outline=Fa;exports.OwnershipEvent=h0;exports.OwnershipModel=Tm;exports.PUBLIC_KEY=ea;exports.Padding=wr;exports.ParticleBurst=Wd;exports.ParticleSubEmitter=ey;exports.ParticleSystem=fc;exports.ParticleSystemBaseBehaviour=yo;exports.ParticleSystemRenderer=Vi;exports.ParticleSystemShapeType=$d;exports.PeerHandle=os;exports.PeerNetworking=l0;exports.Physics=va;exports.PhysicsExtension=jg;exports.PhysicsMaterialCombine=it;exports.PixelationEffect=ih;exports.PlayAnimationOnClick=dc;exports.PlayAudioOnClick=to;exports.PlayableDirector=lr;exports.PlayerColor=Pa;exports.PlayerState=en;exports.PlayerStateEvent=bw;exports.PlayerSync=Dg;exports.PlayerView=iv;exports.PlayerViewManager=nv;exports.PointerEventData=Lc;exports.PointerType=eu;exports.PostProcessingEffect=$e;exports.PostProcessingEffectOrder=Ke;exports.PostProcessingHandler=oy;exports.PreliminaryAction=Ia;exports.PreliminaryTrigger=Vc;exports.PrimitiveType=Jo;exports.Progress=ie;exports.PromiseAllWithErrors=fm;exports.PromiseErrorResult=gp;exports.RGBAColor=Z;exports.RapierPhysics=pa;exports.RawImage=Xu;exports.RaycastOptions=lo;exports.Rect=ww;exports.RectTransform=cn;exports.ReflectionProbe=hc;exports.RegisteredAnimationInfo=qs;exports.RemoteSkybox=Bu;exports.RenderTexture=En;exports.RenderTextureSerializer=Mv;exports.Renderer=Ut;exports.RendererData=sv;exports.RendererLightmap=pg;exports.Rigidbody=Ve;exports.RigidbodyConstraints=Ie;exports.RoomEvents=Q;exports.RotationBySpeedModule=Ni;exports.RotationOverLifetimeModule=un;exports.SceneLightSettings=Fd;exports.SceneSwitcher=Fe;exports.ScreenCapture=bo;exports.ScreenSpaceAmbientOcclusion=ws;exports.ScreenSpaceAmbientOcclusionN8=pn;exports.ScrollFollow=Cs;exports.SeeThrough=xs;exports.SendQueue=Zi;exports.SerializationContext=Vm;exports.SetActiveOnClick=Mg;exports.ShadowCatcher=rh;exports.ShapeModule=Zg;exports.ShapeOverlapResult=Dv;exports.SharpeningEffect=sh;exports.SignalAsset=$u;exports.SignalReceiver=dh;exports.SignalReceiverEvent=hh;exports.SignalTrackHandler=gc;exports.Size=vw;exports.SizeBySpeedModule=ni;exports.SizeOverLifetimeModule=Mr;exports.SkinnedMeshRenderer=mg;exports.SmoothFollow=Uu;exports.SpatialGrabRaycaster=nr;exports.SpatialHtml=fh;exports.SpatialTrigger=zu;exports.SpatialTriggerReceiver=jn;exports.SpectatorCamera=Nu;exports.SphereCollider=Ta;exports.SphereIntersection=Lm;exports.SplineContainer=Tr;exports.SplineData=Fn;exports.SplineWalker=Wi;exports.Sprite=ys;exports.SpriteData=fa;exports.SpriteRenderer=ei;exports.SpriteSheet=Sa;exports.StateMachineBehaviour=X1;exports.StreamEndedEvent=Jm;exports.StreamReceivedEvent=Lv;exports.SubEmitterSystem=Hd;exports.SyncedCamera=ay;exports.SyncedRoom=mn;exports.SyncedTransform=ln;exports.TapGestureTrigger=Eg;exports.TeleportTarget=Mu;exports.TestRunner=ly;exports.TestSceneUtils=eT;exports.TestSimulateUserData=cy;exports.Text=Ot;exports.TextBuilder=Fg;exports.TextExtension=Eu;exports.TextureSheetAnimationModule=kt;exports.TiltShiftEffect=Wn;exports.Time=rv;exports.ToneMappingEffect=so;exports.TrackHandler=Xa;exports.TrackType=ri;exports.TrailModule=Re;exports.TransformData=ke;exports.TransformGizmo=Ar;exports.TriggerBuilder=St;exports.TriggerModel=Ks;exports.TypeStore=P;exports.UIRaycastUtils=Km;exports.UIRootComponent=Wc;exports.USDDocument=Sg;exports.USDObject=Ne;exports.USDWriter=aw;exports.USDZExporter=sn;exports.USDZExporter$1=lw;exports.USDZText=oa;exports.USDZUIExtension=$g;exports.UriSerializer=kv;exports.UsageMarker=Fc;exports.UserJoinedOrLeftRoomModel=GS;exports.VERSION=tn;exports.VariantAction=Pg;exports.VelocityOverLifetimeModule=De;exports.VerticalLayoutGroup=Ug;exports.VideoPlayer=Ze;exports.ViewDevice=Xs;exports.Vignette=Rr;exports.VisibilityAction=$c;exports.Voip=co;exports.Volume=Ha;exports.VolumeParameter=F;exports.VolumeProfile=Du;exports.WaitForFrames=ZC;exports.WaitForPromise=tv;exports.WaitForSeconds=Hm;exports.Watch=as;exports.WebARCameraBackground=mh;exports.WebARSessionRoot=di;exports.WebXR=ku;exports.WebXRButtonFactory=Zs;exports.WebXRImageTracking=gh;exports.WebXRImageTrackingModel=Os;exports.WebXRPlaneTracking=Ms;exports.WebXRTrackedImage=Oa;exports.XRControllerFollow=Ps;exports.XRControllerModel=ds;exports.XRControllerMovement=gi;exports.XRFlag=Ti;exports.XRRig=tf;exports.XRState=jt;exports.XRStateFlag=Mn;exports.__Ignore=ux;exports.__internalNotifyObjectDestroyed=cC;exports.activeInHierarchyFieldName=ls;exports.addAttributeChangeCallback=dm;exports.addComponent=nn;exports.addCustomExtensionPlugin=vO;exports.addNewComponent=Wo;exports.addPatch=Zd;exports.apply=su;exports.applyHMRChanges=N1;exports.applyPrototypeExtensions=z0;exports.beginListenDestroy=M0;exports.beginListenInstantiate=R0;exports.binaryIdentifierCasts=km;exports.build_scene_functions=O1;exports.builtinComponentKeyName=Do;exports.calculateProgress01=by;exports.clearMessages=Vx;exports.colorSerializer=dP;exports.compareAssociation=L0;exports.componentSerializer=ld;exports.copyTexture=Wb;exports.createMotion=xv;exports.debugNet=Nt;exports.debugOwner=xl;exports.decompressGpuTexture=uw;exports.deepClone=vc;exports.delay=Bn;exports.delayForFrames=wc;exports.deserializeObject=kd;exports.destroy=ji;exports.destroyComponentInstance=$0;exports.determineMimeTypeFromExtension=$v;exports.disposeObjectResources=_e;exports.disposeStream=Tn;exports.editorGuidKeyName=Ul;exports.enableSpatialConsole=No;exports.euler=fP;exports.eventListSerializer=yP;exports.exportAsGLTF=nT;exports.findByGuid=Wm;exports.findObjectOfType=ka;exports.findObjectsOfType=H0;exports.findResourceUsers=Im;exports.fitCamera=Sv;exports.fitObjectIntoVolume=Gb;exports.foreachComponent=tr;exports.foreachComponentEnumerator=ru;exports.forward=rS;exports.generateQRCode=cv;exports.generateSeed=E0;exports.getBoundingBox=Ft;exports.getCameraController=Bb;exports.getComponent=ur;exports.getComponentInChildren=Ec;exports.getComponentInParent=oc;exports.getComponents=kc;exports.getComponentsInChildren=Ma;exports.getComponentsInParent=nu;exports.getFormattedDate=nw;exports.getIconElement=pt;exports.getIconTexture=jp;exports.getLoader=rn;exports.getOrAddComponent=Mc;exports.getParam=x;exports.getParentHierarchyPath=cS;exports.getPath=vx;exports.getPeerOptions=zS;exports.getPeerjsInstance=a0;exports.getResourceUserCount=dC;exports.getTempColor=zb;exports.getTempQuaternion=qt;exports.getTempVector=j;exports.getUrlParams=bc;exports.getVisibleInCustomShadowRendering=Hb;exports.getWorldDirection=Nb;exports.getWorldEuler=_m;exports.getWorldPosition=X;exports.getWorldQuaternion=ue;exports.getWorldRotation=Yd;exports.getWorldScale=je;exports.hasCommercialLicense=cs;exports.hasIndieLicense=Tc;exports.hasPointerEventComponent=Id;exports.hasProLicense=In;exports.hideDebugConsole=Yb;exports.imageToCanvas=fw;exports.instantiate=ir;exports.invokeLoadedImportPluginHooks=Yv;exports.invokeXRSessionEnd=i0;exports.invokeXRSessionStart=t0;exports.isActiveInHierarchy=G0;exports.isActiveSelf=Ea;exports.isAndroidDevice=Ox;exports.isAnimationAction=$b;exports.isComponent=Rv;exports.isDebugMode=gx;exports.isDesktop=xx;exports.isDestroyed=er;exports.isDevEnvironment=A;exports.isDisposed=lC;exports.isExporting=tT;exports.isGLTFModel=Ev;exports.isHostedOnGlitch=Pb;exports.isHotReloadEnabled=Np;exports.isHotReloading=U1;exports.isIPad=Cx;exports.isIconElement=hv;exports.isLocalNetwork=Ii;exports.isMacOS=kx;exports.isMobileDevice=Sx;exports.isMozillaXR=Mx;exports.isQuest=Tx;exports.isResourceTrackingEnabled=y0;exports.isSafari=Rx;exports.isUsingInstancing=ou;exports.isiOS=Ex;exports.isiPad=Px;exports.loadAsset=UR;exports.loadPMREM=$w;exports.loadSync=_y;exports.logHierarchy=vd;exports.lookAtInverse=Zx;exports.lookAtObject=xc;exports.lookAtScreenPoint=Jx;exports.makeId=_x;exports.makeIdFromRandomWords=kb;exports.makeNameSafe=mi;exports.markAsInstancedRendered=q0;exports.microphonePermissionsGranted=Ax;exports.nameof=mx;exports.nameofFactory=Ob;exports.objectSerializer=Ov;exports.offXRSessionEnd=AS;exports.offXRSessionStart=TS;exports.onAfterRender=B1;exports.onBeforeRender=j1;exports.onClear=L1;exports.onDestroy=I1;exports.onInitialized=mv;exports.onStart=cu;exports.onUpdate=gv;exports.onXRSessionEnd=Om;exports.onXRSessionStart=Jd;exports.parseSync=sx;exports.placeOnSurface=qb;exports.postprocessFBXMaterials=wm;exports.prefix=oP;exports.pushState=Mb;exports.randomNumber=bx;exports.registerBinaryType=Em;exports.registerComponent=lu;exports.registerComponentExtension=ug;exports.registerCustomEffectType=$i;exports.registerExportExtensions=fg;exports.registerExtensions=zd;exports.registerHotReloadType=_v;exports.registerLoader=Cm;exports.registerPrefabProvider=A0;exports.registerPrototypeExtensions=N0;exports.registerType=Um;exports.relativePathPrefix=Rb;exports.removeAttributeChangeCallback=um;exports.removeComponent=$m;exports.removeCustomImportExtensionType=wO;exports.removePatch=ES;exports.resolveUrl=oo;exports.sanitizeString=Eb;exports.saveImage=ex;exports.screenshot=xR;exports.screenshot2=yy;exports.sendDestroyed=Bm;exports.serializable=f;exports.serializeObject=j0;exports.serializeable=Be;exports.setActive=Vl;exports.setAllowBalloonMessages=Lb;exports.setAllowOverlayMessages=Fx;exports.setAutoFitEnabled=_d;exports.setCameraController=_p;exports.setDestroyed=Q0;exports.setDevEnvironment=yS;exports.setDisposable=b0;exports.setDontDestroy=qr;exports.setOrAddParamsToUrl=mp;exports.setParam=yx;exports.setParamWithoutReload=tc;exports.setPeerOptions=NS;exports.setResourceTrackingEnabled=aC;exports.setState=cm;exports.setVisibleInCustomShadowRendering=vm;exports.setWorldEuler=bm;exports.setWorldPosition=ot;exports.setWorldPositionXYZ=Zo;exports.setWorldQuaternion=on;exports.setWorldQuaternionXYZW=ym;exports.setWorldRotation=Vb;exports.setWorldRotationXYZ=Sc;exports.setWorldScale=ga;exports.showBalloonError=Cc;exports.showBalloonMessage=Ce;exports.showBalloonWarning=de;exports.showDebugConsole=xm;exports.slerp=Kx;exports.syncDestroy=Pc;exports.syncField=Ag;exports.syncInstantiate=Fm;exports.textureToCanvas=hS;exports.toSourceId=Tb;exports.tryCastBinary=o0;exports.tryDetermineMimetypeFromBinary=Hv;exports.tryDetermineMimetypeFromURL=Wv;exports.tryFindObject=ma;exports.tryGetGuid=r0;exports.unregisterHotReloadType=bv;exports.unwatchWrite=hm;exports.useForAutoFit=Fb;exports.validate=yt;exports.watchWrite=Qd;
1652
+ `),this.#n.innerHTML=this.#e.innerHTML,this.#n.style.cssText="display: flex; align-items: center; justify-content: center;",this.#e.innerHTML=this.#n.outerHTML,this.#t.innerHTML=this.#e.outerHTML,this.#t.prepend(this.#s),Ad(Bp,{element:this.#t}),this.#o?.disconnect(),this.#o??=new MutationObserver(()=>this.#l()),this.#o.observe(this.#e,{attributes:!0}),fp&&console.log("Needle Button updated")}#l(){this.#e&&(this.#e.style.display==="none"?this.style.display="none":this.style.display==="none"&&(this.style.display=""))}#r=e=>{fp&&console.log("Needle Button clicked"),!e.defaultPrevented&&this.#e&&this.#e.click()}}typeof window<"u"&&!window.customElements.get(Cb)&&window.customElements.define(Cb,cx);const vl=x("debugavatar");class wy{root;head;leftHand;rigthHand;get isValid(){return this.head!==null&&this.head!==void 0}constructor(e,t,i,n){this.root=e,this.head=t,this.leftHand=i,this.rigthHand=n,this.root?.traverse(o=>o.layers.set(2))}}class hx{avatarRegistryUrl=null;async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let i=null;if(typeof t=="string"){if(i=await this.loadAvatar(e,t),!i){const o=new hn;i=S.instantiate(ma(t,e.scene),o)}}else i=t;if(!i)return null;const n=this.findAvatar(i);return n.isValid?(vl&&console.log("[Custom Avatar] valid config",t,vl?n:""),n):(console.warn("[Custom Avatar] config isn't valid",t,vl?n:""),null)}async loadAvatar(e,t){if(console.assert(t!=null&&typeof t=="string","Avatar id must not be null"),t.length<=0||!t)return null;if(vl&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){const n=await fetch("./"+t);let o=null;if(n.ok){const a=await n.blob();a&&(o=await a.arrayBuffer())}return o?(await rn().parseSync(e,o,null,0))?.scene??null:null}const i=new q.GLTFLoader;return Xm(i,e),new Promise((n,o)=>{const r=this.avatarRegistryUrl+"/"+t;i.load(r,async a=>{await rn().createBuiltinComponents(e,r,a,null,void 0),n(a.scene)},a=>{vl&&console.log("[Custom Avatar] "+a.loaded/a.total*100+"% loaded of "+a.total/1024+"kB")},a=>{console.error("[Custom Avatar] Error when loading: "+a),n(null)})})}cacheModel(e,t){}findAvatar(e){const t=e;let i=t;i.children.length==1&&(i=e.children[0]);let n=this.findAvatarPart(i,["head"]);const o=this.findAvatarPart(i,["left","hand"]),r=this.findAvatarPart(i,["right","hand"]);if(!n){n=t;const l=new c.Vector3;new c.Box3().setFromObject(n).getSize(l);const h=Math.max(l.x,l.y,l.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+h+" meters! Should be < 0.3m"),h>.3&&n.scale.multiplyScalar(1/h*.3)}return new wy(t,n,o,r)}findAvatarPart(e,t){const i=e.name.toLowerCase();let n=!0;for(const o of t){if(!n)break;i.indexOf(o)===-1&&(n=!1)}if(n)return e;if(e.children)for(const o of e.children){const r=this.findAvatarPart(o,t);if(r)return r}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}}class dx{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(e){}}class ux{}const rT=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:le,ActionCollection:gw,ActionModel:Gt,AlignmentConstraint:Ac,Animation:Ct,AnimationCurve:Zc,AnimationExtension:xu,AnimationTrackHandler:mc,Animator:rt,AnimatorController:Li,Antialiasing:eh,Attractor:$a,AudioExtension:br,AudioListener:ss,AudioSource:pi,AudioTrackHandler:rs,Avatar:io,AvatarBlink_Simple:mr,AvatarEyeLook_Rotation:ng,AvatarLoader:hx,AvatarMarker:Se,AvatarModel:wy,Avatar_Brain_LookAt:cc,Avatar_MouthShapes:jc,Avatar_MustacheShake:tg,Avatar_POI:Yo,AxesHelper:Ra,BaseUIComponent:Bi,BasicIKConstraint:og,BehaviorExtension:Ig,BehaviorModel:gt,BloomEffect:Iu,BoxCollider:yu,BoxGizmo:Sr,BoxHelperComponent:nt,Button:Ss,CallInfo:ns,Camera:Qt,CameraTargetReachedEvent:lc,Canvas:Ca,CanvasGroup:no,CapsuleCollider:hs,ChangeMaterialOnClick:Og,ChangeTransformOnClick:vr,CharacterController:gr,CharacterControllerInput:ps,ChromaticAberration:th,ClickThrough:Zu,Collider:Jt,ColorAdjustments:_o,ColorBySpeedModule:Va,ColorOverLifetimeModule:Au,ContactShadows:Bc,ControlTrackHandler:Hu,CursorFollow:Dr,CustomBranding:xr,Deletable:cg,DeleteBox:Ys,DepthOfField:fn,DeviceFlag:_u,DocumentExtension:dx,DragControls:Fo,DropListener:gs,Duplicatable:yg,EffectWrapper:pc,EmissionModule:vs,EmphasizeOnClick:La,EnvironmentScene:Yu,EventList:oe,EventListEvent:uu,EventSystem:Bt,EventTrigger:vu,FieldWithDefault:Kv,FixedJoint:Qg,Fog:Ua,GltfExport:xg,GltfExportBox:vg,Gradient:Pr,Graphic:Gc,GraphicRaycaster:fu,GridHelper:za,GridLayoutGroup:Ng,GroundProjectedEnv:Un,GroupActionModel:Uo,HideOnStart:Ei,HingeJoint:Xc,HorizontalLayoutGroup:zg,get HoverAnimation(){return exports.HoverAnimation},Image:Qa,InheritVelocityModule:Jg,InputField:fy,InstanceHandle:Ko,InstancingHandler:or,Interactable:lg,Keyframe:Yt,LODGroup:Yc,LODModel:Na,Light:ii,LimitVelocityOverLifetimeModule:et,LogStats:ag,LookAt:py,LookAtConstraint:pr,MainModule:Mt,MarkerTrackHandler:Wu,MaskableGraphic:qc,MeshCollider:ho,MeshRenderer:Uc,MinMaxCurve:H,MinMaxGradient:Or,NeedleMenu:Nn,NestedGltf:Kc,Networking:Kg,NoiseModule:fe,ObjectRaycaster:fi,OffsetConstraint:Cr,OpenURL:Ya,OrbitControls:ce,Outline:Fa,Padding:wr,ParticleBurst:Wd,ParticleSubEmitter:ey,ParticleSystem:fc,ParticleSystemRenderer:Vi,PhysicsExtension:jg,PixelationEffect:ih,PlayAnimationOnClick:dc,PlayAudioOnClick:to,PlayableDirector:lr,PlayerColor:Pa,PointerEventData:Lc,PostProcessingHandler:oy,PreliminaryAction:Ia,PreliminaryTrigger:Vc,RawImage:Xu,Rect:ww,RectTransform:cn,ReflectionProbe:hc,RegisteredAnimationInfo:qs,RemoteSkybox:Bu,Renderer:Ut,RendererLightmap:pg,Rigidbody:Ve,RotationBySpeedModule:Ni,RotationOverLifetimeModule:un,SceneSwitcher:Fe,ScreenCapture:bo,ScreenSpaceAmbientOcclusion:ws,ScreenSpaceAmbientOcclusionN8:pn,ScrollFollow:Cs,SeeThrough:xs,SetActiveOnClick:Mg,ShadowCatcher:rh,ShapeModule:Zg,SharpeningEffect:sh,SignalAsset:$u,SignalReceiver:dh,SignalReceiverEvent:hh,SignalTrackHandler:gc,Size:vw,SizeBySpeedModule:ni,SizeOverLifetimeModule:Mr,SkinnedMeshRenderer:mg,SmoothFollow:Uu,SpatialGrabRaycaster:nr,SpatialHtml:fh,SpatialTrigger:zu,SpatialTriggerReceiver:jn,SpectatorCamera:Nu,SphereCollider:Ta,SplineContainer:Tr,SplineData:Fn,SplineWalker:Wi,Sprite:ys,SpriteData:fa,SpriteRenderer:ei,SpriteSheet:Sa,SubEmitterSystem:Hd,SyncedCamera:ay,SyncedRoom:mn,SyncedTransform:ln,TapGestureTrigger:Eg,TeleportTarget:Mu,TestRunner:ly,TestSimulateUserData:cy,Text:Ot,TextBuilder:Fg,TextExtension:Eu,TextureSheetAnimationModule:kt,TiltShiftEffect:Wn,ToneMappingEffect:so,TrailModule:Re,TransformData:ke,TransformGizmo:Ar,TriggerBuilder:St,TriggerModel:Ks,UIRaycastUtils:Km,UIRootComponent:Wc,USDZExporter:sn,USDZText:oa,USDZUIExtension:$g,UsageMarker:Fc,VariantAction:Pg,VelocityOverLifetimeModule:De,VerticalLayoutGroup:Ug,VideoPlayer:Ze,get ViewBox(){return exports.ViewBox},Vignette:Rr,VisibilityAction:$c,Voip:co,Volume:Ha,VolumeParameter:F,VolumeProfile:Du,WebARCameraBackground:mh,WebARSessionRoot:di,WebXR:ku,WebXRImageTracking:gh,WebXRImageTrackingModel:Os,WebXRPlaneTracking:Ms,WebXRTrackedImage:Oa,XRControllerFollow:Ps,XRControllerModel:ds,XRControllerMovement:gi,XRFlag:Ti,XRRig:tf,XRState:jt,__Ignore:ux},Symbol.toStringTag,{value:"Module"})),_c=x("debugmissingcamera");ae.registerCallback(re.MissingCamera,s=>{_c&&console.warn("Creating missing camera");const e=s.context.scene,t=new c.PerspectiveCamera;t.name="Default Fallback Camera",e.add(t);const i=new Qt;if(i.sourceId=s.files?.[0]?.src??"unknown",i.fieldOfView=35,s.context.domElement.getAttribute("transparent")!=null)i.clearFlags=Qo.Uninitialized;else if(s.context.domElement.getAttribute("background-image")?.length||s.context.lightmaps.tryGetSkybox(i.sourceId))i.clearFlags=Qo.Skybox;else{if(i.clearFlags=Qo.SolidColor,!s.context.domElement.getAttribute("background-color")){let a="#efefef";typeof window!==void 0&&window.matchMedia("(prefers-color-scheme: dark)").matches&&(a="#1f1f1f"),e.background=new c.Color(a)}if(!e.environment){const a=new c.PMREMGenerator$1(s.context.renderer),l=new Yu("neutral");e.environment=a.fromScene(l,.025).texture}}const o=Wo(t,i,!0);return t.position.x=0,t.position.y=1,t.position.z=2,s.context.domElement?.cameraControls!=!1&&fx(s.context,o),o});ae.registerCallback(re.ContextCreated,s=>{if(!s.context.mainCamera){_c&&console.log("Will not auto-fit because a default camera exists");return}if(s.context.domElement?.cameraControls==!0){if(Bb(s.context.mainCamera)?.isCameraController==!0){_c&&console.log("Will not auto-fit because a camera controller exists");return}fx(s.context)}});function fx(s,e){e=e??s.mainCameraComponent;const t=e?.gameObject;if(_c&&console.log("Creating default camera controls",e?.name),t){const i=Mc(t,ce);i.sourceId=e?.sourceId??"unknown";const n=s.domElement.getAttribute("auto-rotate");i.autoRotate=n!="0"&&n?.toLowerCase()!="false";const o=Number.parseFloat(n||".5");i.autoRotateSpeed=isNaN(o)?.5:o,_c&&console.log("Auto-rotate",i.autoRotate,"speed:",i.autoRotateSpeed);const r=s.domElement.getAttribute("auto-fit");i.autoFit=r!=="0"&&r?.toLowerCase()!="false",i.autoTarget=!0}else console.warn("Missing camera object, can not add orbit controls")}ae.registerCallback(re.ContextCreated,s=>{const e=s.context.domElement.getAttribute("autoplay");if(e!==void 0&&(e===""||e==="true"||e==="1")&&s.files)for(const t of s.files)S.foreachComponent(t.file.scene,n=>{if(n.enabled!==!1){if(n instanceof Ct&&n.playAutomatically||n instanceof rt||n instanceof lr&&n.playOnAwake===!0)return!0;if(n instanceof Ct)return n.playAutomatically=!0,!0;if(n instanceof lr)return n.playOnAwake=!0,!0}},!0)!==!0&&eo.autoplayAnimations(t.file)});exports.SplineUtils=void 0;(s=>{function e(t,i=!1,n=.75){const o=new Tr,r=1-L.clamp(n,0,1);return t.forEach((a,l)=>{const h=new c.Vector3;l<t.length-1?h.subVectors(t[l+1],a).normalize().multiplyScalar(r):i&&t.length>1&&h.subVectors(t[0],a).normalize().multiplyScalar(r);const d=new Fn;d.position.copy(a),d.tangentIn.copy(h),d.tangentOut.copy(h),o.addKnot(d)}),o.closed=i,o}s.createFromPoints=e})(exports.SplineUtils||(exports.SplineUtils={}));class aT extends se.WorkerBase{constructor(){super(new Worker(new URL("/generateMeshBVH.worker-B9bjdr6J.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:sf&&sf.tagName.toUpperCase()==="SCRIPT"&&sf.src||new URL("needle-engine.bundle-DYcVfok9.umd.cjs",document.baseURI).href),{type:"module"})),this.name="GenerateMeshBVHWorker"}runTask(e,t,i={}){return new Promise((n,o)=>{if(t.getAttribute("position").isInterleavedBufferAttribute||t.index&&t.index.isInterleavedBufferAttribute)throw new Error("GenerateMeshBVHWorker: InterleavedBufferAttribute are not supported for the geometry attributes.");e.onerror=h=>{o(new Error(`[GenerateMeshBVHWorker] ${h.message||"Unknown error. Please check the server console. If you're using vite try adding 'three-mesh-bvh' to 'optimizeDeps.exclude' in your vite.config.js"}`))},e.onmessage=h=>{const{data:d}=h;if(d.error)o(new Error(d.error)),e.onmessage=null;else if(d.serialized){const{serialized:u,position:p}=d,m=se.MeshBVH.deserialize(u,t,{setIndex:!1}),y=Object.assign({setBoundingBox:!0},i);if(t.attributes.position.array=p,u.index)if(t.index)t.index.array=u.index;else{const _=new c.BufferAttribute(u.index,1,!1);t.setIndex(_)}y.setBoundingBox&&(t.boundingBox=m.getBoundingBox(new c.Box3)),i.onProgress&&i.onProgress(d.progress),n(m),e.onmessage=null}else i.onProgress&&i.onProgress(d.progress)};const r=t.index?t.index.array:null,a=t.attributes.position.array,l=[a];r&&l.push(r),e.postMessage({index:r,position:a,options:{...i,onProgress:null,includedProgressCallback:!!i.onProgress,groups:[...t.groups]}},l.map(h=>h.buffer).filter(h=>typeof SharedArrayBuffer>"u"||!(h instanceof SharedArrayBuffer)))})}}const lT=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:aT},Symbol.toStringTag,{value:"Module"}));exports.$physicsKey=IP;exports.ActionBuilder=le;exports.ActionCollection=gw;exports.ActionModel=Gt;exports.Addressables=Z0;exports.AlignmentConstraint=Ac;exports.AmbientMode=da;exports.Animation=Ct;exports.AnimationCurve=Zc;exports.AnimationExtension=xu;exports.AnimationTrackHandler=mc;exports.AnimationUtils=eo;exports.Animator=rt;exports.AnimatorConditionMode=Vs;exports.AnimatorController=Li;exports.AnimatorControllerParameterType=Qm;exports.AnimatorStateInfo=Pl;exports.Antialiasing=eh;exports.Application=an;exports.AssetDatabase=m0;exports.AssetReference=Y;exports.Attractor=$a;exports.AudioExtension=br;exports.AudioListener=ss;exports.AudioSource=pi;exports.AudioTrackHandler=rs;exports.Avatar=io;exports.AvatarBlink_Simple=mr;exports.AvatarEyeLook_Rotation=ng;exports.AvatarLoader=hx;exports.AvatarMarker=Se;exports.AvatarModel=wy;exports.Avatar_Brain_LookAt=cc;exports.Avatar_MouthShapes=jc;exports.Avatar_MustacheShake=tg;exports.Avatar_POI=Yo;exports.Axes=na;exports.AxesHelper=Ra;exports.BUILD_TIME=Sm;exports.BaseUIComponent=Bi;exports.BasicIKConstraint=og;exports.BehaviorExtension=Ig;exports.BehaviorModel=gt;exports.BloomEffect=Iu;exports.BoxCollider=yu;exports.BoxGizmo=Sr;exports.BoxHelperComponent=nt;exports.Button=Ss;exports.ButtonsFactory=Ji;exports.CallDirection=Iv;exports.CallInfo=ns;exports.Camera=Qt;exports.CameraTargetReachedEvent=lc;exports.Canvas=Ca;exports.CanvasGroup=no;exports.CapsuleCollider=hs;exports.ChangeMaterialOnClick=Og;exports.ChangeTransformOnClick=vr;exports.CharacterController=gr;exports.CharacterControllerInput=ps;exports.ChromaticAberration=th;exports.CircularBuffer=ui;exports.ClearFlags=Qo;exports.ClickThrough=Zu;exports.ClipExtrapolation=xn;exports.Collider=Jt;exports.Collision=Av;exports.CollisionDetectionMode=du;exports.ColorAdjustments=_o;exports.ColorBySpeedModule=Va;exports.ColorOverLifetimeModule=Au;exports.Component=V1;exports.Component$1=E;exports.ComponentLifecycleEvents=iu;exports.Components=rT;exports.ConnectionEvents=c0;exports.ContactPoint=Tv;exports.ContactShadows=Bc;exports.Context=N;exports.ContextArgs=M1;exports.ContextEvent=re;exports.ContextRegistry=ae;exports.ControlTrackHandler=Hu;exports.CursorFollow=Dr;exports.CustomBranding=xr;exports.CustomShader=ye;exports.DefaultReflectionMode=Rd;exports.Deletable=cg;exports.DeleteBox=Ys;exports.DepthOfField=fn;exports.DeviceFlag=_u;exports.DocumentExtension=dx;exports.DragControls=Fo;exports.DragMode=hg;exports.DropListener=gs;exports.Duplicatable=yg;exports.EffectWrapper=pc;exports.EmissionModule=vs;exports.EmphasizeOnClick=La;exports.EngineLoadingView=yc;exports.EnvironmentScene=Yu;exports.EventList=oe;exports.EventListEvent=uu;exports.EventSystem=Bt;exports.EventTrigger=vu;exports.FieldWithDefault=Kv;exports.FileReference=qo;exports.FileReferenceSerializer=ev;exports.FileSpawnModel=sO;exports.File_Event=Vv;exports.FixedJoint=Qg;exports.Fog=Ua;exports.FrameEvent=pe;exports.GENERATOR=Kd;exports.GameObject=S;exports.Gizmos=B;exports.GltfExport=xg;exports.GltfExportBox=vg;exports.Gradient=Pr;exports.Graphic=Gc;exports.GraphicRaycaster=fu;exports.Graphics=Js;exports.GridHelper=za;exports.GridLayoutGroup=Ng;exports.GroundProjectedEnv=Un;exports.GroupActionModel=Uo;exports.HideFlags=pu;exports.HideOnStart=Ei;exports.HingeJoint=Xc;exports.HorizontalLayoutGroup=zg;exports.HostData=vC;exports.Image=Qa;exports.ImageReference=Go;exports.ImageReferenceSerializer=J0;exports.InheritVelocityModule=Jg;exports.Input=n0;exports.InputEventQueue=Xt;exports.InputEvents=xe;exports.InputField=fy;exports.InstanceHandle=Ko;exports.InstancingHandler=or;exports.InstancingUtil=Di;exports.InstantiateEvent=O0;exports.InstantiateIdProvider=mt;exports.InstantiateOptions=hn;exports.Interactable=lg;exports.JoinedRoomResponse=WS;exports.KeyEventArgs=DS;exports.Keyframe=Yt;exports.LODGroup=Yc;exports.LODModel=Na;exports.LeftRoomResponse=HS;exports.Light=ii;exports.LightData=ov;exports.LimitVelocityOverLifetimeModule=et;exports.LoadingElementOptions=HR;exports.LogStats=ag;exports.LogType=hi;exports.LookAt=py;exports.LookAtConstraint=pr;exports.MainModule=Mt;exports.MarkerTrackHandler=Wu;exports.MarkerType=hy;exports.MaskableGraphic=qc;exports.Mathf=L;exports.MeshCollider=ho;exports.MeshRenderer=Uc;exports.MinMaxCurve=H;exports.MinMaxGradient=Or;exports.NEKeyboardEvent=wl;exports.NEPointerEvent=Zn;exports.NeedleButtonElement=cx;exports.NeedleEngineWebComponent=vy;exports.NeedleMenu=Nn;exports.NeedlePatchesKey=Jh;exports.NeedleXRController=Mm;exports.NeedleXRSession=G;exports.NeedleXRSync=u0;exports.NeedleXRUtils=p0;exports.NestedGltf=Kc;exports.NetworkConnection=d0;exports.NetworkedStreamEvents=Rn;exports.NetworkedStreams=Ic;exports.Networking=Kg;exports.NewInstanceModel=k0;exports.NoiseModule=fe;exports.ObjectRaycaster=fi;exports.ObjectUtils=hr;exports.OffsetConstraint=Cr;exports.OneEuroFilter=Kh;exports.OneEuroFilterXYZ=mm;exports.OpenURL=Ya;exports.OrbitControls=ce;exports.Outline=Fa;exports.OwnershipEvent=h0;exports.OwnershipModel=Tm;exports.PUBLIC_KEY=ea;exports.Padding=wr;exports.ParticleBurst=Wd;exports.ParticleSubEmitter=ey;exports.ParticleSystem=fc;exports.ParticleSystemBaseBehaviour=yo;exports.ParticleSystemRenderer=Vi;exports.ParticleSystemShapeType=$d;exports.PeerHandle=os;exports.PeerNetworking=l0;exports.Physics=va;exports.PhysicsExtension=jg;exports.PhysicsMaterialCombine=it;exports.PixelationEffect=ih;exports.PlayAnimationOnClick=dc;exports.PlayAudioOnClick=to;exports.PlayableDirector=lr;exports.PlayerColor=Pa;exports.PlayerState=en;exports.PlayerStateEvent=bw;exports.PlayerSync=Dg;exports.PlayerView=iv;exports.PlayerViewManager=nv;exports.PointerEventData=Lc;exports.PointerType=eu;exports.PostProcessingEffect=$e;exports.PostProcessingEffectOrder=Ke;exports.PostProcessingHandler=oy;exports.PreliminaryAction=Ia;exports.PreliminaryTrigger=Vc;exports.PrimitiveType=Jo;exports.Progress=ie;exports.PromiseAllWithErrors=fm;exports.PromiseErrorResult=gp;exports.RGBAColor=Z;exports.RapierPhysics=pa;exports.RawImage=Xu;exports.RaycastOptions=lo;exports.Rect=ww;exports.RectTransform=cn;exports.ReflectionProbe=hc;exports.RegisteredAnimationInfo=qs;exports.RemoteSkybox=Bu;exports.RenderTexture=En;exports.RenderTextureSerializer=Mv;exports.Renderer=Ut;exports.RendererData=sv;exports.RendererLightmap=pg;exports.Rigidbody=Ve;exports.RigidbodyConstraints=Ie;exports.RoomEvents=Q;exports.RotationBySpeedModule=Ni;exports.RotationOverLifetimeModule=un;exports.SceneLightSettings=Fd;exports.SceneSwitcher=Fe;exports.ScreenCapture=bo;exports.ScreenSpaceAmbientOcclusion=ws;exports.ScreenSpaceAmbientOcclusionN8=pn;exports.ScrollFollow=Cs;exports.SeeThrough=xs;exports.SendQueue=Zi;exports.SerializationContext=Vm;exports.SetActiveOnClick=Mg;exports.ShadowCatcher=rh;exports.ShapeModule=Zg;exports.ShapeOverlapResult=Dv;exports.SharpeningEffect=sh;exports.SignalAsset=$u;exports.SignalReceiver=dh;exports.SignalReceiverEvent=hh;exports.SignalTrackHandler=gc;exports.Size=vw;exports.SizeBySpeedModule=ni;exports.SizeOverLifetimeModule=Mr;exports.SkinnedMeshRenderer=mg;exports.SmoothFollow=Uu;exports.SpatialGrabRaycaster=nr;exports.SpatialHtml=fh;exports.SpatialTrigger=zu;exports.SpatialTriggerReceiver=jn;exports.SpectatorCamera=Nu;exports.SphereCollider=Ta;exports.SphereIntersection=Lm;exports.SplineContainer=Tr;exports.SplineData=Fn;exports.SplineWalker=Wi;exports.Sprite=ys;exports.SpriteData=fa;exports.SpriteRenderer=ei;exports.SpriteSheet=Sa;exports.StateMachineBehaviour=X1;exports.StreamEndedEvent=Jm;exports.StreamReceivedEvent=Lv;exports.SubEmitterSystem=Hd;exports.SyncedCamera=ay;exports.SyncedRoom=mn;exports.SyncedTransform=ln;exports.TapGestureTrigger=Eg;exports.TeleportTarget=Mu;exports.TestRunner=ly;exports.TestSceneUtils=eT;exports.TestSimulateUserData=cy;exports.Text=Ot;exports.TextBuilder=Fg;exports.TextExtension=Eu;exports.TextureSheetAnimationModule=kt;exports.TiltShiftEffect=Wn;exports.Time=rv;exports.ToneMappingEffect=so;exports.TrackHandler=Xa;exports.TrackType=ri;exports.TrailModule=Re;exports.TransformData=ke;exports.TransformGizmo=Ar;exports.TriggerBuilder=St;exports.TriggerModel=Ks;exports.TypeStore=P;exports.UIRaycastUtils=Km;exports.UIRootComponent=Wc;exports.USDDocument=Sg;exports.USDObject=Ne;exports.USDWriter=aw;exports.USDZExporter=sn;exports.USDZExporter$1=lw;exports.USDZText=oa;exports.USDZUIExtension=$g;exports.UriSerializer=kv;exports.UsageMarker=Fc;exports.UserJoinedOrLeftRoomModel=GS;exports.VERSION=tn;exports.VariantAction=Pg;exports.VelocityOverLifetimeModule=De;exports.VerticalLayoutGroup=Ug;exports.VideoPlayer=Ze;exports.ViewDevice=Xs;exports.Vignette=Rr;exports.VisibilityAction=$c;exports.Voip=co;exports.Volume=Ha;exports.VolumeParameter=F;exports.VolumeProfile=Du;exports.WaitForFrames=ZC;exports.WaitForPromise=tv;exports.WaitForSeconds=Hm;exports.Watch=as;exports.WebARCameraBackground=mh;exports.WebARSessionRoot=di;exports.WebXR=ku;exports.WebXRButtonFactory=Zs;exports.WebXRImageTracking=gh;exports.WebXRImageTrackingModel=Os;exports.WebXRPlaneTracking=Ms;exports.WebXRTrackedImage=Oa;exports.XRControllerFollow=Ps;exports.XRControllerModel=ds;exports.XRControllerMovement=gi;exports.XRFlag=Ti;exports.XRRig=tf;exports.XRState=jt;exports.XRStateFlag=Mn;exports.__Ignore=ux;exports.__internalNotifyObjectDestroyed=cC;exports.activeInHierarchyFieldName=ls;exports.addAttributeChangeCallback=dm;exports.addComponent=nn;exports.addCustomExtensionPlugin=vO;exports.addNewComponent=Wo;exports.addPatch=Zd;exports.apply=su;exports.applyHMRChanges=N1;exports.applyPrototypeExtensions=z0;exports.beginListenDestroy=M0;exports.beginListenInstantiate=R0;exports.binaryIdentifierCasts=km;exports.build_scene_functions=O1;exports.builtinComponentKeyName=Do;exports.calculateProgress01=by;exports.clearMessages=Vx;exports.colorSerializer=dP;exports.compareAssociation=L0;exports.componentSerializer=ld;exports.copyTexture=Wb;exports.createMotion=xv;exports.debugNet=Nt;exports.debugOwner=xl;exports.decompressGpuTexture=uw;exports.deepClone=vc;exports.delay=Bn;exports.delayForFrames=wc;exports.deserializeObject=kd;exports.destroy=ji;exports.destroyComponentInstance=$0;exports.determineMimeTypeFromExtension=$v;exports.disposeObjectResources=_e;exports.disposeStream=Tn;exports.editorGuidKeyName=Ul;exports.enableSpatialConsole=No;exports.euler=fP;exports.eventListSerializer=yP;exports.exportAsGLTF=nT;exports.findByGuid=Wm;exports.findObjectOfType=ka;exports.findObjectsOfType=H0;exports.findResourceUsers=Im;exports.fitCamera=Sv;exports.fitObjectIntoVolume=Gb;exports.foreachComponent=tr;exports.foreachComponentEnumerator=ru;exports.forward=rS;exports.generateQRCode=cv;exports.generateSeed=E0;exports.getBoundingBox=Ft;exports.getCameraController=Bb;exports.getComponent=ur;exports.getComponentInChildren=Ec;exports.getComponentInParent=oc;exports.getComponents=kc;exports.getComponentsInChildren=Ma;exports.getComponentsInParent=nu;exports.getFormattedDate=nw;exports.getIconElement=pt;exports.getIconTexture=jp;exports.getLoader=rn;exports.getOrAddComponent=Mc;exports.getParam=x;exports.getParentHierarchyPath=cS;exports.getPath=vx;exports.getPeerOptions=zS;exports.getPeerjsInstance=a0;exports.getResourceUserCount=dC;exports.getTempColor=zb;exports.getTempQuaternion=qt;exports.getTempVector=j;exports.getUrlParams=bc;exports.getVisibleInCustomShadowRendering=Hb;exports.getWorldDirection=Nb;exports.getWorldEuler=_m;exports.getWorldPosition=X;exports.getWorldQuaternion=ue;exports.getWorldRotation=Yd;exports.getWorldScale=je;exports.hasCommercialLicense=cs;exports.hasIndieLicense=Tc;exports.hasPointerEventComponent=Id;exports.hasProLicense=In;exports.hideDebugConsole=Yb;exports.imageToCanvas=fw;exports.instantiate=ir;exports.invokeLoadedImportPluginHooks=Yv;exports.invokeXRSessionEnd=i0;exports.invokeXRSessionStart=t0;exports.isActiveInHierarchy=G0;exports.isActiveSelf=Ea;exports.isAndroidDevice=Ox;exports.isAnimationAction=$b;exports.isComponent=Rv;exports.isDebugMode=gx;exports.isDesktop=xx;exports.isDestroyed=er;exports.isDevEnvironment=A;exports.isDisposed=lC;exports.isExporting=tT;exports.isGLTFModel=Ev;exports.isHostedOnGlitch=Pb;exports.isHotReloadEnabled=Np;exports.isHotReloading=U1;exports.isIPad=Cx;exports.isIconElement=hv;exports.isLocalNetwork=Ii;exports.isMacOS=kx;exports.isMobileDevice=Sx;exports.isMozillaXR=Mx;exports.isQuest=Tx;exports.isResourceTrackingEnabled=y0;exports.isSafari=Rx;exports.isUsingInstancing=ou;exports.isiOS=Ex;exports.isiPad=Px;exports.loadAsset=UR;exports.loadPMREM=$w;exports.loadSync=_y;exports.logHierarchy=vd;exports.lookAtInverse=Zx;exports.lookAtObject=xc;exports.lookAtScreenPoint=Jx;exports.makeId=_x;exports.makeIdFromRandomWords=kb;exports.makeNameSafe=mi;exports.markAsInstancedRendered=q0;exports.microphonePermissionsGranted=Ax;exports.nameof=mx;exports.nameofFactory=Ob;exports.objectSerializer=Ov;exports.offXRSessionEnd=AS;exports.offXRSessionStart=TS;exports.onAfterRender=B1;exports.onBeforeRender=j1;exports.onClear=L1;exports.onDestroy=I1;exports.onInitialized=mv;exports.onStart=cu;exports.onUpdate=gv;exports.onXRSessionEnd=Om;exports.onXRSessionStart=Jd;exports.parseSync=sx;exports.placeOnSurface=qb;exports.postprocessFBXMaterials=wm;exports.prefix=oP;exports.pushState=Mb;exports.randomNumber=bx;exports.registerBinaryType=Em;exports.registerComponent=lu;exports.registerComponentExtension=ug;exports.registerCustomEffectType=$i;exports.registerExportExtensions=fg;exports.registerExtensions=zd;exports.registerHotReloadType=_v;exports.registerLoader=Cm;exports.registerPrefabProvider=A0;exports.registerPrototypeExtensions=N0;exports.registerType=Um;exports.relativePathPrefix=Rb;exports.removeAttributeChangeCallback=um;exports.removeComponent=$m;exports.removeCustomImportExtensionType=wO;exports.removePatch=ES;exports.resolveUrl=oo;exports.sanitizeString=Eb;exports.saveImage=ex;exports.screenshot=xR;exports.screenshot2=yy;exports.sendDestroyed=Bm;exports.serializable=f;exports.serializeObject=j0;exports.serializeable=Be;exports.setActive=Vl;exports.setAllowBalloonMessages=Lb;exports.setAllowOverlayMessages=Fx;exports.setAutoFitEnabled=_d;exports.setCameraController=_p;exports.setDestroyed=Q0;exports.setDevEnvironment=yS;exports.setDisposable=b0;exports.setDontDestroy=qr;exports.setOrAddParamsToUrl=mp;exports.setParam=yx;exports.setParamWithoutReload=tc;exports.setPeerOptions=NS;exports.setResourceTrackingEnabled=aC;exports.setState=cm;exports.setVisibleInCustomShadowRendering=vm;exports.setWorldEuler=bm;exports.setWorldPosition=ot;exports.setWorldPositionXYZ=Zo;exports.setWorldQuaternion=on;exports.setWorldQuaternionXYZW=ym;exports.setWorldRotation=Vb;exports.setWorldRotationXYZ=Sc;exports.setWorldScale=ga;exports.showBalloonError=Cc;exports.showBalloonMessage=Ce;exports.showBalloonWarning=de;exports.showDebugConsole=xm;exports.slerp=Kx;exports.syncDestroy=Pc;exports.syncField=Ag;exports.syncInstantiate=Fm;exports.textureToCanvas=hS;exports.toSourceId=Tb;exports.tryCastBinary=o0;exports.tryDetermineMimetypeFromBinary=Hv;exports.tryDetermineMimetypeFromURL=Wv;exports.tryFindObject=ma;exports.tryGetGuid=r0;exports.unregisterHotReloadType=bv;exports.unwatchWrite=hm;exports.useForAutoFit=Fb;exports.validate=yt;exports.watchWrite=Qd;