@needle-tools/engine 4.8.8-next.8add297 → 4.8.8-next.9f3f7b5
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.
- package/dist/{needle-engine.bundle-DwiJRlay.umd.cjs → needle-engine.bundle-DXoJZx7H.umd.cjs} +5 -5
- package/dist/{needle-engine.bundle-WO60MbmU.min.js → needle-engine.bundle-cvcRzUlh.min.js} +4 -4
- package/dist/{needle-engine.bundle-DwigPmVZ.js → needle-engine.bundle-zcDWD5tM.js} +8 -8
- package/dist/needle-engine.js +2 -2
- package/dist/needle-engine.min.js +1 -1
- package/dist/needle-engine.umd.cjs +1 -1
- package/lib/engine/engine_create_objects.d.ts +3 -3
- package/lib/engine/engine_create_objects.js +4 -5
- package/lib/engine/engine_create_objects.js.map +1 -1
- package/lib/engine/extensions/NEEDLE_lighting_settings.js +2 -5
- package/lib/engine/extensions/NEEDLE_lighting_settings.js.map +1 -1
- package/lib/engine-components/OrbitControls.js +4 -2
- package/lib/engine-components/OrbitControls.js.map +1 -1
- package/package.json +1 -1
- package/src/engine/engine_create_objects.ts +7 -8
- package/src/engine/extensions/NEEDLE_lighting_settings.ts +2 -5
- package/src/engine-components/OrbitControls.ts +6 -2
package/dist/{needle-engine.bundle-DwiJRlay.umd.cjs → needle-engine.bundle-DXoJZx7H.umd.cjs}
RENAMED
|
@@ -141,7 +141,7 @@ void main(){
|
|
|
141
141
|
#__vconsole .vc-mask {
|
|
142
142
|
overflow: hidden;
|
|
143
143
|
}
|
|
144
|
-
`,po?.prepend(i),s===!0&&Z_()<=0&&gb(),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.":"")),Fa=!1,Mi=null},e.src="https://cdn.jsdelivr.net/npm/vconsole@3.15.1/dist/vconsole.min.js",document.body.appendChild(e)}function Yw(){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"),Mi?.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 Kw(){const s=document.querySelector("#__vconsole .vc-switch");return s||null}function Zw(){const s=document.querySelector("#__vconsole");return s||null}const yb=x("debugdefines");Ks('if(!globalThis["NEEDLE_ENGINE_VERSION"]) globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";');Ks('if(!globalThis["NEEDLE_ENGINE_GENERATOR"]) globalThis["NEEDLE_ENGINE_GENERATOR"] = "unknown";');Ks('if(!globalThis["NEEDLE_PROJECT_BUILD_TIME"]) globalThis["NEEDLE_PROJECT_BUILD_TIME"] = "unknown";');Ks('if(!globalThis["NEEDLE_PUBLIC_KEY"]) globalThis["NEEDLE_PUBLIC_KEY"] = "unknown";');Ks('globalThis["__NEEDLE_ENGINE_VERSION__"] = "4.8.8";');Ks('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";');Ks('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Thu Sep 04 2025
|
|
144
|
+
`,po?.prepend(i),s===!0&&Z_()<=0&&gb(),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.":"")),Fa=!1,Mi=null},e.src="https://cdn.jsdelivr.net/npm/vconsole@3.15.1/dist/vconsole.min.js",document.body.appendChild(e)}function Yw(){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"),Mi?.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 Kw(){const s=document.querySelector("#__vconsole .vc-switch");return s||null}function Zw(){const s=document.querySelector("#__vconsole");return s||null}const yb=x("debugdefines");Ks('if(!globalThis["NEEDLE_ENGINE_VERSION"]) globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";');Ks('if(!globalThis["NEEDLE_ENGINE_GENERATOR"]) globalThis["NEEDLE_ENGINE_GENERATOR"] = "unknown";');Ks('if(!globalThis["NEEDLE_PROJECT_BUILD_TIME"]) globalThis["NEEDLE_PROJECT_BUILD_TIME"] = "unknown";');Ks('if(!globalThis["NEEDLE_PUBLIC_KEY"]) globalThis["NEEDLE_PUBLIC_KEY"] = "unknown";');Ks('globalThis["__NEEDLE_ENGINE_VERSION__"] = "4.8.8";');Ks('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";');Ks('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Thu Sep 04 2025 08:41:57 GMT+0000 (Coordinated Universal Time)";');Ks('globalThis["__NEEDLE_PUBLIC_KEY__"] = "'+NEEDLE_PUBLIC_KEY+'";');const Ki="4.8.8",Ad="undefined",Xp="Thu Sep 04 2025 08:41:57 GMT+0000 (Coordinated Universal Time)";yb&&console.log(`Engine version: ${Ki} (generator: ${Ad})
|
|
145
145
|
Project built at ${Xp}`);const Fr=NEEDLE_PUBLIC_KEY,os="needle_isActiveInHierarchy",wo="builtin_components",wl="needle_editor_guid";function Ks(s){try{(0,eval)(s)}catch(e){yb&&console.error(e)}}let _b,ny=null;function Ji(){return _b}function Qp(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}ny!==s&&(ny=s,_b=new s)}const ii=Symbol("shadowDomOwner"),Jw=x("debugpatch");function Ld(s,e,t,i){const n=Jw===e;if(!t&&!i)return;const o=e+"___needle";tS(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]=oy(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]=oy(l,s,e);else{const h=this[o];bb(s,e,this,h,l),this[o]=l,vb(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=Yp(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 sy=Symbol("Needle:Patches:WrappedFunction");function oy(s,e,t){if(s[sy])return s;const i=function(...n){bb(e,t,this,...n);const o=s.apply(this,n);return vb(e,t,this,o,...n),o};return i[sy]=!0,i}const Lh="Needle:Patches";function Xf(){return globalThis[Lh]||(globalThis[Lh]=new WeakMap),globalThis[Lh]}function Yp(s,e){const t=Xf().get(s);return t?t.get(e):null}function tS(s,e,t,i){let n=Xf().get(s);n||(n=new Map,Xf().set(s,n));let o=n.get(e);o||(o=[],n.set(e,o)),o.push({prefix:t,postfix:i})}function bb(s,e,t,...i){if(!t)return;const n=Yp(s,e);if(n)for(const o of n)o.prefix?.call(t,...i)}function vb(s,e,t,i,...n){if(!t)return;const o=Yp(s,e);if(o)for(const r of o)r.postfix?.call(t,i,...n)}const ta=[];function Dd(s){ta.indexOf(s)===-1&&ta.push(s)}function iS(s){const e=ta.indexOf(s);e!==-1&&ta.splice(e,1)}const ia=[];function Kp(s){ia.indexOf(s)===-1&&ia.push(s)}function nS(s){const e=ia.indexOf(s);e!==-1&&ia.splice(e,1)}function xb(s){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-start",{detail:s}));for(let e=0;e<ta.length;e++)ta[e](s)}function wb(s){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-end",{detail:s}));for(let e=0;e<ia.length;e++)ia[e](s)}const He=x("debuginput");var Id=(s=>(s.Mouse="mouse",s.Touch="touch",s.Controller="controller",s.Hand="hand",s))(Id||{}),xe=(s=>(s.PointerDown="pointerdown",s.PointerUp="pointerup",s.PointerMove="pointermove",s.KeyDown="keydown",s.KeyUp="keyup",s.KeyPressed="keypress",s))(xe||{});class Qn 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(),He&&console.warn("Stop propagation...",this.pointerId,this.pointerType)}}class nl extends KeyboardEvent{source;constructor(e,t,i){super(e,i),this.source=t}stopImmediatePropagation(){super.stopImmediatePropagation(),this.source?.stopImmediatePropagation()}}class sS{key;keyType;source;constructor(e){this.key=e.key,this.keyType=e.type,this.source=e}}var Nt=(s=>(s[s.Early=-100]="Early",s[s.Default=0]="Default",s[s.Late=100]="Late",s))(Nt||{});class Sb{_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 nl){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 Qn){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,He&&console.log("immediatePropagationStopped",e.type);break}else e.propagationStopped&&(t=!0,He&&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":He&&Se("Create Pointer down"),this.onDownButton(e.deviceIndex,e.button),this.onDown(e);break;case"pointermove":He&&Se("Create Pointer move"),this.onMove(e);break;case"pointerup":He&&Se("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:(He&&console.warn("CanReceiveInput:False for",e.target),!1)}onContextMenu=e=>{this.canReceiveInput(e)!==!1&&e instanceof PointerEvent&&e.pointerType};keysPressed={};onKeyDown=e=>{if(He&&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 nl("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 nl("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 nl("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);He&&Se(`pointer down #${t}, identifier:${e.pointerId}`);const i=this.getAndUpdateSpatialObjectForScreenPosition(t,e.clientX,e.clientY),n=new Qn("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 Qn("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||(He&&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 Qn("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,He&&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 Qn("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 Qn("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 Qn("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||V(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 He&&!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}`,He?e:""),He&&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)){He&&console.log(e.pointerType,"UP",t,"was not down");return}He&&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]){He&&he("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;He&&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):(He&&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=F.Current;try{F.Current=this.context,this.dispatchEvent(e)}finally{F.Current=t}}}const Gr=new c.Matrix4().makeRotationY(Math.PI),Pi=new c.Quaternion().setFromAxisAngle(new c.Vector3(0,1,0),Math.PI),oS=x("debugwebxr");class rS{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",oS){const e=sm(16733661);e.position.y+=.5,this.gameObject.add(e)}}}const Un=x("debugwebxr"),eh=x("debugcustomgesture"),aS="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",lS="generic-trigger",cS=new c.Quaternion().setFromEuler(new c.Euler(c.MathUtils.degToRad(0),c.MathUtils.degToRad(-90),c.MathUtils.degToRad(-90))),hS=new c.Vector3(.04,-.04,0);class Zp{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 V(this._gripPosition)}get gripQuaternion(){return qi(this._gripQuaternion)}get gripMatrix(){return this._gripMatrix}get gripLinearVelocity(){return V(this._linearVelocity).applyQuaternion(Pi)}get rayPosition(){return V(this._rayPosition)}get rayQuaternion(){return qi(this._rayQuaternion)}get gripWorldPosition(){return V(this._gripWorldPosition)}_gripWorldPosition=new c.Vector3;get gripWorldQuaternion(){return qi(this._gripWorldQuaternion)}_gripWorldQuaternion=new c.Quaternion;get rayWorldPosition(){return V(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 qi(this._rayWorldQuaternion)}_rayWorldQuaternion=new c.Quaternion;get pinchPosition(){return V(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(Pi),t&&this._rayWorldQuaternion.premultiply(t)}get ray(){return this._ray.origin.copy(this.rayWorldPosition),this._ray.direction.copy(V(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=V(0,1,0).applyQuaternion(e.quaternion),i=V(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}`,Un&&(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,V(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+=`
|
|
@@ -161,7 +161,7 @@ or by using the once option like onStart(()=>{}, { once:true }).
|
|
|
161
161
|
See https://engine.needle.tools/docs/scripting.html#special-lifecycle-hooks for more information.`))}}function Zs(s,e){const t=zr.get(e);if(t){for(let n=0;n<t.length;n++)if(t[n].method===s){t.splice(n,1);return}}const i=Hr.get(e);if(i){for(let n=0;n<i.length;n++)if(i[n].method===s){i.splice(n,1);return}}}function hn(s,e){e===oe.ContextCreated&&Yf.delete(s),Cb(s,e)}function Cb(s,e){e===pe.Start&&Hr.get(oe.ContextCreated)&&Cb(s,oe.ContextCreated);const t=e===pe.Start||e===oe.ContextCreated,i=zr.get(e);i&&i.length>0&&hy(s,i,t);const n=Hr.get(e);if(n&&n.length>0){const o=[...n];n.length=0,hy(s,o,t),o.length>0&&(zr.has(e)||zr.set(e,new Array),zr.get(e).push(...o))}}const th=new Array,cy={context:null};function hy(s,e,t){th.length=0;for(let n=0;n<e.length;n++)th.push(e[n]);let i=Yf.get(s);for(let n=0;n<th.length;n++){const o=th[n];let r=!0;if(i&&i.has(o)&&(r=!1),r)try{cy.context=s,o.method?.call(cy,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,Yf.set(s,i)),i.add(o))}}const Yf=new WeakMap,Jp={};function em(s,e){Jp[s]=e}function Pb(s){const e=s.getBufferIdentifier(),t=Jp[e];return t(s)}function Ob(s){return typeof s.guid=="function"?s.guid():null}let tm;function dS(){return tm}function uS(s){tm=s}function Mb(s,e){return e||(e={}),e={...tm,...e},s?new se.$70d766613f57b014$export$2e2bcd8739ae039(s,e):new se.$70d766613f57b014$export$2e2bcd8739ae039(e)}async function dy(){const s=await Promise.resolve().then(()=>require("./vendor-xfQ8tKF3.umd.cjs")).then(e=>e.bundler);return console.log(s),s.default===void 0?s:s.default}class kb{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 dy(),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 pS(i)})}async trySetupClient(e){const t=await dy();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 fS{_peer;constructor(e){this._peer=e}}class pS extends fS{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 Xi=(s=>(s[s.OnConnection=0]="OnConnection",s[s.OnRoomJoin=1]="OnRoomJoin",s[s.Queued=2]="Queued",s[s.Immediate=3]="Immediate",s))(Xi||{});const uy="https://urls.needle.tools/default-networking-backend/index";let _i="wss://networking.needle.tools/socket";const jt=!!x("debugnet"),sl=!!(jt||x("debugowner")),ih=x("debugnetbin");var Rb=(s=>(s.ConnectionInfo="connection-start-info",s))(Rb||{}),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 mS{room;viewId;allowEditing;inRoom}class gS{room}class yS{userId}var Eb=(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))(Eb||{});class im{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||(sl&&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 sl&&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?(sl&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(sl&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}}class Tb{context;_peer=null;constructor(e){this.context=e}get peer(){return this._peer||(this._peer=new kb),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return jt}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(),jt&&console.log("join: "+e),this.send("join-room",{room:e,viewOnly:t},Xi.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=Xi.Queued){if(t===null&&(t={}),i===Xi.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){ih&&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,Xi.Immediate);break}const o=this.toMessage(n.key,n.value);this._defaultMessagesBufferArray.push(o)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&jt&&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!==_i)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?_i=t:V_()&&(_i="wss://"+window.location.host+"/socket"),this.connectWebsocket()}disconnect(){this._ws?.close(),this._ws=void 0,_i=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(_i===void 0&&(console.log("Fetch default backend url: "+uy),_i=await(await fetch(uy)).text()),_i===void 0){n(!1);return}console.debug(`⊡ Connecting to networking backend on
|
|
162
162
|
`+_i);const o=await Promise.resolve().then(()=>require("./vendor-xfQ8tKF3.umd.cjs")).then(h=>h.index),r=o.default?.WebsocketBuilder??o.WebsocketBuilder,a=o.default?.ExponentialBackoff??o.ExponentialBackoff,l=new r(_i).withMaxRetries(10).withBackoff(new a(2e3,4)).onOpen(()=>{this._connectingToWebsocketPromise=null,this._ws=l,this.connected=!0,A()||jt?console.log(`⊞ Connected to networking backend
|
|
163
163
|
`+_i):console.debug("⊞ Connected to networking backend",_i),n(!0),this.onSendQueued(Xi.OnConnection)}).onClose(h=>{this._connectingToWebsocketPromise=null,this.connected=!1,this._isInRoom=!1,n(!1);let d="Websocket connection closed...";_i?.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){jt&&i==="pong"?console.log("<<",i):A()&&console.error("Failed to parse message",n)}}async handleIncomingBinaryMessage(e){ih&&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=Pb(n),l=Ob(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(jt&&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(jt&&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),(ih||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}
|
|
164
|
-
${a.href}`)}this.onSendQueued(Xi.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,(ih||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),jt&&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&&(jt&&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":jt&&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),jt&&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=Xi.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));jt&&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 Sl=x("debugwebxr");class Nu{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=>{Sl&&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||(Sl&&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),Sl&&console.log(`XRSync: ${i.type} ${i.handedness} added`,i.index)}}}class Ab{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)||(Sl&&console.log("XRSync: Local user joined room",this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new Nu(this.context.connection.connectionId,this.context)));for(const e of this.context.connection.usersInRoom())this._states.has(e)||this._states.set(e,new Nu(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)||(Sl&&console.log("XRSync: Remote user joined room",t),this._states.set(t,new Nu(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 fy{_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=D.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 Vo=(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))(Vo||{});class Zo{static createText(e,t){let i=null;const n=t?.font||bS(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=_S(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",vS(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 _S(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 b=[];return b.push(new c.Vector2(d[u]/s,d[u+1]/e)),b.push(new c.Vector2(d[p]/s,d[p+1]/e)),b.push(new c.Vector2(d[m]/s,d[m+1]/e)),b.push(new c.Vector2(d[y]/s,d[y+1]/e)),b}}});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 nh=new Map;function bS(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(nh.has(e)){const n=nh.get(e);if(n)return n}const t=new q.FontLoader,i=new Promise((n,o)=>{t.load(e,r=>{nh.set(e,r),n(r)},void 0,o)});return nh.set(e,i),i}let Vu=!1,$u=null;function vS(s,e){if($u===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),Vu=!0,$u=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),my())).finally(()=>{Vu=!1})}if(Vu){const t=my();t.name="ShaderBall-Placeholder";const i=t.children[0];i?.type==="Mesh"&&py(i,e),s.add(t)}$u.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(),py(n,e)),s.add(i)})}function py(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 my(){return new c.Group().add(Zo.createPrimitive("Sphere",{material:new c.MeshBasicMaterial({transparent:!0,opacity:.1})}))}class na{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 na(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 Tn(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 Tn(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=D.random(0,1)>.5?Vo.Sphere:Vo.Cube,l=Zo.createPrimitive(a,{material:r});l.position.x=D.random(-n,n),l.position.y=D.random(-2,n),l.position.z=D.random(-n,n),l.rotation.x=D.random(0,Math.PI*2),l.rotation.y=D.random(0,Math.PI*2),l.rotation.z=D.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 jl;(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})(jl||(jl={}));const je=x("debugwebxr"),gy=x("stats");let Wu=0;function xS(s){let e=null;const t=s;return t.getAROverlayContainer?e=t.getAROverlayContainer():e=s,e}wS();async function wS(){if(x("debugasap")){let s=globalThis["needle:XRSession"];if(s instanceof Promise){delete globalThis["needle:XRSession"],re.addContextCreatedCallback(async e=>{if(!s)return;Eo(!0);const t=await s;if(t){const i=H.getDefaultSessionInit("immersive-vr");H.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()=>{Eo(!0),console.log("Received Session Granted..."),await Tn(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(Lb()&&(await na.start(s||"immersive-vr",t||H.getDefaultSessionInit("immersive-vr")),await PS(),i=await na.handoff()),i)H.setSession(i.mode,i.session,i.init,F.Current);else if(s&&e){console.log("Session Granted: Restore last session");const n=JSON.parse(e);H.start(s,n).catch(o=>console.warn(o))}else H.start("immersive-vr").catch(n=>console.warn("Session Granted failed:",n))},{once:!0})}}function SS(s,e){sessionStorage.setItem("needle_xr_session_mode",s),sessionStorage.setItem("needle_xr_session_init",JSON.stringify(e))}function CS(){sessionStorage.removeItem("needle_xr_session_mode"),sessionStorage.removeItem("needle_xr_session_init")}const nm=new Set;re.registerCallback(oe.ContextCreationStart,async s=>{nm.add(s.context)});re.registerCallback(oe.ContextCreated,async s=>{nm.delete(s.context);const e=s.context?.domElement.getAttribute("autostart")||null;OS(e)});function Lb(){return nm.size>0}function PS(){return new Promise(s=>{const e=Date.now(),t=setInterval(()=>{(!Lb()||Date.now()-e>6e4)&&(clearInterval(t),s())},100)})}exports.DeviceUtilities.isDesktop()&&A()&&window.addEventListener("keydown",s=>{(s.key==="x"||s.key==="Escape")&&H.active&&H.stop()});function OS(s){if(s)switch(s?.toLowerCase()){case"ar":en.registerWaitForInteraction(()=>{H.start("ar")});break}}class H{static _sync=null;static getXRSync(e){return this._sync||(this._sync=new Ab(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=>(je&&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=>H.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 jl.exportAndOpen(),null}else e=="ar"&&(e="immersive-ar");if(A()&&x("debugxrpreroom"))return console.warn("Debug: Starting temporary XR session"),await na.start(e,t||H.getDefaultSessionInit(e)),null;if(this._currentSessionRequest)return console.warn("A XRSession is already being requested"),(je||A())&&he("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=F.Current),i||(i=re.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=xS(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 na.stop();const n=e=="immersive-ar"?i.scripts_immersive_ar:i.scripts_immersive_vr;je?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});je&&Se("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&&he("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:"&&he("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 H(e,t,n,{scripts:o,controller_added:this._controllerAddedListeners,controller_removed:this._controllerRemovedListeners,init:i}),t.addEventListener("end",this.onEnd),je?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?(je&&console.log("[NeedleXRSession] Stopping XR Session... (new)"),e[this.$_stop_request]=setTimeout(()=>{e.end()})):je&&console.warn("[NeedleXRSession] XR Session stop already requested"))}static onEnd=()=>{je&&console.log("XR Session ended"),this._activeSession=null};context;get sync(){return H._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&&$o(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 V(0,0,0);const t=V(e);return t.x*=-1,t.z*=-1,t.applyQuaternion(qi(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($o(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)}je&&(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=V(i.transform.position),o=qi(i.transform.orientation),r=this.context.mainCamera;if(r?.parent!==this._cameraRenderParent&&n.applyMatrix4(Gr),r?.parent){n.applyMatrix4(r.parent.matrixWorld),o.multiply(Pi);const a=ue(r.parent);a.premultiply(Pi),o.premultiply(a)}return{hit:e,position:n,quaternion:o}}return null}convertSpace(e){const t=V(e.position);t.applyMatrix4(Gr);const i=qi(e.orientation);return i.premultiply(Pi),{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){SS(e,n.init),this.session=t,this.mode=e,this.context=i,(je||x("console"))&&Eo(!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,ls(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=Ae(this.context.mainCamera,new c.Vector3),this._originalCameraParent=this.context.mainCamera.parent),this._defaultRig=new rS,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):je&&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 Zp(this,e,t);this._newControllers.push(i)};disconnectInputSource(e){const t=(i,n,o)=>{if(i.inputSource===e){je&&console.log("Disconnecting controller",i.index),this.controllers.splice(o,1),this.invokeControllerEvent(i,this._controllerRemoved,"removed");const r={xr:this,controller:i,change:"removed"};for(const a of this._xr_scripts)a.onXRControllerRemoved&&a.onXRControllerRemoved(r);i.onDisconnected()}};for(let i=this.controllers.length-1;i>=0;i--){const n=this.controllers[i];t(n,this.controllers,i)}for(let i=this._newControllers.length-1;i>=0;i--){const n=this._newControllers[i];t(n,this._newControllers,i)}}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"),CS(),this.onAfterRender(),this.revertCustomForward(),this._didStart=!1,this._previousCameraParent=null,Zs(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()}),wb({session:this});for(const o of H._xrEndListeners)o({xr:this});const n=[...this.controllers];for(let o=0;o<n.length;o++)this.disconnectInputSource(n[o].inputSource);this._newControllers.length=0,this.controllers.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&&Ye(this.context.mainCamera,this._originalCameraWorldPosition),this._originalCameraWorldRotation&&Li(this.context.mainCamera,this._originalCameraWorldRotation),this._originalCameraWorldScale&&ea(this.context.mainCamera,this._originalCameraWorldScale)),this.context.requestSizeUpdate(),this._defaultRig.gameObject.removeFromParent(),Eo(!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&&(je&&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=Wt(this.context.scene.children);if(o){const r=o.getSize(V());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(V());l.y=a.position.y,a.lookAt(l)}}}xb({session:this}),Ko();for(const o of H._xrStartListeners)o(i);const n=[...this._xr_scripts];je&&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)}je&&this.context.time.frame%30===0&&this.controllers.length<=0&&this.session.inputSources.length>0&&(Eo(!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(je)for(const e of this.controllers)e.onRenderDebug();if((je||gy)&&this.rig&&(Wu++,Wu>=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()}`,je||gy)for(const o of this.controllers)n+=`
|
|
164
|
+
${a.href}`)}this.onSendQueued(Xi.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,(ih||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),jt&&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&&(jt&&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":jt&&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),jt&&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=Xi.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));jt&&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 Sl=x("debugwebxr");class Nu{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=>{Sl&&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||(Sl&&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),Sl&&console.log(`XRSync: ${i.type} ${i.handedness} added`,i.index)}}}class Ab{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)||(Sl&&console.log("XRSync: Local user joined room",this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new Nu(this.context.connection.connectionId,this.context)));for(const e of this.context.connection.usersInRoom())this._states.has(e)||this._states.set(e,new Nu(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)||(Sl&&console.log("XRSync: Remote user joined room",t),this._states.set(t,new Nu(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 fy{_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=D.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 Vo=(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))(Vo||{});class Zo{static createText(e,t){let i=null;const n=t?.font||bS(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=_S(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",vS(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,t.position.y,t.position.z)),t?.rotation&&(Array.isArray(t.rotation)?e.rotation.set(t.rotation[0],t.rotation[1],t.rotation[2]):e.rotation.set(t.rotation.x,t.rotation.y,t.rotation.z)),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,t.scale.y,t.scale.z)),t?.receiveShadow!=null&&(e.receiveShadow=t.receiveShadow),t?.castShadow!=null&&(e.castShadow=t.castShadow),t?.parent&&t.parent.add(e)}}function _S(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 b=[];return b.push(new c.Vector2(d[u]/s,d[u+1]/e)),b.push(new c.Vector2(d[p]/s,d[p+1]/e)),b.push(new c.Vector2(d[m]/s,d[m+1]/e)),b.push(new c.Vector2(d[y]/s,d[y+1]/e)),b}}});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 nh=new Map;function bS(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(nh.has(e)){const n=nh.get(e);if(n)return n}const t=new q.FontLoader,i=new Promise((n,o)=>{t.load(e,r=>{nh.set(e,r),n(r)},void 0,o)});return nh.set(e,i),i}let Vu=!1,$u=null;function vS(s,e){if($u===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),Vu=!0,$u=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),my())).finally(()=>{Vu=!1})}if(Vu){const t=my();t.name="ShaderBall-Placeholder";const i=t.children[0];i?.type==="Mesh"&&py(i,e),s.add(t)}$u.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(),py(n,e)),s.add(i)})}function py(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 my(){return new c.Group().add(Zo.createPrimitive("Sphere",{material:new c.MeshBasicMaterial({transparent:!0,opacity:.1})}))}class na{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 na(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 Tn(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 Tn(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=D.random(0,1)>.5?Vo.Sphere:Vo.Cube,l=Zo.createPrimitive(a,{material:r});l.position.x=D.random(-n,n),l.position.y=D.random(-2,n),l.position.z=D.random(-n,n),l.rotation.x=D.random(0,Math.PI*2),l.rotation.y=D.random(0,Math.PI*2),l.rotation.z=D.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 jl;(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})(jl||(jl={}));const je=x("debugwebxr"),gy=x("stats");let Wu=0;function xS(s){let e=null;const t=s;return t.getAROverlayContainer?e=t.getAROverlayContainer():e=s,e}wS();async function wS(){if(x("debugasap")){let s=globalThis["needle:XRSession"];if(s instanceof Promise){delete globalThis["needle:XRSession"],re.addContextCreatedCallback(async e=>{if(!s)return;Eo(!0);const t=await s;if(t){const i=H.getDefaultSessionInit("immersive-vr");H.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()=>{Eo(!0),console.log("Received Session Granted..."),await Tn(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(Lb()&&(await na.start(s||"immersive-vr",t||H.getDefaultSessionInit("immersive-vr")),await PS(),i=await na.handoff()),i)H.setSession(i.mode,i.session,i.init,F.Current);else if(s&&e){console.log("Session Granted: Restore last session");const n=JSON.parse(e);H.start(s,n).catch(o=>console.warn(o))}else H.start("immersive-vr").catch(n=>console.warn("Session Granted failed:",n))},{once:!0})}}function SS(s,e){sessionStorage.setItem("needle_xr_session_mode",s),sessionStorage.setItem("needle_xr_session_init",JSON.stringify(e))}function CS(){sessionStorage.removeItem("needle_xr_session_mode"),sessionStorage.removeItem("needle_xr_session_init")}const nm=new Set;re.registerCallback(oe.ContextCreationStart,async s=>{nm.add(s.context)});re.registerCallback(oe.ContextCreated,async s=>{nm.delete(s.context);const e=s.context?.domElement.getAttribute("autostart")||null;OS(e)});function Lb(){return nm.size>0}function PS(){return new Promise(s=>{const e=Date.now(),t=setInterval(()=>{(!Lb()||Date.now()-e>6e4)&&(clearInterval(t),s())},100)})}exports.DeviceUtilities.isDesktop()&&A()&&window.addEventListener("keydown",s=>{(s.key==="x"||s.key==="Escape")&&H.active&&H.stop()});function OS(s){if(s)switch(s?.toLowerCase()){case"ar":en.registerWaitForInteraction(()=>{H.start("ar")});break}}class H{static _sync=null;static getXRSync(e){return this._sync||(this._sync=new Ab(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=>(je&&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=>H.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 jl.exportAndOpen(),null}else e=="ar"&&(e="immersive-ar");if(A()&&x("debugxrpreroom"))return console.warn("Debug: Starting temporary XR session"),await na.start(e,t||H.getDefaultSessionInit(e)),null;if(this._currentSessionRequest)return console.warn("A XRSession is already being requested"),(je||A())&&he("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=F.Current),i||(i=re.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=xS(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 na.stop();const n=e=="immersive-ar"?i.scripts_immersive_ar:i.scripts_immersive_vr;je?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});je&&Se("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&&he("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:"&&he("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 H(e,t,n,{scripts:o,controller_added:this._controllerAddedListeners,controller_removed:this._controllerRemovedListeners,init:i}),t.addEventListener("end",this.onEnd),je?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?(je&&console.log("[NeedleXRSession] Stopping XR Session... (new)"),e[this.$_stop_request]=setTimeout(()=>{e.end()})):je&&console.warn("[NeedleXRSession] XR Session stop already requested"))}static onEnd=()=>{je&&console.log("XR Session ended"),this._activeSession=null};context;get sync(){return H._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&&$o(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 V(0,0,0);const t=V(e);return t.x*=-1,t.z*=-1,t.applyQuaternion(qi(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($o(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)}je&&(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=V(i.transform.position),o=qi(i.transform.orientation),r=this.context.mainCamera;if(r?.parent!==this._cameraRenderParent&&n.applyMatrix4(Gr),r?.parent){n.applyMatrix4(r.parent.matrixWorld),o.multiply(Pi);const a=ue(r.parent);a.premultiply(Pi),o.premultiply(a)}return{hit:e,position:n,quaternion:o}}return null}convertSpace(e){const t=V(e.position);t.applyMatrix4(Gr);const i=qi(e.orientation);return i.premultiply(Pi),{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){SS(e,n.init),this.session=t,this.mode=e,this.context=i,(je||x("console"))&&Eo(!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,ls(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=Ae(this.context.mainCamera,new c.Vector3),this._originalCameraParent=this.context.mainCamera.parent),this._defaultRig=new rS,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):je&&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 Zp(this,e,t);this._newControllers.push(i)};disconnectInputSource(e){const t=(i,n,o)=>{if(i.inputSource===e){je&&console.log("Disconnecting controller",i.index),this.controllers.splice(o,1),this.invokeControllerEvent(i,this._controllerRemoved,"removed");const r={xr:this,controller:i,change:"removed"};for(const a of this._xr_scripts)a.onXRControllerRemoved&&a.onXRControllerRemoved(r);i.onDisconnected()}};for(let i=this.controllers.length-1;i>=0;i--){const n=this.controllers[i];t(n,this.controllers,i)}for(let i=this._newControllers.length-1;i>=0;i--){const n=this._newControllers[i];t(n,this._newControllers,i)}}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"),CS(),this.onAfterRender(),this.revertCustomForward(),this._didStart=!1,this._previousCameraParent=null,Zs(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()}),wb({session:this});for(const o of H._xrEndListeners)o({xr:this});const n=[...this.controllers];for(let o=0;o<n.length;o++)this.disconnectInputSource(n[o].inputSource);this._newControllers.length=0,this.controllers.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&&Ye(this.context.mainCamera,this._originalCameraWorldPosition),this._originalCameraWorldRotation&&Li(this.context.mainCamera,this._originalCameraWorldRotation),this._originalCameraWorldScale&&ea(this.context.mainCamera,this._originalCameraWorldScale)),this.context.requestSizeUpdate(),this._defaultRig.gameObject.removeFromParent(),Eo(!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&&(je&&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=Wt(this.context.scene.children);if(o){const r=o.getSize(V());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(V());l.y=a.position.y,a.lookAt(l)}}}xb({session:this}),Ko();for(const o of H._xrStartListeners)o(i);const n=[...this._xr_scripts];je&&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)}je&&this.context.time.frame%30===0&&this.controllers.length<=0&&this.session.inputSources.length>0&&(Eo(!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(je)for(const e of this.controllers)e.onRenderDebug();if((je||gy)&&this.rig&&(Wu++,Wu>=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()}`,je||gy)for(const o of this.controllers)n+=`
|
|
165
165
|
${o.hand?"hand":"ctrl"} ${o.inputSource.handedness}[${o.index}] con:${o.connected} tr:${o.isTracking} hts:${o.hasHitTestSource?"yes":"no"}`;Wu=0,B.DrawLabel(e,n,void 0,1/60*20)}}onBeforeRender=()=>{this.context.mainCamera&&this.updateFade(this.context.mainCamera)};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:(je&&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){je&&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;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;if(this.rig){const t=Ae(this.rig.gameObject);e*=t.x}this._camera instanceof c.PerspectiveCamera&&this._camera.near>e&&(this.originalCameraNearPlane=this._camera.near,this._camera.near=e)}}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)}_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 fy),this._transition}fadeTransition(){return this._transition||(this._transition=new fy),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 Gu=x("debugwebxr");class Db{static tryFindAvatarObjects(e,t,i){if(i.head&&i.leftHand&&i.rightHand)return;const n=e.name.toLocaleLowerCase();!i.head&&n.includes("head")&&(Gu&&console.log("FOUND AVATAR HEAD",e.name),i.head=new Y("",t,e)),n.includes("hand")&&(!i.leftHand&&n.includes("left")&&(Gu&&console.log("FOUND AVATAR LEFT HAND",e.name),i.leftHand=new Y("",t,e)),!i.rightHand&&n.includes("right")&&(Gu&&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)}}}const _t=new c.Vector3,yy=new c.Vector3,_y=new c.Quaternion,MS=x("debuggizmos"),Wi=8947848,Hu=32;class B{constructor(){}static enabled=!0;static isGizmo(e){return e[Kf]!==void 0}static setVisible(e){for(const t of bi.timedObjectsBuffer)t.visible=e}static DrawLabel(e,t,i=.05,n=0,o,r,a){if(!B.enabled)return null;o||(o=Wi);const l=H.active?.rigScale??1,h=bi.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=Wi,n=0,o=!0){if(!B.enabled)return;const r=bi.getLine(n),a=r.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),_t.set(t.x,t.y,t.z).multiplyScalar(999999999),a.setXYZ(1,e.x+_t.x,e.y+_t.y,e.z+_t.z),a.needsUpdate=!0,r.material.color.set(i),r.material.depthTest=o,r.material.depthWrite=!1}static DrawDirection(e,t,i=Wi,n=0,o=!0,r=1){if(!B.enabled)return;const a=bi.getLine(n),l=a.geometry.getAttribute("position");l.setXYZ(0,e.x,e.y,e.z),t.w!==void 0?(_t.set(0,0,-r),_y.set(t.x,t.y,t.z,t.w),_t.applyQuaternion(_y)):(_t.set(t.x,t.y,t.z),_t.multiplyScalar(r)),l.setXYZ(1,e.x+_t.x,e.y+_t.y,e.z+_t.z),l.needsUpdate=!0,a.material.color.set(i),a.material.depthTest=o,a.material.depthWrite=!1}static DrawLine(e,t,i=Wi,n=0,o=!0){if(!B.enabled)return;const r=bi.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.color.set(i),r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1}static DrawCircle(e,t,i,n=Wi,o=0,r=!0){if(!B.enabled)return;const a=bi.getCircle(o);a.position.set(e.x,e.y,e.z),a.scale.set(i,i,i),a.quaternion.setFromUnitVectors(this._up,_t.set(t.x,t.y,t.z).normalize()),a.material.color.set(n),a.material.depthTest=r,a.material.depthWrite=!1,a.material.fog=!1}static DrawWireSphere(e,t,i=Wi,n=0,o=!0){if(!B.enabled)return;const r=bi.getSphere(t,n,!0);No(r,e.x,e.y,e.z),r.material.color.set(i),r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1}static DrawSphere(e,t,i=Wi,n=0,o=!0){if(!B.enabled)return;const r=bi.getSphere(t,n,!1);No(r,e.x,e.y,e.z),r.material.color.set(i),r.material.depthTest=o,r.material.depthWrite=!1}static DrawWireBox(e,t,i=Wi,n=0,o=!0,r=void 0){if(!B.enabled)return;const a=bi.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.color.set(i),a.material.depthTest=o,a.material.wireframe=!0,a.material.depthWrite=!1,a.material.fog=!1}static DrawWireBox3(e,t=Wi,i=0,n=!0){if(!B.enabled)return;const o=bi.getBox(i);o.position.copy(e.getCenter(_t)),o.scale.copy(e.getSize(_t)),o.material.color.set(t),o.material.depthTest=n,o.material.wireframe=!0,o.material.depthWrite=!1,o.material.fog=!1}static _up=new c.Vector3(0,1,0);static DrawArrow(e,t,i=Wi,n=0,o=!0,r=!1){if(!B.enabled)return;const a=bi.getArrowHead(n);a.position.set(t.x,t.y,t.z),a.quaternion.setFromUnitVectors(this._up.set(0,1,0),_t.set(t.x,t.y,t.z).sub(yy.set(e.x,e.y,e.z)).normalize());const h=_t.set(t.x,t.y,t.z).sub(yy.set(e.x,e.y,e.z)).length()*.1;a.scale.set(h,h,h),a.material.color.set(i),a.material.depthTest=o,a.material.wireframe=r,this.DrawLine(e,t,i,n,o)}static DrawWireMesh(e){const t=bi.getMesh(e.duration??0);"mesh"in e?(t.geometry=e.mesh.geometry,t.matrix.copy(e.mesh.matrixWorld)):(t.geometry=e.geometry,t.matrix.copy(e.matrix)),t.matrixAutoUpdate=!1,t.matrixWorldAutoUpdate=!1,t.material.color.set(e.color??Wi),t.material.depthTest=e.depthTest??!0,t.material.wireframe=!0}}const kS=new c.BoxGeometry(1,1,1);function sm(s=null){const e=new c.Color(s??14540253),t=new c.EdgesGeometry(kS);return new c.LineSegments(t,new c.LineBasicMaterial({color:e}))}const Kf=Symbol("GizmoCache");class bi{static familyName="needle-gizmos";static ensureFont(){let e=J.__webpack_exports__default.FontLibrary.getFontFamily(this.familyName);e||(e=J.__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",()=>{J.__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),MS&&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 J.__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(F.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(F.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(F.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(Hu*3),3),t.geometry.setAttribute("position",i);const n=V(0,1,0),o=V(0,0,1),r=V(o);r.cross(n).normalize();const a=V(r),l=Math.PI*2/(Hu-1);for(let h=0;h<Hu+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(F.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(F.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(F.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(F.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[Kf]=n,t.castShadow=!1,t.receiveShadow=!1,t.isGizmo=!0,this.timedObjectsBuffer.push(t),this.timesBuffer.push(F.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,J.__webpack_exports__default.update());for(let i=0;i<t.length;i++){const n=t[i];if(e.mainCamera&&n instanceof J.__webpack_exports__default.MeshUIBaseElement){if($o(n))continue;const o=e.isInVR,r=!1,a=!o;ec(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(),$o(r)!=!0&&r[Kf].push(r))}}}const At=x("debugphysics"),by=new c.Layers;class Js{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){by.set(e),this.layerMask=by}setMask(e){this.layerMask||(this.layerMask=new c.Layers);const t=this.layerMask;t?t.mask=e:this.layerMask=e}}class om{distance;point;object;constructor(e,t,i){this.object=e,this.distance=t,this.point=i}}class sa{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 Js;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){At&&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 At&&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)),At&&console.time("raycast"),o.length=0,sa._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))),sa._raycasting--,At&&(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(n.testObject){const h=n.testObject?.(o);if(h===!1)continue;h==="continue in children"&&(r=!1)}if(r&&(l&&vy(l)||(r=!1)),r){const h=ne.getRaycastMesh(o);h&&(a.geometry=h);const d=i.length;let u=!0;if(n.precise===!1&&(u=!1),u||=l.getAttribute("position")?.array?.length<64,a instanceof q.GroundedSkybox&&(u=!1),!u&&ES(a,e,i)||(n.useAcceleratedRaycast!==!1?nd.runMeshBVHRaycast(e,a,i,this.context,n):e.intersectObject(a,!1,i)),At&&i.length!=d){const p=i[i.length-1],m=h?8969557:7798784;B.DrawWireSphere(p.point,.1,m,1,!1),B.DrawWireMesh({mesh:o,depthTest:!1,duration:.2,color:m})}a.geometry=l}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&&vy(u)||(h=!1),h){if(a){const p=this.sphere;p.center.copy(t),p.radius=i;const m=o.length;if(nd.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),b=y.distanceTo(m.center),g=new om(e,b,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 vy(s){return!(s.index&&s.index.array.length<3)}const mo=new c.Sphere,sh=new c.Plane,RS=new c.Matrix3;function ES(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){sh.setFromNormalAndCoplanarPoint(V(0,1,0),V(0,-l.position.y,0)),sh.applyMatrix4(l.matrixWorld,RS);const u=o.ray.intersectPlane(sh,V());if(u){mo.copy(h),mo.applyMatrix4(l.matrixWorld);const m=V(u).sub(o.ray.origin).length(),y=mo.radius*.5;m<y&&r.push({distance:m,point:u,object:l,normal:sh.normal.clone()})}return}mo.copy(h),mo.applyMatrix4(l.matrixWorld);const d=o.ray.intersectSphere(mo,V());if(d){const u=V(d).sub(o.ray.origin),p=u.length();if(p>mo.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 nd;(s=>{function e(v,_,w,T,O){if(!_.geometry||!_.geometry.hasAttribute("position"))return!1;const M=_.geometry;if(_?.isSkinnedMesh){const R=_,j=R.bvhNeedsUpdate;if(!R.staticGenerator)a(),o&&(R.staticGenerator=new o(_),R.staticGenerator.applyWorldTransforms=!1,R.staticGeometry=R.staticGenerator.generate(),M.boundsTree=r?.call(R.staticGeometry),R.staticGeometryLastUpdate=performance.now()+Math.random()*200,R.bvhNeedsUpdate=!0);else if(M.boundsTree&&(R.autoUpdateMeshBvhInterval!==void 0&&R.autoUpdateMeshBvhInterval>=0||j===!0)){const L=performance.now(),z=L-R.staticGeometryLastUpdate,$=R.autoUpdateMeshBvhInterval??100;(j||z>$)&&(At&&console.warn(`Physics: updating skinned mesh bvh for ${_.name} after ${z.toFixed(2)}ms`),R.bvhNeedsUpdate=!1,R.staticGeometryLastUpdate=L,R.staticGenerator?.generate(R.staticGeometry),M.boundsTree.refit())}}else if(!M.boundsTree){h||g();let R=!0;if((T.xr||M[m]===!1||M.getAttribute("position")?.isInterleavedBufferAttribute||M.index&&M.index?.isInterleavedBufferAttribute)&&(R=!1),R&&u){if(M[p]===void 0){let j=null;if(b.length>0){const L=b.shift();L&&!L.running&&(j=L)}if(!j&&y.length<3&&(j=new u,y.push(j)),j!=null&&!j.running){const L=_.name;At&&console.log("<<<< worker start",L,j),M[p]="queued",performance.mark("bvh.create.start");const z=M.clone();try{j.generate(z).then($=>{M[p]="done",M.boundsTree=$}).catch($=>{M[p]="failed - "+$?.message,M[m]=!1,At&&console.error("Failed to generate mesh bvh on worker",$)}).finally(()=>{At&&console.log(">>>>> worker done",L,{hasBoundsTre:M.boundsTree!=null}),b.push(j),z.dispose(),performance.mark("bvh.create.end"),performance.measure("bvh.create (worker)","bvh.create.start","bvh.create.end")})}catch($){console.error("Failed to generate mesh bvh on worker",$)}}else At&&console.warn("No worker available")}}else(!d||!R)&&(a(),n&&(performance.mark("bvh.create.start"),M.boundsTree=new n(M),performance.mark("bvh.create.end"),performance.measure("bvh.create","bvh.create.start","bvh.create.end")))}if(v instanceof c.Raycaster){const R=v,j=_.raycast;if(M.boundsTree)a(),i&&(_.acceleratedRaycast||(_.acceleratedRaycast=i.bind(_),At&&console.debug(`Physics: bind acceleratedRaycast fn to "${_.name}"`)),_.raycast=_.acceleratedRaycast);else if(At&&console.warn("No bounds tree found for mesh",_.name,{workerTask:M[p],hasAcceleratedRaycast:i!=null}),O.allowSlowRaycastFallback===!1)return At&&console.warn("Skipping raycast because no bounds tree is available and allowSlowRaycastFallback is false"),!1;const L=R.firstHitOnly;return R.firstHitOnly=!1,R.intersectObject(_,!1,w),R.firstHitOnly=L,_.raycast=j,!0}else if(v instanceof c.Sphere){const R=M.boundsTree;if(R){const j=v;if(l.copy(_.matrixWorld).invert(),j.applyMatrix4(l),R.intersectsSphere(j)){const z=X(_),$=z.distanceTo(j.center),E=new om(_,$,z);w.push(E)}}return!0}return!1}s.runMeshBVHRaycast=e;let t=!1,i=null,n=null,o=null,r=null;function a(){t||(t=!0,Promise.resolve().then(()=>require("./vendor-xfQ8tKF3.umd.cjs")).then(v=>v.index$1).then(v=>{i=v.acceleratedRaycast,n=v.MeshBVH,o=v.StaticGeometryGenerator,r=v.computeBoundsTree}).catch(v=>{(At||A())&&console.error("Failed to load BVH library...",v.message)}))}const l=new c.Matrix4;let h=!1,d=!1,u=null;const p=Symbol("Needle:MeshBVH-Worker"),m=Symbol("Needle:MeshBVH-CanUseWorker"),y=[],b=[];function g(){h=!0,d=!0,Promise.resolve().then(()=>iE).then(v=>{u=v.GenerateMeshBVHWorker}).catch(v=>{(At||A())&&console.warn("Failed to setup mesh bvh worker")}).finally(()=>{d=!1})}})(nd||(nd={}));const xy=Symbol("gltf-loader-internal-usage-tracker"),TS=x("debugusers");class qr{get name(){return"NEEDLE_internal_usage_tracker"}static isLoading(e){return qr._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(){qr._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[xy]=e._loadingId),r)),o},null}afterRoot(e){qr._loadingProcesses--,this.parser.getDependency=this._getDependency;for(const t of this._loadedObjects)delete t[xy],t instanceof c.Object3D&&(t.parent||t instanceof c.Mesh&&setTimeout(()=>{TS&&console.warn("> GLTF LOADER: Mesh not used in scene!",t),t.material=null,t.geometry=null},1e3));return null}}class Ib{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:
|
|
166
166
|
`+i.src),e.preventDefault())}})}}const jd=x("trackresources");function jb(){return jd==="dispose"}let Jo=!0;jd===0&&(Jo=!1);function AS(s){Jo=s}function Bb(){return Jo}const Fb=Symbol("disposable");function Ub(s,e){s&&(s[Fb]=e,Ao&&console.warn("Set disposable",e,s))}const zb=Symbol("disposed");function LS(s){return s[zb]===!0}function _e(s){if(s){if(s[Fb]===!1){Ao&&console.warn("Object is marked as not disposable",s);return}if(typeof s=="object"&&(s[zb]=!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.geometry={},s.material={},s.visible=!1;else if(s instanceof c.Mesh)_e(s.geometry),_e(s.material),_e(s.customDepthMaterial),_e(s.customDistanceMaterial),s.geometry={},s.material={},s.visible=!1;else if(s instanceof c.BufferGeometry){wr(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)Ao&&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){wr(s);for(const t of Object.keys(s)){const i=s[t];i instanceof c.Texture&&(_e(i),s[t]=null)}const e=s.uniforms;if(e)for(const t of Object.keys(e)){const i=e[t];i instanceof c.Texture?(_e(i),e[t]=null):i instanceof c.Uniform$1&&(_e(i.value),i.value=null)}}else s instanceof c.Texture?(wr(s),wr(s.source),s.source?.data instanceof ImageBitmap&&wr(s.source.data)):s instanceof c.Skeleton?(wr(s.boneTexture),s.boneTexture=null):s instanceof c.Bone||!(s instanceof c.Object3D)&&Ao&&console.warn("Unknown object type",s)}}function wr(s){s&&((Ao||jb()||jd)&&console.warn("🧨 FREE",s),s instanceof ImageBitmap?s.close():s instanceof c.Source?s.data=null:s.dispose())}function Nb(s){(s instanceof c.Mesh||s instanceof c.SkinnedMesh)&&(s.material={},s.geometry={})}const DS=new Set;function rm(s,e,t=null,i){if(i||(i=DS,i.clear()),!s)return i;const n=s[Bl];if(n)for(const o of n)i.has(o)||t?.call(null,o)!==!1&&(i.add(o),e&&rm(o,!0,t,i));return i}function IS(s){return s[ol]}const Ao=x("debugresourceusers")||x("debugmemory"),Bl=Symbol("needle-resource-users"),ol=Symbol("needle-resource-users-count");function Ot(s,e){Ld(s,e,function(t,i){Jo&&!sa.raycasting&&(sd(Bl,this,t,!1),sd(Bl,this,i,!0))})}Jo&&(Ot(c.Mesh.prototype,"material"),Ot(c.Mesh.prototype,"geometry"),Ot(c.Material.prototype,"map"),Ot(c.Material.prototype,"bumpMap"),Ot(c.Material.prototype,"alphaMap"),Ot(c.Material.prototype,"normalMap"),Ot(c.Material.prototype,"displacementMap"),Ot(c.Material.prototype,"roughnessMap"),Ot(c.Material.prototype,"metalnessMap"),Ot(c.Material.prototype,"emissiveMap"),Ot(c.Material.prototype,"specularMap"),Ot(c.Material.prototype,"envMap"),Ot(c.Material.prototype,"lightMap"),Ot(c.Material.prototype,"aoMap"),Ot(c.Material.prototype,"gradientMap"));function jS(s){if(Jo===!1)return;const e=s[Bl];if(e)for(const t of e)sd(Bl,t,s,!1)}Jo&&Ld(c.Material.prototype,"dispose",function(){jS(this)});let Zf=0;function sd(s,e,t,i){if(Zf>0)return;if(Array.isArray(t)){for(const o of t)sd(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[ol]||0;o+=1,t[ol]=o,Ao&&console.warn(`🟢 Added user of "${t.type}"`,e,t,o,"users:",n)}}else if(e&&n.has(e)){n.delete(e);let o=t[ol]||0;o>0&&(o-=1,t[ol]=o),Ao&&console.warn(`🔴 Removed user of "${t.type}"`,e,t,o,"users:",n),o<=0&&(qr.isLoading(t)||(jd&&console.warn(`🔴 Removed all user of "${t.type}"`,t),jb()&&_e(t)))}t[s]=n}try{Ld(c.WebGLRenderer.prototype,"render",function(){Zf++},function(){Zf--})}catch(s){console.warn("Could not wrap WebGLRenderer.render",s)}const wy=x("debugcomponentevents");class Bd{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),wy&&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(wy&&console.log("Dispatching event "+e,i),!!i)for(const n of i)n(t)}}const Fl=Symbol("NEEDLE_NEED_UPDATE_INSTANCE"),Vb=Symbol("isUsingInstancing"),$b=Symbol("instancingRenderer"),rl=Symbol("instancingAutoUpdateBounds");class Ei{static isUsingInstancing(e){return e[Vb]===!0}static getRenderer(e){return e[$b]||null}setAutoUpdateBounds(e,t){const i=Ei.getRenderer(e);i&&(i[rl]=t)}static markDirty(e,t=!0){if(e&&(this.isUsingInstancing(e)&&(e[Fl]=!0,e.matrixWorldNeedsUpdate=!0),t))for(const i of e.children)Ei.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 Xr(s,e){try{e||s()}catch(t){return console.error(t),!1}return!0}const Jf=x("debugnewscripts"),BS=x("debughierarchy"),ve=[];function FS(){return ve.length>0}function od(s){if(Jf&&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)){ve.length=0,s.new_scripts.length>0&&ve.push(...s.new_scripts),s.new_scripts.length=0;for(let e=0;e<ve.length;e++)try{const t=ve[e];if(t.isComponent!==!0){(A()||Jf)&&console.error(`Registered script is not a Needle Engine component.
|
|
167
167
|
The script will be ignored. Please make sure your component extends "Behaviour" imported from "@needle-tools/engine"
|
|
@@ -946,7 +946,7 @@ ${t.path}! : AssetReference;
|
|
|
946
946
|
Could not find method ${r.method} on object ${l.name}. Please rename ${r.method} to ${p}?
|
|
947
947
|
`,l[p],`
|
|
948
948
|
in script: `,l),he("EventList methods must start with lowercase letter, see console for details");return}else console.warn(`EventList method:
|
|
949
|
-
Could not find method ${r.method} on object ${l.name}`,l,typeof l[r.method])};if(typeof l[r.method]!="function"){let p=!1,m=l;for(;m;){const y=Object.getOwnPropertyDescriptor(m,r.method);if(y&&(y.writable===!0||y.set)){p=!0;break}m=Object.getPrototypeOf(m)}!p&&(A()||st)&&d()}}if(l){let d=r.argument;if(d!==void 0?d=a(d):r.arguments!==void 0&&(d=r.arguments.map(a)),!l[r.method])console.warn(`EventList method not found: "${r.method}" on ${l?.name}`);else{d!==void 0&&!Array.isArray(d)&&(d=[d]);const p=new es(l,r.method,d,r.enabled);i.push(p)}}else A()&&console.warn(`[Dev] EventList: Could not find event listener in scene (${t.object?.name})`,r)}const n=new ae(i);st&&console.log(n);const o=t.target;return o!==void 0&&t.path!==void 0&&n.setEventTarget(t.path,o),n}}}const E1=new R1,pd=new WeakMap,T1=c.Texture.prototype.clone;c.Texture.prototype.clone=function(){const s=T1.call(this);return pd.has(s)||pd.set(s,this),s};class H0 extends Fi{constructor(){super([xn,c.WebGLRenderTarget])}onSerialize(e,t){}onDeserialize(e,t){if(e instanceof c.Texture&&t.type===xn){let i=e;pd.has(i)&&(i=pd.get(i)),i.isRenderTargetTexture=!0,i.flipY=!0,i.offset.y=1,i.repeat.y=-1,i.needsUpdate=!0,i.mipmaps=[],i instanceof c.CompressedTexture&&(i.isCompressedTexture=!1,i.format=c.RGBAFormat);const n=new xn(i.image.width,i.image.height,{colorSpace:c.LinearSRGBColorSpace});return n.texture=i,n}}}new H0;class q0 extends Fi{constructor(){super([URL])}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"&&e.length>0)return Ys(t.gltfId,e)}}new q0;var A1=Object.defineProperty,L1=(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&&A1(e,t,n),n};class la extends k{awake(){Dt.createIfNoneExists(this.context)}onEnable(){Dt.get(this.context)?.register(this)}onDisable(){Dt.get(this.context)?.unregister(this)}}class ci extends la{targets=null;raycastHits=[];ignoreSkinnedMeshes=!1;start(){this.targets=[this.gameObject]}performRaycast(e=null){if(!this.targets)return null;e??=new Js,e.targets=this.targets,e.results=this.raycastHits,e.useAcceleratedRaycast=!0;const t=e.testObject;this.ignoreSkinnedMeshes&&(e.testObject=n=>n instanceof c.SkinnedMesh?"continue in children":t?t(n):!0);const i=this.context.physics.raycast(e);return e.testObject=t,i}}L1([f()],ci.prototype,"ignoreSkinnedMeshes");class qd extends ci{constructor(){super(),this.ignoreSkinnedMeshes=!0}}class Ho extends la{static allow=!0;performRaycast(e){if(!H.active||!Ho.allow||!e?.ray)return null;const t=e.ray.origin;return this.context.physics.sphereOverlap(t,.015,!1,!0)}}class wm{static getObject(e){const t=e[ii];return t&&(t.isComponent===!0?e=t.gameObject:e=t),e}static isInteractable(e,t){if(t&&(t.canvasGroup=void 0,t.graphic=void 0),e==null||!e.visible||(e=this.getObject(e),!e.visible))return!1;const i=this.tryFindCanvasGroup(e);if(i?.isCanvasGroup===!0&&(t&&(t.canvasGroup=i),i.blocksRaycasts===!1||i.interactable===!1))return!1;const n=Wo(e,o=>{if(o.isGraphic===!0)return o},!1);return t&&n?.isGraphic===!0&&(t.graphic=n),!(n?.raycastTarget===!1||n?.layer===2)}static tryFindCanvasGroup(e){if(!e)return null;const t=Wo(e,i=>{const n=i;if(n.blocksRaycasts!==void 0&&n.interactable!==void 0)return n},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}}function Sm(s){const e=s[ii];return e||(s.parent?Sm(s.parent):null)}function D1(s){return s.isUI===!0||typeof s[ii]=="object"}function md(s,e){if(!s)return;const t=s.material;if(t?.isMaterial===!0){const i=s.parent;i&&i.isText,t.side=e.doubleSided??!0?c.DoubleSide:c.FrontSide,t.shadowSide=e.doubleSided?c.DoubleSide:c.FrontSide,s.castShadow=e.castShadows?e.castShadows:!1,s.receiveShadow=e.receiveShadows?e.receiveShadows:!1}for(const i of s.children)md(i,e)}function Lr(s,e,t){s[e]===void 0&&console.warn("Field",e,"is undefined on",s);const i=Proxy.revocable(s[e],{set(r,a,l,h){const d=r[a],u=Reflect.set(r,a,l,h);return t(l,d),u}}),n=i.revoke,o=s[e];return i.revoke=()=>{s[e]=o,n()},s[e]=i.proxy,i}const Qy=Symbol("Scheduled action");function I1(s,e,t=pe.OnBeforeRender){let i=s[Qy];i||(i=s[Qy]={});const n=e.name;i[t]||(i[t]={});const o=i[t];if(o[n])return;function*a(){e?.call(s),o[n]=null}const l=s.startCoroutine(a(),t);o[n]=l}const Ts=x("debugeventsystem");var gp=(s=>(s.BeforeHandleInput="BeforeHandleInput",s.AfterHandleInput="AfterHandleInput",s))(gp||{});I0(s=>{Dt.createIfNoneExists(s)});class Dt extends k{static ensureUpdateMeshUI(e,t,i=!1){za.update(e,t,i)}static markUIDirty(e){za.markDirty()}static createIfNoneExists(e){e.scene.getComponent(Dt)||e.scene.addComponent(Dt)}static get(e){return this.createIfNoneExists(e),e.scene.getComponent(Dt)}static get instance(){return this.get(F.Current)}raycaster=[];register(e){e&&this.raycaster&&!this.raycaster.includes(e)&&this.raycaster?.push(e)}unregister(e){const t=this.raycaster?.indexOf(e);t!==void 0&&t!==-1&&this.raycaster?.splice(t,1)}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.hoveredByID.size>0}awake(){this.gameObject!==this.context.scene&&(console.debug(`[Needle Engine] EventSystem is only allowed on the scene root. Disabling EventSystem on '${this.gameObject.name}'`),this.enabled=!1)}start(){this.context.scene.getComponent(la)||this.context.scene.addComponent(ci)}onEnable(){this.context.input.addEventListener(xe.PointerDown,this.onPointerEvent),this.context.input.addEventListener(xe.PointerUp,this.onPointerEvent),this.context.input.addEventListener(xe.PointerMove,this.onPointerEvent)}onDisable(){this.context.input.removeEventListener(xe.PointerDown,this.onPointerEvent),this.context.input.removeEventListener(xe.PointerUp,this.onPointerEvent),this.context.input.removeEventListener(xe.PointerMove,this.onPointerEvent)}pressedByID=new Map;hoveredByID=new Map;onBeforeRender(){this.resetMeshUIStates()}onPointerEvent=e=>{if(e===void 0||e.propagationStopped||e.defaultPrevented||e.used)return;const t=new fc(this.context.input,e);this._currentPointerEventName=e.type,t.inputSource=this.context.input,t.isClick=e.isClick,t.isDoubleClick=e.isDoubleClick,t.isDown=e.type==xe.PointerDown,t.isUp=e.type==xe.PointerUp,t.isPressed=this.context.input.getPointerPressed(e.pointerId);const i=new Js;e.hasRay?i.ray=e.ray:i.screenPoint=this.context.input.getPointerPositionRC(e.pointerId),i.allowSlowRaycastFallback=e.isClick||e.isDoubleClick;const n=this.performRaycast(i);if(Ts&&(t.isDown?console.log("DOWN",{id:t.pointerId,hits:n.length}):t.isUp&&console.log("UP",{id:t.pointerId,hits:n.length}),t.isClick&&console.log("CLICK",{id:t.pointerId,hits:n.length})),n){for(const r of n)r.event=e,e.intersections.push(r);e.origin.onPointerHits&&e.origin.onPointerHits({sender:this,event:e,hits:n})}Ts&&t.isClick&&Se("EventSystem: "+t.pointerId+" - "+this.context.time.frame+" - Up:"+t.isUp+", Down:"+t.isDown);const o={sender:this,args:t,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:o})),this.handleIntersections(n,t),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:o}))};_sortedHits=[];_testObjectsCache=new Map;_currentlyActiveRaycaster=null;_currentPointerEventName=null;shouldRaycastObject=e=>{const t=e&&"getComponent"in e?e.getComponent(la):null;if(t&&t!=this._currentlyActiveRaycaster)return!1;let i=null;if(D1(e)&&(i=e[ii]?.gameObject),this._testObjectsCache.has(e)||i&&this._testObjectsCache.has(i))return this._testObjectsCache.get(e)===!1?"continue in children":!0;{let o=fd(e,this._currentPointerEventName);if(!o&&i&&(o=fd(i,this._currentPointerEventName)),o){this._testObjectsCache.set(e,!0);for(const r of e.children)this.shouldRaycastObject_AddToYesCache(r);return!0}return this._testObjectsCache.set(e,!1),"continue in children"}};shouldRaycastObject_AddToYesCache(e){this._testObjectsCache.set(e,!0);for(const t of e.children)this.shouldRaycastObject_AddToYesCache(t)}performRaycast(e){if(!this.raycaster)return null;this._testObjectsCache.clear(),this._sortedHits.length=0,e.testObject=this.shouldRaycastObject;for(const t of this.raycaster){if(!t.activeAndEnabled)continue;this._currentlyActiveRaycaster=t;const i=t.performRaycast(e);this._currentlyActiveRaycaster=null,i&&i.length>0&&this._sortedHits.push(...i)}return this._sortedHits.sort((t,i)=>t.distance-i.distance),this._sortedHits}assignHitInformation(e,t){t?(e.intersection=t,e.point=t.point,e.normal=t.normal,e.face=t.face,e.distance=t.distance,e.instanceId=t.instanceId):(e.intersection=void 0,e.point=void 0,e.normal=void 0,e.face=void 0,e.distance=void 0,e.instanceId=void 0)}handleIntersections(e,t){if(e?.length){e=this.sortCandidates(e);for(const n of e){if(t.event.immediatePropagationStopped)return!1;if(this.assignHitInformation(t,n),this.handleEventOnObject(n.object,t))return!0}}this.assignHitInformation(t,e?.[0]),this.invokePointerCapture(t);const i=this.hoveredByID.get(t.pointerId);return i&&this.propagatePointerExit(i.obj,i.data,null),this.hoveredByID.delete(t.pointerId),t.isUp&&(this.pressedByID.get(t.pointerId)?.handlers.forEach(n=>this.invokeOnPointerUp(t,n)),this.pressedByID.delete(t.pointerId)),!1}_sortingBuffer=[];_noDepthTestingResults=[];sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let t=0;t<e.length;t++){const i=e[t],n=i.object;if(n.material&&n.material.depthTest===!1){this._noDepthTestingResults.push(i);continue}this._sortingBuffer.push(i)}for(const t of this._sortingBuffer)this._noDepthTestingResults.push(t);return this._noDepthTestingResults}out={};handleEventOnObject(e,t){if(!this.testIsVisible(e))return t.isClick&&Ts&&console.log("not allowed",e),!1;if(t.pointerId===void 0)return Ts&&console.error("Event without pointer can't be handled",t),!1;t.object=e;const i=e.parent,n=t.isClick??!1;let o=null;if(i&&i.isUI){const d=(t.isPressed||t.isClick)??!1;if(i[ii]){const u=i[ii].gameObject;if(u){if(!wm.isInteractable(u,this.out))return!1;o=this.out.canvasGroup??null,this.handleMeshUIIntersection(e,d),e=u}}}n&&Ts&&console.log(this.context.time.frame,e);const r=this.hoveredByID.get(t.pointerId),a=r?.obj;a!==e&&a&&this.propagatePointerExit(a,r.data,e);const h=this.hoveredByID.get(t.pointerId);if(h?(h.obj=e,h.data=t):this.hoveredByID.set(t.pointerId,{obj:e,data:t}),t.isDown){const d=this.pressedByID.get(t.pointerId);d?(d.obj=e,d.data=t):this.pressedByID.set(t.pointerId,{obj:e,data:t,handlers:new Set})}return(o===null||o.interactable)&&this.handleMainInteraction(e,t,a??null),!0}propagate(e,t){for(;e;)S.foreachComponent(e,i=>{t(i)},!1),e=e.parent}handleMainInteraction(e,t,i){const n=this.pressedByID.get(t.pointerId),o=i!==e;let r=!0;switch(t.event.pointerType){case"mouse":case"touch":const a=this.context.input.getPointerPositionLastFrame(t.pointerId),l=this.context.input.getPointerPosition(t.pointerId);r=a&&!D.approximately(a,l);break}this.propagate(e,a=>{const l=a;l.interactable!==!1&&(!l.activeAndEnabled||!l.enabled||(l.onPointerEnter&&o&&this.handlePointerEnter(l,t),t.isDown&&l.onPointerDown&&(l.onPointerDown(t),n?.handlers.add(l),this.handlePointerCapture(t,l)),l.onPointerMove&&(r&&l.onPointerMove(t),this.handlePointerCapture(t,l)),t.isUp&&(l.onPointerUp&&(this.invokeOnPointerUp(t,l),n?.handlers.delete(l)),l.onPointerExit&&t.event?.pointerType===Id.Touch&&(this.handlePointerExit(l,t),this.hoveredByID.delete(t.pointerId))),t.isClick&&l.onPointerClick&&l.onPointerClick(t)))}),t.isUp&&(n?.handlers.forEach(a=>{this.invokeOnPointerUp(t,a)}),this.pressedByID.delete(t.pointerId))}propagatePointerExit(e,t,i){this.propagate(e,n=>{if(!n.gameObject||n.destroyed)return;const o=n;if(o.onPointerExit||o.onPointerEnter){if(i&&this.isChild(i,n.gameObject))return;this.handlePointerExit(o,t)}})}invokeOnPointerUp(e,t){t.onPointerUp?.call(t,e),this.releasePointerCapture(e,t)}handlePointerEnter(e,t){e.onPointerEnter&&this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!0)&&e.onPointerEnter(t),this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!1)}handlePointerExit(e,t){e.onPointerExit&&this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!0)&&e.onPointerExit(t),this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!1)}updatePointerState(e,t,i,n){let o=e[i];if(n)return o&&o.includes(t)?!1:(o=o||[],o.push(t),e[i]=o,!0);{if(!o||!o.includes(t))return!1;const r=o.indexOf(t);return r!==-1&&o.splice(r,1),!0}}_capturedPointer={};handlePointerCapture(e,t){if(e.z__pointer_ctured){e.z__pointer_ctured=!1;const i=e.pointerId;if(t.onPointerMove){const n=this._capturedPointer[i]||[];n.push(t),this._capturedPointer[i]=n}else A()&&!t.z__warned_no_pointermove&&(t.z__warned_no_pointermove=!0,console.warn("PointerCapture was requested but the component doesn't implement onPointerMove. It will not receive any pointer events"))}else e.z__pointer_cture_rleased&&(e.z__pointer_cture_rleased=!1,this.releasePointerCapture(e,t))}releasePointerCapture(e,t){const i=e.pointerId;if(this._capturedPointer[i]){const n=this._capturedPointer[i].indexOf(t);n!==-1&&(this._capturedPointer[i].splice(n,1),Ts&&console.log("released pointer capture",i,t,this._capturedPointer))}}invokePointerCapture(e){if(e.event.type===xe.PointerMove){const t=e.pointerId,i=this._capturedPointer[t];if(i){Ts&&console.log("Captured",t,i);for(let n=0;n<i.length;n++){const o=i[n];if(o.destroyed){i.splice(n,1),n--;continue}o.onPointerMove?.call(o,e)}}}}pointerEnterSymbol=Symbol("pointerEnter");pointerExitSymbol=Symbol("pointerExit");isChild(e,t){return!e||!t?!1:e===t?!0:e.parent?this.isChild(e.parent,t):!1}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}currentActiveMeshUIComponents=[];handleMeshUIIntersection(e,t){const i=za.updateState(e,t);return i&&this.currentActiveMeshUIComponents.push(i),i!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&za.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){const t=this.currentActiveMeshUIComponents[e];za.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?S.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}}class za{static lastSelected=null;static lastUpdateFrame=[];static needsUpdate=!1;static markDirty(){this.needsUpdate=!0}static update(e,t,i=!1){if(i){e.update();return}const n=t.time.frameCount;for(const o of this.lastUpdateFrame)if(o.context===t){if(n===o.frame)return;o.frame=n;let r=this.needsUpdate||n<1;o.nextUpdate<=n&&(r=!0),r&&(Ts&&console.log("Update threemeshui"),this.needsUpdate=!1,o.nextUpdate=n+60,e.update());return}this.lastUpdateFrame=[{context:t,frame:n,nextUpdate:n+60}],e.update(),this.needsUpdate=!1}static updateState(e,t){let i=null;if(e&&(i=this.findBlockOrTextInParent(e),i&&i!==this.lastSelected)){if(i.interactable===!1)return null;this.needsUpdate=!0}return i}static resetLastSelected(){const e=this.lastSelected;e&&(this.lastSelected=null,this.resetState(e))}static resetState(e){e&&(this.needsUpdate=!0)}static findBlockOrTextInParent(e){return e?e.isBlock||e.isText?e:this.findBlockOrTextInParent(e.parent):null}}var j1=Object.defineProperty,Ce=(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&&j1(e,t,n),n};const wi=x("debugorbit"),sf=x("freecam"),Na=x("debugcamerafit"),dh=x("smoothcam"),B1={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let of;class Vl extends CustomEvent{constructor(e,t){super("target-reached",{detail:{controls:e,type:t}})}}class de extends k{get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){this.controls?.addEventListener("start",e)}autoTarget=!0;autoFit=!1;enableRotate=!0;autoRotate=!1;autoRotateSpeed=1;minAzimuthAngle=1/0;maxAzimuthAngle=1/0;minPolarAngle=0;maxPolarAngle=Math.PI;enableKeys=!1;enableDamping=!0;dampingFactor=.1;enableZoom=!0;minZoom=0;maxZoom=1/0;zoomSpeed=1;zoomToCursor=!1;enablePan=!0;lookAtConstraint=null;lookAtConstraint01=1;allowInterrupt=!0;middleClickToFocus=!0;doubleClickToFocus=!0;clickBackgroundToFitScene=2;get targetElement(){return this._controls?.domElement??this._targetElement}set targetElement(e){this._targetElement=e,this._controls&&this._controls.domElement!==e&&(this._controls.disconnect(),this._controls.domElement=e,this._controls.connect())}_targetElement=null;debugLog=!1;get targetLerpSpeed(){return 5}set targetLerpSpeed(e){this.targetLerpDuration=1/e}targetLerpDuration=1;rotateLeft(e){this._controls?._rotateLeft(e)}rotateUp(e){this._controls?._rotateUp(e)}pan(e,t){this._controls?._pan(e,t)}zoomIn(e){e>0?this._controls?._dollyIn(1-e):e<0&&this._controls?._dollyOut(1+e)}_controls=null;_cameraObject=null;_lookTargetLerpActive=!1;_lookTargetStartPosition=new c.Vector3;_lookTargetEndPosition=new c.Vector3;_lookTargetLerp01=0;_lookTargetLerpDuration=0;_cameraLerpActive=!1;_cameraStartPosition=new c.Vector3;_cameraEndPosition=new c.Vector3;_cameraLerp01=0;_cameraLerpDuration=0;_fovLerpActive=!1;_fovLerpStartValue=0;_fovLerpEndValue=0;_fovLerp01=0;_fovLerpDuration=0;_inputs=0;_enableTime=0;_startedListeningToKeyEvents=!1;_eventSystem;_afterHandleInputFn;_camera=null;_syncedTransform;_didSetTarget=0;awake(){wi&&console.debug("OrbitControls",this),this._didSetTarget=0,this._startedListeningToKeyEvents=!1}start(){this._eventSystem=Dt.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(gp.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){this._controls?.dispose(),this._eventSystem?.removeEventListener(gp.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._didSetTarget=0,this._enableTime=this.context.time.time;const e=S.getComponent(this.gameObject,Vt);this._camera=e;let t=e?.threeCamera;if(!t&&this.gameObject instanceof c.PerspectiveCamera&&(t=this.gameObject),t&&Gf(t,this,!0),!this._controls&&t instanceof c.Object3D){this._cameraObject=t;const i=this.targetElement??this.context.renderer.domElement,n=t?.quaternion.clone();this._controls=new q.OrbitControls(t,i),t?.quaternion.copy(n),of===void 0&&(of={...this._controls.keys});const o=X(t),r=this.gameObject.worldForward,l=o.clone().sub(r.multiplyScalar(2.5));this._controls.target.copy(l)}if(this._controls)if(sf&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,exports.DeviceUtilities.isMobileDevice()&&(this.doubleClickToFocus=!0)),this._controls.addEventListener("start",this.onControlsChangeStarted),this._controls.addEventListener("endMovement",this.onControlsChangeEnded),!this._startedListeningToKeyEvents&&this.enableKeys)this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(this.context.domElement);else try{this._controls.stopListenToKeyEvents()}catch{}this._syncedTransform=S.getComponent(this.gameObject,tn)??void 0,this.context.pre_render_callbacks.push(this.__onPreRender),this._activePointerEvents=[],this.context.input.addEventListener("pointerdown",this._onPointerDown,{queue:Nt.Early}),this.context.input.addEventListener("pointerdown",this._onPointerDownLate,{queue:Nt.Late}),this.context.input.addEventListener("pointerup",this._onPointerUp,{queue:Nt.Early}),this.context.input.addEventListener("pointerup",this._onPointerUpLate,{queue:Nt.Late})}onDisable(){if(this._camera?.threeCamera&&Gf(this._camera.threeCamera,this,!1),this._controls){this._controls.enabled=!1,this._controls.autoRotate=!1,this._controls.removeEventListener("start",this.onControlsChangeStarted),this._controls.removeEventListener("endMovement",this.onControlsChangeEnded);try{this._controls.stopListenToKeyEvents()}catch{}this._startedListeningToKeyEvents=!1}this._activePointerEvents.length=0,this.context.input.removeEventListener("pointerdown",this._onPointerDown),this.context.input.removeEventListener("pointerdown",this._onPointerDownLate),this.context.input.removeEventListener("pointerup",this._onPointerUp),this.context.input.removeEventListener("pointerup",this._onPointerUpLate)}_activePointerEvents;_lastTimeClickOnBackground=-1;_clickOnBackgroundCount=0;_onPointerDown=e=>{this._activePointerEvents.push(e)};_onPointerDownLate=e=>{e.used&&this._controls&&(this._controls.enabled=!1)};_onPointerUp=e=>{for(let t=this._activePointerEvents.length-1;t>=0;t--){const i=this._activePointerEvents[t];if(i.pointerId===e.pointerId&&i.button===e.button){this._activePointerEvents.splice(t,1);break}}if(this.clickBackgroundToFitScene>0&&e.isClick&&e.button===0){if(e.hasRay||e.intersections.push(...this.context.physics.raycast()),e.intersections.length<=0){const t=this.context.time.time-this._lastTimeClickOnBackground;this._lastTimeClickOnBackground=this.context.time.time,this.clickBackgroundToFitScene<=1||t<this.clickBackgroundToFitScene*.15?(this._clickOnBackgroundCount+=1,this._clickOnBackgroundCount>=this.clickBackgroundToFitScene-1&&this.fitCamera(this.context.scene.children,{immediate:!1})):this._clickOnBackgroundCount=0}wi&&console.log(this.clickBackgroundToFitScene,e.intersections.length,this._clickOnBackgroundCount)}};_onPointerUpLate=e=>{this.doubleClickToFocus&&e.isDoubleClick&&!e.used&&this.setTargetFromRaycast()};updateTargetNow(e){const t=new c.Ray(this._cameraObject?.worldPosition,this._cameraObject?.worldForward.multiplyScalar(-1)),i=this.context.physics.raycastFromRay(t,e),n=i.length>0?i[0]:void 0;n&&n.distance>this.minZoom&&n.distance<this.maxZoom&&(wi&&B.DrawWireSphere(n.point,.1,16711680,2),this._controls?.target.copy(i[0].point))}_orbitStartAngle=0;_zoomStartDistance=0;onControlsChangeStarted=()=>{this._controls&&(this._orbitStartAngle=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle(),this._zoomStartDistance=this._controls.getDistance()),this._syncedTransform&&this._syncedTransform.requestOwnership()};onControlsChangeEnded=()=>{if(this._controls&&this.autoTarget){const t=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle()-this._orbitStartAngle;Math.abs(t)<.01?(wi&&console.debug("OrbitControls: Update target",{deltaAngle:t}),this.updateTargetNow({allowSlowRaycastFallback:!1})):wi&&console.debug("OrbitControls: No target update",{deltaAngle:t})}};_shouldDisable=!1;afterHandleInput(e){e.detail.args.pointerId===0&&(e.detail.args.isDown?this._controls&&this._eventSystem&&(this._shouldDisable=this._eventSystem.hasActiveUI):(!e.detail.args.isPressed||e.detail.args.isUp)&&(this._shouldDisable=!1))}onPausedChanged(e){this._controls&&e&&(this._controls.enabled=!1)}onBeforeRender(){if(!this._controls)return;if(this._cameraObject!==this.context.mainCamera){this._controls.enabled=!1;return}if(this._controls.enabled=!0,(this.context.input.getPointerDown(1)||this.context.input.getPointerDown(2)||this.context.input.mouseWheelChanged||this.context.input.getPointerPressed(0)&&this.context.input.getPointerPositionDelta(0)?.length())&&(this._inputs+=1),this._inputs>0&&this.allowInterrupt&&(this.enableRotate&&(this.autoRotate=!1),this._cameraLerpActive=!1,this._lookTargetLerpActive=!1),this._inputs=0,this.autoTarget&&this._didSetTarget++===0){const t=S.getComponent(this.gameObject,Vt);if(t&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log("NO TARGET");const i=X(t.threeCamera),n=Math.max(.01,i.length()),o=new c.Vector3(0,0,-n).applyMatrix4(t.threeCamera.matrixWorld);wi&&B.DrawLine(i,o,5592575,10),this.setLookTargetPosition(o,!0)}if(!this.setLookTargetFromConstraint()){const i=new Js;i.screenPoint=new c.Vector2(0,0),i.lineThreshold=.1;const n=this.context.physics.raycast(i);n.length>0&&this.setLookTargetPosition(n[0].point,!0),Na&&console.log("OrbitControls hits",...n)}}if(this.middleClickToFocus&&this.context.input.getPointerClicked(1)&&this.setTargetFromRaycast(),this._lookTargetLerpActive||this._cameraLerpActive||this._fovLerpActive){if(this._cameraLerpActive&&this._cameraObject)if(this._cameraLerp01+=this.context.time.deltaTime/this._cameraLerpDuration,this._cameraLerp01>=1)this._cameraObject.position.copy(this._cameraEndPosition),this._cameraLerpActive=!1,this.dispatchEvent(new Vl(this,"camera"));else{const t=D.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,t)}if(this._lookTargetLerpActive)if(this._lookTargetLerp01+=this.context.time.deltaTime/this._lookTargetLerpDuration,this._lookTargetLerp01>=1)this.lerpLookTarget(this._lookTargetEndPosition,this._lookTargetEndPosition,1),this._lookTargetLerpActive=!1,this.dispatchEvent(new Vl(this,"lookat"));else{const t=D.easeInOutCubic(this._lookTargetLerp01);this.lerpLookTarget(this._lookTargetStartPosition,this._lookTargetEndPosition,t)}if(this._fovLerpActive&&this._cameraObject){const t=this._cameraObject;if(this._fovLerp01+=this.context.time.deltaTime/this._fovLerpDuration,this._fovLerp01>=1)t.fov=this._fovLerpEndValue,this._fovLerpActive=!1;else{const i=D.easeInOutCubic(this._fovLerp01);t.fov=D.lerp(this._fovLerpStartValue,this._fovLerpEndValue,i)}t.updateProjectionMatrix()}}if(this._controls){if(this.debugLog&&(this._controls.domElement=this.context.renderer.domElement),this._controls.enabled=!this._shouldDisable&&this._camera===this.context.mainCameraComponent&&!this.context.isInXR&&!this._activePointerEvents.some(t=>t.used),this._controls.keys=this.enableKeys?of:B1,this._controls.autoRotate=this.autoRotate,this._controls.autoRotateSpeed=this.autoRotateSpeed,this._controls.enableZoom=this.enableZoom,this._controls.zoomSpeed=this.zoomSpeed,this._controls.zoomToCursor=this.zoomToCursor,this._controls.enableDamping=this.enableDamping,this._controls.dampingFactor=this.dampingFactor,this._controls.enablePan=this.enablePan,this._controls.enableRotate=this.enableRotate,this._controls.minAzimuthAngle=this.minAzimuthAngle,this._controls.maxAzimuthAngle=this.maxAzimuthAngle,this._controls.minPolarAngle=this.minPolarAngle,this._controls.maxPolarAngle=this.maxPolarAngle,sf||(this._camera?.threeCamera?.type==="PerspectiveCamera"?(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom,this._controls.minZoom=0,this._controls.maxZoom=1/0):(this._controls.minDistance=0,this._controls.maxDistance=1/0,this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom)),typeof dh=="number"||dh===!0){this._controls.enableDamping=!0;const t=typeof dh=="number"?dh:.99;this._controls.dampingFactor=Math.max(.001,1-Math.min(1,t))}this.allowInterrupt||(this._lookTargetLerpActive&&(this._controls.enablePan=!1),this._cameraLerpActive&&(this._controls.enableRotate=!1,this._controls.autoRotate=!1),(this._lookTargetLerpActive||this._cameraLerpActive)&&(this._controls.enableZoom=!1)),this.context.isInXR||(!sf&&this.lookAtConstraint?.locked&&!this._lookTargetLerpActive&&this.setLookTargetFromConstraint(0,this.lookAtConstraint01),this._controls.update(this.context.time.deltaTime),wi&&B.DrawWireSphere(this._controls.target,.1,65280))}}__onPreRender=()=>{const e=this.context.pre_render_callbacks.indexOf(this.__onPreRender);e>=0&&this.context.pre_render_callbacks.splice(e,1),this.autoFit&&(this.autoFit=!1,this.fitCamera({centerCamera:"y",immediate:!0,objects:this.scene.children}))};setCameraAndLookTarget(e,t=!1){if(!e)return(A()||wi)&&console.warn("[OrbitControls] setCameraAndLookTarget target is null"),!1;if(!(e instanceof c.Object3D)&&!(e instanceof Vt))return(A()||wi)&&console.warn("[OrbitControls] setCameraAndLookTarget target is not an Object3D or Camera"),!1;e instanceof Vt&&(e=e.gameObject);const i=e.worldPosition,n=e.worldForward;e instanceof c.Camera&&(wi&&console.debug("[OrbitControls] setCameraAndLookTarget flip forward direction for camera"),n.multiplyScalar(-1));const o=new c.Ray(i,n);return wi&&B.DrawRay(o.origin,o.direction,16711680,10),this.setTargetFromRaycast(o,t)||this.setLookTargetPosition(o.at(2,V()),t),this.setCameraTargetPosition(i,t),!0}setCameraTargetPosition(e,t=!1){e&&(e instanceof c.Object3D&&(e=X(e)),this._cameraEndPosition||(this._cameraEndPosition=new c.Vector3),this._cameraEndPosition.copy(e),t===!0?(this._cameraLerpActive=!1,this._cameraObject&&this._cameraObject.position.copy(this._cameraEndPosition)):this._cameraObject&&(this._cameraLerpActive=!0,this._cameraLerp01=0,this._cameraStartPosition.copy(this._cameraObject?.position),typeof t=="number"?this._cameraLerpDuration=t:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setFieldOfView(e,t=!1){if(!this._controls||typeof e!="number")return;const i=this._camera?.threeCamera;i&&(t===!0?i.fov=e:(this._fovLerpActive=!0,this._fovLerp01=0,this._fovLerpStartValue=i.fov,this._fovLerpEndValue=e,typeof t=="number"?this._fovLerpDuration=t:this._fovLerpDuration=this.targetLerpDuration))}setLookTargetPosition(e=null,t=!1){this._controls&&e&&(e instanceof c.Object3D&&(e=X(e)),this._lookTargetEndPosition.copy(e),this._didSetTarget++,wi&&(console.warn("OrbitControls: setLookTargetPosition",e,t),B.DrawWireSphere(this._lookTargetEndPosition,.2,16711680,2)),t===!0?this.lerpLookTarget(this._lookTargetEndPosition,this._lookTargetEndPosition,1):(this._lookTargetLerpActive=!0,this._lookTargetLerp01=0,this._lookTargetStartPosition.copy(this._controls.target),typeof t=="number"?this._lookTargetLerpDuration=t:this._lookTargetLerpDuration=this.targetLerpDuration))}get lookTargetLerpActive(){return this._lookTargetLerpActive}stopLookTargetLerp(){this._lookTargetLerpActive=!1}setLookTargetFromConstraint(e=0,t=1){if(!this._controls||this.lookAtConstraint?.enabled===!1)return!1;const i=this.lookAtConstraint?.sources;if(i&&i.length>0){const n=i[e];if(n)return n.getWorldPosition(this._lookTargetEndPosition),this.lerpLookTarget(this._controls.target,this._lookTargetEndPosition,t),!0}return!1}lerpLookTarget(e,t,i){this._controls&&(i>=1?this._controls.target.copy(t):this._controls.target.lerpVectors(e,t,i),this.lookAtConstraint&&this.lookAtConstraint.setConstraintPosition(this._controls.target))}setTargetFromRaycast(e,t=!1){if(!this.controls)return!1;const i=e?this.context.physics.raycastFromRay(e):this.context.physics.raycast();for(const n of i)if(n.distance>0&&S.isActiveInHierarchy(n.object)){const o=Sm(n.object);if(o&&o.canvas?.screenspace)break;return this.setLookTargetPosition(n.point,t),!0}return!1}fitCamera(e,t){if(this.context.isInXR){console.warn("[OrbitControls] Can not fit camera while XR session is active");return}let i;if(Array.isArray(e)?i=e:e&&"type"in e?i=e.children:e&&typeof e=="object"&&!(e instanceof c.Object3D)&&!Array.isArray(e)&&(t=e,i=t.objects),i&&!Array.isArray(i)&&(i=i.children),(!Array.isArray(i)||i&&i.length<=0)&&(i=this.context.scene.children),!Array.isArray(i)||i.length<=0){console.warn("No objects to fit camera to...");return}const n=this._cameraObject,o=this._controls;if(!n||!o){console.warn("No camera or controls found to fit camera to objects...");return}t||(t={});const{immediate:r=!1,centerCamera:a,cameraNearFar:l="auto",fitOffset:h=1.1,fov:d=n?.fov}=t,u=new c.Vector3,p=new c.Vector3,m=Wt(i,void 0,this._camera?.threeCamera?.layers),y=m.clone();m.getCenter(p);const b=new c.Vector3;if(m.getSize(b),n.updateMatrixWorld(),m.applyMatrix4(n.matrixWorldInverse),m.getSize(u),m.setFromCenterAndSize(p,u),Number.isNaN(u.x)||Number.isNaN(u.y)||Number.isNaN(u.z)){console.warn("Camera fit size resultet in NaN",n,m,[...i]);return}if(u.length()<=1e-10){Na&&console.warn("Camera fit size is zero",m,[...i]);return}const g=d,v=2*Math.atan(Math.tan(g*Math.PI/360/2)*n.aspect)/Math.PI*360,_=u.y/(2*Math.atan(Math.PI*g/360)),w=u.x/(2*Math.atan(Math.PI*v/360)),T=h*Math.max(_,w)+u.z/2;Na&&console.log("Fit camera to objects",{fitHeightDistance:_,fitWidthDistance:w,distance:T,verticalFov:g,horizontalFov:v}),this.maxZoom=T*10,this.minZoom=T*.01;const O=.05,M=p.clone();if(M.y-=u.y*O,t.targetOffset&&(t.targetOffset.x!==void 0&&(M.x+=t.targetOffset.x),t.targetOffset.y!==void 0&&(M.y+=t.targetOffset.y),t.targetOffset.z!==void 0&&(M.z+=t.targetOffset.z)),t.relativeTargetOffset&&(t.relativeTargetOffset.x!==void 0&&(M.x+=t.relativeTargetOffset.x*u.x),t.relativeTargetOffset.y!==void 0&&(M.y+=t.relativeTargetOffset.y*u.y),t.relativeTargetOffset.z!==void 0&&(M.z+=t.relativeTargetOffset.z*u.z)),this.setLookTargetPosition(M,r),this.setFieldOfView(t.fov,r),l==null||l=="auto"){const z=S.findObjectOfType(An),$=z?z.radius:0,E=Math.max(b.x,b.y,b.z,$);n.near=T/100,n.far=E+T*10,n.updateProjectionMatrix(),z&&(this.maxZoom=Math.max(Math.min(this.maxZoom,$*.5),T))}const R=o.getDistance();R<this.minZoom&&(this.minZoom=R*.9),R>this.maxZoom&&(this.maxZoom=R*1.1);const j=p.clone();t.fitDirection?j.sub(new c.Vector3().copy(t.fitDirection).multiplyScalar(1e6)):j.sub(n.worldPosition),a==="y"&&(j.y=0),j.normalize(),j.multiplyScalar(T),a==="y"&&(j.y+=-O*4*T);let L=p.clone().sub(j);t.cameraOffset&&(t.cameraOffset.x!==void 0&&(L.x+=t.cameraOffset.x),t.cameraOffset.y!==void 0&&(L.y+=t.cameraOffset.y),t.cameraOffset.z!==void 0&&(L.z+=t.cameraOffset.z)),t.relativeCameraOffset&&(t.relativeCameraOffset.x!==void 0&&(L.x+=t.relativeCameraOffset.x*u.x),t.relativeCameraOffset.y!==void 0&&(L.y+=t.relativeCameraOffset.y*u.y),t.relativeCameraOffset.z!==void 0&&(L.z+=t.relativeCameraOffset.z*u.z)),n.parent&&(L=n.parent.worldToLocal(L)),this.setCameraTargetPosition(L,r),(Na||t.debug)&&(B.DrawWireBox3(m,16777011,10),B.DrawWireBox3(y,65280,10),!this._haveAttachedKeyboardEvents&&Na&&(this._haveAttachedKeyboardEvents=!0,document.body.addEventListener("keydown",z=>{if(z.code==="KeyF"){let $;this._cameraObject instanceof c.PerspectiveCamera&&($=Math.random()*Math.random()*170+10),this.fitCamera({objects:i,fitOffset:h,immediate:!1,fov:$})}z.code==="KeyV"&&this._cameraObject instanceof c.PerspectiveCamera&&(this._cameraObject.fov=60)}))),this.onBeforeRender()}_haveAttachedKeyboardEvents=!1}Ce([f()],de.prototype,"autoTarget");Ce([f()],de.prototype,"autoFit");Ce([f()],de.prototype,"enableRotate");Ce([f()],de.prototype,"autoRotate");Ce([f()],de.prototype,"autoRotateSpeed");Ce([f()],de.prototype,"minAzimuthAngle");Ce([f()],de.prototype,"maxAzimuthAngle");Ce([f()],de.prototype,"minPolarAngle");Ce([f()],de.prototype,"maxPolarAngle");Ce([f()],de.prototype,"enableKeys");Ce([f()],de.prototype,"enableDamping");Ce([f()],de.prototype,"dampingFactor");Ce([f()],de.prototype,"enableZoom");Ce([f()],de.prototype,"minZoom");Ce([f()],de.prototype,"maxZoom");Ce([f()],de.prototype,"zoomSpeed");Ce([f()],de.prototype,"enablePan");Ce([f(nr)],de.prototype,"lookAtConstraint");Ce([f()],de.prototype,"lookAtConstraint01");Ce([f()],de.prototype,"allowInterrupt");Ce([f()],de.prototype,"middleClickToFocus");Ce([f()],de.prototype,"doubleClickToFocus");Ce([f()],de.prototype,"clickBackgroundToFitScene");Ce([f()],de.prototype,"targetLerpDuration");var F1=Object.defineProperty,U1=Object.getOwnPropertyDescriptor,It=(s,e,t,i)=>{for(var n=i>1?void 0:i?U1(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&&F1(e,t,n),n},Fo=(s=>(s[s.None=0]="None",s[s.Skybox=1]="Skybox",s[s.SolidColor=2]="SolidColor",s[s.Uninitialized=4]="Uninitialized",s))(Fo||{});const As=x("debugcam"),Yy=x("debugscreenpointtoray"),xt=class ll extends k{get isCamera(){return!0}get aspect(){return this._cam instanceof c.PerspectiveCamera?this._cam.aspect:this.context.domWidth/this.context.domHeight}set aspect(e){this._cam instanceof c.PerspectiveCamera&&this._cam.aspect!==e&&(this._cam.aspect=e,this._cam.updateProjectionMatrix())}get fieldOfView(){return this._cam instanceof c.PerspectiveCamera?this._cam.fov:this._fov}set fieldOfView(e){const t=this.fieldOfView!=e;if(this._fov=e,t&&this._cam&&this._cam instanceof c.PerspectiveCamera){if(this._fov===void 0){console.warn("Can not set undefined fov on PerspectiveCamera");return}this._cam.fov=this._fov,this._cam.updateProjectionMatrix()}}get nearClipPlane(){return this._nearClipPlane}set nearClipPlane(e){const t=this._nearClipPlane!=e;this._nearClipPlane=e,this._cam&&(t||this._cam.near!=e)&&(this._cam.near=e,this._cam.updateProjectionMatrix())}_nearClipPlane=.1;get farClipPlane(){return this._farClipPlane}set farClipPlane(e){const t=this._farClipPlane!=e;this._farClipPlane=e,this._cam&&(t||this._cam.far!=e)&&(this._cam.far=e,this._cam.updateProjectionMatrix())}_farClipPlane=1e3;applyClippingPlane(){this._cam&&(this._cam.near=this._nearClipPlane,this._cam.far=this._farClipPlane,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(e){if(typeof e=="string")switch(e){case"skybox":e=1;break;case"solidcolor":e=2;break;default:e=0;break}e!==this._clearFlags&&(this._clearFlags=e,this.applyClearFlagsIfIsActiveCamera())}orthographic=!1;orthographicSize=5;ARBackgroundAlpha=0;set cullingMask(e){this._cullingMask=e,this._cam&&(this._cam.layers.mask=e)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}_cullingMask=4294967295;set cullingLayer(e){this.cullingMask=(1<<e|0)>>>0}set backgroundBlurriness(e){e!==this._backgroundBlurriness&&(e===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(e,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}_backgroundBlurriness=void 0;set backgroundIntensity(e){e!==this._backgroundIntensity&&(e===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(e,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}_backgroundIntensity=void 0;set backgroundRotation(e){e!==this._backgroundRotation&&(e===void 0?this._backgroundRotation=void 0:this._backgroundRotation=e,this.applyClearFlagsIfIsActiveCamera())}get backgroundRotation(){return this._backgroundRotation}_backgroundRotation=void 0;set environmentIntensity(e){this._environmentIntensity=e}get environmentIntensity(){return this._environmentIntensity}_environmentIntensity=void 0;get backgroundColor(){return this._backgroundColor??null}set backgroundColor(e){e&&(this._backgroundColor||(this._backgroundColor=new Z(1,1,1,1)),this._backgroundColor.copy(e),(!("alpha"in e)||e.alpha===void 0)&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera())}set targetTexture(e){this._targetTexture=e}get targetTexture(){return this._targetTexture}_targetTexture=null;_backgroundColor;_fov;_cam=null;_clearFlags=2;_skybox;get cam(){return this.threeCamera}get threeCamera(){return this.activeAndEnabled&&this.buildCamera(),this._cam}static _origin=new c.Vector3;static _direction=new c.Vector3;screenPointToRay(e,t,i){const n=this.threeCamera,o=ll._origin;o.set(e,t,-1),this.context.input.convertScreenspaceToRaycastSpace(o),Yy&&console.log("screenPointToRay",e.toFixed(2),t.toFixed(2),"now:",o.x.toFixed(2),o.y.toFixed(2),"isInXR:"+this.context.isInXR),o.z=-1,o.unproject(n);const r=ll._direction.set(o.x,o.y,o.z),a=X(n);return r.sub(a),r.normalize(),i?(i.set(a,r),i):new c.Ray(a.clone(),r.clone())}_frustum;getFrustum(){return this._frustum||(this._frustum=new c.Frustum,this.updateFrustum()),this._frustum}updateFrustum(){this._frustum||(this._frustum=new c.Frustum),this._frustum.setFromProjectionMatrix(this.getProjectionScreenMatrix(this._projScreenMatrix,!0),this.context.renderer.coordinateSystem)}getProjectionScreenMatrix(e,t){return t&&this._projScreenMatrix.multiplyMatrices(this.threeCamera.projectionMatrix,this.threeCamera.matrixWorldInverse),e===this._projScreenMatrix?e:e.copy(this._projScreenMatrix)}_projScreenMatrix=new c.Matrix4;awake(){Yy&&window.addEventListener("pointerdown",e=>{const t=e.clientX,i=e.clientY;console.log("touch",t.toFixed(2),i.toFixed(2));const n=this.screenPointToRay(t,i),o="#"+Math.floor(Math.random()*16777215).toString(16);B.DrawRay(n.origin,n.direction,o,10)})}onEnable(){As&&console.log(`Camera enabled: "${this.name}". ClearFlags=${Fo[this._clearFlags]}`,this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),N1(this)),this.applyClearFlagsIfIsActiveCamera({applySkybox:!0})}onDisable(){this.context.removeCamera(this)}onLeaveXR(e){this.fieldOfView=this._fov}onBeforeRender(){if(this._cam&&(this._frustum&&this.updateFrustum(),this._clearFlags===2&&this.applyClearFlagsIfIsActiveCamera(),this._targetTexture)){this.context.isManagedExternally&&(this._warnedAboutExternalRenderer||(this._warnedAboutExternalRenderer=!0,console.warn("Rendering with external renderer is not supported yet. This may not work or throw errors. Please remove the the target texture from your camera: "+this.name,this.targetTexture))),this.context.composer;const e=this.context.renderer;if(e){const t=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,e),t?.applyClearFlags()}}}buildCamera(){if(this._cam)return;const e=this.gameObject.isCamera;let t=null;if(e?(t=this.gameObject,t?.layers.enableAll(),t instanceof c.PerspectiveCamera&&(this._fov=t.fov)):t=this.gameObject.children[0],t&&t.isCamera)t instanceof c.PerspectiveCamera&&(this._fov&&(t.fov=this._fov),t.near=this._nearClipPlane,t.far=this._farClipPlane,t.updateProjectionMatrix());else if(!this.orthographic)t=new c.PerspectiveCamera(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(t.fov=this.fieldOfView),this.gameObject.add(t);else{const i=this.orthographicSize*100;t=new c.OrthographicCamera(window.innerWidth/-i,window.innerWidth/i,window.innerHeight/i,window.innerHeight/-i,this._nearClipPlane,this._farClipPlane),this.gameObject.add(t)}this._cam=t,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(e){this.context.mainCameraComponent===this&&this.applyClearFlags(e)}applyClearFlags(e){if(!this._cam){As&&console.log("Camera does not exist (apply clear flags)");return}if(this.fieldOfView=this.fieldOfView,As){const i=`[Camera] Apply ClearFlags: ${Fo[this._clearFlags]} - "${this.name}"`;console.debug(i)}const t=this.context.domElement.getAttribute("background-image")||this.context.domElement.getAttribute("background-color");switch(this._clearFlags){case 0:return;case 1:if(ll.backgroundShouldBeTransparent(this.context)&&(!this.ARBackgroundAlpha||this.ARBackgroundAlpha<.001)){this.context.scene.background=null,this.context.renderer.setClearColor(0,0);return}(!this.scene.background||!this._skybox||e?.applySkybox===!0)&&this.applySceneSkybox(),this._backgroundBlurriness!==void 0&&!this.context.domElement.getAttribute("background-blurriness")?this.context.scene.backgroundBlurriness=this._backgroundBlurriness:As&&console.warn(`Camera "${this.name}" has no background blurriness`),this._backgroundIntensity!==void 0&&!this.context.domElement.getAttribute("background-intensity")&&(this.context.scene.backgroundIntensity=this._backgroundIntensity),this._backgroundRotation!==void 0&&!this.context.domElement.getAttribute("background-rotation")?this.context.scene.backgroundRotation=this._backgroundRotation:As&&console.warn(`Camera "${this.name}" has no background intensity`);break;case 2:if(this._backgroundColor&&!t){let i=this._backgroundColor.alpha;ll.backgroundShouldBeTransparent(this.context)&&(i=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.xr?.isVR?this.context.renderer.setClearColor(rb(this._backgroundColor).convertLinearToSRGB()):this.context.renderer.setClearColor(this._backgroundColor,i)}else this._backgroundColor||As&&console.warn(`[Camera] has no background color "${this.name}" `);break;case 4:t||(this.context.scene.background=null,this.context.renderer.setClearColor(0,0));break}}applySceneSkybox(){this._skybox||(this._skybox=new z1(this)),this._skybox.apply()}static backgroundShouldBeTransparent(e){const t=e.renderer.xr?.getSession();if(!t)return!1;if(typeof t._transparent=="boolean")return t._transparent;const i=t.environmentBlendMode;As&&Se("Environment blend mode: "+i+" on "+navigator.userAgent);let n=i==="additive"||i==="alpha-blend";return e.isInAR&&i==="opaque"&&(navigator.userAgent?.includes("OculusBrowser")||navigator.userAgent?.includes("Mozilla")&&navigator.userAgent?.includes("Mobile WebXRViewer/v2"))&&(n=!0),t._transparent=n,n}};It([f()],xt.prototype,"aspect",1);It([f()],xt.prototype,"fieldOfView",1);It([f()],xt.prototype,"nearClipPlane",1);It([f()],xt.prototype,"farClipPlane",1);It([f()],xt.prototype,"clearFlags",1);It([f()],xt.prototype,"orthographic",2);It([f()],xt.prototype,"orthographicSize",2);It([f()],xt.prototype,"ARBackgroundAlpha",2);It([f()],xt.prototype,"cullingMask",1);It([f()],xt.prototype,"backgroundBlurriness",1);It([f()],xt.prototype,"backgroundIntensity",1);It([f(c.Euler)],xt.prototype,"backgroundRotation",1);It([f()],xt.prototype,"environmentIntensity",1);It([f(Z)],xt.prototype,"backgroundColor",1);It([f(xn)],xt.prototype,"targetTexture",1);let Vt=xt;class z1{_camera;_skybox;get context(){return this._camera?.context}constructor(e){this._camera=e}apply(){if(this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),!this._skybox)this._did_log_failed_to_find_skybox||(this._did_log_failed_to_find_skybox=!0,console.warn(`Camera "${this._camera.name}" has no skybox texture. ${this._camera.sourceId}`));else if(this.context.scene.background!==this._skybox){const e=this.context.domElement.getAttribute("background-image")||this.context.domElement.getAttribute("background-color");As&&console.debug(`[Camera] Apply Skybox ${this._skybox?.name} ${e} - "${this._camera.name}"`),e?.length||(this._skybox.mapping=c.EquirectangularReflectionMapping,this.context.scene.background=this._skybox)}}}function N1(s){x("freecam")&&s.context.mainCameraComponent===s&&S.getOrAddComponent(s.gameObject,de)}class ts extends k{get listener(){return this._listener==null&&(this._listener=new c.AudioListener),this._listener}_listener=null;onEnable(){en.registerWaitForInteraction(this.onInteraction),this.addListenerIfItExists()}onDisable(){en.unregisterWaitForInteraction(this.onInteraction),this.removeListenerIfItExists()}onInteraction=()=>{this.destroyed||this.listener==null||this.addListenerIfItExists()};addListenerIfItExists(){const e=this._listener;if(!e||e?.parent)return;const t=this.context.mainCameraComponent||S.getComponentInParent(this.gameObject,Vt);t?.threeCamera?t.threeCamera.add(e):this.gameObject.add(e),e.filter?(e.gain.connect(e.filter),e.filter.connect(e.context.destination)):e.gain.connect(e.context.destination)}removeListenerIfItExists(){const e=this._listener;e&&(e.removeFromParent(),e.filter&&e.filter.disconnect(),e.gain&&e.gain.disconnect())}}var V1=Object.defineProperty,$1=Object.getOwnPropertyDescriptor,on=(s,e,t,i)=>{for(var n=i>1?void 0:i?$1(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&&V1(e,t,n),n};const lt=x("debugaudio"),Ui=class Ls extends k{static get userInteractionRegistered(){return en.userInteractionRegistered}static registerWaitForAllowAudio(e){en.registerWaitForInteraction(e)}clip="";playOnAwake=!1;preload=!0;playInBackground=!0;get isPlaying(){return this.sound?.isPlaying??!1}get duration(){return this.sound?.buffer?.duration}get time01(){const e=this.duration;return e&&this.sound?this.sound?.context.currentTime/e:0}set time01(e){const t=this.duration;t&&this.sound&&(this.time=e*t)}get time(){return this.sound?.source?this.sound.source?.context.currentTime-this._lastContextTime+this.sound.offset:0}set time(e){if(this.sound){if(e===this.sound.offset)return;const t=this.isPlaying;this.stop(),this.sound.offset=e,t&&this.play()}}get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(e){this._loop=e,this.sound&&this.sound.setLoop(e)}get spatialBlend(){return this._spatialBlend}set spatialBlend(e){e!==this._spatialBlend&&(this._spatialBlend=e,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(e){this._minDistance!==e&&(this._minDistance=e,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(e){this._maxDistance!==e&&(this._maxDistance=e,this._needUpdateSpatialDistanceSettings=!0)}_spatialBlend=0;_minDistance=1;_maxDistance=100;get volume(){return this._volume}set volume(e){this._volume=e,this.sound&&!this.context.application.muted&&(lt&&console.log(this.name,"audio set volume",e),this.sound.setVolume(e))}_volume=1;set pitch(e){this.sound&&this.sound.setPlaybackRate(e)}get pitch(){return this.sound?this.sound.getPlaybackRate():1}rollOffMode=0;_loop=!1;sound=null;helper=null;wasPlaying=!1;audioLoader=null;shouldPlay=!1;_lastClipStartedLoading=null;_audioElement=null;get Sound(){if(!this.sound&&Ls.userInteractionRegistered){let e=this.gameObject.getComponent(ts)??this.context.mainCamera.getComponent(ts)??lc(ts,this.context,!1);!e&&this.context.mainCamera&&(e=this.context.mainCamera.addComponent(ts)),e?.listener?(this.sound=new c.PositionalAudio(e.listener),this.gameObject?.add(this.sound)):lt&&console.warn("No audio listener found in scene - can not play audio")}return this.sound}get ShouldPlay(){return this.shouldPlay}get audioContext(){return this.sound?.context}awake(){lt&&console.log("[AudioSource]",this),this.audioLoader=new c.AudioLoader,this.playOnAwake&&(this.shouldPlay=!0),this.preload&&typeof this.clip=="string"&&this.audioLoader.load(this.clip,this.createAudio,()=>{},console.error)}onEnable(){this.sound&&this.gameObject.add(this.sound),Ls.userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():Ls.registerWaitForAllowAudio(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.onNewClip(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(Qf.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(Qf.MuteChanged,this.onApplicationMuteChanged),this.pause()}onVisibilityChanged=()=>{switch(document.visibilityState){case"hidden":(this.playInBackground===!1||exports.DeviceUtilities.isMobileDevice())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":lt&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,Ls.userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&Ls.userInteractionRegistered&&this.wasPlaying&&this.play();break}};onApplicationMuteChanged=()=>{this.context.application.muted?this.sound?.setVolume(0):this.sound?.setVolume(this.volume)};createAudio=e=>{if(this.destroyed){lt&&console.warn("AudioSource destroyed, not creating audio",this.name);return}lt&&console.log("AudioBuffer finished loading",e);const t=this.Sound;if(!t){lt&&console.warn("Failed getting sound?",this.name);return}t.isPlaying&&t.stop(),e&&t.setBuffer(e),t.loop=this._loop,this.context.application.muted?t.setVolume(0):t.setVolume(this.volume),t.autoplay=this.shouldPlay&&Ls.userInteractionRegistered,this.applySpatialDistanceSettings(),t.isPlaying&&t.stop(),Ls.registerWaitForAllowAudio(this.__onAllowAudioCallback)};__onAllowAudioCallback=()=>{this.shouldPlay&&this.play()};applySpatialDistanceSettings(){const e=this.sound;if(!e)return;this._needUpdateSpatialDistanceSettings=!1;const t=D.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(lt&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+t),e.setRefDistance(t),e.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:e.setDistanceModel("exponential");break;case 1:e.setDistanceModel("linear");break;case 2:console.warn("Custom rolloff for AudioSource is not supported: "+this.name);break}this.spatialBlend>0?lt&&!this.helper&&(this.helper=new q.PositionalAudioHelper(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}async onNewClip(e){if(e&&(this.clip=e),typeof e=="string")if(lt&&console.log(e),e.endsWith(".mp3")||e.endsWith(".wav")){if(this.audioLoader||(this.audioLoader=new c.AudioLoader),this.shouldPlay=!0,this._lastClipStartedLoading===e){lt&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=e,lt&&console.log("load audio",e);const t=await this.audioLoader.loadAsync(e).catch(console.error);if(this.destroyed)return;this._lastClipStartedLoading===e&&(this._lastClipStartedLoading=null),t&&this.createAudio(t)}else console.warn("Unsupported audio clip type",e);else this.shouldPlay=!0,this.createAudio()}play(e=void 0){!e&&this.clip&&(e=this.clip),e!==void 0&&typeof e!="string"&&!(e instanceof MediaStream)&&(A()&&console.warn("Called play on AudioSource with unknown argument type:",e+`
|
|
949
|
+
Could not find method ${r.method} on object ${l.name}`,l,typeof l[r.method])};if(typeof l[r.method]!="function"){let p=!1,m=l;for(;m;){const y=Object.getOwnPropertyDescriptor(m,r.method);if(y&&(y.writable===!0||y.set)){p=!0;break}m=Object.getPrototypeOf(m)}!p&&(A()||st)&&d()}}if(l){let d=r.argument;if(d!==void 0?d=a(d):r.arguments!==void 0&&(d=r.arguments.map(a)),!l[r.method])console.warn(`EventList method not found: "${r.method}" on ${l?.name}`);else{d!==void 0&&!Array.isArray(d)&&(d=[d]);const p=new es(l,r.method,d,r.enabled);i.push(p)}}else A()&&console.warn(`[Dev] EventList: Could not find event listener in scene (${t.object?.name})`,r)}const n=new ae(i);st&&console.log(n);const o=t.target;return o!==void 0&&t.path!==void 0&&n.setEventTarget(t.path,o),n}}}const E1=new R1,pd=new WeakMap,T1=c.Texture.prototype.clone;c.Texture.prototype.clone=function(){const s=T1.call(this);return pd.has(s)||pd.set(s,this),s};class H0 extends Fi{constructor(){super([xn,c.WebGLRenderTarget])}onSerialize(e,t){}onDeserialize(e,t){if(e instanceof c.Texture&&t.type===xn){let i=e;pd.has(i)&&(i=pd.get(i)),i.isRenderTargetTexture=!0,i.flipY=!0,i.offset.y=1,i.repeat.y=-1,i.needsUpdate=!0,i.mipmaps=[],i instanceof c.CompressedTexture&&(i.isCompressedTexture=!1,i.format=c.RGBAFormat);const n=new xn(i.image.width,i.image.height,{colorSpace:c.LinearSRGBColorSpace});return n.texture=i,n}}}new H0;class q0 extends Fi{constructor(){super([URL])}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"&&e.length>0)return Ys(t.gltfId,e)}}new q0;var A1=Object.defineProperty,L1=(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&&A1(e,t,n),n};class la extends k{awake(){Dt.createIfNoneExists(this.context)}onEnable(){Dt.get(this.context)?.register(this)}onDisable(){Dt.get(this.context)?.unregister(this)}}class ci extends la{targets=null;raycastHits=[];ignoreSkinnedMeshes=!1;start(){this.targets=[this.gameObject]}performRaycast(e=null){if(!this.targets)return null;e??=new Js,e.targets=this.targets,e.results=this.raycastHits,e.useAcceleratedRaycast=!0;const t=e.testObject;this.ignoreSkinnedMeshes&&(e.testObject=n=>n instanceof c.SkinnedMesh?"continue in children":t?t(n):!0);const i=this.context.physics.raycast(e);return e.testObject=t,i}}L1([f()],ci.prototype,"ignoreSkinnedMeshes");class qd extends ci{constructor(){super(),this.ignoreSkinnedMeshes=!0}}class Ho extends la{static allow=!0;performRaycast(e){if(!H.active||!Ho.allow||!e?.ray)return null;const t=e.ray.origin;return this.context.physics.sphereOverlap(t,.015,!1,!0)}}class wm{static getObject(e){const t=e[ii];return t&&(t.isComponent===!0?e=t.gameObject:e=t),e}static isInteractable(e,t){if(t&&(t.canvasGroup=void 0,t.graphic=void 0),e==null||!e.visible||(e=this.getObject(e),!e.visible))return!1;const i=this.tryFindCanvasGroup(e);if(i?.isCanvasGroup===!0&&(t&&(t.canvasGroup=i),i.blocksRaycasts===!1||i.interactable===!1))return!1;const n=Wo(e,o=>{if(o.isGraphic===!0)return o},!1);return t&&n?.isGraphic===!0&&(t.graphic=n),!(n?.raycastTarget===!1||n?.layer===2)}static tryFindCanvasGroup(e){if(!e)return null;const t=Wo(e,i=>{const n=i;if(n.blocksRaycasts!==void 0&&n.interactable!==void 0)return n},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}}function Sm(s){const e=s[ii];return e||(s.parent?Sm(s.parent):null)}function D1(s){return s.isUI===!0||typeof s[ii]=="object"}function md(s,e){if(!s)return;const t=s.material;if(t?.isMaterial===!0){const i=s.parent;i&&i.isText,t.side=e.doubleSided??!0?c.DoubleSide:c.FrontSide,t.shadowSide=e.doubleSided?c.DoubleSide:c.FrontSide,s.castShadow=e.castShadows?e.castShadows:!1,s.receiveShadow=e.receiveShadows?e.receiveShadows:!1}for(const i of s.children)md(i,e)}function Lr(s,e,t){s[e]===void 0&&console.warn("Field",e,"is undefined on",s);const i=Proxy.revocable(s[e],{set(r,a,l,h){const d=r[a],u=Reflect.set(r,a,l,h);return t(l,d),u}}),n=i.revoke,o=s[e];return i.revoke=()=>{s[e]=o,n()},s[e]=i.proxy,i}const Qy=Symbol("Scheduled action");function I1(s,e,t=pe.OnBeforeRender){let i=s[Qy];i||(i=s[Qy]={});const n=e.name;i[t]||(i[t]={});const o=i[t];if(o[n])return;function*a(){e?.call(s),o[n]=null}const l=s.startCoroutine(a(),t);o[n]=l}const Ts=x("debugeventsystem");var gp=(s=>(s.BeforeHandleInput="BeforeHandleInput",s.AfterHandleInput="AfterHandleInput",s))(gp||{});I0(s=>{Dt.createIfNoneExists(s)});class Dt extends k{static ensureUpdateMeshUI(e,t,i=!1){za.update(e,t,i)}static markUIDirty(e){za.markDirty()}static createIfNoneExists(e){e.scene.getComponent(Dt)||e.scene.addComponent(Dt)}static get(e){return this.createIfNoneExists(e),e.scene.getComponent(Dt)}static get instance(){return this.get(F.Current)}raycaster=[];register(e){e&&this.raycaster&&!this.raycaster.includes(e)&&this.raycaster?.push(e)}unregister(e){const t=this.raycaster?.indexOf(e);t!==void 0&&t!==-1&&this.raycaster?.splice(t,1)}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.hoveredByID.size>0}awake(){this.gameObject!==this.context.scene&&(console.debug(`[Needle Engine] EventSystem is only allowed on the scene root. Disabling EventSystem on '${this.gameObject.name}'`),this.enabled=!1)}start(){this.context.scene.getComponent(la)||this.context.scene.addComponent(ci)}onEnable(){this.context.input.addEventListener(xe.PointerDown,this.onPointerEvent),this.context.input.addEventListener(xe.PointerUp,this.onPointerEvent),this.context.input.addEventListener(xe.PointerMove,this.onPointerEvent)}onDisable(){this.context.input.removeEventListener(xe.PointerDown,this.onPointerEvent),this.context.input.removeEventListener(xe.PointerUp,this.onPointerEvent),this.context.input.removeEventListener(xe.PointerMove,this.onPointerEvent)}pressedByID=new Map;hoveredByID=new Map;onBeforeRender(){this.resetMeshUIStates()}onPointerEvent=e=>{if(e===void 0||e.propagationStopped||e.defaultPrevented||e.used)return;const t=new fc(this.context.input,e);this._currentPointerEventName=e.type,t.inputSource=this.context.input,t.isClick=e.isClick,t.isDoubleClick=e.isDoubleClick,t.isDown=e.type==xe.PointerDown,t.isUp=e.type==xe.PointerUp,t.isPressed=this.context.input.getPointerPressed(e.pointerId);const i=new Js;e.hasRay?i.ray=e.ray:i.screenPoint=this.context.input.getPointerPositionRC(e.pointerId),i.allowSlowRaycastFallback=e.isClick||e.isDoubleClick;const n=this.performRaycast(i);if(Ts&&(t.isDown?console.log("DOWN",{id:t.pointerId,hits:n.length}):t.isUp&&console.log("UP",{id:t.pointerId,hits:n.length}),t.isClick&&console.log("CLICK",{id:t.pointerId,hits:n.length})),n){for(const r of n)r.event=e,e.intersections.push(r);e.origin.onPointerHits&&e.origin.onPointerHits({sender:this,event:e,hits:n})}Ts&&t.isClick&&Se("EventSystem: "+t.pointerId+" - "+this.context.time.frame+" - Up:"+t.isUp+", Down:"+t.isDown);const o={sender:this,args:t,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:o})),this.handleIntersections(n,t),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:o}))};_sortedHits=[];_testObjectsCache=new Map;_currentlyActiveRaycaster=null;_currentPointerEventName=null;shouldRaycastObject=e=>{const t=e&&"getComponent"in e?e.getComponent(la):null;if(t&&t!=this._currentlyActiveRaycaster)return!1;let i=null;if(D1(e)&&(i=e[ii]?.gameObject),this._testObjectsCache.has(e)||i&&this._testObjectsCache.has(i))return this._testObjectsCache.get(e)===!1?"continue in children":!0;{let o=fd(e,this._currentPointerEventName);if(!o&&i&&(o=fd(i,this._currentPointerEventName)),o){this._testObjectsCache.set(e,!0);for(const r of e.children)this.shouldRaycastObject_AddToYesCache(r);return!0}return this._testObjectsCache.set(e,!1),"continue in children"}};shouldRaycastObject_AddToYesCache(e){this._testObjectsCache.set(e,!0);for(const t of e.children)this.shouldRaycastObject_AddToYesCache(t)}performRaycast(e){if(!this.raycaster)return null;this._testObjectsCache.clear(),this._sortedHits.length=0,e.testObject=this.shouldRaycastObject;for(const t of this.raycaster){if(!t.activeAndEnabled)continue;this._currentlyActiveRaycaster=t;const i=t.performRaycast(e);this._currentlyActiveRaycaster=null,i&&i.length>0&&this._sortedHits.push(...i)}return this._sortedHits.sort((t,i)=>t.distance-i.distance),this._sortedHits}assignHitInformation(e,t){t?(e.intersection=t,e.point=t.point,e.normal=t.normal,e.face=t.face,e.distance=t.distance,e.instanceId=t.instanceId):(e.intersection=void 0,e.point=void 0,e.normal=void 0,e.face=void 0,e.distance=void 0,e.instanceId=void 0)}handleIntersections(e,t){if(e?.length){e=this.sortCandidates(e);for(const n of e){if(t.event.immediatePropagationStopped)return!1;if(this.assignHitInformation(t,n),this.handleEventOnObject(n.object,t))return!0}}this.assignHitInformation(t,e?.[0]),this.invokePointerCapture(t);const i=this.hoveredByID.get(t.pointerId);return i&&this.propagatePointerExit(i.obj,i.data,null),this.hoveredByID.delete(t.pointerId),t.isUp&&(this.pressedByID.get(t.pointerId)?.handlers.forEach(n=>this.invokeOnPointerUp(t,n)),this.pressedByID.delete(t.pointerId)),!1}_sortingBuffer=[];_noDepthTestingResults=[];sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let t=0;t<e.length;t++){const i=e[t],n=i.object;if(n.material&&n.material.depthTest===!1){this._noDepthTestingResults.push(i);continue}this._sortingBuffer.push(i)}for(const t of this._sortingBuffer)this._noDepthTestingResults.push(t);return this._noDepthTestingResults}out={};handleEventOnObject(e,t){if(!this.testIsVisible(e))return t.isClick&&Ts&&console.log("not allowed",e),!1;if(t.pointerId===void 0)return Ts&&console.error("Event without pointer can't be handled",t),!1;t.object=e;const i=e.parent,n=t.isClick??!1;let o=null;if(i&&i.isUI){const d=(t.isPressed||t.isClick)??!1;if(i[ii]){const u=i[ii].gameObject;if(u){if(!wm.isInteractable(u,this.out))return!1;o=this.out.canvasGroup??null,this.handleMeshUIIntersection(e,d),e=u}}}n&&Ts&&console.log(this.context.time.frame,e);const r=this.hoveredByID.get(t.pointerId),a=r?.obj;a!==e&&a&&this.propagatePointerExit(a,r.data,e);const h=this.hoveredByID.get(t.pointerId);if(h?(h.obj=e,h.data=t):this.hoveredByID.set(t.pointerId,{obj:e,data:t}),t.isDown){const d=this.pressedByID.get(t.pointerId);d?(d.obj=e,d.data=t):this.pressedByID.set(t.pointerId,{obj:e,data:t,handlers:new Set})}return(o===null||o.interactable)&&this.handleMainInteraction(e,t,a??null),!0}propagate(e,t){for(;e;)S.foreachComponent(e,i=>{t(i)},!1),e=e.parent}handleMainInteraction(e,t,i){const n=this.pressedByID.get(t.pointerId),o=i!==e;let r=!0;switch(t.event.pointerType){case"mouse":case"touch":const a=this.context.input.getPointerPositionLastFrame(t.pointerId),l=this.context.input.getPointerPosition(t.pointerId);r=a&&!D.approximately(a,l);break}this.propagate(e,a=>{const l=a;l.interactable!==!1&&(!l.activeAndEnabled||!l.enabled||(l.onPointerEnter&&o&&this.handlePointerEnter(l,t),t.isDown&&l.onPointerDown&&(l.onPointerDown(t),n?.handlers.add(l),this.handlePointerCapture(t,l)),l.onPointerMove&&(r&&l.onPointerMove(t),this.handlePointerCapture(t,l)),t.isUp&&(l.onPointerUp&&(this.invokeOnPointerUp(t,l),n?.handlers.delete(l)),l.onPointerExit&&t.event?.pointerType===Id.Touch&&(this.handlePointerExit(l,t),this.hoveredByID.delete(t.pointerId))),t.isClick&&l.onPointerClick&&l.onPointerClick(t)))}),t.isUp&&(n?.handlers.forEach(a=>{this.invokeOnPointerUp(t,a)}),this.pressedByID.delete(t.pointerId))}propagatePointerExit(e,t,i){this.propagate(e,n=>{if(!n.gameObject||n.destroyed)return;const o=n;if(o.onPointerExit||o.onPointerEnter){if(i&&this.isChild(i,n.gameObject))return;this.handlePointerExit(o,t)}})}invokeOnPointerUp(e,t){t.onPointerUp?.call(t,e),this.releasePointerCapture(e,t)}handlePointerEnter(e,t){e.onPointerEnter&&this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!0)&&e.onPointerEnter(t),this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!1)}handlePointerExit(e,t){e.onPointerExit&&this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!0)&&e.onPointerExit(t),this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!1)}updatePointerState(e,t,i,n){let o=e[i];if(n)return o&&o.includes(t)?!1:(o=o||[],o.push(t),e[i]=o,!0);{if(!o||!o.includes(t))return!1;const r=o.indexOf(t);return r!==-1&&o.splice(r,1),!0}}_capturedPointer={};handlePointerCapture(e,t){if(e.z__pointer_ctured){e.z__pointer_ctured=!1;const i=e.pointerId;if(t.onPointerMove){const n=this._capturedPointer[i]||[];n.push(t),this._capturedPointer[i]=n}else A()&&!t.z__warned_no_pointermove&&(t.z__warned_no_pointermove=!0,console.warn("PointerCapture was requested but the component doesn't implement onPointerMove. It will not receive any pointer events"))}else e.z__pointer_cture_rleased&&(e.z__pointer_cture_rleased=!1,this.releasePointerCapture(e,t))}releasePointerCapture(e,t){const i=e.pointerId;if(this._capturedPointer[i]){const n=this._capturedPointer[i].indexOf(t);n!==-1&&(this._capturedPointer[i].splice(n,1),Ts&&console.log("released pointer capture",i,t,this._capturedPointer))}}invokePointerCapture(e){if(e.event.type===xe.PointerMove){const t=e.pointerId,i=this._capturedPointer[t];if(i){Ts&&console.log("Captured",t,i);for(let n=0;n<i.length;n++){const o=i[n];if(o.destroyed){i.splice(n,1),n--;continue}o.onPointerMove?.call(o,e)}}}}pointerEnterSymbol=Symbol("pointerEnter");pointerExitSymbol=Symbol("pointerExit");isChild(e,t){return!e||!t?!1:e===t?!0:e.parent?this.isChild(e.parent,t):!1}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}currentActiveMeshUIComponents=[];handleMeshUIIntersection(e,t){const i=za.updateState(e,t);return i&&this.currentActiveMeshUIComponents.push(i),i!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&za.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){const t=this.currentActiveMeshUIComponents[e];za.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?S.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}}class za{static lastSelected=null;static lastUpdateFrame=[];static needsUpdate=!1;static markDirty(){this.needsUpdate=!0}static update(e,t,i=!1){if(i){e.update();return}const n=t.time.frameCount;for(const o of this.lastUpdateFrame)if(o.context===t){if(n===o.frame)return;o.frame=n;let r=this.needsUpdate||n<1;o.nextUpdate<=n&&(r=!0),r&&(Ts&&console.log("Update threemeshui"),this.needsUpdate=!1,o.nextUpdate=n+60,e.update());return}this.lastUpdateFrame=[{context:t,frame:n,nextUpdate:n+60}],e.update(),this.needsUpdate=!1}static updateState(e,t){let i=null;if(e&&(i=this.findBlockOrTextInParent(e),i&&i!==this.lastSelected)){if(i.interactable===!1)return null;this.needsUpdate=!0}return i}static resetLastSelected(){const e=this.lastSelected;e&&(this.lastSelected=null,this.resetState(e))}static resetState(e){e&&(this.needsUpdate=!0)}static findBlockOrTextInParent(e){return e?e.isBlock||e.isText?e:this.findBlockOrTextInParent(e.parent):null}}var j1=Object.defineProperty,Ce=(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&&j1(e,t,n),n};const wi=x("debugorbit"),sf=x("freecam"),Na=x("debugcamerafit"),dh=x("smoothcam"),B1={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let of;class Vl extends CustomEvent{constructor(e,t){super("target-reached",{detail:{controls:e,type:t}})}}class de extends k{get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){this.controls?.addEventListener("start",e)}autoTarget=!0;autoFit=!1;enableRotate=!0;autoRotate=!1;autoRotateSpeed=1;minAzimuthAngle=1/0;maxAzimuthAngle=1/0;minPolarAngle=0;maxPolarAngle=Math.PI;enableKeys=!1;enableDamping=!0;dampingFactor=.1;enableZoom=!0;minZoom=0;maxZoom=1/0;zoomSpeed=1;zoomToCursor=!1;enablePan=!0;lookAtConstraint=null;lookAtConstraint01=1;allowInterrupt=!0;middleClickToFocus=!0;doubleClickToFocus=!0;clickBackgroundToFitScene=2;get targetElement(){return this._controls?.domElement??this._targetElement}set targetElement(e){this._targetElement=e,this._controls&&this._controls.domElement!==e&&(this._controls.disconnect(),this._controls.domElement=e,this._controls.connect())}_targetElement=null;debugLog=!1;get targetLerpSpeed(){return 5}set targetLerpSpeed(e){this.targetLerpDuration=1/e}targetLerpDuration=1;rotateLeft(e){this._controls?._rotateLeft(e)}rotateUp(e){this._controls?._rotateUp(e)}pan(e,t){this._controls?._pan(e,t)}zoomIn(e){e>0?this._controls?._dollyIn(1-e):e<0&&this._controls?._dollyOut(1+e)}_controls=null;_cameraObject=null;_lookTargetLerpActive=!1;_lookTargetStartPosition=new c.Vector3;_lookTargetEndPosition=new c.Vector3;_lookTargetLerp01=0;_lookTargetLerpDuration=0;_cameraLerpActive=!1;_cameraStartPosition=new c.Vector3;_cameraEndPosition=new c.Vector3;_cameraLerp01=0;_cameraLerpDuration=0;_fovLerpActive=!1;_fovLerpStartValue=0;_fovLerpEndValue=0;_fovLerp01=0;_fovLerpDuration=0;_inputs=0;_enableTime=0;_startedListeningToKeyEvents=!1;_eventSystem;_afterHandleInputFn;_camera=null;_syncedTransform;_didSetTarget=0;awake(){wi&&console.debug("OrbitControls",this),this._didSetTarget=0,this._startedListeningToKeyEvents=!1}start(){this._eventSystem=Dt.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(gp.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){this._controls?.dispose(),this._eventSystem?.removeEventListener(gp.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._didSetTarget=0,this._enableTime=this.context.time.time;const e=S.getComponent(this.gameObject,Vt);this._camera=e;let t=e?.threeCamera;if(!t&&this.gameObject instanceof c.PerspectiveCamera&&(t=this.gameObject),t&&Gf(t,this,!0),!this._controls&&t instanceof c.Object3D){this._cameraObject=t;const i=this.targetElement??this.context.renderer.domElement,n=t?.quaternion.clone();this._controls=new q.OrbitControls(t,i),t?.quaternion.copy(n),of===void 0&&(of={...this._controls.keys});const o=X(t),r=this.gameObject.worldForward,l=o.clone().sub(r.multiplyScalar(2.5));this._controls.target.copy(l)}if(this._controls)if(sf&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,exports.DeviceUtilities.isMobileDevice()&&(this.doubleClickToFocus=!0)),this._controls.addEventListener("start",this.onControlsChangeStarted),this._controls.addEventListener("endMovement",this.onControlsChangeEnded),!this._startedListeningToKeyEvents&&this.enableKeys)this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(this.context.domElement);else try{this._controls.stopListenToKeyEvents()}catch{}this._syncedTransform=S.getComponent(this.gameObject,tn)??void 0,this.context.pre_render_callbacks.push(this.__onPreRender),this._activePointerEvents=[],this.context.input.addEventListener("pointerdown",this._onPointerDown,{queue:Nt.Early}),this.context.input.addEventListener("pointerdown",this._onPointerDownLate,{queue:Nt.Late}),this.context.input.addEventListener("pointerup",this._onPointerUp,{queue:Nt.Early}),this.context.input.addEventListener("pointerup",this._onPointerUpLate,{queue:Nt.Late})}onDisable(){if(this._camera?.threeCamera&&Gf(this._camera.threeCamera,this,!1),this._controls){this._controls.enabled=!1,this._controls.autoRotate=!1,this._controls.removeEventListener("start",this.onControlsChangeStarted),this._controls.removeEventListener("endMovement",this.onControlsChangeEnded);try{this._controls.stopListenToKeyEvents()}catch{}this._startedListeningToKeyEvents=!1}this._activePointerEvents.length=0,this.context.input.removeEventListener("pointerdown",this._onPointerDown),this.context.input.removeEventListener("pointerdown",this._onPointerDownLate),this.context.input.removeEventListener("pointerup",this._onPointerUp),this.context.input.removeEventListener("pointerup",this._onPointerUpLate)}_activePointerEvents;_lastTimeClickOnBackground=-1;_clickOnBackgroundCount=0;_onPointerDown=e=>{this._activePointerEvents.push(e)};_onPointerDownLate=e=>{e.used&&this._controls&&(this._controls.enabled=!1)};_onPointerUp=e=>{for(let t=this._activePointerEvents.length-1;t>=0;t--){const i=this._activePointerEvents[t];if(i.pointerId===e.pointerId&&i.button===e.button){this._activePointerEvents.splice(t,1);break}}if(this.clickBackgroundToFitScene>0&&e.isClick&&e.button===0){if(e.hasRay||e.intersections.push(...this.context.physics.raycast()),e.intersections.length<=0){const t=this.context.time.time-this._lastTimeClickOnBackground;this._lastTimeClickOnBackground=this.context.time.time,this.clickBackgroundToFitScene<=1||t<this.clickBackgroundToFitScene*.15?(this._clickOnBackgroundCount+=1,this._clickOnBackgroundCount>=this.clickBackgroundToFitScene-1&&this.fitCamera(this.context.scene.children,{immediate:!1})):this._clickOnBackgroundCount=0}wi&&console.log(this.clickBackgroundToFitScene,e.intersections.length,this._clickOnBackgroundCount)}};_onPointerUpLate=e=>{this.doubleClickToFocus&&e.isDoubleClick&&!e.used&&this.setTargetFromRaycast()};updateTargetNow(e){const t=new c.Ray(this._cameraObject?.worldPosition,this._cameraObject?.worldForward.multiplyScalar(-1)),i=this.context.physics.raycastFromRay(t,e),n=i.length>0?i[0]:void 0;n&&n.distance>this.minZoom&&n.distance<this.maxZoom&&(wi&&B.DrawWireSphere(n.point,.1,16711680,2),this._controls?.target.copy(i[0].point))}_orbitStartAngle=0;_zoomStartDistance=0;onControlsChangeStarted=()=>{this._controls&&(this._orbitStartAngle=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle(),this._zoomStartDistance=this._controls.getDistance()),this._syncedTransform&&this._syncedTransform.requestOwnership()};onControlsChangeEnded=()=>{if(this._controls&&this.autoTarget){const t=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle()-this._orbitStartAngle;Math.abs(t)<.01?(wi&&console.debug("OrbitControls: Update target",{deltaAngle:t}),this.updateTargetNow({allowSlowRaycastFallback:!1})):wi&&console.debug("OrbitControls: No target update",{deltaAngle:t})}};_shouldDisable=!1;afterHandleInput(e){e.detail.args.pointerId===0&&(e.detail.args.isDown?this._controls&&this._eventSystem&&(this._shouldDisable=this._eventSystem.hasActiveUI):(!e.detail.args.isPressed||e.detail.args.isUp)&&(this._shouldDisable=!1))}onPausedChanged(e){this._controls&&e&&(this._controls.enabled=!1)}onBeforeRender(){if(!this._controls)return;if(this._cameraObject!==this.context.mainCamera){this._controls.enabled=!1;return}if(this._controls.enabled=!0,(this.context.input.getPointerDown(1)||this.context.input.getPointerDown(2)||this.context.input.mouseWheelChanged||this.context.input.getPointerPressed(0)&&this.context.input.getPointerPositionDelta(0)?.length())&&(this._inputs+=1),this._inputs>0&&this.allowInterrupt&&(this.enableRotate&&(this.autoRotate=!1),this._cameraLerpActive=!1,this._lookTargetLerpActive=!1),this._inputs=0,this.autoTarget&&this._didSetTarget++===0){const t=S.getComponent(this.gameObject,Vt);if(t&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log("NO TARGET");const i=X(t.threeCamera),n=Math.max(.01,i.length()),o=new c.Vector3(0,0,-n).applyMatrix4(t.threeCamera.matrixWorld);wi&&B.DrawLine(i,o,5592575,10),this.setLookTargetPosition(o,!0)}if(!this.setLookTargetFromConstraint()){const i=new Js;i.screenPoint=new c.Vector2(0,0),i.lineThreshold=.1;const n=this.context.physics.raycast(i);n.length>0&&this.setLookTargetPosition(n[0].point,!0),Na&&console.log("OrbitControls hits",...n)}}if(this.middleClickToFocus&&this.context.input.getPointerClicked(1)&&this.setTargetFromRaycast(),this._lookTargetLerpActive||this._cameraLerpActive||this._fovLerpActive){if(this._cameraLerpActive&&this._cameraObject)if(this._cameraLerp01+=this.context.time.deltaTime/this._cameraLerpDuration,this._cameraLerp01>=1)this._cameraObject.position.copy(this._cameraEndPosition),this._cameraLerpActive=!1,this.dispatchEvent(new Vl(this,"camera"));else{const t=D.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,t)}if(this._lookTargetLerpActive)if(this._lookTargetLerp01+=this.context.time.deltaTime/this._lookTargetLerpDuration,this._lookTargetLerp01>=1)this.lerpLookTarget(this._lookTargetEndPosition,this._lookTargetEndPosition,1),this._lookTargetLerpActive=!1,this.dispatchEvent(new Vl(this,"lookat"));else{const t=D.easeInOutCubic(this._lookTargetLerp01);this.lerpLookTarget(this._lookTargetStartPosition,this._lookTargetEndPosition,t)}if(this._fovLerpActive&&this._cameraObject){const t=this._cameraObject;if(this._fovLerp01+=this.context.time.deltaTime/this._fovLerpDuration,this._fovLerp01>=1)t.fov=this._fovLerpEndValue,this._fovLerpActive=!1;else{const i=D.easeInOutCubic(this._fovLerp01);t.fov=D.lerp(this._fovLerpStartValue,this._fovLerpEndValue,i)}t.updateProjectionMatrix()}}if(this._controls){if(this.debugLog&&(this._controls.domElement=this.context.renderer.domElement),this._controls.enabled=!this._shouldDisable&&this._camera===this.context.mainCameraComponent&&!this.context.isInXR&&!this._activePointerEvents.some(t=>t.used),this._controls.keys=this.enableKeys?of:B1,this._controls.autoRotate=this.autoRotate,this._controls.autoRotateSpeed=this.autoRotateSpeed,this._controls.enableZoom=this.enableZoom,this._controls.zoomSpeed=this.zoomSpeed,this._controls.zoomToCursor=this.zoomToCursor,this._controls.enableDamping=this.enableDamping,this._controls.dampingFactor=this.dampingFactor,this._controls.enablePan=this.enablePan,this._controls.enableRotate=this.enableRotate,this._controls.minAzimuthAngle=this.minAzimuthAngle,this._controls.maxAzimuthAngle=this.maxAzimuthAngle,this._controls.minPolarAngle=this.minPolarAngle,this._controls.maxPolarAngle=this.maxPolarAngle,sf||(this._camera?.threeCamera?.type==="PerspectiveCamera"?(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom,this._controls.minZoom=0,this._controls.maxZoom=1/0):(this._controls.minDistance=0,this._controls.maxDistance=1/0,this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom)),typeof dh=="number"||dh===!0){this._controls.enableDamping=!0;const t=typeof dh=="number"?dh:.99;this._controls.dampingFactor=Math.max(.001,1-Math.min(1,t))}this.allowInterrupt||(this._lookTargetLerpActive&&(this._controls.enablePan=!1),this._cameraLerpActive&&(this._controls.enableRotate=!1,this._controls.autoRotate=!1),(this._lookTargetLerpActive||this._cameraLerpActive)&&(this._controls.enableZoom=!1)),this.context.isInXR||(!sf&&this.lookAtConstraint?.locked&&!this._lookTargetLerpActive&&this.setLookTargetFromConstraint(0,this.lookAtConstraint01),this._controls.update(this.context.time.deltaTime),wi&&B.DrawWireSphere(this._controls.target,.1,65280))}}__onPreRender=()=>{const e=this.context.pre_render_callbacks.indexOf(this.__onPreRender);e>=0&&this.context.pre_render_callbacks.splice(e,1),this.autoFit&&(this.autoFit=!1,this.fitCamera({centerCamera:"y",immediate:!0,objects:this.scene.children}))};setCameraAndLookTarget(e,t=!1){if(!e)return(A()||wi)&&console.warn("[OrbitControls] setCameraAndLookTarget target is null"),!1;if(!(e instanceof c.Object3D)&&!(e instanceof Vt))return(A()||wi)&&console.warn("[OrbitControls] setCameraAndLookTarget target is not an Object3D or Camera"),!1;e instanceof Vt&&(e=e.gameObject);const i=e.worldPosition,n=e.worldForward;e instanceof c.Camera&&(wi&&console.debug("[OrbitControls] setCameraAndLookTarget flip forward direction for camera"),n.multiplyScalar(-1));const o=new c.Ray(i,n);return wi&&B.DrawRay(o.origin,o.direction,16711680,10),this.setTargetFromRaycast(o,t)||this.setLookTargetPosition(o.at(2,V()),t),this.setCameraTargetPosition(i,t),!0}setCameraTargetPosition(e,t=!1){e&&(e instanceof c.Object3D&&(e=X(e)),this._cameraEndPosition||(this._cameraEndPosition=new c.Vector3),this._cameraEndPosition.copy(e),t===!0?(this._cameraLerpActive=!1,this._cameraObject&&this._cameraObject.position.copy(this._cameraEndPosition)):this._cameraObject&&(this._cameraLerpActive=!0,this._cameraLerp01=0,this._cameraStartPosition.copy(this._cameraObject?.position),typeof t=="number"?this._cameraLerpDuration=t:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setFieldOfView(e,t=!1){if(!this._controls||typeof e!="number")return;const i=this._camera?.threeCamera;i&&(t===!0?i.fov=e:(this._fovLerpActive=!0,this._fovLerp01=0,this._fovLerpStartValue=i.fov,this._fovLerpEndValue=e,typeof t=="number"?this._fovLerpDuration=t:this._fovLerpDuration=this.targetLerpDuration))}setLookTargetPosition(e=null,t=!1){this._controls&&e&&(e instanceof c.Object3D&&(e=X(e)),this._lookTargetEndPosition.copy(e),this._didSetTarget++,wi&&(console.warn("OrbitControls: setLookTargetPosition",e,t),B.DrawWireSphere(this._lookTargetEndPosition,.2,16711680,2)),t===!0?this.lerpLookTarget(this._lookTargetEndPosition,this._lookTargetEndPosition,1):(this._lookTargetLerpActive=!0,this._lookTargetLerp01=0,this._lookTargetStartPosition.copy(this._controls.target),typeof t=="number"?this._lookTargetLerpDuration=t:this._lookTargetLerpDuration=this.targetLerpDuration))}get lookTargetLerpActive(){return this._lookTargetLerpActive}stopLookTargetLerp(){this._lookTargetLerpActive=!1}setLookTargetFromConstraint(e=0,t=1){if(!this._controls||this.lookAtConstraint?.enabled===!1)return!1;const i=this.lookAtConstraint?.sources;if(i&&i.length>0){const n=i[e];if(n)return n.getWorldPosition(this._lookTargetEndPosition),this.lerpLookTarget(this._controls.target,this._lookTargetEndPosition,t),!0}return!1}lerpLookTarget(e,t,i){this._controls&&(i>=1?this._controls.target.copy(t):this._controls.target.lerpVectors(e,t,i),this.lookAtConstraint&&this.lookAtConstraint.setConstraintPosition(this._controls.target))}setTargetFromRaycast(e,t=!1){if(!this.controls)return!1;const i=e?this.context.physics.raycastFromRay(e):this.context.physics.raycast();for(const n of i)if(n.distance>0&&S.isActiveInHierarchy(n.object)){const o=Sm(n.object);if(o&&o.canvas?.screenspace)break;return this.setLookTargetPosition(n.point,t),!0}return!1}fitCamera(e,t){if(this.context.isInXR){console.warn("[OrbitControls] Can not fit camera while XR session is active");return}let i;if(Array.isArray(e)?i=e:e&&"type"in e?i=e.children:e&&typeof e=="object"&&!(e instanceof c.Object3D)&&!Array.isArray(e)&&(t=e,i=t.objects),i&&!Array.isArray(i)&&(i=i.children),(!Array.isArray(i)||i&&i.length<=0)&&(i=this.context.scene.children),!Array.isArray(i)||i.length<=0){console.warn("No objects to fit camera to...");return}const n=this._cameraObject,o=this._controls;if(!n||!o){console.warn("No camera or controls found to fit camera to objects...");return}t||(t={});const{immediate:r=!1,centerCamera:a,cameraNearFar:l="auto",fitOffset:h=1.1,fov:d=n?.fov}=t,u=new c.Vector3,p=new c.Vector3,m=Wt(i,void 0,this._camera?.threeCamera?.layers),y=m.clone();n.updateMatrixWorld(),n.updateProjectionMatrix(),m.getCenter(p);const b=new c.Vector3;if(m.getSize(b),m.applyMatrix4(n.matrixWorldInverse),m.getSize(u),m.setFromCenterAndSize(p,u),Number.isNaN(u.x)||Number.isNaN(u.y)||Number.isNaN(u.z)){console.warn("Camera fit size resultet in NaN",n,m,[...i]);return}if(u.length()<=1e-10){Na&&console.warn("Camera fit size is zero",m,[...i]);return}const g=d,v=2*Math.atan(Math.tan(g*Math.PI/360/2)*n.aspect)/Math.PI*360,_=u.y/(2*Math.atan(Math.PI*g/360)),w=u.x/(2*Math.atan(Math.PI*v/360)),T=h*Math.max(_,w)+u.z/2;Na&&console.log("Fit camera to objects",{fitHeightDistance:_,fitWidthDistance:w,distance:T,verticalFov:g,horizontalFov:v}),this.maxZoom=T*10,this.minZoom=T*.01;const O=.05,M=p.clone();if(M.y-=u.y*O,t.targetOffset&&(t.targetOffset.x!==void 0&&(M.x+=t.targetOffset.x),t.targetOffset.y!==void 0&&(M.y+=t.targetOffset.y),t.targetOffset.z!==void 0&&(M.z+=t.targetOffset.z)),t.relativeTargetOffset&&(t.relativeTargetOffset.x!==void 0&&(M.x+=t.relativeTargetOffset.x*u.x),t.relativeTargetOffset.y!==void 0&&(M.y+=t.relativeTargetOffset.y*u.y),t.relativeTargetOffset.z!==void 0&&(M.z+=t.relativeTargetOffset.z*u.z)),this.setLookTargetPosition(M,r),this.setFieldOfView(t.fov,r),l==null||l=="auto"){const z=S.findObjectOfType(An),$=z?z.radius:0,E=Math.max(b.x,b.y,b.z,$);n.near=T/100,n.far=E+T*10,z&&(this.maxZoom=Math.max(Math.min(this.maxZoom,$*.5),T))}const R=o.getDistance();R<this.minZoom&&(this.minZoom=R*.9),R>this.maxZoom&&(this.maxZoom=R*1.1),n.updateMatrixWorld(),n.updateProjectionMatrix();const j=p.clone();t.fitDirection?j.sub(new c.Vector3().copy(t.fitDirection).multiplyScalar(1e6)):j.sub(n.worldPosition),a==="y"&&(j.y=0),j.normalize(),j.multiplyScalar(T),a==="y"&&(j.y+=-O*4*T);let L=p.clone().sub(j);t.cameraOffset&&(t.cameraOffset.x!==void 0&&(L.x+=t.cameraOffset.x),t.cameraOffset.y!==void 0&&(L.y+=t.cameraOffset.y),t.cameraOffset.z!==void 0&&(L.z+=t.cameraOffset.z)),t.relativeCameraOffset&&(t.relativeCameraOffset.x!==void 0&&(L.x+=t.relativeCameraOffset.x*u.x),t.relativeCameraOffset.y!==void 0&&(L.y+=t.relativeCameraOffset.y*u.y),t.relativeCameraOffset.z!==void 0&&(L.z+=t.relativeCameraOffset.z*u.z)),n.parent&&(L=n.parent.worldToLocal(L)),this.setCameraTargetPosition(L,r),(Na||t.debug)&&(B.DrawWireBox3(m,16777011,10),B.DrawWireBox3(y,65280,10),!this._haveAttachedKeyboardEvents&&Na&&(this._haveAttachedKeyboardEvents=!0,document.body.addEventListener("keydown",z=>{if(z.code==="KeyF"){let $;this._cameraObject instanceof c.PerspectiveCamera&&($=Math.random()*Math.random()*170+10),this.fitCamera({objects:i,fitOffset:h,immediate:!1,fov:$})}z.code==="KeyV"&&this._cameraObject instanceof c.PerspectiveCamera&&(this._cameraObject.fov=60)}))),this.onBeforeRender()}_haveAttachedKeyboardEvents=!1}Ce([f()],de.prototype,"autoTarget");Ce([f()],de.prototype,"autoFit");Ce([f()],de.prototype,"enableRotate");Ce([f()],de.prototype,"autoRotate");Ce([f()],de.prototype,"autoRotateSpeed");Ce([f()],de.prototype,"minAzimuthAngle");Ce([f()],de.prototype,"maxAzimuthAngle");Ce([f()],de.prototype,"minPolarAngle");Ce([f()],de.prototype,"maxPolarAngle");Ce([f()],de.prototype,"enableKeys");Ce([f()],de.prototype,"enableDamping");Ce([f()],de.prototype,"dampingFactor");Ce([f()],de.prototype,"enableZoom");Ce([f()],de.prototype,"minZoom");Ce([f()],de.prototype,"maxZoom");Ce([f()],de.prototype,"zoomSpeed");Ce([f()],de.prototype,"enablePan");Ce([f(nr)],de.prototype,"lookAtConstraint");Ce([f()],de.prototype,"lookAtConstraint01");Ce([f()],de.prototype,"allowInterrupt");Ce([f()],de.prototype,"middleClickToFocus");Ce([f()],de.prototype,"doubleClickToFocus");Ce([f()],de.prototype,"clickBackgroundToFitScene");Ce([f()],de.prototype,"targetLerpDuration");var F1=Object.defineProperty,U1=Object.getOwnPropertyDescriptor,It=(s,e,t,i)=>{for(var n=i>1?void 0:i?U1(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&&F1(e,t,n),n},Fo=(s=>(s[s.None=0]="None",s[s.Skybox=1]="Skybox",s[s.SolidColor=2]="SolidColor",s[s.Uninitialized=4]="Uninitialized",s))(Fo||{});const As=x("debugcam"),Yy=x("debugscreenpointtoray"),xt=class ll extends k{get isCamera(){return!0}get aspect(){return this._cam instanceof c.PerspectiveCamera?this._cam.aspect:this.context.domWidth/this.context.domHeight}set aspect(e){this._cam instanceof c.PerspectiveCamera&&this._cam.aspect!==e&&(this._cam.aspect=e,this._cam.updateProjectionMatrix())}get fieldOfView(){return this._cam instanceof c.PerspectiveCamera?this._cam.fov:this._fov}set fieldOfView(e){const t=this.fieldOfView!=e;if(this._fov=e,t&&this._cam&&this._cam instanceof c.PerspectiveCamera){if(this._fov===void 0){console.warn("Can not set undefined fov on PerspectiveCamera");return}this._cam.fov=this._fov,this._cam.updateProjectionMatrix()}}get nearClipPlane(){return this._nearClipPlane}set nearClipPlane(e){const t=this._nearClipPlane!=e;this._nearClipPlane=e,this._cam&&(t||this._cam.near!=e)&&(this._cam.near=e,this._cam.updateProjectionMatrix())}_nearClipPlane=.1;get farClipPlane(){return this._farClipPlane}set farClipPlane(e){const t=this._farClipPlane!=e;this._farClipPlane=e,this._cam&&(t||this._cam.far!=e)&&(this._cam.far=e,this._cam.updateProjectionMatrix())}_farClipPlane=1e3;applyClippingPlane(){this._cam&&(this._cam.near=this._nearClipPlane,this._cam.far=this._farClipPlane,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(e){if(typeof e=="string")switch(e){case"skybox":e=1;break;case"solidcolor":e=2;break;default:e=0;break}e!==this._clearFlags&&(this._clearFlags=e,this.applyClearFlagsIfIsActiveCamera())}orthographic=!1;orthographicSize=5;ARBackgroundAlpha=0;set cullingMask(e){this._cullingMask=e,this._cam&&(this._cam.layers.mask=e)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}_cullingMask=4294967295;set cullingLayer(e){this.cullingMask=(1<<e|0)>>>0}set backgroundBlurriness(e){e!==this._backgroundBlurriness&&(e===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(e,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}_backgroundBlurriness=void 0;set backgroundIntensity(e){e!==this._backgroundIntensity&&(e===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(e,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}_backgroundIntensity=void 0;set backgroundRotation(e){e!==this._backgroundRotation&&(e===void 0?this._backgroundRotation=void 0:this._backgroundRotation=e,this.applyClearFlagsIfIsActiveCamera())}get backgroundRotation(){return this._backgroundRotation}_backgroundRotation=void 0;set environmentIntensity(e){this._environmentIntensity=e}get environmentIntensity(){return this._environmentIntensity}_environmentIntensity=void 0;get backgroundColor(){return this._backgroundColor??null}set backgroundColor(e){e&&(this._backgroundColor||(this._backgroundColor=new Z(1,1,1,1)),this._backgroundColor.copy(e),(!("alpha"in e)||e.alpha===void 0)&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera())}set targetTexture(e){this._targetTexture=e}get targetTexture(){return this._targetTexture}_targetTexture=null;_backgroundColor;_fov;_cam=null;_clearFlags=2;_skybox;get cam(){return this.threeCamera}get threeCamera(){return this.activeAndEnabled&&this.buildCamera(),this._cam}static _origin=new c.Vector3;static _direction=new c.Vector3;screenPointToRay(e,t,i){const n=this.threeCamera,o=ll._origin;o.set(e,t,-1),this.context.input.convertScreenspaceToRaycastSpace(o),Yy&&console.log("screenPointToRay",e.toFixed(2),t.toFixed(2),"now:",o.x.toFixed(2),o.y.toFixed(2),"isInXR:"+this.context.isInXR),o.z=-1,o.unproject(n);const r=ll._direction.set(o.x,o.y,o.z),a=X(n);return r.sub(a),r.normalize(),i?(i.set(a,r),i):new c.Ray(a.clone(),r.clone())}_frustum;getFrustum(){return this._frustum||(this._frustum=new c.Frustum,this.updateFrustum()),this._frustum}updateFrustum(){this._frustum||(this._frustum=new c.Frustum),this._frustum.setFromProjectionMatrix(this.getProjectionScreenMatrix(this._projScreenMatrix,!0),this.context.renderer.coordinateSystem)}getProjectionScreenMatrix(e,t){return t&&this._projScreenMatrix.multiplyMatrices(this.threeCamera.projectionMatrix,this.threeCamera.matrixWorldInverse),e===this._projScreenMatrix?e:e.copy(this._projScreenMatrix)}_projScreenMatrix=new c.Matrix4;awake(){Yy&&window.addEventListener("pointerdown",e=>{const t=e.clientX,i=e.clientY;console.log("touch",t.toFixed(2),i.toFixed(2));const n=this.screenPointToRay(t,i),o="#"+Math.floor(Math.random()*16777215).toString(16);B.DrawRay(n.origin,n.direction,o,10)})}onEnable(){As&&console.log(`Camera enabled: "${this.name}". ClearFlags=${Fo[this._clearFlags]}`,this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),N1(this)),this.applyClearFlagsIfIsActiveCamera({applySkybox:!0})}onDisable(){this.context.removeCamera(this)}onLeaveXR(e){this.fieldOfView=this._fov}onBeforeRender(){if(this._cam&&(this._frustum&&this.updateFrustum(),this._clearFlags===2&&this.applyClearFlagsIfIsActiveCamera(),this._targetTexture)){this.context.isManagedExternally&&(this._warnedAboutExternalRenderer||(this._warnedAboutExternalRenderer=!0,console.warn("Rendering with external renderer is not supported yet. This may not work or throw errors. Please remove the the target texture from your camera: "+this.name,this.targetTexture))),this.context.composer;const e=this.context.renderer;if(e){const t=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,e),t?.applyClearFlags()}}}buildCamera(){if(this._cam)return;const e=this.gameObject.isCamera;let t=null;if(e?(t=this.gameObject,t?.layers.enableAll(),t instanceof c.PerspectiveCamera&&(this._fov=t.fov)):t=this.gameObject.children[0],t&&t.isCamera)t instanceof c.PerspectiveCamera&&(this._fov&&(t.fov=this._fov),t.near=this._nearClipPlane,t.far=this._farClipPlane,t.updateProjectionMatrix());else if(!this.orthographic)t=new c.PerspectiveCamera(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(t.fov=this.fieldOfView),this.gameObject.add(t);else{const i=this.orthographicSize*100;t=new c.OrthographicCamera(window.innerWidth/-i,window.innerWidth/i,window.innerHeight/i,window.innerHeight/-i,this._nearClipPlane,this._farClipPlane),this.gameObject.add(t)}this._cam=t,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(e){this.context.mainCameraComponent===this&&this.applyClearFlags(e)}applyClearFlags(e){if(!this._cam){As&&console.log("Camera does not exist (apply clear flags)");return}if(this.fieldOfView=this.fieldOfView,As){const i=`[Camera] Apply ClearFlags: ${Fo[this._clearFlags]} - "${this.name}"`;console.debug(i)}const t=this.context.domElement.getAttribute("background-image")||this.context.domElement.getAttribute("background-color");switch(this._clearFlags){case 0:return;case 1:if(ll.backgroundShouldBeTransparent(this.context)&&(!this.ARBackgroundAlpha||this.ARBackgroundAlpha<.001)){this.context.scene.background=null,this.context.renderer.setClearColor(0,0);return}(!this.scene.background||!this._skybox||e?.applySkybox===!0)&&this.applySceneSkybox(),this._backgroundBlurriness!==void 0&&!this.context.domElement.getAttribute("background-blurriness")?this.context.scene.backgroundBlurriness=this._backgroundBlurriness:As&&console.warn(`Camera "${this.name}" has no background blurriness`),this._backgroundIntensity!==void 0&&!this.context.domElement.getAttribute("background-intensity")&&(this.context.scene.backgroundIntensity=this._backgroundIntensity),this._backgroundRotation!==void 0&&!this.context.domElement.getAttribute("background-rotation")?this.context.scene.backgroundRotation=this._backgroundRotation:As&&console.warn(`Camera "${this.name}" has no background intensity`);break;case 2:if(this._backgroundColor&&!t){let i=this._backgroundColor.alpha;ll.backgroundShouldBeTransparent(this.context)&&(i=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.xr?.isVR?this.context.renderer.setClearColor(rb(this._backgroundColor).convertLinearToSRGB()):this.context.renderer.setClearColor(this._backgroundColor,i)}else this._backgroundColor||As&&console.warn(`[Camera] has no background color "${this.name}" `);break;case 4:t||(this.context.scene.background=null,this.context.renderer.setClearColor(0,0));break}}applySceneSkybox(){this._skybox||(this._skybox=new z1(this)),this._skybox.apply()}static backgroundShouldBeTransparent(e){const t=e.renderer.xr?.getSession();if(!t)return!1;if(typeof t._transparent=="boolean")return t._transparent;const i=t.environmentBlendMode;As&&Se("Environment blend mode: "+i+" on "+navigator.userAgent);let n=i==="additive"||i==="alpha-blend";return e.isInAR&&i==="opaque"&&(navigator.userAgent?.includes("OculusBrowser")||navigator.userAgent?.includes("Mozilla")&&navigator.userAgent?.includes("Mobile WebXRViewer/v2"))&&(n=!0),t._transparent=n,n}};It([f()],xt.prototype,"aspect",1);It([f()],xt.prototype,"fieldOfView",1);It([f()],xt.prototype,"nearClipPlane",1);It([f()],xt.prototype,"farClipPlane",1);It([f()],xt.prototype,"clearFlags",1);It([f()],xt.prototype,"orthographic",2);It([f()],xt.prototype,"orthographicSize",2);It([f()],xt.prototype,"ARBackgroundAlpha",2);It([f()],xt.prototype,"cullingMask",1);It([f()],xt.prototype,"backgroundBlurriness",1);It([f()],xt.prototype,"backgroundIntensity",1);It([f(c.Euler)],xt.prototype,"backgroundRotation",1);It([f()],xt.prototype,"environmentIntensity",1);It([f(Z)],xt.prototype,"backgroundColor",1);It([f(xn)],xt.prototype,"targetTexture",1);let Vt=xt;class z1{_camera;_skybox;get context(){return this._camera?.context}constructor(e){this._camera=e}apply(){if(this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),!this._skybox)this._did_log_failed_to_find_skybox||(this._did_log_failed_to_find_skybox=!0,console.warn(`Camera "${this._camera.name}" has no skybox texture. ${this._camera.sourceId}`));else if(this.context.scene.background!==this._skybox){const e=this.context.domElement.getAttribute("background-image")||this.context.domElement.getAttribute("background-color");As&&console.debug(`[Camera] Apply Skybox ${this._skybox?.name} ${e} - "${this._camera.name}"`),e?.length||(this._skybox.mapping=c.EquirectangularReflectionMapping,this.context.scene.background=this._skybox)}}}function N1(s){x("freecam")&&s.context.mainCameraComponent===s&&S.getOrAddComponent(s.gameObject,de)}class ts extends k{get listener(){return this._listener==null&&(this._listener=new c.AudioListener),this._listener}_listener=null;onEnable(){en.registerWaitForInteraction(this.onInteraction),this.addListenerIfItExists()}onDisable(){en.unregisterWaitForInteraction(this.onInteraction),this.removeListenerIfItExists()}onInteraction=()=>{this.destroyed||this.listener==null||this.addListenerIfItExists()};addListenerIfItExists(){const e=this._listener;if(!e||e?.parent)return;const t=this.context.mainCameraComponent||S.getComponentInParent(this.gameObject,Vt);t?.threeCamera?t.threeCamera.add(e):this.gameObject.add(e),e.filter?(e.gain.connect(e.filter),e.filter.connect(e.context.destination)):e.gain.connect(e.context.destination)}removeListenerIfItExists(){const e=this._listener;e&&(e.removeFromParent(),e.filter&&e.filter.disconnect(),e.gain&&e.gain.disconnect())}}var V1=Object.defineProperty,$1=Object.getOwnPropertyDescriptor,on=(s,e,t,i)=>{for(var n=i>1?void 0:i?$1(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&&V1(e,t,n),n};const lt=x("debugaudio"),Ui=class Ls extends k{static get userInteractionRegistered(){return en.userInteractionRegistered}static registerWaitForAllowAudio(e){en.registerWaitForInteraction(e)}clip="";playOnAwake=!1;preload=!0;playInBackground=!0;get isPlaying(){return this.sound?.isPlaying??!1}get duration(){return this.sound?.buffer?.duration}get time01(){const e=this.duration;return e&&this.sound?this.sound?.context.currentTime/e:0}set time01(e){const t=this.duration;t&&this.sound&&(this.time=e*t)}get time(){return this.sound?.source?this.sound.source?.context.currentTime-this._lastContextTime+this.sound.offset:0}set time(e){if(this.sound){if(e===this.sound.offset)return;const t=this.isPlaying;this.stop(),this.sound.offset=e,t&&this.play()}}get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(e){this._loop=e,this.sound&&this.sound.setLoop(e)}get spatialBlend(){return this._spatialBlend}set spatialBlend(e){e!==this._spatialBlend&&(this._spatialBlend=e,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(e){this._minDistance!==e&&(this._minDistance=e,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(e){this._maxDistance!==e&&(this._maxDistance=e,this._needUpdateSpatialDistanceSettings=!0)}_spatialBlend=0;_minDistance=1;_maxDistance=100;get volume(){return this._volume}set volume(e){this._volume=e,this.sound&&!this.context.application.muted&&(lt&&console.log(this.name,"audio set volume",e),this.sound.setVolume(e))}_volume=1;set pitch(e){this.sound&&this.sound.setPlaybackRate(e)}get pitch(){return this.sound?this.sound.getPlaybackRate():1}rollOffMode=0;_loop=!1;sound=null;helper=null;wasPlaying=!1;audioLoader=null;shouldPlay=!1;_lastClipStartedLoading=null;_audioElement=null;get Sound(){if(!this.sound&&Ls.userInteractionRegistered){let e=this.gameObject.getComponent(ts)??this.context.mainCamera.getComponent(ts)??lc(ts,this.context,!1);!e&&this.context.mainCamera&&(e=this.context.mainCamera.addComponent(ts)),e?.listener?(this.sound=new c.PositionalAudio(e.listener),this.gameObject?.add(this.sound)):lt&&console.warn("No audio listener found in scene - can not play audio")}return this.sound}get ShouldPlay(){return this.shouldPlay}get audioContext(){return this.sound?.context}awake(){lt&&console.log("[AudioSource]",this),this.audioLoader=new c.AudioLoader,this.playOnAwake&&(this.shouldPlay=!0),this.preload&&typeof this.clip=="string"&&this.audioLoader.load(this.clip,this.createAudio,()=>{},console.error)}onEnable(){this.sound&&this.gameObject.add(this.sound),Ls.userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():Ls.registerWaitForAllowAudio(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.onNewClip(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(Qf.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(Qf.MuteChanged,this.onApplicationMuteChanged),this.pause()}onVisibilityChanged=()=>{switch(document.visibilityState){case"hidden":(this.playInBackground===!1||exports.DeviceUtilities.isMobileDevice())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":lt&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,Ls.userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&Ls.userInteractionRegistered&&this.wasPlaying&&this.play();break}};onApplicationMuteChanged=()=>{this.context.application.muted?this.sound?.setVolume(0):this.sound?.setVolume(this.volume)};createAudio=e=>{if(this.destroyed){lt&&console.warn("AudioSource destroyed, not creating audio",this.name);return}lt&&console.log("AudioBuffer finished loading",e);const t=this.Sound;if(!t){lt&&console.warn("Failed getting sound?",this.name);return}t.isPlaying&&t.stop(),e&&t.setBuffer(e),t.loop=this._loop,this.context.application.muted?t.setVolume(0):t.setVolume(this.volume),t.autoplay=this.shouldPlay&&Ls.userInteractionRegistered,this.applySpatialDistanceSettings(),t.isPlaying&&t.stop(),Ls.registerWaitForAllowAudio(this.__onAllowAudioCallback)};__onAllowAudioCallback=()=>{this.shouldPlay&&this.play()};applySpatialDistanceSettings(){const e=this.sound;if(!e)return;this._needUpdateSpatialDistanceSettings=!1;const t=D.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(lt&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+t),e.setRefDistance(t),e.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:e.setDistanceModel("exponential");break;case 1:e.setDistanceModel("linear");break;case 2:console.warn("Custom rolloff for AudioSource is not supported: "+this.name);break}this.spatialBlend>0?lt&&!this.helper&&(this.helper=new q.PositionalAudioHelper(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}async onNewClip(e){if(e&&(this.clip=e),typeof e=="string")if(lt&&console.log(e),e.endsWith(".mp3")||e.endsWith(".wav")){if(this.audioLoader||(this.audioLoader=new c.AudioLoader),this.shouldPlay=!0,this._lastClipStartedLoading===e){lt&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=e,lt&&console.log("load audio",e);const t=await this.audioLoader.loadAsync(e).catch(console.error);if(this.destroyed)return;this._lastClipStartedLoading===e&&(this._lastClipStartedLoading=null),t&&this.createAudio(t)}else console.warn("Unsupported audio clip type",e);else this.shouldPlay=!0,this.createAudio()}play(e=void 0){!e&&this.clip&&(e=this.clip),e!==void 0&&typeof e!="string"&&!(e instanceof MediaStream)&&(A()&&console.warn("Called play on AudioSource with unknown argument type:",e+`
|
|
950
950
|
Using the assigned clip instead:`,this.clip),e=this.clip);let t=!this.sound||e&&e!==this.clip;if(typeof e=="string"&&!this.audioLoader&&(t=!0),(e instanceof MediaStream||typeof e=="string")&&(this.clip=e),t){this.shouldPlay=!0,this.onNewClip(e);return}if(this.shouldPlay=!0,this._hasEnded=!1,lt&&console.log("play",this.sound?.getVolume(),this.sound),this.sound&&!this.sound.isPlaying){const i=this.context.application.muted;i&&this.sound.setVolume(0),this.gameObject?.add(this.sound),this.clip instanceof MediaStream?(this.sound.setMediaStreamSource(this.clip),this._audioElement||(this._audioElement=document.createElement("audio"),this._audioElement.style.display="none"),this._audioElement.parentNode||this.context.domElement.shadowRoot?.append(this._audioElement),this._audioElement.srcObject=this.clip,this._audioElement.autoplay=!1):(this._audioElement&&this._audioElement.remove(),this.sound.play(i?.1:0))}}pause(){lt&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&this.sound.source&&(this._lastContextTime=this.sound?.context.currentTime,this.sound.pause()),this._audioElement?.remove()}stop(){lt&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.source&&(this._lastContextTime=this.sound?.context.currentTime,lt&&console.log(this._lastContextTime),this.sound.stop()),this._audioElement?.remove()}_lastContextTime=0;_hasEnded=!0;_needUpdateSpatialDistanceSettings=!1;update(){this.helper&&(this.isPlaying&&this.helper.update(),this.helper.visible=this.isPlaying),this._needUpdateSpatialDistanceSettings&&this.applySpatialDistanceSettings(),this.sound&&!this.sound.isPlaying&&this.shouldPlay&&!this._hasEnded&&(this._hasEnded=!0,lt&&console.log("Audio clip ended",this.clip),this.dispatchEvent(new CustomEvent("ended",{detail:this})))}};on([f(URL)],Ui.prototype,"clip",2);on([f()],Ui.prototype,"playOnAwake",2);on([f()],Ui.prototype,"preload",2);on([f()],Ui.prototype,"playInBackground",2);on([f()],Ui.prototype,"loop",1);on([f()],Ui.prototype,"spatialBlend",1);on([f()],Ui.prototype,"minDistance",1);on([f()],Ui.prototype,"maxDistance",1);on([f()],Ui.prototype,"volume",1);on([f()],Ui.prototype,"pitch",1);on([f()],Ui.prototype,"rollOffMode",2);let Di=Ui;const W1=x("debugavatar");class we extends k{static getAvatar(e){return e>=0&&e<we.instances.length?we.instances[e]:null}static instances=[];static onAvatarMarkerCreated(e){return we._onNewAvatarMarkerAdded.push(e),e}static onAvatarMarkerDestroyed(e){return we._onAvatarMarkerDestroyed.push(e),e}static _onNewAvatarMarkerAdded=[];static _onAvatarMarkerDestroyed=[];connectionId;avatar;awake(){we.instances.push(this),W1&&console.log(this);for(const e of we._onNewAvatarMarkerAdded)e({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){we.instances.splice(we.instances.indexOf(this),1);for(const e of we._onAvatarMarkerDestroyed)e({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}}class Uo{static Pois=[];static LastChangeTime=0;static Add(e,t,i=null){if(t){for(const n of this.Pois)if(n.obj===t)return;this.Pois.push({obj:t,avatar:i}),this.LastChangeTime=e.time.time}}static Remove(e,t){if(t){for(const i of this.Pois)if(i.obj===t){this.Pois.splice(this.Pois.indexOf(i),1),this.LastChangeTime=e?.time.time??F.Current?.time.time;return}}}}class G1{guid;position=new c.Vector3}class $l extends k{set controlledTarget(e){this.target=e;const t=P.get("MoveRandom");if(t&&this.target){const i=S.getComponent(this.target,t);i&&i.destroy()}}target=null;avatar=null;_model=null;_targetModel=new G1;_currentTargetObject=null;_lastUpdateTime=0;_lookDuration=0;_lastPoiChangedTime=0;awake(){if(this.avatar=S.getComponentInParent(this.gameObject,we),this.avatar){const e=S.getComponentInParent(this.gameObject,we);this._model=new im(this.context.connection,this.guid),e?.isLocalAvatar&&this._model.requestOwnership()}this.context.connection.beginListen("avatar-look-target-changed",e=>{this.target&&e&&e.guid===this.avatar?.guid&&Ye(this.target,e.position)})}update(){if((!this.context.connection.isConnected||this._model?.hasOwnership)&&(Uo.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=Uo.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){const t=X(this._currentTargetObject);Ye(this.target,t),this.context.connection.isConnected&&this.avatar&&(this.context.connection.send("avatar-look-target-changed",this._targetModel),this._targetModel.guid=this.avatar.guid,this._targetModel.position.copy(t))}}selectTarget(){if(this.context.time.time-this._lastUpdateTime>this._lookDuration){this._lastUpdateTime=this.context.time.time,this._lookDuration=Math.random()*.5+.2;const t=Uo.Pois;if(t.length>0){const i=t[Math.floor(Math.random()*t.length)];if(i&&i.obj){if(i.avatar&&i.avatar===this.avatar)return;this._currentTargetObject=i.obj}}}}}function X0(s){const e=s;return!!(e.parser&&e.parser.json)}var Xd=(s=>(s[s.None=0]="None",s[s.DontExport=1]="DontExport",s))(Xd||{});function Q0(s){return s&&s.isComponent}const H1=Symbol("object"),rf=new ai(()=>new c.Vector3,20);class Y0{_point;_normal;_tangentVelocity;distance;impulse;friction;get point(){return rf.get().set(this._point.x,this._point.y,this._point.z)}get normal(){return rf.get().set(this._normal.x,this._normal.y,this._normal.z)}get tangentVelocity(){return rf.get().set(this._tangentVelocity.x,this._tangentVelocity.y,this._tangentVelocity.z)}constructor(e,t,i,n,o,r){this._point=e,this.distance=t,this._normal=i,this.impulse=n,this.friction=o,this._tangentVelocity=r}}class K0{contacts;constructor(e,t,i){this.me=e,this._collider=t,this._gameObject=t.gameObject,this.contacts=i}me;_collider;get collider(){return this._collider}_gameObject;get gameObject(){return this._gameObject}get rigidBody(){return this.collider?.attachedRigidbody}}class Z0{object;collider;constructor(e,t){this.object=e,this.collider=t}}const Me=x("debugnetworkingstreams");var wn=(s=>(s.Connected="peer-user-connected",s.StreamReceived="receive-stream",s.StreamEnded="call-ended",s.Disconnected="peer-user-disconnected",s.UserJoined="user-joined",s))(wn||{});class Cm{type="call-ended";userId;direction;constructor(e,t){this.userId=e,this.direction=t}}class J0{type="receive-stream";userId;stream;target;constructor(e,t,i){this.userId=e,this.stream=t,this.target=i}}class q1{guid;peerId;dontSave=!0;constructor(e,t){this.guid=e.id,this.peerId=t}}var ev=(s=>(s.Incoming="incoming",s.Outgoing="outgoing",s))(ev||{});class X1 extends c.EventDispatcher{peerId;userId;direction;call;get stream(){return this._stream}_stream=null;_isDisposed=!1;close(){this._isDisposed||(this._isDisposed=!0,this.call.close(),Sn(this._stream))}get isOpen(){return this.call.peerConnection?.connectionState==="connected"}get isOpening(){return this.call.peerConnection?.connectionState==="connecting"}get isClosed(){return!this.isOpen||this._isDisposed}constructor(e,t,i,n=null){super(),this.peerId=t.peer,this.userId=e,this.call=t,this.direction=i,this._stream=n,t.on("stream",o=>{if(Me&&console.log("Receive stream",`
|
|
951
951
|
Audio:`,o.getAudioTracks(),`
|
|
952
952
|
Video:`,o.getVideoTracks()),this._stream=o,i==="incoming"){const r=new J0(e,o,this);this.dispatchEvent(r)}}),t.on("close",()=>{this.dispatchEvent(new Cm(e,i))})}}function Ky(s){return s=s.replace("a=fmtp:111 minptime=10;useinbandfec=1","a=fmtp:111 ptime=5;useinbandfec=1;stereo=1;maxplaybackrate=48000;maxaveragebitrat=128000;sprop-stereo=1"),s}class is extends c.EventDispatcher{static instances=new Map;static getOrCreate(e,t){if(is.instances.has(t))return is.instances.get(t);const i=new is(e,t);return is.instances.set(t,i),i}getMyPeerId(){if(this.context.connection.connectionId)return this.getPeerIdFromUserId(this.context.connection.connectionId)}getPeerIdFromUserId(e){return this.id+"-"+e}getUserIdFromPeerId(e){return e.substring(this.id.length+1)}makeCall(e,t){if(!t?.id){Me?console.warn("Can not make a call: mediastream has no id or is undefined"):console.debug("Can not make a call: mediastream has no id or is undefined");return}const i={metadata:{userId:this.context.connection.connectionId,streamId:t.id},sdpTransform:o=>Ky(o)},n=this._peer?.call(e,t,i);if(n){const o=this.registerCall(n,"outgoing",t);return Me&&console.warn(`📞 CALL ${e}`,`
|
|
@@ -973,7 +973,7 @@ Consider registering a custom loader via the 'onCreateCustomModelLoader' callbac
|
|
|
973
973
|
Content-Type: "${t.headers.get("content-type")}
|
|
974
974
|
"Text: "${o}"
|
|
975
975
|
Binary:`,i)}else console.debug("Could not determine file type from binary data");return"unknown"}var gP=Object.defineProperty,ba=(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&&gP(e,t,n),n};const ti=x("debugdroplistener");class yP extends CustomEvent{constructor(e){super("object-added",{detail:e})}}const _P="blob";class ds extends k{dropArea;fitIntoVolume=!1;fitVolumeSize=new c.Vector3(1,1,1);placeAtHitPosition=!0;useNetworking=!1;onDropped=new ae;loadFromURL(e,t){return this.addFromUrl(e,{screenposition:new c.Vector2,point:t?.point,size:t?.size},!1)}forgetObjects(){this.removePreviouslyAddedObjects(!1)}onEnable(){this.context.renderer.domElement.addEventListener("dragover",this.onDrag),this.context.renderer.domElement.addEventListener("drop",this.onDrop),window.addEventListener("paste",this.handlePaste),this.context.connection.beginListen("droplistener",this.onNetworkEvent)}onDisable(){this.context.renderer.domElement.removeEventListener("dragover",this.onDrag),this.context.renderer.domElement.removeEventListener("drop",this.onDrop),window.removeEventListener("paste",this.handlePaste),this.context.connection.stopListen("droplistener",this.onNetworkEvent)}onNetworkEvent=e=>{if(!this.useNetworking){ti&&console.debug("[DropListener] Ignoring networked event because networking is disabled",e);return}if(e.guid?.startsWith(this.guid)){const t=e.url;if(console.debug("[DropListener] Received networked event",e),t)if(Array.isArray(t))for(const i of t)this.addFromUrl(i,{screenposition:new c.Vector2,point:e.point,size:e.size},!0);else this.addFromUrl(t,{screenposition:new c.Vector2,point:e.point,size:e.size},!0)}};handlePaste=e=>{if(this.context.connection.allowEditing===!1||e.defaultPrevented)return;navigator.clipboard.readText().then(i=>{if(i&&(i.startsWith("http")||i.startsWith("https")||i.startsWith("blob"))){const o={screenposition:new c.Vector2(this.context.input.mousePosition.x,this.context.input.mousePosition.y)};this.testIfIsInDropArea(o)&&this.addFromUrl(i,o,!1)}}).catch(console.warn)};onDrag=e=>{this.context.connection.allowEditing!==!1&&e.preventDefault()};onDrop=async e=>{if(this.context.connection.allowEditing===!1||(ti&&console.log(e),!e?.dataTransfer)||e["droplistener:handled"])return;e.preventDefault();const t={screenposition:new c.Vector2(e.offsetX,e.offsetY)};if(this.dropArea&&this.testIfIsInDropArea(t)===!1)return;e["droplistener:handled"]=!0;const i=e.dataTransfer.items;if(!i)return;const n=[];for(const o in i){const r=i[o];if(r.kind==="file"){const a=r.getAsFile();if(!a)continue;n.push(a)}else r.kind==="string"&&r.type=="text/plain"&&r.getAsString(a=>{this.addFromUrl(a,t,!1)})}n.length>0&&await this.addFromFiles(n,t)};async addFromUrl(e,t,i){ti&&console.log("dropped url",e);try{if(e.startsWith("https://github.com/")){const r=e.split("/"),a=r[3],l=r[4],h=r[6],d=r.slice(7).join("/");e=`https://raw.githubusercontent.com/${a}/${l}/${h}/${d}`}else e.startsWith("https://polyhaven.com/a")&&(e=bP(e));if(!e)return null;const n=e.toLowerCase();if(n.endsWith(".hdr")||n.endsWith(".hdri")||n.endsWith(".exr")||n.endsWith(".png")||n.endsWith(".jpg")||n.endsWith(".jpeg"))return console.warn(`Fileformat is not supported: ${n}`),null;this.removePreviouslyAddedObjects();const o=await gd.loadFileFromURL(new URL(e),{guid:this.guid,context:this.context,parent:this.gameObject,point:t.point,size:t.size});if(o&&this._addedObjects.length<=0)return t.url=e,this.onObjectLoaded(o,t,i)}catch{console.warn("String is not a valid URL",e)}return null}_abort=null;async addFromFiles(e,t){if(ti&&console.log("Add files",e),!!Array.isArray(e)&&e.length){this.deleteDropEvent(),this.removePreviouslyAddedObjects(),Il(_P,null),this._abort?.abort("New files dropped"),this._abort=new AbortController;for(const i of e){if(!i)continue;if(i.type.startsWith("image/")){ti&&console.warn("Ignoring dropped image file",i.name,i.type);continue}else if(i.name.endsWith(".bin")){ti&&console.warn("Ignoring dropped binary file",i.name,i.type);continue}console.debug("Load file "+i.name+" + "+i.type);const n=await gd.loadFile(i,this.context,{guid:this.guid});if(n){this.dispatchEvent(new CustomEvent("file-dropped",{detail:i})),t.file=i;const o=this.onObjectLoaded(n,t,!1);o&&this.context.connection.isConnected&&this.useNetworking&&(console.debug("Uploading dropped file to blob storage"),exports.BlobStorage.upload(i,{abort:this._abort?.signal}).then(r=>{r?.download_url&&this._addedObjects.includes(o)&&this.sendDropEvent(r.download_url,o,n.contentMD5)}).catch(console.warn));break}}}}_addedObjects=new Array;_addedModels=new Array;removePreviouslyAddedObjects(e=!0){if(e)for(const t of this._addedObjects)t.parent===this.gameObject&&li(t,!0,!0);this._addedObjects.length=0,this._addedModels.length=0}onObjectLoaded(e,t,i){const{model:n,contentMD5:o}=e;if(ti&&console.log(`Dropped ${this.gameObject.name}`,n),!n?.scene)return console.warn("No object specified to add to scene",n),null;this.removePreviouslyAddedObjects();const r=n.scene;this.gameObject.attach(r),r.position.set(0,0,0),r.quaternion.identity(),this._addedObjects.push(r),this._addedModels.push(n);const a=new c.Box3().setFromCenterAndSize(new c.Vector3(0,this.fitVolumeSize.y*.5,0).add(this.gameObject.worldPosition),this.fitVolumeSize);if(ti&&B.DrawWireBox3(a,255,5),this.fitIntoVolume&&ub(r,a,{position:!this.placeAtHitPosition}),this.placeAtHitPosition&&t&&t.screenposition){r.visible=!1;const h=this.context.physics.raycast({screenPoint:this.context.input.convertScreenspaceToRaycastSpace(t.screenposition.clone())});if(r.visible=!0,h&&h.length>0)for(const d of h){const u=d.point.clone();ti&&console.log("Place object at hit",d),fb(r,u);break}}ra.autoplayAnimations(n);const l=new yP({sender:this,gltf:n,model:n,object:r,contentMD5:o,dropped:t.file||(t.url?new URL(t.url):void 0)});return this.dispatchEvent(l),this.onDropped?.invoke(l.detail),!i&&t.url?.startsWith("http")&&this.context.connection.isConnected&&r&&this.sendDropEvent(t.url,r,o),r}async sendDropEvent(e,t,i){if(!this.useNetworking){ti&&console.debug("[DropListener] Ignoring networked event because networking is disabled",e);return}if(this.context.connection.isConnected){console.debug('Sending drop event "'+t.name+'"',e);const n=Wt([t]),o={name:t.name,guid:this.guid,url:e,point:t.worldPosition.clone(),size:n.getSize(new c.Vector3),contentMD5:i};this.context.connection.send("droplistener",o)}}deleteDropEvent(){this.context.connection.sendDeleteRemoteState(this.guid)}testIfIsInDropArea(e){if(this.dropArea){const t=this.context.input.convertScreenspaceToRaycastSpace(e.screenposition.clone());if(!this.context.physics.raycast({targets:[this.dropArea],screenPoint:t,recursive:!0,testObject:n=>!this._addedObjects.includes(n)}).length)return A()&&console.log(`Dropped outside of drop area for DropListener "${this.name}".`),!1}return!0}}ba([f(c.Object3D)],ds.prototype,"dropArea");ba([f()],ds.prototype,"fitIntoVolume");ba([f(c.Vector3)],ds.prototype,"fitVolumeSize");ba([f()],ds.prototype,"placeAtHitPosition");ba([f()],ds.prototype,"useNetworking");ba([f(ae)],ds.prototype,"onDropped");function bP(s){if(!s.startsWith("https://polyhaven.com/"))return s;const e="https://dl.polyhaven.org/file/ph-assets/Models/gltf/4k/",n=new URL(s).pathname.split("/").pop(),o=`${e}${n}/${n}_4k.gltf`;return console.log("Resolved polyhaven asset url",s,"→",o),o}var gd;(s=>{async function e(i,n,o){const r=o.guid,a=new ft(r),l=new Blob([i],{type:i.type||lv(i.name)||void 0}),h=URL.createObjectURL(l),d=await Ji().loadSync(n,h,i.name,a).catch(u=>(console.error(`Failed to load file "${i.name}" (${i.type}):`,u),null));return URL.revokeObjectURL(h),d?new Promise((u,p)=>{const m=new FileReader;m.readAsArrayBuffer(i),m.onloadend=async y=>{const b=m.result,g=exports.BlobStorage.hashMD5(b);return u({model:d,contentMD5:g})}}):(console.warn(`Failed to load "${i.name}" (${i.type})`),null)}s.loadFile=e;async function t(i,n){return new Promise(async(o,r)=>{const a=new ft(n.guid),l=i.toString();ti&&B.DrawWireSphere(n.point,.1,16711680,3);const h=exports.PreviewHelper.addPreview({guid:n.guid,parent:n.parent,position:n?.point,size:n?.size}),d=await Ji().loadSync(n.context,l,l,a,u=>{h.onProgress(u.loaded/u.total)}).catch(console.warn);if(d){const u=await fetch(l).then(m=>m.arrayBuffer()),p=exports.BlobStorage.hashMD5(u);ti?setTimeout(()=>exports.PreviewHelper.removePreview(n.guid),3e3):exports.PreviewHelper.removePreview(n.guid),o({model:d,contentMD5:p})}else ti?setTimeout(()=>exports.PreviewHelper.removePreview(n.guid),3e3):exports.PreviewHelper.removePreview(n.guid),console.warn("Unsupported file type: "+i.toString())})}s.loadFileFromURL=t})(gd||(gd={}));var vP=Object.defineProperty,jm=(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&&vP(e,t,n),n};const Jd=class dv extends k{parent=null;object=null;limitCount=60;_currentCount=0;_startPosition=null;_startQuaternion=null;start(){if(this._currentCount=0,this._startPosition=null,this._startQuaternion=null,this.object||(this.object=this.gameObject),this.object){if(this.object===this.gameObject){const t=new ft(this.guid);this.object=S.instantiate(this.object,{idProvider:t,keepWorldPosition:!1}),S.getComponent(this.object,dv)?.destroy();let n=this.object.getComponentInChildren(Mo);n||(n=this.object.addComponent(Mo,{dragMode:Im.SnapToSurfaces}),n.guid=t.generateUUID());let o=S.getComponent(n.gameObject,tn);o||(o=n.gameObject.addComponent(tn),o.guid=t.generateUUID())}this.object.visible=!1;const e=this.gameObject.getComponent(Mo);e&&(e.enabled=!1),this._startPosition=this.object.position?.clone()??new c.Vector3(0,0,0),this._startQuaternion=this.object.quaternion?.clone()??new c.Quaternion(0,0,0,1)}this.gameObject.getComponentInParent(ci)||this.gameObject.addComponent(ci)}onEnable(){this.startCoroutine(this.cloneLimitIntervalFn())}_forwardPointerEvents=new Map;onPointerEnter(e){e.used||this.object&&this.context.connection.allowEditing&&e.button===0&&this.context.input.setCursor("pointer")}onPointerExit(e){e.used||this.object&&this.context.connection.allowEditing&&e.button===0&&this.context.input.unsetCursor("pointer")}onPointerDown(e){if(e.used||!this.object||!this.context.connection.allowEditing||e.button!==0)return;const t=this.handleDuplication();if(t){const i=S.getComponent(t,Mo);i?(i.onPointerDown(e),this._forwardPointerEvents.set(e.event.space,i)):A()&&console.warn(`Duplicated object (${t.name}) does not have DragControls`)}else this._currentCount>=this.limitCount?console.warn(`[Duplicatable] Limit of ${this.limitCount} objects created within a few seconds reached. Please wait a moment before creating more objects.`):console.warn("[Duplicatable] Could not duplicate object.")}onPointerUp(e){if(e.used)return;const t=this._forwardPointerEvents.get(e.event.space);t&&(t.onPointerUp(e),this._forwardPointerEvents.delete(e.event.space))}*cloneLimitIntervalFn(){for(;this.activeAndEnabled&&!this.destroyed;)this._currentCount>0?this._currentCount-=1:this._currentCount<0&&(this._currentCount=0),yield mm(1)}handleDuplication(){if(!this.object||this.limitCount>0&&this._currentCount>=this.limitCount||this.object===this.gameObject)return null;if(S.isDestroyed(this.object))return this.object=null,null;this.object.visible=!0,this._startPosition&&this.object.position.copy(this._startPosition),this._startQuaternion&&this.object.quaternion.copy(this._startQuaternion);const e=new sn;this.parent||(this.parent=this.gameObject.parent),this.parent&&(e.parent=this.parent.guid??this.parent.userData?.guid,e.keepWorldPosition=!0),e.position=this.worldPosition,e.rotation=this.worldQuaternion,e.context=this.context,this._currentCount+=1;const t=S.instantiateSynced(this.object,e);return console.assert(t!==this.object,"Duplicated object is original"),this.object.visible=!1,this._startPosition&&this.object.position.clone().copy(this._startPosition),this._startQuaternion&&this.object.quaternion.clone().copy(this._startQuaternion),t}};jm([f(c.Object3D)],Jd.prototype,"parent");jm([f(c.Object3D)],Jd.prototype,"object");jm([f()],Jd.prototype,"limitCount");let Bm=Jd;var Hn=(s=>(s[s.PointerEnter=0]="PointerEnter",s[s.PointerExit=1]="PointerExit",s[s.PointerDown=2]="PointerDown",s[s.PointerUp=3]="PointerUp",s[s.PointerClick=4]="PointerClick",s[s.Drag=5]="Drag",s[s.Drop=6]="Drop",s[s.Scroll=7]="Scroll",s[s.UpdateSelected=8]="UpdateSelected",s[s.Select=9]="Select",s[s.Deselect=10]="Deselect",s[s.Move=11]="Move",s[s.InitializePotentialDrag=12]="InitializePotentialDrag",s[s.BeginDrag=13]="BeginDrag",s[s.EndDrag=14]="EndDrag",s[s.Submit=15]="Submit",s[s.Cancel=16]="Cancel",s))(Hn||{}),xP=Object.defineProperty,Fm=(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&&xP(e,t,n),n};class Um{eventID;callback=new ae}Fm([f()],Um.prototype,"eventID");Fm([f(ae)],Um.prototype,"callback");class eu extends k{triggers=[];invoke(e){if(this.triggers)for(const t of this.triggers)t.eventID===e&&t.callback?.invoke()}hasTrigger(e){return this.triggers?.some(t=>t.eventID===e)??!1}shouldChangeCursor(){return this.hasTrigger(Hn.PointerClick)||this.hasTrigger(Hn.PointerDown)||this.hasTrigger(Hn.PointerUp)}onPointerClick(e){this.invoke(Hn.PointerClick)}onPointerEnter(e){this.shouldChangeCursor()&&this.context.input.setCursor("pointer"),this.invoke(Hn.PointerEnter)}onPointerExit(e){this.shouldChangeCursor()&&this.context.input.unsetCursor("pointer"),this.invoke(Hn.PointerExit)}onPointerDown(e){this.invoke(Hn.PointerDown)}onPointerUp(e){this.invoke(Hn.PointerUp)}}Fm([f(Um)],eu.prototype,"triggers");class uv{writer;constructor(e){this.writer=e}writeNode(e){}}class wP extends uv{beforeWriteNode(e,t){B.isGizmo(e)&&(t.keep=!1)}}class fv extends uv{beforeWriteTexture(e,t){e.isRenderTargetTexture&&(t.newTexture=gm(new Z(1,1,1,0)))}}function yp(s){const e=Xd.DontExport;return!(s.hideFlags&e)}const hf=x("debugexr");class SP{get name(){return"EXT_texture_exr"}parser;constructor(e){this.parser=e,hf&&console.log(e)}loadTexture(e){const t=this.name,i=this.parser,o=i.json.textures[e];if(hf&&console.log("EXT_texture_exr.loadTexture",e,o),!o.extensions||!o.extensions[t])return null;const r=o.extensions[t],a=new q.EXRLoader(i.options.manager);return hf&&console.log("EXT_texture_exr.loadTexture",r),i.loadTextureImage(e,r.source,a)}}typeof window<"u"&&window.addEventListener("unhandledrejection",s=>{});const Nn=st,uh="$___Export_Components",CP="NEEDLE_components";class PP{[wo]}class OP{node;nodeIndex;nodeDef;constructor(e,t,i){this.node=e,this.nodeIndex=t,this.nodeDef=i}}class pv{get name(){return CP}parser;nodeToObjectMap={};gltf=null;exportContext;objectToNodeMap={};context;writer;registerExport(e){e.register(t=>{if("serializeUserData"in t){const i=t.serializeUserData.bind(t);this.writer=t,t.serializeUserData=(n,o)=>{try{this.serializeUserData(n,o)&&(t.extensionsUsed[this.name]=!0),i(n,o)}finally{this.afterSerializeUserData(n,o)}}}return this})}beforeParse(){this.exportContext={},this.objectToNodeMap={}}serializeUserData(e,t){const i=e.userData?.components;return!i||i.length<=0?!1:(delete e.userData.components,e[uh]=i,!0)}afterSerializeUserData(e,t){if(e.type==="Scene"&&Nn&&console.log("DONE",JSON.stringify(t)),e[uh]===void 0)return;const i=e[uh];delete e[uh],i!==null&&(e.userData.components=i)}writeNode(e,t){const i=this.writer.json.nodes.length;Nn&&console.log(e.name,i,e.uuid);const n=new OP(e,i,t);this.exportContext[i]=n,this.objectToNodeMap[e.uuid]=i}afterParse(e){Nn&&console.log("AFTER",e);for(const t in this.exportContext){const i=this.exportContext[t],n=i.node,o=i.nodeDef,r=i.nodeIndex,a=n.userData?.components;if(!a||a.length<=0)continue;const l=new PP;o.extensions=o.extensions||{},o.extensions[this.name]=l,this.context.object=n,this.context.nodeId=r,this.context.objectToNode=this.objectToNodeMap;const h=[];for(const d of a){this.context.target=d;const u=Ji().writeBuiltinComponentData(d,this.context);u!==null&&h.push(u)}h.length>0&&(l[wo]=h,Nn&&console.log("DID WRITE",n,"nodeIndex",r,h))}}beforeRoot(){return Nn&&console.log("BEGIN LOAD"),this.nodeToObjectMap={},null}async afterRoot(e){this.gltf=e;const t=e.parser,i=t?.extensions;if(!i)return;const n=i[this.name];Nn&&console.log("After root",e,this.parser,i);const o=[];if(n===!0){const r=t.json.nodes;if(r){for(let a=0;a<r.length;a++){const l=await t.getDependency("node",a);this.nodeToObjectMap[a]=l}for(let a=0;a<r.length;a++){const l=r[a],h=a,d=l.extensions;if(!d)continue;const u=d[this.name];if(!u)continue;Nn&&console.log("NODE",l);const p=this.nodeToObjectMap[h];if(!p){console.error("Could not find object for node index: "+h,l,t);continue}Ud(p),o.push(this.createComponents(p,u))}}}await Promise.all(o);for(const r of t.associations.keys()){const a=t.associations.get(r);if(a?.materials!=null){const l="/materials/"+a.materials;ZS(r,l)}}}async createComponents(e,t){if(!t)return;const i=t[wo];if(i){const n=new Array;Nn&&console.log(e.name,i);for(const o in i){const r=i[o];Nn&&console.log("Serialized data",JSON.parse(JSON.stringify(r))),r&&this.parser&&n.push(dm(this.parser,r).catch(a=>console.error(`Error while resolving references (see console for details)
|
|
976
|
-
`,a,e,r))),e.userData=e.userData||{},e.userData[wo]=e.userData[wo]||[],e.userData[wo].push(r)}await Promise.all(n).catch(o=>{console.error("Error while loading components",o)})}}}const t_="NEEDLE_gameobject_data";class MP{get name(){return t_}parser;constructor(e){this.parser=e}afterRoot(e){const t=[];for(let i=0;i<this.parser.json.nodes?.length;i++){const n=this.parser.json.nodes[i];if(n&&n.extensions){const o=n.extensions[t_];if(o){const r=this.findAndApplyExtensionData(i,o);t.push(r)}}}return Promise.all(t).then(()=>null)}async findAndApplyExtensionData(e,t){const i=await this.parser.getDependency("node",e);i&&this.applyExtensionData(i,t)}applyExtensionData(e,t){t.layers===void 0&&(t.layers=0),e.userData.layer=t.layers,e.layers.disableAll(),e.layers.set(t.layers),e.userData.tag=t.tag??"none",e.hideFlags=0,e.userData.static=t.static??!1,e.visible=t.activeSelf??!0,e.guid=t.guid}}const i_="NEEDLE_lighting_settings",Ir=x("debugenvlight");class kP{get name(){return i_}parser;sourceId;context;constructor(e,t,i){this.parser=e,this.sourceId=t,this.context=i}afterRoot(e){const t=this.parser.json.extensions;if(t){const i=t[i_];if(i){Ir&&console.log('Loaded "'+this.name+'", src: "'+this.sourceId+'"',i);let n;if(e.scene.children.length===1){const o=e.scene.children[0];n=S.addComponent(o,yd,{},{callAwake:!1})}else{const o=new c.Object3D;o.name="LightSettings "+this.sourceId,e.scene.add(o),n=S.addComponent(o,yd,{},{callAwake:!1})}n.sourceId=this.sourceId,n.ambientIntensity=i.ambientIntensity,n.ambientLight=new c.Color().fromArray(i.ambientLight),Array.isArray(i.ambientTrilight)&&(n.ambientTrilight=i.ambientTrilight.map(o=>new c.Color().fromArray(o))),n.ambientMode=i.ambientMode,n.environmentReflectionSource=i.environmentReflectionSource}}return null}}re.registerCallback(oe.ContextCreated,s=>{const e=s.context,t=S.findObjectOfType(yd,e);t?.sourceId&&(t.enabled=!0)});class yd extends k{ambientMode=Qr.Skybox;ambientLight;ambientTrilight;ambientIntensity=1;environmentReflectionSource=hd.Skybox;_hasReflection=!1;_ambientLightObj;_hemisphereLightObj;awake(){if(this.sourceId){const t=this.environmentReflectionSource===hd.Skybox?gn.Skybox:gn.Reflection,i=this.context.lightmaps.tryGet(this.sourceId,t,0);this._hasReflection=i!=null,i&&this.context.sceneLighting.internalRegisterReflection(this.sourceId,i)}this.enabled=!1,this.context.sceneLighting.internalRegisterSceneLightSettings(this),Ir&&window.addEventListener("keydown",t=>{if(!this.destroyed)switch(t.key){case"l":this.enabled=!this.enabled;break}});const e=this.gameObject.userData?.components;if(e){const t=e.indexOf(this);e.splice(t,1),e.push(this)}}onDestroy(){this.context.sceneLighting.internalUnregisterSceneLightSettings(this)}calculateIntensityFactor(e){const t=Math.max(e.r,e.g,e.b);return 2.2*D.lerp(0,1.33,t)}onEnable(){if(Ir&&console.warn("💡🟡 >>> Enable lighting",this.sourceId,this.enabled,this),this.ambientMode==Qr.Flat){if(this.ambientLight&&!this._ambientLightObj){const e=this.calculateIntensityFactor(this.ambientLight);this._ambientLightObj=new c.AmbientLight(this.ambientLight,this.ambientIntensity*e),Ir&&console.log("Created ambient light",this.sourceId,this._ambientLightObj,this.ambientIntensity,e)}this._ambientLightObj&&this.gameObject.add(this._ambientLightObj)}else if(this.ambientMode===Qr.Trilight){if(this.ambientTrilight){const e=this.ambientTrilight[0],t=this.ambientTrilight[this.ambientTrilight.length-1],i=this.calculateIntensityFactor(t);this._hemisphereLightObj=new c.HemisphereLight(t,e,this.ambientIntensity*i),this.gameObject.add(this._hemisphereLightObj),Ir&&console.log("Created hemisphere ambient light",this.sourceId,this._hemisphereLightObj,this.ambientIntensity,i)}}else this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent();this.sourceId&&(this.context.domElement.getAttribute("environment-image")||this.context.sceneLighting.internalEnableReflection(this.sourceId))}onDisable(){Ir&&console.warn("💡⚫ <<< Disable lighting:",this.sourceId,this),this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent(),this.sourceId&&this.context.sceneLighting.internalDisableReflection(this.sourceId)}}const df=x("debugstencil");function RP(s,e){return(s&1<<e.layer)!=0}const EP=Symbol("stencils");class js{get name(){return"NEEDLE_render_objects"}static stencils={};static applyStencil(e){if(!e)return;const t=e.sourceId;if(df&&console.log(t,js.stencils),!t)return;const i=js.stencils[t];if(i)for(let n=i.length-1;n>=0;n--){const o=i[n];if(RP(o.layer,e)){df&&console.log(o),setTimeout(()=>{Ai()&&zd(e.gameObject)&&(he("Stencil not supported on instanced objects"),console.warn("Stencil not supported on instanced objects",e))},500);for(let r=0;r<e.sharedMaterials.length;r++){let a=e.sharedMaterials[r];a&&(a=a.clone(),a[EP]=!0,a.stencilWrite=!0,a.stencilWriteMask=255,a.stencilFuncMask=255,a.stencilRef=o.value,a.stencilFunc=o.compareFunc,a.stencilZPass=o.passOp,a.stencilFail=o.failOp,a.stencilZFail=o.zFailOp,e.sharedMaterials[r]=a)}e.gameObject.renderOrder=o.event*1e3+o.index*50;break}}}parser;source;constructor(e,t){this.parser=e,this.source=t}afterRoot(e){const t=this.parser.json.extensions;if(t){const i=t[AP];if(i){df&&console.log(i);const n=i.stencil;if(n&&Array.isArray(n))for(const o of n){const r={...o};r.compareFunc=TP(r.compareFunc),r.passOp=uf(r.passOp),r.failOp=uf(r.failOp),r.zFailOp=uf(r.zFailOp),js.stencils[this.source]||(js.stencils[this.source]=[]),js.stencils[this.source].push(r)}}}return null}}function uf(s){switch(s){case 0:return c.KeepStencilOp;case 1:return c.ZeroStencilOp;case 2:return c.ReplaceStencilOp;case 3:return c.IncrementStencilOp;case 4:return c.DecrementStencilOp;case 6:return c.IncrementWrapStencilOp;case 7:return c.DecrementWrapStencilOp;case 5:return c.InvertStencilOp}return 0}function TP(s){switch(s){case 1:return c.NeverStencilFunc;case 2:return c.LessStencilFunc;case 3:return c.EqualStencilFunc;case 4:return c.LessEqualStencilFunc;case 5:return c.GreaterStencilFunc;case 6:return c.NotEqualStencilFunc;case 7:return c.GreaterEqualStencilFunc;case 8:return c.AlwaysStencilFunc}return c.NeverStencilFunc}const AP="NEEDLE_render_objects";var mv=(s=>(s[s.INT=5124]="INT",s[s.FLOAT=5126]="FLOAT",s[s.FLOAT_VEC2=35664]="FLOAT_VEC2",s[s.FLOAT_VEC3=35665]="FLOAT_VEC3",s[s.FLOAT_VEC4=35666]="FLOAT_VEC4",s[s.INT_VEC2=35667]="INT_VEC2",s[s.INT_VEC3=35668]="INT_VEC3",s[s.INT_VEC4=35669]="INT_VEC4",s[s.BOOL=35670]="BOOL",s[s.BOOL_VEC2=35671]="BOOL_VEC2",s[s.BOOL_VEC3=35672]="BOOL_VEC3",s[s.BOOL_VEC4=35673]="BOOL_VEC4",s[s.FLOAT_MAT2=35674]="FLOAT_MAT2",s[s.FLOAT_MAT3=35675]="FLOAT_MAT3",s[s.FLOAT_MAT4=35676]="FLOAT_MAT4",s[s.SAMPLER_2D=35678]="SAMPLER_2D",s[s.SAMPLER_3D=35680]="SAMPLER_3D",s[s.SAMPLER_CUBE=35681]="SAMPLER_CUBE",s[s.UNKNOWN=0]="UNKNOWN",s))(mv||{});const fn=x("debugcustomshader"),Cr="NEEDLE_techniques_webgl";class LP{objectToWorldMatrix=new c.Matrix4;worldToObjectMatrix=new c.Matrix4;objectToWorld=new Array;worldToObject=new Array;updateFrom(e){this.objectToWorldMatrix.copy(e.matrixWorld),cd(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(e.matrixWorld).invert(),cd(this.worldToObjectMatrix,this.worldToObject)}}class ye extends c.RawShaderMaterial{identifier;onBeforeRenderSceneCallback=this.onBeforeRenderScene.bind(this);clone(){const e=super.clone();return gv(e),e}constructor(e,...t){super(...t),this.identifier=e,fn&&console.log(this),this.type="NEEDLE_CUSTOM_SHADER",this.uniforms[this._objToWorldName]||(this.uniforms[this._objToWorldName]={value:[]}),this.uniforms[this._worldToObjectName]||(this.uniforms[this._worldToObjectName]={value:[]}),this.uniforms[this._viewProjectionName]||(this.uniforms[this._viewProjectionName]={value:[]}),this.uniforms[this._sphericalHarmonicsName],(this.depthTextureUniform||this.opaqueTextureUniform)&&F.Current.pre_render_callbacks.push(this.onBeforeRenderSceneCallback)}dispose(){super.dispose();const e=F.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);e>=0&&F.Current.pre_render_callbacks.splice(e,1)}_sphericalHarmonicsName="unity_SpecCube0";_objToWorldName="hlslcc_mtx4x4unity_ObjectToWorld";_worldToObjectName="hlslcc_mtx4x4unity_WorldToObject";static viewProjection=new c.Matrix4;static _viewProjectionValues=[];_viewProjectionName="hlslcc_mtx4x4unity_MatrixVP";static viewMatrix=new c.Matrix4;static _viewMatrixValues=[];_viewMatrixName="hlslcc_mtx4x4unity_MatrixV";static _worldSpaceCameraPosName="_WorldSpaceCameraPos";static _worldSpaceCameraPos=new c.Vector3;static _mainLightColor=new c.Vector4;static _mainLightPosition=new c.Vector3;static _lightData=new c.Vector4;_rendererData=new LP;get depthTextureUniform(){if(this.uniforms)return this.uniforms._CameraDepthTexture}get opaqueTextureUniform(){if(this.uniforms)return this.uniforms._CameraOpaqueTexture}onBeforeRenderScene(){this.opaqueTextureUniform&&F.Current.setRequireColor(!0),this.depthTextureUniform&&F.Current.setRequireDepth(!0)}onBeforeRender(e,t,i,n,o,r){n.attributes.tangent||n.computeTangents(),this.onUpdateUniforms(i,o)}onUpdateUniforms(e,t){const i=F.Current;if(e&&(ye.viewProjection&&this.uniforms[this._viewProjectionName]&&(ye.viewProjection.copy(e.projectionMatrix).multiply(e.matrixWorldInverse),cd(ye.viewProjection,ye._viewProjectionValues)),ye.viewMatrix&&this.uniforms[this._viewMatrixName]&&(ye.viewMatrix.copy(e.matrixWorldInverse),cd(ye.viewMatrix,ye._viewMatrixValues)),this.uniforms[ye._worldSpaceCameraPosName]&&ye._worldSpaceCameraPos.setFromMatrixPosition(e.matrixWorld)),this.uniforms._TimeParameters&&(this.uniforms._TimeParameters.value=i.sceneLighting.timeVec4),this.uniforms._Time){const a=this.uniforms._Time.value;a.x=i.sceneLighting.timeVec4.x/20,a.y=i.sceneLighting.timeVec4.x,a.z=i.sceneLighting.timeVec4.x*2,a.w=i.sceneLighting.timeVec4.x*3}if(this.uniforms._SinTime){const a=this.uniforms._SinTime.value;a.x=Math.sin(i.sceneLighting.timeVec4.x/8),a.y=Math.sin(i.sceneLighting.timeVec4.x/4),a.z=Math.sin(i.sceneLighting.timeVec4.x/2),a.w=Math.sin(i.sceneLighting.timeVec4.x)}if(this.uniforms._CosTime){const a=this.uniforms._CosTime.value;a.x=Math.cos(i.sceneLighting.timeVec4.x/8),a.y=Math.cos(i.sceneLighting.timeVec4.x/4),a.z=Math.cos(i.sceneLighting.timeVec4.x/2),a.w=Math.cos(i.sceneLighting.timeVec4.x)}if(this.uniforms.unity_DeltaTime){const a=this.uniforms.unity_DeltaTime.value;a.x=i.time.deltaTime,a.y=1/i.time.deltaTime,a.z=i.time.smoothedDeltaTime,a.w=1/i.time.smoothedDeltaTime}const n=i.mainLight;if(n){const a=X(n.gameObject,ye._mainLightPosition);this.uniforms._MainLightPosition={value:a.normalize()},ye._mainLightColor.set(n.color.r,n.color.g,n.color.b,0),this.uniforms._MainLightColor={value:ye._mainLightColor};const l=n.intensity;ye._lightData.z=l,this.uniforms.unity_LightData={value:ye._lightData}}if(e&&(ye.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=ye._viewProjectionValues),ye.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=ye._viewMatrixValues),this.uniforms[ye._worldSpaceCameraPosName]&&(this.uniforms[ye._worldSpaceCameraPosName]={value:ye._worldSpaceCameraPos}),i.mainCameraComponent)){if(this.uniforms._ProjectionParams){const a=this.uniforms._ProjectionParams.value;a.x=1,a.y=i.mainCameraComponent.nearClipPlane,a.z=i.mainCameraComponent.farClipPlane,a.w=1/a.z,this.uniforms._ProjectionParams.value=a}if(this.uniforms._ZBufferParams){const a=this.uniforms._ZBufferParams.value,l=i.mainCameraComponent;a.x=1-l.farClipPlane/l.nearClipPlane,a.y=l.farClipPlane/l.nearClipPlane,a.z=a.x/l.farClipPlane,a.w=a.y/l.farClipPlane,this.uniforms._ZBufferParams.value=a}if(this.uniforms._ScreenParams){const a=this.uniforms._ScreenParams.value;a.x=i.domWidth,a.y=i.domHeight,a.z=1+1/a.x,a.w=1+1/a.y,this.uniforms._ScreenParams.value=a}if(this.uniforms._ScaledScreenParams){const a=this.uniforms._ScaledScreenParams.value;a.x=i.domWidth,a.y=i.domHeight,a.z=1+1/a.x,a.w=1+1/a.y,this.uniforms._ScaledScreenParams.value=a}}const o=this.depthTextureUniform;o&&(o.value=i.depthTexture);const r=this.opaqueTextureUniform;if(r&&(r.value=i.opaqueColorTexture),t){const a=this._rendererData;a.updateFrom(t),this.uniforms[this._worldToObjectName].value=a.worldToObject,this.uniforms[this._objToWorldName].value=a.objectToWorld}this.uniformsNeedUpdate=!0}}class DP{get name(){return Cr}parser;identifier;constructor(e,t){this.parser=e,this.identifier=t}loadMaterial(e){const t=this.parser.json.materials[e];if(!t)return fn&&console.log(e,this.parser.json.materials),null;if(!t.extensions||!t.extensions[Cr])return fn&&console.log(`Material ${e} does not use NEEDLE_techniques_webgl`),null;fn&&console.log(`Material ${e} uses NEEDLE_techniques_webgl`,t);const i=t.extensions[Cr].technique;if(i<0)return console.debug(`Material ${e} does not have a valid technique index`),null;const n=this.parser.json.extensions[Cr];if(!n)return fn?console.error("Missing shader data",this.parser.json.extensions):console.debug("Missing custom shader data in parser.json.extensions"),null;fn&&console.log(n);const o=n.techniques[i];return o?new Promise(async(r,a)=>{const l=await kC(n,o.program),h=l?.fragmentShader,d=l?.vertexShader;if(!h||!d)return a();fn&&console.log("loadMaterial",t,l);const u={},p=o.uniforms;(d.includes("_Time")||h.includes("_Time"))&&(u._Time={value:new c.Vector4(0,0,0,0)}),(d.includes("_SinTime")||h.includes("_SinTime"))&&(u._SinTime={value:new c.Vector4(0,0,0,0)}),(d.includes("_CosTime")||h.includes("_CosTime"))&&(u._CosTime={value:new c.Vector4(0,0,0,0)}),(d.includes("unity_DeltaTime")||h.includes("unity_DeltaTime"))&&(u.unity_DeltaTime={value:new c.Vector4(0,0,0,0)});for(const v in p){const _=v;switch(_){case"_TimeParameters":const w=new c.Vector4;u[_]={value:w};break;case"hlslcc_mtx4x4unity_MatrixV":case"hlslcc_mtx4x4unity_MatrixVP":u[_]={value:[]};break;case"_MainLightPosition":case"_MainLightColor":case"_WorldSpaceCameraPos":u[_]={value:[0,0,0,1]};break;case"unity_OrthoParams":break;case"unity_SpecCube0":u[_]={value:null};break;default:case"_ScreenParams":case"_ZBufferParams":case"_ProjectionParams":u[_]={value:[0,0,0,0]};break;case"_CameraOpaqueTexture":case"_CameraDepthTexture":u[_]={value:null};break}}let m=!1;if(t.extensions&&t.extensions[Cr]){const v=t.extensions[Cr];if(v.technique===i){fn&&console.log(t.name,"Material Properties",v);for(const _ in v.values){const w=v.values[_];if(typeof w=="string"){if(w.startsWith("/textures/")){const T=w.substring(10),O=Number.parseInt(T);if(O>=0){const M=await this.parser.getDependency("texture",O);M instanceof c.Texture&&(M.colorSpace=c.LinearSRGBColorSpace,M.needsUpdate=!0),u[_]={value:M};continue}}switch(_){case"alphaMode":w==="BLEND"&&(m=!0);continue}}if(Array.isArray(w)&&w.length===4){u[_]={value:new c.Vector4(w[0],w[1],w[2],w[3])};continue}u[_]={value:w}}}}const y=new ye(this.identifier,{name:t.name??"",uniforms:u,vertexShader:d,fragmentShader:h,lights:!1});switch(y.glslVersion=c.GLSL3,y.vertexShader=y.vertexShader.replace("#version 300 es",""),y.fragmentShader=y.fragmentShader.replace("#version 300 es",""),u._Cull?.value){case 0:y.side=c.DoubleSide;break;case 1:y.side=c.BackSide;break;case 2:y.side=c.FrontSide;break;default:y.side=c.FrontSide;break}switch(u._ZTest?.value){case 3:y.depthTest=!0,y.depthFunc=c.EqualDepth;break;case 6:y.depthTest=!0,y.depthFunc=c.NotEqualDepth;break;case 2:y.depthTest=!0,y.depthFunc=c.LessDepth;break;case 4:y.depthTest=!0,y.depthFunc=c.LessEqualDepth;break;case 5:y.depthTest=!0,y.depthFunc=c.GreaterDepth;break;case 7:y.depthTest=!0,y.depthFunc=c.GreaterEqualDepth;break;case 8:y.depthTest=!1,y.depthFunc=c.AlwaysDepth;break}y.transparent=m,m&&(y.depthWrite=!1),OC(u),y.onUpdateUniforms();for(const v in p){const _=v,w=p[v].type;if(u[_]?.value===void 0)switch(w){case mv.SAMPLER_2D:u[_]={value:CC},console.warn("Missing/unassigned texture, fallback to white: "+_);break;default:_==="unity_OrthoParams"||console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+_,p[v]);break}}fn&&console.log(y.uuid,u),gv(y),r(y)}):null}}function gv(s){if(s.uniforms){fn&&console.log("Uniforms:",s.uniforms);for(const t in s.uniforms)switch(e(t,t),t){case"_Color":e("color",t);break}}function e(t,i){Object.getOwnPropertyDescriptor(s,t)||Object.defineProperty(s,t,{get:()=>s.uniforms[i].value,set:n=>{s.uniforms[i].value=n,s.needsUpdate=!0}})}}const IP=x("debugextensions");let _d;const jP=Promise.resolve().then(()=>require("./vendor-xfQ8tKF3.umd.cjs")).then(s=>s.index$2).then(async s=>(_d=s.GLTFAnimationPointerExtension,_d)).catch(s=>{console.warn("Failed to import GLTFLoaderAnimationPointer. Please use @needle-tools/three-animationpointer for full KHR_animation support",s)}),qo=new Array;function BP(s){qo.includes(s)||qo.push(s)}function FP(s){const e=qo.indexOf(s);e>=0&&qo.splice(e,1)}function zm(s){if(s instanceof q.GLTFLoader){const e=new pv;return s.register(t=>(e.parser=t,e)),e}return null}class UP{resolvePath(e){return e.includes("/extensions/builtin_components/")?e.replace("/extensions/builtin_components/","/userData/components/"):e.includes("extensions/builtin_components/")?e.replace("extensions/builtin_components/","/userData/components/"):e}}async function bd(s,e,t){const i=t.indexOf("?");i>=0&&(t=t.substring(0,i)),s.register(n=>new MP(n)),s.register(n=>new eC(n)),s.register(n=>new vC(n,e.lightmaps,t)),s.register(n=>new kP(n,t,e)),s.register(n=>new DP(n,t)),s.register(n=>new js(n,t)),s.register(n=>new ne.NEEDLE_progressive(n)),s.register(n=>new SP(n)),Bb()&&s.register(n=>new qr(n)),await jP.catch(n=>{}),s.register(n=>{if(_d){const o=new _d(n);return o.setAnimationPointerResolver.bind(o)(new UP),o}else return(IP||A())&&console.error("Missing KHR_animation_pointer extension..."),{name:"KHR_animation_pointer_NOT_AVAILABLE"}});for(const n of qo)n.onImport&&n.onImport(s,t,e)}function Nm(s,e){for(const t of qo)t.onExport&&t.onExport(s,e)}function yv(s,e,t){for(const i of qo)i.onLoaded&&i.onLoaded(s,e,t)}class _v{constructor(e){this.writer=e,this.name="EXT_mesh_gpu_instancing"}writeNode(e,t){if(e.constructor.name!=="InstancedMesh")return;const i=this.writer,n=i.extensionsUsed,o={};t.extensions=t.extensions||{},t.extensions[this.name]=o;let r=new c.Matrix4;const a=new Array,l=new Array,h=new Array;for(let m=0;m<e.count;m++){e.getMatrixAt(m,r);let y=new c.Vector3,b=new c.Quaternion,g=new c.Vector3;r.decompose(y,b,g),a.push(y.x,y.y,y.z),l.push(b.x,b.y,b.z,b.w),h.push(g.x,g.y,g.z)}const d=new Float32Array(a),u=new Float32Array(l),p=new Float32Array(h);o.attributes={TRANSLATION:i.processAccessor(new c.BufferAttribute(d,3)),ROTATION:i.processAccessor(new c.BufferAttribute(u,4)),SCALE:i.processAccessor(new c.BufferAttribute(p,3))},n[this.name]=!0}}var zP=Object.defineProperty,bv=(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&&zP(e,t,n),n};const $a=x("debugreflectionprobe"),n_=x("noreflectionprobe"),ff=Symbol("reflectionProbeKey"),s_=Symbol("original material"),Vm=class qn extends k{static _probes=new Map;static isUsingReflectionProbe(e){return!!(e[ff]||e[s_]?.[ff])}static get(e,t,i,n){if(!e||e.isObject3D!==!0||n_)return null;const o=qn._probes.get(t);if(o){for(const r of o)if(r.__didAwake||r.__internalAwake(),r.activeAndEnabled){if(n){if(r.gameObject===n)return r}else if(r.isInBox(e))return $a&&console.log("Found reflection probe",e.name,r.name),r}}return $a&&console.debug("Did not find reflection probe",e.name,i,e),null}_texture;set texture(e){if(e&&!(e instanceof c.Texture)){console.error("ReflectionProbe.texture must be a Texture",e);return}this._texture=e,e&&(e.mapping=c.EquirectangularReflectionMapping,e.colorSpace=c.LinearSRGBColorSpace,e.needsUpdate=!0)}get texture(){return this._texture}center;size;_boxHelper;isInBox(e){return this._boxHelper?.isInBox(e)}constructor(){super(),qn._probes.has(this.context)||qn._probes.set(this.context,[]),qn._probes.get(this.context)?.push(this)}awake(){this._boxHelper=this.gameObject.addComponent(nt),this._boxHelper.updateBox(!0),$a&&this._boxHelper.showHelper(5592320,!0),this._texture&&(this._texture.mapping=c.EquirectangularReflectionMapping,this._texture.colorSpace=c.LinearSRGBColorSpace,this._texture.needsUpdate=!0)}start(){!this._texture&&A()&&(console.warn(`[ReflectionProbe] Missing texture. Please assign a custom cubemap texture. To use reflection probes assign them to your renderer's "anchor" property.`),he("ReflectionProbe configuration hint: See browser console for details"))}onDestroy(){const e=qn._probes.get(this.context);if(e){const t=e.indexOf(this);t>=0&&e.splice(t,1)}}static _rendererMaterialsCache=new Map;onSet(e){if(n_||!this.enabled||e.sharedMaterials?.length<=0||!this.texture)return;let t=qn._rendererMaterialsCache.get(e);t||(t=[],qn._rendererMaterialsCache.set(e,t));for(let i=0;i<e.sharedMaterials.length;i++){const n=e.sharedMaterials[i];if(!n||n.envMap===void 0||n instanceof c.MeshBasicMaterial)continue;let o=t[i];const r=n===o?.copy,a=!o||o.material.uuid!==n.uuid||o.copy.version!==n.version;if(!r&&a){if($a){let d="";o?o.material!==n?d="reference changed; cached instance?: "+r:o.copy.version!==n.version&&(d="version changed"):d="not cached",console.warn("Cloning material",n.name,n.version,"Reason:",d,`
|
|
976
|
+
`,a,e,r))),e.userData=e.userData||{},e.userData[wo]=e.userData[wo]||[],e.userData[wo].push(r)}await Promise.all(n).catch(o=>{console.error("Error while loading components",o)})}}}const t_="NEEDLE_gameobject_data";class MP{get name(){return t_}parser;constructor(e){this.parser=e}afterRoot(e){const t=[];for(let i=0;i<this.parser.json.nodes?.length;i++){const n=this.parser.json.nodes[i];if(n&&n.extensions){const o=n.extensions[t_];if(o){const r=this.findAndApplyExtensionData(i,o);t.push(r)}}}return Promise.all(t).then(()=>null)}async findAndApplyExtensionData(e,t){const i=await this.parser.getDependency("node",e);i&&this.applyExtensionData(i,t)}applyExtensionData(e,t){t.layers===void 0&&(t.layers=0),e.userData.layer=t.layers,e.layers.disableAll(),e.layers.set(t.layers),e.userData.tag=t.tag??"none",e.hideFlags=0,e.userData.static=t.static??!1,e.visible=t.activeSelf??!0,e.guid=t.guid}}const i_="NEEDLE_lighting_settings",Ir=x("debugenvlight");class kP{get name(){return i_}parser;sourceId;context;constructor(e,t,i){this.parser=e,this.sourceId=t,this.context=i}afterRoot(e){const t=this.parser.json.extensions;if(t){const i=t[i_];if(i){Ir&&console.log('Loaded "'+this.name+'", src: "'+this.sourceId+'"',i);let n;if(e.scene.children.length===1){const o=e.scene.children[0];n=S.addComponent(o,yd,{},{callAwake:!1})}else{const o=new c.Object3D;o.name="LightSettings "+this.sourceId,e.scene.add(o),n=S.addComponent(o,yd,{},{callAwake:!1})}n.sourceId=this.sourceId,n.ambientIntensity=i.ambientIntensity,n.ambientLight=new c.Color().fromArray(i.ambientLight),Array.isArray(i.ambientTrilight)&&(n.ambientTrilight=i.ambientTrilight.map(o=>new c.Color().fromArray(o))),n.ambientMode=i.ambientMode,n.environmentReflectionSource=i.environmentReflectionSource}}return null}}re.registerCallback(oe.ContextCreated,s=>{const e=s.context,t=S.findObjectOfType(yd,e);t?.sourceId&&(t.enabled=!0)});class yd extends k{ambientMode=Qr.Skybox;ambientLight;ambientTrilight;ambientIntensity=1;environmentReflectionSource=hd.Skybox;_hasReflection=!1;_ambientLightObj;_hemisphereLightObj;awake(){if(this.sourceId){const t=this.environmentReflectionSource===hd.Skybox?gn.Skybox:gn.Reflection,i=this.context.lightmaps.tryGet(this.sourceId,t,0);this._hasReflection=i!=null,i&&this.context.sceneLighting.internalRegisterReflection(this.sourceId,i)}this.enabled=!1,this.context.sceneLighting.internalRegisterSceneLightSettings(this),Ir&&window.addEventListener("keydown",t=>{if(!this.destroyed)switch(t.key){case"l":this.enabled=!this.enabled;break}});const e=this.gameObject.userData?.components;if(e){const t=e.indexOf(this);e.splice(t,1),e.push(this)}}onDestroy(){this.context.sceneLighting.internalUnregisterSceneLightSettings(this)}calculateIntensityFactor(e){const t=Math.max(e.r,e.g,e.b);return 2.2*D.lerp(0,1.33,t)}onEnable(){if(Ir&&console.warn("💡🟡 >>> Enable lighting",this.sourceId,this.enabled,this),this.ambientMode==Qr.Flat){if(this.ambientLight&&!this._ambientLightObj){const e=this.calculateIntensityFactor(this.ambientLight);this._ambientLightObj=new c.AmbientLight(this.ambientLight,this.ambientIntensity*e),Ir&&console.log("Created ambient light",this.sourceId,this._ambientLightObj,this.ambientIntensity,e)}this._ambientLightObj&&this.gameObject.add(this._ambientLightObj)}else if(this.ambientMode===Qr.Trilight){if(this.ambientTrilight){const e=this.ambientTrilight[0],t=this.ambientTrilight[this.ambientTrilight.length-1],i=this.calculateIntensityFactor(t);this._hemisphereLightObj=new c.HemisphereLight(t,e,this.ambientIntensity*i),this.gameObject.add(this._hemisphereLightObj),Ir&&console.log("Created hemisphere ambient light",this.sourceId,this._hemisphereLightObj,this.ambientIntensity,i)}}else this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent();this.sourceId&&this.context.sceneLighting.internalEnableReflection(this.sourceId)}onDisable(){Ir&&console.warn("💡⚫ <<< Disable lighting:",this.sourceId,this),this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent(),this.sourceId&&this.context.sceneLighting.internalDisableReflection(this.sourceId)}}const df=x("debugstencil");function RP(s,e){return(s&1<<e.layer)!=0}const EP=Symbol("stencils");class js{get name(){return"NEEDLE_render_objects"}static stencils={};static applyStencil(e){if(!e)return;const t=e.sourceId;if(df&&console.log(t,js.stencils),!t)return;const i=js.stencils[t];if(i)for(let n=i.length-1;n>=0;n--){const o=i[n];if(RP(o.layer,e)){df&&console.log(o),setTimeout(()=>{Ai()&&zd(e.gameObject)&&(he("Stencil not supported on instanced objects"),console.warn("Stencil not supported on instanced objects",e))},500);for(let r=0;r<e.sharedMaterials.length;r++){let a=e.sharedMaterials[r];a&&(a=a.clone(),a[EP]=!0,a.stencilWrite=!0,a.stencilWriteMask=255,a.stencilFuncMask=255,a.stencilRef=o.value,a.stencilFunc=o.compareFunc,a.stencilZPass=o.passOp,a.stencilFail=o.failOp,a.stencilZFail=o.zFailOp,e.sharedMaterials[r]=a)}e.gameObject.renderOrder=o.event*1e3+o.index*50;break}}}parser;source;constructor(e,t){this.parser=e,this.source=t}afterRoot(e){const t=this.parser.json.extensions;if(t){const i=t[AP];if(i){df&&console.log(i);const n=i.stencil;if(n&&Array.isArray(n))for(const o of n){const r={...o};r.compareFunc=TP(r.compareFunc),r.passOp=uf(r.passOp),r.failOp=uf(r.failOp),r.zFailOp=uf(r.zFailOp),js.stencils[this.source]||(js.stencils[this.source]=[]),js.stencils[this.source].push(r)}}}return null}}function uf(s){switch(s){case 0:return c.KeepStencilOp;case 1:return c.ZeroStencilOp;case 2:return c.ReplaceStencilOp;case 3:return c.IncrementStencilOp;case 4:return c.DecrementStencilOp;case 6:return c.IncrementWrapStencilOp;case 7:return c.DecrementWrapStencilOp;case 5:return c.InvertStencilOp}return 0}function TP(s){switch(s){case 1:return c.NeverStencilFunc;case 2:return c.LessStencilFunc;case 3:return c.EqualStencilFunc;case 4:return c.LessEqualStencilFunc;case 5:return c.GreaterStencilFunc;case 6:return c.NotEqualStencilFunc;case 7:return c.GreaterEqualStencilFunc;case 8:return c.AlwaysStencilFunc}return c.NeverStencilFunc}const AP="NEEDLE_render_objects";var mv=(s=>(s[s.INT=5124]="INT",s[s.FLOAT=5126]="FLOAT",s[s.FLOAT_VEC2=35664]="FLOAT_VEC2",s[s.FLOAT_VEC3=35665]="FLOAT_VEC3",s[s.FLOAT_VEC4=35666]="FLOAT_VEC4",s[s.INT_VEC2=35667]="INT_VEC2",s[s.INT_VEC3=35668]="INT_VEC3",s[s.INT_VEC4=35669]="INT_VEC4",s[s.BOOL=35670]="BOOL",s[s.BOOL_VEC2=35671]="BOOL_VEC2",s[s.BOOL_VEC3=35672]="BOOL_VEC3",s[s.BOOL_VEC4=35673]="BOOL_VEC4",s[s.FLOAT_MAT2=35674]="FLOAT_MAT2",s[s.FLOAT_MAT3=35675]="FLOAT_MAT3",s[s.FLOAT_MAT4=35676]="FLOAT_MAT4",s[s.SAMPLER_2D=35678]="SAMPLER_2D",s[s.SAMPLER_3D=35680]="SAMPLER_3D",s[s.SAMPLER_CUBE=35681]="SAMPLER_CUBE",s[s.UNKNOWN=0]="UNKNOWN",s))(mv||{});const fn=x("debugcustomshader"),Cr="NEEDLE_techniques_webgl";class LP{objectToWorldMatrix=new c.Matrix4;worldToObjectMatrix=new c.Matrix4;objectToWorld=new Array;worldToObject=new Array;updateFrom(e){this.objectToWorldMatrix.copy(e.matrixWorld),cd(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(e.matrixWorld).invert(),cd(this.worldToObjectMatrix,this.worldToObject)}}class ye extends c.RawShaderMaterial{identifier;onBeforeRenderSceneCallback=this.onBeforeRenderScene.bind(this);clone(){const e=super.clone();return gv(e),e}constructor(e,...t){super(...t),this.identifier=e,fn&&console.log(this),this.type="NEEDLE_CUSTOM_SHADER",this.uniforms[this._objToWorldName]||(this.uniforms[this._objToWorldName]={value:[]}),this.uniforms[this._worldToObjectName]||(this.uniforms[this._worldToObjectName]={value:[]}),this.uniforms[this._viewProjectionName]||(this.uniforms[this._viewProjectionName]={value:[]}),this.uniforms[this._sphericalHarmonicsName],(this.depthTextureUniform||this.opaqueTextureUniform)&&F.Current.pre_render_callbacks.push(this.onBeforeRenderSceneCallback)}dispose(){super.dispose();const e=F.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);e>=0&&F.Current.pre_render_callbacks.splice(e,1)}_sphericalHarmonicsName="unity_SpecCube0";_objToWorldName="hlslcc_mtx4x4unity_ObjectToWorld";_worldToObjectName="hlslcc_mtx4x4unity_WorldToObject";static viewProjection=new c.Matrix4;static _viewProjectionValues=[];_viewProjectionName="hlslcc_mtx4x4unity_MatrixVP";static viewMatrix=new c.Matrix4;static _viewMatrixValues=[];_viewMatrixName="hlslcc_mtx4x4unity_MatrixV";static _worldSpaceCameraPosName="_WorldSpaceCameraPos";static _worldSpaceCameraPos=new c.Vector3;static _mainLightColor=new c.Vector4;static _mainLightPosition=new c.Vector3;static _lightData=new c.Vector4;_rendererData=new LP;get depthTextureUniform(){if(this.uniforms)return this.uniforms._CameraDepthTexture}get opaqueTextureUniform(){if(this.uniforms)return this.uniforms._CameraOpaqueTexture}onBeforeRenderScene(){this.opaqueTextureUniform&&F.Current.setRequireColor(!0),this.depthTextureUniform&&F.Current.setRequireDepth(!0)}onBeforeRender(e,t,i,n,o,r){n.attributes.tangent||n.computeTangents(),this.onUpdateUniforms(i,o)}onUpdateUniforms(e,t){const i=F.Current;if(e&&(ye.viewProjection&&this.uniforms[this._viewProjectionName]&&(ye.viewProjection.copy(e.projectionMatrix).multiply(e.matrixWorldInverse),cd(ye.viewProjection,ye._viewProjectionValues)),ye.viewMatrix&&this.uniforms[this._viewMatrixName]&&(ye.viewMatrix.copy(e.matrixWorldInverse),cd(ye.viewMatrix,ye._viewMatrixValues)),this.uniforms[ye._worldSpaceCameraPosName]&&ye._worldSpaceCameraPos.setFromMatrixPosition(e.matrixWorld)),this.uniforms._TimeParameters&&(this.uniforms._TimeParameters.value=i.sceneLighting.timeVec4),this.uniforms._Time){const a=this.uniforms._Time.value;a.x=i.sceneLighting.timeVec4.x/20,a.y=i.sceneLighting.timeVec4.x,a.z=i.sceneLighting.timeVec4.x*2,a.w=i.sceneLighting.timeVec4.x*3}if(this.uniforms._SinTime){const a=this.uniforms._SinTime.value;a.x=Math.sin(i.sceneLighting.timeVec4.x/8),a.y=Math.sin(i.sceneLighting.timeVec4.x/4),a.z=Math.sin(i.sceneLighting.timeVec4.x/2),a.w=Math.sin(i.sceneLighting.timeVec4.x)}if(this.uniforms._CosTime){const a=this.uniforms._CosTime.value;a.x=Math.cos(i.sceneLighting.timeVec4.x/8),a.y=Math.cos(i.sceneLighting.timeVec4.x/4),a.z=Math.cos(i.sceneLighting.timeVec4.x/2),a.w=Math.cos(i.sceneLighting.timeVec4.x)}if(this.uniforms.unity_DeltaTime){const a=this.uniforms.unity_DeltaTime.value;a.x=i.time.deltaTime,a.y=1/i.time.deltaTime,a.z=i.time.smoothedDeltaTime,a.w=1/i.time.smoothedDeltaTime}const n=i.mainLight;if(n){const a=X(n.gameObject,ye._mainLightPosition);this.uniforms._MainLightPosition={value:a.normalize()},ye._mainLightColor.set(n.color.r,n.color.g,n.color.b,0),this.uniforms._MainLightColor={value:ye._mainLightColor};const l=n.intensity;ye._lightData.z=l,this.uniforms.unity_LightData={value:ye._lightData}}if(e&&(ye.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=ye._viewProjectionValues),ye.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=ye._viewMatrixValues),this.uniforms[ye._worldSpaceCameraPosName]&&(this.uniforms[ye._worldSpaceCameraPosName]={value:ye._worldSpaceCameraPos}),i.mainCameraComponent)){if(this.uniforms._ProjectionParams){const a=this.uniforms._ProjectionParams.value;a.x=1,a.y=i.mainCameraComponent.nearClipPlane,a.z=i.mainCameraComponent.farClipPlane,a.w=1/a.z,this.uniforms._ProjectionParams.value=a}if(this.uniforms._ZBufferParams){const a=this.uniforms._ZBufferParams.value,l=i.mainCameraComponent;a.x=1-l.farClipPlane/l.nearClipPlane,a.y=l.farClipPlane/l.nearClipPlane,a.z=a.x/l.farClipPlane,a.w=a.y/l.farClipPlane,this.uniforms._ZBufferParams.value=a}if(this.uniforms._ScreenParams){const a=this.uniforms._ScreenParams.value;a.x=i.domWidth,a.y=i.domHeight,a.z=1+1/a.x,a.w=1+1/a.y,this.uniforms._ScreenParams.value=a}if(this.uniforms._ScaledScreenParams){const a=this.uniforms._ScaledScreenParams.value;a.x=i.domWidth,a.y=i.domHeight,a.z=1+1/a.x,a.w=1+1/a.y,this.uniforms._ScaledScreenParams.value=a}}const o=this.depthTextureUniform;o&&(o.value=i.depthTexture);const r=this.opaqueTextureUniform;if(r&&(r.value=i.opaqueColorTexture),t){const a=this._rendererData;a.updateFrom(t),this.uniforms[this._worldToObjectName].value=a.worldToObject,this.uniforms[this._objToWorldName].value=a.objectToWorld}this.uniformsNeedUpdate=!0}}class DP{get name(){return Cr}parser;identifier;constructor(e,t){this.parser=e,this.identifier=t}loadMaterial(e){const t=this.parser.json.materials[e];if(!t)return fn&&console.log(e,this.parser.json.materials),null;if(!t.extensions||!t.extensions[Cr])return fn&&console.log(`Material ${e} does not use NEEDLE_techniques_webgl`),null;fn&&console.log(`Material ${e} uses NEEDLE_techniques_webgl`,t);const i=t.extensions[Cr].technique;if(i<0)return console.debug(`Material ${e} does not have a valid technique index`),null;const n=this.parser.json.extensions[Cr];if(!n)return fn?console.error("Missing shader data",this.parser.json.extensions):console.debug("Missing custom shader data in parser.json.extensions"),null;fn&&console.log(n);const o=n.techniques[i];return o?new Promise(async(r,a)=>{const l=await kC(n,o.program),h=l?.fragmentShader,d=l?.vertexShader;if(!h||!d)return a();fn&&console.log("loadMaterial",t,l);const u={},p=o.uniforms;(d.includes("_Time")||h.includes("_Time"))&&(u._Time={value:new c.Vector4(0,0,0,0)}),(d.includes("_SinTime")||h.includes("_SinTime"))&&(u._SinTime={value:new c.Vector4(0,0,0,0)}),(d.includes("_CosTime")||h.includes("_CosTime"))&&(u._CosTime={value:new c.Vector4(0,0,0,0)}),(d.includes("unity_DeltaTime")||h.includes("unity_DeltaTime"))&&(u.unity_DeltaTime={value:new c.Vector4(0,0,0,0)});for(const v in p){const _=v;switch(_){case"_TimeParameters":const w=new c.Vector4;u[_]={value:w};break;case"hlslcc_mtx4x4unity_MatrixV":case"hlslcc_mtx4x4unity_MatrixVP":u[_]={value:[]};break;case"_MainLightPosition":case"_MainLightColor":case"_WorldSpaceCameraPos":u[_]={value:[0,0,0,1]};break;case"unity_OrthoParams":break;case"unity_SpecCube0":u[_]={value:null};break;default:case"_ScreenParams":case"_ZBufferParams":case"_ProjectionParams":u[_]={value:[0,0,0,0]};break;case"_CameraOpaqueTexture":case"_CameraDepthTexture":u[_]={value:null};break}}let m=!1;if(t.extensions&&t.extensions[Cr]){const v=t.extensions[Cr];if(v.technique===i){fn&&console.log(t.name,"Material Properties",v);for(const _ in v.values){const w=v.values[_];if(typeof w=="string"){if(w.startsWith("/textures/")){const T=w.substring(10),O=Number.parseInt(T);if(O>=0){const M=await this.parser.getDependency("texture",O);M instanceof c.Texture&&(M.colorSpace=c.LinearSRGBColorSpace,M.needsUpdate=!0),u[_]={value:M};continue}}switch(_){case"alphaMode":w==="BLEND"&&(m=!0);continue}}if(Array.isArray(w)&&w.length===4){u[_]={value:new c.Vector4(w[0],w[1],w[2],w[3])};continue}u[_]={value:w}}}}const y=new ye(this.identifier,{name:t.name??"",uniforms:u,vertexShader:d,fragmentShader:h,lights:!1});switch(y.glslVersion=c.GLSL3,y.vertexShader=y.vertexShader.replace("#version 300 es",""),y.fragmentShader=y.fragmentShader.replace("#version 300 es",""),u._Cull?.value){case 0:y.side=c.DoubleSide;break;case 1:y.side=c.BackSide;break;case 2:y.side=c.FrontSide;break;default:y.side=c.FrontSide;break}switch(u._ZTest?.value){case 3:y.depthTest=!0,y.depthFunc=c.EqualDepth;break;case 6:y.depthTest=!0,y.depthFunc=c.NotEqualDepth;break;case 2:y.depthTest=!0,y.depthFunc=c.LessDepth;break;case 4:y.depthTest=!0,y.depthFunc=c.LessEqualDepth;break;case 5:y.depthTest=!0,y.depthFunc=c.GreaterDepth;break;case 7:y.depthTest=!0,y.depthFunc=c.GreaterEqualDepth;break;case 8:y.depthTest=!1,y.depthFunc=c.AlwaysDepth;break}y.transparent=m,m&&(y.depthWrite=!1),OC(u),y.onUpdateUniforms();for(const v in p){const _=v,w=p[v].type;if(u[_]?.value===void 0)switch(w){case mv.SAMPLER_2D:u[_]={value:CC},console.warn("Missing/unassigned texture, fallback to white: "+_);break;default:_==="unity_OrthoParams"||console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+_,p[v]);break}}fn&&console.log(y.uuid,u),gv(y),r(y)}):null}}function gv(s){if(s.uniforms){fn&&console.log("Uniforms:",s.uniforms);for(const t in s.uniforms)switch(e(t,t),t){case"_Color":e("color",t);break}}function e(t,i){Object.getOwnPropertyDescriptor(s,t)||Object.defineProperty(s,t,{get:()=>s.uniforms[i].value,set:n=>{s.uniforms[i].value=n,s.needsUpdate=!0}})}}const IP=x("debugextensions");let _d;const jP=Promise.resolve().then(()=>require("./vendor-xfQ8tKF3.umd.cjs")).then(s=>s.index$2).then(async s=>(_d=s.GLTFAnimationPointerExtension,_d)).catch(s=>{console.warn("Failed to import GLTFLoaderAnimationPointer. Please use @needle-tools/three-animationpointer for full KHR_animation support",s)}),qo=new Array;function BP(s){qo.includes(s)||qo.push(s)}function FP(s){const e=qo.indexOf(s);e>=0&&qo.splice(e,1)}function zm(s){if(s instanceof q.GLTFLoader){const e=new pv;return s.register(t=>(e.parser=t,e)),e}return null}class UP{resolvePath(e){return e.includes("/extensions/builtin_components/")?e.replace("/extensions/builtin_components/","/userData/components/"):e.includes("extensions/builtin_components/")?e.replace("extensions/builtin_components/","/userData/components/"):e}}async function bd(s,e,t){const i=t.indexOf("?");i>=0&&(t=t.substring(0,i)),s.register(n=>new MP(n)),s.register(n=>new eC(n)),s.register(n=>new vC(n,e.lightmaps,t)),s.register(n=>new kP(n,t,e)),s.register(n=>new DP(n,t)),s.register(n=>new js(n,t)),s.register(n=>new ne.NEEDLE_progressive(n)),s.register(n=>new SP(n)),Bb()&&s.register(n=>new qr(n)),await jP.catch(n=>{}),s.register(n=>{if(_d){const o=new _d(n);return o.setAnimationPointerResolver.bind(o)(new UP),o}else return(IP||A())&&console.error("Missing KHR_animation_pointer extension..."),{name:"KHR_animation_pointer_NOT_AVAILABLE"}});for(const n of qo)n.onImport&&n.onImport(s,t,e)}function Nm(s,e){for(const t of qo)t.onExport&&t.onExport(s,e)}function yv(s,e,t){for(const i of qo)i.onLoaded&&i.onLoaded(s,e,t)}class _v{constructor(e){this.writer=e,this.name="EXT_mesh_gpu_instancing"}writeNode(e,t){if(e.constructor.name!=="InstancedMesh")return;const i=this.writer,n=i.extensionsUsed,o={};t.extensions=t.extensions||{},t.extensions[this.name]=o;let r=new c.Matrix4;const a=new Array,l=new Array,h=new Array;for(let m=0;m<e.count;m++){e.getMatrixAt(m,r);let y=new c.Vector3,b=new c.Quaternion,g=new c.Vector3;r.decompose(y,b,g),a.push(y.x,y.y,y.z),l.push(b.x,b.y,b.z,b.w),h.push(g.x,g.y,g.z)}const d=new Float32Array(a),u=new Float32Array(l),p=new Float32Array(h);o.attributes={TRANSLATION:i.processAccessor(new c.BufferAttribute(d,3)),ROTATION:i.processAccessor(new c.BufferAttribute(u,4)),SCALE:i.processAccessor(new c.BufferAttribute(p,3))},n[this.name]=!0}}var zP=Object.defineProperty,bv=(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&&zP(e,t,n),n};const $a=x("debugreflectionprobe"),n_=x("noreflectionprobe"),ff=Symbol("reflectionProbeKey"),s_=Symbol("original material"),Vm=class qn extends k{static _probes=new Map;static isUsingReflectionProbe(e){return!!(e[ff]||e[s_]?.[ff])}static get(e,t,i,n){if(!e||e.isObject3D!==!0||n_)return null;const o=qn._probes.get(t);if(o){for(const r of o)if(r.__didAwake||r.__internalAwake(),r.activeAndEnabled){if(n){if(r.gameObject===n)return r}else if(r.isInBox(e))return $a&&console.log("Found reflection probe",e.name,r.name),r}}return $a&&console.debug("Did not find reflection probe",e.name,i,e),null}_texture;set texture(e){if(e&&!(e instanceof c.Texture)){console.error("ReflectionProbe.texture must be a Texture",e);return}this._texture=e,e&&(e.mapping=c.EquirectangularReflectionMapping,e.colorSpace=c.LinearSRGBColorSpace,e.needsUpdate=!0)}get texture(){return this._texture}center;size;_boxHelper;isInBox(e){return this._boxHelper?.isInBox(e)}constructor(){super(),qn._probes.has(this.context)||qn._probes.set(this.context,[]),qn._probes.get(this.context)?.push(this)}awake(){this._boxHelper=this.gameObject.addComponent(nt),this._boxHelper.updateBox(!0),$a&&this._boxHelper.showHelper(5592320,!0),this._texture&&(this._texture.mapping=c.EquirectangularReflectionMapping,this._texture.colorSpace=c.LinearSRGBColorSpace,this._texture.needsUpdate=!0)}start(){!this._texture&&A()&&(console.warn(`[ReflectionProbe] Missing texture. Please assign a custom cubemap texture. To use reflection probes assign them to your renderer's "anchor" property.`),he("ReflectionProbe configuration hint: See browser console for details"))}onDestroy(){const e=qn._probes.get(this.context);if(e){const t=e.indexOf(this);t>=0&&e.splice(t,1)}}static _rendererMaterialsCache=new Map;onSet(e){if(n_||!this.enabled||e.sharedMaterials?.length<=0||!this.texture)return;let t=qn._rendererMaterialsCache.get(e);t||(t=[],qn._rendererMaterialsCache.set(e,t));for(let i=0;i<e.sharedMaterials.length;i++){const n=e.sharedMaterials[i];if(!n||n.envMap===void 0||n instanceof c.MeshBasicMaterial)continue;let o=t[i];const r=n===o?.copy,a=!o||o.material.uuid!==n.uuid||o.copy.version!==n.version;if(!r&&a){if($a){let d="";o?o.material!==n?d="reference changed; cached instance?: "+r:o.copy.version!==n.version&&(d="version changed"):d="not cached",console.warn("Cloning material",n.name,n.version,"Reason:",d,`
|
|
977
977
|
`,n.uuid,`
|
|
978
978
|
`,o?.copy.uuid,`
|
|
979
979
|
`,e.name)}const h=n.clone();h.version=n.version,o?(o.copy=h,o.material=n):(o={material:n,copy:h},t.push(o)),h[ff]=this,h[s_]=n,$a&&console.log("Set reflection",e.name,e.guid)}o&&o.copy&&(o.copy.onBeforeCompile=n.onBeforeCompile);const l=o?.copy;l.envMap=this.texture,e.sharedMaterials[i]=l}}onUnset(e){const t=qn._rendererMaterialsCache.get(e);if(t)for(let i=0;i<t.length;i++){const n=t[i];e.sharedMaterials[i]=n.material}}};bv([f(c.Vector3)],Vm.prototype,"center");bv([f(c.Vector3)],Vm.prototype,"size");let Wl=Vm;const Bt=x("debuginstancing");class Xo{static instance=new Xo;static getStartInstanceCount=e=>4;objs=[];setup(e,t,i,n,o,r=0){e.applySettings(t);const a=this.tryCreateOrAddInstance(t,i,o);if(a){n===null&&(n=[]),n.push(a),ne.NEEDLE_progressive.assignTextureLOD(a.renderer.material,0);for(let l=0;l<e.sharedMeshes.length;l++){const h=e.sharedMeshes[l],d=h.geometry;ne.NEEDLE_progressive.assignMeshLOD(h,0).then(u=>{u&&e.activeAndEnabled&&d!=u&&a.setGeometry(u)})}}else if(r<=0&&t.type!=="Mesh"){const l=r+1;for(const h of t.children)n=this.setup(e,h,i,n,o,l)}return r===0&&o.useMatrixWorldAutoUpdate&&n&&n.length>=0&&this.autoUpdateInstanceMatrix(t),n}tryCreateOrAddInstance(e,t,i){if(e.type==="Mesh"){const n=i.foundMeshes;if(i.foundMeshes+=1,!i.rend.enableInstancing)return null;if(i.rend.enableInstancing!==!0){if(n>=i.rend.enableInstancing.length)return Bt&&console.error("Something is wrong with instance setup",e,i.rend.enableInstancing,n),null;if(!i.rend.enableInstancing[n])return null}const o=e,r=o.material;for(const u of this.objs){if(!u.canAdd(o.geometry,r))continue;return u.addInstance(o)}let a=Xo.getStartInstanceCount(e);(!a||a<0)&&(a=4);let l=e.name;l?.length||(l=H_());const h=new NP(l,o.geometry,r,a,t);return this.objs.push(h),h.addInstance(o)}return null}autoUpdateInstanceMatrix(e){const t=e.matrixWorld.multiplyMatrices.bind(e.matrixWorld),i=e.matrixWorld.clone(),n=(o,r)=>{const a=t(o,r);return(e[Fl]||i.equals(a)===!1)&&(i.copy(a),e[Fl]=!0),a};e.matrixWorld.multiplyMatrices=n}}class zo{static all=[];get name(){return this.object.name}get isActive(){return this.__instanceIndex>=0}get vertexCount(){return this.object.geometry.attributes.position.count}get maxVertexCount(){return Math.max(this.meshInformation.vertexCount,this.vertexCount)}get reservedVertexCount(){return this.__reservedVertexRange}get indexCount(){return this.object.geometry.index?this.object.geometry.index.count:0}get maxIndexCount(){return Math.max(this.meshInformation.indexCount,this.indexCount)}get reservedIndexCount(){return this.__reservedIndexRange}object;renderer;__instanceIndex=-1;__reservedVertexRange=0;__reservedIndexRange=0;__geometryIndex=-1;meshInformation;constructor(e,t){this.__instanceIndex=-1,this.object=e,this.renderer=t,e[$b]=t,this.meshInformation=Co(e.geometry),zo.all.push(this)}updateMeshInformation(){const e=Co(this.object.geometry),t=this.meshInformation.vertexCount,i=this.meshInformation.indexCount;return Object.assign(this.meshInformation,e),t!==this.meshInformation.vertexCount||i!==this.meshInformation.indexCount}updateInstanceMatrix(e=!1,t=!0){this.__instanceIndex<0||(t&&this.object.updateWorldMatrix(!0,e),this.renderer.updateInstance(this.object.matrixWorld,this.__instanceIndex))}setMatrix(e){this.__instanceIndex<0||this.renderer.updateInstance(e,this.__instanceIndex)}setGeometry(e){if(this.__geometryIndex<0)return!1;const t=this;if(this.vertexCount>this.__reservedVertexRange)return i(`Instancing: Can not update geometry (${this.name}), reserved vertex range is too small: ${this.__reservedVertexRange.toLocaleString()} < ${this.vertexCount.toLocaleString()} vertices for ${this.name}`);if(this.indexCount>this.__reservedIndexRange)return i(`Instancing: Can not update geometry (${this.name}), reserved index range is too small: ${this.__reservedIndexRange.toLocaleString()} < ${this.indexCount.toLocaleString()} indices for ${this.name}`);return this.renderer.updateGeometry(e,this.__geometryIndex);function i(n){return t.updateMeshInformation()&&(t.renderer.remove(t,!0),t.renderer.add(t))?!0:((A()||Bt)&&console.error(n),!1)}}add(){this.__instanceIndex>=0||(this.renderer.add(this),S.markAsInstancedRendered(this.object,!0))}remove(e){if(!(this.__instanceIndex<0)&&(this.renderer.remove(this,e),S.markAsInstancedRendered(this.object,!1),e)){const t=zo.all.indexOf(this);t>=0&&zo.all.splice(t,1)}}}class NP{get batchedMesh(){return this._batchedMesh}get visible(){return this._batchedMesh.visible}set visible(e){this._batchedMesh.visible=e}get castShadow(){return this._batchedMesh.castShadow}set castShadow(e){this._batchedMesh.castShadow=e}set receiveShadow(e){this._batchedMesh.receiveShadow=e}allowResize=!0;name="";geometry;material;get count(){return this._currentInstanceCount}updateBounds(e=!0,t=!0){if(this._needUpdateBounds=!1,e&&this._batchedMesh.computeBoundingBox(),t&&this._batchedMesh.computeBoundingSphere(),Bt&&this._batchedMesh.boundingSphere){const i=this._batchedMesh.boundingSphere;B.DrawWireSphere(i.center,i.radius,65280)}}_context;_batchedMesh;_handles=[];_geometryIds=new Map;_maxInstanceCount;_currentInstanceCount=0;_currentVertexCount=0;_currentIndexCount=0;_maxVertexCount;_maxIndexCount;static nullMatrix=new c.Matrix4;canAdd(e,t){return this._maxVertexCount>1e7||t!==this.material||!this.validateGeometry(e)?!1:!!(!this.mustGrow(e)||this.allowResize)}_needUpdateBounds=!1;_debugMaterial=null;constructor(e,t,i,n,o){this.name=e,this.geometry=t,this.material=i,this._context=o,this._maxInstanceCount=Math.max(2,n),Bt&&(this._debugMaterial=o_());const r=this.tryEstimateVertexCountSize(this._maxInstanceCount,[t],n);this._maxVertexCount=r.vertexCount,this._maxIndexCount=r.indexCount,this._batchedMesh=new c.BatchedMesh(this._maxInstanceCount,this._maxVertexCount,this._maxIndexCount,this._debugMaterial??this.material),this._batchedMesh[rl]=!0,this._batchedMesh.visible=!0,this._context.scene.add(this._batchedMesh),i instanceof c.RawShaderMaterial&&(i.defines.USE_INSTANCING=!0,i.needsUpdate=!0),o.pre_render_callbacks.push(this.onBeforeRender),o.post_render_callbacks.push(this.onAfterRender),Bt&&console.log(`Instanced renderer created with ${this._maxInstanceCount} instances, ${this._maxVertexCount} max vertices and ${this._maxIndexCount} max indices for "${e}"`)}dispose(){Bt&&console.warn("Dispose instanced renderer",this.name),this._context.scene.remove(this._batchedMesh),this._batchedMesh.dispose(),this._batchedMesh=null,this._handles=[]}addInstance(e){const t=new zo(e,this);e.castShadow===!0&&this._batchedMesh.castShadow===!1&&(this._batchedMesh.castShadow=!0),e.receiveShadow===!0&&this._batchedMesh.receiveShadow===!1&&(this._batchedMesh.receiveShadow=!0);try{this.add(t)}catch(i){if(console.error(`Failed adding mesh to instancing (object name: "${e.name}", instances: ${this._currentInstanceCount.toLocaleString()}/${this._maxInstanceCount.toLocaleString()}, vertices: ${this._currentVertexCount.toLocaleString()}/${this._maxVertexCount.toLocaleString()}, indices: ${this._currentIndexCount.toLocaleString()}/${this._maxIndexCount.toLocaleString()})
|
|
@@ -1613,4 +1613,4 @@ Error:`,r),null}}updateColliderCollisionGroups(e){const t=e[kt],i=e.membership;l
|
|
|
1613
1613
|
justify-content: center;
|
|
1614
1614
|
gap: .5rem;
|
|
1615
1615
|
}
|
|
1616
|
-
`),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),dd(hp,{element:this.#t}),this.#o?.disconnect(),this.#o??=new MutationObserver(()=>this.#l()),this.#o.observe(this.#e,{attributes:!0}),zf&&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=>{zf&&console.log("Needle Button clicked"),!e.defaultPrevented&&this.#e&&this.#e.click()}}typeof window<"u"&&!window.customElements.get(N_)&&window.customElements.define(N_,Ox);const il=x("debugavatar");class $g{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 Mx{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 sn;i=S.instantiate(Jr(t,e.scene),o)}}else i=t;if(!i)return null;const n=this.findAvatar(i);return n.isValid?(il&&console.log("[Custom Avatar] valid config",t,il?n:""),n):(console.warn("[Custom Avatar] config isn't valid",t,il?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(il&&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 Ji().parseSync(e,o,null,0))?.scene??null:null}const i=new q.GLTFLoader;return bm(i,e),new Promise((n,o)=>{const r=this.avatarRegistryUrl+"/"+t;i.load(r,async a=>{await Ji().createBuiltinComponents(e,r,a,null,void 0),n(a.scene)},a=>{il&&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 $g(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 kx{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(e){}}class Rx{}const eE=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:le,ActionCollection:Iv,ActionModel:zt,AlignmentConstraint:dc,Animation:Gt,AnimationCurve:Tc,AnimationExtension:iu,AnimationTrackHandler:Cu,Animator:mt,AnimatorController:Ti,Antialiasing:Lc,AudioExtension:lr,AudioListener:ts,AudioSource:Di,AudioTrackHandler:ns,Avatar:qs,AvatarBlink_Simple:sr,AvatarEyeLook_Rotation:km,AvatarLoader:Mx,AvatarMarker:we,AvatarModel:$g,Avatar_Brain_LookAt:$l,Avatar_MouthShapes:mc,Avatar_MustacheShake:Om,Avatar_POI:Uo,AxesHelper:ga,BaseUIComponent:ji,BasicIKConstraint:Em,BehaviorExtension:og,BehaviorModel:pt,BloomEffect:mu,BoxCollider:Kd,BoxGizmo:ur,BoxHelperComponent:nt,Button:_s,CallInfo:es,Camera:Vt,CameraTargetReachedEvent:Vl,Canvas:ha,CanvasGroup:Xs,CapsuleCollider:rs,ChangeMaterialOnClick:Ym,ChangeTransformOnClick:cr,CharacterController:or,CharacterControllerInput:hs,ChromaticAberration:Dc,Collider:Xt,ColorAdjustments:lo,ColorBySpeedModule:ka,ColorOverLifetimeModule:uu,ContactShadows:gc,ControlTrackHandler:Pu,CustomBranding:dr,Deletable:Dm,DeleteBox:Vs,DepthOfField:an,DeviceFlag:Zd,DocumentExtension:kx,DragControls:Mo,DropListener:ds,Duplicatable:Bm,EffectWrapper:Xl,EmissionModule:gs,EmphasizeOnClick:va,EnvironmentScene:Eu,EventList:ae,EventListEvent:Hd,EventSystem:Dt,EventTrigger:eu,FieldWithDefault:vv,FixedJoint:bg,Fog:Pa,GltfExport:Hm,GltfExportBox:Wm,Gradient:pr,Graphic:Pc,GraphicRaycaster:qd,GridHelper:Oa,GridLayoutGroup:dg,GroundProjectedEnv:An,GroupActionModel:ko,HideOnStart:Oi,HingeJoint:Mc,HorizontalLayoutGroup:hg,Image:Ta,InheritVelocityModule:Sg,InputField:jg,InstanceHandle:zo,InstancingHandler:Xo,Interactable:Lm,Keyframe:$t,LODGroup:Rc,LODModel:Ma,Light:pi,LimitVelocityOverLifetimeModule:et,LogStats:Am,LookAt:Bg,LookAtConstraint:nr,MainModule:St,MaskableGraphic:Oc,MeshCollider:to,MeshRenderer:_c,MinMaxCurve:G,MinMaxGradient:mr,NeedleMenu:Dn,NestedGltf:Ec,Networking:xg,NoiseModule:fe,ObjectRaycaster:ci,OffsetConstraint:fr,OpenURL:Aa,OrbitControls:de,Outline:Ca,Padding:hr,ParticleBurst:Cd,ParticleSubEmitter:Cg,ParticleSystem:ql,ParticleSystemRenderer:Ni,PhysicsExtension:rg,PixelationEffect:Ic,PlayAnimationOnClick:Gl,PlayAudioOnClick:Hs,PlayableDirector:ua,PlayerColor:da,PointerEventData:fc,PostProcessingHandler:kg,PreliminaryAction:xa,PreliminaryTrigger:xc,RawImage:ku,Rect:zv,RectTransform:nn,ReflectionProbe:Wl,RegisteredAnimationInfo:Us,RemoteSkybox:yu,Renderer:hi,RendererLightmap:vd,Rigidbody:Ke,RotationBySpeedModule:zi,RotationOverLifetimeModule:rn,SceneSwitcher:Ie,ScreenCapture:co,ScreenSpaceAmbientOcclusion:ys,ScreenSpaceAmbientOcclusionN8:ln,SetActiveOnClick:Km,ShadowCatcher:Uc,ShapeModule:wg,SharpeningEffect:Bc,SignalAsset:Su,SignalReceiver:Wc,SignalReceiverEvent:$c,SignalTrackHandler:Ql,Size:Uv,SizeBySpeedModule:Kt,SizeOverLifetimeModule:gr,SkinnedMeshRenderer:$m,SmoothFollow:bu,SpatialGrabRaycaster:Ho,SpatialHtml:qc,SpatialTrigger:vu,SpatialTriggerReceiver:En,SpectatorCamera:xu,SphereCollider:ya,Sprite:fs,SpriteData:Kr,SpriteRenderer:Qt,SpriteSheet:ca,SubEmitterSystem:Pd,SyncedCamera:Eg,SyncedRoom:cn,SyncedTransform:tn,TapGestureTrigger:Jm,TeleportTarget:au,TestRunner:Tg,TestSimulateUserData:Ag,Text:wt,TextBuilder:lg,TextExtension:cu,TextureSheetAnimationModule:Ct,TiltShiftEffect:Bn,ToneMappingEffect:Qs,TrailModule:Ee,TransformData:ke,TransformGizmo:vr,TriggerBuilder:vt,TriggerModel:$s,UIRaycastUtils:wm,UIRootComponent:Sc,USDZExporter:Rn,USDZText:$r,USDZUIExtension:fg,UsageMarker:yc,VariantAction:Qm,VelocityOverLifetimeModule:Le,VerticalLayoutGroup:cg,VideoPlayer:Ze,Vignette:br,VisibilityAction:wc,Voip:eo,Volume:Ea,VolumeParameter:I,VolumeProfile:fu,WebARCameraBackground:Qc,WebARSessionRoot:ri,WebXR:lu,WebXRImageTracking:Yc,WebXRImageTrackingModel:vs,WebXRPlaneTracking:xs,WebXRTrackedImage:fa,XRControllerFollow:bs,XRControllerModel:as,XRControllerMovement:di,XRFlag:ki,XRRig:Au,XRState:Lt,__Ignore:Rx},Symbol.toStringTag,{value:"Module"})),Rd=x("debugmissingcamera");re.registerCallback(oe.MissingCamera,s=>{Rd&&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 Vt;if(i.sourceId=s.files?.[0]?.src??"unknown",i.fieldOfView=35,s.context.domElement.getAttribute("transparent")!=null)i.clearFlags=Fo.Uninitialized;else if(s.context.domElement.getAttribute("background-image")?.length||s.context.lightmaps.tryGetSkybox(i.sourceId))i.clearFlags=Fo.Skybox;else{if(i.clearFlags=Fo.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 Eu("neutral");e.environment=a.fromScene(l,.025).texture}}const o=Lo(t,i,!0);return t.position.x=0,t.position.y=1,t.position.z=2,s.context.domElement?.cameraControls!=!1&&Ex(s.context,o),o});re.registerCallback(oe.ContextCreated,s=>{if(!s.context.mainCamera){Rd&&console.log("Will not auto-fit because a default camera exists");return}if(s.context.domElement?.cameraControls==!0){if(nb(s.context.mainCamera)?.isCameraController==!0){Rd&&console.log("Will not auto-fit because a camera controller exists");return}Ex(s.context)}});function Ex(s,e){e=e??s.mainCameraComponent;const t=e?.gameObject;if(Rd&&console.log("Creating default camera controls",e?.name),t){const i=oc(t,de);i.sourceId=e?.sourceId??"unknown";const n=s.domElement.getAttribute("auto-rotate");if(i.autoRotate=n!=null&&n!="0"&&n?.toLowerCase()!="false",i.autoRotateSpeed=.5,i.autoFit=!0,i.autoRotate&&n){const o=parseFloat(n);isNaN(o)||(i.autoRotateSpeed=o)}}else console.warn("Missing camera object, can not add orbit controls")}re.registerCallback(oe.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 Gt&&n.playAutomatically||n instanceof mt||n instanceof ua&&n.playOnAwake===!0)return!0;if(n instanceof Gt)return n.playAutomatically=!0,!0;if(n instanceof ua)return n.playOnAwake=!0,!0}},!0)!==!0&&ra.autoplayAnimations(t.file)});class tE extends se.WorkerBase{constructor(){super(new Worker(new URL("/generateMeshBVH.worker-2qGLkQjg.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:Du&&Du.tagName.toUpperCase()==="SCRIPT"&&Du.src||new URL("needle-engine.bundle-DwiJRlay.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 b=new c.BufferAttribute(u.index,1,!1);t.setIndex(b)}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 iE=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:tE},Symbol.toStringTag,{value:"Module"}));exports.$physicsKey=H1;exports.ActionBuilder=le;exports.ActionCollection=Iv;exports.ActionModel=zt;exports.Addressables=b0;exports.AlignmentConstraint=dc;exports.AmbientMode=Qr;exports.Animation=Gt;exports.AnimationCurve=Tc;exports.AnimationExtension=iu;exports.AnimationTrackHandler=Cu;exports.AnimationUtils=ra;exports.Animator=mt;exports.AnimatorConditionMode=Ds;exports.AnimatorController=Ti;exports.AnimatorControllerParameterType=vm;exports.AnimatorStateInfo=al;exports.Antialiasing=Lc;exports.Application=en;exports.AssetDatabase=Ib;exports.AssetReference=Y;exports.AudioExtension=lr;exports.AudioListener=ts;exports.AudioSource=Di;exports.AudioTrackHandler=ns;exports.Avatar=qs;exports.AvatarBlink_Simple=sr;exports.AvatarEyeLook_Rotation=km;exports.AvatarLoader=Mx;exports.AvatarMarker=we;exports.AvatarModel=$g;exports.Avatar_Brain_LookAt=$l;exports.Avatar_MouthShapes=mc;exports.Avatar_MustacheShake=Om;exports.Avatar_POI=Uo;exports.Axes=Nr;exports.AxesHelper=ga;exports.BUILD_TIME=Xp;exports.BaseUIComponent=ji;exports.BasicIKConstraint=Em;exports.BehaviorExtension=og;exports.BehaviorModel=pt;exports.BloomEffect=mu;exports.BoxCollider=Kd;exports.BoxGizmo=ur;exports.BoxHelperComponent=nt;exports.Button=_s;exports.ButtonsFactory=Qi;exports.CallDirection=ev;exports.CallInfo=es;exports.Camera=Vt;exports.CameraTargetReachedEvent=Vl;exports.Canvas=ha;exports.CanvasGroup=Xs;exports.CapsuleCollider=rs;exports.ChangeMaterialOnClick=Ym;exports.ChangeTransformOnClick=cr;exports.CharacterController=or;exports.CharacterControllerInput=hs;exports.ChromaticAberration=Dc;exports.CircularBuffer=ai;exports.ClearFlags=Fo;exports.ClipExtrapolation=pn;exports.Collider=Xt;exports.Collision=K0;exports.CollisionDetectionMode=Gd;exports.ColorAdjustments=lo;exports.ColorBySpeedModule=ka;exports.ColorOverLifetimeModule=uu;exports.Component=t1;exports.Component$1=k;exports.ComponentLifecycleEvents=Bd;exports.Components=eE;exports.ConnectionEvents=Rb;exports.ContactPoint=Y0;exports.ContactShadows=gc;exports.Context=F;exports.ContextArgs=zC;exports.ContextEvent=oe;exports.ContextRegistry=re;exports.ControlTrackHandler=Pu;exports.CustomBranding=dr;exports.CustomShader=ye;exports.DefaultReflectionMode=hd;exports.Deletable=Dm;exports.DeleteBox=Vs;exports.DepthOfField=an;exports.DeviceFlag=Zd;exports.DocumentExtension=kx;exports.DragControls=Mo;exports.DragMode=Im;exports.DropListener=ds;exports.Duplicatable=Bm;exports.EffectWrapper=Xl;exports.EmissionModule=gs;exports.EmphasizeOnClick=va;exports.EngineLoadingView=Yl;exports.EnvironmentScene=Eu;exports.EventList=ae;exports.EventListEvent=Hd;exports.EventSystem=Dt;exports.EventTrigger=eu;exports.FieldWithDefault=vv;exports.FileReference=jo;exports.FileReferenceSerializer=x0;exports.FileSpawnModel=mP;exports.File_Event=av;exports.FixedJoint=bg;exports.Fog=Pa;exports.FrameEvent=pe;exports.GENERATOR=Ad;exports.GameObject=S;exports.Gizmos=B;exports.GltfExport=Hm;exports.GltfExportBox=Wm;exports.Gradient=pr;exports.Graphic=Pc;exports.GraphicRaycaster=qd;exports.Graphics=Gs;exports.GridHelper=Oa;exports.GridLayoutGroup=dg;exports.GroundProjectedEnv=An;exports.GroupActionModel=ko;exports.HideFlags=Xd;exports.HideOnStart=Oi;exports.HingeJoint=Mc;exports.HorizontalLayoutGroup=hg;exports.HostData=WS;exports.Image=Ta;exports.ImageReference=Io;exports.ImageReferenceSerializer=v0;exports.InheritVelocityModule=Sg;exports.Input=Sb;exports.InputEventQueue=Nt;exports.InputEvents=xe;exports.InputField=jg;exports.InstanceHandle=zo;exports.InstancingHandler=Xo;exports.InstancingUtil=Ei;exports.InstantiateEvent=qb;exports.InstantiateIdProvider=ft;exports.InstantiateOptions=sn;exports.Interactable=Lm;exports.JoinedRoomResponse=mS;exports.KeyEventArgs=sS;exports.Keyframe=$t;exports.LODGroup=Rc;exports.LODModel=Ma;exports.LeftRoomResponse=gS;exports.Light=pi;exports.LightData=O0;exports.LimitVelocityOverLifetimeModule=et;exports.LoadingElementOptions=UR;exports.LogStats=Am;exports.LogType=oi;exports.LookAt=Bg;exports.LookAtConstraint=nr;exports.MainModule=St;exports.MarkerType=Lg;exports.MaskableGraphic=Oc;exports.Mathf=D;exports.MeshCollider=to;exports.MeshRenderer=_c;exports.MinMaxCurve=G;exports.MinMaxGradient=mr;exports.NEKeyboardEvent=nl;exports.NEPointerEvent=Qn;exports.NeedleButtonElement=Ox;exports.NeedleEngineWebComponent=Vg;exports.NeedleMenu=Dn;exports.NeedlePatchesKey=Lh;exports.NeedleXRController=Zp;exports.NeedleXRSession=H;exports.NeedleXRSync=Ab;exports.NeedleXRUtils=Db;exports.NestedGltf=Ec;exports.NetworkConnection=Tb;exports.NetworkedStreamEvents=wn;exports.NetworkedStreams=pc;exports.Networking=xg;exports.NewInstanceModel=Qb;exports.NoiseModule=fe;exports.ObjectRaycaster=ci;exports.ObjectUtils=Zo;exports.OffsetConstraint=fr;exports.OneEuroFilter=Th;exports.OneEuroFilterXYZ=zp;exports.OpenURL=Aa;exports.OrbitControls=de;exports.Outline=Ca;exports.OwnershipEvent=Eb;exports.OwnershipModel=im;exports.PUBLIC_KEY=Fr;exports.Padding=hr;exports.ParticleBurst=Cd;exports.ParticleSubEmitter=Cg;exports.ParticleSystem=ql;exports.ParticleSystemBaseBehaviour=ao;exports.ParticleSystemRenderer=Ni;exports.ParticleSystemShapeType=Sd;exports.PeerHandle=is;exports.PeerNetworking=kb;exports.Physics=sa;exports.PhysicsExtension=rg;exports.PhysicsMaterialCombine=it;exports.PixelationEffect=Ic;exports.PlayAnimationOnClick=Gl;exports.PlayAudioOnClick=Hs;exports.PlayableDirector=ua;exports.PlayerColor=da;exports.PlayerState=Yi;exports.PlayerStateEvent=Fv;exports.PlayerSync=ng;exports.PlayerView=S0;exports.PlayerViewManager=C0;exports.PointerEventData=fc;exports.PointerType=Id;exports.PostProcessingEffect=Ne;exports.PostProcessingEffectOrder=Qe;exports.PostProcessingHandler=kg;exports.PreliminaryAction=xa;exports.PreliminaryTrigger=xc;exports.PrimitiveType=Vo;exports.Progress=ie;exports.PromiseAllWithErrors=Fp;exports.PromiseErrorResult=$f;exports.RGBAColor=Z;exports.RapierPhysics=Zr;exports.RawImage=ku;exports.RaycastOptions=Js;exports.Rect=zv;exports.RectTransform=nn;exports.ReflectionProbe=Wl;exports.RegisteredAnimationInfo=Us;exports.RemoteSkybox=yu;exports.RenderTexture=xn;exports.RenderTextureSerializer=H0;exports.Renderer=hi;exports.RendererData=P0;exports.RendererLightmap=vd;exports.Rigidbody=Ke;exports.RigidbodyConstraints=De;exports.RoomEvents=Q;exports.RotationBySpeedModule=zi;exports.RotationOverLifetimeModule=rn;exports.SceneLightSettings=yd;exports.SceneSwitcher=Ie;exports.ScreenCapture=co;exports.ScreenSpaceAmbientOcclusion=ys;exports.ScreenSpaceAmbientOcclusionN8=ln;exports.SendQueue=Xi;exports.SerializationContext=um;exports.SetActiveOnClick=Km;exports.ShadowCatcher=Uc;exports.ShapeModule=wg;exports.ShapeOverlapResult=Z0;exports.SharpeningEffect=Bc;exports.SignalAsset=Su;exports.SignalReceiver=Wc;exports.SignalReceiverEvent=$c;exports.SignalTrackHandler=Ql;exports.Size=Uv;exports.SizeBySpeedModule=Kt;exports.SizeOverLifetimeModule=gr;exports.SkinnedMeshRenderer=$m;exports.SmoothFollow=bu;exports.SpatialGrabRaycaster=Ho;exports.SpatialHtml=qc;exports.SpatialTrigger=vu;exports.SpatialTriggerReceiver=En;exports.SpectatorCamera=xu;exports.SphereCollider=ya;exports.SphereIntersection=om;exports.Sprite=fs;exports.SpriteData=Kr;exports.SpriteRenderer=Qt;exports.SpriteSheet=ca;exports.StateMachineBehaviour=a1;exports.StreamEndedEvent=Cm;exports.StreamReceivedEvent=J0;exports.SubEmitterSystem=Pd;exports.SyncedCamera=Eg;exports.SyncedRoom=cn;exports.SyncedTransform=tn;exports.TapGestureTrigger=Jm;exports.TeleportTarget=au;exports.TestRunner=Tg;exports.TestSceneUtils=XR;exports.TestSimulateUserData=Ag;exports.Text=wt;exports.TextBuilder=lg;exports.TextExtension=cu;exports.TextureSheetAnimationModule=Ct;exports.TiltShiftEffect=Bn;exports.Time=M0;exports.ToneMappingEffect=Qs;exports.TrackHandler=Gc;exports.TrackType=ei;exports.TrailModule=Ee;exports.TransformData=ke;exports.TransformGizmo=vr;exports.TriggerBuilder=vt;exports.TriggerModel=$s;exports.TypeStore=P;exports.UIRaycastUtils=wm;exports.UIRootComponent=Sc;exports.USDDocument=qm;exports.USDObject=ze;exports.USDWriter=Ov;exports.USDZExporter=Rn;exports.USDZExporter$1=Mv;exports.USDZText=$r;exports.USDZUIExtension=fg;exports.UriSerializer=q0;exports.UsageMarker=yc;exports.UserJoinedOrLeftRoomModel=yS;exports.VERSION=Ki;exports.VariantAction=Qm;exports.VelocityOverLifetimeModule=Le;exports.VerticalLayoutGroup=cg;exports.VideoPlayer=Ze;exports.ViewDevice=zs;exports.Vignette=br;exports.VisibilityAction=wc;exports.Voip=eo;exports.Volume=Ea;exports.VolumeParameter=I;exports.VolumeProfile=fu;exports.WaitForFrames=bC;exports.WaitForPromise=w0;exports.WaitForSeconds=mm;exports.Watch=ss;exports.WebARCameraBackground=Qc;exports.WebARSessionRoot=ri;exports.WebXR=lu;exports.WebXRButtonFactory=Ws;exports.WebXRImageTracking=Yc;exports.WebXRImageTrackingModel=vs;exports.WebXRPlaneTracking=xs;exports.WebXRTrackedImage=fa;exports.XRControllerFollow=bs;exports.XRControllerModel=as;exports.XRControllerMovement=di;exports.XRFlag=ki;exports.XRRig=Au;exports.XRState=Lt;exports.XRStateFlag=bn;exports.__Ignore=Rx;exports.__internalNotifyObjectDestroyed=Nb;exports.activeInHierarchyFieldName=os;exports.addAttributeChangeCallback=Q_;exports.addComponent=Zi;exports.addCustomExtensionPlugin=BP;exports.addNewComponent=Lo;exports.addPatch=Ld;exports.apply=Ud;exports.applyHMRChanges=e1;exports.applyPrototypeExtensions=a0;exports.beginListenDestroy=Xb;exports.beginListenInstantiate=Kb;exports.binaryIdentifierCasts=Jp;exports.build_scene_functions=UC;exports.builtinComponentKeyName=wo;exports.calculateProgress01=Ng;exports.clearMessages=pw;exports.colorSerializer=C1;exports.compareAssociation=t0;exports.componentSerializer=Vh;exports.copyTexture=hb;exports.createMotion=V0;exports.debugNet=jt;exports.debugOwner=sl;exports.decompressGpuTexture=Tv;exports.deepClone=Zl;exports.delay=Tn;exports.delayForFrames=Jl;exports.deserializeObject=ld;exports.destroy=li;exports.destroyComponentInstance=h0;exports.determineMimeTypeFromExtension=lv;exports.disposeObjectResources=_e;exports.disposeStream=Sn;exports.editorGuidKeyName=wl;exports.enableSpatialConsole=Eo;exports.euler=O1;exports.eventListSerializer=E1;exports.exportAsGLTF=KR;exports.findByGuid=pm;exports.findObjectOfType=lc;exports.findObjectsOfType=u0;exports.findResourceUsers=rm;exports.fitObjectIntoVolume=ub;exports.foreachComponent=Wo;exports.foreachComponentEnumerator=Nd;exports.forward=Tw;exports.generateQRCode=K_;exports.generateSeed=Yb;exports.getBoundingBox=Wt;exports.getCameraController=nb;exports.getComponent=er;exports.getComponentInChildren=ac;exports.getComponentInParent=Ul;exports.getComponents=rc;exports.getComponentsInChildren=pa;exports.getComponentsInParent=Fd;exports.getFormattedDate=wv;exports.getIconElement=ut;exports.getIconTexture=cp;exports.getLoader=Ji;exports.getOrAddComponent=oc;exports.getParam=x;exports.getParentHierarchyPath=Dw;exports.getPath=Gx;exports.getPeerOptions=dS;exports.getPeerjsInstance=Mb;exports.getResourceUserCount=IS;exports.getTempColor=rb;exports.getTempQuaternion=qi;exports.getTempVector=V;exports.getUrlParams=Kl;exports.getVisibleInCustomShadowRendering=db;exports.getWorldDirection=ab;exports.getWorldEuler=$p;exports.getWorldPosition=X;exports.getWorldQuaternion=ue;exports.getWorldRotation=Td;exports.getWorldScale=Ae;exports.hasCommercialLicense=kn;exports.hasIndieLicense=hc;exports.hasPointerEventComponent=fd;exports.hasProLicense=Mn;exports.hideDebugConsole=gb;exports.imageToCanvas=Av;exports.instantiate=Go;exports.invokeLoadedImportPluginHooks=yv;exports.invokeXRSessionEnd=wb;exports.invokeXRSessionStart=xb;exports.isActiveInHierarchy=f0;exports.isActiveSelf=ma;exports.isAndroidDevice=Kx;exports.isAnimationAction=cb;exports.isComponent=Q0;exports.isDebugMode=Nx;exports.isDesktop=qx;exports.isDestroyed=$o;exports.isDevEnvironment=A;exports.isDisposed=LS;exports.isExporting=QR;exports.isGLTFModel=X0;exports.isHostedOnGlitch=V_;exports.isHotReloadEnabled=pp;exports.isHotReloading=ZC;exports.isIPad=Qx;exports.isIconElement=E0;exports.isLocalNetwork=Ai;exports.isMacOS=Jx;exports.isMobileDevice=Xx;exports.isMozillaXR=Zx;exports.isQuest=iw;exports.isResourceTrackingEnabled=Bb;exports.isSafari=tw;exports.isUsingInstancing=zd;exports.isiOS=ew;exports.isiPad=Yx;exports.loadAsset=LR;exports.loadPMREM=lx;exports.loadSync=zg;exports.logHierarchy=ed;exports.lookAtInverse=Sw;exports.lookAtObject=ec;exports.lookAtScreenPoint=Cw;exports.makeId=$x;exports.makeIdFromRandomWords=H_;exports.makeNameSafe=Ii;exports.markAsInstancedRendered=p0;exports.microphonePermissionsGranted=nw;exports.nameof=zx;exports.nameofFactory=W_;exports.objectSerializer=G0;exports.offXRSessionEnd=nS;exports.offXRSessionStart=iS;exports.onAfterRender=YC;exports.onBeforeRender=QC;exports.onClear=qC;exports.onDestroy=XC;exports.onInitialized=I0;exports.onStart=_m;exports.onUpdate=j0;exports.onXRSessionEnd=Kp;exports.onXRSessionStart=Dd;exports.parseSync=xx;exports.placeOnSurface=fb;exports.postprocessFBXMaterials=Hp;exports.prefix=_1;exports.pushState=G_;exports.randomNumber=Wx;exports.registerBinaryType=em;exports.registerComponent=$d;exports.registerComponentExtension=zm;exports.registerCustomEffectType=Vi;exports.registerExportExtensions=Nm;exports.registerExtensions=bd;exports.registerHotReloadType=F0;exports.registerLoader=Qp;exports.registerPrefabProvider=Jb;exports.registerPrototypeExtensions=l0;exports.registerType=QS;exports.relativePathPrefix=X_;exports.removeAttributeChangeCallback=Y_;exports.removeComponent=fm;exports.removeCustomImportExtensionType=FP;exports.removePatch=eS;exports.resolveUrl=Ys;exports.sanitizeString=q_;exports.saveImage=yx;exports.screenshot=mR;exports.screenshot2=Ug;exports.sendDestroyed=lm;exports.serializable=f;exports.serializeObject=n0;exports.serializeable=tr;exports.setActive=Pl;exports.setAllowBalloonMessages=eb;exports.setAllowOverlayMessages=hw;exports.setAutoFitEnabled=Zh;exports.setCameraController=Gf;exports.setDestroyed=g0;exports.setDevEnvironment=Vw;exports.setDisposable=Ub;exports.setDontDestroy=Ar;exports.setOrAddParamsToUrl=Vf;exports.setParam=Vx;exports.setParamWithoutReload=Il;exports.setPeerOptions=uS;exports.setResourceTrackingEnabled=AS;exports.setState=jp;exports.setVisibleInCustomShadowRendering=Gp;exports.setWorldEuler=Wp;exports.setWorldPosition=Ye;exports.setWorldPositionXYZ=No;exports.setWorldQuaternion=Li;exports.setWorldQuaternionXYZW=Vp;exports.setWorldRotation=lb;exports.setWorldRotationXYZ=tc;exports.setWorldScale=ea;exports.showBalloonError=ic;exports.showBalloonMessage=Se;exports.showBalloonWarning=he;exports.showDebugConsole=qp;exports.slerp=ww;exports.syncDestroy=nc;exports.syncField=ig;exports.syncInstantiate=cm;exports.textureToCanvas=Iw;exports.tryCastBinary=Pb;exports.tryDetermineMimetypeFromBinary=hv;exports.tryDetermineMimetypeFromURL=cv;exports.tryFindObject=Jr;exports.tryGetGuid=Ob;exports.unregisterHotReloadType=U0;exports.unwatchWrite=Bp;exports.useForAutoFit=sb;exports.validate=gt;exports.watchWrite=Ed;
|
|
1616
|
+
`),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),dd(hp,{element:this.#t}),this.#o?.disconnect(),this.#o??=new MutationObserver(()=>this.#l()),this.#o.observe(this.#e,{attributes:!0}),zf&&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=>{zf&&console.log("Needle Button clicked"),!e.defaultPrevented&&this.#e&&this.#e.click()}}typeof window<"u"&&!window.customElements.get(N_)&&window.customElements.define(N_,Ox);const il=x("debugavatar");class $g{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 Mx{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 sn;i=S.instantiate(Jr(t,e.scene),o)}}else i=t;if(!i)return null;const n=this.findAvatar(i);return n.isValid?(il&&console.log("[Custom Avatar] valid config",t,il?n:""),n):(console.warn("[Custom Avatar] config isn't valid",t,il?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(il&&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 Ji().parseSync(e,o,null,0))?.scene??null:null}const i=new q.GLTFLoader;return bm(i,e),new Promise((n,o)=>{const r=this.avatarRegistryUrl+"/"+t;i.load(r,async a=>{await Ji().createBuiltinComponents(e,r,a,null,void 0),n(a.scene)},a=>{il&&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 $g(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 kx{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(e){}}class Rx{}const eE=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:le,ActionCollection:Iv,ActionModel:zt,AlignmentConstraint:dc,Animation:Gt,AnimationCurve:Tc,AnimationExtension:iu,AnimationTrackHandler:Cu,Animator:mt,AnimatorController:Ti,Antialiasing:Lc,AudioExtension:lr,AudioListener:ts,AudioSource:Di,AudioTrackHandler:ns,Avatar:qs,AvatarBlink_Simple:sr,AvatarEyeLook_Rotation:km,AvatarLoader:Mx,AvatarMarker:we,AvatarModel:$g,Avatar_Brain_LookAt:$l,Avatar_MouthShapes:mc,Avatar_MustacheShake:Om,Avatar_POI:Uo,AxesHelper:ga,BaseUIComponent:ji,BasicIKConstraint:Em,BehaviorExtension:og,BehaviorModel:pt,BloomEffect:mu,BoxCollider:Kd,BoxGizmo:ur,BoxHelperComponent:nt,Button:_s,CallInfo:es,Camera:Vt,CameraTargetReachedEvent:Vl,Canvas:ha,CanvasGroup:Xs,CapsuleCollider:rs,ChangeMaterialOnClick:Ym,ChangeTransformOnClick:cr,CharacterController:or,CharacterControllerInput:hs,ChromaticAberration:Dc,Collider:Xt,ColorAdjustments:lo,ColorBySpeedModule:ka,ColorOverLifetimeModule:uu,ContactShadows:gc,ControlTrackHandler:Pu,CustomBranding:dr,Deletable:Dm,DeleteBox:Vs,DepthOfField:an,DeviceFlag:Zd,DocumentExtension:kx,DragControls:Mo,DropListener:ds,Duplicatable:Bm,EffectWrapper:Xl,EmissionModule:gs,EmphasizeOnClick:va,EnvironmentScene:Eu,EventList:ae,EventListEvent:Hd,EventSystem:Dt,EventTrigger:eu,FieldWithDefault:vv,FixedJoint:bg,Fog:Pa,GltfExport:Hm,GltfExportBox:Wm,Gradient:pr,Graphic:Pc,GraphicRaycaster:qd,GridHelper:Oa,GridLayoutGroup:dg,GroundProjectedEnv:An,GroupActionModel:ko,HideOnStart:Oi,HingeJoint:Mc,HorizontalLayoutGroup:hg,Image:Ta,InheritVelocityModule:Sg,InputField:jg,InstanceHandle:zo,InstancingHandler:Xo,Interactable:Lm,Keyframe:$t,LODGroup:Rc,LODModel:Ma,Light:pi,LimitVelocityOverLifetimeModule:et,LogStats:Am,LookAt:Bg,LookAtConstraint:nr,MainModule:St,MaskableGraphic:Oc,MeshCollider:to,MeshRenderer:_c,MinMaxCurve:G,MinMaxGradient:mr,NeedleMenu:Dn,NestedGltf:Ec,Networking:xg,NoiseModule:fe,ObjectRaycaster:ci,OffsetConstraint:fr,OpenURL:Aa,OrbitControls:de,Outline:Ca,Padding:hr,ParticleBurst:Cd,ParticleSubEmitter:Cg,ParticleSystem:ql,ParticleSystemRenderer:Ni,PhysicsExtension:rg,PixelationEffect:Ic,PlayAnimationOnClick:Gl,PlayAudioOnClick:Hs,PlayableDirector:ua,PlayerColor:da,PointerEventData:fc,PostProcessingHandler:kg,PreliminaryAction:xa,PreliminaryTrigger:xc,RawImage:ku,Rect:zv,RectTransform:nn,ReflectionProbe:Wl,RegisteredAnimationInfo:Us,RemoteSkybox:yu,Renderer:hi,RendererLightmap:vd,Rigidbody:Ke,RotationBySpeedModule:zi,RotationOverLifetimeModule:rn,SceneSwitcher:Ie,ScreenCapture:co,ScreenSpaceAmbientOcclusion:ys,ScreenSpaceAmbientOcclusionN8:ln,SetActiveOnClick:Km,ShadowCatcher:Uc,ShapeModule:wg,SharpeningEffect:Bc,SignalAsset:Su,SignalReceiver:Wc,SignalReceiverEvent:$c,SignalTrackHandler:Ql,Size:Uv,SizeBySpeedModule:Kt,SizeOverLifetimeModule:gr,SkinnedMeshRenderer:$m,SmoothFollow:bu,SpatialGrabRaycaster:Ho,SpatialHtml:qc,SpatialTrigger:vu,SpatialTriggerReceiver:En,SpectatorCamera:xu,SphereCollider:ya,Sprite:fs,SpriteData:Kr,SpriteRenderer:Qt,SpriteSheet:ca,SubEmitterSystem:Pd,SyncedCamera:Eg,SyncedRoom:cn,SyncedTransform:tn,TapGestureTrigger:Jm,TeleportTarget:au,TestRunner:Tg,TestSimulateUserData:Ag,Text:wt,TextBuilder:lg,TextExtension:cu,TextureSheetAnimationModule:Ct,TiltShiftEffect:Bn,ToneMappingEffect:Qs,TrailModule:Ee,TransformData:ke,TransformGizmo:vr,TriggerBuilder:vt,TriggerModel:$s,UIRaycastUtils:wm,UIRootComponent:Sc,USDZExporter:Rn,USDZText:$r,USDZUIExtension:fg,UsageMarker:yc,VariantAction:Qm,VelocityOverLifetimeModule:Le,VerticalLayoutGroup:cg,VideoPlayer:Ze,Vignette:br,VisibilityAction:wc,Voip:eo,Volume:Ea,VolumeParameter:I,VolumeProfile:fu,WebARCameraBackground:Qc,WebARSessionRoot:ri,WebXR:lu,WebXRImageTracking:Yc,WebXRImageTrackingModel:vs,WebXRPlaneTracking:xs,WebXRTrackedImage:fa,XRControllerFollow:bs,XRControllerModel:as,XRControllerMovement:di,XRFlag:ki,XRRig:Au,XRState:Lt,__Ignore:Rx},Symbol.toStringTag,{value:"Module"})),Rd=x("debugmissingcamera");re.registerCallback(oe.MissingCamera,s=>{Rd&&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 Vt;if(i.sourceId=s.files?.[0]?.src??"unknown",i.fieldOfView=35,s.context.domElement.getAttribute("transparent")!=null)i.clearFlags=Fo.Uninitialized;else if(s.context.domElement.getAttribute("background-image")?.length||s.context.lightmaps.tryGetSkybox(i.sourceId))i.clearFlags=Fo.Skybox;else{if(i.clearFlags=Fo.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 Eu("neutral");e.environment=a.fromScene(l,.025).texture}}const o=Lo(t,i,!0);return t.position.x=0,t.position.y=1,t.position.z=2,s.context.domElement?.cameraControls!=!1&&Ex(s.context,o),o});re.registerCallback(oe.ContextCreated,s=>{if(!s.context.mainCamera){Rd&&console.log("Will not auto-fit because a default camera exists");return}if(s.context.domElement?.cameraControls==!0){if(nb(s.context.mainCamera)?.isCameraController==!0){Rd&&console.log("Will not auto-fit because a camera controller exists");return}Ex(s.context)}});function Ex(s,e){e=e??s.mainCameraComponent;const t=e?.gameObject;if(Rd&&console.log("Creating default camera controls",e?.name),t){const i=oc(t,de);i.sourceId=e?.sourceId??"unknown";const n=s.domElement.getAttribute("auto-rotate");if(i.autoRotate=n!=null&&n!="0"&&n?.toLowerCase()!="false",i.autoRotateSpeed=.5,i.autoFit=!0,i.autoRotate&&n){const o=parseFloat(n);isNaN(o)||(i.autoRotateSpeed=o)}}else console.warn("Missing camera object, can not add orbit controls")}re.registerCallback(oe.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 Gt&&n.playAutomatically||n instanceof mt||n instanceof ua&&n.playOnAwake===!0)return!0;if(n instanceof Gt)return n.playAutomatically=!0,!0;if(n instanceof ua)return n.playOnAwake=!0,!0}},!0)!==!0&&ra.autoplayAnimations(t.file)});class tE extends se.WorkerBase{constructor(){super(new Worker(new URL("/generateMeshBVH.worker-2qGLkQjg.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:Du&&Du.tagName.toUpperCase()==="SCRIPT"&&Du.src||new URL("needle-engine.bundle-DXoJZx7H.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 b=new c.BufferAttribute(u.index,1,!1);t.setIndex(b)}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 iE=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:tE},Symbol.toStringTag,{value:"Module"}));exports.$physicsKey=H1;exports.ActionBuilder=le;exports.ActionCollection=Iv;exports.ActionModel=zt;exports.Addressables=b0;exports.AlignmentConstraint=dc;exports.AmbientMode=Qr;exports.Animation=Gt;exports.AnimationCurve=Tc;exports.AnimationExtension=iu;exports.AnimationTrackHandler=Cu;exports.AnimationUtils=ra;exports.Animator=mt;exports.AnimatorConditionMode=Ds;exports.AnimatorController=Ti;exports.AnimatorControllerParameterType=vm;exports.AnimatorStateInfo=al;exports.Antialiasing=Lc;exports.Application=en;exports.AssetDatabase=Ib;exports.AssetReference=Y;exports.AudioExtension=lr;exports.AudioListener=ts;exports.AudioSource=Di;exports.AudioTrackHandler=ns;exports.Avatar=qs;exports.AvatarBlink_Simple=sr;exports.AvatarEyeLook_Rotation=km;exports.AvatarLoader=Mx;exports.AvatarMarker=we;exports.AvatarModel=$g;exports.Avatar_Brain_LookAt=$l;exports.Avatar_MouthShapes=mc;exports.Avatar_MustacheShake=Om;exports.Avatar_POI=Uo;exports.Axes=Nr;exports.AxesHelper=ga;exports.BUILD_TIME=Xp;exports.BaseUIComponent=ji;exports.BasicIKConstraint=Em;exports.BehaviorExtension=og;exports.BehaviorModel=pt;exports.BloomEffect=mu;exports.BoxCollider=Kd;exports.BoxGizmo=ur;exports.BoxHelperComponent=nt;exports.Button=_s;exports.ButtonsFactory=Qi;exports.CallDirection=ev;exports.CallInfo=es;exports.Camera=Vt;exports.CameraTargetReachedEvent=Vl;exports.Canvas=ha;exports.CanvasGroup=Xs;exports.CapsuleCollider=rs;exports.ChangeMaterialOnClick=Ym;exports.ChangeTransformOnClick=cr;exports.CharacterController=or;exports.CharacterControllerInput=hs;exports.ChromaticAberration=Dc;exports.CircularBuffer=ai;exports.ClearFlags=Fo;exports.ClipExtrapolation=pn;exports.Collider=Xt;exports.Collision=K0;exports.CollisionDetectionMode=Gd;exports.ColorAdjustments=lo;exports.ColorBySpeedModule=ka;exports.ColorOverLifetimeModule=uu;exports.Component=t1;exports.Component$1=k;exports.ComponentLifecycleEvents=Bd;exports.Components=eE;exports.ConnectionEvents=Rb;exports.ContactPoint=Y0;exports.ContactShadows=gc;exports.Context=F;exports.ContextArgs=zC;exports.ContextEvent=oe;exports.ContextRegistry=re;exports.ControlTrackHandler=Pu;exports.CustomBranding=dr;exports.CustomShader=ye;exports.DefaultReflectionMode=hd;exports.Deletable=Dm;exports.DeleteBox=Vs;exports.DepthOfField=an;exports.DeviceFlag=Zd;exports.DocumentExtension=kx;exports.DragControls=Mo;exports.DragMode=Im;exports.DropListener=ds;exports.Duplicatable=Bm;exports.EffectWrapper=Xl;exports.EmissionModule=gs;exports.EmphasizeOnClick=va;exports.EngineLoadingView=Yl;exports.EnvironmentScene=Eu;exports.EventList=ae;exports.EventListEvent=Hd;exports.EventSystem=Dt;exports.EventTrigger=eu;exports.FieldWithDefault=vv;exports.FileReference=jo;exports.FileReferenceSerializer=x0;exports.FileSpawnModel=mP;exports.File_Event=av;exports.FixedJoint=bg;exports.Fog=Pa;exports.FrameEvent=pe;exports.GENERATOR=Ad;exports.GameObject=S;exports.Gizmos=B;exports.GltfExport=Hm;exports.GltfExportBox=Wm;exports.Gradient=pr;exports.Graphic=Pc;exports.GraphicRaycaster=qd;exports.Graphics=Gs;exports.GridHelper=Oa;exports.GridLayoutGroup=dg;exports.GroundProjectedEnv=An;exports.GroupActionModel=ko;exports.HideFlags=Xd;exports.HideOnStart=Oi;exports.HingeJoint=Mc;exports.HorizontalLayoutGroup=hg;exports.HostData=WS;exports.Image=Ta;exports.ImageReference=Io;exports.ImageReferenceSerializer=v0;exports.InheritVelocityModule=Sg;exports.Input=Sb;exports.InputEventQueue=Nt;exports.InputEvents=xe;exports.InputField=jg;exports.InstanceHandle=zo;exports.InstancingHandler=Xo;exports.InstancingUtil=Ei;exports.InstantiateEvent=qb;exports.InstantiateIdProvider=ft;exports.InstantiateOptions=sn;exports.Interactable=Lm;exports.JoinedRoomResponse=mS;exports.KeyEventArgs=sS;exports.Keyframe=$t;exports.LODGroup=Rc;exports.LODModel=Ma;exports.LeftRoomResponse=gS;exports.Light=pi;exports.LightData=O0;exports.LimitVelocityOverLifetimeModule=et;exports.LoadingElementOptions=UR;exports.LogStats=Am;exports.LogType=oi;exports.LookAt=Bg;exports.LookAtConstraint=nr;exports.MainModule=St;exports.MarkerType=Lg;exports.MaskableGraphic=Oc;exports.Mathf=D;exports.MeshCollider=to;exports.MeshRenderer=_c;exports.MinMaxCurve=G;exports.MinMaxGradient=mr;exports.NEKeyboardEvent=nl;exports.NEPointerEvent=Qn;exports.NeedleButtonElement=Ox;exports.NeedleEngineWebComponent=Vg;exports.NeedleMenu=Dn;exports.NeedlePatchesKey=Lh;exports.NeedleXRController=Zp;exports.NeedleXRSession=H;exports.NeedleXRSync=Ab;exports.NeedleXRUtils=Db;exports.NestedGltf=Ec;exports.NetworkConnection=Tb;exports.NetworkedStreamEvents=wn;exports.NetworkedStreams=pc;exports.Networking=xg;exports.NewInstanceModel=Qb;exports.NoiseModule=fe;exports.ObjectRaycaster=ci;exports.ObjectUtils=Zo;exports.OffsetConstraint=fr;exports.OneEuroFilter=Th;exports.OneEuroFilterXYZ=zp;exports.OpenURL=Aa;exports.OrbitControls=de;exports.Outline=Ca;exports.OwnershipEvent=Eb;exports.OwnershipModel=im;exports.PUBLIC_KEY=Fr;exports.Padding=hr;exports.ParticleBurst=Cd;exports.ParticleSubEmitter=Cg;exports.ParticleSystem=ql;exports.ParticleSystemBaseBehaviour=ao;exports.ParticleSystemRenderer=Ni;exports.ParticleSystemShapeType=Sd;exports.PeerHandle=is;exports.PeerNetworking=kb;exports.Physics=sa;exports.PhysicsExtension=rg;exports.PhysicsMaterialCombine=it;exports.PixelationEffect=Ic;exports.PlayAnimationOnClick=Gl;exports.PlayAudioOnClick=Hs;exports.PlayableDirector=ua;exports.PlayerColor=da;exports.PlayerState=Yi;exports.PlayerStateEvent=Fv;exports.PlayerSync=ng;exports.PlayerView=S0;exports.PlayerViewManager=C0;exports.PointerEventData=fc;exports.PointerType=Id;exports.PostProcessingEffect=Ne;exports.PostProcessingEffectOrder=Qe;exports.PostProcessingHandler=kg;exports.PreliminaryAction=xa;exports.PreliminaryTrigger=xc;exports.PrimitiveType=Vo;exports.Progress=ie;exports.PromiseAllWithErrors=Fp;exports.PromiseErrorResult=$f;exports.RGBAColor=Z;exports.RapierPhysics=Zr;exports.RawImage=ku;exports.RaycastOptions=Js;exports.Rect=zv;exports.RectTransform=nn;exports.ReflectionProbe=Wl;exports.RegisteredAnimationInfo=Us;exports.RemoteSkybox=yu;exports.RenderTexture=xn;exports.RenderTextureSerializer=H0;exports.Renderer=hi;exports.RendererData=P0;exports.RendererLightmap=vd;exports.Rigidbody=Ke;exports.RigidbodyConstraints=De;exports.RoomEvents=Q;exports.RotationBySpeedModule=zi;exports.RotationOverLifetimeModule=rn;exports.SceneLightSettings=yd;exports.SceneSwitcher=Ie;exports.ScreenCapture=co;exports.ScreenSpaceAmbientOcclusion=ys;exports.ScreenSpaceAmbientOcclusionN8=ln;exports.SendQueue=Xi;exports.SerializationContext=um;exports.SetActiveOnClick=Km;exports.ShadowCatcher=Uc;exports.ShapeModule=wg;exports.ShapeOverlapResult=Z0;exports.SharpeningEffect=Bc;exports.SignalAsset=Su;exports.SignalReceiver=Wc;exports.SignalReceiverEvent=$c;exports.SignalTrackHandler=Ql;exports.Size=Uv;exports.SizeBySpeedModule=Kt;exports.SizeOverLifetimeModule=gr;exports.SkinnedMeshRenderer=$m;exports.SmoothFollow=bu;exports.SpatialGrabRaycaster=Ho;exports.SpatialHtml=qc;exports.SpatialTrigger=vu;exports.SpatialTriggerReceiver=En;exports.SpectatorCamera=xu;exports.SphereCollider=ya;exports.SphereIntersection=om;exports.Sprite=fs;exports.SpriteData=Kr;exports.SpriteRenderer=Qt;exports.SpriteSheet=ca;exports.StateMachineBehaviour=a1;exports.StreamEndedEvent=Cm;exports.StreamReceivedEvent=J0;exports.SubEmitterSystem=Pd;exports.SyncedCamera=Eg;exports.SyncedRoom=cn;exports.SyncedTransform=tn;exports.TapGestureTrigger=Jm;exports.TeleportTarget=au;exports.TestRunner=Tg;exports.TestSceneUtils=XR;exports.TestSimulateUserData=Ag;exports.Text=wt;exports.TextBuilder=lg;exports.TextExtension=cu;exports.TextureSheetAnimationModule=Ct;exports.TiltShiftEffect=Bn;exports.Time=M0;exports.ToneMappingEffect=Qs;exports.TrackHandler=Gc;exports.TrackType=ei;exports.TrailModule=Ee;exports.TransformData=ke;exports.TransformGizmo=vr;exports.TriggerBuilder=vt;exports.TriggerModel=$s;exports.TypeStore=P;exports.UIRaycastUtils=wm;exports.UIRootComponent=Sc;exports.USDDocument=qm;exports.USDObject=ze;exports.USDWriter=Ov;exports.USDZExporter=Rn;exports.USDZExporter$1=Mv;exports.USDZText=$r;exports.USDZUIExtension=fg;exports.UriSerializer=q0;exports.UsageMarker=yc;exports.UserJoinedOrLeftRoomModel=yS;exports.VERSION=Ki;exports.VariantAction=Qm;exports.VelocityOverLifetimeModule=Le;exports.VerticalLayoutGroup=cg;exports.VideoPlayer=Ze;exports.ViewDevice=zs;exports.Vignette=br;exports.VisibilityAction=wc;exports.Voip=eo;exports.Volume=Ea;exports.VolumeParameter=I;exports.VolumeProfile=fu;exports.WaitForFrames=bC;exports.WaitForPromise=w0;exports.WaitForSeconds=mm;exports.Watch=ss;exports.WebARCameraBackground=Qc;exports.WebARSessionRoot=ri;exports.WebXR=lu;exports.WebXRButtonFactory=Ws;exports.WebXRImageTracking=Yc;exports.WebXRImageTrackingModel=vs;exports.WebXRPlaneTracking=xs;exports.WebXRTrackedImage=fa;exports.XRControllerFollow=bs;exports.XRControllerModel=as;exports.XRControllerMovement=di;exports.XRFlag=ki;exports.XRRig=Au;exports.XRState=Lt;exports.XRStateFlag=bn;exports.__Ignore=Rx;exports.__internalNotifyObjectDestroyed=Nb;exports.activeInHierarchyFieldName=os;exports.addAttributeChangeCallback=Q_;exports.addComponent=Zi;exports.addCustomExtensionPlugin=BP;exports.addNewComponent=Lo;exports.addPatch=Ld;exports.apply=Ud;exports.applyHMRChanges=e1;exports.applyPrototypeExtensions=a0;exports.beginListenDestroy=Xb;exports.beginListenInstantiate=Kb;exports.binaryIdentifierCasts=Jp;exports.build_scene_functions=UC;exports.builtinComponentKeyName=wo;exports.calculateProgress01=Ng;exports.clearMessages=pw;exports.colorSerializer=C1;exports.compareAssociation=t0;exports.componentSerializer=Vh;exports.copyTexture=hb;exports.createMotion=V0;exports.debugNet=jt;exports.debugOwner=sl;exports.decompressGpuTexture=Tv;exports.deepClone=Zl;exports.delay=Tn;exports.delayForFrames=Jl;exports.deserializeObject=ld;exports.destroy=li;exports.destroyComponentInstance=h0;exports.determineMimeTypeFromExtension=lv;exports.disposeObjectResources=_e;exports.disposeStream=Sn;exports.editorGuidKeyName=wl;exports.enableSpatialConsole=Eo;exports.euler=O1;exports.eventListSerializer=E1;exports.exportAsGLTF=KR;exports.findByGuid=pm;exports.findObjectOfType=lc;exports.findObjectsOfType=u0;exports.findResourceUsers=rm;exports.fitObjectIntoVolume=ub;exports.foreachComponent=Wo;exports.foreachComponentEnumerator=Nd;exports.forward=Tw;exports.generateQRCode=K_;exports.generateSeed=Yb;exports.getBoundingBox=Wt;exports.getCameraController=nb;exports.getComponent=er;exports.getComponentInChildren=ac;exports.getComponentInParent=Ul;exports.getComponents=rc;exports.getComponentsInChildren=pa;exports.getComponentsInParent=Fd;exports.getFormattedDate=wv;exports.getIconElement=ut;exports.getIconTexture=cp;exports.getLoader=Ji;exports.getOrAddComponent=oc;exports.getParam=x;exports.getParentHierarchyPath=Dw;exports.getPath=Gx;exports.getPeerOptions=dS;exports.getPeerjsInstance=Mb;exports.getResourceUserCount=IS;exports.getTempColor=rb;exports.getTempQuaternion=qi;exports.getTempVector=V;exports.getUrlParams=Kl;exports.getVisibleInCustomShadowRendering=db;exports.getWorldDirection=ab;exports.getWorldEuler=$p;exports.getWorldPosition=X;exports.getWorldQuaternion=ue;exports.getWorldRotation=Td;exports.getWorldScale=Ae;exports.hasCommercialLicense=kn;exports.hasIndieLicense=hc;exports.hasPointerEventComponent=fd;exports.hasProLicense=Mn;exports.hideDebugConsole=gb;exports.imageToCanvas=Av;exports.instantiate=Go;exports.invokeLoadedImportPluginHooks=yv;exports.invokeXRSessionEnd=wb;exports.invokeXRSessionStart=xb;exports.isActiveInHierarchy=f0;exports.isActiveSelf=ma;exports.isAndroidDevice=Kx;exports.isAnimationAction=cb;exports.isComponent=Q0;exports.isDebugMode=Nx;exports.isDesktop=qx;exports.isDestroyed=$o;exports.isDevEnvironment=A;exports.isDisposed=LS;exports.isExporting=QR;exports.isGLTFModel=X0;exports.isHostedOnGlitch=V_;exports.isHotReloadEnabled=pp;exports.isHotReloading=ZC;exports.isIPad=Qx;exports.isIconElement=E0;exports.isLocalNetwork=Ai;exports.isMacOS=Jx;exports.isMobileDevice=Xx;exports.isMozillaXR=Zx;exports.isQuest=iw;exports.isResourceTrackingEnabled=Bb;exports.isSafari=tw;exports.isUsingInstancing=zd;exports.isiOS=ew;exports.isiPad=Yx;exports.loadAsset=LR;exports.loadPMREM=lx;exports.loadSync=zg;exports.logHierarchy=ed;exports.lookAtInverse=Sw;exports.lookAtObject=ec;exports.lookAtScreenPoint=Cw;exports.makeId=$x;exports.makeIdFromRandomWords=H_;exports.makeNameSafe=Ii;exports.markAsInstancedRendered=p0;exports.microphonePermissionsGranted=nw;exports.nameof=zx;exports.nameofFactory=W_;exports.objectSerializer=G0;exports.offXRSessionEnd=nS;exports.offXRSessionStart=iS;exports.onAfterRender=YC;exports.onBeforeRender=QC;exports.onClear=qC;exports.onDestroy=XC;exports.onInitialized=I0;exports.onStart=_m;exports.onUpdate=j0;exports.onXRSessionEnd=Kp;exports.onXRSessionStart=Dd;exports.parseSync=xx;exports.placeOnSurface=fb;exports.postprocessFBXMaterials=Hp;exports.prefix=_1;exports.pushState=G_;exports.randomNumber=Wx;exports.registerBinaryType=em;exports.registerComponent=$d;exports.registerComponentExtension=zm;exports.registerCustomEffectType=Vi;exports.registerExportExtensions=Nm;exports.registerExtensions=bd;exports.registerHotReloadType=F0;exports.registerLoader=Qp;exports.registerPrefabProvider=Jb;exports.registerPrototypeExtensions=l0;exports.registerType=QS;exports.relativePathPrefix=X_;exports.removeAttributeChangeCallback=Y_;exports.removeComponent=fm;exports.removeCustomImportExtensionType=FP;exports.removePatch=eS;exports.resolveUrl=Ys;exports.sanitizeString=q_;exports.saveImage=yx;exports.screenshot=mR;exports.screenshot2=Ug;exports.sendDestroyed=lm;exports.serializable=f;exports.serializeObject=n0;exports.serializeable=tr;exports.setActive=Pl;exports.setAllowBalloonMessages=eb;exports.setAllowOverlayMessages=hw;exports.setAutoFitEnabled=Zh;exports.setCameraController=Gf;exports.setDestroyed=g0;exports.setDevEnvironment=Vw;exports.setDisposable=Ub;exports.setDontDestroy=Ar;exports.setOrAddParamsToUrl=Vf;exports.setParam=Vx;exports.setParamWithoutReload=Il;exports.setPeerOptions=uS;exports.setResourceTrackingEnabled=AS;exports.setState=jp;exports.setVisibleInCustomShadowRendering=Gp;exports.setWorldEuler=Wp;exports.setWorldPosition=Ye;exports.setWorldPositionXYZ=No;exports.setWorldQuaternion=Li;exports.setWorldQuaternionXYZW=Vp;exports.setWorldRotation=lb;exports.setWorldRotationXYZ=tc;exports.setWorldScale=ea;exports.showBalloonError=ic;exports.showBalloonMessage=Se;exports.showBalloonWarning=he;exports.showDebugConsole=qp;exports.slerp=ww;exports.syncDestroy=nc;exports.syncField=ig;exports.syncInstantiate=cm;exports.textureToCanvas=Iw;exports.tryCastBinary=Pb;exports.tryDetermineMimetypeFromBinary=hv;exports.tryDetermineMimetypeFromURL=cv;exports.tryFindObject=Jr;exports.tryGetGuid=Ob;exports.unregisterHotReloadType=U0;exports.unwatchWrite=Bp;exports.useForAutoFit=sb;exports.validate=gt;exports.watchWrite=Ed;
|