@needle-tools/engine 4.5.0-alpha.5 → 4.5.0-alpha.6
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-d2825f28.min.js → needle-engine.bundle-0e1129e3.min.js} +2 -2
- package/dist/{needle-engine.bundle-ee9f7e66.light.umd.cjs → needle-engine.bundle-12ffa86b.light.umd.cjs} +4 -4
- package/dist/{needle-engine.bundle-946378ce.light.js → needle-engine.bundle-17f4eeec.light.js} +6 -6
- package/dist/{needle-engine.bundle-3a87a331.light.min.js → needle-engine.bundle-49c948a1.light.min.js} +2 -2
- package/dist/{needle-engine.bundle-6f1f506d.umd.cjs → needle-engine.bundle-a8ee7980.umd.cjs} +4 -4
- package/dist/{needle-engine.bundle-716cf6ce.js → needle-engine.bundle-dd25a467.js} +6 -6
- package/dist/needle-engine.js +2 -2
- package/dist/needle-engine.light.js +2 -2
- package/dist/needle-engine.light.min.js +1 -1
- package/dist/needle-engine.light.umd.cjs +1 -1
- package/dist/needle-engine.min.js +1 -1
- package/dist/needle-engine.umd.cjs +1 -1
- package/lib/engine/engine_loaders.js +1 -1
- package/lib/engine/engine_loaders.js.map +1 -1
- package/package.json +1 -1
- package/plugins/types/userconfig.d.ts +1 -1
- package/plugins/types/vite.d.ts +12 -2
- package/src/engine/engine_loaders.ts +1 -1
|
@@ -130,7 +130,7 @@ Open this page to get the console: `+t.toString())}const s=exports.DeviceUtiliti
|
|
|
130
130
|
#__vconsole .vc-mask {
|
|
131
131
|
overflow: hidden;
|
|
132
132
|
}
|
|
133
|
-
`,mi==null||mi.prepend(i),s===!0&&Tm()<=0&&i0(),console.log("🌵 Debug console has loaded")}},t.onerror=()=>{console.warn("🌵 Debug console failed to load."+(window.crossOriginIsolated?"This page is using cross-origin isolation, so external scripts can't be loaded.":"")),gl=!1,Wt=null},t.src="https://unpkg.com/vconsole@latest/dist/vconsole.min.js",document.body.appendChild(t)}function CS(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("needle-console","🌵 Inspect glTF"),t=()=>document.querySelector("#__vc_plug_"+s._id+" iframe");return s.on("renderTab",function(e){const i=globalThis["needle:codegen_files"];if(!i||i.length===0)return;let n=globalThis["needle:codegen_files"][0];const o=n.indexOf("?");o>-1&&(n=n.substring(0,o));const l=location.protocol+"//"+location.host+location.pathname+"/"+n,c=encodeURIComponent(l);s.fullUrl="https://viewer.needle.tools?inspect&file="+c;var d='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';e(d)}),s.on("show",function(){const e=t();e&&e.src!==s.fullUrl&&(e.src=s.fullUrl)}),s.on("hide",function(){const e=t();e&&(e.src="")}),s.on("addTopBar",function(e){var i=new Array;i.push({name:"Open in new window ↗",onClick:function(n){window.open(s.fullUrl,"_blank"),Wt==null||Wt.hide()}}),i.push({name:"Reload",onClick:function(n){const o=t();o&&(o.src=s.fullUrl)}}),i.push({name:"Fullscreen",onClick:function(n){const o=t();o.requestFullscreen?o.requestFullscreen():o.webkitRequestFullscreen instanceof Function&&o.webkitRequestFullscreen()}}),e(i)}),s}function PS(){const s=document.querySelector("#__vconsole .vc-switch");return s||null}function OS(){const s=document.querySelector("#__vconsole");return s||null}const o0=x("debugdefines");yo('if(!globalThis[""4.5.0-alpha.
|
|
133
|
+
`,mi==null||mi.prepend(i),s===!0&&Tm()<=0&&i0(),console.log("🌵 Debug console has loaded")}},t.onerror=()=>{console.warn("🌵 Debug console failed to load."+(window.crossOriginIsolated?"This page is using cross-origin isolation, so external scripts can't be loaded.":"")),gl=!1,Wt=null},t.src="https://unpkg.com/vconsole@latest/dist/vconsole.min.js",document.body.appendChild(t)}function CS(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("needle-console","🌵 Inspect glTF"),t=()=>document.querySelector("#__vc_plug_"+s._id+" iframe");return s.on("renderTab",function(e){const i=globalThis["needle:codegen_files"];if(!i||i.length===0)return;let n=globalThis["needle:codegen_files"][0];const o=n.indexOf("?");o>-1&&(n=n.substring(0,o));const l=location.protocol+"//"+location.host+location.pathname+"/"+n,c=encodeURIComponent(l);s.fullUrl="https://viewer.needle.tools?inspect&file="+c;var d='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';e(d)}),s.on("show",function(){const e=t();e&&e.src!==s.fullUrl&&(e.src=s.fullUrl)}),s.on("hide",function(){const e=t();e&&(e.src="")}),s.on("addTopBar",function(e){var i=new Array;i.push({name:"Open in new window ↗",onClick:function(n){window.open(s.fullUrl,"_blank"),Wt==null||Wt.hide()}}),i.push({name:"Reload",onClick:function(n){const o=t();o&&(o.src=s.fullUrl)}}),i.push({name:"Fullscreen",onClick:function(n){const o=t();o.requestFullscreen?o.requestFullscreen():o.webkitRequestFullscreen instanceof Function&&o.webkitRequestFullscreen()}}),e(i)}),s}function PS(){const s=document.querySelector("#__vconsole .vc-switch");return s||null}function OS(){const s=document.querySelector("#__vconsole");return s||null}const o0=x("debugdefines");yo('if(!globalThis[""4.5.0-alpha.6""]) globalThis[""4.5.0-alpha.6""] = "0.0.0";');yo('if(!globalThis[""undefined""]) globalThis[""undefined""] = "unknown";');yo('if(!globalThis[""Wed May 14 2025 21:49:24 GMT+0700 (Indochina Time)""]) globalThis[""Wed May 14 2025 21:49:24 GMT+0700 (Indochina Time)""] = "unknown";');yo('if(!globalThis[""npk_ad8e492e31253a2800d563522e42a7311d0d7b766ac4ec1f64d3b425f06eacbd""]) globalThis[""npk_ad8e492e31253a2800d563522e42a7311d0d7b766ac4ec1f64d3b425f06eacbd""] = "unknown";');yo('globalThis["__NEEDLE_ENGINE_VERSION__"] = "4.5.0-alpha.6";');yo('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";');yo('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Wed May 14 2025 21:49:24 GMT+0700 (Indochina Time)";');yo('globalThis["__NEEDLE_PUBLIC_KEY__"] = "npk_ad8e492e31253a2800d563522e42a7311d0d7b766ac4ec1f64d3b425f06eacbd";');const hn="4.5.0-alpha.6",Su="undefined",zm="Wed May 14 2025 21:49:24 GMT+0700 (Indochina Time)";o0&&console.log(`Engine version: ${hn} (generator: ${Su})
|
|
134
134
|
Project built at ${zm}`);const ec="npk_ad8e492e31253a2800d563522e42a7311d0d7b766ac4ec1f64d3b425f06eacbd",gs="needle_isActiveInHierarchy",Uo="builtin_components",tc="needle_editor_guid";function yo(s){try{(0,eval)(s)}catch(t){o0&&console.error(t)}}let r0,zy=null;function un(){return r0}function Nm(s){if(s==null){console.warn("Oh no: someone tried registering a non-existend gltf-loader. When you see this log it might mean that needle-engine is being imported multiple times. Please check your project setup.");return}zy!==s&&(zy=s,r0=new s)}const _i=Symbol("shadowDomOwner"),MS=x("debugpatch");function Cu(s,t,e,i){const n=MS===t;if(!e&&!i)return;const o=t+"___needle";ES(s,t,e,i);const a=Object.getOwnPropertyDescriptor(s,t),l=s[t];n&&console.log("Patch",s.constructor.name,t,a,l),a?(n&&console.log("Apply patch with existing descriptor",s.constructor.name,t,a),typeof a.value=="function"&&(s[t]=Vy(a.value,s,t))):(n&&console.log("Create patch with new property",s.constructor.name,t,a),Object.defineProperty(s,t,{set:function(c){if(typeof c=="function")this[o]=Vy(c,s,t);else{const d=this[o];a0(s,t,this,d,c),this[o]=c,l0(s,t,this,d,c)}},get:function(){const c=this[o];return typeof c=="function"&&c[o]?c[o]:c}}))}function RS(s,t,e){const i=Vm(s,t);if(i)for(let n=i.length-1;n>=0;n--){const o=i[n];o.prefix===e&&(o.prefix=null),o.postfix===e&&(o.postfix=null),!o.prefix&&!o.postfix&&i.splice(n,1)}}const Ny=Symbol("Needle:Patches:WrappedFunction");function Vy(s,t,e){if(s[Ny])return s;const i=function(...n){a0(t,e,this,...n);const o=s.apply(this,n);return l0(t,e,this,o,...n),o};return i[Ny]=!0,i}const md="Needle:Patches";function Np(){return globalThis[md]||(globalThis[md]=new WeakMap),globalThis[md]}function Vm(s,t){const e=Np().get(s);return e?e.get(t):null}function ES(s,t,e,i){let n=Np().get(s);n||(n=new Map,Np().set(s,n));let o=n.get(t);o||(o=[],n.set(t,o)),o.push({prefix:e,postfix:i})}function a0(s,t,e,...i){var o;if(!e)return;const n=Vm(s,t);if(n)for(const a of n)(o=a.prefix)==null||o.call(e,...i)}function l0(s,t,e,i,...n){var a;if(!e)return;const o=Vm(s,t);if(o)for(const l of o)(a=l.postfix)==null||a.call(e,i,...n)}const ka=[];function Pu(s){ka.indexOf(s)===-1&&ka.push(s)}function kS(s){const t=ka.indexOf(s);t!==-1&&ka.splice(t,1)}const Ta=[];function $m(s){Ta.indexOf(s)===-1&&Ta.push(s)}function TS(s){const t=Ta.indexOf(s);t!==-1&&Ta.splice(t,1)}function c0(s){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-start",{detail:s}));for(let t=0;t<ka.length;t++)ka[t](s)}function h0(s){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-end",{detail:s}));for(let t=0;t<Ta.length;t++)Ta[t](s)}const Ze=x("debuginput");var Ou=(s=>(s.Mouse="mouse",s.Touch="touch",s.Controller="controller",s.Hand="hand",s))(Ou||{}),Ee=(s=>(s.PointerDown="pointerdown",s.PointerUp="pointerup",s.PointerMove="pointermove",s.KeyDown="keydown",s.KeyUp="keyup",s.KeyPressed="keypress",s))(Ee||{});class os extends PointerEvent{constructor(e,i,n){super(e,n);r(this,"clientZ");r(this,"deviceIndex");r(this,"origin");r(this,"source");r(this,"mode");r(this,"_ray");r(this,"space");r(this,"isClick",!1);r(this,"isDoubleClick",!1);r(this,"_used",!1);r(this,"_pointerid");r(this,"_pointerType");r(this,"_type");r(this,"metadata",{});r(this,"intersections",new Array);r(this,"_immediatePropagationStopped",!1);r(this,"_propagationStopped",!1);this.clientZ=n.clientZ,this._pointerid=n.pointerId,this._pointerType=n.pointerType,this._type=e,this.deviceIndex=n.deviceIndex,this.origin=n.origin,this.source=i,this.mode=n.mode,this._ray=n.ray,this.space=n.device}get isSpatial(){return this.mode!="screen"}get ray(){return this._ray||(this._ray=new h.Ray(this.space.worldPosition.clone(),this.space.worldForward.clone())),this._ray}set ray(e){this._ray=e}get hasRay(){return this._ray!==void 0}get used(){return this._used}use(){this._used=!0}get pointerId(){return this._pointerid}get pointerType(){return this._pointerType}get type(){return this._type}get immediatePropagationStopped(){return this._immediatePropagationStopped}get propagationStopped(){return this._immediatePropagationStopped||this._propagationStopped}stopImmediatePropagation(){var e;this._immediatePropagationStopped=!0,super.stopImmediatePropagation(),(e=this.source)==null||e.stopImmediatePropagation()}stopPropagation(){var e;this._propagationStopped=!0,super.stopPropagation(),(e=this.source)==null||e.stopPropagation(),Ze&&console.warn("Stop propagation...",this.pointerId,this.pointerType)}}class jl extends KeyboardEvent{constructor(e,i,n){super(e,n);r(this,"source");this.source=i}stopImmediatePropagation(){var e;super.stopImmediatePropagation(),(e=this.source)==null||e.stopImmediatePropagation()}}class AS{constructor(t){r(this,"key");r(this,"keyType");r(this,"source");this.key=t.key,this.keyType=t.type,this.source=t}}var ei=(s=>(s[s.Early=-100]="Early",s[s.Default=0]="Default",s[s.Late=100]="Late",s))(ei||{});class d0{constructor(t){r(this,"_eventListeners",{});r(this,"_doubleClickTimeThreshold",.2);r(this,"_longPressTimeThreshold",1);r(this,"_setCursorTypes",[]);r(this,"context");r(this,"_pointerDown",[!1]);r(this,"_pointerUp",[!1]);r(this,"_pointerClick",[!1]);r(this,"_pointerDoubleClick",[!1]);r(this,"_pointerPressed",[!1]);r(this,"_pointerPositions",[new h.Vector2]);r(this,"_pointerPositionsLastFrame",[new h.Vector2]);r(this,"_pointerPositionsDelta",[new h.Vector2]);r(this,"_pointerPositionsRC",[new h.Vector2]);r(this,"_pointerPositionDown",[new h.Vector3]);r(this,"_pointerDownTime",[]);r(this,"_pointerUpTime",[]);r(this,"_pointerUpTimestamp",[]);r(this,"_pointerIds",[]);r(this,"_pointerTypes",[""]);r(this,"_mouseWheelChanged",[!1]);r(this,"_mouseWheelDeltaY",[0]);r(this,"_pointerEvent",[]);r(this,"_pointerEventsPressed",[]);r(this,"_pointerSpace",[]);r(this,"_pressedStack",new Map);r(this,"_htmlEventSource");r(this,"onLostFocus",()=>{for(const t in this.keysPressed)this.keysPressed[t].pressed=!1});r(this,"_receivedPointerMoveEventsThisFrame",new Array);r(this,"onEndOfFrame",()=>{this._receivedPointerMoveEventsThisFrame.length=0;for(let t=0;t<this._pointerUp.length;t++)this._pointerUp[t]=!1;for(let t=0;t<this._pointerDown.length;t++)this._pointerDown[t]=!1;for(let t=0;t<this._pointerClick.length;t++)this._pointerClick[t]=!1;for(let t=0;t<this._pointerDoubleClick.length;t++)this._pointerDoubleClick[t]=!1;for(const t of this._pointerPositionsDelta)t.set(0,0);for(let t=0;t<this._mouseWheelChanged.length;t++)this._mouseWheelChanged[t]=!1;for(let t=0;t<this._mouseWheelDeltaY.length;t++)this._mouseWheelDeltaY[t]=0});r(this,"onContextMenu",t=>{this.canReceiveInput(t)!==!1&&t instanceof PointerEvent&&t.pointerType});r(this,"keysPressed",{});r(this,"onKeyDown",t=>{if(Ze&&console.log(`key down ${t.code}, ${this.context.application.hasFocus}`,t),!this.context.application.hasFocus)return;const e=this.keysPressed[t.code];if(e&&e.pressed)return;this.keysPressed[t.code]={pressed:!0,frame:this.context.time.frameCount+1,startFrame:this.context.time.frameCount+1,key:t.key,code:t.code};const i=new jl("keydown",t,t);this.onDispatchEvent(i)});r(this,"onKeyPressed",t=>{if(!this.context.application.hasFocus)return;const e=this.keysPressed[t.code];if(!e)return;e.pressed=!0,e.frame=this.context.time.frameCount+1;const i=new jl("keypress",t,t);this.onDispatchEvent(i)});r(this,"onKeyUp",t=>{if(!this.context.application.hasFocus)return;const e=this.keysPressed[t.code];if(!e)return;e.pressed=!1,e.frame=this.context.time.frameCount+1;const i=new jl("keyup",t,t);this.onDispatchEvent(i)});r(this,"onWheelWindow",t=>{document.pointerLockElement&&this.onMouseWheel(t)});r(this,"onMouseWheel",t=>{if(this.canReceiveInput(t)===!1)return;this._mouseWheelDeltaY.length<=0&&this._mouseWheelDeltaY.push(0),this._mouseWheelChanged.length<=0&&this._mouseWheelChanged.push(!1),this._mouseWheelChanged[0]=!0;const e=this._mouseWheelDeltaY[0];this._mouseWheelDeltaY[0]=e+t.deltaY});r(this,"onPointerDown",t=>{if(this.context.isInAR||this.canReceiveInput(t)===!1)return;t.target instanceof HTMLElement&&t.target.setPointerCapture(t.pointerId);const e=this.getPointerId(t);Ze&&Te(`pointer down #${e}, identifier:${t.pointerId}`);const i=this.getAndUpdateSpatialObjectForScreenPosition(e,t.clientX,t.clientY),n=new os("pointerdown",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:e,button:t.button,clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,buttonName:this.getButtonName(t),device:i,pressure:t.pressure});this.onDown(n)});r(this,"onPointerMove",t=>{if(this.context.isInAR||this._receivedPointerMoveEventsThisFrame.includes(t.pointerId))return;this._receivedPointerMoveEventsThisFrame.push(t.pointerId);let e=t.button;t.pointerType==="mouse"&&(e=this.getFirstPressedButtonForPointer(0)??0);const i=this.getPointerId(t,e);e===-1&&(e=i);const n=this.getAndUpdateSpatialObjectForScreenPosition(i,t.clientX,t.clientY),o=new os("pointermove",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:i,button:e,clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,buttonName:this.getButtonName(t),device:n,pressure:t.pressure});this.onMove(o)});r(this,"onPointerCancel",t=>{this.context.isInAR||(Ze&&console.log("Pointer cancel",t),this.onPointerUp(t))});r(this,"onPointerUp",t=>{if(this.context.isInAR)return;t.target instanceof HTMLElement&&t.target.releasePointerCapture(t.pointerId);const e=this.getPointerId(t),i=new os("pointerup",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:e,button:t.button,clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,buttonName:this.getButtonName(t),device:this.getAndUpdateSpatialObjectForScreenPosition(e,t.clientX,t.clientY),pressure:t.pressure});this.onUp(i),this._pointerIds[e]=-1,Ze&&console.log("ID="+e,"PointerId="+t.pointerId,"ALL:",[...this._pointerIds])});r(this,"onTouchStart",t=>{if(this.context.isInAR)for(let e=0;e<t.changedTouches.length;e++){const i=t.changedTouches[e],n=this.getPointerIndex(i.identifier),o=this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),a=new os("pointerdown",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:0,clientX:i.clientX,clientY:i.clientY,pointerType:"touch",buttonName:"unknown",device:o,pressure:i.force});this.onDown(a)}});r(this,"onTouchMove",t=>{if(this.context.isInAR)for(let e=0;e<t.changedTouches.length;e++){const i=t.changedTouches[e],n=this.getPointerIndex(i.identifier),o=this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),a=new os("pointermove",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:0,clientX:i.clientX,clientY:i.clientY,pointerType:"touch",buttonName:"unknown",device:o,pressure:i.force});this.onMove(a)}});r(this,"onTouchEnd",t=>{if(this.context.isInAR)for(let e=0;e<t.changedTouches.length;e++){const i=t.changedTouches[e],n=this.getPointerIndex(i.identifier),o=new os("pointerup",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:0,clientX:i.clientX,clientY:i.clientY,pointerType:"touch",buttonName:"unknown",device:this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),pressure:i.force});this.onUp(o),this._pointerIds[n]=-1}});r(this,"tempNearPlaneVector",new h.Vector3);r(this,"tempFarPlaneVector",new h.Vector3);r(this,"tempLookMatrix",new h.Matrix4);this.context=t,this.context.post_render_callbacks.push(this.onEndOfFrame)}addEventListener(t,e,i){if(this._eventListeners[t]||(this._eventListeners[t]=[]),!e||typeof e!="function"){console.error("Invalid call to addEventListener: callback is required and must be a function!");return}i?i={...i}:i={};let n=0;(i==null?void 0:i.queue)!=null&&(n=i.queue);const o=this._eventListeners[t],a=o.find(l=>l.priority===n);a?a.listeners.push({callback:e,options:i}):(o.push({priority:n,listeners:[{callback:e,options:i}]}),o.sort((l,c)=>l.priority-c.priority))}removeEventListener(t,e,i){if(!this._eventListeners[t]||!e)return;const n=this._eventListeners[t];if((i==null?void 0:i.queue)!=null){const o=n.find(l=>l.priority===i.queue);if(!o)return;const a=o.listeners.findIndex(l=>l.callback===e);a>=0&&o.listeners.splice(a,1)}else for(const o of n){const a=o.listeners.findIndex(l=>l.callback===e);a>=0&&o.listeners.splice(a,1)}}dispatchEvent(t){var i,n,o,a;let e=!1;if(t instanceof jl){const l=this._eventListeners[t.type];if(l)for(const c of l)for(let d=0;d<c.listeners.length;d++){const u=c.listeners[d];if((n=(i=u.options)==null?void 0:i.signal)!=null&&n.aborted){c.listeners.splice(d,1),d--;continue}u.options.once&&(c.listeners.splice(d,1),d--),u.callback(t)}}if(t instanceof os){const l=this._eventListeners[t.type];if(l)for(const c of l){if(e)break;for(let d=0;d<c.listeners.length;d++){const u=c.listeners[d];if((a=(o=u.options)==null?void 0:o.signal)!=null&&a.aborted){c.listeners.splice(d,1),d--;continue}if(t.immediatePropagationStopped){e=!0,Ze&&console.log("immediatePropagationStopped",t.type);break}else t.propagationStopped&&(e=!0,Ze&&console.log("propagationStopped",t.type));u.options.once&&(c.listeners.splice(d,1),d--),u.callback(t)}}}}get mousePosition(){return this._pointerPositions[0]}get mousePositionRC(){return this._pointerPositionsRC[0]}get mouseDown(){return this._pointerDown[0]}get mouseUp(){return this._pointerUp[0]}get mouseClick(){return this._pointerClick[0]}get mouseDoubleClick(){return this._pointerDoubleClick[0]}get mousePressed(){return this._pointerPressed[0]}get mouseWheelChanged(){return this.getMouseWheelChanged(0)}get click(){return this._pointerClick[0]}get doubleClick(){return this._pointerDoubleClick[0]}getGamepad(t=0){return typeof navigator<"u"&&"getGamepads"in navigator&&navigator.getGamepads()[t]||null}setCursorPointer(){this.setCursor("pointer")}setCursorNormal(){this.unsetCursor("pointer")}setCursor(t){this._setCursorTypes.push(t),this._setCursorTypes.length>10&&this._setCursorTypes.shift(),this.updateCursor()}unsetCursor(t){for(let e=this._setCursorTypes.length-1;e>=0;e--)if(this._setCursorTypes[e]===t){this._setCursorTypes.splice(e,1),this.updateCursor();break}}updateCursor(){var t;((t=this._setCursorTypes)==null?void 0:t.length)==0?this.context.domElement.style.cursor="default":this.context.domElement.style.cursor=this._setCursorTypes[this._setCursorTypes.length-1]}getIsPointerIdInUse(t){for(const e of this._pointerEventsPressed)if(e.pointerId===t&&e.used)return!0;return!1}getPointerPressedCount(){let t=0;for(let e=0;e<this._pointerPressed.length;e++)this._pointerPressed[e]&&t++;return t}getPointerPosition(t){return t>=this._pointerPositions.length?null:this._pointerPositions[t]}getPointerPositionLastFrame(t){return t>=this._pointerPositionsLastFrame.length?null:this._pointerPositionsLastFrame[t]}getPointerPositionDelta(t){return t>=this._pointerPositionsDelta.length?null:this._pointerPositionsDelta[t]}getPointerPositionRC(t){return t>=this._pointerPositionsRC.length?null:this._pointerPositionsRC[t]}getPointerDown(t){return t>=this._pointerDown.length?!1:this._pointerDown[t]}getPointerUp(t){return t>=this._pointerUp.length?!1:this._pointerUp[t]}getPointerPressed(t){return t>=this._pointerPressed.length?!1:this._pointerPressed[t]}getPointerClicked(t){return t>=this._pointerClick.length?!1:this._pointerClick[t]}getPointerDoubleClicked(t){return t>=this._pointerDoubleClick.length?!1:this._pointerDoubleClick[t]}getPointerDownTime(t){return t>=this._pointerDownTime.length?-1:this._pointerDownTime[t]}getPointerUpTime(t){return t>=this._pointerUpTime.length?-1:this._pointerUpTime[t]}getPointerLongPress(t){return t>=this._pointerDownTime.length?!1:this.getPointerPressed(t)&&this.context.time.time-this._pointerDownTime[t]>this._longPressTimeThreshold}getIsMouse(t){return t<0||t>=this._pointerTypes.length?!1:this._pointerTypes[t]==="mouse"}getIsTouch(t){return t<0||t>=this._pointerTypes.length?!1:this._pointerTypes[t]==="touch"}getTouchesPressedCount(){let t=0;for(let e=0;e<this._pointerPressed.length;e++)this._pointerPressed[e]&&this.getIsTouch(e)&&t++;return t}getMouseWheelChanged(t=0){return t>=this._mouseWheelChanged.length?!1:this._mouseWheelChanged[t]}getMouseWheelDeltaY(t=0){return t>=this._mouseWheelDeltaY.length?0:this._mouseWheelDeltaY[t]}getPointerEvent(t){if(!(t>=this._pointerEvent.length))return this._pointerEvent[t]??void 0}*foreachPointerId(t){for(let e=0;e<this._pointerTypes.length;e++)if(this._pointerIsActive(e)){if(t!==void 0){const i=this._pointerTypes[e];if(Array.isArray(t)){let n=!1;for(const o of t)if(i===o){n=!0;break}if(!n)continue}else if(t!==i)continue}yield e}}*foreachTouchId(){for(let t=0;t<this._pointerTypes.length;t++)this._pointerTypes[t]==="touch"&&this._pointerIsActive[t]&&(yield t)}_pointerIsActive(t){return t<0?!1:this._pointerPressed[t]||this._pointerDown[t]||this._pointerUp[t]}onDownButton(t,e){let i=this._pressedStack.get(t);i||(i=[],this._pressedStack.set(t,i)),i.push(e)}onReleaseButton(t,e){const i=this._pressedStack.get(t);if(!i)return;const n=i.indexOf(e);n>=0&&i.splice(n,1)}getFirstPressedButtonForPointer(t){const e=this._pressedStack.get(t);if(e)return e[0]}getLatestPressedButtonForPointer(t){const e=this._pressedStack.get(t);if(e)return e[e.length-1]}getKeyDown(t){if(t!==void 0)return this.isKeyDown(t);for(const e in this.keysPressed){const i=this.keysPressed[e];if(i.startFrame===this.context.time.frameCount)return i.key}return null}getKeyPressed(t){if(t!==void 0)return this.isKeyPressed(t);for(const e in this.keysPressed){const i=this.keysPressed[e];if(i.pressed)return i.key}return null}getKeyUp(t){if(t!==void 0)return this.isKeyUp(t);for(const e in this.keysPressed){const i=this.keysPressed[e];return i.pressed===!1&&i.frame===this.context.time.frameCount}return null}isKeyDown(t){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const e=this.getCodeForCommonKeyName(t);if(e!==null){for(const n of e)if(this.isKeyDown(n))return!0;return!1}const i=this.keysPressed[t];return i?i.startFrame===this.context.time.frameCount&&i.pressed:!1}isKeyUp(t){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const e=this.getCodeForCommonKeyName(t);if(e!==null){for(const n of e)if(this.isKeyUp(n))return!0;return!1}const i=this.keysPressed[t];return i?i.frame===this.context.time.frameCount&&i.pressed===!1:!1}isKeyPressed(t){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const e=this.getCodeForCommonKeyName(t);if(e!==null){for(const n of e)if(this.isKeyPressed(n))return!0;return!1}const i=this.keysPressed[t];return i&&i.pressed||!1}getCodeForCommonKeyName(t){if(t.length===1){if(t>="0"&&t<="9")return["Digit"+t];if(t>="a"&&t<="z")return["Key"+t.toUpperCase()];if(t==" ")return["Space"]}switch(t){case"shift":case"Shift":return["ShiftLeft","ShiftRight"];case"control":case"Control":return["ControlLeft","ControlRight"];case"alt":case"Alt":return["AltLeft","AltRight"]}return null}createInputEvent(t){switch(t.type){case"pointerdown":Ze&&Te("Create Pointer down"),this.onDownButton(t.deviceIndex,t.button),this.onDown(t);break;case"pointermove":Ze&&Te("Create Pointer move"),this.onMove(t);break;case"pointerup":Ze&&Te("Create Pointer up"),this.onUp(t),this.onReleaseButton(t.deviceIndex,t.button);break}}convertScreenspaceToRaycastSpace(t){return t.x=(t.x-this.context.domX)/this.context.domWidth*2-1,t.y=-((t.y-this.context.domY)/this.context.domHeight)*2+1,t}bindEvents(){this.unbindEvents(),this._htmlEventSource=this.context.renderer.domElement,window.addEventListener("contextmenu",this.onContextMenu),this._htmlEventSource.addEventListener("pointerdown",this.onPointerDown,{passive:!0}),window.addEventListener("pointermove",this.onPointerMove,{passive:!0,capture:!0}),window.addEventListener("pointerup",this.onPointerUp,{passive:!0}),window.addEventListener("pointercancel",this.onPointerCancel,{passive:!0}),window.addEventListener("touchstart",this.onTouchStart,{passive:!0}),window.addEventListener("touchmove",this.onTouchMove,{passive:!0}),window.addEventListener("touchend",this.onTouchEnd,{passive:!0}),this._htmlEventSource.addEventListener("wheel",this.onMouseWheel,{passive:!0}),window.addEventListener("wheel",this.onWheelWindow,{passive:!0}),window.addEventListener("keydown",this.onKeyDown,!1),window.addEventListener("keypress",this.onKeyPressed,!1),window.addEventListener("keyup",this.onKeyUp,!1),window.addEventListener("blur",this.onLostFocus)}unbindEvents(){var t,e;window.removeEventListener("contextmenu",this.onContextMenu),(t=this._htmlEventSource)==null||t.removeEventListener("pointerdown",this.onPointerDown),window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),window.removeEventListener("pointercancel",this.onPointerCancel),window.removeEventListener("touchstart",this.onTouchStart),window.removeEventListener("touchmove",this.onTouchMove),window.removeEventListener("touchend",this.onTouchEnd),(e=this._htmlEventSource)==null||e.removeEventListener("wheel",this.onMouseWheel,!1),window.removeEventListener("wheel",this.onWheelWindow,!1),window.removeEventListener("keydown",this.onKeyDown,!1),window.removeEventListener("keypress",this.onKeyPressed,!1),window.removeEventListener("keyup",this.onKeyUp,!1),window.removeEventListener("blur",this.onLostFocus)}dispose(){const t=this.context.post_render_callbacks.indexOf(this.onEndOfFrame);t>=0&&this.context.post_render_callbacks.splice(t,1),this.unbindEvents()}canReceiveInput(t){var e;return t.target===((e=this.context.renderer)==null?void 0:e.domElement)||t.target===this.context.domElement||this.context.isInAR||this.context.isInAR&&t.target===document.body&&exports.DeviceUtilities.isMozillaXR()?!0:(Ze&&console.warn("CanReceiveInput:False for",t.target),!1)}getPointerId(t,e){return t.pointerType==="mouse"?0+(e??t.button):this.getPointerIndex(t.pointerId)}getButtonName(t){const e=t.button;if(t.pointerType==="mouse")switch(e){case 0:return"left";case 1:return"middle";case 2:return"right"}return"unknown"}getAndUpdateSpatialObjectForScreenPosition(t,e,i){let n=this._pointerSpace[t];n||(n=new h.Object3D,this._pointerSpace[t]=n),this._pointerSpace[t]=n;const o=this.context.mainCamera;if(o){const a=this.tempNearPlaneVector.set(e,i,-1);this.convertScreenspaceToRaycastSpace(a);const l=this.tempFarPlaneVector.set(a.x,a.y,1);a.unproject(o),l.unproject(o);const c=o.worldUp||$(0,1,0).applyQuaternion(ye(o));this.tempLookMatrix.lookAt(l,a,c),n.position.set(a.x,a.y,a.z),n.quaternion.setFromRotationMatrix(this.tempLookMatrix)}return n}isInRect(t){if(this.context.isInXR)return!0;const e=this.context.domElement.getBoundingClientRect(),i=t.clientX,n=t.clientY,o=i>=e.x&&i<=e.right&&n>=e.y&&n<=e.bottom;return Ze&&!o&&console.log("Not in rect",e,i,n),o}onDown(t){const e=t.pointerId;if(this.getPointerPressed(e)&&console.warn(`Received pointerDown for pointerId that is already pressed: ${e}`,Ze?t:""),Ze&&console.log(t.pointerType,"DOWN",e),!!this.isInRect(t)){for(this.setPointerState(e,this._pointerPressed,!0),this.setPointerState(e,this._pointerDown,!0),this.setPointerStateT(e,this._pointerEvent,t.source);e>=this._pointerTypes.length;)this._pointerTypes.push(t.pointerType);for(this._pointerTypes[e]=t.pointerType;e>=this._pointerPositionDown.length;)this._pointerPositionDown.push(new h.Vector3);for(this._pointerPositionDown[e].set(t.clientX,t.clientY,t.clientZ??0);e>=this._pointerPositions.length;)this._pointerPositions.push(new h.Vector2);this._pointerPositions[e].set(t.clientX,t.clientY),e>=this._pointerDownTime.length&&this._pointerDownTime.push(0),this._pointerDownTime[e]=this.context.time.realtimeSinceStartup,this.updatePointerPosition(t),this._pointerEventsPressed.push(t),this.onDispatchEvent(t)}}onMove(t){const e=t.pointerId,i=this.getPointerPressed(e);i===!1&&!this.isInRect(t)||t.pointerType==="touch"&&!i||(this.updatePointerPosition(t),this.setPointerStateT(e,this._pointerEvent,t.source),this.onDispatchEvent(t))}onUp(t){const e=t.pointerId;if(!this.getPointerPressed(e)){Ze&&console.log(t.pointerType,"UP",e,"was not down");return}Ze&&console.log(t.pointerType,"UP",e),this.setPointerState(e,this._pointerPressed,!1),this.setPointerStateT(e,this._pointerEvent,t.source),this.setPointerState(e,this._pointerUp,!0),this.updatePointerPosition(t);for(let c=this._pointerEventsPressed.length-1;c>=0;c--)if(this._pointerEventsPressed[c].pointerId===e){this._pointerEventsPressed.splice(c,1);break}if(!this._pointerPositionDown[e]){Ze&&pe("Received pointer up event without matching down event for button: "+e),console.warn("Received pointer up event without matching down event for button: "+e);return}const n=this._pointerUpTime[e],o=this._pointerDownTime[e],a=this.context.time.realtimeSinceStartup,l=a-o;if(e>=this._pointerUpTime.length&&this._pointerUpTime.push(-99),this._pointerUpTime[e]=a,l<1){let c=t.clientX-this._pointerPositionDown[e].x,d=t.clientY-this._pointerPositionDown[e].y,u=0;if(t.isSpatial&&t.clientZ!=null&&(u=t.clientZ-this._pointerPositionDown[e].z,c*=200,d*=200,u*=200),Math.abs(c)<5&&Math.abs(d)<5&&Math.abs(u)<5){this.setPointerState(e,this._pointerClick,!0),t.isClick=!0;const f=a-n;Ze&&console.log("CLICK",e,c,d,u,f),f<this._doubleClickTimeThreshold&&f>0&&(this.setPointerState(e,this._pointerDoubleClick,!0),t.isDoubleClick=!0)}}this.onDispatchEvent(t)}updatePointerPosition(t){const e=t.pointerId;for(;e>=this._pointerPositions.length;)this._pointerPositions.push(new h.Vector2);for(;e>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new h.Vector2);for(;e>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new h.Vector2);const i=this._pointerPositionsLastFrame[e];i.copy(this._pointerPositions[e]);const n=this._pointerPositionsDelta[e];let o=t.clientX-i.x,a=t.clientY-i.y;if(t.source instanceof MouseEvent||t.source instanceof TouchEvent){const u=t.source;o===0&&u.movementX!==0&&(o=u.movementX||0),a===0&&u.movementY!==0&&(a=u.movementY||0)}n.x+=o,n.y+=a,this._pointerPositions[e].x=t.clientX,this._pointerPositions[e].y=t.clientY;const l=t.clientX,c=t.clientY;for(;e>=this._pointerPositionsRC.length;)this._pointerPositionsRC.push(new h.Vector2);const d=this._pointerPositionsRC[e];d.set(l,c),this.convertScreenspaceToRaycastSpace(d)}getPointerIndex(t){let e=-1;for(let i=0;i<this._pointerIds.length;i++){if(this._pointerIds[i]===t)return i;e===-1&&this._pointerIds[i]===-1&&(e=i)}return e!==-1?(this._pointerIds[e]=t,e):(Ze&&console.log("PUSH pointerId:",t),this._pointerIds.push(t),this._pointerIds.length-1)}setPointerState(t,e,i){e[t]=i}setPointerStateT(t,e,i){return e[t]=i,i}onDispatchEvent(t){const e=Q.Current;try{Q.Current=this.context,this.dispatchEvent(t)}finally{Q.Current=e}}}const _a=new h.Matrix4().makeRotationY(Math.PI),Bi=new h.Quaternion().setFromAxisAngle(new h.Vector3(0,1,0),Math.PI),DS=x("debugwebxr");class LS{constructor(){r(this,"priority",-1e5);r(this,"gameObject");if(this.gameObject=new h.Object3D,this.gameObject.name="Implicit XR Rig",DS){const t=Ym(16733661);t.position.y+=.5,this.gameObject.add(t)}}isXRRig(){return!0}get isActive(){return this.gameObject.visible}}const Qn=x("debugwebxr"),Lh=x("debugcustomgesture"),IS="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",jS="generic-trigger",BS=new h.Quaternion().setFromEuler(new h.Euler(h.MathUtils.degToRad(0),h.MathUtils.degToRad(-90),h.MathUtils.degToRad(-90))),FS=new h.Vector3(.04,-.04,0);class Wm{constructor(t,e,i){r(this,"xr");r(this,"inputSource");r(this,"index",0);r(this,"emitEvents",!0);r(this,"_connected",!0);r(this,"_isTracking",!1);r(this,"__gamepad");r(this,"__hand");r(this,"__side");r(this,"_hitTestSource");r(this,"_hasSelectEvent",!1);r(this,"_isMxInk",!1);r(this,"_isMetaQuestTouchController",!1);r(this,"_handJointPoses",new Map);r(this,"_gripMatrix",new h.Matrix4);r(this,"_gripPosition",new h.Vector3);r(this,"_gripQuaternion",new h.Quaternion);r(this,"_linearVelocity",new h.Vector3);r(this,"_rayPositionRaw",new h.Vector3);r(this,"_rayRotationRaw",new h.Quaternion);r(this,"_rayMatrix",new h.Matrix4);r(this,"_rayPosition",new h.Vector3);r(this,"_rayQuaternion",new h.Quaternion);r(this,"_gripWorldPosition",new h.Vector3);r(this,"_gripWorldQuaternion",new h.Quaternion);r(this,"_rayWorldPosition",new h.Vector3);r(this,"_rayWorldQuaternion",new h.Quaternion);r(this,"_pinchPosition",new h.Vector3);r(this,"_ray");r(this,"_hand_wristDotUp");r(this,"_object");r(this,"_gripSpaceObject");r(this,"_raySpaceObject");r(this,"model",null);r(this,"_debugAxesHelper",new h.AxesHelper(.15));r(this,"_debugGripAxesHelper",new h.AxesHelper(.07));r(this,"_debugRayAxesHelper",new h.AxesHelper(.07));r(this,"_hitTestSourcePromise",null);r(this,"onPointerHits",t=>{});r(this,"_needleGamepadButtons",{});r(this,"_buttonMap",new Map);r(this,"_motioncontroller");r(this,"_layout");r(this,"getMotionController");r(this,"emitPointerDownEvent",!0);r(this,"emitPointerUpEvent",!0);r(this,"emitPointerMoveEvent",!0);r(this,"pointerMoveDistanceThreshold",.03);r(this,"pointerMoveAngleThreshold",.05);r(this,"_selectButtonIndex");r(this,"_squeezeButtonIndex");r(this,"onSelectStart",t=>{var n,o,a,l;if(!this.emitPointerDownEvent||this.inputSource!==t.inputSource)return;this.onUpdateFrame(t.frame),this._hasSelectEvent=!0;const e=(n=this._layout)==null?void 0:n.selectComponentId,i=(l=(a=(o=this._layout)==null?void 0:o.components[e])==null?void 0:a.gamepadIndices)==null?void 0:l.button;i!==void 0&&(this._selectButtonIndex=i),!Lh&&(Qn&&N.DrawDirection(this.rayWorldPosition,$(0,.01,1).applyQuaternion(this.rayWorldQuaternion),16711680,10),this.emitPointerEvent(Ee.PointerDown,this._selectButtonIndex||0,"xr-standard-trigger",!0,t))});r(this,"onSelectEnd",t=>{this.emitPointerUpEvent&&(Lh||this.inputSource===t.inputSource&&this.emitPointerEvent(Ee.PointerUp,this._selectButtonIndex||0,"xr-standard-trigger",!0,t))});r(this,"onSequeezeStart",t=>{var e,i,n;this.emitPointerDownEvent&&this.inputSource===t.inputSource&&(this._squeezeButtonIndex=(n=(i=(e=this._layout)==null?void 0:e.components["xr-standard-squeeze"])==null?void 0:i.gamepadIndices)==null?void 0:n.button,this._squeezeButtonIndex!==void 0&&(Qn&&N.DrawDirection(this.rayWorldPosition,$(0,.01,1).applyQuaternion(this.rayWorldQuaternion),255,10),this.emitPointerEvent(Ee.PointerDown,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,t)))});r(this,"onSequeezeEnd",t=>{this.emitPointerUpEvent&&this.inputSource===t.inputSource&&this._squeezeButtonIndex!==void 0&&this.emitPointerEvent(Ee.PointerUp,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,t)});r(this,"states",{});r(this,"_didMoveLastFrame",!1);r(this,"_lastPointerMovePosition",new h.Vector3);r(this,"_lastPointerMoveQuaternion",new h.Quaternion);r(this,"pointerInit");this.xr=t,this.inputSource=e,this.index=i,this._object=new h.Object3D,this._object.name=`NeedleXRController_${i}`,Qn&&(this._object.add(this._debugAxesHelper),this._gripSpaceObject=new h.Object3D,this._raySpaceObject=new h.Object3D,this._gripSpaceObject.name=`NeedleXRController_${i}_gripSpace`,this._raySpaceObject.name=`NeedleXRController_${i}_raySpace`,this._gripSpaceObject.add(this._debugGripAxesHelper),this._raySpaceObject.add(this._debugRayAxesHelper),this.xr.context.scene.add(this._gripSpaceObject),this.xr.context.scene.add(this._raySpaceObject)),this.xr.context.scene.add(this._object),this._ray=new h.Ray,this.pointerInit={origin:this,pointerType:this.hand?"hand":"controller",deviceIndex:this.index,pointerId:-1,mode:this.inputSource.targetRayMode,ray:this._ray,device:this._object,buttonName:"none"},this.initialize(),this.subscribeEvents()}get context(){return this.xr.context}get connected(){return this._connected}get isTracking(){return this._isTracking}get gamepad(){return this.__gamepad??(this.__gamepad=this.inputSource.gamepad)}get isHand(){return this.hand!=null}get hand(){return this.__hand??(this.__hand=this.inputSource.hand)}get handObject(){return this.context.renderer.xr.getHand(this.index)}get profiles(){return this.inputSource.profiles}get layout(){return this._layout}get targetRayMode(){return this.inputSource.targetRayMode}get targetRaySpace(){return this.inputSource.targetRaySpace}get gripSpace(){return this.inputSource.gripSpace}get side(){return this.__side??(this.__side=this.inputSource.handedness)}get isRight(){return this.side==="right"}get isLeft(){return this.side==="left"}get isStylus(){return this._isMxInk}getHitTestSource(){return this._hitTestSource||this._requestHitTestSource(),this._hitTestSource}get hasHitTestSource(){return this._hitTestSource}cancelHitTestSource(){this._hitTestSource&&(this._hitTestSource.cancel(),this._hitTestSource=void 0)}get hasSelectEvent(){return this._hasSelectEvent}getHitTest(){return this.xr.getHitTest(this)}getHandJointPose(t,e){var n;if(e=e||this.xr.frame,!this.hand||!(e!=null&&e.getJointPose)||!this.xr.referenceSpace)return null;let i=(n=this._handJointPoses)==null?void 0:n.get(t);return i||(i=e.getJointPose(t,this.xr.referenceSpace),i&&this._handJointPoses.set(t,i),i)}get gripPosition(){return $(this._gripPosition)}get gripQuaternion(){return an(this._gripQuaternion)}get gripMatrix(){return this._gripMatrix}get gripLinearVelocity(){return $(this._linearVelocity).applyQuaternion(Bi)}get rayPosition(){return $(this._rayPosition)}get rayQuaternion(){return an(this._rayQuaternion)}get gripWorldPosition(){return $(this._gripWorldPosition)}get gripWorldQuaternion(){return an(this._gripWorldQuaternion)}get rayWorldPosition(){return $(this._rayWorldPosition)}updateRayWorldPosition(){var e;const t=(e=this.xr.context.mainCamera)==null?void 0:e.parent;this._rayWorldPosition.copy(this._rayPositionRaw),t&&this._rayWorldPosition.applyMatrix4(t.matrixWorld)}get rayWorldQuaternion(){return an(this._rayWorldQuaternion)}get pinchPosition(){return $(this._pinchPosition)}updateRayWorldQuaternion(){var i;const t=(i=this.xr.context.mainCamera)==null?void 0:i.parent,e=t?ye(t):void 0;this._rayWorldQuaternion.copy(this._rayRotationRaw).multiply(Bi),e&&this._rayWorldQuaternion.premultiply(e)}get ray(){return this._ray.origin.copy(this.rayWorldPosition),this._ray.direction.copy($(0,0,1).applyQuaternion(this.rayWorldQuaternion)),this._ray}get handWristDotUp(){var e;if(this._hand_wristDotUp!==void 0)return this._hand_wristDotUp;const t=(e=this.handObject)==null?void 0:e.joints.wrist;if(t){const i=$(0,1,0).applyQuaternion(t.quaternion),n=$(0,1,0).dot(i);return this._hand_wristDotUp=n}}get isHandUpsideDown(){return this.handWristDotUp!==void 0?this.handWristDotUp<-.7:!1}get isTeleportGesture(){var t;return this.isHandUpsideDown&&((t=this.getGesture("pinch"))==null?void 0:t.isDown)}get object(){return this._object}async getModelUrl(){var t;return(t=this.getMotionController)==null?void 0:t.then(e=>(e==null?void 0:e.assetUrl)||null)}_requestHitTestSource(){var t;return this._hitTestSourcePromise?this._hitTestSourcePromise:this.xr.mode==="immersive-ar"&&this.inputSource.targetRayMode==="tracked-pointer"&&this.xr.session.requestHitTestSourceForTransientInput?this._hitTestSourcePromise=((t=this.xr.session.requestHitTestSourceForTransientInput({profile:this.inputSource.profiles[0],offsetRay:new XRRay}))==null?void 0:t.then(e=>(this._hitTestSourcePromise=null,this.connected?this._hitTestSource=e:(e.cancel(),null))))??null:null}onUpdate(t){this.onUpdateFrame(t),this.updateInputEvents(),this.onUpdateMove()}onRenderDebug(){var o;N.DrawSphere(this.rayWorldPosition,.003),N.DrawDirection(this.rayWorldPosition,$(0,0,10).applyQuaternion(this.rayWorldQuaternion));const e=(this.inputSource.gripSpace?this.gripWorldPosition:this.object.worldPosition).sub(this.object.worldForward.multiplyScalar(.1)),i=this.inputSource.profiles.join(`
|
|
135
135
|
`);let n=`Controller[${this.index}] (${this.inputSource.targetRayMode}, ${this.side})
|
|
136
136
|
C:${this.connected?"x":"-"} T:${this.isTracking?"x":"-"} Hand:${this.inputSource.hand?"x":"-"} Pen: ${this._isMxInk?"x":"-"}`;if(this.inputSource.hand&&(n+=`
|
|
@@ -1266,7 +1266,7 @@ axisFormat %s
|
|
|
1266
1266
|
outputColor = sharp;
|
|
1267
1267
|
}
|
|
1268
1268
|
|
|
1269
|
-
`;class e extends exports.MODULES.POSTPROCESSING.MODULE.Effect{constructor(){super("Sharpening",t,{vertexShader:s,blendFunction:exports.MODULES.POSTPROCESSING.MODULE.BlendFunction.NORMAL,uniforms:new Map([["amount",new h.Uniform$1(1)],["radius",new h.Uniform$1(1)]])})}}return e}var VE=Object.defineProperty,$E=Object.getOwnPropertyDescriptor,ol=(s,t,e,i)=>{for(var n=i>1?void 0:i?$E(t,e):t,o=s.length-1,a;o>=0;o--)(a=s[o])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&VE(t,e,n),n};class Xn extends Xe{constructor(){super(...arguments);r(this,"offset",new U(0));r(this,"rotation",new U(0));r(this,"focusArea",new U(.4));r(this,"feather",new U(.3));r(this,"kernelSize",new U(2));r(this,"resolutionScale",new U(1/window.devicePixelRatio))}get typeName(){return"TiltShiftEffect"}init(){this.offset.defaultValue=0,this.rotation.defaultValue=0,this.focusArea.defaultValue=.4,this.feather.defaultValue=.3,this.kernelSize.defaultValue=exports.MODULES.POSTPROCESSING.MODULE.KernelSize.MEDIUM,this.resolutionScale.defaultValue=1/window.devicePixelRatio}onCreateEffect(){const e=new exports.MODULES.POSTPROCESSING.MODULE.TiltShiftEffect({kernelSize:exports.MODULES.POSTPROCESSING.MODULE.KernelSize.VERY_LARGE,offset:this.offset.value,rotation:this.rotation.value,focusArea:this.focusArea.value,feather:this.feather.value});return this.offset.onValueChanged=i=>e.offset=i,this.rotation.onValueChanged=i=>e.rotation=i,this.focusArea.onValueChanged=i=>e.focusArea=i,this.feather.onValueChanged=i=>e.feather=i,this.kernelSize.onValueChanged=i=>e.blurPass.kernelSize=i,this.resolutionScale.onValueChanged=i=>e.resolution.scale=i/window.devicePixelRatio,e}}ol([p(U)],Xn.prototype,"offset",2);ol([p(U)],Xn.prototype,"rotation",2);ol([p(U)],Xn.prototype,"focusArea",2);ol([p(U)],Xn.prototype,"feather",2);ol([p(U)],Xn.prototype,"kernelSize",2);ol([p(U)],Xn.prototype,"resolutionScale",2);Ki("TiltShiftEffect",Xn);var WE=Object.defineProperty,HE=Object.getOwnPropertyDescriptor,sy=(s,t,e,i)=>{for(var n=i>1?void 0:i?HE(t,e):t,o=s.length-1,a;o>=0;o--)(a=s[o])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&WE(t,e,n),n};class Br extends Xe{constructor(){super(...arguments);r(this,"color",new U({r:0,g:0,b:0,a:1}));r(this,"intensity",new U(0));r(this,"center",new U({x:.5,y:.5}))}get typeName(){return"Vignette"}init(){this.color.defaultValue={r:0,g:0,b:0,a:1},this.intensity.defaultValue=0,this.center.defaultValue={x:.5,y:.5}}onCreateEffect(){const e=new exports.MODULES.POSTPROCESSING.MODULE.VignetteEffect;return this.intensity.onValueChanged=i=>{e.offset=i,this.updateDarkness(e)},this.color.onValueChanged=i=>{this.updateDarkness(e)},e}updateDarkness(e){const i=this.intensity.value;e.darkness=i}}sy([p(U)],Br.prototype,"color",2);sy([p(U)],Br.prototype,"intensity",2);sy([p(U)],Br.prototype,"center",2);Ki("Vignette",Br);globalThis.false=globalThis.false!==void 0?globalThis.false:!0;const Jn=x("debugpost"),GE=x("debugpostpasses"),cp=Symbol("needle:postprocessing-handler"),hp=Symbol("needle:previous-autoclear-state");class oy{constructor(t){r(this,"_composer",null);r(this,"_lastVolumeComponents");r(this,"_effects",[]);r(this,"_isActive",!1);r(this,"context");r(this,"_menuEntry",null);r(this,"_passIndices",null);this.context=t}get isActive(){return this._isActive}get composer(){return this._composer}apply(t){return"env"in{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:ya&&ya.tagName.toUpperCase()==="SCRIPT"&&ya.src||new URL("needle-engine.bundle-ee9f7e66.light.umd.cjs",document.baseURI).href}&&{}.VITE_NEEDLE_USE_POSTPROCESSING==="false"?(Jn?console.warn("Postprocessing is disabled via vite env setting"):console.debug("Postprocessing is disabled via vite env setting"),Promise.resolve()):(Jn?console.warn("Postprocessing is disabled via global vite define setting"):console.debug("Postprocessing is disabled via vite define"),Promise.resolve())}unapply(){var i;if(Jn&&console.log("Unapplying postprocessing effects"),this._isActive=!1,this._lastVolumeComponents){for(const n of this._lastVolumeComponents)n.unapply();this._lastVolumeComponents.length=0}const t=this.context;t[cp]===this&&delete t[cp],t.composer===this._composer&&((i=t.composer)==null||i.dispose(),t.composer=null),typeof t.renderer[hp]=="boolean"&&(t.renderer.autoClear=t.renderer[hp])}dispose(){this.unapply();for(const t of this._effects)t.dispose();this._effects.length=0,this._composer=null}async onApply(t,e){if(!e)return;await Promise.all([exports.MODULES.POSTPROCESSING.load(),exports.MODULES.POSTPROCESSING_AO.load()]),t[cp]=this,Jn&&console.log("Apply Postprocessing Effects",e),this._lastVolumeComponents=[...e],this._effects.length=0;const i={handler:this,components:this._lastVolumeComponents};for(let n=0;n<this._lastVolumeComponents.length;n++){const o=this._lastVolumeComponents[n];if(o.context=t,o.apply){if(o.active){if(!t.mainCameraComponent){console.error("No camera in scene found or available yet - can not create postprocessing effects");return}const a=o.apply(i);if(!a)continue;Array.isArray(a)?this._effects.push(...a):this._effects.push(a)}}else o.active&&pe("Volume component is not a VolumeComponent: "+o.__type)}if(this.context.renderer.toneMapping!=h.NoToneMapping&&!this._effects.find(n=>n instanceof exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect)){const n=new exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect;this._effects.push(n)}this.applyEffects(t)}applyEffects(t){const e=this._effects;if(e.length<=0)return;const i=t.mainCameraComponent,n=t.renderer,o=t.scene,a=i.threeCamera;n[hp]=n.autoClear,this._composer||(this._composer=new exports.MODULES.POSTPROCESSING.MODULE.EffectComposer(n,{frameBufferType:h.HalfFloatType,stencilBuffer:!0})),t.composer&&t.composer!==this._composer&&console.warn("There's already an active EffectComposer in your scene: replacing it with a new one. This might cause unexpected behaviour. Make sure to only use one PostprocessingManager/Volume in your scene."),t.composer=this._composer;const l=t.composer;l.setMainCamera(a),l.setRenderer(n),l.setMainScene(o);for(const d of l.passes)d.dispose();l.removeAllPasses();const c=new exports.MODULES.POSTPROCESSING.MODULE.RenderPass(o,a);if(c.name="Render To Screen",c.mainScene=o,l.addPass(c),GE){this.orderEffects();for(const d of e)if(d instanceof exports.MODULES.POSTPROCESSING.MODULE.Effect){const u=new exports.MODULES.POSTPROCESSING.MODULE.EffectPass(a,d);u.name=d.name,l.addPass(u)}else d instanceof exports.MODULES.POSTPROCESSING.MODULE.Pass,l.addPass(d)}else try{this.orderEffects();const d=[];for(const u of e)u instanceof exports.MODULES.POSTPROCESSING.MODULE.Effect?d.push(u):(u instanceof exports.MODULES.POSTPROCESSING.MODULE.Pass,l.addPass(u));if(d.length>0){const u=new exports.MODULES.POSTPROCESSING.MODULE.EffectPass(a,...d);u.name=d.map(f=>f.name).join(" "),u.mainScene=o,u.enabled=!0,l.addPass(u)}}catch(d){console.error("Error while applying postprocessing effects",d),l.removeAllPasses()}if(Jn){console.log("[PostProcessing] Passes →",l.passes);const d=new exports.MODULES.POSTPROCESSING.MODULE.DepthEffect({blendFunction:exports.MODULES.POSTPROCESSING.MODULE.BlendFunction.NORMAL,inverted:!0});d.name="Depth Effect";const u=new exports.MODULES.POSTPROCESSING.MODULE.EffectPass(a,d);if(u.name="Depth Effect Pass",u.enabled=!1,l.passes.push(u),this._passIndices!==null){const m=[l.passes[0]];this._passIndices.length>0&&m.push(...this._passIndices.filter(g=>g!==0).map(g=>l.passes[g]).filter(g=>g)),m.length>0&&console.log("[PostProcessing] Passes (selected) →",m),l.passes.length=0;for(const g of m)g.enabled=!0,g.renderToScreen=!1,l.addPass(g)}const f=this.context.menu;if(f&&this._passIndices===null){this._menuEntry&&this._menuEntry.remove();const m=document.createElement("select");m.multiple=!0;const g=document.createElement("option");g.innerText="Final Output",g.value="-1",m.appendChild(g);for(const y of l.passes){const _=document.createElement("option");_.innerText=y.name,_.value=`${l.passes.indexOf(y)}`,_.title=y.name,m.appendChild(_)}f.appendChild(m),this._menuEntry=m,m.addEventListener("change",()=>{const y=Array.from(m.selectedOptions).map(_=>parseInt(_.value));y.length===1&&y[0]===-1?this._passIndices=null:this._passIndices=y,this.applyEffects(t)})}}}orderEffects(){var e;Jn&&console.log("Before ordering effects",[...this._effects]),dp??(dp=[exports.MODULES.POSTPROCESSING.MODULE.NormalPass,exports.MODULES.POSTPROCESSING.MODULE.DepthDownsamplingPass,exports.MODULES.POSTPROCESSING.MODULE.SMAAEffect,exports.MODULES.POSTPROCESSING.MODULE.SSAOEffect,exports.MODULES.POSTPROCESSING_AO.MODULE.N8AOPostPass,exports.MODULES.POSTPROCESSING.MODULE.TiltShiftEffect,exports.MODULES.POSTPROCESSING.MODULE.DepthOfFieldEffect,exports.MODULES.POSTPROCESSING.MODULE.ChromaticAberrationEffect,exports.MODULES.POSTPROCESSING.MODULE.BloomEffect,exports.MODULES.POSTPROCESSING.MODULE.SelectiveBloomEffect,exports.MODULES.POSTPROCESSING.MODULE.VignetteEffect,exports.MODULES.POSTPROCESSING.MODULE.PixelationEffect,exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect,exports.MODULES.POSTPROCESSING.MODULE.HueSaturationEffect,exports.MODULES.POSTPROCESSING.MODULE.BrightnessContrastEffect]);const t=this._effects;t.sort((i,n)=>{const o=dp.findIndex(l=>i.constructor.name.endsWith(l.name)),a=dp.findIndex(l=>n.constructor.name.endsWith(l.name));return o<0?(Jn&&console.warn("Unknown effect found: ",i.constructor.name),-1):a<0?(Jn&&console.warn("Unknown effect found: ",n.constructor.name),1):o<0?1:a<0?-1:o-a}),Jn&&console.log("After ordering effects",[...this._effects]);for(let i=0;i<t.length;i++){const n=t[i];if(((e=n==null?void 0:n.configuration)==null?void 0:e.gammaCorrection)!==void 0){const o=i===t.length-1;n.configuration.gammaCorrection=o}}}}let dp=null;var qE=Object.defineProperty,XE=Object.getOwnPropertyDescriptor,Uw=(s,t,e,i)=>{for(var n=i>1?void 0:i?XE(t,e):t,o=s.length-1,a;o>=0;o--)(a=s[o])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&qE(t,e,n),n};const Xr=x("debugpost");class rl extends D{constructor(){super(...arguments);r(this,"sharedProfile");r(this,"multisampling","auto");r(this,"_postprocessing");r(this,"_activeEffects",[]);r(this,"_effects",[]);r(this,"_componentEnabledTime",-1);r(this,"_multisampleAutoChangeTime",0);r(this,"_multisampleAutoDecreaseTime",0);r(this,"_lastApplyTime");r(this,"_rapidApplyCount",0);r(this,"_isDirty",!1);r(this,"_modificationQueue");r(this,"_recreateId",-1)}get isPostProcessingManager(){return!0}get effects(){return this._activeEffects}addEffect(e){let i=e;return i instanceof Xe||(i=new Ic(i)),i.gameObject===void 0&&this.gameObject.addComponent(i),this._effects.includes(i)||(this._effects.push(i),this._isDirty=!0),e}removeEffect(e){var n,o,a,l;let i=-1;if(e instanceof Xe?i=this._effects.indexOf(e):i=this._effects.findIndex(c=>c instanceof Ic&&c.effect===e),i!==-1)return this._effects.splice(i,1),this._isDirty=!0,e;if(e instanceof Xe){const c=(o=(n=this.sharedProfile)==null?void 0:n.components)==null?void 0:o.indexOf(e);c!==void 0&&c!==-1&&(this._isDirty=!0,(l=(a=this.sharedProfile)==null?void 0:a.components)==null||l.splice(c,1))}return e}markDirty(){this._isDirty=!0}awake(){var e;Xr&&(console.log("PostprocessingManager Awake",this),console.log("Press P to toggle post processing"),window.addEventListener("keydown",i=>{i.key==="p"&&(this.enabled=!this.enabled,Te("Toggle PostProcessing "+this.name+": Enabled="+this.enabled),this.markDirty())})),(e=this.sharedProfile)==null||e.__init(this)}onEnable(){this._componentEnabledTime=this.context.time.realtimeSinceStartup,this._isDirty=!0}onDisable(){var e;(e=this._postprocessing)==null||e.unapply(),this._isDirty=!1}onBeforeRender(){if(!this.context.isInXR&&(this.context.mainCamera&&this._isDirty&&this.apply(),this.context.composer&&this._postprocessing&&this._postprocessing.composer===this.context.composer)){this.context.renderer.getContext().isContextLost()&&this.context.renderer.forceContextRestore(),this.context.composer.getRenderer()!==this.context.renderer&&this.context.composer.setRenderer(this.context.renderer),this.context.composer.setMainScene(this.context.scene);const e=this.context.composer;if(this.multisampling==="auto"){const i=this.context.time.realtimeSinceStartup-this._multisampleAutoChangeTime;if(this.context.time.realtimeSinceStartup-this._componentEnabledTime>2&&i>.5){const n=e.multisampling;e.multisampling>0&&this.context.time.smoothedFps<=50?(this._multisampleAutoChangeTime=this.context.time.realtimeSinceStartup,this._multisampleAutoDecreaseTime=this.context.time.realtimeSinceStartup,e.multisampling*=.5,e.multisampling=Math.floor(e.multisampling),Xr&&console.debug(`[PostProcessing] Reduced multisampling from ${n} to ${e.multisampling}`)):i>1&&this.context.time.smoothedFps>=59&&e.multisampling<this.context.renderer.capabilities.maxSamples&&this.context.time.realtimeSinceStartup-this._multisampleAutoDecreaseTime>10&&(this._multisampleAutoChangeTime=this.context.time.realtimeSinceStartup,e.multisampling=e.multisampling<=0?1:e.multisampling*2,e.multisampling=Math.floor(e.multisampling),Xr&&console.debug(`[PostProcessing] Increased multisampling from ${n} to ${e.multisampling}`))}}else e.multisampling=Math.max(0,Math.min(this.multisampling,this.context.renderer.capabilities.maxSamples));if(this.context.mainCamera){const i=this.context.composer.passes;for(const n of i)if(n.mainCamera&&n.mainCamera!==this.context.mainCamera){this.context.composer.setMainCamera(this.context.mainCamera);break}}}}onDestroy(){var e;(e=this._postprocessing)==null||e.dispose()}apply(){var e,i;if(Xr&&console.log(`Apply PostProcessing "${this.name}"`),I()&&(this._lastApplyTime!==void 0&&Date.now()-this._lastApplyTime<100&&(this._rapidApplyCount++,this._rapidApplyCount===5&&console.warn("Detected rapid post processing modifications - this might be a bug",this)),this._lastApplyTime=Date.now()),this._isDirty=!1,this.unapply(),this._activeEffects.length=0,(e=this.sharedProfile)!=null&&e.components){const n=this.sharedProfile.components;for(const o of n)o.active&&o.enabled&&!this._activeEffects.includes(o)&&this._activeEffects.push(o)}for(const n of this._effects)n.active&&n.enabled&&!this._activeEffects.includes(n)&&this._activeEffects.push(n);this._activeEffects.length>0&&(this._postprocessing||(this._postprocessing=new oy(this.context)),(i=this._postprocessing.apply(this._activeEffects))==null||i.then(()=>{var o;if(!this.activeAndEnabled)return;this._applyPostQueue();const n=(o=this._postprocessing)==null?void 0:o.composer;n?(this.multisampling==="auto"?n.multisampling=exports.DeviceUtilities.isMobileDevice()?2:4:n.multisampling=Math.max(0,Math.min(this.multisampling,this.context.renderer.capabilities.maxSamples)),Xr&&console.debug(`[PostProcessing] Set multisampling to ${n.multisampling} (Is Mobile: ${exports.DeviceUtilities.isMobileDevice()})`)):Xr&&console.warn("[PostProcessing] No composer found")}))}unapply(){var e;(e=this._postprocessing)==null||e.unapply()}_applyPostQueue(){if(this._modificationQueue){for(const e of this._modificationQueue.values())this.onEditorModification(e);this._modificationQueue.clear()}}onEditorModification(e){var i,n;if(e.propertyName.startsWith("postprocessing.")){if(!this._postprocessing)return this._modificationQueue||(this._modificationQueue=new Map),this._modificationQueue.set(e.propertyName,e),!0;if(!((i=this._activeEffects)!=null&&i.length))return;const o=e.propertyName.split(".");if(o.length===3||o.length===4){const a=o[1],l=o[2];for(const c of this._activeEffects)if(((n=c.typeName)==null?void 0:n.toLowerCase())===a.toLowerCase()){if(l==="active"){c.active=e.value,this.scheduleRecreate();return}if(!rd.has(a)){const d=new Array;rd.set(a,d);const u=Object.keys(c);for(const f of u)c[f]instanceof U&&d.push(f)}if(rd.has(a)){const d=l.toLowerCase(),u=rd.get(a);for(const f of u)if(f.toLowerCase()===d){const m=c[f];m instanceof U&&(o.length===4&&o[3]==="active"?(m.overrideState=e.value,this.scheduleRecreate()):m&&m.value!==void 0&&(m.value=e.value));return}}console.warn("Unknown modification",l);return}}return!0}return!1}scheduleRecreate(){const e=++this._recreateId;setTimeout(()=>{e===this._recreateId&&(this.onDisable(),this.onEnable())},200)}}Uw([yr(Qu)],rl.prototype,"sharedProfile",2);Uw([yr()],rl.prototype,"multisampling",2);const rd=new Map;tE(rl);async function ry(s){const{NeedleEngineHTMLElement:t}=await Promise.resolve().then(()=>VT);t.observedAttributes.includes(s)||t.observedAttributes.push(s)}var QE=Object.defineProperty,YE=Object.getOwnPropertyDescriptor,ut=(s,t,e,i)=>{for(var n=i>1?void 0:i?YE(t,e):t,o=s.length-1,a;o>=0;o--)(a=s[o])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&QE(t,e,n),n};const Rt=x("debugsceneswitcher"),KE=x("sceneswitcher:clearscene"),Td="scene";ry(Td);const zs=Promise.resolve(!1);class Ge extends D{constructor(){super(...arguments);r(this,"autoLoadFirstScene",!0);r(this,"scenes",[]);r(this,"loadingScene");r(this,"queryParameterName","scene");r(this,"useSceneName",!0);r(this,"clamp",!0);r(this,"useHistory",!0);r(this,"useKeyboard",!0);r(this,"useSwipe",!0);r(this,"useSceneLighting",!0);r(this,"useSceneBackground",!0);r(this,"preloadNext",1);r(this,"preloadPrevious",1);r(this,"preloadConcurrent",2);r(this,"createMenuButtons",!1);r(this,"sceneLoadingStart",new ge);r(this,"sceneLoadingProgress",new ge);r(this,"sceneLoaded",new ge);r(this,"_currentIndex",-1);r(this,"_currentScene");r(this,"_engineElementOverserver");r(this,"_preloadScheduler");r(this,"_menuButtons");r(this,"onPopState",async e=>{if(!this.useHistory)return;const i=this.useHistory;try{this.useHistory=!1;let n=!1;if(this.queryParameterName&&(n=await this.tryLoadFromQueryParam()),!n){const o=e==null?void 0:e.state;if(o&&o.startsWith(this.guid)){const a=o.substr(this.guid.length+2);Rt&&console.log("PopState",a),await this.trySelectSceneFromValue(a)}}}finally{this.useHistory=i}});r(this,"normalizedSwipeThresholdX",.1);r(this,"_didSwipe",!1);r(this,"onInputPointerMove",e=>{if(this.useSwipe&&!this._didSwipe&&e.button===0&&e.pointerType==="touch"&&this.context.input.getPointerPressedCount()===1){const i=this.context.input.getPointerPositionDelta(e.button);if(i){const n=i.x/this.context.domWidth;n>=this.normalizedSwipeThresholdX?(this._didSwipe=!0,this.selectPrev()):n<=-this.normalizedSwipeThresholdX&&(this._didSwipe=!0,this.selectNext())}}});r(this,"onInputPointerUp",e=>{e.button===0&&(this._didSwipe=!1)});r(this,"onInputKeyDown",e=>{if(!this.useKeyboard||!this.scenes)return;const i=e.key.toLowerCase();if(!i)return;const n=parseInt(i)-1;if(n>=0){this.trySelectSceneFromValue(n);return}switch(i){case"arrowright":case"d":this.selectNext();break;case"arrowleft":case"a":this.selectPrev();break}});r(this,"__lastSwitchScene");r(this,"__lastSwitchScenePromise");r(this,"_currentlyLoadingScene");r(this,"_lastLoadingScene");r(this,"_loadingScenePromise");r(this,"_isCurrentlyLoading",!1);r(this,"_currentLoadingProgress")}get currentIndex(){return this._currentIndex}get currentLoadingProgress(){return this._currentLoadingProgress}get currentlyLoadingScene(){return this._currentlyLoadingScene}get currentlyLoadedScene(){return this._currentScene}awake(){this.scenes===void 0&&(this.scenes=[]);for(const e of this.scenes)e&&!e.hasUrl&&e.asset instanceof h.Object3D?S.remove(e.asset):e instanceof h.Object3D&&S.remove(e);Rt&&console.log("SceneSwitcher",this)}async onEnable(){if(globalThis.addEventListener("popstate",this.onPopState),this.context.input.addEventListener(Ee.KeyDown,this.onInputKeyDown),this.context.input.addEventListener(Ee.PointerMove,this.onInputPointerMove),this.context.input.addEventListener(Ee.PointerUp,this.onInputPointerUp),this._engineElementOverserver||(this._engineElementOverserver=new MutationObserver(e=>{for(const i of e)if(i.type==="attributes"&&i.attributeName===Td){const n=this.context.domElement.getAttribute(Td);n!==null&&this.trySelectSceneFromValue(n)}})),this._engineElementOverserver.observe(this.context.domElement,{attributes:!0}),this._preloadScheduler||(this._preloadScheduler=new ZE(this)),this._preloadScheduler.maxLoadAhead=this.preloadNext,this._preloadScheduler.maxLoadBehind=this.preloadPrevious,this._preloadScheduler.maxConcurrent=this.preloadConcurrent,this._preloadScheduler.begin(2e3),this.autoLoadFirstScene&&this._currentIndex===-1&&!await this.tryLoadFromQueryParam()){const e=this.context.domElement.getAttribute(Td);try{(e===null||!await this.trySelectSceneFromValue(e))&&this._currentIndex===-1&&this.select(0)}finally{}}this.createMenuButtons&&(this._menuButtons??(this._menuButtons=[]),this._menuButtons.push(this.context.menu.appendChild({label:"Previous",icon:"arrow_back_ios",onClick:()=>this.selectPrev(),priority:-1005,class:"row2"})),this._menuButtons.push(this.context.menu.appendChild({label:"Next",icon:"arrow_forward_ios",iconSide:"right",onClick:()=>this.selectNext(),priority:-1e3,class:"row2"})))}onDisable(){var e;if(globalThis.removeEventListener("popstate",this.onPopState),this.context.input.removeEventListener(Ee.KeyDown,this.onInputKeyDown),this.context.input.removeEventListener(Ee.PointerMove,this.onInputPointerMove),this.context.input.removeEventListener(Ee.PointerUp,this.onInputPointerUp),(e=this._preloadScheduler)==null||e.stop(),this._menuButtons){for(const i of this._menuButtons)i.remove();this._menuButtons=void 0}}addScene(e){if(typeof e=="string"){let i=this.context.addressables.findAssetReference(e);return i||(i=new ee(e),this.context.addressables.registerAssetReference(i)),this.scenes.push(i),i}return this.scenes.push(e),e}selectNext(){return this.select(this._currentIndex+1)}selectPrev(){return this.select(this._currentIndex-1)}select(e){var n,o,a;if(Rt&&console.log("select",e),typeof e=="object"&&console.warn('Switching to "'+e+'" might not work. Please either use an index or a AssetReference (not a scene reference)'),typeof e=="string"){const l=(n=this.scenes)==null?void 0:n.find(c=>c.url===e);if(!l){const c=ee.getOrCreate(this.sourceId??"",e,this.context);return this.switchScene(c)}if(l)e=(o=this.scenes)==null?void 0:o.indexOf(l);else return zs}if(!((a=this.scenes)!=null&&a.length))return zs;if(e<0){if(this.clamp)return zs;e=this.scenes.length-1}else if(e>=this.scenes.length){if(this.clamp)return zs;e=0}const i=this.scenes[e];return this.switchScene(i)}unload(){return this.__lastSwitchScene=void 0,this.__lastSwitchScenePromise=void 0,this.__unloadCurrentScene()}async reload(){if(this.__lastSwitchScene){const e=this.__lastSwitchScene;return this.__lastSwitchScene=void 0,this.switchScene(e)}return!1}async switchScene(e){var n;if(!(e instanceof ee)){const o=typeof e;if(o==="string")return this.select(e);if(o==="number")return this.select(e);if(e&&e instanceof h.Object3D){const a=(n=this.scenes)==null?void 0:n.indexOf(e);e=new ee(e.name,void 0,e),a>=0&&(this.scenes[a]=e)}else return console.warn(`[SceneSwitcher] Can't switch to scene of type ${o}`),!1}return e.url===this.sourceId?(console.warn("[SceneSwitcher] Can't load own scene - prevent recursive loading",this.sourceId),!1):this.__lastSwitchScene===e&&this.__lastSwitchScenePromise?this.__lastSwitchScenePromise:(this.__lastSwitchScene=e,this.__lastSwitchScenePromise=this.__internalSwitchScene(e),await this.__lastSwitchScenePromise)}async __unloadCurrentScene(){const e=this._currentScene;if(this._currentScene=void 0,e){Rt&&console.log("UNLOAD",e.url,"HasURL?: "+e.hasUrl);const i=this.tryGetSceneEventListener(e.asset);if(i!=null&&i.sceneClosing){const n=i.sceneClosing();n instanceof Promise&&await n}e.hasUrl?e.unload():e.asset instanceof h.Object3D&&S.remove(e.asset)}}async __internalSwitchScene(e){var n,o,a,l,c;await this.__unloadCurrentScene();const i=this._currentIndex=((n=this.scenes)==null?void 0:n.indexOf(e))??-1;try{this._currentlyLoadingScene=e,this._currentLoadingProgress=new ProgressEvent("progress",{loaded:0,total:1});const d=new CustomEvent("loadscene-start",{detail:{scene:e,switcher:this,index:i}});this.dispatchEvent(d),(o=this.sceneLoadingStart)==null||o.invoke(d.detail),await this.onStartLoading(),await e.loadAssetAsync((f,m)=>{var g;if(Rt){const y=m.loaded/m.total,_="["+"=".repeat(Math.floor(y*20))+"-".repeat(20-Math.floor(y*20))+"]";console.debug(`[SceneSwitcher] Download ${(y*100).toFixed(1)} % ${_}`,e.url)}this._currentLoadingProgress=m,this.dispatchEvent(m),(g=this.sceneLoadingProgress)==null||g.invoke(m)}).catch(console.error),await this.onEndLoading();const u=new CustomEvent("loadscene-finished",{detail:{scene:e,switcher:this,index:i}});if(this.dispatchEvent(u),this._currentLoadingProgress=void 0,this._currentlyLoadingScene=void 0,u.defaultPrevented)return Rt&&console.warn("Adding loaded scene prevented:",e,u),!1;if(!e.asset)return Rt&&console.warn("Failed loading scene:",e),!1;if(this._currentIndex===i){if(Rt&&console.log("ADD",e.url),this._currentScene=e,KE){const g=((a=this.context.mainCameraComponent)==null?void 0:a.gameObject)||this.context.mainCamera;g==null||g.removeFromParent();const y=this.gameObject.removeFromParent();Ci(this.context.scene,!0,!0),this.context.scene=new h.Scene,this.context.scene.add(y),g&&this.context.scene.add(g)}if(S.add(e.asset,this.gameObject),this.useSceneLighting&&this.context.sceneLighting.enable(e),this.useSceneBackground){const g=this.context.lightmaps.tryGetSkybox(e.url);g?(g.mapping=h.EquirectangularReflectionMapping,this.context.scene.background=g):Rt&&console.warn("SceneSwitcher: Can't find skybox for scene "+e.url)}if(this.useHistory&&i>=0){let g=i.toString();if(this.useSceneName&&(e instanceof h.Object3D?g=e.name:e.url&&(g=ub(e.url))),(l=this.queryParameterName)!=null&&l.length)Cc(this.queryParameterName,g,this.useHistory);else{const y=history.state,_=this.guid+"::"+i;y!==_&&history.pushState(_,"unused",location.href)}}const f=this.tryGetSceneEventListener(e.asset);if(f!=null&&f.sceneOpened){const g=f.sceneOpened(this);g instanceof Promise&&await g}const m=new CustomEvent("scene-opened",{detail:{scene:e,switcher:this,index:i}});return this.dispatchEvent(m),(c=this.sceneLoaded)==null||c.invoke(this),!0}}catch(d){console.error(d)}return!1}preload(e){if(e>=0&&e<this.scenes.length){const i=this.scenes[e];if(i instanceof ee)return i.preload()}return zs}tryLoadFromQueryParam(){var i;if(!((i=this.queryParameterName)!=null&&i.length))return zs;const e=x(this.queryParameterName);return typeof e=="boolean"?zs:this.trySelectSceneFromValue(e)}trySelectSceneFromValue(e){if(typeof e=="string"){const i=parseInt(e);if(i>=0&&i<this.scenes.length)return this.select(i);{const n=e.toLowerCase();for(let o=0;o<this.scenes.length;o++){const a=this.scenes[o];if(!a)continue;if((a instanceof h.Object3D?a.name:ub(a.url)).toLowerCase().includes(n))return this.select(o)}}}else if(typeof e=="number"&&e>=0&&e<this.scenes.length)return this.select(e);return Gt()&&console.warn('Can not find scene: "'+e+'"',this),zs}async onStartLoading(){var e,i;if(this._isCurrentlyLoading=!0,this.loadingScene&&(this._lastLoadingScene!==this.loadingScene&&(this._loadingScenePromise=void 0),this._lastLoadingScene=this.loadingScene,this._loadingScenePromise||(this._loadingScenePromise=(e=this.loadingScene)==null?void 0:e.loadAssetAsync().then(n=>n!=null)),await this._loadingScenePromise,this._isCurrentlyLoading&&((i=this.loadingScene)!=null&&i.asset))){Rt&&console.log("Add loading scene",this.loadingScene.url,this.loadingScene.asset);const n=this.loadingScene.asset;S.add(n,this.gameObject);const o=this.tryGetSceneEventListener(n);if(o!=null&&o.sceneOpened){const a=o.sceneOpened(this);a instanceof Promise&&await a}}if(this._isCurrentlyLoading){const n=this.tryGetSceneEventListener(this.gameObject);if(n&&n.sceneOpened){const o=n.sceneOpened(this);o instanceof Promise&&await o}}}async onEndLoading(){var e;if(this._isCurrentlyLoading=!1,(e=this.loadingScene)!=null&&e.asset){Rt&&console.log("Remove loading scene",this.loadingScene.url);const i=this.loadingScene.asset,n=this.tryGetSceneEventListener(i);if(typeof(n==null?void 0:n.sceneClosing)=="function"){const o=n.sceneClosing();o instanceof Promise&&await o}S.remove(i)}if(!this._isCurrentlyLoading){const i=this.tryGetSceneEventListener(this.gameObject);if(i&&i.sceneClosing){const n=i.sceneClosing();n instanceof Promise&&await n}}}tryGetSceneEventListener(e,i=0){if(!e)return null;const n=S.foreachComponent(e,o=>{const a=o;if(a.sceneClosing||a.sceneOpened)return a});if(i===0&&!n&&e.children.length)for(const o of e.children){const a=this.tryGetSceneEventListener(o,i+1);if(a)return a}return n||null}}ut([p()],Ge.prototype,"autoLoadFirstScene",2);ut([p(ee)],Ge.prototype,"scenes",2);ut([p(ee)],Ge.prototype,"loadingScene",2);ut([p()],Ge.prototype,"queryParameterName",2);ut([p()],Ge.prototype,"useSceneName",2);ut([p()],Ge.prototype,"clamp",2);ut([p()],Ge.prototype,"useHistory",2);ut([p()],Ge.prototype,"useKeyboard",2);ut([p()],Ge.prototype,"useSwipe",2);ut([p()],Ge.prototype,"useSceneLighting",2);ut([p()],Ge.prototype,"useSceneBackground",2);ut([p()],Ge.prototype,"preloadNext",2);ut([p()],Ge.prototype,"preloadPrevious",2);ut([p()],Ge.prototype,"preloadConcurrent",2);ut([p()],Ge.prototype,"createMenuButtons",2);ut([p(ge)],Ge.prototype,"sceneLoadingStart",2);ut([p(ge)],Ge.prototype,"sceneLoadingProgress",2);ut([p(ge)],Ge.prototype,"sceneLoaded",2);function ub(s){const t=s.split("/").pop(),e=t==null?void 0:t.split(".").shift();return e!=null&&e.length?e:s}class ZE{constructor(t,e=1,i=1,n=2){r(this,"maxLoadAhead");r(this,"maxLoadBehind");r(this,"maxConcurrent");r(this,"_isRunning",!1);r(this,"_switcher");r(this,"_loadTasks",[]);r(this,"_maxConcurrentLoads",1);this._switcher=t,this.maxLoadAhead=e,this.maxLoadBehind=i,this.maxConcurrent=n}begin(t){if(this._isRunning)return;Rt&&console.log("Preload begin",{delay:t}),this._isRunning=!0;let e=-10,i,n;const o=this._switcher.scenes,a=Date.now()+t,l=setInterval(()=>{if(this.allLoaded()&&(Rt&&console.log("All scenes (pre-)loaded"),this.stop()),!this._isRunning){clearInterval(l);return}if(Date.now()<a||this.canLoadNewScene()===!1)return;(e===-10||e!==this._switcher.currentIndex)&&(e=this._switcher.currentIndex,n=0,i=0);const c=n%2===0;c&&(i+=1),n+=1;const d=c?this.maxLoadAhead:this.maxLoadBehind;if(i>d)return;const u=c?e+i:e-i;if(!(u<0)&&!(u<0||u>=o.length)&&!this._loadTasks.some(f=>f.index===u)){const f=o[u];Rt&&console.log("Preload scene",{roomIndex:u,searchForward:c,lastRoom:e,currentIndex:this._switcher.currentIndex,tasks:this._loadTasks.length},f==null?void 0:f.url),new JE(u,f,this._loadTasks)}},200)}stop(){this._isRunning=!1}canLoadNewScene(){return this._loadTasks.length<this._maxConcurrentLoads}allLoaded(){if(this._switcher.scenes){for(const t of this._switcher.scenes)if(t!=null&&t.isLoaded&&t.isLoaded()===!1)return!1}return!0}}class JE{constructor(t,e,i){r(this,"index");r(this,"asset");r(this,"tasks");this.index=t,this.asset=e,this.tasks=i,i.push(this),this.awaitLoading()}async awaitLoading(){this.asset&&!this.asset.isLoaded()&&(Rt&&console.log("Preload start: "+this.asset.url,this.index),await this.asset.preload(),Rt&&console.log("Preload finished: "+this.asset.url,this.index));const t=this.tasks.indexOf(this);t>=0&&this.tasks.splice(t,1)}}function ek(){return new Promise((s,t)=>{const i=()=>{i!=null&&(document.removeEventListener("pointerdown",i),document.removeEventListener("click",i),document.removeEventListener("dragstart",i),document.removeEventListener("touchstart",i),s())};document.addEventListener("pointerdown",i),document.addEventListener("click",i),document.addEventListener("dragstart",i),document.addEventListener("touchstart",i)})}async function tk(s){await ek(),s()}var ik=Object.defineProperty,nk=Object.getOwnPropertyDescriptor,Ei=(s,t,e,i)=>{for(var n=i>1?void 0:i?nk(t,e):t,o=s.length-1,a;o>=0;o--)(a=s[o])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&ik(t,e,n),n};const rt=x("debugvideo");var zw=(s=>(s[s.None=0]="None",s[s.AdjustHeight=1]="AdjustHeight",s[s.AdjustWidth=2]="AdjustWidth",s))(zw||{}),Nw=(s=>(s[s.VideoClip=0]="VideoClip",s[s.Url=1]="Url",s))(Nw||{}),Vw=(s=>(s[s.CameraFarPlane=0]="CameraFarPlane",s[s.CameraNearPlane=1]="CameraNearPlane",s[s.RenderTexture=2]="RenderTexture",s[s.MaterialOverride=3]="MaterialOverride",s))(Vw||{});class nt extends D{constructor(){super();r(this,"playOnAwake",!0);r(this,"aspectMode",0);r(this,"clip",null);r(this,"source",1);r(this,"_url",null);r(this,"renderMode");r(this,"targetMaterialProperty");r(this,"targetMaterialRenderer");r(this,"targetTexture");r(this,"time",0);r(this,"_playbackSpeed",1);r(this,"_isLooping",!1);r(this,"_muted",!1);r(this,"_audioOutputMode",2);r(this,"playInBackground",!0);r(this,"_crossOrigin","anonymous");r(this,"_videoElement",null);r(this,"_videoTexture",null);r(this,"_videoMaterial",null);r(this,"_isPlaying",!1);r(this,"wasPlaying",!1);r(this,"visibilityChanged",e=>{switch(document.visibilityState){case"hidden":this.playInBackground||(this.wasPlaying=this._isPlaying,this.pause());break;case"visible":this.wasPlaying&&!this._isPlaying&&this.play();break}});r(this,"_receivedInput",!1);r(this,"_overlay",null);r(this,"_targetObjects");r(this,"_updateAspectRoutineId",-1);r(this,"_hls");r(this,"onHlsAvailable",()=>{var e;rt&&console.log("HLS: available",this.clip),!(!this.shouldUseM3U||!this.url)&&(this._hls||(this._hls=new Hls),this.videoElement.autoplay=!0,this._hls.loadSource(this.url),this._hls.attachMedia(this.videoElement),(e=this._videoElement)==null||e.play(),rt&&console.log("HLS: loaded",this.clip))});tk(()=>{this._receivedInput=!0,this.updateVideoElementSettings()}),this._targetObjects=[],x("videoscreenspace")&&window.addEventListener("keydown",e=>{e.key==="f"&&(this.screenspace=!this.screenspace)})}get url(){return this._url}set url(e){const n=this._url!==e;this.__didAwake?n&&this.setClipURL(e??""):this._url=e}get playbackSpeed(){var e;return((e=this._videoElement)==null?void 0:e.playbackRate)??this._playbackSpeed}set playbackSpeed(e){this._playbackSpeed=e,this._videoElement&&(this._videoElement.playbackRate=e)}get isLooping(){var e;return((e=this._videoElement)==null?void 0:e.loop)??this._isLooping}set isLooping(e){this._isLooping=e,this._videoElement&&(this._videoElement.loop=e)}get currentTime(){var e;return((e=this._videoElement)==null?void 0:e.currentTime)??this.time}set currentTime(e){this._videoElement?this._videoElement.currentTime=e:this.time=e}get isPlaying(){const e=this._videoElement;if(e){if(e.currentTime>0&&!e.paused&&!e.ended&&e.readyState>e.HAVE_CURRENT_DATA)return!0;if(e.srcObject&&e.srcObject.active)return!0}return!1}get crossOrigin(){var e;return((e=this._videoElement)==null?void 0:e.crossOrigin)??this._crossOrigin}set crossOrigin(e){this._crossOrigin=e,this._videoElement&&(e!==null?this._videoElement.setAttribute("crossorigin",e):this._videoElement.removeAttribute("crossorigin"))}get videoMaterial(){return!this._videoMaterial&&!this.create(!1)?null:this._videoMaterial}get videoTexture(){return!this._videoTexture&&!this.create(!1)?null:this._videoTexture}get videoElement(){return!this._videoElement&&!this.create(!1)?null:this._videoElement}requestPictureInPicture(){return this._videoElement?this._videoElement.requestPictureInPicture():null}get muted(){var e;return((e=this._videoElement)==null?void 0:e.muted)??this._muted}set muted(e){this._muted=e,this._videoElement&&(this._videoElement.muted=e)}get currentVideo(){return this.clip}set audioOutputMode(e){e!==this._audioOutputMode&&(e===1&&I()&&console.warn("VideoAudioOutputMode.AudioSource is not yet implemented"),this._audioOutputMode=e,this.updateVideoElementSettings())}get audioOutputMode(){return this._audioOutputMode}preloadVideo(){rt&&console.log("Video Preload: "+this.name,this.clip),this.create(!1)}preload(){this.preloadVideo()}setVideo(e){this.clip=e,this.source=0,this._videoElement?(this._videoElement.srcObject=e,this._isPlaying&&this.play(),this.updateAspect()):this.create(this.playOnAwake)}setClipURL(e){this._url!==e&&(this._url=e,this.source=1,rt&&console.log("set url",e),this._videoElement?e.endsWith(".m3u8")||e.includes(".m3u")?this.ensureM3UCanBePlayed():(this._videoElement.src=e,this._isPlaying&&(this.stop(),this.play())):this.create(this.playOnAwake))}onEnable(){var e,i;rt&&console.log("VideoPlayer.onEnable",Nw[this.source],this.clip,this.url,this),window.addEventListener("visibilitychange",this.visibilityChanged),this.playOnAwake===!0?this.create(!0):this.preloadVideo(),this.screenspace?(e=this._overlay)==null||e.start():(i=this._overlay)==null||i.stop()}onDisable(){var e;window.removeEventListener("visibilitychange",this.visibilityChanged),(e=this._overlay)==null||e.stop(),this.pause()}onDestroy(){var e;this._videoElement&&((e=this.videoElement)==null||e.remove(),this._videoElement=null),this._videoTexture&&(this._videoTexture.dispose(),this._videoTexture=null)}play(){var e,i;if(this._videoElement||this.create(!1),!this._videoElement){rt&&console.warn("Can not play: no video element found",this);return}if(!(this._isPlaying&&!((e=this._videoElement)!=null&&e.ended)&&!((i=this._videoElement)!=null&&i.paused))){if(this._isPlaying=!0,this._receivedInput||(this._videoElement.muted=!0),this.handleBeginPlaying(!1),this.shouldUseM3U){this.ensureM3UCanBePlayed();return}rt&&console.log("Video Play()",this.clip,this._videoElement,this.time),this._videoElement.currentTime=this.time,this._videoElement.play().catch(n=>{var o;console.log(n),rt&&console.error("Error playing video",n,"CODE="+n.code,(o=this.videoElement)==null?void 0:o.src,this),setTimeout(()=>{this._isPlaying&&!this.destroyed&&this.activeAndEnabled&&this.play()},1e3)}),rt&&console.log("play",this._videoElement,this.time)}}stop(){this._isPlaying=!1,this.time=0,this._videoElement&&(this._videoElement.currentTime=0,this._videoElement.pause(),rt&&console.log("STOP",this))}pause(){var e,i;this.time=((e=this._videoElement)==null?void 0:e.currentTime)??0,this._isPlaying=!1,(i=this._videoElement)==null||i.pause(),rt&&console.log("PAUSE",this,this.currentTime)}create(e){let i;switch(this.source){case 0:i=this.clip;break;case 1:i=this.url,!(i!=null&&i.length)&&typeof this.clip=="string"&&(i=this.clip);break}return i?(this._videoElement||(rt&&console.warn("Create VideoElement",this),this._videoElement=this.createVideoElement(),this.context.domElement.shadowRoot.prepend(this._videoElement),this.updateVideoElementStyles()),typeof i=="string"?(rt&&console.log("Set Video src",i),this._videoElement.src=i):(rt&&console.log("Set Video srcObject",i),this._videoElement.srcObject=i),this._videoTexture||(this._videoTexture=new h.VideoTexture(this._videoElement)),this._videoTexture.flipY=!1,this._videoTexture.colorSpace=h.SRGBColorSpace,e&&this.handleBeginPlaying(e),rt&&console.log("Video: handle playing done...",i,e),!0):(rt&&console.warn("No video source set",this),!1)}updateAspect(){this.aspectMode!==0&&this.startCoroutine(this.updateAspectImpl())}get screenspace(){var e;return((e=this._overlay)==null?void 0:e.enabled)??!1}set screenspace(e){var i;if(e){if(!this._videoTexture)return;this._overlay||(this._overlay=new sk(this.context)),this._overlay.add(this._videoTexture)}else(i=this._overlay)==null||i.remove(this._videoTexture);this._overlay&&(this._overlay.enabled=e)}createVideoElement(){const e=document.createElement("video");return this._crossOrigin&&e.setAttribute("crossorigin",this._crossOrigin),rt&&console.log("created video element",e),e}handleBeginPlaying(e){var o,a;if(!this.activeAndEnabled||!this._videoElement)return;this._targetObjects.length=0;let i=this.gameObject;switch(this.renderMode){case 3:i=(o=this.targetMaterialRenderer)==null?void 0:o.gameObject,i||(i=(a=S.getComponent(this.gameObject,ze))==null?void 0:a.gameObject);break;case 2:console.error("VideoPlayer renderTexture not implemented yet. Please use material override instead");return}if(!i){console.error("Missing target for video material renderer",this.name,Vw[this.renderMode],this);return}const n=i.material;if(n){this._targetObjects.push(i),n!==this._videoMaterial&&(this._videoMaterial=n.clone(),i.material=this._videoMaterial);const l="map",c=this._videoMaterial;if(!this.targetMaterialProperty)c[l]=this._videoTexture;else switch(this.targetMaterialProperty){default:c[l]=this._videoTexture;break}}else{console.warn("Can not play video, no material found, this might be a multimaterial case which is not supported yet");return}this.updateVideoElementSettings(),this.updateVideoElementStyles(),e&&(this.shouldUseM3U&&this.ensureM3UCanBePlayed(),this.play())}updateVideoElementSettings(){if(!this._videoElement)return;this._videoElement.loop=this._isLooping,this._videoElement.currentTime=this.currentTime,this._videoElement.playbackRate=this._playbackSpeed,this._videoElement.playsInline=!0;let e=!this._receivedInput||this.audioOutputMode===0;!e&&this._muted&&(e=!0),this._videoElement.muted=e,this.playOnAwake&&(this._videoElement.autoplay=!0)}updateVideoElementStyles(){this._videoElement&&(this._videoElement.style.userSelect="none",this._videoElement.style.visibility="hidden",this._videoElement.style.display="none",this.updateAspect())}*updateAspectImpl(){const e=++this._updateAspectRoutineId,i=void 0,n=this.clip;for(;e===this._updateAspectRoutineId&&this.aspectMode!==0&&this.clip&&n===this.clip&&this._isPlaying;){if(!n||typeof n=="string")return;let o;for(const a of n.getVideoTracks()){const l=a.getSettings();if(l&&l.width&&l.height){o=l.width/l.height;break}else o=this.context.renderer.domElement.clientWidth/this.context.renderer.domElement.clientHeight}if(o===void 0){for(let a=0;a<10;a++)yield;if(!this.isPlaying)break;continue}if(i===o){yield;continue}for(const a of this._targetObjects){let l=1;if(a.parent){const c=Ue(a.parent);l=c.x/c.y}switch(this.aspectMode){case 1:a.scale.y=1/o*a.scale.x*l;break;case 2:a.scale.x=o*a.scale.y*l;break}}for(let a=0;a<3;a++)yield}}get shouldUseM3U(){return this.url!=null&&(this.url.endsWith(".m3u8")||this.url.endsWith(".m3u"))&&this.source===1}ensureM3UCanBePlayed(){if(!this.shouldUseM3U)return;let e=document.head.querySelector("script[data-hls_library]");e?globalThis.Hls?this.onHlsAvailable():e.addEventListener("load",this.onHlsAvailable):(rt&&console.log("HLS: load script"),e=document.createElement("script"),e.dataset.hls_library="hls.js",e.src="https://cdn.jsdelivr.net/npm/hls.js@1",e.addEventListener("load",this.onHlsAvailable),document.head.append(e))}}Ei([p()],nt.prototype,"playOnAwake",2);Ei([p()],nt.prototype,"aspectMode",2);Ei([p(URL)],nt.prototype,"clip",2);Ei([p()],nt.prototype,"source",2);Ei([p(URL)],nt.prototype,"url",1);Ei([p()],nt.prototype,"renderMode",2);Ei([p()],nt.prototype,"targetMaterialProperty",2);Ei([p(ze)],nt.prototype,"targetMaterialRenderer",2);Ei([p(h.Texture)],nt.prototype,"targetTexture",2);Ei([p()],nt.prototype,"time",2);Ei([p()],nt.prototype,"playbackSpeed",1);Ei([p()],nt.prototype,"isLooping",1);Ei([p()],nt.prototype,"audioOutputMode",1);class sk{constructor(t){r(this,"context");r(this,"_videos",[]);r(this,"_screenspaceModeQuad");r(this,"_isInScreenspaceMode",!1);r(this,"_input");this.context=t,this._input=new ok(this)}get enabled(){return this._isInScreenspaceMode}set enabled(t){t?this.start():this.stop()}add(t){this._videos.indexOf(t)===-1&&this._videos.push(t)}remove(t){if(!t)return;const e=this._videos.indexOf(t);e>=0&&this._videos.splice(e,1)}start(){var n;if(this._isInScreenspaceMode||this._videos.length<0)return;const t=this._videos[this._videos.length-1];if(!t)return;if(this._isInScreenspaceMode=!0,!this._screenspaceModeQuad){if(this._screenspaceModeQuad=bo.createPrimitive(ar.Quad,{material:new rk(t)}),!this._screenspaceModeQuad)return;this._screenspaceModeQuad.geometry.scale(2,2,2)}const e=this._screenspaceModeQuad;this.context.scene.add(e),this.updateScreenspaceMaterialUniforms();const i=e.material;i==null||i.reset(),(n=this._input)==null||n.enable(i)}stop(){var t;this._isInScreenspaceMode=!1,this._screenspaceModeQuad&&((t=this._input)==null||t.disable(),this._screenspaceModeQuad.removeFromParent())}updateScreenspaceMaterialUniforms(){var e;const t=(e=this._screenspaceModeQuad)==null?void 0:e.material;t&&(t.screenAspect=this.context.domElement.clientWidth/this.context.domElement.clientHeight)}}class ok{constructor(t){r(this,"_onResizeScreenFn");r(this,"_onKeyUpFn");r(this,"_onMouseWheelFn");r(this,"context");r(this,"overlay");r(this,"_material");r(this,"_isPinching",!1);r(this,"_lastPinch",0);this.overlay=t,this.context=t.context}enable(t){this._material=t,window.addEventListener("resize",this._onResizeScreenFn=()=>{this.overlay.updateScreenspaceMaterialUniforms()}),window.addEventListener("keyup",this._onKeyUpFn=n=>{n.key==="Escape"&&this.overlay.stop()}),window.addEventListener("wheel",this._onMouseWheelFn=n=>{this.overlay.enabled&&(t.zoom+=n.deltaY*5e-4,n.preventDefault())},{passive:!1});const e=new h.Vector2;window.addEventListener("mousemove",n=>{if(this.overlay.enabled&&this.context.input.getPointerPressed(0)){const o=new h.Vector2(n.movementX,n.movementY);o.x/=this.context.domElement.clientWidth,o.y/=this.context.domElement.clientHeight,e.set(o.x,o.y),e.multiplyScalar(t.zoom/-this.context.time.deltaTime*.01),t.offset=t.offset.add(e)}}),window.addEventListener("pointermove",n=>{this.overlay.enabled&&this.context.input.getPointerPressed(0)&&this.context.input.getTouchesPressedCount()===1&&(e.set(n.movementX,n.movementY),e.multiplyScalar(t.zoom*-this.context.time.deltaTime*.05),t.offset=t.offset.add(e))});let i=0;window.addEventListener("touchstart",n=>{if(n.touches.length<2){this.context.time.time-i<.3&&this.overlay.stop(),i=this.context.time.time;return}this._isPinching=!0,this._lastPinch=0}),window.addEventListener("touchmove",n=>{if(!this._isPinching||!this._material)return;const o=n.touches[0],a=n.touches[1],l=o.clientX-a.clientX,c=o.clientY-a.clientY,d=Math.sqrt(l*l+c*c);if(this._lastPinch!==0){const u=d-this._lastPinch;this._material.zoom-=u*.004}this._lastPinch=d}),window.addEventListener("touchend",()=>{this._isPinching=!1})}disable(){this._onResizeScreenFn&&(window.removeEventListener("resize",this._onResizeScreenFn),this._onResizeScreenFn=void 0),this._onKeyUpFn&&(window.removeEventListener("keyup",this._onKeyUpFn),this._onKeyUpFn=void 0),this._onMouseWheelFn&&(window.removeEventListener("wheel",this._onMouseWheelFn),this._onMouseWheelFn=void 0)}}class rk extends h.ShaderMaterial{constructor(e){super();r(this,"_offset",new h.Vector2);this.uniforms={map:{value:e},screenAspect:{value:1},offsetScale:{value:new h.Vector4(0,0,1,1)}},this.vertexShader=`
|
|
1269
|
+
`;class e extends exports.MODULES.POSTPROCESSING.MODULE.Effect{constructor(){super("Sharpening",t,{vertexShader:s,blendFunction:exports.MODULES.POSTPROCESSING.MODULE.BlendFunction.NORMAL,uniforms:new Map([["amount",new h.Uniform$1(1)],["radius",new h.Uniform$1(1)]])})}}return e}var VE=Object.defineProperty,$E=Object.getOwnPropertyDescriptor,ol=(s,t,e,i)=>{for(var n=i>1?void 0:i?$E(t,e):t,o=s.length-1,a;o>=0;o--)(a=s[o])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&VE(t,e,n),n};class Xn extends Xe{constructor(){super(...arguments);r(this,"offset",new U(0));r(this,"rotation",new U(0));r(this,"focusArea",new U(.4));r(this,"feather",new U(.3));r(this,"kernelSize",new U(2));r(this,"resolutionScale",new U(1/window.devicePixelRatio))}get typeName(){return"TiltShiftEffect"}init(){this.offset.defaultValue=0,this.rotation.defaultValue=0,this.focusArea.defaultValue=.4,this.feather.defaultValue=.3,this.kernelSize.defaultValue=exports.MODULES.POSTPROCESSING.MODULE.KernelSize.MEDIUM,this.resolutionScale.defaultValue=1/window.devicePixelRatio}onCreateEffect(){const e=new exports.MODULES.POSTPROCESSING.MODULE.TiltShiftEffect({kernelSize:exports.MODULES.POSTPROCESSING.MODULE.KernelSize.VERY_LARGE,offset:this.offset.value,rotation:this.rotation.value,focusArea:this.focusArea.value,feather:this.feather.value});return this.offset.onValueChanged=i=>e.offset=i,this.rotation.onValueChanged=i=>e.rotation=i,this.focusArea.onValueChanged=i=>e.focusArea=i,this.feather.onValueChanged=i=>e.feather=i,this.kernelSize.onValueChanged=i=>e.blurPass.kernelSize=i,this.resolutionScale.onValueChanged=i=>e.resolution.scale=i/window.devicePixelRatio,e}}ol([p(U)],Xn.prototype,"offset",2);ol([p(U)],Xn.prototype,"rotation",2);ol([p(U)],Xn.prototype,"focusArea",2);ol([p(U)],Xn.prototype,"feather",2);ol([p(U)],Xn.prototype,"kernelSize",2);ol([p(U)],Xn.prototype,"resolutionScale",2);Ki("TiltShiftEffect",Xn);var WE=Object.defineProperty,HE=Object.getOwnPropertyDescriptor,sy=(s,t,e,i)=>{for(var n=i>1?void 0:i?HE(t,e):t,o=s.length-1,a;o>=0;o--)(a=s[o])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&WE(t,e,n),n};class Br extends Xe{constructor(){super(...arguments);r(this,"color",new U({r:0,g:0,b:0,a:1}));r(this,"intensity",new U(0));r(this,"center",new U({x:.5,y:.5}))}get typeName(){return"Vignette"}init(){this.color.defaultValue={r:0,g:0,b:0,a:1},this.intensity.defaultValue=0,this.center.defaultValue={x:.5,y:.5}}onCreateEffect(){const e=new exports.MODULES.POSTPROCESSING.MODULE.VignetteEffect;return this.intensity.onValueChanged=i=>{e.offset=i,this.updateDarkness(e)},this.color.onValueChanged=i=>{this.updateDarkness(e)},e}updateDarkness(e){const i=this.intensity.value;e.darkness=i}}sy([p(U)],Br.prototype,"color",2);sy([p(U)],Br.prototype,"intensity",2);sy([p(U)],Br.prototype,"center",2);Ki("Vignette",Br);globalThis.false=globalThis.false!==void 0?globalThis.false:!0;const Jn=x("debugpost"),GE=x("debugpostpasses"),cp=Symbol("needle:postprocessing-handler"),hp=Symbol("needle:previous-autoclear-state");class oy{constructor(t){r(this,"_composer",null);r(this,"_lastVolumeComponents");r(this,"_effects",[]);r(this,"_isActive",!1);r(this,"context");r(this,"_menuEntry",null);r(this,"_passIndices",null);this.context=t}get isActive(){return this._isActive}get composer(){return this._composer}apply(t){return"env"in{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:ya&&ya.tagName.toUpperCase()==="SCRIPT"&&ya.src||new URL("needle-engine.bundle-12ffa86b.light.umd.cjs",document.baseURI).href}&&{}.VITE_NEEDLE_USE_POSTPROCESSING==="false"?(Jn?console.warn("Postprocessing is disabled via vite env setting"):console.debug("Postprocessing is disabled via vite env setting"),Promise.resolve()):(Jn?console.warn("Postprocessing is disabled via global vite define setting"):console.debug("Postprocessing is disabled via vite define"),Promise.resolve())}unapply(){var i;if(Jn&&console.log("Unapplying postprocessing effects"),this._isActive=!1,this._lastVolumeComponents){for(const n of this._lastVolumeComponents)n.unapply();this._lastVolumeComponents.length=0}const t=this.context;t[cp]===this&&delete t[cp],t.composer===this._composer&&((i=t.composer)==null||i.dispose(),t.composer=null),typeof t.renderer[hp]=="boolean"&&(t.renderer.autoClear=t.renderer[hp])}dispose(){this.unapply();for(const t of this._effects)t.dispose();this._effects.length=0,this._composer=null}async onApply(t,e){if(!e)return;await Promise.all([exports.MODULES.POSTPROCESSING.load(),exports.MODULES.POSTPROCESSING_AO.load()]),t[cp]=this,Jn&&console.log("Apply Postprocessing Effects",e),this._lastVolumeComponents=[...e],this._effects.length=0;const i={handler:this,components:this._lastVolumeComponents};for(let n=0;n<this._lastVolumeComponents.length;n++){const o=this._lastVolumeComponents[n];if(o.context=t,o.apply){if(o.active){if(!t.mainCameraComponent){console.error("No camera in scene found or available yet - can not create postprocessing effects");return}const a=o.apply(i);if(!a)continue;Array.isArray(a)?this._effects.push(...a):this._effects.push(a)}}else o.active&&pe("Volume component is not a VolumeComponent: "+o.__type)}if(this.context.renderer.toneMapping!=h.NoToneMapping&&!this._effects.find(n=>n instanceof exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect)){const n=new exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect;this._effects.push(n)}this.applyEffects(t)}applyEffects(t){const e=this._effects;if(e.length<=0)return;const i=t.mainCameraComponent,n=t.renderer,o=t.scene,a=i.threeCamera;n[hp]=n.autoClear,this._composer||(this._composer=new exports.MODULES.POSTPROCESSING.MODULE.EffectComposer(n,{frameBufferType:h.HalfFloatType,stencilBuffer:!0})),t.composer&&t.composer!==this._composer&&console.warn("There's already an active EffectComposer in your scene: replacing it with a new one. This might cause unexpected behaviour. Make sure to only use one PostprocessingManager/Volume in your scene."),t.composer=this._composer;const l=t.composer;l.setMainCamera(a),l.setRenderer(n),l.setMainScene(o);for(const d of l.passes)d.dispose();l.removeAllPasses();const c=new exports.MODULES.POSTPROCESSING.MODULE.RenderPass(o,a);if(c.name="Render To Screen",c.mainScene=o,l.addPass(c),GE){this.orderEffects();for(const d of e)if(d instanceof exports.MODULES.POSTPROCESSING.MODULE.Effect){const u=new exports.MODULES.POSTPROCESSING.MODULE.EffectPass(a,d);u.name=d.name,l.addPass(u)}else d instanceof exports.MODULES.POSTPROCESSING.MODULE.Pass,l.addPass(d)}else try{this.orderEffects();const d=[];for(const u of e)u instanceof exports.MODULES.POSTPROCESSING.MODULE.Effect?d.push(u):(u instanceof exports.MODULES.POSTPROCESSING.MODULE.Pass,l.addPass(u));if(d.length>0){const u=new exports.MODULES.POSTPROCESSING.MODULE.EffectPass(a,...d);u.name=d.map(f=>f.name).join(" "),u.mainScene=o,u.enabled=!0,l.addPass(u)}}catch(d){console.error("Error while applying postprocessing effects",d),l.removeAllPasses()}if(Jn){console.log("[PostProcessing] Passes →",l.passes);const d=new exports.MODULES.POSTPROCESSING.MODULE.DepthEffect({blendFunction:exports.MODULES.POSTPROCESSING.MODULE.BlendFunction.NORMAL,inverted:!0});d.name="Depth Effect";const u=new exports.MODULES.POSTPROCESSING.MODULE.EffectPass(a,d);if(u.name="Depth Effect Pass",u.enabled=!1,l.passes.push(u),this._passIndices!==null){const m=[l.passes[0]];this._passIndices.length>0&&m.push(...this._passIndices.filter(g=>g!==0).map(g=>l.passes[g]).filter(g=>g)),m.length>0&&console.log("[PostProcessing] Passes (selected) →",m),l.passes.length=0;for(const g of m)g.enabled=!0,g.renderToScreen=!1,l.addPass(g)}const f=this.context.menu;if(f&&this._passIndices===null){this._menuEntry&&this._menuEntry.remove();const m=document.createElement("select");m.multiple=!0;const g=document.createElement("option");g.innerText="Final Output",g.value="-1",m.appendChild(g);for(const y of l.passes){const _=document.createElement("option");_.innerText=y.name,_.value=`${l.passes.indexOf(y)}`,_.title=y.name,m.appendChild(_)}f.appendChild(m),this._menuEntry=m,m.addEventListener("change",()=>{const y=Array.from(m.selectedOptions).map(_=>parseInt(_.value));y.length===1&&y[0]===-1?this._passIndices=null:this._passIndices=y,this.applyEffects(t)})}}}orderEffects(){var e;Jn&&console.log("Before ordering effects",[...this._effects]),dp??(dp=[exports.MODULES.POSTPROCESSING.MODULE.NormalPass,exports.MODULES.POSTPROCESSING.MODULE.DepthDownsamplingPass,exports.MODULES.POSTPROCESSING.MODULE.SMAAEffect,exports.MODULES.POSTPROCESSING.MODULE.SSAOEffect,exports.MODULES.POSTPROCESSING_AO.MODULE.N8AOPostPass,exports.MODULES.POSTPROCESSING.MODULE.TiltShiftEffect,exports.MODULES.POSTPROCESSING.MODULE.DepthOfFieldEffect,exports.MODULES.POSTPROCESSING.MODULE.ChromaticAberrationEffect,exports.MODULES.POSTPROCESSING.MODULE.BloomEffect,exports.MODULES.POSTPROCESSING.MODULE.SelectiveBloomEffect,exports.MODULES.POSTPROCESSING.MODULE.VignetteEffect,exports.MODULES.POSTPROCESSING.MODULE.PixelationEffect,exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect,exports.MODULES.POSTPROCESSING.MODULE.HueSaturationEffect,exports.MODULES.POSTPROCESSING.MODULE.BrightnessContrastEffect]);const t=this._effects;t.sort((i,n)=>{const o=dp.findIndex(l=>i.constructor.name.endsWith(l.name)),a=dp.findIndex(l=>n.constructor.name.endsWith(l.name));return o<0?(Jn&&console.warn("Unknown effect found: ",i.constructor.name),-1):a<0?(Jn&&console.warn("Unknown effect found: ",n.constructor.name),1):o<0?1:a<0?-1:o-a}),Jn&&console.log("After ordering effects",[...this._effects]);for(let i=0;i<t.length;i++){const n=t[i];if(((e=n==null?void 0:n.configuration)==null?void 0:e.gammaCorrection)!==void 0){const o=i===t.length-1;n.configuration.gammaCorrection=o}}}}let dp=null;var qE=Object.defineProperty,XE=Object.getOwnPropertyDescriptor,Uw=(s,t,e,i)=>{for(var n=i>1?void 0:i?XE(t,e):t,o=s.length-1,a;o>=0;o--)(a=s[o])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&qE(t,e,n),n};const Xr=x("debugpost");class rl extends D{constructor(){super(...arguments);r(this,"sharedProfile");r(this,"multisampling","auto");r(this,"_postprocessing");r(this,"_activeEffects",[]);r(this,"_effects",[]);r(this,"_componentEnabledTime",-1);r(this,"_multisampleAutoChangeTime",0);r(this,"_multisampleAutoDecreaseTime",0);r(this,"_lastApplyTime");r(this,"_rapidApplyCount",0);r(this,"_isDirty",!1);r(this,"_modificationQueue");r(this,"_recreateId",-1)}get isPostProcessingManager(){return!0}get effects(){return this._activeEffects}addEffect(e){let i=e;return i instanceof Xe||(i=new Ic(i)),i.gameObject===void 0&&this.gameObject.addComponent(i),this._effects.includes(i)||(this._effects.push(i),this._isDirty=!0),e}removeEffect(e){var n,o,a,l;let i=-1;if(e instanceof Xe?i=this._effects.indexOf(e):i=this._effects.findIndex(c=>c instanceof Ic&&c.effect===e),i!==-1)return this._effects.splice(i,1),this._isDirty=!0,e;if(e instanceof Xe){const c=(o=(n=this.sharedProfile)==null?void 0:n.components)==null?void 0:o.indexOf(e);c!==void 0&&c!==-1&&(this._isDirty=!0,(l=(a=this.sharedProfile)==null?void 0:a.components)==null||l.splice(c,1))}return e}markDirty(){this._isDirty=!0}awake(){var e;Xr&&(console.log("PostprocessingManager Awake",this),console.log("Press P to toggle post processing"),window.addEventListener("keydown",i=>{i.key==="p"&&(this.enabled=!this.enabled,Te("Toggle PostProcessing "+this.name+": Enabled="+this.enabled),this.markDirty())})),(e=this.sharedProfile)==null||e.__init(this)}onEnable(){this._componentEnabledTime=this.context.time.realtimeSinceStartup,this._isDirty=!0}onDisable(){var e;(e=this._postprocessing)==null||e.unapply(),this._isDirty=!1}onBeforeRender(){if(!this.context.isInXR&&(this.context.mainCamera&&this._isDirty&&this.apply(),this.context.composer&&this._postprocessing&&this._postprocessing.composer===this.context.composer)){this.context.renderer.getContext().isContextLost()&&this.context.renderer.forceContextRestore(),this.context.composer.getRenderer()!==this.context.renderer&&this.context.composer.setRenderer(this.context.renderer),this.context.composer.setMainScene(this.context.scene);const e=this.context.composer;if(this.multisampling==="auto"){const i=this.context.time.realtimeSinceStartup-this._multisampleAutoChangeTime;if(this.context.time.realtimeSinceStartup-this._componentEnabledTime>2&&i>.5){const n=e.multisampling;e.multisampling>0&&this.context.time.smoothedFps<=50?(this._multisampleAutoChangeTime=this.context.time.realtimeSinceStartup,this._multisampleAutoDecreaseTime=this.context.time.realtimeSinceStartup,e.multisampling*=.5,e.multisampling=Math.floor(e.multisampling),Xr&&console.debug(`[PostProcessing] Reduced multisampling from ${n} to ${e.multisampling}`)):i>1&&this.context.time.smoothedFps>=59&&e.multisampling<this.context.renderer.capabilities.maxSamples&&this.context.time.realtimeSinceStartup-this._multisampleAutoDecreaseTime>10&&(this._multisampleAutoChangeTime=this.context.time.realtimeSinceStartup,e.multisampling=e.multisampling<=0?1:e.multisampling*2,e.multisampling=Math.floor(e.multisampling),Xr&&console.debug(`[PostProcessing] Increased multisampling from ${n} to ${e.multisampling}`))}}else e.multisampling=Math.max(0,Math.min(this.multisampling,this.context.renderer.capabilities.maxSamples));if(this.context.mainCamera){const i=this.context.composer.passes;for(const n of i)if(n.mainCamera&&n.mainCamera!==this.context.mainCamera){this.context.composer.setMainCamera(this.context.mainCamera);break}}}}onDestroy(){var e;(e=this._postprocessing)==null||e.dispose()}apply(){var e,i;if(Xr&&console.log(`Apply PostProcessing "${this.name}"`),I()&&(this._lastApplyTime!==void 0&&Date.now()-this._lastApplyTime<100&&(this._rapidApplyCount++,this._rapidApplyCount===5&&console.warn("Detected rapid post processing modifications - this might be a bug",this)),this._lastApplyTime=Date.now()),this._isDirty=!1,this.unapply(),this._activeEffects.length=0,(e=this.sharedProfile)!=null&&e.components){const n=this.sharedProfile.components;for(const o of n)o.active&&o.enabled&&!this._activeEffects.includes(o)&&this._activeEffects.push(o)}for(const n of this._effects)n.active&&n.enabled&&!this._activeEffects.includes(n)&&this._activeEffects.push(n);this._activeEffects.length>0&&(this._postprocessing||(this._postprocessing=new oy(this.context)),(i=this._postprocessing.apply(this._activeEffects))==null||i.then(()=>{var o;if(!this.activeAndEnabled)return;this._applyPostQueue();const n=(o=this._postprocessing)==null?void 0:o.composer;n?(this.multisampling==="auto"?n.multisampling=exports.DeviceUtilities.isMobileDevice()?2:4:n.multisampling=Math.max(0,Math.min(this.multisampling,this.context.renderer.capabilities.maxSamples)),Xr&&console.debug(`[PostProcessing] Set multisampling to ${n.multisampling} (Is Mobile: ${exports.DeviceUtilities.isMobileDevice()})`)):Xr&&console.warn("[PostProcessing] No composer found")}))}unapply(){var e;(e=this._postprocessing)==null||e.unapply()}_applyPostQueue(){if(this._modificationQueue){for(const e of this._modificationQueue.values())this.onEditorModification(e);this._modificationQueue.clear()}}onEditorModification(e){var i,n;if(e.propertyName.startsWith("postprocessing.")){if(!this._postprocessing)return this._modificationQueue||(this._modificationQueue=new Map),this._modificationQueue.set(e.propertyName,e),!0;if(!((i=this._activeEffects)!=null&&i.length))return;const o=e.propertyName.split(".");if(o.length===3||o.length===4){const a=o[1],l=o[2];for(const c of this._activeEffects)if(((n=c.typeName)==null?void 0:n.toLowerCase())===a.toLowerCase()){if(l==="active"){c.active=e.value,this.scheduleRecreate();return}if(!rd.has(a)){const d=new Array;rd.set(a,d);const u=Object.keys(c);for(const f of u)c[f]instanceof U&&d.push(f)}if(rd.has(a)){const d=l.toLowerCase(),u=rd.get(a);for(const f of u)if(f.toLowerCase()===d){const m=c[f];m instanceof U&&(o.length===4&&o[3]==="active"?(m.overrideState=e.value,this.scheduleRecreate()):m&&m.value!==void 0&&(m.value=e.value));return}}console.warn("Unknown modification",l);return}}return!0}return!1}scheduleRecreate(){const e=++this._recreateId;setTimeout(()=>{e===this._recreateId&&(this.onDisable(),this.onEnable())},200)}}Uw([yr(Qu)],rl.prototype,"sharedProfile",2);Uw([yr()],rl.prototype,"multisampling",2);const rd=new Map;tE(rl);async function ry(s){const{NeedleEngineHTMLElement:t}=await Promise.resolve().then(()=>VT);t.observedAttributes.includes(s)||t.observedAttributes.push(s)}var QE=Object.defineProperty,YE=Object.getOwnPropertyDescriptor,ut=(s,t,e,i)=>{for(var n=i>1?void 0:i?YE(t,e):t,o=s.length-1,a;o>=0;o--)(a=s[o])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&QE(t,e,n),n};const Rt=x("debugsceneswitcher"),KE=x("sceneswitcher:clearscene"),Td="scene";ry(Td);const zs=Promise.resolve(!1);class Ge extends D{constructor(){super(...arguments);r(this,"autoLoadFirstScene",!0);r(this,"scenes",[]);r(this,"loadingScene");r(this,"queryParameterName","scene");r(this,"useSceneName",!0);r(this,"clamp",!0);r(this,"useHistory",!0);r(this,"useKeyboard",!0);r(this,"useSwipe",!0);r(this,"useSceneLighting",!0);r(this,"useSceneBackground",!0);r(this,"preloadNext",1);r(this,"preloadPrevious",1);r(this,"preloadConcurrent",2);r(this,"createMenuButtons",!1);r(this,"sceneLoadingStart",new ge);r(this,"sceneLoadingProgress",new ge);r(this,"sceneLoaded",new ge);r(this,"_currentIndex",-1);r(this,"_currentScene");r(this,"_engineElementOverserver");r(this,"_preloadScheduler");r(this,"_menuButtons");r(this,"onPopState",async e=>{if(!this.useHistory)return;const i=this.useHistory;try{this.useHistory=!1;let n=!1;if(this.queryParameterName&&(n=await this.tryLoadFromQueryParam()),!n){const o=e==null?void 0:e.state;if(o&&o.startsWith(this.guid)){const a=o.substr(this.guid.length+2);Rt&&console.log("PopState",a),await this.trySelectSceneFromValue(a)}}}finally{this.useHistory=i}});r(this,"normalizedSwipeThresholdX",.1);r(this,"_didSwipe",!1);r(this,"onInputPointerMove",e=>{if(this.useSwipe&&!this._didSwipe&&e.button===0&&e.pointerType==="touch"&&this.context.input.getPointerPressedCount()===1){const i=this.context.input.getPointerPositionDelta(e.button);if(i){const n=i.x/this.context.domWidth;n>=this.normalizedSwipeThresholdX?(this._didSwipe=!0,this.selectPrev()):n<=-this.normalizedSwipeThresholdX&&(this._didSwipe=!0,this.selectNext())}}});r(this,"onInputPointerUp",e=>{e.button===0&&(this._didSwipe=!1)});r(this,"onInputKeyDown",e=>{if(!this.useKeyboard||!this.scenes)return;const i=e.key.toLowerCase();if(!i)return;const n=parseInt(i)-1;if(n>=0){this.trySelectSceneFromValue(n);return}switch(i){case"arrowright":case"d":this.selectNext();break;case"arrowleft":case"a":this.selectPrev();break}});r(this,"__lastSwitchScene");r(this,"__lastSwitchScenePromise");r(this,"_currentlyLoadingScene");r(this,"_lastLoadingScene");r(this,"_loadingScenePromise");r(this,"_isCurrentlyLoading",!1);r(this,"_currentLoadingProgress")}get currentIndex(){return this._currentIndex}get currentLoadingProgress(){return this._currentLoadingProgress}get currentlyLoadingScene(){return this._currentlyLoadingScene}get currentlyLoadedScene(){return this._currentScene}awake(){this.scenes===void 0&&(this.scenes=[]);for(const e of this.scenes)e&&!e.hasUrl&&e.asset instanceof h.Object3D?S.remove(e.asset):e instanceof h.Object3D&&S.remove(e);Rt&&console.log("SceneSwitcher",this)}async onEnable(){if(globalThis.addEventListener("popstate",this.onPopState),this.context.input.addEventListener(Ee.KeyDown,this.onInputKeyDown),this.context.input.addEventListener(Ee.PointerMove,this.onInputPointerMove),this.context.input.addEventListener(Ee.PointerUp,this.onInputPointerUp),this._engineElementOverserver||(this._engineElementOverserver=new MutationObserver(e=>{for(const i of e)if(i.type==="attributes"&&i.attributeName===Td){const n=this.context.domElement.getAttribute(Td);n!==null&&this.trySelectSceneFromValue(n)}})),this._engineElementOverserver.observe(this.context.domElement,{attributes:!0}),this._preloadScheduler||(this._preloadScheduler=new ZE(this)),this._preloadScheduler.maxLoadAhead=this.preloadNext,this._preloadScheduler.maxLoadBehind=this.preloadPrevious,this._preloadScheduler.maxConcurrent=this.preloadConcurrent,this._preloadScheduler.begin(2e3),this.autoLoadFirstScene&&this._currentIndex===-1&&!await this.tryLoadFromQueryParam()){const e=this.context.domElement.getAttribute(Td);try{(e===null||!await this.trySelectSceneFromValue(e))&&this._currentIndex===-1&&this.select(0)}finally{}}this.createMenuButtons&&(this._menuButtons??(this._menuButtons=[]),this._menuButtons.push(this.context.menu.appendChild({label:"Previous",icon:"arrow_back_ios",onClick:()=>this.selectPrev(),priority:-1005,class:"row2"})),this._menuButtons.push(this.context.menu.appendChild({label:"Next",icon:"arrow_forward_ios",iconSide:"right",onClick:()=>this.selectNext(),priority:-1e3,class:"row2"})))}onDisable(){var e;if(globalThis.removeEventListener("popstate",this.onPopState),this.context.input.removeEventListener(Ee.KeyDown,this.onInputKeyDown),this.context.input.removeEventListener(Ee.PointerMove,this.onInputPointerMove),this.context.input.removeEventListener(Ee.PointerUp,this.onInputPointerUp),(e=this._preloadScheduler)==null||e.stop(),this._menuButtons){for(const i of this._menuButtons)i.remove();this._menuButtons=void 0}}addScene(e){if(typeof e=="string"){let i=this.context.addressables.findAssetReference(e);return i||(i=new ee(e),this.context.addressables.registerAssetReference(i)),this.scenes.push(i),i}return this.scenes.push(e),e}selectNext(){return this.select(this._currentIndex+1)}selectPrev(){return this.select(this._currentIndex-1)}select(e){var n,o,a;if(Rt&&console.log("select",e),typeof e=="object"&&console.warn('Switching to "'+e+'" might not work. Please either use an index or a AssetReference (not a scene reference)'),typeof e=="string"){const l=(n=this.scenes)==null?void 0:n.find(c=>c.url===e);if(!l){const c=ee.getOrCreate(this.sourceId??"",e,this.context);return this.switchScene(c)}if(l)e=(o=this.scenes)==null?void 0:o.indexOf(l);else return zs}if(!((a=this.scenes)!=null&&a.length))return zs;if(e<0){if(this.clamp)return zs;e=this.scenes.length-1}else if(e>=this.scenes.length){if(this.clamp)return zs;e=0}const i=this.scenes[e];return this.switchScene(i)}unload(){return this.__lastSwitchScene=void 0,this.__lastSwitchScenePromise=void 0,this.__unloadCurrentScene()}async reload(){if(this.__lastSwitchScene){const e=this.__lastSwitchScene;return this.__lastSwitchScene=void 0,this.switchScene(e)}return!1}async switchScene(e){var n;if(!(e instanceof ee)){const o=typeof e;if(o==="string")return this.select(e);if(o==="number")return this.select(e);if(e&&e instanceof h.Object3D){const a=(n=this.scenes)==null?void 0:n.indexOf(e);e=new ee(e.name,void 0,e),a>=0&&(this.scenes[a]=e)}else return console.warn(`[SceneSwitcher] Can't switch to scene of type ${o}`),!1}return e.url===this.sourceId?(console.warn("[SceneSwitcher] Can't load own scene - prevent recursive loading",this.sourceId),!1):this.__lastSwitchScene===e&&this.__lastSwitchScenePromise?this.__lastSwitchScenePromise:(this.__lastSwitchScene=e,this.__lastSwitchScenePromise=this.__internalSwitchScene(e),await this.__lastSwitchScenePromise)}async __unloadCurrentScene(){const e=this._currentScene;if(this._currentScene=void 0,e){Rt&&console.log("UNLOAD",e.url,"HasURL?: "+e.hasUrl);const i=this.tryGetSceneEventListener(e.asset);if(i!=null&&i.sceneClosing){const n=i.sceneClosing();n instanceof Promise&&await n}e.hasUrl?e.unload():e.asset instanceof h.Object3D&&S.remove(e.asset)}}async __internalSwitchScene(e){var n,o,a,l,c;await this.__unloadCurrentScene();const i=this._currentIndex=((n=this.scenes)==null?void 0:n.indexOf(e))??-1;try{this._currentlyLoadingScene=e,this._currentLoadingProgress=new ProgressEvent("progress",{loaded:0,total:1});const d=new CustomEvent("loadscene-start",{detail:{scene:e,switcher:this,index:i}});this.dispatchEvent(d),(o=this.sceneLoadingStart)==null||o.invoke(d.detail),await this.onStartLoading(),await e.loadAssetAsync((f,m)=>{var g;if(Rt){const y=m.loaded/m.total,_="["+"=".repeat(Math.floor(y*20))+"-".repeat(20-Math.floor(y*20))+"]";console.debug(`[SceneSwitcher] Download ${(y*100).toFixed(1)} % ${_}`,e.url)}this._currentLoadingProgress=m,this.dispatchEvent(m),(g=this.sceneLoadingProgress)==null||g.invoke(m)}).catch(console.error),await this.onEndLoading();const u=new CustomEvent("loadscene-finished",{detail:{scene:e,switcher:this,index:i}});if(this.dispatchEvent(u),this._currentLoadingProgress=void 0,this._currentlyLoadingScene=void 0,u.defaultPrevented)return Rt&&console.warn("Adding loaded scene prevented:",e,u),!1;if(!e.asset)return Rt&&console.warn("Failed loading scene:",e),!1;if(this._currentIndex===i){if(Rt&&console.log("ADD",e.url),this._currentScene=e,KE){const g=((a=this.context.mainCameraComponent)==null?void 0:a.gameObject)||this.context.mainCamera;g==null||g.removeFromParent();const y=this.gameObject.removeFromParent();Ci(this.context.scene,!0,!0),this.context.scene=new h.Scene,this.context.scene.add(y),g&&this.context.scene.add(g)}if(S.add(e.asset,this.gameObject),this.useSceneLighting&&this.context.sceneLighting.enable(e),this.useSceneBackground){const g=this.context.lightmaps.tryGetSkybox(e.url);g?(g.mapping=h.EquirectangularReflectionMapping,this.context.scene.background=g):Rt&&console.warn("SceneSwitcher: Can't find skybox for scene "+e.url)}if(this.useHistory&&i>=0){let g=i.toString();if(this.useSceneName&&(e instanceof h.Object3D?g=e.name:e.url&&(g=ub(e.url))),(l=this.queryParameterName)!=null&&l.length)Cc(this.queryParameterName,g,this.useHistory);else{const y=history.state,_=this.guid+"::"+i;y!==_&&history.pushState(_,"unused",location.href)}}const f=this.tryGetSceneEventListener(e.asset);if(f!=null&&f.sceneOpened){const g=f.sceneOpened(this);g instanceof Promise&&await g}const m=new CustomEvent("scene-opened",{detail:{scene:e,switcher:this,index:i}});return this.dispatchEvent(m),(c=this.sceneLoaded)==null||c.invoke(this),!0}}catch(d){console.error(d)}return!1}preload(e){if(e>=0&&e<this.scenes.length){const i=this.scenes[e];if(i instanceof ee)return i.preload()}return zs}tryLoadFromQueryParam(){var i;if(!((i=this.queryParameterName)!=null&&i.length))return zs;const e=x(this.queryParameterName);return typeof e=="boolean"?zs:this.trySelectSceneFromValue(e)}trySelectSceneFromValue(e){if(typeof e=="string"){const i=parseInt(e);if(i>=0&&i<this.scenes.length)return this.select(i);{const n=e.toLowerCase();for(let o=0;o<this.scenes.length;o++){const a=this.scenes[o];if(!a)continue;if((a instanceof h.Object3D?a.name:ub(a.url)).toLowerCase().includes(n))return this.select(o)}}}else if(typeof e=="number"&&e>=0&&e<this.scenes.length)return this.select(e);return Gt()&&console.warn('Can not find scene: "'+e+'"',this),zs}async onStartLoading(){var e,i;if(this._isCurrentlyLoading=!0,this.loadingScene&&(this._lastLoadingScene!==this.loadingScene&&(this._loadingScenePromise=void 0),this._lastLoadingScene=this.loadingScene,this._loadingScenePromise||(this._loadingScenePromise=(e=this.loadingScene)==null?void 0:e.loadAssetAsync().then(n=>n!=null)),await this._loadingScenePromise,this._isCurrentlyLoading&&((i=this.loadingScene)!=null&&i.asset))){Rt&&console.log("Add loading scene",this.loadingScene.url,this.loadingScene.asset);const n=this.loadingScene.asset;S.add(n,this.gameObject);const o=this.tryGetSceneEventListener(n);if(o!=null&&o.sceneOpened){const a=o.sceneOpened(this);a instanceof Promise&&await a}}if(this._isCurrentlyLoading){const n=this.tryGetSceneEventListener(this.gameObject);if(n&&n.sceneOpened){const o=n.sceneOpened(this);o instanceof Promise&&await o}}}async onEndLoading(){var e;if(this._isCurrentlyLoading=!1,(e=this.loadingScene)!=null&&e.asset){Rt&&console.log("Remove loading scene",this.loadingScene.url);const i=this.loadingScene.asset,n=this.tryGetSceneEventListener(i);if(typeof(n==null?void 0:n.sceneClosing)=="function"){const o=n.sceneClosing();o instanceof Promise&&await o}S.remove(i)}if(!this._isCurrentlyLoading){const i=this.tryGetSceneEventListener(this.gameObject);if(i&&i.sceneClosing){const n=i.sceneClosing();n instanceof Promise&&await n}}}tryGetSceneEventListener(e,i=0){if(!e)return null;const n=S.foreachComponent(e,o=>{const a=o;if(a.sceneClosing||a.sceneOpened)return a});if(i===0&&!n&&e.children.length)for(const o of e.children){const a=this.tryGetSceneEventListener(o,i+1);if(a)return a}return n||null}}ut([p()],Ge.prototype,"autoLoadFirstScene",2);ut([p(ee)],Ge.prototype,"scenes",2);ut([p(ee)],Ge.prototype,"loadingScene",2);ut([p()],Ge.prototype,"queryParameterName",2);ut([p()],Ge.prototype,"useSceneName",2);ut([p()],Ge.prototype,"clamp",2);ut([p()],Ge.prototype,"useHistory",2);ut([p()],Ge.prototype,"useKeyboard",2);ut([p()],Ge.prototype,"useSwipe",2);ut([p()],Ge.prototype,"useSceneLighting",2);ut([p()],Ge.prototype,"useSceneBackground",2);ut([p()],Ge.prototype,"preloadNext",2);ut([p()],Ge.prototype,"preloadPrevious",2);ut([p()],Ge.prototype,"preloadConcurrent",2);ut([p()],Ge.prototype,"createMenuButtons",2);ut([p(ge)],Ge.prototype,"sceneLoadingStart",2);ut([p(ge)],Ge.prototype,"sceneLoadingProgress",2);ut([p(ge)],Ge.prototype,"sceneLoaded",2);function ub(s){const t=s.split("/").pop(),e=t==null?void 0:t.split(".").shift();return e!=null&&e.length?e:s}class ZE{constructor(t,e=1,i=1,n=2){r(this,"maxLoadAhead");r(this,"maxLoadBehind");r(this,"maxConcurrent");r(this,"_isRunning",!1);r(this,"_switcher");r(this,"_loadTasks",[]);r(this,"_maxConcurrentLoads",1);this._switcher=t,this.maxLoadAhead=e,this.maxLoadBehind=i,this.maxConcurrent=n}begin(t){if(this._isRunning)return;Rt&&console.log("Preload begin",{delay:t}),this._isRunning=!0;let e=-10,i,n;const o=this._switcher.scenes,a=Date.now()+t,l=setInterval(()=>{if(this.allLoaded()&&(Rt&&console.log("All scenes (pre-)loaded"),this.stop()),!this._isRunning){clearInterval(l);return}if(Date.now()<a||this.canLoadNewScene()===!1)return;(e===-10||e!==this._switcher.currentIndex)&&(e=this._switcher.currentIndex,n=0,i=0);const c=n%2===0;c&&(i+=1),n+=1;const d=c?this.maxLoadAhead:this.maxLoadBehind;if(i>d)return;const u=c?e+i:e-i;if(!(u<0)&&!(u<0||u>=o.length)&&!this._loadTasks.some(f=>f.index===u)){const f=o[u];Rt&&console.log("Preload scene",{roomIndex:u,searchForward:c,lastRoom:e,currentIndex:this._switcher.currentIndex,tasks:this._loadTasks.length},f==null?void 0:f.url),new JE(u,f,this._loadTasks)}},200)}stop(){this._isRunning=!1}canLoadNewScene(){return this._loadTasks.length<this._maxConcurrentLoads}allLoaded(){if(this._switcher.scenes){for(const t of this._switcher.scenes)if(t!=null&&t.isLoaded&&t.isLoaded()===!1)return!1}return!0}}class JE{constructor(t,e,i){r(this,"index");r(this,"asset");r(this,"tasks");this.index=t,this.asset=e,this.tasks=i,i.push(this),this.awaitLoading()}async awaitLoading(){this.asset&&!this.asset.isLoaded()&&(Rt&&console.log("Preload start: "+this.asset.url,this.index),await this.asset.preload(),Rt&&console.log("Preload finished: "+this.asset.url,this.index));const t=this.tasks.indexOf(this);t>=0&&this.tasks.splice(t,1)}}function ek(){return new Promise((s,t)=>{const i=()=>{i!=null&&(document.removeEventListener("pointerdown",i),document.removeEventListener("click",i),document.removeEventListener("dragstart",i),document.removeEventListener("touchstart",i),s())};document.addEventListener("pointerdown",i),document.addEventListener("click",i),document.addEventListener("dragstart",i),document.addEventListener("touchstart",i)})}async function tk(s){await ek(),s()}var ik=Object.defineProperty,nk=Object.getOwnPropertyDescriptor,Ei=(s,t,e,i)=>{for(var n=i>1?void 0:i?nk(t,e):t,o=s.length-1,a;o>=0;o--)(a=s[o])&&(n=(i?a(t,e,n):a(n))||n);return i&&n&&ik(t,e,n),n};const rt=x("debugvideo");var zw=(s=>(s[s.None=0]="None",s[s.AdjustHeight=1]="AdjustHeight",s[s.AdjustWidth=2]="AdjustWidth",s))(zw||{}),Nw=(s=>(s[s.VideoClip=0]="VideoClip",s[s.Url=1]="Url",s))(Nw||{}),Vw=(s=>(s[s.CameraFarPlane=0]="CameraFarPlane",s[s.CameraNearPlane=1]="CameraNearPlane",s[s.RenderTexture=2]="RenderTexture",s[s.MaterialOverride=3]="MaterialOverride",s))(Vw||{});class nt extends D{constructor(){super();r(this,"playOnAwake",!0);r(this,"aspectMode",0);r(this,"clip",null);r(this,"source",1);r(this,"_url",null);r(this,"renderMode");r(this,"targetMaterialProperty");r(this,"targetMaterialRenderer");r(this,"targetTexture");r(this,"time",0);r(this,"_playbackSpeed",1);r(this,"_isLooping",!1);r(this,"_muted",!1);r(this,"_audioOutputMode",2);r(this,"playInBackground",!0);r(this,"_crossOrigin","anonymous");r(this,"_videoElement",null);r(this,"_videoTexture",null);r(this,"_videoMaterial",null);r(this,"_isPlaying",!1);r(this,"wasPlaying",!1);r(this,"visibilityChanged",e=>{switch(document.visibilityState){case"hidden":this.playInBackground||(this.wasPlaying=this._isPlaying,this.pause());break;case"visible":this.wasPlaying&&!this._isPlaying&&this.play();break}});r(this,"_receivedInput",!1);r(this,"_overlay",null);r(this,"_targetObjects");r(this,"_updateAspectRoutineId",-1);r(this,"_hls");r(this,"onHlsAvailable",()=>{var e;rt&&console.log("HLS: available",this.clip),!(!this.shouldUseM3U||!this.url)&&(this._hls||(this._hls=new Hls),this.videoElement.autoplay=!0,this._hls.loadSource(this.url),this._hls.attachMedia(this.videoElement),(e=this._videoElement)==null||e.play(),rt&&console.log("HLS: loaded",this.clip))});tk(()=>{this._receivedInput=!0,this.updateVideoElementSettings()}),this._targetObjects=[],x("videoscreenspace")&&window.addEventListener("keydown",e=>{e.key==="f"&&(this.screenspace=!this.screenspace)})}get url(){return this._url}set url(e){const n=this._url!==e;this.__didAwake?n&&this.setClipURL(e??""):this._url=e}get playbackSpeed(){var e;return((e=this._videoElement)==null?void 0:e.playbackRate)??this._playbackSpeed}set playbackSpeed(e){this._playbackSpeed=e,this._videoElement&&(this._videoElement.playbackRate=e)}get isLooping(){var e;return((e=this._videoElement)==null?void 0:e.loop)??this._isLooping}set isLooping(e){this._isLooping=e,this._videoElement&&(this._videoElement.loop=e)}get currentTime(){var e;return((e=this._videoElement)==null?void 0:e.currentTime)??this.time}set currentTime(e){this._videoElement?this._videoElement.currentTime=e:this.time=e}get isPlaying(){const e=this._videoElement;if(e){if(e.currentTime>0&&!e.paused&&!e.ended&&e.readyState>e.HAVE_CURRENT_DATA)return!0;if(e.srcObject&&e.srcObject.active)return!0}return!1}get crossOrigin(){var e;return((e=this._videoElement)==null?void 0:e.crossOrigin)??this._crossOrigin}set crossOrigin(e){this._crossOrigin=e,this._videoElement&&(e!==null?this._videoElement.setAttribute("crossorigin",e):this._videoElement.removeAttribute("crossorigin"))}get videoMaterial(){return!this._videoMaterial&&!this.create(!1)?null:this._videoMaterial}get videoTexture(){return!this._videoTexture&&!this.create(!1)?null:this._videoTexture}get videoElement(){return!this._videoElement&&!this.create(!1)?null:this._videoElement}requestPictureInPicture(){return this._videoElement?this._videoElement.requestPictureInPicture():null}get muted(){var e;return((e=this._videoElement)==null?void 0:e.muted)??this._muted}set muted(e){this._muted=e,this._videoElement&&(this._videoElement.muted=e)}get currentVideo(){return this.clip}set audioOutputMode(e){e!==this._audioOutputMode&&(e===1&&I()&&console.warn("VideoAudioOutputMode.AudioSource is not yet implemented"),this._audioOutputMode=e,this.updateVideoElementSettings())}get audioOutputMode(){return this._audioOutputMode}preloadVideo(){rt&&console.log("Video Preload: "+this.name,this.clip),this.create(!1)}preload(){this.preloadVideo()}setVideo(e){this.clip=e,this.source=0,this._videoElement?(this._videoElement.srcObject=e,this._isPlaying&&this.play(),this.updateAspect()):this.create(this.playOnAwake)}setClipURL(e){this._url!==e&&(this._url=e,this.source=1,rt&&console.log("set url",e),this._videoElement?e.endsWith(".m3u8")||e.includes(".m3u")?this.ensureM3UCanBePlayed():(this._videoElement.src=e,this._isPlaying&&(this.stop(),this.play())):this.create(this.playOnAwake))}onEnable(){var e,i;rt&&console.log("VideoPlayer.onEnable",Nw[this.source],this.clip,this.url,this),window.addEventListener("visibilitychange",this.visibilityChanged),this.playOnAwake===!0?this.create(!0):this.preloadVideo(),this.screenspace?(e=this._overlay)==null||e.start():(i=this._overlay)==null||i.stop()}onDisable(){var e;window.removeEventListener("visibilitychange",this.visibilityChanged),(e=this._overlay)==null||e.stop(),this.pause()}onDestroy(){var e;this._videoElement&&((e=this.videoElement)==null||e.remove(),this._videoElement=null),this._videoTexture&&(this._videoTexture.dispose(),this._videoTexture=null)}play(){var e,i;if(this._videoElement||this.create(!1),!this._videoElement){rt&&console.warn("Can not play: no video element found",this);return}if(!(this._isPlaying&&!((e=this._videoElement)!=null&&e.ended)&&!((i=this._videoElement)!=null&&i.paused))){if(this._isPlaying=!0,this._receivedInput||(this._videoElement.muted=!0),this.handleBeginPlaying(!1),this.shouldUseM3U){this.ensureM3UCanBePlayed();return}rt&&console.log("Video Play()",this.clip,this._videoElement,this.time),this._videoElement.currentTime=this.time,this._videoElement.play().catch(n=>{var o;console.log(n),rt&&console.error("Error playing video",n,"CODE="+n.code,(o=this.videoElement)==null?void 0:o.src,this),setTimeout(()=>{this._isPlaying&&!this.destroyed&&this.activeAndEnabled&&this.play()},1e3)}),rt&&console.log("play",this._videoElement,this.time)}}stop(){this._isPlaying=!1,this.time=0,this._videoElement&&(this._videoElement.currentTime=0,this._videoElement.pause(),rt&&console.log("STOP",this))}pause(){var e,i;this.time=((e=this._videoElement)==null?void 0:e.currentTime)??0,this._isPlaying=!1,(i=this._videoElement)==null||i.pause(),rt&&console.log("PAUSE",this,this.currentTime)}create(e){let i;switch(this.source){case 0:i=this.clip;break;case 1:i=this.url,!(i!=null&&i.length)&&typeof this.clip=="string"&&(i=this.clip);break}return i?(this._videoElement||(rt&&console.warn("Create VideoElement",this),this._videoElement=this.createVideoElement(),this.context.domElement.shadowRoot.prepend(this._videoElement),this.updateVideoElementStyles()),typeof i=="string"?(rt&&console.log("Set Video src",i),this._videoElement.src=i):(rt&&console.log("Set Video srcObject",i),this._videoElement.srcObject=i),this._videoTexture||(this._videoTexture=new h.VideoTexture(this._videoElement)),this._videoTexture.flipY=!1,this._videoTexture.colorSpace=h.SRGBColorSpace,e&&this.handleBeginPlaying(e),rt&&console.log("Video: handle playing done...",i,e),!0):(rt&&console.warn("No video source set",this),!1)}updateAspect(){this.aspectMode!==0&&this.startCoroutine(this.updateAspectImpl())}get screenspace(){var e;return((e=this._overlay)==null?void 0:e.enabled)??!1}set screenspace(e){var i;if(e){if(!this._videoTexture)return;this._overlay||(this._overlay=new sk(this.context)),this._overlay.add(this._videoTexture)}else(i=this._overlay)==null||i.remove(this._videoTexture);this._overlay&&(this._overlay.enabled=e)}createVideoElement(){const e=document.createElement("video");return this._crossOrigin&&e.setAttribute("crossorigin",this._crossOrigin),rt&&console.log("created video element",e),e}handleBeginPlaying(e){var o,a;if(!this.activeAndEnabled||!this._videoElement)return;this._targetObjects.length=0;let i=this.gameObject;switch(this.renderMode){case 3:i=(o=this.targetMaterialRenderer)==null?void 0:o.gameObject,i||(i=(a=S.getComponent(this.gameObject,ze))==null?void 0:a.gameObject);break;case 2:console.error("VideoPlayer renderTexture not implemented yet. Please use material override instead");return}if(!i){console.error("Missing target for video material renderer",this.name,Vw[this.renderMode],this);return}const n=i.material;if(n){this._targetObjects.push(i),n!==this._videoMaterial&&(this._videoMaterial=n.clone(),i.material=this._videoMaterial);const l="map",c=this._videoMaterial;if(!this.targetMaterialProperty)c[l]=this._videoTexture;else switch(this.targetMaterialProperty){default:c[l]=this._videoTexture;break}}else{console.warn("Can not play video, no material found, this might be a multimaterial case which is not supported yet");return}this.updateVideoElementSettings(),this.updateVideoElementStyles(),e&&(this.shouldUseM3U&&this.ensureM3UCanBePlayed(),this.play())}updateVideoElementSettings(){if(!this._videoElement)return;this._videoElement.loop=this._isLooping,this._videoElement.currentTime=this.currentTime,this._videoElement.playbackRate=this._playbackSpeed,this._videoElement.playsInline=!0;let e=!this._receivedInput||this.audioOutputMode===0;!e&&this._muted&&(e=!0),this._videoElement.muted=e,this.playOnAwake&&(this._videoElement.autoplay=!0)}updateVideoElementStyles(){this._videoElement&&(this._videoElement.style.userSelect="none",this._videoElement.style.visibility="hidden",this._videoElement.style.display="none",this.updateAspect())}*updateAspectImpl(){const e=++this._updateAspectRoutineId,i=void 0,n=this.clip;for(;e===this._updateAspectRoutineId&&this.aspectMode!==0&&this.clip&&n===this.clip&&this._isPlaying;){if(!n||typeof n=="string")return;let o;for(const a of n.getVideoTracks()){const l=a.getSettings();if(l&&l.width&&l.height){o=l.width/l.height;break}else o=this.context.renderer.domElement.clientWidth/this.context.renderer.domElement.clientHeight}if(o===void 0){for(let a=0;a<10;a++)yield;if(!this.isPlaying)break;continue}if(i===o){yield;continue}for(const a of this._targetObjects){let l=1;if(a.parent){const c=Ue(a.parent);l=c.x/c.y}switch(this.aspectMode){case 1:a.scale.y=1/o*a.scale.x*l;break;case 2:a.scale.x=o*a.scale.y*l;break}}for(let a=0;a<3;a++)yield}}get shouldUseM3U(){return this.url!=null&&(this.url.endsWith(".m3u8")||this.url.endsWith(".m3u"))&&this.source===1}ensureM3UCanBePlayed(){if(!this.shouldUseM3U)return;let e=document.head.querySelector("script[data-hls_library]");e?globalThis.Hls?this.onHlsAvailable():e.addEventListener("load",this.onHlsAvailable):(rt&&console.log("HLS: load script"),e=document.createElement("script"),e.dataset.hls_library="hls.js",e.src="https://cdn.jsdelivr.net/npm/hls.js@1",e.addEventListener("load",this.onHlsAvailable),document.head.append(e))}}Ei([p()],nt.prototype,"playOnAwake",2);Ei([p()],nt.prototype,"aspectMode",2);Ei([p(URL)],nt.prototype,"clip",2);Ei([p()],nt.prototype,"source",2);Ei([p(URL)],nt.prototype,"url",1);Ei([p()],nt.prototype,"renderMode",2);Ei([p()],nt.prototype,"targetMaterialProperty",2);Ei([p(ze)],nt.prototype,"targetMaterialRenderer",2);Ei([p(h.Texture)],nt.prototype,"targetTexture",2);Ei([p()],nt.prototype,"time",2);Ei([p()],nt.prototype,"playbackSpeed",1);Ei([p()],nt.prototype,"isLooping",1);Ei([p()],nt.prototype,"audioOutputMode",1);class sk{constructor(t){r(this,"context");r(this,"_videos",[]);r(this,"_screenspaceModeQuad");r(this,"_isInScreenspaceMode",!1);r(this,"_input");this.context=t,this._input=new ok(this)}get enabled(){return this._isInScreenspaceMode}set enabled(t){t?this.start():this.stop()}add(t){this._videos.indexOf(t)===-1&&this._videos.push(t)}remove(t){if(!t)return;const e=this._videos.indexOf(t);e>=0&&this._videos.splice(e,1)}start(){var n;if(this._isInScreenspaceMode||this._videos.length<0)return;const t=this._videos[this._videos.length-1];if(!t)return;if(this._isInScreenspaceMode=!0,!this._screenspaceModeQuad){if(this._screenspaceModeQuad=bo.createPrimitive(ar.Quad,{material:new rk(t)}),!this._screenspaceModeQuad)return;this._screenspaceModeQuad.geometry.scale(2,2,2)}const e=this._screenspaceModeQuad;this.context.scene.add(e),this.updateScreenspaceMaterialUniforms();const i=e.material;i==null||i.reset(),(n=this._input)==null||n.enable(i)}stop(){var t;this._isInScreenspaceMode=!1,this._screenspaceModeQuad&&((t=this._input)==null||t.disable(),this._screenspaceModeQuad.removeFromParent())}updateScreenspaceMaterialUniforms(){var e;const t=(e=this._screenspaceModeQuad)==null?void 0:e.material;t&&(t.screenAspect=this.context.domElement.clientWidth/this.context.domElement.clientHeight)}}class ok{constructor(t){r(this,"_onResizeScreenFn");r(this,"_onKeyUpFn");r(this,"_onMouseWheelFn");r(this,"context");r(this,"overlay");r(this,"_material");r(this,"_isPinching",!1);r(this,"_lastPinch",0);this.overlay=t,this.context=t.context}enable(t){this._material=t,window.addEventListener("resize",this._onResizeScreenFn=()=>{this.overlay.updateScreenspaceMaterialUniforms()}),window.addEventListener("keyup",this._onKeyUpFn=n=>{n.key==="Escape"&&this.overlay.stop()}),window.addEventListener("wheel",this._onMouseWheelFn=n=>{this.overlay.enabled&&(t.zoom+=n.deltaY*5e-4,n.preventDefault())},{passive:!1});const e=new h.Vector2;window.addEventListener("mousemove",n=>{if(this.overlay.enabled&&this.context.input.getPointerPressed(0)){const o=new h.Vector2(n.movementX,n.movementY);o.x/=this.context.domElement.clientWidth,o.y/=this.context.domElement.clientHeight,e.set(o.x,o.y),e.multiplyScalar(t.zoom/-this.context.time.deltaTime*.01),t.offset=t.offset.add(e)}}),window.addEventListener("pointermove",n=>{this.overlay.enabled&&this.context.input.getPointerPressed(0)&&this.context.input.getTouchesPressedCount()===1&&(e.set(n.movementX,n.movementY),e.multiplyScalar(t.zoom*-this.context.time.deltaTime*.05),t.offset=t.offset.add(e))});let i=0;window.addEventListener("touchstart",n=>{if(n.touches.length<2){this.context.time.time-i<.3&&this.overlay.stop(),i=this.context.time.time;return}this._isPinching=!0,this._lastPinch=0}),window.addEventListener("touchmove",n=>{if(!this._isPinching||!this._material)return;const o=n.touches[0],a=n.touches[1],l=o.clientX-a.clientX,c=o.clientY-a.clientY,d=Math.sqrt(l*l+c*c);if(this._lastPinch!==0){const u=d-this._lastPinch;this._material.zoom-=u*.004}this._lastPinch=d}),window.addEventListener("touchend",()=>{this._isPinching=!1})}disable(){this._onResizeScreenFn&&(window.removeEventListener("resize",this._onResizeScreenFn),this._onResizeScreenFn=void 0),this._onKeyUpFn&&(window.removeEventListener("keyup",this._onKeyUpFn),this._onKeyUpFn=void 0),this._onMouseWheelFn&&(window.removeEventListener("wheel",this._onMouseWheelFn),this._onMouseWheelFn=void 0)}}class rk extends h.ShaderMaterial{constructor(e){super();r(this,"_offset",new h.Vector2);this.uniforms={map:{value:e},screenAspect:{value:1},offsetScale:{value:new h.Vector4(0,0,1,1)}},this.vertexShader=`
|
|
1270
1270
|
uniform sampler2D map;
|
|
1271
1271
|
uniform float screenAspect;
|
|
1272
1272
|
uniform vec4 offsetScale;
|
|
@@ -1407,7 +1407,7 @@ Consider registering a custom loader via the 'onCreateCustomModelLoader' callbac
|
|
|
1407
1407
|
|
|
1408
1408
|
Content-Type: "${e.headers.get("content-type")}
|
|
1409
1409
|
"Text: "${n}"
|
|
1410
|
-
Binary:`,i)}else console.debug("Could not determine file type from binary data");return"unknown"}class tx{createBuiltinComponents(t,e,i,n,o){return ET(t,e,i,n,o)}writeBuiltinComponentData(t,e){return MT(t,e)}parseSync(t,e,i,n){return sx(t,e,i,n)}loadSync(t,e,i,n,o){return fy(t,e,i,n,o)}}Nm(tx);const ix=x("printGltf")||x("printgltf"),TT=x("debugfileformat");async function nx(s,t){const e=await Jw(s,{useExtension:!0})||"unknown";TT&&console.debug(`Determined file type: '${e}' for url '${s}'`,{registeredModelLoaderCallbacks:ua});for(const i of ua){const{callback:n}=i;let o=n({context:t,url:s,mimetype:e});if(o instanceof Promise&&await o,o)return console.debug(`Using custom loader (${i.name}) for
|
|
1410
|
+
Binary:`,i)}else console.debug("Could not determine file type from binary data");return"unknown"}class tx{createBuiltinComponents(t,e,i,n,o){return ET(t,e,i,n,o)}writeBuiltinComponentData(t,e){return MT(t,e)}parseSync(t,e,i,n){return sx(t,e,i,n)}loadSync(t,e,i,n,o){return fy(t,e,i,n,o)}}Nm(tx);const ix=x("printGltf")||x("printgltf"),TT=x("debugfileformat");async function nx(s,t){const e=await Jw(s,{useExtension:!0})||"unknown";TT&&console.debug(`Determined file type: '${e}' for url '${s}'`,{registeredModelLoaderCallbacks:ua});for(const i of ua){const{callback:n}=i;let o=n({context:t,url:s,mimetype:e});if(o instanceof Promise&&await o,o)return console.debug(`Using custom loader (${i.name||"unnamed"}) for ${e} at '${s}'`),o}switch(e){default:case"unknown":{console.warn(`Unknown file type (${e}). Needle Engine will fallback to the GLTFLoader - To support more model formats please create a Needle loader plugin.
|
|
1411
1411
|
Use import { NeedleEngineModelLoader } from "@needle-tools/engine" namespace to register your loader.`,s);const i=new Y.GLTFLoader;return await iu(i,t,s),i}case"model/fbx":case"model/vnd.autodesk.fbx":return new Y.FBXLoader;case"model/obj":return new Y.OBJLoader;case"model/vnd.usdz+zip":case"model/vnd.usd+zip":case"model/vnd.usda+zip":return console.warn(e.toUpperCase()+" files are not supported."),null;case"model/gltf+json":case"model/gltf-binary":case"model/vrm":{const i=new Y.GLTFLoader;return await iu(i,t,s),i}}}function AT(s,t){return fy((t==null?void 0:t.context)||Q.Current,s,s,(t==null?void 0:t.seed)||null,t==null?void 0:t.onprogress)}async function sx(s,t,e,i){typeof e!="string"&&(console.warn("Parse gltf binary without path, this might lead to errors in resolving extensions. Please provide the source path of the gltf/glb file",e,typeof e),e=""),ix&&console.log("Parse glTF",e);const n=await nx(e,s);if(!n)return;const{componentsExtension:o}=ox(n,s);if(n instanceof Y.OBJLoader){typeof t!="string"&&(t=new TextDecoder().decode(t));const l=n.parse(t);return await pc(n,s,e,l,i,o)}if(!(n instanceof Y.GLTFLoader)){if(n.parse===void 0){console.error("Loader does not support parse");return}const l=n.parse(t,e);return await pc(n,s,e,l,i,o)}return new Promise((l,c)=>{try{let d=e.split("?")[0].trimEnd();const u=d.split("/");u.length>0&&u[u.length-1]!==""&&u.pop(),d=u.join("/"),d.endsWith("/")||(d+="/"),n.resourcePath=d,n.parse(t,"",async f=>{const m=await pc(n,s,e,f,i,o);l(m)},f=>{console.error('Loading asset at "'+e+`" failed
|
|
1412
1412
|
`,f),l(void 0)})}catch(d){console.error(d),c(d)}})}async function fy(s,t,e,i,n){LT(t);const o=await nx(t,s);if(!o)return;const{componentsExtension:a}=ox(o,s);if(!(o instanceof Y.GLTFLoader)){const l=await o.loadAsync(t,n);return await pc(o,s,t,l,i,a)}return new Promise((l,c)=>{try{o.load(t,async d=>{const u=await pc(o,s,e,d,i,a);l(u)},d=>{n==null||n.call(o,d)},d=>{console.error('Loading asset at "'+t+`" failed
|
|
1413
1413
|
`,d),l(void 0)})}catch(d){console.error(d),c(d)}})}function ox(s,t){const e=Eg(s);return s instanceof Y.GLTFLoader&&dg(s,t),{componentsExtension:e}}async function pc(s,t,e,i,n,o){var a;if(ix&&console.warn("Loaded",e,i),i==null)return console.error(`Loaded model is null '${e}' - please make sure the loader is registered correctly`),{scene:new h.Object3D,animations:[],scenes:[]};if(typeof i!="object")return console.error(`Loaded model is not an object '${e}' - please make sure the loader is registered correctly`),{scene:new h.Object3D,animations:[],scenes:[]};if(i instanceof h.Object3D)i={scene:i,animations:i.animations,scenes:[i]};else if(i instanceof h.BufferGeometry){const l=new h.MeshStandardMaterial({color:new h.Color(14540253)}),c=new h.Mesh(i,l);i={scene:c,animations:[],scenes:[c]}}else Array.isArray(i.scenes)===!1&&console.error(`[Needle Engine] The loaded model object does not have a scenes property '${e}' - please make sure the loader is registered correctly and three.js is not imported multiple times.`);if(e.includes("?")&&(e=e.split("?")[0]),"scenes"in i)for(const l of i.scenes)l&&!((a=l.animations)!=null&&a.length)&&(l.animations=[...i.animations]);return IT(s,i),Iv(i)&&(Jv(e,i,t),await un().createBuiltinComponents(t,e,i,n,o||void 0)),await DT(i.scene,t,t.mainCamera),i}async function DT(s,t,e){e||(e=t.mainCamera);try{e?await t.renderer.compileAsync(s,e,t.scene).catch(i=>{console.warn(i.message)}):mC(s,t)}catch(i){console.warn((i==null?void 0:i.message)||i)}}function LT(s){if(new URL(s,window.location.href).href.startsWith("file://")){const e=`Hi - it looks like you are trying to load a local file which will not work. You need to use a webserver to serve your files.
|
|
@@ -1521,7 +1521,7 @@ Needle Engine: Begin loading `+i+`
|
|
|
1521
1521
|
`,e),this.onBeforeBeginLoading();const l=[],c={context:this._context,name:"",progress:{},index:0,count:e.length,totalProgress01:this._loadingProgress01},d=new CustomEvent("progress",{detail:c}),u=new Array,f=new AbortController;this._abortController=f;const m={files:e,abortSignal:f.signal,onLoadingProgress:v=>{var C;if(Se&&console.debug("Loading progress: ",v),f.signal.aborted)return;const w=v.index;!u[w]&&v.name&&(u[w]=NT(v.name)),v.name=u[w],a&&((C=this._loadingView)==null||C.onLoadingUpdate(v)),c.name=v.name,c.progress=v.progress,this._loadingProgress01=py(v),c.totalProgress01=this._loadingProgress01,this.dispatchEvent(d)},onLoadingFinished:(v,w,C)=>{Se&&console.debug(`Finished loading "${w}" (aborted? ${f.signal.aborted})`),!f.signal.aborted&&C&&l.push({src:w,file:C})}},g=this.getAttribute("hash");g!=null&&(this._context.hash=g),this._context.alias=n,this._createContextPromise=this._context.create(m);const y=await this._createContextPromise;if(this.applyAttributes(),Se&&console.warn(`--------------
|
|
1522
1522
|
Needle Engine: finished loading `+i+`
|
|
1523
1523
|
`,e,`Aborted? ${f.signal.aborted}`),f.signal.aborted){console.log("Loading finished but aborted...");return}if(this._loadId!==i){console.log("Load id changed during loading process");return}this._loadingProgress01=1,a&&y&&((b=this._loadingView)==null||b.onLoadingUpdate(1,"creating scene")),this._didFullyLoad=!0,this.classList.remove("loading"),this.classList.add("loading-finished"),this.dispatchEvent(new CustomEvent("loadfinished",{detail:{context:this._context,src:n,loadedFiles:l}}))}applyAttributes(){var n,o;if((n=this._context)!=null&&n.renderer){const a=this.getAttribute("tonemapping")||this.getAttribute("tone-mapping");switch(a==null?void 0:a.toLowerCase()){case"none":this._context.renderer.toneMapping=h.NoToneMapping;break;case"linear":this._context.renderer.toneMapping=h.LinearToneMapping;break;case"neutral":this._context.renderer.toneMapping=h.NeutralToneMapping;break;case"agx":this._context.renderer.toneMapping=h.AgXToneMapping;break;default:a!=null&&console.warn("Invalid tone-mapping attribute: "+a)}const l=this.getAttribute("tone-mapping-exposure");if(l!=null){const c=parseFloat(l);isNaN(c)||(this._context.renderer.toneMappingExposure=c)}}const e=this.getAttribute("background-blurriness");if(e!=null){const a=parseFloat(e);a!==void 0&&this._context&&(this._context.scene.backgroundBlurriness=a)}const i=this.getAttribute("background-color");if((o=this._context)!=null&&o.renderer&&typeof i=="string"&&i.length>0){const a=ie.fromColorRepresentation(i);Se&&console.debug("<needle-engine> background-color changed, str:",i,"→",a),this._context.renderer.setClearColor(a,a.alpha),this.context.scene.background=null}}internalSetLoadingMessage(e){var i;(i=this._loadingView)==null||i.setMessage(e)}getSourceFiles(){const e=this.getAttribute("src");if(!e)return[];let i;Array.isArray(e)?i=e:e.startsWith("[")&&e.endsWith("]")?i=JSON.parse(e):e.includes(",")?i=e.split(","):i=[e];for(let n=i.length-1;n>=0;n--){const o=i[n];(o==="null"||o==="undefined"||(o==null?void 0:o.length)<=0)&&i.splice(n,1)}return i}checkIfSourceHasChanged(e,i){if((e==null?void 0:e.length)!==(i==null?void 0:i.length)||e==null&&i!==null||e!==null&&i==null)return!0;if(e!==null&&i!==null){for(let n=0;n<(e==null?void 0:e.length);n++)if(e[n]!==i[n])return!0}return!1}ensureLoadStartIsRegistered(){const e=this.getAttribute("loadstart");e&&this.registerEventFromAttribute("loadstart",e)}registerEventFromAttribute(e,i){const n=this._previouslyRegisteredMap.get(e);if(n&&(this._previouslyRegisteredMap.delete(e),this.removeEventListener(e,n)),typeof i=="string"&&i.length>0)try{const o=(0,eval)(i);typeof o=="function"&&(this._previouslyRegisteredMap.set(e,o),this.addEventListener(e,a=>o==null?void 0:o.call(globalThis,this._context,a)))}catch(o){console.error("Error registering event "+e+'="'+i+`" failed with the following error:
|
|
1524
|
-
`,o)}}setPublicKey(){ec.length>0&&this.setAttribute("public-key",ec)}setVersion(){hn.length>0&&this.setAttribute("version",hn)}getAROverlayContainer(){return this._overlay_ar.createOverlayContainer(this)}getVROverlayContainer(){for(let e=0;e<this.children.length;e++){const i=this.children[e];if(i.classList.contains("vr"))return i}return null}onEnterAR(e){var n;this.onSetupAR();const i=this.getAROverlayContainer();this._overlay_ar.onBegin(this._context,i,e),this.dispatchEvent(new CustomEvent("enter-ar",{detail:{session:e,context:this._context,htmlContainer:(n=this._overlay_ar)==null?void 0:n.ARContainer}}))}onExitAR(e){var i;this._overlay_ar.onEnd(this._context),this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-ar",{detail:{session:e,context:this._context,htmlContainer:(i=this._overlay_ar)==null?void 0:i.ARContainer}}))}onEnterVR(e){this.onSetupVR(),this.dispatchEvent(new CustomEvent("enter-vr",{detail:{session:e,context:this._context}}))}onExitVR(e){this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-vr",{detail:{session:e,context:this._context}}))}onSetupAR(){this.classList.add(El),this.classList.remove(kl);const e=this.getAROverlayContainer();Se&&console.warn("onSetupAR:",e),e&&(e.classList.add(El),e.classList.remove(kl)),this.foreachHtmlElement(i=>this.setupElementsForMode(i,rx))}onSetupVR(){this.classList.remove(El),this.classList.remove(kl),this.foreachHtmlElement(e=>this.setupElementsForMode(e,ax))}onSetupDesktop(){this.classList.remove(El),this.classList.add(kl);const e=this.getAROverlayContainer();e&&(e.classList.remove(El),e.classList.add(kl)),this.foreachHtmlElement(i=>this.setupElementsForMode(i,lx))}setupElementsForMode(e,i,n=null){var a,l;if(e===((l=(a=this._context)==null?void 0:a.renderer)==null?void 0:l.domElement)||e.id==="VRButton"||e.id==="ARButton")return;if(e.classList.contains(i))e.style.visibility="visible",e.style.display==="none"&&(e.style.display="block");else for(const c of UT)e.classList.contains(c)&&(e.style.visibility="hidden",e.style.display="none")}foreachHtmlElement(e){for(let i=0;i<this.children.length;i++){const n=this.children[i];n.style&&e(n)}}onBeforeBeginLoading(){const e=this.getAttribute("dracoDecoderPath");e&&(Se&&console.log("using custom draco decoder path",e),P_(e));const i=this.getAttribute("dracoDecoderType");i&&(Se&&console.log("using custom draco decoder type",i),O_(i));const n=this.getAttribute("ktx2DecoderPath");n&&(Se&&console.log("using custom ktx2 decoder path",n),M_(n))}}typeof window<"u"&&!window.customElements.get(Sb)&&window.customElements.define(Sb,my);function NT(s){if(s.startsWith("blob:"))return"blob";const t=s.split("/");let e=t[t.length-1];const i=e.indexOf("?");i>0&&(e=e.substring(0,i));const n=e.indexOf("=");n>0&&(e=e.substring(n));const o=e.split(".").pop(),l=o?["glb","gltf","usdz","usd","fbx","obj","mtl"].indexOf(o.toLowerCase()):-1;if(o&&l>=0&&(e=e.substring(0,e.length-o.length-1)),e=decodeURIComponent(e),e.length>3){let c="",d=!1;const u=["(",")","[","]","{","}",":",";",",",".","!","?"];for(let f=0;f<e.length;f++){let m=e[f];(m==="_"||m==="-")&&(m=" "),!(m===" "&&c.length<=0||u.includes(m)||(c.length===0&&(m=m.toUpperCase()),d&&m===" "))&&(d&&(m=m.toUpperCase()),d=!1,c+=m,m===" "&&(d=!0))}return I()&&e!==c&&console.debug('Generated display name: "'+e+'" → "'+c+'"'),c.trim()}return I()&&console.debug("Loading: use default name",e),e}const VT=Object.freeze(Object.defineProperty({__proto__:null,NeedleEngineHTMLElement:my},Symbol.toStringTag,{value:"Module"}));function $T(){$i.registerWaitForInteraction(()=>{const s=h.AudioContext.getContext();s.addEventListener("statechange",()=>{setTimeout(()=>{const t=s.state;(t==="suspended"||t==="interrupted")&&s.resume().then(()=>{console.log("AudioContext resumed successfully")}).catch(e=>{console.log("Failed to resume AudioContext: "+e)})},500)})})}setTimeout($T,1e3);const _t=x("debugphysics"),mp=x("debugcolliderplacement"),gp=x("debugcollisions"),WT=x("showcolliders"),yp=x("debugraycasts"),Zt=Symbol("needle component"),Ut=Symbol("physics body"),Cb=Symbol("rigidbody");globalThis.false=globalThis.false!==void 0?globalThis.false:!0;_t&&console.log("Use Rapier",!1,globalThis.false);const Sc=class{constructor(t){r(this,"debugRenderColliders",!1);r(this,"debugRenderRaycasts",!1);r(this,"context");r(this,"_initializePromise");r(this,"_isInitialized",!1);r(this,"rapierRay");r(this,"raycastVectorsBuffer",new Si(()=>new h.Vector3,10));r(this,"rapierSphere",null);r(this,"rapierColliderArray",[]);r(this,"rapierIdentityRotation",{x:0,y:0,z:0,w:1});r(this,"rapierForwardVector",{x:0,y:0,z:1});r(this,"enabled",!1);r(this,"_tempPosition",new h.Vector3);r(this,"_tempQuaternion",new h.Quaternion);r(this,"_tempScale",new h.Vector3);r(this,"_tempMatrix",new h.Matrix4);r(this,"_isUpdatingPhysicsWorld",!1);r(this,"_world");r(this,"_hasCreatedWorld",!1);r(this,"eventQueue");r(this,"collisionHandler");r(this,"objects",[]);r(this,"bodies",[]);r(this,"_meshCache",new Map);r(this,"_gravity",{x:0,y:-9.81,z:0});r(this,"lines");r(this,"_tempCenterPos",new h.Vector3);r(this,"_tempCenterVec",new h.Vector3);r(this,"_tempCenterQuaternion",new h.Quaternion);this.context=t}removeBody(t){var i,n,o;if(!t)return;this.validate();const e=t[Ut];if(t[Ut]=null,e&&this.world){const a=this.objects.findIndex(l=>l===t);if(a>=0){const l=this.bodies[a];if(this.bodies.splice(a,1),this.objects.splice(a,1),l instanceof exports.MODULES.RAPIER_PHYSICS.MODULE.Collider){const c=l;(i=this.world)==null||i.removeCollider(c,!0);const d=c.parent();d&&d.numColliders()<=0&&(d[Zt]||(n=this.world)==null||n.removeRigidBody(d))}else l instanceof exports.MODULES.RAPIER_PHYSICS.MODULE.RigidBody&&(l.numColliders()<=0?(o=this.world)==null||o.removeRigidBody(l):I()&&(l.did_log_removing||setTimeout(()=>{l.numColliders()>0&&(l.did_log_removing=!0,console.warn("RapierPhysics: removing rigidbody with colliders from the physics world is not possible right now, please remove the colliders first"))},1)))}}}updateBody(t,e,i){if(this.validate(),!!this.enabled&&!(t.destroyed||!t.gameObject)&&!(!e&&!i))if(t.isCollider===!0)console.warn("TODO: implement updating collider position");else{const n=t,o=n[Ut];o&&this.syncPhysicsBody(n.gameObject,o,e,i)}}updateProperties(t){if(this.validate(),t.isCollider){const e=t,i=e[Ut];i&&(this.internalUpdateColliderProperties(e,i),e.sharedMaterial&&this.updatePhysicsMaterial(e))}else{const e=t,i=this.internal_getRigidbody(e);i&&this.internalUpdateRigidbodyProperties(e,i)}}addForce(t,e,i){this.validate();const n=this.internal_getRigidbody(t);n?n.addForce(e,i):console.warn("Rigidbody doesn't exist: can not apply force (does your object with the Rigidbody have a collider?)")}addImpulse(t,e,i){this.validate();const n=this.internal_getRigidbody(t);n?n.applyImpulse(e,i):console.warn("Rigidbody doesn't exist: can not apply impulse (does your object with the Rigidbody have a collider?)")}getLinearVelocity(t){this.validate();const e=this.internal_getRigidbody(t);return e?e.linvel():null}getAngularVelocity(t){this.validate();const e=this.internal_getRigidbody(t);return e?e.angvel():null}resetForces(t,e){this.validate();const i=this.internal_getRigidbody(t);i==null||i.resetForces(e)}resetTorques(t,e){this.validate();const i=this.internal_getRigidbody(t);i==null||i.resetTorques(e)}applyImpulse(t,e,i){this.validate();const n=this.internal_getRigidbody(t);n?n.applyImpulse(e,i):console.warn("Rigidbody doesn't exist: can not apply impulse (does your object with the Rigidbody have a collider?)")}wakeup(t){this.validate();const e=this.internal_getRigidbody(t);e?e.wakeUp():console.warn("Rigidbody doesn't exist: can not wake up (does your object with the Rigidbody have a collider?)")}isSleeping(t){this.validate();const e=this.internal_getRigidbody(t);return e==null?void 0:e.isSleeping()}setAngularVelocity(t,e,i){this.validate();const n=this.internal_getRigidbody(t);n?n.setAngvel(e,i):console.warn("Rigidbody doesn't exist: can not set angular velocity (does your object with the Rigidbody have a collider?)")}setLinearVelocity(t,e,i){this.validate();const n=this.internal_getRigidbody(t);n?n.setLinvel(e,i):console.warn("Rigidbody doesn't exist: can not set linear velocity (does your object with the Rigidbody have a collider?)")}get isInitialized(){return this._isInitialized}async initialize(){return this._initializePromise||(this._initializePromise=this.internalInitialization()),this._initializePromise}async internalInitialization(){return x("__nophysics")?(console.warn("Physics are disabled"),!1):(_t&&console.log("Initialize rapier physics engine"),"env"in{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:ya&&ya.tagName.toUpperCase()==="SCRIPT"&&ya.src||new URL("needle-engine.bundle-ee9f7e66.light.umd.cjs",document.baseURI).href}&&{}.VITE_NEEDLE_USE_RAPIER==="false"&&_t&&console.log("Rapier disabled"),!1)}validate(){this._isInitialized||_t&&(this._lastWarnTime=this._lastWarnTime??0,Date.now()-this._lastWarnTime>1e3&&(this._lastWarnTime=Date.now(),console.warn("Physics engine is not initialized")))}raycast(t,e,i){var c;if(!this._isInitialized)return console.log("Physics engine is not initialized"),null;let n=i==null?void 0:i.maxDistance,o=i==null?void 0:i.solid;n===void 0&&(n=1/0),o===void 0&&(o=!0);const a=this.getPhysicsRay(this.rapierRay,t,e);if(!a)return null;(this.debugRenderRaycasts||yp)&&N.DrawRay(a.origin,a.dir,255,1);const l=(c=this.world)==null?void 0:c.castRay(a,n,o,i==null?void 0:i.queryFilterFlags,i==null?void 0:i.filterGroups,void 0,void 0,d=>{const u=d[Zt];return i!=null&&i.filterPredicate?i.filterPredicate(u):(i==null?void 0:i.useIgnoreRaycastLayer)!==!1?!(u!=null&&u.gameObject.layers.isEnabled(2)):!0});if(l){const d=a.pointAt(l.timeOfImpact),u=this.raycastVectorsBuffer.get();return u.set(d.x,d.y,d.z),{point:u,collider:l.collider[Zt]}}return null}raycastAndGetNormal(t,e,i){var c;if(!this._isInitialized)return null;let n=i==null?void 0:i.maxDistance,o=i==null?void 0:i.solid;n===void 0&&(n=1/0),o===void 0&&(o=!0);const a=this.getPhysicsRay(this.rapierRay,t,e);if(!a)return null;(this.debugRenderRaycasts||yp)&&N.DrawRay(a.origin,a.dir,255,1);const l=(c=this.world)==null?void 0:c.castRayAndGetNormal(a,n,o,i==null?void 0:i.queryFilterFlags,i==null?void 0:i.filterGroups,void 0,void 0,d=>{const u=d[Zt];return i!=null&&i.filterPredicate?i.filterPredicate(u):(i==null?void 0:i.useIgnoreRaycastLayer)!==!1?!(u!=null&&u.gameObject.layers.isEnabled(2)):!0});if(l){const d=a.pointAt(l.timeOfImpact),u=l.normal,f=this.raycastVectorsBuffer.get(),m=this.raycastVectorsBuffer.get();return f.set(d.x,d.y,d.z),m.set(u.x,u.y,u.z),{point:f,normal:m,collider:l.collider[Zt]}}return null}getPhysicsRay(t,e,i){var l,c,d;const n=(l=this.context)==null?void 0:l.mainCamera;if(e===void 0){const u=(c=this.context)==null?void 0:c.input.getPointerPosition(0);if(u)e=u;else return null}if(e.z===void 0){if(!n)return console.error("Can not perform raycast from 2d point - no main camera found"),null;const u=this.raycastVectorsBuffer.get();u.x=e.x,u.y=e.y,u.z=0,(u.x>1||u.y>1||u.y<-1||u.x<-1)&&(_t&&console.warn("Converting screenspace to raycast space",u),(d=this.context)==null||d.input.convertScreenspaceToRaycastSpace(u)),u.unproject(n),e=u}const o=e;t.origin.x=o.x,t.origin.y=o.y,t.origin.z=o.z;const a=this.raycastVectorsBuffer.get();if(i)a.set(i.x,i.y,i.z);else{if(!n)return console.error("Can not perform raycast - no camera found"),null;a.set(t.origin.x,t.origin.y,t.origin.z);const u=Z(n);a.sub(u)}return a.normalize(),t.dir.x=a.x,t.dir.y=a.y,t.dir.z=a.z,t}sphereOverlap(t,e){return this.rapierColliderArray.length=0,this._isInitialized?this.world?(this.rapierSphere??(this.rapierSphere=new exports.MODULES.RAPIER_PHYSICS.MODULE.Ball(e)),this.rapierSphere.radius=e,(this.debugRenderRaycasts||yp)&&N.DrawWireSphere(t,e,3359999,1),this.world.intersectionsWithShape(t,this.rapierIdentityRotation,this.rapierSphere,i=>{const n=i[Zt],o=new Uv(n.gameObject,n);return this.rapierColliderArray.push(o),!0},void 0,void 0,void 0,void 0,i=>i.isSensor()?!1:i[Zt].gameObject.layers.isEnabled(2)==!1),this.rapierColliderArray):this.rapierColliderArray:this.rapierColliderArray}get world(){return this._world}get isUpdating(){return this._isUpdatingPhysicsWorld}get gravity(){var t;return((t=this.world)==null?void 0:t.gravity)??this._gravity}set gravity(t){this.world?this.world.gravity=t:this._gravity=t}clearCaches(){var t,e,i,n;this._meshCache.clear(),(t=this.eventQueue)!=null&&t.raw&&((e=this.eventQueue)==null||e.free()),(i=this.world)!=null&&i.bodies&&((n=this.world)==null||n.free())}async addBoxCollider(t,e){if(this._isInitialized||await this.initialize(),!t.activeAndEnabled)return;if(!this.enabled){_t&&console.warn("Physics are disabled");return}const i=t.gameObject,n=Ue(i,this._tempPosition).multiply(e);n.multiplyScalar(.5),n.x<0&&(n.x=Math.abs(n.x)),n.y<0&&(n.y=Math.abs(n.y)),n.z<0&&(n.z=Math.abs(n.z));const o=1e-7;n.x<o&&(n.x=o),n.y<o&&(n.y=o),n.z<o&&(n.z=o);const a=exports.MODULES.RAPIER_PHYSICS.MODULE.ColliderDesc.cuboid(n.x,n.y,n.z);this.createCollider(t,a)}async addSphereCollider(t){if(this._isInitialized||await this.initialize(),!t.activeAndEnabled)return;if(!this.enabled){_t&&console.warn("Physics are disabled");return}const e=exports.MODULES.RAPIER_PHYSICS.MODULE.ColliderDesc.ball(.5);this.createCollider(t,e),this.updateProperties(t)}async addCapsuleCollider(t,e,i){if(this._isInitialized||await this.initialize(),!t.activeAndEnabled)return;if(!this.enabled){_t&&console.warn("Physics are disabled");return}const n=t.gameObject,o=Ue(n,this._tempPosition);o.x=Math.abs(o.x),o.y=Math.abs(o.y);const a=i*o.x;e=Math.max(e,a*2);const l=z.clamp(e*.5*o.y-i*o.x,0,Number.MAX_SAFE_INTEGER),c=exports.MODULES.RAPIER_PHYSICS.MODULE.ColliderDesc.capsule(l,a);this.createCollider(t,c)}async addMeshCollider(t,e,i,n){var f,m,g;let o=e.geometry;if(!o){_t&&console.warn("Missing mesh geometry",e.name);return}(m=(f=o.index)==null?void 0:f.array)!=null&&m.length||(console.warn(`Your MeshCollider is missing vertices or indices in the assined mesh "${e.name}". Consider providing an indexed geometry.`),o=Y.mergeVertices(o));let a=null;const l=o.getAttribute("position");if(l instanceof h.InterleavedBufferAttribute){const y=l.count;a=new Float32Array(y*3);for(let _=0;_<y;_++){const b=l.getX(_),v=l.getY(_),w=l.getZ(_);a[_*3]=b,a[_*3+1]=v,a[_*3+2]=w}}else a=l.array;if(await this.initialize(),!this.enabled){_t&&console.warn("Physics are disabled");return}if(!t.activeAndEnabled)return;const c=(g=o.index)==null?void 0:g.array,d=t.gameObject.worldScale.clone();if(n&&d.multiply(n),Math.abs(d.x-1)>1e-4||Math.abs(d.y-1)>1e-4||Math.abs(d.z-1)>1e-4){const y=`${o.uuid}_${d.x}_${d.y}_${d.z}_${i}`;if(this._meshCache.has(y))_t&&console.warn("Use cached mesh collider"),a=this._meshCache.get(y);else{(_t||I())&&console.debug(`[Performance] Your MeshCollider "${t.name}" is scaled: consider applying the scale to the collider mesh instead (${d.x}, ${d.y}, ${d.z})`);const _=new Float32Array(a.length);for(let b=0;b<a.length;b+=3)_[b]=a[b]*d.x,_[b+1]=a[b+1]*d.y,_[b+2]=a[b+2]*d.z;a=_,this._meshCache.set(y,_)}}const u=i?exports.MODULES.RAPIER_PHYSICS.MODULE.ColliderDesc.convexHull(a):exports.MODULES.RAPIER_PHYSICS.MODULE.ColliderDesc.trimesh(a,c);u&&this.createCollider(t,u)}updatePhysicsMaterial(t){if(!t)return;const e=t.sharedMaterial,i=t[Ut];if(i&&e){if(e.bounciness!==void 0&&i.setRestitution(e.bounciness),e.bounceCombine!==void 0)switch(e.bounceCombine){case at.Average:i.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case at.Maximum:i.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case at.Minimum:i.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case at.Multiply:i.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}if(e.dynamicFriction!==void 0&&i.setFriction(e.dynamicFriction),e.frictionCombine!==void 0)switch(e.frictionCombine){case at.Average:i.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case at.Maximum:i.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case at.Minimum:i.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case at.Multiply:i.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}}}getBody(t){return t?t[Ut]:null}getComponent(t){return t?t[Zt]:null}createCollider(t,e){var a;if(!this.world)throw new Error("Physics world not initialized");const i=this._tempMatrix;let n;t.attachedRigidbody?n=this.getRigidbody(t,this._tempMatrix):(_t&&console.log("Create collider without rigidbody",t.name),i.makeRotationFromQuaternion(ye(t.gameObject)),i.setPosition(Z(t.gameObject))),i.decompose(this._tempPosition,this._tempQuaternion,this._tempScale),this.tryApplyCenter(t,this._tempPosition),e.setTranslation(this._tempPosition.x,this._tempPosition.y,this._tempPosition.z),e.setRotation(this._tempQuaternion),e.setSensor(t.isTrigger);const o=t.sharedMaterial;if(o){if(o.bounciness!==void 0&&e.setRestitution(o.bounciness),o.bounceCombine!==void 0)switch(o.bounceCombine){case at.Average:e.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case at.Maximum:e.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case at.Minimum:e.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case at.Multiply:e.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}if(o.dynamicFriction!==void 0&&e.setFriction(o.dynamicFriction),o.frictionCombine!==void 0)switch(o.frictionCombine){case at.Average:e.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case at.Maximum:e.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case at.Minimum:e.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case at.Multiply:e.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}}((a=t.attachedRigidbody)==null?void 0:a.autoMass)===!1&&(e.setDensity(1e-6),e.setMass(1e-6));try{const l=this.world.createCollider(e,n);return l[Zt]=t,t[Ut]=l,l.setActiveEvents(exports.MODULES.RAPIER_PHYSICS.MODULE.ActiveEvents.COLLISION_EVENTS),l.setActiveCollisionTypes(exports.MODULES.RAPIER_PHYSICS.MODULE.ActiveCollisionTypes.ALL),this.objects.push(t),this.bodies.push(l),this.updateColliderCollisionGroups(t),l}catch(l){return console.error('Error creating collider "'+t.name+`"
|
|
1524
|
+
`,o)}}setPublicKey(){ec.length>0&&this.setAttribute("public-key",ec)}setVersion(){hn.length>0&&this.setAttribute("version",hn)}getAROverlayContainer(){return this._overlay_ar.createOverlayContainer(this)}getVROverlayContainer(){for(let e=0;e<this.children.length;e++){const i=this.children[e];if(i.classList.contains("vr"))return i}return null}onEnterAR(e){var n;this.onSetupAR();const i=this.getAROverlayContainer();this._overlay_ar.onBegin(this._context,i,e),this.dispatchEvent(new CustomEvent("enter-ar",{detail:{session:e,context:this._context,htmlContainer:(n=this._overlay_ar)==null?void 0:n.ARContainer}}))}onExitAR(e){var i;this._overlay_ar.onEnd(this._context),this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-ar",{detail:{session:e,context:this._context,htmlContainer:(i=this._overlay_ar)==null?void 0:i.ARContainer}}))}onEnterVR(e){this.onSetupVR(),this.dispatchEvent(new CustomEvent("enter-vr",{detail:{session:e,context:this._context}}))}onExitVR(e){this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-vr",{detail:{session:e,context:this._context}}))}onSetupAR(){this.classList.add(El),this.classList.remove(kl);const e=this.getAROverlayContainer();Se&&console.warn("onSetupAR:",e),e&&(e.classList.add(El),e.classList.remove(kl)),this.foreachHtmlElement(i=>this.setupElementsForMode(i,rx))}onSetupVR(){this.classList.remove(El),this.classList.remove(kl),this.foreachHtmlElement(e=>this.setupElementsForMode(e,ax))}onSetupDesktop(){this.classList.remove(El),this.classList.add(kl);const e=this.getAROverlayContainer();e&&(e.classList.remove(El),e.classList.add(kl)),this.foreachHtmlElement(i=>this.setupElementsForMode(i,lx))}setupElementsForMode(e,i,n=null){var a,l;if(e===((l=(a=this._context)==null?void 0:a.renderer)==null?void 0:l.domElement)||e.id==="VRButton"||e.id==="ARButton")return;if(e.classList.contains(i))e.style.visibility="visible",e.style.display==="none"&&(e.style.display="block");else for(const c of UT)e.classList.contains(c)&&(e.style.visibility="hidden",e.style.display="none")}foreachHtmlElement(e){for(let i=0;i<this.children.length;i++){const n=this.children[i];n.style&&e(n)}}onBeforeBeginLoading(){const e=this.getAttribute("dracoDecoderPath");e&&(Se&&console.log("using custom draco decoder path",e),P_(e));const i=this.getAttribute("dracoDecoderType");i&&(Se&&console.log("using custom draco decoder type",i),O_(i));const n=this.getAttribute("ktx2DecoderPath");n&&(Se&&console.log("using custom ktx2 decoder path",n),M_(n))}}typeof window<"u"&&!window.customElements.get(Sb)&&window.customElements.define(Sb,my);function NT(s){if(s.startsWith("blob:"))return"blob";const t=s.split("/");let e=t[t.length-1];const i=e.indexOf("?");i>0&&(e=e.substring(0,i));const n=e.indexOf("=");n>0&&(e=e.substring(n));const o=e.split(".").pop(),l=o?["glb","gltf","usdz","usd","fbx","obj","mtl"].indexOf(o.toLowerCase()):-1;if(o&&l>=0&&(e=e.substring(0,e.length-o.length-1)),e=decodeURIComponent(e),e.length>3){let c="",d=!1;const u=["(",")","[","]","{","}",":",";",",",".","!","?"];for(let f=0;f<e.length;f++){let m=e[f];(m==="_"||m==="-")&&(m=" "),!(m===" "&&c.length<=0||u.includes(m)||(c.length===0&&(m=m.toUpperCase()),d&&m===" "))&&(d&&(m=m.toUpperCase()),d=!1,c+=m,m===" "&&(d=!0))}return I()&&e!==c&&console.debug('Generated display name: "'+e+'" → "'+c+'"'),c.trim()}return I()&&console.debug("Loading: use default name",e),e}const VT=Object.freeze(Object.defineProperty({__proto__:null,NeedleEngineHTMLElement:my},Symbol.toStringTag,{value:"Module"}));function $T(){$i.registerWaitForInteraction(()=>{const s=h.AudioContext.getContext();s.addEventListener("statechange",()=>{setTimeout(()=>{const t=s.state;(t==="suspended"||t==="interrupted")&&s.resume().then(()=>{console.log("AudioContext resumed successfully")}).catch(e=>{console.log("Failed to resume AudioContext: "+e)})},500)})})}setTimeout($T,1e3);const _t=x("debugphysics"),mp=x("debugcolliderplacement"),gp=x("debugcollisions"),WT=x("showcolliders"),yp=x("debugraycasts"),Zt=Symbol("needle component"),Ut=Symbol("physics body"),Cb=Symbol("rigidbody");globalThis.false=globalThis.false!==void 0?globalThis.false:!0;_t&&console.log("Use Rapier",!1,globalThis.false);const Sc=class{constructor(t){r(this,"debugRenderColliders",!1);r(this,"debugRenderRaycasts",!1);r(this,"context");r(this,"_initializePromise");r(this,"_isInitialized",!1);r(this,"rapierRay");r(this,"raycastVectorsBuffer",new Si(()=>new h.Vector3,10));r(this,"rapierSphere",null);r(this,"rapierColliderArray",[]);r(this,"rapierIdentityRotation",{x:0,y:0,z:0,w:1});r(this,"rapierForwardVector",{x:0,y:0,z:1});r(this,"enabled",!1);r(this,"_tempPosition",new h.Vector3);r(this,"_tempQuaternion",new h.Quaternion);r(this,"_tempScale",new h.Vector3);r(this,"_tempMatrix",new h.Matrix4);r(this,"_isUpdatingPhysicsWorld",!1);r(this,"_world");r(this,"_hasCreatedWorld",!1);r(this,"eventQueue");r(this,"collisionHandler");r(this,"objects",[]);r(this,"bodies",[]);r(this,"_meshCache",new Map);r(this,"_gravity",{x:0,y:-9.81,z:0});r(this,"lines");r(this,"_tempCenterPos",new h.Vector3);r(this,"_tempCenterVec",new h.Vector3);r(this,"_tempCenterQuaternion",new h.Quaternion);this.context=t}removeBody(t){var i,n,o;if(!t)return;this.validate();const e=t[Ut];if(t[Ut]=null,e&&this.world){const a=this.objects.findIndex(l=>l===t);if(a>=0){const l=this.bodies[a];if(this.bodies.splice(a,1),this.objects.splice(a,1),l instanceof exports.MODULES.RAPIER_PHYSICS.MODULE.Collider){const c=l;(i=this.world)==null||i.removeCollider(c,!0);const d=c.parent();d&&d.numColliders()<=0&&(d[Zt]||(n=this.world)==null||n.removeRigidBody(d))}else l instanceof exports.MODULES.RAPIER_PHYSICS.MODULE.RigidBody&&(l.numColliders()<=0?(o=this.world)==null||o.removeRigidBody(l):I()&&(l.did_log_removing||setTimeout(()=>{l.numColliders()>0&&(l.did_log_removing=!0,console.warn("RapierPhysics: removing rigidbody with colliders from the physics world is not possible right now, please remove the colliders first"))},1)))}}}updateBody(t,e,i){if(this.validate(),!!this.enabled&&!(t.destroyed||!t.gameObject)&&!(!e&&!i))if(t.isCollider===!0)console.warn("TODO: implement updating collider position");else{const n=t,o=n[Ut];o&&this.syncPhysicsBody(n.gameObject,o,e,i)}}updateProperties(t){if(this.validate(),t.isCollider){const e=t,i=e[Ut];i&&(this.internalUpdateColliderProperties(e,i),e.sharedMaterial&&this.updatePhysicsMaterial(e))}else{const e=t,i=this.internal_getRigidbody(e);i&&this.internalUpdateRigidbodyProperties(e,i)}}addForce(t,e,i){this.validate();const n=this.internal_getRigidbody(t);n?n.addForce(e,i):console.warn("Rigidbody doesn't exist: can not apply force (does your object with the Rigidbody have a collider?)")}addImpulse(t,e,i){this.validate();const n=this.internal_getRigidbody(t);n?n.applyImpulse(e,i):console.warn("Rigidbody doesn't exist: can not apply impulse (does your object with the Rigidbody have a collider?)")}getLinearVelocity(t){this.validate();const e=this.internal_getRigidbody(t);return e?e.linvel():null}getAngularVelocity(t){this.validate();const e=this.internal_getRigidbody(t);return e?e.angvel():null}resetForces(t,e){this.validate();const i=this.internal_getRigidbody(t);i==null||i.resetForces(e)}resetTorques(t,e){this.validate();const i=this.internal_getRigidbody(t);i==null||i.resetTorques(e)}applyImpulse(t,e,i){this.validate();const n=this.internal_getRigidbody(t);n?n.applyImpulse(e,i):console.warn("Rigidbody doesn't exist: can not apply impulse (does your object with the Rigidbody have a collider?)")}wakeup(t){this.validate();const e=this.internal_getRigidbody(t);e?e.wakeUp():console.warn("Rigidbody doesn't exist: can not wake up (does your object with the Rigidbody have a collider?)")}isSleeping(t){this.validate();const e=this.internal_getRigidbody(t);return e==null?void 0:e.isSleeping()}setAngularVelocity(t,e,i){this.validate();const n=this.internal_getRigidbody(t);n?n.setAngvel(e,i):console.warn("Rigidbody doesn't exist: can not set angular velocity (does your object with the Rigidbody have a collider?)")}setLinearVelocity(t,e,i){this.validate();const n=this.internal_getRigidbody(t);n?n.setLinvel(e,i):console.warn("Rigidbody doesn't exist: can not set linear velocity (does your object with the Rigidbody have a collider?)")}get isInitialized(){return this._isInitialized}async initialize(){return this._initializePromise||(this._initializePromise=this.internalInitialization()),this._initializePromise}async internalInitialization(){return x("__nophysics")?(console.warn("Physics are disabled"),!1):(_t&&console.log("Initialize rapier physics engine"),"env"in{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:ya&&ya.tagName.toUpperCase()==="SCRIPT"&&ya.src||new URL("needle-engine.bundle-12ffa86b.light.umd.cjs",document.baseURI).href}&&{}.VITE_NEEDLE_USE_RAPIER==="false"&&_t&&console.log("Rapier disabled"),!1)}validate(){this._isInitialized||_t&&(this._lastWarnTime=this._lastWarnTime??0,Date.now()-this._lastWarnTime>1e3&&(this._lastWarnTime=Date.now(),console.warn("Physics engine is not initialized")))}raycast(t,e,i){var c;if(!this._isInitialized)return console.log("Physics engine is not initialized"),null;let n=i==null?void 0:i.maxDistance,o=i==null?void 0:i.solid;n===void 0&&(n=1/0),o===void 0&&(o=!0);const a=this.getPhysicsRay(this.rapierRay,t,e);if(!a)return null;(this.debugRenderRaycasts||yp)&&N.DrawRay(a.origin,a.dir,255,1);const l=(c=this.world)==null?void 0:c.castRay(a,n,o,i==null?void 0:i.queryFilterFlags,i==null?void 0:i.filterGroups,void 0,void 0,d=>{const u=d[Zt];return i!=null&&i.filterPredicate?i.filterPredicate(u):(i==null?void 0:i.useIgnoreRaycastLayer)!==!1?!(u!=null&&u.gameObject.layers.isEnabled(2)):!0});if(l){const d=a.pointAt(l.timeOfImpact),u=this.raycastVectorsBuffer.get();return u.set(d.x,d.y,d.z),{point:u,collider:l.collider[Zt]}}return null}raycastAndGetNormal(t,e,i){var c;if(!this._isInitialized)return null;let n=i==null?void 0:i.maxDistance,o=i==null?void 0:i.solid;n===void 0&&(n=1/0),o===void 0&&(o=!0);const a=this.getPhysicsRay(this.rapierRay,t,e);if(!a)return null;(this.debugRenderRaycasts||yp)&&N.DrawRay(a.origin,a.dir,255,1);const l=(c=this.world)==null?void 0:c.castRayAndGetNormal(a,n,o,i==null?void 0:i.queryFilterFlags,i==null?void 0:i.filterGroups,void 0,void 0,d=>{const u=d[Zt];return i!=null&&i.filterPredicate?i.filterPredicate(u):(i==null?void 0:i.useIgnoreRaycastLayer)!==!1?!(u!=null&&u.gameObject.layers.isEnabled(2)):!0});if(l){const d=a.pointAt(l.timeOfImpact),u=l.normal,f=this.raycastVectorsBuffer.get(),m=this.raycastVectorsBuffer.get();return f.set(d.x,d.y,d.z),m.set(u.x,u.y,u.z),{point:f,normal:m,collider:l.collider[Zt]}}return null}getPhysicsRay(t,e,i){var l,c,d;const n=(l=this.context)==null?void 0:l.mainCamera;if(e===void 0){const u=(c=this.context)==null?void 0:c.input.getPointerPosition(0);if(u)e=u;else return null}if(e.z===void 0){if(!n)return console.error("Can not perform raycast from 2d point - no main camera found"),null;const u=this.raycastVectorsBuffer.get();u.x=e.x,u.y=e.y,u.z=0,(u.x>1||u.y>1||u.y<-1||u.x<-1)&&(_t&&console.warn("Converting screenspace to raycast space",u),(d=this.context)==null||d.input.convertScreenspaceToRaycastSpace(u)),u.unproject(n),e=u}const o=e;t.origin.x=o.x,t.origin.y=o.y,t.origin.z=o.z;const a=this.raycastVectorsBuffer.get();if(i)a.set(i.x,i.y,i.z);else{if(!n)return console.error("Can not perform raycast - no camera found"),null;a.set(t.origin.x,t.origin.y,t.origin.z);const u=Z(n);a.sub(u)}return a.normalize(),t.dir.x=a.x,t.dir.y=a.y,t.dir.z=a.z,t}sphereOverlap(t,e){return this.rapierColliderArray.length=0,this._isInitialized?this.world?(this.rapierSphere??(this.rapierSphere=new exports.MODULES.RAPIER_PHYSICS.MODULE.Ball(e)),this.rapierSphere.radius=e,(this.debugRenderRaycasts||yp)&&N.DrawWireSphere(t,e,3359999,1),this.world.intersectionsWithShape(t,this.rapierIdentityRotation,this.rapierSphere,i=>{const n=i[Zt],o=new Uv(n.gameObject,n);return this.rapierColliderArray.push(o),!0},void 0,void 0,void 0,void 0,i=>i.isSensor()?!1:i[Zt].gameObject.layers.isEnabled(2)==!1),this.rapierColliderArray):this.rapierColliderArray:this.rapierColliderArray}get world(){return this._world}get isUpdating(){return this._isUpdatingPhysicsWorld}get gravity(){var t;return((t=this.world)==null?void 0:t.gravity)??this._gravity}set gravity(t){this.world?this.world.gravity=t:this._gravity=t}clearCaches(){var t,e,i,n;this._meshCache.clear(),(t=this.eventQueue)!=null&&t.raw&&((e=this.eventQueue)==null||e.free()),(i=this.world)!=null&&i.bodies&&((n=this.world)==null||n.free())}async addBoxCollider(t,e){if(this._isInitialized||await this.initialize(),!t.activeAndEnabled)return;if(!this.enabled){_t&&console.warn("Physics are disabled");return}const i=t.gameObject,n=Ue(i,this._tempPosition).multiply(e);n.multiplyScalar(.5),n.x<0&&(n.x=Math.abs(n.x)),n.y<0&&(n.y=Math.abs(n.y)),n.z<0&&(n.z=Math.abs(n.z));const o=1e-7;n.x<o&&(n.x=o),n.y<o&&(n.y=o),n.z<o&&(n.z=o);const a=exports.MODULES.RAPIER_PHYSICS.MODULE.ColliderDesc.cuboid(n.x,n.y,n.z);this.createCollider(t,a)}async addSphereCollider(t){if(this._isInitialized||await this.initialize(),!t.activeAndEnabled)return;if(!this.enabled){_t&&console.warn("Physics are disabled");return}const e=exports.MODULES.RAPIER_PHYSICS.MODULE.ColliderDesc.ball(.5);this.createCollider(t,e),this.updateProperties(t)}async addCapsuleCollider(t,e,i){if(this._isInitialized||await this.initialize(),!t.activeAndEnabled)return;if(!this.enabled){_t&&console.warn("Physics are disabled");return}const n=t.gameObject,o=Ue(n,this._tempPosition);o.x=Math.abs(o.x),o.y=Math.abs(o.y);const a=i*o.x;e=Math.max(e,a*2);const l=z.clamp(e*.5*o.y-i*o.x,0,Number.MAX_SAFE_INTEGER),c=exports.MODULES.RAPIER_PHYSICS.MODULE.ColliderDesc.capsule(l,a);this.createCollider(t,c)}async addMeshCollider(t,e,i,n){var f,m,g;let o=e.geometry;if(!o){_t&&console.warn("Missing mesh geometry",e.name);return}(m=(f=o.index)==null?void 0:f.array)!=null&&m.length||(console.warn(`Your MeshCollider is missing vertices or indices in the assined mesh "${e.name}". Consider providing an indexed geometry.`),o=Y.mergeVertices(o));let a=null;const l=o.getAttribute("position");if(l instanceof h.InterleavedBufferAttribute){const y=l.count;a=new Float32Array(y*3);for(let _=0;_<y;_++){const b=l.getX(_),v=l.getY(_),w=l.getZ(_);a[_*3]=b,a[_*3+1]=v,a[_*3+2]=w}}else a=l.array;if(await this.initialize(),!this.enabled){_t&&console.warn("Physics are disabled");return}if(!t.activeAndEnabled)return;const c=(g=o.index)==null?void 0:g.array,d=t.gameObject.worldScale.clone();if(n&&d.multiply(n),Math.abs(d.x-1)>1e-4||Math.abs(d.y-1)>1e-4||Math.abs(d.z-1)>1e-4){const y=`${o.uuid}_${d.x}_${d.y}_${d.z}_${i}`;if(this._meshCache.has(y))_t&&console.warn("Use cached mesh collider"),a=this._meshCache.get(y);else{(_t||I())&&console.debug(`[Performance] Your MeshCollider "${t.name}" is scaled: consider applying the scale to the collider mesh instead (${d.x}, ${d.y}, ${d.z})`);const _=new Float32Array(a.length);for(let b=0;b<a.length;b+=3)_[b]=a[b]*d.x,_[b+1]=a[b+1]*d.y,_[b+2]=a[b+2]*d.z;a=_,this._meshCache.set(y,_)}}const u=i?exports.MODULES.RAPIER_PHYSICS.MODULE.ColliderDesc.convexHull(a):exports.MODULES.RAPIER_PHYSICS.MODULE.ColliderDesc.trimesh(a,c);u&&this.createCollider(t,u)}updatePhysicsMaterial(t){if(!t)return;const e=t.sharedMaterial,i=t[Ut];if(i&&e){if(e.bounciness!==void 0&&i.setRestitution(e.bounciness),e.bounceCombine!==void 0)switch(e.bounceCombine){case at.Average:i.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case at.Maximum:i.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case at.Minimum:i.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case at.Multiply:i.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}if(e.dynamicFriction!==void 0&&i.setFriction(e.dynamicFriction),e.frictionCombine!==void 0)switch(e.frictionCombine){case at.Average:i.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case at.Maximum:i.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case at.Minimum:i.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case at.Multiply:i.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}}}getBody(t){return t?t[Ut]:null}getComponent(t){return t?t[Zt]:null}createCollider(t,e){var a;if(!this.world)throw new Error("Physics world not initialized");const i=this._tempMatrix;let n;t.attachedRigidbody?n=this.getRigidbody(t,this._tempMatrix):(_t&&console.log("Create collider without rigidbody",t.name),i.makeRotationFromQuaternion(ye(t.gameObject)),i.setPosition(Z(t.gameObject))),i.decompose(this._tempPosition,this._tempQuaternion,this._tempScale),this.tryApplyCenter(t,this._tempPosition),e.setTranslation(this._tempPosition.x,this._tempPosition.y,this._tempPosition.z),e.setRotation(this._tempQuaternion),e.setSensor(t.isTrigger);const o=t.sharedMaterial;if(o){if(o.bounciness!==void 0&&e.setRestitution(o.bounciness),o.bounceCombine!==void 0)switch(o.bounceCombine){case at.Average:e.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case at.Maximum:e.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case at.Minimum:e.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case at.Multiply:e.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}if(o.dynamicFriction!==void 0&&e.setFriction(o.dynamicFriction),o.frictionCombine!==void 0)switch(o.frictionCombine){case at.Average:e.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case at.Maximum:e.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case at.Minimum:e.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case at.Multiply:e.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}}((a=t.attachedRigidbody)==null?void 0:a.autoMass)===!1&&(e.setDensity(1e-6),e.setMass(1e-6));try{const l=this.world.createCollider(e,n);return l[Zt]=t,t[Ut]=l,l.setActiveEvents(exports.MODULES.RAPIER_PHYSICS.MODULE.ActiveEvents.COLLISION_EVENTS),l.setActiveCollisionTypes(exports.MODULES.RAPIER_PHYSICS.MODULE.ActiveCollisionTypes.ALL),this.objects.push(t),this.bodies.push(l),this.updateColliderCollisionGroups(t),l}catch(l){return console.error('Error creating collider "'+t.name+`"
|
|
1525
1525
|
Error:`,l),null}}updateColliderCollisionGroups(t){const e=t[Ut],i=t.membership;let n=0;if(i==null)n=65535;else for(let l=0;l<i.length;l++){const c=i[l];c>31?console.error(`Rapier only supports 32 layers, layer ${c} is not supported`):n|=1<<Math.floor(c)}const o=t.filter;let a=0;if(o==null)a=65535;else for(let l=0;l<o.length;l++){const c=o[l];c>31?console.error(`Rapier only supports 32 layers, layer ${c} is not supported`):a|=1<<Math.floor(c)}e.setCollisionGroups(n<<16|a)}getRigidbody(t,e){if(!this.world)throw new Error("Physics world not initialized");let i=null;if(t.attachedRigidbody){const n=t.attachedRigidbody;if(i=n[Ut],!i){const o=n.isKinematic&&!mp;_t&&console.log("Create rigidbody",o);const a=o?exports.MODULES.RAPIER_PHYSICS.MODULE.RigidBodyDesc.kinematicPositionBased():exports.MODULES.RAPIER_PHYSICS.MODULE.RigidBodyDesc.dynamic(),l=Z(t.attachedRigidbody.gameObject);a.setTranslation(l.x,l.y,l.z),a.setRotation(ye(t.attachedRigidbody.gameObject)),a.centerOfMass=new exports.MODULES.RAPIER_PHYSICS.MODULE.Vector3(n.centerOfMass.x,n.centerOfMass.y,n.centerOfMass.z),i=this.world.createRigidBody(a),this.bodies.push(i),this.objects.push(n)}i[Zt]=n,n[Ut]=i,this.internalUpdateRigidbodyProperties(n,i),this.getRigidbodyRelativeMatrix(t.gameObject,n.gameObject,e),t[Cb]=i}else{const n=exports.MODULES.RAPIER_PHYSICS.MODULE.RigidBodyDesc.kinematicPositionBased(),o=Z(t.gameObject);n.setTranslation(o.x,o.y,o.z),n.setRotation(ye(t.gameObject)),i=this.world.createRigidBody(n),e.identity(),i[Zt]=null}return i}internal_getRigidbody(t){return t.isCollider===!0?t[Cb]:t[Ut]}internalUpdateColliderProperties(t,e){const i=e.shape;let n=!1;switch(i.type){case exports.MODULES.RAPIER_PHYSICS.MODULE.ShapeType.Ball:{const m=i,g=t,y=t.gameObject,_=Ue(y,this._tempPosition),b=Math.abs(g.radius*_.x);n=m.radius!==b,m.radius=b,n&&e.setShape(m);break}case exports.MODULES.RAPIER_PHYSICS.MODULE.ShapeType.Cuboid:const o=i,a=t,l=t.gameObject,c=Ue(l,this._tempPosition),d=Math.abs(a.size.x*.5*c.x),u=Math.abs(a.size.y*.5*c.y),f=Math.abs(a.size.z*.5*c.z);n=o.halfExtents.x!==d||o.halfExtents.y!==u||o.halfExtents.z!==f,o.halfExtents.x=d,o.halfExtents.y=u,o.halfExtents.z=f,n&&e.setShape(o);break}if(n){const o=t.attachedRigidbody;if(o!=null&&o.autoMass){const a=this.getBody(o);a==null||a.recomputeMassPropertiesFromColliders()}}this.updateColliderCollisionGroups(t),t.isTrigger!==e.isSensor()&&e.setSensor(t.isTrigger)}internalUpdateRigidbodyProperties(t,e){if(e.enableCcd(t.collisionDetectionMode!==Lu.Discrete),e.setLinearDamping(t.drag),e.setAngularDamping(t.angularDrag),e.setGravityScale(t.useGravity?t.gravityScale:0,!0),t.dominanceGroup<=127&&t.dominanceGroup>=-127?e.setDominanceGroup(Math.floor(t.dominanceGroup)):e.setDominanceGroup(0),t.autoMass){e.setAdditionalMass(0,!1);for(let i=0;i<e.numColliders();i++)e.collider(i).setDensity(1);e.recomputeMassPropertiesFromColliders()}else{e.setAdditionalMass(t.mass,!1);for(let i=0;i<e.numColliders();i++)e.collider(i).setDensity(1e-7);e.recomputeMassPropertiesFromColliders()}e.setEnabledRotations(!t.lockRotationX,!t.lockRotationY,!t.lockRotationZ,!1),e.setEnabledTranslations(!t.lockPositionX,!t.lockPositionY,!t.lockPositionZ,!1),t.isKinematic?e.setBodyType(exports.MODULES.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicPositionBased,!1):e.setBodyType(exports.MODULES.RAPIER_PHYSICS.MODULE.RigidBodyType.Dynamic,!1)}step(t){if(this.world&&this.enabled){if(this._isUpdatingPhysicsWorld=!0,this.eventQueue||(this.eventQueue=new exports.MODULES.RAPIER_PHYSICS.MODULE.EventQueue(!1)),t===void 0||t<=0){this._isUpdatingPhysicsWorld=!1;return}else t!==void 0&&(this.world.timestep=z.lerp(this.world.timestep,t,.8));try{this.world.step(this.eventQueue)}catch(e){console.warn("Error running physics step",e)}this._isUpdatingPhysicsWorld=!1}}postStep(){this.world&&this.enabled&&(this._isUpdatingPhysicsWorld=!0,this.syncObjects(),this._isUpdatingPhysicsWorld=!1,this.eventQueue&&!this.collisionHandler&&(this.collisionHandler=new HT(this.world,this.eventQueue)),this.collisionHandler&&(this.collisionHandler.handleCollisionEvents(),this.collisionHandler.update()),this.updateDebugRendering(this.world))}updateDebugRendering(t){var e,i,n,o;if(_t||mp||WT||this.debugRenderColliders===!0){if(!this.lines){const l=new h.LineBasicMaterial({color:7855479,fog:!1}),c=new h.BufferGeometry;this.lines=new h.LineSegments(c,l),this.lines.layers.disableAll(),this.lines.layers.enable(2)}this.lines.parent!==((e=this.context)==null?void 0:e.scene)&&((i=this.context)==null||i.scene.add(this.lines));const a=t.debugRender();this.lines.geometry.setAttribute("position",new h.BufferAttribute(a.vertices,3)),this.lines.geometry.setAttribute("color",new h.BufferAttribute(a.colors,4)),(this.context.time.frame%30===0||((n=this.lines.geometry.boundingSphere)==null?void 0:n.radius)===0)&&this.lines.geometry.computeBoundingSphere()}else this.lines&&((o=this.context)==null||o.scene.remove(this.lines))}syncObjects(){if(!mp)for(let t=0;t<this.bodies.length;t++){const e=this.objects[t],i=this.bodies[t],n=e;if((n==null?void 0:n.isCollider)===!0&&!n.attachedRigidbody){const c=i.parent();c?this.syncPhysicsBody(e.gameObject,c,!0,!0):this.syncPhysicsBody(e.gameObject,i,!0,!0);continue}const o=i.translation(),a=i.rotation();if(Number.isNaN(o.x)||Number.isNaN(a.x)){!n.__COLLIDER_NAN&&I()&&(console.warn("Collider has NaN values",n.name,n.gameObject,i),n.__COLLIDER_NAN=!0);continue}const l=e.center;if(l&&l.isVector3){this._tempQuaternion.set(a.x,a.y,a.z,a.w);const c=this._tempPosition.copy(l).applyQuaternion(this._tempQuaternion),d=Ue(e.gameObject);c.multiply(d),o.x-=c.x,o.y-=c.y,o.z-=c.z}rr(e.gameObject,o.x,o.y,o.z),Lm(e.gameObject,a.x,a.y,a.z,a.w)}}syncPhysicsBody(t,e,i,n){if(e instanceof exports.MODULES.RAPIER_PHYSICS.MODULE.RigidBody){const o=Z(t,this._tempPosition),a=ye(t,this._tempQuaternion);switch(e.bodyType()){case exports.MODULES.RAPIER_PHYSICS.MODULE.RigidBodyType.Fixed:case exports.MODULES.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicPositionBased:case exports.MODULES.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicVelocityBased:i&&e.setNextKinematicTranslation(o),n&&e.setNextKinematicRotation(a);break;default:i&&e.setTranslation(o,!1),n&&e.setRotation(a,!1);break}}else if(e instanceof exports.MODULES.RAPIER_PHYSICS.MODULE.Collider){t.matrixWorldNeedsUpdate&&t.updateWorldMatrix(!0,!1),t.matrixWorld.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const o=this._tempPosition,a=this._tempQuaternion,l=e[Zt];if(this.tryApplyCenter(l,o),i){const c=e.translation();(c.x!==o.x||c.y!==o.y||c.z!==o.z)&&e.setTranslation(o)}if(n){const c=e.rotation();(c.x!==a.x||c.y!==a.y||c.z!==a.z||c.w!==a.w)&&e.setRotation(a)}}}tryApplyCenter(t,e){const i=t.center;i&&t.gameObject&&(i.x!==0||i.y!==0||i.z!==0)&&(this._tempCenterPos.x=i.x,this._tempCenterPos.y=i.y,this._tempCenterPos.z=i.z,Ue(t.gameObject,this._tempCenterVec),this._tempCenterPos.multiply(this._tempCenterVec),t.attachedRigidbody?this._tempCenterPos.applyQuaternion(t.gameObject.quaternion):(ye(t.gameObject,this._tempCenterQuaternion),this._tempCenterPos.applyQuaternion(this._tempCenterQuaternion)),e.x+=this._tempCenterPos.x,e.y+=this._tempCenterPos.y,e.z+=this._tempCenterPos.z)}getRigidbodyRelativeMatrix(t,e,i,n){if(n===void 0&&(n=Sc._matricesBuffer,n.length=0),t===e){const o=Ue(t,this._tempPosition);i.makeScale(o.x,o.y,o.z);for(let a=n.length-1;a>=0;a--)i.multiply(n[a]);return i}return n.push(t.matrix),t.parent&&this.getRigidbodyRelativeMatrix(t.parent,e,i,n),i}addFixedJoint(t,e){if(!this.world){console.error("Physics world not initialized");return}const i=t[Ut],n=e[Ut];this.calculateJointRelativeMatrices(t.gameObject,e.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const o=exports.MODULES.RAPIER_PHYSICS.MODULE.JointData.fixed(Sc.centerConnectionPos,Sc.centerConnectionRot,this._tempPosition,this._tempQuaternion),a=this.world.createImpulseJoint(o,i,n,!0);_t&&console.log("ADD FIXED JOINT",a)}addHingeJoint(t,e,i,n){if(!this.world){console.error("Physics world not initialized");return}const o=t[Ut],a=e[Ut];this.calculateJointRelativeMatrices(t.gameObject,e.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const l=exports.MODULES.RAPIER_PHYSICS.MODULE.JointData.revolute(i,this._tempPosition,n),c=this.world.createImpulseJoint(l,o,a,!0);_t&&console.log("ADD HINGE JOINT",c)}calculateJointRelativeMatrices(t,e,i){t.updateWorldMatrix(!0,!1),e.updateWorldMatrix(!0,!1);const n=t.matrixWorld,o=e.matrixWorld;n.elements[0]=1,n.elements[5]=1,n.elements[10]=1,o.elements[0]=1,o.elements[5]=1,o.elements[10]=1,i.copy(o).premultiply(n.invert()).invert()}};let Bo=Sc;r(Bo,"_didLoadPhysicsEngine",!1),r(Bo,"_matricesBuffer",[]),r(Bo,"centerConnectionPos",{x:0,y:0,z:0}),r(Bo,"centerConnectionRot",{x:0,y:0,z:0,w:1});class HT{constructor(t,e){r(this,"world");r(this,"eventQueue");r(this,"activeCollisions",[]);r(this,"activeCollisionsStay",[]);r(this,"activeTriggers",[]);this.world=t,this.eventQueue=e}handleCollisionEvents(){this.eventQueue&&this.world&&this.eventQueue.drainCollisionEvents((t,e,i)=>{const n=this.world.getCollider(t),o=this.world.getCollider(e);if(!n||!o)return;const a=n[Zt],l=o[Zt];gp&&console.log("EVT",a.name,l.name,i,n,o),a&&l&&(i?(this.onCollisionStarted(a,n,l,o),this.onCollisionStarted(l,o,a,n)):(this.onCollisionEnded(a,l),this.onCollisionEnded(l,a)))})}update(){this.onHandleCollisionStay()}onCollisionStarted(t,e,i,n){let o=null;if(t.isTrigger||i.isTrigger)cr(t.gameObject,a=>{a.onTriggerEnter&&!a.destroyed&&a.onTriggerEnter(i),this.activeTriggers.push({collider:t,component:a,otherCollider:i})});else{const a=t.gameObject;this.world.contactPair(e,n,(l,c)=>{cr(a,d=>{var f;if(d.destroyed)return;const u=d.onCollisionEnter||d.onCollisionStay||d.onCollisionExit;if(u||gp){if(!o){const m=[],g=l.normal();i instanceof wo&&i.convex&&(g.x=-g.x,g.y=-g.y,g.z=-g.z);for(let y=0;y<l.numSolverContacts();y++){const _=l.solverContactPoint(y),b=l.contactImpulse(y);if(_){const v=l.contactDist(y),w=l.solverContactFriction(y),C=l.solverContactTangentVelocity(y),E=new Bv(_,v,g,b,w,C);m.push(E),gp&&N.DrawDirection(_,g,16711680,3,!0)}}o=new Fv(a,i,m)}if(u){const m={collider:t,component:d,collision:o};this.activeCollisions.push(m),d.onCollisionStay&&this.activeCollisionsStay.push(m),(f=d.onCollisionEnter)==null||f.call(d,o)}}})})}}onHandleCollisionStay(){for(const t of this.activeCollisionsStay){const e=t.component;if(!e.destroyed&&e.activeAndEnabled&&e.onCollisionStay){if(t.collision.collider.destroyed)continue;const i=t.collision;e.onCollisionStay(i)}}for(const t of this.activeTriggers){const e=t.component;if(!e.destroyed&&e.activeAndEnabled&&e.onTriggerStay){const i=t.otherCollider;if(i.destroyed)continue;e.onTriggerStay(i)}}}onCollisionEnded(t,e){if(!(t.destroyed||e.destroyed)){for(let i=0;i<this.activeCollisions.length;i++){const n=this.activeCollisions[i],o=n.collider;if(o.destroyed||n.collision.collider.destroyed){this.activeCollisions.splice(i,1),i--;continue}if(o===t&&n.collision.collider===e){const a=n.component;if(this.activeCollisions.splice(i,1),i--,a.activeAndEnabled&&a.onCollisionExit){const l=n.collision;a.onCollisionExit(l)}}}for(let i=0;i<this.activeCollisionsStay.length;i++){const n=this.activeCollisionsStay[i],o=n.collider;if(o.destroyed||n.collision.collider.destroyed){this.activeCollisionsStay.splice(i,1),i--;continue}if(o===t&&n.collision.collider===e){const a=n.component;if(this.activeCollisionsStay.splice(i,1),i--,a.activeAndEnabled&&a.onCollisionExit){const l=n.collision;a.onCollisionExit(l)}}}for(let i=0;i<this.activeTriggers.length;i++){const n=this.activeTriggers[i],o=n.collider;if(o.destroyed||n.otherCollider.destroyed){this.activeTriggers.splice(i,1),i--;continue}if(o===t&&n.otherCollider===e){const a=n.component;if(this.activeTriggers.splice(i,1),i--,a.activeAndEnabled&&a.onTriggerExit){const l=n.otherCollider;a.onTriggerExit(l)}}}}}}class GT{static async createComparisonScene(t){const{files:e}=t,n=await Promise.all(e.map(b=>new ee(b).loadAssetAsync())),o=new h.Scene;let a=0;for(const b of n)if(b instanceof h.Object3D){b.position.y=a,o.add(b);const v=si([b]);a+=v.getSize(new h.Vector3).y,a+=.1}const l=new h.PerspectiveCamera(20);o.add(l);const c=t.environment||"https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/studio_small_09_1k.exr";if(c){let b=null;if(c.endsWith(".hdr")){const v=(await Promise.resolve().then(()=>require("./three-examples-609de8cf.light.umd.cjs")).then(w=>w.RGBELoader$1)).RGBELoader;b=new v}else if(c.endsWith(".exr")){const v=(await Promise.resolve().then(()=>require("./three-examples-609de8cf.light.umd.cjs")).then(w=>w.EXRLoader$1)).EXRLoader;b=new v}if(b){const v=await b.loadAsync(c).catch(w=>(console.error(w),null));v&&(v.mapping=h.EquirectangularReflectionMapping,v.needsUpdate=!0,o.background=v,o.environment=v,o.backgroundBlurriness=.75)}else console.warn("Unsupported environment map format",c)}const d=si(o.children),u=d.getCenter(new h.Vector3),f=d.getSize(new h.Vector3),g=Math.max(f.x,f.y,f.z)/(2*Math.tan(Math.PI*l.fov/360));l.position.set(u.x,u.y,g),l.lookAt(u);const y=new Y.OrbitControls(l,t.domElement||document.body);y.target=u,y.update();const _=(t.domElement||document.body).getBoundingClientRect();return l.aspect=_.width/_.height,l.updateProjectionMatrix(),{scene:o,camera:l}}}let Mm=0;function Pb(s){s?Mm++:Mm--}function qT(){return Mm>0}const XT={binary:!0,animations:!0};async function QT(s){if(!s.context)throw new Error("No context provided to exportAsGLTF");s.scene||(s.scene=s.context.scene);const t={...XT,...s},{context:e}=t,i=new Y.GLTFExporter;i.register(l=>new ew(l)),i.register(l=>new SO(l)),i.register(l=>new Qv(l)),kg(i,t.context);const n={binary:t.binary,animations:KT(e,t.scene,[])},o=new YT;console.debug("Exporting GLTF",n),o.onBeforeExport(t),Pb(!0);const a=await i.parseAsync(t.scene,n).catch(l=>(console.error(l),null));if(Pb(!1),o.onAfterExport(t),!a)throw new Error("Failed to export GLTF");if(t.downloadAs!=null){let l=null;if(a instanceof ArrayBuffer?l=new Blob([a],{type:"application/octet-stream"}):console.error("Can not download GLTF as a blob",a),l){const c=URL.createObjectURL(l),d=document.createElement("a");d.href=c;let u=t.downloadAs;!u.endsWith(".glb")&&!u.endsWith(".gltf")&&(u+=t.binary?".glb":".gltf"),d.download=u,d.click()}}return a}const Ob=Symbol("needle:weight");class YT{constructor(){r(this,"_undo",[])}onBeforeExport(t){t.context.animations.mixers.forEach(e=>{const i=Da.tryGetActionsFromMixer(e);if(i)for(let n=0;n<i.length;n++){const o=i[n];o[Ob]=o.weight,o.weight=0,this._undo.push(()=>{o.weight=o[Ob]})}e.update(0)}),t.context.scene.traverse(e=>{if(!cm(e)){const i=e.parent;i&&(e.removeFromParent(),this._undo.push(()=>i.add(e)))}})}onAfterExport(t){this._undo.forEach(e=>e()),this._undo.length=0}}function KT(s,t,e){s.animations.mixers.forEach(n=>{const o=Da.tryGetActionsFromMixer(n);if(o)for(let a=0;a<o.length;a++){const c=o[a].getClip();e.push(c)}}),Array.isArray(t)||(t=[t]);for(const n of t)Da.tryGetAnimationClipsFromObjectHierarchy(n,e);const i=new Set(e);return Array.from(i)}const Mb="needle-button",_p=I();var Xo,Qo,Yo,Nt,cs,Ma,bu,cx,vu,hx,Uc;class gy extends HTMLElement{constructor(){super();Ti(this,bu);Ti(this,vu);Ti(this,Xo,void 0);Ti(this,Qo,void 0);Ti(this,Yo,void 0);Ti(this,Nt,void 0);Ti(this,cs,void 0);Ti(this,Ma,void 0);Ti(this,Uc,e=>{_p&&console.log("Needle Button clicked"),!e.defaultPrevented&&ce(this,Nt)&&ce(this,Nt).click()});this.removeEventListener("click",ce(this,Uc)),this.addEventListener("click",ce(this,Uc))}attributeChangedCallback(e,i,n){pl(this,bu,cx).call(this)}}Xo=new WeakMap,Qo=new WeakMap,Yo=new WeakMap,Nt=new WeakMap,cs=new WeakMap,Ma=new WeakMap,bu=new WeakSet,cx=function(){var i,n;if((i=ce(this,Nt))==null||i.remove(),this.getAttribute("ar")!=null)ce(this,cs)??Ji(this,cs,new vs),Ji(this,Nt,ce(this,cs).createARButton());else if(this.getAttribute("vr")!=null)ce(this,cs)??Ji(this,cs,new vs),Ji(this,Nt,ce(this,cs).createVRButton());else if(this.getAttribute("quicklook")!=null)ce(this,cs)??Ji(this,cs,new vs),Ji(this,Nt,ce(this,cs).createQuicklookButton());else{_p?console.warn("No button type specified for <needle-button>. Use either ar, vr or quicklook attribute."):console.debug("No button type specified for <needle-button>. Use either ar, vr or quicklook attribute.");return}ce(this,Xo)??Ji(this,Xo,this.attachShadow({mode:"open"})),ce(this,Qo)??Ji(this,Qo,document.createElement("slot")),ce(this,Yo)??Ji(this,Yo,document.createElement("style")),ce(this,Yo).innerHTML=`
|
|
1526
1526
|
button {
|
|
1527
1527
|
all: initial;
|
package/dist/{needle-engine.bundle-946378ce.light.js → needle-engine.bundle-17f4eeec.light.js}
RENAMED
|
@@ -1792,15 +1792,15 @@ function TC() {
|
|
|
1792
1792
|
return s || null;
|
|
1793
1793
|
}
|
|
1794
1794
|
const z0 = x("debugdefines");
|
|
1795
|
-
Ro('if(!globalThis[""4.5.0-alpha.
|
|
1795
|
+
Ro('if(!globalThis[""4.5.0-alpha.6""]) globalThis[""4.5.0-alpha.6""] = "0.0.0";');
|
|
1796
1796
|
Ro('if(!globalThis[""undefined""]) globalThis[""undefined""] = "unknown";');
|
|
1797
|
-
Ro('if(!globalThis[""Wed May 14 2025 21:
|
|
1797
|
+
Ro('if(!globalThis[""Wed May 14 2025 21:49:24 GMT+0700 (Indochina Time)""]) globalThis[""Wed May 14 2025 21:49:24 GMT+0700 (Indochina Time)""] = "unknown";');
|
|
1798
1798
|
Ro('if(!globalThis[""npk_ad8e492e31253a2800d563522e42a7311d0d7b766ac4ec1f64d3b425f06eacbd""]) globalThis[""npk_ad8e492e31253a2800d563522e42a7311d0d7b766ac4ec1f64d3b425f06eacbd""] = "unknown";');
|
|
1799
|
-
Ro('globalThis["__NEEDLE_ENGINE_VERSION__"] = "4.5.0-alpha.
|
|
1799
|
+
Ro('globalThis["__NEEDLE_ENGINE_VERSION__"] = "4.5.0-alpha.6";');
|
|
1800
1800
|
Ro('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";');
|
|
1801
|
-
Ro('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Wed May 14 2025 21:
|
|
1801
|
+
Ro('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Wed May 14 2025 21:49:24 GMT+0700 (Indochina Time)";');
|
|
1802
1802
|
Ro('globalThis["__NEEDLE_PUBLIC_KEY__"] = "npk_ad8e492e31253a2800d563522e42a7311d0d7b766ac4ec1f64d3b425f06eacbd";');
|
|
1803
|
-
const Vn = "4.5.0-alpha.
|
|
1803
|
+
const Vn = "4.5.0-alpha.6", bg = "undefined", U0 = "Wed May 14 2025 21:49:24 GMT+0700 (Indochina Time)";
|
|
1804
1804
|
z0 && console.log(`Engine version: ${Vn} (generator: ${bg})
|
|
1805
1805
|
Project built at ${U0}`);
|
|
1806
1806
|
const md = "npk_ad8e492e31253a2800d563522e42a7311d0d7b766ac4ec1f64d3b425f06eacbd", _o = "needle_isActiveInHierarchy", sa = "builtin_components", gd = "needle_editor_guid";
|
|
@@ -40842,7 +40842,7 @@ async function fx(s, t) {
|
|
|
40842
40842
|
const { callback: n } = i;
|
|
40843
40843
|
let o = n({ context: t, url: s, mimetype: e });
|
|
40844
40844
|
if (o instanceof Promise && await o, o)
|
|
40845
|
-
return console.debug(`Using custom loader (${i.name}) for
|
|
40845
|
+
return console.debug(`Using custom loader (${i.name || "unnamed"}) for ${e} at '${s}'`), o;
|
|
40846
40846
|
}
|
|
40847
40847
|
switch (e) {
|
|
40848
40848
|
default:
|